diff --git a/.cargo/config.toml b/.cargo/config.toml index 4e54d1d3b18..79a36b71742 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -10,9 +10,12 @@ rustflags = ["--cfg=getrandom_backend=\"wasm_js\""] # Enforce a 1 MB stack limit for WASI targets. # (Runaway heap growth is fixed by the smaller DataStack chunk # and the size‑optimized wasm‑release profile.) + [target.wasm32-wasip1] rustflags = [ "-C", "link-arg=-zstack-size=1048576", + "-L", "crates/host_env/vendor/wasm32-wasip1", + "-l", "wasi-emulated-signal", ] [target.wasm32-wasip2] diff --git a/.claude/scripts/setup-env.sh b/.claude/scripts/setup-env.sh index f5d28a3f14c..17bc083fc82 100755 --- a/.claude/scripts/setup-env.sh +++ b/.claude/scripts/setup-env.sh @@ -16,7 +16,7 @@ if [ "$(printf '%s\n' "3.13" "$CURRENT_PY" | sort -V | head -1)" != "3.13" ]; th echo "Upgrading python3 default to 3.13..." # Find best available Python >= 3.13 TARGET="" - for ver in python3.14 python3.13; do + for ver in python3.15 python3.14 python3.13; do if command -v "$ver" &>/dev/null; then TARGET=$(command -v "$ver") break @@ -38,13 +38,17 @@ else echo "python3 already >= 3.13: $(python3 --version)" fi -# 2. Clone CPython source if not present (needed for scripts/update_lib) -if [ ! -d "cpython" ]; then - echo "Cloning CPython v3.14.3 (shallow)..." - git clone --depth 1 --branch v3.14.3 https://github.com/python/cpython.git cpython - echo "CPython source ready." +# 2. Ensure the CPython source matches the target (needed for scripts/update_lib) +PYTHON_VERSION="v3.15.2" +if [ ! -e "cpython" ]; then + git clone --depth 1 --branch "$PYTHON_VERSION" https://github.com/python/cpython.git cpython +elif [ ! -d "cpython/.git" ] || [ ! -d "cpython/Lib" ] || + [ "$(git -C cpython rev-parse HEAD)" != "$(git -C cpython rev-parse --verify "$PYTHON_VERSION^{commit}" 2>/dev/null)" ] || + [ -n "$(git -C cpython status --porcelain)" ]; then + echo "ERROR: cpython must be a clean checkout of $PYTHON_VERSION. Move the existing directory aside and rerun." >&2 + exit 1 else - echo "CPython source already present." + echo "CPython $PYTHON_VERSION source already present." fi echo "=== Setup complete ===" diff --git a/.cspell.dict/cpython.txt b/.cspell.dict/cpython.txt index a00cd9e2584..7fc991670d2 100644 --- a/.cspell.dict/cpython.txt +++ b/.cspell.dict/cpython.txt @@ -222,6 +222,7 @@ pylifecycle pymain pymem pyrepl +pyrun pystate pystrcmp PYTHONTRACEMALLOC diff --git a/.cspell.dict/python-more.txt b/.cspell.dict/python-more.txt index 7ea660a5d1f..f2383f15f97 100644 --- a/.cspell.dict/python-more.txt +++ b/.cspell.dict/python-more.txt @@ -127,6 +127,7 @@ isabstractmethod isbytes iscased isfinal +issubnormal istext itemiterator itemsize diff --git a/.cspell.dict/rust-more.txt b/.cspell.dict/rust-more.txt index c8614f12e65..60cd912d9bf 100644 --- a/.cspell.dict/rust-more.txt +++ b/.cspell.dict/rust-more.txt @@ -83,6 +83,8 @@ trai ulonglong unic unistd +unparked +unparking unraw unsync wasip1 diff --git a/.cspell.dict/rustpython.txt b/.cspell.dict/rustpython.txt index b4170d20da4..928a32c241f 100644 --- a/.cspell.dict/rustpython.txt +++ b/.cspell.dict/rustpython.txt @@ -12,6 +12,7 @@ pyast pyattr pyclass pyclassmethod +pycode pyexception pyfunction pygetset @@ -36,6 +37,7 @@ pyperformance pytype qsbr rustix +rustpythonw struc unscanned zelf diff --git a/.cspell.json b/.cspell.json index 6bcf6abef82..9de880f1296 100644 --- a/.cspell.json +++ b/.cspell.json @@ -97,6 +97,8 @@ "implicits", "inity", "interps", + "isxidcontinue", + "isxidstart", "jitted", "jitting", "kwonly", diff --git a/.gitattributes b/.gitattributes index 44fc4c8f9b0..72ef6114d61 100644 --- a/.gitattributes +++ b/.gitattributes @@ -71,3 +71,20 @@ Lib/test/certdata/*.0 generated Lib/test/levenshtein_examples.json generated Lib/test/test_stable_abi_ctypes.py generated Lib/token.py generated + +# Preserve canonical profiling resource bytes for frozen asset hashing. +Lib/profiling/sampling/_flamegraph_assets/flamegraph.css text eol=lf +Lib/profiling/sampling/_flamegraph_assets/flamegraph.js text eol=lf +Lib/profiling/sampling/_flamegraph_assets/flamegraph_template.html text eol=lf +Lib/profiling/sampling/_heatmap_assets/heatmap.css text eol=lf +Lib/profiling/sampling/_heatmap_assets/heatmap.js text eol=lf +Lib/profiling/sampling/_heatmap_assets/heatmap_index.js text eol=lf +Lib/profiling/sampling/_heatmap_assets/heatmap_index_template.html text eol=lf +Lib/profiling/sampling/_heatmap_assets/heatmap_pyfile_template.html text eol=lf +Lib/profiling/sampling/_heatmap_assets/heatmap_shared.js text eol=lf +Lib/profiling/sampling/_shared_assets/base.css text eol=lf +Lib/profiling/sampling/_shared_assets/base.js text eol=lf +Lib/profiling/sampling/_vendor/d3/7.8.5/d3.min.js text eol=lf +Lib/profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph-tooltip.min.js text eol=lf +Lib/profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph.css text eol=lf +Lib/profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph.min.js text eol=lf diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e9e2041d482..e8517d5c49f 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -161,7 +161,8 @@ updates: cooldown: default-days: 7 - package-ecosystem: npm - directory: / + directories: + - "wasm/*" schedule: interval: weekly cooldown: diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index cd0b1349c09..0855ec30787 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -19,8 +19,8 @@ concurrency: cancel-in-progress: true env: - CARGO_ARGS: --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env,doc - CARGO_ARGS_NO_SSL: --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,host_env,doc + CARGO_ARGS: --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,ssl-rustls-aws-lc,host_env,doc,ucd_3_2_0 + CARGO_ARGS_NO_SSL: --no-default-features --features stdlib,importlib,stdio,encodings,sqlite,host_env,doc,ucd_3_2_0 CARGO_ARGS_MOST_FEATS: --features capi,encodings,jit,sqlite,threading # Crates excluded from workspace builds: # - rustpython_wasm: requires wasm target @@ -43,6 +43,7 @@ jobs: outputs: # Flag that is raised when any rust code is changed. rust_code: ${{ steps.check_rust_code.outputs.changed }} + update_lib: ${{ steps.check_update_lib.outputs.changed }} # WASM demo / notebook / example_projects, independent of rust_code. wasm_code: ${{ steps.check_wasm_code.outputs.changed }} # Cross-target cargo check is skipped unless the diff can change @@ -77,6 +78,10 @@ jobs: ':examples/**' \ ':benches/**' \ ':example_projects/**' \ + ':extra_tests/snippets/**' \ + ':extra_tests/test_snippets.py' \ + ':extra_tests/rustpython_wasi.sh' \ + ':extra_tests/requirements.txt' \ ':.github/workflows/ci.yaml' \ ; then echo "changed=false" >> "$GITHUB_OUTPUT" @@ -86,6 +91,17 @@ jobs: env: MERGE_BASE: ${{ steps.merge_base.outputs.sha }} + - name: Check if update_lib changed + id: check_update_lib + run: | + if git diff --quiet "${MERGE_BASE}...HEAD" -- ':scripts/update_lib/**' ':.python-version'; then + echo "changed=false" >> "$GITHUB_OUTPUT" + else + echo "changed=true" >> "$GITHUB_OUTPUT" + fi + env: + MERGE_BASE: ${{ steps.merge_base.outputs.sha }} + - name: Check if WASM package or demo sources changed id: check_wasm_code run: | @@ -208,6 +224,7 @@ jobs: env: RUST_BACKTRACE: full RUN_RUST_TESTS: ${{ needs.determine_changes.outputs.rust_code == 'true' || github.ref == 'refs/heads/main' }} + RUN_UPDATE_LIB_TESTS: ${{ needs.determine_changes.outputs.update_lib == 'true' }} # Named after the matrix entry rather than left to be named for it: a # generated name lists every value in the entry, so adding or removing one # renames the check and drops it from the required list. @@ -221,10 +238,10 @@ jobs: steps: - name: Skip rust tests when sources did not change if: env.RUN_RUST_TESTS != 'true' - run: echo "No rust source changes; required check is green without rebuilding." + run: echo "No rust source changes; skipping Rust build and tests." - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - if: env.RUN_RUST_TESTS == 'true' + if: env.RUN_RUST_TESTS == 'true' || (env.RUN_UPDATE_LIB_TESTS == 'true' && runner.os == 'Linux') with: persist-credentials: false @@ -295,6 +312,10 @@ jobs: working-directory: crates/capi run: cargo test --doc --locked + - name: Check host_env without ctypes + if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Windows' + run: cargo check --locked -p rustpython-host_env --no-default-features --lib + - name: check compilation without host_env (sandbox mode) if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' run: | @@ -302,6 +323,10 @@ jobs: cargo check --locked -p rustpython-stdlib --no-default-features --features compiler cargo build --locked --no-default-features --features stdlib,importlib,stdio,encodings,freeze-stdlib + - name: Test FileIO without other host modules + if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' + run: cargo test --locked -p rustpython-vm --no-default-features --features compiler,host_io --test host_io + - name: sandbox smoke test if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' run: | @@ -310,7 +335,12 @@ jobs: - name: Test openssl build if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' - run: cargo build --locked --no-default-features --features ssl-openssl + run: | + cargo build --locked --no-default-features --features ssl-openssl + cargo build --locked --release --features threading,jit,ssl-openssl ${{ env.CARGO_ARGS_NO_SSL }} + target/release/rustpython -B extra_tests/snippets/stdlib_ssl.py + target/release/rustpython -B -m test -v --single-process --timeout=300 test_ssl + timeout-minutes: 30 - name: Test vendored OpenSSL build if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' @@ -329,20 +359,32 @@ jobs: run: | cargo build --manifest-path example_projects/barebone/Cargo.toml cargo build --manifest-path example_projects/frozen_stdlib/Cargo.toml + env: + CARGO_TARGET_DIR: example_projects/target - name: Run example projects if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' run: | - example_projects/barebone/target/debug/example-barebone - example_projects/frozen_stdlib/target/debug/example_frozen_stdlib + example_projects/target/debug/example-barebone + example_projects/target/debug/example_frozen_stdlib - name: Build rustpython for update_lib tests if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' run: cargo build --locked + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + if: env.RUN_RUST_TESTS != 'true' && env.RUN_UPDATE_LIB_TESTS == 'true' && runner.os == 'Linux' + with: + python-version-file: .python-version + - name: run update_lib tests - if: env.RUN_RUST_TESTS == 'true' && runner.os == 'Linux' - run: target/debug/rustpython -m unittest discover -s scripts/update_lib/tests -v + if: (env.RUN_RUST_TESTS == 'true' || env.RUN_UPDATE_LIB_TESTS == 'true') && runner.os == 'Linux' + run: | + if [ "$RUN_RUST_TESTS" = "true" ]; then + target/debug/rustpython -m unittest discover -s scripts/update_lib/tests -v + else + python -m unittest update_lib.tests.test_patch_spec update_lib.tests.test_migrate -v + fi env: PYTHONPATH: scripts @@ -388,9 +430,7 @@ jobs: dependencies: gcc-mingw-w64-x86-64: true - os: macos-latest - target: aarch64-apple-ios - - os: macos-latest - target: x86_64-apple-darwin + target: aarch64-apple-ios x86_64-apple-darwin fail-fast: false steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -459,11 +499,19 @@ jobs: # args: --ignore-rust-version - name: Check compilation with threading - run: cargo check --locked --target "${{ matrix.target }}" ${{ env.CARGO_ARGS_NO_SSL }} --features threading + run: | + read -ra targets <<< "$TARGETS" + cargo check --locked "${targets[@]/#/--target=}" ${{ env.CARGO_ARGS_NO_SSL }} --features threading + env: + TARGETS: ${{ matrix.target }} - name: Check compilation with ssl if: ${{ !matrix.skip_ssl }} - run: cargo check --locked --target "${{ matrix.target }}" ${{ env.CARGO_ARGS }} + run: | + read -ra targets <<< "$TARGETS" + cargo check --locked "${targets[@]/#/--target=}" ${{ env.CARGO_ARGS }} + env: + TARGETS: ${{ matrix.target }} snippets_cpython: if: ${{ !contains(github.event.pull_request.labels.*.name, 'skip:ci') }} @@ -498,6 +546,9 @@ jobs: - '-u all' - '--timeout 600' - '--dont-add-python-opts' + # CPython's installed py.exe reports its own version, not RustPython's. + # Keep the remaining launcher integration tests and runtime version checks. + - '--ignore test.test_launcher.TestLauncher.test_version' env_polluting_tests: [] skips: [] timeout: 50 @@ -535,7 +586,7 @@ jobs: # Windows runners randomly crashes, https://github.com/actions/cache/issues/1754 continue-on-error: true - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - name: Install macOS dependencies uses: ./.github/actions/install-macos-deps @@ -559,6 +610,7 @@ jobs: - name: Run CPython tests run: | + # shellcheck disable=SC2086 target/release/rustpython -u -m test --slow-ci -j "$CORES" $EXTRA_TEST_ARGS $SKIPS timeout-minutes: ${{ matrix.timeout }} shell: bash @@ -630,7 +682,7 @@ jobs: - name: Check whats_left is not broken shell: bash - run: python -I scripts/whats_left.py --rustpython target/release/rustpython + run: python -I scripts/whats_left.py --signature --rustpython target/release/rustpython clippy: # Named after the matrix entry rather than left to be named for it: a @@ -725,7 +777,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable - - uses: taiki-e/install-action@94c31af3204a9f15ab40b35ad084410b905bbc73 # v2.87.17 + - uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 with: tool: cargo-shear fallback: none @@ -747,17 +799,17 @@ jobs: with: persist-credentials: false - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - name: actionlint - uses: reviewdog/action-actionlint@320fcdd9c860767cf17fab3b20e22e739d5d02b8 # v1.76.0 + uses: reviewdog/action-actionlint@ae857e78c1b42b3d0a49637181b09d3d56d402b4 # v1.84.1 - name: zizmor - uses: zizmorcore/zizmor-action@cc914d7f3750a2d13d75c7f184a1060aa0e9d482 # v0.6.4 + uses: zizmorcore/zizmor-action@45d7276c9ca790aabd705e31ca99c6185c3e76dd # v0.8.1 - name: restore prek cache uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -767,7 +819,7 @@ jobs: - name: install prek id: prek - uses: j178/prek-action@4e14d07f9231acabce116ccfca13b13dd9755ece # v3.0.0 + uses: j178/prek-action@44924fe9ef4a6f88253c4b6b1bf11c689d3ce53d # v3.1.0 with: cache: false show-verbose-logs: false @@ -776,18 +828,12 @@ jobs: - name: prek run run: prek run --show-diff-on-failure --color=always --all-files - - name: Get target CPython version - id: cpython-version - run: | - version=$(cat .python-version) - echo "version=${version}" >> "$GITHUB_OUTPUT" - - - name: Clone CPython + - name: Clone CPython opcode metadata source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: python/cpython path: cpython - ref: "v${{ steps.cpython-version.outputs.version }}" + ref: "v3.15.0" persist-credentials: false - name: prek run (manual stage) @@ -808,7 +854,7 @@ jobs: - name: reviewdog if: ${{ !cancelled() }} - uses: reviewdog/action-suggester@c387862ad6765a9729f2b40ee4d8b5769f2145c7 # v1.26.1 + uses: reviewdog/action-suggester@fd22a83b1ebc13fd8aee5d57b06793fce6f20fb9 # v1.27.1 with: level: warning fail_level: error @@ -906,19 +952,19 @@ jobs: run: cargo --locked clippy --keep-going --manifest-path=crates/wasm/Cargo.toml -- -Dwarnings - name: install wasm-pack - run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + run: curl https://wasm-bindgen.github.io/wasm-pack/installer/init.sh -sSf | sh - name: install geckodriver run: | wget https://github.com/mozilla/geckodriver/releases/download/v0.36.0/geckodriver-v0.36.0-linux64.tar.gz mkdir geckodriver tar -xzf geckodriver-v0.36.0-linux64.tar.gz -C geckodriver - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - run: python -m pip install -r requirements.txt working-directory: ./wasm/tests - - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: package-manager-cache: false @@ -947,24 +993,33 @@ jobs: NODE_OPTIONS: "--openssl-legacy-provider" working-directory: ./wasm/demo - - uses: mwilliamson/setup-wabt-action@427f2fdd70bc4dbc2e53c2eb4f19f66162d71bd2 # v4.0.0 - with: - wabt-version: "1.0.36" - - name: Build wasm32-unknown without js working-directory: example_projects/wasm32_without_js/rustpython-without-js run: cargo build - name: Build wasm-runtime - run: cargo build --release --manifest-path example_projects/wasm32_without_js/wasm-runtime/Cargo.toml + run: cargo build --locked --release --manifest-path example_projects/wasm32_without_js/wasm-runtime/Cargo.toml - name: Check wasm32-unknown without js working-directory: example_projects/wasm32_without_js run: | - if wasm-objdump -xj Import rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm; then - echo "ERROR: wasm32-unknown module expects imports from the host environment" >&2 - fi - wasm-runtime/target/release/wasm-runtime rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm + python3 test_runtime.py -v \ + --runtime wasm-runtime/target/release/wasm-runtime \ + --module rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm + + - name: Test WASI host runner + run: cargo test --locked --release --manifest-path example_projects/wasm32_without_js/wasm-runtime/Cargo.toml + + - name: Build wasm32-unknown with host-io + working-directory: example_projects/wasm32_without_js/rustpython-without-js + run: cargo build --features host-io + + - name: Check WASI FileIO contract + working-directory: example_projects/wasm32_without_js + run: | + python3 test_wasi_fs.py -v \ + --runtime wasm-runtime/target/release/wasm-runtime \ + --module rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm - name: build notebook demo if: github.ref == 'refs/heads/release' @@ -1005,11 +1060,59 @@ jobs: env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true RUN_WASM_WASI: ${{ needs.determine_changes.outputs.rust_code == 'true' || github.ref == 'refs/heads/main' }} - # Passing snippets under wasm32-wasip1. - WASM_WASI_SNIPPETS: >- - stdlib_random - stdlib_time - # Passing Lib/test files under wasm32-wasip1 + # extra_tests/snippets files that still fail or hang under wasm32-wasip1; + # every other snippet is discovered and run automatically. + WASM_WASI_SNIPPET_EXCLUDE: >- + builtin_bytearray + builtin_memoryview + builtin_posixshmem + builtin_thread + cli_int_max_str_digits + protocol_index_argument + recursion + stdlib_ast + stdlib_asyncio + stdlib_contextvars + stdlib_ctypes + stdlib_ctypes_byvalue + stdlib_ctypes_calls + stdlib_ctypes_from_buffer + stdlib_genericalias + stdlib_io + stdlib_io_blocking_buffer + stdlib_mmap + stdlib_multiprocessing_condition + stdlib_multiprocessing_fork_sharer + stdlib_multiprocessing_sharedctypes + stdlib_os + stdlib_pwd + stdlib_queue_signal + stdlib_select + stdlib_socket + stdlib_sqlite + stdlib_ssl + stdlib_ssl_short_recv + stdlib_subinterpreters + stdlib_subprocess + stdlib_sys + stdlib_sys_audit + stdlib_threading_current_frames + stdlib_threading_gc_frame_race + stdlib_threading_gc_import + stdlib_threading_generator + stdlib_threading_set_repr + stdlib_threading_type_cache + stdlib_thread_native_id + stdlib_typing + stdlib_urllib_https_misaligned_recv + stdlib_zoneinfo_cache + syntax_async + syntax_async_comprehension + syntax_deep_nesting + vm_frame_locals + xfail_assert + # Passing Lib/test suites under wasm32-wasip1 with the default resource + # policy. CPU-heavy, network and other opt-in resources stay disabled. WASM_WASI_TEST_FILES: >- test_int test_dict @@ -1023,10 +1126,76 @@ jobs: test_genericpath test_grammar test_fstring + test_array + test_bool + test_bytes + test_codecs + test_complex + test_enumerate + test_float + test_list + test_long + test_memoryview + test_range + test_set + test_slice + test_tuple + test_bisect + test_heapq + test_operator + test_functools + test_str + test_abc + test_base64 + test_binascii + test_colorsys + test_copyreg + test_difflib + test_errno + test_fnmatch + test_fractions + test_html + test_ipaddress + test_keyword + test_numeric_tower + test_pprint + test_quopri + test_textwrap + test_urlparse + test_hmac + test_random + test_stringprep + test_weakref + test_reprlib + test_contains + test_unary + test_augassign + test_keywordonlyarg + test_positional_only_arg + test_scope + test_super + test_property + test_iter + test_iterlen + test_listcomps + test_dictcomps + test_setcomps + test_genexps + test_types + test_typechecks + test_richcmp + test_int_literal + test_unpack + test_unpack_ex + test_ntpath + test_calendar + test_math + test_hashlib + test_unicodedata steps: - name: Skip wasm-wasi when rust sources did not change if: env.RUN_WASM_WASI != 'true' - run: echo "No rust source changes; required check is green without rebuilding." + run: echo "No rust source changes; skipping Rust build and tests." - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 if: env.RUN_WASM_WASI == 'true' @@ -1067,21 +1236,38 @@ jobs: - name: build rustpython if: env.RUN_WASM_WASI == 'true' - run: cargo build --locked --profile wasm-release --target wasm32-wasip1 --no-default-features --features freeze-stdlib,stdlib,stdio,importlib,host_env,doc --verbose - - name: run snippets + run: cargo build --locked --profile wasm-release --target wasm32-wasip1 --no-default-features --features freeze-stdlib,stdlib,stdio,importlib,host_env,doc,ucd_3_2_0 --verbose + - name: Check WASI FileIO contract if: env.RUN_WASM_WASI == 'true' run: | - for name in $WASM_WASI_SNIPPETS; do - echo "::group::extra_tests/snippets/${name}.py" - wasmer run --volume "$(pwd)" target/wasm32-wasip1/wasm-release/rustpython.wasm -- "$(pwd)/extra_tests/snippets/${name}.py" - echo "::endgroup::" - done + python3 example_projects/wasm32_without_js/test_wasi_fs.py -v \ + --wasmer "$(command -v wasmer)" \ + --wasi-module target/wasm32-wasip1/wasm-release/rustpython.wasm + - name: Setup Python for the snippet harness + if: env.RUN_WASM_WASI == 'true' + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version-file: .python-version + + - name: Install snippet harness dependencies + if: env.RUN_WASM_WASI == 'true' + run: python -m pip install -r extra_tests/requirements.txt + + - name: run snippets + if: env.RUN_WASM_WASI == 'true' + working-directory: extra_tests + env: + RUSTPYTHON: ${{ github.workspace }}/extra_tests/rustpython_wasi.sh + RUSTPYTHON_SNIPPET_EXCLUDE: ${{ env.WASM_WASI_SNIPPET_EXCLUDE }} + run: pytest -v test_snippets.py -k test_rustpython_ - name: run cpython unittest if: env.RUN_WASM_WASI == 'true' run: | for name in $WASM_WASI_TEST_FILES; do echo "::group::Lib/test/${name}.py" - wasmer run --volume "$(pwd)" target/wasm32-wasip1/wasm-release/rustpython.wasm -- "$(pwd)/Lib/test/${name}.py" + # Load the checkout's sources, including filenames and source lines + # used by traceback tests, rather than the frozen test modules. + extra_tests/rustpython_wasi.sh -X frozen_modules=off -m test -u none "$name" echo "::endgroup::" done @@ -1119,4 +1305,4 @@ jobs: ${{ runner.os }}-stable-- - name: cargo doc - run: cargo doc --locked + run: cargo doc --locked --no-deps diff --git a/.github/workflows/codspeed.yaml b/.github/workflows/codspeed.yaml index c7fc88352c1..7459dea3537 100644 --- a/.github/workflows/codspeed.yaml +++ b/.github/workflows/codspeed.yaml @@ -49,7 +49,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable # The benchmarks are linked against libpython through the pyo3 dev-dependency. - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - name: Restore the machine main last measured on # A recording that cannot be fetched is read as "none yet", which the step @@ -85,7 +85,7 @@ jobs: - name: Install cargo-codspeed if: ${{ steps.environment.outputs.match != 'false' }} - run: cargo install cargo-codspeed --locked --version ^5 + run: cargo install cargo-codspeed --locked --version ^6 - name: Build the benchmark targets if: ${{ steps.environment.outputs.match != 'false' }} @@ -101,7 +101,7 @@ jobs: - name: Run the benchmarks if: ${{ steps.environment.outputs.match != 'false' }} - uses: CodSpeedHQ/action@373d6868929f444bc08d901fd0eb0ad52a8875ea # v5.2.1 + uses: CodSpeedHQ/action@af75f77f17a054769abefaa42fe8dc2975469b5f # v5.6.3 with: mode: simulation run: cargo codspeed run -p rustpython -p rustpython-sre_engine diff --git a/.github/workflows/cron-ci.yaml b/.github/workflows/cron-ci.yaml index 16c74bdc43a..b0b74828900 100644 --- a/.github/workflows/cron-ci.yaml +++ b/.github/workflows/cron-ci.yaml @@ -14,7 +14,7 @@ on: - .github/workflows/cron-ci.yaml env: - CARGO_ARGS: --no-default-features --features stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc + CARGO_ARGS: --no-default-features --features stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc,ucd_3_2_0 jobs: # codecov collects code coverage data from the rust tests, python snippets and python test suite. @@ -33,23 +33,25 @@ jobs: - uses: dtolnay/rust-toolchain@stable - - uses: taiki-e/install-action@94c31af3204a9f15ab40b35ad084410b905bbc73 # v2.87.17 + - uses: taiki-e/install-action@cfdb7ed4ccc7c7dce37759eae89dc5674b469b39 # v2.90.3 with: tool: cargo-llvm-cov - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - run: sudo apt-get update && sudo apt-get -y install lcov - name: Run cargo-llvm-cov with Rust tests. - run: cargo llvm-cov --no-report --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher --exclude rustpython-capi --verbose --no-default-features --features stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc + run: cargo llvm-cov --no-report --workspace --exclude rustpython_wasm --exclude rustpython-venvlauncher --exclude rustpython-capi --verbose --no-default-features --features stdlib,importlib,stdio,encodings,ssl-rustls-aws-lc,jit,host_env,doc,ucd_3_2_0 - name: Run cargo-llvm-cov with Python snippets. run: python scripts/cargo-llvm-cov.py continue-on-error: true - name: Run cargo-llvm-cov with Python test suite. - run: cargo llvm-cov --no-report run -- -m test -u all --slowest --fail-env-changed + id: python-suite + # One worker at a time, with a fresh process for each test module. + run: cargo llvm-cov --no-report run -- -m test -j 1 -u all --slowest --fail-env-changed continue-on-error: true - name: Prepare code coverage data @@ -57,10 +59,14 @@ jobs: - name: Upload to Codecov if: ${{ github.event_name != 'pull_request' }} - uses: codecov/codecov-action@fb8b3582c8e4def4969c97caa2f19720cb33a72f # v7.0.0 + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: files: ./codecov.lcov + - name: Report Python test suite failure + if: ${{ !cancelled() && steps.python-suite.outcome == 'failure' }} + run: exit 1 + testdata: name: Collect regression test data runs-on: ubuntu-latest @@ -78,8 +84,6 @@ jobs: - name: collect tests data run: target/release/rustpython extra_tests/jsontests.py - env: - RUSTPYTHONPATH: ${{ github.workspace }}/Lib - name: upload tests data to the website if: ${{ github.event_name != 'pull_request' }} @@ -110,7 +114,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - name: build rustpython run: cargo build --release --verbose --features sqlite @@ -170,7 +174,7 @@ jobs: - uses: dtolnay/rust-toolchain@stable - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - run: cargo install cargo-criterion diff --git a/.github/workflows/lib-deps-check.yaml b/.github/workflows/lib-deps-check.yaml index 6f147542ee6..69ea0980e01 100644 --- a/.github/workflows/lib-deps-check.yaml +++ b/.github/workflows/lib-deps-check.yaml @@ -8,6 +8,10 @@ on: permissions: {} +env: + # Keep aligned with the upgrade-pylib and update-libs-status source baseline. + PYTHON_VERSION: "3.15.2" + concurrency: group: ${{ github.workflow }}-${{ github.ref_name }}-${{ github.event.pull_request.number }} cancel-in-progress: true @@ -40,18 +44,12 @@ jobs: # Checkout only Lib/ directory from PR head for accurate comparison git checkout "$PR_HEAD_SHA" -- Lib/ - - name: Get target CPython version - id: cpython-version - run: | - version=$(cat .python-version) - echo "version=${version}" >> "$GITHUB_OUTPUT" - - name: Checkout CPython uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: python/cpython path: cpython - ref: "v${{ steps.cpython-version.outputs.version }}" + ref: "v${{ env.PYTHON_VERSION }}" fetch-depth: 1 persist-credentials: false @@ -107,7 +105,7 @@ jobs: - name: Setup Python if: steps.changed-files.outputs.modules != '' - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - name: Run deps check if: steps.changed-files.outputs.modules != '' @@ -116,6 +114,17 @@ jobs: # Run deps for all modules at once echo "deps_output<> "$GITHUB_OUTPUT" output=$(python scripts/update_lib deps "${MODULES}" --depth 2 2>&1 || true) + output=$(python -c ' + import sys + + output = sys.stdin.read() + limit = 60000 + encoded = output.encode() + if len(encoded) > limit: + output = encoded[:limit].decode("utf-8", errors="ignore") + output += "\n\n[Dependency report truncated to fit in a GitHub comment.]" + print(output, end="") + ' <<< "$output") echo "$output" >> "$GITHUB_OUTPUT" echo "EOF" >> "$GITHUB_OUTPUT" env: diff --git a/.github/workflows/oscca-pr.yml b/.github/workflows/oscca-pr.yml deleted file mode 100644 index 38b67625ce0..00000000000 --- a/.github/workflows/oscca-pr.yml +++ /dev/null @@ -1,70 +0,0 @@ -name: Manage OSCCA pull requests - -on: - pull_request_target: - types: [opened] - -permissions: {} - -jobs: - label-and-assign: - name: Label and assign OSCCA pull request - runs-on: ubuntu-slim - timeout-minutes: 5 - permissions: - pull-requests: write - steps: - - name: Label and assign pull request - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - with: - script: | - const osccaUsers = new Set( - [ - "2jiyong", - "chestnut1717", - "devyubin", - "fregataa", - "hyoinandout", - "HyoJongPark", - "JaceJung-dev", - "jinmay", - "jiwahn", - "kangdora", - "kim-jaedeok", - "kyokuping", - "leehanjeong", - "lms0806", - "lsahn-gh", - "moreal", - "name-of-okja", - "rlaisqls", - "seungje0612", - "shAn-kor", - "sigmaith", - "teddygood", - "widehyo1", - "YangSiJun528", - "zzarbttoo", - ].map((login) => login.toLowerCase()), - ); - const pullRequest = context.payload.pull_request; - const author = pullRequest.user.login; - - if (!osccaUsers.has(author.toLowerCase())) { - core.info(`${author} is not an OSCCA participant; skipping.`); - return; - } - - const issue = { - ...context.repo, - issue_number: pullRequest.number, - }; - - await github.rest.issues.addLabels({ - ...issue, - labels: ["z-ca-2026"], - }); - await github.rest.issues.addAssignees({ - ...issue, - assignees: [author], - }); diff --git a/.github/workflows/pyperformance-comment.yaml b/.github/workflows/pyperformance-comment.yaml index 565d933e967..53d76d012ba 100644 --- a/.github/workflows/pyperformance-comment.yaml +++ b/.github/workflows/pyperformance-comment.yaml @@ -21,7 +21,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Download the comparison produced by the pyperformance workflow - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: name: pyperformance-diff run-id: ${{ github.event.workflow_run.id }} diff --git a/.github/workflows/pyperformance.yaml b/.github/workflows/pyperformance.yaml index 1d304582ce2..b59ce256697 100644 --- a/.github/workflows/pyperformance.yaml +++ b/.github/workflows/pyperformance.yaml @@ -60,10 +60,10 @@ jobs: # Both the third interpreter under test and the host pyperformance # itself runs on (it only runs under a real CPython; RustPython is just # the `--python` target it drives). - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 id: cpython with: - python-version: "3.14" + python-version: "3.15.0" - name: Restore cache uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 @@ -172,7 +172,7 @@ jobs: # repo's context. This artifact is the hand-off. - name: Upload the comparison if: always() - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: pyperformance-diff path: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9291f9f3754..da549859631 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -86,7 +86,7 @@ jobs: if: runner.os == 'Windows' - name: Upload Binary Artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: rustpython-release-${{ runner.os }}-${{ matrix.target }} path: target/rustpython-release-${{ runner.os }}-${{ matrix.target }}* @@ -113,7 +113,7 @@ jobs: run: cp target/wasm32-wasip1/release/rustpython.wasm target/rustpython-release-wasm32-wasip1.wasm - name: Upload Binary Artifacts - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: rustpython-release-wasm32-wasip1 path: target/rustpython-release-wasm32-wasip1.wasm @@ -121,7 +121,7 @@ jobs: - name: install wasm-pack run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh - - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 with: package-manager-cache: false @@ -168,7 +168,7 @@ jobs: persist-credentials: false - name: Download Binary Artifacts - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: path: bin pattern: rustpython-* diff --git a/.github/workflows/update-doc-db.yml b/.github/workflows/update-doc-db.yml index 8874c3aeac8..b2c6b78f541 100644 --- a/.github/workflows/update-doc-db.yml +++ b/.github/workflows/update-doc-db.yml @@ -8,11 +8,15 @@ on: python-version: description: Target python version to generate doc db for type: string - default: "3.14.7" + default: "3.15.0" base-ref: description: Base branch to create the update branch from type: string default: "main" + artifact-only: + description: Generate artifacts from main without pushing or creating a PR + type: boolean + default: false defaults: run: @@ -30,20 +34,31 @@ jobs: - windows-latest - macos-latest steps: + - name: Validate artifact-only source + if: ${{ inputs.artifact-only }} + env: + BASE_REF: ${{ inputs.base-ref }} + run: | + if [ "$GITHUB_REF" != "refs/heads/main" ] || [ "$BASE_REF" != "main" ]; then + echo 'Artifact-only generation requires the main workflow ref and main base.' >&2 + exit 1 + fi + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + ref: ${{ github.sha }} sparse-checkout: | crates/doc - - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 with: python-version: ${{ inputs.python-version }} - name: Generate docs run: python crates/doc/generate.py - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: doc-db-${{ inputs.python-version }}-${{ matrix.os }} path: "crates/doc/generated/*.json" @@ -54,22 +69,22 @@ jobs: merge: runs-on: ubuntu-latest needs: generate + outputs: + base-sha: ${{ steps.base.outputs.sha }} permissions: - contents: write - pull-requests: write + contents: read steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - persist-credentials: true - ref: ${{ inputs.base-ref }} + persist-credentials: false + ref: ${{ inputs.artifact-only && github.sha || inputs.base-ref }} - - name: Create update branch - run: git switch -c "update-doc-${PYTHON_VERSION}" - env: - PYTHON_VERSION: ${{ inputs.python-version }} + - name: Record merge base + id: base + run: echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" - name: Download generated doc DBs - uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: pattern: "doc-db-${{ inputs.python-version }}-**" path: crates/doc/generated/ @@ -99,7 +114,7 @@ jobs: echo '];' } > "$OUTPUT_FILE" - - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: name: doc-db-${{ inputs.python-version }} path: "crates/doc/src/data.inc.rs" @@ -107,6 +122,30 @@ jobs: retention-days: 7 overwrite: true + publish: + if: ${{ !inputs.artifact-only }} + runs-on: ubuntu-latest + needs: merge + permissions: + contents: write + pull-requests: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: true + ref: ${{ needs.merge.outputs.base-sha }} + + - name: Create update branch + run: git switch -c "update-doc-${PYTHON_VERSION}" + env: + PYTHON_VERSION: ${{ inputs.python-version }} + + - name: Download merged doc DB + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: doc-db-${{ inputs.python-version }} + path: crates/doc/src/ + - name: Commit, push and create PR env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/update-libs-status.yaml b/.github/workflows/update-libs-status.yaml index c1c656d2068..db5f614a62a 100644 --- a/.github/workflows/update-libs-status.yaml +++ b/.github/workflows/update-libs-status.yaml @@ -6,6 +6,7 @@ on: - main paths: - "Lib/**" + - ".github/workflows/update-libs-status.yaml" workflow_dispatch: permissions: @@ -13,7 +14,9 @@ permissions: issues: write env: - ISSUE_ID: "6839" + ISSUE_ID: "9852" + # Library source baseline, independent of the CI interpreter in .python-version. + PYTHON_VERSION: "3.15.2" jobs: update-issue: @@ -28,20 +31,13 @@ jobs: sparse-checkout: |- Lib scripts/update_lib - .python-version - - - name: Get target CPython version - id: cpython-version - run: | - version=$(cat rustpython/.python-version) - echo "version=${version}" >> "$GITHUB_OUTPUT" - name: Clone CPython uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: python/cpython path: cpython - ref: "v${{ steps.cpython-version.outputs.version }}" + ref: "v${{ env.PYTHON_VERSION }}" persist-credentials: false sparse-checkout: | Lib @@ -62,14 +58,15 @@ jobs: ## Summary - Check \`scripts/update_lib\` for tools. As a note, the current latest Python version is \`${{ steps.cpython-version.outputs.version }}\`. + Check \`scripts/update_lib\` for tools. As a note, the current latest Python version is \`${{ env.PYTHON_VERSION }}\`. Previous versions' issues as reference + - 3.14: #6839 - 3.13: #5529 + + + + + + +
+ +
+
+ + Tachyon + + {{SUBTITLE}} +
+
+ + +
+
+ + + + + + + + +
+
+ + +
+ + + + +
+
+
+
+ + +
+ + Tachyon Profiler + + + Python Sampling Profiler + + + + + +
+
+ + + + diff --git a/Lib/profiling/sampling/_format_utils.py b/Lib/profiling/sampling/_format_utils.py new file mode 100644 index 00000000000..237a4f4186b --- /dev/null +++ b/Lib/profiling/sampling/_format_utils.py @@ -0,0 +1,5 @@ +import locale + + +def fmt(value: int | float, decimals: int = 1) -> str: + return locale.format_string(f'%.{decimals}f', value, grouping=True) diff --git a/Lib/profiling/sampling/_heatmap_assets/heatmap.css b/Lib/profiling/sampling/_heatmap_assets/heatmap.css new file mode 100644 index 00000000000..8f7f034ba7e --- /dev/null +++ b/Lib/profiling/sampling/_heatmap_assets/heatmap.css @@ -0,0 +1,1555 @@ +/* ========================================================================== + Heatmap Viewer - Component-Specific CSS + + DEPENDENCY: Requires _shared_assets/base.css to be loaded first + This file extends the shared foundation with heatmap-specific styles. + ========================================================================== */ + +/* Heatmap heat colors - using base.css colors with 60% opacity */ +[data-theme="dark"] { + --heat-1: rgba(90, 123, 167, 0.60); + --heat-2: rgba(106, 148, 168, 0.60); + --heat-3: rgba(122, 172, 172, 0.60); + --heat-4: rgba(142, 196, 152, 0.60); + --heat-5: rgba(168, 216, 136, 0.60); + --heat-6: rgba(200, 222, 122, 0.60); + --heat-7: rgba(244, 212, 93, 0.60); + --heat-8: rgba(255, 122, 69, 0.60); +} + +/* -------------------------------------------------------------------------- + Layout Overrides (Heatmap-specific) + -------------------------------------------------------------------------- */ + +.app-layout { + min-height: 100vh; +} + +/* Sticky top bar for heatmap views */ +.top-bar { + position: sticky; + top: 0; + z-index: 100; +} + +/* -------------------------------------------------------------------------- + Main Content Area + -------------------------------------------------------------------------- */ + +.main-content { + flex: 1; + padding: 24px 3%; + width: 100%; + max-width: 100%; +} + +/* -------------------------------------------------------------------------- + Stats Summary Cards - Enhanced with Icons & Animations + -------------------------------------------------------------------------- */ + +.stats-summary { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; + margin-bottom: 24px; +} + +.stat-card { + display: flex; + align-items: center; + gap: 12px; + background: var(--bg-primary); + border: 2px solid var(--border); + border-radius: 10px; + padding: 14px 16px; + transition: all var(--transition-fast); + animation: slideUp 0.5s ease-out backwards; + animation-delay: calc(var(--i, 0) * 0.08s); + position: relative; + overflow: hidden; +} + +.stat-card:nth-child(1) { --i: 0; --card-color: var(--card-blue); } +.stat-card:nth-child(2) { --i: 1; --card-color: var(--card-green); } +.stat-card:nth-child(3) { --i: 2; --card-color: var(--card-yellow); } +.stat-card:nth-child(4) { --i: 3; --card-color: var(--card-purple); } + +.stat-card:hover { + border-color: rgba(var(--card-color), 0.6); + background: linear-gradient(135deg, rgba(var(--card-color), 0.08) 0%, var(--bg-primary) 100%); + transform: translateY(-2px); + box-shadow: 0 4px 16px rgba(var(--card-color), 0.15); +} + +.stat-icon { + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + font-size: 18px; + background: linear-gradient(135deg, rgba(var(--card-color), 0.15) 0%, rgba(var(--card-color), 0.05) 100%); + border: 1px solid rgba(var(--card-color), 0.2); + border-radius: 10px; + flex-shrink: 0; + transition: all var(--transition-fast); +} + +.stat-card:hover .stat-icon { + transform: scale(1.05) rotate(-2deg); + background: linear-gradient(135deg, rgba(var(--card-color), 0.25) 0%, rgba(var(--card-color), 0.1) 100%); +} + +.stat-data { + flex: 1; + min-width: 0; +} + +.stat-value { + font-family: var(--font-mono); + font-size: 1.35em; + font-weight: 800; + color: rgb(var(--card-color)); + display: block; + line-height: 1.1; + letter-spacing: -0.3px; +} + +.stat-label { + font-size: 10px; + font-weight: 600; + color: var(--text-muted); + text-transform: uppercase; + letter-spacing: 0.3px; + margin-top: 2px; +} + +/* Sparkline decoration for stats */ +.stat-sparkline { + position: absolute; + bottom: 0; + left: 0; + right: 0; + height: 30px; + opacity: 0.1; + background: linear-gradient(180deg, + transparent 0%, + rgba(var(--card-color), 0.3) 100% + ); + pointer-events: none; +} + +/* -------------------------------------------------------------------------- + Rate Cards (Error Rate, Missed Samples) with Progress Bars + -------------------------------------------------------------------------- */ + +.rate-card { + display: flex; + flex-direction: column; + gap: 12px; + background: var(--bg-primary); + border: 2px solid var(--border); + border-radius: 12px; + padding: 18px 20px; + transition: all var(--transition-fast); + animation: slideUp 0.5s ease-out backwards; + position: relative; + overflow: hidden; +} + +.rate-card:nth-child(5) { animation-delay: 0.32s; --rate-color: var(--card-red); } +.rate-card:nth-child(6) { animation-delay: 0.40s; --rate-color: var(--card-orange); } + +.rate-card:hover { + border-color: rgba(var(--rate-color), 0.5); + transform: translateY(-2px); + box-shadow: 0 6px 20px rgba(var(--rate-color), 0.15); +} + +.rate-header { + display: flex; + justify-content: space-between; + align-items: center; +} + +.rate-info { + display: flex; + align-items: center; + gap: 10px; +} + +.rate-icon { + width: 36px; + height: 36px; + display: flex; + align-items: center; + justify-content: center; + font-size: 18px; + background: linear-gradient(135deg, rgba(var(--rate-color), 0.15) 0%, rgba(var(--rate-color), 0.05) 100%); + border: 1px solid rgba(var(--rate-color), 0.2); + border-radius: 10px; + flex-shrink: 0; +} + +.rate-label { + font-size: 12px; + font-weight: 600; + color: var(--text-secondary); + text-transform: uppercase; + letter-spacing: 0.3px; +} + +.rate-value { + font-family: var(--font-mono); + font-size: 1.4em; + font-weight: 800; + color: rgb(var(--rate-color)); +} + +.rate-bar { + height: 8px; + background: var(--bg-tertiary); + border-radius: 4px; + overflow: hidden; + position: relative; +} + +.rate-fill { + height: 100%; + border-radius: 4px; + transition: width 0.8s ease-out; + position: relative; + overflow: hidden; +} + +.rate-fill.error { + background: linear-gradient(90deg, #dc3545 0%, #ff6b6b 100%); +} + +.rate-fill.warning { + background: linear-gradient(90deg, #ff9800 0%, #ffc107 100%); +} + +.rate-fill.good { + background: linear-gradient(90deg, #28a745 0%, #20c997 100%); +} + +/* Shimmer animation on rate bars */ +.rate-fill::after { + content: ''; + position: absolute; + top: 0; + left: -100%; + width: 100%; + height: 100%; + background: linear-gradient( + 90deg, + transparent 0%, + rgba(255, 255, 255, 0.4) 50%, + transparent 100% + ); + animation: shimmer 2.5s ease-in-out infinite; +} + +/* -------------------------------------------------------------------------- + Section Headers + -------------------------------------------------------------------------- */ + +.section-header { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 16px; + padding-bottom: 12px; + border-bottom: 2px solid var(--python-gold); +} + +.section-title { + font-size: 18px; + font-weight: 700; + color: var(--text-primary); + margin: 0; + flex: 1; +} + +/* -------------------------------------------------------------------------- + Filter Controls + -------------------------------------------------------------------------- */ + +.filter-controls { + display: flex; + gap: 8px; + flex-wrap: wrap; + align-items: center; + margin-bottom: 16px; +} + +.control-btn { + padding: 8px 16px; + background: var(--bg-secondary); + color: var(--text-primary); + border: 1px solid var(--border); + border-radius: 6px; + font-size: 13px; + font-weight: 500; + cursor: pointer; + transition: all var(--transition-fast); +} + +.control-btn:hover { + background: var(--accent); + color: white; + border-color: var(--accent); +} + +/* -------------------------------------------------------------------------- + Type Sections (stdlib, project, etc) + -------------------------------------------------------------------------- */ + +.type-section { + background: var(--bg-primary); + border: 1px solid var(--border); + border-radius: 8px; + overflow: hidden; + margin-bottom: 12px; +} + +.type-header { + padding: 12px 16px; + background: var(--header-gradient); + color: white; + cursor: pointer; + display: flex; + align-items: center; + gap: 10px; + user-select: none; + transition: all var(--transition-fast); + font-weight: 600; +} + +.type-header:hover { + opacity: 0.95; +} + +.type-icon { + font-size: 12px; + transition: transform var(--transition-fast); + min-width: 12px; +} + +.type-title { + font-size: 14px; + flex: 1; +} + +.type-stats { + font-size: 12px; + opacity: 0.9; + background: rgba(255, 255, 255, 0.15); + padding: 4px 10px; + border-radius: 4px; + font-family: var(--font-mono); +} + +.type-content { + padding: 12px; +} + +/* -------------------------------------------------------------------------- + Folder Nodes (hierarchical structure) + -------------------------------------------------------------------------- */ + +.folder-node { + margin-bottom: 6px; +} + +.folder-header { + padding: 8px 12px; + background: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: 6px; + cursor: pointer; + display: flex; + align-items: center; + gap: 8px; + user-select: none; + transition: all var(--transition-fast); +} + +.folder-header:hover { + background: var(--accent-glow); + border-color: var(--accent); +} + +.folder-icon { + font-size: 10px; + color: var(--accent); + transition: transform var(--transition-fast); + min-width: 12px; +} + +.folder-name { + flex: 1; + font-weight: 500; + color: var(--text-primary); + font-size: 13px; +} + +.folder-stats { + font-size: 11px; + color: var(--text-secondary); + background: var(--bg-tertiary); + padding: 2px 8px; + border-radius: 4px; + font-family: var(--font-mono); +} + +.folder-content { + padding-left: 20px; + margin-top: 6px; +} + +/* -------------------------------------------------------------------------- + File Items + -------------------------------------------------------------------------- */ + +.files-list { + display: flex; + flex-direction: column; + gap: 4px; + margin-top: 8px; +} + +.file-item { + display: flex; + align-items: center; + gap: 12px; + padding: 8px 12px; + background: var(--bg-primary); + border: 1px solid var(--border-subtle); + border-radius: 6px; + transition: all var(--transition-fast); +} + +.file-item:hover { + background: var(--bg-secondary); + border-color: var(--border); +} + +.file-item .file-link { + flex: 1; + min-width: 0; + font-size: 13px; +} + +.file-samples { + font-size: 12px; + color: var(--text-secondary); + font-weight: 600; + white-space: nowrap; + width: 130px; + flex-shrink: 0; + text-align: right; + font-family: var(--font-mono); +} + +.heatmap-bar-container { + width: 120px; + flex-shrink: 0; + display: flex; + align-items: center; +} + +.heatmap-bar { + flex-shrink: 0; + border-radius: 2px; +} + +/* Links */ +.file-link { + color: var(--accent); + text-decoration: none; + font-weight: 500; + transition: color var(--transition-fast); +} + +.file-link:hover { + color: var(--accent-hover); + text-decoration: underline; +} + +/* -------------------------------------------------------------------------- + Module Badges + -------------------------------------------------------------------------- */ + +.module-badge { + display: inline-block; + padding: 3px 8px; + border-radius: 4px; + font-size: 11px; + font-weight: 600; +} + +.badge-stdlib { + background: rgba(40, 167, 69, 0.15); + color: #28a745; +} + +.badge-site-packages { + background: rgba(0, 123, 255, 0.15); + color: #007bff; +} + +.badge-project { + background: rgba(255, 193, 7, 0.2); + color: #d39e00; +} + +.badge-other { + background: var(--bg-tertiary); + color: var(--text-secondary); +} + +[data-theme="dark"] .badge-stdlib { + background: rgba(40, 167, 69, 0.25); + color: #5dd879; +} + +[data-theme="dark"] .badge-site-packages { + background: rgba(88, 166, 255, 0.25); + color: #79b8ff; +} + +[data-theme="dark"] .badge-project { + background: rgba(255, 212, 59, 0.25); + color: #ffd43b; +} + +/* ========================================================================== + FILE VIEW STYLES (Code Display) + ========================================================================== */ + +.code-view { + font-family: var(--font-mono); + min-height: 100vh; +} + +/* Code Header (Top Bar for file view) */ +.code-header { + height: var(--topbar-height); + background: var(--header-gradient); + display: flex; + align-items: center; + padding: 0 16px; + gap: 16px; + box-shadow: 0 2px 10px rgba(55, 118, 171, 0.25); + border-bottom: 2px solid var(--python-gold); + position: sticky; + top: 0; + z-index: 100; +} + +.code-header-content { + display: flex; + align-items: center; + justify-content: space-between; + width: 94%; + max-width: 100%; + margin: 0 auto; +} + +.code-header h1 { + font-size: 14px; + font-weight: 600; + color: white; + margin: 0; + font-family: var(--font-mono); + display: flex; + align-items: center; + gap: 8px; +} + +/* File Stats Bar */ +.file-stats { + background: var(--bg-secondary); + padding: 16px 24px; + border-bottom: 1px solid var(--border); +} + +.file-stats .stats-grid { + width: 94%; + max-width: 100%; + margin: 0 auto; + display: grid; + grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); + gap: 12px; +} + +.stat-item { + background: var(--bg-primary); + padding: 12px; + border-radius: 8px; + box-shadow: var(--shadow-sm); + text-align: center; + border: 1px solid var(--border); + transition: all var(--transition-fast); +} + +.stat-item:hover { + transform: translateY(-2px); + box-shadow: var(--shadow-md); + border-color: var(--accent); +} + +.stat-item .stat-value { + font-size: 1.4em; + font-weight: 700; + color: var(--accent); +} + +.stat-item .stat-label { + color: var(--text-muted); + font-size: 10px; + margin-top: 2px; +} + +/* Legend */ +.legend { + background: var(--bg-secondary); + padding: 12px 24px; + border-bottom: 1px solid var(--border); +} + +.legend-content { + width: 100%; + display: flex; + align-items: center; + gap: 20px; + flex-wrap: nowrap; +} + +.legend-separator { + width: 1px; + height: 24px; + background: var(--border); + flex-shrink: 0; +} + +.legend-title { + font-weight: 600; + color: var(--text-primary); + font-size: 13px; + font-family: var(--font-sans); + flex-shrink: 0; +} + +.legend-gradient { + width: 150px; + flex-shrink: 0; + height: 20px; + background: linear-gradient(90deg, + var(--bg-tertiary) 0%, + var(--heat-2) 25%, + var(--heat-4) 50%, + var(--heat-6) 75%, + var(--heat-8) 100% + ); + border-radius: 4px; + border: 1px solid var(--border); +} + +.legend-labels { + display: flex; + gap: 12px; + font-size: 11px; + color: var(--text-muted); + font-family: var(--font-sans); + flex-shrink: 0; +} + +/* Legend Controls Group - wraps toggles and bytecode button together */ +.legend-controls { + display: flex; + align-items: center; + gap: 20px; + flex-shrink: 0; + margin-left: auto; +} + +/* Heatmap-Specific Toggle Overrides */ +#toggle-color-mode .toggle-track.on { + background: #8e44ad; + border-color: #8e44ad; + box-shadow: 0 0 8px rgba(142, 68, 173, 0.3); +} + +#toggle-cold .toggle-track.on { + background: #e67e22; + border-color: #e67e22; + box-shadow: 0 0 8px rgba(230, 126, 34, 0.3); +} + +/* Code Container */ +.code-container { + width: 94%; + max-width: 100%; + margin: 16px auto; + background: var(--bg-primary); + border: 1px solid var(--border); + border-radius: 8px 8px 8px 8px; + box-shadow: var(--shadow-sm); + /* Allow horizontal scroll for long lines, but don't clip sticky header */ +} + +/* Code Header Row */ +.code-header-row { + position: sticky; + top: var(--topbar-height); + z-index: 50; + display: flex; + background: var(--bg-secondary); + border-bottom: 2px solid var(--border); + font-weight: 700; + font-size: 11px; + color: var(--text-muted); + text-transform: uppercase; + letter-spacing: 0.5px; + border-radius: 8px 8px 0 0; +} + +.header-line-number { + flex-shrink: 0; + width: 60px; + padding: 8px 10px; + text-align: right; + border-right: 1px solid var(--border); +} + +.header-samples-self, +.header-samples-cumulative { + flex-shrink: 0; + width: 90px; + padding: 8px 10px; + text-align: right; + border-right: 1px solid var(--border); +} + +.header-samples-self { + color: var(--heat-8); +} + +.header-samples-cumulative { + color: var(--accent); +} + +.header-content { + flex: 1; + padding: 8px 15px; +} + +/* Code Lines */ +.code-line { + position: relative; + display: flex; + min-height: 20px; + line-height: 20px; + font-size: 13px; + transition: background var(--transition-fast); + scroll-margin-top: calc(var(--topbar-height) + 50px); +} + +.code-line:hover { + filter: brightness(0.97); +} + +[data-theme="dark"] .code-line:hover { + filter: brightness(1.1); +} + +.line-number { + flex-shrink: 0; + width: 60px; + padding: 0 10px; + text-align: right; + color: var(--text-muted); + background: var(--bg-secondary); + border-right: 1px solid var(--border); + user-select: none; + transition: all var(--transition-fast); +} + +.line-number:hover { + background: var(--accent); + color: white; + cursor: pointer; +} + +.line-samples-self, +.line-samples-cumulative { + flex-shrink: 0; + width: 90px; + padding: 0 10px; + text-align: right; + background: var(--bg-secondary); + border-right: 1px solid var(--border); + font-weight: 600; + user-select: none; + font-size: 12px; +} + +.line-samples-self { + color: var(--heat-8); +} + +.line-samples-cumulative { + color: var(--accent); +} + +.line-content { + flex: 1; + padding: 0 15px; + white-space: pre; + overflow-x: auto; +} + +/* Scrollbar Styling */ +.line-content::-webkit-scrollbar { + height: 6px; +} + +.line-content::-webkit-scrollbar-thumb { + background: var(--border); + border-radius: 3px; +} + +.line-content::-webkit-scrollbar-thumb:hover { + background: var(--text-muted); +} + +/* Navigation Buttons */ +.line-nav-buttons { + position: absolute; + right: 8px; + top: 50%; + transform: translateY(-50%); + display: flex; + gap: 4px; + align-items: center; +} + +.nav-btn { + padding: 2px 6px; + font-size: 12px; + font-weight: 500; + border: 1px solid var(--accent); + border-radius: 4px; + background: var(--bg-primary); + color: var(--accent); + cursor: pointer; + transition: all var(--transition-fast); + user-select: none; + line-height: 1; +} + +.nav-btn:hover:not(:disabled) { + background: var(--accent); + color: white; + transform: translateY(-1px); + box-shadow: var(--shadow-sm); +} + +.nav-btn:active:not(:disabled) { + transform: translateY(0); +} + +.nav-btn:disabled { + opacity: 0.3; + cursor: not-allowed; + color: var(--text-muted); + background: var(--bg-secondary); + border-color: var(--border); +} + +.nav-btn.caller { + color: var(--nav-caller); + border-color: var(--nav-caller); +} + +.nav-btn.callee { + color: var(--nav-callee); + border-color: var(--nav-callee); +} + +.nav-btn.caller:hover:not(:disabled) { + background: var(--nav-caller-hover); + color: white; +} + +.nav-btn.callee:hover:not(:disabled) { + background: var(--nav-callee-hover); + color: white; +} + +/* Highlighted target line */ +.code-line:target { + animation: highlight-line 2s ease-out; +} + +@keyframes highlight-line { + 0% { + background: rgba(255, 212, 59, 0.6) !important; + outline: 3px solid var(--python-gold); + outline-offset: -3px; + } + 50% { + background: rgba(255, 212, 59, 0.5) !important; + outline: 3px solid var(--python-gold); + outline-offset: -3px; + } + 100% { + outline: 3px solid transparent; + outline-offset: -3px; + } +} + +/* Popup menu for multiple callees */ +.callee-menu { + position: absolute; + background: var(--bg-primary); + border: 1px solid var(--border); + border-radius: 8px; + box-shadow: var(--shadow-lg); + padding: 8px; + z-index: 1000; + min-width: 250px; + max-width: 400px; + max-height: 300px; + overflow-y: auto; +} + +.callee-menu-header { + font-weight: 600; + color: var(--text-primary); + margin-bottom: 8px; + padding-bottom: 8px; + border-bottom: 1px solid var(--border); + font-size: 13px; + font-family: var(--font-sans); +} + +.callee-menu-item { + padding: 8px; + margin: 4px 0; + border-radius: 6px; + cursor: pointer; + transition: background var(--transition-fast); + display: flex; + flex-direction: column; + gap: 4px; +} + +.callee-menu-item:hover { + background: var(--bg-secondary); +} + +.callee-menu-func { + font-weight: 500; + color: var(--accent); + font-size: 12px; +} + +.callee-menu-file { + font-size: 11px; + color: var(--text-muted); +} + +.count-badge { + display: inline-block; + background: var(--accent); + color: white; + font-size: 10px; + padding: 2px 6px; + border-radius: 4px; + font-weight: 600; + margin-left: 6px; +} + +/* Callee menu scrollbar */ +.callee-menu::-webkit-scrollbar { + width: 6px; +} + +.callee-menu::-webkit-scrollbar-track { + background: var(--bg-secondary); + border-radius: 3px; +} + +.callee-menu::-webkit-scrollbar-thumb { + background: var(--border); + border-radius: 3px; +} + +/* -------------------------------------------------------------------------- + Scroll Minimap Marker + -------------------------------------------------------------------------- */ + +#scroll_marker { + position: fixed; + z-index: 1000; + right: 0; + top: 0; + width: 12px; + height: 100%; + background: var(--bg-secondary); + border-left: 1px solid var(--border); + pointer-events: none; +} + +#scroll_marker .marker { + position: absolute; + min-height: 3px; + width: 100%; + pointer-events: none; +} + +#scroll_marker .marker.cold { + background: var(--heat-1); +} + +#scroll_marker .marker.cool { + background: var(--heat-2); +} + +#scroll_marker .marker.mild { + background: var(--heat-3); +} + +#scroll_marker .marker.warm { + background: var(--heat-4); +} + +#scroll_marker .marker.hot { + background: var(--heat-5); +} + +#scroll_marker .marker.very-hot { + background: var(--heat-6); +} + +#scroll_marker .marker.intense { + background: var(--heat-7); +} + +#scroll_marker .marker.extreme { + background: var(--heat-8); +} + +/* -------------------------------------------------------------------------- + Responsive (Heatmap-specific) + -------------------------------------------------------------------------- */ + +@media (max-width: 1100px) { + .stats-summary { + grid-template-columns: repeat(2, 1fr); + } + + .legend-content { + flex-wrap: wrap; + justify-content: center; + } + + .legend-controls { + margin-left: 0; + } +} + +@media (max-width: 900px) { + .main-content { + padding: 16px; + } +} + +@media (max-width: 600px) { + .stats-summary { + grid-template-columns: 1fr; + } + + .file-stats .stats-grid { + grid-template-columns: repeat(2, 1fr); + } + + .legend-content { + flex-direction: column; + align-items: center; + gap: 12px; + } + + .legend-gradient { + width: 100%; + max-width: none; + } + + .legend-separator { + width: 80%; + height: 1px; + } + + .legend-controls { + flex-direction: column; + gap: 12px; + } + + .legend-controls .toggle-switch { + justify-content: center; + } + + .legend-controls .toggle-switch .toggle-label:first-child { + width: 70px; + text-align: right; + } + + .legend-controls .toggle-switch .toggle-label:last-child { + width: 90px; + text-align: left; + } + + /* Compact code columns on small screens */ + .header-line-number, + .line-number { + width: 40px; + } + + .header-samples-self, + .header-samples-cumulative, + .line-samples-self, + .line-samples-cumulative { + width: 55px; + font-size: 10px; + } + + /* Adjust padding - headers need vertical, data rows don't */ + .header-line-number, + .header-samples-self, + .header-samples-cumulative { + padding: 8px 4px; + } + + .line-number, + .line-samples-self, + .line-samples-cumulative { + padding: 0 4px; + } + + .bytecode-panel { + margin: 8px 10px 8px 160px; + } +} + +.bytecode-toggle { + flex-shrink: 0; + width: 20px; + height: 20px; + padding: 0; + margin: 0 4px; + border: none; + background: transparent; + color: var(--code-accent); + cursor: pointer; + font-size: 10px; + transition: transform var(--transition-fast), color var(--transition-fast); + display: inline-flex; + align-items: center; + justify-content: center; +} + +.bytecode-toggle:hover { + color: var(--accent); +} + +.bytecode-spacer { + flex-shrink: 0; + width: 20px; + height: 20px; + margin: 0 4px; +} + +.bytecode-panel { + background: var(--bg-primary); + border: 1px solid var(--border); + border-radius: 8px; + box-shadow: var(--shadow-md); + font-family: var(--font-mono); + font-size: 12px; + color: var(--text-primary); + line-height: 1.5; + word-wrap: break-word; + overflow-wrap: break-word; + padding: 0; + margin: 8px 10px 8px 250px; + position: relative; + z-index: 1; + overflow-y: auto; + max-height: 500px; + flex: 1; + transition: padding 0.3s cubic-bezier(0.4, 0, 0.2, 1); +} + +.bytecode-panel.expanded { + padding: 14px; +} + +.bytecode-wrapper { + position: relative; + display: flex; + overflow: visible; + max-height: 0; + opacity: 0; + transition: max-height 0.4s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease-in-out; +} + +.bytecode-wrapper.expanded { + max-height: 600px; + opacity: 1; + transition: max-height 0.5s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.4s ease-in-out; +} + +/* Column backdrop matching table header columns (line/self/total) */ +.bytecode-columns { + display: none; + position: absolute; + left: 0; + overflow: hidden; + pointer-events: none; + z-index: 0; +} + +.bytecode-wrapper.expanded .bytecode-columns { + display: flex; + top: 0; + bottom: 0; +} + +.bytecode-panel::-webkit-scrollbar { + width: 8px; +} + +.bytecode-panel::-webkit-scrollbar-track { + background: var(--bg-secondary); + border-radius: 4px; +} + +.bytecode-panel::-webkit-scrollbar-thumb { + background: var(--border); + border-radius: 4px; +} + +.bytecode-panel::-webkit-scrollbar-thumb:hover { + background: var(--text-muted); +} + +/* Specialization summary bar */ +.bytecode-spec-summary { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + margin-bottom: 10px; + border-radius: var(--radius-sm); + background: rgba(100, 100, 100, 0.1); +} + +.bytecode-spec-summary .spec-pct { + font-size: 1.4em; + font-weight: 700; +} + +.bytecode-spec-summary .spec-label { + font-weight: 500; + text-transform: uppercase; + font-size: 0.85em; + letter-spacing: 0.5px; +} + +.bytecode-spec-summary .spec-detail { + color: var(--text-secondary); + font-size: 0.9em; + margin-left: auto; +} + +.bytecode-spec-summary.high { + background: var(--spec-high-bg); + border-left: 3px solid var(--spec-high); +} +.bytecode-spec-summary.high .spec-pct, +.bytecode-spec-summary.high .spec-label { + color: var(--spec-high-text); +} + +.bytecode-spec-summary.medium { + background: var(--spec-medium-bg); + border-left: 3px solid var(--spec-medium); +} +.bytecode-spec-summary.medium .spec-pct, +.bytecode-spec-summary.medium .spec-label { + color: var(--spec-medium-text); +} + +.bytecode-spec-summary.low { + background: var(--spec-low-bg); + border-left: 3px solid var(--spec-low); +} +.bytecode-spec-summary.low .spec-pct, +.bytecode-spec-summary.low .spec-label { + color: var(--spec-low-text); +} + +.bytecode-header { + display: grid; + grid-template-columns: 1fr 80px 80px; + gap: 12px; + padding: 4px 8px; + font-weight: 600; + color: var(--text-secondary); + border-bottom: 1px solid var(--code-border); + margin-bottom: 4px; +} + +.bytecode-expand-all { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 6px 12px; + background: var(--bg-secondary); + border: 1px solid var(--code-border); + border-radius: var(--radius-sm); + color: var(--text-secondary); + font-size: 12px; + font-weight: 500; + cursor: pointer; + transition: all var(--transition-fast); + flex-shrink: 0; +} + +.bytecode-expand-all:hover, +.bytecode-expand-all.expanded { + background: var(--accent); + color: white; + border-color: var(--accent); +} + +.bytecode-expand-all .expand-icon { + font-size: 10px; + transition: transform var(--transition-fast); +} + +.bytecode-expand-all.expanded .expand-icon { + transform: rotate(90deg); +} + +/* ======================================== + INSTRUCTION SPAN HIGHLIGHTING + (triggered only from bytecode panel hover) + ======================================== */ + +/* Highlight from bytecode panel hover */ +.instr-span.highlight-from-bytecode { + outline: 3px solid #ff6b6b !important; + background-color: rgba(255, 107, 107, 0.4) !important; + border-radius: 2px; +} + +/* Bytecode instruction row */ +.bytecode-instruction { + display: grid; + grid-template-columns: 1fr 80px 80px; + gap: 12px; + align-items: center; + padding: 4px 8px; + margin: 2px 0; + border-radius: var(--radius-sm); + cursor: pointer; + transition: background-color var(--transition-fast); +} + +.bytecode-instruction:hover, +.bytecode-instruction.highlight { + background-color: rgba(55, 118, 171, 0.15); +} + +.bytecode-instruction[data-locations] { + cursor: pointer; +} + +.bytecode-instruction[data-locations]:hover { + background-color: rgba(255, 107, 107, 0.2); +} + +.bytecode-opname { + font-weight: 600; + font-family: var(--font-mono); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.bytecode-opname.specialized { + color: #2e7d32; +} + +[data-theme="dark"] .bytecode-opname.specialized { + color: #81c784; +} + +.bytecode-opname .base-op { + color: var(--code-text-muted); + font-weight: normal; + font-size: 0.9em; + margin-left: 4px; +} + +.bytecode-samples { + text-align: right; + font-weight: 600; + color: var(--accent); + font-family: var(--font-mono); +} + +.bytecode-samples.hot { + color: #ff6b6b; +} + +.bytecode-heatbar { + width: 60px; + height: 12px; + background: var(--bg-secondary); + border-radius: 2px; + overflow: hidden; + border: 1px solid var(--code-border); +} + +.bytecode-heatbar-fill { + height: 100%; + background: linear-gradient(90deg, #00d4ff 0%, #ff6b00 100%); +} + +.specialization-badge { + display: inline-block; + padding: 1px 6px; + font-size: 0.75em; + background: #e8f5e9; + color: #2e7d32; + border-radius: 3px; + margin-left: 6px; + font-weight: 600; +} + +[data-theme="dark"] .specialization-badge { + background: rgba(129, 199, 132, 0.2); + color: #81c784; +} + +.bytecode-empty { + color: var(--code-text-muted); + font-style: italic; + padding: 8px; +} + +.bytecode-error { + color: #d32f2f; + font-style: italic; + padding: 8px; +} + +/* ======================================== + SPAN TOOLTIPS + ======================================== */ + +.span-tooltip { + position: absolute; + z-index: 10000; + background: var(--bg-primary); + color: var(--text-primary); + padding: 10px 14px; + border-radius: var(--radius-md); + border: 1px solid var(--border); + font-family: var(--font-sans); + font-size: 12px; + box-shadow: var(--shadow-lg); + pointer-events: none; + min-width: 160px; + max-width: 300px; +} + +.span-tooltip::after { + content: ''; + position: absolute; + bottom: -7px; + left: 50%; + transform: translateX(-50%); + border-width: 7px 7px 0; + border-style: solid; + border-color: var(--bg-primary) transparent transparent; + filter: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.1)); +} + +.span-tooltip-header { + font-weight: 600; + margin-bottom: 8px; + padding-bottom: 6px; + border-bottom: 1px solid var(--border); + color: var(--text-primary); +} + +.span-tooltip-header.hot { + color: #e65100; +} + +.span-tooltip-header.warm { + color: #f59e0b; +} + +.span-tooltip-header.cold { + color: var(--text-muted); +} + +.span-tooltip-row { + display: flex; + justify-content: space-between; + margin: 4px 0; + gap: 16px; +} + +.span-tooltip-label { + color: var(--text-secondary); +} + +.span-tooltip-value { + font-weight: 600; + text-align: right; + color: var(--text-primary); +} + +.span-tooltip-value.highlight { + color: var(--accent); +} + +.span-tooltip-section { + font-weight: 600; + color: var(--text-secondary); + font-size: 11px; + margin-top: 8px; + margin-bottom: 4px; + padding-top: 6px; + border-top: 1px solid var(--border); +} + +.span-tooltip-opcode { + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-primary); + background: var(--bg-secondary); + padding: 3px 8px; + margin: 2px 0; + border-radius: var(--radius-sm); + border-left: 2px solid var(--accent); +} diff --git a/Lib/profiling/sampling/_heatmap_assets/heatmap.js b/Lib/profiling/sampling/_heatmap_assets/heatmap.js new file mode 100644 index 00000000000..1f698779f3a --- /dev/null +++ b/Lib/profiling/sampling/_heatmap_assets/heatmap.js @@ -0,0 +1,738 @@ +// Tachyon Profiler - Heatmap JavaScript +// Interactive features for the heatmap visualization +// Aligned with Flamegraph viewer design patterns + +// ============================================================================ +// State Management +// ============================================================================ + +let currentMenu = null; +let colorMode = 'self'; // 'self' or 'cumulative' - default to self +let coldCodeHidden = false; + +// ============================================================================ +// Theme Support +// ============================================================================ + +function toggleTheme() { + toggleAndSaveTheme(); + applyLineColors(); + + // Rebuild scroll marker with new theme colors + buildScrollMarker(); +} + +// ============================================================================ +// Utility Functions +// ============================================================================ + +function createElement(tag, className, textContent = '') { + const el = document.createElement(tag); + if (className) el.className = className; + if (textContent) el.textContent = textContent; + return el; +} + +function calculateMenuPosition(buttonRect, menuWidth, menuHeight) { + const viewport = { width: window.innerWidth, height: window.innerHeight }; + const scroll = { + x: window.pageXOffset || document.documentElement.scrollLeft, + y: window.pageYOffset || document.documentElement.scrollTop + }; + + const left = buttonRect.right + menuWidth + 10 < viewport.width + ? buttonRect.right + scroll.x + 10 + : Math.max(scroll.x + 10, buttonRect.left + scroll.x - menuWidth - 10); + + const top = buttonRect.bottom + menuHeight + 10 < viewport.height + ? buttonRect.bottom + scroll.y + 5 + : Math.max(scroll.y + 10, buttonRect.top + scroll.y - menuHeight - 10); + + return { left, top }; +} + +// ============================================================================ +// Menu Management +// ============================================================================ + +function closeMenu() { + if (currentMenu) { + currentMenu.remove(); + currentMenu = null; + } +} + +function showNavigationMenu(button, items, title) { + closeMenu(); + + const menu = createElement('div', 'callee-menu'); + menu.appendChild(createElement('div', 'callee-menu-header', title)); + + items.forEach(linkData => { + const item = createElement('div', 'callee-menu-item'); + + const funcDiv = createElement('div', 'callee-menu-func'); + funcDiv.textContent = linkData.func; + + if (linkData.count !== undefined && linkData.count > 0) { + const countBadge = createElement('span', 'count-badge'); + countBadge.textContent = linkData.count.toLocaleString(); + countBadge.title = `${linkData.count.toLocaleString()} samples`; + funcDiv.appendChild(document.createTextNode(' ')); + funcDiv.appendChild(countBadge); + } + + item.appendChild(funcDiv); + item.appendChild(createElement('div', 'callee-menu-file', linkData.file)); + item.addEventListener('click', () => navigateToLine(linkData.link)); + menu.appendChild(item); + }); + + const pos = calculateMenuPosition(button.getBoundingClientRect(), 350, 300); + menu.style.left = `${pos.left}px`; + menu.style.top = `${pos.top}px`; + + document.body.appendChild(menu); + currentMenu = menu; +} + +// ============================================================================ +// Navigation +// ============================================================================ + +function handleNavigationClick(button, e) { + e.stopPropagation(); + + const navData = button.getAttribute('data-nav'); + if (navData) { + navigateToLine(JSON.parse(navData).link); + return; + } + + const navMulti = button.getAttribute('data-nav-multi'); + if (navMulti) { + const items = JSON.parse(navMulti); + const title = button.classList.contains('caller') ? 'Choose a caller:' : 'Choose a callee:'; + showNavigationMenu(button, items, title); + } +} + +function restartLineHighlight(target) { + target.style.animation = 'none'; + // Force style recalculation so restoring the animation restarts it. + void target.offsetWidth; + target.style.animation = ''; +} + +function navigateToLine(link) { + const url = new URL(link, window.location.href); + + if (url.href === window.location.href) { + scrollToTargetLine(); + } else { + window.location.href = link; + } +} + +function scrollToTargetLine() { + if (!window.location.hash) return; + const target = document.querySelector(window.location.hash); + if (target) { + target.scrollIntoView({ behavior: 'smooth', block: 'start' }); + restartLineHighlight(target); + } +} + +// ============================================================================ +// Sample Count & Intensity +// ============================================================================ + +function getSampleCount(line) { + let text; + if (colorMode === 'self') { + text = line.querySelector('.line-samples-self')?.textContent.trim().replace(/,/g, ''); + } else { + text = line.querySelector('.line-samples-cumulative')?.textContent.trim().replace(/,/g, ''); + } + return parseInt(text) || 0; +} + +// ============================================================================ +// Scroll Minimap +// ============================================================================ + +function buildScrollMarker() { + const existing = document.getElementById('scroll_marker'); + if (existing) existing.remove(); + + if (document.body.scrollHeight <= window.innerHeight) return; + + const allLines = document.querySelectorAll('.code-line'); + const lines = Array.from(allLines).filter(line => line.style.display !== 'none'); + const markerScale = window.innerHeight / document.body.scrollHeight; + const lineHeight = Math.min(Math.max(3, window.innerHeight / lines.length), 10); + const maxSamples = Math.max(...Array.from(lines, getSampleCount)); + + const scrollMarker = createElement('div', ''); + scrollMarker.id = 'scroll_marker'; + + let prevLine = -99, lastMark, lastTop; + + lines.forEach((line, index) => { + const samples = getSampleCount(line); + if (samples === 0) return; + + const lineTop = Math.floor(line.offsetTop * markerScale); + const lineNumber = index + 1; + const intensityClass = maxSamples > 0 ? (intensityToClass(samples / maxSamples) || 'cold') : 'cold'; + + if (lineNumber === prevLine + 1 && lastMark?.classList.contains(intensityClass)) { + lastMark.style.height = `${lineTop + lineHeight - lastTop}px`; + } else { + lastMark = createElement('div', `marker ${intensityClass}`); + lastMark.style.height = `${lineHeight}px`; + lastMark.style.top = `${lineTop}px`; + scrollMarker.appendChild(lastMark); + lastTop = lineTop; + } + + prevLine = lineNumber; + }); + + document.body.appendChild(scrollMarker); +} + +function applyLineColors() { + const lines = document.querySelectorAll('.code-line'); + lines.forEach(line => { + let intensity; + if (colorMode === 'self') { + intensity = parseFloat(line.getAttribute('data-self-intensity')) || 0; + } else { + intensity = parseFloat(line.getAttribute('data-cumulative-intensity')) || 0; + } + + const color = intensityToColor(intensity); + line.style.background = color; + }); +} + +// ============================================================================ +// Toggle Controls +// ============================================================================ + +function toggleColdCode() { + coldCodeHidden = !coldCodeHidden; + applyHotFilter(); + updateToggleUI('toggle-cold', coldCodeHidden); + buildScrollMarker(); +} + +function applyHotFilter() { + const lines = document.querySelectorAll('.code-line'); + + lines.forEach(line => { + const selfSamples = line.querySelector('.line-samples-self')?.textContent.trim(); + const cumulativeSamples = line.querySelector('.line-samples-cumulative')?.textContent.trim(); + + let isCold; + if (colorMode === 'self') { + isCold = !selfSamples || selfSamples === ''; + } else { + isCold = !cumulativeSamples || cumulativeSamples === ''; + } + + if (isCold) { + line.style.display = coldCodeHidden ? 'none' : 'flex'; + } else { + line.style.display = 'flex'; + } + }); +} + +function toggleColorMode() { + colorMode = colorMode === 'self' ? 'cumulative' : 'self'; + applyLineColors(); + + updateToggleUI('toggle-color-mode', colorMode === 'cumulative'); + + if (coldCodeHidden) { + applyHotFilter(); + } + + buildScrollMarker(); +} + +// ============================================================================ +// Initialization +// ============================================================================ + +document.addEventListener('DOMContentLoaded', function() { + restoreUIState(); + applyLineColors(); + + // Initialize navigation buttons + document.querySelectorAll('.nav-btn').forEach(button => { + button.addEventListener('click', e => handleNavigationClick(button, e)); + }); + + // Initialize line number permalink handlers + document.querySelectorAll('.line-number').forEach(lineNum => { + lineNum.style.cursor = 'pointer'; + lineNum.addEventListener('click', e => { + window.location.hash = `line-${e.target.textContent.trim()}`; + }); + }); + + // Initialize toggle buttons + const toggleColdBtn = document.getElementById('toggle-cold'); + if (toggleColdBtn) toggleColdBtn.addEventListener('click', toggleColdCode); + + const colorModeBtn = document.getElementById('toggle-color-mode'); + if (colorModeBtn) colorModeBtn.addEventListener('click', toggleColorMode); + + // Initialize specialization view toggle (hide if no bytecode data) + const hasBytecode = document.querySelectorAll('.bytecode-toggle').length > 0; + + const specViewBtn = document.getElementById('toggle-spec-view'); + if (specViewBtn) { + if (hasBytecode) { + specViewBtn.addEventListener('click', toggleSpecView); + } else { + specViewBtn.style.display = 'none'; + } + } + + // Initialize expand-all bytecode button + const expandAllBtn = document.getElementById('toggle-all-bytecode'); + if (expandAllBtn) { + if (hasBytecode) { + expandAllBtn.addEventListener('click', toggleAllBytecode); + } else { + expandAllBtn.style.display = 'none'; + } + } + + // Initialize span tooltips + initSpanTooltips(); + + // Build scroll marker and scroll to target + setTimeout(buildScrollMarker, 200); + setTimeout(scrollToTargetLine, 100); +}); + +// Close menu when clicking outside +document.addEventListener('click', e => { + if (currentMenu && !currentMenu.contains(e.target) && !e.target.classList.contains('nav-btn')) { + closeMenu(); + } +}); + +// ======================================== +// SPECIALIZATION VIEW TOGGLE +// ======================================== + +let specViewEnabled = false; + +/** + * Calculate heat color for given intensity (0-1) + * Hot spans (>30%) get warm orange, cold spans get dimmed gray + * @param {number} intensity - Value between 0 and 1 + * @returns {string} rgba color string + */ +function calculateHeatColor(intensity) { + // Hot threshold: only spans with >30% of max samples get color + if (intensity > 0.3) { + // Normalize intensity above threshold to 0-1 + const normalizedIntensity = (intensity - 0.3) / 0.7; + // Warm orange-red with increasing opacity for hotter spans + const alpha = 0.25 + normalizedIntensity * 0.35; // 0.25 to 0.6 + const hotColor = getComputedStyle(document.documentElement).getPropertyValue('--span-hot-base').trim(); + return `rgba(${hotColor}, ${alpha})`; + } else if (intensity > 0) { + // Cold spans: very subtle gray, almost invisible + const coldColor = getComputedStyle(document.documentElement).getPropertyValue('--span-cold-base').trim(); + return `rgba(${coldColor}, 0.1)`; + } + return 'transparent'; +} + +/** + * Apply intensity-based heat colors to source spans + * Hot spans get orange highlight, cold spans get dimmed + * @param {boolean} enable - Whether to enable or disable span coloring + */ +function applySpanHeatColors(enable) { + document.querySelectorAll('.instr-span').forEach(span => { + const samples = enable ? (parseInt(span.dataset.samples) || 0) : 0; + if (samples > 0) { + const intensity = samples / (parseInt(span.dataset.maxSamples) || 1); + span.style.backgroundColor = calculateHeatColor(intensity); + span.style.borderRadius = '2px'; + span.style.padding = '0 1px'; + span.style.cursor = 'pointer'; + } else { + span.style.cssText = ''; + } + }); +} + +// ======================================== +// SPAN TOOLTIPS +// ======================================== + +let activeTooltip = null; + +/** + * Create and show tooltip for a span + */ +function showSpanTooltip(span) { + hideSpanTooltip(); + + const samples = parseInt(span.dataset.samples) || 0; + const maxSamples = parseInt(span.dataset.maxSamples) || 1; + const pct = span.dataset.pct || '0'; + const opcodes = span.dataset.opcodes || ''; + + if (samples === 0) return; + + const intensity = samples / maxSamples; + const isHot = intensity > 0.7; + const isWarm = intensity > 0.3; + const hotnessText = isHot ? 'Hot' : isWarm ? 'Warm' : 'Cold'; + const hotnessClass = isHot ? 'hot' : isWarm ? 'warm' : 'cold'; + + // Build opcodes rows - each opcode on its own row + let opcodesHtml = ''; + if (opcodes) { + const opcodeList = opcodes.split(',').map(op => op.trim()).filter(op => op); + if (opcodeList.length > 0) { + opcodesHtml = ` +
Opcodes:
+ ${opcodeList.map(op => `
${op}
`).join('')} + `; + } + } + + const tooltip = document.createElement('div'); + tooltip.className = 'span-tooltip'; + tooltip.innerHTML = ` +
${hotnessText}
+
+ Samples: + ${samples.toLocaleString()} +
+
+ % of line: + ${pct}% +
+ ${opcodesHtml} + `; + + document.body.appendChild(tooltip); + activeTooltip = tooltip; + + // Position tooltip above the span + const rect = span.getBoundingClientRect(); + const tooltipRect = tooltip.getBoundingClientRect(); + + let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2); + let top = rect.top - tooltipRect.height - 8; + + // Keep tooltip in viewport + if (left < 5) left = 5; + if (left + tooltipRect.width > window.innerWidth - 5) { + left = window.innerWidth - tooltipRect.width - 5; + } + if (top < 5) { + top = rect.bottom + 8; // Show below if no room above + } + + tooltip.style.left = `${left + window.scrollX}px`; + tooltip.style.top = `${top + window.scrollY}px`; +} + +/** + * Hide active tooltip + */ +function hideSpanTooltip() { + if (activeTooltip) { + activeTooltip.remove(); + activeTooltip = null; + } +} + +/** + * Initialize span tooltip handlers + */ +function initSpanTooltips() { + document.addEventListener('mouseover', (e) => { + const span = e.target.closest('.instr-span'); + if (span && specViewEnabled) { + showSpanTooltip(span); + } + }); + + document.addEventListener('mouseout', (e) => { + const span = e.target.closest('.instr-span'); + if (span) { + hideSpanTooltip(); + } + }); +} + +function toggleSpecView() { + specViewEnabled = !specViewEnabled; + const lines = document.querySelectorAll('.code-line'); + + if (specViewEnabled) { + lines.forEach(line => { + const specColor = line.getAttribute('data-spec-color'); + line.style.background = specColor || 'transparent'; + }); + } else { + applyLineColors(); + } + + applySpanHeatColors(specViewEnabled); + updateToggleUI('toggle-spec-view', specViewEnabled); + + // Disable/enable color mode toggle based on spec view state + const colorModeToggle = document.getElementById('toggle-color-mode'); + if (colorModeToggle) { + colorModeToggle.classList.toggle('disabled', specViewEnabled); + } + + buildScrollMarker(); +} + +// ======================================== +// BYTECODE PANEL TOGGLE +// ======================================== + +/** + * Toggle bytecode panel visibility for a source line + * @param {HTMLElement} button - The toggle button that was clicked + */ +function toggleBytecode(button) { + const lineDiv = button.closest('.code-line'); + const lineId = lineDiv.id; + const lineNum = lineId.replace('line-', ''); + const panel = document.getElementById(`bytecode-${lineNum}`); + const wrapper = document.getElementById(`bytecode-wrapper-${lineNum}`); + + if (!panel || !wrapper) return; + + const isExpanded = panel.classList.contains('expanded'); + + if (isExpanded) { + panel.classList.remove('expanded'); + wrapper.classList.remove('expanded'); + button.classList.remove('expanded'); + button.innerHTML = '▶'; // Right arrow + } else { + if (!panel.dataset.populated) { + populateBytecodePanel(panel, button); + } + panel.classList.add('expanded'); + wrapper.classList.add('expanded'); + button.classList.add('expanded'); + button.innerHTML = '▼'; // Down arrow + } +} + +/** + * Populate bytecode panel with instruction data + * @param {HTMLElement} panel - The panel element to populate + * @param {HTMLElement} button - The button containing the bytecode data + */ +function populateBytecodePanel(panel, button) { + const bytecodeJson = button.getAttribute('data-bytecode'); + if (!bytecodeJson) return; + + // Get line number from parent + const lineDiv = button.closest('.code-line'); + const lineNum = lineDiv ? lineDiv.id.replace('line-', '') : null; + + try { + const instructions = JSON.parse(bytecodeJson); + if (!instructions.length) { + panel.innerHTML = '
No bytecode data
'; + panel.dataset.populated = 'true'; + return; + } + + const maxSamples = Math.max(...instructions.map(i => i.samples), 1); + + // Calculate specialization stats + const totalSamples = instructions.reduce((sum, i) => sum + i.samples, 0); + const specializedSamples = instructions + .filter(i => i.is_specialized) + .reduce((sum, i) => sum + i.samples, 0); + const specPct = totalSamples > 0 ? Math.round(100 * specializedSamples / totalSamples) : 0; + const specializedCount = instructions.filter(i => i.is_specialized).length; + + // Determine specialization level class + let specClass = 'low'; + if (specPct >= 67) specClass = 'high'; + else if (specPct >= 33) specClass = 'medium'; + + // Build specialization summary + const instruction_word = instructions.length === 1 ? 'instruction' : 'instructions'; + const sample_word = totalSamples === 1 ? 'sample' : 'samples'; + let html = `
+ ${specPct}% + specialized + (${specializedCount}/${instructions.length} ${instruction_word}, ${specializedSamples.toLocaleString()}/${totalSamples.toLocaleString()} ${sample_word}) +
`; + + html += '
' + + 'Instruction' + + 'Samples' + + 'Heat
'; + + for (const instr of instructions) { + const heatPct = (instr.samples / maxSamples) * 100; + const isHot = heatPct > 50; + const specializedClass = instr.is_specialized ? ' specialized' : ''; + const baseOpHtml = instr.is_specialized + ? `(${escapeHtml(instr.base_opname)})` : ''; + const badge = instr.is_specialized + ? 'SPECIALIZED' : ''; + + // Build location data attributes for cross-referencing with source spans + const hasLocations = instr.locations && instr.locations.length > 0; + const locationData = hasLocations + ? `data-locations='${JSON.stringify(instr.locations)}' data-line="${lineNum}" data-opcode="${instr.opcode}"` + : ''; + + html += `
+ ${escapeHtml(instr.opname)}${baseOpHtml}${badge} + ${instr.samples.toLocaleString()} +
+
`; + } + + panel.innerHTML = html; + panel.dataset.populated = 'true'; + + // Add hover handlers for bytecode instructions to highlight source spans + panel.querySelectorAll('.bytecode-instruction[data-locations]').forEach(instrEl => { + instrEl.addEventListener('mouseenter', highlightSourceFromBytecode); + instrEl.addEventListener('mouseleave', unhighlightSourceFromBytecode); + }); + } catch (e) { + panel.innerHTML = '
Error loading bytecode
'; + console.error('Error parsing bytecode data:', e); + } +} + +/** + * Highlight source spans when hovering over bytecode instruction + */ +function highlightSourceFromBytecode(e) { + const instrEl = e.currentTarget; + const lineNum = instrEl.dataset.line; + const locationsStr = instrEl.dataset.locations; + + if (!lineNum) return; + + const lineDiv = document.getElementById(`line-${lineNum}`); + if (!lineDiv) return; + + // Parse locations and highlight matching spans by column range + try { + const locations = JSON.parse(locationsStr || '[]'); + const spans = lineDiv.querySelectorAll('.instr-span'); + spans.forEach(span => { + const spanStart = parseInt(span.dataset.colStart); + const spanEnd = parseInt(span.dataset.colEnd); + for (const loc of locations) { + // Match if span's range matches instruction's location + if (spanStart === loc.col_offset && spanEnd === loc.end_col_offset) { + span.classList.add('highlight-from-bytecode'); + break; + } + } + }); + } catch (err) { + console.error('Error parsing locations:', err); + } + + // Also highlight the instruction row itself + instrEl.classList.add('highlight'); +} + +/** + * Remove highlighting from source spans + */ +function unhighlightSourceFromBytecode(e) { + const instrEl = e.currentTarget; + const lineNum = instrEl.dataset.line; + + if (!lineNum) return; + + const lineDiv = document.getElementById(`line-${lineNum}`); + if (!lineDiv) return; + + const spans = lineDiv.querySelectorAll('.instr-span.highlight-from-bytecode'); + spans.forEach(span => { + span.classList.remove('highlight-from-bytecode'); + }); + + instrEl.classList.remove('highlight'); +} + +/** + * Escape HTML special characters + * @param {string} text - Text to escape + * @returns {string} Escaped HTML + */ +function escapeHtml(text) { + const div = document.createElement('div'); + div.textContent = text; + return div.innerHTML; +} + +/** + * Toggle all bytecode panels at once + */ +function toggleAllBytecode() { + const buttons = document.querySelectorAll('.bytecode-toggle'); + if (buttons.length === 0) return; + + const someExpanded = Array.from(buttons).some(b => b.classList.contains('expanded')); + const expandAllBtn = document.getElementById('toggle-all-bytecode'); + + buttons.forEach(button => { + const isExpanded = button.classList.contains('expanded'); + if (someExpanded ? isExpanded : !isExpanded) { + toggleBytecode(button); + } + }); + + // Update the expand-all button state + if (expandAllBtn) { + expandAllBtn.classList.toggle('expanded', !someExpanded); + } +} + +// Keyboard shortcut: 'b' toggles all bytecode panels, Enter/Space activates toggle switches +document.addEventListener('keydown', function(e) { + if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') { + return; + } + if (e.key === 'b' && !e.ctrlKey && !e.altKey && !e.metaKey) { + toggleAllBytecode(); + } + if ((e.key === 'Enter' || e.key === ' ') && e.target.classList.contains('toggle-switch')) { + e.preventDefault(); + e.target.click(); + } +}); + +// Handle hash changes +window.addEventListener('hashchange', () => setTimeout(scrollToTargetLine, 50)); + +// Rebuild scroll marker on resize +window.addEventListener('resize', buildScrollMarker); diff --git a/Lib/profiling/sampling/_heatmap_assets/heatmap_index.js b/Lib/profiling/sampling/_heatmap_assets/heatmap_index.js new file mode 100644 index 00000000000..db4b5485056 --- /dev/null +++ b/Lib/profiling/sampling/_heatmap_assets/heatmap_index.js @@ -0,0 +1,104 @@ +// Tachyon Profiler - Heatmap Index JavaScript +// Index page specific functionality + +// ============================================================================ +// Heatmap Bar Coloring +// ============================================================================ + +function applyHeatmapBarColors() { + const bars = document.querySelectorAll('.heatmap-bar[data-intensity]'); + bars.forEach(bar => { + const intensity = parseFloat(bar.getAttribute('data-intensity')) || 0; + const color = intensityToColor(intensity); + bar.style.backgroundColor = color; + }); +} + +// ============================================================================ +// Theme Support +// ============================================================================ + +function toggleTheme() { + toggleAndSaveTheme(); + applyHeatmapBarColors(); +} + +// ============================================================================ +// Type Section Toggle (stdlib, project, etc) +// ============================================================================ + +function toggleTypeSection(header) { + const section = header.parentElement; + const content = section.querySelector('.type-content'); + const icon = header.querySelector('.type-icon'); + + if (content.style.display === 'none') { + content.style.display = 'block'; + icon.textContent = '\u25BC'; + } else { + content.style.display = 'none'; + icon.textContent = '\u25B6'; + } +} + +// ============================================================================ +// Folder Toggle +// ============================================================================ + +function toggleFolder(header) { + const folder = header.parentElement; + const content = folder.querySelector('.folder-content'); + const icon = header.querySelector('.folder-icon'); + + if (content.style.display === 'none') { + content.style.display = 'block'; + icon.textContent = '\u25BC'; + folder.classList.remove('collapsed'); + } else { + content.style.display = 'none'; + icon.textContent = '\u25B6'; + folder.classList.add('collapsed'); + } +} + +// ============================================================================ +// Expand/Collapse All +// ============================================================================ + +function expandAll() { + // Expand all type sections + document.querySelectorAll('.type-section').forEach(section => { + const content = section.querySelector('.type-content'); + const icon = section.querySelector('.type-icon'); + content.style.display = 'block'; + icon.textContent = '\u25BC'; + }); + + // Expand all folders + document.querySelectorAll('.folder-node').forEach(folder => { + const content = folder.querySelector('.folder-content'); + const icon = folder.querySelector('.folder-icon'); + content.style.display = 'block'; + icon.textContent = '\u25BC'; + folder.classList.remove('collapsed'); + }); +} + +function collapseAll() { + document.querySelectorAll('.folder-node').forEach(folder => { + const content = folder.querySelector('.folder-content'); + const icon = folder.querySelector('.folder-icon'); + content.style.display = 'none'; + icon.textContent = '\u25B6'; + folder.classList.add('collapsed'); + }); +} + +// ============================================================================ +// Initialization +// ============================================================================ + +document.addEventListener('DOMContentLoaded', function() { + restoreUIState(); + applyHeatmapBarColors(); +}); diff --git a/Lib/profiling/sampling/_heatmap_assets/heatmap_index_template.html b/Lib/profiling/sampling/_heatmap_assets/heatmap_index_template.html new file mode 100644 index 00000000000..8d04149abe3 --- /dev/null +++ b/Lib/profiling/sampling/_heatmap_assets/heatmap_index_template.html @@ -0,0 +1,136 @@ + + + + + + Tachyon Profiler - Heatmap Report + + + +
+ +
+
+ + Tachyon + + Heatmap Report +
+
+ + + + + + +
+
+ + +
+ +
+
+
📄
+
+ + Files Profiled +
+
+
+
+
📊
+
+ + Total Snapshots +
+
+
+
+
⏱
+
+ + Duration +
+
+
+
+
⚡
+
+ + Samples/sec +
+
+
+
+
+
+
⚠
+ Error Rate +
+ +
+
+
+
+
+
+
+
+
💥
+ Missed Samples +
+ +
+
+
+
+
+
+ + +
+

Profiled Files

+
+ +
+ + +
+ +
+ +
+
+ + +
+ + Tachyon Profiler + + + Python Sampling Profiler + +
+
+ + + + diff --git a/Lib/profiling/sampling/_heatmap_assets/heatmap_pyfile_template.html b/Lib/profiling/sampling/_heatmap_assets/heatmap_pyfile_template.html new file mode 100644 index 00000000000..2a9c07647e6 --- /dev/null +++ b/Lib/profiling/sampling/_heatmap_assets/heatmap_pyfile_template.html @@ -0,0 +1,131 @@ + + + + + + <!-- FILENAME --> - Heatmap + + + +
+ +
+
+ + Tachyon + + +
+
+ + + + + + + + + + + +
+
+ + +
+
+
+
+
Self Samples
+
+
+
+
Cumulative
+
+
+
+
Lines Hit
+
+
+
%
+
% of Total
+
+
+
+
Max Self
+
+
+
+
Max Total
+
+
+
+ + +
+
+ Intensity: +
+
+ Cold + + Hot +
+ +
+
+ Self Time +
+ Total Time +
+
+ Show All +
+ Hot Only +
+
+ Heat +
+ Specialization +
+ + +
+
+
+ + +
+
+
Line
+
Self
+
Total
+
Code
+
+ +
+
+ + + + diff --git a/Lib/profiling/sampling/_heatmap_assets/heatmap_shared.js b/Lib/profiling/sampling/_heatmap_assets/heatmap_shared.js new file mode 100644 index 00000000000..fb761335876 --- /dev/null +++ b/Lib/profiling/sampling/_heatmap_assets/heatmap_shared.js @@ -0,0 +1,64 @@ +// Tachyon Profiler - Shared Heatmap JavaScript +// Common utilities shared between index and file views + +// ============================================================================ +// Heat Level Mapping (Single source of truth for intensity thresholds) +// ============================================================================ + +// Maps intensity (0-1) to heat level (0-8). Level 0 = no heat, 1-8 = heat levels. +function intensityToHeatLevel(intensity) { + if (intensity <= 0) return 0; + if (intensity <= 0.125) return 1; + if (intensity <= 0.25) return 2; + if (intensity <= 0.375) return 3; + if (intensity <= 0.5) return 4; + if (intensity <= 0.625) return 5; + if (intensity <= 0.75) return 6; + if (intensity <= 0.875) return 7; + return 8; +} + +// Class names corresponding to heat levels 1-8 (used by scroll marker) +const HEAT_CLASS_NAMES = ['cold', 'cool', 'mild', 'warm', 'hot', 'very-hot', 'intense', 'extreme']; + +function intensityToClass(intensity) { + const level = intensityToHeatLevel(intensity); + return level === 0 ? null : HEAT_CLASS_NAMES[level - 1]; +} + +// ============================================================================ +// Color Mapping (Intensity to Heat Color) +// ============================================================================ + +function intensityToColor(intensity) { + const level = intensityToHeatLevel(intensity); + if (level === 0) { + return 'transparent'; + } + const rootStyle = getComputedStyle(document.documentElement); + return rootStyle.getPropertyValue(`--heat-${level}`).trim(); +} + +// ============================================================================ +// Theme Support +// ============================================================================ + +// Restore theme from localStorage, or use browser preference +function restoreUIState() { + applyTheme(getPreferredTheme()); +} + +// ============================================================================ +// Favicon (Reuse logo image as favicon) +// ============================================================================ + +(function() { + const logo = document.querySelector('.brand-logo img'); + if (logo) { + const favicon = document.createElement('link'); + favicon.rel = 'icon'; + favicon.type = 'image/png'; + favicon.href = logo.src; + document.head.appendChild(favicon); + } +})(); diff --git a/Lib/profiling/sampling/_shared_assets/base.css b/Lib/profiling/sampling/_shared_assets/base.css new file mode 100644 index 00000000000..2164f3f3aa1 --- /dev/null +++ b/Lib/profiling/sampling/_shared_assets/base.css @@ -0,0 +1,514 @@ +/* ========================================================================== + Python Profiler - Shared CSS Foundation + Design system shared between Flamegraph and Heatmap viewers + ========================================================================== */ + +/* -------------------------------------------------------------------------- + CSS Variables & Theme System + -------------------------------------------------------------------------- */ + +:root { + /* Typography */ + --font-sans: "Source Sans Pro", "Lucida Grande", "Lucida Sans Unicode", + "Geneva", "Verdana", sans-serif; + --font-mono: 'SF Mono', 'Monaco', 'Consolas', 'Liberation Mono', monospace; + + /* Python brand colors (theme-independent) */ + --python-blue: #3776ab; + --python-blue-light: #4584bb; + --python-blue-lighter: #5592cc; + --python-gold: #ffd43b; + --python-gold-dark: #ffcd02; + --python-gold-light: #ffdc5c; + + /* Heat palette - defined per theme below */ + + /* Layout */ + --sidebar-width: 280px; + --sidebar-collapsed: 44px; + --topbar-height: 56px; + --statusbar-height: 32px; + + /* Border radius */ + --radius-sm: 4px; + --radius-md: 8px; + --radius-lg: 12px; + + /* Transitions */ + --transition-fast: 0.15s ease; + --transition-normal: 0.25s ease; + --transition-slow: 0.3s ease; +} + +/* Light theme (default) */ +:root, [data-theme="light"] { + --bg-primary: #ffffff; + --bg-secondary: #f8f9fa; + --bg-tertiary: #e9ecef; + --border: #e9ecef; + --border-subtle: #f0f2f5; + + --text-primary: #2e3338; + --text-secondary: #5a6c7d; + --text-muted: #6f767e; + + --accent: #3776ab; + --accent-hover: #2d5aa0; + --accent-glow: rgba(55, 118, 171, 0.15); + + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.08); + --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.1); + --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.15); + + --header-gradient: linear-gradient(135deg, #3776ab 0%, #4584bb 100%); + + /* Light mode heat palette - blue to yellow to orange to red (cold to hot) */ + --heat-1: #7ba3d1; + --heat-2: #a8d0ef; + --heat-3: #d6e9f8; + --heat-4: #ffe6a8; + --heat-5: #ffd43b; + --heat-6: #ffb84d; + --heat-7: #ff9966; + --heat-8: #ff6347; + + /* Code view specific */ + --code-bg: #ffffff; + --code-bg-line: #f8f9fa; + --code-border: #e9ecef; + --code-text: #2e3338; + --code-text-muted: #8b949e; + --code-accent: #3776ab; + + /* Navigation colors */ + --nav-caller: #2563eb; + --nav-caller-hover: #1d4ed8; + --nav-callee: #dc2626; + --nav-callee-hover: #b91c1c; + + /* Specialization status colors */ + --spec-high: #4caf50; + --spec-high-text: #2e7d32; + --spec-high-bg: rgba(76, 175, 80, 0.15); + --spec-medium: #ff9800; + --spec-medium-text: #e65100; + --spec-medium-bg: rgba(255, 152, 0, 0.15); + --spec-low: #9e9e9e; + --spec-low-text: #616161; + --spec-low-bg: rgba(158, 158, 158, 0.15); + + /* Heatmap span highlighting colors */ + --span-hot-base: 255, 100, 50; + --span-cold-base: 150, 150, 150; + + /* Summary card colors - optimized for 4.5:1 contrast on light bg */ + --card-blue: 44, 102, 149; + --card-green: 26, 116, 49; + --card-yellow: 134, 100, 4; + --card-purple: 102, 57, 166; + --card-red: 180, 40, 50; + --card-orange: 166, 90, 0; +} + +/* Dark theme */ +[data-theme="dark"] { + --bg-primary: #0d1117; + --bg-secondary: #161b22; + --bg-tertiary: #21262d; + --border: #30363d; + --border-subtle: #21262d; + + --text-primary: #e6edf3; + --text-secondary: #8b949e; + --text-muted: #757e8a; + + --accent: #58a6ff; + --accent-hover: #79b8ff; + --accent-glow: rgba(88, 166, 255, 0.15); + + --shadow-sm: 0 1px 3px rgba(0, 0, 0, 0.3); + --shadow-md: 0 4px 12px rgba(0, 0, 0, 0.4); + --shadow-lg: 0 8px 24px rgba(0, 0, 0, 0.5); + + --header-gradient: linear-gradient(135deg, #21262d 0%, #30363d 100%); + + /* Dark mode heat palette - cool to warm gradient for visualization */ + --heat-1: rgba(90, 123, 167, 1); + --heat-2: rgba(106, 148, 168, 1); + --heat-3: rgba(122, 172, 172, 1); + --heat-4: rgba(142, 196, 152, 1); + --heat-5: rgba(168, 216, 136, 1); + --heat-6: rgba(200, 222, 122, 1); + --heat-7: rgba(244, 212, 93, 1); + --heat-8: rgba(255, 122, 69, 1); + + /* Code view specific - dark mode */ + --code-bg: #0d1117; + --code-bg-line: #161b22; + --code-border: #30363d; + --code-text: #e6edf3; + --code-text-muted: #6e7681; + --code-accent: #58a6ff; + + /* Navigation colors - dark theme friendly */ + --nav-caller: #58a6ff; + --nav-caller-hover: #4184e4; + --nav-callee: #f87171; + --nav-callee-hover: #e53e3e; + + /* Specialization status colors - dark theme */ + --spec-high: #81c784; + --spec-high-text: #81c784; + --spec-high-bg: rgba(129, 199, 132, 0.2); + --spec-medium: #ffb74d; + --spec-medium-text: #ffb74d; + --spec-medium-bg: rgba(255, 183, 77, 0.2); + --spec-low: #bdbdbd; + --spec-low-text: #9e9e9e; + --spec-low-bg: rgba(189, 189, 189, 0.15); + + /* Heatmap span highlighting colors - dark theme */ + --span-hot-base: 255, 107, 53; + --span-cold-base: 189, 189, 189; + + /* Summary card colors - optimized for 4.5:1 contrast on dark bg */ + --card-blue: 88, 166, 255; + --card-green: 63, 185, 80; + --card-yellow: 210, 153, 34; + --card-purple: 163, 113, 247; + --card-red: 248, 113, 113; + --card-orange: 251, 146, 60; +} + +/* -------------------------------------------------------------------------- + Base Styles + -------------------------------------------------------------------------- */ + +*, *::before, *::after { + box-sizing: border-box; +} + +html, body { + margin: 0; + padding: 0; +} + +body { + font-family: var(--font-sans); + font-size: 14px; + line-height: 1.6; + color: var(--text-primary); + background: var(--bg-primary); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + transition: background var(--transition-normal), color var(--transition-normal); +} + +/* -------------------------------------------------------------------------- + Layout Structure + -------------------------------------------------------------------------- */ + +.app-layout { + display: flex; + flex-direction: column; +} + +/* -------------------------------------------------------------------------- + Top Bar + -------------------------------------------------------------------------- */ + +.top-bar { + height: var(--topbar-height); + background: var(--header-gradient); + display: flex; + align-items: center; + padding: 0 16px; + gap: 16px; + flex-shrink: 0; + box-shadow: 0 2px 10px rgba(55, 118, 171, 0.25); + border-bottom: 2px solid var(--python-gold); +} + +/* Brand / Logo */ +.brand { + display: flex; + align-items: center; + gap: 12px; + color: white; + text-decoration: none; + flex-shrink: 0; +} + +.brand-logo { + display: flex; + align-items: center; + justify-content: center; + width: 48px; + height: 40px; + flex-shrink: 0; +} + +/* Style the inlined SVG/img inside brand-logo */ +.brand-logo svg, +.brand-logo img { + width: 48px; + height: 40px; + display: block; + object-fit: contain; + filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.2)); +} + +.brand-info { + display: flex; + flex-direction: column; + line-height: 1.15; +} + +.brand-text { + font-family: var(--font-sans); + font-weight: 700; + font-size: 16px; + letter-spacing: -0.3px; + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.15); + color: inherit; + text-decoration: none; +} + +.brand-subtitle { + font-weight: 500; + font-size: 10px; + opacity: 0.9; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.brand-divider { + width: 1px; + height: 16px; + background: rgba(255, 255, 255, 0.3); +} + +/* Toolbar */ +.toolbar { + display: flex; + align-items: center; + gap: 6px; + margin-left: auto; +} + +.toolbar-btn { + display: flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + padding: 0; + font-size: 15px; + color: white; + background: rgba(255, 255, 255, 0.12); + border: 1px solid rgba(255, 255, 255, 0.18); + border-radius: 6px; + cursor: pointer; + text-decoration: none; + transition: all var(--transition-fast); +} + +.toolbar-btn:hover { + background: rgba(255, 255, 255, 0.22); + border-color: rgba(255, 255, 255, 0.35); +} + +.toolbar-btn:active { + transform: scale(0.95); +} + +/* -------------------------------------------------------------------------- + Status Bar + -------------------------------------------------------------------------- */ + +.status-bar { + height: var(--statusbar-height); + background: var(--bg-secondary); + border-top: 1px solid var(--border); + display: flex; + align-items: center; + padding: 0 16px; + gap: 16px; + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-secondary); + flex-shrink: 0; +} + +.status-item { + display: flex; + align-items: center; + gap: 5px; +} + +.status-item::before { + content: ''; + width: 4px; + height: 4px; + background: var(--python-gold); + border-radius: 50%; +} + +.status-item:first-child::before { + display: none; +} + +.status-label { + color: var(--text-muted); +} + +.status-value { + color: var(--text-primary); + font-weight: 500; +} + +.status-value.accent { + color: var(--accent); + font-weight: 600; +} + +/* -------------------------------------------------------------------------- + Animations + -------------------------------------------------------------------------- */ + +@keyframes fadeIn { + from { opacity: 0; } + to { opacity: 1; } +} + +@keyframes slideUp { + from { + opacity: 0; + transform: translateY(12px); + } + to { + opacity: 1; + transform: translateY(0); + } +} + +@keyframes shimmer { + 0% { left: -100%; } + 100% { left: 100%; } +} + +/* -------------------------------------------------------------------------- + Focus States (Accessibility) + -------------------------------------------------------------------------- */ + +button:focus-visible, +select:focus-visible, +input:focus-visible, +.toggle-switch:focus-visible, +a.toolbar-btn:focus-visible { + outline: 2px solid var(--python-gold); + outline-offset: 2px; +} + +/* -------------------------------------------------------------------------- + Shared Responsive + -------------------------------------------------------------------------- */ + +@media (max-width: 900px) { + .brand-subtitle { + display: none; + } +} + +@media (max-width: 600px) { + .toolbar-btn:not(.theme-toggle) { + display: none; + } +} + +/* -------------------------------------------------------------------------- + Toggle Switch + -------------------------------------------------------------------------- */ + +.toggle-switch { + display: inline-flex; + align-items: center; + gap: 8px; + cursor: pointer; + user-select: none; + font-family: var(--font-sans); + transition: opacity var(--transition-fast); + flex-shrink: 0; +} + +.toggle-switch:hover { + opacity: 0.85; +} + +.toggle-switch .toggle-label { + font-size: 11px; + font-weight: 500; + color: var(--text-muted); + transition: color var(--transition-fast); + white-space: nowrap; + display: inline-flex; + flex-direction: column; +} + +.toggle-switch .toggle-label.active { + color: var(--text-primary); + font-weight: 600; +} + +/* Reserve space for bold text to prevent layout shift on toggle */ +.toggle-switch .toggle-label::after { + content: attr(data-text); + font-weight: 600; + height: 0; + visibility: hidden; +} + +.toggle-switch.disabled { + opacity: 0.4; + pointer-events: none; + cursor: not-allowed; +} + +.toggle-track { + position: relative; + width: 36px; + height: 20px; + background: var(--bg-tertiary); + border: 2px solid var(--border); + border-radius: 12px; + transition: all var(--transition-fast); + box-shadow: inset var(--shadow-sm); +} + +.toggle-track:hover { + border-color: var(--text-muted); +} + +.toggle-track.on { + background: var(--accent); + border-color: var(--accent); + box-shadow: 0 0 8px var(--accent-glow); +} + +.toggle-track::after { + content: ''; + position: absolute; + top: 1px; + left: 1px; + width: 14px; + height: 14px; + background: white; + border-radius: 50%; + box-shadow: var(--shadow-sm); + transition: all var(--transition-fast); +} + +.toggle-track.on::after { + transform: translateX(16px); + box-shadow: var(--shadow-md); +} diff --git a/Lib/profiling/sampling/_shared_assets/base.js b/Lib/profiling/sampling/_shared_assets/base.js new file mode 100644 index 00000000000..da8b5851c85 --- /dev/null +++ b/Lib/profiling/sampling/_shared_assets/base.js @@ -0,0 +1,58 @@ +// Tachyon Profiler - Shared JavaScript +// Common utilities shared between flamegraph and heatmap views + +// ============================================================================ +// Theme Support +// ============================================================================ + +// Storage key for theme preference +const THEME_STORAGE_KEY = 'tachyon-theme'; + +// Get the preferred theme from localStorage or system preference +function getPreferredTheme() { + const saved = localStorage.getItem(THEME_STORAGE_KEY); + if (saved) return saved; + return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; +} + +// Apply theme and update UI +function applyTheme(theme) { + document.documentElement.setAttribute('data-theme', theme); + const btn = document.getElementById('theme-btn'); + if (btn) { + const moonIcon = btn.querySelector('.icon-moon'); + const sunIcon = btn.querySelector('.icon-sun'); + if (moonIcon) moonIcon.style.display = theme === 'dark' ? 'none' : ''; + if (sunIcon) sunIcon.style.display = theme === 'dark' ? '' : 'none'; + } +} + +// Toggle theme and save preference. Returns the new theme. +function toggleAndSaveTheme() { + const current = document.documentElement.getAttribute('data-theme') || 'light'; + const next = current === 'light' ? 'dark' : 'light'; + applyTheme(next); + localStorage.setItem(THEME_STORAGE_KEY, next); + return next; +} + +// ============================================================================ +// Toggle Switch UI +// ============================================================================ + +function updateToggleUI(toggleId, isOn) { + const toggle = document.getElementById(toggleId); + if (toggle) { + const track = toggle.querySelector('.toggle-track'); + const labels = toggle.querySelectorAll('.toggle-label'); + if (isOn) { + track.classList.add('on'); + labels[0].classList.remove('active'); + labels[1].classList.add('active'); + } else { + track.classList.remove('on'); + labels[0].classList.add('active'); + labels[1].classList.remove('active'); + } + } +} diff --git a/Lib/profiling/sampling/_sync_coordinator.py b/Lib/profiling/sampling/_sync_coordinator.py new file mode 100644 index 00000000000..bb0ee5b5317 --- /dev/null +++ b/Lib/profiling/sampling/_sync_coordinator.py @@ -0,0 +1,261 @@ +""" +Internal synchronization coordinator for the sample profiler. + +This module is used internally by the sample profiler to coordinate +the startup of target processes. It should not be called directly by users. +""" + +import importlib.util +import os +import sys +import socket +import runpy +import time +import types +from typing import List, NoReturn + + +class CoordinatorError(Exception): + """Base exception for coordinator errors.""" + pass + + +class ArgumentError(CoordinatorError): + """Raised when invalid arguments are provided.""" + pass + + +class SyncError(CoordinatorError): + """Raised when synchronization with profiler fails.""" + pass + + +class TargetError(CoordinatorError): + """Raised when target execution fails.""" + pass + + +def _validate_arguments(args: List[str]) -> tuple[int, str, List[str]]: + """ + Validate and parse command line arguments. + + Args: + args: Command line arguments including script name + + Returns: + Tuple of (sync_port, working_directory, target_args) + + Raises: + ArgumentError: If arguments are invalid + """ + if len(args) < 4: + raise ArgumentError( + "Insufficient arguments. Expected: [args...]" + ) + + try: + sync_port = int(args[1]) + if not (1 <= sync_port <= 65535): + raise ValueError("Port out of range") + except ValueError as e: + raise ArgumentError(f"Invalid sync port '{args[1]}': {e}") from e + + cwd = args[2] + if not os.path.isdir(cwd): + raise ArgumentError(f"Working directory does not exist: {cwd}") + + target_args = args[3:] + if not target_args: + raise ArgumentError("No target specified") + + return sync_port, cwd, target_args + + +# Constants for socket communication +_MAX_RETRIES = 3 +_INITIAL_RETRY_DELAY_SEC = 0.1 +_SOCKET_TIMEOUT_SEC = 2.0 +_READY_MESSAGE = b"ready" + + +def _signal_readiness(sync_port: int) -> None: + """ + Signal readiness to the profiler via TCP socket. + + Args: + sync_port: Port number where profiler is listening + + Raises: + SyncError: If unable to signal readiness + """ + last_error = None + + for attempt in range(_MAX_RETRIES): + try: + # Use context manager for automatic cleanup + with socket.create_connection(("127.0.0.1", sync_port), timeout=_SOCKET_TIMEOUT_SEC) as sock: + sock.send(_READY_MESSAGE) + return + except (socket.error, OSError) as e: + last_error = e + if attempt < _MAX_RETRIES - 1: + # Exponential backoff before retry + time.sleep(_INITIAL_RETRY_DELAY_SEC * (2 ** attempt)) + + # If we get here, all retries failed + raise SyncError(f"Failed to signal readiness after {_MAX_RETRIES} attempts: {last_error}") from last_error + + +def _setup_environment(cwd: str) -> None: + """ + Set up the execution environment. + + Args: + cwd: Working directory to change to + + Raises: + TargetError: If unable to set up environment + """ + try: + os.chdir(cwd) + except OSError as e: + raise TargetError(f"Failed to change to directory {cwd}: {e}") from e + + # Add current directory to sys.path if not present (for module imports) + if cwd not in sys.path: + sys.path.insert(0, cwd) + + +def _execute_module(module_name: str, module_args: List[str]) -> None: + """ + Execute a Python module. + + Args: + module_name: Name of the module to execute + module_args: Arguments to pass to the module + + Raises: + TargetError: If module cannot be found + """ + # Replace sys.argv to match how Python normally runs modules + # When running 'python -m module args', sys.argv is ["__main__.py", "args"] + sys.argv = ["__main__.py"] + module_args + + try: + runpy.run_module(module_name, run_name="__main__", alter_sys=True) + except ImportError as e: + raise TargetError(f"Module '{module_name}' not found: {e}") from e + # Let other exceptions (including SystemExit) propagate naturally + # so Python prints the full traceback to stderr + + +def _execute_script(script_path: str, script_args: List[str], cwd: str) -> None: + """ + Execute a Python script. + + Args: + script_path: Path to the script to execute + script_args: Arguments to pass to the script + cwd: Current working directory for path resolution + + Raises: + TargetError: If script execution fails + """ + # Make script path absolute if it isn't already + if not os.path.isabs(script_path): + script_path = os.path.join(cwd, script_path) + + if not os.path.isfile(script_path): + raise TargetError(f"Script not found: {script_path}") + + script_dir = os.path.dirname(os.path.realpath(script_path)) + if script_dir in sys.path: + sys.path.remove(script_dir) + sys.path.insert(0, script_dir) + + # Replace sys.argv to match original script call + sys.argv = [script_path] + script_args + + try: + with open(script_path, 'rb') as f: + source_code = f.read() + + except FileNotFoundError as e: + raise TargetError(f"Script file not found: {script_path}") from e + except PermissionError as e: + raise TargetError(f"Permission denied reading script: {script_path}") from e + + main_module = types.ModuleType("__main__") + main_module.__file__ = script_path + main_module.__builtins__ = __builtins__ + # gh-140729: Create a __mp_main__ module to allow pickling + sys.modules['__main__'] = sys.modules['__mp_main__'] = main_module + + try: + code = compile(source_code, script_path, 'exec', module='__main__') + except SyntaxError as e: + raise TargetError(f"Syntax error in script {script_path}: {e}") from e + + # Execute the script - let exceptions propagate naturally so Python + # prints the full traceback to stderr + exec(code, main_module.__dict__) + + +def main() -> NoReturn: + """ + Main coordinator function. + + This function coordinates the startup of a target Python process + with the sample profiler by signaling when the process is ready + to be profiled. + """ + # Phase 1: Parse arguments and set up environment + # Errors here are coordinator errors, not script errors + try: + # Parse and validate arguments + sync_port, cwd, target_args = _validate_arguments(sys.argv) + + # Set up execution environment + _setup_environment(cwd) + + # Determine execution type and validate target exists + is_module = target_args[0] == "-m" + if is_module: + if len(target_args) < 2: + raise ArgumentError("Module name required after -m") + module_name = target_args[1] + module_args = target_args[2:] + + if importlib.util.find_spec(module_name) is None: + raise TargetError(f"Module not found: {module_name}") + else: + script_path = target_args[0] + script_args = target_args[1:] + # Match the path resolution logic in _execute_script + check_path = script_path if os.path.isabs(script_path) else os.path.join(cwd, script_path) + if not os.path.isfile(check_path): + raise TargetError(f"Script not found: {script_path}") + + # Signal readiness to profiler + _signal_readiness(sync_port) + + except CoordinatorError as e: + print(f"Profiler coordinator error: {e}", file=sys.stderr) + sys.exit(1) + except KeyboardInterrupt: + print("Interrupted", file=sys.stderr) + sys.exit(1) + + # Phase 2: Execute the target script/module + # Let exceptions propagate naturally so Python prints full tracebacks + if is_module: + _execute_module(module_name, module_args) + else: + _execute_script(script_path, script_args, cwd) + + # Normal exit + sys.exit(0) + + +if __name__ == "__main__": + main() diff --git a/Lib/profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph-tooltip.min.js b/Lib/profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph-tooltip.min.js new file mode 100644 index 00000000000..7468437093b --- /dev/null +++ b/Lib/profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph-tooltip.min.js @@ -0,0 +1 @@ +!function(t,n){"object"==typeof exports&&"object"==typeof module?module.exports=n():"function"==typeof define&&define.amd?define([],n):"object"==typeof exports?exports.flamegraph=n():(t.flamegraph=t.flamegraph||{},t.flamegraph.tooltip=n())}(self,(function(){return(()=>{"use strict";var t={d:(n,e)=>{for(var r in e)t.o(e,r)&&!t.o(n,r)&&Object.defineProperty(n,r,{enumerable:!0,get:e[r]})},o:(t,n)=>Object.prototype.hasOwnProperty.call(t,n),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},n={};function e(){}function r(t){return null==t?e:function(){return this.querySelector(t)}}function i(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function o(){return[]}function u(t){return null==t?o:function(){return this.querySelectorAll(t)}}function a(t){return function(){return this.matches(t)}}function s(t){return function(n){return n.matches(t)}}t.r(n),t.d(n,{defaultFlamegraphTooltip:()=>Ae});var l=Array.prototype.find;function c(){return this.firstElementChild}var f=Array.prototype.filter;function h(){return Array.from(this.children)}function p(t){return new Array(t.length)}function d(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function y(t){return function(){return t}}function v(t,n,e,r,i,o){for(var u,a=0,s=n.length,l=o.length;an?1:t>=n?0:NaN}d.prototype={constructor:d,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,n){return this._parent.insertBefore(t,n)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var b="http://www.w3.org/1999/xhtml";const x={svg:"http://www.w3.org/2000/svg",xhtml:b,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function A(t){var n=t+="",e=n.indexOf(":");return e>=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),x.hasOwnProperty(n)?{space:x[n],local:t}:t}function N(t){return function(){this.removeAttribute(t)}}function k(t){return function(){this.removeAttributeNS(t.space,t.local)}}function M(t,n){return function(){this.setAttribute(t,n)}}function E(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function S(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function C(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function P(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function O(t){return function(){this.style.removeProperty(t)}}function q(t,n,e){return function(){this.style.setProperty(t,n,e)}}function j(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function T(t,n){return t.style.getPropertyValue(n)||P(t).getComputedStyle(t,null).getPropertyValue(n)}function X(t){return function(){delete this[t]}}function R(t,n){return function(){this[t]=n}}function I(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function L(t){return t.trim().split(/^|\s+/)}function D(t){return t.classList||new H(t)}function H(t){this._node=t,this._names=L(t.getAttribute("class")||"")}function Y(t,n){for(var e=D(t),r=-1,i=n.length;++r=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}function st(t){return function(){var n=this.__on;if(n){for(var e,r=0,i=-1,o=n.length;r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var pt=[null];function dt(t,n){this._groups=t,this._parents=n}function yt(){return new dt([[document.documentElement]],pt)}dt.prototype=yt.prototype={constructor:dt,select:function(t){"function"!=typeof t&&(t=r(t));for(var n=this._groups,e=n.length,i=new Array(e),o=0;o=M&&(M=k+1);!(N=b[M])&&++M=0;)(r=i[o])&&(u&&4^r.compareDocumentPosition(u)&&u.parentNode.insertBefore(r,u),u=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=w);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?O:"function"==typeof n?j:q)(t,n,null==e?"":e)):T(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?X:"function"==typeof n?I:R)(t,n)):this.node()[t]},classed:function(t,n){var e=L(t+"");if(arguments.length<2){for(var r=D(this.node()),i=-1,o=e.length;++i{}};function _t(){for(var t,n=0,e=arguments.length,r={};n=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}}))}function bt(t,n){for(var e,r=0,i=t.length;r0)for(var e,r,i=new Array(e),o=0;o=0&&n._call.call(void 0,t),n=n._next;--Mt}()}finally{Mt=0,function(){var t,n,e=Nt,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:Nt=n);kt=t,Ht(r)}(),Pt=0}}function Dt(){var t=qt.now(),n=t-Ct;n>1e3&&(Ot-=n,Ct=t)}function Ht(t){Mt||(Et&&(Et=clearTimeout(Et)),t-Pt>24?(t<1/0&&(Et=setTimeout(Lt,t-qt.now()-Ot)),St&&(St=clearInterval(St))):(St||(Ct=qt.now(),St=setInterval(Dt,1e3)),Mt=1,jt(Lt)))}function Yt(t,n,e){var r=new Rt;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Rt.prototype=It.prototype={constructor:Rt,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?Tt():+e)+(null==n?0:+n),this._next||kt===this||(kt?kt._next=this:Nt=this,kt=this),this._call=t,this._time=e,Ht()},stop:function(){this._call&&(this._call=null,this._time=1/0,Ht())}};var Bt=At("start","end","cancel","interrupt"),$t=[];function Vt(t,n,e,r,i,o){var u=t.__transition;if(u){if(e in u)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=1,e.timer.restart(u,e.delay,e.time),e.delay<=t&&u(t-e.delay)}function u(o){var l,c,f,h;if(1!==e.state)return s();for(l in i)if((h=i[l]).name===e.name){if(3===h.state)return Yt(u);4===h.state?(h.state=6,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[l]):+l0)throw new Error("too late; already scheduled");return e}function Ut(t,n){var e=Ft(t,n);if(e.state>3)throw new Error("too late; already running");return e}function Ft(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Kt(t,n){return t=+t,n=+n,function(e){return t*(1-e)+n*e}}var Wt,Gt=180/Math.PI,Jt={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function Qt(t,n,e,r,i,o){var u,a,s;return(u=Math.sqrt(t*t+n*n))&&(t/=u,n/=u),(s=t*e+n*r)&&(e-=t*s,r-=n*s),(a=Math.sqrt(e*e+r*r))&&(e/=a,r/=a,s/=a),t*r180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:Kt(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,u.rotate,a,s),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:Kt(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,u.skewX,a,s),function(t,n,e,r,o,u){if(t!==e||n!==r){var a=o.push(i(o)+"scale(",null,",",null,")");u.push({i:a-4,x:Kt(t,e)},{i:a-2,x:Kt(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,u.scaleX,u.scaleY,a,s),o=u=null,function(t){for(var n,e=-1,r=s.length;++e>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?Mn(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?Mn(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=yn.exec(t))?new Cn(n[1],n[2],n[3],1):(n=vn.exec(t))?new Cn(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=gn.exec(t))?Mn(n[1],n[2],n[3],n[4]):(n=_n.exec(t))?Mn(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=mn.exec(t))?jn(n[1],n[2]/100,n[3]/100,1):(n=wn.exec(t))?jn(n[1],n[2]/100,n[3]/100,n[4]):bn.hasOwnProperty(t)?kn(bn[t]):"transparent"===t?new Cn(NaN,NaN,NaN,0):null}function kn(t){return new Cn(t>>16&255,t>>8&255,255&t,1)}function Mn(t,n,e,r){return r<=0&&(t=n=e=NaN),new Cn(t,n,e,r)}function En(t){return t instanceof sn||(t=Nn(t)),t?new Cn((t=t.rgb()).r,t.g,t.b,t.opacity):new Cn}function Sn(t,n,e,r){return 1===arguments.length?En(t):new Cn(t,n,e,null==r?1:r)}function Cn(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Pn(){return"#"+qn(this.r)+qn(this.g)+qn(this.b)}function On(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function qn(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function jn(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Xn(t,n,e,r)}function Tn(t){if(t instanceof Xn)return new Xn(t.h,t.s,t.l,t.opacity);if(t instanceof sn||(t=Nn(t)),!t)return new Xn;if(t instanceof Xn)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),u=NaN,a=o-i,s=(o+i)/2;return a?(u=n===o?(e-r)/a+6*(e0&&s<1?0:u,new Xn(u,a,s,t.opacity)}function Xn(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Rn(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}function In(t,n,e,r,i){var o=t*t,u=o*t;return((1-3*t+3*o-u)*n+(4-6*o+3*u)*e+(1+3*t+3*o-3*u)*r+u*i)/6}un(sn,Nn,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:xn,formatHex:xn,formatHsl:function(){return Tn(this).formatHsl()},formatRgb:An,toString:An}),un(Cn,Sn,an(sn,{brighter:function(t){return t=null==t?cn:Math.pow(cn,t),new Cn(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?ln:Math.pow(ln,t),new Cn(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Pn,formatHex:Pn,formatRgb:On,toString:On})),un(Xn,(function(t,n,e,r){return 1===arguments.length?Tn(t):new Xn(t,n,e,null==r?1:r)}),an(sn,{brighter:function(t){return t=null==t?cn:Math.pow(cn,t),new Xn(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?ln:Math.pow(ln,t),new Xn(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new Cn(Rn(t>=240?t-240:t+120,i,r),Rn(t,i,r),Rn(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const Ln=t=>()=>t;function Dn(t,n){return function(e){return t+e*n}}function Hn(t){return 1==(t=+t)?Yn:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):Ln(isNaN(n)?e:n)}}function Yn(t,n){var e=n-t;return e?Dn(t,e):Ln(isNaN(t)?n:t)}const Bn=function t(n){var e=Hn(n);function r(t,n){var r=e((t=Sn(t)).r,(n=Sn(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),u=Yn(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=u(n),t+""}}return r.gamma=t,r}(1);function $n(t){return function(n){var e,r,i=n.length,o=new Array(i),u=new Array(i),a=new Array(i);for(e=0;e=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],u=r>0?t[r-1]:2*i-o,a=ro&&(i=n.slice(o,i),a[u]?a[u]+=i:a[++u]=i),(e=e[0])===(r=r[0])?a[u]?a[u]+=r:a[++u]=r:(a[++u]=null,s.push({i:u,x:Kt(e,r)})),o=zn.lastIndex;return o=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?zt:Ut;return function(){var u=o(this,t),a=u.on;a!==r&&(i=(r=a).copy()).on(n,e),u.on=i}}var ce=vt.prototype.constructor;function fe(t){return function(){this.style.removeProperty(t)}}function he(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}function pe(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&he(t,o,e)),r}return o._value=n,o}function de(t){return function(n){this.textContent=t.call(this,n)}}function ye(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&de(r)),n}return r._value=t,r}var ve=0;function ge(t,n,e,r){this._groups=t,this._parents=n,this._name=e,this._id=r}function _e(){return++ve}var me=vt.prototype;ge.prototype=function(t){return vt().transition(t)}.prototype={constructor:ge,select:function(t){var n=this._name,e=this._id;"function"!=typeof t&&(t=r(t));for(var i=this._groups,o=i.length,u=new Array(o),a=0;a2&&e.state<5,e.state=6,e.timer.stop(),e.on.call(r?"interrupt":"cancel",t,t.__data__,e.index,e.group),delete o[i]):u=!1;u&&delete t.__transition}}(this,t)}))},vt.prototype.transition=function(t){var n,e;t instanceof ge?(n=t._id,t=t._name):(n=_e(),(e=we).time=Tt(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,o=0;o{"use strict";var t={d:(n,e)=>{for(var r in e)t.o(e,r)&&!t.o(n,r)&&Object.defineProperty(n,r,{enumerable:!0,get:e[r]})},o:(t,n)=>Object.prototype.hasOwnProperty.call(t,n)},n={};function e(){}function r(t){return null==t?e:function(){return this.querySelector(t)}}function i(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function o(){return[]}function u(t){return null==t?o:function(){return this.querySelectorAll(t)}}function a(t){return function(){return this.matches(t)}}function l(t){return function(n){return n.matches(t)}}t.d(n,{default:()=>xr});var s=Array.prototype.find;function c(){return this.firstElementChild}var h=Array.prototype.filter;function f(){return Array.from(this.children)}function p(t){return new Array(t.length)}function d(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function g(t){return function(){return t}}function v(t,n,e,r,i,o){for(var u,a=0,l=n.length,s=o.length;an?1:t>=n?0:NaN}d.prototype={constructor:d,appendChild:function(t){return this._parent.insertBefore(t,this._next)},insertBefore:function(t,n){return this._parent.insertBefore(t,n)},querySelector:function(t){return this._parent.querySelector(t)},querySelectorAll:function(t){return this._parent.querySelectorAll(t)}};var b="http://www.w3.org/1999/xhtml";const x={svg:"http://www.w3.org/2000/svg",xhtml:b,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function M(t){var n=t+="",e=n.indexOf(":");return e>=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),x.hasOwnProperty(n)?{space:x[n],local:t}:t}function A(t){return function(){this.removeAttribute(t)}}function N(t){return function(){this.removeAttributeNS(t.space,t.local)}}function k(t,n){return function(){this.setAttribute(t,n)}}function E(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function S(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function C(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function j(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function q(t){return function(){this.style.removeProperty(t)}}function O(t,n,e){return function(){this.style.setProperty(t,n,e)}}function P(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function H(t,n){return t.style.getPropertyValue(n)||j(t).getComputedStyle(t,null).getPropertyValue(n)}function L(t){return function(){delete this[t]}}function T(t,n){return function(){this[t]=n}}function D(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function B(t){return t.trim().split(/^|\s+/)}function X(t){return t.classList||new z(t)}function z(t){this._node=t,this._names=B(t.getAttribute("class")||"")}function R(t,n){for(var e=X(t),r=-1,i=n.length;++r=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}function lt(t){return function(){var n=this.__on;if(n){for(var e,r=0,i=-1,o=n.length;r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var pt=[null];function dt(t,n){this._groups=t,this._parents=n}function gt(){return new dt([[document.documentElement]],pt)}dt.prototype=gt.prototype={constructor:dt,select:function(t){"function"!=typeof t&&(t=r(t));for(var n=this._groups,e=n.length,i=new Array(e),o=0;o=k&&(k=N+1);!(A=b[k])&&++k=0;)(r=i[o])&&(u&&4^r.compareDocumentPosition(u)&&u.parentNode.insertBefore(r,u),u=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=_);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?q:"function"==typeof n?P:O)(t,n,null==e?"":e)):H(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?L:"function"==typeof n?D:T)(t,n)):this.node()[t]},classed:function(t,n){var e=B(t+"");if(arguments.length<2){for(var r=X(this.node()),i=-1,o=e.length;++i1?r[0]+r.slice(2):r,+t.slice(e+1)]}function wt(t){return(t=mt(Math.abs(t)))?t[1]:NaN}var _t,bt=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function xt(t){if(!(n=bt.exec(t)))throw new Error("invalid format: "+t);var n;return new Mt({fill:n[1],align:n[2],sign:n[3],symbol:n[4],zero:n[5],width:n[6],comma:n[7],precision:n[8]&&n[8].slice(1),trim:n[9],type:n[10]})}function Mt(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function At(t,n){var e=mt(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}xt.prototype=Mt.prototype,Mt.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};const Nt={"%":(t,n)=>(100*t).toFixed(n),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,n)=>t.toExponential(n),f:(t,n)=>t.toFixed(n),g:(t,n)=>t.toPrecision(n),o:t=>Math.round(t).toString(8),p:(t,n)=>At(100*t,n),r:At,s:function(t,n){var e=mt(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(_t=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,u=r.length;return o===u?r:o>u?r+new Array(o-u+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+mt(t,Math.max(0,n+o-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function kt(t){return t}var Et,St,Ct,jt=Array.prototype.map,qt=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Ot(t){var n,e,r=void 0===t.grouping||void 0===t.thousands?kt:(n=jt.call(t.grouping,Number),e=t.thousands+"",function(t,r){for(var i=t.length,o=[],u=0,a=n[0],l=0;i>0&&a>0&&(l+a+1>r&&(a=Math.max(1,r-l)),o.push(t.substring(i-=a,i+a)),!((l+=a+1)>r));)a=n[u=(u+1)%n.length];return o.reverse().join(e)}),i=void 0===t.currency?"":t.currency[0]+"",o=void 0===t.currency?"":t.currency[1]+"",u=void 0===t.decimal?".":t.decimal+"",a=void 0===t.numerals?kt:function(t){return function(n){return n.replace(/[0-9]/g,(function(n){return t[+n]}))}}(jt.call(t.numerals,String)),l=void 0===t.percent?"%":t.percent+"",s=void 0===t.minus?"−":t.minus+"",c=void 0===t.nan?"NaN":t.nan+"";function h(t){var n=(t=xt(t)).fill,e=t.align,h=t.sign,f=t.symbol,p=t.zero,d=t.width,g=t.comma,v=t.precision,y=t.trim,m=t.type;"n"===m?(g=!0,m="g"):Nt[m]||(void 0===v&&(v=12),y=!0,m="g"),(p||"0"===n&&"="===e)&&(p=!0,n="0",e="=");var w="$"===f?i:"#"===f&&/[boxX]/.test(m)?"0"+m.toLowerCase():"",_="$"===f?o:/[%p]/.test(m)?l:"",b=Nt[m],x=/[defgprs%]/.test(m);function M(t){var i,o,l,f=w,M=_;if("c"===m)M=b(t)+M,t="";else{var A=(t=+t)<0||1/t<0;if(t=isNaN(t)?c:b(Math.abs(t),v),y&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),A&&0==+t&&"+"!==h&&(A=!1),f=(A?"("===h?h:s:"-"===h||"("===h?"":h)+f,M=("s"===m?qt[8+_t/3]:"")+M+(A&&"("===h?")":""),x)for(i=-1,o=t.length;++i(l=t.charCodeAt(i))||l>57){M=(46===l?u+t.slice(i+1):t.slice(i))+M,t=t.slice(0,i);break}}g&&!p&&(t=r(t,1/0));var N=f.length+t.length+M.length,k=N>1)+f+t+M+k.slice(N);break;default:t=k+f+t+M}return a(t)}return v=void 0===v?6:/[gprs]/.test(m)?Math.max(1,Math.min(21,v)):Math.max(0,Math.min(20,v)),M.toString=function(){return t+""},M}return{format:h,formatPrefix:function(t,n){var e=h(((t=xt(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(wt(n)/3))),i=Math.pow(10,-r),o=qt[8+r/3];return function(t){return e(i*t)+o}}}}function Pt(t,n){return null==t||null==n?NaN:tn?1:t>=n?0:NaN}function Ht(t){t.x0=Math.round(t.x0),t.y0=Math.round(t.y0),t.x1=Math.round(t.x1),t.y1=Math.round(t.y1)}function Lt(){var t=1,n=1,e=0,r=!1;function i(i){var o=i.height+1;return i.x0=i.y0=e,i.x1=t,i.y1=n/o,i.eachBefore(function(t,n){return function(r){r.children&&function(t,n,e,r,i){for(var o,u=t.children,a=-1,l=u.length,s=t.value&&(r-n)/t.value;++a=0;)n+=e[r].value;else n=1;t.value=n}function Dt(t,n){t instanceof Map?(t=[void 0,t],void 0===n&&(n=Xt)):void 0===n&&(n=Bt);for(var e,r,i,o,u,a=new It(t),l=[a];e=l.pop();)if((i=n(e.data))&&(u=(i=Array.from(i)).length))for(e.children=i,o=u-1;o>=0;--o)l.push(r=i[o]=new It(i[o])),r.parent=e,r.depth=e.depth+1;return a.eachBefore(Rt)}function Bt(t){return t.children}function Xt(t){return Array.isArray(t)?t[1]:null}function zt(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function Rt(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function It(t){this.data=t,this.depth=this.height=0,this.parent=null}Et=Ot({thousands:",",grouping:[3],currency:["$",""]}),St=Et.format,Ct=Et.formatPrefix,It.prototype=Dt.prototype={constructor:It,count:function(){return this.eachAfter(Tt)},each:function(t,n){let e=-1;for(const r of this)t.call(n,r,++e,this);return this},eachAfter:function(t,n){for(var e,r,i,o=this,u=[o],a=[],l=-1;o=u.pop();)if(a.push(o),e=o.children)for(r=0,i=e.length;r=0;--r)o.push(e[r]);return this},find:function(t,n){let e=-1;for(const r of this)if(t.call(n,r,++e,this))return r},sum:function(t){return this.eachAfter((function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e}))},sort:function(t){return this.eachBefore((function(n){n.children&&n.children.sort(t)}))},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;t=e.pop(),n=r.pop();for(;t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(n){n.children||t.push(n)})),t},links:function(){var t=this,n=[];return t.each((function(e){e!==t&&n.push({source:e.parent,target:e})})),n},copy:function(){return Dt(this).eachBefore(zt)},[Symbol.iterator]:function*(){var t,n,e,r,i=this,o=[i];do{for(t=o.reverse(),o=[];i=t.pop();)if(yield i,n=i.children)for(e=0,r=n.length;e=0?(o>=$t?10:o>=Vt?5:o>=Yt?2:1)*Math.pow(10,i):-Math.pow(10,-i)/(o>=$t?10:o>=Vt?5:o>=Yt?2:1)}function Ut(t){let n=t,e=t,r=t;function i(t,n,i=0,o=t.length){if(i>>1;r(t[e],n)<0?i=e+1:o=e}while(it(n)-e,e=Pt,r=(n,e)=>Pt(t(n),e)),{left:i,center:function(t,e,r=0,o=t.length){const u=i(t,e,r,o-1);return u>r&&n(t[u-1],e)>-n(t[u],e)?u-1:u},right:function(t,n,i=0,o=t.length){if(i>>1;r(t[e],n)<=0?i=e+1:o=e}while(i>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?mn(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?mn(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=an.exec(t))?new bn(n[1],n[2],n[3],1):(n=ln.exec(t))?new bn(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=sn.exec(t))?mn(n[1],n[2],n[3],n[4]):(n=cn.exec(t))?mn(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=hn.exec(t))?Nn(n[1],n[2]/100,n[3]/100,1):(n=fn.exec(t))?Nn(n[1],n[2]/100,n[3]/100,n[4]):pn.hasOwnProperty(t)?yn(pn[t]):"transparent"===t?new bn(NaN,NaN,NaN,0):null}function yn(t){return new bn(t>>16&255,t>>8&255,255&t,1)}function mn(t,n,e,r){return r<=0&&(t=n=e=NaN),new bn(t,n,e,r)}function wn(t){return t instanceof Qt||(t=vn(t)),t?new bn((t=t.rgb()).r,t.g,t.b,t.opacity):new bn}function _n(t,n,e,r){return 1===arguments.length?wn(t):new bn(t,n,e,null==r?1:r)}function bn(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function xn(){return"#"+An(this.r)+An(this.g)+An(this.b)}function Mn(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"rgb(":"rgba(")+Math.max(0,Math.min(255,Math.round(this.r)||0))+", "+Math.max(0,Math.min(255,Math.round(this.g)||0))+", "+Math.max(0,Math.min(255,Math.round(this.b)||0))+(1===t?")":", "+t+")")}function An(t){return((t=Math.max(0,Math.min(255,Math.round(t)||0)))<16?"0":"")+t.toString(16)}function Nn(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new En(t,n,e,r)}function kn(t){if(t instanceof En)return new En(t.h,t.s,t.l,t.opacity);if(t instanceof Qt||(t=vn(t)),!t)return new En;if(t instanceof En)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),u=NaN,a=o-i,l=(o+i)/2;return a?(u=n===o?(e-r)/a+6*(e0&&l<1?0:u,new En(u,a,l,t.opacity)}function En(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Sn(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}function Cn(t,n,e,r,i){var o=t*t,u=o*t;return((1-3*t+3*o-u)*n+(4-6*o+3*u)*e+(1+3*t+3*o-3*u)*r+u*i)/6}Wt(Qt,vn,{copy:function(t){return Object.assign(new this.constructor,this,t)},displayable:function(){return this.rgb().displayable()},hex:dn,formatHex:dn,formatHsl:function(){return kn(this).formatHsl()},formatRgb:gn,toString:gn}),Wt(bn,_n,Jt(Qt,{brighter:function(t){return t=null==t?nn:Math.pow(nn,t),new bn(this.r*t,this.g*t,this.b*t,this.opacity)},darker:function(t){return t=null==t?tn:Math.pow(tn,t),new bn(this.r*t,this.g*t,this.b*t,this.opacity)},rgb:function(){return this},displayable:function(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:xn,formatHex:xn,formatRgb:Mn,toString:Mn})),Wt(En,(function(t,n,e,r){return 1===arguments.length?kn(t):new En(t,n,e,null==r?1:r)}),Jt(Qt,{brighter:function(t){return t=null==t?nn:Math.pow(nn,t),new En(this.h,this.s,this.l*t,this.opacity)},darker:function(t){return t=null==t?tn:Math.pow(tn,t),new En(this.h,this.s,this.l*t,this.opacity)},rgb:function(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new bn(Sn(t>=240?t-240:t+120,i,r),Sn(t,i,r),Sn(t<120?t+240:t-120,i,r),this.opacity)},displayable:function(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl:function(){var t=this.opacity;return(1===(t=isNaN(t)?1:Math.max(0,Math.min(1,t)))?"hsl(":"hsla(")+(this.h||0)+", "+100*(this.s||0)+"%, "+100*(this.l||0)+"%"+(1===t?")":", "+t+")")}}));const jn=t=>()=>t;function qn(t,n){return function(e){return t+e*n}}function On(t){return 1==(t=+t)?Pn:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):jn(isNaN(n)?e:n)}}function Pn(t,n){var e=n-t;return e?qn(t,e):jn(isNaN(t)?n:t)}const Hn=function t(n){var e=On(n);function r(t,n){var r=e((t=_n(t)).r,(n=_n(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),u=Pn(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=u(n),t+""}}return r.gamma=t,r}(1);function Ln(t){return function(n){var e,r,i=n.length,o=new Array(i),u=new Array(i),a=new Array(i);for(e=0;e=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],u=r>0?t[r-1]:2*i-o,a=ro&&(i=n.slice(o,i),a[u]?a[u]+=i:a[++u]=i),(e=e[0])===(r=r[0])?a[u]?a[u]+=r:a[++u]=r:(a[++u]=null,l.push({i:u,x:Bn(e,r)})),o=Rn.lastIndex;return on&&(e=t,t=n,n=e),s=function(e){return Math.max(t,Math.min(n,e))}),r=l>2?Wn:Kn,i=o=null,h}function h(n){return null==n||isNaN(n=+n)?e:(i||(i=r(u.map(t),a,l)))(t(s(n)))}return h.invert=function(e){return s(n((o||(o=r(a,u.map(t),Bn)))(e)))},h.domain=function(t){return arguments.length?(u=Array.from(t,Fn),c()):u.slice()},h.range=function(t){return arguments.length?(a=Array.from(t),c()):a.slice()},h.rangeRound=function(t){return a=Array.from(t),l=Yn,c()},h.clamp=function(t){return arguments.length?(s=!!t||Zn,c()):s!==Zn},h.interpolate=function(t){return arguments.length?(l=t,c()):l},h.unknown=function(t){return arguments.length?(e=t,h):e},function(e,r){return t=e,n=r,c()}}function te(){return Qn()(Zn,Zn)}function ne(t,n){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(n).domain(t)}return this}function ee(t,n,e,r){var i,o=function(t,n,e){var r=Math.abs(n-t)/Math.max(0,e),i=Math.pow(10,Math.floor(Math.log(r)/Math.LN10)),o=r/i;return o>=$t?i*=10:o>=Vt?i*=5:o>=Yt&&(i*=2),n0)return[t];if((r=n0){let e=Math.round(t/u),r=Math.round(n/u);for(e*un&&--r,o=new Array(i=r-e+1);++an&&--r,o=new Array(i=r-e+1);++a0;){if((i=Ft(l,s,e))===r)return o[u]=l,o[a]=s,n(o);if(i>0)l=Math.floor(l/i)*i,s=Math.ceil(s/i)*i;else{if(!(i<0))break;l=Math.ceil(l*i)/i,s=Math.floor(s*i)/i}r=i}return t},t}function ie(){var t=te();return t.copy=function(){return Jn(t,ie())},ne.apply(t,arguments),re(t)}function oe(t){return((t*=2)<=1?t*t*t:(t-=2)*t*t+2)/2}var ue={value:()=>{}};function ae(){for(var t,n=0,e=arguments.length,r={};n=0&&(e=t.slice(r+1),t=t.slice(0,r)),t&&!n.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:e}}))}function ce(t,n){for(var e,r=0,i=t.length;r0)for(var e,r,i=new Array(e),o=0;o=0&&n._call.call(void 0,t),n=n._next;--ge}()}finally{ge=0,function(){var t,n,e=pe,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:pe=n);de=t,Ce(r)}(),we=0}}function Se(){var t=be.now(),n=t-me;n>1e3&&(_e-=n,me=t)}function Ce(t){ge||(ve&&(ve=clearTimeout(ve)),t-we>24?(t<1/0&&(ve=setTimeout(Ee,t-be.now()-_e)),ye&&(ye=clearInterval(ye))):(ye||(me=be.now(),ye=setInterval(Se,1e3)),ge=1,xe(Ee)))}function je(t,n,e){var r=new Ne;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Ne.prototype=ke.prototype={constructor:Ne,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?Me():+e)+(null==n?0:+n),this._next||de===this||(de?de._next=this:pe=this,de=this),this._call=t,this._time=e,Ce()},stop:function(){this._call&&(this._call=null,this._time=1/0,Ce())}};var qe=fe("start","end","cancel","interrupt"),Oe=[];function Pe(t,n,e,r,i,o){var u=t.__transition;if(u){if(e in u)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=1,e.timer.restart(u,e.delay,e.time),e.delay<=t&&u(t-e.delay)}function u(o){var s,c,h,f;if(1!==e.state)return l();for(s in i)if((f=i[s]).name===e.name){if(3===f.state)return je(u);4===f.state?(f.state=6,f.timer.stop(),f.on.call("interrupt",t,t.__data__,f.index,f.group),delete i[s]):+s0)throw new Error("too late; already scheduled");return e}function Le(t,n){var e=Te(t,n);if(e.state>3)throw new Error("too late; already running");return e}function Te(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}var De,Be=180/Math.PI,Xe={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function ze(t,n,e,r,i,o){var u,a,l;return(u=Math.sqrt(t*t+n*n))&&(t/=u,n/=u),(l=t*e+n*r)&&(e-=t*l,r-=n*l),(a=Math.sqrt(e*e+r*r))&&(e/=a,r/=a,l/=a),t*r180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:Bn(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,u.rotate,a,l),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:Bn(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,u.skewX,a,l),function(t,n,e,r,o,u){if(t!==e||n!==r){var a=o.push(i(o)+"scale(",null,",",null,")");u.push({i:a-4,x:Bn(t,e)},{i:a-2,x:Bn(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,u.scaleX,u.scaleY,a,l),o=u=null,function(t){for(var n,e=-1,r=l.length;++e=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?He:Le;return function(){var u=o(this,t),a=u.on;a!==r&&(i=(r=a).copy()).on(n,e),u.on=i}}var cr=vt.prototype.constructor;function hr(t){return function(){this.style.removeProperty(t)}}function fr(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}function pr(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&fr(t,o,e)),r}return o._value=n,o}function dr(t){return function(n){this.textContent=t.call(this,n)}}function gr(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&dr(r)),n}return r._value=t,r}var vr=0;function yr(t,n,e,r){this._groups=t,this._parents=n,this._name=e,this._id=r}function mr(){return++vr}var wr=vt.prototype;yr.prototype=function(t){return vt().transition(t)}.prototype={constructor:yr,select:function(t){var n=this._name,e=this._id;"function"!=typeof t&&(t=r(t));for(var i=this._groups,o=i.length,u=new Array(o),a=0;a{p&&(p.textContent="search: "+n+" of "+e+" total samples ( "+St(".3f")(n/e*100,3)+"%)")},d()};const E=k;let S=(t,n,e=!1)=>{if(!n)return!1;let r=b(t);e&&(n=n.toLowerCase(),r=r.toLowerCase());const i=new RegExp(n);return void 0!==r&&r&&r.match(i)};const C=S;let j=function(t){p&&(t?p.textContent=t:"function"==typeof d?d():p.textContent="")};const q=j;let O=function(t){return b(t)+" ("+St(".3f")(100*(t.x1-t.x0),3)+"%, "+x(t)+" samples)"},P=function(t){return t.highlight?"#E600E6":function(t,n){let e=_||"warm";_||void 0===n||""===n||(e="red",void 0!==t&&t&&t.match(/::/)&&(e="yellow"),"kernel"===n?e="orange":"jit"===n?e="green":"inlined"===n&&(e="aqua"));const r=function(t){let n=0;if(t){const e=t.split("`");e.length>1&&(t=e[e.length-1]),n=function(t){let n=0,e=0,r=1;if(t){for(let i=0;i6);i++)n+=r*(t.charCodeAt(i)%10),e+=9*r,r*=.7;e>0&&(n/=e)}return n}(t=t.split("(")[0])}return n}(t);return function(t,n){let e,r,i;return"red"===t?(e=200+Math.round(55*n),r=50+Math.round(80*n),i=r):"orange"===t?(e=190+Math.round(65*n),r=90+Math.round(65*n),i=0):"yellow"===t?(e=175+Math.round(55*n),r=e,i=50+Math.round(20*n)):"green"===t?(e=50+Math.round(60*n),r=200+Math.round(55*n),i=e):"pastelgreen"===t?(e=163+Math.round(75*n),r=195+Math.round(49*n),i=72+Math.round(149*n)):"blue"===t?(e=91+Math.round(126*n),r=156+Math.round(76*n),i=221+Math.round(26*n)):"aqua"===t?(e=50+Math.round(60*n),r=165+Math.round(55*n),i=r):"cold"===t?(e=0+Math.round(55*(1-n)),r=0+Math.round(230*(1-n)),i=200+Math.round(55*n)):(e=200+Math.round(55*n),r=0+Math.round(230*(1-n)),i=0+Math.round(55*(1-n))),"rgb("+e+","+r+","+i+")"}(e,r)}(b(t),A(t))};const H=P;function L(t){t.data.fade=!1,t.data.hide=!1,t.children&&t.children.forEach(L)}function T(t){t.parent&&(t.parent.data.fade=!0,T(t.parent))}function D(t){if(i&&i.hide(),function(t){let n,e,r,i=t,o=i.parent;for(;o;){for(n=o.children,e=n.length;e--;)r=n[e],r!==i&&(r.data.hide=!0);i=o,o=i.parent}}(t),L(t),T(t),I(),y){const n=yt(this).select("svg")._groups[0][0].parentNode.offsetTop,r=(window.innerHeight-n)/e,i=(t.height-r+10)*e;window.scrollTo({top:n+i,left:0,behavior:"smooth"})}"function"==typeof c&&c(t)}function B(t,n){if(t.id===n)return t;{const e=M(t);if(e)for(let t=0;t0){const r=t/(n.x1-n.x0);e=e.filter((function(t){return(t.x1-t.x0)*r>f}))}return e}(r),y=yt(this).select("svg");y.attr("width",t);let w=y.selectAll("g").data(g,(function(t){return t.id}));if(!n||v){const t=Math.max.apply(null,g.map((function(t){return t.depth})));n=(t+3)*e,n{D(n)})),w.exit().remove(),w.on("mouseover",(function(t,n){i&&i.show(n,this),j(O(n)),"function"==typeof h&&h(n)})).on("mouseout",(function(){i&&i.hide(),j(null)}))}))}function $(t,n){n.forEach((function(n){const e=t.find((function(t){return t.name===n.name}));e?(e.value+=n.value,n.children&&(e.children||(e.children=[]),$(e.children,n.children))):t.push(n)}))}function V(t){let n,e,r,i,o,u,a,l;const s=[],c=[],h=[],f=!g;let p=t.data;for(p.hide?(t.value=0,e=t.children,e&&h.push(e)):(t.value=p.fade?0:x(p),s.push(t));n=s.pop();)if(e=n.children,e&&(o=e.length)){for(i=0;o--;)a=e[o],p=a.data,p.hide?(a.value=0,r=a.children,r&&h.push(r)):(p.fade?a.value=0:(l=x(p),a.value=l,i+=l),s.push(a));f&&n.value&&(n.value-=i),c.push(e)}for(o=c.length;o--;){for(e=c[o],i=0,u=e.length;u--;)i+=e[u].value;e[0].parent.value+=i}for(;h.length;)for(e=h.pop(),u=e.length;u--;)a=e[u],a.value=0,r=a.children,r&&h.push(r)}function Y(){r.datum((t=>{if("Node"!==t.constructor.name){const n=Dt(t,M);return function(t){let n=0;!function(t,n){n(t);let e=t.children;if(e){const t=[e];let r,i,o;for(;t.length;)for(e=t.pop(),r=e.length;r--;)i=e[r],n(i),o=i.children,o&&t.push(o)}}(t,(function(t){t.id=n++}))}(n),V(n),n.originalValue=n.value,w&&n.eachAfter((t=>{let n=N(t);const e=t.children;let r=e&&e.length;for(;--r>=0;)n+=e[r].delta;t.delta=n})),n}}))}function F(e){if(!arguments.length)return F;r=e,Y(),r.each((function(e){if(0===yt(this).select("svg").size()){const e=yt(this).append("svg:svg").attr("width",t).attr("class","partition d3-flame-graph");n&&(n($([n.data],[t]),n.data))),Y(),I(),F):F},F.update=function(t){return r?(t&&(r.datum(t),Y()),I(),F):F},F.destroy=function(){return r?(i&&(i.hide(),"function"==typeof i.destroy&&i.destroy()),r.selectAll("svg").remove(),F):F},F.setColorMapper=function(t){return arguments.length?(P=n=>{const e=H(n);return t(n,e)},F):(P=H,F)},F.color=F.setColorMapper,F.setColorHue=function(t){return arguments.length?(_=t,F):(_=null,F)},F.minFrameSize=function(t){return arguments.length?(f=t,F):f},F.setDetailsElement=function(t){return arguments.length?(p=t,F):p},F.details=F.setDetailsElement,F.selfValue=function(t){return arguments.length?(g=t,F):g},F.resetHeightOnZoom=function(t){return arguments.length?(v=t,F):v},F.scrollOnZoom=function(t){return arguments.length?(y=t,F):y},F.getName=function(t){return arguments.length?(b=t,F):b},F.getValue=function(t){return arguments.length?(x=t,F):x},F.getChildren=function(t){return arguments.length?(M=t,F):M},F.getLibtype=function(t){return arguments.length?(A=t,F):A},F.getDelta=function(t){return arguments.length?(N=t,F):N},F.setSearchHandler=function(t){return arguments.length?(k=t,F):(k=E,F)},F.setDetailsHandler=function(t){return arguments.length?(j=t,F):(j=q,F)},F.setSearchMatch=function(t){return arguments.length?(S=t,F):(S=C,F)},F}return vt.prototype.interrupt=function(t){return this.each((function(){!function(t,n){var e,r,i,o=t.__transition,u=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>2&&e.state<5,e.state=6,e.timer.stop(),e.on.call(r?"interrupt":"cancel",t,t.__data__,e.index,e.group),delete o[i]):u=!1;u&&delete t.__transition}}(this,t)}))},vt.prototype.transition=function(t){var n,e;t instanceof yr?(n=t._id,t=t._name):(n=mr(),(e=_r).time=Me(),t=null==t?null:t+"");for(var r=this._groups,i=r.length,o=0;on?1:t>=n?0:NaN}function e(t,n){return null==t||null==n?NaN:nt?1:n>=t?0:NaN}function r(t){let r,o,a;function u(t,n,e=0,i=t.length){if(e>>1;o(t[r],n)<0?e=r+1:i=r}while(en(t(e),r),a=(n,e)=>t(n)-e):(r=t===n||t===e?t:i,o=t,a=t),{left:u,center:function(t,n,e=0,r=t.length){const i=u(t,n,e,r-1);return i>e&&a(t[i-1],n)>-a(t[i],n)?i-1:i},right:function(t,n,e=0,i=t.length){if(e>>1;o(t[r],n)<=0?e=r+1:i=r}while(e{n(t,e,(r<<=2)+0,(i<<=2)+0,o<<=2),n(t,e,r+1,i+1,o),n(t,e,r+2,i+2,o),n(t,e,r+3,i+3,o)}}));function d(t){return function(n,e,r=e){if(!((e=+e)>=0))throw new RangeError("invalid rx");if(!((r=+r)>=0))throw new RangeError("invalid ry");let{data:i,width:o,height:a}=n;if(!((o=Math.floor(o))>=0))throw new RangeError("invalid width");if(!((a=Math.floor(void 0!==a?a:i.length/o))>=0))throw new RangeError("invalid height");if(!o||!a||!e&&!r)return n;const u=e&&t(e),c=r&&t(r),f=i.slice();return u&&c?(p(u,f,i,o,a),p(u,i,f,o,a),p(u,f,i,o,a),g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)):u?(p(u,i,f,o,a),p(u,f,i,o,a),p(u,i,f,o,a)):c&&(g(c,i,f,o,a),g(c,f,i,o,a),g(c,i,f,o,a)),n}}function p(t,n,e,r,i){for(let o=0,a=r*i;o{if(!((o-=a)>=i))return;let u=t*r[i];const c=a*t;for(let t=i,n=i+c;t{if(!((a-=u)>=o))return;let c=n*i[o];const f=u*n,s=f+u;for(let t=o,n=o+f;t=n&&++e;else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(i=+i)>=i&&++e}return e}function _(t){return 0|t.length}function b(t){return!(t>0)}function m(t){return"object"!=typeof t||"length"in t?t:Array.from(t)}function x(t,n){let e,r=0,i=0,o=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(e=n-i,i+=e/++r,o+=e*(n-i));else{let a=-1;for(let u of t)null!=(u=n(u,++a,t))&&(u=+u)>=u&&(e=u-i,i+=e/++r,o+=e*(u-i))}if(r>1)return o/(r-1)}function w(t,n){const e=x(t,n);return e?Math.sqrt(e):e}function M(t,n){let e,r;if(void 0===n)for(const n of t)null!=n&&(void 0===e?n>=n&&(e=r=n):(e>n&&(e=n),r=o&&(e=r=o):(e>o&&(e=o),r0){for(o=t[--i];i>0&&(n=o,e=t[--i],o=n+e,r=e-(o-n),!r););i>0&&(r<0&&t[i-1]<0||r>0&&t[i-1]>0)&&(e=2*r,n=o+e,e==n-o&&(o=n))}return o}}class InternMap extends Map{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const[n,e]of t)this.set(n,e)}get(t){return super.get(A(this,t))}has(t){return super.has(A(this,t))}set(t,n){return super.set(S(this,t),n)}delete(t){return super.delete(E(this,t))}}class InternSet extends Set{constructor(t,n=N){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),null!=t)for(const n of t)this.add(n)}has(t){return super.has(A(this,t))}add(t){return super.add(S(this,t))}delete(t){return super.delete(E(this,t))}}function A({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):e}function S({_intern:t,_key:n},e){const r=n(e);return t.has(r)?t.get(r):(t.set(r,e),e)}function E({_intern:t,_key:n},e){const r=n(e);return t.has(r)&&(e=t.get(r),t.delete(r)),e}function N(t){return null!==t&&"object"==typeof t?t.valueOf():t}function k(t){return t}function C(t,...n){return F(t,k,k,n)}function P(t,...n){return F(t,Array.from,k,n)}function z(t,n){for(let e=1,r=n.length;et.pop().map((([n,e])=>[...t,n,e]))));return t}function $(t,n,...e){return F(t,k,n,e)}function D(t,n,...e){return F(t,Array.from,n,e)}function R(t){if(1!==t.length)throw new Error("duplicate key");return t[0]}function F(t,n,e,r){return function t(i,o){if(o>=r.length)return e(i);const a=new InternMap,u=r[o++];let c=-1;for(const t of i){const n=u(t,++c,i),e=a.get(n);e?e.push(t):a.set(n,[t])}for(const[n,e]of a)a.set(n,t(e,o));return n(a)}(t,0)}function q(t,n){return Array.from(n,(n=>t[n]))}function U(t,...n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");t=Array.from(t);let[e]=n;if(e&&2!==e.length||n.length>1){const r=Uint32Array.from(t,((t,n)=>n));return n.length>1?(n=n.map((n=>t.map(n))),r.sort(((t,e)=>{for(const r of n){const n=O(r[t],r[e]);if(n)return n}}))):(e=t.map(e),r.sort(((t,n)=>O(e[t],e[n])))),q(t,r)}return t.sort(I(e))}function I(t=n){if(t===n)return O;if("function"!=typeof t)throw new TypeError("compare is not a function");return(n,e)=>{const r=t(n,e);return r||0===r?r:(0===t(e,e))-(0===t(n,n))}}function O(t,n){return(null==t||!(t>=t))-(null==n||!(n>=n))||(tn?1:0)}var B=Array.prototype.slice;function Y(t){return()=>t}const L=Math.sqrt(50),j=Math.sqrt(10),H=Math.sqrt(2);function X(t,n,e){const r=(n-t)/Math.max(0,e),i=Math.floor(Math.log10(r)),o=r/Math.pow(10,i),a=o>=L?10:o>=j?5:o>=H?2:1;let u,c,f;return i<0?(f=Math.pow(10,-i)/a,u=Math.round(t*f),c=Math.round(n*f),u/fn&&--c,f=-f):(f=Math.pow(10,i)*a,u=Math.round(t/f),c=Math.round(n/f),u*fn&&--c),c0))return[];if((t=+t)===(n=+n))return[t];const r=n=i))return[];const u=o-i+1,c=new Array(u);if(r)if(a<0)for(let t=0;t0?(t=Math.floor(t/i)*i,n=Math.ceil(n/i)*i):i<0&&(t=Math.ceil(t*i)/i,n=Math.floor(n*i)/i),r=i}}function K(t){return Math.max(1,Math.ceil(Math.log(v(t))/Math.LN2)+1)}function Q(){var t=k,n=M,e=K;function r(r){Array.isArray(r)||(r=Array.from(r));var i,o,a,u=r.length,c=new Array(u);for(i=0;i=h)if(t>=h&&n===M){const t=V(l,h,e);isFinite(t)&&(t>0?h=(Math.floor(h/t)+1)*t:t<0&&(h=(Math.ceil(h*-t)+1)/-t))}else d.pop()}for(var p=d.length,g=0,y=p;d[g]<=l;)++g;for(;d[y-1]>h;)--y;(g||y0?d[i-1]:l,v.x1=i0)for(i=0;i=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e=i)&&(e=i)}return e}function tt(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e=o)&&(e=o,r=i);return r}function nt(t,n){let e;if(void 0===n)for(const n of t)null!=n&&(e>n||void 0===e&&n>=n)&&(e=n);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&(e>i||void 0===e&&i>=i)&&(e=i)}return e}function et(t,n){let e,r=-1,i=-1;if(void 0===n)for(const n of t)++i,null!=n&&(e>n||void 0===e&&n>=n)&&(e=n,r=i);else for(let o of t)null!=(o=n(o,++i,t))&&(e>o||void 0===e&&o>=o)&&(e=o,r=i);return r}function rt(t,n,e=0,r=1/0,i){if(n=Math.floor(n),e=Math.floor(Math.max(0,e)),r=Math.floor(Math.min(t.length-1,r)),!(e<=n&&n<=r))return t;for(i=void 0===i?O:I(i);r>e;){if(r-e>600){const o=r-e+1,a=n-e+1,u=Math.log(o),c=.5*Math.exp(2*u/3),f=.5*Math.sqrt(u*c*(o-c)/o)*(a-o/2<0?-1:1);rt(t,n,Math.max(e,Math.floor(n-a*c/o+f)),Math.min(r,Math.floor(n+(o-a)*c/o+f)),i)}const o=t[n];let a=e,u=r;for(it(t,e,n),i(t[r],o)>0&&it(t,e,r);a0;)--u}0===i(t[e],o)?it(t,e,u):(++u,it(t,u,r)),u<=n&&(e=u+1),n<=u&&(r=u-1)}return t}function it(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function ot(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)>0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)>0:0===e(n,n))&&(r=n,i=!0);return r}function at(t,n,e){if(t=Float64Array.from(function*(t,n){if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(yield n);else{let e=-1;for(let r of t)null!=(r=n(r,++e,t))&&(r=+r)>=r&&(yield r)}}(t,e)),(r=t.length)&&!isNaN(n=+n)){if(n<=0||r<2)return nt(t);if(n>=1)return J(t);var r,i=(r-1)*n,o=Math.floor(i),a=J(rt(t,o).subarray(0,o+1));return a+(nt(t.subarray(o+1))-a)*(i-o)}}function ut(t,n,e=o){if((r=t.length)&&!isNaN(n=+n)){if(n<=0||r<2)return+e(t[0],0,t);if(n>=1)return+e(t[r-1],r-1,t);var r,i=(r-1)*n,a=Math.floor(i),u=+e(t[a],a,t);return u+(+e(t[a+1],a+1,t)-u)*(i-a)}}function ct(t,n,e=o){if(!isNaN(n=+n)){if(r=Float64Array.from(t,((n,r)=>o(e(t[r],r,t)))),n<=0)return et(r);if(n>=1)return tt(r);var r,i=Uint32Array.from(t,((t,n)=>n)),a=r.length-1,u=Math.floor(a*n);return rt(i,u,0,a,((t,n)=>O(r[t],r[n]))),(u=ot(i.subarray(0,u+1),(t=>r[t])))>=0?u:-1}}function ft(t){return Array.from(function*(t){for(const n of t)yield*n}(t))}function st(t,n){return[t,n]}function lt(t,n,e){t=+t,n=+n,e=(i=arguments.length)<2?(n=t,t=0,1):i<3?1:+e;for(var r=-1,i=0|Math.max(0,Math.ceil((n-t)/e)),o=new Array(i);++r+t(n)}function kt(t,n){return n=Math.max(0,t.bandwidth()-2*n)/2,t.round()&&(n=Math.round(n)),e=>+t(e)+n}function Ct(){return!this.__axis}function Pt(t,n){var e=[],r=null,i=null,o=6,a=6,u=3,c="undefined"!=typeof window&&window.devicePixelRatio>1?0:.5,f=t===xt||t===Tt?-1:1,s=t===Tt||t===wt?"x":"y",l=t===xt||t===Mt?St:Et;function h(h){var d=null==r?n.ticks?n.ticks.apply(n,e):n.domain():r,p=null==i?n.tickFormat?n.tickFormat.apply(n,e):mt:i,g=Math.max(o,0)+u,y=n.range(),v=+y[0]+c,_=+y[y.length-1]+c,b=(n.bandwidth?kt:Nt)(n.copy(),c),m=h.selection?h.selection():h,x=m.selectAll(".domain").data([null]),w=m.selectAll(".tick").data(d,n).order(),M=w.exit(),T=w.enter().append("g").attr("class","tick"),A=w.select("line"),S=w.select("text");x=x.merge(x.enter().insert("path",".tick").attr("class","domain").attr("stroke","currentColor")),w=w.merge(T),A=A.merge(T.append("line").attr("stroke","currentColor").attr(s+"2",f*o)),S=S.merge(T.append("text").attr("fill","currentColor").attr(s,f*g).attr("dy",t===xt?"0em":t===Mt?"0.71em":"0.32em")),h!==m&&(x=x.transition(h),w=w.transition(h),A=A.transition(h),S=S.transition(h),M=M.transition(h).attr("opacity",At).attr("transform",(function(t){return isFinite(t=b(t))?l(t+c):this.getAttribute("transform")})),T.attr("opacity",At).attr("transform",(function(t){var n=this.parentNode.__axis;return l((n&&isFinite(n=n(t))?n:b(t))+c)}))),M.remove(),x.attr("d",t===Tt||t===wt?a?"M"+f*a+","+v+"H"+c+"V"+_+"H"+f*a:"M"+c+","+v+"V"+_:a?"M"+v+","+f*a+"V"+c+"H"+_+"V"+f*a:"M"+v+","+c+"H"+_),w.attr("opacity",1).attr("transform",(function(t){return l(b(t)+c)})),A.attr(s+"2",f*o),S.attr(s,f*g).text(p),m.filter(Ct).attr("fill","none").attr("font-size",10).attr("font-family","sans-serif").attr("text-anchor",t===wt?"start":t===Tt?"end":"middle"),m.each((function(){this.__axis=b}))}return h.scale=function(t){return arguments.length?(n=t,h):n},h.ticks=function(){return e=Array.from(arguments),h},h.tickArguments=function(t){return arguments.length?(e=null==t?[]:Array.from(t),h):e.slice()},h.tickValues=function(t){return arguments.length?(r=null==t?null:Array.from(t),h):r&&r.slice()},h.tickFormat=function(t){return arguments.length?(i=t,h):i},h.tickSize=function(t){return arguments.length?(o=a=+t,h):o},h.tickSizeInner=function(t){return arguments.length?(o=+t,h):o},h.tickSizeOuter=function(t){return arguments.length?(a=+t,h):a},h.tickPadding=function(t){return arguments.length?(u=+t,h):u},h.offset=function(t){return arguments.length?(c=+t,h):c},h}var zt={value:()=>{}};function $t(){for(var t,n=0,e=arguments.length,r={};n=0&&(n=t.slice(e+1),t=t.slice(0,e)),t&&!r.hasOwnProperty(t))throw new Error("unknown type: "+t);return{type:t,name:n}}))),a=-1,u=o.length;if(!(arguments.length<2)){if(null!=n&&"function"!=typeof n)throw new Error("invalid callback: "+n);for(;++a0)for(var e,r,i=new Array(e),o=0;o=0&&"xmlns"!==(n=t.slice(0,e))&&(t=t.slice(e+1)),Ut.hasOwnProperty(n)?{space:Ut[n],local:t}:t}function Ot(t){return function(){var n=this.ownerDocument,e=this.namespaceURI;return e===qt&&n.documentElement.namespaceURI===qt?n.createElement(t):n.createElementNS(e,t)}}function Bt(t){return function(){return this.ownerDocument.createElementNS(t.space,t.local)}}function Yt(t){var n=It(t);return(n.local?Bt:Ot)(n)}function Lt(){}function jt(t){return null==t?Lt:function(){return this.querySelector(t)}}function Ht(t){return null==t?[]:Array.isArray(t)?t:Array.from(t)}function Xt(){return[]}function Gt(t){return null==t?Xt:function(){return this.querySelectorAll(t)}}function Vt(t){return function(){return this.matches(t)}}function Wt(t){return function(n){return n.matches(t)}}var Zt=Array.prototype.find;function Kt(){return this.firstElementChild}var Qt=Array.prototype.filter;function Jt(){return Array.from(this.children)}function tn(t){return new Array(t.length)}function nn(t,n){this.ownerDocument=t.ownerDocument,this.namespaceURI=t.namespaceURI,this._next=null,this._parent=t,this.__data__=n}function en(t,n,e,r,i,o){for(var a,u=0,c=n.length,f=o.length;un?1:t>=n?0:NaN}function cn(t){return function(){this.removeAttribute(t)}}function fn(t){return function(){this.removeAttributeNS(t.space,t.local)}}function sn(t,n){return function(){this.setAttribute(t,n)}}function ln(t,n){return function(){this.setAttributeNS(t.space,t.local,n)}}function hn(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttribute(t):this.setAttribute(t,e)}}function dn(t,n){return function(){var e=n.apply(this,arguments);null==e?this.removeAttributeNS(t.space,t.local):this.setAttributeNS(t.space,t.local,e)}}function pn(t){return t.ownerDocument&&t.ownerDocument.defaultView||t.document&&t||t.defaultView}function gn(t){return function(){this.style.removeProperty(t)}}function yn(t,n,e){return function(){this.style.setProperty(t,n,e)}}function vn(t,n,e){return function(){var r=n.apply(this,arguments);null==r?this.style.removeProperty(t):this.style.setProperty(t,r,e)}}function _n(t,n){return t.style.getPropertyValue(n)||pn(t).getComputedStyle(t,null).getPropertyValue(n)}function bn(t){return function(){delete this[t]}}function mn(t,n){return function(){this[t]=n}}function xn(t,n){return function(){var e=n.apply(this,arguments);null==e?delete this[t]:this[t]=e}}function wn(t){return t.trim().split(/^|\s+/)}function Mn(t){return t.classList||new Tn(t)}function Tn(t){this._node=t,this._names=wn(t.getAttribute("class")||"")}function An(t,n){for(var e=Mn(t),r=-1,i=n.length;++r=0&&(this._names.splice(n,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(t){return this._names.indexOf(t)>=0}};var Gn=[null];function Vn(t,n){this._groups=t,this._parents=n}function Wn(){return new Vn([[document.documentElement]],Gn)}function Zn(t){return"string"==typeof t?new Vn([[document.querySelector(t)]],[document.documentElement]):new Vn([[t]],Gn)}Vn.prototype=Wn.prototype={constructor:Vn,select:function(t){"function"!=typeof t&&(t=jt(t));for(var n=this._groups,e=n.length,r=new Array(e),i=0;i=m&&(m=b+1);!(_=y[m])&&++m=0;)(r=i[o])&&(a&&4^r.compareDocumentPosition(a)&&a.parentNode.insertBefore(r,a),a=r);return this},sort:function(t){function n(n,e){return n&&e?t(n.__data__,e.__data__):!n-!e}t||(t=un);for(var e=this._groups,r=e.length,i=new Array(r),o=0;o1?this.each((null==n?gn:"function"==typeof n?vn:yn)(t,n,null==e?"":e)):_n(this.node(),t)},property:function(t,n){return arguments.length>1?this.each((null==n?bn:"function"==typeof n?xn:mn)(t,n)):this.node()[t]},classed:function(t,n){var e=wn(t+"");if(arguments.length<2){for(var r=Mn(this.node()),i=-1,o=e.length;++i=0&&(n=t.slice(e+1),t=t.slice(0,e)),{type:t,name:n}}))}(t+""),a=o.length;if(!(arguments.length<2)){for(u=n?Ln:Yn,r=0;r()=>t;function fe(t,{sourceEvent:n,subject:e,target:r,identifier:i,active:o,x:a,y:u,dx:c,dy:f,dispatch:s}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},subject:{value:e,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:o,enumerable:!0,configurable:!0},x:{value:a,enumerable:!0,configurable:!0},y:{value:u,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:f,enumerable:!0,configurable:!0},_:{value:s}})}function se(t){return!t.ctrlKey&&!t.button}function le(){return this.parentNode}function he(t,n){return null==n?{x:t.x,y:t.y}:n}function de(){return navigator.maxTouchPoints||"ontouchstart"in this}function pe(t,n,e){t.prototype=n.prototype=e,e.constructor=t}function ge(t,n){var e=Object.create(t.prototype);for(var r in n)e[r]=n[r];return e}function ye(){}fe.prototype.on=function(){var t=this._.on.apply(this._,arguments);return t===this._?this:t};var ve=.7,_e=1/ve,be="\\s*([+-]?\\d+)\\s*",me="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",xe="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",we=/^#([0-9a-f]{3,8})$/,Me=new RegExp(`^rgb\\(${be},${be},${be}\\)$`),Te=new RegExp(`^rgb\\(${xe},${xe},${xe}\\)$`),Ae=new RegExp(`^rgba\\(${be},${be},${be},${me}\\)$`),Se=new RegExp(`^rgba\\(${xe},${xe},${xe},${me}\\)$`),Ee=new RegExp(`^hsl\\(${me},${xe},${xe}\\)$`),Ne=new RegExp(`^hsla\\(${me},${xe},${xe},${me}\\)$`),ke={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};function Ce(){return this.rgb().formatHex()}function Pe(){return this.rgb().formatRgb()}function ze(t){var n,e;return t=(t+"").trim().toLowerCase(),(n=we.exec(t))?(e=n[1].length,n=parseInt(n[1],16),6===e?$e(n):3===e?new qe(n>>8&15|n>>4&240,n>>4&15|240&n,(15&n)<<4|15&n,1):8===e?De(n>>24&255,n>>16&255,n>>8&255,(255&n)/255):4===e?De(n>>12&15|n>>8&240,n>>8&15|n>>4&240,n>>4&15|240&n,((15&n)<<4|15&n)/255):null):(n=Me.exec(t))?new qe(n[1],n[2],n[3],1):(n=Te.exec(t))?new qe(255*n[1]/100,255*n[2]/100,255*n[3]/100,1):(n=Ae.exec(t))?De(n[1],n[2],n[3],n[4]):(n=Se.exec(t))?De(255*n[1]/100,255*n[2]/100,255*n[3]/100,n[4]):(n=Ee.exec(t))?Le(n[1],n[2]/100,n[3]/100,1):(n=Ne.exec(t))?Le(n[1],n[2]/100,n[3]/100,n[4]):ke.hasOwnProperty(t)?$e(ke[t]):"transparent"===t?new qe(NaN,NaN,NaN,0):null}function $e(t){return new qe(t>>16&255,t>>8&255,255&t,1)}function De(t,n,e,r){return r<=0&&(t=n=e=NaN),new qe(t,n,e,r)}function Re(t){return t instanceof ye||(t=ze(t)),t?new qe((t=t.rgb()).r,t.g,t.b,t.opacity):new qe}function Fe(t,n,e,r){return 1===arguments.length?Re(t):new qe(t,n,e,null==r?1:r)}function qe(t,n,e,r){this.r=+t,this.g=+n,this.b=+e,this.opacity=+r}function Ue(){return`#${Ye(this.r)}${Ye(this.g)}${Ye(this.b)}`}function Ie(){const t=Oe(this.opacity);return`${1===t?"rgb(":"rgba("}${Be(this.r)}, ${Be(this.g)}, ${Be(this.b)}${1===t?")":`, ${t})`}`}function Oe(t){return isNaN(t)?1:Math.max(0,Math.min(1,t))}function Be(t){return Math.max(0,Math.min(255,Math.round(t)||0))}function Ye(t){return((t=Be(t))<16?"0":"")+t.toString(16)}function Le(t,n,e,r){return r<=0?t=n=e=NaN:e<=0||e>=1?t=n=NaN:n<=0&&(t=NaN),new Xe(t,n,e,r)}function je(t){if(t instanceof Xe)return new Xe(t.h,t.s,t.l,t.opacity);if(t instanceof ye||(t=ze(t)),!t)return new Xe;if(t instanceof Xe)return t;var n=(t=t.rgb()).r/255,e=t.g/255,r=t.b/255,i=Math.min(n,e,r),o=Math.max(n,e,r),a=NaN,u=o-i,c=(o+i)/2;return u?(a=n===o?(e-r)/u+6*(e0&&c<1?0:a,new Xe(a,u,c,t.opacity)}function He(t,n,e,r){return 1===arguments.length?je(t):new Xe(t,n,e,null==r?1:r)}function Xe(t,n,e,r){this.h=+t,this.s=+n,this.l=+e,this.opacity=+r}function Ge(t){return(t=(t||0)%360)<0?t+360:t}function Ve(t){return Math.max(0,Math.min(1,t||0))}function We(t,n,e){return 255*(t<60?n+(e-n)*t/60:t<180?e:t<240?n+(e-n)*(240-t)/60:n)}pe(ye,ze,{copy(t){return Object.assign(new this.constructor,this,t)},displayable(){return this.rgb().displayable()},hex:Ce,formatHex:Ce,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return je(this).formatHsl()},formatRgb:Pe,toString:Pe}),pe(qe,Fe,ge(ye,{brighter(t){return t=null==t?_e:Math.pow(_e,t),new qe(this.r*t,this.g*t,this.b*t,this.opacity)},darker(t){return t=null==t?ve:Math.pow(ve,t),new qe(this.r*t,this.g*t,this.b*t,this.opacity)},rgb(){return this},clamp(){return new qe(Be(this.r),Be(this.g),Be(this.b),Oe(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:Ue,formatHex:Ue,formatHex8:function(){return`#${Ye(this.r)}${Ye(this.g)}${Ye(this.b)}${Ye(255*(isNaN(this.opacity)?1:this.opacity))}`},formatRgb:Ie,toString:Ie})),pe(Xe,He,ge(ye,{brighter(t){return t=null==t?_e:Math.pow(_e,t),new Xe(this.h,this.s,this.l*t,this.opacity)},darker(t){return t=null==t?ve:Math.pow(ve,t),new Xe(this.h,this.s,this.l*t,this.opacity)},rgb(){var t=this.h%360+360*(this.h<0),n=isNaN(t)||isNaN(this.s)?0:this.s,e=this.l,r=e+(e<.5?e:1-e)*n,i=2*e-r;return new qe(We(t>=240?t-240:t+120,i,r),We(t,i,r),We(t<120?t+240:t-120,i,r),this.opacity)},clamp(){return new Xe(Ge(this.h),Ve(this.s),Ve(this.l),Oe(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const t=Oe(this.opacity);return`${1===t?"hsl(":"hsla("}${Ge(this.h)}, ${100*Ve(this.s)}%, ${100*Ve(this.l)}%${1===t?")":`, ${t})`}`}}));const Ze=Math.PI/180,Ke=180/Math.PI,Qe=.96422,Je=1,tr=.82521,nr=4/29,er=6/29,rr=3*er*er,ir=er*er*er;function or(t){if(t instanceof ur)return new ur(t.l,t.a,t.b,t.opacity);if(t instanceof pr)return gr(t);t instanceof qe||(t=Re(t));var n,e,r=lr(t.r),i=lr(t.g),o=lr(t.b),a=cr((.2225045*r+.7168786*i+.0606169*o)/Je);return r===i&&i===o?n=e=a:(n=cr((.4360747*r+.3850649*i+.1430804*o)/Qe),e=cr((.0139322*r+.0971045*i+.7141733*o)/tr)),new ur(116*a-16,500*(n-a),200*(a-e),t.opacity)}function ar(t,n,e,r){return 1===arguments.length?or(t):new ur(t,n,e,null==r?1:r)}function ur(t,n,e,r){this.l=+t,this.a=+n,this.b=+e,this.opacity=+r}function cr(t){return t>ir?Math.pow(t,1/3):t/rr+nr}function fr(t){return t>er?t*t*t:rr*(t-nr)}function sr(t){return 255*(t<=.0031308?12.92*t:1.055*Math.pow(t,1/2.4)-.055)}function lr(t){return(t/=255)<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)}function hr(t){if(t instanceof pr)return new pr(t.h,t.c,t.l,t.opacity);if(t instanceof ur||(t=or(t)),0===t.a&&0===t.b)return new pr(NaN,0=1?(e=1,n-1):Math.floor(e*n),i=t[r],o=t[r+1],a=r>0?t[r-1]:2*i-o,u=r()=>t;function Cr(t,n){return function(e){return t+e*n}}function Pr(t,n){var e=n-t;return e?Cr(t,e>180||e<-180?e-360*Math.round(e/360):e):kr(isNaN(t)?n:t)}function zr(t){return 1==(t=+t)?$r:function(n,e){return e-n?function(t,n,e){return t=Math.pow(t,e),n=Math.pow(n,e)-t,e=1/e,function(r){return Math.pow(t+r*n,e)}}(n,e,t):kr(isNaN(n)?e:n)}}function $r(t,n){var e=n-t;return e?Cr(t,e):kr(isNaN(t)?n:t)}var Dr=function t(n){var e=zr(n);function r(t,n){var r=e((t=Fe(t)).r,(n=Fe(n)).r),i=e(t.g,n.g),o=e(t.b,n.b),a=$r(t.opacity,n.opacity);return function(n){return t.r=r(n),t.g=i(n),t.b=o(n),t.opacity=a(n),t+""}}return r.gamma=t,r}(1);function Rr(t){return function(n){var e,r,i=n.length,o=new Array(i),a=new Array(i),u=new Array(i);for(e=0;eo&&(i=n.slice(o,i),u[a]?u[a]+=i:u[++a]=i),(e=e[0])===(r=r[0])?u[a]?u[a]+=r:u[++a]=r:(u[++a]=null,c.push({i:a,x:Yr(e,r)})),o=Hr.lastIndex;return o180?n+=360:n-t>180&&(t+=360),o.push({i:e.push(i(e)+"rotate(",null,r)-2,x:Yr(t,n)})):n&&e.push(i(e)+"rotate("+n+r)}(o.rotate,a.rotate,u,c),function(t,n,e,o){t!==n?o.push({i:e.push(i(e)+"skewX(",null,r)-2,x:Yr(t,n)}):n&&e.push(i(e)+"skewX("+n+r)}(o.skewX,a.skewX,u,c),function(t,n,e,r,o,a){if(t!==e||n!==r){var u=o.push(i(o)+"scale(",null,",",null,")");a.push({i:u-4,x:Yr(t,e)},{i:u-2,x:Yr(n,r)})}else 1===e&&1===r||o.push(i(o)+"scale("+e+","+r+")")}(o.scaleX,o.scaleY,a.scaleX,a.scaleY,u,c),o=a=null,function(t){for(var n,e=-1,r=c.length;++e=0&&n._call.call(void 0,t),n=n._next;--yi}function Ci(){xi=(mi=Mi.now())+wi,yi=vi=0;try{ki()}finally{yi=0,function(){var t,n,e=pi,r=1/0;for(;e;)e._call?(r>e._time&&(r=e._time),t=e,e=e._next):(n=e._next,e._next=null,e=t?t._next=n:pi=n);gi=t,zi(r)}(),xi=0}}function Pi(){var t=Mi.now(),n=t-mi;n>bi&&(wi-=n,mi=t)}function zi(t){yi||(vi&&(vi=clearTimeout(vi)),t-xi>24?(t<1/0&&(vi=setTimeout(Ci,t-Mi.now()-wi)),_i&&(_i=clearInterval(_i))):(_i||(mi=Mi.now(),_i=setInterval(Pi,bi)),yi=1,Ti(Ci)))}function $i(t,n,e){var r=new Ei;return n=null==n?0:+n,r.restart((e=>{r.stop(),t(e+n)}),n,e),r}Ei.prototype=Ni.prototype={constructor:Ei,restart:function(t,n,e){if("function"!=typeof t)throw new TypeError("callback is not a function");e=(null==e?Ai():+e)+(null==n?0:+n),this._next||gi===this||(gi?gi._next=this:pi=this,gi=this),this._call=t,this._time=e,zi()},stop:function(){this._call&&(this._call=null,this._time=1/0,zi())}};var Di=$t("start","end","cancel","interrupt"),Ri=[],Fi=0,qi=1,Ui=2,Ii=3,Oi=4,Bi=5,Yi=6;function Li(t,n,e,r,i,o){var a=t.__transition;if(a){if(e in a)return}else t.__transition={};!function(t,n,e){var r,i=t.__transition;function o(t){e.state=qi,e.timer.restart(a,e.delay,e.time),e.delay<=t&&a(t-e.delay)}function a(o){var f,s,l,h;if(e.state!==qi)return c();for(f in i)if((h=i[f]).name===e.name){if(h.state===Ii)return $i(a);h.state===Oi?(h.state=Yi,h.timer.stop(),h.on.call("interrupt",t,t.__data__,h.index,h.group),delete i[f]):+fFi)throw new Error("too late; already scheduled");return e}function Hi(t,n){var e=Xi(t,n);if(e.state>Ii)throw new Error("too late; already running");return e}function Xi(t,n){var e=t.__transition;if(!e||!(e=e[n]))throw new Error("transition not found");return e}function Gi(t,n){var e,r,i,o=t.__transition,a=!0;if(o){for(i in n=null==n?null:n+"",o)(e=o[i]).name===n?(r=e.state>Ui&&e.state=0&&(t=t.slice(0,n)),!t||"start"===t}))}(n)?ji:Hi;return function(){var a=o(this,t),u=a.on;u!==r&&(i=(r=u).copy()).on(n,e),a.on=i}}(e,t,n))},attr:function(t,n){var e=It(t),r="transform"===e?ni:Ki;return this.attrTween(t,"function"==typeof n?(e.local?ro:eo)(e,r,Zi(this,"attr."+t,n)):null==n?(e.local?Ji:Qi)(e):(e.local?no:to)(e,r,n))},attrTween:function(t,n){var e="attr."+t;if(arguments.length<2)return(e=this.tween(e))&&e._value;if(null==n)return this.tween(e,null);if("function"!=typeof n)throw new Error;var r=It(t);return this.tween(e,(r.local?io:oo)(r,n))},style:function(t,n,e){var r="transform"==(t+="")?ti:Ki;return null==n?this.styleTween(t,function(t,n){var e,r,i;return function(){var o=_n(this,t),a=(this.style.removeProperty(t),_n(this,t));return o===a?null:o===e&&a===r?i:i=n(e=o,r=a)}}(t,r)).on("end.style."+t,lo(t)):"function"==typeof n?this.styleTween(t,function(t,n,e){var r,i,o;return function(){var a=_n(this,t),u=e(this),c=u+"";return null==u&&(this.style.removeProperty(t),c=u=_n(this,t)),a===c?null:a===r&&c===i?o:(i=c,o=n(r=a,u))}}(t,r,Zi(this,"style."+t,n))).each(function(t,n){var e,r,i,o,a="style."+n,u="end."+a;return function(){var c=Hi(this,t),f=c.on,s=null==c.value[a]?o||(o=lo(n)):void 0;f===e&&i===s||(r=(e=f).copy()).on(u,i=s),c.on=r}}(this._id,t)):this.styleTween(t,function(t,n,e){var r,i,o=e+"";return function(){var a=_n(this,t);return a===o?null:a===r?i:i=n(r=a,e)}}(t,r,n),e).on("end.style."+t,null)},styleTween:function(t,n,e){var r="style."+(t+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(null==n)return this.tween(r,null);if("function"!=typeof n)throw new Error;return this.tween(r,function(t,n,e){var r,i;function o(){var o=n.apply(this,arguments);return o!==i&&(r=(i=o)&&function(t,n,e){return function(r){this.style.setProperty(t,n.call(this,r),e)}}(t,o,e)),r}return o._value=n,o}(t,n,null==e?"":e))},text:function(t){return this.tween("text","function"==typeof t?function(t){return function(){var n=t(this);this.textContent=null==n?"":n}}(Zi(this,"text",t)):function(t){return function(){this.textContent=t}}(null==t?"":t+""))},textTween:function(t){var n="text";if(arguments.length<1)return(n=this.tween(n))&&n._value;if(null==t)return this.tween(n,null);if("function"!=typeof t)throw new Error;return this.tween(n,function(t){var n,e;function r(){var r=t.apply(this,arguments);return r!==e&&(n=(e=r)&&function(t){return function(n){this.textContent=t.call(this,n)}}(r)),n}return r._value=t,r}(t))},remove:function(){return this.on("end.remove",function(t){return function(){var n=this.parentNode;for(var e in this.__transition)if(+e!==t)return;n&&n.removeChild(this)}}(this._id))},tween:function(t,n){var e=this._id;if(t+="",arguments.length<2){for(var r,i=Xi(this.node(),e).tween,o=0,a=i.length;o()=>t;function Qo(t,{sourceEvent:n,target:e,selection:r,mode:i,dispatch:o}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},selection:{value:r,enumerable:!0,configurable:!0},mode:{value:i,enumerable:!0,configurable:!0},_:{value:o}})}function Jo(t){t.preventDefault(),t.stopImmediatePropagation()}var ta={name:"drag"},na={name:"space"},ea={name:"handle"},ra={name:"center"};const{abs:ia,max:oa,min:aa}=Math;function ua(t){return[+t[0],+t[1]]}function ca(t){return[ua(t[0]),ua(t[1])]}var fa={name:"x",handles:["w","e"].map(va),input:function(t,n){return null==t?null:[[+t[0],n[0][1]],[+t[1],n[1][1]]]},output:function(t){return t&&[t[0][0],t[1][0]]}},sa={name:"y",handles:["n","s"].map(va),input:function(t,n){return null==t?null:[[n[0][0],+t[0]],[n[1][0],+t[1]]]},output:function(t){return t&&[t[0][1],t[1][1]]}},la={name:"xy",handles:["n","w","e","s","nw","ne","sw","se"].map(va),input:function(t){return null==t?null:ca(t)},output:function(t){return t}},ha={overlay:"crosshair",selection:"move",n:"ns-resize",e:"ew-resize",s:"ns-resize",w:"ew-resize",nw:"nwse-resize",ne:"nesw-resize",se:"nwse-resize",sw:"nesw-resize"},da={e:"w",w:"e",nw:"ne",ne:"nw",se:"sw",sw:"se"},pa={n:"s",s:"n",nw:"sw",ne:"se",se:"ne",sw:"nw"},ga={overlay:1,selection:1,n:null,e:1,s:null,w:-1,nw:-1,ne:1,se:1,sw:-1},ya={overlay:1,selection:1,n:-1,e:null,s:1,w:null,nw:-1,ne:-1,se:1,sw:1};function va(t){return{type:t}}function _a(t){return!t.ctrlKey&&!t.button}function ba(){var t=this.ownerSVGElement||this;return t.hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]}function ma(){return navigator.maxTouchPoints||"ontouchstart"in this}function xa(t){for(;!t.__brush;)if(!(t=t.parentNode))return;return t.__brush}function wa(t){var n,e=ba,r=_a,i=ma,o=!0,a=$t("start","brush","end"),u=6;function c(n){var e=n.property("__brush",g).selectAll(".overlay").data([va("overlay")]);e.enter().append("rect").attr("class","overlay").attr("pointer-events","all").attr("cursor",ha.overlay).merge(e).each((function(){var t=xa(this).extent;Zn(this).attr("x",t[0][0]).attr("y",t[0][1]).attr("width",t[1][0]-t[0][0]).attr("height",t[1][1]-t[0][1])})),n.selectAll(".selection").data([va("selection")]).enter().append("rect").attr("class","selection").attr("cursor",ha.selection).attr("fill","#777").attr("fill-opacity",.3).attr("stroke","#fff").attr("shape-rendering","crispEdges");var r=n.selectAll(".handle").data(t.handles,(function(t){return t.type}));r.exit().remove(),r.enter().append("rect").attr("class",(function(t){return"handle handle--"+t.type})).attr("cursor",(function(t){return ha[t.type]})),n.each(f).attr("fill","none").attr("pointer-events","all").on("mousedown.brush",h).filter(i).on("touchstart.brush",h).on("touchmove.brush",d).on("touchend.brush touchcancel.brush",p).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function f(){var t=Zn(this),n=xa(this).selection;n?(t.selectAll(".selection").style("display",null).attr("x",n[0][0]).attr("y",n[0][1]).attr("width",n[1][0]-n[0][0]).attr("height",n[1][1]-n[0][1]),t.selectAll(".handle").style("display",null).attr("x",(function(t){return"e"===t.type[t.type.length-1]?n[1][0]-u/2:n[0][0]-u/2})).attr("y",(function(t){return"s"===t.type[0]?n[1][1]-u/2:n[0][1]-u/2})).attr("width",(function(t){return"n"===t.type||"s"===t.type?n[1][0]-n[0][0]+u:u})).attr("height",(function(t){return"e"===t.type||"w"===t.type?n[1][1]-n[0][1]+u:u}))):t.selectAll(".selection,.handle").style("display","none").attr("x",null).attr("y",null).attr("width",null).attr("height",null)}function s(t,n,e){var r=t.__brush.emitter;return!r||e&&r.clean?new l(t,n,e):r}function l(t,n,e){this.that=t,this.args=n,this.state=t.__brush,this.active=0,this.clean=e}function h(e){if((!n||e.touches)&&r.apply(this,arguments)){var i,a,u,c,l,h,d,p,g,y,v,_=this,b=e.target.__data__.type,m="selection"===(o&&e.metaKey?b="overlay":b)?ta:o&&e.altKey?ra:ea,x=t===sa?null:ga[b],w=t===fa?null:ya[b],M=xa(_),T=M.extent,A=M.selection,S=T[0][0],E=T[0][1],N=T[1][0],k=T[1][1],C=0,P=0,z=x&&w&&o&&e.shiftKey,$=Array.from(e.touches||[e],(t=>{const n=t.identifier;return(t=ne(t,_)).point0=t.slice(),t.identifier=n,t}));Gi(_);var D=s(_,arguments,!0).beforestart();if("overlay"===b){A&&(g=!0);const n=[$[0],$[1]||$[0]];M.selection=A=[[i=t===sa?S:aa(n[0][0],n[1][0]),u=t===fa?E:aa(n[0][1],n[1][1])],[l=t===sa?N:oa(n[0][0],n[1][0]),d=t===fa?k:oa(n[0][1],n[1][1])]],$.length>1&&I(e)}else i=A[0][0],u=A[0][1],l=A[1][0],d=A[1][1];a=i,c=u,h=l,p=d;var R=Zn(_).attr("pointer-events","none"),F=R.selectAll(".overlay").attr("cursor",ha[b]);if(e.touches)D.moved=U,D.ended=O;else{var q=Zn(e.view).on("mousemove.brush",U,!0).on("mouseup.brush",O,!0);o&&q.on("keydown.brush",(function(t){switch(t.keyCode){case 16:z=x&&w;break;case 18:m===ea&&(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=ra,I(t));break;case 32:m!==ea&&m!==ra||(x<0?l=h-C:x>0&&(i=a-C),w<0?d=p-P:w>0&&(u=c-P),m=na,F.attr("cursor",ha.selection),I(t));break;default:return}Jo(t)}),!0).on("keyup.brush",(function(t){switch(t.keyCode){case 16:z&&(y=v=z=!1,I(t));break;case 18:m===ra&&(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=ea,I(t));break;case 32:m===na&&(t.altKey?(x&&(l=h-C*x,i=a+C*x),w&&(d=p-P*w,u=c+P*w),m=ra):(x<0?l=h:x>0&&(i=a),w<0?d=p:w>0&&(u=c),m=ea),F.attr("cursor",ha[b]),I(t));break;default:return}Jo(t)}),!0),ae(e.view)}f.call(_),D.start(e,m.name)}function U(t){for(const n of t.changedTouches||[t])for(const t of $)t.identifier===n.identifier&&(t.cur=ne(n,_));if(z&&!y&&!v&&1===$.length){const t=$[0];ia(t.cur[0]-t[0])>ia(t.cur[1]-t[1])?v=!0:y=!0}for(const t of $)t.cur&&(t[0]=t.cur[0],t[1]=t.cur[1]);g=!0,Jo(t),I(t)}function I(t){const n=$[0],e=n.point0;var r;switch(C=n[0]-e[0],P=n[1]-e[1],m){case na:case ta:x&&(C=oa(S-i,aa(N-l,C)),a=i+C,h=l+C),w&&(P=oa(E-u,aa(k-d,P)),c=u+P,p=d+P);break;case ea:$[1]?(x&&(a=oa(S,aa(N,$[0][0])),h=oa(S,aa(N,$[1][0])),x=1),w&&(c=oa(E,aa(k,$[0][1])),p=oa(E,aa(k,$[1][1])),w=1)):(x<0?(C=oa(S-i,aa(N-i,C)),a=i+C,h=l):x>0&&(C=oa(S-l,aa(N-l,C)),a=i,h=l+C),w<0?(P=oa(E-u,aa(k-u,P)),c=u+P,p=d):w>0&&(P=oa(E-d,aa(k-d,P)),c=u,p=d+P));break;case ra:x&&(a=oa(S,aa(N,i-C*x)),h=oa(S,aa(N,l+C*x))),w&&(c=oa(E,aa(k,u-P*w)),p=oa(E,aa(k,d+P*w)))}ht+e))}function za(t,n){var e=0,r=null,i=null,o=null;function a(a){var u,c=a.length,f=new Array(c),s=Pa(0,c),l=new Array(c*c),h=new Array(c),d=0;a=Float64Array.from({length:c*c},n?(t,n)=>a[n%c][n/c|0]:(t,n)=>a[n/c|0][n%c]);for(let n=0;nr(f[t],f[n])));for(const e of s){const r=n;if(t){const t=Pa(1+~c,c).filter((t=>t<0?a[~t*c+e]:a[e*c+t]));i&&t.sort(((t,n)=>i(t<0?-a[~t*c+e]:a[e*c+t],n<0?-a[~n*c+e]:a[e*c+n])));for(const r of t)if(r<0){(l[~r*c+e]||(l[~r*c+e]={source:null,target:null})).target={index:e,startAngle:n,endAngle:n+=a[~r*c+e]*d,value:a[~r*c+e]}}else{(l[e*c+r]||(l[e*c+r]={source:null,target:null})).source={index:e,startAngle:n,endAngle:n+=a[e*c+r]*d,value:a[e*c+r]}}h[e]={index:e,startAngle:r,endAngle:n,value:f[e]}}else{const t=Pa(0,c).filter((t=>a[e*c+t]||a[t*c+e]));i&&t.sort(((t,n)=>i(a[e*c+t],a[e*c+n])));for(const r of t){let t;if(e=0))throw new Error(`invalid digits: ${t}`);if(n>15)return qa;const e=10**n;return function(t){this._+=t[0];for(let n=1,r=t.length;nRa)if(Math.abs(s*u-c*f)>Ra&&i){let h=e-o,d=r-a,p=u*u+c*c,g=h*h+d*d,y=Math.sqrt(p),v=Math.sqrt(l),_=i*Math.tan(($a-Math.acos((p+l-g)/(2*y*v)))/2),b=_/v,m=_/y;Math.abs(b-1)>Ra&&this._append`L${t+b*f},${n+b*s}`,this._append`A${i},${i},0,0,${+(s*h>f*d)},${this._x1=t+m*u},${this._y1=n+m*c}`}else this._append`L${this._x1=t},${this._y1=n}`;else;}arc(t,n,e,r,i,o){if(t=+t,n=+n,o=!!o,(e=+e)<0)throw new Error(`negative radius: ${e}`);let a=e*Math.cos(r),u=e*Math.sin(r),c=t+a,f=n+u,s=1^o,l=o?r-i:i-r;null===this._x1?this._append`M${c},${f}`:(Math.abs(this._x1-c)>Ra||Math.abs(this._y1-f)>Ra)&&this._append`L${c},${f}`,e&&(l<0&&(l=l%Da+Da),l>Fa?this._append`A${e},${e},0,1,${s},${t-a},${n-u}A${e},${e},0,1,${s},${this._x1=c},${this._y1=f}`:l>Ra&&this._append`A${e},${e},0,${+(l>=$a)},${s},${this._x1=t+e*Math.cos(i)},${this._y1=n+e*Math.sin(i)}`)}rect(t,n,e,r){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${e=+e}v${+r}h${-e}Z`}toString(){return this._}};function Ia(){return new Ua}Ia.prototype=Ua.prototype;var Oa=Array.prototype.slice;function Ba(t){return function(){return t}}function Ya(t){return t.source}function La(t){return t.target}function ja(t){return t.radius}function Ha(t){return t.startAngle}function Xa(t){return t.endAngle}function Ga(){return 0}function Va(){return 10}function Wa(t){var n=Ya,e=La,r=ja,i=ja,o=Ha,a=Xa,u=Ga,c=null;function f(){var f,s=n.apply(this,arguments),l=e.apply(this,arguments),h=u.apply(this,arguments)/2,d=Oa.call(arguments),p=+r.apply(this,(d[0]=s,d)),g=o.apply(this,d)-Ea,y=a.apply(this,d)-Ea,v=+i.apply(this,(d[0]=l,d)),_=o.apply(this,d)-Ea,b=a.apply(this,d)-Ea;if(c||(c=f=Ia()),h>Ca&&(Ma(y-g)>2*h+Ca?y>g?(g+=h,y-=h):(g-=h,y+=h):g=y=(g+y)/2,Ma(b-_)>2*h+Ca?b>_?(_+=h,b-=h):(_-=h,b+=h):_=b=(_+b)/2),c.moveTo(p*Ta(g),p*Aa(g)),c.arc(0,0,p,g,y),g!==_||y!==b)if(t){var m=v-+t.apply(this,arguments),x=(_+b)/2;c.quadraticCurveTo(0,0,m*Ta(_),m*Aa(_)),c.lineTo(v*Ta(x),v*Aa(x)),c.lineTo(m*Ta(b),m*Aa(b))}else c.quadraticCurveTo(0,0,v*Ta(_),v*Aa(_)),c.arc(0,0,v,_,b);if(c.quadraticCurveTo(0,0,p*Ta(g),p*Aa(g)),c.closePath(),f)return c=null,f+""||null}return t&&(f.headRadius=function(n){return arguments.length?(t="function"==typeof n?n:Ba(+n),f):t}),f.radius=function(t){return arguments.length?(r=i="function"==typeof t?t:Ba(+t),f):r},f.sourceRadius=function(t){return arguments.length?(r="function"==typeof t?t:Ba(+t),f):r},f.targetRadius=function(t){return arguments.length?(i="function"==typeof t?t:Ba(+t),f):i},f.startAngle=function(t){return arguments.length?(o="function"==typeof t?t:Ba(+t),f):o},f.endAngle=function(t){return arguments.length?(a="function"==typeof t?t:Ba(+t),f):a},f.padAngle=function(t){return arguments.length?(u="function"==typeof t?t:Ba(+t),f):u},f.source=function(t){return arguments.length?(n=t,f):n},f.target=function(t){return arguments.length?(e=t,f):e},f.context=function(t){return arguments.length?(c=null==t?null:t,f):c},f}var Za=Array.prototype.slice;function Ka(t,n){return t-n}var Qa=t=>()=>t;function Ja(t,n){for(var e,r=-1,i=n.length;++rr!=d>r&&e<(h-f)*(r-s)/(d-s)+f&&(i=-i)}return i}function nu(t,n,e){var r,i,o,a;return function(t,n,e){return(n[0]-t[0])*(e[1]-t[1])==(e[0]-t[0])*(n[1]-t[1])}(t,n,e)&&(i=t[r=+(t[0]===n[0])],o=e[r],a=n[r],i<=o&&o<=a||a<=o&&o<=i)}function eu(){}var ru=[[],[[[1,1.5],[.5,1]]],[[[1.5,1],[1,1.5]]],[[[1.5,1],[.5,1]]],[[[1,.5],[1.5,1]]],[[[1,1.5],[.5,1]],[[1,.5],[1.5,1]]],[[[1,.5],[1,1.5]]],[[[1,.5],[.5,1]]],[[[.5,1],[1,.5]]],[[[1,1.5],[1,.5]]],[[[.5,1],[1,.5]],[[1.5,1],[1,1.5]]],[[[1.5,1],[1,.5]]],[[[.5,1],[1.5,1]]],[[[1,1.5],[1.5,1]]],[[[.5,1],[1,1.5]]],[]];function iu(){var t=1,n=1,e=K,r=u;function i(t){var n=e(t);if(Array.isArray(n))n=n.slice().sort(Ka);else{const e=M(t,ou);for(n=G(...Z(e[0],e[1],n),n);n[n.length-1]>=e[1];)n.pop();for(;n[1]o(t,n)))}function o(e,i){const o=null==i?NaN:+i;if(isNaN(o))throw new Error(`invalid value: ${i}`);var u=[],c=[];return function(e,r,i){var o,u,c,f,s,l,h=new Array,d=new Array;o=u=-1,f=au(e[0],r),ru[f<<1].forEach(p);for(;++o=r,ru[s<<2].forEach(p);for(;++o0?u.push([t]):c.push(t)})),c.forEach((function(t){for(var n,e=0,r=u.length;e0&&o0&&a=0&&o>=0))throw new Error("invalid size");return t=r,n=o,i},i.thresholds=function(t){return arguments.length?(e="function"==typeof t?t:Array.isArray(t)?Qa(Za.call(t)):Qa(t),i):e},i.smooth=function(t){return arguments.length?(r=t?u:eu,i):r===u},i}function ou(t){return isFinite(t)?t:NaN}function au(t,n){return null!=t&&+t>=n}function uu(t){return null==t||isNaN(t=+t)?-1/0:t}function cu(t,n,e,r){const i=r-n,o=e-n,a=isFinite(i)||isFinite(o)?i/o:Math.sign(i)/Math.sign(o);return isNaN(a)?t:t+a-.5}function fu(t){return t[0]}function su(t){return t[1]}function lu(){return 1}const hu=134217729,du=33306690738754706e-32;function pu(t,n,e,r,i){let o,a,u,c,f=n[0],s=r[0],l=0,h=0;s>f==s>-f?(o=f,f=n[++l]):(o=s,s=r[++h]);let d=0;if(lf==s>-f?(a=f+o,u=o-(a-f),f=n[++l]):(a=s+o,u=o-(a-s),s=r[++h]),o=a,0!==u&&(i[d++]=u);lf==s>-f?(a=o+f,c=a-o,u=o-(a-c)+(f-c),f=n[++l]):(a=o+s,c=a-o,u=o-(a-c)+(s-c),s=r[++h]),o=a,0!==u&&(i[d++]=u);for(;l=33306690738754716e-32*f?c:-function(t,n,e,r,i,o,a){let u,c,f,s,l,h,d,p,g,y,v,_,b,m,x,w,M,T;const A=t-i,S=e-i,E=n-o,N=r-o;m=A*N,h=hu*A,d=h-(h-A),p=A-d,h=hu*N,g=h-(h-N),y=N-g,x=p*y-(m-d*g-p*g-d*y),w=E*S,h=hu*E,d=h-(h-E),p=E-d,h=hu*S,g=h-(h-S),y=S-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,_u[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,_u[1]=b-(v+l)+(l-w),T=_+v,l=T-_,_u[2]=_-(T-l)+(v-l),_u[3]=T;let k=function(t,n){let e=n[0];for(let r=1;r=C||-k>=C)return k;if(l=t-A,u=t-(A+l)+(l-i),l=e-S,f=e-(S+l)+(l-i),l=n-E,c=n-(E+l)+(l-o),l=r-N,s=r-(N+l)+(l-o),0===u&&0===c&&0===f&&0===s)return k;if(C=vu*a+du*Math.abs(k),k+=A*s+N*u-(E*f+S*c),k>=C||-k>=C)return k;m=u*N,h=hu*u,d=h-(h-u),p=u-d,h=hu*N,g=h-(h-N),y=N-g,x=p*y-(m-d*g-p*g-d*y),w=c*S,h=hu*c,d=h-(h-c),p=c-d,h=hu*S,g=h-(h-S),y=S-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,wu[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,wu[1]=b-(v+l)+(l-w),T=_+v,l=T-_,wu[2]=_-(T-l)+(v-l),wu[3]=T;const P=pu(4,_u,4,wu,bu);m=A*s,h=hu*A,d=h-(h-A),p=A-d,h=hu*s,g=h-(h-s),y=s-g,x=p*y-(m-d*g-p*g-d*y),w=E*f,h=hu*E,d=h-(h-E),p=E-d,h=hu*f,g=h-(h-f),y=f-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,wu[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,wu[1]=b-(v+l)+(l-w),T=_+v,l=T-_,wu[2]=_-(T-l)+(v-l),wu[3]=T;const z=pu(P,bu,4,wu,mu);m=u*s,h=hu*u,d=h-(h-u),p=u-d,h=hu*s,g=h-(h-s),y=s-g,x=p*y-(m-d*g-p*g-d*y),w=c*f,h=hu*c,d=h-(h-c),p=c-d,h=hu*f,g=h-(h-f),y=f-g,M=p*y-(w-d*g-p*g-d*y),v=x-M,l=x-v,wu[0]=x-(v+l)+(l-M),_=m+v,l=_-m,b=m-(_-l)+(v-l),v=b-w,l=b-v,wu[1]=b-(v+l)+(l-w),T=_+v,l=T-_,wu[2]=_-(T-l)+(v-l),wu[3]=T;const $=pu(z,mu,4,wu,xu);return xu[$-1]}(t,n,e,r,i,o,f)}const Tu=Math.pow(2,-52),Au=new Uint32Array(512);class Su{static from(t,n=zu,e=$u){const r=t.length,i=new Float64Array(2*r);for(let o=0;o>1;if(n>0&&"number"!=typeof t[0])throw new Error("Expected coords to contain numbers.");this.coords=t;const e=Math.max(2*n-5,0);this._triangles=new Uint32Array(3*e),this._halfedges=new Int32Array(3*e),this._hashSize=Math.ceil(Math.sqrt(n)),this._hullPrev=new Uint32Array(n),this._hullNext=new Uint32Array(n),this._hullTri=new Uint32Array(n),this._hullHash=new Int32Array(this._hashSize).fill(-1),this._ids=new Uint32Array(n),this._dists=new Float64Array(n),this.update()}update(){const{coords:t,_hullPrev:n,_hullNext:e,_hullTri:r,_hullHash:i}=this,o=t.length>>1;let a=1/0,u=1/0,c=-1/0,f=-1/0;for(let n=0;nc&&(c=e),r>f&&(f=r),this._ids[n]=n}const s=(a+c)/2,l=(u+f)/2;let h,d,p,g=1/0;for(let n=0;n0&&(d=n,g=e)}let _=t[2*d],b=t[2*d+1],m=1/0;for(let n=0;nr&&(n[e++]=i,r=this._dists[i])}return this.hull=n.subarray(0,e),this.triangles=new Uint32Array(0),void(this.halfedges=new Uint32Array(0))}if(Mu(y,v,_,b,x,w)<0){const t=d,n=_,e=b;d=p,_=x,b=w,p=t,x=n,w=e}const M=function(t,n,e,r,i,o){const a=e-t,u=r-n,c=i-t,f=o-n,s=a*a+u*u,l=c*c+f*f,h=.5/(a*f-u*c),d=t+(f*s-u*l)*h,p=n+(a*l-c*s)*h;return{x:d,y:p}}(y,v,_,b,x,w);this._cx=M.x,this._cy=M.y;for(let n=0;n0&&Math.abs(f-o)<=Tu&&Math.abs(s-a)<=Tu)continue;if(o=f,a=s,c===h||c===d||c===p)continue;let l=0;for(let t=0,n=this._hashKey(f,s);t=0;)if(y=g,y===l){y=-1;break}if(-1===y)continue;let v=this._addTriangle(y,c,e[y],-1,-1,r[y]);r[c]=this._legalize(v+2),r[y]=v,T++;let _=e[y];for(;g=e[_],Mu(f,s,t[2*_],t[2*_+1],t[2*g],t[2*g+1])<0;)v=this._addTriangle(_,c,g,r[c],-1,r[_]),r[c]=this._legalize(v+2),e[_]=_,T--,_=g;if(y===l)for(;g=n[y],Mu(f,s,t[2*g],t[2*g+1],t[2*y],t[2*y+1])<0;)v=this._addTriangle(g,c,y,-1,r[y],r[g]),this._legalize(v+2),r[g]=v,e[y]=y,T--,y=g;this._hullStart=n[c]=y,e[y]=n[_]=c,e[c]=_,i[this._hashKey(f,s)]=c,i[this._hashKey(t[2*y],t[2*y+1])]=y}this.hull=new Uint32Array(T);for(let t=0,n=this._hullStart;t0?3-e:1+e)/4}(t-this._cx,n-this._cy)*this._hashSize)%this._hashSize}_legalize(t){const{_triangles:n,_halfedges:e,coords:r}=this;let i=0,o=0;for(;;){const a=e[t],u=t-t%3;if(o=u+(t+2)%3,-1===a){if(0===i)break;t=Au[--i];continue}const c=a-a%3,f=u+(t+1)%3,s=c+(a+2)%3,l=n[o],h=n[t],d=n[f],p=n[s];if(Nu(r[2*l],r[2*l+1],r[2*h],r[2*h+1],r[2*d],r[2*d+1],r[2*p],r[2*p+1])){n[t]=p,n[a]=l;const r=e[s];if(-1===r){let n=this._hullStart;do{if(this._hullTri[n]===s){this._hullTri[n]=t;break}n=this._hullPrev[n]}while(n!==this._hullStart)}this._link(t,r),this._link(a,e[o]),this._link(o,s);const u=c+(a+1)%3;i=e&&n[t[a]]>o;)t[a+1]=t[a--];t[a+1]=r}else{let i=e+1,o=r;Pu(t,e+r>>1,i),n[t[e]]>n[t[r]]&&Pu(t,e,r),n[t[i]]>n[t[r]]&&Pu(t,i,r),n[t[e]]>n[t[i]]&&Pu(t,e,i);const a=t[i],u=n[a];for(;;){do{i++}while(n[t[i]]u);if(o=o-e?(Cu(t,n,i,r),Cu(t,n,e,o-1)):(Cu(t,n,e,o-1),Cu(t,n,i,r))}}function Pu(t,n,e){const r=t[n];t[n]=t[e],t[e]=r}function zu(t){return t[0]}function $u(t){return t[1]}const Du=1e-6;class Ru{constructor(){this._x0=this._y0=this._x1=this._y1=null,this._=""}moveTo(t,n){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}`}closePath(){null!==this._x1&&(this._x1=this._x0,this._y1=this._y0,this._+="Z")}lineTo(t,n){this._+=`L${this._x1=+t},${this._y1=+n}`}arc(t,n,e){const r=(t=+t)+(e=+e),i=n=+n;if(e<0)throw new Error("negative radius");null===this._x1?this._+=`M${r},${i}`:(Math.abs(this._x1-r)>Du||Math.abs(this._y1-i)>Du)&&(this._+="L"+r+","+i),e&&(this._+=`A${e},${e},0,1,1,${t-e},${n}A${e},${e},0,1,1,${this._x1=r},${this._y1=i}`)}rect(t,n,e,r){this._+=`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${+e}v${+r}h${-e}Z`}value(){return this._||null}}class Fu{constructor(){this._=[]}moveTo(t,n){this._.push([t,n])}closePath(){this._.push(this._[0].slice())}lineTo(t,n){this._.push([t,n])}value(){return this._.length?this._:null}}class qu{constructor(t,[n,e,r,i]=[0,0,960,500]){if(!((r=+r)>=(n=+n)&&(i=+i)>=(e=+e)))throw new Error("invalid bounds");this.delaunay=t,this._circumcenters=new Float64Array(2*t.points.length),this.vectors=new Float64Array(2*t.points.length),this.xmax=r,this.xmin=n,this.ymax=i,this.ymin=e,this._init()}update(){return this.delaunay.update(),this._init(),this}_init(){const{delaunay:{points:t,hull:n,triangles:e},vectors:r}=this;let i,o;const a=this.circumcenters=this._circumcenters.subarray(0,e.length/3*2);for(let r,u,c=0,f=0,s=e.length;c1;)i-=2;for(let t=2;t0){if(n>=this.ymax)return null;(i=(this.ymax-n)/r)0){if(t>=this.xmax)return null;(i=(this.xmax-t)/e)this.xmax?2:0)|(nthis.ymax?8:0)}_simplify(t){if(t&&t.length>4){for(let n=0;n2&&function(t){const{triangles:n,coords:e}=t;for(let t=0;t1e-10)return!1}return!0}(t)){this.collinear=Int32Array.from({length:n.length/2},((t,n)=>n)).sort(((t,e)=>n[2*t]-n[2*e]||n[2*t+1]-n[2*e+1]));const t=this.collinear[0],e=this.collinear[this.collinear.length-1],r=[n[2*t],n[2*t+1],n[2*e],n[2*e+1]],i=1e-8*Math.hypot(r[3]-r[1],r[2]-r[0]);for(let t=0,e=n.length/2;t0&&(this.triangles=new Int32Array(3).fill(-1),this.halfedges=new Int32Array(3).fill(-1),this.triangles[0]=r[0],o[r[0]]=1,2===r.length&&(o[r[1]]=0,this.triangles[1]=r[1],this.triangles[2]=r[1]))}voronoi(t){return new qu(this,t)}*neighbors(t){const{inedges:n,hull:e,_hullIndex:r,halfedges:i,triangles:o,collinear:a}=this;if(a){const n=a.indexOf(t);return n>0&&(yield a[n-1]),void(n=0&&i!==e&&i!==r;)e=i;return i}_step(t,n,e){const{inedges:r,hull:i,_hullIndex:o,halfedges:a,triangles:u,points:c}=this;if(-1===r[t]||!c.length)return(t+1)%(c.length>>1);let f=t,s=Iu(n-c[2*t],2)+Iu(e-c[2*t+1],2);const l=r[t];let h=l;do{let r=u[h];const l=Iu(n-c[2*r],2)+Iu(e-c[2*r+1],2);if(l9999?"+"+Ku(n,6):Ku(n,4))+"-"+Ku(t.getUTCMonth()+1,2)+"-"+Ku(t.getUTCDate(),2)+(o?"T"+Ku(e,2)+":"+Ku(r,2)+":"+Ku(i,2)+"."+Ku(o,3)+"Z":i?"T"+Ku(e,2)+":"+Ku(r,2)+":"+Ku(i,2)+"Z":r||e?"T"+Ku(e,2)+":"+Ku(r,2)+"Z":"")}function Ju(t){var n=new RegExp('["'+t+"\n\r]"),e=t.charCodeAt(0);function r(t,n){var r,i=[],o=t.length,a=0,u=0,c=o<=0,f=!1;function s(){if(c)return Hu;if(f)return f=!1,ju;var n,r,i=a;if(t.charCodeAt(i)===Xu){for(;a++=o?c=!0:(r=t.charCodeAt(a++))===Gu?f=!0:r===Vu&&(f=!0,t.charCodeAt(a)===Gu&&++a),t.slice(i+1,n-1).replace(/""/g,'"')}for(;amc(n,e).then((n=>(new DOMParser).parseFromString(n,t)))}var Sc=Ac("application/xml"),Ec=Ac("text/html"),Nc=Ac("image/svg+xml");function kc(t,n,e,r){if(isNaN(n)||isNaN(e))return t;var i,o,a,u,c,f,s,l,h,d=t._root,p={data:r},g=t._x0,y=t._y0,v=t._x1,_=t._y1;if(!d)return t._root=p,t;for(;d.length;)if((f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a,i=d,!(d=d[l=s<<1|f]))return i[l]=p,t;if(u=+t._x.call(null,d.data),c=+t._y.call(null,d.data),n===u&&e===c)return p.next=d,i?i[l]=p:t._root=p,t;do{i=i?i[l]=new Array(4):t._root=new Array(4),(f=n>=(o=(g+v)/2))?g=o:v=o,(s=e>=(a=(y+_)/2))?y=a:_=a}while((l=s<<1|f)==(h=(c>=a)<<1|u>=o));return i[h]=d,i[l]=p,t}function Cc(t,n,e,r,i){this.node=t,this.x0=n,this.y0=e,this.x1=r,this.y1=i}function Pc(t){return t[0]}function zc(t){return t[1]}function $c(t,n,e){var r=new Dc(null==n?Pc:n,null==e?zc:e,NaN,NaN,NaN,NaN);return null==t?r:r.addAll(t)}function Dc(t,n,e,r,i,o){this._x=t,this._y=n,this._x0=e,this._y0=r,this._x1=i,this._y1=o,this._root=void 0}function Rc(t){for(var n={data:t.data},e=n;t=t.next;)e=e.next={data:t.data};return n}var Fc=$c.prototype=Dc.prototype;function qc(t){return function(){return t}}function Uc(t){return 1e-6*(t()-.5)}function Ic(t){return t.x+t.vx}function Oc(t){return t.y+t.vy}function Bc(t){return t.index}function Yc(t,n){var e=t.get(n);if(!e)throw new Error("node not found: "+n);return e}Fc.copy=function(){var t,n,e=new Dc(this._x,this._y,this._x0,this._y0,this._x1,this._y1),r=this._root;if(!r)return e;if(!r.length)return e._root=Rc(r),e;for(t=[{source:r,target:e._root=new Array(4)}];r=t.pop();)for(var i=0;i<4;++i)(n=r.source[i])&&(n.length?t.push({source:n,target:r.target[i]=new Array(4)}):r.target[i]=Rc(n));return e},Fc.add=function(t){const n=+this._x.call(null,t),e=+this._y.call(null,t);return kc(this.cover(n,e),n,e,t)},Fc.addAll=function(t){var n,e,r,i,o=t.length,a=new Array(o),u=new Array(o),c=1/0,f=1/0,s=-1/0,l=-1/0;for(e=0;es&&(s=r),il&&(l=i));if(c>s||f>l)return this;for(this.cover(c,f).cover(s,l),e=0;et||t>=i||r>n||n>=o;)switch(u=(nh||(o=c.y0)>d||(a=c.x1)=v)<<1|t>=y)&&(c=p[p.length-1],p[p.length-1]=p[p.length-1-f],p[p.length-1-f]=c)}else{var _=t-+this._x.call(null,g.data),b=n-+this._y.call(null,g.data),m=_*_+b*b;if(m=(u=(p+y)/2))?p=u:y=u,(s=a>=(c=(g+v)/2))?g=c:v=c,n=d,!(d=d[l=s<<1|f]))return this;if(!d.length)break;(n[l+1&3]||n[l+2&3]||n[l+3&3])&&(e=n,h=l)}for(;d.data!==t;)if(r=d,!(d=d.next))return this;return(i=d.next)&&delete d.next,r?(i?r.next=i:delete r.next,this):n?(i?n[l]=i:delete n[l],(d=n[0]||n[1]||n[2]||n[3])&&d===(n[3]||n[2]||n[1]||n[0])&&!d.length&&(e?e[h]=d:this._root=d),this):(this._root=i,this)},Fc.removeAll=function(t){for(var n=0,e=t.length;n1?r[0]+r.slice(2):r,+t.slice(e+1)]}function Zc(t){return(t=Wc(Math.abs(t)))?t[1]:NaN}var Kc,Qc=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function Jc(t){if(!(n=Qc.exec(t)))throw new Error("invalid format: "+t);var n;return new tf({fill:n[1],align:n[2],sign:n[3],symbol:n[4],zero:n[5],width:n[6],comma:n[7],precision:n[8]&&n[8].slice(1),trim:n[9],type:n[10]})}function tf(t){this.fill=void 0===t.fill?" ":t.fill+"",this.align=void 0===t.align?">":t.align+"",this.sign=void 0===t.sign?"-":t.sign+"",this.symbol=void 0===t.symbol?"":t.symbol+"",this.zero=!!t.zero,this.width=void 0===t.width?void 0:+t.width,this.comma=!!t.comma,this.precision=void 0===t.precision?void 0:+t.precision,this.trim=!!t.trim,this.type=void 0===t.type?"":t.type+""}function nf(t,n){var e=Wc(t,n);if(!e)return t+"";var r=e[0],i=e[1];return i<0?"0."+new Array(-i).join("0")+r:r.length>i+1?r.slice(0,i+1)+"."+r.slice(i+1):r+new Array(i-r.length+2).join("0")}Jc.prototype=tf.prototype,tf.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(void 0===this.width?"":Math.max(1,0|this.width))+(this.comma?",":"")+(void 0===this.precision?"":"."+Math.max(0,0|this.precision))+(this.trim?"~":"")+this.type};var ef={"%":(t,n)=>(100*t).toFixed(n),b:t=>Math.round(t).toString(2),c:t=>t+"",d:function(t){return Math.abs(t=Math.round(t))>=1e21?t.toLocaleString("en").replace(/,/g,""):t.toString(10)},e:(t,n)=>t.toExponential(n),f:(t,n)=>t.toFixed(n),g:(t,n)=>t.toPrecision(n),o:t=>Math.round(t).toString(8),p:(t,n)=>nf(100*t,n),r:nf,s:function(t,n){var e=Wc(t,n);if(!e)return t+"";var r=e[0],i=e[1],o=i-(Kc=3*Math.max(-8,Math.min(8,Math.floor(i/3))))+1,a=r.length;return o===a?r:o>a?r+new Array(o-a+1).join("0"):o>0?r.slice(0,o)+"."+r.slice(o):"0."+new Array(1-o).join("0")+Wc(t,Math.max(0,n+o-1))[0]},X:t=>Math.round(t).toString(16).toUpperCase(),x:t=>Math.round(t).toString(16)};function rf(t){return t}var of,af=Array.prototype.map,uf=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function cf(t){var n,e,r=void 0===t.grouping||void 0===t.thousands?rf:(n=af.call(t.grouping,Number),e=t.thousands+"",function(t,r){for(var i=t.length,o=[],a=0,u=n[0],c=0;i>0&&u>0&&(c+u+1>r&&(u=Math.max(1,r-c)),o.push(t.substring(i-=u,i+u)),!((c+=u+1)>r));)u=n[a=(a+1)%n.length];return o.reverse().join(e)}),i=void 0===t.currency?"":t.currency[0]+"",o=void 0===t.currency?"":t.currency[1]+"",a=void 0===t.decimal?".":t.decimal+"",u=void 0===t.numerals?rf:function(t){return function(n){return n.replace(/[0-9]/g,(function(n){return t[+n]}))}}(af.call(t.numerals,String)),c=void 0===t.percent?"%":t.percent+"",f=void 0===t.minus?"−":t.minus+"",s=void 0===t.nan?"NaN":t.nan+"";function l(t){var n=(t=Jc(t)).fill,e=t.align,l=t.sign,h=t.symbol,d=t.zero,p=t.width,g=t.comma,y=t.precision,v=t.trim,_=t.type;"n"===_?(g=!0,_="g"):ef[_]||(void 0===y&&(y=12),v=!0,_="g"),(d||"0"===n&&"="===e)&&(d=!0,n="0",e="=");var b="$"===h?i:"#"===h&&/[boxX]/.test(_)?"0"+_.toLowerCase():"",m="$"===h?o:/[%p]/.test(_)?c:"",x=ef[_],w=/[defgprs%]/.test(_);function M(t){var i,o,c,h=b,M=m;if("c"===_)M=x(t)+M,t="";else{var T=(t=+t)<0||1/t<0;if(t=isNaN(t)?s:x(Math.abs(t),y),v&&(t=function(t){t:for(var n,e=t.length,r=1,i=-1;r0&&(i=0)}return i>0?t.slice(0,i)+t.slice(n+1):t}(t)),T&&0==+t&&"+"!==l&&(T=!1),h=(T?"("===l?l:f:"-"===l||"("===l?"":l)+h,M=("s"===_?uf[8+Kc/3]:"")+M+(T&&"("===l?")":""),w)for(i=-1,o=t.length;++i(c=t.charCodeAt(i))||c>57){M=(46===c?a+t.slice(i+1):t.slice(i))+M,t=t.slice(0,i);break}}g&&!d&&(t=r(t,1/0));var A=h.length+t.length+M.length,S=A>1)+h+t+M+S.slice(A);break;default:t=S+h+t+M}return u(t)}return y=void 0===y?6:/[gprs]/.test(_)?Math.max(1,Math.min(21,y)):Math.max(0,Math.min(20,y)),M.toString=function(){return t+""},M}return{format:l,formatPrefix:function(t,n){var e=l(((t=Jc(t)).type="f",t)),r=3*Math.max(-8,Math.min(8,Math.floor(Zc(n)/3))),i=Math.pow(10,-r),o=uf[8+r/3];return function(t){return e(i*t)+o}}}}function ff(n){return of=cf(n),t.format=of.format,t.formatPrefix=of.formatPrefix,of}function sf(t){return Math.max(0,-Zc(Math.abs(t)))}function lf(t,n){return Math.max(0,3*Math.max(-8,Math.min(8,Math.floor(Zc(n)/3)))-Zc(Math.abs(t)))}function hf(t,n){return t=Math.abs(t),n=Math.abs(n)-t,Math.max(0,Zc(n)-Zc(t))+1}t.format=void 0,t.formatPrefix=void 0,ff({thousands:",",grouping:[3],currency:["$",""]});var df=1e-6,pf=1e-12,gf=Math.PI,yf=gf/2,vf=gf/4,_f=2*gf,bf=180/gf,mf=gf/180,xf=Math.abs,wf=Math.atan,Mf=Math.atan2,Tf=Math.cos,Af=Math.ceil,Sf=Math.exp,Ef=Math.hypot,Nf=Math.log,kf=Math.pow,Cf=Math.sin,Pf=Math.sign||function(t){return t>0?1:t<0?-1:0},zf=Math.sqrt,$f=Math.tan;function Df(t){return t>1?0:t<-1?gf:Math.acos(t)}function Rf(t){return t>1?yf:t<-1?-yf:Math.asin(t)}function Ff(t){return(t=Cf(t/2))*t}function qf(){}function Uf(t,n){t&&Of.hasOwnProperty(t.type)&&Of[t.type](t,n)}var If={Feature:function(t,n){Uf(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r=0?1:-1,i=r*e,o=Tf(n=(n*=mf)/2+vf),a=Cf(n),u=Vf*a,c=Gf*o+u*Tf(i),f=u*r*Cf(i);as.add(Mf(f,c)),Xf=t,Gf=o,Vf=a}function ds(t){return[Mf(t[1],t[0]),Rf(t[2])]}function ps(t){var n=t[0],e=t[1],r=Tf(e);return[r*Tf(n),r*Cf(n),Cf(e)]}function gs(t,n){return t[0]*n[0]+t[1]*n[1]+t[2]*n[2]}function ys(t,n){return[t[1]*n[2]-t[2]*n[1],t[2]*n[0]-t[0]*n[2],t[0]*n[1]-t[1]*n[0]]}function vs(t,n){t[0]+=n[0],t[1]+=n[1],t[2]+=n[2]}function _s(t,n){return[t[0]*n,t[1]*n,t[2]*n]}function bs(t){var n=zf(t[0]*t[0]+t[1]*t[1]+t[2]*t[2]);t[0]/=n,t[1]/=n,t[2]/=n}var ms,xs,ws,Ms,Ts,As,Ss,Es,Ns,ks,Cs,Ps,zs,$s,Ds,Rs,Fs={point:qs,lineStart:Is,lineEnd:Os,polygonStart:function(){Fs.point=Bs,Fs.lineStart=Ys,Fs.lineEnd=Ls,rs=new T,cs.polygonStart()},polygonEnd:function(){cs.polygonEnd(),Fs.point=qs,Fs.lineStart=Is,Fs.lineEnd=Os,as<0?(Wf=-(Kf=180),Zf=-(Qf=90)):rs>df?Qf=90:rs<-df&&(Zf=-90),os[0]=Wf,os[1]=Kf},sphere:function(){Wf=-(Kf=180),Zf=-(Qf=90)}};function qs(t,n){is.push(os=[Wf=t,Kf=t]),nQf&&(Qf=n)}function Us(t,n){var e=ps([t*mf,n*mf]);if(es){var r=ys(es,e),i=ys([r[1],-r[0],0],r);bs(i),i=ds(i);var o,a=t-Jf,u=a>0?1:-1,c=i[0]*bf*u,f=xf(a)>180;f^(u*JfQf&&(Qf=o):f^(u*Jf<(c=(c+360)%360-180)&&cQf&&(Qf=n)),f?tjs(Wf,Kf)&&(Kf=t):js(t,Kf)>js(Wf,Kf)&&(Wf=t):Kf>=Wf?(tKf&&(Kf=t)):t>Jf?js(Wf,t)>js(Wf,Kf)&&(Kf=t):js(t,Kf)>js(Wf,Kf)&&(Wf=t)}else is.push(os=[Wf=t,Kf=t]);nQf&&(Qf=n),es=e,Jf=t}function Is(){Fs.point=Us}function Os(){os[0]=Wf,os[1]=Kf,Fs.point=qs,es=null}function Bs(t,n){if(es){var e=t-Jf;rs.add(xf(e)>180?e+(e>0?360:-360):e)}else ts=t,ns=n;cs.point(t,n),Us(t,n)}function Ys(){cs.lineStart()}function Ls(){Bs(ts,ns),cs.lineEnd(),xf(rs)>df&&(Wf=-(Kf=180)),os[0]=Wf,os[1]=Kf,es=null}function js(t,n){return(n-=t)<0?n+360:n}function Hs(t,n){return t[0]-n[0]}function Xs(t,n){return t[0]<=t[1]?t[0]<=n&&n<=t[1]:ngf&&(t-=Math.round(t/_f)*_f),[t,n]}function ul(t,n,e){return(t%=_f)?n||e?ol(fl(t),sl(n,e)):fl(t):n||e?sl(n,e):al}function cl(t){return function(n,e){return xf(n+=t)>gf&&(n-=Math.round(n/_f)*_f),[n,e]}}function fl(t){var n=cl(t);return n.invert=cl(-t),n}function sl(t,n){var e=Tf(t),r=Cf(t),i=Tf(n),o=Cf(n);function a(t,n){var a=Tf(n),u=Tf(t)*a,c=Cf(t)*a,f=Cf(n),s=f*e+u*r;return[Mf(c*i-s*o,u*e-f*r),Rf(s*i+c*o)]}return a.invert=function(t,n){var a=Tf(n),u=Tf(t)*a,c=Cf(t)*a,f=Cf(n),s=f*i-c*o;return[Mf(c*i+f*o,u*e+s*r),Rf(s*e-u*r)]},a}function ll(t){function n(n){return(n=t(n[0]*mf,n[1]*mf))[0]*=bf,n[1]*=bf,n}return t=ul(t[0]*mf,t[1]*mf,t.length>2?t[2]*mf:0),n.invert=function(n){return(n=t.invert(n[0]*mf,n[1]*mf))[0]*=bf,n[1]*=bf,n},n}function hl(t,n,e,r,i,o){if(e){var a=Tf(n),u=Cf(n),c=r*e;null==i?(i=n+r*_f,o=n-c/2):(i=dl(a,i),o=dl(a,o),(r>0?io)&&(i+=r*_f));for(var f,s=i;r>0?s>o:s1&&n.push(n.pop().concat(n.shift()))},result:function(){var e=n;return n=[],t=null,e}}}function gl(t,n){return xf(t[0]-n[0])=0;--o)i.point((s=f[o])[0],s[1]);else r(h.x,h.p.x,-1,i);h=h.p}f=(h=h.o).z,d=!d}while(!h.v);i.lineEnd()}}}function _l(t){if(n=t.length){for(var n,e,r=0,i=t[0];++r=0?1:-1,E=S*A,N=E>gf,k=y*w;if(c.add(Mf(k*S*Cf(E),v*M+k*Tf(E))),a+=N?A+S*_f:A,N^p>=e^m>=e){var C=ys(ps(d),ps(b));bs(C);var P=ys(o,C);bs(P);var z=(N^A>=0?-1:1)*Rf(P[2]);(r>z||r===z&&(C[0]||C[1]))&&(u+=N^A>=0?1:-1)}}return(a<-df||a0){for(l||(i.polygonStart(),l=!0),i.lineStart(),t=0;t1&&2&c&&h.push(h.pop().concat(h.shift())),a.push(h.filter(wl))}return h}}function wl(t){return t.length>1}function Ml(t,n){return((t=t.x)[0]<0?t[1]-yf-df:yf-t[1])-((n=n.x)[0]<0?n[1]-yf-df:yf-n[1])}al.invert=al;var Tl=xl((function(){return!0}),(function(t){var n,e=NaN,r=NaN,i=NaN;return{lineStart:function(){t.lineStart(),n=1},point:function(o,a){var u=o>0?gf:-gf,c=xf(o-e);xf(c-gf)0?yf:-yf),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),t.point(o,r),n=0):i!==u&&c>=gf&&(xf(e-i)df?wf((Cf(n)*(o=Tf(r))*Cf(e)-Cf(r)*(i=Tf(n))*Cf(t))/(i*o*a)):(n+r)/2}(e,r,o,a),t.point(i,r),t.lineEnd(),t.lineStart(),t.point(u,r),n=0),t.point(e=o,r=a),i=u},lineEnd:function(){t.lineEnd(),e=r=NaN},clean:function(){return 2-n}}}),(function(t,n,e,r){var i;if(null==t)i=e*yf,r.point(-gf,i),r.point(0,i),r.point(gf,i),r.point(gf,0),r.point(gf,-i),r.point(0,-i),r.point(-gf,-i),r.point(-gf,0),r.point(-gf,i);else if(xf(t[0]-n[0])>df){var o=t[0]0,i=xf(n)>df;function o(t,e){return Tf(t)*Tf(e)>n}function a(t,e,r){var i=[1,0,0],o=ys(ps(t),ps(e)),a=gs(o,o),u=o[0],c=a-u*u;if(!c)return!r&&t;var f=n*a/c,s=-n*u/c,l=ys(i,o),h=_s(i,f);vs(h,_s(o,s));var d=l,p=gs(h,d),g=gs(d,d),y=p*p-g*(gs(h,h)-1);if(!(y<0)){var v=zf(y),_=_s(d,(-p-v)/g);if(vs(_,h),_=ds(_),!r)return _;var b,m=t[0],x=e[0],w=t[1],M=e[1];x0^_[1]<(xf(_[0]-m)gf^(m<=_[0]&&_[0]<=x)){var S=_s(d,(-p+v)/g);return vs(S,h),[_,ds(S)]}}}function u(n,e){var i=r?t:gf-t,o=0;return n<-i?o|=1:n>i&&(o|=2),e<-i?o|=4:e>i&&(o|=8),o}return xl(o,(function(t){var n,e,c,f,s;return{lineStart:function(){f=c=!1,s=1},point:function(l,h){var d,p=[l,h],g=o(l,h),y=r?g?0:u(l,h):g?u(l+(l<0?gf:-gf),h):0;if(!n&&(f=c=g)&&t.lineStart(),g!==c&&(!(d=a(n,p))||gl(n,d)||gl(p,d))&&(p[2]=1),g!==c)s=0,g?(t.lineStart(),d=a(p,n),t.point(d[0],d[1])):(d=a(n,p),t.point(d[0],d[1],2),t.lineEnd()),n=d;else if(i&&n&&r^g){var v;y&e||!(v=a(p,n,!0))||(s=0,r?(t.lineStart(),t.point(v[0][0],v[0][1]),t.point(v[1][0],v[1][1]),t.lineEnd()):(t.point(v[1][0],v[1][1]),t.lineEnd(),t.lineStart(),t.point(v[0][0],v[0][1],3)))}!g||n&&gl(n,p)||t.point(p[0],p[1]),n=p,c=g,e=y},lineEnd:function(){c&&t.lineEnd(),n=null},clean:function(){return s|(f&&c)<<1}}}),(function(n,r,i,o){hl(o,t,e,i,n,r)}),r?[0,-t]:[-gf,t-gf])}var Sl,El,Nl,kl,Cl=1e9,Pl=-Cl;function zl(t,n,e,r){function i(i,o){return t<=i&&i<=e&&n<=o&&o<=r}function o(i,o,u,f){var s=0,l=0;if(null==i||(s=a(i,u))!==(l=a(o,u))||c(i,o)<0^u>0)do{f.point(0===s||3===s?t:e,s>1?r:n)}while((s=(s+u+4)%4)!==l);else f.point(o[0],o[1])}function a(r,i){return xf(r[0]-t)0?0:3:xf(r[0]-e)0?2:1:xf(r[1]-n)0?1:0:i>0?3:2}function u(t,n){return c(t.x,n.x)}function c(t,n){var e=a(t,1),r=a(n,1);return e!==r?e-r:0===e?n[1]-t[1]:1===e?t[0]-n[0]:2===e?t[1]-n[1]:n[0]-t[0]}return function(a){var c,f,s,l,h,d,p,g,y,v,_,b=a,m=pl(),x={point:w,lineStart:function(){x.point=M,f&&f.push(s=[]);v=!0,y=!1,p=g=NaN},lineEnd:function(){c&&(M(l,h),d&&y&&m.rejoin(),c.push(m.result()));x.point=w,y&&b.lineEnd()},polygonStart:function(){b=m,c=[],f=[],_=!0},polygonEnd:function(){var n=function(){for(var n=0,e=0,i=f.length;er&&(h-o)*(r-a)>(d-a)*(t-o)&&++n:d<=r&&(h-o)*(r-a)<(d-a)*(t-o)&&--n;return n}(),e=_&&n,i=(c=ft(c)).length;(e||i)&&(a.polygonStart(),e&&(a.lineStart(),o(null,null,1,a),a.lineEnd()),i&&vl(c,u,n,o,a),a.polygonEnd());b=a,c=f=s=null}};function w(t,n){i(t,n)&&b.point(t,n)}function M(o,a){var u=i(o,a);if(f&&s.push([o,a]),v)l=o,h=a,d=u,v=!1,u&&(b.lineStart(),b.point(o,a));else if(u&&y)b.point(o,a);else{var c=[p=Math.max(Pl,Math.min(Cl,p)),g=Math.max(Pl,Math.min(Cl,g))],m=[o=Math.max(Pl,Math.min(Cl,o)),a=Math.max(Pl,Math.min(Cl,a))];!function(t,n,e,r,i,o){var a,u=t[0],c=t[1],f=0,s=1,l=n[0]-u,h=n[1]-c;if(a=e-u,l||!(a>0)){if(a/=l,l<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=i-u,l||!(a<0)){if(a/=l,l<0){if(a>s)return;a>f&&(f=a)}else if(l>0){if(a0)){if(a/=h,h<0){if(a0){if(a>s)return;a>f&&(f=a)}if(a=o-c,h||!(a<0)){if(a/=h,h<0){if(a>s)return;a>f&&(f=a)}else if(h>0){if(a0&&(t[0]=u+f*l,t[1]=c+f*h),s<1&&(n[0]=u+s*l,n[1]=c+s*h),!0}}}}}(c,m,t,n,e,r)?u&&(b.lineStart(),b.point(o,a),_=!1):(y||(b.lineStart(),b.point(c[0],c[1])),b.point(m[0],m[1]),u||b.lineEnd(),_=!1)}p=o,g=a,y=u}return x}}var $l={sphere:qf,point:qf,lineStart:function(){$l.point=Rl,$l.lineEnd=Dl},lineEnd:qf,polygonStart:qf,polygonEnd:qf};function Dl(){$l.point=$l.lineEnd=qf}function Rl(t,n){El=t*=mf,Nl=Cf(n*=mf),kl=Tf(n),$l.point=Fl}function Fl(t,n){t*=mf;var e=Cf(n*=mf),r=Tf(n),i=xf(t-El),o=Tf(i),a=r*Cf(i),u=kl*e-Nl*r*o,c=Nl*e+kl*r*o;Sl.add(Mf(zf(a*a+u*u),c)),El=t,Nl=e,kl=r}function ql(t){return Sl=new T,Lf(t,$l),+Sl}var Ul=[null,null],Il={type:"LineString",coordinates:Ul};function Ol(t,n){return Ul[0]=t,Ul[1]=n,ql(Il)}var Bl={Feature:function(t,n){return Ll(t.geometry,n)},FeatureCollection:function(t,n){for(var e=t.features,r=-1,i=e.length;++r0&&(i=Ol(t[o],t[o-1]))>0&&e<=i&&r<=i&&(e+r-i)*(1-Math.pow((e-r)/i,2))df})).map(c)).concat(lt(Af(o/d)*d,i,d).filter((function(t){return xf(t%g)>df})).map(f))}return v.lines=function(){return _().map((function(t){return{type:"LineString",coordinates:t}}))},v.outline=function(){return{type:"Polygon",coordinates:[s(r).concat(l(a).slice(1),s(e).reverse().slice(1),l(u).reverse().slice(1))]}},v.extent=function(t){return arguments.length?v.extentMajor(t).extentMinor(t):v.extentMinor()},v.extentMajor=function(t){return arguments.length?(r=+t[0][0],e=+t[1][0],u=+t[0][1],a=+t[1][1],r>e&&(t=r,r=e,e=t),u>a&&(t=u,u=a,a=t),v.precision(y)):[[r,u],[e,a]]},v.extentMinor=function(e){return arguments.length?(n=+e[0][0],t=+e[1][0],o=+e[0][1],i=+e[1][1],n>t&&(e=n,n=t,t=e),o>i&&(e=o,o=i,i=e),v.precision(y)):[[n,o],[t,i]]},v.step=function(t){return arguments.length?v.stepMajor(t).stepMinor(t):v.stepMinor()},v.stepMajor=function(t){return arguments.length?(p=+t[0],g=+t[1],v):[p,g]},v.stepMinor=function(t){return arguments.length?(h=+t[0],d=+t[1],v):[h,d]},v.precision=function(h){return arguments.length?(y=+h,c=Wl(o,i,90),f=Zl(n,t,y),s=Wl(u,a,90),l=Zl(r,e,y),v):y},v.extentMajor([[-180,-90+df],[180,90-df]]).extentMinor([[-180,-80-df],[180,80+df]])}var Ql,Jl,th,nh,eh=t=>t,rh=new T,ih=new T,oh={point:qf,lineStart:qf,lineEnd:qf,polygonStart:function(){oh.lineStart=ah,oh.lineEnd=fh},polygonEnd:function(){oh.lineStart=oh.lineEnd=oh.point=qf,rh.add(xf(ih)),ih=new T},result:function(){var t=rh/2;return rh=new T,t}};function ah(){oh.point=uh}function uh(t,n){oh.point=ch,Ql=th=t,Jl=nh=n}function ch(t,n){ih.add(nh*t-th*n),th=t,nh=n}function fh(){ch(Ql,Jl)}var sh=oh,lh=1/0,hh=lh,dh=-lh,ph=dh,gh={point:function(t,n){tdh&&(dh=t);nph&&(ph=n)},lineStart:qf,lineEnd:qf,polygonStart:qf,polygonEnd:qf,result:function(){var t=[[lh,hh],[dh,ph]];return dh=ph=-(hh=lh=1/0),t}};var yh,vh,_h,bh,mh=gh,xh=0,wh=0,Mh=0,Th=0,Ah=0,Sh=0,Eh=0,Nh=0,kh=0,Ch={point:Ph,lineStart:zh,lineEnd:Rh,polygonStart:function(){Ch.lineStart=Fh,Ch.lineEnd=qh},polygonEnd:function(){Ch.point=Ph,Ch.lineStart=zh,Ch.lineEnd=Rh},result:function(){var t=kh?[Eh/kh,Nh/kh]:Sh?[Th/Sh,Ah/Sh]:Mh?[xh/Mh,wh/Mh]:[NaN,NaN];return xh=wh=Mh=Th=Ah=Sh=Eh=Nh=kh=0,t}};function Ph(t,n){xh+=t,wh+=n,++Mh}function zh(){Ch.point=$h}function $h(t,n){Ch.point=Dh,Ph(_h=t,bh=n)}function Dh(t,n){var e=t-_h,r=n-bh,i=zf(e*e+r*r);Th+=i*(_h+t)/2,Ah+=i*(bh+n)/2,Sh+=i,Ph(_h=t,bh=n)}function Rh(){Ch.point=Ph}function Fh(){Ch.point=Uh}function qh(){Ih(yh,vh)}function Uh(t,n){Ch.point=Ih,Ph(yh=_h=t,vh=bh=n)}function Ih(t,n){var e=t-_h,r=n-bh,i=zf(e*e+r*r);Th+=i*(_h+t)/2,Ah+=i*(bh+n)/2,Sh+=i,Eh+=(i=bh*t-_h*n)*(_h+t),Nh+=i*(bh+n),kh+=3*i,Ph(_h=t,bh=n)}var Oh=Ch;function Bh(t){this._context=t}Bh.prototype={_radius:4.5,pointRadius:function(t){return this._radius=t,this},polygonStart:function(){this._line=0},polygonEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){0===this._line&&this._context.closePath(),this._point=NaN},point:function(t,n){switch(this._point){case 0:this._context.moveTo(t,n),this._point=1;break;case 1:this._context.lineTo(t,n);break;default:this._context.moveTo(t+this._radius,n),this._context.arc(t,n,this._radius,0,_f)}},result:qf};var Yh,Lh,jh,Hh,Xh,Gh=new T,Vh={point:qf,lineStart:function(){Vh.point=Wh},lineEnd:function(){Yh&&Zh(Lh,jh),Vh.point=qf},polygonStart:function(){Yh=!0},polygonEnd:function(){Yh=null},result:function(){var t=+Gh;return Gh=new T,t}};function Wh(t,n){Vh.point=Zh,Lh=Hh=t,jh=Xh=n}function Zh(t,n){Hh-=t,Xh-=n,Gh.add(zf(Hh*Hh+Xh*Xh)),Hh=t,Xh=n}var Kh=Vh;let Qh,Jh,td,nd;class ed{constructor(t){this._append=null==t?rd:function(t){const n=Math.floor(t);if(!(n>=0))throw new RangeError(`invalid digits: ${t}`);if(n>15)return rd;if(n!==Qh){const t=10**n;Qh=n,Jh=function(n){let e=1;this._+=n[0];for(const r=n.length;e4*n&&g--){var m=a+h,x=u+d,w=c+p,M=zf(m*m+x*x+w*w),T=Rf(w/=M),A=xf(xf(w)-1)n||xf((v*k+_*C)/b-.5)>.3||a*h+u*d+c*p2?t[2]%360*mf:0,k()):[y*bf,v*bf,_*bf]},E.angle=function(t){return arguments.length?(b=t%360*mf,k()):b*bf},E.reflectX=function(t){return arguments.length?(m=t?-1:1,k()):m<0},E.reflectY=function(t){return arguments.length?(x=t?-1:1,k()):x<0},E.precision=function(t){return arguments.length?(a=dd(u,S=t*t),C()):zf(S)},E.fitExtent=function(t,n){return ud(E,t,n)},E.fitSize=function(t,n){return cd(E,t,n)},E.fitWidth=function(t,n){return fd(E,t,n)},E.fitHeight=function(t,n){return sd(E,t,n)},function(){return n=t.apply(this,arguments),E.invert=n.invert&&N,k()}}function _d(t){var n=0,e=gf/3,r=vd(t),i=r(n,e);return i.parallels=function(t){return arguments.length?r(n=t[0]*mf,e=t[1]*mf):[n*bf,e*bf]},i}function bd(t,n){var e=Cf(t),r=(e+Cf(n))/2;if(xf(r)0?n<-yf+df&&(n=-yf+df):n>yf-df&&(n=yf-df);var e=i/kf(Nd(n),r);return[e*Cf(r*t),i-e*Tf(r*t)]}return o.invert=function(t,n){var e=i-n,o=Pf(r)*zf(t*t+e*e),a=Mf(t,xf(e))*Pf(e);return e*r<0&&(a-=gf*Pf(t)*Pf(e)),[a/r,2*wf(kf(i/o,1/r))-yf]},o}function Cd(t,n){return[t,n]}function Pd(t,n){var e=Tf(t),r=t===n?Cf(t):(e-Tf(n))/(n-t),i=e/r+t;if(xf(r)=0;)n+=e[r].value;else n=1;t.value=n}function Gd(t,n){t instanceof Map?(t=[void 0,t],void 0===n&&(n=Wd)):void 0===n&&(n=Vd);for(var e,r,i,o,a,u=new Qd(t),c=[u];e=c.pop();)if((i=n(e.data))&&(a=(i=Array.from(i)).length))for(e.children=i,o=a-1;o>=0;--o)c.push(r=i[o]=new Qd(i[o])),r.parent=e,r.depth=e.depth+1;return u.eachBefore(Kd)}function Vd(t){return t.children}function Wd(t){return Array.isArray(t)?t[1]:null}function Zd(t){void 0!==t.data.value&&(t.value=t.data.value),t.data=t.data.data}function Kd(t){var n=0;do{t.height=n}while((t=t.parent)&&t.height<++n)}function Qd(t){this.data=t,this.depth=this.height=0,this.parent=null}function Jd(t){return null==t?null:tp(t)}function tp(t){if("function"!=typeof t)throw new Error;return t}function np(){return 0}function ep(t){return function(){return t}}qd.invert=function(t,n){for(var e,r=n,i=r*r,o=i*i*i,a=0;a<12&&(o=(i=(r-=e=(r*(zd+$d*i+o*(Dd+Rd*i))-n)/(zd+3*$d*i+o*(7*Dd+9*Rd*i)))*r)*i*i,!(xf(e)df&&--i>0);return[t/(.8707+(o=r*r)*(o*(o*o*o*(.003971-.001529*o)-.013791)-.131979)),r]},Od.invert=Md(Rf),Bd.invert=Md((function(t){return 2*wf(t)})),Yd.invert=function(t,n){return[-n,2*wf(Sf(t))-yf]},Qd.prototype=Gd.prototype={constructor:Qd,count:function(){return this.eachAfter(Xd)},each:function(t,n){let e=-1;for(const r of this)t.call(n,r,++e,this);return this},eachAfter:function(t,n){for(var e,r,i,o=this,a=[o],u=[],c=-1;o=a.pop();)if(u.push(o),e=o.children)for(r=0,i=e.length;r=0;--r)o.push(e[r]);return this},find:function(t,n){let e=-1;for(const r of this)if(t.call(n,r,++e,this))return r},sum:function(t){return this.eachAfter((function(n){for(var e=+t(n.data)||0,r=n.children,i=r&&r.length;--i>=0;)e+=r[i].value;n.value=e}))},sort:function(t){return this.eachBefore((function(n){n.children&&n.children.sort(t)}))},path:function(t){for(var n=this,e=function(t,n){if(t===n)return t;var e=t.ancestors(),r=n.ancestors(),i=null;t=e.pop(),n=r.pop();for(;t===n;)i=t,t=e.pop(),n=r.pop();return i}(n,t),r=[n];n!==e;)n=n.parent,r.push(n);for(var i=r.length;t!==e;)r.splice(i,0,t),t=t.parent;return r},ancestors:function(){for(var t=this,n=[t];t=t.parent;)n.push(t);return n},descendants:function(){return Array.from(this)},leaves:function(){var t=[];return this.eachBefore((function(n){n.children||t.push(n)})),t},links:function(){var t=this,n=[];return t.each((function(e){e!==t&&n.push({source:e.parent,target:e})})),n},copy:function(){return Gd(this).eachBefore(Zd)},[Symbol.iterator]:function*(){var t,n,e,r,i=this,o=[i];do{for(t=o.reverse(),o=[];i=t.pop();)if(yield i,n=i.children)for(e=0,r=n.length;e(t=(rp*t+ip)%op)/op}function up(t,n){for(var e,r,i=0,o=(t=function(t,n){let e,r,i=t.length;for(;i;)r=n()*i--|0,e=t[i],t[i]=t[r],t[r]=e;return t}(Array.from(t),n)).length,a=[];i0&&e*e>r*r+i*i}function lp(t,n){for(var e=0;e1e-6?(E+Math.sqrt(E*E-4*S*N))/(2*S):N/E);return{x:r+w+M*k,y:i+T+A*k,r:k}}function gp(t,n,e){var r,i,o,a,u=t.x-n.x,c=t.y-n.y,f=u*u+c*c;f?(i=n.r+e.r,i*=i,a=t.r+e.r,i>(a*=a)?(r=(f+a-i)/(2*f),o=Math.sqrt(Math.max(0,a/f-r*r)),e.x=t.x-r*u-o*c,e.y=t.y-r*c+o*u):(r=(f+i-a)/(2*f),o=Math.sqrt(Math.max(0,i/f-r*r)),e.x=n.x+r*u-o*c,e.y=n.y+r*c+o*u)):(e.x=n.x+e.r,e.y=n.y)}function yp(t,n){var e=t.r+n.r-1e-6,r=n.x-t.x,i=n.y-t.y;return e>0&&e*e>r*r+i*i}function vp(t){var n=t._,e=t.next._,r=n.r+e.r,i=(n.x*e.r+e.x*n.r)/r,o=(n.y*e.r+e.y*n.r)/r;return i*i+o*o}function _p(t){this._=t,this.next=null,this.previous=null}function bp(t,n){if(!(o=(t=function(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}(t)).length))return 0;var e,r,i,o,a,u,c,f,s,l,h;if((e=t[0]).x=0,e.y=0,!(o>1))return e.r;if(r=t[1],e.x=-r.r,r.x=e.r,r.y=0,!(o>2))return e.r+r.r;gp(r,e,i=t[2]),e=new _p(e),r=new _p(r),i=new _p(i),e.next=i.previous=r,r.next=e.previous=i,i.next=r.previous=e;t:for(c=3;c1&&!zp(t,n););return t.slice(0,n)}function zp(t,n){if("/"===t[n]){let e=0;for(;n>0&&"\\"===t[--n];)++e;if(0==(1&e))return!0}return!1}function $p(t,n){return t.parent===n.parent?1:2}function Dp(t){var n=t.children;return n?n[0]:t.t}function Rp(t){var n=t.children;return n?n[n.length-1]:t.t}function Fp(t,n,e){var r=e/(n.i-t.i);n.c-=r,n.s+=e,t.c+=r,n.z+=e,n.m+=e}function qp(t,n,e){return t.a.parent===n.parent?t.a:e}function Up(t,n){this._=t,this.parent=null,this.children=null,this.A=null,this.a=this,this.z=0,this.m=0,this.c=0,this.s=0,this.t=null,this.i=n}function Ip(t,n,e,r,i){for(var o,a=t.children,u=-1,c=a.length,f=t.value&&(i-e)/t.value;++uh&&(h=u),y=s*s*g,(d=Math.max(h/y,y/l))>p){s-=u;break}p=d}v.push(a={value:s,dice:c1?n:1)},e}(Op);var Lp=function t(n){function e(t,e,r,i,o){if((a=t._squarify)&&a.ratio===n)for(var a,u,c,f,s,l=-1,h=a.length,d=t.value;++l1?n:1)},e}(Op);function jp(t,n,e){return(n[0]-t[0])*(e[1]-t[1])-(n[1]-t[1])*(e[0]-t[0])}function Hp(t,n){return t[0]-n[0]||t[1]-n[1]}function Xp(t){const n=t.length,e=[0,1];let r,i=2;for(r=2;r1&&jp(t[e[i-2]],t[e[i-1]],t[r])<=0;)--i;e[i++]=r}return e.slice(0,i)}var Gp=Math.random,Vp=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,1===arguments.length?(e=t,t=0):e-=t,function(){return n()*e+t}}return e.source=t,e}(Gp),Wp=function t(n){function e(t,e){return arguments.length<2&&(e=t,t=0),t=Math.floor(t),e=Math.floor(e)-t,function(){return Math.floor(n()*e+t)}}return e.source=t,e}(Gp),Zp=function t(n){function e(t,e){var r,i;return t=null==t?0:+t,e=null==e?1:+e,function(){var o;if(null!=r)o=r,r=null;else do{r=2*n()-1,o=2*n()-1,i=r*r+o*o}while(!i||i>1);return t+e*o*Math.sqrt(-2*Math.log(i)/i)}}return e.source=t,e}(Gp),Kp=function t(n){var e=Zp.source(n);function r(){var t=e.apply(this,arguments);return function(){return Math.exp(t())}}return r.source=t,r}(Gp),Qp=function t(n){function e(t){return(t=+t)<=0?()=>0:function(){for(var e=0,r=t;r>1;--r)e+=n();return e+r*n()}}return e.source=t,e}(Gp),Jp=function t(n){var e=Qp.source(n);function r(t){if(0==(t=+t))return n;var r=e(t);return function(){return r()/t}}return r.source=t,r}(Gp),tg=function t(n){function e(t){return function(){return-Math.log1p(-n())/t}}return e.source=t,e}(Gp),ng=function t(n){function e(t){if((t=+t)<0)throw new RangeError("invalid alpha");return t=1/-t,function(){return Math.pow(1-n(),t)}}return e.source=t,e}(Gp),eg=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return function(){return Math.floor(n()+t)}}return e.source=t,e}(Gp),rg=function t(n){function e(t){if((t=+t)<0||t>1)throw new RangeError("invalid p");return 0===t?()=>1/0:1===t?()=>1:(t=Math.log1p(-t),function(){return 1+Math.floor(Math.log1p(-n())/t)})}return e.source=t,e}(Gp),ig=function t(n){var e=Zp.source(n)();function r(t,r){if((t=+t)<0)throw new RangeError("invalid k");if(0===t)return()=>0;if(r=null==r?1:+r,1===t)return()=>-Math.log1p(-n())*r;var i=(t<1?t+1:t)-1/3,o=1/(3*Math.sqrt(i)),a=t<1?()=>Math.pow(n(),1/t):()=>1;return function(){do{do{var t=e(),u=1+o*t}while(u<=0);u*=u*u;var c=1-n()}while(c>=1-.0331*t*t*t*t&&Math.log(c)>=.5*t*t+i*(1-u+Math.log(u)));return i*u*a()*r}}return r.source=t,r}(Gp),og=function t(n){var e=ig.source(n);function r(t,n){var r=e(t),i=e(n);return function(){var t=r();return 0===t?0:t/(t+i())}}return r.source=t,r}(Gp),ag=function t(n){var e=rg.source(n),r=og.source(n);function i(t,n){return t=+t,(n=+n)>=1?()=>t:n<=0?()=>0:function(){for(var i=0,o=t,a=n;o*a>16&&o*(1-a)>16;){var u=Math.floor((o+1)*a),c=r(u,o-u+1)();c<=a?(i+=u,o-=u,a=(a-c)/(1-c)):(o=u-1,a/=c)}for(var f=a<.5,s=e(f?a:1-a),l=s(),h=0;l<=o;++h)l+=s();return i+(f?h:o-h)}}return i.source=t,i}(Gp),ug=function t(n){function e(t,e,r){var i;return 0==(t=+t)?i=t=>-Math.log(t):(t=1/t,i=n=>Math.pow(n,t)),e=null==e?0:+e,r=null==r?1:+r,function(){return e+r*i(-Math.log1p(-n()))}}return e.source=t,e}(Gp),cg=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){return t+e*Math.tan(Math.PI*n())}}return e.source=t,e}(Gp),fg=function t(n){function e(t,e){return t=null==t?0:+t,e=null==e?1:+e,function(){var r=n();return t+e*Math.log(r/(1-r))}}return e.source=t,e}(Gp),sg=function t(n){var e=ig.source(n),r=ag.source(n);function i(t){return function(){for(var i=0,o=t;o>16;){var a=Math.floor(.875*o),u=e(a)();if(u>o)return i+r(a-1,o/u)();i+=a,o-=u}for(var c=-Math.log1p(-n()),f=0;c<=o;++f)c-=Math.log1p(-n());return i+f}}return i.source=t,i}(Gp);const lg=1/4294967296;function hg(t,n){switch(arguments.length){case 0:break;case 1:this.range(t);break;default:this.range(n).domain(t)}return this}function dg(t,n){switch(arguments.length){case 0:break;case 1:"function"==typeof t?this.interpolator(t):this.range(t);break;default:this.domain(t),"function"==typeof n?this.interpolator(n):this.range(n)}return this}const pg=Symbol("implicit");function gg(){var t=new InternMap,n=[],e=[],r=pg;function i(i){let o=t.get(i);if(void 0===o){if(r!==pg)return r;t.set(i,o=n.push(i)-1)}return e[o%e.length]}return i.domain=function(e){if(!arguments.length)return n.slice();n=[],t=new InternMap;for(const r of e)t.has(r)||t.set(r,n.push(r)-1);return i},i.range=function(t){return arguments.length?(e=Array.from(t),i):e.slice()},i.unknown=function(t){return arguments.length?(r=t,i):r},i.copy=function(){return gg(n,e).unknown(r)},hg.apply(i,arguments),i}function yg(){var t,n,e=gg().unknown(void 0),r=e.domain,i=e.range,o=0,a=1,u=!1,c=0,f=0,s=.5;function l(){var e=r().length,l=an&&(e=t,t=n,n=e),function(e){return Math.max(t,Math.min(n,e))}}(a[0],a[t-1])),r=t>2?Mg:wg,i=o=null,l}function l(n){return null==n||isNaN(n=+n)?e:(i||(i=r(a.map(t),u,c)))(t(f(n)))}return l.invert=function(e){return f(n((o||(o=r(u,a.map(t),Yr)))(e)))},l.domain=function(t){return arguments.length?(a=Array.from(t,_g),s()):a.slice()},l.range=function(t){return arguments.length?(u=Array.from(t),s()):u.slice()},l.rangeRound=function(t){return u=Array.from(t),c=Vr,s()},l.clamp=function(t){return arguments.length?(f=!!t||mg,s()):f!==mg},l.interpolate=function(t){return arguments.length?(c=t,s()):c},l.unknown=function(t){return arguments.length?(e=t,l):e},function(e,r){return t=e,n=r,s()}}function Sg(){return Ag()(mg,mg)}function Eg(n,e,r,i){var o,a=W(n,e,r);switch((i=Jc(null==i?",f":i)).type){case"s":var u=Math.max(Math.abs(n),Math.abs(e));return null!=i.precision||isNaN(o=lf(a,u))||(i.precision=o),t.formatPrefix(i,u);case"":case"e":case"g":case"p":case"r":null!=i.precision||isNaN(o=hf(a,Math.max(Math.abs(n),Math.abs(e))))||(i.precision=o-("e"===i.type));break;case"f":case"%":null!=i.precision||isNaN(o=sf(a))||(i.precision=o-2*("%"===i.type))}return t.format(i)}function Ng(t){var n=t.domain;return t.ticks=function(t){var e=n();return G(e[0],e[e.length-1],null==t?10:t)},t.tickFormat=function(t,e){var r=n();return Eg(r[0],r[r.length-1],null==t?10:t,e)},t.nice=function(e){null==e&&(e=10);var r,i,o=n(),a=0,u=o.length-1,c=o[a],f=o[u],s=10;for(f0;){if((i=V(c,f,e))===r)return o[a]=c,o[u]=f,n(o);if(i>0)c=Math.floor(c/i)*i,f=Math.ceil(f/i)*i;else{if(!(i<0))break;c=Math.ceil(c*i)/i,f=Math.floor(f*i)/i}r=i}return t},t}function kg(t,n){var e,r=0,i=(t=t.slice()).length-1,o=t[r],a=t[i];return a-t(-n,e)}function Fg(n){const e=n(Cg,Pg),r=e.domain;let i,o,a=10;function u(){return i=function(t){return t===Math.E?Math.log:10===t&&Math.log10||2===t&&Math.log2||(t=Math.log(t),n=>Math.log(n)/t)}(a),o=function(t){return 10===t?Dg:t===Math.E?Math.exp:n=>Math.pow(t,n)}(a),r()[0]<0?(i=Rg(i),o=Rg(o),n(zg,$g)):n(Cg,Pg),e}return e.base=function(t){return arguments.length?(a=+t,u()):a},e.domain=function(t){return arguments.length?(r(t),u()):r()},e.ticks=t=>{const n=r();let e=n[0],u=n[n.length-1];const c=u0){for(;l<=h;++l)for(f=1;fu)break;p.push(s)}}else for(;l<=h;++l)for(f=a-1;f>=1;--f)if(s=l>0?f/o(-l):f*o(l),!(su)break;p.push(s)}2*p.length{if(null==n&&(n=10),null==r&&(r=10===a?"s":","),"function"!=typeof r&&(a%1||null!=(r=Jc(r)).precision||(r.trim=!0),r=t.format(r)),n===1/0)return r;const u=Math.max(1,a*n/e.ticks().length);return t=>{let n=t/o(Math.round(i(t)));return n*ar(kg(r(),{floor:t=>o(Math.floor(i(t))),ceil:t=>o(Math.ceil(i(t)))})),e}function qg(t){return function(n){return Math.sign(n)*Math.log1p(Math.abs(n/t))}}function Ug(t){return function(n){return Math.sign(n)*Math.expm1(Math.abs(n))*t}}function Ig(t){var n=1,e=t(qg(n),Ug(n));return e.constant=function(e){return arguments.length?t(qg(n=+e),Ug(n)):n},Ng(e)}function Og(t){return function(n){return n<0?-Math.pow(-n,t):Math.pow(n,t)}}function Bg(t){return t<0?-Math.sqrt(-t):Math.sqrt(t)}function Yg(t){return t<0?-t*t:t*t}function Lg(t){var n=t(mg,mg),e=1;return n.exponent=function(n){return arguments.length?1===(e=+n)?t(mg,mg):.5===e?t(Bg,Yg):t(Og(e),Og(1/e)):e},Ng(n)}function jg(){var t=Lg(Ag());return t.copy=function(){return Tg(t,jg()).exponent(t.exponent())},hg.apply(t,arguments),t}function Hg(t){return Math.sign(t)*t*t}const Xg=new Date,Gg=new Date;function Vg(t,n,e,r){function i(n){return t(n=0===arguments.length?new Date:new Date(+n)),n}return i.floor=n=>(t(n=new Date(+n)),n),i.ceil=e=>(t(e=new Date(e-1)),n(e,1),t(e),e),i.round=t=>{const n=i(t),e=i.ceil(t);return t-n(n(t=new Date(+t),null==e?1:Math.floor(e)),t),i.range=(e,r,o)=>{const a=[];if(e=i.ceil(e),o=null==o?1:Math.floor(o),!(e0))return a;let u;do{a.push(u=new Date(+e)),n(e,o),t(e)}while(uVg((n=>{if(n>=n)for(;t(n),!e(n);)n.setTime(n-1)}),((t,r)=>{if(t>=t)if(r<0)for(;++r<=0;)for(;n(t,-1),!e(t););else for(;--r>=0;)for(;n(t,1),!e(t););})),e&&(i.count=(n,r)=>(Xg.setTime(+n),Gg.setTime(+r),t(Xg),t(Gg),Math.floor(e(Xg,Gg))),i.every=t=>(t=Math.floor(t),isFinite(t)&&t>0?t>1?i.filter(r?n=>r(n)%t==0:n=>i.count(0,n)%t==0):i:null)),i}const Wg=Vg((()=>{}),((t,n)=>{t.setTime(+t+n)}),((t,n)=>n-t));Wg.every=t=>(t=Math.floor(t),isFinite(t)&&t>0?t>1?Vg((n=>{n.setTime(Math.floor(n/t)*t)}),((n,e)=>{n.setTime(+n+e*t)}),((n,e)=>(e-n)/t)):Wg:null);const Zg=Wg.range,Kg=1e3,Qg=6e4,Jg=36e5,ty=864e5,ny=6048e5,ey=2592e6,ry=31536e6,iy=Vg((t=>{t.setTime(t-t.getMilliseconds())}),((t,n)=>{t.setTime(+t+n*Kg)}),((t,n)=>(n-t)/Kg),(t=>t.getUTCSeconds())),oy=iy.range,ay=Vg((t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Kg)}),((t,n)=>{t.setTime(+t+n*Qg)}),((t,n)=>(n-t)/Qg),(t=>t.getMinutes())),uy=ay.range,cy=Vg((t=>{t.setUTCSeconds(0,0)}),((t,n)=>{t.setTime(+t+n*Qg)}),((t,n)=>(n-t)/Qg),(t=>t.getUTCMinutes())),fy=cy.range,sy=Vg((t=>{t.setTime(t-t.getMilliseconds()-t.getSeconds()*Kg-t.getMinutes()*Qg)}),((t,n)=>{t.setTime(+t+n*Jg)}),((t,n)=>(n-t)/Jg),(t=>t.getHours())),ly=sy.range,hy=Vg((t=>{t.setUTCMinutes(0,0,0)}),((t,n)=>{t.setTime(+t+n*Jg)}),((t,n)=>(n-t)/Jg),(t=>t.getUTCHours())),dy=hy.range,py=Vg((t=>t.setHours(0,0,0,0)),((t,n)=>t.setDate(t.getDate()+n)),((t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qg)/ty),(t=>t.getDate()-1)),gy=py.range,yy=Vg((t=>{t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+n)}),((t,n)=>(n-t)/ty),(t=>t.getUTCDate()-1)),vy=yy.range,_y=Vg((t=>{t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+n)}),((t,n)=>(n-t)/ty),(t=>Math.floor(t/ty))),by=_y.range;function my(t){return Vg((n=>{n.setDate(n.getDate()-(n.getDay()+7-t)%7),n.setHours(0,0,0,0)}),((t,n)=>{t.setDate(t.getDate()+7*n)}),((t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Qg)/ny))}const xy=my(0),wy=my(1),My=my(2),Ty=my(3),Ay=my(4),Sy=my(5),Ey=my(6),Ny=xy.range,ky=wy.range,Cy=My.range,Py=Ty.range,zy=Ay.range,$y=Sy.range,Dy=Ey.range;function Ry(t){return Vg((n=>{n.setUTCDate(n.getUTCDate()-(n.getUTCDay()+7-t)%7),n.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCDate(t.getUTCDate()+7*n)}),((t,n)=>(n-t)/ny))}const Fy=Ry(0),qy=Ry(1),Uy=Ry(2),Iy=Ry(3),Oy=Ry(4),By=Ry(5),Yy=Ry(6),Ly=Fy.range,jy=qy.range,Hy=Uy.range,Xy=Iy.range,Gy=Oy.range,Vy=By.range,Wy=Yy.range,Zy=Vg((t=>{t.setDate(1),t.setHours(0,0,0,0)}),((t,n)=>{t.setMonth(t.getMonth()+n)}),((t,n)=>n.getMonth()-t.getMonth()+12*(n.getFullYear()-t.getFullYear())),(t=>t.getMonth())),Ky=Zy.range,Qy=Vg((t=>{t.setUTCDate(1),t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCMonth(t.getUTCMonth()+n)}),((t,n)=>n.getUTCMonth()-t.getUTCMonth()+12*(n.getUTCFullYear()-t.getUTCFullYear())),(t=>t.getUTCMonth())),Jy=Qy.range,tv=Vg((t=>{t.setMonth(0,1),t.setHours(0,0,0,0)}),((t,n)=>{t.setFullYear(t.getFullYear()+n)}),((t,n)=>n.getFullYear()-t.getFullYear()),(t=>t.getFullYear()));tv.every=t=>isFinite(t=Math.floor(t))&&t>0?Vg((n=>{n.setFullYear(Math.floor(n.getFullYear()/t)*t),n.setMonth(0,1),n.setHours(0,0,0,0)}),((n,e)=>{n.setFullYear(n.getFullYear()+e*t)})):null;const nv=tv.range,ev=Vg((t=>{t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)}),((t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n)}),((t,n)=>n.getUTCFullYear()-t.getUTCFullYear()),(t=>t.getUTCFullYear()));ev.every=t=>isFinite(t=Math.floor(t))&&t>0?Vg((n=>{n.setUTCFullYear(Math.floor(n.getUTCFullYear()/t)*t),n.setUTCMonth(0,1),n.setUTCHours(0,0,0,0)}),((n,e)=>{n.setUTCFullYear(n.getUTCFullYear()+e*t)})):null;const rv=ev.range;function iv(t,n,e,i,o,a){const u=[[iy,1,Kg],[iy,5,5e3],[iy,15,15e3],[iy,30,3e4],[a,1,Qg],[a,5,3e5],[a,15,9e5],[a,30,18e5],[o,1,Jg],[o,3,108e5],[o,6,216e5],[o,12,432e5],[i,1,ty],[i,2,1728e5],[e,1,ny],[n,1,ey],[n,3,7776e6],[t,1,ry]];function c(n,e,i){const o=Math.abs(e-n)/i,a=r((([,,t])=>t)).right(u,o);if(a===u.length)return t.every(W(n/ry,e/ry,i));if(0===a)return Wg.every(Math.max(W(n,e,i),1));const[c,f]=u[o/u[a-1][2]=12)]},q:function(t){return 1+~~(t.getMonth()/3)},Q:k_,s:C_,S:Zv,u:Kv,U:Qv,V:t_,w:n_,W:e_,x:null,X:null,y:r_,Y:o_,Z:u_,"%":N_},m={a:function(t){return a[t.getUTCDay()]},A:function(t){return o[t.getUTCDay()]},b:function(t){return c[t.getUTCMonth()]},B:function(t){return u[t.getUTCMonth()]},c:null,d:c_,e:c_,f:d_,g:T_,G:S_,H:f_,I:s_,j:l_,L:h_,m:p_,M:g_,p:function(t){return i[+(t.getUTCHours()>=12)]},q:function(t){return 1+~~(t.getUTCMonth()/3)},Q:k_,s:C_,S:y_,u:v_,U:__,V:m_,w:x_,W:w_,x:null,X:null,y:M_,Y:A_,Z:E_,"%":N_},x={a:function(t,n,e){var r=d.exec(n.slice(e));return r?(t.w=p.get(r[0].toLowerCase()),e+r[0].length):-1},A:function(t,n,e){var r=l.exec(n.slice(e));return r?(t.w=h.get(r[0].toLowerCase()),e+r[0].length):-1},b:function(t,n,e){var r=v.exec(n.slice(e));return r?(t.m=_.get(r[0].toLowerCase()),e+r[0].length):-1},B:function(t,n,e){var r=g.exec(n.slice(e));return r?(t.m=y.get(r[0].toLowerCase()),e+r[0].length):-1},c:function(t,e,r){return T(t,n,e,r)},d:zv,e:zv,f:Uv,g:Nv,G:Ev,H:Dv,I:Dv,j:$v,L:qv,m:Pv,M:Rv,p:function(t,n,e){var r=f.exec(n.slice(e));return r?(t.p=s.get(r[0].toLowerCase()),e+r[0].length):-1},q:Cv,Q:Ov,s:Bv,S:Fv,u:Mv,U:Tv,V:Av,w:wv,W:Sv,x:function(t,n,r){return T(t,e,n,r)},X:function(t,n,e){return T(t,r,n,e)},y:Nv,Y:Ev,Z:kv,"%":Iv};function w(t,n){return function(e){var r,i,o,a=[],u=-1,c=0,f=t.length;for(e instanceof Date||(e=new Date(+e));++u53)return null;"w"in o||(o.w=1),"Z"in o?(i=(r=sv(lv(o.y,0,1))).getUTCDay(),r=i>4||0===i?qy.ceil(r):qy(r),r=yy.offset(r,7*(o.V-1)),o.y=r.getUTCFullYear(),o.m=r.getUTCMonth(),o.d=r.getUTCDate()+(o.w+6)%7):(i=(r=fv(lv(o.y,0,1))).getDay(),r=i>4||0===i?wy.ceil(r):wy(r),r=py.offset(r,7*(o.V-1)),o.y=r.getFullYear(),o.m=r.getMonth(),o.d=r.getDate()+(o.w+6)%7)}else("W"in o||"U"in o)&&("w"in o||(o.w="u"in o?o.u%7:"W"in o?1:0),i="Z"in o?sv(lv(o.y,0,1)).getUTCDay():fv(lv(o.y,0,1)).getDay(),o.m=0,o.d="W"in o?(o.w+6)%7+7*o.W-(i+5)%7:o.w+7*o.U-(i+6)%7);return"Z"in o?(o.H+=o.Z/100|0,o.M+=o.Z%100,sv(o)):fv(o)}}function T(t,n,e,r){for(var i,o,a=0,u=n.length,c=e.length;a=c)return-1;if(37===(i=n.charCodeAt(a++))){if(i=n.charAt(a++),!(o=x[i in pv?n.charAt(a++):i])||(r=o(t,e,r))<0)return-1}else if(i!=e.charCodeAt(r++))return-1}return r}return b.x=w(e,b),b.X=w(r,b),b.c=w(n,b),m.x=w(e,m),m.X=w(r,m),m.c=w(n,m),{format:function(t){var n=w(t+="",b);return n.toString=function(){return t},n},parse:function(t){var n=M(t+="",!1);return n.toString=function(){return t},n},utcFormat:function(t){var n=w(t+="",m);return n.toString=function(){return t},n},utcParse:function(t){var n=M(t+="",!0);return n.toString=function(){return t},n}}}var dv,pv={"-":"",_:" ",0:"0"},gv=/^\s*\d+/,yv=/^%/,vv=/[\\^$*+?|[\]().{}]/g;function _v(t,n,e){var r=t<0?"-":"",i=(r?-t:t)+"",o=i.length;return r+(o[t.toLowerCase(),n])))}function wv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.w=+r[0],e+r[0].length):-1}function Mv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.u=+r[0],e+r[0].length):-1}function Tv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.U=+r[0],e+r[0].length):-1}function Av(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.V=+r[0],e+r[0].length):-1}function Sv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.W=+r[0],e+r[0].length):-1}function Ev(t,n,e){var r=gv.exec(n.slice(e,e+4));return r?(t.y=+r[0],e+r[0].length):-1}function Nv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.y=+r[0]+(+r[0]>68?1900:2e3),e+r[0].length):-1}function kv(t,n,e){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(n.slice(e,e+6));return r?(t.Z=r[1]?0:-(r[2]+(r[3]||"00")),e+r[0].length):-1}function Cv(t,n,e){var r=gv.exec(n.slice(e,e+1));return r?(t.q=3*r[0]-3,e+r[0].length):-1}function Pv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.m=r[0]-1,e+r[0].length):-1}function zv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.d=+r[0],e+r[0].length):-1}function $v(t,n,e){var r=gv.exec(n.slice(e,e+3));return r?(t.m=0,t.d=+r[0],e+r[0].length):-1}function Dv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.H=+r[0],e+r[0].length):-1}function Rv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.M=+r[0],e+r[0].length):-1}function Fv(t,n,e){var r=gv.exec(n.slice(e,e+2));return r?(t.S=+r[0],e+r[0].length):-1}function qv(t,n,e){var r=gv.exec(n.slice(e,e+3));return r?(t.L=+r[0],e+r[0].length):-1}function Uv(t,n,e){var r=gv.exec(n.slice(e,e+6));return r?(t.L=Math.floor(r[0]/1e3),e+r[0].length):-1}function Iv(t,n,e){var r=yv.exec(n.slice(e,e+1));return r?e+r[0].length:-1}function Ov(t,n,e){var r=gv.exec(n.slice(e));return r?(t.Q=+r[0],e+r[0].length):-1}function Bv(t,n,e){var r=gv.exec(n.slice(e));return r?(t.s=+r[0],e+r[0].length):-1}function Yv(t,n){return _v(t.getDate(),n,2)}function Lv(t,n){return _v(t.getHours(),n,2)}function jv(t,n){return _v(t.getHours()%12||12,n,2)}function Hv(t,n){return _v(1+py.count(tv(t),t),n,3)}function Xv(t,n){return _v(t.getMilliseconds(),n,3)}function Gv(t,n){return Xv(t,n)+"000"}function Vv(t,n){return _v(t.getMonth()+1,n,2)}function Wv(t,n){return _v(t.getMinutes(),n,2)}function Zv(t,n){return _v(t.getSeconds(),n,2)}function Kv(t){var n=t.getDay();return 0===n?7:n}function Qv(t,n){return _v(xy.count(tv(t)-1,t),n,2)}function Jv(t){var n=t.getDay();return n>=4||0===n?Ay(t):Ay.ceil(t)}function t_(t,n){return t=Jv(t),_v(Ay.count(tv(t),t)+(4===tv(t).getDay()),n,2)}function n_(t){return t.getDay()}function e_(t,n){return _v(wy.count(tv(t)-1,t),n,2)}function r_(t,n){return _v(t.getFullYear()%100,n,2)}function i_(t,n){return _v((t=Jv(t)).getFullYear()%100,n,2)}function o_(t,n){return _v(t.getFullYear()%1e4,n,4)}function a_(t,n){var e=t.getDay();return _v((t=e>=4||0===e?Ay(t):Ay.ceil(t)).getFullYear()%1e4,n,4)}function u_(t){var n=t.getTimezoneOffset();return(n>0?"-":(n*=-1,"+"))+_v(n/60|0,"0",2)+_v(n%60,"0",2)}function c_(t,n){return _v(t.getUTCDate(),n,2)}function f_(t,n){return _v(t.getUTCHours(),n,2)}function s_(t,n){return _v(t.getUTCHours()%12||12,n,2)}function l_(t,n){return _v(1+yy.count(ev(t),t),n,3)}function h_(t,n){return _v(t.getUTCMilliseconds(),n,3)}function d_(t,n){return h_(t,n)+"000"}function p_(t,n){return _v(t.getUTCMonth()+1,n,2)}function g_(t,n){return _v(t.getUTCMinutes(),n,2)}function y_(t,n){return _v(t.getUTCSeconds(),n,2)}function v_(t){var n=t.getUTCDay();return 0===n?7:n}function __(t,n){return _v(Fy.count(ev(t)-1,t),n,2)}function b_(t){var n=t.getUTCDay();return n>=4||0===n?Oy(t):Oy.ceil(t)}function m_(t,n){return t=b_(t),_v(Oy.count(ev(t),t)+(4===ev(t).getUTCDay()),n,2)}function x_(t){return t.getUTCDay()}function w_(t,n){return _v(qy.count(ev(t)-1,t),n,2)}function M_(t,n){return _v(t.getUTCFullYear()%100,n,2)}function T_(t,n){return _v((t=b_(t)).getUTCFullYear()%100,n,2)}function A_(t,n){return _v(t.getUTCFullYear()%1e4,n,4)}function S_(t,n){var e=t.getUTCDay();return _v((t=e>=4||0===e?Oy(t):Oy.ceil(t)).getUTCFullYear()%1e4,n,4)}function E_(){return"+0000"}function N_(){return"%"}function k_(t){return+t}function C_(t){return Math.floor(+t/1e3)}function P_(n){return dv=hv(n),t.timeFormat=dv.format,t.timeParse=dv.parse,t.utcFormat=dv.utcFormat,t.utcParse=dv.utcParse,dv}t.timeFormat=void 0,t.timeParse=void 0,t.utcFormat=void 0,t.utcParse=void 0,P_({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});var z_="%Y-%m-%dT%H:%M:%S.%LZ";var $_=Date.prototype.toISOString?function(t){return t.toISOString()}:t.utcFormat(z_),D_=$_;var R_=+new Date("2000-01-01T00:00:00.000Z")?function(t){var n=new Date(t);return isNaN(n)?null:n}:t.utcParse(z_),F_=R_;function q_(t){return new Date(t)}function U_(t){return t instanceof Date?+t:+new Date(+t)}function I_(t,n,e,r,i,o,a,u,c,f){var s=Sg(),l=s.invert,h=s.domain,d=f(".%L"),p=f(":%S"),g=f("%I:%M"),y=f("%I %p"),v=f("%a %d"),_=f("%b %d"),b=f("%B"),m=f("%Y");function x(t){return(c(t)Fr(t[t.length-1]),rb=new Array(3).concat("d8b365f5f5f55ab4ac","a6611adfc27d80cdc1018571","a6611adfc27df5f5f580cdc1018571","8c510ad8b365f6e8c3c7eae55ab4ac01665e","8c510ad8b365f6e8c3f5f5f5c7eae55ab4ac01665e","8c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e","8c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e","5430058c510abf812ddfc27df6e8c3c7eae580cdc135978f01665e003c30","5430058c510abf812ddfc27df6e8c3f5f5f5c7eae580cdc135978f01665e003c30").map(H_),ib=eb(rb),ob=new Array(3).concat("af8dc3f7f7f77fbf7b","7b3294c2a5cfa6dba0008837","7b3294c2a5cff7f7f7a6dba0008837","762a83af8dc3e7d4e8d9f0d37fbf7b1b7837","762a83af8dc3e7d4e8f7f7f7d9f0d37fbf7b1b7837","762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b7837","762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b7837","40004b762a839970abc2a5cfe7d4e8d9f0d3a6dba05aae611b783700441b","40004b762a839970abc2a5cfe7d4e8f7f7f7d9f0d3a6dba05aae611b783700441b").map(H_),ab=eb(ob),ub=new Array(3).concat("e9a3c9f7f7f7a1d76a","d01c8bf1b6dab8e1864dac26","d01c8bf1b6daf7f7f7b8e1864dac26","c51b7de9a3c9fde0efe6f5d0a1d76a4d9221","c51b7de9a3c9fde0eff7f7f7e6f5d0a1d76a4d9221","c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221","c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221","8e0152c51b7dde77aef1b6dafde0efe6f5d0b8e1867fbc414d9221276419","8e0152c51b7dde77aef1b6dafde0eff7f7f7e6f5d0b8e1867fbc414d9221276419").map(H_),cb=eb(ub),fb=new Array(3).concat("998ec3f7f7f7f1a340","5e3c99b2abd2fdb863e66101","5e3c99b2abd2f7f7f7fdb863e66101","542788998ec3d8daebfee0b6f1a340b35806","542788998ec3d8daebf7f7f7fee0b6f1a340b35806","5427888073acb2abd2d8daebfee0b6fdb863e08214b35806","5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b35806","2d004b5427888073acb2abd2d8daebfee0b6fdb863e08214b358067f3b08","2d004b5427888073acb2abd2d8daebf7f7f7fee0b6fdb863e08214b358067f3b08").map(H_),sb=eb(fb),lb=new Array(3).concat("ef8a62f7f7f767a9cf","ca0020f4a58292c5de0571b0","ca0020f4a582f7f7f792c5de0571b0","b2182bef8a62fddbc7d1e5f067a9cf2166ac","b2182bef8a62fddbc7f7f7f7d1e5f067a9cf2166ac","b2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac","b2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac","67001fb2182bd6604df4a582fddbc7d1e5f092c5de4393c32166ac053061","67001fb2182bd6604df4a582fddbc7f7f7f7d1e5f092c5de4393c32166ac053061").map(H_),hb=eb(lb),db=new Array(3).concat("ef8a62ffffff999999","ca0020f4a582bababa404040","ca0020f4a582ffffffbababa404040","b2182bef8a62fddbc7e0e0e09999994d4d4d","b2182bef8a62fddbc7ffffffe0e0e09999994d4d4d","b2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d","b2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d","67001fb2182bd6604df4a582fddbc7e0e0e0bababa8787874d4d4d1a1a1a","67001fb2182bd6604df4a582fddbc7ffffffe0e0e0bababa8787874d4d4d1a1a1a").map(H_),pb=eb(db),gb=new Array(3).concat("fc8d59ffffbf91bfdb","d7191cfdae61abd9e92c7bb6","d7191cfdae61ffffbfabd9e92c7bb6","d73027fc8d59fee090e0f3f891bfdb4575b4","d73027fc8d59fee090ffffbfe0f3f891bfdb4575b4","d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4","d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4","a50026d73027f46d43fdae61fee090e0f3f8abd9e974add14575b4313695","a50026d73027f46d43fdae61fee090ffffbfe0f3f8abd9e974add14575b4313695").map(H_),yb=eb(gb),vb=new Array(3).concat("fc8d59ffffbf91cf60","d7191cfdae61a6d96a1a9641","d7191cfdae61ffffbfa6d96a1a9641","d73027fc8d59fee08bd9ef8b91cf601a9850","d73027fc8d59fee08bffffbfd9ef8b91cf601a9850","d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850","d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850","a50026d73027f46d43fdae61fee08bd9ef8ba6d96a66bd631a9850006837","a50026d73027f46d43fdae61fee08bffffbfd9ef8ba6d96a66bd631a9850006837").map(H_),_b=eb(vb),bb=new Array(3).concat("fc8d59ffffbf99d594","d7191cfdae61abdda42b83ba","d7191cfdae61ffffbfabdda42b83ba","d53e4ffc8d59fee08be6f59899d5943288bd","d53e4ffc8d59fee08bffffbfe6f59899d5943288bd","d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd","d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd","9e0142d53e4ff46d43fdae61fee08be6f598abdda466c2a53288bd5e4fa2","9e0142d53e4ff46d43fdae61fee08bffffbfe6f598abdda466c2a53288bd5e4fa2").map(H_),mb=eb(bb),xb=new Array(3).concat("e5f5f999d8c92ca25f","edf8fbb2e2e266c2a4238b45","edf8fbb2e2e266c2a42ca25f006d2c","edf8fbccece699d8c966c2a42ca25f006d2c","edf8fbccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45005824","f7fcfde5f5f9ccece699d8c966c2a441ae76238b45006d2c00441b").map(H_),wb=eb(xb),Mb=new Array(3).concat("e0ecf49ebcda8856a7","edf8fbb3cde38c96c688419d","edf8fbb3cde38c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68856a7810f7c","edf8fbbfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d6e016b","f7fcfde0ecf4bfd3e69ebcda8c96c68c6bb188419d810f7c4d004b").map(H_),Tb=eb(Mb),Ab=new Array(3).concat("e0f3dba8ddb543a2ca","f0f9e8bae4bc7bccc42b8cbe","f0f9e8bae4bc7bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc443a2ca0868ac","f0f9e8ccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe08589e","f7fcf0e0f3dbccebc5a8ddb57bccc44eb3d32b8cbe0868ac084081").map(H_),Sb=eb(Ab),Eb=new Array(3).concat("fee8c8fdbb84e34a33","fef0d9fdcc8afc8d59d7301f","fef0d9fdcc8afc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59e34a33b30000","fef0d9fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301f990000","fff7ecfee8c8fdd49efdbb84fc8d59ef6548d7301fb300007f0000").map(H_),Nb=eb(Eb),kb=new Array(3).concat("ece2f0a6bddb1c9099","f6eff7bdc9e167a9cf02818a","f6eff7bdc9e167a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf1c9099016c59","f6eff7d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016450","fff7fbece2f0d0d1e6a6bddb67a9cf3690c002818a016c59014636").map(H_),Cb=eb(kb),Pb=new Array(3).concat("ece7f2a6bddb2b8cbe","f1eef6bdc9e174a9cf0570b0","f1eef6bdc9e174a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf2b8cbe045a8d","f1eef6d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0034e7b","fff7fbece7f2d0d1e6a6bddb74a9cf3690c00570b0045a8d023858").map(H_),zb=eb(Pb),$b=new Array(3).concat("e7e1efc994c7dd1c77","f1eef6d7b5d8df65b0ce1256","f1eef6d7b5d8df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0dd1c77980043","f1eef6d4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125691003f","f7f4f9e7e1efd4b9dac994c7df65b0e7298ace125698004367001f").map(H_),Db=eb($b),Rb=new Array(3).concat("fde0ddfa9fb5c51b8a","feebe2fbb4b9f768a1ae017e","feebe2fbb4b9f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1c51b8a7a0177","feebe2fcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a0177","fff7f3fde0ddfcc5c0fa9fb5f768a1dd3497ae017e7a017749006a").map(H_),Fb=eb(Rb),qb=new Array(3).concat("edf8b17fcdbb2c7fb8","ffffcca1dab441b6c4225ea8","ffffcca1dab441b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c42c7fb8253494","ffffccc7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea80c2c84","ffffd9edf8b1c7e9b47fcdbb41b6c41d91c0225ea8253494081d58").map(H_),Ub=eb(qb),Ib=new Array(3).concat("f7fcb9addd8e31a354","ffffccc2e69978c679238443","ffffccc2e69978c67931a354006837","ffffccd9f0a3addd8e78c67931a354006837","ffffccd9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443005a32","ffffe5f7fcb9d9f0a3addd8e78c67941ab5d238443006837004529").map(H_),Ob=eb(Ib),Bb=new Array(3).concat("fff7bcfec44fd95f0e","ffffd4fed98efe9929cc4c02","ffffd4fed98efe9929d95f0e993404","ffffd4fee391fec44ffe9929d95f0e993404","ffffd4fee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c028c2d04","ffffe5fff7bcfee391fec44ffe9929ec7014cc4c02993404662506").map(H_),Yb=eb(Bb),Lb=new Array(3).concat("ffeda0feb24cf03b20","ffffb2fecc5cfd8d3ce31a1c","ffffb2fecc5cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cf03b20bd0026","ffffb2fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cb10026","ffffccffeda0fed976feb24cfd8d3cfc4e2ae31a1cbd0026800026").map(H_),jb=eb(Lb),Hb=new Array(3).concat("deebf79ecae13182bd","eff3ffbdd7e76baed62171b5","eff3ffbdd7e76baed63182bd08519c","eff3ffc6dbef9ecae16baed63182bd08519c","eff3ffc6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b5084594","f7fbffdeebf7c6dbef9ecae16baed64292c62171b508519c08306b").map(H_),Xb=eb(Hb),Gb=new Array(3).concat("e5f5e0a1d99b31a354","edf8e9bae4b374c476238b45","edf8e9bae4b374c47631a354006d2c","edf8e9c7e9c0a1d99b74c47631a354006d2c","edf8e9c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45005a32","f7fcf5e5f5e0c7e9c0a1d99b74c47641ab5d238b45006d2c00441b").map(H_),Vb=eb(Gb),Wb=new Array(3).concat("f0f0f0bdbdbd636363","f7f7f7cccccc969696525252","f7f7f7cccccc969696636363252525","f7f7f7d9d9d9bdbdbd969696636363252525","f7f7f7d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525","fffffff0f0f0d9d9d9bdbdbd969696737373525252252525000000").map(H_),Zb=eb(Wb),Kb=new Array(3).concat("efedf5bcbddc756bb1","f2f0f7cbc9e29e9ac86a51a3","f2f0f7cbc9e29e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8756bb154278f","f2f0f7dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a34a1486","fcfbfdefedf5dadaebbcbddc9e9ac8807dba6a51a354278f3f007d").map(H_),Qb=eb(Kb),Jb=new Array(3).concat("fee0d2fc9272de2d26","fee5d9fcae91fb6a4acb181d","fee5d9fcae91fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4ade2d26a50f15","fee5d9fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181d99000d","fff5f0fee0d2fcbba1fc9272fb6a4aef3b2ccb181da50f1567000d").map(H_),tm=eb(Jb),nm=new Array(3).concat("fee6cefdae6be6550d","feeddefdbe85fd8d3cd94701","feeddefdbe85fd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3ce6550da63603","feeddefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d948018c2d04","fff5ebfee6cefdd0a2fdae6bfd8d3cf16913d94801a636037f2704").map(H_),em=eb(nm);var rm=hi(Tr(300,.5,0),Tr(-240,.5,1)),im=hi(Tr(-100,.75,.35),Tr(80,1.5,.8)),om=hi(Tr(260,.75,.35),Tr(80,1.5,.8)),am=Tr();var um=Fe(),cm=Math.PI/3,fm=2*Math.PI/3;function sm(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}}var lm=sm(H_("44015444025645045745055946075a46085c460a5d460b5e470d60470e6147106347116447136548146748166848176948186a481a6c481b6d481c6e481d6f481f70482071482173482374482475482576482677482878482979472a7a472c7a472d7b472e7c472f7d46307e46327e46337f463480453581453781453882443983443a83443b84433d84433e85423f854240864241864142874144874045884046883f47883f48893e49893e4a893e4c8a3d4d8a3d4e8a3c4f8a3c508b3b518b3b528b3a538b3a548c39558c39568c38588c38598c375a8c375b8d365c8d365d8d355e8d355f8d34608d34618d33628d33638d32648e32658e31668e31678e31688e30698e306a8e2f6b8e2f6c8e2e6d8e2e6e8e2e6f8e2d708e2d718e2c718e2c728e2c738e2b748e2b758e2a768e2a778e2a788e29798e297a8e297b8e287c8e287d8e277e8e277f8e27808e26818e26828e26828e25838e25848e25858e24868e24878e23888e23898e238a8d228b8d228c8d228d8d218e8d218f8d21908d21918c20928c20928c20938c1f948c1f958b1f968b1f978b1f988b1f998a1f9a8a1e9b8a1e9c891e9d891f9e891f9f881fa0881fa1881fa1871fa28720a38620a48621a58521a68522a78522a88423a98324aa8325ab8225ac8226ad8127ad8128ae8029af7f2ab07f2cb17e2db27d2eb37c2fb47c31b57b32b67a34b67935b77937b87838b9773aba763bbb753dbc743fbc7340bd7242be7144bf7046c06f48c16e4ac16d4cc26c4ec36b50c46a52c56954c56856c66758c7655ac8645cc8635ec96260ca6063cb5f65cb5e67cc5c69cd5b6ccd5a6ece5870cf5773d05675d05477d1537ad1517cd2507fd34e81d34d84d44b86d54989d5488bd6468ed64590d74393d74195d84098d83e9bd93c9dd93ba0da39a2da37a5db36a8db34aadc32addc30b0dd2fb2dd2db5de2bb8de29bade28bddf26c0df25c2df23c5e021c8e020cae11fcde11dd0e11cd2e21bd5e21ad8e219dae319dde318dfe318e2e418e5e419e7e419eae51aece51befe51cf1e51df4e61ef6e620f8e621fbe723fde725")),hm=sm(H_("00000401000501010601010802010902020b02020d03030f03031204041405041606051806051a07061c08071e0907200a08220b09240c09260d0a290e0b2b100b2d110c2f120d31130d34140e36150e38160f3b180f3d19103f1a10421c10441d11471e114920114b21114e22115024125325125527125829115a2a115c2c115f2d11612f116331116533106734106936106b38106c390f6e3b0f703d0f713f0f72400f74420f75440f764510774710784910784a10794c117a4e117b4f127b51127c52137c54137d56147d57157e59157e5a167e5c167f5d177f5f187f601880621980641a80651a80671b80681c816a1c816b1d816d1d816e1e81701f81721f817320817521817621817822817922827b23827c23827e24828025828125818326818426818627818827818928818b29818c29818e2a81902a81912b81932b80942c80962c80982d80992d809b2e7f9c2e7f9e2f7fa02f7fa1307ea3307ea5317ea6317da8327daa337dab337cad347cae347bb0357bb2357bb3367ab5367ab73779b83779ba3878bc3978bd3977bf3a77c03a76c23b75c43c75c53c74c73d73c83e73ca3e72cc3f71cd4071cf4070d0416fd2426fd3436ed5446dd6456cd8456cd9466bdb476adc4869de4968df4a68e04c67e24d66e34e65e44f64e55064e75263e85362e95462ea5661eb5760ec5860ed5a5fee5b5eef5d5ef05f5ef1605df2625df2645cf3655cf4675cf4695cf56b5cf66c5cf66e5cf7705cf7725cf8745cf8765cf9785df9795df97b5dfa7d5efa7f5efa815ffb835ffb8560fb8761fc8961fc8a62fc8c63fc8e64fc9065fd9266fd9467fd9668fd9869fd9a6afd9b6bfe9d6cfe9f6dfea16efea36ffea571fea772fea973feaa74feac76feae77feb078feb27afeb47bfeb67cfeb77efeb97ffebb81febd82febf84fec185fec287fec488fec68afec88cfeca8dfecc8ffecd90fecf92fed194fed395fed597fed799fed89afdda9cfddc9efddea0fde0a1fde2a3fde3a5fde5a7fde7a9fde9aafdebacfcecaefceeb0fcf0b2fcf2b4fcf4b6fcf6b8fcf7b9fcf9bbfcfbbdfcfdbf")),dm=sm(H_("00000401000501010601010802010a02020c02020e03021004031204031405041706041907051b08051d09061f0a07220b07240c08260d08290e092b10092d110a30120a32140b34150b37160b39180c3c190c3e1b0c411c0c431e0c451f0c48210c4a230c4c240c4f260c51280b53290b552b0b572d0b592f0a5b310a5c320a5e340a5f3609613809623909633b09643d09653e0966400a67420a68440a68450a69470b6a490b6a4a0c6b4c0c6b4d0d6c4f0d6c510e6c520e6d540f6d550f6d57106e59106e5a116e5c126e5d126e5f136e61136e62146e64156e65156e67166e69166e6a176e6c186e6d186e6f196e71196e721a6e741a6e751b6e771c6d781c6d7a1d6d7c1d6d7d1e6d7f1e6c801f6c82206c84206b85216b87216b88226a8a226a8c23698d23698f24699025689225689326679526679727669827669a28659b29649d29649f2a63a02a63a22b62a32c61a52c60a62d60a82e5fa92e5eab2f5ead305dae305cb0315bb1325ab3325ab43359b63458b73557b93556ba3655bc3754bd3853bf3952c03a51c13a50c33b4fc43c4ec63d4dc73e4cc83f4bca404acb4149cc4248ce4347cf4446d04545d24644d34743d44842d54a41d74b3fd84c3ed94d3dda4e3cdb503bdd513ade5238df5337e05536e15635e25734e35933e45a31e55c30e65d2fe75e2ee8602de9612bea632aeb6429eb6628ec6726ed6925ee6a24ef6c23ef6e21f06f20f1711ff1731df2741cf3761bf37819f47918f57b17f57d15f67e14f68013f78212f78410f8850ff8870ef8890cf98b0bf98c0af98e09fa9008fa9207fa9407fb9606fb9706fb9906fb9b06fb9d07fc9f07fca108fca309fca50afca60cfca80dfcaa0ffcac11fcae12fcb014fcb216fcb418fbb61afbb81dfbba1ffbbc21fbbe23fac026fac228fac42afac62df9c72ff9c932f9cb35f8cd37f8cf3af7d13df7d340f6d543f6d746f5d949f5db4cf4dd4ff4df53f4e156f3e35af3e55df2e661f2e865f2ea69f1ec6df1ed71f1ef75f1f179f2f27df2f482f3f586f3f68af4f88ef5f992f6fa96f8fb9af9fc9dfafda1fcffa4")),pm=sm(H_("0d088710078813078916078a19068c1b068d1d068e20068f2206902406912605912805922a05932c05942e05952f059631059733059735049837049938049a3a049a3c049b3e049c3f049c41049d43039e44039e46039f48039f4903a04b03a14c02a14e02a25002a25102a35302a35502a45601a45801a45901a55b01a55c01a65e01a66001a66100a76300a76400a76600a76700a86900a86a00a86c00a86e00a86f00a87100a87201a87401a87501a87701a87801a87a02a87b02a87d03a87e03a88004a88104a78305a78405a78606a68707a68808a68a09a58b0aa58d0ba58e0ca48f0da4910ea3920fa39410a29511a19613a19814a099159f9a169f9c179e9d189d9e199da01a9ca11b9ba21d9aa31e9aa51f99a62098a72197a82296aa2395ab2494ac2694ad2793ae2892b02991b12a90b22b8fb32c8eb42e8db52f8cb6308bb7318ab83289ba3388bb3488bc3587bd3786be3885bf3984c03a83c13b82c23c81c33d80c43e7fc5407ec6417dc7427cc8437bc9447aca457acb4679cc4778cc4977cd4a76ce4b75cf4c74d04d73d14e72d24f71d35171d45270d5536fd5546ed6556dd7566cd8576bd9586ada5a6ada5b69db5c68dc5d67dd5e66de5f65de6164df6263e06363e16462e26561e26660e3685fe4695ee56a5de56b5de66c5ce76e5be76f5ae87059e97158e97257ea7457eb7556eb7655ec7754ed7953ed7a52ee7b51ef7c51ef7e50f07f4ff0804ef1814df1834cf2844bf3854bf3874af48849f48948f58b47f58c46f68d45f68f44f79044f79143f79342f89441f89540f9973ff9983ef99a3efa9b3dfa9c3cfa9e3bfb9f3afba139fba238fca338fca537fca636fca835fca934fdab33fdac33fdae32fdaf31fdb130fdb22ffdb42ffdb52efeb72dfeb82cfeba2cfebb2bfebd2afebe2afec029fdc229fdc328fdc527fdc627fdc827fdca26fdcb26fccd25fcce25fcd025fcd225fbd324fbd524fbd724fad824fada24f9dc24f9dd25f8df25f8e125f7e225f7e425f6e626f6e826f5e926f5eb27f4ed27f3ee27f3f027f2f227f1f426f1f525f0f724f0f921"));function gm(t){return function(){return t}}const ym=Math.abs,vm=Math.atan2,_m=Math.cos,bm=Math.max,mm=Math.min,xm=Math.sin,wm=Math.sqrt,Mm=1e-12,Tm=Math.PI,Am=Tm/2,Sm=2*Tm;function Em(t){return t>=1?Am:t<=-1?-Am:Math.asin(t)}function Nm(t){let n=3;return t.digits=function(e){if(!arguments.length)return n;if(null==e)n=null;else{const t=Math.floor(e);if(!(t>=0))throw new RangeError(`invalid digits: ${e}`);n=t}return t},()=>new Ua(n)}function km(t){return t.innerRadius}function Cm(t){return t.outerRadius}function Pm(t){return t.startAngle}function zm(t){return t.endAngle}function $m(t){return t&&t.padAngle}function Dm(t,n,e,r,i,o,a){var u=t-e,c=n-r,f=(a?o:-o)/wm(u*u+c*c),s=f*c,l=-f*u,h=t+s,d=n+l,p=e+s,g=r+l,y=(h+p)/2,v=(d+g)/2,_=p-h,b=g-d,m=_*_+b*b,x=i-o,w=h*g-p*d,M=(b<0?-1:1)*wm(bm(0,x*x*m-w*w)),T=(w*b-_*M)/m,A=(-w*_-b*M)/m,S=(w*b+_*M)/m,E=(-w*_+b*M)/m,N=T-y,k=A-v,C=S-y,P=E-v;return N*N+k*k>C*C+P*P&&(T=S,A=E),{cx:T,cy:A,x01:-s,y01:-l,x11:T*(i/x-1),y11:A*(i/x-1)}}var Rm=Array.prototype.slice;function Fm(t){return"object"==typeof t&&"length"in t?t:Array.from(t)}function qm(t){this._context=t}function Um(t){return new qm(t)}function Im(t){return t[0]}function Om(t){return t[1]}function Bm(t,n){var e=gm(!0),r=null,i=Um,o=null,a=Nm(u);function u(u){var c,f,s,l=(u=Fm(u)).length,h=!1;for(null==r&&(o=i(s=a())),c=0;c<=l;++c)!(c=l;--h)u.point(v[h],_[h]);u.lineEnd(),u.areaEnd()}y&&(v[s]=+t(d,s,f),_[s]=+n(d,s,f),u.point(r?+r(d,s,f):v[s],e?+e(d,s,f):_[s]))}if(p)return u=null,p+""||null}function s(){return Bm().defined(i).curve(a).context(o)}return t="function"==typeof t?t:void 0===t?Im:gm(+t),n="function"==typeof n?n:gm(void 0===n?0:+n),e="function"==typeof e?e:void 0===e?Om:gm(+e),f.x=function(n){return arguments.length?(t="function"==typeof n?n:gm(+n),r=null,f):t},f.x0=function(n){return arguments.length?(t="function"==typeof n?n:gm(+n),f):t},f.x1=function(t){return arguments.length?(r=null==t?null:"function"==typeof t?t:gm(+t),f):r},f.y=function(t){return arguments.length?(n="function"==typeof t?t:gm(+t),e=null,f):n},f.y0=function(t){return arguments.length?(n="function"==typeof t?t:gm(+t),f):n},f.y1=function(t){return arguments.length?(e=null==t?null:"function"==typeof t?t:gm(+t),f):e},f.lineX0=f.lineY0=function(){return s().x(t).y(n)},f.lineY1=function(){return s().x(t).y(e)},f.lineX1=function(){return s().x(r).y(n)},f.defined=function(t){return arguments.length?(i="function"==typeof t?t:gm(!!t),f):i},f.curve=function(t){return arguments.length?(a=t,null!=o&&(u=a(o)),f):a},f.context=function(t){return arguments.length?(null==t?o=u=null:u=a(o=t),f):o},f}function Lm(t,n){return nt?1:n>=t?0:NaN}function jm(t){return t}qm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._context.lineTo(t,n)}}};var Hm=Gm(Um);function Xm(t){this._curve=t}function Gm(t){function n(n){return new Xm(t(n))}return n._curve=t,n}function Vm(t){var n=t.curve;return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t.curve=function(t){return arguments.length?n(Gm(t)):n()._curve},t}function Wm(){return Vm(Bm().curve(Hm))}function Zm(){var t=Ym().curve(Hm),n=t.curve,e=t.lineX0,r=t.lineX1,i=t.lineY0,o=t.lineY1;return t.angle=t.x,delete t.x,t.startAngle=t.x0,delete t.x0,t.endAngle=t.x1,delete t.x1,t.radius=t.y,delete t.y,t.innerRadius=t.y0,delete t.y0,t.outerRadius=t.y1,delete t.y1,t.lineStartAngle=function(){return Vm(e())},delete t.lineX0,t.lineEndAngle=function(){return Vm(r())},delete t.lineX1,t.lineInnerRadius=function(){return Vm(i())},delete t.lineY0,t.lineOuterRadius=function(){return Vm(o())},delete t.lineY1,t.curve=function(t){return arguments.length?n(Gm(t)):n()._curve},t}function Km(t,n){return[(n=+n)*Math.cos(t-=Math.PI/2),n*Math.sin(t)]}Xm.prototype={areaStart:function(){this._curve.areaStart()},areaEnd:function(){this._curve.areaEnd()},lineStart:function(){this._curve.lineStart()},lineEnd:function(){this._curve.lineEnd()},point:function(t,n){this._curve.point(n*Math.sin(t),n*-Math.cos(t))}};class Qm{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line}point(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n)}this._x0=t,this._y0=n}}class Jm{constructor(t){this._context=t}lineStart(){this._point=0}lineEnd(){}point(t,n){if(t=+t,n=+n,0===this._point)this._point=1;else{const e=Km(this._x0,this._y0),r=Km(this._x0,this._y0=(this._y0+n)/2),i=Km(t,this._y0),o=Km(t,n);this._context.moveTo(...e),this._context.bezierCurveTo(...r,...i,...o)}this._x0=t,this._y0=n}}function tx(t){return new Qm(t,!0)}function nx(t){return new Qm(t,!1)}function ex(t){return new Jm(t)}function rx(t){return t.source}function ix(t){return t.target}function ox(t){let n=rx,e=ix,r=Im,i=Om,o=null,a=null,u=Nm(c);function c(){let c;const f=Rm.call(arguments),s=n.apply(this,f),l=e.apply(this,f);if(null==o&&(a=t(c=u())),a.lineStart(),f[0]=s,a.point(+r.apply(this,f),+i.apply(this,f)),f[0]=l,a.point(+r.apply(this,f),+i.apply(this,f)),a.lineEnd(),c)return a=null,c+""||null}return c.source=function(t){return arguments.length?(n=t,c):n},c.target=function(t){return arguments.length?(e=t,c):e},c.x=function(t){return arguments.length?(r="function"==typeof t?t:gm(+t),c):r},c.y=function(t){return arguments.length?(i="function"==typeof t?t:gm(+t),c):i},c.context=function(n){return arguments.length?(null==n?o=a=null:a=t(o=n),c):o},c}const ax=wm(3);var ux={draw(t,n){const e=.59436*wm(n+mm(n/28,.75)),r=e/2,i=r*ax;t.moveTo(0,e),t.lineTo(0,-e),t.moveTo(-i,-r),t.lineTo(i,r),t.moveTo(-i,r),t.lineTo(i,-r)}},cx={draw(t,n){const e=wm(n/Tm);t.moveTo(e,0),t.arc(0,0,e,0,Sm)}},fx={draw(t,n){const e=wm(n/5)/2;t.moveTo(-3*e,-e),t.lineTo(-e,-e),t.lineTo(-e,-3*e),t.lineTo(e,-3*e),t.lineTo(e,-e),t.lineTo(3*e,-e),t.lineTo(3*e,e),t.lineTo(e,e),t.lineTo(e,3*e),t.lineTo(-e,3*e),t.lineTo(-e,e),t.lineTo(-3*e,e),t.closePath()}};const sx=wm(1/3),lx=2*sx;var hx={draw(t,n){const e=wm(n/lx),r=e*sx;t.moveTo(0,-e),t.lineTo(r,0),t.lineTo(0,e),t.lineTo(-r,0),t.closePath()}},dx={draw(t,n){const e=.62625*wm(n);t.moveTo(0,-e),t.lineTo(e,0),t.lineTo(0,e),t.lineTo(-e,0),t.closePath()}},px={draw(t,n){const e=.87559*wm(n-mm(n/7,2));t.moveTo(-e,0),t.lineTo(e,0),t.moveTo(0,e),t.lineTo(0,-e)}},gx={draw(t,n){const e=wm(n),r=-e/2;t.rect(r,r,e,e)}},yx={draw(t,n){const e=.4431*wm(n);t.moveTo(e,e),t.lineTo(e,-e),t.lineTo(-e,-e),t.lineTo(-e,e),t.closePath()}};const vx=xm(Tm/10)/xm(7*Tm/10),_x=xm(Sm/10)*vx,bx=-_m(Sm/10)*vx;var mx={draw(t,n){const e=wm(.8908130915292852*n),r=_x*e,i=bx*e;t.moveTo(0,-e),t.lineTo(r,i);for(let n=1;n<5;++n){const o=Sm*n/5,a=_m(o),u=xm(o);t.lineTo(u*e,-a*e),t.lineTo(a*r-u*i,u*r+a*i)}t.closePath()}};const xx=wm(3);var wx={draw(t,n){const e=-wm(n/(3*xx));t.moveTo(0,2*e),t.lineTo(-xx*e,-e),t.lineTo(xx*e,-e),t.closePath()}};const Mx=wm(3);var Tx={draw(t,n){const e=.6824*wm(n),r=e/2,i=e*Mx/2;t.moveTo(0,-e),t.lineTo(i,r),t.lineTo(-i,r),t.closePath()}};const Ax=-.5,Sx=wm(3)/2,Ex=1/wm(12),Nx=3*(Ex/2+1);var kx={draw(t,n){const e=wm(n/Nx),r=e/2,i=e*Ex,o=r,a=e*Ex+e,u=-o,c=a;t.moveTo(r,i),t.lineTo(o,a),t.lineTo(u,c),t.lineTo(Ax*r-Sx*i,Sx*r+Ax*i),t.lineTo(Ax*o-Sx*a,Sx*o+Ax*a),t.lineTo(Ax*u-Sx*c,Sx*u+Ax*c),t.lineTo(Ax*r+Sx*i,Ax*i-Sx*r),t.lineTo(Ax*o+Sx*a,Ax*a-Sx*o),t.lineTo(Ax*u+Sx*c,Ax*c-Sx*u),t.closePath()}},Cx={draw(t,n){const e=.6189*wm(n-mm(n/6,1.7));t.moveTo(-e,-e),t.lineTo(e,e),t.moveTo(-e,e),t.lineTo(e,-e)}};const Px=[cx,fx,hx,gx,mx,wx,kx],zx=[cx,px,Cx,Tx,ux,yx,dx];function $x(){}function Dx(t,n,e){t._context.bezierCurveTo((2*t._x0+t._x1)/3,(2*t._y0+t._y1)/3,(t._x0+2*t._x1)/3,(t._y0+2*t._y1)/3,(t._x0+4*t._x1+n)/6,(t._y0+4*t._y1+e)/6)}function Rx(t){this._context=t}function Fx(t){this._context=t}function qx(t){this._context=t}function Ux(t,n){this._basis=new Rx(t),this._beta=n}Rx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:Dx(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:Dx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},Fx.prototype={areaStart:$x,areaEnd:$x,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x2=t,this._y2=n;break;case 1:this._point=2,this._x3=t,this._y3=n;break;case 2:this._point=3,this._x4=t,this._y4=n,this._context.moveTo((this._x0+4*this._x1+t)/6,(this._y0+4*this._y1+n)/6);break;default:Dx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},qx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var e=(this._x0+4*this._x1+t)/6,r=(this._y0+4*this._y1+n)/6;this._line?this._context.lineTo(e,r):this._context.moveTo(e,r);break;case 3:this._point=4;default:Dx(this,t,n)}this._x0=this._x1,this._x1=t,this._y0=this._y1,this._y1=n}},Ux.prototype={lineStart:function(){this._x=[],this._y=[],this._basis.lineStart()},lineEnd:function(){var t=this._x,n=this._y,e=t.length-1;if(e>0)for(var r,i=t[0],o=n[0],a=t[e]-i,u=n[e]-o,c=-1;++c<=e;)r=c/e,this._basis.point(this._beta*t[c]+(1-this._beta)*(i+r*a),this._beta*n[c]+(1-this._beta)*(o+r*u));this._x=this._y=null,this._basis.lineEnd()},point:function(t,n){this._x.push(+t),this._y.push(+n)}};var Ix=function t(n){function e(t){return 1===n?new Rx(t):new Ux(t,n)}return e.beta=function(n){return t(+n)},e}(.85);function Ox(t,n,e){t._context.bezierCurveTo(t._x1+t._k*(t._x2-t._x0),t._y1+t._k*(t._y2-t._y0),t._x2+t._k*(t._x1-n),t._y2+t._k*(t._y1-e),t._x2,t._y2)}function Bx(t,n){this._context=t,this._k=(1-n)/6}Bx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:Ox(this,this._x1,this._y1)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2,this._x1=t,this._y1=n;break;case 2:this._point=3;default:Ox(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Yx=function t(n){function e(t){return new Bx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Lx(t,n){this._context=t,this._k=(1-n)/6}Lx.prototype={areaStart:$x,areaEnd:$x,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:Ox(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var jx=function t(n){function e(t){return new Lx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Hx(t,n){this._context=t,this._k=(1-n)/6}Hx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Ox(this,t,n)}this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Xx=function t(n){function e(t){return new Hx(t,n)}return e.tension=function(n){return t(+n)},e}(0);function Gx(t,n,e){var r=t._x1,i=t._y1,o=t._x2,a=t._y2;if(t._l01_a>Mm){var u=2*t._l01_2a+3*t._l01_a*t._l12_a+t._l12_2a,c=3*t._l01_a*(t._l01_a+t._l12_a);r=(r*u-t._x0*t._l12_2a+t._x2*t._l01_2a)/c,i=(i*u-t._y0*t._l12_2a+t._y2*t._l01_2a)/c}if(t._l23_a>Mm){var f=2*t._l23_2a+3*t._l23_a*t._l12_a+t._l12_2a,s=3*t._l23_a*(t._l23_a+t._l12_a);o=(o*f+t._x1*t._l23_2a-n*t._l12_2a)/s,a=(a*f+t._y1*t._l23_2a-e*t._l12_2a)/s}t._context.bezierCurveTo(r,i,o,a,t._x2,t._y2)}function Vx(t,n){this._context=t,this._alpha=n}Vx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x2,this._y2);break;case 3:this.point(this._x2,this._y2)}(this._line||0!==this._line&&1===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;break;case 2:this._point=3;default:Gx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Wx=function t(n){function e(t){return n?new Vx(t,n):new Bx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Zx(t,n){this._context=t,this._alpha=n}Zx.prototype={areaStart:$x,areaEnd:$x,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._x5=this._y0=this._y1=this._y2=this._y3=this._y4=this._y5=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x3,this._y3),this._context.closePath();break;case 2:this._context.lineTo(this._x3,this._y3),this._context.closePath();break;case 3:this.point(this._x3,this._y3),this.point(this._x4,this._y4),this.point(this._x5,this._y5)}},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1,this._x3=t,this._y3=n;break;case 1:this._point=2,this._context.moveTo(this._x4=t,this._y4=n);break;case 2:this._point=3,this._x5=t,this._y5=n;break;default:Gx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Kx=function t(n){function e(t){return n?new Zx(t,n):new Lx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function Qx(t,n){this._context=t,this._alpha=n}Qx.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._x2=this._y0=this._y1=this._y2=NaN,this._l01_a=this._l12_a=this._l23_a=this._l01_2a=this._l12_2a=this._l23_2a=this._point=0},lineEnd:function(){(this._line||0!==this._line&&3===this._point)&&this._context.closePath(),this._line=1-this._line},point:function(t,n){if(t=+t,n=+n,this._point){var e=this._x2-t,r=this._y2-n;this._l23_a=Math.sqrt(this._l23_2a=Math.pow(e*e+r*r,this._alpha))}switch(this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3,this._line?this._context.lineTo(this._x2,this._y2):this._context.moveTo(this._x2,this._y2);break;case 3:this._point=4;default:Gx(this,t,n)}this._l01_a=this._l12_a,this._l12_a=this._l23_a,this._l01_2a=this._l12_2a,this._l12_2a=this._l23_2a,this._x0=this._x1,this._x1=this._x2,this._x2=t,this._y0=this._y1,this._y1=this._y2,this._y2=n}};var Jx=function t(n){function e(t){return n?new Qx(t,n):new Hx(t,0)}return e.alpha=function(n){return t(+n)},e}(.5);function tw(t){this._context=t}function nw(t){return t<0?-1:1}function ew(t,n,e){var r=t._x1-t._x0,i=n-t._x1,o=(t._y1-t._y0)/(r||i<0&&-0),a=(e-t._y1)/(i||r<0&&-0),u=(o*i+a*r)/(r+i);return(nw(o)+nw(a))*Math.min(Math.abs(o),Math.abs(a),.5*Math.abs(u))||0}function rw(t,n){var e=t._x1-t._x0;return e?(3*(t._y1-t._y0)/e-n)/2:n}function iw(t,n,e){var r=t._x0,i=t._y0,o=t._x1,a=t._y1,u=(o-r)/3;t._context.bezierCurveTo(r+u,i+u*n,o-u,a-u*e,o,a)}function ow(t){this._context=t}function aw(t){this._context=new uw(t)}function uw(t){this._context=t}function cw(t){this._context=t}function fw(t){var n,e,r=t.length-1,i=new Array(r),o=new Array(r),a=new Array(r);for(i[0]=0,o[0]=2,a[0]=t[0]+2*t[1],n=1;n=0;--n)i[n]=(a[n]-i[n+1])/o[n];for(o[r-1]=(t[r]+i[r-1])/2,n=0;n1)for(var e,r,i,o=1,a=t[n[0]],u=a.length;o=0;)e[n]=n;return e}function dw(t,n){return t[n]}function pw(t){const n=[];return n.key=t,n}function gw(t){var n=t.map(yw);return hw(t).sort((function(t,e){return n[t]-n[e]}))}function yw(t){for(var n,e=-1,r=0,i=t.length,o=-1/0;++eo&&(o=n,r=e);return r}function vw(t){var n=t.map(_w);return hw(t).sort((function(t,e){return n[t]-n[e]}))}function _w(t){for(var n,e=0,r=-1,i=t.length;++r=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(t,n){switch(t=+t,n=+n,this._point){case 0:this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,n),this._context.lineTo(t,n);else{var e=this._x*(1-this._t)+t*this._t;this._context.lineTo(e,this._y),this._context.lineTo(e,n)}}this._x=t,this._y=n}};var bw=t=>()=>t;function mw(t,{sourceEvent:n,target:e,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:t,enumerable:!0,configurable:!0},sourceEvent:{value:n,enumerable:!0,configurable:!0},target:{value:e,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function xw(t,n,e){this.k=t,this.x=n,this.y=e}xw.prototype={constructor:xw,scale:function(t){return 1===t?this:new xw(this.k*t,this.x,this.y)},translate:function(t,n){return 0===t&0===n?this:new xw(this.k,this.x+this.k*t,this.y+this.k*n)},apply:function(t){return[t[0]*this.k+this.x,t[1]*this.k+this.y]},applyX:function(t){return t*this.k+this.x},applyY:function(t){return t*this.k+this.y},invert:function(t){return[(t[0]-this.x)/this.k,(t[1]-this.y)/this.k]},invertX:function(t){return(t-this.x)/this.k},invertY:function(t){return(t-this.y)/this.k},rescaleX:function(t){return t.copy().domain(t.range().map(this.invertX,this).map(t.invert,t))},rescaleY:function(t){return t.copy().domain(t.range().map(this.invertY,this).map(t.invert,t))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var ww=new xw(1,0,0);function Mw(t){for(;!t.__zoom;)if(!(t=t.parentNode))return ww;return t.__zoom}function Tw(t){t.stopImmediatePropagation()}function Aw(t){t.preventDefault(),t.stopImmediatePropagation()}function Sw(t){return!(t.ctrlKey&&"wheel"!==t.type||t.button)}function Ew(){var t=this;return t instanceof SVGElement?(t=t.ownerSVGElement||t).hasAttribute("viewBox")?[[(t=t.viewBox.baseVal).x,t.y],[t.x+t.width,t.y+t.height]]:[[0,0],[t.width.baseVal.value,t.height.baseVal.value]]:[[0,0],[t.clientWidth,t.clientHeight]]}function Nw(){return this.__zoom||ww}function kw(t){return-t.deltaY*(1===t.deltaMode?.05:t.deltaMode?1:.002)*(t.ctrlKey?10:1)}function Cw(){return navigator.maxTouchPoints||"ontouchstart"in this}function Pw(t,n,e){var r=t.invertX(n[0][0])-e[0][0],i=t.invertX(n[1][0])-e[1][0],o=t.invertY(n[0][1])-e[0][1],a=t.invertY(n[1][1])-e[1][1];return t.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),a>o?(o+a)/2:Math.min(0,o)||Math.max(0,a))}Mw.prototype=xw.prototype,t.Adder=T,t.Delaunay=Lu,t.FormatSpecifier=tf,t.InternMap=InternMap,t.InternSet=InternSet,t.Node=Qd,t.Path=Ua,t.Voronoi=qu,t.ZoomTransform=xw,t.active=function(t,n){var e,r,i=t.__transition;if(i)for(r in n=null==n?null:n+"",i)if((e=i[r]).state>qi&&e.name===n)return new po([[t]],Zo,n,+r);return null},t.arc=function(){var t=km,n=Cm,e=gm(0),r=null,i=Pm,o=zm,a=$m,u=null,c=Nm(f);function f(){var f,s,l=+t.apply(this,arguments),h=+n.apply(this,arguments),d=i.apply(this,arguments)-Am,p=o.apply(this,arguments)-Am,g=ym(p-d),y=p>d;if(u||(u=f=c()),hMm)if(g>Sm-Mm)u.moveTo(h*_m(d),h*xm(d)),u.arc(0,0,h,d,p,!y),l>Mm&&(u.moveTo(l*_m(p),l*xm(p)),u.arc(0,0,l,p,d,y));else{var v,_,b=d,m=p,x=d,w=p,M=g,T=g,A=a.apply(this,arguments)/2,S=A>Mm&&(r?+r.apply(this,arguments):wm(l*l+h*h)),E=mm(ym(h-l)/2,+e.apply(this,arguments)),N=E,k=E;if(S>Mm){var C=Em(S/l*xm(A)),P=Em(S/h*xm(A));(M-=2*C)>Mm?(x+=C*=y?1:-1,w-=C):(M=0,x=w=(d+p)/2),(T-=2*P)>Mm?(b+=P*=y?1:-1,m-=P):(T=0,b=m=(d+p)/2)}var z=h*_m(b),$=h*xm(b),D=l*_m(w),R=l*xm(w);if(E>Mm){var F,q=h*_m(m),U=h*xm(m),I=l*_m(x),O=l*xm(x);if(g1?0:t<-1?Tm:Math.acos(t)}((B*L+Y*j)/(wm(B*B+Y*Y)*wm(L*L+j*j)))/2),X=wm(F[0]*F[0]+F[1]*F[1]);N=mm(E,(l-X)/(H-1)),k=mm(E,(h-X)/(H+1))}else N=k=0}T>Mm?k>Mm?(v=Dm(I,O,z,$,h,k,y),_=Dm(q,U,D,R,h,k,y),u.moveTo(v.cx+v.x01,v.cy+v.y01),kMm&&M>Mm?N>Mm?(v=Dm(D,R,q,U,l,-N,y),_=Dm(z,$,I,O,l,-N,y),u.lineTo(v.cx+v.x01,v.cy+v.y01),N=0))throw new RangeError("invalid r");let e=t.length;if(!((e=Math.floor(e))>=0))throw new RangeError("invalid length");if(!e||!n)return t;const r=y(n),i=t.slice();return r(t,i,0,e,1),r(i,t,0,e,1),r(t,i,0,e,1),t},t.blur2=l,t.blurImage=h,t.brush=function(){return wa(la)},t.brushSelection=function(t){var n=t.__brush;return n?n.dim.output(n.selection):null},t.brushX=function(){return wa(fa)},t.brushY=function(){return wa(sa)},t.buffer=function(t,n){return fetch(t,n).then(_c)},t.chord=function(){return za(!1,!1)},t.chordDirected=function(){return za(!0,!1)},t.chordTranspose=function(){return za(!1,!0)},t.cluster=function(){var t=Ld,n=1,e=1,r=!1;function i(i){var o,a=0;i.eachAfter((function(n){var e=n.children;e?(n.x=function(t){return t.reduce(jd,0)/t.length}(e),n.y=function(t){return 1+t.reduce(Hd,0)}(e)):(n.x=o?a+=t(n,o):0,n.y=0,o=n)}));var u=function(t){for(var n;n=t.children;)t=n[0];return t}(i),c=function(t){for(var n;n=t.children;)t=n[n.length-1];return t}(i),f=u.x-t(u,c)/2,s=c.x+t(c,u)/2;return i.eachAfter(r?function(t){t.x=(t.x-i.x)*n,t.y=(i.y-t.y)*e}:function(t){t.x=(t.x-f)/(s-f)*n,t.y=(1-(i.y?t.y/i.y:1))*e})}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.color=ze,t.contourDensity=function(){var t=fu,n=su,e=lu,r=960,i=500,o=20,a=2,u=3*o,c=r+2*u>>a,f=i+2*u>>a,s=Qa(20);function h(r){var i=new Float32Array(c*f),s=Math.pow(2,-a),h=-1;for(const o of r){var d=(t(o,++h,r)+u)*s,p=(n(o,h,r)+u)*s,g=+e(o,h,r);if(g&&d>=0&&d=0&&pt*r)))(n).map(((t,n)=>(t.value=+e[n],p(t))))}function p(t){return t.coordinates.forEach(g),t}function g(t){t.forEach(y)}function y(t){t.forEach(v)}function v(t){t[0]=t[0]*Math.pow(2,a)-u,t[1]=t[1]*Math.pow(2,a)-u}function _(){return c=r+2*(u=3*o)>>a,f=i+2*u>>a,d}return d.contours=function(t){var n=h(t),e=iu().size([c,f]),r=Math.pow(2,2*a),i=t=>{t=+t;var i=p(e.contour(n,t*r));return i.value=t,i};return Object.defineProperty(i,"max",{get:()=>J(n)/r}),i},d.x=function(n){return arguments.length?(t="function"==typeof n?n:Qa(+n),d):t},d.y=function(t){return arguments.length?(n="function"==typeof t?t:Qa(+t),d):n},d.weight=function(t){return arguments.length?(e="function"==typeof t?t:Qa(+t),d):e},d.size=function(t){if(!arguments.length)return[r,i];var n=+t[0],e=+t[1];if(!(n>=0&&e>=0))throw new Error("invalid size");return r=n,i=e,_()},d.cellSize=function(t){if(!arguments.length)return 1<=1))throw new Error("invalid cell size");return a=Math.floor(Math.log(t)/Math.LN2),_()},d.thresholds=function(t){return arguments.length?(s="function"==typeof t?t:Array.isArray(t)?Qa(Za.call(t)):Qa(t),d):s},d.bandwidth=function(t){if(!arguments.length)return Math.sqrt(o*(o+1));if(!((t=+t)>=0))throw new Error("invalid bandwidth");return o=(Math.sqrt(4*t*t+1)-1)/2,_()},d},t.contours=iu,t.count=v,t.create=function(t){return Zn(Yt(t).call(document.documentElement))},t.creator=Yt,t.cross=function(...t){const n="function"==typeof t[t.length-1]&&function(t){return n=>t(...n)}(t.pop()),e=(t=t.map(m)).map(_),r=t.length-1,i=new Array(r+1).fill(0),o=[];if(r<0||e.some(b))return o;for(;;){o.push(i.map(((n,e)=>t[e][n])));let a=r;for(;++i[a]===e[a];){if(0===a)return n?o.map(n):o;i[a--]=0}}},t.csv=wc,t.csvFormat=rc,t.csvFormatBody=ic,t.csvFormatRow=ac,t.csvFormatRows=oc,t.csvFormatValue=uc,t.csvParse=nc,t.csvParseRows=ec,t.cubehelix=Tr,t.cumsum=function(t,n){var e=0,r=0;return Float64Array.from(t,void 0===n?t=>e+=+t||0:i=>e+=+n(i,r++,t)||0)},t.curveBasis=function(t){return new Rx(t)},t.curveBasisClosed=function(t){return new Fx(t)},t.curveBasisOpen=function(t){return new qx(t)},t.curveBumpX=tx,t.curveBumpY=nx,t.curveBundle=Ix,t.curveCardinal=Yx,t.curveCardinalClosed=jx,t.curveCardinalOpen=Xx,t.curveCatmullRom=Wx,t.curveCatmullRomClosed=Kx,t.curveCatmullRomOpen=Jx,t.curveLinear=Um,t.curveLinearClosed=function(t){return new tw(t)},t.curveMonotoneX=function(t){return new ow(t)},t.curveMonotoneY=function(t){return new aw(t)},t.curveNatural=function(t){return new cw(t)},t.curveStep=function(t){return new sw(t,.5)},t.curveStepAfter=function(t){return new sw(t,1)},t.curveStepBefore=function(t){return new sw(t,0)},t.descending=e,t.deviation=w,t.difference=function(t,...n){t=new InternSet(t);for(const e of n)for(const n of e)t.delete(n);return t},t.disjoint=function(t,n){const e=n[Symbol.iterator](),r=new InternSet;for(const n of t){if(r.has(n))return!1;let t,i;for(;({value:t,done:i}=e.next())&&!i;){if(Object.is(n,t))return!1;r.add(t)}}return!0},t.dispatch=$t,t.drag=function(){var t,n,e,r,i=se,o=le,a=he,u=de,c={},f=$t("start","drag","end"),s=0,l=0;function h(t){t.on("mousedown.drag",d).filter(u).on("touchstart.drag",y).on("touchmove.drag",v,ee).on("touchend.drag touchcancel.drag",_).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function d(a,u){if(!r&&i.call(this,a,u)){var c=b(this,o.call(this,a,u),a,u,"mouse");c&&(Zn(a.view).on("mousemove.drag",p,re).on("mouseup.drag",g,re),ae(a.view),ie(a),e=!1,t=a.clientX,n=a.clientY,c("start",a))}}function p(r){if(oe(r),!e){var i=r.clientX-t,o=r.clientY-n;e=i*i+o*o>l}c.mouse("drag",r)}function g(t){Zn(t.view).on("mousemove.drag mouseup.drag",null),ue(t.view,e),oe(t),c.mouse("end",t)}function y(t,n){if(i.call(this,t,n)){var e,r,a=t.changedTouches,u=o.call(this,t,n),c=a.length;for(e=0;e+t,t.easePoly=wo,t.easePolyIn=mo,t.easePolyInOut=wo,t.easePolyOut=xo,t.easeQuad=_o,t.easeQuadIn=function(t){return t*t},t.easeQuadInOut=_o,t.easeQuadOut=function(t){return t*(2-t)},t.easeSin=Ao,t.easeSinIn=function(t){return 1==+t?1:1-Math.cos(t*To)},t.easeSinInOut=Ao,t.easeSinOut=function(t){return Math.sin(t*To)},t.every=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(!n(r,++e,t))return!1;return!0},t.extent=M,t.fcumsum=function(t,n){const e=new T;let r=-1;return Float64Array.from(t,void 0===n?t=>e.add(+t||0):i=>e.add(+n(i,++r,t)||0))},t.filter=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");const e=[];let r=-1;for(const i of t)n(i,++r,t)&&e.push(i);return e},t.flatGroup=function(t,...n){return z(P(t,...n),n)},t.flatRollup=function(t,n,...e){return z(D(t,n,...e),e)},t.forceCenter=function(t,n){var e,r=1;function i(){var i,o,a=e.length,u=0,c=0;for(i=0;if+p||os+p||ac.index){var g=f-u.x-u.vx,y=s-u.y-u.vy,v=g*g+y*y;vt.r&&(t.r=t[n].r)}function c(){if(n){var r,i,o=n.length;for(e=new Array(o),r=0;r[u(t,n,r),t])));for(a=0,i=new Array(f);a=u)){(t.data!==n||t.next)&&(0===l&&(p+=(l=Uc(e))*l),0===h&&(p+=(h=Uc(e))*h),p(t=(Lc*t+jc)%Hc)/Hc}();function l(){h(),f.call("tick",n),e1?(null==e?u.delete(t):u.set(t,p(e)),n):u.get(t)},find:function(n,e,r){var i,o,a,u,c,f=0,s=t.length;for(null==r?r=1/0:r*=r,f=0;f1?(f.on(t,e),n):f.on(t)}}},t.forceX=function(t){var n,e,r,i=qc(.1);function o(t){for(var i,o=0,a=n.length;o=.12&&i<.234&&r>=-.425&&r<-.214?u:i>=.166&&i<.234&&r>=-.214&&r<-.115?c:a).invert(t)},s.stream=function(e){return t&&n===e?t:(r=[a.stream(n=e),u.stream(e),c.stream(e)],i=r.length,t={point:function(t,n){for(var e=-1;++ejs(r[0],r[1])&&(r[1]=i[1]),js(i[0],r[1])>js(r[0],r[1])&&(r[0]=i[0])):o.push(r=i);for(a=-1/0,n=0,r=o[e=o.length-1];n<=e;r=i,++n)i=o[n],(u=js(r[1],i[0]))>a&&(a=u,Wf=i[0],Kf=r[1])}return is=os=null,Wf===1/0||Zf===1/0?[[NaN,NaN],[NaN,NaN]]:[[Wf,Zf],[Kf,Qf]]},t.geoCentroid=function(t){ms=xs=ws=Ms=Ts=As=Ss=Es=0,Ns=new T,ks=new T,Cs=new T,Lf(t,Gs);var n=+Ns,e=+ks,r=+Cs,i=Ef(n,e,r);return i=0))throw new RangeError(`invalid digits: ${t}`);i=n}return null===n&&(r=new ed(i)),a},a.projection(t).digits(i).context(n)},t.geoProjection=yd,t.geoProjectionMutator=vd,t.geoRotation=ll,t.geoStereographic=function(){return yd(Bd).scale(250).clipAngle(142)},t.geoStereographicRaw=Bd,t.geoStream=Lf,t.geoTransform=function(t){return{stream:id(t)}},t.geoTransverseMercator=function(){var t=Ed(Yd),n=t.center,e=t.rotate;return t.center=function(t){return arguments.length?n([-t[1],t[0]]):[(t=n())[1],-t[0]]},t.rotate=function(t){return arguments.length?e([t[0],t[1],t.length>2?t[2]+90:90]):[(t=e())[0],t[1],t[2]-90]},e([0,0,90]).scale(159.155)},t.geoTransverseMercatorRaw=Yd,t.gray=function(t,n){return new ur(t,0,0,null==n?1:n)},t.greatest=ot,t.greatestIndex=function(t,e=n){if(1===e.length)return tt(t,e);let r,i=-1,o=-1;for(const n of t)++o,(i<0?0===e(n,n):e(n,r)>0)&&(r=n,i=o);return i},t.group=C,t.groupSort=function(t,e,r){return(2!==e.length?U($(t,e,r),(([t,e],[r,i])=>n(e,i)||n(t,r))):U(C(t,r),(([t,r],[i,o])=>e(r,o)||n(t,i)))).map((([t])=>t))},t.groups=P,t.hcl=dr,t.hierarchy=Gd,t.histogram=Q,t.hsl=He,t.html=Ec,t.image=function(t,n){return new Promise((function(e,r){var i=new Image;for(var o in n)i[o]=n[o];i.onerror=r,i.onload=function(){e(i)},i.src=t}))},t.index=function(t,...n){return F(t,k,R,n)},t.indexes=function(t,...n){return F(t,Array.from,R,n)},t.interpolate=Gr,t.interpolateArray=function(t,n){return(Ir(n)?Ur:Or)(t,n)},t.interpolateBasis=Er,t.interpolateBasisClosed=Nr,t.interpolateBlues=Xb,t.interpolateBrBG=ib,t.interpolateBuGn=wb,t.interpolateBuPu=Tb,t.interpolateCividis=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(-4.54-t*(35.34-t*(2381.73-t*(6402.7-t*(7024.72-2710.57*t)))))))+", "+Math.max(0,Math.min(255,Math.round(32.49+t*(170.73+t*(52.82-t*(131.46-t*(176.58-67.37*t)))))))+", "+Math.max(0,Math.min(255,Math.round(81.24+t*(442.36-t*(2482.43-t*(6167.24-t*(6614.94-2475.67*t)))))))+")"},t.interpolateCool=om,t.interpolateCubehelix=li,t.interpolateCubehelixDefault=rm,t.interpolateCubehelixLong=hi,t.interpolateDate=Br,t.interpolateDiscrete=function(t){var n=t.length;return function(e){return t[Math.max(0,Math.min(n-1,Math.floor(e*n)))]}},t.interpolateGnBu=Sb,t.interpolateGreens=Vb,t.interpolateGreys=Zb,t.interpolateHcl=ci,t.interpolateHclLong=fi,t.interpolateHsl=oi,t.interpolateHslLong=ai,t.interpolateHue=function(t,n){var e=Pr(+t,+n);return function(t){var n=e(t);return n-360*Math.floor(n/360)}},t.interpolateInferno=dm,t.interpolateLab=function(t,n){var e=$r((t=ar(t)).l,(n=ar(n)).l),r=$r(t.a,n.a),i=$r(t.b,n.b),o=$r(t.opacity,n.opacity);return function(n){return t.l=e(n),t.a=r(n),t.b=i(n),t.opacity=o(n),t+""}},t.interpolateMagma=hm,t.interpolateNumber=Yr,t.interpolateNumberArray=Ur,t.interpolateObject=Lr,t.interpolateOrRd=Nb,t.interpolateOranges=em,t.interpolatePRGn=ab,t.interpolatePiYG=cb,t.interpolatePlasma=pm,t.interpolatePuBu=zb,t.interpolatePuBuGn=Cb,t.interpolatePuOr=sb,t.interpolatePuRd=Db,t.interpolatePurples=Qb,t.interpolateRainbow=function(t){(t<0||t>1)&&(t-=Math.floor(t));var n=Math.abs(t-.5);return am.h=360*t-100,am.s=1.5-1.5*n,am.l=.8-.9*n,am+""},t.interpolateRdBu=hb,t.interpolateRdGy=pb,t.interpolateRdPu=Fb,t.interpolateRdYlBu=yb,t.interpolateRdYlGn=_b,t.interpolateReds=tm,t.interpolateRgb=Dr,t.interpolateRgbBasis=Fr,t.interpolateRgbBasisClosed=qr,t.interpolateRound=Vr,t.interpolateSinebow=function(t){var n;return t=(.5-t)*Math.PI,um.r=255*(n=Math.sin(t))*n,um.g=255*(n=Math.sin(t+cm))*n,um.b=255*(n=Math.sin(t+fm))*n,um+""},t.interpolateSpectral=mb,t.interpolateString=Xr,t.interpolateTransformCss=ti,t.interpolateTransformSvg=ni,t.interpolateTurbo=function(t){return t=Math.max(0,Math.min(1,t)),"rgb("+Math.max(0,Math.min(255,Math.round(34.61+t*(1172.33-t*(10793.56-t*(33300.12-t*(38394.49-14825.05*t)))))))+", "+Math.max(0,Math.min(255,Math.round(23.31+t*(557.33+t*(1225.33-t*(3574.96-t*(1073.77+707.56*t)))))))+", "+Math.max(0,Math.min(255,Math.round(27.2+t*(3211.1-t*(15327.97-t*(27814-t*(22569.18-6838.66*t)))))))+")"},t.interpolateViridis=lm,t.interpolateWarm=im,t.interpolateYlGn=Ob,t.interpolateYlGnBu=Ub,t.interpolateYlOrBr=Yb,t.interpolateYlOrRd=jb,t.interpolateZoom=ri,t.interrupt=Gi,t.intersection=function(t,...n){t=new InternSet(t),n=n.map(vt);t:for(const e of t)for(const r of n)if(!r.has(e)){t.delete(e);continue t}return t},t.interval=function(t,n,e){var r=new Ei,i=n;return null==n?(r.restart(t,n,e),r):(r._restart=r.restart,r.restart=function(t,n,e){n=+n,e=null==e?Ai():+e,r._restart((function o(a){a+=i,r._restart(o,i+=n,e),t(a)}),n,e)},r.restart(t,n,e),r)},t.isoFormat=D_,t.isoParse=F_,t.json=function(t,n){return fetch(t,n).then(Tc)},t.lab=ar,t.lch=function(t,n,e,r){return 1===arguments.length?hr(t):new pr(e,n,t,null==r?1:r)},t.least=function(t,e=n){let r,i=!1;if(1===e.length){let o;for(const a of t){const t=e(a);(i?n(t,o)<0:0===n(t,t))&&(r=a,o=t,i=!0)}}else for(const n of t)(i?e(n,r)<0:0===e(n,n))&&(r=n,i=!0);return r},t.leastIndex=ht,t.line=Bm,t.lineRadial=Wm,t.link=ox,t.linkHorizontal=function(){return ox(tx)},t.linkRadial=function(){const t=ox(ex);return t.angle=t.x,delete t.x,t.radius=t.y,delete t.y,t},t.linkVertical=function(){return ox(nx)},t.local=Qn,t.map=function(t,n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");if("function"!=typeof n)throw new TypeError("mapper is not a function");return Array.from(t,((e,r)=>n(e,r,t)))},t.matcher=Vt,t.max=J,t.maxIndex=tt,t.mean=function(t,n){let e=0,r=0;if(void 0===n)for(let n of t)null!=n&&(n=+n)>=n&&(++e,r+=n);else{let i=-1;for(let o of t)null!=(o=n(o,++i,t))&&(o=+o)>=o&&(++e,r+=o)}if(e)return r/e},t.median=function(t,n){return at(t,.5,n)},t.medianIndex=function(t,n){return ct(t,.5,n)},t.merge=ft,t.min=nt,t.minIndex=et,t.mode=function(t,n){const e=new InternMap;if(void 0===n)for(let n of t)null!=n&&n>=n&&e.set(n,(e.get(n)||0)+1);else{let r=-1;for(let i of t)null!=(i=n(i,++r,t))&&i>=i&&e.set(i,(e.get(i)||0)+1)}let r,i=0;for(const[t,n]of e)n>i&&(i=n,r=t);return r},t.namespace=It,t.namespaces=Ut,t.nice=Z,t.now=Ai,t.pack=function(){var t=null,n=1,e=1,r=np;function i(i){const o=ap();return i.x=n/2,i.y=e/2,t?i.eachBefore(xp(t)).eachAfter(wp(r,.5,o)).eachBefore(Mp(1)):i.eachBefore(xp(mp)).eachAfter(wp(np,1,o)).eachAfter(wp(r,i.r/Math.min(n,e),o)).eachBefore(Mp(Math.min(n,e)/(2*i.r))),i}return i.radius=function(n){return arguments.length?(t=Jd(n),i):t},i.size=function(t){return arguments.length?(n=+t[0],e=+t[1],i):[n,e]},i.padding=function(t){return arguments.length?(r="function"==typeof t?t:ep(+t),i):r},i},t.packEnclose=function(t){return up(t,ap())},t.packSiblings=function(t){return bp(t,ap()),t},t.pairs=function(t,n=st){const e=[];let r,i=!1;for(const o of t)i&&e.push(n(r,o)),r=o,i=!0;return e},t.partition=function(){var t=1,n=1,e=0,r=!1;function i(i){var o=i.height+1;return i.x0=i.y0=e,i.x1=t,i.y1=n/o,i.eachBefore(function(t,n){return function(r){r.children&&Ap(r,r.x0,t*(r.depth+1)/n,r.x1,t*(r.depth+2)/n);var i=r.x0,o=r.y0,a=r.x1-e,u=r.y1-e;a0&&(d+=l);for(null!=n?p.sort((function(t,e){return n(g[t],g[e])})):null!=e&&p.sort((function(t,n){return e(a[t],a[n])})),u=0,f=d?(v-h*b)/d:0;u0?l*f:0)+b,g[c]={data:a[c],index:u,value:l,startAngle:y,endAngle:s,padAngle:_};return g}return a.value=function(n){return arguments.length?(t="function"==typeof n?n:gm(+n),a):t},a.sortValues=function(t){return arguments.length?(n=t,e=null,a):n},a.sort=function(t){return arguments.length?(e=t,n=null,a):e},a.startAngle=function(t){return arguments.length?(r="function"==typeof t?t:gm(+t),a):r},a.endAngle=function(t){return arguments.length?(i="function"==typeof t?t:gm(+t),a):i},a.padAngle=function(t){return arguments.length?(o="function"==typeof t?t:gm(+t),a):o},a},t.piecewise=di,t.pointRadial=Km,t.pointer=ne,t.pointers=function(t,n){return t.target&&(t=te(t),void 0===n&&(n=t.currentTarget),t=t.touches||[t]),Array.from(t,(t=>ne(t,n)))},t.polygonArea=function(t){for(var n,e=-1,r=t.length,i=t[r-1],o=0;++eu!=f>u&&a<(c-e)*(u-r)/(f-r)+e&&(s=!s),c=e,f=r;return s},t.polygonHull=function(t){if((e=t.length)<3)return null;var n,e,r=new Array(e),i=new Array(e);for(n=0;n=0;--n)f.push(t[r[o[n]][2]]);for(n=+u;n(n=1664525*n+1013904223|0,lg*(n>>>0))},t.randomLogNormal=Kp,t.randomLogistic=fg,t.randomNormal=Zp,t.randomPareto=ng,t.randomPoisson=sg,t.randomUniform=Vp,t.randomWeibull=ug,t.range=lt,t.rank=function(t,e=n){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");let r=Array.from(t);const i=new Float64Array(r.length);2!==e.length&&(r=r.map(e),e=n);const o=(t,n)=>e(r[t],r[n]);let a,u;return(t=Uint32Array.from(r,((t,n)=>n))).sort(e===n?(t,n)=>O(r[t],r[n]):I(o)),t.forEach(((t,n)=>{const e=o(t,void 0===a?t:a);e>=0?((void 0===a||e>0)&&(a=t,u=n),i[t]=u):i[t]=NaN})),i},t.reduce=function(t,n,e){if("function"!=typeof n)throw new TypeError("reducer is not a function");const r=t[Symbol.iterator]();let i,o,a=-1;if(arguments.length<3){if(({done:i,value:e}=r.next()),i)return;++a}for(;({done:i,value:o}=r.next()),!i;)e=n(e,o,++a,t);return e},t.reverse=function(t){if("function"!=typeof t[Symbol.iterator])throw new TypeError("values is not iterable");return Array.from(t).reverse()},t.rgb=Fe,t.ribbon=function(){return Wa()},t.ribbonArrow=function(){return Wa(Va)},t.rollup=$,t.rollups=D,t.scaleBand=yg,t.scaleDiverging=function t(){var n=Ng(L_()(mg));return n.copy=function(){return B_(n,t())},dg.apply(n,arguments)},t.scaleDivergingLog=function t(){var n=Fg(L_()).domain([.1,1,10]);return n.copy=function(){return B_(n,t()).base(n.base())},dg.apply(n,arguments)},t.scaleDivergingPow=j_,t.scaleDivergingSqrt=function(){return j_.apply(null,arguments).exponent(.5)},t.scaleDivergingSymlog=function t(){var n=Ig(L_());return n.copy=function(){return B_(n,t()).constant(n.constant())},dg.apply(n,arguments)},t.scaleIdentity=function t(n){var e;function r(t){return null==t||isNaN(t=+t)?e:t}return r.invert=r,r.domain=r.range=function(t){return arguments.length?(n=Array.from(t,_g),r):n.slice()},r.unknown=function(t){return arguments.length?(e=t,r):e},r.copy=function(){return t(n).unknown(e)},n=arguments.length?Array.from(n,_g):[0,1],Ng(r)},t.scaleImplicit=pg,t.scaleLinear=function t(){var n=Sg();return n.copy=function(){return Tg(n,t())},hg.apply(n,arguments),Ng(n)},t.scaleLog=function t(){const n=Fg(Ag()).domain([1,10]);return n.copy=()=>Tg(n,t()).base(n.base()),hg.apply(n,arguments),n},t.scaleOrdinal=gg,t.scalePoint=function(){return vg(yg.apply(null,arguments).paddingInner(1))},t.scalePow=jg,t.scaleQuantile=function t(){var e,r=[],i=[],o=[];function a(){var t=0,n=Math.max(1,i.length);for(o=new Array(n-1);++t0?o[n-1]:r[0],n=i?[o[i-1],r]:[o[n-1],o[n]]},u.unknown=function(t){return arguments.length?(n=t,u):u},u.thresholds=function(){return o.slice()},u.copy=function(){return t().domain([e,r]).range(a).unknown(n)},hg.apply(Ng(u),arguments)},t.scaleRadial=function t(){var n,e=Sg(),r=[0,1],i=!1;function o(t){var r=function(t){return Math.sign(t)*Math.sqrt(Math.abs(t))}(e(t));return isNaN(r)?n:i?Math.round(r):r}return o.invert=function(t){return e.invert(Hg(t))},o.domain=function(t){return arguments.length?(e.domain(t),o):e.domain()},o.range=function(t){return arguments.length?(e.range((r=Array.from(t,_g)).map(Hg)),o):r.slice()},o.rangeRound=function(t){return o.range(t).round(!0)},o.round=function(t){return arguments.length?(i=!!t,o):i},o.clamp=function(t){return arguments.length?(e.clamp(t),o):e.clamp()},o.unknown=function(t){return arguments.length?(n=t,o):n},o.copy=function(){return t(e.domain(),r).round(i).clamp(e.clamp()).unknown(n)},hg.apply(o,arguments),Ng(o)},t.scaleSequential=function t(){var n=Ng(O_()(mg));return n.copy=function(){return B_(n,t())},dg.apply(n,arguments)},t.scaleSequentialLog=function t(){var n=Fg(O_()).domain([1,10]);return n.copy=function(){return B_(n,t()).base(n.base())},dg.apply(n,arguments)},t.scaleSequentialPow=Y_,t.scaleSequentialQuantile=function t(){var e=[],r=mg;function i(t){if(null!=t&&!isNaN(t=+t))return r((s(e,t,1)-1)/(e.length-1))}return i.domain=function(t){if(!arguments.length)return e.slice();e=[];for(let n of t)null==n||isNaN(n=+n)||e.push(n);return e.sort(n),i},i.interpolator=function(t){return arguments.length?(r=t,i):r},i.range=function(){return e.map(((t,n)=>r(n/(e.length-1))))},i.quantiles=function(t){return Array.from({length:t+1},((n,r)=>at(e,r/t)))},i.copy=function(){return t(r).domain(e)},dg.apply(i,arguments)},t.scaleSequentialSqrt=function(){return Y_.apply(null,arguments).exponent(.5)},t.scaleSequentialSymlog=function t(){var n=Ig(O_());return n.copy=function(){return B_(n,t()).constant(n.constant())},dg.apply(n,arguments)},t.scaleSqrt=function(){return jg.apply(null,arguments).exponent(.5)},t.scaleSymlog=function t(){var n=Ig(Ag());return n.copy=function(){return Tg(n,t()).constant(n.constant())},hg.apply(n,arguments)},t.scaleThreshold=function t(){var n,e=[.5],r=[0,1],i=1;function o(t){return null!=t&&t<=t?r[s(e,t,0,i)]:n}return o.domain=function(t){return arguments.length?(e=Array.from(t),i=Math.min(e.length,r.length-1),o):e.slice()},o.range=function(t){return arguments.length?(r=Array.from(t),i=Math.min(e.length,r.length-1),o):r.slice()},o.invertExtent=function(t){var n=r.indexOf(t);return[e[n-1],e[n]]},o.unknown=function(t){return arguments.length?(n=t,o):n},o.copy=function(){return t().domain(e).range(r).unknown(n)},hg.apply(o,arguments)},t.scaleTime=function(){return hg.apply(I_(uv,cv,tv,Zy,xy,py,sy,ay,iy,t.timeFormat).domain([new Date(2e3,0,1),new Date(2e3,0,2)]),arguments)},t.scaleUtc=function(){return hg.apply(I_(ov,av,ev,Qy,Fy,yy,hy,cy,iy,t.utcFormat).domain([Date.UTC(2e3,0,1),Date.UTC(2e3,0,2)]),arguments)},t.scan=function(t,n){const e=ht(t,n);return e<0?void 0:e},t.schemeAccent=G_,t.schemeBlues=Hb,t.schemeBrBG=rb,t.schemeBuGn=xb,t.schemeBuPu=Mb,t.schemeCategory10=X_,t.schemeDark2=V_,t.schemeGnBu=Ab,t.schemeGreens=Gb,t.schemeGreys=Wb,t.schemeOrRd=Eb,t.schemeOranges=nm,t.schemePRGn=ob,t.schemePaired=W_,t.schemePastel1=Z_,t.schemePastel2=K_,t.schemePiYG=ub,t.schemePuBu=Pb,t.schemePuBuGn=kb,t.schemePuOr=fb,t.schemePuRd=$b,t.schemePurples=Kb,t.schemeRdBu=lb,t.schemeRdGy=db,t.schemeRdPu=Rb,t.schemeRdYlBu=gb,t.schemeRdYlGn=vb,t.schemeReds=Jb,t.schemeSet1=Q_,t.schemeSet2=J_,t.schemeSet3=tb,t.schemeSpectral=bb,t.schemeTableau10=nb,t.schemeYlGn=Ib,t.schemeYlGnBu=qb,t.schemeYlOrBr=Bb,t.schemeYlOrRd=Lb,t.select=Zn,t.selectAll=function(t){return"string"==typeof t?new Vn([document.querySelectorAll(t)],[document.documentElement]):new Vn([Ht(t)],Gn)},t.selection=Wn,t.selector=jt,t.selectorAll=Gt,t.shuffle=dt,t.shuffler=pt,t.some=function(t,n){if("function"!=typeof n)throw new TypeError("test is not a function");let e=-1;for(const r of t)if(n(r,++e,t))return!0;return!1},t.sort=U,t.stack=function(){var t=gm([]),n=hw,e=lw,r=dw;function i(i){var o,a,u=Array.from(t.apply(this,arguments),pw),c=u.length,f=-1;for(const t of i)for(o=0,++f;o0)for(var e,r,i,o,a,u,c=0,f=t[n[0]].length;c0?(r[0]=o,r[1]=o+=i):i<0?(r[1]=a,r[0]=a+=i):(r[0]=0,r[1]=i)},t.stackOffsetExpand=function(t,n){if((r=t.length)>0){for(var e,r,i,o=0,a=t[0].length;o0){for(var e,r=0,i=t[n[0]],o=i.length;r0&&(r=(e=t[n[0]]).length)>0){for(var e,r,i,o=0,a=1;afunction(t){t=`${t}`;let n=t.length;zp(t,n-1)&&!zp(t,n-2)&&(t=t.slice(0,-1));return"/"===t[0]?t:`/${t}`}(t(n,e,r)))),e=n.map(Pp),i=new Set(n).add("");for(const t of e)i.has(t)||(i.add(t),n.push(t),e.push(Pp(t)),h.push(Np));d=(t,e)=>n[e],p=(t,n)=>e[n]}for(a=0,i=h.length;a=0&&(f=h[t]).data===Np;--t)f.data=null}if(u.parent=Sp,u.eachBefore((function(t){t.depth=t.parent.depth+1,--i})).eachBefore(Kd),u.parent=null,i>0)throw new Error("cycle");return u}return r.id=function(t){return arguments.length?(n=Jd(t),r):n},r.parentId=function(t){return arguments.length?(e=Jd(t),r):e},r.path=function(n){return arguments.length?(t=Jd(n),r):t},r},t.style=_n,t.subset=function(t,n){return _t(n,t)},t.sum=function(t,n){let e=0;if(void 0===n)for(let n of t)(n=+n)&&(e+=n);else{let r=-1;for(let i of t)(i=+n(i,++r,t))&&(e+=i)}return e},t.superset=_t,t.svg=Nc,t.symbol=function(t,n){let e=null,r=Nm(i);function i(){let i;if(e||(e=i=r()),t.apply(this,arguments).draw(e,+n.apply(this,arguments)),i)return e=null,i+""||null}return t="function"==typeof t?t:gm(t||cx),n="function"==typeof n?n:gm(void 0===n?64:+n),i.type=function(n){return arguments.length?(t="function"==typeof n?n:gm(n),i):t},i.size=function(t){return arguments.length?(n="function"==typeof t?t:gm(+t),i):n},i.context=function(t){return arguments.length?(e=null==t?null:t,i):e},i},t.symbolAsterisk=ux,t.symbolCircle=cx,t.symbolCross=fx,t.symbolDiamond=hx,t.symbolDiamond2=dx,t.symbolPlus=px,t.symbolSquare=gx,t.symbolSquare2=yx,t.symbolStar=mx,t.symbolTimes=Cx,t.symbolTriangle=wx,t.symbolTriangle2=Tx,t.symbolWye=kx,t.symbolX=Cx,t.symbols=Px,t.symbolsFill=Px,t.symbolsStroke=zx,t.text=mc,t.thresholdFreedmanDiaconis=function(t,n,e){const r=v(t),i=at(t,.75)-at(t,.25);return r&&i?Math.ceil((e-n)/(2*i*Math.pow(r,-1/3))):1},t.thresholdScott=function(t,n,e){const r=v(t),i=w(t);return r&&i?Math.ceil((e-n)*Math.cbrt(r)/(3.49*i)):1},t.thresholdSturges=K,t.tickFormat=Eg,t.tickIncrement=V,t.tickStep=W,t.ticks=G,t.timeDay=py,t.timeDays=gy,t.timeFormatDefaultLocale=P_,t.timeFormatLocale=hv,t.timeFriday=Sy,t.timeFridays=$y,t.timeHour=sy,t.timeHours=ly,t.timeInterval=Vg,t.timeMillisecond=Wg,t.timeMilliseconds=Zg,t.timeMinute=ay,t.timeMinutes=uy,t.timeMonday=wy,t.timeMondays=ky,t.timeMonth=Zy,t.timeMonths=Ky,t.timeSaturday=Ey,t.timeSaturdays=Dy,t.timeSecond=iy,t.timeSeconds=oy,t.timeSunday=xy,t.timeSundays=Ny,t.timeThursday=Ay,t.timeThursdays=zy,t.timeTickInterval=cv,t.timeTicks=uv,t.timeTuesday=My,t.timeTuesdays=Cy,t.timeWednesday=Ty,t.timeWednesdays=Py,t.timeWeek=xy,t.timeWeeks=Ny,t.timeYear=tv,t.timeYears=nv,t.timeout=$i,t.timer=Ni,t.timerFlush=ki,t.transition=go,t.transpose=gt,t.tree=function(){var t=$p,n=1,e=1,r=null;function i(i){var c=function(t){for(var n,e,r,i,o,a=new Up(t,0),u=[a];n=u.pop();)if(r=n._.children)for(n.children=new Array(o=r.length),i=o-1;i>=0;--i)u.push(e=n.children[i]=new Up(r[i],i)),e.parent=n;return(a.parent=new Up(null,0)).children=[a],a}(i);if(c.eachAfter(o),c.parent.m=-c.z,c.eachBefore(a),r)i.eachBefore(u);else{var f=i,s=i,l=i;i.eachBefore((function(t){t.xs.x&&(s=t),t.depth>l.depth&&(l=t)}));var h=f===s?1:t(f,s)/2,d=h-f.x,p=n/(s.x+h+d),g=e/(l.depth||1);i.eachBefore((function(t){t.x=(t.x+d)*p,t.y=t.depth*g}))}return i}function o(n){var e=n.children,r=n.parent.children,i=n.i?r[n.i-1]:null;if(e){!function(t){for(var n,e=0,r=0,i=t.children,o=i.length;--o>=0;)(n=i[o]).z+=e,n.m+=e,e+=n.s+(r+=n.c)}(n);var o=(e[0].z+e[e.length-1].z)/2;i?(n.z=i.z+t(n._,i._),n.m=n.z-o):n.z=o}else i&&(n.z=i.z+t(n._,i._));n.parent.A=function(n,e,r){if(e){for(var i,o=n,a=n,u=e,c=o.parent.children[0],f=o.m,s=a.m,l=u.m,h=c.m;u=Rp(u),o=Dp(o),u&&o;)c=Dp(c),(a=Rp(a)).a=n,(i=u.z+l-o.z-f+t(u._,o._))>0&&(Fp(qp(u,n,r),n,i),f+=i,s+=i),l+=u.m,f+=o.m,h+=c.m,s+=a.m;u&&!Rp(a)&&(a.t=u,a.m+=l-s),o&&!Dp(c)&&(c.t=o,c.m+=f-h,r=n)}return r}(n,i,n.parent.A||r[0])}function a(t){t._.x=t.z+t.parent.m,t.m+=t.parent.m}function u(t){t.x*=n,t.y=t.depth*e}return i.separation=function(n){return arguments.length?(t=n,i):t},i.size=function(t){return arguments.length?(r=!1,n=+t[0],e=+t[1],i):r?null:[n,e]},i.nodeSize=function(t){return arguments.length?(r=!0,n=+t[0],e=+t[1],i):r?[n,e]:null},i},t.treemap=function(){var t=Yp,n=!1,e=1,r=1,i=[0],o=np,a=np,u=np,c=np,f=np;function s(t){return t.x0=t.y0=0,t.x1=e,t.y1=r,t.eachBefore(l),i=[0],n&&t.eachBefore(Tp),t}function l(n){var e=i[n.depth],r=n.x0+e,s=n.y0+e,l=n.x1-e,h=n.y1-e;l=e-1){var s=u[n];return s.x0=i,s.y0=o,s.x1=a,void(s.y1=c)}var l=f[n],h=r/2+l,d=n+1,p=e-1;for(;d>>1;f[g]c-o){var _=r?(i*v+a*y)/r:a;t(n,d,y,i,o,_,c),t(d,e,v,_,o,a,c)}else{var b=r?(o*v+c*y)/r:c;t(n,d,y,i,o,a,b),t(d,e,v,i,b,a,c)}}(0,c,t.value,n,e,r,i)},t.treemapDice=Ap,t.treemapResquarify=Lp,t.treemapSlice=Ip,t.treemapSliceDice=function(t,n,e,r,i){(1&t.depth?Ip:Ap)(t,n,e,r,i)},t.treemapSquarify=Yp,t.tsv=Mc,t.tsvFormat=lc,t.tsvFormatBody=hc,t.tsvFormatRow=pc,t.tsvFormatRows=dc,t.tsvFormatValue=gc,t.tsvParse=fc,t.tsvParseRows=sc,t.union=function(...t){const n=new InternSet;for(const e of t)for(const t of e)n.add(t);return n},t.unixDay=_y,t.unixDays=by,t.utcDay=yy,t.utcDays=vy,t.utcFriday=By,t.utcFridays=Vy,t.utcHour=hy,t.utcHours=dy,t.utcMillisecond=Wg,t.utcMilliseconds=Zg,t.utcMinute=cy,t.utcMinutes=fy,t.utcMonday=qy,t.utcMondays=jy,t.utcMonth=Qy,t.utcMonths=Jy,t.utcSaturday=Yy,t.utcSaturdays=Wy,t.utcSecond=iy,t.utcSeconds=oy,t.utcSunday=Fy,t.utcSundays=Ly,t.utcThursday=Oy,t.utcThursdays=Gy,t.utcTickInterval=av,t.utcTicks=ov,t.utcTuesday=Uy,t.utcTuesdays=Hy,t.utcWednesday=Iy,t.utcWednesdays=Xy,t.utcWeek=Fy,t.utcWeeks=Ly,t.utcYear=ev,t.utcYears=rv,t.variance=x,t.version="7.8.5",t.window=pn,t.xml=Sc,t.zip=function(){return gt(arguments)},t.zoom=function(){var t,n,e,r=Sw,i=Ew,o=Pw,a=kw,u=Cw,c=[0,1/0],f=[[-1/0,-1/0],[1/0,1/0]],s=250,l=ri,h=$t("start","zoom","end"),d=500,p=150,g=0,y=10;function v(t){t.property("__zoom",Nw).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",A).on("dblclick.zoom",S).filter(u).on("touchstart.zoom",E).on("touchmove.zoom",N).on("touchend.zoom touchcancel.zoom",k).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function _(t,n){return(n=Math.max(c[0],Math.min(c[1],n)))===t.k?t:new xw(n,t.x,t.y)}function b(t,n,e){var r=n[0]-e[0]*t.k,i=n[1]-e[1]*t.k;return r===t.x&&i===t.y?t:new xw(t.k,r,i)}function m(t){return[(+t[0][0]+ +t[1][0])/2,(+t[0][1]+ +t[1][1])/2]}function x(t,n,e,r){t.on("start.zoom",(function(){w(this,arguments).event(r).start()})).on("interrupt.zoom end.zoom",(function(){w(this,arguments).event(r).end()})).tween("zoom",(function(){var t=this,o=arguments,a=w(t,o).event(r),u=i.apply(t,o),c=null==e?m(u):"function"==typeof e?e.apply(t,o):e,f=Math.max(u[1][0]-u[0][0],u[1][1]-u[0][1]),s=t.__zoom,h="function"==typeof n?n.apply(t,o):n,d=l(s.invert(c).concat(f/s.k),h.invert(c).concat(f/h.k));return function(t){if(1===t)t=h;else{var n=d(t),e=f/n[2];t=new xw(e,c[0]-n[0]*e,c[1]-n[1]*e)}a.zoom(null,t)}}))}function w(t,n,e){return!e&&t.__zooming||new M(t,n)}function M(t,n){this.that=t,this.args=n,this.active=0,this.sourceEvent=null,this.extent=i.apply(t,n),this.taps=0}function T(t,...n){if(r.apply(this,arguments)){var e=w(this,n).event(t),i=this.__zoom,u=Math.max(c[0],Math.min(c[1],i.k*Math.pow(2,a.apply(this,arguments)))),s=ne(t);if(e.wheel)e.mouse[0][0]===s[0]&&e.mouse[0][1]===s[1]||(e.mouse[1]=i.invert(e.mouse[0]=s)),clearTimeout(e.wheel);else{if(i.k===u)return;e.mouse=[s,i.invert(s)],Gi(this),e.start()}Aw(t),e.wheel=setTimeout((function(){e.wheel=null,e.end()}),p),e.zoom("mouse",o(b(_(i,u),e.mouse[0],e.mouse[1]),e.extent,f))}}function A(t,...n){if(!e&&r.apply(this,arguments)){var i=t.currentTarget,a=w(this,n,!0).event(t),u=Zn(t.view).on("mousemove.zoom",(function(t){if(Aw(t),!a.moved){var n=t.clientX-s,e=t.clientY-l;a.moved=n*n+e*e>g}a.event(t).zoom("mouse",o(b(a.that.__zoom,a.mouse[0]=ne(t,i),a.mouse[1]),a.extent,f))}),!0).on("mouseup.zoom",(function(t){u.on("mousemove.zoom mouseup.zoom",null),ue(t.view,a.moved),Aw(t),a.event(t).end()}),!0),c=ne(t,i),s=t.clientX,l=t.clientY;ae(t.view),Tw(t),a.mouse=[c,this.__zoom.invert(c)],Gi(this),a.start()}}function S(t,...n){if(r.apply(this,arguments)){var e=this.__zoom,a=ne(t.changedTouches?t.changedTouches[0]:t,this),u=e.invert(a),c=e.k*(t.shiftKey?.5:2),l=o(b(_(e,c),a,u),i.apply(this,n),f);Aw(t),s>0?Zn(this).transition().duration(s).call(x,l,a,t):Zn(this).call(v.transform,l,a,t)}}function E(e,...i){if(r.apply(this,arguments)){var o,a,u,c,f=e.touches,s=f.length,l=w(this,i,e.changedTouches.length===s).event(e);for(Tw(e),a=0;a --help` for command-specific help.""" + + +# Constants for socket synchronization +_SYNC_TIMEOUT_SEC = 5.0 +_PROCESS_KILL_TIMEOUT_SEC = 2.0 +_READY_MESSAGE = b"ready" +_RECV_BUFFER_SIZE = 1024 +_BINARY_PROFILE_HEADER_SIZE = 64 +_BINARY_PROFILE_MAGICS = (b"HCAT", b"TACH") + +# Format configuration +FORMAT_EXTENSIONS = { + "pstats": "pstats", + "collapsed": "txt", + "flamegraph": "html", + "diff_flamegraph": "html", + "gecko": "json", + "heatmap": "html", + "jsonl": "jsonl", + "binary": "bin", +} + +COLLECTOR_MAP = { + "pstats": PstatsCollector, + "collapsed": CollapsedStackCollector, + "flamegraph": FlamegraphCollector, + "diff_flamegraph": DiffFlamegraphCollector, + "gecko": GeckoCollector, + "heatmap": HeatmapCollector, + "jsonl": JsonlCollector, + "binary": BinaryCollector, +} + +BROWSER_COMPATIBLE_FORMATS = ("flamegraph", "diff_flamegraph", "heatmap") + + +def _setup_child_monitor(args, parent_pid): + # Build CLI args for child profilers (excluding --subprocesses to avoid recursion) + child_cli_args = _build_child_profiler_args(args) + + # Build output pattern + output_pattern = _build_output_pattern(args) + + return ChildProcessMonitor( + pid=parent_pid, + cli_args=child_cli_args, + output_pattern=output_pattern, + ) + + +def _get_child_monitor_context(args, pid): + if getattr(args, 'subprocesses', False): + return _setup_child_monitor(args, pid) + return nullcontext() + + +def _build_child_profiler_args(args): + child_args = [] + + # Sampling options + hz = MICROSECONDS_PER_SECOND // args.sample_interval_usec + child_args.extend(["-r", str(hz)]) + if args.duration is not None: + child_args.extend(["-d", str(args.duration)]) + if args.all_threads: + child_args.append("-a") + if args.realtime_stats: + child_args.append("--realtime-stats") + if args.native: + child_args.append("--native") + if not args.gc: + child_args.append("--no-gc") + if args.opcodes: + child_args.append("--opcodes") + if args.async_aware: + child_args.append("--async-aware") + async_mode = getattr(args, 'async_mode', 'running') + if async_mode != "running": + child_args.extend(["--async-mode", async_mode]) + + # Mode options + mode = getattr(args, 'mode', 'wall') + if mode != "wall": + child_args.extend(["--mode", mode]) + + # Format options (skip pstats as it's the default) + if args.format == "diff_flamegraph": + child_args.extend(["--diff-flamegraph", args.diff_baseline]) + elif args.format != "pstats": + child_args.append(f"--{args.format}") + + return child_args + + +def _build_output_pattern(args): + """Build output filename pattern for child profilers. + + The pattern uses {pid} as a placeholder which will be replaced with the + actual child PID using str.replace(), so user filenames with braces are safe. + """ + if args.outfile: + # User specified output - add PID to filename + base, ext = os.path.splitext(args.outfile) + if ext: + return f"{base}_{{pid}}{ext}" + else: + return f"{args.outfile}_{{pid}}" + else: + # Use default pattern based on format (consistent _ separator) + extension = FORMAT_EXTENSIONS.get(args.format, "txt") + if args.format == "heatmap": + return "heatmap_{pid}" + if args.format == "pstats": + # pstats defaults to stdout, but for subprocesses we need files + return "profile_{pid}.pstats" + return f"{args.format}_{{pid}}.{extension}" + + +def _parse_mode(mode_string): + """Convert mode string to mode constant.""" + mode_map = { + "wall": PROFILING_MODE_WALL, + "cpu": PROFILING_MODE_CPU, + "gil": PROFILING_MODE_GIL, + "exception": PROFILING_MODE_EXCEPTION, + } + return mode_map[mode_string] + + +def _check_process_died(process): + """Check if process died and raise an error with stderr if available.""" + if process.poll() is None: + return + + # Process died - try to get stderr for error message + stderr_msg = "" + if process.stderr: + try: + stderr_msg = process.stderr.read().decode().strip() + except (OSError, UnicodeDecodeError): + pass + + if stderr_msg: + raise RuntimeError(stderr_msg) + raise RuntimeError(f"Process exited with code {process.returncode}") + + +def _wait_for_ready_signal(sync_sock, process, timeout): + """Wait for the ready signal from the subprocess, checking for early death.""" + deadline = time.monotonic() + timeout + sel = selectors.DefaultSelector() + sel.register(sync_sock, selectors.EVENT_READ) + + try: + while True: + _check_process_died(process) + + remaining = deadline - time.monotonic() + if remaining <= 0: + raise socket.timeout("timed out") + + if not sel.select(timeout=min(0.1, remaining)): + continue + + conn, _ = sync_sock.accept() + try: + ready_signal = conn.recv(_RECV_BUFFER_SIZE) + finally: + conn.close() + + if ready_signal != _READY_MESSAGE: + raise RuntimeError(f"Invalid ready signal received: {ready_signal!r}") + return + finally: + sel.close() + + +def _run_with_sync(original_cmd, suppress_output=False): + """Run a command with socket-based synchronization and return the process.""" + # Create a TCP socket for synchronization with better socket options + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sync_sock: + # Set SO_REUSEADDR to avoid "Address already in use" errors + sync_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + sync_sock.bind(("127.0.0.1", 0)) # Let OS choose a free port + sync_port = sync_sock.getsockname()[1] + sync_sock.listen(1) + sync_sock.settimeout(_SYNC_TIMEOUT_SEC) + + # Get current working directory to preserve it + cwd = os.getcwd() + + # Build command using the sync coordinator + target_args = original_cmd[1:] # Remove python executable + cmd = ( + sys.executable, + "-m", + "profiling.sampling._sync_coordinator", + str(sync_port), + cwd, + ) + tuple(target_args) + + # Start the process with coordinator + # When suppress_output=True (live mode), capture stderr so we can + # report errors if the process dies before signaling ready. + # When suppress_output=False (normal mode), let stderr inherit so + # script errors print to the terminal. + popen_kwargs = {} + if suppress_output: + popen_kwargs["stdin"] = subprocess.DEVNULL + popen_kwargs["stdout"] = subprocess.DEVNULL + popen_kwargs["stderr"] = subprocess.PIPE + + process = subprocess.Popen(cmd, **popen_kwargs) + + try: + _wait_for_ready_signal(sync_sock, process, _SYNC_TIMEOUT_SEC) + except socket.timeout: + # If we timeout, kill the process and raise an error + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=_PROCESS_KILL_TIMEOUT_SEC) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + raise RuntimeError( + "Process failed to signal readiness within timeout" + ) + + return process + + +_RATE_PATTERN = re.compile(r''' + ^ # Start of string + ( # Group 1: The numeric value + \d+ # One or more digits (integer part) + (?:\.\d+)? # Optional: decimal point followed by digits + ) # Examples: "10", "0.5", "100.25" + ( # Group 2: Optional unit suffix + hz # "hz" - hertz + | khz # "khz" - kilohertz + | k # "k" - shorthand for kilohertz + )? # Suffix is optional (bare number = Hz) + $ # End of string + ''', re.VERBOSE | re.IGNORECASE) + + +def _parse_sampling_rate(rate_str: str) -> int: + """Parse sampling rate string to microseconds.""" + rate_str = rate_str.strip().lower() + + match = _RATE_PATTERN.match(rate_str) + if not match: + raise argparse.ArgumentTypeError( + f"Invalid sampling rate format: {rate_str}. " + "Expected: number followed by optional suffix (hz, khz, k) with no spaces (e.g., 10khz)" + ) + + number_part = match.group(1) + suffix = match.group(2) or '' + + # Determine multiplier based on suffix + suffix_map = { + 'hz': 1, + 'khz': 1000, + 'k': 1000, + } + multiplier = suffix_map.get(suffix, 1) + hz = float(number_part) * multiplier + if hz <= 0: + raise argparse.ArgumentTypeError(f"Sampling rate must be positive: {rate_str}") + + interval_usec = int(MICROSECONDS_PER_SECOND / hz) + if interval_usec < 1: + raise argparse.ArgumentTypeError(f"Sampling rate too high: {rate_str}") + + return interval_usec + + +def _add_sampling_options(parser): + """Add sampling configuration options to a parser.""" + sampling_group = parser.add_argument_group("Sampling configuration") + sampling_group.add_argument( + "-r", + "--sampling-rate", + type=_parse_sampling_rate, + default="1khz", + metavar="RATE", + dest="sample_interval_usec", + help="sampling rate (e.g., 10000, 10khz, 10k)", + ) + sampling_group.add_argument( + "-d", + "--duration", + type=int, + default=None, + metavar="SECONDS", + help="Sampling duration (default: run to completion)", + ) + sampling_group.add_argument( + "-a", + "--all-threads", + action="store_true", + help="Sample all threads in the process instead of just the main thread", + ) + sampling_group.add_argument( + "--realtime-stats", + action="store_true", + help="Print real-time sampling statistics (Hz, mean, min, max) during profiling", + ) + sampling_group.add_argument( + "--native", + action="store_true", + help='Include artificial `` frames to denote calls to non-Python code', + ) + sampling_group.add_argument( + "--no-gc", + action="store_false", + dest="gc", + help='Don\'t include artificial `` frames to denote active garbage collection', + ) + sampling_group.add_argument( + "--opcodes", + action="store_true", + help="Gather bytecode opcode information for instruction-level profiling " + "(shows which bytecode instructions are executing, including specializations).", + ) + sampling_group.add_argument( + "--async-aware", + action="store_true", + help="Enable async-aware profiling (uses task-based stack reconstruction)", + ) + sampling_group.add_argument( + "--subprocesses", + action="store_true", + help="Also profile subprocesses. Each subprocess gets its own profiler and output file.", + ) + sampling_group.add_argument( + "--blocking", + action="store_true", + help="Stop all threads in target process before sampling to get consistent snapshots. " + "Uses thread_suspend on macOS and ptrace on Linux. Adds overhead but ensures memory " + "reads are from a frozen state.", + ) + + +def _add_mode_options(parser): + """Add mode options to a parser.""" + mode_group = parser.add_argument_group("Mode options") + mode_group.add_argument( + "--mode", + choices=["wall", "cpu", "gil", "exception"], + default="wall", + help="Sampling mode: wall (all samples), cpu (only samples when thread is on CPU), " + "gil (only samples when thread holds the GIL), " + "exception (only samples when thread has an active exception). " + "Incompatible with `--async-aware`", + ) + mode_group.add_argument( + "--async-mode", + choices=["running", "all"], + default="running", + help='Async profiling mode: "running" (only running task) ' + 'or "all" (all tasks including waiting). Requires `--async-aware`', + ) + + +def _add_format_options(parser, include_compression=True, include_binary=True): + """Add output format options to a parser.""" + output_group = parser.add_argument_group("Output options") + format_group = output_group.add_mutually_exclusive_group() + format_group.add_argument( + "--pstats", + action="store_const", + const="pstats", + dest="format", + help="Generate pstats output (default)", + ) + format_group.add_argument( + "--collapsed", + action="store_const", + const="collapsed", + dest="format", + help="Generate collapsed stack traces for flamegraphs", + ) + format_group.add_argument( + "--flamegraph", + action="store_const", + const="flamegraph", + dest="format", + help="Generate interactive HTML flamegraph visualization", + ) + format_group.add_argument( + "--gecko", + action="store_const", + const="gecko", + dest="format", + help="Generate Gecko format for Firefox Profiler", + ) + format_group.add_argument( + "--heatmap", + action="store_const", + const="heatmap", + dest="format", + help="Generate interactive HTML heatmap visualization with line-level sample counts", + ) + format_group.add_argument( + "--diff-flamegraph", + metavar="BASELINE", + action=DiffFlamegraphAction, + help="Generate differential flamegraph comparing current profile to `BASELINE` binary file", + ) + format_group.add_argument( + "--jsonl", + action="store_const", + const="jsonl", + dest="format", + help="Generate newline-delimited JSON (JSONL) for programmatic consumers", + ) + if include_binary: + format_group.add_argument( + "--binary", + action="store_const", + const="binary", + dest="format", + help="Generate high-performance binary format (use `replay` command to convert)", + ) + parser.set_defaults(format="pstats", diff_baseline=None) + + if include_compression: + output_group.add_argument( + "--compression", + choices=["auto", "zstd", "none"], + default="auto", + help="Compression for binary format: auto (use zstd if available), zstd, none", + ) + + output_group.add_argument( + "-o", + "--output", + dest="outfile", + help="Output path (default: `stdout` for `pstats` text; with `-o`, `pstats` is binary). " + "Auto-generated for other formats. For heatmap: directory name (default: `heatmap_PID`)", + ) + output_group.add_argument( + "--browser", + action="store_true", + help=( + "Automatically open HTML output " + f"({', '.join('--' + f.replace('_', '-') for f in BROWSER_COMPATIBLE_FORMATS)}) " + "in browser. " + "When using `--subprocesses`, only the main process opens the browser" + ), + ) + + +def _add_pstats_options(parser): + """Add pstats-specific display options to a parser.""" + pstats_group = parser.add_argument_group("pstats format options") + pstats_group.add_argument( + "--sort", + choices=[ + "nsamples", + "tottime", + "cumtime", + "sample-pct", + "cumul-pct", + "nsamples-cumul", + "name", + ], + default=None, + help="Sort order for pstats output (default: nsamples)", + ) + pstats_group.add_argument( + "-l", + "--limit", + type=int, + default=None, + help="Limit the number of rows in the output (default: 15)", + ) + pstats_group.add_argument( + "--no-summary", + action="store_true", + help="Disable the summary section in the pstats output", + ) + + +def _add_dump_options(parser): + """Add one-shot stack dump options to a parser.""" + dump_group = parser.add_argument_group("Dump options") + dump_group.add_argument( + "-a", + "--all-threads", + action="store_true", + help="Dump all threads in the process instead of just the main thread", + ) + dump_group.add_argument( + "--native", + action="store_true", + help='Include artificial `` frames to denote calls to non-Python code', + ) + dump_group.add_argument( + "--no-gc", + action="store_false", + dest="gc", + help='Don\'t include artificial `` frames to denote active garbage collection', + ) + dump_group.add_argument( + "--opcodes", + action="store_true", + help="Show bytecode opcode names when available.", + ) + dump_group.add_argument( + "--async-aware", + action="store_true", + help="Enable async-aware stack reconstruction", + ) + dump_group.add_argument( + "--async-mode", + choices=["running", "all"], + default=argparse.SUPPRESS, + help='Async stack mode: "running" (only running task) ' + 'or "all" (all tasks including waiting, default for dump). ' + "Requires `--async-aware`", + ) + dump_group.add_argument( + "--blocking", + action="store_true", + help="Stop all threads in target process before dumping the stack.", + ) + + +def _sort_to_mode(sort_choice): + """Convert sort choice string to SORT_MODE constant.""" + sort_map = { + "nsamples": SORT_MODE_NSAMPLES, + "tottime": SORT_MODE_TOTTIME, + "cumtime": SORT_MODE_CUMTIME, + "sample-pct": SORT_MODE_SAMPLE_PCT, + "cumul-pct": SORT_MODE_CUMUL_PCT, + "nsamples-cumul": SORT_MODE_NSAMPLES_CUMUL, + "name": -1, + } + return sort_map.get(sort_choice, SORT_MODE_NSAMPLES) + + +def _capture_config_from_args(args): + return { + "all_threads": args.all_threads, + "native": args.native, + "gc": args.gc, + "opcodes": args.opcodes, + "blocking": args.blocking, + } + + +def _create_collector(format_type, sample_interval_usec, skip_idle, opcodes=False, + mode=None, output_file=None, compression='auto', + diff_baseline=None, capture_config=None): + """Create the appropriate collector based on format type. + + Args: + format_type: The output format ('pstats', 'collapsed', 'flamegraph', + 'gecko', 'heatmap', 'jsonl', 'binary', 'diff_flamegraph') + sample_interval_usec: Sampling interval in microseconds + skip_idle: Whether to skip idle samples + opcodes: Whether to collect opcode information (only used by gecko format + for creating interval markers in Firefox Profiler) + mode: Profiling mode for collectors that expose it in metadata + output_file: Output file path (required for binary format) + compression: Compression type for binary format ('auto', 'zstd', 'none') + diff_baseline: Path to baseline binary file for differential flamegraph + capture_config: Capture feature mapping for binary profiles and diffs + + Returns: + A collector instance of the appropriate type + """ + collector_class = COLLECTOR_MAP.get(format_type) + if collector_class is None: + raise ValueError(f"Unknown format: {format_type}") + + if format_type == "diff_flamegraph": + if diff_baseline is None: + raise ValueError("Differential flamegraph requires a baseline file") + if not os.path.exists(diff_baseline): + raise ValueError(f"Baseline file not found: {diff_baseline}") + return collector_class( + sample_interval_usec, + baseline_binary_path=diff_baseline, + skip_idle=skip_idle, + mode=mode, + capture_config=capture_config, + ) + + # Binary format requires output file and compression + if format_type == "binary": + if output_file is None: + raise ValueError("Binary format requires an output file") + return collector_class(output_file, sample_interval_usec, skip_idle=skip_idle, + compression=compression, mode=mode, + capture_config=capture_config) + + # Gecko format never skips idle (it needs both GIL and CPU data) + # and is the only format that uses opcodes for interval markers + if format_type == "gecko": + skip_idle = False + return collector_class(sample_interval_usec, skip_idle=skip_idle, opcodes=opcodes) + + if format_type == "jsonl": + return collector_class( + sample_interval_usec, skip_idle=skip_idle, mode=mode + ) + + return collector_class(sample_interval_usec, skip_idle=skip_idle) + + +def _generate_output_filename(format_type, pid): + """Generate output filename based on format and PID. + + Args: + format_type: The output format + pid: Process ID + + Returns: + Generated filename + """ + extension = FORMAT_EXTENSIONS.get(format_type, "txt") + # For heatmap, use cleaner directory name without extension + if format_type == "heatmap": + return f"heatmap_{pid}" + return f"{format_type}_{pid}.{extension}" + + +def _open_in_browser(path): + """Open a file or directory in the default web browser. + + Args: + path: File path or directory path to open + + For directories (heatmap), opens the index.html file inside. + """ + abs_path = os.path.abspath(path) + + # For heatmap directories, open the index.html file + if os.path.isdir(abs_path): + index_path = os.path.join(abs_path, 'index.html') + if os.path.exists(index_path): + abs_path = index_path + else: + print(f"Warning: Could not find index.html in {path}", file=sys.stderr) + return + + file_url = f"file://{abs_path}" + try: + webbrowser.open(file_url) + except Exception as e: + print(f"Warning: Could not open browser: {e}", file=sys.stderr) + + +def _validate_replay_input_file(filename): + """Validate that the replay input looks like a sampling binary profile.""" + try: + with open(filename, "rb") as file: + header = file.read(_BINARY_PROFILE_HEADER_SIZE) + except OSError as exc: + sys.exit(f"Error: Could not read input file {filename}: {exc}") + + if ( + len(header) < _BINARY_PROFILE_HEADER_SIZE + or header[:4] not in _BINARY_PROFILE_MAGICS + ): + sys.exit( + "Error: Input file is not a binary sampling profile. " + "The replay command only accepts files created with --binary" + ) + + +def _replay_with_reader(args, reader): + """Replay samples from an open binary reader.""" + info = reader.get_info() + interval = info['sample_interval_us'] + + print(f"Replaying {info['sample_count']} samples from {args.input_file}") + print(f" Sample interval: {interval} us") + print( + " Compression: " + f"{'zstd' if info.get('compression_type', 0) == 1 else 'none'}" + ) + + collector = _create_collector( + args.format, interval, skip_idle=False, + mode=info.get("mode"), + diff_baseline=args.diff_baseline, + capture_config=info.get("capture_config"), + ) + + def progress_callback(current, total): + if total > 0: + pct = current / total + bar_width = 40 + filled = int(bar_width * pct) + bar = '█' * filled + '░' * (bar_width - filled) + print( + f"\r [{bar}] {pct*100:5.1f}% ({current:,}/{total:,})", + end="", + flush=True, + ) + + count = reader.replay_samples(collector, progress_callback) + if hasattr(collector, "set_replay_stats"): + collector.set_replay_stats(info) + if hasattr(collector, "set_mode"): + collector.set_mode(info.get("mode")) + print() + + if args.format == "pstats": + if args.outfile: + collector.export(args.outfile) + else: + sort_choice = ( + args.sort if args.sort is not None else "nsamples" + ) + limit = args.limit if args.limit is not None else 15 + sort_mode = _sort_to_mode(sort_choice) + collector.print_stats( + sort_mode, limit, not args.no_summary, + info.get("mode") if info.get("mode") is not None + else PROFILING_MODE_WALL + ) + else: + filename = ( + args.outfile + or _generate_output_filename(args.format, os.getpid()) + ) + export_ok = collector.export(filename) + + # Auto-open browser for HTML output if --browser flag is set + if ( + export_ok + and args.format in BROWSER_COMPATIBLE_FORMATS + and getattr(args, 'browser', False) + ): + _open_in_browser(filename) + + print(f"Replayed {count} samples") + + +def _handle_output(collector, args, pid, mode): + """Handle output for the collector based on format and arguments. + + Args: + collector: The collector instance with profiling data + args: Parsed command-line arguments + pid: Process ID (for generating filenames) + mode: Profiling mode used + """ + if args.format == "binary": + # Binary format already wrote to file incrementally, just finalize + collector.export(None) + filename = collector.filename + print(f"Binary profile written to {filename} ({collector.total_samples} samples)") + elif args.format == "pstats": + if args.outfile: + # If outfile is a directory, generate filename inside it + if os.path.isdir(args.outfile): + filename = os.path.join(args.outfile, _generate_output_filename(args.format, pid)) + collector.export(filename) + else: + collector.export(args.outfile) + else: + # Print to stdout with defaults applied + sort_choice = args.sort if args.sort is not None else "nsamples" + limit = args.limit if args.limit is not None else 15 + sort_mode = _sort_to_mode(sort_choice) + collector.print_stats( + sort_mode, limit, not args.no_summary, mode + ) + else: + # Export to file + if args.outfile and os.path.isdir(args.outfile): + # If outfile is a directory, generate filename inside it + filename = os.path.join(args.outfile, _generate_output_filename(args.format, pid)) + else: + filename = args.outfile or _generate_output_filename(args.format, pid) + export_ok = collector.export(filename) + + # Auto-open browser for HTML output if --browser flag is set + if ( + export_ok + and args.format in BROWSER_COMPATIBLE_FORMATS + and getattr(args, 'browser', False) + ): + _open_in_browser(filename) + + +def _validate_args(args, parser): + """Validate format-specific options and live mode requirements. + + Args: + args: Parsed command-line arguments + parser: ArgumentParser instance for error reporting + """ + command = getattr(args, 'command', None) + + if command == "replay": + return + + # Check if live mode is available + if hasattr(args, 'live') and args.live and LiveStatsCollector is None: + parser.error( + "Live mode requires the curses module, which is not available." + ) + + # --subprocesses is incompatible with --live + if hasattr(args, 'subprocesses') and args.subprocesses: + if ChildProcessMonitor is None: + parser.error( + "--subprocesses is not available on this platform " + "(requires _remote_debugging module)." + ) + if hasattr(args, 'live') and args.live: + parser.error("--subprocesses is incompatible with --live mode.") + + # Async-aware mode is incompatible with options that need thread data. + if getattr(args, 'async_aware', False): + issues = [] + if getattr(args, 'native', False): + issues.append("--native") + if not getattr(args, 'gc', True): + issues.append("--no-gc") + if getattr(args, 'format', None) == "binary": + issues.append("--binary") + if hasattr(args, 'mode') and args.mode != "wall": + issues.append(f"--mode={args.mode}") + if hasattr(args, 'all_threads') and args.all_threads: + issues.append("--all-threads") + if issues: + parser.error( + f"Options {', '.join(issues)} are incompatible with --async-aware. " + "Async-aware profiling uses task-based stack reconstruction." + ) + + # --async-mode requires --async-aware when explicitly set + if not getattr(args, 'async_aware', False): + if command == "dump": + # dump uses SUPPRESS default, so attr only exists if user passed it + if hasattr(args, 'async_mode'): + parser.error("--async-mode requires --async-aware to be enabled.") + elif hasattr(args, 'async_mode') and args.async_mode != "running": + parser.error("--async-mode requires --async-aware to be enabled.") + + if command == "dump": + return + + # Warn about blocking mode with aggressive sampling intervals + if args.blocking and args.sample_interval_usec < 100: + print( + f"Warning: --blocking with a {args.sample_interval_usec} µs interval will stop all threads " + f"{1_000_000 // args.sample_interval_usec} times per second. " + "Consider using --sampling-rate 1khz or lower to reduce overhead.", + file=sys.stderr + ) + + # Live mode is incompatible with format options + if hasattr(args, 'live') and args.live: + if args.format != "pstats": + format_flag = f"--{args.format}" + parser.error( + f"--live is incompatible with {format_flag}. Live mode uses a TUI interface." + ) + + # Live mode is also incompatible with pstats-specific options + issues = [] + if args.sort is not None: + issues.append("--sort") + if args.limit is not None: + issues.append("--limit") + if args.no_summary: + issues.append("--no-summary") + + if issues: + parser.error( + f"Options {', '.join(issues)} are incompatible with --live. " + "Live mode uses a TUI interface with its own controls." + ) + return + + # Validate gecko mode doesn't use non-wall mode + if args.format == "gecko" and getattr(args, 'mode', 'wall') != "wall": + parser.error( + "--mode option is incompatible with --gecko. " + "Gecko format automatically includes both GIL-holding and CPU status analysis." + ) + + # Validate --opcodes is only used with compatible formats + opcodes_compatible_formats = ("live", "gecko", "flamegraph", "diff_flamegraph", "heatmap", "binary") + if getattr(args, 'opcodes', False) and args.format not in opcodes_compatible_formats: + parser.error( + f"--opcodes is only compatible with {', '.join('--' + f for f in opcodes_compatible_formats)}." + ) + + # Validate pstats-specific options are only used with pstats format + if args.format != "pstats": + issues = [] + if args.sort is not None: + issues.append("--sort") + if args.limit is not None: + issues.append("--limit") + if args.no_summary: + issues.append("--no-summary") + + if issues: + format_flag = f"--{args.format}" + parser.error( + f"Options {', '.join(issues)} are only valid with --pstats, not {format_flag}" + ) + + +def main(): + """Main entry point for the CLI.""" + # Set locale for number formatting, restore on exit + old_locale = locale.setlocale(locale.LC_ALL, None) + locale.setlocale(locale.LC_ALL, "") + try: + _main() + finally: + locale.setlocale(locale.LC_ALL, old_locale) + + +def _main(): + # Create the main parser + parser = argparse.ArgumentParser( + description=_HELP_DESCRIPTION, + formatter_class=CustomFormatter, + ) + + # Create subparsers for commands + subparsers = parser.add_subparsers( + dest="command", required=True, help="Command to run" + ) + + # === RUN COMMAND === + run_parser = subparsers.add_parser( + "run", + help="Run and profile a script or module", + formatter_class=CustomFormatter, + description="""Run and profile a Python script or module + +Examples: + # Run and profile a module + `python -m profiling.sampling run -m mymodule arg1 arg2` + + # Generate flamegraph from a script + `python -m profiling.sampling run --flamegraph -o output.html script.py` + + # Profile with custom rate and duration + `python -m profiling.sampling run -r 5khz -d 30 script.py` + + # Save collapsed stacks to file + `python -m profiling.sampling run --collapsed -o stacks.txt script.py` + + # Live interactive mode for a script + `python -m profiling.sampling run --live script.py`""", + ) + run_parser.add_argument( + "-m", + "--module", + action="store_true", + help="Run target as a module (like `python -m`)", + ) + run_parser.add_argument( + "target", + help="Script file or module name to profile", + ) + run_parser.add_argument( + "args", + nargs=argparse.REMAINDER, + help="Arguments to pass to the script or module", + ) + run_parser.add_argument( + "--live", + action="store_true", + help="Interactive TUI profiler (top-like interface, press 'q' to quit, 's' to cycle sort)", + ) + _add_sampling_options(run_parser) + _add_mode_options(run_parser) + _add_format_options(run_parser) + _add_pstats_options(run_parser) + + # === ATTACH COMMAND === + attach_parser = subparsers.add_parser( + "attach", + help="Attach to and profile a running process", + formatter_class=CustomFormatter, + description="""Attach to a running process and profile it + +Examples: + # Profile all threads, sort by total time + `python -m profiling.sampling attach -a --sort tottime 1234` + + # Live interactive mode for a running process + `python -m profiling.sampling attach --live 1234`""", + ) + attach_parser.add_argument( + "pid", + type=int, + help="Process ID to attach to", + ) + attach_parser.add_argument( + "--live", + action="store_true", + help="Interactive TUI profiler (top-like interface, press 'q' to quit, 's' to cycle sort)", + ) + _add_sampling_options(attach_parser) + _add_mode_options(attach_parser) + _add_format_options(attach_parser) + _add_pstats_options(attach_parser) + + # === DUMP COMMAND === + dump_parser = subparsers.add_parser( + "dump", + help="Dump a running process's current stack", + formatter_class=CustomFormatter, + description="""Dump a running process's current Python stack + +Examples: + # Dump the main thread stack + `python -m profiling.sampling dump 1234` + + # Dump all thread stacks + `python -m profiling.sampling dump -a 1234`""", + ) + dump_parser.add_argument( + "pid", + type=int, + help="Process ID to dump", + ) + _add_dump_options(dump_parser) + + # === REPLAY COMMAND === + replay_parser = subparsers.add_parser( + "replay", + help="Replay a binary profile and convert to another format", + formatter_class=CustomFormatter, + description="""Replay a binary profile file and convert to another format + +Examples: + # Convert binary to flamegraph + `python -m profiling.sampling replay --flamegraph -o output.html profile.bin` + + # Convert binary to pstats and print to stdout + `python -m profiling.sampling replay profile.bin` + + # Convert binary to gecko format + `python -m profiling.sampling replay --gecko -o profile.json profile.bin`""", + ) + replay_parser.add_argument( + "input_file", + help="Binary profile file to replay", + ) + _add_format_options(replay_parser, include_compression=False, include_binary=False) + _add_pstats_options(replay_parser) + + # Parse arguments + args = parser.parse_args() + + # Validate arguments + _validate_args(args, parser) + + # Command dispatch table + command_handlers = { + "run": _handle_run, + "attach": _handle_attach, + "dump": _handle_dump, + "replay": _handle_replay, + } + + # Execute the appropriate command + handler = command_handlers.get(args.command) + if handler: + handler(args) + else: + parser.error(f"Unknown command: {args.command}") + + +def _handle_attach(args): + """Handle the 'attach' command.""" + if not _is_process_running(args.pid): + raise SamplingUnknownProcessError(args.pid) + # Check if live mode is requested + if args.live: + _handle_live_attach(args, args.pid) + return + + # Use PROFILING_MODE_ALL for gecko format + mode = ( + PROFILING_MODE_ALL + if args.format == "gecko" + else _parse_mode(args.mode) + ) + + # Determine skip_idle based on mode + skip_idle = ( + mode != PROFILING_MODE_WALL if mode != PROFILING_MODE_ALL else False + ) + + output_file = None + if args.format == "binary": + output_file = args.outfile or _generate_output_filename(args.format, args.pid) + + # Create the appropriate collector + collector = _create_collector( + args.format, args.sample_interval_usec, skip_idle, args.opcodes, mode, + output_file=output_file, + compression=getattr(args, 'compression', 'auto'), + diff_baseline=args.diff_baseline, + capture_config=_capture_config_from_args(args), + ) + + with _get_child_monitor_context(args, args.pid): + collector = sample( + args.pid, + collector, + duration_sec=args.duration, + all_threads=args.all_threads, + realtime_stats=args.realtime_stats, + mode=mode, + async_aware=args.async_mode if args.async_aware else None, + native=args.native, + gc=args.gc, + opcodes=args.opcodes, + blocking=args.blocking, + ) + _handle_output(collector, args, args.pid, mode) + + +def _handle_dump(args): + if not _is_process_running(args.pid): + raise SamplingUnknownProcessError(args.pid) + + # Async-aware reconstruction requires wall mode so every thread is sampled, + # not just those holding the GIL or on CPU. + mode = PROFILING_MODE_WALL if args.async_aware else PROFILING_MODE_ALL + async_mode = getattr(args, "async_mode", "all") if args.async_aware else None + try: + stack_frames = dump_stack( + args.pid, + all_threads=args.all_threads, + mode=mode, + async_aware=async_mode, + native=args.native, + gc=args.gc, + opcodes=args.opcodes, + blocking=args.blocking, + ) + except ProcessLookupError: + sys.exit( + f"No stack dump collected - process {args.pid} exited before " + "its stack could be read." + ) + + print_stack_dump(stack_frames, pid=args.pid) + + +def _handle_run(args): + """Handle the 'run' command.""" + # Validate target exists before launching subprocess + if args.module: + # Temporarily add cwd to sys.path so we can find modules in the + # current directory, matching the coordinator's behavior + cwd = os.getcwd() + added_cwd = False + if cwd not in sys.path: + sys.path.insert(0, cwd) + added_cwd = True + try: + if importlib.util.find_spec(args.target) is None: + raise SamplingModuleNotFoundError(args.target) + finally: + if added_cwd: + sys.path.remove(cwd) + else: + if not os.path.exists(args.target): + raise SamplingScriptNotFoundError(args.target) + + # Check if live mode is requested + if args.live: + _handle_live_run(args) + return + + # Build the command to run + if args.module: + cmd = (sys.executable, "-m", args.target, *args.args) + else: + cmd = (sys.executable, args.target, *args.args) + + # Run with synchronization + try: + process = _run_with_sync(cmd, suppress_output=False) + except RuntimeError as e: + sys.exit(f"Error: {e}") + + # Use PROFILING_MODE_ALL for gecko format + mode = ( + PROFILING_MODE_ALL + if args.format == "gecko" + else _parse_mode(args.mode) + ) + + # Determine skip_idle based on mode + skip_idle = ( + mode != PROFILING_MODE_WALL if mode != PROFILING_MODE_ALL else False + ) + + output_file = None + if args.format == "binary": + output_file = args.outfile or _generate_output_filename(args.format, process.pid) + + # Create the appropriate collector + collector = _create_collector( + args.format, args.sample_interval_usec, skip_idle, args.opcodes, mode, + output_file=output_file, + compression=getattr(args, 'compression', 'auto'), + diff_baseline=args.diff_baseline, + capture_config=_capture_config_from_args(args), + ) + + with _get_child_monitor_context(args, process.pid): + try: + collector = sample( + process.pid, + collector, + duration_sec=args.duration, + all_threads=args.all_threads, + realtime_stats=args.realtime_stats, + mode=mode, + async_aware=args.async_mode if args.async_aware else None, + native=args.native, + gc=args.gc, + opcodes=args.opcodes, + blocking=args.blocking, + ) + _handle_output(collector, args, process.pid, mode) + finally: + # Terminate the main subprocess - child profilers finish when their + # target processes exit + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=_PROCESS_KILL_TIMEOUT_SEC) + except subprocess.TimeoutExpired: + process.kill() + process.wait() + + +def _handle_live_attach(args, pid): + """Handle live mode for an existing process.""" + mode = _parse_mode(args.mode) + + # Determine skip_idle based on mode + skip_idle = mode != PROFILING_MODE_WALL + + # Create live collector with default settings + collector = LiveStatsCollector( + args.sample_interval_usec, + skip_idle=skip_idle, + sort_by="tottime", # Default initial sort + limit=20, # Default limit + pid=pid, + mode=mode, + opcodes=args.opcodes, + async_aware=args.async_mode if args.async_aware else None, + ) + + # Sample in live mode + sample_live( + pid, + collector, + duration_sec=args.duration, + all_threads=args.all_threads, + realtime_stats=args.realtime_stats, + mode=mode, + async_aware=args.async_mode if args.async_aware else None, + native=args.native, + gc=args.gc, + opcodes=args.opcodes, + blocking=args.blocking, + ) + + +def _handle_live_run(args): + """Handle live mode for running a script/module.""" + # Build the command to run + if args.module: + cmd = (sys.executable, "-m", args.target, *args.args) + else: + cmd = (sys.executable, args.target, *args.args) + + # Run with synchronization, suppressing output for live mode + try: + process = _run_with_sync(cmd, suppress_output=True) + except RuntimeError as e: + sys.exit(f"Error: {e}") + + mode = _parse_mode(args.mode) + + # Determine skip_idle based on mode + skip_idle = mode != PROFILING_MODE_WALL + + # Create live collector with default settings + collector = LiveStatsCollector( + args.sample_interval_usec, + skip_idle=skip_idle, + sort_by="tottime", # Default initial sort + limit=20, # Default limit + pid=process.pid, + mode=mode, + opcodes=args.opcodes, + async_aware=args.async_mode if args.async_aware else None, + ) + + # Profile the subprocess in live mode + try: + sample_live( + process.pid, + collector, + duration_sec=args.duration, + all_threads=args.all_threads, + realtime_stats=args.realtime_stats, + mode=mode, + async_aware=args.async_mode if args.async_aware else None, + native=args.native, + gc=args.gc, + opcodes=args.opcodes, + blocking=args.blocking, + ) + finally: + # Clean up the subprocess and get any error output + returncode = process.poll() + if returncode is None: + # Process still running - terminate it + process.terminate() + try: + process.wait(timeout=_PROCESS_KILL_TIMEOUT_SEC) + except subprocess.TimeoutExpired: + process.kill() + # Ensure process is fully terminated + process.wait() + # Read any stderr output (tracebacks, errors, etc.) + if process.stderr: + with process.stderr: + try: + stderr = process.stderr.read() + if stderr: + print(stderr.decode(), file=sys.stderr) + except (OSError, ValueError): + # Ignore errors if pipe is already closed + pass + + +def _handle_replay(args): + """Handle the 'replay' command - convert binary profile to another format.""" + if not os.path.exists(args.input_file): + sys.exit(f"Error: Input file not found: {args.input_file}") + + _validate_replay_input_file(args.input_file) + + try: + with BinaryReader(args.input_file) as reader: + _replay_with_reader(args, reader) + except (OSError, ValueError) as exc: + sys.exit(f"Error: {exc}") + + +if __name__ == "__main__": + main() diff --git a/Lib/profiling/sampling/collector.py b/Lib/profiling/sampling/collector.py new file mode 100644 index 00000000000..1dc3656e0eb --- /dev/null +++ b/Lib/profiling/sampling/collector.py @@ -0,0 +1,292 @@ +from abc import ABC, abstractmethod +from .constants import ( + DEFAULT_LOCATION, + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_UNKNOWN, + THREAD_STATUS_HAS_EXCEPTION, + _INTERNAL_FRAME_SUFFIXES, +) + +try: + from _remote_debugging import FrameInfo +except ImportError: + # Fallback definition if _remote_debugging is not available + FrameInfo = None + + +def normalize_location(location): + """Normalize location to a 4-tuple format. + + Args: + location: tuple (lineno, end_lineno, col_offset, end_col_offset), + an integer line number, or None + + Returns: + tuple: (lineno, end_lineno, col_offset, end_col_offset) + """ + if location is None: + return DEFAULT_LOCATION + if isinstance(location, int): + return (location, location, -1, -1) + return location + + +def extract_lineno(location): + """Extract lineno from location. + + Args: + location: tuple (lineno, end_lineno, col_offset, end_col_offset), + an integer line number, or None + + Returns: + int: The line number (0 for synthetic frames) + """ + if location is None: + return 0 + if isinstance(location, int): + return location + return location[0] + +def _is_internal_frame(frame): + if isinstance(frame, tuple): + filename = frame[0] if frame else "" + else: + filename = getattr(frame, "filename", "") + + if not filename: + return False + + return filename.endswith(_INTERNAL_FRAME_SUFFIXES) + + +def filter_internal_frames(frames): + if not frames: + return frames + + return [f for f in frames if not _is_internal_frame(f)] + + +def _build_task_graph(awaited_info_list): + task_map = {} + child_to_parent = {} # child_id -> (selected_parent_id, parent_count) + all_task_ids = set() + all_parent_ids = set() + + for awaited_info in awaited_info_list: + thread_id = awaited_info.thread_id + for task_info in awaited_info.awaited_by: + task_id = task_info.task_id + task_map[task_id] = (task_info, thread_id) + all_task_ids.add(task_id) + + if task_info.awaited_by: + parent_ids = [p.task_name for p in task_info.awaited_by] + parent_count = len(parent_ids) + all_parent_ids.update(parent_ids) + selected_parent = min(parent_ids) if parent_count > 1 else parent_ids[0] + child_to_parent[task_id] = (selected_parent, parent_count) + + return task_map, child_to_parent, all_task_ids, all_parent_ids + + +def _find_leaf_tasks(all_task_ids, all_parent_ids): + return all_task_ids - all_parent_ids + + +def _build_linear_stacks(leaf_task_ids, task_map, child_to_parent): + for leaf_id in leaf_task_ids: + frames = [] + visited = set() + current_id = leaf_id + thread_id = None + + while current_id is not None: + if current_id in visited: + break + visited.add(current_id) + + if current_id not in task_map: + break + + task_info, tid = task_map[current_id] + + if thread_id is None: + thread_id = tid + + if task_info.coroutine_stack: + for coro_info in task_info.coroutine_stack: + for frame in coro_info.call_stack: + frames.append(frame) + + parent_info = child_to_parent.get(current_id) + task_name = task_info.task_name or "Task-" + str(task_info.task_id) + if parent_info: + selected_parent, parent_count = parent_info + if parent_count > 1: + task_name = f"{task_name} ({parent_count} parents)" + frames.append(FrameInfo(("", None, task_name, None))) + current_id = selected_parent + else: + frames.append(FrameInfo(("", None, task_name, None))) + current_id = None + + if frames and thread_id is not None: + yield frames, thread_id, leaf_id + + +def iter_async_frames(awaited_info_list): + task_map, child_to_parent, all_task_ids, all_parent_ids = _build_task_graph(awaited_info_list) + leaf_task_ids = _find_leaf_tasks(all_task_ids, all_parent_ids) + yield from _build_linear_stacks(leaf_task_ids, task_map, child_to_parent) + + +class Collector(ABC): + aggregating = False + + @abstractmethod + def collect(self, stack_frames, timestamps_us=None): + """Collect profiling data from stack frames. + + Args: + stack_frames: List of InterpreterInfo objects + timestamps_us: Optional list of timestamps in microseconds. If provided + (from binary replay with RLE batching), use these instead of current + time. If None, collectors should use time.monotonic() or similar. + The list may contain multiple timestamps when samples are batched + together (same stack, different times). + """ + + def collect_failed_sample(self): + """Collect data about a failed sample attempt.""" + + @abstractmethod + def export(self, filename): + """Export collected data. + + Returns: + bool: True if output was generated, False if there was no data to export. + """ + + @staticmethod + def _filter_internal_frames(frames): + return filter_internal_frames(frames) + + def _iter_all_frames(self, stack_frames, skip_idle=False): + for interpreter_info in stack_frames: + for thread_info in interpreter_info.threads: + # skip_idle now means: skip if thread is not actively running + # A thread is "active" if it has the GIL OR is on CPU + if skip_idle: + status_flags = thread_info.status + has_gil = bool(status_flags & THREAD_STATUS_HAS_GIL) + on_cpu = bool(status_flags & THREAD_STATUS_ON_CPU) + if not (has_gil or on_cpu): + continue + frames = thread_info.frame_info + if frames: + # Filter out internal profiler frames from the bottom of the stack + frames = self._filter_internal_frames(frames) + if frames: + yield frames, thread_info.thread_id + + def _iter_async_frames(self, awaited_info_list): + yield from iter_async_frames(awaited_info_list) + + def _iter_stacks(self, stack_frames, skip_idle=False): + """Yield (frames, thread_id) for all stacks, handling both sync and async modes.""" + if stack_frames and hasattr(stack_frames[0], "awaited_by"): + for frames, thread_id, _ in iter_async_frames(stack_frames): + if frames: + yield frames, thread_id + else: + for frames, thread_id in self._iter_all_frames(stack_frames, skip_idle=skip_idle): + if frames: + yield frames, thread_id + + def _is_gc_frame(self, frame): + if isinstance(frame, tuple): + funcname = frame[2] if len(frame) >= 3 else "" + else: + funcname = getattr(frame, "funcname", "") + + return "" in funcname or "gc_collect" in funcname + + def _collect_thread_status_stats(self, stack_frames): + """Collect aggregate and per-thread status statistics from a sample. + + Returns: + tuple: (aggregate_status_counts, has_gc_frame, per_thread_stats) + - aggregate_status_counts: dict with has_gil, on_cpu, has_exception, etc. + - has_gc_frame: bool indicating if any thread has GC frames + - per_thread_stats: dict mapping thread_id to per-thread counts + """ + status_counts = { + "has_gil": 0, + "on_cpu": 0, + "gil_requested": 0, + "unknown": 0, + "has_exception": 0, + "total": 0, + } + has_gc_frame = False + per_thread_stats = {} + + for interpreter_info in stack_frames: + threads = getattr(interpreter_info, "threads", []) + for thread_info in threads: + status_counts["total"] += 1 + + # Track thread status using bit flags + status_flags = getattr(thread_info, "status", 0) + + if status_flags & THREAD_STATUS_HAS_GIL: + status_counts["has_gil"] += 1 + if status_flags & THREAD_STATUS_ON_CPU: + status_counts["on_cpu"] += 1 + if status_flags & THREAD_STATUS_GIL_REQUESTED: + status_counts["gil_requested"] += 1 + if status_flags & THREAD_STATUS_UNKNOWN: + status_counts["unknown"] += 1 + if status_flags & THREAD_STATUS_HAS_EXCEPTION: + status_counts["has_exception"] += 1 + + # Track per-thread statistics + thread_id = getattr(thread_info, "thread_id", None) + if thread_id is not None: + if thread_id not in per_thread_stats: + per_thread_stats[thread_id] = { + "has_gil": 0, + "on_cpu": 0, + "gil_requested": 0, + "unknown": 0, + "has_exception": 0, + "total": 0, + "gc_samples": 0, + } + + thread_stats = per_thread_stats[thread_id] + thread_stats["total"] += 1 + + if status_flags & THREAD_STATUS_HAS_GIL: + thread_stats["has_gil"] += 1 + if status_flags & THREAD_STATUS_ON_CPU: + thread_stats["on_cpu"] += 1 + if status_flags & THREAD_STATUS_GIL_REQUESTED: + thread_stats["gil_requested"] += 1 + if status_flags & THREAD_STATUS_UNKNOWN: + thread_stats["unknown"] += 1 + if status_flags & THREAD_STATUS_HAS_EXCEPTION: + thread_stats["has_exception"] += 1 + + # Check for GC frames in this thread + frames = getattr(thread_info, "frame_info", None) + if frames: + for frame in frames: + if self._is_gc_frame(frame): + thread_stats["gc_samples"] += 1 + has_gc_frame = True + break + + return status_counts, has_gc_frame, per_thread_stats diff --git a/Lib/profiling/sampling/constants.py b/Lib/profiling/sampling/constants.py new file mode 100644 index 00000000000..d7c710f943b --- /dev/null +++ b/Lib/profiling/sampling/constants.py @@ -0,0 +1,57 @@ +"""Constants for the sampling profiler.""" + +# Time unit conversion constants +MICROSECONDS_PER_SECOND = 1_000_000 +MILLISECONDS_PER_SECOND = 1_000 + +# Profiling mode constants +PROFILING_MODE_WALL = 0 +PROFILING_MODE_CPU = 1 +PROFILING_MODE_GIL = 2 +PROFILING_MODE_ALL = 3 # Combines GIL + CPU checks +PROFILING_MODE_EXCEPTION = 4 # Only samples when thread has an active exception + +PROFILING_MODE_NAMES = { + PROFILING_MODE_WALL: "wall", + PROFILING_MODE_CPU: "cpu", + PROFILING_MODE_GIL: "gil", + PROFILING_MODE_ALL: "all", + PROFILING_MODE_EXCEPTION: "exception", +} + +# Sort mode constants +SORT_MODE_NSAMPLES = 0 +SORT_MODE_TOTTIME = 1 +SORT_MODE_CUMTIME = 2 +SORT_MODE_SAMPLE_PCT = 3 +SORT_MODE_CUMUL_PCT = 4 +SORT_MODE_NSAMPLES_CUMUL = 5 + +# Default location for synthetic frames (native, GC) that have no source location +# Format: (lineno, end_lineno, col_offset, end_col_offset) +DEFAULT_LOCATION = (0, 0, -1, -1) + +# Internal frame path suffixes to filter from profiling output +# These are internal profiler modules that should not appear in user-facing output +_INTERNAL_FRAME_SUFFIXES = ( + "_sync_coordinator.py", +) + +# Thread status flags +try: + from _remote_debugging import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_UNKNOWN, + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_HAS_EXCEPTION, + THREAD_STATUS_MAIN_THREAD, + ) +except ImportError: + # Fallback for tests or when module is not available + THREAD_STATUS_HAS_GIL = (1 << 0) + THREAD_STATUS_ON_CPU = (1 << 1) + THREAD_STATUS_UNKNOWN = (1 << 2) + THREAD_STATUS_GIL_REQUESTED = (1 << 3) + THREAD_STATUS_HAS_EXCEPTION = (1 << 4) + THREAD_STATUS_MAIN_THREAD = (1 << 5) diff --git a/Lib/profiling/sampling/dump.py b/Lib/profiling/sampling/dump.py new file mode 100644 index 00000000000..7cf43bd29eb --- /dev/null +++ b/Lib/profiling/sampling/dump.py @@ -0,0 +1,295 @@ +"""Pretty printing for one-shot sampling stack dumps.""" + +import contextlib +import linecache +import os +import sys +from traceback import _byte_offset_to_character_offset + +import _colorize + +from .collector import extract_lineno, filter_internal_frames, iter_async_frames +from .constants import ( + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_HAS_EXCEPTION, + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_MAIN_THREAD, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_UNKNOWN, +) +from .opcode_utils import format_opcode + + +_STATUS_LABELS = ( + (THREAD_STATUS_MAIN_THREAD, "main thread"), + (THREAD_STATUS_HAS_GIL, "has GIL"), + (THREAD_STATUS_ON_CPU, "on CPU"), + (THREAD_STATUS_GIL_REQUESTED, "waiting for GIL"), + (THREAD_STATUS_HAS_EXCEPTION, "has exception"), +) + + +def _theme_for(file, colorize): + if colorize is True: + return _colorize.get_theme(force_color=True).profiler_dump + if colorize is False: + return _colorize.get_theme(force_no_color=True).profiler_dump + return _colorize.get_theme(tty_file=file).profiler_dump + + +def _color(text, color, theme): + if not color: + return text + return f"{color}{text}{theme.reset}" + + +def _frame_fields(frame): + if isinstance(frame, tuple): + filename = frame[0] if len(frame) > 0 else "" + location = frame[1] if len(frame) > 1 else None + qualname = frame[2] if len(frame) > 2 else "" + opcode = frame[3] if len(frame) > 3 else None + else: + filename = getattr(frame, "filename", "") + location = getattr(frame, "location", None) + qualname = getattr(frame, "qualname", None) + if qualname is None: + qualname = getattr(frame, "funcname", "") + opcode = getattr(frame, "opcode", None) + return filename, location, qualname, opcode + + +def _location_field(location, index, default=None): + if location is None: + return default + try: + value = location[index] + except (IndexError, TypeError): + return default + return default if value is None else value + + +def _status_text(status): + labels = [label for flag, label in _STATUS_LABELS if status & flag] + has_state = status & ( + THREAD_STATUS_HAS_GIL + | THREAD_STATUS_GIL_REQUESTED + | THREAD_STATUS_HAS_EXCEPTION + ) + if not has_state and not status & (THREAD_STATUS_UNKNOWN | THREAD_STATUS_ON_CPU): + labels.append("idle") + return ", ".join(labels) if labels else None + + +def _is_async_dump(stack_frames): + return bool(stack_frames) and hasattr(stack_frames[0], "awaited_by") + + +def _iter_dump_sections(stack_frames): + if not stack_frames: + return + + if _is_async_dump(stack_frames): + for frames, thread_id, leaf_id in iter_async_frames(stack_frames): + frames = filter_internal_frames(frames) + if frames: + yield None, thread_id, None, frames, f"task {leaf_id}" + return + + for interpreter_info in stack_frames: + interpreter_id = getattr(interpreter_info, "interpreter_id", None) + for thread_info in getattr(interpreter_info, "threads", ()): + frames = getattr(thread_info, "frame_info", None) or [] + frames = filter_internal_frames(frames) + yield ( + interpreter_id, + getattr(thread_info, "thread_id", None), + getattr(thread_info, "status", None), + frames, + None, + ) + + +def _display_filename(filename): + if not filename or filename == "~": + return filename + with contextlib.suppress(ValueError): + relpath = os.path.relpath(filename) + if not relpath.startswith(".." + os.sep) and relpath != "..": + return relpath + return filename + + +def _format_frame(frame, theme): + filename, location, qualname, opcode = _frame_fields(frame) + source_filename = filename + lineno = extract_lineno(location) + qualname_part = _color(qualname, theme.frame, theme) + + if filename == "~" and lineno == 0: + line = f" {qualname_part}" + else: + filename = _display_filename(filename) + if filename: + file_part = _color(f'"{filename}"', theme.filename, theme) + if lineno > 0: + line_part = _color(str(lineno), theme.line_no, theme) + line = f" File {file_part}, line {line_part}, in {qualname_part}" + else: + line = f" File {file_part}, in {qualname_part}" + else: + line = f" {qualname_part}" + + if opcode is not None: + line = f"{line} {_color(f'opcode={format_opcode(opcode)}', theme.opcode, theme)}" + + lines = [line] + source = _source_line(source_filename, location, lineno, theme) + if source: + lines.append(f" {source}") + return lines + + +def _source_offsets(line, location, lineno): + end_lineno = _location_field(location, 1, lineno) + col_offset = _location_field(location, 2, -1) + end_col_offset = _location_field(location, 3, -1) + + if col_offset < 0 or end_col_offset < 0 or end_lineno < lineno: + return None + + start = _byte_offset_to_character_offset(line, col_offset) + if end_lineno == lineno: + end = _byte_offset_to_character_offset(line, end_col_offset) + else: + end = len(line) + if start < 0 or end <= start: + return None + return start, end + + +def _trim_source_line(line, offsets): + stripped = line.lstrip() + leading = len(line) - len(stripped) + if offsets is None: + return stripped, None + + start, end = offsets + start = max(start - leading, 0) + end = max(end - leading, start + 1) + end = min(end, len(stripped)) + return stripped, (start, end) + + +def _highlight_source_line(line, offsets, theme): + if offsets is None or offsets[1] <= offsets[0]: + return _color(line, theme.source, theme) + + start, end = offsets + parts = [] + if line[:start]: + parts.append(_color(line[:start], theme.source, theme)) + parts.append(_color(line[start:end], theme.source_highlight, theme)) + if line[end:]: + parts.append(_color(line[end:], theme.source, theme)) + return "".join(parts) + + +def _source_line(filename, location, lineno, theme): + if not filename or filename == "~" or lineno <= 0: + return None + line = linecache.getline(filename, lineno).removesuffix("\n") + if not line: + return None + + offsets = _source_offsets(line, location, lineno) + line, offsets = _trim_source_line(line, offsets) + if not line: + return None + return _highlight_source_line(line, offsets, theme) + + +def _section_header( + *, + pid, + interpreter_id, + thread_id, + status, + label, + show_pid, + show_interpreter, + theme, +): + subject = "Stack dump" + if show_pid and pid is not None: + subject = f"{subject} for PID {pid}" + if thread_id is not None: + subject = f"{subject}, thread {thread_id}" + + details = [] + if show_interpreter and interpreter_id is not None: + details.append(f"interpreter {interpreter_id}") + if label: + details.append(label) + if status is not None: + status_text = _status_text(status) + if status_text: + details.append(status_text) + + suffix = "most recent call last" + if details: + suffix = f"{'; '.join(details)}; {suffix}" + return _color(f"{subject} ({suffix}):", theme.header, theme) + + +def format_stack_dump(stack_frames, *, pid=None, file=None, colorize=None): + """Return a formatted one-shot stack dump.""" + if file is None: + file = sys.stdout + + theme = _theme_for(file, colorize) + lines = [] + sections = list(_iter_dump_sections(stack_frames)) + if not sections: + if pid is None: + return f"{_color('No Python stacks found', theme.warning, theme)}\n" + return f"{_color(f'No Python stacks found for PID {pid}', theme.warning, theme)}\n" + + interpreter_ids = { + interpreter_id + for interpreter_id, _thread_id, _status, _frames, _label in sections + if interpreter_id is not None + } + show_interpreter = len(interpreter_ids) > 1 + + for section_index, (interpreter_id, thread_id, status, frames, label) in enumerate(sections): + if section_index: + lines.append("") + lines.append( + _section_header( + pid=pid, + interpreter_id=interpreter_id, + thread_id=thread_id, + status=status, + label=label, + show_pid=section_index == 0, + show_interpreter=show_interpreter, + theme=theme, + ) + ) + + if not frames: + lines.append(_color("No Python frames", theme.warning, theme)) + continue + + for frame in reversed(frames): + lines.extend(_format_frame(frame, theme)) + + return "\n".join(lines) + "\n" + + +def print_stack_dump(stack_frames, *, pid=None, file=None, colorize=None): + """Pretty-print a one-shot stack dump.""" + if file is None: + file = sys.stdout + file.write(format_stack_dump(stack_frames, pid=pid, file=file, colorize=colorize)) diff --git a/Lib/profiling/sampling/errors.py b/Lib/profiling/sampling/errors.py new file mode 100644 index 00000000000..0832ad2d438 --- /dev/null +++ b/Lib/profiling/sampling/errors.py @@ -0,0 +1,19 @@ +"""Custom exceptions for the sampling profiler.""" + +class SamplingProfilerError(Exception): + """Base exception for sampling profiler errors.""" + +class SamplingUnknownProcessError(SamplingProfilerError): + def __init__(self, pid): + self.pid = pid + super().__init__(f"Process with PID '{pid}' does not exist.") + +class SamplingScriptNotFoundError(SamplingProfilerError): + def __init__(self, script_path): + self.script_path = script_path + super().__init__(f"Script '{script_path}' not found.") + +class SamplingModuleNotFoundError(SamplingProfilerError): + def __init__(self, module_name): + self.module_name = module_name + super().__init__(f"Module '{module_name}' not found.") diff --git a/Lib/profiling/sampling/gecko_collector.py b/Lib/profiling/sampling/gecko_collector.py new file mode 100644 index 00000000000..2de8cce387e --- /dev/null +++ b/Lib/profiling/sampling/gecko_collector.py @@ -0,0 +1,1006 @@ +import itertools +import io +import json +import os +import platform +import sys +import tempfile +import threading +import time + +from .collector import Collector, filter_internal_frames +from .opcode_utils import get_opcode_info, format_opcode +try: + from _remote_debugging import THREAD_STATUS_HAS_GIL, THREAD_STATUS_ON_CPU, THREAD_STATUS_UNKNOWN, THREAD_STATUS_GIL_REQUESTED, THREAD_STATUS_HAS_EXCEPTION, THREAD_STATUS_MAIN_THREAD +except ImportError: + # Fallback if module not available (shouldn't happen in normal use) + THREAD_STATUS_HAS_GIL = (1 << 0) + THREAD_STATUS_ON_CPU = (1 << 1) + THREAD_STATUS_UNKNOWN = (1 << 2) + THREAD_STATUS_GIL_REQUESTED = (1 << 3) + THREAD_STATUS_HAS_EXCEPTION = (1 << 4) + THREAD_STATUS_MAIN_THREAD = (1 << 5) + + +# Categories matching Firefox Profiler expectations +GECKO_CATEGORIES = [ + {"name": "Other", "color": "grey", "subcategories": ["Other"]}, + {"name": "Python", "color": "yellow", "subcategories": ["Other"]}, + {"name": "Native", "color": "blue", "subcategories": ["Other"]}, + {"name": "GC", "color": "orange", "subcategories": ["Other"]}, + {"name": "GIL", "color": "green", "subcategories": ["Other"]}, + {"name": "CPU", "color": "purple", "subcategories": ["Other"]}, + {"name": "Code Type", "color": "red", "subcategories": ["Other"]}, + {"name": "Opcodes", "color": "magenta", "subcategories": ["Other"]}, + {"name": "Exception", "color": "lightblue", "subcategories": ["Other"]}, +] + +# Category indices +CATEGORY_OTHER = 0 +CATEGORY_PYTHON = 1 +CATEGORY_NATIVE = 2 +CATEGORY_GC = 3 +CATEGORY_GIL = 4 +CATEGORY_CPU = 5 +CATEGORY_CODE_TYPE = 6 +CATEGORY_OPCODES = 7 +CATEGORY_EXCEPTION = 8 + +# Subcategory indices +DEFAULT_SUBCATEGORY = 0 + +GECKO_FORMAT_VERSION = 32 +GECKO_PREPROCESSED_VERSION = 57 + +# Resource type constants +RESOURCE_TYPE_LIBRARY = 1 + +# Frame constants +FRAME_ADDRESS_NONE = -1 +FRAME_INLINE_DEPTH_ROOT = 0 + +# Process constants +PROCESS_TYPE_MAIN = 0 +STACKWALK_DISABLED = 0 + +# In-memory buffer before spilling to disk +DEFAULT_SPILL_BUFFER_BYTES = 128 * 1024 +_JSON_SEPARATORS = (",", ":") +_JSON_ENCODER = json.JSONEncoder( + separators=_JSON_SEPARATORS, allow_nan=False +) + + +class SpillColumn: + def __init__(self, directory, basename, *, + buffer_bytes=None): + self.path = os.path.join(directory, basename) + self.buffer = bytearray() + self._buffer_bytes = ( + DEFAULT_SPILL_BUFFER_BYTES if buffer_bytes is None + else buffer_bytes + ) + + def append(self, value): + self.buffer += (_JSON_ENCODER.encode(value) + "\n").encode("utf-8") + if len(self.buffer) >= self._buffer_bytes: + self.flush() + + def flush(self): + with open(self.path, "ab") as file: + file.write(self.buffer) + self.buffer.clear() + + def iter_tokens(self): + with open(self.path, encoding="utf-8") as file: + for line in file: + yield line.rstrip("\n") + + +class GeckoThreadSpill: + _COLUMNS = ( + ("samples_stack", "samples-stack.json"), + ("samples_time", "samples-time.json"), + ("markers_name", "markers-name.json"), + ("markers_start_time", "markers-start-time.json"), + ("markers_end_time", "markers-end-time.json"), + ("markers_phase", "markers-phase.json"), + ("markers_category", "markers-category.json"), + ("markers_data", "markers-data.json"), + ) + + def __init__(self, directory, tid): + prefix = f"thread-{tid}-" + for attr, basename in self._COLUMNS: + setattr(self, attr, SpillColumn(directory, prefix + basename)) + self.sample_count = 0 + self.marker_count = 0 + + def append_sample(self, stack_index, time_ms): + self.samples_stack.append(stack_index) + self.samples_time.append(time_ms) + self.sample_count += 1 + + def append_marker(self, name_idx, start_time, end_time, phase, category, data): + self.markers_name.append(name_idx) + self.markers_start_time.append(start_time) + self.markers_end_time.append(end_time) + self.markers_phase.append(phase) + self.markers_category.append(category) + self.markers_data.append(data) + self.marker_count += 1 + + def prepare_read(self): + for attr, _basename in self._COLUMNS: + getattr(self, attr).flush() + + +class GeckoCollector(Collector): + aggregating = True + + def __init__(self, sample_interval_usec, *, skip_idle=False, opcodes=False): + self.sample_interval_usec = sample_interval_usec + self.skip_idle = skip_idle + self.opcodes_enabled = opcodes + self.start_time = time.monotonic() * 1000 # milliseconds since start + + # Global string table (shared across all threads) + self.global_strings = ["(root)"] # Start with root + self.global_string_map = {"(root)": 0} + + # Per-thread data structures + self.threads = {} # tid -> thread data + self.spill_dir = None + self.exported = False + + # Global tables + self.libs = [] + + # Sampling interval tracking + self.sample_count = 0 + self.last_sample_time = 0 + self.interval = 1.0 # Will be calculated from actual sampling + + # State tracking for interval markers (tid -> start_time) + self.has_gil_start = {} # Thread has the GIL + self.no_gil_start = {} # Thread doesn't have the GIL + self.on_cpu_start = {} # Thread is running on CPU + self.off_cpu_start = {} # Thread is off CPU + self.python_code_start = {} # Thread running Python code (has GIL) + self.native_code_start = {} # Thread running native code (on CPU without GIL) + self.gil_wait_start = {} # Thread waiting for GIL + self.exception_start = {} # Thread has an exception set + self.no_exception_start = {} # Thread has no exception set + + # GC event tracking: track GC start time per thread + self.gc_start_per_thread = {} # tid -> start_time + + # Track which threads have been initialized for state tracking + self.initialized_threads = set() + + # Opcode state tracking per thread: tid -> (opcode, lineno, col_offset, funcname, filename, start_time) + self.opcode_state = {} + + # For binary replay: track base timestamp (first sample's timestamp) + self._replay_base_timestamp_us = None + + def _track_state_transition(self, tid, condition, active_dict, inactive_dict, + active_name, inactive_name, category, current_time): + """Track binary state transitions and emit markers. + + Args: + tid: Thread ID + condition: Whether the active state is true + active_dict: Dict tracking start time of active state + inactive_dict: Dict tracking start time of inactive state + active_name: Name for active state marker + inactive_name: Name for inactive state marker + category: Gecko category for the markers + current_time: Current timestamp + """ + # On first observation of a thread, just record the current state + # without creating a marker (we don't know what the previous state was) + if tid not in self.initialized_threads: + if condition: + active_dict[tid] = current_time + else: + inactive_dict[tid] = current_time + return + + # For already-initialized threads, track transitions + if condition: + active_dict.setdefault(tid, current_time) + if tid in inactive_dict: + self._add_marker(tid, inactive_name, inactive_dict.pop(tid), + current_time, category) + else: + inactive_dict.setdefault(tid, current_time) + if tid in active_dict: + self._add_marker(tid, active_name, active_dict.pop(tid), + current_time, category) + + def collect(self, stack_frames, timestamps_us=None): + """Collect samples from stack frames. + + Args: + stack_frames: List of interpreter/thread frame info + timestamps_us: List of timestamps in microseconds (None for live sampling) + """ + if self.exported: + raise RuntimeError("cannot append to GeckoCollector after export") + + # Handle live sampling (no timestamps provided) + if timestamps_us is None: + current_time = (time.monotonic() * 1000) - self.start_time + times = [current_time] + else: + if not timestamps_us: + return + # Initialize base timestamp if needed + if self._replay_base_timestamp_us is None: + self._replay_base_timestamp_us = timestamps_us[0] + # Convert all timestamps to times (ms relative to first sample) + base = self._replay_base_timestamp_us + times = [(ts - base) / 1000 for ts in timestamps_us] + + first_time = times[0] + + # Update interval calculation + if self.sample_count > 0 and self.last_sample_time > 0: + self.interval = (times[-1] - self.last_sample_time) / self.sample_count + self.last_sample_time = times[-1] + + # Process async tasks + if stack_frames and hasattr(stack_frames[0], "awaited_by"): + for frames, thread_id, _ in self._iter_async_frames(stack_frames): + frames = filter_internal_frames(frames) + if not frames: + continue + + if thread_id not in self.threads: + self.threads[thread_id] = self._create_thread( + thread_id, False + ) + + self._record_stack_sample( + self.threads[thread_id], frames, thread_id, times, first_time + ) + + self.sample_count += len(times) + return + + # Process threads + for interpreter_info in stack_frames: + for thread_info in interpreter_info.threads: + frames = filter_internal_frames(thread_info.frame_info) + tid = thread_info.thread_id + status_flags = thread_info.status + is_main_thread = bool(status_flags & THREAD_STATUS_MAIN_THREAD) + + # Initialize thread if needed + if tid not in self.threads: + self.threads[tid] = self._create_thread(tid, is_main_thread) + + thread_data = self.threads[tid] + + # Decode status flags + has_gil = bool(status_flags & THREAD_STATUS_HAS_GIL) + on_cpu = bool(status_flags & THREAD_STATUS_ON_CPU) + gil_requested = bool(status_flags & THREAD_STATUS_GIL_REQUESTED) + + # Track state transitions using first timestamp + self._track_state_transition( + tid, has_gil, self.has_gil_start, self.no_gil_start, + "Has GIL", "No GIL", CATEGORY_GIL, first_time + ) + self._track_state_transition( + tid, on_cpu, self.on_cpu_start, self.off_cpu_start, + "On CPU", "Off CPU", CATEGORY_CPU, first_time + ) + + # Track code type + if has_gil: + self._track_state_transition( + tid, True, self.python_code_start, self.native_code_start, + "Python Code", "Native Code", CATEGORY_CODE_TYPE, first_time + ) + elif on_cpu: + self._track_state_transition( + tid, True, self.native_code_start, self.python_code_start, + "Native Code", "Python Code", CATEGORY_CODE_TYPE, first_time + ) + else: + if tid in self.initialized_threads: + if tid in self.python_code_start: + self._add_marker(tid, "Python Code", self.python_code_start.pop(tid), + first_time, CATEGORY_CODE_TYPE) + if tid in self.native_code_start: + self._add_marker(tid, "Native Code", self.native_code_start.pop(tid), + first_time, CATEGORY_CODE_TYPE) + + # Track GIL wait + if gil_requested: + self.gil_wait_start.setdefault(tid, first_time) + elif tid in self.gil_wait_start: + self._add_marker(tid, "Waiting for GIL", self.gil_wait_start.pop(tid), + first_time, CATEGORY_GIL) + + # Track exception state + has_exception = bool(status_flags & THREAD_STATUS_HAS_EXCEPTION) + self._track_state_transition( + tid, has_exception, self.exception_start, self.no_exception_start, + "Has Exception", "No Exception", CATEGORY_EXCEPTION, first_time + ) + + # Track GC events + has_gc_frame = any(frame[2] == "" for frame in frames) + if has_gc_frame: + if tid not in self.gc_start_per_thread: + self.gc_start_per_thread[tid] = first_time + elif tid in self.gc_start_per_thread: + self._add_marker(tid, "GC Collecting", self.gc_start_per_thread.pop(tid), + first_time, CATEGORY_GC) + + # Mark thread as initialized + self.initialized_threads.add(tid) + + # Skip idle threads if requested + is_idle = not has_gil and not on_cpu + if self.skip_idle and is_idle: + continue + + if not frames: + continue + + self._record_stack_sample( + thread_data, frames, tid, times, first_time + ) + + self.sample_count += len(times) + + def _record_stack_sample(self, thread_data, frames, tid, times, first_time): + stack_index = self._process_stack(thread_data, frames) + + thread_spill = thread_data["_spill"] + for t in times: + thread_spill.append_sample(stack_index, t) + + if self.opcodes_enabled and frames: + leaf_frame = frames[0] + filename, location, funcname, opcode = leaf_frame + if isinstance(location, tuple): + lineno, _, col_offset, _ = location + else: + lineno = location + col_offset = -1 + + current_state = (opcode, lineno, col_offset, funcname, filename) + + if tid not in self.opcode_state: + self.opcode_state[tid] = (*current_state, first_time) + elif self.opcode_state[tid][:5] != current_state: + ( + prev_opcode, prev_lineno, prev_col, prev_funcname, + prev_filename, prev_start + ) = self.opcode_state[tid] + self._add_opcode_interval_marker( + tid, prev_opcode, prev_lineno, prev_col, prev_funcname, + prev_start, first_time + ) + self.opcode_state[tid] = (*current_state, first_time) + + def _create_thread(self, tid, is_main_thread): + """Create a new thread structure with processed profile format.""" + if self.spill_dir is None: + self.spill_dir = tempfile.TemporaryDirectory() + + thread = { + "name": f"Thread-{tid}", + "isMainThread": is_main_thread, + "processStartupTime": 0, + "processShutdownTime": None, + "registerTime": 0, + "unregisterTime": None, + "pausedRanges": [], + "pid": str(os.getpid()), + "tid": tid, + "processType": "default", + "processName": "Python Process", + # Stack table - processed format + "stackTable": { + "frame": [], + "category": [], + "subcategory": [], + "prefix": [], + "length": 0, # Will be updated on export + }, + # Frame table - processed format + "frameTable": { + "address": [], + "category": [], + "subcategory": [], + "func": [], + "innerWindowID": [], + "implementation": [], + "optimizations": [], + "line": [], + "column": [], + "inlineDepth": [], + "nativeSymbol": [], + "length": 0, # Will be updated on export + }, + # Function table - processed format + "funcTable": { + "name": [], + "isJS": [], + "relevantForJS": [], + "resource": [], + "fileName": [], + "lineNumber": [], + "columnNumber": [], + "length": 0, # Will be updated on export + }, + # Resource table - processed format + "resourceTable": { + "lib": [], + "name": [], + "host": [], + "type": [], + "length": 0, # Will be updated on export + }, + # Native symbols table (empty for Python) + "nativeSymbols": { + "libIndex": [], + "address": [], + "name": [], + "functionSize": [], + "length": 0, + }, + # Caches for deduplication + "_stackCache": {}, + "_frameCache": {}, + "_funcCache": {}, + "_resourceCache": {}, + "_spill": GeckoThreadSpill(self.spill_dir.name, tid), + } + + return thread + + def _is_python(self, filename: str) -> bool: + return not filename.startswith("<") or filename in ["", ""] + + def _get_category(self, filename: str) -> int: + return CATEGORY_PYTHON if self._is_python(filename) else CATEGORY_NATIVE + + def _intern_string(self, s): + """Intern a string in the global string table.""" + if s in self.global_string_map: + return self.global_string_map[s] + idx = len(self.global_strings) + self.global_strings.append(s) + self.global_string_map[s] = idx + return idx + + def _add_marker(self, tid, name, start_time, end_time, category): + """Add an interval marker for a specific thread.""" + if tid not in self.threads: + return + + duration = end_time - start_time + + name_idx = self._intern_string(name) + self.threads[tid]["_spill"].append_marker( + name_idx, start_time, end_time, 1, category, { + "type": name.replace(" ", ""), + "duration": duration, + "tid": tid, + } + ) + + def _add_opcode_interval_marker(self, tid, opcode, lineno, col_offset, + funcname, start_time, end_time): + """Add an interval marker for opcode execution span.""" + if tid not in self.threads or opcode is None: + return + + opcode_info = get_opcode_info(opcode) + # Use formatted opcode name (with base opcode for specialized ones) + formatted_opname = format_opcode(opcode) + + name_idx = self._intern_string(formatted_opname) + + self.threads[tid]["_spill"].append_marker( + name_idx, start_time, end_time, 1, CATEGORY_OPCODES, { + "type": "Opcode", + "opcode": opcode, + "opname": formatted_opname, + "base_opname": opcode_info["base_opname"], + "is_specialized": opcode_info["is_specialized"], + "line": lineno, + "column": col_offset if col_offset >= 0 else None, + "function": funcname, + "duration": end_time - start_time, + } + ) + + def _process_stack(self, thread_data, frames): + """Process a stack and return the stack index.""" + if not frames: + return None + + # Cache references to avoid repeated dictionary lookups + stack_cache = thread_data["_stackCache"] + stack_table = thread_data["stackTable"] + stack_frames = stack_table["frame"] + stack_prefix = stack_table["prefix"] + stack_category = stack_table["category"] + stack_subcategory = stack_table["subcategory"] + + # Build stack bottom-up (from root to leaf) + prefix_stack_idx = None + + for frame_tuple in reversed(frames): + # frame_tuple is (filename, location, funcname, opcode) + # location is (lineno, end_lineno, col_offset, end_col_offset) or just lineno + filename, location, funcname, opcode = frame_tuple + if isinstance(location, tuple): + lineno, end_lineno, col_offset, end_col_offset = location + else: + # Legacy format: location is just lineno + lineno = location + col_offset = -1 + end_col_offset = -1 + + # Get or create function + func_idx = self._get_or_create_func( + thread_data, filename, funcname, lineno + ) + + # Get or create frame (include column for precise source location) + frame_idx = self._get_or_create_frame( + thread_data, func_idx, lineno, col_offset + ) + + # Check stack cache + stack_key = (frame_idx, prefix_stack_idx) + if stack_key in stack_cache: + prefix_stack_idx = stack_cache[stack_key] + else: + # Create new stack entry + stack_idx = len(stack_frames) + stack_frames.append(frame_idx) + stack_prefix.append(prefix_stack_idx) + + # Determine category + category = self._get_category(filename) + stack_category.append(category) + stack_subcategory.append(DEFAULT_SUBCATEGORY) + + stack_cache[stack_key] = stack_idx + prefix_stack_idx = stack_idx + + return prefix_stack_idx + + def _get_or_create_func(self, thread_data, filename, funcname, lineno): + """Get or create a function entry.""" + func_cache = thread_data["_funcCache"] + func_key = (filename, funcname) + + if func_key in func_cache: + return func_cache[func_key] + + # Cache references for func table + func_table = thread_data["funcTable"] + func_names = func_table["name"] + func_is_js = func_table["isJS"] + func_relevant = func_table["relevantForJS"] + func_resources = func_table["resource"] + func_filenames = func_table["fileName"] + func_line_numbers = func_table["lineNumber"] + func_column_numbers = func_table["columnNumber"] + + func_idx = len(func_names) + + # Intern strings in global table + name_idx = self._intern_string(funcname) + + # Determine if Python + is_python = self._is_python(filename) + + # Create resource + resource_idx = self._get_or_create_resource(thread_data, filename) + + # Add function + func_names.append(name_idx) + func_is_js.append(is_python) + func_relevant.append(is_python) + func_resources.append(resource_idx) + + if is_python: + filename_idx = self._intern_string(os.path.basename(filename)) + func_filenames.append(filename_idx) + func_line_numbers.append(lineno) + else: + func_filenames.append(None) + func_line_numbers.append(None) + func_column_numbers.append(None) + + func_cache[func_key] = func_idx + return func_idx + + def _get_or_create_resource(self, thread_data, filename): + """Get or create a resource entry.""" + resource_cache = thread_data["_resourceCache"] + + if filename in resource_cache: + return resource_cache[filename] + + # Cache references for resource table + resource_table = thread_data["resourceTable"] + resource_libs = resource_table["lib"] + resource_names = resource_table["name"] + resource_hosts = resource_table["host"] + resource_types = resource_table["type"] + + resource_idx = len(resource_names) + resource_name = ( + os.path.basename(filename) if "/" in filename else filename + ) + name_idx = self._intern_string(resource_name) + + resource_libs.append(None) + resource_names.append(name_idx) + resource_hosts.append(None) + resource_types.append(RESOURCE_TYPE_LIBRARY) + + resource_cache[filename] = resource_idx + return resource_idx + + def _get_or_create_frame(self, thread_data, func_idx, lineno, col_offset=-1): + """Get or create a frame entry.""" + frame_cache = thread_data["_frameCache"] + # Include column in cache key for precise frame identification + frame_key = (func_idx, lineno, col_offset if col_offset >= 0 else None) + + if frame_key in frame_cache: + return frame_cache[frame_key] + + # Cache references for frame table + frame_table = thread_data["frameTable"] + frame_addresses = frame_table["address"] + frame_inline_depths = frame_table["inlineDepth"] + frame_categories = frame_table["category"] + frame_subcategories = frame_table["subcategory"] + frame_funcs = frame_table["func"] + frame_native_symbols = frame_table["nativeSymbol"] + frame_inner_window_ids = frame_table["innerWindowID"] + frame_implementations = frame_table["implementation"] + frame_lines = frame_table["line"] + frame_columns = frame_table["column"] + frame_optimizations = frame_table["optimizations"] + + frame_idx = len(frame_funcs) + + # Determine category based on function - use cached func table reference + is_python = thread_data["funcTable"]["isJS"][func_idx] + category = CATEGORY_PYTHON if is_python else CATEGORY_NATIVE + + frame_addresses.append(FRAME_ADDRESS_NONE) + frame_inline_depths.append(FRAME_INLINE_DEPTH_ROOT) + frame_categories.append(category) + frame_subcategories.append(DEFAULT_SUBCATEGORY) + frame_funcs.append(func_idx) + frame_native_symbols.append(None) + frame_inner_window_ids.append(None) + frame_implementations.append(None) + frame_lines.append(lineno if lineno else None) + # Store column offset if available (>= 0), otherwise None + frame_columns.append(col_offset if col_offset >= 0 else None) + frame_optimizations.append(None) + + frame_cache[frame_key] = frame_idx + return frame_idx + + def _finalize_markers(self): + """Close any open markers at the end of profiling.""" + end_time = self.last_sample_time + + # Close all open markers for each thread using a generic approach + marker_states = [ + (self.has_gil_start, "Has GIL", CATEGORY_GIL), + (self.no_gil_start, "No GIL", CATEGORY_GIL), + (self.on_cpu_start, "On CPU", CATEGORY_CPU), + (self.off_cpu_start, "Off CPU", CATEGORY_CPU), + (self.python_code_start, "Python Code", CATEGORY_CODE_TYPE), + (self.native_code_start, "Native Code", CATEGORY_CODE_TYPE), + (self.gil_wait_start, "Waiting for GIL", CATEGORY_GIL), + (self.gc_start_per_thread, "GC Collecting", CATEGORY_GC), + (self.exception_start, "Has Exception", CATEGORY_EXCEPTION), + (self.no_exception_start, "No Exception", CATEGORY_EXCEPTION), + ] + + for state_dict, marker_name, category in marker_states: + for tid in list(state_dict.keys()): + self._add_marker(tid, marker_name, state_dict[tid], end_time, category) + del state_dict[tid] + + # Close any open opcode markers + for tid, state in list(self.opcode_state.items()): + opcode, lineno, col_offset, funcname, filename, start_time = state + self._add_opcode_interval_marker(tid, opcode, lineno, col_offset, funcname, start_time, end_time) + self.opcode_state.clear() + + def export(self, filename): + """Export the profile to a Gecko JSON file.""" + if self.sample_count > 0 and self.last_sample_time > 0: + self.interval = self.last_sample_time / self.sample_count + + # Spinner for progress indication + spinner = itertools.cycle(['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']) + stop_spinner = threading.Event() + + def spin(): + message = 'Building Gecko profile...' + while not stop_spinner.is_set(): + sys.stderr.write(f'\r{next(spinner)} {message}') + sys.stderr.flush() + time.sleep(0.1) + # Clear the spinner line + sys.stderr.write('\r' + ' ' * (len(message) + 3) + '\r') + sys.stderr.flush() + + spinner_thread = threading.Thread(target=spin, daemon=True) + spinner_thread.start() + + temp_path = None + replaced = False + try: + self._prepare_for_serialization() + output_dir = os.path.dirname(os.path.abspath(filename)) or "." + with tempfile.NamedTemporaryFile( + "w", dir=output_dir, delete=False + ) as file: + temp_path = file.name + self._stream_profile(file) + os.replace(temp_path, filename) + replaced = True + finally: + self.exported = True + stop_spinner.set() + spinner_thread.join(timeout=1.0) + # Small delay to ensure the clear happens + time.sleep(0.01) + if temp_path is not None and not replaced: + try: + os.unlink(temp_path) + except FileNotFoundError: + pass + self._cleanup_spills() + + print(f"Gecko profile written to {filename}") + print( + f"Open in Firefox Profiler: https://profiler.firefox.com/" + ) + return True + + def _build_marker_schema(self): + """Build marker schema definitions for Firefox Profiler.""" + schema = [] + + # Opcode marker schema (only if opcodes enabled) + if self.opcodes_enabled: + schema.append({ + "name": "Opcode", + "display": ["marker-table", "marker-chart"], + "tooltipLabel": "{marker.data.opname}", + "tableLabel": "{marker.data.opname} at line {marker.data.line}", + "chartLabel": "{marker.data.opname}", + "fields": [ + {"key": "opname", "label": "Opcode", "format": "string", "searchable": True}, + {"key": "base_opname", "label": "Base Opcode", "format": "string"}, + {"key": "is_specialized", "label": "Specialized", "format": "string"}, + {"key": "line", "label": "Line", "format": "integer"}, + {"key": "column", "label": "Column", "format": "integer"}, + {"key": "function", "label": "Function", "format": "string"}, + {"key": "duration", "label": "Duration", "format": "duration"}, + ], + }) + + return schema + + def _build_profile(self): + """Build the complete profile structure in processed format.""" + try: + self._prepare_for_serialization() + file = io.StringIO() + self._stream_profile(file) + return json.loads(file.getvalue()) + finally: + self.exported = True + self._cleanup_spills() + + def _profile_head(self): + return { + "meta": { + "interval": self.interval, + "startTime": self.start_time, + "abi": platform.machine(), + "misc": "Python profiler", + "oscpu": platform.machine(), + "platform": platform.system(), + "processType": PROCESS_TYPE_MAIN, + "categories": GECKO_CATEGORIES, + "stackwalk": STACKWALK_DISABLED, + "toolkit": "", + "version": GECKO_FORMAT_VERSION, + "preprocessedProfileVersion": GECKO_PREPROCESSED_VERSION, + "appBuildID": "", + "physicalCPUs": os.cpu_count() or 0, + "logicalCPUs": os.cpu_count() or 0, + "CPUName": "", + "product": "Python", + "symbolicated": True, + "markerSchema": self._build_marker_schema(), + "importedFrom": "Tachyon Sampling Profiler", + "extensions": { + "id": [], + "name": [], + "baseURL": [], + "length": 0, + }, + }, + "libs": self.libs, + } + + def _profile_tail(self): + return { + "pages": [], + "shared": { + "stringArray": self.global_strings, + "sources": {"length": 0, "uuid": [], "filename": []}, + }, + } + + def _prepare_for_serialization(self): + if self.exported: + raise RuntimeError("GeckoCollector has already been exported") + self._finalize_markers() + for thread_data in self.threads.values(): + thread_data["_spill"].prepare_read() + thread_data["stackTable"]["length"] = len(thread_data["stackTable"]["frame"]) + thread_data["frameTable"]["length"] = len(thread_data["frameTable"]["func"]) + thread_data["funcTable"]["length"] = len(thread_data["funcTable"]["name"]) + thread_data["resourceTable"]["length"] = len(thread_data["resourceTable"]["name"]) + + def _cleanup_spills(self): + if self.spill_dir is not None: + self.spill_dir.cleanup() + self.spill_dir = None + + def _stream_profile(self, file): + file.write("{") + first = True + for key, value in self._profile_head().items(): + first = _write_json_member(file, key, value, first) + + first = _write_member_name(file, "threads", first) + file.write("[") + for index, (tid, thread_data) in enumerate(self.threads.items()): + if index: + file.write(",") + self._stream_thread(file, tid, thread_data) + file.write("]") + + for key, value in self._profile_tail().items(): + first = _write_json_member(file, key, value, first) + file.write("}") + + def _stream_thread(self, file, tid, thread_data): + spill = thread_data["_spill"] + metadata = { + "name": thread_data["name"], + "isMainThread": thread_data["isMainThread"], + "processStartupTime": thread_data["processStartupTime"], + "processShutdownTime": thread_data["processShutdownTime"], + "registerTime": thread_data["registerTime"], + "unregisterTime": thread_data["unregisterTime"], + "pausedRanges": thread_data["pausedRanges"], + "pid": thread_data["pid"], + "tid": thread_data["tid"], + "processType": thread_data["processType"], + "processName": thread_data["processName"], + } + file.write("{") + first = True + for key, value in metadata.items(): + first = _write_json_member(file, key, value, first) + + first = _write_member_name(file, "samples", first) + self._stream_samples(file, spill) + for key in ( + "stackTable", + "frameTable", + "funcTable", + "resourceTable", + "nativeSymbols", + ): + first = _write_json_member(file, key, thread_data[key], first) + first = _write_member_name(file, "markers", first) + self._stream_markers(file, spill) + file.write("}") + + def _stream_samples(self, file, spill): + _stream_column_table( + file, + ( + ("stack", spill.samples_stack.iter_tokens()), + ("time", spill.samples_time.iter_tokens()), + ("eventDelay", ("null" for _ in range(spill.sample_count))), + ), + spill.sample_count, + ( + ("weight", None), + ("weightType", "samples"), + ("length", spill.sample_count), + ), + ) + + def _stream_markers(self, file, spill): + _stream_column_table( + file, + ( + ("data", spill.markers_data.iter_tokens()), + ("name", spill.markers_name.iter_tokens()), + ("startTime", spill.markers_start_time.iter_tokens()), + ("endTime", spill.markers_end_time.iter_tokens()), + ("phase", spill.markers_phase.iter_tokens()), + ("category", spill.markers_category.iter_tokens()), + ), + spill.marker_count, + (("length", spill.marker_count),), + ) + + +def _write_json(file, value): + for chunk in _JSON_ENCODER.iterencode(value): + file.write(chunk) + + +def _write_member_name(file, name, first): + if not first: + file.write(",") + _write_json(file, name) + file.write(":") + return False + + +def _write_json_member(file, name, value, first): + first = _write_member_name(file, name, first) + _write_json(file, value) + return first + + +def _stream_column_table(file, columns, expected_count, trailing_members=()): + file.write("{") + first = True + for name, token_iter in columns: + first = _write_member_name(file, name, first) + _stream_array(file, token_iter, expected_count, name) + for name, value in trailing_members: + first = _write_json_member(file, name, value, first) + file.write("}") + + +def _stream_array(file, token_iter, expected_count, label="array"): + file.write("[") + count = 0 + for token in token_iter: + if count: + file.write(",") + file.write(token) + count += 1 + if count != expected_count: + raise RuntimeError( + f"streamed {count} {label} items, expected {expected_count}" + ) + file.write("]") diff --git a/Lib/profiling/sampling/heatmap_collector.py b/Lib/profiling/sampling/heatmap_collector.py new file mode 100644 index 00000000000..38f4d7985ff --- /dev/null +++ b/Lib/profiling/sampling/heatmap_collector.py @@ -0,0 +1,1145 @@ +"""Heatmap collector for Python profiling with line-level execution heat visualization.""" + +import base64 +import collections +import html +import importlib.resources +import json +import locale +import math +import os +import platform +import site +import sys +from dataclasses import dataclass, field +from pathlib import Path +from typing import Dict, List, Tuple + +from ._css_utils import get_combined_css +from ._format_utils import fmt +from .collector import normalize_location, extract_lineno +from .opcode_utils import get_opcode_info, format_opcode +from .stack_collector import StackTraceCollector +from .module_utils import extract_module_name, get_python_path_info + + +# ============================================================================ +# Data Classes +# ============================================================================ + +@dataclass +class FileStats: + """Statistics for a single profiled file.""" + filename: str + module_name: str + module_type: str + total_samples: int + total_self_samples: int + num_lines: int + max_samples: int + max_self_samples: int + percentage: float = 0.0 + + +@dataclass +class TreeNode: + """Node in the hierarchical file tree structure.""" + files: List[FileStats] = field(default_factory=list) + samples: int = 0 + count: int = 0 + children: Dict[str, 'TreeNode'] = field(default_factory=dict) + + +# ============================================================================ +# Helper Classes +# ============================================================================ + +class _TemplateLoader: + """Loads and caches HTML/CSS/JS templates for heatmap generation.""" + + def __init__(self): + """Load all templates and assets once.""" + self.index_template = None + self.file_template = None + self.index_css = None + self.index_js = None + self.file_css = None + self.file_js = None + self.logo_html = None + + self._load_templates() + + def _load_templates(self): + """Load all template files from _heatmap_assets.""" + try: + template_dir = importlib.resources.files(__package__) + assets_dir = template_dir / "_heatmap_assets" + + # Load HTML templates + self.index_template = (assets_dir / "heatmap_index_template.html").read_text(encoding="utf-8") + self.file_template = (assets_dir / "heatmap_pyfile_template.html").read_text(encoding="utf-8") + + # Load CSS (same file used for both index and file pages) + css_content = get_combined_css("heatmap") + self.index_css = css_content + self.file_css = css_content + + # Load JS + base_js = (template_dir / "_shared_assets" / "base.js").read_text(encoding="utf-8") + heatmap_shared_js = (assets_dir / "heatmap_shared.js").read_text(encoding="utf-8") + shared_js = f"{base_js}\n{heatmap_shared_js}" + self.index_js = f"{shared_js}\n{(assets_dir / 'heatmap_index.js').read_text(encoding='utf-8')}" + self.file_js = f"{shared_js}\n{(assets_dir / 'heatmap.js').read_text(encoding='utf-8')}" + + # Load Tachyon logo + logo_dir = template_dir / "_assets" + try: + png_path = logo_dir / "tachyon-logo.png" + b64_logo = base64.b64encode(png_path.read_bytes()).decode("ascii") + self.logo_html = f'' + except (FileNotFoundError, IOError) as e: + self.logo_html = '
' + print(f"Warning: Could not load Tachyon logo: {e}") + + except (FileNotFoundError, IOError) as e: + raise RuntimeError(f"Failed to load heatmap template files: {e}") from e + + +class _TreeBuilder: + """Builds hierarchical tree structure from file statistics.""" + + @staticmethod + def build_file_tree(file_stats: List[FileStats]) -> Dict[str, TreeNode]: + """Build hierarchical tree grouped by module type, then by module structure. + + Args: + file_stats: List of FileStats objects + + Returns: + Dictionary mapping module types to their tree roots + """ + # Group by module type first + type_groups = {'stdlib': [], 'site-packages': [], 'project': [], 'other': []} + for stat in file_stats: + type_groups[stat.module_type].append(stat) + + # Build tree for each type + trees = {} + for module_type, stats in type_groups.items(): + if not stats: + continue + + root_node = TreeNode() + + for stat in stats: + module_name = stat.module_name + parts = module_name.split('.') + + # Navigate/create tree structure + current_node = root_node + for i, part in enumerate(parts): + if i == len(parts) - 1: + # Last part - store the file + current_node.files.append(stat) + else: + # Intermediate part - create or navigate + if part not in current_node.children: + current_node.children[part] = TreeNode() + current_node = current_node.children[part] + + # Calculate aggregate stats for this type's tree + _TreeBuilder._calculate_node_stats(root_node) + trees[module_type] = root_node + + return trees + + @staticmethod + def _calculate_node_stats(node: TreeNode) -> Tuple[int, int]: + """Recursively calculate aggregate statistics for tree nodes. + + Args: + node: TreeNode to calculate stats for + + Returns: + Tuple of (total_samples, file_count) + """ + total_samples = 0 + file_count = 0 + + # Count files at this level + for file_stat in node.files: + total_samples += file_stat.total_samples + file_count += 1 + + # Recursively process children + for child in node.children.values(): + child_samples, child_count = _TreeBuilder._calculate_node_stats(child) + total_samples += child_samples + file_count += child_count + + node.samples = total_samples + node.count = file_count + return total_samples, file_count + + +class _HtmlRenderer: + """Renders hierarchical tree structures as HTML.""" + + def __init__(self, file_index: Dict[str, str]): + """Initialize renderer with file index. + + Args: + file_index: Mapping from filenames to HTML file names + """ + self.file_index = file_index + self.heatmap_bar_height = 16 + + def render_hierarchical_html(self, trees: Dict[str, TreeNode]) -> str: + """Build hierarchical HTML with type sections and collapsible module folders. + + Args: + trees: Dictionary mapping module types to tree roots + + Returns: + Complete HTML string for all sections + """ + type_names = { + 'stdlib': '📚 Standard Library', + 'site-packages': '📦 Site Packages', + 'project': '🏗️ Project Files', + 'other': '📄 Other Files' + } + + sections = [] + for module_type in ['project', 'stdlib', 'site-packages', 'other']: + if module_type not in trees: + continue + + tree = trees[module_type] + + # Project starts expanded, others start collapsed + is_collapsed = module_type in {'stdlib', 'site-packages', 'other'} + icon = '▶' if is_collapsed else '▼' + content_style = ' style="display: none;"' if is_collapsed else '' + + file_word = "file" if tree.count == 1 else "files" + sample_word = "sample" if tree.samples == 1 else "samples" + section_html = f''' +
+
+ {icon} + {type_names[module_type]} + ({tree.count} {file_word}, {tree.samples:n} {sample_word}) +
+
+''' + + # Render root folders + root_folders = sorted(tree.children.items(), + key=lambda x: x[1].samples, reverse=True) + + for folder_name, folder_node in root_folders: + section_html += self._render_folder(folder_node, folder_name, level=1) + + # Render root files (files not in any module) + if tree.files: + sorted_files = sorted(tree.files, key=lambda x: x.total_samples, reverse=True) + section_html += '
\n' + for stat in sorted_files: + section_html += self._render_file_item(stat, indent=' ') + section_html += '
\n' + + section_html += '
\n
\n' + sections.append(section_html) + + return '\n'.join(sections) + + def _render_folder(self, node: TreeNode, name: str, level: int = 1) -> str: + """Render a single folder node recursively. + + Args: + node: TreeNode to render + name: Display name for the folder + level: Nesting level for indentation + + Returns: + HTML string for this folder and its contents + """ + indent = ' ' * level + parts = [] + + # Render folder header (collapsed by default) + file_word = "file" if node.count == 1 else "files" + sample_word = "sample" if node.samples == 1 else "samples" + parts.append(f'{indent}') + + return '\n'.join(parts) + + def _render_file_item(self, stat: FileStats, indent: str = '') -> str: + """Render a single file item with heatmap bar. + + Args: + stat: FileStats object + indent: Indentation string + + Returns: + HTML string for file item + """ + full_path = html.escape(stat.filename) + module_name = html.escape(stat.module_name) + + intensity = stat.percentage / 100.0 + bar_width = min(stat.percentage, 100) + + html_file = self.file_index[stat.filename] + s = "" if stat.total_samples == 1 else "s" + + return (f'{indent}
\n' + f'{indent} 📄 {module_name}\n' + f'{indent} {stat.total_samples:n} sample{s}\n' + f'{indent}
\n' + f'{indent}
\n') + + +# ============================================================================ +# Main Collector Class +# ============================================================================ + +class HeatmapCollector(StackTraceCollector): + """Collector that generates coverage.py-style heatmap HTML output with line intensity. + + This collector creates detailed HTML reports showing which lines of code + were executed most frequently during profiling, similar to coverage.py + but showing execution "heat" rather than just coverage. + """ + + # File naming and formatting constants + FILE_INDEX_FORMAT = "file_{:04d}.html" + + def __init__(self, *args, **kwargs): + """Initialize the heatmap collector with data structures for analysis.""" + super().__init__(*args, **kwargs) + + # Sample counting data structures + self.line_samples = collections.Counter() + self.file_samples = collections.defaultdict(collections.Counter) + self.line_self_samples = collections.Counter() + self.file_self_samples = collections.defaultdict(collections.Counter) + + # Call graph data structures for navigation (sets for O(1) deduplication) + self.call_graph = collections.defaultdict(set) + self.callers_graph = collections.defaultdict(set) + self.function_definitions = {} + + # Map each sampled line to its function for proper caller lookup + # (filename, lineno) -> funcname + self.line_to_function = {} + + # Edge counting for call path analysis + self.edge_samples = collections.Counter() + + # Bytecode-level tracking data structures + # Track samples per (file, lineno) -> {opcode: {'count': N, 'locations': set()}} + # Locations are deduplicated via set to minimize memory usage + self.line_opcodes = collections.defaultdict(dict) + + # Statistics and metadata + self._total_samples = 0 + self._path_info = get_python_path_info() + self.stats = {} + + # Opcode collection flag + self.opcodes_enabled = False + + # Template loader (loads all templates once) + self._template_loader = _TemplateLoader() + + # File index (populated during export) + self.file_index = {} + + # Reusable set for deduplicating line locations within a single sample. + # This avoids over-counting recursive functions in cumulative stats. + self._seen_lines = set() + + def set_stats(self, sample_interval_usec, duration_sec, sample_rate, error_rate=None, missed_samples=None, **kwargs): + """Set profiling statistics to include in heatmap output. + + Args: + sample_interval_usec: Sampling interval in microseconds + duration_sec: Total profiling duration in seconds + sample_rate: Effective sampling rate + error_rate: Optional error rate during profiling + missed_samples: Optional percentage of missed samples + **kwargs: Additional statistics to include + """ + self.stats = { + "sample_interval_usec": sample_interval_usec, + "duration_sec": duration_sec, + "sample_rate": sample_rate, + "error_rate": error_rate, + "missed_samples": missed_samples, + "python_version": sys.version, + "python_implementation": platform.python_implementation(), + "platform": platform.platform(), + } + self.stats.update(kwargs) + + def process_frames(self, frames, thread_id, weight=1): + """Process stack frames and count samples per line. + + Args: + frames: List of (filename, location, funcname, opcode) tuples in + leaf-to-root order. location is (lineno, end_lineno, col_offset, end_col_offset). + opcode is None if not gathered. + thread_id: Thread ID for this stack trace + weight: Number of samples this stack represents (for batched RLE) + """ + self._total_samples += weight + self._seen_lines.clear() + + for i, (filename, location, funcname, opcode) in enumerate(frames): + # Normalize location to 4-tuple format + lineno, end_lineno, col_offset, end_col_offset = normalize_location(location) + + if not self._is_valid_frame(filename, lineno): + continue + + # frames[0] is the leaf - where execution is actually happening + is_leaf = (i == 0) + line_key = (filename, lineno) + count_cumulative = line_key not in self._seen_lines + if count_cumulative: + self._seen_lines.add(line_key) + + self._record_line_sample(filename, lineno, funcname, is_leaf=is_leaf, + count_cumulative=count_cumulative, weight=weight) + + if opcode is not None: + # Set opcodes_enabled flag when we first encounter opcode data + self.opcodes_enabled = True + self._record_bytecode_sample(filename, lineno, opcode, + end_lineno, col_offset, end_col_offset, + weight=weight) + + # Build call graph for adjacent frames (relationships are deduplicated anyway) + if i + 1 < len(frames): + next_frame = frames[i + 1] + next_lineno = extract_lineno(next_frame[1]) + self._record_call_relationship( + (filename, lineno, funcname), + (next_frame[0], next_lineno, next_frame[2]), + weight=weight, + ) + + def _is_valid_frame(self, filename, lineno): + """Check if a frame should be included in the heatmap.""" + # Skip internal or invalid files + if not filename or filename.startswith('<') or filename.startswith('['): + return False + + # Skip invalid frames with corrupted filename data + if filename == "__init__" and lineno == 0: + return False + + return True + + def _record_line_sample(self, filename, lineno, funcname, is_leaf=False, + count_cumulative=True, weight=1): + """Record a sample for a specific line.""" + # Track cumulative samples (all occurrences in stack) + if count_cumulative: + self.line_samples[(filename, lineno)] += weight + self.file_samples[filename][lineno] += weight + + # Track self/leaf samples (only when at top of stack) + if is_leaf: + self.line_self_samples[(filename, lineno)] += weight + self.file_self_samples[filename][lineno] += weight + + # Record function definition location + if funcname and (filename, funcname) not in self.function_definitions: + self.function_definitions[(filename, funcname)] = lineno + + # Map this line to its function for caller/callee navigation + if funcname: + self.line_to_function[(filename, lineno)] = funcname + + def _record_bytecode_sample(self, filename, lineno, opcode, + end_lineno=None, col_offset=None, end_col_offset=None, + weight=1): + """Record a sample for a specific bytecode instruction. + + Args: + filename: Source filename + lineno: Line number + opcode: Opcode number being executed + end_lineno: End line number (may be -1 if not available) + col_offset: Column offset in UTF-8 bytes (may be -1 if not available) + end_col_offset: End column offset in UTF-8 bytes (may be -1 if not available) + weight: Number of samples this represents (for batched RLE) + """ + key = (filename, lineno) + + # Initialize opcode entry if needed - use set for location deduplication + if opcode not in self.line_opcodes[key]: + self.line_opcodes[key][opcode] = {'count': 0, 'locations': set()} + + self.line_opcodes[key][opcode]['count'] += weight + + # Store unique location info if column offset is available (not -1) + if col_offset is not None and col_offset >= 0: + # Use tuple as set key for deduplication + loc_key = (end_lineno, col_offset, end_col_offset) + self.line_opcodes[key][opcode]['locations'].add(loc_key) + + def _get_bytecode_data_for_line(self, filename, lineno): + """Get bytecode disassembly data for instructions on a specific line. + + Args: + filename: Source filename + lineno: Line number + + Returns: + List of dicts with instruction info, sorted by samples descending + """ + key = (filename, lineno) + opcode_data = self.line_opcodes.get(key, {}) + + result = [] + for opcode, data in opcode_data.items(): + info = get_opcode_info(opcode) + # Handle both old format (int count) and new format (dict with count/locations) + if isinstance(data, dict): + count = data.get('count', 0) + raw_locations = data.get('locations', set()) + # Convert set of tuples to list of dicts for JSON serialization + if isinstance(raw_locations, set): + locations = [ + {'end_lineno': loc[0], 'col_offset': loc[1], 'end_col_offset': loc[2]} + for loc in raw_locations + ] + else: + locations = raw_locations + else: + count = data + locations = [] + + result.append({ + 'opcode': opcode, + 'opname': format_opcode(opcode), + 'base_opname': info['base_opname'], + 'is_specialized': info['is_specialized'], + 'samples': count, + 'locations': locations, + }) + + # Sort by samples descending, then by opcode number + result.sort(key=lambda x: (-x['samples'], x['opcode'])) + return result + + def _record_call_relationship(self, callee_frame, caller_frame, weight=1): + """Record caller/callee relationship between adjacent frames.""" + callee_filename, callee_lineno, callee_funcname = callee_frame + caller_filename, caller_lineno, caller_funcname = caller_frame + + # Skip internal files for call graph + if callee_filename.startswith('<') or callee_filename.startswith('['): + return + + # Get the callee's function definition line + callee_def_line = self.function_definitions.get( + (callee_filename, callee_funcname), callee_lineno + ) + + # Record caller -> callee relationship (set handles deduplication) + caller_key = (caller_filename, caller_lineno) + callee_info = (callee_filename, callee_def_line, callee_funcname) + self.call_graph[caller_key].add(callee_info) + + # Record callee <- caller relationship (set handles deduplication) + callee_key = (callee_filename, callee_def_line) + caller_info = (caller_filename, caller_lineno, caller_funcname) + self.callers_graph[callee_key].add(caller_info) + + # Count this call edge for path analysis + edge_key = (caller_key, callee_key) + self.edge_samples[edge_key] += weight + + def export(self, output_path): + """Export heatmap data as HTML files in a directory. + + Args: + output_path: Path where to create the heatmap output directory + """ + if not self.file_samples: + print("Warning: No heatmap data to export") + return False + + try: + output_dir = self._prepare_output_directory(output_path) + file_stats = self._calculate_file_stats() + self._create_file_index(file_stats) + + # Generate individual file reports + self._generate_file_reports(output_dir, file_stats) + + # Generate index page + self._generate_index_html(output_dir / 'index.html', file_stats) + + self._print_export_summary(output_dir, file_stats) + return True + + except Exception as e: + print(f"Error: Failed to export heatmap: {e}") + raise + + def _prepare_output_directory(self, output_path): + """Create output directory for heatmap files.""" + output_dir = Path(output_path) + if output_dir.suffix == '.html': + output_dir = output_dir.with_suffix('') + + try: + output_dir.mkdir(exist_ok=True, parents=True) + except (IOError, OSError) as e: + raise RuntimeError(f"Failed to create output directory {output_dir}: {e}") from e + + return output_dir + + def _create_file_index(self, file_stats: List[FileStats]): + """Create mapping from filenames to HTML file names.""" + self.file_index = { + stat.filename: self.FILE_INDEX_FORMAT.format(i) + for i, stat in enumerate(file_stats) + } + + def _generate_file_reports(self, output_dir, file_stats: List[FileStats]): + """Generate HTML report for each source file.""" + for stat in file_stats: + file_path = output_dir / self.file_index[stat.filename] + line_counts = self.file_samples[stat.filename] + valid_line_counts = {line: count for line, count in line_counts.items() if line >= 0} + + self_counts = self.file_self_samples.get(stat.filename, {}) + valid_self_counts = {line: count for line, count in self_counts.items() if line >= 0} + + self._generate_file_html( + file_path, + stat.filename, + valid_line_counts, + valid_self_counts, + stat + ) + + def _print_export_summary(self, output_dir, file_stats: List[FileStats]): + """Print summary of exported heatmap.""" + print(f"Heatmap output written to {output_dir}/") + print(f" - Index: {output_dir / 'index.html'}") + s = "" if len(file_stats) == 1 else "s" + print(f" - {len(file_stats)} source file{s} analyzed") + + def _calculate_file_stats(self) -> List[FileStats]: + """Calculate statistics for each file. + + Returns: + List of FileStats objects sorted by total samples + """ + file_stats = [] + for filename, line_counts in self.file_samples.items(): + # Skip special frames + if filename in ('~', '...', '.') or filename.startswith('<') or filename.startswith('['): + continue + + # Filter out lines with -1 (special frames) + valid_line_counts = {line: count for line, count in line_counts.items() if line >= 0} + if not valid_line_counts: + continue + + # Get self samples for this file + self_line_counts = self.file_self_samples.get(filename, {}) + valid_self_counts = {line: count for line, count in self_line_counts.items() if line >= 0} + + total_samples = sum(valid_line_counts.values()) + total_self_samples = sum(valid_self_counts.values()) + num_lines = len(valid_line_counts) + max_samples = max(valid_line_counts.values()) + max_self_samples = max(valid_self_counts.values()) if valid_self_counts else 0 + module_name, module_type = extract_module_name(filename, self._path_info) + + file_stats.append(FileStats( + filename=filename, + module_name=module_name, + module_type=module_type, + total_samples=total_samples, + total_self_samples=total_self_samples, + num_lines=num_lines, + max_samples=max_samples, + max_self_samples=max_self_samples, + percentage=0.0 + )) + + # Sort by total samples and calculate percentages + file_stats.sort(key=lambda x: x.total_samples, reverse=True) + if file_stats: + max_total = file_stats[0].total_samples + for stat in file_stats: + stat.percentage = (stat.total_samples / max_total * 100) if max_total > 0 else 0 + + return file_stats + + def _generate_index_html(self, index_path: Path, file_stats: List[FileStats]): + """Generate index.html with list of all profiled files.""" + # Build hierarchical tree + tree = _TreeBuilder.build_file_tree(file_stats) + + # Render tree as HTML + renderer = _HtmlRenderer(self.file_index) + sections_html = renderer.render_hierarchical_html(tree) + + # Format error rate and missed samples with bar classes + error_rate = self.stats.get('error_rate') + if error_rate is not None: + error_rate_str = f"{fmt(error_rate)}%" + error_rate_width = min(error_rate, 100) + # Determine bar color class based on rate + if error_rate < 5: + error_rate_class = "good" + elif error_rate < 15: + error_rate_class = "warning" + else: + error_rate_class = "error" + else: + error_rate_str = "N/A" + error_rate_width = 0 + error_rate_class = "good" + + missed_samples = self.stats.get('missed_samples') + if missed_samples is not None: + missed_samples_str = f"{fmt(missed_samples)}%" + missed_samples_width = min(missed_samples, 100) + if missed_samples < 5: + missed_samples_class = "good" + elif missed_samples < 15: + missed_samples_class = "warning" + else: + missed_samples_class = "error" + else: + missed_samples_str = "N/A" + missed_samples_width = 0 + missed_samples_class = "good" + + # Populate template + replacements = { + "": f"", + "": f"", + "": self._template_loader.logo_html, + "": f"{sys.version_info.major}.{sys.version_info.minor}", + "": f"{len(file_stats):n}", + "": f"{self._total_samples:n}", + "": fmt(self.stats.get('duration_sec', 0)), + "": fmt(self.stats.get('sample_rate', 0)), + "": error_rate_str, + "": str(error_rate_width), + "": error_rate_class, + "": missed_samples_str, + "": str(missed_samples_width), + "": missed_samples_class, + "": sections_html, + } + + html_content = self._template_loader.index_template + for placeholder, value in replacements.items(): + html_content = html_content.replace(placeholder, value) + + try: + index_path.write_text(html_content, encoding='utf-8') + except (IOError, OSError) as e: + raise RuntimeError(f"Failed to write index file {index_path}: {e}") from e + + def _generate_file_html(self, output_path: Path, filename: str, + line_counts: Dict[int, int], self_counts: Dict[int, int], + file_stat: FileStats): + """Generate HTML for a single source file with heatmap coloring.""" + source_lines = [f"# Source file not available: {filename}"] + try: + path = Path(filename) + if path.is_file(): + source_lines = path.read_text( + encoding='utf-8', errors='replace').splitlines() + except (IOError, OSError): + pass + + # Generate HTML for each line + max_samples = max(line_counts.values()) if line_counts else 1 + max_self_samples = max(self_counts.values()) if self_counts else 1 + code_lines_html = [ + self._build_line_html(line_num, line_content, line_counts, self_counts, + max_samples, max_self_samples, filename) + for line_num, line_content in enumerate(source_lines, start=1) + ] + + # Populate template + replacements = { + "": html.escape(filename), + "": f"{file_stat.total_samples:n}", + "": f"{file_stat.total_self_samples:n}", + "": f"{file_stat.num_lines:n}", + "": fmt(file_stat.percentage, 2), + "": f"{file_stat.max_samples:n}", + "": f"{file_stat.max_self_samples:n}", + "": ''.join(code_lines_html), + "": f"", + "": f"", + "": self._template_loader.logo_html, + "": f"{sys.version_info.major}.{sys.version_info.minor}", + } + + html_content = self._template_loader.file_template + for placeholder, value in replacements.items(): + html_content = html_content.replace(placeholder, value) + + try: + output_path.write_text(html_content, encoding='utf-8') + except (IOError, OSError) as e: + raise RuntimeError(f"Failed to write file {output_path}: {e}") from e + + def _build_line_html(self, line_num: int, line_content: str, + line_counts: Dict[int, int], self_counts: Dict[int, int], + max_samples: int, max_self_samples: int, filename: str) -> str: + """Build HTML for a single line of source code.""" + cumulative_samples = line_counts.get(line_num, 0) + self_samples = self_counts.get(line_num, 0) + + # Calculate colors for both self and cumulative modes + if cumulative_samples > 0: + log_cumulative = math.log(cumulative_samples + 1) + log_max = math.log(max_samples + 1) + cumulative_intensity = log_cumulative / log_max if log_max > 0 else 0 + + if self_samples > 0 and max_self_samples > 0: + log_self = math.log(self_samples + 1) + log_max_self = math.log(max_self_samples + 1) + self_intensity = log_self / log_max_self if log_max_self > 0 else 0 + else: + self_intensity = 0 + + self_display = f"{self_samples:n}" if self_samples > 0 else "" + cumulative_display = f"{cumulative_samples:n}" + tooltip = f"Self: {self_samples:n}, Total: {cumulative_samples:n}" + else: + cumulative_intensity = 0 + self_intensity = 0 + self_display = "" + cumulative_display = "" + tooltip = "" + + # Get bytecode data for this line (if any) + bytecode_data = self._get_bytecode_data_for_line(filename, line_num) + has_bytecode = len(bytecode_data) > 0 and cumulative_samples > 0 + + # Build bytecode toggle button if data is available + bytecode_btn_html = '' + bytecode_panel_html = '' + if has_bytecode: + bytecode_json = html.escape(json.dumps(bytecode_data)) + + # Calculate specialization percentage + total_samples = sum(d['samples'] for d in bytecode_data) + specialized_samples = sum(d['samples'] for d in bytecode_data if d['is_specialized']) + spec_pct = int(100 * specialized_samples / total_samples) if total_samples > 0 else 0 + + bytecode_btn_html = ( + f'' + ) + # Wrapper contains columns + content panel + bytecode_panel_html = ( + f'
\n' + f'
' + f'
' + f'
' + f'
' + f'
\n' + f'
\n' + f'
\n' + ) + elif self.opcodes_enabled: + # Add invisible spacer to maintain consistent indentation when opcodes are enabled + bytecode_btn_html = '
' + + # Get navigation buttons + nav_buttons_html = self._build_navigation_buttons(filename, line_num) + + # Build line HTML with instruction highlights if available + line_html = self._render_source_with_highlights(line_content, line_num, + filename, bytecode_data) + title_attr = f' title="{html.escape(tooltip)}"' if tooltip else "" + + # Specialization color for toggle mode (green gradient based on spec %) + spec_color_attr = '' + if has_bytecode: + spec_color = self._format_specialization_color(spec_pct) + spec_color_attr = f'data-spec-color="{spec_color}" ' + + return ( + f'
\n' + f'
{line_num}
\n' + f'
{self_display}
\n' + f'
{cumulative_display}
\n' + f' {bytecode_btn_html}\n' + f'
{line_html}
\n' + f' {nav_buttons_html}\n' + f'
\n' + f'{bytecode_panel_html}' + ) + + def _render_source_with_highlights(self, line_content: str, line_num: int, + filename: str, bytecode_data: list) -> str: + """Render source line with instruction highlight spans. + + Simple: collect ranges with sample counts, assign each byte position to + smallest covering range, then emit spans for contiguous runs with sample data. + """ + content = line_content.rstrip('\n') + if not content: + return '' + + # Collect all (start, end) -> {samples, opcodes} mapping from instructions + # Multiple instructions may share the same range, so we sum samples and collect opcodes + range_data = {} + for instr in bytecode_data: + samples = instr.get('samples', 0) + opname = instr.get('opname', '') + for loc in instr.get('locations', []): + if loc.get('end_lineno', line_num) == line_num: + start, end = loc.get('col_offset', -1), loc.get('end_col_offset', -1) + if start >= 0 and end >= 0: + key = (start, end) + if key not in range_data: + range_data[key] = {'samples': 0, 'opcodes': []} + range_data[key]['samples'] += samples + if opname and opname not in range_data[key]['opcodes']: + range_data[key]['opcodes'].append(opname) + + if not range_data: + return html.escape(content) + + # For each byte position, find the smallest covering range + byte_to_range = {} + for (start, end) in range_data.keys(): + for pos in range(start, end): + if pos not in byte_to_range: + byte_to_range[pos] = (start, end) + else: + # Keep smaller range + old_start, old_end = byte_to_range[pos] + if (end - start) < (old_end - old_start): + byte_to_range[pos] = (start, end) + + # Calculate totals for percentage and intensity + total_line_samples = sum(d['samples'] for d in range_data.values()) + max_range_samples = max(d['samples'] for d in range_data.values()) if range_data else 1 + + # Render character by character + result = [] + byte_offset = 0 + char_idx = 0 + current_range = None + span_chars = [] + + def flush_span(): + nonlocal span_chars, current_range + if span_chars: + text = html.escape(''.join(span_chars)) + if current_range: + data = range_data.get(current_range, {'samples': 0, 'opcodes': []}) + samples = data['samples'] + opcodes = ', '.join(data['opcodes'][:3]) # Top 3 opcodes + if len(data['opcodes']) > 3: + opcodes += f" +{len(data['opcodes']) - 3} more" + pct = int(100 * samples / total_line_samples) if total_line_samples > 0 else 0 + result.append(f'{text}') + else: + result.append(text) + span_chars = [] + + while char_idx < len(content): + char = content[char_idx] + char_bytes = len(char.encode('utf-8')) + char_range = byte_to_range.get(byte_offset) + + if char_range != current_range: + flush_span() + current_range = char_range + + span_chars.append(char) + byte_offset += char_bytes + char_idx += 1 + + flush_span() + return ''.join(result) + + def _format_specialization_color(self, spec_pct: int) -> str: + """Format specialization color based on percentage. + + Uses a gradient from gray (0%) through orange (50%) to green (100%). + """ + # Normalize to 0-1 + ratio = spec_pct / 100.0 + + if ratio >= 0.5: + # Orange to green (50-100%) + t = (ratio - 0.5) * 2 # 0 to 1 + r = int(255 * (1 - t)) # 255 -> 0 + g = int(180 + 75 * t) # 180 -> 255 + b = int(50 * (1 - t)) # 50 -> 0 + else: + # Gray to orange (0-50%) + t = ratio * 2 # 0 to 1 + r = int(158 + 97 * t) # 158 -> 255 + g = int(158 + 22 * t) # 158 -> 180 + b = int(158 - 108 * t) # 158 -> 50 + + alpha = 0.15 + 0.25 * ratio # 0.15 to 0.4 + return f"rgba({r}, {g}, {b}, {alpha})" + + def _build_navigation_buttons(self, filename: str, line_num: int) -> str: + """Build navigation buttons for callers/callees. + + - Callers: All lines in a function show who calls this function + - Callees: Only actual call site lines show what they call + """ + line_key = (filename, line_num) + + funcname = self.line_to_function.get(line_key) + + # Get callers: look up by function definition line, not current line + # This ensures all lines in a function show who calls this function + if funcname: + func_def_line = self.function_definitions.get((filename, funcname), line_num) + func_def_key = (filename, func_def_line) + caller_list = self._deduplicate_by_function(self.callers_graph.get(func_def_key, set())) + else: + caller_list = self._deduplicate_by_function(self.callers_graph.get(line_key, set())) + + # Get callees: only show for actual call site lines (not every line in function) + callee_list = self._deduplicate_by_function(self.call_graph.get(line_key, set())) + + # Get edge counts for each caller/callee + # For callers, use the function definition key for edge lookup + if funcname: + func_def_line = self.function_definitions.get((filename, funcname), line_num) + caller_edge_key = (filename, func_def_line) + else: + caller_edge_key = line_key + callers_with_counts = self._get_edge_counts(caller_edge_key, caller_list, is_caller=True) + # For callees, use the actual line key since that's where the call happens + callees_with_counts = self._get_edge_counts(line_key, callee_list, is_caller=False) + + # Build navigation buttons with counts + caller_btn = self._create_navigation_button(callers_with_counts, 'caller', '▲') + callee_btn = self._create_navigation_button(callees_with_counts, 'callee', '▼') + + if caller_btn or callee_btn: + return f'
{caller_btn}{callee_btn}
' + return '' + + def _get_edge_counts(self, line_key: Tuple[str, int], + items: List[Tuple[str, int, str]], + is_caller: bool) -> List[Tuple[str, int, str, int]]: + """Get sample counts for each caller/callee edge.""" + result = [] + for file, line, func in items: + edge_line_key = (file, line) + if is_caller: + edge_key = (edge_line_key, line_key) + else: + edge_key = (line_key, edge_line_key) + + count = self.edge_samples.get(edge_key, 0) + result.append((file, line, func, count)) + + result.sort(key=lambda x: x[3], reverse=True) + return result + + def _deduplicate_by_function(self, items) -> List[Tuple[str, int, str]]: + """Remove duplicate entries based on (file, function) key. + + Args: + items: Iterable of (file, line, func) tuples (set or list) + """ + seen = {} + result = [] + for file, line, func in items: + key = (file, func) + if key not in seen: + seen[key] = True + result.append((file, line, func)) + return result + + def _create_navigation_button(self, items_with_counts: List[Tuple[str, int, str, int]], + btn_class: str, arrow: str) -> str: + """Create HTML for a navigation button with sample counts.""" + # Filter valid items + valid_items = [(f, l, fn, cnt) for f, l, fn, cnt in items_with_counts + if f in self.file_index and l > 0] + if not valid_items: + return "" + + if len(valid_items) == 1: + file, line, func, count = valid_items[0] + target_html = self.file_index[file] + nav_data = json.dumps({'link': f"{target_html}#line-{line}", 'func': func}) + title = f"Go to {btn_class}: {html.escape(func)} ({count:n} samples)" + return f'' + + # Multiple items - create menu + total_samples = sum(cnt for _, _, _, cnt in valid_items) + items_data = [ + { + 'file': os.path.basename(file), + 'func': func, + 'count': count, + 'link': f"{self.file_index[file]}#line-{line}" + } + for file, line, func, count in valid_items + ] + items_json = html.escape(json.dumps(items_data)) + title = f"{len(items_data)} {btn_class}s ({total_samples:n} samples)" + return f'' diff --git a/Lib/profiling/sampling/jsonl_collector.py b/Lib/profiling/sampling/jsonl_collector.py new file mode 100644 index 00000000000..41b0456d6f5 --- /dev/null +++ b/Lib/profiling/sampling/jsonl_collector.py @@ -0,0 +1,268 @@ +"""JSON Lines (JSONL) collector for the sampling profiler. + +Emits a normalized newline-delimited JSON record stream suitable for +programmatic consumption by external tools, scripts, and agents. Each line +is one JSON object; consumers can parse the file incrementally line by +line, but the producer writes the whole file at the end of the run (it is +not a live/streaming producer). + +Record schema +============= + +Every record is a JSON object with at least ``"type"``, ``"v"`` (record +schema version), and ``"run_id"`` (UUID4 hex tagging the run; allows +demultiplexing concatenated streams). Records appear in this fixed order: + +1. ``meta`` (exactly one, first line):: + + {"type":"meta","v":0,"run_id":"", + "sample_interval_usec":,"mode":"wall|cpu|gil|all|exception"} + + ``mode`` is omitted when not provided. + +2. ``string_table`` (zero or more):: + + {"type":"string_table","v":0,"run_id":"", + "strings":[{"str_id":,"value":""}, ...]} + + Strings (filenames, function names) are interned to keep repeated values + compact. IDs are zero-based. Each chunk holds up to ``_CHUNK_SIZE`` + entries, and each entry carries its explicit ``str_id`` so consumers do + not need to infer offsets across chunks. + +3. ``frame_table`` (zero or more):: + + {"type":"frame_table","v":0,"run_id":"", + "frames":[{"frame_id":,"path_str_id":,"func_str_id":, + "line":,"end_line":,"col":, + "end_col":}, ...]} + + ``end_line``/``col``/``end_col`` are *omitted* when source location data + is unavailable (a missing key means "not available", not zero or null). + ``line`` is ``0`` for synthetic frames (for example, internal marker + frames whose source location is None). Frame IDs are zero-based. + +4. ``agg`` (zero or more):: + + {"type":"agg","v":0,"run_id":"","kind":"frame","scope":"final", + "samples_total":, + "entries":[{"frame_id":,"self":,"cumulative":}, ...]} + + ``self`` counts samples where the frame was the leaf (currently + executing); ``cumulative`` counts samples where the frame appeared + anywhere in the stack (deduped per sample so recursion does not + double-count). ``samples_total`` is the run-wide total, repeated on + each chunk so a streaming consumer always knows the denominator. + +5. ``end`` (exactly one, last line):: + + {"type":"end","v":0,"run_id":"","samples_total":} + + Presence of ``end`` is the consumer's signal that the file is complete. + +Forward compatibility +===================== + +Consumers MUST ignore unknown record ``"type"`` values and unknown object +fields. New fields will be added by adding optional keys; an incompatible +schema change will bump the per-record ``"v"``. +""" + +from collections import Counter +import json +import uuid +from itertools import batched + +from .constants import PROFILING_MODE_NAMES +from .collector import normalize_location +from .stack_collector import StackTraceCollector + + +_CHUNK_SIZE = 256 +_SCHEMA_VERSION = 0 + + +class JsonlCollector(StackTraceCollector): + """Collector that exports finalized profiling data as JSONL. + + See the module docstring for the full record schema. The collector + accumulates samples in memory and writes the complete file at + ``export()`` time. + """ + + def __init__(self, sample_interval_usec, *, skip_idle=False, mode=None): + super().__init__(sample_interval_usec, skip_idle=skip_idle) + self.run_id = uuid.uuid4().hex + + self._string_to_id = {} + self._strings = [] + + self._frame_to_id = {} + self._frames = [] + + self._frame_self = Counter() + self._frame_cumulative = Counter() + self._samples_total = 0 + self._seen_frame_ids = set() + + self._mode = mode + + def process_frames(self, frames, _thread_id, weight=1): + self._samples_total += weight + self._seen_frame_ids.clear() + + for i, (filename, location, funcname, _opcode) in enumerate(frames): + frame_id = self._get_or_create_frame_id( + filename, location, funcname + ) + is_leaf = i == 0 + count_cumulative = frame_id not in self._seen_frame_ids + + if count_cumulative: + self._seen_frame_ids.add(frame_id) + + if is_leaf: + self._frame_self[frame_id] += weight + + if count_cumulative: + self._frame_cumulative[frame_id] += weight + + def export(self, filename): + with open(filename, "w", encoding="utf-8") as output: + self._write_message(output, self._build_meta_record()) + self._write_chunked_records( + output, + { + "type": "string_table", + "v": _SCHEMA_VERSION, + "run_id": self.run_id, + }, + "strings", + self._strings, + ) + self._write_chunked_records( + output, + { + "type": "frame_table", + "v": _SCHEMA_VERSION, + "run_id": self.run_id, + }, + "frames", + self._frames, + ) + self._write_chunked_records( + output, + { + "type": "agg", + "v": _SCHEMA_VERSION, + "run_id": self.run_id, + "kind": "frame", + "scope": "final", + "samples_total": self._samples_total, + }, + "entries", + self._iter_final_agg_entries(), + ) + self._write_message(output, self._build_end_record()) + print(f"JSONL profile written to {filename}") + return True + + def _build_meta_record(self): + record = { + "type": "meta", + "v": _SCHEMA_VERSION, + "run_id": self.run_id, + "sample_interval_usec": self.sample_interval_usec, + } + + if self._mode is not None: + record["mode"] = PROFILING_MODE_NAMES.get( + self._mode, str(self._mode) + ) + + return record + + def _build_end_record(self): + record = { + "type": "end", + "v": _SCHEMA_VERSION, + "run_id": self.run_id, + "samples_total": self._samples_total, + } + + return record + + def _iter_final_agg_entries(self): + for frame_record in self._frames: + frame_id = frame_record["frame_id"] + yield { + "frame_id": frame_id, + "self": self._frame_self[frame_id], + "cumulative": self._frame_cumulative[frame_id], + } + + def _get_or_create_frame_id(self, filename, location, funcname): + location_fields = self._location_to_export_fields(location) + func_str_id = self._intern_string(funcname) + path_str_id = self._intern_string(filename) + + frame_key = ( + path_str_id, + func_str_id, + location_fields["line"], + location_fields.get("end_line"), + location_fields.get("col"), + location_fields.get("end_col"), + ) + + if (frame_id := self._frame_to_id.get(frame_key)) is not None: + return frame_id + + frame_id = len(self._frames) + frame_record = { + "frame_id": frame_id, + "path_str_id": path_str_id, + "func_str_id": func_str_id, + **location_fields, + } + + self._frame_to_id[frame_key] = frame_id + self._frames.append(frame_record) + return frame_id + + def _intern_string(self, value): + value = str(value) + + if (string_id := self._string_to_id.get(value)) is not None: + return string_id + + string_id = len(self._strings) + self._string_to_id[value] = string_id + self._strings.append({"str_id": string_id, "value": value}) + return string_id + + @staticmethod + def _location_to_export_fields(location): + lineno, end_lineno, col_offset, end_col_offset = normalize_location( + location + ) + + fields = {"line": lineno} + if end_lineno > 0: + fields["end_line"] = end_lineno + if col_offset >= 0: + fields["col"] = col_offset + if end_col_offset >= 0: + fields["end_col"] = end_col_offset + return fields + + def _write_chunked_records( + self, output, base_record, chunk_field, entries + ): + for chunk in batched(entries, _CHUNK_SIZE): + self._write_message(output, {**base_record, chunk_field: chunk}) + + @staticmethod + def _write_message(output, record): + output.write(json.dumps(record, separators=(",", ":"))) + output.write("\n") diff --git a/Lib/profiling/sampling/live_collector/__init__.py b/Lib/profiling/sampling/live_collector/__init__.py new file mode 100644 index 00000000000..59d50955e52 --- /dev/null +++ b/Lib/profiling/sampling/live_collector/__init__.py @@ -0,0 +1,200 @@ +"""Live profiling collector that displays top-like statistics using curses. + + ┌─────────────────────────────┐ + │ Target Python Process │ + │ (being profiled) │ + └──────────────┬──────────────┘ + │ Stack sampling at + │ configured interval + │ (e.g., 10000µs) + ▼ + ┌─────────────────────────────┐ + │ LiveStatsCollector │ + │ ┌───────────────────────┐ │ + │ │ collect() │ │ Aggregates samples + │ │ - Iterates frames │ │ into statistics + │ │ - Updates counters │ │ + │ └───────────┬───────────┘ │ + │ │ │ + │ ▼ │ + │ ┌───────────────────────┐ │ + │ │ Data Storage │ │ + │ │ - result dict │ │ Tracks per-function: + │ │ - direct_calls │ │ • Direct samples + │ │ - cumulative_calls │ │ • Cumulative samples + │ └───────────┬───────────┘ │ • Derived time stats + │ │ │ + │ ▼ │ + │ ┌───────────────────────┐ │ + │ │ Display Update │ │ + │ │ (10Hz by default) │ │ Rate-limited refresh + │ └───────────┬───────────┘ │ + └──────────────┼──────────────┘ + │ + ▼ + ┌─────────────────────────────┐ + │ DisplayInterface │ + │ (Abstract layer) │ + └──────────────┬──────────────┘ + ┌───────┴────────┐ + │ │ + ┌──────────▼────────┐ ┌───▼──────────┐ + │ CursesDisplay │ │ MockDisplay │ + │ - Real terminal │ │ - Testing │ + │ - ncurses backend │ │ - No UI │ + └─────────┬─────────┘ └──────────────┘ + │ + ▼ + ┌─────────────────────────────────────┐ + │ Widget-Based Rendering │ + │ ┌─────────────────────────────────┐ │ + │ │ HeaderWidget │ │ + │ │ • PID, uptime, time, interval │ │ + │ │ • Sample stats & progress bar │ │ + │ │ • Efficiency bar │ │ + │ │ • Thread status & GC stats │ │ + │ │ • Function summary │ │ + │ │ • Top 3 hottest functions │ │ + │ ├─────────────────────────────────┤ │ + │ │ TableWidget │ │ + │ │ • Column headers (sortable) │ │ Interactive display + │ │ • Stats rows (scrolling) │ │ with keyboard controls: + │ │ - nsamples % time │ │ s: sort, p: pause + │ │ - function file:line │ │ r: reset, /: filter + │ ├─────────────────────────────────┤ │ q: quit, h: help + │ │ FooterWidget │ │ + │ │ • Legend and status │ │ + │ │ • Filter input prompt │ │ + │ └─────────────────────────────────┘ │ + └─────────────────────────────────────┘ + +Architecture: + +The live collector is organized into four layers. The data collection layer +(LiveStatsCollector) aggregates stack samples into per-function statistics without +any knowledge of how they will be presented. The display abstraction layer +(DisplayInterface) defines rendering operations without coupling to curses or any +specific UI framework. The widget layer (Widget, HeaderWidget, TableWidget, +FooterWidget, HelpWidget, ProgressBarWidget) encapsulates individual UI components +with their own rendering logic, promoting modularity and reusability. The +presentation layer (CursesDisplay/MockDisplay) implements the actual rendering for +terminal output and testing. + +The system runs two independent update loops. The sampling loop is driven by the +profiler at the configured interval (e.g., 10000µs) and continuously collects +stack frames and updates statistics. The display loop runs at a fixed refresh rate +(default 10Hz) and updates the terminal independently of sampling frequency. This +separation allows high-frequency sampling without overwhelming the terminal with +constant redraws. + +Statistics are computed incrementally as samples arrive. The collector maintains +running counters (direct calls and cumulative calls) in a dictionary keyed by +function location. Derived metrics like time estimates and percentages are computed +on-demand during display updates rather than being stored, which minimizes memory +overhead as the number of tracked functions grows. + +User input is processed asynchronously during display updates using non-blocking I/O. +This allows interactive controls (sorting, filtering, pausing) without interrupting +the data collection pipeline. The collector maintains mode flags (paused, +filter_input_mode) that affect what gets displayed but not what gets collected. + +""" + +# Re-export all public classes and constants for backward compatibility +from .collector import LiveStatsCollector +from .display import DisplayInterface, CursesDisplay, MockDisplay +from .widgets import ( + Widget, + ProgressBarWidget, + HeaderWidget, + TableWidget, + FooterWidget, + HelpWidget, +) +from .constants import ( + MICROSECONDS_PER_SECOND, + DISPLAY_UPDATE_HZ, + DISPLAY_UPDATE_INTERVAL_SEC, + MIN_TERMINAL_WIDTH, + MIN_TERMINAL_HEIGHT, + WIDTH_THRESHOLD_SAMPLE_PCT, + WIDTH_THRESHOLD_TOTTIME, + WIDTH_THRESHOLD_CUMUL_PCT, + WIDTH_THRESHOLD_CUMTIME, + HEADER_LINES, + FOOTER_LINES, + SAFETY_MARGIN, + TOP_FUNCTIONS_DISPLAY_COUNT, + COL_WIDTH_NSAMPLES, + COL_SPACING, + COL_WIDTH_SAMPLE_PCT, + COL_WIDTH_TIME, + MIN_FUNC_NAME_WIDTH, + MAX_FUNC_NAME_WIDTH, + MIN_AVAILABLE_SPACE, + MIN_BAR_WIDTH, + MAX_SAMPLE_RATE_BAR_WIDTH, + MAX_EFFICIENCY_BAR_WIDTH, + MIN_SAMPLE_RATE_FOR_SCALING, + FINISHED_BANNER_EXTRA_LINES, + COLOR_PAIR_HEADER_BG, + COLOR_PAIR_CYAN, + COLOR_PAIR_YELLOW, + COLOR_PAIR_GREEN, + COLOR_PAIR_MAGENTA, + COLOR_PAIR_RED, + COLOR_PAIR_SORTED_HEADER, + DEFAULT_SORT_BY, + DEFAULT_DISPLAY_LIMIT, +) + +__all__ = [ + # Main collector + "LiveStatsCollector", + # Display interfaces + "DisplayInterface", + "CursesDisplay", + "MockDisplay", + # Widgets + "Widget", + "ProgressBarWidget", + "HeaderWidget", + "TableWidget", + "FooterWidget", + "HelpWidget", + # Constants + "MICROSECONDS_PER_SECOND", + "DISPLAY_UPDATE_HZ", + "DISPLAY_UPDATE_INTERVAL_SEC", + "MIN_TERMINAL_WIDTH", + "MIN_TERMINAL_HEIGHT", + "WIDTH_THRESHOLD_SAMPLE_PCT", + "WIDTH_THRESHOLD_TOTTIME", + "WIDTH_THRESHOLD_CUMUL_PCT", + "WIDTH_THRESHOLD_CUMTIME", + "HEADER_LINES", + "FOOTER_LINES", + "SAFETY_MARGIN", + "TOP_FUNCTIONS_DISPLAY_COUNT", + "COL_WIDTH_NSAMPLES", + "COL_SPACING", + "COL_WIDTH_SAMPLE_PCT", + "COL_WIDTH_TIME", + "MIN_FUNC_NAME_WIDTH", + "MAX_FUNC_NAME_WIDTH", + "MIN_AVAILABLE_SPACE", + "MIN_BAR_WIDTH", + "MAX_SAMPLE_RATE_BAR_WIDTH", + "MAX_EFFICIENCY_BAR_WIDTH", + "MIN_SAMPLE_RATE_FOR_SCALING", + "FINISHED_BANNER_EXTRA_LINES", + "COLOR_PAIR_HEADER_BG", + "COLOR_PAIR_CYAN", + "COLOR_PAIR_YELLOW", + "COLOR_PAIR_GREEN", + "COLOR_PAIR_MAGENTA", + "COLOR_PAIR_RED", + "COLOR_PAIR_SORTED_HEADER", + "DEFAULT_SORT_BY", + "DEFAULT_DISPLAY_LIMIT", +] diff --git a/Lib/profiling/sampling/live_collector/collector.py b/Lib/profiling/sampling/live_collector/collector.py new file mode 100644 index 00000000000..c5bd0178f26 --- /dev/null +++ b/Lib/profiling/sampling/live_collector/collector.py @@ -0,0 +1,1112 @@ +"""LiveStatsCollector - Main collector class for live profiling.""" + +import collections +import contextlib +import curses +from dataclasses import dataclass, field +import os +import site +import sys +import sysconfig +import time +lazy import _colorize + +from ..collector import Collector, extract_lineno +from ..constants import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_UNKNOWN, + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_HAS_EXCEPTION, + PROFILING_MODE_CPU, + PROFILING_MODE_GIL, + PROFILING_MODE_WALL, +) +from .constants import ( + MICROSECONDS_PER_SECOND, + DISPLAY_UPDATE_INTERVAL_SEC, + MIN_TERMINAL_WIDTH, + MIN_TERMINAL_HEIGHT, + HEADER_LINES, + FOOTER_LINES, + SAFETY_MARGIN, + FINISHED_BANNER_EXTRA_LINES, + DEFAULT_SORT_BY, + DEFAULT_DISPLAY_LIMIT, + COLOR_PAIR_SAMPLES, + COLOR_PAIR_FILE, + COLOR_PAIR_FUNC, + COLOR_PAIR_HEADER_BG, + COLOR_PAIR_CYAN, + COLOR_PAIR_YELLOW, + COLOR_PAIR_GREEN, + COLOR_PAIR_MAGENTA, + COLOR_PAIR_RED, + COLOR_PAIR_SORTED_HEADER, +) +from .display import CursesDisplay +from .widgets import HeaderWidget, TableWidget, FooterWidget, HelpWidget, OpcodePanel +from .trend_tracker import TrendTracker + + +@dataclass +class ThreadData: + """Encapsulates all profiling data for a single thread.""" + + thread_id: int + + # Function call statistics: {location: {direct_calls: int, cumulative_calls: int}} + result: dict = field(default_factory=lambda: collections.defaultdict( + lambda: dict(direct_calls=0, cumulative_calls=0) + )) + + # Thread status statistics + has_gil: int = 0 + on_cpu: int = 0 + gil_requested: int = 0 + unknown: int = 0 + has_exception: int = 0 + total: int = 0 # Total status samples for this thread + + # Sample counts + sample_count: int = 0 + gc_frame_samples: int = 0 + + # Opcode statistics: {location: {opcode: count}} + opcode_stats: dict = field(default_factory=lambda: collections.defaultdict( + lambda: collections.defaultdict(int) + )) + + def increment_status_flag(self, status_flags): + """Update status counts based on status bit flags.""" + if status_flags & THREAD_STATUS_HAS_GIL: + self.has_gil += 1 + if status_flags & THREAD_STATUS_ON_CPU: + self.on_cpu += 1 + if status_flags & THREAD_STATUS_GIL_REQUESTED: + self.gil_requested += 1 + if status_flags & THREAD_STATUS_UNKNOWN: + self.unknown += 1 + if status_flags & THREAD_STATUS_HAS_EXCEPTION: + self.has_exception += 1 + self.total += 1 + + def as_status_dict(self): + """Return status counts as a dict for compatibility.""" + return { + "has_gil": self.has_gil, + "on_cpu": self.on_cpu, + "gil_requested": self.gil_requested, + "unknown": self.unknown, + "has_exception": self.has_exception, + "total": self.total, + } + + +class LiveStatsCollector(Collector): + """Collector that displays live top-like statistics using ncurses.""" + + def __init__( + self, + sample_interval_usec, + *, + skip_idle=False, + sort_by=DEFAULT_SORT_BY, + limit=DEFAULT_DISPLAY_LIMIT, + pid=None, + display=None, + mode=None, + opcodes=False, + async_aware=None, + ): + """ + Initialize the live stats collector. + + Args: + sample_interval_usec: Sampling interval in microseconds + skip_idle: Whether to skip idle threads + sort_by: Sort key ('tottime', 'nsamples', 'cumtime', 'sample_pct', 'cumul_pct') + limit: Maximum number of functions to display + pid: Process ID being profiled + display: DisplayInterface implementation (None means curses will be used) + mode: Profiling mode ('cpu', 'gil', etc.) - affects what stats are shown + opcodes: Whether to show opcode panel (requires --opcodes flag) + async_aware: Async tracing mode - None (sync only), "all" or "running" + """ + self.result = collections.defaultdict( + lambda: dict(total_rec_calls=0, direct_calls=0, cumulative_calls=0) + ) + self.sample_interval_usec = sample_interval_usec + self.sample_interval_sec = ( + sample_interval_usec / MICROSECONDS_PER_SECOND + ) + self.skip_idle = skip_idle + self.sort_by = sort_by + self.limit = limit + self.total_samples = 0 + self.start_time = None + self.stdscr = None + self.display = display # DisplayInterface implementation + self.running = True + self.pid = pid + self.mode = mode # Profiling mode + self.async_aware = async_aware # Async tracing mode + # Pre-select frame iterator method to avoid per-call dispatch overhead + self._get_frame_iterator = self._get_async_frame_iterator if async_aware else self._get_sync_frame_iterator + self._saved_stdout = None + self._saved_stderr = None + self._devnull = None + self._last_display_update = None + self.max_sample_rate = 0 # Track maximum sample rate seen + self.successful_samples = 0 # Track samples that captured frames + self.failed_samples = 0 # Track samples that failed to capture frames + self.display_update_interval_sec = DISPLAY_UPDATE_INTERVAL_SEC # Instance variable for display refresh rate + + # Thread status statistics (bit flags) + self.thread_status_counts = { + "has_gil": 0, + "on_cpu": 0, + "gil_requested": 0, + "unknown": 0, + "has_exception": 0, + "total": 0, # Total thread count across all samples + } + self.gc_frame_samples = 0 # Track samples with GC frames + + # Opcode statistics: {location: {opcode: count}} + self.opcode_stats = collections.defaultdict(lambda: collections.defaultdict(int)) + self.show_opcodes = opcodes # Show opcode panel when --opcodes flag is passed + self.selected_row = 0 # Currently selected row in table for opcode view + self.scroll_offset = 0 # Scroll offset for table when in opcode mode + + # Interactive controls state + self.paused = False # Pause UI updates (profiling continues) + self.show_help = False # Show help screen + self.filter_pattern = None # Glob pattern to filter functions + self.filter_input_mode = False # Currently entering filter text + self.filter_input_buffer = "" # Buffer for filter input + self.finished = False # Program has finished, showing final state + self.finish_timestamp = None # When profiling finished (for time freezing) + self.finish_wall_time = None # Wall clock time when profiling finished + + # Thread tracking state + self.thread_ids = [] # List of thread IDs seen + self.view_mode = "ALL" # "ALL" or "PER_THREAD" + self.current_thread_index = ( + 0 # Index into thread_ids when in PER_THREAD mode + ) + self.per_thread_data = {} # {thread_id: ThreadData} + + # Calculate common path prefixes to strip + self._path_prefixes = self._get_common_path_prefixes() + + # Widgets (initialized when display is available) + self.header_widget = None + self.table_widget = None + self.footer_widget = None + self.help_widget = None + self.opcode_panel = None + + # Color mode + self._can_colorize = _colorize.can_colorize() + + # Trend tracking (initialized after colors are set up) + self._trend_tracker = None + + self._seen_locations = set() + + @property + def elapsed_time(self): + """Get the elapsed time, frozen when finished.""" + if self.finished and self.finish_timestamp is not None: + # Handle case where process exited before any samples were collected + if self.start_time is None: + return 0 + return self.finish_timestamp - self.start_time + return time.perf_counter() - self.start_time if self.start_time else 0 + + @property + def current_time_display(self): + """Get the current time for display, frozen when finished.""" + if self.finished and self.finish_wall_time is not None: + return time.strftime("%H:%M:%S", time.localtime(self.finish_wall_time)) + return time.strftime("%H:%M:%S") + + def _get_or_create_thread_data(self, thread_id): + """Get or create ThreadData for a thread ID.""" + if thread_id not in self.per_thread_data: + self.per_thread_data[thread_id] = ThreadData(thread_id=thread_id) + return self.per_thread_data[thread_id] + + def _get_current_thread_data(self): + """Get ThreadData for currently selected thread in PER_THREAD mode.""" + if self.view_mode == "PER_THREAD" and self.current_thread_index < len(self.thread_ids): + thread_id = self.thread_ids[self.current_thread_index] + return self.per_thread_data.get(thread_id) + return None + + def _get_current_result_source(self): + """Get result dict for current view mode (aggregated or per-thread).""" + if self.view_mode == "ALL": + return self.result + thread_data = self._get_current_thread_data() + return thread_data.result if thread_data else {} + + def _get_common_path_prefixes(self): + """Get common path prefixes to strip from file paths.""" + prefixes = [] + + # Get the actual stdlib location from the os module + # This works for both installed Python and development builds + os_module_file = os.__file__ + if os_module_file: + # os.__file__ points to os.py, get its directory + stdlib_dir = os.path.dirname(os.path.abspath(os_module_file)) + prefixes.append(stdlib_dir) + + # Get stdlib location from sysconfig (may be different or same) + stdlib_path = sysconfig.get_path("stdlib") + if stdlib_path: + prefixes.append(stdlib_path) + + # Get platstdlib location (platform-specific stdlib) + platstdlib_path = sysconfig.get_path("platstdlib") + if platstdlib_path: + prefixes.append(platstdlib_path) + + # Get site-packages locations + for site_path in site.getsitepackages(): + prefixes.append(site_path) + + # Also check user site-packages + user_site = site.getusersitepackages() + if user_site: + prefixes.append(user_site) + + # Remove duplicates and sort by length (longest first) to match most specific paths first + prefixes = list(set(prefixes)) + prefixes.sort(key=lambda x: len(x), reverse=True) + + return prefixes + + def simplify_path(self, filepath): + """Simplify a file path by removing common prefixes.""" + # Try to match against known prefixes + for prefix_path in self._path_prefixes: + if filepath.startswith(prefix_path): + # Remove the prefix completely + relative = filepath[len(prefix_path) :].lstrip(os.sep) + return relative + + # If no match, return the original path + return filepath + + def process_frames(self, frames, thread_id=None): + """Process a single thread's frame stack. + + Args: + frames: List of frame information + thread_id: Thread ID for per-thread tracking (optional) + """ + if not frames: + return + + # Get per-thread data if tracking per-thread + thread_data = self._get_or_create_thread_data(thread_id) if thread_id is not None else None + self._seen_locations.clear() + + # Process each frame in the stack to track cumulative calls + # frame.location is (lineno, end_lineno, col_offset, end_col_offset), int, or None + for frame in frames: + lineno = extract_lineno(frame.location) + location = (frame.filename, lineno, frame.funcname) + if location not in self._seen_locations: + self._seen_locations.add(location) + self.result[location]["cumulative_calls"] += 1 + if thread_data: + thread_data.result[location]["cumulative_calls"] += 1 + + # The top frame gets counted as an inline call (directly executing) + top_frame = frames[0] + top_lineno = extract_lineno(top_frame.location) + top_location = (top_frame.filename, top_lineno, top_frame.funcname) + self.result[top_location]["direct_calls"] += 1 + if thread_data: + thread_data.result[top_location]["direct_calls"] += 1 + + # Track opcode for top frame (the actively executing instruction) + opcode = getattr(top_frame, 'opcode', None) + if opcode is not None: + self.opcode_stats[top_location][opcode] += 1 + if thread_data: + thread_data.opcode_stats[top_location][opcode] += 1 + + def _get_sync_frame_iterator(self, stack_frames): + """Iterator for sync frames.""" + return self._iter_all_frames(stack_frames, skip_idle=self.skip_idle) + + def _get_async_frame_iterator(self, stack_frames): + """Iterator for async frames, yielding (frames, thread_id) tuples.""" + for frames, thread_id, task_id in self._iter_async_frames(stack_frames): + yield frames, thread_id + + def collect_failed_sample(self): + self.failed_samples += 1 + self.total_samples += 1 + + def collect(self, stack_frames, timestamp_us=None): + """Collect and display profiling data.""" + if self.start_time is None: + self.start_time = time.perf_counter() + self._last_display_update = self.start_time + + has_gc_frame = False + + # Collect thread status stats (only available in sync mode) + if not self.async_aware: + status_counts, sample_has_gc, per_thread_stats = self._collect_thread_status_stats(stack_frames) + for key, count in status_counts.items(): + self.thread_status_counts[key] += count + if sample_has_gc: + has_gc_frame = True + + for thread_id, stats in per_thread_stats.items(): + thread_data = self._get_or_create_thread_data(thread_id) + thread_data.has_gil += stats.get("has_gil", 0) + thread_data.on_cpu += stats.get("on_cpu", 0) + thread_data.gil_requested += stats.get("gil_requested", 0) + thread_data.unknown += stats.get("unknown", 0) + thread_data.has_exception += stats.get("has_exception", 0) + thread_data.total += stats.get("total", 0) + if stats.get("gc_samples", 0): + thread_data.gc_frame_samples += stats["gc_samples"] + + # Process frames using pre-selected iterator + frames_processed = False + for frames, thread_id in self._get_frame_iterator(stack_frames): + if not frames: + continue + + self.process_frames(frames, thread_id=thread_id) + frames_processed = True + + # Track thread IDs + if thread_id is not None and thread_id not in self.thread_ids: + self.thread_ids.append(thread_id) + + if thread_id is not None: + thread_data = self._get_or_create_thread_data(thread_id) + thread_data.sample_count += 1 + + if has_gc_frame: + self.gc_frame_samples += 1 + + # Count as successful - the sample worked even if no frames matched the filter + # (e.g., in --mode exception when no thread has an active exception) + self.successful_samples += 1 + self.total_samples += 1 + + # Handle input on every sample for instant responsiveness + if self.display is not None: + self._handle_input() + + # Update display at configured rate if display is initialized and not paused + if self.display is not None and not self.paused: + current_time = time.perf_counter() + if ( + self._last_display_update is None + or (current_time - self._last_display_update) + >= self.display_update_interval_sec + ): + self._update_display() + self._last_display_update = current_time + + def _prepare_display_data(self, height): + """Prepare data for display rendering.""" + elapsed = self.elapsed_time + stats_list = self.build_stats_list() + + # Calculate available space for stats + # Add extra lines for finished banner when in finished state + extra_header_lines = ( + FINISHED_BANNER_EXTRA_LINES if self.finished else 0 + ) + max_stats_lines = max( + 0, + height + - HEADER_LINES + - extra_header_lines + - FOOTER_LINES + - SAFETY_MARGIN, + ) + stats_list = stats_list[:max_stats_lines] + + return elapsed, stats_list + + def _initialize_widgets(self, colors): + """Initialize widgets with display and colors.""" + if self.header_widget is None: + # Initialize trend tracker with colors + if self._trend_tracker is None: + self._trend_tracker = TrendTracker(colors, enabled=True) + + self.header_widget = HeaderWidget(self.display, colors, self) + self.table_widget = TableWidget(self.display, colors, self) + self.footer_widget = FooterWidget(self.display, colors, self) + self.help_widget = HelpWidget(self.display, colors) + self.opcode_panel = OpcodePanel(self.display, colors, self) + + def _render_display_sections( + self, height, width, elapsed, stats_list, colors + ): + """Render all display sections to the screen.""" + line = 0 + try: + # Initialize widgets if not already done + self._initialize_widgets(colors) + + # Render header + line = self.header_widget.render( + line, width, elapsed=elapsed, stats_list=stats_list + ) + + # Render table + line = self.table_widget.render( + line, width, height=height, stats_list=stats_list + ) + + # Render opcode panel if enabled + if self.show_opcodes: + line = self.opcode_panel.render( + line, width, height=height, stats_list=stats_list + ) + + except curses.error: + pass + + def _update_display(self): + """Update the display with current stats.""" + try: + # Clear screen and get dimensions + self.display.clear() + height, width = self.display.get_dimensions() + + # Check terminal size + if width < MIN_TERMINAL_WIDTH or height < MIN_TERMINAL_HEIGHT: + self._show_terminal_too_small(height, width) + self.display.refresh() + return + + # Setup colors and initialize widgets (needed for both help and normal display) + colors = self._setup_colors() + self._initialize_widgets(colors) + + # Show help screen if requested + if self.show_help: + self.help_widget.render(0, width, height=height) + self.display.refresh() + return + + # Prepare data + elapsed, stats_list = self._prepare_display_data(height) + + # Render all sections + self._render_display_sections( + height, width, elapsed, stats_list, colors + ) + + # Footer + self.footer_widget.render(height - 2, width) + + # Show filter input prompt if in filter input mode + if self.filter_input_mode: + self.footer_widget.render_filter_input_prompt( + height - 1, width + ) + + # Refresh display + self.display.redraw() + self.display.refresh() + + except Exception: + pass + + def _cycle_sort(self, reverse=False): + """Cycle through different sort modes in column order. + + Args: + reverse: If True, cycle backwards (right to left), otherwise forward (left to right) + """ + sort_modes = [ + "nsamples", + "sample_pct", + "tottime", + "cumul_pct", + "cumtime", + ] + try: + current_idx = sort_modes.index(self.sort_by) + if reverse: + self.sort_by = sort_modes[(current_idx - 1) % len(sort_modes)] + else: + self.sort_by = sort_modes[(current_idx + 1) % len(sort_modes)] + except ValueError: + self.sort_by = "nsamples" + + def _setup_colors(self): + """Set up color pairs and return color attributes.""" + A_BOLD = self.display.get_attr("A_BOLD") + A_REVERSE = self.display.get_attr("A_REVERSE") + A_UNDERLINE = self.display.get_attr("A_UNDERLINE") + A_NORMAL = self.display.get_attr("A_NORMAL") + + if self.display.has_colors() and self._can_colorize: + with contextlib.suppress(Exception): + theme = _colorize.get_theme(force_color=True).live_profiler + default_bg = -1 + + self.display.init_color_pair(COLOR_PAIR_SAMPLES, theme.samples_fg, default_bg) + self.display.init_color_pair(COLOR_PAIR_FILE, theme.file_fg, default_bg) + self.display.init_color_pair(COLOR_PAIR_FUNC, theme.func_fg, default_bg) + + # Normal header background color pair + self.display.init_color_pair( + COLOR_PAIR_HEADER_BG, + theme.normal_header_fg, + theme.normal_header_bg, + ) + + self.display.init_color_pair(COLOR_PAIR_CYAN, theme.pid_fg, default_bg) + self.display.init_color_pair(COLOR_PAIR_YELLOW, theme.time_fg, default_bg) + self.display.init_color_pair(COLOR_PAIR_GREEN, theme.uptime_fg, default_bg) + self.display.init_color_pair(COLOR_PAIR_MAGENTA, theme.interval_fg, default_bg) + self.display.init_color_pair(COLOR_PAIR_RED, theme.off_gil_fg, default_bg) + self.display.init_color_pair( + COLOR_PAIR_SORTED_HEADER, + theme.sorted_header_fg, + theme.sorted_header_bg, + ) + + TREND_UP_PAIR = 11 + TREND_DOWN_PAIR = 12 + self.display.init_color_pair(TREND_UP_PAIR, theme.trend_up_fg, default_bg) + self.display.init_color_pair(TREND_DOWN_PAIR, theme.trend_down_fg, default_bg) + + return { + "header": self.display.get_color_pair(COLOR_PAIR_HEADER_BG) | A_BOLD, + "cyan": self.display.get_color_pair(COLOR_PAIR_CYAN) | A_BOLD, + "yellow": self.display.get_color_pair(COLOR_PAIR_YELLOW) | A_BOLD, + "green": self.display.get_color_pair(COLOR_PAIR_GREEN) | A_BOLD, + "magenta": self.display.get_color_pair(COLOR_PAIR_MAGENTA) | A_BOLD, + "red": self.display.get_color_pair(COLOR_PAIR_RED) | A_BOLD, + "sorted_header": self.display.get_color_pair(COLOR_PAIR_SORTED_HEADER) | A_BOLD, + "normal_header": self.display.get_color_pair(COLOR_PAIR_HEADER_BG) | A_BOLD, + "color_samples": self.display.get_color_pair(COLOR_PAIR_SAMPLES), + "color_file": self.display.get_color_pair(COLOR_PAIR_FILE), + "color_func": self.display.get_color_pair(COLOR_PAIR_FUNC), + "trend_up": self.display.get_color_pair(TREND_UP_PAIR) | A_BOLD, + "trend_down": self.display.get_color_pair(TREND_DOWN_PAIR) | A_BOLD, + "trend_stable": A_NORMAL, + } + + # Fallback for no-color mode + return { + "header": A_REVERSE | A_BOLD, + "cyan": A_BOLD, + "yellow": A_BOLD, + "green": A_BOLD, + "magenta": A_BOLD, + "red": A_BOLD, + "sorted_header": A_REVERSE | A_BOLD | A_UNDERLINE, + "normal_header": A_REVERSE | A_BOLD, + "color_samples": A_NORMAL, + "color_file": A_NORMAL, + "color_func": A_NORMAL, + "trend_up": A_BOLD, + "trend_down": A_BOLD, + "trend_stable": A_NORMAL, + } + + def build_stats_list(self): + """Build and sort the statistics list.""" + stats_list = [] + result_source = self._get_current_result_source() + + for func, call_counts in result_source.items(): + # Apply filter if set (using substring matching) + if self.filter_pattern: + filename, lineno, funcname = func + # Simple substring match (case-insensitive) + pattern_lower = self.filter_pattern.lower() + filename_lower = filename.lower() + funcname_lower = funcname.lower() + + # Match if pattern is substring of filename, funcname, or combined + matched = ( + pattern_lower in filename_lower + or pattern_lower in funcname_lower + or pattern_lower in f"{filename_lower}:{funcname_lower}" + ) + if not matched: + continue + + direct_calls = call_counts.get("direct_calls", 0) + cumulative_calls = call_counts.get("cumulative_calls", 0) + total_time = direct_calls * self.sample_interval_sec + cumulative_time = cumulative_calls * self.sample_interval_sec + + # Calculate sample percentages using successful_samples as denominator + # This ensures percentages are relative to samples that actually had data, + # not all sampling attempts (important for filtered modes like --mode exception) + sample_pct = (direct_calls / self.successful_samples * 100) if self.successful_samples > 0 else 0 + cumul_pct = (cumulative_calls / self.successful_samples * 100) if self.successful_samples > 0 else 0 + + # Calculate trends for all columns using TrendTracker + trends = {} + if self._trend_tracker is not None: + trends = self._trend_tracker.update_metrics( + func, + { + 'nsamples': direct_calls, + 'tottime': total_time, + 'cumtime': cumulative_time, + 'sample_pct': sample_pct, + 'cumul_pct': cumul_pct, + } + ) + + stats_list.append( + { + "func": func, + "direct_calls": direct_calls, + "cumulative_calls": cumulative_calls, + "total_time": total_time, + "cumulative_time": cumulative_time, + "sample_pct": sample_pct, + "cumul_pct": cumul_pct, + "trends": trends, + } + ) + + # Sort the stats + if self.sort_by == "nsamples": + stats_list.sort(key=lambda x: x["direct_calls"], reverse=True) + elif self.sort_by == "tottime": + stats_list.sort(key=lambda x: x["total_time"], reverse=True) + elif self.sort_by == "cumtime": + stats_list.sort(key=lambda x: x["cumulative_time"], reverse=True) + elif self.sort_by == "sample_pct": + stats_list.sort(key=lambda x: x["sample_pct"], reverse=True) + elif self.sort_by == "cumul_pct": + stats_list.sort(key=lambda x: x["cumul_pct"], reverse=True) + + return stats_list + + def reset_stats(self): + """Reset all collected statistics.""" + self.result.clear() + self.opcode_stats.clear() + self.per_thread_data.clear() + self.thread_ids.clear() + self.view_mode = "ALL" + self.current_thread_index = 0 + self.total_samples = 0 + self.successful_samples = 0 + self.failed_samples = 0 + self.max_sample_rate = 0 + self.thread_status_counts = { + "has_gil": 0, + "on_cpu": 0, + "gil_requested": 0, + "unknown": 0, + "has_exception": 0, + "total": 0, + } + self.gc_frame_samples = 0 + # Clear trend tracking + if self._trend_tracker is not None: + self._trend_tracker.clear() + # Reset finished state and finish timestamp + self.finished = False + self.finish_timestamp = None + self.finish_wall_time = None + self.start_time = time.perf_counter() + self._last_display_update = self.start_time + + def mark_finished(self): + """Mark the profiling session as finished.""" + self.finished = True + # Capture the finish timestamp to freeze all timing displays + self.finish_timestamp = time.perf_counter() + self.finish_wall_time = time.time() # Wall clock time for display + # Force a final display update to show the finished message + if self.display is not None: + self._update_display() + + def _handle_finished_input_update(self, had_input): + """Update display after input when program is finished.""" + if self.finished and had_input and self.display is not None: + self._update_display() + + def _get_visible_rows_info(self): + """Calculate visible rows and stats list for opcode navigation.""" + stats_list = self.build_stats_list() + if self.display: + height, _ = self.display.get_dimensions() + extra_header = FINISHED_BANNER_EXTRA_LINES if self.finished else 0 + max_stats = max(0, height - HEADER_LINES - extra_header - FOOTER_LINES - SAFETY_MARGIN) + stats_list = stats_list[:max_stats] + visible_rows = max(1, height - 8 - 2 - 12) + else: + visible_rows = self.limit + total_rows = len(stats_list) + return stats_list, visible_rows, total_rows + + def _move_selection_down(self): + """Move selection down in opcode mode with scrolling.""" + if not self.show_opcodes: + return + + stats_list, visible_rows, total_rows = self._get_visible_rows_info() + if total_rows == 0: + return + + # Max scroll is when last item is at bottom + max_scroll = max(0, total_rows - visible_rows) + # Current absolute position + abs_pos = self.scroll_offset + self.selected_row + + # Only move if not at the last item + if abs_pos < total_rows - 1: + # Try to move selection within visible area first + if self.selected_row < visible_rows - 1: + self.selected_row += 1 + elif self.scroll_offset < max_scroll: + # Scroll down + self.scroll_offset += 1 + + # Clamp to valid range + self.scroll_offset = min(self.scroll_offset, max_scroll) + max_selected = min(visible_rows - 1, total_rows - self.scroll_offset - 1) + self.selected_row = min(self.selected_row, max(0, max_selected)) + + def _move_selection_up(self): + """Move selection up in opcode mode with scrolling.""" + if not self.show_opcodes: + return + + if self.selected_row > 0: + self.selected_row -= 1 + elif self.scroll_offset > 0: + self.scroll_offset -= 1 + + # Clamp to valid range based on actual stats_list + stats_list, visible_rows, total_rows = self._get_visible_rows_info() + if total_rows > 0: + max_scroll = max(0, total_rows - visible_rows) + self.scroll_offset = min(self.scroll_offset, max_scroll) + max_selected = min(visible_rows - 1, total_rows - self.scroll_offset - 1) + self.selected_row = min(self.selected_row, max(0, max_selected)) + + def _navigate_to_previous_thread(self): + """Navigate to previous thread in PER_THREAD mode, or switch from ALL to PER_THREAD.""" + if len(self.thread_ids) > 0: + if self.view_mode == "ALL": + self.view_mode = "PER_THREAD" + self.current_thread_index = len(self.thread_ids) - 1 + else: + self.current_thread_index = ( + self.current_thread_index - 1 + ) % len(self.thread_ids) + + def _navigate_to_next_thread(self): + """Navigate to next thread in PER_THREAD mode, or switch from ALL to PER_THREAD.""" + if len(self.thread_ids) > 0: + if self.view_mode == "ALL": + self.view_mode = "PER_THREAD" + self.current_thread_index = 0 + else: + self.current_thread_index = ( + self.current_thread_index + 1 + ) % len(self.thread_ids) + + def _show_terminal_too_small(self, height, width): + """Display a message when terminal is too small.""" + A_BOLD = self.display.get_attr("A_BOLD") + msg1 = "Terminal too small!" + msg2 = f"Need: {MIN_TERMINAL_WIDTH}x{MIN_TERMINAL_HEIGHT}" + msg3 = f"Have: {width}x{height}" + msg4 = "Please resize" + + # Center the messages + if height >= 4: + self.display.add_str( + height // 2 - 2, + max(0, (width - len(msg1)) // 2), + msg1[: width - 1], + A_BOLD, + ) + self.display.add_str( + height // 2 - 1, + max(0, (width - len(msg2)) // 2), + msg2[: width - 1], + ) + self.display.add_str( + height // 2, + max(0, (width - len(msg3)) // 2), + msg3[: width - 1], + ) + self.display.add_str( + height // 2 + 1, + max(0, (width - len(msg4)) // 2), + msg4[: width - 1], + ) + elif height >= 1: + self.display.add_str(0, 0, msg1[: width - 1], A_BOLD) + + def _show_terminal_size_warning_and_wait(self, height, width): + """Show terminal size warning during initialization and wait for user acknowledgment.""" + A_BOLD = self.display.get_attr("A_BOLD") + A_DIM = self.display.get_attr("A_DIM") + + self.display.clear() + msg1 = "WARNING: Terminal too small!" + msg2 = f"Required: {MIN_TERMINAL_WIDTH}x{MIN_TERMINAL_HEIGHT}" + msg3 = f"Current: {width}x{height}" + msg4 = "Please resize your terminal for best experience" + msg5 = "Press any key to continue..." + + # Center the messages + if height >= 5: + self.display.add_str( + height // 2 - 2, + max(0, (width - len(msg1)) // 2), + msg1[: width - 1], + A_BOLD, + ) + self.display.add_str( + height // 2 - 1, + max(0, (width - len(msg2)) // 2), + msg2[: width - 1], + ) + self.display.add_str( + height // 2, + max(0, (width - len(msg3)) // 2), + msg3[: width - 1], + ) + self.display.add_str( + height // 2 + 1, + max(0, (width - len(msg4)) // 2), + msg4[: width - 1], + ) + self.display.add_str( + height // 2 + 3, + max(0, (width - len(msg5)) // 2), + msg5[: width - 1], + A_DIM, + ) + elif height >= 1: + self.display.add_str(0, 0, msg1[: width - 1], A_BOLD) + + self.display.refresh() + # Wait for user acknowledgment (2 seconds timeout) + self.display.set_nodelay(False) + # Note: timeout is curses-specific, skipping for now + self.display.get_input() + self.display.set_nodelay(True) + + def _handle_input(self): + """Handle keyboard input (non-blocking).""" + self.display.set_nodelay(True) + ch = self.display.get_input() + + # Handle filter input mode FIRST - takes precedence over all commands + if self.filter_input_mode: + if ch == 27: # ESC key + self.filter_input_mode = False + self.filter_input_buffer = "" + elif ch == 10 or ch == 13: # Enter key + self.filter_pattern = ( + self.filter_input_buffer + if self.filter_input_buffer + else None + ) + self.filter_input_mode = False + self.filter_input_buffer = "" + elif ch == 127 or ch == 263: # Backspace + if self.filter_input_buffer: + self.filter_input_buffer = self.filter_input_buffer[:-1] + elif ch >= 32 and ch < 127: # Printable characters + self.filter_input_buffer += chr(ch) + + # Update display if input was processed while finished + self._handle_finished_input_update(ch != -1) + return + + # Handle help toggle keys + if ch == ord("h") or ch == ord("H") or ch == ord("?"): + self.show_help = not self.show_help + return + + # If showing help, any other key closes it + if self.show_help and ch != -1: + self.show_help = False + return + + # Handle regular commands + if ch == ord("q") or ch == ord("Q"): + self.running = False + + elif ch == ord("s"): + self._cycle_sort(reverse=False) + + elif ch == ord("S"): + self._cycle_sort(reverse=True) + + elif ch == ord("p") or ch == ord("P"): + self.paused = not self.paused + + elif ch == ord("r") or ch == ord("R"): + # Don't allow reset when profiling is finished + if not self.finished: + self.reset_stats() + + elif ch == ord("+") or ch == ord("="): + # Decrease update interval (faster refresh) + self.display_update_interval_sec = max( + 0.05, self.display_update_interval_sec - 0.05 + ) # Min 20Hz + + elif ch == ord("-") or ch == ord("_"): + # Increase update interval (slower refresh) + self.display_update_interval_sec = min( + 1.0, self.display_update_interval_sec + 0.05 + ) # Max 1Hz + + elif ch == ord("c") or ch == ord("C"): + if self.filter_pattern: + self.filter_pattern = None + + elif ch == ord("/"): + self.filter_input_mode = True + self.filter_input_buffer = self.filter_pattern or "" + + elif ch == ord("t") or ch == ord("T"): + # Toggle between ALL and PER_THREAD modes + if self.view_mode == "ALL": + if len(self.thread_ids) > 0: + self.view_mode = "PER_THREAD" + self.current_thread_index = 0 + else: + self.view_mode = "ALL" + + elif ch == ord("x") or ch == ord("X"): + # Toggle trend colors on/off + if self._trend_tracker is not None: + self._trend_tracker.toggle() + + elif ch == ord("j") or ch == ord("J"): + # Move selection down in opcode mode (with scrolling) + self._move_selection_down() + + elif ch == ord("k") or ch == ord("K"): + # Move selection up in opcode mode (with scrolling) + self._move_selection_up() + + elif ch == curses.KEY_UP: + # Move selection up (same as 'k') when in opcode mode + if self.show_opcodes: + self._move_selection_up() + else: + # Navigate to previous thread (same as KEY_LEFT) + self._navigate_to_previous_thread() + + elif ch == curses.KEY_DOWN: + # Move selection down (same as 'j') when in opcode mode + if self.show_opcodes: + self._move_selection_down() + else: + # Navigate to next thread (same as KEY_RIGHT) + self._navigate_to_next_thread() + + elif ch == curses.KEY_LEFT: + # Navigate to previous thread + self._navigate_to_previous_thread() + + elif ch == curses.KEY_RIGHT: + # Navigate to next thread + self._navigate_to_next_thread() + + # Update display if input was processed while finished + self._handle_finished_input_update(ch != -1) + + def init_curses(self, stdscr): + """Initialize curses display and suppress stdout/stderr.""" + self.stdscr = stdscr + self.display = CursesDisplay(stdscr) + + # Check terminal size upfront and warn if too small + height, width = self.display.get_dimensions() + + if width < MIN_TERMINAL_WIDTH or height < MIN_TERMINAL_HEIGHT: + # Show warning and wait briefly for user to see it + self._show_terminal_size_warning_and_wait(height, width) + + curses.curs_set(0) # Hide cursor + stdscr.nodelay(True) # Non-blocking input + stdscr.scrollok(False) # Disable scrolling + stdscr.idlok(False) # Disable hardware insert/delete + stdscr.leaveok(True) # Don't care about cursor position + + if curses.has_colors(): + curses.start_color() + curses.use_default_colors() + + # Suppress stdout and stderr to prevent interfering with curses display + # Use contextlib.redirect_stdout/stderr for better resource management + self._saved_stdout = sys.stdout + self._saved_stderr = sys.stderr + # Open devnull and ensure it's cleaned up even if an exception occurs + try: + self._devnull = open(os.devnull, "w") + sys.stdout = self._devnull + sys.stderr = self._devnull + except Exception: + # If redirection fails, restore original streams + sys.stdout = self._saved_stdout + sys.stderr = self._saved_stderr + raise + + # Initial clear + self.display.clear() + self.display.refresh() + + def cleanup_curses(self): + """Clean up curses display and restore stdout/stderr.""" + # Restore stdout and stderr in reverse order + # Use try-finally to ensure cleanup even if restoration fails + try: + if self._saved_stdout is not None: + sys.stdout = self._saved_stdout + self._saved_stdout = None + if self._saved_stderr is not None: + sys.stderr = self._saved_stderr + self._saved_stderr = None + finally: + # Always close devnull, even if stdout/stderr restoration fails + if self._devnull is not None: + with contextlib.suppress(Exception): + self._devnull.close() + self._devnull = None + + if self.display is not None and self.stdscr is not None: + with contextlib.suppress(Exception): + curses.curs_set(1) # Show cursor + self.display.set_nodelay(False) + + def export(self, filename): + """Export is not supported in live mode.""" + raise NotImplementedError( + "Export to file is not supported in live mode. " + "Use the live TUI to view statistics in real-time." + ) diff --git a/Lib/profiling/sampling/live_collector/constants.py b/Lib/profiling/sampling/live_collector/constants.py new file mode 100644 index 00000000000..bb45006553a --- /dev/null +++ b/Lib/profiling/sampling/live_collector/constants.py @@ -0,0 +1,65 @@ +"""Constants for the live profiling collector.""" + +# Time conversion constants +MICROSECONDS_PER_SECOND = 1_000_000 + +# Display update constants +DISPLAY_UPDATE_HZ = 10 +DISPLAY_UPDATE_INTERVAL_SEC = 1.0 / DISPLAY_UPDATE_HZ # 0.1 seconds + +# Terminal size constraints +MIN_TERMINAL_WIDTH = 60 +MIN_TERMINAL_HEIGHT = 12 + +# Column width thresholds +WIDTH_THRESHOLD_SAMPLE_PCT = 80 +WIDTH_THRESHOLD_TOTTIME = 100 +WIDTH_THRESHOLD_CUMUL_PCT = 120 +WIDTH_THRESHOLD_CUMTIME = 140 + +# Display layout constants +HEADER_LINES = 10 # Increased to include thread status line +FOOTER_LINES = 2 +SAFETY_MARGIN = 1 +TOP_FUNCTIONS_DISPLAY_COUNT = 3 + +# Column widths for data display +COL_WIDTH_NSAMPLES = 13 +COL_SPACING = 2 +COL_WIDTH_SAMPLE_PCT = 5 +COL_WIDTH_TIME = 10 + +# Function name display +MIN_FUNC_NAME_WIDTH = 10 +MAX_FUNC_NAME_WIDTH = 40 +MIN_AVAILABLE_SPACE = 10 + +# Progress bar display +MIN_BAR_WIDTH = 10 +MAX_SAMPLE_RATE_BAR_WIDTH = 30 +MAX_EFFICIENCY_BAR_WIDTH = 60 + +# Sample rate scaling +MIN_SAMPLE_RATE_FOR_SCALING = 100 + +# Finished banner display +FINISHED_BANNER_EXTRA_LINES = 3 # Blank line + banner + blank line + +# Opcode panel display +OPCODE_PANEL_HEIGHT = 12 # Height reserved for opcode statistics panel + +# Color pair IDs +COLOR_PAIR_SAMPLES = 1 +COLOR_PAIR_FILE = 2 +COLOR_PAIR_FUNC = 3 +COLOR_PAIR_HEADER_BG = 4 +COLOR_PAIR_CYAN = 5 +COLOR_PAIR_YELLOW = 6 +COLOR_PAIR_GREEN = 7 +COLOR_PAIR_MAGENTA = 8 +COLOR_PAIR_RED = 9 +COLOR_PAIR_SORTED_HEADER = 10 + +# Default display settings +DEFAULT_SORT_BY = "nsamples" # Number of samples in leaf (self time) +DEFAULT_DISPLAY_LIMIT = 20 diff --git a/Lib/profiling/sampling/live_collector/display.py b/Lib/profiling/sampling/live_collector/display.py new file mode 100644 index 00000000000..f5324421b10 --- /dev/null +++ b/Lib/profiling/sampling/live_collector/display.py @@ -0,0 +1,240 @@ +"""Display interface abstractions for the live profiling collector.""" + +import contextlib +import curses +from abc import ABC, abstractmethod + + +class DisplayInterface(ABC): + """Abstract interface for display operations to enable testing.""" + + @abstractmethod + def get_dimensions(self): + """Get terminal dimensions as (height, width).""" + pass + + @abstractmethod + def clear(self): + """Clear the screen.""" + pass + + @abstractmethod + def refresh(self): + """Refresh the screen to show changes.""" + pass + + @abstractmethod + def redraw(self): + """Redraw the entire window.""" + pass + + @abstractmethod + def add_str(self, line, col, text, attr=0): + """Add a string at the specified position.""" + pass + + @abstractmethod + def get_input(self): + """Get a character from input (non-blocking). Returns -1 if no input.""" + pass + + @abstractmethod + def set_nodelay(self, flag): + """Set non-blocking mode for input.""" + pass + + @abstractmethod + def has_colors(self): + """Check if terminal supports colors.""" + pass + + @abstractmethod + def init_color_pair(self, pair_id, fg, bg): + """Initialize a color pair.""" + pass + + @abstractmethod + def get_color_pair(self, pair_id): + """Get a color pair attribute.""" + pass + + @abstractmethod + def get_attr(self, name): + """Get a display attribute by name (e.g., 'A_BOLD', 'A_REVERSE').""" + pass + + +class CursesDisplay(DisplayInterface): + """Real curses display implementation.""" + + def __init__(self, stdscr): + self.stdscr = stdscr + + def get_dimensions(self): + return self.stdscr.getmaxyx() + + def clear(self): + # Use erase() instead of clear() to avoid flickering + # clear() forces a complete screen redraw, erase() just clears the buffer + self.stdscr.erase() + + def refresh(self): + self.stdscr.refresh() + + def redraw(self): + # Use noutrefresh + doupdate for smoother updates + self.stdscr.noutrefresh() + curses.doupdate() + + def add_str(self, line, col, text, attr=0): + try: + height, width = self.get_dimensions() + if 0 <= line < height and 0 <= col < width: + max_len = width - col - 1 + if len(text) > max_len: + text = text[:max_len] + self.stdscr.addstr(line, col, text, attr) + except curses.error: + pass + + def get_input(self): + try: + return self.stdscr.getch() + except (KeyError, curses.error): + return -1 + + def set_nodelay(self, flag): + self.stdscr.nodelay(flag) + + def has_colors(self): + return curses.has_colors() + + def init_color_pair(self, pair_id, fg, bg): + try: + curses.init_pair(pair_id, fg, bg) + except curses.error: + pass + + def get_color_pair(self, pair_id): + return curses.color_pair(pair_id) + + def get_attr(self, name): + return getattr(curses, name, 0) + + +class MockDisplay(DisplayInterface): + """Mock display for testing.""" + + def __init__(self, height=40, width=160): + self.height = height + self.width = width + self.buffer = {} + self.cleared = False + self.refreshed = False + self.redrawn = False + self.input_queue = [] + self.nodelay_flag = True + self.colors_supported = True + self.color_pairs = {} + + def get_dimensions(self): + return (self.height, self.width) + + def clear(self): + self.buffer.clear() + self.cleared = True + + def refresh(self): + self.refreshed = True + + def redraw(self): + self.redrawn = True + + def add_str(self, line, col, text, attr=0): + if 0 <= line < self.height and 0 <= col < self.width: + max_len = self.width - col - 1 + if len(text) > max_len: + text = text[:max_len] + self.buffer[(line, col)] = (text, attr) + + def get_input(self): + if self.input_queue: + return self.input_queue.pop(0) + return -1 + + def set_nodelay(self, flag): + self.nodelay_flag = flag + + def has_colors(self): + return self.colors_supported + + def init_color_pair(self, pair_id, fg, bg): + self.color_pairs[pair_id] = (fg, bg) + + def get_color_pair(self, pair_id): + return pair_id << 8 + + def get_attr(self, name): + attrs = { + "A_NORMAL": 0, + "A_BOLD": 1 << 16, + "A_REVERSE": 1 << 17, + "A_UNDERLINE": 1 << 18, + "A_DIM": 1 << 19, + } + return attrs.get(name, 0) + + def simulate_input(self, char): + """Helper method for tests to simulate keyboard input.""" + self.input_queue.append(char) + + def get_text_at(self, line, col): + """Helper method for tests to inspect buffer content.""" + if (line, col) in self.buffer: + return self.buffer[(line, col)][0] + return None + + def get_all_lines(self): + """Get all display content as a list of lines (for testing).""" + if not self.buffer: + return [] + + max_line = max(pos[0] for pos in self.buffer.keys()) + lines = [] + for line_num in range(max_line + 1): + line_parts = [] + for col in range(self.width): + if (line_num, col) in self.buffer: + text, _ = self.buffer[(line_num, col)] + line_parts.append((col, text)) + + # Reconstruct line from parts + if line_parts: + line_parts.sort(key=lambda x: x[0]) + line = "" + last_col = 0 + for col, text in line_parts: + if col > last_col: + line += " " * (col - last_col) + line += text + last_col = col + len(text) + lines.append(line.rstrip()) + else: + lines.append("") + + # Remove trailing empty lines + while lines and not lines[-1]: + lines.pop() + + return lines + + def find_text(self, pattern): + """Find text matching pattern in buffer (for testing). Returns (line, col) or None.""" + for (line, col), (text, _) in self.buffer.items(): + if pattern in text: + return (line, col) + return None + + def contains_text(self, text): + """Check if display contains the given text anywhere (for testing).""" + return self.find_text(text) is not None diff --git a/Lib/profiling/sampling/live_collector/trend_tracker.py b/Lib/profiling/sampling/live_collector/trend_tracker.py new file mode 100644 index 00000000000..c025b83a134 --- /dev/null +++ b/Lib/profiling/sampling/live_collector/trend_tracker.py @@ -0,0 +1,157 @@ +"""TrendTracker - Encapsulated trend tracking for live profiling metrics. + +This module provides trend tracking functionality for profiling metrics, +calculating direction indicators (up/down/stable) and managing associated +visual attributes like colors. +""" + +import curses +from typing import Dict, Literal, Any + +TrendDirection = Literal["up", "down", "stable"] + + +class TrendTracker: + """ + Tracks metric trends over time and provides visual indicators. + + This class encapsulates all logic for: + - Tracking previous values of metrics + - Calculating trend directions (up/down/stable) + - Determining visual attributes (colors) for trends + - Managing enable/disable state + + Example: + tracker = TrendTracker(colors_dict) + tracker.update("func1", "nsamples", 10) + trend = tracker.get_trend("func1", "nsamples") + color = tracker.get_color("func1", "nsamples") + """ + + # Threshold for determining if a value has changed significantly + CHANGE_THRESHOLD = 0.001 + + def __init__(self, colors: Dict[str, int], enabled: bool = True): + """ + Initialize the trend tracker. + + Args: + colors: Dictionary containing color attributes including + 'trend_up', 'trend_down', 'trend_stable' + enabled: Whether trend tracking is initially enabled + """ + self._previous_values: Dict[Any, Dict[str, float]] = {} + self._enabled = enabled + self._colors = colors + + @property + def enabled(self) -> bool: + """Whether trend tracking is enabled.""" + return self._enabled + + def toggle(self) -> bool: + """ + Toggle trend tracking on/off. + + Returns: + New enabled state + """ + self._enabled = not self._enabled + return self._enabled + + def set_enabled(self, enabled: bool) -> None: + """Set trend tracking enabled state.""" + self._enabled = enabled + + def update(self, key: Any, metric: str, value: float) -> TrendDirection: + """ + Update a metric value and calculate its trend. + + Args: + key: Identifier for the entity (e.g., function) + metric: Name of the metric (e.g., 'nsamples', 'tottime') + value: Current value of the metric + + Returns: + Trend direction: 'up', 'down', or 'stable' + """ + # Initialize storage for this key if needed + if key not in self._previous_values: + self._previous_values[key] = {} + + # Get previous value, defaulting to current if not tracked yet + prev_value = self._previous_values[key].get(metric, value) + + # Calculate trend + if value > prev_value + self.CHANGE_THRESHOLD: + trend = "up" + elif value < prev_value - self.CHANGE_THRESHOLD: + trend = "down" + else: + trend = "stable" + + # Update previous value for next iteration + self._previous_values[key][metric] = value + + return trend + + def get_trend(self, key: Any, metric: str) -> TrendDirection: + """ + Get the current trend for a metric without updating. + + Args: + key: Identifier for the entity + metric: Name of the metric + + Returns: + Trend direction, or 'stable' if not tracked + """ + # This would require storing trends separately, which we don't do + # For now, return stable if not found + return "stable" + + def get_color(self, trend: TrendDirection) -> int: + """ + Get the color attribute for a trend direction. + + Args: + trend: The trend direction + + Returns: + Curses color attribute (or A_NORMAL if disabled) + """ + if not self._enabled: + return curses.A_NORMAL + + if trend == "up": + return self._colors.get("trend_up", curses.A_BOLD) + elif trend == "down": + return self._colors.get("trend_down", curses.A_BOLD) + else: # stable + return self._colors.get("trend_stable", curses.A_NORMAL) + + def update_metrics(self, key: Any, metrics: Dict[str, float]) -> Dict[str, TrendDirection]: + """ + Update multiple metrics at once and get their trends. + + Args: + key: Identifier for the entity + metrics: Dictionary of metric_name -> value + + Returns: + Dictionary of metric_name -> trend_direction + """ + trends = {} + for metric, value in metrics.items(): + trends[metric] = self.update(key, metric, value) + return trends + + def clear(self) -> None: + """Clear all tracked values (useful on stats reset).""" + self._previous_values.clear() + + def __repr__(self) -> str: + """String representation for debugging.""" + status = "enabled" if self._enabled else "disabled" + tracked = len(self._previous_values) + return f"TrendTracker({status}, tracking {tracked} entities)" diff --git a/Lib/profiling/sampling/live_collector/widgets.py b/Lib/profiling/sampling/live_collector/widgets.py new file mode 100644 index 00000000000..86d2649f875 --- /dev/null +++ b/Lib/profiling/sampling/live_collector/widgets.py @@ -0,0 +1,1090 @@ +"""Widget classes for the live profiling collector UI.""" + +import curses +import time +from abc import ABC, abstractmethod + +from .constants import ( + TOP_FUNCTIONS_DISPLAY_COUNT, + MIN_FUNC_NAME_WIDTH, + MAX_FUNC_NAME_WIDTH, + WIDTH_THRESHOLD_SAMPLE_PCT, + WIDTH_THRESHOLD_TOTTIME, + WIDTH_THRESHOLD_CUMUL_PCT, + WIDTH_THRESHOLD_CUMTIME, + MICROSECONDS_PER_SECOND, + DISPLAY_UPDATE_INTERVAL_SEC, + MIN_BAR_WIDTH, + MAX_SAMPLE_RATE_BAR_WIDTH, + MAX_EFFICIENCY_BAR_WIDTH, + MIN_SAMPLE_RATE_FOR_SCALING, + FOOTER_LINES, + FINISHED_BANNER_EXTRA_LINES, + OPCODE_PANEL_HEIGHT, +) +from ..constants import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_UNKNOWN, + THREAD_STATUS_GIL_REQUESTED, + PROFILING_MODE_CPU, + PROFILING_MODE_GIL, + PROFILING_MODE_WALL, +) +from ..opcode_utils import get_opcode_info, format_opcode + + +class Widget(ABC): + """Base class for UI widgets.""" + + def __init__(self, display, colors): + """ + Initialize widget. + + Args: + display: DisplayInterface implementation + colors: Dictionary of color attributes + """ + self.display = display + self.colors = colors + + @abstractmethod + def render(self, line, width, **kwargs): + """ + Render the widget starting at the given line. + + Args: + line: Starting line number + width: Available width + **kwargs: Additional rendering parameters + + Returns: + Next available line number after rendering + """ + pass + + def add_str(self, line, col, text, attr=0): + """Add a string to the display at the specified position.""" + self.display.add_str(line, col, text, attr) + + +class ProgressBarWidget(Widget): + """Reusable progress bar widget.""" + + def render(self, line, width, **kwargs): + """Render is not used for progress bars - use render_bar instead.""" + raise NotImplementedError("Use render_bar method instead") + + def render_bar( + self, filled, total, max_width, fill_char="█", empty_char="░" + ): + """ + Render a progress bar and return the bar string and its length. + + Args: + filled: Current filled amount + total: Total amount (max value) + max_width: Maximum width for the bar + fill_char: Character to use for filled portion + empty_char: Character to use for empty portion + + Returns: + Tuple of (bar_string, bar_length) + """ + bar_width = min(max_width, max_width) + normalized = min(filled / max(total, 1), 1.0) + bar_fill = int(normalized * bar_width) + + bar = "[" + for i in range(bar_width): + if i < bar_fill: + bar += fill_char + else: + bar += empty_char + bar += "]" + return bar, len(bar) + + +class HeaderWidget(Widget): + """Widget for rendering the header section (lines 0-8).""" + + def __init__(self, display, colors, collector): + """ + Initialize header widget. + + Args: + display: DisplayInterface implementation + colors: Dictionary of color attributes + collector: Reference to LiveStatsCollector for accessing stats + """ + super().__init__(display, colors) + self.collector = collector + self.progress_bar = ProgressBarWidget(display, colors) + + def render(self, line, width, **kwargs): + """ + Render the complete header section. + + Args: + line: Starting line number + width: Available width + kwargs: Must contain 'elapsed' key + + Returns: + Next available line number + """ + elapsed = kwargs["elapsed"] + + line = self.draw_header_info(line, width, elapsed) + line = self.draw_sample_stats(line, width, elapsed) + line = self.draw_efficiency_bar(line, width) + line = self.draw_thread_status(line, width) + line = self.draw_function_stats( + line, width, kwargs.get("stats_list", []) + ) + line = self.draw_top_functions( + line, width, kwargs.get("stats_list", []) + ) + + # Show prominent finished banner if profiling is complete + if self.collector.finished: + line = self.draw_finished_banner(line, width) + + # Separator + A_DIM = self.display.get_attr("A_DIM") + separator = "─" * (width - 1) + self.add_str(line, 0, separator[: width - 1], A_DIM) + line += 1 + + return line + + def format_uptime(self, elapsed): + """Format elapsed time as uptime string.""" + uptime_sec = int(elapsed) + hours = uptime_sec // 3600 + minutes = (uptime_sec % 3600) // 60 + seconds = uptime_sec % 60 + if hours > 0: + return f"{hours}h{minutes:02d}m{seconds:02d}s" + else: + return f"{minutes}m{seconds:02d}s" + + def draw_header_info(self, line, width, elapsed): + """Draw the header information line with PID, uptime, time, and interval.""" + # Draw title + A_BOLD = self.display.get_attr("A_BOLD") + title = "Tachyon Profiler" + self.add_str(line, 0, title, A_BOLD | self.colors["cyan"]) + line += 1 + + current_time = self.collector.current_time_display + uptime = self.format_uptime(elapsed) + + # Calculate display refresh rate + refresh_hz = ( + 1.0 / self.collector.display_update_interval_sec if self.collector.display_update_interval_sec > 0 else 0 + ) + + # Get current view mode and thread display + if self.collector.view_mode == "ALL": + thread_name = "ALL" + thread_color = self.colors["green"] + else: + # PER_THREAD mode + if self.collector.current_thread_index < len( + self.collector.thread_ids + ): + thread_id = self.collector.thread_ids[ + self.collector.current_thread_index + ] + num_threads = len(self.collector.thread_ids) + thread_name = f"{thread_id} ({self.collector.current_thread_index + 1}/{num_threads})" + thread_color = self.colors["magenta"] + else: + thread_name = "ALL" + thread_color = self.colors["green"] + + header_parts = [ + ("PID: ", curses.A_BOLD), + (f"{self.collector.pid}", self.colors["cyan"]), + (" │ ", curses.A_DIM), + ("Thread: ", curses.A_BOLD), + (thread_name, thread_color), + (" │ ", curses.A_DIM), + ("Uptime: ", curses.A_BOLD), + (uptime, self.colors["green"]), + (" │ ", curses.A_DIM), + ("Time: ", curses.A_BOLD), + (current_time, self.colors["yellow"]), + (" │ ", curses.A_DIM), + ("Interval: ", curses.A_BOLD), + ( + f"{self.collector.sample_interval_usec}µs", + self.colors["magenta"], + ), + (" │ ", curses.A_DIM), + ("Display: ", curses.A_BOLD), + (f"{refresh_hz:.1f}Hz", self.colors["cyan"]), + ] + + col = 0 + for text, attr in header_parts: + if col < width - 1: + self.add_str(line, col, text, attr) + col += len(text) + return line + 1 + + def format_rate_with_units(self, rate_hz): + """Format a rate in Hz with appropriate units (Hz, KHz, MHz).""" + if rate_hz >= MICROSECONDS_PER_SECOND: + return f"{rate_hz / MICROSECONDS_PER_SECOND:.1f}MHz" + elif rate_hz >= 1_000: + return f"{rate_hz / 1_000:.1f}KHz" + else: + return f"{rate_hz:.1f}Hz" + + def draw_sample_stats(self, line, width, elapsed): + """Draw sample statistics with visual progress bar.""" + sample_rate = ( + self.collector.total_samples / elapsed if elapsed > 0 else 0 + ) + + # Update max sample rate + if sample_rate > self.collector.max_sample_rate: + self.collector.max_sample_rate = sample_rate + + col = 0 + self.add_str(line, col, "Samples: ", curses.A_BOLD) + col += 9 + self.add_str( + line, + col, + f"{self.collector.total_samples:>8}", + self.colors["cyan"], + ) + col += 8 + self.add_str( + line, col, f" total ({sample_rate:>7.1f}/s) ", curses.A_NORMAL + ) + col += 23 + + # Draw sample rate bar + target_rate = ( + MICROSECONDS_PER_SECOND / self.collector.sample_interval_usec + ) + + # Show current/target ratio with percentage + if sample_rate > 0 and target_rate > 0: + percentage = min((sample_rate / target_rate) * 100, 100) + current_formatted = self.format_rate_with_units(sample_rate) + target_formatted = self.format_rate_with_units(target_rate) + + if percentage >= 99.5: # Show 100% when very close + rate_label = f" {current_formatted}/{target_formatted} (100%)" + else: + rate_label = f" {current_formatted}/{target_formatted} ({percentage:>4.1f}%)" + else: + target_formatted = self.format_rate_with_units(target_rate) + rate_label = f" target: {target_formatted}" + + available_width = width - col - len(rate_label) - 3 + + if available_width >= MIN_BAR_WIDTH: + bar_width = min(MAX_SAMPLE_RATE_BAR_WIDTH, available_width) + # Use target rate as the reference, with a minimum for scaling + reference_rate = max(target_rate, MIN_SAMPLE_RATE_FOR_SCALING) + normalized_rate = min(sample_rate / reference_rate, 1.0) + bar_fill = int(normalized_rate * bar_width) + + bar = "[" + for i in range(bar_width): + bar += "█" if i < bar_fill else "░" + bar += "]" + self.add_str(line, col, bar, self.colors["green"]) + col += len(bar) + + if col + len(rate_label) < width - 1: + self.add_str(line, col + 1, rate_label, curses.A_DIM) + return line + 1 + + def draw_efficiency_bar(self, line, width): + """Draw sample efficiency bar showing success/failure rates.""" + # total_samples = successful_samples + failed_samples, so percentages add to 100% + total = max(1, self.collector.total_samples) + success_pct = (self.collector.successful_samples / total) * 100 + failed_pct = (self.collector.failed_samples / total) * 100 + + col = 0 + self.add_str(line, col, "Efficiency:", curses.A_BOLD) + col += 11 + + label = f" {success_pct:>5.2f}% good, {failed_pct:>5.2f}% failed" + available_width = width - col - len(label) - 3 + + if available_width >= MIN_BAR_WIDTH: + bar_width = min(MAX_EFFICIENCY_BAR_WIDTH, available_width) + success_fill = int((self.collector.successful_samples / total) * bar_width) + failed_fill = bar_width - success_fill + + self.add_str(line, col, "[", curses.A_NORMAL) + col += 1 + if success_fill > 0: + self.add_str( + line, col, "█" * success_fill, self.colors["green"] + ) + col += success_fill + if failed_fill > 0: + self.add_str(line, col, "█" * failed_fill, self.colors["red"]) + col += failed_fill + self.add_str(line, col, "]", curses.A_NORMAL) + col += 1 + + self.add_str(line, col + 1, label, curses.A_NORMAL) + return line + 1 + + def _add_percentage_stat( + self, line, col, value, label, color, add_separator=False + ): + """Add a percentage stat to the display. + + Args: + line: Line number + col: Starting column + value: Percentage value + label: Label text + color: Color attribute + add_separator: Whether to add separator before the stat + + Returns: + Updated column position + """ + if add_separator: + self.add_str(line, col, " │ ", curses.A_DIM) + col += 3 + + self.add_str(line, col, f"{value:>4.1f}", color) + col += 4 + self.add_str(line, col, f"% {label}", curses.A_NORMAL) + col += len(label) + 2 + + return col + + def draw_thread_status(self, line, width): + """Draw thread status statistics and GC information.""" + # Get status counts for current view mode + thread_data = self.collector._get_current_thread_data() + status_counts = thread_data.as_status_dict() if thread_data else self.collector.thread_status_counts + + # Calculate percentages + total_threads = max(1, status_counts["total"]) + pct_on_gil = (status_counts["has_gil"] / total_threads) * 100 + pct_off_gil = 100.0 - pct_on_gil + pct_gil_requested = (status_counts["gil_requested"] / total_threads) * 100 + pct_exception = (status_counts.get("has_exception", 0) / total_threads) * 100 + + # Get GC percentage based on view mode + if thread_data: + total_samples = max(1, thread_data.sample_count) + pct_gc = (thread_data.gc_frame_samples / total_samples) * 100 + else: + # Use total_samples for GC percentage since gc_frame_samples is tracked + # across ALL samples (via thread status), not just successful ones + total_samples = max(1, self.collector.total_samples) + pct_gc = (self.collector.gc_frame_samples / total_samples) * 100 + + col = 0 + self.add_str(line, col, "Threads: ", curses.A_BOLD) + col += 11 + + # Show GIL stats only if mode is not GIL (GIL mode filters to only GIL holders) + if self.collector.mode != PROFILING_MODE_GIL: + col = self._add_percentage_stat( + line, col, pct_on_gil, "on gil", self.colors["green"] + ) + col = self._add_percentage_stat( + line, + col, + pct_off_gil, + "off gil", + self.colors["red"], + add_separator=True, + ) + + # Show "waiting for gil" only if mode is not GIL + if self.collector.mode != PROFILING_MODE_GIL and col < width - 30: + col = self._add_percentage_stat( + line, + col, + pct_gil_requested, + "waiting for gil", + self.colors["yellow"], + add_separator=True, + ) + + # Show exception stats + if col < width - 15: + col = self._add_percentage_stat( + line, + col, + pct_exception, + "exc", + self.colors["red"], + add_separator=(col > 11), + ) + + # Always show GC stats + if col < width - 15: + col = self._add_percentage_stat( + line, + col, + pct_gc, + "GC", + self.colors["magenta"], + add_separator=(col > 11), + ) + + return line + 1 + + def draw_function_stats(self, line, width, stats_list): + """Draw function statistics summary.""" + result_set = self.collector._get_current_result_source() + total_funcs = len(result_set) + funcs_shown = len(stats_list) + executing_funcs = sum( + 1 for f in result_set.values() if f.get("direct_calls", 0) > 0 + ) + stack_only = total_funcs - executing_funcs + + col = 0 + self.add_str(line, col, "Functions: ", curses.A_BOLD) + col += 11 + self.add_str(line, col, f"{total_funcs:>5}", self.colors["cyan"]) + col += 5 + self.add_str(line, col, " total", curses.A_NORMAL) + col += 6 + + if col < width - 25: + self.add_str(line, col, " │ ", curses.A_DIM) + col += 3 + self.add_str( + line, col, f"{executing_funcs:>5}", self.colors["green"] + ) + col += 5 + self.add_str(line, col, " exec", curses.A_NORMAL) + col += 5 + + if col < width - 25: + self.add_str(line, col, " │ ", curses.A_DIM) + col += 3 + self.add_str(line, col, f"{stack_only:>5}", self.colors["yellow"]) + col += 5 + self.add_str(line, col, " stack", curses.A_NORMAL) + col += 6 + + if col < width - 20: + self.add_str(line, col, " │ ", curses.A_DIM) + col += 3 + self.add_str( + line, col, f"{funcs_shown:>5}", self.colors["magenta"] + ) + col += 5 + self.add_str(line, col, " shown", curses.A_NORMAL) + return line + 1 + + def draw_top_functions(self, line, width, stats_list): + """Draw top N hottest functions.""" + col = 0 + self.add_str( + line, + col, + f"Top {TOP_FUNCTIONS_DISPLAY_COUNT}: ", + curses.A_BOLD, + ) + col += 11 + + top_by_samples = sorted( + stats_list, key=lambda x: x["direct_calls"], reverse=True + ) + emojis = ["🥇", "🥈", "🥉"] + medal_colors = [ + self.colors["red"], + self.colors["yellow"], + self.colors["green"], + ] + + displayed = 0 + for func_data in top_by_samples: + if displayed >= TOP_FUNCTIONS_DISPLAY_COUNT: + break + if col >= width - 20: + break + if func_data["direct_calls"] == 0: + continue + + func_name = func_data["func"][2] + func_pct = func_data["sample_pct"] + + # Medal emoji + if col + 3 < width - 15: + self.add_str( + line, col, emojis[displayed] + " ", medal_colors[displayed] + ) + col += 3 + + # Function name (truncate to fit) + available_for_name = width - col - 15 + max_name_len = min(25, max(5, available_for_name)) + if len(func_name) > max_name_len: + func_name = func_name[: max_name_len - 3] + "..." + + if col + len(func_name) < width - 10: + self.add_str(line, col, func_name, medal_colors[displayed]) + col += len(func_name) + + pct_str = ( + f" ({func_pct:.1f}%)" + if func_pct >= 0.1 + else f" ({func_data['direct_calls']})" + ) + self.add_str(line, col, pct_str, curses.A_DIM) + col += len(pct_str) + + displayed += 1 + + if displayed < 3 and col < width - 30: + self.add_str(line, col, " │ ", curses.A_DIM) + col += 3 + + if displayed == 0 and col < width - 25: + self.add_str(line, col, "(collecting samples...)", curses.A_DIM) + + return line + 1 + + def draw_finished_banner(self, line, width): + """Draw a prominent banner when profiling is finished.""" + A_REVERSE = self.display.get_attr("A_REVERSE") + A_BOLD = self.display.get_attr("A_BOLD") + + # Add blank line for separation + line += 1 + + # Create the banner message + message = " ✓ PROFILING COMPLETE - Final Results Below - Press 'q' to Quit " + + # Center the message and fill the width with reverse video + if len(message) < width - 1: + padding_total = width - len(message) - 1 + padding_left = padding_total // 2 + padding_right = padding_total - padding_left + full_message = " " * padding_left + message + " " * padding_right + else: + full_message = message[: width - 1] + + # Draw the banner with reverse video and bold + self.add_str( + line, 0, full_message, A_REVERSE | A_BOLD | self.colors["green"] + ) + line += 1 + + # Add blank line for separation + line += 1 + + return line + + +class TableWidget(Widget): + """Widget for rendering column headers and data rows.""" + + def __init__(self, display, colors, collector): + """ + Initialize table widget. + + Args: + display: DisplayInterface implementation + colors: Dictionary of color attributes + collector: Reference to LiveStatsCollector for accessing stats + """ + super().__init__(display, colors) + self.collector = collector + + def render(self, line, width, **kwargs): + """ + Render column headers and data rows. + + Args: + line: Starting line number + width: Available width + kwargs: Must contain 'height' and 'stats_list' keys + + Returns: + Next available line number + """ + height = kwargs["height"] + stats_list = kwargs["stats_list"] + + # Draw column headers + line, show_sample_pct, show_tottime, show_cumul_pct, show_cumtime = ( + self.draw_column_headers(line, width) + ) + column_flags = ( + show_sample_pct, + show_tottime, + show_cumul_pct, + show_cumtime, + ) + + # Draw data rows + line = self.draw_stats_rows( + line, height, width, stats_list, column_flags + ) + + return line + + def draw_column_headers(self, line, width): + """Draw column headers with sort indicators.""" + # Determine which columns to show based on width + show_sample_pct = width >= WIDTH_THRESHOLD_SAMPLE_PCT + show_tottime = width >= WIDTH_THRESHOLD_TOTTIME + show_cumul_pct = width >= WIDTH_THRESHOLD_CUMUL_PCT + show_cumtime = width >= WIDTH_THRESHOLD_CUMTIME + + sorted_header = self.colors["sorted_header"] + normal_header = self.colors["normal_header"] + + # Determine which column is sorted + sort_col = { + "nsamples": 0, + "sample_pct": 1, + "tottime": 2, + "cumul_pct": 3, + "cumtime": 4, + }.get(self.collector.sort_by, -1) + + # Build the full header line first, then draw it + # This avoids gaps between columns when using reverse video + header_parts = [] + col = 0 + + # Column 0: nsamples + text = f"{'▼nsamples' if sort_col == 0 else 'nsamples':>13} " + header_parts.append((col, text, sorted_header if sort_col == 0 else normal_header)) + col += 15 + + # Column 1: sample % + if show_sample_pct: + text = f"{'▼%' if sort_col == 1 else '%':>5} " + header_parts.append((col, text, sorted_header if sort_col == 1 else normal_header)) + col += 7 + + # Column 2: tottime + if show_tottime: + text = f"{'▼tottime' if sort_col == 2 else 'tottime':>10} " + header_parts.append((col, text, sorted_header if sort_col == 2 else normal_header)) + col += 12 + + # Column 3: cumul % + if show_cumul_pct: + text = f"{'▼%' if sort_col == 3 else '%':>5} " + header_parts.append((col, text, sorted_header if sort_col == 3 else normal_header)) + col += 7 + + # Column 4: cumtime + if show_cumtime: + text = f"{'▼cumtime' if sort_col == 4 else 'cumtime':>10} " + header_parts.append((col, text, sorted_header if sort_col == 4 else normal_header)) + col += 12 + + # Remaining headers + if col < width - 15: + remaining_space = width - col - 1 + func_width = min( + MAX_FUNC_NAME_WIDTH, + max(MIN_FUNC_NAME_WIDTH, remaining_space // 2), + ) + text = f"{'function':<{func_width}} " + header_parts.append((col, text, normal_header)) + col += func_width + 2 + + if col < width - 10: + file_text = "file:line" + padding = width - col - len(file_text) + text = file_text + " " * max(0, padding) + header_parts.append((col, text, normal_header)) + + # Draw full-width background first + self.add_str(line, 0, " " * (width - 1), normal_header) + + # Draw each header part on top + for col_pos, text, attr in header_parts: + self.add_str(line, col_pos, text.rstrip(), attr) + + return ( + line + 1, + show_sample_pct, + show_tottime, + show_cumul_pct, + show_cumtime, + ) + + def draw_stats_rows(self, line, height, width, stats_list, column_flags): + """Draw the statistics data rows.""" + show_sample_pct, show_tottime, show_cumul_pct, show_cumtime = ( + column_flags + ) + + # Get color attributes + color_file = self.colors.get("color_file", curses.A_NORMAL) + color_func = self.colors.get("color_func", curses.A_NORMAL) + + # Get trend tracker for color decisions + trend_tracker = self.collector._trend_tracker + + # Check if opcode mode is enabled for row selection highlighting + show_opcodes = getattr(self.collector, 'show_opcodes', False) + selected_row = getattr(self.collector, 'selected_row', 0) + scroll_offset = getattr(self.collector, 'scroll_offset', 0) if show_opcodes else 0 + A_REVERSE = self.display.get_attr("A_REVERSE") + A_BOLD = self.display.get_attr("A_BOLD") + + # Reserve space for opcode panel when enabled + opcode_panel_height = OPCODE_PANEL_HEIGHT if show_opcodes else 0 + + # Apply scroll offset when in opcode mode + display_stats = stats_list[scroll_offset:] if show_opcodes else stats_list + + for row_idx, stat in enumerate(display_stats): + if line >= height - FOOTER_LINES - opcode_panel_height: + break + + func = stat["func"] + direct_calls = stat["direct_calls"] + cumulative_calls = stat["cumulative_calls"] + total_time = stat["total_time"] + cumulative_time = stat["cumulative_time"] + sample_pct = stat["sample_pct"] + cum_pct = stat["cumul_pct"] + trends = stat.get("trends", {}) + + # Check if this row is selected + is_selected = show_opcodes and row_idx == selected_row + + # Helper function to get trend color + def get_trend_color(column_name): + if is_selected: + return A_REVERSE | A_BOLD + trend = trends.get(column_name, "stable") + if trend_tracker is not None and trend_tracker.enabled: + return trend_tracker.get_color(trend) + return curses.A_NORMAL + + filename, lineno, funcname = func[0], func[1], func[2] + samples_str = f"{direct_calls}/{cumulative_calls}" + col = 0 + + # Fill entire row with reverse video background for selected row + if is_selected: + self.add_str(line, 0, " " * (width - 1), A_REVERSE | A_BOLD) + + # Show selection indicator when opcode panel is enabled + if show_opcodes: + if is_selected: + self.add_str(line, col, "►", A_REVERSE | A_BOLD) + else: + self.add_str(line, col, " ", curses.A_NORMAL) + col += 2 + + # Samples column - apply trend color based on nsamples trend + nsamples_color = get_trend_color("nsamples") + self.add_str(line, col, f"{samples_str:>13} ", nsamples_color) + col += 15 + + # Sample % column + if show_sample_pct: + sample_pct_color = get_trend_color("sample_pct") + self.add_str(line, col, f"{sample_pct:>5.1f} ", sample_pct_color) + col += 7 + + # Total time column + if show_tottime: + tottime_color = get_trend_color("tottime") + self.add_str(line, col, f"{total_time:>10.3f} ", tottime_color) + col += 12 + + # Cumul % column + if show_cumul_pct: + cumul_pct_color = get_trend_color("cumul_pct") + self.add_str(line, col, f"{cum_pct:>5.1f} ", cumul_pct_color) + col += 7 + + # Cumul time column + if show_cumtime: + cumtime_color = get_trend_color("cumtime") + self.add_str(line, col, f"{cumulative_time:>10.3f} ", cumtime_color) + col += 12 + + # Function name column + if col < width - 15: + remaining_space = width - col - 1 + func_width = min( + MAX_FUNC_NAME_WIDTH, + max(MIN_FUNC_NAME_WIDTH, remaining_space // 2), + ) + + func_display = funcname + if len(funcname) > func_width: + func_display = funcname[: func_width - 3] + "..." + func_display = f"{func_display:<{func_width}}" + func_color = A_REVERSE | A_BOLD if is_selected else color_func + self.add_str(line, col, func_display, func_color) + col += func_width + 2 + + # File:line column + if col < width - 10: + simplified_path = self.collector.simplify_path(filename) + file_line = f"{simplified_path}:{lineno}" + remaining_width = width - col - 1 + file_color = A_REVERSE | A_BOLD if is_selected else color_file + self.add_str( + line, col, file_line[:remaining_width], file_color + ) + + line += 1 + + return line + + +class FooterWidget(Widget): + """Widget for rendering the footer section (legend and controls).""" + + def __init__(self, display, colors, collector): + """ + Initialize footer widget. + + Args: + display: DisplayInterface implementation + colors: Dictionary of color attributes + collector: Reference to LiveStatsCollector for accessing state + """ + super().__init__(display, colors) + self.collector = collector + + def render(self, line, width, **kwargs): + """ + Render the footer at the specified position. + + Args: + line: Starting line number (should be height - 2) + width: Available width + + Returns: + Next available line number + """ + A_DIM = self.display.get_attr("A_DIM") + A_BOLD = self.display.get_attr("A_BOLD") + + # Legend line + legend = "nsamples: direct/cumulative (direct=executing, cumulative=on stack)" + self.add_str(line, 0, legend[: width - 1], A_DIM) + line += 1 + + # Controls line with status + sort_names = { + "tottime": "Total Time", + "nsamples": "Direct Samples", + "cumtime": "Cumulative Time", + "sample_pct": "Sample %", + "cumul_pct": "Cumulative %", + } + sort_display = sort_names.get( + self.collector.sort_by, self.collector.sort_by + ) + + # Build status indicators + status = [] + if self.collector.finished: + status.append("[PROFILING FINISHED - Press 'q' to quit]") + elif self.collector.paused: + status.append("[PAUSED]") + if self.collector.filter_pattern: + status.append( + f"[Filter: {self.collector.filter_pattern} (c to clear)]" + ) + # Show trend colors status if disabled + if self.collector._trend_tracker is not None and not self.collector._trend_tracker.enabled: + status.append("[Trend colors: OFF]") + status_str = " ".join(status) + " " if status else "" + + if self.collector.finished: + footer = f"{status_str}" + else: + footer = f"{status_str}Sort: {sort_display} | 't':mode 'x':trends ←→:thread 'h':help 'q':quit" + self.add_str( + line, + 0, + footer[: width - 1], + A_BOLD + if (self.collector.paused or self.collector.finished) + else A_DIM, + ) + + return line + 1 + + def render_filter_input_prompt(self, line, width): + """Draw the filter input prompt at the bottom of the screen.""" + A_BOLD = self.display.get_attr("A_BOLD") + A_REVERSE = self.display.get_attr("A_REVERSE") + + # Draw prompt on last line + prompt = f"Function filter: {self.collector.filter_input_buffer}_" + self.add_str(line, 0, prompt[: width - 1], A_REVERSE | A_BOLD) + + +class HelpWidget(Widget): + """Widget for rendering the help screen overlay.""" + + def render(self, line, width, **kwargs): + """ + Render the help screen. + + Args: + line: Starting line number (ignored, help is centered) + width: Available width + kwargs: Must contain 'height' key + + Returns: + Next available line number (not used for overlays) + """ + height = kwargs["height"] + A_BOLD = self.display.get_attr("A_BOLD") + A_NORMAL = self.display.get_attr("A_NORMAL") + + help_lines = [ + ("Tachyon Profiler - Interactive Commands", A_BOLD), + ("", A_NORMAL), + ("Navigation & Display:", A_BOLD), + (" s - Cycle through sort modes (forward)", A_NORMAL), + (" S - Cycle through sort modes (backward)", A_NORMAL), + (" t - Toggle view mode (ALL / per-thread)", A_NORMAL), + (" x - Toggle trend colors (on/off)", A_NORMAL), + (" j/k or ↑/↓ - Select next/previous function (--opcodes)", A_NORMAL), + (" ← / → - Cycle through threads", A_NORMAL), + (" + - Faster display refresh rate", A_NORMAL), + (" - - Slower display refresh rate", A_NORMAL), + ("", A_NORMAL), + ("Control:", A_BOLD), + (" p - Freeze display (snapshot)", A_NORMAL), + (" r - Reset all statistics", A_NORMAL), + ("", A_NORMAL), + ("Filtering:", A_BOLD), + (" / - Enter function filter (substring)", A_NORMAL), + (" c - Clear filter", A_NORMAL), + (" ESC - Cancel filter input", A_NORMAL), + ("", A_NORMAL), + ("Other:", A_BOLD), + (" h or ? - Show/hide this help", A_NORMAL), + (" q - Quit profiler", A_NORMAL), + ("", A_NORMAL), + ("Press any key to close this help screen", A_BOLD), + ] + + start_line = (height - len(help_lines)) // 2 + for i, (text, attr) in enumerate(help_lines): + if start_line + i < height - 1: + col = 2 # Left-align with small margin + self.add_str(start_line + i, col, text[: width - 3], attr) + + return line # Not used for overlays + + +class OpcodePanel(Widget): + """Widget for displaying opcode statistics for a selected function.""" + + def __init__(self, display, colors, collector): + super().__init__(display, colors) + self.collector = collector + + def render(self, line, width, **kwargs): + """Render opcode statistics panel. + + Args: + line: Starting line number + width: Available width + kwargs: Must contain 'stats_list', 'height' + + Returns: + Next available line number + """ + stats_list = kwargs.get("stats_list", []) + height = kwargs.get("height", 24) + selected_row = self.collector.selected_row + scroll_offset = getattr(self.collector, 'scroll_offset', 0) + + A_BOLD = self.display.get_attr("A_BOLD") + A_NORMAL = self.display.get_attr("A_NORMAL") + color_cyan = self.colors.get("color_cyan", A_NORMAL) + color_yellow = self.colors.get("color_yellow", A_NORMAL) + color_magenta = self.colors.get("color_magenta", A_NORMAL) + + # Get the selected function from stats_list (accounting for scroll) + actual_index = scroll_offset + selected_row + if not stats_list or actual_index >= len(stats_list): + self.add_str(line, 0, "No function selected (use j/k to select)", A_NORMAL) + return line + 1 + + selected_stat = stats_list[actual_index] + func = selected_stat["func"] + filename, lineno, funcname = func + + # Get opcode stats for this function + opcode_stats = self.collector.opcode_stats.get(func, {}) + + if not opcode_stats: + self.add_str(line, 0, f"No opcode data for {funcname}() (requires --opcodes)", A_NORMAL) + return line + 1 + + # Sort opcodes by count + sorted_opcodes = sorted(opcode_stats.items(), key=lambda x: -x[1]) + total_opcode_samples = sum(opcode_stats.values()) + + # Draw header + header = f"─── Opcodes for {funcname}() " + header += "─" * max(0, width - len(header) - 1) + self.add_str(line, 0, header[:width-1], color_cyan | A_BOLD) + line += 1 + + # Calculate max samples for bar scaling + max_count = sorted_opcodes[0][1] if sorted_opcodes else 1 + + # Draw opcode rows (limit to available space) + max_rows = min(8, height - line - 3) # Leave room for footer + bar_width = 20 + + for i, (opcode_num, count) in enumerate(sorted_opcodes[:max_rows]): + if line >= height - 3: + break + + opcode_info = get_opcode_info(opcode_num) + is_specialized = opcode_info["is_specialized"] + name_display = format_opcode(opcode_num) + + pct = (count / total_opcode_samples * 100) if total_opcode_samples > 0 else 0 + + # Draw bar + bar_fill = int((count / max_count) * bar_width) if max_count > 0 else 0 + bar = "█" * bar_fill + "░" * (bar_width - bar_fill) + + # Format: [████████░░░░] LOAD_ATTR 45.2% (1234) + # Specialized opcodes shown in magenta, base opcodes in yellow + name_color = color_magenta if is_specialized else color_yellow + + row_text = f"[{bar}] {name_display:<35} {pct:>5.1f}% ({count:>6})" + self.add_str(line, 2, row_text[:width-3], name_color) + line += 1 + + # Show "..." if more opcodes exist + if len(sorted_opcodes) > max_rows: + remaining = len(sorted_opcodes) - max_rows + self.add_str(line, 2, f"... and {remaining} more opcodes", A_NORMAL) + line += 1 + + return line diff --git a/Lib/profiling/sampling/module_utils.py b/Lib/profiling/sampling/module_utils.py new file mode 100644 index 00000000000..dfde2b28ab2 --- /dev/null +++ b/Lib/profiling/sampling/module_utils.py @@ -0,0 +1,102 @@ +"""Utilities for extracting module names from file paths.""" + +import os +import site +import sys +from pathlib import Path + + +def get_python_path_info(): + """Get information about Python's search paths. + + Returns: + dict: Dictionary containing stdlib path, site-packages paths, and sys.path entries. + """ + info = { + 'stdlib': None, + 'site_packages': [], + 'sys_path': [] + } + + # Get standard library path from os module location + try: + if hasattr(os, '__file__') and os.__file__: + info['stdlib'] = Path(os.__file__).parent + except (AttributeError, OSError): + pass # Silently continue if we can't determine stdlib path + + # Get site-packages directories + site_packages = [] + try: + site_packages.extend(Path(p) for p in site.getsitepackages()) + except (AttributeError, OSError): + pass # Continue without site packages if unavailable + + # Get user site-packages + try: + user_site = site.getusersitepackages() + if user_site and Path(user_site).exists(): + site_packages.append(Path(user_site)) + except (AttributeError, OSError): + pass # Continue without user site packages + + info['site_packages'] = site_packages + info['sys_path'] = [Path(p) for p in sys.path if p] + + return info + + +def extract_module_name(filename, path_info): + """Extract Python module name and type from file path. + + Args: + filename: Path to the Python file + path_info: Dictionary from get_python_path_info() + + Returns: + tuple: (module_name, module_type) where module_type is one of: + 'stdlib', 'site-packages', 'project', or 'other' + """ + if not filename: + return ('unknown', 'other') + + try: + file_path = Path(filename) + except (ValueError, OSError): + return (str(filename), 'other') + + # Check if it's in stdlib + if path_info['stdlib'] and file_path.is_relative_to(path_info['stdlib']): + return (_path_to_module(file_path.relative_to(path_info['stdlib'])), 'stdlib') + + # Check site-packages + for site_pkg in path_info['site_packages']: + if file_path.is_relative_to(site_pkg): + return (_path_to_module(file_path.relative_to(site_pkg)), 'site-packages') + + # Check other sys.path entries (project files) + if not str(file_path).startswith(('<', '[')): # Skip special files + for path_entry in path_info['sys_path']: + if file_path.is_relative_to(path_entry): + return (_path_to_module(file_path.relative_to(path_entry)), 'project') + + # Fallback: just use the filename + return (_path_to_module(file_path), 'other') + + +def _path_to_module(path): + if isinstance(path, str): + path = Path(path) + + # Remove .py extension + if path.suffix == '.py': + path = path.with_suffix('') + + # Convert path separators to dots, stripping root/drive (e.g. "/" or "C:\") + parts = [p for p in path.parts if p != path.root and p != path.drive] + + # Handle __init__ files - they represent the package itself + if parts and parts[-1] == '__init__': + parts = parts[:-1] + + return '.'.join(parts) if parts else path.stem diff --git a/Lib/profiling/sampling/opcode_utils.py b/Lib/profiling/sampling/opcode_utils.py new file mode 100644 index 00000000000..71b35383da1 --- /dev/null +++ b/Lib/profiling/sampling/opcode_utils.py @@ -0,0 +1,94 @@ +"""Opcode utilities for bytecode-level profiler visualization. + +This module provides utilities to get opcode names and detect specialization +status using the opcode module's metadata. Used by heatmap and flamegraph +collectors to display which bytecode instructions are executing at each +source line, including Python's adaptive specialization optimizations. +""" + +import opcode + +# Build opcode name mapping: opcode number -> opcode name +# This includes both standard opcodes and specialized variants (Python 3.11+) +_OPCODE_NAMES = dict(enumerate(opcode.opname)) +if hasattr(opcode, "_specialized_opmap"): + for name, op in opcode._specialized_opmap.items(): + _OPCODE_NAMES[op] = name + +# Build deopt mapping: specialized opcode number -> base opcode number +# Python 3.11+ uses adaptive specialization where generic opcodes like +# LOAD_ATTR can be replaced at runtime with specialized variants like +# LOAD_ATTR_INSTANCE_VALUE. This mapping lets us show both forms. +_DEOPT_MAP = {} +if hasattr(opcode, "_specializations") and hasattr( + opcode, "_specialized_opmap" +): + for base_name, variant_names in opcode._specializations.items(): + base_opcode = opcode.opmap.get(base_name) + if base_opcode is not None: + for variant_name in variant_names: + variant_opcode = opcode._specialized_opmap.get(variant_name) + if variant_opcode is not None: + _DEOPT_MAP[variant_opcode] = base_opcode + + +def get_opcode_info(opcode_num): + """Get opcode name and specialization info from an opcode number. + + Args: + opcode_num: The opcode number (0-255 or higher for specialized) + + Returns: + A dict with keys: + - 'opname': The opcode name (e.g., 'LOAD_ATTR_INSTANCE_VALUE') + - 'base_opname': The base opcode name (e.g., 'LOAD_ATTR') + - 'is_specialized': True if this is a specialized instruction + """ + opname = _OPCODE_NAMES.get(opcode_num) + if opname is None: + return { + "opname": f"<{opcode_num}>", + "base_opname": f"<{opcode_num}>", + "is_specialized": False, + } + + base_opcode = _DEOPT_MAP.get(opcode_num) + if base_opcode is not None: + base_opname = _OPCODE_NAMES.get(base_opcode, f"<{base_opcode}>") + return { + "opname": opname, + "base_opname": base_opname, + "is_specialized": True, + } + + return { + "opname": opname, + "base_opname": opname, + "is_specialized": False, + } + + +def format_opcode(opcode_num): + """Format an opcode for display, showing base opcode for specialized ones. + + Args: + opcode_num: The opcode number (0-255 or higher for specialized) + + Returns: + A formatted string like 'LOAD_ATTR' or 'LOAD_ATTR_INSTANCE_VALUE (LOAD_ATTR)' + """ + info = get_opcode_info(opcode_num) + if info["is_specialized"]: + return f"{info['opname']} ({info['base_opname']})" + return info["opname"] + + +def get_opcode_mapping(): + """Get opcode name and deopt mappings for JavaScript consumption. + + Returns: + A dict with keys: + - 'names': Dict mapping opcode numbers to opcode names + - 'deopt': Dict mapping specialized opcode numbers to base opcode numbers + """ + return {"names": _OPCODE_NAMES, "deopt": _DEOPT_MAP} diff --git a/Lib/profiling/sampling/pstats_collector.py b/Lib/profiling/sampling/pstats_collector.py new file mode 100644 index 00000000000..0f31d93582b --- /dev/null +++ b/Lib/profiling/sampling/pstats_collector.py @@ -0,0 +1,429 @@ +import collections +import marshal +import pstats +lazy from _colorize import get_colors + +from .collector import Collector, extract_lineno +from .constants import MICROSECONDS_PER_SECOND, PROFILING_MODE_CPU + + +class PstatsCollector(Collector): + aggregating = True + + def __init__(self, sample_interval_usec, *, skip_idle=False): + self.result = collections.defaultdict( + lambda: dict(total_rec_calls=0, direct_calls=0, cumulative_calls=0) + ) + self.stats = {} + self.sample_interval_usec = sample_interval_usec + self.callers = collections.defaultdict( + lambda: collections.defaultdict(int) + ) + self.skip_idle = skip_idle + self._seen_locations = set() + + def _process_frames(self, frames, weight=1): + """Process a single thread's frame stack.""" + if not frames: + return + + self._seen_locations.clear() + + # Process each frame in the stack to track cumulative calls + # frame.location is int, tuple (lineno, end_lineno, col_offset, end_col_offset), or None + for frame in frames: + lineno = extract_lineno(frame.location) + location = (frame.filename, lineno, frame.funcname) + if location not in self._seen_locations: + self._seen_locations.add(location) + self.result[location]["cumulative_calls"] += weight + + # The top frame gets counted as an inline call (directly executing) + top_lineno = extract_lineno(frames[0].location) + top_location = (frames[0].filename, top_lineno, frames[0].funcname) + self.result[top_location]["direct_calls"] += weight + + # Track caller-callee relationships for call graph + for i in range(1, len(frames)): + callee_frame = frames[i - 1] + caller_frame = frames[i] + + callee_lineno = extract_lineno(callee_frame.location) + caller_lineno = extract_lineno(caller_frame.location) + callee = (callee_frame.filename, callee_lineno, callee_frame.funcname) + caller = (caller_frame.filename, caller_lineno, caller_frame.funcname) + + self.callers[callee][caller] += weight + + def collect(self, stack_frames, timestamps_us=None): + weight = len(timestamps_us) if timestamps_us else 1 + for frames, _ in self._iter_stacks(stack_frames, skip_idle=self.skip_idle): + self._process_frames(frames, weight=weight) + + def export(self, filename): + self.create_stats() + self._dump_stats(filename) + return True + + def _dump_stats(self, file): + stats_with_marker = dict(self.stats) + stats_with_marker[("__sampled__",)] = True + with open(file, "wb") as f: + marshal.dump(stats_with_marker, f) + + # Needed for compatibility with pstats.Stats + def create_stats(self): + sample_interval_sec = self.sample_interval_usec / MICROSECONDS_PER_SECOND + callers = {} + for fname, call_counts in self.result.items(): + total = call_counts["direct_calls"] * sample_interval_sec + cumulative_calls = call_counts["cumulative_calls"] + cumulative = cumulative_calls * sample_interval_sec + callers = dict(self.callers.get(fname, {})) + self.stats[fname] = ( + call_counts["direct_calls"], # cc = direct calls for sample percentage + cumulative_calls, # nc = cumulative calls for cumulative percentage + total, + cumulative, + callers, + ) + + def print_stats(self, sort=-1, limit=None, show_summary=True, mode=None): + """Print formatted statistics to stdout.""" + # Create stats object + stats = pstats.SampledStats(self).strip_dirs() + if not stats.stats: + print("No samples were collected.") + if mode == PROFILING_MODE_CPU: + print("This can happen in CPU mode when all threads are idle.") + return + + # Get the stats data + stats_list = [] + for func, ( + direct_calls, + cumulative_calls, + total_time, + cumulative_time, + callers, + ) in stats.stats.items(): + stats_list.append( + ( + func, + direct_calls, + cumulative_calls, + total_time, + cumulative_time, + callers, + ) + ) + + # Calculate total samples for percentage calculations (using direct_calls) + total_samples = sum( + direct_calls for _, direct_calls, _, _, _, _ in stats_list + ) + + # Sort based on the requested field + sort_field = sort + if sort_field == -1: # stdname + stats_list.sort(key=lambda x: str(x[0])) + elif sort_field == 0: # nsamples (direct samples) + stats_list.sort(key=lambda x: x[1], reverse=True) # direct_calls + elif sort_field == 1: # tottime + stats_list.sort(key=lambda x: x[3], reverse=True) # total_time + elif sort_field == 2: # cumtime + stats_list.sort(key=lambda x: x[4], reverse=True) # cumulative_time + elif sort_field == 3: # sample% + stats_list.sort( + key=lambda x: (x[1] / total_samples * 100) + if total_samples > 0 + else 0, + reverse=True, # direct_calls percentage + ) + elif sort_field == 4: # cumul% + stats_list.sort( + key=lambda x: (x[2] / total_samples * 100) + if total_samples > 0 + else 0, + reverse=True, # cumulative_calls percentage + ) + elif sort_field == 5: # nsamples (cumulative samples) + stats_list.sort(key=lambda x: x[2], reverse=True) # cumulative_calls + + # Apply limit if specified + if limit is not None: + stats_list = stats_list[:limit] + + # Determine the best unit for time columns based on maximum values + max_total_time = max( + (total_time for _, _, _, total_time, _, _ in stats_list), default=0 + ) + max_cumulative_time = max( + (cumulative_time for _, _, _, _, cumulative_time, _ in stats_list), + default=0, + ) + + total_time_unit, total_time_scale = self._determine_best_unit(max_total_time) + cumulative_time_unit, cumulative_time_scale = self._determine_best_unit( + max_cumulative_time + ) + + # Define column widths for consistent alignment + col_widths = { + "nsamples": 15, # "nsamples" column (inline/cumulative format) + "sample_pct": 8, # "sample%" column + "tottime": max(12, len(f"tottime ({total_time_unit})")), + "cum_pct": 8, # "cumul%" column + "cumtime": max(12, len(f"cumtime ({cumulative_time_unit})")), + } + + # Print header with colors and proper alignment + ANSIColors = get_colors() + + print(f"{ANSIColors.BOLD_BLUE}Profile Stats:{ANSIColors.RESET}") + + header_nsamples = f"{ANSIColors.BOLD_BLUE}{'nsamples':>{col_widths['nsamples']}}{ANSIColors.RESET}" + header_sample_pct = f"{ANSIColors.BOLD_BLUE}{'sample%':>{col_widths['sample_pct']}}{ANSIColors.RESET}" + header_tottime = f"{ANSIColors.BOLD_BLUE}{f'tottime ({total_time_unit})':>{col_widths['tottime']}}{ANSIColors.RESET}" + header_cum_pct = f"{ANSIColors.BOLD_BLUE}{'cumul%':>{col_widths['cum_pct']}}{ANSIColors.RESET}" + header_cumtime = f"{ANSIColors.BOLD_BLUE}{f'cumtime ({cumulative_time_unit})':>{col_widths['cumtime']}}{ANSIColors.RESET}" + header_filename = ( + f"{ANSIColors.BOLD_BLUE}filename:lineno(function){ANSIColors.RESET}" + ) + + print( + f"{header_nsamples} {header_sample_pct} {header_tottime} {header_cum_pct} {header_cumtime} {header_filename}" + ) + + # Print each line with proper alignment + for ( + func, + direct_calls, + cumulative_calls, + total_time, + cumulative_time, + callers, + ) in stats_list: + # Calculate percentages + sample_pct = ( + (direct_calls / total_samples * 100) if total_samples > 0 else 0 + ) + cum_pct = ( + (cumulative_calls / total_samples * 100) + if total_samples > 0 + else 0 + ) + + # Format values with proper alignment - always use A/B format + nsamples_str = f"{direct_calls}/{cumulative_calls}" + nsamples_str = f"{nsamples_str:>{col_widths['nsamples']}}" + sample_pct_str = f"{sample_pct:{col_widths['sample_pct']}.1f}" + tottime = f"{total_time * total_time_scale:{col_widths['tottime']}.3f}" + cum_pct_str = f"{cum_pct:{col_widths['cum_pct']}.1f}" + cumtime = f"{cumulative_time * cumulative_time_scale:{col_widths['cumtime']}.3f}" + + # Format the function name with colors + func_name = ( + f"{ANSIColors.GREEN}{func[0]}{ANSIColors.RESET}:" + f"{ANSIColors.YELLOW}{func[1]}{ANSIColors.RESET}(" + f"{ANSIColors.CYAN}{func[2]}{ANSIColors.RESET})" + ) + + # Print the formatted line with consistent spacing + print( + f"{nsamples_str} {sample_pct_str} {tottime} {cum_pct_str} {cumtime} {func_name}" + ) + + # Print legend + print(f"\n{ANSIColors.BOLD_BLUE}Legend:{ANSIColors.RESET}") + print( + f" {ANSIColors.YELLOW}nsamples{ANSIColors.RESET}: Direct/Cumulative samples (direct executing / on call stack)" + ) + print( + f" {ANSIColors.YELLOW}sample%{ANSIColors.RESET}: Percentage of total samples this function was directly executing" + ) + print( + f" {ANSIColors.YELLOW}tottime{ANSIColors.RESET}: Estimated total time spent directly in this function" + ) + print( + f" {ANSIColors.YELLOW}cumul%{ANSIColors.RESET}: Percentage of total samples when this function was on the call stack" + ) + print( + f" {ANSIColors.YELLOW}cumtime{ANSIColors.RESET}: Estimated cumulative time (including time in called functions)" + ) + print( + f" {ANSIColors.YELLOW}filename:lineno(function){ANSIColors.RESET}: Function location and name" + ) + + # Print summary of interesting functions if enabled + if show_summary and stats_list: + self._print_summary(stats_list, total_samples) + + @staticmethod + def _determine_best_unit(max_value): + """Determine the best unit (s, ms, μs) and scale factor for a maximum value.""" + if max_value >= 1.0: + return "s", 1.0 + elif max_value >= 0.001: + return "ms", 1000.0 + else: + return "μs", float(MICROSECONDS_PER_SECOND) + + def _print_summary(self, stats_list, total_samples): + """Print summary of interesting functions.""" + ANSIColors = get_colors() + + print( + f"\n{ANSIColors.BOLD_BLUE}Summary of Interesting Functions:{ANSIColors.RESET}" + ) + + # Aggregate stats by fully qualified function name (ignoring line numbers) + func_aggregated = {} + for ( + func, + direct_calls, + cumulative_calls, + total_time, + cumulative_time, + callers, + ) in stats_list: + # Use filename:function_name as the key to get fully qualified name + qualified_name = f"{func[0]}:{func[2]}" + if qualified_name not in func_aggregated: + func_aggregated[qualified_name] = [ + 0, + 0, + 0, + 0, + ] # direct_calls, cumulative_calls, total_time, cumulative_time + func_aggregated[qualified_name][0] += direct_calls + func_aggregated[qualified_name][1] += cumulative_calls + func_aggregated[qualified_name][2] += total_time + func_aggregated[qualified_name][3] += cumulative_time + + # Convert aggregated data back to list format for processing + aggregated_stats = [] + for qualified_name, ( + prim_calls, + total_calls, + total_time, + cumulative_time, + ) in func_aggregated.items(): + # Parse the qualified name back to filename and function name + if ":" in qualified_name: + filename, func_name = qualified_name.rsplit(":", 1) + else: + filename, func_name = "", qualified_name + # Create a dummy func tuple with filename and function name for display + dummy_func = (filename, "", func_name) + aggregated_stats.append( + ( + dummy_func, + prim_calls, + total_calls, + total_time, + cumulative_time, + {}, + ) + ) + + # Determine best units for summary metrics + max_total_time = max( + (total_time for _, _, _, total_time, _, _ in aggregated_stats), + default=0, + ) + max_cumulative_time = max( + ( + cumulative_time + for _, _, _, _, cumulative_time, _ in aggregated_stats + ), + default=0, + ) + + total_unit, total_scale = self._determine_best_unit(max_total_time) + cumulative_unit, cumulative_scale = self._determine_best_unit( + max_cumulative_time + ) + + def _format_func_name(func): + """Format function name with colors.""" + return ( + f"{ANSIColors.GREEN}{func[0]}{ANSIColors.RESET}:" + f"{ANSIColors.YELLOW}{func[1]}{ANSIColors.RESET}(" + f"{ANSIColors.CYAN}{func[2]}{ANSIColors.RESET})" + ) + + def _print_top_functions(stats_list, title, key_func, format_line, n=3): + """Print top N functions sorted by key_func with formatted output.""" + print(f"\n{ANSIColors.BOLD_BLUE}{title}:{ANSIColors.RESET}") + sorted_stats = sorted(stats_list, key=key_func, reverse=True) + for stat in sorted_stats[:n]: + if line := format_line(stat): + print(f" {line}") + + # Functions with highest direct/cumulative ratio (hot spots) + def format_hotspots(stat): + func, direct_calls, cumulative_calls, total_time, _, _ = stat + if direct_calls > 0 and cumulative_calls > 0: + ratio = direct_calls / cumulative_calls + direct_pct = ( + (direct_calls / total_samples * 100) + if total_samples > 0 + else 0 + ) + return ( + f"{ratio:.3f} direct/cumulative ratio, " + f"{direct_pct:.1f}% direct samples: {_format_func_name(func)}" + ) + return None + + _print_top_functions( + aggregated_stats, + "Functions with Highest Direct/Cumulative Ratio (Hot Spots)", + key_func=lambda x: (x[1] / x[2]) if x[2] > 0 else 0, + format_line=format_hotspots, + ) + + # Functions with highest call frequency (cumulative/direct difference) + def format_call_frequency(stat): + func, direct_calls, cumulative_calls, total_time, _, _ = stat + if cumulative_calls > direct_calls: + call_frequency = cumulative_calls - direct_calls + cum_pct = ( + (cumulative_calls / total_samples * 100) + if total_samples > 0 + else 0 + ) + return ( + f"{call_frequency:d} indirect calls, " + f"{cum_pct:.1f}% total stack presence: {_format_func_name(func)}" + ) + return None + + _print_top_functions( + aggregated_stats, + "Functions with Highest Call Frequency (Indirect Calls)", + key_func=lambda x: x[2] - x[1], # Sort by (cumulative - direct) + format_line=format_call_frequency, + ) + + # Functions with highest cumulative-to-direct multiplier (call magnification) + def format_call_magnification(stat): + func, direct_calls, cumulative_calls, total_time, _, _ = stat + if direct_calls > 0 and cumulative_calls > direct_calls: + multiplier = cumulative_calls / direct_calls + indirect_calls = cumulative_calls - direct_calls + return ( + f"{multiplier:.1f}x call magnification, " + f"{indirect_calls:d} indirect calls from {direct_calls:d} direct: {_format_func_name(func)}" + ) + return None + + _print_top_functions( + aggregated_stats, + "Functions with Highest Call Magnification (Cumulative/Direct)", + key_func=lambda x: (x[2] / x[1]) + if x[1] > 0 + else 0, # Sort by cumulative/direct ratio + format_line=format_call_magnification, + ) diff --git a/Lib/profiling/sampling/sample.py b/Lib/profiling/sampling/sample.py new file mode 100644 index 00000000000..702e00c87b9 --- /dev/null +++ b/Lib/profiling/sampling/sample.py @@ -0,0 +1,665 @@ +import _remote_debugging +import contextlib +import os +import statistics +import sys +import sysconfig +import time +from collections import deque +lazy from _colorize import get_colors + +from .pstats_collector import PstatsCollector +from .stack_collector import CollapsedStackCollector, FlamegraphCollector +from .heatmap_collector import HeatmapCollector +from .gecko_collector import GeckoCollector +from .binary_collector import BinaryCollector + + +@contextlib.contextmanager +def _pause_threads(unwinder, blocking): + """Context manager to pause/resume threads around sampling if blocking is True.""" + if blocking: + unwinder.pause_threads() + try: + yield + finally: + unwinder.resume_threads() + else: + yield + + +from .constants import ( + PROFILING_MODE_WALL, + PROFILING_MODE_CPU, + PROFILING_MODE_GIL, + PROFILING_MODE_ALL, + PROFILING_MODE_EXCEPTION, +) +from ._format_utils import fmt +try: + from .live_collector import LiveStatsCollector +except ImportError: + LiveStatsCollector = None + +_FREE_THREADED_BUILD = sysconfig.get_config_var("Py_GIL_DISABLED") is not None + +# Minimum number of samples required before showing the TUI +# If fewer samples are collected, we skip the TUI and just print a message +MIN_SAMPLES_FOR_TUI = 200 + +# Maximum number of consecutive identical samples to keep before flushing. +MAX_PENDING_SAMPLES = 8192 + + +def _resolve_python_pid(pid): + """On Windows, if pid is a venvlauncher process, return the child Python PID. + + The venvlauncher (used as python.exe in venvs) spawns the real Python + interpreter as a child process via CreateProcessW. The RemoteUnwinder + needs the child's PID, not the launcher's. + + Returns the original pid if not on Windows, not a venv launcher, + or no child process is found. + """ + if os.name != "nt" or sys.prefix == sys.base_prefix: + return pid + try: + children = _remote_debugging.get_child_pids(pid, recursive=False) + python_children = [ + child for child in children + if _remote_debugging.is_python_process(child) + ] + if len(python_children) == 1: + return python_children[0] + except (OSError, RuntimeError) as err: + raise SystemExit( + f"Failed to initialize profiler from virtualenv: {err}\n" + f"Try running with the base interpreter: {sys._base_executable}" + ) from err + return pid + + +class SampleProfiler: + def __init__(self, pid, sample_interval_usec, all_threads, *, mode=PROFILING_MODE_WALL, native=False, gc=True, opcodes=False, skip_non_matching_threads=True, collect_stats=False, blocking=False): + self.pid = _resolve_python_pid(pid) + self.sample_interval_usec = sample_interval_usec + self.all_threads = all_threads + self.mode = mode # Store mode for later use + self.collect_stats = collect_stats + self.blocking = blocking + try: + self.unwinder = self._new_unwinder(native, gc, opcodes, skip_non_matching_threads) + except RuntimeError as err: + raise SystemExit(err) from err + # Track sample intervals and total sample count + self.sample_intervals = deque(maxlen=100) + self.total_samples = 0 + self.realtime_stats = False + + def _new_unwinder(self, native, gc, opcodes, skip_non_matching_threads): + kwargs = {} + if _FREE_THREADED_BUILD or self.all_threads: + kwargs['all_threads'] = self.all_threads + else: + kwargs['only_active_thread'] = bool(self.all_threads) + + return _remote_debugging.RemoteUnwinder( + self.pid, + mode=self.mode, + native=native, + gc=gc, + opcodes=opcodes, + skip_non_matching_threads=skip_non_matching_threads, + cache_frames=True, + stats=self.collect_stats, + **kwargs + ) + + def _get_stack_trace(self, async_aware=None): + with _pause_threads(self.unwinder, self.blocking): + if async_aware == "all": + return self.unwinder.get_all_awaited_by() + if async_aware == "running": + return self.unwinder.get_async_stack_trace() + return self.unwinder.get_stack_trace() + + def dump_stack(self, *, async_aware=None): + """Return a single stack snapshot from the target process.""" + return self._get_stack_trace(async_aware=async_aware) + + def sample(self, collector, duration_sec=None, *, async_aware=False): + sample_interval_sec = self.sample_interval_usec / 1_000_000 + num_samples = 0 + errors = 0 + interrupted = False + running_time_sec = 0 + start_time = next_time = time.perf_counter() + last_sample_time = start_time + realtime_update_interval = 1.0 # Update every second + last_realtime_update = start_time + aggregating = getattr(collector, 'aggregating', False) is True + prev_stack = None + pending_count = 0 + pending_timestamps = [] if aggregating else None + + def flush_pending(): + nonlocal pending_count, pending_timestamps + if pending_count == 0: + return + pending_count = 0 + ts = pending_timestamps + pending_timestamps = [] + collector.collect(prev_stack, timestamps_us=ts) + + try: + while duration_sec is None or running_time_sec < duration_sec: + # Check if live collector wants to stop + if hasattr(collector, 'running') and not collector.running: + break + + current_time = time.perf_counter() + current_time_us = int(current_time * 1_000_000) + if next_time > current_time: + sleep_time = (next_time - current_time) * 0.9 + if sleep_time > 0.0001: + time.sleep(sleep_time) + elif next_time < current_time: + try: + stack_frames = self._get_stack_trace( + async_aware=async_aware + ) + if aggregating: + if stack_frames != prev_stack: + flush_pending() + prev_stack = stack_frames + pending_count += 1 + pending_timestamps.append(current_time_us) + if pending_count >= MAX_PENDING_SAMPLES: + flush_pending() + else: + collector.collect(stack_frames) + except ProcessLookupError as e: + running_time_sec = current_time - start_time + break + except (RuntimeError, UnicodeDecodeError, MemoryError, OSError): + flush_pending() + collector.collect_failed_sample() + errors += 1 + prev_stack = None + except Exception as e: + if not _is_process_running(self.pid): + break + raise e from None + + # Track actual sampling intervals for real-time stats + if num_samples > 0: + actual_interval = current_time - last_sample_time + self.sample_intervals.append( + 1.0 / actual_interval + ) # Convert to Hz + self.total_samples += 1 + + # Print real-time statistics if enabled + if ( + self.realtime_stats + and (current_time - last_realtime_update) + >= realtime_update_interval + ): + self._print_realtime_stats() + last_realtime_update = current_time + + last_sample_time = current_time + num_samples += 1 + next_time += sample_interval_sec + + running_time_sec = time.perf_counter() - start_time + except KeyboardInterrupt: + interrupted = True + running_time_sec = time.perf_counter() - start_time + print("Interrupted by user.") + finally: + flush_pending() + + # Clear real-time stats line if it was being displayed + if self.realtime_stats and len(self.sample_intervals) > 0: + print() # Add newline after real-time stats + + sample_rate = num_samples / running_time_sec if running_time_sec > 0 else 0 + error_rate = (errors / num_samples) * 100 if num_samples > 0 else 0 + expected_samples = int(running_time_sec / sample_interval_sec) + missed_samples = (expected_samples - num_samples) / expected_samples * 100 if expected_samples > 0 else 0 + + # Don't print stats for live mode (curses is handling display) + is_live_mode = LiveStatsCollector is not None and isinstance(collector, LiveStatsCollector) + if not is_live_mode: + s = "" if num_samples == 1 else "s" + print(f"Captured {num_samples:n} sample{s} in {fmt(running_time_sec, 2)} seconds") + print(f"Sample rate: {fmt(sample_rate, 2)} samples/sec") + print(f"Error rate: {fmt(error_rate, 2)}") + + # Print unwinder stats if stats collection is enabled + if self.collect_stats: + self._print_unwinder_stats() + + if isinstance(collector, BinaryCollector): + self._print_binary_stats(collector) + + # Pass stats to flamegraph collector if it's the right type + if hasattr(collector, 'set_stats'): + collector.set_stats(self.sample_interval_usec, running_time_sec, sample_rate, error_rate, missed_samples, mode=self.mode) + + if num_samples < expected_samples and not is_live_mode and not interrupted: + print( + f"Warning: missed {expected_samples - num_samples} samples " + f"from the expected total of {expected_samples} " + f"({fmt((expected_samples - num_samples) / expected_samples * 100, 2)}%)" + ) + + def _print_realtime_stats(self): + """Print real-time sampling statistics.""" + if len(self.sample_intervals) < 2: + return + + # Calculate statistics on the Hz values (deque automatically maintains rolling window) + hz_values = list(self.sample_intervals) + mean_hz = statistics.mean(hz_values) + min_hz = min(hz_values) + max_hz = max(hz_values) + + # Calculate microseconds per sample for all metrics (1/Hz * 1,000,000) + mean_us_per_sample = (1.0 / mean_hz) * 1_000_000 if mean_hz > 0 else 0 + min_us_per_sample = ( + (1.0 / max_hz) * 1_000_000 if max_hz > 0 else 0 + ) # Min time = Max Hz + max_us_per_sample = ( + (1.0 / min_hz) * 1_000_000 if min_hz > 0 else 0 + ) # Max time = Min Hz + + # Build cache stats string if stats collection is enabled + ANSIColors = get_colors() + + cache_stats_str = "" + if self.collect_stats: + try: + stats = self.unwinder.get_stats() + hits = stats.get('frame_cache_hits', 0) + partial = stats.get('frame_cache_partial_hits', 0) + misses = stats.get('frame_cache_misses', 0) + total = hits + partial + misses + if total > 0: + hit_pct = (hits + partial) / total * 100 + cache_stats_str = f" {ANSIColors.MAGENTA}Cache: {fmt(hit_pct)}% ({hits}+{partial}/{misses}){ANSIColors.RESET}" + except RuntimeError: + pass + + # Clear line and print stats + print( + f"\r\033[K{ANSIColors.BOLD_BLUE}Stats:{ANSIColors.RESET} " + f"{ANSIColors.YELLOW}{fmt(mean_hz)}Hz ({fmt(mean_us_per_sample)}µs){ANSIColors.RESET} " + f"{ANSIColors.GREEN}Min: {fmt(min_hz)}Hz{ANSIColors.RESET} " + f"{ANSIColors.RED}Max: {fmt(max_hz)}Hz{ANSIColors.RESET} " + f"{ANSIColors.CYAN}N={self.total_samples}{ANSIColors.RESET}" + f"{cache_stats_str}", + end="", + flush=True, + ) + + def _print_unwinder_stats(self): + """Print unwinder statistics including cache performance.""" + try: + stats = self.unwinder.get_stats() + except RuntimeError: + return # Stats not enabled + + ANSIColors = get_colors() + + print(f"\n{ANSIColors.BOLD_BLUE}{'='*50}{ANSIColors.RESET}") + print(f"{ANSIColors.BOLD_BLUE}Unwinder Statistics:{ANSIColors.RESET}") + + # Frame cache stats + total_samples = stats.get('total_samples', 0) + frame_cache_hits = stats.get('frame_cache_hits', 0) + frame_cache_partial_hits = stats.get('frame_cache_partial_hits', 0) + frame_cache_misses = stats.get('frame_cache_misses', 0) + total_lookups = frame_cache_hits + frame_cache_partial_hits + frame_cache_misses + + # Calculate percentages + hits_pct = (frame_cache_hits / total_lookups * 100) if total_lookups > 0 else 0 + partial_pct = (frame_cache_partial_hits / total_lookups * 100) if total_lookups > 0 else 0 + misses_pct = (frame_cache_misses / total_lookups * 100) if total_lookups > 0 else 0 + + print(f" {ANSIColors.CYAN}Frame Cache:{ANSIColors.RESET}") + print(f" Total samples: {total_samples:n}") + print(f" Full hits: {frame_cache_hits:n} ({ANSIColors.GREEN}{fmt(hits_pct)}%{ANSIColors.RESET})") + print(f" Partial hits: {frame_cache_partial_hits:n} ({ANSIColors.YELLOW}{fmt(partial_pct)}%{ANSIColors.RESET})") + print(f" Misses: {frame_cache_misses:n} ({ANSIColors.RED}{fmt(misses_pct)}%{ANSIColors.RESET})") + + # Frame read stats + frames_from_cache = stats.get('frames_read_from_cache', 0) + frames_from_memory = stats.get('frames_read_from_memory', 0) + total_frames = frames_from_cache + frames_from_memory + cache_frame_pct = (frames_from_cache / total_frames * 100) if total_frames > 0 else 0 + memory_frame_pct = (frames_from_memory / total_frames * 100) if total_frames > 0 else 0 + + print(f" {ANSIColors.CYAN}Frame Reads:{ANSIColors.RESET}") + print(f" From cache: {frames_from_cache:n} ({ANSIColors.GREEN}{fmt(cache_frame_pct)}%{ANSIColors.RESET})") + print(f" From memory: {frames_from_memory:n} ({ANSIColors.RED}{fmt(memory_frame_pct)}%{ANSIColors.RESET})") + + # Code object cache stats + code_hits = stats.get('code_object_cache_hits', 0) + code_misses = stats.get('code_object_cache_misses', 0) + total_code = code_hits + code_misses + code_hits_pct = (code_hits / total_code * 100) if total_code > 0 else 0 + code_misses_pct = (code_misses / total_code * 100) if total_code > 0 else 0 + + print(f" {ANSIColors.CYAN}Code Object Cache:{ANSIColors.RESET}") + print(f" Hits: {code_hits:n} ({ANSIColors.GREEN}{fmt(code_hits_pct)}%{ANSIColors.RESET})") + print(f" Misses: {code_misses:n} ({ANSIColors.RED}{fmt(code_misses_pct)}%{ANSIColors.RESET})") + + batched_attempts = stats.get('batched_read_attempts', 0) + batched_successes = stats.get('batched_read_successes', 0) + batched_misses = stats.get('batched_read_misses', 0) + segments_requested = stats.get('batched_read_segments_requested', 0) + segments_completed = stats.get('batched_read_segments_completed', 0) + if batched_attempts > 0: + batched_success_rate = stats.get('batched_read_success_rate', 0.0) + batched_miss_rate = 100.0 - batched_success_rate + segment_completion_rate = stats.get( + 'batched_read_segment_completion_rate', 0.0 + ) + + print(f" {ANSIColors.CYAN}Batched Reads:{ANSIColors.RESET}") + print(f" Attempts: {batched_attempts:n}") + print( + f" Successes: {batched_successes:n} " + f"({ANSIColors.GREEN}{fmt(batched_success_rate)}%{ANSIColors.RESET})" + ) + print( + f" Misses: {batched_misses:n} " + f"({ANSIColors.RED}{fmt(batched_miss_rate)}%{ANSIColors.RESET})" + ) + print( + f" Segments read: {segments_completed:n}/{segments_requested:n} " + f"({ANSIColors.GREEN}{fmt(segment_completion_rate)}%{ANSIColors.RESET})" + ) + + # Memory operations + memory_reads = stats.get('memory_reads', 0) + memory_bytes = stats.get('memory_bytes_read', 0) + if memory_bytes >= 1024 * 1024: + memory_str = f"{fmt(memory_bytes / (1024 * 1024))} MB" + elif memory_bytes >= 1024: + memory_str = f"{fmt(memory_bytes / 1024)} KB" + else: + memory_str = f"{memory_bytes} B" + print(f" {ANSIColors.CYAN}Memory:{ANSIColors.RESET}") + print(f" Read operations: {memory_reads:n} ({memory_str})") + + # Stale invalidations + stale_invalidations = stats.get('stale_cache_invalidations', 0) + if stale_invalidations > 0: + print(f" {ANSIColors.YELLOW}Stale cache invalidations: {stale_invalidations}{ANSIColors.RESET}") + + def _print_binary_stats(self, collector): + """Print binary I/O encoding statistics.""" + try: + stats = collector.get_stats() + except (ValueError, RuntimeError): + return # Collector closed or stats unavailable + + ANSIColors = get_colors() + + print(f" {ANSIColors.CYAN}Binary Encoding:{ANSIColors.RESET}") + + repeat_records = stats.get('repeat_records', 0) + repeat_samples = stats.get('repeat_samples', 0) + full_records = stats.get('full_records', 0) + suffix_records = stats.get('suffix_records', 0) + pop_push_records = stats.get('pop_push_records', 0) + total_records = stats.get('total_records', 0) + + if total_records > 0: + repeat_pct = repeat_records / total_records * 100 + full_pct = full_records / total_records * 100 + suffix_pct = suffix_records / total_records * 100 + pop_push_pct = pop_push_records / total_records * 100 + else: + repeat_pct = full_pct = suffix_pct = pop_push_pct = 0 + + print(f" Records: {total_records:,}") + print(f" RLE repeat: {repeat_records:,} ({ANSIColors.GREEN}{repeat_pct:.1f}%{ANSIColors.RESET}) [{repeat_samples:,} samples]") + print(f" Full stack: {full_records:,} ({full_pct:.1f}%)") + print(f" Suffix match: {suffix_records:,} ({suffix_pct:.1f}%)") + print(f" Pop-push: {pop_push_records:,} ({pop_push_pct:.1f}%)") + + frames_written = stats.get('total_frames_written', 0) + frames_saved = stats.get('frames_saved', 0) + compression_pct = stats.get('frame_compression_pct', 0) + + print(f" {ANSIColors.CYAN}Frame Efficiency:{ANSIColors.RESET}") + print(f" Frames written: {frames_written:,}") + print(f" Frames saved: {frames_saved:,} ({ANSIColors.GREEN}{compression_pct:.1f}%{ANSIColors.RESET})") + + bytes_written = stats.get('bytes_written', 0) + if bytes_written >= 1024 * 1024: + bytes_str = f"{bytes_written / (1024 * 1024):.1f} MB" + elif bytes_written >= 1024: + bytes_str = f"{bytes_written / 1024:.1f} KB" + else: + bytes_str = f"{bytes_written} B" + print(f" Bytes (pre-zstd): {bytes_str}") + + +def _is_process_running(pid): + if pid <= 0: + return False + if os.name == "posix": + try: + os.kill(pid, 0) + return True + except ProcessLookupError: + return False + except PermissionError: + # EPERM means process exists but we can't signal it + return True + elif sys.platform == "win32": + try: + _remote_debugging.RemoteUnwinder(pid) + except Exception: + return False + return True + else: + raise ValueError(f"Unsupported platform: {sys.platform}") + + +def sample( + pid, + collector, + *, + duration_sec=None, + all_threads=False, + realtime_stats=False, + mode=PROFILING_MODE_WALL, + async_aware=None, + native=False, + gc=True, + opcodes=False, + blocking=False, +): + """Sample a process using the provided collector. + + Args: + pid: Process ID to sample + collector: Collector instance to use for gathering samples + duration_sec: How long to sample for (seconds), or None to run until + the process exits or interrupted + all_threads: Whether to sample all threads + realtime_stats: Whether to print real-time sampling statistics + mode: Profiling mode - WALL (all samples), CPU (only when on CPU), + GIL (only when holding GIL), ALL (includes GIL and CPU status), + EXCEPTION (only when thread has an active exception) + native: Whether to include native frames + gc: Whether to include GC frames + opcodes: Whether to include opcode information + blocking: Whether to stop all threads before sampling for consistent snapshots + + Returns: + The collector with collected samples + """ + # Get sample interval from collector + sample_interval_usec = collector.sample_interval_usec + + # PROFILING_MODE_ALL implies no skipping at all + if mode == PROFILING_MODE_ALL: + skip_non_matching_threads = False + else: + # For most modes, skip non-matching threads + # Gecko collector overrides this by setting skip_idle=False + skip_non_matching_threads = True + + profiler = SampleProfiler( + pid, + sample_interval_usec, + all_threads=all_threads, + mode=mode, + native=native, + gc=gc, + opcodes=opcodes, + skip_non_matching_threads=skip_non_matching_threads, + collect_stats=realtime_stats, + blocking=blocking, + ) + profiler.realtime_stats = realtime_stats + + # Run the sampling + profiler.sample(collector, duration_sec, async_aware=async_aware) + + return collector + + +def dump_stack( + pid, + *, + all_threads=False, + mode=PROFILING_MODE_ALL, + async_aware=None, + native=False, + gc=True, + opcodes=False, + blocking=False, +): + """Return a single stack snapshot from a process.""" + if mode == PROFILING_MODE_ALL: + skip_non_matching_threads = False + else: + skip_non_matching_threads = True + + profiler = SampleProfiler( + pid, + sample_interval_usec=1, + all_threads=all_threads, + mode=mode, + native=native, + gc=gc, + opcodes=opcodes, + skip_non_matching_threads=skip_non_matching_threads, + blocking=blocking, + ) + return profiler.dump_stack(async_aware=async_aware) + + +def sample_live( + pid, + collector, + *, + duration_sec=None, + all_threads=False, + realtime_stats=False, + mode=PROFILING_MODE_WALL, + async_aware=None, + native=False, + gc=True, + opcodes=False, + blocking=False, +): + """Sample a process in live/interactive mode with curses TUI. + + Args: + pid: Process ID to sample + collector: LiveStatsCollector instance + duration_sec: How long to sample for (seconds) + all_threads: Whether to sample all threads + realtime_stats: Whether to print real-time sampling statistics + mode: Profiling mode - WALL (all samples), CPU (only when on CPU), + GIL (only when holding GIL), ALL (includes GIL and CPU status), + EXCEPTION (only when thread has an active exception) + native: Whether to include native frames + gc: Whether to include GC frames + opcodes: Whether to include opcode information + blocking: Whether to stop all threads before sampling for consistent snapshots + + Returns: + The collector with collected samples + """ + import curses + + # Check if process is alive before doing any heavy initialization + if not _is_process_running(pid): + print(f"No samples collected - process {pid} exited before profiling could begin.", file=sys.stderr) + return collector + + # Get sample interval from collector + sample_interval_usec = collector.sample_interval_usec + + # PROFILING_MODE_ALL implies no skipping at all + if mode == PROFILING_MODE_ALL: + skip_non_matching_threads = False + else: + skip_non_matching_threads = True + + profiler = SampleProfiler( + pid, + sample_interval_usec, + all_threads=all_threads, + mode=mode, + native=native, + gc=gc, + opcodes=opcodes, + skip_non_matching_threads=skip_non_matching_threads, + collect_stats=realtime_stats, + blocking=blocking, + ) + profiler.realtime_stats = realtime_stats + + def curses_wrapper_func(stdscr): + collector.init_curses(stdscr) + try: + profiler.sample(collector, duration_sec, async_aware=async_aware) + # If too few samples were collected, exit cleanly without showing TUI + if collector.successful_samples < MIN_SAMPLES_FOR_TUI: + # Clear screen before exiting to avoid visual artifacts + stdscr.clear() + stdscr.refresh() + return + # Mark as finished and keep the TUI running until user presses 'q' + collector.mark_finished() + # Keep processing input until user quits + while collector.running: + collector._handle_input() + time.sleep(0.05) # Small sleep to avoid busy waiting + finally: + collector.cleanup_curses() + + try: + curses.wrapper(curses_wrapper_func) + except KeyboardInterrupt: + pass + + # If too few samples were collected, print a message + if collector.successful_samples < MIN_SAMPLES_FOR_TUI: + if collector.successful_samples == 0: + print(f"No samples collected - process {pid} exited before profiling could begin.", file=sys.stderr) + else: + print(f"Only {collector.successful_samples} sample(s) collected (minimum {MIN_SAMPLES_FOR_TUI} required for TUI) - process {pid} exited too quickly.", file=sys.stderr) + + return collector diff --git a/Lib/profiling/sampling/stack_collector.py b/Lib/profiling/sampling/stack_collector.py new file mode 100644 index 00000000000..60061b4a2ec --- /dev/null +++ b/Lib/profiling/sampling/stack_collector.py @@ -0,0 +1,928 @@ +import base64 +import collections +import functools +import importlib.resources +import json +import linecache +import os +import sys +import sysconfig + +from ._css_utils import get_combined_css +from .collector import Collector, extract_lineno +from .opcode_utils import get_opcode_mapping +from .string_table import StringTable +from .module_utils import extract_module_name, get_python_path_info + + +class StackTraceCollector(Collector): + aggregating = True + + def __init__(self, sample_interval_usec, *, skip_idle=False): + self.sample_interval_usec = sample_interval_usec + self.skip_idle = skip_idle + + def collect(self, stack_frames, timestamps_us=None): + weight = len(timestamps_us) if timestamps_us else 1 + for frames, thread_id in self._iter_stacks(stack_frames, skip_idle=self.skip_idle): + self.process_frames(frames, thread_id, weight=weight) + + def process_frames(self, frames, thread_id, weight=1): + pass + + +class CollapsedStackCollector(StackTraceCollector): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.stack_counter = collections.Counter() + + def process_frames(self, frames, thread_id, weight=1): + # Extract only (filename, lineno, funcname) - opcode not needed for collapsed stacks + # frame is (filename, location, funcname, opcode) + call_tree = tuple( + (f[0], extract_lineno(f[1]), f[2]) for f in reversed(frames) + ) + self.stack_counter[(call_tree, thread_id)] += weight + + def export(self, filename): + lines = [] + for (call_tree, thread_id), count in self.stack_counter.items(): + parts = [f"tid:{thread_id}"] + for file, line, func in call_tree: + # This is what pstats does for "special" frames: + if file == "~" and line == 0: + part = func + else: + part = f"{os.path.basename(file)}:{func}:{line}" + parts.append(part) + stack_str = ";".join(parts) + lines.append((stack_str, count)) + + lines.sort(key=lambda x: (-x[1], x[0])) + + with open(filename, "w", + encoding="utf-8", errors="surrogatepass") as f: + for stack, count in lines: + f.write(f"{stack} {count}\n") + print(f"Collapsed stack output written to {filename}") + return True + + +# Allow for tree conversion and the dict/list frames in the Python JSON encoder. +_FLAMEGRAPH_RECURSION_MARGIN = 6000 + + +class FlamegraphCollector(StackTraceCollector): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.stats = {"sample_interval_usec": self.sample_interval_usec} + self._root = { + "samples": 0, + "children": {}, + "threads": set(), + "thread_samples": collections.Counter(), + "thread_self": collections.Counter(), + } + self._total_samples = 0 + self._sample_count = 0 # Track actual number of samples (not thread traces) + self._func_intern = {} + self._string_table = StringTable() + self._module_cache = {} + self._all_threads = set() + + # Thread status statistics (similar to LiveStatsCollector) + self.thread_status_counts = { + "has_gil": 0, + "on_cpu": 0, + "gil_requested": 0, + "unknown": 0, + "has_exception": 0, + "total": 0, + } + self.samples_with_gc_frames = 0 + + # Per-thread statistics + self.per_thread_stats = {} # {thread_id: {has_gil, on_cpu, gil_requested, unknown, has_exception, total, gc_samples}} + + def collect(self, stack_frames, timestamps_us=None): + """Override to track thread status statistics before processing frames.""" + # Weight is number of timestamps (samples with identical stack) + weight = len(timestamps_us) if timestamps_us else 1 + # Increment sample count by weight + self._sample_count += weight + + # Collect both aggregate and per-thread statistics using base method + status_counts, has_gc_frame, per_thread_stats = self._collect_thread_status_stats(stack_frames) + + # Merge aggregate status counts (multiply by weight) + for key in status_counts: + self.thread_status_counts[key] += status_counts[key] * weight + + # Update aggregate GC frame count + if has_gc_frame: + self.samples_with_gc_frames += weight + + # Merge per-thread statistics (multiply by weight) + for thread_id, stats in per_thread_stats.items(): + if thread_id not in self.per_thread_stats: + self.per_thread_stats[thread_id] = { + "has_gil": 0, + "on_cpu": 0, + "gil_requested": 0, + "unknown": 0, + "has_exception": 0, + "total": 0, + "gc_samples": 0, + } + for key, value in stats.items(): + self.per_thread_stats[thread_id][key] += value * weight + + # Call parent collect to process frames + super().collect(stack_frames, timestamps_us) + + def set_stats(self, sample_interval_usec, duration_sec, sample_rate, + error_rate=None, missed_samples=None, mode=None): + """Set profiling statistics to include in flamegraph data.""" + self.stats = { + "sample_interval_usec": sample_interval_usec, + "duration_sec": duration_sec, + "sample_rate": sample_rate, + "error_rate": error_rate, + "missed_samples": missed_samples, + "mode": mode + } + + def set_replay_stats(self, info): + """Restore measured statistics stored in a binary profile.""" + duration_sec = info.get("duration_sec") + sample_rate = info.get("sample_rate") + if duration_sec is None or sample_rate is None: + return + self.set_stats( + self.sample_interval_usec, + duration_sec, + sample_rate, + error_rate=info.get("error_rate"), + missed_samples=info.get("missed_samples"), + mode=self.stats.get("mode"), + ) + def set_mode(self, mode): + self.stats["mode"] = mode + + def export(self, filename): + # Converting the call tree recurses to the sampled stack depth. + old_limit = sys.getrecursionlimit() + sys.setrecursionlimit(old_limit + _FLAMEGRAPH_RECURSION_MARGIN) + try: + flamegraph_data = self._convert_to_flamegraph_format() + + # Debug output with string table statistics + num_functions = len(flamegraph_data.get("children", [])) + total_time = flamegraph_data.get("value", 0) + string_count = len(self._string_table) + s1 = "" if num_functions == 1 else "s" + s2 = "" if total_time == 1 else "s" + s3 = "" if string_count == 1 else "s" + print( + f"Flamegraph data: {num_functions} root function{s1}, " + f"{total_time} total sample{s2}, " + f"{string_count} unique string{s3}" + ) + + if num_functions == 0: + print( + "Warning: No functions found in profiling data. " + "Check if sampling captured any data." + ) + return False + + html_content = self._create_flamegraph_html(flamegraph_data) + + with open(filename, "w", encoding="utf-8") as f: + f.write(html_content) + + print(f"Flamegraph saved to: {filename}") + return True + finally: + sys.setrecursionlimit(old_limit) + + @staticmethod + @functools.lru_cache(maxsize=None) + def _format_function_name(func): + filename, lineno, funcname = func + + # Special frames like and should not show file:line + if filename == "~" and lineno == 0: + return funcname + + if len(filename) > 50: + parts = filename.split("/") + if len(parts) > 2: + filename = f".../{'/'.join(parts[-2:])}" + + return f"{funcname} ({filename}:{lineno})" + + @staticmethod + @functools.lru_cache(maxsize=None) + def _format_module_name(func, module_name): + filename, lineno, funcname = func + + # Special frames like and should not show file:line + if filename == "~" and lineno == 0: + return funcname + + return f"{funcname} ({module_name}:{lineno})" + + def _get_module_name(self, filename, path_info): + module_name = self._module_cache.get(filename) + if module_name is None: + module_name, _ = extract_module_name(filename, path_info) + self._module_cache[filename] = module_name + return module_name + + def _convert_to_flamegraph_format(self, *, min_samples=None): + if self._total_samples == 0: + return { + "name": self._string_table.intern("No Data"), + "value": 0, + "children": [], + "threads": [], + "strings": self._string_table.get_strings() + } + + def convert_children(children, min_samples, path_info): + out = [] + for func, node in children.items(): + samples = node["samples"] + significant_for_thread = any( + thread_samples >= max( + 1, + int( + self._root["thread_samples"][thread_id] + * 0.001 + ), + ) + for thread_id, thread_samples + in node["thread_samples"].items() + ) + if samples < min_samples and not significant_for_thread: + continue + + # Intern all string components for maximum efficiency + filename_idx = self._string_table.intern(func[0]) + funcname_idx = self._string_table.intern(func[2]) + module_name = self._get_module_name(func[0], path_info) + + module_idx = self._string_table.intern(module_name) + name_idx = self._string_table.intern(self._format_function_name(func)) + label_idx = self._string_table.intern(self._format_module_name(func, module_name)) + + child_entry = { + "name": name_idx, + "label": label_idx, + "value": samples, + "self": node.get("self", 0), + "children": [], + "filename": filename_idx, + "module": module_idx, + "lineno": func[1], + "funcname": funcname_idx, + "threads": sorted(list(node.get("threads", set()))), + "thread_values": { + thread_id: [ + samples, + node["thread_self"].get(thread_id, 0), + ] + for thread_id, samples in sorted( + node["thread_samples"].items() + ) + }, + } + + source = self._get_source_lines(func) + if source: + # Intern source lines for memory efficiency + source_indices = [self._string_table.intern(line) for line in source] + child_entry["source"] = source_indices + + # Include opcode data if available + opcodes = node.get("opcodes", {}) + if opcodes: + child_entry["opcodes"] = dict(opcodes) + thread_opcodes = node.get("thread_opcodes") + if thread_opcodes: + child_entry["thread_opcodes"] = { + thread_id: dict(counts) + for thread_id, counts in sorted( + thread_opcodes.items() + ) + } + + # Recurse + child_entry["children"] = convert_children( + node["children"], min_samples, path_info + ) + out.append(child_entry) + + # Sort by value (descending) then by name index for consistent ordering + out.sort(key=lambda x: (-x["value"], x["name"])) + return out + + # Filter out very small functions (less than 0.1% of total samples) + total_samples = self._total_samples + if min_samples is None: + min_samples = max(1, int(total_samples * 0.001)) + path_info = get_python_path_info() + + root_children = convert_children(self._root["children"], min_samples, path_info) + if not root_children: + return { + "name": self._string_table.intern("No significant data"), + "value": 0, + "children": [], + "strings": self._string_table.get_strings() + } + + # Calculate thread status percentages for display + is_free_threaded = bool(sysconfig.get_config_var("Py_GIL_DISABLED")) + total_threads = max(1, self.thread_status_counts["total"]) + thread_stats = { + "has_gil_pct": (self.thread_status_counts["has_gil"] / total_threads) * 100, + "on_cpu_pct": (self.thread_status_counts["on_cpu"] / total_threads) * 100, + "gil_requested_pct": (self.thread_status_counts["gil_requested"] / total_threads) * 100, + "has_exception_pct": (self.thread_status_counts["has_exception"] / total_threads) * 100, + "gc_pct": (self.samples_with_gc_frames / max(1, self._sample_count)) * 100, + "free_threaded": is_free_threaded, + **self.thread_status_counts + } + + # Calculate per-thread statistics with percentages + per_thread_stats_with_pct = {} + total_samples_denominator = max(1, self._sample_count) + for thread_id, stats in self.per_thread_stats.items(): + total = max(1, stats["total"]) + per_thread_stats_with_pct[thread_id] = { + "has_gil_pct": (stats["has_gil"] / total) * 100, + "on_cpu_pct": (stats["on_cpu"] / total) * 100, + "gil_requested_pct": (stats["gil_requested"] / total) * 100, + "has_exception_pct": (stats["has_exception"] / total) * 100, + "gc_pct": (stats["gc_samples"] / total_samples_denominator) * 100, + **stats + } + + # Build opcode mapping for JS + opcode_mapping = get_opcode_mapping() + + # If we only have one root child, make it the root to avoid redundant level + root_thread_values = { + thread_id: [samples, 0] + for thread_id, samples in sorted( + self._root["thread_samples"].items() + ) + } + sole_root_covers_profile = ( + len(root_children) == 1 + and root_children[0]["value"] == total_samples + and { + thread_id: values[0] + for thread_id, values + in root_children[0]["thread_values"].items() + } == { + thread_id: values[0] + for thread_id, values in root_thread_values.items() + } + ) + if sole_root_covers_profile: + main_child = root_children[0] + # Update name and label to indicate it's the program root + old_name = self._string_table.get_string(main_child["name"]) + main_child["name"] = self._string_table.intern(f"Program Root: {old_name}") + old_label = self._string_table.get_string(main_child["label"]) + main_child["label"] = self._string_table.intern(f"Program Root: {old_label}") + main_child["stats"] = { + **self.stats, + "thread_stats": thread_stats, + "per_thread_stats": per_thread_stats_with_pct + } + main_child["threads"] = sorted(list(self._all_threads)) + main_child["strings"] = self._string_table.get_strings() + main_child["opcode_mapping"] = opcode_mapping + return main_child + + program_root_idx = self._string_table.intern("Program Root") + return { + "name": program_root_idx, + "label": program_root_idx, + "value": total_samples, + "children": root_children, + "stats": { + **self.stats, + "thread_stats": thread_stats, + "per_thread_stats": per_thread_stats_with_pct + }, + "threads": sorted(list(self._all_threads)), + "thread_values": root_thread_values, + "strings": self._string_table.get_strings(), + "opcode_mapping": opcode_mapping + } + + def process_frames(self, frames, thread_id, weight=1): + """Process stack frames into flamegraph tree structure. + + Args: + frames: List of (filename, location, funcname, opcode) tuples in + leaf-to-root order. location is (lineno, end_lineno, col_offset, end_col_offset). + opcode is None if not gathered. + thread_id: Thread ID for this stack trace + weight: Number of samples this stack represents (for batched RLE) + """ + # Reverse to root->leaf order for tree building + self._root["samples"] += weight + self._root["thread_samples"][thread_id] += weight + self._total_samples += weight + self._root["threads"].add(thread_id) + self._all_threads.add(thread_id) + + current = self._root + for filename, location, funcname, opcode in reversed(frames): + lineno = extract_lineno(location) + func = (filename, lineno, funcname) + func = self._func_intern.setdefault(func, func) + + node = current["children"].get(func) + if node is None: + node = { + "samples": 0, + "children": {}, + "threads": set(), + "thread_samples": collections.Counter(), + "thread_self": collections.Counter(), + "opcodes": collections.Counter(), + "self": 0, + } + current["children"][func] = node + node["samples"] += weight + node["thread_samples"][thread_id] += weight + node["threads"].add(thread_id) + + if opcode is not None: + node["opcodes"][opcode] += weight + thread_opcodes = node.setdefault("thread_opcodes", {}) + thread_opcodes.setdefault( + thread_id, collections.Counter() + )[opcode] += weight + + current = node + + if current is not self._root: + current["self"] += weight + current["thread_self"][thread_id] += weight + + def _get_source_lines(self, func): + filename, lineno, _ = func + + try: + lines = [] + start_line = max(1, lineno - 2) + end_line = lineno + 3 + + for line_num in range(start_line, end_line): + line = linecache.getline(filename, line_num) + if line.strip(): + marker = "→ " if line_num == lineno else " " + lines.append(f"{marker}{line_num}: {line.rstrip()}") + + return lines if lines else None + + except Exception: + return None + + def _create_flamegraph_html(self, data): + try: + data_json = json.dumps(data) + except RecursionError: + # The C encoder can exhaust the C stack independently of the + # Python recursion limit. iterencode() uses the Python encoder. + data_json = "".join(json.JSONEncoder().iterencode(data)) + + template_dir = importlib.resources.files(__package__) + vendor_dir = template_dir / "_vendor" + assets_dir = template_dir / "_assets" + + d3_path = vendor_dir / "d3" / "7.8.5" / "d3.min.js" + d3_flame_graph_dir = vendor_dir / "d3-flame-graph" / "4.1.3" + fg_css_path = d3_flame_graph_dir / "d3-flamegraph.css" + fg_js_path = d3_flame_graph_dir / "d3-flamegraph.min.js" + fg_tooltip_js_path = d3_flame_graph_dir / "d3-flamegraph-tooltip.min.js" + + html_template = (template_dir / "_flamegraph_assets" / "flamegraph_template.html").read_text(encoding="utf-8") + css_content = get_combined_css("flamegraph") + base_js = (template_dir / "_shared_assets" / "base.js").read_text(encoding="utf-8") + component_js = (template_dir / "_flamegraph_assets" / "flamegraph.js").read_text(encoding="utf-8") + js_content = f"{base_js}\n{component_js}" + + # Set title and subtitle based on whether this is a differential flamegraph + is_differential = data.get("stats", {}).get("is_differential", False) + if is_differential: + title = "Tachyon Profiler - Differential Flamegraph Report" + subtitle = "Differential Flamegraph Report" + else: + title = "Tachyon Profiler - Flamegraph Report" + subtitle = "Flamegraph Report" + + html_template = html_template.replace("{{TITLE}}", title) + html_template = html_template.replace("{{SUBTITLE}}", subtitle) + + # Inline first-party CSS/JS + html_template = html_template.replace( + "", f"" + ) + html_template = html_template.replace( + "", f"" + ) + + png_path = assets_dir / "tachyon-logo.png" + b64_logo = base64.b64encode(png_path.read_bytes()).decode("ascii") + + # Let CSS control size; keep markup simple + logo_html = f'Tachyon logo' + html_template = html_template.replace("", logo_html) + html_template = html_template.replace( + "", f"{sys.version_info.major}.{sys.version_info.minor}" + ) + + d3_js = d3_path.read_text(encoding="utf-8") + fg_css = fg_css_path.read_text(encoding="utf-8") + fg_js = fg_js_path.read_text(encoding="utf-8") + fg_tooltip_js = fg_tooltip_js_path.read_text(encoding="utf-8") + + html_template = html_template.replace( + "", + f"", + ) + html_template = html_template.replace( + "", + f"", + ) + html_template = html_template.replace( + "", + f"", + ) + html_template = html_template.replace( + "", + f"", + ) + + # Replace the placeholder with actual data + html_content = html_template.replace( + "{{FLAMEGRAPH_DATA}}", data_json + ) + + return html_content + + +class DiffFlamegraphCollector(FlamegraphCollector): + """Differential flamegraph collector that compares against a baseline binary profile.""" + + def __init__(self, sample_interval_usec, *, baseline_binary_path, + skip_idle=False, mode=None, capture_config=None): + super().__init__(sample_interval_usec, skip_idle=skip_idle) + if not os.path.exists(baseline_binary_path): + raise ValueError(f"Baseline file not found: {baseline_binary_path}") + self.baseline_binary_path = baseline_binary_path + self._baseline_collector = None + self._elided_paths = set() + self.mode = mode + self.capture_config = capture_config + + def _load_baseline(self): + """Load baseline profile from binary file.""" + from .binary_reader import BinaryReader + + with BinaryReader(self.baseline_binary_path) as reader: + info = reader.get_info() + + baseline_mode = info.get("mode") + if ( + baseline_mode is not None + and self.mode is not None + and baseline_mode != self.mode + ): + raise ValueError( + "Baseline profiling mode does not match current mode" + ) + + baseline_config = info.get("capture_config") + if baseline_config is not None and self.capture_config is not None: + names = baseline_config.keys() | self.capture_config.keys() + mismatches = [ + name for name in names + if baseline_config.get(name, False) + != self.capture_config.get(name, False) + ] + else: + mismatches = [] + if mismatches: + raise ValueError( + "Baseline capture configuration does not match current " + f"configuration: {', '.join(sorted(mismatches))}" + ) + + baseline_collector = FlamegraphCollector( + sample_interval_usec=info['sample_interval_us'], + skip_idle=self.skip_idle + ) + + reader.replay_samples(baseline_collector) + + self._baseline_collector = baseline_collector + + def _aggregate_path_samples(self, root_node, path=None): + """Aggregate samples by stack path, excluding line numbers for cross-profile matching.""" + if path is None: + path = () + + stats = {} + + for func, node in root_node["children"].items(): + filename, _lineno, funcname = func + func_key = (filename, funcname) + path_key = path + (func_key,) + + total_samples = node.get("samples", 0) + self_samples = node.get("self", 0) + + if path_key in stats: + stats[path_key]["total"] += total_samples + stats[path_key]["self"] += self_samples + else: + stats[path_key] = { + "total": total_samples, + "self": self_samples + } + + child_stats = self._aggregate_path_samples(node, path_key) + for key, data in child_stats.items(): + if key in stats: + stats[key]["total"] += data["total"] + stats[key]["self"] += data["self"] + else: + stats[key] = data + + return stats + + def _convert_to_flamegraph_format(self): + """Convert to flamegraph format with differential annotations.""" + if self._baseline_collector is None: + self._load_baseline() + + current_flamegraph = super()._convert_to_flamegraph_format() + + current_stats = self._aggregate_path_samples(self._root) + baseline_stats = self._aggregate_path_samples(self._baseline_collector._root) + + # Express baseline samples in units of the current sample interval. + # Do not normalize by total profile duration: doing so makes unchanged + # functions appear different when another function becomes faster or + # slower. + baseline_total = self._baseline_collector._total_samples + if baseline_total > 0: + scale = ( + self._baseline_collector.sample_interval_usec + / self.sample_interval_usec + ) + else: + scale = 1.0 + + self._annotate_nodes_with_diff(current_flamegraph, current_stats, baseline_stats, scale) + self._add_elided_flamegraph(current_flamegraph, current_stats, baseline_stats, scale) + + return current_flamegraph + + def _annotate_nodes_with_diff(self, current_flamegraph, current_stats, baseline_stats, scale): + """Annotate each node in the tree with diff metadata.""" + if "stats" not in current_flamegraph: + current_flamegraph["stats"] = {} + + current_flamegraph["stats"]["baseline_samples"] = self._baseline_collector._total_samples + current_flamegraph["stats"]["current_samples"] = self._total_samples + current_flamegraph["stats"]["baseline_scale"] = scale + current_flamegraph["stats"]["is_differential"] = True + + if self._is_promoted_root(current_flamegraph): + self._add_diff_data_to_node(current_flamegraph, (), current_stats, baseline_stats, scale) + else: + for child in current_flamegraph["children"]: + self._add_diff_data_to_node(child, (), current_stats, baseline_stats, scale) + + def _add_diff_data_to_node(self, node, path, current_stats, baseline_stats, scale): + """Recursively add diff metadata to nodes.""" + func_key = self._extract_func_key(node, self._string_table) + path_key = path + (func_key,) if func_key else path + + current_data = current_stats.get(path_key, {"total": 0, "self": 0}) + baseline_data = baseline_stats.get(path_key, {"total": 0, "self": 0}) + + current_self = node.get("self", 0) + current_total = node.get("value", 0) + + current_nonself = current_total - current_self + aggregate_nonself = current_data["total"] - current_data["self"] + + # Allocate self and descendant samples separately. Line-number + # changes can split one function path into several rendered nodes, + # and using independent weights for self and inclusive totals could + # otherwise assign a node more self samples than total samples. + self_weight = self._sample_weight( + current_self, + current_data["self"], + current_total, + current_data["total"], + ) + nonself_weight = self._sample_weight( + current_nonself, + aggregate_nonself, + current_total, + current_data["total"], + ) + baseline_self = baseline_data["self"] * scale * self_weight + baseline_nonself = ( + baseline_data["total"] - baseline_data["self"] + ) * scale * nonself_weight + baseline_total = baseline_self + baseline_nonself + + diff = current_self - baseline_self + if baseline_self > 0: + diff_pct = (diff / baseline_self) * 100.0 + elif current_self > 0: + diff_pct = 100.0 + else: + diff_pct = 0.0 + + node["baseline"] = baseline_self + node["baseline_total"] = baseline_total + node["self_time"] = current_self + node["diff"] = diff + node["diff_pct"] = diff_pct + + if "children" in node and node["children"]: + for child in node["children"]: + self._add_diff_data_to_node(child, path_key, current_stats, baseline_stats, scale) + + @staticmethod + def _sample_weight(value, aggregate, fallback_value, fallback_aggregate): + if aggregate > 0: + return value / aggregate + if fallback_aggregate > 0: + return fallback_value / fallback_aggregate + return 0 + + def _is_promoted_root(self, data): + """Check if the data represents a promoted root node.""" + return "filename" in data and "funcname" in data + + def _add_elided_flamegraph(self, current_flamegraph, current_stats, baseline_stats, scale): + """Calculate elided paths and add elided flamegraph to stats.""" + self._elided_paths = baseline_stats.keys() - current_stats.keys() + + # A sampled stack can end at an internal path that also has elided + # descendants. Count every disappeared path with self samples, not + # just the leaves of the elided path tree. + elided_stacks = { + path + for path in self._elided_paths + if baseline_stats[path]["self"] > 0 + } + current_flamegraph["stats"]["elided_count"] = len(elided_stacks) + + if self._elided_paths: + elided_flamegraph = self._build_elided_flamegraph(baseline_stats, scale) + if elided_flamegraph: + current_flamegraph["stats"]["elided_flamegraph"] = elided_flamegraph + + def _build_elided_flamegraph(self, baseline_stats, scale): + """Build flamegraph containing only elided paths from baseline. + + This re-runs the base conversion pipeline on the baseline collector + to produce a complete formatted flamegraph, then prunes it to keep + only elided paths. + """ + if not self._baseline_collector or not self._elided_paths: + return None + + # Suppress source line collection for elided nodes - these functions + # no longer exist in the current profile, so source lines from the + # current machine's filesystem would be misleading or unavailable. + orig_get_source = self._baseline_collector._get_source_lines + self._baseline_collector._get_source_lines = lambda func: None + try: + baseline_data = self._baseline_collector._convert_to_flamegraph_format( + min_samples=1 + ) + finally: + self._baseline_collector._get_source_lines = orig_get_source + + # Remove non-elided nodes and recalculate values + if not self._extract_elided_nodes(baseline_data, path=()): + return None + + self._add_elided_metadata(baseline_data, baseline_stats, scale, path=()) + + # Merge only profiling metadata, not thread-level stats + for key in ("sample_interval_usec", "duration_sec", "sample_rate", + "error_rate", "missed_samples", "mode"): + if key in self.stats: + baseline_data["stats"][key] = self.stats[key] + baseline_data["stats"]["is_differential"] = True + baseline_data["stats"]["baseline_samples"] = self._baseline_collector._total_samples + baseline_data["stats"]["current_samples"] = self._total_samples + + return baseline_data + + def _extract_elided_nodes(self, node, path): + """Remove non-elided nodes and recalculate values bottom-up.""" + if not node: + return False + + func_key = self._extract_func_key(node, self._baseline_collector._string_table) + current_path = path + (func_key,) if func_key else path + + is_elided = current_path in self._elided_paths if func_key else False + + if "children" in node: + # Filter children, keeping only those with elided descendants + elided_children = [] + total_value = 0 + for child in node["children"]: + if self._extract_elided_nodes(child, current_path): + elided_children.append(child) + total_value += child.get("value", 0) + node["children"] = elided_children + + # Recalculate value for structural (non-elided) ancestor nodes; + # elided nodes keep their original value to preserve self-samples + if elided_children and not is_elided: + node["value"] = total_value + node["self"] = 0 + node.pop("opcodes", None) + node.pop("thread_opcodes", None) + + # Keep this node if it's elided or has elided descendants + return is_elided or bool(node.get("children")) + + def _add_elided_metadata(self, node, baseline_stats, scale, path): + """Add differential metadata showing this path disappeared.""" + if not node: + return + + func_key = self._extract_func_key(node, self._baseline_collector._string_table) + current_path = path + (func_key,) if func_key else path + + baseline_self = 0 + baseline_total = 0 + if func_key and current_path in baseline_stats: + baseline_total = node.get("value", 0) * scale + + # Matched nodes are retained only as structural ancestors. Their + # own samples are still present in the current profile and must + # not be reported as disappeared. + if current_path in self._elided_paths: + baseline_self = node.get("self", 0) * scale + + node["baseline"] = baseline_self + node["baseline_total"] = baseline_total + node["diff"] = -baseline_self + else: + node["baseline"] = 0 + node["baseline_total"] = 0 + node["diff"] = 0 + + node["self_time"] = 0 + # Elided paths have zero current self-time, so the change is always + # -100% when there was actual baseline self-time to lose. + # For internal nodes with no baseline self-time, use 0% to avoid + # misleading tooltips. + if baseline_self > 0: + node["diff_pct"] = -100.0 + else: + node["diff_pct"] = 0.0 + + # Scale geometry after computing metadata from raw baseline counts. + node["value"] = node.get("value", 0) * scale + node["self"] = node.get("self", 0) * scale + + if "children" in node and node["children"]: + for child in node["children"]: + self._add_elided_metadata(child, baseline_stats, scale, current_path) + + def _extract_func_key(self, node, string_table): + """Extract (filename, funcname) key from node, excluding line numbers. + + Line numbers are excluded to match functions even if they moved. + Returns None for root nodes that don't have function information. + """ + if "filename" not in node or "funcname" not in node: + return None + filename = string_table.get_string(node["filename"]) + funcname = string_table.get_string(node["funcname"]) + return (filename, funcname) diff --git a/Lib/profiling/sampling/string_table.py b/Lib/profiling/sampling/string_table.py new file mode 100644 index 00000000000..25c347f7ff1 --- /dev/null +++ b/Lib/profiling/sampling/string_table.py @@ -0,0 +1,53 @@ +"""String table implementation for memory-efficient string storage in profiling data.""" + +class StringTable: + """A string table for interning strings and reducing memory usage.""" + + def __init__(self): + self._strings = [] + self._string_to_index = {} + + def intern(self, string): + """Intern a string and return its index. + + Args: + string: The string to intern + + Returns: + int: The index of the string in the table + """ + if not isinstance(string, str): + string = str(string) + + if string in self._string_to_index: + return self._string_to_index[string] + + index = len(self._strings) + self._strings.append(string) + self._string_to_index[string] = index + return index + + def get_string(self, index): + """Get a string by its index. + + Args: + index: The index of the string + + Returns: + str: The string at the given index, or empty string if invalid + """ + if 0 <= index < len(self._strings): + return self._strings[index] + return "" + + def get_strings(self): + """Get the list of all strings in the table. + + Returns: + list: A copy of the strings list + """ + return self._strings.copy() + + def __len__(self): + """Return the number of strings in the table.""" + return len(self._strings) diff --git a/Lib/profiling/tracing/__init__.py b/Lib/profiling/tracing/__init__.py new file mode 100644 index 00000000000..165665304e0 --- /dev/null +++ b/Lib/profiling/tracing/__init__.py @@ -0,0 +1,220 @@ +"""Tracing profiler for Python. + +This module provides deterministic profiling of Python programs by tracing +every function call and return. +""" + +__all__ = ("run", "runctx", "Profile") + +import _lsprof +import importlib.machinery +import importlib.util +import io +from profiling.tracing._utils import _Utils + +# ____________________________________________________________ +# Simple interface + +def run(statement, filename=None, sort=-1): + """Run statement under profiler optionally saving results in filename + + This function takes a single argument that can be passed to the + "exec" statement, and an optional file name. In all cases this + routine attempts to "exec" its first argument and gather profiling + statistics from the execution. If no file name is present, then this + function automatically prints a simple profiling report, sorted by the + standard name string (file/line/function-name) that is presented in + each line. + """ + return _Utils(Profile).run(statement, filename, sort) + +def runctx(statement, globals, locals, filename=None, sort=-1): + """Run statement under profiler, supplying your own globals and locals, + optionally saving results in filename. + + statement and filename have the same semantics as profile.run + """ + return _Utils(Profile).runctx(statement, globals, locals, + filename, sort) + +# ____________________________________________________________ + +class Profile(_lsprof.Profiler): + """Profile(timer=None, timeunit=None, subcalls=True, builtins=True) + + Builds a profiler object using the specified timer function. + The default timer is a fast built-in one based on real time. + For custom timer functions returning integers, timeunit can + be a float specifying a scale (i.e. how long each integer unit + is, in seconds). + """ + + # Most of the functionality is in the base class. + # This subclass only adds convenient and backward-compatible methods. + + def print_stats(self, sort=-1): + import pstats + if not isinstance(sort, tuple): + sort = (sort,) + pstats.Stats(self).strip_dirs().sort_stats(*sort).print_stats() + + def dump_stats(self, file): + import marshal + with open(file, 'wb') as f: + self.create_stats() + marshal.dump(self.stats, f) + + def create_stats(self): + self.disable() + self.snapshot_stats() + + def snapshot_stats(self): + entries = self.getstats() + self.stats = {} + callersdicts = {} + # call information + for entry in entries: + func = label(entry.code) + nc = entry.callcount # ncalls column of pstats (before '/') + cc = nc - entry.reccallcount # ncalls column of pstats (after '/') + tt = entry.inlinetime # tottime column of pstats + ct = entry.totaltime # cumtime column of pstats + callers = {} + callersdicts[id(entry.code)] = callers + self.stats[func] = cc, nc, tt, ct, callers + # subcall information + for entry in entries: + if entry.calls: + func = label(entry.code) + for subentry in entry.calls: + try: + callers = callersdicts[id(subentry.code)] + except KeyError: + continue + nc = subentry.callcount + cc = nc - subentry.reccallcount + tt = subentry.inlinetime + ct = subentry.totaltime + if func in callers: + prev = callers[func] + nc += prev[0] + cc += prev[1] + tt += prev[2] + ct += prev[3] + callers[func] = nc, cc, tt, ct + + # The following two methods can be called by clients to use + # a profiler to profile a statement, given as a string. + + def run(self, cmd): + import __main__ + dict = __main__.__dict__ + return self.runctx(cmd, dict, dict) + + def runctx(self, cmd, globals, locals): + self.enable() + try: + exec(cmd, globals, locals) + finally: + self.disable() + return self + + # This method is more useful to profile a single function call. + def runcall(self, func, /, *args, **kw): + self.enable() + try: + return func(*args, **kw) + finally: + self.disable() + + def __enter__(self): + self.enable() + return self + + def __exit__(self, *exc_info): + self.disable() + +# ____________________________________________________________ + +def label(code): + if isinstance(code, str): + return ('~', 0, code) # built-in functions ('~' sorts at the end) + else: + return (code.co_filename, code.co_firstlineno, code.co_name) + +# ____________________________________________________________ + +def main(): + import os + import sys + import runpy + import pstats + from optparse import OptionParser + usage = "cProfile.py [-o output_file_path] [-s sort] [-m module | scriptfile] [arg] ..." + parser = OptionParser(usage=usage) + parser.allow_interspersed_args = False + parser.add_option('-o', '--outfile', dest="outfile", + help="Save stats to ", default=None) + parser.add_option('-s', '--sort', dest="sort", + help="Sort order when printing to stdout, based on pstats.Stats class", + default=2, + choices=sorted(pstats.Stats.sort_arg_dict_default)) + parser.add_option('-m', dest="module", action="store_true", + help="Profile a library module", default=False) + + if not sys.argv[1:]: + parser.print_usage() + sys.exit(2) + + (options, args) = parser.parse_args() + sys.argv[:] = args + + # The script that we're profiling may chdir, so capture the absolute path + # to the output file at startup. + if options.outfile is not None: + options.outfile = os.path.abspath(options.outfile) + + if len(args) > 0: + if options.module: + code = "run_module(modname, run_name='__main__')" + globs = { + 'run_module': runpy.run_module, + 'modname': args[0] + } + else: + progname = args[0] + sys.path.insert(0, os.path.dirname(progname)) + with io.open_code(progname) as fp: + code = compile(fp.read(), progname, 'exec', module='__main__') + spec = importlib.machinery.ModuleSpec(name='__main__', loader=None, + origin=progname) + module = importlib.util.module_from_spec(spec) + # Set __main__ so that importing __main__ in the profiled code will + # return the same namespace that the code is executing under. + sys.modules['__main__'] = module + # Ensure that we're using the same __dict__ instance as the module + # for the global variables so that updates to globals are reflected + # in the module's namespace. + globs = module.__dict__ + globs.update({ + # Set __spec__ to None so the profiled program behaves like a + # script run directly (gh-140729). + '__spec__': None, + '__file__': spec.origin, + '__name__': spec.name, + '__package__': None, + }) + + try: + runctx(code, globs, None, options.outfile, options.sort) + except BrokenPipeError as exc: + # Prevent "Exception ignored" during interpreter shutdown. + sys.stdout = None + sys.exit(exc.errno) + else: + parser.print_usage() + return parser + +# When invoked as main program, invoke the profiler on a script +if __name__ == '__main__': + main() diff --git a/Lib/profiling/tracing/__main__.py b/Lib/profiling/tracing/__main__.py new file mode 100644 index 00000000000..95041d1368b --- /dev/null +++ b/Lib/profiling/tracing/__main__.py @@ -0,0 +1,6 @@ +"""Run the tracing profiler from the command line.""" + +from profiling.tracing import main + +if __name__ == '__main__': + main() diff --git a/Lib/profiling/tracing/_utils.py b/Lib/profiling/tracing/_utils.py new file mode 100644 index 00000000000..8c4b65889c7 --- /dev/null +++ b/Lib/profiling/tracing/_utils.py @@ -0,0 +1,32 @@ +class _Utils: + """Support class for utility functions which are shared by + profile.py and cProfile.py modules. + Not supposed to be used directly. + """ + + def __init__(self, profiler): + self.profiler = profiler + + def run(self, statement, filename, sort): + prof = self.profiler() + try: + prof.run(statement) + except SystemExit: + pass + finally: + self._show(prof, filename, sort) + + def runctx(self, statement, globals, locals, filename, sort): + prof = self.profiler() + try: + prof.runctx(statement, globals, locals) + except SystemExit: + pass + finally: + self._show(prof, filename, sort) + + def _show(self, prof, filename, sort): + if filename is not None: + prof.dump_stats(filename) + else: + prof.print_stats(sort) diff --git a/Lib/pstats.py b/Lib/pstats.py index becaf35580e..07ecda07796 100644 --- a/Lib/pstats.py +++ b/Lib/pstats.py @@ -139,7 +139,11 @@ def load_stats(self, arg): return elif isinstance(arg, str): with open(arg, 'rb') as f: - self.stats = marshal.load(f) + stats = marshal.load(f) + if (('__sampled__',)) in stats: + stats.pop((('__sampled__',))) + self.__class__ = SampledStats + self.stats = stats try: file_stats = os.stat(arg) arg = time.ctime(file_stats.st_mtime) + " " + arg @@ -150,6 +154,7 @@ def load_stats(self, arg): arg.create_stats() self.stats = arg.stats arg.stats = {} + return if not self.stats: raise TypeError("Cannot create or construct a %r object from %r" % (self.__class__, arg)) @@ -467,7 +472,10 @@ def print_call_heading(self, name_size, column_title): subheader = isinstance(value, tuple) break if subheader: - print(" "*name_size + " ncalls tottime cumtime", file=self.stream) + self.print_call_subheading(name_size) + + def print_call_subheading(self, name_size): + print(" "*name_size + " ncalls tottime cumtime", file=self.stream) def print_call_line(self, name_size, source, call_dict, arrow="->"): print(func_std_string(source).ljust(name_size) + arrow, end=' ', file=self.stream) @@ -516,6 +524,35 @@ def print_line(self, func): # hack: should print percentages print(f8(ct/cc), end=' ', file=self.stream) print(func_std_string(func), file=self.stream) + +class SampledStats(Stats): + def __init__(self, *args, stream=None): + super().__init__(*args, stream=stream) + + self.sort_arg_dict = { + "samples" : (((1,-1), ), "sample count"), + "nsamples" : (((1,-1), ), "sample count"), + "cumtime" : (((3,-1), ), "cumulative time"), + "cumulative": (((3,-1), ), "cumulative time"), + "filename" : (((4, 1), ), "file name"), + "line" : (((5, 1), ), "line number"), + "module" : (((4, 1), ), "file name"), + "name" : (((6, 1), ), "function name"), + "nfl" : (((6, 1),(4, 1),(5, 1),), "name/file/line"), + "psamples" : (((0,-1), ), "primitive call count"), + "stdname" : (((7, 1), ), "standard name"), + "time" : (((2,-1), ), "internal time"), + "tottime" : (((2,-1), ), "internal time"), + } + + def print_call_subheading(self, name_size): + print(" "*name_size + " nsamples tottime cumtime", file=self.stream) + + def print_title(self): + print(' nsamples tottime persample cumtime persample', end=' ', file=self.stream) + print('filename:lineno(function)', file=self.stream) + + class TupleComp: """This class provides a generic function for comparing any two tuples. Each instance records a list of tuple-indices (from most significant @@ -607,6 +644,24 @@ def f8(x): # Statistics browser added by ESR, April 2001 #************************************************************************** +class StatsLoaderShim: + """Compatibility shim implementing 'create_stats' needed by Stats classes + to handle already unmarshalled data.""" + def __init__(self, raw_stats): + self.stats = raw_stats + + def create_stats(self): + pass + +def stats_factory(raw_stats): + """Return a Stats or SampledStats instance based on the marker in raw_stats.""" + if (('__sampled__',)) in raw_stats: + raw_stats = dict(raw_stats) # avoid mutating caller's dict + raw_stats.pop((('__sampled__',))) + return SampledStats(StatsLoaderShim(raw_stats)) + else: + return Stats(StatsLoaderShim(raw_stats)) + if __name__ == '__main__': import cmd try: @@ -693,7 +748,15 @@ def help_quit(self): def do_read(self, line): if line: try: - self.stats = Stats(line) + with open(line, 'rb') as f: + raw_stats = marshal.load(f) + self.stats = stats_factory(raw_stats) + try: + file_stats = os.stat(line) + arg = time.ctime(file_stats.st_mtime) + " " + line + except Exception: + arg = line + self.stats.files = [arg] except OSError as err: print(err.args[1], file=self.stream) return diff --git a/Lib/py_compile.py b/Lib/py_compile.py index 43d8ec90ffb..7ca479141e0 100644 --- a/Lib/py_compile.py +++ b/Lib/py_compile.py @@ -177,7 +177,7 @@ def main(): import argparse description = 'A simple command-line interface for py_compile module.' - parser = argparse.ArgumentParser(description=description, color=True) + parser = argparse.ArgumentParser(description=description) parser.add_argument( '-q', '--quiet', action='store_true', @@ -194,8 +194,10 @@ def main(): else: filenames = args.filenames for filename in filenames: + cfilename = (None if sys.implementation.cache_tag + else f"{filename.rpartition('.')[0]}.pyc") try: - compile(filename, doraise=True) + compile(filename, cfilename, doraise=True) except PyCompileError as error: if args.quiet: parser.exit(1) diff --git a/Lib/pyclbr.py b/Lib/pyclbr.py index 37f86995d6c..35772cc01d0 100644 --- a/Lib/pyclbr.py +++ b/Lib/pyclbr.py @@ -158,7 +158,6 @@ def _readmodule(module, path, inpackage=None): return _readmodule(submodule, parent['__path__'], package) # Search the path for the module. - f = None if inpackage is not None: search_path = path else: diff --git a/Lib/pydoc.py b/Lib/pydoc.py index 091f8af01b2..561ba3a8d63 100644 --- a/Lib/pydoc.py +++ b/Lib/pydoc.py @@ -71,27 +71,47 @@ class or function within a module or module in a package. If the import textwrap import time import tokenize -import urllib.parse import warnings from annotationlib import Format from collections import deque from reprlib import Repr from traceback import format_exception_only -from _pyrepl.pager import (get_pager, pipe_pager, - plain_pager, tempfile_pager, tty_pager) +try: + from _pyrepl.pager import (get_pager, pipe_pager, + plain_pager, tempfile_pager, tty_pager) -# Expose plain() as pydoc.plain() -from _pyrepl.pager import plain # noqa: F401 + # Expose plain() as pydoc.plain() + from _pyrepl.pager import plain # noqa: F401 + # --------------------------------------------------------- old names + getpager = get_pager + pipepager = pipe_pager + plainpager = plain_pager + tempfilepager = tempfile_pager + ttypager = tty_pager -# --------------------------------------------------------- old names +except ModuleNotFoundError: + # Minimal alternatives for cases where _pyrepl is absent. -getpager = get_pager -pipepager = pipe_pager -plainpager = plain_pager -tempfilepager = tempfile_pager -ttypager = tty_pager + def plain(text: str) -> str: + """Remove boldface formatting from text.""" + return re.sub('.\b', '', text) + + def plain_pager(text: str, title: str = '') -> None: + """Simply print unformatted text. This is the ultimate fallback.""" + encoding = getattr(sys.stdout, 'encoding', None) or 'utf-8' + text = text.encode(encoding, 'backslashreplace').decode(encoding) + text = plain(text) + sys.stdout.write(text) + + def get_pager(): + """Unconditionally return the plain pager, since _pyrepl is absent.""" + return plain_pager + + # --------------------------------------------------------- old names + getpager = get_pager + plainpager = plain_pager # --------------------------------------------------------- common routines @@ -108,96 +128,10 @@ def pathdirs(): normdirs.append(normdir) return dirs -def _findclass(func): - cls = sys.modules.get(func.__module__) - if cls is None: - return None - for name in func.__qualname__.split('.')[:-1]: - cls = getattr(cls, name) - if not inspect.isclass(cls): - return None - return cls - -def _finddoc(obj): - if inspect.ismethod(obj): - name = obj.__func__.__name__ - self = obj.__self__ - if (inspect.isclass(self) and - getattr(getattr(self, name, None), '__func__') is obj.__func__): - # classmethod - cls = self - else: - cls = self.__class__ - elif inspect.isfunction(obj): - name = obj.__name__ - cls = _findclass(obj) - if cls is None or getattr(cls, name) is not obj: - return None - elif inspect.isbuiltin(obj): - name = obj.__name__ - self = obj.__self__ - if (inspect.isclass(self) and - self.__qualname__ + '.' + name == obj.__qualname__): - # classmethod - cls = self - else: - cls = self.__class__ - # Should be tested before isdatadescriptor(). - elif isinstance(obj, property): - name = obj.__name__ - cls = _findclass(obj.fget) - if cls is None or getattr(cls, name) is not obj: - return None - elif inspect.ismethoddescriptor(obj) or inspect.isdatadescriptor(obj): - name = obj.__name__ - cls = obj.__objclass__ - if getattr(cls, name) is not obj: - return None - if inspect.ismemberdescriptor(obj): - slots = getattr(cls, '__slots__', None) - if isinstance(slots, dict) and name in slots: - return slots[name] - else: - return None - for base in cls.__mro__: - try: - doc = _getowndoc(getattr(base, name)) - except AttributeError: - continue - if doc is not None: - return doc - return None - -def _getowndoc(obj): - """Get the documentation string for an object if it is not - inherited from its class.""" - try: - doc = object.__getattribute__(obj, '__doc__') - if doc is None: - return None - if obj is not type: - typedoc = type(obj).__doc__ - if isinstance(typedoc, str) and typedoc == doc: - return None - return doc - except AttributeError: - return None - def _getdoc(object): - """Get the documentation string for an object. - - All tabs are expanded to spaces. To clean up docstrings that are - indented to line up with blocks of code, any whitespace than can be - uniformly removed from the second line onwards is removed.""" - doc = _getowndoc(object) - if doc is None: - try: - doc = _finddoc(object) - except (AttributeError, TypeError): - return None - if not isinstance(doc, str): - return None - return inspect.cleandoc(doc) + return inspect.getdoc(object, + fallback_to_class_doc=False, + inherit_class_doc=False) def getdoc(object): """Get the doc string or comments for an object.""" @@ -327,12 +261,12 @@ def visiblename(name, all=None, obj=None): """Decide whether to show documentation on a variable.""" # Certain special names are redundant or internal. # XXX Remove __initializing__? - if name in {'__author__', '__builtins__', '__cached__', '__credits__', - '__date__', '__doc__', '__file__', '__spec__', - '__loader__', '__module__', '__name__', '__package__', - '__path__', '__qualname__', '__slots__', '__version__', - '__static_attributes__', '__firstlineno__', - '__annotate_func__', '__annotations_cache__'}: + if name in {'__author__', '__builtins__', '__credits__', '__date__', + '__doc__', '__file__', '__spec__', '__loader__', '__module__', + '__name__', '__package__', '__path__', '__qualname__', + '__slots__', '__version__', '__static_attributes__', + '__firstlineno__', '__annotate_func__', + '__annotations_cache__'}: return 0 # Private names are hidden, but special names are displayed. if name.startswith('__') and name.endswith('__'): return 1 @@ -536,6 +470,13 @@ class Doc: PYTHONDOCS = os.environ.get("PYTHONDOCS", "https://docs.python.org/%d.%d/library" % sys.version_info[:2]) + STDLIB_DIR = sysconfig.get_path('stdlib') + # TODO: RUSTPYTHON; Cargo builds keep Lib outside sysconfig's install paths. + if (sys.implementation.name == 'rustpython' + and getattr(sys, '_is_python_build', False) + and not sysconfig.is_python_build() + and getattr(sys, '_stdlib_dir', None)): + STDLIB_DIR = sys._stdlib_dir def document(self, object, name=None, *args): """Generate documentation for an object.""" @@ -561,23 +502,12 @@ def fail(self, object, name=None, *args): docmodule = docclass = docroutine = docother = docproperty = docdata = fail - def getdocloc(self, object, basedir=sysconfig.get_path('stdlib')): + def getdocloc(self, object, basedir=None): """Return the location of module docs or None""" - - try: - file = inspect.getabsfile(object) - except TypeError: - file = '(built-in)' - + basedir = self.STDLIB_DIR if basedir is None else basedir docloc = os.environ.get("PYTHONDOCS", self.PYTHONDOCS) - basedir = os.path.normcase(basedir) - if (isinstance(object, type(os)) and - (object.__name__ in ('errno', 'exceptions', 'gc', - 'marshal', 'posix', 'signal', 'sys', - '_thread', 'zipimport') or - (file.startswith(basedir) and - not file.startswith(os.path.join(basedir, 'site-packages')))) and + if (self._is_stdlib_module(object, basedir) and object.__name__ not in ('xml.etree', 'test.test_pydoc.pydoc_mod')): try: @@ -597,6 +527,36 @@ def getdocloc(self, object, basedir=sysconfig.get_path('stdlib')): docloc = None return docloc + def _get_version(self, object): + if self._is_stdlib_module(object): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + version = getattr(object, '__version__', None) + else: + version = getattr(object, '__version__', None) + return '' if version is None else str(version) + + def _is_stdlib_module(self, object, basedir=None): + basedir = self.STDLIB_DIR if basedir is None else basedir + + try: + file = inspect.getabsfile(object) + except TypeError: + file = '(built-in)' + + if sysconfig.is_python_build(): + srcdir = sysconfig.get_config_var('srcdir') + if srcdir: + basedir = os.path.join(srcdir, 'Lib') + + basedir = os.path.normcase(basedir) + return (isinstance(object, type(os)) and + (object.__name__ in ('errno', 'exceptions', 'gc', + 'marshal', 'posix', 'signal', 'sys', + '_thread', 'zipimport') + or (file.startswith(basedir) and + not file.startswith(os.path.join(basedir, 'site-packages'))))) + # -------------------------------------------- HTML documentation generator class HTMLRepr(Repr): @@ -851,13 +811,14 @@ def docmodule(self, object, name=None, mod=None, *ignored): head = '%s' % linkedname try: path = inspect.getabsfile(object) - url = urllib.parse.quote(path) + import urllib.request + url = urllib.request.pathname2url(path) filelink = self.filelink(url, path) except TypeError: filelink = '(built-in)' info = [] - if hasattr(object, '__version__'): - version = str(object.__version__) + + if version := self._get_version(object): if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() info.append('version %s' % self.escape(version)) @@ -1392,8 +1353,7 @@ def docmodule(self, object, name=None, mod=None, *ignored): contents.append(self.docother(value, key, name, maxlen=70)) result = result + self.section('DATA', '\n'.join(contents)) - if hasattr(object, '__version__'): - version = str(object.__version__) + if version := self._get_version(object): if version[:11] == '$' + 'Revision: ' and version[-1:] == '$': version = version[11:-1].strip() result = result + self.section('VERSION', version) @@ -1811,7 +1771,8 @@ def writedoc(thing, forceload=0): """Write HTML documentation to a file in the current directory.""" object, name = resolve(thing, forceload) page = html.page(describe(object), html.document(object, name)) - with open(name + '.html', 'w', encoding='utf-8') as file: + with open(name + '.html', 'w', encoding='utf-8', + errors='backslashreplace') as file: file.write(page) print('wrote', name + '.html') @@ -1824,7 +1785,6 @@ def writedocs(dir, pkgpath='', done=None): def _introdoc(): - import textwrap ver = '%d.%d' % sys.version_info[:2] if os.environ.get('PYTHON_BASIC_REPL'): pyrepl_keys = '' @@ -1893,6 +1853,7 @@ class Helper: 'in': ('in', 'SEQUENCEMETHODS'), 'is': 'COMPARISON', 'lambda': ('lambda', 'FUNCTIONS'), + 'lazy': ('lazy', 'MODULES'), 'match': ('match', 'if'), 'nonlocal': ('nonlocal', 'global NAMESPACES'), 'not': 'BOOLEAN', @@ -2185,7 +2146,6 @@ def showtopic(self, topic, more_xrefs=''): if more_xrefs: xrefs = (xrefs or '') + ' ' + more_xrefs if xrefs: - import textwrap text = 'Related help topics: ' + ', '.join(xrefs.split()) + '\n' wrapped_text = textwrap.wrap(text, 72) doc += '\n%s\n' % '\n'.join(wrapped_text) @@ -2409,7 +2369,7 @@ def do_GET(self): self.send_header('Content-Type', '%s; charset=UTF-8' % content_type) self.end_headers() self.wfile.write(self.urlhandler( - self.path, content_type).encode('utf-8')) + self.path, content_type).encode('utf-8', 'backslashreplace')) def log_message(self, *args): # Don't log messages. diff --git a/Lib/pydoc_data/module_docs.py b/Lib/pydoc_data/module_docs.py index 2d3543f2983..0d851ffb6db 100644 --- a/Lib/pydoc_data/module_docs.py +++ b/Lib/pydoc_data/module_docs.py @@ -1,4 +1,4 @@ -# Autogenerated by Sphinx on Wed Aug 5 13:29:41 2026 +# Autogenerated by Sphinx on Sun Oct 25 18:57:09 2026 # as part of the release process. module_docs = { @@ -23,7 +23,6 @@ 'bisect': 'bisect#module-bisect', 'builtins': 'builtins#module-builtins', 'bz2': 'bz2#module-bz2', - 'cProfile': 'profile#module-cProfile', 'calendar': 'calendar#module-calendar', 'cgi': 'cgi#module-cgi', 'cgitb': 'cgitb#module-cgitb', @@ -49,6 +48,7 @@ 'crypt': 'crypt#module-crypt', 'csv': 'csv#module-csv', 'ctypes': 'ctypes#module-ctypes', + 'ctypes.wintypes': 'ctypes#module-ctypes.wintypes', 'curses': 'curses#module-curses', 'curses.ascii': 'curses.ascii#module-curses.ascii', 'curses.panel': 'curses.panel#module-curses.panel', @@ -149,6 +149,7 @@ 'mailcap': 'mailcap#module-mailcap', 'marshal': 'marshal#module-marshal', 'math': 'math#module-math', + 'math.integer': 'math.integer#module-math.integer', 'mimetypes': 'mimetypes#module-mimetypes', 'mmap': 'mmap#module-mmap', 'modulefinder': 'modulefinder#module-modulefinder', @@ -183,7 +184,10 @@ 'posix': 'posix#module-posix', 'pprint': 'pprint#module-pprint', 'profile': 'profile#module-profile', - 'pstats': 'profile#module-pstats', + 'profiling': 'profiling#module-profiling', + 'profiling.sampling': 'profiling.sampling#module-profiling.sampling', + 'profiling.tracing': 'profiling.tracing#module-profiling.tracing', + 'pstats': 'pstats#module-pstats', 'pty': 'pty#module-pty', 'pwd': 'pwd#module-pwd', 'py_compile': 'py_compile#module-py_compile', diff --git a/Lib/pydoc_data/topics.py b/Lib/pydoc_data/topics.py index 753d9d43069..8d3669ca3d4 100644 --- a/Lib/pydoc_data/topics.py +++ b/Lib/pydoc_data/topics.py @@ -1,4 +1,4 @@ -# Autogenerated by Sphinx on Wed Aug 5 13:29:41 2026 +# Autogenerated by Sphinx on Sun Oct 25 18:57:09 2026 # as part of the release process. topics = { @@ -912,9 +912,10 @@ class to a new value, *value*. renders the meaning of the program undefined. In the future, a check may be added to prevent this. -* "TypeError" will be raised if nonempty *__slots__* are defined for a - class derived from a ""variable-length" built-in type" such as - "int", "bytes", and "tuple". +* "TypeError" will be raised if *__slots__* other than *__dict__* and + *__weakref__* are defined for a class derived from a ""variable- + length" built-in type" such as "int", "bytes", and "type", except + "tuple". * Any non-string *iterable* may be assigned to *__slots__*. @@ -934,6 +935,10 @@ class derived from a ""variable-length" built-in type" such as * If an *iterator* is used for *__slots__* then a *descriptor* is created for each of the iterator’s values. However, the *__slots__* attribute will be an empty iterator. + +Changed in version 3.15: Allowed defining the *__dict__* and +*__weakref__* *__slots__* for any class. Allowed defining any +*__slots__* for a class derived from "tuple". ''', 'attribute-references': r'''Attribute references ******************** @@ -1394,7 +1399,7 @@ class and instance attributes applies as for regular assignments. "return" statement, the return value is "None". a built-in function or method: - The result is up to the interpreter; see Built-in Functions for the + The result is up to the interpreter; see Built-in functions for the descriptions of built-in functions and methods. a class object: @@ -1433,6 +1438,9 @@ class Foo: class Foo(object): pass +There may be one or more base classes; see Multiple inheritance below +for more information. + The class’s suite is then executed in a new execution frame (see Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly @@ -1496,6 +1504,115 @@ class attributes; they are shared by instances. Instance attributes **PEP 3129** - Class Decorators The proposal that added class decorators. Function and method decorators were introduced in **PEP 318**. + + +Multiple inheritance +==================== + +Python classes may have multiple base classes, a technique known as +*multiple inheritance*. The base classes are specified in the class +definition by listing them in parentheses after the class name, +separated by commas. For example, the following class definition: + + >>> class A: pass + >>> class B: pass + >>> class C(A, B): pass + +defines a class "C" that inherits from classes "A" and "B". + +The *method resolution order* (MRO) is the order in which base classes +are searched when looking up an attribute on a class. See The Python +2.3 Method Resolution Order for a description of how Python determines +the MRO for a class. + +Multiple inheritance is not always allowed. Attempting to define a +class with multiple inheritance will raise an error if one of the +bases does not allow subclassing, if a consistent MRO cannot be +created, if no valid metaclass can be determined, or if there is an +instance layout conflict. We’ll discuss each of these in turn. + +First, all base classes must allow subclassing. While most classes +allow subclassing, some built-in classes do not, such as "bool": + + >>> class SubBool(bool): # TypeError + ... pass + Traceback (most recent call last): + ... + TypeError: type 'bool' is not an acceptable base type + +In the resolved MRO of a class, the class’s bases appear in the order +they were specified in the class’s bases list. Additionally, the MRO +always lists a child class before any of its bases. A class definition +will fail if it is impossible to resolve a consistent MRO that +satisfies these rules from the list of bases provided: + + >>> class Base: pass + >>> class Child(Base): pass + >>> class Grandchild(Base, Child): pass # TypeError + Traceback (most recent call last): + ... + TypeError: Cannot create a consistent method resolution order (MRO) for bases Base, Child + +In the MRO of "Grandchild", "Base" must appear before "Child" because +it is first in the base class list, but it must also appear after +"Child" because it is a parent of "Child". This is a contradiction, so +the class cannot be defined. + +If some of the bases have a custom *metaclass*, the metaclass of the +resulting class is chosen among the metaclasses of the bases and the +explicitly specified metaclass of the child class. It must be a +metaclass that is a subclass of all other candidate metaclasses. If no +such metaclass exists among the candidates, the class cannot be +created, as explained in Determining the appropriate metaclass. + +Finally, the instance layouts of the bases must be compatible. This +means that it must be possible to compute a *solid base* for the +class. Exactly which classes are solid bases depends on the Python +implementation. + +**CPython implementation detail:** In CPython, a class is a solid base +if it has a nonempty "__slots__" definition. Many but not all classes +defined in C are also solid bases, including most builtins (such as +"int" or "BaseException") but excluding most concrete "Exception" +classes. Generally, a C class is a solid base if its underlying struct +is different in size from its base class. + +Every class has a solid base. "object", the base class, has itself as +its solid base. If there is a single base, the child class’s solid +base is that class if it is a solid base, or else the base class’s +solid base. If there are multiple bases, we first find the solid base +for each base class to produce a list of candidate solid bases. If +there is a unique solid base that is a subclass of all others, then +that class is the solid base. Otherwise, class creation fails. + +Example: + + >>> class Solid1: + ... __slots__ = ("solid1",) + >>> + >>> class Solid2: + ... __slots__ = ("solid2",) + >>> + >>> class SolidChild(Solid1): + ... __slots__ = ("solid_child",) + >>> + >>> class C1: # solid base is `object` + ... pass + >>> + >>> # OK: solid bases are `Solid1` and `object`, and `Solid1` is a subclass of `object`. + >>> class C2(Solid1, C1): # solid base is `Solid1` + ... pass + >>> + >>> # OK: solid bases are `SolidChild` and `Solid1`, and `SolidChild` is a subclass of `Solid1`. + >>> class C3(SolidChild, Solid1): # solid base is `SolidChild` + ... pass + >>> + >>> # Error: solid bases are `Solid1` and `Solid2`, but neither is a subclass of the other. + >>> class C4(Solid1, Solid2): # error: no single solid base + ... pass + Traceback (most recent call last): + ... + TypeError: multiple bases have instance lay-out conflict ''', 'comparisons': r'''Comparisons *********** @@ -1851,7 +1968,7 @@ class attributes; they are shared by instances. Instance attributes iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see Assignment statements), and the suite is executed. This repeats for -each item provided by the iterator. When the iterator is exhausted, +each item provided by the iterator. When the iterator is *exhausted*, the suite in the "else" clause, if present, is executed, and the loop terminates. @@ -2455,7 +2572,7 @@ def foo(): | "None" | "True" | "False" - signed_number: ["-"] NUMBER + signed_number: ["+" | "-"] NUMBER The rule "strings" and the token "NUMBER" are defined in the standard Python grammar. Triple-quoted strings are supported. Raw strings and @@ -2779,6 +2896,8 @@ def foo(): * "float" + * "frozendict" + * "frozenset" * "int" @@ -2832,7 +2951,7 @@ def foo(): | parameter_list_no_posonly parameter_list_no_posonly: defparameter ("," defparameter)* ["," [parameter_list_starargs]] | parameter_list_starargs - parameter_list_starargs: "*" [star_parameter] ("," defparameter)* ["," [parameter_star_kwargs]] + parameter_list_starargs: "*" star_parameter ("," defparameter)* ["," [parameter_star_kwargs]] | "*" ("," defparameter)+ ["," [parameter_star_kwargs]] | parameter_star_kwargs parameter_star_kwargs: "**" parameter [","] @@ -2997,6 +3116,9 @@ class Foo: class Foo(object): pass +There may be one or more base classes; see Multiple inheritance below +for more information. + The class’s suite is then executed in a new execution frame (see Naming and binding), using a newly created local namespace and the original global namespace. (Usually, the suite contains mostly @@ -3062,6 +3184,115 @@ class attributes; they are shared by instances. Instance attributes decorators were introduced in **PEP 318**. +Multiple inheritance +-------------------- + +Python classes may have multiple base classes, a technique known as +*multiple inheritance*. The base classes are specified in the class +definition by listing them in parentheses after the class name, +separated by commas. For example, the following class definition: + + >>> class A: pass + >>> class B: pass + >>> class C(A, B): pass + +defines a class "C" that inherits from classes "A" and "B". + +The *method resolution order* (MRO) is the order in which base classes +are searched when looking up an attribute on a class. See The Python +2.3 Method Resolution Order for a description of how Python determines +the MRO for a class. + +Multiple inheritance is not always allowed. Attempting to define a +class with multiple inheritance will raise an error if one of the +bases does not allow subclassing, if a consistent MRO cannot be +created, if no valid metaclass can be determined, or if there is an +instance layout conflict. We’ll discuss each of these in turn. + +First, all base classes must allow subclassing. While most classes +allow subclassing, some built-in classes do not, such as "bool": + + >>> class SubBool(bool): # TypeError + ... pass + Traceback (most recent call last): + ... + TypeError: type 'bool' is not an acceptable base type + +In the resolved MRO of a class, the class’s bases appear in the order +they were specified in the class’s bases list. Additionally, the MRO +always lists a child class before any of its bases. A class definition +will fail if it is impossible to resolve a consistent MRO that +satisfies these rules from the list of bases provided: + + >>> class Base: pass + >>> class Child(Base): pass + >>> class Grandchild(Base, Child): pass # TypeError + Traceback (most recent call last): + ... + TypeError: Cannot create a consistent method resolution order (MRO) for bases Base, Child + +In the MRO of "Grandchild", "Base" must appear before "Child" because +it is first in the base class list, but it must also appear after +"Child" because it is a parent of "Child". This is a contradiction, so +the class cannot be defined. + +If some of the bases have a custom *metaclass*, the metaclass of the +resulting class is chosen among the metaclasses of the bases and the +explicitly specified metaclass of the child class. It must be a +metaclass that is a subclass of all other candidate metaclasses. If no +such metaclass exists among the candidates, the class cannot be +created, as explained in Determining the appropriate metaclass. + +Finally, the instance layouts of the bases must be compatible. This +means that it must be possible to compute a *solid base* for the +class. Exactly which classes are solid bases depends on the Python +implementation. + +**CPython implementation detail:** In CPython, a class is a solid base +if it has a nonempty "__slots__" definition. Many but not all classes +defined in C are also solid bases, including most builtins (such as +"int" or "BaseException") but excluding most concrete "Exception" +classes. Generally, a C class is a solid base if its underlying struct +is different in size from its base class. + +Every class has a solid base. "object", the base class, has itself as +its solid base. If there is a single base, the child class’s solid +base is that class if it is a solid base, or else the base class’s +solid base. If there are multiple bases, we first find the solid base +for each base class to produce a list of candidate solid bases. If +there is a unique solid base that is a subclass of all others, then +that class is the solid base. Otherwise, class creation fails. + +Example: + + >>> class Solid1: + ... __slots__ = ("solid1",) + >>> + >>> class Solid2: + ... __slots__ = ("solid2",) + >>> + >>> class SolidChild(Solid1): + ... __slots__ = ("solid_child",) + >>> + >>> class C1: # solid base is `object` + ... pass + >>> + >>> # OK: solid bases are `Solid1` and `object`, and `Solid1` is a subclass of `object`. + >>> class C2(Solid1, C1): # solid base is `Solid1` + ... pass + >>> + >>> # OK: solid bases are `SolidChild` and `Solid1`, and `SolidChild` is a subclass of `Solid1`. + >>> class C3(SolidChild, Solid1): # solid base is `SolidChild` + ... pass + >>> + >>> # Error: solid bases are `Solid1` and `Solid2`, but neither is a subclass of the other. + >>> class C4(Solid1, Solid2): # error: no single solid base + ... pass + Traceback (most recent call last): + ... + TypeError: multiple bases have instance lay-out conflict + + Coroutines ========== @@ -3816,11 +4047,11 @@ def f() -> annotation: ... object.__hash__(self) Called by built-in function "hash()" and for operations on members - of hashed collections including "set", "frozenset", and "dict". - The "__hash__()" method should return an integer. The only required - property is that objects which compare equal have the same hash - value; it is advised to mix together the hash values of the - components of the object that also play a part in comparison of + of hashed collections including "set", "frozenset", "dict", and + "frozendict". The "__hash__()" method should return an integer. The + only required property is that objects which compare equal have the + same hash value; it is advised to mix together the hash values of + the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. Example: @@ -4381,8 +4612,8 @@ class pdb.Pdb(completekey='tab', stdin=None, stdout=None, skip=None, nosigint=Fa To remove all commands from a breakpoint, type "commands" and follow it immediately with "end"; that is, give no commands. - With no *bpnumber* argument, "commands" refers to the last - breakpoint set. + With no *bpnumber* argument, "commands" refers to the most recently + set breakpoint that still exists. You can use breakpoint commands to start your program up again. Simply use the "continue" command, or "step", or any other command @@ -4686,7 +4917,7 @@ def middle(): def inner(x): 1 / x - out() + out() calling "pdb.pm()" will allow to move between exceptions: @@ -4742,47 +4973,49 @@ def inner(x): 'dict': r'''Dictionary displays ******************* -A dictionary display is a possibly empty series of dict items -(key/value pairs) enclosed in curly braces: - - dict_display: "{" [dict_item_list | dict_comprehension] "}" - dict_item_list: dict_item ("," dict_item)* [","] - dict_item: expression ":" expression | "**" or_expr - dict_comprehension: expression ":" expression comp_for - -A dictionary display yields a new dictionary object. - -If a comma-separated sequence of dict items is given, they are -evaluated from left to right to define the entries of the dictionary: -each key object is used as a key into the dictionary to store the -corresponding value. This means that you can specify the same key -multiple times in the dict item list, and the final dictionary’s value -for that key will be the last one given. - -A double asterisk "**" denotes *dictionary unpacking*. Its operand -must be a *mapping*. Each mapping item is added to the new -dictionary. Later values replace values already set by earlier dict -items and earlier dictionary unpackings. +A *dictionary display* is a possibly empty series of *dict items* +enclosed in curly braces. Each dict item is a colon-separated pair of +expressions: the *key* and its associated *value*. For example: + + >>> {1: 'one', 2: 'two'} + {1: 'one', 2: 'two'} + +At runtime, when a dictionary comprehension is evaluated, the +expressions are evaluated from left to right. Each key object is used +as a key into the dictionary to store the corresponding value. This +means that you can specify the same key multiple times in the +comprehension, and the final dictionary’s value for a given key will +be the last one given. For example: + + >>> { + ... 1: 'this will be overridden', + ... 2: 'two', + ... 1: 'also overridden', + ... 1: 'one', + ... } + {1: 'one', 2: 'two'} + +Instead of a key-value pair, a dict item may be an expression prefixed +by a double asterisk "**". This denotes *dictionary unpacking*. At +runtime, the expression must evaluate to a *mapping*; each item of the +mapping is added to the new dictionary. As with key-value pairs, later +values replace values already set by earlier items and unpackings. +This may be used to override a set of defaults: + + >>> defaults = {'color': 'blue', 'count': 8} + >>> overrides = {'color': 'yellow'} + >>> {**defaults, **overrides} + {'color': 'yellow', 'count': 8} Added in version 3.5: Unpacking into dictionary displays, originally proposed by **PEP 448**. -A dict comprehension, in contrast to list and set comprehensions, -needs two expressions separated with a colon followed by the usual -“for” and “if” clauses. When the comprehension is run, the resulting -key and value elements are inserted in the new dictionary in the order -they are produced. - -Restrictions on the types of the key values are listed earlier in -section The standard type hierarchy. (To summarize, the key type -should be *hashable*, which excludes all mutable objects.) Clashes -between duplicate keys are not detected; the last value (textually -rightmost in the display) stored for a given key value prevails. - -Changed in version 3.8: Prior to Python 3.8, in dict comprehensions, -the evaluation order of key and value was not well-defined. In -CPython, the value was evaluated before the key. Starting with 3.8, -the key is evaluated before the value, as proposed by **PEP 572**. +The formal grammar for dict displays is: + + dict: '{' [double_starred_kvpairs] '}' + double_starred_kvpairs: ','.double_starred_kvpair+ [','] + double_starred_kvpair: '**' or_expr | kvpair + kvpair: expression ':' expression ''', 'dynamic-features': r'''Interaction with dynamic features ********************************* @@ -5412,8 +5645,22 @@ class of the instance or a *non-virtual base class* thereof. The is the number of expressions in the list. The expressions are evaluated from left to right. -An asterisk "*" denotes *iterable unpacking*. Its operand must be an -*iterable*. The iterable is expanded into a sequence of items, which +A trailing comma is required only to create a one-item tuple, such as +"1,"; it is optional in all other cases. A single expression without a +trailing comma doesn’t create a tuple, but rather yields the value of +that expression. (To create an empty tuple, use an empty pair of +parentheses: "()".) + + +Iterable unpacking +================== + +In an expression list or tuple, list or set display, any expression +may be prefixed with an asterisk ("*"). This denotes *iterable +unpacking*. + +At runtime, the asterisk-prefixed expression must evaluate to an +*iterable*. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking. @@ -5422,12 +5669,6 @@ class of the instance or a *non-virtual base class* thereof. The Added in version 3.11: Any item in an expression list may be starred. See **PEP 646**. - -A trailing comma is required only to create a one-item tuple, such as -"1,"; it is optional in all other cases. A single expression without a -trailing comma doesn’t create a tuple, but rather yields the value of -that expression. (To create an empty tuple, use an empty pair of -parentheses: "()".) ''', 'floating': r'''Floating-point literals *********************** @@ -5497,7 +5738,7 @@ class of the instance or a *non-virtual base class* thereof. The iterable. The first item provided by the iterator is then assigned to the target list using the standard rules for assignments (see Assignment statements), and the suite is executed. This repeats for -each item provided by the iterator. When the iterator is exhausted, +each item provided by the iterator. When the iterator is *exhausted*, the suite in the "else" clause, if present, is executed, and the loop terminates. @@ -6096,7 +6337,7 @@ class of the instance or a *non-virtual base class* thereof. The | parameter_list_no_posonly parameter_list_no_posonly: defparameter ("," defparameter)* ["," [parameter_list_starargs]] | parameter_list_starargs - parameter_list_starargs: "*" [star_parameter] ("," defparameter)* ["," [parameter_star_kwargs]] + parameter_list_starargs: "*" star_parameter ("," defparameter)* ["," [parameter_star_kwargs]] | "*" ("," defparameter)+ ["," [parameter_star_kwargs]] | parameter_star_kwargs parameter_star_kwargs: "**" parameter [","] @@ -6369,6 +6610,8 @@ def whats_on_the_telly(penguin=None): * "type", when used in the "type" statement. +* "lazy", when used before an "import" statement. + These syntactically act as keywords in their specific contexts, but this distinction is done at the parser level, not when tokenizing. @@ -6378,6 +6621,8 @@ def whats_on_the_telly(penguin=None): Changed in version 3.12: "type" is now a soft keyword. +Changed in version 3.15: "lazy" is now a soft keyword. + Reserved classes of identifiers =============================== @@ -6587,10 +6832,10 @@ def whats_on_the_telly(penguin=None): 'import': r'''The "import" statement ********************** - import_stmt: "import" module ["as" identifier] ("," module ["as" identifier])* - | "from" relative_module "import" identifier ["as" identifier] + import_stmt: ["lazy"] "import" module ["as" identifier] ("," module ["as" identifier])* + | ["lazy"] "from" relative_module "import" identifier ["as" identifier] ("," identifier ["as" identifier])* - | "from" relative_module "import" "(" identifier ["as" identifier] + | ["lazy"] "from" relative_module "import" "(" identifier ["as" identifier] ("," identifier ["as" identifier])* [","] ")" | "from" relative_module "import" "*" module: (identifier ".")* identifier @@ -6703,6 +6948,91 @@ def whats_on_the_telly(penguin=None): "sys.path", "sys.meta_path", "sys.path_hooks". +Lazy imports +============ + +The "lazy" keyword is a soft keyword that only has special meaning +when it appears immediately before an "import" or "from" statement. +When an import statement is preceded by the "lazy" keyword, the import +becomes *lazy*: the module is not loaded immediately at the import +statement. Instead, a lazy proxy object is created and bound to the +name. The actual module is loaded on first use of that name. + +Lazy imports are only permitted at module scope. Using "lazy" inside a +function, class body, or "try"/"except"/"finally" block raises a +"SyntaxError". Star imports cannot be lazy ("lazy from module import +*" is a syntax error), and future statements cannot be lazy. + +When using "lazy from ... import", each imported name is bound to a +lazy proxy object. The first access to any of these names triggers +loading of the entire module and resolves only that specific name to +its actual value. Other names remain as lazy proxies until they are +accessed. + +Example: + + lazy import json + import sys + + print('json' in sys.modules) # False - json module not yet loaded + + # First use triggers loading + result = json.dumps({"hello": "world"}) + + print('json' in sys.modules) # True - now loaded + +If an error occurs during module loading (such as "ImportError" or +"SyntaxError"), it is raised at the point where the lazy import is +first used, not at the import statement itself. + +See **PEP 810** for the full specification of lazy imports. + +Added in version 3.15. + + +Compatibility via "__lazy_modules__" +------------------------------------ + +As an alternative to using the "lazy" keyword, a module can opt into +lazy loading for specific imports by defining a module-level +"__lazy_modules__" variable. When present, it must be a container of +fully qualified module name strings. Any regular (non-"lazy") +"import" statement at module scope whose target appears in +"__lazy_modules__" is treated as a lazy import, exactly as if the +"lazy" keyword had been used. + +This provides a way to enable lazy loading for specific dependencies +without changing individual "import" statements. This is useful when +supporting Python versions older than 3.15 while using lazy imports in +3.15+: + + __lazy_modules__ = ["json", "pathlib"] + + import json # loaded lazily (name is in __lazy_modules__) + import os # loaded eagerly (name not in __lazy_modules__) + + import pathlib # loaded lazily + +Relative imports are resolved to their absolute name before the +lookup, so "__lazy_modules__" must always contain fully qualified +module names. + +For "from"-style imports, the relevant name is the module following +"from", not the names of its members: + + # In mypackage/mymodule.py + __lazy_modules__ = ["mypackage", "mypackage.sub.utils"] + + from . import helper # loaded lazily: . resolves to mypackage + from .sub.utils import func # loaded lazily: .sub.utils resolves to mypackage.sub.utils + import json # loaded eagerly (not in __lazy_modules__) + +Imports inside functions, class bodies, or "try"/"except"/"finally" +blocks are always eager, regardless of "__lazy_modules__". + +Added in version 3.15. + + Future statements ================= @@ -6902,21 +7232,109 @@ def (parameters): See section Function definitions for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations. +''', + 'lazy': r'''Lazy imports +************ + +The "lazy" keyword is a soft keyword that only has special meaning +when it appears immediately before an "import" or "from" statement. +When an import statement is preceded by the "lazy" keyword, the import +becomes *lazy*: the module is not loaded immediately at the import +statement. Instead, a lazy proxy object is created and bound to the +name. The actual module is loaded on first use of that name. + +Lazy imports are only permitted at module scope. Using "lazy" inside a +function, class body, or "try"/"except"/"finally" block raises a +"SyntaxError". Star imports cannot be lazy ("lazy from module import +*" is a syntax error), and future statements cannot be lazy. + +When using "lazy from ... import", each imported name is bound to a +lazy proxy object. The first access to any of these names triggers +loading of the entire module and resolves only that specific name to +its actual value. Other names remain as lazy proxies until they are +accessed. + +Example: + + lazy import json + import sys + + print('json' in sys.modules) # False - json module not yet loaded + + # First use triggers loading + result = json.dumps({"hello": "world"}) + + print('json' in sys.modules) # True - now loaded + +If an error occurs during module loading (such as "ImportError" or +"SyntaxError"), it is raised at the point where the lazy import is +first used, not at the import statement itself. + +See **PEP 810** for the full specification of lazy imports. + +Added in version 3.15. + + +Compatibility via "__lazy_modules__" +==================================== + +As an alternative to using the "lazy" keyword, a module can opt into +lazy loading for specific imports by defining a module-level +"__lazy_modules__" variable. When present, it must be a container of +fully qualified module name strings. Any regular (non-"lazy") +"import" statement at module scope whose target appears in +"__lazy_modules__" is treated as a lazy import, exactly as if the +"lazy" keyword had been used. + +This provides a way to enable lazy loading for specific dependencies +without changing individual "import" statements. This is useful when +supporting Python versions older than 3.15 while using lazy imports in +3.15+: + + __lazy_modules__ = ["json", "pathlib"] + + import json # loaded lazily (name is in __lazy_modules__) + import os # loaded eagerly (name not in __lazy_modules__) + + import pathlib # loaded lazily + +Relative imports are resolved to their absolute name before the +lookup, so "__lazy_modules__" must always contain fully qualified +module names. + +For "from"-style imports, the relevant name is the module following +"from", not the names of its members: + + # In mypackage/mymodule.py + __lazy_modules__ = ["mypackage", "mypackage.sub.utils"] + + from . import helper # loaded lazily: . resolves to mypackage + from .sub.utils import func # loaded lazily: .sub.utils resolves to mypackage.sub.utils + import json # loaded eagerly (not in __lazy_modules__) + +Imports inside functions, class bodies, or "try"/"except"/"finally" +blocks are always eager, regardless of "__lazy_modules__". + +Added in version 3.15. ''', 'lists': r'''List displays ************* -A list display is a possibly empty series of expressions enclosed in -square brackets: +A *list display* is a possibly empty series of expressions enclosed in +square brackets. For example: - list_display: "[" [flexible_expression_list | comprehension] "]" + >>> ["one", "two", "three"] + ['one', 'two', 'three'] + >>> ["one"] # One-element list + ['one'] + >>> [] # empty list + [] -A list display yields a new list object, the contents being specified -by either a list of expressions or a comprehension. When a comma- -separated list of expressions is supplied, its elements are evaluated -from left to right and placed into the list object in that order. -When a comprehension is supplied, the list is constructed from the -elements resulting from the comprehension. +See Container displays for general information on displays. + +The formal grammar for list displays is: + + list: '[' [flexible_expression_list] ']' ''', 'match': r'''The "match" statement ********************* @@ -7154,7 +7572,7 @@ def (parameters): | "None" | "True" | "False" - signed_number: ["-"] NUMBER + signed_number: ["+" | "-"] NUMBER The rule "strings" and the token "NUMBER" are defined in the standard Python grammar. Triple-quoted strings are supported. Raw strings and @@ -7478,6 +7896,8 @@ def (parameters): * "float" + * "frozendict" + * "frozenset" * "int" @@ -9054,11 +9474,11 @@ class C: pass # a class with no methods (yet) object.__hash__(self) Called by built-in function "hash()" and for operations on members - of hashed collections including "set", "frozenset", and "dict". - The "__hash__()" method should return an integer. The only required - property is that objects which compare equal have the same hash - value; it is advised to mix together the hash values of the - components of the object that also play a part in comparison of + of hashed collections including "set", "frozenset", "dict", and + "frozendict". The "__hash__()" method should return an integer. The + only required property is that objects which compare equal have the + same hash value; it is advised to mix together the hash values of + the components of the object that also play a part in comparison of objects by packing them into a tuple and hashing the tuple. Example: @@ -9449,9 +9869,10 @@ class to a new value, *value*. renders the meaning of the program undefined. In the future, a check may be added to prevent this. -* "TypeError" will be raised if nonempty *__slots__* are defined for a - class derived from a ""variable-length" built-in type" such as - "int", "bytes", and "tuple". +* "TypeError" will be raised if *__slots__* other than *__dict__* and + *__weakref__* are defined for a class derived from a ""variable- + length" built-in type" such as "int", "bytes", and "type", except + "tuple". * Any non-string *iterable* may be assigned to *__slots__*. @@ -9472,6 +9893,10 @@ class derived from a ""variable-length" built-in type" such as created for each of the iterator’s values. However, the *__slots__* attribute will be an empty iterator. +Changed in version 3.15: Allowed defining the *__dict__* and +*__weakref__* *__slots__* for any class. Allowed defining any +*__slots__* for a class derived from "tuple". + Customizing class creation ========================== @@ -10530,7 +10955,7 @@ class is used in a class pattern with positional arguments, each >>> 'straße'.casefold() 'strasse' - The casefolding algorithm is described in section 3.13 ‘Default + The casefolding algorithm is described in section 3.13.3 ‘Default Case Folding’ of the Unicode Standard. Added in version 3.3. @@ -10754,7 +11179,7 @@ class is used in a class pattern with positional arguments, each characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is - different from the Alphabetic property defined in the section 4.10 + different from the Alphabetic property defined in section 4.10 ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard. For example: @@ -10985,8 +11410,8 @@ class is used in a class pattern with positional arguments, each >>> 'Lower Method Example'.lower() 'lower method example' - The lowercasing algorithm used is described in section 3.13 - ‘Default Case Folding’ of the Unicode Standard. + The lowercasing algorithm used is described in section 3.13.2 + ‘Default Case Conversion’ of the Unicode Standard. str.lstrip(chars=None, /) @@ -11026,6 +11451,8 @@ class is used in a class pattern with positional arguments, each a third argument, it must be a string, whose characters will be mapped to "None" in the result. + Changed in version 3.15: *dict* can now be a "frozendict". + str.partition(sep, /) Split the string at the first occurrence of *sep*, and return a @@ -11162,9 +11589,9 @@ class is used in a class pattern with positional arguments, each Return a list of the words in the string, using *sep* as the delimiter string. If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost* ones. If *sep* is not specified or - "None", any whitespace string is a separator. Except for splitting - from the right, "rsplit()" behaves like "split()" which is - described in detail below. + "None", any "whitespace" string is a separator. Except for + splitting from the right, "rsplit()" behaves like "split()" which + is described in detail below. str.rstrip(chars=None, /) @@ -11216,7 +11643,7 @@ class is used in a class pattern with positional arguments, each ['1', '2', '3<4'] If *sep* is not specified or is "None", a different splitting - algorithm is applied: runs of consecutive whitespace are regarded + algorithm is applied: runs of consecutive "whitespace" are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string @@ -11422,6 +11849,12 @@ class is used in a class pattern with positional arguments, each You can use "str.maketrans()" to create a translation map from character-to-character mappings in different formats. + The following example uses a mapping to replace "'a'" with "'X'", + "'b'" with "'Y'", and delete "'c'": + + >>> 'abc123'.translate({ord('a'): 'X', ord('b'): 'Y', ord('c'): None}) + 'XY123' + See also the "codecs" module for a more flexible approach to custom character mappings. @@ -11433,8 +11866,8 @@ class is used in a class pattern with positional arguments, each category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase). - The uppercasing algorithm used is described in section 3.13 - ‘Default Case Folding’ of the Unicode Standard. + The uppercasing algorithm used is described in section 3.13.2 + ‘Default Case Conversion’ of the Unicode Standard. str.zfill(width, /) @@ -12717,7 +13150,7 @@ def foo(): target of assignments or "del" statements. The built-in function "len()" returns the number of items in a mapping. -There is currently a single intrinsic mapping type: +There are two intrinsic mapping types: Dictionaries @@ -12751,6 +13184,18 @@ def foo(): rather than a language guarantee. +Frozen dictionaries +------------------- + +These represent an immutable dictionary. They are created by the +built-in "frozendict()" constructor. A frozendict is *hashable* if +all of its keys and values are hashable, in which case it can be used +as an element of a set, or as a key in another mapping. "frozendict" +is not a subclass of "dict"; it inherits directly from "object". + +Added in version 3.15. + + Callable types ============== @@ -12914,12 +13359,12 @@ def foo(): Generator functions ------------------- -A function or method which uses the "yield" statement (see section The -yield statement) is called a *generator function*. Such a function, +A function or method which contains a "yield" expression (see section +Yield expressions) is called a *generator function*. Such a function, when called, always returns an *iterator* object which can be used to execute the body of the function: calling the iterator’s "iterator.__next__()" method will cause the function to execute until -it provides a value using the "yield" statement. When the function +it provides a value using the "yield" expression. When the function executes a "return" statement or falls off the end, a "StopIteration" exception is raised and the iterator will have reached the end of the set of values to be returned. @@ -12938,11 +13383,11 @@ def foo(): Asynchronous generator functions -------------------------------- -A function or method which is defined using "async def" and which uses -the "yield" statement is called a *asynchronous generator function*. -Such a function, when called, returns an *asynchronous iterator* -object which can be used in an "async for" statement to execute the -body of the function. +A function or method which is defined using "async def" and which +contains a "yield" expression is called a *asynchronous generator +function*. Such a function, when called, returns an *asynchronous +iterator* object which can be used in an "async for" statement to +execute the body of the function. Calling the asynchronous iterator’s "aiterator.__anext__" method will return an *awaitable* which when awaited will execute until it @@ -12965,7 +13410,8 @@ def foo(): * "__name__" is the function’s name. See "function.__name__". -* "__self__" is set to "None" (but see the next item). +* "__self__" is the module object the function was defined in or + "None" if unavailable. * "__module__" is the name of the module the function was defined in or "None" if unavailable. See "function.__module__". @@ -13108,7 +13554,7 @@ def foo(): "ImportWarning" when falling back to "__package__" during import resolution. - Deprecated since version 3.13, will be removed in version 3.15: + Deprecated since version 3.13, removed in version 3.15: "__package__" will cease to be set or taken into consideration by the import system or standard library. @@ -13152,41 +13598,21 @@ def foo(): module.__file__ -module.__cached__ - - "__file__" and "__cached__" are both optional attributes that may - or may not be set. Both attributes should be a "str" when they are - available. - - "__file__" indicates the pathname of the file from which the module - was loaded (if loaded from a file), or the pathname of the shared - library file for extension modules loaded dynamically from a shared - library. It might be missing for certain types of modules, such as - C modules that are statically linked into the interpreter, and the - import system may opt to leave it unset if it has no semantic - meaning (for example, a module loaded from a database). - - If "__file__" is set then the "__cached__" attribute might also be - set, which is the path to any compiled version of the code (for - example, a byte-compiled file). The file does not need to exist to - set this attribute; the path can simply point to where the compiled - file *would* exist (see **PEP 3147**). - - Note that "__cached__" may be set even if "__file__" is not set. - However, that scenario is quite atypical. Ultimately, the *loader* - is what makes use of the module spec provided by the *finder* (from - which "__file__" and "__cached__" are derived). So if a loader can - load from a cached module but otherwise does not load from a file, - that atypical scenario may be appropriate. + "__file__" is an optional attribute that may or may not be set. + Both attributes should be a "str" when they are available. - It is **strongly** recommended that you use - "module.__spec__.cached" instead of "module.__cached__". + An optional attribute, "__file__" indicates the pathname of the + file from which the module was loaded (if loaded from a file), or + the pathname of the shared library file for extension modules + loaded dynamically from a shared library. It might be missing for + certain types of modules, such as C modules that are statically + linked into the interpreter, and the import system may opt to leave + it unset if it has no semantic meaning (for example, a module + loaded from a database). - Deprecated since version 3.13, will be removed in version 3.15: - Setting "__cached__" on a module while failing to set - "__spec__.cached" is deprecated. In Python 3.15, "__cached__" will - cease to be set or taken into consideration by the import system or - standard library. +Changed in version 3.15: The "__cached__" attribute is no longer set +on modules or taken into consideration by the import system or +standard library. Other writable attributes on module objects @@ -13216,6 +13642,19 @@ def foo(): Added in version 3.14. +module.__lazy_modules__ + + A container (an object implementing "__contains__()") of fully + qualified module name strings. When defined at module scope, any + regular "import" statement in that module whose target module name + appears in this container is treated as a lazy import, as if the + "lazy" keyword had been used. Imports inside functions, class + bodies, or "try"/"except"/"finally" blocks are unaffected. + + See Compatibility via __lazy_modules__ for details and examples. + + Added in version 3.15. + Module dictionaries ------------------- @@ -13512,11 +13951,14 @@ class instance has a namespace implemented as a dictionary which is +----------------------------------------------------+----------------------------------------------------+ | codeobject.co_firstlineno | The line number of the first line of the function | +----------------------------------------------------+----------------------------------------------------+ -| codeobject.co_lnotab | A string encoding the mapping from *bytecode* | -| | offsets to line numbers. For details, see the | -| | source code of the interpreter. Deprecated since | -| | version 3.12: This attribute of code objects is | -| | deprecated, and may be removed in Python 3.15. | +| codeobject.co_linetable | A "bytes" object containing encoded source | +| | location information. The exact format is an | +| | implementation detail and may change between | +| | Python versions. Use "co_lines()" and | +| | "co_positions()" for supported access to line and | +| | position information. To create a modified copy of | +| | a code object, use "replace()". Added in version | +| | 3.10. | +----------------------------------------------------+----------------------------------------------------+ | codeobject.co_stacksize | The required stack size of the code object | +----------------------------------------------------+----------------------------------------------------+ @@ -13785,6 +14227,10 @@ class instance has a namespace implemented as a dictionary which is Slice objects are used to represent slices for "__getitem__()" methods. They are also created by the built-in "slice()" function. +Added in version 3.15: The "slice()" type now supports subscription. +For example, "slice[float]" may be used in type annotations to +indicate a slice containing "float" objects. + Special read-only attributes: "start" is the lower bound; "stop" is the upper bound; "step" is the step value; each is "None" if omitted. These attributes can have any type. @@ -13838,13 +14284,15 @@ class instance has a namespace implemented as a dictionary which is See Function definitions for more information. ''', - 'typesmapping': r'''Mapping Types — "dict" -********************** + 'typesmapping': r'''Mapping types — "dict", "frozendict" +************************************ -A *mapping* object maps *hashable* values to arbitrary objects. -Mappings are mutable objects. There is currently only one standard -mapping type, the *dictionary*. (For other containers see the built- -in "list", "set", and "tuple" classes, and the "collections" module.) +A *mapping* object maps *hashable* values to arbitrary objects. There +are currently two standard mapping types, the *dictionary* and +"frozendict". (For other containers see the built-in "list", "set", +and "tuple" classes, and the "collections" module.) See Time +complexity of operations on built-in types for the costs of the +various dictionary operations. A dictionary’s keys are *almost* arbitrary values. Values that are not *hashable*, that is, values containing lists, dictionaries or @@ -14121,10 +14569,10 @@ class dict(iterable, /, **kwargs) Changed in version 3.8: Dictionaries are now reversible. -See also: + See also: - "types.MappingProxyType" can be used to create a read-only view of a - "dict". + "frozendict" and "types.MappingProxyType" can be used to create a + read-only view of a "dict". See also: @@ -14234,13 +14682,65 @@ class dict(iterable, /, **kwargs) mappingproxy({'bacon': 1, 'spam': 500}) >>> values.mapping['spam'] 500 + + +Frozen dictionaries +=================== + +class frozendict(**kwargs) +class frozendict(mapping, /, **kwargs) +class frozendict(iterable, /, **kwargs) + + Return a new frozen dictionary initialized from an optional + positional argument and a possibly empty set of keyword arguments. + + A "frozendict" has a similar API to the "dict" API, with the + following differences: + + * "dict" has more methods than "frozendict": + + * "__delitem__()" + + * "__setitem__()" + + * "clear()" + + * "pop()" + + * "popitem()" + + * "setdefault()" + + * "update()" + + * A "frozendict" can be hashed with "hash(frozendict)" if all keys + and values can be hashed. + + * "frozendict |= other" does not modify the "frozendict" in-place + but creates a new frozen dictionary. + + "frozendict" is not a "dict" subclass but inherits directly from + "object". + + Like dictionaries, frozendicts are generic over two types, + signifying (respectively) the types of the frozendict’s keys and + values. + + classmethod fromkeys(iterable, value=None, /) + + Similar to "dict.fromkeys()", but call again the type + constructor with an initialized "frozendict" if the type is a + "frozendict" subclass or if the constructor returned a + "frozendict". + + Added in version 3.15. ''', 'typesmethods': r'''Methods ******* Methods are functions that are called using the attribute notation. There are two flavors: built-in methods (such as "append()" on lists) -and class instance method. Built-in methods are described with the +and class instance methods. Built-in methods are described with the types that support them. If you access a method (a function defined in a class namespace) @@ -14324,6 +14824,9 @@ class dict(iterable, /, **kwargs) operations have the same priority as the corresponding numeric operations. [3] +See Time complexity of operations on built-in types for the costs of +the various sequence operations. + +----------------------------+----------------------------------+------------+ | Operation | Result | Notes | |============================|==================================|============| @@ -14589,8 +15092,8 @@ class dict(iterable, /, **kwargs) sequence.pop(index=-1, /) - Retrieve the item at *index* and also removes it from *sequence*. - By default, the last item in *sequence* is removed and returned. + Retrieve the item at *index* and also remove it from *sequence*. By + default, the last item in *sequence* is removed and returned. sequence.remove(value, /) @@ -14948,8 +15451,8 @@ class range(start, stop, step=1, /) sequence.pop(index=-1, /) - Retrieve the item at *index* and also removes it from *sequence*. - By default, the last item in *sequence* is removed and returned. + Retrieve the item at *index* and also remove it from *sequence*. By + default, the last item in *sequence* is removed and returned. sequence.remove(value, /) diff --git a/Lib/queue.py b/Lib/queue.py index c0b35987654..80db0b978b9 100644 --- a/Lib/queue.py +++ b/Lib/queue.py @@ -346,7 +346,9 @@ def get(self, block=True, timeout=None): available, else raise the Empty exception ('timeout' is ignored in that case). ''' - if timeout is not None and timeout < 0: + if not block: + timeout = None + elif timeout is not None and timeout < 0: raise ValueError("'timeout' must be a non-negative number") if not self._count.acquire(block, timeout): raise Empty diff --git a/Lib/random.py b/Lib/random.py index 0e6a183d179..7db76103450 100644 --- a/Lib/random.py +++ b/Lib/random.py @@ -1020,26 +1020,26 @@ def _test(N=10_000): def _parse_args(arg_list: list[str] | None): import argparse parser = argparse.ArgumentParser( - formatter_class=argparse.RawTextHelpFormatter, color=True) + formatter_class=argparse.RawTextHelpFormatter) group = parser.add_mutually_exclusive_group() group.add_argument( "-c", "--choice", nargs="+", help="print a random choice") group.add_argument( "-i", "--integer", type=int, metavar="N", - help="print a random integer between 1 and N inclusive") + help="print a random integer between 1 and `N` inclusive") group.add_argument( "-f", "--float", type=float, metavar="N", - help="print a random floating-point number between 0 and N inclusive") + help="print a random floating-point number between 0 and `N` inclusive") group.add_argument( "--test", type=int, const=10_000, nargs="?", help=argparse.SUPPRESS) parser.add_argument("input", nargs="*", help="""\ if no options given, output depends on the input - string or multiple: same as --choice - integer: same as --integer - float: same as --float""") + string or multiple: same as `--choice` + integer: same as `--integer` + float: same as `--float`""") args = parser.parse_args(arg_list) return args, parser.format_help() diff --git a/Lib/re/__init__.py b/Lib/re/__init__.py index af2808a77da..e6d29fd7a40 100644 --- a/Lib/re/__init__.py +++ b/Lib/re/__init__.py @@ -85,17 +85,18 @@ \\ Matches a literal backslash. This module exports the following functions: - match Match a regular expression pattern to the beginning of a string. - fullmatch Match a regular expression pattern to all of a string. - search Search a string for the presence of a pattern. - sub Substitute occurrences of a pattern found in a string. - subn Same as sub, but also return the number of substitutions made. - split Split a string by the occurrences of a pattern. - findall Find all occurrences of a pattern in a string. - finditer Return an iterator yielding a Match object for each match. - compile Compile a pattern into a Pattern object. - purge Clear the regular expression cache. - escape Backslash all non-alphanumerics in a string. + prefixmatch Match a regular expression pattern to the beginning of a str. + match The original name of prefixmatch prior to 3.15. + fullmatch Match a regular expression pattern to all of a string. + search Search a string for the presence of a pattern. + sub Substitute occurrences of a pattern found in a string. + subn Same as sub, but also return the number of substitutions made. + split Split a string by the occurrences of a pattern. + findall Find all occurrences of a pattern in a string. + finditer Return an iterator yielding a Match object for each match. + compile Compile a pattern into a Pattern object. + purge Clear the regular expression cache. + escape Backslash all non-alphanumerics in a string. Each function other than purge and escape can take an optional 'flags' argument consisting of one or more of the following module constants, joined by "|". @@ -130,15 +131,13 @@ # public symbols __all__ = [ - "match", "fullmatch", "search", "sub", "subn", "split", + "prefixmatch", "match", "fullmatch", "search", "sub", "subn", "split", "findall", "finditer", "compile", "purge", "escape", "error", "Pattern", "Match", "A", "I", "L", "M", "S", "X", "U", "ASCII", "IGNORECASE", "LOCALE", "MULTILINE", "DOTALL", "VERBOSE", "UNICODE", "NOFLAG", "RegexFlag", "PatternError" ] -__version__ = "2.2.1" - @enum.global_enum @enum._simple_enum(enum.IntFlag, boundary=enum.KEEP) class RegexFlag: @@ -161,10 +160,13 @@ class RegexFlag: # -------------------------------------------------------------------- # public interface -def match(pattern, string, flags=0): +def prefixmatch(pattern, string, flags=0): """Try to apply the pattern at the start of the string, returning a Match object, or None if no match was found.""" - return _compile(pattern, flags).match(string) + return _compile(pattern, flags).prefixmatch(string) + +# Our original name which was less explicitly clear about the behavior for prefixmatch. +match = prefixmatch def fullmatch(pattern, string, flags=0): """Try to apply the pattern to all of the string, returning @@ -313,7 +315,7 @@ def escape(pattern): return pattern.translate(_special_chars_map).encode('latin1') Pattern = type(_compiler.compile('', 0)) -Match = type(_compiler.compile('', 0).match('')) +Match = type(_compiler.compile('', 0).prefixmatch('')) # -------------------------------------------------------------------- # internals @@ -399,9 +401,12 @@ def __init__(self, lexicon, flags=0): s = _parser.State() s.flags = flags for phrase, action in lexicon: + sub_pattern = _parser.parse(phrase, flags) + if sub_pattern.state.groups != 1: + raise ValueError("Cannot use capturing groups in re.Scanner") gid = s.opengroup() p.append(_parser.SubPattern(s, [ - (SUBPATTERN, (gid, 0, 0, _parser.parse(phrase, flags))), + (SUBPATTERN, (gid, 0, 0, sub_pattern)), ])) s.closegroup(gid, p[-1]) p = _parser.SubPattern(s, [(BRANCH, (None, p))]) @@ -409,10 +414,10 @@ def __init__(self, lexicon, flags=0): def scan(self, string): result = [] append = result.append - match = self.scanner.scanner(string).match + _match = self.scanner.scanner(string).prefixmatch i = 0 while True: - m = match() + m = _match() if not m: break j = m.end() @@ -426,3 +431,12 @@ def scan(self, string): append(action) i = j return result, string[i:] + + +def __getattr__(name): + if name == "__version__": + from warnings import _deprecated + + _deprecated("__version__", remove=(3, 20)) + return "2.2.1" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/Lib/re/_compiler.py b/Lib/re/_compiler.py index 20dd561d1c1..c2ca8e25abe 100644 --- a/Lib/re/_compiler.py +++ b/Lib/re/_compiler.py @@ -375,7 +375,7 @@ def _optimize_charset(charset, iscased=None, fixup=None, fixes=None): # less significant byte is a bit index in the chunk (just like the # CHARSET matching). - charmap = bytes(charmap) # should be hashable + charmap = charmap.take_bytes() # should be hashable comps = {} mapping = bytearray(256) block = 0 diff --git a/Lib/re/_parser.py b/Lib/re/_parser.py index 35ab7ede2a7..bd189fe0695 100644 --- a/Lib/re/_parser.py +++ b/Lib/re/_parser.py @@ -455,7 +455,6 @@ def _parse_sub(source, state, verbose, nested): items = [] itemsappend = items.append sourcematch = source.match - start = source.tell() while True: itemsappend(_parse(source, state, verbose, nested + 1, not nested and not items)) diff --git a/Lib/rlcompleter.py b/Lib/rlcompleter.py index e75dd0a9e3d..6c6d9bb6b34 100644 --- a/Lib/rlcompleter.py +++ b/Lib/rlcompleter.py @@ -34,9 +34,9 @@ import inspect import keyword import re -import types import __main__ import warnings +import types __all__ = ["Completer"] @@ -189,7 +189,17 @@ def attr_matches(self, text): # arbitrary code or raise exceptions. matches.append(match) continue - if (value := getattr(thisobject, word, None)) is not None: + + if (isinstance(thisobject, types.ModuleType) + and + isinstance(thisobject.__dict__.get(word), + types.LazyImportType) + ): + value = thisobject.__dict__.get(word) + else: + value = getattr(thisobject, word, None) + + if value is not None: matches.append(self._callable_postfix(value, match)) else: matches.append(match) diff --git a/Lib/runpy.py b/Lib/runpy.py index 1d5ecf0cf15..a535b4f651a 100644 --- a/Lib/runpy.py +++ b/Lib/runpy.py @@ -80,7 +80,6 @@ def _run_code(code, run_globals, init_globals=None, pkg_name = mod_spec.parent run_globals.update(__name__ = mod_name, __file__ = fname, - __cached__ = cached, __doc__ = None, __loader__ = loader, __package__ = pkg_name, @@ -185,7 +184,6 @@ def _run_module_as_main(mod_name, alter_argv=True): At the very least, these variables in __main__ will be overwritten: __name__ __file__ - __cached__ __loader__ __package__ """ @@ -254,7 +252,7 @@ def _get_main_module_details(error=ImportError): sys.modules[main_name] = saved_main -def _get_code_from_file(fname): +def _get_code_from_file(fname, module): # Check for a compiled file first from pkgutil import read_code code_path = os.path.abspath(fname) @@ -263,7 +261,7 @@ def _get_code_from_file(fname): if code is None: # That didn't work, so try it as normal source code with io.open_code(code_path) as f: - code = compile(f.read(), fname, 'exec') + code = compile(f.read(), fname, 'exec', module=module) return code def run_path(path_name, init_globals=None, run_name=None): @@ -290,7 +288,7 @@ def run_path(path_name, init_globals=None, run_name=None): if isinstance(importer, type(None)): # Not a valid sys.path entry, so run the code directly # execfile() doesn't help as we want to allow compiled files - code = _get_code_from_file(path_name) + code = _get_code_from_file(path_name, run_name) return _run_module_code(code, init_globals, run_name, pkg_name=pkg_name, script_name=path_name) else: diff --git a/Lib/shelve.py b/Lib/shelve.py index 50584716e9e..9f6296667fd 100644 --- a/Lib/shelve.py +++ b/Lib/shelve.py @@ -56,12 +56,16 @@ the persistent dictionary on disk, if feasible). """ -from pickle import DEFAULT_PROTOCOL, Pickler, Unpickler -from io import BytesIO +from pickle import DEFAULT_PROTOCOL, dumps, loads import collections.abc -__all__ = ["Shelf", "BsdDbShelf", "DbfilenameShelf", "open"] +__all__ = ["ShelveError", "Shelf", "BsdDbShelf", "DbfilenameShelf", "open"] + + +class ShelveError(Exception): + pass + class _ClosedDict(collections.abc.MutableMapping): 'Marker for a closed dict. Access attempts raise a ValueError.' @@ -82,7 +86,7 @@ class Shelf(collections.abc.MutableMapping): """ def __init__(self, dict, protocol=None, writeback=False, - keyencoding="utf-8"): + keyencoding="utf-8", *, serializer=None, deserializer=None): self.dict = dict if protocol is None: protocol = DEFAULT_PROTOCOL @@ -91,6 +95,16 @@ def __init__(self, dict, protocol=None, writeback=False, self.cache = {} self.keyencoding = keyencoding + if serializer is None and deserializer is None: + self.serializer = dumps + self.deserializer = loads + elif (serializer is None) ^ (deserializer is None): + raise ShelveError("serializer and deserializer must be " + "defined together") + else: + self.serializer = serializer + self.deserializer = deserializer + def __iter__(self): for k in self.dict.keys(): yield k.decode(self.keyencoding) @@ -110,8 +124,8 @@ def __getitem__(self, key): try: value = self.cache[key] except KeyError: - f = BytesIO(self.dict[key.encode(self.keyencoding)]) - value = Unpickler(f).load() + f = self.dict[key.encode(self.keyencoding)] + value = self.deserializer(f) if self.writeback: self.cache[key] = value return value @@ -119,10 +133,8 @@ def __getitem__(self, key): def __setitem__(self, key, value): if self.writeback: self.cache[key] = value - f = BytesIO() - p = Pickler(f, self._protocol) - p.dump(value) - self.dict[key.encode(self.keyencoding)] = f.getvalue() + serialized_value = self.serializer(value, self._protocol) + self.dict[key.encode(self.keyencoding)] = serialized_value def __delitem__(self, key): del self.dict[key.encode(self.keyencoding)] @@ -171,6 +183,11 @@ def sync(self): if hasattr(self.dict, 'sync'): self.dict.sync() + def reorganize(self): + self.sync() + if hasattr(self.dict, 'reorganize'): + self.dict.reorganize() + class BsdDbShelf(Shelf): """Shelf implementation using the "BSD" db interface. @@ -186,33 +203,29 @@ class BsdDbShelf(Shelf): """ def __init__(self, dict, protocol=None, writeback=False, - keyencoding="utf-8"): - Shelf.__init__(self, dict, protocol, writeback, keyencoding) + keyencoding="utf-8", *, serializer=None, deserializer=None): + Shelf.__init__(self, dict, protocol, writeback, keyencoding, + serializer=serializer, deserializer=deserializer) def set_location(self, key): (key, value) = self.dict.set_location(key) - f = BytesIO(value) - return (key.decode(self.keyencoding), Unpickler(f).load()) + return (key.decode(self.keyencoding), self.deserializer(value)) def next(self): (key, value) = next(self.dict) - f = BytesIO(value) - return (key.decode(self.keyencoding), Unpickler(f).load()) + return (key.decode(self.keyencoding), self.deserializer(value)) def previous(self): (key, value) = self.dict.previous() - f = BytesIO(value) - return (key.decode(self.keyencoding), Unpickler(f).load()) + return (key.decode(self.keyencoding), self.deserializer(value)) def first(self): (key, value) = self.dict.first() - f = BytesIO(value) - return (key.decode(self.keyencoding), Unpickler(f).load()) + return (key.decode(self.keyencoding), self.deserializer(value)) def last(self): (key, value) = self.dict.last() - f = BytesIO(value) - return (key.decode(self.keyencoding), Unpickler(f).load()) + return (key.decode(self.keyencoding), self.deserializer(value)) class DbfilenameShelf(Shelf): @@ -222,9 +235,11 @@ class DbfilenameShelf(Shelf): See the module's __doc__ string for an overview of the interface. """ - def __init__(self, filename, flag='c', protocol=None, writeback=False): + def __init__(self, filename, flag='c', protocol=None, writeback=False, *, + serializer=None, deserializer=None): import dbm - Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) + Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback, + serializer=serializer, deserializer=deserializer) def clear(self): """Remove all items from the shelf.""" @@ -233,8 +248,8 @@ def clear(self): self.cache.clear() self.dict.clear() - -def open(filename, flag='c', protocol=None, writeback=False): +def open(filename, flag='c', protocol=None, writeback=False, *, + serializer=None, deserializer=None): """Open a persistent dictionary for reading and writing. The filename parameter is the base filename for the underlying @@ -247,4 +262,5 @@ def open(filename, flag='c', protocol=None, writeback=False): See the module's __doc__ string for an overview of the interface. """ - return DbfilenameShelf(filename, flag, protocol, writeback) + return DbfilenameShelf(filename, flag, protocol, writeback, + serializer=serializer, deserializer=deserializer) diff --git a/Lib/shutil.py b/Lib/shutil.py index a3a112f6954..0086c1c96c1 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -745,6 +745,7 @@ def _rmtree_safe_fd_step(stack, onexc): # save a call to os.lstat() when walking subdirectories. func, dirfd, path, orig_entry = stack.pop() name = path if orig_entry is None else orig_entry.name + parent_fd = None if func is os.close else dirfd try: if func is os.close: os.close(dirfd) @@ -792,14 +793,14 @@ def _rmtree_safe_fd_step(stack, onexc): except FileNotFoundError: continue except OSError as err: - onexc(os.unlink, fullname, err) + onexc(os.unlink, fullname, err, direntry=entry, dir_fd=topfd) except FileNotFoundError as err: if orig_entry is None or func is os.close: err.filename = path - onexc(func, path, err) + onexc(func, path, err, direntry=orig_entry, dir_fd=parent_fd) except OSError as err: err.filename = path - onexc(func, path, err) + onexc(func, path, err, direntry=orig_entry, dir_fd=parent_fd) _use_fd_functions = ({os.open, os.stat, os.unlink, os.rmdir} <= os.supports_dir_fd and @@ -807,7 +808,8 @@ def _rmtree_safe_fd_step(stack, onexc): os.stat in os.supports_follow_symlinks) _rmtree_impl = _rmtree_safe_fd if _use_fd_functions else _rmtree_unsafe -def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None): +def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None, + _onexc_kwargs=False): """Recursively delete a directory tree. If dir_fd is not None, it should be a file descriptor open to a directory; @@ -830,24 +832,29 @@ def rmtree(path, ignore_errors=False, onerror=None, *, onexc=None, dir_fd=None): sys.audit("shutil.rmtree", path, dir_fd) if ignore_errors: - def onexc(*args): + def onexc(*args, **kwargs): pass elif onerror is None and onexc is None: - def onexc(*args): + def onexc(*args, **kwargs): raise elif onexc is None: if onerror is None: - def onexc(*args): + def onexc(*args, **kwargs): raise else: # delegate to onerror - def onexc(*args): + def onexc(*args, **kwargs): func, path, exc = args if exc is None: exc_info = None, None, None else: exc_info = type(exc), exc, exc.__traceback__ return onerror(func, path, exc_info) + elif not _onexc_kwargs: + # Only the internal caller in tempfile asks for the extra arguments. + _onexc = onexc + def onexc(func, path, err, **kwargs): + return _onexc(func, path, err) _rmtree_impl(path, dir_fd, onexc) @@ -1216,19 +1223,22 @@ def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, for arg, val in format_info[1]: kwargs[arg] = val + base_name = os.fspath(base_name) + if base_dir is None: base_dir = os.curdir + else: + base_dir = os.fspath(base_dir) supports_root_dir = getattr(func, 'supports_root_dir', False) save_cwd = None if root_dir is not None: + root_dir = os.fspath(root_dir) stmd = os.stat(root_dir).st_mode if not stat.S_ISDIR(stmd): raise NotADirectoryError(errno.ENOTDIR, 'Not a directory', root_dir) if supports_root_dir: - # Support path-like base_name here for backwards-compatibility. - base_name = os.fspath(base_name) kwargs['root_dir'] = root_dir else: save_cwd = os.getcwd() diff --git a/Lib/site-packages/README.txt b/Lib/site-packages/README.txt new file mode 100644 index 00000000000..273f6251a7f --- /dev/null +++ b/Lib/site-packages/README.txt @@ -0,0 +1,2 @@ +This directory exists so that 3rd party packages can be installed +here. Read the source for site.py for more details. diff --git a/Lib/site.py b/Lib/site.py index b6d840fb23a..72bdf0b9f19 100644 --- a/Lib/site.py +++ b/Lib/site.py @@ -18,55 +18,26 @@ it is also checked for site-packages (sys.base_prefix and sys.base_exec_prefix will always be the "real" prefixes of the Python installation). If "pyvenv.cfg" (a bootstrap configuration file) contains -the key "include-system-site-packages" set to anything other than "false" -(case-insensitive), the system-level prefixes will still also be -searched for site-packages; otherwise they won't. - -All of the resulting site-specific directories, if they exist, are -appended to sys.path, and also inspected for path configuration -files. - -A path configuration file is a file whose name has the form -.pth; its contents are additional directories (one per line) -to be added to sys.path. Non-existing directories (or -non-directories) are never added to sys.path; no directory is added to -sys.path more than once. Blank lines and lines beginning with -'#' are skipped. Lines starting with 'import' are executed. - -For example, suppose sys.prefix and sys.exec_prefix are set to -/usr/local and there is a directory /usr/local/lib/python2.5/site-packages -with three subdirectories, foo, bar and spam, and two path -configuration files, foo.pth and bar.pth. Assume foo.pth contains the -following: - - # foo package configuration - foo - bar - bletch - -and bar.pth contains: - - # bar package configuration - bar - -Then the following directories are added to sys.path, in this order: - - /usr/local/lib/python2.5/site-packages/bar - /usr/local/lib/python2.5/site-packages/foo - -Note that bletch is omitted because it doesn't exist; bar precedes foo -because bar.pth comes alphabetically before foo.pth; and spam is -omitted because it is not mentioned in either path configuration file. - -The readline module is also automatically configured to enable -completion for systems that support it. This can be overridden in -sitecustomize, usercustomize or PYTHONSTARTUP. Starting Python in -isolated mode (-I) disables automatic readline configuration. - -After these operations, an attempt is made to import a module -named sitecustomize, which can perform arbitrary additional -site-specific customizations. If this import fails with an -ImportError exception, it is silently ignored. +the key "include-system-site-packages" set to "true" (case-insensitive), +the system-level prefixes will still also be searched for site-packages; +otherwise they won't. + +Two kinds of configuration files are processed in each site-packages +directory: + +- .pth files extend sys.path with additional directories (one per + line). Lines starting with "import" are deprecated (see PEP 829). + +- .start files specify startup entry points using the pkg.mod:callable + syntax. These are resolved via pkgutil.resolve_name() and called with no + arguments. + +When called from main(), all .pth path extensions are applied before any +.start entry points are executed, ensuring that paths are available before +startup code runs. + +See the documentation for the site module for full details: +https://docs.python.org/3/library/site.html """ import sys @@ -77,6 +48,11 @@ import stat import errno +lazy import locale +lazy import pkgutil +lazy import traceback +lazy import warnings + # Prefixes for site-packages; add additional prefixes like /usr/local here PREFIXES = [sys.prefix, sys.exec_prefix] # Enable per user site-packages directory @@ -90,17 +66,34 @@ USER_BASE = None -def _trace(message): +def _trace(message, exc=None): if sys.flags.verbose: - print(message, file=sys.stderr) + _print_error(message, exc) -def _warn(*args, **kwargs): - import warnings +def _print_error(message, exc=None): + """Print an error message to stderr, optionally with a formatted traceback.""" + print(message, file=sys.stderr) + if exc is not None: + for record in traceback.format_exception(exc): + for line in record.splitlines(): + print(' ' + line, file=sys.stderr) + +def _warn(*args, **kwargs): warnings.warn(*args, **kwargs) +def _warn_future_us(message, remove): + # Don't call warnings._deprecated() directly because we're lazily importing warnings and don't + # want to have to trigger an eager import if it's not necessary. Startup time matters a lot + # here and warnings isn't cheap! This inlines the check from + # warnings._py_warnings._deprecated(). + _version = sys.version_info + if (_version[:2] > remove) or (_version[:2] == remove and _version[3] != "alpha"): + warnings._deprecated(message, remove=remove) + + def makepath(*paths): dir = os.path.join(*paths) try: @@ -111,7 +104,7 @@ def makepath(*paths): def abs_paths(): - """Set all module __file__ and __cached__ attributes to an absolute path""" + """Set __file__ to an absolute path.""" for m in set(sys.modules.values()): loader_module = None try: @@ -127,10 +120,6 @@ def abs_paths(): m.__file__ = os.path.abspath(m.__file__) except (AttributeError, OSError, TypeError): pass - try: - m.__cached__ = os.path.abspath(m.__cached__) - except (AttributeError, OSError, TypeError): - pass def removeduppaths(): @@ -165,95 +154,461 @@ def _init_pathinfo(): return d -def addpackage(sitedir, name, known_paths): - """Process a .pth file within the site-packages directory: - For each line in the file, either combine it with sitedir to a path - and add that to known_paths, or execute it if it starts with 'import '. +# PEP 829 implementation notes. +# +# Startup information (.pth and .start file information) can be processed in +# implicit or explicit batches. Implicit batches are self-contained +# site.addsitedir() calls: they create a per-call StartupState, populate it +# from the site directory's .pth and .start files, run process() on it, and +# then throw the state away. +# +# main() needs different semantics: it accumulates state across multiple +# StartupState.addsitedir() calls (user-site plus all global site-packages) so +# that every sys.path extension is visible *before* any startup code (.start +# entry points and .pth import lines) runs. Callers can opt into the same +# behavior by creating a StartupState directly and calling its addsitedir(), +# addusersitepackages(), and addsitepackages() methods, then invoking +# process() once at the end of the batch. +# +# Here's the CRITICAL reentrancy invariant: recursive site.addsitedir() calls +# reached from a .start entry point or an exec'd .pth import line must not +# mutate the StartupState currently being processed. Reentrant calls reach +# the module-level site.addsitedir() shim, which always builds a fresh +# per-call state. + + +def _read_pthstart_file(sitedir, name, suffix): + """Parse a .start or .pth file and return (lines, filename). + + On success, ``lines`` is a (possibly empty) list of the file's lines. + On failure (file missing, hidden, unreadable, or .start with bad + encoding), ``lines`` is ``None`` so callers can distinguish a + successfully-read empty file from one that could not be read. """ - if known_paths is None: - known_paths = _init_pathinfo() - reset = True - else: - reset = False - fullname = os.path.join(sitedir, name) + filename = os.path.join(sitedir, name) + _trace(f"Reading startup configuration file: {filename}") + try: - st = os.lstat(fullname) - except OSError: - return + st = os.lstat(filename) + except OSError as exc: + _trace(f"Cannot stat {filename!r}", exc) + return None, filename + if ((getattr(st, 'st_flags', 0) & stat.UF_HIDDEN) or (getattr(st, 'st_file_attributes', 0) & stat.FILE_ATTRIBUTE_HIDDEN)): - _trace(f"Skipping hidden .pth file: {fullname!r}") - return - _trace(f"Processing .pth file: {fullname!r}") + _trace(f"Skipping hidden {suffix} file: {filename!r}") + return None, filename + + _trace(f"Processing {suffix} file: {filename!r}") try: - with io.open_code(fullname) as f: - pth_content = f.read() - except OSError: - return + with io.open_code(filename) as f: + raw_content = f.read() + except OSError as exc: + _trace(f"Cannot read {filename!r}", exc) + return None, filename try: - # Accept BOM markers in .pth files as we do in source files - # (Windows PowerShell 5.1 makes it hard to emit UTF-8 files without a BOM) - pth_content = pth_content.decode("utf-8-sig") + # Accept BOM markers in .start and .pth files as we do in source files + # (Windows PowerShell 5.1 makes it hard to emit UTF-8 files without a BOM). + content = raw_content.decode("utf-8-sig") except UnicodeDecodeError: - # Fallback to locale encoding for backward compatibility. - # We will deprecate this fallback in the future. - import locale - pth_content = pth_content.decode(locale.getencoding()) - _trace(f"Cannot read {fullname!r} as UTF-8. " - f"Using fallback encoding {locale.getencoding()!r}") - - for n, line in enumerate(pth_content.splitlines(), 1): - if line.startswith("#"): - continue - if line.strip() == "": - continue + _trace(f"Cannot read {filename!r} as UTF-8.") + # For .pth files only, and then only until Python 3.20, fall back to + # locale encoding for backward compatibility. + _warn_future_us( + ".pth files decoded to locale encoding as a fallback", + remove=(3, 20) + ) + if suffix == ".pth": + content = raw_content.decode(locale.getencoding()) + _trace(f"Using fallback encoding {locale.getencoding()!r}") + else: + return None, filename + + return content.splitlines(), filename + + +class StartupState: + """Per-batch accumulator for .pth and .start file processing. + + A StartupState collects sys.path extensions, deprecated .pth import lines, + and .start entry points read from one or more site-packages directories. + Calling process() applies them in PEP 829 order: paths are added to + sys.path first, then import lines from .pth files (skipping any with a + matching .start), then entry points from .start files. + + State lives entirely on the instance; there is no module-level pending + state. This is what makes the module reentrancy-safe: a site.addsitedir() + call reached recursively from an exec'd import line or a .start entry + point operates on a different StartupState than the one being processed by + the outer call. + + The internal data is intentionally private. The lower-level write + methods (_record_sitedir(), _read_pth_file(), _read_start_file()) are + private to the site module; the public surface is addsitedir(), + addusersitepackages(), addsitepackages(), and process(). + """ + __slots__ = ( + '_known_paths', + '_processed_sitedirs', + '_path_entries', + '_importexecs', + '_entrypoints', + ) + + def __init__(self, known_paths=None): + """Create an independent startup state. + + *known_paths* is a set of case-normalized paths already present + on sys.path, used to avoid duplicate path entries. When None + (the default), it is initialized from the current sys.path. + + A caller-supplied set is stored by reference and mutated in place + as new paths are recorded; pass a fresh set per StartupState if + isolation across instances is required. + """ + self._known_paths = ( + _init_pathinfo() + if known_paths is None + else known_paths) + self._processed_sitedirs = set() + # The sys.path append ledger. This is a list of 2-tuples of the form + # (pthfile, path) where `pthfile` is the .pth file which is extending + # the path, and `path` is the directory to add to sys.path. Note that + # to preserve the interleaving semantics (i.e. .pth file paths are + # added after the sitedir in which the .pth file is found), `path` + # could be a sitedir, in which case `pthfile` will always be None. + self._path_entries = [] + # Both dicts map "" -> list + # of items collected from that file. Mapping by filename lets us + # cross-reference a .pth and its matching .start (PEP 829 import + # suppression rule) and lets _print_error report the source file + # when an entry fails. + self._importexecs = {} + self._entrypoints = {} + + def addsitedir(self, sitedir): + """Add a site directory and accumulate its .pth and .start startup data. + + Read the .pth and .start files in *sitedir* and record their + sys.path extensions, deprecated .pth import lines, and .start entry + points on this state. The recorded data is not applied until + process() is called. + + Typically used to batch multiple site directories before a single + process() call, so that every sys.path extension is visible before + any startup code runs. Reentrant calls reached from a .start entry + point or an exec'd .pth import line must not mutate the state + currently being processed; for those cases, use site.addsitedir() + instead, which always creates a fresh per-call state. + """ + self._addsitedir(sitedir, process_known_sitedirs=True) + + def addusersitepackages(self): + """Add the per-user site-packages directory, if enabled. + + The user site directory is added only when user site-packages are + enabled and the directory exists. Its startup data is accumulated + for later processing by process(). + """ + _trace("Processing user site-packages") + user_site = getusersitepackages() + if ENABLE_USER_SITE and os.path.isdir(user_site): + self.addsitedir(user_site) + + def addsitepackages(self, prefixes=None): + """Add global site-packages directories, if they exist. + + Site-packages directories are computed from *prefixes*, or from the + global PREFIXES when *prefixes* is None. Each directory's startup + data is accumulated for later processing by process(). + """ + _trace("Processing global site-packages") + for sitedir in getsitepackages(prefixes): + if os.path.isdir(sitedir): + self.addsitedir(sitedir) + + def _addsitedir(self, sitedir, *, process_known_sitedirs): + """Internal addsitedir() implementation with full dedup control. + + The public addsitedir() always uses process_known_sitedirs=True + (gh-149819 semantics). The module-level legacy known_paths shim + uses process_known_sitedirs=False to preserve 3.14 idempotency + (gh-75723). + """ + sitedir = self._record_sitedir( + sitedir, process_known_sitedirs=process_known_sitedirs) + if sitedir is None: + return try: + names = os.listdir(sitedir) + except OSError: + return + + # The following phases are defined by PEP 829. + # Phases 1-3: Read .pth files, accumulating paths and import lines. + pth_names = sorted( + name for name in names + if name.endswith(".pth") and not name.startswith(".") + ) + for name in pth_names: + self._read_pth_file(sitedir, name) + + # Phases 6-7: Discover .start files and accumulate their entry points. + # Import lines from .pth files with a matching .start file are + # discarded at flush time by _exec_imports(). + start_names = sorted( + name for name in names + if name.endswith(".start") and not name.startswith(".") + ) + for name in start_names: + self._read_start_file(sitedir, name) + + def _record_sitedir(self, sitedir, *, process_known_sitedirs=True): + sitedir, sitedircase = makepath(sitedir) + # Have we already processed this sitedir? + if sitedircase in self._processed_sitedirs: + return None + # In legacy known_paths mode, a known sitedir means its startup files + # were already processed by an earlier addsitedir() call, so skip it + # to preserve idempotency (gh-75723). In explicit StartupState mode, + # known_paths only tracks sys.path entries; a sitedir may already be + # on sys.path (for example from $PYTHONPATH, gh-149819) but still need + # its .pth and .start files processed once. The separate + # _processed_sitedirs set is what lets explicit batches distinguish + # "already on sys.path" from "startup files already read". + if not process_known_sitedirs and sitedircase in self._known_paths: + return None + # Record that we've processed this sitedir. + self._processed_sitedirs.add(sitedircase) + if sitedircase not in self._known_paths: + self._known_paths.add(sitedircase) + # Add the sitedir to the sys.path extension ledger. There is no + # .pth file to record. + self._path_entries.append((None, sitedir)) + return sitedir + + def _read_pth_file(self, sitedir, name): + """Parse a .pth file, accumulating sys.path extensions and import lines. + + Errors on individual lines do not abort processing of the rest of + the file (PEP 829). Per-batch deduplication is done against + self._known_paths: any path already in it is skipped, and newly + accepted paths are added to it so that subsequent .pth files in + the same batch don't add them more than once. + """ + lines, filename = _read_pthstart_file(sitedir, name, ".pth") + if lines is None: + return + + for n, line in enumerate(lines, 1): + line = line.strip() + if not line or line.startswith("#"): + continue + + # In Python 3.18 and 3.19, `import` lines are silently + # ignored. In Python 3.20 and beyond, issue a warning when + # `import` lines in .pth files are detected. if line.startswith(("import ", "import\t")): - exec(line) + _warn_future_us( + "import lines in .pth files are silently ignored", + remove=(3, 18), + ) + _warn_future_us( + "import lines in .pth files are noisily ignored", + remove=(3, 20), + ) + self._importexecs.setdefault(filename, []).append(line) continue - line = line.rstrip() - dir, dircase = makepath(sitedir, line) - if dircase not in known_paths and os.path.exists(dir): - sys.path.append(dir) - known_paths.add(dircase) - except Exception as exc: - print(f"Error processing line {n:d} of {fullname}:\n", - file=sys.stderr) - import traceback - for record in traceback.format_exception(exc): - for line in record.splitlines(): - print(' '+line, file=sys.stderr) - print("\nRemainder of file ignored", file=sys.stderr) - break - if reset: - known_paths = None - return known_paths + try: + dir_, dircase = makepath(sitedir, line) + except Exception as exc: + _trace(f"Error in {filename!r}, line {n:d}: {line!r}", exc) + continue -def addsitedir(sitedir, known_paths=None): - """Add 'sitedir' argument to sys.path if missing and handle .pth files in - 'sitedir'""" - _trace(f"Adding directory: {sitedir!r}") + # PEP 829 dedup: skip paths already seen in this batch. + if dircase in self._known_paths: + _trace( + f"In {filename!r}, line {n:d}: " + f"skipping duplicate sys.path entry: {dir_}" + ) + else: + # Add this directory to the sys.path extension ledger, while + # also recording the .pth file it was found in. + self._path_entries.append((filename, dir_)) + self._known_paths.add(dircase) + + def _read_start_file(self, sitedir, name): + """Parse a .start file for a list of entry point strings.""" + lines, filename = _read_pthstart_file(sitedir, name, ".start") + if lines is None: + return + + # PEP 829: the *presence* of a matching .start file disables `import` + # line processing in the matched .pth file, regardless of whether this + # .start file contains any entry points. Register the filename as a + # key now so an empty (or comment-only) .start file still suppresses. + entrypoints = self._entrypoints.setdefault(filename, []) + + for n, line in enumerate(lines, 1): + line = line.strip() + if not line or line.startswith("#"): + continue + # Syntax validation is deferred to entry point execution + # time, where pkgutil.resolve_name(strict=True) enforces the + # pkg.mod:callable form. + entrypoints.append(line) + + def process(self): + """Apply accumulated state in PEP 829 order. + + Phase order matters: all .pth path extensions are applied to + sys.path *before* any import line or .start entry point runs, so + that an entry point may live in a module reachable only via a + .pth-extended path. + """ + self._extend_syspath() + self._exec_imports() + self._execute_start_entrypoints() + + def _extend_syspath(self): + # Duplicate path-extension specifications have already been filtered + # out upstream across .pth files within this batch (via known_paths), + # and ledger entries are already abspath/normpath'd. .pth-derived + # entries (filename is not None) are existence-checked and skipped + # with an error if missing. Sitedir entries (filename is None) are + # appended unconditionally: legacy addsitedir() added the sitedir to + # sys.path before attempting to list it, so an unreadable or + # non-existent sitedir still landed on sys.path. Deferring the + # append to here preserves that contract. + for filename, dir_ in self._path_entries: + # As a backstop, known_paths may not have been seeded from sys.path + # (callers can pass an empty set), and multiple StartupState + # instances against the same sys.path don't share state, so always + # do a final anti-duplication check. + if dir_ in sys.path: + continue + if filename is None or os.path.exists(dir_): + if filename is not None: + _trace(f"Extending sys.path with {dir_} from {filename}") + sys.path.append(dir_) + else: + _print_error( + f"In {filename}: {dir_} does not exist; " + f"skipping sys.path append" + ) + + def _exec_imports(self): + # For each `import` line we've seen in a .pth file, exec() it in + # order, unless the .pth has a matching .start file in this same + # batch. In that case, PEP 829 says the import lines are + # suppressed in favor of the .start's entry points. + for filename, imports in self._importexecs.items(): + # Inject 'sitedir' local variable in the current frame for + # compatibility with Python 3.14. Especially, "-nspkg.pth" files + # generated by setuptools use: sys._getframe(1).f_locals['sitedir']. + sitedir = os.path.dirname(filename) + + # Inject 'fullname' local variable in the current frame for + # compatibility with Python 3.14, where the path of the ".pth" + # file being processed was available to import lines under that + # name. + fullname = filename + + # Given "/path/to/foo.pth", check whether "/path/to/foo.start" was + # registered in this same batch. + name, dot, pth = filename.rpartition(".") + assert dot == "." and pth == "pth", ( + f"Bad startup filename: {filename}" + ) + if f"{name}.start" in self._entrypoints: + _trace( + f"import lines in {filename} are suppressed " + f"due to matching {name}.start file." + ) + continue + + _trace( + f"import lines in {filename} are deprecated, " + f"use entry points in a {name}.start file instead." + ) + for line in imports: + try: + _trace(f"Exec'ing from {filename}: {line}") + exec(line) + except Exception as exc: + _print_error( + f"Error in import line from {filename}: {line}", + exc, + ) + + def _execute_start_entrypoints(self): + # Resolve each entry point string to a callable via + # pkgutil.resolve_name(strict=True), which both validates the + # required pkg.mod:callable form and performs the import in one + # step, then call it with no arguments. + for filename, entrypoints in self._entrypoints.items(): + for entrypoint in entrypoints: + try: + _trace( + f"Executing entry point: {entrypoint} from {filename}" + ) + callable_ = pkgutil.resolve_name(entrypoint, strict=True) + except ValueError as exc: + _print_error( + f"Invalid entry point syntax in {filename}: " + f"{entrypoint!r}", + exc, + ) + except Exception as exc: + _print_error( + f"Error resolving entry point {entrypoint} " + f"from {filename}", + exc, + ) + else: + try: + callable_() + except Exception as exc: + _print_error( + f"Error in entry point {entrypoint} from {filename}", + exc, + ) + + +def addpackage(sitedir, name, known_paths): + """Process a .pth file within the site-packages directory.""" if known_paths is None: known_paths = _init_pathinfo() reset = True else: reset = False - sitedir, sitedircase = makepath(sitedir) - if not sitedircase in known_paths: - sys.path.append(sitedir) # Add path component - known_paths.add(sitedircase) - try: - names = os.listdir(sitedir) - except OSError: - return - names = [name for name in names - if name.endswith(".pth") and not name.startswith(".")] - for name in sorted(names): - addpackage(sitedir, name, known_paths) - if reset: - known_paths = None + + state = StartupState(known_paths) + state._read_pth_file(sitedir, name) + state.process() + + return None if reset else known_paths + + +def addsitedir(sitedir, known_paths=None): + """Add a site directory and process its startup files. + + For batched processing across multiple site directories, build a + StartupState explicitly and call StartupState.addsitedir() on it; that + defers .pth/.start processing until a single StartupState.process() call. + """ + _trace(f"Adding directory: {sitedir!r}") + if known_paths is None: + state = StartupState(_init_pathinfo()) + state.addsitedir(sitedir) + else: + # Preserve gh-75723 idempotency for legacy known_paths mode: a + # sitedir already present in known_paths is skipped, not reprocessed. + state = StartupState(known_paths) + state._addsitedir(sitedir, process_known_sitedirs=False) + state.process() return known_paths @@ -333,8 +688,7 @@ def _get_path(userbase): if sys.platform == 'darwin' and sys._framework: return f'{userbase}/lib/{implementation_lower}/site-packages' - # XXX: RUSTPYTHON - return f'{userbase}/lib/rustpython{version[0]}.{version[1]}{abi_thread}/site-packages' + return f'{userbase}/lib/{implementation_lower}{version[0]}.{version[1]}{abi_thread}/site-packages' def getuserbase(): @@ -367,21 +721,20 @@ def getusersitepackages(): return USER_SITE + def addusersitepackages(known_paths): - """Add a per user site-package to sys.path + """Add the per-user site-packages directory, if enabled. - Each user has its own python directory with site-packages in the - home directory. + The user site directory is added only when user site-packages are enabled + and the directory exists. Return *known_paths*, updated with any paths + added by addsitedir(). """ - # get the per user site-package path - # this call will also make sure USER_BASE and USER_SITE are set - _trace("Processing user site-packages") - user_site = getusersitepackages() - - if ENABLE_USER_SITE and os.path.isdir(user_site): - addsitedir(user_site, known_paths) + state = StartupState(known_paths) + state.addusersitepackages() + state.process() return known_paths + def getsitepackages(prefixes=None): """Returns a list containing all global site-packages directories. @@ -421,15 +774,20 @@ def getsitepackages(prefixes=None): sitepackages.append(os.path.join(prefix, "Lib", "site-packages")) return sitepackages + def addsitepackages(known_paths, prefixes=None): - """Add site-packages to sys.path""" - _trace("Processing global site-packages") - for sitedir in getsitepackages(prefixes): - if os.path.isdir(sitedir): - addsitedir(sitedir, known_paths) + """Add global site-packages directories, if they exist. + Site-packages directories are computed from *prefixes*, or from the global + prefixes when *prefixes* is None. Return *known_paths*, updated with any + paths added by addsitedir(). + """ + state = StartupState(known_paths) + state.addsitepackages(prefixes) + state.process() return known_paths + def setquit(): """Define new builtins 'quit' and 'exit'. @@ -532,6 +890,8 @@ def register_readline(): import _pyrepl.unix_console console_errors = _pyrepl.unix_console._error from _pyrepl.main import CAN_USE_PYREPL + except ModuleNotFoundError: + CAN_USE_PYREPL = False finally: sys.path = original_path except ImportError: @@ -594,6 +954,15 @@ def write_history(): def venv(known_paths): + """Process pyvenv.cfg and add the venv site-packages, if applicable.""" + state = StartupState(known_paths) + _venv(state) + state.process() + return known_paths + + +def _venv(state): + """State-driven implementation of venv(); used by main() for batching.""" global PREFIXES, ENABLE_USER_SITE env = os.environ @@ -633,20 +1002,22 @@ def venv(known_paths): sys._home = value if sys.prefix != site_prefix: - _warn(f'Unexpected value in sys.prefix, expected {site_prefix}, got {sys.prefix}', RuntimeWarning) + _warn( + f'Unexpected value in sys.prefix, expected {site_prefix}, got {sys.prefix}', + RuntimeWarning) if sys.exec_prefix != site_prefix: - _warn(f'Unexpected value in sys.exec_prefix, expected {site_prefix}, got {sys.exec_prefix}', RuntimeWarning) + _warn( + f'Unexpected value in sys.exec_prefix, expected {site_prefix}, got {sys.exec_prefix}', + RuntimeWarning) - # Doing this here ensures venv takes precedence over user-site - addsitepackages(known_paths, [sys.prefix]) + # Doing this here ensures venv takes precedence over user-site. + state.addsitepackages([sys.prefix]) if system_site == "true": PREFIXES += [sys.base_prefix, sys.base_exec_prefix] else: ENABLE_USER_SITE = False - return known_paths - def execsitecustomize(): """Run custom site specific code, if available.""" @@ -697,17 +1068,25 @@ def main(): global ENABLE_USER_SITE orig_path = sys.path[:] - known_paths = removeduppaths() + removeduppaths() if orig_path != sys.path: # removeduppaths() might make sys.path absolute. - # fix __file__ and __cached__ of already imported modules too. + # Fix __file__ of already imported modules too. abs_paths() - known_paths = venv(known_paths) + state = StartupState(set()) + _venv(state) + if ENABLE_USER_SITE is None: ENABLE_USER_SITE = check_enableusersite() - known_paths = addusersitepackages(known_paths) - known_paths = addsitepackages(known_paths) + + state.addusersitepackages() + state.addsitepackages() + # PEP 829: flush accumulated data from all .pth and .start files. + # Paths are extended first, then deprecated import lines are exec'd, + # and finally .start entry points are executed — ensuring sys.path is + # fully populated before any startup code runs. + state.process() setquit() setcopyright() sethelper() diff --git a/Lib/socket.py b/Lib/socket.py index 9ac0badc660..2a4f875f76b 100644 --- a/Lib/socket.py +++ b/Lib/socket.py @@ -56,6 +56,7 @@ import os import sys from enum import IntEnum, IntFlag +from functools import partial try: import errno @@ -122,7 +123,7 @@ def _intenum_converter(value, enum_klass): 10004: "The operation was interrupted.", 10009: "A bad file handle was passed.", 10013: "Permission denied.", - 10014: "A fault occurred on the network??", + 10014: "An invalid pointer was passed.", 10022: "An invalid operation was attempted.", 10024: "Too many open files.", 10035: "The socket operation would block.", @@ -180,7 +181,7 @@ def _intenum_converter(value, enum_klass): 11001: "Host not found.", 11002: "Nonauthoritative host not found.", 11003: "This is a nonrecoverable error.", - 11004: "Valid name, no data record requested type.", + 11004: "Valid name, no data record of requested type.", 11005: "QoS receivers.", 11006: "QoS senders.", 11007: "No QoS senders.", @@ -196,7 +197,7 @@ def _intenum_converter(value, enum_klass): 11017: "QoS flowspec error.", 11018: "Invalid QoS provider buffer.", 11019: "Invalid QoS filter style.", - 11020: "Invalid QoS filter style.", + 11020: "Invalid QoS filter type.", 11021: "Incorrect QoS filter count.", 11022: "Invalid QoS object length.", 11023: "Incorrect QoS flow count.", @@ -348,75 +349,83 @@ def makefile(self, mode="r", buffering=None, *, text.mode = mode return text - if hasattr(os, 'sendfile'): + def _sendfile_zerocopy(self, zerocopy_func, giveup_exc_type, file, + offset=0, count=None): + """ + Send a file using a zero-copy function. + """ + import selectors - def _sendfile_use_sendfile(self, file, offset=0, count=None): - # Lazy import to improve module import time - import selectors + self._check_sendfile_params(file, offset, count) + sockno = self.fileno() + try: + fileno = file.fileno() + except (AttributeError, io.UnsupportedOperation) as err: + raise giveup_exc_type(err) # not a regular file + try: + fsize = os.fstat(fileno).st_size + except OSError as err: + raise giveup_exc_type(err) # not a regular file + if not fsize: + return 0 # empty file + # Truncate to 1GiB to avoid OverflowError, see bpo-38319. + blocksize = min(count or fsize, 2 ** 30) + timeout = self.gettimeout() + if timeout == 0: + raise ValueError("non-blocking sockets are not supported") + # poll/select have the advantage of not requiring any + # extra file descriptor, contrarily to epoll/kqueue + # (also, they require a single syscall). + if hasattr(selectors, 'PollSelector'): + selector = selectors.PollSelector() + else: + selector = selectors.SelectSelector() + selector.register(sockno, selectors.EVENT_WRITE) - self._check_sendfile_params(file, offset, count) - sockno = self.fileno() - try: - fileno = file.fileno() - except (AttributeError, io.UnsupportedOperation) as err: - raise _GiveupOnSendfile(err) # not a regular file - try: - fsize = os.fstat(fileno).st_size - except OSError as err: - raise _GiveupOnSendfile(err) # not a regular file - if not fsize: - return 0 # empty file - # Truncate to 1GiB to avoid OverflowError, see bpo-38319. - blocksize = min(count or fsize, 2 ** 30) - timeout = self.gettimeout() - if timeout == 0: - raise ValueError("non-blocking sockets are not supported") - # poll/select have the advantage of not requiring any - # extra file descriptor, contrarily to epoll/kqueue - # (also, they require a single syscall). - if hasattr(selectors, 'PollSelector'): - selector = selectors.PollSelector() - else: - selector = selectors.SelectSelector() - selector.register(sockno, selectors.EVENT_WRITE) - - total_sent = 0 - # localize variable access to minimize overhead - selector_select = selector.select - os_sendfile = os.sendfile - try: - while True: - if timeout and not selector_select(timeout): - raise TimeoutError('timed out') - if count: - blocksize = min(count - total_sent, blocksize) - if blocksize <= 0: - break - try: - sent = os_sendfile(sockno, fileno, offset, blocksize) - except BlockingIOError: - if not timeout: - # Block until the socket is ready to send some - # data; avoids hogging CPU resources. - selector_select() - continue - except OSError as err: - if total_sent == 0: - # We can get here for different reasons, the main - # one being 'file' is not a regular mmap(2)-like - # file, in which case we'll fall back on using - # plain send(). - raise _GiveupOnSendfile(err) - raise err from None - else: - if sent == 0: - break # EOF - offset += sent - total_sent += sent - return total_sent - finally: - if total_sent > 0 and hasattr(file, 'seek'): - file.seek(offset) + total_sent = 0 + # localize variable access to minimize overhead + selector_select = selector.select + try: + while True: + if timeout and not selector_select(timeout): + raise TimeoutError('timed out') + if count: + blocksize = min(count - total_sent, blocksize) + if blocksize <= 0: + break + try: + sent = zerocopy_func(fileno, offset, blocksize) + except BlockingIOError: + if not timeout: + # Block until the socket is ready to send some + # data; avoids hogging CPU resources. + selector_select() + continue + except OSError as err: + if total_sent == 0: + # We can get here for different reasons, the main + # one being 'file' is not a regular mmap(2)-like + # file, in which case we'll fall back on using + # plain send(). + raise giveup_exc_type(err) + raise err from None + else: + if sent == 0: + break # EOF + offset += sent + total_sent += sent + return total_sent + finally: + if total_sent > 0 and hasattr(file, 'seek'): + file.seek(offset) + + if hasattr(os, 'sendfile'): + def _sendfile_use_sendfile(self, file, offset=0, count=None): + return self._sendfile_zerocopy( + partial(os.sendfile, self.fileno()), + _GiveupOnSendfile, + file, offset, count, + ) else: def _sendfile_use_sendfile(self, file, offset=0, count=None): raise _GiveupOnSendfile( diff --git a/Lib/socketserver.py b/Lib/socketserver.py index 35b2723de3b..ec389457ef5 100644 --- a/Lib/socketserver.py +++ b/Lib/socketserver.py @@ -120,9 +120,6 @@ class will essentially render the service "deaf" while one request is # Author of the BaseServer patch: Luke Kenneth Casson Leighton -__version__ = "0.4" - - import socket import selectors import os @@ -441,7 +438,7 @@ class TCPServer(BaseServer): socket_type = socket.SOCK_STREAM - request_queue_size = 5 + request_queue_size = getattr(socket, "SOMAXCONN", 5) allow_reuse_address = False @@ -861,3 +858,12 @@ def setup(self): def finish(self): self.socket.sendto(self.wfile.getvalue(), self.client_address) + + +def __getattr__(name): + if name == "__version__": + from warnings import _deprecated + + _deprecated("__version__", remove=(3, 20)) + return "0.4" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/Lib/sqlite3/__main__.py b/Lib/sqlite3/__main__.py index 4ccf292ddf2..ec72c694390 100644 --- a/Lib/sqlite3/__main__.py +++ b/Lib/sqlite3/__main__.py @@ -10,9 +10,12 @@ from argparse import ArgumentParser from code import InteractiveConsole from textwrap import dedent +from _colorize import get_theme, theme_no_color +from ._completer import completer -def execute(c, sql, suppress_errors=True): + +def execute(c, sql, suppress_errors=True, theme=theme_no_color): """Helper that wraps execution of SQL code. This is used both by the REPL and by direct execution from the CLI. @@ -25,11 +28,15 @@ def execute(c, sql, suppress_errors=True): for row in c.execute(sql): print(row) except sqlite3.Error as e: + t = theme.traceback tp = type(e).__name__ try: - print(f"{tp} ({e.sqlite_errorname}): {e}", file=sys.stderr) + tp += f" ({e.sqlite_errorname})" except AttributeError: - print(f"{tp}: {e}", file=sys.stderr) + pass + print( + f"{t.type}{tp}{t.reset}: {t.message}{e}{t.reset}", file=sys.stderr + ) if not suppress_errors: sys.exit(1) @@ -37,10 +44,11 @@ def execute(c, sql, suppress_errors=True): class SqliteInteractiveConsole(InteractiveConsole): """A simple SQLite REPL.""" - def __init__(self, connection): + def __init__(self, connection, use_color=False): super().__init__() self._con = connection self._cur = connection.cursor() + self._use_color = use_color def runsource(self, source, filename="", symbol="single"): """Override runsource, the core of the InteractiveConsole REPL. @@ -48,37 +56,42 @@ def runsource(self, source, filename="", symbol="single"): Return True if more input is needed; buffering is done automatically. Return False if input is a complete statement ready for execution. """ + theme = get_theme(force_no_color=not self._use_color) + if not source or source.isspace(): return False + # Remember to update CLI_COMMANDS in _completer.py if source[0] == ".": match source[1:].strip(): case "version": - print(f"{sqlite3.sqlite_version}") + print(sqlite3.sqlite_version) case "help": - print("Enter SQL code and press enter.") + t = theme.syntax + print(f"Enter SQL code or one of the below commands, and press enter.\n\n" + f"{t.builtin}.version{t.reset} Print underlying SQLite library version\n" + f"{t.builtin}.help{t.reset} Print this help message\n" + f"{t.builtin}.quit{t.reset} Exit the CLI, equivalent to CTRL-D\n") case "quit": sys.exit(0) case "": pass case _ as unknown: - self.write("Error: unknown command or invalid arguments:" - f' "{unknown}".\n') + t = theme.traceback + self.write(f'{t.type}Error{t.reset}: {t.message}unknown ' + f'command: "{unknown}"{t.reset}\n') else: if not sqlite3.complete_statement(source): return True - execute(self._cur, source) + execute(self._cur, source, theme=theme) return False def main(*args): - parser = ArgumentParser( - description="Python sqlite3 CLI", - color=True, - ) + parser = ArgumentParser(description="Python sqlite3 CLI") parser.add_argument( "filename", type=str, default=":memory:", nargs="?", help=( - "SQLite database to open (defaults to ':memory:'). " + "SQLite database to open (defaults to `:memory:`). " "A new database is created if the file does not previously exist." ), ) @@ -86,7 +99,7 @@ def main(*args): "sql", type=str, nargs="?", help=( "An SQL query to execute. " - "Any returned rows are printed to stdout." + "Any returned rows are printed to `stdout`." ), ) parser.add_argument( @@ -113,22 +126,26 @@ def main(*args): Each command will be run using execute() on the cursor. Type ".help" for more information; type ".quit" or {eofkey} to quit. """).strip() - sys.ps1 = "sqlite> " - sys.ps2 = " ... " + + theme = get_theme() + s = theme.syntax + + # Use RL_PROMPT_START_IGNORE (\001) and RL_PROMPT_END_IGNORE (\002) to + # bracket non-printing characters. This tells readline to ignore them + # when calculating screen space for redisplay during history scrolling. + sys.ps1 = f"\001{s.prompt}\002sqlite> \001{s.reset}\002" + sys.ps2 = f"\001{s.prompt}\002 ... \001{s.reset}\002" con = sqlite3.connect(args.filename, isolation_level=None) try: if args.sql: # SQL statement provided on the command-line; execute it directly. - execute(con, args.sql, suppress_errors=False) + execute(con, args.sql, suppress_errors=False, theme=theme) else: # No SQL provided; start the REPL. - console = SqliteInteractiveConsole(con) - try: - import readline # noqa: F401 - except ImportError: - pass - console.interact(banner, exitmsg="") + with completer(con): + console = SqliteInteractiveConsole(con, use_color=True) + console.interact(banner, exitmsg="") finally: con.close() diff --git a/Lib/sqlite3/_completer.py b/Lib/sqlite3/_completer.py new file mode 100644 index 00000000000..ba580f968bf --- /dev/null +++ b/Lib/sqlite3/_completer.py @@ -0,0 +1,111 @@ +from _sqlite3 import OperationalError +from contextlib import contextmanager + +try: + from _sqlite3 import SQLITE_KEYWORDS +except ImportError: + SQLITE_KEYWORDS = () + +CLI_COMMANDS = ('.quit', '.help', '.version') + +_completion_matches = [] + + +def _complete(con, text, state): + global _completion_matches + + if state == 0: + if text.startswith("."): + _completion_matches = [ + c + " " for c in CLI_COMMANDS if c.startswith(text) + ] + else: + text_upper = text.upper() + _completion_matches = [ + c + " " for c in SQLITE_KEYWORDS if c.startswith(text_upper) + ] + + cursor = con.cursor() + schemata = tuple(row[1] for row + in cursor.execute("PRAGMA database_list")) + # tables, indexes, triggers, and views + # escape '_' which can appear in attached database names + select_clauses = ( + f"""\ + SELECT name || ' ' FROM \"{schema}\".sqlite_master + WHERE name LIKE REPLACE(:text, '_', '^_') || '%' ESCAPE '^'""" + for schema in schemata + ) + _completion_matches.extend( + row[0] + for row in cursor.execute( + " UNION ".join(select_clauses), {"text": text} + ) + ) + # columns + try: + select_clauses = ( + f"""\ + SELECT pti.name || ' ' FROM "{schema}".sqlite_master AS sm + JOIN pragma_table_xinfo(sm.name,'{schema}') AS pti + WHERE sm.type='table' AND + pti.name LIKE REPLACE(:text, '_', '^_') || '%' ESCAPE '^'""" + for schema in schemata + ) + _completion_matches.extend( + row[0] + for row in cursor.execute( + " UNION ".join(select_clauses), {"text": text} + ) + ) + except OperationalError: + # skip on SQLite<3.16.0 where pragma table-valued function is + # not supported yet + pass + # functions + try: + _completion_matches.extend( + row[0] for row in cursor.execute("""\ + SELECT DISTINCT UPPER(name) || '(' + FROM pragma_function_list() + WHERE name NOT IN ('->', '->>') AND + name LIKE REPLACE(:text, '_', '^_') || '%' ESCAPE '^'""", + {"text": text}, + ) + ) + except OperationalError: + # skip on SQLite<3.30.0 where function_list is not supported yet + pass + # schemata + text_lower = text.lower() + _completion_matches.extend(c for c in schemata + if c.lower().startswith(text_lower)) + _completion_matches = sorted(set(_completion_matches)) + try: + return _completion_matches[state] + except IndexError: + return None + + +@contextmanager +def completer(con): + try: + import readline + except ImportError: + yield + return + + old_completer = readline.get_completer() + def complete(text, state): + return _complete(con, text, state) + try: + readline.set_completer(complete) + if readline.backend == "editline": + # libedit uses "^I" instead of "tab" + command_string = "bind ^I rl_complete" + else: + command_string = "tab: complete" + readline.parse_and_bind(command_string) + yield + finally: + readline.set_completer(old_completer) diff --git a/Lib/sqlite3/dump.py b/Lib/sqlite3/dump.py index 57e6a3b4f1e..95e14a6655e 100644 --- a/Lib/sqlite3/dump.py +++ b/Lib/sqlite3/dump.py @@ -11,8 +11,12 @@ def _quote_name(name): return '"{0}"'.format(name.replace('"', '""')) +def _escape_single_quotes(value): + return value.replace("'", "''") + + def _quote_value(value): - return "'{0}'".format(value.replace("'", "''")) + return "'{0}'".format(_escape_single_quotes(value)) def _iterdump(connection, *, filter=None): @@ -80,11 +84,12 @@ def _iterdump(connection, *, filter=None): table_name_ident = _quote_name(table_name) res = cu.execute(f'PRAGMA table_info({table_name_ident})') column_names = [str(table_info[1]) for table_info in res.fetchall()] - q = "SELECT 'INSERT INTO {0} VALUES('{1}')' FROM {0};".format( - table_name_ident, + q = "SELECT 'INSERT INTO {0} VALUES('{1}')' FROM {2};".format( + _escape_single_quotes(table_name_ident), "','".join( "||quote({0})||".format(_quote_name(col)) for col in column_names - ) + ), + table_name_ident, ) query_res = cu.execute(q) for row in query_res: diff --git a/Lib/sre_compile.py b/Lib/sre_compile.py deleted file mode 100644 index f9da61e6487..00000000000 --- a/Lib/sre_compile.py +++ /dev/null @@ -1,7 +0,0 @@ -import warnings -warnings.warn(f"module {__name__!r} is deprecated", - DeprecationWarning, - stacklevel=2) - -from re import _compiler as _ -globals().update({k: v for k, v in vars(_).items() if k[:2] != '__'}) diff --git a/Lib/sre_constants.py b/Lib/sre_constants.py deleted file mode 100644 index fa09d044292..00000000000 --- a/Lib/sre_constants.py +++ /dev/null @@ -1,7 +0,0 @@ -import warnings -warnings.warn(f"module {__name__!r} is deprecated", - DeprecationWarning, - stacklevel=2) - -from re import _constants as _ -globals().update({k: v for k, v in vars(_).items() if k[:2] != '__'}) diff --git a/Lib/sre_parse.py b/Lib/sre_parse.py deleted file mode 100644 index 25a3f557d44..00000000000 --- a/Lib/sre_parse.py +++ /dev/null @@ -1,7 +0,0 @@ -import warnings -warnings.warn(f"module {__name__!r} is deprecated", - DeprecationWarning, - stacklevel=2) - -from re import _parser as _ -globals().update({k: v for k, v in vars(_).items() if k[:2] != '__'}) diff --git a/Lib/ssl.py b/Lib/ssl.py index 8889aff92fa..b07281f9758 100644 --- a/Lib/ssl.py +++ b/Lib/ssl.py @@ -13,6 +13,9 @@ Functions: + get_sigalgs -- return a list of all available TLS signature + algorithms (requires OpenSSL 3.4 or later) + cert_time_to_seconds -- convert time string used for certificate notBefore and notAfter functions to integer seconds past the Epoch (the time values @@ -107,16 +110,12 @@ ) from _ssl import txt2obj as _txt2obj, nid2obj as _nid2obj from _ssl import RAND_status, RAND_add, RAND_bytes -try: - from _ssl import RAND_egd -except ImportError: - # RAND_egd is not supported on some platforms - pass +from _ssl import get_sigalgs from _ssl import ( HAS_SNI, HAS_ECDH, HAS_NPN, HAS_ALPN, HAS_SSLv2, HAS_SSLv3, HAS_TLSv1, - HAS_TLSv1_1, HAS_TLSv1_2, HAS_TLSv1_3, HAS_PSK, HAS_PHA + HAS_TLSv1_1, HAS_TLSv1_2, HAS_TLSv1_3, HAS_PSK, HAS_PSK_TLS13, HAS_PHA ) from _ssl import _DEFAULT_CIPHERS, _OPENSSL_API_VERSION @@ -151,7 +150,8 @@ source=_ssl) PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_SSLv23 = _SSLMethod.PROTOCOL_TLS -_PROTOCOL_NAMES = {value: name for name, value in _SSLMethod.__members__.items()} +_PROTOCOL_NAMES = frozendict({ + value: name for name, value in _SSLMethod.__members__.items()}) _SSLv2_IF_EXISTS = getattr(_SSLMethod, 'PROTOCOL_SSLv2', None) @@ -373,6 +373,20 @@ def _ipaddress_match(cert_ipaddress, host_ip): return ip == host_ip +def _check_sslobject_params(server_side, context=None, server_hostname=None, session=None): + """Raises a ValueError if SSLObject._create() parameters aren't valid. + """ + if server_side: + if server_hostname: + raise ValueError("server_hostname can only be specified " + "in client mode") + if session is not None: + raise ValueError("session can only be specified in " + "client mode") + if context.check_hostname and not server_hostname: + raise ValueError("check_hostname requires server_hostname") + + DefaultVerifyPaths = namedtuple("DefaultVerifyPaths", "cafile capath openssl_cafile_env openssl_cafile openssl_capath_env " "openssl_capath") @@ -755,6 +769,8 @@ def _create_unverified_context(protocol=None, *, cert_reqs=CERT_NONE, raise ValueError(purpose) context = SSLContext(protocol) + # Setting verify_mode to CERT_NONE fails while check_hostname is + # enabled, so assign check_hostname first (gh-114905). context.check_hostname = check_hostname if cert_reqs is not None: context.verify_mode = cert_reqs @@ -813,6 +829,8 @@ def __init__(self, *args, **kwargs): @classmethod def _create(cls, incoming, outgoing, server_side=False, server_hostname=None, session=None, context=None): + _check_sslobject_params(server_side=server_side, context=context, + server_hostname=server_hostname, session=session) self = cls.__new__(cls) sslobj = context._wrap_bio( incoming, outgoing, server_side=server_side, @@ -931,6 +949,18 @@ def cipher(self): ssl_version, secret_bits)``.""" return self._sslobj.cipher() + def group(self): + """Return the currently selected key agreement group name.""" + return self._sslobj.group() + + def client_sigalg(self): + """Return the selected client authentication signature algorithm.""" + return self._sslobj.client_sigalg() + + def server_sigalg(self): + """Return the selected server handshake signature algorithm.""" + return self._sslobj.server_sigalg() + def shared_ciphers(self): """Return a list of ciphers shared by the client during the handshake or None if this is not a valid server connection. @@ -975,6 +1005,10 @@ def _sslcopydoc(func): return func +class _GiveupOnSSLSendfile(Exception): + pass + + class SSLSocket(socket): """This class implements a subtype of socket.socket that wraps the underlying OS socket in an SSL context when necessary, and @@ -993,15 +1027,8 @@ def _create(cls, sock, server_side=False, do_handshake_on_connect=True, context=None, session=None): if sock.getsockopt(SOL_SOCKET, SO_TYPE) != SOCK_STREAM: raise NotImplementedError("only stream sockets are supported") - if server_side: - if server_hostname: - raise ValueError("server_hostname can only be specified " - "in client mode") - if session is not None: - raise ValueError("session can only be specified in " - "client mode") - if context.check_hostname and not server_hostname: - raise ValueError("check_hostname requires server_hostname") + _check_sslobject_params(server_side=server_side, context=context, + server_hostname=server_hostname, session=session) sock_timeout = sock.gettimeout() kwargs = dict( @@ -1206,6 +1233,30 @@ def cipher(self): else: return self._sslobj.cipher() + @_sslcopydoc + def group(self): + self._checkClosed() + if self._sslobj is None: + return None + else: + return self._sslobj.group() + + @_sslcopydoc + def client_sigalg(self): + self._checkClosed() + if self._sslobj is None: + return None + else: + return self._sslobj.client_sigalg() + + @_sslcopydoc + def server_sigalg(self): + self._checkClosed() + if self._sslobj is None: + return None + else: + return self._sslobj.server_sigalg() + @_sslcopydoc def shared_ciphers(self): self._checkClosed() @@ -1266,15 +1317,26 @@ def sendall(self, data, flags=0): return super().sendall(data, flags) def sendfile(self, file, offset=0, count=None): - """Send a file, possibly by using os.sendfile() if this is a - clear-text socket. Return the total number of bytes sent. + """Send a file, possibly by using an efficient sendfile() call if + the system supports it. Return the total number of bytes sent. """ - if self._sslobj is not None: - return self._sendfile_use_send(file, offset, count) - else: - # os.sendfile() works with plain sockets only + if self._sslobj is None: return super().sendfile(file, offset, count) + if not self._sslobj.uses_ktls_for_send(): + return self._sendfile_use_send(file, offset, count) + + sendfile = getattr(self._sslobj, "sendfile", None) + if sendfile is None: + return self._sendfile_use_send(file, offset, count) + + try: + return self._sendfile_zerocopy( + sendfile, _GiveupOnSSLSendfile, file, offset, count, + ) + except _GiveupOnSSLSendfile: + return self._sendfile_use_send(file, offset, count) + def recv(self, buflen=1024, flags=0): self._checkClosed() if self._sslobj is not None: @@ -1484,11 +1546,8 @@ def DER_cert_to_PEM_cert(der_cert_bytes): """Takes a certificate in binary DER format and returns the PEM version of it as a string.""" - f = str(base64.standard_b64encode(der_cert_bytes), 'ASCII', 'strict') - ss = [PEM_HEADER] - ss += [f[i:i+64] for i in range(0, len(f), 64)] - ss.append(PEM_FOOTER + '\n') - return '\n'.join(ss) + f = str(base64.b64encode(der_cert_bytes, wrapcol=64), 'ASCII') + return f'{PEM_HEADER}\n{f}\n{PEM_FOOTER}\n' def PEM_cert_to_DER_cert(pem_cert_string): """Takes a certificate in ASCII PEM format and returns the diff --git a/Lib/stat.py b/Lib/stat.py index 81f694329bf..214c7917b5e 100644 --- a/Lib/stat.py +++ b/Lib/stat.py @@ -205,6 +205,21 @@ def filemode(mode): FILE_ATTRIBUTE_VIRTUAL = 65536 +# Linux STATX_ATTR constants for interpreting os.statx()'s +# "stx_attributes" and "stx_attributes_mask" members + +STATX_ATTR_COMPRESSED = 0x00000004 +STATX_ATTR_IMMUTABLE = 0x00000010 +STATX_ATTR_APPEND = 0x00000020 +STATX_ATTR_NODUMP = 0x00000040 +STATX_ATTR_ENCRYPTED = 0x00000800 +STATX_ATTR_AUTOMOUNT = 0x00001000 +STATX_ATTR_MOUNT_ROOT = 0x00002000 +STATX_ATTR_VERITY = 0x00100000 +STATX_ATTR_DAX = 0x00200000 +STATX_ATTR_WRITE_ATOMIC = 0x00400000 + + # If available, use C implementation try: from _stat import * diff --git a/Lib/statistics.py b/Lib/statistics.py index 26cf925529e..01ca6c51daf 100644 --- a/Lib/statistics.py +++ b/Lib/statistics.py @@ -136,7 +136,7 @@ from fractions import Fraction from decimal import Decimal -from itertools import count, groupby, repeat +from itertools import compress, count, groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erfc, tau, log, fsum, sumprod from math import isfinite, isinf, pi, cos, sin, tan, cosh, asin, atan, acos @@ -145,6 +145,7 @@ from collections import Counter, namedtuple, defaultdict _SQRT2 = sqrt(2.0) +_SQRT2PI = sqrt(tau) _random = random ## Exceptions ############################################################## @@ -194,9 +195,9 @@ def fmean(data, weights=None): n = len(data) except TypeError: # Handle iterators that do not define __len__(). - counter = count() - total = fsum(map(itemgetter(0), zip(data, counter))) - n = next(counter) + counter = count(1) + total = fsum(compress(data, counter)) + n = next(counter) - 1 else: total = fsum(data) @@ -247,7 +248,7 @@ def count_positive(iterable): elif x == 0.0: found_zero = True else: - raise StatisticsError('No negative inputs allowed', x) + raise StatisticsError(f'No negative inputs allowed: {x!r}') total = fsum(map(log, count_positive(data))) @@ -1257,11 +1258,11 @@ def samples(self, n, *, seed=None): def pdf(self, x): "Probability density function. P(x <= X < x+dx) / dx" - variance = self._sigma * self._sigma - if not variance: + sigma = self._sigma + if not sigma: raise StatisticsError('pdf() not defined when sigma is zero') - diff = x - self._mu - return exp(diff * diff / (-2.0 * variance)) / sqrt(tau * variance) + z = (x - self._mu) / sigma + return exp(-0.5 * z * z) / (_SQRT2PI * sigma) def cdf(self, x): "Cumulative distribution function. P(X <= x)" diff --git a/Lib/string/__init__.py b/Lib/string/__init__.py index b2c369ef9d1..88f1ae1b9b0 100644 --- a/Lib/string/__init__.py +++ b/Lib/string/__init__.py @@ -198,16 +198,14 @@ def get_identifiers(self): ######################################################################## -# the Formatter class -# see PEP 3101 for details and purpose of this class - -# The hard parts are reused from the C implementation. They're exposed as "_" -# prefixed methods of str. - +# The Formatter class (PEP 3101). +# # The overall parser is implemented in _string.formatter_parser. -# The field name parser is implemented in _string.formatter_field_name_split +# The field name parser is implemented in _string.formatter_field_name_split. class Formatter: + """See PEP 3101 for details and purpose of this class.""" + def format(self, format_string, /, *args, **kwargs): return self.vformat(format_string, args, kwargs) @@ -271,22 +269,18 @@ def _vformat(self, format_string, args, kwargs, used_args, recursion_depth, return ''.join(result), auto_arg_index - def get_value(self, key, args, kwargs): if isinstance(key, int): return args[key] else: return kwargs[key] - def check_unused_args(self, used_args, args, kwargs): pass - def format_field(self, value, format_spec): return format(value, format_spec) - def convert_field(self, value, conversion): # do any conversion on the resulting object if conversion is None: @@ -299,28 +293,26 @@ def convert_field(self, value, conversion): return ascii(value) raise ValueError("Unknown conversion specifier {0!s}".format(conversion)) - - # returns an iterable that contains tuples of the form: - # (literal_text, field_name, format_spec, conversion) - # literal_text can be zero length - # field_name can be None, in which case there's no - # object to format and output - # if field_name is not None, it is looked up, formatted - # with format_spec and conversion and then used def parse(self, format_string): + """ + Return an iterable that contains tuples of the form + (literal_text, field_name, format_spec, conversion). + + *field_name* can be None, in which case there's no object + to format and output; otherwise, it is looked up and + formatted with *format_spec* and *conversion*. + """ return _string.formatter_parser(format_string) - - # given a field_name, find the object it references. - # field_name: the field being looked up, e.g. "0.name" - # or "lookup[3]" - # used_args: a set of which args have been used - # args, kwargs: as passed in to vformat def get_field(self, field_name, args, kwargs): - first, rest = _string.formatter_field_name_split(field_name) + """Find the object referenced by a given field name. + The field name *field_name* can be for instance "0.name" + or "lookup[3]". The *args* and *kwargs* arguments are + passed to get_value(). + """ + first, rest = _string.formatter_field_name_split(field_name) obj = self.get_value(first, args, kwargs) - # loop through the rest of the field_name, doing # getattr or getitem as needed for is_attr, i in rest: @@ -328,5 +320,4 @@ def get_field(self, field_name, args, kwargs): obj = getattr(obj, i) else: obj = obj[i] - return obj, first diff --git a/Lib/stringprep.py b/Lib/stringprep.py index 44ecdb266ce..abad847830c 100644 --- a/Lib/stringprep.py +++ b/Lib/stringprep.py @@ -5,12 +5,18 @@ and mappings, for which a mapping function is provided. """ -from unicodedata import ucd_3_2_0 as unicodedata +# This check asserts that mkstringprep.py has been run +# when unicodedata is modified to ensure conformant behavior. +import unicodedata -assert unicodedata.unidata_version == '3.2.0' +assert unicodedata.unidata_version == '17.0.0' + +from unicodedata import ucd_3_2_0 as unicodedata_320 + +assert unicodedata_320.unidata_version == '3.2.0' def in_table_a1(code): - if unicodedata.category(code) != 'Cn': return False + if unicodedata_320.category(code) != 'Cn': return False c = ord(code) if 0xFDD0 <= c < 0xFDF0: return False return (c & 0xFFFF) not in (0xFFFE, 0xFFFF) @@ -22,57 +28,233 @@ def in_table_b1(code): b3_exceptions = { -0xb5:'\u03bc', 0xdf:'ss', 0x130:'i\u0307', 0x149:'\u02bcn', -0x17f:'s', 0x1f0:'j\u030c', 0x345:'\u03b9', 0x37a:' \u03b9', -0x390:'\u03b9\u0308\u0301', 0x3b0:'\u03c5\u0308\u0301', 0x3c2:'\u03c3', 0x3d0:'\u03b2', -0x3d1:'\u03b8', 0x3d2:'\u03c5', 0x3d3:'\u03cd', 0x3d4:'\u03cb', -0x3d5:'\u03c6', 0x3d6:'\u03c0', 0x3f0:'\u03ba', 0x3f1:'\u03c1', -0x3f2:'\u03c3', 0x3f5:'\u03b5', 0x587:'\u0565\u0582', 0x1e96:'h\u0331', -0x1e97:'t\u0308', 0x1e98:'w\u030a', 0x1e99:'y\u030a', 0x1e9a:'a\u02be', -0x1e9b:'\u1e61', 0x1f50:'\u03c5\u0313', 0x1f52:'\u03c5\u0313\u0300', 0x1f54:'\u03c5\u0313\u0301', -0x1f56:'\u03c5\u0313\u0342', 0x1f80:'\u1f00\u03b9', 0x1f81:'\u1f01\u03b9', 0x1f82:'\u1f02\u03b9', -0x1f83:'\u1f03\u03b9', 0x1f84:'\u1f04\u03b9', 0x1f85:'\u1f05\u03b9', 0x1f86:'\u1f06\u03b9', -0x1f87:'\u1f07\u03b9', 0x1f88:'\u1f00\u03b9', 0x1f89:'\u1f01\u03b9', 0x1f8a:'\u1f02\u03b9', -0x1f8b:'\u1f03\u03b9', 0x1f8c:'\u1f04\u03b9', 0x1f8d:'\u1f05\u03b9', 0x1f8e:'\u1f06\u03b9', -0x1f8f:'\u1f07\u03b9', 0x1f90:'\u1f20\u03b9', 0x1f91:'\u1f21\u03b9', 0x1f92:'\u1f22\u03b9', -0x1f93:'\u1f23\u03b9', 0x1f94:'\u1f24\u03b9', 0x1f95:'\u1f25\u03b9', 0x1f96:'\u1f26\u03b9', -0x1f97:'\u1f27\u03b9', 0x1f98:'\u1f20\u03b9', 0x1f99:'\u1f21\u03b9', 0x1f9a:'\u1f22\u03b9', -0x1f9b:'\u1f23\u03b9', 0x1f9c:'\u1f24\u03b9', 0x1f9d:'\u1f25\u03b9', 0x1f9e:'\u1f26\u03b9', -0x1f9f:'\u1f27\u03b9', 0x1fa0:'\u1f60\u03b9', 0x1fa1:'\u1f61\u03b9', 0x1fa2:'\u1f62\u03b9', -0x1fa3:'\u1f63\u03b9', 0x1fa4:'\u1f64\u03b9', 0x1fa5:'\u1f65\u03b9', 0x1fa6:'\u1f66\u03b9', -0x1fa7:'\u1f67\u03b9', 0x1fa8:'\u1f60\u03b9', 0x1fa9:'\u1f61\u03b9', 0x1faa:'\u1f62\u03b9', -0x1fab:'\u1f63\u03b9', 0x1fac:'\u1f64\u03b9', 0x1fad:'\u1f65\u03b9', 0x1fae:'\u1f66\u03b9', -0x1faf:'\u1f67\u03b9', 0x1fb2:'\u1f70\u03b9', 0x1fb3:'\u03b1\u03b9', 0x1fb4:'\u03ac\u03b9', -0x1fb6:'\u03b1\u0342', 0x1fb7:'\u03b1\u0342\u03b9', 0x1fbc:'\u03b1\u03b9', 0x1fbe:'\u03b9', -0x1fc2:'\u1f74\u03b9', 0x1fc3:'\u03b7\u03b9', 0x1fc4:'\u03ae\u03b9', 0x1fc6:'\u03b7\u0342', -0x1fc7:'\u03b7\u0342\u03b9', 0x1fcc:'\u03b7\u03b9', 0x1fd2:'\u03b9\u0308\u0300', 0x1fd3:'\u03b9\u0308\u0301', -0x1fd6:'\u03b9\u0342', 0x1fd7:'\u03b9\u0308\u0342', 0x1fe2:'\u03c5\u0308\u0300', 0x1fe3:'\u03c5\u0308\u0301', -0x1fe4:'\u03c1\u0313', 0x1fe6:'\u03c5\u0342', 0x1fe7:'\u03c5\u0308\u0342', 0x1ff2:'\u1f7c\u03b9', -0x1ff3:'\u03c9\u03b9', 0x1ff4:'\u03ce\u03b9', 0x1ff6:'\u03c9\u0342', 0x1ff7:'\u03c9\u0342\u03b9', -0x1ffc:'\u03c9\u03b9', 0x20a8:'rs', 0x2102:'c', 0x2103:'\xb0c', -0x2107:'\u025b', 0x2109:'\xb0f', 0x210b:'h', 0x210c:'h', -0x210d:'h', 0x2110:'i', 0x2111:'i', 0x2112:'l', -0x2115:'n', 0x2116:'no', 0x2119:'p', 0x211a:'q', -0x211b:'r', 0x211c:'r', 0x211d:'r', 0x2120:'sm', -0x2121:'tel', 0x2122:'tm', 0x2124:'z', 0x2128:'z', -0x212c:'b', 0x212d:'c', 0x2130:'e', 0x2131:'f', -0x2133:'m', 0x213e:'\u03b3', 0x213f:'\u03c0', 0x2145:'d', -0x3371:'hpa', 0x3373:'au', 0x3375:'ov', 0x3380:'pa', -0x3381:'na', 0x3382:'\u03bca', 0x3383:'ma', 0x3384:'ka', -0x3385:'kb', 0x3386:'mb', 0x3387:'gb', 0x338a:'pf', -0x338b:'nf', 0x338c:'\u03bcf', 0x3390:'hz', 0x3391:'khz', -0x3392:'mhz', 0x3393:'ghz', 0x3394:'thz', 0x33a9:'pa', -0x33aa:'kpa', 0x33ab:'mpa', 0x33ac:'gpa', 0x33b4:'pv', -0x33b5:'nv', 0x33b6:'\u03bcv', 0x33b7:'mv', 0x33b8:'kv', -0x33b9:'mv', 0x33ba:'pw', 0x33bb:'nw', 0x33bc:'\u03bcw', -0x33bd:'mw', 0x33be:'kw', 0x33bf:'mw', 0x33c0:'k\u03c9', -0x33c1:'m\u03c9', 0x33c3:'bq', 0x33c6:'c\u2215kg', 0x33c7:'co.', -0x33c8:'db', 0x33c9:'gy', 0x33cb:'hp', 0x33cd:'kk', -0x33ce:'km', 0x33d7:'ph', 0x33d9:'ppm', 0x33da:'pr', -0x33dc:'sv', 0x33dd:'wb', 0xfb00:'ff', 0xfb01:'fi', -0xfb02:'fl', 0xfb03:'ffi', 0xfb04:'ffl', 0xfb05:'st', -0xfb06:'st', 0xfb13:'\u0574\u0576', 0xfb14:'\u0574\u0565', 0xfb15:'\u0574\u056b', -0xfb16:'\u057e\u0576', 0xfb17:'\u0574\u056d', 0x1d400:'a', 0x1d401:'b', +0xb5:'\u03bc', 0xdf:'ss', 0x149:'\u02bcn', 0x17f:'s', +0x1f0:'j\u030c', 0x23a:'\u023a', 0x23b:'\u023b', 0x23d:'\u023d', +0x23e:'\u023e', 0x241:'\u0241', 0x243:'\u0243', 0x244:'\u0244', +0x245:'\u0245', 0x246:'\u0246', 0x248:'\u0248', 0x24a:'\u024a', +0x24c:'\u024c', 0x24e:'\u024e', 0x345:'\u03b9', 0x370:'\u0370', +0x372:'\u0372', 0x376:'\u0376', 0x37a:' \u03b9', 0x37f:'\u037f', +0x390:'\u03b9\u0308\u0301', 0x3b0:'\u03c5\u0308\u0301', 0x3c2:'\u03c3', 0x3cf:'\u03cf', +0x3d0:'\u03b2', 0x3d1:'\u03b8', 0x3d2:'\u03c5', 0x3d3:'\u03cd', +0x3d4:'\u03cb', 0x3d5:'\u03c6', 0x3d6:'\u03c0', 0x3f0:'\u03ba', +0x3f1:'\u03c1', 0x3f2:'\u03c3', 0x3f5:'\u03b5', 0x3f7:'\u03f7', +0x3f9:'\u03f9', 0x3fa:'\u03fa', 0x3fd:'\u03fd', 0x3fe:'\u03fe', +0x3ff:'\u03ff', 0x4c0:'\u04c0', 0x4f6:'\u04f6', 0x4fa:'\u04fa', +0x4fc:'\u04fc', 0x4fe:'\u04fe', 0x510:'\u0510', 0x512:'\u0512', +0x514:'\u0514', 0x516:'\u0516', 0x518:'\u0518', 0x51a:'\u051a', +0x51c:'\u051c', 0x51e:'\u051e', 0x520:'\u0520', 0x522:'\u0522', +0x524:'\u0524', 0x526:'\u0526', 0x528:'\u0528', 0x52a:'\u052a', +0x52c:'\u052c', 0x52e:'\u052e', 0x587:'\u0565\u0582', 0x10a0:'\u10a0', +0x10a1:'\u10a1', 0x10a2:'\u10a2', 0x10a3:'\u10a3', 0x10a4:'\u10a4', +0x10a5:'\u10a5', 0x10a6:'\u10a6', 0x10a7:'\u10a7', 0x10a8:'\u10a8', +0x10a9:'\u10a9', 0x10aa:'\u10aa', 0x10ab:'\u10ab', 0x10ac:'\u10ac', +0x10ad:'\u10ad', 0x10ae:'\u10ae', 0x10af:'\u10af', 0x10b0:'\u10b0', +0x10b1:'\u10b1', 0x10b2:'\u10b2', 0x10b3:'\u10b3', 0x10b4:'\u10b4', +0x10b5:'\u10b5', 0x10b6:'\u10b6', 0x10b7:'\u10b7', 0x10b8:'\u10b8', +0x10b9:'\u10b9', 0x10ba:'\u10ba', 0x10bb:'\u10bb', 0x10bc:'\u10bc', +0x10bd:'\u10bd', 0x10be:'\u10be', 0x10bf:'\u10bf', 0x10c0:'\u10c0', +0x10c1:'\u10c1', 0x10c2:'\u10c2', 0x10c3:'\u10c3', 0x10c4:'\u10c4', +0x10c5:'\u10c5', 0x10c7:'\u10c7', 0x10cd:'\u10cd', 0x13a0:'\u13a0', +0x13a1:'\u13a1', 0x13a2:'\u13a2', 0x13a3:'\u13a3', 0x13a4:'\u13a4', +0x13a5:'\u13a5', 0x13a6:'\u13a6', 0x13a7:'\u13a7', 0x13a8:'\u13a8', +0x13a9:'\u13a9', 0x13aa:'\u13aa', 0x13ab:'\u13ab', 0x13ac:'\u13ac', +0x13ad:'\u13ad', 0x13ae:'\u13ae', 0x13af:'\u13af', 0x13b0:'\u13b0', +0x13b1:'\u13b1', 0x13b2:'\u13b2', 0x13b3:'\u13b3', 0x13b4:'\u13b4', +0x13b5:'\u13b5', 0x13b6:'\u13b6', 0x13b7:'\u13b7', 0x13b8:'\u13b8', +0x13b9:'\u13b9', 0x13ba:'\u13ba', 0x13bb:'\u13bb', 0x13bc:'\u13bc', +0x13bd:'\u13bd', 0x13be:'\u13be', 0x13bf:'\u13bf', 0x13c0:'\u13c0', +0x13c1:'\u13c1', 0x13c2:'\u13c2', 0x13c3:'\u13c3', 0x13c4:'\u13c4', +0x13c5:'\u13c5', 0x13c6:'\u13c6', 0x13c7:'\u13c7', 0x13c8:'\u13c8', +0x13c9:'\u13c9', 0x13ca:'\u13ca', 0x13cb:'\u13cb', 0x13cc:'\u13cc', +0x13cd:'\u13cd', 0x13ce:'\u13ce', 0x13cf:'\u13cf', 0x13d0:'\u13d0', +0x13d1:'\u13d1', 0x13d2:'\u13d2', 0x13d3:'\u13d3', 0x13d4:'\u13d4', +0x13d5:'\u13d5', 0x13d6:'\u13d6', 0x13d7:'\u13d7', 0x13d8:'\u13d8', +0x13d9:'\u13d9', 0x13da:'\u13da', 0x13db:'\u13db', 0x13dc:'\u13dc', +0x13dd:'\u13dd', 0x13de:'\u13de', 0x13df:'\u13df', 0x13e0:'\u13e0', +0x13e1:'\u13e1', 0x13e2:'\u13e2', 0x13e3:'\u13e3', 0x13e4:'\u13e4', +0x13e5:'\u13e5', 0x13e6:'\u13e6', 0x13e7:'\u13e7', 0x13e8:'\u13e8', +0x13e9:'\u13e9', 0x13ea:'\u13ea', 0x13eb:'\u13eb', 0x13ec:'\u13ec', +0x13ed:'\u13ed', 0x13ee:'\u13ee', 0x13ef:'\u13ef', 0x13f0:'\u13f0', +0x13f1:'\u13f1', 0x13f2:'\u13f2', 0x13f3:'\u13f3', 0x13f4:'\u13f4', +0x13f5:'\u13f5', 0x1c89:'\u1c89', 0x1c90:'\u1c90', 0x1c91:'\u1c91', +0x1c92:'\u1c92', 0x1c93:'\u1c93', 0x1c94:'\u1c94', 0x1c95:'\u1c95', +0x1c96:'\u1c96', 0x1c97:'\u1c97', 0x1c98:'\u1c98', 0x1c99:'\u1c99', +0x1c9a:'\u1c9a', 0x1c9b:'\u1c9b', 0x1c9c:'\u1c9c', 0x1c9d:'\u1c9d', +0x1c9e:'\u1c9e', 0x1c9f:'\u1c9f', 0x1ca0:'\u1ca0', 0x1ca1:'\u1ca1', +0x1ca2:'\u1ca2', 0x1ca3:'\u1ca3', 0x1ca4:'\u1ca4', 0x1ca5:'\u1ca5', +0x1ca6:'\u1ca6', 0x1ca7:'\u1ca7', 0x1ca8:'\u1ca8', 0x1ca9:'\u1ca9', +0x1caa:'\u1caa', 0x1cab:'\u1cab', 0x1cac:'\u1cac', 0x1cad:'\u1cad', +0x1cae:'\u1cae', 0x1caf:'\u1caf', 0x1cb0:'\u1cb0', 0x1cb1:'\u1cb1', +0x1cb2:'\u1cb2', 0x1cb3:'\u1cb3', 0x1cb4:'\u1cb4', 0x1cb5:'\u1cb5', +0x1cb6:'\u1cb6', 0x1cb7:'\u1cb7', 0x1cb8:'\u1cb8', 0x1cb9:'\u1cb9', +0x1cba:'\u1cba', 0x1cbd:'\u1cbd', 0x1cbe:'\u1cbe', 0x1cbf:'\u1cbf', +0x1e96:'h\u0331', 0x1e97:'t\u0308', 0x1e98:'w\u030a', 0x1e99:'y\u030a', +0x1e9a:'a\u02be', 0x1e9b:'\u1e61', 0x1e9e:'\u1e9e', 0x1efa:'\u1efa', +0x1efc:'\u1efc', 0x1efe:'\u1efe', 0x1f50:'\u03c5\u0313', 0x1f52:'\u03c5\u0313\u0300', +0x1f54:'\u03c5\u0313\u0301', 0x1f56:'\u03c5\u0313\u0342', 0x1f80:'\u1f00\u03b9', 0x1f81:'\u1f01\u03b9', +0x1f82:'\u1f02\u03b9', 0x1f83:'\u1f03\u03b9', 0x1f84:'\u1f04\u03b9', 0x1f85:'\u1f05\u03b9', +0x1f86:'\u1f06\u03b9', 0x1f87:'\u1f07\u03b9', 0x1f88:'\u1f00\u03b9', 0x1f89:'\u1f01\u03b9', +0x1f8a:'\u1f02\u03b9', 0x1f8b:'\u1f03\u03b9', 0x1f8c:'\u1f04\u03b9', 0x1f8d:'\u1f05\u03b9', +0x1f8e:'\u1f06\u03b9', 0x1f8f:'\u1f07\u03b9', 0x1f90:'\u1f20\u03b9', 0x1f91:'\u1f21\u03b9', +0x1f92:'\u1f22\u03b9', 0x1f93:'\u1f23\u03b9', 0x1f94:'\u1f24\u03b9', 0x1f95:'\u1f25\u03b9', +0x1f96:'\u1f26\u03b9', 0x1f97:'\u1f27\u03b9', 0x1f98:'\u1f20\u03b9', 0x1f99:'\u1f21\u03b9', +0x1f9a:'\u1f22\u03b9', 0x1f9b:'\u1f23\u03b9', 0x1f9c:'\u1f24\u03b9', 0x1f9d:'\u1f25\u03b9', +0x1f9e:'\u1f26\u03b9', 0x1f9f:'\u1f27\u03b9', 0x1fa0:'\u1f60\u03b9', 0x1fa1:'\u1f61\u03b9', +0x1fa2:'\u1f62\u03b9', 0x1fa3:'\u1f63\u03b9', 0x1fa4:'\u1f64\u03b9', 0x1fa5:'\u1f65\u03b9', +0x1fa6:'\u1f66\u03b9', 0x1fa7:'\u1f67\u03b9', 0x1fa8:'\u1f60\u03b9', 0x1fa9:'\u1f61\u03b9', +0x1faa:'\u1f62\u03b9', 0x1fab:'\u1f63\u03b9', 0x1fac:'\u1f64\u03b9', 0x1fad:'\u1f65\u03b9', +0x1fae:'\u1f66\u03b9', 0x1faf:'\u1f67\u03b9', 0x1fb2:'\u1f70\u03b9', 0x1fb3:'\u03b1\u03b9', +0x1fb4:'\u03ac\u03b9', 0x1fb6:'\u03b1\u0342', 0x1fb7:'\u03b1\u0342\u03b9', 0x1fbc:'\u03b1\u03b9', +0x1fbe:'\u03b9', 0x1fc2:'\u1f74\u03b9', 0x1fc3:'\u03b7\u03b9', 0x1fc4:'\u03ae\u03b9', +0x1fc6:'\u03b7\u0342', 0x1fc7:'\u03b7\u0342\u03b9', 0x1fcc:'\u03b7\u03b9', 0x1fd2:'\u03b9\u0308\u0300', +0x1fd3:'\u03b9\u0308\u0301', 0x1fd6:'\u03b9\u0342', 0x1fd7:'\u03b9\u0308\u0342', 0x1fe2:'\u03c5\u0308\u0300', +0x1fe3:'\u03c5\u0308\u0301', 0x1fe4:'\u03c1\u0313', 0x1fe6:'\u03c5\u0342', 0x1fe7:'\u03c5\u0308\u0342', +0x1ff2:'\u1f7c\u03b9', 0x1ff3:'\u03c9\u03b9', 0x1ff4:'\u03ce\u03b9', 0x1ff6:'\u03c9\u0342', +0x1ff7:'\u03c9\u0342\u03b9', 0x1ffc:'\u03c9\u03b9', 0x20a8:'rs', 0x2102:'c', +0x2103:'\xb0c', 0x2107:'\u025b', 0x2109:'\xb0f', 0x210b:'h', +0x210c:'h', 0x210d:'h', 0x2110:'i', 0x2111:'i', +0x2112:'l', 0x2115:'n', 0x2116:'no', 0x2119:'p', +0x211a:'q', 0x211b:'r', 0x211c:'r', 0x211d:'r', +0x2120:'sm', 0x2121:'tel', 0x2122:'tm', 0x2124:'z', +0x2128:'z', 0x212c:'b', 0x212d:'c', 0x2130:'e', +0x2131:'f', 0x2132:'\u2132', 0x2133:'m', 0x213e:'\u03b3', +0x213f:'\u03c0', 0x2145:'d', 0x2183:'\u2183', 0x2c00:'\u2c00', +0x2c01:'\u2c01', 0x2c02:'\u2c02', 0x2c03:'\u2c03', 0x2c04:'\u2c04', +0x2c05:'\u2c05', 0x2c06:'\u2c06', 0x2c07:'\u2c07', 0x2c08:'\u2c08', +0x2c09:'\u2c09', 0x2c0a:'\u2c0a', 0x2c0b:'\u2c0b', 0x2c0c:'\u2c0c', +0x2c0d:'\u2c0d', 0x2c0e:'\u2c0e', 0x2c0f:'\u2c0f', 0x2c10:'\u2c10', +0x2c11:'\u2c11', 0x2c12:'\u2c12', 0x2c13:'\u2c13', 0x2c14:'\u2c14', +0x2c15:'\u2c15', 0x2c16:'\u2c16', 0x2c17:'\u2c17', 0x2c18:'\u2c18', +0x2c19:'\u2c19', 0x2c1a:'\u2c1a', 0x2c1b:'\u2c1b', 0x2c1c:'\u2c1c', +0x2c1d:'\u2c1d', 0x2c1e:'\u2c1e', 0x2c1f:'\u2c1f', 0x2c20:'\u2c20', +0x2c21:'\u2c21', 0x2c22:'\u2c22', 0x2c23:'\u2c23', 0x2c24:'\u2c24', +0x2c25:'\u2c25', 0x2c26:'\u2c26', 0x2c27:'\u2c27', 0x2c28:'\u2c28', +0x2c29:'\u2c29', 0x2c2a:'\u2c2a', 0x2c2b:'\u2c2b', 0x2c2c:'\u2c2c', +0x2c2d:'\u2c2d', 0x2c2e:'\u2c2e', 0x2c2f:'\u2c2f', 0x2c60:'\u2c60', +0x2c62:'\u2c62', 0x2c63:'\u2c63', 0x2c64:'\u2c64', 0x2c67:'\u2c67', +0x2c69:'\u2c69', 0x2c6b:'\u2c6b', 0x2c6d:'\u2c6d', 0x2c6e:'\u2c6e', +0x2c6f:'\u2c6f', 0x2c70:'\u2c70', 0x2c72:'\u2c72', 0x2c75:'\u2c75', +0x2c7e:'\u2c7e', 0x2c7f:'\u2c7f', 0x2c80:'\u2c80', 0x2c82:'\u2c82', +0x2c84:'\u2c84', 0x2c86:'\u2c86', 0x2c88:'\u2c88', 0x2c8a:'\u2c8a', +0x2c8c:'\u2c8c', 0x2c8e:'\u2c8e', 0x2c90:'\u2c90', 0x2c92:'\u2c92', +0x2c94:'\u2c94', 0x2c96:'\u2c96', 0x2c98:'\u2c98', 0x2c9a:'\u2c9a', +0x2c9c:'\u2c9c', 0x2c9e:'\u2c9e', 0x2ca0:'\u2ca0', 0x2ca2:'\u2ca2', +0x2ca4:'\u2ca4', 0x2ca6:'\u2ca6', 0x2ca8:'\u2ca8', 0x2caa:'\u2caa', +0x2cac:'\u2cac', 0x2cae:'\u2cae', 0x2cb0:'\u2cb0', 0x2cb2:'\u2cb2', +0x2cb4:'\u2cb4', 0x2cb6:'\u2cb6', 0x2cb8:'\u2cb8', 0x2cba:'\u2cba', +0x2cbc:'\u2cbc', 0x2cbe:'\u2cbe', 0x2cc0:'\u2cc0', 0x2cc2:'\u2cc2', +0x2cc4:'\u2cc4', 0x2cc6:'\u2cc6', 0x2cc8:'\u2cc8', 0x2cca:'\u2cca', +0x2ccc:'\u2ccc', 0x2cce:'\u2cce', 0x2cd0:'\u2cd0', 0x2cd2:'\u2cd2', +0x2cd4:'\u2cd4', 0x2cd6:'\u2cd6', 0x2cd8:'\u2cd8', 0x2cda:'\u2cda', +0x2cdc:'\u2cdc', 0x2cde:'\u2cde', 0x2ce0:'\u2ce0', 0x2ce2:'\u2ce2', +0x2ceb:'\u2ceb', 0x2ced:'\u2ced', 0x2cf2:'\u2cf2', 0x3371:'hpa', +0x3373:'au', 0x3375:'ov', 0x3380:'pa', 0x3381:'na', +0x3382:'\u03bca', 0x3383:'ma', 0x3384:'ka', 0x3385:'kb', +0x3386:'mb', 0x3387:'gb', 0x338a:'pf', 0x338b:'nf', +0x338c:'\u03bcf', 0x3390:'hz', 0x3391:'khz', 0x3392:'mhz', +0x3393:'ghz', 0x3394:'thz', 0x33a9:'pa', 0x33aa:'kpa', +0x33ab:'mpa', 0x33ac:'gpa', 0x33b4:'pv', 0x33b5:'nv', +0x33b6:'\u03bcv', 0x33b7:'mv', 0x33b8:'kv', 0x33b9:'mv', +0x33ba:'pw', 0x33bb:'nw', 0x33bc:'\u03bcw', 0x33bd:'mw', +0x33be:'kw', 0x33bf:'mw', 0x33c0:'k\u03c9', 0x33c1:'m\u03c9', +0x33c3:'bq', 0x33c6:'c\u2215kg', 0x33c7:'co.', 0x33c8:'db', +0x33c9:'gy', 0x33cb:'hp', 0x33cd:'kk', 0x33ce:'km', +0x33d7:'ph', 0x33d9:'ppm', 0x33da:'pr', 0x33dc:'sv', +0x33dd:'wb', 0xa640:'\ua640', 0xa642:'\ua642', 0xa644:'\ua644', +0xa646:'\ua646', 0xa648:'\ua648', 0xa64a:'\ua64a', 0xa64c:'\ua64c', +0xa64e:'\ua64e', 0xa650:'\ua650', 0xa652:'\ua652', 0xa654:'\ua654', +0xa656:'\ua656', 0xa658:'\ua658', 0xa65a:'\ua65a', 0xa65c:'\ua65c', +0xa65e:'\ua65e', 0xa660:'\ua660', 0xa662:'\ua662', 0xa664:'\ua664', +0xa666:'\ua666', 0xa668:'\ua668', 0xa66a:'\ua66a', 0xa66c:'\ua66c', +0xa680:'\ua680', 0xa682:'\ua682', 0xa684:'\ua684', 0xa686:'\ua686', +0xa688:'\ua688', 0xa68a:'\ua68a', 0xa68c:'\ua68c', 0xa68e:'\ua68e', +0xa690:'\ua690', 0xa692:'\ua692', 0xa694:'\ua694', 0xa696:'\ua696', +0xa698:'\ua698', 0xa69a:'\ua69a', 0xa722:'\ua722', 0xa724:'\ua724', +0xa726:'\ua726', 0xa728:'\ua728', 0xa72a:'\ua72a', 0xa72c:'\ua72c', +0xa72e:'\ua72e', 0xa732:'\ua732', 0xa734:'\ua734', 0xa736:'\ua736', +0xa738:'\ua738', 0xa73a:'\ua73a', 0xa73c:'\ua73c', 0xa73e:'\ua73e', +0xa740:'\ua740', 0xa742:'\ua742', 0xa744:'\ua744', 0xa746:'\ua746', +0xa748:'\ua748', 0xa74a:'\ua74a', 0xa74c:'\ua74c', 0xa74e:'\ua74e', +0xa750:'\ua750', 0xa752:'\ua752', 0xa754:'\ua754', 0xa756:'\ua756', +0xa758:'\ua758', 0xa75a:'\ua75a', 0xa75c:'\ua75c', 0xa75e:'\ua75e', +0xa760:'\ua760', 0xa762:'\ua762', 0xa764:'\ua764', 0xa766:'\ua766', +0xa768:'\ua768', 0xa76a:'\ua76a', 0xa76c:'\ua76c', 0xa76e:'\ua76e', +0xa779:'\ua779', 0xa77b:'\ua77b', 0xa77d:'\ua77d', 0xa77e:'\ua77e', +0xa780:'\ua780', 0xa782:'\ua782', 0xa784:'\ua784', 0xa786:'\ua786', +0xa78b:'\ua78b', 0xa78d:'\ua78d', 0xa790:'\ua790', 0xa792:'\ua792', +0xa796:'\ua796', 0xa798:'\ua798', 0xa79a:'\ua79a', 0xa79c:'\ua79c', +0xa79e:'\ua79e', 0xa7a0:'\ua7a0', 0xa7a2:'\ua7a2', 0xa7a4:'\ua7a4', +0xa7a6:'\ua7a6', 0xa7a8:'\ua7a8', 0xa7aa:'\ua7aa', 0xa7ab:'\ua7ab', +0xa7ac:'\ua7ac', 0xa7ad:'\ua7ad', 0xa7ae:'\ua7ae', 0xa7b0:'\ua7b0', +0xa7b1:'\ua7b1', 0xa7b2:'\ua7b2', 0xa7b3:'\ua7b3', 0xa7b4:'\ua7b4', +0xa7b6:'\ua7b6', 0xa7b8:'\ua7b8', 0xa7ba:'\ua7ba', 0xa7bc:'\ua7bc', +0xa7be:'\ua7be', 0xa7c0:'\ua7c0', 0xa7c2:'\ua7c2', 0xa7c4:'\ua7c4', +0xa7c5:'\ua7c5', 0xa7c6:'\ua7c6', 0xa7c7:'\ua7c7', 0xa7c9:'\ua7c9', +0xa7cb:'\ua7cb', 0xa7cc:'\ua7cc', 0xa7ce:'\ua7ce', 0xa7d0:'\ua7d0', +0xa7d2:'\ua7d2', 0xa7d4:'\ua7d4', 0xa7d6:'\ua7d6', 0xa7d8:'\ua7d8', +0xa7da:'\ua7da', 0xa7dc:'\ua7dc', 0xa7f5:'\ua7f5', 0xfb00:'ff', +0xfb01:'fi', 0xfb02:'fl', 0xfb03:'ffi', 0xfb04:'ffl', +0xfb05:'st', 0xfb06:'st', 0xfb13:'\u0574\u0576', 0xfb14:'\u0574\u0565', +0xfb15:'\u0574\u056b', 0xfb16:'\u057e\u0576', 0xfb17:'\u0574\u056d', 0x10426:'\U00010426', +0x10427:'\U00010427', 0x104b0:'\U000104b0', 0x104b1:'\U000104b1', 0x104b2:'\U000104b2', +0x104b3:'\U000104b3', 0x104b4:'\U000104b4', 0x104b5:'\U000104b5', 0x104b6:'\U000104b6', +0x104b7:'\U000104b7', 0x104b8:'\U000104b8', 0x104b9:'\U000104b9', 0x104ba:'\U000104ba', +0x104bb:'\U000104bb', 0x104bc:'\U000104bc', 0x104bd:'\U000104bd', 0x104be:'\U000104be', +0x104bf:'\U000104bf', 0x104c0:'\U000104c0', 0x104c1:'\U000104c1', 0x104c2:'\U000104c2', +0x104c3:'\U000104c3', 0x104c4:'\U000104c4', 0x104c5:'\U000104c5', 0x104c6:'\U000104c6', +0x104c7:'\U000104c7', 0x104c8:'\U000104c8', 0x104c9:'\U000104c9', 0x104ca:'\U000104ca', +0x104cb:'\U000104cb', 0x104cc:'\U000104cc', 0x104cd:'\U000104cd', 0x104ce:'\U000104ce', +0x104cf:'\U000104cf', 0x104d0:'\U000104d0', 0x104d1:'\U000104d1', 0x104d2:'\U000104d2', +0x104d3:'\U000104d3', 0x10570:'\U00010570', 0x10571:'\U00010571', 0x10572:'\U00010572', +0x10573:'\U00010573', 0x10574:'\U00010574', 0x10575:'\U00010575', 0x10576:'\U00010576', +0x10577:'\U00010577', 0x10578:'\U00010578', 0x10579:'\U00010579', 0x1057a:'\U0001057a', +0x1057c:'\U0001057c', 0x1057d:'\U0001057d', 0x1057e:'\U0001057e', 0x1057f:'\U0001057f', +0x10580:'\U00010580', 0x10581:'\U00010581', 0x10582:'\U00010582', 0x10583:'\U00010583', +0x10584:'\U00010584', 0x10585:'\U00010585', 0x10586:'\U00010586', 0x10587:'\U00010587', +0x10588:'\U00010588', 0x10589:'\U00010589', 0x1058a:'\U0001058a', 0x1058c:'\U0001058c', +0x1058d:'\U0001058d', 0x1058e:'\U0001058e', 0x1058f:'\U0001058f', 0x10590:'\U00010590', +0x10591:'\U00010591', 0x10592:'\U00010592', 0x10594:'\U00010594', 0x10595:'\U00010595', +0x10c80:'\U00010c80', 0x10c81:'\U00010c81', 0x10c82:'\U00010c82', 0x10c83:'\U00010c83', +0x10c84:'\U00010c84', 0x10c85:'\U00010c85', 0x10c86:'\U00010c86', 0x10c87:'\U00010c87', +0x10c88:'\U00010c88', 0x10c89:'\U00010c89', 0x10c8a:'\U00010c8a', 0x10c8b:'\U00010c8b', +0x10c8c:'\U00010c8c', 0x10c8d:'\U00010c8d', 0x10c8e:'\U00010c8e', 0x10c8f:'\U00010c8f', +0x10c90:'\U00010c90', 0x10c91:'\U00010c91', 0x10c92:'\U00010c92', 0x10c93:'\U00010c93', +0x10c94:'\U00010c94', 0x10c95:'\U00010c95', 0x10c96:'\U00010c96', 0x10c97:'\U00010c97', +0x10c98:'\U00010c98', 0x10c99:'\U00010c99', 0x10c9a:'\U00010c9a', 0x10c9b:'\U00010c9b', +0x10c9c:'\U00010c9c', 0x10c9d:'\U00010c9d', 0x10c9e:'\U00010c9e', 0x10c9f:'\U00010c9f', +0x10ca0:'\U00010ca0', 0x10ca1:'\U00010ca1', 0x10ca2:'\U00010ca2', 0x10ca3:'\U00010ca3', +0x10ca4:'\U00010ca4', 0x10ca5:'\U00010ca5', 0x10ca6:'\U00010ca6', 0x10ca7:'\U00010ca7', +0x10ca8:'\U00010ca8', 0x10ca9:'\U00010ca9', 0x10caa:'\U00010caa', 0x10cab:'\U00010cab', +0x10cac:'\U00010cac', 0x10cad:'\U00010cad', 0x10cae:'\U00010cae', 0x10caf:'\U00010caf', +0x10cb0:'\U00010cb0', 0x10cb1:'\U00010cb1', 0x10cb2:'\U00010cb2', 0x10d50:'\U00010d50', +0x10d51:'\U00010d51', 0x10d52:'\U00010d52', 0x10d53:'\U00010d53', 0x10d54:'\U00010d54', +0x10d55:'\U00010d55', 0x10d56:'\U00010d56', 0x10d57:'\U00010d57', 0x10d58:'\U00010d58', +0x10d59:'\U00010d59', 0x10d5a:'\U00010d5a', 0x10d5b:'\U00010d5b', 0x10d5c:'\U00010d5c', +0x10d5d:'\U00010d5d', 0x10d5e:'\U00010d5e', 0x10d5f:'\U00010d5f', 0x10d60:'\U00010d60', +0x10d61:'\U00010d61', 0x10d62:'\U00010d62', 0x10d63:'\U00010d63', 0x10d64:'\U00010d64', +0x10d65:'\U00010d65', 0x118a0:'\U000118a0', 0x118a1:'\U000118a1', 0x118a2:'\U000118a2', +0x118a3:'\U000118a3', 0x118a4:'\U000118a4', 0x118a5:'\U000118a5', 0x118a6:'\U000118a6', +0x118a7:'\U000118a7', 0x118a8:'\U000118a8', 0x118a9:'\U000118a9', 0x118aa:'\U000118aa', +0x118ab:'\U000118ab', 0x118ac:'\U000118ac', 0x118ad:'\U000118ad', 0x118ae:'\U000118ae', +0x118af:'\U000118af', 0x118b0:'\U000118b0', 0x118b1:'\U000118b1', 0x118b2:'\U000118b2', +0x118b3:'\U000118b3', 0x118b4:'\U000118b4', 0x118b5:'\U000118b5', 0x118b6:'\U000118b6', +0x118b7:'\U000118b7', 0x118b8:'\U000118b8', 0x118b9:'\U000118b9', 0x118ba:'\U000118ba', +0x118bb:'\U000118bb', 0x118bc:'\U000118bc', 0x118bd:'\U000118bd', 0x118be:'\U000118be', +0x118bf:'\U000118bf', 0x16e40:'\U00016e40', 0x16e41:'\U00016e41', 0x16e42:'\U00016e42', +0x16e43:'\U00016e43', 0x16e44:'\U00016e44', 0x16e45:'\U00016e45', 0x16e46:'\U00016e46', +0x16e47:'\U00016e47', 0x16e48:'\U00016e48', 0x16e49:'\U00016e49', 0x16e4a:'\U00016e4a', +0x16e4b:'\U00016e4b', 0x16e4c:'\U00016e4c', 0x16e4d:'\U00016e4d', 0x16e4e:'\U00016e4e', +0x16e4f:'\U00016e4f', 0x16e50:'\U00016e50', 0x16e51:'\U00016e51', 0x16e52:'\U00016e52', +0x16e53:'\U00016e53', 0x16e54:'\U00016e54', 0x16e55:'\U00016e55', 0x16e56:'\U00016e56', +0x16e57:'\U00016e57', 0x16e58:'\U00016e58', 0x16e59:'\U00016e59', 0x16e5a:'\U00016e5a', +0x16e5b:'\U00016e5b', 0x16e5c:'\U00016e5c', 0x16e5d:'\U00016e5d', 0x16e5e:'\U00016e5e', +0x16e5f:'\U00016e5f', 0x16ea0:'\U00016ea0', 0x16ea1:'\U00016ea1', 0x16ea2:'\U00016ea2', +0x16ea3:'\U00016ea3', 0x16ea4:'\U00016ea4', 0x16ea5:'\U00016ea5', 0x16ea6:'\U00016ea6', +0x16ea7:'\U00016ea7', 0x16ea8:'\U00016ea8', 0x16ea9:'\U00016ea9', 0x16eaa:'\U00016eaa', +0x16eab:'\U00016eab', 0x16eac:'\U00016eac', 0x16ead:'\U00016ead', 0x16eae:'\U00016eae', +0x16eaf:'\U00016eaf', 0x16eb0:'\U00016eb0', 0x16eb1:'\U00016eb1', 0x16eb2:'\U00016eb2', +0x16eb3:'\U00016eb3', 0x16eb4:'\U00016eb4', 0x16eb5:'\U00016eb5', 0x16eb6:'\U00016eb6', +0x16eb7:'\U00016eb7', 0x16eb8:'\U00016eb8', 0x1d400:'a', 0x1d401:'b', 0x1d402:'c', 0x1d403:'d', 0x1d404:'e', 0x1d405:'f', 0x1d406:'g', 0x1d407:'h', 0x1d408:'i', 0x1d409:'j', 0x1d40a:'k', 0x1d40b:'l', 0x1d40c:'m', 0x1d40d:'n', @@ -184,7 +366,16 @@ def in_table_b1(code): 0x1d79c:'\u03bd', 0x1d79d:'\u03be', 0x1d79e:'\u03bf', 0x1d79f:'\u03c0', 0x1d7a0:'\u03c1', 0x1d7a1:'\u03b8', 0x1d7a2:'\u03c3', 0x1d7a3:'\u03c4', 0x1d7a4:'\u03c5', 0x1d7a5:'\u03c6', 0x1d7a6:'\u03c7', 0x1d7a7:'\u03c8', -0x1d7a8:'\u03c9', 0x1d7bb:'\u03c3', } +0x1d7a8:'\u03c9', 0x1d7bb:'\u03c3', 0x1e900:'\U0001e900', 0x1e901:'\U0001e901', +0x1e902:'\U0001e902', 0x1e903:'\U0001e903', 0x1e904:'\U0001e904', 0x1e905:'\U0001e905', +0x1e906:'\U0001e906', 0x1e907:'\U0001e907', 0x1e908:'\U0001e908', 0x1e909:'\U0001e909', +0x1e90a:'\U0001e90a', 0x1e90b:'\U0001e90b', 0x1e90c:'\U0001e90c', 0x1e90d:'\U0001e90d', +0x1e90e:'\U0001e90e', 0x1e90f:'\U0001e90f', 0x1e910:'\U0001e910', 0x1e911:'\U0001e911', +0x1e912:'\U0001e912', 0x1e913:'\U0001e913', 0x1e914:'\U0001e914', 0x1e915:'\U0001e915', +0x1e916:'\U0001e916', 0x1e917:'\U0001e917', 0x1e918:'\U0001e918', 0x1e919:'\U0001e919', +0x1e91a:'\U0001e91a', 0x1e91b:'\U0001e91b', 0x1e91c:'\U0001e91c', 0x1e91d:'\U0001e91d', +0x1e91e:'\U0001e91e', 0x1e91f:'\U0001e91f', 0x1e920:'\U0001e920', 0x1e921:'\U0001e921', +} def map_table_b3(code): r = b3_exceptions.get(ord(code)) @@ -194,9 +385,9 @@ def map_table_b3(code): def map_table_b2(a): al = map_table_b3(a) - b = unicodedata.normalize("NFKC", al) + b = unicodedata_320.normalize("NFKC", al) bl = "".join([map_table_b3(ch) for ch in b]) - c = unicodedata.normalize("NFKC", bl) + c = unicodedata_320.normalize("NFKC", bl) if b != c: return c else: @@ -208,29 +399,29 @@ def in_table_c11(code): def in_table_c12(code): - return unicodedata.category(code) == "Zs" and code != " " + return unicodedata_320.category(code) == "Zs" and code != " " def in_table_c11_c12(code): - return unicodedata.category(code) == "Zs" + return unicodedata_320.category(code) == "Zs" def in_table_c21(code): - return ord(code) < 128 and unicodedata.category(code) == "Cc" + return ord(code) < 128 and unicodedata_320.category(code) == "Cc" c22_specials = set([1757, 1807, 6158, 8204, 8205, 8232, 8233, 65279] + list(range(8288,8292)) + list(range(8298,8304)) + list(range(65529,65533)) + list(range(119155,119163))) def in_table_c22(code): c = ord(code) if c < 128: return False - if unicodedata.category(code) == "Cc": return True + if unicodedata_320.category(code) == "Cc": return True return c in c22_specials def in_table_c21_c22(code): - return unicodedata.category(code) == "Cc" or \ + return unicodedata_320.category(code) == "Cc" or \ ord(code) in c22_specials def in_table_c3(code): - return unicodedata.category(code) == "Co" + return unicodedata_320.category(code) == "Co" def in_table_c4(code): @@ -241,7 +432,7 @@ def in_table_c4(code): def in_table_c5(code): - return unicodedata.category(code) == "Cs" + return unicodedata_320.category(code) == "Cs" c6_set = set(range(65529,65534)) @@ -265,8 +456,8 @@ def in_table_c9(code): def in_table_d1(code): - return unicodedata.bidirectional(code) in ("R","AL") + return unicodedata_320.bidirectional(code) in ("R","AL") def in_table_d2(code): - return unicodedata.bidirectional(code) == "L" + return unicodedata_320.bidirectional(code) == "L" diff --git a/Lib/subprocess.py b/Lib/subprocess.py index 52b7b711770..4a956cd6d6e 100644 --- a/Lib/subprocess.py +++ b/Lib/subprocess.py @@ -143,7 +143,7 @@ def __init__(self, returncode, cmd, output=None, stderr=None): self.stderr = stderr def __str__(self): - if self.returncode and self.returncode < 0: + if isinstance(self.returncode, int) and self.returncode < 0: try: return "Command '%s' died with %r." % ( self.cmd, signal.Signals(-self.returncode)) @@ -151,8 +151,8 @@ def __str__(self): return "Command '%s' died with unknown signal %d." % ( self.cmd, -self.returncode) else: - return "Command '%s' returned non-zero exit status %d." % ( - self.cmd, self.returncode) + return (f"Command {self.cmd!r} returned non-zero " + f"exit status {self.returncode}.") @property def stdout(self): @@ -250,6 +250,82 @@ def __repr__(self): else: _PopenSelector = selectors.SelectSelector + def _communicate_io_posix(selector, stdin, input_view, input_offset, + output_buffers, endtime, *, close_on_eof=False): + """ + Low-level POSIX I/O multiplexing loop used by Popen._communicate. + + Handles the select loop for reading/writing but does not manage + stream lifecycle or raise timeout exceptions. + + Args: + selector: A _PopenSelector with streams already registered + stdin: Writable file object for input, or None + input_view: memoryview of input bytes, or None + input_offset: Starting offset into input_view (for resume support) + output_buffers: Dict {file_object: list} to append read chunks to + endtime: Deadline timestamp, or None for no timeout + close_on_eof: If True, close output streams immediately when they + EOF rather than leaving them open for the caller to close. + Used by Popen._communicate() to match its historical behavior + of releasing fds as soon as the child closes the corresponding + pipe. + + Returns: + (new_input_offset, completed) + - new_input_offset: How many bytes of input were written + - completed: True if all I/O finished, False if timed out + + Note: + - Closes output streams on EOF only if close_on_eof=True + - Does NOT raise TimeoutExpired (caller handles) + - Appends to output_buffers lists in place + """ + stdin_fd = stdin.fileno() if stdin else None + + while selector.get_map(): + remaining = _deadline_remaining(endtime) + if remaining is not None and remaining <= 0: + return (input_offset, False) # Timed out + + ready = selector.select(remaining) + + # Check timeout after select (may have woken spuriously) + if endtime is not None and _time() > endtime: + return (input_offset, False) # Timed out + + for key, events in ready: + if key.fd == stdin_fd: + chunk = input_view[input_offset:input_offset + _PIPE_BUF] + try: + input_offset += os.write(key.fd, chunk) + except BrokenPipeError: + selector.unregister(key.fd) + try: + stdin.close() + except BrokenPipeError: + pass + else: + if input_offset >= len(input_view): + selector.unregister(key.fd) + try: + stdin.close() + except BrokenPipeError: + pass + elif key.fileobj in output_buffers: + data = os.read(key.fd, 32768) + if not data: + selector.unregister(key.fileobj) + if close_on_eof: + try: + key.fileobj.close() + except OSError: + pass + else: + output_buffers[key.fileobj].append(data) + + return (input_offset, True) # Completed + if _mswindows: # On Windows we just need to close `Popen._handle` when we no longer need @@ -289,6 +365,45 @@ def _cleanup(): DEVNULL = -3 +def _deadline_remaining(endtime): + """Calculate remaining time until deadline.""" + if endtime is None: + return None + return endtime - _time() + + +def _flush_stdin(stdin): + """Flush stdin, ignoring BrokenPipeError and closed file ValueError.""" + try: + stdin.flush() + except BrokenPipeError: + pass # communicate() must ignore BrokenPipeError. + except ValueError: + # Ignore ValueError: I/O operation on closed file. + if not stdin.closed: + raise + + +def _make_input_view(input_data): + """Convert input data to a byte memoryview for writing. + + Handles the case where input_data is already a memoryview with + non-byte elements (e.g., int32 array) by casting to a byte view. + This ensures len(view) returns the byte count, not element count. + """ + if not input_data: + return None + if isinstance(input_data, memoryview): + return input_data.cast("b") # ensure byte view for correct len() + return memoryview(input_data) + + +def _translate_newlines(data, encoding, errors): + """Decode bytes to str and translate newlines to \n.""" + data = data.decode(encoding, errors) + return data.replace("\r\n", "\n").replace("\r", "\n") + + # XXX This function is only used by multiprocessing and the test suite, # but it's here so that it can be imported when Python is compiled without # threads. @@ -381,8 +496,7 @@ def _text_encoding(): if sys.flags.utf8_mode: return "utf-8" - else: - return locale.getencoding() + return locale.getencoding() def call(*popenargs, timeout=None, **kwargs): @@ -750,6 +864,66 @@ def _use_posix_spawn(): return False +def _can_use_pidfd_open(): + # Availability: Linux >= 5.3 + if not hasattr(os, "pidfd_open"): + return False + try: + pidfd = os.pidfd_open(os.getpid(), 0) + except OSError as err: + if err.errno in {errno.EMFILE, errno.ENFILE}: + # transitory 'too many open files' + return True + # likely blocked by security policy like SECCOMP (EPERM, + # EACCES, ENOSYS) + return False + else: + os.close(pidfd) + return True + + +def _can_use_kqueue(): + # Availability: macOS, BSD + names = ( + "kqueue", + "KQ_EV_ADD", + "KQ_EV_ONESHOT", + "KQ_FILTER_PROC", + "KQ_NOTE_EXIT", + ) + if not all(hasattr(select, x) for x in names): + return False + kq = None + try: + kq = select.kqueue() + kev = select.kevent( + os.getpid(), + filter=select.KQ_FILTER_PROC, + flags=select.KQ_EV_ADD | select.KQ_EV_ONESHOT, + fflags=select.KQ_NOTE_EXIT, + ) + kq.control([kev], 1, 0) + return True + except OSError as err: + if err.errno in {errno.EMFILE, errno.ENFILE}: + # transitory 'too many open files' + return True + return False + finally: + if kq is not None: + kq.close() + + +_CAN_USE_PIDFD_OPEN = not _mswindows and _can_use_pidfd_open() +_CAN_USE_KQUEUE = not _mswindows and _can_use_kqueue() + +# Maximum timeout passed to poll() / kqueue.control() by Popen._wait(): +# very large values (e.g. timeout=float('inf')) overflow the C timestamp +# conversion (gh-154836). Longer waits are performed in bounded slices +# until the deadline, like asyncio's MAXIMUM_SELECT_TIMEOUT. +_MAXIMUM_WAIT_TIMEOUT = 24 * 3600 + + # These are primarily fail-safe knobs for negatives. A True value does not # guarantee the given libc/syscall API will be used. _USE_POSIX_SPAWN = _use_posix_spawn() @@ -1096,8 +1270,8 @@ def universal_newlines(self, universal_newlines): self.text_mode = bool(universal_newlines) def _translate_newlines(self, data, encoding, errors): - data = data.decode(encoding, errors) - return data.replace("\r\n", "\n").replace("\r", "\n") + # Subclass-overridable hook; defers to the module-level helper. + return _translate_newlines(data, encoding, errors) def __enter__(self): return self @@ -1224,7 +1398,7 @@ def communicate(self, input=None, timeout=None): # See the detailed comment in .wait(). if timeout is not None: sigint_timeout = min(self._sigint_wait_secs, - self._remaining_time(endtime)) + _deadline_remaining(endtime)) else: sigint_timeout = self._sigint_wait_secs self._sigint_wait_secs = 0 # nothing else should wait. @@ -1237,7 +1411,7 @@ def communicate(self, input=None, timeout=None): finally: self._communication_started = True try: - sts = self.wait(timeout=self._remaining_time(endtime)) + self.wait(timeout=_deadline_remaining(endtime)) except TimeoutExpired as exc: exc.timeout = timeout raise @@ -1251,14 +1425,6 @@ def poll(self): return self._internal_poll() - def _remaining_time(self, endtime): - """Convenience for _communicate when computing timeouts.""" - if endtime is None: - return None - else: - return endtime - _time() - - def _check_timeout(self, endtime, orig_timeout, stdout_seq, stderr_seq, skip_check_and_raise=False): """Convenience for checking if a timeout has expired.""" @@ -1284,7 +1450,7 @@ def wait(self, timeout=None): # generated SIGINT and will exit rapidly. if timeout is not None: sigint_timeout = min(self._sigint_wait_secs, - self._remaining_time(endtime)) + _deadline_remaining(endtime)) else: sigint_timeout = self._sigint_wait_secs self._sigint_wait_secs = 0 # nothing else should wait. @@ -1651,7 +1817,7 @@ def _communicate(self, input, endtime, orig_timeout): # thread remains writing and the fd left open in case the user # calls communicate again. if hasattr(self, "_stdin_thread"): - self._stdin_thread.join(self._remaining_time(endtime)) + self._stdin_thread.join(_deadline_remaining(endtime)) if self._stdin_thread.is_alive(): raise TimeoutExpired(self.args, orig_timeout) @@ -1659,11 +1825,11 @@ def _communicate(self, input, endtime, orig_timeout): # threads remain reading and the fds left open in case the user # calls communicate again. if self.stdout is not None: - self.stdout_thread.join(self._remaining_time(endtime)) + self.stdout_thread.join(_deadline_remaining(endtime)) if self.stdout_thread.is_alive(): raise TimeoutExpired(self.args, orig_timeout) if self.stderr is not None: - self.stderr_thread.join(self._remaining_time(endtime)) + self.stderr_thread.join(_deadline_remaining(endtime)) if self.stderr_thread.is_alive(): raise TimeoutExpired(self.args, orig_timeout) @@ -2048,14 +2214,121 @@ def _try_wait(self, wait_flags): sts = 0 return (pid, sts) + def _wait_pidfd(self, timeout): + """Wait for PID to terminate using pidfd_open() + poll(). + Linux >= 5.3 only. + """ + if not _CAN_USE_PIDFD_OPEN: + return False + try: + pidfd = os.pidfd_open(self.pid, 0) + except OSError: + # May be: + # - ESRCH: no such process + # - EMFILE, ENFILE: too many open files (usually 1024) + # - ENODEV: anonymous inode filesystem not supported + # - EPERM, EACCES, ENOSYS: undocumented; may happen if + # blocked by security policy like SECCOMP + return False + + try: + poller = select.poll() + poller.register(pidfd, select.POLLIN) + endtime = _time() + timeout + while True: + # Clamp very large timeouts (e.g. float('inf')): + # they overflow the C timestamp conversion in + # poll(). Wait in bounded slices until the real + # deadline (gh-154836). + delay = min(_deadline_remaining(endtime), + _MAXIMUM_WAIT_TIMEOUT) + events = poller.poll(max(delay, 0) * 1000) + if events: + return True + if _deadline_remaining(endtime) <= 0: + raise TimeoutExpired(self.args, timeout) + finally: + os.close(pidfd) + + def _wait_kqueue(self, timeout): + """Wait for PID to terminate using kqueue(). macOS and BSD only.""" + if not _CAN_USE_KQUEUE: + return False + try: + kq = select.kqueue() + except OSError: + # likely EMFILE / ENFILE (too many open files) + return False + + try: + kev = select.kevent( + self.pid, + filter=select.KQ_FILTER_PROC, + flags=select.KQ_EV_ADD | select.KQ_EV_ONESHOT, + fflags=select.KQ_NOTE_EXIT, + ) + changelist = [kev] + endtime = _time() + timeout + while True: + # Clamp very large timeouts (e.g. float('inf')): + # they overflow the C timestamp conversion in + # kqueue.control(). Wait in bounded slices until + # the real deadline (gh-154836). + delay = min(_deadline_remaining(endtime), + _MAXIMUM_WAIT_TIMEOUT) + try: + events = kq.control(changelist, 1, max(delay, 0)) + except OSError: + return False + if events: + return True + if _deadline_remaining(endtime) <= 0: + raise TimeoutExpired(self.args, timeout) + # The kevent was registered by the first control() + # call; don't re-add it on later slices. + changelist = None + finally: + kq.close() def _wait(self, timeout): - """Internal implementation of wait() on POSIX.""" + """Internal implementation of wait() on POSIX. + + Uses efficient pidfd_open() + poll() on Linux or kqueue() + on macOS/BSD when available. Falls back to polling + waitpid(WNOHANG) otherwise. + """ if self.returncode is not None: return self.returncode if timeout is not None: - endtime = _time() + timeout + if timeout < 0: + raise TimeoutExpired(self.args, timeout) + started = _time() + endtime = started + timeout + + # Try efficient wait first. + if self._wait_pidfd(timeout) or self._wait_kqueue(timeout): + # Process is gone. At this point os.waitpid(pid, 0) + # will return immediately, but in very rare races + # the PID may have been reused. + # os.waitpid(pid, WNOHANG) ensures we attempt a + # non-blocking reap without blocking indefinitely. + with self._waitpid_lock: + if self.returncode is not None: + return self.returncode # Another thread waited. + (pid, sts) = self._try_wait(os.WNOHANG) + assert pid == self.pid or pid == 0 + if pid == self.pid: + self._handle_exitstatus(sts) + return self.returncode + # os.waitpid(pid, WNOHANG) returned 0 instead + # of our PID, meaning PID has not yet exited, + # even though poll() / kqueue() said so. Very + # rare and mostly theoretical. Fallback to busy + # polling. + elapsed = _time() - started + endtime -= elapsed + # Enter a busy loop if we have a timeout. This busy loop was # cribbed from Lib/threading.py in Thread.wait() at r71065. delay = 0.0005 # 500 us -> initial delay of 1 ms @@ -2071,7 +2344,7 @@ def _wait(self, timeout): break finally: self._waitpid_lock.release() - remaining = self._remaining_time(endtime) + remaining = _deadline_remaining(endtime) if remaining <= 0: raise TimeoutExpired(self.args, timeout) delay = min(delay * 2, remaining, .05) @@ -2087,6 +2360,7 @@ def _wait(self, timeout): # http://bugs.python.org/issue14396. if pid == self.pid: self._handle_exitstatus(sts) + return self.returncode @@ -2094,14 +2368,7 @@ def _communicate(self, input, endtime, orig_timeout): if self.stdin and not self._communication_started: # Flush stdio buffer. This might block, if the user has # been writing to .stdin in an uncontrolled fashion. - try: - self.stdin.flush() - except BrokenPipeError: - pass # communicate() must ignore BrokenPipeError. - except ValueError: - # ignore ValueError: I/O operation on closed file. - if not self.stdin.closed: - raise + _flush_stdin(self.stdin) if not input: try: self.stdin.close() @@ -2126,11 +2393,8 @@ def _communicate(self, input, endtime, orig_timeout): self._save_input(input) - if self._input: - if not isinstance(self._input, memoryview): - input_view = memoryview(self._input) - else: - input_view = self._input.cast("b") # byte input required + input_view = _make_input_view(self._input) + input_offset = self._input_offset if self._input else 0 with _PopenSelector() as selector: if self.stdin and not self.stdin.closed and self._input: @@ -2140,43 +2404,31 @@ def _communicate(self, input, endtime, orig_timeout): if self.stderr and not self.stderr.closed: selector.register(self.stderr, selectors.EVENT_READ) - while selector.get_map(): - timeout = self._remaining_time(endtime) - if timeout is not None and timeout <= 0: - self._check_timeout(endtime, orig_timeout, - stdout, stderr, - skip_check_and_raise=True) - raise RuntimeError( # Impossible :) - '_check_timeout(..., skip_check_and_raise=True) ' - 'failed to raise TimeoutExpired.') - - ready = selector.select(timeout) - self._check_timeout(endtime, orig_timeout, stdout, stderr) - - # XXX Rewrite these to use non-blocking I/O on the file - # objects; they are no longer using C stdio! - - for key, events in ready: - if key.fileobj is self.stdin: - chunk = input_view[self._input_offset : - self._input_offset + _PIPE_BUF] - try: - self._input_offset += os.write(key.fd, chunk) - except BrokenPipeError: - selector.unregister(key.fileobj) - key.fileobj.close() - else: - if self._input_offset >= len(input_view): - selector.unregister(key.fileobj) - key.fileobj.close() - elif key.fileobj in (self.stdout, self.stderr): - data = os.read(key.fd, 32768) - if not data: - selector.unregister(key.fileobj) - key.fileobj.close() - self._fileobj2output[key.fileobj].append(data) + stdin_to_write = (self.stdin if self.stdin and self._input + and not self.stdin.closed else None) + # Persist the returned offset on self so a subsequent + # communicate() after a TimeoutExpired resumes mid-input + # rather than re-sending bytes the child already consumed. + new_offset, completed = _communicate_io_posix( + selector, + stdin_to_write, + input_view, + input_offset, + self._fileobj2output, + endtime, + close_on_eof=True) + if self._input: + self._input_offset = new_offset + + if not completed: + self._check_timeout(endtime, orig_timeout, stdout, stderr, + skip_check_and_raise=True) + raise RuntimeError( # Impossible :) + '_check_timeout(..., skip_check_and_raise=True) ' + 'failed to raise TimeoutExpired.') + try: - self.wait(timeout=self._remaining_time(endtime)) + self.wait(timeout=_deadline_remaining(endtime)) except TimeoutExpired as exc: exc.timeout = orig_timeout raise diff --git a/Lib/symtable.py b/Lib/symtable.py index 7a30e1ac4ca..c7152a70f5a 100644 --- a/Lib/symtable.py +++ b/Lib/symtable.py @@ -17,13 +17,13 @@ __all__ = ["symtable", "SymbolTableType", "SymbolTable", "Class", "Function", "Symbol"] -def symtable(code, filename, compile_type): +def symtable(code, filename, compile_type, *, module=None): """ Return the toplevel *SymbolTable* for the source code. *filename* is the name of the file with the code and *compile_type* is the *compile()* mode argument. """ - top = _symtable.symtable(code, filename, compile_type) + top = _symtable.symtable(code, filename, compile_type, module=module) return _newSymbolTable(top, filename) class SymbolTableFactory: @@ -184,6 +184,7 @@ class Function(SymbolTable): __frees = None __globals = None __nonlocals = None + __cells = None def __idents_matching(self, test_func): return tuple(ident for ident in self.get_identifiers() @@ -229,6 +230,14 @@ def get_frees(self): self.__frees = self.__idents_matching(is_free) return self.__frees + def get_cells(self): + """Return a tuple of cell variables in the function. + """ + if self.__cells is None: + is_cell = lambda x: _get_scope(x) == CELL + self.__cells = self.__idents_matching(is_cell) + return self.__cells + class Class(SymbolTable): @@ -255,11 +264,6 @@ def is_local_symbol(ident): if is_local_symbol(st.name): match st.type: case _symtable.TYPE_FUNCTION: - # generators are of type TYPE_FUNCTION with a ".0" - # parameter as a first parameter (which makes them - # distinguishable from a function named 'genexpr') - if st.name == 'genexpr' and '.0' in st.varnames: - continue d[st.name] = 1 case _symtable.TYPE_TYPE_PARAMETERS: # Get the function-def block in the annotation @@ -267,13 +271,6 @@ def is_local_symbol(ident): scope_name = st.name for c in st.children: if c.name == scope_name and c.type == _symtable.TYPE_FUNCTION: - # A generic generator of type TYPE_FUNCTION - # cannot be a direct child of 'st' (but it - # can be a descendant), e.g.: - # - # class A: - # type genexpr[genexpr] = (x for x in []) - assert scope_name != 'genexpr' or '.0' not in c.varnames d[scope_name] = 1 break self.__methods = tuple(d) @@ -354,6 +351,10 @@ def is_free(self): """ return bool(self.__scope == FREE) + def is_cell(self): + """Return *True* if the symbol is a cell variable.""" + return bool(self.__scope == CELL) + def is_free_class(self): """Return *True* if a class-scoped symbol is free from the perspective of a method.""" @@ -413,7 +414,7 @@ def get_namespace(self): _flags = [('USE', USE)] _flags.extend(kv for kv in globals().items() if kv[0].startswith('DEF_')) _scopes_names = ('FREE', 'LOCAL', 'GLOBAL_IMPLICIT', 'GLOBAL_EXPLICIT', 'CELL') -_scopes_value_to_name = {globals()[n]: n for n in _scopes_names} +_scopes_value_to_name = frozendict({globals()[n]: n for n in _scopes_names}) def main(args): diff --git a/Lib/sysconfig/__init__.py b/Lib/sysconfig/__init__.py index 029d5bcfcbe..9c13c0fec58 100644 --- a/Lib/sysconfig/__init__.py +++ b/Lib/sysconfig/__init__.py @@ -219,18 +219,7 @@ def _safe_realpath(path): if "_PYTHON_PROJECT_BASE" in os.environ: _PROJECT_BASE = _safe_realpath(os.environ["_PYTHON_PROJECT_BASE"]) -def is_python_build(check_home=None): - if check_home is not None: - import warnings - warnings.warn( - ( - 'The check_home argument of sysconfig.is_python_build is ' - 'deprecated and its value is ignored. ' - 'It will be removed in Python 3.15.' - ), - DeprecationWarning, - stacklevel=2, - ) +def is_python_build(): for fn in ("Setup", "Setup.local"): if os.path.isfile(os.path.join(_PROJECT_BASE, "Modules", fn)): return True @@ -423,7 +412,13 @@ def _init_non_posix(vars): vars['EXE'] = '.exe' vars['VERSION'] = _PY_VERSION_SHORT_NO_DOT vars['BINDIR'] = os.path.dirname(_safe_realpath(sys.executable)) - vars['TZPATH'] = '' + # No standard path exists on Windows for this, but we'll check + # whether someone is imitating a POSIX-like layout + check_tzpath = os.path.join(vars['prefix'], 'share', 'zoneinfo') + if os.path.exists(check_tzpath): + vars['TZPATH'] = check_tzpath + else: + vars['TZPATH'] = '' # # public APIs @@ -440,8 +435,10 @@ def parse_config_h(fp, vars=None): if vars is None: vars = {} import re - define_rx = re.compile("#define ([A-Z][A-Za-z0-9_]+) (.*)\n") - undef_rx = re.compile("/[*] #undef ([A-Z][A-Za-z0-9_]+) [*]/\n") + name_rx = '(?:[A-Z]|_Py_)[A-Za-z0-9_]+' + define_rx = re.compile(fr"#define ({name_rx}) (.*)\n") + undef_rx = re.compile(fr"/[*] #undef ({name_rx}) [*]/\n") + quoted_re = re.compile(r'"(.*)"') while True: line = fp.readline() @@ -450,6 +447,8 @@ def parse_config_h(fp, vars=None): m = define_rx.match(line) if m: n, v = m.group(1, 2) + if mq := quoted_re.fullmatch(v): + v = mq.group(1) try: if n in _ALWAYS_STR: raise ValueError @@ -650,6 +649,9 @@ def get_platform(): isn't particularly important. Examples of returned values: + linux-x86_64 + linux-aarch64 + solaris-2.6-sun4u Windows: @@ -667,12 +669,10 @@ def get_platform(): For other non-POSIX platforms, currently just returns :data:`sys.platform`.""" if os.name == 'nt': - if 'amd64' in sys.version.lower(): - return 'win-amd64' - if '(arm)' in sys.version.lower(): - return 'win-arm32' - if '(arm64)' in sys.version.lower(): - return 'win-arm64' + import _sysconfig + platform = _sysconfig.get_platform() + if platform: + return platform return sys.platform if os.name != "posix" or not hasattr(os, 'uname'): diff --git a/Lib/sysconfig/__main__.py b/Lib/sysconfig/__main__.py index bc2197cfe79..0cf0cf4dbb9 100644 --- a/Lib/sysconfig/__main__.py +++ b/Lib/sysconfig/__main__.py @@ -21,8 +21,9 @@ # Regexes needed for parsing Makefile (and similar syntaxes, # like old-style Setup files). _variable_rx = r"([a-zA-Z][a-zA-Z0-9_]+)\s*=\s*(.*)" -_findvar1_rx = r"\$\(([A-Za-z][A-Za-z0-9_]*)\)" -_findvar2_rx = r"\${([A-Za-z][A-Za-z0-9_]*)}" +_findvar_rx = (r"\$(\([A-Za-z][A-Za-z0-9_]*\)" + r"|\{[A-Za-z][A-Za-z0-9_]*\}" + r"|\$?)") def _parse_makefile(filename, vars=None, keep_unresolved=True): @@ -49,26 +50,7 @@ def _parse_makefile(filename, vars=None, keep_unresolved=True): m = re.match(_variable_rx, line) if m: n, v = m.group(1, 2) - v = v.strip() - # `$$' is a literal `$' in make - tmpv = v.replace('$$', '') - - if "$" in tmpv: - notdone[n] = v - else: - try: - if n in _ALWAYS_STR: - raise ValueError - - v = int(v) - except ValueError: - # insert literal `$' - done[n] = v.replace('$$', '$') - else: - done[n] = v - - # do variable interpolation here - variables = list(notdone.keys()) + notdone[n] = v.strip() # Variables with a 'PY_' prefix in the makefile. These need to # be made available without that prefix through sysconfig. @@ -76,72 +58,64 @@ def _parse_makefile(filename, vars=None, keep_unresolved=True): # if the expansion uses the name without a prefix. renamed_variables = ('CFLAGS', 'LDFLAGS', 'CPPFLAGS') - while len(variables) > 0: - for name in tuple(variables): - value = notdone[name] - m1 = re.search(_findvar1_rx, value) - m2 = re.search(_findvar2_rx, value) - if m1 and m2: - m = m1 if m1.start() < m2.start() else m2 - else: - m = m1 if m1 else m2 - if m is not None: - n = m.group(1) - found = True - if n in done: - item = str(done[n]) - elif n in notdone: - # get it on a subsequent round - found = False - elif n in os.environ: - # do it like make: fall back to environment - item = os.environ[n] - - elif n in renamed_variables: - if (name.startswith('PY_') and - name[3:] in renamed_variables): - item = "" - - elif 'PY_' + n in notdone: - found = False - - else: - item = str(done['PY_' + n]) - + def resolve_var(name): + def repl(m): + n = m[1] + if n == '$': + return '$' + elif n == '': + # bogus variable reference (e.g. "prefix=$/opt/python") + if keep_unresolved: + return m[0] + raise ValueError + elif n[0] == '(' and n[-1] == ')': + n = n[1:-1] + elif n[0] == '{' and n[-1] == '}': + n = n[1:-1] + + if n in done: + return str(done[n]) + elif n in notdone: + return str(resolve_var(n)) + elif n in os.environ: + # do it like make: fall back to environment + return os.environ[n] + elif n in renamed_variables: + if name.startswith('PY_') and name[3:] in renamed_variables: + return "" + n = 'PY_' + n + if n in notdone: + return str(resolve_var(n)) else: - done[n] = item = "" - - if found: - after = value[m.end():] - value = value[:m.start()] + item + after - if "$" in after: - notdone[name] = value - else: - try: - if name in _ALWAYS_STR: - raise ValueError - value = int(value) - except ValueError: - done[name] = value.strip() - else: - done[name] = value - variables.remove(name) - - if name.startswith('PY_') \ - and name[3:] in renamed_variables: - - name = name[3:] - if name not in done: - done[name] = value - + assert n not in done + return "" else: - # Adds unresolved variables to the done dict. - # This is disabled when called from distutils.sysconfig - if keep_unresolved: - done[name] = value - # bogus variable reference (e.g. "prefix=$/opt/python"); - # just drop it since we can't deal - variables.remove(name) + done[n] = "" + return "" + + assert name not in done + done[name] = "" + try: + value = re.sub(_findvar_rx, repl, notdone[name]) + except ValueError: + del done[name] + return "" + value = value.strip() + if name not in _ALWAYS_STR: + try: + value = int(value) + except ValueError: + pass + done[name] = value + if name.startswith('PY_') and name[3:] in renamed_variables: + name = name[3:] + if name not in done: + done[name] = value + return value + + for n in notdone: + if n not in done: + resolve_var(n) # strip spurious spaces for k, v in done.items(): diff --git a/Lib/tabnanny.py b/Lib/tabnanny.py index c0097351b26..04c5baf7b52 100644 --- a/Lib/tabnanny.py +++ b/Lib/tabnanny.py @@ -16,8 +16,6 @@ # XXX The API needs to undergo changes however; the current code is too # XXX script-like. This will be addressed later. -__version__ = "6" - import os import sys import tokenize @@ -49,7 +47,7 @@ def main(): if o == '-v': verbose = verbose + 1 if not args: - errprint("Usage:", sys.argv[0], "[-v] file_or_directory ...") + errprint(f"Usage: {sys.executable} -m tabnanny [-v] file_or_directory ...") for arg in args: check(arg) @@ -334,5 +332,14 @@ def _process_tokens(tokens): raise NannyNag(start[0], msg, line) +def __getattr__(name): + if name == "__version__": + from warnings import _deprecated + + _deprecated("__version__", remove=(3, 20)) + return "6" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + if __name__ == '__main__': main() diff --git a/Lib/tarfile.py b/Lib/tarfile.py index d3c48999700..38a389bcab1 100644 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -28,7 +28,6 @@ """Read from and write to tar format archives. """ -version = "0.9.0" __author__ = "Lars Gust\u00e4bel (lars@gustaebel.de)" __credits__ = "Gustavo Niemeyer, Niels Gust\u00e4bel, Richard Townsend." @@ -201,7 +200,6 @@ def itn(n, digits=8, format=DEFAULT_FORMAT): # base-256 representation. This allows values up to (256**(digits-1))-1. # A 0o200 byte indicates a positive number, a 0o377 byte a negative # number. - original_n = n n = int(n) if 0 <= n < 8 ** (digits - 1): s = bytes("%0*o" % (digits - 1, n), "ascii") + NUL @@ -365,7 +363,7 @@ class _Stream: """ def __init__(self, name, mode, comptype, fileobj, bufsize, - compresslevel, preset): + compresslevel, preset, mtime): """Construct a _Stream object. """ self._extfileobj = True @@ -400,7 +398,7 @@ def __init__(self, name, mode, comptype, fileobj, bufsize, self.exception = zlib.error self._init_read_gz() else: - self._init_write_gz(compresslevel) + self._init_write_gz(compresslevel, mtime) elif comptype == "bz2": try: @@ -408,7 +406,6 @@ def __init__(self, name, mode, comptype, fileobj, bufsize, except ImportError: raise CompressionError("bz2 module is not available") from None if mode == "r": - self.dbuf = b"" self.cmp = bz2.BZ2Decompressor() self.exception = OSError else: @@ -420,7 +417,6 @@ def __init__(self, name, mode, comptype, fileobj, bufsize, except ImportError: raise CompressionError("lzma module is not available") from None if mode == "r": - self.dbuf = b"" self.cmp = lzma.LZMADecompressor() self.exception = lzma.LZMAError else: @@ -431,7 +427,6 @@ def __init__(self, name, mode, comptype, fileobj, bufsize, except ImportError: raise CompressionError("compression.zstd module is not available") from None if mode == "r": - self.dbuf = b"" self.cmp = zstd.ZstdDecompressor() self.exception = zstd.ZstdError else: @@ -449,7 +444,7 @@ def __del__(self): if hasattr(self, "closed") and not self.closed: self.close() - def _init_write_gz(self, compresslevel): + def _init_write_gz(self, compresslevel, mtime): """Initialize for writing with gzip compression. """ self.cmp = self.zlib.compressobj(compresslevel, @@ -457,7 +452,13 @@ def _init_write_gz(self, compresslevel): -self.zlib.MAX_WBITS, self.zlib.DEF_MEM_LEVEL, 0) - timestamp = struct.pack("', repr(lock)) p.terminate() + p.join() def test_lock(self): lock = self.Lock() @@ -1580,6 +1614,7 @@ def _test_lock_locked_2processes(cls, lock, event, res): res.value = lock.locked() event.set() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes') def test_lock_locked_2processes(self): if self.TYPE != 'processes': @@ -1606,6 +1641,7 @@ def _acquire_release(lock, timeout, l=None, n=1): for _ in range(n): lock.release() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_repr_rlock(self): if self.TYPE != 'processes': self.skipTest('test not appropriate for {}'.format(self.TYPE)) @@ -1665,6 +1701,7 @@ def test_rlock(self): self.assertFalse(lock.locked()) self.assertRaises((AssertionError, RuntimeError), lock.release) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes') def test_rlock_locked_2processes(self): if self.TYPE != 'processes': @@ -1776,6 +1813,7 @@ def check_invariant(self, cond): except NotImplementedError: pass + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_notify(self): cond = self.Condition() sleeping = self.Semaphore(0) @@ -1818,6 +1856,7 @@ def test_notify(self): threading_helper.join_thread(t) join_process(p) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_notify_all(self): cond = self.Condition() sleeping = self.Semaphore(0) @@ -1887,6 +1926,7 @@ def test_notify_all(self): # NOTE: join_process and join_thread are the same threading_helper.join_thread(w) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_notify_n(self): cond = self.Condition() sleeping = self.Semaphore(0) @@ -1960,6 +2000,7 @@ def _test_waitfor_f(cls, cond, state): if not result or state.value != 4: sys.exit(1) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes') def test_waitfor(self): # based on test in test/lock_tests.py @@ -1995,6 +2036,7 @@ def _test_waitfor_timeout_f(cls, cond, state, success, sem): if not result and (expected - CLOCK_RES) <= dt: success.value = True + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(HAS_SHAREDCTYPES, 'needs sharedctypes') def test_waitfor_timeout(self): # based on test in test/lock_tests.py @@ -2027,6 +2069,7 @@ def _test_wait_result(cls, c, pid): if pid is not None: os.kill(pid, signal.SIGINT) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_wait_result(self): if isinstance(self, ProcessesMixin) and sys.platform != 'win32': pid = os.getpid() @@ -2055,6 +2098,7 @@ def _test_event(cls, event): time.sleep(TIMEOUT2) event.set() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_event(self): event = self.Event() wait = TimingWrapper(event.wait) @@ -2251,6 +2295,7 @@ def multipass(cls, barrier, results, n): pass assert not barrier.broken + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_barrier(self, passes=1): """ Test that a barrier is passed in lockstep @@ -2258,6 +2303,7 @@ def test_barrier(self, passes=1): results = [self.DummyList(), self.DummyList()] self.run_threads(self.multipass, (self.barrier, results, passes)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_barrier_10(self): """ Test that a barrier works for 10 consecutive runs @@ -2269,6 +2315,7 @@ def _test_wait_return_f(cls, barrier, queue): res = barrier.wait() queue.put(res) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_wait_return(self): """ test the return value from barrier.wait @@ -2285,6 +2332,7 @@ def _test_action_f(cls, barrier, results): if len(results) != 1: raise RuntimeError + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_action(self): """ Test the 'action' callback @@ -2307,6 +2355,7 @@ def _test_abort_f(cls, barrier, results1, results2): except RuntimeError: barrier.abort() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_abort(self): """ Test that an abort will put the barrier in a broken state @@ -2337,6 +2386,7 @@ def _test_reset_f(cls, barrier, results1, results2, results3): barrier.wait() results3.append(True) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_reset(self): """ Test that a 'reset' on a barrier frees the waiting threads @@ -2372,6 +2422,7 @@ def _test_abort_and_reset_f(cls, barrier, barrier2, barrier.wait() results3.append(True) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_abort_and_reset(self): """ Test that a barrier can be reset after being broken. @@ -2398,6 +2449,7 @@ def _test_timeout_f(cls, barrier, results): except threading.BrokenBarrierError: results.append(True) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_timeout(self): """ Test wait(timeout) @@ -2417,6 +2469,7 @@ def _test_default_timeout_f(cls, barrier, results): except threading.BrokenBarrierError: results.append(True) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_default_timeout(self): """ Test the barrier's default timeout @@ -2438,6 +2491,7 @@ def _test_thousand_f(cls, barrier, passes, conn, lock): with lock: conn.send(i) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_thousand(self): if self.TYPE == 'manager': self.skipTest('test not appropriate for {}'.format(self.TYPE)) @@ -2479,7 +2533,7 @@ def _test(cls, values): for sv, cv in zip(values, cls.codes_values): sv.value = cv[2] - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_value(self, raw=False): if raw: values = [self.RawValue(code, value) @@ -2527,6 +2581,12 @@ def test_getobj_getlock(self): self.assertNotHasAttr(arr5, 'get_lock') self.assertNotHasAttr(arr5, 'get_obj') + @unittest.skipIf(c_int is None, "requires _ctypes") + def test_invalid_typecode(self): + with self.assertRaisesRegex(TypeError, 'bad typecode'): + self.Value('x', None) + with self.assertRaisesRegex(TypeError, 'bad typecode'): + self.RawValue('x', None) class _TestArray(BaseTestCase): @@ -2537,6 +2597,7 @@ def f(cls, seq): for i in range(1, len(seq)): seq[i] += seq[i-1] + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipIf(c_int is None, "requires _ctypes") def test_array(self, raw=False): seq = [680, 626, 934, 821, 150, 233, 548, 982, 714, 831] @@ -2607,6 +2668,12 @@ def test_getobj_getlock_obj(self): self.assertNotHasAttr(arr5, 'get_lock') self.assertNotHasAttr(arr5, 'get_obj') + @unittest.skipIf(c_int is None, "requires _ctypes") + def test_invalid_typecode(self): + with self.assertRaisesRegex(TypeError, 'bad typecode'): + self.Array('x', []) + with self.assertRaisesRegex(TypeError, 'bad typecode'): + self.RawArray('x', []) # # # @@ -2842,8 +2909,9 @@ class _TestPool(BaseTestCase): @classmethod def setUpClass(cls): - super().setUpClass() - cls.pool = cls.Pool(4) + with warnings_helper.ignore_fork_in_thread_deprecation_warnings(): + super().setUpClass() + cls.pool = cls.Pool(4) @classmethod def tearDownClass(cls): @@ -2942,6 +3010,7 @@ def test_async(self): self.assertEqual(get(), 49) self.assertTimingAlmostEqual(get.elapsed, TIMEOUT1) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_async_timeout(self): p = self.Pool(3) try: @@ -3039,6 +3108,7 @@ def test_imap_unordered_handle_iterable_exception(self): self.assertIn(value, expected_values) expected_values.remove(value) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_make_pool(self): expected_error = (RemoteError if self.TYPE == 'manager' else ValueError) @@ -3054,6 +3124,7 @@ def test_make_pool(self): p.close() p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_terminate(self): # Simulate slow tasks which take "forever" to complete sleep_time = support.LONG_TIMEOUT @@ -3071,6 +3142,7 @@ def test_terminate(self): p.terminate() p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_empty_iterable(self): # See Issue 12157 p = self.Pool(1) @@ -3083,6 +3155,7 @@ def test_empty_iterable(self): p.close() p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_context(self): if self.TYPE == 'processes': L = list(range(10)) @@ -3097,6 +3170,7 @@ def test_context(self): def _test_traceback(cls): raise RuntimeError(123) # some comment + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_traceback(self): # We want ensure that the traceback from the child process is # contained in the traceback raised in the main process. @@ -3136,9 +3210,11 @@ def test_traceback(self): p.join() @classmethod + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def _test_wrapped_exception(cls): raise RuntimeError('foo') + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_wrapped_exception(self): # Issue #20980: Should not wrap exception when using thread pool with self.Pool(1) as p: @@ -3146,6 +3222,7 @@ def test_wrapped_exception(self): p.apply(self._test_wrapped_exception) p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map_no_failfast(self): # Issue #23992: the fail-fast behaviour when an exception is raised # during map() would make Pool.join() deadlock, because a worker @@ -3181,6 +3258,7 @@ def test_release_task_refs(self): # they were released too. self.assertEqual(CountedObject.n_instances, 0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_enter(self): if self.TYPE == 'manager': self.skipTest("test not applicable to manager") @@ -3197,6 +3275,7 @@ def test_enter(self): pass pool.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_resource_warning(self): if self.TYPE == 'manager': self.skipTest("test not applicable to manager") @@ -3222,6 +3301,7 @@ def unpickleable_result(): class _TestPoolWorkerErrors(BaseTestCase): ALLOWED_TYPES = ('processes', ) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_async_error_callback(self): p = multiprocessing.Pool(2) @@ -3237,6 +3317,7 @@ def errback(exc): p.close() p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_unpickleable_result(self): from multiprocessing.pool import MaybeEncodingError p = multiprocessing.Pool(2) @@ -3262,6 +3343,7 @@ def errback(exc): class _TestPoolWorkerLifetime(BaseTestCase): ALLOWED_TYPES = ('processes', ) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_pool_worker_lifetime(self): p = multiprocessing.Pool(3, maxtasksperchild=10) self.assertEqual(3, len(p._pool)) @@ -3291,6 +3373,7 @@ def test_pool_worker_lifetime(self): p.close() p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_pool_worker_lifetime_early_close(self): # Issue #10332: closing a pool whose workers have limited lifetimes # before all the tasks completed would make join() hang. @@ -3364,6 +3447,7 @@ class _TestMyManager(BaseTestCase): ALLOWED_TYPES = ('manager',) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.skip_if_sanitizer('TSan: leaks threads', thread=True) def test_mymanager(self): manager = MyManager(shutdown_timeout=SHUTDOWN_TIMEOUT) @@ -3376,6 +3460,7 @@ def test_mymanager(self): # which happens on slow buildbots. self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.skip_if_sanitizer('TSan: leaks threads', thread=True) def test_mymanager_context(self): manager = MyManager(shutdown_timeout=SHUTDOWN_TIMEOUT) @@ -3386,6 +3471,7 @@ def test_mymanager_context(self): # which happens on slow buildbots. self.assertIn(manager._process.exitcode, (0, -signal.SIGTERM)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.skip_if_sanitizer('TSan: leaks threads', thread=True) def test_mymanager_context_prestarted(self): manager = MyManager(shutdown_timeout=SHUTDOWN_TIMEOUT) @@ -3457,6 +3543,7 @@ def _putter(cls, address, authkey): # Note that xmlrpclib will deserialize object as a list not a tuple queue.put(tuple(cls.values)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.skip_if_sanitizer('TSan: leaks threads', thread=True) def test_remote(self): authkey = os.urandom(32) @@ -3499,6 +3586,7 @@ def _putter(cls, address, authkey): queue = manager.get_queue() queue.put('hello world') + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.skip_if_sanitizer("TSan: leaks threads", thread=True) def test_rapid_restart(self): authkey = os.urandom(32) @@ -3552,12 +3640,14 @@ def recv(self): class TestManagerExceptions(unittest.TestCase): # Issue 106558: Manager exceptions avoids creating cyclic references. def setUp(self): - self.mgr = multiprocessing.Manager() + with warnings_helper.ignore_fork_in_thread_deprecation_warnings(): + self.mgr = multiprocessing.Manager() def tearDown(self): self.mgr.shutdown() self.mgr.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_queue_get(self): queue = self.mgr.Queue() if gc.isenabled(): @@ -3569,6 +3659,7 @@ def test_queue_get(self): wr = weakref.ref(e) self.assertEqual(wr(), None) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_dispatch(self): if gc.isenabled(): gc.disable() @@ -3595,6 +3686,7 @@ def _echo(cls, conn): conn.send_bytes(msg) conn.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_connection(self): conn, child_conn = self.Pipe() @@ -3687,6 +3779,7 @@ def test_duplex_false(self): self.assertRaises(OSError, writer.recv) self.assertRaises(OSError, writer.poll) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_spawn_close(self): # We test that a pipe connection can be closed by parent # process immediately after child is spawned. On Windows this @@ -3763,6 +3856,7 @@ def _writefd(cls, conn, data, create_dummy_fds=False): os.write(fd, data) os.close(fd) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") def test_fd_transfer(self): if self.TYPE != 'processes': @@ -3782,6 +3876,7 @@ def test_fd_transfer(self): with open(os_helper.TESTFN, "rb") as f: self.assertEqual(f.read(), b"foo") + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") @unittest.skipIf(sys.platform == "win32", "test semantics don't make sense on Windows") @@ -3819,6 +3914,7 @@ def test_large_fd_transfer(self): def _send_data_without_fd(self, conn): os.write(conn.fileno(), b"\0") + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(HAS_REDUCTION, "test needs multiprocessing.reduction") @unittest.skipIf(sys.platform == "win32", "doesn't make sense on Windows") def test_missing_fd_transfer(self): @@ -3850,6 +3946,19 @@ def test_context(self): self.assertRaises(OSError, a.recv) self.assertRaises(OSError, b.recv) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_wait_empty(self): + if self.TYPE != 'processes': + self.skipTest('test not appropriate for {}'.format(self.TYPE)) + # gh-145587: wait() with empty list should respect timeout + timeout = 0.5 + start = time.monotonic() + res = self.connection.wait([], timeout=timeout) + duration = time.monotonic() - start + + self.assertEqual(res, []) + self.assertGreaterEqual(duration, timeout - 0.1) + class _TestListener(BaseTestCase): ALLOWED_TYPES = ('processes',) @@ -3918,6 +4027,7 @@ def _test(cls, address): conn.send('hello') conn.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_listener_client(self): for family in self.connection.families: l = self.connection.Listener(family=family) @@ -3929,6 +4039,7 @@ def test_listener_client(self): p.join() l.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_issue14725(self): l = self.connection.Listener() p = self.Process(target=self._test, args=(l.address,)) @@ -3974,6 +4085,7 @@ def _child_strings(cls, conn, strings): conn.send_bytes(s) conn.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_strings(self): strings = (b'hello', b'', b'a', b'b', b'', b'bye', b'', b'lop') a, b = self.Pipe() @@ -3997,6 +4109,7 @@ def _child_boundaries(cls, r): # read from it. r.poll(5) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_boundaries(self): r, w = self.Pipe(False) p = self.Process(target=self._child_boundaries, args=(r,)) @@ -4015,6 +4128,7 @@ def _child_dont_merge(cls, b): b.send_bytes(b'b') b.send_bytes(b'cd') + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_dont_merge(self): a, b = self.Pipe() self.assertEqual(a.poll(0.0), False) @@ -4083,6 +4197,7 @@ def _remote(cls, conn): conn.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_pickling(self): families = self.connection.families @@ -4141,6 +4256,7 @@ def child_access(cls, conn): conn.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_access(self): # On Windows, if we do not specify a destination pid when # using DupHandle then we need to be careful to use the @@ -4304,6 +4420,7 @@ def _double(cls, x, y, z, foo, arr, string): for i in range(len(arr)): arr[i] *= 2 + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_sharedctypes(self, lock=False): x = Value('i', 7, lock=lock) y = Value(c_double, 1.0/3.0, lock=lock) @@ -4578,6 +4695,7 @@ def test_shared_memory_pickle_unpickle_dead_object(self): with self.assertRaises(FileNotFoundError): pickle.loads(pickled_sms) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_shared_memory_across_processes(self): # bpo-40135: don't define shared memory block's name in case of # the failure when we run multiprocessing tests in parallel. @@ -4606,6 +4724,7 @@ def test_shared_memory_across_processes(self): sms.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipIf(os.name != "posix", "not feasible in non-posix platforms") def test_shared_memory_SharedMemoryServer_ignores_sigint(self): # bpo-36368: protect SharedMemoryManager server process from @@ -4652,6 +4771,7 @@ def test_shared_memory_SharedMemoryManager_reuses_resource_tracker(self): # properly released sl. self.assertFalse(err) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_shared_memory_SharedMemoryManager_basics(self): smm1 = multiprocessing.managers.SharedMemoryManager() with self.assertRaises(ValueError): @@ -4993,6 +5113,7 @@ class Foo(object): conn.close() os._exit(0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_finalize(self): conn, child_conn = self.Pipe() @@ -5120,6 +5241,7 @@ def _test_level(cls, conn): logger = multiprocessing.get_logger() conn.send(logger.getEffectiveLevel()) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_level(self): LEVEL1 = 32 LEVEL2 = 37 @@ -5204,6 +5326,7 @@ def _killer(cls, pid): time.sleep(0.1) os.kill(pid, signal.SIGUSR1) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1') def test_poll_eintr(self): got_signal = [False] @@ -5343,14 +5466,16 @@ def initializer(ns): @hashlib_helper.requires_hashdigest('sha256') class TestInitializers(unittest.TestCase): def setUp(self): - self.mgr = multiprocessing.Manager() - self.ns = self.mgr.Namespace() - self.ns.test = 0 + with warnings_helper.ignore_fork_in_thread_deprecation_warnings(): + self.mgr = multiprocessing.Manager() + self.ns = self.mgr.Namespace() + self.ns.test = 0 def tearDown(self): self.mgr.shutdown() self.mgr.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_manager_initializer(self): m = multiprocessing.managers.SyncManager() self.assertRaises(TypeError, m.start, 1) @@ -5359,6 +5484,7 @@ def test_manager_initializer(self): m.shutdown() m.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_pool_initializer(self): self.assertRaises(TypeError, multiprocessing.Pool, initializer=1) p = multiprocessing.Pool(1, initializer, (self.ns,)) @@ -5416,16 +5542,19 @@ def flush(self): class TestStdinBadfiledescriptor(unittest.TestCase): + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_queue_in_process(self): proc = multiprocessing.Process(target=_test_process) proc.start() proc.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_pool_in_process(self): p = multiprocessing.Process(target=pool_in_process) p.start() p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_flushing(self): sio = io.StringIO() flike = _file_like(sio) @@ -5445,6 +5574,7 @@ def _child_test_wait(cls, w, slow): w.send((i, os.getpid())) w.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_wait(self, slow=False): from multiprocessing.connection import wait readers = [] @@ -5485,6 +5615,7 @@ def _child_test_wait_socket(cls, address, slow): s.sendall(('%s\n' % i).encode('ascii')) s.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_wait_socket(self, slow=False): from multiprocessing.connection import wait l = socket.create_server((socket_helper.HOST, 0)) @@ -5549,6 +5680,7 @@ def signal_and_sleep(cls, sem, period): sem.release() time.sleep(period) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.requires_resource('walltime') def test_wait_integer(self): from multiprocessing.connection import wait @@ -5593,6 +5725,7 @@ def test_wait_integer(self): p.terminate() p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_neg_timeout(self): from multiprocessing.connection import wait a, b = multiprocessing.Pipe() @@ -5670,6 +5803,7 @@ def _test_timeout(cls, child, address): conn.send(456) conn.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_timeout(self): old_timeout = socket.getdefaulttimeout() try: @@ -5727,6 +5861,7 @@ def child(cls, n, conn): conn.send(len(util._afterfork_registry)) conn.close() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_lock(self): r, w = multiprocessing.Pipe(False) l = util.ForkAwareThreadLock() @@ -5778,6 +5913,7 @@ def _test_closefds(cls, conn, fd): s.close() conn.send(None) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_closefd(self): if not HAS_REDUCTION: raise unittest.SkipTest('requires fd pickling') @@ -5823,6 +5959,7 @@ def handler(signum, frame): conn.send(x) conn.send_bytes(b'x' * cls.CONN_MAX_SIZE) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1') def test_ignore(self): conn, child_conn = multiprocessing.Pipe() @@ -5856,6 +5993,7 @@ def handler(signum, frame): a = l.accept() a.send('welcome') + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(hasattr(signal, 'SIGUSR1'), 'requires SIGUSR1') def test_ignore_listener(self): conn, child_conn = multiprocessing.Pipe() @@ -5890,6 +6028,7 @@ def check_context(self, ctx): p.join() self.assertEqual(child_method, ctx.get_start_method()) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_context(self): for method in ('fork', 'spawn', 'forkserver'): try: @@ -5906,6 +6045,7 @@ def test_context(self): def _dummy_func(): pass + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_spawn_dont_set_context(self): # Run a process with spawn or forkserver context may change # the global start method, see gh-109263. @@ -5943,6 +6083,7 @@ def test_context_check_module_types(self): with self.assertRaisesRegex(TypeError, 'module_names must be a list of strings'): ctx.set_forkserver_preload([1, 2, 3]) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_set_get(self): multiprocessing.set_forkserver_preload(PRELOAD) count = 0 @@ -6000,6 +6141,7 @@ def test_preload_resources(self): print(err) self.fail("failed spawning forkserver or grandchild") + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipIf(sys.platform == "win32", "Only Spawn on windows so no risk of mixing") @only_run_in_spawn_testsuite("avoids redundant testing.") @@ -6033,6 +6175,7 @@ def _put_two_and_nest_once(cls, queue): process.start() process.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_nested_startmethod(self): # gh-108520: Regression test to ensure that child process can send its # arguments to another process @@ -6050,6 +6193,97 @@ def test_nested_startmethod(self): # there is no synchronization in the test. self.assertSetEqual(set(results), set([2, 1])) + @unittest.skipIf(os.name == "nt", "requires POSIX") + @support.requires_non_root_user + @support.subTests("mode", [ + os.R_OK, # read-only directory + os.R_OK | os.X_OK, # read-only directory + os.W_OK # write-only directory _without_ permissions for creating files + ]) + def test_forkserver_requires_writeable_tempdir(self, mode): + # Regression test to ensure that the defualt start method is + # not 'forkserver' when the temporary directory is not writeable. + # + # See https://github.com/python/cpython/issues/155717. + + cmd = '''if 1: + import os, tempfile + # We fake the read-onlyiness of /tmp (which is a fallback when + # the user-defined TMPDIR is not acceptable) by hardcoding the + # temporary directory for this specific test. + tempfile.tempdir = os.environ["TMPDIR"] + + # Imported after patching 'tempfile' so that the default start + # method is deduced according to the permissions of TMPDIR. + import multiprocessing + if __name__ == "__main__": + print(multiprocessing.get_start_method()) + ''' + + with support.os_helper.temp_dir() as root: + TMPDIR = pathlib.Path(root, "TMPDIR") + TMPDIR.mkdir(mode=mode) + file = pathlib.Path(TMPDIR, "file") + self.assertRaises(OSError, file.touch) + _, out, err = script_helper.assert_python_ok('-c', cmd, TMPDIR=TMPDIR) + self.assertEqual(out.decode().strip(), "spawn") + + @unittest.skipIf(os.name == "nt", "requires POSIX") + @support.requires_non_root_user + def test_default_start_method_without_usable_tempdir(self): + # Neither importing multiprocessing nor determining the default + # start method may fail when tempfile finds no usable temporary + # directory at all, and the default start method must be 'spawn'. + # + # See https://github.com/python/cpython/issues/155717. + + cmd = '''if 1: + import os, tempfile + # Make TMPDIR the only candidate, so that tempfile.gettempdir() + # raises FileNotFoundError instead of falling back to /tmp. + tempfile._candidate_tempdir_list = lambda: [os.environ["TMPDIR"]] + try: + tempfile.gettempdir() + except FileNotFoundError: + pass + else: + raise AssertionError("TMPDIR is usable") + + import multiprocessing + if __name__ == "__main__": + print(multiprocessing.get_start_method(), + multiprocessing.get_all_start_methods()[0]) + ''' + + with support.os_helper.temp_dir() as root: + TMPDIR = pathlib.Path(root, "TMPDIR") + TMPDIR.mkdir(mode=os.R_OK | os.X_OK) + _, out, err = script_helper.assert_python_ok('-c', cmd, TMPDIR=TMPDIR) + self.assertEqual(out.decode().split(), ["spawn", "spawn"]) + + def test_import_does_not_determine_default_start_method(self): + # Determining the default start method requires checking that the + # temporary directory is writeable. That must not happen, nor may + # the modules it needs be loaded, when importing multiprocessing. + import_helper.ensure_lazy_imports( + "multiprocessing", {"tempfile", "shutil", "subprocess"}) + + cmd = '''if 1: + import sys + import multiprocessing + print(multiprocessing.get_start_method(allow_none=True), + "tempfile" in sys.modules, + multiprocessing.get_start_method(), + multiprocessing.get_all_start_methods()[0]) + ''' + # -S: site customizations could import tempfile themselves. + _, out, err = script_helper.assert_python_ok('-S', '-c', cmd) + unset, probed, method, first = out.decode().split() + self.assertEqual(unset, "None") + self.assertEqual(probed, "False") + self.assertEqual(method, first) + self.assertIn(method, multiprocessing.get_all_start_methods()) + @unittest.skipIf(sys.platform == "win32", "test semantics don't make sense on Windows") @@ -6189,6 +6423,7 @@ def _is_resource_tracker_reused(conn, pid): reused &= _resource_tracker._check_alive() conn.send(reused) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_resource_tracker_reused(self): from multiprocessing.resource_tracker import _resource_tracker _resource_tracker.ensure_running() @@ -6467,6 +6702,7 @@ def test_empty_exceptions(self): with self.assertRaisesRegex(OSError, 'is closed'): q.empty() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_empty(self): queue = multiprocessing.SimpleQueue() child_can_start = multiprocessing.Event() @@ -6574,7 +6810,8 @@ def test_list(self): def setUp(self): self.manager = self.manager_class() - self.manager.start() + with warnings_helper.ignore_fork_in_thread_deprecation_warnings(): + self.manager.start() self.proc = None def tearDown(self): @@ -6623,6 +6860,7 @@ def _test_event(cls, obj): obj.clear() obj.wait(0.001) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_event(self): o = self.manager.Event() o.set() @@ -6635,6 +6873,7 @@ def _test_lock(cls, obj): obj.acquire() obj.locked() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_lock(self, lname="Lock"): o = getattr(self.manager, lname)() self.run_worker(self._test_lock, o) @@ -6647,6 +6886,7 @@ def _test_rlock(cls, obj): obj.release() obj.locked() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_rlock(self, lname="RLock"): o = getattr(self.manager, lname)() self.run_worker(self._test_rlock, o) @@ -6655,6 +6895,7 @@ def test_rlock(self, lname="RLock"): def _test_semaphore(cls, obj): obj.acquire() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_semaphore(self, sname="Semaphore"): o = getattr(self.manager, sname)() self.run_worker(self._test_semaphore, o) @@ -6668,6 +6909,7 @@ def _test_condition(cls, obj): obj.acquire() obj.release() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_condition(self): o = self.manager.Condition() self.run_worker(self._test_condition, o) @@ -6677,6 +6919,7 @@ def _test_barrier(cls, obj): assert obj.parties == 5 obj.reset() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_barrier(self): o = self.manager.Barrier(5) self.run_worker(self._test_barrier, o) @@ -6687,6 +6930,7 @@ def _test_pool(cls, obj): with obj: pass + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_pool(self): o = self.manager.Pool(processes=4) self.run_worker(self._test_pool, o) @@ -6701,6 +6945,7 @@ def _test_queue(cls, obj): assert obj.get() == 6 assert obj.empty() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_queue(self, qname="Queue"): o = getattr(self.manager, qname)(2) o.put(5) @@ -6709,6 +6954,7 @@ def test_queue(self, qname="Queue"): assert o.empty() assert not o.full() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_joinable_queue(self): self.test_queue("JoinableQueue") @@ -6743,6 +6989,7 @@ def _test_list(cls, obj): obj.clear() case.assertEqual(len(obj), 0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_list(self): o = self.manager.list() o.append(5) @@ -6784,6 +7031,7 @@ def _test_dict(cls, obj): obj.clear() case.assertEqual(len(obj), 0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_dict(self): o = self.manager.dict() o['foo'] = 5 @@ -6798,6 +7046,7 @@ def _test_value(cls, obj): case.assertEqual(obj.get(), 1) obj.set(2) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_value(self): o = self.manager.Value('i', 1) self.run_worker(self._test_value, o) @@ -6812,6 +7061,7 @@ def _test_array(cls, obj): case.assertEqual(len(obj), 2) case.assertListEqual(list(obj), [0, 1]) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_array(self): o = self.manager.Array('i', [0, 1]) self.run_worker(self._test_array, o) @@ -6822,6 +7072,7 @@ def _test_namespace(cls, obj): case.assertEqual(obj.x, 0) case.assertEqual(obj.y, 1) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_namespace(self): o = self.manager.Namespace() o.x = 0 @@ -6941,6 +7192,7 @@ def _test_set_comparisons(cls, obj): case.assertGreater(obj, {'a'}) case.assertGreaterEqual(obj, {'a', 'b'}) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_set(self): o = self.manager.set() self.run_worker(self._test_set_operator_symbols, o) @@ -6958,6 +7210,7 @@ def test_set_init(self): self.assertSetEqual(o, {"a", "b", "c"}) self.assertRaises(RemoteError, self.manager.set, 1234) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_set_contain_all_method(self): o = self.manager.set() set_methods = { @@ -7011,6 +7264,7 @@ def exit_handler(): f.write("deadbeef") atexit.register(exit_handler) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_atexit(self): # gh-83856 with os_helper.temp_dir() as temp_dir: @@ -7148,6 +7402,7 @@ def f(x): return x*x self.assertEqual("332833500", out.decode('utf-8').strip()) self.assertFalse(err, msg=err.decode('utf-8')) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_forked_thread_not_started(self): # gh-134381: Ensure that a thread that has not been started yet in # the parent process can be started within a forked child process. @@ -7298,8 +7553,9 @@ def Pool(cls, *args, **kwds): @classmethod def setUpClass(cls): - super().setUpClass() - cls.manager = multiprocessing.Manager() + with warnings_helper.ignore_fork_in_thread_deprecation_warnings(): + super().setUpClass() + cls.manager = multiprocessing.Manager() @classmethod def tearDownClass(cls): @@ -7468,6 +7724,64 @@ class SemLock(_multiprocessing.SemLock): _multiprocessing.sem_unlink(name) +@unittest.skipIf(sys.platform != "linux", "Linux only") +class ForkInThreads(unittest.TestCase): + + def test_fork(self): + code = """ + import os, sys, threading, time + + t = threading.Thread(target=time.sleep, args=(1,), daemon=True) + t.start() + + assert threading.active_count() == 2 + + pid = os.fork() + if pid < 0: + print("Fork failed") + elif pid == 0: + print("In child") + sys.exit(0) + print("In parent") + """ + + res = assert_python_ok("-c", code, PYTHONWARNINGS='always') + self.assertIn(b'In child', res.out) + self.assertIn(b'In parent', res.out) + self.assertIn(b'DeprecationWarning', res.err) + self.assertIn(b'is multi-threaded, use of fork() may lead to deadlocks in the child', res.err) + + res = assert_python_failure("-c", code, PYTHONWARNINGS='error') + self.assertIn(b'DeprecationWarning', res.err) + self.assertIn(b'is multi-threaded, use of fork() may lead to deadlocks in the child', res.err) + + def test_forkpty(self): + code = """ + import os, sys, threading, time + + t = threading.Thread(target=time.sleep, args=(1,), daemon=True) + t.start() + + assert threading.active_count() == 2 + + pid, _ = os.forkpty() + if pid < 0: + print(f"forkpty failed") + elif pid == 0: + print(f"In child") + sys.exit(0) + print(f"In parent") + """ + + res = assert_python_ok("-c", code, PYTHONWARNINGS='always') + self.assertIn(b'In parent', res.out) + self.assertIn(b'DeprecationWarning', res.err) + self.assertIn(b'is multi-threaded, use of forkpty() may lead to deadlocks in the child', res.err) + + res = assert_python_failure("-c", code, PYTHONWARNINGS='error') + self.assertIn(b'DeprecationWarning', res.err) + self.assertIn(b'is multi-threaded, use of forkpty() may lead to deadlocks in the child', res.err) + @unittest.skipUnless(HAS_SHMEM, "requires multiprocessing.shared_memory") class TestSharedMemoryNames(unittest.TestCase): @subTests('use_simple_format', (True, False)) @@ -7511,7 +7825,7 @@ def test_that_shared_memory_name_with_colons_has_no_resource_tracker_errors( print("SUCCESS") """ % use_simple_format) - rc, out, err = script_helper.assert_python_ok("-c", test_script) + rc, out, err = assert_python_ok("-c", test_script) self.assertIn(b"SUCCESS", out) self.assertNotIn(b"traceback", err.lower(), err) self.assertNotIn(b"resource_tracker.py", err, err) diff --git a/Lib/test/audiodata/pluck-float32.wav b/Lib/test/audiodata/pluck-float32.wav new file mode 100644 index 00000000000..2030fb16d6e Binary files /dev/null and b/Lib/test/audiodata/pluck-float32.wav differ diff --git a/Lib/test/audiotest.au b/Lib/test/audiotest.au deleted file mode 100644 index f76b0501b8c..00000000000 Binary files a/Lib/test/audiotest.au and /dev/null differ diff --git a/Lib/test/audiotests.py b/Lib/test/audiotests.py index 9d6c4cc2b4b..394097df17d 100644 --- a/Lib/test/audiotests.py +++ b/Lib/test/audiotests.py @@ -27,17 +27,18 @@ def tearDown(self): unlink(TESTFN) def check_params(self, f, nchannels, sampwidth, framerate, nframes, - comptype, compname): + comptype, compname, format): self.assertEqual(f.getnchannels(), nchannels) self.assertEqual(f.getsampwidth(), sampwidth) self.assertEqual(f.getframerate(), framerate) self.assertEqual(f.getnframes(), nframes) self.assertEqual(f.getcomptype(), comptype) self.assertEqual(f.getcompname(), compname) + self.assertEqual(f.getformat(), format) params = f.getparams() self.assertEqual(params, - (nchannels, sampwidth, framerate, nframes, comptype, compname)) + (nchannels, sampwidth, framerate, nframes, comptype, compname)) self.assertEqual(params.nchannels, nchannels) self.assertEqual(params.sampwidth, sampwidth) self.assertEqual(params.framerate, framerate) @@ -51,13 +52,17 @@ def check_params(self, f, nchannels, sampwidth, framerate, nframes, class AudioWriteTests(AudioTests): + readonly = False def create_file(self, testfile): + if self.readonly: + self.skipTest('Read only file format') f = self.fout = self.module.open(testfile, 'wb') f.setnchannels(self.nchannels) f.setsampwidth(self.sampwidth) f.setframerate(self.framerate) f.setcomptype(self.comptype, self.compname) + f.setformat(self.format) return f def check_file(self, testfile, nframes, frames): @@ -67,13 +72,14 @@ def check_file(self, testfile, nframes, frames): self.assertEqual(f.getframerate(), self.framerate) self.assertEqual(f.getnframes(), nframes) self.assertEqual(f.readframes(nframes), frames) + self.assertEqual(f.getformat(), self.format) def test_write_params(self): f = self.create_file(TESTFN) f.setnframes(self.nframes) f.writeframes(self.frames) self.check_params(f, self.nchannels, self.sampwidth, self.framerate, - self.nframes, self.comptype, self.compname) + self.nframes, self.comptype, self.compname, self.format) f.close() def test_write_context_manager_calls_close(self): @@ -257,7 +263,7 @@ def test_read_params(self): f = self.f = self.module.open(self.sndfilepath) #self.assertEqual(f.getfp().name, self.sndfilepath) self.check_params(f, self.nchannels, self.sampwidth, self.framerate, - self.sndfilenframes, self.comptype, self.compname) + self.sndfilenframes, self.comptype, self.compname, self.format) def test_close(self): with open(self.sndfilepath, 'rb') as testfile: @@ -298,6 +304,8 @@ def test_read(self): f.setpos(f.getnframes() + 1) def test_copy(self): + if self.readonly: + self.skipTest('Read only file format') f = self.f = self.module.open(self.sndfilepath) fout = self.fout = self.module.open(TESTFN, 'wb') fout.setparams(f.getparams()) diff --git a/Lib/test/audit-tests.py b/Lib/test/audit-tests.py index 6884ac0dbe6..8be5bf8aa4f 100644 --- a/Lib/test/audit-tests.py +++ b/Lib/test/audit-tests.py @@ -8,6 +8,8 @@ import contextlib import os import sys +import unittest.mock +from test.support import swap_item class TestHook: @@ -206,6 +208,16 @@ def rl(name): else: return None + try: + import _remote_debugging + except ImportError: + _remote_debugging = None + + def rd(name): + if _remote_debugging: + return getattr(_remote_debugging, name, None) + return None + # Try a range of "open" functions. # All of them should fail with TestHook(raise_on_events={"open"}) as hook: @@ -223,6 +235,8 @@ def rl(name): (rl("append_history_file"), 0, None), (rl("read_init_file"), testfn), (rl("read_init_file"), None), + (rd("BinaryWriter"), testfn, 1000, 0), + (rd("BinaryReader"), testfn), ]: if not fn: continue @@ -256,6 +270,8 @@ def rl(name): ("~/.history", "a") if rl("append_history_file") else None, (testfn, "r") if readline else None, ("", "r") if readline else None, + (testfn, "wb") if rd("BinaryWriter") else None, + (testfn, "rb") if rd("BinaryReader") else None, ] if i is not None ], @@ -672,6 +688,84 @@ def hook(event, args): assertEqual(event_script_path, tmp_file.name) assertEqual(remote_event_script_path, tmp_file.name) +def test_import_module(): + import importlib + + with TestHook() as hook: + importlib.import_module("importlib") # already imported, won't get logged + importlib.import_module("email") # standard library module + importlib.import_module("pythoninfo") # random module + importlib.import_module(".audit_test_data.submodule", "test") # relative import + importlib.import_module("test.audit_test_data.submodule2") # absolute import + importlib.import_module("_testcapi") # extension module + + actual = [a for e, a in hook.seen if e == "import"] + assertSequenceEqual( + [ + ("email", None, sys.path, sys.meta_path, sys.path_hooks), + ("pythoninfo", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data.submodule", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data.submodule2", None, sys.path, sys.meta_path, sys.path_hooks), + ("_testcapi", None, sys.path, sys.meta_path, sys.path_hooks), + ("_testcapi", unittest.mock.ANY, None, None, None) + ], + actual, + ) + +def test_builtin__import__(): + import importlib # noqa: F401 + + with TestHook() as hook: + __import__("importlib") + __import__("email") + __import__("pythoninfo") + __import__("audit_test_data.submodule", level=1, globals={"__package__": "test"}) + __import__("test.audit_test_data.submodule2") + __import__("_testcapi") + + actual = [a for e, a in hook.seen if e == "import"] + assertSequenceEqual( + [ + ("email", None, sys.path, sys.meta_path, sys.path_hooks), + ("pythoninfo", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data.submodule", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data.submodule2", None, sys.path, sys.meta_path, sys.path_hooks), + ("_testcapi", None, sys.path, sys.meta_path, sys.path_hooks), + ("_testcapi", unittest.mock.ANY, None, None, None) + ], + actual, + ) + +def test_import_statement(): + import importlib # noqa: F401 + # Set __package__ so relative imports work + with swap_item(globals(), "__package__", "test"): + with TestHook() as hook: + import importlib # noqa: F401 + import email # noqa: F401 + import pythoninfo # noqa: F401 + from .audit_test_data import submodule # noqa: F401 + import test.audit_test_data.submodule2 # noqa: F401 + import _testcapi # noqa: F401 + + actual = [a for e, a in hook.seen if e == "import"] + # Import statement ordering is different because the package is + # loaded first and then the submodule + assertSequenceEqual( + [ + ("email", None, sys.path, sys.meta_path, sys.path_hooks), + ("pythoninfo", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data.submodule", None, sys.path, sys.meta_path, sys.path_hooks), + ("test.audit_test_data.submodule2", None, sys.path, sys.meta_path, sys.path_hooks), + ("_testcapi", None, sys.path, sys.meta_path, sys.path_hooks), + ("_testcapi", unittest.mock.ANY, None, None, None) + ], + actual, + ) + if __name__ == "__main__": from test.support import suppress_msvcrt_asserts diff --git a/Lib/test/test_importlib/data/__init__.py b/Lib/test/audit_test_data/__init__.py similarity index 100% rename from Lib/test/test_importlib/data/__init__.py rename to Lib/test/audit_test_data/__init__.py diff --git a/Lib/test/test_importlib/resources/data01/__init__.py b/Lib/test/audit_test_data/submodule.py similarity index 100% rename from Lib/test/test_importlib/resources/data01/__init__.py rename to Lib/test/audit_test_data/submodule.py diff --git a/Lib/test/test_importlib/resources/data01/subdirectory/__init__.py b/Lib/test/audit_test_data/submodule2.py similarity index 100% rename from Lib/test/test_importlib/resources/data01/subdirectory/__init__.py rename to Lib/test/audit_test_data/submodule2.py diff --git a/Lib/test/badsyntax_3131.py b/Lib/test/badsyntax_3131.py deleted file mode 100644 index 901d3744ca0..00000000000 --- a/Lib/test/badsyntax_3131.py +++ /dev/null @@ -1,2 +0,0 @@ -# -*- coding: utf-8 -*- -€ = 2 diff --git a/Lib/test/badsyntax_pep3120.py b/Lib/test/badsyntax_pep3120.py deleted file mode 100644 index d14b4c96ede..00000000000 --- a/Lib/test/badsyntax_pep3120.py +++ /dev/null @@ -1 +0,0 @@ -print("böse") diff --git a/Lib/test/bisect_cmd.py b/Lib/test/bisect_cmd.py new file mode 100644 index 00000000000..aee2e8ac120 --- /dev/null +++ b/Lib/test/bisect_cmd.py @@ -0,0 +1,185 @@ +#!/usr/bin/env python3 +""" +Command line tool to bisect failing CPython tests. + +Find the test_os test method which alters the environment: + + ./python -m test.bisect_cmd --fail-env-changed test_os + +Find a reference leak in "test_os", write the list of failing tests into the +"bisect" file: + + ./python -m test.bisect_cmd -o bisect -R 3:3 test_os + +Load an existing list of tests from a file using -i option: + + ./python -m test --list-cases -m FileTests test_os > tests + ./python -m test.bisect_cmd -i tests test_os +""" + +import argparse +import datetime +import os.path +import math +import random +import subprocess +import sys +import tempfile +import time + + +def write_tests(filename, tests): + with open(filename, "w") as fp: + for name in tests: + print(name, file=fp) + fp.flush() + + +def write_output(filename, tests): + if not filename: + return + print("Writing %s tests into %s" % (len(tests), filename)) + write_tests(filename, tests) + return filename + + +def format_shell_args(args): + return ' '.join(args) + + +def python_cmd(): + cmd = [sys.executable] + cmd.extend(subprocess._args_from_interpreter_flags()) + cmd.extend(subprocess._optim_args_from_interpreter_flags()) + cmd.extend(('-X', 'faulthandler')) + return cmd + + +def list_cases(args): + cmd = python_cmd() + cmd.extend(['-m', 'test', '--list-cases']) + cmd.extend(args.test_args) + proc = subprocess.run(cmd, + stdout=subprocess.PIPE, + universal_newlines=True) + exitcode = proc.returncode + if exitcode: + cmd = format_shell_args(cmd) + print("Failed to list tests: %s failed with exit code %s" + % (cmd, exitcode)) + sys.exit(exitcode) + tests = proc.stdout.splitlines() + return tests + + +def run_tests(args, tests, huntrleaks=None): + tmp = tempfile.mktemp() + try: + write_tests(tmp, tests) + + cmd = python_cmd() + cmd.extend(['-u', '-m', 'test', '--matchfile', tmp]) + cmd.extend(args.test_args) + print("+ %s" % format_shell_args(cmd)) + + sys.stdout.flush() + sys.stderr.flush() + + proc = subprocess.run(cmd) + return proc.returncode + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser.add_argument('-i', '--input', + help='Test names produced by --list-tests written ' + 'into a file. If not set, run --list-tests') + parser.add_argument('-o', '--output', + help='Result of the bisection') + parser.add_argument('-n', '--max-tests', type=int, default=1, + help='Maximum number of tests to stop the bisection ' + '(default: 1)') + parser.add_argument('-N', '--max-iter', type=int, default=100, + help='Maximum number of bisection iterations ' + '(default: 100)') + # FIXME: document that following arguments are test arguments + + args, test_args = parser.parse_known_args() + args.test_args = test_args + return args + + +def main(): + args = parse_args() + for opt in ('-w', '--rerun', '--verbose2'): + if opt in args.test_args: + print(f"WARNING: {opt} option should not be used to bisect!") + print() + + if args.input: + with open(args.input) as fp: + tests = [line.strip() for line in fp] + else: + tests = list_cases(args) + + print("Start bisection with %s tests" % len(tests)) + print("Test arguments: %s" % format_shell_args(args.test_args)) + print("Bisection will stop when getting %s or less tests " + "(-n/--max-tests option), or after %s iterations " + "(-N/--max-iter option)" + % (args.max_tests, args.max_iter)) + output = write_output(args.output, tests) + print() + + start_time = time.monotonic() + iteration = 1 + try: + while len(tests) > args.max_tests and iteration <= args.max_iter: + ntest = len(tests) + ntest = max(ntest // 2, 1) + subtests = random.sample(tests, ntest) + + print(f"[+] Iteration {iteration}/{args.max_iter}: " + f"run {len(subtests)} tests/{len(tests)}") + print() + + exitcode = run_tests(args, subtests) + + print("ran %s tests/%s" % (ntest, len(tests))) + print("exit", exitcode) + if exitcode: + print("Tests failed: continuing with this subtest") + tests = subtests + output = write_output(args.output, tests) + else: + print("Tests succeeded: skipping this subtest, trying a new subset") + print() + iteration += 1 + except KeyboardInterrupt: + print() + print("Bisection interrupted!") + print() + + print("Tests (%s):" % len(tests)) + for test in tests: + print("* %s" % test) + print() + + if output: + print("Output written into %s" % output) + + dt = math.ceil(time.monotonic() - start_time) + if len(tests) <= args.max_tests: + print("Bisection completed in %s iterations and %s" + % (iteration, datetime.timedelta(seconds=dt))) + else: + print("Bisection failed after %s iterations and %s" + % (iteration, datetime.timedelta(seconds=dt))) + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/Lib/test/certdata/distrusted.zip b/Lib/test/certdata/distrusted.zip new file mode 100644 index 00000000000..83184329a5a Binary files /dev/null and b/Lib/test/certdata/distrusted.zip differ diff --git a/Lib/test/cov.py b/Lib/test/cov.py new file mode 100644 index 00000000000..8717b1f20dd --- /dev/null +++ b/Lib/test/cov.py @@ -0,0 +1,48 @@ +"""A minimal hook for gathering line coverage of the standard library. + +Designed to be used with -Xpresite=test.cov:enable which means: + +* it can't import anything besides `sys` to avoid tainting gathered coverage +* filenames are not normalized + +To get gathered coverage back, look for 'test.cov' in `sys.modules` +instead of importing directly. That way you can determine if the module +was already in use. + +If you need to disable the hook, call the `disable()` function. +""" + +import sys + +mon = sys.monitoring + +FileName = str +LineNo = int +Location = tuple[FileName, LineNo] + +coverage: set[Location] = set() + + +# `types` and `typing` aren't imported to avoid invalid coverage +def add_line( + code: "types.CodeType", + lineno: int, +) -> "typing.Literal[sys.monitoring.DISABLE]": + coverage.add((code.co_filename, lineno)) + return mon.DISABLE + + +def enable(): + mon.use_tool_id(mon.COVERAGE_ID, "regrtest coverage") + mon.register_callback(mon.COVERAGE_ID, mon.events.LINE, add_line) + mon.set_events(mon.COVERAGE_ID, mon.events.LINE) + + +def disable(): + mon.set_events(mon.COVERAGE_ID, 0) + mon.register_callback(mon.COVERAGE_ID, mon.events.LINE, None) + mon.free_tool_id(mon.COVERAGE_ID) + + +if __name__ == "__main__": + enable() diff --git a/Lib/test/curses_tests.py b/Lib/test/curses_tests.py new file mode 100755 index 00000000000..40e832dec25 --- /dev/null +++ b/Lib/test/curses_tests.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# +# $Id: ncurses.py 36559 2004-07-18 05:56:09Z tim_one $ +# +# Interactive test suite for the curses module. +# This script displays various things and the user should verify whether +# they display correctly. +# + +import curses +from curses import textpad + +def test_textpad(stdscr, insert_mode=False): + ncols, nlines = 8, 3 + uly, ulx = 3, 2 + if insert_mode: + mode = 'insert mode' + else: + mode = 'overwrite mode' + + stdscr.addstr(uly-3, ulx, "Use Ctrl-G to end editing (%s)." % mode) + stdscr.addstr(uly-2, ulx, "Be sure to try typing in the lower-right corner.") + win = curses.newwin(nlines, ncols, uly, ulx) + textpad.rectangle(stdscr, uly-1, ulx-1, uly + nlines, ulx + ncols) + stdscr.refresh() + + box = textpad.Textbox(win, insert_mode) + contents = box.edit() + stdscr.addstr(uly+ncols+2, 0, "Text entered in the box\n") + stdscr.addstr(repr(contents)) + stdscr.addstr('\n') + stdscr.addstr('Press any key') + stdscr.getch() + + for i in range(3): + stdscr.move(uly+ncols+2 + i, 0) + stdscr.clrtoeol() + +def main(stdscr): + stdscr.clear() + test_textpad(stdscr, False) + test_textpad(stdscr, True) + + +if __name__ == '__main__': + curses.wrapper(main) diff --git a/Lib/test/dataclass_module_1.py b/Lib/test/dataclass_module_1.py deleted file mode 100644 index 87a33f8191d..00000000000 --- a/Lib/test/dataclass_module_1.py +++ /dev/null @@ -1,32 +0,0 @@ -#from __future__ import annotations -USING_STRINGS = False - -# dataclass_module_1.py and dataclass_module_1_str.py are identical -# except only the latter uses string annotations. - -import dataclasses -import typing - -T_CV2 = typing.ClassVar[int] -T_CV3 = typing.ClassVar - -T_IV2 = dataclasses.InitVar[int] -T_IV3 = dataclasses.InitVar - -@dataclasses.dataclass -class CV: - T_CV4 = typing.ClassVar - cv0: typing.ClassVar[int] = 20 - cv1: typing.ClassVar = 30 - cv2: T_CV2 - cv3: T_CV3 - not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. - -@dataclasses.dataclass -class IV: - T_IV4 = dataclasses.InitVar - iv0: dataclasses.InitVar[int] - iv1: dataclasses.InitVar - iv2: T_IV2 - iv3: T_IV3 - not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar. diff --git a/Lib/test/dataclass_module_1_str.py b/Lib/test/dataclass_module_1_str.py deleted file mode 100644 index 6de490b7ad7..00000000000 --- a/Lib/test/dataclass_module_1_str.py +++ /dev/null @@ -1,32 +0,0 @@ -from __future__ import annotations -USING_STRINGS = True - -# dataclass_module_1.py and dataclass_module_1_str.py are identical -# except only the latter uses string annotations. - -import dataclasses -import typing - -T_CV2 = typing.ClassVar[int] -T_CV3 = typing.ClassVar - -T_IV2 = dataclasses.InitVar[int] -T_IV3 = dataclasses.InitVar - -@dataclasses.dataclass -class CV: - T_CV4 = typing.ClassVar - cv0: typing.ClassVar[int] = 20 - cv1: typing.ClassVar = 30 - cv2: T_CV2 - cv3: T_CV3 - not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. - -@dataclasses.dataclass -class IV: - T_IV4 = dataclasses.InitVar - iv0: dataclasses.InitVar[int] - iv1: dataclasses.InitVar - iv2: T_IV2 - iv3: T_IV3 - not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar. diff --git a/Lib/test/dataclass_textanno.py b/Lib/test/dataclass_textanno.py deleted file mode 100644 index 3eb6c943d4c..00000000000 --- a/Lib/test/dataclass_textanno.py +++ /dev/null @@ -1,12 +0,0 @@ -from __future__ import annotations - -import dataclasses - - -class Foo: - pass - - -@dataclasses.dataclass -class Bar: - foo: Foo diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 1b71b71c544..dae71a6b667 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -3,6 +3,7 @@ import contextlib import copy import decimal +import fractions import io import itertools import os @@ -21,7 +22,7 @@ from test import support from test.support import is_resource_enabled, ALWAYS_EQ, LARGEST, SMALLEST -from test.support import os_helper, script_helper, warnings_helper +from test.support import os_helper, script_helper import datetime as datetime_module from datetime import MINYEAR, MAXYEAR @@ -1205,15 +1206,20 @@ def test_strptime_single_digit(self): newdate = strptime(string, format) self.assertEqual(newdate, target, msg=reason) - @warnings_helper.ignore_warnings(category=DeprecationWarning) def test_strptime_leap_year(self): - # GH-70647: warns if parsing a format with a day and no year. + # GH-70647: %d errors if parsing a format with a day and no year. with self.assertRaises(ValueError): # The existing behavior that GH-70647 seeks to change. date.strptime('02-29', '%m-%d') + # %e without a year is deprecated, scheduled for removal in 3.17. + _strptime._regex_cache.clear() + with self.assertWarnsRegex(DeprecationWarning, + r'.*day of month without a year.*'): + date.strptime('02-01', '%m-%e') with self._assertNotWarns(DeprecationWarning): date.strptime('20-03-14', '%y-%m-%d') date.strptime('02-29,2024', '%m-%d,%Y') + date.strptime('02-29,2024', '%m-%e,%Y') class SubclassDate(date): sub_var = 1 @@ -2100,7 +2106,15 @@ def test_fromisoformat_fails(self): '10000-W25-1', # Invalid year '2020-W25-0', # Invalid day-of-week '2020-W25-8', # Invalid day-of-week - '٢025-03-09' # Unicode characters + # gh-152204: each fixed-width field must be exactly N ASCII digits + '2020+12', # '+' in a basic-format field + '2020 12', # space in a basic-format field + '+020-06-15', # leading sign in the year + '202012+9', # '+' in the day field + '2020-W 5', # space in the week number + '2020061', # 7 chars: day slice reads a 1-character tail + '2020-W2', # 1-digit week number + '٢025-03-09', # Unicode characters '2009\ud80002\ud80028', # Separators are surrogate codepoints ] @@ -2157,14 +2171,20 @@ def test_fromisocalendar_value_errors(self): (10000, 1, 1), (0, 1, 1), (9999999, 1, 1), + ] + for isocal in isocals: + with self.subTest(isocal=isocal): + with self.assertRaises(ValueError): + self.theclass.fromisocalendar(*isocal) + + isocals = [ (2<<32, 1, 1), (2019, 2<<32, 1), (2019, 1, 2<<32), ] - for isocal in isocals: with self.subTest(isocal=isocal): - with self.assertRaises(ValueError): + with self.assertRaises((ValueError, OverflowError)): self.theclass.fromisocalendar(*isocal) def test_fromisocalendar_type_errors(self): @@ -2190,6 +2210,34 @@ def test_fromisocalendar_type_errors(self): with self.assertRaises(TypeError): self.theclass.fromisocalendar(*isocal) + def test_strptime_F_format(self): + test_date = "2025-10-26" + self.assertEqual( + self.theclass.strptime(test_date, "%F"), + self.theclass.strptime(test_date, "%Y-%m-%d") + ) + + def test_strptime_D_format(self): + test_date = "11/28/25" + self.assertEqual( + self.theclass.strptime(test_date, "%D"), + self.theclass.strptime(test_date, "%m/%d/%y") + ) + + def test_strptime_n_and_t_format(self): + format_directives = ('%n', '%t', '%n%t', '%t%n') + whitespaces = ('', ' ', '\t', '\r', '\v', '\n', '\f') + for fd in format_directives: + for ws in (*whitespaces, ''.join(whitespaces)): + with self.subTest(format_directive=fd, whitespace=ws): + self.assertEqual( + self.theclass.strptime( + f"2026{ws}02{ws}03", + f"%Y{fd}%m{fd}%d", + ), + self.theclass(2026, 2, 3), + ) + ############################################################################# # datetime tests @@ -2311,7 +2359,7 @@ def test_isoformat_timezone(self): dt = dt_base.replace(tzinfo=tzi) exp = exp_base + exp_tz with self.subTest(tzi=tzi): - assert dt.isoformat() == exp + self.assertEqual(dt.isoformat(), exp) def test_format(self): dt = self.theclass(2007, 9, 10, 4, 5, 1, 123) @@ -2624,6 +2672,10 @@ def test_fromtimestamp(self): expected = time.localtime(ts) got = self.theclass.fromtimestamp(ts) self.verify_field_equality(expected, got) + got = self.theclass.fromtimestamp(decimal.Decimal(ts)) + self.verify_field_equality(expected, got) + got = self.theclass.fromtimestamp(fractions.Fraction(ts)) + self.verify_field_equality(expected, got) def test_fromtimestamp_keyword_arg(self): import time @@ -2639,6 +2691,12 @@ def test_utcfromtimestamp(self): with self.assertWarns(DeprecationWarning): got = self.theclass.utcfromtimestamp(ts) self.verify_field_equality(expected, got) + with self.assertWarns(DeprecationWarning): + got = self.theclass.utcfromtimestamp(decimal.Decimal(ts)) + self.verify_field_equality(expected, got) + with self.assertWarns(DeprecationWarning): + got = self.theclass.utcfromtimestamp(fractions.Fraction(ts)) + self.verify_field_equality(expected, got) # Run with US-style DST rules: DST begins 2 a.m. on second Sunday in # March (M3.2.0) and ends 2 a.m. on first Sunday in November (M11.1.0). @@ -2693,24 +2751,20 @@ def utcfromtimestamp(*args, **kwargs): self.assertEqual(zero.second, 0) self.assertEqual(zero.microsecond, 0) one = fts(1e-6) - try: - minus_one = fts(-1e-6) - except OSError: - # localtime(-1) and gmtime(-1) is not supported on Windows - pass - else: - self.assertEqual(minus_one.second, 59) - self.assertEqual(minus_one.microsecond, 999999) - - t = fts(-1e-8) - self.assertEqual(t, zero) - t = fts(-9e-7) - self.assertEqual(t, minus_one) - t = fts(-1e-7) - self.assertEqual(t, zero) - t = fts(-1/2**7) - self.assertEqual(t.second, 59) - self.assertEqual(t.microsecond, 992188) + minus_one = fts(-1e-6) + + self.assertEqual(minus_one.second, 59) + self.assertEqual(minus_one.microsecond, 999999) + + t = fts(-1e-8) + self.assertEqual(t, zero) + t = fts(-9e-7) + self.assertEqual(t, minus_one) + t = fts(-1e-7) + self.assertEqual(t, zero) + t = fts(-1/2**7) + self.assertEqual(t.second, 59) + self.assertEqual(t.microsecond, 992188) t = fts(1e-7) self.assertEqual(t, zero) @@ -2726,6 +2780,100 @@ def utcfromtimestamp(*args, **kwargs): self.assertEqual(t.second, 0) self.assertEqual(t.microsecond, 7812) + @support.run_with_tz('MSK-03') # Something east of Greenwich + def test_microsecond_rounding_decimal(self): + D = decimal.Decimal + def utcfromtimestamp(*args, **kwargs): + with self.assertWarns(DeprecationWarning): + return self.theclass.utcfromtimestamp(*args, **kwargs) + + for fts in [self.theclass.fromtimestamp, + utcfromtimestamp]: + zero = fts(D(0)) + self.assertEqual(zero.second, 0) + self.assertEqual(zero.microsecond, 0) + one = fts(D('0.000_001')) + minus_one = fts(D('-0.000_001')) + + self.assertEqual(minus_one.second, 59) + self.assertEqual(minus_one.microsecond, 999_999) + + t = fts(D('-0.000_000_1')) + self.assertEqual(t, zero) + t = fts(D('-0.000_000_9')) + self.assertEqual(t, minus_one) + t = fts(D(-1)/2**7) + self.assertEqual(t.second, 59) + self.assertEqual(t.microsecond, 992188) + + t = fts(D('0.000_000_1')) + self.assertEqual(t, zero) + t = fts(D('0.000_000_5')) + self.assertEqual(t, zero) + t = fts(D('0.000_000_500_000_000_000_000_1')) + self.assertEqual(t, one) + t = fts(D('0.000_000_9')) + self.assertEqual(t, one) + t = fts(D('0.999_999_499_999_999_9')) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 999_999) + t = fts(D('0.999_999_5')) + self.assertEqual(t.second, 1) + self.assertEqual(t.microsecond, 0) + t = fts(D('0.999_999_9')) + self.assertEqual(t.second, 1) + self.assertEqual(t.microsecond, 0) + t = fts(D(1)/2**7) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 7812) + + @support.run_with_tz('MSK-03') # Something east of Greenwich + def test_microsecond_rounding_fraction(self): + F = fractions.Fraction + def utcfromtimestamp(*args, **kwargs): + with self.assertWarns(DeprecationWarning): + return self.theclass.utcfromtimestamp(*args, **kwargs) + + for fts in [self.theclass.fromtimestamp, + utcfromtimestamp]: + zero = fts(F(0)) + self.assertEqual(zero.second, 0) + self.assertEqual(zero.microsecond, 0) + one = fts(F(1, 1_000_000)) + minus_one = fts(F(-1, 1_000_000)) + + self.assertEqual(minus_one.second, 59) + self.assertEqual(minus_one.microsecond, 999_999) + + t = fts(F(-1, 10_000_000)) + self.assertEqual(t, zero) + t = fts(F(-9, 10_000_000)) + self.assertEqual(t, minus_one) + t = fts(F(-1, 2**7)) + self.assertEqual(t.second, 59) + self.assertEqual(t.microsecond, 992188) + + t = fts(F(1, 10_000_000)) + self.assertEqual(t, zero) + t = fts(F(5, 10_000_000)) + self.assertEqual(t, zero) + t = fts(F(5_000_000_000, 9_999_999_999_999_999)) + self.assertEqual(t, one) + t = fts(F(9, 10_000_000)) + self.assertEqual(t, one) + t = fts(F(9_999_995_000_000_000, 10_000_000_000_000_001)) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 999_999) + t = fts(F(9_999_995, 10_000_000)) + self.assertEqual(t.second, 1) + self.assertEqual(t.microsecond, 0) + t = fts(F(9_999_999, 10_000_000)) + self.assertEqual(t.second, 1) + self.assertEqual(t.microsecond, 0) + t = fts(F(1, 2**7)) + self.assertEqual(t.second, 0) + self.assertEqual(t.microsecond, 7812) + def test_timestamp_limits(self): with self.subTest("minimum UTC"): min_dt = self.theclass.min.replace(tzinfo=timezone.utc) @@ -2745,6 +2893,7 @@ def test_timestamp_limits(self): # If that assumption changes, this value can change as well self.assertEqual(max_ts, 253402300799.0) + @unittest.skipIf(sys.platform == "win32", "Windows doesn't support min timestamp") def test_fromtimestamp_limits(self): try: self.theclass.fromtimestamp(-2**32 - 1) @@ -2784,6 +2933,7 @@ def test_fromtimestamp_limits(self): # OverflowError, especially on 32-bit platforms. self.theclass.fromtimestamp(ts) + @unittest.skipIf(sys.platform == "win32", "Windows doesn't support min timestamp") def test_utcfromtimestamp_limits(self): with self.assertWarns(DeprecationWarning): try: @@ -2845,13 +2995,11 @@ def test_insane_utcfromtimestamp(self): self.assertRaises(OverflowError, self.theclass.utcfromtimestamp, insane) - @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_fromtimestamp(self): # The result is tz-dependent; at least test that this doesn't # fail (like it did before bug 1646728 was fixed). self.theclass.fromtimestamp(-1.05) - @unittest.skipIf(sys.platform == "win32", "Windows doesn't accept negative timestamps") def test_negative_float_utcfromtimestamp(self): with self.assertWarns(DeprecationWarning): d = self.theclass.utcfromtimestamp(-1.05) @@ -2905,6 +3053,12 @@ def test_strptime(self): strptime("-00:02:01.000003", "%z").utcoffset(), -timedelta(minutes=2, seconds=1, microseconds=3) ) + self.assertEqual(strptime("+01:07", "%:z").utcoffset(), + 1 * HOUR + 7 * MINUTE) + self.assertEqual(strptime("-10:02", "%:z").utcoffset(), + -(10 * HOUR + 2 * MINUTE)) + self.assertEqual(strptime("-00:00:01.00001", "%:z").utcoffset(), + -timedelta(seconds=1, microseconds=10)) # Only local timezone and UTC are supported for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'), (-_time.timezone, _time.tzname[0])): @@ -2934,6 +3088,16 @@ def test_strptime(self): with self.assertRaises(ValueError): strptime("-000", "%z") with self.assertRaises(ValueError): strptime("z", "%z") + def test_strptime_ampm(self): + dt = datetime(1999, 3, 17, 0, 44, 55, 2) + for hour in range(0, 24): + with self.subTest(hour=hour): + new_dt = dt.replace(hour=hour) + dt_str = new_dt.strftime("%I %p") + + self.assertEqual(self.theclass.strptime(dt_str, "%I %p").hour, + hour) + def test_strptime_single_digit(self): # bpo-34903: Check that single digit dates and times are allowed. @@ -2968,19 +3132,35 @@ def test_strptime_single_digit(self): newdate = strptime(string, format) self.assertEqual(newdate, target, msg=reason) - @warnings_helper.ignore_warnings(category=DeprecationWarning) def test_strptime_leap_year(self): - # GH-70647: warns if parsing a format with a day and no year. + # GH-70647: %d errors if parsing a format with a day and no year. with self.assertRaises(ValueError): # The existing behavior that GH-70647 seeks to change. self.theclass.strptime('02-29', '%m-%d') + with self.assertRaises(ValueError): + self.theclass.strptime('03-14.159265', '%m-%d.%f') + # %e without a year is deprecated, scheduled for removal in 3.17. + _strptime._regex_cache.clear() with self.assertWarnsRegex(DeprecationWarning, r'.*day of month without a year.*'): - self.theclass.strptime('03-14.159265', '%m-%d.%f') + self.theclass.strptime('03-14.159265', '%m-%e.%f') with self._assertNotWarns(DeprecationWarning): self.theclass.strptime('20-03-14.159265', '%y-%m-%d.%f') with self._assertNotWarns(DeprecationWarning): self.theclass.strptime('02-29,2024', '%m-%d,%Y') + with self._assertNotWarns(DeprecationWarning): + self.theclass.strptime('02-29,2024', '%m-%e,%Y') + + def test_strptime_z_empty(self): + for directive in ('z', ':z'): + string = '2025-04-25 11:42:47' + format = f'%Y-%m-%d %H:%M:%S%{directive}' + target = self.theclass(2025, 4, 25, 11, 42, 47) + with self.subTest(string=string, + format=format, + target=target): + result = self.theclass.strptime(string, format) + self.assertEqual(result, target) def test_more_timetuple(self): # This tests fields beyond those tested by the TestDate.test_timetuple. @@ -3348,7 +3528,7 @@ def test_fromisoformat_timezone(self): with self.subTest(tstr=dtstr): dt_rt = self.theclass.fromisoformat(dtstr) - assert dt == dt_rt, dt_rt + self.assertEqual(dt_rt, dt) def test_fromisoformat_separators(self): separators = [ @@ -3581,11 +3761,24 @@ def test_fromisoformat_fails_datetime(self): '2009-04-19T12:30:45.400 +02:30', # Space between ms and timezone (gh-130959) '2009-04-19T12:30:45.400 ', # Trailing space (gh-130959) '2009-04-19T12:30:45. 400', # Space before fraction (gh-130959) - '2020-2020', # Ambiguous 9-char date portion - '2009-04-19T12:30:45.+05:00', # Empty fraction before offset - '2009-04-19T12:30:45.-05:00', # Empty fraction before offset - '2009-04-19T12:30:45.Z', # Empty fraction before Z - '2009-04-19T12:30:45,+05:00', # Empty fraction (comma) before offset + '2009-04-19T12:30:45+00:90:00', # Time zone field out from range + '2009-04-19T12:30:45+00:00:90', # Time zone field out from range + '2009-04-19T12:30:45-00:90:00', # Time zone field out from range + '2009-04-19T12:30:45-00:00:90', # Time zone field out from range + '2020-2020', # Ambiguous 9-char date portion + # gh-152204: each time field must be exactly N ASCII digits + '2020-12-12T0٥:02:03', # Unicode digit in the hour + '2020-12-12T01:0٥:03', # Unicode digit in the minute + '2020-12-12T01:02:0٥', # Unicode digit in the second + '2020-12-12T01:02:03.٥', # Unicode digit in the fraction + '2020-12-12T01:02:03.4_6', # underscore in the fraction + '2020-12-12T01:02:03+0٥:00', # Unicode digit in the tz hour + '2020-12-12T01:02:03+01:0٥', # Unicode digit in the tz minute + '20201212T0102٣٤', # Unicode digits in the basic-format time + '2009-04-19T12:30:45.+05:00', # Empty fraction before offset + '2009-04-19T12:30:45.-05:00', # Empty fraction before offset + '2009-04-19T12:30:45.Z', # Empty fraction before Z + '2009-04-19T12:30:45,+05:00', # Empty fraction (comma) before offset ] for bad_str in bad_strs: @@ -3678,6 +3871,13 @@ def test_repr_subclass(self): td = SubclassDatetime(2010, 10, 2, second=3) self.assertEqual(repr(td), "SubclassDatetime(2010, 10, 2, 0, 0, 3)") + def test_strptime_T_format(self): + test_time = "15:00:00" + self.assertEqual( + self.theclass.strptime(test_time, "%T"), + self.theclass.strptime(test_time, "%H:%M:%S") + ) + class TestSubclassDateTime(TestDateTime): theclass = SubclassDatetime @@ -3892,7 +4092,7 @@ def test_isoformat_timezone(self): t = t_base.replace(tzinfo=tzi) exp = exp_base + exp_tz with self.subTest(tzi=tzi): - assert t.isoformat() == exp + self.assertEqual(t.isoformat(), exp) def test_1653736(self): # verify it doesn't accept extra keyword arguments @@ -4073,6 +4273,12 @@ def test_strptime_tz(self): strptime("-00:02:01.000003", "%z").utcoffset(), -timedelta(minutes=2, seconds=1, microseconds=3) ) + self.assertEqual(strptime("+01:07", "%:z").utcoffset(), + 1 * HOUR + 7 * MINUTE) + self.assertEqual(strptime("-10:02", "%:z").utcoffset(), + -(10 * HOUR + 2 * MINUTE)) + self.assertEqual(strptime("-00:00:01.00001", "%:z").utcoffset(), + -timedelta(seconds=1, microseconds=10)) # Only local timezone and UTC are supported for tzseconds, tzname in ((0, 'UTC'), (0, 'GMT'), (-_time.timezone, _time.tzname[0])): @@ -4102,9 +4308,11 @@ def test_strptime_tz(self): self.assertEqual(strptime("UTC", "%Z").tzinfo, None) def test_strptime_errors(self): - for tzstr in ("-2400", "-000", "z"): + for tzstr in ("-2400", "-000", "z", "24:00"): with self.assertRaises(ValueError): self.theclass.strptime(tzstr, "%z") + with self.assertRaises(ValueError): + self.theclass.strptime(tzstr, "%:z") def test_strptime_single_digit(self): # bpo-34903: Check that single digit times are allowed. @@ -4382,7 +4590,7 @@ def utcoffset(self, t): elif x is d2: expected = -1 else: - assert y is d2 + self.assertIs(y, d2) expected = 1 self.assertEqual(got, expected) @@ -4710,7 +4918,7 @@ def test_fromisoformat_timezone(self): with self.subTest(tstr=tstr): t_rt = self.theclass.fromisoformat(tstr) - assert t == t_rt + self.assertEqual(t_rt, t) def test_fromisoformat_timespecs(self): time_bases = [ @@ -4842,6 +5050,11 @@ def test_fromisoformat_fails(self): '12:30:45.400 +02:30', # Space between ms and timezone (gh-130959) '12:30:45.400 ', # Trailing space (gh-130959) '12:30:45. 400', # Space before fraction (gh-130959) + '24:00:00.000001', # Has non-zero microseconds on 24:00 + '24:00:01.000000', # Has non-zero seconds on 24:00 + '24:01:00.000000', # Has non-zero minutes on 24:00 + '12:30:45+00:90:00', # Time zone field out from range + '12:30:45+00:00:90', # Time zone field out from range '12:30:45.+05:00', # Empty fraction before offset '12:30:45.-05:00', # Empty fraction before offset '12:30:45.Z', # Empty fraction before Z @@ -5546,7 +5759,7 @@ def utcoffset(self, t): elif x is d2: expected = timedelta(minutes=(11-59)-0) else: - assert y is d2 + self.assertIs(y, d2) expected = timedelta(minutes=0-(11-59)) self.assertEqual(got, expected) diff --git a/Lib/test/double_const.py b/Lib/test/double_const.py deleted file mode 100644 index 67852aaf982..00000000000 --- a/Lib/test/double_const.py +++ /dev/null @@ -1,30 +0,0 @@ -from test.support import TestFailed - -# A test for SF bug 422177: manifest float constants varied way too much in -# precision depending on whether Python was loading a module for the first -# time, or reloading it from a precompiled .pyc. The "expected" failure -# mode is that when test_import imports this after all .pyc files have been -# erased, it passes, but when test_import imports this from -# double_const.pyc, it fails. This indicates a woeful loss of precision in -# the marshal format for doubles. It's also possible that repr() doesn't -# produce enough digits to get reasonable precision for this box. - -PI = 3.14159265358979324 -TWOPI = 6.28318530717958648 - -PI_str = "3.14159265358979324" -TWOPI_str = "6.28318530717958648" - -# Verify that the double x is within a few bits of eval(x_str). -def check_ok(x, x_str): - assert x > 0.0 - x2 = eval(x_str) - assert x2 > 0.0 - diff = abs(x - x2) - # If diff is no larger than 3 ULP (wrt x2), then diff/8 is no larger - # than 0.375 ULP, so adding diff/8 to x2 should have no effect. - if x2 + (diff / 8.) != x2: - raise TestFailed("Manifest const %s lost too much precision " % x_str) - -check_ok(PI, PI_str) -check_ok(TWOPI, TWOPI_str) diff --git a/Lib/test/dtracedata/call_stack.py b/Lib/test/dtracedata/call_stack.py index ee9f3ae8d6c..11c0369d4ba 100644 --- a/Lib/test/dtracedata/call_stack.py +++ b/Lib/test/dtracedata/call_stack.py @@ -5,16 +5,16 @@ def function_1(): def function_2(): function_1() -# CALL_FUNCTION_VAR +# CALL with positional args def function_3(dummy, dummy2): pass -# CALL_FUNCTION_KW +# CALL_KW (keyword arguments) def function_4(**dummy): return 1 return 2 # unreachable -# CALL_FUNCTION_VAR_KW +# CALL_FUNCTION_EX (unpacking) def function_5(dummy, dummy2, **dummy3): if False: return 7 diff --git a/Lib/test/dtracedata/call_stack.stp b/Lib/test/dtracedata/call_stack.stp index 54082c202f6..2901f44654b 100644 --- a/Lib/test/dtracedata/call_stack.stp +++ b/Lib/test/dtracedata/call_stack.stp @@ -10,32 +10,21 @@ function basename:string(path:string) return last_token; } -probe process.mark("function__entry") -{ - funcname = user_string($arg2); - - if (funcname == "start") { - tracing = 1; - } -} - -probe process.mark("function__entry"), process.mark("function__return") +probe @PYTHON_SYSTEMTAP_PROBE@("function__entry"), + @PYTHON_SYSTEMTAP_PROBE@("function__return") { filename = user_string($arg1); funcname = user_string($arg2); lineno = $arg3; - if (tracing) { + if (funcname == "start") { + if ($$name == "function__entry") { + tracing = 1; + } else { + tracing = 0; + } + } else if (tracing) { printf("%d\t%s:%s:%s:%d\n", gettimeofday_us(), $$name, basename(filename), funcname, lineno); } } - -probe process.mark("function__return") -{ - funcname = user_string($arg2); - - if (funcname == "start") { - tracing = 0; - } -} diff --git a/Lib/test/dtracedata/call_stack.stp.expected b/Lib/test/dtracedata/call_stack.stp.expected index 32cf396f820..044eae62018 100644 --- a/Lib/test/dtracedata/call_stack.stp.expected +++ b/Lib/test/dtracedata/call_stack.stp.expected @@ -1,8 +1,11 @@ -function__entry:call_stack.py:start:23 function__entry:call_stack.py:function_1:1 +function__entry:call_stack.py:function_3:9 +function__return:call_stack.py:function_3:10 function__return:call_stack.py:function_1:2 function__entry:call_stack.py:function_2:5 function__entry:call_stack.py:function_1:1 +function__entry:call_stack.py:function_3:9 +function__return:call_stack.py:function_3:10 function__return:call_stack.py:function_1:2 function__return:call_stack.py:function_2:6 function__entry:call_stack.py:function_3:9 @@ -11,4 +14,3 @@ function__entry:call_stack.py:function_4:13 function__return:call_stack.py:function_4:14 function__entry:call_stack.py:function_5:18 function__return:call_stack.py:function_5:21 -function__return:call_stack.py:start:28 diff --git a/Lib/test/dtracedata/gc.stp b/Lib/test/dtracedata/gc.stp index 162c6d3a220..11d2715e6c7 100644 --- a/Lib/test/dtracedata/gc.stp +++ b/Lib/test/dtracedata/gc.stp @@ -1,6 +1,6 @@ global tracing -probe process.mark("function__entry") +probe @PYTHON_SYSTEMTAP_PROBE@("function__entry") { funcname = user_string($arg2); @@ -9,14 +9,15 @@ probe process.mark("function__entry") } } -probe process.mark("gc__start"), process.mark("gc__done") +probe @PYTHON_SYSTEMTAP_PROBE@("gc__start"), + @PYTHON_SYSTEMTAP_PROBE@("gc__done") { if (tracing) { printf("%d\t%s:%ld\n", gettimeofday_us(), $$name, $arg1); } } -probe process.mark("function__return") +probe @PYTHON_SYSTEMTAP_PROBE@("function__return") { funcname = user_string($arg2); diff --git a/Lib/test/dtracedata/line.d b/Lib/test/dtracedata/line.d deleted file mode 100644 index 03f22db6fcc..00000000000 --- a/Lib/test/dtracedata/line.d +++ /dev/null @@ -1,7 +0,0 @@ -python$target:::line -/(copyinstr(arg1)=="test_line")/ -{ - printf("%d\t%s:%s:%s:%d\n", timestamp, - probename, basename(copyinstr(arg0)), - copyinstr(arg1), arg2); -} diff --git a/Lib/test/dtracedata/line.d.expected b/Lib/test/dtracedata/line.d.expected deleted file mode 100644 index 9b16ce76ee6..00000000000 --- a/Lib/test/dtracedata/line.d.expected +++ /dev/null @@ -1,20 +0,0 @@ -line:line.py:test_line:2 -line:line.py:test_line:3 -line:line.py:test_line:4 -line:line.py:test_line:5 -line:line.py:test_line:6 -line:line.py:test_line:7 -line:line.py:test_line:8 -line:line.py:test_line:9 -line:line.py:test_line:10 -line:line.py:test_line:11 -line:line.py:test_line:4 -line:line.py:test_line:5 -line:line.py:test_line:6 -line:line.py:test_line:7 -line:line.py:test_line:8 -line:line.py:test_line:10 -line:line.py:test_line:11 -line:line.py:test_line:4 -line:line.py:test_line:12 -line:line.py:test_line:13 diff --git a/Lib/test/dtracedata/line.py b/Lib/test/dtracedata/line.py deleted file mode 100644 index 0930ff391f7..00000000000 --- a/Lib/test/dtracedata/line.py +++ /dev/null @@ -1,17 +0,0 @@ -def test_line(): - a = 1 - print('# Preamble', a) - for i in range(2): - a = i - b = i+2 - c = i+3 - if c < 4: - a = c - d = a + b +c - print('#', a, b, c, d) - a = 1 - print('# Epilogue', a) - - -if __name__ == '__main__': - test_line() diff --git a/Lib/test/empty.vbs b/Lib/test/empty.vbs new file mode 100644 index 00000000000..f35f076fdb9 --- /dev/null +++ b/Lib/test/empty.vbs @@ -0,0 +1 @@ +'Empty VBS file, does nothing. Helper for Lib\test\test_startfile.py. \ No newline at end of file diff --git a/Lib/test/exception_hierarchy.txt b/Lib/test/exception_hierarchy.txt index f2649aa2d41..98a5e950602 100644 --- a/Lib/test/exception_hierarchy.txt +++ b/Lib/test/exception_hierarchy.txt @@ -14,6 +14,7 @@ BaseException ├── EOFError ├── ExceptionGroup [BaseExceptionGroup] ├── ImportError + │ └── ImportCycleError │ └── ModuleNotFoundError ├── LookupError │ ├── IndexError diff --git a/Lib/test/floating_points.txt b/Lib/test/floating_points.txt deleted file mode 100644 index 539073d19d8..00000000000 --- a/Lib/test/floating_points.txt +++ /dev/null @@ -1,1028 +0,0 @@ -# These numbers are used to test floating point binary-to-decimal conversion. -# They are based on the TCL test suite (tests/expr.test), which is based on -# test data from: -# Brigitte Verdonk, Annie Cuyt, Dennis Verschaeren, A precision and range -# independent tool for testing floating-point arithmetic II: Conversions, -# ACM Transactions on Mathematical Software 27:2 (March 2001), pp. 119-140. - -0E0 --0E0 -1E0 -15E-1 -125E-2 -1125E-3 -10625E-4 -103125E-5 -1015625E-6 -10078125E-7 -100390625E-8 -1001953125E-9 -10009765625E-10 -100048828125E-11 -1000244140625E-12 -10001220703125E-13 -100006103515625E-14 -1000030517578125E-15 -10000152587890625E-16 -+8E153 --1E153 -+9E306 --2E153 -+7E-304 --3E-49 -+7E-303 --6E-49 -+9E43 --9E44 -+8E303 --1E303 -+7E-287 --2E-204 -+2E-205 --9E-47 -+34E195 --68E195 -+85E194 --67E97 -+93E-234 --19E-87 -+38E-87 --38E-88 --69E220 -+18E43 --36E43 -+61E-99 --43E-92 -+86E-92 --51E-74 -+283E85 --566E85 -+589E187 --839E143 --744E-234 -+930E-235 --186E-234 -+604E175 --302E175 -+755E174 --151E175 -+662E-213 --408E-74 -+510E-75 -+6782E55 --2309E92 -+7963E34 --3391E55 -+7903E-96 --7611E-226 -+4907E-196 --5547E-311 -+5311E241 --5311E243 -+5311E242 -+9269E-45 --8559E-289 -+8699E-276 --8085E-64 -+74819E201 --82081E41 -+51881E37 --55061E157 -+77402E-215 --33891E-92 -+38701E-215 --82139E-76 -+75859E25 -+89509E140 --57533E287 -+46073E-32 --92146E-32 -+83771E-74 --34796E-276 -+584169E229 -+164162E41 --328324E41 -+209901E-11 --419802E-11 -+940189E-112 --892771E-213 -+757803E120 --252601E120 -+252601E121 --505202E120 -+970811E-264 --654839E-60 -+289767E-178 --579534E-178 --8823691E130 -+9346704E229 --1168338E229 --6063369E-136 -+3865421E-225 --5783893E-127 -+2572231E223 --5144462E223 -+1817623E109 -+6431543E-97 --5444097E-21 -+8076999E-121 --9997649E-270 -+50609263E157 -+70589528E130 --88236910E129 -+87575437E-310 --23135572E-127 -+85900881E177 --84863171E113 -+68761586E232 --50464069E286 -+27869147E-248 --55738294E-248 -+70176353E-53 --80555086E-32 --491080654E121 -+526250918E287 --245540327E121 --175150874E-310 -+350301748E-310 --437877185E-311 -+458117166E52 --916234332E52 -+229058583E52 --525789935E98 -+282926897E-227 --565853794E-227 -+667284113E-240 --971212611E-126 -+9981396317E-182 --5035231965E-156 -+8336960483E-153 --8056371144E-155 -+6418488827E79 --3981006983E252 -+7962013966E252 --4713898551E261 -+8715380633E-58 --9078555839E-109 -+9712126110E-127 -+42333842451E201 --84667684902E201 -+23792120709E-315 --78564021519E-227 -+71812054883E-188 --30311163631E-116 -+71803914657E292 -+36314223356E-109 -+18157111678E-109 --45392779195E-110 -+778380362293E218 --685763015669E280 -+952918668151E70 --548357443505E32 -+384865004907E-285 --769730009814E-285 -+697015418417E-93 --915654049301E-28 -+178548656339E169 --742522891517E259 -+742522891517E258 --357097312678E169 --3113521449172E218 -+3891901811465E217 --1556760724586E218 -+9997878507563E-195 --7247563029154E-319 -+3623781514577E-319 --3092446298323E-200 -+6363857920591E145 --8233559360849E94 -+2689845954547E49 --5379691909094E49 -+5560322501926E-301 --7812878489261E-179 -+8439398533053E-256 --2780161250963E-301 --87605699161665E155 --17521139832333E156 --88218101363513E-170 -+38639244311627E-115 -+35593959807306E261 --53390939710959E260 -+71187919614612E261 --88984899518265E260 -+77003665618895E-73 --15400733123779E-72 -+61602932495116E-72 --30801466247558E-72 -+834735494917063E-300 --589795149206434E-151 -+475603213226859E-42 --294897574603217E-151 -+850813008001913E93 --203449172043339E185 -+406898344086678E185 --813796688173356E185 -+6045338514609393E244 --5145963778954906E142 -+2572981889477453E142 --6965949469487146E74 -+6182410494241627E-119 --8510309498186985E-277 -+6647704637273331E-212 --2215901545757777E-212 -+3771476185376383E276 --3729901848043846E212 -+3771476185376383E277 --9977830465649166E119 -+8439928496349319E-142 --8204230082070882E-59 -+8853686434843997E-244 --5553274272288559E-104 -+36149023611096162E144 --36149023611096162E147 -+18074511805548081E146 --18074511805548081E147 -+97338774138954421E-290 --88133809804950961E-308 -+94080055902682397E-243 --24691002732654881E-115 -+52306490527514614E49 --26153245263757307E49 -+55188692254193604E165 --68985865317742005E164 -+27176258005319167E-261 --73169230107256116E-248 -+91461537634070145E-249 --54352516010638334E-261 -+586144289638535878E280 --601117006785295431E245 -+293072144819267939E280 --953184713238516652E272 -+902042358290366539E-281 --557035730189854663E-294 -+902042358290366539E-280 --354944100507554393E-238 -+272104041512242479E199 --816312124536727437E199 -+544208083024484958E199 --792644927852378159E78 --679406450132979175E-263 -+543525160106383340E-262 -+7400253695682920196E215 --1850063423920730049E215 -+3700126847841460098E215 --9250317119603650245E214 -+8396094300569779681E-252 --3507665085003296281E-75 -+7015330170006592562E-75 --7015330170006592562E-74 -+7185620434951919351E205 --1360520207561212395E198 -+2178999185345151731E-184 --8691089486201567102E-218 -+4345544743100783551E-218 --4357998370690303462E-184 -+59825267349106892461E177 --62259110684423957791E47 -+58380168477038565599E265 --62259110684423957791E48 --33584377202279118724E-252 --57484963479615354808E205 -+71856204349519193510E204 --14371240869903838702E205 -+36992084760177624177E-318 --73984169520355248354E-318 -+99257763227713890244E-115 --87336362425182547697E-280 -+7E289 --3E153 -+6E153 --5E243 -+7E-161 --7E-172 -+8E-63 --7E-113 -+8E126 --4E126 -+5E125 --1E126 -+8E-163 --1E-163 -+2E-163 --4E-163 -+51E195 --37E46 -+74E46 --56E289 -+69E-145 --70E-162 -+56E-161 --21E-303 -+34E-276 --68E-276 -+85E-277 --87E-274 -+829E102 --623E100 -+723E-162 --457E-102 -+914E-102 --323E-135 -+151E176 --302E176 -+921E90 --604E176 -+823E-206 --463E-114 -+348E-274 -+9968E100 --6230E99 -+1246E100 -+6676E-296 --8345E-297 -+1669E-296 --3338E-296 -+3257E58 --6514E58 -+2416E176 -+8085E-63 --3234E-62 -+1617E-62 --6468E-62 -+53418E111 --60513E160 -+26709E111 --99447E166 -+12549E48 --25098E48 -+50196E48 --62745E47 -+83771E-73 --97451E-167 -+86637E-203 --75569E-254 -+473806E83 --947612E83 -+292369E76 --584738E76 -+933587E-140 --720919E-14 -+535001E-149 --890521E-235 -+548057E81 --706181E88 -+820997E106 --320681E63 -+928609E-261 --302276E-254 -+151138E-254 -+4691773E45 --9383546E45 -+3059949E-243 --6119898E-243 -+5356626E-213 --4877378E-199 -+7716693E223 --5452869E109 -+4590831E156 --9181662E156 --3714436E-261 -+4643045E-262 --7428872E-261 -+52942146E130 --27966061E145 -+26471073E130 --55932122E145 -+95412548E-99 --47706274E-99 -+23853137E-99 --78493654E-301 -+65346417E29 --51083099E167 -+89396333E264 --84863171E114 -+59540836E-251 --74426045E-252 -+14885209E-251 --29770418E-251 -+982161308E122 --245540327E122 -+491080654E122 -+525452622E-310 --771837113E-134 -+820858081E-150 --262726311E-310 -+923091487E209 --653777767E273 -+842116236E-53 --741111169E-202 -+839507247E-284 --951487269E-264 --9821613080E121 -+6677856011E-31 --3573796826E-266 -+7147593652E-266 --9981396317E-181 -+3268888835E272 --2615111068E273 -+1307555534E273 -+2990671154E-190 --1495335577E-190 -+5981342308E-190 --7476677885E-191 -+82259684194E-202 --93227267727E-49 -+41129842097E-202 --47584241418E-314 --79360293406E92 -+57332259349E225 --57202326162E111 -+86860597053E-206 --53827010643E-200 -+53587107423E-61 -+635007636765E200 -+508006109412E201 --254003054706E201 -+561029718715E-72 --897647549944E-71 -+112205943743E-71 --873947086081E-236 -+809184709177E116 --573112917422E81 -+286556458711E81 -+952805821491E-259 --132189992873E-44 --173696038493E-144 -+1831132757599E-107 --9155663787995E-108 -+7324531030396E-107 --9277338894969E-200 -+8188292423973E287 --5672557437938E59 -+2836278718969E59 --9995153153494E54 -+9224786422069E-291 --3142213164987E-294 -+6284426329974E-294 --8340483752889E-301 -+67039371486466E89 --62150786615239E197 -+33519685743233E89 --52563419496999E156 -+32599460466991E-65 --41010988798007E-133 -+65198920933982E-65 --82021977596014E-133 -+80527976643809E61 --74712611505209E158 -+53390939710959E261 --69277302659155E225 -+46202199371337E-72 --23438635467783E-179 -+41921560615349E-67 --92404398742674E-72 -+738545606647197E124 --972708181182949E117 --837992143580825E87 -+609610927149051E-255 --475603213226859E-41 -+563002800671023E-177 --951206426453718E-41 -+805416432656519E202 --530658674694337E159 -+946574173863918E208 --318329953318553E113 --462021993713370E-73 -+369617594970696E-72 -+3666156212014994E233 --1833078106007497E233 -+8301790508624232E174 --1037723813578029E174 -+7297662880581139E-286 --5106185698912191E-276 -+7487252720986826E-165 --3743626360493413E-165 -+3773057430100257E230 --7546114860200514E230 -+4321222892463822E58 --7793560217139653E51 -+26525993941010681E112 --53051987882021362E112 -+72844871414247907E77 --88839359596763261E105 -+18718131802467065E-166 --14974505441973652E-165 -+73429396004640239E106 --58483921078398283E57 -+41391519190645203E165 --82783038381290406E165 -+58767043776702677E-163 --90506231831231999E-129 -+64409240769861689E-159 --77305427432277771E-190 -+476592356619258326E273 --953184713238516652E273 -+899810892172646163E283 --929167076892018333E187 -+647761278967534239E-312 --644290479820542942E-180 -+926145344610700019E-225 --958507931896511964E-246 -+272104041512242479E200 --792644927852378159E79 -+544208083024484958E200 --929963218616126365E290 -+305574339166810102E-219 --152787169583405051E-219 -+611148678333620204E-219 --763935847917025255E-220 -+7439550220920798612E158 --3719775110460399306E158 -+9299437776150998265E157 --7120190517612959703E120 -+3507665085003296281E-73 --7015330170006592562E-73 --6684428762278255956E-294 --1088416166048969916E200 --8707329328391759328E200 -+4439021781608558002E-65 --8878043563217116004E-65 -+2219510890804279001E-65 -+33051223951904955802E55 --56961524140903677624E120 -+71201905176129597030E119 -+14030660340013185124E-73 --17538325425016481405E-74 -+67536228609141569109E-133 --35620497849450218807E-306 -+66550376797582521751E-126 --71240995698900437614E-306 -+3E24 --6E24 -+6E26 --7E25 -+1E-14 --2E-14 -+4E-14 --8E-14 -+5E26 --8E27 -+1E27 --4E27 -+9E-13 --7E-20 -+56E25 --70E24 -+51E26 -+71E-17 --31E-5 -+62E-5 --94E-8 -+67E27 --81E24 -+54E23 --54E25 -+63E-22 --63E-23 -+43E-4 --86E-4 -+942E26 --471E25 -+803E24 --471E26 --409E-21 -+818E-21 --867E-8 -+538E27 --857E24 -+269E27 --403E26 -+959E-7 --959E-6 -+373E-27 --746E-27 -+4069E24 --4069E23 --8138E24 -+8294E-15 --4147E-14 -+4147E-15 --8294E-14 -+538E27 --2690E26 -+269E27 --2152E27 -+1721E-17 --7979E-27 -+6884E-17 --8605E-18 -+82854E27 --55684E24 -+27842E24 --48959E25 -+81921E-17 --76207E-8 -+4147E-15 --41470E-16 -+89309E24 -+75859E26 --75859E25 -+14257E-23 --28514E-23 -+57028E-23 --71285E-24 -+344863E27 --951735E27 -+200677E23 --401354E24 -+839604E-11 --209901E-11 -+419802E-11 --537734E-24 -+910308E26 --227577E26 -+455154E26 --531013E25 -+963019E-21 --519827E-13 -+623402E-27 --311701E-27 -+9613651E26 --9191316E23 -+4595658E23 --2297829E23 --1679208E-11 -+3379223E27 --6758446E27 -+5444097E-21 --8399969E-27 -+8366487E-16 --8366487E-15 -+65060671E25 -+65212389E23 -+55544957E-13 --51040905E-20 -+99585767E-22 --99585767E-23 -+40978393E26 --67488159E24 -+69005339E23 --81956786E26 --87105552E-21 -+10888194E-21 --21776388E-21 -+635806667E27 --670026614E25 -+335013307E26 --335013307E25 -+371790617E-24 --371790617E-25 -+743581234E-24 --743581234E-25 -+202464477E24 --404928954E24 -+997853758E27 --997853758E26 -+405498418E-17 --582579084E-14 -+608247627E-18 --291289542E-14 --9537100005E26 -+6358066670E27 --1271613334E27 -+5229646999E-16 -+5229646999E-17 -+4429943614E24 --8859887228E24 -+2214971807E24 --4176887093E26 -+4003495257E-20 --4361901637E-23 -+8723803274E-23 --8006990514E-20 -+72835110098E27 --36417555049E27 -+84279630104E25 --84279630104E24 -+21206176437E-27 --66461566917E-22 -+64808355539E-16 --84932679673E-19 -+65205430094E26 --68384463429E25 -+32602715047E26 --62662203426E27 -+58784444678E-18 --50980203373E-21 -+29392222339E-18 --75529940323E-27 --937495906299E26 -+842642485799E-20 --387824150699E-23 -+924948814726E-27 --775648301398E-23 -+547075707432E25 -+683844634290E24 --136768926858E25 -+509802033730E-22 -+101960406746E-21 --815683253968E-21 -+7344124123524E24 --9180155154405E23 -+6479463327323E27 --1836031030881E24 -+4337269293039E-19 --4599163554373E-23 -+9198327108746E-23 -+4812803938347E27 --8412030890011E23 -+9625607876694E27 --4739968828249E24 -+9697183891673E-23 --7368108517543E-20 -+51461358161422E25 --77192037242133E26 -+77192037242133E25 --51461358161422E27 -+43999661561541E-21 --87999323123082E-21 -+48374886826137E-26 --57684246567111E-23 -+87192805957686E23 --75108713005913E24 -+64233110587487E27 --77577471133384E-23 -+48485919458365E-24 --56908598265713E-26 -+589722294620133E23 -+652835804449289E-22 --656415363936202E-23 -+579336749585745E-25 --381292764980839E-26 -+965265859649698E23 --848925235434882E27 -+536177612222491E23 --424462617717441E27 -+276009279888989E-27 --608927158043691E-26 -+552018559777978E-27 --425678377667758E-22 -+8013702726927119E26 -+8862627962362001E27 --5068007907757162E26 --7379714799828406E-23 -+4114538064016107E-27 --3689857399914203E-23 -+5575954851815478E23 -+3395700941739528E27 -+4115535777581961E-23 --8231071555163922E-23 -+6550246696190871E-26 --68083046403986701E27 -+43566388595783643E27 --87132777191567286E27 -+59644881059342141E25 --83852770718576667E23 -+99482967418206961E-25 --99482967418206961E-26 -+87446669969994614E-27 --43723334984997307E-27 -+5E24 --8E25 -+1E25 --4E25 -+2E-5 --5E-6 -+4E-5 --3E-20 -+3E27 --9E26 -+7E25 --6E27 -+2E-21 --5E-22 --4E-21 -+87E25 --97E24 -+82E-24 --41E-24 -+76E-23 -+83E25 --50E27 -+25E27 --99E27 -+97E-10 --57E-20 -+997E23 -+776E24 --388E24 -+521E-10 --506E-26 -+739E-10 --867E-7 --415E24 -+332E25 --664E25 -+291E-13 --982E-8 -+582E-13 --491E-8 -+4574E26 --8609E26 -+2287E26 --4818E24 -+6529E-8 --8151E-21 -+1557E-12 --2573E-18 -+4929E-16 --3053E-22 -+9858E-16 --7767E-11 -+54339E26 --62409E25 -+32819E27 --89849E27 -+63876E-20 --15969E-20 -+31938E-20 --79845E-21 -+89306E27 --25487E24 -+79889E24 --97379E26 -+81002E-8 --43149E-25 -+40501E-8 --60318E-10 --648299E27 -+780649E24 -+720919E-14 --629703E-11 -+557913E24 --847899E23 -+565445E27 --736531E24 -+680013E-19 --529981E-10 -+382923E-23 --633614E-18 -+2165479E27 --8661916E27 -+4330958E27 --9391993E22 --5767352E-14 -+7209190E-15 --1441838E-14 -+8478990E22 -+1473062E24 -+8366487E-14 --8399969E-25 -+9366737E-12 --9406141E-13 -+65970979E24 --65060671E26 -+54923002E27 --63846927E25 -+99585767E-21 -+67488159E25 --69005339E24 -+81956786E27 --40978393E27 -+77505754E-12 --38752877E-12 -+82772981E-15 --95593517E-25 -+200036989E25 --772686455E27 -+859139907E23 --400073978E25 -+569014327E-14 --794263862E-15 -+397131931E-15 --380398957E-16 -+567366773E27 --337440795E24 -+134976318E25 --269952636E25 -+932080597E-20 --331091924E-15 --413864905E-16 -+8539246247E26 --5859139791E26 -+6105010149E24 --3090745820E27 -+3470877773E-20 --6136309089E-27 -+8917758713E-19 --6941755546E-20 -+9194900535E25 --1838980107E26 -+7355920428E26 --3677960214E26 -+8473634343E-17 --8870766274E-16 -+4435383137E-16 --9598990129E-15 -+71563496764E26 --89454370955E25 -+17890874191E26 --35781748382E26 -+57973447842E-19 --28986723921E-19 -+76822711313E-19 --97699466874E-20 -+67748656762E27 --19394840991E24 -+38789681982E24 --33874328381E27 -+54323763886E-27 --58987193887E-20 -+27161881943E-27 --93042648033E-19 -+520831059055E27 --768124264394E25 -+384062132197E25 -+765337749889E-25 -+794368912771E25 --994162090146E23 -+781652779431E26 -+910077190046E-26 --455038595023E-26 -+471897551096E-20 --906698409911E-21 -+8854128003935E25 --8146122716299E27 -+7083302403148E26 --3541651201574E26 -+8394920649291E-25 --7657975756753E-22 -+5473834002228E-20 --6842292502785E-21 --2109568884597E25 -+8438275538388E25 --4219137769194E25 -+3200141789841E-25 --8655689322607E-22 -+6400283579682E-25 --8837719634493E-21 -+19428217075297E24 --38856434150594E24 -+77712868301188E24 --77192037242133E27 -+76579757567530E-23 -+15315951513506E-22 --38289878783765E-23 -+49378033925202E25 --50940527102367E24 -+98756067850404E25 --99589397544892E26 --56908598265713E-25 -+97470695699657E-22 --35851901247343E-25 -+154384074484266E27 --308768148968532E27 -+910990389005985E23 -+271742424169201E-27 --543484848338402E-27 -+162192083357563E-26 --869254552770081E-23 -+664831007626046E24 --332415503813023E24 -+943701829041427E24 --101881054204734E24 -+828027839666967E-27 --280276135608777E-27 -+212839188833879E-21 --113817196531426E-25 -+9711553197796883E27 --2739849386524269E26 -+5479698773048538E26 -+6124568318523113E-25 --1139777988171071E-24 -+6322612303128019E-27 --2955864564844617E-25 --9994029144998961E25 --2971238324022087E27 --1656055679333934E-27 --1445488709150234E-26 -+55824717499885172E27 --69780896874856465E26 -+84161538867545199E25 --27912358749942586E27 -+24711112462926331E-25 --12645224606256038E-27 --12249136637046226E-25 -+74874448287465757E27 --35642836832753303E24 --71285673665506606E24 -+43723334984997307E-26 -+10182419849537963E-24 --93501703572661982E-26 - -# A value that caused a crash in debug builds for Python >= 2.7, 3.1 -# See http://bugs.python.org/issue7632 -2183167012312112312312.23538020374420446192e-370 - -# Another value designed to test a corner case of Python's strtod code. -0.99999999999999999999999999999999999999999e+23 diff --git a/Lib/test/formatfloat_testcases.txt b/Lib/test/formatfloat_testcases.txt deleted file mode 100644 index 25c07ba2939..00000000000 --- a/Lib/test/formatfloat_testcases.txt +++ /dev/null @@ -1,355 +0,0 @@ --- 'f' code formatting, with explicit precision (>= 0). Output always --- has the given number of places after the point; zeros are added if --- necessary to make this true. - --- zeros -%.0f 0 -> 0 -%.1f 0 -> 0.0 -%.2f 0 -> 0.00 -%.3f 0 -> 0.000 -%.50f 0 -> 0.00000000000000000000000000000000000000000000000000 - --- precision 0; result should never include a . -%.0f 1.5 -> 2 -%.0f 2.5 -> 2 -%.0f 3.5 -> 4 -%.0f 0.0 -> 0 -%.0f 0.1 -> 0 -%.0f 0.001 -> 0 -%.0f 10.0 -> 10 -%.0f 10.1 -> 10 -%.0f 10.01 -> 10 -%.0f 123.456 -> 123 -%.0f 1234.56 -> 1235 -%.0f 1e49 -> 9999999999999999464902769475481793196872414789632 -%.0f 9.9999999999999987e+49 -> 99999999999999986860582406952576489172979654066176 -%.0f 1e50 -> 100000000000000007629769841091887003294964970946560 - --- precision 1 -%.1f 0.0001 -> 0.0 -%.1f 0.001 -> 0.0 -%.1f 0.01 -> 0.0 -%.1f 0.04 -> 0.0 -%.1f 0.06 -> 0.1 -%.1f 0.25 -> 0.2 -%.1f 0.75 -> 0.8 -%.1f 1.4 -> 1.4 -%.1f 1.5 -> 1.5 -%.1f 10.0 -> 10.0 -%.1f 1000.03 -> 1000.0 -%.1f 1234.5678 -> 1234.6 -%.1f 1234.7499 -> 1234.7 -%.1f 1234.75 -> 1234.8 - --- precision 2 -%.2f 0.0001 -> 0.00 -%.2f 0.001 -> 0.00 -%.2f 0.004999 -> 0.00 -%.2f 0.005001 -> 0.01 -%.2f 0.01 -> 0.01 -%.2f 0.125 -> 0.12 -%.2f 0.375 -> 0.38 -%.2f 1234500 -> 1234500.00 -%.2f 1234560 -> 1234560.00 -%.2f 1234567 -> 1234567.00 -%.2f 1234567.8 -> 1234567.80 -%.2f 1234567.89 -> 1234567.89 -%.2f 1234567.891 -> 1234567.89 -%.2f 1234567.8912 -> 1234567.89 - --- alternate form always includes a decimal point. This only --- makes a difference when the precision is 0. -%#.0f 0 -> 0. -%#.1f 0 -> 0.0 -%#.0f 1.5 -> 2. -%#.0f 2.5 -> 2. -%#.0f 10.1 -> 10. -%#.0f 1234.56 -> 1235. -%#.1f 1.4 -> 1.4 -%#.2f 0.375 -> 0.38 - --- if precision is omitted it defaults to 6 -%f 0 -> 0.000000 -%f 1230000 -> 1230000.000000 -%f 1234567 -> 1234567.000000 -%f 123.4567 -> 123.456700 -%f 1.23456789 -> 1.234568 -%f 0.00012 -> 0.000120 -%f 0.000123 -> 0.000123 -%f 0.00012345 -> 0.000123 -%f 0.000001 -> 0.000001 -%f 0.0000005001 -> 0.000001 -%f 0.0000004999 -> 0.000000 - --- 'e' code formatting with explicit precision (>= 0). Output should --- always have exactly the number of places after the point that were --- requested. - --- zeros -%.0e 0 -> 0e+00 -%.1e 0 -> 0.0e+00 -%.2e 0 -> 0.00e+00 -%.10e 0 -> 0.0000000000e+00 -%.50e 0 -> 0.00000000000000000000000000000000000000000000000000e+00 - --- precision 0. no decimal point in the output -%.0e 0.01 -> 1e-02 -%.0e 0.1 -> 1e-01 -%.0e 1 -> 1e+00 -%.0e 10 -> 1e+01 -%.0e 100 -> 1e+02 -%.0e 0.012 -> 1e-02 -%.0e 0.12 -> 1e-01 -%.0e 1.2 -> 1e+00 -%.0e 12 -> 1e+01 -%.0e 120 -> 1e+02 -%.0e 123.456 -> 1e+02 -%.0e 0.000123456 -> 1e-04 -%.0e 123456000 -> 1e+08 -%.0e 0.5 -> 5e-01 -%.0e 1.4 -> 1e+00 -%.0e 1.5 -> 2e+00 -%.0e 1.6 -> 2e+00 -%.0e 2.4999999 -> 2e+00 -%.0e 2.5 -> 2e+00 -%.0e 2.5000001 -> 3e+00 -%.0e 3.499999999999 -> 3e+00 -%.0e 3.5 -> 4e+00 -%.0e 4.5 -> 4e+00 -%.0e 5.5 -> 6e+00 -%.0e 6.5 -> 6e+00 -%.0e 7.5 -> 8e+00 -%.0e 8.5 -> 8e+00 -%.0e 9.4999 -> 9e+00 -%.0e 9.5 -> 1e+01 -%.0e 10.5 -> 1e+01 -%.0e 14.999 -> 1e+01 -%.0e 15 -> 2e+01 - --- precision 1 -%.1e 0.0001 -> 1.0e-04 -%.1e 0.001 -> 1.0e-03 -%.1e 0.01 -> 1.0e-02 -%.1e 0.1 -> 1.0e-01 -%.1e 1 -> 1.0e+00 -%.1e 10 -> 1.0e+01 -%.1e 100 -> 1.0e+02 -%.1e 120 -> 1.2e+02 -%.1e 123 -> 1.2e+02 -%.1e 123.4 -> 1.2e+02 - --- precision 2 -%.2e 0.00013 -> 1.30e-04 -%.2e 0.000135 -> 1.35e-04 -%.2e 0.0001357 -> 1.36e-04 -%.2e 0.0001 -> 1.00e-04 -%.2e 0.001 -> 1.00e-03 -%.2e 0.01 -> 1.00e-02 -%.2e 0.1 -> 1.00e-01 -%.2e 1 -> 1.00e+00 -%.2e 10 -> 1.00e+01 -%.2e 100 -> 1.00e+02 -%.2e 1000 -> 1.00e+03 -%.2e 1500 -> 1.50e+03 -%.2e 1590 -> 1.59e+03 -%.2e 1598 -> 1.60e+03 -%.2e 1598.7 -> 1.60e+03 -%.2e 1598.76 -> 1.60e+03 -%.2e 9999 -> 1.00e+04 - --- omitted precision defaults to 6 -%e 0 -> 0.000000e+00 -%e 165 -> 1.650000e+02 -%e 1234567 -> 1.234567e+06 -%e 12345678 -> 1.234568e+07 -%e 1.1 -> 1.100000e+00 - --- alternate form always contains a decimal point. This only makes --- a difference when precision is 0. - -%#.0e 0.01 -> 1.e-02 -%#.0e 0.1 -> 1.e-01 -%#.0e 1 -> 1.e+00 -%#.0e 10 -> 1.e+01 -%#.0e 100 -> 1.e+02 -%#.0e 0.012 -> 1.e-02 -%#.0e 0.12 -> 1.e-01 -%#.0e 1.2 -> 1.e+00 -%#.0e 12 -> 1.e+01 -%#.0e 120 -> 1.e+02 -%#.0e 123.456 -> 1.e+02 -%#.0e 0.000123456 -> 1.e-04 -%#.0e 123456000 -> 1.e+08 -%#.0e 0.5 -> 5.e-01 -%#.0e 1.4 -> 1.e+00 -%#.0e 1.5 -> 2.e+00 -%#.0e 1.6 -> 2.e+00 -%#.0e 2.4999999 -> 2.e+00 -%#.0e 2.5 -> 2.e+00 -%#.0e 2.5000001 -> 3.e+00 -%#.0e 3.499999999999 -> 3.e+00 -%#.0e 3.5 -> 4.e+00 -%#.0e 4.5 -> 4.e+00 -%#.0e 5.5 -> 6.e+00 -%#.0e 6.5 -> 6.e+00 -%#.0e 7.5 -> 8.e+00 -%#.0e 8.5 -> 8.e+00 -%#.0e 9.4999 -> 9.e+00 -%#.0e 9.5 -> 1.e+01 -%#.0e 10.5 -> 1.e+01 -%#.0e 14.999 -> 1.e+01 -%#.0e 15 -> 2.e+01 -%#.1e 123.4 -> 1.2e+02 -%#.2e 0.0001357 -> 1.36e-04 - --- 'g' code formatting. - --- zeros -%.0g 0 -> 0 -%.1g 0 -> 0 -%.2g 0 -> 0 -%.3g 0 -> 0 -%.4g 0 -> 0 -%.10g 0 -> 0 -%.50g 0 -> 0 -%.100g 0 -> 0 - --- precision 0 doesn't make a lot of sense for the 'g' code (what does --- it mean to have no significant digits?); in practice, it's interpreted --- as identical to precision 1 -%.0g 1000 -> 1e+03 -%.0g 100 -> 1e+02 -%.0g 10 -> 1e+01 -%.0g 1 -> 1 -%.0g 0.1 -> 0.1 -%.0g 0.01 -> 0.01 -%.0g 1e-3 -> 0.001 -%.0g 1e-4 -> 0.0001 -%.0g 1e-5 -> 1e-05 -%.0g 1e-6 -> 1e-06 -%.0g 12 -> 1e+01 -%.0g 120 -> 1e+02 -%.0g 1.2 -> 1 -%.0g 0.12 -> 0.1 -%.0g 0.012 -> 0.01 -%.0g 0.0012 -> 0.001 -%.0g 0.00012 -> 0.0001 -%.0g 0.000012 -> 1e-05 -%.0g 0.0000012 -> 1e-06 - --- precision 1 identical to precision 0 -%.1g 1000 -> 1e+03 -%.1g 100 -> 1e+02 -%.1g 10 -> 1e+01 -%.1g 1 -> 1 -%.1g 0.1 -> 0.1 -%.1g 0.01 -> 0.01 -%.1g 1e-3 -> 0.001 -%.1g 1e-4 -> 0.0001 -%.1g 1e-5 -> 1e-05 -%.1g 1e-6 -> 1e-06 -%.1g 12 -> 1e+01 -%.1g 120 -> 1e+02 -%.1g 1.2 -> 1 -%.1g 0.12 -> 0.1 -%.1g 0.012 -> 0.01 -%.1g 0.0012 -> 0.001 -%.1g 0.00012 -> 0.0001 -%.1g 0.000012 -> 1e-05 -%.1g 0.0000012 -> 1e-06 - --- precision 2 -%.2g 1000 -> 1e+03 -%.2g 100 -> 1e+02 -%.2g 10 -> 10 -%.2g 1 -> 1 -%.2g 0.1 -> 0.1 -%.2g 0.01 -> 0.01 -%.2g 0.001 -> 0.001 -%.2g 1e-4 -> 0.0001 -%.2g 1e-5 -> 1e-05 -%.2g 1e-6 -> 1e-06 -%.2g 1234 -> 1.2e+03 -%.2g 123 -> 1.2e+02 -%.2g 12.3 -> 12 -%.2g 1.23 -> 1.2 -%.2g 0.123 -> 0.12 -%.2g 0.0123 -> 0.012 -%.2g 0.00123 -> 0.0012 -%.2g 0.000123 -> 0.00012 -%.2g 0.0000123 -> 1.2e-05 - --- bad cases from http://bugs.python.org/issue9980 -%.12g 38210.0 -> 38210 -%.12g 37210.0 -> 37210 -%.12g 36210.0 -> 36210 - --- alternate g formatting: always include decimal point and --- exactly significant digits. -%#.0g 0 -> 0. -%#.1g 0 -> 0. -%#.2g 0 -> 0.0 -%#.3g 0 -> 0.00 -%#.4g 0 -> 0.000 - -%#.0g 0.2 -> 0.2 -%#.1g 0.2 -> 0.2 -%#.2g 0.2 -> 0.20 -%#.3g 0.2 -> 0.200 -%#.4g 0.2 -> 0.2000 -%#.10g 0.2 -> 0.2000000000 - -%#.0g 2 -> 2. -%#.1g 2 -> 2. -%#.2g 2 -> 2.0 -%#.3g 2 -> 2.00 -%#.4g 2 -> 2.000 - -%#.0g 20 -> 2.e+01 -%#.1g 20 -> 2.e+01 -%#.2g 20 -> 20. -%#.3g 20 -> 20.0 -%#.4g 20 -> 20.00 - -%#.0g 234.56 -> 2.e+02 -%#.1g 234.56 -> 2.e+02 -%#.2g 234.56 -> 2.3e+02 -%#.3g 234.56 -> 235. -%#.4g 234.56 -> 234.6 -%#.5g 234.56 -> 234.56 -%#.6g 234.56 -> 234.560 - --- repr formatting. Result always includes decimal point and at --- least one digit after the point, or an exponent. -%r 0 -> 0.0 -%r 1 -> 1.0 - -%r 0.01 -> 0.01 -%r 0.02 -> 0.02 -%r 0.03 -> 0.03 -%r 0.04 -> 0.04 -%r 0.05 -> 0.05 - --- values >= 1e16 get an exponent -%r 10 -> 10.0 -%r 100 -> 100.0 -%r 1e15 -> 1000000000000000.0 -%r 9.999e15 -> 9999000000000000.0 -%r 9999999999999998 -> 9999999999999998.0 -%r 9999999999999999 -> 1e+16 -%r 1e16 -> 1e+16 -%r 1e17 -> 1e+17 - --- as do values < 1e-4 -%r 1e-3 -> 0.001 -%r 1.001e-4 -> 0.0001001 -%r 1.0000000000000001e-4 -> 0.0001 -%r 1.000000000000001e-4 -> 0.0001000000000000001 -%r 1.00000000001e-4 -> 0.000100000000001 -%r 1.0000000001e-4 -> 0.00010000000001 -%r 1e-4 -> 0.0001 -%r 0.99999999999999999e-4 -> 0.0001 -%r 0.9999999999999999e-4 -> 9.999999999999999e-05 -%r 0.999999999999e-4 -> 9.99999999999e-05 -%r 0.999e-4 -> 9.99e-05 -%r 1e-5 -> 1e-05 diff --git a/Lib/test/levenshtein_examples.json b/Lib/test/levenshtein_examples.json new file mode 100644 index 00000000000..a32672cfdba --- /dev/null +++ b/Lib/test/levenshtein_examples.json @@ -0,0 +1,50002 @@ +[ + [ + "", + "", + 0 + ], + [ + "", + "AabBbb", + 12 + ], + [ + "", + "AbaC", + 8 + ], + [ + "", + "B", + 2 + ], + [ + "", + "Ba", + 4 + ], + [ + "", + "CBaACCCa", + 16 + ], + [ + "", + "CCbBC", + 10 + ], + [ + "", + "CcbCbaaAB", + 18 + ], + [ + "", + "bAa", + 6 + ], + [ + "", + "bAaCABb", + 14 + ], + [ + "A", + "A", + 0 + ], + [ + "A", + "AA", + 2 + ], + [ + "A", + "AABCAabcC", + 16 + ], + [ + "A", + "AACB", + 6 + ], + [ + "A", + "AACC", + 6 + ], + [ + "A", + "ABAaBbc", + 12 + ], + [ + "A", + "ABCcC", + 8 + ], + [ + "A", + "ABa", + 4 + ], + [ + "A", + "ABbBabcaa", + 16 + ], + [ + "A", + "ABbbCBcA", + 14 + ], + [ + "A", + "ACCBcBbBb", + 16 + ], + [ + "A", + "ACa", + 4 + ], + [ + "A", + "ACb", + 4 + ], + [ + "A", + "ACcbbaAB", + 14 + ], + [ + "A", + "AaAaccAb", + 14 + ], + [ + "A", + "AaabbCC", + 12 + ], + [ + "A", + "AabB", + 6 + ], + [ + "A", + "AbBa", + 6 + ], + [ + "A", + "AbBaA", + 8 + ], + [ + "A", + "AbCBBCaC", + 14 + ], + [ + "A", + "AbCb", + 6 + ], + [ + "A", + "AbcB", + 6 + ], + [ + "A", + "B", + 2 + ], + [ + "A", + "BA", + 2 + ], + [ + "A", + "BABbCc", + 10 + ], + [ + "A", + "BABca", + 8 + ], + [ + "A", + "BB", + 4 + ], + [ + "A", + "BBaBBaa", + 13 + ], + [ + "A", + "BBbbaAA", + 12 + ], + [ + "A", + "BCCAAc", + 10 + ], + [ + "A", + "BCa", + 5 + ], + [ + "A", + "BCcaC", + 9 + ], + [ + "A", + "BCccaa", + 11 + ], + [ + "A", + "BaacCbC", + 13 + ], + [ + "A", + "BabCC", + 9 + ], + [ + "A", + "Bac", + 5 + ], + [ + "A", + "BbCbb", + 10 + ], + [ + "A", + "BbaBAC", + 10 + ], + [ + "A", + "Bbc", + 6 + ], + [ + "A", + "BcB", + 6 + ], + [ + "A", + "BcCAbCBA", + 14 + ], + [ + "A", + "BcaaCbCB", + 15 + ], + [ + "A", + "C", + 2 + ], + [ + "A", + "CA", + 2 + ], + [ + "A", + "CABAacB", + 12 + ], + [ + "A", + "CABBABBc", + 14 + ], + [ + "A", + "CAaaBc", + 10 + ], + [ + "A", + "CBAA", + 6 + ], + [ + "A", + "CBCcBaBAB", + 16 + ], + [ + "A", + "CBcbc", + 10 + ], + [ + "A", + "CC", + 4 + ], + [ + "A", + "CCA", + 4 + ], + [ + "A", + "CCB", + 6 + ], + [ + "A", + "CCBaACcC", + 14 + ], + [ + "A", + "CCBcAAacb", + 16 + ], + [ + "A", + "CaCCaA", + 10 + ], + [ + "A", + "CbAB", + 6 + ], + [ + "A", + "CbBaAACC", + 14 + ], + [ + "A", + "CbCCbB", + 12 + ], + [ + "A", + "CbacBb", + 11 + ], + [ + "A", + "CbbABc", + 10 + ], + [ + "A", + "CcC", + 6 + ], + [ + "A", + "CcCacAAAC", + 16 + ], + [ + "A", + "CccCbaCcb", + 17 + ], + [ + "A", + "a", + 1 + ], + [ + "A", + "aABABBa", + 12 + ], + [ + "A", + "aABBA", + 8 + ], + [ + "A", + "aABCaBCa", + 14 + ], + [ + "A", + "aACBabAC", + 14 + ], + [ + "A", + "aBCb", + 7 + ], + [ + "A", + "aBaB", + 7 + ], + [ + "A", + "aBbBb", + 9 + ], + [ + "A", + "aC", + 3 + ], + [ + "A", + "aCA", + 4 + ], + [ + "A", + "aaBBb", + 9 + ], + [ + "A", + "aaC", + 5 + ], + [ + "A", + "aaCb", + 7 + ], + [ + "A", + "aaCbABbb", + 14 + ], + [ + "A", + "aaCcbb", + 11 + ], + [ + "A", + "aaaaCcAB", + 14 + ], + [ + "A", + "aaabb", + 9 + ], + [ + "A", + "aaacCabCC", + 17 + ], + [ + "A", + "aacBccCAC", + 16 + ], + [ + "A", + "aacC", + 7 + ], + [ + "A", + "abCAb", + 8 + ], + [ + "A", + "abbBcaccc", + 17 + ], + [ + "A", + "acCAB", + 8 + ], + [ + "A", + "acacBcAA", + 14 + ], + [ + "A", + "b", + 2 + ], + [ + "A", + "bABACaB", + 12 + ], + [ + "A", + "bAbA", + 6 + ], + [ + "A", + "bAbaBc", + 10 + ], + [ + "A", + "bBAa", + 6 + ], + [ + "A", + "bBa", + 5 + ], + [ + "A", + "bBaCAab", + 12 + ], + [ + "A", + "bBaCaCBbB", + 17 + ], + [ + "A", + "bBbAbaBa", + 14 + ], + [ + "A", + "bBbacabAb", + 16 + ], + [ + "A", + "bCCbA", + 8 + ], + [ + "A", + "bCCbB", + 10 + ], + [ + "A", + "bCbbACc", + 12 + ], + [ + "A", + "bCbbc", + 10 + ], + [ + "A", + "baACBCB", + 12 + ], + [ + "A", + "babABb", + 10 + ], + [ + "A", + "bacB", + 7 + ], + [ + "A", + "bacacA", + 10 + ], + [ + "A", + "bb", + 4 + ], + [ + "A", + "bbCa", + 7 + ], + [ + "A", + "bbCbaa", + 11 + ], + [ + "A", + "bbbAcb", + 10 + ], + [ + "A", + "bc", + 4 + ], + [ + "A", + "bcAAcCAb", + 14 + ], + [ + "A", + "bcC", + 6 + ], + [ + "A", + "bcbbaab", + 13 + ], + [ + "A", + "c", + 2 + ], + [ + "A", + "cAB", + 4 + ], + [ + "A", + "cACAc", + 8 + ], + [ + "A", + "cAaBccaC", + 14 + ], + [ + "A", + "cAcAaCAc", + 14 + ], + [ + "A", + "cBAaC", + 8 + ], + [ + "A", + "cBAac", + 8 + ], + [ + "A", + "cBCAABbc", + 14 + ], + [ + "A", + "cBaCbab", + 13 + ], + [ + "A", + "cBacA", + 8 + ], + [ + "A", + "cBb", + 6 + ], + [ + "A", + "cC", + 4 + ], + [ + "A", + "cCBABaC", + 12 + ], + [ + "A", + "cCCCa", + 9 + ], + [ + "A", + "cCa", + 5 + ], + [ + "A", + "cCaAaCaCB", + 16 + ], + [ + "A", + "cCabbbCa", + 15 + ], + [ + "A", + "caacCacAb", + 16 + ], + [ + "A", + "cabbC", + 9 + ], + [ + "A", + "cb", + 4 + ], + [ + "A", + "cbC", + 6 + ], + [ + "A", + "cbCAaAaAB", + 16 + ], + [ + "A", + "cbbaaAbbB", + 16 + ], + [ + "A", + "cc", + 4 + ], + [ + "A", + "ccCcCBaB", + 15 + ], + [ + "A", + "ccabbC", + 11 + ], + [ + "AA", + "AA", + 0 + ], + [ + "AA", + "ACAA", + 4 + ], + [ + "AA", + "BAc", + 4 + ], + [ + "AA", + "BC", + 4 + ], + [ + "AA", + "BaccaAA", + 10 + ], + [ + "AA", + "Bba", + 5 + ], + [ + "AA", + "BbcbcccAB", + 16 + ], + [ + "AA", + "CAb", + 4 + ], + [ + "AA", + "Cc", + 4 + ], + [ + "AA", + "CcBACCa", + 11 + ], + [ + "AA", + "aCBa", + 6 + ], + [ + "AA", + "aaBA", + 5 + ], + [ + "AA", + "aaBac", + 8 + ], + [ + "AA", + "bAAabBA", + 10 + ], + [ + "AA", + "bABbacbb", + 13 + ], + [ + "AA", + "bBbBbc", + 12 + ], + [ + "AA", + "bC", + 4 + ], + [ + "AA", + "bCabb", + 9 + ], + [ + "AA", + "baAB", + 5 + ], + [ + "AA", + "bbBaBcCBB", + 17 + ], + [ + "AA", + "bbBbAaaB", + 13 + ], + [ + "AA", + "c", + 4 + ], + [ + "AA", + "cACaCbab", + 13 + ], + [ + "AA", + "cBbCbBcA", + 14 + ], + [ + "AA", + "cBba", + 7 + ], + [ + "AA", + "cCbBBCca", + 15 + ], + [ + "AA", + "cacaca", + 10 + ], + [ + "AA", + "ccbccAa", + 11 + ], + [ + "AAA", + "B", + 6 + ], + [ + "AAA", + "C", + 6 + ], + [ + "AAA", + "aBBbcAaBa", + 14 + ], + [ + "AAA", + "aacbbBbbc", + 16 + ], + [ + "AAA", + "abAb", + 5 + ], + [ + "AAA", + "cccaAbBcB", + 15 + ], + [ + "AAAAABA", + "CaBcAaa", + 10 + ], + [ + "AAABACbC", + "BBBC", + 11 + ], + [ + "AAABAbaaA", + "CBbbacb", + 12 + ], + [ + "AAABa", + "AA", + 6 + ], + [ + "AAABc", + "cbBabcaBA", + 14 + ], + [ + "AAAC", + "acBcCCcC", + 13 + ], + [ + "AAACAbAaa", + "BCc", + 16 + ], + [ + "AAACBACc", + "CaCabAc", + 10 + ], + [ + "AAACCbbcA", + "bc", + 14 + ], + [ + "AAACa", + "A", + 8 + ], + [ + "AAACbCaa", + "acABAAa", + 9 + ], + [ + "AAACbaaa", + "BBa", + 13 + ], + [ + "AAAa", + "bBaaCc", + 9 + ], + [ + "AAAaAB", + "BCB", + 10 + ], + [ + "AAAaAcC", + "CAbBcBBC", + 12 + ], + [ + "AAAaCAAb", + "aBbAbaaA", + 12 + ], + [ + "AAAaCaA", + "cBcABaAb", + 11 + ], + [ + "AAAaaaaA", + "ABBBcaA", + 10 + ], + [ + "AAAb", + "AcC", + 6 + ], + [ + "AAAb", + "B", + 7 + ], + [ + "AAAbAB", + "cCBaAbcc", + 11 + ], + [ + "AAAbBcbc", + "C", + 15 + ], + [ + "AAAbaAABb", + "cCcAaca", + 15 + ], + [ + "AAAbbaA", + "Cbcc", + 12 + ], + [ + "AAAbbc", + "ABcaCCbca", + 11 + ], + [ + "AAAbcAcBA", + "bBaACAC", + 13 + ], + [ + "AAAbcbCa", + "cabCCbCba", + 10 + ], + [ + "AAAcAcCC", + "cbBCAAB", + 13 + ], + [ + "AAAcBAbCB", + "cbbABC", + 12 + ], + [ + "AAB", + "CB", + 4 + ], + [ + "AAB", + "accAC", + 7 + ], + [ + "AAB", + "bCCbaBbAc", + 15 + ], + [ + "AAB", + "bbb", + 5 + ], + [ + "AAB", + "bcCBcC", + 10 + ], + [ + "AABA", + "AAc", + 4 + ], + [ + "AABA", + "cBCAbA", + 7 + ], + [ + "AABABCcCc", + "abAC", + 12 + ], + [ + "AABAaB", + "BAB", + 6 + ], + [ + "AABAbAa", + "BcaB", + 11 + ], + [ + "AABAcb", + "cca", + 10 + ], + [ + "AABBA", + "AbAaCBb", + 8 + ], + [ + "AABBAACcC", + "A", + 16 + ], + [ + "AABBBcb", + "B", + 12 + ], + [ + "AABBCaB", + "bAbBA", + 8 + ], + [ + "AABBCabC", + "BCC", + 10 + ], + [ + "AABBCcB", + "cABBBAACc", + 10 + ], + [ + "AABBabAA", + "A", + 14 + ], + [ + "AABBac", + "BACCCB", + 10 + ], + [ + "AABBc", + "CAaBaA", + 7 + ], + [ + "AABCb", + "CcaCab", + 8 + ], + [ + "AABCbccb", + "B", + 14 + ], + [ + "AABCcA", + "BabC", + 8 + ], + [ + "AABCcB", + "BAB", + 8 + ], + [ + "AABCca", + "AbBBC", + 7 + ], + [ + "AABCcbBB", + "Bab", + 12 + ], + [ + "AABa", + "ACCcBA", + 7 + ], + [ + "AABa", + "BCcbaAa", + 11 + ], + [ + "AABa", + "C", + 8 + ], + [ + "AABaAc", + "Ccaa", + 9 + ], + [ + "AABaC", + "aA", + 7 + ], + [ + "AABaCccb", + "AABaAAbc", + 8 + ], + [ + "AABabcc", + "ccaABC", + 11 + ], + [ + "AABacB", + "cCbaa", + 9 + ], + [ + "AABacBac", + "AcAa", + 10 + ], + [ + "AABaccb", + "CcbBbbc", + 12 + ], + [ + "AABbBa", + "bBAcbaaB", + 10 + ], + [ + "AABbCc", + "AccbaB", + 8 + ], + [ + "AABba", + "cBbAc", + 7 + ], + [ + "AABbaBa", + "BBaAbb", + 10 + ], + [ + "AABc", + "BccAAA", + 10 + ], + [ + "AABcABaaA", + "cbB", + 14 + ], + [ + "AABcAC", + "acabAC", + 7 + ], + [ + "AABcBbcb", + "baAACAbAB", + 11 + ], + [ + "AABcCB", + "ca", + 10 + ], + [ + "AABcaBC", + "AaAaab", + 8 + ], + [ + "AAC", + "CBabAaB", + 11 + ], + [ + "AAC", + "aBA", + 5 + ], + [ + "AAC", + "aCBCBbac", + 13 + ], + [ + "AAC", + "aCa", + 5 + ], + [ + "AAC", + "baaBAba", + 11 + ], + [ + "AAC", + "bbAbc", + 7 + ], + [ + "AACA", + "aaCB", + 4 + ], + [ + "AACA", + "ab", + 7 + ], + [ + "AACA", + "cc", + 7 + ], + [ + "AACAba", + "CBAAaAB", + 9 + ], + [ + "AACAba", + "b", + 10 + ], + [ + "AACAbbc", + "AbaCABCcB", + 8 + ], + [ + "AACBACbcB", + "b", + 16 + ], + [ + "AACBC", + "Abbc", + 6 + ], + [ + "AACBC", + "aaCcAb", + 8 + ], + [ + "AACBCA", + "A", + 10 + ], + [ + "AACBCcbaa", + "cbBca", + 12 + ], + [ + "AACBaB", + "AAcABBA", + 7 + ], + [ + "AACBc", + "aABCaACA", + 10 + ], + [ + "AACC", + "bB", + 8 + ], + [ + "AACCA", + "b", + 10 + ], + [ + "AACCAC", + "Ccab", + 8 + ], + [ + "AACCBBAac", + "abbabb", + 14 + ], + [ + "AACCCCbc", + "BBCCaB", + 11 + ], + [ + "AACCCc", + "bcCbaBACA", + 14 + ], + [ + "AACCaBcA", + "BaC", + 13 + ], + [ + "AACCaca", + "ccbaBBaB", + 13 + ], + [ + "AACCc", + "b", + 10 + ], + [ + "AACa", + "BAC", + 4 + ], + [ + "AACaAaBA", + "AbcbB", + 11 + ], + [ + "AACaac", + "C", + 10 + ], + [ + "AACacB", + "CcbCBaBb", + 11 + ], + [ + "AACb", + "AC", + 4 + ], + [ + "AACb", + "ac", + 6 + ], + [ + "AACbAC", + "BBCCBCa", + 10 + ], + [ + "AACbC", + "bb", + 8 + ], + [ + "AACbbcaa", + "bbaaBCBb", + 14 + ], + [ + "AACbc", + "AbcbbBcCB", + 11 + ], + [ + "AACbc", + "aCCB", + 6 + ], + [ + "AACbcAaAb", + "BABcaBBAA", + 12 + ], + [ + "AACbcb", + "cabBc", + 8 + ], + [ + "AACc", + "BbCC", + 5 + ], + [ + "AACc", + "bbb", + 8 + ], + [ + "AACcAABAC", + "CBAcBaABa", + 11 + ], + [ + "AACcAb", + "CBCbCACcb", + 11 + ], + [ + "AACcCAAc", + "AbAACbCC", + 11 + ], + [ + "AACcabbC", + "cAAccbAB", + 9 + ], + [ + "AACcbA", + "BCCCcaCc", + 12 + ], + [ + "AAa", + "ACCC", + 6 + ], + [ + "AAa", + "BcAC", + 6 + ], + [ + "AAa", + "CACcaAAAb", + 13 + ], + [ + "AAa", + "CAaCA", + 6 + ], + [ + "AAa", + "aCcBACb", + 11 + ], + [ + "AAa", + "abACAA", + 7 + ], + [ + "AAa", + "b", + 6 + ], + [ + "AAa", + "cAAaBA", + 6 + ], + [ + "AAa", + "cBaB", + 6 + ], + [ + "AAaA", + "ca", + 6 + ], + [ + "AAaACcb", + "ABCcb", + 6 + ], + [ + "AAaB", + "aCAC", + 6 + ], + [ + "AAaB", + "cbAb", + 6 + ], + [ + "AAaBA", + "bBAc", + 8 + ], + [ + "AAaBB", + "ABCCaCBb", + 9 + ], + [ + "AAaBa", + "AcB", + 6 + ], + [ + "AAaBaB", + "aCcb", + 9 + ], + [ + "AAaBacBaC", + "CacABc", + 12 + ], + [ + "AAaBbAb", + "cC", + 14 + ], + [ + "AAaBbcaa", + "caB", + 12 + ], + [ + "AAaC", + "aCbBcBCB", + 13 + ], + [ + "AAaCACAB", + "cBa", + 14 + ], + [ + "AAaCCaCaA", + "baACABCCA", + 10 + ], + [ + "AAaCCcbb", + "aa", + 13 + ], + [ + "AAaCaccb", + "AAA", + 11 + ], + [ + "AAaCbAAAc", + "babcbBccb", + 14 + ], + [ + "AAaCcB", + "aA", + 9 + ], + [ + "AAaa", + "Abcbb", + 8 + ], + [ + "AAaaA", + "ACaCAcaa", + 9 + ], + [ + "AAaaB", + "cAaaAB", + 4 + ], + [ + "AAaaBbaC", + "bbCaCBc", + 12 + ], + [ + "AAaaCBabC", + "bBb", + 14 + ], + [ + "AAaacacca", + "C", + 17 + ], + [ + "AAaaccbA", + "CB", + 14 + ], + [ + "AAabAbac", + "cbABacbbc", + 11 + ], + [ + "AAabBBaA", + "caCcAAB", + 13 + ], + [ + "AAabCA", + "CbACAA", + 9 + ], + [ + "AAabCbCA", + "ACb", + 10 + ], + [ + "AAabb", + "B", + 9 + ], + [ + "AAabc", + "cBc", + 7 + ], + [ + "AAacA", + "CBBcB", + 8 + ], + [ + "AAacA", + "Cc", + 8 + ], + [ + "AAacCBCBc", + "bAaacCc", + 9 + ], + [ + "AAacCaBa", + "a", + 14 + ], + [ + "AAacCbCCC", + "BaB", + 15 + ], + [ + "AAaccABAA", + "bBCb", + 16 + ], + [ + "AAb", + "AbB", + 3 + ], + [ + "AAb", + "B", + 5 + ], + [ + "AAb", + "aCBbBBa", + 11 + ], + [ + "AAb", + "bAAc", + 4 + ], + [ + "AAb", + "bABA", + 5 + ], + [ + "AAb", + "bBCbBbaCA", + 16 + ], + [ + "AAb", + "bbBBaB", + 10 + ], + [ + "AAb", + "bbCcAb", + 8 + ], + [ + "AAbA", + "Bbb", + 6 + ], + [ + "AAbAAaBCC", + "b", + 16 + ], + [ + "AAbABB", + "Ca", + 11 + ], + [ + "AAbAaBBcB", + "BABaCB", + 10 + ], + [ + "AAbBBb", + "a", + 11 + ], + [ + "AAbBCCb", + "bA", + 12 + ], + [ + "AAbBbBcC", + "C", + 14 + ], + [ + "AAbBbbBcc", + "aCA", + 16 + ], + [ + "AAbC", + "cBbBCBBb", + 12 + ], + [ + "AAbCbBcC", + "BaABcCaCc", + 11 + ], + [ + "AAbCcCbC", + "a", + 15 + ], + [ + "AAba", + "cBCabCC", + 11 + ], + [ + "AAba", + "cBcBCcaBc", + 15 + ], + [ + "AAbaCabC", + "Aa", + 12 + ], + [ + "AAbabb", + "cbBAca", + 10 + ], + [ + "AAbb", + "AcbaaAB", + 9 + ], + [ + "AAbb", + "bccb", + 6 + ], + [ + "AAbbAcAB", + "cbacaBBBA", + 14 + ], + [ + "AAbbBAaAC", + "bcbaabc", + 11 + ], + [ + "AAbbbB", + "bCa", + 10 + ], + [ + "AAbcBbA", + "aaccCbB", + 8 + ], + [ + "AAbcaBBBA", + "ABb", + 13 + ], + [ + "AAbcacaB", + "cAAAbBb", + 12 + ], + [ + "AAbcbacC", + "abbbAaCCa", + 10 + ], + [ + "AAc", + "ACAc", + 2 + ], + [ + "AAc", + "AbB", + 4 + ], + [ + "AAc", + "BAabA", + 7 + ], + [ + "AAc", + "aAbc", + 3 + ], + [ + "AAc", + "aaaaacAA", + 12 + ], + [ + "AAc", + "aab", + 4 + ], + [ + "AAc", + "c", + 4 + ], + [ + "AAcA", + "AAbAAA", + 6 + ], + [ + "AAcABCA", + "bBBAbab", + 11 + ], + [ + "AAcAC", + "cCAAa", + 8 + ], + [ + "AAcAac", + "cAcA", + 6 + ], + [ + "AAcAbBcB", + "AAAAB", + 8 + ], + [ + "AAcAccAb", + "Ccac", + 11 + ], + [ + "AAcBBBcCB", + "A", + 16 + ], + [ + "AAcBbA", + "Aa", + 9 + ], + [ + "AAcC", + "bCbcaCCa", + 12 + ], + [ + "AAcCabaB", + "cACAC", + 11 + ], + [ + "AAcaACCBA", + "abcBCca", + 11 + ], + [ + "AAcaCBAcB", + "cCaBCcC", + 11 + ], + [ + "AAcab", + "A", + 8 + ], + [ + "AAcab", + "AcaabCccc", + 12 + ], + [ + "AAcb", + "aCBCcCBcC", + 14 + ], + [ + "AAcbAccc", + "CcccbA", + 12 + ], + [ + "AAcbCCAcB", + "BbbCaACc", + 11 + ], + [ + "AAcbCca", + "a", + 12 + ], + [ + "AAcbc", + "caCcb", + 7 + ], + [ + "AAcc", + "CcaBbcC", + 10 + ], + [ + "AAccB", + "cCca", + 7 + ], + [ + "AAccb", + "aA", + 7 + ], + [ + "AAccccbAA", + "caAaa", + 14 + ], + [ + "AB", + "A", + 2 + ], + [ + "AB", + "AACca", + 8 + ], + [ + "AB", + "ABcAc", + 6 + ], + [ + "AB", + "ACCACCbC", + 13 + ], + [ + "AB", + "BAA", + 4 + ], + [ + "AB", + "BAbac", + 7 + ], + [ + "AB", + "BC", + 4 + ], + [ + "AB", + "BbaCAc", + 10 + ], + [ + "AB", + "Bbac", + 7 + ], + [ + "AB", + "BcA", + 6 + ], + [ + "AB", + "CAAacB", + 8 + ], + [ + "AB", + "CC", + 4 + ], + [ + "AB", + "CCaabBcb", + 13 + ], + [ + "AB", + "CCcB", + 6 + ], + [ + "AB", + "CbA", + 5 + ], + [ + "AB", + "aCAC", + 6 + ], + [ + "AB", + "bBA", + 4 + ], + [ + "AB", + "bCbB", + 6 + ], + [ + "AB", + "bCccbbb", + 13 + ], + [ + "AB", + "bbb", + 5 + ], + [ + "AB", + "bcAbAAA", + 11 + ], + [ + "AB", + "bcbC", + 7 + ], + [ + "AB", + "c", + 4 + ], + [ + "AB", + "cCabccbCB", + 15 + ], + [ + "AB", + "caCBB", + 7 + ], + [ + "AB", + "caaac", + 9 + ], + [ + "AB", + "cababCa", + 12 + ], + [ + "ABA", + "A", + 4 + ], + [ + "ABA", + "ACBcBa", + 7 + ], + [ + "ABA", + "AcAb", + 4 + ], + [ + "ABA", + "abbBaaC", + 10 + ], + [ + "ABA", + "c", + 6 + ], + [ + "ABA", + "caAaCCbc", + 13 + ], + [ + "ABAAB", + "cbB", + 7 + ], + [ + "ABAABacbC", + "Ba", + 14 + ], + [ + "ABAAaCAa", + "cABb", + 14 + ], + [ + "ABAAaaBb", + "BCACaB", + 8 + ], + [ + "ABAAabb", + "bAcABc", + 9 + ], + [ + "ABAAabbCC", + "cbcBc", + 15 + ], + [ + "ABAAbBCb", + "aCACb", + 9 + ], + [ + "ABAAc", + "AbCc", + 5 + ], + [ + "ABAAcC", + "A", + 10 + ], + [ + "ABABBCaBb", + "aAcBcc", + 12 + ], + [ + "ABABCAB", + "cbBBCaA", + 8 + ], + [ + "ABABaaCc", + "BBBBBAB", + 11 + ], + [ + "ABABbCCab", + "aAC", + 13 + ], + [ + "ABAC", + "abaAC", + 4 + ], + [ + "ABACAccCC", + "BBCBcbCAc", + 11 + ], + [ + "ABACCAACA", + "aAacA", + 11 + ], + [ + "ABACaa", + "BA", + 8 + ], + [ + "ABACb", + "b", + 8 + ], + [ + "ABACbaCcC", + "cCBBbCbC", + 12 + ], + [ + "ABAa", + "A", + 6 + ], + [ + "ABAaAbbc", + "ccaCBA", + 13 + ], + [ + "ABAaB", + "bb", + 8 + ], + [ + "ABAaCCAB", + "acba", + 12 + ], + [ + "ABAaaBCBB", + "BaCC", + 12 + ], + [ + "ABAacbAbA", + "ABAb", + 10 + ], + [ + "ABAb", + "AcA", + 4 + ], + [ + "ABAb", + "cCab", + 5 + ], + [ + "ABAbACCB", + "cBCB", + 10 + ], + [ + "ABAbBC", + "BBAacabC", + 9 + ], + [ + "ABAbCCb", + "BAA", + 10 + ], + [ + "ABAbaCBB", + "aaCbbbBB", + 9 + ], + [ + "ABAbaCcC", + "bac", + 10 + ], + [ + "ABAc", + "CBACCbBA", + 11 + ], + [ + "ABAcAcB", + "Ac", + 10 + ], + [ + "ABAca", + "aCcCaAbC", + 12 + ], + [ + "ABAcaBc", + "bCaabABAb", + 14 + ], + [ + "ABAcaac", + "BcA", + 9 + ], + [ + "ABAcabA", + "aa", + 11 + ], + [ + "ABAcb", + "cCa", + 9 + ], + [ + "ABB", + "acaccCcA", + 15 + ], + [ + "ABB", + "bAaAAC", + 10 + ], + [ + "ABB", + "bBbAA", + 7 + ], + [ + "ABB", + "bac", + 6 + ], + [ + "ABBAAaCc", + "CaCaCAaCc", + 9 + ], + [ + "ABBAAbb", + "acBbCba", + 9 + ], + [ + "ABBAAc", + "bBccabAcB", + 11 + ], + [ + "ABBAbbAA", + "abAaaa", + 10 + ], + [ + "ABBAcBaa", + "Ab", + 13 + ], + [ + "ABBAcbAc", + "abBccbA", + 6 + ], + [ + "ABBBAa", + "ccBbcBa", + 9 + ], + [ + "ABBBAbAcc", + "abCaCAbcc", + 10 + ], + [ + "ABBBB", + "cAaCBCbCb", + 12 + ], + [ + "ABBBCaB", + "BaAbBabBa", + 12 + ], + [ + "ABBCC", + "aBBbaBAab", + 13 + ], + [ + "ABBCCc", + "aAcAbB", + 11 + ], + [ + "ABBCCcab", + "AcBcbcbAc", + 10 + ], + [ + "ABBa", + "bA", + 6 + ], + [ + "ABBaACA", + "cbBcAB", + 9 + ], + [ + "ABBaACCcb", + "bbCCcCb", + 10 + ], + [ + "ABBaa", + "bcabCCC", + 12 + ], + [ + "ABBabAbAC", + "AbcbbAcCc", + 10 + ], + [ + "ABBaba", + "BCcbAaBCA", + 13 + ], + [ + "ABBacb", + "CAbcBAbBa", + 11 + ], + [ + "ABBb", + "Aabc", + 5 + ], + [ + "ABBb", + "aAcAb", + 6 + ], + [ + "ABBbBAbCA", + "CCBACAAb", + 14 + ], + [ + "ABBbCbb", + "bccbcAc", + 11 + ], + [ + "ABBbb", + "aAabbCbCC", + 11 + ], + [ + "ABBcBBC", + "bCaB", + 10 + ], + [ + "ABBcCCC", + "bABbaCCC", + 5 + ], + [ + "ABBcb", + "aCc", + 7 + ], + [ + "ABBcbcC", + "AACBbAC", + 8 + ], + [ + "ABBccBcAa", + "ABa", + 12 + ], + [ + "ABBccCBA", + "CCCACa", + 12 + ], + [ + "ABBccc", + "B", + 10 + ], + [ + "ABC", + "BAaACA", + 8 + ], + [ + "ABC", + "BCc", + 4 + ], + [ + "ABC", + "CAa", + 6 + ], + [ + "ABC", + "CBca", + 5 + ], + [ + "ABC", + "CbCbbCB", + 11 + ], + [ + "ABC", + "bacacB", + 10 + ], + [ + "ABC", + "c", + 5 + ], + [ + "ABCAB", + "bAaAc", + 8 + ], + [ + "ABCAC", + "BaCBaC", + 7 + ], + [ + "ABCAa", + "aABbb", + 8 + ], + [ + "ABCAbAacA", + "cbCAa", + 11 + ], + [ + "ABCBC", + "AB", + 6 + ], + [ + "ABCBa", + "CcAACBC", + 8 + ], + [ + "ABCBa", + "caBbccC", + 10 + ], + [ + "ABCCAa", + "A", + 10 + ], + [ + "ABCCC", + "CC", + 6 + ], + [ + "ABCCbcBc", + "AbCBcBB", + 6 + ], + [ + "ABCCcCBB", + "bbccAbBBc", + 11 + ], + [ + "ABCCccaB", + "aCcACCCa", + 10 + ], + [ + "ABCaBa", + "BBb", + 8 + ], + [ + "ABCaBa", + "bbAcAA", + 10 + ], + [ + "ABCaC", + "bcCcab", + 8 + ], + [ + "ABCaa", + "AbCcaAb", + 6 + ], + [ + "ABCab", + "b", + 8 + ], + [ + "ABCabB", + "AAc", + 9 + ], + [ + "ABCb", + "CBBBC", + 7 + ], + [ + "ABCb", + "aABCcBC", + 7 + ], + [ + "ABCbAA", + "Ba", + 9 + ], + [ + "ABCbBBbc", + "cabbbCbcB", + 11 + ], + [ + "ABCbC", + "cc", + 8 + ], + [ + "ABCbCaCCc", + "aABB", + 15 + ], + [ + "ABCbaaCbb", + "CBbBBABBB", + 12 + ], + [ + "ABCbaaac", + "aaCaCCCca", + 13 + ], + [ + "ABCbbA", + "BCaAa", + 7 + ], + [ + "ABCbcC", + "ccbBBa", + 11 + ], + [ + "ABCc", + "Aa", + 6 + ], + [ + "ABCcAabbB", + "cCCaBBc", + 11 + ], + [ + "ABCcBcbC", + "Bcbcc", + 8 + ], + [ + "ABCcb", + "CacBAb", + 9 + ], + [ + "ABCccaAcC", + "BaAcBbC", + 12 + ], + [ + "ABa", + "AaabCa", + 7 + ], + [ + "ABa", + "CaA", + 5 + ], + [ + "ABaABc", + "caC", + 9 + ], + [ + "ABaAC", + "Caca", + 8 + ], + [ + "ABaAb", + "bAaC", + 7 + ], + [ + "ABaB", + "c", + 8 + ], + [ + "ABaBa", + "aacCAc", + 10 + ], + [ + "ABaBb", + "acbaBCcb", + 8 + ], + [ + "ABaBccB", + "BacbBBBcb", + 11 + ], + [ + "ABaCAb", + "aba", + 8 + ], + [ + "ABaCCC", + "aCAaacbc", + 10 + ], + [ + "ABaCc", + "bB", + 8 + ], + [ + "ABaa", + "CCcCC", + 10 + ], + [ + "ABabAbb", + "BCAcB", + 9 + ], + [ + "ABabBC", + "acc", + 9 + ], + [ + "ABabBaAc", + "AbBCbaBBB", + 12 + ], + [ + "ABababAC", + "aabaaBAA", + 8 + ], + [ + "ABabb", + "bBb", + 6 + ], + [ + "ABabcBacC", + "aC", + 14 + ], + [ + "ABabcBcc", + "BAcB", + 9 + ], + [ + "ABacCac", + "bbaCBcbcB", + 11 + ], + [ + "ABacbAAab", + "bC", + 16 + ], + [ + "ABacbbaCC", + "CbCbcbBAA", + 13 + ], + [ + "ABb", + "AaAcB", + 7 + ], + [ + "ABb", + "B", + 4 + ], + [ + "ABb", + "BB", + 3 + ], + [ + "ABb", + "BBaCCAAA", + 14 + ], + [ + "ABb", + "bBBaA", + 7 + ], + [ + "ABb", + "baCaaBaa", + 13 + ], + [ + "ABbA", + "CaACAABa", + 12 + ], + [ + "ABbACAC", + "BAcBBaB", + 12 + ], + [ + "ABbACAaAa", + "Cca", + 14 + ], + [ + "ABbAaa", + "cbacaa", + 7 + ], + [ + "ABbAaaB", + "BBc", + 11 + ], + [ + "ABbAacbAC", + "bAbAaacaa", + 11 + ], + [ + "ABbAbA", + "aaAaB", + 9 + ], + [ + "ABbBAb", + "a", + 11 + ], + [ + "ABbBcCbcA", + "acaAacBAB", + 15 + ], + [ + "ABbCC", + "caACcc", + 9 + ], + [ + "ABbCaAbb", + "b", + 14 + ], + [ + "ABbCb", + "aABCBBca", + 10 + ], + [ + "ABbCbA", + "A", + 10 + ], + [ + "ABbCbA", + "AbCbB", + 4 + ], + [ + "ABbCbbBa", + "B", + 14 + ], + [ + "ABbCcB", + "AaCccab", + 8 + ], + [ + "ABbaACBCc", + "baBCbCbcB", + 11 + ], + [ + "ABbaabcCC", + "aaaacAAAA", + 15 + ], + [ + "ABbacAAA", + "CAAccb", + 13 + ], + [ + "ABbb", + "cAaC", + 8 + ], + [ + "ABbbA", + "BCcbb", + 8 + ], + [ + "ABbbC", + "ABBc", + 4 + ], + [ + "ABbbbB", + "BCabaCc", + 12 + ], + [ + "ABbc", + "bBcAAac", + 10 + ], + [ + "ABbcc", + "AbBABaaa", + 11 + ], + [ + "ABbccBA", + "cACaCcCC", + 11 + ], + [ + "ABc", + "a", + 5 + ], + [ + "ABc", + "aA", + 5 + ], + [ + "ABc", + "b", + 5 + ], + [ + "ABcA", + "CB", + 6 + ], + [ + "ABcAa", + "BcbAC", + 6 + ], + [ + "ABcAaB", + "ab", + 9 + ], + [ + "ABcAbAa", + "AcAABbb", + 9 + ], + [ + "ABcAc", + "c", + 8 + ], + [ + "ABcAcCAc", + "cAcBcCaC", + 8 + ], + [ + "ABcBBcCCB", + "BaAcBbC", + 12 + ], + [ + "ABcBbAb", + "aAbACcAca", + 13 + ], + [ + "ABcBcCCbB", + "cbAC", + 13 + ], + [ + "ABcC", + "Cabc", + 6 + ], + [ + "ABcC", + "c", + 6 + ], + [ + "ABcCAaCc", + "C", + 14 + ], + [ + "ABcCAbCba", + "CcBa", + 12 + ], + [ + "ABcCBb", + "CAb", + 8 + ], + [ + "ABcCCa", + "bCaca", + 7 + ], + [ + "ABcCCcBa", + "Cbc", + 12 + ], + [ + "ABcCbbBbC", + "b", + 16 + ], + [ + "ABcaBC", + "Bcc", + 7 + ], + [ + "ABcaBb", + "CB", + 9 + ], + [ + "ABcb", + "a", + 7 + ], + [ + "ABcbAcc", + "AbBa", + 9 + ], + [ + "ABcbBC", + "cCcAa", + 10 + ], + [ + "ABcbCacCb", + "ba", + 14 + ], + [ + "ABcc", + "bAAcbCa", + 9 + ], + [ + "ABccA", + "CA", + 7 + ], + [ + "ABcccb", + "CB", + 10 + ], + [ + "AC", + "A", + 2 + ], + [ + "AC", + "AAb", + 4 + ], + [ + "AC", + "AB", + 2 + ], + [ + "AC", + "ABBc", + 5 + ], + [ + "AC", + "ABaaaBc", + 11 + ], + [ + "AC", + "ACBaAbb", + 10 + ], + [ + "AC", + "AaBcBC", + 8 + ], + [ + "AC", + "AaCCCB", + 8 + ], + [ + "AC", + "AabB", + 6 + ], + [ + "AC", + "AacAaBc", + 11 + ], + [ + "AC", + "AbBCacbA", + 12 + ], + [ + "AC", + "AbbbcbACb", + 14 + ], + [ + "AC", + "B", + 4 + ], + [ + "AC", + "BBbA", + 8 + ], + [ + "AC", + "BCaa", + 6 + ], + [ + "AC", + "BbCaaA", + 10 + ], + [ + "AC", + "BcAab", + 8 + ], + [ + "AC", + "C", + 2 + ], + [ + "AC", + "CAcb", + 5 + ], + [ + "AC", + "Ca", + 4 + ], + [ + "AC", + "CabAB", + 8 + ], + [ + "AC", + "aABaABAB", + 14 + ], + [ + "AC", + "aAacbbcAC", + 14 + ], + [ + "AC", + "aBCaCBba", + 13 + ], + [ + "AC", + "aa", + 3 + ], + [ + "AC", + "aaaBBabAb", + 16 + ], + [ + "AC", + "baccAbcB", + 13 + ], + [ + "AC", + "c", + 3 + ], + [ + "AC", + "cACCaBA", + 10 + ], + [ + "AC", + "cCaaAacaA", + 15 + ], + [ + "AC", + "cbcbbcC", + 12 + ], + [ + "ACA", + "Aa", + 3 + ], + [ + "ACA", + "C", + 4 + ], + [ + "ACA", + "CbaaBc", + 11 + ], + [ + "ACA", + "aAABAAcb", + 12 + ], + [ + "ACA", + "cACCbaAaC", + 12 + ], + [ + "ACAA", + "AcaAAb", + 5 + ], + [ + "ACAABBaC", + "A", + 14 + ], + [ + "ACAABcA", + "bCBACacC", + 10 + ], + [ + "ACAAC", + "bB", + 10 + ], + [ + "ACAAC", + "cBaaCabaC", + 11 + ], + [ + "ACAAa", + "CAa", + 4 + ], + [ + "ACAAaCaA", + "AAacb", + 9 + ], + [ + "ACAAbcaAa", + "bba", + 14 + ], + [ + "ACABA", + "bAB", + 6 + ], + [ + "ACABA", + "c", + 9 + ], + [ + "ACABABA", + "CcC", + 12 + ], + [ + "ACABACaB", + "bcBAaAB", + 8 + ], + [ + "ACABbCaBc", + "cA", + 15 + ], + [ + "ACAC", + "aaBAA", + 7 + ], + [ + "ACACB", + "aaCcbaBC", + 11 + ], + [ + "ACACBB", + "cCb", + 8 + ], + [ + "ACACBbccA", + "BABbAc", + 10 + ], + [ + "ACACC", + "BaAA", + 8 + ], + [ + "ACACa", + "Bccc", + 8 + ], + [ + "ACACbB", + "aCaacAaC", + 11 + ], + [ + "ACACbab", + "cC", + 11 + ], + [ + "ACAaA", + "Aaabbc", + 9 + ], + [ + "ACAaB", + "caBBcB", + 9 + ], + [ + "ACAaBA", + "CAbCC", + 8 + ], + [ + "ACAaCBccb", + "c", + 16 + ], + [ + "ACAabbCAc", + "BB", + 16 + ], + [ + "ACAb", + "AaaCC", + 7 + ], + [ + "ACAbBCaCA", + "A", + 16 + ], + [ + "ACAbbaaBA", + "aacacABbc", + 15 + ], + [ + "ACAbcB", + "bcBCB", + 7 + ], + [ + "ACAc", + "CCbcaabA", + 12 + ], + [ + "ACAcBCc", + "AcaAbcb", + 8 + ], + [ + "ACAcaabA", + "CACbBC", + 10 + ], + [ + "ACB", + "ACbbaBb", + 8 + ], + [ + "ACB", + "aCbbc", + 6 + ], + [ + "ACB", + "baBacBAB", + 12 + ], + [ + "ACB", + "cabbCcBA", + 11 + ], + [ + "ACBA", + "CbCCCaCAc", + 14 + ], + [ + "ACBAC", + "CaABbbcBA", + 13 + ], + [ + "ACBACBB", + "cAABCbBC", + 9 + ], + [ + "ACBACCba", + "ACBCcCb", + 5 + ], + [ + "ACBAbCBc", + "bC", + 12 + ], + [ + "ACBAba", + "aAaCaC", + 10 + ], + [ + "ACBAcb", + "aCACc", + 6 + ], + [ + "ACBB", + "bAbb", + 6 + ], + [ + "ACBBAB", + "BbBCb", + 8 + ], + [ + "ACBBABBa", + "bbabA", + 11 + ], + [ + "ACBBBaA", + "bccbA", + 10 + ], + [ + "ACBBBaCA", + "bCCCB", + 12 + ], + [ + "ACBBcAccc", + "ab", + 16 + ], + [ + "ACBCCC", + "a", + 11 + ], + [ + "ACBCbaa", + "ACCAbCCb", + 10 + ], + [ + "ACBaA", + "BcBcBcA", + 9 + ], + [ + "ACBaBa", + "AaAa", + 6 + ], + [ + "ACBabaa", + "abcAbbb", + 10 + ], + [ + "ACBabbab", + "CAa", + 11 + ], + [ + "ACBac", + "BcbcCb", + 9 + ], + [ + "ACBb", + "bcCAca", + 10 + ], + [ + "ACBbCaaBB", + "Cc", + 15 + ], + [ + "ACBba", + "CcaAbbc", + 10 + ], + [ + "ACBbaAbAC", + "aCabbAC", + 7 + ], + [ + "ACBbcAcB", + "cb", + 13 + ], + [ + "ACBcAB", + "cb", + 9 + ], + [ + "ACBcaaAAb", + "ACBA", + 10 + ], + [ + "ACC", + "BcccCaAba", + 15 + ], + [ + "ACC", + "Ccb", + 5 + ], + [ + "ACC", + "aB", + 5 + ], + [ + "ACC", + "bBcABBbAC", + 14 + ], + [ + "ACC", + "cABA", + 6 + ], + [ + "ACC", + "caACC", + 4 + ], + [ + "ACCA", + "BaaBc", + 9 + ], + [ + "ACCA", + "BacAabAAa", + 14 + ], + [ + "ACCACABB", + "ABAAbBaBa", + 11 + ], + [ + "ACCAbB", + "CcbAacC", + 11 + ], + [ + "ACCAccAB", + "ACbCC", + 10 + ], + [ + "ACCBAAC", + "Ac", + 11 + ], + [ + "ACCBAaBC", + "a", + 14 + ], + [ + "ACCBB", + "BcCccabbA", + 13 + ], + [ + "ACCBBcac", + "CCB", + 10 + ], + [ + "ACCBCBC", + "AcaaCacba", + 11 + ], + [ + "ACCBac", + "aCACaCc", + 7 + ], + [ + "ACCBb", + "BaCac", + 8 + ], + [ + "ACCBbcbAC", + "AAaCaCBCC", + 12 + ], + [ + "ACCBcCBB", + "aBBABb", + 10 + ], + [ + "ACCBcaaCa", + "CBb", + 14 + ], + [ + "ACCBcc", + "bbAa", + 11 + ], + [ + "ACCCAaCcC", + "CBAc", + 12 + ], + [ + "ACCCBac", + "CcCBACBB", + 9 + ], + [ + "ACCCC", + "CACCACc", + 5 + ], + [ + "ACCCb", + "CbBaCcb", + 9 + ], + [ + "ACCCbaCAc", + "abACCC", + 11 + ], + [ + "ACCaAACa", + "C", + 14 + ], + [ + "ACCaACAa", + "a", + 14 + ], + [ + "ACCaB", + "A", + 8 + ], + [ + "ACCaCA", + "a", + 10 + ], + [ + "ACCaaAc", + "A", + 12 + ], + [ + "ACCac", + "a", + 8 + ], + [ + "ACCbA", + "aCCBa", + 3 + ], + [ + "ACCbB", + "BaAa", + 10 + ], + [ + "ACCbC", + "CcbaCC", + 7 + ], + [ + "ACCbCba", + "a", + 12 + ], + [ + "ACCbaBbb", + "aA", + 14 + ], + [ + "ACCbba", + "aaCBCbccB", + 11 + ], + [ + "ACCbbbC", + "BCbABAbaA", + 13 + ], + [ + "ACCbcBa", + "aCBaBcbC", + 9 + ], + [ + "ACCbcbccB", + "caAAbaCcb", + 13 + ], + [ + "ACCcAccCc", + "AccAb", + 11 + ], + [ + "ACCcBcB", + "AcBcAAca", + 9 + ], + [ + "ACCcC", + "a", + 9 + ], + [ + "ACCcaC", + "cCA", + 8 + ], + [ + "ACCcacC", + "BBaaAcAab", + 14 + ], + [ + "ACa", + "AcbCAbaB", + 10 + ], + [ + "ACa", + "Bca", + 3 + ], + [ + "ACa", + "ba", + 4 + ], + [ + "ACa", + "baAAaba", + 10 + ], + [ + "ACaA", + "A", + 6 + ], + [ + "ACaA", + "ABCAba", + 6 + ], + [ + "ACaA", + "acbCc", + 8 + ], + [ + "ACaA", + "cc", + 7 + ], + [ + "ACaAC", + "cABCBAc", + 7 + ], + [ + "ACaAcABa", + "cCAACC", + 10 + ], + [ + "ACaB", + "ABAbccB", + 9 + ], + [ + "ACaB", + "bAAAaAbAA", + 13 + ], + [ + "ACaBBBCB", + "AaAC", + 10 + ], + [ + "ACaBBaAa", + "AcaBcBbcB", + 9 + ], + [ + "ACaBCB", + "cc", + 10 + ], + [ + "ACaBCBb", + "b", + 12 + ], + [ + "ACaBacCc", + "bb", + 15 + ], + [ + "ACaBcb", + "BcCc", + 9 + ], + [ + "ACaCACc", + "c", + 12 + ], + [ + "ACaCBccBc", + "CcABCcBcb", + 9 + ], + [ + "ACaCCBA", + "AAcacC", + 8 + ], + [ + "ACaa", + "BAAc", + 7 + ], + [ + "ACaaBAbc", + "ACAccba", + 9 + ], + [ + "ACaabb", + "BCAb", + 7 + ], + [ + "ACaacBa", + "cBCBAc", + 11 + ], + [ + "ACabABBA", + "CAcCbB", + 10 + ], + [ + "ACabC", + "B", + 9 + ], + [ + "ACabac", + "BACcbCcbB", + 10 + ], + [ + "ACabbcA", + "aCacc", + 7 + ], + [ + "ACaccaa", + "AA", + 11 + ], + [ + "ACb", + "A", + 4 + ], + [ + "ACb", + "cBAab", + 6 + ], + [ + "ACb", + "ccbccbB", + 11 + ], + [ + "ACbA", + "AaBacA", + 7 + ], + [ + "ACbA", + "BaCCbA", + 5 + ], + [ + "ACbA", + "abACa", + 7 + ], + [ + "ACbACcbaB", + "ccc", + 14 + ], + [ + "ACbAbaCBC", + "acbaba", + 9 + ], + [ + "ACbB", + "aCACBAbb", + 9 + ], + [ + "ACbBA", + "CACB", + 6 + ], + [ + "ACbBCC", + "bcbCaAB", + 11 + ], + [ + "ACbBa", + "B", + 8 + ], + [ + "ACbBaCab", + "cbB", + 11 + ], + [ + "ACbCCbBb", + "aaca", + 14 + ], + [ + "ACbCaA", + "bAbC", + 8 + ], + [ + "ACbCb", + "c", + 9 + ], + [ + "ACbCc", + "ABc", + 5 + ], + [ + "ACbCcbA", + "accAAAaCc", + 15 + ], + [ + "ACba", + "acABAcbC", + 11 + ], + [ + "ACba", + "bCabba", + 6 + ], + [ + "ACbaAaA", + "BaaAbcC", + 12 + ], + [ + "ACbaAbB", + "AaBbbbb", + 8 + ], + [ + "ACbaAc", + "ABaBbCBcB", + 12 + ], + [ + "ACbaCAC", + "bBcaC", + 8 + ], + [ + "ACbaCaB", + "cbaA", + 8 + ], + [ + "ACbaaaB", + "CAcA", + 10 + ], + [ + "ACbabABB", + "BCBABBAc", + 11 + ], + [ + "ACbabcac", + "ABBA", + 11 + ], + [ + "ACbbBB", + "cAbbaC", + 8 + ], + [ + "ACbbBb", + "abAAbCab", + 10 + ], + [ + "ACbbCc", + "AccCbBAAB", + 11 + ], + [ + "ACbbca", + "cbABC", + 9 + ], + [ + "ACbbccB", + "b", + 12 + ], + [ + "ACbcBBc", + "CBacBbCbA", + 11 + ], + [ + "ACbcCba", + "abBBc", + 10 + ], + [ + "ACbcCccA", + "BBaA", + 13 + ], + [ + "ACc", + "AABbabcbb", + 14 + ], + [ + "ACc", + "ABbCcC", + 6 + ], + [ + "ACc", + "ABcBaB", + 8 + ], + [ + "ACc", + "a", + 5 + ], + [ + "ACc", + "b", + 6 + ], + [ + "ACc", + "baCBbbCbc", + 13 + ], + [ + "ACc", + "bcAcC", + 6 + ], + [ + "ACc", + "c", + 4 + ], + [ + "ACcA", + "CbcBBcbb", + 13 + ], + [ + "ACcA", + "aBBA", + 5 + ], + [ + "ACcAAb", + "ccAa", + 6 + ], + [ + "ACcABac", + "cA", + 10 + ], + [ + "ACcAc", + "baC", + 8 + ], + [ + "ACcBCBbbB", + "aA", + 17 + ], + [ + "ACcBa", + "ABBbBAbca", + 12 + ], + [ + "ACcBa", + "abbaca", + 9 + ], + [ + "ACcBba", + "baaAcAcA", + 12 + ], + [ + "ACcBbaa", + "CbCcCCBAC", + 12 + ], + [ + "ACcC", + "AcCABAC", + 8 + ], + [ + "ACcCACb", + "CABB", + 9 + ], + [ + "ACcCC", + "ccabBBC", + 11 + ], + [ + "ACcCa", + "Bcb", + 8 + ], + [ + "ACcCacAa", + "CbCba", + 10 + ], + [ + "ACcCc", + "bbBCC", + 7 + ], + [ + "ACca", + "cBBCBcbC", + 12 + ], + [ + "ACcaCAb", + "aaA", + 9 + ], + [ + "ACcaaAb", + "CaCAc", + 8 + ], + [ + "ACcabc", + "AAACb", + 8 + ], + [ + "ACcac", + "abBCBCc", + 9 + ], + [ + "ACcbB", + "caBaa", + 10 + ], + [ + "ACcbC", + "aCA", + 7 + ], + [ + "ACcbaBb", + "aCACCCAaA", + 12 + ], + [ + "ACcbbC", + "cacb", + 8 + ], + [ + "ACcbcCBB", + "A", + 14 + ], + [ + "ACcc", + "Cca", + 4 + ], + [ + "ACcca", + "accBbB", + 8 + ], + [ + "ACccabBC", + "Bb", + 14 + ], + [ + "ACccb", + "C", + 8 + ], + [ + "ACccbCccb", + "BbCacaA", + 14 + ], + [ + "ACccca", + "A", + 10 + ], + [ + "Aa", + "A", + 2 + ], + [ + "Aa", + "AAcac", + 6 + ], + [ + "Aa", + "ABBa", + 4 + ], + [ + "Aa", + "AbAabCcB", + 12 + ], + [ + "Aa", + "AbCCCCbcC", + 16 + ], + [ + "Aa", + "AbccAA", + 9 + ], + [ + "Aa", + "B", + 4 + ], + [ + "Aa", + "BA", + 3 + ], + [ + "Aa", + "BB", + 4 + ], + [ + "Aa", + "BBaccBAc", + 14 + ], + [ + "Aa", + "BCAaBb", + 8 + ], + [ + "Aa", + "BaBBAc", + 10 + ], + [ + "Aa", + "BaBcCaBc", + 13 + ], + [ + "Aa", + "BaCc", + 6 + ], + [ + "Aa", + "BabcCcAb", + 14 + ], + [ + "Aa", + "BbBB", + 8 + ], + [ + "Aa", + "C", + 4 + ], + [ + "Aa", + "CAabcaaAB", + 14 + ], + [ + "Aa", + "CAbbCbCB", + 14 + ], + [ + "Aa", + "CBBaBccb", + 14 + ], + [ + "Aa", + "CBCAccba", + 12 + ], + [ + "Aa", + "a", + 2 + ], + [ + "Aa", + "aAc", + 4 + ], + [ + "Aa", + "aacb", + 5 + ], + [ + "Aa", + "acAAacaB", + 12 + ], + [ + "Aa", + "acaA", + 5 + ], + [ + "Aa", + "acbc", + 7 + ], + [ + "Aa", + "b", + 4 + ], + [ + "Aa", + "bBA", + 5 + ], + [ + "Aa", + "bBABbc", + 10 + ], + [ + "Aa", + "baABcc", + 10 + ], + [ + "Aa", + "babbc", + 8 + ], + [ + "Aa", + "bbabBCac", + 13 + ], + [ + "Aa", + "cAAB", + 5 + ], + [ + "Aa", + "cC", + 4 + ], + [ + "Aa", + "caCAB", + 8 + ], + [ + "Aa", + "ccabB", + 8 + ], + [ + "AaA", + "Acbc", + 6 + ], + [ + "AaA", + "BBAcB", + 8 + ], + [ + "AaA", + "BaAbb", + 6 + ], + [ + "AaA", + "CAcBB", + 8 + ], + [ + "AaA", + "Cc", + 6 + ], + [ + "AaA", + "a", + 4 + ], + [ + "AaA", + "bAcaab", + 7 + ], + [ + "AaA", + "bCbCac", + 10 + ], + [ + "AaA", + "bCcaBAa", + 10 + ], + [ + "AaA", + "cAbaCAbB", + 10 + ], + [ + "AaAA", + "bcacBb", + 10 + ], + [ + "AaAABca", + "aACbAbaa", + 9 + ], + [ + "AaAAbA", + "CAbA", + 6 + ], + [ + "AaAAbBCcc", + "bbcAb", + 14 + ], + [ + "AaAAcbcbB", + "aAcCCBba", + 11 + ], + [ + "AaABbA", + "BBaACcACA", + 12 + ], + [ + "AaABc", + "cCcaBB", + 9 + ], + [ + "AaABcBAbb", + "BABAbaB", + 11 + ], + [ + "AaACCAb", + "C", + 12 + ], + [ + "AaACCaac", + "aabBbAbCA", + 13 + ], + [ + "AaACa", + "BBb", + 10 + ], + [ + "AaAaABB", + "CABcCCcCA", + 16 + ], + [ + "AaAaBbCc", + "B", + 14 + ], + [ + "AaAaa", + "cba", + 8 + ], + [ + "AaAabb", + "CACAA", + 9 + ], + [ + "AaAaccCB", + "bAaacBbaA", + 12 + ], + [ + "AaAb", + "cABAcb", + 6 + ], + [ + "AaAbAaAb", + "a", + 14 + ], + [ + "AaAbAbbB", + "aA", + 12 + ], + [ + "AaAbBba", + "CCBac", + 12 + ], + [ + "AaAbb", + "BbaB", + 8 + ], + [ + "AaAbbc", + "cAAcCC", + 8 + ], + [ + "AaAbc", + "a", + 8 + ], + [ + "AaAc", + "aAaCA", + 6 + ], + [ + "AaAcA", + "BCAAAba", + 8 + ], + [ + "AaAccaBbc", + "baAcAACaa", + 11 + ], + [ + "AaB", + "AbbAbb", + 8 + ], + [ + "AaB", + "Bca", + 6 + ], + [ + "AaB", + "bbaAb", + 7 + ], + [ + "AaB", + "bcABBBCc", + 12 + ], + [ + "AaB", + "caAb", + 5 + ], + [ + "AaBA", + "cBAB", + 6 + ], + [ + "AaBACC", + "BCAAbB", + 10 + ], + [ + "AaBACaBA", + "cAc", + 13 + ], + [ + "AaBAa", + "c", + 10 + ], + [ + "AaBAc", + "CcACba", + 10 + ], + [ + "AaBAcBcaa", + "cb", + 15 + ], + [ + "AaBBAC", + "ACAca", + 9 + ], + [ + "AaBBAcbcc", + "CbCcBb", + 14 + ], + [ + "AaBBbcA", + "A", + 12 + ], + [ + "AaBCcbCB", + "CCcAb", + 11 + ], + [ + "AaBa", + "abA", + 4 + ], + [ + "AaBa", + "bbbCabA", + 10 + ], + [ + "AaBaaaCBa", + "A", + 16 + ], + [ + "AaBabBCb", + "aBac", + 9 + ], + [ + "AaBbB", + "bBaa", + 8 + ], + [ + "AaBba", + "ab", + 6 + ], + [ + "AaBbba", + "caAbBAa", + 7 + ], + [ + "AaBbbaac", + "Cbcca", + 12 + ], + [ + "AaBbbbA", + "AabcBAa", + 7 + ], + [ + "AaBc", + "bAaaBaCCB", + 11 + ], + [ + "AaBcA", + "aCbCbB", + 9 + ], + [ + "AaBcAbBC", + "CBCACaBBA", + 12 + ], + [ + "AaBccbA", + "BBcaaccb", + 10 + ], + [ + "AaC", + "AACcabcAa", + 13 + ], + [ + "AaC", + "ABAaabA", + 10 + ], + [ + "AaC", + "Acc", + 3 + ], + [ + "AaC", + "aCCB", + 5 + ], + [ + "AaC", + "bbbbbbAA", + 15 + ], + [ + "AaCA", + "CCc", + 6 + ], + [ + "AaCAAAcac", + "ABB", + 16 + ], + [ + "AaCAAbaa", + "CCbABc", + 11 + ], + [ + "AaCACCa", + "BCcBACc", + 10 + ], + [ + "AaCACCbcc", + "CAacc", + 10 + ], + [ + "AaCAcAcB", + "bbA", + 14 + ], + [ + "AaCB", + "BbBC", + 8 + ], + [ + "AaCB", + "bCCbBAA", + 10 + ], + [ + "AaCBa", + "ACAbC", + 7 + ], + [ + "AaCBaC", + "Ba", + 8 + ], + [ + "AaCBaaAAC", + "CaBc", + 13 + ], + [ + "AaCBbBBa", + "CBbAcCBb", + 12 + ], + [ + "AaCCAAC", + "ACaBb", + 9 + ], + [ + "AaCCAbcBB", + "BCaab", + 13 + ], + [ + "AaCCCB", + "AaaAA", + 8 + ], + [ + "AaCCCBB", + "bB", + 11 + ], + [ + "AaCCcbB", + "BCcaCcB", + 9 + ], + [ + "AaCCcc", + "cbc", + 9 + ], + [ + "AaCaAAa", + "ccccBbcaC", + 15 + ], + [ + "AaCaCccb", + "aCB", + 11 + ], + [ + "AaCaaaA", + "a", + 12 + ], + [ + "AaCaac", + "CBabAA", + 10 + ], + [ + "AaCac", + "AbaBC", + 7 + ], + [ + "AaCbbbBaB", + "ccC", + 16 + ], + [ + "AaCbcCb", + "ccAAaB", + 12 + ], + [ + "AaCc", + "a", + 6 + ], + [ + "AaCcABAa", + "B", + 14 + ], + [ + "AaCcAbC", + "Bb", + 12 + ], + [ + "AaCcBBcc", + "cBb", + 11 + ], + [ + "AaCcaCBaA", + "ABca", + 12 + ], + [ + "AaCcab", + "bBcB", + 9 + ], + [ + "AaCcacA", + "BBBAcbC", + 13 + ], + [ + "AaCcbBbCa", + "BBBAaabCb", + 14 + ], + [ + "AaCcc", + "abcBAb", + 10 + ], + [ + "AaCccBBCb", + "cB", + 14 + ], + [ + "AaCccbC", + "baaaaAb", + 11 + ], + [ + "Aaa", + "BaAA", + 5 + ], + [ + "Aaa", + "CbabcBBB", + 14 + ], + [ + "Aaa", + "aAa", + 2 + ], + [ + "Aaa", + "aBB", + 5 + ], + [ + "Aaa", + "bAAbBaBcc", + 13 + ], + [ + "Aaa", + "ca", + 4 + ], + [ + "AaaA", + "aBabbB", + 9 + ], + [ + "AaaA", + "baCb", + 6 + ], + [ + "AaaAAC", + "a", + 10 + ], + [ + "AaaAAaC", + "b", + 14 + ], + [ + "AaaACAcbA", + "CBAcAC", + 12 + ], + [ + "AaaACa", + "BABcccC", + 11 + ], + [ + "AaaAbBAab", + "bacccCc", + 16 + ], + [ + "AaaAcBCB", + "Bbbb", + 14 + ], + [ + "AaaAcb", + "AcabAA", + 8 + ], + [ + "AaaB", + "aaCAC", + 6 + ], + [ + "AaaBABa", + "bBaC", + 11 + ], + [ + "AaaBCaCC", + "c", + 15 + ], + [ + "AaaBa", + "CBCBc", + 8 + ], + [ + "AaaC", + "aaAc", + 3 + ], + [ + "AaaC", + "b", + 8 + ], + [ + "AaaC", + "caaBCAABc", + 12 + ], + [ + "AaaCB", + "ABcbBCCA", + 12 + ], + [ + "AaaCcbcc", + "B", + 15 + ], + [ + "Aaaa", + "abCBCBa", + 11 + ], + [ + "AaaaA", + "CccAB", + 9 + ], + [ + "AaaaBcb", + "BCabBBBC", + 11 + ], + [ + "AaaaCCC", + "BBcaacaCB", + 11 + ], + [ + "AaaacbC", + "CcAcBACcb", + 13 + ], + [ + "AaabA", + "cB", + 9 + ], + [ + "AaabACBca", + "bAc", + 12 + ], + [ + "AaabCAC", + "bCaacCbB", + 10 + ], + [ + "Aaaba", + "BbccCaa", + 12 + ], + [ + "AaabaBba", + "aBaB", + 9 + ], + [ + "Aaababb", + "BcbBCcc", + 13 + ], + [ + "AaabcBb", + "abab", + 8 + ], + [ + "Aaac", + "BAbaab", + 6 + ], + [ + "AaacACBc", + "ACbbCaABA", + 12 + ], + [ + "AaaccCBcb", + "CBabaCACb", + 11 + ], + [ + "AaacccCc", + "c", + 14 + ], + [ + "Aab", + "BcBaaCBC", + 12 + ], + [ + "Aab", + "CBBaACcBA", + 15 + ], + [ + "Aab", + "a", + 4 + ], + [ + "AabA", + "acCbacA", + 9 + ], + [ + "AabAAcBBB", + "aa", + 15 + ], + [ + "AabAbBbcB", + "AcCcA", + 14 + ], + [ + "AabAccB", + "AcabBCb", + 8 + ], + [ + "AabBABc", + "AAabbCcCc", + 9 + ], + [ + "AabBCAaC", + "aBcCbc", + 10 + ], + [ + "AabBCC", + "A", + 10 + ], + [ + "AabBaBcBB", + "cbcc", + 14 + ], + [ + "AabBacAaa", + "aAc", + 13 + ], + [ + "AabBba", + "bcabb", + 8 + ], + [ + "AabBbc", + "CcAaA", + 12 + ], + [ + "AabBcBca", + "Ca", + 13 + ], + [ + "AabBcbc", + "ac", + 10 + ], + [ + "AabCbA", + "B", + 11 + ], + [ + "AabCbC", + "ccBbc", + 8 + ], + [ + "Aaba", + "BBaa", + 6 + ], + [ + "AabaACCC", + "aaBBcccCa", + 10 + ], + [ + "AabaCCccc", + "BaB", + 15 + ], + [ + "AabbA", + "AB", + 7 + ], + [ + "AabbABCBb", + "aBB", + 12 + ], + [ + "AabbB", + "AA", + 7 + ], + [ + "AabbB", + "bCCC", + 10 + ], + [ + "AabbbbbC", + "bBbBaB", + 10 + ], + [ + "AabbcCACc", + "AAa", + 14 + ], + [ + "Aabc", + "bBCbc", + 6 + ], + [ + "Aabc", + "bbA", + 6 + ], + [ + "AabcAAbCc", + "Aa", + 14 + ], + [ + "AabcBBb", + "bAbAcCBB", + 8 + ], + [ + "AabcBb", + "bb", + 8 + ], + [ + "AabcC", + "BbbBcbbC", + 10 + ], + [ + "AabcbCa", + "CB", + 12 + ], + [ + "Aac", + "Bccc", + 6 + ], + [ + "Aac", + "CBABCbaA", + 12 + ], + [ + "Aac", + "Cb", + 6 + ], + [ + "Aac", + "a", + 4 + ], + [ + "Aac", + "aBbCCaaa", + 13 + ], + [ + "Aac", + "baBAcA", + 8 + ], + [ + "Aac", + "c", + 4 + ], + [ + "Aac", + "caAABac", + 8 + ], + [ + "AacA", + "ACcBA", + 4 + ], + [ + "AacA", + "BaaAccBcA", + 11 + ], + [ + "AacAABbaa", + "a", + 16 + ], + [ + "AacABAB", + "CCc", + 12 + ], + [ + "AacAcbbC", + "cbCa", + 12 + ], + [ + "AacBBCc", + "BcBAA", + 10 + ], + [ + "AacBaA", + "AAa", + 7 + ], + [ + "AacBbaCBB", + "CcbC", + 12 + ], + [ + "AacBbcccc", + "CbACCaBab", + 18 + ], + [ + "AacC", + "BcBcAbb", + 12 + ], + [ + "AacCaBcaB", + "CAAb", + 13 + ], + [ + "AacCacC", + "CaABC", + 9 + ], + [ + "AacCcCcAC", + "CCBBabBA", + 16 + ], + [ + "AacCcc", + "Aab", + 8 + ], + [ + "AacaaCc", + "bAaA", + 10 + ], + [ + "AacacB", + "aaBBB", + 7 + ], + [ + "AacacBC", + "CBBcAcba", + 10 + ], + [ + "AacacBb", + "AAabbcaC", + 10 + ], + [ + "Aacb", + "c", + 6 + ], + [ + "AacbAAA", + "BbcBaCCCb", + 14 + ], + [ + "Aacbaa", + "aCBbbCaAc", + 12 + ], + [ + "Aacc", + "ACAA", + 6 + ], + [ + "Aacc", + "CBAcB", + 7 + ], + [ + "AaccAB", + "baAcAcbcc", + 11 + ], + [ + "AaccABc", + "bB", + 12 + ], + [ + "AaccAaAb", + "acb", + 10 + ], + [ + "AaccB", + "ac", + 6 + ], + [ + "AaccBcc", + "BC", + 11 + ], + [ + "AaccC", + "bAbacBAa", + 10 + ], + [ + "AaccaAc", + "Bc", + 12 + ], + [ + "AaccaBa", + "B", + 12 + ], + [ + "AaccaCcBb", + "bABCca", + 13 + ], + [ + "Aaccac", + "c", + 10 + ], + [ + "AacccAa", + "AC", + 11 + ], + [ + "AacccAcC", + "ab", + 14 + ], + [ + "AacccBBcC", + "Bb", + 15 + ], + [ + "Ab", + "A", + 2 + ], + [ + "Ab", + "AA", + 2 + ], + [ + "Ab", + "AaabCAAA", + 12 + ], + [ + "Ab", + "AbACAaCAA", + 14 + ], + [ + "Ab", + "AbCCAAACc", + 14 + ], + [ + "Ab", + "AbCbAa", + 8 + ], + [ + "Ab", + "Ac", + 2 + ], + [ + "Ab", + "AcaABbc", + 10 + ], + [ + "Ab", + "BAcCa", + 8 + ], + [ + "Ab", + "BBc", + 5 + ], + [ + "Ab", + "BbcAcCCaa", + 16 + ], + [ + "Ab", + "CABa", + 5 + ], + [ + "Ab", + "CAaB", + 5 + ], + [ + "Ab", + "CCBcAbbc", + 12 + ], + [ + "Ab", + "CaBc", + 6 + ], + [ + "Ab", + "CbBCAbaBc", + 14 + ], + [ + "Ab", + "aCAccA", + 10 + ], + [ + "Ab", + "aab", + 3 + ], + [ + "Ab", + "acaCBAa", + 12 + ], + [ + "Ab", + "bA", + 4 + ], + [ + "Ab", + "bCBc", + 7 + ], + [ + "Ab", + "c", + 4 + ], + [ + "Ab", + "cBBB", + 7 + ], + [ + "Ab", + "cC", + 4 + ], + [ + "Ab", + "cCAaBbbBC", + 14 + ], + [ + "Ab", + "cCaAcc", + 10 + ], + [ + "Ab", + "caA", + 5 + ], + [ + "Ab", + "caCacCcBC", + 16 + ], + [ + "Ab", + "cbcacAC", + 12 + ], + [ + "Ab", + "ccAbB", + 6 + ], + [ + "Ab", + "ccb", + 4 + ], + [ + "AbA", + "BCBAaC", + 9 + ], + [ + "AbA", + "BbBAaA", + 8 + ], + [ + "AbA", + "CcBa", + 6 + ], + [ + "AbA", + "aAC", + 5 + ], + [ + "AbA", + "b", + 4 + ], + [ + "AbA", + "caABB", + 7 + ], + [ + "AbA", + "ccc", + 6 + ], + [ + "AbAA", + "CBba", + 6 + ], + [ + "AbAAC", + "BAAC", + 3 + ], + [ + "AbAAC", + "bbab", + 7 + ], + [ + "AbAACaAb", + "C", + 14 + ], + [ + "AbAACbbBB", + "BCbaa", + 13 + ], + [ + "AbAAbC", + "caCaAAAbA", + 11 + ], + [ + "AbAAcbBa", + "BabBBCa", + 11 + ], + [ + "AbAB", + "Ab", + 4 + ], + [ + "AbAB", + "Bcb", + 6 + ], + [ + "AbAB", + "ac", + 7 + ], + [ + "AbABCa", + "cC", + 10 + ], + [ + "AbABa", + "BAaaCB", + 9 + ], + [ + "AbACABc", + "aBCACA", + 8 + ], + [ + "AbACBCA", + "aBB", + 10 + ], + [ + "AbACaa", + "AcAba", + 6 + ], + [ + "AbACbA", + "A", + 10 + ], + [ + "AbACbAA", + "aACA", + 7 + ], + [ + "AbACccccb", + "cCbbCBA", + 15 + ], + [ + "AbAaABB", + "BcaaA", + 9 + ], + [ + "AbAaAb", + "CB", + 11 + ], + [ + "AbAaC", + "AacbbACba", + 11 + ], + [ + "AbAaCAab", + "CabaacCaA", + 9 + ], + [ + "AbAaaa", + "AaC", + 8 + ], + [ + "AbAacaaac", + "abACABAc", + 8 + ], + [ + "AbAb", + "bbccBB", + 9 + ], + [ + "AbAbCba", + "BCbA", + 8 + ], + [ + "AbAbabac", + "bc", + 12 + ], + [ + "AbAbbBaab", + "bbabb", + 10 + ], + [ + "AbAc", + "BcbBCbC", + 11 + ], + [ + "AbAcACAa", + "cBcBBA", + 11 + ], + [ + "AbAcB", + "c", + 8 + ], + [ + "AbAcbCbca", + "AcBaaB", + 13 + ], + [ + "AbAccAbBc", + "aACcAACbA", + 11 + ], + [ + "AbAccBCa", + "BACCAaA", + 10 + ], + [ + "AbB", + "AABC", + 4 + ], + [ + "AbB", + "AbCbCCc", + 9 + ], + [ + "AbB", + "BcaAbAAAb", + 13 + ], + [ + "AbB", + "bBBA", + 5 + ], + [ + "AbB", + "cAaaaB", + 8 + ], + [ + "AbB", + "cbbABB", + 7 + ], + [ + "AbBAcCAC", + "CAAbcCC", + 9 + ], + [ + "AbBB", + "AAAAC", + 8 + ], + [ + "AbBBabc", + "Bcb", + 10 + ], + [ + "AbBBbCaA", + "AaCccAAA", + 11 + ], + [ + "AbBBcaAaa", + "bcbBbcCb", + 13 + ], + [ + "AbBCAacC", + "c", + 14 + ], + [ + "AbBCAcaa", + "aa", + 12 + ], + [ + "AbBCBbA", + "abbcBb", + 5 + ], + [ + "AbBaABC", + "AabAAbc", + 6 + ], + [ + "AbBaBB", + "AAaAca", + 9 + ], + [ + "AbBaCC", + "CAb", + 10 + ], + [ + "AbBaaAb", + "ACcBcca", + 11 + ], + [ + "AbBabBa", + "bccBAbb", + 10 + ], + [ + "AbBb", + "A", + 6 + ], + [ + "AbBb", + "BbaAB", + 7 + ], + [ + "AbBbA", + "babCBABbb", + 11 + ], + [ + "AbBbAABc", + "AbAa", + 9 + ], + [ + "AbBbCb", + "bcAACCcac", + 15 + ], + [ + "AbBbb", + "aCAC", + 9 + ], + [ + "AbBbbacbC", + "CcbccAb", + 14 + ], + [ + "AbBbcb", + "Ab", + 8 + ], + [ + "AbBbcbabC", + "Ba", + 14 + ], + [ + "AbBcBaaCc", + "BbcAB", + 13 + ], + [ + "AbBcaaCCA", + "aba", + 13 + ], + [ + "AbBcb", + "BAaAcb", + 6 + ], + [ + "AbBcc", + "AaccBc", + 6 + ], + [ + "AbBcccB", + "cB", + 10 + ], + [ + "AbC", + "BccBcC", + 9 + ], + [ + "AbC", + "C", + 4 + ], + [ + "AbCAA", + "CCcCcacBa", + 14 + ], + [ + "AbCABa", + "ACBC", + 6 + ], + [ + "AbCACa", + "BcaBacAA", + 12 + ], + [ + "AbCACcBbB", + "C", + 16 + ], + [ + "AbCAc", + "BbCbcBCAb", + 12 + ], + [ + "AbCB", + "Caa", + 8 + ], + [ + "AbCB", + "acbAc", + 7 + ], + [ + "AbCB", + "caaaba", + 10 + ], + [ + "AbCBbB", + "BacABACaB", + 13 + ], + [ + "AbCBbbC", + "cACb", + 10 + ], + [ + "AbCCcAbc", + "abB", + 12 + ], + [ + "AbCCca", + "C", + 10 + ], + [ + "AbCCcacba", + "aaAaabcb", + 13 + ], + [ + "AbCa", + "CcAaCAaA", + 10 + ], + [ + "AbCa", + "aBcccBBa", + 11 + ], + [ + "AbCaA", + "bBbAB", + 8 + ], + [ + "AbCaAAbab", + "BCbCcb", + 13 + ], + [ + "AbCaC", + "AbABC", + 4 + ], + [ + "AbCaabBCB", + "Cb", + 14 + ], + [ + "AbCabbc", + "BcCaB", + 9 + ], + [ + "AbCacAacb", + "aaAAAAC", + 12 + ], + [ + "AbCb", + "A", + 6 + ], + [ + "AbCb", + "BbaBcaCb", + 10 + ], + [ + "AbCbC", + "Cc", + 7 + ], + [ + "AbCbaB", + "aCac", + 7 + ], + [ + "AbCc", + "bAaCac", + 6 + ], + [ + "AbCcBBACC", + "cACC", + 10 + ], + [ + "AbCcbaBCA", + "cccCAbbCA", + 11 + ], + [ + "Aba", + "ACA", + 3 + ], + [ + "Aba", + "C", + 6 + ], + [ + "Aba", + "aB", + 4 + ], + [ + "Aba", + "bccccA", + 11 + ], + [ + "Aba", + "cabbcC", + 9 + ], + [ + "AbaAACBCb", + "CACabC", + 13 + ], + [ + "AbaAabca", + "CBCBCA", + 12 + ], + [ + "AbaAb", + "cb", + 8 + ], + [ + "AbaB", + "aCaB", + 3 + ], + [ + "AbaBAaCbC", + "cbbacCbA", + 10 + ], + [ + "AbaBAbaB", + "cbaC", + 12 + ], + [ + "AbaBBcbAA", + "bCaaC", + 14 + ], + [ + "AbaBCa", + "B", + 10 + ], + [ + "AbaBCbaB", + "acBcb", + 10 + ], + [ + "AbaBaca", + "acAAABBB", + 13 + ], + [ + "AbaBcCba", + "accBCABAB", + 12 + ], + [ + "AbaC", + "BAAb", + 7 + ], + [ + "AbaC", + "aA", + 6 + ], + [ + "AbaCb", + "B", + 9 + ], + [ + "AbaCbBc", + "ACBAaCAcA", + 11 + ], + [ + "Abaa", + "aAcBb", + 8 + ], + [ + "Abaa", + "cbbAaabCc", + 12 + ], + [ + "AbaaAbab", + "CCaaBc", + 11 + ], + [ + "AbaaAc", + "bAba", + 8 + ], + [ + "AbaaabCBb", + "aa", + 14 + ], + [ + "Abab", + "bbbBb", + 6 + ], + [ + "Abab", + "cab", + 4 + ], + [ + "AbabBBb", + "CaAAc", + 12 + ], + [ + "AbabCC", + "CACcAabA", + 12 + ], + [ + "AbabcCbb", + "AbcCcbB", + 7 + ], + [ + "AbacAa", + "bCAAabcCa", + 10 + ], + [ + "AbacB", + "CBaCBAcBa", + 11 + ], + [ + "AbacBCc", + "B", + 12 + ], + [ + "AbacBbBCC", + "bC", + 14 + ], + [ + "AbacaaCB", + "B", + 14 + ], + [ + "AbacaaaBC", + "AacAa", + 9 + ], + [ + "Abacb", + "AcccbAb", + 8 + ], + [ + "Abb", + "Aba", + 2 + ], + [ + "Abb", + "Ac", + 4 + ], + [ + "Abb", + "BCcba", + 8 + ], + [ + "AbbA", + "BCb", + 6 + ], + [ + "AbbABab", + "baacCBb", + 11 + ], + [ + "AbbACbab", + "ccAcA", + 12 + ], + [ + "AbbAcA", + "CabbA", + 7 + ], + [ + "AbbB", + "b", + 6 + ], + [ + "AbbBbCbAC", + "bCCaBA", + 13 + ], + [ + "AbbBbb", + "BBcAbaAbB", + 11 + ], + [ + "AbbBcaaBa", + "aAAAaCAba", + 13 + ], + [ + "AbbCACaB", + "CbBBAbcB", + 9 + ], + [ + "AbbCB", + "AAC", + 6 + ], + [ + "AbbCBbCA", + "aAa", + 14 + ], + [ + "AbbCCA", + "bBBcbaAcC", + 13 + ], + [ + "AbbCCaBCB", + "AabbCB", + 9 + ], + [ + "AbbCCcAAb", + "ABCbbBCC", + 13 + ], + [ + "AbbCaCCa", + "B", + 15 + ], + [ + "AbbCbBC", + "Cc", + 11 + ], + [ + "AbbCcA", + "BaaCcBac", + 11 + ], + [ + "AbbaBacBC", + "BaCaCBcC", + 10 + ], + [ + "Abbaa", + "aCbBbc", + 8 + ], + [ + "Abbb", + "bBab", + 5 + ], + [ + "Abbbba", + "BbbaA", + 6 + ], + [ + "AbbcBbA", + "cCbCcaC", + 11 + ], + [ + "Abc", + "CBAaABCCc", + 13 + ], + [ + "Abc", + "Cab", + 5 + ], + [ + "Abc", + "ba", + 4 + ], + [ + "Abc", + "cCBCa", + 8 + ], + [ + "AbcAAAa", + "CBcBBAabc", + 11 + ], + [ + "AbcABaa", + "cCcBCb", + 10 + ], + [ + "AbcAcA", + "B", + 11 + ], + [ + "AbcB", + "AbaCBBaA", + 9 + ], + [ + "AbcBAA", + "BAAb", + 8 + ], + [ + "AbcBBaBB", + "CCBACAA", + 13 + ], + [ + "AbcBCcAA", + "abbABCcCa", + 8 + ], + [ + "AbcCACAbB", + "aBcCb", + 10 + ], + [ + "AbcCAacab", + "a", + 16 + ], + [ + "AbcCa", + "cBAaab", + 9 + ], + [ + "AbcCbbc", + "ACccaBbAB", + 10 + ], + [ + "AbcaA", + "cac", + 6 + ], + [ + "AbcaBABac", + "aA", + 14 + ], + [ + "AbcaBbBcA", + "CBbA", + 11 + ], + [ + "AbcaCAAAB", + "ac", + 15 + ], + [ + "AbcacabA", + "ABbaAC", + 10 + ], + [ + "Abcb", + "AbCCcbb", + 6 + ], + [ + "AbcbA", + "b", + 8 + ], + [ + "AbcbABc", + "bCBCabbBb", + 12 + ], + [ + "AbcbB", + "A", + 8 + ], + [ + "AbcbbC", + "bABbBAa", + 10 + ], + [ + "Abcc", + "bAABaA", + 9 + ], + [ + "Abcc", + "cAABAAa", + 11 + ], + [ + "AbccB", + "cA", + 8 + ], + [ + "Abccc", + "bba", + 8 + ], + [ + "Ac", + "ACbAa", + 7 + ], + [ + "Ac", + "AbB", + 4 + ], + [ + "Ac", + "BCB", + 5 + ], + [ + "Ac", + "BCacCBaBb", + 15 + ], + [ + "Ac", + "BaaCB", + 8 + ], + [ + "Ac", + "BacBbABCa", + 15 + ], + [ + "Ac", + "Bacc", + 5 + ], + [ + "Ac", + "BbaBaACcC", + 14 + ], + [ + "Ac", + "BccaAa", + 10 + ], + [ + "Ac", + "CA", + 4 + ], + [ + "Ac", + "CABacA", + 8 + ], + [ + "Ac", + "CABbbCA", + 11 + ], + [ + "Ac", + "CAa", + 4 + ], + [ + "Ac", + "CBCaAcBaB", + 14 + ], + [ + "Ac", + "CCA", + 5 + ], + [ + "Ac", + "CCcbBBc", + 12 + ], + [ + "Ac", + "CbBBBBbBA", + 18 + ], + [ + "Ac", + "Cbba", + 8 + ], + [ + "Ac", + "aCaa", + 6 + ], + [ + "Ac", + "aCbca", + 7 + ], + [ + "Ac", + "aaBC", + 6 + ], + [ + "Ac", + "aaCAa", + 8 + ], + [ + "Ac", + "aaaA", + 7 + ], + [ + "Ac", + "aabca", + 7 + ], + [ + "Ac", + "abcAAaB", + 11 + ], + [ + "Ac", + "acaBBbaAC", + 15 + ], + [ + "Ac", + "bAaa", + 6 + ], + [ + "Ac", + "bCCCCC", + 11 + ], + [ + "Ac", + "baAcB", + 6 + ], + [ + "Ac", + "bc", + 2 + ], + [ + "Ac", + "cB", + 4 + ], + [ + "Ac", + "cBaaaAAAb", + 16 + ], + [ + "Ac", + "cC", + 3 + ], + [ + "Ac", + "cCAcbCA", + 10 + ], + [ + "Ac", + "cCcCAAA", + 12 + ], + [ + "Ac", + "cbAAcc", + 8 + ], + [ + "AcA", + "ABAACCbc", + 12 + ], + [ + "AcA", + "BBBb", + 8 + ], + [ + "AcA", + "CcabCab", + 11 + ], + [ + "AcA", + "acA", + 1 + ], + [ + "AcA", + "bAbCc", + 7 + ], + [ + "AcA", + "bccBB", + 8 + ], + [ + "AcA", + "cCCA", + 5 + ], + [ + "AcAAAb", + "Acba", + 7 + ], + [ + "AcAABAc", + "bCaa", + 11 + ], + [ + "AcAABBc", + "c", + 12 + ], + [ + "AcAACA", + "cCb", + 8 + ], + [ + "AcAACBb", + "AbaA", + 9 + ], + [ + "AcAAbb", + "abBbA", + 9 + ], + [ + "AcAAcBaB", + "caB", + 10 + ], + [ + "AcABCCba", + "Ca", + 12 + ], + [ + "AcABa", + "aAbBBCA", + 9 + ], + [ + "AcAC", + "c", + 6 + ], + [ + "AcACB", + "aBBCbBabC", + 13 + ], + [ + "AcACCBA", + "c", + 12 + ], + [ + "AcACCaACA", + "aCAAAcABC", + 12 + ], + [ + "AcACaA", + "Ac", + 8 + ], + [ + "AcACcC", + "bABBAcC", + 8 + ], + [ + "AcACccA", + "CaacccB", + 8 + ], + [ + "AcAa", + "b", + 8 + ], + [ + "AcAaaCBA", + "abB", + 12 + ], + [ + "AcAac", + "BBCCC", + 9 + ], + [ + "AcAb", + "cCBBcBCAc", + 14 + ], + [ + "AcAbA", + "cCbbBcb", + 11 + ], + [ + "AcAbBabb", + "BBCBa", + 12 + ], + [ + "AcAbBcABC", + "baCcCcb", + 15 + ], + [ + "AcAbCB", + "ccCCaC", + 10 + ], + [ + "AcAba", + "CcBcBcC", + 11 + ], + [ + "AcAbb", + "bAAbc", + 6 + ], + [ + "AcAcB", + "aAcBAbC", + 8 + ], + [ + "AcAcCB", + "bc", + 10 + ], + [ + "AcAcCCCbb", + "BAaBC", + 14 + ], + [ + "AcAcbacA", + "cb", + 12 + ], + [ + "AcB", + "AbCbCa", + 8 + ], + [ + "AcB", + "CCABca", + 8 + ], + [ + "AcB", + "aBA", + 5 + ], + [ + "AcB", + "b", + 5 + ], + [ + "AcB", + "bCB", + 3 + ], + [ + "AcB", + "cBBaB", + 8 + ], + [ + "AcB", + "caBcC", + 7 + ], + [ + "AcB", + "caCCCaA", + 12 + ], + [ + "AcBAAa", + "ac", + 9 + ], + [ + "AcBAbbAA", + "ACCB", + 12 + ], + [ + "AcBB", + "AAAccBcA", + 10 + ], + [ + "AcBB", + "BaccCCACc", + 15 + ], + [ + "AcBB", + "bBCA", + 8 + ], + [ + "AcBB", + "cCAaaBaBb", + 12 + ], + [ + "AcBBAC", + "AaCA", + 8 + ], + [ + "AcBBACA", + "aAA", + 9 + ], + [ + "AcBBACCaC", + "abBcCAC", + 8 + ], + [ + "AcBBaB", + "aC", + 10 + ], + [ + "AcBBbbaBc", + "CC", + 16 + ], + [ + "AcBBbcb", + "ABBAAc", + 8 + ], + [ + "AcBBcabc", + "a", + 14 + ], + [ + "AcBC", + "ACabcCbBB", + 12 + ], + [ + "AcBC", + "AacAcBCcA", + 10 + ], + [ + "AcBC", + "bCbcAbbA", + 13 + ], + [ + "AcBCAcb", + "AB", + 10 + ], + [ + "AcBCCaAbc", + "ca", + 14 + ], + [ + "AcBCCb", + "aCcCAccc", + 11 + ], + [ + "AcBCaccAA", + "cBAcc", + 9 + ], + [ + "AcBCb", + "aBbaBac", + 11 + ], + [ + "AcBCcbCb", + "AAABCa", + 11 + ], + [ + "AcBCcbbaB", + "bBbC", + 14 + ], + [ + "AcBa", + "BBbCBAA", + 10 + ], + [ + "AcBaCCbCa", + "bbBBb", + 14 + ], + [ + "AcBaCCc", + "aaCcca", + 8 + ], + [ + "AcBaacCb", + "BBbbCbcC", + 13 + ], + [ + "AcBbAb", + "BabcbBbc", + 11 + ], + [ + "AcBbAc", + "cbAbC", + 7 + ], + [ + "AcBbaac", + "bA", + 11 + ], + [ + "AcBbbbB", + "ACaa", + 11 + ], + [ + "AcBc", + "abAcbb", + 7 + ], + [ + "AcBcAcA", + "aaCBAaAAa", + 11 + ], + [ + "AcBcBBB", + "a", + 13 + ], + [ + "AcBcCba", + "BCb", + 8 + ], + [ + "AcBca", + "Ab", + 7 + ], + [ + "AcBcbbA", + "ABb", + 8 + ], + [ + "AcBcbbA", + "BB", + 11 + ], + [ + "AcBcbcA", + "B", + 12 + ], + [ + "AcBccbbbC", + "CbBAAbB", + 13 + ], + [ + "AcBcccC", + "b", + 13 + ], + [ + "AcC", + "ACAbc", + 6 + ], + [ + "AcC", + "bBBA", + 8 + ], + [ + "AcC", + "bbCBACbcA", + 14 + ], + [ + "AcC", + "c", + 4 + ], + [ + "AcC", + "cBBa", + 8 + ], + [ + "AcCACC", + "bbAcCCcc", + 8 + ], + [ + "AcCACaCA", + "CBcCCB", + 11 + ], + [ + "AcCAb", + "bCBAACBC", + 12 + ], + [ + "AcCAbA", + "Bac", + 11 + ], + [ + "AcCAbcaBb", + "Cb", + 14 + ], + [ + "AcCAcCCCA", + "AcCC", + 10 + ], + [ + "AcCBA", + "a", + 9 + ], + [ + "AcCBBaBb", + "AC", + 12 + ], + [ + "AcCBba", + "CaaBCAa", + 10 + ], + [ + "AcCCAA", + "BcA", + 8 + ], + [ + "AcCCBcc", + "bbBACCa", + 13 + ], + [ + "AcCCCbb", + "AcaAc", + 9 + ], + [ + "AcCCb", + "bb", + 8 + ], + [ + "AcCCba", + "BC", + 10 + ], + [ + "AcCCcBACB", + "cb", + 15 + ], + [ + "AcCCccCB", + "baaCaAaB", + 12 + ], + [ + "AcCa", + "AAaCcC", + 8 + ], + [ + "AcCaAcccA", + "AaaaBaCBB", + 13 + ], + [ + "AcCaBCACC", + "a", + 16 + ], + [ + "AcCaC", + "CAcC", + 6 + ], + [ + "AcCaa", + "Ccab", + 6 + ], + [ + "AcCabb", + "BbCBa", + 9 + ], + [ + "AcCb", + "A", + 6 + ], + [ + "AcCbA", + "BaCcaC", + 9 + ], + [ + "AcCbA", + "aA", + 7 + ], + [ + "AcCbBb", + "CCAcb", + 7 + ], + [ + "AcCba", + "cBBbCbCc", + 12 + ], + [ + "AcCbac", + "cCBa", + 5 + ], + [ + "AcCbbbc", + "BbBbABCBc", + 12 + ], + [ + "AcCbc", + "ABBaaAc", + 10 + ], + [ + "AcCc", + "BBBAA", + 10 + ], + [ + "AcCc", + "CABBBCaCb", + 13 + ], + [ + "AcCc", + "acCbACCcc", + 11 + ], + [ + "AcCcA", + "AbCbabBc", + 11 + ], + [ + "AcCcABb", + "cCBaAc", + 9 + ], + [ + "AcCcBB", + "AAaCAaA", + 10 + ], + [ + "AcCcabBCB", + "BcA", + 15 + ], + [ + "AcCcb", + "bC", + 8 + ], + [ + "AcCccABB", + "bbCbbCB", + 12 + ], + [ + "AcCccbBBb", + "ACABAa", + 12 + ], + [ + "Aca", + "BaAA", + 6 + ], + [ + "Aca", + "CCBCCB", + 11 + ], + [ + "Aca", + "cA", + 3 + ], + [ + "AcaAAA", + "CcbbaB", + 9 + ], + [ + "AcaABAaCb", + "CcCACC", + 12 + ], + [ + "AcaABCa", + "bacAcA", + 9 + ], + [ + "AcaAcBC", + "ccbAaa", + 10 + ], + [ + "AcaBACCb", + "ACacBaBAb", + 8 + ], + [ + "AcaBAabCb", + "ACACAbaCB", + 9 + ], + [ + "AcaBC", + "ABacC", + 4 + ], + [ + "AcaBCa", + "AbBC", + 6 + ], + [ + "AcaBacc", + "CBB", + 11 + ], + [ + "AcaBcba", + "AbAbCBcC", + 10 + ], + [ + "AcaC", + "Aca", + 2 + ], + [ + "AcaCB", + "C", + 8 + ], + [ + "AcaCBB", + "cbacccC", + 11 + ], + [ + "AcaCBb", + "CCcaBC", + 8 + ], + [ + "AcaCa", + "bCA", + 7 + ], + [ + "AcaCaC", + "BB", + 12 + ], + [ + "AcaCbcC", + "aBBCccaC", + 9 + ], + [ + "AcaCc", + "CaaCBBb", + 10 + ], + [ + "AcaCc", + "aBaCb", + 5 + ], + [ + "AcaCcAc", + "acA", + 8 + ], + [ + "Acaa", + "BACcCA", + 7 + ], + [ + "AcaaA", + "bacbCca", + 10 + ], + [ + "Acaaa", + "ACccca", + 6 + ], + [ + "AcaaaaaBA", + "b", + 17 + ], + [ + "AcaaabbAC", + "AACbc", + 12 + ], + [ + "AcaabBaAc", + "aCAbBBCaA", + 10 + ], + [ + "AcaacaAAB", + "CA", + 15 + ], + [ + "AcaacbaC", + "A", + 14 + ], + [ + "Acab", + "AB", + 5 + ], + [ + "AcabA", + "BCcca", + 8 + ], + [ + "AcabBAcB", + "B", + 14 + ], + [ + "AcabCaab", + "cCCaBB", + 9 + ], + [ + "AcabcC", + "AC", + 8 + ], + [ + "Acabca", + "cCCC", + 9 + ], + [ + "AcacaAbbb", + "abB", + 13 + ], + [ + "AcacaBC", + "bbaCB", + 9 + ], + [ + "AcacaCCCc", + "aBbbcACA", + 14 + ], + [ + "AcaccB", + "aaBc", + 7 + ], + [ + "Acb", + "BcbA", + 4 + ], + [ + "Acb", + "BccCaB", + 9 + ], + [ + "Acb", + "aC", + 4 + ], + [ + "Acb", + "bAccAa", + 8 + ], + [ + "Acb", + "ccAcbaB", + 8 + ], + [ + "AcbA", + "cA", + 4 + ], + [ + "AcbAAcaA", + "Cba", + 11 + ], + [ + "AcbAB", + "cbBbAa", + 8 + ], + [ + "AcbACBAaA", + "cc", + 15 + ], + [ + "AcbB", + "C", + 7 + ], + [ + "AcbBa", + "aAABbACcB", + 13 + ], + [ + "AcbBaCb", + "bCcacBbA", + 12 + ], + [ + "AcbBaba", + "CbbCBaB", + 9 + ], + [ + "AcbBb", + "abBbA", + 5 + ], + [ + "AcbC", + "bbCaA", + 8 + ], + [ + "AcbCAC", + "CcACABBb", + 10 + ], + [ + "AcbCAc", + "aaBCaAbAa", + 12 + ], + [ + "AcbCBcc", + "aA", + 13 + ], + [ + "AcbCaCb", + "ccAABC", + 10 + ], + [ + "AcbCcBCa", + "bbbcAcB", + 11 + ], + [ + "AcbCcbCa", + "CcaABBcCa", + 11 + ], + [ + "Acba", + "aACbbBcc", + 11 + ], + [ + "AcbaCAA", + "bAaBbaca", + 10 + ], + [ + "Acbab", + "acBc", + 6 + ], + [ + "AcbbAcCa", + "cCb", + 12 + ], + [ + "AcbbC", + "B", + 9 + ], + [ + "Acbbb", + "cCbCAACA", + 13 + ], + [ + "AcbbcAB", + "cca", + 9 + ], + [ + "Acbc", + "AbCaCB", + 8 + ], + [ + "Acbc", + "Bac", + 6 + ], + [ + "AcbcBB", + "ABBBB", + 5 + ], + [ + "AcbcBcA", + "AaaBaba", + 11 + ], + [ + "AcbcCbcbA", + "ac", + 15 + ], + [ + "Acc", + "BbBCABBb", + 14 + ], + [ + "Acc", + "aAbBbBca", + 12 + ], + [ + "Acc", + "aa", + 5 + ], + [ + "Acc", + "aaBcC", + 6 + ], + [ + "Acc", + "bCbAaCab", + 13 + ], + [ + "AccA", + "BCBA", + 5 + ], + [ + "AccA", + "aC", + 6 + ], + [ + "AccAB", + "Bcb", + 7 + ], + [ + "AccABcbBC", + "AAcBcAcc", + 9 + ], + [ + "AccACBbA", + "c", + 14 + ], + [ + "AccAbcC", + "cbbB", + 10 + ], + [ + "AccBbab", + "bcAaaaA", + 10 + ], + [ + "AccC", + "BBbca", + 8 + ], + [ + "AccCBBACa", + "b", + 17 + ], + [ + "AccCCCcaa", + "aabC", + 15 + ], + [ + "AccCcAA", + "CCbAaABCA", + 13 + ], + [ + "Acca", + "C", + 7 + ], + [ + "Acca", + "aB", + 7 + ], + [ + "AccaCABA", + "CBBBc", + 13 + ], + [ + "AccaaAbbC", + "BaAB", + 13 + ], + [ + "Accb", + "baBaaCaCa", + 15 + ], + [ + "Accbbbb", + "bA", + 12 + ], + [ + "Accbcc", + "aaAAcb", + 9 + ], + [ + "Accc", + "ABbAB", + 8 + ], + [ + "AcccAC", + "BAAbCacBb", + 13 + ], + [ + "AcccAbbB", + "BaBCa", + 14 + ], + [ + "AcccBAAbC", + "CCbCb", + 13 + ], + [ + "AcccCACac", + "BAbccaC", + 11 + ], + [ + "AcccCabab", + "bBAAaBaA", + 13 + ], + [ + "AcccCb", + "BACacbcC", + 9 + ], + [ + "AcccaCb", + "CBBCcaCB", + 8 + ], + [ + "Acccac", + "acCaAcaCb", + 9 + ], + [ + "B", + "A", + 2 + ], + [ + "B", + "AAABB", + 8 + ], + [ + "B", + "AAAcc", + 10 + ], + [ + "B", + "AABBcC", + 10 + ], + [ + "B", + "AABCBb", + 10 + ], + [ + "B", + "AAC", + 6 + ], + [ + "B", + "AACA", + 8 + ], + [ + "B", + "AACaaaa", + 14 + ], + [ + "B", + "AAcaBa", + 10 + ], + [ + "B", + "AAcacbab", + 15 + ], + [ + "B", + "ABBc", + 6 + ], + [ + "B", + "ABCBcBCB", + 14 + ], + [ + "B", + "ABaAba", + 10 + ], + [ + "B", + "ABaB", + 6 + ], + [ + "B", + "ABaBba", + 10 + ], + [ + "B", + "ABaaCcBa", + 14 + ], + [ + "B", + "ABc", + 4 + ], + [ + "B", + "ACB", + 4 + ], + [ + "B", + "ACCCCCBc", + 14 + ], + [ + "B", + "ACbbC", + 9 + ], + [ + "B", + "ACbbCA", + 11 + ], + [ + "B", + "AaA", + 6 + ], + [ + "B", + "AaACbbaaB", + 16 + ], + [ + "B", + "AaAaCCbaa", + 17 + ], + [ + "B", + "AaBaBcba", + 14 + ], + [ + "B", + "AabcAaa", + 13 + ], + [ + "B", + "AacCacAb", + 15 + ], + [ + "B", + "AaccbBacB", + 16 + ], + [ + "B", + "Ab", + 3 + ], + [ + "B", + "AbBc", + 6 + ], + [ + "B", + "AbaBCcaBa", + 16 + ], + [ + "B", + "Abc", + 5 + ], + [ + "B", + "AcA", + 6 + ], + [ + "B", + "AcBA", + 6 + ], + [ + "B", + "AcBaBbCc", + 14 + ], + [ + "B", + "AcCc", + 8 + ], + [ + "B", + "AcaC", + 8 + ], + [ + "B", + "AccBacc", + 12 + ], + [ + "B", + "B", + 0 + ], + [ + "B", + "BAA", + 4 + ], + [ + "B", + "BBAbCc", + 10 + ], + [ + "B", + "BBAccA", + 10 + ], + [ + "B", + "BBBCb", + 8 + ], + [ + "B", + "BBa", + 4 + ], + [ + "B", + "BBaAcacab", + 16 + ], + [ + "B", + "BBc", + 4 + ], + [ + "B", + "BC", + 2 + ], + [ + "B", + "BCC", + 4 + ], + [ + "B", + "BCCbaBA", + 12 + ], + [ + "B", + "BCbCb", + 8 + ], + [ + "B", + "BCcC", + 6 + ], + [ + "B", + "BCcCccC", + 12 + ], + [ + "B", + "BCcb", + 6 + ], + [ + "B", + "BCcc", + 6 + ], + [ + "B", + "Ba", + 2 + ], + [ + "B", + "BaBCAaCAa", + 16 + ], + [ + "B", + "Baca", + 6 + ], + [ + "B", + "BacbcaCaC", + 16 + ], + [ + "B", + "BbcCCbAbb", + 16 + ], + [ + "B", + "BcACbAAC", + 14 + ], + [ + "B", + "BcACbbbc", + 14 + ], + [ + "B", + "BcabCBbab", + 16 + ], + [ + "B", + "C", + 2 + ], + [ + "B", + "CAAb", + 7 + ], + [ + "B", + "CAAba", + 9 + ], + [ + "B", + "CACcA", + 10 + ], + [ + "B", + "CB", + 2 + ], + [ + "B", + "CBCcAcbb", + 14 + ], + [ + "B", + "CBc", + 4 + ], + [ + "B", + "CBcA", + 6 + ], + [ + "B", + "CBcCC", + 8 + ], + [ + "B", + "CCaaCaac", + 16 + ], + [ + "B", + "CCcBBCb", + 12 + ], + [ + "B", + "Ca", + 4 + ], + [ + "B", + "CaCC", + 8 + ], + [ + "B", + "Caa", + 6 + ], + [ + "B", + "Cab", + 5 + ], + [ + "B", + "Cacbc", + 9 + ], + [ + "B", + "Cb", + 3 + ], + [ + "B", + "Cbc", + 5 + ], + [ + "B", + "CbcaAaACC", + 17 + ], + [ + "B", + "CbccCbca", + 15 + ], + [ + "B", + "Cc", + 4 + ], + [ + "B", + "CcAacCAA", + 16 + ], + [ + "B", + "CcBb", + 6 + ], + [ + "B", + "CcbBb", + 8 + ], + [ + "B", + "Ccc", + 6 + ], + [ + "B", + "a", + 2 + ], + [ + "B", + "aAA", + 6 + ], + [ + "B", + "aAACAb", + 11 + ], + [ + "B", + "aABCB", + 8 + ], + [ + "B", + "aACaCCBbA", + 16 + ], + [ + "B", + "aB", + 2 + ], + [ + "B", + "aBBbc", + 8 + ], + [ + "B", + "aBabc", + 8 + ], + [ + "B", + "aBcbCA", + 10 + ], + [ + "B", + "aBccCCBC", + 14 + ], + [ + "B", + "aC", + 4 + ], + [ + "B", + "aCBBAAc", + 12 + ], + [ + "B", + "aCBcA", + 8 + ], + [ + "B", + "aCCaAabB", + 14 + ], + [ + "B", + "aCCcbbac", + 15 + ], + [ + "B", + "aCa", + 6 + ], + [ + "B", + "aCaBABACa", + 16 + ], + [ + "B", + "aCcbCA", + 11 + ], + [ + "B", + "aaBBac", + 10 + ], + [ + "B", + "aaBCC", + 8 + ], + [ + "B", + "aab", + 5 + ], + [ + "B", + "aabBcbBa", + 14 + ], + [ + "B", + "aacbAB", + 10 + ], + [ + "B", + "abA", + 5 + ], + [ + "B", + "abAAA", + 9 + ], + [ + "B", + "abBBCBBcb", + 16 + ], + [ + "B", + "abC", + 5 + ], + [ + "B", + "abCcacAC", + 15 + ], + [ + "B", + "ac", + 4 + ], + [ + "B", + "acAbAB", + 10 + ], + [ + "B", + "acBcBba", + 12 + ], + [ + "B", + "b", + 1 + ], + [ + "B", + "bA", + 3 + ], + [ + "B", + "bAAbcbb", + 13 + ], + [ + "B", + "bABAacc", + 12 + ], + [ + "B", + "bACA", + 7 + ], + [ + "B", + "bAaAbBbcb", + 16 + ], + [ + "B", + "bAc", + 5 + ], + [ + "B", + "bB", + 2 + ], + [ + "B", + "bC", + 3 + ], + [ + "B", + "bCAbccaCA", + 17 + ], + [ + "B", + "bCCA", + 7 + ], + [ + "B", + "bCabCB", + 10 + ], + [ + "B", + "bCabcCa", + 13 + ], + [ + "B", + "ba", + 3 + ], + [ + "B", + "baba", + 7 + ], + [ + "B", + "babaa", + 9 + ], + [ + "B", + "bb", + 3 + ], + [ + "B", + "bbc", + 5 + ], + [ + "B", + "bbcbCCCb", + 15 + ], + [ + "B", + "bc", + 3 + ], + [ + "B", + "bcCBCacb", + 14 + ], + [ + "B", + "bcaAcbbB", + 14 + ], + [ + "B", + "c", + 2 + ], + [ + "B", + "cABAAb", + 10 + ], + [ + "B", + "cAaaACc", + 14 + ], + [ + "B", + "cAcCA", + 10 + ], + [ + "B", + "cAccC", + 10 + ], + [ + "B", + "cB", + 2 + ], + [ + "B", + "cBBBa", + 8 + ], + [ + "B", + "cBaCCba", + 12 + ], + [ + "B", + "cBbbaAaBC", + 16 + ], + [ + "B", + "cBcCaA", + 10 + ], + [ + "B", + "cC", + 4 + ], + [ + "B", + "cCABB", + 8 + ], + [ + "B", + "cCBAacA", + 12 + ], + [ + "B", + "cCbBBAccB", + 16 + ], + [ + "B", + "cCbcaBaca", + 16 + ], + [ + "B", + "cCcBaC", + 10 + ], + [ + "B", + "cCcbcaCcc", + 17 + ], + [ + "B", + "cabBca", + 10 + ], + [ + "B", + "cabccaAAB", + 16 + ], + [ + "B", + "cb", + 3 + ], + [ + "B", + "cbAACcCCb", + 17 + ], + [ + "B", + "cbAC", + 7 + ], + [ + "B", + "cbBbCC", + 10 + ], + [ + "B", + "cbC", + 5 + ], + [ + "B", + "cbCaba", + 11 + ], + [ + "B", + "cbCbBBaa", + 14 + ], + [ + "B", + "cbaaAAA", + 13 + ], + [ + "B", + "cbaaCAb", + 13 + ], + [ + "B", + "cbbCaccA", + 15 + ], + [ + "B", + "cbbb", + 7 + ], + [ + "B", + "cbcCa", + 9 + ], + [ + "B", + "ccABaB", + 10 + ], + [ + "B", + "ccAc", + 8 + ], + [ + "B", + "ccCbCbc", + 13 + ], + [ + "B", + "ccabaC", + 11 + ], + [ + "B", + "ccb", + 5 + ], + [ + "BA", + "A", + 2 + ], + [ + "BA", + "ABaabAbAc", + 14 + ], + [ + "BA", + "B", + 2 + ], + [ + "BA", + "BBABbCAaB", + 14 + ], + [ + "BA", + "BBcaC", + 7 + ], + [ + "BA", + "BBcacAbcb", + 14 + ], + [ + "BA", + "BCbCbbcAB", + 14 + ], + [ + "BA", + "CACCAaac", + 14 + ], + [ + "BA", + "CAaaacb", + 12 + ], + [ + "BA", + "CBC", + 4 + ], + [ + "BA", + "aACbbcba", + 14 + ], + [ + "BA", + "ab", + 4 + ], + [ + "BA", + "abCAa", + 7 + ], + [ + "BA", + "b", + 3 + ], + [ + "BA", + "bABaAca", + 10 + ], + [ + "BA", + "baCCBbC", + 12 + ], + [ + "BA", + "bbBcB", + 8 + ], + [ + "BA", + "bbbCC", + 9 + ], + [ + "BA", + "bbbaBA", + 8 + ], + [ + "BA", + "bbbbCBb", + 12 + ], + [ + "BA", + "cBABaC", + 8 + ], + [ + "BA", + "cBBbbA", + 8 + ], + [ + "BA", + "cC", + 4 + ], + [ + "BA", + "ccB", + 6 + ], + [ + "BA", + "ccCa", + 7 + ], + [ + "BAA", + "A", + 4 + ], + [ + "BAA", + "abA", + 4 + ], + [ + "BAA", + "acCAc", + 8 + ], + [ + "BAA", + "bB", + 5 + ], + [ + "BAA", + "bbcACCCAB", + 13 + ], + [ + "BAA", + "bcBC", + 7 + ], + [ + "BAA", + "cBaCaBc", + 10 + ], + [ + "BAAA", + "B", + 6 + ], + [ + "BAAA", + "BBCacaC", + 10 + ], + [ + "BAAA", + "bBAc", + 5 + ], + [ + "BAAAAAA", + "CbcbAc", + 12 + ], + [ + "BAAAACb", + "cbcACabBc", + 13 + ], + [ + "BAAAC", + "cbCBcbCC", + 12 + ], + [ + "BAAAaCCAB", + "bcCB", + 12 + ], + [ + "BAAAabC", + "CCaaaAcc", + 11 + ], + [ + "BAAAbcBa", + "aCcAAAcc", + 12 + ], + [ + "BAABC", + "bccab", + 9 + ], + [ + "BAABaC", + "Cbb", + 11 + ], + [ + "BAABabAb", + "ACC", + 14 + ], + [ + "BAAC", + "bB", + 7 + ], + [ + "BAAC", + "ccaBab", + 10 + ], + [ + "BAAC", + "ccbC", + 6 + ], + [ + "BAACAA", + "a", + 11 + ], + [ + "BAACaC", + "Cac", + 7 + ], + [ + "BAAaA", + "a", + 8 + ], + [ + "BAAaACaC", + "bb", + 15 + ], + [ + "BAAaB", + "ccAcbA", + 9 + ], + [ + "BAAaa", + "b", + 9 + ], + [ + "BAAaa", + "cacCaBc", + 11 + ], + [ + "BAAaaac", + "c", + 12 + ], + [ + "BAAaabB", + "aaAAA", + 9 + ], + [ + "BAAaac", + "BCaCcCAB", + 12 + ], + [ + "BAAacA", + "ccBAcCAc", + 11 + ], + [ + "BAAb", + "AA", + 4 + ], + [ + "BAAbAC", + "BbAccCba", + 10 + ], + [ + "BAAbCbbC", + "CCCBBc", + 11 + ], + [ + "BAAbacbC", + "aBAabc", + 9 + ], + [ + "BAAbbACC", + "CCABb", + 11 + ], + [ + "BAAcCBa", + "ACcA", + 9 + ], + [ + "BAAcaBBCa", + "AccB", + 12 + ], + [ + "BAAcac", + "Bb", + 10 + ], + [ + "BAAcc", + "CACbabA", + 11 + ], + [ + "BAB", + "AcbBaaBa", + 11 + ], + [ + "BAB", + "BB", + 2 + ], + [ + "BAB", + "Caa", + 5 + ], + [ + "BAB", + "cc", + 6 + ], + [ + "BABA", + "abbccc", + 11 + ], + [ + "BABA", + "caCca", + 8 + ], + [ + "BABB", + "bBCCBcAcb", + 13 + ], + [ + "BABBAAc", + "caAaa", + 10 + ], + [ + "BABBbCA", + "bAca", + 9 + ], + [ + "BABBc", + "BCCcAcCC", + 11 + ], + [ + "BABCB", + "AB", + 6 + ], + [ + "BABCcBbA", + "CBb", + 10 + ], + [ + "BABa", + "abbbaccAa", + 14 + ], + [ + "BABabAB", + "b", + 12 + ], + [ + "BABacA", + "abcBA", + 8 + ], + [ + "BABb", + "cC", + 8 + ], + [ + "BABbC", + "BaA", + 7 + ], + [ + "BABbb", + "Ccc", + 10 + ], + [ + "BABc", + "aB", + 5 + ], + [ + "BABcACCaC", + "CbbBaCbaC", + 10 + ], + [ + "BABcBA", + "CA", + 9 + ], + [ + "BABcBCaBc", + "CBAaBCC", + 11 + ], + [ + "BABcBcBa", + "bCBACcc", + 11 + ], + [ + "BABcaBB", + "bAaabb", + 7 + ], + [ + "BABcb", + "CcCAaC", + 11 + ], + [ + "BABcbcaa", + "BbbCcAAab", + 11 + ], + [ + "BABccba", + "cCbbbA", + 10 + ], + [ + "BAC", + "BB", + 4 + ], + [ + "BAC", + "BBacAbC", + 8 + ], + [ + "BAC", + "BaacBaC", + 9 + ], + [ + "BAC", + "BbbBaB", + 9 + ], + [ + "BAC", + "CAAaa", + 8 + ], + [ + "BAC", + "CBBbBccbc", + 15 + ], + [ + "BAC", + "b", + 5 + ], + [ + "BAC", + "babAAcA", + 10 + ], + [ + "BACACcCcc", + "cbB", + 16 + ], + [ + "BACB", + "AaCABa", + 7 + ], + [ + "BACBAACba", + "BaA", + 13 + ], + [ + "BACBCAC", + "A", + 12 + ], + [ + "BACBaB", + "Bcbc", + 8 + ], + [ + "BACBbCbB", + "ACaAAaCb", + 12 + ], + [ + "BACC", + "ab", + 7 + ], + [ + "BACCBcbaa", + "ab", + 15 + ], + [ + "BACCCAaCA", + "bCCcBb", + 12 + ], + [ + "BACCbABA", + "AAAAcAB", + 10 + ], + [ + "BACCbAac", + "AcBCaacB", + 10 + ], + [ + "BACCc", + "BbAAcA", + 7 + ], + [ + "BACCc", + "aBbbBBCa", + 12 + ], + [ + "BACaC", + "CB", + 8 + ], + [ + "BACab", + "bCA", + 6 + ], + [ + "BACb", + "AcBC", + 6 + ], + [ + "BACbAbCbC", + "BbC", + 12 + ], + [ + "BACbbaaAc", + "ACabC", + 11 + ], + [ + "BACcBbcCb", + "AcbB", + 11 + ], + [ + "BACcbBbc", + "AC", + 12 + ], + [ + "BACccabb", + "bAcAAa", + 10 + ], + [ + "BACcccA", + "aacC", + 10 + ], + [ + "BAa", + "AC", + 4 + ], + [ + "BAa", + "AbCBcA", + 9 + ], + [ + "BAa", + "CabbAabb", + 11 + ], + [ + "BAa", + "cBaAa", + 4 + ], + [ + "BAaA", + "BCB", + 6 + ], + [ + "BAaABbB", + "ABabABcbC", + 9 + ], + [ + "BAaAbCc", + "acb", + 10 + ], + [ + "BAaAcCb", + "AbbC", + 10 + ], + [ + "BAaAcbB", + "Aa", + 10 + ], + [ + "BAaBBaAb", + "bBaBcaAAa", + 9 + ], + [ + "BAaBaB", + "A", + 10 + ], + [ + "BAaBbCc", + "cacBaAcaB", + 13 + ], + [ + "BAaBbabc", + "A", + 14 + ], + [ + "BAaBcCaaa", + "ab", + 15 + ], + [ + "BAaBcCb", + "aCAA", + 11 + ], + [ + "BAaCB", + "BBb", + 7 + ], + [ + "BAaCB", + "aABACA", + 7 + ], + [ + "BAaCaA", + "acB", + 9 + ], + [ + "BAaCabCCa", + "b", + 16 + ], + [ + "BAaCbAC", + "bA", + 10 + ], + [ + "BAaCbB", + "aCcbbAAA", + 13 + ], + [ + "BAaCcc", + "bc", + 9 + ], + [ + "BAaaACaA", + "Ccbcaa", + 12 + ], + [ + "BAaaCCb", + "bCBC", + 11 + ], + [ + "BAab", + "c", + 8 + ], + [ + "BAab", + "ccaba", + 6 + ], + [ + "BAabAbBB", + "ABaBaaBa", + 10 + ], + [ + "BAabCA", + "Cb", + 10 + ], + [ + "BAabCCA", + "CCbBcb", + 11 + ], + [ + "BAac", + "bBbcaca", + 8 + ], + [ + "BAacBb", + "cABAca", + 9 + ], + [ + "BAacbBbCb", + "bBAca", + 13 + ], + [ + "BAacbaBC", + "ABCbcaCAc", + 12 + ], + [ + "BAaccAba", + "BAbBbCA", + 11 + ], + [ + "BAb", + "Aa", + 4 + ], + [ + "BAb", + "AbaccbCbC", + 14 + ], + [ + "BAb", + "BaCa", + 5 + ], + [ + "BAb", + "CCaBA", + 8 + ], + [ + "BAb", + "CbCb", + 5 + ], + [ + "BAb", + "caAAC", + 8 + ], + [ + "BAb", + "ccCAAAABC", + 15 + ], + [ + "BAbABaBbC", + "CAAcAb", + 11 + ], + [ + "BAbACcA", + "aBaaCcc", + 8 + ], + [ + "BAbAa", + "ABbCbabac", + 11 + ], + [ + "BAbAa", + "c", + 10 + ], + [ + "BAbAc", + "cBc", + 7 + ], + [ + "BAbAcABa", + "ac", + 13 + ], + [ + "BAbAcbB", + "aCAcBB", + 6 + ], + [ + "BAbBA", + "BcaCBcaBa", + 11 + ], + [ + "BAbBAB", + "ABBCCb", + 8 + ], + [ + "BAbBBaB", + "abaA", + 9 + ], + [ + "BAbBCc", + "aaAcAcAAC", + 14 + ], + [ + "BAbBc", + "ABcAAABb", + 10 + ], + [ + "BAbCCbBC", + "bc", + 13 + ], + [ + "BAbCbBacB", + "acBca", + 12 + ], + [ + "BAbCc", + "BBbcBAab", + 11 + ], + [ + "BAbCcB", + "CbacAaaa", + 14 + ], + [ + "BAbCcBB", + "ccaBBcACC", + 14 + ], + [ + "BAba", + "Bc", + 6 + ], + [ + "BAbaBCAB", + "bbCbBa", + 11 + ], + [ + "BAbaBbBc", + "baAC", + 11 + ], + [ + "BAbaCc", + "C", + 10 + ], + [ + "BAbabca", + "cBabaCb", + 8 + ], + [ + "BAbacCaa", + "CCa", + 11 + ], + [ + "BAbb", + "baBaBaB", + 9 + ], + [ + "BAbbBAA", + "ACbcccc", + 12 + ], + [ + "BAbc", + "B", + 6 + ], + [ + "BAbc", + "bABCB", + 5 + ], + [ + "BAbc", + "bcBAb", + 6 + ], + [ + "BAbcAcA", + "ccA", + 8 + ], + [ + "BAbcaBab", + "CaACACbcB", + 13 + ], + [ + "BAbccAcB", + "BA", + 12 + ], + [ + "BAbccaBA", + "CCCcaa", + 10 + ], + [ + "BAc", + "AAAccAa", + 10 + ], + [ + "BAc", + "Bbc", + 2 + ], + [ + "BAc", + "ba", + 4 + ], + [ + "BAcA", + "Ac", + 4 + ], + [ + "BAcAA", + "acbCAA", + 7 + ], + [ + "BAcAACc", + "accA", + 9 + ], + [ + "BAcAAb", + "AbC", + 10 + ], + [ + "BAcAB", + "aAacCcbac", + 13 + ], + [ + "BAcACCb", + "cccBC", + 10 + ], + [ + "BAcACcBA", + "BCAbccA", + 7 + ], + [ + "BAcAcC", + "aAcBb", + 8 + ], + [ + "BAcBa", + "CCAbBCc", + 10 + ], + [ + "BAcBcba", + "aaa", + 11 + ], + [ + "BAcCBCbaA", + "bCb", + 13 + ], + [ + "BAcCC", + "ACCaC", + 5 + ], + [ + "BAcCCBAbA", + "b", + 16 + ], + [ + "BAcCaB", + "cCBBCaa", + 10 + ], + [ + "BAcCbC", + "CAB", + 9 + ], + [ + "BAcCbaC", + "CCBBaCabB", + 14 + ], + [ + "BAcCbc", + "Cb", + 8 + ], + [ + "BAcCcAACa", + "aacaCaA", + 11 + ], + [ + "BAcaBBBc", + "a", + 14 + ], + [ + "BAcaBc", + "CAbaa", + 8 + ], + [ + "BAcaC", + "cAcaCA", + 4 + ], + [ + "BAcaab", + "ACbA", + 8 + ], + [ + "BAcab", + "BaCbca", + 7 + ], + [ + "BAcbA", + "AbA", + 4 + ], + [ + "BAcbA", + "bACBCbbCA", + 10 + ], + [ + "BAcbAcCB", + "ac", + 13 + ], + [ + "BAcbBCC", + "bBaba", + 11 + ], + [ + "BAcbCC", + "c", + 10 + ], + [ + "BAcbCc", + "B", + 10 + ], + [ + "BAcbabcB", + "aAa", + 12 + ], + [ + "BAcbbba", + "Cb", + 11 + ], + [ + "BAcbcABbA", + "baABcBCa", + 10 + ], + [ + "BAccAAA", + "AaaC", + 10 + ], + [ + "BAccAAca", + "BBCbbCcab", + 11 + ], + [ + "BAccAbCB", + "Cba", + 13 + ], + [ + "BAccCAb", + "cCBcCcac", + 11 + ], + [ + "BAccCAbC", + "BCabCBA", + 11 + ], + [ + "BAccCCcA", + "CbbBaCB", + 14 + ], + [ + "BAccCcCB", + "bcCAB", + 9 + ], + [ + "BAcca", + "cBcCBBcbC", + 13 + ], + [ + "BAccaAaC", + "cbBcAaA", + 10 + ], + [ + "BAcccCbb", + "Bb", + 12 + ], + [ + "BB", + "A", + 4 + ], + [ + "BB", + "AACBAacBB", + 14 + ], + [ + "BB", + "ABaA", + 6 + ], + [ + "BB", + "ACbbCcc", + 12 + ], + [ + "BB", + "AbAABC", + 9 + ], + [ + "BB", + "AbbbBBa", + 10 + ], + [ + "BB", + "BC", + 2 + ], + [ + "BB", + "Ba", + 2 + ], + [ + "BB", + "BbcAaACB", + 12 + ], + [ + "BB", + "CAcaACbBb", + 15 + ], + [ + "BB", + "CBabcc", + 9 + ], + [ + "BB", + "CaCBb", + 7 + ], + [ + "BB", + "CaaAAaAAc", + 18 + ], + [ + "BB", + "Cab", + 5 + ], + [ + "BB", + "Cb", + 3 + ], + [ + "BB", + "CbAAC", + 9 + ], + [ + "BB", + "CbcbCcBc", + 13 + ], + [ + "BB", + "Ccccc", + 10 + ], + [ + "BB", + "a", + 4 + ], + [ + "BB", + "aAAbcc", + 11 + ], + [ + "BB", + "aACBABa", + 10 + ], + [ + "BB", + "aACbBCaac", + 15 + ], + [ + "BB", + "aAcCCb", + 11 + ], + [ + "BB", + "aCACcBC", + 12 + ], + [ + "BB", + "aCa", + 6 + ], + [ + "BB", + "aa", + 4 + ], + [ + "BB", + "bAABCCabC", + 15 + ], + [ + "BB", + "bABBCb", + 8 + ], + [ + "BB", + "bBacaAb", + 11 + ], + [ + "BB", + "bc", + 3 + ], + [ + "BB", + "cBBcCBaAa", + 14 + ], + [ + "BB", + "cCaAaBc", + 12 + ], + [ + "BB", + "cCb", + 5 + ], + [ + "BB", + "cCc", + 6 + ], + [ + "BB", + "caBcCA", + 10 + ], + [ + "BB", + "cac", + 6 + ], + [ + "BB", + "cbb", + 4 + ], + [ + "BB", + "ccaC", + 8 + ], + [ + "BBA", + "BB", + 2 + ], + [ + "BBA", + "BCCaaAb", + 10 + ], + [ + "BBA", + "Bb", + 3 + ], + [ + "BBA", + "Bba", + 2 + ], + [ + "BBA", + "CBbBab", + 7 + ], + [ + "BBA", + "aaBbAc", + 7 + ], + [ + "BBA", + "ab", + 5 + ], + [ + "BBA", + "bAAaBCbA", + 11 + ], + [ + "BBA", + "cbcBbC", + 9 + ], + [ + "BBAACb", + "BBaBbb", + 5 + ], + [ + "BBAAb", + "abaBbac", + 10 + ], + [ + "BBAAbbCc", + "a", + 15 + ], + [ + "BBAAcAb", + "cCBCaBCA", + 12 + ], + [ + "BBAAcbba", + "aCACbcCc", + 13 + ], + [ + "BBABA", + "bbccbbb", + 11 + ], + [ + "BBABACCCB", + "c", + 17 + ], + [ + "BBABBAca", + "aCCAAcCA", + 13 + ], + [ + "BBABBaBA", + "CaAaaa", + 11 + ], + [ + "BBABBaaBB", + "CccbccAc", + 16 + ], + [ + "BBABa", + "b", + 9 + ], + [ + "BBABcC", + "aCAA", + 10 + ], + [ + "BBABccb", + "C", + 13 + ], + [ + "BBAC", + "bBCAcBaC", + 9 + ], + [ + "BBACB", + "bAb", + 6 + ], + [ + "BBACC", + "CBccc", + 6 + ], + [ + "BBACC", + "aCBBBB", + 10 + ], + [ + "BBACaBC", + "C", + 12 + ], + [ + "BBACcCbBa", + "CCCcCC", + 12 + ], + [ + "BBAbA", + "AbCaCcB", + 12 + ], + [ + "BBAbCcacC", + "aBaacBcb", + 11 + ], + [ + "BBAba", + "BCbBcB", + 9 + ], + [ + "BBAbcB", + "BBc", + 6 + ], + [ + "BBAbcBBaA", + "bCcAB", + 13 + ], + [ + "BBAbcC", + "BacA", + 7 + ], + [ + "BBAcA", + "bBcaAacbb", + 11 + ], + [ + "BBAcC", + "cC", + 6 + ], + [ + "BBB", + "BaBbB", + 4 + ], + [ + "BBB", + "Bbcbc", + 6 + ], + [ + "BBB", + "CC", + 6 + ], + [ + "BBB", + "CCCAbc", + 11 + ], + [ + "BBB", + "CcbcBc", + 9 + ], + [ + "BBB", + "aaAbb", + 8 + ], + [ + "BBBAAA", + "AA", + 8 + ], + [ + "BBBAAAcB", + "BAcAcCCA", + 11 + ], + [ + "BBBACc", + "AaBCBb", + 10 + ], + [ + "BBBAbAaAB", + "aAcBABA", + 13 + ], + [ + "BBBAccBbC", + "ccbCbAb", + 14 + ], + [ + "BBBB", + "baABcbb", + 9 + ], + [ + "BBBBCCacA", + "bbCCc", + 10 + ], + [ + "BBBBcCA", + "bBAabcB", + 10 + ], + [ + "BBBBccCCC", + "C", + 16 + ], + [ + "BBBCABbb", + "cAAaAB", + 12 + ], + [ + "BBBCab", + "abBACbBc", + 10 + ], + [ + "BBBa", + "CCabbCcaB", + 14 + ], + [ + "BBBa", + "cAa", + 6 + ], + [ + "BBBaCA", + "AAbbaaACB", + 12 + ], + [ + "BBBaaBb", + "cBcaac", + 8 + ], + [ + "BBBab", + "bAa", + 7 + ], + [ + "BBBac", + "aaCcCBcAB", + 15 + ], + [ + "BBBb", + "B", + 6 + ], + [ + "BBBbCCb", + "BbBaCc", + 6 + ], + [ + "BBBba", + "BCaC", + 8 + ], + [ + "BBBbcBcCA", + "BbBB", + 11 + ], + [ + "BBBbccc", + "A", + 14 + ], + [ + "BBBc", + "cCAba", + 9 + ], + [ + "BBBcAB", + "AbCAAbc", + 10 + ], + [ + "BBBcBAa", + "AbBCCa", + 8 + ], + [ + "BBBcBabbB", + "aCC", + 16 + ], + [ + "BBBcbBA", + "AbACCCbCb", + 14 + ], + [ + "BBBcc", + "CCbbabCb", + 12 + ], + [ + "BBBccBaaB", + "BcCB", + 11 + ], + [ + "BBC", + "CaAAAaCbB", + 16 + ], + [ + "BBC", + "Cbcbcc", + 9 + ], + [ + "BBC", + "abBBacA", + 9 + ], + [ + "BBC", + "b", + 5 + ], + [ + "BBC", + "bCBAA", + 7 + ], + [ + "BBC", + "bcCaAbb", + 11 + ], + [ + "BBC", + "cba", + 5 + ], + [ + "BBCA", + "BAcCC", + 6 + ], + [ + "BBCAbbbc", + "BAa", + 12 + ], + [ + "BBCAcb", + "Ca", + 9 + ], + [ + "BBCBb", + "aac", + 9 + ], + [ + "BBCBbc", + "CaaBB", + 9 + ], + [ + "BBCBcaBb", + "ccCcCbBC", + 11 + ], + [ + "BBCBcb", + "CBcCBcacC", + 10 + ], + [ + "BBCC", + "C", + 6 + ], + [ + "BBCCBC", + "aCbbA", + 9 + ], + [ + "BBCCBab", + "cBCaaC", + 8 + ], + [ + "BBCCCbaCB", + "AAA", + 17 + ], + [ + "BBCCaBbB", + "BaBAcCbC", + 11 + ], + [ + "BBCCccBCB", + "bCaaCA", + 13 + ], + [ + "BBCa", + "aB", + 6 + ], + [ + "BBCaa", + "AccACcAAC", + 14 + ], + [ + "BBCabCCBB", + "BcAcCaCC", + 12 + ], + [ + "BBCbB", + "BBb", + 4 + ], + [ + "BBCbB", + "CB", + 6 + ], + [ + "BBCbB", + "caABAb", + 10 + ], + [ + "BBCbc", + "BAAbcaaBc", + 11 + ], + [ + "BBCc", + "BabAb", + 7 + ], + [ + "BBCc", + "cbabab", + 10 + ], + [ + "BBCcbACcB", + "Ab", + 15 + ], + [ + "BBCccCAba", + "aCcCCBAb", + 9 + ], + [ + "BBa", + "AcBcBAb", + 9 + ], + [ + "BBa", + "Ccb", + 6 + ], + [ + "BBa", + "aCCcbCAc", + 14 + ], + [ + "BBa", + "bBaCBa", + 6 + ], + [ + "BBa", + "cbAcBBaA", + 10 + ], + [ + "BBaA", + "bAAaBAAAB", + 12 + ], + [ + "BBaAAccbb", + "CABB", + 14 + ], + [ + "BBaACBaB", + "cbcC", + 13 + ], + [ + "BBaAab", + "BCB", + 9 + ], + [ + "BBaAcAAcb", + "cbCBBCAcb", + 11 + ], + [ + "BBaAcB", + "ACbAcb", + 7 + ], + [ + "BBaBbcB", + "C", + 13 + ], + [ + "BBaCB", + "cC", + 8 + ], + [ + "BBaCCA", + "ABAcc", + 7 + ], + [ + "BBaCccb", + "Cbcbb", + 9 + ], + [ + "BBaa", + "ba", + 5 + ], + [ + "BBaaCCBA", + "AbCbC", + 12 + ], + [ + "BBaaCca", + "aaBBcbAB", + 13 + ], + [ + "BBaaa", + "B", + 8 + ], + [ + "BBaab", + "bbAcbB", + 7 + ], + [ + "BBaabcA", + "BACBAC", + 10 + ], + [ + "BBaacbcaB", + "Abacab", + 10 + ], + [ + "BBaacc", + "C", + 11 + ], + [ + "BBabBa", + "BbBBcAACB", + 13 + ], + [ + "BBabcBab", + "abB", + 10 + ], + [ + "BBabcbb", + "BbbCbA", + 6 + ], + [ + "BBac", + "cBAB", + 5 + ], + [ + "BBacAcaAa", + "Bba", + 13 + ], + [ + "BBacCaBBa", + "aa", + 14 + ], + [ + "BBacCc", + "bcaBA", + 9 + ], + [ + "BBacaABc", + "Cbbaac", + 10 + ], + [ + "BBacb", + "AbbaCBCb", + 9 + ], + [ + "BBacb", + "abCACCBBA", + 14 + ], + [ + "BBb", + "BAcaAaca", + 14 + ], + [ + "BBb", + "BBa", + 2 + ], + [ + "BBb", + "CAcBCAAc", + 14 + ], + [ + "BBb", + "aBACcCCC", + 14 + ], + [ + "BBb", + "acbCc", + 8 + ], + [ + "BBbA", + "ca", + 7 + ], + [ + "BBbAACb", + "ACCbb", + 10 + ], + [ + "BBbABAaAB", + "cAbaCba", + 13 + ], + [ + "BBbABbac", + "cAB", + 12 + ], + [ + "BBbAabbCA", + "A", + 16 + ], + [ + "BBbAbcB", + "AcAAcbABa", + 12 + ], + [ + "BBbAcaAB", + "cBB", + 12 + ], + [ + "BBbAcc", + "bBAb", + 7 + ], + [ + "BBbB", + "ccABABc", + 10 + ], + [ + "BBbBB", + "a", + 10 + ], + [ + "BBbBBbba", + "aACbb", + 12 + ], + [ + "BBbBBcacc", + "AcAa", + 15 + ], + [ + "BBbBCbBc", + "BbABC", + 9 + ], + [ + "BBbBaa", + "bbBbbbaAb", + 9 + ], + [ + "BBbCCCCbc", + "ccaAB", + 15 + ], + [ + "BBbCCcbAc", + "bABcac", + 11 + ], + [ + "BBbCbcb", + "Ab", + 12 + ], + [ + "BBba", + "a", + 6 + ], + [ + "BBbaBc", + "ac", + 8 + ], + [ + "BBbab", + "AcAB", + 8 + ], + [ + "BBbabb", + "CCbAa", + 9 + ], + [ + "BBbabbab", + "bCBBbaA", + 9 + ], + [ + "BBbb", + "BA", + 6 + ], + [ + "BBbbACc", + "A", + 12 + ], + [ + "BBbbCCBB", + "AaCcBAAA", + 15 + ], + [ + "BBbcABBbC", + "AaC", + 14 + ], + [ + "BBbcB", + "ACbA", + 8 + ], + [ + "BBbcCac", + "cbb", + 11 + ], + [ + "BBbccCCBB", + "BbaBcb", + 12 + ], + [ + "BBc", + "ABCbAA", + 9 + ], + [ + "BBc", + "BbbABAACA", + 13 + ], + [ + "BBc", + "BcccAbBaC", + 13 + ], + [ + "BBc", + "aBaCccA", + 10 + ], + [ + "BBc", + "aC", + 5 + ], + [ + "BBc", + "aCacBbCCa", + 14 + ], + [ + "BBcAAA", + "Acbc", + 10 + ], + [ + "BBcAAac", + "acCcAbc", + 9 + ], + [ + "BBcABAA", + "BbBaABaC", + 7 + ], + [ + "BBcB", + "AAacBC", + 8 + ], + [ + "BBcB", + "aAaabB", + 10 + ], + [ + "BBcB", + "acb", + 5 + ], + [ + "BBcB", + "bAcAAbac", + 12 + ], + [ + "BBcBACa", + "CBACA", + 6 + ], + [ + "BBcBCB", + "c", + 10 + ], + [ + "BBcBbCBA", + "cBaaAca", + 12 + ], + [ + "BBcBbcA", + "bBbca", + 6 + ], + [ + "BBcC", + "AcAcAcCc", + 12 + ], + [ + "BBcCBCac", + "ababc", + 12 + ], + [ + "BBcCC", + "ccB", + 7 + ], + [ + "BBcCCabAA", + "BCC", + 12 + ], + [ + "BBcCCcab", + "bCcc", + 10 + ], + [ + "BBcCa", + "BBAA", + 5 + ], + [ + "BBcCcb", + "BCb", + 6 + ], + [ + "BBca", + "b", + 7 + ], + [ + "BBcaA", + "AaCCAbCCC", + 15 + ], + [ + "BBcaA", + "b", + 9 + ], + [ + "BBcaACbB", + "AbCb", + 11 + ], + [ + "BBcaC", + "CCccCCCC", + 12 + ], + [ + "BBcaa", + "aBaa", + 4 + ], + [ + "BBcaa", + "bAAAC", + 8 + ], + [ + "BBcaa", + "ccCCcABA", + 12 + ], + [ + "BBcaaCBB", + "BbCcbC", + 10 + ], + [ + "BBcab", + "aaBc", + 8 + ], + [ + "BBcbA", + "BcBabbA", + 6 + ], + [ + "BBcbaA", + "caBbCcaa", + 9 + ], + [ + "BBcbbaB", + "ccCbbAccB", + 10 + ], + [ + "BBcbbabC", + "BB", + 12 + ], + [ + "BBcc", + "AcbAAB", + 11 + ], + [ + "BBcc", + "CCcBccBbC", + 12 + ], + [ + "BBccAb", + "aCACbAC", + 11 + ], + [ + "BBccB", + "BcB", + 4 + ], + [ + "BBccc", + "BBAbCAcbB", + 11 + ], + [ + "BBcccCAAB", + "ABABBAca", + 14 + ], + [ + "BC", + "A", + 4 + ], + [ + "BC", + "AAcba", + 9 + ], + [ + "BC", + "AC", + 2 + ], + [ + "BC", + "ACBACCA", + 10 + ], + [ + "BC", + "AaA", + 6 + ], + [ + "BC", + "AaCABABAb", + 16 + ], + [ + "BC", + "Ac", + 3 + ], + [ + "BC", + "AcCCcc", + 10 + ], + [ + "BC", + "B", + 2 + ], + [ + "BC", + "BAbC", + 4 + ], + [ + "BC", + "BC", + 0 + ], + [ + "BC", + "BCCCC", + 6 + ], + [ + "BC", + "BbAaaBAbb", + 16 + ], + [ + "BC", + "BbB", + 4 + ], + [ + "BC", + "BcB", + 3 + ], + [ + "BC", + "C", + 2 + ], + [ + "BC", + "CA", + 4 + ], + [ + "BC", + "CaaaCAcaC", + 16 + ], + [ + "BC", + "CbCC", + 5 + ], + [ + "BC", + "CcC", + 4 + ], + [ + "BC", + "CcCCCab", + 12 + ], + [ + "BC", + "CcaAbbbcb", + 16 + ], + [ + "BC", + "CccAb", + 9 + ], + [ + "BC", + "aAA", + 6 + ], + [ + "BC", + "aAbbcbac", + 14 + ], + [ + "BC", + "aCbAaAbBB", + 16 + ], + [ + "BC", + "abbba", + 9 + ], + [ + "BC", + "acAACAC", + 12 + ], + [ + "BC", + "acbCA", + 7 + ], + [ + "BC", + "acccbAAB", + 15 + ], + [ + "BC", + "bAABa", + 8 + ], + [ + "BC", + "bBBAcBbCC", + 14 + ], + [ + "BC", + "bC", + 1 + ], + [ + "BC", + "bCaCaCaa", + 13 + ], + [ + "BC", + "bCbaCa", + 9 + ], + [ + "BC", + "bCbaaaAAC", + 15 + ], + [ + "BC", + "babCAbca", + 13 + ], + [ + "BC", + "babbBBaB", + 14 + ], + [ + "BC", + "bbCA", + 5 + ], + [ + "BC", + "c", + 3 + ], + [ + "BC", + "cAAB", + 8 + ], + [ + "BC", + "cABCBCAB", + 12 + ], + [ + "BC", + "cBaACA", + 8 + ], + [ + "BC", + "cBbaAcB", + 11 + ], + [ + "BC", + "cCCBb", + 8 + ], + [ + "BC", + "cb", + 4 + ], + [ + "BC", + "cbBBB", + 8 + ], + [ + "BC", + "cba", + 5 + ], + [ + "BC", + "cbaB", + 7 + ], + [ + "BC", + "cbaCbBAC", + 12 + ], + [ + "BC", + "cbbCabA", + 11 + ], + [ + "BC", + "ccAACb", + 10 + ], + [ + "BC", + "ccccbb", + 11 + ], + [ + "BCA", + "A", + 4 + ], + [ + "BCA", + "AbcCbCaA", + 11 + ], + [ + "BCA", + "abccbBCC", + 12 + ], + [ + "BCAABABCB", + "abBbBaB", + 11 + ], + [ + "BCAABc", + "bBACcBa", + 9 + ], + [ + "BCAAbBc", + "AaABC", + 8 + ], + [ + "BCAAbbbc", + "A", + 14 + ], + [ + "BCAAcbb", + "CAaCAcBbC", + 9 + ], + [ + "BCAAccAa", + "Aaaa", + 10 + ], + [ + "BCABBA", + "AbBba", + 8 + ], + [ + "BCABBBAa", + "bCAbBA", + 6 + ], + [ + "BCABa", + "b", + 9 + ], + [ + "BCABcB", + "bcAAbCb", + 7 + ], + [ + "BCABcCCc", + "CACcbBAc", + 10 + ], + [ + "BCABccC", + "B", + 12 + ], + [ + "BCABccaB", + "cAaCbBCc", + 13 + ], + [ + "BCAC", + "CAcCB", + 6 + ], + [ + "BCACBaACB", + "aaCaC", + 11 + ], + [ + "BCACBaba", + "BbAaAbc", + 9 + ], + [ + "BCACBb", + "aCbCA", + 8 + ], + [ + "BCACb", + "CAABCa", + 8 + ], + [ + "BCACcABBB", + "C", + 16 + ], + [ + "BCACcCAC", + "aBcAaaB", + 12 + ], + [ + "BCACcb", + "AC", + 8 + ], + [ + "BCAa", + "A", + 6 + ], + [ + "BCAa", + "Cc", + 6 + ], + [ + "BCAacBCB", + "CaCC", + 9 + ], + [ + "BCAbBAbAc", + "aBcbB", + 13 + ], + [ + "BCAbBaCB", + "caCba", + 11 + ], + [ + "BCAbCB", + "ccBcBCC", + 10 + ], + [ + "BCAbaCC", + "aB", + 12 + ], + [ + "BCAbbAcBA", + "A", + 16 + ], + [ + "BCAbbBA", + "BBAAAbac", + 10 + ], + [ + "BCAbc", + "Cb", + 6 + ], + [ + "BCAbcaBCC", + "ccBacBbA", + 13 + ], + [ + "BCAbccbb", + "bAcaCCbAB", + 12 + ], + [ + "BCAc", + "BaBb", + 6 + ], + [ + "BCAcC", + "Ccc", + 5 + ], + [ + "BCAcCabcc", + "CBC", + 14 + ], + [ + "BCAcabbBc", + "bcbC", + 12 + ], + [ + "BCB", + "caa", + 6 + ], + [ + "BCB", + "ccB", + 3 + ], + [ + "BCBA", + "B", + 6 + ], + [ + "BCBA", + "bAB", + 5 + ], + [ + "BCBAACcc", + "aBB", + 14 + ], + [ + "BCBACbAbA", + "ccABAa", + 11 + ], + [ + "BCBACbCb", + "cBA", + 11 + ], + [ + "BCBAaBcA", + "baC", + 12 + ], + [ + "BCBAabB", + "Bcb", + 9 + ], + [ + "BCBAb", + "CccbcCcBb", + 13 + ], + [ + "BCBAcbbC", + "AccaABA", + 13 + ], + [ + "BCBB", + "A", + 8 + ], + [ + "BCBBA", + "ACAC", + 8 + ], + [ + "BCBBACa", + "AbbAA", + 9 + ], + [ + "BCBBbCbC", + "Ccb", + 11 + ], + [ + "BCBBbab", + "cCAccAbb", + 11 + ], + [ + "BCBBcCa", + "BCCCBbA", + 9 + ], + [ + "BCBBcaCBA", + "CbBCCBacA", + 10 + ], + [ + "BCBBccB", + "B", + 12 + ], + [ + "BCBC", + "CbaBa", + 7 + ], + [ + "BCBC", + "cabAcCaCc", + 13 + ], + [ + "BCBCAaB", + "CAcb", + 9 + ], + [ + "BCBCBaAA", + "b", + 15 + ], + [ + "BCBCBbbc", + "CBBA", + 10 + ], + [ + "BCBCbbBC", + "CACcaACaB", + 14 + ], + [ + "BCBCc", + "aBAA", + 8 + ], + [ + "BCBaACb", + "aCB", + 9 + ], + [ + "BCBaAcb", + "AaC", + 11 + ], + [ + "BCBaC", + "BC", + 6 + ], + [ + "BCBaCCabc", + "aAcbC", + 12 + ], + [ + "BCBb", + "AaaBabaAa", + 14 + ], + [ + "BCBbAABB", + "A", + 14 + ], + [ + "BCBbBCaA", + "B", + 14 + ], + [ + "BCBbc", + "AbBba", + 6 + ], + [ + "BCBbcbBC", + "ca", + 14 + ], + [ + "BCBcB", + "bbC", + 7 + ], + [ + "BCBcaACa", + "bbCaabC", + 10 + ], + [ + "BCBcabB", + "aaBaaaAac", + 14 + ], + [ + "BCC", + "AabbC", + 7 + ], + [ + "BCC", + "AbbBBa", + 10 + ], + [ + "BCC", + "CCBcABb", + 11 + ], + [ + "BCCA", + "bcbbc", + 8 + ], + [ + "BCCA", + "cBBbacAc", + 11 + ], + [ + "BCCAAbbC", + "ccCB", + 12 + ], + [ + "BCCABc", + "c", + 10 + ], + [ + "BCCAaba", + "CAbB", + 8 + ], + [ + "BCCB", + "cBca", + 7 + ], + [ + "BCCBCC", + "ACCBaa", + 6 + ], + [ + "BCCBbcAAA", + "aaaCCB", + 16 + ], + [ + "BCCCAbA", + "CabCcbc", + 10 + ], + [ + "BCCCCAB", + "BC", + 10 + ], + [ + "BCCCCBAB", + "cABCcc", + 13 + ], + [ + "BCCCb", + "cCCAc", + 6 + ], + [ + "BCCaAcbB", + "Cabccaa", + 12 + ], + [ + "BCCaB", + "cAaAcAa", + 12 + ], + [ + "BCCaBABCc", + "a", + 16 + ], + [ + "BCCaCBCAA", + "cBbCaccaA", + 9 + ], + [ + "BCCac", + "CbC", + 7 + ], + [ + "BCCbAc", + "AcCAaBcCc", + 12 + ], + [ + "BCCbCbaB", + "caa", + 13 + ], + [ + "BCCbaBBbC", + "baBAB", + 11 + ], + [ + "BCCbb", + "aAAcc", + 10 + ], + [ + "BCCbbb", + "BCaB", + 7 + ], + [ + "BCCbc", + "BBaAbbBCC", + 13 + ], + [ + "BCCbc", + "caBaAbbC", + 11 + ], + [ + "BCCcaAccC", + "bacbC", + 11 + ], + [ + "BCCcbAcBa", + "CA", + 14 + ], + [ + "BCCcbaBc", + "CcCcCAba", + 9 + ], + [ + "BCCccbaC", + "C", + 14 + ], + [ + "BCa", + "CBbbAac", + 10 + ], + [ + "BCa", + "aAbCCb", + 9 + ], + [ + "BCa", + "bbcAB", + 7 + ], + [ + "BCa", + "c", + 5 + ], + [ + "BCaABBaAB", + "acCcBAC", + 13 + ], + [ + "BCaAa", + "AC", + 8 + ], + [ + "BCaAaCac", + "aaAB", + 11 + ], + [ + "BCaAba", + "a", + 10 + ], + [ + "BCaAcAbC", + "B", + 14 + ], + [ + "BCaBAC", + "bCAcCAaB", + 10 + ], + [ + "BCaBcCB", + "BaAA", + 10 + ], + [ + "BCaCAc", + "CBAaBc", + 8 + ], + [ + "BCaCCCcc", + "ccbaBCaC", + 12 + ], + [ + "BCaCbbbc", + "aaAAa", + 14 + ], + [ + "BCaa", + "bc", + 6 + ], + [ + "BCaaAbaB", + "ccCA", + 13 + ], + [ + "BCaaab", + "cAbBBa", + 11 + ], + [ + "BCaaabC", + "Bbbcb", + 10 + ], + [ + "BCaabcbA", + "BabcCAb", + 8 + ], + [ + "BCabaB", + "BaBAbcB", + 7 + ], + [ + "BCabacC", + "a", + 12 + ], + [ + "BCabbbABB", + "BBCcABb", + 10 + ], + [ + "BCabbcCCC", + "ABcCAcbc", + 13 + ], + [ + "BCabcaAAA", + "Baa", + 12 + ], + [ + "BCacBBAAB", + "aBC", + 14 + ], + [ + "BCacBBbB", + "CBCB", + 10 + ], + [ + "BCacCB", + "bB", + 9 + ], + [ + "BCacCba", + "BaBbaAAba", + 10 + ], + [ + "BCb", + "BBa", + 4 + ], + [ + "BCb", + "bBCCa", + 6 + ], + [ + "BCb", + "bCAAAAC", + 11 + ], + [ + "BCbA", + "Bccc", + 5 + ], + [ + "BCbAAC", + "aA", + 9 + ], + [ + "BCbAcbcCB", + "cbBcba", + 11 + ], + [ + "BCbBCacaC", + "AACB", + 16 + ], + [ + "BCbBa", + "cbbBC", + 6 + ], + [ + "BCbBaa", + "aCAAbACc", + 12 + ], + [ + "BCbBca", + "bBaB", + 8 + ], + [ + "BCbCA", + "cB", + 8 + ], + [ + "BCbCccA", + "aaABcCAB", + 11 + ], + [ + "BCbaAABaa", + "AA", + 14 + ], + [ + "BCbaBAb", + "cAAAcbbaA", + 15 + ], + [ + "BCbaCbBAc", + "CBCcabcAb", + 10 + ], + [ + "BCbaaCCaa", + "cCbac", + 11 + ], + [ + "BCbaabbBC", + "abcCBbB", + 11 + ], + [ + "BCbaccCC", + "bbBc", + 11 + ], + [ + "BCbbc", + "AcCbBaACc", + 11 + ], + [ + "BCbbcbbB", + "AbbCca", + 11 + ], + [ + "BCbc", + "cbcCCcBAA", + 13 + ], + [ + "BCbcBbaC", + "babCBCACb", + 9 + ], + [ + "BCbcaACBB", + "aab", + 14 + ], + [ + "BCbccccB", + "Ca", + 14 + ], + [ + "BCc", + "AAaCBcAbc", + 13 + ], + [ + "BCc", + "AcBbBbcba", + 14 + ], + [ + "BCc", + "CAcB", + 6 + ], + [ + "BCc", + "bABBC", + 7 + ], + [ + "BCcA", + "Aac", + 6 + ], + [ + "BCcA", + "bbbCc", + 7 + ], + [ + "BCcACaB", + "CBcbcaBAA", + 11 + ], + [ + "BCcACaCca", + "cca", + 12 + ], + [ + "BCcAcb", + "bbcacbb", + 6 + ], + [ + "BCcBBAccb", + "cBB", + 12 + ], + [ + "BCcBBacB", + "B", + 14 + ], + [ + "BCcBBc", + "ca", + 10 + ], + [ + "BCcBac", + "Cb", + 9 + ], + [ + "BCcBbBAb", + "BBcBBcA", + 7 + ], + [ + "BCcBbBCc", + "A", + 16 + ], + [ + "BCcBc", + "a", + 10 + ], + [ + "BCcCB", + "CABB", + 6 + ], + [ + "BCcCC", + "baB", + 9 + ], + [ + "BCcCcaaB", + "CAaa", + 10 + ], + [ + "BCca", + "aBcCcA", + 5 + ], + [ + "BCcaAc", + "aaAAA", + 9 + ], + [ + "BCcaBbAb", + "A", + 14 + ], + [ + "BCcab", + "CA", + 7 + ], + [ + "BCcacCbcc", + "CBcabaBCC", + 11 + ], + [ + "BCcb", + "CCbBACCcc", + 12 + ], + [ + "BCcb", + "Ca", + 6 + ], + [ + "BCcb", + "bC", + 5 + ], + [ + "BCcbAc", + "B", + 10 + ], + [ + "BCcbAcBAA", + "AacbBc", + 12 + ], + [ + "BCcbBac", + "Aaa", + 12 + ], + [ + "BCcbaC", + "cB", + 9 + ], + [ + "BCcbc", + "BBa", + 7 + ], + [ + "BCccAac", + "ABB", + 12 + ], + [ + "BCccBb", + "Cc", + 8 + ], + [ + "BCccCC", + "BBA", + 10 + ], + [ + "Ba", + "AAACAbbb", + 15 + ], + [ + "Ba", + "AAaBBbBaa", + 14 + ], + [ + "Ba", + "ABBaAabBa", + 14 + ], + [ + "Ba", + "AaccaB", + 10 + ], + [ + "Ba", + "AcABCBc", + 12 + ], + [ + "Ba", + "AcB", + 6 + ], + [ + "Ba", + "AcaAcb", + 10 + ], + [ + "Ba", + "B", + 2 + ], + [ + "Ba", + "BAcBc", + 7 + ], + [ + "Ba", + "Ba", + 0 + ], + [ + "Ba", + "BcAACc", + 9 + ], + [ + "Ba", + "BcCa", + 4 + ], + [ + "Ba", + "BcbBb", + 8 + ], + [ + "Ba", + "C", + 4 + ], + [ + "Ba", + "CABbaBcb", + 12 + ], + [ + "Ba", + "CBBAAB", + 9 + ], + [ + "Ba", + "CC", + 4 + ], + [ + "Ba", + "CCCcABBC", + 14 + ], + [ + "Ba", + "CbCbCa", + 9 + ], + [ + "Ba", + "Cc", + 4 + ], + [ + "Ba", + "a", + 2 + ], + [ + "Ba", + "aA", + 3 + ], + [ + "Ba", + "aB", + 4 + ], + [ + "Ba", + "aCB", + 6 + ], + [ + "Ba", + "aCbCa", + 7 + ], + [ + "Ba", + "acBbb", + 8 + ], + [ + "Ba", + "b", + 3 + ], + [ + "Ba", + "bcBCAbcCB", + 15 + ], + [ + "Ba", + "c", + 4 + ], + [ + "Ba", + "cAaAABbCB", + 16 + ], + [ + "Ba", + "cBBa", + 4 + ], + [ + "Ba", + "cbBaCAb", + 10 + ], + [ + "Ba", + "ccBcACA", + 11 + ], + [ + "Ba", + "ccC", + 6 + ], + [ + "BaA", + "CACaA", + 6 + ], + [ + "BaA", + "CBAbbaca", + 11 + ], + [ + "BaA", + "aaBB", + 6 + ], + [ + "BaA", + "bA", + 3 + ], + [ + "BaA", + "baACAbcA", + 11 + ], + [ + "BaA", + "cbc", + 6 + ], + [ + "BaA", + "ccBAAB", + 7 + ], + [ + "BaAAA", + "BB", + 8 + ], + [ + "BaAAa", + "ca", + 8 + ], + [ + "BaAAaCBaA", + "ACCC", + 14 + ], + [ + "BaAAcCA", + "abCCBA", + 9 + ], + [ + "BaAAcc", + "aaAAbac", + 6 + ], + [ + "BaAAccaCA", + "CcABcBCc", + 12 + ], + [ + "BaAB", + "BBAB", + 2 + ], + [ + "BaAB", + "ac", + 6 + ], + [ + "BaAB", + "bBB", + 5 + ], + [ + "BaABAACBA", + "bAb", + 14 + ], + [ + "BaABCaACb", + "bCbabAaBb", + 13 + ], + [ + "BaABa", + "abC", + 7 + ], + [ + "BaABcbab", + "cAaca", + 10 + ], + [ + "BaACAcCc", + "BC", + 12 + ], + [ + "BaACB", + "bcAa", + 7 + ], + [ + "BaACBAbAC", + "Bac", + 13 + ], + [ + "BaACaCbC", + "AACACCC", + 6 + ], + [ + "BaAa", + "BBCC", + 6 + ], + [ + "BaAa", + "BcbccbCC", + 14 + ], + [ + "BaAa", + "aAbB", + 6 + ], + [ + "BaAaAaAB", + "Ccab", + 13 + ], + [ + "BaAaaAAb", + "ABBCBAcB", + 13 + ], + [ + "BaAacA", + "bACCCb", + 9 + ], + [ + "BaAb", + "AbCBcCba", + 12 + ], + [ + "BaAbCBa", + "CCCcAb", + 13 + ], + [ + "BaAbab", + "aAbaBCc", + 7 + ], + [ + "BaAbcCCB", + "CBcA", + 13 + ], + [ + "BaAcAB", + "BabCCCaC", + 10 + ], + [ + "BaAcAa", + "abaCCCBAA", + 11 + ], + [ + "BaAcAbbC", + "ABaBBAC", + 10 + ], + [ + "BaAcB", + "CBAACbCa", + 9 + ], + [ + "BaAcCbb", + "Abb", + 8 + ], + [ + "BaAcCbca", + "BcCbCAAcB", + 12 + ], + [ + "BaAcbcb", + "c", + 12 + ], + [ + "BaB", + "CACAb", + 8 + ], + [ + "BaB", + "aCACaB", + 8 + ], + [ + "BaB", + "bc", + 5 + ], + [ + "BaB", + "cBBB", + 4 + ], + [ + "BaB", + "cCacaaB", + 10 + ], + [ + "BaBA", + "cABACbbA", + 10 + ], + [ + "BaBAA", + "bbAacbA", + 9 + ], + [ + "BaBAB", + "acAaABBA", + 11 + ], + [ + "BaBABabC", + "C", + 14 + ], + [ + "BaBACA", + "ACAcbbccb", + 15 + ], + [ + "BaBAc", + "BaBABaaC", + 7 + ], + [ + "BaBB", + "aBBCaA", + 8 + ], + [ + "BaBBaABA", + "AaabaABb", + 7 + ], + [ + "BaBBb", + "BC", + 8 + ], + [ + "BaBBc", + "C", + 9 + ], + [ + "BaBBcAaAc", + "C", + 17 + ], + [ + "BaBBcbcb", + "bbabb", + 10 + ], + [ + "BaBCAbab", + "A", + 14 + ], + [ + "BaBCBC", + "BA", + 9 + ], + [ + "BaBCaCac", + "cACc", + 10 + ], + [ + "BaBCc", + "cBcCbAab", + 13 + ], + [ + "BaBa", + "bBBABAabb", + 11 + ], + [ + "BaBa", + "bCAbaAbCb", + 13 + ], + [ + "BaBaBB", + "C", + 12 + ], + [ + "BaBb", + "CC", + 8 + ], + [ + "BaBb", + "bbAbCcbBc", + 13 + ], + [ + "BaBbABA", + "ababcCAc", + 11 + ], + [ + "BaBbBb", + "cCAAb", + 10 + ], + [ + "BaBbC", + "BBACac", + 8 + ], + [ + "BaBbabbCb", + "b", + 16 + ], + [ + "BaBc", + "CB", + 6 + ], + [ + "BaBcACac", + "AbCaBA", + 11 + ], + [ + "BaBcB", + "AaabaaBAa", + 13 + ], + [ + "BaBcBbbAa", + "BCACcab", + 13 + ], + [ + "BaBcCA", + "CbCACA", + 8 + ], + [ + "BaBcCA", + "bCa", + 8 + ], + [ + "BaBcaCCbB", + "BCC", + 12 + ], + [ + "BaBcacC", + "ACB", + 12 + ], + [ + "BaC", + "ABAbc", + 6 + ], + [ + "BaC", + "ABbb", + 6 + ], + [ + "BaC", + "ACa", + 5 + ], + [ + "BaC", + "Aaba", + 6 + ], + [ + "BaC", + "BACccaaBA", + 13 + ], + [ + "BaC", + "BC", + 2 + ], + [ + "BaC", + "Bccb", + 5 + ], + [ + "BaC", + "a", + 4 + ], + [ + "BaC", + "bCbbBcB", + 12 + ], + [ + "BaC", + "baBcbC", + 7 + ], + [ + "BaC", + "cBAabACAa", + 12 + ], + [ + "BaC", + "cBaBAaCc", + 10 + ], + [ + "BaCAA", + "cbbcBBbb", + 14 + ], + [ + "BaCAAbbB", + "BAcB", + 10 + ], + [ + "BaCAB", + "cC", + 8 + ], + [ + "BaCABCB", + "bB", + 11 + ], + [ + "BaCABccaB", + "CAacBCCA", + 12 + ], + [ + "BaCAaAc", + "bCa", + 9 + ], + [ + "BaCB", + "B", + 6 + ], + [ + "BaCBa", + "BbAbaBC", + 9 + ], + [ + "BaCBaCcCC", + "aCCAc", + 11 + ], + [ + "BaCBbCB", + "acB", + 9 + ], + [ + "BaCBc", + "ABCB", + 6 + ], + [ + "BaCBcBC", + "cc", + 11 + ], + [ + "BaCCAcAb", + "Bab", + 10 + ], + [ + "BaCCC", + "CcBCabAAa", + 14 + ], + [ + "BaCCCAcb", + "bbcAaA", + 12 + ], + [ + "BaCCCbb", + "bCCaaCb", + 9 + ], + [ + "BaCCbAA", + "acCBcBB", + 10 + ], + [ + "BaCCc", + "Ca", + 8 + ], + [ + "BaCCcCcc", + "baAbcaCc", + 8 + ], + [ + "BaCa", + "bbAba", + 6 + ], + [ + "BaCaAAaca", + "CCbCb", + 15 + ], + [ + "BaCaCCABa", + "bCaC", + 11 + ], + [ + "BaCb", + "bbaA", + 7 + ], + [ + "BaCb", + "cABC", + 7 + ], + [ + "BaCbAB", + "BAcbaAC", + 6 + ], + [ + "BaCbBA", + "bcAacBaa", + 10 + ], + [ + "BaCbBCaa", + "acBCAAcA", + 11 + ], + [ + "BaCbBcbB", + "bc", + 12 + ], + [ + "BaCbbbBaa", + "CcCAcCCC", + 16 + ], + [ + "BaCc", + "Bc", + 4 + ], + [ + "BaCc", + "CCBcbAAA", + 13 + ], + [ + "BaCcBbAb", + "BcaAaBa", + 11 + ], + [ + "BaCcCcab", + "abBAcBA", + 12 + ], + [ + "BaCcCcbAc", + "BacCAaaaA", + 11 + ], + [ + "BaCcaAabB", + "BBc", + 14 + ], + [ + "BaCcaBAa", + "AaCb", + 11 + ], + [ + "BaCccaaaA", + "cBacBCA", + 12 + ], + [ + "Baa", + "A", + 5 + ], + [ + "Baa", + "AcccabBa", + 12 + ], + [ + "Baa", + "BaaBCABcB", + 12 + ], + [ + "Baa", + "CAAa", + 5 + ], + [ + "Baa", + "CBBcBcC", + 12 + ], + [ + "Baa", + "CCABBacBb", + 14 + ], + [ + "Baa", + "CbABbAcbb", + 15 + ], + [ + "Baa", + "CbCaAbc", + 10 + ], + [ + "Baa", + "bBaBbabAc", + 12 + ], + [ + "Baa", + "bBccbbaAC", + 13 + ], + [ + "Baa", + "bcAbaAACA", + 14 + ], + [ + "BaaA", + "CaBBc", + 8 + ], + [ + "BaaA", + "baBabC", + 7 + ], + [ + "BaaABa", + "bCbcaa", + 9 + ], + [ + "BaaACcAAc", + "bccAaa", + 11 + ], + [ + "BaaAaCc", + "cB", + 13 + ], + [ + "BaaB", + "C", + 8 + ], + [ + "BaaB", + "cAa", + 5 + ], + [ + "BaaBAbAb", + "baccCC", + 13 + ], + [ + "BaaBBcA", + "ccC", + 12 + ], + [ + "BaaC", + "bCb", + 7 + ], + [ + "BaaC", + "cacAcCBcC", + 13 + ], + [ + "BaaCACAaB", + "cAaCabab", + 9 + ], + [ + "BaaCBCBBc", + "ac", + 14 + ], + [ + "BaaCbAC", + "AbCAbca", + 11 + ], + [ + "BaaCcCa", + "cBACb", + 11 + ], + [ + "BaaaBcCab", + "BaBbbbAaC", + 11 + ], + [ + "BaaaC", + "accb", + 8 + ], + [ + "Baaaa", + "B", + 8 + ], + [ + "Baaaa", + "CaA", + 7 + ], + [ + "BaaababB", + "bCAcBCB", + 11 + ], + [ + "BaaacbA", + "aBCba", + 8 + ], + [ + "Baab", + "cCAAcBa", + 11 + ], + [ + "Baab", + "ccaAACcAC", + 15 + ], + [ + "BaabA", + "b", + 8 + ], + [ + "BaabAA", + "A", + 10 + ], + [ + "BaabBAcC", + "aaBCaab", + 10 + ], + [ + "BaabBcc", + "cCCAaCbc", + 12 + ], + [ + "BaabCBCC", + "CcCaB", + 14 + ], + [ + "BaabCa", + "cAaAB", + 9 + ], + [ + "BaabCb", + "CA", + 10 + ], + [ + "Baabacaa", + "bAcbccB", + 10 + ], + [ + "Baabb", + "bBbAbbA", + 7 + ], + [ + "BaabbAaA", + "BBA", + 11 + ], + [ + "BaabcAb", + "aBaC", + 10 + ], + [ + "Baac", + "AaCacBCA", + 10 + ], + [ + "Baac", + "CcBaBAb", + 9 + ], + [ + "Baac", + "a", + 6 + ], + [ + "Baac", + "aaAB", + 5 + ], + [ + "Baac", + "cCcBC", + 9 + ], + [ + "Baac", + "ccCb", + 8 + ], + [ + "BaacCABbA", + "cA", + 14 + ], + [ + "Bab", + "BaCABaCa", + 11 + ], + [ + "Bab", + "C", + 6 + ], + [ + "Bab", + "a", + 4 + ], + [ + "Bab", + "acabAacac", + 14 + ], + [ + "Bab", + "bbCaccBaB", + 13 + ], + [ + "BabA", + "a", + 6 + ], + [ + "BabA", + "cbAc", + 6 + ], + [ + "BabAAccaB", + "abb", + 13 + ], + [ + "BabACA", + "b", + 10 + ], + [ + "BabAaC", + "baCCBcC", + 9 + ], + [ + "BabAb", + "Aa", + 8 + ], + [ + "BabAbACA", + "CBAaCaaa", + 12 + ], + [ + "BabAbCA", + "CccAab", + 12 + ], + [ + "BabBBAaCa", + "AcCAccAB", + 15 + ], + [ + "BabBa", + "ABbACcCcb", + 15 + ], + [ + "BabBcA", + "ACC", + 10 + ], + [ + "BabBcBcA", + "acbCABcB", + 10 + ], + [ + "BabC", + "aABb", + 6 + ], + [ + "BabCaBca", + "AA", + 14 + ], + [ + "Baba", + "BaBCbCBB", + 10 + ], + [ + "BabaBaAA", + "AaB", + 11 + ], + [ + "BabacAbAb", + "cCaA", + 14 + ], + [ + "Babb", + "CcAa", + 8 + ], + [ + "Babb", + "aaACcbc", + 10 + ], + [ + "BabbA", + "CaCb", + 6 + ], + [ + "BabbAaaBA", + "BbCcACC", + 13 + ], + [ + "BabbAccb", + "cacBB", + 11 + ], + [ + "BabbBcBA", + "cAabCbba", + 11 + ], + [ + "BabbCBb", + "aCCcBcB", + 10 + ], + [ + "BabbCCbCA", + "AbAcBa", + 12 + ], + [ + "BabbcBAAa", + "aCacA", + 12 + ], + [ + "BabcBAbcc", + "CabA", + 12 + ], + [ + "BabcCbCA", + "cbC", + 10 + ], + [ + "BabcaC", + "ABB", + 10 + ], + [ + "Babcac", + "bcccAbBC", + 11 + ], + [ + "Bac", + "BBcaBcC", + 8 + ], + [ + "Bac", + "CbcAbAbB", + 14 + ], + [ + "Bac", + "bacBAccb", + 11 + ], + [ + "Bac", + "bbACab", + 9 + ], + [ + "BacAa", + "bBCb", + 8 + ], + [ + "BacAaaCaB", + "ccaaAb", + 10 + ], + [ + "BacAb", + "aBBaBa", + 9 + ], + [ + "BacAbA", + "caAaBbCAb", + 11 + ], + [ + "BacBBa", + "AbBBAAA", + 10 + ], + [ + "BacBCAB", + "cCBaBCc", + 10 + ], + [ + "BacBab", + "CbBABcB", + 10 + ], + [ + "BacCAaBAB", + "ccAb", + 12 + ], + [ + "BacCBBCc", + "B", + 14 + ], + [ + "BacCCaA", + "bcaBA", + 9 + ], + [ + "BacCCcbB", + "cCbaaCBB", + 12 + ], + [ + "BacCa", + "cCBBB", + 10 + ], + [ + "BacCab", + "bA", + 10 + ], + [ + "BacCabcAc", + "CCbBC", + 12 + ], + [ + "BacCccBa", + "ABCBA", + 10 + ], + [ + "BacaB", + "bbac", + 7 + ], + [ + "BacaC", + "AAC", + 6 + ], + [ + "BacaCaBB", + "bB", + 13 + ], + [ + "BacaCbA", + "caBCAa", + 9 + ], + [ + "BacbB", + "CcaACc", + 10 + ], + [ + "BacbC", + "AAabcbbCB", + 10 + ], + [ + "BacbCbBca", + "cCcCC", + 13 + ], + [ + "BacbbCaAa", + "aCACaC", + 11 + ], + [ + "Bacc", + "b", + 7 + ], + [ + "BaccACa", + "B", + 12 + ], + [ + "BaccAaacb", + "A", + 16 + ], + [ + "BaccBcCBB", + "acb", + 13 + ], + [ + "BaccCB", + "BaC", + 6 + ], + [ + "Bacca", + "Ac", + 7 + ], + [ + "BaccaCC", + "CcbA", + 11 + ], + [ + "Baccb", + "aCc", + 5 + ], + [ + "Baccba", + "cbaaBcbc", + 9 + ], + [ + "Bb", + "AAABBB", + 9 + ], + [ + "Bb", + "AAccaCAaa", + 18 + ], + [ + "Bb", + "AaA", + 6 + ], + [ + "Bb", + "AaAAc", + 10 + ], + [ + "Bb", + "B", + 2 + ], + [ + "Bb", + "BACBbABA", + 12 + ], + [ + "Bb", + "BBaBb", + 6 + ], + [ + "Bb", + "BacCBA", + 9 + ], + [ + "Bb", + "BbCBCABAC", + 14 + ], + [ + "Bb", + "Bba", + 2 + ], + [ + "Bb", + "BcBAACA", + 11 + ], + [ + "Bb", + "CC", + 4 + ], + [ + "Bb", + "CcaaBa", + 10 + ], + [ + "Bb", + "a", + 4 + ], + [ + "Bb", + "aAbbb", + 7 + ], + [ + "Bb", + "aBa", + 4 + ], + [ + "Bb", + "aBbcCbAAC", + 14 + ], + [ + "Bb", + "aCCAB", + 9 + ], + [ + "Bb", + "aCccacCB", + 15 + ], + [ + "Bb", + "aacA", + 8 + ], + [ + "Bb", + "abBaBbAa", + 12 + ], + [ + "Bb", + "b", + 2 + ], + [ + "Bb", + "bAcCbc", + 9 + ], + [ + "Bb", + "bBaCBc", + 9 + ], + [ + "Bb", + "bBbBCccc", + 12 + ], + [ + "Bb", + "bCCc", + 7 + ], + [ + "Bb", + "bCaBcC", + 10 + ], + [ + "Bb", + "bCcbbc", + 9 + ], + [ + "Bb", + "baB", + 4 + ], + [ + "Bb", + "bc", + 3 + ], + [ + "Bb", + "bcCaacCC", + 15 + ], + [ + "Bb", + "bcaBccAcb", + 14 + ], + [ + "Bb", + "cab", + 4 + ], + [ + "Bb", + "cbAACCBb", + 12 + ], + [ + "Bb", + "cbabCcbb", + 13 + ], + [ + "Bb", + "cc", + 4 + ], + [ + "BbA", + "BCaAcABab", + 14 + ], + [ + "BbA", + "C", + 6 + ], + [ + "BbA", + "aacCbAc", + 10 + ], + [ + "BbA", + "cbCcbaAAA", + 13 + ], + [ + "BbAAaA", + "AbbBccC", + 11 + ], + [ + "BbAAaA", + "bBc", + 10 + ], + [ + "BbABB", + "BBAACAa", + 9 + ], + [ + "BbABBbAa", + "acaCCbbcB", + 14 + ], + [ + "BbABC", + "c", + 9 + ], + [ + "BbABa", + "accBbBcBb", + 12 + ], + [ + "BbABaacaA", + "b", + 16 + ], + [ + "BbAC", + "CaCCBcAa", + 12 + ], + [ + "BbAC", + "caAcaab", + 11 + ], + [ + "BbACAbcB", + "aaaAB", + 11 + ], + [ + "BbAa", + "ACcA", + 7 + ], + [ + "BbAa", + "cCA", + 6 + ], + [ + "BbAaAaaa", + "cBbbcCB", + 14 + ], + [ + "BbAaCab", + "cA", + 12 + ], + [ + "BbAaa", + "Bbbcacaa", + 7 + ], + [ + "BbAac", + "b", + 8 + ], + [ + "BbAb", + "CccCbabaC", + 13 + ], + [ + "BbAbC", + "CABA", + 7 + ], + [ + "BbAbC", + "ccA", + 8 + ], + [ + "BbAbCab", + "bcabABC", + 10 + ], + [ + "BbAbCcBab", + "CAaAbcbAC", + 12 + ], + [ + "BbAbCcaAC", + "ABbcCa", + 11 + ], + [ + "BbAbbcbb", + "B", + 14 + ], + [ + "BbAbc", + "aABB", + 7 + ], + [ + "BbAcaaaa", + "bBccaac", + 8 + ], + [ + "BbAcbca", + "acCCcbBCB", + 13 + ], + [ + "BbB", + "ACbcc", + 8 + ], + [ + "BbB", + "Acaca", + 10 + ], + [ + "BbB", + "bBcb", + 5 + ], + [ + "BbBA", + "CA", + 6 + ], + [ + "BbBABCcA", + "aaC", + 13 + ], + [ + "BbBAaBa", + "b", + 12 + ], + [ + "BbBAb", + "aaCCcb", + 10 + ], + [ + "BbBAbABAc", + "cBbbBCcB", + 12 + ], + [ + "BbBBCbca", + "cbBcCbC", + 7 + ], + [ + "BbBBa", + "cC", + 10 + ], + [ + "BbBBaBBba", + "bAC", + 15 + ], + [ + "BbBBabAb", + "cbB", + 12 + ], + [ + "BbBC", + "cbbbcaA", + 9 + ], + [ + "BbBCAbb", + "baCCbBbb", + 9 + ], + [ + "BbBCbAb", + "BbCcBbbac", + 9 + ], + [ + "BbBa", + "aCaaaA", + 10 + ], + [ + "BbBa", + "caCcb", + 10 + ], + [ + "BbBaC", + "BA", + 7 + ], + [ + "BbBaCbCcB", + "baAbCbaCc", + 11 + ], + [ + "BbBaaCBbc", + "bcAAAbC", + 11 + ], + [ + "BbBacBCca", + "c", + 16 + ], + [ + "BbBbA", + "BbaaA", + 4 + ], + [ + "BbBbBAb", + "CbcCbAaCc", + 13 + ], + [ + "BbBbBa", + "A", + 11 + ], + [ + "BbBbBbC", + "cBbacbBa", + 10 + ], + [ + "BbBbbbBAb", + "AabCcBa", + 13 + ], + [ + "BbBcBc", + "bcaaC", + 9 + ], + [ + "BbBcaAC", + "cB", + 12 + ], + [ + "BbBcabAa", + "BaBAaACc", + 10 + ], + [ + "BbBcbbC", + "bCBAabbaa", + 11 + ], + [ + "BbC", + "A", + 6 + ], + [ + "BbC", + "Cc", + 5 + ], + [ + "BbC", + "aAAAc", + 9 + ], + [ + "BbC", + "aAAbca", + 9 + ], + [ + "BbC", + "bAaBabC", + 8 + ], + [ + "BbC", + "bBCcCa", + 8 + ], + [ + "BbC", + "baCACBbc", + 11 + ], + [ + "BbC", + "bcBccBcBa", + 14 + ], + [ + "BbCAACcac", + "AcCbB", + 14 + ], + [ + "BbCAACcb", + "b", + 14 + ], + [ + "BbCAaCaC", + "BBc", + 12 + ], + [ + "BbCAbc", + "aaa", + 11 + ], + [ + "BbCAcCaCC", + "CCcB", + 13 + ], + [ + "BbCAcaab", + "BCbACaABc", + 9 + ], + [ + "BbCBCB", + "bAAccbCc", + 11 + ], + [ + "BbCBCbAc", + "CcACA", + 11 + ], + [ + "BbCCAAab", + "ccCCC", + 12 + ], + [ + "BbCCABABa", + "Acaab", + 14 + ], + [ + "BbCCBBb", + "aacCb", + 9 + ], + [ + "BbCCCBCC", + "BCA", + 12 + ], + [ + "BbCCa", + "aaaCAc", + 9 + ], + [ + "BbCCcCcCc", + "AaAAA", + 18 + ], + [ + "BbCCcbc", + "BaaBCc", + 9 + ], + [ + "BbCa", + "aCC", + 6 + ], + [ + "BbCaB", + "A", + 9 + ], + [ + "BbCaBAA", + "AbAABc", + 9 + ], + [ + "BbCaCbACB", + "AAA", + 15 + ], + [ + "BbCaCcC", + "aAAcA", + 11 + ], + [ + "BbCaCcaC", + "A", + 15 + ], + [ + "BbCbC", + "bAACAAcAC", + 13 + ], + [ + "BbCbCCb", + "AbBAA", + 11 + ], + [ + "BbCbaAB", + "C", + 12 + ], + [ + "BbCbaB", + "aAcC", + 11 + ], + [ + "BbCbaBB", + "Cabb", + 8 + ], + [ + "BbCbbBc", + "b", + 12 + ], + [ + "BbCbbb", + "cCcAcBAcA", + 16 + ], + [ + "BbCbcc", + "AAACbaaAa", + 14 + ], + [ + "BbCc", + "A", + 8 + ], + [ + "BbCc", + "aac", + 6 + ], + [ + "BbCcCACB", + "cB", + 12 + ], + [ + "BbCcaBBC", + "CB", + 12 + ], + [ + "BbCccBCB", + "cCcbBb", + 9 + ], + [ + "Bba", + "ABBBcACb", + 12 + ], + [ + "Bba", + "AbAcAbCcA", + 14 + ], + [ + "Bba", + "CaBCAaaaB", + 14 + ], + [ + "Bba", + "CacBBCBA", + 12 + ], + [ + "Bba", + "aBAcbCC", + 10 + ], + [ + "Bba", + "aCCcAaAc", + 14 + ], + [ + "Bba", + "abcA", + 5 + ], + [ + "Bba", + "bcCa", + 5 + ], + [ + "BbaAB", + "BbB", + 4 + ], + [ + "BbaABacc", + "bccbc", + 11 + ], + [ + "BbaAbBCAA", + "caAcCbc", + 12 + ], + [ + "BbaAcAb", + "bacACCbC", + 9 + ], + [ + "BbaB", + "aBbAaCb", + 7 + ], + [ + "BbaB", + "bBbBAbBC", + 9 + ], + [ + "BbaBCB", + "bcA", + 9 + ], + [ + "BbaBcbacc", + "CCBAC", + 14 + ], + [ + "BbaC", + "C", + 6 + ], + [ + "BbaCBC", + "C", + 10 + ], + [ + "BbaCCCb", + "Cca", + 11 + ], + [ + "BbaCa", + "AcCC", + 8 + ], + [ + "BbaCa", + "ccbA", + 9 + ], + [ + "BbaCcBba", + "ACb", + 11 + ], + [ + "BbaCcC", + "cbCCAAbcc", + 11 + ], + [ + "Bbaa", + "abbaAA", + 6 + ], + [ + "BbaaAbAA", + "Acc", + 14 + ], + [ + "BbaaBAb", + "CBbaCbaBB", + 9 + ], + [ + "BbaacA", + "ccAbCabAa", + 12 + ], + [ + "BbaacBcbC", + "cabbCaC", + 12 + ], + [ + "Bbab", + "BCBb", + 4 + ], + [ + "BbabA", + "Cbc", + 8 + ], + [ + "BbabBc", + "AcA", + 11 + ], + [ + "BbabC", + "ab", + 6 + ], + [ + "BbabCcBA", + "AabACBc", + 9 + ], + [ + "Bbaba", + "AAa", + 7 + ], + [ + "BbabbBb", + "b", + 12 + ], + [ + "Bbac", + "bbb", + 5 + ], + [ + "BbacB", + "CBcBB", + 7 + ], + [ + "BbacCc", + "Cb", + 10 + ], + [ + "Bbacaa", + "AaAaac", + 8 + ], + [ + "Bbb", + "ACCCCc", + 12 + ], + [ + "Bbb", + "BCABAa", + 9 + ], + [ + "Bbb", + "BabbbBcCA", + 12 + ], + [ + "Bbb", + "acaCCaa", + 14 + ], + [ + "Bbb", + "bAAcBa", + 10 + ], + [ + "Bbb", + "ccacA", + 10 + ], + [ + "BbbA", + "ACccA", + 8 + ], + [ + "BbbAAB", + "baBAb", + 7 + ], + [ + "BbbABccc", + "AbaABca", + 8 + ], + [ + "BbbAC", + "bcAaBBBca", + 14 + ], + [ + "BbbAaAba", + "a", + 14 + ], + [ + "BbbB", + "Bcc", + 6 + ], + [ + "BbbBCCA", + "cBBb", + 11 + ], + [ + "BbbBCba", + "BA", + 11 + ], + [ + "BbbBcaa", + "b", + 12 + ], + [ + "BbbCAaA", + "cbbBaBaCA", + 9 + ], + [ + "BbbCAb", + "AACC", + 10 + ], + [ + "BbbCAc", + "cbaB", + 9 + ], + [ + "BbbCBcac", + "bAbaBCba", + 10 + ], + [ + "BbbCCB", + "C", + 10 + ], + [ + "BbbCCBAc", + "cbbBcCCAC", + 8 + ], + [ + "Bbba", + "AAaAB", + 9 + ], + [ + "Bbba", + "abAc", + 6 + ], + [ + "BbbaAC", + "aBABcAAaB", + 12 + ], + [ + "BbbaC", + "AbBaaAaA", + 11 + ], + [ + "BbbaabCCA", + "CbcAb", + 13 + ], + [ + "BbbacCbb", + "AaccA", + 11 + ], + [ + "BbbbCAaA", + "cACCaCcAC", + 15 + ], + [ + "BbbbbAc", + "AbbcCb", + 10 + ], + [ + "BbbbcA", + "AaCcBabb", + 14 + ], + [ + "BbbbcbbA", + "bAA", + 12 + ], + [ + "Bbbc", + "CbccaAc", + 10 + ], + [ + "BbbcABb", + "bbbcc", + 7 + ], + [ + "BbbcB", + "bbacbbc", + 8 + ], + [ + "BbbcbAcbB", + "aCaCbaAc", + 13 + ], + [ + "Bbbcbcab", + "caCaAAbc", + 14 + ], + [ + "BbcA", + "CBaA", + 5 + ], + [ + "BbcA", + "CBcAB", + 5 + ], + [ + "BbcABcB", + "AcA", + 10 + ], + [ + "BbcACB", + "BaaCCBBC", + 10 + ], + [ + "BbcACCcB", + "bcbbaaBba", + 14 + ], + [ + "BbcAbCa", + "CbbaCba", + 9 + ], + [ + "BbcAcaB", + "Aca", + 8 + ], + [ + "BbcAccCab", + "abCCaA", + 11 + ], + [ + "BbcB", + "aACCccCaA", + 16 + ], + [ + "BbcBbB", + "baacAca", + 11 + ], + [ + "BbcBbbaC", + "Ab", + 14 + ], + [ + "BbcC", + "AccAcaBaC", + 14 + ], + [ + "BbcCB", + "bBca", + 6 + ], + [ + "BbcCBaB", + "AcCcaCbb", + 11 + ], + [ + "BbcCaab", + "cACaC", + 10 + ], + [ + "BbcaBbCCb", + "acBBcc", + 11 + ], + [ + "BbcaCcaa", + "AbcccaBB", + 9 + ], + [ + "BbcaaACb", + "A", + 14 + ], + [ + "BbcbACAa", + "a", + 14 + ], + [ + "BbcbBCCA", + "AcaCB", + 12 + ], + [ + "BbcbCcCCc", + "a", + 18 + ], + [ + "Bbcbaa", + "a", + 10 + ], + [ + "BbcbbbBab", + "aaBcBcCB", + 14 + ], + [ + "BbcbccB", + "bAACb", + 10 + ], + [ + "Bbcc", + "caAACBBb", + 15 + ], + [ + "BbccBcb", + "BCAbccb", + 8 + ], + [ + "BbccC", + "CaaAC", + 8 + ], + [ + "Bbcca", + "bBcb", + 6 + ], + [ + "BbccccCC", + "aAbcc", + 12 + ], + [ + "Bc", + "A", + 4 + ], + [ + "Bc", + "AB", + 4 + ], + [ + "Bc", + "ABAccAcC", + 12 + ], + [ + "Bc", + "ABBbBBbb", + 14 + ], + [ + "Bc", + "AaA", + 6 + ], + [ + "Bc", + "AaaBaCcCc", + 14 + ], + [ + "Bc", + "AabBBC", + 9 + ], + [ + "Bc", + "Aac", + 4 + ], + [ + "Bc", + "Aba", + 5 + ], + [ + "Bc", + "Abccbabbc", + 15 + ], + [ + "Bc", + "AcAbBC", + 9 + ], + [ + "Bc", + "B", + 2 + ], + [ + "Bc", + "BACaACBC", + 13 + ], + [ + "Bc", + "BBcBCbCB", + 12 + ], + [ + "Bc", + "BcBAAAaA", + 12 + ], + [ + "Bc", + "BcaaABCcc", + 14 + ], + [ + "Bc", + "C", + 3 + ], + [ + "Bc", + "CBCccCbaA", + 14 + ], + [ + "Bc", + "CCaBABaBA", + 16 + ], + [ + "Bc", + "CaBCBbBbc", + 14 + ], + [ + "Bc", + "CbaBCbb", + 11 + ], + [ + "Bc", + "a", + 4 + ], + [ + "Bc", + "aC", + 3 + ], + [ + "Bc", + "abAbBBcc", + 12 + ], + [ + "Bc", + "abaCAABA", + 14 + ], + [ + "Bc", + "abaabAbc", + 13 + ], + [ + "Bc", + "abcbBBB", + 11 + ], + [ + "Bc", + "ac", + 2 + ], + [ + "Bc", + "acCCcb", + 10 + ], + [ + "Bc", + "acCacaaAa", + 16 + ], + [ + "Bc", + "ba", + 3 + ], + [ + "Bc", + "cC", + 3 + ], + [ + "Bc", + "cb", + 4 + ], + [ + "Bc", + "cbACCabca", + 15 + ], + [ + "BcA", + "AC", + 5 + ], + [ + "BcA", + "BAaB", + 5 + ], + [ + "BcA", + "BBc", + 4 + ], + [ + "BcA", + "CBababB", + 11 + ], + [ + "BcA", + "CcB", + 4 + ], + [ + "BcA", + "CcCb", + 6 + ], + [ + "BcA", + "a", + 5 + ], + [ + "BcA", + "bAcab", + 6 + ], + [ + "BcA", + "bBAbb", + 7 + ], + [ + "BcA", + "bbbc", + 7 + ], + [ + "BcA", + "c", + 4 + ], + [ + "BcAABaB", + "bACcAc", + 10 + ], + [ + "BcAAaA", + "BcCAbaBb", + 8 + ], + [ + "BcAB", + "aBCCcACc", + 10 + ], + [ + "BcABAc", + "BaAa", + 7 + ], + [ + "BcABaAaA", + "aCCaCcb", + 13 + ], + [ + "BcABaa", + "CaaBBaa", + 7 + ], + [ + "BcAC", + "BCAbcbCAa", + 11 + ], + [ + "BcACAA", + "aCb", + 9 + ], + [ + "BcACB", + "bCcC", + 6 + ], + [ + "BcACBaBCa", + "BCcBAbACc", + 10 + ], + [ + "BcACC", + "aa", + 9 + ], + [ + "BcAa", + "Cb", + 7 + ], + [ + "BcAaA", + "CBBc", + 9 + ], + [ + "BcAaA", + "abBbBBcB", + 14 + ], + [ + "BcAaACA", + "cbCABAaCb", + 10 + ], + [ + "BcAaCCBB", + "cBbCaBbA", + 11 + ], + [ + "BcAaCbB", + "ACB", + 8 + ], + [ + "BcAaaaC", + "cC", + 10 + ], + [ + "BcAb", + "BB", + 5 + ], + [ + "BcAb", + "CC", + 7 + ], + [ + "BcAbAbCac", + "bab", + 13 + ], + [ + "BcAbB", + "B", + 8 + ], + [ + "BcAbabBA", + "acb", + 12 + ], + [ + "BcAbabBBB", + "BA", + 14 + ], + [ + "BcAbabC", + "BBbaCAB", + 10 + ], + [ + "BcAbbcC", + "AaAcbC", + 8 + ], + [ + "BcAbc", + "BAC", + 5 + ], + [ + "BcAbc", + "BbbcbBabB", + 11 + ], + [ + "BcAbcAAC", + "A", + 14 + ], + [ + "BcAc", + "bC", + 6 + ], + [ + "BcAcAaACb", + "aAbBBB", + 14 + ], + [ + "BcAcB", + "caaAbbccB", + 12 + ], + [ + "BcAcaccb", + "cbAbAb", + 11 + ], + [ + "BcAcba", + "aA", + 10 + ], + [ + "BcAcc", + "BCaCBcAcC", + 9 + ], + [ + "BcB", + "AcCCAC", + 10 + ], + [ + "BcB", + "BBAcaAaB", + 10 + ], + [ + "BcB", + "BabAcacCA", + 14 + ], + [ + "BcB", + "aaBcAb", + 7 + ], + [ + "BcB", + "abcC", + 5 + ], + [ + "BcB", + "bcBBCbab", + 11 + ], + [ + "BcB", + "cAAc", + 8 + ], + [ + "BcB", + "ca", + 4 + ], + [ + "BcB", + "caBaaAAb", + 13 + ], + [ + "BcBA", + "CAabC", + 9 + ], + [ + "BcBA", + "baaC", + 7 + ], + [ + "BcBAAc", + "cBBaaabBB", + 14 + ], + [ + "BcBAB", + "aCaAaBb", + 9 + ], + [ + "BcBABCB", + "aaB", + 11 + ], + [ + "BcBAccAc", + "c", + 14 + ], + [ + "BcBBBA", + "ACc", + 11 + ], + [ + "BcBBC", + "cCABb", + 7 + ], + [ + "BcBBbb", + "bbBAa", + 8 + ], + [ + "BcBBbcAaA", + "CA", + 15 + ], + [ + "BcBC", + "c", + 6 + ], + [ + "BcBCA", + "cAaCC", + 8 + ], + [ + "BcBCAAAcc", + "abc", + 15 + ], + [ + "BcBCBBC", + "BbC", + 9 + ], + [ + "BcBCbAc", + "cBBCaC", + 8 + ], + [ + "BcBCcbccc", + "BcBC", + 10 + ], + [ + "BcBCccAa", + "acb", + 13 + ], + [ + "BcBa", + "aCB", + 5 + ], + [ + "BcBaAcAAc", + "bccBBBcBc", + 11 + ], + [ + "BcBaC", + "acBbcABAa", + 11 + ], + [ + "BcBab", + "CbCACC", + 10 + ], + [ + "BcBb", + "acAABAA", + 10 + ], + [ + "BcBbA", + "Ccba", + 5 + ], + [ + "BcBbAbABB", + "a", + 17 + ], + [ + "BcBbbCAa", + "baACcBCcC", + 14 + ], + [ + "BcBbbCa", + "AcCBAa", + 9 + ], + [ + "BcBbc", + "CcABb", + 6 + ], + [ + "BcBc", + "cBBcc", + 6 + ], + [ + "BcBcAbbc", + "babC", + 11 + ], + [ + "BcBcBc", + "cAAc", + 8 + ], + [ + "BcC", + "ABabcbC", + 8 + ], + [ + "BcC", + "Ac", + 4 + ], + [ + "BcC", + "C", + 4 + ], + [ + "BcC", + "acbcaAaa", + 13 + ], + [ + "BcC", + "bAbB", + 7 + ], + [ + "BcCA", + "ccaBaaAac", + 14 + ], + [ + "BcCAABBB", + "BCabBB", + 6 + ], + [ + "BcCAaAC", + "acCaB", + 8 + ], + [ + "BcCAaBc", + "Bcab", + 7 + ], + [ + "BcCAbB", + "ACaccCB", + 10 + ], + [ + "BcCAbaACc", + "aCAAcCBC", + 12 + ], + [ + "BcCAbcbA", + "bccAbCC", + 7 + ], + [ + "BcCAcA", + "BbB", + 10 + ], + [ + "BcCBABA", + "accb", + 10 + ], + [ + "BcCBAaC", + "b", + 13 + ], + [ + "BcCBbabcc", + "cCb", + 12 + ], + [ + "BcCBc", + "ba", + 9 + ], + [ + "BcCBcaAcc", + "B", + 16 + ], + [ + "BcCBcaCbC", + "CA", + 15 + ], + [ + "BcCCAA", + "caaA", + 7 + ], + [ + "BcCCBaaa", + "AaaCBb", + 12 + ], + [ + "BcCCCAA", + "b", + 13 + ], + [ + "BcCCaaaA", + "BccaAabBa", + 9 + ], + [ + "BcCCbCac", + "AcAa", + 12 + ], + [ + "BcCa", + "AB", + 8 + ], + [ + "BcCa", + "cB", + 6 + ], + [ + "BcCaACC", + "cbACaA", + 9 + ], + [ + "BcCaACCc", + "aaaCb", + 11 + ], + [ + "BcCaBbCAC", + "AbaAc", + 12 + ], + [ + "BcCaBc", + "CCAAB", + 8 + ], + [ + "BcCaCacc", + "CaCbbbc", + 10 + ], + [ + "BcCaaC", + "AcC", + 8 + ], + [ + "BcCb", + "aBacB", + 6 + ], + [ + "BcCbAcCb", + "CAA", + 12 + ], + [ + "BcCbCCCa", + "CBCC", + 9 + ], + [ + "BcCbaBabc", + "abcbB", + 13 + ], + [ + "BcCbbb", + "ccBCb", + 6 + ], + [ + "BcCc", + "bBb", + 7 + ], + [ + "BcCcBBb", + "aCCC", + 10 + ], + [ + "BcCcBcAb", + "aacbBbC", + 13 + ], + [ + "BcCca", + "CCcCaaB", + 8 + ], + [ + "Bca", + "AcbCBab", + 10 + ], + [ + "Bca", + "Bb", + 4 + ], + [ + "Bca", + "Bcc", + 2 + ], + [ + "Bca", + "CAAbA", + 9 + ], + [ + "Bca", + "CcBc", + 6 + ], + [ + "Bca", + "aAAccCBB", + 14 + ], + [ + "Bca", + "aCbbBBcCb", + 14 + ], + [ + "Bca", + "ac", + 4 + ], + [ + "Bca", + "c", + 4 + ], + [ + "BcaAAbACa", + "cAaacBB", + 13 + ], + [ + "BcaAaC", + "B", + 10 + ], + [ + "BcaB", + "A", + 7 + ], + [ + "BcaB", + "ABC", + 7 + ], + [ + "BcaB", + "AcAacA", + 8 + ], + [ + "BcaB", + "CAba", + 7 + ], + [ + "BcaB", + "cc", + 6 + ], + [ + "BcaBACC", + "aabAcbb", + 10 + ], + [ + "BcaBACbA", + "cB", + 12 + ], + [ + "BcaBAc", + "CAcBaCC", + 10 + ], + [ + "BcaBb", + "bABA", + 6 + ], + [ + "BcaBcab", + "aAaA", + 10 + ], + [ + "BcaC", + "abbAb", + 8 + ], + [ + "BcaC", + "ba", + 5 + ], + [ + "BcaC", + "ccaCBCB", + 8 + ], + [ + "BcaCBAbA", + "BA", + 12 + ], + [ + "BcaCC", + "CAbBbB", + 12 + ], + [ + "BcaCCbb", + "bbb", + 9 + ], + [ + "BcaCc", + "AaCABAACA", + 13 + ], + [ + "Bcaa", + "C", + 7 + ], + [ + "Bcaa", + "CbBABaa", + 8 + ], + [ + "Bcaa", + "cbbBcc", + 10 + ], + [ + "BcaaAc", + "AcaCCb", + 8 + ], + [ + "BcaaBBa", + "bBBCAAb", + 12 + ], + [ + "BcaaBcB", + "cCBbbAAcA", + 13 + ], + [ + "Bcaaba", + "ACbcA", + 10 + ], + [ + "Bcaabc", + "Bba", + 8 + ], + [ + "BcaacbcC", + "CBBBbCCA", + 12 + ], + [ + "Bcab", + "AcABabB", + 8 + ], + [ + "Bcab", + "abA", + 6 + ], + [ + "BcabB", + "BcbCc", + 6 + ], + [ + "BcabBB", + "BbAbbbA", + 7 + ], + [ + "BcabCA", + "b", + 10 + ], + [ + "BcabCac", + "BbAAaca", + 9 + ], + [ + "Bcaba", + "aCcbA", + 6 + ], + [ + "BcabaABA", + "CAbB", + 10 + ], + [ + "Bcac", + "CcCAbaaa", + 12 + ], + [ + "Bcac", + "ccc", + 4 + ], + [ + "BcacAC", + "abBc", + 9 + ], + [ + "BcacAaca", + "acbAbc", + 10 + ], + [ + "BcacCB", + "cbabacC", + 9 + ], + [ + "BcacaBC", + "ACCac", + 9 + ], + [ + "BcacabbA", + "Bcb", + 10 + ], + [ + "Bcacc", + "b", + 9 + ], + [ + "Bcb", + "AaAcacaB", + 13 + ], + [ + "Bcb", + "Cc", + 4 + ], + [ + "Bcb", + "aBBC", + 6 + ], + [ + "BcbAACc", + "aBBcA", + 11 + ], + [ + "BcbAAb", + "ab", + 9 + ], + [ + "BcbAC", + "AcC", + 6 + ], + [ + "BcbAaaacc", + "cc", + 14 + ], + [ + "BcbB", + "BbcbBbBC", + 8 + ], + [ + "BcbB", + "aB", + 6 + ], + [ + "BcbBcB", + "bCbb", + 7 + ], + [ + "BcbCA", + "bCc", + 6 + ], + [ + "BcbCAAba", + "CCaa", + 10 + ], + [ + "BcbCBCA", + "BcBa", + 7 + ], + [ + "BcbCC", + "b", + 8 + ], + [ + "BcbCCcc", + "Abb", + 12 + ], + [ + "BcbCabC", + "A", + 13 + ], + [ + "BcbCcB", + "cbaccCa", + 9 + ], + [ + "Bcba", + "ACa", + 5 + ], + [ + "Bcbb", + "baaAa", + 9 + ], + [ + "BcbbA", + "BBb", + 5 + ], + [ + "BcbbC", + "ccaBAABCC", + 12 + ], + [ + "BcbcA", + "bcBcAAcB", + 8 + ], + [ + "BcbcB", + "Ccc", + 6 + ], + [ + "Bcc", + "Ab", + 6 + ], + [ + "Bcc", + "BCAbacBc", + 10 + ], + [ + "Bcc", + "aacb", + 6 + ], + [ + "Bcc", + "baAa", + 7 + ], + [ + "BccABAbcA", + "Aba", + 13 + ], + [ + "BccACA", + "aa", + 10 + ], + [ + "BccAcAbbC", + "caC", + 13 + ], + [ + "BccBA", + "BACCAC", + 7 + ], + [ + "BccBAAbb", + "aac", + 14 + ], + [ + "BccBCbAA", + "BBCCC", + 10 + ], + [ + "BccBaAaa", + "AACAbbbbB", + 16 + ], + [ + "BccBac", + "CCabACa", + 10 + ], + [ + "BccC", + "ac", + 6 + ], + [ + "BccC", + "bCA", + 6 + ], + [ + "BccCa", + "caaBBaaB", + 14 + ], + [ + "BccCab", + "Cbcbac", + 8 + ], + [ + "BccCacBC", + "BBbA", + 13 + ], + [ + "BccCcA", + "BcCBCAB", + 6 + ], + [ + "Bcca", + "AAb", + 8 + ], + [ + "BccaA", + "cCC", + 7 + ], + [ + "BccaA", + "ccc", + 6 + ], + [ + "BccaBbB", + "AA", + 13 + ], + [ + "Bccac", + "CcbaCCa", + 9 + ], + [ + "Bccb", + "AcbC", + 6 + ], + [ + "BccbB", + "bbccA", + 7 + ], + [ + "BccbBCAA", + "AA", + 12 + ], + [ + "BccbBaCbb", + "CbcBBCAA", + 11 + ], + [ + "BccbacAAc", + "CAac", + 12 + ], + [ + "BccbbACa", + "acCAbCAc", + 10 + ], + [ + "BcccAC", + "cccBbBaac", + 12 + ], + [ + "BcccBB", + "bABCc", + 10 + ], + [ + "BcccBBb", + "Cbacbaa", + 11 + ], + [ + "C", + "A", + 2 + ], + [ + "C", + "AAA", + 6 + ], + [ + "C", + "AAAb", + 8 + ], + [ + "C", + "AAB", + 6 + ], + [ + "C", + "AAacba", + 11 + ], + [ + "C", + "AAbb", + 8 + ], + [ + "C", + "ABA", + 6 + ], + [ + "C", + "ABAB", + 8 + ], + [ + "C", + "ABAcBAabA", + 17 + ], + [ + "C", + "ABCB", + 6 + ], + [ + "C", + "ABCbbbBAC", + 16 + ], + [ + "C", + "ABabc", + 9 + ], + [ + "C", + "ACCCcAcAa", + 16 + ], + [ + "C", + "ACc", + 4 + ], + [ + "C", + "ACcbaABc", + 14 + ], + [ + "C", + "AaAAa", + 10 + ], + [ + "C", + "AaAa", + 8 + ], + [ + "C", + "AaAbcaBb", + 15 + ], + [ + "C", + "AabbbC", + 10 + ], + [ + "C", + "AacCCABaB", + 16 + ], + [ + "C", + "AacaaaB", + 13 + ], + [ + "C", + "Ab", + 4 + ], + [ + "C", + "AbBbBACab", + 16 + ], + [ + "C", + "AbBcCcBAb", + 16 + ], + [ + "C", + "AbC", + 4 + ], + [ + "C", + "AbCCaCbc", + 14 + ], + [ + "C", + "Abb", + 6 + ], + [ + "C", + "AbbCcBb", + 12 + ], + [ + "C", + "Acbc", + 7 + ], + [ + "C", + "B", + 2 + ], + [ + "C", + "BAAbAbCa", + 14 + ], + [ + "C", + "BAAc", + 7 + ], + [ + "C", + "BACcBbAcB", + 16 + ], + [ + "C", + "BBBaAcB", + 13 + ], + [ + "C", + "BBacaaA", + 13 + ], + [ + "C", + "BC", + 2 + ], + [ + "C", + "BCCbA", + 8 + ], + [ + "C", + "BCba", + 6 + ], + [ + "C", + "Ba", + 4 + ], + [ + "C", + "BaA", + 6 + ], + [ + "C", + "BaBCCBcb", + 14 + ], + [ + "C", + "BaBcbbCBA", + 16 + ], + [ + "C", + "BaaC", + 6 + ], + [ + "C", + "BabbcCBa", + 14 + ], + [ + "C", + "BacccCB", + 12 + ], + [ + "C", + "BbABc", + 9 + ], + [ + "C", + "BbAaAAC", + 12 + ], + [ + "C", + "BbBBcc", + 11 + ], + [ + "C", + "BbCBCB", + 10 + ], + [ + "C", + "BbcCCbAC", + 14 + ], + [ + "C", + "BcB", + 5 + ], + [ + "C", + "BcBBBbAaa", + 17 + ], + [ + "C", + "BcCAcacAB", + 16 + ], + [ + "C", + "BcCB", + 6 + ], + [ + "C", + "BcacCaB", + 12 + ], + [ + "C", + "BccAaa", + 11 + ], + [ + "C", + "BccaAa", + 11 + ], + [ + "C", + "C", + 0 + ], + [ + "C", + "CA", + 2 + ], + [ + "C", + "CAAbCa", + 10 + ], + [ + "C", + "CABBB", + 8 + ], + [ + "C", + "CAaAa", + 8 + ], + [ + "C", + "CAbAABb", + 12 + ], + [ + "C", + "CBBCaABbB", + 16 + ], + [ + "C", + "CBaacB", + 10 + ], + [ + "C", + "CBc", + 4 + ], + [ + "C", + "CC", + 2 + ], + [ + "C", + "CCA", + 4 + ], + [ + "C", + "CCBbccA", + 12 + ], + [ + "C", + "CCc", + 4 + ], + [ + "C", + "CCcbbCBCc", + 16 + ], + [ + "C", + "CCcc", + 6 + ], + [ + "C", + "CCccCaCa", + 14 + ], + [ + "C", + "Ca", + 2 + ], + [ + "C", + "CaA", + 4 + ], + [ + "C", + "Caab", + 6 + ], + [ + "C", + "Cacaacba", + 14 + ], + [ + "C", + "Cb", + 2 + ], + [ + "C", + "CbaCBcAb", + 14 + ], + [ + "C", + "CbbBCbC", + 12 + ], + [ + "C", + "Cc", + 2 + ], + [ + "C", + "CcAcCA", + 10 + ], + [ + "C", + "CcBBCbBB", + 14 + ], + [ + "C", + "CcCBBbB", + 12 + ], + [ + "C", + "a", + 2 + ], + [ + "C", + "aA", + 4 + ], + [ + "C", + "aAABBb", + 12 + ], + [ + "C", + "aACBaca", + 12 + ], + [ + "C", + "aAaCB", + 8 + ], + [ + "C", + "aAaaBcaB", + 15 + ], + [ + "C", + "aAabb", + 10 + ], + [ + "C", + "aAccAABB", + 15 + ], + [ + "C", + "aBAaa", + 10 + ], + [ + "C", + "aBbab", + 10 + ], + [ + "C", + "aCBccCbBc", + 16 + ], + [ + "C", + "aCCBcbcBc", + 16 + ], + [ + "C", + "aCCC", + 6 + ], + [ + "C", + "aCcB", + 6 + ], + [ + "C", + "aCcccA", + 10 + ], + [ + "C", + "aa", + 4 + ], + [ + "C", + "aaBA", + 8 + ], + [ + "C", + "aaBAbA", + 12 + ], + [ + "C", + "aaBabBB", + 14 + ], + [ + "C", + "aaCAC", + 8 + ], + [ + "C", + "aaCBb", + 8 + ], + [ + "C", + "aaaBcBBc", + 15 + ], + [ + "C", + "aaab", + 8 + ], + [ + "C", + "aab", + 6 + ], + [ + "C", + "aacCCabb", + 14 + ], + [ + "C", + "abBbAcaCc", + 16 + ], + [ + "C", + "abbbAaaC", + 14 + ], + [ + "C", + "abcBBB", + 11 + ], + [ + "C", + "ac", + 3 + ], + [ + "C", + "b", + 2 + ], + [ + "C", + "bAAAccb", + 13 + ], + [ + "C", + "bAAaCBaCa", + 16 + ], + [ + "C", + "bAaABACCb", + 16 + ], + [ + "C", + "bAbAcCAc", + 14 + ], + [ + "C", + "bBABA", + 10 + ], + [ + "C", + "bBB", + 6 + ], + [ + "C", + "bBacA", + 9 + ], + [ + "C", + "bBcbbCabb", + 16 + ], + [ + "C", + "bC", + 2 + ], + [ + "C", + "bCcAcACba", + 16 + ], + [ + "C", + "ba", + 4 + ], + [ + "C", + "baAA", + 8 + ], + [ + "C", + "baAba", + 10 + ], + [ + "C", + "baCABab", + 12 + ], + [ + "C", + "baaA", + 8 + ], + [ + "C", + "baaB", + 8 + ], + [ + "C", + "baaCbCb", + 12 + ], + [ + "C", + "bbABBCA", + 12 + ], + [ + "C", + "bbABcCb", + 12 + ], + [ + "C", + "bbCab", + 8 + ], + [ + "C", + "bbacCaabC", + 16 + ], + [ + "C", + "bbbcaAb", + 13 + ], + [ + "C", + "bc", + 3 + ], + [ + "C", + "bcAca", + 9 + ], + [ + "C", + "bcBAABAAC", + 16 + ], + [ + "C", + "bcBcA", + 9 + ], + [ + "C", + "bcC", + 4 + ], + [ + "C", + "bcCAb", + 8 + ], + [ + "C", + "bcaAb", + 9 + ], + [ + "C", + "bcacBAC", + 12 + ], + [ + "C", + "bcb", + 5 + ], + [ + "C", + "bcbBba", + 11 + ], + [ + "C", + "bcbacaAA", + 15 + ], + [ + "C", + "bccC", + 6 + ], + [ + "C", + "bccccCA", + 12 + ], + [ + "C", + "c", + 1 + ], + [ + "C", + "cAc", + 5 + ], + [ + "C", + "cAcBCbCb", + 14 + ], + [ + "C", + "cAcaABCA", + 14 + ], + [ + "C", + "cBAA", + 7 + ], + [ + "C", + "cBBB", + 7 + ], + [ + "C", + "cBc", + 5 + ], + [ + "C", + "cBccbAA", + 13 + ], + [ + "C", + "cC", + 2 + ], + [ + "C", + "cCBAAB", + 10 + ], + [ + "C", + "cCaACAAC", + 14 + ], + [ + "C", + "cCbA", + 6 + ], + [ + "C", + "cCbbABa", + 12 + ], + [ + "C", + "cCcabCbBb", + 16 + ], + [ + "C", + "ca", + 3 + ], + [ + "C", + "caCACCCaB", + 16 + ], + [ + "C", + "cabCa", + 8 + ], + [ + "C", + "cacACaBB", + 14 + ], + [ + "C", + "cacBaACc", + 14 + ], + [ + "C", + "cbACabc", + 12 + ], + [ + "C", + "cbCCB", + 8 + ], + [ + "C", + "cbcC", + 6 + ], + [ + "C", + "cc", + 3 + ], + [ + "C", + "ccBAbBBC", + 14 + ], + [ + "C", + "ccBaC", + 8 + ], + [ + "C", + "ccaCbbCbb", + 16 + ], + [ + "C", + "ccabC", + 8 + ], + [ + "C", + "ccbBbCCc", + 14 + ], + [ + "CA", + "A", + 2 + ], + [ + "CA", + "AAa", + 4 + ], + [ + "CA", + "Aaacbb", + 11 + ], + [ + "CA", + "AcC", + 5 + ], + [ + "CA", + "BBaB", + 7 + ], + [ + "CA", + "BcAcbBC", + 11 + ], + [ + "CA", + "C", + 2 + ], + [ + "CA", + "CBCAa", + 6 + ], + [ + "CA", + "CacbbBaa", + 13 + ], + [ + "CA", + "CcBcBAB", + 10 + ], + [ + "CA", + "CcbCaBB", + 11 + ], + [ + "CA", + "a", + 3 + ], + [ + "CA", + "aAABAaC", + 12 + ], + [ + "CA", + "aABBa", + 8 + ], + [ + "CA", + "abbCC", + 8 + ], + [ + "CA", + "acbb", + 7 + ], + [ + "CA", + "bAbAAcbA", + 13 + ], + [ + "CA", + "bAcBcACC", + 13 + ], + [ + "CA", + "bCBaBBaB", + 13 + ], + [ + "CA", + "bbbB", + 8 + ], + [ + "CA", + "cAaaaA", + 9 + ], + [ + "CA", + "caCBCcaaA", + 14 + ], + [ + "CAA", + "CCbc", + 6 + ], + [ + "CAA", + "CbCcba", + 9 + ], + [ + "CAA", + "bb", + 6 + ], + [ + "CAA", + "c", + 5 + ], + [ + "CAA", + "cACAaa", + 7 + ], + [ + "CAA", + "cAaabbacA", + 13 + ], + [ + "CAAA", + "bb", + 8 + ], + [ + "CAAAAAcCB", + "bC", + 16 + ], + [ + "CAAAB", + "ba", + 9 + ], + [ + "CAAABaBAc", + "CaaC", + 12 + ], + [ + "CAAACa", + "AAcbAAc", + 9 + ], + [ + "CAAACaAC", + "aABBcbcBa", + 15 + ], + [ + "CAAAaBAa", + "BCBc", + 14 + ], + [ + "CAAAba", + "CacBaB", + 8 + ], + [ + "CAAAbb", + "cCaCb", + 8 + ], + [ + "CAAB", + "CbcCbBBA", + 12 + ], + [ + "CAABAAcBC", + "bccb", + 14 + ], + [ + "CAABAAcbB", + "ABBa", + 13 + ], + [ + "CAABCaaBa", + "aBCACcBca", + 12 + ], + [ + "CAABCcAAa", + "ccCB", + 15 + ], + [ + "CAABbaA", + "AbBaAac", + 10 + ], + [ + "CAAC", + "cacABc", + 7 + ], + [ + "CAACAAC", + "Ab", + 12 + ], + [ + "CAACAbca", + "Bb", + 14 + ], + [ + "CAACCAc", + "CAAB", + 8 + ], + [ + "CAACb", + "CA", + 6 + ], + [ + "CAAa", + "cBCC", + 7 + ], + [ + "CAAaBaAC", + "AaccBBB", + 13 + ], + [ + "CAAaaA", + "CaAaACca", + 7 + ], + [ + "CAAab", + "b", + 8 + ], + [ + "CAAabac", + "Accbbc", + 8 + ], + [ + "CAAbCbCcC", + "B", + 17 + ], + [ + "CAAbb", + "caC", + 8 + ], + [ + "CAAbbAbb", + "BC", + 15 + ], + [ + "CAAcBB", + "aCBCbAAb", + 13 + ], + [ + "CAAccAcC", + "abA", + 13 + ], + [ + "CAB", + "ABabCcc", + 12 + ], + [ + "CAB", + "ABccbC", + 10 + ], + [ + "CAB", + "CABba", + 4 + ], + [ + "CAB", + "CcbB", + 4 + ], + [ + "CAB", + "aababa", + 10 + ], + [ + "CAB", + "bC", + 6 + ], + [ + "CAB", + "cAbbABAac", + 13 + ], + [ + "CABA", + "CaabCCc", + 10 + ], + [ + "CABAAa", + "abC", + 10 + ], + [ + "CABACacA", + "cAbaaABC", + 10 + ], + [ + "CABACcA", + "B", + 12 + ], + [ + "CABAa", + "aac", + 8 + ], + [ + "CABAcBa", + "b", + 13 + ], + [ + "CABBAa", + "bbBcabcC", + 13 + ], + [ + "CABBBAa", + "B", + 12 + ], + [ + "CABBBCaa", + "ACb", + 12 + ], + [ + "CABBBb", + "cacaAACa", + 14 + ], + [ + "CABC", + "cCbacA", + 9 + ], + [ + "CABCAcaC", + "B", + 14 + ], + [ + "CABa", + "B", + 6 + ], + [ + "CABaCc", + "BCaaaAAcb", + 11 + ], + [ + "CABab", + "baB", + 6 + ], + [ + "CABacBA", + "BaACb", + 10 + ], + [ + "CABb", + "bCcBaCba", + 10 + ], + [ + "CABbABcBA", + "aBaAccabA", + 10 + ], + [ + "CABbbC", + "CbACCAcc", + 11 + ], + [ + "CABcAaAb", + "bb", + 13 + ], + [ + "CABcaa", + "C", + 10 + ], + [ + "CABcaa", + "aCaBABAab", + 10 + ], + [ + "CABcabCAa", + "AcbaBcCA", + 11 + ], + [ + "CABcbCAc", + "ABAcc", + 9 + ], + [ + "CABcbbA", + "BBbcA", + 8 + ], + [ + "CABcbcacA", + "cb", + 14 + ], + [ + "CAC", + "aCAAaABb", + 12 + ], + [ + "CAC", + "abCCACaBc", + 12 + ], + [ + "CAC", + "bbcbB", + 9 + ], + [ + "CAC", + "caBAa", + 7 + ], + [ + "CAC", + "ccBaBcb", + 11 + ], + [ + "CACAACccb", + "bc", + 16 + ], + [ + "CACABBA", + "cCACAcCcC", + 10 + ], + [ + "CACACAcBB", + "aBAACCc", + 12 + ], + [ + "CACAabc", + "cbAaBbbbB", + 13 + ], + [ + "CACAcaAC", + "ACcACc", + 8 + ], + [ + "CACAcbC", + "Cc", + 10 + ], + [ + "CACB", + "Cbc", + 5 + ], + [ + "CACBb", + "C", + 8 + ], + [ + "CACC", + "bCa", + 6 + ], + [ + "CACCAAB", + "bACabAC", + 8 + ], + [ + "CACCAb", + "abBBB", + 10 + ], + [ + "CACCCBA", + "cabaac", + 12 + ], + [ + "CACCc", + "ba", + 9 + ], + [ + "CACaAcc", + "acaBbCbb", + 13 + ], + [ + "CACaCBBc", + "a", + 14 + ], + [ + "CACaabcBb", + "aCabba", + 10 + ], + [ + "CACacaABb", + "b", + 16 + ], + [ + "CACb", + "ABbb", + 6 + ], + [ + "CACb", + "AabbaCa", + 11 + ], + [ + "CACbA", + "bCbbC", + 8 + ], + [ + "CACbaCB", + "caacaaC", + 9 + ], + [ + "CACbaaCa", + "bBacacB", + 12 + ], + [ + "CACbbBBc", + "Bc", + 12 + ], + [ + "CACbc", + "Cc", + 6 + ], + [ + "CACbcAcac", + "cCAcA", + 10 + ], + [ + "CACbcba", + "caABaCb", + 10 + ], + [ + "CACcBabCc", + "baAbbaBB", + 13 + ], + [ + "CACcCacC", + "ABcC", + 10 + ], + [ + "CACccCAC", + "B", + 16 + ], + [ + "CAa", + "Ab", + 4 + ], + [ + "CAa", + "CabcCc", + 9 + ], + [ + "CAa", + "aaCAbaBc", + 10 + ], + [ + "CAa", + "bABABaCA", + 12 + ], + [ + "CAa", + "bBAaB", + 6 + ], + [ + "CAa", + "bca", + 4 + ], + [ + "CAa", + "cbC", + 5 + ], + [ + "CAaAAaA", + "abAbbcbaC", + 14 + ], + [ + "CAaAAbaaB", + "CAcBB", + 11 + ], + [ + "CAaAcb", + "bBCBB", + 11 + ], + [ + "CAaBAA", + "AacAcBABB", + 11 + ], + [ + "CAaBB", + "Cc", + 8 + ], + [ + "CAaBBACa", + "CAaacBccC", + 9 + ], + [ + "CAaBC", + "b", + 9 + ], + [ + "CAaBbbaBA", + "BBB", + 13 + ], + [ + "CAaC", + "AaBCacAba", + 14 + ], + [ + "CAaC", + "BcccCbBb", + 13 + ], + [ + "CAaCBbcab", + "CbC", + 13 + ], + [ + "CAaCc", + "AA", + 7 + ], + [ + "CAaCcabB", + "cBABCb", + 11 + ], + [ + "CAaCccCc", + "A", + 14 + ], + [ + "CAaa", + "bcABBaAb", + 10 + ], + [ + "CAaa", + "cbabABAC", + 12 + ], + [ + "CAaaB", + "b", + 9 + ], + [ + "CAaabBcC", + "a", + 14 + ], + [ + "CAaabbCac", + "bAC", + 14 + ], + [ + "CAaabcaB", + "cabCacbaA", + 12 + ], + [ + "CAabABbAa", + "bcbaCa", + 13 + ], + [ + "CAabac", + "baaABbB", + 10 + ], + [ + "CAabb", + "b", + 8 + ], + [ + "CAabb", + "cACACBaBB", + 10 + ], + [ + "CAac", + "aaB", + 5 + ], + [ + "CAac", + "cccBB", + 9 + ], + [ + "CAacAB", + "a", + 10 + ], + [ + "CAaccC", + "cacbc", + 6 + ], + [ + "CAb", + "ACCCAcaA", + 12 + ], + [ + "CAb", + "Aca", + 6 + ], + [ + "CAb", + "BCcBBAA", + 10 + ], + [ + "CAb", + "C", + 4 + ], + [ + "CAb", + "CCAcbAB", + 8 + ], + [ + "CAb", + "CcCbCBC", + 10 + ], + [ + "CAb", + "acAc", + 5 + ], + [ + "CAb", + "bab", + 3 + ], + [ + "CAb", + "cA", + 3 + ], + [ + "CAbAAaAA", + "abc", + 13 + ], + [ + "CAbAc", + "ABBCCB", + 10 + ], + [ + "CAbB", + "acC", + 7 + ], + [ + "CAbBBBB", + "BCcaBbabB", + 10 + ], + [ + "CAbBCCBAC", + "baA", + 14 + ], + [ + "CAbBab", + "cbABcBc", + 10 + ], + [ + "CAbBc", + "bBcAcCA", + 11 + ], + [ + "CAbBc", + "bCAcbba", + 7 + ], + [ + "CAbC", + "AaAc", + 6 + ], + [ + "CAbC", + "cBAC", + 5 + ], + [ + "CAbCBaBb", + "cAbcBa", + 6 + ], + [ + "CAbCCC", + "c", + 11 + ], + [ + "CAbCabbA", + "BbAABACba", + 12 + ], + [ + "CAbCcc", + "babBA", + 9 + ], + [ + "CAba", + "abbB", + 6 + ], + [ + "CAbaAbBBC", + "CbBBAbB", + 9 + ], + [ + "CAbaAcCCC", + "AcbB", + 14 + ], + [ + "CAbaBb", + "A", + 10 + ], + [ + "CAbaa", + "cc", + 9 + ], + [ + "CAbacbba", + "cBCccabA", + 10 + ], + [ + "CAbbAA", + "BAAaCbC", + 12 + ], + [ + "CAbbAAcC", + "CBBACbBCB", + 12 + ], + [ + "CAbbBCcB", + "Abca", + 10 + ], + [ + "CAbbBbC", + "ABcaca", + 11 + ], + [ + "CAbbbAC", + "bcB", + 11 + ], + [ + "CAbbcCABA", + "CbB", + 12 + ], + [ + "CAbc", + "B", + 7 + ], + [ + "CAbcA", + "CAcaccACb", + 10 + ], + [ + "CAbcACCB", + "BB", + 13 + ], + [ + "CAbcBAa", + "bccBACB", + 10 + ], + [ + "CAbcCca", + "cAc", + 9 + ], + [ + "CAbcaBbca", + "ccaacBaaa", + 12 + ], + [ + "CAc", + "AAcacbcC", + 12 + ], + [ + "CAc", + "AbbAbbcc", + 12 + ], + [ + "CAc", + "BAB", + 4 + ], + [ + "CAc", + "ab", + 5 + ], + [ + "CAc", + "b", + 6 + ], + [ + "CAc", + "bbaaac", + 9 + ], + [ + "CAcAaCcaC", + "AAa", + 12 + ], + [ + "CAcAbaaA", + "ccBcBc", + 12 + ], + [ + "CAcAcC", + "BAbCb", + 9 + ], + [ + "CAcAca", + "CCbb", + 9 + ], + [ + "CAcAcbbAc", + "Cca", + 13 + ], + [ + "CAcB", + "cBcaaCcB", + 10 + ], + [ + "CAcBbCccb", + "BBAbAbAB", + 15 + ], + [ + "CAcBbbAaA", + "aACbbCbaa", + 9 + ], + [ + "CAcBbcbCa", + "bcBc", + 12 + ], + [ + "CAcBcBC", + "abCaCb", + 11 + ], + [ + "CAcC", + "CBcB", + 4 + ], + [ + "CAcCACCA", + "cAAa", + 10 + ], + [ + "CAcCaCBCC", + "aac", + 14 + ], + [ + "CAca", + "AaBACbAab", + 13 + ], + [ + "CAcaABcab", + "aCCbC", + 14 + ], + [ + "CAcaaa", + "bbccA", + 9 + ], + [ + "CAcaacBB", + "c", + 14 + ], + [ + "CAcb", + "B", + 7 + ], + [ + "CAcb", + "aBCBAb", + 8 + ], + [ + "CAcbBA", + "bBAaba", + 9 + ], + [ + "CAcbBB", + "CCcCBA", + 6 + ], + [ + "CAcbBacb", + "AbbbB", + 10 + ], + [ + "CAcbCCaaC", + "bccB", + 14 + ], + [ + "CAcbCbc", + "bAcCA", + 8 + ], + [ + "CAcbbabC", + "abAccCaac", + 11 + ], + [ + "CAcbcA", + "BBca", + 8 + ], + [ + "CAcbcB", + "Ab", + 8 + ], + [ + "CAcc", + "b", + 8 + ], + [ + "CAccAaAcc", + "bccbAB", + 12 + ], + [ + "CAccBaAC", + "abbAAaB", + 13 + ], + [ + "CAccBaaCc", + "BCAb", + 15 + ], + [ + "CAccBbA", + "bcBbBcBc", + 13 + ], + [ + "CAccac", + "aAc", + 8 + ], + [ + "CB", + "A", + 4 + ], + [ + "CB", + "ABac", + 6 + ], + [ + "CB", + "AC", + 4 + ], + [ + "CB", + "ACbbcbb", + 11 + ], + [ + "CB", + "ACcCCBAC", + 12 + ], + [ + "CB", + "AaAAcBc", + 11 + ], + [ + "CB", + "AaBCab", + 9 + ], + [ + "CB", + "BCc", + 4 + ], + [ + "CB", + "BaCaB", + 6 + ], + [ + "CB", + "BccbcabCB", + 14 + ], + [ + "CB", + "C", + 2 + ], + [ + "CB", + "CAAAb", + 7 + ], + [ + "CB", + "CCba", + 5 + ], + [ + "CB", + "CaAcA", + 8 + ], + [ + "CB", + "CcCaAccb", + 13 + ], + [ + "CB", + "a", + 4 + ], + [ + "CB", + "aAa", + 6 + ], + [ + "CB", + "aBCBaBbC", + 12 + ], + [ + "CB", + "aCbcAc", + 9 + ], + [ + "CB", + "ac", + 4 + ], + [ + "CB", + "bAa", + 6 + ], + [ + "CB", + "bBAAbcb", + 12 + ], + [ + "CB", + "bCB", + 2 + ], + [ + "CB", + "bCaCCcaCA", + 16 + ], + [ + "CB", + "ba", + 4 + ], + [ + "CB", + "baBCcCc", + 12 + ], + [ + "CB", + "bbcbCB", + 8 + ], + [ + "CB", + "bcaab", + 8 + ], + [ + "CB", + "c", + 3 + ], + [ + "CB", + "cACca", + 8 + ], + [ + "CB", + "cBCbAB", + 8 + ], + [ + "CB", + "cCB", + 2 + ], + [ + "CB", + "cbb", + 4 + ], + [ + "CB", + "cbbBbACCA", + 15 + ], + [ + "CBA", + "ba", + 4 + ], + [ + "CBA", + "cbcBb", + 7 + ], + [ + "CBAA", + "ABBaBcB", + 11 + ], + [ + "CBAA", + "Ba", + 5 + ], + [ + "CBAA", + "bcc", + 7 + ], + [ + "CBAABa", + "BAaBA", + 4 + ], + [ + "CBAAC", + "CBAac", + 2 + ], + [ + "CBAAa", + "cccbAb", + 9 + ], + [ + "CBAAaac", + "bcAAb", + 10 + ], + [ + "CBAAbCc", + "bbaABBB", + 9 + ], + [ + "CBAAbbBC", + "CbBAaAc", + 10 + ], + [ + "CBAAc", + "AAA", + 6 + ], + [ + "CBAAc", + "bCbBbAAaC", + 9 + ], + [ + "CBAB", + "A", + 6 + ], + [ + "CBABAbcBA", + "b", + 16 + ], + [ + "CBABAcBc", + "cAb", + 12 + ], + [ + "CBABCacb", + "aCCbbBABA", + 14 + ], + [ + "CBABaa", + "cBbcCcc", + 11 + ], + [ + "CBABbbCa", + "BbAaA", + 11 + ], + [ + "CBABbcCCC", + "cCAC", + 12 + ], + [ + "CBABc", + "cCc", + 7 + ], + [ + "CBABccBbc", + "caAaaACbb", + 13 + ], + [ + "CBACAA", + "CCc", + 8 + ], + [ + "CBACAcC", + "aCbbc", + 10 + ], + [ + "CBACa", + "BACaBBaB", + 10 + ], + [ + "CBACbcB", + "a", + 13 + ], + [ + "CBACc", + "baCCCA", + 9 + ], + [ + "CBACcAccA", + "aAb", + 15 + ], + [ + "CBAaAC", + "ccbC", + 9 + ], + [ + "CBAaBaC", + "bCccccCb", + 14 + ], + [ + "CBAaCB", + "acabB", + 8 + ], + [ + "CBAaCa", + "Cabb", + 8 + ], + [ + "CBAaCc", + "cBBBBBaC", + 11 + ], + [ + "CBAabb", + "bbCabaBa", + 10 + ], + [ + "CBAacCa", + "Bccbacb", + 11 + ], + [ + "CBAb", + "cCAcbc", + 7 + ], + [ + "CBAbCcaB", + "aC", + 13 + ], + [ + "CBAba", + "CbbabA", + 5 + ], + [ + "CBAbabb", + "BABa", + 7 + ], + [ + "CBAbba", + "ba", + 8 + ], + [ + "CBAcAAbcb", + "BBBBBbABA", + 15 + ], + [ + "CBAcC", + "acbabBA", + 11 + ], + [ + "CBAccB", + "cb", + 9 + ], + [ + "CBAccab", + "cbB", + 11 + ], + [ + "CBB", + "Aa", + 6 + ], + [ + "CBB", + "BbAaC", + 9 + ], + [ + "CBB", + "CB", + 2 + ], + [ + "CBB", + "CCA", + 4 + ], + [ + "CBB", + "CcbCb", + 6 + ], + [ + "CBB", + "baBB", + 4 + ], + [ + "CBB", + "cAcBBccA", + 11 + ], + [ + "CBB", + "cBccaB", + 7 + ], + [ + "CBBABB", + "BbBb", + 6 + ], + [ + "CBBABC", + "AABcaac", + 10 + ], + [ + "CBBAbACb", + "CCBCbAbcB", + 8 + ], + [ + "CBBBA", + "bB", + 7 + ], + [ + "CBBBBaAC", + "ca", + 13 + ], + [ + "CBBBBbbcC", + "BaAbCaB", + 14 + ], + [ + "CBBBb", + "bCbaBBAb", + 7 + ], + [ + "CBBBbCbcA", + "ABCCcABc", + 13 + ], + [ + "CBBC", + "ACaca", + 8 + ], + [ + "CBBC", + "cB", + 5 + ], + [ + "CBBCAAB", + "b", + 13 + ], + [ + "CBBCAb", + "CBA", + 6 + ], + [ + "CBBCCAB", + "AbCa", + 10 + ], + [ + "CBBCCa", + "c", + 11 + ], + [ + "CBBCabAa", + "Cca", + 11 + ], + [ + "CBBaCc", + "CbbA", + 7 + ], + [ + "CBBab", + "acBCcA", + 9 + ], + [ + "CBBabb", + "BBCcBb", + 7 + ], + [ + "CBBacBacB", + "caCCccBc", + 12 + ], + [ + "CBBbAb", + "Bbab", + 5 + ], + [ + "CBBba", + "bcCcb", + 9 + ], + [ + "CBBbaAcbc", + "ABcABaAAc", + 11 + ], + [ + "CBBbbbabc", + "baAaBC", + 12 + ], + [ + "CBBbcaaC", + "bABABABB", + 13 + ], + [ + "CBBc", + "abCABc", + 6 + ], + [ + "CBBcACB", + "abBbC", + 9 + ], + [ + "CBBcBcc", + "A", + 14 + ], + [ + "CBBcbA", + "ccbBAca", + 9 + ], + [ + "CBBcbaBc", + "C", + 14 + ], + [ + "CBBcbaC", + "bBcAAbaaC", + 9 + ], + [ + "CBBccBCCB", + "bacCC", + 11 + ], + [ + "CBBccc", + "aBabc", + 8 + ], + [ + "CBC", + "ACB", + 4 + ], + [ + "CBC", + "CAbCabB", + 9 + ], + [ + "CBC", + "aCaAaAC", + 10 + ], + [ + "CBCAA", + "C", + 8 + ], + [ + "CBCAABa", + "BBcCbBa", + 7 + ], + [ + "CBCAACB", + "bBBcAAB", + 7 + ], + [ + "CBCACAa", + "ABbA", + 10 + ], + [ + "CBCAaCA", + "BbaAbac", + 10 + ], + [ + "CBCAacCc", + "cCb", + 12 + ], + [ + "CBCB", + "aAAaA", + 10 + ], + [ + "CBCBBA", + "acc", + 11 + ], + [ + "CBCBBCAA", + "ABC", + 12 + ], + [ + "CBCBC", + "aBccbCB", + 8 + ], + [ + "CBCBCC", + "BAbc", + 8 + ], + [ + "CBCC", + "CbaaA", + 7 + ], + [ + "CBCCBC", + "aACAA", + 10 + ], + [ + "CBCCBCcCb", + "Ba", + 16 + ], + [ + "CBCCCB", + "cacbAbbaA", + 15 + ], + [ + "CBCCCbaB", + "cacAbc", + 12 + ], + [ + "CBCCacb", + "a", + 12 + ], + [ + "CBCCbcc", + "BbbBcbCBc", + 11 + ], + [ + "CBCCcCbA", + "CBaAa", + 11 + ], + [ + "CBCa", + "aaAbbabA", + 13 + ], + [ + "CBCa", + "b", + 7 + ], + [ + "CBCaA", + "ab", + 8 + ], + [ + "CBCaAaBaa", + "acBbAa", + 12 + ], + [ + "CBCaB", + "caa", + 7 + ], + [ + "CBCacBBBB", + "BcabACCb", + 12 + ], + [ + "CBCb", + "AabACCa", + 11 + ], + [ + "CBCb", + "aABc", + 7 + ], + [ + "CBCbBa", + "abaCaB", + 9 + ], + [ + "CBCbbc", + "CcBCBCcbA", + 9 + ], + [ + "CBCbccaA", + "AbCbbCba", + 9 + ], + [ + "CBCc", + "bbcCBBAcb", + 12 + ], + [ + "CBCcB", + "BAa", + 8 + ], + [ + "CBCcBbb", + "ccaCBbA", + 8 + ], + [ + "CBCcccacB", + "BA", + 15 + ], + [ + "CBa", + "ACaba", + 5 + ], + [ + "CBa", + "CAaB", + 4 + ], + [ + "CBa", + "CBBCccc", + 10 + ], + [ + "CBa", + "CacAccB", + 11 + ], + [ + "CBa", + "c", + 5 + ], + [ + "CBaAAa", + "caCcaBAA", + 9 + ], + [ + "CBaAC", + "CBb", + 6 + ], + [ + "CBaAbaaAA", + "CbbcC", + 13 + ], + [ + "CBaB", + "aabBAbbC", + 12 + ], + [ + "CBaBBAa", + "AaAcA", + 10 + ], + [ + "CBaBCABC", + "AAA", + 13 + ], + [ + "CBaBaCcB", + "cBaAbBAAa", + 12 + ], + [ + "CBaBaa", + "AAB", + 9 + ], + [ + "CBaCAbC", + "BbCaCC", + 7 + ], + [ + "CBaCBba", + "bcABB", + 10 + ], + [ + "CBaCCAB", + "cBcBAcA", + 10 + ], + [ + "CBaCabccB", + "Bba", + 14 + ], + [ + "CBaaA", + "AacbaC", + 10 + ], + [ + "CBaaAcac", + "aacbcbACc", + 13 + ], + [ + "CBaaB", + "CbaAcB", + 4 + ], + [ + "CBaaBc", + "Ba", + 8 + ], + [ + "CBaaCaCa", + "c", + 15 + ], + [ + "CBaaaBB", + "B", + 12 + ], + [ + "CBaab", + "BaabBcba", + 10 + ], + [ + "CBaab", + "bBB", + 7 + ], + [ + "CBaabAB", + "CBCC", + 10 + ], + [ + "CBaacACCC", + "a", + 16 + ], + [ + "CBab", + "CB", + 4 + ], + [ + "CBab", + "aBcc", + 6 + ], + [ + "CBabACCaA", + "A", + 16 + ], + [ + "CBabCbbaC", + "AcbAc", + 12 + ], + [ + "CBacA", + "acBCCaCB", + 10 + ], + [ + "CBacaCBCB", + "aB", + 14 + ], + [ + "CBacbacB", + "CaBa", + 9 + ], + [ + "CBb", + "Cbb", + 1 + ], + [ + "CBb", + "a", + 6 + ], + [ + "CBb", + "bBbcc", + 6 + ], + [ + "CBb", + "bCaaaA", + 10 + ], + [ + "CBbA", + "bAaCbBC", + 10 + ], + [ + "CBbAAa", + "aabB", + 10 + ], + [ + "CBbAB", + "A", + 8 + ], + [ + "CBbAB", + "bbb", + 6 + ], + [ + "CBbACca", + "CbCAcB", + 7 + ], + [ + "CBbACcbC", + "bCcbBAb", + 12 + ], + [ + "CBbBB", + "C", + 8 + ], + [ + "CBbBB", + "CBCBcCBa", + 8 + ], + [ + "CBbBBCaBB", + "AbAca", + 13 + ], + [ + "CBbCA", + "aca", + 8 + ], + [ + "CBbCCB", + "BAbC", + 8 + ], + [ + "CBbCCCa", + "Ca", + 10 + ], + [ + "CBbCCb", + "CACbBBb", + 8 + ], + [ + "CBbCbbBc", + "ABaA", + 14 + ], + [ + "CBbaAcAAc", + "ccAACB", + 12 + ], + [ + "CBbaAca", + "bB", + 12 + ], + [ + "CBbaB", + "B", + 8 + ], + [ + "CBbaBBCaC", + "baaCcA", + 12 + ], + [ + "CBbaC", + "c", + 9 + ], + [ + "CBbaCa", + "cbbcAa", + 6 + ], + [ + "CBbaCbB", + "AcCcACbA", + 10 + ], + [ + "CBbabC", + "abB", + 8 + ], + [ + "CBbb", + "C", + 6 + ], + [ + "CBbb", + "a", + 8 + ], + [ + "CBbbbaB", + "B", + 12 + ], + [ + "CBbc", + "BaAABc", + 9 + ], + [ + "CBbcBAAB", + "cAbCAA", + 8 + ], + [ + "CBbcbb", + "cBCaC", + 8 + ], + [ + "CBc", + "Bcab", + 6 + ], + [ + "CBc", + "CBAAacc", + 8 + ], + [ + "CBc", + "abaCa", + 8 + ], + [ + "CBc", + "cAabccaaA", + 14 + ], + [ + "CBcA", + "CCA", + 3 + ], + [ + "CBcAAaccC", + "abBcAbaBC", + 10 + ], + [ + "CBcAaCCCb", + "aB", + 15 + ], + [ + "CBcAbAA", + "BabCcAAc", + 11 + ], + [ + "CBcAcB", + "CbbAAA", + 7 + ], + [ + "CBcB", + "a", + 8 + ], + [ + "CBcB", + "bcCBCCcbb", + 11 + ], + [ + "CBcBA", + "cBbCb", + 7 + ], + [ + "CBcBBABcc", + "bbBcabA", + 13 + ], + [ + "CBcBC", + "cAbCAAbcA", + 13 + ], + [ + "CBcBaaACB", + "cCc", + 14 + ], + [ + "CBcBb", + "c", + 8 + ], + [ + "CBcC", + "bCBBbBa", + 10 + ], + [ + "CBcC", + "c", + 6 + ], + [ + "CBcCC", + "aB", + 8 + ], + [ + "CBca", + "cC", + 6 + ], + [ + "CBcaAa", + "A", + 10 + ], + [ + "CBcaAba", + "AaAAaaCaA", + 13 + ], + [ + "CBcaBCc", + "AcBcb", + 9 + ], + [ + "CBcabbbba", + "bCCBc", + 15 + ], + [ + "CBcacCbCC", + "bCAaab", + 13 + ], + [ + "CBcb", + "Acb", + 4 + ], + [ + "CBcb", + "CbcABCA", + 8 + ], + [ + "CBcb", + "cBAac", + 7 + ], + [ + "CBcbCbc", + "cBBaBc", + 7 + ], + [ + "CBcbCcaBc", + "BAACAaC", + 11 + ], + [ + "CBcba", + "abCA", + 7 + ], + [ + "CBcbab", + "ABBabBC", + 9 + ], + [ + "CBcbbaC", + "ABcCa", + 8 + ], + [ + "CBcbcAAA", + "aaAbb", + 14 + ], + [ + "CBcbcbC", + "c", + 12 + ], + [ + "CBccaC", + "CAAa", + 8 + ], + [ + "CBccaCaaa", + "ccbBabcBB", + 15 + ], + [ + "CBccac", + "aB", + 10 + ], + [ + "CBccbaAbb", + "bBaacaC", + 14 + ], + [ + "CBccbbc", + "ACaAaCB", + 13 + ], + [ + "CC", + "AA", + 4 + ], + [ + "CC", + "AAaacAc", + 12 + ], + [ + "CC", + "ACACbCABB", + 14 + ], + [ + "CC", + "ACBaCAb", + 10 + ], + [ + "CC", + "ACaaB", + 8 + ], + [ + "CC", + "ACcCAaabb", + 14 + ], + [ + "CC", + "AacCBBc", + 11 + ], + [ + "CC", + "BaAACABCC", + 14 + ], + [ + "CC", + "BaBcaCbb", + 13 + ], + [ + "CC", + "Bc", + 3 + ], + [ + "CC", + "CBC", + 2 + ], + [ + "CC", + "CCAAAbab", + 12 + ], + [ + "CC", + "CCc", + 2 + ], + [ + "CC", + "Cb", + 2 + ], + [ + "CC", + "CbbBb", + 8 + ], + [ + "CC", + "CcAc", + 5 + ], + [ + "CC", + "a", + 4 + ], + [ + "CC", + "aACcC", + 6 + ], + [ + "CC", + "aBC", + 4 + ], + [ + "CC", + "aBbc", + 7 + ], + [ + "CC", + "aa", + 4 + ], + [ + "CC", + "bA", + 4 + ], + [ + "CC", + "c", + 3 + ], + [ + "CC", + "cBBB", + 7 + ], + [ + "CC", + "cBcCbBcab", + 15 + ], + [ + "CC", + "cCabBBC", + 10 + ], + [ + "CC", + "cCbBB", + 7 + ], + [ + "CCA", + "A", + 4 + ], + [ + "CCA", + "BaaabCA", + 10 + ], + [ + "CCA", + "CBaCacAB", + 10 + ], + [ + "CCA", + "aba", + 5 + ], + [ + "CCA", + "bb", + 6 + ], + [ + "CCAA", + "ABBCA", + 8 + ], + [ + "CCAA", + "BcCbBA", + 7 + ], + [ + "CCAA", + "babAabAA", + 12 + ], + [ + "CCAA", + "cAcC", + 7 + ], + [ + "CCAABbAAc", + "CA", + 14 + ], + [ + "CCAABc", + "BacACaaB", + 11 + ], + [ + "CCAACAbaa", + "BA", + 16 + ], + [ + "CCAAaB", + "CaCCcCa", + 10 + ], + [ + "CCAAbabbc", + "cc", + 15 + ], + [ + "CCAAcCCcA", + "ABcACaBc", + 13 + ], + [ + "CCAAcb", + "C", + 10 + ], + [ + "CCAB", + "bbc", + 8 + ], + [ + "CCABAAB", + "BCABbccB", + 8 + ], + [ + "CCABBCcbB", + "CabB", + 11 + ], + [ + "CCABCCAaa", + "CBCc", + 11 + ], + [ + "CCABb", + "Bcc", + 9 + ], + [ + "CCABcCBAa", + "bbBa", + 13 + ], + [ + "CCABcaC", + "caCc", + 10 + ], + [ + "CCABcbBaC", + "cAAaAAaC", + 11 + ], + [ + "CCAC", + "aBAccBA", + 11 + ], + [ + "CCACb", + "BABcBc", + 10 + ], + [ + "CCACbACc", + "Aabbbac", + 11 + ], + [ + "CCACcaCB", + "ABbCACbB", + 11 + ], + [ + "CCAa", + "aACCbaaac", + 11 + ], + [ + "CCAb", + "ACCBba", + 6 + ], + [ + "CCAbBcABA", + "cAaCBc", + 12 + ], + [ + "CCAbBcb", + "baCB", + 10 + ], + [ + "CCAbCAb", + "BaCCaa", + 10 + ], + [ + "CCAbaC", + "BBbcaa", + 10 + ], + [ + "CCAbaCBa", + "bcccA", + 12 + ], + [ + "CCAcAB", + "ccAAbCa", + 9 + ], + [ + "CCAcACA", + "acBA", + 9 + ], + [ + "CCAcBAa", + "aCacBaBAA", + 8 + ], + [ + "CCAcC", + "BbcBbC", + 9 + ], + [ + "CCAcCB", + "cBcaBBBA", + 11 + ], + [ + "CCAcaC", + "CcaB", + 6 + ], + [ + "CCAcaaca", + "cC", + 13 + ], + [ + "CCAcacccc", + "cAcabcB", + 9 + ], + [ + "CCAcbCb", + "ACCa", + 9 + ], + [ + "CCAcbbCBc", + "CcAbBCa", + 8 + ], + [ + "CCB", + "ACbaAACcB", + 12 + ], + [ + "CCB", + "Cc", + 3 + ], + [ + "CCB", + "abaAB", + 8 + ], + [ + "CCB", + "baCac", + 8 + ], + [ + "CCBA", + "Aaaaa", + 9 + ], + [ + "CCBAA", + "a", + 9 + ], + [ + "CCBABcc", + "BCABb", + 8 + ], + [ + "CCBAC", + "bCCcaCAc", + 9 + ], + [ + "CCBAbAC", + "bCA", + 10 + ], + [ + "CCBAc", + "BC", + 7 + ], + [ + "CCBAcaacb", + "aCCAA", + 13 + ], + [ + "CCBBCBccb", + "BBAa", + 14 + ], + [ + "CCBBbB", + "CbcAACa", + 11 + ], + [ + "CCBBccC", + "c", + 12 + ], + [ + "CCBC", + "CBCaABac", + 9 + ], + [ + "CCBCAaAA", + "CaC", + 12 + ], + [ + "CCBCBCcc", + "bcCccbAbb", + 13 + ], + [ + "CCBCb", + "c", + 9 + ], + [ + "CCBaAaB", + "bACAC", + 11 + ], + [ + "CCBaAaB", + "cbcCBca", + 11 + ], + [ + "CCBaAcba", + "BaaaCAA", + 11 + ], + [ + "CCBaBbbBC", + "a", + 16 + ], + [ + "CCBaCcAa", + "ccBbACCb", + 10 + ], + [ + "CCBbAAAB", + "CCcaBabc", + 11 + ], + [ + "CCBbACc", + "bbbaacBb", + 12 + ], + [ + "CCBbB", + "cBBBACC", + 10 + ], + [ + "CCBbBC", + "bAcCCab", + 12 + ], + [ + "CCBbabCB", + "bCcaB", + 10 + ], + [ + "CCBbca", + "bc", + 8 + ], + [ + "CCBcB", + "ACbbCa", + 8 + ], + [ + "CCBca", + "BacCaaAA", + 12 + ], + [ + "CCBcbbC", + "cB", + 11 + ], + [ + "CCC", + "CcaB", + 5 + ], + [ + "CCC", + "baaaC", + 8 + ], + [ + "CCCAABC", + "CC", + 10 + ], + [ + "CCCAbbBCb", + "cBBaaBab", + 12 + ], + [ + "CCCAc", + "BaccCaB", + 9 + ], + [ + "CCCBAbcc", + "accAb", + 10 + ], + [ + "CCCBBcab", + "ACCA", + 11 + ], + [ + "CCCBCaAcC", + "aaCcAbAa", + 14 + ], + [ + "CCCBbbbC", + "aCb", + 12 + ], + [ + "CCCBcBBaa", + "aBACAbAA", + 14 + ], + [ + "CCCBccaB", + "ccBcc", + 8 + ], + [ + "CCCC", + "bBcAaAbaC", + 15 + ], + [ + "CCCCA", + "BBACa", + 7 + ], + [ + "CCCCA", + "bAcAbbC", + 13 + ], + [ + "CCCCA", + "cccAC", + 7 + ], + [ + "CCCCAbaa", + "CaBaccBB", + 14 + ], + [ + "CCCCBC", + "ABbBc", + 9 + ], + [ + "CCCCCa", + "BCACA", + 7 + ], + [ + "CCCCaBCA", + "Bacbcab", + 13 + ], + [ + "CCCCbaC", + "b", + 12 + ], + [ + "CCCCbbba", + "BAbcAbcBb", + 14 + ], + [ + "CCCCcA", + "bbCCbbc", + 10 + ], + [ + "CCCCcBAC", + "acACBcC", + 9 + ], + [ + "CCCa", + "bAb", + 8 + ], + [ + "CCCaABacb", + "bacBBcAA", + 14 + ], + [ + "CCCaCcA", + "bAcAC", + 10 + ], + [ + "CCCaCcbBA", + "bAbc", + 15 + ], + [ + "CCCaaCaBA", + "AbAbBCb", + 15 + ], + [ + "CCCabaaab", + "cAbca", + 12 + ], + [ + "CCCacacb", + "CAcCBcA", + 10 + ], + [ + "CCCb", + "C", + 6 + ], + [ + "CCCbBBB", + "A", + 14 + ], + [ + "CCCba", + "BbAcaC", + 10 + ], + [ + "CCCbbAA", + "a", + 13 + ], + [ + "CCCbbaA", + "cCB", + 10 + ], + [ + "CCCbbcc", + "BCA", + 12 + ], + [ + "CCCc", + "CBbBBaBBa", + 16 + ], + [ + "CCCcBBba", + "CcBbcAa", + 9 + ], + [ + "CCCcBaA", + "CCCBAAAcA", + 9 + ], + [ + "CCa", + "Ca", + 2 + ], + [ + "CCa", + "CbabbAAcA", + 14 + ], + [ + "CCa", + "bbbCBA", + 9 + ], + [ + "CCa", + "cCAcbAbCC", + 14 + ], + [ + "CCaA", + "c", + 7 + ], + [ + "CCaAA", + "BBACcB", + 11 + ], + [ + "CCaAAb", + "cBa", + 9 + ], + [ + "CCaABbBaA", + "CcACab", + 11 + ], + [ + "CCaAcb", + "ABbBCaCa", + 13 + ], + [ + "CCaBAcbAC", + "CBbc", + 11 + ], + [ + "CCaBBA", + "bAbBB", + 8 + ], + [ + "CCaCAAbA", + "AA", + 12 + ], + [ + "CCaCACBcb", + "caC", + 13 + ], + [ + "CCaCAaA", + "BCAaCaa", + 7 + ], + [ + "CCaCB", + "CAAA", + 7 + ], + [ + "CCaCBcAC", + "bcCa", + 12 + ], + [ + "CCaCCC", + "CACcBa", + 8 + ], + [ + "CCaCaCc", + "BcCba", + 11 + ], + [ + "CCaCaCcBA", + "a", + 16 + ], + [ + "CCaCabaAa", + "CcccAacAC", + 11 + ], + [ + "CCaCb", + "bAcaCbCAb", + 11 + ], + [ + "CCaCbaaaC", + "CaCBCBBc", + 10 + ], + [ + "CCaaBbbA", + "BAAc", + 14 + ], + [ + "CCaaCbCab", + "aBbB", + 13 + ], + [ + "CCaaaaccC", + "AABcca", + 12 + ], + [ + "CCaacBa", + "a", + 12 + ], + [ + "CCabA", + "acbCAAbb", + 10 + ], + [ + "CCabA", + "bbaacCA", + 10 + ], + [ + "CCabCAac", + "ABABA", + 12 + ], + [ + "CCabcCbc", + "BCbc", + 9 + ], + [ + "CCac", + "a", + 6 + ], + [ + "CCacAac", + "bbBbaC", + 11 + ], + [ + "CCacAbCcb", + "bCbBa", + 14 + ], + [ + "CCacBca", + "C", + 12 + ], + [ + "CCacCb", + "cBAC", + 8 + ], + [ + "CCacab", + "Aa", + 9 + ], + [ + "CCacbb", + "CAb", + 7 + ], + [ + "CCacbcB", + "Cca", + 9 + ], + [ + "CCb", + "BAbBAaB", + 12 + ], + [ + "CCb", + "CAAAbca", + 10 + ], + [ + "CCb", + "bAc", + 6 + ], + [ + "CCb", + "bcabBaB", + 11 + ], + [ + "CCb", + "cbCcaAaac", + 15 + ], + [ + "CCbA", + "AABAC", + 7 + ], + [ + "CCbA", + "BbBCabCaa", + 13 + ], + [ + "CCbAAa", + "BcABbC", + 11 + ], + [ + "CCbABCC", + "a", + 13 + ], + [ + "CCbACCBa", + "BbbaBbC", + 12 + ], + [ + "CCbAaaA", + "aB", + 12 + ], + [ + "CCbAbC", + "cAacBCa", + 10 + ], + [ + "CCbAbbBB", + "abcaA", + 13 + ], + [ + "CCbB", + "Aa", + 8 + ], + [ + "CCbB", + "cbaBCBBA", + 10 + ], + [ + "CCbBBB", + "CACCacCBc", + 12 + ], + [ + "CCbBCC", + "BbCAbcAA", + 12 + ], + [ + "CCbBbaBa", + "BcbccCAc", + 13 + ], + [ + "CCbCBCbB", + "cCbbB", + 7 + ], + [ + "CCbCbA", + "ABACcA", + 8 + ], + [ + "CCbCbcacC", + "bBC", + 13 + ], + [ + "CCba", + "aBaAcAaCC", + 15 + ], + [ + "CCba", + "caCAcc", + 9 + ], + [ + "CCba", + "cbaCcba", + 7 + ], + [ + "CCbaB", + "Ba", + 7 + ], + [ + "CCbaBB", + "CCaccA", + 8 + ], + [ + "CCbaCC", + "aBbcaa", + 10 + ], + [ + "CCbaaBcAB", + "a", + 16 + ], + [ + "CCbaba", + "ACbaBAAb", + 8 + ], + [ + "CCbb", + "aBbacACBa", + 14 + ], + [ + "CCbbACcA", + "CBabaAA", + 9 + ], + [ + "CCbbAabCa", + "cAABb", + 13 + ], + [ + "CCbbBabb", + "aBBcc", + 13 + ], + [ + "CCbbaBC", + "cBC", + 9 + ], + [ + "CCbbca", + "bAC", + 9 + ], + [ + "CCbbcaCBA", + "CCaAaBBAB", + 10 + ], + [ + "CCbcAac", + "a", + 12 + ], + [ + "CCbcBC", + "aabbAc", + 9 + ], + [ + "CCbcBca", + "B", + 12 + ], + [ + "CCbcCAc", + "Bb", + 12 + ], + [ + "CCbcb", + "cBaC", + 8 + ], + [ + "CCbcc", + "aBaccBcB", + 11 + ], + [ + "CCc", + "A", + 6 + ], + [ + "CCc", + "Ac", + 4 + ], + [ + "CCc", + "Bc", + 4 + ], + [ + "CCc", + "Cacbb", + 6 + ], + [ + "CCc", + "bCcbAbbAB", + 14 + ], + [ + "CCcAC", + "CABCA", + 7 + ], + [ + "CCcACBCC", + "B", + 14 + ], + [ + "CCcACc", + "cACCCA", + 8 + ], + [ + "CCcAaaba", + "CCCBcABca", + 9 + ], + [ + "CCcAc", + "abaaaCCc", + 13 + ], + [ + "CCcB", + "aCAaBc", + 8 + ], + [ + "CCcBAB", + "CacAbbcbB", + 11 + ], + [ + "CCcBAcC", + "bB", + 12 + ], + [ + "CCcBbAb", + "aBbC", + 10 + ], + [ + "CCcBcaB", + "cBbb", + 9 + ], + [ + "CCcCaaAC", + "CAAbccC", + 12 + ], + [ + "CCcCb", + "B", + 9 + ], + [ + "CCcCbacba", + "AAa", + 15 + ], + [ + "CCcCcABB", + "cAcBabacb", + 13 + ], + [ + "CCcCcccAB", + "BAaACCCAB", + 11 + ], + [ + "CCca", + "Acc", + 5 + ], + [ + "CCca", + "a", + 6 + ], + [ + "CCcaBCabB", + "cAabc", + 11 + ], + [ + "CCcaC", + "bbCACAA", + 10 + ], + [ + "CCcaCca", + "CabacBb", + 9 + ], + [ + "CCcaaBaB", + "ccaAabb", + 9 + ], + [ + "CCcaaabbc", + "BCaCC", + 13 + ], + [ + "CCcabA", + "bCCAAcaBC", + 9 + ], + [ + "CCcacbB", + "Babb", + 9 + ], + [ + "CCcb", + "C", + 6 + ], + [ + "CCcbB", + "abB", + 6 + ], + [ + "CCcbBBC", + "aAAaCCCc", + 14 + ], + [ + "CCcbC", + "ACcBBBBc", + 10 + ], + [ + "CCcbC", + "a", + 10 + ], + [ + "CCcbCACab", + "Accba", + 11 + ], + [ + "CCcbcaaaA", + "ccaaAbaaB", + 12 + ], + [ + "CCccAAB", + "CCaaa", + 8 + ], + [ + "CCccB", + "AACBAbC", + 11 + ], + [ + "CCcca", + "baAaCccaa", + 10 + ], + [ + "CCccaAA", + "b", + 14 + ], + [ + "CCccbb", + "babC", + 10 + ], + [ + "Ca", + "ABCCb", + 8 + ], + [ + "Ca", + "AaCcCBaab", + 14 + ], + [ + "Ca", + "Aac", + 4 + ], + [ + "Ca", + "BAAABca", + 11 + ], + [ + "Ca", + "BACaCCb", + 10 + ], + [ + "Ca", + "BAc", + 5 + ], + [ + "Ca", + "BBAA", + 7 + ], + [ + "Ca", + "BCB", + 4 + ], + [ + "Ca", + "BCBbBaAC", + 12 + ], + [ + "Ca", + "BaCCAcBAa", + 14 + ], + [ + "Ca", + "BabB", + 6 + ], + [ + "Ca", + "BababbBb", + 14 + ], + [ + "Ca", + "BbCB", + 6 + ], + [ + "Ca", + "Bbb", + 6 + ], + [ + "Ca", + "CAbc", + 5 + ], + [ + "Ca", + "CBAbac", + 8 + ], + [ + "Ca", + "CBB", + 4 + ], + [ + "Ca", + "CBaA", + 4 + ], + [ + "Ca", + "CCAB", + 5 + ], + [ + "Ca", + "CCaCBaaA", + 12 + ], + [ + "Ca", + "CCbaAA", + 8 + ], + [ + "Ca", + "CCbb", + 6 + ], + [ + "Ca", + "Cb", + 2 + ], + [ + "Ca", + "aACCba", + 8 + ], + [ + "Ca", + "aB", + 4 + ], + [ + "Ca", + "aBBA", + 7 + ], + [ + "Ca", + "aac", + 4 + ], + [ + "Ca", + "acBacBcAA", + 15 + ], + [ + "Ca", + "b", + 4 + ], + [ + "Ca", + "bAbBbbAa", + 14 + ], + [ + "Ca", + "bBCA", + 5 + ], + [ + "Ca", + "bbBAAAa", + 12 + ], + [ + "Ca", + "c", + 3 + ], + [ + "Ca", + "cCBCBbAAa", + 14 + ], + [ + "Ca", + "caBabaBc", + 13 + ], + [ + "Ca", + "ccCaCCC", + 10 + ], + [ + "CaA", + "BcBcAb", + 9 + ], + [ + "CaA", + "CCBBA", + 6 + ], + [ + "CaA", + "aBa", + 5 + ], + [ + "CaA", + "aBcbcb", + 11 + ], + [ + "CaA", + "bBcCBcbcc", + 16 + ], + [ + "CaA", + "bCABC", + 7 + ], + [ + "CaA", + "bCcBaAaA", + 10 + ], + [ + "CaA", + "c", + 5 + ], + [ + "CaAA", + "bacCbbA", + 10 + ], + [ + "CaAABbc", + "c", + 12 + ], + [ + "CaAAC", + "c", + 9 + ], + [ + "CaAACB", + "bB", + 10 + ], + [ + "CaAAa", + "AcCbA", + 9 + ], + [ + "CaAAbcCa", + "a", + 14 + ], + [ + "CaAB", + "BCaCaCB", + 7 + ], + [ + "CaAB", + "Ba", + 6 + ], + [ + "CaAB", + "bCb", + 7 + ], + [ + "CaABBc", + "b", + 11 + ], + [ + "CaABCBA", + "bBb", + 11 + ], + [ + "CaABa", + "B", + 8 + ], + [ + "CaABbACB", + "BA", + 12 + ], + [ + "CaABbC", + "AAacAc", + 9 + ], + [ + "CaAC", + "BBCbCcaaC", + 11 + ], + [ + "CaAC", + "aCAABab", + 9 + ], + [ + "CaAC", + "acCBbcbA", + 13 + ], + [ + "CaACB", + "B", + 8 + ], + [ + "CaACbacC", + "BAbabAAB", + 12 + ], + [ + "CaACbc", + "CBA", + 8 + ], + [ + "CaACcBACc", + "aAcc", + 10 + ], + [ + "CaAa", + "Bababa", + 7 + ], + [ + "CaAa", + "ccAC", + 5 + ], + [ + "CaAaAC", + "ACa", + 9 + ], + [ + "CaAaACCc", + "BaabbBCbC", + 12 + ], + [ + "CaAaBbB", + "cbAb", + 9 + ], + [ + "CaAaa", + "cAAACBa", + 7 + ], + [ + "CaAab", + "BBbcbaa", + 12 + ], + [ + "CaAabcABB", + "ACcBacC", + 14 + ], + [ + "CaAbC", + "bC", + 6 + ], + [ + "CaAbbBa", + "c", + 13 + ], + [ + "CaAc", + "Ac", + 4 + ], + [ + "CaAc", + "abB", + 6 + ], + [ + "CaAcCAb", + "cABCaAA", + 9 + ], + [ + "CaAcCa", + "bBabcCCC", + 10 + ], + [ + "CaAca", + "bcAcBAABA", + 13 + ], + [ + "CaAcb", + "aBbACB", + 8 + ], + [ + "CaAcc", + "ACc", + 5 + ], + [ + "CaB", + "B", + 4 + ], + [ + "CaB", + "C", + 4 + ], + [ + "CaB", + "acbCAcC", + 11 + ], + [ + "CaB", + "bbAaAaBB", + 12 + ], + [ + "CaB", + "cabbb", + 6 + ], + [ + "CaBA", + "cbcAB", + 7 + ], + [ + "CaBAAB", + "BBAC", + 8 + ], + [ + "CaBAAB", + "a", + 10 + ], + [ + "CaBAAaBB", + "AACB", + 10 + ], + [ + "CaBAbCb", + "baA", + 10 + ], + [ + "CaBAcBCcb", + "A", + 16 + ], + [ + "CaBAcc", + "AACCaA", + 11 + ], + [ + "CaBAcc", + "bAcBbA", + 11 + ], + [ + "CaBB", + "aCCBbcaba", + 13 + ], + [ + "CaBB", + "babABcb", + 9 + ], + [ + "CaBBBa", + "Cc", + 10 + ], + [ + "CaBBBbBB", + "CAAaC", + 13 + ], + [ + "CaBBCccC", + "bAac", + 13 + ], + [ + "CaBBaA", + "a", + 10 + ], + [ + "CaBBabBcc", + "b", + 16 + ], + [ + "CaBBcC", + "BA", + 10 + ], + [ + "CaBBccac", + "accCBA", + 11 + ], + [ + "CaBC", + "CaaacC", + 6 + ], + [ + "CaBCACabA", + "CbcABbc", + 10 + ], + [ + "CaBCBbC", + "ccbBbaC", + 8 + ], + [ + "CaBCCcaCc", + "CaC", + 12 + ], + [ + "CaBaaBcA", + "C", + 14 + ], + [ + "CaBacBc", + "c", + 12 + ], + [ + "CaBba", + "bbcCaAa", + 10 + ], + [ + "CaBbac", + "A", + 11 + ], + [ + "CaBcAc", + "CAAab", + 8 + ], + [ + "CaBcBAbB", + "BABCCca", + 12 + ], + [ + "CaBcaA", + "bcC", + 9 + ], + [ + "CaBccaAc", + "bBa", + 12 + ], + [ + "CaC", + "aC", + 2 + ], + [ + "CaCA", + "bcBA", + 6 + ], + [ + "CaCAAbCcB", + "aBCc", + 11 + ], + [ + "CaCABCcbA", + "bB", + 16 + ], + [ + "CaCACCaA", + "BCBBaaBCA", + 13 + ], + [ + "CaCAbBA", + "bCBb", + 10 + ], + [ + "CaCB", + "AB", + 5 + ], + [ + "CaCB", + "bAb", + 6 + ], + [ + "CaCBa", + "ACabCC", + 8 + ], + [ + "CaCBa", + "abBaa", + 6 + ], + [ + "CaCBaaC", + "bcACBa", + 8 + ], + [ + "CaCBbBBb", + "bab", + 12 + ], + [ + "CaCBc", + "cAC", + 6 + ], + [ + "CaCCbB", + "babA", + 8 + ], + [ + "CaCCbc", + "BAbcCcBB", + 11 + ], + [ + "CaCa", + "Aab", + 6 + ], + [ + "CaCa", + "CCccAab", + 9 + ], + [ + "CaCa", + "CcbcAAC", + 10 + ], + [ + "CaCa", + "abCCa", + 6 + ], + [ + "CaCaAB", + "aBb", + 9 + ], + [ + "CaCb", + "bCab", + 4 + ], + [ + "CaCbBcCCC", + "CaBBab", + 11 + ], + [ + "CaCbbCAcb", + "aABcAc", + 10 + ], + [ + "CaCbbaB", + "ABB", + 10 + ], + [ + "CaCc", + "A", + 7 + ], + [ + "CaCc", + "ccBbc", + 7 + ], + [ + "CaCcAAb", + "baCBCB", + 9 + ], + [ + "CaCcB", + "AA", + 9 + ], + [ + "CaCcBa", + "cAc", + 8 + ], + [ + "CaCcaa", + "CABabbB", + 11 + ], + [ + "CaCcbBA", + "CAbccCaa", + 9 + ], + [ + "Caa", + "Acc", + 6 + ], + [ + "Caa", + "BAcBcBCbb", + 16 + ], + [ + "Caa", + "abbAb", + 9 + ], + [ + "CaaABcBab", + "acACccaCa", + 12 + ], + [ + "CaaAaAa", + "bbaabAc", + 9 + ], + [ + "CaaAaAaba", + "aaCBc", + 13 + ], + [ + "CaaAbCcAb", + "bc", + 14 + ], + [ + "CaaBAab", + "CcC", + 12 + ], + [ + "CaaBcB", + "Caaa", + 6 + ], + [ + "CaaC", + "AAbBaC", + 7 + ], + [ + "CaaCA", + "A", + 8 + ], + [ + "CaaCbCB", + "c", + 13 + ], + [ + "Caaa", + "BBaBcA", + 9 + ], + [ + "CaaaCabaC", + "CAa", + 13 + ], + [ + "Caaab", + "a", + 8 + ], + [ + "CaaabAbc", + "ACc", + 12 + ], + [ + "CaaabCbB", + "ABcB", + 11 + ], + [ + "Caaabcc", + "babAaAC", + 10 + ], + [ + "Caaac", + "AAbbccabb", + 15 + ], + [ + "Caab", + "BacAc", + 7 + ], + [ + "CaacAaCb", + "AbccbacB", + 10 + ], + [ + "CaacCb", + "acbcCABBB", + 13 + ], + [ + "Caacaccbc", + "bCcbB", + 13 + ], + [ + "CaacccACC", + "baBCAaCA", + 12 + ], + [ + "Cab", + "AbBCbcBbc", + 14 + ], + [ + "Cab", + "AcC", + 6 + ], + [ + "Cab", + "BCA", + 5 + ], + [ + "Cab", + "BaB", + 3 + ], + [ + "Cab", + "c", + 5 + ], + [ + "CabA", + "b", + 6 + ], + [ + "CabAabA", + "cbCaBBb", + 10 + ], + [ + "CabAbcCB", + "acbCa", + 10 + ], + [ + "CabB", + "AACcCBcab", + 14 + ], + [ + "CabB", + "BabB", + 2 + ], + [ + "CabB", + "Ccba", + 4 + ], + [ + "CabBCa", + "AaCaab", + 10 + ], + [ + "CabBacbC", + "C", + 14 + ], + [ + "CabBbab", + "Bc", + 12 + ], + [ + "CabBbc", + "BbBCbcBca", + 12 + ], + [ + "CabBcC", + "AaAcCAC", + 9 + ], + [ + "CabCB", + "AaCBCab", + 8 + ], + [ + "CabCaAABb", + "BbaB", + 12 + ], + [ + "CabCb", + "BcCbacbb", + 10 + ], + [ + "Caba", + "AA", + 6 + ], + [ + "Caba", + "CBbBBbCC", + 12 + ], + [ + "CabaAAcbc", + "aA", + 14 + ], + [ + "CabaAaab", + "Bccb", + 13 + ], + [ + "CabaBCc", + "acBcBb", + 11 + ], + [ + "CabaCAC", + "bAaa", + 10 + ], + [ + "CababAAcB", + "a", + 16 + ], + [ + "Cabb", + "aBbABaA", + 11 + ], + [ + "CabbAAABB", + "ccA", + 15 + ], + [ + "CabbACc", + "ABCCca", + 10 + ], + [ + "CabbB", + "BabCaAC", + 10 + ], + [ + "CabbB", + "CbBbAccbc", + 12 + ], + [ + "CabbCaa", + "bbaBbcacC", + 10 + ], + [ + "CabbaAba", + "CABaCBAbA", + 9 + ], + [ + "CabbbAACB", + "Babac", + 12 + ], + [ + "CabcB", + "aBAbaA", + 9 + ], + [ + "CabcBaC", + "Cac", + 8 + ], + [ + "CabcaABb", + "cBBc", + 12 + ], + [ + "CabcaBcB", + "bAABcbCA", + 12 + ], + [ + "Cabcb", + "Ba", + 8 + ], + [ + "Cabccb", + "BBBA", + 11 + ], + [ + "Cac", + "A", + 5 + ], + [ + "Cac", + "BAcb", + 5 + ], + [ + "Cac", + "BCcCCac", + 8 + ], + [ + "Cac", + "Bc", + 4 + ], + [ + "Cac", + "CBaacCcCb", + 12 + ], + [ + "Cac", + "cC", + 4 + ], + [ + "Cac", + "cbACbC", + 9 + ], + [ + "CacA", + "BaBabBAA", + 12 + ], + [ + "CacA", + "CacbC", + 4 + ], + [ + "CacAb", + "acCAb", + 4 + ], + [ + "CacAcAa", + "ACbcC", + 10 + ], + [ + "CacAcBc", + "caABbAAAA", + 13 + ], + [ + "CacBBBC", + "B", + 12 + ], + [ + "CacBCa", + "CcbcBA", + 7 + ], + [ + "CacBaCbca", + "aaBaaaBc", + 11 + ], + [ + "CacBbbB", + "CaCbbaBbb", + 7 + ], + [ + "CacBc", + "bBbAC", + 9 + ], + [ + "CacC", + "AcC", + 3 + ], + [ + "CacCbaAcc", + "bCaAaCB", + 13 + ], + [ + "CacaAc", + "aAbC", + 8 + ], + [ + "Cacab", + "AaBCAa", + 8 + ], + [ + "Cacab", + "c", + 8 + ], + [ + "CacacC", + "AABCCAA", + 12 + ], + [ + "Cacb", + "ac", + 4 + ], + [ + "CacbB", + "BCbcBaa", + 9 + ], + [ + "CacbC", + "bBbCaBBB", + 11 + ], + [ + "CacbC", + "cCAAcCa", + 9 + ], + [ + "CacbCAccB", + "AAaBBcbBc", + 14 + ], + [ + "Cacc", + "AACc", + 4 + ], + [ + "CaccAC", + "BabBAaC", + 8 + ], + [ + "CaccBca", + "aCbb", + 10 + ], + [ + "CaccaAbbC", + "BBbC", + 13 + ], + [ + "CaccaCCa", + "cc", + 12 + ], + [ + "Cb", + "A", + 4 + ], + [ + "Cb", + "AACB", + 5 + ], + [ + "Cb", + "AACCbcBc", + 12 + ], + [ + "Cb", + "ABcAcaCcC", + 16 + ], + [ + "Cb", + "ACCBAaCaA", + 15 + ], + [ + "Cb", + "AaBCBCc", + 11 + ], + [ + "Cb", + "Aaa", + 6 + ], + [ + "Cb", + "AacabCcB", + 13 + ], + [ + "Cb", + "Ac", + 4 + ], + [ + "Cb", + "BABB", + 7 + ], + [ + "Cb", + "BBcAabC", + 11 + ], + [ + "Cb", + "Ba", + 4 + ], + [ + "Cb", + "BaaB", + 7 + ], + [ + "Cb", + "BbCaabCCC", + 14 + ], + [ + "Cb", + "CA", + 2 + ], + [ + "Cb", + "CCcBaAB", + 11 + ], + [ + "Cb", + "Cbb", + 2 + ], + [ + "Cb", + "CcBccBacC", + 15 + ], + [ + "Cb", + "aBcaCb", + 8 + ], + [ + "Cb", + "aCBCcAACA", + 15 + ], + [ + "Cb", + "aaAbc", + 8 + ], + [ + "Cb", + "aaCBBaB", + 11 + ], + [ + "Cb", + "aaaB", + 7 + ], + [ + "Cb", + "abBaC", + 8 + ], + [ + "Cb", + "abaaaCABA", + 15 + ], + [ + "Cb", + "acBbAAca", + 13 + ], + [ + "Cb", + "acbbabbCC", + 15 + ], + [ + "Cb", + "bcCCBA", + 9 + ], + [ + "Cb", + "c", + 3 + ], + [ + "Cb", + "cAbcbCA", + 11 + ], + [ + "Cb", + "cAcCbBA", + 10 + ], + [ + "Cb", + "cB", + 2 + ], + [ + "Cb", + "cBcB", + 6 + ], + [ + "Cb", + "caacb", + 7 + ], + [ + "Cb", + "cbCBBbacA", + 14 + ], + [ + "Cb", + "cbcbccA", + 11 + ], + [ + "CbA", + "AAC", + 6 + ], + [ + "CbA", + "BBCBaCC", + 10 + ], + [ + "CbA", + "BBcBB", + 8 + ], + [ + "CbA", + "baaA", + 6 + ], + [ + "CbA", + "c", + 5 + ], + [ + "CbA", + "caBAbA", + 7 + ], + [ + "CbAABaAC", + "A", + 14 + ], + [ + "CbAACACcC", + "ba", + 15 + ], + [ + "CbAACa", + "AaCaAccab", + 11 + ], + [ + "CbAAaAB", + "BCaBCcaaC", + 12 + ], + [ + "CbAAb", + "bacAabaAB", + 11 + ], + [ + "CbAAcAb", + "caC", + 11 + ], + [ + "CbAAcC", + "ABbcaCa", + 10 + ], + [ + "CbABACcaB", + "Babb", + 14 + ], + [ + "CbABC", + "b", + 8 + ], + [ + "CbABaBaAC", + "acaC", + 12 + ], + [ + "CbAC", + "A", + 6 + ], + [ + "CbAC", + "c", + 7 + ], + [ + "CbACaB", + "aBcA", + 9 + ], + [ + "CbACb", + "bcABcCC", + 10 + ], + [ + "CbACc", + "BbabcaBCA", + 13 + ], + [ + "CbACcABba", + "baABAcBc", + 12 + ], + [ + "CbAaAaaa", + "ACbBACbbc", + 13 + ], + [ + "CbAaabbC", + "A", + 14 + ], + [ + "CbAacB", + "c", + 10 + ], + [ + "CbAacBB", + "CacbBBbBA", + 12 + ], + [ + "CbAb", + "baBac", + 8 + ], + [ + "CbAbBaC", + "aCAaACb", + 11 + ], + [ + "CbAba", + "CbaA", + 4 + ], + [ + "CbAbb", + "Bc", + 9 + ], + [ + "CbAc", + "a", + 7 + ], + [ + "CbAcAC", + "bcbCB", + 8 + ], + [ + "CbAcB", + "aac", + 7 + ], + [ + "CbAcBCcaa", + "ccABcacAc", + 11 + ], + [ + "CbAcCb", + "AC", + 8 + ], + [ + "CbAcaAAA", + "accCbbACC", + 15 + ], + [ + "CbAcc", + "AABbcBBc", + 11 + ], + [ + "CbB", + "ABcCCBb", + 10 + ], + [ + "CbB", + "B", + 4 + ], + [ + "CbB", + "BB", + 3 + ], + [ + "CbB", + "BBb", + 4 + ], + [ + "CbB", + "ababacC", + 11 + ], + [ + "CbB", + "bAaaABc", + 12 + ], + [ + "CbB", + "cCb", + 4 + ], + [ + "CbBABACb", + "BCcBAA", + 10 + ], + [ + "CbBABBaA", + "BacaabAc", + 13 + ], + [ + "CbBAb", + "cB", + 7 + ], + [ + "CbBB", + "CcBCBCcAC", + 12 + ], + [ + "CbBBB", + "BCCcb", + 9 + ], + [ + "CbBBaC", + "ab", + 10 + ], + [ + "CbBBcCCBb", + "B", + 16 + ], + [ + "CbBCCbbB", + "cC", + 13 + ], + [ + "CbBa", + "a", + 6 + ], + [ + "CbBa", + "aAb", + 7 + ], + [ + "CbBabA", + "CcCB", + 9 + ], + [ + "CbBb", + "aBccCBA", + 11 + ], + [ + "CbBbC", + "CCCbbC", + 5 + ], + [ + "CbBbbba", + "BaCCABCcC", + 15 + ], + [ + "CbBbc", + "C", + 8 + ], + [ + "CbBc", + "aAaAAbBA", + 12 + ], + [ + "CbBcB", + "b", + 8 + ], + [ + "CbC", + "AcacbAB", + 11 + ], + [ + "CbC", + "BCAc", + 5 + ], + [ + "CbC", + "Bc", + 4 + ], + [ + "CbC", + "CbB", + 2 + ], + [ + "CbC", + "b", + 4 + ], + [ + "CbCAAbb", + "bAAaC", + 8 + ], + [ + "CbCABcaC", + "aCcAACB", + 12 + ], + [ + "CbCACA", + "baAac", + 8 + ], + [ + "CbCAa", + "cCbabBb", + 10 + ], + [ + "CbCB", + "BAcbcAba", + 11 + ], + [ + "CbCBBb", + "cAbACcA", + 11 + ], + [ + "CbCBC", + "cacCccCb", + 11 + ], + [ + "CbCBCAB", + "bBBcC", + 9 + ], + [ + "CbCBcCAaa", + "aAAaAa", + 14 + ], + [ + "CbCCCc", + "BcBCaba", + 10 + ], + [ + "CbCCbAccA", + "cCbBB", + 13 + ], + [ + "CbCCcCCaB", + "bcaaab", + 11 + ], + [ + "CbCa", + "cBBaCacA", + 10 + ], + [ + "CbCaAaB", + "acaa", + 9 + ], + [ + "CbCaB", + "ACbaa", + 6 + ], + [ + "CbCaB", + "AcbAa", + 7 + ], + [ + "CbCaBCb", + "bcA", + 10 + ], + [ + "CbCaa", + "ABCBCcAb", + 10 + ], + [ + "CbCaa", + "ba", + 6 + ], + [ + "CbCaaaC", + "bAcBcBaAa", + 12 + ], + [ + "CbCb", + "Bbc", + 5 + ], + [ + "CbCbaBa", + "AbacBbabc", + 10 + ], + [ + "CbCbcC", + "Ca", + 10 + ], + [ + "CbCc", + "ACC", + 5 + ], + [ + "CbCc", + "Cabbb", + 6 + ], + [ + "CbCcAaBaA", + "cbC", + 13 + ], + [ + "CbCcAcAc", + "AcBaCaAC", + 11 + ], + [ + "CbCcBAb", + "c", + 12 + ], + [ + "CbCcBC", + "CacBbCAc", + 10 + ], + [ + "CbCcBac", + "AAbAC", + 11 + ], + [ + "Cba", + "ABBBbaab", + 12 + ], + [ + "Cba", + "AcbAbB", + 8 + ], + [ + "Cba", + "C", + 4 + ], + [ + "Cba", + "CCCbbbC", + 10 + ], + [ + "Cba", + "CCaaAa", + 8 + ], + [ + "Cba", + "CcBCCAAAA", + 14 + ], + [ + "Cba", + "aABbaC", + 8 + ], + [ + "CbaA", + "CAbCBaB", + 8 + ], + [ + "CbaA", + "CBb", + 5 + ], + [ + "CbaABAC", + "aBCBCBc", + 12 + ], + [ + "CbaAaBCaB", + "AcCcB", + 12 + ], + [ + "CbaAcBb", + "C", + 12 + ], + [ + "CbaAcc", + "acaCaaccA", + 10 + ], + [ + "CbaBA", + "ab", + 7 + ], + [ + "CbaBBcBaB", + "bB", + 14 + ], + [ + "CbaBa", + "CBC", + 6 + ], + [ + "CbaBb", + "CCCbcB", + 8 + ], + [ + "CbaBba", + "BC", + 10 + ], + [ + "CbaBcAcbC", + "cc", + 14 + ], + [ + "CbaC", + "B", + 7 + ], + [ + "CbaCA", + "BAbaAacA", + 9 + ], + [ + "CbaCABBb", + "cAB", + 11 + ], + [ + "CbaCABcbA", + "BbaCbC", + 10 + ], + [ + "CbaCAaCc", + "a", + 14 + ], + [ + "CbaCAcCba", + "BCcaB", + 12 + ], + [ + "CbaCbCA", + "ccBBAcBc", + 12 + ], + [ + "CbaaA", + "BA", + 7 + ], + [ + "CbaaBA", + "AcccAAaac", + 14 + ], + [ + "CbabAACaC", + "cABaCcbB", + 13 + ], + [ + "CbabACa", + "A", + 12 + ], + [ + "CbabAac", + "aaaB", + 9 + ], + [ + "CbabAcC", + "cbb", + 9 + ], + [ + "CbabBBBcc", + "c", + 16 + ], + [ + "CbabBCCab", + "bB", + 14 + ], + [ + "CbabC", + "CacBB", + 7 + ], + [ + "CbabbBbb", + "BaAABCC", + 11 + ], + [ + "Cbabc", + "aACbC", + 7 + ], + [ + "CbabcB", + "CBcbAcb", + 6 + ], + [ + "CbacAab", + "c", + 12 + ], + [ + "CbacCAB", + "cCC", + 10 + ], + [ + "CbacCCb", + "caaC", + 9 + ], + [ + "CbacCaCAB", + "Cbbba", + 12 + ], + [ + "Cbacaca", + "BACAc", + 8 + ], + [ + "Cbb", + "Ababcb", + 8 + ], + [ + "Cbb", + "Bb", + 3 + ], + [ + "Cbb", + "CACbbBCb", + 10 + ], + [ + "Cbb", + "CBaABccaA", + 14 + ], + [ + "Cbb", + "abcb", + 4 + ], + [ + "Cbb", + "bACBBCCaa", + 14 + ], + [ + "Cbb", + "caCCACBaB", + 14 + ], + [ + "Cbb", + "cbAcABac", + 12 + ], + [ + "CbbA", + "cAACAA", + 9 + ], + [ + "CbbAACbC", + "ccaABC", + 9 + ], + [ + "CbbABCCA", + "CBCABCA", + 5 + ], + [ + "CbbAb", + "B", + 9 + ], + [ + "CbbAbbac", + "bCBbca", + 10 + ], + [ + "CbbAcaCbC", + "CAbBbcAc", + 11 + ], + [ + "CbbB", + "A", + 8 + ], + [ + "CbbB", + "C", + 6 + ], + [ + "CbbBA", + "BBCabAB", + 10 + ], + [ + "CbbBAbcA", + "CcCCAaBb", + 12 + ], + [ + "CbbBAcCba", + "BBbbCaBA", + 11 + ], + [ + "CbbBaBcB", + "cCabACB", + 10 + ], + [ + "CbbCCacBc", + "cbbAcacab", + 8 + ], + [ + "CbbaAacC", + "bcbcbbaBa", + 13 + ], + [ + "CbbaCBAb", + "aBCBBcC", + 13 + ], + [ + "CbbbBb", + "BA", + 10 + ], + [ + "CbbbaA", + "aacCccBbB", + 15 + ], + [ + "CbbbaACba", + "aCBba", + 12 + ], + [ + "Cbbbab", + "AABAbbc", + 11 + ], + [ + "Cbbc", + "bcaAb", + 9 + ], + [ + "Cbbc", + "cba", + 5 + ], + [ + "CbbcBcAc", + "BbC", + 12 + ], + [ + "CbbcCBacB", + "AaC", + 15 + ], + [ + "Cbbcbb", + "bBaBCBA", + 10 + ], + [ + "CbbcbcabC", + "AcBcBcba", + 10 + ], + [ + "Cbbcc", + "B", + 9 + ], + [ + "Cbbcc", + "CcbA", + 6 + ], + [ + "CbbccBAaB", + "cCA", + 13 + ], + [ + "Cbbccc", + "BcA", + 9 + ], + [ + "Cbc", + "A", + 6 + ], + [ + "Cbc", + "BAa", + 6 + ], + [ + "Cbc", + "BaabcacC", + 12 + ], + [ + "Cbc", + "CBbAc", + 4 + ], + [ + "Cbc", + "aCCbab", + 8 + ], + [ + "Cbc", + "baB", + 6 + ], + [ + "Cbc", + "bcB", + 4 + ], + [ + "Cbc", + "caACbaC", + 9 + ], + [ + "Cbc", + "cbabc", + 5 + ], + [ + "CbcAB", + "AabCABAb", + 9 + ], + [ + "CbcAaaBa", + "aACA", + 12 + ], + [ + "CbcB", + "CBcC", + 3 + ], + [ + "CbcBCbB", + "CAAacC", + 11 + ], + [ + "CbcBb", + "aaCACAAcC", + 15 + ], + [ + "CbcBcb", + "AabcC", + 9 + ], + [ + "CbcBcbC", + "aCa", + 13 + ], + [ + "CbcCAAc", + "aaBBbbc", + 12 + ], + [ + "CbcCAB", + "bbaCCcc", + 9 + ], + [ + "CbcCB", + "c", + 8 + ], + [ + "CbcCBB", + "aB", + 10 + ], + [ + "CbcCCa", + "BB", + 11 + ], + [ + "CbcCcA", + "aCaacCaAa", + 10 + ], + [ + "Cbca", + "cABAAaaA", + 12 + ], + [ + "CbcaC", + "bCcabCa", + 8 + ], + [ + "Cbcb", + "AA", + 8 + ], + [ + "Cbcb", + "AaCc", + 7 + ], + [ + "Cbcb", + "CbBAa", + 6 + ], + [ + "CbcbA", + "bccbACcC", + 10 + ], + [ + "CbcbB", + "aC", + 9 + ], + [ + "CbcbBCBC", + "cBB", + 10 + ], + [ + "CbcbC", + "a", + 10 + ], + [ + "Cbcbb", + "cccAB", + 6 + ], + [ + "Cbcbcbc", + "CbaccAcCC", + 9 + ], + [ + "Cbcc", + "BbAcAabc", + 10 + ], + [ + "Cbcc", + "bbBBA", + 8 + ], + [ + "CbccCAcBA", + "acCA", + 12 + ], + [ + "CbccaACc", + "AC", + 12 + ], + [ + "Cc", + "AAbABC", + 11 + ], + [ + "Cc", + "AAcbCAca", + 12 + ], + [ + "Cc", + "ABaC", + 7 + ], + [ + "Cc", + "AC", + 3 + ], + [ + "Cc", + "ACCcCa", + 8 + ], + [ + "Cc", + "AaCCC", + 7 + ], + [ + "Cc", + "BBCBCbbb", + 13 + ], + [ + "Cc", + "BbAbcC", + 10 + ], + [ + "Cc", + "Bc", + 2 + ], + [ + "Cc", + "Bccba", + 7 + ], + [ + "Cc", + "CABACbAcB", + 14 + ], + [ + "Cc", + "CAaCbCA", + 11 + ], + [ + "Cc", + "CCCCAaC", + 11 + ], + [ + "Cc", + "CCbCaAb", + 11 + ], + [ + "Cc", + "Ccb", + 2 + ], + [ + "Cc", + "a", + 4 + ], + [ + "Cc", + "aAABCBacb", + 14 + ], + [ + "Cc", + "aAAccbC", + 11 + ], + [ + "Cc", + "aBBCbc", + 8 + ], + [ + "Cc", + "aCAcaCca", + 12 + ], + [ + "Cc", + "bB", + 4 + ], + [ + "Cc", + "baABAABbC", + 17 + ], + [ + "Cc", + "bbacA", + 8 + ], + [ + "Cc", + "bc", + 2 + ], + [ + "Cc", + "c", + 2 + ], + [ + "Cc", + "cAaAAbc", + 11 + ], + [ + "Cc", + "cBbbBbcA", + 13 + ], + [ + "Cc", + "ca", + 3 + ], + [ + "Cc", + "ccAC", + 5 + ], + [ + "Cc", + "ccCb", + 5 + ], + [ + "CcA", + "BbcbaAB", + 10 + ], + [ + "CcA", + "aCA", + 3 + ], + [ + "CcA", + "bAAbca", + 9 + ], + [ + "CcA", + "bBccA", + 5 + ], + [ + "CcA", + "bCCBb", + 7 + ], + [ + "CcA", + "cBAbaC", + 9 + ], + [ + "CcAA", + "bcACbc", + 8 + ], + [ + "CcAAAAC", + "abCa", + 12 + ], + [ + "CcAAAB", + "bBAbaC", + 9 + ], + [ + "CcAAAcCb", + "cAcBcBBC", + 11 + ], + [ + "CcAABaC", + "BbC", + 10 + ], + [ + "CcAABbc", + "BCaAbab", + 9 + ], + [ + "CcAACB", + "b", + 11 + ], + [ + "CcAAaC", + "CAbaab", + 7 + ], + [ + "CcAB", + "BbcCBc", + 8 + ], + [ + "CcAB", + "accAaa", + 7 + ], + [ + "CcABACACb", + "abBBbCAA", + 12 + ], + [ + "CcABBccA", + "cc", + 12 + ], + [ + "CcABb", + "a", + 9 + ], + [ + "CcABbabBA", + "cCA", + 14 + ], + [ + "CcABcAaa", + "Ba", + 12 + ], + [ + "CcACAbc", + "AbBB", + 11 + ], + [ + "CcACbaCA", + "abbBaBbBa", + 16 + ], + [ + "CcACcCAa", + "AaB", + 13 + ], + [ + "CcAa", + "aAbBCCc", + 13 + ], + [ + "CcAa", + "ccBC", + 5 + ], + [ + "CcAaA", + "cbcC", + 8 + ], + [ + "CcAaB", + "babCBbCAC", + 15 + ], + [ + "CcAaCABA", + "cbaBaCCCb", + 12 + ], + [ + "CcAaCcbcB", + "aBbaCAAC", + 13 + ], + [ + "CcAac", + "Cabaac", + 5 + ], + [ + "CcAacBAaC", + "bCACB", + 12 + ], + [ + "CcAb", + "b", + 6 + ], + [ + "CcAbBcBaa", + "CBc", + 12 + ], + [ + "CcAbaaA", + "cCa", + 10 + ], + [ + "CcAbcaB", + "bcA", + 9 + ], + [ + "CcAc", + "AAaaABABA", + 16 + ], + [ + "CcAcAB", + "aabAabCcb", + 14 + ], + [ + "CcAcCcC", + "cACbbac", + 10 + ], + [ + "CcAcCcc", + "A", + 12 + ], + [ + "CcB", + "AbcBBCAac", + 14 + ], + [ + "CcB", + "Ac", + 4 + ], + [ + "CcB", + "Ccb", + 1 + ], + [ + "CcB", + "ba", + 6 + ], + [ + "CcB", + "cab", + 4 + ], + [ + "CcB", + "cbc", + 5 + ], + [ + "CcBABc", + "cAAC", + 7 + ], + [ + "CcBACb", + "ac", + 10 + ], + [ + "CcBAaAa", + "aCCcB", + 12 + ], + [ + "CcBB", + "bab", + 7 + ], + [ + "CcBBA", + "B", + 8 + ], + [ + "CcBBAb", + "aBCAAc", + 10 + ], + [ + "CcBBCAAC", + "A", + 14 + ], + [ + "CcBBbac", + "Bb", + 10 + ], + [ + "CcBCBaa", + "bbbbB", + 11 + ], + [ + "CcBCCaAbC", + "aAaCaCA", + 14 + ], + [ + "CcBCCbABb", + "BbBCbccaC", + 14 + ], + [ + "CcBCaacCB", + "CAbCcbA", + 11 + ], + [ + "CcBCc", + "C", + 8 + ], + [ + "CcBCc", + "cBcba", + 7 + ], + [ + "CcBCccbb", + "abaAAAa", + 15 + ], + [ + "CcBaBb", + "BAabCcBcB", + 12 + ], + [ + "CcBaa", + "abBac", + 6 + ], + [ + "CcBabaabc", + "bCB", + 15 + ], + [ + "CcBacBC", + "aa", + 12 + ], + [ + "CcBb", + "AAB", + 6 + ], + [ + "CcBb", + "BaAcbA", + 9 + ], + [ + "CcBbC", + "A", + 10 + ], + [ + "CcBbaCbb", + "abcBCCBab", + 11 + ], + [ + "CcBbbaB", + "baCb", + 11 + ], + [ + "CcBc", + "aBabCbbcB", + 13 + ], + [ + "CcBc", + "cabcACa", + 10 + ], + [ + "CcBcABAC", + "AAC", + 10 + ], + [ + "CcBcBCBaa", + "CBA", + 13 + ], + [ + "CcC", + "CBAacacBa", + 13 + ], + [ + "CcC", + "CBbcac", + 7 + ], + [ + "CcCAA", + "cB", + 8 + ], + [ + "CcCABC", + "ACA", + 8 + ], + [ + "CcCACCb", + "CbAbCccC", + 11 + ], + [ + "CcCAaCAaB", + "ABbAAaBb", + 12 + ], + [ + "CcCAbB", + "abb", + 8 + ], + [ + "CcCAbCBc", + "cbaCBaB", + 11 + ], + [ + "CcCB", + "ABbCBAc", + 10 + ], + [ + "CcCB", + "bcaabaccc", + 14 + ], + [ + "CcCB", + "cbBaC", + 8 + ], + [ + "CcCBA", + "CbAbcb", + 9 + ], + [ + "CcCBCcCA", + "BbCcaa", + 10 + ], + [ + "CcCBb", + "aBBC", + 8 + ], + [ + "CcCBc", + "BCBb", + 6 + ], + [ + "CcCC", + "b", + 8 + ], + [ + "CcCCAB", + "CCbB", + 6 + ], + [ + "CcCCBACCa", + "ABAABAAAb", + 14 + ], + [ + "CcCCacbB", + "aACA", + 13 + ], + [ + "CcCaA", + "baa", + 7 + ], + [ + "CcCaaaaA", + "bCbbACC", + 13 + ], + [ + "CcCacAB", + "BCCBacCcb", + 10 + ], + [ + "CcCacbC", + "ACBabB", + 9 + ], + [ + "CcCbB", + "BABCbb", + 7 + ], + [ + "CcCbCA", + "aBcA", + 8 + ], + [ + "CcCbCbBbc", + "ccabB", + 11 + ], + [ + "CcCba", + "BCb", + 6 + ], + [ + "CcCbaAbB", + "aBbcaCB", + 11 + ], + [ + "CcCbcaC", + "CcBbaCbCb", + 9 + ], + [ + "CcCc", + "cBAACa", + 9 + ], + [ + "CcCcAB", + "aCBbA", + 9 + ], + [ + "CcCcAc", + "baBacaB", + 11 + ], + [ + "CcCcBB", + "bcbBbcAbB", + 11 + ], + [ + "CcCcCCAb", + "BCBBaABab", + 13 + ], + [ + "CcCca", + "bCaBAB", + 10 + ], + [ + "CcCcaB", + "aAacCCb", + 10 + ], + [ + "CcCcbCb", + "BBBCBaCC", + 12 + ], + [ + "CcCcbCb", + "cC", + 10 + ], + [ + "CcCccCbbc", + "cabBaCB", + 14 + ], + [ + "Cca", + "AbbaBABCA", + 16 + ], + [ + "Cca", + "AcacBcc", + 10 + ], + [ + "Cca", + "a", + 4 + ], + [ + "Cca", + "b", + 6 + ], + [ + "Cca", + "bAbaCBB", + 12 + ], + [ + "CcaAB", + "B", + 8 + ], + [ + "CcaABA", + "a", + 10 + ], + [ + "CcaAC", + "BaCbAbaAa", + 12 + ], + [ + "CcaACB", + "BcBbAAA", + 10 + ], + [ + "CcaACCA", + "bCacCB", + 8 + ], + [ + "CcaAa", + "cCC", + 8 + ], + [ + "CcaAbCCC", + "AbCBCb", + 10 + ], + [ + "CcaAcb", + "bcBAa", + 8 + ], + [ + "CcaAcc", + "babAAAcbB", + 13 + ], + [ + "CcaB", + "BbaCbBbCB", + 14 + ], + [ + "CcaBA", + "ACCCABCBC", + 12 + ], + [ + "CcaBaBC", + "bacAbAab", + 11 + ], + [ + "CcaBaa", + "A", + 11 + ], + [ + "CcaBcBAB", + "Ac", + 13 + ], + [ + "CcaBcC", + "A", + 11 + ], + [ + "CcaCAaabB", + "CABCacccB", + 11 + ], + [ + "CcaCCAAA", + "BCAaCCcc", + 10 + ], + [ + "CcaCa", + "BAa", + 7 + ], + [ + "CcaCabAcb", + "BaaaBAC", + 10 + ], + [ + "CcaCacbba", + "bccAB", + 13 + ], + [ + "CcaCbbA", + "CcB", + 9 + ], + [ + "CcaCcBc", + "cbaCa", + 9 + ], + [ + "Ccaa", + "AabAcaC", + 10 + ], + [ + "CcaaA", + "aaCAA", + 7 + ], + [ + "CcaaAAbc", + "aABCaCacc", + 13 + ], + [ + "CcaaBC", + "abBCaC", + 10 + ], + [ + "Ccaaa", + "cc", + 7 + ], + [ + "CcaaaAB", + "bc", + 12 + ], + [ + "Ccaaaa", + "ABbbbb", + 12 + ], + [ + "Ccaaabccc", + "cA", + 15 + ], + [ + "CcaabbCCA", + "Bbc", + 14 + ], + [ + "Ccab", + "AC", + 7 + ], + [ + "Ccab", + "Cba", + 4 + ], + [ + "Ccab", + "abBAaBB", + 11 + ], + [ + "Ccab", + "abbBCaBb", + 11 + ], + [ + "CcabACcb", + "cCAaC", + 10 + ], + [ + "Ccac", + "cbCCA", + 8 + ], + [ + "CcacB", + "cCBbaCB", + 7 + ], + [ + "CcacBabBC", + "CaBBaB", + 8 + ], + [ + "CcacC", + "AbbacBa", + 10 + ], + [ + "CcacCABB", + "ba", + 14 + ], + [ + "CcacCaA", + "CaAC", + 8 + ], + [ + "CcacaBB", + "B", + 12 + ], + [ + "CcacbC", + "cCb", + 7 + ], + [ + "Ccb", + "AcbABaCC", + 12 + ], + [ + "Ccb", + "CAA", + 4 + ], + [ + "Ccb", + "CbAcC", + 6 + ], + [ + "Ccb", + "c", + 4 + ], + [ + "CcbA", + "BccAc", + 6 + ], + [ + "CcbA", + "aabCBb", + 10 + ], + [ + "CcbA", + "bABb", + 7 + ], + [ + "CcbAACA", + "bcc", + 11 + ], + [ + "CcbAACB", + "acBBAcac", + 10 + ], + [ + "CcbAAaA", + "ccBCaCa", + 8 + ], + [ + "CcbACBA", + "A", + 12 + ], + [ + "CcbACC", + "bbaC", + 7 + ], + [ + "CcbAaBcAA", + "bAcac", + 11 + ], + [ + "CcbAc", + "AcbbBBBa", + 12 + ], + [ + "CcbBAbCcC", + "AAb", + 14 + ], + [ + "CcbBaCC", + "ABcA", + 11 + ], + [ + "CcbBac", + "BCAAA", + 10 + ], + [ + "CcbBbBBA", + "AbB", + 12 + ], + [ + "CcbBbbbbb", + "bb", + 14 + ], + [ + "CcbBc", + "cBAcacB", + 11 + ], + [ + "CcbBcAC", + "BbCcAbcbB", + 11 + ], + [ + "CcbBcaA", + "bbcca", + 8 + ], + [ + "CcbBcc", + "bbcc", + 5 + ], + [ + "CcbCA", + "a", + 9 + ], + [ + "CcbCA", + "aabAA", + 6 + ], + [ + "CcbCbB", + "CACab", + 7 + ], + [ + "CcbCbCA", + "BcaCaCAb", + 8 + ], + [ + "CcbCc", + "AC", + 8 + ], + [ + "CcbCc", + "cBbbc", + 5 + ], + [ + "CcbCcC", + "c", + 10 + ], + [ + "CcbaccBCb", + "bbCBA", + 13 + ], + [ + "CcbbABb", + "CbCbacB", + 8 + ], + [ + "CcbbaAbbB", + "bc", + 16 + ], + [ + "Ccbbb", + "CBAcACB", + 9 + ], + [ + "CcbbbC", + "cBacabCb", + 11 + ], + [ + "CcbbbCbc", + "BbCAaBaB", + 15 + ], + [ + "CcbbcABBa", + "BcAcCcBCB", + 13 + ], + [ + "Ccbc", + "ABAaaBAb", + 15 + ], + [ + "Ccc", + "B", + 6 + ], + [ + "Ccc", + "BABa", + 8 + ], + [ + "Ccc", + "BcaBAc", + 8 + ], + [ + "Ccc", + "CBB", + 4 + ], + [ + "Ccc", + "CC", + 3 + ], + [ + "Ccc", + "aaaaCC", + 10 + ], + [ + "Ccc", + "ac", + 4 + ], + [ + "Ccc", + "bb", + 6 + ], + [ + "CccABA", + "AAbBcA", + 10 + ], + [ + "CccACCB", + "AcbaC", + 9 + ], + [ + "CccAaB", + "baCaBcCa", + 12 + ], + [ + "CccAb", + "aABBc", + 10 + ], + [ + "CccAcbbca", + "c", + 16 + ], + [ + "CccBBBcB", + "bBbbCa", + 11 + ], + [ + "CccBBbC", + "Bba", + 10 + ], + [ + "CccBa", + "B", + 8 + ], + [ + "CccBa", + "caBA", + 5 + ], + [ + "CccBaaAB", + "C", + 14 + ], + [ + "CccBbBCb", + "a", + 16 + ], + [ + "CccBbca", + "BacAbCBbC", + 12 + ], + [ + "CccCAa", + "CcBcBCCc", + 8 + ], + [ + "CccCCa", + "Ba", + 10 + ], + [ + "CccCa", + "aA", + 9 + ], + [ + "CccCb", + "baA", + 10 + ], + [ + "Ccca", + "A", + 7 + ], + [ + "CccaABbBb", + "aAcB", + 12 + ], + [ + "CccaBBCb", + "BBbaaCCC", + 12 + ], + [ + "Cccaa", + "BbbC", + 10 + ], + [ + "CccacCBb", + "ccBa", + 10 + ], + [ + "CccbABBbb", + "B", + 16 + ], + [ + "Cccbbc", + "CCcBcBa", + 7 + ], + [ + "Cccc", + "BaCbb", + 9 + ], + [ + "CcccAB", + "aCBAB", + 7 + ], + [ + "CcccAbbA", + "BCBcBc", + 12 + ], + [ + "CcccBacc", + "BCAcB", + 11 + ], + [ + "CcccBcCB", + "cCAb", + 12 + ], + [ + "a", + "AA", + 3 + ], + [ + "a", + "AABaCbca", + 14 + ], + [ + "a", + "AACaBBAC", + 14 + ], + [ + "a", + "ABCaa", + 8 + ], + [ + "a", + "ABaaBCCb", + 14 + ], + [ + "a", + "ABab", + 6 + ], + [ + "a", + "ABcB", + 7 + ], + [ + "a", + "ACbcCBCB", + 15 + ], + [ + "a", + "ACbcaA", + 10 + ], + [ + "a", + "AaAA", + 6 + ], + [ + "a", + "AaABacaAA", + 16 + ], + [ + "a", + "AaAbBca", + 12 + ], + [ + "a", + "AabBCaab", + 14 + ], + [ + "a", + "AabCbCb", + 12 + ], + [ + "a", + "AaccB", + 8 + ], + [ + "a", + "Ab", + 3 + ], + [ + "a", + "AbBBaB", + 10 + ], + [ + "a", + "AbCb", + 7 + ], + [ + "a", + "AbCc", + 7 + ], + [ + "a", + "AbbbBacAa", + 16 + ], + [ + "a", + "AbcCaCbac", + 16 + ], + [ + "a", + "AcABaA", + 10 + ], + [ + "a", + "AcACCA", + 11 + ], + [ + "a", + "AcCbc", + 9 + ], + [ + "a", + "AcaB", + 6 + ], + [ + "a", + "B", + 2 + ], + [ + "a", + "BA", + 3 + ], + [ + "a", + "BABAAcBBc", + 17 + ], + [ + "a", + "BABaBa", + 10 + ], + [ + "a", + "BAC", + 5 + ], + [ + "a", + "BAaAbAc", + 12 + ], + [ + "a", + "BAabccCBc", + 16 + ], + [ + "a", + "BAbaaa", + 10 + ], + [ + "a", + "BAbb", + 7 + ], + [ + "a", + "BBAcbBB", + 13 + ], + [ + "a", + "BBBaCab", + 12 + ], + [ + "a", + "BBC", + 6 + ], + [ + "a", + "BBaCbBAC", + 14 + ], + [ + "a", + "BBcca", + 8 + ], + [ + "a", + "BCA", + 5 + ], + [ + "a", + "BCBab", + 8 + ], + [ + "a", + "BaAAAcAbc", + 16 + ], + [ + "a", + "BaAcABBC", + 14 + ], + [ + "a", + "BaBcaC", + 10 + ], + [ + "a", + "BaC", + 4 + ], + [ + "a", + "BaabBAabb", + 16 + ], + [ + "a", + "BbCaCa", + 10 + ], + [ + "a", + "BbcACCA", + 13 + ], + [ + "a", + "Bbcba", + 8 + ], + [ + "a", + "BcAb", + 7 + ], + [ + "a", + "BcBABC", + 11 + ], + [ + "a", + "BcBaAacC", + 14 + ], + [ + "a", + "Bca", + 4 + ], + [ + "a", + "Bcabba", + 10 + ], + [ + "a", + "BccCbbAb", + 15 + ], + [ + "a", + "C", + 2 + ], + [ + "a", + "CA", + 3 + ], + [ + "a", + "CABAcBbc", + 15 + ], + [ + "a", + "CABCB", + 9 + ], + [ + "a", + "CAbC", + 7 + ], + [ + "a", + "CAba", + 6 + ], + [ + "a", + "CAcCAa", + 10 + ], + [ + "a", + "CAcc", + 7 + ], + [ + "a", + "CBA", + 5 + ], + [ + "a", + "CBABB", + 9 + ], + [ + "a", + "CBAa", + 6 + ], + [ + "a", + "CBBCcB", + 12 + ], + [ + "a", + "CBBcA", + 9 + ], + [ + "a", + "CBaCAC", + 10 + ], + [ + "a", + "CBbaCCbC", + 14 + ], + [ + "a", + "CCBc", + 8 + ], + [ + "a", + "CCcaC", + 8 + ], + [ + "a", + "Ca", + 2 + ], + [ + "a", + "CaAaC", + 8 + ], + [ + "a", + "CaBacbb", + 12 + ], + [ + "a", + "CaabacC", + 12 + ], + [ + "a", + "CbBc", + 8 + ], + [ + "a", + "CbbcAB", + 11 + ], + [ + "a", + "CcBBaaCc", + 14 + ], + [ + "a", + "CcBbabBAc", + 16 + ], + [ + "a", + "CcaACcB", + 12 + ], + [ + "a", + "Ccca", + 6 + ], + [ + "a", + "a", + 0 + ], + [ + "a", + "aA", + 2 + ], + [ + "a", + "aAACAbCC", + 14 + ], + [ + "a", + "aACABcAb", + 14 + ], + [ + "a", + "aAbaB", + 8 + ], + [ + "a", + "aBB", + 4 + ], + [ + "a", + "aBBCb", + 8 + ], + [ + "a", + "aBaCbb", + 10 + ], + [ + "a", + "aBb", + 4 + ], + [ + "a", + "aC", + 2 + ], + [ + "a", + "aCCCCcab", + 14 + ], + [ + "a", + "aCaBBABa", + 14 + ], + [ + "a", + "aCaC", + 6 + ], + [ + "a", + "aCb", + 4 + ], + [ + "a", + "aCcBaAa", + 12 + ], + [ + "a", + "aa", + 2 + ], + [ + "a", + "aaBbC", + 8 + ], + [ + "a", + "aaCA", + 6 + ], + [ + "a", + "ab", + 2 + ], + [ + "a", + "abACBBAcC", + 16 + ], + [ + "a", + "abBbBba", + 12 + ], + [ + "a", + "abCaAaCbC", + 16 + ], + [ + "a", + "aba", + 4 + ], + [ + "a", + "abcac", + 8 + ], + [ + "a", + "acAcBAbaB", + 16 + ], + [ + "a", + "acBcAA", + 10 + ], + [ + "a", + "accCCCc", + 12 + ], + [ + "a", + "b", + 2 + ], + [ + "a", + "bA", + 3 + ], + [ + "a", + "bAAaB", + 8 + ], + [ + "a", + "bABBa", + 8 + ], + [ + "a", + "bACca", + 8 + ], + [ + "a", + "bAbAccb", + 13 + ], + [ + "a", + "bAccbcaAB", + 16 + ], + [ + "a", + "bBAca", + 8 + ], + [ + "a", + "bBBC", + 8 + ], + [ + "a", + "bBBCaccC", + 14 + ], + [ + "a", + "bBCb", + 8 + ], + [ + "a", + "bBbC", + 8 + ], + [ + "a", + "bBbCABa", + 12 + ], + [ + "a", + "bC", + 4 + ], + [ + "a", + "bCBacAcC", + 14 + ], + [ + "a", + "bCC", + 6 + ], + [ + "a", + "bCCbaccA", + 14 + ], + [ + "a", + "bCbA", + 7 + ], + [ + "a", + "bCbBab", + 10 + ], + [ + "a", + "bCcaCbc", + 12 + ], + [ + "a", + "bCcaaCbB", + 14 + ], + [ + "a", + "ba", + 2 + ], + [ + "a", + "baa", + 4 + ], + [ + "a", + "baacacaba", + 16 + ], + [ + "a", + "babcA", + 8 + ], + [ + "a", + "babcCAA", + 12 + ], + [ + "a", + "bb", + 4 + ], + [ + "a", + "bbAc", + 7 + ], + [ + "a", + "bbB", + 6 + ], + [ + "a", + "bbBA", + 7 + ], + [ + "a", + "bbBBcaBc", + 14 + ], + [ + "a", + "bbBbAaAAc", + 16 + ], + [ + "a", + "bbCCaACb", + 14 + ], + [ + "a", + "bbCaca", + 10 + ], + [ + "a", + "bbaC", + 6 + ], + [ + "a", + "bbbAcAB", + 13 + ], + [ + "a", + "bbbBAABC", + 15 + ], + [ + "a", + "bbcCBcB", + 14 + ], + [ + "a", + "bcAca", + 8 + ], + [ + "a", + "bcAcacCB", + 14 + ], + [ + "a", + "bcaAcBAbC", + 16 + ], + [ + "a", + "bcb", + 6 + ], + [ + "a", + "bcc", + 6 + ], + [ + "a", + "c", + 2 + ], + [ + "a", + "cAC", + 5 + ], + [ + "a", + "cACBACca", + 14 + ], + [ + "a", + "cACaCa", + 10 + ], + [ + "a", + "cAa", + 4 + ], + [ + "a", + "cBAaa", + 8 + ], + [ + "a", + "cBbBbab", + 12 + ], + [ + "a", + "cC", + 4 + ], + [ + "a", + "cCBA", + 7 + ], + [ + "a", + "cCCa", + 6 + ], + [ + "a", + "cCCbaa", + 10 + ], + [ + "a", + "cCaCcb", + 10 + ], + [ + "a", + "cCacac", + 10 + ], + [ + "a", + "cCcBbCBAa", + 16 + ], + [ + "a", + "cabbcaBBc", + 16 + ], + [ + "a", + "cb", + 4 + ], + [ + "a", + "cbAcAab", + 12 + ], + [ + "a", + "cbAcCB", + 11 + ], + [ + "a", + "cbBaC", + 8 + ], + [ + "a", + "cbCcbC", + 12 + ], + [ + "a", + "cbaCbbBb", + 14 + ], + [ + "a", + "cbbAaCA", + 12 + ], + [ + "a", + "ccACCaBAa", + 16 + ], + [ + "a", + "ccACbaC", + 12 + ], + [ + "a", + "ccAbAC", + 11 + ], + [ + "a", + "ccAbbaBA", + 14 + ], + [ + "a", + "ccCBaCcB", + 14 + ], + [ + "a", + "ccac", + 6 + ], + [ + "aA", + "AAc", + 3 + ], + [ + "aA", + "ABcACbCcb", + 15 + ], + [ + "aA", + "ACcbCBA", + 11 + ], + [ + "aA", + "AacACCa", + 10 + ], + [ + "aA", + "B", + 4 + ], + [ + "aA", + "BabBBcCbC", + 16 + ], + [ + "aA", + "Babb", + 6 + ], + [ + "aA", + "BcAcB", + 8 + ], + [ + "aA", + "CAacB", + 8 + ], + [ + "aA", + "CBABBaAB", + 12 + ], + [ + "aA", + "CaBbbbA", + 10 + ], + [ + "aA", + "CcAabB", + 10 + ], + [ + "aA", + "CcaAb", + 6 + ], + [ + "aA", + "a", + 2 + ], + [ + "aA", + "aCAcAb", + 8 + ], + [ + "aA", + "aCBb", + 6 + ], + [ + "aA", + "aCacaAA", + 10 + ], + [ + "aA", + "aaACBacA", + 12 + ], + [ + "aA", + "aaC", + 3 + ], + [ + "aA", + "abbAaBC", + 10 + ], + [ + "aA", + "abbBBbc", + 12 + ], + [ + "aA", + "bAc", + 4 + ], + [ + "aA", + "bB", + 4 + ], + [ + "aA", + "bBCBC", + 10 + ], + [ + "aA", + "baCBAbCa", + 12 + ], + [ + "aA", + "cABBaA", + 8 + ], + [ + "aA", + "cBc", + 6 + ], + [ + "aA", + "cabbabbA", + 12 + ], + [ + "aA", + "ccbcB", + 10 + ], + [ + "aAA", + "aACbBCCb", + 12 + ], + [ + "aAA", + "ac", + 4 + ], + [ + "aAA", + "bAc", + 4 + ], + [ + "aAAA", + "AaAC", + 4 + ], + [ + "aAAAA", + "c", + 10 + ], + [ + "aAAAAC", + "CbaaCCBBa", + 14 + ], + [ + "aAAAAaAA", + "cbAabBb", + 13 + ], + [ + "aAAABb", + "BABBaB", + 9 + ], + [ + "aAAAC", + "bC", + 8 + ], + [ + "aAAAaAb", + "AAC", + 10 + ], + [ + "aAAAabBca", + "AB", + 14 + ], + [ + "aAAAcCbCB", + "CcBbABBB", + 15 + ], + [ + "aAAB", + "A", + 6 + ], + [ + "aAAB", + "bcabAb", + 7 + ], + [ + "aAAB", + "c", + 8 + ], + [ + "aAAB", + "cCAB", + 4 + ], + [ + "aAABCcCcC", + "CbBBCAB", + 14 + ], + [ + "aAABbBACb", + "aACb", + 10 + ], + [ + "aAACC", + "ccbbaBA", + 13 + ], + [ + "aAACaCa", + "ACbabAc", + 11 + ], + [ + "aAAaAAaa", + "ACBcbbcaA", + 14 + ], + [ + "aAAaaaB", + "BABbaaAbA", + 10 + ], + [ + "aAAabaAbA", + "bcCBbaBB", + 13 + ], + [ + "aAAacaaC", + "a", + 14 + ], + [ + "aAAb", + "aCAA", + 4 + ], + [ + "aAAbBbaA", + "BaaaAbb", + 11 + ], + [ + "aAAbCbCcC", + "cBC", + 14 + ], + [ + "aAAbbA", + "bcbbaBa", + 10 + ], + [ + "aAAc", + "AccBbB", + 10 + ], + [ + "aAAcA", + "BBBABa", + 9 + ], + [ + "aAAcA", + "bb", + 10 + ], + [ + "aAAcAA", + "aCAA", + 5 + ], + [ + "aAAcAa", + "CbCAa", + 7 + ], + [ + "aAAcAaa", + "bAAACb", + 8 + ], + [ + "aAAcB", + "AbcACA", + 8 + ], + [ + "aAAcBBba", + "BcaAcACb", + 11 + ], + [ + "aAAcCCbCB", + "C", + 16 + ], + [ + "aAAcCaCc", + "caACAaAa", + 10 + ], + [ + "aAAcCb", + "bbAbA", + 10 + ], + [ + "aAAcabaab", + "cAACAbb", + 8 + ], + [ + "aAAcbACab", + "bCcAaBbCC", + 15 + ], + [ + "aAAcc", + "aaAC", + 4 + ], + [ + "aAB", + "AAaAcCaa", + 12 + ], + [ + "aAB", + "AbCBB", + 7 + ], + [ + "aAB", + "AcaAB", + 4 + ], + [ + "aAB", + "CAbaA", + 7 + ], + [ + "aAB", + "CCBAcbaCC", + 15 + ], + [ + "aAB", + "aBcbbB", + 8 + ], + [ + "aAB", + "aCCcaBCC", + 11 + ], + [ + "aAB", + "bcbccABCA", + 14 + ], + [ + "aABA", + "cCac", + 8 + ], + [ + "aABAB", + "AaaBBcCA", + 11 + ], + [ + "aABACAa", + "CcBBbA", + 10 + ], + [ + "aABAaA", + "C", + 12 + ], + [ + "aABAb", + "BbBCC", + 8 + ], + [ + "aABAb", + "ca", + 9 + ], + [ + "aABAbab", + "a", + 12 + ], + [ + "aABAc", + "AabAabaB", + 10 + ], + [ + "aABAcCbbA", + "aB", + 14 + ], + [ + "aABB", + "CCAaaccbA", + 14 + ], + [ + "aABB", + "aCac", + 6 + ], + [ + "aABB", + "cb", + 7 + ], + [ + "aABBBBCc", + "cBAcbb", + 13 + ], + [ + "aABBBBa", + "CaBaCCBB", + 11 + ], + [ + "aABBCc", + "cc", + 9 + ], + [ + "aABBacCA", + "BBbacBc", + 9 + ], + [ + "aABBbA", + "aCBbC", + 6 + ], + [ + "aABBbaB", + "CbbBCbacb", + 10 + ], + [ + "aABCAa", + "bBbC", + 9 + ], + [ + "aABCB", + "cAB", + 6 + ], + [ + "aABCCcbB", + "CBbaCcbc", + 9 + ], + [ + "aABCaca", + "Bb", + 12 + ], + [ + "aABCbCba", + "CabccBaB", + 11 + ], + [ + "aABaBA", + "BC", + 10 + ], + [ + "aABaBbAAA", + "B", + 16 + ], + [ + "aABb", + "BC", + 6 + ], + [ + "aABbAa", + "bCbBcC", + 10 + ], + [ + "aABbBbCca", + "ABCCBAbAc", + 12 + ], + [ + "aABbaA", + "bcBC", + 10 + ], + [ + "aABbac", + "AbBbABAAb", + 12 + ], + [ + "aABbccca", + "BcaA", + 11 + ], + [ + "aABcACB", + "A", + 12 + ], + [ + "aABccB", + "A", + 10 + ], + [ + "aAC", + "BA", + 4 + ], + [ + "aAC", + "CAbbaab", + 11 + ], + [ + "aAC", + "CbC", + 4 + ], + [ + "aAC", + "b", + 6 + ], + [ + "aAC", + "bACCbC", + 8 + ], + [ + "aAC", + "bcaBacc", + 10 + ], + [ + "aACABAcCa", + "ccCB", + 13 + ], + [ + "aACBA", + "Aa", + 7 + ], + [ + "aACBACA", + "BaCBa", + 8 + ], + [ + "aACBBcBC", + "A", + 14 + ], + [ + "aACCA", + "Cb", + 8 + ], + [ + "aACCAAb", + "Bca", + 12 + ], + [ + "aACCBc", + "AcbAaCB", + 9 + ], + [ + "aACCa", + "ACccABA", + 10 + ], + [ + "aACCbAA", + "AAaa", + 9 + ], + [ + "aACCc", + "BBcc", + 7 + ], + [ + "aACCc", + "cbaBAC", + 10 + ], + [ + "aACaaA", + "bcACaCbA", + 8 + ], + [ + "aACacACa", + "aaBccaB", + 10 + ], + [ + "aACacCb", + "C", + 12 + ], + [ + "aACaccCAC", + "cC", + 14 + ], + [ + "aACbAC", + "AB", + 9 + ], + [ + "aACbBBcb", + "b", + 14 + ], + [ + "aACbbbaBC", + "aBBACCB", + 13 + ], + [ + "aACcaBb", + "ABabA", + 9 + ], + [ + "aACcbCa", + "b", + 12 + ], + [ + "aAa", + "BbBb", + 8 + ], + [ + "aAa", + "CBCBAabb", + 12 + ], + [ + "aAa", + "Cc", + 6 + ], + [ + "aAa", + "bCaaCBcAa", + 12 + ], + [ + "aAa", + "bc", + 6 + ], + [ + "aAaA", + "b", + 8 + ], + [ + "aAaAcc", + "B", + 12 + ], + [ + "aAaAccAb", + "BCAbabcAA", + 11 + ], + [ + "aAaBBCb", + "Cbbc", + 11 + ], + [ + "aAaBaBBBc", + "cAcCCCA", + 16 + ], + [ + "aAaBaBa", + "bBbBc", + 10 + ], + [ + "aAaCB", + "cCc", + 8 + ], + [ + "aAaCCCc", + "bbcBabaAA", + 16 + ], + [ + "aAaCaaAc", + "BCaA", + 10 + ], + [ + "aAaa", + "bb", + 8 + ], + [ + "aAaaAcCA", + "cBbcccB", + 13 + ], + [ + "aAaaBbbb", + "bCca", + 14 + ], + [ + "aAaaC", + "aCAC", + 5 + ], + [ + "aAaaCBa", + "aaCBCc", + 8 + ], + [ + "aAaaaA", + "aBACbaBAC", + 10 + ], + [ + "aAaabBcb", + "AcCAcBA", + 12 + ], + [ + "aAab", + "C", + 8 + ], + [ + "aAab", + "bCaB", + 5 + ], + [ + "aAab", + "bbaacCCB", + 12 + ], + [ + "aAabC", + "ccbBa", + 9 + ], + [ + "aAabCAc", + "aBCb", + 9 + ], + [ + "aAabCCBaa", + "bBC", + 14 + ], + [ + "aAabbbbB", + "CBAACBCCb", + 13 + ], + [ + "aAabbcCaA", + "A", + 16 + ], + [ + "aAac", + "cCBbCAaBB", + 14 + ], + [ + "aAacB", + "cAcbcBa", + 8 + ], + [ + "aAacBcCBa", + "cba", + 13 + ], + [ + "aAb", + "A", + 4 + ], + [ + "aAb", + "a", + 4 + ], + [ + "aAb", + "b", + 4 + ], + [ + "aAbA", + "bccaaaCAB", + 13 + ], + [ + "aAbABAA", + "bCBAcabBb", + 14 + ], + [ + "aAbAC", + "cACcCa", + 8 + ], + [ + "aAbACaBAA", + "CB", + 14 + ], + [ + "aAbAb", + "cBBabc", + 8 + ], + [ + "aAbAcCb", + "c", + 12 + ], + [ + "aAbBB", + "AC", + 8 + ], + [ + "aAbBaBcAA", + "C", + 17 + ], + [ + "aAbCAcbCC", + "BAAaA", + 14 + ], + [ + "aAbCBA", + "aCBaCABc", + 9 + ], + [ + "aAbCCACCb", + "AbcacbAb", + 11 + ], + [ + "aAbCCC", + "Aca", + 9 + ], + [ + "aAbCa", + "bABc", + 6 + ], + [ + "aAbCbCa", + "AabbBCbA", + 8 + ], + [ + "aAbCbbaba", + "CcBbccaB", + 14 + ], + [ + "aAbCc", + "cCa", + 8 + ], + [ + "aAba", + "BbcbcCBcC", + 16 + ], + [ + "aAbaBA", + "aBAAAA", + 7 + ], + [ + "aAbaBBba", + "Cb", + 14 + ], + [ + "aAbaCAA", + "cAB", + 11 + ], + [ + "aAbaaBA", + "bcCbaccBA", + 10 + ], + [ + "aAbb", + "bBBaACCBC", + 13 + ], + [ + "aAbbABabC", + "cbACbB", + 12 + ], + [ + "aAbbBab", + "caaA", + 11 + ], + [ + "aAbbCAA", + "BBbBcbA", + 8 + ], + [ + "aAbbCbCCa", + "AAB", + 14 + ], + [ + "aAbbCbcb", + "CBc", + 11 + ], + [ + "aAbbaB", + "a", + 10 + ], + [ + "aAbbacAb", + "BccBb", + 11 + ], + [ + "aAbbcbA", + "A", + 12 + ], + [ + "aAbcCaA", + "CCc", + 11 + ], + [ + "aAbcaABCA", + "BCAcbCab", + 13 + ], + [ + "aAbcaAa", + "CCababB", + 11 + ], + [ + "aAbcbbB", + "baba", + 10 + ], + [ + "aAc", + "aBbBCbac", + 11 + ], + [ + "aAc", + "abbAbaC", + 9 + ], + [ + "aAcA", + "A", + 6 + ], + [ + "aAcA", + "ACABBCB", + 10 + ], + [ + "aAcAAb", + "ACC", + 9 + ], + [ + "aAcAAbB", + "cAbbBaCBb", + 13 + ], + [ + "aAcAabacA", + "aCbBcA", + 9 + ], + [ + "aAcAacaba", + "caACb", + 11 + ], + [ + "aAcAbaCac", + "bBc", + 14 + ], + [ + "aAcAcAbaB", + "bcCCa", + 13 + ], + [ + "aAcB", + "aaaCC", + 6 + ], + [ + "aAcB", + "caC", + 6 + ], + [ + "aAcBACBB", + "a", + 14 + ], + [ + "aAcBC", + "aCca", + 6 + ], + [ + "aAcBbABB", + "AA", + 12 + ], + [ + "aAcBbAaBC", + "BbCbaCcaC", + 14 + ], + [ + "aAcCAaC", + "b", + 14 + ], + [ + "aAcCCcAc", + "baabCBAaA", + 12 + ], + [ + "aAcCccBB", + "AaAa", + 14 + ], + [ + "aAcaAaB", + "AcC", + 10 + ], + [ + "aAcaBaA", + "ACcaaA", + 5 + ], + [ + "aAcaaac", + "BaABaBaBA", + 10 + ], + [ + "aAcb", + "AABbA", + 5 + ], + [ + "aAcb", + "aABC", + 4 + ], + [ + "aAcbA", + "cbcAAC", + 8 + ], + [ + "aAcbBb", + "CbcccCBcC", + 14 + ], + [ + "aAcbBcca", + "A", + 14 + ], + [ + "aAcba", + "acBcBBBAc", + 12 + ], + [ + "aAcba", + "b", + 8 + ], + [ + "aAcc", + "CACC", + 4 + ], + [ + "aAccac", + "ACABCBBAC", + 12 + ], + [ + "aAccbCaba", + "BCBbBc", + 14 + ], + [ + "aB", + "A", + 3 + ], + [ + "aB", + "AA", + 3 + ], + [ + "aB", + "AB", + 1 + ], + [ + "aB", + "ABAb", + 5 + ], + [ + "aB", + "ACcb", + 6 + ], + [ + "aB", + "Aabaaa", + 9 + ], + [ + "aB", + "AccabABB", + 12 + ], + [ + "aB", + "B", + 2 + ], + [ + "aB", + "BBcbB", + 8 + ], + [ + "aB", + "BCc", + 6 + ], + [ + "aB", + "Bca", + 6 + ], + [ + "aB", + "C", + 4 + ], + [ + "aB", + "CAAaa", + 8 + ], + [ + "aB", + "CbccACC", + 13 + ], + [ + "aB", + "Cc", + 4 + ], + [ + "aB", + "CcAcCC", + 11 + ], + [ + "aB", + "aCbBBc", + 8 + ], + [ + "aB", + "aaAbCb", + 9 + ], + [ + "aB", + "aaaAb", + 7 + ], + [ + "aB", + "aabCACc", + 11 + ], + [ + "aB", + "abAC", + 5 + ], + [ + "aB", + "bB", + 2 + ], + [ + "aB", + "bBB", + 4 + ], + [ + "aB", + "bb", + 3 + ], + [ + "aB", + "bbbca", + 9 + ], + [ + "aB", + "bbc", + 5 + ], + [ + "aB", + "bc", + 4 + ], + [ + "aB", + "bcb", + 5 + ], + [ + "aB", + "cB", + 2 + ], + [ + "aB", + "cCC", + 6 + ], + [ + "aB", + "cc", + 4 + ], + [ + "aBA", + "BAaAaaCBc", + 14 + ], + [ + "aBAAA", + "CBCAbbcAA", + 10 + ], + [ + "aBAAB", + "BacBABcAc", + 10 + ], + [ + "aBAAaB", + "caAc", + 9 + ], + [ + "aBAAacaa", + "acabBBcBC", + 13 + ], + [ + "aBAAbCcB", + "BCB", + 10 + ], + [ + "aBAAcbCc", + "cBCBBcAAB", + 14 + ], + [ + "aBAB", + "aaCc", + 6 + ], + [ + "aBAB", + "bbaAbA", + 8 + ], + [ + "aBABa", + "bacAa", + 6 + ], + [ + "aBABaABc", + "AAaCCC", + 10 + ], + [ + "aBABcaABA", + "CBcbB", + 12 + ], + [ + "aBACC", + "a", + 8 + ], + [ + "aBACa", + "c", + 9 + ], + [ + "aBACba", + "C", + 10 + ], + [ + "aBACcAA", + "B", + 12 + ], + [ + "aBAa", + "aaB", + 5 + ], + [ + "aBAaC", + "cCACbbBb", + 14 + ], + [ + "aBAabaAB", + "cacCbb", + 13 + ], + [ + "aBAabba", + "AaBABbCBc", + 9 + ], + [ + "aBAacCbbb", + "aBaCaAc", + 10 + ], + [ + "aBAacc", + "aAaAAcABC", + 10 + ], + [ + "aBAb", + "aBBbAac", + 8 + ], + [ + "aBAbAC", + "aABAbCAc", + 5 + ], + [ + "aBAbaaab", + "CCbbAaba", + 11 + ], + [ + "aBAbbB", + "aCacbAB", + 7 + ], + [ + "aBAbbcbb", + "bcBAb", + 11 + ], + [ + "aBAcABbb", + "Ca", + 14 + ], + [ + "aBAcBa", + "CbBcCaa", + 9 + ], + [ + "aBAcBbC", + "aaAaBac", + 7 + ], + [ + "aBAca", + "AACACCcAa", + 11 + ], + [ + "aBAcabBA", + "BBACb", + 9 + ], + [ + "aBAcba", + "bBaaCcB", + 10 + ], + [ + "aBAccCaba", + "CAcabBBbC", + 14 + ], + [ + "aBAcca", + "ABAABbCa", + 8 + ], + [ + "aBB", + "AaAbaAaBb", + 13 + ], + [ + "aBB", + "AaCaB", + 6 + ], + [ + "aBB", + "Acbc", + 6 + ], + [ + "aBB", + "aC", + 4 + ], + [ + "aBB", + "aa", + 4 + ], + [ + "aBB", + "bbCAAaBBB", + 12 + ], + [ + "aBBA", + "BAAc", + 6 + ], + [ + "aBBABAaAA", + "AbCAcbAA", + 10 + ], + [ + "aBBABaaaa", + "bCC", + 17 + ], + [ + "aBBABca", + "bA", + 11 + ], + [ + "aBBACC", + "caaCB", + 9 + ], + [ + "aBBAc", + "aCAA", + 6 + ], + [ + "aBBB", + "AcBcBa", + 7 + ], + [ + "aBBBA", + "CcbaAB", + 9 + ], + [ + "aBBBABAB", + "BBA", + 10 + ], + [ + "aBBBACB", + "Aa", + 12 + ], + [ + "aBBBAaA", + "bB", + 11 + ], + [ + "aBBBB", + "AaBb", + 6 + ], + [ + "aBBBCCBbb", + "BCBca", + 12 + ], + [ + "aBBBaBaAa", + "cCCB", + 16 + ], + [ + "aBBC", + "AbabA", + 7 + ], + [ + "aBBC", + "CcbcBBCb", + 10 + ], + [ + "aBBC", + "cCbbBa", + 9 + ], + [ + "aBBCBac", + "AbacacaCC", + 12 + ], + [ + "aBBCBbab", + "bb", + 12 + ], + [ + "aBBCaCCAB", + "ccBAcA", + 12 + ], + [ + "aBBCbAb", + "cACACb", + 10 + ], + [ + "aBBCbB", + "aCabbA", + 8 + ], + [ + "aBBCcabCb", + "CCacAacc", + 14 + ], + [ + "aBBaB", + "BCaccaa", + 10 + ], + [ + "aBBaB", + "bACCbA", + 11 + ], + [ + "aBBaCCab", + "CBcAbcC", + 12 + ], + [ + "aBBaa", + "a", + 8 + ], + [ + "aBBabAb", + "bACbcAa", + 11 + ], + [ + "aBBac", + "BbAa", + 6 + ], + [ + "aBBacABac", + "CbCbc", + 13 + ], + [ + "aBBb", + "BCAaBa", + 9 + ], + [ + "aBBbA", + "aaa", + 7 + ], + [ + "aBBbB", + "bbBaba", + 7 + ], + [ + "aBBbba", + "bCCcacbB", + 14 + ], + [ + "aBBc", + "BccbaCCac", + 14 + ], + [ + "aBBcABB", + "BBcAbCBAB", + 8 + ], + [ + "aBBcBAab", + "CcCBBA", + 12 + ], + [ + "aBBcBBA", + "cC", + 12 + ], + [ + "aBBcBcb", + "BBBca", + 6 + ], + [ + "aBBcaB", + "AbBAa", + 6 + ], + [ + "aBBccB", + "abcac", + 7 + ], + [ + "aBBcca", + "bABb", + 10 + ], + [ + "aBBcccbCB", + "bCcab", + 12 + ], + [ + "aBC", + "AABCBaAAC", + 13 + ], + [ + "aBC", + "CcaCAB", + 10 + ], + [ + "aBC", + "aACCc", + 6 + ], + [ + "aBC", + "aaaCcCcB", + 12 + ], + [ + "aBC", + "bABBAa", + 9 + ], + [ + "aBC", + "bC", + 3 + ], + [ + "aBC", + "baCCa", + 6 + ], + [ + "aBC", + "bc", + 4 + ], + [ + "aBCA", + "AbbcbAb", + 9 + ], + [ + "aBCA", + "CBaAa", + 6 + ], + [ + "aBCAa", + "BbCCAbAAb", + 12 + ], + [ + "aBCAcBAa", + "BC", + 12 + ], + [ + "aBCAcBCAC", + "AABaCbBcA", + 12 + ], + [ + "aBCAccBCB", + "b", + 17 + ], + [ + "aBCBA", + "b", + 9 + ], + [ + "aBCBBCa", + "aCCAaa", + 8 + ], + [ + "aBCBC", + "bCccB", + 8 + ], + [ + "aBCBC", + "bbB", + 7 + ], + [ + "aBCBabb", + "a", + 12 + ], + [ + "aBCCcc", + "caAAc", + 10 + ], + [ + "aBCaB", + "cB", + 7 + ], + [ + "aBCaCa", + "aCA", + 7 + ], + [ + "aBCaCbC", + "BcaaBaABA", + 13 + ], + [ + "aBCab", + "cAacAcCaA", + 12 + ], + [ + "aBCababA", + "ccbABc", + 11 + ], + [ + "aBCac", + "CbCBbaAB", + 11 + ], + [ + "aBCb", + "acabaC", + 8 + ], + [ + "aBCbb", + "C", + 8 + ], + [ + "aBCbbB", + "bCcBb", + 7 + ], + [ + "aBCbcCBc", + "cBaCAc", + 10 + ], + [ + "aBCc", + "bABcbCa", + 9 + ], + [ + "aBCcAc", + "cCAaaAc", + 10 + ], + [ + "aBCcAcAC", + "BCcBaca", + 8 + ], + [ + "aBCcCBaa", + "b", + 15 + ], + [ + "aBCcCBbcC", + "ba", + 16 + ], + [ + "aBCcaBAaC", + "bBbcaCC", + 10 + ], + [ + "aBa", + "cBCbb", + 8 + ], + [ + "aBa", + "caB", + 4 + ], + [ + "aBaA", + "caBAC", + 5 + ], + [ + "aBaAaAcC", + "CAbBbbabc", + 13 + ], + [ + "aBaAcCBBA", + "AcAcc", + 12 + ], + [ + "aBaAcCC", + "Bc", + 10 + ], + [ + "aBaB", + "CBBbc", + 7 + ], + [ + "aBaB", + "bBAaA", + 6 + ], + [ + "aBaBC", + "CBbcaaBA", + 10 + ], + [ + "aBaBbA", + "CCabBBAaC", + 11 + ], + [ + "aBaBbCcc", + "aB", + 12 + ], + [ + "aBaBc", + "CcCAb", + 10 + ], + [ + "aBaC", + "A", + 7 + ], + [ + "aBaC", + "aa", + 4 + ], + [ + "aBaC", + "accAbAC", + 8 + ], + [ + "aBaCCAb", + "cbBC", + 11 + ], + [ + "aBaCaA", + "Aa", + 9 + ], + [ + "aBaCaC", + "CbaCccAc", + 9 + ], + [ + "aBaCaabAc", + "bCcACb", + 13 + ], + [ + "aBaCba", + "baB", + 8 + ], + [ + "aBaa", + "CBaBAABbB", + 12 + ], + [ + "aBaa", + "Cb", + 7 + ], + [ + "aBaaA", + "aAAaABCB", + 9 + ], + [ + "aBaabC", + "bCBbAabAC", + 9 + ], + [ + "aBaabCba", + "bCCaB", + 12 + ], + [ + "aBaabaB", + "AA", + 12 + ], + [ + "aBaacBbca", + "cCc", + 14 + ], + [ + "aBabACAA", + "acABb", + 12 + ], + [ + "aBabBcb", + "bAbA", + 10 + ], + [ + "aBabbaBbc", + "cbaccAb", + 12 + ], + [ + "aBac", + "c", + 6 + ], + [ + "aBacAAcA", + "aaCB", + 11 + ], + [ + "aBacBB", + "cb", + 9 + ], + [ + "aBacC", + "ACCCcAb", + 11 + ], + [ + "aBacCB", + "abccAac", + 9 + ], + [ + "aBaccCAa", + "aBcacaaCb", + 10 + ], + [ + "aBb", + "BCBAabbac", + 13 + ], + [ + "aBb", + "Ccb", + 4 + ], + [ + "aBb", + "aaac", + 6 + ], + [ + "aBb", + "bbcbbbAaC", + 15 + ], + [ + "aBb", + "cbCaBb", + 6 + ], + [ + "aBb", + "cbaB", + 6 + ], + [ + "aBbA", + "bbaaAbab", + 11 + ], + [ + "aBbACC", + "cCcccBCC", + 12 + ], + [ + "aBbAcCBCA", + "cCBab", + 12 + ], + [ + "aBbB", + "BacA", + 8 + ], + [ + "aBbB", + "aCcCb", + 7 + ], + [ + "aBbBA", + "aAcC", + 8 + ], + [ + "aBbBB", + "aBCc", + 6 + ], + [ + "aBbBCbBAa", + "Ac", + 16 + ], + [ + "aBbBa", + "bAa", + 6 + ], + [ + "aBbBbAbC", + "Abc", + 11 + ], + [ + "aBbBbaBA", + "AbbBCccC", + 10 + ], + [ + "aBbBbcBcb", + "abaBAAAAB", + 12 + ], + [ + "aBbC", + "bCbBAcBc", + 12 + ], + [ + "aBbCABBA", + "Caa", + 12 + ], + [ + "aBbCACaCb", + "A", + 16 + ], + [ + "aBbCBCaBC", + "aCcc", + 12 + ], + [ + "aBbCaa", + "cbAC", + 9 + ], + [ + "aBbCbbbBA", + "aA", + 14 + ], + [ + "aBbCbcCAb", + "BcAC", + 12 + ], + [ + "aBbCc", + "AcACCCba", + 12 + ], + [ + "aBba", + "BcAcCBB", + 12 + ], + [ + "aBbaAACBA", + "BacacbaC", + 12 + ], + [ + "aBbaAB", + "bbCc", + 9 + ], + [ + "aBbaBcC", + "c", + 12 + ], + [ + "aBbaCcbC", + "bbbbcab", + 10 + ], + [ + "aBbaaCcaA", + "bBABBAbCc", + 13 + ], + [ + "aBbabCc", + "CaCB", + 10 + ], + [ + "aBbb", + "Bb", + 4 + ], + [ + "aBbb", + "cccAbB", + 9 + ], + [ + "aBbbA", + "AAC", + 9 + ], + [ + "aBbbAB", + "C", + 12 + ], + [ + "aBbbCab", + "AaCBacaba", + 10 + ], + [ + "aBbbbBA", + "BcbbBBA", + 5 + ], + [ + "aBbcCBaCc", + "C", + 16 + ], + [ + "aBbcCba", + "BbAcaBac", + 9 + ], + [ + "aBc", + "A", + 5 + ], + [ + "aBc", + "Bac", + 4 + ], + [ + "aBc", + "bCCc", + 6 + ], + [ + "aBc", + "baC", + 5 + ], + [ + "aBcAA", + "ABc", + 5 + ], + [ + "aBcAABabC", + "cab", + 12 + ], + [ + "aBcAaAccc", + "BacacaA", + 12 + ], + [ + "aBcAabAA", + "aBcB", + 9 + ], + [ + "aBcAc", + "bCCbbCc", + 11 + ], + [ + "aBcB", + "c", + 6 + ], + [ + "aBcBBBA", + "BbBBaAAab", + 12 + ], + [ + "aBcBBCAbb", + "AAA", + 15 + ], + [ + "aBcBaa", + "bbB", + 9 + ], + [ + "aBcBbbCb", + "cAcBCca", + 11 + ], + [ + "aBcC", + "CCAAA", + 10 + ], + [ + "aBcCABCc", + "BCbbcC", + 9 + ], + [ + "aBcCBbAc", + "cAbABaAa", + 12 + ], + [ + "aBcCCbA", + "cbA", + 8 + ], + [ + "aBcCcbaAC", + "aBBbBaB", + 11 + ], + [ + "aBca", + "BacbCCcB", + 11 + ], + [ + "aBca", + "CBAcCcCA", + 11 + ], + [ + "aBcaCC", + "c", + 10 + ], + [ + "aBcaaBB", + "BAbBaACbc", + 12 + ], + [ + "aBcbABAAa", + "bCCc", + 16 + ], + [ + "aBcbCAb", + "abA", + 8 + ], + [ + "aBcba", + "cAbCC", + 9 + ], + [ + "aBccABa", + "baBbCAAB", + 9 + ], + [ + "aBccAbac", + "CAaaCbb", + 14 + ], + [ + "aBccacCBa", + "ccbc", + 12 + ], + [ + "aBcccC", + "CccbACAcc", + 12 + ], + [ + "aC", + "AABacca", + 11 + ], + [ + "aC", + "ABABACC", + 11 + ], + [ + "aC", + "AcaBa", + 8 + ], + [ + "aC", + "AcaCBcaCB", + 14 + ], + [ + "aC", + "BBbbBcA", + 13 + ], + [ + "aC", + "BCABB", + 8 + ], + [ + "aC", + "Ba", + 4 + ], + [ + "aC", + "BaACBc", + 8 + ], + [ + "aC", + "BacccCb", + 10 + ], + [ + "aC", + "BcACaaCa", + 12 + ], + [ + "aC", + "BcB", + 5 + ], + [ + "aC", + "CAAcA", + 8 + ], + [ + "aC", + "CBbB", + 8 + ], + [ + "aC", + "CCA", + 4 + ], + [ + "aC", + "CaAA", + 6 + ], + [ + "aC", + "a", + 2 + ], + [ + "aC", + "aACaBBaB", + 12 + ], + [ + "aC", + "abCBcb", + 8 + ], + [ + "aC", + "abcabC", + 8 + ], + [ + "aC", + "bA", + 4 + ], + [ + "aC", + "bABAabc", + 11 + ], + [ + "aC", + "bBAAbCAcB", + 15 + ], + [ + "aC", + "bBaaaA", + 10 + ], + [ + "aC", + "bCBA", + 6 + ], + [ + "aC", + "baaaCC", + 8 + ], + [ + "aC", + "babcC", + 6 + ], + [ + "aC", + "bbc", + 5 + ], + [ + "aC", + "caCbAcaCc", + 14 + ], + [ + "aC", + "cbCaCaB", + 10 + ], + [ + "aCA", + "BCcBBaBc", + 13 + ], + [ + "aCA", + "CAACacC", + 10 + ], + [ + "aCA", + "bAaaC", + 8 + ], + [ + "aCA", + "babAaaBaC", + 14 + ], + [ + "aCA", + "baccbBBC", + 13 + ], + [ + "aCA", + "cBCc", + 6 + ], + [ + "aCAAA", + "aB", + 8 + ], + [ + "aCAAAaAba", + "BAbB", + 14 + ], + [ + "aCAABBBBb", + "BBABB", + 11 + ], + [ + "aCAACBcA", + "aA", + 12 + ], + [ + "aCAAaaa", + "AcbacaACb", + 12 + ], + [ + "aCAAbCBbA", + "cBc", + 15 + ], + [ + "aCAAcbC", + "CAaAcCcCc", + 10 + ], + [ + "aCAB", + "AbabAb", + 7 + ], + [ + "aCAB", + "BA", + 6 + ], + [ + "aCAB", + "CBAC", + 6 + ], + [ + "aCABAcBac", + "CCBCcbCC", + 10 + ], + [ + "aCABBC", + "ABb", + 7 + ], + [ + "aCABaAaC", + "BCaaABcC", + 9 + ], + [ + "aCABaBca", + "c", + 14 + ], + [ + "aCABaa", + "C", + 10 + ], + [ + "aCACACAC", + "baAbACC", + 8 + ], + [ + "aCACBBC", + "aCACBaAac", + 7 + ], + [ + "aCACBaaA", + "acCcCB", + 10 + ], + [ + "aCACCca", + "aBA", + 10 + ], + [ + "aCACa", + "baBbABB", + 10 + ], + [ + "aCACcbaa", + "CbAbBCBb", + 14 + ], + [ + "aCAa", + "bBCCcc", + 10 + ], + [ + "aCAaCba", + "AabAc", + 9 + ], + [ + "aCAab", + "CCCcCCAA", + 13 + ], + [ + "aCAacCAAa", + "abAcBacA", + 10 + ], + [ + "aCAb", + "Aaac", + 6 + ], + [ + "aCAbCC", + "bca", + 9 + ], + [ + "aCAbCC", + "cCABABac", + 10 + ], + [ + "aCAbCaCca", + "cACA", + 12 + ], + [ + "aCAbaBab", + "BABbA", + 11 + ], + [ + "aCAbca", + "B", + 11 + ], + [ + "aCAcBbbC", + "acaAbACAB", + 12 + ], + [ + "aCAcaCB", + "CbC", + 10 + ], + [ + "aCAcacc", + "aA", + 10 + ], + [ + "aCAcbA", + "aa", + 9 + ], + [ + "aCAcbabB", + "Aabbca", + 12 + ], + [ + "aCAccCa", + "AaBca", + 8 + ], + [ + "aCB", + "A", + 5 + ], + [ + "aCB", + "aAaCbBcA", + 10 + ], + [ + "aCB", + "aBABAaccA", + 14 + ], + [ + "aCB", + "aBcAb", + 6 + ], + [ + "aCB", + "abCbBA", + 6 + ], + [ + "aCB", + "b", + 5 + ], + [ + "aCB", + "cCcaBbc", + 10 + ], + [ + "aCBA", + "BCcCccBA", + 10 + ], + [ + "aCBA", + "cCCbcA", + 7 + ], + [ + "aCBAabBa", + "aA", + 12 + ], + [ + "aCBAb", + "B", + 8 + ], + [ + "aCBAbb", + "c", + 11 + ], + [ + "aCBB", + "bAb", + 7 + ], + [ + "aCBBAAB", + "bcbCAAAbc", + 11 + ], + [ + "aCBBBAab", + "CBcBbBcb", + 9 + ], + [ + "aCBBCcC", + "aBaCAa", + 8 + ], + [ + "aCBBabca", + "bCaaC", + 11 + ], + [ + "aCBBbb", + "cb", + 9 + ], + [ + "aCBBcBBC", + "c", + 14 + ], + [ + "aCBCCa", + "AaaABcA", + 10 + ], + [ + "aCBCc", + "bacBbaaaA", + 13 + ], + [ + "aCBa", + "cAA", + 6 + ], + [ + "aCBaABA", + "ba", + 11 + ], + [ + "aCBaAC", + "a", + 10 + ], + [ + "aCBaacBc", + "cacacCBB", + 10 + ], + [ + "aCBb", + "Ba", + 6 + ], + [ + "aCBb", + "CaAc", + 8 + ], + [ + "aCBb", + "CaBb", + 4 + ], + [ + "aCBbABbA", + "CbBcaA", + 10 + ], + [ + "aCBbACC", + "cAaBBC", + 10 + ], + [ + "aCBbBAcBB", + "aabBbCcaB", + 9 + ], + [ + "aCBbBc", + "aBabCbbaC", + 10 + ], + [ + "aCBbcccA", + "cCA", + 11 + ], + [ + "aCBc", + "ABAAaC", + 10 + ], + [ + "aCBc", + "BCcc", + 4 + ], + [ + "aCBcB", + "bBCCAC", + 10 + ], + [ + "aCBcaC", + "A", + 11 + ], + [ + "aCC", + "AB", + 5 + ], + [ + "aCC", + "Ac", + 4 + ], + [ + "aCC", + "abABbCBc", + 11 + ], + [ + "aCC", + "cBAcBCcb", + 12 + ], + [ + "aCC", + "cCCcBaa", + 10 + ], + [ + "aCCAA", + "C", + 8 + ], + [ + "aCCAB", + "bbCB", + 6 + ], + [ + "aCCABabA", + "aCa", + 10 + ], + [ + "aCCAcCbA", + "cBbCc", + 13 + ], + [ + "aCCAccAA", + "CB", + 14 + ], + [ + "aCCBBB", + "cccacc", + 10 + ], + [ + "aCCBCcA", + "aAc", + 10 + ], + [ + "aCCBCcCC", + "acBCbA", + 9 + ], + [ + "aCCC", + "ACbCcBa", + 8 + ], + [ + "aCCCBAC", + "AB", + 11 + ], + [ + "aCCCBCBa", + "a", + 14 + ], + [ + "aCCCBaAAa", + "CcBb", + 13 + ], + [ + "aCCCCB", + "cCABAcbA", + 12 + ], + [ + "aCCCCbCc", + "B", + 15 + ], + [ + "aCCCCcCb", + "AAB", + 14 + ], + [ + "aCCCab", + "BAaBcaC", + 10 + ], + [ + "aCCCc", + "aBabBBaa", + 14 + ], + [ + "aCCaA", + "aAAbb", + 8 + ], + [ + "aCCaA", + "cAA", + 6 + ], + [ + "aCCaBCcb", + "BAcc", + 12 + ], + [ + "aCCaC", + "CcacABac", + 10 + ], + [ + "aCCbBBbCB", + "baAcABCC", + 13 + ], + [ + "aCCbbAC", + "BAcbcB", + 11 + ], + [ + "aCCbbbaaB", + "abbC", + 12 + ], + [ + "aCCc", + "bAa", + 8 + ], + [ + "aCCc", + "cbaB", + 8 + ], + [ + "aCCcABBCB", + "bbC", + 14 + ], + [ + "aCCcBBABA", + "bABaacb", + 15 + ], + [ + "aCCcBCCBc", + "a", + 16 + ], + [ + "aCCcbaa", + "B", + 13 + ], + [ + "aCCccBBa", + "baAB", + 14 + ], + [ + "aCa", + "B", + 6 + ], + [ + "aCa", + "BCcC", + 6 + ], + [ + "aCa", + "bbbbCBA", + 11 + ], + [ + "aCaAAACa", + "AcCAA", + 10 + ], + [ + "aCaAAb", + "BCBccaB", + 10 + ], + [ + "aCaABBc", + "aCAbcbB", + 8 + ], + [ + "aCaABbAb", + "aBc", + 12 + ], + [ + "aCaAb", + "aCc", + 6 + ], + [ + "aCaAcCBb", + "baCcbb", + 9 + ], + [ + "aCaAcaC", + "BBCcCcbc", + 11 + ], + [ + "aCaB", + "BacaaAcBA", + 11 + ], + [ + "aCaB", + "C", + 6 + ], + [ + "aCaBAC", + "ab", + 9 + ], + [ + "aCaBBa", + "B", + 10 + ], + [ + "aCaBCB", + "a", + 10 + ], + [ + "aCaBCCB", + "cAccc", + 10 + ], + [ + "aCaBa", + "aC", + 6 + ], + [ + "aCaBacB", + "AAbcaB", + 9 + ], + [ + "aCaC", + "BBcc", + 7 + ], + [ + "aCaC", + "CAAaCAB", + 9 + ], + [ + "aCaC", + "accBcAAbA", + 14 + ], + [ + "aCaCAAac", + "CcCAB", + 10 + ], + [ + "aCaCBaaBb", + "CC", + 14 + ], + [ + "aCaCacAba", + "cbaAbBB", + 13 + ], + [ + "aCaCccca", + "CbACAc", + 11 + ], + [ + "aCaa", + "BAbB", + 8 + ], + [ + "aCaaC", + "ABacC", + 5 + ], + [ + "aCaac", + "AcabAC", + 6 + ], + [ + "aCaacB", + "CA", + 9 + ], + [ + "aCaacacbC", + "b", + 16 + ], + [ + "aCab", + "AcccBcB", + 11 + ], + [ + "aCab", + "BaaacBbbA", + 12 + ], + [ + "aCabBacCB", + "AAc", + 14 + ], + [ + "aCabCBBB", + "CBBcBbBBB", + 10 + ], + [ + "aCabCbbb", + "CBCCCcA", + 12 + ], + [ + "aCabaA", + "bABbaB", + 8 + ], + [ + "aCabbbCA", + "Ba", + 14 + ], + [ + "aCabcb", + "bBBb", + 9 + ], + [ + "aCacA", + "BbAB", + 9 + ], + [ + "aCacCa", + "baABcBcAb", + 12 + ], + [ + "aCacCcAaC", + "CbAbBa", + 14 + ], + [ + "aCacbC", + "CcbABcb", + 10 + ], + [ + "aCb", + "AaBaAc", + 10 + ], + [ + "aCb", + "BB", + 5 + ], + [ + "aCb", + "a", + 4 + ], + [ + "aCb", + "cCbBC", + 6 + ], + [ + "aCbA", + "CcCccBc", + 11 + ], + [ + "aCbA", + "bBaC", + 8 + ], + [ + "aCbAa", + "AABbbcCAC", + 13 + ], + [ + "aCbBAA", + "BcCC", + 11 + ], + [ + "aCbBAB", + "bcCBb", + 8 + ], + [ + "aCbBB", + "B", + 8 + ], + [ + "aCbBCaB", + "aCcAcaAbB", + 9 + ], + [ + "aCbBb", + "CBbA", + 6 + ], + [ + "aCbCBB", + "CAaACaA", + 11 + ], + [ + "aCbCBc", + "ABaBAcAcC", + 13 + ], + [ + "aCbCcCBCB", + "CBbc", + 13 + ], + [ + "aCba", + "aCba", + 0 + ], + [ + "aCbaa", + "BacbBccb", + 11 + ], + [ + "aCbb", + "bBcCBAAcc", + 15 + ], + [ + "aCbbCCCB", + "AaAC", + 13 + ], + [ + "aCbbaBAa", + "BbB", + 11 + ], + [ + "aCbbc", + "BBCAb", + 8 + ], + [ + "aCbbcAcB", + "accCaaB", + 9 + ], + [ + "aCbca", + "AbAc", + 7 + ], + [ + "aCbcb", + "cBcacaa", + 11 + ], + [ + "aCbcc", + "cBCbBAbB", + 12 + ], + [ + "aCbcca", + "CBbCaaCC", + 11 + ], + [ + "aCbccb", + "cAAab", + 9 + ], + [ + "aCc", + "AaAbC", + 7 + ], + [ + "aCc", + "BCbb", + 6 + ], + [ + "aCc", + "CCABBCAa", + 13 + ], + [ + "aCc", + "aAB", + 4 + ], + [ + "aCc", + "bbAcb", + 8 + ], + [ + "aCc", + "bbCcccb", + 10 + ], + [ + "aCc", + "caCAC", + 5 + ], + [ + "aCcA", + "a", + 6 + ], + [ + "aCcA", + "aC", + 4 + ], + [ + "aCcA", + "aaAAaaCBa", + 13 + ], + [ + "aCcA", + "cABb", + 8 + ], + [ + "aCcAAA", + "AbaBACBC", + 13 + ], + [ + "aCcABAc", + "BC", + 11 + ], + [ + "aCcABCB", + "b", + 13 + ], + [ + "aCcACA", + "baCcaaAa", + 7 + ], + [ + "aCcAaAba", + "aCAca", + 8 + ], + [ + "aCcAbB", + "cBCAB", + 7 + ], + [ + "aCcB", + "CCbcBaBBb", + 12 + ], + [ + "aCcBbCAC", + "CACbBb", + 11 + ], + [ + "aCcCC", + "A", + 9 + ], + [ + "aCcCCa", + "CcCabCc", + 8 + ], + [ + "aCcCabC", + "BcACaABCC", + 10 + ], + [ + "aCcCcAaA", + "baaAacBAb", + 13 + ], + [ + "aCcCca", + "cBCbCCAcb", + 11 + ], + [ + "aCcaAABb", + "BCACAAb", + 8 + ], + [ + "aCcaCAA", + "AabCbBBAC", + 12 + ], + [ + "aCcacbabC", + "a", + 16 + ], + [ + "aCcbAb", + "CbbcbaCAB", + 11 + ], + [ + "aCcbB", + "aA", + 8 + ], + [ + "aCcbBbAcC", + "bBBc", + 11 + ], + [ + "aCcbaCbca", + "bcBCCcbC", + 12 + ], + [ + "aCcbb", + "ccAabbABa", + 13 + ], + [ + "aCcbbaccb", + "AaCaCaCC", + 12 + ], + [ + "aCcbcBBA", + "CaBccABCa", + 11 + ], + [ + "aCcbcb", + "AcaacBCc", + 10 + ], + [ + "aCcc", + "baCACCa", + 8 + ], + [ + "aCccAaBa", + "BAaBcB", + 12 + ], + [ + "aCccAb", + "bBbaAcCC", + 13 + ], + [ + "aCccBB", + "CCa", + 9 + ], + [ + "aCccaaABC", + "CcBac", + 11 + ], + [ + "aCcccAaba", + "ccBbaA", + 11 + ], + [ + "aa", + "AACcaACB", + 13 + ], + [ + "aa", + "AcBCa", + 7 + ], + [ + "aa", + "Bbaba", + 6 + ], + [ + "aa", + "Bbc", + 6 + ], + [ + "aa", + "BcaBA", + 7 + ], + [ + "aa", + "C", + 4 + ], + [ + "aa", + "CBcC", + 8 + ], + [ + "aa", + "CbB", + 6 + ], + [ + "aa", + "CbBC", + 8 + ], + [ + "aa", + "a", + 2 + ], + [ + "aa", + "aABACBBb", + 13 + ], + [ + "aa", + "aBC", + 4 + ], + [ + "aa", + "aBcaaCAC", + 12 + ], + [ + "aa", + "aCbbAaaCa", + 14 + ], + [ + "aa", + "aaAaA", + 6 + ], + [ + "aa", + "aaAbcb", + 8 + ], + [ + "aa", + "aabCb", + 6 + ], + [ + "aa", + "abCBc", + 8 + ], + [ + "aa", + "abCbAb", + 9 + ], + [ + "aa", + "acAAbAAB", + 13 + ], + [ + "aa", + "bAaB", + 5 + ], + [ + "aa", + "bB", + 4 + ], + [ + "aa", + "bBAaBCA", + 11 + ], + [ + "aa", + "bCaaBbCA", + 12 + ], + [ + "aa", + "baCCBCBB", + 14 + ], + [ + "aa", + "bbAabBcCc", + 15 + ], + [ + "aa", + "bbcAC", + 9 + ], + [ + "aa", + "cAaabc", + 8 + ], + [ + "aa", + "cB", + 4 + ], + [ + "aa", + "cBB", + 6 + ], + [ + "aa", + "cBcBAAbA", + 14 + ], + [ + "aa", + "cCAB", + 7 + ], + [ + "aa", + "cCB", + 6 + ], + [ + "aa", + "caccAcB", + 11 + ], + [ + "aa", + "cb", + 4 + ], + [ + "aa", + "cbbcCB", + 12 + ], + [ + "aaA", + "A", + 4 + ], + [ + "aaA", + "ACBACBC", + 11 + ], + [ + "aaA", + "bCCA", + 6 + ], + [ + "aaA", + "bcaaAB", + 6 + ], + [ + "aaAA", + "aab", + 4 + ], + [ + "aaAAaaAaB", + "BAA", + 14 + ], + [ + "aaAAbbAC", + "cCbBbCAab", + 14 + ], + [ + "aaAAcC", + "cabbCa", + 9 + ], + [ + "aaAB", + "cAa", + 6 + ], + [ + "aaAB", + "cCaBCcB", + 10 + ], + [ + "aaABAbAC", + "CCAB", + 12 + ], + [ + "aaABAbb", + "CC", + 14 + ], + [ + "aaABB", + "Ccb", + 9 + ], + [ + "aaABCC", + "acABACB", + 6 + ], + [ + "aaABCb", + "CABbAaa", + 12 + ], + [ + "aaABaaA", + "CaaaBBabc", + 9 + ], + [ + "aaABbbCbc", + "B", + 16 + ], + [ + "aaAC", + "Ac", + 5 + ], + [ + "aaAC", + "bccBBBb", + 14 + ], + [ + "aaACa", + "cbAAaCB", + 9 + ], + [ + "aaAaAcbBC", + "A", + 16 + ], + [ + "aaAaaaAb", + "bcBc", + 16 + ], + [ + "aaAabBCbc", + "B", + 16 + ], + [ + "aaAabCaAa", + "BbbbcA", + 13 + ], + [ + "aaAabbbaC", + "bbbCaAbC", + 14 + ], + [ + "aaAac", + "cBCCc", + 8 + ], + [ + "aaAbaBbBa", + "baaCCa", + 12 + ], + [ + "aaAbcbBa", + "BbBbaaC", + 12 + ], + [ + "aaAc", + "bbCBca", + 10 + ], + [ + "aaAccCbC", + "BBa", + 15 + ], + [ + "aaB", + "bAAa", + 6 + ], + [ + "aaB", + "cccCAcAaC", + 15 + ], + [ + "aaBA", + "ABccb", + 9 + ], + [ + "aaBA", + "aca", + 5 + ], + [ + "aaBABCc", + "Aaa", + 10 + ], + [ + "aaBABaCc", + "acBaac", + 7 + ], + [ + "aaBABbCAc", + "cCb", + 16 + ], + [ + "aaBB", + "BbbBbcAB", + 12 + ], + [ + "aaBB", + "bAaAaAB", + 8 + ], + [ + "aaBB", + "bBabBA", + 7 + ], + [ + "aaBBa", + "caaB", + 6 + ], + [ + "aaBC", + "BacaAB", + 8 + ], + [ + "aaBCAaaaB", + "aaACA", + 10 + ], + [ + "aaBCC", + "BAAaBb", + 9 + ], + [ + "aaBCCa", + "CA", + 9 + ], + [ + "aaBCCbAac", + "AcaaBacc", + 13 + ], + [ + "aaBa", + "BabbcC", + 9 + ], + [ + "aaBaAaCa", + "aBbcAcAb", + 11 + ], + [ + "aaBaC", + "bcCAbac", + 9 + ], + [ + "aaBaCc", + "BCAaCCb", + 9 + ], + [ + "aaBaa", + "AAb", + 7 + ], + [ + "aaBaa", + "ccba", + 7 + ], + [ + "aaBaaAcBA", + "aCcBCAc", + 12 + ], + [ + "aaBabACBC", + "CCCc", + 15 + ], + [ + "aaBabbBA", + "aAbB", + 9 + ], + [ + "aaBacaB", + "BCABCCCbc", + 13 + ], + [ + "aaBbAaBA", + "BAc", + 12 + ], + [ + "aaBbb", + "aA", + 7 + ], + [ + "aaBbcA", + "CBcb", + 8 + ], + [ + "aaBbcbb", + "C", + 13 + ], + [ + "aaBcBaBa", + "aaBaaaB", + 6 + ], + [ + "aaBccACb", + "bCCBccC", + 10 + ], + [ + "aaC", + "ABcAca", + 9 + ], + [ + "aaC", + "BAbaCaa", + 9 + ], + [ + "aaC", + "CaCbcCc", + 10 + ], + [ + "aaC", + "Cc", + 5 + ], + [ + "aaC", + "aCa", + 4 + ], + [ + "aaC", + "caBBCb", + 8 + ], + [ + "aaCA", + "B", + 8 + ], + [ + "aaCAA", + "BcbBC", + 10 + ], + [ + "aaCABbb", + "CCcbBAb", + 9 + ], + [ + "aaCACa", + "Bb", + 12 + ], + [ + "aaCAcbc", + "AaaAAa", + 9 + ], + [ + "aaCAccaAB", + "CcCABcA", + 10 + ], + [ + "aaCC", + "B", + 8 + ], + [ + "aaCCC", + "ABAcC", + 6 + ], + [ + "aaCCCc", + "cCAaaAbAb", + 14 + ], + [ + "aaCCa", + "CAA", + 7 + ], + [ + "aaCCbaCaB", + "cCCcCAccC", + 13 + ], + [ + "aaCCcbCA", + "acAcb", + 9 + ], + [ + "aaCa", + "aCBca", + 5 + ], + [ + "aaCa", + "cAAca", + 5 + ], + [ + "aaCaABa", + "ba", + 11 + ], + [ + "aaCaABbc", + "B", + 14 + ], + [ + "aaCaBaA", + "aBcAa", + 8 + ], + [ + "aaCaa", + "Ac", + 8 + ], + [ + "aaCacA", + "CbabcA", + 8 + ], + [ + "aaCacAAb", + "CcCAc", + 10 + ], + [ + "aaCacaBC", + "BBaCcA", + 11 + ], + [ + "aaCacaba", + "ACbc", + 11 + ], + [ + "aaCbAAB", + "ABc", + 12 + ], + [ + "aaCbabb", + "Bc", + 13 + ], + [ + "aaCbabc", + "C", + 12 + ], + [ + "aaCbbAAc", + "BaBa", + 12 + ], + [ + "aaCcAcc", + "aC", + 10 + ], + [ + "aaCcaBcB", + "ccAaAbaBC", + 12 + ], + [ + "aaCcaC", + "AAABCccC", + 8 + ], + [ + "aaCccbAaa", + "B", + 17 + ], + [ + "aaa", + "ABAbCbC", + 12 + ], + [ + "aaa", + "abABCcbA", + 12 + ], + [ + "aaa", + "abaC", + 4 + ], + [ + "aaa", + "baa", + 2 + ], + [ + "aaa", + "cCbC", + 8 + ], + [ + "aaaA", + "BaCacbbc", + 12 + ], + [ + "aaaA", + "aaaabAC", + 6 + ], + [ + "aaaAAb", + "abCC", + 10 + ], + [ + "aaaAAcb", + "cbABcb", + 8 + ], + [ + "aaaABb", + "BBCCbBaba", + 14 + ], + [ + "aaaACcA", + "aaa", + 8 + ], + [ + "aaaAac", + "CCAaC", + 7 + ], + [ + "aaaAb", + "ACc", + 9 + ], + [ + "aaaB", + "b", + 7 + ], + [ + "aaaBBB", + "CcACCaCB", + 13 + ], + [ + "aaaBCAbBc", + "baCaab", + 12 + ], + [ + "aaaBaBCAb", + "BaBccAb", + 9 + ], + [ + "aaaBbAC", + "baBCAc", + 7 + ], + [ + "aaaBbBA", + "a", + 12 + ], + [ + "aaaC", + "aca", + 4 + ], + [ + "aaaCAAcAA", + "cCacb", + 13 + ], + [ + "aaaCBacCc", + "aA", + 15 + ], + [ + "aaaCaBcCC", + "ACAbBb", + 13 + ], + [ + "aaaCaaC", + "C", + 12 + ], + [ + "aaaCaaCb", + "bC", + 14 + ], + [ + "aaaCb", + "bcBbaB", + 11 + ], + [ + "aaaCbC", + "AabAc", + 8 + ], + [ + "aaaCcB", + "A", + 11 + ], + [ + "aaaa", + "CacBC", + 8 + ], + [ + "aaaaB", + "aCBcbC", + 9 + ], + [ + "aaaaBBCc", + "aCcCcaab", + 14 + ], + [ + "aaaaBCc", + "bcbaB", + 10 + ], + [ + "aaaaC", + "CBb", + 10 + ], + [ + "aaabCBaAB", + "cbBccA", + 14 + ], + [ + "aaac", + "BAaB", + 5 + ], + [ + "aaacCCB", + "aaAaacA", + 8 + ], + [ + "aab", + "CcCcaACB", + 12 + ], + [ + "aab", + "ab", + 2 + ], + [ + "aab", + "b", + 4 + ], + [ + "aab", + "bBb", + 4 + ], + [ + "aab", + "ccbCc", + 8 + ], + [ + "aabAA", + "CBCcBcac", + 14 + ], + [ + "aabACB", + "AACA", + 7 + ], + [ + "aabACB", + "Ca", + 10 + ], + [ + "aabAacba", + "bCbcBC", + 11 + ], + [ + "aabAbBc", + "AbCaCcCB", + 13 + ], + [ + "aabBAA", + "CbaACAbAA", + 10 + ], + [ + "aabBBcB", + "CbACCCc", + 13 + ], + [ + "aabCAAc", + "CBaA", + 10 + ], + [ + "aabCAcB", + "BBCA", + 9 + ], + [ + "aabaCc", + "Acab", + 9 + ], + [ + "aabb", + "a", + 6 + ], + [ + "aabbA", + "bA", + 6 + ], + [ + "aabbCAA", + "AaAAAbbC", + 11 + ], + [ + "aabbacA", + "AbC", + 10 + ], + [ + "aabbcABba", + "AC", + 16 + ], + [ + "aabc", + "A", + 7 + ], + [ + "aabc", + "Baab", + 4 + ], + [ + "aabcA", + "cabBcCc", + 8 + ], + [ + "aabcBcB", + "Ab", + 11 + ], + [ + "aabcaAA", + "abccacA", + 6 + ], + [ + "aabcbBc", + "BaCaaaA", + 12 + ], + [ + "aabcbaaac", + "BbCbccCc", + 11 + ], + [ + "aac", + "BCC", + 5 + ], + [ + "aac", + "BbCaCBbBc", + 14 + ], + [ + "aac", + "C", + 5 + ], + [ + "aac", + "a", + 4 + ], + [ + "aacA", + "CABCabaa", + 12 + ], + [ + "aacAaCCA", + "CBCbB", + 13 + ], + [ + "aacAaCCAb", + "BBCAB", + 13 + ], + [ + "aacAcb", + "baAacaCAB", + 9 + ], + [ + "aacB", + "ABcCcBAca", + 13 + ], + [ + "aacB", + "CACAABc", + 10 + ], + [ + "aacB", + "c", + 6 + ], + [ + "aacBAabc", + "caCBa", + 9 + ], + [ + "aacBc", + "aBCaCbAc", + 8 + ], + [ + "aacC", + "Ba", + 6 + ], + [ + "aacC", + "Bc", + 6 + ], + [ + "aacC", + "CAbBAbCaA", + 14 + ], + [ + "aacCCb", + "ccBAc", + 10 + ], + [ + "aacCc", + "CaB", + 8 + ], + [ + "aacaA", + "Bbaa", + 7 + ], + [ + "aacaa", + "cCB", + 8 + ], + [ + "aacaaCbBc", + "BCab", + 13 + ], + [ + "aacabaBA", + "cbbA", + 9 + ], + [ + "aacac", + "ABBCabcc", + 10 + ], + [ + "aacacAaB", + "aAbbA", + 11 + ], + [ + "aacb", + "BCcAb", + 6 + ], + [ + "aacbAAC", + "BbabBAC", + 8 + ], + [ + "aacbAcA", + "acbccC", + 6 + ], + [ + "aacbCABAC", + "AAbaCAbbA", + 11 + ], + [ + "aacbb", + "BBAbAC", + 10 + ], + [ + "aacc", + "acACBAa", + 10 + ], + [ + "aaccAaABA", + "BAbBacAC", + 14 + ], + [ + "aacccAccB", + "BBCAb", + 14 + ], + [ + "ab", + "ABca", + 6 + ], + [ + "ab", + "ACA", + 5 + ], + [ + "ab", + "AaB", + 3 + ], + [ + "ab", + "B", + 3 + ], + [ + "ab", + "BAabAa", + 8 + ], + [ + "ab", + "BAacbb", + 8 + ], + [ + "ab", + "Ba", + 4 + ], + [ + "ab", + "BbaBBa", + 9 + ], + [ + "ab", + "CACABaC", + 12 + ], + [ + "ab", + "CCbaA", + 8 + ], + [ + "ab", + "CbBACbc", + 11 + ], + [ + "ab", + "CbcbcbB", + 12 + ], + [ + "ab", + "CcB", + 5 + ], + [ + "ab", + "CcacBC", + 9 + ], + [ + "ab", + "aBBAbbaB", + 12 + ], + [ + "ab", + "aBCbBCACa", + 14 + ], + [ + "ab", + "abAbbc", + 8 + ], + [ + "ab", + "abB", + 2 + ], + [ + "ab", + "bAbCcBAaA", + 15 + ], + [ + "ab", + "baBcBa", + 9 + ], + [ + "ab", + "bb", + 2 + ], + [ + "ab", + "c", + 4 + ], + [ + "ab", + "cAAabacc", + 12 + ], + [ + "ab", + "cABcCCb", + 11 + ], + [ + "ab", + "cCbbbCa", + 12 + ], + [ + "ab", + "cbcb", + 6 + ], + [ + "ab", + "ccb", + 4 + ], + [ + "ab", + "cccaaCAA", + 14 + ], + [ + "abA", + "AaacB", + 8 + ], + [ + "abA", + "BAB", + 5 + ], + [ + "abA", + "abca", + 3 + ], + [ + "abA", + "bAAcC", + 8 + ], + [ + "abA", + "bBbaa", + 7 + ], + [ + "abA", + "bbbAcabb", + 12 + ], + [ + "abA", + "cAbCCcbb", + 13 + ], + [ + "abA", + "cBaaC", + 8 + ], + [ + "abAAB", + "BAbACC", + 7 + ], + [ + "abAAcaCa", + "c", + 14 + ], + [ + "abAB", + "AaCBBbb", + 10 + ], + [ + "abABAA", + "aBABbaabA", + 8 + ], + [ + "abABcAaC", + "aCbAcb", + 10 + ], + [ + "abABcb", + "b", + 10 + ], + [ + "abAC", + "BAC", + 3 + ], + [ + "abACAC", + "CBCaaCcA", + 12 + ], + [ + "abACC", + "BbCbBb", + 10 + ], + [ + "abACCBBa", + "abb", + 11 + ], + [ + "abACCaABb", + "aAcbb", + 10 + ], + [ + "abACb", + "Ca", + 8 + ], + [ + "abACbBAaA", + "cAAcCaCaB", + 13 + ], + [ + "abACccA", + "bBaCBC", + 9 + ], + [ + "abAaAaCCC", + "cACCbAbCC", + 13 + ], + [ + "abAaBAAC", + "ABca", + 11 + ], + [ + "abAacCCaa", + "acbCAC", + 11 + ], + [ + "abAbAcCc", + "b", + 14 + ], + [ + "abAbbBC", + "CAbbBbBb", + 8 + ], + [ + "abAc", + "bC", + 5 + ], + [ + "abAcBBbBA", + "CabccbcaA", + 11 + ], + [ + "abAccAbba", + "caCACCC", + 14 + ], + [ + "abAccBA", + "ACAbbABaa", + 12 + ], + [ + "abAccCbBa", + "cbccBbBac", + 8 + ], + [ + "abB", + "BAAA", + 7 + ], + [ + "abB", + "BACbb", + 6 + ], + [ + "abB", + "BcaBabA", + 10 + ], + [ + "abB", + "a", + 4 + ], + [ + "abB", + "cbBaACaAB", + 14 + ], + [ + "abBA", + "AACBCAbA", + 11 + ], + [ + "abBAA", + "bA", + 6 + ], + [ + "abBAAcaA", + "AACCC", + 11 + ], + [ + "abBAAcbb", + "bCCcbb", + 8 + ], + [ + "abBAB", + "aa", + 7 + ], + [ + "abBABBA", + "BBCBccbaA", + 12 + ], + [ + "abBAaBa", + "bbaBCcbc", + 11 + ], + [ + "abBAaCacb", + "bbaca", + 10 + ], + [ + "abBAaCcc", + "ccCACB", + 12 + ], + [ + "abBAc", + "bB", + 6 + ], + [ + "abBAc", + "bBB", + 6 + ], + [ + "abBB", + "BbaBbCbb", + 10 + ], + [ + "abBBCc", + "b", + 10 + ], + [ + "abBBaAcBc", + "bbCaB", + 11 + ], + [ + "abBBaBbCc", + "Cac", + 14 + ], + [ + "abBBac", + "BAc", + 7 + ], + [ + "abBBb", + "A", + 9 + ], + [ + "abBBb", + "ACAAc", + 9 + ], + [ + "abBBbB", + "b", + 10 + ], + [ + "abBCACBBc", + "B", + 16 + ], + [ + "abBCBAB", + "cCA", + 10 + ], + [ + "abBCCb", + "AbaCcCcA", + 9 + ], + [ + "abBCCcc", + "BcBCCbCbb", + 11 + ], + [ + "abBCac", + "cCcbACcC", + 11 + ], + [ + "abBCcCbA", + "bC", + 12 + ], + [ + "abBa", + "cbabba", + 5 + ], + [ + "abBaA", + "CA", + 8 + ], + [ + "abBaAAc", + "BB", + 11 + ], + [ + "abBaBcabA", + "BBBAabAba", + 10 + ], + [ + "abBaCbB", + "CaCaacbC", + 9 + ], + [ + "abBabAb", + "Aacb", + 9 + ], + [ + "abBacbc", + "cAccCaaa", + 15 + ], + [ + "abBacca", + "bAACac", + 10 + ], + [ + "abBb", + "ABCaACb", + 10 + ], + [ + "abBb", + "BAABc", + 7 + ], + [ + "abBb", + "c", + 8 + ], + [ + "abBb", + "cAB", + 6 + ], + [ + "abBbBB", + "Aaccb", + 10 + ], + [ + "abBbC", + "aaccbac", + 9 + ], + [ + "abBbCBBa", + "C", + 14 + ], + [ + "abBbb", + "BBA", + 7 + ], + [ + "abBbba", + "CBbAAb", + 9 + ], + [ + "abBc", + "AABBCcBcc", + 12 + ], + [ + "abBc", + "bcbbCABca", + 12 + ], + [ + "abBcB", + "CbCaCca", + 10 + ], + [ + "abBcBBCA", + "BCCCacAac", + 15 + ], + [ + "abBcaBa", + "bcBCCc", + 11 + ], + [ + "abC", + "ACAbb", + 7 + ], + [ + "abC", + "Cc", + 5 + ], + [ + "abC", + "aAabBb", + 8 + ], + [ + "abC", + "b", + 4 + ], + [ + "abC", + "bccBAC", + 9 + ], + [ + "abC", + "bccabCBc", + 10 + ], + [ + "abC", + "cBA", + 5 + ], + [ + "abC", + "cCB", + 6 + ], + [ + "abCA", + "Acb", + 6 + ], + [ + "abCA", + "cc", + 7 + ], + [ + "abCAA", + "BAcbCCBc", + 11 + ], + [ + "abCAAcbCB", + "acCabB", + 9 + ], + [ + "abCAaA", + "AcbaAB", + 8 + ], + [ + "abCB", + "BABBbAABA", + 13 + ], + [ + "abCBB", + "Bb", + 7 + ], + [ + "abCBCB", + "baCaaa", + 10 + ], + [ + "abCC", + "CA", + 6 + ], + [ + "abCC", + "CCcCAcaA", + 13 + ], + [ + "abCCAacb", + "babaA", + 12 + ], + [ + "abCCBB", + "baB", + 8 + ], + [ + "abCCBBC", + "aAc", + 11 + ], + [ + "abCCCBaAC", + "CCBbCbBA", + 13 + ], + [ + "abCCaAca", + "bBCBCaC", + 10 + ], + [ + "abCCbBBaA", + "Ab", + 15 + ], + [ + "abCCc", + "BcbBabBc", + 12 + ], + [ + "abCCcAcBB", + "BaAAAaAB", + 13 + ], + [ + "abCa", + "ABA", + 5 + ], + [ + "abCaBC", + "bCCaCaA", + 10 + ], + [ + "abCaC", + "acc", + 6 + ], + [ + "abCaCAbB", + "aCaba", + 8 + ], + [ + "abCabA", + "ACba", + 6 + ], + [ + "abCabbccb", + "CcAcA", + 14 + ], + [ + "abCacaaC", + "aC", + 12 + ], + [ + "abCb", + "cBCBaA", + 8 + ], + [ + "abCbBCcAa", + "a", + 16 + ], + [ + "abCbaCC", + "CAabaabBB", + 14 + ], + [ + "abCbbba", + "CcbBCBAA", + 12 + ], + [ + "abCc", + "Ca", + 6 + ], + [ + "abCcAbbC", + "B", + 15 + ], + [ + "abCcCCC", + "BbAaca", + 11 + ], + [ + "abCcCc", + "ACacA", + 8 + ], + [ + "abCcaA", + "aca", + 6 + ], + [ + "abCcaABB", + "AbcBb", + 8 + ], + [ + "aba", + "CBb", + 5 + ], + [ + "aba", + "CBbbaAb", + 10 + ], + [ + "aba", + "aCccA", + 7 + ], + [ + "aba", + "acaB", + 4 + ], + [ + "aba", + "bcCCa", + 8 + ], + [ + "aba", + "cBB", + 5 + ], + [ + "abaAAA", + "cAbB", + 10 + ], + [ + "abaACCcC", + "abacCBA", + 7 + ], + [ + "abaAaccC", + "CCaacc", + 8 + ], + [ + "abaAbb", + "a", + 10 + ], + [ + "abaBCABc", + "aCcccB", + 11 + ], + [ + "abaBaCca", + "aAcAbaB", + 12 + ], + [ + "abaC", + "Bba", + 4 + ], + [ + "abaCACccC", + "BBBBB", + 17 + ], + [ + "abaCBABaB", + "abacbacc", + 9 + ], + [ + "abaCCbcA", + "AcBBc", + 11 + ], + [ + "abaCbB", + "cC", + 10 + ], + [ + "abaCbaCB", + "AAcC", + 11 + ], + [ + "abaCbaa", + "aCCaCCA", + 9 + ], + [ + "abaaACcB", + "cBBCBBAbC", + 16 + ], + [ + "abab", + "CcaCC", + 8 + ], + [ + "abab", + "aCAAaaaB", + 11 + ], + [ + "abab", + "acBbA", + 6 + ], + [ + "ababA", + "CBBC", + 8 + ], + [ + "ababACcC", + "BC", + 13 + ], + [ + "ababCBBbB", + "CbC", + 14 + ], + [ + "ababa", + "CABCcCcb", + 14 + ], + [ + "ababcCb", + "aCAbCc", + 7 + ], + [ + "abacA", + "ABb", + 8 + ], + [ + "abacABc", + "babCCAbb", + 8 + ], + [ + "abacAc", + "BacbCaaB", + 11 + ], + [ + "abacBBa", + "CbCAa", + 9 + ], + [ + "abacBbaCC", + "a", + 16 + ], + [ + "abacCb", + "b", + 10 + ], + [ + "abaca", + "cAB", + 9 + ], + [ + "abacaCbBc", + "bACcACB", + 10 + ], + [ + "abaccABb", + "cBcCc", + 12 + ], + [ + "abaccaAcA", + "B", + 17 + ], + [ + "abacccc", + "Cba", + 10 + ], + [ + "abb", + "B", + 5 + ], + [ + "abb", + "CbBBAc", + 9 + ], + [ + "abb", + "aC", + 4 + ], + [ + "abb", + "bbbcaca", + 10 + ], + [ + "abbAAABBb", + "CbCcB", + 14 + ], + [ + "abbAcB", + "BbaaBc", + 8 + ], + [ + "abbBBCcB", + "aaa", + 14 + ], + [ + "abbBbAbcc", + "c", + 16 + ], + [ + "abbBbbbcC", + "aBbBaB", + 10 + ], + [ + "abbCBA", + "aA", + 8 + ], + [ + "abbCBA", + "bb", + 8 + ], + [ + "abbCBabac", + "CBAB", + 12 + ], + [ + "abbCaBB", + "Ab", + 11 + ], + [ + "abbCaBC", + "aBcc", + 9 + ], + [ + "abbCbbBB", + "cbbaaca", + 12 + ], + [ + "abbCc", + "bC", + 6 + ], + [ + "abbaA", + "BabaAAaBb", + 11 + ], + [ + "abbaBaaBc", + "CAcBbc", + 13 + ], + [ + "abbaBbc", + "aABbAcc", + 8 + ], + [ + "abbaCcba", + "Cba", + 10 + ], + [ + "abbbA", + "ACAcc", + 9 + ], + [ + "abbbBAbAA", + "aCACcAbA", + 10 + ], + [ + "abbbCCCaC", + "acBCBABcC", + 13 + ], + [ + "abbbb", + "cCcbBcb", + 9 + ], + [ + "abbbc", + "C", + 9 + ], + [ + "abbbca", + "BBAcBbAB", + 12 + ], + [ + "abbcABB", + "ac", + 10 + ], + [ + "abbcB", + "ABbcCB", + 4 + ], + [ + "abbcBac", + "bACca", + 9 + ], + [ + "abbccAa", + "AcC", + 10 + ], + [ + "abbccb", + "cbCb", + 7 + ], + [ + "abc", + "AbC", + 2 + ], + [ + "abc", + "BAAb", + 7 + ], + [ + "abc", + "C", + 5 + ], + [ + "abc", + "aB", + 3 + ], + [ + "abcAA", + "CAAabC", + 11 + ], + [ + "abcAaaccb", + "cAcAAcbcA", + 11 + ], + [ + "abcAbB", + "AbcCacc", + 8 + ], + [ + "abcAcaB", + "acBcBb", + 7 + ], + [ + "abcAcbbb", + "CaABc", + 13 + ], + [ + "abcB", + "AaCcAbCa", + 11 + ], + [ + "abcB", + "bbab", + 5 + ], + [ + "abcBaBb", + "cBBa", + 8 + ], + [ + "abcBacc", + "ACBa", + 8 + ], + [ + "abcBb", + "BBbcccBB", + 9 + ], + [ + "abcBbBAb", + "cB", + 12 + ], + [ + "abcC", + "BCc", + 5 + ], + [ + "abcCAB", + "CbCcC", + 8 + ], + [ + "abcCBAc", + "ACCBaA", + 7 + ], + [ + "abcCaBcCB", + "AAba", + 15 + ], + [ + "abcCbBCA", + "Ba", + 13 + ], + [ + "abca", + "cbaccAA", + 9 + ], + [ + "abcaCB", + "CCaaAB", + 8 + ], + [ + "abcb", + "a", + 6 + ], + [ + "abcbbC", + "BBc", + 9 + ], + [ + "abcbbbcb", + "b", + 14 + ], + [ + "abccC", + "bbcBab", + 8 + ], + [ + "abccCBabC", + "AbABaaabc", + 10 + ], + [ + "abccCaB", + "Bbaa", + 10 + ], + [ + "abccCcAa", + "BCbb", + 13 + ], + [ + "abccaB", + "aCABaba", + 9 + ], + [ + "abccaC", + "ABbCB", + 9 + ], + [ + "abccaCcBB", + "AAB", + 14 + ], + [ + "abccbCC", + "BAc", + 11 + ], + [ + "ac", + "A", + 3 + ], + [ + "ac", + "AAaCcbBa", + 12 + ], + [ + "ac", + "AAcCbbCca", + 15 + ], + [ + "ac", + "ACAcCa", + 9 + ], + [ + "ac", + "ACCBbAcCc", + 15 + ], + [ + "ac", + "B", + 4 + ], + [ + "ac", + "BAab", + 6 + ], + [ + "ac", + "BCCBbccb", + 14 + ], + [ + "ac", + "BCc", + 4 + ], + [ + "ac", + "BaBbbAA", + 12 + ], + [ + "ac", + "BcCACbB", + 12 + ], + [ + "ac", + "CBA", + 6 + ], + [ + "ac", + "CccBcaB", + 12 + ], + [ + "ac", + "aB", + 2 + ], + [ + "ac", + "aBBCacBbC", + 14 + ], + [ + "ac", + "aC", + 1 + ], + [ + "ac", + "aCcCC", + 6 + ], + [ + "ac", + "aaCaCaca", + 12 + ], + [ + "ac", + "ab", + 2 + ], + [ + "ac", + "acacCAbBA", + 14 + ], + [ + "ac", + "bACaaCCCC", + 15 + ], + [ + "ac", + "bAbaCCcBC", + 14 + ], + [ + "ac", + "bCCaAaa", + 12 + ], + [ + "ac", + "cBAcc", + 7 + ], + [ + "acA", + "AaCCAaabc", + 13 + ], + [ + "acA", + "aABBBACc", + 12 + ], + [ + "acA", + "ac", + 2 + ], + [ + "acA", + "cBcBb", + 8 + ], + [ + "acAA", + "bc", + 6 + ], + [ + "acAAABBa", + "cbcC", + 13 + ], + [ + "acAACBA", + "BcbaCbbA", + 8 + ], + [ + "acAB", + "ccbAAAa", + 10 + ], + [ + "acABCCA", + "BCcABBAa", + 9 + ], + [ + "acABc", + "BBcABbCba", + 11 + ], + [ + "acAC", + "A", + 6 + ], + [ + "acACCB", + "AAcBCba", + 9 + ], + [ + "acAaaAcba", + "BabCcbCbb", + 15 + ], + [ + "acAaaaBc", + "BacCBc", + 10 + ], + [ + "acAabACa", + "acaCB", + 8 + ], + [ + "acAabBbA", + "cabCb", + 8 + ], + [ + "acAacCc", + "BBCC", + 11 + ], + [ + "acAb", + "cc", + 6 + ], + [ + "acAbabcBa", + "ABABcaB", + 11 + ], + [ + "acAc", + "ABa", + 6 + ], + [ + "acAc", + "CcBCaa", + 9 + ], + [ + "acAc", + "aBbCaB", + 8 + ], + [ + "acAcBCCa", + "BaB", + 13 + ], + [ + "acAcCAc", + "cAbab", + 9 + ], + [ + "acAcaC", + "B", + 12 + ], + [ + "acAcabB", + "baaacbB", + 7 + ], + [ + "acAcbcAC", + "ccaCbCcc", + 8 + ], + [ + "acB", + "ABcAcBAcb", + 13 + ], + [ + "acB", + "acb", + 1 + ], + [ + "acB", + "bCccA", + 8 + ], + [ + "acB", + "cbabb", + 7 + ], + [ + "acBA", + "BcAaBCBAA", + 11 + ], + [ + "acBAcc", + "AAabb", + 10 + ], + [ + "acBB", + "AaaAbB", + 7 + ], + [ + "acBB", + "cA", + 6 + ], + [ + "acBBAb", + "bCcAbBCAC", + 11 + ], + [ + "acBBAbacB", + "aaCBB", + 12 + ], + [ + "acBBBbAcb", + "BAa", + 14 + ], + [ + "acBBCC", + "ccAbcBbCb", + 10 + ], + [ + "acBBCc", + "bcCaAbAa", + 13 + ], + [ + "acBBbBa", + "Cba", + 9 + ], + [ + "acBBcCC", + "ABbb", + 10 + ], + [ + "acBCBcabA", + "caCbca", + 9 + ], + [ + "acBCCbab", + "ccA", + 12 + ], + [ + "acBCa", + "BabbAcb", + 10 + ], + [ + "acBa", + "AC", + 6 + ], + [ + "acBaA", + "ABBCC", + 7 + ], + [ + "acBaAacc", + "bbab", + 13 + ], + [ + "acBaBCab", + "ac", + 12 + ], + [ + "acBaBaC", + "bbccbac", + 10 + ], + [ + "acBacCbAc", + "bBBACbaAA", + 11 + ], + [ + "acBb", + "CA", + 7 + ], + [ + "acBb", + "bCBAAB", + 8 + ], + [ + "acBbAc", + "aaaBCA", + 8 + ], + [ + "acBbCca", + "acA", + 9 + ], + [ + "acBcCcaB", + "CC", + 13 + ], + [ + "acBcabcAC", + "Aac", + 13 + ], + [ + "acC", + "AABcbaC", + 9 + ], + [ + "acC", + "AcBAaC", + 7 + ], + [ + "acC", + "CabBabaBC", + 14 + ], + [ + "acC", + "b", + 6 + ], + [ + "acC", + "baBCBCbAC", + 13 + ], + [ + "acC", + "baaCBCBC", + 11 + ], + [ + "acCA", + "C", + 6 + ], + [ + "acCA", + "aabBCaaaC", + 13 + ], + [ + "acCAAaCB", + "ba", + 14 + ], + [ + "acCAB", + "BccCcCbB", + 10 + ], + [ + "acCAa", + "c", + 8 + ], + [ + "acCAabBcc", + "Bb", + 16 + ], + [ + "acCAb", + "abB", + 7 + ], + [ + "acCAcc", + "cccCCacCC", + 10 + ], + [ + "acCB", + "B", + 6 + ], + [ + "acCBAcb", + "acaBcA", + 6 + ], + [ + "acCBBA", + "caccBbabC", + 9 + ], + [ + "acCBBb", + "aCbc", + 7 + ], + [ + "acCBCbaBC", + "bCabBc", + 11 + ], + [ + "acCBaaAc", + "BAAABCA", + 13 + ], + [ + "acCC", + "BAB", + 8 + ], + [ + "acCCABBb", + "Bbcca", + 13 + ], + [ + "acCCCaAb", + "acCCbAcca", + 9 + ], + [ + "acCCab", + "aB", + 9 + ], + [ + "acCCbA", + "CCAbCbBA", + 9 + ], + [ + "acCCbBcc", + "aAAaA", + 14 + ], + [ + "acCCcaC", + "AcbBabcCb", + 13 + ], + [ + "acCCcab", + "ccab", + 6 + ], + [ + "acCa", + "aaAcAbBbB", + 14 + ], + [ + "acCaAA", + "BAbcAcbC", + 13 + ], + [ + "acCaABcbb", + "A", + 16 + ], + [ + "acCaC", + "abBACBCB", + 10 + ], + [ + "acCaCa", + "aBa", + 8 + ], + [ + "acCb", + "aACBa", + 5 + ], + [ + "acCbBBa", + "BbbACCccb", + 15 + ], + [ + "acCbCCCBb", + "B", + 16 + ], + [ + "acCbbBB", + "bcca", + 11 + ], + [ + "acCc", + "A", + 7 + ], + [ + "acCc", + "AABBa", + 9 + ], + [ + "acCcA", + "CBBcaBCCA", + 11 + ], + [ + "acCcAcB", + "b", + 13 + ], + [ + "acCcB", + "BBCCBA", + 7 + ], + [ + "acCcaAA", + "b", + 14 + ], + [ + "acCcacB", + "cbAccBcb", + 10 + ], + [ + "acCcc", + "AC", + 7 + ], + [ + "aca", + "ACAB", + 5 + ], + [ + "aca", + "AaAc", + 6 + ], + [ + "aca", + "cAAbacBCa", + 12 + ], + [ + "aca", + "cbCCabAaB", + 14 + ], + [ + "acaA", + "C", + 7 + ], + [ + "acaA", + "aCbcACABa", + 11 + ], + [ + "acaAAAbc", + "B", + 15 + ], + [ + "acaABAcA", + "Cacca", + 10 + ], + [ + "acaAcb", + "cbc", + 8 + ], + [ + "acaBA", + "baBCbCBBC", + 13 + ], + [ + "acaBcacBc", + "b", + 17 + ], + [ + "acaBccaC", + "C", + 14 + ], + [ + "acaC", + "bccCAccA", + 12 + ], + [ + "acaCAaBB", + "Bc", + 14 + ], + [ + "acaCBBB", + "A", + 13 + ], + [ + "acaCaA", + "BCB", + 10 + ], + [ + "acaCaC", + "c", + 10 + ], + [ + "acaCbC", + "acaabCaa", + 6 + ], + [ + "acaCcaAB", + "ABAaaaba", + 12 + ], + [ + "acaCcbcB", + "CcbACBBc", + 10 + ], + [ + "acaCcbcc", + "C", + 14 + ], + [ + "acaa", + "AabBa", + 6 + ], + [ + "acaaBAA", + "cBBbaAB", + 10 + ], + [ + "acaaCC", + "cAACA", + 6 + ], + [ + "acaaaCCA", + "AaC", + 11 + ], + [ + "acaacAbB", + "bCbb", + 12 + ], + [ + "acaaca", + "cBACccCa", + 11 + ], + [ + "acaacb", + "ccCbBca", + 10 + ], + [ + "acabCb", + "ccaCbA", + 6 + ], + [ + "acabaBCbB", + "cab", + 12 + ], + [ + "acabcA", + "AB", + 10 + ], + [ + "acacA", + "bcBACcaa", + 10 + ], + [ + "acacbA", + "A", + 10 + ], + [ + "acacbABa", + "bCbcBa", + 9 + ], + [ + "acacbBa", + "BAbA", + 10 + ], + [ + "acb", + "AabAbA", + 8 + ], + [ + "acb", + "BCCa", + 7 + ], + [ + "acb", + "cBCB", + 6 + ], + [ + "acbA", + "AcBCbCa", + 8 + ], + [ + "acbA", + "aAaBCAB", + 9 + ], + [ + "acbAA", + "bc", + 8 + ], + [ + "acbACbbA", + "a", + 14 + ], + [ + "acbAbacc", + "caAcB", + 10 + ], + [ + "acbB", + "aBAb", + 5 + ], + [ + "acbBBC", + "caB", + 8 + ], + [ + "acbBaAAb", + "bbBcABBaC", + 13 + ], + [ + "acbBaC", + "CaA", + 9 + ], + [ + "acbBc", + "abB", + 4 + ], + [ + "acbC", + "ABABaBbca", + 13 + ], + [ + "acbC", + "bbBbcaaA", + 13 + ], + [ + "acbCA", + "A", + 8 + ], + [ + "acbCA", + "cBb", + 7 + ], + [ + "acbCBb", + "acAbCCaBc", + 8 + ], + [ + "acbCaaAaB", + "CaCc", + 14 + ], + [ + "acbCabC", + "cBACbcBC", + 10 + ], + [ + "acbaBaA", + "BBcA", + 9 + ], + [ + "acbabAa", + "CaAbcbc", + 10 + ], + [ + "acbabbaB", + "c", + 14 + ], + [ + "acbb", + "AAa", + 7 + ], + [ + "acbb", + "AbCaBCcBA", + 13 + ], + [ + "acbb", + "BbAca", + 9 + ], + [ + "acbb", + "CBaCBcCbA", + 12 + ], + [ + "acbbA", + "AcCAAbc", + 9 + ], + [ + "acbbAbA", + "CCCaccab", + 13 + ], + [ + "acbbcABBB", + "BcCBbb", + 11 + ], + [ + "acbc", + "aBAbB", + 6 + ], + [ + "acbcAa", + "BaCC", + 10 + ], + [ + "acbcBbc", + "B", + 12 + ], + [ + "acbcCAC", + "ACaAab", + 11 + ], + [ + "acbcCab", + "BAb", + 10 + ], + [ + "acbcaacbc", + "CbccCCBcb", + 11 + ], + [ + "acbcbbcc", + "CcAbaCCbb", + 13 + ], + [ + "acbccACA", + "b", + 14 + ], + [ + "acbccBcB", + "CCcc", + 10 + ], + [ + "acbccCB", + "bbbaaCAAB", + 12 + ], + [ + "acc", + "C", + 5 + ], + [ + "acc", + "bAac", + 5 + ], + [ + "accA", + "CBBaA", + 8 + ], + [ + "accAA", + "C", + 9 + ], + [ + "accABbb", + "cBbAAbaC", + 12 + ], + [ + "accAac", + "CCcacb", + 7 + ], + [ + "accAb", + "bcbAbB", + 6 + ], + [ + "accAcbAa", + "B", + 15 + ], + [ + "accB", + "bBbAb", + 9 + ], + [ + "accBC", + "bCCCCab", + 10 + ], + [ + "accBbcCaa", + "aaCcaBACB", + 12 + ], + [ + "accC", + "CCcbBc", + 8 + ], + [ + "accC", + "aa", + 6 + ], + [ + "accCAcACa", + "AABbCCc", + 14 + ], + [ + "accCCaCB", + "aCBba", + 11 + ], + [ + "accCCcA", + "cBbA", + 10 + ], + [ + "accCaB", + "aBaB", + 6 + ], + [ + "accCbbC", + "cBBcaa", + 12 + ], + [ + "acca", + "BBCAcbaba", + 13 + ], + [ + "acca", + "BBcCC", + 7 + ], + [ + "accaACAAc", + "cbbCABA", + 12 + ], + [ + "accaaAcAb", + "ccB", + 13 + ], + [ + "accaaC", + "CbA", + 10 + ], + [ + "accab", + "AAaAcA", + 9 + ], + [ + "accabbcB", + "aa", + 12 + ], + [ + "accac", + "C", + 9 + ], + [ + "accb", + "CBCAcCaBB", + 13 + ], + [ + "accbAA", + "Ba", + 10 + ], + [ + "accbAa", + "Ca", + 9 + ], + [ + "accbBac", + "caC", + 9 + ], + [ + "accbCcBAc", + "cbA", + 12 + ], + [ + "accbaAc", + "ACAaCAAA", + 11 + ], + [ + "accbb", + "CCcC", + 7 + ], + [ + "acccAB", + "cb", + 9 + ], + [ + "acccC", + "baaaaB", + 10 + ], + [ + "acccaAaB", + "C", + 15 + ], + [ + "acccc", + "cAAC", + 7 + ], + [ + "b", + "A", + 2 + ], + [ + "b", + "AAbAaCb", + 12 + ], + [ + "b", + "ABBBC", + 9 + ], + [ + "b", + "ABbCCBC", + 12 + ], + [ + "b", + "ABc", + 5 + ], + [ + "b", + "ABcba", + 8 + ], + [ + "b", + "ACAAC", + 10 + ], + [ + "b", + "ACBbAcabc", + 16 + ], + [ + "b", + "ACBbCBcCC", + 16 + ], + [ + "b", + "ACCaA", + 10 + ], + [ + "b", + "Aa", + 4 + ], + [ + "b", + "AaAbBCA", + 12 + ], + [ + "b", + "Aac", + 6 + ], + [ + "b", + "AacaBc", + 11 + ], + [ + "b", + "AbaC", + 6 + ], + [ + "b", + "Abcba", + 8 + ], + [ + "b", + "Ac", + 4 + ], + [ + "b", + "AcCbB", + 8 + ], + [ + "b", + "AcCbBca", + 12 + ], + [ + "b", + "AcaaCaAa", + 16 + ], + [ + "b", + "B", + 1 + ], + [ + "b", + "BBA", + 5 + ], + [ + "b", + "BBaaabB", + 12 + ], + [ + "b", + "BBbaBcba", + 14 + ], + [ + "b", + "BCBaC", + 9 + ], + [ + "b", + "BCcAABb", + 12 + ], + [ + "b", + "Ba", + 3 + ], + [ + "b", + "BaC", + 5 + ], + [ + "b", + "BaCbBc", + 10 + ], + [ + "b", + "Bac", + 5 + ], + [ + "b", + "BacBAc", + 11 + ], + [ + "b", + "Bb", + 2 + ], + [ + "b", + "BbA", + 4 + ], + [ + "b", + "BbBacbb", + 12 + ], + [ + "b", + "BbacaCc", + 12 + ], + [ + "b", + "BbbcAcAab", + 16 + ], + [ + "b", + "Bc", + 3 + ], + [ + "b", + "BcBA", + 7 + ], + [ + "b", + "BcBCAAaCB", + 17 + ], + [ + "b", + "BcC", + 5 + ], + [ + "b", + "BcCa", + 7 + ], + [ + "b", + "C", + 2 + ], + [ + "b", + "CAB", + 5 + ], + [ + "b", + "CACCBca", + 13 + ], + [ + "b", + "CBABaBAB", + 15 + ], + [ + "b", + "CBCCa", + 9 + ], + [ + "b", + "CBCCcC", + 11 + ], + [ + "b", + "CBCcaBBAB", + 17 + ], + [ + "b", + "CBaBaaCbB", + 16 + ], + [ + "b", + "CBaabA", + 10 + ], + [ + "b", + "CCBABBcC", + 15 + ], + [ + "b", + "CCC", + 6 + ], + [ + "b", + "CCbCA", + 8 + ], + [ + "b", + "Ca", + 4 + ], + [ + "b", + "CaCBcA", + 11 + ], + [ + "b", + "Cabacc", + 10 + ], + [ + "b", + "CabccCBCB", + 16 + ], + [ + "b", + "CacAbAAac", + 16 + ], + [ + "b", + "CbA", + 4 + ], + [ + "b", + "CbcBbA", + 10 + ], + [ + "b", + "Cc", + 4 + ], + [ + "b", + "CcAABbA", + 12 + ], + [ + "b", + "CcabBB", + 10 + ], + [ + "b", + "CcacCcAcC", + 18 + ], + [ + "b", + "CcbCACB", + 12 + ], + [ + "b", + "Ccbc", + 6 + ], + [ + "b", + "a", + 2 + ], + [ + "b", + "aA", + 4 + ], + [ + "b", + "aABBCcC", + 13 + ], + [ + "b", + "aABccbaCc", + 16 + ], + [ + "b", + "aACCCCba", + 14 + ], + [ + "b", + "aACCa", + 10 + ], + [ + "b", + "aAaBA", + 9 + ], + [ + "b", + "aAacBab", + 12 + ], + [ + "b", + "aB", + 3 + ], + [ + "b", + "aBCAac", + 11 + ], + [ + "b", + "aBCBC", + 9 + ], + [ + "b", + "aBCbacab", + 14 + ], + [ + "b", + "aBaCa", + 9 + ], + [ + "b", + "aBc", + 5 + ], + [ + "b", + "aC", + 4 + ], + [ + "b", + "aCBA", + 7 + ], + [ + "b", + "aCCa", + 8 + ], + [ + "b", + "aa", + 4 + ], + [ + "b", + "aabCCBca", + 14 + ], + [ + "b", + "aabbAb", + 10 + ], + [ + "b", + "aabbcC", + 10 + ], + [ + "b", + "ab", + 2 + ], + [ + "b", + "abB", + 4 + ], + [ + "b", + "abBBcb", + 10 + ], + [ + "b", + "abCCBCA", + 12 + ], + [ + "b", + "abcACcaa", + 14 + ], + [ + "b", + "abcBccCa", + 14 + ], + [ + "b", + "abca", + 6 + ], + [ + "b", + "ac", + 4 + ], + [ + "b", + "acACCaAca", + 18 + ], + [ + "b", + "acC", + 6 + ], + [ + "b", + "aca", + 6 + ], + [ + "b", + "acaabCC", + 12 + ], + [ + "b", + "b", + 0 + ], + [ + "b", + "bACAbB", + 10 + ], + [ + "b", + "bBAccb", + 10 + ], + [ + "b", + "bBBC", + 6 + ], + [ + "b", + "bBbaAA", + 10 + ], + [ + "b", + "bC", + 2 + ], + [ + "b", + "bCA", + 4 + ], + [ + "b", + "bCBCAbaCA", + 16 + ], + [ + "b", + "bCCbA", + 8 + ], + [ + "b", + "bCaAC", + 8 + ], + [ + "b", + "bCaCAB", + 10 + ], + [ + "b", + "bCabBB", + 10 + ], + [ + "b", + "bCbBbcA", + 12 + ], + [ + "b", + "bCcbAb", + 10 + ], + [ + "b", + "baBACBaaB", + 16 + ], + [ + "b", + "baCCbBC", + 12 + ], + [ + "b", + "baabBABb", + 14 + ], + [ + "b", + "baabbaCBB", + 16 + ], + [ + "b", + "baaccc", + 10 + ], + [ + "b", + "babBAcb", + 12 + ], + [ + "b", + "bb", + 2 + ], + [ + "b", + "bcBACbaBb", + 16 + ], + [ + "b", + "bcCa", + 6 + ], + [ + "b", + "bcCcAcbc", + 14 + ], + [ + "b", + "c", + 2 + ], + [ + "b", + "cABCaB", + 11 + ], + [ + "b", + "cAC", + 6 + ], + [ + "b", + "cAbBbBcc", + 14 + ], + [ + "b", + "cAbaBABBc", + 16 + ], + [ + "b", + "cAbaCBAa", + 14 + ], + [ + "b", + "cBAAAcaA", + 15 + ], + [ + "b", + "cBBcbAabb", + 16 + ], + [ + "b", + "cBCCAcb", + 12 + ], + [ + "b", + "cBCCa", + 9 + ], + [ + "b", + "cBCaCAc", + 13 + ], + [ + "b", + "cBbaBbcB", + 14 + ], + [ + "b", + "cBbbBaAa", + 14 + ], + [ + "b", + "cCAACba", + 12 + ], + [ + "b", + "cCaccAaCb", + 16 + ], + [ + "b", + "cCcbA", + 8 + ], + [ + "b", + "caA", + 6 + ], + [ + "b", + "caAb", + 6 + ], + [ + "b", + "caAccaCbb", + 16 + ], + [ + "b", + "caB", + 5 + ], + [ + "b", + "cabBbcA", + 12 + ], + [ + "b", + "cacbbBAb", + 14 + ], + [ + "b", + "cb", + 2 + ], + [ + "b", + "cbAa", + 6 + ], + [ + "b", + "cbAaCa", + 10 + ], + [ + "b", + "cbcBAcCbA", + 16 + ], + [ + "b", + "ccCaacc", + 14 + ], + [ + "b", + "ccCbaaaa", + 14 + ], + [ + "b", + "ccaC", + 8 + ], + [ + "b", + "ccbbcb", + 10 + ], + [ + "bA", + "AAAcACAbA", + 14 + ], + [ + "bA", + "AAbB", + 6 + ], + [ + "bA", + "ABaC", + 6 + ], + [ + "bA", + "ACBbbA", + 8 + ], + [ + "bA", + "ACBbccB", + 12 + ], + [ + "bA", + "ACbbBB", + 10 + ], + [ + "bA", + "Accc", + 8 + ], + [ + "bA", + "BAcCabc", + 11 + ], + [ + "bA", + "BCCcccB", + 13 + ], + [ + "bA", + "BabcCBCaa", + 15 + ], + [ + "bA", + "BbCaCBca", + 13 + ], + [ + "bA", + "BbbcbCCB", + 14 + ], + [ + "bA", + "Bbca", + 5 + ], + [ + "bA", + "C", + 4 + ], + [ + "bA", + "CAbABbBC", + 12 + ], + [ + "bA", + "CB", + 4 + ], + [ + "bA", + "CBCBa", + 8 + ], + [ + "bA", + "CbAaAaB", + 10 + ], + [ + "bA", + "CbcAAc", + 8 + ], + [ + "bA", + "CcAAcbcBC", + 16 + ], + [ + "bA", + "aAc", + 4 + ], + [ + "bA", + "aBCCcAcb", + 13 + ], + [ + "bA", + "aCb", + 6 + ], + [ + "bA", + "aCcbbc", + 10 + ], + [ + "bA", + "bAbcaAA", + 10 + ], + [ + "bA", + "bAc", + 2 + ], + [ + "bA", + "ba", + 1 + ], + [ + "bA", + "bb", + 2 + ], + [ + "bA", + "cAcCABaAb", + 15 + ], + [ + "bA", + "cCAABbBb", + 14 + ], + [ + "bA", + "cCC", + 6 + ], + [ + "bA", + "cabc", + 6 + ], + [ + "bA", + "ccCbcC", + 10 + ], + [ + "bAA", + "AabBB", + 8 + ], + [ + "bAA", + "BBAAaBCbC", + 13 + ], + [ + "bAA", + "C", + 6 + ], + [ + "bAA", + "CBaBcBb", + 12 + ], + [ + "bAA", + "CCBAc", + 7 + ], + [ + "bAA", + "abBBBAA", + 8 + ], + [ + "bAA", + "baacAbb", + 9 + ], + [ + "bAA", + "bcbBccAb", + 12 + ], + [ + "bAAA", + "C", + 8 + ], + [ + "bAAA", + "bBAAC", + 4 + ], + [ + "bAAAA", + "c", + 10 + ], + [ + "bAAAAbaCa", + "abacbC", + 12 + ], + [ + "bAAACbbb", + "Aaa", + 12 + ], + [ + "bAAACccC", + "CC", + 12 + ], + [ + "bAAAacAc", + "caC", + 12 + ], + [ + "bAAAbABC", + "CBCbBa", + 12 + ], + [ + "bAAB", + "bC", + 6 + ], + [ + "bAABaCA", + "A", + 12 + ], + [ + "bAABb", + "CaBBB", + 6 + ], + [ + "bAABcbbB", + "CbACCB", + 11 + ], + [ + "bAAC", + "AabbbaBA", + 13 + ], + [ + "bAAC", + "Acb", + 6 + ], + [ + "bAAC", + "aaB", + 6 + ], + [ + "bAACcACbc", + "Aaa", + 14 + ], + [ + "bAAa", + "AaABbabC", + 11 + ], + [ + "bAAa", + "bCAbbaa", + 7 + ], + [ + "bAAaCba", + "bAca", + 7 + ], + [ + "bAAaaaa", + "BC", + 13 + ], + [ + "bAAbAab", + "CBcA", + 12 + ], + [ + "bAAbCa", + "C", + 10 + ], + [ + "bAAbb", + "A", + 8 + ], + [ + "bAAc", + "CCAbca", + 8 + ], + [ + "bAAc", + "cCBAba", + 9 + ], + [ + "bAAcA", + "bbc", + 6 + ], + [ + "bAAccABbb", + "aAc", + 13 + ], + [ + "bAAccaCC", + "A", + 14 + ], + [ + "bAB", + "ACBcB", + 7 + ], + [ + "bAB", + "CbAA", + 4 + ], + [ + "bAB", + "bbABC", + 4 + ], + [ + "bABAC", + "BCaabaCBC", + 12 + ], + [ + "bABACCCB", + "abB", + 12 + ], + [ + "bABAaB", + "cCCCBbc", + 13 + ], + [ + "bABAaCBBA", + "BAbA", + 11 + ], + [ + "bABAaba", + "A", + 12 + ], + [ + "bABAba", + "BBBAccBA", + 9 + ], + [ + "bABAbbCbB", + "bA", + 14 + ], + [ + "bABAcCCb", + "abCaB", + 11 + ], + [ + "bABBCCC", + "bbCbBc", + 10 + ], + [ + "bABBa", + "bA", + 6 + ], + [ + "bABBcAc", + "bAC", + 9 + ], + [ + "bABC", + "AbBca", + 7 + ], + [ + "bABCBcAc", + "cBCAA", + 10 + ], + [ + "bABCC", + "aBCa", + 5 + ], + [ + "bABCCbbbC", + "cABACBBa", + 10 + ], + [ + "bABCaBCa", + "CaBbB", + 10 + ], + [ + "bABCbaB", + "ACCaCBc", + 10 + ], + [ + "bABa", + "BA", + 5 + ], + [ + "bABa", + "BAB", + 3 + ], + [ + "bABaCBBAa", + "Aa", + 14 + ], + [ + "bABb", + "acA", + 7 + ], + [ + "bABb", + "ccCA", + 8 + ], + [ + "bABbAB", + "ABCBCACc", + 11 + ], + [ + "bABbAC", + "bcBaCcAb", + 10 + ], + [ + "bABbBCB", + "cb", + 12 + ], + [ + "bABbaB", + "cAcAbbCAb", + 11 + ], + [ + "bABbaBAA", + "C", + 16 + ], + [ + "bABbbABBB", + "cAcb", + 14 + ], + [ + "bABbbbC", + "a", + 13 + ], + [ + "bABbcCab", + "ccccaa", + 11 + ], + [ + "bAC", + "AcAbc", + 7 + ], + [ + "bAC", + "bCcbAabb", + 12 + ], + [ + "bACA", + "ACaAAAaC", + 12 + ], + [ + "bACA", + "CAc", + 5 + ], + [ + "bACA", + "c", + 7 + ], + [ + "bACACAAa", + "cbBbC", + 14 + ], + [ + "bACAb", + "Cbc", + 8 + ], + [ + "bACAcc", + "BacBcAB", + 9 + ], + [ + "bACB", + "cBccC", + 8 + ], + [ + "bACBAC", + "BCCABaC", + 6 + ], + [ + "bACBBaA", + "bBACB", + 8 + ], + [ + "bACBCbb", + "b", + 12 + ], + [ + "bACBa", + "BCC", + 7 + ], + [ + "bACBaAcAb", + "C", + 16 + ], + [ + "bACBabABB", + "aCA", + 13 + ], + [ + "bACBcB", + "accBbaCcC", + 13 + ], + [ + "bACCaCcBb", + "aBaBcb", + 11 + ], + [ + "bACaBC", + "bA", + 8 + ], + [ + "bACaCCBAB", + "aaBacb", + 13 + ], + [ + "bACaCcC", + "aBCac", + 8 + ], + [ + "bACab", + "aBcBcAB", + 10 + ], + [ + "bACac", + "Bc", + 7 + ], + [ + "bACac", + "cBAacCAcB", + 10 + ], + [ + "bACbAA", + "B", + 11 + ], + [ + "bACbBbc", + "CbcAcBcA", + 11 + ], + [ + "bACc", + "bcA", + 5 + ], + [ + "bACc", + "cCb", + 6 + ], + [ + "bACcABb", + "BaC", + 10 + ], + [ + "bACcCaaC", + "AAbAbb", + 13 + ], + [ + "bAa", + "AaaACbAcc", + 14 + ], + [ + "bAa", + "AcAabb", + 8 + ], + [ + "bAa", + "bCbBCABBA", + 13 + ], + [ + "bAaA", + "aACcbaB", + 10 + ], + [ + "bAaAA", + "BacbCbBaa", + 14 + ], + [ + "bAaAAAa", + "cabAbA", + 9 + ], + [ + "bAaABAAC", + "AB", + 12 + ], + [ + "bAaAcA", + "cbC", + 11 + ], + [ + "bAaB", + "B", + 6 + ], + [ + "bAaB", + "acCCbb", + 11 + ], + [ + "bAaBAA", + "a", + 10 + ], + [ + "bAaBAcac", + "AABcaa", + 7 + ], + [ + "bAaBC", + "CBcaaaBa", + 10 + ], + [ + "bAaBa", + "C", + 10 + ], + [ + "bAaBaCBAB", + "CCbCCC", + 15 + ], + [ + "bAaBb", + "bCAA", + 7 + ], + [ + "bAaBbBc", + "AC", + 11 + ], + [ + "bAaBbc", + "cbbcAaab", + 10 + ], + [ + "bAaBc", + "a", + 8 + ], + [ + "bAaBc", + "cbCCBBbcc", + 12 + ], + [ + "bAaC", + "ABA", + 6 + ], + [ + "bAaC", + "BAaACAB", + 7 + ], + [ + "bAaCCa", + "CbCBB", + 10 + ], + [ + "bAaCa", + "bCBaABcbB", + 13 + ], + [ + "bAaCab", + "caBC", + 9 + ], + [ + "bAaa", + "AAcCbAC", + 11 + ], + [ + "bAaa", + "bBAAb", + 5 + ], + [ + "bAaaA", + "AbA", + 6 + ], + [ + "bAaaB", + "CABBC", + 8 + ], + [ + "bAaaB", + "bABBaC", + 6 + ], + [ + "bAaabaAc", + "cBaa", + 12 + ], + [ + "bAab", + "CcC", + 8 + ], + [ + "bAab", + "bAc", + 4 + ], + [ + "bAabAbC", + "A", + 12 + ], + [ + "bAabBACA", + "cCca", + 14 + ], + [ + "bAabBBCb", + "CbaCbA", + 12 + ], + [ + "bAabCAB", + "aA", + 10 + ], + [ + "bAabb", + "AaacAAA", + 11 + ], + [ + "bAabbC", + "babAb", + 6 + ], + [ + "bAabcA", + "bA", + 8 + ], + [ + "bAabcbc", + "BaAabcAaa", + 9 + ], + [ + "bAabccAa", + "aCbaB", + 12 + ], + [ + "bAac", + "ccACbbAA", + 13 + ], + [ + "bAacA", + "BBaACC", + 8 + ], + [ + "bAacAb", + "bacccBCc", + 10 + ], + [ + "bAacAbBca", + "C", + 17 + ], + [ + "bAacC", + "bbaAb", + 6 + ], + [ + "bAaccCB", + "c", + 12 + ], + [ + "bAb", + "ABCCAACCA", + 15 + ], + [ + "bAb", + "CCBAA", + 7 + ], + [ + "bAbACaC", + "bABcCAb", + 6 + ], + [ + "bAbAaC", + "BAbbA", + 6 + ], + [ + "bAbAabcab", + "CAabcBa", + 10 + ], + [ + "bAbAbcA", + "CAABBca", + 8 + ], + [ + "bAbBC", + "AACcbCca", + 11 + ], + [ + "bAbBCbaB", + "acacab", + 11 + ], + [ + "bAbBaCBcb", + "BaA", + 14 + ], + [ + "bAbBbbBbb", + "cAaacAC", + 16 + ], + [ + "bAbCAABaB", + "ACcBAccB", + 11 + ], + [ + "bAbCbCcCA", + "aBB", + 15 + ], + [ + "bAbCcB", + "aCAbA", + 10 + ], + [ + "bAba", + "CaAAb", + 8 + ], + [ + "bAbaCC", + "Bba", + 7 + ], + [ + "bAbab", + "CbCAcBcB", + 10 + ], + [ + "bAbb", + "acAbCBb", + 8 + ], + [ + "bAbb", + "b", + 6 + ], + [ + "bAbb", + "bAaAcBBab", + 11 + ], + [ + "bAbbB", + "AaACcBacC", + 14 + ], + [ + "bAbbaa", + "cCBC", + 11 + ], + [ + "bAbbbbBc", + "cABcBBC", + 9 + ], + [ + "bAbbbc", + "aCA", + 11 + ], + [ + "bAbc", + "Accbacc", + 9 + ], + [ + "bAbcBB", + "A", + 10 + ], + [ + "bAbcCaA", + "bACaCAcbC", + 11 + ], + [ + "bAbcCab", + "ABC", + 9 + ], + [ + "bAbcCbAA", + "BcBb", + 11 + ], + [ + "bAbcbA", + "CBCBCac", + 11 + ], + [ + "bAc", + "aaC", + 4 + ], + [ + "bAcA", + "bb", + 6 + ], + [ + "bAcAABA", + "aAAbca", + 9 + ], + [ + "bAcAAbA", + "BABabc", + 8 + ], + [ + "bAcAAbb", + "aC", + 12 + ], + [ + "bAcAbc", + "CAAcaaBa", + 10 + ], + [ + "bAcAc", + "BaC", + 7 + ], + [ + "bAcB", + "bcBC", + 4 + ], + [ + "bAcB", + "bccaA", + 6 + ], + [ + "bAcBAaaCa", + "aABCccaBa", + 12 + ], + [ + "bAcBAbBcC", + "B", + 16 + ], + [ + "bAcBBBABa", + "caA", + 14 + ], + [ + "bAcBCCbac", + "accBBAB", + 12 + ], + [ + "bAcBabbC", + "ca", + 12 + ], + [ + "bAcBbAb", + "cbaBA", + 9 + ], + [ + "bAcBbaA", + "AaBaaA", + 6 + ], + [ + "bAcC", + "Acac", + 5 + ], + [ + "bAcC", + "bba", + 6 + ], + [ + "bAcCAa", + "C", + 10 + ], + [ + "bAcCaCc", + "abbCcb", + 11 + ], + [ + "bAcCb", + "Bbcacac", + 9 + ], + [ + "bAcCbACCB", + "aA", + 15 + ], + [ + "bAcCcACA", + "ABCAaBB", + 11 + ], + [ + "bAcaAbA", + "baCCbBca", + 10 + ], + [ + "bAcac", + "BBbAbCccA", + 11 + ], + [ + "bAcb", + "aa", + 7 + ], + [ + "bAcb", + "cAbbb", + 6 + ], + [ + "bAcbAbBAC", + "CbBc", + 12 + ], + [ + "bAcbBbcb", + "cCcBBCaa", + 11 + ], + [ + "bAcc", + "aCcABC", + 9 + ], + [ + "bAccA", + "ccBaaCA", + 9 + ], + [ + "bAccCabB", + "aABCAAaAA", + 13 + ], + [ + "bAccCbb", + "BaAAcB", + 10 + ], + [ + "bAcca", + "CBbcBBBba", + 13 + ], + [ + "bAccaACaa", + "CCcBCaA", + 10 + ], + [ + "bAccaCCA", + "aABAABBCb", + 13 + ], + [ + "bAcccAC", + "ABC", + 10 + ], + [ + "bAcccAbaA", + "CBcCAbcC", + 11 + ], + [ + "bAcccaB", + "BccACBBC", + 10 + ], + [ + "bB", + "ACaAbC", + 10 + ], + [ + "bB", + "BCbCb", + 7 + ], + [ + "bB", + "Baa", + 5 + ], + [ + "bB", + "BbbbBAb", + 10 + ], + [ + "bB", + "Bcba", + 6 + ], + [ + "bB", + "CAAcBb", + 10 + ], + [ + "bB", + "CbbC", + 5 + ], + [ + "bB", + "aACCab", + 11 + ], + [ + "bB", + "aBaccb", + 10 + ], + [ + "bB", + "aBbC", + 6 + ], + [ + "bB", + "aCACcaA", + 14 + ], + [ + "bB", + "aaAABaCCc", + 16 + ], + [ + "bB", + "ac", + 4 + ], + [ + "bB", + "acACccAac", + 18 + ], + [ + "bB", + "bAAacb", + 9 + ], + [ + "bB", + "bBCccbcC", + 12 + ], + [ + "bB", + "bBbbcb", + 8 + ], + [ + "bB", + "bCbBAAbCc", + 14 + ], + [ + "bB", + "ba", + 2 + ], + [ + "bB", + "baAbcC", + 9 + ], + [ + "bB", + "bcBbACaa", + 12 + ], + [ + "bB", + "c", + 4 + ], + [ + "bB", + "cBCcc", + 8 + ], + [ + "bB", + "cCBa", + 6 + ], + [ + "bB", + "caBc", + 6 + ], + [ + "bB", + "caCCACb", + 13 + ], + [ + "bBA", + "AB", + 4 + ], + [ + "bBA", + "B", + 4 + ], + [ + "bBA", + "abBCbccC", + 12 + ], + [ + "bBA", + "bCaaa", + 7 + ], + [ + "bBA", + "cBB", + 4 + ], + [ + "bBAA", + "cAb", + 6 + ], + [ + "bBAAba", + "C", + 12 + ], + [ + "bBAAcb", + "BCcBABB", + 10 + ], + [ + "bBAB", + "ccaa", + 7 + ], + [ + "bBABbBc", + "Bb", + 10 + ], + [ + "bBAC", + "aCBb", + 8 + ], + [ + "bBACA", + "bbcaBB", + 8 + ], + [ + "bBACBA", + "CA", + 8 + ], + [ + "bBACBABc", + "ca", + 14 + ], + [ + "bBACCbCB", + "B", + 14 + ], + [ + "bBACbaC", + "aabAbaCC", + 9 + ], + [ + "bBAa", + "CBBbBaa", + 7 + ], + [ + "bBAa", + "CabC", + 8 + ], + [ + "bBAa", + "cCcCCCA", + 13 + ], + [ + "bBAaBAcB", + "CbCaaAbAA", + 12 + ], + [ + "bBAaBcAaB", + "ACcb", + 13 + ], + [ + "bBAaC", + "acBaAcC", + 8 + ], + [ + "bBAaCB", + "bcBbCBBca", + 12 + ], + [ + "bBAaCc", + "Aca", + 9 + ], + [ + "bBAac", + "AcccCbBc", + 14 + ], + [ + "bBAacA", + "aBCbaAAA", + 10 + ], + [ + "bBAbCA", + "cBAaaCACb", + 10 + ], + [ + "bBAba", + "B", + 8 + ], + [ + "bBAbac", + "cBbAaccb", + 10 + ], + [ + "bBAc", + "Bc", + 4 + ], + [ + "bBAcAbca", + "baB", + 12 + ], + [ + "bBAcBA", + "aAa", + 9 + ], + [ + "bBAcC", + "abbBbCBc", + 10 + ], + [ + "bBAcC", + "c", + 8 + ], + [ + "bBAca", + "Ba", + 6 + ], + [ + "bBAca", + "b", + 8 + ], + [ + "bBAca", + "c", + 8 + ], + [ + "bBB", + "ABACC", + 8 + ], + [ + "bBB", + "AcaBacAc", + 14 + ], + [ + "bBB", + "BCCBCB", + 7 + ], + [ + "bBB", + "Cba", + 5 + ], + [ + "bBB", + "bACbcbAc", + 12 + ], + [ + "bBBABBb", + "Cbab", + 10 + ], + [ + "bBBAa", + "c", + 10 + ], + [ + "bBBBB", + "AacCA", + 10 + ], + [ + "bBBBBAa", + "AbbBAB", + 8 + ], + [ + "bBBBCb", + "B", + 10 + ], + [ + "bBBBabC", + "abBacCCBA", + 13 + ], + [ + "bBBBc", + "AB", + 8 + ], + [ + "bBBC", + "B", + 6 + ], + [ + "bBBC", + "abAbBBcab", + 11 + ], + [ + "bBBCABbB", + "caaCC", + 14 + ], + [ + "bBBCAbB", + "BcBCBCcBc", + 10 + ], + [ + "bBBa", + "abbCAA", + 8 + ], + [ + "bBBaB", + "cacCCbAA", + 14 + ], + [ + "bBBaC", + "Bcc", + 7 + ], + [ + "bBBaaBC", + "bcbcbBba", + 11 + ], + [ + "bBBaaBb", + "a", + 12 + ], + [ + "bBBaabc", + "caaBba", + 10 + ], + [ + "bBBabac", + "aaAA", + 11 + ], + [ + "bBBb", + "Accaab", + 10 + ], + [ + "bBBb", + "aAacAbca", + 14 + ], + [ + "bBBbAcBB", + "BBAbBAb", + 9 + ], + [ + "bBBbBbbbB", + "cc", + 18 + ], + [ + "bBBbCa", + "BcC", + 8 + ], + [ + "bBBbaB", + "caAaaC", + 10 + ], + [ + "bBBbaBbCa", + "a", + 16 + ], + [ + "bBBbacabB", + "Ba", + 14 + ], + [ + "bBBbcc", + "bcA", + 8 + ], + [ + "bBBc", + "ABBbACc", + 8 + ], + [ + "bBBc", + "BAAb", + 7 + ], + [ + "bBBcA", + "caB", + 8 + ], + [ + "bBBcaca", + "CBBBbABcb", + 10 + ], + [ + "bBC", + "AB", + 4 + ], + [ + "bBC", + "aaCaCAcBc", + 15 + ], + [ + "bBC", + "bcaBACB", + 8 + ], + [ + "bBC", + "cAB", + 6 + ], + [ + "bBC", + "cBaCcbca", + 12 + ], + [ + "bBCA", + "AAc", + 7 + ], + [ + "bBCA", + "bCCACBc", + 8 + ], + [ + "bBCA", + "babCCBAC", + 9 + ], + [ + "bBCA", + "cBaabcA", + 9 + ], + [ + "bBCAB", + "ACcBBBBab", + 13 + ], + [ + "bBCABBA", + "BCabbCAB", + 9 + ], + [ + "bBCAbAb", + "caAbA", + 8 + ], + [ + "bBCAbBba", + "CbbBbbC", + 10 + ], + [ + "bBCAcBcCA", + "B", + 16 + ], + [ + "bBCBa", + "cbAAB", + 8 + ], + [ + "bBCBaBCaa", + "bA", + 15 + ], + [ + "bBCBaC", + "aABCAca", + 10 + ], + [ + "bBCBabBC", + "cCAc", + 12 + ], + [ + "bBCC", + "baAbacaA", + 12 + ], + [ + "bBCCA", + "aa", + 9 + ], + [ + "bBCCCCABc", + "babacAA", + 13 + ], + [ + "bBCCCb", + "ACc", + 9 + ], + [ + "bBCCbAb", + "a", + 13 + ], + [ + "bBCaABB", + "CbACac", + 10 + ], + [ + "bBCaCCC", + "ABccBC", + 8 + ], + [ + "bBCaabcAA", + "CBABCC", + 13 + ], + [ + "bBCac", + "BA", + 7 + ], + [ + "bBCacbCA", + "BaCBcCBC", + 10 + ], + [ + "bBCb", + "bBcCA", + 4 + ], + [ + "bBCbAAaAC", + "CCbCCA", + 12 + ], + [ + "bBCbBa", + "AbBaACCB", + 10 + ], + [ + "bBCbb", + "aCcaC", + 9 + ], + [ + "bBCc", + "ccB", + 7 + ], + [ + "bBCcaAAa", + "caabAbC", + 13 + ], + [ + "bBa", + "Bba", + 2 + ], + [ + "bBa", + "b", + 4 + ], + [ + "bBa", + "bBcAca", + 6 + ], + [ + "bBa", + "bCA", + 3 + ], + [ + "bBa", + "cACaAbBa", + 10 + ], + [ + "bBa", + "ccBcbcAcc", + 15 + ], + [ + "bBaABCcC", + "ABA", + 12 + ], + [ + "bBaACBaB", + "BCBBABbb", + 10 + ], + [ + "bBaAaA", + "Bb", + 10 + ], + [ + "bBaAaBc", + "BAbcaACBc", + 8 + ], + [ + "bBaAaC", + "cCBACaaA", + 10 + ], + [ + "bBaAb", + "bACbbacAB", + 10 + ], + [ + "bBaBCAAaa", + "CACBAc", + 13 + ], + [ + "bBaBCCcA", + "bb", + 13 + ], + [ + "bBaBCaAaB", + "bCAbCbbB", + 10 + ], + [ + "bBaBCcBcB", + "cabcc", + 11 + ], + [ + "bBaBa", + "BC", + 8 + ], + [ + "bBaBbAbAB", + "aBAAbCCBA", + 12 + ], + [ + "bBaBbb", + "BaCAbbb", + 7 + ], + [ + "bBaC", + "BAaAcb", + 8 + ], + [ + "bBaCbcC", + "bA", + 11 + ], + [ + "bBaCcAA", + "cAbb", + 12 + ], + [ + "bBaaBb", + "Caa", + 8 + ], + [ + "bBaaBcBbb", + "cABAaA", + 15 + ], + [ + "bBaaCABa", + "bcbaBcbC", + 11 + ], + [ + "bBaaCa", + "bAAC", + 6 + ], + [ + "bBaabbbbc", + "cbA", + 16 + ], + [ + "bBaacaC", + "bccaBC", + 8 + ], + [ + "bBabAcBA", + "ccaAbA", + 9 + ], + [ + "bBabB", + "BabcBBB", + 8 + ], + [ + "bBabC", + "ABc", + 7 + ], + [ + "bBabaAC", + "ccaCb", + 12 + ], + [ + "bBac", + "AbaAcAaB", + 11 + ], + [ + "bBac", + "BBCc", + 3 + ], + [ + "bBacbBcb", + "bCbc", + 9 + ], + [ + "bBb", + "AA", + 6 + ], + [ + "bBb", + "AbCaacc", + 12 + ], + [ + "bBb", + "CaaCCCaA", + 16 + ], + [ + "bBb", + "Ccac", + 8 + ], + [ + "bBb", + "a", + 6 + ], + [ + "bBb", + "aCC", + 6 + ], + [ + "bBb", + "baAC", + 6 + ], + [ + "bBb", + "cBA", + 4 + ], + [ + "bBb", + "caBaCBa", + 11 + ], + [ + "bBbA", + "C", + 8 + ], + [ + "bBbA", + "CBcBAA", + 7 + ], + [ + "bBbA", + "caBBABaBa", + 13 + ], + [ + "bBbAAa", + "aabbb", + 10 + ], + [ + "bBbB", + "AcbAA", + 8 + ], + [ + "bBbB", + "a", + 8 + ], + [ + "bBbBBaBAc", + "c", + 16 + ], + [ + "bBbBBba", + "Bbc", + 10 + ], + [ + "bBbBb", + "B", + 8 + ], + [ + "bBbCA", + "abBBcBBbc", + 12 + ], + [ + "bBbCCca", + "aCaCBCB", + 11 + ], + [ + "bBba", + "aAA", + 7 + ], + [ + "bBba", + "abB", + 6 + ], + [ + "bBbaA", + "cBCBCcCCB", + 15 + ], + [ + "bBbaC", + "bc", + 7 + ], + [ + "bBbaCba", + "aBBccAaB", + 10 + ], + [ + "bBbabBAC", + "bCBa", + 11 + ], + [ + "bBbacbBCA", + "BA", + 14 + ], + [ + "bBbbCA", + "bACbBAa", + 8 + ], + [ + "bBbbbc", + "c", + 10 + ], + [ + "bBbcAAba", + "cC", + 14 + ], + [ + "bBbcBBCa", + "b", + 14 + ], + [ + "bBbcCC", + "aacCBb", + 10 + ], + [ + "bBbcCC", + "acabCCb", + 9 + ], + [ + "bBbcbA", + "BcBCabB", + 9 + ], + [ + "bBbcbA", + "cBaCcCbB", + 10 + ], + [ + "bBbcbBa", + "BbA", + 9 + ], + [ + "bBc", + "A", + 6 + ], + [ + "bBc", + "ACA", + 6 + ], + [ + "bBc", + "CC", + 5 + ], + [ + "bBc", + "bCbA", + 5 + ], + [ + "bBc", + "bbcA", + 3 + ], + [ + "bBcA", + "BaCba", + 7 + ], + [ + "bBcAACbB", + "bCba", + 10 + ], + [ + "bBcABCb", + "BAca", + 9 + ], + [ + "bBcAa", + "Ca", + 7 + ], + [ + "bBcAcBabB", + "ccaCAb", + 11 + ], + [ + "bBcAccBAc", + "cAc", + 12 + ], + [ + "bBcB", + "Ca", + 7 + ], + [ + "bBcBAbB", + "A", + 12 + ], + [ + "bBcBAca", + "BcbC", + 8 + ], + [ + "bBcBc", + "C", + 9 + ], + [ + "bBcCCbcb", + "CAAcacCaC", + 14 + ], + [ + "bBcCaAb", + "CbbbCa", + 9 + ], + [ + "bBcCbAAa", + "c", + 14 + ], + [ + "bBcaaaCAC", + "ACBbc", + 16 + ], + [ + "bBcb", + "bCCac", + 7 + ], + [ + "bBcba", + "bba", + 4 + ], + [ + "bBcbaB", + "BaCCbc", + 10 + ], + [ + "bBcbaBAbB", + "AAb", + 13 + ], + [ + "bBcbaBbAB", + "c", + 16 + ], + [ + "bBcc", + "CcBABA", + 10 + ], + [ + "bBcc", + "aAc", + 6 + ], + [ + "bBccACBbA", + "CaCCCB", + 12 + ], + [ + "bBccBc", + "Caac", + 9 + ], + [ + "bBccC", + "bAcc", + 4 + ], + [ + "bBccb", + "bccAbBbC", + 10 + ], + [ + "bBccb", + "caBAA", + 10 + ], + [ + "bBccbBbCb", + "AAAbbaBA", + 15 + ], + [ + "bBccbBccC", + "c", + 16 + ], + [ + "bBccbb", + "AaABa", + 11 + ], + [ + "bBcccB", + "bcCAca", + 7 + ], + [ + "bC", + "A", + 4 + ], + [ + "bC", + "ACBBaBa", + 12 + ], + [ + "bC", + "Abc", + 3 + ], + [ + "bC", + "BAAcb", + 8 + ], + [ + "bC", + "BAa", + 5 + ], + [ + "bC", + "BAcaBCAcc", + 15 + ], + [ + "bC", + "BCbcCA", + 8 + ], + [ + "bC", + "BacAcb", + 10 + ], + [ + "bC", + "CC", + 2 + ], + [ + "bC", + "CbBcAbcc", + 13 + ], + [ + "bC", + "aBaCA", + 7 + ], + [ + "bC", + "aCCbCABBB", + 14 + ], + [ + "bC", + "aaBBCAA", + 11 + ], + [ + "bC", + "aaCbaAcB", + 13 + ], + [ + "bC", + "acCcbcB", + 11 + ], + [ + "bC", + "b", + 2 + ], + [ + "bC", + "bBBBC", + 6 + ], + [ + "bC", + "bBb", + 4 + ], + [ + "bC", + "bC", + 0 + ], + [ + "bC", + "baAAcb", + 9 + ], + [ + "bC", + "bac", + 3 + ], + [ + "bC", + "bbBb", + 6 + ], + [ + "bC", + "c", + 3 + ], + [ + "bC", + "cABAac", + 10 + ], + [ + "bC", + "cABcACACa", + 15 + ], + [ + "bC", + "cAaCb", + 8 + ], + [ + "bC", + "cBbB", + 6 + ], + [ + "bC", + "cBcCbcc", + 11 + ], + [ + "bC", + "cBcCcAa", + 11 + ], + [ + "bC", + "cccCBcaba", + 16 + ], + [ + "bCA", + "BbCaCc", + 7 + ], + [ + "bCA", + "ac", + 5 + ], + [ + "bCA", + "bCB", + 2 + ], + [ + "bCA", + "ba", + 3 + ], + [ + "bCA", + "cbcbAc", + 7 + ], + [ + "bCAAA", + "Cc", + 8 + ], + [ + "bCAAA", + "cBabbA", + 9 + ], + [ + "bCAAABc", + "Aabab", + 11 + ], + [ + "bCAABaCbc", + "Cab", + 12 + ], + [ + "bCAABccA", + "AaacCBBcB", + 13 + ], + [ + "bCAAC", + "bBAaCcc", + 7 + ], + [ + "bCAACaCa", + "CcAACaC", + 5 + ], + [ + "bCAAaBbCA", + "CbaAcB", + 13 + ], + [ + "bCAB", + "bAAA", + 4 + ], + [ + "bCABB", + "bA", + 6 + ], + [ + "bCABBCAA", + "bBCbcCc", + 11 + ], + [ + "bCABBcB", + "bBbACbaBb", + 11 + ], + [ + "bCABa", + "AaAa", + 6 + ], + [ + "bCABaBAcc", + "CBbaCCba", + 13 + ], + [ + "bCAC", + "ABCcc", + 6 + ], + [ + "bCAC", + "caCa", + 6 + ], + [ + "bCAC", + "cbCcb", + 6 + ], + [ + "bCACBA", + "cbac", + 10 + ], + [ + "bCACBB", + "Bcb", + 9 + ], + [ + "bCACa", + "c", + 9 + ], + [ + "bCACaaC", + "Cacaaa", + 6 + ], + [ + "bCACaaa", + "cC", + 11 + ], + [ + "bCACb", + "B", + 9 + ], + [ + "bCACbA", + "Cb", + 8 + ], + [ + "bCAaCB", + "aCAbcCbB", + 8 + ], + [ + "bCAaCbac", + "a", + 14 + ], + [ + "bCAaccaCC", + "b", + 16 + ], + [ + "bCAbAAcA", + "bBBCAabAc", + 10 + ], + [ + "bCAbab", + "ca", + 9 + ], + [ + "bCAbb", + "CBAcBAcBB", + 12 + ], + [ + "bCAc", + "BaCAaaBa", + 11 + ], + [ + "bCAcBA", + "CBBcCCA", + 10 + ], + [ + "bCAcC", + "BbaccaCA", + 10 + ], + [ + "bCAcC", + "BcA", + 6 + ], + [ + "bCAcc", + "cbCAB", + 6 + ], + [ + "bCB", + "CCabaC", + 9 + ], + [ + "bCB", + "abaaAbbAC", + 15 + ], + [ + "bCB", + "bCAca", + 6 + ], + [ + "bCB", + "cBAB", + 5 + ], + [ + "bCBA", + "BccBbcAA", + 10 + ], + [ + "bCBAAa", + "c", + 11 + ], + [ + "bCBBBCbc", + "CAbbbB", + 10 + ], + [ + "bCBBBcB", + "BBaBCBbC", + 10 + ], + [ + "bCBBa", + "CccaaC", + 9 + ], + [ + "bCBBbCc", + "bBaAB", + 10 + ], + [ + "bCBC", + "AbaCcaCB", + 10 + ], + [ + "bCBC", + "CcbaCaA", + 10 + ], + [ + "bCBC", + "aCAbcbCC", + 10 + ], + [ + "bCBCAB", + "C", + 10 + ], + [ + "bCBCACBb", + "bBacBCaA", + 11 + ], + [ + "bCBCBcbc", + "bA", + 14 + ], + [ + "bCBCaAc", + "a", + 12 + ], + [ + "bCBCbC", + "A", + 12 + ], + [ + "bCBa", + "Ba", + 4 + ], + [ + "bCBaAb", + "CABCCcb", + 10 + ], + [ + "bCBaabC", + "ACb", + 10 + ], + [ + "bCBabCa", + "cAbaccCC", + 11 + ], + [ + "bCBacABab", + "ccAacAaCc", + 11 + ], + [ + "bCBacaAB", + "ACbABB", + 10 + ], + [ + "bCBb", + "aaAbAbbC", + 11 + ], + [ + "bCBb", + "cBabcA", + 9 + ], + [ + "bCBb", + "cBcccaA", + 12 + ], + [ + "bCBbAaAb", + "BabA", + 11 + ], + [ + "bCBbAac", + "CBcca", + 8 + ], + [ + "bCBbAcC", + "CBbBbb", + 8 + ], + [ + "bCBbC", + "CA", + 8 + ], + [ + "bCBbaCCA", + "BAAab", + 13 + ], + [ + "bCBbabb", + "BcCBA", + 10 + ], + [ + "bCBbbCb", + "ABcbAba", + 10 + ], + [ + "bCBc", + "bbBACc", + 6 + ], + [ + "bCBcB", + "bCAbccACb", + 10 + ], + [ + "bCBcBBc", + "b", + 12 + ], + [ + "bCBca", + "cAABaCCa", + 11 + ], + [ + "bCBcabA", + "CAcbbcBcB", + 14 + ], + [ + "bCBcba", + "ABAcbc", + 8 + ], + [ + "bCBcccbC", + "Cbbbc", + 10 + ], + [ + "bCC", + "A", + 6 + ], + [ + "bCC", + "ABBbCCC", + 8 + ], + [ + "bCC", + "AaC", + 4 + ], + [ + "bCC", + "BB", + 5 + ], + [ + "bCC", + "a", + 6 + ], + [ + "bCC", + "aCbBaaCB", + 12 + ], + [ + "bCC", + "b", + 4 + ], + [ + "bCC", + "bbBaCaCAc", + 12 + ], + [ + "bCC", + "cB", + 5 + ], + [ + "bCCAACA", + "bc", + 11 + ], + [ + "bCCAAbAa", + "aC", + 14 + ], + [ + "bCCACBb", + "BcAA", + 10 + ], + [ + "bCCAc", + "bcBCABabC", + 10 + ], + [ + "bCCBACAa", + "cCB", + 11 + ], + [ + "bCCBC", + "CbbbACC", + 10 + ], + [ + "bCCBaBa", + "BC", + 11 + ], + [ + "bCCBbBAA", + "ACBbbBc", + 9 + ], + [ + "bCCCABcb", + "BaBbbAb", + 12 + ], + [ + "bCCCa", + "aA", + 9 + ], + [ + "bCCCbccc", + "aCAA", + 14 + ], + [ + "bCCa", + "AabcB", + 9 + ], + [ + "bCCa", + "BccBa", + 5 + ], + [ + "bCCa", + "bCACAaBb", + 8 + ], + [ + "bCCaA", + "cbAbaAA", + 8 + ], + [ + "bCCaAbBB", + "CcC", + 13 + ], + [ + "bCCaBa", + "AcCabCAc", + 9 + ], + [ + "bCCaCc", + "abAcCA", + 9 + ], + [ + "bCCaa", + "cA", + 8 + ], + [ + "bCCaaCaa", + "cbcc", + 14 + ], + [ + "bCCab", + "B", + 9 + ], + [ + "bCCaccbbB", + "cC", + 15 + ], + [ + "bCCb", + "cBBaBB", + 10 + ], + [ + "bCCbA", + "bcBC", + 6 + ], + [ + "bCCbACBBB", + "CA", + 14 + ], + [ + "bCCbB", + "aaBcCbAA", + 10 + ], + [ + "bCCbCc", + "aACbC", + 6 + ], + [ + "bCCbcA", + "caACc", + 10 + ], + [ + "bCCcAcAB", + "aCAB", + 10 + ], + [ + "bCCcc", + "aACCcacB", + 8 + ], + [ + "bCCccC", + "aabAb", + 12 + ], + [ + "bCa", + "Cb", + 4 + ], + [ + "bCa", + "aBbb", + 7 + ], + [ + "bCa", + "bBACAbba", + 10 + ], + [ + "bCa", + "baba", + 4 + ], + [ + "bCa", + "cbacb", + 7 + ], + [ + "bCa", + "ccaCaCCc", + 12 + ], + [ + "bCaA", + "AABbbA", + 9 + ], + [ + "bCaA", + "CBc", + 6 + ], + [ + "bCaAC", + "ACaaABaCa", + 10 + ], + [ + "bCaBAc", + "bbbBcbcAc", + 10 + ], + [ + "bCaBBBA", + "caCcBBCcB", + 12 + ], + [ + "bCaBBC", + "cacbBC", + 6 + ], + [ + "bCaBbCAC", + "aaCAcCAbC", + 11 + ], + [ + "bCaCAabc", + "bBaB", + 11 + ], + [ + "bCaCAcaC", + "bcccaa", + 8 + ], + [ + "bCaCCC", + "cAbabbACA", + 14 + ], + [ + "bCaCcB", + "ABbbcCABC", + 12 + ], + [ + "bCaCcac", + "CBbCAA", + 10 + ], + [ + "bCaa", + "a", + 6 + ], + [ + "bCaa", + "aBC", + 7 + ], + [ + "bCaabBC", + "CCABcA", + 10 + ], + [ + "bCabAacbC", + "BAB", + 14 + ], + [ + "bCabCc", + "CA", + 9 + ], + [ + "bCabaAAB", + "A", + 14 + ], + [ + "bCabbAacb", + "Cba", + 12 + ], + [ + "bCabbC", + "CAacA", + 9 + ], + [ + "bCac", + "C", + 6 + ], + [ + "bCac", + "cC", + 6 + ], + [ + "bCacAbBa", + "a", + 14 + ], + [ + "bCacBA", + "abB", + 8 + ], + [ + "bCacCcB", + "aAabBBbC", + 13 + ], + [ + "bCaccBAa", + "CB", + 12 + ], + [ + "bCb", + "aCBc", + 5 + ], + [ + "bCb", + "ab", + 4 + ], + [ + "bCb", + "ccA", + 5 + ], + [ + "bCbA", + "ab", + 6 + ], + [ + "bCbAAAB", + "AccbcBaB", + 10 + ], + [ + "bCbAB", + "BcBB", + 5 + ], + [ + "bCbACcbc", + "b", + 14 + ], + [ + "bCbAa", + "acCBABB", + 9 + ], + [ + "bCbAbcBc", + "b", + 14 + ], + [ + "bCbB", + "b", + 6 + ], + [ + "bCbBabC", + "cbacBCaBc", + 10 + ], + [ + "bCbBacaA", + "aBAaBCaa", + 11 + ], + [ + "bCbBbbbC", + "a", + 16 + ], + [ + "bCbBbcAb", + "ba", + 13 + ], + [ + "bCbCAbB", + "CABBbb", + 9 + ], + [ + "bCbCCCAcb", + "a", + 17 + ], + [ + "bCbCbb", + "AAACCCB", + 11 + ], + [ + "bCbCccc", + "abbAbC", + 11 + ], + [ + "bCbaACBbb", + "bCCccaa", + 13 + ], + [ + "bCbaAc", + "BA", + 9 + ], + [ + "bCbaaBc", + "CbAAcaBc", + 7 + ], + [ + "bCbac", + "aAcBABbaA", + 13 + ], + [ + "bCbac", + "b", + 8 + ], + [ + "bCbacABa", + "cCaac", + 10 + ], + [ + "bCbb", + "bbCBabAC", + 9 + ], + [ + "bCbbb", + "AcBc", + 8 + ], + [ + "bCbbba", + "AaBbc", + 9 + ], + [ + "bCbc", + "ABb", + 6 + ], + [ + "bCbc", + "CCb", + 4 + ], + [ + "bCbcB", + "AbAab", + 9 + ], + [ + "bCbcCBA", + "BCbBacC", + 9 + ], + [ + "bCbcCC", + "BbbABA", + 9 + ], + [ + "bCbcCbAC", + "ccccC", + 10 + ], + [ + "bCbca", + "bcbBCBa", + 6 + ], + [ + "bCbcaAAAA", + "A", + 16 + ], + [ + "bCbcaca", + "bBBAcc", + 8 + ], + [ + "bCbcbbBbC", + "CaC", + 14 + ], + [ + "bCc", + "BabBBCb", + 10 + ], + [ + "bCc", + "CCBcAA", + 8 + ], + [ + "bCc", + "CCCcCBcC", + 12 + ], + [ + "bCc", + "aaAABCCaB", + 14 + ], + [ + "bCc", + "aabbbaaB", + 14 + ], + [ + "bCc", + "bccB", + 3 + ], + [ + "bCcABC", + "aAcBcCC", + 10 + ], + [ + "bCcACCBa", + "cac", + 12 + ], + [ + "bCcACCaC", + "AbcaC", + 9 + ], + [ + "bCcB", + "BBB", + 5 + ], + [ + "bCcBA", + "CcAbcCbaA", + 11 + ], + [ + "bCcBB", + "cBb", + 5 + ], + [ + "bCcC", + "ACBaB", + 8 + ], + [ + "bCcCb", + "ccbBac", + 10 + ], + [ + "bCcCcCCCB", + "BCAaAa", + 15 + ], + [ + "bCca", + "CCaaaBbc", + 12 + ], + [ + "bCcaA", + "cACB", + 9 + ], + [ + "bCcaBbac", + "bBa", + 10 + ], + [ + "bCcaCc", + "A", + 11 + ], + [ + "bCcaCcC", + "bcCB", + 8 + ], + [ + "bCcaaa", + "B", + 11 + ], + [ + "bCcaabCB", + "bbAbcaAA", + 13 + ], + [ + "bCcacBCA", + "aACBccC", + 11 + ], + [ + "bCcbAaBBc", + "c", + 16 + ], + [ + "bCcbCCbb", + "bBbacaC", + 11 + ], + [ + "bCcbbaCab", + "BC", + 15 + ], + [ + "bCcbbc", + "bBBCB", + 9 + ], + [ + "bCcbc", + "acBCAcc", + 9 + ], + [ + "bCcc", + "CAbacbA", + 10 + ], + [ + "bCccbbbc", + "bBABAaBAc", + 13 + ], + [ + "ba", + "ABbbC", + 8 + ], + [ + "ba", + "BA", + 2 + ], + [ + "ba", + "BAABBb", + 10 + ], + [ + "ba", + "BacAAbA", + 11 + ], + [ + "ba", + "BbAaaCACc", + 14 + ], + [ + "ba", + "BcCAAC", + 10 + ], + [ + "ba", + "Bcc", + 5 + ], + [ + "ba", + "CCccCCa", + 12 + ], + [ + "ba", + "CaAbAb", + 9 + ], + [ + "ba", + "Cba", + 2 + ], + [ + "ba", + "Cca", + 4 + ], + [ + "ba", + "Ccac", + 6 + ], + [ + "ba", + "a", + 2 + ], + [ + "ba", + "aBABA", + 8 + ], + [ + "ba", + "aBaABB", + 9 + ], + [ + "ba", + "aCcaCbAbB", + 15 + ], + [ + "ba", + "bBC", + 4 + ], + [ + "ba", + "bBCC", + 6 + ], + [ + "ba", + "baABc", + 6 + ], + [ + "ba", + "baCAbB", + 8 + ], + [ + "ba", + "cA", + 3 + ], + [ + "ba", + "cABA", + 6 + ], + [ + "ba", + "cBbCCaB", + 10 + ], + [ + "ba", + "cBc", + 5 + ], + [ + "ba", + "cCCBcC", + 11 + ], + [ + "ba", + "caBBCAca", + 13 + ], + [ + "ba", + "cbBbb", + 8 + ], + [ + "ba", + "ccb", + 6 + ], + [ + "baA", + "AbAAaCaa", + 11 + ], + [ + "baA", + "B", + 5 + ], + [ + "baA", + "BBB", + 5 + ], + [ + "baA", + "a", + 4 + ], + [ + "baA", + "aCaaB", + 7 + ], + [ + "baA", + "cAaBCBaCB", + 15 + ], + [ + "baA", + "cBBcccca", + 14 + ], + [ + "baA", + "ccABbC", + 10 + ], + [ + "baAA", + "BBAaCacBC", + 14 + ], + [ + "baAA", + "cbbbCcbac", + 15 + ], + [ + "baAAA", + "CCcC", + 10 + ], + [ + "baAAABbC", + "BcACCbBa", + 11 + ], + [ + "baAAAbAC", + "caBb", + 12 + ], + [ + "baAAa", + "cACaAB", + 8 + ], + [ + "baAAc", + "bC", + 7 + ], + [ + "baAAcCa", + "CCABACcBC", + 12 + ], + [ + "baABBcc", + "cbcaaABc", + 9 + ], + [ + "baABCaCA", + "CABCbCAC", + 8 + ], + [ + "baABaBaAA", + "CAabb", + 13 + ], + [ + "baABbAcC", + "BcCBCCC", + 10 + ], + [ + "baAC", + "bCbAbBCA", + 10 + ], + [ + "baACCCcaA", + "Cb", + 16 + ], + [ + "baACca", + "bBcB", + 8 + ], + [ + "baAa", + "AbAab", + 6 + ], + [ + "baAaCAcc", + "acAbB", + 11 + ], + [ + "baAbCAc", + "baAacAac", + 5 + ], + [ + "baAbaAaba", + "cBA", + 15 + ], + [ + "baAbabAb", + "CC", + 16 + ], + [ + "baAcABAC", + "aabCBbBcB", + 13 + ], + [ + "baAcB", + "bbcb", + 5 + ], + [ + "baAcCcaaa", + "ccAA", + 12 + ], + [ + "baAca", + "aaAcCc", + 6 + ], + [ + "baAcaA", + "C", + 11 + ], + [ + "baAcab", + "B", + 11 + ], + [ + "baAcc", + "AbacACCCb", + 10 + ], + [ + "baB", + "BbccbbBbC", + 14 + ], + [ + "baB", + "acbAB", + 5 + ], + [ + "baB", + "accCa", + 10 + ], + [ + "baB", + "cA", + 5 + ], + [ + "baB", + "ca", + 4 + ], + [ + "baB", + "ccBACC", + 10 + ], + [ + "baBA", + "aa", + 5 + ], + [ + "baBAC", + "aA", + 6 + ], + [ + "baBAbccc", + "BCBaC", + 11 + ], + [ + "baBB", + "bCCaAca", + 10 + ], + [ + "baBB", + "cacbb", + 6 + ], + [ + "baBBC", + "BbBAA", + 7 + ], + [ + "baBBCAAc", + "bBaabAccc", + 11 + ], + [ + "baBBCcBCa", + "ABbBca", + 9 + ], + [ + "baBBaa", + "BCABAa", + 6 + ], + [ + "baBBbAb", + "bACa", + 10 + ], + [ + "baBBbCbBC", + "cBABabC", + 11 + ], + [ + "baBBcaBcC", + "CCCb", + 16 + ], + [ + "baBBcb", + "BBCbCCb", + 9 + ], + [ + "baBCcbbA", + "BBacCC", + 11 + ], + [ + "baBa", + "aA", + 5 + ], + [ + "baBa", + "bBbcAAb", + 10 + ], + [ + "baBa", + "cCbbbcBC", + 12 + ], + [ + "baBaABBb", + "bBcB", + 10 + ], + [ + "baBaaC", + "A", + 11 + ], + [ + "baBaaC", + "bBbAcc", + 7 + ], + [ + "baBbC", + "ACAc", + 8 + ], + [ + "baBbcCbaC", + "C", + 16 + ], + [ + "baBc", + "BAAbCa", + 8 + ], + [ + "baBcAAC", + "aBAAbACa", + 8 + ], + [ + "baBcC", + "Abc", + 6 + ], + [ + "baBcCCBBA", + "bbacBaaaC", + 14 + ], + [ + "baBcCCBb", + "Bccacb", + 9 + ], + [ + "baBcaAc", + "bc", + 10 + ], + [ + "baBcbccA", + "bCCa", + 11 + ], + [ + "baBccBC", + "C", + 12 + ], + [ + "baBccccb", + "AAbbaBCb", + 11 + ], + [ + "baC", + "AABBAb", + 10 + ], + [ + "baC", + "AB", + 5 + ], + [ + "baC", + "BBa", + 5 + ], + [ + "baC", + "CAaCCcbb", + 12 + ], + [ + "baC", + "CC", + 4 + ], + [ + "baC", + "caBcB", + 7 + ], + [ + "baCA", + "Bc", + 6 + ], + [ + "baCACBCac", + "a", + 16 + ], + [ + "baCAaAaBa", + "bcBcCab", + 12 + ], + [ + "baCAbc", + "CCc", + 8 + ], + [ + "baCB", + "B", + 6 + ], + [ + "baCBACbBa", + "b", + 16 + ], + [ + "baCBC", + "CAAcaCaB", + 12 + ], + [ + "baCBbCB", + "abc", + 9 + ], + [ + "baCCCCBB", + "b", + 14 + ], + [ + "baCCCcC", + "bbcAcABac", + 13 + ], + [ + "baCCbAB", + "CbBAC", + 9 + ], + [ + "baCCc", + "BcACCa", + 6 + ], + [ + "baCCc", + "ab", + 8 + ], + [ + "baCa", + "BAabaACcC", + 12 + ], + [ + "baCa", + "CCAABc", + 11 + ], + [ + "baCaAAB", + "aCB", + 8 + ], + [ + "baCaCa", + "caC", + 7 + ], + [ + "baCaCcbAb", + "bCB", + 13 + ], + [ + "baCb", + "CAbA", + 7 + ], + [ + "baCbCAB", + "aCBccCcC", + 11 + ], + [ + "baCbCC", + "ACCbA", + 8 + ], + [ + "baCbbCb", + "bACAc", + 8 + ], + [ + "baCbc", + "aaAbAb", + 8 + ], + [ + "baCbcACBc", + "CACcBb", + 11 + ], + [ + "baCc", + "BbcaaB", + 8 + ], + [ + "baCcA", + "bbbBcB", + 8 + ], + [ + "baCcaaC", + "cCCA", + 10 + ], + [ + "baCcb", + "BaCacAa", + 7 + ], + [ + "baa", + "ACbBca", + 8 + ], + [ + "baa", + "BaC", + 3 + ], + [ + "baaABBcBb", + "ABcacAC", + 14 + ], + [ + "baaAC", + "aCAb", + 6 + ], + [ + "baaAaBB", + "ccABBac", + 12 + ], + [ + "baaAb", + "bAcBabC", + 8 + ], + [ + "baaAcA", + "B", + 11 + ], + [ + "baaBAA", + "CbabaCCAA", + 8 + ], + [ + "baaBAAabB", + "cCB", + 16 + ], + [ + "baaBBBb", + "aC", + 12 + ], + [ + "baaBabb", + "cAaB", + 9 + ], + [ + "baaBb", + "CBbaBAbC", + 9 + ], + [ + "baaBcaa", + "CcCCbb", + 13 + ], + [ + "baaCCcAB", + "cCA", + 11 + ], + [ + "baaCaac", + "aCAaCCbA", + 11 + ], + [ + "baaCbA", + "ccBAAcC", + 12 + ], + [ + "baaa", + "CaCbCb", + 10 + ], + [ + "baaa", + "bBbBAAC", + 10 + ], + [ + "baaaAc", + "CBBbBBB", + 13 + ], + [ + "baaaCA", + "aab", + 8 + ], + [ + "baaaaabB", + "BCbbccA", + 15 + ], + [ + "baaacac", + "ABa", + 11 + ], + [ + "baab", + "aABbABC", + 11 + ], + [ + "baabA", + "cACC", + 9 + ], + [ + "baabaBaab", + "aCcA", + 15 + ], + [ + "baac", + "ACBbca", + 10 + ], + [ + "baacACa", + "bccCB", + 8 + ], + [ + "baacBbA", + "AaaCCbaaA", + 9 + ], + [ + "baacCc", + "CACBAA", + 11 + ], + [ + "baacaCcb", + "BBbbbAaBA", + 16 + ], + [ + "baacabBAA", + "aaaaBaB", + 9 + ], + [ + "bab", + "Cc", + 6 + ], + [ + "bab", + "CcBC", + 7 + ], + [ + "bab", + "a", + 4 + ], + [ + "bab", + "aabbAaBca", + 13 + ], + [ + "babA", + "AB", + 6 + ], + [ + "babA", + "bCb", + 4 + ], + [ + "babA", + "cccABCc", + 12 + ], + [ + "babAAaBC", + "Cb", + 14 + ], + [ + "babAaAA", + "bc", + 12 + ], + [ + "babAaBA", + "BbcBAbC", + 10 + ], + [ + "babBBB", + "b", + 10 + ], + [ + "babBa", + "BB", + 7 + ], + [ + "babBbAbAC", + "CbabB", + 12 + ], + [ + "babC", + "BCB", + 6 + ], + [ + "babC", + "CABB", + 6 + ], + [ + "babCABaa", + "BbcCAab", + 9 + ], + [ + "babCB", + "bcCCaABBC", + 12 + ], + [ + "babCBb", + "AAcbb", + 7 + ], + [ + "babCCCc", + "cCAbbca", + 12 + ], + [ + "babCCa", + "c", + 11 + ], + [ + "babCabCab", + "caac", + 13 + ], + [ + "babCbcc", + "AaAAcA", + 10 + ], + [ + "baba", + "abBcbAc", + 9 + ], + [ + "babaBA", + "CbcBbBabB", + 11 + ], + [ + "babaC", + "CbAaAA", + 8 + ], + [ + "babaCBaa", + "BbCa", + 9 + ], + [ + "babaa", + "C", + 10 + ], + [ + "babaaCBCC", + "BbaaAc", + 10 + ], + [ + "babb", + "AcB", + 6 + ], + [ + "babbA", + "BabaAAaB", + 9 + ], + [ + "babbCaaCB", + "cCaAAaBc", + 15 + ], + [ + "babbCbC", + "AA", + 13 + ], + [ + "babbCc", + "acbACaB", + 10 + ], + [ + "babbbbA", + "acA", + 10 + ], + [ + "babbcccAA", + "bAA", + 12 + ], + [ + "babcacA", + "c", + 12 + ], + [ + "bac", + "CBC", + 5 + ], + [ + "bac", + "CcBc", + 6 + ], + [ + "bac", + "Ccbca", + 8 + ], + [ + "bac", + "aacAc", + 6 + ], + [ + "bac", + "ba", + 2 + ], + [ + "bacABcBc", + "ABccc", + 8 + ], + [ + "bacAbca", + "aBCACc", + 9 + ], + [ + "bacBCbBb", + "ccAbcABA", + 12 + ], + [ + "bacBCc", + "cBcBB", + 8 + ], + [ + "bacBaBc", + "AcbcAcA", + 10 + ], + [ + "bacC", + "bbAbaCAB", + 11 + ], + [ + "bacCACCA", + "b", + 14 + ], + [ + "bacCAa", + "b", + 10 + ], + [ + "bacCCCccC", + "CCBbcacA", + 13 + ], + [ + "bacCbaBcB", + "Cab", + 13 + ], + [ + "bacCcBC", + "aBcbcccB", + 10 + ], + [ + "bacaCC", + "BAaAbcAC", + 10 + ], + [ + "bacaCcA", + "BcBAc", + 9 + ], + [ + "bacabaAA", + "AAACCBaC", + 13 + ], + [ + "bacacBa", + "BCAAaAA", + 11 + ], + [ + "bacbABaB", + "bCABBAc", + 10 + ], + [ + "bacbCAbbb", + "BaA", + 13 + ], + [ + "bacc", + "aAcAA", + 7 + ], + [ + "baccAA", + "C", + 11 + ], + [ + "baccAa", + "abCCB", + 9 + ], + [ + "baccBAA", + "ccCCbcCC", + 13 + ], + [ + "baccBBc", + "CAb", + 12 + ], + [ + "baccBbBaa", + "AbcaCcbb", + 12 + ], + [ + "baccCaCA", + "CAccb", + 11 + ], + [ + "baccaBc", + "AccABCbCC", + 11 + ], + [ + "baccccCB", + "cC", + 12 + ], + [ + "bb", + "A", + 4 + ], + [ + "bb", + "AABcCbCB", + 13 + ], + [ + "bb", + "AC", + 4 + ], + [ + "bb", + "Aabc", + 6 + ], + [ + "bb", + "AbC", + 4 + ], + [ + "bb", + "AbCC", + 6 + ], + [ + "bb", + "AbCCbbB", + 10 + ], + [ + "bb", + "Acaa", + 8 + ], + [ + "bb", + "B", + 3 + ], + [ + "bb", + "BAbcaB", + 9 + ], + [ + "bb", + "BCAC", + 7 + ], + [ + "bb", + "Bbccc", + 7 + ], + [ + "bb", + "CC", + 4 + ], + [ + "bb", + "a", + 4 + ], + [ + "bb", + "aBcCcc", + 11 + ], + [ + "bb", + "aaBBCc", + 10 + ], + [ + "bb", + "acCc", + 8 + ], + [ + "bb", + "accBa", + 9 + ], + [ + "bb", + "bA", + 2 + ], + [ + "bb", + "bAc", + 4 + ], + [ + "bb", + "bCbAcbaC", + 12 + ], + [ + "bb", + "baAB", + 5 + ], + [ + "bb", + "cAbBAbC", + 10 + ], + [ + "bb", + "cB", + 3 + ], + [ + "bb", + "cBC", + 5 + ], + [ + "bb", + "cbAacCaca", + 16 + ], + [ + "bb", + "cbBbABC", + 10 + ], + [ + "bbA", + "ABC", + 5 + ], + [ + "bbA", + "BBCabAA", + 9 + ], + [ + "bbA", + "BcCC", + 7 + ], + [ + "bbA", + "CB", + 5 + ], + [ + "bbA", + "bBbaababa", + 13 + ], + [ + "bbA", + "cCabBCAc", + 11 + ], + [ + "bbAA", + "B", + 7 + ], + [ + "bbAA", + "CC", + 8 + ], + [ + "bbAAaBb", + "AcC", + 12 + ], + [ + "bbAAb", + "BBBaaACAb", + 10 + ], + [ + "bbAAc", + "bBaCb", + 6 + ], + [ + "bbAAcAca", + "CCbBaccCB", + 12 + ], + [ + "bbAAcBca", + "bcA", + 11 + ], + [ + "bbAAcbCb", + "bAabCBAAC", + 12 + ], + [ + "bbAB", + "AaABCCB", + 10 + ], + [ + "bbAB", + "AbabABcC", + 8 + ], + [ + "bbAB", + "cBb", + 6 + ], + [ + "bbABACAbC", + "Ccabbc", + 13 + ], + [ + "bbABBC", + "CaAA", + 10 + ], + [ + "bbABCBA", + "ACb", + 9 + ], + [ + "bbABCBCbc", + "b", + 16 + ], + [ + "bbABab", + "CAcaba", + 8 + ], + [ + "bbABc", + "Bac", + 6 + ], + [ + "bbABcBBc", + "Aa", + 14 + ], + [ + "bbABcb", + "c", + 10 + ], + [ + "bbACABB", + "acC", + 12 + ], + [ + "bbACCcCbb", + "CCcC", + 10 + ], + [ + "bbAa", + "CbCaC", + 6 + ], + [ + "bbAa", + "cBcBBC", + 10 + ], + [ + "bbAaC", + "bBcCcAB", + 10 + ], + [ + "bbAaCaBAB", + "aabBc", + 13 + ], + [ + "bbAabBcca", + "BbaabB", + 8 + ], + [ + "bbAaccbAb", + "aCbBAAc", + 14 + ], + [ + "bbAb", + "B", + 7 + ], + [ + "bbAb", + "baaCABAa", + 11 + ], + [ + "bbAb", + "caAABCaac", + 15 + ], + [ + "bbAbAcaCA", + "cacab", + 13 + ], + [ + "bbAbB", + "ccAaCc", + 10 + ], + [ + "bbAbBc", + "AbcAbaBa", + 8 + ], + [ + "bbAbC", + "BBa", + 7 + ], + [ + "bbAbC", + "BcAcaCaaa", + 13 + ], + [ + "bbAbcBA", + "cAbbcBC", + 8 + ], + [ + "bbAc", + "bB", + 5 + ], + [ + "bbAcBabb", + "b", + 14 + ], + [ + "bbAcCaAC", + "CccacCABB", + 12 + ], + [ + "bbAcaA", + "caCabBaAB", + 13 + ], + [ + "bbAcabA", + "bBcbCb", + 9 + ], + [ + "bbB", + "Ac", + 6 + ], + [ + "bbB", + "aCbba", + 6 + ], + [ + "bbB", + "cAcbbBb", + 8 + ], + [ + "bbBA", + "B", + 6 + ], + [ + "bbBACc", + "AcCCBa", + 12 + ], + [ + "bbBAab", + "caAaBCbCb", + 14 + ], + [ + "bbBAbaa", + "aa", + 10 + ], + [ + "bbBBA", + "A", + 8 + ], + [ + "bbBBaaC", + "aCB", + 12 + ], + [ + "bbBBbc", + "ab", + 10 + ], + [ + "bbBCCCAbA", + "aAcCBBc", + 14 + ], + [ + "bbBCCaa", + "AACaAbAA", + 14 + ], + [ + "bbBCaaAC", + "bBAc", + 9 + ], + [ + "bbBCcbcbc", + "BBBaCcbBc", + 7 + ], + [ + "bbBa", + "BBcbc", + 7 + ], + [ + "bbBa", + "Cc", + 8 + ], + [ + "bbBaAcBaC", + "Bcc", + 13 + ], + [ + "bbBaCacbC", + "BAAaBcCa", + 13 + ], + [ + "bbBbA", + "Bbca", + 6 + ], + [ + "bbBbB", + "bBCaCbABa", + 11 + ], + [ + "bbBbBc", + "ABbBbc", + 5 + ], + [ + "bbBbCcBa", + "ba", + 12 + ], + [ + "bbBbaaaBB", + "C", + 18 + ], + [ + "bbBbabc", + "ABACBBacC", + 11 + ], + [ + "bbBbbcCA", + "AaabaCabb", + 15 + ], + [ + "bbBbc", + "Bab", + 7 + ], + [ + "bbBc", + "AaCcBCbCb", + 15 + ], + [ + "bbBcBCA", + "acaba", + 11 + ], + [ + "bbBcCc", + "BAc", + 8 + ], + [ + "bbBcab", + "cAabaC", + 10 + ], + [ + "bbBcbAba", + "b", + 14 + ], + [ + "bbBccBaCB", + "AcbAaCc", + 12 + ], + [ + "bbC", + "A", + 6 + ], + [ + "bbC", + "AAccbCBAA", + 14 + ], + [ + "bbC", + "BCAC", + 5 + ], + [ + "bbC", + "BacBCA", + 8 + ], + [ + "bbC", + "acBbCB", + 7 + ], + [ + "bbCAAb", + "aBAAcAc", + 9 + ], + [ + "bbCABbc", + "aCa", + 11 + ], + [ + "bbCACA", + "cBc", + 10 + ], + [ + "bbCAaBb", + "babcacCA", + 10 + ], + [ + "bbCAaa", + "cBaBbCa", + 11 + ], + [ + "bbCBCca", + "bC", + 10 + ], + [ + "bbCBacAB", + "aC", + 13 + ], + [ + "bbCBcBBcb", + "bCCCaa", + 13 + ], + [ + "bbCC", + "cAbBccA", + 9 + ], + [ + "bbCCAA", + "b", + 10 + ], + [ + "bbCCCBc", + "CCBAcbab", + 14 + ], + [ + "bbCCaccaA", + "ba", + 14 + ], + [ + "bbCCbBA", + "A", + 12 + ], + [ + "bbCCcABa", + "CBBbC", + 13 + ], + [ + "bbCCcCc", + "BbaabbaCc", + 11 + ], + [ + "bbCa", + "BC", + 5 + ], + [ + "bbCa", + "abBbA", + 6 + ], + [ + "bbCaAB", + "CCACcabAC", + 12 + ], + [ + "bbCaBabbC", + "CaBABbacC", + 10 + ], + [ + "bbCaaC", + "BbaBCcbCA", + 11 + ], + [ + "bbCaaCA", + "BcBBB", + 12 + ], + [ + "bbCabA", + "BaBBA", + 8 + ], + [ + "bbCabcAA", + "bc", + 12 + ], + [ + "bbCbAaBaA", + "CbAaAAc", + 9 + ], + [ + "bbCbCB", + "AaBB", + 9 + ], + [ + "bbCbaACb", + "Abbc", + 11 + ], + [ + "bbCbcaBA", + "AB", + 13 + ], + [ + "bbCc", + "aBaC", + 6 + ], + [ + "bbCcAA", + "ccaBAabBA", + 14 + ], + [ + "bbCcBaA", + "aAbCCabAb", + 11 + ], + [ + "bbCcaABc", + "a", + 14 + ], + [ + "bbCcc", + "BBAAA", + 8 + ], + [ + "bbCccBCCa", + "cacaCc", + 12 + ], + [ + "bba", + "ABBcccabc", + 14 + ], + [ + "bba", + "Bb", + 3 + ], + [ + "bba", + "C", + 6 + ], + [ + "bba", + "CBACA", + 8 + ], + [ + "bba", + "aCCAABCcb", + 17 + ], + [ + "bba", + "bbba", + 2 + ], + [ + "bbaA", + "CaCcCbb", + 14 + ], + [ + "bbaACCB", + "bAcAccABC", + 10 + ], + [ + "bbaAaaacc", + "CbaACB", + 11 + ], + [ + "bbaAcBA", + "cBbcaa", + 10 + ], + [ + "bbaB", + "Acc", + 8 + ], + [ + "bbaBAccC", + "cBBAb", + 11 + ], + [ + "bbaBBCc", + "C", + 12 + ], + [ + "bbaBCaAb", + "cCbA", + 12 + ], + [ + "bbaBaAc", + "cABCaA", + 9 + ], + [ + "bbaBbCbCb", + "aBccbBC", + 11 + ], + [ + "bbaBbaAbC", + "acaccca", + 15 + ], + [ + "bbaBc", + "bAbbCc", + 6 + ], + [ + "bbaCbCB", + "CCCA", + 10 + ], + [ + "bbaCbbC", + "c", + 13 + ], + [ + "bbaCc", + "CbCaBAaC", + 11 + ], + [ + "bbaCcBccb", + "C", + 16 + ], + [ + "bbab", + "ACB", + 7 + ], + [ + "bbab", + "CbbCbCbcC", + 12 + ], + [ + "bbabAbca", + "cBbbAB", + 10 + ], + [ + "bbabBcc", + "CAa", + 12 + ], + [ + "bbabC", + "abBAaAba", + 9 + ], + [ + "bbabC", + "cBb", + 7 + ], + [ + "bbabc", + "AAccbABAc", + 12 + ], + [ + "bbacC", + "aabaacA", + 8 + ], + [ + "bbacacb", + "acbCBaAcC", + 12 + ], + [ + "bbacccaa", + "AbBABACaa", + 9 + ], + [ + "bbb", + "ABC", + 5 + ], + [ + "bbb", + "C", + 6 + ], + [ + "bbb", + "aCBc", + 7 + ], + [ + "bbbA", + "bccbbcCCB", + 12 + ], + [ + "bbbABA", + "a", + 11 + ], + [ + "bbbACCCa", + "CBbcC", + 10 + ], + [ + "bbbAaBB", + "B", + 12 + ], + [ + "bbbAaCac", + "cCc", + 12 + ], + [ + "bbbAcbcC", + "aBBACacb", + 9 + ], + [ + "bbbB", + "ABAc", + 7 + ], + [ + "bbbB", + "AbABcABAB", + 12 + ], + [ + "bbbB", + "BB", + 5 + ], + [ + "bbbB", + "aC", + 8 + ], + [ + "bbbB", + "cCCcBcbCb", + 14 + ], + [ + "bbbBBBBCb", + "BcaBa", + 14 + ], + [ + "bbbBbA", + "bbA", + 6 + ], + [ + "bbbBbCBcB", + "bbcBcCC", + 9 + ], + [ + "bbbCa", + "CCB", + 8 + ], + [ + "bbbCccAA", + "bBAa", + 10 + ], + [ + "bbbaABaac", + "abaCbCB", + 13 + ], + [ + "bbbaAa", + "b", + 10 + ], + [ + "bbbaB", + "AC", + 9 + ], + [ + "bbbaa", + "CBBccC", + 10 + ], + [ + "bbbaaBba", + "Baa", + 11 + ], + [ + "bbbaacbb", + "cBbaC", + 10 + ], + [ + "bbbacBbBc", + "bcbcbCCC", + 10 + ], + [ + "bbbb", + "AbaACaC", + 12 + ], + [ + "bbbbbAB", + "aaAaCb", + 13 + ], + [ + "bbbbc", + "BBbC", + 5 + ], + [ + "bbbcAB", + "aBAbBBa", + 11 + ], + [ + "bbbcAcCAC", + "AaBbcCCcb", + 12 + ], + [ + "bbbcB", + "bcCc", + 6 + ], + [ + "bbbcBa", + "CAAccB", + 10 + ], + [ + "bbbcCB", + "aAbBABa", + 10 + ], + [ + "bbbca", + "cBbcabCC", + 9 + ], + [ + "bbbcbBAbc", + "AAacbcc", + 12 + ], + [ + "bbbcbcbc", + "Cbbaac", + 10 + ], + [ + "bbc", + "ACBaABaCC", + 15 + ], + [ + "bbc", + "BcCBaBcCc", + 14 + ], + [ + "bbc", + "CcB", + 6 + ], + [ + "bbc", + "bCCcBAac", + 11 + ], + [ + "bbc", + "c", + 4 + ], + [ + "bbcA", + "AAC", + 7 + ], + [ + "bbcACCca", + "bAABA", + 11 + ], + [ + "bbcAbBa", + "CaaA", + 11 + ], + [ + "bbcAbca", + "CCCCc", + 11 + ], + [ + "bbcAcbBab", + "CBacCca", + 12 + ], + [ + "bbcB", + "BaAbbccBb", + 10 + ], + [ + "bbcBAa", + "baaacc", + 10 + ], + [ + "bbcBCa", + "CaBabc", + 11 + ], + [ + "bbcCA", + "CAb", + 8 + ], + [ + "bbcCBACB", + "bcBBCaBc", + 10 + ], + [ + "bbcCBbAA", + "CcAc", + 12 + ], + [ + "bbcCC", + "BcbCc", + 6 + ], + [ + "bbcCCcB", + "b", + 12 + ], + [ + "bbca", + "AbbcaAcCa", + 10 + ], + [ + "bbca", + "acaBbbB", + 11 + ], + [ + "bbcaACCab", + "aACBab", + 8 + ], + [ + "bbcaAb", + "b", + 10 + ], + [ + "bbcaCab", + "B", + 13 + ], + [ + "bbcaaBCA", + "BCaaC", + 8 + ], + [ + "bbcaacCC", + "bCCcBACB", + 11 + ], + [ + "bbcab", + "bABaa", + 6 + ], + [ + "bbcabAB", + "BcC", + 11 + ], + [ + "bbcb", + "abAA", + 6 + ], + [ + "bbcbB", + "bCbAab", + 7 + ], + [ + "bbcbBccAa", + "bA", + 14 + ], + [ + "bbcbCcAB", + "cacaCCaBA", + 10 + ], + [ + "bbcc", + "B", + 7 + ], + [ + "bbcc", + "CcBBaABa", + 14 + ], + [ + "bbccAcBCB", + "CbacCAaB", + 11 + ], + [ + "bbccC", + "bac", + 6 + ], + [ + "bbccCa", + "baacc", + 7 + ], + [ + "bbccCcA", + "CbbbC", + 10 + ], + [ + "bbccaca", + "bb", + 10 + ], + [ + "bbccb", + "ABCA", + 8 + ], + [ + "bbccbB", + "Cbccbcb", + 5 + ], + [ + "bbccbBB", + "cbCB", + 8 + ], + [ + "bc", + "ACcCb", + 8 + ], + [ + "bc", + "Aa", + 4 + ], + [ + "bc", + "Ac", + 2 + ], + [ + "bc", + "BBAA", + 7 + ], + [ + "bc", + "BcA", + 3 + ], + [ + "bc", + "BcbBaCaCB", + 15 + ], + [ + "bc", + "CACcCBc", + 11 + ], + [ + "bc", + "CBBaAccB", + 13 + ], + [ + "bc", + "CaBa", + 7 + ], + [ + "bc", + "CcCaaABa", + 14 + ], + [ + "bc", + "a", + 4 + ], + [ + "bc", + "aAA", + 6 + ], + [ + "bc", + "aACBcB", + 9 + ], + [ + "bc", + "aBacc", + 7 + ], + [ + "bc", + "aBbAa", + 8 + ], + [ + "bc", + "acb", + 4 + ], + [ + "bc", + "b", + 2 + ], + [ + "bc", + "bA", + 2 + ], + [ + "bc", + "bBCcbA", + 8 + ], + [ + "bc", + "c", + 2 + ], + [ + "bc", + "cBb", + 5 + ], + [ + "bc", + "caaabc", + 8 + ], + [ + "bc", + "ccAB", + 6 + ], + [ + "bcA", + "ABbA", + 5 + ], + [ + "bcA", + "BBB", + 5 + ], + [ + "bcA", + "aabaAAB", + 10 + ], + [ + "bcA", + "acacbc", + 9 + ], + [ + "bcA", + "cbaACAB", + 9 + ], + [ + "bcAA", + "BaCc", + 7 + ], + [ + "bcAABAab", + "CB", + 13 + ], + [ + "bcAABbbBa", + "ABcccc", + 14 + ], + [ + "bcAABcb", + "c", + 12 + ], + [ + "bcAAbc", + "B", + 11 + ], + [ + "bcAB", + "a", + 7 + ], + [ + "bcAB", + "bcB", + 2 + ], + [ + "bcABAABcB", + "Cc", + 15 + ], + [ + "bcABAbBC", + "c", + 14 + ], + [ + "bcABAcB", + "bcCBCAbCa", + 9 + ], + [ + "bcAC", + "AAaC", + 5 + ], + [ + "bcACABab", + "c", + 14 + ], + [ + "bcACBbBaC", + "baaAbBbB", + 10 + ], + [ + "bcACa", + "bbaAcCBB", + 10 + ], + [ + "bcACbCa", + "aaaBBAbC", + 13 + ], + [ + "bcAa", + "BC", + 6 + ], + [ + "bcAa", + "b", + 6 + ], + [ + "bcAaAabA", + "abBB", + 13 + ], + [ + "bcAaBABA", + "CABac", + 10 + ], + [ + "bcAaBAaC", + "AaC", + 10 + ], + [ + "bcAaBCc", + "ca", + 10 + ], + [ + "bcAaaC", + "cbA", + 9 + ], + [ + "bcAabc", + "BAABb", + 7 + ], + [ + "bcAb", + "BcbbbA", + 7 + ], + [ + "bcAbAAAAb", + "abCBaAABc", + 11 + ], + [ + "bcAbACaB", + "cCaCAC", + 10 + ], + [ + "bcAbacAbc", + "BccaBBCbb", + 12 + ], + [ + "bcAc", + "BCBcaBCaB", + 13 + ], + [ + "bcAca", + "A", + 8 + ], + [ + "bcAcba", + "CcAc", + 6 + ], + [ + "bcAcbccB", + "Abbac", + 10 + ], + [ + "bcAccA", + "bbabbAcC", + 11 + ], + [ + "bcAccab", + "CCACcbcC", + 10 + ], + [ + "bcB", + "AaCbCccbb", + 13 + ], + [ + "bcB", + "BaAACbA", + 11 + ], + [ + "bcB", + "CAAABA", + 10 + ], + [ + "bcB", + "aaAaBccC", + 13 + ], + [ + "bcB", + "bAAAACCA", + 13 + ], + [ + "bcB", + "cAbcb", + 5 + ], + [ + "bcBA", + "bBBAb", + 4 + ], + [ + "bcBAAc", + "BccA", + 7 + ], + [ + "bcBACabcB", + "abBA", + 14 + ], + [ + "bcBAab", + "baaaBbcc", + 11 + ], + [ + "bcBAcAC", + "aCCC", + 10 + ], + [ + "bcBBC", + "c", + 8 + ], + [ + "bcBBCbAbA", + "bcCCb", + 10 + ], + [ + "bcBBaA", + "ABCBb", + 9 + ], + [ + "bcBBabABb", + "BcbaBBBCa", + 11 + ], + [ + "bcBBbB", + "bbbCC", + 8 + ], + [ + "bcBCAaaaB", + "CC", + 15 + ], + [ + "bcBCBC", + "aCB", + 8 + ], + [ + "bcBCCAB", + "ABCbc", + 10 + ], + [ + "bcBCCB", + "cAb", + 9 + ], + [ + "bcBCCcbA", + "c", + 14 + ], + [ + "bcBCa", + "CBccAbA", + 10 + ], + [ + "bcBa", + "abaBbcaba", + 11 + ], + [ + "bcBaBB", + "CB", + 9 + ], + [ + "bcBaCc", + "aaCBa", + 9 + ], + [ + "bcBaa", + "BcBB", + 5 + ], + [ + "bcBabcbc", + "accAbcB", + 8 + ], + [ + "bcBac", + "BB", + 7 + ], + [ + "bcBbAB", + "aCAbA", + 7 + ], + [ + "bcBbACCB", + "BAbcCc", + 10 + ], + [ + "bcBbACCac", + "CB", + 15 + ], + [ + "bcBbBCB", + "BcCbb", + 8 + ], + [ + "bcBbbAcac", + "ACbccac", + 9 + ], + [ + "bcBbc", + "caC", + 7 + ], + [ + "bcBc", + "A", + 8 + ], + [ + "bcBcaa", + "BbbCAaBB", + 10 + ], + [ + "bcBccBCBA", + "ABaCCAba", + 13 + ], + [ + "bcBccbcC", + "aC", + 14 + ], + [ + "bcC", + "ACabb", + 9 + ], + [ + "bcC", + "Ac", + 4 + ], + [ + "bcC", + "CACac", + 8 + ], + [ + "bcC", + "CAaCbCbb", + 13 + ], + [ + "bcC", + "CacBAbbac", + 15 + ], + [ + "bcC", + "a", + 6 + ], + [ + "bcC", + "abBBcB", + 8 + ], + [ + "bcC", + "acaAAaCbb", + 14 + ], + [ + "bcC", + "bBCaBBC", + 9 + ], + [ + "bcC", + "bbbCCABb", + 11 + ], + [ + "bcC", + "cBBBBCac", + 13 + ], + [ + "bcC", + "cCAAb", + 8 + ], + [ + "bcC", + "ccBcB", + 7 + ], + [ + "bcCAAA", + "CCCBbBAC", + 11 + ], + [ + "bcCAaA", + "AbCabC", + 9 + ], + [ + "bcCAb", + "CbBccBC", + 9 + ], + [ + "bcCAcAa", + "cB", + 12 + ], + [ + "bcCAcbC", + "AcAAbc", + 7 + ], + [ + "bcCB", + "a", + 8 + ], + [ + "bcCBAB", + "AaBAcB", + 8 + ], + [ + "bcCBBcb", + "CaCbaa", + 11 + ], + [ + "bcCBC", + "cb", + 7 + ], + [ + "bcCBaCAAc", + "aBb", + 16 + ], + [ + "bcCBaCb", + "aaaacC", + 11 + ], + [ + "bcCCAbB", + "BBcCAcA", + 8 + ], + [ + "bcCCa", + "BACbBaAcC", + 13 + ], + [ + "bcCCaa", + "cBcC", + 9 + ], + [ + "bcCCcbA", + "AAaAcCCA", + 12 + ], + [ + "bcCa", + "bCCC", + 3 + ], + [ + "bcCaaAB", + "cAAc", + 9 + ], + [ + "bcCaacC", + "BbcaccCCB", + 10 + ], + [ + "bcCab", + "BcCABbCAC", + 10 + ], + [ + "bcCacAA", + "CcbB", + 10 + ], + [ + "bcCacCaa", + "ABc", + 14 + ], + [ + "bcCacba", + "Bc", + 11 + ], + [ + "bcCb", + "aCbcBbCc", + 10 + ], + [ + "bcCbB", + "bAbCc", + 8 + ], + [ + "bcCbBCbaB", + "BC", + 14 + ], + [ + "bcCbaa", + "BbAACBAaC", + 10 + ], + [ + "bcCbbc", + "baAA", + 10 + ], + [ + "bcCc", + "AAA", + 8 + ], + [ + "bcCcBB", + "BaAccBC", + 8 + ], + [ + "bcCcaCCca", + "AaCc", + 12 + ], + [ + "bcCcbAAc", + "Ca", + 13 + ], + [ + "bca", + "AB", + 6 + ], + [ + "bca", + "AcaaBC", + 8 + ], + [ + "bca", + "CACBbcC", + 10 + ], + [ + "bca", + "bccb", + 4 + ], + [ + "bcaA", + "aBaCBBAa", + 12 + ], + [ + "bcaAAbCbC", + "CCcAA", + 13 + ], + [ + "bcaABAa", + "Ac", + 12 + ], + [ + "bcaACb", + "bAbCaCB", + 8 + ], + [ + "bcaAa", + "BbCcc", + 9 + ], + [ + "bcaAaaAC", + "acaaABc", + 8 + ], + [ + "bcaAba", + "BabBAaccb", + 14 + ], + [ + "bcaB", + "bCBCBAA", + 9 + ], + [ + "bcaBBAC", + "Cb", + 12 + ], + [ + "bcaCA", + "ACA", + 5 + ], + [ + "bcaCA", + "aB", + 8 + ], + [ + "bcaCAABcB", + "bBAbCcbc", + 12 + ], + [ + "bcaCB", + "AbaACbaC", + 10 + ], + [ + "bcaCBa", + "BaAbAB", + 9 + ], + [ + "bcaCa", + "cCbccbA", + 9 + ], + [ + "bcaCbBA", + "bcBabAb", + 8 + ], + [ + "bcaCbCbaA", + "bbCBb", + 11 + ], + [ + "bcaCcB", + "cAab", + 8 + ], + [ + "bcaa", + "CC", + 7 + ], + [ + "bcaa", + "aaBA", + 7 + ], + [ + "bcaaA", + "BAAacaAba", + 11 + ], + [ + "bcaaABBA", + "baa", + 10 + ], + [ + "bcaaAcbC", + "aBACAcaab", + 13 + ], + [ + "bcaaBaAb", + "b", + 14 + ], + [ + "bcaacb", + "acCb", + 7 + ], + [ + "bcab", + "a", + 6 + ], + [ + "bcab", + "cCAabCBCb", + 13 + ], + [ + "bcabAA", + "BAAcca", + 9 + ], + [ + "bcabC", + "Aac", + 7 + ], + [ + "bcabb", + "aAaA", + 8 + ], + [ + "bcac", + "CCAAbCbC", + 12 + ], + [ + "bcb", + "A", + 6 + ], + [ + "bcb", + "aBabCcB", + 9 + ], + [ + "bcb", + "abACACc", + 11 + ], + [ + "bcbA", + "AcbAcbCaB", + 11 + ], + [ + "bcbAAA", + "a", + 11 + ], + [ + "bcbAAAB", + "a", + 13 + ], + [ + "bcbACB", + "CBbcbCca", + 9 + ], + [ + "bcbACCA", + "AabaACAcB", + 11 + ], + [ + "bcbACCC", + "c", + 12 + ], + [ + "bcbAbCbB", + "caA", + 12 + ], + [ + "bcbAc", + "BACCccbCb", + 13 + ], + [ + "bcbBA", + "baaaa", + 7 + ], + [ + "bcbBAABCa", + "cBAcaa", + 10 + ], + [ + "bcbCAaAC", + "bB", + 13 + ], + [ + "bcbCAc", + "caccbaABC", + 11 + ], + [ + "bcbCB", + "c", + 8 + ], + [ + "bcbCcCa", + "CCCbACb", + 11 + ], + [ + "bcbaAACb", + "aBAcA", + 11 + ], + [ + "bcbaBBB", + "AA", + 13 + ], + [ + "bcbaccb", + "ACACCB", + 9 + ], + [ + "bcbb", + "cBcACA", + 9 + ], + [ + "bcbb", + "cCCBaaA", + 12 + ], + [ + "bcbbABC", + "CAAaa", + 11 + ], + [ + "bcbbB", + "ABB", + 7 + ], + [ + "bcbbBc", + "cCc", + 8 + ], + [ + "bcbbCBabA", + "cCccbccBA", + 12 + ], + [ + "bcbc", + "AAA", + 8 + ], + [ + "bcbc", + "Ca", + 7 + ], + [ + "bcbcAC", + "bBAaaacb", + 12 + ], + [ + "bcc", + "C", + 5 + ], + [ + "bcc", + "CaACa", + 9 + ], + [ + "bcc", + "bACb", + 5 + ], + [ + "bcc", + "bbcCcAa", + 8 + ], + [ + "bccA", + "C", + 7 + ], + [ + "bccA", + "aAb", + 8 + ], + [ + "bccA", + "ab", + 8 + ], + [ + "bccABAba", + "acacC", + 13 + ], + [ + "bccAC", + "BbbBcA", + 8 + ], + [ + "bccAbaA", + "aAc", + 12 + ], + [ + "bccAbcbcb", + "CbbcbbA", + 11 + ], + [ + "bccB", + "BcacaCB", + 7 + ], + [ + "bccB", + "cAcb", + 5 + ], + [ + "bccBABc", + "bAacbb", + 10 + ], + [ + "bccBBB", + "aAbbbbC", + 11 + ], + [ + "bccBBCbBa", + "bbbaabCbB", + 11 + ], + [ + "bccBBc", + "cCcbac", + 6 + ], + [ + "bccBBccA", + "bB", + 12 + ], + [ + "bccBCCAC", + "bABBCAabC", + 9 + ], + [ + "bccBCCBc", + "ACBaa", + 13 + ], + [ + "bccBa", + "CAcbB", + 7 + ], + [ + "bccBbA", + "aBCcBBBC", + 9 + ], + [ + "bccCA", + "BaBAAba", + 11 + ], + [ + "bccCAbbB", + "ccC", + 10 + ], + [ + "bccCBab", + "c", + 12 + ], + [ + "bccCCAaBB", + "bBa", + 14 + ], + [ + "bccCaBCC", + "Bb", + 14 + ], + [ + "bcca", + "AaAaabA", + 12 + ], + [ + "bccaCBb", + "bAbcabA", + 9 + ], + [ + "bccaCCC", + "CCBCBbAAA", + 16 + ], + [ + "bccaa", + "C", + 9 + ], + [ + "bccaab", + "cAcc", + 9 + ], + [ + "bccbAbab", + "b", + 14 + ], + [ + "bccbBCcCA", + "B", + 16 + ], + [ + "bccbBb", + "ccba", + 6 + ], + [ + "bccbC", + "bBC", + 5 + ], + [ + "bccbbCC", + "bBccA", + 9 + ], + [ + "bccbbbCB", + "BbcABC", + 10 + ], + [ + "bccbccAc", + "bBC", + 12 + ], + [ + "bccc", + "ACcca", + 5 + ], + [ + "bcccAA", + "bCBAbca", + 10 + ], + [ + "bcccAaBca", + "BaC", + 14 + ], + [ + "bcccBBCaA", + "bcAcaCcb", + 10 + ], + [ + "bcccC", + "aAAaa", + 10 + ], + [ + "bcccCCCbc", + "Bac", + 15 + ], + [ + "c", + "A", + 2 + ], + [ + "c", + "AA", + 4 + ], + [ + "c", + "AABacBC", + 12 + ], + [ + "c", + "AAbBBaBB", + 16 + ], + [ + "c", + "AB", + 4 + ], + [ + "c", + "ABA", + 6 + ], + [ + "c", + "ABBaCCBBB", + 17 + ], + [ + "c", + "ABBbBBCBA", + 17 + ], + [ + "c", + "ABbCb", + 9 + ], + [ + "c", + "ABbaaba", + 14 + ], + [ + "c", + "AC", + 3 + ], + [ + "c", + "ACABa", + 9 + ], + [ + "c", + "ACCB", + 7 + ], + [ + "c", + "ACCcbCCbC", + 16 + ], + [ + "c", + "ACbBBC", + 11 + ], + [ + "c", + "Aa", + 4 + ], + [ + "c", + "AaABA", + 10 + ], + [ + "c", + "Aaa", + 6 + ], + [ + "c", + "AaaaBbBC", + 15 + ], + [ + "c", + "AaabCAb", + 13 + ], + [ + "c", + "Ab", + 4 + ], + [ + "c", + "AbaCAAA", + 13 + ], + [ + "c", + "AcCACaAA", + 14 + ], + [ + "c", + "AcCCBAcaB", + 16 + ], + [ + "c", + "Acb", + 4 + ], + [ + "c", + "AcccbCacB", + 16 + ], + [ + "c", + "B", + 2 + ], + [ + "c", + "BA", + 4 + ], + [ + "c", + "BAAAAbB", + 14 + ], + [ + "c", + "BACA", + 7 + ], + [ + "c", + "BACbAC", + 11 + ], + [ + "c", + "BAbBbAc", + 12 + ], + [ + "c", + "BAbb", + 8 + ], + [ + "c", + "BAcBb", + 8 + ], + [ + "c", + "BB", + 4 + ], + [ + "c", + "BBAACAb", + 13 + ], + [ + "c", + "BBABBC", + 11 + ], + [ + "c", + "BBBcBccc", + 14 + ], + [ + "c", + "BBbbc", + 8 + ], + [ + "c", + "BBbcbbac", + 14 + ], + [ + "c", + "BBcBc", + 8 + ], + [ + "c", + "BC", + 3 + ], + [ + "c", + "BCA", + 5 + ], + [ + "c", + "BCAAcBC", + 12 + ], + [ + "c", + "BCAbCb", + 11 + ], + [ + "c", + "BCBc", + 6 + ], + [ + "c", + "BCa", + 5 + ], + [ + "c", + "BCcbaB", + 10 + ], + [ + "c", + "Ba", + 4 + ], + [ + "c", + "BaAaaA", + 12 + ], + [ + "c", + "BaBacca", + 12 + ], + [ + "c", + "BaCCBaCAC", + 17 + ], + [ + "c", + "BaaBcAcBb", + 16 + ], + [ + "c", + "BaaccC", + 10 + ], + [ + "c", + "BabCcAAcA", + 16 + ], + [ + "c", + "BbABABaBC", + 17 + ], + [ + "c", + "BbCa", + 7 + ], + [ + "c", + "BbaAacbb", + 14 + ], + [ + "c", + "BbaCAAcBa", + 16 + ], + [ + "c", + "BbcBb", + 8 + ], + [ + "c", + "Bbcc", + 6 + ], + [ + "c", + "Bc", + 2 + ], + [ + "c", + "BcBa", + 6 + ], + [ + "c", + "Bcb", + 4 + ], + [ + "c", + "Bcccb", + 8 + ], + [ + "c", + "C", + 1 + ], + [ + "c", + "CB", + 3 + ], + [ + "c", + "CBABBC", + 11 + ], + [ + "c", + "CBAcCA", + 10 + ], + [ + "c", + "CBBAbbA", + 13 + ], + [ + "c", + "CBCBb", + 9 + ], + [ + "c", + "CBCaBa", + 11 + ], + [ + "c", + "CBb", + 5 + ], + [ + "c", + "CCCBaaCB", + 15 + ], + [ + "c", + "CCCCCC", + 11 + ], + [ + "c", + "Ca", + 3 + ], + [ + "c", + "CaAb", + 7 + ], + [ + "c", + "CaCa", + 7 + ], + [ + "c", + "Cab", + 5 + ], + [ + "c", + "CabC", + 7 + ], + [ + "c", + "CbAC", + 7 + ], + [ + "c", + "CbabCAaAc", + 16 + ], + [ + "c", + "CcAABA", + 10 + ], + [ + "c", + "CccaaAa", + 12 + ], + [ + "c", + "a", + 2 + ], + [ + "c", + "aAAa", + 8 + ], + [ + "c", + "aAAc", + 6 + ], + [ + "c", + "aACbcB", + 10 + ], + [ + "c", + "aAbACcCA", + 14 + ], + [ + "c", + "aAbab", + 10 + ], + [ + "c", + "aB", + 4 + ], + [ + "c", + "aBAC", + 7 + ], + [ + "c", + "aBBbbc", + 10 + ], + [ + "c", + "aBaaA", + 10 + ], + [ + "c", + "aBb", + 6 + ], + [ + "c", + "aBcABcCCb", + 16 + ], + [ + "c", + "aBcBBCBbc", + 16 + ], + [ + "c", + "aCa", + 5 + ], + [ + "c", + "aa", + 4 + ], + [ + "c", + "aaCBCbC", + 13 + ], + [ + "c", + "aabcBAAcc", + 16 + ], + [ + "c", + "aabcBcA", + 12 + ], + [ + "c", + "aacABB", + 10 + ], + [ + "c", + "aacb", + 6 + ], + [ + "c", + "aaccAca", + 12 + ], + [ + "c", + "ab", + 4 + ], + [ + "c", + "abAa", + 8 + ], + [ + "c", + "abCAcC", + 10 + ], + [ + "c", + "abCCAB", + 11 + ], + [ + "c", + "abCc", + 6 + ], + [ + "c", + "ac", + 2 + ], + [ + "c", + "accbaBBAB", + 16 + ], + [ + "c", + "b", + 2 + ], + [ + "c", + "bAAccBAa", + 14 + ], + [ + "c", + "bAaBAbcCc", + 16 + ], + [ + "c", + "bAcacAbb", + 14 + ], + [ + "c", + "bBAaCa", + 11 + ], + [ + "c", + "bBAcaCaca", + 16 + ], + [ + "c", + "bBBCbaB", + 13 + ], + [ + "c", + "bBBa", + 8 + ], + [ + "c", + "bBab", + 8 + ], + [ + "c", + "bBcCbcABC", + 16 + ], + [ + "c", + "bBcCca", + 10 + ], + [ + "c", + "bCBC", + 7 + ], + [ + "c", + "bCC", + 5 + ], + [ + "c", + "bCCAbcBBa", + 16 + ], + [ + "c", + "bCCa", + 7 + ], + [ + "c", + "bCabaBC", + 13 + ], + [ + "c", + "bCc", + 4 + ], + [ + "c", + "bCcA", + 6 + ], + [ + "c", + "baaAB", + 10 + ], + [ + "c", + "baaABBC", + 13 + ], + [ + "c", + "baaAccba", + 14 + ], + [ + "c", + "bbBbbBBa", + 16 + ], + [ + "c", + "bbCccAAC", + 14 + ], + [ + "c", + "bc", + 2 + ], + [ + "c", + "bcAbC", + 8 + ], + [ + "c", + "bcBAcAcB", + 14 + ], + [ + "c", + "bcbBbCcb", + 14 + ], + [ + "c", + "bccAAa", + 10 + ], + [ + "c", + "c", + 0 + ], + [ + "c", + "cAABBb", + 10 + ], + [ + "c", + "cAACa", + 8 + ], + [ + "c", + "cABc", + 6 + ], + [ + "c", + "cAaCBc", + 10 + ], + [ + "c", + "cAacbCCA", + 14 + ], + [ + "c", + "cBCCAbA", + 12 + ], + [ + "c", + "cBacAc", + 10 + ], + [ + "c", + "cBcCBb", + 10 + ], + [ + "c", + "cCAB", + 6 + ], + [ + "c", + "cCCbbBBcA", + 16 + ], + [ + "c", + "cCcaBbcba", + 16 + ], + [ + "c", + "ca", + 2 + ], + [ + "c", + "caC", + 4 + ], + [ + "c", + "caa", + 4 + ], + [ + "c", + "cabA", + 6 + ], + [ + "c", + "cb", + 2 + ], + [ + "c", + "cbCaBBab", + 14 + ], + [ + "c", + "cbCbAa", + 10 + ], + [ + "c", + "cbbBbCcC", + 14 + ], + [ + "c", + "cbcaAAC", + 12 + ], + [ + "c", + "cc", + 2 + ], + [ + "c", + "ccB", + 4 + ], + [ + "c", + "ccCBaBAC", + 14 + ], + [ + "c", + "ccc", + 4 + ], + [ + "cA", + "A", + 2 + ], + [ + "cA", + "AAbaCB", + 10 + ], + [ + "cA", + "AC", + 4 + ], + [ + "cA", + "Ac", + 4 + ], + [ + "cA", + "Acc", + 4 + ], + [ + "cA", + "BABCB", + 8 + ], + [ + "cA", + "BBc", + 6 + ], + [ + "cA", + "BaaBCbA", + 11 + ], + [ + "cA", + "Bbb", + 6 + ], + [ + "cA", + "BbbAAccB", + 14 + ], + [ + "cA", + "Bc", + 4 + ], + [ + "cA", + "C", + 3 + ], + [ + "cA", + "CAaCAABb", + 13 + ], + [ + "cA", + "CAaacAcc", + 12 + ], + [ + "cA", + "CbaAccc", + 11 + ], + [ + "cA", + "Cbbb", + 7 + ], + [ + "cA", + "CcC", + 4 + ], + [ + "cA", + "aB", + 4 + ], + [ + "cA", + "aC", + 4 + ], + [ + "cA", + "ab", + 4 + ], + [ + "cA", + "abAAcc", + 10 + ], + [ + "cA", + "abC", + 6 + ], + [ + "cA", + "bBCAbCa", + 11 + ], + [ + "cA", + "bCbbBCAC", + 13 + ], + [ + "cA", + "bCcCBcCA", + 12 + ], + [ + "cA", + "bcaCcbC", + 11 + ], + [ + "cA", + "cABaBCb", + 10 + ], + [ + "cA", + "cBaAB", + 6 + ], + [ + "cA", + "cCBababA", + 12 + ], + [ + "cA", + "ccCBbBab", + 13 + ], + [ + "cA", + "cca", + 3 + ], + [ + "cAA", + "AaaCaBcCb", + 16 + ], + [ + "cAA", + "AbBC", + 8 + ], + [ + "cAA", + "a", + 5 + ], + [ + "cAA", + "cb", + 4 + ], + [ + "cAAA", + "cBaC", + 5 + ], + [ + "cAAAA", + "bcA", + 8 + ], + [ + "cAAAC", + "aBAaCcCca", + 13 + ], + [ + "cAAAacbCB", + "BBaACbA", + 12 + ], + [ + "cAAAbabc", + "BCAacBCBc", + 10 + ], + [ + "cAAAbbc", + "AAbb", + 6 + ], + [ + "cAAAcB", + "bbAB", + 8 + ], + [ + "cAAB", + "ABCaCbCbC", + 15 + ], + [ + "cAAB", + "Aab", + 4 + ], + [ + "cAABaBAa", + "bAaBaBA", + 5 + ], + [ + "cAAC", + "CAB", + 5 + ], + [ + "cAACA", + "CaABCCbAb", + 10 + ], + [ + "cAACAC", + "BC", + 10 + ], + [ + "cAACaCc", + "AcabA", + 9 + ], + [ + "cAACb", + "BCAcca", + 8 + ], + [ + "cAACbABCc", + "CCbAB", + 9 + ], + [ + "cAACbb", + "aAaC", + 7 + ], + [ + "cAACcAA", + "bAaCcacb", + 8 + ], + [ + "cAAa", + "caABcbBAB", + 12 + ], + [ + "cAAaB", + "BBaAb", + 7 + ], + [ + "cAAaBAAA", + "aCb", + 14 + ], + [ + "cAAaCbCc", + "CC", + 12 + ], + [ + "cAAaba", + "bcb", + 10 + ], + [ + "cAAabcCCA", + "aAa", + 13 + ], + [ + "cAAbB", + "AAcaBaa", + 10 + ], + [ + "cAAbBA", + "caCcABAB", + 9 + ], + [ + "cAAbBBaCa", + "CabcB", + 12 + ], + [ + "cAAbC", + "BAbbb", + 6 + ], + [ + "cAAba", + "CCBAabaAB", + 10 + ], + [ + "cAAc", + "bCcCCB", + 10 + ], + [ + "cAAcABCcb", + "BCBB", + 13 + ], + [ + "cAAcB", + "ca", + 7 + ], + [ + "cAAcCCAc", + "Cb", + 14 + ], + [ + "cAAcaabB", + "A", + 14 + ], + [ + "cAAccaaB", + "BBbbAcBc", + 15 + ], + [ + "cAB", + "B", + 4 + ], + [ + "cAB", + "BCAAacb", + 10 + ], + [ + "cAB", + "CaCbCca", + 11 + ], + [ + "cAB", + "CbacbCcbB", + 14 + ], + [ + "cAB", + "b", + 5 + ], + [ + "cAB", + "baabbCA", + 12 + ], + [ + "cAB", + "cbbaBbCb", + 11 + ], + [ + "cAB", + "cccBBCBC", + 12 + ], + [ + "cAB", + "cccCCCCb", + 13 + ], + [ + "cABA", + "CA", + 5 + ], + [ + "cABAABc", + "acabCCb", + 11 + ], + [ + "cABABAACA", + "cBaBCcaa", + 10 + ], + [ + "cABAa", + "c", + 8 + ], + [ + "cABAcaBb", + "BCBaBCBc", + 11 + ], + [ + "cABBAaCac", + "aAacACCcc", + 10 + ], + [ + "cABBCaBbc", + "bBAaBcACC", + 13 + ], + [ + "cABBc", + "B", + 8 + ], + [ + "cABBcacb", + "bBcCcCAA", + 13 + ], + [ + "cABC", + "B", + 6 + ], + [ + "cABCAB", + "bAcb", + 8 + ], + [ + "cABCAc", + "cBCBa", + 6 + ], + [ + "cABCAca", + "ABaCCCbcc", + 12 + ], + [ + "cABCBbbCA", + "ABBccc", + 11 + ], + [ + "cABCa", + "CaA", + 7 + ], + [ + "cABaA", + "aAAbaBb", + 9 + ], + [ + "cABaAaA", + "BAB", + 10 + ], + [ + "cABaBAC", + "acCa", + 12 + ], + [ + "cABaCAbbA", + "A", + 16 + ], + [ + "cABac", + "BaCc", + 6 + ], + [ + "cABbACA", + "BbccCBCBc", + 15 + ], + [ + "cABba", + "AAC", + 8 + ], + [ + "cABc", + "AaccB", + 7 + ], + [ + "cABcABc", + "cAcBBca", + 6 + ], + [ + "cABcBcb", + "cbBCa", + 8 + ], + [ + "cABcb", + "Cac", + 6 + ], + [ + "cABcba", + "BAab", + 8 + ], + [ + "cAC", + "BCaCAbaCa", + 13 + ], + [ + "cAC", + "C", + 4 + ], + [ + "cAC", + "CABbA", + 7 + ], + [ + "cAC", + "CAcABbA", + 10 + ], + [ + "cAC", + "bAa", + 4 + ], + [ + "cAC", + "cBBac", + 6 + ], + [ + "cACAACCbc", + "CAcABb", + 10 + ], + [ + "cACABcACC", + "CAc", + 12 + ], + [ + "cACACbC", + "BbCcAa", + 11 + ], + [ + "cACAabC", + "BbcbBcAAa", + 14 + ], + [ + "cACBCaC", + "C", + 12 + ], + [ + "cACBCcCBb", + "bBaaBaCbC", + 14 + ], + [ + "cACBaaB", + "bccBcBaB", + 9 + ], + [ + "cACCBBcb", + "Ba", + 14 + ], + [ + "cACCaa", + "aBcCaab", + 7 + ], + [ + "cACCc", + "ccAa", + 7 + ], + [ + "cACa", + "aBBcB", + 9 + ], + [ + "cACa", + "cAbCCA", + 5 + ], + [ + "cACaB", + "cAbbaBB", + 6 + ], + [ + "cACac", + "cBCBbbbB", + 12 + ], + [ + "cACbCBB", + "bBbAC", + 12 + ], + [ + "cACbaCc", + "AacCACBaB", + 11 + ], + [ + "cACbaba", + "acAACBcCC", + 11 + ], + [ + "cACbbC", + "Cba", + 8 + ], + [ + "cACbbb", + "ccacBccbA", + 11 + ], + [ + "cACbcb", + "b", + 10 + ], + [ + "cACc", + "Cc", + 4 + ], + [ + "cACc", + "bAba", + 6 + ], + [ + "cACcA", + "Caccc", + 5 + ], + [ + "cACcAcc", + "bbB", + 14 + ], + [ + "cACca", + "acabb", + 9 + ], + [ + "cACcaA", + "bB", + 12 + ], + [ + "cACccAacA", + "bcCBabCc", + 14 + ], + [ + "cAa", + "BacbCAbcA", + 13 + ], + [ + "cAa", + "Bbcb", + 8 + ], + [ + "cAa", + "C", + 5 + ], + [ + "cAa", + "aCBcCAcc", + 12 + ], + [ + "cAa", + "aCacc", + 8 + ], + [ + "cAa", + "caBcA", + 6 + ], + [ + "cAa", + "cacAbaAb", + 10 + ], + [ + "cAa", + "ccccAcaBC", + 12 + ], + [ + "cAaA", + "CbbaAaba", + 10 + ], + [ + "cAaAA", + "CaCbcbab", + 13 + ], + [ + "cAaAA", + "acAc", + 7 + ], + [ + "cAaAABAcb", + "bAba", + 14 + ], + [ + "cAaACBaa", + "cbBabcaac", + 11 + ], + [ + "cAaACc", + "ccbBB", + 10 + ], + [ + "cAaAaaB", + "CBCbBccBa", + 15 + ], + [ + "cAaAc", + "ABCACcb", + 10 + ], + [ + "cAaB", + "C", + 7 + ], + [ + "cAaB", + "aBaBA", + 6 + ], + [ + "cAaBCBbAA", + "aAc", + 14 + ], + [ + "cAaBaA", + "a", + 10 + ], + [ + "cAaC", + "BcbAbbCb", + 10 + ], + [ + "cAaC", + "CbB", + 7 + ], + [ + "cAaCAc", + "ac", + 8 + ], + [ + "cAaCaAc", + "bBBBbaC", + 12 + ], + [ + "cAaCaC", + "ABBa", + 8 + ], + [ + "cAaCc", + "c", + 8 + ], + [ + "cAaaAAA", + "BBCAa", + 11 + ], + [ + "cAaaaBCA", + "AcABc", + 10 + ], + [ + "cAaaacAB", + "aAbCB", + 10 + ], + [ + "cAaaacaa", + "ABB", + 14 + ], + [ + "cAaacB", + "AaCBbACB", + 10 + ], + [ + "cAaaca", + "bAbbc", + 8 + ], + [ + "cAabACa", + "bcaabaaAb", + 9 + ], + [ + "cAabCA", + "CbACAAcb", + 11 + ], + [ + "cAaba", + "a", + 8 + ], + [ + "cAabcacaa", + "aA", + 15 + ], + [ + "cAacAaBBC", + "bBaBAbcaC", + 12 + ], + [ + "cAaca", + "AcacAA", + 7 + ], + [ + "cAaca", + "BcCcBBBA", + 13 + ], + [ + "cAacc", + "BBCaCA", + 9 + ], + [ + "cAacc", + "a", + 8 + ], + [ + "cAacccAb", + "ccbbBACA", + 13 + ], + [ + "cAb", + "B", + 5 + ], + [ + "cAb", + "BAbABAC", + 10 + ], + [ + "cAb", + "BBAAc", + 8 + ], + [ + "cAb", + "CBABCa", + 8 + ], + [ + "cAb", + "CbBBaA", + 10 + ], + [ + "cAb", + "caBACCa", + 10 + ], + [ + "cAbA", + "Cacc", + 6 + ], + [ + "cAbA", + "aAAACA", + 8 + ], + [ + "cAbABbab", + "aCA", + 13 + ], + [ + "cAbAC", + "BAAc", + 5 + ], + [ + "cAbACB", + "bAcCC", + 8 + ], + [ + "cAbACcCaa", + "cBa", + 13 + ], + [ + "cAbAb", + "acBC", + 9 + ], + [ + "cAbAbA", + "bACaC", + 9 + ], + [ + "cAbAbAAAa", + "A", + 16 + ], + [ + "cAbBB", + "AbaaC", + 8 + ], + [ + "cAbBaAAAA", + "BabaaBAa", + 9 + ], + [ + "cAbBaB", + "AcB", + 8 + ], + [ + "cAbaBbBC", + "a", + 14 + ], + [ + "cAbab", + "Ba", + 7 + ], + [ + "cAbabb", + "bC", + 10 + ], + [ + "cAbbB", + "aBBcaAA", + 13 + ], + [ + "cAbbBCAcB", + "aabbaC", + 11 + ], + [ + "cAbbBaca", + "CbCAcBaC", + 12 + ], + [ + "cAbbBbcC", + "CB", + 13 + ], + [ + "cAbbb", + "cCbaBAAAc", + 13 + ], + [ + "cAbcAcBA", + "AcA", + 10 + ], + [ + "cAbcaCccC", + "ABbAbbcB", + 12 + ], + [ + "cAbcbB", + "AAABaac", + 11 + ], + [ + "cAbccBCBc", + "AAACAcbAc", + 12 + ], + [ + "cAc", + "AbBCcaBB", + 13 + ], + [ + "cAc", + "BCCcCaBac", + 13 + ], + [ + "cAc", + "CB", + 5 + ], + [ + "cAc", + "bBb", + 6 + ], + [ + "cAc", + "bCaCaCb", + 11 + ], + [ + "cAc", + "bcb", + 6 + ], + [ + "cAc", + "cAAcaa", + 6 + ], + [ + "cAcA", + "CaaB", + 6 + ], + [ + "cAcAA", + "cbAcBbB", + 8 + ], + [ + "cAcABAAc", + "aABaBBc", + 9 + ], + [ + "cAcACcBb", + "cacbCccC", + 7 + ], + [ + "cAcAb", + "aBbAA", + 8 + ], + [ + "cAcAcAcCc", + "caaAAcbc", + 7 + ], + [ + "cAcAcCB", + "ccbcbBbC", + 10 + ], + [ + "cAcBBaBCb", + "C", + 16 + ], + [ + "cAcBCb", + "abCbAAB", + 11 + ], + [ + "cAcBCcBba", + "A", + 16 + ], + [ + "cAcBbA", + "aBabBACbB", + 13 + ], + [ + "cAcBbB", + "ABBcacBBA", + 10 + ], + [ + "cAcCAB", + "CBBbc", + 11 + ], + [ + "cAcCBCa", + "CCA", + 9 + ], + [ + "cAcCBcBBa", + "CacACBBBB", + 8 + ], + [ + "cAcCCBCBA", + "ccCcbcbc", + 8 + ], + [ + "cAcCbCcAB", + "caC", + 13 + ], + [ + "cAcCcbaaA", + "CcBaa", + 9 + ], + [ + "cAca", + "BAcbCbC", + 10 + ], + [ + "cAcaAa", + "caAAaab", + 7 + ], + [ + "cAcaBAAC", + "BBB", + 14 + ], + [ + "cAcaaa", + "BaBaBC", + 9 + ], + [ + "cAcaaca", + "aaCBA", + 10 + ], + [ + "cAcabCbCB", + "BacBcbABb", + 11 + ], + [ + "cAcabaB", + "Cc", + 11 + ], + [ + "cAcac", + "acbA", + 7 + ], + [ + "cAcbABCBB", + "aABc", + 12 + ], + [ + "cAcbBCBac", + "bCbAAacB", + 13 + ], + [ + "cAcbbccAc", + "AABAaBbCb", + 16 + ], + [ + "cAcc", + "aCa", + 6 + ], + [ + "cAcc", + "bCAAcaCC", + 10 + ], + [ + "cAcc", + "cc", + 4 + ], + [ + "cAccCB", + "aAABca", + 9 + ], + [ + "cAccaBCAb", + "BBcBCCAbb", + 12 + ], + [ + "cAccaaABa", + "bCAcB", + 13 + ], + [ + "cAcccAA", + "bCAb", + 11 + ], + [ + "cAcccaCaA", + "abaB", + 14 + ], + [ + "cAcccacab", + "BbCCbaB", + 13 + ], + [ + "cB", + "AbAB", + 6 + ], + [ + "cB", + "AbBbCA", + 10 + ], + [ + "cB", + "B", + 2 + ], + [ + "cB", + "BACbBc", + 9 + ], + [ + "cB", + "BAcB", + 4 + ], + [ + "cB", + "BBaBaaccC", + 16 + ], + [ + "cB", + "BcAaA", + 8 + ], + [ + "cB", + "C", + 3 + ], + [ + "cB", + "CAA", + 5 + ], + [ + "cB", + "CAAA", + 7 + ], + [ + "cB", + "CAacabCCC", + 15 + ], + [ + "cB", + "CBBB", + 5 + ], + [ + "cB", + "CCBCABaaA", + 15 + ], + [ + "cB", + "Cc", + 3 + ], + [ + "cB", + "CcBAc", + 6 + ], + [ + "cB", + "a", + 4 + ], + [ + "cB", + "aACCba", + 10 + ], + [ + "cB", + "aacbcC", + 9 + ], + [ + "cB", + "acaaAABB", + 12 + ], + [ + "cB", + "b", + 3 + ], + [ + "cB", + "ba", + 4 + ], + [ + "cB", + "baacB", + 6 + ], + [ + "cB", + "bc", + 4 + ], + [ + "cB", + "cABAbCBc", + 12 + ], + [ + "cB", + "cCAB", + 4 + ], + [ + "cB", + "caAAbbBC", + 12 + ], + [ + "cB", + "caBAAa", + 8 + ], + [ + "cBA", + "Ac", + 6 + ], + [ + "cBA", + "CB", + 3 + ], + [ + "cBA", + "a", + 5 + ], + [ + "cBA", + "ac", + 6 + ], + [ + "cBA", + "b", + 5 + ], + [ + "cBA", + "bbaBac", + 9 + ], + [ + "cBA", + "cAaabbab", + 12 + ], + [ + "cBAA", + "AAB", + 6 + ], + [ + "cBAA", + "aCabbA", + 8 + ], + [ + "cBAAB", + "CCa", + 8 + ], + [ + "cBAABa", + "bA", + 9 + ], + [ + "cBAABccc", + "caBcbAAa", + 13 + ], + [ + "cBAAbCcC", + "Bcc", + 11 + ], + [ + "cBAAcAbAC", + "bBaacb", + 10 + ], + [ + "cBAB", + "cBBcaCCb", + 10 + ], + [ + "cBABaBCc", + "BAABc", + 7 + ], + [ + "cBABaac", + "baCbbb", + 12 + ], + [ + "cBABbBAaA", + "c", + 16 + ], + [ + "cBABba", + "AaAccABac", + 12 + ], + [ + "cBABca", + "aBcB", + 7 + ], + [ + "cBACBAAcA", + "BBCbCCBb", + 13 + ], + [ + "cBACa", + "cbaabBBcA", + 12 + ], + [ + "cBACc", + "cBbBaCb", + 7 + ], + [ + "cBACcBBC", + "AbaaBbcC", + 11 + ], + [ + "cBACcbCaa", + "ab", + 15 + ], + [ + "cBAa", + "cCCBaAc", + 8 + ], + [ + "cBAaBcaB", + "b", + 15 + ], + [ + "cBAacbBa", + "aaBb", + 11 + ], + [ + "cBAbCaBA", + "ccaB", + 9 + ], + [ + "cBAba", + "B", + 8 + ], + [ + "cBAbaa", + "CaccCBA", + 12 + ], + [ + "cBAbb", + "ca", + 7 + ], + [ + "cBAbbCaCc", + "aaCA", + 13 + ], + [ + "cBAbca", + "aaACbA", + 9 + ], + [ + "cBAc", + "BA", + 4 + ], + [ + "cBAc", + "aCCcbbbcC", + 13 + ], + [ + "cBAcAb", + "BCabCbcc", + 13 + ], + [ + "cBAcAbaa", + "AAC", + 12 + ], + [ + "cBAcBBc", + "cCcaaa", + 10 + ], + [ + "cBAcCCb", + "cCcAc", + 9 + ], + [ + "cBAcb", + "CaAAACba", + 10 + ], + [ + "cBB", + "BacacBcCA", + 14 + ], + [ + "cBB", + "Bc", + 4 + ], + [ + "cBB", + "bAACA", + 10 + ], + [ + "cBB", + "bCbBBC", + 7 + ], + [ + "cBBA", + "AcAAcABa", + 11 + ], + [ + "cBBA", + "Cca", + 6 + ], + [ + "cBBABC", + "bCcbaAB", + 9 + ], + [ + "cBBABC", + "cCCcBcBc", + 9 + ], + [ + "cBBAac", + "CbbbcB", + 9 + ], + [ + "cBBBABBA", + "AAAbAAAB", + 13 + ], + [ + "cBBBCA", + "caacccAbA", + 13 + ], + [ + "cBBBCacAB", + "Accab", + 13 + ], + [ + "cBBBcbA", + "cB", + 10 + ], + [ + "cBBC", + "acaC", + 6 + ], + [ + "cBBCBaCbA", + "CBcBaAc", + 10 + ], + [ + "cBBCCAca", + "ABCcCa", + 8 + ], + [ + "cBBCb", + "cBBbaaC", + 8 + ], + [ + "cBBCbB", + "aCbBaCaB", + 8 + ], + [ + "cBBaBaAac", + "C", + 17 + ], + [ + "cBBaaCbBb", + "baCCBa", + 11 + ], + [ + "cBBabaAc", + "b", + 14 + ], + [ + "cBBac", + "ba", + 7 + ], + [ + "cBBacC", + "aBcCAC", + 8 + ], + [ + "cBBbAaabA", + "aaA", + 12 + ], + [ + "cBBbB", + "BCcAACb", + 11 + ], + [ + "cBBbBaBcA", + "bbCCCc", + 13 + ], + [ + "cBBbCbc", + "ACccCBaCB", + 13 + ], + [ + "cBBbbaBcb", + "Cc", + 15 + ], + [ + "cBBbbbb", + "acBbaBca", + 10 + ], + [ + "cBBbbcAC", + "bCaBbbcbB", + 9 + ], + [ + "cBBbbcacb", + "BcCcaaBA", + 13 + ], + [ + "cBBbca", + "BbA", + 7 + ], + [ + "cBBcAccA", + "AcbbAC", + 11 + ], + [ + "cBBcBb", + "BaCb", + 7 + ], + [ + "cBBcaBcB", + "Aa", + 14 + ], + [ + "cBBcbC", + "bcCBacb", + 8 + ], + [ + "cBC", + "cACacBc", + 9 + ], + [ + "cBC", + "cCa", + 4 + ], + [ + "cBCA", + "C", + 6 + ], + [ + "cBCACaCaC", + "ccBBBCaac", + 9 + ], + [ + "cBCAaac", + "cB", + 10 + ], + [ + "cBCAacA", + "aaAcA", + 8 + ], + [ + "cBCAcCccC", + "cbB", + 15 + ], + [ + "cBCAcbC", + "CcAbCbbaA", + 13 + ], + [ + "cBCB", + "bbabCAAbB", + 13 + ], + [ + "cBCBCbCa", + "bcCAaCCa", + 10 + ], + [ + "cBCBacA", + "AcbBaA", + 7 + ], + [ + "cBCBbCBa", + "c", + 14 + ], + [ + "cBCCABcC", + "Baa", + 13 + ], + [ + "cBCCB", + "a", + 10 + ], + [ + "cBCCBcaBa", + "AcAAba", + 13 + ], + [ + "cBCCC", + "A", + 10 + ], + [ + "cBCCcBc", + "ccaBCB", + 9 + ], + [ + "cBCaB", + "BBbAA", + 7 + ], + [ + "cBCab", + "aaABbC", + 10 + ], + [ + "cBCacA", + "abcbAbAa", + 11 + ], + [ + "cBCb", + "aCbCc", + 6 + ], + [ + "cBCb", + "b", + 6 + ], + [ + "cBCb", + "cAA", + 6 + ], + [ + "cBCbCAc", + "ACacAB", + 9 + ], + [ + "cBCbCca", + "aaB", + 13 + ], + [ + "cBCbabA", + "bbBbABB", + 9 + ], + [ + "cBCbbBBbc", + "aCaBBbbb", + 10 + ], + [ + "cBCbcCC", + "ACBbBBc", + 10 + ], + [ + "cBCc", + "AcaCBCb", + 8 + ], + [ + "cBCcAbcac", + "aBcac", + 10 + ], + [ + "cBCcbccaa", + "bBbCaBB", + 13 + ], + [ + "cBa", + "b", + 5 + ], + [ + "cBa", + "bAAaA", + 8 + ], + [ + "cBaAA", + "baaCbca", + 11 + ], + [ + "cBaAAB", + "BcbB", + 8 + ], + [ + "cBaAACacA", + "bBa", + 14 + ], + [ + "cBaABacb", + "ACb", + 11 + ], + [ + "cBaB", + "BabB", + 4 + ], + [ + "cBaB", + "CBBBC", + 5 + ], + [ + "cBaBBAB", + "B", + 12 + ], + [ + "cBaBBCc", + "BacCACa", + 10 + ], + [ + "cBaBaABBB", + "bcc", + 17 + ], + [ + "cBaBbCBC", + "cAAB", + 11 + ], + [ + "cBaBc", + "bbC", + 7 + ], + [ + "cBaC", + "BacB", + 5 + ], + [ + "cBaC", + "bA", + 6 + ], + [ + "cBaCA", + "CAcabbb", + 11 + ], + [ + "cBaCAbCC", + "B", + 14 + ], + [ + "cBaCAccbc", + "bbccAcCBB", + 10 + ], + [ + "cBaCCC", + "ab", + 10 + ], + [ + "cBaCaBC", + "Cb", + 11 + ], + [ + "cBaCab", + "BC", + 8 + ], + [ + "cBaa", + "BAab", + 5 + ], + [ + "cBaaA", + "Bb", + 8 + ], + [ + "cBaaCabBb", + "aCACcCbbb", + 11 + ], + [ + "cBaaaBBac", + "bcaAbBcC", + 10 + ], + [ + "cBaab", + "acAacAbCc", + 11 + ], + [ + "cBab", + "ACCAB", + 7 + ], + [ + "cBabB", + "C", + 9 + ], + [ + "cBabBCaca", + "C", + 16 + ], + [ + "cBabBcab", + "CbcAAAa", + 12 + ], + [ + "cBabCaA", + "aaAbAaac", + 10 + ], + [ + "cBabbBCBb", + "C", + 16 + ], + [ + "cBac", + "A", + 7 + ], + [ + "cBacCAB", + "B", + 12 + ], + [ + "cBacabC", + "aAAaB", + 10 + ], + [ + "cBacac", + "c", + 10 + ], + [ + "cBb", + "BbbA", + 5 + ], + [ + "cBb", + "CAbcC", + 7 + ], + [ + "cBb", + "acAB", + 5 + ], + [ + "cBbACBB", + "bCCCAbbC", + 12 + ], + [ + "cBbACC", + "ACa", + 8 + ], + [ + "cBbAcabB", + "aA", + 14 + ], + [ + "cBbC", + "abAabbbc", + 12 + ], + [ + "cBbCAACc", + "bBB", + 13 + ], + [ + "cBbCAB", + "cbCb", + 5 + ], + [ + "cBbCAa", + "cacaBBAb", + 11 + ], + [ + "cBbCAaA", + "AB", + 12 + ], + [ + "cBbCAb", + "bC", + 8 + ], + [ + "cBbCBAAA", + "AbBbc", + 12 + ], + [ + "cBbCCC", + "BCba", + 8 + ], + [ + "cBbCc", + "ccaCBA", + 8 + ], + [ + "cBbCccaC", + "bA", + 13 + ], + [ + "cBba", + "cb", + 4 + ], + [ + "cBbaACaa", + "cC", + 12 + ], + [ + "cBbaCbc", + "ccaaca", + 9 + ], + [ + "cBbaaac", + "b", + 12 + ], + [ + "cBbaab", + "BbbBcC", + 9 + ], + [ + "cBbaccBA", + "c", + 14 + ], + [ + "cBbb", + "CCcCaa", + 10 + ], + [ + "cBbb", + "abCb", + 5 + ], + [ + "cBbbA", + "A", + 8 + ], + [ + "cBbbA", + "B", + 8 + ], + [ + "cBbbBAAb", + "AAaa", + 13 + ], + [ + "cBbbBBacb", + "cCaCCcAac", + 14 + ], + [ + "cBbbBCaa", + "AaBc", + 13 + ], + [ + "cBbbCa", + "CB", + 9 + ], + [ + "cBbbcBB", + "bAACBBb", + 10 + ], + [ + "cBbcBaCBC", + "abA", + 15 + ], + [ + "cBbcCAC", + "b", + 12 + ], + [ + "cBbcCb", + "caBBbb", + 7 + ], + [ + "cBbcaBAAc", + "bB", + 14 + ], + [ + "cBbcbAAb", + "aba", + 13 + ], + [ + "cBbcbcBB", + "AccaA", + 12 + ], + [ + "cBbccCcc", + "aaCBabcBB", + 15 + ], + [ + "cBbccb", + "caaABcBb", + 9 + ], + [ + "cBc", + "BCaAAAbB", + 14 + ], + [ + "cBc", + "CAAC", + 6 + ], + [ + "cBc", + "aAc", + 4 + ], + [ + "cBc", + "aBaAAc", + 8 + ], + [ + "cBc", + "aabbAc", + 9 + ], + [ + "cBc", + "aac", + 4 + ], + [ + "cBc", + "c", + 4 + ], + [ + "cBcA", + "bC", + 6 + ], + [ + "cBcAAbbcb", + "BAbb", + 10 + ], + [ + "cBcACAA", + "a", + 13 + ], + [ + "cBcACb", + "Bc", + 8 + ], + [ + "cBcAaACbc", + "abbB", + 14 + ], + [ + "cBcBaaC", + "AbC", + 11 + ], + [ + "cBcBbCC", + "aBbCaba", + 11 + ], + [ + "cBcBbCbbA", + "cBa", + 13 + ], + [ + "cBcBbb", + "Acb", + 8 + ], + [ + "cBcCaaAcb", + "baccACCCc", + 13 + ], + [ + "cBcCbcCa", + "aCa", + 12 + ], + [ + "cBcCccaAa", + "BCaCCabbA", + 12 + ], + [ + "cBcaAaC", + "bACBCAB", + 12 + ], + [ + "cBcaAbBCb", + "baCbbaa", + 12 + ], + [ + "cBcaAbc", + "aa", + 11 + ], + [ + "cBcaAcaaA", + "CACbcC", + 14 + ], + [ + "cBcaBcBc", + "aBbBCACc", + 11 + ], + [ + "cBcaCcCA", + "Bcc", + 10 + ], + [ + "cBcabC", + "bAAAabb", + 10 + ], + [ + "cBcbACbBB", + "ACBc", + 12 + ], + [ + "cBcbBAbAC", + "A", + 16 + ], + [ + "cBcbC", + "AAbBcCa", + 10 + ], + [ + "cBcbcaCb", + "cCbcCB", + 6 + ], + [ + "cBcc", + "bAcAcaaba", + 14 + ], + [ + "cBcc", + "cacc", + 2 + ], + [ + "cBccaAac", + "aab", + 12 + ], + [ + "cBccaBCB", + "Caa", + 13 + ], + [ + "cBccacbCA", + "bBCBAca", + 11 + ], + [ + "cBccbc", + "CAbA", + 9 + ], + [ + "cBcccCAC", + "BA", + 12 + ], + [ + "cC", + "A", + 4 + ], + [ + "cC", + "ABCCCa", + 9 + ], + [ + "cC", + "AbAacCAc", + 12 + ], + [ + "cC", + "AccAAABc", + 13 + ], + [ + "cC", + "BBAabcC", + 10 + ], + [ + "cC", + "BBc", + 5 + ], + [ + "cC", + "BBcaACaA", + 12 + ], + [ + "cC", + "BCABBCAaC", + 15 + ], + [ + "cC", + "BaAbcaBc", + 13 + ], + [ + "cC", + "BaBaccb", + 11 + ], + [ + "cC", + "CBA", + 5 + ], + [ + "cC", + "CacCac", + 8 + ], + [ + "cC", + "CcACcacbB", + 14 + ], + [ + "cC", + "CcBbb", + 8 + ], + [ + "cC", + "aACbbCAB", + 13 + ], + [ + "cC", + "aBABCBbc", + 14 + ], + [ + "cC", + "aCCcAAca", + 13 + ], + [ + "cC", + "aaBaBbAA", + 16 + ], + [ + "cC", + "acAb", + 6 + ], + [ + "cC", + "b", + 4 + ], + [ + "cC", + "bA", + 4 + ], + [ + "cC", + "bACBaA", + 10 + ], + [ + "cC", + "bacAcbc", + 11 + ], + [ + "cC", + "bcaCBaB", + 10 + ], + [ + "cC", + "c", + 2 + ], + [ + "cC", + "cA", + 2 + ], + [ + "cC", + "cABAc", + 7 + ], + [ + "cC", + "cAbc", + 5 + ], + [ + "cC", + "cBA", + 4 + ], + [ + "cC", + "cBCAccaCb", + 14 + ], + [ + "cC", + "cabcBCB", + 10 + ], + [ + "cC", + "cccaBa", + 9 + ], + [ + "cCA", + "c", + 4 + ], + [ + "cCAABb", + "ACbaBC", + 7 + ], + [ + "cCAACb", + "bbC", + 10 + ], + [ + "cCAAacBb", + "a", + 14 + ], + [ + "cCAAc", + "ABbCcbBb", + 14 + ], + [ + "cCAAc", + "AC", + 7 + ], + [ + "cCAB", + "AAaCAABab", + 12 + ], + [ + "cCABbAb", + "Ab", + 10 + ], + [ + "cCABbaBaA", + "aacC", + 15 + ], + [ + "cCAC", + "bCbbbbAC", + 10 + ], + [ + "cCACAb", + "AbC", + 10 + ], + [ + "cCACCc", + "cccbAabc", + 9 + ], + [ + "cCACc", + "BbAcaB", + 9 + ], + [ + "cCAa", + "CBA", + 5 + ], + [ + "cCAaabBbA", + "bCCCcacb", + 13 + ], + [ + "cCAac", + "BBA", + 8 + ], + [ + "cCAacBCc", + "CCBBaA", + 11 + ], + [ + "cCAacCCbA", + "bCACCa", + 9 + ], + [ + "cCAbA", + "aBBcaccbA", + 11 + ], + [ + "cCAbABC", + "bbACCaACB", + 13 + ], + [ + "cCAbACcc", + "AbBAccbb", + 11 + ], + [ + "cCAbCacAA", + "BcABBAC", + 12 + ], + [ + "cCAbbaA", + "CcACabA", + 8 + ], + [ + "cCAbcA", + "BABABC", + 10 + ], + [ + "cCAcAcbaB", + "BccBaCC", + 13 + ], + [ + "cCAcCAB", + "bcccCbbab", + 11 + ], + [ + "cCAcaabBA", + "bBcbCCBa", + 13 + ], + [ + "cCAcbBBa", + "AaBca", + 10 + ], + [ + "cCAcbcB", + "c", + 12 + ], + [ + "cCB", + "BBCAbba", + 11 + ], + [ + "cCB", + "BCcab", + 7 + ], + [ + "cCB", + "CC", + 3 + ], + [ + "cCB", + "CbBa", + 5 + ], + [ + "cCB", + "a", + 6 + ], + [ + "cCB", + "aC", + 4 + ], + [ + "cCBA", + "abcA", + 6 + ], + [ + "cCBACb", + "abBccaC", + 11 + ], + [ + "cCBAbCCa", + "a", + 14 + ], + [ + "cCBAbaC", + "aAbaAa", + 10 + ], + [ + "cCBAcCB", + "CbaCB", + 6 + ], + [ + "cCBBAb", + "cBcaC", + 7 + ], + [ + "cCBBBc", + "Cc", + 8 + ], + [ + "cCBBaa", + "CBC", + 8 + ], + [ + "cCBCBAc", + "ABCBCBbCB", + 9 + ], + [ + "cCBCa", + "AcacaBCAc", + 10 + ], + [ + "cCBCbB", + "Cc", + 9 + ], + [ + "cCBCcbB", + "cCBaAaBc", + 8 + ], + [ + "cCBaAac", + "C", + 12 + ], + [ + "cCBaCc", + "CcbBBbB", + 10 + ], + [ + "cCBac", + "bb", + 9 + ], + [ + "cCBbAC", + "abAbC", + 8 + ], + [ + "cCBbAaabb", + "BCc", + 16 + ], + [ + "cCBbAcCAC", + "acBCCbA", + 12 + ], + [ + "cCBbAccB", + "abA", + 12 + ], + [ + "cCBbbB", + "bbaaCCBbB", + 11 + ], + [ + "cCBc", + "ABbacCc", + 10 + ], + [ + "cCBc", + "cAcBb", + 5 + ], + [ + "cCBcABc", + "ac", + 11 + ], + [ + "cCBcACBa", + "cACcB", + 10 + ], + [ + "cCBcACCa", + "BACAAaa", + 11 + ], + [ + "cCBca", + "cbCacC", + 6 + ], + [ + "cCBcb", + "BCbAABAba", + 12 + ], + [ + "cCBcbCaCb", + "cbBCa", + 10 + ], + [ + "cCC", + "BbacaAb", + 12 + ], + [ + "cCC", + "CB", + 4 + ], + [ + "cCC", + "accaCCCcb", + 12 + ], + [ + "cCC", + "bAbcCcbcb", + 13 + ], + [ + "cCC", + "bB", + 6 + ], + [ + "cCC", + "bCBbABBCc", + 14 + ], + [ + "cCC", + "baAAb", + 10 + ], + [ + "cCC", + "cABBc", + 7 + ], + [ + "cCC", + "cCCbaac", + 8 + ], + [ + "cCCAbbbaa", + "BccccA", + 15 + ], + [ + "cCCAc", + "ccAbbb", + 9 + ], + [ + "cCCBBaBC", + "bcaA", + 13 + ], + [ + "cCCBCAaA", + "baB", + 13 + ], + [ + "cCCBc", + "bAccaAcB", + 11 + ], + [ + "cCCCC", + "cBC", + 6 + ], + [ + "cCCCaA", + "cCbB", + 8 + ], + [ + "cCCCaac", + "BCAcCb", + 11 + ], + [ + "cCCCbA", + "CcBBBBb", + 11 + ], + [ + "cCCCbb", + "ABccCcA", + 10 + ], + [ + "cCCCbbbAa", + "cA", + 14 + ], + [ + "cCCa", + "AccBc", + 7 + ], + [ + "cCCaA", + "BcACCA", + 6 + ], + [ + "cCCaAAAC", + "aBbcC", + 12 + ], + [ + "cCCaCB", + "CaaAcbCAB", + 12 + ], + [ + "cCCaccA", + "bc", + 12 + ], + [ + "cCCaccAC", + "abAACcCa", + 12 + ], + [ + "cCCb", + "C", + 6 + ], + [ + "cCCb", + "cAcBa", + 6 + ], + [ + "cCCbBCBab", + "CCcaca", + 11 + ], + [ + "cCCbb", + "BCBbbcA", + 8 + ], + [ + "cCCbc", + "bCCC", + 5 + ], + [ + "cCCbcbabA", + "aaCCc", + 14 + ], + [ + "cCCcABBB", + "aBBbABcb", + 11 + ], + [ + "cCCcCCcAa", + "bBCab", + 15 + ], + [ + "cCCcaaC", + "aBC", + 10 + ], + [ + "cCa", + "BacAaCAcA", + 13 + ], + [ + "cCa", + "C", + 4 + ], + [ + "cCa", + "CAACAAaC", + 11 + ], + [ + "cCa", + "aBBcbc", + 10 + ], + [ + "cCa", + "aCBab", + 6 + ], + [ + "cCa", + "aaCCAAAb", + 12 + ], + [ + "cCa", + "bBAcCcB", + 10 + ], + [ + "cCa", + "cBBcaCB", + 9 + ], + [ + "cCaA", + "CCaca", + 4 + ], + [ + "cCaA", + "cBcccC", + 9 + ], + [ + "cCaAAACA", + "cBBbacc", + 12 + ], + [ + "cCaAAacCc", + "cbCaBcA", + 12 + ], + [ + "cCaABCAAA", + "A", + 16 + ], + [ + "cCaAb", + "aBaAB", + 5 + ], + [ + "cCaAbAABA", + "CCabcAAbb", + 8 + ], + [ + "cCaAc", + "ABAbbBBB", + 15 + ], + [ + "cCaAcACaa", + "caaBcBc", + 11 + ], + [ + "cCaAcCBca", + "ABcc", + 12 + ], + [ + "cCaAcbA", + "aBCBcCCba", + 12 + ], + [ + "cCaB", + "ABABAbBBc", + 15 + ], + [ + "cCaBBaAb", + "aA", + 12 + ], + [ + "cCaBBaCAC", + "bC", + 15 + ], + [ + "cCaBBba", + "aa", + 10 + ], + [ + "cCaBCbb", + "BcaCB", + 8 + ], + [ + "cCaBb", + "Ac", + 9 + ], + [ + "cCaC", + "AC", + 5 + ], + [ + "cCaCA", + "BBBbbCAC", + 12 + ], + [ + "cCaCBBBCb", + "B", + 16 + ], + [ + "cCaCCB", + "BcBac", + 9 + ], + [ + "cCaCaB", + "AbcA", + 10 + ], + [ + "cCaCaaaA", + "abcCcc", + 14 + ], + [ + "cCaCc", + "aA", + 8 + ], + [ + "cCaa", + "CcCbcbA", + 9 + ], + [ + "cCaaBCb", + "A", + 13 + ], + [ + "cCaab", + "a", + 8 + ], + [ + "cCabB", + "AbbA", + 8 + ], + [ + "cCabB", + "AcaaACCb", + 11 + ], + [ + "cCabC", + "aBcB", + 8 + ], + [ + "cCabaBC", + "aB", + 10 + ], + [ + "cCabc", + "cabcccAB", + 10 + ], + [ + "cCabcBa", + "abccAaAB", + 12 + ], + [ + "cCac", + "AacBAaA", + 10 + ], + [ + "cCacacaa", + "CACbAbcC", + 13 + ], + [ + "cCacba", + "aAbAbBAc", + 13 + ], + [ + "cCb", + "AccbcbcB", + 11 + ], + [ + "cCb", + "BaC", + 6 + ], + [ + "cCb", + "BabCcAA", + 12 + ], + [ + "cCb", + "aCaBbBbC", + 12 + ], + [ + "cCb", + "accCcBAbA", + 12 + ], + [ + "cCb", + "cC", + 2 + ], + [ + "cCbAB", + "bcaac", + 8 + ], + [ + "cCbAB", + "cca", + 6 + ], + [ + "cCbAc", + "baB", + 7 + ], + [ + "cCbAcaB", + "AaBB", + 10 + ], + [ + "cCbBAc", + "bbBBBCa", + 10 + ], + [ + "cCbBBAbC", + "BCa", + 13 + ], + [ + "cCbBa", + "AAcCCaAB", + 11 + ], + [ + "cCbBacc", + "aBAbCAc", + 11 + ], + [ + "cCbBb", + "aacaBa", + 9 + ], + [ + "cCbBb", + "baAAacaCA", + 17 + ], + [ + "cCbBbc", + "acaAbC", + 8 + ], + [ + "cCbC", + "B", + 7 + ], + [ + "cCbC", + "CcBaA", + 7 + ], + [ + "cCbC", + "aC", + 6 + ], + [ + "cCbCCbCaA", + "acBBbCcC", + 12 + ], + [ + "cCbCaCBa", + "aBBAAbaA", + 13 + ], + [ + "cCbCac", + "CBAB", + 8 + ], + [ + "cCbCcaCc", + "cAbbAab", + 10 + ], + [ + "cCbCcbcbA", + "cbb", + 12 + ], + [ + "cCbaACaB", + "AB", + 12 + ], + [ + "cCbaAcaa", + "BCcCcb", + 12 + ], + [ + "cCbaB", + "aCCbc", + 7 + ], + [ + "cCbbAaaba", + "CccBCA", + 14 + ], + [ + "cCbbAbBC", + "acaAcBC", + 9 + ], + [ + "cCbbBC", + "bca", + 10 + ], + [ + "cCbbCB", + "AaBb", + 9 + ], + [ + "cCbbCBc", + "aBBAbba", + 12 + ], + [ + "cCbbCaA", + "A", + 12 + ], + [ + "cCbbabAC", + "B", + 15 + ], + [ + "cCbbccCb", + "bAcCc", + 10 + ], + [ + "cCbcABAa", + "ABaACa", + 11 + ], + [ + "cCbcB", + "bBBcbbA", + 10 + ], + [ + "cCbcbc", + "Aa", + 12 + ], + [ + "cCbccbB", + "abaaBc", + 11 + ], + [ + "cCbccbbaC", + "aCBAcBB", + 11 + ], + [ + "cCc", + "ABcAcB", + 8 + ], + [ + "cCc", + "BbaaC", + 9 + ], + [ + "cCc", + "CAbAabcAc", + 14 + ], + [ + "cCc", + "CccC", + 4 + ], + [ + "cCcA", + "CBaCbc", + 9 + ], + [ + "cCcAAC", + "cCbaCa", + 7 + ], + [ + "cCcAAbbcB", + "A", + 16 + ], + [ + "cCcAB", + "BCCa", + 6 + ], + [ + "cCcACAaCB", + "cccb", + 12 + ], + [ + "cCcAbbBbc", + "CBbaAb", + 12 + ], + [ + "cCcAcAa", + "c", + 12 + ], + [ + "cCcBC", + "CBBAbBAcC", + 13 + ], + [ + "cCcBCcbcb", + "C", + 16 + ], + [ + "cCcC", + "aAcbBCb", + 10 + ], + [ + "cCcCAb", + "bAaCcaCCB", + 11 + ], + [ + "cCcCaCaCB", + "AC", + 15 + ], + [ + "cCcCcB", + "b", + 11 + ], + [ + "cCcaAbCC", + "cAAaCC", + 7 + ], + [ + "cCcaBA", + "C", + 10 + ], + [ + "cCcaBBB", + "BCaCCcB", + 10 + ], + [ + "cCcaC", + "CCAcbCcCc", + 11 + ], + [ + "cCcaCa", + "AAcb", + 10 + ], + [ + "cCcaabba", + "A", + 15 + ], + [ + "cCcabc", + "bc", + 8 + ], + [ + "cCcb", + "BBaAbbaAb", + 16 + ], + [ + "cCcbAbcb", + "AcCbcAAA", + 12 + ], + [ + "cCcbBCCBC", + "cC", + 14 + ], + [ + "cCcbCCB", + "BAbABC", + 12 + ], + [ + "cCcbCaaC", + "cbbcccbca", + 12 + ], + [ + "cCcbaCca", + "baBCABcC", + 13 + ], + [ + "cCcbaba", + "cCBBA", + 7 + ], + [ + "cCcc", + "a", + 8 + ], + [ + "cCccBaa", + "CBcBA", + 7 + ], + [ + "cCccCaCbA", + "caABbAcB", + 13 + ], + [ + "cCccaA", + "abb", + 12 + ], + [ + "cCccbA", + "BBabb", + 10 + ], + [ + "cCccbB", + "abAcB", + 8 + ], + [ + "cCcccAAb", + "aa", + 14 + ], + [ + "cCcccC", + "CBcBaAAc", + 12 + ], + [ + "cCcccCA", + "bcCACb", + 9 + ], + [ + "ca", + "AC", + 4 + ], + [ + "ca", + "ACA", + 4 + ], + [ + "ca", + "ACACb", + 8 + ], + [ + "ca", + "ACa", + 3 + ], + [ + "ca", + "Aaaa", + 6 + ], + [ + "ca", + "BAacabbab", + 14 + ], + [ + "ca", + "BB", + 4 + ], + [ + "ca", + "BBcaAbBcb", + 14 + ], + [ + "ca", + "BacCBC", + 10 + ], + [ + "ca", + "BbA", + 5 + ], + [ + "ca", + "BbBbBC", + 12 + ], + [ + "ca", + "BbCACC", + 10 + ], + [ + "ca", + "Bcbc", + 6 + ], + [ + "ca", + "BccA", + 5 + ], + [ + "ca", + "C", + 3 + ], + [ + "ca", + "CA", + 2 + ], + [ + "ca", + "CAC", + 4 + ], + [ + "ca", + "CCcbBaaab", + 14 + ], + [ + "ca", + "CbCaAaB", + 11 + ], + [ + "ca", + "a", + 2 + ], + [ + "ca", + "aBAA", + 7 + ], + [ + "ca", + "aC", + 4 + ], + [ + "ca", + "aaAbcACCc", + 15 + ], + [ + "ca", + "acccCcBc", + 14 + ], + [ + "ca", + "bAAaCCAc", + 14 + ], + [ + "ca", + "bBcAABbbB", + 15 + ], + [ + "ca", + "bbb", + 6 + ], + [ + "ca", + "cBC", + 4 + ], + [ + "ca", + "cCbba", + 6 + ], + [ + "ca", + "ccBBaba", + 10 + ], + [ + "caA", + "B", + 6 + ], + [ + "caA", + "CcCcAA", + 7 + ], + [ + "caA", + "aCAbCCCA", + 12 + ], + [ + "caA", + "aCcCbbAAC", + 13 + ], + [ + "caA", + "bBbac", + 8 + ], + [ + "caA", + "bCACCACC", + 12 + ], + [ + "caA", + "bbaA", + 4 + ], + [ + "caA", + "bbbBA", + 8 + ], + [ + "caA", + "cbAacAbbc", + 12 + ], + [ + "caAA", + "bAbaa", + 7 + ], + [ + "caAAAB", + "ab", + 9 + ], + [ + "caAAAcaA", + "CacaAcA", + 6 + ], + [ + "caAACbc", + "CBBCABbbb", + 13 + ], + [ + "caAB", + "A", + 6 + ], + [ + "caAB", + "BCAcbbB", + 10 + ], + [ + "caAB", + "CAaAab", + 6 + ], + [ + "caABabc", + "ACbbCCC", + 12 + ], + [ + "caABb", + "AaCaBC", + 7 + ], + [ + "caAC", + "CbCcB", + 8 + ], + [ + "caAC", + "bBBBCCBA", + 14 + ], + [ + "caACABAA", + "aa", + 13 + ], + [ + "caACBa", + "BbbBcAc", + 13 + ], + [ + "caACCBAaa", + "bbAcA", + 13 + ], + [ + "caACCac", + "a", + 12 + ], + [ + "caAa", + "abBcaB", + 10 + ], + [ + "caAa", + "acaCcBc", + 10 + ], + [ + "caAaBaBc", + "bcbCa", + 14 + ], + [ + "caAaa", + "ac", + 8 + ], + [ + "caAaaaaa", + "ccc", + 14 + ], + [ + "caAac", + "ACcACAbc", + 9 + ], + [ + "caAbAAcBb", + "c", + 16 + ], + [ + "caAbAcACB", + "CBCCaAaaB", + 13 + ], + [ + "caAbBBAbC", + "bacC", + 13 + ], + [ + "caAbBCb", + "bbaaaCc", + 11 + ], + [ + "caAbbBa", + "bAC", + 12 + ], + [ + "caAbbb", + "bbCACabaC", + 13 + ], + [ + "caAc", + "baCBB", + 8 + ], + [ + "caAcCc", + "ACc", + 6 + ], + [ + "caAcbbaCB", + "cbcBc", + 12 + ], + [ + "caAcc", + "BBbabc", + 9 + ], + [ + "caAcccaAb", + "Acab", + 10 + ], + [ + "caB", + "CbAcacAa", + 12 + ], + [ + "caB", + "ccBA", + 4 + ], + [ + "caBAA", + "aCbc", + 8 + ], + [ + "caBABbbC", + "CB", + 13 + ], + [ + "caBAabAcC", + "aCA", + 14 + ], + [ + "caBAbAAc", + "bcCBBa", + 12 + ], + [ + "caBAbaAb", + "ba", + 12 + ], + [ + "caBAcB", + "BaaaBA", + 9 + ], + [ + "caBBA", + "Bc", + 8 + ], + [ + "caBBA", + "CacB", + 5 + ], + [ + "caBBaBAB", + "acAbaa", + 11 + ], + [ + "caBBbaaA", + "bB", + 13 + ], + [ + "caBC", + "CBaaBaAa", + 11 + ], + [ + "caBCBaBC", + "aABaB", + 8 + ], + [ + "caBCac", + "b", + 11 + ], + [ + "caBCc", + "CBCabB", + 9 + ], + [ + "caBa", + "CaBabAC", + 7 + ], + [ + "caBa", + "CcbccA", + 9 + ], + [ + "caBaB", + "BcA", + 8 + ], + [ + "caBaCAb", + "AacCAA", + 8 + ], + [ + "caBaCc", + "cCCA", + 8 + ], + [ + "caBb", + "AaCbCAAa", + 12 + ], + [ + "caBb", + "BCBC", + 6 + ], + [ + "caBb", + "b", + 6 + ], + [ + "caBbCaa", + "caCCbb", + 8 + ], + [ + "caBbCbbBB", + "aBCBCabca", + 11 + ], + [ + "caBbCcBC", + "cccBaB", + 11 + ], + [ + "caBbac", + "bac", + 6 + ], + [ + "caBbbB", + "BcBBA", + 9 + ], + [ + "caBbbcBa", + "b", + 14 + ], + [ + "caBc", + "bA", + 7 + ], + [ + "caBc", + "bBA", + 6 + ], + [ + "caBc", + "cc", + 4 + ], + [ + "caBcAA", + "ccacac", + 7 + ], + [ + "caBcacCb", + "bBc", + 12 + ], + [ + "caC", + "BCbb", + 7 + ], + [ + "caC", + "BbBcA", + 9 + ], + [ + "caC", + "babCacB", + 10 + ], + [ + "caC", + "bb", + 6 + ], + [ + "caC", + "cCbAaa", + 8 + ], + [ + "caCAB", + "CBA", + 7 + ], + [ + "caCAC", + "AcaaCaacc", + 10 + ], + [ + "caCAb", + "BaC", + 6 + ], + [ + "caCAccca", + "bACc", + 11 + ], + [ + "caCBA", + "aBBBBcA", + 10 + ], + [ + "caCBC", + "BcBBabA", + 11 + ], + [ + "caCBC", + "ac", + 7 + ], + [ + "caCBba", + "cBA", + 7 + ], + [ + "caCBbaBB", + "a", + 14 + ], + [ + "caCBbc", + "A", + 11 + ], + [ + "caCC", + "CaBC", + 3 + ], + [ + "caCCAa", + "Baabb", + 10 + ], + [ + "caCCAcaa", + "aC", + 12 + ], + [ + "caCCC", + "bCBaAAbC", + 11 + ], + [ + "caCCaa", + "acabCacA", + 7 + ], + [ + "caCCbCc", + "aCBcC", + 7 + ], + [ + "caCCcc", + "cbaCAacc", + 6 + ], + [ + "caCaBB", + "ccbBaBA", + 8 + ], + [ + "caCaBbcAA", + "baCcAB", + 10 + ], + [ + "caCaCAaaC", + "ABB", + 16 + ], + [ + "caCabcBa", + "CAcCABcc", + 10 + ], + [ + "caCb", + "BcAcABAB", + 11 + ], + [ + "caCb", + "bAbBCb", + 7 + ], + [ + "caCbAAcb", + "aaBbAB", + 9 + ], + [ + "caCbCBBb", + "A", + 15 + ], + [ + "caCbbC", + "cCcc", + 7 + ], + [ + "caCbbcbC", + "CBAAbCC", + 10 + ], + [ + "caCbc", + "B", + 9 + ], + [ + "caCcCaaB", + "AacCbcca", + 11 + ], + [ + "caa", + "CCAcAcaab", + 12 + ], + [ + "caa", + "b", + 6 + ], + [ + "caa", + "bAB", + 5 + ], + [ + "caa", + "bacAa", + 5 + ], + [ + "caaA", + "BaCbcC", + 10 + ], + [ + "caaAABaac", + "AC", + 15 + ], + [ + "caaACA", + "cB", + 10 + ], + [ + "caaAa", + "CaBaAbcB", + 9 + ], + [ + "caaAa", + "bbC", + 10 + ], + [ + "caaAbbc", + "Aa", + 11 + ], + [ + "caaB", + "bAc", + 7 + ], + [ + "caaB", + "cB", + 4 + ], + [ + "caaBA", + "C", + 9 + ], + [ + "caaBAabC", + "BACB", + 11 + ], + [ + "caaBCC", + "Ab", + 10 + ], + [ + "caaBCc", + "CCb", + 9 + ], + [ + "caaCCAa", + "bCccbA", + 11 + ], + [ + "caaCaBcBb", + "aCabaa", + 11 + ], + [ + "caaCbaB", + "CCc", + 11 + ], + [ + "caaCc", + "b", + 10 + ], + [ + "caaCcc", + "cbA", + 9 + ], + [ + "caaa", + "AcCc", + 8 + ], + [ + "caaa", + "bCabaCaa", + 9 + ], + [ + "caaaCb", + "AabC", + 7 + ], + [ + "caaaaC", + "CaaBCCaC", + 7 + ], + [ + "caaab", + "BCC", + 10 + ], + [ + "caaac", + "AaBbACcBa", + 13 + ], + [ + "caab", + "C", + 7 + ], + [ + "caabACbb", + "bb", + 12 + ], + [ + "caabB", + "AbaCbac", + 10 + ], + [ + "caabaABA", + "cbacccaA", + 10 + ], + [ + "caabcbcBB", + "abaAAaC", + 14 + ], + [ + "caac", + "ABb", + 7 + ], + [ + "caacAABaB", + "CbBcbaB", + 10 + ], + [ + "caacaccC", + "BAaccaBA", + 11 + ], + [ + "caacbaAc", + "Abccbc", + 10 + ], + [ + "cab", + "CB", + 4 + ], + [ + "cab", + "a", + 4 + ], + [ + "cab", + "abCCb", + 7 + ], + [ + "cab", + "bAaaBBA", + 11 + ], + [ + "cab", + "bBbCABC", + 11 + ], + [ + "cabAA", + "c", + 8 + ], + [ + "cabACCCCb", + "b", + 16 + ], + [ + "cabACc", + "bBBAb", + 9 + ], + [ + "cabBAaaB", + "BbCCBaBc", + 12 + ], + [ + "cabBC", + "A", + 9 + ], + [ + "cabBCa", + "C", + 10 + ], + [ + "cabBCcBbA", + "BbCbAAaAb", + 16 + ], + [ + "cabBaA", + "cCa", + 8 + ], + [ + "cabC", + "BBCabBCa", + 9 + ], + [ + "cabC", + "BCBb", + 7 + ], + [ + "cabC", + "Baccb", + 7 + ], + [ + "cabCCAcC", + "cCcA", + 9 + ], + [ + "cabCCaBca", + "BCbBc", + 11 + ], + [ + "cabCaba", + "a", + 12 + ], + [ + "cabCb", + "cB", + 7 + ], + [ + "cabCcbB", + "BBbAcBaac", + 13 + ], + [ + "cabaBBb", + "AbC", + 11 + ], + [ + "cabaa", + "ccBCAbAB", + 10 + ], + [ + "cababBBaB", + "AcBCAC", + 14 + ], + [ + "cabac", + "BCa", + 8 + ], + [ + "cabb", + "CACcCcac", + 14 + ], + [ + "cabb", + "a", + 6 + ], + [ + "cabbBBA", + "CCab", + 11 + ], + [ + "cabbBc", + "aCccAAcc", + 12 + ], + [ + "cabbbACA", + "bcaCC", + 11 + ], + [ + "cabc", + "BCBcBca", + 10 + ], + [ + "cabc", + "CaaBBAABA", + 14 + ], + [ + "cabcBCc", + "BABAC", + 10 + ], + [ + "cabca", + "aAaC", + 8 + ], + [ + "cac", + "BBbaabba", + 14 + ], + [ + "cac", + "bb", + 6 + ], + [ + "cac", + "bcBa", + 6 + ], + [ + "cac", + "cBaaBa", + 8 + ], + [ + "cacABBaB", + "BaBAabBbA", + 11 + ], + [ + "cacAaA", + "bc", + 10 + ], + [ + "cacAaaaBb", + "Aba", + 14 + ], + [ + "cacAbbcCB", + "AcCcAaBC", + 11 + ], + [ + "cacAc", + "cAcaAB", + 5 + ], + [ + "cacB", + "BCcbAAcbB", + 11 + ], + [ + "cacB", + "c", + 6 + ], + [ + "cacBAA", + "BbbCCab", + 12 + ], + [ + "cacBAc", + "bbaBB", + 10 + ], + [ + "cacBaAa", + "aBBBCbbbA", + 15 + ], + [ + "cacBab", + "AC", + 10 + ], + [ + "cacCCaB", + "ABCc", + 10 + ], + [ + "caca", + "bCbbAa", + 9 + ], + [ + "cacaAbAAA", + "bc", + 16 + ], + [ + "cacaAcc", + "bc", + 12 + ], + [ + "cacaBc", + "BaabCbbB", + 12 + ], + [ + "cacaaBc", + "caAacCAAa", + 11 + ], + [ + "cacaabBCa", + "AACaccAc", + 13 + ], + [ + "cacacBAbC", + "C", + 16 + ], + [ + "cacaca", + "aB", + 10 + ], + [ + "cacbAAaCa", + "b", + 16 + ], + [ + "cacbB", + "AbBaCB", + 9 + ], + [ + "cacbCcbcB", + "cc", + 14 + ], + [ + "cacbc", + "BbAACAAC", + 13 + ], + [ + "cacc", + "CAccbBacC", + 11 + ], + [ + "caccA", + "ccc", + 4 + ], + [ + "caccbc", + "ab", + 8 + ], + [ + "cb", + "AAaBCAa", + 13 + ], + [ + "cb", + "AAaC", + 8 + ], + [ + "cb", + "ABAcbc", + 8 + ], + [ + "cb", + "ABccA", + 8 + ], + [ + "cb", + "ACABcb", + 8 + ], + [ + "cb", + "Aa", + 4 + ], + [ + "cb", + "AbBAaB", + 10 + ], + [ + "cb", + "BCcbbACB", + 12 + ], + [ + "cb", + "BabCaAAB", + 14 + ], + [ + "cb", + "BbBCACCBb", + 15 + ], + [ + "cb", + "C", + 3 + ], + [ + "cb", + "CAAbCCB", + 11 + ], + [ + "cb", + "CABBCa", + 10 + ], + [ + "cb", + "CCACAAB", + 12 + ], + [ + "cb", + "aBcA", + 6 + ], + [ + "cb", + "aCBAaabaa", + 15 + ], + [ + "cb", + "aCBaacAac", + 16 + ], + [ + "cb", + "aCC", + 5 + ], + [ + "cb", + "aaBcCC", + 10 + ], + [ + "cb", + "acBAC", + 7 + ], + [ + "cb", + "bCBcaCbA", + 12 + ], + [ + "cb", + "bcCCC", + 8 + ], + [ + "cb", + "cBCaBCC", + 11 + ], + [ + "cb", + "cCabBBabA", + 14 + ], + [ + "cb", + "cb", + 0 + ], + [ + "cb", + "cccCa", + 8 + ], + [ + "cbA", + "AaAaB", + 8 + ], + [ + "cbA", + "AcACCa", + 9 + ], + [ + "cbA", + "BbCBABAA", + 12 + ], + [ + "cbA", + "aBcCCAAca", + 14 + ], + [ + "cbA", + "aaab", + 7 + ], + [ + "cbAA", + "BAbBc", + 8 + ], + [ + "cbAAaBcc", + "cABABCbb", + 10 + ], + [ + "cbAAcB", + "a", + 11 + ], + [ + "cbAAcC", + "cacC", + 5 + ], + [ + "cbAB", + "CAABa", + 5 + ], + [ + "cbABBb", + "acBA", + 9 + ], + [ + "cbABc", + "cbcAaCb", + 7 + ], + [ + "cbAC", + "C", + 6 + ], + [ + "cbACAbc", + "aABCAbA", + 8 + ], + [ + "cbACcAC", + "bbcAcbB", + 10 + ], + [ + "cbACcBBC", + "cABbcbbaB", + 12 + ], + [ + "cbACcb", + "cabbaAC", + 10 + ], + [ + "cbAaB", + "babCC", + 9 + ], + [ + "cbAaBc", + "Acc", + 8 + ], + [ + "cbAaBcCA", + "C", + 14 + ], + [ + "cbAaCBbB", + "A", + 14 + ], + [ + "cbAabcC", + "BBBCAc", + 11 + ], + [ + "cbAbAaBbc", + "bC", + 15 + ], + [ + "cbAbBBAA", + "bcaBbAc", + 9 + ], + [ + "cbAbCBA", + "acABcaC", + 10 + ], + [ + "cbAbCBBB", + "AAaaa", + 14 + ], + [ + "cbAbCaA", + "cbAcBB", + 7 + ], + [ + "cbAbaCc", + "BACabcaa", + 11 + ], + [ + "cbAbcCA", + "ccC", + 8 + ], + [ + "cbAbcaB", + "cc", + 10 + ], + [ + "cbAbcbAbB", + "AccBbbcA", + 13 + ], + [ + "cbAbcbb", + "caCaAB", + 10 + ], + [ + "cbAc", + "BABcCB", + 9 + ], + [ + "cbAc", + "bacb", + 5 + ], + [ + "cbAcCBb", + "ABac", + 10 + ], + [ + "cbAcbcccB", + "CCC", + 15 + ], + [ + "cbB", + "Aaa", + 6 + ], + [ + "cbB", + "CbC", + 3 + ], + [ + "cbB", + "caCaB", + 6 + ], + [ + "cbBA", + "BcBBccBA", + 9 + ], + [ + "cbBA", + "aCcbB", + 6 + ], + [ + "cbBAAc", + "bcABA", + 8 + ], + [ + "cbBAB", + "AbcBc", + 8 + ], + [ + "cbBABc", + "Cbba", + 7 + ], + [ + "cbBACACa", + "aA", + 13 + ], + [ + "cbBACBccA", + "Ca", + 15 + ], + [ + "cbBAba", + "AcAca", + 8 + ], + [ + "cbBAbb", + "CbaaC", + 8 + ], + [ + "cbBB", + "cAb", + 5 + ], + [ + "cbBB", + "cAba", + 5 + ], + [ + "cbBBbB", + "BBBBcaA", + 9 + ], + [ + "cbBBbca", + "cACABCb", + 10 + ], + [ + "cbBBcACBb", + "AACbBbbb", + 13 + ], + [ + "cbBCCaA", + "AccCcBc", + 11 + ], + [ + "cbBCacA", + "cB", + 10 + ], + [ + "cbBCb", + "CAAbBA", + 9 + ], + [ + "cbBa", + "aaCC", + 8 + ], + [ + "cbBa", + "cBaB", + 4 + ], + [ + "cbBa", + "cccB", + 6 + ], + [ + "cbBaBcAc", + "Aab", + 13 + ], + [ + "cbBaCAC", + "CCcCCc", + 10 + ], + [ + "cbBac", + "c", + 8 + ], + [ + "cbBacA", + "bCaaaBaa", + 12 + ], + [ + "cbBb", + "AABA", + 6 + ], + [ + "cbBb", + "CCaa", + 7 + ], + [ + "cbBbAbB", + "cC", + 12 + ], + [ + "cbBbCACCC", + "Ccc", + 14 + ], + [ + "cbBba", + "ccb", + 6 + ], + [ + "cbBbbb", + "BccCbaAAB", + 13 + ], + [ + "cbBc", + "A", + 8 + ], + [ + "cbBcCAa", + "acab", + 11 + ], + [ + "cbBcCCbAA", + "caAbaCaBc", + 14 + ], + [ + "cbBcaCB", + "bA", + 11 + ], + [ + "cbBcbaccC", + "CaAACBAAA", + 16 + ], + [ + "cbBcbc", + "ABBBAAc", + 9 + ], + [ + "cbBcc", + "CACaBC", + 10 + ], + [ + "cbC", + "AcABa", + 7 + ], + [ + "cbC", + "bCCBBa", + 10 + ], + [ + "cbCAbaAa", + "ccBCaC", + 11 + ], + [ + "cbCB", + "AABCCaaA", + 13 + ], + [ + "cbCBABAAb", + "a", + 17 + ], + [ + "cbCBAcacb", + "CAa", + 12 + ], + [ + "cbCBC", + "cbcaCaaba", + 11 + ], + [ + "cbCBccbcc", + "BcCbA", + 11 + ], + [ + "cbCC", + "B", + 7 + ], + [ + "cbCCBBCB", + "baBaCbC", + 11 + ], + [ + "cbCCBccBb", + "BaAaC", + 16 + ], + [ + "cbCCC", + "AACACB", + 8 + ], + [ + "cbCCbABBB", + "CcaABC", + 11 + ], + [ + "cbCCbBac", + "CAaA", + 12 + ], + [ + "cbCa", + "CBA", + 5 + ], + [ + "cbCa", + "bbcacb", + 7 + ], + [ + "cbCaB", + "cbBaCb", + 5 + ], + [ + "cbCbAaCCa", + "ACAAb", + 13 + ], + [ + "cbCbaC", + "BACcBC", + 8 + ], + [ + "cbCbaCcaC", + "AaaaBC", + 14 + ], + [ + "cbCbb", + "A", + 10 + ], + [ + "cbCbbCAAc", + "caccc", + 12 + ], + [ + "cbCbcC", + "B", + 11 + ], + [ + "cbCcAAcA", + "AcaAaCcCa", + 13 + ], + [ + "cbCcCAc", + "babCC", + 9 + ], + [ + "cbCcCB", + "BCABA", + 9 + ], + [ + "cbCcCbA", + "cB", + 11 + ], + [ + "cbCcb", + "AacBB", + 8 + ], + [ + "cbCcbca", + "BCB", + 10 + ], + [ + "cbCccca", + "AAA", + 13 + ], + [ + "cba", + "A", + 5 + ], + [ + "cba", + "b", + 4 + ], + [ + "cba", + "bBCaaCc", + 11 + ], + [ + "cba", + "cAAbc", + 6 + ], + [ + "cba", + "caABABbab", + 12 + ], + [ + "cba", + "ccAB", + 5 + ], + [ + "cbaAa", + "cBbbcB", + 8 + ], + [ + "cbaAc", + "cAAc", + 3 + ], + [ + "cbaBACBAc", + "a", + 16 + ], + [ + "cbaBCAAC", + "BAAcCc", + 12 + ], + [ + "cbaBCbbcC", + "BcAaabac", + 12 + ], + [ + "cbaBbCa", + "BBACcA", + 10 + ], + [ + "cbaC", + "BBCaACabc", + 13 + ], + [ + "cbaC", + "aaA", + 6 + ], + [ + "cbaCABA", + "BbAaBccBC", + 11 + ], + [ + "cbaCCA", + "cbCABA", + 6 + ], + [ + "cbaCCCa", + "a", + 12 + ], + [ + "cbaCacac", + "AcBBbAA", + 13 + ], + [ + "cbaCcaA", + "C", + 12 + ], + [ + "cbaa", + "aaBcCBcBa", + 13 + ], + [ + "cbaaA", + "cBaa", + 3 + ], + [ + "cbaabCcC", + "bB", + 13 + ], + [ + "cbabAA", + "Bc", + 11 + ], + [ + "cbabBbc", + "AbcacAC", + 11 + ], + [ + "cbabC", + "CBbaAa", + 7 + ], + [ + "cbabbC", + "aCacAcBAC", + 13 + ], + [ + "cbac", + "cCbBcACa", + 10 + ], + [ + "cbacAAAA", + "BcAbcAbc", + 12 + ], + [ + "cbacAAacc", + "ab", + 16 + ], + [ + "cbacAC", + "BaaABAbC", + 10 + ], + [ + "cbacACa", + "AcBbcBaC", + 10 + ], + [ + "cbacB", + "CaBAa", + 9 + ], + [ + "cbacCCab", + "Acbc", + 12 + ], + [ + "cbacCabBB", + "CCcc", + 14 + ], + [ + "cbb", + "BBbB", + 5 + ], + [ + "cbb", + "CcAaAC", + 10 + ], + [ + "cbb", + "bBcABAcCC", + 15 + ], + [ + "cbb", + "cbccAbA", + 8 + ], + [ + "cbbABaCBa", + "Ca", + 14 + ], + [ + "cbbAa", + "aBBcAa", + 6 + ], + [ + "cbbAaC", + "cbc", + 7 + ], + [ + "cbbAbB", + "BABaBA", + 9 + ], + [ + "cbbAbaaB", + "CCababBa", + 10 + ], + [ + "cbbBAC", + "AacCcb", + 12 + ], + [ + "cbbBbA", + "AbCAACc", + 12 + ], + [ + "cbbBbb", + "b", + 10 + ], + [ + "cbbBbbbCA", + "bBB", + 13 + ], + [ + "cbbBcBbBb", + "BaABc", + 14 + ], + [ + "cbbBcC", + "C", + 10 + ], + [ + "cbbCAaB", + "A", + 12 + ], + [ + "cbbCbC", + "cBaCCABb", + 10 + ], + [ + "cbbCcbA", + "baCBaBab", + 12 + ], + [ + "cbbaCA", + "aCAbbbCcA", + 9 + ], + [ + "cbbaCb", + "ABaCaB", + 8 + ], + [ + "cbbaaC", + "BcAAbAba", + 11 + ], + [ + "cbbabc", + "BaAaacCAc", + 14 + ], + [ + "cbbacB", + "b", + 10 + ], + [ + "cbbb", + "CC", + 7 + ], + [ + "cbbb", + "bBcCaCAC", + 14 + ], + [ + "cbbbB", + "abacb", + 7 + ], + [ + "cbbbBBcb", + "cA", + 14 + ], + [ + "cbbbaBbC", + "CbAABAC", + 8 + ], + [ + "cbbbc", + "c", + 8 + ], + [ + "cbbc", + "aCBAcAc", + 10 + ], + [ + "cbbc", + "abBBCAB", + 10 + ], + [ + "cbbcBC", + "BAB", + 9 + ], + [ + "cbbcBcCCb", + "bc", + 14 + ], + [ + "cbc", + "AACAAbCCB", + 14 + ], + [ + "cbc", + "BcbaA", + 6 + ], + [ + "cbc", + "CbBbACB", + 10 + ], + [ + "cbc", + "b", + 4 + ], + [ + "cbc", + "cBCcBaC", + 9 + ], + [ + "cbcA", + "ABBAcC", + 9 + ], + [ + "cbcAA", + "c", + 8 + ], + [ + "cbcACAabb", + "bccBcbAaA", + 13 + ], + [ + "cbcAaAAb", + "BBccBbCA", + 13 + ], + [ + "cbcAb", + "CCCbbbcba", + 13 + ], + [ + "cbcB", + "Aba", + 6 + ], + [ + "cbcB", + "bCaaaAba", + 14 + ], + [ + "cbcBacB", + "acbB", + 9 + ], + [ + "cbcBbb", + "cBa", + 8 + ], + [ + "cbcBcc", + "bbCcA", + 7 + ], + [ + "cbcC", + "aABacCCC", + 11 + ], + [ + "cbcCA", + "bBAaba", + 10 + ], + [ + "cbcCBcbc", + "acBa", + 12 + ], + [ + "cbcCcBa", + "CbbACa", + 8 + ], + [ + "cbcaB", + "bCaAAc", + 9 + ], + [ + "cbcabBAac", + "bcBCbCBb", + 13 + ], + [ + "cbcb", + "bba", + 6 + ], + [ + "cbcbCCA", + "AaaCCabcc", + 15 + ], + [ + "cbcbaCBb", + "BccCAb", + 9 + ], + [ + "cbcbbC", + "BAaa", + 11 + ], + [ + "cbcbcaCC", + "BaBbbB", + 14 + ], + [ + "cbcccaCc", + "acAAAa", + 13 + ], + [ + "cc", + "AAAbBbC", + 13 + ], + [ + "cc", + "ABBaccbbB", + 14 + ], + [ + "cc", + "ABa", + 6 + ], + [ + "cc", + "ABaA", + 8 + ], + [ + "cc", + "BAbbAab", + 14 + ], + [ + "cc", + "BAbc", + 6 + ], + [ + "cc", + "BBacCb", + 9 + ], + [ + "cc", + "BCbaB", + 9 + ], + [ + "cc", + "BaBcBAAc", + 12 + ], + [ + "cc", + "BaC", + 5 + ], + [ + "cc", + "Bbca", + 6 + ], + [ + "cc", + "CAbbcb", + 9 + ], + [ + "cc", + "CCAcCb", + 9 + ], + [ + "cc", + "Ccb", + 3 + ], + [ + "cc", + "aAaBCaA", + 13 + ], + [ + "cc", + "aB", + 4 + ], + [ + "cc", + "aBA", + 6 + ], + [ + "cc", + "acCcCabA", + 12 + ], + [ + "cc", + "b", + 4 + ], + [ + "cc", + "bACABABA", + 15 + ], + [ + "cc", + "baCaAAAc", + 13 + ], + [ + "cc", + "bacAbacB", + 12 + ], + [ + "cc", + "bcbA", + 6 + ], + [ + "cc", + "cABcAA", + 8 + ], + [ + "cc", + "cACac", + 6 + ], + [ + "cc", + "cAbba", + 8 + ], + [ + "cc", + "cB", + 2 + ], + [ + "cc", + "cCac", + 4 + ], + [ + "cc", + "cCbbAcaA", + 12 + ], + [ + "cc", + "cb", + 2 + ], + [ + "cc", + "ccBc", + 4 + ], + [ + "cc", + "ccCab", + 6 + ], + [ + "ccA", + "AcCccAcc", + 10 + ], + [ + "ccA", + "CBAaC", + 7 + ], + [ + "ccA", + "b", + 6 + ], + [ + "ccAABB", + "ccCBBbC", + 7 + ], + [ + "ccAAb", + "BaABC", + 8 + ], + [ + "ccAAbaA", + "BaA", + 9 + ], + [ + "ccAAbbbaB", + "AABBCc", + 12 + ], + [ + "ccAB", + "BcA", + 4 + ], + [ + "ccABA", + "BcBBcbBA", + 8 + ], + [ + "ccABBAA", + "bCCac", + 12 + ], + [ + "ccABcAA", + "AABBaBaA", + 11 + ], + [ + "ccAC", + "CAACBCaCA", + 13 + ], + [ + "ccAC", + "bA", + 6 + ], + [ + "ccACAAcb", + "AbabCa", + 12 + ], + [ + "ccACABbAc", + "BCbAb", + 12 + ], + [ + "ccACB", + "CBbabcAC", + 11 + ], + [ + "ccACBAaBa", + "ca", + 14 + ], + [ + "ccACBca", + "Cb", + 11 + ], + [ + "ccACC", + "CcaAba", + 7 + ], + [ + "ccACC", + "aCc", + 6 + ], + [ + "ccACaABcb", + "CBBCCABCc", + 10 + ], + [ + "ccACaBbAC", + "cBaAaB", + 11 + ], + [ + "ccACcAAB", + "AbCbaCAbb", + 13 + ], + [ + "ccACcbb", + "abCcBCb", + 9 + ], + [ + "ccAa", + "bca", + 4 + ], + [ + "ccAa", + "c", + 6 + ], + [ + "ccAaACB", + "BCabaaA", + 11 + ], + [ + "ccAaAbccA", + "AAbAAb", + 12 + ], + [ + "ccAaC", + "bAaaACAB", + 11 + ], + [ + "ccAcAC", + "c", + 10 + ], + [ + "ccAcAb", + "AbABBCbBA", + 14 + ], + [ + "ccAcb", + "bcAb", + 4 + ], + [ + "ccAcccc", + "ccCca", + 7 + ], + [ + "ccB", + "B", + 4 + ], + [ + "ccB", + "CcBAB", + 5 + ], + [ + "ccB", + "aAa", + 6 + ], + [ + "ccB", + "b", + 5 + ], + [ + "ccB", + "cAaAbaa", + 11 + ], + [ + "ccB", + "cBbCACaAB", + 13 + ], + [ + "ccBA", + "B", + 6 + ], + [ + "ccBA", + "CAac", + 7 + ], + [ + "ccBACbca", + "Abb", + 12 + ], + [ + "ccBAc", + "baaaCaaB", + 14 + ], + [ + "ccBB", + "BcC", + 6 + ], + [ + "ccBBA", + "BbACCaA", + 11 + ], + [ + "ccBBbAa", + "b", + 12 + ], + [ + "ccBBbb", + "cBbBb", + 4 + ], + [ + "ccBBbcC", + "CAbacA", + 10 + ], + [ + "ccBC", + "AaBAA", + 8 + ], + [ + "ccBC", + "Baba", + 7 + ], + [ + "ccBC", + "b", + 7 + ], + [ + "ccBC", + "cbba", + 5 + ], + [ + "ccBCAaBc", + "bBCCCAA", + 12 + ], + [ + "ccBCAbC", + "abC", + 9 + ], + [ + "ccBCBBcac", + "BCabBA", + 12 + ], + [ + "ccBCC", + "AbbC", + 7 + ], + [ + "ccBCCCa", + "BaCaB", + 10 + ], + [ + "ccBCCaBcB", + "AcC", + 14 + ], + [ + "ccBCCc", + "aBb", + 10 + ], + [ + "ccBCbBcC", + "ca", + 14 + ], + [ + "ccBCcCaA", + "bcbBAcaBA", + 10 + ], + [ + "ccBa", + "ACCaABcCa", + 12 + ], + [ + "ccBaC", + "AC", + 7 + ], + [ + "ccBaaAa", + "Cc", + 11 + ], + [ + "ccBab", + "BACC", + 9 + ], + [ + "ccBabcaBA", + "CBbc", + 11 + ], + [ + "ccBacCAbB", + "cCCcA", + 11 + ], + [ + "ccBbAABB", + "ccb", + 10 + ], + [ + "ccBbAaB", + "Cc", + 11 + ], + [ + "ccBbaCAb", + "Bcc", + 13 + ], + [ + "ccBbab", + "cCbBc", + 7 + ], + [ + "ccBbbbcB", + "Aacaaa", + 16 + ], + [ + "ccBcb", + "bbcACCb", + 9 + ], + [ + "ccC", + "Ab", + 6 + ], + [ + "ccC", + "CBcCaAbAc", + 13 + ], + [ + "ccC", + "aaCB", + 6 + ], + [ + "ccC", + "bBBAA", + 10 + ], + [ + "ccCAA", + "aCC", + 7 + ], + [ + "ccCAcCB", + "baAAbBac", + 14 + ], + [ + "ccCBAa", + "AABbcA", + 10 + ], + [ + "ccCBCc", + "caBcB", + 7 + ], + [ + "ccCBbC", + "BbbA", + 9 + ], + [ + "ccCC", + "A", + 8 + ], + [ + "ccCC", + "CCaBcACBC", + 11 + ], + [ + "ccCC", + "aab", + 8 + ], + [ + "ccCCAaa", + "B", + 14 + ], + [ + "ccCCBAaaC", + "Bb", + 16 + ], + [ + "ccCCBbCaA", + "AcACCaB", + 10 + ], + [ + "ccCCCaaCb", + "BaAbBB", + 16 + ], + [ + "ccCCacA", + "ACAAa", + 10 + ], + [ + "ccCa", + "acbBa", + 6 + ], + [ + "ccCaa", + "aCBCa", + 7 + ], + [ + "ccCab", + "CCAb", + 4 + ], + [ + "ccCbBB", + "AAcabCa", + 10 + ], + [ + "ccCba", + "aacAbCBb", + 11 + ], + [ + "ccCbbCBA", + "AaCBcAb", + 12 + ], + [ + "ccCbc", + "aCbBCcb", + 10 + ], + [ + "ccCbcCcA", + "aAA", + 14 + ], + [ + "ccCbcaaAC", + "abB", + 16 + ], + [ + "ccCcAbCA", + "AB", + 13 + ], + [ + "ccCcAccA", + "CCABcCCbc", + 13 + ], + [ + "ccCcBaA", + "caC", + 10 + ], + [ + "ccCcBbc", + "aaacAca", + 12 + ], + [ + "ccCcBcC", + "CBCCCBAA", + 9 + ], + [ + "ccCcabcb", + "baAb", + 12 + ], + [ + "ccCccbABc", + "b", + 16 + ], + [ + "cca", + "ABc", + 6 + ], + [ + "cca", + "aa", + 4 + ], + [ + "cca", + "bACA", + 6 + ], + [ + "ccaA", + "AcBa", + 5 + ], + [ + "ccaA", + "Ca", + 5 + ], + [ + "ccaABaccb", + "AAaaCBb", + 10 + ], + [ + "ccaACAC", + "BAc", + 11 + ], + [ + "ccaAba", + "Ccb", + 7 + ], + [ + "ccaAc", + "B", + 10 + ], + [ + "ccaAcCB", + "ccBB", + 8 + ], + [ + "ccaB", + "BbcB", + 6 + ], + [ + "ccaBC", + "CbbbB", + 8 + ], + [ + "ccaCA", + "ABBbb", + 10 + ], + [ + "ccaCAB", + "cCbcb", + 7 + ], + [ + "ccaCAcAB", + "acbb", + 11 + ], + [ + "ccaCAcBb", + "ccCbb", + 7 + ], + [ + "ccaCCCcCC", + "AACAc", + 13 + ], + [ + "ccaCaABb", + "bA", + 14 + ], + [ + "ccaCc", + "babb", + 8 + ], + [ + "ccaCcAAaB", + "BcAAaB", + 8 + ], + [ + "ccaCcB", + "B", + 10 + ], + [ + "ccaaBCB", + "AAA", + 12 + ], + [ + "ccaaaa", + "Aa", + 9 + ], + [ + "ccaab", + "acbbC", + 8 + ], + [ + "ccaac", + "BCBBb", + 9 + ], + [ + "ccab", + "C", + 7 + ], + [ + "ccab", + "aabBBcABa", + 14 + ], + [ + "ccabaB", + "CACba", + 7 + ], + [ + "ccabaCa", + "ccAac", + 6 + ], + [ + "ccababcA", + "abc", + 10 + ], + [ + "ccacAbBBB", + "Cb", + 15 + ], + [ + "ccacb", + "cbCA", + 7 + ], + [ + "ccb", + "A", + 6 + ], + [ + "ccb", + "Aa", + 6 + ], + [ + "ccb", + "Aca", + 4 + ], + [ + "ccb", + "acBAcb", + 6 + ], + [ + "ccb", + "acBccbAcA", + 12 + ], + [ + "ccbA", + "ba", + 5 + ], + [ + "ccbAAA", + "BAaca", + 9 + ], + [ + "ccbAACAc", + "CaaCBcBAa", + 14 + ], + [ + "ccbABAA", + "BBaccbb", + 13 + ], + [ + "ccbACa", + "cabACc", + 4 + ], + [ + "ccbAaCA", + "cCccaCCA", + 7 + ], + [ + "ccbAb", + "bbbCaACa", + 12 + ], + [ + "ccbAbA", + "cbcaBb", + 8 + ], + [ + "ccbAbBB", + "cBcbA", + 8 + ], + [ + "ccbAcC", + "AbBCcaacB", + 12 + ], + [ + "ccbBbcb", + "bCbCAC", + 10 + ], + [ + "ccbC", + "ACccBAc", + 8 + ], + [ + "ccbC", + "CB", + 6 + ], + [ + "ccbC", + "aCAA", + 7 + ], + [ + "ccbCC", + "AcCcCcb", + 8 + ], + [ + "ccbCa", + "bcBBcb", + 8 + ], + [ + "ccbCaACca", + "BBcaA", + 12 + ], + [ + "ccbCbbB", + "b", + 12 + ], + [ + "ccba", + "CAbbBc", + 9 + ], + [ + "ccba", + "Caa", + 5 + ], + [ + "ccba", + "bA", + 5 + ], + [ + "ccba", + "cbc", + 4 + ], + [ + "ccbabbC", + "AB", + 12 + ], + [ + "ccbbBbAb", + "CBc", + 13 + ], + [ + "ccbbabB", + "bCcaCa", + 11 + ], + [ + "ccbbcB", + "ACbcaaA", + 11 + ], + [ + "ccbbccCAC", + "CcccBcBC", + 10 + ], + [ + "ccbcABBCb", + "aAcAacC", + 12 + ], + [ + "ccbcAbBbc", + "a", + 17 + ], + [ + "ccbcB", + "CBaCAAcBc", + 12 + ], + [ + "ccbcBBAbB", + "cBccCc", + 13 + ], + [ + "ccbcCaab", + "cCaAAB", + 10 + ], + [ + "ccbcCbcB", + "CCCa", + 12 + ], + [ + "ccbcba", + "CA", + 10 + ], + [ + "ccc", + "AcBcbBcb", + 10 + ], + [ + "ccc", + "BbcCbB", + 9 + ], + [ + "ccc", + "CACABCbb", + 13 + ], + [ + "ccc", + "ac", + 4 + ], + [ + "ccc", + "baAABCbcc", + 13 + ], + [ + "ccc", + "c", + 4 + ], + [ + "ccc", + "cabACBAbB", + 15 + ], + [ + "cccA", + "cbBAbbB", + 10 + ], + [ + "cccAAA", + "AcB", + 10 + ], + [ + "cccAABCcA", + "ba", + 16 + ], + [ + "cccAC", + "ABCaa", + 8 + ], + [ + "cccAaccc", + "bcCC", + 12 + ], + [ + "cccAbC", + "cBbCAb", + 7 + ], + [ + "cccB", + "bACBcb", + 8 + ], + [ + "cccB", + "c", + 6 + ], + [ + "cccBAA", + "cbB", + 8 + ], + [ + "cccBAbb", + "bCCacb", + 9 + ], + [ + "cccBBAC", + "bbbcB", + 12 + ], + [ + "cccBBCc", + "CAaaAb", + 13 + ], + [ + "cccC", + "ACbB", + 7 + ], + [ + "cccC", + "bbbA", + 8 + ], + [ + "cccCabBA", + "AaBc", + 12 + ], + [ + "cccCbbcc", + "CcC", + 11 + ], + [ + "cccCccaC", + "b", + 16 + ], + [ + "ccca", + "cCcCAa", + 5 + ], + [ + "cccaAb", + "Abb", + 9 + ], + [ + "cccaCbA", + "cBcCBBbaA", + 9 + ], + [ + "cccaaa", + "BaABcbcca", + 14 + ], + [ + "cccacB", + "abBB", + 10 + ], + [ + "cccb", + "AABc", + 8 + ], + [ + "cccb", + "CbBAAbA", + 11 + ], + [ + "cccbABcc", + "a", + 15 + ], + [ + "cccbB", + "bcCAcaaba", + 11 + ], + [ + "cccbaBC", + "cbACAac", + 10 + ], + [ + "cccbabBb", + "ACc", + 13 + ], + [ + "cccbbA", + "bbcAc", + 10 + ], + [ + "cccbcaCC", + "AbCACBcCb", + 13 + ], + [ + "cccbcaaaC", + "baCcCc", + 14 + ], + [ + "ccccBa", + "abcbaaCbA", + 13 + ], + [ + "ccccCBcCA", + "Cbbab", + 15 + ], + [ + "ccccCCc", + "aabB", + 14 + ], + [ + "ccccaCA", + "Cb", + 12 + ], + [ + "cccccb", + "a", + 12 + ], + [ + "ccccccAcc", + "AB", + 16 + ] +] \ No newline at end of file diff --git a/Lib/test/libregrtest/cmdline.py b/Lib/test/libregrtest/cmdline.py index 2c404f6d80b..64c035307e6 100644 --- a/Lib/test/libregrtest/cmdline.py +++ b/Lib/test/libregrtest/cmdline.py @@ -15,73 +15,73 @@ Run Python regression tests. If no arguments or options are provided, finds all files matching -the pattern "test_*" in the Lib/test subdirectory and runs -them in alphabetical order (but see -M and -u, below, for exceptions). +the pattern `test_*` in the `Lib/test` subdirectory and runs +them in alphabetical order (but see `-M` and `-u`, below, for exceptions). For more rigorous testing, it is useful to use the following command line: -python -E -Wd -m test [options] [test_name1 ...] +`python -E -Wd -m test [options] [test_name1 ...]` """ EPILOG = """\ Additional option details: --r randomizes test execution order. You can use --randseed=int to provide an -int seed value for the randomizer. The randseed value will be used +`-r` randomizes test execution order. You can use `--randseed=int` to provide an +int seed value for the randomizer. The `randseed` value will be used to set seeds for all random usages in tests -(including randomizing the tests order if -r is set). +(including randomizing the tests order if `-r` is set). By default we always set random seed, but do not randomize test order. --s On the first invocation of regrtest using -s, the first test file found +`-s` On the first invocation of regrtest using `-s`, the first test file found or the first test file given on the command line is run, and the name of -the next test is recorded in a file named pynexttest. If run from the -Python build directory, pynexttest is located in the 'build' subdirectory, -otherwise it is located in tempfile.gettempdir(). On subsequent runs, -the test in pynexttest is run, and the next test is written to pynexttest. -When the last test has been run, pynexttest is deleted. In this way it +the next test is recorded in a file named `pynexttest`. If run from the +Python build directory, `pynexttest` is located in the 'build' subdirectory, +otherwise it is located in `tempfile.gettempdir()`. On subsequent runs, +the test in `pynexttest` is run, and the next test is written to `pynexttest`. +When the last test has been run, `pynexttest` is deleted. In this way it is possible to single step through the test files. This is useful when doing memory analysis on the Python interpreter, which process tends to consume too many resources to run the full regression test non-stop. --S is used to resume running tests after an interrupted run. It will -maintain the order a standard run (i.e. it assumes -r is not used). +`-S` is used to resume running tests after an interrupted run. It will +maintain the order a standard run (i.e. it assumes `-r` is not used). This is useful after the tests have prematurely stopped for some external reason and you want to resume the run from where you left off rather -than starting from the beginning. Note: this is different from --prioritize. +than starting from the beginning. Note: this is different from `--prioritize`. ---prioritize is used to influence the order of selected tests, such that +`--prioritize` is used to influence the order of selected tests, such that the tests listed as an argument are executed first. This is especially -useful when combined with -j and -r to pin the longest-running tests -to start at the beginning of a test run. Pass --prioritize=test_a,test_b -to make test_a run first, followed by test_b, and then the other tests. -If test_a wasn't selected for execution by regular means, --prioritize will +useful when combined with `-j` and `-r` to pin the longest-running tests +to start at the beginning of a test run. Pass `--prioritize=test_a,test_b` +to make `test_a` run first, followed by `test_b`, and then the other tests. +If test_a wasn't selected for execution by regular means, `--prioritize` will not make it execute. --f reads the names of tests from the file given as f's argument, one +`-f` reads the names of tests from the file given as `f`'s argument, one or more test names per line. Whitespace is ignored. Blank lines and -lines beginning with '#' are ignored. This is especially useful for +lines beginning with `#` are ignored. This is especially useful for whittling down failures involving interactions among tests. --L causes the leaks(1) command to be run just before exit if it exists. -leaks(1) is available on Mac OS X and presumably on some other +`-L` causes the leaks(1) command to be run just before exit if it exists. +leaks(1) is available on macOS and presumably on some other FreeBSD-derived systems. --R runs each test several times and examines sys.gettotalrefcount() to +`-R` runs each test several times and examines `sys.gettotalrefcount()` to see if the test appears to be leaking references. The argument should -be of the form stab:run:fname where 'stab' is the number of times the -test is run to let gettotalrefcount settle down, 'run' is the number -of times further it is run and 'fname' is the name of the file the -reports are written to. These parameters all have defaults (5, 4 and -"reflog.txt" respectively), and the minimal invocation is '-R :'. +be of the form `stab:run:fname` where `stab` is the number of times the +test is run to let gettotalrefcount settle down, `run` is the number +of times further it is run and `fname` is the name of the file the +reports are written to. These parameters all have defaults (`5`, `4` and +`"reflog.txt"` respectively), and the minimal invocation is `-R :`. --M runs tests that require an exorbitant amount of memory. These tests +`-M` runs tests that require an exorbitant amount of memory. These tests typically try to ascertain containers keep working when containing more than 2 billion objects, which only works on 64-bit systems. There are also some tests that try to exhaust the address space of the process, which only makes sense on 32-bit systems with at least 2Gb of memory. The passed-in memlimit, -which is a string in the form of '2.5Gb', determines how much memory the -tests will limit themselves to (but they may go slightly over.) The number +which is a string in the form of `'2.5Gb'`, determines how much memory the +tests will limit themselves to (but they may go slightly over). The number shouldn't be more memory than the machine has (including swap memory). You should also keep in mind that swap memory is generally much, much slower than RAM, and setting memlimit to all available RAM or higher will heavily @@ -90,7 +90,7 @@ to use more than memlimit memory will be skipped. The big-memory tests generally run very, very long. --u is used to specify which special resource intensive tests to run, +`-u` is used to specify which special resource intensive tests to run, such as those requiring large file support or network connectivity. The argument is a comma-separated list of words indicating the resources to test. Currently only the following are defined: @@ -137,16 +137,16 @@ wantobjects - Allows to run Tkinter tests with the specified value of tkinter.wantobjects. -To enable all resources except one, use '-uall,-'. For -example, to run all the tests except for the gui tests, give the -option '-uall,-gui'. +To enable all resources except one, use `-uall,-`. For +example, to run all the tests except for the `gui` tests, give the +option `-uall,-gui`. ---matchfile filters tests using a text file, one pattern per line. +`--matchfile` filters tests using a text file, one pattern per line. Pattern examples: -- test method: test_stat_attributes -- test class: FileTests -- test identifier: test_os.FileTests.test_stat_attributes +- test method: `test_stat_attributes` +- test class: `FileTests` +- test identifier: `test_os.FileTests.test_stat_attributes` """ @@ -245,7 +245,7 @@ def _create_parser(): 'buildbot workers') group.add_argument('--timeout', metavar='TIMEOUT', help='dump the traceback and exit if a test takes ' - 'more than TIMEOUT seconds; disabled if TIMEOUT ' + 'more than `TIMEOUT` seconds; disabled if `TIMEOUT` ' 'is negative or equals to zero') group.add_argument('--wait', action='store_true', help='wait for user input, e.g., allow a debugger ' @@ -261,11 +261,11 @@ def _create_parser(): group = parser.add_argument_group('Verbosity') group.add_argument('-v', '--verbose', action='count', - help='run tests in verbose mode with output to stdout') + help='run tests in verbose mode with output to `stdout`') group.add_argument('-w', '--rerun', action='store_true', help='re-run failed tests in verbose mode') group.add_argument('--verbose2', action='store_true', dest='rerun', - help='deprecated alias to --rerun') + help='deprecated alias to `--rerun`') group.add_argument('-W', '--verbose3', action='store_true', help='display test output on failure') group.add_argument('-q', '--quiet', action='store_true', @@ -295,22 +295,22 @@ def _create_parser(): more_details) group.add_argument('-m', '--match', metavar='PAT', dest='match_tests', action=FilterAction, const=True, - help='match test cases and methods with glob pattern PAT') + help='match test cases and methods with glob pattern `PAT`') group.add_argument('-i', '--ignore', metavar='PAT', dest='match_tests', action=FilterAction, const=False, - help='ignore test cases and methods with glob pattern PAT') + help='ignore test cases and methods with glob pattern `PAT`') group.add_argument('--matchfile', metavar='FILENAME', dest='match_tests', action=FromFileFilterAction, const=True, - help='similar to --match but get patterns from a ' + help='similar to `--match` but get patterns from a ' 'text file, one pattern per line') group.add_argument('--ignorefile', metavar='FILENAME', dest='match_tests', action=FromFileFilterAction, const=False, - help='similar to --matchfile but it receives patterns ' + help='similar to `--matchfile` but it receives patterns ' 'from text file to ignore') group.add_argument('-G', '--failfast', action='store_true', - help='fail as soon as a test fails (only with -v or -W)') + help='fail as soon as a test fails (only with `-v` or `-W`)') group.add_argument('-u', '--use', metavar='RES1,RES2,...', action='extend', type=resources_list, help='specify which special resource intensive tests ' @@ -325,7 +325,7 @@ def _create_parser(): group = parser.add_argument_group('Special runs') group.add_argument('-L', '--runleaks', action='store_true', - help='run the leaks(1) command just before exit.' + + help='run the `leaks(1)` command just before exit.' + more_details) group.add_argument('-R', '--huntrleaks', metavar='RUNCOUNTS', type=huntrleaks, @@ -333,20 +333,20 @@ def _create_parser(): 'very slow).' + more_details) group.add_argument('-j', '--multiprocess', metavar='PROCESSES', dest='use_mp', type=int, - help='run PROCESSES processes at once') + help='run `PROCESSES` processes at once') group.add_argument('--single-process', action='store_true', dest='single_process', help='always run all tests sequentially in ' - 'a single process, ignore -jN option, ' + 'a single process, ignore `-jN` option, ' 'and failed tests are also rerun sequentially ' 'in the same process') group.add_argument('--parallel-threads', metavar='PARALLEL_THREADS', type=int, - help='run copies of each test in PARALLEL_THREADS at ' + help='run copies of each test in `PARALLEL_THREADS` at ' 'once') group.add_argument('-T', '--coverage', action='store_true', dest='trace', - help='turn on code coverage tracing using the trace ' + help='turn on code coverage tracing using the `trace` ' 'module') group.add_argument('-D', '--coverdir', metavar='DIR', type=relative_filename, @@ -356,18 +356,18 @@ def _create_parser(): help='put coverage files alongside modules') group.add_argument('-t', '--threshold', metavar='THRESHOLD', type=int, - help='call gc.set_threshold(THRESHOLD)') + help='call `gc.set_threshold(THRESHOLD)`') group.add_argument('-n', '--nowindows', action='store_true', help='suppress error message boxes on Windows') group.add_argument('-F', '--forever', action='store_true', help='run the specified tests in a loop, until an ' - 'error happens; imply --failfast') + 'error happens; imply `--failfast`') group.add_argument('--list-tests', action='store_true', help="only write the name of tests that will be run, " "don't execute them") group.add_argument('--list-cases', action='store_true', - help='only write the name of test cases that will be run' - ' , don\'t execute them') + help='only write the name of test cases that will be run, ' + 'don\'t execute them') group.add_argument('-P', '--pgo', dest='pgo', action='store_true', help='enable Profile Guided Optimization (PGO) training') group.add_argument('--pgo-extended', action='store_true', @@ -390,9 +390,11 @@ def _create_parser(): group.add_argument('--tempdir', metavar='PATH', help='override the working directory for the test run') group.add_argument('--cleanup', action='store_true', - help='remove old test_python_* directories') + help='remove old `test_python_*` directories') group.add_argument('--bisect', action='store_true', - help='if some tests fail, run test.bisect_cmd on them') + help='if some tests fail, run `test.bisect_cmd` on them') + group.add_argument('--pythoninfo', action='store_true', + help="run `python -m test.pythoninfo` before tests") group.add_argument('--dont-add-python-opts', dest='_add_python_opts', action='store_false', help="internal option, don't use it") diff --git a/Lib/test/libregrtest/findtests.py b/Lib/test/libregrtest/findtests.py index f01c1240774..cd19a7c5c83 100644 --- a/Lib/test/libregrtest/findtests.py +++ b/Lib/test/libregrtest/findtests.py @@ -21,13 +21,16 @@ "test_asyncio", "test_concurrent_futures", "test_doctests", + "test_free_threading", "test_future_stmt", "test_gdb", "test_inspect", - "test_pydoc", + "test_io", "test_multiprocessing_fork", "test_multiprocessing_forkserver", "test_multiprocessing_spawn", + "test_os", + "test_pydoc", } diff --git a/Lib/test/libregrtest/main.py b/Lib/test/libregrtest/main.py index d8b9605ea49..62f66adadeb 100644 --- a/Lib/test/libregrtest/main.py +++ b/Lib/test/libregrtest/main.py @@ -26,7 +26,7 @@ strip_py_suffix, count, format_duration, printlist, get_temp_dir, get_work_dir, exit_timeout, display_header, cleanup_temp_dir, print_warning, - is_cross_compiled, get_host_runner, + is_cross_compiled, get_host_runner, display_title, EXIT_TIMEOUT) @@ -126,6 +126,7 @@ def __init__(self, ns: Namespace, _add_python_opts: bool = False): self.coverage: bool = ns.trace self.coverage_dir: StrPath | None = ns.coverdir self._tmp_dir: StrPath | None = ns.tempdir + self.pythoninfo: bool = ns.pythoninfo # Randomize self.randomize: bool = ns.randomize @@ -322,9 +323,7 @@ def _run_bisect(self, runtests: RunTests, test: str, progress: str) -> bool: title = f"Bisect {test}" if progress: title = f"{title} ({progress})" - print(title) - print("#" * len(title)) - print() + display_title(title) cmd = runtests.create_python_cmd() cmd.extend([ @@ -345,9 +344,7 @@ def _run_bisect(self, runtests: RunTests, test: str, progress: str) -> bool: exitcode = proc.returncode title = f"{title}: exit code {exitcode}" - print(title) - print("#" * len(title)) - print(flush=True) + display_title(title) if exitcode: print(f"Bisect failed with exit code {exitcode}") @@ -446,7 +443,7 @@ def run_tests_sequentially(self, runtests: RunTests) -> None: def get_state(self) -> str: state = self.results.get_state(self.fail_env_changed) - if self.first_state: + if self.first_state and self.first_state != state: state = f'{self.first_state} then {state}' return state @@ -752,6 +749,15 @@ def tmp_dir(self) -> StrPath: ) return self._tmp_dir + def run_pythoninfo(self): + from test import pythoninfo + try: + pythoninfo.main() + except SystemExit: + # Ignore non-zero exit code on purpose + pass + print() + def main(self, tests: TestList | None = None) -> NoReturn: if self.want_add_python_opts: self._add_python_opts() @@ -765,6 +771,9 @@ def main(self, tests: TestList | None = None) -> NoReturn: if self.want_wait: input("Press any key to continue...") + if self.pythoninfo: + self.run_pythoninfo() + setup_test_dir(self.test_dir) selected, tests = self.find_tests(tests) diff --git a/Lib/test/libregrtest/refleak.py b/Lib/test/libregrtest/refleak.py index 5c78515506d..e7da17e500e 100644 --- a/Lib/test/libregrtest/refleak.py +++ b/Lib/test/libregrtest/refleak.py @@ -93,6 +93,13 @@ def runtest_refleak(test_name, test_func, for obj in abc.__subclasses__() + [abc]: abcs[obj] = _get_dump(obj)[0] + # `ByteString` is not included in `collections.abc.__all__` + with warnings.catch_warnings(action='ignore', category=DeprecationWarning): + ByteString = collections.abc.ByteString + # Mypy doesn't even think `ByteString` is a class, hence the `type: ignore` + for obj in ByteString.__subclasses__() + [ByteString]: # type: ignore[attr-defined] + abcs[obj] = _get_dump(obj)[0] + # bpo-31217: Integer pool to get a single integer object for the same # value. The pool is used to prevent false alarm when checking for memory # block leaks. Fill the pool with values in -1000..1000 which are the most @@ -254,6 +261,8 @@ def dash_R_cleanup(fs, ps, pic, zdc, abcs, linecache_data): # Clear ABC registries, restoring previously saved ABC registries. abs_classes = [getattr(collections.abc, a) for a in collections.abc.__all__] + with warnings.catch_warnings(action='ignore', category=DeprecationWarning): + abs_classes.append(collections.abc.ByteString) abs_classes = filter(isabstract, abs_classes) for abc in abs_classes: for obj in abc.__subclasses__() + [abc]: diff --git a/Lib/test/libregrtest/result.py b/Lib/test/libregrtest/result.py index daf7624366e..5324a46bb8c 100644 --- a/Lib/test/libregrtest/result.py +++ b/Lib/test/libregrtest/result.py @@ -100,6 +100,9 @@ class TestResult: # partial coverage in a worker run; not used by sequential in-process runs covered_lines: list[Location] | None = None + # short descriptions of how the test altered the execution environment + env_changed_reasons: list[str] | None = None + def is_failed(self, fail_env_changed: bool) -> bool: if self.state == State.ENV_CHANGED: return fail_env_changed @@ -175,9 +178,15 @@ def __str__(self) -> str: def has_meaningful_duration(self): return State.has_meaningful_duration(self.state) - def set_env_changed(self): + def set_env_changed(self, *reasons): if self.state is None or self.state == State.PASSED: self.state = State.ENV_CHANGED + if reasons: + if self.env_changed_reasons is None: + self.env_changed_reasons = [] + for reason in reasons: + if reason not in self.env_changed_reasons: + self.env_changed_reasons.append(reason) def must_stop(self, fail_fast: bool, fail_env_changed: bool) -> bool: if State.must_stop(self.state): diff --git a/Lib/test/libregrtest/results.py b/Lib/test/libregrtest/results.py index a35934fc2c9..ea5fee33421 100644 --- a/Lib/test/libregrtest/results.py +++ b/Lib/test/libregrtest/results.py @@ -30,6 +30,8 @@ def __init__(self) -> None: self.skipped: TestList = [] self.resource_denied: TestList = [] self.env_changed: TestList = [] + # test name => how the test altered the execution environment + self.env_changed_reasons: dict[TestName, list[str]] = {} self.run_no_tests: TestList = [] self.rerun: TestList = [] self.rerun_results: list[TestResult] = [] @@ -107,6 +109,9 @@ def accumulate_result(self, result: TestResult, runtests: RunTests) -> None: self.good.append(test_name) case State.ENV_CHANGED: self.env_changed.append(test_name) + if result.env_changed_reasons: + self.env_changed_reasons[test_name] = \ + result.env_changed_reasons self.rerun_results.append(result) case State.SKIPPED: self.skipped.append(test_name) @@ -254,7 +259,18 @@ def display_result(self, tests: TestTuple, quiet: bool, print_slowest: bool) -> print() count_text = count(len(tests_list), count_text) print(title_format.format(count_text)) - printlist(tests_list) + if tests_list is self.env_changed: + # List every test and every reason on a separate line. + for test_name in sorted(tests_list): + reasons = self.env_changed_reasons.get(test_name) + if reasons: + print(f" {test_name}:") + for reason in reasons: + print(f" {reason}") + else: + print(f" {test_name}") + else: + printlist(tests_list) if self.good and not quiet: print() diff --git a/Lib/test/libregrtest/run_workers.py b/Lib/test/libregrtest/run_workers.py index 424085a0050..1c94a15a186 100644 --- a/Lib/test/libregrtest/run_workers.py +++ b/Lib/test/libregrtest/run_workers.py @@ -147,9 +147,12 @@ def _kill(self) -> None: use_killpg = USE_PROCESS_GROUP if use_killpg: - parent_sid = os.getsid(0) - sid = os.getsid(popen.pid) - use_killpg = (sid != parent_sid) + try: + use_killpg = (os.getsid(popen.pid) != os.getsid(0)) + except PermissionError: + # On OpenBSD getsid() is only allowed for a process in the + # same session, so the failure means that it is not. + use_killpg = True if use_killpg: what = f"{self} process group" @@ -383,7 +386,8 @@ def _runtest(self, test_name: TestName) -> MultiprocessResult: f'Warning -- {test_name} leaked temporary files ' f'({len(tmp_files)}): {", ".join(sorted(tmp_files))}') stdout += msg - result.set_env_changed() + result.set_env_changed( + f"leaked temporary files: {', '.join(sorted(tmp_files))}") return MultiprocessResult(result, stdout) diff --git a/Lib/test/libregrtest/runtests.py b/Lib/test/libregrtest/runtests.py index e6d34d8e6a3..0a9edce1085 100644 --- a/Lib/test/libregrtest/runtests.py +++ b/Lib/test/libregrtest/runtests.py @@ -159,7 +159,7 @@ def create_python_cmd(self) -> list[str]: if '-u' not in python_opts: cmd.append('-u') # Unbuffered stdout and stderr if self.coverage: - cmd.append("-Xpresite=test.cov") + cmd.append("-Xpresite=test.cov:enable") return cmd def bisect_cmd_args(self) -> list[str]: diff --git a/Lib/test/libregrtest/save_env.py b/Lib/test/libregrtest/save_env.py index 138465012a2..708ab53b66c 100644 --- a/Lib/test/libregrtest/save_env.py +++ b/Lib/test/libregrtest/save_env.py @@ -347,7 +347,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): current = get() # Check for changes to the resource's value if current != original: - support.environment_altered = True + support.set_environment_altered(f"{name} was modified") restore(original) if not self.quiet and not self.pgo: print_warning( diff --git a/Lib/test/libregrtest/setup.py b/Lib/test/libregrtest/setup.py index b9b76a44e3b..d62194acd9c 100644 --- a/Lib/test/libregrtest/setup.py +++ b/Lib/test/libregrtest/setup.py @@ -50,6 +50,14 @@ def setup_process() -> None: for signum in signals: faulthandler.register(signum, chain=True, file=stderr_fd) + # Restore the default SIGINT handler if there is no Python-level + # handler. Python inherits the SIG_IGN disposition when the test + # suite runs as a shell background job; then asyncio.Runner does not + # install its own handler and _thread.interrupt_main() is a no-op, + # which makes some tests in test_asyncio and test_threading hang. + if signal.getsignal(signal.SIGINT) in (signal.SIG_IGN, signal.SIG_DFL): + signal.signal(signal.SIGINT, signal.default_int_handler) + adjust_rlimit_nofile() support.record_original_stdout(sys.stdout) diff --git a/Lib/test/libregrtest/single.py b/Lib/test/libregrtest/single.py index d0759d26269..d7a1c6bea20 100644 --- a/Lib/test/libregrtest/single.py +++ b/Lib/test/libregrtest/single.py @@ -173,7 +173,8 @@ def test_func(): remove_testfn(test_name, runtests.verbose) if gc.garbage: - support.environment_altered = True + support.set_environment_altered( + f"{len(gc.garbage)} uncollectable object(s)") print_warning(f"{test_name} created {len(gc.garbage)} " f"uncollectable object(s)") @@ -194,6 +195,7 @@ def _runtest_env_changed_exc(result: TestResult, runtests: RunTests, # Reset the environment_altered flag to detect if a test altered # the environment support.environment_altered = False + support.environment_altered_reasons.clear() pgo = runtests.pgo if pgo: @@ -261,7 +263,7 @@ def _runtest_env_changed_exc(result: TestResult, runtests: RunTests, return if support.environment_altered: - result.set_env_changed() + result.set_env_changed(*support.environment_altered_reasons) # Don't override the state if it was already set (REFLEAK or ENV_CHANGED) if result.state is None: result.state = State.PASSED diff --git a/Lib/test/libregrtest/tsan.py b/Lib/test/libregrtest/tsan.py index d984a735bdf..c7ec63763bc 100644 --- a/Lib/test/libregrtest/tsan.py +++ b/Lib/test/libregrtest/tsan.py @@ -3,13 +3,12 @@ TSAN_TESTS = [ 'test_asyncio', - # TODO: enable more of test_capi once bugs are fixed (GH-116908, GH-116909). - 'test_capi.test_mem', - 'test_capi.test_pyatomic', + 'test_capi', 'test_code', 'test_ctypes', - # 'test_concurrent_futures', # gh-130605: too many data races + 'test_concurrent_futures', 'test_enum', + 'test_enumerate', 'test_functools', 'test_httpservers', 'test_imaplib', @@ -31,6 +30,7 @@ 'test_threadsignals', 'test_weakref', 'test_free_threading', + 'test_embed', ] # Tests that should be run with `--parallel-threads=N` under TSAN. These tests diff --git a/Lib/test/libregrtest/utils.py b/Lib/test/libregrtest/utils.py index 15caba75acf..4581ab328e7 100644 --- a/Lib/test/libregrtest/utils.py +++ b/Lib/test/libregrtest/utils.py @@ -118,7 +118,8 @@ def printlist(x, width=70, indent=4, file=None): blanks = ' ' * indent # Print the sorted list: 'x' may be a '--random' list or a set() print(textwrap.fill(' '.join(str(elt) for elt in sorted(x)), width, - initial_indent=blanks, subsequent_indent=blanks), + initial_indent=blanks, subsequent_indent=blanks, + break_long_words=False, break_on_hyphens=False), file=file) @@ -131,7 +132,8 @@ def print_warning(msg: str) -> None: def regrtest_unraisable_hook(unraisable) -> None: global orig_unraisablehook - support.environment_altered = True + support.set_environment_altered( + f"unraisable exception ({unraisable.exc_type.__name__})") support.print_warning("Unraisable exception") old_stderr = sys.stderr try: @@ -155,7 +157,8 @@ def setup_unraisable_hook() -> None: def regrtest_threading_excepthook(args) -> None: global orig_threading_excepthook - support.environment_altered = True + support.set_environment_altered( + f"uncaught thread exception ({args.exc_type.__name__})") support.print_warning(f"Uncaught thread exception: {args.exc_type.__name__}") old_stderr = sys.stderr try: @@ -294,6 +297,25 @@ def clear_caches(): else: importlib_metadata.FastPath.__new__.cache_clear() + try: + encodings = sys.modules['encodings'] + except KeyError: + pass + else: + encodings._cache.clear() + + try: + codecs = sys.modules['codecs'] + except KeyError: + pass + else: + # There's no direct API to clear the codecs search cache, but + # `unregister` clears it implicitly. + def noop_search_function(name): + return None + codecs.register(noop_search_function) + codecs.unregister(noop_search_function) + def get_build_info(): # Get most important configure and build options as a list of strings. @@ -496,7 +518,7 @@ def remove_testfn(test_name: TestName, verbose: int) -> None: if verbose: print_warning(f"{test_name} left behind {kind} {name!r}") - support.environment_altered = True + support.set_environment_altered(f"left behind {kind} {name!r}") try: import stat @@ -727,3 +749,9 @@ def _sanitize_xml_replace(regs): def sanitize_xml(text: str) -> str: return ILLEGAL_XML_CHARS_RE.sub(_sanitize_xml_replace, text) + + +def display_title(title): + print(title) + print("#" * len(title)) + print(flush=True) diff --git a/Lib/test/lock_tests.py b/Lib/test/lock_tests.py index fb11f482895..47025c041da 100644 --- a/Lib/test/lock_tests.py +++ b/Lib/test/lock_tests.py @@ -124,6 +124,11 @@ def test_constructor(self): lock = self.locktype() del lock + def test_constructor_noargs(self): + self.assertRaises(TypeError, self.locktype, 1) + self.assertRaises(TypeError, self.locktype, x=1) + self.assertRaises(TypeError, self.locktype, 1, x=2) + def test_repr(self): lock = self.locktype() self.assertRegex(repr(lock), "") @@ -557,6 +562,10 @@ def f(): for r, dt in results2: self.assertTrue(r) + def test_nan_timeout(self): + evt = self.eventtype() + self.assertRaises(ValueError, evt.wait, float('nan')) + def test_set_and_clear(self): # gh-57711: check that wait() returns true even when the event is # cleared before the waiting thread is woken up. @@ -755,6 +764,14 @@ def f(): # In practice, this implementation has no spurious wakeups. self.assertFalse(result) + def test_nan_timeout(self): + cond = self.condtype() + nan = float('nan') + with cond: + self.assertRaises(ValueError, cond.wait, nan) + self.assertRaises(ValueError, cond.wait_for, lambda: False, nan) + self.assertEqual(len(cond._waiters), 0) + def test_waitfor(self): cond = self.condtype() state = 0 diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py index 1358200add5..e3f348d272a 100644 --- a/Lib/test/mapping_tests.py +++ b/Lib/test/mapping_tests.py @@ -4,7 +4,7 @@ from test import support -class BasicTestMappingProtocol(unittest.TestCase): +class BasicTestImmutableMappingProtocol(unittest.TestCase): # This base class can be used to check that an object conforms to the # mapping protocol @@ -20,12 +20,9 @@ def _empty_mapping(self): """Return an empty mapping object""" return self.type2test() def _full_mapping(self, data): - """Return a mapping object with the value contained in data + """Return a mapping object with the values contained in data dictionary""" - x = self._empty_mapping() - for key, value in data.items(): - x[key] = value - return x + return self.type2test(data) def __init__(self, *args, **kw): unittest.TestCase.__init__(self, *args, **kw) @@ -88,6 +85,72 @@ def check_iterandlist(iter, lst, ref): self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.assertNotIn(knownkey, d) + def test_constructor(self): + self.assertEqual(self._empty_mapping(), self._empty_mapping()) + + def test_bool(self): + self.assertTrue(not self._empty_mapping()) + self.assertTrue(self.reference) + self.assertFalse(bool(self._empty_mapping())) + self.assertTrue(bool(self.reference)) + + def test_keys(self): + d = self._empty_mapping() + self.assertEqual(list(d.keys()), []) + d = self.reference + self.assertIn(list(self.inmapping.keys())[0], d.keys()) + self.assertNotIn(list(self.other.keys())[0], d.keys()) + self.assertRaises(TypeError, d.keys, None) + + def test_values(self): + d = self._empty_mapping() + self.assertEqual(list(d.values()), []) + + self.assertRaises(TypeError, d.values, None) + + def test_items(self): + d = self._empty_mapping() + self.assertEqual(list(d.items()), []) + + self.assertRaises(TypeError, d.items, None) + + def test_len(self): + d = self._empty_mapping() + self.assertEqual(len(d), 0) + + def test_getitem(self): + d = self.reference + self.assertEqual(d[list(self.inmapping.keys())[0]], + list(self.inmapping.values())[0]) + + self.assertRaises(TypeError, d.__getitem__) + + # no test_fromkeys or test_copy as both os.environ and selves don't support it + + def test_get(self): + d = self._empty_mapping() + self.assertIsNone(d.get(list(self.other.keys())[0])) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) + d = self.reference + self.assertIsNone(d.get(list(self.other.keys())[0])) + self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) + self.assertEqual(d.get(list(self.inmapping.keys())[0]), + list(self.inmapping.values())[0]) + self.assertEqual(d.get(list(self.inmapping.keys())[0], 3), + list(self.inmapping.values())[0]) + self.assertRaises(TypeError, d.get) + self.assertRaises(TypeError, d.get, None, None, None) + + +class BasicTestMappingProtocol(BasicTestImmutableMappingProtocol): + def _full_mapping(self, data): + """Return a mapping object with the values contained in data + dictionary""" + x = self._empty_mapping() + for key, value in data.items(): + x[key] = value + return x + def test_write(self): # Test for write operations on mapping p = self._empty_mapping() @@ -130,46 +193,6 @@ def test_write(self): p=self._empty_mapping() self.assertRaises(KeyError, p.popitem) - def test_constructor(self): - self.assertEqual(self._empty_mapping(), self._empty_mapping()) - - def test_bool(self): - self.assertTrue(not self._empty_mapping()) - self.assertTrue(self.reference) - self.assertTrue(bool(self._empty_mapping()) is False) - self.assertTrue(bool(self.reference) is True) - - def test_keys(self): - d = self._empty_mapping() - self.assertEqual(list(d.keys()), []) - d = self.reference - self.assertIn(list(self.inmapping.keys())[0], d.keys()) - self.assertNotIn(list(self.other.keys())[0], d.keys()) - self.assertRaises(TypeError, d.keys, None) - - def test_values(self): - d = self._empty_mapping() - self.assertEqual(list(d.values()), []) - - self.assertRaises(TypeError, d.values, None) - - def test_items(self): - d = self._empty_mapping() - self.assertEqual(list(d.items()), []) - - self.assertRaises(TypeError, d.items, None) - - def test_len(self): - d = self._empty_mapping() - self.assertEqual(len(d), 0) - - def test_getitem(self): - d = self.reference - self.assertEqual(d[list(self.inmapping.keys())[0]], - list(self.inmapping.values())[0]) - - self.assertRaises(TypeError, d.__getitem__) - def test_update(self): # mapping argument d = self._empty_mapping() @@ -265,22 +288,6 @@ def __next__(self): self.assertRaises(ValueError, d.update, [(1, 2, 3)]) - # no test_fromkeys or test_copy as both os.environ and selves don't support it - - def test_get(self): - d = self._empty_mapping() - self.assertTrue(d.get(list(self.other.keys())[0]) is None) - self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) - d = self.reference - self.assertTrue(d.get(list(self.other.keys())[0]) is None) - self.assertEqual(d.get(list(self.other.keys())[0], 3), 3) - self.assertEqual(d.get(list(self.inmapping.keys())[0]), - list(self.inmapping.values())[0]) - self.assertEqual(d.get(list(self.inmapping.keys())[0], 3), - list(self.inmapping.values())[0]) - self.assertRaises(TypeError, d.get) - self.assertRaises(TypeError, d.get, None, None, None) - def test_setdefault(self): d = self._empty_mapping() self.assertRaises(TypeError, d.setdefault) diff --git a/Lib/test/mock_socket.py b/Lib/test/mock_socket.py index c7abddcf5fa..b85b955d7f6 100644 --- a/Lib/test/mock_socket.py +++ b/Lib/test/mock_socket.py @@ -1,4 +1,4 @@ -"""Mock socket module used by the smtpd and smtplib tests. +"""Mock socket module used by the smtplib tests. """ # imported for _GLOBAL_DEFAULT_TIMEOUT @@ -33,7 +33,7 @@ def close(self): class MockSocket: - """Mock socket object used by smtpd and smtplib tests. + """Mock socket object used by the smtplib tests. """ def __init__(self, family=None): global _reply_data diff --git a/Lib/test/picklecommon.py b/Lib/test/picklecommon.py index 4c19b6c421f..bb8e41b0149 100644 --- a/Lib/test/picklecommon.py +++ b/Lib/test/picklecommon.py @@ -263,6 +263,17 @@ class MyFrozenSet(frozenset): MyStr, MyUnicode, MyTuple, MyList, MyDict, MySet, MyFrozenSet] +try: + frozendict +except NameError: + # Python 3.14 and older + pass +else: + class MyFrozenDict(dict): + sample = frozendict({"a": 1, "b": 2}) + myclasses.append(MyFrozenDict) + + # For test_newobj_overridden_new class MyIntWithNew(int): def __new__(cls, value): @@ -388,3 +399,48 @@ def pie(self): class Subclass(tuple): class Nested(str): pass + +# For test_private_methods +class PrivateMethods: + def __init__(self, value): + self.value = value + + def __private_method(self): + return self.value + + def get_method(self): + return self.__private_method + + @classmethod + def get_unbound_method(cls): + return cls.__private_method + + @classmethod + def __private_classmethod(cls): + return 43 + + @classmethod + def get_classmethod(cls): + return cls.__private_classmethod + + @staticmethod + def __private_staticmethod(): + return 44 + + @classmethod + def get_staticmethod(cls): + return cls.__private_staticmethod + +# For test_private_nested_classes +class PrivateNestedClasses: + @classmethod + def get_nested(cls): + return cls.__Nested + + class __Nested: + @classmethod + def get_nested2(cls): + return cls.__Nested2 + + class __Nested2: + pass diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py index 75e2afa7ae6..805c010abae 100644 --- a/Lib/test/pickletester.py +++ b/Lib/test/pickletester.py @@ -79,6 +79,15 @@ def count_opcode(code, pickle): def identity(x): return x +def itersize(start, stop): + # Produce geometrical increasing sequence from start to stop + # (inclusively) for tests. + size = start + while size < stop: + yield size + size <<= 1 + yield stop + class UnseekableIO(io.BytesIO): def peek(self, *args): @@ -751,9 +760,8 @@ def assert_is_copy(self, obj, objcopy, msg=None): self.assertEqual(getattr(obj, slot, None), getattr(objcopy, slot, None), msg=msg) - def check_unpickling_error(self, errors, data): - with self.subTest(data=data), \ - self.assertRaises(errors): + def check_unpickling_error_strict(self, errors, data): + with self.assertRaises(errors): try: self.loads(data) except BaseException as exc: @@ -762,6 +770,10 @@ def check_unpickling_error(self, errors, data): (data, exc.__class__.__name__, exc)) raise + def check_unpickling_error(self, errors, data): + with self.subTest(data=data): + self.check_unpickling_error_strict(errors, data) + def test_load_from_data0(self): self.assert_is_copy(self._testdata, self.loads(DATA0)) @@ -910,6 +922,16 @@ def test_constants(self): self.assertIs(self.loads(b'I01\n.'), True) self.assertIs(self.loads(b'I00\n.'), False) + def test_issue135241(self): + # C implementation should check for hardcoded values 00 and 01 + # when getting booleans from the INT opcode. Doing a str comparison + # to bypass truthy/falsy comparisons. These payloads should return + # 0, not False. + out1 = self.loads(b'I+0\n.') + self.assertEqual(str(out1), '0') + out2 = self.loads(b'I 0\n.') + self.assertEqual(str(out2), '0') + def test_zero_padded_integers(self): self.assertEqual(self.loads(b'I010\n.'), 10) self.assertEqual(self.loads(b'I-010\n.'), -10) @@ -1038,6 +1060,155 @@ def test_negative_32b_binput(self): dumped = b'\x80\x03X\x01\x00\x00\x00ar\xff\xff\xff\xff.' self.check_unpickling_error(ValueError, dumped) + def test_too_large_put(self): + # Test that PUT with large id does not cause allocation of + # too large memo table. The C implementation uses a dict-based memo + # for sparse indices (when idx > memo_len * 2) instead of allocating + # a massive array. This test verifies large sparse indices work without + # causing memory exhaustion. + # + # The following simple pickle creates an empty list, memoizes it + # using a large index, then loads it back on the stack, builds + # a tuple containing 2 identical empty lists and returns it. + data = lambda n: (b'((lp' + str(n).encode() + b'\n' + + b'g' + str(n).encode() + b'\nt.') + # 0: ( MARK + # 1: ( MARK + # 2: l LIST (MARK at 1) + # 3: p PUT 1000000000000 + # 18: g GET 1000000000000 + # 33: t TUPLE (MARK at 0) + # 34: . STOP + for idx in [10**6, 10**9, 10**12]: + if idx > sys.maxsize: + continue + self.assertEqual(self.loads(data(idx)), ([],)*2) + + def test_too_large_long_binput(self): + # Test that LONG_BINPUT with large id does not cause allocation of + # too large memo table. The C implementation uses a dict-based memo + # for sparse indices (when idx > memo_len * 2) instead of allocating + # a massive array. This test verifies large sparse indices work without + # causing memory exhaustion. + # + # The following simple pickle creates an empty list, memoizes it + # using a large index, then loads it back on the stack, builds + # a tuple containing 2 identical empty lists and returns it. + data = lambda n: (b'(]r' + struct.pack(' sys.maxsize')) + + def test_truncated_large_binunicode8(self): + data = lambda size: b'\x8d' + struct.pack(' None: max_memuse = memlimit -class _MemoryWatchdog: - """An object which periodically watches the process' memory consumption - and prints it out. - """ - - def __init__(self): - self.procfile = '/proc/{pid}/statm'.format(pid=os.getpid()) - self.started = False - - def start(self): - import warnings - try: - f = open(self.procfile, 'r') - except OSError as e: - logging.getLogger(__name__).warning('/proc not available for stats: %s', e, exc_info=e) - sys.stderr.flush() - return - - import subprocess - with f: - watchdog_script = findfile("memory_watchdog.py") - self.mem_watchdog = subprocess.Popen([sys.executable, watchdog_script], - stdin=f, - stderr=subprocess.DEVNULL) - self.started = True - - def stop(self): - if self.started: - self.mem_watchdog.terminate() - self.mem_watchdog.wait() - - def bigmemtest(size, memuse, dry_run=True): """Decorator for bigmem tests. @@ -1191,8 +1274,15 @@ def bigmemtest(size, memuse, dry_run=True): extra argument. If 'dry_run' is true, the value passed to the test method may be less than the requested value. If 'dry_run' is false, it means the test doesn't support dummy runs when -M is not specified. + + A test that actually allocates the requested memory (that is, one run with + -M) runs in a subprocess, so that the memory it uses and the address space + it fragments are released when it ends. A dummy run stays in the process. """ def decorator(f): + from test.support import isolation + + @functools.wraps(f) def wrapper(self): size = wrapper.size memuse = wrapper.memuse @@ -1207,44 +1297,41 @@ def wrapper(self): "not enough memory: %.1fG minimum needed" % (size * memuse / (1024 ** 3))) - if real_max_memuse and verbose: + if (real_max_memuse and verbose + and not isolation.runningInSubprocess): print() - print(" ... expected peak memory use: {peak:.1f}G" - .format(peak=size * memuse / (1024 ** 3))) - watchdog = _MemoryWatchdog() - watchdog.start() - else: - watchdog = None + peak = (size * memuse) / (1024 ** 3) + print(f" ... expected peak memory use: {peak:.1f} GiB") + + if (real_max_memuse and has_subprocess_support + and not isolation.runningInSubprocess): + cls = type(self) + qualname = f'{cls.__qualname__}.{f.__name__}' + proc = isolation._start_test(cls.__module__, qualname) + isolation._replay_test(self, *proc.wait()) + return - try: - return f(self, maxsize) - finally: - if watchdog: - watchdog.stop() + return f(self, maxsize) wrapper.size = size wrapper.memuse = memuse return wrapper return decorator -def nomemtest(f): +def nomemtest(test): """Check that we can use this test with `_testcapi.set_nomemory`.""" from .import_helper import import_module - @functools.wraps(f) + @functools.wraps(test) def internal(*args, **kwargs): import_module('_testcapi') - return f(*args, **kwargs) + return test(*args, **kwargs) - return unittest.skipIf( - # Python built with Py_TRACE_REFS fail with a fatal error in - # _PyRefchain_Trace() on memory allocation error. - Py_TRACE_REFS, - 'cannot test Py_TRACE_REFS build', - )(cpython_only(internal)) + return cpython_only(internal) def bigaddrspacetest(f): """Decorator for tests that fill the address space.""" + @functools.wraps(f) def wrapper(self): if max_memuse < MAX_Py_ssize_t: if MAX_Py_ssize_t >= 2**63 - 1 and max_memuse >= 2**31: @@ -1326,7 +1413,7 @@ def trace_wrapper(*args, **kwargs): sys.settrace(original_trace) coverage_wrapper = trace_wrapper - if 'test.cov' in sys.modules: # -Xpresite=test.cov used + if 'test.cov' in sys.modules: # -Xpresite=test.cov:enable used cov = sys.monitoring.COVERAGE_ID @functools.wraps(func) def coverage_wrapper(*args, **kwargs): @@ -1350,6 +1437,7 @@ def no_rerun(reason): def deco(func): assert not isinstance(func, type), func _has_run = False + @functools.wraps(func) def wrapper(self): nonlocal _has_run if _has_run: @@ -1389,11 +1477,6 @@ def requires_specialization(test): _opcode.ENABLE_SPECIALIZATION, "requires specialization")(test) -def requires_specialization_ft(test): - return unittest.skipUnless( - _opcode.ENABLE_SPECIALIZATION_FT, "requires specialization")(test) - - def reset_code(f: types.FunctionType) -> types.FunctionType: """Clear all specializations, local instrumentation, and JIT code for the given function.""" f.__code__ = f.__code__.replace() @@ -1452,14 +1535,25 @@ def print_warning(msg): # to cleanup threads. environment_altered = False -def reap_children(): - """Use this function at the end of test_main() whenever sub-processes - are started. This will help ensure that no extra children (zombies) - stick around to hog resources and create problems when looking - for refleaks. - """ +# Short descriptions of what was altered, e.g. "unraisable exception". +# They are reported by regrtest together with the name of the test. +environment_altered_reasons = [] + + +def set_environment_altered(reason): + """Set the environment_altered flag and record why it was set.""" global environment_altered + environment_altered = True + if reason not in environment_altered_reasons: + environment_altered_reasons.append(reason) + +def reap_children(): + """Call this from setUp(), tearDown(), or tearDownModule() in tests + that start subprocesses. This will help ensure that no extra children + (zombies) stick around to hog resources and create problems when + looking for refleaks. + """ # Need os.waitpid(-1, os.WNOHANG): Windows is not supported if not (hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG')): return @@ -1479,7 +1573,7 @@ def reap_children(): break print_warning(f"reap_children() reaped child process {pid}") - environment_altered = True + set_environment_altered("reaped child process") @contextlib.contextmanager @@ -1651,8 +1745,12 @@ def _platform_specific(self): )) self._env = {k.upper(): os.getenv(k) for k in os.environ} - self._env["PYTHONHOME"] = os.path.dirname(self.real) + home = os.path.dirname(self.real) if sysconfig.is_python_build(): + home = os.path.join(home, sysconfig.get_config_var('VPATH')) + self._env["PYTHONHOME"] = home + # TODO: RUSTPYTHON; Cargo builds do not use CPython's Modules/Setup. + if sys.implementation.name == 'rustpython': self._env["PYTHONPATH"] = STDLIB_DIR else: def _platform_specific(self): @@ -2911,7 +3009,7 @@ def iter_builtin_types(): # Fall back to making a best-effort guess. if hasattr(object, '__flags__'): # Look for any type object with the Py_TPFLAGS_STATIC_BUILTIN flag set. - import datetime + import datetime # noqa: F401 seen = set() for cls, subs in walk_class_hierarchy(object): if cls in seen: @@ -3047,6 +3145,13 @@ def force_color(color: bool): import _colorize from .os_helper import EnvironmentVarGuard + if color: + try: + import _pyrepl # noqa: F401 + except ModuleNotFoundError: + # Can't force enable color without _pyrepl, so just skip. + raise unittest.SkipTest("_pyrepl is missing") + with ( swap_attr(_colorize, "can_colorize", lambda *, file=None: color), EnvironmentVarGuard() as env, @@ -3336,6 +3441,11 @@ def control_characters_c0() -> list[str]: return [chr(c) for c in range(0x00, 0x20)] + ["\x7F"] +_ROOT_IN_POSIX = hasattr(os, 'geteuid') and os.geteuid() == 0 +requires_root_user = unittest.skipUnless(_ROOT_IN_POSIX, "test needs root privilege") +requires_non_root_user = unittest.skipIf(_ROOT_IN_POSIX, "test needs non-root account") + + STATUS_DLL_INIT_FAILED = 0xC0000142 def skip_on_low_desktop_heap_memory_subprocess(returncode): if sys.platform not in ('win32', 'cygwin'): @@ -3349,3 +3459,48 @@ def skip_on_low_desktop_heap_memory_subprocess(returncode): if returncode == STATUS_DLL_INIT_FAILED: raise unittest.SkipTest('gh-150436: DLL init failed, likely because ' 'of low desktop heap memory') + + +def built_with_c_assertions(): + """Check if Python was built with C assertions (assert()).""" + try: + import _testlimitedcapi + except ImportError: + return Py_DEBUG + else: + return bool(_testlimitedcapi._py_getbuiltwithassert()) + + +def inject_memory_error(start=0, stop=0): + """ + Memory allocation fails after 'start' allocation requests, and until 'stop' + allocation requests except when 'stop' is negative or equal to 0 (default) + in which case allocation failures never stop. + + Raise SkipTest if the _testcapi extension module is missing + """ + try: + import _testcapi + except ImportError: + raise unittest.SkipTest("_testcapi required") + + _testcapi.set_nomemory(start, stop) + + +@contextlib.contextmanager +def inject_memory_error_cm(start=0, stop=0): + """ + Similar to inject_memory_error() but can be used as a context manager. + + Raise SkipTest if the _testcapi extension module is missing + """ + try: + import _testcapi + except ImportError: + raise unittest.SkipTest("_testcapi required") + + try: + _testcapi.set_nomemory(start, stop) + yield + finally: + _testcapi.remove_mem_hooks() diff --git a/Lib/test/support/_hypothesis_stubs/__init__.py b/Lib/test/support/_hypothesis_stubs/__init__.py index 6ba5bb814b9..6fa013b55b2 100644 --- a/Lib/test/support/_hypothesis_stubs/__init__.py +++ b/Lib/test/support/_hypothesis_stubs/__init__.py @@ -24,7 +24,13 @@ def decorator(f): @functools.wraps(f) def test_function(self): for example_args, example_kwargs in examples: - with self.subTest(*example_args, **example_kwargs): + if len(example_args) < 2: + subtest_args = example_args + else: + # subTest takes up to one positional argument. + # When there are more, display them as a tuple + subtest_args = [example_args] + with self.subTest(*subtest_args, **example_kwargs): f(self, *example_args, **example_kwargs) else: diff --git a/Lib/test/support/channels.py b/Lib/test/support/channels.py index 5352f7d4da3..fab1797659b 100644 --- a/Lib/test/support/channels.py +++ b/Lib/test/support/channels.py @@ -6,8 +6,8 @@ # aliases: from _interpchannels import ( - ChannelError, ChannelNotFoundError, ChannelClosedError, - ChannelEmptyError, ChannelNotEmptyError, + ChannelError, ChannelNotFoundError, ChannelClosedError, # noqa: F401 + ChannelEmptyError, ChannelNotEmptyError, # noqa: F401 ) from concurrent.interpreters._crossinterp import ( UNBOUND_ERROR, UNBOUND_REMOVE, diff --git a/Lib/test/support/hashlib_helper.py b/Lib/test/support/hashlib_helper.py index 7032257b068..818f99d0023 100644 --- a/Lib/test/support/hashlib_helper.py +++ b/Lib/test/support/hashlib_helper.py @@ -1,45 +1,515 @@ +import contextlib +import enum import functools -import hashlib import importlib +import inspect import unittest -from test.support.import_helper import import_module +import unittest.mock +from test.support import import_helper -try: - import _hashlib -except ImportError: - _hashlib = None -try: - import _hmac -except ImportError: - _hmac = None +def _parse_fullname(fullname, *, strict=False): + """Parse a fully-qualified name ``.``. + The ``module_name`` component contains one or more dots. + The ``member_name`` component does not contain any dot. -def requires_hashlib(): - return unittest.skipIf(_hashlib is None, "requires _hashlib") + If *strict* is true, *fullname* must be a string. Otherwise, + it can be None, and, ``module_name`` and ``member_name`` will + also be None. + """ + if fullname is None: + assert not strict + return None, None + assert isinstance(fullname, str), fullname + assert fullname.count(".") >= 1, fullname + module_name, member_name = fullname.rsplit(".", maxsplit=1) + return module_name, member_name -def requires_builtin_hmac(): - return unittest.skipIf(_hmac is None, "requires _hmac") +def _import_module(module_name, *, strict=False): + """Import a module from its fully-qualified name. + If *strict* is false, import failures are suppressed and None is returned. + """ + if module_name is None: + # To prevent a TypeError in importlib.import_module + if strict: + raise ImportError("no module to import") + return None + try: + return importlib.import_module(module_name) + except ImportError as exc: + if strict: + raise exc + return None -def _missing_hash(digestname, implementation=None, *, exc=None): - parts = ["missing", implementation, f"hash algorithm: {digestname!r}"] - msg = " ".join(filter(None, parts)) - raise unittest.SkipTest(msg) from exc +def _import_member(module_name, member_name, *, strict=False): + """Import a member from a module. + + If *strict* is false, import failures are suppressed and None is returned. + """ + if member_name is None: + if strict: + raise ImportError(f"no member to import from {module_name}") + return None + module = _import_module(module_name, strict=strict) + if strict: + return getattr(module, member_name) + return getattr(module, member_name, None) + + +class Implementation(enum.StrEnum): + # Indicate that the hash function is implemented by a built-in module. + builtin = enum.auto() + # Indicate that the hash function is implemented by OpenSSL. + openssl = enum.auto() + # Indicate that the hash function is provided through the public API. + hashlib = enum.auto() + + +class _HashId(enum.StrEnum): + """Enumeration containing the canonical digest names. + + Those names should only be used by hashlib.new() or hmac.new(). + Their support by _hashlib.new() is not necessarily guaranteed. + """ + + md5 = enum.auto() + sha1 = enum.auto() + + sha224 = enum.auto() + sha256 = enum.auto() + sha384 = enum.auto() + sha512 = enum.auto() + + sha3_224 = enum.auto() + sha3_256 = enum.auto() + sha3_384 = enum.auto() + sha3_512 = enum.auto() + + shake_128 = enum.auto() + shake_256 = enum.auto() + + blake2s = enum.auto() + blake2b = enum.auto() + + def __repr__(self): + return str(self) + + @property + def is_xof(self): + """Indicate whether the hash is an extendable-output hash function.""" + return self.startswith("shake_") + + @property + def is_keyed(self): + """Indicate whether the hash is a keyed hash function.""" + return self.startswith("blake2") + + +CANONICAL_DIGEST_NAMES = frozenset(map(str, _HashId.__members__)) +NON_HMAC_DIGEST_NAMES = frozenset(( + _HashId.shake_128, _HashId.shake_256, + _HashId.blake2s, _HashId.blake2b, +)) + + +class _HashInfoItem: + """Interface for interacting with a named object. + + The object is entirely described by its fully-qualified *fullname*. + + *fullname* must be None or a string ".". + """ + + def __init__(self, fullname=None, *, strict=False): + module_name, member_name = _parse_fullname(fullname, strict=strict) + self.fullname = fullname + self.module_name = module_name + self.member_name = member_name + + def import_module(self, *, strict=False): + """Import the described module. + + If *strict* is true, an ImportError may be raised if importing fails, + otherwise, None is returned on error. + """ + return _import_module(self.module_name, strict=strict) + + def import_member(self, *, strict=False): + """Import the described member. + + If *strict* is true, an AttributeError or an ImportError may be + raised if importing fails; otherwise, None is returned on error. + """ + return _import_member( + self.module_name, self.member_name, strict=strict + ) -def _openssl_availabillity(digestname, *, usedforsecurity): - try: - _hashlib.new(digestname, usedforsecurity=usedforsecurity) - except AttributeError: - assert _hashlib is None - _missing_hash(digestname, "OpenSSL") - except ValueError as exc: - _missing_hash(digestname, "OpenSSL", exc=exc) +class _HashInfoBase: + """Base dataclass containing "backend" information. + + Subclasses may define an attribute named after one of the known + implementations ("builtin", "openssl" or "hashlib") which stores + an _HashInfoItem object. + + Those attributes can be retrieved through __getitem__(), e.g., + ``info["builtin"]`` returns the _HashInfoItem corresponding to + the builtin implementation. + """ + + def __init__(self, canonical_name): + assert isinstance(canonical_name, _HashId), canonical_name + self.canonical_name = canonical_name + + def __getitem__(self, implementation): + try: + attrname = Implementation(implementation) + except ValueError: + raise self.invalid_implementation_error(implementation) from None + + try: + provider = getattr(self, attrname) + except AttributeError: + raise self.invalid_implementation_error(implementation) from None + + if not isinstance(provider, _HashInfoItem): + raise KeyError(implementation) + return provider + + def invalid_implementation_error(self, implementation): + msg = f"no implementation {implementation} for {self.canonical_name}" + return AssertionError(msg) + + +class _HashTypeInfo(_HashInfoBase): + """Dataclass containing information for hash functions types. + + - *canonical_name* must be a _HashId. + + - *builtin* is the fully-qualified name for the builtin HACL* type, + e.g., "_md5.MD5Type". + + - *openssl* is the fully-qualified name for the OpenSSL wrapper type, + e.g., "_hashlib.HASH". + """ + + def __init__(self, canonical_name, builtin, openssl): + super().__init__(canonical_name) + self.builtin = _HashInfoItem(builtin, strict=True) + self.openssl = _HashInfoItem(openssl, strict=True) + + def fullname(self, implementation): + """Get the fully qualified name of a given implementation. + + This returns a string of the form "MODULE_NAME.OBJECT_NAME" or None + if the hash function does not have a corresponding implementation. + + *implementation* must be "builtin" or "openssl". + """ + return self[implementation].fullname + + def module_name(self, implementation): + """Get the name of the module containing the hash object type.""" + return self[implementation].module_name + + def object_type_name(self, implementation): + """Get the name of the hash object class name.""" + return self[implementation].member_name + + def import_module(self, implementation, *, allow_skip=False): + """Import the module containing the hash object type. + + On error, return None if *allow_skip* is false, or raise SkipNoHash. + """ + target = self[implementation] + module = target.import_module() + if allow_skip and module is None: + reason = f"cannot import module {target.module_name}" + raise SkipNoHash(self.canonical_name, implementation, reason) + return module + + def import_object_type(self, implementation, *, allow_skip=False): + """Get the runtime hash object type. + + On error, return None if *allow_skip* is false, or raise SkipNoHash. + """ + target = self[implementation] + member = target.import_member() + if allow_skip and member is None: + reason = f"cannot import class {target.fullname}" + raise SkipNoHash(self.canonical_name, implementation, reason) + return member + + +class _HashFuncInfo(_HashInfoBase): + """Dataclass containing information for hash functions constructors. + + - *canonical_name* must be a _HashId. + + - *builtin* is the fully-qualified name of the HACL* + hash constructor function, e.g., "_md5.md5". + + - *openssl* is the fully-qualified name of the "_hashlib" method + for the OpenSSL named constructor, e.g., "_hashlib.openssl_md5". + + - *hashlib* is the fully-qualified name of the "hashlib" method + for the explicit named hash constructor, e.g., "hashlib.md5". + """ -def _decorate_func_or_class(func_or_class, decorator_func): + def __init__(self, canonical_name, builtin, openssl=None, hashlib=None): + super().__init__(canonical_name) + self.builtin = _HashInfoItem(builtin, strict=True) + self.openssl = _HashInfoItem(openssl, strict=False) + self.hashlib = _HashInfoItem(hashlib, strict=False) + + def fullname(self, implementation): + """Get the fully qualified name of a given implementation. + + This returns a string of the form "MODULE_NAME.METHOD_NAME" or None + if the hash function does not have a corresponding implementation. + + *implementation* must be "builtin", "openssl" or "hashlib". + """ + return self[implementation].fullname + + def module_name(self, implementation): + """Get the name of the constructor function module. + + The *implementation* must be "builtin", "openssl" or "hashlib". + """ + return self[implementation].module_name + + def method_name(self, implementation): + """Get the name of the constructor function module method. + + Use fullname() to get the constructor function fully-qualified name. + + The *implementation* must be "builtin", "openssl" or "hashlib". + """ + return self[implementation].member_name + + +class _HashInfo: + """Dataclass containing information for supported hash functions. + + Attributes + ---------- + canonical_name : _HashId + The hash function canonical name. + type : _HashTypeInfo + The hash object types information. + func : _HashTypeInfo + The hash object constructors information. + """ + + def __init__( + self, + canonical_name, + builtin_object_type_fullname, + openssl_object_type_fullname, + builtin_method_fullname, + openssl_method_fullname=None, + hashlib_method_fullname=None, + ): + """ + - *canonical_name* must be a _HashId. + + - *builtin_object_type_fullname* is the fully-qualified name + for the builtin HACL* type, e.g., "_md5.MD5Type". + + - *openssl_object_type_fullname* is the fully-qualified name + for the OpenSSL wrapper type, e.g., "_hashlib.HASH". + + - *builtin_method_fullname* is the fully-qualified name + of the HACL* hash constructor function, e.g., "_md5.md5". + + - *openssl_method_fullname* is the fully-qualified name + of the "_hashlib" module method for the explicit OpenSSL + hash constructor function, e.g., "_hashlib.openssl_md5". + + - *hashlib_method_fullname* is the fully-qualified name + of the "hashlib" module method for the explicit hash + constructor function, e.g., "hashlib.md5". + """ + assert isinstance(canonical_name, _HashId), canonical_name + self.canonical_name = canonical_name + self.type = _HashTypeInfo( + canonical_name, + builtin_object_type_fullname, + openssl_object_type_fullname, + ) + self.func = _HashFuncInfo( + canonical_name, + builtin_method_fullname, + openssl_method_fullname, + hashlib_method_fullname, + ) + + +_HASHINFO_DATABASE = frozendict({ + _HashId.md5: _HashInfo( + _HashId.md5, + "_md5.MD5Type", + "_hashlib.HASH", + "_md5.md5", + "_hashlib.openssl_md5", + "hashlib.md5", + ), + _HashId.sha1: _HashInfo( + _HashId.sha1, + "_sha1.SHA1Type", + "_hashlib.HASH", + "_sha1.sha1", + "_hashlib.openssl_sha1", + "hashlib.sha1", + ), + _HashId.sha224: _HashInfo( + _HashId.sha224, + "_sha2.SHA224Type", + "_hashlib.HASH", + "_sha2.sha224", + "_hashlib.openssl_sha224", + "hashlib.sha224", + ), + _HashId.sha256: _HashInfo( + _HashId.sha256, + "_sha2.SHA256Type", + "_hashlib.HASH", + "_sha2.sha256", + "_hashlib.openssl_sha256", + "hashlib.sha256", + ), + _HashId.sha384: _HashInfo( + _HashId.sha384, + "_sha2.SHA384Type", + "_hashlib.HASH", + "_sha2.sha384", + "_hashlib.openssl_sha384", + "hashlib.sha384", + ), + _HashId.sha512: _HashInfo( + _HashId.sha512, + "_sha2.SHA512Type", + "_hashlib.HASH", + "_sha2.sha512", + "_hashlib.openssl_sha512", + "hashlib.sha512", + ), + _HashId.sha3_224: _HashInfo( + _HashId.sha3_224, + "_sha3.sha3_224", + "_hashlib.HASH", + "_sha3.sha3_224", + "_hashlib.openssl_sha3_224", + "hashlib.sha3_224", + ), + _HashId.sha3_256: _HashInfo( + _HashId.sha3_256, + "_sha3.sha3_256", + "_hashlib.HASH", + "_sha3.sha3_256", + "_hashlib.openssl_sha3_256", + "hashlib.sha3_256", + ), + _HashId.sha3_384: _HashInfo( + _HashId.sha3_384, + "_sha3.sha3_384", + "_hashlib.HASH", + "_sha3.sha3_384", + "_hashlib.openssl_sha3_384", + "hashlib.sha3_384", + ), + _HashId.sha3_512: _HashInfo( + _HashId.sha3_512, + "_sha3.sha3_512", + "_hashlib.HASH", + "_sha3.sha3_512", + "_hashlib.openssl_sha3_512", + "hashlib.sha3_512", + ), + _HashId.shake_128: _HashInfo( + _HashId.shake_128, + "_sha3.shake_128", + "_hashlib.HASHXOF", + "_sha3.shake_128", + "_hashlib.openssl_shake_128", + "hashlib.shake_128", + ), + _HashId.shake_256: _HashInfo( + _HashId.shake_256, + "_sha3.shake_256", + "_hashlib.HASHXOF", + "_sha3.shake_256", + "_hashlib.openssl_shake_256", + "hashlib.shake_256", + ), + _HashId.blake2s: _HashInfo( + _HashId.blake2s, + "_blake2.blake2s", + "_hashlib.HASH", + "_blake2.blake2s", + None, + "hashlib.blake2s", + ), + _HashId.blake2b: _HashInfo( + _HashId.blake2b, + "_blake2.blake2b", + "_hashlib.HASH", + "_blake2.blake2b", + None, + "hashlib.blake2b", + ), +}) +assert _HASHINFO_DATABASE.keys() == CANONICAL_DIGEST_NAMES + + +def get_hash_type_info(name): + info = _HASHINFO_DATABASE[name] + assert isinstance(info, _HashInfo), info + return info.type + + +def get_hash_func_info(name): + info = _HASHINFO_DATABASE[name] + assert isinstance(info, _HashInfo), info + return info.func + + +def _iter_hash_func_info(excluded): + for name, info in _HASHINFO_DATABASE.items(): + if name not in excluded: + yield info.func + + +# Mapping from canonical hash names to their explicit HACL* HMAC constructor. +# There is currently no OpenSSL one-shot named function and there will likely +# be none in the future. +_HMACINFO_DATABASE = { + _HashId(canonical_name): _HashInfoItem(f"_hmac.compute_{canonical_name}") + for canonical_name in CANONICAL_DIGEST_NAMES +} +# Neither HACL* nor OpenSSL supports HMAC over XOFs. +_HMACINFO_DATABASE[_HashId.shake_128] = _HashInfoItem() +_HMACINFO_DATABASE[_HashId.shake_256] = _HashInfoItem() +# Strictly speaking, HMAC-BLAKE is meaningless as BLAKE2 is already a +# keyed hash function. However, as it's exposed by HACL*, we test it. +_HMACINFO_DATABASE[_HashId.blake2s] = _HashInfoItem('_hmac.compute_blake2s_32') +_HMACINFO_DATABASE[_HashId.blake2b] = _HashInfoItem('_hmac.compute_blake2b_32') +_HMACINFO_DATABASE = frozendict(_HMACINFO_DATABASE) +assert _HMACINFO_DATABASE.keys() == CANONICAL_DIGEST_NAMES + + +def get_hmac_item_info(name): + info = _HMACINFO_DATABASE[name] + assert isinstance(info, _HashInfoItem), info + return info + + +def _decorate_func_or_class(decorator_func, func_or_class): if not isinstance(func_or_class, type): return decorator_func(func_or_class) @@ -57,114 +527,225 @@ def setUpClass(cls): return decorated_class -def requires_hashdigest(digestname, openssl=None, usedforsecurity=True): - """Decorator raising SkipTest if a hashing algorithm is not available. +def _chain_decorators(decorators): + """Obtain a decorator by chaining multiple decorators. - The hashing algorithm may be missing, blocked by a strict crypto policy, - or Python may be configured with `--with-builtin-hashlib-hashes=no`. + The decorators are applied in the order they are given. + """ + def decorator_func(func): + return functools.reduce(lambda w, deco: deco(w), decorators, func) + return functools.partial(_decorate_func_or_class, decorator_func) - If 'openssl' is True, then the decorator checks that OpenSSL provides - the algorithm. Otherwise the check falls back to (optional) built-in - HACL* implementations. - The usedforsecurity flag is passed to the constructor but has no effect - on HACL* implementations. +def _ensure_wrapper_signature(wrapper, wrapped): + """Ensure that a wrapper has the same signature as the wrapped function. - Examples of exceptions being suppressed: - ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS - ValueError: unsupported hash type md4 + This is used to guarantee that a TypeError raised due to a bad API call + is raised consistently (using variadic signatures would hide such errors). """ - if openssl and _hashlib is not None: - def test_availability(): - _hashlib.new(digestname, usedforsecurity=usedforsecurity) - else: - def test_availability(): - hashlib.new(digestname, usedforsecurity=usedforsecurity) + try: + wrapped_sig = inspect.signature(wrapped) + except ValueError: # built-in signature cannot be found + return + + wrapper_sig = inspect.signature(wrapper) + if wrapped_sig != wrapper_sig: + fullname = f"{wrapped.__module__}.{wrapped.__qualname__}" + raise AssertionError( + f"signature for {fullname}() is incorrect:\n" + f" expect: {wrapped_sig}\n" + f" actual: {wrapper_sig}" + ) + +def _make_conditional_decorator(test, /, *test_args, **test_kwargs): def decorator_func(func): @functools.wraps(func) def wrapper(*args, **kwargs): - try: - test_availability() - except ValueError as exc: - _missing_hash(digestname, exc=exc) + test(*test_args, **test_kwargs) return func(*args, **kwargs) return wrapper + return functools.partial(_decorate_func_or_class, decorator_func) - def decorator(func_or_class): - return _decorate_func_or_class(func_or_class, decorator_func) - return decorator +def requires_openssl_hashlib(): + _hashlib = _import_module("_hashlib") + return unittest.skipIf(_hashlib is None, "requires _hashlib") -def requires_openssl_hashdigest(digestname, *, usedforsecurity=True): - """Decorator raising SkipTest if an OpenSSL hashing algorithm is missing. - The hashing algorithm may be missing or blocked by a strict crypto policy. - """ - def decorator_func(func): - @requires_hashlib() # avoid checking at each call - @functools.wraps(func) - def wrapper(*args, **kwargs): - _openssl_availabillity(digestname, usedforsecurity=usedforsecurity) - return func(*args, **kwargs) - return wrapper +def requires_builtin_hmac(): + _hmac = _import_module("_hmac") + return unittest.skipIf(_hmac is None, "requires _hmac") + + +class SkipNoHash(unittest.SkipTest): + """A SkipTest exception raised when a hash is not available.""" + + def __init__(self, digestname, implementation=None, reason=None): + parts = ["missing", implementation, f"hash algorithm {digestname!r}"] + if reason is not None: + parts.insert(0, f"{reason}: ") + super().__init__(" ".join(filter(None, parts))) + - def decorator(func_or_class): - return _decorate_func_or_class(func_or_class, decorator_func) - return decorator +class SkipNoHashInCall(SkipNoHash): + def __init__(self, func, digestname, implementation=None): + super().__init__(digestname, implementation, f"cannot use {func}") -def find_openssl_hashdigest_constructor(digestname, *, usedforsecurity=True): - """Find the OpenSSL hash function constructor by its name.""" + +def _hashlib_new(digestname, openssl, /, **kwargs): + """Check availability of [hashlib|_hashlib].new(digestname, **kwargs). + + If *openssl* is True, module is "_hashlib" (C extension module), + otherwise it is "hashlib" (pure Python interface). + + The constructor function is returned (without binding **kwargs), + or SkipTest is raised if none exists. + """ assert isinstance(digestname, str), digestname - _openssl_availabillity(digestname, usedforsecurity=usedforsecurity) - # This returns a function of the form _hashlib.openssl_ and - # not a lambda function as it is rejected by _hashlib.hmac_new(). - return getattr(_hashlib, f"openssl_{digestname}") + # Re-import 'hashlib' in case it was mocked, but propagate + # exceptions as it should be unconditionally available. + hashlib = importlib.import_module("hashlib") + # re-import '_hashlib' in case it was mocked + _hashlib = _import_module("_hashlib") + module = _hashlib if openssl and _hashlib is not None else hashlib + try: + module.new(digestname, **kwargs) + except ValueError as exc: + raise SkipNoHashInCall(f"{module.__name__}.new", digestname) from exc + return functools.partial(module.new, digestname) -def requires_builtin_hashdigest( - module_name, digestname, *, usedforsecurity=True -): - """Decorator raising SkipTest if a HACL* hashing algorithm is missing. +def _builtin_hash(module_name, digestname, /, **kwargs): + """Check availability of .(**kwargs). - The *module_name* is the C extension module name based on HACL*. - The *digestname* is one of its member, e.g., 'md5'. + + The constructor function is returned, or SkipTest is raised if none exists. """ - def decorator_func(func): - @functools.wraps(func) - def wrapper(*args, **kwargs): - module = import_module(module_name) - try: - getattr(module, digestname) - except AttributeError: - fullname = f'{module_name}.{digestname}' - _missing_hash(fullname, implementation="HACL") - return func(*args, **kwargs) - return wrapper + assert isinstance(module_name, str), module_name + assert isinstance(digestname, str), digestname + fullname = f'{module_name}.{digestname}' + try: + builtin_module = importlib.import_module(module_name) + except ImportError as exc: + raise SkipNoHash(fullname, "builtin") from exc + try: + constructor = getattr(builtin_module, digestname) + except AttributeError as exc: + raise SkipNoHash(fullname, "builtin") from exc + try: + constructor(**kwargs) + except ValueError as exc: + raise SkipNoHash(fullname, "builtin") from exc + return constructor - def decorator(func_or_class): - return _decorate_func_or_class(func_or_class, decorator_func) - return decorator +def _openssl_new(digestname, /, **kwargs): + """Check availability of _hashlib.new(digestname, **kwargs). -def find_builtin_hashdigest_constructor( - module_name, digestname, *, usedforsecurity=True -): - """Find the HACL* hash function constructor. + The constructor function is returned (without binding **kwargs), + or SkipTest is raised if none exists. + """ + assert isinstance(digestname, str), digestname + try: + # re-import '_hashlib' in case it was mocked + _hashlib = importlib.import_module("_hashlib") + except ImportError as exc: + raise SkipNoHash(digestname, "openssl") from exc + try: + _hashlib.new(digestname, **kwargs) + except ValueError as exc: + raise SkipNoHashInCall("_hashlib.new", digestname) from exc + return functools.partial(_hashlib.new, digestname) - - The *module_name* is the C extension module name based on HACL*. - - The *digestname* is one of its member, e.g., 'md5'. + +def _openssl_hash(digestname, /, **kwargs): + """Check availability of _hashlib.openssl_(**kwargs). + + The constructor function is returned (without binding **kwargs), + or SkipTest is raised if none exists. """ - module = import_module(module_name) + assert isinstance(digestname, str), digestname + method_name = f"openssl_{digestname}" + fullname = f"_hashlib.{method_name}" + try: + # re-import '_hashlib' in case it was mocked + _hashlib = importlib.import_module("_hashlib") + except ImportError as exc: + raise SkipNoHash(fullname, "openssl") from exc try: - constructor = getattr(module, digestname) - constructor(b'', usedforsecurity=usedforsecurity) - except (AttributeError, TypeError, ValueError): - _missing_hash(f'{module_name}.{digestname}', implementation="HACL") + constructor = getattr(_hashlib, method_name) + except AttributeError as exc: + raise SkipNoHash(fullname, "openssl") from exc + try: + constructor(**kwargs) + except ValueError as exc: + raise SkipNoHash(fullname, "openssl") from exc return constructor +def requires_hashdigest(digestname, openssl=None, *, usedforsecurity=True): + """Decorator raising SkipTest if a hashing algorithm is not available. + + The hashing algorithm may be missing, blocked by a strict crypto policy, + or Python may be configured with `--with-builtin-hashlib-hashes=no`. + + If 'openssl' is True, then the decorator checks that OpenSSL provides + the algorithm. Otherwise the check falls back to (optional) built-in + HACL* implementations. + + The usedforsecurity flag is passed to the constructor but has no effect + on HACL* implementations. + + Examples of exceptions being suppressed: + ValueError: [digital envelope routines: EVP_DigestInit_ex] disabled for FIPS + ValueError: unsupported hash type md4 + """ + return _make_conditional_decorator( + _hashlib_new, digestname, openssl, usedforsecurity=usedforsecurity + ) + + +def requires_openssl_hashdigest(digestname, *, usedforsecurity=True): + """Decorator raising SkipTest if an OpenSSL hashing algorithm is missing. + + The hashing algorithm may be missing or blocked by a strict crypto policy. + """ + return _make_conditional_decorator( + _openssl_new, digestname, usedforsecurity=usedforsecurity + ) + + +def _make_requires_builtin_hashdigest_decorator(item, *, usedforsecurity=True): + assert isinstance(item, _HashInfoItem), item + return _make_conditional_decorator( + _builtin_hash, + item.module_name, + item.member_name, + usedforsecurity=usedforsecurity, + ) + + +def requires_builtin_hashdigest(canonical_name, *, usedforsecurity=True): + """Decorator raising SkipTest if a HACL* hashing algorithm is missing.""" + info = get_hash_func_info(canonical_name) + return _make_requires_builtin_hashdigest_decorator( + info.builtin, usedforsecurity=usedforsecurity + ) + + +def requires_builtin_hashes(*, exclude=(), usedforsecurity=True): + """Decorator raising SkipTest if one HACL* hashing algorithm is missing.""" + return _chain_decorators(( + _make_requires_builtin_hashdigest_decorator( + info.builtin, usedforsecurity=usedforsecurity + ) for info in _iter_hash_func_info(exclude) + )) + + class HashFunctionsTrait: """Mixin trait class containing hash functions. @@ -178,59 +759,31 @@ class HashFunctionsTrait: implementation of HMAC). """ - ALGORITHMS = [ - 'md5', 'sha1', - 'sha224', 'sha256', 'sha384', 'sha512', - 'sha3_224', 'sha3_256', 'sha3_384', 'sha3_512', - ] - - # Default 'usedforsecurity' to use when looking up a hash function. + # Default 'usedforsecurity' to use when checking a hash function. + # When the trait properties are callables (e.g., _md5.md5) and + # not strings, they must be called with the same 'usedforsecurity'. usedforsecurity = True - def _find_constructor(self, name): - # By default, a missing algorithm skips the test that uses it. - self.assertIn(name, self.ALGORITHMS) - self.skipTest(f"missing hash function: {name}") - - @property - def md5(self): - return self._find_constructor("md5") + def is_valid_digest_name(self, digestname): + self.assertIn(digestname, _HashId) - @property - def sha1(self): - return self._find_constructor("sha1") - - @property - def sha224(self): - return self._find_constructor("sha224") - - @property - def sha256(self): - return self._find_constructor("sha256") - - @property - def sha384(self): - return self._find_constructor("sha384") - - @property - def sha512(self): - return self._find_constructor("sha512") - - @property - def sha3_224(self): - return self._find_constructor("sha3_224") + def _find_constructor(self, digestname): + # By default, a missing algorithm skips the test that uses it. + self.is_valid_digest_name(digestname) + self.skipTest(f"missing hash function: {digestname}") - @property - def sha3_256(self): - return self._find_constructor("sha3_256") + md5 = property(lambda self: self._find_constructor("md5")) + sha1 = property(lambda self: self._find_constructor("sha1")) - @property - def sha3_384(self): - return self._find_constructor("sha3_384") + sha224 = property(lambda self: self._find_constructor("sha224")) + sha256 = property(lambda self: self._find_constructor("sha256")) + sha384 = property(lambda self: self._find_constructor("sha384")) + sha512 = property(lambda self: self._find_constructor("sha512")) - @property - def sha3_512(self): - return self._find_constructor("sha3_512") + sha3_224 = property(lambda self: self._find_constructor("sha3_224")) + sha3_256 = property(lambda self: self._find_constructor("sha3_256")) + sha3_384 = property(lambda self: self._find_constructor("sha3_384")) + sha3_512 = property(lambda self: self._find_constructor("sha3_512")) class NamedHashFunctionsTrait(HashFunctionsTrait): @@ -239,9 +792,9 @@ class NamedHashFunctionsTrait(HashFunctionsTrait): Hash functions are available if and only if they are available in hashlib. """ - def _find_constructor(self, name): - self.assertIn(name, self.ALGORITHMS) - return name + def _find_constructor(self, digestname): + self.is_valid_digest_name(digestname) + return str(digestname) # ensure that we are an exact string class OpenSSLHashFunctionsTrait(HashFunctionsTrait): @@ -250,11 +803,11 @@ class OpenSSLHashFunctionsTrait(HashFunctionsTrait): Hash functions are available if and only if they are available in _hashlib. """ - def _find_constructor(self, name): - self.assertIn(name, self.ALGORITHMS) - return find_openssl_hashdigest_constructor( - name, usedforsecurity=self.usedforsecurity - ) + def _find_constructor(self, digestname): + self.is_valid_digest_name(digestname) + # This returns a function of the form _hashlib.openssl_ and + # not a lambda function as it is rejected by _hashlib.hmac_new(). + return _openssl_hash(digestname, usedforsecurity=self.usedforsecurity) class BuiltinHashFunctionsTrait(HashFunctionsTrait): @@ -265,65 +818,278 @@ class BuiltinHashFunctionsTrait(HashFunctionsTrait): is not since the former is unconditionally built. """ - def _find_constructor_in(self, module, name): - self.assertIn(name, self.ALGORITHMS) - return find_builtin_hashdigest_constructor(module, name) + def _find_constructor(self, digestname): + self.is_valid_digest_name(digestname) + info = get_hash_func_info(digestname) + return _builtin_hash( + info.builtin.module_name, + info.builtin.member_name, + usedforsecurity=self.usedforsecurity, + ) - @property - def md5(self): - return self._find_constructor_in("_md5", "md5") - @property - def sha1(self): - return self._find_constructor_in("_sha1", "sha1") +def find_gil_minsize(modules_names, default=2048): + """Get the largest GIL_MINSIZE value for the given cryptographic modules. - @property - def sha224(self): - return self._find_constructor_in("_sha2", "sha224") + The valid module names are the following: - @property - def sha256(self): - return self._find_constructor_in("_sha2", "sha256") + - _hashlib + - _md5, _sha1, _sha2, _sha3, _blake2 + - _hmac + """ + sizes = [] + for module_name in modules_names: + module = _import_module(module_name) + if module is not None: + sizes.append(getattr(module, '_GIL_MINSIZE', default)) + return max(sizes, default=default) - @property - def sha384(self): - return self._find_constructor_in("_sha2", "sha384") - @property - def sha512(self): - return self._find_constructor_in("_sha2", "sha512") +def _block_openssl_hash_new(blocked_name): + """Block OpenSSL implementation of _hashlib.new().""" + assert isinstance(blocked_name, str), blocked_name - @property - def sha3_224(self): - return self._find_constructor_in("_sha3", "sha3_224") + # re-import '_hashlib' in case it was mocked + if (_hashlib := _import_module("_hashlib")) is None: + return contextlib.nullcontext() - @property - def sha3_256(self): - return self._find_constructor_in("_sha3","sha3_256") + @functools.wraps(wrapped := _hashlib.new) + def _hashlib_new(name, data=b'', *, usedforsecurity=True, string=None): + if name == blocked_name: + raise _hashlib.UnsupportedDigestmodError(blocked_name) + return wrapped(name, data, + usedforsecurity=usedforsecurity, string=string) - @property - def sha3_384(self): - return self._find_constructor_in("_sha3","sha3_384") + _ensure_wrapper_signature(_hashlib_new, wrapped) + return unittest.mock.patch('_hashlib.new', _hashlib_new) - @property - def sha3_512(self): - return self._find_constructor_in("_sha3","sha3_512") +def _block_openssl_hmac_new(blocked_name): + """Block OpenSSL HMAC-HASH implementation.""" + assert isinstance(blocked_name, str), blocked_name -def find_gil_minsize(modules_names, default=2048): - """Get the largest GIL_MINSIZE value for the given cryptographic modules. + # re-import '_hashlib' in case it was mocked + if (_hashlib := _import_module("_hashlib")) is None: + return contextlib.nullcontext() - The valid module names are the following: + @functools.wraps(wrapped := _hashlib.hmac_new) + def wrapper(key, msg=b'', digestmod=None): + if digestmod == blocked_name: + raise _hashlib.UnsupportedDigestmodError(blocked_name) + return wrapped(key, msg, digestmod) - - _hashlib - - _md5, _sha1, _sha2, _sha3, _blake2 - - _hmac + _ensure_wrapper_signature(wrapper, wrapped) + return unittest.mock.patch('_hashlib.hmac_new', wrapper) + + +def _block_openssl_hmac_digest(blocked_name): + """Block OpenSSL HMAC-HASH one-shot digest implementation.""" + assert isinstance(blocked_name, str), blocked_name + + # re-import '_hashlib' in case it was mocked + if (_hashlib := _import_module("_hashlib")) is None: + return contextlib.nullcontext() + + @functools.wraps(wrapped := _hashlib.hmac_digest) + def _hashlib_hmac_digest(key, msg, digest): + if digest == blocked_name: + raise _hashlib.UnsupportedDigestmodError(blocked_name) + return wrapped(key, msg, digest) + + _ensure_wrapper_signature(_hashlib_hmac_digest, wrapped) + return unittest.mock.patch('_hashlib.hmac_digest', _hashlib_hmac_digest) + + +def _block_builtin_hash_new(name): + """Block a buitin-in hash name from the hashlib.new() interface.""" + assert isinstance(name, str), name + assert name.lower() == name, f"invalid name: {name}" + assert name in _HashId, f"invalid hash: {name}" + + # Re-import 'hashlib' in case it was mocked + hashlib = importlib.import_module('hashlib') + builtin_constructor_cache = getattr(hashlib, '__builtin_constructor_cache') + builtin_constructor_cache_mock = builtin_constructor_cache.copy() + builtin_constructor_cache_mock.pop(name, None) + builtin_constructor_cache_mock.pop(name.upper(), None) + + # __get_builtin_constructor() imports the HACL* modules on demand, + # so we need to block the possibility of importing it, but only + # during the call to __get_builtin_constructor(). + get_builtin_constructor = getattr(hashlib, '__get_builtin_constructor') + builtin_module_name = get_hash_func_info(name).builtin.module_name + + @functools.wraps(get_builtin_constructor) + def get_builtin_constructor_mock(name): + with import_helper.isolated_modules(): + sys = importlib.import_module("sys") + sys.modules[builtin_module_name] = None # block module's import + return get_builtin_constructor(name) + + return unittest.mock.patch.multiple( + hashlib, + __get_builtin_constructor=get_builtin_constructor_mock, + __builtin_constructor_cache=builtin_constructor_cache_mock, + ) + + +def _block_builtin_hmac_new(blocked_name): + assert isinstance(blocked_name, str), blocked_name + + # re-import '_hmac' in case it was mocked + if (_hmac := _import_module("_hmac")) is None: + return contextlib.nullcontext() + + @functools.wraps(wrapped := _hmac.new) + def _hmac_new(key, msg=None, digestmod=None): + if digestmod == blocked_name: + raise _hmac.UnknownHashError(blocked_name) + return wrapped(key, msg, digestmod) + + _ensure_wrapper_signature(_hmac_new, wrapped) + return unittest.mock.patch('_hmac.new', _hmac_new) + + +def _block_builtin_hmac_digest(blocked_name): + assert isinstance(blocked_name, str), blocked_name + + # re-import '_hmac' in case it was mocked + if (_hmac := _import_module("_hmac")) is None: + return contextlib.nullcontext() + + @functools.wraps(wrapped := _hmac.compute_digest) + def _hmac_compute_digest(key, msg, digest): + if digest == blocked_name: + raise _hmac.UnknownHashError(blocked_name) + return wrapped(key, msg, digest) + + _ensure_wrapper_signature(_hmac_compute_digest, wrapped) + return unittest.mock.patch('_hmac.compute_digest', _hmac_compute_digest) + + +def _make_hash_constructor_blocker(name, dummy, implementation): + info = get_hash_func_info(name)[implementation] + if (wrapped := info.import_member()) is None: + # function shouldn't exist for this implementation + return contextlib.nullcontext() + wrapper = functools.wraps(wrapped)(dummy) + _ensure_wrapper_signature(wrapper, wrapped) + return unittest.mock.patch(info.fullname, wrapper) + + +def _block_hashlib_hash_constructor(name): + """Block explicit public constructors.""" + def dummy(data=b'', *, usedforsecurity=True, string=None): + raise ValueError(f"blocked explicit public hash name: {name}") + return _make_hash_constructor_blocker(name, dummy, 'hashlib') + + +def _block_openssl_hash_constructor(name): + """Block explicit OpenSSL constructors.""" + def dummy(data=b'', *, usedforsecurity=True, string=None): + raise ValueError(f"blocked explicit OpenSSL hash name: {name}") + return _make_hash_constructor_blocker(name, dummy, 'openssl') + + +def _block_builtin_hash_constructor(name): + """Block explicit HACL* constructors.""" + def dummy(data=b'', *, usedforsecurity=True, string=b''): + raise ValueError(f"blocked explicit builtin hash name: {name}") + return _make_hash_constructor_blocker(name, dummy, 'builtin') + + +def _block_builtin_hmac_constructor(name): + """Block explicit HACL* HMAC constructors.""" + info = get_hmac_item_info(name) + assert info.module_name is None or info.module_name == "_hmac", info + if (wrapped := info.import_member()) is None: + # function shouldn't exist for this implementation + return contextlib.nullcontext() + + @functools.wraps(wrapped) + def wrapper(key, obj): + raise ValueError(f"blocked hash name: {name}") + + _ensure_wrapper_signature(wrapper, wrapped) + return unittest.mock.patch(info.fullname, wrapper) + + +@contextlib.contextmanager +def block_algorithm(name, *, allow_openssl=False, allow_builtin=False): + """Block a hash algorithm for both hashing and HMAC. + + Be careful with this helper as a function may be allowed, but can + still raise a ValueError at runtime if the OpenSSL security policy + disables it, e.g., if allow_openssl=True and FIPS mode is on. """ - sizes = [] - for module_name in modules_names: - try: - module = importlib.import_module(module_name) - except ImportError: - continue - sizes.append(getattr(module, '_GIL_MINSIZE', default)) - return max(sizes, default=default) + with contextlib.ExitStack() as stack: + if not (allow_openssl or allow_builtin): + # Named constructors have a different behavior in the sense + # that they are either built-ins or OpenSSL ones, but not + # "agile" ones (namely once "hashlib" has been imported, + # they are fixed). + # + # If OpenSSL is not available, hashes fall back to built-in ones, + # in which case we don't need to block the explicit public hashes + # as they will call a mocked one. + # + # If OpenSSL is available, hashes fall back to "openssl_*" ones, + # except for BLAKE2b and BLAKE2s. + stack.enter_context(_block_hashlib_hash_constructor(name)) + elif ( + # In FIPS mode, hashlib.() functions may raise if they use + # the OpenSSL implementation, except with usedforsecurity=False. + # However, blocking such functions also means blocking them + # so we again need to block them if we want to. + (_hashlib := _import_module("_hashlib")) + and _hashlib.get_fips_mode() + and not allow_openssl + ) or ( + # Without OpenSSL, hashlib.() functions are aliases + # to built-in functions, so both of them must be blocked + # as the module may have been imported before the HACL ones. + not (_hashlib := _import_module("_hashlib")) + and not allow_builtin + ): + stack.enter_context(_block_hashlib_hash_constructor(name)) + + if not allow_openssl: + # _hashlib.new() + stack.enter_context(_block_openssl_hash_new(name)) + # _hashlib.openssl_*() + stack.enter_context(_block_openssl_hash_constructor(name)) + # _hashlib.hmac_new() + stack.enter_context(_block_openssl_hmac_new(name)) + # _hashlib.hmac_digest() + stack.enter_context(_block_openssl_hmac_digest(name)) + + if not allow_builtin: + # __get_builtin_constructor(name) + stack.enter_context(_block_builtin_hash_new(name)) + # .() + stack.enter_context(_block_builtin_hash_constructor(name)) + # _hmac.new(..., name) + stack.enter_context(_block_builtin_hmac_new(name)) + # _hmac.compute_() + stack.enter_context(_block_builtin_hmac_constructor(name)) + # _hmac.compute_digest(..., name) + stack.enter_context(_block_builtin_hmac_digest(name)) + yield + + +@contextlib.contextmanager +def block_openssl_algorithms(*, exclude=()): + """Block OpenSSL implementations, except those given in *exclude*.""" + with contextlib.ExitStack() as stack: + for name in CANONICAL_DIGEST_NAMES.difference(exclude): + stack.enter_context(block_algorithm(name, allow_builtin=True)) + yield + + +@contextlib.contextmanager +def block_builtin_algorithms(*, exclude=()): + """Block HACL* implementations, except those given in *exclude*.""" + with contextlib.ExitStack() as stack: + for name in CANONICAL_DIGEST_NAMES.difference(exclude): + stack.enter_context(block_algorithm(name, allow_openssl=True)) + yield diff --git a/Lib/test/support/import_helper.py b/Lib/test/support/import_helper.py index 4c7eac0b7eb..e8a3d176ad6 100644 --- a/Lib/test/support/import_helper.py +++ b/Lib/test/support/import_helper.py @@ -4,6 +4,7 @@ import importlib.machinery import importlib.util import os +import py_compile import shutil import sys import textwrap @@ -49,20 +50,31 @@ def forget(modname): # combinations of PEP 3147/488 and legacy pyc files. unlink(source + 'c') for opt in ('', 1, 2): - unlink(importlib.util.cache_from_source(source, optimization=opt)) + try: + unlink(importlib.util.cache_from_source(source, optimization=opt)) + except NotImplementedError: + pass -def make_legacy_pyc(source): +def make_legacy_pyc(source, allow_compile=False): """Move a PEP 3147/488 pyc file to its legacy pyc location. :param source: The file system path to the source file. The source file - does not need to exist, however the PEP 3147/488 pyc file must exist. + does not need to exist, however the PEP 3147/488 pyc file must exist or + allow_compile must be set. + :param allow_compile: If True, uses py_compile to create a .pyc if it does + not exist. This should be passed as True if cache_tag may be None. :return: The file system path to the legacy pyc file. """ - pyc_file = importlib.util.cache_from_source(source) assert source.endswith('.py') legacy_pyc = source + 'c' - shutil.move(pyc_file, legacy_pyc) + try: + pyc_file = importlib.util.cache_from_source(source) + shutil.move(pyc_file, legacy_pyc) + except FileNotFoundError, NotImplementedError: + if not allow_compile: + raise + py_compile.compile(source, legacy_pyc, doraise=True) return legacy_pyc @@ -313,7 +325,7 @@ def ready_to_import(name=None, source=""): sys.modules.pop(name, None) -def ensure_lazy_imports(imported_module, modules_to_block): +def ensure_lazy_imports(imported_module, modules_to_block, *, additional_code=None): """Test that when imported_module is imported, none of the modules in modules_to_block are imported as a side effect.""" modules_to_block = frozenset(modules_to_block) @@ -331,6 +343,16 @@ def ensure_lazy_imports(imported_module, modules_to_block): raise AssertionError(f'unexpectedly imported after importing {imported_module}: {{after}}') """ ) + if additional_code: + script += additional_code + script += textwrap.dedent( + f""" + if unexpected := modules_to_block & sys.modules.keys(): + after = ", ".join(unexpected) + raise AssertionError(f'unexpectedly imported after additional code: {{after}}') + """ + ) + from .script_helper import assert_python_ok assert_python_ok("-S", "-c", script) diff --git a/Lib/test/support/isolation.py b/Lib/test/support/isolation.py index bc2189329c0..e6cc41cdafa 100644 --- a/Lib/test/support/isolation.py +++ b/Lib/test/support/isolation.py @@ -78,7 +78,11 @@ def _decode(data): def _remote(detail): # Wrap the subprocess traceback the way concurrent.futures does, so it is - # clearly delimited when shown as the cause. + # clearly delimited when shown as the cause. Return None if the subprocess + # said nothing (a hung one usually does not), so that "raise ... from None" + # suppresses an empty cause. + if not detail: + return None return _RemoteTraceback(f'\n"""\n{detail}"""') @@ -90,38 +94,151 @@ def _check_subprocess_support(): raise unittest.SkipTest('requires subprocess support') -def _run_in_subprocess(module, qualname): - """Run module.qualname (a test method or class) in a fresh subprocess. +def _child_environ(env): + # Start from the inherited environment, so that *env* only has to name what + # the test changes. + if not env: + return None + environ = dict(os.environ) + for name, value in env.items(): + if value is None: + environ.pop(name, None) + else: + environ[name] = value + return environ + + +class _SubprocessTest: + """A test running in a subprocess, started by _start_test(). - Return ``(payload, output, returncode)``, where *payload* is the decoded - ``{'outcomes': ..., 'durations': ...}`` mapping from the subprocess, or - ``None`` if it did not run to completion (crash, import error, ...). + The parent can watch the subprocess (its pid) while the test runs, and + must wait() for it. + """ + + def __init__(self, proc, result_path, stdout, stderr): + self._proc = proc + self._result_path = result_path + self._stdout = stdout + self._stderr = stderr + + def _read_output(self): + def snapshot(stream): + # A descendant may still write. Snapshot only the current extent, + # without moving the shared writer offset or waiting for pipe EOF. + stream.flush() + size = os.fstat(stream.fileno()).st_size + if os.name == 'nt': + # TemporaryFile is a named, delete-on-close file on Windows. + # Reopening with O_TEMPORARY shares deletion permission and + # gives the reader an independent file position. + def opener(path, flags): + return os.open(path, flags | os.O_TEMPORARY | os.O_BINARY) + with open(stream.name, 'rb', opener=opener) as reader: + data = reader.read(size) + else: + data = os.pread(stream.fileno(), size, 0) + return _decode(data) + return snapshot(self._stdout) + snapshot(self._stderr) + + @property + def pid(self): + return self._proc.pid + + def wait(self, timeout=None, tick=None, interval=1.0): + """Wait for the test to finish, calling *tick* every *interval* seconds. + + Return ``(payload, output, returncode)``, where *payload* is the + decoded ``{'outcomes': ..., 'durations': ...}`` mapping from the + subprocess, or ``None`` if it did not run to completion (crash, + import error, ...). + """ + import marshal + import subprocess + import time + deadline = None if timeout is None else time.monotonic() + timeout + try: + while True: + step = None if deadline is None else max( + 0.0, deadline - time.monotonic()) + # Wake up for the next tick, unless the timeout comes first. + ticking = tick is not None and (step is None or step > interval) + try: + # Output goes to temporary files, so a full pipe cannot + # block the worker, and inherited handles cannot hold up + # the parent after the worker exits. + self._proc.wait(timeout=interval if ticking else step) + break + except subprocess.TimeoutExpired: + if ticking: + tick() + continue + # Report the hang rather than leaving the runner stuck. + self._proc.kill() + self._proc.wait() + raise _SubprocessTestError( + f'test did not complete in a subprocess ' + f'within {timeout} seconds' + ) from _remote(self._read_output()) + try: + with open(self._result_path, 'rb') as f: + payload = marshal.load(f) + except (OSError, EOFError, ValueError): + payload = None + return payload, self._read_output(), self._proc.returncode + except BaseException: + # Also cover KeyboardInterrupt and exceptions raised by tick(). + # Reap only our direct worker; do not change its session or kill + # unrelated descendants belonging to the test. + if self._proc.poll() is None: + self._proc.kill() + self._proc.wait() + raise + finally: + self._stdout.close() + self._stderr.close() + try: + os.unlink(self._result_path) + except OSError: + pass + + +def _start_test(module, qualname, options=(), env=None): + """Start module.qualname (a test method or class) in a fresh subprocess. + + Return a _SubprocessTest. Its wait() is what removes the temporary file + the subprocess writes its result to. """ import marshal import subprocess import tempfile fd, result_path = tempfile.mkstemp(suffix='.json') os.close(fd) + stdout = stderr = None try: + stdout = tempfile.TemporaryFile() + stderr = tempfile.TemporaryFile() # Pass the config on the command line, not in the environment, so that - # the test cannot pass it on to the processes it spawns itself. Use - # marshal, not json: it is built in, so the child imports nothing that - # the test would not see in a normal test run. - cmd = [sys.executable, '-m', 'test.support.subprocess_runner', + # the test cannot pass it on to the processes it spawns itself, and so + # that it survives the -E and -I options. Use marshal, not json: it is + # built in, so the child imports nothing that the test would not see in + # a normal test run. + cmd = [sys.executable, *options, '-m', 'test.support.subprocess_runner', module, qualname, result_path, marshal.dumps(_child_config()).hex()] - proc = subprocess.run(cmd, capture_output=True) - try: - with open(result_path, 'rb') as f: - payload = marshal.load(f) - except (OSError, EOFError, ValueError): - payload = None - finally: + proc = subprocess.Popen(cmd, stdout=stdout, + stderr=stderr, env=_child_environ(env)) + except BaseException: + if stdout is not None: + stdout.close() + if stderr is not None: + stderr.close() try: os.unlink(result_path) except OSError: pass - return payload, _decode(proc.stdout) + _decode(proc.stderr), proc.returncode + raise + return _SubprocessTest(proc, result_path, stdout, stderr) + def _replay_outcome(test, outcome): @@ -173,7 +290,20 @@ def _check_returncode(returncode, output, what): raise exc from _remote(output) -def _isolate_method(func): +def _replay_test(test, payload, output, returncode): + """Reproduce in *test* the result that _SubprocessTest.wait() returned.""" + if payload is None: + exc = _SubprocessTestError( + f'test did not complete in a subprocess (exit code {returncode})') + raise exc from _remote(output) + # The parent measures the test method's own duration (the real cost of the + # isolated run, subprocess startup included), so nothing to forward here. + # Replay the outcomes first: a failure of the test itself is more useful. + _replay_outcomes(test, payload['outcomes']) + _check_returncode(returncode, output, 'test') + + +def _isolate_method(func, options, env, timeout): @functools.wraps(func) def wrapper(self, /, *args, **kwargs): if runningInSubprocess: @@ -182,21 +312,12 @@ def wrapper(self, /, *args, **kwargs): _check_subprocess_support() cls = type(self) qualname = f'{cls.__qualname__}.{func.__name__}' - payload, output, returncode = _run_in_subprocess(cls.__module__, - qualname) - if payload is None: - exc = _SubprocessTestError( - f'test did not complete in a subprocess (exit code {returncode})') - raise exc from _remote(output) - # The parent measures this method's own duration (the real cost of the - # isolated run, subprocess startup included), so nothing to forward here. - # Replay the outcomes first: a failure of the test itself is more useful. - _replay_outcomes(self, payload['outcomes']) - _check_returncode(returncode, output, 'test') + proc = _start_test(cls.__module__, qualname, options, env) + _replay_test(self, *proc.wait(timeout)) return wrapper -def _isolate_class(cls): +def _isolate_class(cls, options, env, timeout): # Unwrap to the plain functions so the replacements can call them with the # runtime cls; a bound classmethod would freeze the decoration-time class # and a subclass would run the fixtures bound to the base class. @@ -216,8 +337,8 @@ def setUpClass(cls): _check_subprocess_support() # Run the whole class in a single subprocess and stash the outcomes # for the test methods to replay. - payload, output, returncode = _run_in_subprocess(cls.__module__, - cls.__qualname__) + proc = _start_test(cls.__module__, cls.__qualname__, options, env) + payload, output, returncode = proc.wait(timeout) if payload is None: exc = _SubprocessTestError( f'class did not complete in a subprocess (exit code {returncode})') @@ -283,7 +404,7 @@ def _addDuration(self, result, elapsed): return cls -def runInSubprocess(): +def runInSubprocess(*, options=(), env=None, timeout=None): """Decorator to run a test method or class in a fresh subprocess. The decorated test runs in a separate, fresh Python process, so it does not @@ -293,6 +414,16 @@ def runInSubprocess(): once there; when a method is decorated, only that method runs in a subprocess. Decorated methods must take no extra arguments. + *options* is a sequence of interpreter command line options for the + subprocess, and *env* is a mapping of environment variables to set in it, + on top of the inherited environment; a value of ``None`` unsets a variable. + Note that ``-E`` and ``-I`` make the subprocess ignore the ``PYTHON*`` + variables, including ``PYTHONPATH``. + + *timeout* is the number of seconds to wait for the subprocess; the test is + reported as an error if it does not complete in time. By default there is + no timeout, and a hung test is left to the timeout of the test runner. + A failure, error or skip of the whole test is reported for the test, and individual subtests (:meth:`~unittest.TestCase.subTest`) that fail or are skipped are reported individually. The original subprocess traceback is @@ -304,6 +435,6 @@ def runInSubprocess(): """ def decorator(obj): if isinstance(obj, type) and issubclass(obj, unittest.TestCase): - return _isolate_class(obj) - return _isolate_method(obj) + return _isolate_class(obj, options, env, timeout) + return _isolate_method(obj, options, env, timeout) return decorator diff --git a/Lib/test/support/os_helper.py b/Lib/test/support/os_helper.py index daf6060940e..183a8681271 100644 --- a/Lib/test/support/os_helper.py +++ b/Lib/test/support/os_helper.py @@ -1,6 +1,7 @@ import collections.abc import contextlib import errno +import functools import logging import os import re @@ -433,7 +434,10 @@ def _rmtree_inner(path): file=sys.__stderr__) mode = 0 if stat.S_ISDIR(mode): - _waitfor(_rmtree_inner, fullname, waitall=True) + # Do not follow junctions, which os.lstat() reports + # as directories. + if not os.path.isjunction(fullname): + _waitfor(_rmtree_inner, fullname, waitall=True) _force_run(fullname, os.rmdir, fullname) else: _force_run(fullname, os.unlink, fullname) @@ -682,6 +686,24 @@ def fd_count(): except FileNotFoundError: pass + if sys.platform == "freebsd" and fd_count._dev_fd_mounted: + # Check if /dev/fd/ fdescfs file system is mounted. By default, it's + # not mounted and /dev/fd/ always contains 3 files (0, 1, 2). + try: + dirfd = os.open("/dev/fd", os.O_RDONLY) + try: + if os.path.exists(f"/dev/fd/{dirfd}"): + names = list(os.scandir(dirfd)) + # Don't count dirfd + return len(names) - 1 + else: + # fdescfs is not mounted + fd_count._dev_fd_mounted = False + finally: + os.close(dirfd) + except FileNotFoundError: + pass + MAXFD = 256 if hasattr(os, 'sysconf'): try: @@ -729,6 +751,9 @@ def fd_count(): return count +# On FreeBSD, flag set to False if /dev/fd/ is not mounted as fdescfs +fd_count._dev_fd_mounted = True + if hasattr(os, "umask"): @contextlib.contextmanager @@ -806,6 +831,48 @@ def __exit__(self, *ignore_exc): os.environ = self._environ +def without_source_date_epoch(fxn): + """Runs function with SOURCE_DATE_EPOCH unset.""" + @functools.wraps(fxn) + def wrapper(*args, **kwargs): + with EnvironmentVarGuard() as env: + env.unset('SOURCE_DATE_EPOCH') + return fxn(*args, **kwargs) + return wrapper + + +_MISSING = sentinel("MISSING") + +def with_source_date_epoch(fxn=_MISSING, *, epoch=123456789): + """Runs function with SOURCE_DATE_EPOCH set to *epoch*.""" + if fxn is _MISSING: + return functools.partial(with_source_date_epoch, epoch=epoch) + + @functools.wraps(fxn) + def wrapper(*args, **kwargs): + with EnvironmentVarGuard() as env: + env['SOURCE_DATE_EPOCH'] = str(epoch) + return fxn(*args, **kwargs) + return wrapper + + +# Run tests with SOURCE_DATE_EPOCH set or unset explicitly. +class SourceDateEpochTestMeta(type(unittest.TestCase)): + def __new__(mcls, name, bases, dct, *, source_date_epoch): + cls = super().__new__(mcls, name, bases, dct) + + for attr in dir(cls): + if attr.startswith('test_'): + meth = getattr(cls, attr) + if source_date_epoch: + wrapper = with_source_date_epoch(meth) + else: + wrapper = without_source_date_epoch(meth) + setattr(cls, attr, wrapper) + + return cls + + try: if support.MS_WINDOWS: import ctypes diff --git a/Lib/test/support/strace_helper.py b/Lib/test/support/strace_helper.py index cf95f7bdc7d..bf15283d302 100644 --- a/Lib/test/support/strace_helper.py +++ b/Lib/test/support/strace_helper.py @@ -74,7 +74,7 @@ def sections(self): def _filter_memory_call(call): # mmap can operate on a fd or "MAP_ANONYMOUS" which gives a block of memory. # Ignore "MAP_ANONYMOUS + the "MAP_ANON" alias. - if call.syscall == "mmap" and "MAP_ANON" in call.args[3]: + if call.syscall in ("mmap", "mmap2") and "MAP_ANON" in call.args[3]: return True if call.syscall in ("munmap", "mprotect"): diff --git a/Lib/test/support/threading_helper.py b/Lib/test/support/threading_helper.py index cf87233f0e2..31be31ac9a9 100644 --- a/Lib/test/support/threading_helper.py +++ b/Lib/test/support/threading_helper.py @@ -1,6 +1,7 @@ import _thread import contextlib import functools +import inspect import sys import threading import time @@ -59,6 +60,11 @@ def reap_threads(func): """Use this function when threads are being used. This will ensure that the threads are cleaned up even when the test fails. """ + + if inspect.isclass(func): + # It should be used on each test method, not on the whole class + raise ValueError("@reap_threads is not compatible with classes") + @functools.wraps(func) def decorator(*args): key = threading_setup() diff --git a/Lib/test/support/warnings_helper.py b/Lib/test/support/warnings_helper.py index 5f6f14afd74..c046f39fbff 100644 --- a/Lib/test/support/warnings_helper.py +++ b/Lib/test/support/warnings_helper.py @@ -1,11 +1,11 @@ import contextlib -import functools import importlib import re import sys import warnings + def import_deprecated(name): """Import *name* while suppressing DeprecationWarning.""" with warnings.catch_warnings(): @@ -42,20 +42,32 @@ def check_syntax_warning(testcase, statement, errtext='', testcase.assertEqual(warns, []) -def ignore_warnings(*, category): +@contextlib.contextmanager +def ignore_warnings(*, category, message=''): """Decorator to suppress warnings. - Use of context managers to hide warnings make diffs - more noisy and tools like 'git blame' less useful. + Can also be used as a context manager. This is not preferred, + because it makes diffs more noisy and tools like 'git blame' less useful. + But, it's useful for async functions. """ - def decorator(test): - @functools.wraps(test) - def wrapper(self, *args, **kwargs): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', category=category) - return test(self, *args, **kwargs) - return wrapper - return decorator + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=category, message=message) + yield + + +@contextlib.contextmanager +def ignore_fork_in_thread_deprecation_warnings(): + """Suppress deprecation warnings related to forking in multi-threaded code. + + See gh-135427 + + Can be used as decorator (preferred) or context manager. + """ + with ignore_warnings( + message=".*fork.*may lead to deadlocks in the child.*", + category=DeprecationWarning, + ): + yield class WarningsRecorder(object): diff --git a/Lib/test/test__colorize.py b/Lib/test/test__colorize.py index 026277267e0..c7bc6914ac1 100644 --- a/Lib/test/test__colorize.py +++ b/Lib/test/test__colorize.py @@ -5,6 +5,7 @@ import unittest import unittest.mock import _colorize +from test.support import cpython_only, import_helper from test.support.os_helper import EnvironmentVarGuard @@ -22,6 +23,15 @@ def supports_virtual_terminal(): return contextlib.nullcontext() +class TestImportTime(unittest.TestCase): + + @cpython_only + def test_lazy_import(self): + import_helper.ensure_lazy_imports( + "_colorize", {"copy", "re", "inspect", "typing"} + ) + + class TestTheme(unittest.TestCase): def test_attributes(self): @@ -40,6 +50,7 @@ def test_copy_with(self): unittest_no_colors = _colorize.Unittest.no_colors() copy = theme.copy_with(unittest=unittest_no_colors) self.assertEqual(copy.argparse, theme.argparse) + self.assertEqual(copy.difflib, theme.difflib) self.assertEqual(copy.syntax, theme.syntax) self.assertEqual(copy.traceback, theme.traceback) self.assertEqual(copy.unittest, unittest_no_colors) diff --git a/Lib/test/test__interpchannels.py b/Lib/test/test__interpchannels.py new file mode 100644 index 00000000000..2b0aba42896 --- /dev/null +++ b/Lib/test/test__interpchannels.py @@ -0,0 +1,1842 @@ +from collections import namedtuple +import contextlib +import sys +from textwrap import dedent +import threading +import time +import unittest + +from test.support import import_helper + +_channels = import_helper.import_module('_interpchannels') +from concurrent.interpreters import _crossinterp +from test.test__interpreters import ( + _interpreters, + _run_output, + clean_up_interpreters, +) + + +REPLACE = _crossinterp._UNBOUND_CONSTANT_TO_FLAG[_crossinterp.UNBOUND] + + +# Additional tests are found in Lib/test/test_interpreters/test_channels.py. +# New tests should be added there. +# XXX The tests here should be moved there. See the note under LowLevelTests. + + +################################## +# helpers + +def recv_wait(cid): + while True: + try: + obj, unboundop = _channels.recv(cid) + except _channels.ChannelEmptyError: + time.sleep(0.1) + else: + assert unboundop is None, repr(unboundop) + return obj + + +def recv_nowait(cid, *args, unbound=False): + obj, unboundop = _channels.recv(cid, *args) + assert (unboundop is None) != unbound, repr(unboundop) + return obj + + +#@contextmanager +#def run_threaded(id, source, **shared): +# def run(): +# run_interp(id, source, **shared) +# t = threading.Thread(target=run) +# t.start() +# yield +# t.join() + + +def run_interp(id, source, **shared): + _run_interp(id, source, shared) + + +def _run_interp(id, source, shared, _mainns={}): + source = dedent(source) + main, *_ = _interpreters.get_main() + if main == id: + cur, *_ = _interpreters.get_current() + if cur != main: + raise RuntimeError + # XXX Run a func? + exec(source, _mainns) + else: + _interpreters.run_string(id, source, shared) + + +class Interpreter(namedtuple('Interpreter', 'name id')): + + @classmethod + def from_raw(cls, raw): + if isinstance(raw, cls): + return raw + elif isinstance(raw, str): + return cls(raw) + else: + raise NotImplementedError + + def __new__(cls, name=None, id=None): + main, *_ = _interpreters.get_main() + if id == main: + if not name: + name = 'main' + elif name != 'main': + raise ValueError( + 'name mismatch (expected "main", got "{}")'.format(name)) + id = main + elif id is not None: + if not name: + name = 'interp' + elif name == 'main': + raise ValueError('name mismatch (unexpected "main")') + assert isinstance(id, int), repr(id) + elif not name or name == 'main': + name = 'main' + id = main + else: + id = _interpreters.create() + self = super().__new__(cls, name, id) + return self + + +# XXX expect_channel_closed() is unnecessary once we improve exc propagation. + +@contextlib.contextmanager +def expect_channel_closed(): + try: + yield + except _channels.ChannelClosedError: + pass + else: + assert False, 'channel not closed' + + +class ChannelAction(namedtuple('ChannelAction', 'action end interp')): + + def __new__(cls, action, end=None, interp=None): + if not end: + end = 'both' + if not interp: + interp = 'main' + self = super().__new__(cls, action, end, interp) + return self + + def __init__(self, *args, **kwargs): + if self.action == 'use': + if self.end not in ('same', 'opposite', 'send', 'recv'): + raise ValueError(self.end) + elif self.action in ('close', 'force-close'): + if self.end not in ('both', 'same', 'opposite', 'send', 'recv'): + raise ValueError(self.end) + else: + raise ValueError(self.action) + if self.interp not in ('main', 'same', 'other', 'extra'): + raise ValueError(self.interp) + + def resolve_end(self, end): + if self.end == 'same': + return end + elif self.end == 'opposite': + return 'recv' if end == 'send' else 'send' + else: + return self.end + + def resolve_interp(self, interp, other, extra): + if self.interp == 'same': + return interp + elif self.interp == 'other': + if other is None: + raise RuntimeError + return other + elif self.interp == 'extra': + if extra is None: + raise RuntimeError + return extra + elif self.interp == 'main': + if interp.name == 'main': + return interp + elif other and other.name == 'main': + return other + else: + raise RuntimeError + # Per __init__(), there aren't any others. + + +class ChannelState(namedtuple('ChannelState', 'pending closed')): + + def __new__(cls, pending=0, *, closed=False): + self = super().__new__(cls, pending, closed) + return self + + def incr(self): + return type(self)(self.pending + 1, closed=self.closed) + + def decr(self): + return type(self)(self.pending - 1, closed=self.closed) + + def close(self, *, force=True): + if self.closed: + if not force or self.pending == 0: + return self + return type(self)(0 if force else self.pending, closed=True) + + +def run_action(cid, action, end, state, *, hideclosed=True): + if state.closed: + if action == 'use' and end == 'recv' and state.pending: + expectfail = False + else: + expectfail = True + else: + expectfail = False + + try: + result = _run_action(cid, action, end, state) + except _channels.ChannelClosedError: + if not hideclosed and not expectfail: + raise + result = state.close() + else: + if expectfail: + raise ... # XXX + return result + + +def _run_action(cid, action, end, state): + if action == 'use': + if end == 'send': + _channels.send(cid, b'spam', blocking=False) + return state.incr() + elif end == 'recv': + if not state.pending: + try: + _channels.recv(cid) + except _channels.ChannelEmptyError: + return state + else: + raise Exception('expected ChannelEmptyError') + else: + recv_nowait(cid) + return state.decr() + else: + raise ValueError(end) + elif action == 'close': + kwargs = {} + if end in ('recv', 'send'): + kwargs[end] = True + _channels.close(cid, **kwargs) + return state.close() + elif action == 'force-close': + kwargs = { + 'force': True, + } + if end in ('recv', 'send'): + kwargs[end] = True + _channels.close(cid, **kwargs) + return state.close(force=True) + else: + raise ValueError(action) + + +def clean_up_channels(): + for cid, _, _ in _channels.list_all(): + try: + _channels.destroy(cid) + except _channels.ChannelNotFoundError: + pass # already destroyed + + +class TestBase(unittest.TestCase): + + def tearDown(self): + clean_up_channels() + clean_up_interpreters() + + +################################## +# channel tests + +class ChannelIDTests(TestBase): + + def test_default_kwargs(self): + cid = _channels._channel_id(10, force=True) + + self.assertEqual(int(cid), 10) + self.assertEqual(cid.end, 'both') + + def test_with_kwargs(self): + cid = _channels._channel_id(10, send=True, force=True) + self.assertEqual(cid.end, 'send') + + cid = _channels._channel_id(10, send=True, recv=False, force=True) + self.assertEqual(cid.end, 'send') + + cid = _channels._channel_id(10, recv=True, force=True) + self.assertEqual(cid.end, 'recv') + + cid = _channels._channel_id(10, recv=True, send=False, force=True) + self.assertEqual(cid.end, 'recv') + + cid = _channels._channel_id(10, send=True, recv=True, force=True) + self.assertEqual(cid.end, 'both') + + def test_coerce_id(self): + class Int(str): + def __index__(self): + return 10 + + cid = _channels._channel_id(Int(), force=True) + self.assertEqual(int(cid), 10) + + def test_bad_id(self): + self.assertRaises(TypeError, _channels._channel_id, object()) + self.assertRaises(TypeError, _channels._channel_id, 10.0) + self.assertRaises(TypeError, _channels._channel_id, '10') + self.assertRaises(TypeError, _channels._channel_id, b'10') + self.assertRaises(ValueError, _channels._channel_id, -1) + self.assertRaises(OverflowError, _channels._channel_id, 2**64) + + def test_bad_kwargs(self): + with self.assertRaises(ValueError): + _channels._channel_id(10, send=False, recv=False) + + def test_does_not_exist(self): + cid = _channels.create(REPLACE) + with self.assertRaises(_channels.ChannelNotFoundError): + _channels._channel_id(int(cid) + 1) # unforced + + def test_str(self): + cid = _channels._channel_id(10, force=True) + self.assertEqual(str(cid), '10') + + def test_repr(self): + cid = _channels._channel_id(10, force=True) + self.assertEqual(repr(cid), 'ChannelID(10)') + + cid = _channels._channel_id(10, send=True, force=True) + self.assertEqual(repr(cid), 'ChannelID(10, send=True)') + + cid = _channels._channel_id(10, recv=True, force=True) + self.assertEqual(repr(cid), 'ChannelID(10, recv=True)') + + cid = _channels._channel_id(10, send=True, recv=True, force=True) + self.assertEqual(repr(cid), 'ChannelID(10)') + + def test_equality(self): + cid1 = _channels.create(REPLACE) + cid2 = _channels._channel_id(int(cid1)) + cid3 = _channels.create(REPLACE) + + self.assertTrue(cid1 == cid1) + self.assertTrue(cid1 == cid2) + self.assertTrue(cid1 == int(cid1)) + self.assertTrue(int(cid1) == cid1) + self.assertTrue(cid1 == float(int(cid1))) + self.assertTrue(float(int(cid1)) == cid1) + self.assertFalse(cid1 == float(int(cid1)) + 0.1) + self.assertFalse(cid1 == str(int(cid1))) + self.assertFalse(cid1 == 2**1000) + self.assertFalse(cid1 == float('inf')) + self.assertFalse(cid1 == 'spam') + self.assertFalse(cid1 == cid3) + + self.assertFalse(cid1 != cid1) + self.assertFalse(cid1 != cid2) + self.assertTrue(cid1 != cid3) + + def test_shareable(self): + chan = _channels.create(REPLACE) + + obj = _channels.create(REPLACE) + _channels.send(chan, obj, blocking=False) + got = recv_nowait(chan) + + self.assertEqual(got, obj) + self.assertIs(type(got), type(obj)) + # XXX Check the following in the channel tests? + #self.assertIsNot(got, obj) + + +class ChannelTests(TestBase): + + def test_create_cid(self): + cid = _channels.create(REPLACE) + self.assertIsInstance(cid, _channels.ChannelID) + + def test_sequential_ids(self): + before = [cid for cid, _, _ in _channels.list_all()] + id1 = _channels.create(REPLACE) + id2 = _channels.create(REPLACE) + id3 = _channels.create(REPLACE) + after = [cid for cid, _, _ in _channels.list_all()] + + self.assertEqual(id2, int(id1) + 1) + self.assertEqual(id3, int(id2) + 1) + self.assertEqual(set(after) - set(before), {id1, id2, id3}) + + def test_channel_list_all_closed(self): + id1 = _channels.create() + id2 = _channels.create() + id3 = _channels.create() + before = _channels.list_all() + expected = [info for info in before if info[0] != id2] + _channels.close(id2, force=True) + after = _channels.list_all() + self.assertEqual(set(after), set(expected)) + self.assertEqual(len(after), len(before) - 1) + + def test_channel_list_all_destroyed(self): + id1 = _channels.create() + id2 = _channels.create() + id3 = _channels.create() + before = _channels.list_all() + expected = [info for info in before if info[0] != id2] + _channels.destroy(id2) + after = _channels.list_all() + self.assertEqual(set(after), set(expected)) + self.assertEqual(len(after), len(before) - 1) + + def test_channel_list_all_released(self): + id1 = _channels.create() + id2 = _channels.create() + id3 = _channels.create() + before = _channels.list_all() + _channels.release(id2, send=True, recv=True) + after = _channels.list_all() + self.assertEqual(set(after), set(before)) + self.assertEqual(len(after), len(before)) + + def test_ids_global(self): + id1 = _interpreters.create() + out = _run_output(id1, dedent(""" + import _interpchannels as _channels + cid = _channels.create(3) + print(cid) + """)) + cid1 = int(out.strip()) + + id2 = _interpreters.create() + out = _run_output(id2, dedent(""" + import _interpchannels as _channels + cid = _channels.create(3) + print(cid) + """)) + cid2 = int(out.strip()) + + self.assertEqual(cid2, int(cid1) + 1) + + def test_channel_list_interpreters_none(self): + """Test listing interpreters for a channel with no associations.""" + # Test for channel with no associated _interpreters. + cid = _channels.create(REPLACE) + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(send_interps, []) + self.assertEqual(recv_interps, []) + + def test_channel_list_interpreters_basic(self): + """Test basic listing channel _interpreters.""" + interp0, *_ = _interpreters.get_main() + cid = _channels.create(REPLACE) + _channels.send(cid, "send", blocking=False) + # Test for a channel that has one end associated to an interpreter. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(send_interps, [interp0]) + self.assertEqual(recv_interps, []) + + interp1 = _interpreters.create() + _run_output(interp1, dedent(f""" + import _interpchannels as _channels + _channels.recv({cid}) + """)) + # Test for channel that has both ends associated to an interpreter. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(send_interps, [interp0]) + self.assertEqual(recv_interps, [interp1]) + + def test_channel_list_interpreters_multiple(self): + """Test listing interpreters for a channel with many associations.""" + interp0, *_ = _interpreters.get_main() + interp1 = _interpreters.create() + interp2 = _interpreters.create() + interp3 = _interpreters.create() + cid = _channels.create(REPLACE) + + _channels.send(cid, "send", blocking=False) + _run_output(interp1, dedent(f""" + import _interpchannels as _channels + _channels.send({cid}, "send", blocking=False) + """)) + _run_output(interp2, dedent(f""" + import _interpchannels as _channels + _channels.recv({cid}) + """)) + _run_output(interp3, dedent(f""" + import _interpchannels as _channels + _channels.recv({cid}) + """)) + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(set(send_interps), {interp0, interp1}) + self.assertEqual(set(recv_interps), {interp2, interp3}) + + def test_channel_list_interpreters_destroyed(self): + """Test listing channel interpreters with a destroyed interpreter.""" + interp0, *_ = _interpreters.get_main() + interp1 = _interpreters.create() + cid = _channels.create(REPLACE) + _channels.send(cid, "send", blocking=False) + _run_output(interp1, dedent(f""" + import _interpchannels as _channels + _channels.recv({cid}) + """)) + # Should be one interpreter associated with each end. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(send_interps, [interp0]) + self.assertEqual(recv_interps, [interp1]) + + _interpreters.destroy(interp1) + # Destroyed interpreter should not be listed. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(send_interps, [interp0]) + self.assertEqual(recv_interps, []) + + def test_channel_list_interpreters_released(self): + """Test listing channel interpreters with a released channel.""" + # Set up one channel with main interpreter on the send end and two + # subinterpreters on the receive end. + interp0, *_ = _interpreters.get_main() + interp1 = _interpreters.create() + interp2 = _interpreters.create() + cid = _channels.create(REPLACE) + _channels.send(cid, "data", blocking=False) + _run_output(interp1, dedent(f""" + import _interpchannels as _channels + _channels.recv({cid}) + """)) + _channels.send(cid, "data", blocking=False) + _run_output(interp2, dedent(f""" + import _interpchannels as _channels + _channels.recv({cid}) + """)) + # Check the setup. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(len(send_interps), 1) + self.assertEqual(len(recv_interps), 2) + + # Release the main interpreter from the send end. + _channels.release(cid, send=True) + # Send end should have no associated _interpreters. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(len(send_interps), 0) + self.assertEqual(len(recv_interps), 2) + + # Release one of the subinterpreters from the receive end. + _run_output(interp2, dedent(f""" + import _interpchannels as _channels + _channels.release({cid}) + """)) + # Receive end should have the released interpreter removed. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(len(send_interps), 0) + self.assertEqual(recv_interps, [interp1]) + + def test_channel_list_interpreters_closed(self): + """Test listing channel interpreters with a closed channel.""" + interp0, *_ = _interpreters.get_main() + interp1 = _interpreters.create() + cid = _channels.create(REPLACE) + # Put something in the channel so that it's not empty. + _channels.send(cid, "send", blocking=False) + + # Check initial state. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(len(send_interps), 1) + self.assertEqual(len(recv_interps), 0) + + # Force close the channel. + _channels.close(cid, force=True) + # Both ends should raise an error. + with self.assertRaises(_channels.ChannelClosedError): + _channels.list_interpreters(cid, send=True) + with self.assertRaises(_channels.ChannelClosedError): + _channels.list_interpreters(cid, send=False) + + def test_channel_list_interpreters_closed_send_end(self): + """Test listing channel interpreters with a channel's send end closed.""" + interp0, *_ = _interpreters.get_main() + interp1 = _interpreters.create() + cid = _channels.create(REPLACE) + # Put something in the channel so that it's not empty. + _channels.send(cid, "send", blocking=False) + + # Check initial state. + send_interps = _channels.list_interpreters(cid, send=True) + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(len(send_interps), 1) + self.assertEqual(len(recv_interps), 0) + + # Close the send end of the channel. + _channels.close(cid, send=True) + # Send end should raise an error. + with self.assertRaises(_channels.ChannelClosedError): + _channels.list_interpreters(cid, send=True) + # Receive end should not be closed (since channel is not empty). + recv_interps = _channels.list_interpreters(cid, send=False) + self.assertEqual(len(recv_interps), 0) + + # Close the receive end of the channel from a subinterpreter. + _run_output(interp1, dedent(f""" + import _interpchannels as _channels + _channels.close({cid}, force=True) + """)) + return + # Both ends should raise an error. + with self.assertRaises(_channels.ChannelClosedError): + _channels.list_interpreters(cid, send=True) + with self.assertRaises(_channels.ChannelClosedError): + _channels.list_interpreters(cid, send=False) + + def test_allowed_types(self): + cid = _channels.create(REPLACE) + objects = [ + None, + 'spam', + b'spam', + 42, + ] + for obj in objects: + with self.subTest(obj): + _channels.send(cid, obj, blocking=False) + got = recv_nowait(cid) + + self.assertEqual(got, obj) + self.assertIs(type(got), type(obj)) + # XXX Check the following? + #self.assertIsNot(got, obj) + # XXX What about between interpreters? + + def test_run_string_arg_unresolved(self): + cid = _channels.create(REPLACE) + interp = _interpreters.create() + + _interpreters.set___main___attrs(interp, dict(cid=cid.send)) + out = _run_output(interp, dedent(""" + import _interpchannels as _channels + print(cid.end) + _channels.send(cid, b'spam', blocking=False) + """)) + obj = recv_nowait(cid) + + self.assertEqual(obj, b'spam') + self.assertEqual(out.strip(), 'send') + + # XXX For now there is no high-level channel into which the + # sent channel ID can be converted... + # Note: this test caused crashes on some buildbots (bpo-33615). + @unittest.skip('disabled until high-level channels exist') + def test_run_string_arg_resolved(self): + cid = _channels.create(REPLACE) + cid = _channels._channel_id(cid, _resolve=True) + interp = _interpreters.create() + + out = _run_output(interp, dedent(""" + import _interpchannels as _channels + print(chan.id.end) + _channels.send(chan.id, b'spam', blocking=False) + """), + dict(chan=cid.send)) + obj = recv_nowait(cid) + + self.assertEqual(obj, b'spam') + self.assertEqual(out.strip(), 'send') + + #------------------- + # send/recv + + def test_send_recv_main(self): + cid = _channels.create(REPLACE) + orig = b'spam' + _channels.send(cid, orig, blocking=False) + obj = recv_nowait(cid) + + self.assertEqual(obj, orig) + self.assertIsNot(obj, orig) + + def test_send_recv_same_interpreter(self): + id1 = _interpreters.create() + out = _run_output(id1, dedent(""" + import _interpchannels as _channels + cid = _channels.create(REPLACE) + orig = b'spam' + _channels.send(cid, orig, blocking=False) + obj, _ = _channels.recv(cid) + assert obj is not orig + assert obj == orig + """)) + + def test_send_recv_different_interpreters(self): + cid = _channels.create(REPLACE) + id1 = _interpreters.create() + out = _run_output(id1, dedent(f""" + import _interpchannels as _channels + _channels.send({cid}, b'spam', blocking=False) + """)) + obj = recv_nowait(cid) + + self.assertEqual(obj, b'spam') + + def test_send_recv_different_threads(self): + cid = _channels.create(REPLACE) + + def f(): + obj = recv_wait(cid) + _channels.send(cid, obj) + t = threading.Thread(target=f) + t.start() + + _channels.send(cid, b'spam') + obj = recv_wait(cid) + t.join() + + self.assertEqual(obj, b'spam') + + def test_send_recv_different_interpreters_and_threads(self): + cid = _channels.create(REPLACE) + id1 = _interpreters.create() + out = None + + def f(): + nonlocal out + out = _run_output(id1, dedent(f""" + import time + import _interpchannels as _channels + while True: + try: + obj, _ = _channels.recv({cid}) + break + except _channels.ChannelEmptyError: + time.sleep(0.1) + assert(obj == b'spam') + _channels.send({cid}, b'eggs') + """)) + t = threading.Thread(target=f) + t.start() + + _channels.send(cid, b'spam') + obj = recv_wait(cid) + t.join() + + self.assertEqual(obj, b'eggs') + + def test_send_not_found(self): + with self.assertRaises(_channels.ChannelNotFoundError): + _channels.send(10, b'spam') + + def test_recv_not_found(self): + with self.assertRaises(_channels.ChannelNotFoundError): + _channels.recv(10) + + def test_recv_empty(self): + cid = _channels.create(REPLACE) + with self.assertRaises(_channels.ChannelEmptyError): + _channels.recv(cid) + + def test_recv_default(self): + default = object() + cid = _channels.create(REPLACE) + obj1 = recv_nowait(cid, default) + _channels.send(cid, None, blocking=False) + _channels.send(cid, 1, blocking=False) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'eggs', blocking=False) + obj2 = recv_nowait(cid, default) + obj3 = recv_nowait(cid, default) + obj4 = recv_nowait(cid) + obj5 = recv_nowait(cid, default) + obj6 = recv_nowait(cid, default) + + self.assertIs(obj1, default) + self.assertIs(obj2, None) + self.assertEqual(obj3, 1) + self.assertEqual(obj4, b'spam') + self.assertEqual(obj5, b'eggs') + self.assertIs(obj6, default) + + def test_recv_sending_interp_destroyed(self): + with self.subTest('closed'): + cid1 = _channels.create(REPLACE) + interp = _interpreters.create() + _interpreters.run_string(interp, dedent(f""" + import _interpchannels as _channels + _channels.send({cid1}, b'spam', blocking=False) + """)) + _interpreters.destroy(interp) + + with self.assertRaisesRegex(RuntimeError, + f'channel {cid1} is closed'): + _channels.recv(cid1) + del cid1 + with self.subTest('still open'): + cid2 = _channels.create(REPLACE) + interp = _interpreters.create() + _interpreters.run_string(interp, dedent(f""" + import _interpchannels as _channels + _channels.send({cid2}, b'spam', blocking=False) + """)) + _channels.send(cid2, b'eggs', blocking=False) + _interpreters.destroy(interp) + + recv_nowait(cid2, unbound=True) + recv_nowait(cid2, unbound=False) + with self.assertRaisesRegex(RuntimeError, + f'channel {cid2} is empty'): + _channels.recv(cid2) + del cid2 + + #------------------- + # send_buffer + + def test_send_buffer(self): + buf = bytearray(b'spamspamspam') + cid = _channels.create(REPLACE) + _channels.send_buffer(cid, buf, blocking=False) + obj = recv_nowait(cid) + + self.assertIsNot(obj, buf) + self.assertIsInstance(obj, memoryview) + self.assertEqual(obj, buf) + + buf[4:8] = b'eggs' + self.assertEqual(obj, buf) + obj[4:8] = b'ham.' + self.assertEqual(obj, buf) + + #------------------- + # send with waiting + + def build_send_waiter(self, obj, *, buffer=False): + # We want a long enough sleep that send() actually has to wait. + + if buffer: + send = _channels.send_buffer + else: + send = _channels.send + + cid = _channels.create(REPLACE) + try: + started = time.monotonic() + send(cid, obj, blocking=False) + stopped = time.monotonic() + recv_nowait(cid) + finally: + _channels.destroy(cid) + delay = stopped - started # seconds + delay *= 3 + + def wait(): + time.sleep(delay) + return wait + + def test_send_blocking_waiting(self): + received = None + obj = b'spam' + wait = self.build_send_waiter(obj) + cid = _channels.create(REPLACE) + def f(): + nonlocal received + wait() + received = recv_wait(cid) + t = threading.Thread(target=f) + t.start() + _channels.send(cid, obj, blocking=True) + t.join() + + self.assertEqual(received, obj) + + def test_send_buffer_blocking_waiting(self): + received = None + obj = bytearray(b'spam') + wait = self.build_send_waiter(obj, buffer=True) + cid = _channels.create(REPLACE) + def f(): + nonlocal received + wait() + received = recv_wait(cid) + t = threading.Thread(target=f) + t.start() + _channels.send_buffer(cid, obj, blocking=True) + t.join() + + self.assertEqual(received, obj) + + def test_send_blocking_no_wait(self): + received = None + obj = b'spam' + cid = _channels.create(REPLACE) + def f(): + nonlocal received + received = recv_wait(cid) + t = threading.Thread(target=f) + t.start() + _channels.send(cid, obj, blocking=True) + t.join() + + self.assertEqual(received, obj) + + def test_send_buffer_blocking_no_wait(self): + received = None + obj = bytearray(b'spam') + cid = _channels.create(REPLACE) + def f(): + nonlocal received + received = recv_wait(cid) + t = threading.Thread(target=f) + t.start() + _channels.send_buffer(cid, obj, blocking=True) + t.join() + + self.assertEqual(received, obj) + + def test_send_timeout(self): + obj = b'spam' + + with self.subTest('non-blocking with timeout'): + cid = _channels.create(REPLACE) + with self.assertRaises(ValueError): + _channels.send(cid, obj, blocking=False, timeout=0.1) + + with self.subTest('timeout hit'): + cid = _channels.create(REPLACE) + with self.assertRaises(TimeoutError): + _channels.send(cid, obj, blocking=True, timeout=0.1) + with self.assertRaises(_channels.ChannelEmptyError): + received = recv_nowait(cid) + print(repr(received)) + + with self.subTest('timeout not hit'): + cid = _channels.create(REPLACE) + def f(): + recv_wait(cid) + t = threading.Thread(target=f) + t.start() + _channels.send(cid, obj, blocking=True, timeout=10) + t.join() + + def test_send_buffer_timeout(self): + try: + self._has_run_once_timeout + except AttributeError: + # At the moment, this test leaks a few references. + # It looks like the leak originates with the addition + # of _channels.send_buffer() (gh-110246), whereas the + # tests were added afterward. We want this test even + # if the refleak isn't fixed yet, so we skip here. + raise unittest.SkipTest('temporarily skipped due to refleaks') + else: + self._has_run_once_timeout = True + + obj = bytearray(b'spam') + + with self.subTest('non-blocking with timeout'): + cid = _channels.create(REPLACE) + with self.assertRaises(ValueError): + _channels.send_buffer(cid, obj, blocking=False, timeout=0.1) + + with self.subTest('timeout hit'): + cid = _channels.create(REPLACE) + with self.assertRaises(TimeoutError): + _channels.send_buffer(cid, obj, blocking=True, timeout=0.1) + with self.assertRaises(_channels.ChannelEmptyError): + received = recv_nowait(cid) + print(repr(received)) + + with self.subTest('timeout not hit'): + cid = _channels.create(REPLACE) + def f(): + recv_wait(cid) + t = threading.Thread(target=f) + t.start() + _channels.send_buffer(cid, obj, blocking=True, timeout=10) + t.join() + + def test_send_closed_while_waiting(self): + obj = b'spam' + wait = self.build_send_waiter(obj) + + with self.subTest('without timeout'): + cid = _channels.create(REPLACE) + def f(): + wait() + _channels.close(cid, force=True) + t = threading.Thread(target=f) + t.start() + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, obj, blocking=True) + t.join() + + with self.subTest('with timeout'): + cid = _channels.create(REPLACE) + def f(): + wait() + _channels.close(cid, force=True) + t = threading.Thread(target=f) + t.start() + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, obj, blocking=True, timeout=30) + t.join() + + def test_send_buffer_closed_while_waiting(self): + try: + self._has_run_once_closed + except AttributeError: + # At the moment, this test leaks a few references. + # It looks like the leak originates with the addition + # of _channels.send_buffer() (gh-110246), whereas the + # tests were added afterward. We want this test even + # if the refleak isn't fixed yet, so we skip here. + raise unittest.SkipTest('temporarily skipped due to refleaks') + else: + self._has_run_once_closed = True + + obj = bytearray(b'spam') + wait = self.build_send_waiter(obj, buffer=True) + + with self.subTest('without timeout'): + cid = _channels.create(REPLACE) + def f(): + wait() + _channels.close(cid, force=True) + t = threading.Thread(target=f) + t.start() + with self.assertRaises(_channels.ChannelClosedError): + _channels.send_buffer(cid, obj, blocking=True) + t.join() + + with self.subTest('with timeout'): + cid = _channels.create(REPLACE) + def f(): + wait() + _channels.close(cid, force=True) + t = threading.Thread(target=f) + t.start() + with self.assertRaises(_channels.ChannelClosedError): + _channels.send_buffer(cid, obj, blocking=True, timeout=30) + t.join() + + #------------------- + # close + + def test_close_single_user(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.close(cid) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_close_multiple_users(self): + cid = _channels.create(REPLACE) + id1 = _interpreters.create() + id2 = _interpreters.create() + _interpreters.run_string(id1, dedent(f""" + import _interpchannels as _channels + _channels.send({cid}, b'spam', blocking=False) + """)) + _interpreters.run_string(id2, dedent(f""" + import _interpchannels as _channels + _channels.recv({cid}) + """)) + _channels.close(cid) + + excsnap = _interpreters.run_string(id1, dedent(f""" + _channels.send({cid}, b'spam') + """)) + self.assertEqual(excsnap.type.__name__, 'ChannelClosedError') + + excsnap = _interpreters.run_string(id2, dedent(f""" + _channels.send({cid}, b'spam') + """)) + self.assertEqual(excsnap.type.__name__, 'ChannelClosedError') + + def test_close_multiple_times(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.close(cid) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.close(cid) + + def test_close_empty(self): + tests = [ + (False, False), + (True, False), + (False, True), + (True, True), + ] + for send, recv in tests: + with self.subTest((send, recv)): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.close(cid, send=send, recv=recv) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_close_defaults_with_unused_items(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + + with self.assertRaises(_channels.ChannelNotEmptyError): + _channels.close(cid) + recv_nowait(cid) + _channels.send(cid, b'eggs', blocking=False) + + def test_close_recv_with_unused_items_unforced(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + + with self.assertRaises(_channels.ChannelNotEmptyError): + _channels.close(cid, recv=True) + recv_nowait(cid) + _channels.send(cid, b'eggs', blocking=False) + recv_nowait(cid) + recv_nowait(cid) + _channels.close(cid, recv=True) + + def test_close_send_with_unused_items_unforced(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + _channels.close(cid, send=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + recv_nowait(cid) + recv_nowait(cid) + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_close_both_with_unused_items_unforced(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + + with self.assertRaises(_channels.ChannelNotEmptyError): + _channels.close(cid, recv=True, send=True) + recv_nowait(cid) + _channels.send(cid, b'eggs', blocking=False) + recv_nowait(cid) + recv_nowait(cid) + _channels.close(cid, recv=True) + + def test_close_recv_with_unused_items_forced(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + _channels.close(cid, recv=True, force=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_close_send_with_unused_items_forced(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + _channels.close(cid, send=True, force=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_close_both_with_unused_items_forced(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + _channels.close(cid, send=True, recv=True, force=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_close_never_used(self): + cid = _channels.create(REPLACE) + _channels.close(cid) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'spam') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_close_by_unassociated_interp(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + interp = _interpreters.create() + _interpreters.run_string(interp, dedent(f""" + import _interpchannels as _channels + _channels.close({cid}, force=True) + """)) + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + with self.assertRaises(_channels.ChannelClosedError): + _channels.close(cid) + + def test_close_used_multiple_times_by_single_user(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.close(cid, force=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_channel_list_interpreters_invalid_channel(self): + cid = _channels.create(REPLACE) + # Test for invalid channel ID. + with self.assertRaises(_channels.ChannelNotFoundError): + _channels.list_interpreters(1000, send=True) + + _channels.close(cid) + # Test for a channel that has been closed. + with self.assertRaises(_channels.ChannelClosedError): + _channels.list_interpreters(cid, send=True) + + def test_channel_list_interpreters_invalid_args(self): + # Tests for invalid arguments passed to the API. + cid = _channels.create(REPLACE) + with self.assertRaises(TypeError): + _channels.list_interpreters(cid) + + +class ChannelReleaseTests(TestBase): + + # XXX Add more test coverage a la the tests for close(). + + """ + - main / interp / other + - run in: current thread / new thread / other thread / different threads + - end / opposite + - force / no force + - used / not used (associated / not associated) + - empty / emptied / never emptied / partly emptied + - closed / not closed + - released / not released + - creator (interp) / other + - associated interpreter not running + - associated interpreter destroyed + """ + + """ + use + pre-release + release + after + check + """ + + """ + release in: main, interp1 + creator: same, other (incl. interp2) + + use: None,send,recv,send/recv in None,same,other(incl. interp2),same+other(incl. interp2),all + pre-release: None,send,recv,both in None,same,other(incl. interp2),same+other(incl. interp2),all + pre-release forced: None,send,recv,both in None,same,other(incl. interp2),same+other(incl. interp2),all + + release: same + release forced: same + + use after: None,send,recv,send/recv in None,same,other(incl. interp2),same+other(incl. interp2),all + release after: None,send,recv,send/recv in None,same,other(incl. interp2),same+other(incl. interp2),all + check released: send/recv for same/other(incl. interp2) + check closed: send/recv for same/other(incl. interp2) + """ + + def test_single_user(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.release(cid, send=True, recv=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_multiple_users(self): + cid = _channels.create(REPLACE) + id1 = _interpreters.create() + id2 = _interpreters.create() + _interpreters.run_string(id1, dedent(f""" + import _interpchannels as _channels + _channels.send({cid}, b'spam', blocking=False) + """)) + out = _run_output(id2, dedent(f""" + import _interpchannels as _channels + obj, _ = _channels.recv({cid}) + _channels.release({cid}) + print(repr(obj)) + """)) + _interpreters.run_string(id1, dedent(f""" + _channels.release({cid}) + """)) + + self.assertEqual(out.strip(), "b'spam'") + + def test_no_kwargs(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.release(cid) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_multiple_times(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.release(cid, send=True, recv=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.release(cid, send=True, recv=True) + + def test_with_unused_items(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'ham', blocking=False) + _channels.release(cid, send=True, recv=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_never_used(self): + cid = _channels.create(REPLACE) + _channels.release(cid) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'spam') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_by_unassociated_interp(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + interp = _interpreters.create() + _interpreters.run_string(interp, dedent(f""" + import _interpchannels as _channels + _channels.release({cid}) + """)) + obj = recv_nowait(cid) + _channels.release(cid) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + self.assertEqual(obj, b'spam') + + def test_close_if_unassociated(self): + # XXX Something's not right with this test... + cid = _channels.create(REPLACE) + interp = _interpreters.create() + _interpreters.run_string(interp, dedent(f""" + import _interpchannels as _channels + obj = _channels.send({cid}, b'spam', blocking=False) + _channels.release({cid}) + """)) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + def test_partially(self): + # XXX Is partial close too weird/confusing? + cid = _channels.create(REPLACE) + _channels.send(cid, None, blocking=False) + recv_nowait(cid) + _channels.send(cid, b'spam', blocking=False) + _channels.release(cid, send=True) + obj = recv_nowait(cid) + + self.assertEqual(obj, b'spam') + + def test_used_multiple_times_by_single_user(self): + cid = _channels.create(REPLACE) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'spam', blocking=False) + _channels.send(cid, b'spam', blocking=False) + recv_nowait(cid) + _channels.release(cid, send=True, recv=True) + + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(cid, b'eggs') + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(cid) + + +class ChannelCloseFixture(namedtuple('ChannelCloseFixture', + 'end interp other extra creator')): + + # Set this to True to avoid creating interpreters, e.g. when + # scanning through test permutations without running them. + QUICK = False + + def __new__(cls, end, interp, other, extra, creator): + assert end in ('send', 'recv') + if cls.QUICK: + known = {} + else: + interp = Interpreter.from_raw(interp) + other = Interpreter.from_raw(other) + extra = Interpreter.from_raw(extra) + known = { + interp.name: interp, + other.name: other, + extra.name: extra, + } + if not creator: + creator = 'same' + self = super().__new__(cls, end, interp, other, extra, creator) + self._prepped = set() + self._state = ChannelState() + self._known = known + return self + + @property + def state(self): + return self._state + + @property + def cid(self): + try: + return self._cid + except AttributeError: + creator = self._get_interpreter(self.creator) + self._cid = self._new_channel(creator) + return self._cid + + def get_interpreter(self, interp): + interp = self._get_interpreter(interp) + self._prep_interpreter(interp) + return interp + + def expect_closed_error(self, end=None): + if end is None: + end = self.end + if end == 'recv' and self.state.closed == 'send': + return False + return bool(self.state.closed) + + def prep_interpreter(self, interp): + self._prep_interpreter(interp) + + def record_action(self, action, result): + self._state = result + + def clean_up(self): + clean_up_interpreters() + clean_up_channels() + + # internal methods + + def _new_channel(self, creator): + if creator.name == 'main': + return _channels.create(REPLACE) + else: + ch = _channels.create(REPLACE) + run_interp(creator.id, f""" + import _interpreters + cid = _xxsubchannels.create() + # We purposefully send back an int to avoid tying the + # channel to the other interpreter. + _xxsubchannels.send({ch}, int(cid), blocking=False) + del _interpreters + """) + self._cid = recv_nowait(ch) + return self._cid + + def _get_interpreter(self, interp): + if interp in ('same', 'interp'): + return self.interp + elif interp == 'other': + return self.other + elif interp == 'extra': + return self.extra + else: + name = interp + try: + interp = self._known[name] + except KeyError: + interp = self._known[name] = Interpreter(name) + return interp + + def _prep_interpreter(self, interp): + if interp.id in self._prepped: + return + self._prepped.add(interp.id) + if interp.name == 'main': + return + run_interp(interp.id, f""" + import _interpchannels as channels + import test.test__interpchannels as helpers + ChannelState = helpers.ChannelState + try: + cid + except NameError: + cid = _channels._channel_id({self.cid}) + """) + + +@unittest.skip('these tests take several hours to run') +class ExhaustiveChannelTests(TestBase): + + """ + - main / interp / other + - run in: current thread / new thread / other thread / different threads + - end / opposite + - force / no force + - used / not used (associated / not associated) + - empty / emptied / never emptied / partly emptied + - closed / not closed + - released / not released + - creator (interp) / other + - associated interpreter not running + - associated interpreter destroyed + + - close after unbound + """ + + """ + use + pre-close + close + after + check + """ + + """ + close in: main, interp1 + creator: same, other, extra + + use: None,send,recv,send/recv in None,same,other,same+other,all + pre-close: None,send,recv in None,same,other,same+other,all + pre-close forced: None,send,recv in None,same,other,same+other,all + + close: same + close forced: same + + use after: None,send,recv,send/recv in None,same,other,extra,same+other,all + close after: None,send,recv,send/recv in None,same,other,extra,same+other,all + check closed: send/recv for same/other(incl. interp2) + """ + + def iter_action_sets(self): + # - used / not used (associated / not associated) + # - empty / emptied / never emptied / partly emptied + # - closed / not closed + # - released / not released + + # never used + yield [] + + # only pre-closed (and possible used after) + for closeactions in self._iter_close_action_sets('same', 'other'): + yield closeactions + for postactions in self._iter_post_close_action_sets(): + yield closeactions + postactions + for closeactions in self._iter_close_action_sets('other', 'extra'): + yield closeactions + for postactions in self._iter_post_close_action_sets(): + yield closeactions + postactions + + # used + for useactions in self._iter_use_action_sets('same', 'other'): + yield useactions + for closeactions in self._iter_close_action_sets('same', 'other'): + actions = useactions + closeactions + yield actions + for postactions in self._iter_post_close_action_sets(): + yield actions + postactions + for closeactions in self._iter_close_action_sets('other', 'extra'): + actions = useactions + closeactions + yield actions + for postactions in self._iter_post_close_action_sets(): + yield actions + postactions + for useactions in self._iter_use_action_sets('other', 'extra'): + yield useactions + for closeactions in self._iter_close_action_sets('same', 'other'): + actions = useactions + closeactions + yield actions + for postactions in self._iter_post_close_action_sets(): + yield actions + postactions + for closeactions in self._iter_close_action_sets('other', 'extra'): + actions = useactions + closeactions + yield actions + for postactions in self._iter_post_close_action_sets(): + yield actions + postactions + + def _iter_use_action_sets(self, interp1, interp2): + interps = (interp1, interp2) + + # only recv end used + yield [ + ChannelAction('use', 'recv', interp1), + ] + yield [ + ChannelAction('use', 'recv', interp2), + ] + yield [ + ChannelAction('use', 'recv', interp1), + ChannelAction('use', 'recv', interp2), + ] + + # never emptied + yield [ + ChannelAction('use', 'send', interp1), + ] + yield [ + ChannelAction('use', 'send', interp2), + ] + yield [ + ChannelAction('use', 'send', interp1), + ChannelAction('use', 'send', interp2), + ] + + # partially emptied + for interp1 in interps: + for interp2 in interps: + for interp3 in interps: + yield [ + ChannelAction('use', 'send', interp1), + ChannelAction('use', 'send', interp2), + ChannelAction('use', 'recv', interp3), + ] + + # fully emptied + for interp1 in interps: + for interp2 in interps: + for interp3 in interps: + for interp4 in interps: + yield [ + ChannelAction('use', 'send', interp1), + ChannelAction('use', 'send', interp2), + ChannelAction('use', 'recv', interp3), + ChannelAction('use', 'recv', interp4), + ] + + def _iter_close_action_sets(self, interp1, interp2): + ends = ('recv', 'send') + interps = (interp1, interp2) + for force in (True, False): + op = 'force-close' if force else 'close' + for interp in interps: + for end in ends: + yield [ + ChannelAction(op, end, interp), + ] + for recvop in ('close', 'force-close'): + for sendop in ('close', 'force-close'): + for recv in interps: + for send in interps: + yield [ + ChannelAction(recvop, 'recv', recv), + ChannelAction(sendop, 'send', send), + ] + + def _iter_post_close_action_sets(self): + for interp in ('same', 'extra', 'other'): + yield [ + ChannelAction('use', 'recv', interp), + ] + yield [ + ChannelAction('use', 'send', interp), + ] + + def run_actions(self, fix, actions): + for action in actions: + self.run_action(fix, action) + + def run_action(self, fix, action, *, hideclosed=True): + end = action.resolve_end(fix.end) + interp = action.resolve_interp(fix.interp, fix.other, fix.extra) + fix.prep_interpreter(interp) + if interp.name == 'main': + result = run_action( + fix.cid, + action.action, + end, + fix.state, + hideclosed=hideclosed, + ) + fix.record_action(action, result) + else: + _cid = _channels.create(REPLACE) + run_interp(interp.id, f""" + result = helpers.run_action( + {fix.cid}, + {repr(action.action)}, + {repr(end)}, + {repr(fix.state)}, + hideclosed={hideclosed}, + ) + _channels.send({_cid}, result.pending.to_bytes(1, 'little'), blocking=False) + _channels.send({_cid}, b'X' if result.closed else b'', blocking=False) + """) + result = ChannelState( + pending=int.from_bytes(recv_nowait(_cid), 'little'), + closed=bool(recv_nowait(_cid)), + ) + fix.record_action(action, result) + + def iter_fixtures(self): + # XXX threads? + interpreters = [ + ('main', 'interp', 'extra'), + ('interp', 'main', 'extra'), + ('interp1', 'interp2', 'extra'), + ('interp1', 'interp2', 'main'), + ] + for interp, other, extra in interpreters: + for creator in ('same', 'other', 'creator'): + for end in ('send', 'recv'): + yield ChannelCloseFixture(end, interp, other, extra, creator) + + def _close(self, fix, *, force): + op = 'force-close' if force else 'close' + close = ChannelAction(op, fix.end, 'same') + if not fix.expect_closed_error(): + self.run_action(fix, close, hideclosed=False) + else: + with self.assertRaises(_channels.ChannelClosedError): + self.run_action(fix, close, hideclosed=False) + + def _assert_closed_in_interp(self, fix, interp=None): + if interp is None or interp.name == 'main': + with self.assertRaises(_channels.ChannelClosedError): + _channels.recv(fix.cid) + with self.assertRaises(_channels.ChannelClosedError): + _channels.send(fix.cid, b'spam') + with self.assertRaises(_channels.ChannelClosedError): + _channels.close(fix.cid) + with self.assertRaises(_channels.ChannelClosedError): + _channels.close(fix.cid, force=True) + else: + run_interp(interp.id, """ + with helpers.expect_channel_closed(): + _channels.recv(cid) + """) + run_interp(interp.id, """ + with helpers.expect_channel_closed(): + _channels.send(cid, b'spam', blocking=False) + """) + run_interp(interp.id, """ + with helpers.expect_channel_closed(): + _channels.close(cid) + """) + run_interp(interp.id, """ + with helpers.expect_channel_closed(): + _channels.close(cid, force=True) + """) + + def _assert_closed(self, fix): + self.assertTrue(fix.state.closed) + + for _ in range(fix.state.pending): + recv_nowait(fix.cid) + self._assert_closed_in_interp(fix) + + for interp in ('same', 'other'): + interp = fix.get_interpreter(interp) + if interp.name == 'main': + continue + self._assert_closed_in_interp(fix, interp) + + interp = fix.get_interpreter('fresh') + self._assert_closed_in_interp(fix, interp) + + def _iter_close_tests(self, verbose=False): + i = 0 + for actions in self.iter_action_sets(): + print() + for fix in self.iter_fixtures(): + i += 1 + if i > 1000: + return + if verbose: + if (i - 1) % 6 == 0: + print() + print(i, fix, '({} actions)'.format(len(actions))) + else: + if (i - 1) % 6 == 0: + print(' ', end='') + print('.', end=''); sys.stdout.flush() + yield i, fix, actions + if verbose: + print('---') + print() + + # This is useful for scanning through the possible tests. + def _skim_close_tests(self): + ChannelCloseFixture.QUICK = True + for i, fix, actions in self._iter_close_tests(): + pass + + def test_close(self): + for i, fix, actions in self._iter_close_tests(): + with self.subTest('{} {} {}'.format(i, fix, actions)): + fix.prep_interpreter(fix.interp) + self.run_actions(fix, actions) + + self._close(fix, force=False) + + self._assert_closed(fix) + # XXX Things slow down if we have too many interpreters. + fix.clean_up() + + def test_force_close(self): + for i, fix, actions in self._iter_close_tests(): + with self.subTest('{} {} {}'.format(i, fix, actions)): + fix.prep_interpreter(fix.interp) + self.run_actions(fix, actions) + + self._close(fix, force=True) + + self._assert_closed(fix) + # XXX Things slow down if we have too many interpreters. + fix.clean_up() + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test__interpreters.py b/Lib/test/test__interpreters.py new file mode 100644 index 00000000000..ec5a26bc1c0 --- /dev/null +++ b/Lib/test/test__interpreters.py @@ -0,0 +1,1124 @@ +import contextlib +import os +import pickle +from textwrap import dedent +import threading +import unittest + +from test import support +from test.support import import_helper +from test.support import os_helper +from test.support import script_helper + + +_interpreters = import_helper.import_module('_interpreters') +from _interpreters import InterpreterNotFoundError + + +################################## +# helpers + +def _captured_script(script): + r, w = os.pipe() + indented = script.replace('\n', '\n ') + wrapped = dedent(f""" + import contextlib + with open({w}, 'w', encoding="utf-8") as spipe: + with contextlib.redirect_stdout(spipe): + {indented} + """) + return wrapped, open(r, encoding="utf-8") + + +def _run_output(interp, request): + script, rpipe = _captured_script(request) + with rpipe: + _interpreters.run_string(interp, script) + return rpipe.read() + + +def _wait_for_interp_to_run(interp, timeout=None): + # bpo-37224: Running this test file in multiprocesses will fail randomly. + # The failure reason is that the thread can't acquire the cpu to + # run subinterpreter earlier than the main thread in multiprocess. + if timeout is None: + timeout = support.SHORT_TIMEOUT + for _ in support.sleeping_retry(timeout, error=False): + if _interpreters.is_running(interp): + break + else: + raise RuntimeError('interp is not running') + + +@contextlib.contextmanager +def _running(interp): + r, w = os.pipe() + def run(): + _interpreters.run_string(interp, dedent(f""" + # wait for "signal" + with open({r}, encoding="utf-8") as rpipe: + rpipe.read() + """)) + + t = threading.Thread(target=run) + t.start() + _wait_for_interp_to_run(interp) + + yield + + with open(w, 'w', encoding="utf-8") as spipe: + spipe.write('done') + t.join() + + +def clean_up_interpreters(): + for id, *_ in _interpreters.list_all(): + if id == 0: # main + continue + try: + _interpreters.destroy(id) + except _interpreters.InterpreterError: + pass # already destroyed + + +class TestBase(unittest.TestCase): + + def tearDown(self): + clean_up_interpreters() + + +################################## +# misc. tests + +class IsShareableTests(unittest.TestCase): + + def test_default_shareables(self): + shareables = [ + # singletons + None, + # builtin objects + b'spam', + 'spam', + 10, + -10, + True, + False, + 100.0, + (1, ('spam', 'eggs')), + ] + for obj in shareables: + with self.subTest(obj): + self.assertTrue( + _interpreters.is_shareable(obj)) + + def test_not_shareable(self): + class Cheese: + def __init__(self, name): + self.name = name + def __str__(self): + return self.name + + class SubBytes(bytes): + """A subclass of a shareable type.""" + + not_shareables = [ + # singletons + NotImplemented, + ..., + # builtin types and objects + type, + object, + object(), + Exception(), + # user-defined types and objects + Cheese, + Cheese('Wensleydale'), + SubBytes(b'spam'), + ] + for obj in not_shareables: + with self.subTest(repr(obj)): + self.assertFalse( + _interpreters.is_shareable(obj)) + + +class ModuleTests(TestBase): + + def test_import_in_interpreter(self): + _run_output( + _interpreters.create(), + 'import _interpreters', + ) + + +################################## +# interpreter tests + +class ListAllTests(TestBase): + + def test_initial(self): + main, *_ = _interpreters.get_main() + ids = [id for id, *_ in _interpreters.list_all()] + self.assertEqual(ids, [main]) + + def test_after_creating(self): + main, *_ = _interpreters.get_main() + first = _interpreters.create() + second = _interpreters.create() + ids = [id for id, *_ in _interpreters.list_all()] + self.assertEqual(ids, [main, first, second]) + + def test_after_destroying(self): + main, *_ = _interpreters.get_main() + first = _interpreters.create() + second = _interpreters.create() + _interpreters.destroy(first) + ids = [id for id, *_ in _interpreters.list_all()] + self.assertEqual(ids, [main, second]) + + +class GetCurrentTests(TestBase): + + def test_main(self): + main, *_ = _interpreters.get_main() + cur, *_ = _interpreters.get_current() + self.assertEqual(cur, main) + self.assertIsInstance(cur, int) + + def test_subinterpreter(self): + main, *_ = _interpreters.get_main() + interp = _interpreters.create() + out = _run_output(interp, dedent(""" + import _interpreters + cur, *_ = _interpreters.get_current() + print(cur) + assert isinstance(cur, int) + """)) + cur = int(out.strip()) + _, expected = [id for id, *_ in _interpreters.list_all()] + self.assertEqual(cur, expected) + self.assertNotEqual(cur, main) + + +class GetMainTests(TestBase): + + def test_from_main(self): + [expected] = [id for id, *_ in _interpreters.list_all()] + main, *_ = _interpreters.get_main() + self.assertEqual(main, expected) + self.assertIsInstance(main, int) + + def test_from_subinterpreter(self): + [expected] = [id for id, *_ in _interpreters.list_all()] + interp = _interpreters.create() + out = _run_output(interp, dedent(""" + import _interpreters + main, *_ = _interpreters.get_main() + print(main) + assert isinstance(main, int) + """)) + main = int(out.strip()) + self.assertEqual(main, expected) + + +class IsRunningTests(TestBase): + + def test_main(self): + main, *_ = _interpreters.get_main() + self.assertTrue(_interpreters.is_running(main)) + + @unittest.skip('Fails on FreeBSD') + def test_subinterpreter(self): + interp = _interpreters.create() + self.assertFalse(_interpreters.is_running(interp)) + + with _running(interp): + self.assertTrue(_interpreters.is_running(interp)) + self.assertFalse(_interpreters.is_running(interp)) + + def test_from_subinterpreter(self): + interp = _interpreters.create() + out = _run_output(interp, dedent(f""" + import _interpreters + if _interpreters.is_running({interp}): + print(True) + else: + print(False) + """)) + self.assertEqual(out.strip(), 'True') + + def test_already_destroyed(self): + interp = _interpreters.create() + _interpreters.destroy(interp) + with self.assertRaises(InterpreterNotFoundError): + _interpreters.is_running(interp) + + def test_does_not_exist(self): + with self.assertRaises(InterpreterNotFoundError): + _interpreters.is_running(1_000_000) + + def test_bad_id(self): + with self.assertRaises(ValueError): + _interpreters.is_running(-1) + + +class CreateTests(TestBase): + + def test_in_main(self): + id = _interpreters.create() + self.assertIsInstance(id, int) + + after = [id for id, *_ in _interpreters.list_all()] + self.assertIn(id, after) + + @unittest.skip('enable this test when working on pystate.c') + def test_unique_id(self): + seen = set() + for _ in range(100): + id = _interpreters.create() + _interpreters.destroy(id) + seen.add(id) + + self.assertEqual(len(seen), 100) + + @support.skip_if_sanitizer('gh-129824: race on tp_flags', thread=True) + def test_in_thread(self): + lock = threading.Lock() + id = None + def f(): + nonlocal id + id = _interpreters.create() + lock.acquire() + lock.release() + + t = threading.Thread(target=f) + with lock: + t.start() + t.join() + after = set(id for id, *_ in _interpreters.list_all()) + self.assertIn(id, after) + + def test_in_subinterpreter(self): + main, = [id for id, *_ in _interpreters.list_all()] + id1 = _interpreters.create() + out = _run_output(id1, dedent(""" + import _interpreters + id = _interpreters.create() + print(id) + assert isinstance(id, int) + """)) + id2 = int(out.strip()) + + after = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(after, {main, id1, id2}) + + def test_in_threaded_subinterpreter(self): + main, = [id for id, *_ in _interpreters.list_all()] + id1 = _interpreters.create() + id2 = None + def f(): + nonlocal id2 + out = _run_output(id1, dedent(""" + import _interpreters + id = _interpreters.create() + print(id) + """)) + id2 = int(out.strip()) + + t = threading.Thread(target=f) + t.start() + t.join() + + after = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(after, {main, id1, id2}) + + def test_after_destroy_all(self): + before = set(id for id, *_ in _interpreters.list_all()) + # Create 3 subinterpreters. + ids = [] + for _ in range(3): + id = _interpreters.create() + ids.append(id) + # Now destroy them. + for id in ids: + _interpreters.destroy(id) + # Finally, create another. + id = _interpreters.create() + after = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(after, before | {id}) + + def test_after_destroy_some(self): + before = set(id for id, *_ in _interpreters.list_all()) + # Create 3 subinterpreters. + id1 = _interpreters.create() + id2 = _interpreters.create() + id3 = _interpreters.create() + # Now destroy 2 of them. + _interpreters.destroy(id1) + _interpreters.destroy(id3) + # Finally, create another. + id = _interpreters.create() + after = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(after, before | {id, id2}) + + +class DestroyTests(TestBase): + + def test_one(self): + id1 = _interpreters.create() + id2 = _interpreters.create() + id3 = _interpreters.create() + before = set(id for id, *_ in _interpreters.list_all()) + self.assertIn(id2, before) + + _interpreters.destroy(id2) + + after = set(id for id, *_ in _interpreters.list_all()) + self.assertNotIn(id2, after) + self.assertIn(id1, after) + self.assertIn(id3, after) + + def test_all(self): + initial = set(id for id, *_ in _interpreters.list_all()) + ids = set() + for _ in range(3): + id = _interpreters.create() + ids.add(id) + before = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(before, initial | ids) + for id in ids: + _interpreters.destroy(id) + after = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(after, initial) + + def test_main(self): + main, = [id for id, *_ in _interpreters.list_all()] + with self.assertRaises(_interpreters.InterpreterError): + _interpreters.destroy(main) + + def f(): + with self.assertRaises(_interpreters.InterpreterError): + _interpreters.destroy(main) + + t = threading.Thread(target=f) + t.start() + t.join() + + def test_already_destroyed(self): + id = _interpreters.create() + _interpreters.destroy(id) + with self.assertRaises(InterpreterNotFoundError): + _interpreters.destroy(id) + + def test_does_not_exist(self): + with self.assertRaises(InterpreterNotFoundError): + _interpreters.destroy(1_000_000) + + def test_bad_id(self): + with self.assertRaises(ValueError): + _interpreters.destroy(-1) + + def test_from_current(self): + main, = [id for id, *_ in _interpreters.list_all()] + id = _interpreters.create() + script = dedent(f""" + import _interpreters + try: + _interpreters.destroy({id}) + except _interpreters.InterpreterError: + pass + """) + + _interpreters.run_string(id, script) + after = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(after, {main, id}) + + def test_from_sibling(self): + main, = [id for id, *_ in _interpreters.list_all()] + id1 = _interpreters.create() + id2 = _interpreters.create() + script = dedent(f""" + import _interpreters + _interpreters.destroy({id2}) + """) + _interpreters.run_string(id1, script) + + after = set(id for id, *_ in _interpreters.list_all()) + self.assertEqual(after, {main, id1}) + + def test_from_other_thread(self): + id = _interpreters.create() + def f(): + _interpreters.destroy(id) + + t = threading.Thread(target=f) + t.start() + t.join() + + def test_still_running(self): + main, = [id for id, *_ in _interpreters.list_all()] + interp = _interpreters.create() + with _running(interp): + self.assertTrue(_interpreters.is_running(interp), + msg=f"Interp {interp} should be running before destruction.") + + with self.assertRaises(_interpreters.InterpreterError, + msg=f"Should not be able to destroy interp {interp} while it's still running."): + _interpreters.destroy(interp) + self.assertTrue(_interpreters.is_running(interp)) + + +class CommonTests(TestBase): + def setUp(self): + super().setUp() + self.id = _interpreters.create() + + def test_signatures(self): + # See https://github.com/python/cpython/issues/126654 + msg = r"exec\(\) argument 'shared' must be dict, not int" + with self.assertRaisesRegex(TypeError, msg): + _interpreters.exec(self.id, 'a', 1) + with self.assertRaisesRegex(TypeError, msg): + _interpreters.exec(self.id, 'a', shared=1) + msg = r"run_string\(\) argument 'shared' must be dict, not int" + with self.assertRaisesRegex(TypeError, msg): + _interpreters.run_string(self.id, 'a', shared=1) + msg = r"run_func\(\) argument 'shared' must be dict, not int" + with self.assertRaisesRegex(TypeError, msg): + _interpreters.run_func(self.id, lambda: None, shared=1) + # See https://github.com/python/cpython/issues/135855 + msg = r"set___main___attrs\(\) argument 'updates' must be dict, not int" + with self.assertRaisesRegex(TypeError, msg): + _interpreters.set___main___attrs(self.id, 1) + + def test_invalid_shared_none(self): + msg = r'must be dict, not None' + with self.assertRaisesRegex(TypeError, msg): + _interpreters.exec(self.id, 'a', shared=None) + with self.assertRaisesRegex(TypeError, msg): + _interpreters.run_string(self.id, 'a', shared=None) + with self.assertRaisesRegex(TypeError, msg): + _interpreters.run_func(self.id, lambda: None, shared=None) + with self.assertRaisesRegex(TypeError, msg): + _interpreters.set___main___attrs(self.id, None) + + def test_invalid_shared_encoding(self): + # See https://github.com/python/cpython/issues/127196 + bad_shared = {"\uD82A": 0} + msg = 'surrogates not allowed' + with self.assertRaisesRegex(UnicodeEncodeError, msg): + _interpreters.exec(self.id, 'a', shared=bad_shared) + with self.assertRaisesRegex(UnicodeEncodeError, msg): + _interpreters.run_string(self.id, 'a', shared=bad_shared) + with self.assertRaisesRegex(UnicodeEncodeError, msg): + _interpreters.run_func(self.id, lambda: None, shared=bad_shared) + + +class RunStringTests(TestBase): + + def setUp(self): + super().setUp() + self.id = _interpreters.create() + + def test_success(self): + script, file = _captured_script('print("it worked!", end="")') + with file: + _interpreters.run_string(self.id, script) + out = file.read() + + self.assertEqual(out, 'it worked!') + + def test_in_thread(self): + script, file = _captured_script('print("it worked!", end="")') + with file: + def f(): + _interpreters.run_string(self.id, script) + + t = threading.Thread(target=f) + t.start() + t.join() + out = file.read() + + self.assertEqual(out, 'it worked!') + + def test_create_thread(self): + subinterp = _interpreters.create() + script, file = _captured_script(""" + import threading + def f(): + print('it worked!', end='') + + t = threading.Thread(target=f) + t.start() + t.join() + """) + with file: + _interpreters.run_string(subinterp, script) + out = file.read() + + self.assertEqual(out, 'it worked!') + + def test_create_daemon_thread(self): + with self.subTest('isolated'): + expected = 'spam spam spam spam spam' + subinterp = _interpreters.create('isolated') + script, file = _captured_script(f""" + import threading + def f(): + print('it worked!', end='') + + try: + t = threading.Thread(target=f, daemon=True) + t.start() + t.join() + except RuntimeError: + print('{expected}', end='') + """) + with file: + _interpreters.run_string(subinterp, script) + out = file.read() + + self.assertEqual(out, expected) + + with self.subTest('not isolated'): + subinterp = _interpreters.create('legacy') + script, file = _captured_script(""" + import threading + def f(): + print('it worked!', end='') + + t = threading.Thread(target=f, daemon=True) + t.start() + t.join() + """) + with file: + _interpreters.run_string(subinterp, script) + out = file.read() + + self.assertEqual(out, 'it worked!') + + def test_shareable_types(self): + interp = _interpreters.create() + objects = [ + None, + 'spam', + b'spam', + 42, + ] + for obj in objects: + with self.subTest(obj): + _interpreters.set___main___attrs(interp, dict(obj=obj)) + _interpreters.run_string( + interp, + f'assert(obj == {obj!r})', + ) + + def test_os_exec(self): + expected = 'spam spam spam spam spam' + subinterp = _interpreters.create() + script, file = _captured_script(f""" + import os, sys + try: + os.execl(sys.executable) + except RuntimeError: + print('{expected}', end='') + """) + with file: + _interpreters.run_string(subinterp, script) + out = file.read() + + self.assertEqual(out, expected) + + @support.requires_fork() + def test_fork(self): + import tempfile + with tempfile.NamedTemporaryFile('w+', encoding="utf-8") as file: + file.write('') + file.flush() + + expected = 'spam spam spam spam spam' + script = dedent(f""" + import os + try: + os.fork() + except RuntimeError: + with open('{file.name}', 'w', encoding='utf-8') as out: + out.write('{expected}') + """) + _interpreters.run_string(self.id, script) + + file.seek(0) + content = file.read() + self.assertEqual(content, expected) + + def test_already_running(self): + with _running(self.id): + with self.assertRaises(_interpreters.InterpreterError): + _interpreters.run_string(self.id, 'print("spam")') + + def test_does_not_exist(self): + id = 0 + while id in set(id for id, *_ in _interpreters.list_all()): + id += 1 + with self.assertRaises(InterpreterNotFoundError): + _interpreters.run_string(id, 'print("spam")') + + def test_error_id(self): + with self.assertRaises(ValueError): + _interpreters.run_string(-1, 'print("spam")') + + def test_bad_id(self): + with self.assertRaises(TypeError): + _interpreters.run_string('spam', 'print("spam")') + + def test_bad_script(self): + with self.assertRaises(TypeError): + _interpreters.run_string(self.id, 10) + + def test_bytes_for_script(self): + with self.assertRaises(TypeError): + _interpreters.run_string(self.id, b'print("spam")') + + def test_str_subclass_string(self): + class StrSubclass(str): pass + + output = _run_output(self.id, StrSubclass('print(1 + 2)')) + self.assertEqual(output, '3\n') + + def test_with_shared(self): + r, w = os.pipe() + + shared = { + 'spam': b'ham', + 'eggs': b'-1', + 'cheddar': None, + } + script = dedent(f""" + eggs = int(eggs) + spam = 42 + result = spam + eggs + + ns = dict(vars()) + del ns['__builtins__'] + import pickle + with open({w}, 'wb') as chan: + pickle.dump(ns, chan) + """) + _interpreters.set___main___attrs(self.id, shared) + _interpreters.run_string(self.id, script) + with open(r, 'rb') as chan: + ns = pickle.load(chan) + + self.assertEqual(ns['spam'], 42) + self.assertEqual(ns['eggs'], -1) + self.assertEqual(ns['result'], 41) + self.assertIsNone(ns['cheddar']) + + def test_shared_overwrites(self): + _interpreters.run_string(self.id, dedent(""" + spam = 'eggs' + ns1 = dict(vars()) + del ns1['__builtins__'] + """)) + + shared = {'spam': b'ham'} + script = dedent(""" + ns2 = dict(vars()) + del ns2['__builtins__'] + """) + _interpreters.set___main___attrs(self.id, shared) + _interpreters.run_string(self.id, script) + + r, w = os.pipe() + script = dedent(f""" + ns = dict(vars()) + del ns['__builtins__'] + import pickle + with open({w}, 'wb') as chan: + pickle.dump(ns, chan) + """) + _interpreters.run_string(self.id, script) + with open(r, 'rb') as chan: + ns = pickle.load(chan) + + self.assertEqual(ns['ns1']['spam'], 'eggs') + self.assertEqual(ns['ns2']['spam'], b'ham') + self.assertEqual(ns['spam'], b'ham') + + def test_shared_overwrites_default_vars(self): + r, w = os.pipe() + + shared = {'__name__': b'not __main__'} + script = dedent(f""" + spam = 42 + + ns = dict(vars()) + del ns['__builtins__'] + import pickle + with open({w}, 'wb') as chan: + pickle.dump(ns, chan) + """) + _interpreters.set___main___attrs(self.id, shared) + _interpreters.run_string(self.id, script) + with open(r, 'rb') as chan: + ns = pickle.load(chan) + + self.assertEqual(ns['__name__'], b'not __main__') + + def test_main_reused(self): + r, w = os.pipe() + _interpreters.run_string(self.id, dedent(f""" + spam = True + + ns = dict(vars()) + del ns['__builtins__'] + import pickle + with open({w}, 'wb') as chan: + pickle.dump(ns, chan) + del ns, pickle, chan + """)) + with open(r, 'rb') as chan: + ns1 = pickle.load(chan) + + r, w = os.pipe() + _interpreters.run_string(self.id, dedent(f""" + eggs = False + + ns = dict(vars()) + del ns['__builtins__'] + import pickle + with open({w}, 'wb') as chan: + pickle.dump(ns, chan) + """)) + with open(r, 'rb') as chan: + ns2 = pickle.load(chan) + + self.assertIn('spam', ns1) + self.assertNotIn('eggs', ns1) + self.assertIn('eggs', ns2) + self.assertIn('spam', ns2) + + def test_execution_namespace_is_main(self): + r, w = os.pipe() + + script = dedent(f""" + spam = 42 + + ns = dict(vars()) + ns['__builtins__'] = str(ns['__builtins__']) + import pickle + with open({w}, 'wb') as chan: + pickle.dump(ns, chan) + """) + _interpreters.run_string(self.id, script) + with open(r, 'rb') as chan: + ns = pickle.load(chan) + + ns.pop('__builtins__') + ns.pop('__loader__') + self.assertEqual(ns, { + '__name__': '__main__', + '__doc__': None, + '__package__': None, + '__spec__': None, + 'spam': 42, + }) + + # XXX Fix this test! + @unittest.skip('blocking forever') + def test_still_running_at_exit(self): + script = dedent(""" + from textwrap import dedent + import threading + import _interpreters + id = _interpreters.create() + def f(): + _interpreters.run_string(id, dedent(''' + import time + # Give plenty of time for the main interpreter to finish. + time.sleep(1_000_000) + ''')) + + t = threading.Thread(target=f) + t.start() + """) + with support.temp_dir() as dirname: + filename = script_helper.make_script(dirname, 'interp', script) + with script_helper.spawn_python(filename) as proc: + retcode = proc.wait() + + self.assertEqual(retcode, 0) + + +class RunFailedTests(TestBase): + + def setUp(self): + super().setUp() + self.id = _interpreters.create() + + def add_module(self, modname, text): + import tempfile + tempdir = tempfile.mkdtemp() + self.addCleanup(lambda: os_helper.rmtree(tempdir)) + _interpreters.run_string(self.id, dedent(f""" + import sys + sys.path.insert(0, {tempdir!r}) + """)) + return script_helper.make_script(tempdir, modname, text) + + def run_script(self, text, *, fails=False): + r, w = os.pipe() + try: + script = dedent(f""" + import os, sys + os.write({w}, b'0') + + # This raises an exception: + {{}} + + # Nothing from here down should ever run. + os.write({w}, b'1') + class NeverError(Exception): pass + raise NeverError # never raised + """).format(dedent(text)) + if fails: + err = _interpreters.run_string(self.id, script) + self.assertIsNot(err, None) + return err + else: + err = _interpreters.run_string(self.id, script) + self.assertIs(err, None) + return None + except: + raise # re-raise + else: + msg = os.read(r, 100) + self.assertEqual(msg, b'0') + finally: + os.close(r) + os.close(w) + + def _assert_run_failed(self, exctype, msg, script): + if isinstance(exctype, str): + exctype_name = exctype + exctype = None + else: + exctype_name = exctype.__name__ + + # Run the script. + excinfo = self.run_script(script, fails=True) + + # Check the wrapper exception. + self.assertEqual(excinfo.type.__name__, exctype_name) + if msg is None: + self.assertEqual(excinfo.formatted.split(':')[0], + exctype_name) + else: + self.assertEqual(excinfo.formatted, + '{}: {}'.format(exctype_name, msg)) + + return excinfo + + def assert_run_failed(self, exctype, script): + self._assert_run_failed(exctype, None, script) + + def assert_run_failed_msg(self, exctype, msg, script): + self._assert_run_failed(exctype, msg, script) + + def test_exit(self): + with self.subTest('sys.exit(0)'): + # XXX Should an unhandled SystemExit(0) be handled as not-an-error? + self.assert_run_failed(SystemExit, """ + sys.exit(0) + """) + + with self.subTest('sys.exit()'): + self.assert_run_failed(SystemExit, """ + import sys + sys.exit() + """) + + with self.subTest('sys.exit(42)'): + self.assert_run_failed_msg(SystemExit, '42', """ + import sys + sys.exit(42) + """) + + with self.subTest('SystemExit'): + self.assert_run_failed_msg(SystemExit, '42', """ + raise SystemExit(42) + """) + + # XXX Also check os._exit() (via a subprocess)? + + def test_plain_exception(self): + self.assert_run_failed_msg(Exception, 'spam', """ + raise Exception("spam") + """) + + def test_invalid_syntax(self): + script = dedent(""" + x = 1 + 2 + y = 2 + 4 + z = 4 + 8 + + # missing close paren + print("spam" + + if x + y + z < 20: + ... + """) + + with self.subTest('script'): + with self.assertRaises(SyntaxError): + _interpreters.run_string(self.id, script) + + with self.subTest('module'): + modname = 'spam_spam_spam' + filename = self.add_module(modname, script) + self.assert_run_failed(SyntaxError, f""" + import {modname} + """) + + def test_NameError(self): + self.assert_run_failed(NameError, """ + res = spam + eggs + """) + # XXX check preserved suggestions + + def test_AttributeError(self): + self.assert_run_failed(AttributeError, """ + object().spam + """) + # XXX check preserved suggestions + + def test_ExceptionGroup(self): + self.assert_run_failed(ExceptionGroup, """ + raise ExceptionGroup('exceptions', [ + Exception('spam'), + ImportError('eggs'), + ]) + """) + + def test_user_defined_exception(self): + self.assert_run_failed_msg('MyError', 'spam', """ + class MyError(Exception): + pass + raise MyError('spam') + """) + + +class RunFuncTests(TestBase): + + def setUp(self): + super().setUp() + self.id = _interpreters.create() + + def test_success(self): + r, w = os.pipe() + def script(): + global w + import contextlib + with open(w, 'w', encoding="utf-8") as spipe: + with contextlib.redirect_stdout(spipe): + print('it worked!', end='') + _interpreters.set___main___attrs(self.id, dict(w=w)) + _interpreters.run_func(self.id, script) + + with open(r, encoding="utf-8") as outfile: + out = outfile.read() + + self.assertEqual(out, 'it worked!') + + def test_in_thread(self): + r, w = os.pipe() + def script(): + global w + import contextlib + with open(w, 'w', encoding="utf-8") as spipe: + with contextlib.redirect_stdout(spipe): + print('it worked!', end='') + failed = None + def f(): + nonlocal failed + try: + _interpreters.set___main___attrs(self.id, dict(w=w)) + _interpreters.run_func(self.id, script) + except Exception as exc: + failed = exc + t = threading.Thread(target=f) + t.start() + t.join() + if failed: + raise Exception from failed + + with open(r, encoding="utf-8") as outfile: + out = outfile.read() + + self.assertEqual(out, 'it worked!') + + def test_code_object(self): + r, w = os.pipe() + + def script(): + global w + import contextlib + with open(w, 'w', encoding="utf-8") as spipe: + with contextlib.redirect_stdout(spipe): + print('it worked!', end='') + code = script.__code__ + _interpreters.set___main___attrs(self.id, dict(w=w)) + _interpreters.run_func(self.id, code) + + with open(r, encoding="utf-8") as outfile: + out = outfile.read() + + self.assertEqual(out, 'it worked!') + + def test_closure(self): + spam = True + def script(): + assert spam + with self.assertRaises(ValueError): + _interpreters.run_func(self.id, script) + + def test_return_value(self): + def script(): + return 'spam' + with self.assertRaises(ValueError): + _interpreters.run_func(self.id, script) + +# @unittest.skip("we're not quite there yet") + def test_args(self): + with self.subTest('args'): + def script(a, b=0): + assert a == b + with self.assertRaises(ValueError): + _interpreters.run_func(self.id, script) + + with self.subTest('*args'): + def script(*args): + assert not args + with self.assertRaises(ValueError): + _interpreters.run_func(self.id, script) + + with self.subTest('**kwargs'): + def script(**kwargs): + assert not kwargs + with self.assertRaises(ValueError): + _interpreters.run_func(self.id, script) + + with self.subTest('kwonly'): + def script(*, spam=True): + assert spam + with self.assertRaises(ValueError): + _interpreters.run_func(self.id, script) + + with self.subTest('posonly'): + def script(spam, /): + assert spam + with self.assertRaises(ValueError): + _interpreters.run_func(self.id, script) + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test__osx_support.py b/Lib/test/test__osx_support.py index 0813c4804c1..b92ce6796b5 100644 --- a/Lib/test/test__osx_support.py +++ b/Lib/test/test__osx_support.py @@ -25,7 +25,7 @@ def setUp(self): 'CFLAGS', 'LDFLAGS', 'CPPFLAGS', 'BASECFLAGS', 'BLDSHARED', 'LDSHARED', 'CC', 'CXX', 'PY_CFLAGS', 'PY_LDFLAGS', 'PY_CPPFLAGS', - 'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS' + 'PY_CORE_CFLAGS', 'PY_CORE_LDFLAGS', 'PY_CORE_EXE_LDFLAGS' ) def add_expected_saved_initial_values(self, config_vars, expected_vars): diff --git a/Lib/test/test_abc.py b/Lib/test/test_abc.py index 80ee9e0ba56..f3e040ff051 100644 --- a/Lib/test/test_abc.py +++ b/Lib/test/test_abc.py @@ -7,10 +7,12 @@ """Unit tests for abc.py.""" import unittest +import weakref import abc import _py_abc from inspect import isabstract +from test.support import gc_collect def test_factory(abc_ABCMeta, abc_get_cache_token): class TestLegacyAPI(unittest.TestCase): @@ -349,6 +351,52 @@ class C(str): pass self.assertIsSubclass(C, A) self.assertIsSubclass(C, (A,)) + def test_instancecheck_class_changes_in_subclasscheck(self): + class Original: + def __getattribute__(self, name): + if name == '__class__': + return int + return object.__getattribute__(self, name) + + class Replacement: + pass + + instance = Original() + original = weakref.ref(Original) + del Original + + class Meta(abc_ABCMeta): + def __subclasscheck__(cls, candidate): + if candidate is int: + instance.__class__ = Replacement + gc_collect() + self.assertIsNotNone(original()) + return False + + class Interface(metaclass=Meta): + pass + + self.assertNotIsInstance(instance, Interface) + + def test_instancecheck_no_class(self): + # gh-153772: __instancecheck__ must fall back to type(instance) + # when the instance has no __class__, matching isinstance(). + class NoClass: + def __getattribute__(self, name): + if name == "__class__": + raise AttributeError(name) + return super().__getattribute__(name) + + class A(metaclass=abc_ABCMeta): + pass + + obj = NoClass() + # Must return False rather than propagating the AttributeError. + self.assertNotIsInstance(obj, A) + # Registering the actual type makes the fallback report a match. + A.register(NoClass) + self.assertIsInstance(obj, A) + def test_registration_edge_cases(self): class A(metaclass=abc_ABCMeta): pass diff --git a/Lib/test/test_android.py b/Lib/test/test_android.py index 31daafbc3d6..edab0fe71a6 100644 --- a/Lib/test/test_android.py +++ b/Lib/test/test_android.py @@ -1,4 +1,5 @@ import io +import platform import queue import re import subprocess @@ -16,6 +17,11 @@ if sys.platform != "android": raise unittest.SkipTest("Android-specific") +# Some API levels filter out consecutive identical lines and replace them with a +# "chatty" marker. +api_level = platform.android_ver().api_level +chatty_issue = (26 <= api_level <= 30) + # (name, level, fileno) STREAM_INFO = [("stdout", "I", 1), ("stderr", "W", 2)] @@ -174,15 +180,13 @@ def write(s, lines=None, *, write_len=None): write("\u0000b", [r"\xc0\x80b"]) write("a\u0000b", [r"a\xc0\x80b"]) - # Multi-line messages. Avoid identical consecutive lines, as - # they may activate "chatty" filtering and break the tests. - # - # Additional spaces will appear in the output where necessary to - # protect leading newlines. + # Multi-line messages. Additional spaces will appear in the output where + # necessary to protect leading newlines. write("\nx", [" "]) write("\na\n", ["x", "a"]) write("\n", [" "]) - write("\n\n", [" ", " "]) + if not chatty_issue: + write("\n\n", [" ", " "]) write("b\n", ["b"]) write("c\n\n", ["c", " "]) write("d\ne", ["d"]) @@ -201,7 +205,8 @@ def write(s, lines=None, *, write_len=None): write("\nx", [" ", "x"]) write("\na\n", [" ", "a"]) write("\n", [" "]) - write("\n\n", [" ", " "]) + if not chatty_issue: + write("\n\n", [" ", " "]) write("b\n", ["b"]) write("c\n\n", ["c", " "]) write("d\ne", ["d", "e"]) diff --git a/Lib/test/test_annotationlib.py b/Lib/test/test_annotationlib.py index 5087c3ca425..151be2a12ff 100644 --- a/Lib/test/test_annotationlib.py +++ b/Lib/test/test_annotationlib.py @@ -654,6 +654,13 @@ def f(x: 'int') -> 'str': ... result = get_annotations(f, eval_str=True) self.assertEqual(result, {'x': int, 'return': str}) + def test_eval_str_wrapped_partial_cycle_self(self): + def f(x: 'int') -> 'str': ... + f.__wrapped__ = functools.partial(f, 0) + # Cycle is detected and broken; globals from f itself are used. + result = get_annotations(f, eval_str=True) + self.assertEqual(result, {'x': int, 'return': str}) + def test_eval_str_wrapped_cycle_mutual(self): # gh-146556: mutual __wrapped__ cycle (a -> b -> a) must not hang. def a(x: 'int'): ... @@ -1850,6 +1857,18 @@ def nested(): type_repr(nested), f"{__name__}.TestTypeRepr.test_type_repr..nested" ) self.assertEqual(type_repr(len), "len") + # gh-152692: built-in methods have __module__ set to None + self.assertEqual(type_repr([].append), "list.append") + self.assertEqual(type_repr((1).bit_length), "int.bit_length") + self.assertEqual(type_repr(dict.fromkeys), "dict.fromkeys") + # Methods of extension types also have __module__ set to None, but + # are not in the builtins module. + import datetime + self.assertEqual( + type_repr(datetime.datetime(2000, 1, 1).isoformat), + "datetime.datetime.isoformat", + ) + self.assertEqual(type_repr(datetime.date.today), "datetime.date.today") self.assertEqual(type_repr(type_repr), "annotationlib.type_repr") self.assertEqual(type_repr(times_three), f"{__name__}.times_three") self.assertEqual(type_repr(...), "...") @@ -1862,7 +1881,7 @@ def nested(): self.assertEqual(type_repr(t'''{ 0 & 1 | 2 - }'''), 't"""{ 0\n & 1\n | 2}"""') + }'''), 't"""{ 0\n & 1\n | 2\n }"""') self.assertEqual( type_repr(Template("hi", Interpolation(42, "42"))), "t'hi{42}'" ) @@ -1874,6 +1893,10 @@ def nested(): type_repr(Template("hi", Interpolation(42, " "))), "Template('hi', Interpolation(42, ' ', None, ''))", ) + self.assertEqual( + type_repr(Template("hi", Interpolation(42, "4!2"))), + "Template('hi', Interpolation(42, '4!2', None, ''))", + ) # gh138558: perhaps in the future, we can improve this behavior: self.assertEqual(type_repr(Template(Interpolation(42, "99"))), "t'{99}'") @@ -2133,8 +2156,13 @@ def f(a: unknown | str | int | list[str] | tuple[int, ...]): ... self.assertIsNone(fr.__resolved_str_cache__) self.assertEqual(fr.evaluate(format=Format.STRING), "unknown | str | int | list[str] | tuple[int, ...]") + + # Test that the cache is now set correctly self.assertEqual(fr.__resolved_str_cache__, "unknown | str | int | list[str] | tuple[int, ...]") + # Test that future evaluations return the same cache + self.assertIs(fr.evaluate(format=Format.STRING), fr.__resolved_str_cache__) + def test_evaluate_forwardref_format(self): fr = ForwardRef("undef") evaluated = fr.evaluate(format=Format.FORWARDREF) @@ -2163,6 +2191,118 @@ def test_evaluate_forwardref_format(self): support.EqualToForwardRef('"a" + 1'), ) + def test_evaluate_lazy_import(self): + ns = {} + exec( + textwrap.dedent( + """ + lazy from test.test_lazy_import.data.basic2 import x + lazy from test.test_lazy_import.data.broken_module import y + + class A: + a: x + + class B: + b: y + """ + ), + ns, + ) + self.addCleanup( + import_helper.unload, "test.test_lazy_import.data.basic2" + ) + self.addCleanup( + import_helper.unload, "test.test_lazy_import.data.broken_module" + ) + self.assertIs(type(ns["x"]), types.LazyImportType) + self.assertIs(type(ns["y"]), types.LazyImportType) + + # The lazy import resolves successfully: + for format in (Format.VALUE, Format.FORWARDREF): + with self.subTest(format=format): + self.assertEqual( + ForwardRef("x").evaluate(globals=ns, format=format), 42 + ) + self.assertEqual( + ForwardRef("x").evaluate(locals=ns, format=format), 42 + ) + self.assertEqual( + get_annotations(ns["A"], format=Format.FORWARDREF), {"a": 42} + ) + + # The lazy import fails to resolve: + fr = ForwardRef("y") + with self.assertRaisesRegex(ValueError, "always fails to import"): + fr.evaluate(globals=ns, format=Format.VALUE) + with self.assertRaisesRegex(ValueError, "always fails to import"): + fr.evaluate(locals=ns, format=Format.VALUE) + self.assertIs(fr.evaluate(globals=ns, format=Format.FORWARDREF), fr) + self.assertIs(fr.evaluate(locals=ns, format=Format.FORWARDREF), fr) + + annos = get_annotations(ns["B"], format=Format.FORWARDREF) + self.assertEqual( + annos, + {"b": support.EqualToForwardRef("y", is_class=True, owner=ns["B"])}, + ) + with self.assertRaisesRegex(ValueError, "always fails to import"): + annos["b"].evaluate(format=Format.VALUE) + with self.assertRaisesRegex(ValueError, "always fails to import"): + get_annotations(ns["B"], format=Format.VALUE) + + def test_get_annotations_lazy_import(self): + ns = {} + exec( + textwrap.dedent( + """ + lazy from test.test_lazy_import.data.basic2 import x + lazy from test.test_lazy_import.data.broken_module import y + + class A: + a: object.fail + b: x + + class B: + a: object.fail + b: y + """ + ), + ns, + ) + self.addCleanup( + import_helper.unload, "test.test_lazy_import.data.basic2" + ) + self.addCleanup( + import_helper.unload, "test.test_lazy_import.data.broken_module" + ) + self.assertIs(type(ns["x"]), types.LazyImportType) + self.assertIs(type(ns["y"]), types.LazyImportType) + + annos = get_annotations(ns["A"], format=Format.FORWARDREF) + self.assertEqual( + annos, + { + "a": support.EqualToForwardRef( + "object.fail", is_class=True, owner=ns["A"] + ), + "b": 42, + }, + ) + + annos = get_annotations(ns["B"], format=Format.FORWARDREF) + self.assertEqual( + annos, + { + "a": support.EqualToForwardRef( + "object.fail", is_class=True, owner=ns["B"] + ), + "b": support.EqualToForwardRef( + "y", is_class=True, owner=ns["B"] + ), + }, + ) + with self.assertRaisesRegex(ValueError, "always fails to import"): + annos["b"].evaluate(format=Format.VALUE) + def test_evaluate_notimplemented_format(self): class C: x: alias diff --git a/Lib/test/test_argparse.py b/Lib/test/test_argparse.py index e376c44faa4..c8954b20740 100644 --- a/Lib/test/test_argparse.py +++ b/Lib/test/test_argparse.py @@ -7,7 +7,6 @@ import io import operator import os -import py_compile import shutil import stat import sys @@ -81,6 +80,108 @@ def test_skip_invalid_stdout(self): self.assertRegex(mocked_stderr.getvalue(), r'usage:') +class TestLazyImports(unittest.TestCase): + LAZY_IMPORTS = { + "_colorize", + "copy", + "difflib", + "shutil", + "textwrap", + "warnings", + } + def test_module_import(self): + import_helper.ensure_lazy_imports( + "argparse", + self.LAZY_IMPORTS, + ) + + def test_create_parser(self): + # Test imports are still unused after + # creating a parser + create_parser = "argparse.ArgumentParser()" + imported_modules = {"shutil"} + + import_helper.ensure_lazy_imports( + "argparse", + self.LAZY_IMPORTS - imported_modules, + additional_code=create_parser, + ) + + def test_add_subparser(self): + add_subparser = textwrap.dedent( + """ + parser = argparse.ArgumentParser() + parser.add_subparsers(dest='command', required=False) + """ + ) + imported_modules = {"shutil"} + + import_helper.ensure_lazy_imports( + "argparse", + self.LAZY_IMPORTS - imported_modules, + additional_code=add_subparser, + ) + + def test_parse_args(self): + example_parser = textwrap.dedent( + """ + parser = argparse.ArgumentParser(prog='PROG') + parser.add_argument('-f', '--foo') + parser.add_argument('bar') + parser.parse_args(['BAR']) + parser.parse_args(['BAR', '--foo', 'FOO']) + """ + ) + imported_modules = {"shutil"} + import_helper.ensure_lazy_imports( + "argparse", + self.LAZY_IMPORTS - imported_modules, + additional_code=example_parser + ) + + +class TestArgumentParserCopiable(unittest.TestCase): + def _get_parser(self): + parser = argparse.ArgumentParser(exit_on_error=False) + parser.add_argument('--foo', type=int, default=42) + parser.add_argument('bar', nargs='?', default='baz') + return parser + + @force_not_colorized + def test_copiable(self): + import copy + parser = self._get_parser() + parser2 = copy.copy(parser) + ns = parser2.parse_args(['--foo', '123', 'quux']) + self.assertEqual(ns.foo, 123) + self.assertEqual(ns.bar, 'quux') + ns2 = parser2.parse_args([]) + self.assertEqual(ns2.foo, 42) + self.assertEqual(ns2.bar, 'baz') + + # Test shallow copy also gets new arguments + parser.add_argument("--extra") + ns3 = parser2.parse_args(["--extra", "bar"]) + self.assertEqual(ns3.extra, "bar") + + @force_not_colorized + def test_deepcopiable(self): + import copy + parser = self._get_parser() + parser2 = copy.deepcopy(parser) + ns = parser2.parse_args(['--foo', '123', 'quux']) + self.assertEqual(ns.foo, 123) + self.assertEqual(ns.bar, 'quux') + ns2 = parser2.parse_args([]) + self.assertEqual(ns2.foo, 42) + self.assertEqual(ns2.bar, 'baz') + + # Test deep copy does not get new arguments + parser.add_argument("--extra") + with self.assertRaises(argparse.ArgumentError): + parser2.parse_args(["--extra", "bar"]) + + class TestArgumentParserPickleable(unittest.TestCase): @force_not_colorized @@ -602,13 +703,22 @@ class TestOptionalsShortLong(ParserTestCase): class TestOptionalsDest(ParserTestCase): """Tests various means of setting destination""" - argument_signatures = [Sig('--foo-bar'), Sig('--baz', dest='zabbaz')] + argument_signatures = [ + Sig('-x', '-foobar', '--foo-bar', '-barfoo', '-X'), + Sig('--baz', dest='zabbaz'), + Sig('-y', '-qux', '-Y'), + Sig('-z'), + ] failures = ['a'] successes = [ - ('--foo-bar f', NS(foo_bar='f', zabbaz=None)), - ('--baz g', NS(foo_bar=None, zabbaz='g')), - ('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i')), - ('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j')), + ('--foo-bar f', NS(foo_bar='f', zabbaz=None, qux=None, z=None)), + ('-x f', NS(foo_bar='f', zabbaz=None, qux=None, z=None)), + ('--baz g', NS(foo_bar=None, zabbaz='g', qux=None, z=None)), + ('--foo-bar h --baz i', NS(foo_bar='h', zabbaz='i', qux=None, z=None)), + ('--baz j --foo-bar k', NS(foo_bar='k', zabbaz='j', qux=None, z=None)), + ('-qux l', NS(foo_bar=None, zabbaz=None, qux='l', z=None)), + ('-y l', NS(foo_bar=None, zabbaz=None, qux='l', z=None)), + ('-z m', NS(foo_bar=None, zabbaz=None, qux=None, z='m')), ] @@ -817,6 +927,76 @@ def test_invalid_name(self): self.assertEqual(str(cm.exception), "invalid option name '--no-foo' for BooleanOptionalAction") +class TestBooleanOptionalActionSingleDash(ParserTestCase): + """Tests BooleanOptionalAction with single dash""" + + argument_signatures = [ + Sig('-foo', '-x', action=argparse.BooleanOptionalAction), + ] + failures = ['--foo', '--no-foo', '-no-foo', '-no-x', '-nox'] + successes = [ + ('', NS(foo=None)), + ('-foo', NS(foo=True)), + ('-nofoo', NS(foo=False)), + ('-x', NS(foo=True)), + ] + + def test_invalid_name(self): + parser = argparse.ArgumentParser() + with self.assertRaises(ValueError) as cm: + parser.add_argument('-nofoo', action=argparse.BooleanOptionalAction) + self.assertEqual(str(cm.exception), + "invalid option name '-nofoo' for BooleanOptionalAction") + +class TestBooleanOptionalActionAlternatePrefixChars(ParserTestCase): + """Tests BooleanOptionalAction with custom prefixes""" + + parser_signature = Sig(prefix_chars='+-', add_help=False) + argument_signatures = [Sig('++foo', action=argparse.BooleanOptionalAction)] + failures = ['--foo', '--no-foo'] + successes = [ + ('', NS(foo=None)), + ('++foo', NS(foo=True)), + ('++no-foo', NS(foo=False)), + ] + + def test_invalid_name(self): + parser = argparse.ArgumentParser(prefix_chars='+/') + with self.assertRaisesRegex(ValueError, + 'BooleanOptionalAction.*is not valid for positional arguments'): + parser.add_argument('--foo', action=argparse.BooleanOptionalAction) + with self.assertRaises(ValueError) as cm: + parser.add_argument('++no-foo', action=argparse.BooleanOptionalAction) + self.assertEqual(str(cm.exception), + "invalid option name '++no-foo' for BooleanOptionalAction") + +class TestBooleanOptionalActionSingleAlternatePrefixChar(ParserTestCase): + """Tests BooleanOptionalAction with single alternate prefix char""" + + parser_signature = Sig(prefix_chars='+/', add_help=False) + argument_signatures = [ + Sig('+foo', '+x', action=argparse.BooleanOptionalAction), + ] + failures = ['++foo', '++no-foo', '++nofoo', + '-no-foo', '-nofoo', '+no-foo', '-nofoo', + '+no-x', '+nox', '-no-x', '-nox'] + successes = [ + ('', NS(foo=None)), + ('+foo', NS(foo=True)), + ('+nofoo', NS(foo=False)), + ('+x', NS(foo=True)), + ] + + def test_invalid_name(self): + parser = argparse.ArgumentParser(prefix_chars='+/') + with self.assertRaisesRegex(ValueError, + 'BooleanOptionalAction.*is not valid for positional arguments'): + parser.add_argument('-foo', action=argparse.BooleanOptionalAction) + with self.assertRaises(ValueError) as cm: + parser.add_argument('+nofoo', action=argparse.BooleanOptionalAction) + self.assertEqual(str(cm.exception), + "invalid option name '+nofoo' for BooleanOptionalAction") + class TestBooleanOptionalActionRequired(ParserTestCase): """Tests BooleanOptionalAction required""" @@ -1856,7 +2036,7 @@ def test_r_1_replace(self): class StdStreamComparer: def __init__(self, attr): # We try to use the actual stdXXX.buffer attribute as our - # marker, but but under some test environments, + # marker, but under some test environments, # sys.stdout/err are replaced by io.StringIO which won't have .buffer, # so we use a sentinel simply to show that the tests do the right thing # for any buffer supporting object @@ -2304,11 +2484,12 @@ class TestNegativeNumber(ParserTestCase): ('--complex -1e-3j', NS(int=None, float=None, complex=-0.001j)), ] +@force_not_colorized_test_class class TestArgumentAndSubparserSuggestions(TestCase): """Test error handling and suggestion when a user makes a typo""" def test_wrong_argument_error_with_suggestions(self): - parser = ErrorRaisingArgumentParser(suggest_on_error=True) + parser = ErrorRaisingArgumentParser() parser.add_argument('foo', choices=['bar', 'baz']) with self.assertRaises(ArgumentParserError) as excinfo: parser.parse_args(('bazz',)) @@ -2328,7 +2509,7 @@ def test_wrong_argument_error_no_suggestions(self): ) def test_wrong_argument_subparsers_with_suggestions(self): - parser = ErrorRaisingArgumentParser(suggest_on_error=True) + parser = ErrorRaisingArgumentParser() subparsers = parser.add_subparsers(required=True) subparsers.add_parser('foo') subparsers.add_parser('bar') @@ -2352,18 +2533,19 @@ def test_wrong_argument_subparsers_no_suggestions(self): excinfo.exception.stderr, ) - def test_wrong_argument_no_suggestion_implicit(self): - parser = ErrorRaisingArgumentParser() + def test_wrong_argument_with_suggestion_explicit(self): + parser = ErrorRaisingArgumentParser(suggest_on_error=True) parser.add_argument('foo', choices=['bar', 'baz']) with self.assertRaises(ArgumentParserError) as excinfo: parser.parse_args(('bazz',)) self.assertIn( - "error: argument foo: invalid choice: 'bazz' (choose from 'bar', 'baz')", + "error: argument foo: invalid choice: 'bazz', maybe you meant" + " 'baz'? (choose from 'bar', 'baz')", excinfo.exception.stderr, ) def test_suggestions_choices_empty(self): - parser = ErrorRaisingArgumentParser(suggest_on_error=True) + parser = ErrorRaisingArgumentParser() parser.add_argument('foo', choices=[]) with self.assertRaises(ArgumentParserError) as excinfo: parser.parse_args(('bazz',)) @@ -2373,7 +2555,7 @@ def test_suggestions_choices_empty(self): ) def test_suggestions_choices_int(self): - parser = ErrorRaisingArgumentParser(suggest_on_error=True) + parser = ErrorRaisingArgumentParser() parser.add_argument('foo', choices=[1, 2]) with self.assertRaises(ArgumentParserError) as excinfo: parser.parse_args(('3',)) @@ -2383,7 +2565,7 @@ def test_suggestions_choices_int(self): ) def test_suggestions_choices_mixed_types(self): - parser = ErrorRaisingArgumentParser(suggest_on_error=True) + parser = ErrorRaisingArgumentParser() parser.add_argument('foo', choices=[1, '2']) with self.assertRaises(ArgumentParserError) as excinfo: parser.parse_args(('3',)) @@ -2710,6 +2892,16 @@ def test_optional_subparsers(self): ret = parser.parse_args(()) self.assertIsNone(ret.command) + def test_subparser_help_with_parent_required_optional(self): + parser = ErrorRaisingArgumentParser(prog='PROG') + parser.add_argument('--foo', required=True) + parser.add_argument('--bar') + subparsers = parser.add_subparsers() + parser_sub = subparsers.add_parser('sub') + parser_sub.add_argument('arg') + self.assertEqual(parser_sub.format_usage(), + 'usage: PROG --foo FOO sub [-h] arg\n') + def test_help(self): self.assertEqual(self.parser.format_usage(), 'usage: PROG [-h] [--foo] bar {1,2,3} ...\n') @@ -5626,6 +5818,11 @@ def custom_formatter(prog): a-very-long-command command that does something ''')) + def test_direct_formatter_instantiation(self): + formatter = argparse.HelpFormatter(prog="program") + formatter.add_usage(usage=None, actions=[], groups=[]) + help_text = formatter.format_help() + self.assertEqual(help_text, "usage: program\n") # ===================================== # Optional/Positional constructor tests @@ -5660,6 +5857,8 @@ def test_invalid_option_strings(self): self.assertTypeError('-', errmsg='dest= is required') self.assertTypeError('--', errmsg='dest= is required') self.assertTypeError('---', errmsg='dest= is required') + self.assertTypeError('-', '--', '---', + errmsg="dest= is required for options like '-', '--', '---'") def test_invalid_prefix(self): self.assertValueError('--foo', '+foo', @@ -6197,6 +6396,7 @@ def spam(string_to_convert): # Check that deprecated arguments output warning # ============================================== +@force_not_colorized_test_class class TestDeprecatedArguments(TestCase): def test_deprecated_option(self): @@ -6507,6 +6707,20 @@ def test_remainder(self): args = parser.parse_args(['--foo', 'a', '--', 'b', '--', 'c']) self.assertEqual(NS(foo='a', bar=['--', 'b', '--', 'c']), args) + def test_optional_remainder(self): + parser = argparse.ArgumentParser(exit_on_error=False) + parser.add_argument('--foo', nargs='...') + parser.add_argument('bar', nargs='*') + + args = parser.parse_args(['--', '--foo', 'a', 'b']) + self.assertEqual(NS(foo=None, bar=['--foo', 'a', 'b']), args) + args = parser.parse_args(['--foo', '--', 'a', 'b']) + self.assertEqual(NS(foo=['--', 'a', 'b'], bar=[]), args) + args = parser.parse_args(['--foo', 'a', '--', 'b']) + self.assertEqual(NS(foo=['a', '--', 'b'], bar=[]), args) + args = parser.parse_args(['--foo', 'a', 'b', '--']) + self.assertEqual(NS(foo=['a', 'b', '--'], bar=[]), args) + def test_subparser(self): parser = argparse.ArgumentParser(exit_on_error=False) parser.add_argument('foo') @@ -7084,9 +7298,8 @@ def make_script(self, dirname, basename, *, compiled=False): script_name = script_helper.make_script(dirname, basename, self.source) if not compiled: return script_name - py_compile.compile(script_name, doraise=True) + pyc_file = import_helper.make_legacy_pyc(script_name, allow_compile=True) os.remove(script_name) - pyc_file = import_helper.make_legacy_pyc(script_name) return pyc_file def make_zip_script(self, script_name, name_in_zip=None): @@ -7132,6 +7345,9 @@ def test_module_as_main_without_altering_argv(self): basename = 'module' + os_helper.FS_NONASCII modulename = f'{self.dirname}.{basename}' self.make_script(self.dirname, basename) + # The filesystem encoding may be non-UTF-8, + # but the runner runs in UTF-8 mode + modulename = os.fsencode(modulename).decode("utf-8", "surrogateescape") runner_source = textwrap.dedent(f'''\ import runpy runpy._run_module_as_main({modulename!r}, alter_argv=False) @@ -7243,6 +7459,13 @@ def test_argparse_color(self): choices=("Aaaaa", "Bbbbb", "Ccccc", "Ddddd"), help="pick one", ) + parser.add_argument( + "--optional8", + default="A", + metavar="X", + choices=("A", "B", "C"), + help="among %(choices)s, default is %(default)s", + ) parser.add_argument("+f") parser.add_argument("++bar") @@ -7268,6 +7491,8 @@ def test_argparse_color(self): short_b = self.theme.short_option label_b = self.theme.label pos_b = self.theme.action + default = self.theme.default + interp = self.theme.interpolated_value reset = self.theme.reset # Act @@ -7280,8 +7505,8 @@ def test_argparse_color(self): f"""\ {heading}usage: {reset}{prog}PROG{reset} [{short}-h{reset}] [{short}-v{reset} | {short}-q{reset}] [{short}-o{reset}] [{long}--optional2 {label}OPTIONAL2{reset}] [{long}--optional3 {label}{{X,Y,Z}}{reset}] [{long}--optional4 {label}{{X,Y,Z}}{reset}] [{long}--optional5 {label}{{X,Y,Z}}{reset}] [{long}--optional6 {label}{{X,Y,Z}}{reset}] - [{short}-p {label}{{Aaaaa,Bbbbb,Ccccc,Ddddd}}{reset}] [{short}+f {label}F{reset}] [{long}++bar {label}BAR{reset}] [{long}-+baz {label}BAZ{reset}] - [{short}-c {label}COUNT{reset}] + [{short}-p {label}{{Aaaaa,Bbbbb,Ccccc,Ddddd}}{reset}] [{long}--optional8 {label}X{reset}] [{short}+f {label}F{reset}] [{long}++bar {label}BAR{reset}] + [{long}-+baz {label}BAZ{reset}] [{short}-c {label}COUNT{reset}] {pos}x{reset} {pos}y{reset} {pos}this_indeed_is_a_very_long_action_name{reset} {pos}{{sub1,sub2}} ...{reset} Colorful help @@ -7294,17 +7519,18 @@ def test_argparse_color(self): {heading}options:{reset} {short_b}-h{reset}, {long_b}--help{reset} show this help message and exit - {short_b}-v{reset}, {long_b}--verbose{reset} more spam (default: False) - {short_b}-q{reset}, {long_b}--quiet{reset} less spam (default: False) + {short_b}-v{reset}, {long_b}--verbose{reset} more spam {default}(default: {reset}{interp}False{reset}{default}){reset} + {short_b}-q{reset}, {long_b}--quiet{reset} less spam {default}(default: {reset}{interp}False{reset}{default}){reset} {short_b}-o{reset}, {long_b}--optional1{reset} {long_b}--optional2{reset} {label_b}OPTIONAL2{reset} - pick one (default: None) + pick one {default}(default: {reset}{interp}None{reset}{default}){reset} {long_b}--optional3{reset} {label_b}{{X,Y,Z}}{reset} - {long_b}--optional4{reset} {label_b}{{X,Y,Z}}{reset} pick one (default: None) - {long_b}--optional5{reset} {label_b}{{X,Y,Z}}{reset} pick one (default: None) - {long_b}--optional6{reset} {label_b}{{X,Y,Z}}{reset} pick one (default: None) + {long_b}--optional4{reset} {label_b}{{X,Y,Z}}{reset} pick one {default}(default: {reset}{interp}None{reset}{default}){reset} + {long_b}--optional5{reset} {label_b}{{X,Y,Z}}{reset} pick one {default}(default: {reset}{interp}None{reset}{default}){reset} + {long_b}--optional6{reset} {label_b}{{X,Y,Z}}{reset} pick one {default}(default: {reset}{interp}None{reset}{default}){reset} {short_b}-p{reset}, {long_b}--optional7{reset} {label_b}{{Aaaaa,Bbbbb,Ccccc,Ddddd}}{reset} - pick one (default: None) + pick one {default}(default: {reset}{interp}None{reset}{default}){reset} + {long_b}--optional8{reset} {label_b}X{reset} among {interp}A, B, C{reset}, default is {interp}A{reset} {short_b}+f{reset} {label_b}F{reset} {long_b}++bar{reset} {label_b}BAR{reset} {long_b}-+baz{reset} {label_b}BAZ{reset} @@ -7370,6 +7596,62 @@ def test_argparse_color_custom_usage(self): ), ) + def test_argparse_color_wrapping_matches_uncolored(self): + # gh-142035: color codes must not affect where help text wraps. + # Stripping the escapes from colored help must yield exactly the + # same text as the uncolored help across representative widths. + def build(color, path="output.txt"): + parser = argparse.ArgumentParser(prog="PROG", color=color) + parser.add_argument( + "--mode", + default="auto", + choices=("auto", "fast", "slow"), + help="select the operating mode from the available choices " + "%(choices)s and note the default is %(default)s here", + ) + parser.add_argument( + "--path", + default=path, + help="write output to %(default)s and continue processing", + ) + return parser + + env = self.enterContext(os_helper.EnvironmentVarGuard()) + paths = ( + "output.txt", + "/var/lib/application/cache/unusually_long_generated_filename", + "production-read-only-replica", + ) + for path in paths: + for columns in ("80", "60", "45", "30", "20"): + with self.subTest(path=path, columns=columns): + env["COLUMNS"] = columns + colored = build(color=True, path=path).format_help() + plain = build(color=False, path=path).format_help() + self.assertIn( + f"{self.theme.interpolated_value}auto" + f"{self.theme.reset}", + colored, + ) + self.assertEqual(_colorize.decolor(colored), plain) + + def test_argparse_color_preserved_when_wrapping_between_words(self): + parser = argparse.ArgumentParser(prog="PROG", color=True) + parser.add_argument( + "--mode", default="auto", + help="select the %(default)s operating mode from the available " + "options and continue with several more words", + ) + + env = self.enterContext(os_helper.EnvironmentVarGuard()) + env["COLUMNS"] = "40" + help_text = parser.format_help() + + self.assertIn( + f"{self.theme.interpolated_value}auto{self.theme.reset}", + help_text, + ) + def test_custom_formatter_function(self): def custom_formatter(prog): return argparse.RawTextHelpFormatter(prog, indent_increment=5) @@ -7454,6 +7736,311 @@ def test_subparser_prog_is_stored_without_color(self): help_text = demo_parser.format_help() self.assertNotIn('\x1b[', help_text) + def test_error_and_warning_keywords_colorized(self): + parser = argparse.ArgumentParser(prog='PROG') + parser.add_argument('foo') + + with self.assertRaises(SystemExit): + with captured_stderr() as stderr: + parser.parse_args([]) + + err = stderr.getvalue() + error_color = self.theme.error + reset = self.theme.reset + self.assertIn(f'{error_color}error:{reset}', err) + + with captured_stderr() as stderr: + parser._warning('test warning') + + warn = stderr.getvalue() + warning_color = self.theme.warning + self.assertIn(f'{warning_color}warning:{reset}', warn) + + def test_error_and_warning_not_colorized_when_disabled(self): + parser = argparse.ArgumentParser(prog='PROG', color=False) + parser.add_argument('foo') + + with self.assertRaises(SystemExit): + with captured_stderr() as stderr: + parser.parse_args([]) + + err = stderr.getvalue() + self.assertNotIn('\x1b[', err) + self.assertIn('error:', err) + + with captured_stderr() as stderr: + parser._warning('test warning') + + warn = stderr.getvalue() + self.assertNotIn('\x1b[', warn) + self.assertIn('warning:', warn) + + def test_backtick_markup_in_epilog(self): + parser = argparse.ArgumentParser( + prog='PROG', + color=True, + epilog='Example: `python -m myapp --verbose`', + ) + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f'Example: {prog_extra}python -m myapp --verbose{reset}', + help_text) + self.assertNotIn('`', help_text) + + def test_backtick_markup_in_description(self): + parser = argparse.ArgumentParser( + prog='PROG', + color=True, + description='Run `python myapp` or ``python -m myapp`` to start.', + ) + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn( + f'Run {prog_extra}python myapp{reset} or ' + f'{prog_extra}python -m myapp{reset} to start.', + help_text, + ) + self.assertNotIn("`", help_text) + + def test_backtick_markup_multiple(self): + parser = argparse.ArgumentParser( + prog='PROG', + color=True, + epilog='Try `app run` or ``app test``.', + ) + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f'{prog_extra}app run{reset}', help_text) + self.assertIn(f'{prog_extra}app test{reset}', help_text) + self.assertNotIn('`', help_text) + + def test_backtick_markup_not_applied_when_color_disabled(self): + # When color is disabled, backticks are preserved as-is + parser = argparse.ArgumentParser( + prog='PROG', + color=False, + epilog='Examples: `python -m myapp` or ``python -m myapp --x``', + ) + + help_text = parser.format_help() + self.assertIn('`python -m myapp`', help_text) + self.assertIn('``python -m myapp --x``', help_text) + self.assertNotIn('\x1b[', help_text) + + def test_backtick_markup_with_format_string(self): + parser = argparse.ArgumentParser( + prog='myapp', + color=True, + epilog='Run `%(prog)s --help` for more info.', + ) + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f'{prog_extra}myapp --help{reset}', help_text) + + def test_backtick_markup_in_subparser(self): + parser = argparse.ArgumentParser(prog='PROG', color=True) + subparsers = parser.add_subparsers() + sub = subparsers.add_parser( + 'sub', + description='Run `PROG sub --foo` to start.', + ) + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = sub.format_help() + self.assertIn(f'{prog_extra}PROG sub --foo{reset}', help_text) + + def test_backtick_markup_special_regex_chars(self): + parser = argparse.ArgumentParser( + prog='PROG', + color=True, + epilog='`grep "foo.*bar" | sort`', + ) + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f'{prog_extra}grep "foo.*bar" | sort{reset}', help_text) + + def test_backtick_markup_in_argument_help(self): + parser = argparse.ArgumentParser(prog="PROG", color=True) + parser.add_argument("--foo", help="set the `foo` value") + parser.add_argument("--bar", help="set the ``bar`` value") + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f"set the {prog_extra}foo{reset} value", help_text) + self.assertIn(f"set the {prog_extra}bar{reset} value", help_text) + self.assertNotIn("`", help_text) + + def test_backtick_markup_in_argument_help_with_format(self): + parser = argparse.ArgumentParser(prog="PROG", color=True) + parser.add_argument( + "--foo", default="bar", help="set `foo` (default: %(default)s)" + ) + + prog_extra = self.theme.prog_extra + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f"set {prog_extra}foo{reset}", help_text) + + def test_backtick_markup_in_argument_help_color_disabled(self): + parser = argparse.ArgumentParser(prog="PROG", color=False) + parser.add_argument("--foo", help="set the `foo` value") + + help_text = parser.format_help() + self.assertIn("set the `foo` value", help_text) + self.assertNotIn("\x1b[", help_text) + + def test_argument_help_interpolation_accepts_string_like_proxy(self): + class LazyStr: + def __init__(self, message): + self._message = message + + def __str__(self): + return self._message + + def __getattr__(self, name): + return getattr(str(self), name) + + def __contains__(self, item): + return item in self._message + + def __mod__(self, other): + return self._message % other + + parser = argparse.ArgumentParser(prog="PROG", color=True) + parser.add_argument( + "--foo", + default="bar", + help=LazyStr("foo (default: %(default)s)"), + ) + parser.add_argument( + "--baz", + help=LazyStr("baz plain text"), + ) + + interp = self.theme.interpolated_value + reset = self.theme.reset + + help_text = parser.format_help() + self.assertIn(f"foo (default: {interp}bar{reset})", help_text) + self.assertIn("baz plain text", help_text) + + def test_help_with_format_specifiers(self): + # GH-142950: format specifiers like %x should work with color=True + parser = argparse.ArgumentParser(prog='PROG', color=True) + parser.add_argument('--hex', type=int, default=255, + help='hex: %(default)x, alt: %(default)#x') + parser.add_argument('--zero', type=int, default=7, + help='zero: %(default)05d') + parser.add_argument('--str', default='test', + help='str: %(default)s') + parser.add_argument('--pct', type=int, default=50, + help='pct: %(default)d%%') + parser.add_argument('--literal', help='literal: 100%%') + parser.add_argument('--prog', help='prog: %(prog)s') + parser.add_argument('--type', type=int, help='type: %(type)s') + parser.add_argument('--choices', choices=['a', 'b'], + help='choices: %(choices)s') + + help_text = parser.format_help() + + interp = self.theme.interpolated_value + reset = self.theme.reset + + self.assertIn(f'hex: {interp}ff{reset}', help_text) + self.assertIn(f'alt: {interp}0xff{reset}', help_text) + self.assertIn(f'zero: {interp}00007{reset}', help_text) + self.assertIn(f'str: {interp}test{reset}', help_text) + self.assertIn(f'pct: {interp}50{reset}%', help_text) + self.assertIn('literal: 100%', help_text) + self.assertIn(f'prog: {interp}PROG{reset}', help_text) + self.assertIn(f'type: {interp}int{reset}', help_text) + self.assertIn(f'choices: {interp}a, b{reset}', help_text) + + def test_print_help_uses_target_file_for_color_decision(self): + parser = argparse.ArgumentParser(prog='PROG', color=True) + parser.add_argument('--opt') + output = io.StringIO() + calls = [] + + def fake_can_colorize(*, file=None): + calls.append(file) + return file is None + + with swap_attr(_colorize, 'can_colorize', fake_can_colorize): + parser.print_help(file=output) + + self.assertIs(calls[-1], output) + self.assertIn(output, calls) + self.assertNotIn('\x1b[', output.getvalue()) + + def test_print_usage_uses_target_file_for_color_decision(self): + parser = argparse.ArgumentParser(prog='PROG', color=True) + parser.add_argument('--opt') + output = io.StringIO() + calls = [] + + def fake_can_colorize(*, file=None): + calls.append(file) + return file is None + + with swap_attr(_colorize, 'can_colorize', fake_can_colorize): + parser.print_usage(file=output) + + self.assertIs(calls[-1], output) + self.assertIn(output, calls) + self.assertNotIn('\x1b[', output.getvalue()) + + def test_fake_color_theme_matches_real(self): + from argparse import _colorless_theme + + # Check the attributes match those of the 'real' theme + _colorize_nocolor = _colorize.get_theme(force_no_color=True).argparse + for k in _colorize_nocolor: + self.assertEqual( + getattr(_colorless_theme, k), getattr(_colorize_nocolor, k) + ) + + def test_fake_color_theme_raises(self): + from argparse import _colorless_theme + + # Make sure the _colorless_theme doesn't return empty strings + # for magic methods or private attributes + with self.assertRaises(AttributeError): + _colorless_theme.__unknown_dunder__ + + with self.assertRaises(AttributeError): + _colorless_theme._private_attribute + + +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(argparse, "__version__") + self.assertEqual(cm.filename, __file__) + def tearDownModule(): # Remove global references to avoid looking like we have refleaks. diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py index 8cf669935f9..8457e1bb72f 100644 --- a/Lib/test/test_array.py +++ b/Lib/test/test_array.py @@ -12,6 +12,7 @@ import weakref import pickle import operator +import re import struct import sys import warnings @@ -31,7 +32,10 @@ class ArraySubclassWithKwargs(array.array): def __init__(self, typecode, newarg=None): array.array.__init__(self) -typecodes = 'uwbBhHiIlLfdqQ' +typecodes = ( + 'u', 'w', 'b', 'B', 'h', 'H', 'i', 'I', 'l', 'L', + 'f', 'd', 'q', 'Q', 'e', 'Zf', 'Zd') + class MiscTest(unittest.TestCase): @@ -47,8 +51,9 @@ def test_array_is_sequence(self): def test_bad_constructor(self): self.assertRaises(TypeError, array.array) self.assertRaises(TypeError, array.array, spam=42) - self.assertRaises(TypeError, array.array, 'xx') + self.assertRaises(ValueError, array.array, 'xx') self.assertRaises(ValueError, array.array, 'x') + self.assertRaises(ValueError, array.array, 'Z') @support.cpython_only def test_does_not_crash_on_broken_imports(self): @@ -90,6 +95,50 @@ def test_empty(self): a += a self.assertEqual(len(a), 0) + def test_fromlist_reentrant_index_mutation(self): + + class Evil: + def __init__(self, lst): + self.lst = lst + def __index__(self): + self.lst.clear() + return "not an int" + + for typecode in ('I', 'L', 'Q'): + with self.subTest(typecode=typecode): + lst = [] + lst.append(Evil(lst)) + a = array.array(typecode) + with self.assertRaises(TypeError): + a.fromlist(lst) + + def test_typecodes(self): + self.assertIsInstance(array.typecodes, tuple) + for typecode in array.typecodes: + self.assertIsInstance(typecode, str) + self.assertGreaterEqual(len(typecode), 1) + + @support.cpython_only + @support.requires_docstrings + def test_typecodes_documented(self): + # The type code table in the array.array docstring must list every + # supported type code, and nothing else, and the minimum size it + # gives for each of them must be one the implementation meets. + row = re.compile(r"^ {4}'(\w+)' +\S.*? +(\d+)(?: \(see note\))?$") + documented = {} + for line in array.array.__doc__.splitlines(): + match = row.match(line) + if match is not None: + documented[match.group(1)] = int(match.group(2)) + + self.assertEqual(sorted(documented), sorted(array.typecodes)) + for typecode, minimum_size in documented.items(): + with self.subTest(typecode=typecode): + with warnings.catch_warnings(): + warnings.simplefilter('ignore', DeprecationWarning) + self.assertGreaterEqual(array.array(typecode).itemsize, + minimum_size) + # Machine format codes. # @@ -118,6 +167,14 @@ def test_empty(self): UTF16_BE = 19 UTF32_LE = 20 UTF32_BE = 21 +IEEE_754_FLOAT_COMPLEX_LE = 22 +IEEE_754_FLOAT_COMPLEX_BE = 23 +IEEE_754_DOUBLE_COMPLEX_LE = 24 +IEEE_754_DOUBLE_COMPLEX_BE = 25 +IEEE_754_FLOAT16_LE = 26 +IEEE_754_FLOAT16_BE = 27 + +MACHINE_FORMAT_CODE_MAX = 27 class ArrayReconstructorTest(unittest.TestCase): @@ -144,7 +201,7 @@ def test_error(self): self.assertRaises(ValueError, array_reconstructor, array.array, "b", UNKNOWN_FORMAT, b"") self.assertRaises(ValueError, array_reconstructor, - array.array, "b", 22, b"") + array.array, "b", MACHINE_FORMAT_CODE_MAX + 1, b"") self.assertRaises(ValueError, array_reconstructor, array.array, "d", 16, b"a") @@ -189,6 +246,10 @@ def test_numbers(self): [-1<<63, (1<<63)-1, 0]), (['l'], SIGNED_INT64_BE, '>qqq', [-1<<63, (1<<63)-1, 0]), + (['e'], IEEE_754_FLOAT16_LE, 'eeee', + [1.0, float('inf'), float('-inf'), -0.0]), (['f'], IEEE_754_FLOAT_LE, 'ffff', @@ -196,7 +257,15 @@ def test_numbers(self): (['d'], IEEE_754_DOUBLE_LE, 'dddd', - [9006104071832581.0, float('inf'), float('-inf'), -0.0]) + [9006104071832581.0, float('inf'), float('-inf'), -0.0]), + (['Zf'], IEEE_754_FLOAT_COMPLEX_LE, 'ZfZfZfZf', + [16711938.0j, float('inf'), complex('1-infj'), -0.0]), + (['Zd'], IEEE_754_DOUBLE_COMPLEX_LE, 'ZdZdZdZd', + [9006104071832581.0j, float('inf'), complex('1-infj'), -0.0]), ) for testcase in testcases: valid_typecodes, mformat_code, struct_fmt, values = testcase @@ -211,6 +280,16 @@ def test_numbers(self): self.assertEqual(a, b, msg="{0!r} != {1!r}; testcase={2!r}".format(a, b, testcase)) + def test_float16_endianness(self): + # gh-154568: array_reconstructor() slow-path decoder for + # IEEE_754_FLOAT16_LE ignored the encoding. + le_bytes = struct.pack('e', 1.5) + b_le = array_reconstructor(array.array, 'd', IEEE_754_FLOAT16_LE, le_bytes) + b_be = array_reconstructor(array.array, 'd', IEEE_754_FLOAT16_BE, be_bytes) + self.assertEqual(b_le.tolist(), [1.5]) + self.assertEqual(b_be.tolist(), [1.5]) + def test_unicode(self): teststr = "Bonne Journ\xe9e \U0002030a\U00020347" testcases = ( @@ -284,7 +363,7 @@ def test_byteswap(self): example = self.example a = array.array(self.typecode, example) self.assertRaises(TypeError, a.byteswap, 42) - if a.itemsize in (1, 2, 4, 8): + if a.itemsize in (1, 2, 4, 8, 16): b = array.array(self.typecode, example) b.byteswap() if a.itemsize==1: @@ -1226,6 +1305,9 @@ def test_free_after_iterating(self): support.check_free_after_iterating(self, reversed, array.array, (self.typecode,)) + def test_known_typecode(self): + self.assertIn(self.typecode, array.typecodes) + class StringTest(BaseTest): def test_setitem(self): @@ -1530,6 +1612,78 @@ def test_byteswap(self): b.byteswap() self.assertEqual(a, b) +class CFPTest(NumberTest): + example = [-42j, 0, 42+1j, 1e5j, -1e10] + outside = 23 + + def assertEntryEqual(self, entry1, entry2): + self.assertAlmostEqual(entry1, entry2) + + def test_cmp(self): + a = array.array(self.typecode, self.example) + self.assertIs(a == 42, False) + self.assertIs(a != 42, True) + + self.assertIs(a == a, True) + self.assertIs(a != a, False) + self.assertIs(a < a, False) + self.assertIs(a <= a, True) + self.assertIs(a > a, False) + self.assertIs(a >= a, True) + + self.assertIs(a == 2*a, False) + self.assertIs(a != 2*a, True) + self.assertIs(a < 2*a, True) + self.assertIs(a <= 2*a, True) + self.assertIs(a > 2*a, False) + self.assertIs(a >= 2*a, False) + + def test_nan(self): + a = array.array(self.typecode, [float('nan')]) + b = array.array(self.typecode, [float('nan')]) + self.assertIs(a != b, True) + self.assertIs(a == b, False) + + def test_byteswap(self): + a = array.array(self.typecode, self.example) + self.assertRaises(TypeError, a.byteswap, 42) + if a.itemsize in (1, 2, 4, 8, 16): + b = array.array(self.typecode, self.example) + b.byteswap() + if a.itemsize == 1: + self.assertEqual(a, b) + else: + # On alphas treating the byte swapped bit patterns as + # floats/doubles results in floating-point exceptions + # => compare the 8bit string values instead + self.assertNotEqual(a.tobytes(), b.tobytes()) + b.byteswap() + self.assertEqual(a, b) + + def test_byteswap_single_call_result(self): + # A single byteswap() must swap each item's two halves (real, + # imag) independently. test_byteswap above only checks that + # byteswap() twice round-trips to the original, which passes + # even if a single call scrambles multi-item arrays. + a = array.array(self.typecode, self.example) + original = a.tobytes() + a.byteswap() + itemsize = a.itemsize + half = itemsize // 2 + expected = bytearray() + for i in range(0, len(original), itemsize): + item = original[i:i + itemsize] + expected += item[half - 1::-1] + item[itemsize - 1:half - 1:-1] + self.assertEqual(a.tobytes(), bytes(expected)) + + +class HalfFloatTest(FPTest, unittest.TestCase): + example = [-42.0, 0, 42, 1e2, -1e4] + smallerexample = [-42.0, 0, 42, 1e2, -2e4] + biggerexample = [-42.0, 0, 42, 1e2, 1e4] + typecode = 'e' + minitemsize = 2 + class FloatTest(FPTest, unittest.TestCase): typecode = 'f' minitemsize = 4 @@ -1556,6 +1710,15 @@ def test_alloc_overflow(self): self.fail("Array of size > maxsize created - MemoryError expected") +class ComplexFloatTest(CFPTest, unittest.TestCase): + typecode = 'Zf' + minitemsize = 8 + +class ComplexDoubleTest(CFPTest, unittest.TestCase): + typecode = 'Zd' + minitemsize = 16 + + class LargeArrayTest(unittest.TestCase): typecode = 'b' diff --git a/Lib/test/test_ast/data/ast_repr.txt b/Lib/test/test_ast/data/ast_repr.txt index 1c1985519cd..cc6accd766b 100644 --- a/Lib/test/test_ast/data/ast_repr.txt +++ b/Lib/test/test_ast/data/ast_repr.txt @@ -69,10 +69,14 @@ Module(body=[Try(body=[Pass()], handlers=[ExceptHandler(type=Name(...), name='ex Module(body=[TryStar(body=[Pass()], handlers=[ExceptHandler(type=Name(...), name='exc', body=[Pass(...)])], orelse=[Pass()], finalbody=[Pass()])], type_ignores=[]) Module(body=[Assert(test=Name(id='v', ctx=Load(...)), msg=None)], type_ignores=[]) Module(body=[Assert(test=Name(id='v', ctx=Load(...)), msg=Constant(value='message', kind=None))], type_ignores=[]) -Module(body=[Import(names=[alias(name='sys', asname=None)])], type_ignores=[]) -Module(body=[Import(names=[alias(name='foo', asname='bar')])], type_ignores=[]) -Module(body=[ImportFrom(module='sys', names=[alias(name='x', asname='y')], level=0)], type_ignores=[]) -Module(body=[ImportFrom(module='sys', names=[alias(name='v', asname=None)], level=0)], type_ignores=[]) +Module(body=[Import(names=[alias(name='sys', asname=None)], is_lazy=0)], type_ignores=[]) +Module(body=[Import(names=[alias(name='foo', asname='bar')], is_lazy=0)], type_ignores=[]) +Module(body=[ImportFrom(module='sys', names=[alias(name='x', asname='y')], level=0, is_lazy=0)], type_ignores=[]) +Module(body=[ImportFrom(module='sys', names=[alias(name='v', asname=None)], level=0, is_lazy=0)], type_ignores=[]) +Module(body=[Import(names=[alias(name='sys', asname=None)], is_lazy=1)], type_ignores=[]) +Module(body=[Import(names=[alias(name='foo', asname='bar')], is_lazy=1)], type_ignores=[]) +Module(body=[ImportFrom(module='sys', names=[alias(name='x', asname='y')], level=0, is_lazy=1)], type_ignores=[]) +Module(body=[ImportFrom(module='sys', names=[alias(name='v', asname=None)], level=0, is_lazy=1)], type_ignores=[]) Module(body=[Global(names=['v'])], type_ignores=[]) Module(body=[Expr(value=Constant(value=1, kind=None))], type_ignores=[]) Module(body=[Pass()], type_ignores=[]) diff --git a/Lib/test/test_ast/snippets.py b/Lib/test/test_ast/snippets.py index b76f98901d2..a565ed10f8b 100644 --- a/Lib/test/test_ast/snippets.py +++ b/Lib/test/test_ast/snippets.py @@ -118,6 +118,12 @@ # ImportFrom "from sys import x as y", "from sys import v", + # Lazy Import + "lazy import sys", + "lazy import foo as bar", + # Lazy ImportFrom + "lazy from sys import x as y", + "lazy from sys import v", # Global "global v", # Expr @@ -460,10 +466,14 @@ def main(): ('Module', [('TryStar', (1, 0, 7, 6), [('Pass', (2, 2, 2, 6))], [('ExceptHandler', (3, 0, 4, 6), ('Name', (3, 8, 3, 17), 'Exception', ('Load',)), 'exc', [('Pass', (4, 2, 4, 6))])], [('Pass', (5, 7, 5, 11))], [('Pass', (7, 2, 7, 6))])], []), ('Module', [('Assert', (1, 0, 1, 8), ('Name', (1, 7, 1, 8), 'v', ('Load',)), None)], []), ('Module', [('Assert', (1, 0, 1, 19), ('Name', (1, 7, 1, 8), 'v', ('Load',)), ('Constant', (1, 10, 1, 19), 'message', None))], []), -('Module', [('Import', (1, 0, 1, 10), [('alias', (1, 7, 1, 10), 'sys', None)])], []), -('Module', [('Import', (1, 0, 1, 17), [('alias', (1, 7, 1, 17), 'foo', 'bar')])], []), -('Module', [('ImportFrom', (1, 0, 1, 22), 'sys', [('alias', (1, 16, 1, 22), 'x', 'y')], 0)], []), -('Module', [('ImportFrom', (1, 0, 1, 17), 'sys', [('alias', (1, 16, 1, 17), 'v', None)], 0)], []), +('Module', [('Import', (1, 0, 1, 10), [('alias', (1, 7, 1, 10), 'sys', None)], 0)], []), +('Module', [('Import', (1, 0, 1, 17), [('alias', (1, 7, 1, 17), 'foo', 'bar')], 0)], []), +('Module', [('ImportFrom', (1, 0, 1, 22), 'sys', [('alias', (1, 16, 1, 22), 'x', 'y')], 0, 0)], []), +('Module', [('ImportFrom', (1, 0, 1, 17), 'sys', [('alias', (1, 16, 1, 17), 'v', None)], 0, 0)], []), +('Module', [('Import', (1, 0, 1, 15), [('alias', (1, 12, 1, 15), 'sys', None)], 1)], []), +('Module', [('Import', (1, 0, 1, 22), [('alias', (1, 12, 1, 22), 'foo', 'bar')], 1)], []), +('Module', [('ImportFrom', (1, 0, 1, 27), 'sys', [('alias', (1, 21, 1, 27), 'x', 'y')], 0, 1)], []), +('Module', [('ImportFrom', (1, 0, 1, 22), 'sys', [('alias', (1, 21, 1, 22), 'v', None)], 0, 1)], []), ('Module', [('Global', (1, 0, 1, 8), ['v'])], []), ('Module', [('Expr', (1, 0, 1, 1), ('Constant', (1, 0, 1, 1), 1, None))], []), ('Module', [('Pass', (1, 0, 1, 4))], []), diff --git a/Lib/test/test_ast/test_ast.py b/Lib/test/test_ast/test_ast.py index aeaa4872e28..9e80b594c68 100644 --- a/Lib/test/test_ast/test_ast.py +++ b/Lib/test/test_ast/test_ast.py @@ -1,4 +1,5 @@ import _ast_unparse +import _ast import ast import builtins import contextlib @@ -13,6 +14,7 @@ import textwrap import types import unittest +import warnings import weakref from io import StringIO from pathlib import Path @@ -86,7 +88,9 @@ def _assertTrueorder(self, ast_node, parent_pos): self.assertEqual(ast_node._fields, ast_node.__match_args__) def test_AST_objects(self): - x = ast.AST() + # Directly instantiating abstract node class AST is allowed (but deprecated) + with self.assertWarns(DeprecationWarning): + x = ast.AST() self.assertEqual(x._fields, ()) x.foobar = 42 self.assertEqual(x.foobar, 42) @@ -95,7 +99,7 @@ def test_AST_objects(self): with self.assertRaises(AttributeError): x.vararg - with self.assertRaises(TypeError): + with self.assertRaises(TypeError), self.assertWarns(DeprecationWarning): # "ast.AST constructor takes 0 positional arguments" ast.AST(2) @@ -111,15 +115,21 @@ def cleanup(): msg = "type object 'ast.AST' has no attribute '_fields'" # Both examples used to crash: - with self.assertRaisesRegex(AttributeError, msg): + with ( + self.assertRaisesRegex(AttributeError, msg), + self.assertWarns(DeprecationWarning), + ): ast.AST(arg1=123) - with self.assertRaisesRegex(AttributeError, msg): + with ( + self.assertRaisesRegex(AttributeError, msg), + self.assertWarns(DeprecationWarning), + ): ast.AST() - def test_AST_garbage_collection(self): + def test_node_garbage_collection(self): class X: pass - a = ast.AST() + a = ast.Module() a.x = X() a.x.a = a ref = weakref.ref(a.x) @@ -133,7 +143,7 @@ def test_snippets(self): (eval_tests, eval_results, "eval")): for i, o in zip(input, output): with self.subTest(action="parsing", input=i): - ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST) + ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST, optimize=False) self.assertEqual(to_tuple(ast_tree), o) self._assertTrueorder(ast_tree, (0, 0)) with self.subTest(action="compiling", input=i, kind=kind): @@ -143,7 +153,7 @@ def test_ast_validation(self): # compile() is the only function that calls PyAST_Validate snippets_to_validate = exec_tests + single_tests + eval_tests for snippet in snippets_to_validate: - tree = ast.parse(snippet) + tree = ast.parse(snippet, optimize=False) compile(tree, '', 'exec') def test_parse_invalid_ast(self): @@ -152,6 +162,15 @@ def test_parse_invalid_ast(self): self.assertRaises(TypeError, ast.parse, ast.Constant(42), optimize=optval) + def test_parse_ast_func_type(self): + # see gh-156689 + tree = ast.parse('(int, str) -> bool', mode='func_type') + self.assertEqual(ast.dump(ast.parse(tree, mode='func_type')), + ast.dump(tree)) + self.assertRaises(TypeError, ast.parse, ast.Constant(42), + mode='func_type') + self.assertRaises(TypeError, ast.parse, tree, mode='exec') + def test_optimization_levels__debug__(self): cases = [(-1, '__debug__'), (0, '__debug__'), (1, False), (2, False)] for (optval, expected) in cases: @@ -419,6 +438,17 @@ def test_field_attr_existence(self): if isinstance(x, ast.AST): self.assertIs(type(x._fields), tuple) + def test_dynamic_attr(self): + for name, item in ast.__dict__.items(): + # constructor has a different signature + if name == 'Index': + continue + if self._is_ast_node(name, item): + x = self._construct_ast_class(item) + # Custom attribute assignment is allowed + x.foo = 5 + self.assertEqual(x.foo, 5) + def _construct_ast_class(self, cls): kwargs = {} for name, typ in cls.__annotations__.items(): @@ -429,7 +459,15 @@ def _construct_ast_class(self, cls): elif typ is object: kwargs[name] = b'capybara' elif isinstance(typ, type) and issubclass(typ, ast.AST): - kwargs[name] = self._construct_ast_class(typ) + if _ast._is_abstract(typ): + # Use an arbitrary concrete subclass + concrete = next((sub for sub in typ.__subclasses__() + if not _ast._is_abstract(sub)), None) + msg = f"abstract node class {typ} has no concrete subclasses" + self.assertIsNotNone(concrete, msg) + else: + concrete = typ + kwargs[name] = self._construct_ast_class(concrete) return cls(**kwargs) def test_arguments(self): @@ -460,14 +498,9 @@ def test_field_attr_writable(self): self.assertEqual(x._fields, 666) def test_classattrs(self): - with self.assertWarns(DeprecationWarning): - x = ast.Constant() + x = ast.Constant(42) self.assertEqual(x._fields, ('value', 'kind')) - with self.assertRaises(AttributeError): - x.value - - x = ast.Constant(42) self.assertEqual(x.value, 42) with self.assertRaises(AttributeError): @@ -487,11 +520,8 @@ def test_classattrs(self): self.assertRaises(TypeError, ast.Constant, 1, None, 2) self.assertRaises(TypeError, ast.Constant, 1, None, 2, lineno=0) - # Arbitrary keyword arguments are supported (but deprecated) - with self.assertWarns(DeprecationWarning): - self.assertEqual(ast.Constant(1, foo='bar').foo, 'bar') - - with self.assertRaisesRegex(TypeError, "Constant got multiple values for argument 'value'"): + msg = "ast.Constant got multiple values for argument 'value'" + with self.assertRaisesRegex(TypeError, re.escape(msg)): ast.Constant(1, value=2) self.assertEqual(ast.Constant(42).value, 42) @@ -530,23 +560,24 @@ def test_module(self): self.assertEqual(x.body, body) def test_nodeclasses(self): - # Zero arguments constructor explicitly allowed (but deprecated) - with self.assertWarns(DeprecationWarning): - x = ast.BinOp() - self.assertEqual(x._fields, ('left', 'op', 'right')) - - # Random attribute allowed too - x.foobarbaz = 5 - self.assertEqual(x.foobarbaz, 5) + # Zero arguments constructor is not allowed + msg = "ast.BinOp.__init__ missing 3 required positional arguments: 'left', 'op', and 'right'" + self.assertRaisesRegex(TypeError, re.escape(msg), ast.BinOp) n1 = ast.Constant(1) n3 = ast.Constant(3) addop = ast.Add() x = ast.BinOp(n1, addop, n3) + self.assertEqual(x._fields, ('left', 'op', 'right')) self.assertEqual(x.left, n1) self.assertEqual(x.op, addop) self.assertEqual(x.right, n3) + # Arbitrary attributes are allowed + x.foobarbaz = 5 + self.assertEqual(x.foobarbaz, 5) + self.assertEqual(x._fields, ('left', 'op', 'right')) + x = ast.BinOp(1, 2, 3) self.assertEqual(x.left, 1) self.assertEqual(x.op, 2) @@ -570,10 +601,14 @@ def test_nodeclasses(self): self.assertEqual(x.right, 3) self.assertEqual(x.lineno, 0) - # Random kwargs also allowed (but deprecated) - with self.assertWarns(DeprecationWarning): - x = ast.BinOp(1, 2, 3, foobarbaz=42) - self.assertEqual(x.foobarbaz, 42) + # Arbitrary keyword arguments are not allowed + msg = "ast.BinOp.__init__ got an unexpected keyword argument 'foobarbaz'" + with self.assertRaisesRegex(TypeError, re.escape(msg)): + ast.BinOp(1, 2, 3, foobarbaz=42) + + # Directly instantiating abstract node types is allowed (but deprecated) + self.assertWarns(DeprecationWarning, ast.stmt) + self.assertWarns(DeprecationWarning, ast.expr_context) def test_no_fields(self): # this used to fail because Sub._fields was None @@ -582,7 +617,10 @@ def test_no_fields(self): def test_invalid_sum(self): pos = dict(lineno=2, col_offset=3) - m = ast.Module([ast.Expr(ast.expr(**pos), **pos)], []) + with self.assertWarns(DeprecationWarning): + # Creating instances of ast.expr is deprecated + e = ast.expr(**pos) + m = ast.Module([ast.Expr(e, **pos)], []) with self.assertRaises(TypeError) as cm: compile(m, "", "exec") self.assertIn("but got expr()", str(cm.exception)) @@ -923,7 +961,6 @@ def test_type_params_feature_version(self): with self.assertRaises(SyntaxError): ast.parse(sample, feature_version=(3, 11)) - @unittest.expectedFailure # TODO: RUSTPYTHON; SyntaxError not raised def test_type_params_default_feature_version(self): samples = [ "type X[*Ts=int] = int", @@ -949,7 +986,34 @@ def test_constant_as_name(self): with self.assertRaisesRegex(ValueError, f"identifier field can't represent '{constant}' constant"): compile(expr, "", "eval") - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError not raised + def test_constant_in_identifier_fields(self): + # gh-85260: an identifier field holding a constant name used to + # crash the compiler + for statement in [ + "def x(): pass", + "async def x(): pass", + "class x: pass", + "from a import x", + "from a import b as x", + "from a import b, c, d as x", + "import x", + "import a, b, x", + "try: pass\nexcept A as x: pass", + "try: pass\nexcept A as b: pass\nexcept B as x: pass\n", + ]: + for constant in "True", "False", "None": + with self.subTest(statement=statement, constant=constant): + tree = ast.parse(statement) + for node in ast.walk(tree): + for field, value in ast.iter_fields(node): + if value == "x": + setattr(node, field, constant) + with self.assertRaisesRegex( + ValueError, + f"identifier field can't represent " + f"'{constant}' constant"): + compile(tree, "", "exec") + def test_constant_as_unicode_name(self): constants = [ ("True", b"Tru\xe1\xb5\x89"), @@ -992,8 +1056,7 @@ def next(self): enum._test_simple_enum(_Precedence, _ast_unparse._Precedence) @support.cpython_only - @support.run_with_limited_c_stack( - 100_000 if sys.platform == "android" else 500_000) + @support.skip_if_huge_c_stack(100_000 if sys.platform == "android" else 500_000) @skip_wasi_stack_overflow() @skip_emscripten_stack_overflow() def test_ast_recursion_limit(self): @@ -1055,7 +1118,7 @@ def test_repr(self) -> None: snapshots = AST_REPR_DATA_FILE.read_text().split("\n") for test, snapshot in zip(ast_repr_get_test_cases(), snapshots, strict=True): with self.subTest(test_input=test): - self.assertEqual(repr(ast.parse(test)), snapshot) + self.assertEqual(repr(ast.parse(test, optimize=False)), snapshot) def test_repr_large_input_crash(self): # gh-125010: Fix use-after-free in ast repr() @@ -1076,13 +1139,28 @@ def test_tstring(self): self.assertIsInstance(tree.body[0].value.values[0], ast.Constant) self.assertIsInstance(tree.body[0].value.values[1], ast.Interpolation) - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_optimization_levels_const_folding(self): - return super().test_optimization_levels_const_folding() - - @unittest.expectedFailure # TODO: RUSTPYTHON; will be removed in Python 3.14 - def test_constant_subclasses_deprecated(self): - return super().test_constant_subclasses_deprecated() + def test_filter_syntax_warnings_by_module(self): + filename = support.findfile('test_import/data/syntax_warnings.py') + with open(filename, 'rb') as f: + source = f.read() + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'\z') + ast.parse(source) + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10]) + for wm in wlog: + self.assertEqual(wm.filename, '') + self.assertIs(wm.category, SyntaxWarning) + + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'package\.module\z') + warnings.filterwarnings('error', module=r'') + ast.parse(source, filename, module='package.module') + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10]) + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) class CopyTests(unittest.TestCase): @@ -1092,14 +1170,19 @@ class CopyTests(unittest.TestCase): def iter_ast_classes(): """Iterate over the (native) subclasses of ast.AST recursively. - This excludes the special class ast.Index since its constructor - returns an integer. + This excludes: + * abstract AST nodes + * the special class ast.Index, since its constructor returns + an integer. """ def do(cls): if cls.__module__ != 'ast': return if cls is ast.Index: return + # Don't attempt to create instances of abstract AST nodes + if _ast._is_abstract(cls): + return yield cls for sub in cls.__subclasses__(): @@ -1366,14 +1449,14 @@ def test_replace_ignore_known_custom_instance_fields(self): self.assertRaises(AttributeError, getattr, repl, 'extra') def test_replace_reject_missing_field(self): - # case: warn if deleted field is not replaced + # case: raise if deleted field is not replaced node = ast.parse('x').body[0].value context = node.ctx del node.id self.assertRaises(AttributeError, getattr, node, 'id') self.assertIs(node.ctx, context) - msg = "Name.__replace__ missing 1 keyword argument: 'id'." + msg = "ast.Name.__init__ missing 1 required positional argument: 'id'" with self.assertRaisesRegex(TypeError, re.escape(msg)): copy.replace(node) # assert that there is no side-effect @@ -1410,7 +1493,7 @@ def test_replace_reject_known_custom_instance_fields_commits(self): # explicit rejection of known instance fields self.assertHasAttr(node, 'extra') - msg = "Name.__replace__ got an unexpected keyword argument 'extra'." + msg = "ast.Name.__init__ got an unexpected keyword argument 'extra'" with self.assertRaisesRegex(TypeError, re.escape(msg)): copy.replace(node, extra=1) # assert that there is no side-effect @@ -1424,7 +1507,7 @@ def test_replace_reject_unknown_instance_fields(self): # explicit rejection of unknown extra fields self.assertRaises(AttributeError, getattr, node, 'unknown') - msg = "Name.__replace__ got an unexpected keyword argument 'unknown'." + msg = "ast.Name.__init__ got an unexpected keyword argument 'unknown'" with self.assertRaisesRegex(TypeError, re.escape(msg)): copy.replace(node, unknown=1) # assert that there is no side-effect @@ -1459,17 +1542,17 @@ def test_parse_in_error(self): def test_dump(self): node = ast.parse('spam(eggs, "and cheese")') self.assertEqual(ast.dump(node), - "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), " - "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')]))])" + "Module(body=[Expr(value=Call(func=Name(id='spam'), " + "args=[Name(id='eggs'), Constant(value='and cheese')]))])" ) self.assertEqual(ast.dump(node, annotate_fields=False), - "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), " + "Module([Expr(Call(Name('spam'), [Name('eggs'), " "Constant('and cheese')]))])" ) self.assertEqual(ast.dump(node, include_attributes=True), - "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), " + "Module(body=[Expr(value=Call(func=Name(id='spam', " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), " - "args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, " + "args=[Name(id='eggs', lineno=1, col_offset=5, " "end_lineno=1, end_col_offset=9), Constant(value='and cheese', " "lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), " @@ -1483,18 +1566,18 @@ def test_dump_indent(self): body=[ Expr( value=Call( - func=Name(id='spam', ctx=Load()), + func=Name(id='spam'), args=[ - Name(id='eggs', ctx=Load()), + Name(id='eggs'), Constant(value='and cheese')]))])""") self.assertEqual(ast.dump(node, annotate_fields=False, indent='\t'), """\ Module( \t[ \t\tExpr( \t\t\tCall( -\t\t\t\tName('spam', Load()), +\t\t\t\tName('spam'), \t\t\t\t[ -\t\t\t\t\tName('eggs', Load()), +\t\t\t\t\tName('eggs'), \t\t\t\t\tConstant('and cheese')]))])""") self.assertEqual(ast.dump(node, include_attributes=True, indent=3), """\ Module( @@ -1503,7 +1586,6 @@ def test_dump_indent(self): value=Call( func=Name( id='spam', - ctx=Load(), lineno=1, col_offset=0, end_lineno=1, @@ -1511,7 +1593,6 @@ def test_dump_indent(self): args=[ Name( id='eggs', - ctx=Load(), lineno=1, col_offset=5, end_lineno=1, @@ -1541,23 +1622,23 @@ def test_dump_incomplete(self): ) node = ast.Raise(exc=ast.Name(id='e', ctx=ast.Load()), lineno=3, col_offset=4) self.assertEqual(ast.dump(node), - "Raise(exc=Name(id='e', ctx=Load()))" + "Raise(exc=Name(id='e'))" ) self.assertEqual(ast.dump(node, annotate_fields=False), - "Raise(Name('e', Load()))" + "Raise(Name('e'))" ) self.assertEqual(ast.dump(node, include_attributes=True), - "Raise(exc=Name(id='e', ctx=Load()), lineno=3, col_offset=4)" + "Raise(exc=Name(id='e'), lineno=3, col_offset=4)" ) self.assertEqual(ast.dump(node, annotate_fields=False, include_attributes=True), - "Raise(Name('e', Load()), lineno=3, col_offset=4)" + "Raise(Name('e'), lineno=3, col_offset=4)" ) node = ast.Raise(cause=ast.Name(id='e', ctx=ast.Load())) self.assertEqual(ast.dump(node), - "Raise(cause=Name(id='e', ctx=Load()))" + "Raise(cause=Name(id='e'))" ) self.assertEqual(ast.dump(node, annotate_fields=False), - "Raise(cause=Name('e', Load()))" + "Raise(cause=Name('e'))" ) # Arguments: node = ast.arguments(args=[ast.arg("x")]) @@ -1589,10 +1670,10 @@ def test_dump_incomplete(self): [ast.Name('dataclass', ctx=ast.Load())], ) self.assertEqual(ast.dump(node), - "ClassDef(name='T', keywords=[keyword(arg='a', value=Constant(value=None))], decorator_list=[Name(id='dataclass', ctx=Load())])", + "ClassDef(name='T', keywords=[keyword(arg='a', value=Constant(value=None))], decorator_list=[Name(id='dataclass')])", ) self.assertEqual(ast.dump(node, annotate_fields=False), - "ClassDef('T', [], [keyword('a', Constant(None))], [], [Name('dataclass', Load())])", + "ClassDef('T', [], [keyword('a', Constant(None))], [], [Name('dataclass')])", ) def test_dump_show_empty(self): @@ -1620,7 +1701,7 @@ def check_text(code, empty, full, **kwargs): check_node( # Corner case: there are no real `Name` instances with `id=''`: ast.Name(id='', ctx=ast.Load()), - empty="Name(id='', ctx=Load())", + empty="Name(id='')", full="Name(id='', ctx=Load())", ) @@ -1668,35 +1749,45 @@ def check_text(code, empty, full, **kwargs): check_text( "def a(b: int = 0, *, c): ...", - empty="Module(body=[FunctionDef(name='a', args=arguments(args=[arg(arg='b', annotation=Name(id='int', ctx=Load()))], kwonlyargs=[arg(arg='c')], kw_defaults=[None], defaults=[Constant(value=0)]), body=[Expr(value=Constant(value=Ellipsis))])])", + empty="Module(body=[FunctionDef(name='a', args=arguments(args=[arg(arg='b', annotation=Name(id='int'))], kwonlyargs=[arg(arg='c')], kw_defaults=[None], defaults=[Constant(value=0)]), body=[Expr(value=Constant(value=Ellipsis))])])", full="Module(body=[FunctionDef(name='a', args=arguments(posonlyargs=[], args=[arg(arg='b', annotation=Name(id='int', ctx=Load()))], kwonlyargs=[arg(arg='c')], kw_defaults=[None], defaults=[Constant(value=0)]), body=[Expr(value=Constant(value=Ellipsis))], decorator_list=[], type_params=[])], type_ignores=[])", ) check_text( "def a(b: int = 0, *, c): ...", - empty="Module(body=[FunctionDef(name='a', args=arguments(args=[arg(arg='b', annotation=Name(id='int', ctx=Load(), lineno=1, col_offset=9, end_lineno=1, end_col_offset=12), lineno=1, col_offset=6, end_lineno=1, end_col_offset=12)], kwonlyargs=[arg(arg='c', lineno=1, col_offset=21, end_lineno=1, end_col_offset=22)], kw_defaults=[None], defaults=[Constant(value=0, lineno=1, col_offset=15, end_lineno=1, end_col_offset=16)]), body=[Expr(value=Constant(value=Ellipsis, lineno=1, col_offset=25, end_lineno=1, end_col_offset=28), lineno=1, col_offset=25, end_lineno=1, end_col_offset=28)], lineno=1, col_offset=0, end_lineno=1, end_col_offset=28)])", + empty="Module(body=[FunctionDef(name='a', args=arguments(args=[arg(arg='b', annotation=Name(id='int', lineno=1, col_offset=9, end_lineno=1, end_col_offset=12), lineno=1, col_offset=6, end_lineno=1, end_col_offset=12)], kwonlyargs=[arg(arg='c', lineno=1, col_offset=21, end_lineno=1, end_col_offset=22)], kw_defaults=[None], defaults=[Constant(value=0, lineno=1, col_offset=15, end_lineno=1, end_col_offset=16)]), body=[Expr(value=Constant(value=Ellipsis, lineno=1, col_offset=25, end_lineno=1, end_col_offset=28), lineno=1, col_offset=25, end_lineno=1, end_col_offset=28)], lineno=1, col_offset=0, end_lineno=1, end_col_offset=28)])", full="Module(body=[FunctionDef(name='a', args=arguments(posonlyargs=[], args=[arg(arg='b', annotation=Name(id='int', ctx=Load(), lineno=1, col_offset=9, end_lineno=1, end_col_offset=12), lineno=1, col_offset=6, end_lineno=1, end_col_offset=12)], kwonlyargs=[arg(arg='c', lineno=1, col_offset=21, end_lineno=1, end_col_offset=22)], kw_defaults=[None], defaults=[Constant(value=0, lineno=1, col_offset=15, end_lineno=1, end_col_offset=16)]), body=[Expr(value=Constant(value=Ellipsis, lineno=1, col_offset=25, end_lineno=1, end_col_offset=28), lineno=1, col_offset=25, end_lineno=1, end_col_offset=28)], decorator_list=[], type_params=[], lineno=1, col_offset=0, end_lineno=1, end_col_offset=28)], type_ignores=[])", include_attributes=True, ) check_text( 'spam(eggs, "and cheese")', - empty="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')]))])", + empty="Module(body=[Expr(value=Call(func=Name(id='spam'), args=[Name(id='eggs'), Constant(value='and cheese')]))])", full="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], keywords=[]))], type_ignores=[])", ) check_text( 'spam(eggs, text="and cheese")', - empty="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load())], keywords=[keyword(arg='text', value=Constant(value='and cheese'))]))])", + empty="Module(body=[Expr(value=Call(func=Name(id='spam'), args=[Name(id='eggs')], keywords=[keyword(arg='text', value=Constant(value='and cheese'))]))])", full="Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), args=[Name(id='eggs', ctx=Load())], keywords=[keyword(arg='text', value=Constant(value='and cheese'))]))], type_ignores=[])", ) check_text( "import _ast as ast; from module import sub", - empty="Module(body=[Import(names=[alias(name='_ast', asname='ast')]), ImportFrom(module='module', names=[alias(name='sub')], level=0)])", - full="Module(body=[Import(names=[alias(name='_ast', asname='ast')]), ImportFrom(module='module', names=[alias(name='sub')], level=0)], type_ignores=[])", + empty="Module(body=[Import(names=[alias(name='_ast', asname='ast')], is_lazy=0), ImportFrom(module='module', names=[alias(name='sub')], level=0, is_lazy=0)])", + full="Module(body=[Import(names=[alias(name='_ast', asname='ast')], is_lazy=0), ImportFrom(module='module', names=[alias(name='sub')], level=0, is_lazy=0)], type_ignores=[])", ) + def test_dump_with_color(self): + node = ast.parse("x = 1") + self.assertNotIn("\x1b[", ast.dump(node)) + self.assertNotIn("\x1b[", ast.dump(node, color=False)) + self.assertIn("\x1b[", ast.dump(node, color=True)) + + node = ast.Constant(value="\x1b[31m") + self.assertEqual(ast.dump(node), "Constant(value='\\x1b[31m')") + self.assertIn("'\\x1b[31m'", ast.dump(node, color=True)) + def test_copy_location(self): src = ast.parse('1 + 1', mode='eval') src.body.right = ast.copy_location(ast.Constant(2), src.body.right) @@ -1721,12 +1812,12 @@ def test_fix_missing_locations(self): self.assertEqual(src, ast.fix_missing_locations(src)) self.maxDiff = None self.assertEqual(ast.dump(src, include_attributes=True), - "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), " + "Module(body=[Expr(value=Call(func=Name(id='write', " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), " "args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, " "end_col_offset=12)], lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, " - "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), " + "end_col_offset=13), Expr(value=Call(func=Name(id='spam', " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), " "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=0)], lineno=1, col_offset=0, end_lineno=1, " @@ -1787,22 +1878,22 @@ def test_iter_child_nodes(self): ) def test_get_docstring(self): - node = ast.parse('"""line one\n line two"""') + node = ast.parse('"""line one\n line two"""', optimize=False) self.assertEqual(ast.get_docstring(node), 'line one\nline two') - node = ast.parse('class foo:\n """line one\n line two"""') + node = ast.parse('class foo:\n """line one\n line two"""', optimize=False) self.assertEqual(ast.get_docstring(node.body[0]), 'line one\nline two') - node = ast.parse('def foo():\n """line one\n line two"""') + node = ast.parse('def foo():\n """line one\n line two"""', optimize=False) self.assertEqual(ast.get_docstring(node.body[0]), 'line one\nline two') - node = ast.parse('async def foo():\n """spam\n ham"""') + node = ast.parse('async def foo():\n """spam\n ham"""', optimize=False) self.assertEqual(ast.get_docstring(node.body[0]), 'spam\nham') - node = ast.parse('async def foo():\n """spam\n ham"""') + node = ast.parse('async def foo():\n """spam\n ham"""', optimize=False) self.assertEqual(ast.get_docstring(node.body[0], clean=False), 'spam\n ham') node = ast.parse('x') @@ -1841,7 +1932,8 @@ def test_multi_line_docstring_col_offset_and_lineno_issue16806(self): 'def foo():\n """line one\n line two"""\n\n' ' def bar():\n """line one\n line two"""\n' ' """line one\n line two"""\n' - '"""line one\nline two"""\n\n' + '"""line one\nline two"""\n\n', + optimize=False ) self.assertEqual(node.body[0].col_offset, 0) self.assertEqual(node.body[0].lineno, 1) @@ -1926,7 +2018,6 @@ def test_literal_eval_malformed_dict_nodes(self): malformed = ast.Dict(keys=[ast.Constant(1)], values=[ast.Constant(2), ast.Constant(3)]) self.assertRaises(ValueError, ast.literal_eval, malformed) - @unittest.expectedFailure # TODO: RUSTPYTHON; SyntaxError: expected an expression def test_literal_eval_trailing_ws(self): self.assertEqual(ast.literal_eval(" -1"), -1) self.assertEqual(ast.literal_eval("\t\t-1"), -1) @@ -1945,7 +2036,6 @@ def test_literal_eval_malformed_lineno(self): with self.assertRaisesRegex(ValueError, msg): ast.literal_eval(node) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: "unexpected indent" does not match "expected an expression (, line 2)" def test_literal_eval_syntax_errors(self): with self.assertRaisesRegex(SyntaxError, "unexpected indent"): ast.literal_eval(r''' @@ -2414,9 +2504,9 @@ def test_stdlib_validates(self): fn = os.path.join(STDLIB, module) with open(fn, "r", encoding="utf-8") as fp: source = fp.read() - mod = ast.parse(source, fn) + mod = ast.parse(source, fn, optimize=False) compile(mod, fn, "exec") - mod2 = ast.parse(source, fn) + mod2 = ast.parse(source, fn, optimize=False) self.assertTrue(ast.compare(mod, mod2)) constant_1 = ast.Constant(1) @@ -2630,16 +2720,17 @@ def test_assign_to_constant(self): "to in Store context") def test_get_docstring(self): - tree = ast.parse("'docstring'\nx = 1") + tree = ast.parse("'docstring'\nx = 1", optimize=False) self.assertEqual(ast.get_docstring(tree), 'docstring') def get_load_const(self, tree): # Compile to bytecode, disassemble and get parameter of LOAD_CONST - # instructions + # and LOAD_COMMON_CONSTANT instructions co = compile(tree, '', 'exec') consts = [] for instr in dis.get_instructions(co): - if instr.opcode in dis.hasconst: + if instr.opcode in dis.hasconst or \ + instr.opname == 'LOAD_COMMON_CONSTANT': consts.append(instr.argval) return consts @@ -3062,8 +3153,8 @@ def test_source_segment_missing_info(self): class NodeTransformerTests(ASTTestMixin, unittest.TestCase): def assertASTTransformation(self, transformer_class, - initial_code, expected_code): - initial_ast = ast.parse(dedent(initial_code)) + code, expected_code): + initial_ast = ast.parse(dedent(code)) expected_ast = ast.parse(dedent(expected_code)) transformer = transformer_class() @@ -3183,11 +3274,10 @@ def test_FunctionDef(self): args = ast.arguments() self.assertEqual(args.args, []) self.assertEqual(args.posonlyargs, []) - with self.assertWarnsRegex(DeprecationWarning, - r"FunctionDef\.__init__ missing 1 required positional argument: 'name'"): - node = ast.FunctionDef(args=args) - self.assertNotHasAttr(node, "name") - self.assertEqual(node.decorator_list, []) + msg = "ast.FunctionDef.__init__ missing 1 required positional argument: 'name'" + with self.assertRaisesRegex(TypeError, re.escape(msg)): + ast.FunctionDef(args=args) + node = ast.FunctionDef(name='foo', args=args) self.assertEqual(node.name, 'foo') self.assertEqual(node.decorator_list, []) @@ -3205,9 +3295,8 @@ def test_expr_context(self): self.assertEqual(name3.id, "x") self.assertIsInstance(name3.ctx, ast.Del) - with self.assertWarnsRegex(DeprecationWarning, - r"Name\.__init__ missing 1 required positional argument: 'id'"): - name3 = ast.Name() + msg = "ast.Name.__init__ missing 1 required positional argument: 'id'" + self.assertRaisesRegex(TypeError, re.escape(msg), ast.Name) def test_custom_subclass_with_no_fields(self): class NoInit(ast.AST): @@ -3246,20 +3335,18 @@ class MyAttrs(ast.AST): self.assertEqual(obj.a, 1) self.assertEqual(obj.b, 2) - with self.assertWarnsRegex(DeprecationWarning, - r"MyAttrs.__init__ got an unexpected keyword argument 'c'."): - obj = MyAttrs(c=3) + msg = "MyAttrs.__init__ got an unexpected keyword argument 'c'" + with self.assertRaisesRegex(TypeError, re.escape(msg)): + MyAttrs(c=3) def test_fields_and_types_no_default(self): class FieldsAndTypesNoDefault(ast.AST): _fields = ('a',) _field_types = {'a': int} - with self.assertWarnsRegex(DeprecationWarning, - r"FieldsAndTypesNoDefault\.__init__ missing 1 required positional argument: 'a'\."): - obj = FieldsAndTypesNoDefault() - with self.assertRaises(AttributeError): - obj.a + msg = "FieldsAndTypesNoDefault.__init__ missing 1 required positional argument: 'a'" + self.assertRaisesRegex(TypeError, re.escape(msg), FieldsAndTypesNoDefault) + obj = FieldsAndTypesNoDefault(a=1) self.assertEqual(obj.a, 1) @@ -3270,13 +3357,8 @@ class MoreFieldsThanTypes(ast.AST): a: int | None = None b: int | None = None - with self.assertWarnsRegex( - DeprecationWarning, - r"Field 'b' is missing from MoreFieldsThanTypes\._field_types" - ): - obj = MoreFieldsThanTypes() - self.assertIs(obj.a, None) - self.assertIs(obj.b, None) + msg = r"Field 'b' is missing from .*\.MoreFieldsThanTypes\._field_types" + self.assertRaisesRegex(TypeError, msg, MoreFieldsThanTypes) obj = MoreFieldsThanTypes(a=1, b=2) self.assertEqual(obj.a, 1) @@ -3288,8 +3370,7 @@ class BadFields(ast.AST): _field_types = {'a': int} # This should not crash - with self.assertWarnsRegex(DeprecationWarning, r"Field b'\\xff\\xff.*' .*"): - obj = BadFields() + self.assertRaisesRegex(TypeError, r"Field b'\\xff\\xff.*' .*", BadFields) def test_complete_field_types(self): class _AllFieldTypes(ast.AST): @@ -3409,6 +3490,7 @@ def test_subinterpreter(self): self.assertEqual(res, 0) +@support.force_not_colorized_test_class class CommandLineTests(unittest.TestCase): def setUp(self): self.filename = tempfile.mktemp() @@ -3481,7 +3563,7 @@ def test_exec_mode_flag(self): body=[ AnnAssign( target=Name(id='x', ctx=Store()), - annotation=Name(id='bool', ctx=Load()), + annotation=Name(id='bool'), value=Constant(value=1), simple=1)], type_ignores=[ @@ -3509,7 +3591,7 @@ def test_eval_mode_flag(self): expect = ''' Expression( body=Call( - func=Name(id='print', ctx=Load()), + func=Name(id='print'), args=[ Constant(value=1), Constant(value=2), @@ -3525,12 +3607,11 @@ def test_func_type_mode_flag(self): expect = ''' FunctionType( argtypes=[ - Name(id='int', ctx=Load()), - Name(id='str', ctx=Load())], + Name(id='int'), + Name(id='str')], returns=Subscript( - value=Name(id='list', ctx=Load()), - slice=Name(id='int', ctx=Load()), - ctx=Load())) + value=Name(id='list'), + slice=Name(id='int'))) ''' for flag in ('-m=func_type', '--mode=func_type'): with self.subTest(flag=flag): @@ -3544,7 +3625,7 @@ def test_no_type_comments_flag(self): body=[ AnnAssign( target=Name(id='x', ctx=Store()), - annotation=Name(id='bool', ctx=Load()), + annotation=Name(id='bool'), value=Constant(value=1), simple=1)]) ''' @@ -3589,7 +3670,7 @@ def test_feature_version_flag(self): Module( body=[ Match( - subject=Name(id='x', ctx=Load()), + subject=Name(id='x'), cases=[ match_case( pattern=MatchValue( @@ -3612,7 +3693,7 @@ def test_no_optimize_flag(self): Module( body=[ Match( - subject=Name(id='a', ctx=Load()), + subject=Name(id='a'), cases=[ match_case( pattern=MatchValue( @@ -3638,7 +3719,7 @@ def test_optimize_flag(self): Module( body=[ Match( - subject=Name(id='a', ctx=Load()), + subject=Name(id='a'), cases=[ match_case( pattern=MatchValue( @@ -3793,46 +3874,6 @@ def test_match_case_not_folded_in_unoptimized_ast(self): for optval in (0, 1, 2): self.assertIn(folded if optval else unfolded, ast.dump(ast.parse(src, optimize=optval))) - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_binop(self): - return super().test_folding_binop() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_comparator(self): - return super().test_folding_comparator() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_iter(self): - return super().test_folding_iter() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_not(self): - return super().test_folding_not() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_subscript(self): - return super().test_folding_subscript() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_tuple(self): - return super().test_folding_tuple() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_type_param_in_class_def(self): - return super().test_folding_type_param_in_class_def() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_type_param_in_function_def(self): - return super().test_folding_type_param_in_function_def() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_type_param_in_type_alias(self): - return super().test_folding_type_param_in_type_alias() - - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: compile() unrecognized flags - def test_folding_unaryop(self): - return super().test_folding_unaryop() - if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == '--snapshot-update': diff --git a/Lib/test/test_asyncgen.py b/Lib/test/test_asyncgen.py index fc3bd7dca62..cd33878d6c7 100644 --- a/Lib/test/test_asyncgen.py +++ b/Lib/test/test_asyncgen.py @@ -1835,20 +1835,6 @@ async def run(): res = self.loop.run_until_complete(run()) self.assertEqual(res, [i * 2 for i in range(1, 10)]) - def test_async_gen_expression_incorrect(self): - async def ag(): - yield 42 - - async def run(arg): - (x async for x in arg) - - err_msg_async = "'async for' requires an object with " \ - "__aiter__ method, got .*" - - self.loop.run_until_complete(run(ag())) - with self.assertRaisesRegex(TypeError, err_msg_async): - self.loop.run_until_complete(run(None)) - def test_asyncgen_nonstarted_hooks_are_cancellable(self): # See https://bugs.python.org/issue38013 messages = [] @@ -2035,6 +2021,15 @@ async def gen(): g.athrow(RuntimeError) gc_collect() + def test_athrow_throws_immediately(self): + async def gen(): + yield 1 + + g = gen() + msg = "athrow expected at least 1 argument, got 0" + with self.assertRaisesRegex(TypeError, msg): + g.athrow() + def test_aclose(self): async def gen(): yield 1 diff --git a/Lib/test/test_asyncio/test_base_events.py b/Lib/test/test_asyncio/test_base_events.py index 1b727f3b1fe..01529a9a2c1 100644 --- a/Lib/test/test_asyncio/test_base_events.py +++ b/Lib/test/test_asyncio/test_base_events.py @@ -150,6 +150,29 @@ def test_ipaddr_info_no_inet_pton(self, m_socket): socket.SOCK_STREAM, socket.IPPROTO_TCP)) + def test_interleave_addrinfos(self): + self.maxDiff = None + SIX_A = (socket.AF_INET6, 0, 0, '', ('2001:db8::1', 1)) + SIX_B = (socket.AF_INET6, 0, 0, '', ('2001:db8::2', 2)) + SIX_C = (socket.AF_INET6, 0, 0, '', ('2001:db8::3', 3)) + SIX_D = (socket.AF_INET6, 0, 0, '', ('2001:db8::4', 4)) + FOUR_A = (socket.AF_INET, 0, 0, '', ('192.0.2.1', 5)) + FOUR_B = (socket.AF_INET, 0, 0, '', ('192.0.2.2', 6)) + FOUR_C = (socket.AF_INET, 0, 0, '', ('192.0.2.3', 7)) + FOUR_D = (socket.AF_INET, 0, 0, '', ('192.0.2.4', 8)) + + addrinfos = [SIX_A, SIX_B, SIX_C, FOUR_A, FOUR_B, FOUR_C, FOUR_D, SIX_D] + expected = [SIX_A, FOUR_A, SIX_B, FOUR_B, SIX_C, FOUR_C, SIX_D, FOUR_D] + + self.assertEqual(expected, base_events._interleave_addrinfos(addrinfos)) + + expected_fafc_2 = [SIX_A, SIX_B, FOUR_A, SIX_C, FOUR_B, SIX_D, FOUR_C, FOUR_D] + self.assertEqual( + expected_fafc_2, + base_events._interleave_addrinfos(addrinfos, first_address_family_count=2), + ) + + class BaseEventLoopTests(test_utils.TestCase): @@ -1053,6 +1076,76 @@ def test_asyncgen_finalization_by_gc_in_other_thread(self): test_utils.run_briefly(self.loop) self.assertTrue(status['finalized']) + @unittest.skipUnless(socket_helper.IPV6_ENABLED, 'no IPv6 support') + @patch_socket + def test_create_connection_happy_eyeballs(self, m_socket): + + class MyProto(asyncio.Protocol): + pass + + async def getaddrinfo(*args, **kw): + return [(socket.AF_INET6, 0, 0, '', ('2001:db8::1', 1)), + (socket.AF_INET, 0, 0, '', ('192.0.2.1', 5))] + + async def sock_connect(sock, address): + if address[0] == '2001:db8::1': + await asyncio.sleep(1) + sock.connect(address) + + # gh-151540: use a selector event loop instead of the platform + # default; the Windows proactor loop would register the mocked + # socket with a real IOCP handle instead of the mocked + # _add_reader/_add_writer below. + loop = asyncio.SelectorEventLoop() + loop._add_writer = mock.Mock() + loop._add_writer = mock.Mock() + loop._add_reader = mock.Mock() + loop.getaddrinfo = getaddrinfo + loop.sock_connect = sock_connect + + coro = loop.create_connection(MyProto, 'example.com', 80, happy_eyeballs_delay=0.3) + transport, protocol = loop.run_until_complete(coro) + try: + sock = transport._sock + sock.connect.assert_called_with(('192.0.2.1', 5)) + finally: + transport.close() + test_utils.run_briefly(loop) # allow transport to close + loop.close() + + @patch_socket + def test_create_connection_happy_eyeballs_ipv4_only(self, m_socket): + + class MyProto(asyncio.Protocol): + pass + + async def getaddrinfo(*args, **kw): + return [(socket.AF_INET, 0, 0, '', ('192.0.2.1', 5)), + (socket.AF_INET, 0, 0, '', ('192.0.2.2', 6))] + + async def sock_connect(sock, address): + if address[0] == '192.0.2.1': + await asyncio.sleep(1) + sock.connect(address) + + # gh-151540: see test_create_connection_happy_eyeballs above. + loop = asyncio.SelectorEventLoop() + loop._add_writer = mock.Mock() + loop._add_writer = mock.Mock() + loop._add_reader = mock.Mock() + loop.getaddrinfo = getaddrinfo + loop.sock_connect = sock_connect + + coro = loop.create_connection(MyProto, 'example.com', 80, happy_eyeballs_delay=0.3) + transport, protocol = loop.run_until_complete(coro) + try: + sock = transport._sock + sock.connect.assert_called_with(('192.0.2.2', 6)) + finally: + transport.close() + test_utils.run_briefly(loop) # allow transport to close + loop.close() + class MyProto(asyncio.Protocol): done = None @@ -1194,6 +1287,47 @@ def getaddrinfo(*args, **kw): self.loop.run_until_complete(coro) self.assertTrue(sock.close.called) + def test_create_connection_sock_transport_error_closes_sock(self): + # gh-153133: a user-provided socket is closed if the transport is + # never created. + sock = mock.Mock() + sock.type = socket.SOCK_STREAM + + def factory(): + raise ZeroDivisionError + + coro = self.loop.create_connection(factory, sock=sock) + with self.assertRaises(ZeroDivisionError): + self.loop.run_until_complete(coro) + self.assertTrue(sock.close.called) + + @patch_socket + def test_create_connection_transport_error_closes_sock(self, m_socket): + # gh-153133: an internally created socket is closed if the transport + # is never created. + sock = mock.Mock() + m_socket.socket.return_value = sock + + def getaddrinfo(*args, **kw): + fut = self.loop.create_future() + addr = (socket.AF_INET, socket.SOCK_STREAM, 0, '', + ('127.0.0.1', 80)) + fut.set_result([addr]) + return fut + self.loop.getaddrinfo = getaddrinfo + + async def sock_connect(sock, address): + return None + + def factory(): + raise ZeroDivisionError + + with mock.patch.object(self.loop, 'sock_connect', sock_connect): + coro = self.loop.create_connection(factory, '127.0.0.1', 80) + with self.assertRaises(ZeroDivisionError): + self.loop.run_until_complete(coro) + self.assertTrue(sock.close.called) + @patch_socket def test_create_connection_happy_eyeballs_empty_exceptions(self, m_socket): # See gh-135836: Fix IndexError when Happy Eyeballs algorithm @@ -1608,7 +1742,8 @@ def mock_make_ssl_transport(sock, protocol, sslcontext, waiter, server_side=False, server_hostname='python.org', ssl_handshake_timeout=handshake_timeout, - ssl_shutdown_timeout=shutdown_timeout) + ssl_shutdown_timeout=shutdown_timeout, + context=ANY) # Next try an explicit server_hostname. self.loop._make_ssl_transport.reset_mock() coro = self.loop.create_connection( @@ -1623,7 +1758,8 @@ def mock_make_ssl_transport(sock, protocol, sslcontext, waiter, server_side=False, server_hostname='perl.com', ssl_handshake_timeout=handshake_timeout, - ssl_shutdown_timeout=shutdown_timeout) + ssl_shutdown_timeout=shutdown_timeout, + context=ANY) # Finally try an explicit empty server_hostname. self.loop._make_ssl_transport.reset_mock() coro = self.loop.create_connection( @@ -1638,7 +1774,8 @@ def mock_make_ssl_transport(sock, protocol, sslcontext, waiter, server_side=False, server_hostname='', ssl_handshake_timeout=handshake_timeout, - ssl_shutdown_timeout=shutdown_timeout) + ssl_shutdown_timeout=shutdown_timeout, + context=ANY) def test_create_connection_no_ssl_server_hostname_errors(self): # When not using ssl, server_hostname must be None. @@ -2016,7 +2153,7 @@ def test_accept_connection_exception(self, m_log): constants.ACCEPT_RETRY_DELAY, # self.loop._start_serving mock.ANY, - MyProto, sock, None, None, mock.ANY, mock.ANY, mock.ANY) + MyProto, sock, None, None, mock.ANY, mock.ANY, mock.ANY, mock.ANY) def test_call_coroutine(self): async def simple_coroutine(): diff --git a/Lib/test/test_asyncio/test_events.py b/Lib/test/test_asyncio/test_events.py index 919d543b032..2bd87a5bdb0 100644 --- a/Lib/test/test_asyncio/test_events.py +++ b/Lib/test/test_asyncio/test_events.py @@ -33,6 +33,7 @@ from multiprocessing.util import _cleanup_tests as multiprocessing_cleanup_tests from test.test_asyncio import utils as test_utils from test import support +from test.support import os_helper from test.support import socket_helper from test.support import threading_helper from test.support import ALWAYS_EQ, LARGEST, SMALLEST @@ -559,6 +560,19 @@ def writer(data): r.close() self.assertEqual(read, data) + def test_writelines_empty_chunk(self): + # gh-155888: an empty chunk can never be drained, so never buffer it + rsock, wsock = socket.socketpair() + self.addCleanup(rsock.close) + + async def main(): + reader, writer = await asyncio.open_connection(sock=wsock) + writer.writelines([b'data', b'']) + writer.close() + await asyncio.wait_for(writer.wait_closed(), support.SHORT_TIMEOUT) + + self.loop.run_until_complete(main()) + @unittest.skipUnless(hasattr(signal, 'SIGKILL'), 'No SIGKILL') def test_add_signal_handler(self): caught = 0 @@ -1188,12 +1202,13 @@ def test_create_server_ssl_verify_failed(self): '(?i)certificate.verify.failed'): self.loop.run_until_complete(f_c) - # execute the loop to log the connection error - test_utils.run_briefly(self.loop) + # close connection: wait until the server-side transport of the + # failed handshake is closed as well, otherwise its socket may + # still be open when the loop is closed (gh-159123). + server.close() + self.loop.run_until_complete(server.wait_closed()) - # close connection self.assertIsNone(proto.transport) - server.close() @socket_helper.skip_unless_bind_unix_socket @unittest.skipIf(ssl is None, 'No ssl module') @@ -1218,12 +1233,13 @@ def test_create_unix_server_ssl_verify_failed(self): '(?i)certificate.verify.failed'): self.loop.run_until_complete(f_c) - # execute the loop to log the connection error - test_utils.run_briefly(self.loop) + # close connection: wait until the server-side transport of the + # failed handshake is closed as well, otherwise its socket may + # still be open when the loop is closed (gh-159123). + server.close() + self.loop.run_until_complete(server.wait_closed()) - # close connection self.assertIsNone(proto.transport) - server.close() @unittest.skipIf(ssl is None, 'No ssl module') def test_create_server_ssl_match_failed(self): @@ -1254,10 +1270,14 @@ def test_create_server_ssl_match_failed(self): with self.assertRaisesRegex(ssl.CertificateError, regex): self.loop.run_until_complete(f_c) - # close connection + # close connection: wait until the server-side transport of the + # failed handshake is closed as well, otherwise its socket may + # still be open when the loop is closed (gh-159123). + server.close() + self.loop.run_until_complete(server.wait_closed()) + # transport is None because TLS ALERT aborted the handshake self.assertIsNone(proto.transport) - server.close() @socket_helper.skip_unless_bind_unix_socket @unittest.skipIf(ssl is None, 'No ssl module') @@ -1509,9 +1529,18 @@ class Protocol(asyncio.DatagramProtocol): _received_datagram = None + def connection_made(self, transport): + self.errors = [] + self.error_received_event = loop.create_future() + def datagram_received(self, data, addr): self._received_datagram.set_result(data) + def error_received(self, exc): + self.errors.append(exc) + if not self.error_received_event.done(): + self.error_received_event.set_result(None) + async def wait_for_datagram_received(self): self._received_datagram = loop.create_future() result = await asyncio.wait_for(self._received_datagram, 10) @@ -1566,9 +1595,330 @@ def create_socket(): protocol_1.wait_for_datagram_received() ), b'd') + if sys.platform == 'win32': + # The bad send to addr_3 should be surfaced to the protocol + # via error_received() instead of being silently dropped, + # while transport_1 keeps working as shown above. + loop.run_until_complete( + asyncio.wait_for(protocol_1.error_received_event, 10)) + self.assertTrue(protocol_1.errors) + self.assertIsInstance(protocol_1.errors[0], ConnectionResetError) + transport_1.close() transport_2.close() + def test_datagram_write_error_resumes_paused_protocol(self): + # See https://github.com/python/cpython/issues/156698: a + # datagram write error must not strand data left in the write + # buffer, nor leave a paused protocol paused forever. + loop = self.loop + + class Protocol(asyncio.DatagramProtocol): + def connection_made(self, transport): + self.transport = transport + self.paused = False + self.resumed = False + self.errors = [] + self.error_received_event = loop.create_future() + + def pause_writing(self): + self.paused = True + + def resume_writing(self): + self.resumed = True + + def error_received(self, exc): + self.errors.append(exc) + if not self.error_received_event.done(): + self.error_received_event.set_result(None) + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setblocking(False) + sock.bind(('127.0.0.1', 0)) + transport, protocol = loop.run_until_complete( + loop.create_datagram_endpoint(Protocol, sock=sock)) + addr = sock.getsockname() + + # A high water mark of 0 makes pausing deterministic whenever + # anything is left in the write buffer. + transport.set_write_buffer_limits(0) + + # The oversized datagram fails while it is in flight, and the + # normal datagram behind it is left queued -- queuing is also + # what trips pause_writing() at a high water mark of 0. + transport.sendto(b'\x00' * 70000, addr) + transport.sendto(b'queued', addr) + + loop.run_until_complete( + asyncio.wait_for(protocol.error_received_event, + support.SHORT_TIMEOUT)) + self.assertTrue(protocol.errors) + self.assertIsInstance(protocol.errors[0], OSError) + + # The write buffer must not be left stranded. + test_utils.run_until( + loop, lambda: transport.get_write_buffer_size() == 0) + + # A protocol that got paused must eventually be resumed too -- + # without requiring an unsolicited extra sendto() to un-stick it. + if protocol.paused: + test_utils.run_until(loop, lambda: protocol.resumed) + + transport.close() + test_utils.run_briefly(loop) + + def test_datagram_write_error_reentrant_sendto(self): + # See https://github.com/python/cpython/issues/156698: an + # error_received() callback that sends more data synchronously + # can itself schedule a new write. The write-loop restart scheduled + # for the failed write must notice that and not try to start a + # second, conflicting one. + loop = self.loop + unhandled = [] + loop.set_exception_handler(lambda loop, context: unhandled.append(context)) + + class Protocol(asyncio.DatagramProtocol): + def connection_made(self, transport): + self.transport = transport + self.sent_extra = False + self.errors = [] + self.done = loop.create_future() + + def datagram_received(self, data, addr): + if not self.done.done(): + self.done.set_result(None) + + def error_received(self, exc): + self.errors.append(exc) + if not self.sent_extra: + # Reentrantly kicks off another write while the + # failing one is still unwinding on the stack. + self.sent_extra = True + self.transport.sendto(b'extra', self.addr) + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setblocking(False) + sock.bind(('127.0.0.1', 0)) + transport, protocol = loop.run_until_complete( + loop.create_datagram_endpoint(Protocol, sock=sock)) + protocol.addr = addr = sock.getsockname() + + oversized = b'\x00' * 70000 + transport.sendto(oversized, addr) + transport.sendto(b'queued', addr) + + # The 'extra' datagram sent from error_received() is delivered + # back to the same socket; waiting for it proves the write loop + # kept running instead of wedging or crashing. + loop.run_until_complete( + asyncio.wait_for(protocol.done, support.SHORT_TIMEOUT)) + + test_utils.run_until( + loop, lambda: transport.get_write_buffer_size() == 0) + + transport.close() + test_utils.run_briefly(loop) + + self.assertTrue(protocol.errors) + self.assertFalse( + unhandled, + f'unhandled exception in the write loop: {unhandled}') + + def test_datagram_close_flushes_queued_data(self): + # See https://github.com/python/cpython/issues/156920: _conn_lost + # used to mean "close() was requested" rather than "no more data + # will be sent". Since add_done_callback() always defers an + # already-completed write's callback with call_soon(), a sendto() + # immediately followed by close() -- with no await in between -- + # leaves a write genuinely outstanding at close() time on every + # platform, not just a slow one. Closing must let that write (and + # anything queued behind it) drain and still call connection_lost(), + # instead of tripping the "no more data will be sent" guard before + # the drain has actually happened and hanging forever. + loop = self.loop + + class Receiver(asyncio.DatagramProtocol): + def connection_made(self, transport): + self.received = [] + + def datagram_received(self, data, addr): + self.received.append(data) + + recv_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + recv_sock.setblocking(False) + recv_sock.bind(('127.0.0.1', 0)) + recv_transport, receiver = loop.run_until_complete( + loop.create_datagram_endpoint(Receiver, sock=recv_sock)) + addr = recv_sock.getsockname() + + class Protocol(asyncio.DatagramProtocol): + def connection_made(self, transport): + self.lost = loop.create_future() + + def connection_lost(self, exc): + if not self.lost.done(): + self.lost.set_result(exc) + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setblocking(False) + sock.bind(('127.0.0.1', 0)) + transport, protocol = loop.run_until_complete( + loop.create_datagram_endpoint(Protocol, sock=sock)) + + # 'first' is still in flight (its completion callback hasn't run + # yet) and 'second' is queued behind it when close() is called. + transport.sendto(b'first', addr) + transport.sendto(b'second', addr) + transport.close() + + loop.run_until_complete( + asyncio.wait_for(protocol.lost, support.SHORT_TIMEOUT)) + + test_utils.run_until( + loop, lambda: len(receiver.received) >= 2) + self.assertEqual(sorted(receiver.received), [b'first', b'second']) + + recv_transport.close() + test_utils.run_briefly(loop) + + def test_datagram_close_during_write_error_calls_connection_lost(self): + # See https://github.com/python/cpython/issues/156920: if the + # write that's outstanding when close() is called goes on to fail + # (rather than succeed), the failure handler used to only re-schedule + # the write loop when data was still queued behind it. If that + # failing write was the last thing in the buffer, nothing re-scheduled + # the loop, so the close() in progress never got to call + # connection_lost() -- it hung forever instead of finishing once + # the buffer was actually empty. + loop = self.loop + + class Protocol(asyncio.DatagramProtocol): + def connection_made(self, transport): + self.lost = loop.create_future() + self.errors = [] + + def error_received(self, exc): + self.errors.append(exc) + + def connection_lost(self, exc): + if not self.lost.done(): + self.lost.set_result(exc) + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setblocking(False) + sock.bind(('127.0.0.1', 0)) + transport, protocol = loop.run_until_complete( + loop.create_datagram_endpoint(Protocol, sock=sock)) + addr = sock.getsockname() + + # 'ok' is still in flight when close() is called; 'oversized' is + # queued behind it and fails once it reaches the front of the + # buffer, leaving the buffer empty right as the error is handled. + oversized = b'\x00' * 70000 + transport.sendto(b'ok', addr) + transport.sendto(oversized, addr) + transport.close() + + loop.run_until_complete( + asyncio.wait_for(protocol.lost, support.SHORT_TIMEOUT)) + self.assertTrue(protocol.errors) + + def test_datagram_write_error_close_from_callback(self): + # See https://github.com/python/cpython/issues/156920: an + # error_received() callback that closes the transport must still + # result in connection_lost() being called eventually, instead of + # leaving the transport hanging forever. Two failing writes are + # used so that the first failure's error_received() call closes + # the transport while the second is still queued (close() defers + # to the write loop), and the second failure then empties the + # buffer with self._closing already True and no write in flight + # -- exercising the `self._closing` half of the + # `if self._buffer or self._closing:` condition in _loop_writing. + loop = self.loop + + class Protocol(asyncio.DatagramProtocol): + def connection_made(self, transport): + self.transport = transport + self.errors = [] + self.lost = loop.create_future() + + def error_received(self, exc): + self.errors.append(exc) + self.transport.close() + + def connection_lost(self, exc): + if not self.lost.done(): + self.lost.set_result(exc) + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setblocking(False) + sock.bind(('127.0.0.1', 0)) + transport, protocol = loop.run_until_complete( + loop.create_datagram_endpoint(Protocol, sock=sock)) + addr = sock.getsockname() + + oversized = b'\x00' * 70000 + transport.sendto(oversized, addr) + transport.sendto(oversized, addr) + + loop.run_until_complete( + asyncio.wait_for(protocol.lost, support.SHORT_TIMEOUT)) + self.assertEqual(len(protocol.errors), 2) + + def test_datagram_recvfrom_connection_reset_recovers(self): + # gh-127057: a UDP socket that sent a datagram to an address that + # wasn't listening can raise ConnectionResetError on a later + # receive. The transport must keep working afterwards. + loop = self.loop + + class Protocol(asyncio.DatagramProtocol): + def connection_made(self, transport): + self.transport = transport + self.errors = [] + self.received = [] + self.datagram_received_event = loop.create_future() + + def error_received(self, exc): + self.errors.append(exc) + + def datagram_received(self, data, addr): + self.received.append(data) + if not self.datagram_received_event.done(): + self.datagram_received_event.set_result(None) + + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + sock.setblocking(False) + sock.bind(('127.0.0.1', 0)) + addr = sock.getsockname() + + # Bind and immediately close a second socket to get an address + # that is guaranteed not to be listening. + closed = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + closed.bind(('127.0.0.1', 0)) + closed_addr = closed.getsockname() + closed.close() + + # Trigger the error before the socket is wrapped in a transport, + # so that the first read raises synchronously. + sock.sendto(b'x', closed_addr) + + transport, protocol = loop.run_until_complete( + loop.create_datagram_endpoint(Protocol, sock=sock)) + + transport.sendto(b'ping', addr) + loop.run_until_complete(asyncio.wait_for( + protocol.datagram_received_event, support.SHORT_TIMEOUT)) + self.assertEqual(protocol.received, [b'ping']) + + if sys.platform == 'win32': + # Other platforms don't report ICMP errors on an + # unconnected UDP socket. + self.assertEqual(len(protocol.errors), 1) + self.assertIsInstance(protocol.errors[0], ConnectionResetError) + + transport.close() + test_utils.run_briefly(loop) + def test_internal_fds(self): loop = self.create_event_loop() if not isinstance(loop, selector_events.BaseSelectorEventLoop): @@ -1724,6 +2074,48 @@ def reader(data): self.loop.run_until_complete(proto.done) self.assertEqual('CLOSED', proto.state) + @unittest.skipUnless(sys.platform != 'win32', + "Don't support pipes for Windows") + @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo()') + def test_write_named_fifo_unread_data(self): + # gh-145030: on macOS and Solaris, the write end of a named FIFO + # polls as readable while unread data sits in the FIFO, which made + # the transport misinterpret the event as the reader hanging up + # and close itself. + path = os_helper.TESTFN + os.mkfifo(path) + self.assertNotEqual(os.stat(path).st_nlink, 0) + self.addCleanup(os_helper.unlink, path) + rfd = os.open(path, os.O_RDONLY | os.O_NONBLOCK) + self.addCleanup(os.close, rfd) + wfd = os.open(path, os.O_WRONLY | os.O_NONBLOCK) + pipeobj = io.open(wfd, 'wb', 1024) + + proto = MyWritePipeProto(loop=self.loop) + connect = self.loop.connect_write_pipe(lambda: proto, pipeobj) + transport, p = self.loop.run_until_complete(connect) + self.assertIs(p, proto) + self.assertEqual('CONNECTED', proto.state) + + transport.write(b'1') + # Iterate the event loop while the data stays unread in the FIFO; + # the transport must not detect a false disconnection. + for _ in range(10): + test_utils.run_briefly(self.loop) + self.assertEqual('CONNECTED', proto.state) + self.assertFalse(transport.is_closing()) + self.assertEqual(b'1', os.read(rfd, 1024)) + + transport.write(b'2345') + for _ in range(10): + test_utils.run_briefly(self.loop) + self.assertEqual('CONNECTED', proto.state) + self.assertEqual(b'2345', os.read(rfd, 1024)) + + transport.close() + self.loop.run_until_complete(proto.done) + self.assertEqual('CLOSED', proto.state) + @unittest.skipUnless(sys.platform != 'win32', "Don't support pipes for Windows") def test_write_pipe_disconnect_on_close(self): @@ -3172,5 +3564,100 @@ def test_get_loop(self): events.AbstractServer().get_loop() +@unittest.skipIf(sys.platform == 'win32', 'Unix pipe transport semantics') +class UnixPipeObjectSupportTests(unittest.TestCase): + def setUp(self): + super().setUp() + self.loop = asyncio.SelectorEventLoop() + self.addCleanup(self.loop.close) + + def check_accepted(self, connect, pipeobj): + lost = self.loop.create_future() + + class Proto(asyncio.Protocol): + def connection_lost(self, exc): + if not lost.done(): + lost.set_result(exc) + + async def run(): + transport, protocol = await connect(Proto, pipeobj) + self.assertIsInstance(protocol, Proto) + self.assertFalse(pipeobj.closed) + transport.close() + self.assertIsNone(await lost) + + self.loop.run_until_complete(run()) + self.assertTrue(pipeobj.closed) + + def check_rejected(self, connect, pipeobj): + self.addCleanup(pipeobj.close) + with self.assertRaisesRegex(ValueError, 'Pipe transport is'): + self.loop.run_until_complete(connect(asyncio.Protocol, pipeobj)) + + def test_read_pipe(self): + rfd, wfd = os.pipe() + self.addCleanup(os.close, wfd) + self.check_accepted(self.loop.connect_read_pipe, open(rfd, 'rb', 0)) + + def test_write_pipe(self): + rfd, wfd = os.pipe() + self.addCleanup(os.close, rfd) + self.check_accepted(self.loop.connect_write_pipe, open(wfd, 'wb', 0)) + + def test_read_fifo(self): + path = os_helper.TESTFN + os.mkfifo(path) + self.addCleanup(os_helper.unlink, path) + rfd = os.open(path, os.O_RDONLY | os.O_NONBLOCK) + wfd = os.open(path, os.O_WRONLY) + self.addCleanup(os.close, wfd) + self.check_accepted(self.loop.connect_read_pipe, open(rfd, 'rb', 0)) + + def test_write_fifo(self): + path = os_helper.TESTFN + os.mkfifo(path) + self.addCleanup(os_helper.unlink, path) + rfd = os.open(path, os.O_RDONLY | os.O_NONBLOCK) + self.addCleanup(os.close, rfd) + wfd = os.open(path, os.O_WRONLY) + self.check_accepted(self.loop.connect_write_pipe, open(wfd, 'wb', 0)) + + def test_read_socket(self): + rsock, wsock = socket.socketpair() + self.addCleanup(wsock.close) + self.check_accepted(self.loop.connect_read_pipe, + open(rsock.detach(), 'rb', 0)) + + def test_write_socket(self): + rsock, wsock = socket.socketpair() + self.addCleanup(rsock.close) + self.check_accepted(self.loop.connect_write_pipe, + open(wsock.detach(), 'wb', 0)) + + @unittest.skipUnless(hasattr(os, 'openpty'), 'need os.openpty()') + def test_read_character_device(self): + master, slave = os.openpty() + self.addCleanup(os.close, slave) + self.check_accepted(self.loop.connect_read_pipe, open(master, 'rb', 0)) + + @unittest.skipUnless(hasattr(os, 'openpty'), 'need os.openpty()') + def test_write_character_device(self): + master, slave = os.openpty() + self.addCleanup(os.close, master) + self.check_accepted(self.loop.connect_write_pipe, open(slave, 'wb', 0)) + + def test_read_regular_file(self): + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + with open(os_helper.TESTFN, 'wb') as f: + f.write(b'spam') + self.check_rejected(self.loop.connect_read_pipe, + open(os_helper.TESTFN, 'rb', 0)) + + def test_write_regular_file(self): + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + self.check_rejected(self.loop.connect_write_pipe, + open(os_helper.TESTFN, 'wb', 0)) + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_asyncio/test_free_threading.py b/Lib/test/test_asyncio/test_free_threading.py index d874ed00bd7..0e149dadd7f 100644 --- a/Lib/test/test_asyncio/test_free_threading.py +++ b/Lib/test/test_asyncio/test_free_threading.py @@ -165,6 +165,45 @@ async def main(): loop.set_task_factory(self.factory) r.run(main()) + def test_all_tasks_from_other_thread_includes_eager_tasks(self): + # gh-152020: all_tasks() called from another thread used to drop + # eager-started tasks on free-threaded builds. + loop = asyncio.new_event_loop() + + async def wait_forever(): + await asyncio.Event().wait() + + def eager_factory(loop, coro, **kwargs): + return self.factory(loop, coro, eager_start=True, **kwargs) + + async def setup(): + loop.set_task_factory(eager_factory) + eager = loop.create_task(wait_forever(), name="EAGER") + loop.set_task_factory(None) + normal = loop.create_task(wait_forever(), name="NORMAL") + return eager, normal + + async def teardown(): + tasks = [t for t in asyncio.all_tasks() + if t is not asyncio.current_task()] + for t in tasks: + t.cancel() + await asyncio.gather(*tasks, return_exceptions=True) + + thread = threading.Thread(target=loop.run_forever) + thread.start() + try: + held = asyncio.run_coroutine_threadsafe(setup(), loop).result() + names = {t.get_name() for t in asyncio.all_tasks(loop)} + self.assertIn("NORMAL", names) + self.assertIn("EAGER", names) + del held + finally: + asyncio.run_coroutine_threadsafe(teardown(), loop).result() + loop.call_soon_threadsafe(loop.stop) + thread.join() + loop.close() + class TestPyFreeThreading(TestFreeThreading, TestCase): diff --git a/Lib/test/test_asyncio/test_futures.py b/Lib/test/test_asyncio/test_futures.py index 785258a2749..2a2817e44b2 100644 --- a/Lib/test/test_asyncio/test_futures.py +++ b/Lib/test/test_asyncio/test_futures.py @@ -255,6 +255,14 @@ def test_future_cancel_message_setter(self): f.cancel('my message') f._cancel_message = 'my new message' self.assertEqual(f._cancel_message, 'my new message') + f._cancel_message = None + self.assertIsNone(f._cancel_message) + f._cancel_message = 'my new message' + if not isinstance(f, futures._PyFuture): + # The C implementation does not support deletion. + with self.assertRaises(AttributeError): + del f._cancel_message + self.assertEqual(f._cancel_message, 'my new message') # Also check that the value is used for cancel(). with self.assertRaises(asyncio.CancelledError): @@ -413,7 +421,7 @@ def func_repr(func): def test_copy_state(self): from asyncio.futures import _copy_future_state - f = self._new_future(loop=self.loop) + f = concurrent.futures.Future() f.set_result(10) newf = self._new_future(loop=self.loop) @@ -421,7 +429,7 @@ def test_copy_state(self): self.assertTrue(newf.done()) self.assertEqual(newf.result(), 10) - f_exception = self._new_future(loop=self.loop) + f_exception = concurrent.futures.Future() f_exception.set_exception(RuntimeError()) newf_exception = self._new_future(loop=self.loop) @@ -429,7 +437,7 @@ def test_copy_state(self): self.assertTrue(newf_exception.done()) self.assertRaises(RuntimeError, newf_exception.result) - f_cancelled = self._new_future(loop=self.loop) + f_cancelled = concurrent.futures.Future() f_cancelled.cancel() newf_cancelled = self._new_future(loop=self.loop) @@ -441,7 +449,7 @@ def test_copy_state(self): except BaseException as e: f_exc = e - f_conexc = self._new_future(loop=self.loop) + f_conexc = concurrent.futures.Future() f_conexc.set_exception(f_exc) newf_conexc = self._new_future(loop=self.loop) @@ -454,6 +462,56 @@ def test_copy_state(self): newf_tb = ''.join(traceback.format_tb(newf_exc.__traceback__)) self.assertEqual(newf_tb.count('raise concurrent.futures.InvalidStateError'), 1) + def test_copy_state_from_concurrent_futures(self): + """Test _copy_future_state from concurrent.futures.Future. + + This tests the optimized path using _get_snapshot when available. + """ + from asyncio.futures import _copy_future_state + + # Test with a result + f_concurrent = concurrent.futures.Future() + f_concurrent.set_result(42) + f_asyncio = self._new_future(loop=self.loop) + _copy_future_state(f_concurrent, f_asyncio) + self.assertTrue(f_asyncio.done()) + self.assertEqual(f_asyncio.result(), 42) + + # Test with an exception + f_concurrent_exc = concurrent.futures.Future() + f_concurrent_exc.set_exception(ValueError("test exception")) + f_asyncio_exc = self._new_future(loop=self.loop) + _copy_future_state(f_concurrent_exc, f_asyncio_exc) + self.assertTrue(f_asyncio_exc.done()) + with self.assertRaises(ValueError) as cm: + f_asyncio_exc.result() + self.assertEqual(str(cm.exception), "test exception") + + # Test with cancelled state + f_concurrent_cancelled = concurrent.futures.Future() + f_concurrent_cancelled.cancel() + f_asyncio_cancelled = self._new_future(loop=self.loop) + _copy_future_state(f_concurrent_cancelled, f_asyncio_cancelled) + self.assertTrue(f_asyncio_cancelled.cancelled()) + + # Test that destination already cancelled prevents copy + f_concurrent_result = concurrent.futures.Future() + f_concurrent_result.set_result(10) + f_asyncio_precancelled = self._new_future(loop=self.loop) + f_asyncio_precancelled.cancel() + _copy_future_state(f_concurrent_result, f_asyncio_precancelled) + self.assertTrue(f_asyncio_precancelled.cancelled()) + + # Test exception type conversion + f_concurrent_invalid = concurrent.futures.Future() + f_concurrent_invalid.set_exception(concurrent.futures.InvalidStateError("invalid")) + f_asyncio_invalid = self._new_future(loop=self.loop) + _copy_future_state(f_concurrent_invalid, f_asyncio_invalid) + self.assertTrue(f_asyncio_invalid.done()) + with self.assertRaises(asyncio.exceptions.InvalidStateError) as cm: + f_asyncio_invalid.result() + self.assertEqual(str(cm.exception), "invalid") + def test_iter(self): fut = self._new_future(loop=self.loop) @@ -700,6 +758,10 @@ def test_future_cancelled_exception_refcycles(self): self.assertIsNotNone(exc) self.assertListEqual(gc.get_referrers(exc), []) + def test_future_disallow_multiple_initialization(self): + f = self._new_future(loop=self.loop) + with self.assertRaises(RuntimeError, msg="is already initialized"): + f.__init__(loop=self.loop) @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') @@ -1041,33 +1103,6 @@ def __getattribute__(self, name): fut.add_done_callback(fut_callback_0) self.assertRaises(ReachableCode, fut.set_result, "boom") - def test_use_after_free_on_fut_context_0_with_evil__getattribute__(self): - # see: https://github.com/python/cpython/issues/125984 - - class EvilEventLoop(SimpleEvilEventLoop): - def call_soon(self, *args, **kwargs): - super().call_soon(*args, **kwargs) - raise ReachableCode - - def __getattribute__(self, name): - if name == 'call_soon': - # resets the future's event loop - fut.__init__(loop=SimpleEvilEventLoop()) - return object.__getattribute__(self, name) - - evil_loop = EvilEventLoop() - with mock.patch.object(self, 'loop', evil_loop): - fut = self._new_future() - self.assertIs(fut.get_loop(), evil_loop) - - fut_callback_0 = mock.Mock() - fut_context_0 = mock.Mock() - fut.add_done_callback(fut_callback_0, context=fut_context_0) - del fut_context_0 - del fut_callback_0 - self.assertRaises(ReachableCode, fut.set_result, "boom") - - @unittest.skipUnless(hasattr(futures, '_CFuture'), 'requires the C _asyncio module') class CFutureDoneCallbackTests(BaseFutureDoneCallbackTests, diff --git a/Lib/test/test_asyncio/test_graph.py b/Lib/test/test_asyncio/test_graph.py index 2f22fbccba4..ba02263dff0 100644 --- a/Lib/test/test_asyncio/test_graph.py +++ b/Lib/test/test_asyncio/test_graph.py @@ -146,6 +146,33 @@ async def main(): 'async generator CallStackTestBase.test_stack_async_gen..gen()', stack_for_gen_nested_call[1]) + async def test_stack_wait_for_non_positive_timeout(self): + # gh-157058: wait_for(fut, 0) must still record the waiter + cleanup = asyncio.Future() + + async def worker(): + try: + await asyncio.Future() + finally: + await cleanup + + async def probe(t): + await asyncio.wait_for(t, 0) + + t = asyncio.ensure_future(worker()) + p = asyncio.create_task(probe(t), name='probe') + for _ in range(5): + await asyncio.sleep(0) + + stack = capture_test_stack(fut=t) + + cleanup.set_result(None) + await asyncio.gather(p, t, return_exceptions=True) + + self.assertEqual(stack[0][2], [ + ['T', ['a _cancel_and_wait', 'a wait_for', 'a probe'], []], + ]) + async def test_stack_gather(self): stack_for_deep = None @@ -175,6 +202,29 @@ async def main(): ] ]) + async def test_stack_gather_survivor(self): + # gh-157213: a child that outlives gather() must not be shown as awaited + + async def fail(): + raise ValueError + + async def survivor(): + await asyncio.Future() + + t = asyncio.create_task(survivor(), name='survivor') + with self.assertRaises(ValueError): + await asyncio.gather(t, fail()) + + self.assertEqual(capture_test_stack(fut=t)[0], [ + 'T', + ['a survivor'], + [] + ]) + + t.cancel() + with self.assertRaises(asyncio.CancelledError): + await t + async def test_stack_shield(self): stack_for_shield = None @@ -271,6 +321,68 @@ async def main(t1, t2): ] ]) + async def test_stack_as_completed(self): + # gh-156523: as_completed() must record the awaiting task + stack_for_inner = None + + async def inner(): + await asyncio.sleep(0) + nonlocal stack_for_inner + stack_for_inner = capture_test_stack() + + async def main(t): + for f in asyncio.as_completed([t]): + await f + + t = asyncio.create_task(inner(), name='inner') + await main(t) + self.assertFalse(t._asyncio_awaited_by) + + self.assertEqual(stack_for_inner[0], [ + 'T', + ['s capture_test_stack', 'a inner'], + [ + ['T', + ['a get', 'a _wait_for_one', 'a main', + 'a test_stack_as_completed'], + [] + ] + ] + ]) + + async def test_stack_as_completed_timeout(self): + # gh-156523: the awaiting task must be dropped when as_completed() times out + stack_for_inner = None + + async def inner(): + nonlocal stack_for_inner + stack_for_inner = capture_test_stack() + await asyncio.sleep(3600) + + async def main(t): + with self.assertRaises(TimeoutError): + for f in asyncio.as_completed([t], timeout=0.01): + await f + + t = asyncio.create_task(inner(), name='inner') + await main(t) + self.assertFalse(t._asyncio_awaited_by) + t.cancel() + with self.assertRaises(asyncio.CancelledError): + await t + + self.assertEqual(stack_for_inner[0], [ + 'T', + ['s capture_test_stack', 'a inner'], + [ + ['T', + ['a get', 'a _wait_for_one', 'a main', + 'a test_stack_as_completed_timeout'], + [] + ] + ] + ]) + async def test_stack_task(self): stack_for_inner = None @@ -345,6 +457,44 @@ async def main(): self.assertTrue(stack_for_fut[1].startswith('* Future(id=')) + async def test_call_graph_finished_task(self): + # gh-156408: the call graph must not record a finished coroutine's None frame + async def boom(): + raise ValueError + + done = asyncio.create_task(asyncio.sleep(0), name='done') + failed = asyncio.create_task(boom(), name='failed') + cancelled = asyncio.create_task(asyncio.Event().wait(), name='cancelled') + cancelled.cancel() + await asyncio.gather(done, failed, cancelled, return_exceptions=True) + + for task in (done, failed, cancelled): + with self.subTest(task=task.get_name()): + buf = io.StringIO() + asyncio.print_call_graph(task, file=buf) + self.assertEqual(asyncio.capture_call_graph(task).call_stack, ()) + self.assertIn(f"name={task.get_name()!r}", buf.getvalue()) + + async def test_capture_call_graph_generator_keeps_caller_frames(self): + # gh-156988: sync gen should not clear the call chain + stack = None + + def gen(): + nonlocal stack + graph = asyncio.capture_call_graph() + stack = [entry.frame.f_code.co_name for entry in graph.call_stack] + yield + + def middle(): + for _ in gen(): + pass + + async def main(): + middle() + + await main() + self.assertEqual(stack[:3], ['gen', 'middle', 'main']) + @unittest.skipIf( not hasattr(asyncio.futures, "_c_future_add_to_awaited_by"), diff --git a/Lib/test/test_asyncio/test_selector_events.py b/Lib/test/test_asyncio/test_selector_events.py index 4bb5d4fb816..27b3af888b7 100644 --- a/Lib/test/test_asyncio/test_selector_events.py +++ b/Lib/test/test_asyncio/test_selector_events.py @@ -1122,6 +1122,49 @@ def _resume_writing(): self.assertEqual(transport.get_write_buffer_size(), 0) self.assertTrue(self.protocol.connection_lost.called) + def test_write_ready_resume_writing_closes(self): + # gh-156512: closing from resume_writing() must not lose the connection twice + self.sock.send.return_value = 2 + + def _resume_writing(): + transport.close() + + self.protocol.resume_writing.side_effect = _resume_writing + self.loop.call_exception_handler = mock.Mock() + + transport = self.socket_transport() + transport.set_write_buffer_limits(high=1, low=0) + transport.write(b'data') + + self.loop.writers[7]._run() + test_utils.run_briefly(self.loop) + + self.assertEqual(self.protocol.connection_lost.call_count, 1) + self.loop.call_exception_handler.assert_not_called() + + @unittest.skipUnless(selector_events._HAS_SENDMSG, 'no sendmsg') + def test_write_sendmsg_resume_writing_closes(self): + # gh-156512: same as above, for the sendmsg write path + self.sock.send.return_value = 2 + self.sock.sendmsg.return_value = 2 + + def _resume_writing(): + transport.close() + + self.protocol.resume_writing.side_effect = _resume_writing + self.loop.call_exception_handler = mock.Mock() + + transport = self.socket_transport(sendmsg=True) + transport.set_write_buffer_limits(high=1, low=0) + transport.write(b'data') + + self.loop.writers[7]._run() + test_utils.run_briefly(self.loop) + + self.assertEqual(self.protocol.connection_lost.call_count, 1) + self.loop.call_exception_handler.assert_not_called() + + class SelectorSocketTransportBufferedProtocolTests(test_utils.TestCase): def setUp(self): diff --git a/Lib/test/test_asyncio/test_sendfile.py b/Lib/test/test_asyncio/test_sendfile.py index a95e7d086ff..e4aaeaa9adc 100644 --- a/Lib/test/test_asyncio/test_sendfile.py +++ b/Lib/test/test_asyncio/test_sendfile.py @@ -98,7 +98,12 @@ class SendfileBase: # 64 KiB page configuration. DATA = b"x" * (1024 * 17 * 64 + 1) # Reduce socket buffer size to test on relative small data sets. - BUF_SIZE = 4 * 1024 # 4 KiB + if sys.platform.startswith('dragonfly'): + # A smaller buffer makes every window update wait 100 ms for the + # delayed ACK timer. + BUF_SIZE = 32 * 1024 # 32 KiB + else: + BUF_SIZE = 4 * 1024 # 4 KiB def create_event_loop(self): raise NotImplementedError diff --git a/Lib/test/test_asyncio/test_server.py b/Lib/test/test_asyncio/test_server.py index 5bd0f7e2af4..581ea47d2de 100644 --- a/Lib/test/test_asyncio/test_server.py +++ b/Lib/test/test_asyncio/test_server.py @@ -266,6 +266,38 @@ async def serve(rd, wr): await asyncio.sleep(0) self.assertTrue(task.done()) + async def test_close_with_hanging_client(self): + # Synchronize server cancellation only after the socket connection is + # accepted and this event is set + conn_event = asyncio.Event() + class Proto(asyncio.Protocol): + def connection_made(self, transport): + conn_event.set() + + loop = asyncio.get_running_loop() + srv = await loop.create_server(Proto, socket_helper.HOSTv4, 0) + + # Start the server + serve_forever_task = asyncio.create_task(srv.serve_forever()) + await asyncio.sleep(0) + + # Create a connection to server + addr = srv.sockets[0].getsockname() + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(addr) + self.addCleanup(sock.close) + + # Send a CancelledError into the server to emulate a Ctrl+C + # KeyboardInterrupt whilst the server is handling a hanging client + await conn_event.wait() + serve_forever_task.cancel() + + # Ensure the client is closed within a timeout + async with asyncio.timeout(0.5): + await srv.wait_closed() + + self.assertFalse(srv.is_serving()) + # Test the various corner cases of Unix server socket removal class UnixServerCleanupTests(unittest.IsolatedAsyncioTestCase): diff --git a/Lib/test/test_asyncio/test_server_context.py b/Lib/test/test_asyncio/test_server_context.py new file mode 100644 index 00000000000..3f15654a1af --- /dev/null +++ b/Lib/test/test_asyncio/test_server_context.py @@ -0,0 +1,314 @@ +import asyncio +import contextvars +import unittest +import sys + +from unittest import TestCase + +try: + import ssl +except ImportError: + ssl = None + +from test.test_asyncio import utils as test_utils + +def tearDownModule(): + asyncio.events._set_event_loop_policy(None) + +class ServerContextvarsTestCase: + loop_factory = None # To be defined in subclasses + server_ssl_context = None # To be defined in subclasses for SSL tests + client_ssl_context = None # To be defined in subclasses for SSL tests + + def run_coro(self, coro): + return asyncio.run(coro, loop_factory=self.loop_factory) + + def test_start_server1(self): + # Test that asyncio.start_server captures the context at the time of server creation + async def test(): + var = contextvars.ContextVar("var", default="default") + + async def handle_client(reader, writer): + value = var.get() + writer.write(value.encode()) + await writer.drain() + writer.close() + + server = await asyncio.start_server(handle_client, '127.0.0.1', 0, + ssl=self.server_ssl_context) + # change the value + var.set("after_server") + + async def client(addr): + reader, writer = await asyncio.open_connection(*addr, + ssl=self.client_ssl_context) + data = await reader.read(100) + writer.close() + await writer.wait_closed() + return data.decode() + + async with server: + addr = server.sockets[0].getsockname() + self.assertEqual(await client(addr), "default") + + self.assertEqual(var.get(), "after_server") + + self.run_coro(test()) + + def test_start_server2(self): + # Test that mutations to the context in one handler don't affect other handlers or the server's context + async def test(): + var = contextvars.ContextVar("var", default="default") + + async def handle_client(reader, writer): + value = var.get() + writer.write(value.encode()) + var.set("in_handler") + await writer.drain() + writer.close() + + server = await asyncio.start_server(handle_client, '127.0.0.1', 0, + ssl=self.server_ssl_context) + var.set("after_server") + + async def client(addr): + reader, writer = await asyncio.open_connection(*addr, + ssl=self.client_ssl_context) + data = await reader.read(100) + writer.close() + await writer.wait_closed() + return data.decode() + + async with server: + addr = server.sockets[0].getsockname() + self.assertEqual(await client(addr), "default") + self.assertEqual(await client(addr), "default") + self.assertEqual(await client(addr), "default") + + self.assertEqual(var.get(), "after_server") + + self.run_coro(test()) + + def test_start_server3(self): + # Test that mutations to context in concurrent handlers don't affect each other or the server's context + async def test(): + var = contextvars.ContextVar("var", default="default") + var.set("before_server") + + async def handle_client(reader, writer): + writer.write(var.get().encode()) + await writer.drain() + writer.close() + + server = await asyncio.start_server(handle_client, '127.0.0.1', 0, + ssl=self.server_ssl_context) + var.set("after_server") + + async def client(addr): + reader, writer = await asyncio.open_connection(*addr, + ssl=self.client_ssl_context) + data = await reader.read(100) + self.assertEqual(data.decode(), "before_server") + writer.close() + await writer.wait_closed() + + async with server: + addr = server.sockets[0].getsockname() + async with asyncio.TaskGroup() as tg: + for _ in range(100): + tg.create_task(client(addr)) + + self.assertEqual(var.get(), "after_server") + + self.run_coro(test()) + + def test_create_server1(self): + # Test that loop.create_server captures the context at the time of server creation + # and that mutations to the context in protocol callbacks don't affect the server's context + async def test(): + var = contextvars.ContextVar("var", default="default") + + class EchoProtocol(asyncio.Protocol): + def connection_made(self, transport): + self.transport = transport + value = var.get() + var.set("in_handler") + self.transport.write(value.encode()) + self.transport.close() + + server = await asyncio.get_running_loop().create_server( + lambda: EchoProtocol(), '127.0.0.1', 0, + ssl=self.server_ssl_context) + var.set("after_server") + + async def client(addr): + reader, writer = await asyncio.open_connection(*addr, + ssl=self.client_ssl_context) + data = await reader.read(100) + self.assertEqual(data.decode(), "default") + writer.close() + await writer.wait_closed() + + async with server: + addr = server.sockets[0].getsockname() + await client(addr) + + self.assertEqual(var.get(), "after_server") + + self.run_coro(test()) + + def test_create_server2(self): + # Test that mutations to context in one protocol instance don't affect other instances or the server's context + async def test(): + var = contextvars.ContextVar("var", default="default") + + class EchoProtocol(asyncio.Protocol): + def __init__(self): + super().__init__() + assert var.get() == "default", var.get() + def connection_made(self, transport): + self.transport = transport + value = var.get() + var.set("in_handler") + self.transport.write(value.encode()) + self.transport.close() + + server = await asyncio.get_running_loop().create_server( + lambda: EchoProtocol(), '127.0.0.1', 0, + ssl=self.server_ssl_context) + + var.set("after_server") + + async def client(addr, expected): + reader, writer = await asyncio.open_connection(*addr, + ssl=self.client_ssl_context) + data = await reader.read(100) + self.assertEqual(data.decode(), expected) + writer.close() + await writer.wait_closed() + + async with server: + addr = server.sockets[0].getsockname() + await client(addr, "default") + await client(addr, "default") + + self.assertEqual(var.get(), "after_server") + + self.run_coro(test()) + + def test_gh140947(self): + # See https://github.com/python/cpython/issues/140947 + + cvar1 = contextvars.ContextVar("cvar1") + cvar2 = contextvars.ContextVar("cvar2") + cvar3 = contextvars.ContextVar("cvar3") + results = {} + is_ssl = self.server_ssl_context is not None + + def capture_context(meth): + result = [] + for k,v in contextvars.copy_context().items(): + if k.name.startswith("cvar"): + result.append((k.name, v)) + results[meth] = sorted(result) + + class DemoProtocol(asyncio.Protocol): + def __init__(self, on_conn_lost): + self.transport = None + self.on_conn_lost = on_conn_lost + self.tasks = set() + + def connection_made(self, transport): + capture_context("connection_made") + self.transport = transport + + def data_received(self, data): + capture_context("data_received") + + task = asyncio.create_task(self.asgi()) + self.tasks.add(task) + task.add_done_callback(self.tasks.discard) + + self.transport.pause_reading() + + def connection_lost(self, exc): + capture_context("connection_lost") + if not self.on_conn_lost.done(): + self.on_conn_lost.set_result(True) + + async def asgi(self): + capture_context("asgi start") + cvar1.set(True) + # make sure that we only resume after the pause + # otherwise the resume does nothing + if is_ssl: + while not self.transport._ssl_protocol._app_reading_paused: + await asyncio.sleep(0.01) + else: + while not self.transport._paused: + await asyncio.sleep(0.01) + cvar2.set(True) + self.transport.resume_reading() + cvar3.set(True) + capture_context("asgi end") + + async def main(): + loop = asyncio.get_running_loop() + on_conn_lost = loop.create_future() + + server = await loop.create_server( + lambda: DemoProtocol(on_conn_lost), '127.0.0.1', 0, + ssl=self.server_ssl_context) + async with server: + addr = server.sockets[0].getsockname() + reader, writer = await asyncio.open_connection(*addr, + ssl=self.client_ssl_context) + writer.write(b"anything") + await writer.drain() + writer.close() + await writer.wait_closed() + await on_conn_lost + + self.run_coro(main()) + self.assertDictEqual(results, { + "connection_made": [], + "data_received": [], + "asgi start": [], + "asgi end": [("cvar1", True), ("cvar2", True), ("cvar3", True)], + "connection_lost": [], + }) + + +class AsyncioEventLoopTests(TestCase, ServerContextvarsTestCase): + loop_factory = staticmethod(asyncio.new_event_loop) + +@unittest.skipUnless(ssl, "SSL not available") +class AsyncioEventLoopSSLTests(AsyncioEventLoopTests): + def setUp(self): + super().setUp() + self.server_ssl_context = test_utils.simple_server_sslcontext() + self.client_ssl_context = test_utils.simple_client_sslcontext() + +if sys.platform == "win32": + class AsyncioProactorEventLoopTests(TestCase, ServerContextvarsTestCase): + loop_factory = asyncio.ProactorEventLoop + + class AsyncioSelectorEventLoopTests(TestCase, ServerContextvarsTestCase): + loop_factory = asyncio.SelectorEventLoop + + @unittest.skipUnless(ssl, "SSL not available") + class AsyncioProactorEventLoopSSLTests(AsyncioProactorEventLoopTests): + def setUp(self): + super().setUp() + self.server_ssl_context = test_utils.simple_server_sslcontext() + self.client_ssl_context = test_utils.simple_client_sslcontext() + + @unittest.skipUnless(ssl, "SSL not available") + class AsyncioSelectorEventLoopSSLTests(AsyncioSelectorEventLoopTests): + def setUp(self): + super().setUp() + self.server_ssl_context = test_utils.simple_server_sslcontext() + self.client_ssl_context = test_utils.simple_client_sslcontext() + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_asyncio/test_sock_lowlevel.py b/Lib/test/test_asyncio/test_sock_lowlevel.py index a34e15b4d89..6ce029008f1 100644 --- a/Lib/test/test_asyncio/test_sock_lowlevel.py +++ b/Lib/test/test_asyncio/test_sock_lowlevel.py @@ -1,5 +1,6 @@ import socket import asyncio +import select import sys import unittest @@ -257,6 +258,38 @@ async def _basetest_sock_connect_racing(self, listener, sock): self.skipTest(skip_reason) + async def _basetest_sock_accept_racing(self, listener, sock): + # gh-153761: cancelling sock_accept() must not let a scheduled + # _sock_accept run on the cancelled future. + listener.setblocking(False) + listener.bind(('127.0.0.1', 0)) + listener.listen(1) + addr = listener.getsockname() + + errors = [] + self.loop.set_exception_handler(lambda loop, ctx: errors.append(ctx)) + task = asyncio.create_task(self.loop.sock_accept(listener)) + await asyncio.sleep(0) + + sock.connect(addr) + select.select([listener], [], [], support.SHORT_TIMEOUT) + + self.loop.call_soon(task.cancel) + await asyncio.sleep(0) + await asyncio.sleep(0) + + with self.assertRaises(asyncio.CancelledError): + await task + self.assertEqual(errors, []) + + # The pending connection must survive + conn, conn_addr = await self.loop.sock_accept(listener) + with conn: + self.assertEqual(conn_addr, sock.getsockname()) + sock.setblocking(False) + await self.loop.sock_sendall(conn, b'ping') + self.assertEqual(await self.loop.sock_recv(sock, 4), b'ping') + def test_sock_client_racing(self): with test_utils.run_test_server() as httpd: sock = socket.socket() @@ -280,6 +313,16 @@ def test_sock_client_connect_racing(self): self.loop.run_until_complete(asyncio.wait_for( self._basetest_sock_connect_racing(listener, sock), 10)) + def test_sock_accept_racing(self): + if sys.platform == 'win32': + if isinstance(self.loop, asyncio.ProactorEventLoop): + raise unittest.SkipTest('Not relevant to ProactorEventLoop') + listener = socket.socket() + sock = socket.socket() + with listener, sock: + self.loop.run_until_complete(asyncio.wait_for( + self._basetest_sock_accept_racing(listener, sock), 10)) + async def _basetest_huge_content(self, address): sock = socket.socket() sock.setblocking(False) @@ -570,19 +613,10 @@ def test_create_connection_sock(self): if sys.platform == 'win32': - class SelectEventLoopTests(BaseSockTestsMixin, - test_utils.TestCase): - - def create_event_loop(self): - return asyncio.SelectorEventLoop() - - - class ProactorEventLoopTests(BaseSockTestsMixin, - test_utils.TestCase): - - def create_event_loop(self): - return asyncio.ProactorEventLoop() - + class _DatagramSendToNonListeningAddressMixin: + # Shared by SelectEventLoopTests and ProactorEventLoopTests so that + # sock_recvfrom()/sock_recvfrom_into() behave identically on both + # event loop implementations. async def _basetest_datagram_send_to_non_listening_address(self, recvfrom): @@ -591,8 +625,9 @@ async def _basetest_datagram_send_to_non_listening_address(self, # https://github.com/python/cpython/issues/88906 # https://bugs.python.org/issue47071 # https://bugs.python.org/issue44743 - # The Proactor event loop would fail to receive datagram messages - # after sending a message to an address that wasn't listening. + # Sending a datagram to an address that isn't listening can + # surface as a ConnectionResetError on a later receive; the + # socket must still be usable afterwards. def create_socket(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -627,7 +662,8 @@ def create_socket(): # this should send to an address that isn't listening await self.loop.sock_sendto(socket_1, b'c', addr_3) - self.assertEqual(await socket_1_recv_task, b'') + with self.assertRaises(ConnectionResetError): + await socket_1_recv_task socket_1_recv_task = self.loop.create_task(recvfrom(socket_1)) await asyncio.sleep(0) @@ -663,9 +699,21 @@ async def recvfrom_into(socket): self._basetest_datagram_send_to_non_listening_address( recvfrom_into)) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON; AssertionError: ValueError not raised") - def test_recvfrom_into_wrong_size(self): - return super().test_recvfrom_into_wrong_size() + + class SelectEventLoopTests(_DatagramSendToNonListeningAddressMixin, + BaseSockTestsMixin, + test_utils.TestCase): + + def create_event_loop(self): + return asyncio.SelectorEventLoop() + + + class ProactorEventLoopTests(_DatagramSendToNonListeningAddressMixin, + BaseSockTestsMixin, + test_utils.TestCase): + + def create_event_loop(self): + return asyncio.ProactorEventLoop() else: import selectors diff --git a/Lib/test/test_asyncio/test_ssl.py b/Lib/test/test_asyncio/test_ssl.py index ca15fc3bdd4..e97d7581f9e 100644 --- a/Lib/test/test_asyncio/test_ssl.py +++ b/Lib/test/test_asyncio/test_ssl.py @@ -1544,6 +1544,9 @@ async def client(addr): # This triggers bug gh-115514, also tested using mocks in # test.test_asyncio.test_selector_events.SelectorSocketTransportTests.test_write_buffer_after_close socket_transport = writer.transport._ssl_protocol._transport + # connection_lost may have already cleared _transport. + if socket_transport is None: + return class SocketWrapper: def __init__(self, sock) -> None: @@ -1736,6 +1739,74 @@ async def client(addr): with self.tcp_server(server) as srv: loop.run_until_complete(client(srv.addr)) + def test_shutdown_timeout_after_eof_from_not_reading_peer(self): + # ssl_shutdown_timeout also applies when the peer has sent EOF, + # before or after close(), but does not read what is still queued. + loop = self.loop + filled = threading.Event() + done = threading.Event() + + def server(sock): + sslctx = self._create_server_ssl_context( + test_utils.ONLYCERT, + test_utils.ONLYKEY + ) + sock = sslctx.wrap_socket(sock, server_side=True) + filled.wait(support.SHORT_TIMEOUT) + # sending EOF here, and never reading + sock.shutdown(socket.SHUT_WR) + done.wait(support.SHORT_TIMEOUT) + sock.close() + + class Protocol(asyncio.Protocol): + def __init__(self): + self.fut = asyncio.Future(loop=loop) + self.paused = False + + def pause_writing(self): + self.paused = True + + def resume_writing(self): + self.paused = False + + def connection_lost(self, exc): + if not self.fut.done(): + self.fut.set_result(exc) + + async def client(addr, close): + ctx = self._create_client_ssl_context() + tr, pr = await loop.create_connection( + Protocol, *addr, ssl=ctx, + ssl_shutdown_timeout=0.1) + try: + # Write until the transport cannot pass any more on to the + # peer; how much the kernel accepts varies by platform. + chunk = bytes(support.SOCK_MAX_SIZE) + for _ in range(16): + if pr.paused: + break + tr.write(chunk) + await asyncio.sleep(0) + else: + self.fail('the transport never paused writing') + if close: + tr.close() + filled.set() + async with asyncio.timeout(support.SHORT_TIMEOUT): + exc = await pr.fut + finally: + filled.set() + done.set() + tr.abort() + self.assertIsInstance(exc, TimeoutError) + + for close in (True, False): + with self.subTest(close_before_eof=close): + filled.clear() + done.clear() + with self.tcp_server(server) as srv: + loop.run_until_complete(client(srv.addr, close)) + ############################################################################### # Socket Testing Utilities diff --git a/Lib/test/test_asyncio/test_sslproto.py b/Lib/test/test_asyncio/test_sslproto.py index 3e304c16642..851dc6e1276 100644 --- a/Lib/test/test_asyncio/test_sslproto.py +++ b/Lib/test/test_asyncio/test_sslproto.py @@ -70,6 +70,50 @@ def test_handshake_timeout_negative(self): sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter, ssl_handshake_timeout=-10) + def test_check_hostname_accepts_server_hostname(self): + # Supplying a server_hostname succeeds with check_hostname enabled. + sslcontext = test_utils.simple_client_sslcontext(disable_verify=False) + sslcontext.check_hostname = True + app_proto = mock.Mock() + waiter = mock.Mock() + + # No ValueError is raised from SSLProtocol with 'server_hostname'. + ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter, + server_hostname='example.org') + self.addCleanup(ssl_proto._app_transport.close) + + @support.subTests("server_hostname", [None, '']) + def test_check_hostname_requires_server_hostname(self, server_hostname): + # A caller-supplied context asking for hostname checking used to be + # taken through wrap_bio() with no name to check against, verifying + # the certificate chain but never the peer's identity. + # loop.start_tls() defaults server_hostname to None, and + # loop.create_connection() turns server_hostname='' into None here, + # so both reached that state. + sslcontext = test_utils.simple_client_sslcontext(disable_verify=False) + sslcontext.check_hostname = True + app_proto = mock.Mock() + waiter = mock.Mock() + + # Supplying an empty server_hostname fails with check_hostname enabled. + with self.assertRaisesRegex( + ValueError, + 'check_hostname requires server_hostname'): + sslproto.SSLProtocol(self.loop, app_proto, sslcontext, + waiter, + server_hostname=server_hostname) + + # Disabling check_hostname allows for an empty or unset server_hostname. + sslcontext.check_hostname = False + + ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, waiter) + self.addCleanup(ssl_proto._app_transport.close) + + ssl_proto = sslproto.SSLProtocol(self.loop, app_proto, sslcontext, + waiter, + server_hostname=server_hostname) + self.addCleanup(ssl_proto._app_transport.close) + def test_eof_received_waiter(self): waiter = self.loop.create_future() ssl_proto = self.ssl_protocol(waiter=waiter) @@ -780,6 +824,68 @@ async def client(addr): with self.assertRaises(ssl.SSLCertVerificationError): self.loop.run_until_complete(client(srv.addr)) + def test_create_connection_ssl_failed_certificate_no_cycles(self): + # gh-159049 + sslctx = test_utils.simple_server_sslcontext() + client_sslctx = test_utils.simple_client_sslcontext( + disable_verify=False) + transports = [] + + def server(sock): + try: + sock.start_tls(sslctx, server_side=True) + except OSError: + pass + + connection_made = sslproto.SSLProtocol.connection_made + + def remember_transport(proto, tr): + transports.append(weakref.ref(tr)) + connection_made(proto, tr) + + async def conn(addr): + try: + await self.loop.create_connection( + asyncio.Protocol, *addr, + ssl=client_sslctx, server_hostname='') + except ssl.SSLCertVerificationError: + pass + + support.gc_collect() + with (self.tcp_server(server) as srv, support.disable_gc(), + mock.patch.object(sslproto.SSLProtocol, 'connection_made', + remember_transport)): + self.loop.run_until_complete(conn(srv.addr)) + self.assertEqual([tr() for tr in transports], [None]) + + def test_start_tls_failed_certificate_no_cycles(self): + # gh-159049 + sslctx = test_utils.simple_server_sslcontext() + client_sslctx = test_utils.simple_client_sslcontext( + disable_verify=False) + transports = [] + + def server(sock): + try: + sock.start_tls(sslctx, server_side=True) + except OSError: + pass + + async def client(addr): + tr, proto = await self.loop.create_connection( + asyncio.Protocol, *addr) + transports.append(weakref.ref(tr)) + try: + await self.loop.start_tls( + tr, proto, client_sslctx, server_hostname='') + except ssl.SSLCertVerificationError: + pass + + support.gc_collect() + with self.tcp_server(server) as srv, support.disable_gc(): + self.loop.run_until_complete(client(srv.addr)) + self.assertEqual([tr() for tr in transports], [None]) + def test_start_tls_client_corrupted_ssl(self): self.loop.set_exception_handler(lambda loop, ctx: None) diff --git a/Lib/test/test_asyncio/test_streams.py b/Lib/test/test_asyncio/test_streams.py index cae8c7c6f7c..f4bcdb5eda1 100644 --- a/Lib/test/test_asyncio/test_streams.py +++ b/Lib/test/test_asyncio/test_streams.py @@ -861,6 +861,34 @@ async def run_test(): self.loop.run_until_complete(run_test()) self.assertEqual(messages, []) + def test_streamwriter_start_tls_updates_reader_transport(self): + reader = asyncio.StreamReader(loop=self.loop) + protocol = asyncio.StreamReaderProtocol(reader, loop=self.loop) + old_transport = mock.Mock() + old_transport.get_extra_info.return_value = None + old_transport.is_closing.return_value = False + protocol.connection_made(old_transport) + + writer = asyncio.StreamWriter(old_transport, protocol, reader, self.loop) + + ssl_context = mock.sentinel.ssl_context + new_transport = mock.Mock() + new_transport.get_extra_info.return_value = ssl_context + self.loop.start_tls = mock.AsyncMock(return_value=new_transport) + + self.loop.run_until_complete(writer.start_tls(ssl_context)) + + self.loop.start_tls.assert_awaited_once_with( + old_transport, protocol, ssl_context, + server_side=False, server_hostname=None, + ssl_handshake_timeout=None, + ssl_shutdown_timeout=None, + ) + self.assertIs(writer.transport, new_transport) + self.assertIs(protocol._transport, new_transport) + self.assertIs(reader._transport, new_transport) + self.assertTrue(protocol._over_ssl) + def test_streamreader_constructor_without_loop(self): with self.assertRaisesRegex(RuntimeError, 'no current event loop'): asyncio.StreamReader() @@ -1239,6 +1267,38 @@ async def handle_echo(reader, writer): messages = self._basetest_unhandled_exceptions(handle_echo) self.assertEqual(messages, []) + def test_unhandled_exception_sync_callback(self): + # An exception raised by a plain-function client_connected_cb is + # reported like the coroutine case and the transport is closed. + port = socket_helper.find_unused_port() + + messages = [] + self.loop.set_exception_handler(lambda loop, ctx: messages.append(ctx)) + + async def client(): + rd, wr = await asyncio.open_connection('localhost', port) + async with asyncio.timeout(60): + data = await rd.read() + self.assertEqual(data, b'') # the server closed the connection + wr.close() + await wr.wait_closed() + + async def main(): + def handle_echo(reader, writer): + raise Exception('test') + + server = await asyncio.start_server( + handle_echo, 'localhost', port) + await server.start_serving() + await client() + server.close() + await server.wait_closed() + + self.loop.run_until_complete(main()) + + self.assertEqual(messages[0]['message'], + 'Unhandled exception in client_connected_cb') + def test_open_connection_happy_eyeball_refcycles(self): port = socket_helper.find_unused_port() async def main(): diff --git a/Lib/test/test_asyncio/test_subprocess.py b/Lib/test/test_asyncio/test_subprocess.py index 9dd596bbf27..cdfaf99ad24 100644 --- a/Lib/test/test_asyncio/test_subprocess.py +++ b/Lib/test/test_asyncio/test_subprocess.py @@ -2,6 +2,7 @@ import signal import sys import textwrap +import threading import unittest import warnings from unittest import mock @@ -11,7 +12,7 @@ from asyncio import subprocess from test.test_asyncio import utils as test_utils from test import support -from test.support import os_helper, warnings_helper, gc_collect +from test.support import os_helper, gc_collect if not support.has_subprocess_support: raise unittest.SkipTest("test module requires subprocess") @@ -111,37 +112,6 @@ def test_subprocess_repr(self): ) transport.close() - def test_proc_exited_no_invalid_state_error_on_exit_waiters(self): - # gh-145541: when _connect_pipes hasn't completed (so - # _pipes_connected is False) and the process exits, _try_finish() - # sets the result on exit waiters. Then _call_connection_lost() must - # not call set_result() again on the same waiters. - self.loop.set_exception_handler( - lambda loop, context: self.fail( - f"unexpected exception: {context}") - ) - waiter = self.loop.create_future() - transport, protocol = self.create_transport(waiter) - - # Simulate a waiter registered via _wait() before the process exits. - exit_waiter = self.loop.create_future() - transport._exit_waiters.append(exit_waiter) - - # _connect_pipes hasn't completed, so _pipes_connected is False. - self.assertFalse(transport._pipes_connected) - - # Simulate process exit. _try_finish() will set the result on - # exit_waiter because _pipes_connected is False, and then schedule - # _call_connection_lost() because _pipes is empty (vacuously all - # disconnected). _call_connection_lost() must skip exit_waiter - # because it's already done. - transport._process_exited(6) - self.loop.run_until_complete(waiter) - - self.assertEqual(exit_waiter.result(), 6) - - transport.close() - class SubprocessMixin: @@ -250,7 +220,7 @@ def test_kill_issue43884(self): # kills the process and all its children. creationflags = CREATE_NEW_PROCESS_GROUP proc = self.loop.run_until_complete( - asyncio.create_subprocess_shell(blocking_shell_command, stdout=asyncio.subprocess.PIPE, + asyncio.create_subprocess_shell(blocking_shell_command, creationflags=creationflags) ) self.loop.run_until_complete(asyncio.sleep(1)) @@ -435,6 +405,46 @@ async def len_message(message): self.assertEqual(output.rstrip(), b'3') self.assertEqual(exitcode, 0) + def test_wait_even_if_pipe_is_open(self): + # gh-119710: Process.wait() must return once the process exits even + # if its stdout pipe is inherited by a grandchild that keeps it open, + # so the pipe never reaches EOF. Otherwise wait() hangs forever + # despite the returncode being known. + + async def run(): + # The grandchild inherits the child's stdin and stdout pipes and + # keeps both open after the child is killed. It writes "ready" + # so we know it has started, and exits once its stdin hits EOF. + code = textwrap.dedent("""\ + import subprocess, sys + subprocess.run([sys.executable, "-c", + "import sys; sys.stdout.write('ready');" + " sys.stdout.flush(); sys.stdin.read()"]) + """) + + proc = await asyncio.create_subprocess_exec( + sys.executable, "-c", code, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + ) + try: + wait_proc = asyncio.create_task(proc.wait()) + # Wait until the grandchild holds the inherited pipes; this + # also lets the wait() task register its waiter. + await proc.stdout.readexactly(5) + proc.kill() + returncode = await asyncio.wait_for( + wait_proc, timeout=support.SHORT_TIMEOUT) + if sys.platform == 'win32': + self.assertIsInstance(returncode, int) + else: + self.assertEqual(-signal.SIGKILL, returncode) + finally: + proc.stdin.close() # let the grandchild exit + await proc.stdout.read() + + self.loop.run_until_complete(run()) + def test_empty_input(self): async def empty_input(): @@ -911,7 +921,6 @@ async def main(): self.loop.run_until_complete(main()) - @warnings_helper.ignore_warnings(category=ResourceWarning) def test_subprocess_read_pipe_cancelled(self): async def main(): loop = asyncio.get_running_loop() @@ -922,7 +931,6 @@ async def main(): asyncio.run(main()) gc_collect() - @warnings_helper.ignore_warnings(category=ResourceWarning) def test_subprocess_write_pipe_cancelled(self): async def main(): loop = asyncio.get_running_loop() @@ -933,7 +941,6 @@ async def main(): asyncio.run(main()) gc_collect() - @warnings_helper.ignore_warnings(category=ResourceWarning) def test_subprocess_read_write_pipe_cancelled(self): async def main(): loop = asyncio.get_running_loop() @@ -967,6 +974,45 @@ def test_watcher_implementation(self): else: self.assertIsInstance(watcher, unix_events._ThreadedChildWatcher) + @unittest.skipUnless(hasattr(os, 'waitid'), 'needs os.waitid()') + def test_send_signal_never_targets_reaped_pid(self): + # gh-127049: there must be no window between the child watcher + # reaping the child and asyncio publishing the exit in which + # send_signal() signals the freed (possibly recycled) PID. + reaped_pids = set() + stale_kills = [] + orig_waitpid = os.waitpid + orig_kill = os.kill + + def waitpid(pid, options): + res = orig_waitpid(pid, options) + if res[0] != 0: + reaped_pids.add(res[0]) + return res + + def kill(pid, sig): + if pid in reaped_pids: + stale_kills.append(pid) + return + orig_kill(pid, sig) + + async def run(): + with mock.patch('os.waitpid', waitpid), \ + mock.patch('os.kill', kill): + proc = await asyncio.create_subprocess_exec( + *PROGRAM_BLOCKED) + proc.kill() + deadline = self.loop.time() + support.SHORT_TIMEOUT + while proc.returncode is None: + if self.loop.time() > deadline: + self.fail('child exit was not published in time') + proc.kill() + await asyncio.sleep(0) + await proc.wait() + self.assertEqual(stale_kills, []) + + self.loop.run_until_complete(run()) + class SubprocessThreadedWatcherTests(SubprocessWatcherMixin, test_utils.TestCase): @@ -980,6 +1026,92 @@ def tearDown(self): unix_events.can_use_pidfd = self._original_can_use_pidfd return super().tearDown() + @unittest.skipUnless(hasattr(os, 'waitid'), 'needs os.waitid()') + def test_pid_not_reaped_before_exit_published(self): + # gh-127049: the watcher thread must wait for the child + # without reaping it: the PID must stay reserved until the + # event loop thread reaps it and publishes the exit as one + # atomic step. + async def run(): + proc = await asyncio.create_subprocess_exec( + *PROGRAM_BLOCKED) + thread = self.loop._watcher._threads.get(proc.pid) + self.assertIsNotNone(thread) + proc.kill() + # Wait for the watcher thread to observe the exit while + # the event loop cannot process the notification yet. + thread.join(support.SHORT_TIMEOUT) + self.assertFalse(thread.is_alive()) + # The exit has not been published yet... + self.assertIsNone(proc.returncode) + # ...so the child must still be an unreaped zombie and + # signalling its PID must still be safe. waitid() raises + # ChildProcessError if the PID was already reaped (and + # possibly recycled by the kernel). + os.waitid(os.P_PID, proc.pid, + os.WEXITED | os.WNOWAIT | os.WNOHANG) + proc.kill() + self.assertEqual(await proc.wait(), -signal.SIGKILL) + + self.loop.run_until_complete(run()) + + @unittest.skipUnless(hasattr(os, 'waitid'), 'needs os.waitid()') + @unittest.skipUnless(hasattr(signal, 'SIGSTOP'), 'needs SIGSTOP') + def test_stopped_child_does_not_block_event_loop(self): + # gh-158287: on macOS, waitid() with WEXITED incorrectly reports + # stopped children (si_code == CLD_STOPPED). The child watcher + # must not mistake this for process termination and attempt to reap + # the child with waitpid(), which blocks the event loop thread. + proc = None + timed_out = False + + def watchdog(): + nonlocal timed_out + timed_out = True + # If the event loop gets stuck in waitpid() because of this bug, + # killing the child process unblocks waitpid() so the test fails + # instead of hanging indefinitely. + if proc is not None: + if hasattr(signal, 'SIGCONT'): + try: + os.kill(proc.pid, signal.SIGCONT) + except ProcessLookupError: + pass + try: + os.kill(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + + timer = threading.Timer(support.SHORT_TIMEOUT, watchdog) + timer.start() + try: + async def run(): + nonlocal proc + proc = await asyncio.create_subprocess_exec(*PROGRAM_BLOCKED) + try: + proc.send_signal(signal.SIGSTOP) + # Verify event loop remains responsive while child is stopped + for _ in range(3): + await asyncio.sleep(0.05) + self.assertFalse(timed_out, "event loop was blocked by stopped child") + self.assertIsNone(proc.returncode) + finally: + if hasattr(signal, 'SIGCONT'): + try: + proc.send_signal(signal.SIGCONT) + except ProcessLookupError: + pass + try: + proc.kill() + except ProcessLookupError: + pass + await proc.wait() + + self.loop.run_until_complete(run()) + finally: + timer.cancel() + timer.join() + @unittest.skipUnless( unix_events.can_use_pidfd(), "operating system does not support pidfds", diff --git a/Lib/test/test_asyncio/test_taskgroups.py b/Lib/test/test_asyncio/test_taskgroups.py index 834430f44e6..12438f1b8eb 100644 --- a/Lib/test/test_asyncio/test_taskgroups.py +++ b/Lib/test/test_asyncio/test_taskgroups.py @@ -1102,11 +1102,240 @@ async def throw_error(): # cancellation happens here and error is more understandable await asyncio.sleep(0) + async def test_taskgroup_cancel_children(self): + # (asserting that TimeoutError is not raised) + async with asyncio.timeout(1): + async with asyncio.TaskGroup() as tg: + tg.create_task(asyncio.sleep(10)) + tg.create_task(asyncio.sleep(10)) + await asyncio.sleep(0) + tg.cancel() + + async def test_taskgroup_cancel_body(self): + count = 0 + async with asyncio.TaskGroup() as tg: + tg.cancel() + count += 1 + await asyncio.sleep(0) + count += 1 + self.assertEqual(count, 1) + + async def test_taskgroup_cancel_idempotent(self): + count = 0 + async with asyncio.TaskGroup() as tg: + tg.cancel() + tg.cancel() + count += 1 + await asyncio.sleep(0) + count += 1 + self.assertEqual(count, 1) + + async def test_taskgroup_cancel_after_exit(self): + async with asyncio.TaskGroup() as tg: + await asyncio.sleep(0) + # (asserting that exception is not raised) + tg.cancel() + + async def test_taskgroup_cancel_before_enter(self): + tg = asyncio.TaskGroup() + tg.cancel() + count = 0 + async with tg: + count += 1 + await asyncio.sleep(0) + count += 1 + self.assertEqual(count, 1) + + async def test_taskgroup_cancel_before_create_task(self): + async with asyncio.TaskGroup() as tg: + tg.cancel() + # TODO: This behavior is not ideal. We'd rather have no exception + # raised, and the child task run until the first await. + with self.assertRaises(RuntimeError): + tg.create_task(asyncio.sleep(1)) + + async def test_taskgroup_cancel_from_child_before_first_suspension(self): + # gh-155418: an eager task can cancel the group before joining _tasks + async def child(tg): + tg.cancel() + await asyncio.sleep(10) + self.fail("the child was not cancelled") + + async with asyncio.TaskGroup() as tg: + task = tg.create_task(child(tg)) + self.assertTrue(task.cancelled()) + + async def test_taskgroup_cancel_keeps_outer_cancellation(self): + # gh-155433: any cancellation from outside the group must propagate. + cancelling = asyncio.Event() + release = asyncio.Event() + + async def child(): + try: + await asyncio.sleep(10) + finally: + # The group is cancelling: it has cancelled its parent task + # and is waiting for this task to finish. + cancelling.set() + await release.wait() + + async def body(): + async with asyncio.TaskGroup() as tg: + tg.create_task(child()) + await asyncio.sleep(0) + tg.cancel() + + task = asyncio.create_task(body()) + await cancelling.wait() + task.cancel('message') + release.set() + with self.assertRaises(asyncio.CancelledError) as cm: + await task + self.assertEqual('message', cm.exception.args[0]) + + async def test_taskgroup_cancel_before_exception(self): + async def raise_exc(parent_tg: asyncio.TaskGroup): + parent_tg.cancel() + raise RuntimeError + + with self.assertRaises(ExceptionGroup): + async with asyncio.TaskGroup() as tg: + tg.create_task(raise_exc(tg)) + await asyncio.sleep(1) + + async def test_taskgroup_cancel_after_exception(self): + async def raise_exc(parent_tg: asyncio.TaskGroup): + try: + raise RuntimeError + finally: + parent_tg.cancel() + + with self.assertRaises(ExceptionGroup): + async with asyncio.TaskGroup() as tg: + tg.create_task(raise_exc(tg)) + await asyncio.sleep(1) + + async def test_taskgroup_body_cancel_before_exception(self): + with self.assertRaises(ExceptionGroup): + async with asyncio.TaskGroup() as tg: + tg.cancel() + raise RuntimeError + + async def test_taskgroup_body_cancel_after_exception(self): + with self.assertRaises(ExceptionGroup): + async with asyncio.TaskGroup() as tg: + try: + raise RuntimeError + finally: + tg.cancel() + + async def test_taskgroup_cancel_one_winner(self): + async def race(*fns): + outcome = None + async def run(fn): + nonlocal outcome + outcome = await fn() + tg.cancel() + + async with asyncio.TaskGroup() as tg: + for fn in fns: + tg.create_task(run(fn)) + return outcome + + event = asyncio.Event() + record = [] + async def fn_1(): + record.append("1 started") + await event.wait() + record.append("1 finished") + return 1 + + async def fn_2(): + record.append("2 started") + await event.wait() + record.append("2 finished") + return 2 + + async def fn_3(): + record.append("3 started") + event.set() + await asyncio.sleep(10) + record.append("3 finished") + return 3 + + self.assertEqual(await race(fn_1, fn_2, fn_3), 1) + self.assertListEqual(record, ["1 started", "2 started", "3 started", "1 finished"]) + + async def test_taskgroup_generator_exit_01(self): + # GeneratorExit in a TaskGroup should be fine + async def gen(): + yield 1 + + async def fn(): + async with asyncio.TaskGroup() as tg: + async for n in gen(): + yield n + + g = fn() + await g.asend(None) + await g.aclose() + + async def test_taskgroup_generator_exit_02(self): + # A lone GeneratorExit in a task should still give an ExceptionGroup + async def t(): + raise GeneratorExit + + async def fn(): + async with asyncio.TaskGroup() as tg: + tg.create_task(t()) + + with self.assertRaises(BaseExceptionGroup) as cm: + await fn() + self.assertEqual(get_error_types(cm.exception), {GeneratorExit}) + + async def test_taskgroup_generator_exit_03(self): + # A GeneratorExit in one task and an error in another should + # still give an ExceptionGroup + async def t1(): + raise GeneratorExit + + async def t2(): + raise AssertionError('t2 failed') + + async def fn(): + async with asyncio.TaskGroup() as tg: + tg.create_task(t1()) + tg.create_task(t2()) + + with self.assertRaises(BaseExceptionGroup) as cm: + await fn() + + self.assertEqual(get_error_types(cm.exception), {GeneratorExit, AssertionError}) + + async def test_taskgroup_generator_exit_04(self): + event = asyncio.Event() + async def t(): + event.set() + raise AssertionError('t failed') + + async def fn(): + async with asyncio.TaskGroup() as tg: + tg.create_task(t()) + yield 1 + + g = fn() + await g.asend(None) + await event.wait() # wait for t() to run + + with self.assertRaises(BaseExceptionGroup) as cm: + await g.aclose() + + self.assertEqual(get_error_types(cm.exception), {GeneratorExit, AssertionError}) + class TestTaskGroup(BaseTestTaskGroup, unittest.IsolatedAsyncioTestCase): loop_factory = asyncio.EventLoop - class TestEagerTaskTaskGroup(BaseTestTaskGroup, unittest.IsolatedAsyncioTestCase): @staticmethod def loop_factory(): diff --git a/Lib/test/test_asyncio/test_tasks.py b/Lib/test/test_asyncio/test_tasks.py index a3c5351fed0..9c56fb3af8f 100644 --- a/Lib/test/test_asyncio/test_tasks.py +++ b/Lib/test/test_asyncio/test_tasks.py @@ -1,5 +1,6 @@ """Tests for tasks.py.""" +import _thread import collections import contextlib import contextvars @@ -19,6 +20,7 @@ from asyncio import tasks from test.test_asyncio import utils as test_utils from test import support +from test.support import threading_helper from test.support.script_helper import assert_python_ok from test.support.warnings_helper import ignore_warnings @@ -1218,6 +1220,69 @@ def gen(): loop.advance_time(10) loop.run_until_complete(asyncio.wait([a, b])) + def test_wait_discards_awaited_by_for_pending(self): + # gh-152569: wait() must remove itself from the await-graph of every + # future once it returns, including futures that never resolved. + async def coro(): + immortal = self.loop.create_future() + done = self.new_task(self.loop, asyncio.sleep(0)) + await asyncio.wait({done, immortal}, + return_when=asyncio.FIRST_COMPLETED) + self.assertFalse(immortal._asyncio_awaited_by) + immortal.cancel() + + self.loop.run_until_complete(self.new_task(self.loop, coro())) + + def test_gather_discards_awaited_by_for_pending(self): + # gh-157213: a child outliving gather() must lose the awaited-by edge + async def fail(): + raise ValueError + + async def survivor(): + await asyncio.Future() + + async def coro(): + t = self.new_task(self.loop, survivor()) + with self.assertRaises(ValueError): + await asyncio.gather(t, fail()) + self.assertFalse(t._asyncio_awaited_by) + t.cancel() + with self.assertRaises(asyncio.CancelledError): + await t + + self.loop.run_until_complete(self.new_task(self.loop, coro())) + + def test_gather_discards_awaited_by_for_cancelled_sibling(self): + # gh-157213: same, when gather() is ended by a cancelled child + async def survivor(): + await asyncio.Future() + + async def coro(): + t = self.new_task(self.loop, survivor()) + victim = self.new_task(self.loop, asyncio.sleep(10)) + victim.cancel() + with self.assertRaises(asyncio.CancelledError): + await asyncio.gather(t, victim) + self.assertFalse(t._asyncio_awaited_by) + t.cancel() + with self.assertRaises(asyncio.CancelledError): + await t + + self.loop.run_until_complete(self.new_task(self.loop, coro())) + + def test_gather_does_not_add_callback_to_outer(self): + # gh-158239: gather() must not add an internal done callback to + # the outer future just to maintain the await graph. + async def child(): + await asyncio.sleep(0) + + async def coro(): + outer = asyncio.gather(child(), child()) + self.assertFalse(outer._callbacks) + await outer + + self.loop.run_until_complete(self.new_task(self.loop, coro())) + def test_wait_really_done(self): # there is possibility that some tasks in the pending list # became done but their callbacks haven't all been called yet @@ -1637,6 +1702,46 @@ async def coro(i): ) self.assertCountEqual(results, (0, 1, 2, 3)) + def test_as_completed_async_iterator_cancelled_anext(self): + async def main(): + loop = asyncio.get_running_loop() + a = loop.create_future() + b = loop.create_future() + iterator = asyncio.as_completed([a, b]) + + waiter = asyncio.create_task(anext(iterator)) + await asyncio.sleep(0) + waiter.cancel() + with self.assertRaises(asyncio.CancelledError): + await waiter + + a.set_result('a') + b.set_result('b') + return [await f async for f in iterator] + + results = self.loop.run_until_complete(main()) + self.assertCountEqual(results, ['a', 'b']) + + def test_as_completed_plain_iterator_cancelled_wait(self): + async def main(): + loop = asyncio.get_running_loop() + a = loop.create_future() + b = loop.create_future() + iterator = asyncio.as_completed([a, b]) + + waiter = asyncio.create_task(next(iterator)) + await asyncio.sleep(0) + waiter.cancel() + with self.assertRaises(asyncio.CancelledError): + await waiter + + a.set_result('a') + b.set_result('b') + return [await c for c in iterator] + + results = self.loop.run_until_complete(main()) + self.assertCountEqual(results, ['a', 'b']) + def test_as_completed_reverse_wait(self): # Tests the plain iterator style of as_completed iteration to # ensure that the first future awaited resolves to the first @@ -2115,6 +2220,8 @@ def test_shield_cancel_outer(self): test_utils.run_briefly(self.loop) self.assertTrue(outer.cancelled()) self.assertEqual(0, 0 if outer._callbacks is None else len(outer._callbacks)) + self.assertFalse(inner._asyncio_awaited_by) + self.assertFalse(inner._callbacks) def test_shield_cancel_outer_result(self): mock_handler = mock.Mock() @@ -2129,6 +2236,23 @@ def test_shield_cancel_outer_result(self): mock_handler.assert_not_called() def test_shield_cancel_outer_exception(self): + # gh-156321: an exception in the inner future must not be reported + # eagerly, as it may still be retrieved later. + mock_handler = mock.Mock() + self.loop.set_exception_handler(mock_handler) + inner = self.new_future(self.loop) + outer = asyncio.shield(inner) + test_utils.run_briefly(self.loop) + outer.cancel() + test_utils.run_briefly(self.loop) + inner.set_exception(Exception('foo')) + test_utils.run_briefly(self.loop) + mock_handler.assert_not_called() + self.assertIsInstance(inner.exception(), Exception) + + def test_shield_cancel_outer_exception_never_retrieved(self): + # gh-156321: an exception nobody retrieves is reported by the inner + # future itself when it is garbage collected, like any other future. mock_handler = mock.Mock() self.loop.set_exception_handler(mock_handler) inner = self.new_future(self.loop) @@ -2138,9 +2262,31 @@ def test_shield_cancel_outer_exception(self): test_utils.run_briefly(self.loop) inner.set_exception(Exception('foo')) test_utils.run_briefly(self.loop) + mock_handler.assert_not_called() + inner = None + outer = None + support.gc_collect() mock_handler.assert_called_once() + context = mock_handler.call_args[0][1] + self.assertEndsWith(context['message'], 'exception was never retrieved') + self.assertIsInstance(context['exception'], Exception) + + def test_shield_cancel_outer_in_task(self): + inner = self.new_future(self.loop) - def test_shield_duplicate_log_once(self): + async def coro(): + outer = asyncio.shield(inner) + self.assertNotEqual(0, len(inner._callbacks)) + outer.cancel() + await asyncio.sleep(0) + self.assertTrue(outer.cancelled()) + + task = self.new_task(self.loop, coro()) + self.loop.run_until_complete(task) + self.assertFalse(inner._asyncio_awaited_by) + self.assertFalse(inner._callbacks) + + def test_shield_cancel_outer_twice_exception(self): mock_handler = mock.Mock() self.loop.set_exception_handler(mock_handler) inner = self.new_future(self.loop) @@ -2152,9 +2298,11 @@ def test_shield_duplicate_log_once(self): test_utils.run_briefly(self.loop) outer.cancel() test_utils.run_briefly(self.loop) + self.assertFalse(inner._callbacks) inner.set_exception(Exception('foo')) test_utils.run_briefly(self.loop) - mock_handler.assert_called_once() + mock_handler.assert_not_called() + self.assertIsInstance(inner.exception(), Exception) def test_shield_shortcut(self): fut = self.new_future(self.loop) @@ -2581,6 +2729,68 @@ async def main(): finally: loop.close() + def test_context_not_a_context(self): + # gh-157301 + async def coro(): + pass + + loop = asyncio.new_event_loop() + c = coro() + try: + with self.assertRaises(TypeError): + self.new_task(loop, c, context='not a context') + finally: + c.close() + loop.close() + + def test_context_not_a_context_leaves_loop_usable(self): + # gh-157301 + async def coro(): + pass + + async def main(): + c = coro() + try: + with self.assertRaises(TypeError): + self.new_task(loop, c, context='not a context', + eager_start=True) + finally: + c.close() + await asyncio.sleep(0) + + loop = asyncio.new_event_loop() + loop.call_later(support.SHORT_TIMEOUT, loop.stop) + try: + loop.run_until_complete(self.new_task(loop, main())) + finally: + loop.close() + + def test_context_already_entered_leaves_loop_usable(self): + # gh-157301 + async def coro(): + pass + + async def main(): + ctx = contextvars.copy_context() + + def inside(): + c = coro() + try: + with self.assertRaises(RuntimeError): + self.new_task(loop, c, context=ctx, eager_start=True) + finally: + c.close() + + ctx.run(inside) + await asyncio.sleep(0) + + loop = asyncio.new_event_loop() + loop.call_later(support.SHORT_TIMEOUT, loop.stop) + try: + loop.run_until_complete(self.new_task(loop, main())) + finally: + loop.close() + def test_context_2(self): cvar = contextvars.ContextVar('cvar', default='nope') @@ -2739,6 +2949,18 @@ async def main(): self.assertEqual(name, "example") await t + def test_eager_start_true_no_loop(self): + # gh-154695: eager_start must use the resolved loop, not loop=None. + async def asyncfn(): + return 42 + + async def main(): + t = self.__class__.Task(asyncfn(), eager_start=True) + self.assertTrue(t.done()) + self.assertEqual(await t, 42) + + asyncio.run(main(), loop_factory=asyncio.EventLoop) + def test_eager_start_false(self): name = None @@ -2776,28 +2998,17 @@ def test_get_context(self): finally: loop.close() - def test_proper_refcounts(self): - # see: https://github.com/python/cpython/issues/126083 - class Break: - def __str__(self): - raise RuntimeError("break") - - obj = object() - initial_refcount = sys.getrefcount(obj) - - coro = coroutine_function() - with contextlib.closing(asyncio.EventLoop()) as loop: - task = asyncio.Task.__new__(asyncio.Task) - for _ in range(5): - with self.assertRaisesRegex(RuntimeError, 'break'): - task.__init__(coro, loop=loop, context=obj, name=Break()) - - coro.close() - task._log_destroy_pending = False - del task + def test_task_disallow_multiple_initialization(self): + async def foo(): + pass - self.assertEqual(sys.getrefcount(obj), initial_refcount) + coro = foo() + self.addCleanup(coro.close) + task = self.new_task(self.loop, coro) + task._log_destroy_pending = False + with self.assertRaises(RuntimeError, msg="is already initialized"): + task.__init__(coro, loop=self.loop) def add_subclass_tests(cls): BaseTask = cls.Task @@ -2921,19 +3132,6 @@ class CTask_CFuture_Tests(BaseTaskTests, SetMethodsTest, all_tasks = getattr(tasks, '_c_all_tasks', None) current_task = staticmethod(getattr(tasks, '_c_current_task', None)) - @support.refcount_test - def test_refleaks_in_task___init__(self): - gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') - async def coro(): - pass - task = self.new_task(self.loop, coro()) - self.loop.run_until_complete(task) - refs_before = gettotalrefcount() - for i in range(100): - task.__init__(coro(), loop=self.loop) - self.loop.run_until_complete(task) - self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) - def test_del__log_destroy_pending_segfault(self): async def coro(): pass @@ -2942,6 +3140,16 @@ async def coro(): with self.assertRaises(AttributeError): del task._log_destroy_pending + def test_get_context_uninitialized_segfault(self): + # https://github.com/python/cpython/issues/154871 + + class UninitializedTask(self.Task): + def __init__(self, *args, **kwargs): + pass + + task = UninitializedTask() + self.assertIsNone(task.get_context()) + @unittest.skipUnless(hasattr(futures, '_CFuture') and hasattr(tasks, '_CTask'), diff --git a/Lib/test/test_asyncio/test_tools.py b/Lib/test/test_asyncio/test_tools.py index 34e94830204..2b8e4940333 100644 --- a/Lib/test/test_asyncio/test_tools.py +++ b/Lib/test/test_asyncio/test_tools.py @@ -2,12 +2,27 @@ from asyncio import tools -from collections import namedtuple +import _remote_debugging -FrameInfo = namedtuple('FrameInfo', ['funcname', 'filename', 'lineno']) -CoroInfo = namedtuple('CoroInfo', ['call_stack', 'task_name']) -TaskInfo = namedtuple('TaskInfo', ['task_id', 'task_name', 'coroutine_stack', 'awaited_by']) -AwaitedInfo = namedtuple('AwaitedInfo', ['thread_id', 'awaited_by']) + +def LocationInfo(lineno, end_lineno=None, col_offset=None, end_col_offset=None): + return _remote_debugging.LocationInfo((lineno, end_lineno, col_offset, end_col_offset)) + + +def FrameInfo(funcname, filename, location, opcode=None): + return _remote_debugging.FrameInfo((filename, location, funcname, opcode)) + + +def CoroInfo(call_stack, task_name): + return _remote_debugging.CoroInfo((call_stack, task_name)) + + +def TaskInfo(task_id, task_name, coroutine_stack, awaited_by): + return _remote_debugging.TaskInfo((task_id, task_name, coroutine_stack, awaited_by)) + + +def AwaitedInfo(thread_id, awaited_by): + return _remote_debugging.AwaitedInfo((thread_id, awaited_by)) # mock output of get_all_awaited_by function. @@ -33,33 +48,33 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("awaiter3", "/path/to/app.py", 130), - FrameInfo("awaiter2", "/path/to/app.py", 120), - FrameInfo("awaiter", "/path/to/app.py", 110) + FrameInfo("awaiter3", "/path/to/app.py", LocationInfo(130)), + FrameInfo("awaiter2", "/path/to/app.py", LocationInfo(120)), + FrameInfo("awaiter", "/path/to/app.py", LocationInfo(110)) ], task_name=4 ), CoroInfo( call_stack=[ - FrameInfo("awaiterB3", "/path/to/app.py", 190), - FrameInfo("awaiterB2", "/path/to/app.py", 180), - FrameInfo("awaiterB", "/path/to/app.py", 170) + FrameInfo("awaiterB3", "/path/to/app.py", LocationInfo(190)), + FrameInfo("awaiterB2", "/path/to/app.py", LocationInfo(180)), + FrameInfo("awaiterB", "/path/to/app.py", LocationInfo(170)) ], task_name=5 ), CoroInfo( call_stack=[ - FrameInfo("awaiterB3", "/path/to/app.py", 190), - FrameInfo("awaiterB2", "/path/to/app.py", 180), - FrameInfo("awaiterB", "/path/to/app.py", 170) + FrameInfo("awaiterB3", "/path/to/app.py", LocationInfo(190)), + FrameInfo("awaiterB2", "/path/to/app.py", LocationInfo(180)), + FrameInfo("awaiterB", "/path/to/app.py", LocationInfo(170)) ], task_name=6 ), CoroInfo( call_stack=[ - FrameInfo("awaiter3", "/path/to/app.py", 130), - FrameInfo("awaiter2", "/path/to/app.py", 120), - FrameInfo("awaiter", "/path/to/app.py", 110) + FrameInfo("awaiter3", "/path/to/app.py", LocationInfo(130)), + FrameInfo("awaiter2", "/path/to/app.py", LocationInfo(120)), + FrameInfo("awaiter", "/path/to/app.py", LocationInfo(110)) ], task_name=7 ) @@ -72,9 +87,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("main", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("main", "", LocationInfo(0)) ], task_name=2 ) @@ -87,9 +102,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("main", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("main", "", LocationInfo(0)) ], task_name=2 ) @@ -102,10 +117,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=8 ) @@ -118,10 +133,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=8 ) @@ -134,10 +149,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=9 ) @@ -150,10 +165,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=9 ) @@ -222,7 +237,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main2", "", 0)], + call_stack=[FrameInfo("main2", "", LocationInfo(0))], task_name=5 ) ] @@ -233,7 +248,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main2", "", 0)], + call_stack=[FrameInfo("main2", "", LocationInfo(0))], task_name=5 ) ] @@ -244,7 +259,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main2", "", 0)], + call_stack=[FrameInfo("main2", "", LocationInfo(0))], task_name=5 ) ] @@ -266,7 +281,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=1 ) ] @@ -277,7 +292,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=1 ) ] @@ -288,7 +303,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=1 ) ] @@ -347,7 +362,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=4 ) ] @@ -358,7 +373,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=4 ) ] @@ -369,7 +384,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=4 ) ] @@ -415,11 +430,11 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("awaiter2", "", 0)], + call_stack=[FrameInfo("awaiter2", "", LocationInfo(0))], task_name=4 ), CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=2 ) ] @@ -430,7 +445,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("awaiter", "", 0)], + call_stack=[FrameInfo("awaiter", "", LocationInfo(0))], task_name=3 ) ] @@ -462,9 +477,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_b", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_b", "", LocationInfo(0)) ], task_name=4 ) @@ -477,17 +492,17 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_c", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_c", "", LocationInfo(0)) ], task_name=5 ), CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_a", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_a", "", LocationInfo(0)) ], task_name=3 ) @@ -500,8 +515,8 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)) ], task_name=6 ) @@ -514,9 +529,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_b", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_b", "", LocationInfo(0)) ], task_name=4 ) @@ -553,33 +568,33 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("awaiter3", "", 0), - FrameInfo("awaiter2", "", 0), - FrameInfo("awaiter", "", 0) + FrameInfo("awaiter3", "", LocationInfo(0)), + FrameInfo("awaiter2", "", LocationInfo(0)), + FrameInfo("awaiter", "", LocationInfo(0)) ], task_name=4 ), CoroInfo( call_stack=[ - FrameInfo("awaiter1_3", "", 0), - FrameInfo("awaiter1_2", "", 0), - FrameInfo("awaiter1", "", 0) + FrameInfo("awaiter1_3", "", LocationInfo(0)), + FrameInfo("awaiter1_2", "", LocationInfo(0)), + FrameInfo("awaiter1", "", LocationInfo(0)) ], task_name=5 ), CoroInfo( call_stack=[ - FrameInfo("awaiter1_3", "", 0), - FrameInfo("awaiter1_2", "", 0), - FrameInfo("awaiter1", "", 0) + FrameInfo("awaiter1_3", "", LocationInfo(0)), + FrameInfo("awaiter1_2", "", LocationInfo(0)), + FrameInfo("awaiter1", "", LocationInfo(0)) ], task_name=6 ), CoroInfo( call_stack=[ - FrameInfo("awaiter3", "", 0), - FrameInfo("awaiter2", "", 0), - FrameInfo("awaiter", "", 0) + FrameInfo("awaiter3", "", LocationInfo(0)), + FrameInfo("awaiter2", "", LocationInfo(0)), + FrameInfo("awaiter", "", LocationInfo(0)) ], task_name=7 ) @@ -592,9 +607,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("main", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("main", "", LocationInfo(0)) ], task_name=2 ) @@ -607,9 +622,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("main", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("main", "", LocationInfo(0)) ], task_name=2 ) @@ -622,10 +637,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=8 ) @@ -638,10 +653,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=8 ) @@ -654,10 +669,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=9 ) @@ -670,10 +685,10 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("_aexit", "", 0), - FrameInfo("__aexit__", "", 0), - FrameInfo("blocho_caller", "", 0), - FrameInfo("bloch", "", 0) + FrameInfo("_aexit", "", LocationInfo(0)), + FrameInfo("__aexit__", "", LocationInfo(0)), + FrameInfo("blocho_caller", "", LocationInfo(0)), + FrameInfo("bloch", "", LocationInfo(0)) ], task_name=9 ) @@ -797,7 +812,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main2", "", 0)], + call_stack=[FrameInfo("main2", "", LocationInfo(0))], task_name=5 ) ] @@ -808,7 +823,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main2", "", 0)], + call_stack=[FrameInfo("main2", "", LocationInfo(0))], task_name=5 ) ] @@ -819,7 +834,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main2", "", 0)], + call_stack=[FrameInfo("main2", "", LocationInfo(0))], task_name=5 ) ] @@ -841,7 +856,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=1 ) ] @@ -852,7 +867,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=1 ) ] @@ -863,7 +878,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=1 ) ] @@ -916,7 +931,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=4 ) ] @@ -927,7 +942,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=4 ) ] @@ -938,7 +953,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=4 ) ] @@ -979,11 +994,11 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("awaiter2", "", 0)], + call_stack=[FrameInfo("awaiter2", "", LocationInfo(0))], task_name=4 ), CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=2 ) ] @@ -994,7 +1009,7 @@ coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("awaiter", "", 0)], + call_stack=[FrameInfo("awaiter", "", LocationInfo(0))], task_name=3 ) ] @@ -1033,9 +1048,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_b", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_b", "", LocationInfo(0)) ], task_name=4 ) @@ -1048,17 +1063,17 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_c", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_c", "", LocationInfo(0)) ], task_name=5 ), CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_a", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_a", "", LocationInfo(0)) ], task_name=3 ) @@ -1071,8 +1086,8 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)) ], task_name=6 ) @@ -1085,9 +1100,9 @@ awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("nested", "", 0), - FrameInfo("nested", "", 0), - FrameInfo("task_b", "", 0) + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("nested", "", LocationInfo(0)), + FrameInfo("task_b", "", LocationInfo(0)) ], task_name=4 ) @@ -1290,7 +1305,7 @@ def test_cycle_detection(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=3 ) ] @@ -1301,7 +1316,7 @@ def test_cycle_detection(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=2 ) ] @@ -1331,7 +1346,7 @@ def test_complex_tree(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=2 ) ] @@ -1342,7 +1357,7 @@ def test_complex_tree(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=3 ) ] @@ -1379,7 +1394,7 @@ def test_complex_table(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=2 ) ] @@ -1390,7 +1405,7 @@ def test_complex_table(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("main", "", 0)], + call_stack=[FrameInfo("main", "", LocationInfo(0))], task_name=3 ) ] @@ -1417,11 +1432,11 @@ def test_deep_coroutine_chain(self): awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("c1", "", 0), - FrameInfo("c2", "", 0), - FrameInfo("c3", "", 0), - FrameInfo("c4", "", 0), - FrameInfo("c5", "", 0) + FrameInfo("c1", "", LocationInfo(0)), + FrameInfo("c2", "", LocationInfo(0)), + FrameInfo("c3", "", LocationInfo(0)), + FrameInfo("c4", "", LocationInfo(0)), + FrameInfo("c5", "", LocationInfo(0)) ], task_name=11 ) @@ -1461,7 +1476,7 @@ def test_multiple_cycles_same_node(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("call1", "", 0)], + call_stack=[FrameInfo("call1", "", LocationInfo(0))], task_name=2 ) ] @@ -1472,7 +1487,7 @@ def test_multiple_cycles_same_node(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("call2", "", 0)], + call_stack=[FrameInfo("call2", "", LocationInfo(0))], task_name=3 ) ] @@ -1483,11 +1498,11 @@ def test_multiple_cycles_same_node(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("call3", "", 0)], + call_stack=[FrameInfo("call3", "", LocationInfo(0))], task_name=1 ), CoroInfo( - call_stack=[FrameInfo("call4", "", 0)], + call_stack=[FrameInfo("call4", "", LocationInfo(0))], task_name=2 ) ] @@ -1511,7 +1526,7 @@ def test_table_output_format(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("foo", "", 0)], + call_stack=[FrameInfo("foo", "", LocationInfo(0))], task_name=2 ) ] @@ -1543,6 +1558,82 @@ def test_table_output_format(self): class TestAsyncioToolsEdgeCases(unittest.TestCase): + def test_frames_without_location_tree(self): + """Frames the unwinder could not fully read - should not crash.""" + input_ = [ + AwaitedInfo( + thread_id=1, + awaited_by=[ + TaskInfo( + task_id=1, + task_name="Task-A", + coroutine_stack=[ + CoroInfo( + call_stack=[ + FrameInfo("", "~", None), + FrameInfo("", "app.py", None), + FrameInfo("big", "big.py", None), + ], + task_name=1 + ) + ], + awaited_by=[] + ) + ] + ) + ] + self.assertEqual( + tools.build_async_tree(input_), + [[ + "└── (T) Task-A", + " └── big big.py", + " └── app.py", + " └── ", + ]], + ) + + def test_frames_without_location_table(self): + """Frame names are not truncated at the first space.""" + input_ = [ + AwaitedInfo( + thread_id=1, + awaited_by=[ + TaskInfo( + task_id=1, + task_name="Task-A", + coroutine_stack=[ + CoroInfo( + call_stack=[ + FrameInfo("", "~", None) + ], + task_name=1 + ) + ], + awaited_by=[ + CoroInfo( + call_stack=[ + FrameInfo("", "app.py", None) + ], + task_name=2 + ) + ] + ) + ] + ) + ] + self.assertEqual( + tools.build_task_table(input_), + [[ + 1, + "0x1", + "Task-A", + "", + "", + "Unknown", + "0x2", + ]], + ) + def test_task_awaits_self(self): """A task directly awaits itself - should raise a cycle.""" input_ = [ @@ -1555,7 +1646,7 @@ def test_task_awaits_self(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("loopback", "", 0)], + call_stack=[FrameInfo("loopback", "", LocationInfo(0))], task_name=1 ) ] @@ -1579,7 +1670,7 @@ def test_task_with_missing_awaiter_id(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("coro", "", 0)], + call_stack=[FrameInfo("coro", "", LocationInfo(0))], task_name=999 ) ] @@ -1603,11 +1694,11 @@ def test_duplicate_coroutine_frames(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("frameA", "", 0)], + call_stack=[FrameInfo("frameA", "", LocationInfo(0))], task_name=2 ), CoroInfo( - call_stack=[FrameInfo("frameA", "", 0)], + call_stack=[FrameInfo("frameA", "", LocationInfo(0))], task_name=3 ) ] @@ -1651,7 +1742,7 @@ def test_task_with_no_name(self): coroutine_stack=[], awaited_by=[ CoroInfo( - call_stack=[FrameInfo("f1", "", 0)], + call_stack=[FrameInfo("f1", "", LocationInfo(0))], task_name=2 ) ] @@ -1682,8 +1773,8 @@ def test_tree_rendering_with_custom_emojis(self): awaited_by=[ CoroInfo( call_stack=[ - FrameInfo("f1", "", 0), - FrameInfo("f2", "", 0) + FrameInfo("f1", "", LocationInfo(0)), + FrameInfo("f2", "", LocationInfo(0)) ], task_name=2 ) diff --git a/Lib/test/test_asyncio/test_unix_events.py b/Lib/test/test_asyncio/test_unix_events.py index 520f5c733c3..118cb866997 100644 --- a/Lib/test/test_asyncio/test_unix_events.py +++ b/Lib/test/test_asyncio/test_unix_events.py @@ -15,7 +15,7 @@ from unittest import mock from test import support -from test.support import os_helper +from test.support import os_helper, warnings_helper from test.support import socket_helper from test.support import wait_process from test.support import hashlib_helper @@ -1182,6 +1182,7 @@ async def runner(): @support.requires_fork() class TestFork(unittest.TestCase): + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_fork_not_share_current_task(self): loop = object() task = object() @@ -1214,6 +1215,7 @@ def test_fork_not_share_current_task(self): self.assertEqual(result, b'NO TASK') wait_process(pid, exitcode=0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_fork_not_share_event_loop(self): # The forked process should not share the event loop with the parent loop = object() @@ -1241,6 +1243,7 @@ def test_fork_not_share_event_loop(self): self.assertEqual(result, b'NO LOOP') wait_process(pid, exitcode=0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @hashlib_helper.requires_hashdigest('md5') @support.skip_if_sanitizer("TSAN doesn't support threads after fork", thread=True) def test_fork_signal_handling(self): @@ -1288,6 +1291,7 @@ async def func(): self.assertFalse(parent_handled.is_set()) self.assertTrue(child_handled.is_set()) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @hashlib_helper.requires_hashdigest('md5') @support.skip_if_sanitizer("TSAN doesn't support threads after fork", thread=True) def test_fork_asyncio_run(self): @@ -1308,6 +1312,7 @@ async def child_main(): self.assertEqual(result.value, 42) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @hashlib_helper.requires_hashdigest('md5') @support.skip_if_sanitizer("TSAN doesn't support threads after fork", thread=True) def test_fork_asyncio_subprocess(self): @@ -1328,5 +1333,45 @@ async def child_main(): self.assertEqual(result.value, 0) + +@unittest.skipUnless( + unix_events.can_use_pidfd(), + "operating system does not support pidfd", +) +class PidfdChildWatcherTests(test_utils.TestCase): + + def setUp(self): + super().setUp() + self.loop = asyncio.new_event_loop() + self.set_event_loop(self.loop) + + def test_pidfd_closed_when_waitpid_raises(self): + # _do_wait() must close the pidfd even when waitpid() + # fails with something other than ChildProcessError, otherwise the + # pidfd is leaked + self.loop.set_exception_handler(lambda loop, context: None) + + async def coro(): + before = os_helper.fd_count() + proc = await asyncio.create_subprocess_exec( + sys.executable, '-c', 'import sys; sys.stdin.read()', + stdin=asyncio.subprocess.PIPE + ) + + with mock.patch.object(os, 'waitpid', + side_effect=OSError('unexpected')) as m: + proc.stdin.close() + while not m.called: + await asyncio.sleep(0) + + os.waitpid(proc.pid, 0) + proc._transport._process_exited(0) + await proc.wait() + + self.assertEqual(os_helper.fd_count(), before) + + self.loop.run_until_complete(coro()) + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_asyncio/test_windows_events.py b/Lib/test/test_asyncio/test_windows_events.py index 0af3368627a..4a85b1a09ee 100644 --- a/Lib/test/test_asyncio/test_windows_events.py +++ b/Lib/test/test_asyncio/test_windows_events.py @@ -5,6 +5,7 @@ import time import threading import unittest +import warnings from unittest import mock if sys.platform != 'win32': @@ -15,6 +16,9 @@ import asyncio from asyncio import windows_events +from asyncio import windows_utils +from test import support +from test.support import os_helper from test.test_asyncio import utils as test_utils @@ -359,5 +363,110 @@ async def main(): asyncio.events._set_event_loop_policy(old_policy) +class ProactorPipeObjectSupportTests(unittest.TestCase): + + def setUp(self): + super().setUp() + self.loop = asyncio.ProactorEventLoop() + self.addCleanup(self.loop.close) + self.errors = [] + self.loop.set_exception_handler( + lambda loop, context: self.errors.append(context)) + + def check_read_rejected(self, pipe): + self.addCleanup(pipe.close) + lost = self.loop.create_future() + + class Proto(asyncio.Protocol): + def connection_lost(self, exc): + if not lost.done(): + lost.set_result(exc) + + async def run(): + transport, _ = await self.loop.connect_read_pipe(Proto, pipe) + exc = await lost + transport.close() + return exc + + exc = self.loop.run_until_complete(run()) + self.assertIsInstance(exc, OSError) + + def check_write_rejected(self, pipe): + self.addCleanup(pipe.close) + with warnings.catch_warnings(): + warnings.simplefilter('ignore', ResourceWarning) + with self.assertRaises(OSError): + self.loop.run_until_complete( + self.loop.connect_write_pipe(asyncio.BaseProtocol, pipe)) + support.gc_collect() + + def check_accepted(self, rpipe, wpipe): + self.addCleanup(rpipe.close) + self.addCleanup(wpipe.close) + + chunks = [] + lost = self.loop.create_future() + + class ReadProto(asyncio.Protocol): + def data_received(self, data): + chunks.append(data) + + def connection_lost(self, exc): + if not lost.done(): + lost.set_result(exc) + + async def run(): + rtransport, _ = await self.loop.connect_read_pipe(ReadProto, rpipe) + wtransport, _ = await self.loop.connect_write_pipe( + asyncio.BaseProtocol, wpipe) + wtransport.write(b'spam') + wtransport.close() + await lost + rtransport.close() + + self.loop.run_until_complete(run()) + self.assertEqual(b''.join(chunks), b'spam') + self.assertFalse(self.errors) + + def test_overlapped_pipe(self): + rhandle, whandle = windows_utils.pipe(duplex=True, overlapped=(True, True)) + self.check_accepted(windows_utils.PipeHandle(rhandle), + windows_utils.PipeHandle(whandle)) + + def test_socketpair(self): + rsock, wsock = socket.socketpair() + self.check_accepted(rsock, wsock) + + def test_read_non_overlapped_pipe(self): + rhandle, whandle = windows_utils.pipe(overlapped=(False, False)) + self.addCleanup(windows_utils.PipeHandle(whandle).close) + self.check_read_rejected(windows_utils.PipeHandle(rhandle)) + + def test_write_non_overlapped_pipe(self): + rhandle, whandle = windows_utils.pipe(overlapped=(False, False)) + self.addCleanup(windows_utils.PipeHandle(rhandle).close) + self.check_write_rejected(windows_utils.PipeHandle(whandle)) + + def test_read_regular_file(self): + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + with open(os_helper.TESTFN, 'wb') as f: + f.write(b'spam') + self.check_read_rejected(open(os_helper.TESTFN, 'rb', 0)) + + def test_write_regular_file(self): + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + self.check_write_rejected(open(os_helper.TESTFN, 'wb', 0)) + + def test_read_os_pipe(self): + rfd, wfd = os.pipe() + self.addCleanup(os.close, wfd) + self.check_read_rejected(open(rfd, 'rb', 0)) + + def test_write_os_pipe(self): + rfd, wfd = os.pipe() + self.addCleanup(os.close, rfd) + self.check_write_rejected(open(wfd, 'wb', 0)) + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_asyncio/utils.py b/Lib/test/test_asyncio/utils.py index a480e16e81b..62cfcf8ceb5 100644 --- a/Lib/test/test_asyncio/utils.py +++ b/Lib/test/test_asyncio/utils.py @@ -388,8 +388,8 @@ def close(self): else: # pragma: no cover raise AssertionError("Time generator is not finished") - def _add_reader(self, fd, callback, *args): - self.readers[fd] = events.Handle(callback, args, self, None) + def _add_reader(self, fd, callback, *args, context=None): + self.readers[fd] = events.Handle(callback, args, self, context) def _remove_reader(self, fd): self.remove_reader_count[fd] += 1 @@ -414,8 +414,8 @@ def assert_no_reader(self, fd): if fd in self.readers: raise AssertionError(f'fd {fd} is registered') - def _add_writer(self, fd, callback, *args): - self.writers[fd] = events.Handle(callback, args, self, None) + def _add_writer(self, fd, callback, *args, context=None): + self.writers[fd] = events.Handle(callback, args, self, context) def _remove_writer(self, fd): self.remove_writer_count[fd] += 1 diff --git a/Lib/test/test_atexit.py b/Lib/test/test_atexit.py index aba377d4175..514c96ecb9f 100644 --- a/Lib/test/test_atexit.py +++ b/Lib/test/test_atexit.py @@ -3,9 +3,9 @@ import subprocess import textwrap import unittest -from test.support import os_helper from test import support from test.support import SuppressCrashReport, script_helper +from test.support import os_helper from test.support import threading_helper class GeneralTest(unittest.TestCase): @@ -82,6 +82,62 @@ def thready(): # want them to affect the rest of the tests. script_helper.assert_python_ok("-c", textwrap.dedent(source)) + @threading_helper.requires_working_threading() + def test_thread_created_in_atexit(self): + source = """if True: + import atexit + import threading + import time + + + def run(): + print(24) + time.sleep(1) + print(42) + + @atexit.register + def start_thread(): + threading.Thread(target=run).start() + """ + return_code, stdout, stderr = script_helper.assert_python_ok("-c", source) + self.assertEqual(return_code, 0) + self.assertEqual(stdout, f"24{os.linesep}42{os.linesep}".encode("utf-8")) + self.assertEqual(stderr, b"") + + @threading_helper.requires_working_threading() + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_thread_created_in_atexit_subinterpreter(self): + try: + from concurrent import interpreters + except ImportError: + self.skipTest("subinterpreters are not available") + + read, write = os.pipe() + source = f"""if True: + import atexit + import threading + import time + import os + + def run(): + os.write({write}, b'spanish') + time.sleep(1) + os.write({write}, b'inquisition') + + @atexit.register + def start_thread(): + threading.Thread(target=run).start() + """ + interp = interpreters.create() + try: + interp.exec(source) + + # Close the interpreter to invoke atexit callbacks + interp.close() + self.assertEqual(os.read(read, 100), b"spanishinquisition") + finally: + os.close(read) + os.close(write) @support.cpython_only class SubinterpreterTest(unittest.TestCase): @@ -142,14 +198,14 @@ def test_atexit_with_low_memory(self): # callback doesn't cause an infinite loop during finalization. code = textwrap.dedent(""" import atexit - import _testcapi + from test.support import inject_memory_error def callback(): print("hello") atexit.register(callback) # Simulate low memory condition - _testcapi.set_nomemory(0) + inject_memory_error() """) with os_helper.temp_dir() as temp_dir: diff --git a/Lib/test/test_audit.py b/Lib/test/test_audit.py index 690a6e7434e..9778bfe8275 100644 --- a/Lib/test/test_audit.py +++ b/Lib/test/test_audit.py @@ -58,7 +58,6 @@ def test_block_add_hook(self): def test_block_add_hook_baseexception(self): self.do_test("test_block_add_hook_baseexception") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_marshal(self): import_helper.import_module("marshal") @@ -69,18 +68,15 @@ def test_pickle(self): self.do_test("test_pickle") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_monkeypatch(self): self.do_test("test_monkeypatch") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_open(self): self.do_test("test_open", os_helper.TESTFN) def test_cantrace(self): self.do_test("test_cantrace") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_mmap(self): self.do_test("test_mmap") @@ -89,12 +85,10 @@ def test_ctypes_call_function(self): import_helper.import_module("ctypes") self.do_test("test_ctypes_call_function") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_posixsubprocess(self): import_helper.import_module("_posixsubprocess") self.do_test("test_posixsubprocess") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_excepthook(self): returncode, events, stderr = self.run_python("test_excepthook") if not returncode: @@ -116,7 +110,6 @@ def test_unraisablehook(self): "RuntimeError('nonfatal-error') Exception ignored for audit hook test", ) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_winreg(self): import_helper.import_module("winreg") returncode, events, stderr = self.run_python("test_winreg") @@ -144,7 +137,6 @@ def test_socket(self): self.assertEqual(events[2][0], "socket.bind") self.assertEndsWith(events[2][2], "('127.0.0.1', 8080)") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_gc(self): returncode, events, stderr = self.run_python("test_gc") if returncode: @@ -174,7 +166,6 @@ def test_http(self): self.assertIn('HTTP', events[1][2]) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_sqlite3(self): sqlite3 = import_helper.import_module("sqlite3") returncode, events, stderr = self.run_python("test_sqlite3") @@ -219,7 +210,6 @@ def test_sys_getframemodulename(self): self.assertEqual(actual, expected) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_threading(self): returncode, events, stderr = self.run_python("test_threading") if returncode: @@ -238,7 +228,7 @@ def test_threading(self): self.assertEqual(actual, expected) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailureIf(sys.platform != "win32", "TODO: RUSTPYTHON") def test_wmi_exec_query(self): import_helper.import_module("_wmi") returncode, events, stderr = self.run_python("test_wmi_exec_query") @@ -252,7 +242,6 @@ def test_wmi_exec_query(self): self.assertEqual(actual, expected) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_syslog(self): syslog = import_helper.import_module("syslog") @@ -314,7 +303,6 @@ def test_sys_monitoring_register_callback(self): self.assertEqual(actual, expected) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_winapi_createnamedpipe(self): winapi = import_helper.import_module("_winapi") @@ -345,5 +333,17 @@ def test_sys_remote_exec(self): if returncode: self.fail(stderr) + @unittest.expectedFailureIf(__import__("importlib.util", fromlist=["find_spec"]).find_spec("_testcapi") is None, "TODO: RUSTPYTHON; requires the absent _testcapi module for extension import audit events; recheck when discoverable") + def test_import_module(self): + self.do_test("test_import_module") + + @unittest.expectedFailureIf(__import__("importlib.util", fromlist=["find_spec"]).find_spec("_testcapi") is None, "TODO: RUSTPYTHON; requires the absent _testcapi module for extension import audit events; recheck when discoverable") + def test_builtin__import__(self): + self.do_test("test_builtin__import__") + + @unittest.expectedFailureIf(__import__("importlib.util", fromlist=["find_spec"]).find_spec("_testcapi") is None, "TODO: RUSTPYTHON; requires the absent _testcapi module for extension import audit events; recheck when discoverable") + def test_import_statement(self): + self.do_test("test_import_statement") + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_base64.py b/Lib/test/test_base64.py index 9fe69f4f692..868abcfee24 100644 --- a/Lib/test/test_base64.py +++ b/Lib/test/test_base64.py @@ -1,9 +1,11 @@ import unittest import base64 import binascii +import string +import sys import os from array import array -from test.support import cpython_only +from test.support import cpython_only, check_impl_detail from test.support import os_helper from test.support import script_helper from test.support.import_helper import ensure_lazy_imports @@ -14,6 +16,8 @@ class LazyImportTest(unittest.TestCase): def test_lazy_import(self): ensure_lazy_imports("base64", {"re", "getopt"}) +from test.support.hypothesis_helper import hypothesis + class LegacyBase64TestCase(unittest.TestCase): @@ -68,6 +72,13 @@ def test_decodebytes(self): eq(base64.decodebytes(array('B', b'YWJj\n')), b'abc') self.check_type_errors(base64.decodebytes) + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz') + def test_bytes_encode_decode_round_trip(self, payload): + encoded = base64.encodebytes(payload) + decoded = base64.decodebytes(encoded) + self.assertEqual(payload, decoded) + def test_encode(self): eq = self.assertEqual from io import BytesIO, StringIO @@ -96,6 +107,19 @@ def test_decode(self): self.assertRaises(TypeError, base64.encode, BytesIO(b'YWJj\n'), StringIO()) self.assertRaises(TypeError, base64.encode, StringIO('YWJj\n'), StringIO()) + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz') + def test_legacy_encode_decode_round_trip(self, payload): + from io import BytesIO + payload_file_r = BytesIO(payload) + encoded_file_w = BytesIO() + base64.encode(payload_file_r, encoded_file_w) + encoded_file_r = BytesIO(encoded_file_w.getvalue()) + decoded_file_w = BytesIO() + base64.decode(encoded_file_r, decoded_file_w) + decoded = decoded_file_w.getvalue() + self.assertEqual(payload, decoded) + class BaseXYTestCase(unittest.TestCase): @@ -149,6 +173,7 @@ def test_b64encode(self): b"YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE" b"RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT" b"Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==") + # Test with arbitrary alternative characters eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=b'*$'), b'01a*b$cd') eq(base64.b64encode(b'\xd3V\xbeo\xf7\x1d', altchars=bytearray(b'*$')), @@ -184,6 +209,55 @@ def test_b64encode(self): b'\xd3V\xbeo\xf7\x1d', b'01a-b_cd') self.check_encode_type_errors(base64.urlsafe_b64encode) + def test_b64encode_padded(self): + b64encode = base64.b64encode + self.assertEqual(b64encode(b'', padded=False), b'') + self.assertEqual(b64encode(b'a', padded=False), b'YQ') + self.assertEqual(b64encode(b'ab', padded=False), b'YWI') + self.assertEqual(b64encode(b'abc', padded=False), b'YWJj') + self.assertEqual(b64encode(b'\xfb', padded=False, altchars=b'-_'), b'-w') + self.assertEqual(b64encode(b'\xfb\xff', padded=False, altchars=b'-_'), + b'-_8') + self.assertEqual(b64encode(b'\xfb\xff\xbf', padded=False, altchars=b'-_'), + b'-_-_') + + urlsafe_b64encode = base64.urlsafe_b64encode + self.assertEqual(urlsafe_b64encode(b'', padded=False), b'') + self.assertEqual(urlsafe_b64encode(b'\xfb', padded=False), b'-w') + self.assertEqual(urlsafe_b64encode(b'\xfb\xff', padded=False), b'-_8') + self.assertEqual(urlsafe_b64encode(b'\xfb\xff\xbf', padded=False), + b'-_-_') + + def _common_test_wrapcol(self, func, data): + eq = self.assertEqual + expected = func(data) + eq(func(data, wrapcol=0), expected) + eq(func(data, wrapcol=80), expected) + eq(func(b'', wrapcol=0), func(b'')) + eq(func(b'', wrapcol=1), func(b'')) + eq(func(data, wrapcol=sys.maxsize), expected) + if check_impl_detail(): + eq(func(data, wrapcol=sys.maxsize*2), expected) + with self.assertRaises(OverflowError): + func(data, wrapcol=2**1000) + with self.assertRaises(ValueError): + func(data, wrapcol=-80) + with self.assertRaises(TypeError): + func(data, wrapcol=80.0) + with self.assertRaises(TypeError): + func(data, wrapcol='80') + if func is not base64.b16encode: + with self.assertRaises(TypeError): + func(data, wrapcol=None) + + def test_b64encode_wrapcol(self): + eq = self.assertEqual + b = b'www.python.org' + self._common_test_wrapcol(base64.b64encode, b) + eq(base64.b64encode(b, wrapcol=8), b'd3d3LnB5\ndGhvbi5v\ncmc=') + eq(base64.b64encode(b, wrapcol=11), b'd3d3LnB5\ndGhvbi5v\ncmc=') + eq(base64.b64encode(b, wrapcol=1), b'd3d3\nLnB5\ndGhv\nbi5v\ncmc=') + def test_b64decode(self): eq = self.assertEqual @@ -241,29 +315,100 @@ def test_b64decode_altchars(self): eq(base64.b64decode(data_str, altchars=altchars), res) eq(base64.b64decode(data, altchars=altchars_str), res) eq(base64.b64decode(data_str, altchars=altchars_str), res) + eq(base64.b64decode(data, altchars=altchars, ignorechars=b'\n'), res) + + eq(base64.b64decode(b'/----', altchars=b'-+', ignorechars=b'/'), b'\xfb\xef\xbe') + eq(base64.b64decode(b'/----', altchars=b'+-', ignorechars=b'/'), b'\xff\xff\xff') + eq(base64.b64decode(b'+----', altchars=b'-/', ignorechars=b'+'), b'\xfb\xef\xbe') + eq(base64.b64decode(b'+----', altchars=b'/-', ignorechars=b'+'), b'\xff\xff\xff') + eq(base64.b64decode(b'+/+/', altchars=b'/+', ignorechars=b''), b'\xff\xef\xfe') + eq(base64.b64decode(b'/+/+', altchars=b'+/', ignorechars=b''), b'\xff\xef\xfe') + + self.assertRaises(ValueError, base64.b64decode, b'', altchars=b'+') + self.assertRaises(ValueError, base64.b64decode, b'', altchars=b'+/-') + self.assertRaises(ValueError, base64.b64decode, '', altchars='+') + self.assertRaises(ValueError, base64.b64decode, '', altchars='+/-') def test_b64decode_padding_error(self): self.assertRaises(binascii.Error, base64.b64decode, b'abc') self.assertRaises(binascii.Error, base64.b64decode, 'abc') + def test_b64decode_padded(self): + b64decode = base64.b64decode + urlsafe_b64decode = base64.urlsafe_b64decode + def check(data, expected, padded=0): + if b'=' in data: + with self.assertRaisesRegex(binascii.Error, 'Padding not allowed'): + b64decode(data, padded=False, validate=True) + self.assertEqual(b64decode(data, padded=False, ignorechars=b'='), + expected) + self.assertEqual(urlsafe_b64decode(data, padded=True), expected) + self.assertEqual(urlsafe_b64decode(data, padded=False), expected) + data = data.replace(b'=', b'') + self.assertEqual(b64decode(data, padded=False), expected) + self.assertEqual(b64decode(data, padded=False, validate=True), + expected) + self.assertEqual(urlsafe_b64decode(data), expected) + + check(b'', b'') + check(b'YQ==', b'a') + check(b'YWI=', b'ab') + check(b'YWJj', b'abc') + check(b'Y=WJj', b'abc') + check(b'YW=Jj', b'abc') + check(b'YWJ=j', b'abc') + + with self.assertRaisesRegex(binascii.Error, 'Incorrect padding'): + urlsafe_b64decode(b'YQ', padded=True) + with self.assertRaisesRegex(binascii.Error, 'Incorrect padding'): + urlsafe_b64decode(b'YWI', padded=True) + + def _common_test_ignorechars(self, func): + eq = self.assertEqual + eq(func(b'', ignorechars=b' \n'), b'') + eq(func(b'', ignorechars=b''), b'') + eq(func(b' \n', ignorechars=b' \n'), b'') + with self.assertRaises(binascii.Error): + func(b' \n', ignorechars=b'') + with self.assertRaises(binascii.Error): + func(b' \n', ignorechars=b' ') + with self.assertRaises(binascii.Error): + func(b' \n', ignorechars=b'\n') + with self.assertRaises(TypeError): + func(b'', ignorechars='') + with self.assertRaises(TypeError): + func(b'', ignorechars=[]) + with self.assertRaises(TypeError): + func(b'', ignorechars=None) + def test_b64decode_invalid_chars(self): # issue 1466065: Test some invalid characters. - tests = ((b'%3d==', b'\xdd'), - (b'$3d==', b'\xdd'), - (b'[==', b''), - (b'YW]3=', b'am'), - (b'3{d==', b'\xdd'), - (b'3d}==', b'\xdd'), - (b'@@', b''), - (b'!', b''), - (b"YWJj\n", b"abc"), - (b'YWJj\nYWI=', b'abcab')) + tests = ((b'%3d==', b'\xdd', b'%$'), + (b'$3d==', b'\xdd', b'%$'), + (b'[==', b'', b'[='), + (b'YW]3=', b'am', b']'), + (b'3{d==', b'\xdd', b'{}'), + (b'3d}==', b'\xdd', b'{}'), + (b'@@', b'', b'@!'), + (b'!', b'', b'@!'), + (b"YWJj\n", b"abc", b'\n'), + (b'YWJj\nYWI=', b'abcab', b'\n'), + (b'=YWJj', b'abc', b'='), + (b'Y=WJj', b'abc', b'='), + (b'Y==WJj', b'abc', b'='), + (b'Y===WJj', b'abc', b'='), + (b'YW=Jj', b'abc', b'='), + (b'YWJj=', b'abc', b'='), + (b'YW\nJj', b'abc', b'\n'), + (b'YW\nJj', b'abc', bytearray(b'\n')), + (b'YW\nJj', b'abc', memoryview(b'\n')), + ) funcs = ( base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, ) - for bstr, res in tests: + for bstr, res, ignorechars in tests: for func in funcs: with self.subTest(bstr=bstr, func=func): self.assertEqual(func(bstr), res) @@ -272,14 +417,111 @@ def test_b64decode_invalid_chars(self): base64.b64decode(bstr, validate=True) with self.assertRaises(binascii.Error): base64.b64decode(bstr.decode('ascii'), validate=True) - - # Normal alphabet characters not discarded when alternative given - res = b'\xfb\xef\xff' - self.assertEqual(base64.b64decode(b'++//', validate=True), res) - self.assertEqual(base64.b64decode(b'++//', '-_', validate=True), res) - self.assertEqual(base64.b64decode(b'--__', '-_', validate=True), res) - self.assertEqual(base64.urlsafe_b64decode(b'++//'), res) - self.assertEqual(base64.urlsafe_b64decode(b'--__'), res) + with self.assertRaises(binascii.Error): + # Even empty ignorechars enables the strict mode. + base64.b64decode(bstr, ignorechars=b'') + r = base64.b64decode(bstr, ignorechars=ignorechars) + self.assertEqual(r, res) + + self._common_test_ignorechars(base64.b64decode) + + # Normal alphabet characters will be discarded when alternative given + discarded = ("invalid character %a in Base64 data with %s " + "will be discarded in future Python versions") + error = ("invalid character %a in Base64 data with %s " + "will be an error in future Python versions") + with self.assertWarns(FutureWarning) as cm: + r = base64.b64decode(b'++++', altchars=b'-_') + self.assertEqual(r, b'\xfb\xef\xbe') + self.assertEqual(str(cm.warning), + discarded % ('+', "altchars=b'-_' and validate=False")) + with self.assertWarns(FutureWarning) as cm: + r = base64.b64decode(b'////', altchars=b'-_') + self.assertEqual(r, b'\xff\xff\xff') + self.assertEqual(str(cm.warning), + discarded % ('/', "altchars=b'-_' and validate=False")) + with self.assertWarns(DeprecationWarning) as cm: + r = base64.b64decode(b'++++', altchars=b'-_', validate=True) + self.assertEqual(r, b'\xfb\xef\xbe') + self.assertEqual(str(cm.warning), + error % ('+', "altchars=b'-_' and validate=True")) + with self.assertWarns(DeprecationWarning) as cm: + r = base64.b64decode(b'////', altchars=b'-_', validate=True) + self.assertEqual(r, b'\xff\xff\xff') + self.assertEqual(str(cm.warning), + error % ('/', "altchars=b'-_' and validate=True")) + r = base64.b64decode(b'++++', altchars=b'-_', ignorechars=b'+') + self.assertEqual(r, b'') + r = base64.b64decode(b'////', altchars=b'-_', ignorechars=b'/') + self.assertEqual(r, b'') + r = base64.b64decode(b'++++////', altchars=b'-_', validate=False, ignorechars=b'') + self.assertEqual(r, b'') + with self.assertRaisesRegex(binascii.Error, 'Only base64 data is allowed'): + base64.b64decode(b'////', altchars=b'-_', ignorechars=b'') + with self.assertRaisesRegex(binascii.Error, 'Only base64 data is allowed'): + base64.b64decode(b'++++', altchars=b'-_', ignorechars=b'') + r = base64.b64decode(b'++++YWJj----____', altchars=b'-_', ignorechars=b'+') + self.assertEqual(r, b'abc\xfb\xef\xbe\xff\xff\xff') + r = base64.b64decode(b'////YWJj----____', altchars=b'-_', ignorechars=b'/') + self.assertEqual(r, b'abc\xfb\xef\xbe\xff\xff\xff') + r = base64.b64decode(b'++++,,,,', altchars=b'+,', ignorechars=b'+') + self.assertEqual(r, b'\xfb\xef\xbe\xff\xff\xff') + r = base64.b64decode(b'////YWJj++++,,,,', altchars=b'+,', ignorechars=b'/') + self.assertEqual(r, b'abc\xfb\xef\xbe\xff\xff\xff') + r = base64.b64decode(b'----////', altchars=b'-/', ignorechars=b'/') + self.assertEqual(r, b'\xfb\xef\xbe\xff\xff\xff') + r = base64.b64decode(b'++++YWJj----////', altchars=b'-/', ignorechars=b'+') + self.assertEqual(r, b'abc\xfb\xef\xbe\xff\xff\xff') + + with self.assertWarns(FutureWarning) as cm: + self.assertEqual(base64.urlsafe_b64decode(b'++++'), b'\xfb\xef\xbe') + self.assertEqual(str(cm.warning), + "invalid character '+' in URL-safe Base64 data " + "will be discarded in future Python versions") + with self.assertWarns(FutureWarning) as cm: + self.assertEqual(base64.urlsafe_b64decode(b'////'), b'\xff\xff\xff') + self.assertEqual(str(cm.warning), + "invalid character '/' in URL-safe Base64 data " + "will be discarded in future Python versions") + with self.assertRaises(binascii.Error): + base64.b64decode(b'+/!', altchars=b'-_') + + def _altchars_strategy(): + """Generate 'altchars' for base64 encoding.""" + reserved_chars = (string.digits + string.ascii_letters + "=").encode() + allowed_chars = hypothesis.strategies.sampled_from( + [n for n in range(256) if n not in reserved_chars]) + two_bytes_strategy = hypothesis.strategies.lists( + allowed_chars, min_size=2, max_size=2, unique=True).map(bytes) + return (hypothesis.strategies.none() + | hypothesis.strategies.just(b"_-") + | two_bytes_strategy) + + @hypothesis.given( + payload=hypothesis.strategies.binary(), + altchars=_altchars_strategy(), + validate=hypothesis.strategies.booleans()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', b"_-", True) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', b"_-", False) + def test_b64_encode_decode_round_trip(self, payload, altchars, validate): + encoded = base64.b64encode(payload, altchars=altchars) + decoded = base64.b64decode(encoded, altchars=altchars, + validate=validate) + self.assertEqual(payload, decoded) + + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz') + def test_standard_b64_encode_decode_round_trip(self, payload): + encoded = base64.standard_b64encode(payload) + decoded = base64.standard_b64decode(encoded) + self.assertEqual(payload, decoded) + + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz') + def test_urlsafe_b64_encode_decode_round_trip(self, payload): + encoded = base64.urlsafe_b64encode(payload) + decoded = base64.urlsafe_b64decode(encoded) + self.assertEqual(payload, decoded) def test_b32encode(self): eq = self.assertEqual @@ -294,6 +536,23 @@ def test_b32encode(self): self.check_other_types(base64.b32encode, b'abcd', b'MFRGGZA=') self.check_encode_type_errors(base64.b32encode) + def test_b32encode_padded(self): + b32encode = base64.b32encode + self.assertEqual(b32encode(b'', padded=False), b'') + self.assertEqual(b32encode(b'a', padded=False), b'ME') + self.assertEqual(b32encode(b'ab', padded=False), b'MFRA') + self.assertEqual(b32encode(b'abc', padded=False), b'MFRGG') + self.assertEqual(b32encode(b'abcd', padded=False), b'MFRGGZA') + self.assertEqual(b32encode(b'abcde', padded=False), b'MFRGGZDF') + + def test_b32encode_wrapcol(self): + eq = self.assertEqual + b = b'www.python.org' + self._common_test_wrapcol(base64.b32encode, b) + eq(base64.b32encode(b, wrapcol=16), b'O53XOLTQPF2GQ33O\nFZXXEZY=') + eq(base64.b32encode(b, wrapcol=23), b'O53XOLTQPF2GQ33O\nFZXXEZY=') + eq(base64.b32encode(b, wrapcol=1), b'O53XOLTQ\nPF2GQ33O\nFZXXEZY=') + def test_b32decode(self): eq = self.assertEqual tests = {b'': b'', @@ -329,6 +588,7 @@ def test_b32decode_casefold(self): for data, res in tests.items(): eq(base64.b32decode(data, True), res) + eq(base64.b32decode(data, casefold=True), res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') @@ -347,6 +607,11 @@ def test_b32decode_map01(self): self.assertRaises(binascii.Error, base64.b32decode, b'M1O23456') self.assertRaises(binascii.Error, base64.b32decode, b'ML023456') self.assertRaises(binascii.Error, base64.b32decode, b'MI023456') + self.assertRaises(ValueError, base64.b32decode, b'', map01=b'') + self.assertRaises(ValueError, base64.b32decode, b'', map01=b'LI') + self.assertRaises(TypeError, base64.b32decode, b'', map01=0) + eq(base64.b32decode(b'MLO23456', map01=None), res_L) + self.assertRaises(binascii.Error, base64.b32decode, b'M1023456', map01=None) data = b'M1023456' data_str = data.decode('ascii') @@ -362,6 +627,56 @@ def test_b32decode_map01(self): eq(base64.b32decode(b'M%c023456' % map01, map01=map01), res) eq(base64.b32decode(b'M%cO23456' % map01, map01=map01), res) + def test_b32decode_padded(self): + b32decode = base64.b32decode + def check(data, expected): + if b'=' in data: + with self.assertRaisesRegex(binascii.Error, 'Padding not allowed'): + b32decode(data, padded=False) + self.assertEqual(b32decode(data, padded=False, ignorechars=b'='), + expected) + data = data.replace(b'=', b'') + self.assertEqual(b32decode(data, padded=False), expected) + + check(b'', b'') + check(b'ME======', b'a') + check(b'MFRA====', b'ab') + check(b'MFRGG===', b'abc') + check(b'MFRGGZA=', b'abcd') + check(b'MFRGGZDF', b'abcde') + check(b'M=FRGGZDF', b'abcde') + check(b'MF=RGGZDF', b'abcde') + check(b'MFR=GGZDF', b'abcde') + check(b'MFRG=GZDF', b'abcde') + check(b'MFRGG=ZDF', b'abcde') + check(b'MFRGGZ=DF', b'abcde') + check(b'MFRGGZD=F', b'abcde') + + def test_b32decode_ignorechars(self): + self._common_test_ignorechars(base64.b32decode) + eq = self.assertEqual + eq(base64.b32decode(b'MFRG\n GZDF\n', ignorechars=b' \n'), b'abcde') + eq(base64.b32decode(b'MFRG\n GZDF\n', ignorechars=bytearray(b' \n')), b'abcde') + eq(base64.b32decode(b'M=======FRGGZDF', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MF======RGGZDF', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MFR=====GGZDF', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MFRG====GZDF', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MFRGG===ZDF', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MFRGGZ==DF', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MFRGGZD=F', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MFRGGZDF=', ignorechars=b'='), b'abcde') + eq(base64.b32decode(b'MFRA======', ignorechars=b'='), b'ab') + + eq(base64.b32decode(b'mfRggzDfmzTQ====', ignorechars=b'mfgz'), + b'\x88\xe7') + eq(base64.b32decode(b'mfRggzDfmzTQ====', casefold=True, ignorechars=b'mfgz'), + b'abcdefg') + eq(base64.b32decode(b'M0F1R0G1G0Z1D0F1', ignorechars=b'01'), b'abcde') + eq(base64.b32decode(b'M0F1R0G1G0Z1D0F1', map01=b'L', ignorechars=b'01'), + b'c\x8a\xb8\xb8\xcb3\xb2\xb1\xb8\xab') + eq(base64.b32decode(b'M0F1R0G1G0Z1D0F1', map01=b'I', ignorechars=b'01'), + b'c\x8a\x88\xb8\xc83\xb2\x81\xb8\xa8') + def test_b32decode_error(self): tests = [b'abc', b'ABCDEF==', b'==ABCDEF'] prefixes = [b'M', b'ME', b'MFRA', b'MFRGG', b'MFRGGZA', b'MFRGGZDF'] @@ -378,6 +693,19 @@ def test_b32decode_error(self): with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii')) + @hypothesis.given( + payload=hypothesis.strategies.binary(), + casefold=hypothesis.strategies.booleans(), + map01=( + hypothesis.strategies.none() + | hypothesis.strategies.binary(min_size=1, max_size=1))) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', True, None) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', False, None) + def test_b32_encode_decode_round_trip(self, payload, casefold, map01): + encoded = base64.b32encode(payload) + decoded = base64.b32decode(encoded, casefold=casefold, map01=map01) + self.assertEqual(payload, decoded) + def test_b32hexencode(self): test_cases = [ # to_encode, expected @@ -392,11 +720,21 @@ def test_b32hexencode(self): for to_encode, expected in test_cases: with self.subTest(to_decode=to_encode): self.assertEqual(base64.b32hexencode(to_encode), expected) + self.assertEqual(base64.b32hexencode(to_encode, padded=False), + expected.rstrip(b'=')) def test_b32hexencode_other_types(self): self.check_other_types(base64.b32hexencode, b'abcd', b'C5H66P0=') self.check_encode_type_errors(base64.b32hexencode) + def test_b32hexencode_wrapcol(self): + eq = self.assertEqual + b = b'www.python.org' + self._common_test_wrapcol(base64.b32hexencode, b) + eq(base64.b32hexencode(b, wrapcol=16), b'ETRNEBJGF5Q6GRRE\n5PNN4PO=') + eq(base64.b32hexencode(b, wrapcol=23), b'ETRNEBJGF5Q6GRRE\n5PNN4PO=') + eq(base64.b32hexencode(b, wrapcol=1), b'ETRNEBJG\nF5Q6GRRE\n5PNN4PO=') + def test_b32hexdecode(self): test_cases = [ # to_decode, expected, casefold @@ -431,6 +769,53 @@ def test_b32hexdecode_other_types(self): self.check_other_types(base64.b32hexdecode, b'C5H66===', b'abc') self.check_decode_type_errors(base64.b32hexdecode) + def test_b32hexdecode_padded(self): + b32hexdecode = base64.b32hexdecode + def check(data, expected): + if b'=' in data: + with self.assertRaisesRegex(binascii.Error, 'Padding not allowed'): + b32hexdecode(data, padded=False) + self.assertEqual(b32hexdecode(data, padded=False, ignorechars=b'='), + expected) + data = data.replace(b'=', b'') + self.assertEqual(b32hexdecode(data, padded=False), expected) + + check(b'', b'') + check(b'C4======', b'a') + check(b'C5H0====', b'ab') + check(b'C5H66===', b'abc') + check(b'C5H66P0=', b'abcd') + check(b'C5H66P35', b'abcde') + check(b'C=5H66P35', b'abcde') + check(b'C5=H66P35', b'abcde') + check(b'C5H=66P35', b'abcde') + check(b'C5H6=6P35', b'abcde') + check(b'C5H66=P35', b'abcde') + check(b'C5H66P=35', b'abcde') + check(b'C5H66P3=5', b'abcde') + + def test_b32hexdecode_ignorechars(self): + self._common_test_ignorechars(base64.b32hexdecode) + eq = self.assertEqual + eq(base64.b32hexdecode(b'C5H6\n 6P35\n', ignorechars=b' \n'), b'abcde') + eq(base64.b32hexdecode(b'C5H6\n 6P35\n', ignorechars=bytearray(b' \n')), b'abcde') + eq(base64.b32hexdecode(b'========C5H66P35', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C=======5H66P35', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5======H66P35', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5H=====66P35', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5H6====6P35', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5H66===P35', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5H66P==35', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5H66P3=5', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5H66P35=', ignorechars=b'='), b'abcde') + eq(base64.b32hexdecode(b'C5H0======', ignorechars=b'='), b'ab') + + eq(base64.b32hexdecode(b'c5h66p35cpjmg===', ignorechars=b'cghjmp'), + b')\x8c2') + eq(base64.b32hexdecode(b'c5h66p35cpjmg===', casefold=True, + ignorechars=b'cghjmp'), + b'abcdefgh') + def test_b32hexdecode_error(self): tests = [b'abc', b'ABCDEF==', b'==ABCDEF', b'c4======'] prefixes = [b'M', b'ME', b'MFRA', b'MFRGG', b'MFRGGZA', b'MFRGGZDF'] @@ -447,6 +832,15 @@ def test_b32hexdecode_error(self): with self.assertRaises(binascii.Error): base64.b32hexdecode(data.decode('ascii')) + @hypothesis.given( + payload=hypothesis.strategies.binary(), + casefold=hypothesis.strategies.booleans()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', True) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', False) + def test_b32_hexencode_decode_round_trip(self, payload, casefold): + encoded = base64.b32hexencode(payload) + decoded = base64.b32hexdecode(encoded, casefold=casefold) + self.assertEqual(payload, decoded) def test_b16encode(self): eq = self.assertEqual @@ -457,6 +851,14 @@ def test_b16encode(self): b'0102ABCDEF') self.check_encode_type_errors(base64.b16encode) + def test_b16encode_wrapcol(self): + eq = self.assertEqual + b = b'\x01\x02\xab\xcd\xef' + self._common_test_wrapcol(base64.b16encode, b) + eq(base64.b16encode(b, wrapcol=4), b'0102\nABCD\nEF') + eq(base64.b16encode(b, wrapcol=5), b'0102\nABCD\nEF') + eq(base64.b16encode(b, wrapcol=1), b'01\n02\nAB\nCD\nEF') + def test_b16decode(self): eq = self.assertEqual eq(base64.b16decode(b'0102ABCDEF'), b'\x01\x02\xab\xcd\xef') @@ -484,6 +886,24 @@ def test_b16decode(self): # Incorrect "padding" self.assertRaises(binascii.Error, base64.b16decode, '010') + def test_b16decode_ignorechars(self): + self._common_test_ignorechars(base64.b16decode) + eq = self.assertEqual + eq(base64.b16decode(b'A B\nC D\n', ignorechars=b' \n'), b'\xab\xcd') + eq(base64.b16decode(b'A B\nC D\n', ignorechars=bytearray(b' \n')), b'\xab\xcd') + eq(base64.b16decode(b'aBcD', ignorechars=b'ac'), b'\xbd') + eq(base64.b16decode(b'aBcD', casefold=True, ignorechars=b'ac'), b'\xab\xcd') + + @hypothesis.given( + payload=hypothesis.strategies.binary(), + casefold=hypothesis.strategies.booleans()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', True) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', False) + def test_b16_encode_decode_round_trip(self, payload, casefold): + endoded = base64.b16encode(payload) + decoded = base64.b16decode(endoded, casefold=casefold) + self.assertEqual(payload, decoded) + def test_a85encode(self): eq = self.assertEqual @@ -522,18 +942,33 @@ def test_a85encode(self): self.assertRaises(TypeError, base64.a85encode, "") - eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=False), - b'GB\\6`E-\nZP=Df.1\nGEb>') - eq(base64.a85encode(b"\0\0\0\0www.python.org", wrapcol=7, adobe=False), - b'zGB\\6`E\n-ZP=Df.\n1GEb>') - eq(base64.a85encode(b"www.python.org", wrapcol=7, adobe=True), - b'<~GB\\6`\nE-ZP=Df\n.1GEb>\n~>') - eq(base64.a85encode(b' '*8, foldspaces=True, adobe=False), b'yy') eq(base64.a85encode(b' '*7, foldspaces=True, adobe=False), b'y+') + eq(base64.a85encode(b"\0\0\0\0www.python.org", wrapcol=7), + b'zGB\\6`E\n-ZP=Df.\n1GEb>') + eq(base64.a85encode(b, wrapcol=75), b'GB\\6`E-ZP=Df.1GEb>') + eq(base64.a85encode(b, wrapcol=1), + b'G\nB\n\\\n6\n`\nE\n-\nZ\nP\n=\nD\nf\n.\n1\nG\nE\nb\n>') + eq(base64.a85encode(b, wrapcol=7, adobe=True), + b'<~GB\\6`\nE-ZP=Df\n.1GEb>\n~>') + eq(base64.a85encode(b, wrapcol=1), + b'G\nB\n\\\n6\n`\nE\n-\nZ\nP\n=\nD\nf\n.\n1\nG\nE\nb\n>') + eq(base64.a85encode(b, wrapcol=1, adobe=True), + b'<~\nGB\n\\6\n`E\n-Z\nP=\nDf\n.1\nGE\nb>\n~>') + with self.assertRaises(ValueError): + base64.a85encode(b, wrapcol=-7, adobe=True) + eq(base64.a85encode(b'', wrapcol=1, adobe=True), b'<~\n~>') + eq(base64.a85encode(b'', wrapcol=3, adobe=True), b'<~\n~>') + eq(base64.a85encode(b'', wrapcol=4, adobe=True), b'<~~>') + def test_b85encode(self): eq = self.assertEqual @@ -568,11 +1003,20 @@ def test_b85encode(self): self.check_other_types(base64.b85encode, b"www.python.org", b'cXxL#aCvlSZ*DGca%T') + def test_b85encode_wrapcol(self): + eq = self.assertEqual + b = b'www.python.org' + self._common_test_wrapcol(base64.b85encode, b) + eq(base64.b85encode(b, wrapcol=10), b'cXxL#aCvlS\nZ*DGca%T') + eq(base64.b85encode(b, wrapcol=14), b'cXxL#aCvlS\nZ*DGca%T') + eq(base64.b85encode(b, wrapcol=1), b'cXxL#\naCvlS\nZ*DGc\na%T') + def test_z85encode(self): eq = self.assertEqual tests = { b'': b'', + b'\x86\x4F\xD2\x6F\xB5\x59\xF7\x5B': b'HelloWorld', b'www.python.org': b'CxXl-AcVLsz/dgCA+t', bytes(range(255)): b"""009c61o!#m2NH?C3>iWS5d]J*6CRx17-skh9337x""" b"""ar.{NbQB=+c[cR@eg&FcfFLssg=mfIi5%2YjuU>)kTv.7l}6Nnnj=AD""" @@ -602,6 +1046,14 @@ def test_z85encode(self): self.check_other_types(base64.z85encode, b"www.python.org", b'CxXl-AcVLsz/dgCA+t') + def test_z85encode_wrapcol(self): + eq = self.assertEqual + b = b'www.python.org' + self._common_test_wrapcol(base64.z85encode, b) + eq(base64.z85encode(b, wrapcol=10), b'CxXl-AcVLs\nz/dgCA+t') + eq(base64.z85encode(b, wrapcol=14), b'CxXl-AcVLs\nz/dgCA+t') + eq(base64.z85encode(b, wrapcol=1), b'CxXl-\nAcVLs\nz/dgC\nA+t') + def test_a85decode(self): eq = self.assertEqual @@ -733,6 +1185,12 @@ def test_a85_padding(self): eq(base64.a85decode(b'G^+IX'), b"xxxx") eq(base64.a85decode(b'G^+IXGQ7^D'), b"xxxxx\x00\x00\x00") + eq(base64.a85encode(b"\x00", pad=True), b'z') + eq(base64.a85encode(b"\x00"*2, pad=True), b'z') + eq(base64.a85encode(b"\x00"*3, pad=True), b'z') + eq(base64.a85encode(b"\x00"*4, pad=True), b'z') + eq(base64.a85encode(b"\x00"*5, pad=True), b'zz') + def test_b85_padding(self): eq = self.assertEqual @@ -748,6 +1206,21 @@ def test_b85_padding(self): eq(base64.b85decode(b'czAet'), b"xxxx") eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00") + def test_z85_padding(self): + eq = self.assertEqual + + eq(base64.z85encode(b"x", pad=True), b'CMmZz') + eq(base64.z85encode(b"xx", pad=True), b'CZ6h*') + eq(base64.z85encode(b"xxx", pad=True), b'CZaDk') + eq(base64.z85encode(b"xxxx", pad=True), b'CZaET') + eq(base64.z85encode(b"xxxxx", pad=True), b'CZaETCMmZz') + + eq(base64.z85decode(b'CMmZz'), b"x\x00\x00\x00") + eq(base64.z85decode(b'CZ6h*'), b"xx\x00\x00") + eq(base64.z85decode(b'CZaDk'), b"xxx\x00") + eq(base64.z85decode(b'CZaET'), b"xxxx") + eq(base64.z85decode(b'CZaETCMmZz'), b"xxxxx\x00\x00\x00") + def test_a85decode_errors(self): illegal = (set(range(32)) | set(range(118, 256))) - set(b' \t\n\r\v') for c in illegal: @@ -787,24 +1260,20 @@ def test_a85decode_errors(self): self.assertEqual(base64.a85decode(b"a b\nc", ignorechars=b" \n"), b'\xc9\x89') - with self.assertRaises(ValueError): - base64.a85decode(b"a b\nc", ignorechars=b"") - with self.assertRaises(ValueError): - base64.a85decode(b"a b\nc", ignorechars=b" ") - with self.assertRaises(ValueError): - base64.a85decode(b"a b\nc", ignorechars=b"\n") - with self.assertRaises(TypeError): - base64.a85decode(b"a b\nc", ignorechars=" \n") - with self.assertRaises(TypeError): - base64.a85decode(b"a b\nc", ignorechars=None) + self._common_test_ignorechars(base64.a85decode) def test_b85decode_errors(self): illegal = list(range(33)) + \ list(b'"\',./:[\\]') + \ list(range(128, 256)) for c in illegal: - with self.assertRaises(ValueError, msg=bytes([c])): - base64.b85decode(b'0000' + bytes([c])) + b = bytes([c]) + with self.assertRaises(ValueError, msg=b): + base64.b85decode(b'0000' + b) + self.assertEqual(base64.b85decode(b'0000' + b, ignorechars=b), + b'\x00\x00\x00') + + self._common_test_ignorechars(base64.b85decode) self.assertRaises(ValueError, base64.b85decode, b'|') self.assertRaises(ValueError, base64.b85decode, b'|N') @@ -817,8 +1286,13 @@ def test_z85decode_errors(self): list(b'"\',;_`|\\~') + \ list(range(128, 256)) for c in illegal: - with self.assertRaises(ValueError, msg=bytes([c])): - base64.z85decode(b'0000' + bytes([c])) + b = bytes([c]) + with self.assertRaises(ValueError, msg=b): + base64.z85decode(b'0000' + b) + self.assertEqual(base64.z85decode(b'0000' + b, ignorechars=b), + b'\x00\x00\x00') + + self._common_test_ignorechars(base64.z85decode) # b'\xff\xff\xff\xff' encodes to b'%nSc0', the following will overflow: self.assertRaises(ValueError, base64.z85decode, b'%') @@ -827,6 +1301,61 @@ def test_z85decode_errors(self): self.assertRaises(ValueError, base64.z85decode, b'%nSc') self.assertRaises(ValueError, base64.z85decode, b'%nSc1') + def add_padding(self, payload): + """Add the expected padding for test_?85_encode_decode_round_trip.""" + if len(payload) % 4 != 0: + padding = b"\0" * ((-len(payload)) % 4) + payload = payload + padding + return payload + + @hypothesis.given( + payload=hypothesis.strategies.binary(), + foldspaces=hypothesis.strategies.booleans(), + wrapcol=( + hypothesis.strategies.just(0) + | hypothesis.strategies.integers(1, 1000)), + pad=hypothesis.strategies.booleans(), + adobe=hypothesis.strategies.booleans(), + ) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', False, 0, False, False) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', False, 20, True, True) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', True, 0, False, True) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', True, 20, True, False) + def test_a85_encode_decode_round_trip( + self, payload, foldspaces, wrapcol, pad, adobe + ): + encoded = base64.a85encode( + payload, foldspaces=foldspaces, wrapcol=wrapcol, + pad=pad, adobe=adobe, + ) + if wrapcol: + if adobe and wrapcol == 1: + # "adobe" needs wrapcol to be at least 2. + # a85decode quietly uses 2 if 1 is given; it's not worth + # loudly deprecating this behavior. + wrapcol = 2 + for line in encoded.splitlines(keepends=False): + self.assertLessEqual(len(line), wrapcol) + if adobe: + self.assertTrue(encoded.startswith(b'<~')) + self.assertTrue(encoded.endswith(b'~>')) + decoded = base64.a85decode(encoded, foldspaces=foldspaces, adobe=adobe) + if pad: + payload = self.add_padding(payload) + self.assertEqual(payload, decoded) + + @hypothesis.given( + payload=hypothesis.strategies.binary(), + pad=hypothesis.strategies.booleans()) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', True) + @hypothesis.example(b'abcdefghijklmnopqrstuvwxyz', False) + def test_b85_encode_decode_round_trip(self, payload, pad): + encoded = base64.b85encode(payload, pad=pad) + if pad: + payload = self.add_padding(payload) + decoded = base64.b85decode(encoded) + self.assertEqual(payload, decoded) + def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, diff --git a/Lib/test/test_bdb.py b/Lib/test/test_bdb.py index 590d8166b68..6a1df6e083e 100644 --- a/Lib/test/test_bdb.py +++ b/Lib/test/test_bdb.py @@ -728,7 +728,6 @@ def test_until_in_caller_frame(self): with TracerRun(self) as tracer: tracer.runcall(tfunc_main) - @unittest.skipIf(hasattr(__import__("sys"), "addaudithook"), "TODO: RUSTPYTHON; Currently no conditional tracing toggle") @patch_list(sys.meta_path) def test_skip(self): # Check that tracing is skipped over the import statement in @@ -966,6 +965,17 @@ def main(): with TracerRun(self) as tracer: tracer.runcall(tfunc_import) + def test_clear_all_file_breaks_same_line(self): + reset_Breakpoint() + self.addCleanup(reset_Breakpoint) + debugger = Bdb() + for _ in range(3): + self.assertIsNone(debugger.set_break(__file__, 1)) + self.assertIsNone(debugger.clear_all_file_breaks(__file__)) + self.assertEqual(debugger.get_all_breaks(), {}) + self.assertEqual(_bdb.Breakpoint.bplist, {}) + self.assertTrue(all(bp is None for bp in _bdb.Breakpoint.bpbynumber)) + def test_clear_at_no_bp(self): self.expect_set = [ ('line', 2, 'tfunc_import'), ('clear', (__file__, 1)) diff --git a/Lib/test/test_bigmem.py b/Lib/test/test_bigmem.py index 7f53379a952..3c09cdb8640 100644 --- a/Lib/test/test_bigmem.py +++ b/Lib/test/test_bigmem.py @@ -901,7 +901,7 @@ def test_repeat_small(self, size): def test_repeat_large(self, size): return self.basic_test_repeat(size) - @bigmemtest(size=_1G - 1, memuse=12) + @bigmemtest(size=_1G - 1, memuse=pointer_size * 3) def test_repeat_large_2(self, size): return self.basic_test_repeat(size) diff --git a/Lib/test/test_binascii.py b/Lib/test/test_binascii.py index 82eabf4bb06..cedbdc61f18 100644 --- a/Lib/test/test_binascii.py +++ b/Lib/test/test_binascii.py @@ -4,14 +4,17 @@ import binascii import array import re -from test.support import bigmemtest, _1G, _4G +import sys +from test.support import bigmemtest, _1G, _4G, check_impl_detail from test.support.hypothesis_helper import hypothesis # Note: "*_hex" functions are aliases for "(un)hexlify" -b2a_functions = ['b2a_base64', 'b2a_hex', 'b2a_qp', 'b2a_uu', +b2a_functions = ['b2a_ascii85', 'b2a_base32', 'b2a_base64', 'b2a_base85', + 'b2a_hex', 'b2a_qp', 'b2a_uu', 'hexlify'] -a2b_functions = ['a2b_base64', 'a2b_hex', 'a2b_qp', 'a2b_uu', +a2b_functions = ['a2b_ascii85', 'a2b_base32', 'a2b_base64', 'a2b_base85', + 'a2b_hex', 'a2b_qp', 'a2b_uu', 'unhexlify'] all_functions = a2b_functions + b2a_functions + ['crc32', 'crc_hqx'] @@ -23,6 +26,8 @@ class BinASCIITest(unittest.TestCase): rawdata = b"The quick brown fox jumps over the lazy dog.\r\n" # Be slow so we don't depend on other modules rawdata += bytes(range(256)) + rawdata += b'\0'*32 + rawdata += b' '*32 rawdata += b"\r\nHello world.\n" def setUp(self): @@ -41,6 +46,40 @@ def test_exceptions(self): self.assertIsSubclass(binascii.Error, Exception) self.assertIsSubclass(binascii.Incomplete, Exception) + def test_constants(self): + self.assertEqual(binascii.BASE64_ALPHABET, + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + b'abcdefghijklmnopqrstuvwxyz' + b'0123456789+/') + self.assertEqual(binascii.URLSAFE_BASE64_ALPHABET, + binascii.BASE64_ALPHABET[:-2] + b'-_') + self.assertEqual(binascii.UU_ALPHABET, bytes(range(32, 32+64))) + self.assertEqual(binascii.CRYPT_ALPHABET, + b'./0123456789' + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + b'abcdefghijklmnopqrstuvwxyz') + self.assertEqual(binascii.BINHEX_ALPHABET, + b'!"#$%&\'()*+,-012345689' + b'@ABCDEFGHIJKLMNPQRSTUVXYZ[' + b'`abcdefhijklmpqr') + + self.assertEqual(binascii.BASE85_ALPHABET, + b'0123456789' + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + b'abcdefghijklmnopqrstuvwxyz' + b'!#$%&()*+-;<=>?@^_`{|}~') + self.assertEqual(binascii.ASCII85_ALPHABET, bytes(range(33, 33+85))) + self.assertEqual(binascii.Z85_ALPHABET, + b'0123456789' + b'abcdefghijklmnopqrstuvwxyz' + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ' + b'.-:+=^!/*?&<>()[]{}@%$#') + + self.assertEqual(binascii.BASE32_ALPHABET, + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567') + self.assertEqual(binascii.BASE32HEX_ALPHABET, + b'0123456789ABCDEFGHIJKLMNOPQRSTUV') + def test_functions(self): # Check presence of all functions for name in all_functions: @@ -117,62 +156,170 @@ def addnoise(line): # empty strings. TBD: shouldn't it raise an exception instead ? self.assertEqual(binascii.a2b_base64(self.type2test(fillers)), b'') - def test_base64_strict_mode(self): - # Test base64 with strict mode on - def _assertRegexTemplate(assert_regex: str, data: bytes, non_strict_mode_expected_result: bytes): + def test_base64_bad_padding(self): + # Test malformed padding + def _assertRegexTemplate(assert_regex, data, + non_strict_mode_expected_result, **kwargs): + data = self.type2test(data) with self.assertRaisesRegex(binascii.Error, assert_regex): - binascii.a2b_base64(self.type2test(data), strict_mode=True) - self.assertEqual(binascii.a2b_base64(self.type2test(data), strict_mode=False), + binascii.a2b_base64(data, strict_mode=True, **kwargs) + self.assertEqual(binascii.a2b_base64(data, strict_mode=False), non_strict_mode_expected_result) - self.assertEqual(binascii.a2b_base64(self.type2test(data)), + self.assertEqual(binascii.a2b_base64(data, strict_mode=True, + ignorechars=b' ='), + non_strict_mode_expected_result) + self.assertEqual(binascii.a2b_base64(data), non_strict_mode_expected_result) - def assertExcessData(data, non_strict_mode_expected_result: bytes): - _assertRegexTemplate(r'(?i)Excess data', data, non_strict_mode_expected_result) - - def assertNonBase64Data(data, non_strict_mode_expected_result: bytes): - _assertRegexTemplate(r'(?i)Only base64 data', data, non_strict_mode_expected_result) + def assertLeadingPadding(*args, **kwargs): + _assertRegexTemplate(r'(?i)Leading padding', *args, **kwargs) - def assertLeadingPadding(data, non_strict_mode_expected_result: bytes): - _assertRegexTemplate(r'(?i)Leading padding', data, non_strict_mode_expected_result) + def assertDiscontinuousPadding(*args): + _assertRegexTemplate(r'(?i)Discontinuous padding', *args) - def assertDiscontinuousPadding(data, non_strict_mode_expected_result: bytes): - _assertRegexTemplate(r'(?i)Discontinuous padding', data, non_strict_mode_expected_result) + def assertExcessPadding(*args): + _assertRegexTemplate(r'(?i)Excess padding', *args) - def assertExcessPadding(data, non_strict_mode_expected_result: bytes): - _assertRegexTemplate(r'(?i)Excess padding', data, non_strict_mode_expected_result) + def assertInvalidLength(data, *args, length=None, **kwargs): + if length is None: + length = len(data.split(b'=', 1)[0].replace(b' ', b'')) + assert_regex = fr"(?i)Invalid.+number of data characters \({length}\)" + _assertRegexTemplate(assert_regex, data, *args, **kwargs) - # Test excess data exceptions assertExcessPadding(b'ab===', b'i') assertExcessPadding(b'ab====', b'i') - assertNonBase64Data(b'ab==:', b'i') - assertExcessData(b'abc=a', b'i\xb7\x1a') - assertNonBase64Data(b'abc=:', b'i\xb7') - assertNonBase64Data(b'ab==\n', b'i') assertExcessPadding(b'abc==', b'i\xb7') assertExcessPadding(b'abc===', b'i\xb7') assertExcessPadding(b'abc====', b'i\xb7') assertExcessPadding(b'abc=====', b'i\xb7') - # Test non-base64 data exceptions - assertNonBase64Data(b'\nab==', b'i') - assertNonBase64Data(b'ab:(){:|:&};:==', b'i') - assertNonBase64Data(b'a\nb==', b'i') - assertNonBase64Data(b'a\x00b==', b'i') - - # Test malformed padding assertLeadingPadding(b'=', b'') assertLeadingPadding(b'==', b'') assertLeadingPadding(b'===', b'') assertLeadingPadding(b'====', b'') assertLeadingPadding(b'=====', b'') + assertLeadingPadding(b'=abcd', b'i\xb7\x1d') + assertLeadingPadding(b'==abcd', b'i\xb7\x1d') + assertLeadingPadding(b'===abcd', b'i\xb7\x1d') + assertLeadingPadding(b'====abcd', b'i\xb7\x1d') + assertLeadingPadding(b'=====abcd', b'i\xb7\x1d') + assertLeadingPadding(b' =abcd', b'i\xb7\x1d', ignorechars=b' ') + + assertInvalidLength(b'a=b==', b'i') + assertInvalidLength(b'a=bc=', b'i\xb7') + assertInvalidLength(b'a=bc==', b'i\xb7') + assertInvalidLength(b'a=bcd', b'i\xb7\x1d') + assertInvalidLength(b'a=bcd=', b'i\xb7\x1d') + assertInvalidLength(b' a=b==', b'i', ignorechars=b' ') + assertInvalidLength(b'abcde=f==', b'i\xb7\x1dy') + assertInvalidLength(b' abcde=f==', b'i\xb7\x1dy', ignorechars=b' ') + assertDiscontinuousPadding(b'ab=c=', b'i\xb7') - assertDiscontinuousPadding(b'ab=ab==', b'i\xb6\x9b') + assertDiscontinuousPadding(b'ab=cd', b'i\xb7\x1d') + assertDiscontinuousPadding(b'ab=cd==', b'i\xb7\x1d') + assertExcessPadding(b'abcd=', b'i\xb7\x1d') assertExcessPadding(b'abcd==', b'i\xb7\x1d') assertExcessPadding(b'abcd===', b'i\xb7\x1d') assertExcessPadding(b'abcd====', b'i\xb7\x1d') assertExcessPadding(b'abcd=====', b'i\xb7\x1d') + assertExcessPadding(b'abcd==', b'i\xb7\x1d') + assertExcessPadding(b'abcd===', b'i\xb7\x1d') + assertExcessPadding(b'abcd====', b'i\xb7\x1d') + assertExcessPadding(b'abcd=====', b'i\xb7\x1d') + assertExcessPadding(b'abcd=efgh', b'i\xb7\x1dy\xf8!') + assertExcessPadding(b'abcd==efgh', b'i\xb7\x1dy\xf8!') + assertExcessPadding(b'abcd===efgh', b'i\xb7\x1dy\xf8!') + assertExcessPadding(b'abcd====efgh', b'i\xb7\x1dy\xf8!') + assertExcessPadding(b'abcd=====efgh', b'i\xb7\x1dy\xf8!') + + def test_a2b_base64_padded(self): + a2b_base64 = binascii.a2b_base64 + t = self.type2test + def check(data, expected): + if b'=' in data: + with self.assertRaisesRegex(binascii.Error, 'Padding not allowed'): + a2b_base64(t(data), padded=False, strict_mode=True) + self.assertEqual(a2b_base64(t(data), padded=False, ignorechars=b'='), + expected) + data = data.replace(b'=', b'') + self.assertEqual(a2b_base64(t(data), padded=False), expected) + self.assertEqual(a2b_base64(t(data), padded=False, strict_mode=True), + expected) + + check(b'', b'') + check(b'YQ==', b'a') + check(b'YWI=', b'ab') + check(b'YWJj', b'abc') + check(b'Y=WJj', b'abc') + check(b'YW=Jj', b'abc') + check(b'YWJ=j', b'abc') + + def _common_test_ignorechars(self, func): + eq = self.assertEqual + empty = self.type2test(b'') + data = self.type2test(b'\n \n') + ignorechars = self.type2test(b' \n') + eq(func(empty, ignorechars=ignorechars), b'') + eq(func(empty, ignorechars=empty), b'') + eq(func(data, ignorechars=ignorechars), b'') + with self.assertRaises(binascii.Error): + func(data, ignorechars=empty) + with self.assertRaises(binascii.Error): + func(data, ignorechars=ignorechars[1:]) + with self.assertRaises(binascii.Error): + func(data, ignorechars=ignorechars[:-1]) + with self.assertRaises(TypeError): + func(empty, ignorechars='') + with self.assertRaises(TypeError): + func(empty, ignorechars=[]) + with self.assertRaises(TypeError): + func(empty, ignorechars=None) + + def test_base64_invalidchars(self): + # Test non-base64 data exceptions + self._common_test_ignorechars(binascii.a2b_base64) + def assertNonBase64Data(data, expected, ignorechars): + data = self.type2test(data) + assert_regex = r'(?i)Only base64 data' + self.assertEqual(binascii.a2b_base64(data), expected) + with self.assertRaisesRegex(binascii.Error, assert_regex): + binascii.a2b_base64(data, strict_mode=True) + with self.assertRaisesRegex(binascii.Error, assert_regex): + binascii.a2b_base64(data, ignorechars=b'') + self.assertEqual(binascii.a2b_base64(data, ignorechars=ignorechars), + expected) + self.assertEqual(binascii.a2b_base64(data, strict_mode=False, ignorechars=b''), + expected) + + assertNonBase64Data(b'\nab==', b'i', ignorechars=b'\n') + assertNonBase64Data(b'ab:(){:|:&};:==', b'i', ignorechars=b':;(){}|&') + assertNonBase64Data(b'a\nb==', b'i', ignorechars=b'\n') + assertNonBase64Data(b'a\x00b==', b'i', ignorechars=b'\x00') + assertNonBase64Data(b'ab:==', b'i', ignorechars=b':') + assertNonBase64Data(b'ab=:=', b'i', ignorechars=b':') + assertNonBase64Data(b'ab==:', b'i', ignorechars=b':') + assertNonBase64Data(b'abc=:', b'i\xb7', ignorechars=b':') + assertNonBase64Data(b'ab==\n', b'i', ignorechars=b'\n') + assertNonBase64Data(b'a\nb==', b'i', ignorechars=bytearray(b'\n')) + assertNonBase64Data(b'a\nb==', b'i', ignorechars=memoryview(b'\n')) + + self.assertEqual(binascii.a2b_base64(b'+A-/B_', ignorechars=b'+/-_'), + b'\xf8\x0f\xc1') + self.assertEqual(binascii.a2b_base64(b'+A-/B_', ignorechars=b'+/-_', + alphabet=binascii.URLSAFE_BASE64_ALPHABET), + b'\x03\xe0\x7f') + + # Same cell in the cache: '\r' >> 3 == '\n' >> 3. + data = self.type2test(b'\r\n') + with self.assertRaises(binascii.Error): + binascii.a2b_base64(data, ignorechars=b'\r') + self.assertEqual(binascii.a2b_base64(data, ignorechars=b'\r\n'), b'') + # Same bit mask in the cache: '*' & 31 == '\n' & 31. + data = self.type2test(b'*\n') + with self.assertRaises(binascii.Error): + binascii.a2b_base64(data, ignorechars=b'*') + self.assertEqual(binascii.a2b_base64(data, ignorechars=b'*\n'), b'') def test_base64_excess_data(self): # Test excess data exceptions @@ -183,6 +330,9 @@ def assertExcessData(data, expected): binascii.a2b_base64(data, strict_mode=True) self.assertEqual(binascii.a2b_base64(data, strict_mode=False), expected) + self.assertEqual(binascii.a2b_base64(data, strict_mode=True, + ignorechars=b'='), + expected) self.assertEqual(binascii.a2b_base64(data), expected) assertExcessData(b'ab==c=', b'i\xb7') @@ -191,9 +341,15 @@ def assertExcessData(data, expected): def test_base64errors(self): # Test base64 with invalid padding - def assertIncorrectPadding(data): + def assertIncorrectPadding(data, strict_mode=True): + data = self.type2test(data) + with self.assertRaisesRegex(binascii.Error, r'(?i)Incorrect padding'): + binascii.a2b_base64(data) with self.assertRaisesRegex(binascii.Error, r'(?i)Incorrect padding'): - binascii.a2b_base64(self.type2test(data)) + binascii.a2b_base64(data, strict_mode=False) + if strict_mode: + with self.assertRaisesRegex(binascii.Error, r'(?i)Incorrect padding'): + binascii.a2b_base64(data, strict_mode=True) assertIncorrectPadding(b'ab') assertIncorrectPadding(b'ab=') @@ -201,16 +357,22 @@ def assertIncorrectPadding(data): assertIncorrectPadding(b'abcdef') assertIncorrectPadding(b'abcdef=') assertIncorrectPadding(b'abcdefg') - assertIncorrectPadding(b'a=b=') - assertIncorrectPadding(b'a\nb=') + assertIncorrectPadding(b'a=b=', strict_mode=False) + assertIncorrectPadding(b'a\nb=', strict_mode=False) # Test base64 with invalid number of valid characters (1 mod 4) - def assertInvalidLength(data): + def assertInvalidLength(data, strict_mode=True): n_data_chars = len(re.sub(br'[^A-Za-z0-9/+]', br'', data)) + data = self.type2test(data) expected_errmsg_re = \ r'(?i)Invalid.+number of data characters.+' + str(n_data_chars) with self.assertRaisesRegex(binascii.Error, expected_errmsg_re): - binascii.a2b_base64(self.type2test(data)) + binascii.a2b_base64(data) + with self.assertRaisesRegex(binascii.Error, expected_errmsg_re): + binascii.a2b_base64(data, strict_mode=False) + if strict_mode: + with self.assertRaisesRegex(binascii.Error, expected_errmsg_re): + binascii.a2b_base64(data, strict_mode=True) assertInvalidLength(b'a') assertInvalidLength(b'a=') @@ -218,7 +380,911 @@ def assertInvalidLength(data): assertInvalidLength(b'a===') assertInvalidLength(b'a' * 5) assertInvalidLength(b'a' * (4 * 87 + 1)) - assertInvalidLength(b'A\tB\nC ??DE') # only 5 valid characters + assertInvalidLength(b'A\tB\nC ??DE', # only 5 valid characters + strict_mode=False) + + def test_base64_canonical(self): + # https://datatracker.ietf.org/doc/html/rfc4648.html#section-3.5 + # Decoders MAY reject encoded data if the pad bits are not zero. + + # Without canonical=True, non-zero padding bits are accepted + self.assertEqual(binascii.a2b_base64(self.type2test(b'AB==')), b'\x00') + self.assertEqual(binascii.a2b_base64(self.type2test(b'AB=='), + strict_mode=True), b'\x00') + + # 2 data chars + "==": last char has 4 padding bits + # 'A' = 0, 'B' = 1 -> leftover 0001 (non-zero) + with self.assertRaises(binascii.Error): + binascii.a2b_base64(self.type2test(b'AB=='), canonical=True) + # 'A' = 0, 'P' = 15 -> leftover 1111 (non-zero) + with self.assertRaises(binascii.Error): + binascii.a2b_base64(self.type2test(b'AP=='), canonical=True) + + # 3 data chars + "=": last char has 2 padding bits + # 'A' = 0, 'A' = 0, 'B' = 1 -> leftover 01 (non-zero) + with self.assertRaises(binascii.Error): + binascii.a2b_base64(self.type2test(b'AAB='), canonical=True) + # 'A' = 0, 'A' = 0, 'D' = 3 -> leftover 11 (non-zero) + with self.assertRaises(binascii.Error): + binascii.a2b_base64(self.type2test(b'AAD='), canonical=True) + + # Verify that zero padding bits are accepted + binascii.a2b_base64(self.type2test(b'AA=='), canonical=True) + binascii.a2b_base64(self.type2test(b'AAA='), canonical=True) + + # Full quads with no padding have no leftover bits -- always valid + binascii.a2b_base64(self.type2test(b'AAAA'), canonical=True) + + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'') + @hypothesis.example(b'\x00') + @hypothesis.example(b'\xff\xff') + @hypothesis.example(b'abc') + def test_base64_canonical_roundtrip(self, payload): + # The encoder must always produce canonical output. + encoded = binascii.b2a_base64(payload, newline=False) + decoded = binascii.a2b_base64(encoded, canonical=True) + self.assertEqual(decoded, payload) + + def test_base64_alphabet(self): + alphabet = (b'!"#$%&\'()*+,-012345689@' + b'ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr') + data = self.type2test(self.rawdata) + encoded = binascii.b2a_base64(data, alphabet=alphabet) + trans = bytes.maketrans(binascii.BASE64_ALPHABET, alphabet) + expected = binascii.b2a_base64(data).translate(trans) + self.assertEqual(encoded, expected) + self.assertEqual(binascii.a2b_base64(encoded, alphabet=alphabet), self.rawdata) + self.assertEqual(binascii.b2a_base64(data, alphabet=self.type2test(alphabet)), expected) + + data = self.type2test(b'') + self.assertEqual(binascii.b2a_base64(data, alphabet=alphabet), b'\n') + self.assertEqual(binascii.a2b_base64(data, alphabet=alphabet), b'') + + for func in binascii.b2a_base64, binascii.a2b_base64: + with self.assertRaises(TypeError): + func(data, alphabet=None) + with self.assertRaises(TypeError): + func(data, alphabet=alphabet.decode()) + with self.assertRaises(ValueError): + func(data, alphabet=alphabet[:-1]) + with self.assertRaises(ValueError): + func(data, alphabet=alphabet+b'?') + with self.assertRaises(TypeError): + binascii.a2b_base64(data, alphabet=bytearray(alphabet)) + + def test_ascii85_valid(self): + # Test Ascii85 with valid data + ASCII85_PREFIX = b"<~" + ASCII85_SUFFIX = b"~>" + + # Interleave blocks of 4 null bytes and 4 spaces into test data + rawdata = bytearray() + rawlines, i = [], 0 + for k in range(1, len(self.rawdata) + 1): + b = b"\0\0\0\0" if k & 1 else b" " + b = b + self.rawdata[i:i + k] + b = b" " if k & 1 else b"\0\0\0\0" + rawdata += b + rawlines.append(b) + i += k + if i >= len(self.rawdata): + break + + # Test core parameter combinations + params = (False, False), (False, True), (True, False), (True, True) + for foldspaces, adobe in params: + lines = [] + for rawline in rawlines: + b = self.type2test(rawline) + a = binascii.b2a_ascii85(b, foldspaces=foldspaces, adobe=adobe) + lines.append(a) + res = bytearray() + for line in lines: + a = self.type2test(line) + b = binascii.a2b_ascii85(a, foldspaces=foldspaces, adobe=adobe) + res += b + self.assertEqual(res, rawdata) + + # Inputs with length 1 mod 5 end with a 1-char group, which is + # an encoding violation per the PLRM spec. + error_params = [ + (b"a", False, False, b""), + (b"xbw", False, False, b"wx"), + (b"<~c~>", False, True, b""), + (b"{d ~>", False, True, b" {"), + (b"ye", True, False, b""), + (b"z\x01y\x00f", True, False, b"\x00\x01"), + (b"<~FCfN8yg~>", True, True, b""), + (b"FE;\x03#8zFCf\x02N8yh~>", True, True, b"\x02\x03"), + ] + for a, foldspaces, adobe, ignorechars in error_params: + kwargs = {"foldspaces": foldspaces, "adobe": adobe, "ignorechars": ignorechars} + with self.assertRaises(binascii.Error): + binascii.a2b_ascii85(self.type2test(a), **kwargs) + + def test_ascii85_invalid(self): + # Test Ascii85 with invalid characters interleaved + lines, i = [], 0 + for k in range(1, len(self.rawdata) + 1): + b = self.type2test(self.rawdata[i:i + k]) + a = binascii.b2a_ascii85(b) + lines.append(a) + i += k + if i >= len(self.rawdata): + break + + fillers = bytearray() + valid = b"!\"#$%&'()*+,-./0123456789:;<=>?@" \ + b"ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu" + b"z" + for i in range(256): + if i not in valid: + fillers.append(i) + def addnoise(line): + res = bytearray() + for i in range(len(line)): + res.append(line[i]) + for j in range(i, len(fillers), len(line)): + res.append(fillers[j]) + return res + res = bytearray() + for line in map(addnoise, lines): + a = self.type2test(line) + b = binascii.a2b_ascii85(a, ignorechars=fillers) + res += b + self.assertEqual(res, self.rawdata) + + # Test Ascii85 with only invalid characters + fillers = self.type2test(fillers) + b = binascii.a2b_ascii85(fillers, ignorechars=fillers) + self.assertEqual(b, b"") + + def test_ascii85_errors(self): + def _assertRegexTemplate(assert_regex, data, **kwargs): + with self.assertRaisesRegex(binascii.Error, assert_regex): + binascii.a2b_ascii85(self.type2test(data), **kwargs) + + def assertMissingDelimiter(data): + _assertRegexTemplate(r"(?i)end with b'~>'", data, adobe=True) + + def assertOverflow(data): + _assertRegexTemplate(r"(?i)Ascii85 overflow", data) + + def assertInvalidSpecial(data): + _assertRegexTemplate(r"(?i)'[yz]'.+5-tuple", data, foldspaces=True) + + def assertInvalidChar(data, **kwargs): + _assertRegexTemplate(r"(?i)Non-Ascii85 digit", data, **kwargs) + + # Test Ascii85 with missing delimiters + assertMissingDelimiter(b"") + assertMissingDelimiter(b"a") + assertMissingDelimiter(b"<~") + assertMissingDelimiter(b"<~!~") + assertMissingDelimiter(b"<~abc>") + assertMissingDelimiter(b"<~has delimiter but not terminal~> !") + + # Test Ascii85 with out-of-range encoded value + assertOverflow(b"t") + assertOverflow(b"s9") + assertOverflow(b"s8X") + assertOverflow(b"s8W.") + assertOverflow(b's8W-"') + assertOverflow(b"s8W-!u") + assertOverflow(b"s8W-!s8W-!zs8X") + + # Test Ascii85 with misplaced short form groups + assertInvalidSpecial(b"ay") + assertInvalidSpecial(b"az") + assertInvalidSpecial(b"aby") + assertInvalidSpecial(b"ayz") + assertInvalidSpecial(b"abcz") + assertInvalidSpecial(b"abcdy") + assertInvalidSpecial(b"y!and!z!then!!y") + + # Test Ascii85 with non-ignored invalid characters + assertInvalidChar(b"j\n") + assertInvalidChar(b" ", ignorechars=b"") + assertInvalidChar(b" valid\x02until\x03", ignorechars=b"\x00\x01\x02\x04") + assertInvalidChar(b"\tFCb", ignorechars=b"\n") + assertInvalidChar(b"xxxB\nP\thU'D v/F+", ignorechars=b" \n\tv") + + def _common_test_wrapcol(self, func): + eq = self.assertEqual + data = self.data + expected = func(data) + eq(func(data, wrapcol=0), expected) + eq(func(data, wrapcol=8000), expected) + eq(func(b'', wrapcol=0), func(b'')) + eq(func(b'', wrapcol=1), func(b'')) + eq(func(data, wrapcol=sys.maxsize), expected) + if check_impl_detail(): + eq(func(data, wrapcol=sys.maxsize*2), expected) + with self.assertRaises(OverflowError): + func(data, wrapcol=2**1000) + with self.assertRaises(ValueError): + func(data, wrapcol=-80) + with self.assertRaises(TypeError): + func(data, wrapcol=80.0) + with self.assertRaises(TypeError): + func(data, wrapcol='80') + with self.assertRaises(TypeError): + func(data, wrapcol=None) + + def test_ascii85_wrapcol(self): + # Test Ascii85 splitting lines + self._common_test_wrapcol(binascii.b2a_ascii85) + + def assertEncode(a_expected, data, n, adobe=False): + b = self.type2test(data) + a = binascii.b2a_ascii85(b, adobe=adobe, wrapcol=n) + self.assertEqual(a, a_expected) + + def assertDecode(data, b_expected, adobe=False): + a = self.type2test(data) + b = binascii.a2b_ascii85(a, adobe=adobe, ignorechars=b"\n") + self.assertEqual(b, b_expected) + + tests = [ + (b"", 0, b"", b"<~~>"), + (b"", 1, b"", b"<~\n~>"), + (b"a", 0, b"@/", b"<~@/~>"), + (b"a", 1, b"@\n/", b"<~\n@/\n~>"), + (b"a", 2, b"@/", b"<~\n@/\n~>"), + (b"a", 3, b"@/", b"<~@\n/~>"), + (b"a", 4, b"@/", b"<~@/\n~>"), + (b"a", 5, b"@/", b"<~@/\n~>"), + (b"a", 6, b"@/", b"<~@/~>"), + (b"a", 7, b"@/", b"<~@/~>"), + (b"a", 123, b"@/", b"<~@/~>"), + (b"this is a test", 7, b"FD,B0+D\nGm>@3BZ\n'F*%", + b"<~FD,B0\n+DGm>@3\nBZ'F*%\n~>"), + (b"a test!!!!!!! ", 11, b"@3BZ'F*&QK+\nX&!P+WqmM+9", + b"<~@3BZ'F*&Q\nK+X&!P+WqmM\n+9~>"), + (b"\0" * 56, 7, b"zzzzzzz\nzzzzzzz", b"<~zzzzz\nzzzzzzz\nzz~>"), + ] + for b, n, a, a_wrap in tests: + assertEncode(a, b, n) + assertEncode(a_wrap, b, n, adobe=True) + assertDecode(a, b) + assertDecode(a_wrap, b, adobe=True) + + def test_ascii85_pad(self): + # Test Ascii85 with encode padding + rawdata = b"n1n3tee\n ch@rAcTer$" + for i in range(1, len(rawdata) + 1): + padding = -i % 4 + b = rawdata[:i] + a_pad = binascii.b2a_ascii85(self.type2test(b), pad=True) + b_pad = binascii.a2b_ascii85(self.type2test(a_pad)) + b_pad_expected = b + b"\0" * padding + self.assertEqual(b_pad, b_pad_expected) + + # Test Ascii85 short form groups with encode padding + def assertShortPad(data, expected, **kwargs): + data = self.type2test(data) + res = binascii.b2a_ascii85(data, **kwargs) + self.assertEqual(res, expected) + + assertShortPad(b"\0", b"!!", pad=False) + assertShortPad(b"\0", b"z", pad=True) + assertShortPad(b"\0" * 2, b"z", pad=True) + assertShortPad(b"\0" * 3, b"z", pad=True) + assertShortPad(b"\0" * 4, b"z", pad=True) + assertShortPad(b"\0" * 5, b"zz", pad=True) + assertShortPad(b"\0" * 6, b"z!!!") + assertShortPad(b" " * 7, b"y+", + foldspaces=True, adobe=True, pad=True) + assertShortPad(b"\0\0\0\0abcd \0\0", b"<~z@:E_Wy\nz~>", + foldspaces=True, adobe=True, wrapcol=9, pad=True) + + def test_ascii85_ignorechars(self): + # Test Ascii85 with ignored characters + def assertIgnore(data, expected, ignorechars=b"", **kwargs): + data = self.type2test(data) + ignore = self.type2test(ignorechars) + with self.assertRaisesRegex(binascii.Error, r"(?i)Non-Ascii85 digit"): + binascii.a2b_ascii85(data, **kwargs) + res = binascii.a2b_ascii85(data, ignorechars=ignorechars, **kwargs) + self.assertEqual(res, expected) + + assertIgnore(b"\n", b"", ignorechars=b"\n") + assertIgnore(b"<~ ~>", b"", ignorechars=b" ", adobe=True) + assertIgnore(b"z|z", b"\0" * 8, ignorechars=b"|||") # repeats don't matter + assertIgnore(b"zz!!|", b"\0" * 9, ignorechars=b"|!z") # ignore only if invalid + assertIgnore(b"<~B P~@~>", b"hi", ignorechars=b" <~>", adobe=True) + assertIgnore(b"zy}", b"\0\0\0\0", ignorechars=b"zy}") + assertIgnore(b"zy}", b"\0\0\0\0 ", ignorechars=b"zy}", foldspaces=True) + + def test_base85_valid(self): + # Test base85 with valid data + lines, i = [], 0 + for k in range(1, len(self.rawdata) + 1): + b = self.type2test(self.rawdata[i:i + k]) + a = binascii.b2a_base85(b) + lines.append(a) + i += k + if i >= len(self.rawdata): + break + res = bytes() + for line in lines: + a = self.type2test(line) + b = binascii.a2b_base85(a) + res += b + self.assertEqual(res, self.rawdata) + + # Test decoding inputs with different length + # 1-char groups are rejected (encoding violation) + with self.assertRaises(binascii.Error): + binascii.a2b_base85(self.type2test(b'a')) + self.assertEqual(binascii.a2b_base85(self.type2test(b'ab')), b'q') + self.assertEqual(binascii.a2b_base85(self.type2test(b'abc')), b'qa') + self.assertEqual(binascii.a2b_base85(self.type2test(b'abcd')), + b'qa\x9e') + self.assertEqual(binascii.a2b_base85(self.type2test(b'abcde')), + b'qa\x9e\xb6') + # 6-char input = full 5-char group + trailing 1-char group (rejected) + with self.assertRaises(binascii.Error): + binascii.a2b_base85(self.type2test(b'abcdef')) + self.assertEqual(binascii.a2b_base85(self.type2test(b'abcdefg')), + b'qa\x9e\xb6\x81') + + def test_base85_errors(self): + def _assertRegexTemplate(assert_regex, data, **kwargs): + with self.assertRaisesRegex(binascii.Error, assert_regex): + binascii.a2b_base85(self.type2test(data), **kwargs) + + def assertNonBase85Data(data): + _assertRegexTemplate(r"(?i)bad base85 character", data) + + def assertOverflow(data): + _assertRegexTemplate(r"(?i)base85 overflow", data) + + assertNonBase85Data(b"\xda") + assertNonBase85Data(b"00\0\0") + assertNonBase85Data(b"Z )*") + assertNonBase85Data(b"bY*jNb0Hyq\n") + + # Test base85 with out-of-range encoded value + assertOverflow(b"}") + assertOverflow(b"|O") + assertOverflow(b"|Nt") + assertOverflow(b"|NsD") + assertOverflow(b"|NsC1") + assertOverflow(b"|NsC0~") + assertOverflow(b"|NsC0|NsC0|NsD0") + + def test_base85_wrapcol(self): + self._common_test_wrapcol(binascii.b2a_base85) + b = self.type2test(b'www.python.org') + self.assertEqual(binascii.b2a_base85(b, wrapcol=10), + b'cXxL#aCvlS\nZ*DGca%T') + self.assertEqual(binascii.b2a_base85(b, wrapcol=14), + b'cXxL#aCvlS\nZ*DGca%T') + self.assertEqual(binascii.b2a_base85(b, wrapcol=1), + b'cXxL#\naCvlS\nZ*DGc\na%T') + + def test_base85_pad(self): + # Test base85 with encode padding + rawdata = b"n1n3Tee\n ch@rAc\te\r$" + for i in range(1, len(rawdata) + 1): + padding = -i % 4 + b = rawdata[:i] + a_pad = binascii.b2a_base85(self.type2test(b), pad=True) + b_pad = binascii.a2b_base85(self.type2test(a_pad)) + b_pad_expected = b + b"\0" * padding + self.assertEqual(b_pad, b_pad_expected) + + def test_base85_ignorechars(self): + a2b_base85 = binascii.a2b_base85 + self._common_test_ignorechars(a2b_base85) + eq = self.assertEqual + eq(a2b_base85(b'VPa\n !s\n', ignorechars=b' \n'), b'abcd') + eq(a2b_base85(b'VPa\n !s\n', ignorechars=bytearray(b' \n')), b'abcd') + + eq(a2b_base85(b'A~[B];C', ignorechars=b';[]~'), b'"1\xa3\x15') + eq(a2b_base85(b'A~[B];C', ignorechars=b';[]~', + alphabet=binascii.Z85_ALPHABET), b'r\xd8dv') + + def test_base85_alphabet(self): + alphabet = (b'0123456789abcdefghijklmnopqrstuvwxyz' + b'ABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#') + data = self.type2test(self.rawdata) + encoded = binascii.b2a_base85(data, alphabet=alphabet) + trans = bytes.maketrans(binascii.BASE85_ALPHABET, alphabet) + expected = binascii.b2a_base85(data).translate(trans) + self.assertEqual(encoded, expected) + self.assertEqual(binascii.a2b_base85(encoded, alphabet=alphabet), self.rawdata) + self.assertEqual(binascii.b2a_base85(data, alphabet=self.type2test(alphabet)), expected) + + data = self.type2test(b'') + self.assertEqual(binascii.b2a_base85(data, alphabet=alphabet), b'') + self.assertEqual(binascii.a2b_base85(data, alphabet=alphabet), b'') + + for func in binascii.b2a_base85, binascii.a2b_base85: + with self.assertRaises(TypeError): + func(data, alphabet=None) + with self.assertRaises(TypeError): + func(data, alphabet=alphabet.decode()) + with self.assertRaises(ValueError): + func(data, alphabet=alphabet[:-1]) + with self.assertRaises(ValueError): + func(data, alphabet=alphabet+b'?') + with self.assertRaises(TypeError): + binascii.a2b_base64(data, alphabet=bytearray(alphabet)) + + def test_base85_canonical(self): + # Non-canonical encodings are accepted without canonical=True + self.assertEqual(binascii.a2b_base85(b'VF'), b'a') + + # 1-char partial groups are always rejected (encoding violation: + # no conforming encoder produces them) + with self.assertRaises(binascii.Error): + binascii.a2b_base85(b'V') + with self.assertRaises(binascii.Error): + binascii.a2b_base85(b'0') + + # Verify round-trip: encode then decode with canonical=True works + for data in [b'a', b'ab', b'abc', b'abcd', b'abcde', + b'\x00', b'\xff', b'\x00\x00', b'\xff\xff\xff']: + encoded = binascii.b2a_base85(data) + decoded = binascii.a2b_base85(encoded, canonical=True) + self.assertEqual(decoded, data) + + # Test non-canonical rejection for each partial group size + # (2-char/1-byte, 3-char/2-byte, 4-char/3-byte). + # Incrementing the last digit by 1 produces a non-canonical + # encoding. For 4-char groups (n_pad=1) a +1 can change the + # output byte, so we use b'ab\x00' whose canonical form allows + # a +1 that still decodes to the same 3 bytes. + for data in [b'a', b'ab', b'ab\x00']: + canonical_enc = binascii.b2a_base85(data) + non_canonical = (canonical_enc[:-1] + + bytes([canonical_enc[-1] + 1])) + # Same decoded output without canonical check + self.assertEqual(binascii.a2b_base85(non_canonical), data) + # Rejected with canonical=True + with self.assertRaises(binascii.Error): + binascii.a2b_base85(non_canonical, canonical=True) + + # Boundary bytes: \x00 and \xff for each partial group size + for data in [b'\x00', b'\x00\x00', b'\x00\x00\x00', + b'\xff', b'\xff\xff', b'\xff\xff\xff']: + canonical_enc = binascii.b2a_base85(data) + binascii.a2b_base85(canonical_enc, canonical=True) + + # Full 5-char groups are always canonical (no padding bits) + self.assertEqual( + binascii.a2b_base85(b'VPa!s', canonical=True), b'abcd') + + # Empty input is valid + self.assertEqual(binascii.a2b_base85(b'', canonical=True), b'') + + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'') + @hypothesis.example(b'\x00') + @hypothesis.example(b'\xff\xff') + @hypothesis.example(b'abc') + def test_base85_canonical_roundtrip(self, payload): + encoded = binascii.b2a_base85(payload) + decoded = binascii.a2b_base85(encoded, canonical=True) + self.assertEqual(decoded, payload) + + @hypothesis.given(payload=hypothesis.strategies.binary(min_size=1, max_size=3)) + @hypothesis.example(b'\x00') + @hypothesis.example(b'\xff') + @hypothesis.example(b'ab\x00') + def test_base85_canonical_unique(self, payload): + # For a partial group, sweeping all 85 last-digit values should + # yield exactly one encoding that both decodes to the original + # payload AND passes canonical=True. + hypothesis.assume(len(payload) % 4 != 0) + canonical_enc = binascii.b2a_base85(payload) + table = binascii.BASE85_ALPHABET + accepted = [] + for digit in table: + candidate = canonical_enc[:-1] + bytes([digit]) + try: + result = binascii.a2b_base85(candidate, canonical=True) + if result == payload: + accepted.append(candidate) + except binascii.Error: + pass + self.assertEqual(accepted, [canonical_enc]) + + def test_ascii85_canonical(self): + # Non-canonical encodings are accepted without canonical=True + self.assertEqual(binascii.a2b_ascii85(b'@0'), b'a') + + # 1-char partial groups are always rejected (PLRM encoding violation) + with self.assertRaises(binascii.Error): + binascii.a2b_ascii85(b'@') + with self.assertRaises(binascii.Error): + binascii.a2b_ascii85(b'!') + + # Verify round-trip: encode then decode with canonical=True works + for data in [b'a', b'ab', b'abc', b'abcd', b'abcde', + b'\x00', b'\xff', b'\x00\x00', b'\xff\xff\xff']: + encoded = binascii.b2a_ascii85(data) + decoded = binascii.a2b_ascii85(encoded, canonical=True) + self.assertEqual(decoded, data) + + # Test non-canonical rejection for each partial group size. + # See test_base85_canonical for why b'ab\x00' is used for 3 bytes. + for data in [b'a', b'ab', b'ab\x00']: + canonical_enc = binascii.b2a_ascii85(data) + non_canonical = (canonical_enc[:-1] + + bytes([canonical_enc[-1] + 1])) + self.assertEqual(binascii.a2b_ascii85(non_canonical), data) + with self.assertRaises(binascii.Error): + binascii.a2b_ascii85(non_canonical, canonical=True) + + # Full 5-char groups are always canonical + self.assertEqual( + binascii.a2b_ascii85(b'@:E_W', canonical=True), b'abcd') + + # 'z' is the canonical form for all-zero groups per the PLRM. + # '!!!!!' decodes identically but is non-canonical. + self.assertEqual(binascii.a2b_ascii85(b'!!!!!'), b'\x00' * 4) + self.assertEqual(binascii.a2b_ascii85(b'z'), b'\x00' * 4) + self.assertEqual( + binascii.a2b_ascii85(b'z', canonical=True), b'\x00' * 4) + with self.assertRaises(binascii.Error): + binascii.a2b_ascii85(b'!!!!!', canonical=True) + # Multiple groups: z + !!!!! should fail + with self.assertRaises(binascii.Error): + binascii.a2b_ascii85(b'z!!!!!', canonical=True) + # Multiple z groups are fine + self.assertEqual( + binascii.a2b_ascii85(b'zz', canonical=True), b'\x00' * 8) + + # Empty input is valid + self.assertEqual(binascii.a2b_ascii85(b'', canonical=True), b'') + + # Adobe-wrapped with canonical + self.assertEqual( + binascii.a2b_ascii85(b'<~@:E_W~>', canonical=True, adobe=True), + b'abcd') + + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'') + @hypothesis.example(b'\x00') + @hypothesis.example(b'\x00\x00\x00\x00') # triggers z abbreviation + @hypothesis.example(b'\xff\xff') + @hypothesis.example(b'abc') + def test_ascii85_canonical_roundtrip(self, payload): + encoded = binascii.b2a_ascii85(payload) + decoded = binascii.a2b_ascii85(encoded, canonical=True) + self.assertEqual(decoded, payload) + + @hypothesis.given(payload=hypothesis.strategies.binary(min_size=1, max_size=3)) + @hypothesis.example(b'\x00') + @hypothesis.example(b'\xff') + @hypothesis.example(b'ab\x00') + def test_ascii85_canonical_unique(self, payload): + hypothesis.assume(len(payload) % 4 != 0) + canonical_enc = binascii.b2a_ascii85(payload) + # Ascii85 alphabet: '!' (33) through 'u' (117) + accepted = [] + for digit in range(33, 118): + candidate = canonical_enc[:-1] + bytes([digit]) + try: + result = binascii.a2b_ascii85(candidate, canonical=True) + if result == payload: + accepted.append(candidate) + except binascii.Error: + pass + self.assertEqual(accepted, [canonical_enc]) + + def test_base32_valid(self): + # Test base32 with valid data + lines = [] + step = 0 + i = 0 + while i < len(self.rawdata): + b = self.type2test(self.rawdata[i:i + step]) + a = binascii.b2a_base32(b) + lines.append(a) + i += step + step += 1 + res = bytes() + for line in lines: + a = self.type2test(line) + b = binascii.a2b_base32(a) + res += b + self.assertEqual(res, self.rawdata) + + def test_base32_errors(self): + def _fixPadding(data): + fixed = data.replace(b"=", b"") + len_8 = len(fixed) % 8 + p = 8 - len_8 if len_8 else 0 + return fixed + b"=" * p + + def _assertRegexTemplate(assert_regex, data, good_padding_result=None, **kwargs): + with self.assertRaisesRegex(binascii.Error, assert_regex): + binascii.a2b_base32(self.type2test(data), **kwargs) + if good_padding_result: + fixed = self.type2test(_fixPadding(data)) + self.assertEqual(binascii.a2b_base32(fixed), good_padding_result) + + def assertNonBase32Data(*args): + _assertRegexTemplate(r"(?i)Only base32 data", *args) + + def assertExcessData(*args): + _assertRegexTemplate(r"(?i)Excess data", *args) + + def assertExcessPadding(*args): + _assertRegexTemplate(r"(?i)Excess padding", *args) + + def assertLeadingPadding(*args, **kwargs): + _assertRegexTemplate(r"(?i)Leading padding", *args, **kwargs) + + def assertIncorrectPadding(*args): + _assertRegexTemplate(r"(?i)Incorrect padding", *args) + + def assertDiscontinuousPadding(*args): + _assertRegexTemplate(r"(?i)Discontinuous padding", *args) + + def assertInvalidLength(data, *args, length=None, **kwargs): + if length is None: + length = len(data.split(b'=', 1)[0].replace(b' ', b'')) + assert_regex = fr"(?i)Invalid.+number of data characters \({length}\)" + _assertRegexTemplate(assert_regex, data, *args, **kwargs) + + assertNonBase32Data(b"a") + assertNonBase32Data(b"AA-") + assertNonBase32Data(b"ABCDE==!") + assertNonBase32Data(b"ab:(){:|:&};:==") + + assertExcessData(b"AB======C") + assertExcessData(b"AB======CD") + assertExcessData(b"ABCD====E") + assertExcessData(b"ABCDE===FGH") + assertExcessData(b"ABCDEFG=H") + assertExcessData(b"432Z====55555555") + + assertExcessData(b"BE======EF", b"\t\x08") + assertExcessData(b"BEEF====C", b"\t\x08Q") + assertExcessData(b"BEEFC===AK", b"\t\x08Q\x01") + assertExcessData(b"BEEFCAK=E", b"\t\x08Q\x01D") + + assertExcessPadding(b"BE=======", b"\t") + assertExcessPadding(b"BE========", b"\t") + assertExcessPadding(b"BEEF=====", b"\t\x08") + assertExcessPadding(b"BEEF======", b"\t\x08") + assertExcessPadding(b"BEEFC====", b"\t\x08Q") + assertExcessPadding(b"BEEFC=====", b"\t\x08Q") + assertExcessPadding(b"BEEFCAK==", b"\t\x08Q\x01") + assertExcessPadding(b"BEEFCAK===", b"\t\x08Q\x01") + assertExcessPadding(b"BEEFCAKE=", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE==", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE===", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE====", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE=====", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE======", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE=======", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE========", b"\t\x08Q\x01D") + assertExcessPadding(b"BEEFCAKE=========", b"\t\x08Q\x01D") + + assertLeadingPadding(b"=", b"") + assertLeadingPadding(b"==", b"") + assertLeadingPadding(b"===", b"") + assertLeadingPadding(b"====", b"") + assertLeadingPadding(b"=====", b"") + assertLeadingPadding(b"======", b"") + assertLeadingPadding(b"=======", b"") + assertLeadingPadding(b"========", b"") + assertLeadingPadding(b"=========", b"") + assertLeadingPadding(b"=BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"==BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"===BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"====BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"=====BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"======BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"=======BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"========BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b"=========BEEFCAKE", b"\t\x08Q\x01D") + assertLeadingPadding(b" =BEEFCAKE", ignorechars=b' ') + + assertIncorrectPadding(b"AB") + assertIncorrectPadding(b"ABCD") + assertIncorrectPadding(b"ABCDE") + assertIncorrectPadding(b"ABCDEFG") + + assertIncorrectPadding(b"BE=", b"\t") + assertIncorrectPadding(b"BE==", b"\t") + assertIncorrectPadding(b"BE===", b"\t") + assertIncorrectPadding(b"BE====", b"\t") + assertIncorrectPadding(b"BE=====", b"\t") + assertIncorrectPadding(b"BEEF=", b"\t\x08") + assertIncorrectPadding(b"BEEF==", b"\t\x08") + assertIncorrectPadding(b"BEEF===", b"\t\x08") + assertIncorrectPadding(b"BEEFC=", b"\t\x08Q") + assertIncorrectPadding(b"BEEFC==", b"\t\x08Q") + + assertDiscontinuousPadding(b"BE=EF===", b"\t\x08") + assertDiscontinuousPadding(b"BE==EF==", b"\t\x08") + assertDiscontinuousPadding(b"BEEF=C==", b"\t\x08Q") + assertDiscontinuousPadding(b"BEEFC=AK", b"\t\x08Q\x01") + + assertInvalidLength(b"A") + assertInvalidLength(b"ABC") + assertInvalidLength(b"ABCDEF") + assertInvalidLength(b"ABCDEFGHI") + assertInvalidLength(b"ABCDEFGHIJK") + assertInvalidLength(b"ABCDEFGHIJKLMN") + + assertInvalidLength(b"A=") + assertInvalidLength(b"A==") + assertInvalidLength(b"A===") + assertInvalidLength(b"A====") + assertInvalidLength(b"A=====") + assertInvalidLength(b"A======") + assertInvalidLength(b"ABC=") + assertInvalidLength(b"ABC==") + assertInvalidLength(b"ABC===") + assertInvalidLength(b"ABC====") + assertInvalidLength(b"ABCDEF=") + + assertInvalidLength(b"B=E=====", b"\t") + assertInvalidLength(b"B==E====", b"\t") + assertInvalidLength(b"BEE=F===", b"\t\x08") + assertInvalidLength(b"BEE==F==", b"\t\x08") + assertInvalidLength(b"BEEFCA=K", b"\t\x08Q\x01") + assertInvalidLength(b"BEEFCA=====K", b"\t\x08Q\x01") + + assertInvalidLength(b" A", ignorechars=b' ') + assertInvalidLength(b" ABC", ignorechars=b' ') + assertInvalidLength(b" ABCDEF", ignorechars=b' ') + assertInvalidLength(b" ABCDEFGHI", ignorechars=b' ') + assertInvalidLength(b" ABCDEFGHIJK", ignorechars=b' ') + assertInvalidLength(b" ABCDEFGHIJKLMN", ignorechars=b' ') + assertInvalidLength(b" A=======", ignorechars=b' ') + assertInvalidLength(b" ABC=====", ignorechars=b' ') + assertInvalidLength(b" ABCDEF==", ignorechars=b' ') + + def test_base32_canonical(self): + # https://datatracker.ietf.org/doc/html/rfc4648.html#section-3.5 + # Decoders MAY reject encoded data if the pad bits are not zero. + + # Without canonical=True, non-zero padding bits are accepted + self.assertEqual(binascii.a2b_base32(self.type2test(b'AB======')), + b'\x00') + + # 2 data chars + "======": last char has 2 padding bits + with self.assertRaises(binascii.Error): + binascii.a2b_base32(self.type2test(b'AB======'), canonical=True) + with self.assertRaises(binascii.Error): + binascii.a2b_base32(self.type2test(b'AD======'), canonical=True) + + # 4 data chars + "====": last char has 4 padding bits + with self.assertRaises(binascii.Error): + binascii.a2b_base32(self.type2test(b'AAAB===='), canonical=True) + with self.assertRaises(binascii.Error): + binascii.a2b_base32(self.type2test(b'AAAP===='), canonical=True) + + # 5 data chars + "===": last char has 1 padding bit + with self.assertRaises(binascii.Error): + binascii.a2b_base32(self.type2test(b'AAAAB==='), canonical=True) + + # 7 data chars + "=": last char has 3 padding bits + with self.assertRaises(binascii.Error): + binascii.a2b_base32(self.type2test(b'AAAAAAB='), canonical=True) + with self.assertRaises(binascii.Error): + binascii.a2b_base32(self.type2test(b'AAAAAAH='), canonical=True) + + # Verify that zero padding bits are accepted + binascii.a2b_base32(self.type2test(b'AA======'), canonical=True) + binascii.a2b_base32(self.type2test(b'AAAA===='), canonical=True) + binascii.a2b_base32(self.type2test(b'AAAAA==='), canonical=True) + binascii.a2b_base32(self.type2test(b'AAAAAAA='), canonical=True) + + # Full octet with no padding -- always valid + binascii.a2b_base32(self.type2test(b'AAAAAAAA'), canonical=True) + + @hypothesis.given(payload=hypothesis.strategies.binary()) + @hypothesis.example(b'') + @hypothesis.example(b'\x00') + @hypothesis.example(b'\xff\xff') + @hypothesis.example(b'abc') + def test_base32_canonical_roundtrip(self, payload): + encoded = binascii.b2a_base32(payload) + decoded = binascii.a2b_base32(encoded, canonical=True) + self.assertEqual(decoded, payload) + + def test_a2b_base32_padded(self): + a2b_base32 = binascii.a2b_base32 + t = self.type2test + def check(data, expected): + if b'=' in data: + with self.assertRaisesRegex(binascii.Error, 'Padding not allowed'): + a2b_base32(t(data), padded=False) + self.assertEqual(a2b_base32(t(data), padded=False, ignorechars=b'='), + expected) + data = data.replace(b'=', b'') + self.assertEqual(a2b_base32(t(data), padded=False), expected) + + check(b'', b'') + check(b'ME======', b'a') + check(b'MFRA====', b'ab') + check(b'MFRGG===', b'abc') + check(b'MFRGGZA=', b'abcd') + check(b'MFRGGZDF', b'abcde') + check(b'M=FRGGZDF', b'abcde') + check(b'MF=RGGZDF', b'abcde') + check(b'MFR=GGZDF', b'abcde') + check(b'MFRG=GZDF', b'abcde') + check(b'MFRGG=ZDF', b'abcde') + check(b'MFRGGZ=DF', b'abcde') + check(b'MFRGGZD=F', b'abcde') + + def test_b2a_base32_padded(self): + b2a_base32 = binascii.b2a_base32 + t = self.type2test + self.assertEqual(b2a_base32(t(b''), padded=False), b'') + self.assertEqual(b2a_base32(t(b'a'), padded=False), b'ME') + self.assertEqual(b2a_base32(t(b'ab'), padded=False), b'MFRA') + self.assertEqual(b2a_base32(t(b'abc'), padded=False), b'MFRGG') + self.assertEqual(b2a_base32(t(b'abcd'), padded=False), b'MFRGGZA') + self.assertEqual(b2a_base32(t(b'abcde'), padded=False), b'MFRGGZDF') + + def test_base32_wrapcol(self): + self._common_test_wrapcol(binascii.b2a_base32) + b = self.type2test(b'www.python.org') + self.assertEqual(binascii.b2a_base32(b, wrapcol=16), + b'O53XOLTQPF2GQ33O\nFZXXEZY=') + self.assertEqual(binascii.b2a_base32(b, wrapcol=23), + b'O53XOLTQPF2GQ33O\nFZXXEZY=') + self.assertEqual(binascii.b2a_base32(b, wrapcol=1), + b'O53XOLTQ\nPF2GQ33O\nFZXXEZY=') + + def test_base32_ignorechars(self): + a2b_base32 = binascii.a2b_base32 + self._common_test_ignorechars(a2b_base32) + eq = self.assertEqual + eq(a2b_base32(b'MFRG\n GZDF\n', ignorechars=b' \n'), b'abcde') + eq(a2b_base32(b'MFRG\n GZDF\n', ignorechars=bytearray(b' \n')), b'abcde') + eq(a2b_base32(b'M=======FRGGZDF', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MF======RGGZDF', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MFR=====GGZDF', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MFRG====GZDF', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MFRGG===ZDF', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MFRGGZ==DF', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MFRGGZD=F', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MFRGGZDF=', ignorechars=b'='), b'abcde') + eq(a2b_base32(b'MFRA======', ignorechars=b'='), b'ab') + + eq(a2b_base32(b'A1B3C5W7Z9', ignorechars=b'19WZ'), b'\x00v.\xdb\xf9') + eq(a2b_base32(b'A1B3C5W7Z9', ignorechars=b'19WZ', + alphabet=binascii.BASE32HEX_ALPHABET), b'PV6\x14\xe9') + + def test_base32_alphabet(self): + alphabet = b'0Aa1Bb2Cc3Dd4Ee5Ff6Gg7Hh8Ii9JjKk' + data = self.type2test(self.rawdata) + encoded = binascii.b2a_base32(data, alphabet=alphabet) + trans = bytes.maketrans(binascii.BASE32_ALPHABET, alphabet) + expected = binascii.b2a_base32(data).translate(trans) + self.assertEqual(encoded, expected) + self.assertEqual(binascii.a2b_base32(encoded, alphabet=alphabet), self.rawdata) + self.assertEqual(binascii.b2a_base32(data, alphabet=self.type2test(alphabet)), expected) + + data = self.type2test(b'') + self.assertEqual(binascii.b2a_base32(data, alphabet=alphabet), b'') + self.assertEqual(binascii.a2b_base32(data, alphabet=alphabet), b'') + + for func in binascii.b2a_base32, binascii.a2b_base32: + with self.assertRaises(TypeError): + func(data, alphabet=None) + with self.assertRaises(TypeError): + func(data, alphabet=alphabet.decode()) + with self.assertRaises(ValueError): + func(data, alphabet=alphabet[:-1]) + with self.assertRaises(ValueError): + func(data, alphabet=alphabet+b'?') + with self.assertRaises(TypeError): + binascii.a2b_base32(data, alphabet=bytearray(alphabet)) def test_uu(self): MAX_UU = 45 @@ -325,6 +1391,15 @@ def test_hex_separator(self): expected1 = s.hex(':').encode('ascii') self.assertEqual(binascii.b2a_hex(self.type2test(s), ':'), expected1) + def test_hex_ignorechars(self): + a2b_hex = binascii.a2b_hex + self._common_test_ignorechars(a2b_hex) + self._common_test_ignorechars(binascii.unhexlify) + eq = self.assertEqual + eq(a2b_hex(b'A B\nC D\n', ignorechars=b' \n'), b'\xab\xcd') + eq(a2b_hex(b'A B\nC D\n', ignorechars=bytearray(b' \n')), b'\xab\xcd') + eq(a2b_hex(b'aBcD', ignorechars=b'ac'), b'\xab\xcd') + def test_qp(self): type2test = self.type2test a2b_qp = binascii.a2b_qp @@ -499,6 +1574,32 @@ def test_b2a_base64_newline(self): b'aGVsbG8=\n') self.assertEqual(binascii.b2a_base64(b, newline=False), b'aGVsbG8=') + b = self.type2test(b'') + self.assertEqual(binascii.b2a_base64(b), b'\n') + self.assertEqual(binascii.b2a_base64(b, newline=True), b'\n') + self.assertEqual(binascii.b2a_base64(b, newline=False), b'') + + def test_b2a_base64_padded(self): + b2a_base64 = binascii.b2a_base64 + t = self.type2test + self.assertEqual(b2a_base64(t(b''), padded=False), b'\n') + self.assertEqual(b2a_base64(t(b'a'), padded=False), b'YQ\n') + self.assertEqual(b2a_base64(t(b'ab'), padded=False), b'YWI\n') + self.assertEqual(b2a_base64(t(b'abc'), padded=False), b'YWJj\n') + + def test_b2a_base64_wrapcol(self): + self._common_test_wrapcol(binascii.b2a_base64) + b = self.type2test(b'www.python.org') + self.assertEqual(binascii.b2a_base64(b, wrapcol=8), + b'd3d3LnB5\ndGhvbi5v\ncmc=\n') + self.assertEqual(binascii.b2a_base64(b, wrapcol=11), + b'd3d3LnB5\ndGhvbi5v\ncmc=\n') + self.assertEqual(binascii.b2a_base64(b, wrapcol=8, newline=False), + b'd3d3LnB5\ndGhvbi5v\ncmc=') + self.assertEqual(binascii.b2a_base64(b, wrapcol=1), + b'd3d3\nLnB5\ndGhv\nbi5v\ncmc=\n') + b = self.type2test(b'') + self.assertEqual(binascii.b2a_base64(b, wrapcol=8, newline=False), b'') @hypothesis.given( binary=hypothesis.strategies.binary(), diff --git a/Lib/test/test_buffer.py b/Lib/test/test_buffer.py index 19582e75716..7454c8a1539 100644 --- a/Lib/test/test_buffer.py +++ b/Lib/test/test_buffer.py @@ -66,7 +66,8 @@ '?':0, 'c':0, 'b':0, 'B':0, 'h':0, 'H':0, 'i':0, 'I':0, 'l':0, 'L':0, 'n':0, 'N':0, - 'e':0, 'f':0, 'd':0, 'P':0 + 'e':0, 'f':0, 'd':0, 'P':0, + 'Zf':0, 'Zd':0, } # NumPy does not have 'n' or 'N': @@ -92,7 +93,9 @@ 'l':(-(1<<31), 1<<31), 'L':(0, 1<<32), 'q':(-(1<<63), 1<<63), 'Q':(0, 1<<64), 'e':(-65519, 65520), 'f':(-(1<<63), 1<<63), - 'd':(-(1<<1023), 1<<1023) + 'd':(-(1<<1023), 1<<1023), + 'Zf':(-(1<<63), 1<<63), + 'Zd':(-(1<<1023), 1<<1023), } def native_type_range(fmt): @@ -107,6 +110,10 @@ def native_type_range(fmt): lh = (-(1<<63), 1<<63) elif fmt == 'd': lh = (-(1<<1023), 1<<1023) + elif fmt == 'Zf': + lh = (-(1<<63), 1<<63) + elif fmt == 'Zd': + lh = (-(1<<1023), 1<<1023) else: for exp in (128, 127, 64, 63, 32, 31, 16, 15, 8, 7): try: @@ -136,7 +143,7 @@ def native_type_range(fmt): # Format codes supported by array.array ARRAY = NATIVE.copy() for k in NATIVE: - if not k in "bBhHiIlLfd": + if k not in list("bBhHiIlLefd") + ['Zf', 'Zd']: del ARRAY[k] BYTEFMT = NATIVE.copy() @@ -175,13 +182,28 @@ def randrange_fmt(mode, char, obj): if char in 'efd': x = struct.pack(char, x) x = struct.unpack(char, x)[0] + if char in ('Zf', 'Zd'): + y = randrange(*fmtdict[mode][char]) + x = complex(x, y) + x = struct.pack(char, x) + x = struct.unpack(char, x)[0] return x +def split_format(fmt): + i = 0 + while i < len(fmt): + if fmt[i] == 'Z': + n = 2 + else: + n = 1 + yield fmt[i:i + n] + i += n + def gen_item(fmt, obj): """Return single random item.""" mode, chars = fmt.split('#') x = [] - for c in chars: + for c in split_format(chars): x.append(randrange_fmt(mode, c, obj)) return x[0] if len(x) == 1 else tuple(x) @@ -242,9 +264,7 @@ def is_byte_format(fmt): def is_memoryview_format(fmt): """format suitable for memoryview""" - x = len(fmt) - return ((x == 1 or (x == 2 and fmt[0] == '@')) and - fmt[x-1] in MEMORYVIEW) + return fmt.removeprefix('@') in MEMORYVIEW NON_BYTE_FORMAT = [c for c in fmtdict['@'] if not is_byte_format(c)] @@ -636,14 +656,22 @@ def ndarray_from_structure(items, fmt, t, flags=0): return ndarray(items, shape=shape, strides=strides, format=fmt, offset=offset, flags=ND_WRITABLE|flags) +# Convert PEP 3118 formats to numpy dtypes +FORMAT_TO_DTYPE = { + 'Zf': 'F', + 'Zd': 'D', +} + def numpy_array_from_structure(items, fmt, t): """Return numpy_array from the tuple returned by rand_structure()""" memlen, itemsize, ndim, shape, strides, offset = t buf = bytearray(memlen) for j, v in enumerate(items): struct.pack_into(fmt, buf, j*itemsize, v) + # Replace Zd/Zf formats with D/F dtypes + dtype = FORMAT_TO_DTYPE.get(fmt, fmt) return numpy_array(buffer=buf, shape=shape, strides=strides, - dtype=fmt, offset=offset) + dtype=dtype, offset=offset) # ====================================================================== @@ -3015,7 +3043,7 @@ def test_memoryview_assign(self): m = memoryview(nd) self.assertRaises(TypeError, m.__setitem__, 0, 100) - ex = ndarray(list(range(120)), shape=[1,2,3,4,5], flags=ND_WRITABLE) + ex = ndarray(list(range(144)), shape=[1,2,3,4,6], flags=ND_WRITABLE) m1 = memoryview(ex) for fmt, _range in fmtdict['@'].items(): @@ -3025,7 +3053,7 @@ def test_memoryview_assign(self): continue m2 = m1.cast(fmt) lo, hi = _range - if fmt == 'd' or fmt == 'f': + if fmt in ("d", "f", "Zd", "Zf"): lo, hi = -2**1024, 2**1024 if fmt != 'P': # PyLong_AsVoidPtr() accepts negative numbers self.assertRaises(ValueError, m2.__setitem__, 0, lo-1) @@ -4447,6 +4475,43 @@ def test_bytearray_release_buffer_read_flag(self): with self.assertRaises(SystemError): obj.__buffer__(inspect.BufferFlags.WRITE) + @support.cpython_only + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_bytearray_alignment(self): + # gh-140557: pointer alignment of buffers including empty allocation + # should be at least to `size_t`. + align = struct.calcsize("N") + cases = [ + bytearray(), + bytearray(1), + bytearray(b"0123456789abcdef"), + bytearray(16), + ] + ptrs = [_testcapi.buffer_pointer_as_int(array) for array in cases] + self.assertEqual([ptr % align for ptr in ptrs], [0]*len(ptrs)) + + @support.cpython_only + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_array_alignment(self): + # gh-140557: pointer alignment of buffers including empty allocation + # should match the maximum array alignment. + formats = [fmt for fmt in ARRAY + if struct.calcsize(fmt) <= struct.calcsize('P')] + align = max(struct.calcsize(fmt) for fmt in formats) + cases = [array.array(fmt) for fmt in formats] + # Empty arrays + self.assertEqual( + [_testcapi.buffer_pointer_as_int(case) % align for case in cases], + [0] * len(cases), + ) + for case in cases: + case.append(0) + # Allocated arrays + self.assertEqual( + [_testcapi.buffer_pointer_as_int(case) % align for case in cases], + [0] * len(cases), + ) + @support.cpython_only def test_pybuffer_size_from_format(self): # basic tests diff --git a/Lib/test/test_bufio.py b/Lib/test/test_bufio.py deleted file mode 100644 index cb9cb4d0bc7..00000000000 --- a/Lib/test/test_bufio.py +++ /dev/null @@ -1,73 +0,0 @@ -import unittest -from test.support import os_helper - -import io # C implementation. -import _pyio as pyio # Python implementation. - -# Simple test to ensure that optimizations in the IO library deliver the -# expected results. For best testing, run this under a debug-build Python too -# (to exercise asserts in the C code). - -lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000, - 16384, 32768, 65536, 1000000] - -class BufferSizeTest: - def try_one(self, s): - # Write s + "\n" + s to file, then open it and ensure that successive - # .readline()s deliver what we wrote. - - # Ensure we can open TESTFN for writing. - os_helper.unlink(os_helper.TESTFN) - - # Since C doesn't guarantee we can write/read arbitrary bytes in text - # files, use binary mode. - f = self.open(os_helper.TESTFN, "wb") - try: - # write once with \n and once without - f.write(s) - f.write(b"\n") - f.write(s) - f.close() - f = self.open(os_helper.TESTFN, "rb") - line = f.readline() - self.assertEqual(line, s + b"\n") - line = f.readline() - self.assertEqual(line, s) - line = f.readline() - self.assertFalse(line) # Must be at EOF - f.close() - finally: - os_helper.unlink(os_helper.TESTFN) - - def drive_one(self, pattern): - for length in lengths: - # Repeat string 'pattern' as often as needed to reach total length - # 'length'. Then call try_one with that string, a string one larger - # than that, and a string one smaller than that. Try this with all - # small sizes and various powers of 2, so we exercise all likely - # stdio buffer sizes, and "off by one" errors on both sides. - q, r = divmod(length, len(pattern)) - teststring = pattern * q + pattern[:r] - self.assertEqual(len(teststring), length) - self.try_one(teststring) - self.try_one(teststring + b"x") - self.try_one(teststring[:-1]) - - def test_primepat(self): - # A pattern with prime length, to avoid simple relationships with - # stdio buffer sizes. - self.drive_one(b"1234567890\00\01\02\03\04\05\06") - - def test_nullpat(self): - self.drive_one(b'\0' * 1000) - - -class CBufferSizeTest(BufferSizeTest, unittest.TestCase): - open = io.open - -class PyBufferSizeTest(BufferSizeTest, unittest.TestCase): - open = staticmethod(pyio.open) - - -if __name__ == "__main__": - unittest.main() diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 8fdee358acf..0b98c08bdfb 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -4,6 +4,7 @@ import builtins import collections import contextlib +import copy import decimal import fractions import gc @@ -21,6 +22,7 @@ import typing import unittest import warnings +import weakref from contextlib import ExitStack from functools import partial from inspect import CO_COROUTINE @@ -31,6 +33,7 @@ from test import support from test.support import cpython_only, swap_attr from test.support import async_yield, run_yielding_async_fn +from test.support import warnings_helper from test.support.import_helper import import_module from test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink) from test.support.script_helper import assert_python_ok @@ -51,6 +54,10 @@ # used as proof of globals being used A_GLOBAL_VALUE = 123 +A_SENTINEL = sentinel("A_SENTINEL") + +class SentinelContainer: + CLASS_SENTINEL = sentinel("SentinelContainer.CLASS_SENTINEL") class Squares: @@ -245,7 +252,7 @@ def test_any(self): S = [10, 20, 30] self.assertEqual(any(x > 42 for x in S), False) - def test_all_any_tuple_optimization(self): + def test_all_any_tuple_list_set_optimization(self): def f_all(): return all(x-2 for x in [1,2,3]) @@ -255,7 +262,13 @@ def f_any(): def f_tuple(): return tuple(2*x for x in [1,2,3]) - funcs = [f_all, f_any, f_tuple] + def f_list(): + return list(2*x for x in [1,2,3]) + + def f_set(): + return set(2*x for x in [1,2,3]) + + funcs = [f_all, f_any, f_tuple, f_list, f_set] for f in funcs: # check that generator code object is not duplicated @@ -265,33 +278,35 @@ def f_tuple(): # check the overriding the builtins works - global all, any, tuple - saved = all, any, tuple + global all, any, tuple, list, set + saved = all, any, tuple, list, set try: all = lambda x : "all" any = lambda x : "any" tuple = lambda x : "tuple" + list = lambda x : "list" + set = lambda x : "set" overridden_outputs = [f() for f in funcs] finally: - all, any, tuple = saved - - self.assertEqual(overridden_outputs, ['all', 'any', 'tuple']) + all, any, tuple, list, set = saved + self.assertEqual(overridden_outputs, ['all', 'any', 'tuple', 'list', 'set']) # Now repeat, overriding the builtins module as well - saved = all, any, tuple + saved = all, any, tuple, list, set try: builtins.all = all = lambda x : "all" builtins.any = any = lambda x : "any" builtins.tuple = tuple = lambda x : "tuple" + builtins.list = list = lambda x : "list" + builtins.set = set = lambda x : "set" overridden_outputs = [f() for f in funcs] finally: - all, any, tuple = saved - builtins.all, builtins.any, builtins.tuple = saved - - self.assertEqual(overridden_outputs, ['all', 'any', 'tuple']) + all, any, tuple, list, set = saved + builtins.all, builtins.any, builtins.tuple, builtins.list, builtins.set = saved + self.assertEqual(overridden_outputs, ['all', 'any', 'tuple', 'list', 'set']) def test_builtin_call_async_genexpr_no_crash(self): async def f_all(): @@ -527,6 +542,10 @@ async def sleep(delay, result=None): '''a = [x async for x in (x async for x in arange(5))][1]''', '''a, = [1 for x in {x async for x in arange(1)}]''', '''a = [await sleep(0, x) async for x in arange(2)][1]''', + '''a = [await sleep(0, 1) for _ in [0]][0]''', + '''a = {await sleep(0, 1) for _ in [0]}.pop()''', + '''a = {0: await sleep(0, 1) for _ in [0]}[0]''', + '''a = (lambda x=[await sleep(0, 1) for _ in [0]]: x)()[0]''', # gh-121637: Make sure we correctly handle the case where the # async code is optimized away '''assert not await sleep(0); a = 1''', @@ -595,7 +614,26 @@ async def __aexit__(self, *exc_info): '''def f(): async with Lock() as l: a = 1 - ''' + ''', + '''class C: + [await x for x in y] + ''', + '''class C: + [x async for x in arange(10)] + ''', + '''async def f(): + class C: + [await x for x in y] + ''', + '''lambda: [await x for x in y]''', + '''class C: + def f(self, x=[await y for y in z]): + pass + ''', + '''type T = [await x for x in y]''', + '''async def f[T=[await x for x in y]](): + pass + ''', ] for mode, code_sample in product(modes, code_samples): source = dedent(code_sample) @@ -796,6 +834,16 @@ def __getitem__(self, key): raise ValueError self.assertRaises(ValueError, eval, "foo", {}, X()) + def test_eval_frozendict(self): + ns = frozendict(x=1, data=[], __builtins__=__builtins__) + eval("data.append(x)", ns, ns) + self.assertEqual(ns['data'], [1]) + + ns = frozendict() + errmsg = "cannot assign __builtins__ to frozendict globals" + with self.assertRaisesRegex(TypeError, errmsg): + eval("", ns, ns) + def test_eval_kwargs(self): data = {"A_GLOBAL_VALUE": 456} self.assertEqual(eval("globals()['A_GLOBAL_VALUE']", globals=data), 456) @@ -894,6 +942,21 @@ def test_exec(self): del l['__builtins__'] self.assertEqual((g, l), ({'a': 1}, {'b': 2})) + def test_exec_frozendict(self): + ns = frozendict(x=1, data=[], __builtins__=__builtins__) + exec("data.append(x)", ns, ns) + self.assertEqual(ns['data'], [1]) + + ns = frozendict(__builtins__=__builtins__) + errmsg = "'frozendict' object does not support item assignment" + with self.assertRaisesRegex(TypeError, errmsg): + exec("x = 1", ns, ns) + + ns = frozendict() + errmsg = "cannot assign __builtins__ to frozendict globals" + with self.assertRaisesRegex(TypeError, errmsg): + exec("", ns, ns) + def test_exec_kwargs(self): g = {} exec('global z\nz = 1', globals=g) @@ -1108,6 +1171,29 @@ def four_freevars(): three_freevars.__globals__, closure=my_closure) + def test_exec_filter_syntax_warnings_by_module(self): + filename = support.findfile('test_import/data/syntax_warnings.py') + with open(filename, 'rb') as f: + source = f.read() + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'\z') + exec(source, {}) + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + for wm in wlog: + self.assertEqual(wm.filename, '') + self.assertIs(wm.category, SyntaxWarning) + + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'package.module\z') + warnings.filterwarnings('error', module=r'') + exec(source, {'__name__': 'package.module', '__file__': filename}) + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + for wm in wlog: + self.assertEqual(wm.filename, '') + self.assertIs(wm.category, SyntaxWarning) + def test_filter(self): self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) @@ -1140,7 +1226,6 @@ def test_filter_pickle(self): f2 = filter(filter_char, "abcdeabcde") self.check_iter_pickle(f1, list(f2), proto) - @unittest.skip("TODO: RUSTPYTHON; Segfault") @support.skip_wasi_stack_overflow() @support.skip_emscripten_stack_overflow() @support.requires_resource('cpu') @@ -1868,6 +1953,115 @@ class C: __repr__ = None self.assertRaises(TypeError, repr, C()) + def test_sentinel(self): + missing = sentinel("MISSING") + other = sentinel("MISSING") + + self.assertIsInstance(missing, sentinel) + self.assertIs(type(missing), sentinel) + self.assertEqual(missing.__name__, "MISSING") + self.assertEqual(missing.__module__, __name__) + self.assertIsNot(missing, other) + self.assertEqual(repr(missing), "MISSING") + self.assertTrue(missing) + self.assertIs(copy.copy(missing), missing) + self.assertIs(copy.deepcopy(missing), missing) + self.assertEqual(missing, missing) + self.assertNotEqual(missing, other) + self.assertRaises(TypeError, sentinel) + self.assertRaises(TypeError, sentinel, "MISSING", "EXTRA") + self.assertRaises(TypeError, sentinel, name="MISSING") + with self.assertRaisesRegex(TypeError, "must be str"): + sentinel(1) + self.assertTrue(sentinel.__flags__ & support._TPFLAGS_IMMUTABLETYPE) + self.assertTrue(sentinel.__flags__ & support._TPFLAGS_HAVE_GC) + self.assertFalse(sentinel.__flags__ & support._TPFLAGS_BASETYPE) + with self.assertRaises(TypeError): + class SubSentinel(sentinel): + pass + + def test_sentinel_attributes(self): + missing = sentinel("MISSING") + with self.assertRaises(TypeError): + sentinel.attribute = "value" + with self.assertRaises(AttributeError): + missing.attribute = "value" + with self.assertRaises(AttributeError): + missing.__name__ = "CHANGED" + missing.__module__ = "changed" + self.assertEqual(missing.__module__, "changed") + with self.assertRaises(AttributeError): + del missing.__name__ + del missing.__module__ + with self.assertRaises(AttributeError): + missing.__module__ + + def test_sentinel_repr(self): + with_repr = sentinel("WITH_REPR", repr="custom") + without_repr = sentinel("WITHOUT_REPR", repr=None) + self.assertEqual(repr(with_repr), "custom") + self.assertEqual(repr(without_repr), "WITHOUT_REPR") + self.assertEqual(str(with_repr), "custom") + self.assertEqual(str(without_repr), "WITHOUT_REPR") + + with self.assertRaisesRegex(TypeError, "repr.*str or None"): + sentinel("BAD_REPR", repr=42) + + def test_sentinel_pickle(self): + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=proto): + self.assertIs( + pickle.loads(pickle.dumps(A_SENTINEL, protocol=proto)), + A_SENTINEL) + self.assertIs( + pickle.loads(pickle.dumps( + SentinelContainer.CLASS_SENTINEL, protocol=proto)), + SentinelContainer.CLASS_SENTINEL) + + missing = sentinel("MISSING") + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=proto): + with self.assertRaises(pickle.PicklingError): + pickle.dumps(missing, protocol=proto) + + def test_sentinel_str_subclass_name_cycle(self): + class Name(str): + pass + + name = Name("MISSING") + missing = sentinel(name) + self.assertIs(missing.__name__, name) + self.assertTrue(gc.is_tracked(missing)) + + name.missing = missing + ref = weakref.ref(name) + del name, missing + support.gc_collect() + self.assertIsNone(ref()) + + def test_sentinel_union(self): + missing = sentinel("MISSING") + + self.assertIsInstance(missing | int, typing.Union) + self.assertEqual((missing | int).__args__, (missing, int)) + self.assertIsInstance(int | missing, typing.Union) + self.assertEqual((int | missing).__args__, (int, missing)) + self.assertIs(missing | missing, missing) + self.assertEqual(repr(int | missing), "int | MISSING") + self.assertIsInstance(missing | None, typing.Union) + self.assertEqual((missing | None).__args__, (missing, type(None))) + self.assertIsInstance(None | missing, typing.Union) + self.assertEqual((None | missing).__args__, (type(None), missing)) + self.assertIsInstance(missing | list[int], typing.Union) + self.assertEqual((missing | list[int]).__args__, (missing, list[int])) + self.assertIsInstance(missing | (int | str), typing.Union) + self.assertEqual((missing | (int | str)).__args__, (missing, int, str)) + + with self.assertRaises(TypeError): + missing | 1 + with self.assertRaises(TypeError): + 1 | missing + def test_round(self): self.assertEqual(round(0.0), 0.0) self.assertEqual(type(round(0.0)), int) @@ -2408,7 +2602,6 @@ def test_bytearray_extend_error(self): bad_iter = map(int, "X") self.assertRaises(ValueError, array.extend, bad_iter) - @unittest.skip("TODO: RUSTPYTHON; Hangs") def test_bytearray_join_with_misbehaving_iterator(self): # Issue #112625 array = bytearray(b',') @@ -2594,6 +2787,7 @@ def run_child(self, child, terminal_input): finally: signal.signal(signal.SIGHUP, old_sighup) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def _run_child(self, child, terminal_input): r, w = os.pipe() # Pipe test results from child back to parent try: @@ -2983,6 +3177,12 @@ def test_type_doc(self): A.__doc__ = doc self.assertEqual(A.__doc__, doc) + def test_type_frozendict(self): + A = type('A', (), frozendict({'x': 4, 'y': 2})) + self.assertEqual(A.x, 4) + self.assertEqual(A.y, 2) + self.assertEqual(A.__name__, 'A') + def test_bad_args(self): with self.assertRaises(TypeError): type() diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py index 57dec4e04a8..f972cd3e18b 100644 --- a/Lib/test/test_bytes.py +++ b/Lib/test/test_bytes.py @@ -5,13 +5,15 @@ """ import array +import codecs +import contextlib +import copy +import functools import operator import os +import pickle import re import sys -import copy -import functools -import pickle import tempfile import textwrap import threading @@ -48,6 +50,13 @@ def __index__(self): return self.value +@contextlib.contextmanager +def inject_memory_error(testcase, start=0): + with testcase.assertRaises(MemoryError): + with support.inject_memory_error_cm(start): + yield + + class BaseBytesTest: def assertTypedEqual(self, actual, expected): @@ -204,7 +213,6 @@ def test_constructor_value_errors(self): self.assertRaises(ValueError, self.type2test, [sys.maxsize+1]) self.assertRaises(ValueError, self.type2test, [10**100]) - @unittest.expectedFailure # TODO: RUSTPYTHON @bigaddrspacetest def test_constructor_overflow(self): size = MAX_Py_ssize_t @@ -328,7 +336,6 @@ def test_decode(self): # Default encoding is utf-8 self.assertEqual(self.type2test(b'\xe2\x98\x83').decode(), '\u2603') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_check_encoding_errors(self): # bpo-37388: bytes(str) and bytes.encode() must check encoding # and errors arguments in dev mode @@ -510,6 +517,15 @@ def test_fromhex(self): self.type2test.fromhex(data) self.assertIn('at position %s' % pos, str(cm.exception)) + # gh-158583: Check for out of bounds reads (uninitialized bytes). + # Create an array from a list to not overallocate. + a = array.array('B', list(b'1234 ')) # Py_ISSPACE() loop + self.assertEqual(self.type2test.fromhex(a), b'\x12\x34') + + a = array.array('B', list(b'12345')) # Missing second digit + with self.assertRaises(ValueError): + self.type2test.fromhex(a) + def test_hex(self): self.assertRaises(TypeError, self.type2test.hex) self.assertRaises(TypeError, self.type2test.hex, 1) @@ -553,10 +569,10 @@ def test_hex_separator_basics(self): self.assertEqual(three_bytes.hex('*', -2), 'b901*ef') self.assertEqual(three_bytes.hex(sep=':', bytes_per_sep=2), 'b9:01ef') self.assertEqual(three_bytes.hex(sep='*', bytes_per_sep=-2), 'b901*ef') - for bytes_per_sep in 3, -3, 2**31-1, -(2**31-1): + for bytes_per_sep in 3, -3, sys.maxsize, -sys.maxsize: with self.subTest(bytes_per_sep=bytes_per_sep): self.assertEqual(three_bytes.hex(':', bytes_per_sep), 'b901ef') - for bytes_per_sep in 2**31, -2**31, 2**1000, -2**1000: + for bytes_per_sep in sys.maxsize+1, -sys.maxsize-1, 2**1000, -2**1000: with self.subTest(bytes_per_sep=bytes_per_sep): try: self.assertEqual(three_bytes.hex(':', bytes_per_sep), 'b901ef') @@ -586,6 +602,37 @@ def test_hex_separator_six_bytes(self): self.assertEqual(six_bytes.hex(':', -6), '0306090c0f12') self.assertEqual(six_bytes.hex(' ', -95), '0306090c0f12') + def test_hex_simd_boundaries(self): + # Test lengths around the SIMD threshold (16 bytes). + # SIMD processes 16 bytes at a time; smaller inputs use scalar code. + for length in (14, 15, 16, 17, 31, 32, 33, 64, 65): + data = self.type2test(bytes(range(length))) + expected = ''.join(f'{b:02x}' for b in range(length)) + with self.subTest(length=length): + self.assertEqual(data.hex(), expected) + + def test_hex_nibble_boundaries(self): + # Test the nibble value boundary at 9/10 (where '9' becomes 'a'). + # SIMD uses signed comparison for efficiency; verify correctness + # at this boundary for various nibble combinations. + boundary_bytes = self.type2test(bytes([ + 0x09, # both nibbles: 0, 9 + 0x0a, # both nibbles: 0, 10 + 0x90, # both nibbles: 9, 0 + 0x99, # both nibbles: 9, 9 (max all-digit) + 0x9a, # both nibbles: 9, 10 + 0xa0, # both nibbles: 10, 0 + 0xa9, # both nibbles: 10, 9 + 0xaa, # both nibbles: 10, 10 (min all-letter) + 0x00, # min value + 0xff, # max value + ])) + self.assertEqual(boundary_bytes.hex(), '090a90999aa0a9aa00ff') + + # Repeat with 16+ bytes to exercise SIMD path + simd_boundary = self.type2test(boundary_bytes * 2) + self.assertEqual(simd_boundary.hex(), '090a90999aa0a9aa00ff' * 2) + def test_join(self): self.assertEqual(self.type2test(b"").join([]), b"") self.assertEqual(self.type2test(b"").join([b""]), b"") @@ -616,6 +663,32 @@ def test_join(self): with self.assertRaises(TypeError): dot_join([memoryview(b"ab"), "cd", b"ef"]) + def test_join_concurrent_buffer_mutation(self): + # __buffer__() can release the GIL, letting another thread concurrently + # mutate the joined sequence (simulated here by mutating in __buffer__). + # See: https://github.com/python/cpython/issues/151295 + def make_seq(mutate): + # Item is only referenced from the list slot, so mutate() frees it. + class Item: + def __buffer__(self, flags): + mutate(seq) + return memoryview(b'x') + seq = [b'a', Item(), b'c'] + return seq + + for sep in (self.type2test(b''), self.type2test(b'::')): + with self.subTest(sep=sep): + # Changing the list length is reported as a RuntimeError. + seq = make_seq(lambda seq: seq.clear()) + self.assertRaises(RuntimeError, sep.join, seq) + + # The list length is unchanged, so the size-change recheck + # cannot fire: only keeping the item alive avoids the crash. + def replace(seq): + seq[1] = b'z' + seq = make_seq(replace) + self.assertEqual(sep.join(seq), sep.join([b'a', b'x', b'c'])) + def test_count(self): b = self.type2test(b'mississippi') i = 105 @@ -794,16 +867,16 @@ def __int__(self): pi = PseudoFloat(3.1415) exceptions_params = [ - ('%x format: an integer is required, not float', b'%x', 3.14), - ('%X format: an integer is required, not float', b'%X', 2.11), - ('%o format: an integer is required, not float', b'%o', 1.79), - ('%x format: an integer is required, not PseudoFloat', b'%x', pi), - ('%x format: an integer is required, not complex', b'%x', 3j), - ('%X format: an integer is required, not complex', b'%X', 2j), - ('%o format: an integer is required, not complex', b'%o', 1j), - ('%u format: a real number is required, not complex', b'%u', 3j), - ('%i format: a real number is required, not complex', b'%i', 2j), - ('%d format: a real number is required, not complex', b'%d', 2j), + ('%x requires an integer, not float', b'%x', 3.14), + ('%X requires an integer, not float', b'%X', 2.11), + ('%o requires an integer, not float', b'%o', 1.79), + (r'%x requires an integer, not .*\.PseudoFloat', b'%x', pi), + ('%x requires an integer, not complex', b'%x', 3j), + ('%X requires an integer, not complex', b'%X', 2j), + ('%o requires an integer, not complex', b'%o', 1j), + ('%u requires a real number, not complex', b'%u', 3j), + ('%i requires a real number, not complex', b'%i', 2j), + ('%d requires a real number, not complex', b'%d', 2j), ( r'%c requires an integer in range\(256\)' r' or a single byte, not .*\.PseudoFloat', @@ -812,7 +885,7 @@ def __int__(self): ] for msg, format_bytes, value in exceptions_params: - with self.assertRaisesRegex(TypeError, msg): + with self.assertRaisesRegex(TypeError, 'format argument: ' + msg): operator.mod(format_bytes, value) def test_memory_leak_gh_140939(self): @@ -822,6 +895,19 @@ def test_memory_leak_gh_140939(self): b = self.type2test(b'%*b') b % (_testcapi.PY_SSIZE_T_MAX, b'abc') + def test_mod_bytes_lookup_error(self): + # An error raised while looking up __bytes__ propagates. + class BadBytes: + @property + def __bytes__(self): + raise ZeroDivisionError + def __buffer__(self, flags): + return memoryview(b'abc') + + b = self.type2test(b'%b') + with self.assertRaises(ZeroDivisionError): + b % BadBytes() + def test_imod(self): b = self.type2test(b'hello, %b!') orig = b @@ -849,6 +935,13 @@ def test_replace(self): self.assertEqual(b.replace(b'i', b'a'), b'massassappa') self.assertEqual(b.replace(b'ss', b'x'), b'mixixippi') + def test_replace_count_keyword(self): + b = self.type2test(b'aa') + self.assertEqual(b.replace(b'a', b'b', count=0), b'aa') + self.assertEqual(b.replace(b'a', b'b', count=1), b'ba') + self.assertEqual(b.replace(b'a', b'b', count=2), b'bb') + self.assertEqual(b.replace(b'a', b'b', count=3), b'bb') + def test_replace_int_error(self): self.assertRaises(TypeError, self.type2test(b'a b').replace, 32, b'') @@ -1337,10 +1430,6 @@ class SubBytes(bytes): self.assertNotEqual(id(s), id(1 * s)) self.assertNotEqual(id(s), id(s * 2)) - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_mod(self): - return super().test_mod() - class ByteArrayTest(BaseBytesTest, unittest.TestCase): type2test = bytearray @@ -1393,7 +1482,6 @@ def test_bytearray_api(self): except OSError: pass - @unittest.skip("TODO: RUSTPYTHON; segfault") def test_mod_concurrent_mutation(self): # Prevent crash in __mod__ when formatting mutates the bytearray. # Regression test for https://github.com/python/cpython/issues/142557. @@ -1432,6 +1520,16 @@ def test_clear(self): b.append(ord('p')) self.assertEqual(b, b'p') + # Cleared object should be empty. + b = bytearray(b'abc') + b.clear() + self.assertEqual(b.__alloc__(), 0) + base_size = sys.getsizeof(bytearray()) + self.assertEqual(sys.getsizeof(b), base_size) + c = b.copy() + self.assertEqual(c.__alloc__(), 0) + self.assertEqual(sys.getsizeof(c), base_size) + def test_copy(self): b = bytearray(b'abc') bb = b.copy() @@ -1456,7 +1554,6 @@ def by(s): b = by("Hello, world") self.assertEqual(re.findall(br"\w+", b), [by("Hello"), by("world")]) - @unittest.skip("TODO: RUSTPYTHON; segfault") def test_resize(self): ba = bytearray(b'abcdef') self.assertIsNone(ba.resize(3)) @@ -1494,6 +1591,199 @@ def test_resize(self): self.assertRaises(MemoryError, bytearray().resize, sys.maxsize) self.assertRaises(MemoryError, bytearray(1000).resize, sys.maxsize) + @support.nomemtest + def test_resize_error(self): + # gh-157242: If bytearray.resize() fails (MemoryError), + # the bytearray must be left unchanged. + + offset = 3 + for logical_offset in (False, True): + with self.subTest(logical_offset=logical_offset): + # grow bytearray + ba = bytearray(b'0123456789') + if logical_offset: + expected = ba[offset:] + del ba[:offset] + else: + expected = ba.copy() + with inject_memory_error(self): + ba.resize(1024) + self.assertEqual(ba, expected) + + # shrink bytearray + ba = bytearray(b'0123456789') + if logical_offset: + expected = ba[offset:] + del ba[:offset] + else: + expected = ba.copy() + with inject_memory_error(self): + ba.resize(1) + self.assertEqual(ba, expected) + + def test_take_bytes(self): + ba = bytearray(b'ab') + self.assertEqual(ba.take_bytes(), b'ab') + self.assertEqual(len(ba), 0) + self.assertEqual(ba, bytearray(b'')) + self.assertEqual(ba.__alloc__(), 0) + base_size = sys.getsizeof(bytearray()) + self.assertEqual(sys.getsizeof(ba), base_size) + + # Positive and negative slicing. + ba = bytearray(b'abcdef') + self.assertEqual(ba.take_bytes(1), b'a') + self.assertEqual(ba, bytearray(b'bcdef')) + self.assertEqual(len(ba), 5) + self.assertEqual(ba.take_bytes(-5), b'') + self.assertEqual(ba, bytearray(b'bcdef')) + self.assertEqual(len(ba), 5) + self.assertEqual(ba.take_bytes(-3), b'bc') + self.assertEqual(ba, bytearray(b'def')) + self.assertEqual(len(ba), 3) + self.assertEqual(ba.take_bytes(3), b'def') + self.assertEqual(ba, bytearray(b'')) + self.assertEqual(len(ba), 0) + + # Take nothing from emptiness. + self.assertEqual(ba.take_bytes(0), b'') + self.assertEqual(ba.take_bytes(), b'') + self.assertEqual(ba.take_bytes(None), b'') + + # Out of bounds, bad take value. + self.assertRaises(IndexError, ba.take_bytes, -1) + self.assertRaises(TypeError, ba.take_bytes, 3.14) + ba = bytearray(b'abcdef') + self.assertRaises(IndexError, ba.take_bytes, 7) + + # Offset between physical and logical start (ob_bytes != ob_start). + ba = bytearray(b'abcde') + del ba[:2] + self.assertEqual(ba, bytearray(b'cde')) + self.assertEqual(ba.take_bytes(), b'cde') + + # Overallocation at end. + ba = bytearray(b'abcde') + del ba[-2:] + self.assertEqual(ba, bytearray(b'abc')) + self.assertEqual(ba.take_bytes(), b'abc') + ba = bytearray(b'abcde') + ba.resize(4) + self.assertEqual(ba.take_bytes(), b'abcd') + + # Take of a bytearray with references should fail. + ba = bytearray(b'abc') + with memoryview(ba) as mv: + self.assertRaises(BufferError, ba.take_bytes) + self.assertEqual(ba.take_bytes(), b'abc') + + # Leaving one byte must not adopt the shared single-byte bytes object + # as the buffer. + ba = bytearray(b'abc') + self.assertEqual(ba.take_bytes(2), b'ab') + ba[0] = ord('A') + self.assertEqual(ba, bytearray(b'A')) + self.assertEqual(ord(b'c'), ord('c')) + + @support.nomemtest + def test_take_bytes_error(self): + # gh-157242: If bytearray.take_bytes() fails (MemoryError), + # the bytearray must be left unchanged. + + for logical_offset, to_take, start_list in ( + (True, 5, (0, 1)), + (False, 5, (0, 1)), + (True, None, (0,)), + ): + for start in start_list: + with self.subTest(logical_offset=logical_offset, start=start): + ba = bytearray(b'0123456789') + if logical_offset: + expected = ba[3:] + del ba[:3] + else: + expected = ba.copy() + with inject_memory_error(self, start): + ba.take_bytes(to_take) + self.assertEqual(ba, expected) + + @support.cpython_only # tests an implementation detail + def test_take_bytes_optimization(self): + # Validate optimization around taking lots of little chunks out of a + # much bigger buffer. Save work by only copying a little rather than + # moving a lot. + ba = bytearray(b'abcdef' + b'0' * 1000) + start_alloc = ba.__alloc__() + + # Take two bytes at a time, checking alloc doesn't change. + self.assertEqual(ba.take_bytes(2), b'ab') + self.assertEqual(ba.__alloc__(), start_alloc) + self.assertEqual(len(ba), 4 + 1000) + self.assertEqual(ba.take_bytes(2), b'cd') + self.assertEqual(ba.__alloc__(), start_alloc) + self.assertEqual(len(ba), 2 + 1000) + self.assertEqual(ba.take_bytes(2), b'ef') + self.assertEqual(ba.__alloc__(), start_alloc) + self.assertEqual(len(ba), 0 + 1000) + self.assertEqual(ba.__alloc__(), start_alloc) + + # Take over half, alloc shrinks to exact size. + self.assertEqual(ba.take_bytes(501), b'0' * 501) + self.assertEqual(len(ba), 499) + bytes_header_size = sys.getsizeof(b'') + self.assertEqual(ba.__alloc__(), 499 + bytes_header_size) + + def test_take_bytes_hash(self): + # gh-158219: bytearray constructor must not use a bytes object + # if its hash value is already cached. + + def encode(string, errors='strict'): + encoded = string.encode('utf-8') + hash(encoded) # a codec may hash its own output + return encoded, len(string) + + def hashing_codec(name): + if name != 'test_take_bytes_hash': + return None + return codecs.CodecInfo(encode, None, name=name) + + codecs.register(hashing_codec) + self.addCleanup(codecs.unregister, hashing_codec) + + ba = bytearray('hello', 'test_take_bytes_hash') + ba[0] = ord('H') + taken = ba.take_bytes() + self.assertEqual(taken, b'Hello') + self.assertEqual(hash(taken), hash(b'Hello')) + + def test_take_bytes_reentrant_resize(self): + # gh-153570: n.__index__() can resize the bytearray, so take_bytes() + # must re-read the size afterwards. It cached the size before the + # call and used it for the bounds check and the buffer reads, so a + # reentrant clear() returned freed memory (a use-after-free read). + def take(target, resize, n): + class Evil: + def __index__(self): + resize(target) + return n + return target.take_bytes(Evil()) + + # clear() during __index__: nothing is left to take. + ba = bytearray(b'abcdefgh') + with self.assertRaises(IndexError): + take(ba, lambda b: b.clear(), 8) + self.assertEqual(ba, b'') + + # shrink during __index__: n past the new size is out of range. + ba = bytearray(b'abcdefgh') + with self.assertRaises(IndexError): + take(ba, lambda b: b.__delitem__(slice(4, None)), 8) + self.assertEqual(ba, b'abcd') + + # grow during __index__: the take runs against the new, larger size. + ba = bytearray(b'abcd') + self.assertEqual(take(ba, lambda b: b.extend(b'efgh'), 8), b'abcdefgh') + self.assertEqual(ba, b'') @unittest.expectedFailure # TODO: RUSTPYTHON def test_setitem(self): @@ -1659,6 +1949,30 @@ def test_setslice_trap(self): b[8:] = b self.assertEqual(b, bytearray(list(range(8)) + list(range(256)))) + def test_setslice_reentrant_resize(self): + # gh-153578: a buffer argument whose __buffer__ resizes the bytearray + # while the buffer is being acquired must not leave the slice bounds + # with lo > hi, which drove a negative-size memmove (an out-of-bounds + # write) in the setslice path reached through extend(). + class Evil: + def __init__(self, resize): + self.resize = resize + def __buffer__(self, flags): + self.resize() + return memoryview(b'ABCDEFGH') + # clear() during __buffer__: extend appends to the emptied bytearray. + b = bytearray(b'x' * 100) + b.extend(Evil(b.clear)) + self.assertEqual(b, b'ABCDEFGH') + # partial shrink during __buffer__. + b = bytearray(b'x' * 100) + b.extend(Evil(lambda: b.__delitem__(slice(30, None)))) + self.assertEqual(b, b'x' * 30 + b'ABCDEFGH') + # grow during __buffer__: the data lands at the original end. + b = bytearray(b'x' * 10) + b.extend(Evil(lambda: b.extend(b'y' * 100))) + self.assertEqual(b, b'x' * 10 + b'ABCDEFGH' + b'y' * 100) + def test_iconcat(self): b = bytearray(b"abc") b1 = b @@ -1733,7 +2047,6 @@ def g(): # self.assertGreater(alloc, len(b)) self.assertGreaterEqual(alloc, len(b)) # NOTE: RUSTPYTHON patched - @unittest.expectedFailure # TODO: RUSTPYTHON def test_extend(self): orig = b'hello' a = bytearray(orig) @@ -1862,7 +2175,6 @@ def test_partition_bytearray_doesnt_share_nullstring(self): self.assertEqual(b, b"") self.assertEqual(c, b"") - @unittest.expectedFailure # TODO: RUSTPYTHON; BufferError: Existing exports of data: object cannot be re-sized def test_resize_forbidden(self): # #4509: can't resize a bytearray when there are buffer exports, even # if it wouldn't reallocate the underlying buffer. @@ -2013,7 +2325,6 @@ def __index__(self): self.assertEqual(instance.ba[0], ord("?"), "Assigned bytearray not altered") self.assertEqual(instance.new_ba, bytearray(0x180), "Wrong object altered") - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: unexpected type Evil def test_search_methods_reentrancy_raises_buffererror(self): # gh-142560: Raise BufferError if buffer mutates during search arg conversion. class Evil: @@ -2063,7 +2374,6 @@ def __length_hint__(self): self.assertRaises(ValueError, float, bytearray()) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: BufferError not raised by hex def test_hex_use_after_free(self): # Prevent UAF in bytearray.hex(sep) with re-entrant sep.__len__. # Regression test for https://github.com/python/cpython/issues/143195. @@ -2076,9 +2386,55 @@ def __len__(self): self.assertRaises(BufferError, ba.hex, S(b':')) - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_mod(self): - return super().test_mod() + def test_no_init_called(self): + # A bytearray created without calling bytearray.__init__ + # should not crash the interpreter (see gh-153419). + def bytearray_new(): + return bytearray.__new__(bytearray) + + bytearray_new().insert(0, 1) + bytearray_new().extend(b"x") + bytearray_new().extend([1, 2, 3]) + bytearray_new().resize(4) + bytearray_new().__init__(5) + bytearray_new().__init__(b"xyz") + bytearray_new().take_bytes() + bytearray_new().take_bytes(0) + + a = bytearray_new() + a.append(1) + + a = bytearray_new() + a += b"x" + + a = bytearray_new() + a[:] = b"xyz" + + def test_reinit_length(self): + # There is a shortcut taken when resizing, where alloc/2 < newsize. + # In this case, the existing buffer is reused, rather than reset. + # If this happens when newsize == 0 and alloc == 1, then various + # code assumptions can be violated. This test should catch those + # in debug builds. (see gh-153419) + a = bytearray(1) + a.__init__() + self.assertEqual(a, b"") + + def test_reinit_with_view(self): + a = bytearray() + with memoryview(a): + self.assertRaises(BufferError, a.__init__, "x", "ascii") + self.assertEqual(a, b"") + + def test_reinit_error(self): + # A failed __init__() must not leave uninitialized bytes in the + # object: it must be empty afterwards. + for source in ([256] * 100, (-1,) * 100, [0] * 50 + [1000], + (1, 2, 1 << 100)): + with self.subTest(source=source): + a = bytearray(b"abc") + self.assertRaises(ValueError, a.__init__, source) + self.assertEqual(a, b"") class AssortedBytesTest(unittest.TestCase): @@ -2108,7 +2464,7 @@ def test_bytearray_repr(self, f=repr): self.assertEqual(f(bytearray([7, 8, 9, 10, 11, 12, 13])), r"bytearray(b'\x07\x08\t\n\x0b\x0c\r')") self.assertEqual(f(bytearray(b'"')), """bytearray(b'"')""") # '"' - self.assertEqual(f(bytearray(b"'")), r'''bytearray(b"\'")''') # "\'" + self.assertEqual(f(bytearray(b"'")), '''bytearray(b"'")''') # "'" self.assertEqual(f(bytearray(b"'\"")), r"""bytearray(b'\'"')""") # '\'"' self.assertEqual(f(bytearray(b"\"'\"")), r"""bytearray(b'"\'"')""") # '"\'"' self.assertEqual(f(bytearray(b'\'"\'')), r"""bytearray(b'\'"\'')""") # '\'"\'' @@ -2427,14 +2783,6 @@ class ByteArraySubclassWithSlotsTest(SubclassTest, unittest.TestCase): basetype = bytearray type2test = ByteArraySubclassWithSlots - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_copy(self): - return super().test_copy() - - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_pickle(self): - return super().test_pickle() - class BytesSubclassTest(SubclassTest, unittest.TestCase): basetype = bytes type2test = BytesSubclass @@ -2701,6 +3049,18 @@ def resize(b, a): # MODIFIES! b.wait() a.resize(10) + def take_bytes(b, a): # MODIFIES! + b.wait() + c = a.take_bytes() + assert not c or c[0] == 48 # '0' + + def take_bytes_n(b, a): # MODIFIES! + b.wait() + try: + c = a.take_bytes(10) + assert c == b'0123456789' + except IndexError: pass + def check(funcs, a=None, *args): if a is None: a = bytearray(b'0' * 0x400000) @@ -2765,6 +3125,10 @@ def check(funcs, a=None, *args): check([clear] + [resize] * 10) + check([clear] + [take_bytes] * 10) + check([take_bytes_n] * 10, bytearray(b'0123456789' * 0x400)) + check([take_bytes_n] * 10, bytearray(b'0123456789' * 5)) + check([clear] + [contains] * 10) check([clear] + [subscript] * 10) check([clear2] + [ass_subscript2] * 10, None, bytearray(b'0' * 0x400000)) @@ -2837,5 +3201,18 @@ def resize_stress(ba): with threading_helper.start_threads(threads): pass + @threading_helper.reap_threads + @threading_helper.requires_working_threading() + def test_free_threading_bytearray_resize_other_thread(self): + # Shrinking a bytearray whose buffer another thread owns must not + # adopt the immortal single-byte bytes object a the buffer. + ba = bytearray(b'abc') + thread = threading.Thread(target=ba.resize, args=(1,)) + with threading_helper.start_threads([thread]): + pass + ba[0] = ord('X') + self.assertEqual(ba, bytearray(b'X')) + self.assertEqual(ord(b'a'), ord('a')) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_c_locale_coercion.py b/Lib/test/test_c_locale_coercion.py index 71f934756e2..340bec3c71b 100644 --- a/Lib/test/test_c_locale_coercion.py +++ b/Lib/test/test_c_locale_coercion.py @@ -12,8 +12,10 @@ from test.support.script_helper import run_python_until_end -# Set the list of ways we expect to be able to ask for the "C" locale -EXPECTED_C_LOCALE_EQUIVALENTS = ["C", "invalid.ascii"] +# Set the list of ways we expect to be able to ask for the "C" locale. +# 'invalid.ascii' is an invalid LOCALE name and so should get turned in to the +# default locale, which is traditionally C. +EXPECTED_C_LOCALE_EQUIVALENTS = ["C", "POSIX", "invalid.ascii"] # Set our expectation for the default encoding used in the C locale # for the filesystem encoding and the standard streams @@ -21,22 +23,22 @@ EXPECTED_C_LOCALE_FS_ENCODING = "ascii" # Set our expectation for the default locale used when none is specified +DEFAULT_LOCALE_IS_C = True EXPECT_COERCION_IN_DEFAULT_LOCALE = True TARGET_LOCALES = ["C.UTF-8", "C.utf8", "UTF-8"] # Apply some platform dependent overrides -if sys.platform.startswith("linux"): - if support.is_android: - # Android defaults to using UTF-8 for all system interfaces - EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8" - EXPECTED_C_LOCALE_FS_ENCODING = "utf-8" - else: - # Linux distros typically alias the POSIX locale directly to the C - # locale. - # TODO: Once https://bugs.python.org/issue30672 is addressed, we'll be - # able to check this case unconditionally - EXPECTED_C_LOCALE_EQUIVALENTS.append("POSIX") +if sys.platform == "android": + # Android defaults to using UTF-8 for all system interfaces + EXPECTED_C_LOCALE_STREAM_ENCODING = "utf-8" + EXPECTED_C_LOCALE_FS_ENCODING = "utf-8" +elif support.linked_to_musl(): + # MUSL defaults to utf-8 unless the C locale is set explicitly. + EXPECTED_C_LOCALE_EQUIVALENTS = ["C"] + DEFAULT_LOCALE_IS_C = False + DEFAULT_ENCODING = 'utf-8' + EXPECT_COERCION_IN_DEFAULT_LOCALE = False elif sys.platform.startswith("aix"): # AIX uses iso8859-1 in the C locale, other *nix platforms use ASCII EXPECTED_C_LOCALE_STREAM_ENCODING = "iso8859-1" @@ -112,12 +114,16 @@ class EncodingDetails(_EncodingDetails): ]) @classmethod - def get_expected_details(cls, coercion_expected, fs_encoding, stream_encoding, env_vars): + def get_expected_details(cls, coercion_expected, fs_encoding, stream_encoding, stream_errors, env_vars): """Returns expected child process details for a given encoding""" _stream = stream_encoding + ":{}" - # stdin and stdout should use surrogateescape either because the - # coercion triggered, or because the C locale was detected - stream_info = 2*[_stream.format("surrogateescape")] + if stream_errors is None: + # stdin and stdout should use surrogateescape either because the + # coercion triggered, or because the C locale was detected + stream_errors = "surrogateescape" + + stream_info = [_stream.format(stream_errors)] * 2 + # stderr should always use backslashreplace stream_info.append(_stream.format("backslashreplace")) expected_lang = env_vars.get("LANG", "not set") @@ -210,6 +216,7 @@ def _check_child_encoding_details(self, env_vars, expected_fs_encoding, expected_stream_encoding, + expected_stream_errors, expected_warnings, coercion_expected): """Check the C locale handling for the given process environment @@ -225,6 +232,7 @@ def _check_child_encoding_details(self, coercion_expected, expected_fs_encoding, expected_stream_encoding, + expected_stream_errors, env_vars ) self.assertEqual(encoding_details, expected_details) @@ -257,6 +265,7 @@ def test_external_target_locale_configuration(self): "LC_CTYPE": "", "LC_ALL": "", "PYTHONCOERCECLOCALE": "", + "PYTHONIOENCODING": "", } for env_var in ("LANG", "LC_CTYPE"): for locale_to_set in AVAILABLE_TARGETS: @@ -273,10 +282,43 @@ def test_external_target_locale_configuration(self): self._check_child_encoding_details(var_dict, expected_fs_encoding, expected_stream_encoding, + expected_stream_errors=None, expected_warnings=None, coercion_expected=False) + def test_with_ioencoding(self): + # Explicitly setting a target locale should give the same behaviour as + # is seen when implicitly coercing to that target locale + self.maxDiff = None + + expected_fs_encoding = "utf-8" + expected_stream_encoding = "utf-8" + + base_var_dict = { + "LANG": "", + "LC_CTYPE": "", + "LC_ALL": "", + "PYTHONCOERCECLOCALE": "", + "PYTHONIOENCODING": "UTF-8", + } + for env_var in ("LANG", "LC_CTYPE"): + for locale_to_set in AVAILABLE_TARGETS: + # XXX (ncoghlan): LANG=UTF-8 doesn't appear to work as + # expected, so skip that combination for now + # See https://bugs.python.org/issue30672 for discussion + if env_var == "LANG" and locale_to_set == "UTF-8": + continue + with self.subTest(env_var=env_var, + configured_locale=locale_to_set): + var_dict = base_var_dict.copy() + var_dict[env_var] = locale_to_set + self._check_child_encoding_details(var_dict, + expected_fs_encoding, + expected_stream_encoding, + expected_stream_errors="strict", + expected_warnings=None, + coercion_expected=False) @support.cpython_only @unittest.skipUnless(sysconfig.get_config_var("PY_COERCE_C_LOCALE"), @@ -316,15 +358,21 @@ def _check_c_locale_coercion(self, "LC_CTYPE": "", "LC_ALL": "", "PYTHONCOERCECLOCALE": "", + "PYTHONIOENCODING": "", } base_var_dict.update(extra_vars) if coerce_c_locale is not None: base_var_dict["PYTHONCOERCECLOCALE"] = coerce_c_locale # Check behaviour for the default locale + _fs_encoding = fs_encoding + _stream_encoding = stream_encoding + if not DEFAULT_LOCALE_IS_C and 'LC_ALL' not in extra_vars: + _fs_encoding = _stream_encoding = DEFAULT_ENCODING with self.subTest(default_locale=True, PYTHONCOERCECLOCALE=coerce_c_locale): - if EXPECT_COERCION_IN_DEFAULT_LOCALE: + if (EXPECT_COERCION_IN_DEFAULT_LOCALE + or (not DEFAULT_LOCALE_IS_C and 'LC_ALL' in extra_vars)): _expected_warnings = expected_warnings _coercion_expected = coercion_expected else: @@ -338,8 +386,9 @@ def _check_c_locale_coercion(self, _expected_warnings == [CLI_COERCION_WARNING]): _expected_warnings = None self._check_child_encoding_details(base_var_dict, - fs_encoding, - stream_encoding, + _fs_encoding, + _stream_encoding, + None, _expected_warnings, _coercion_expected) @@ -348,13 +397,15 @@ def _check_c_locale_coercion(self, for env_var in ("LANG", "LC_CTYPE"): with self.subTest(env_var=env_var, nominal_locale=locale_to_set, - PYTHONCOERCECLOCALE=coerce_c_locale): + PYTHONCOERCECLOCALE=coerce_c_locale, + PYTHONIOENCODING=""): var_dict = base_var_dict.copy() var_dict[env_var] = locale_to_set # Check behaviour on successful coercion self._check_child_encoding_details(var_dict, fs_encoding, stream_encoding, + None, expected_warnings, coercion_expected) @@ -411,8 +462,9 @@ def test_PYTHONCOERCECLOCALE_set_to_one(self): loc = locale.setlocale(locale.LC_CTYPE, "") except locale.Error as e: self.skipTest(str(e)) - if loc == "C": - self.skipTest("test requires LC_CTYPE locale different than C") + if loc in ("C", "POSIX"): + self.skipTest("test requires LC_CTYPE locale different " + "than C and POSIX") if loc in TARGET_LOCALES : self.skipTest("coerced LC_CTYPE locale: %s" % loc) diff --git a/Lib/test/test_calendar.py b/Lib/test/test_calendar.py index 50ccf66b8da..04eb5155a82 100644 --- a/Lib/test/test_calendar.py +++ b/Lib/test/test_calendar.py @@ -8,6 +8,7 @@ import io import locale import os +import platform import sys import time @@ -112,18 +113,25 @@ default_format = dict(year="year", month="month", encoding="ascii") +result_2004_css = """""" + result_2004_html = """\ - - - + + - - + + Calendar for 2004 +{css_styles} + - -
2004
+
+
2004
@@ -132,7 +140,7 @@
January
MonTueWedThuFriSatSun
   1234
19202122232425
262728293031 
-
+
@@ -141,7 +149,7 @@
February
MonTueWedThuFriSatSun
      1
16171819202122
23242526272829
-
+
@@ -150,7 +158,7 @@
March
MonTueWedThuFriSatSun
1234567
22232425262728
293031    
-
+
@@ -159,7 +167,7 @@
April
MonTueWedThuFriSatSun
   1234
19202122232425
2627282930  
-
+
@@ -169,7 +177,7 @@
May
MonTueWedThuFriSatSun
     12
24252627282930
31      
-
+
@@ -178,7 +186,7 @@
June
MonTueWedThuFriSatSun
 123456
21222324252627
282930    
-
+
@@ -187,7 +195,7 @@
July
MonTueWedThuFriSatSun
   1234
19202122232425
262728293031 
-
+ - - + + - - - - - - + + + + + + - - + + - - - - - - - - - + + + + + + + + +
@@ -197,7 +205,7 @@
August
MonTueWedThuFriSatSun
      1
23242526272829
3031     
-
+ - - + + - - - - - - + + + + + + - - + + - - - - - - - - - + + + + + + + + +
@@ -206,7 +214,7 @@
September
MonTueWedThuFriSatSun
  12345
20212223242526
27282930   
-
+ - - + + - - - - - - + + + + + + - - + + - - - - - - - - - + + + + + + + + +
@@ -215,7 +223,7 @@
October
MonTueWedThuFriSatSun
    123
18192021222324
25262728293031
-
+ - - - - - + + + + +
@@ -224,7 +232,7 @@
November
MonTueWedThuFriSatSun
1234567
22232425262728
2930     
-
+ - - - - - + + + + +
@@ -237,6 +245,34 @@ """ +result_2009_6_html = """\ + + + + + +Calendar for 2009 + + + + +
December
MonTueWedThuFriSatSun
  12345
+ + + + + + + +
June 2009
MonTueWedThuFriSatSun
1234567
891011121314
15161718192021
22232425262728
2930     
+ + +""" + result_2004_days = [ [[[0, 0, 0, 1, 2, 3, 4], [5, 6, 7, 8, 9, 10, 11], @@ -384,10 +420,12 @@ def check_htmlcalendar_encoding(self, req, res): cal = calendar.HTMLCalendar() format_ = default_format.copy() format_["encoding"] = req or 'utf-8' + format_with_css = {**format_, "css_styles": result_2004_css} + formatted_html = result_2004_html.format(**format_with_css) output = cal.formatyearpage(2004, encoding=req) self.assertEqual( output, - result_2004_html.format(**format_).encode(res) + formatted_html.encode(res) ) def test_output(self): @@ -417,7 +455,7 @@ def test_output_htmlcalendar_encoding_utf8(self): self.check_htmlcalendar_encoding('utf-8', 'utf-8') def test_output_htmlcalendar_encoding_default(self): - self.check_htmlcalendar_encoding(None, sys.getdefaultencoding()) + self.check_htmlcalendar_encoding(None, 'utf-8') def test_yeardatescalendar(self): def shrink(cal): @@ -501,6 +539,19 @@ def test_format(self): calendar.format(["1", "2", "3"], colwidth=3, spacing=1) self.assertEqual(out.getvalue().strip(), "1 2 3") + def test_format_html_year_with_month(self): + self.assertEqual( + calendar.HTMLCalendar().formatmonthpage(2009, 6).decode("ascii"), + result_2009_6_html + ) + + def test_formatmonthpage_no_width(self): + # gh-140212: formatmonthpage must not accept a 'width' argument. + cal = calendar.HTMLCalendar() + self.assertIn(b'class="month">June 2009', cal.formatmonthpage(2009, 6)) + self.assertRaises(TypeError, cal.formatmonthpage, 2009, 6, width=3) + + class CalendarTestCase(unittest.TestCase): def test_deprecation_warning(self): @@ -556,7 +607,8 @@ def test_days(self): self.assertEqual(value[::-1], list(reversed(value))) def test_months(self): - for attr in "month_name", "month_abbr": + for attr in ("month_name", "month_abbr", "standalone_month_name", + "standalone_month_abbr"): value = getattr(calendar, attr) self.assertEqual(len(value), 13) self.assertEqual(len(value[:]), 13) @@ -566,6 +618,38 @@ def test_months(self): # verify it "acts like a sequence" in two forms of iteration self.assertEqual(value[::-1], list(reversed(value))) + @support.run_with_locale('LC_ALL', 'pl_PL') + @unittest.skipUnless(sys.platform == 'darwin' or platform.libc_ver()[0] == 'glibc', + "Guaranteed to work with glibc and macOS") + def test_standalone_month_name_and_abbr_pl_locale(self): + expected_standalone_month_names = [ + "", "styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", + "lipiec", "sierpień", "wrzesień", "październik", "listopad", + "grudzień" + ] + expected_standalone_month_abbr = [ + "", "sty", "lut", "mar", "kwi", "maj", "cze", + "lip", "sie", "wrz", "paź", "lis", "gru" + ] + self.assertEqual( + list(calendar.standalone_month_name), + expected_standalone_month_names + ) + self.assertEqual( + list(calendar.standalone_month_abbr), + expected_standalone_month_abbr + ) + + def test_standalone_month_name_and_abbr_C_locale(self): + # Ensure that the standalone month names and abbreviations are + # equal to the regular month names and abbreviations for + # the "C" locale. + with calendar.different_locale("C"): + self.assertListEqual(list(calendar.month_name), + list(calendar.standalone_month_name)) + self.assertListEqual(list(calendar.month_abbr), + list(calendar.standalone_month_abbr)) + def test_locale_text_calendar(self): try: cal = calendar.LocaleTextCalendar(locale='') @@ -672,6 +756,57 @@ def test_locale_calendar_formatweekday(self): except locale.Error: raise unittest.SkipTest('cannot set the en_US locale') + # These locales have weekday names all shorter than English's longest + # 'Wednesday'. They should not be abbreviated unnecessarily + @support.run_with_locales("LC_ALL", + 'Chinese', 'zh_CN.UTF-8', + 'French', 'fr_FR.UTF-8', + 'Norwegian', 'nb_NO.UTF-8', + 'Malay', 'ms_MY.UTF8' + ) + def test_locale_calendar_short_weekday_names(self): + names = (datetime.date(2001, 1, i+1).strftime('%A') for i in range(7)) + max_length = max(map(len, names)) + if max_length >= 9: + self.skipTest('weekday names are too long') + + def get_weekday_names(width): + return calendar.TextCalendar().formatweekheader(width).split() + + # Weekday names should not be abbreviated if the width is sufficient + self.assertEqual( + get_weekday_names(max_length), + get_weekday_names(max_length + 10) + ) + + # Any width shorter than necessary should produce abbreviations + self.assertNotEqual( + get_weekday_names(max_length), + get_weekday_names(max_length - 1) + ) + + # These locales have a weekday name longer than 'Wednesday' + # They should be properly abbreviated rather than truncated + @support.run_with_locales("LC_ALL", + 'Portuguese', 'pt_PT.UTF-8', + 'German', 'de_DE.UTF-8', + 'Russian', 'ru_RU.UTF-8', + ) + def test_locale_calendar_long_weekday_names(self): + names = (datetime.date(2001, 1, i+1).strftime('%A') for i in range(7)) + max_length = max(map(len, names)) + abbrev_names = (datetime.date(2001, 1, i+1).strftime('%a') for i in range(7)) + abbrev_max_length = max(map(len, abbrev_names)) + + if max_length <= 9: + self.skipTest('weekday names are too short') + if abbrev_max_length >= 9: + self.skipTest('abbreviated weekday names are too long') + + def get_weekday_names(width): + return calendar.TextCalendar().formatweekheader(width).split() + self.assertEqual(get_weekday_names(abbrev_max_length), get_weekday_names(max_length-1)) + def test_locale_calendar_formatmonthname(self): try: # formatmonthname uses the same month names regardless of the width argument. @@ -944,6 +1079,7 @@ def test_several_leapyears_in_range(self): def conv(s): return s.replace('\n', os.linesep).encode() +@support.force_not_colorized_test_class class CommandLineTestCase(unittest.TestCase): def setUp(self): self.runners = [self.run_cli_ok, self.run_cmd_ok] @@ -997,7 +1133,6 @@ def assertFailure(self, *args): self.assertCLIFails(*args) self.assertCmdFails(*args) - @support.force_not_colorized def test_help(self): stdout = self.run_cmd_ok('-h') self.assertIn(b'usage:', stdout) @@ -1018,7 +1153,6 @@ def test_illegal_arguments(self): self.assertFailure('2004', '1', 'spam') self.assertFailure('2004', '1', '1') self.assertFailure('2004', '1', '1', 'spam') - self.assertFailure('-t', 'html', '2004', '1') def test_output_current_year(self): for run in self.runners: @@ -1108,7 +1242,7 @@ def test_option_type(self): output = run('--type', 'text', '2004') self.assertEqual(output, conv(result_2004_text)) output = run('--type', 'html', '2004') - self.assertStartsWith(output, b'') self.assertIn(b'Calendar for 2004', output) def test_html_output_current_year(self): @@ -1121,15 +1255,25 @@ def test_html_output_current_year(self): def test_html_output_year_encoding(self): for run in self.runners: output = run('-t', 'html', '--encoding', 'ascii', '2004') - self.assertEqual(output, result_2004_html.format(**default_format).encode('ascii')) + format_with_css = default_format.copy() + format_with_css["css_styles"] = result_2004_css + self.assertEqual(output, result_2004_html.format(**format_with_css).encode('ascii')) def test_html_output_year_css(self): self.assertFailure('-t', 'html', '-c') self.assertFailure('-t', 'html', '--css') for run in self.runners: output = run('-t', 'html', '--css', 'custom.css', '2004') - self.assertIn(b'', output) + self.assertIn(b'', output) + + +@support.force_colorized_test_class +class ColorTestCase(unittest.TestCase): + def test_formatmonth_color(self): + today = datetime.date(2026, 5, 4) + cal = calendar._CLIDemoCalendar(highlight_day=today) + output = cal.formatmonth(2026, 5) + self.assertIn("\x1b[30m\x1b[43mMay 2026\x1b[0m\n\x1b[36m", output) class MiscTestCase(unittest.TestCase): @@ -1183,7 +1327,7 @@ def test_formatweek_head(self): def test_format_year(self): self.assertIn( - ('' % + ('
' % self.cal.cssclass_year), self.cal.formatyear(2017)) def test_format_year_head(self): diff --git a/Lib/test/test_call.py b/Lib/test/test_call.py index b18f16a6efc..76f1c351e15 100644 --- a/Lib/test/test_call.py +++ b/Lib/test/test_call.py @@ -3,7 +3,7 @@ set_recursion_limit, skip_on_s390x, skip_emscripten_stack_overflow, skip_wasi_stack_overflow, skip_if_sanitizer, - import_helper) + skip_if_huge_c_stack, import_helper) try: import _testcapi except ImportError: @@ -47,6 +47,54 @@ def fn(**kw): self.assertIsInstance(res, dict) self.assertEqual(list(res.items()), expected) + def test_kwargs_order_preserved(self): + # PEP 468: Preserving Keyword Argument Order + def fn(**kw): + return list(kw) + + self.assertEqual(fn(b=1, a=2, c=3), ['b', 'a', 'c']) + self.assertEqual(fn(c=3, a=2, b=1), ['c', 'a', 'b']) + # Unpacked mappings are merged in place, keeping their own order. + self.assertEqual(fn(z=0, **{'x': 1, 'a': 2}, y=3), + ['z', 'x', 'a', 'y']) + self.assertEqual(fn(**{'b': 1}, **{'a': 2}), ['b', 'a']) + # Named parameters are removed from **kwargs without reordering + # the rest. + def fn2(a, c=None, **kw): + return list(kw) + + self.assertEqual(fn2(d=1, a=2, b=3, c=4, e=5), ['d', 'b', 'e']) + + def test_kwargs_order_preserved_in_methods(self): + # PEP 468: Preserving Keyword Argument Order + class C: + def __init__(self, **kw): + self.init_kw = list(kw) + + def meth(self, **kw): + return list(kw) + + @classmethod + def cmeth(cls, **kw): + return list(kw) + + @staticmethod + def smeth(**kw): + return list(kw) + + c = C(b=1, a=2, c=3) + self.assertEqual(c.init_kw, ['b', 'a', 'c']) + self.assertEqual(c.meth(b=1, a=2, c=3), ['b', 'a', 'c']) + self.assertEqual(C.cmeth(b=1, a=2, c=3), ['b', 'a', 'c']) + self.assertEqual(C.smeth(b=1, a=2, c=3), ['b', 'a', 'c']) + + def test_kwargs_order_preserved_in_c_functions(self): + # PEP 468: Preserving Keyword Argument Order + self.assertEqual(list(dict(b=1, a=2, c=3)), ['b', 'a', 'c']) + self.assertEqual(list(dict(**{'b': 1}, a=2)), ['b', 'a']) + self.assertEqual(list(collections.OrderedDict(b=1, a=2, c=3)), + ['b', 'a', 'c']) + def test_frames_are_popped_after_failed_calls(self): # GH-93252: stuff blows up if we don't pop the new frame after # recovering from failed calls: @@ -1052,16 +1100,17 @@ def get_sp(): self.assertLess(lower_sp, this_sp) safe_margin = this_sp - lower_sp else: - self.assertLess(this_sp, lower_sp) + self.assertGreater(lower_sp, this_sp) safe_margin = lower_sp - this_sp - # Add an (arbitrary) extra 20% for safety - safe_margin *= 6 / 5 + # Add an (arbitrary) extra 25% for safety + safe_margin = safe_margin * 5 / 4 self.assertLess(safe_margin, _testinternalcapi.get_stack_margin()) @skip_on_s390x @unittest.skipIf(is_wasi and Py_DEBUG, "requires deep stack") @skip_if_sanitizer("requires deep stack", thread=True) @unittest.skipIf(_testcapi is None, "requires _testcapi") + @skip_if_huge_c_stack(90_000) @skip_emscripten_stack_overflow() @skip_wasi_stack_overflow() def test_super_deep(self): diff --git a/Lib/test/test_capi/__init__.py b/Lib/test/test_capi/__init__.py new file mode 100644 index 00000000000..5a8ba684539 --- /dev/null +++ b/Lib/test/test_capi/__init__.py @@ -0,0 +1,12 @@ +import os +import unittest +from test.support import load_package_tests +from test.support import TEST_MODULES_ENABLED + + +if not TEST_MODULES_ENABLED: + raise unittest.SkipTest("requires test modules") + + +def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_capi/__main__.py b/Lib/test/test_capi/__main__.py new file mode 100644 index 00000000000..05d01775ddf --- /dev/null +++ b/Lib/test/test_capi/__main__.py @@ -0,0 +1,3 @@ +import unittest + +unittest.main('test.test_capi') diff --git a/Lib/test/test_capi/test_abstract.py b/Lib/test/test_capi/test_abstract.py new file mode 100644 index 00000000000..e455a863620 --- /dev/null +++ b/Lib/test/test_capi/test_abstract.py @@ -0,0 +1,1119 @@ +import unittest +from collections import OrderedDict +from test import support +from test.support import import_helper + +_testcapi = import_helper.import_module('_testcapi') +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') +from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX + +NULL = None + +class StrSubclass(str): + pass + +class BytesSubclass(bytes): + pass + +class WithStr: + def __init__(self, value): + self.value = value + def __str__(self): + return self.value + +class WithRepr: + def __init__(self, value): + self.value = value + def __repr__(self): + return self.value + +class WithBytes: + def __init__(self, value): + self.value = value + def __bytes__(self): + return self.value + +class TestObject: + @property + def evil(self): + raise RuntimeError('do not get evil') + @evil.setter + def evil(self, value): + raise RuntimeError('do not set evil') + @evil.deleter + def evil(self): + raise RuntimeError('do not del evil') + +class ProxyGetItem: + def __init__(self, obj): + self.obj = obj + def __getitem__(self, key): + return self.obj[key] + +class ProxySetItem: + def __init__(self, obj): + self.obj = obj + def __setitem__(self, key, value): + self.obj[key] = value + +class ProxyDelItem: + def __init__(self, obj): + self.obj = obj + def __delitem__(self, key): + del self.obj[key] + +def gen(): + yield 'a' + yield 'b' + yield 'c' + + +class CAPITest(unittest.TestCase): + def assertTypedEqual(self, actual, expected): + self.assertIs(type(actual), type(expected)) + self.assertEqual(actual, expected) + + def test_object_str(self): + # Test PyObject_Str() + object_str = _testlimitedcapi.object_str + self.assertTypedEqual(object_str(''), '') + self.assertTypedEqual(object_str('abc'), 'abc') + self.assertTypedEqual(object_str('\U0001f40d'), '\U0001f40d') + self.assertTypedEqual(object_str(StrSubclass('abc')), 'abc') + self.assertTypedEqual(object_str(WithStr('abc')), 'abc') + self.assertTypedEqual(object_str(WithStr(StrSubclass('abc'))), StrSubclass('abc')) + self.assertTypedEqual(object_str(WithRepr('')), '') + self.assertTypedEqual(object_str(WithRepr(StrSubclass(''))), StrSubclass('')) + self.assertTypedEqual(object_str(NULL), '') + + def test_object_repr(self): + # Test PyObject_Repr() + object_repr = _testlimitedcapi.object_repr + self.assertTypedEqual(object_repr(''), "''") + self.assertTypedEqual(object_repr('abc'), "'abc'") + self.assertTypedEqual(object_repr('\U0001f40d'), "'\U0001f40d'") + self.assertTypedEqual(object_repr(StrSubclass('abc')), "'abc'") + self.assertTypedEqual(object_repr(WithRepr('')), '') + self.assertTypedEqual(object_repr(WithRepr(StrSubclass(''))), StrSubclass('')) + self.assertTypedEqual(object_repr(WithRepr('<\U0001f40d>')), '<\U0001f40d>') + self.assertTypedEqual(object_repr(WithRepr(StrSubclass('<\U0001f40d>'))), StrSubclass('<\U0001f40d>')) + self.assertTypedEqual(object_repr(NULL), '') + + def test_object_ascii(self): + # Test PyObject_ASCII() + object_ascii = _testlimitedcapi.object_ascii + self.assertTypedEqual(object_ascii(''), "''") + self.assertTypedEqual(object_ascii('abc'), "'abc'") + self.assertTypedEqual(object_ascii('\U0001f40d'), r"'\U0001f40d'") + self.assertTypedEqual(object_ascii(StrSubclass('abc')), "'abc'") + self.assertTypedEqual(object_ascii(WithRepr('')), '') + self.assertTypedEqual(object_ascii(WithRepr(StrSubclass(''))), StrSubclass('')) + self.assertTypedEqual(object_ascii(WithRepr('<\U0001f40d>')), r'<\U0001f40d>') + self.assertTypedEqual(object_ascii(WithRepr(StrSubclass('<\U0001f40d>'))), r'<\U0001f40d>') + self.assertTypedEqual(object_ascii(NULL), '') + + def test_object_bytes(self): + # Test PyObject_Bytes() + object_bytes = _testlimitedcapi.object_bytes + self.assertTypedEqual(object_bytes(b''), b'') + self.assertTypedEqual(object_bytes(b'abc'), b'abc') + self.assertTypedEqual(object_bytes(BytesSubclass(b'abc')), b'abc') + self.assertTypedEqual(object_bytes(WithBytes(b'abc')), b'abc') + self.assertTypedEqual(object_bytes(WithBytes(BytesSubclass(b'abc'))), BytesSubclass(b'abc')) + self.assertTypedEqual(object_bytes(bytearray(b'abc')), b'abc') + self.assertTypedEqual(object_bytes(memoryview(b'abc')), b'abc') + self.assertTypedEqual(object_bytes([97, 98, 99]), b'abc') + self.assertTypedEqual(object_bytes((97, 98, 99)), b'abc') + self.assertTypedEqual(object_bytes(iter([97, 98, 99])), b'abc') + self.assertRaises(TypeError, object_bytes, WithBytes(bytearray(b'abc'))) + self.assertRaises(TypeError, object_bytes, WithBytes([97, 98, 99])) + self.assertRaises(TypeError, object_bytes, 3) + self.assertRaises(TypeError, object_bytes, 'abc') + self.assertRaises(TypeError, object_bytes, object()) + self.assertTypedEqual(object_bytes(NULL), b'') + + def test_object_getattr(self): + xgetattr = _testlimitedcapi.object_getattr + obj = TestObject() + obj.a = 11 + setattr(obj, '\U0001f40d', 22) + self.assertEqual(xgetattr(obj, 'a'), 11) + self.assertRaises(AttributeError, xgetattr, obj, 'b') + self.assertEqual(xgetattr(obj, '\U0001f40d'), 22) + + self.assertRaises(RuntimeError, xgetattr, obj, 'evil') + self.assertRaises(TypeError, xgetattr, obj, 1) + # CRASHES xgetattr(obj, NULL) + # CRASHES xgetattr(NULL, 'a') + + def test_object_getattrstring(self): + getattrstring = _testlimitedcapi.object_getattrstring + obj = TestObject() + obj.a = 11 + setattr(obj, '\U0001f40d', 22) + self.assertEqual(getattrstring(obj, b'a'), 11) + self.assertRaises(AttributeError, getattrstring, obj, b'b') + self.assertEqual(getattrstring(obj, '\U0001f40d'.encode()), 22) + + self.assertRaises(RuntimeError, getattrstring, obj, b'evil') + self.assertRaises(UnicodeDecodeError, getattrstring, obj, b'\xff') + # CRASHES getattrstring(obj, NULL) + # CRASHES getattrstring(NULL, b'a') + + def test_object_getoptionalattr(self): + getoptionalattr = _testcapi.object_getoptionalattr + obj = TestObject() + obj.a = 11 + setattr(obj, '\U0001f40d', 22) + self.assertEqual(getoptionalattr(obj, 'a'), 11) + self.assertIs(getoptionalattr(obj, 'b'), AttributeError) + self.assertEqual(getoptionalattr(obj, '\U0001f40d'), 22) + + self.assertRaises(RuntimeError, getoptionalattr, obj, 'evil') + self.assertRaises(TypeError, getoptionalattr, obj, 1) + # CRASHES getoptionalattr(obj, NULL) + # CRASHES getoptionalattr(NULL, 'a') + + def test_object_getoptionalattrstring(self): + getoptionalattrstring = _testcapi.object_getoptionalattrstring + obj = TestObject() + obj.a = 11 + setattr(obj, '\U0001f40d', 22) + self.assertEqual(getoptionalattrstring(obj, b'a'), 11) + self.assertIs(getoptionalattrstring(obj, b'b'), AttributeError) + self.assertEqual(getoptionalattrstring(obj, '\U0001f40d'.encode()), 22) + + self.assertRaises(RuntimeError, getoptionalattrstring, obj, b'evil') + self.assertRaises(UnicodeDecodeError, getoptionalattrstring, obj, b'\xff') + # CRASHES getoptionalattrstring(obj, NULL) + # CRASHES getoptionalattrstring(NULL, b'a') + + def test_object_hasattr(self): + xhasattr = _testlimitedcapi.object_hasattr + obj = TestObject() + obj.a = 1 + setattr(obj, '\U0001f40d', 2) + self.assertTrue(xhasattr(obj, 'a')) + self.assertFalse(xhasattr(obj, 'b')) + self.assertTrue(xhasattr(obj, '\U0001f40d')) + + with support.catch_unraisable_exception() as cm: + self.assertFalse(xhasattr(obj, 'evil')) + self.assertEqual(cm.unraisable.exc_type, RuntimeError) + self.assertEqual(str(cm.unraisable.exc_value), + 'do not get evil') + + with support.catch_unraisable_exception() as cm: + self.assertFalse(xhasattr(obj, 1)) + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + "attribute name must be string, not 'int'") + + # CRASHES xhasattr(obj, NULL) + # CRASHES xhasattr(NULL, 'a') + + def test_object_hasattrstring(self): + hasattrstring = _testlimitedcapi.object_hasattrstring + obj = TestObject() + obj.a = 1 + setattr(obj, '\U0001f40d', 2) + self.assertTrue(hasattrstring(obj, b'a')) + self.assertFalse(hasattrstring(obj, b'b')) + self.assertTrue(hasattrstring(obj, '\U0001f40d'.encode())) + + with support.catch_unraisable_exception() as cm: + self.assertFalse(hasattrstring(obj, b'evil')) + self.assertEqual(cm.unraisable.exc_type, RuntimeError) + self.assertEqual(str(cm.unraisable.exc_value), + 'do not get evil') + + with support.catch_unraisable_exception() as cm: + self.assertFalse(hasattrstring(obj, b'\xff')) + self.assertEqual(cm.unraisable.exc_type, UnicodeDecodeError) + self.assertRegex(str(cm.unraisable.exc_value), + "'utf-8' codec can't decode") + + # CRASHES hasattrstring(obj, NULL) + # CRASHES hasattrstring(NULL, b'a') + + def test_object_hasattrwitherror(self): + xhasattr = _testcapi.object_hasattrwitherror + obj = TestObject() + obj.a = 1 + setattr(obj, '\U0001f40d', 2) + self.assertTrue(xhasattr(obj, 'a')) + self.assertFalse(xhasattr(obj, 'b')) + self.assertTrue(xhasattr(obj, '\U0001f40d')) + + self.assertRaises(RuntimeError, xhasattr, obj, 'evil') + self.assertRaises(TypeError, xhasattr, obj, 1) + # CRASHES xhasattr(obj, NULL) + # CRASHES xhasattr(NULL, 'a') + + def test_object_hasattrstringwitherror(self): + hasattrstring = _testcapi.object_hasattrstringwitherror + obj = TestObject() + obj.a = 1 + setattr(obj, '\U0001f40d', 2) + self.assertTrue(hasattrstring(obj, b'a')) + self.assertFalse(hasattrstring(obj, b'b')) + self.assertTrue(hasattrstring(obj, '\U0001f40d'.encode())) + + self.assertRaises(RuntimeError, hasattrstring, obj, b'evil') + self.assertRaises(UnicodeDecodeError, hasattrstring, obj, b'\xff') + # CRASHES hasattrstring(obj, NULL) + # CRASHES hasattrstring(NULL, b'a') + + def test_object_setattr(self): + xsetattr = _testlimitedcapi.object_setattr + obj = TestObject() + xsetattr(obj, 'a', 5) + self.assertEqual(obj.a, 5) + xsetattr(obj, '\U0001f40d', 8) + self.assertEqual(getattr(obj, '\U0001f40d'), 8) + + # PyObject_SetAttr(obj, attr_name, NULL) removes the attribute + xsetattr(obj, 'a', NULL) + self.assertNotHasAttr(obj, 'a') + self.assertRaises(AttributeError, xsetattr, obj, 'b', NULL) + self.assertRaises(RuntimeError, xsetattr, obj, 'evil', NULL) + + self.assertRaises(RuntimeError, xsetattr, obj, 'evil', 'good') + self.assertRaises(AttributeError, xsetattr, 42, 'a', 5) + self.assertRaises(TypeError, xsetattr, obj, 1, 5) + # CRASHES xsetattr(obj, NULL, 5) + # CRASHES xsetattr(NULL, 'a', 5) + + def test_object_setattrstring(self): + setattrstring = _testlimitedcapi.object_setattrstring + obj = TestObject() + setattrstring(obj, b'a', 5) + self.assertEqual(obj.a, 5) + setattrstring(obj, '\U0001f40d'.encode(), 8) + self.assertEqual(getattr(obj, '\U0001f40d'), 8) + + # PyObject_SetAttrString(obj, attr_name, NULL) removes the attribute + setattrstring(obj, b'a', NULL) + self.assertNotHasAttr(obj, 'a') + self.assertRaises(AttributeError, setattrstring, obj, b'b', NULL) + self.assertRaises(RuntimeError, setattrstring, obj, b'evil', NULL) + + self.assertRaises(RuntimeError, setattrstring, obj, b'evil', 'good') + self.assertRaises(AttributeError, setattrstring, 42, b'a', 5) + self.assertRaises(TypeError, setattrstring, obj, 1, 5) + self.assertRaises(UnicodeDecodeError, setattrstring, obj, b'\xff', 5) + # CRASHES setattrstring(obj, NULL, 5) + # CRASHES setattrstring(NULL, b'a', 5) + + def test_object_delattr(self): + xdelattr = _testlimitedcapi.object_delattr + obj = TestObject() + obj.a = 1 + setattr(obj, '\U0001f40d', 2) + xdelattr(obj, 'a') + self.assertNotHasAttr(obj, 'a') + self.assertRaises(AttributeError, xdelattr, obj, 'b') + xdelattr(obj, '\U0001f40d') + self.assertNotHasAttr(obj, '\U0001f40d') + + self.assertRaises(AttributeError, xdelattr, 42, 'numerator') + self.assertRaises(RuntimeError, xdelattr, obj, 'evil') + self.assertRaises(TypeError, xdelattr, obj, 1) + # CRASHES xdelattr(obj, NULL) + # CRASHES xdelattr(NULL, 'a') + + def test_object_delattrstring(self): + delattrstring = _testlimitedcapi.object_delattrstring + obj = TestObject() + obj.a = 1 + setattr(obj, '\U0001f40d', 2) + delattrstring(obj, b'a') + self.assertNotHasAttr(obj, 'a') + self.assertRaises(AttributeError, delattrstring, obj, b'b') + delattrstring(obj, '\U0001f40d'.encode()) + self.assertNotHasAttr(obj, '\U0001f40d') + + self.assertRaises(AttributeError, delattrstring, 42, b'numerator') + self.assertRaises(RuntimeError, delattrstring, obj, b'evil') + self.assertRaises(UnicodeDecodeError, delattrstring, obj, b'\xff') + # CRASHES delattrstring(obj, NULL) + # CRASHES delattrstring(NULL, b'a') + + + def test_mapping_check(self): + check = _testlimitedcapi.mapping_check + self.assertTrue(check({1: 2})) + self.assertTrue(check([1, 2])) + self.assertTrue(check((1, 2))) + self.assertTrue(check('abc')) + self.assertTrue(check(b'abc')) + self.assertFalse(check(42)) + self.assertFalse(check(object())) + self.assertFalse(check(NULL)) + + def test_mapping_size(self): + for size in _testlimitedcapi.mapping_size, _testlimitedcapi.mapping_length: + self.assertEqual(size({1: 2}), 1) + self.assertEqual(size([1, 2]), 2) + self.assertEqual(size((1, 2)), 2) + self.assertEqual(size('abc'), 3) + self.assertEqual(size(b'abc'), 3) + + self.assertRaises(TypeError, size, 42) + self.assertRaises(TypeError, size, object()) + self.assertRaises(SystemError, size, NULL) + + def test_object_getitem(self): + getitem = _testlimitedcapi.object_getitem + dct = {'a': 1, '\U0001f40d': 2} + self.assertEqual(getitem(dct, 'a'), 1) + self.assertRaises(KeyError, getitem, dct, 'b') + self.assertEqual(getitem(dct, '\U0001f40d'), 2) + + dct2 = ProxyGetItem(dct) + self.assertEqual(getitem(dct2, 'a'), 1) + self.assertRaises(KeyError, getitem, dct2, 'b') + + self.assertEqual(getitem(['a', 'b', 'c'], 1), 'b') + + self.assertRaises(TypeError, getitem, 42, 'a') + self.assertRaises(TypeError, getitem, {}, []) # unhashable + self.assertRaises(SystemError, getitem, {}, NULL) + self.assertRaises(IndexError, getitem, [], 1) + self.assertRaises(TypeError, getitem, [], 'a') + self.assertRaises(SystemError, getitem, NULL, 'a') + + def test_mapping_getitemstring(self): + getitemstring = _testlimitedcapi.mapping_getitemstring + dct = {'a': 1, '\U0001f40d': 2} + self.assertEqual(getitemstring(dct, b'a'), 1) + self.assertRaises(KeyError, getitemstring, dct, b'b') + self.assertEqual(getitemstring(dct, '\U0001f40d'.encode()), 2) + + dct2 = ProxyGetItem(dct) + self.assertEqual(getitemstring(dct2, b'a'), 1) + self.assertRaises(KeyError, getitemstring, dct2, b'b') + + self.assertRaises(TypeError, getitemstring, 42, b'a') + self.assertRaises(UnicodeDecodeError, getitemstring, {}, b'\xff') + self.assertRaises(SystemError, getitemstring, {}, NULL) + self.assertRaises(TypeError, getitemstring, [], b'a') + self.assertRaises(SystemError, getitemstring, NULL, b'a') + + def test_mapping_getoptionalitem(self): + getitem = _testcapi.mapping_getoptionalitem + dct = {'a': 1, '\U0001f40d': 2} + self.assertEqual(getitem(dct, 'a'), 1) + self.assertEqual(getitem(dct, 'b'), KeyError) + self.assertEqual(getitem(dct, '\U0001f40d'), 2) + + dct2 = ProxyGetItem(dct) + self.assertEqual(getitem(dct2, 'a'), 1) + self.assertEqual(getitem(dct2, 'b'), KeyError) + + frozendct = frozendict(dct) + self.assertEqual(getitem(frozendct, 'a'), 1) + self.assertEqual(getitem(frozendct, 'b'), KeyError) + self.assertEqual(getitem(frozendct, '\U0001f40d'), 2) + + self.assertEqual(getitem(['a', 'b', 'c'], 1), 'b') + + self.assertRaises(TypeError, getitem, 42, 'a') + self.assertRaises(TypeError, getitem, {}, []) # unhashable + self.assertRaises(IndexError, getitem, [], 1) + self.assertRaises(TypeError, getitem, [], 'a') + # CRASHES getitem({}, NULL) + # CRASHES getitem(NULL, 'a') + + def test_mapping_getoptionalitemstring(self): + getitemstring = _testcapi.mapping_getoptionalitemstring + dct = {'a': 1, '\U0001f40d': 2} + self.assertEqual(getitemstring(dct, b'a'), 1) + self.assertEqual(getitemstring(dct, b'b'), KeyError) + self.assertEqual(getitemstring(dct, '\U0001f40d'.encode()), 2) + + dct2 = ProxyGetItem(dct) + self.assertEqual(getitemstring(dct2, b'a'), 1) + self.assertEqual(getitemstring(dct2, b'b'), KeyError) + + frozendct = frozendict(dct) + self.assertEqual(getitemstring(frozendct, 'a'), 1) + self.assertEqual(getitemstring(frozendct, 'b'), KeyError) + self.assertEqual(getitemstring(frozendct, '\U0001f40d'.encode()), 2) + + self.assertRaises(TypeError, getitemstring, 42, b'a') + self.assertRaises(UnicodeDecodeError, getitemstring, {}, b'\xff') + self.assertRaises(SystemError, getitemstring, {}, NULL) + self.assertRaises(TypeError, getitemstring, [], b'a') + # CRASHES getitemstring(NULL, b'a') + + def test_mapping_haskey(self): + haskey = _testlimitedcapi.mapping_haskey + dct = {'a': 1, '\U0001f40d': 2} + self.assertTrue(haskey(dct, 'a')) + self.assertFalse(haskey(dct, 'b')) + self.assertTrue(haskey(dct, '\U0001f40d')) + + dct2 = ProxyGetItem(dct) + self.assertTrue(haskey(dct2, 'a')) + self.assertFalse(haskey(dct2, 'b')) + + self.assertTrue(haskey(['a', 'b', 'c'], 1)) + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskey(42, 'a')) + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + "'int' object is not subscriptable") + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskey({}, [])) + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + "cannot use 'list' as a dict key " + "(unhashable type: 'list')") + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskey([], 1)) + self.assertEqual(cm.unraisable.exc_type, IndexError) + self.assertEqual(str(cm.unraisable.exc_value), + 'list index out of range') + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskey([], 'a')) + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + 'list indices must be integers or slices, not str') + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskey({}, NULL)) + self.assertEqual(cm.unraisable.exc_type, SystemError) + self.assertEqual(str(cm.unraisable.exc_value), + 'null argument to internal routine') + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskey(NULL, 'a')) + self.assertEqual(cm.unraisable.exc_type, SystemError) + self.assertEqual(str(cm.unraisable.exc_value), + 'null argument to internal routine') + + def test_mapping_haskeystring(self): + haskeystring = _testlimitedcapi.mapping_haskeystring + dct = {'a': 1, '\U0001f40d': 2} + self.assertTrue(haskeystring(dct, b'a')) + self.assertFalse(haskeystring(dct, b'b')) + self.assertTrue(haskeystring(dct, '\U0001f40d'.encode())) + + dct2 = ProxyGetItem(dct) + self.assertTrue(haskeystring(dct2, b'a')) + self.assertFalse(haskeystring(dct2, b'b')) + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskeystring(42, b'a')) + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + "'int' object is not subscriptable") + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskeystring({}, b'\xff')) + self.assertEqual(cm.unraisable.exc_type, UnicodeDecodeError) + self.assertRegex(str(cm.unraisable.exc_value), + "'utf-8' codec can't decode") + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskeystring({}, NULL)) + self.assertEqual(cm.unraisable.exc_type, SystemError) + self.assertEqual(str(cm.unraisable.exc_value), + "null argument to internal routine") + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskeystring([], b'a')) + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + 'list indices must be integers or slices, not str') + + with support.catch_unraisable_exception() as cm: + self.assertFalse(haskeystring(NULL, b'a')) + self.assertEqual(cm.unraisable.exc_type, SystemError) + self.assertEqual(str(cm.unraisable.exc_value), + "null argument to internal routine") + + def test_mapping_haskeywitherror(self): + haskey = _testlimitedcapi.mapping_haskeywitherror + dct = {'a': 1, '\U0001f40d': 2} + self.assertTrue(haskey(dct, 'a')) + self.assertFalse(haskey(dct, 'b')) + self.assertTrue(haskey(dct, '\U0001f40d')) + + dct2 = ProxyGetItem(dct) + self.assertTrue(haskey(dct2, 'a')) + self.assertFalse(haskey(dct2, 'b')) + + self.assertTrue(haskey(['a', 'b', 'c'], 1)) + + self.assertRaises(TypeError, haskey, 42, 'a') + self.assertRaises(TypeError, haskey, {}, []) # unhashable + self.assertRaises(IndexError, haskey, [], 1) + self.assertRaises(TypeError, haskey, [], 'a') + + # CRASHES haskey({}, NULL)) + # CRASHES haskey(NULL, 'a')) + + def test_mapping_haskeystringwitherror(self): + haskeystring = _testlimitedcapi.mapping_haskeystringwitherror + dct = {'a': 1, '\U0001f40d': 2} + self.assertTrue(haskeystring(dct, b'a')) + self.assertFalse(haskeystring(dct, b'b')) + self.assertTrue(haskeystring(dct, '\U0001f40d'.encode())) + + dct2 = ProxyGetItem(dct) + self.assertTrue(haskeystring(dct2, b'a')) + self.assertFalse(haskeystring(dct2, b'b')) + + self.assertRaises(TypeError, haskeystring, 42, b'a') + self.assertRaises(UnicodeDecodeError, haskeystring, {}, b'\xff') + self.assertRaises(SystemError, haskeystring, {}, NULL) + self.assertRaises(TypeError, haskeystring, [], b'a') + # CRASHES haskeystring(NULL, b'a') + + def test_object_setitem(self): + setitem = _testlimitedcapi.object_setitem + dct = {} + setitem(dct, 'a', 5) + self.assertEqual(dct, {'a': 5}) + setitem(dct, '\U0001f40d', 8) + self.assertEqual(dct, {'a': 5, '\U0001f40d': 8}) + + dct = {} + dct2 = ProxySetItem(dct) + setitem(dct2, 'a', 5) + self.assertEqual(dct, {'a': 5}) + + lst = ['a', 'b', 'c'] + setitem(lst, 1, 'x') + self.assertEqual(lst, ['a', 'x', 'c']) + + self.assertRaises(TypeError, setitem, 42, 'a', 5) + self.assertRaises(TypeError, setitem, {}, [], 5) # unhashable + self.assertRaises(SystemError, setitem, {}, NULL, 5) + self.assertRaises(SystemError, setitem, {}, 'a', NULL) + self.assertRaises(IndexError, setitem, [], 1, 5) + self.assertRaises(TypeError, setitem, [], 'a', 5) + self.assertRaises(TypeError, setitem, (), 1, 5) + self.assertRaises(SystemError, setitem, NULL, 'a', 5) + + def test_mapping_setitemstring(self): + setitemstring = _testlimitedcapi.mapping_setitemstring + dct = {} + setitemstring(dct, b'a', 5) + self.assertEqual(dct, {'a': 5}) + setitemstring(dct, '\U0001f40d'.encode(), 8) + self.assertEqual(dct, {'a': 5, '\U0001f40d': 8}) + + dct = {} + dct2 = ProxySetItem(dct) + setitemstring(dct2, b'a', 5) + self.assertEqual(dct, {'a': 5}) + + self.assertRaises(TypeError, setitemstring, 42, b'a', 5) + self.assertRaises(UnicodeDecodeError, setitemstring, {}, b'\xff', 5) + self.assertRaises(SystemError, setitemstring, {}, NULL, 5) + self.assertRaises(SystemError, setitemstring, {}, b'a', NULL) + self.assertRaises(TypeError, setitemstring, [], b'a', 5) + self.assertRaises(SystemError, setitemstring, NULL, b'a', 5) + + def test_object_delitem(self): + for delitem in _testlimitedcapi.object_delitem, _testlimitedcapi.mapping_delitem: + dct = {'a': 1, 'c': 2, '\U0001f40d': 3} + delitem(dct, 'a') + self.assertEqual(dct, {'c': 2, '\U0001f40d': 3}) + self.assertRaises(KeyError, delitem, dct, 'b') + delitem(dct, '\U0001f40d') + self.assertEqual(dct, {'c': 2}) + + dct = {'a': 1, 'c': 2} + dct2 = ProxyDelItem(dct) + delitem(dct2, 'a') + self.assertEqual(dct, {'c': 2}) + self.assertRaises(KeyError, delitem, dct2, 'b') + + lst = ['a', 'b', 'c'] + delitem(lst, 1) + self.assertEqual(lst, ['a', 'c']) + + self.assertRaises(TypeError, delitem, 42, 'a') + self.assertRaises(TypeError, delitem, {}, []) # unhashable + self.assertRaises(SystemError, delitem, {}, NULL) + self.assertRaises(IndexError, delitem, [], 1) + self.assertRaises(TypeError, delitem, [], 'a') + self.assertRaises(SystemError, delitem, NULL, 'a') + + def test_mapping_delitemstring(self): + delitemstring = _testlimitedcapi.mapping_delitemstring + dct = {'a': 1, 'c': 2, '\U0001f40d': 3} + delitemstring(dct, b'a') + self.assertEqual(dct, {'c': 2, '\U0001f40d': 3}) + self.assertRaises(KeyError, delitemstring, dct, b'b') + delitemstring(dct, '\U0001f40d'.encode()) + self.assertEqual(dct, {'c': 2}) + + dct = {'a': 1, 'c': 2} + dct2 = ProxyDelItem(dct) + delitemstring(dct2, b'a') + self.assertEqual(dct, {'c': 2}) + self.assertRaises(KeyError, delitemstring, dct2, b'b') + + self.assertRaises(TypeError, delitemstring, 42, b'a') + self.assertRaises(UnicodeDecodeError, delitemstring, {}, b'\xff') + self.assertRaises(SystemError, delitemstring, {}, NULL) + self.assertRaises(TypeError, delitemstring, [], b'a') + self.assertRaises(SystemError, delitemstring, NULL, b'a') + + def test_mapping_keys_valuesitems(self): + class Mapping1(dict): + def keys(self): + return list(super().keys()) + def values(self): + return list(super().values()) + def items(self): + return list(super().items()) + class Mapping2(dict): + def keys(self): + return tuple(super().keys()) + def values(self): + return tuple(super().values()) + def items(self): + return tuple(super().items()) + dict_obj = {'foo': 1, 'bar': 2, 'spam': 3} + + for mapping in [{}, OrderedDict(), Mapping1(), Mapping2(), + frozendict(), + dict_obj, OrderedDict(dict_obj), + Mapping1(dict_obj), Mapping2(dict_obj), + frozendict(dict_obj)]: + self.assertListEqual(_testlimitedcapi.mapping_keys(mapping), + list(mapping.keys())) + self.assertListEqual(_testlimitedcapi.mapping_values(mapping), + list(mapping.values())) + self.assertListEqual(_testlimitedcapi.mapping_items(mapping), + list(mapping.items())) + + def test_mapping_keys_valuesitems_bad_arg(self): + self.assertRaises(AttributeError, _testlimitedcapi.mapping_keys, object()) + self.assertRaises(AttributeError, _testlimitedcapi.mapping_values, object()) + self.assertRaises(AttributeError, _testlimitedcapi.mapping_items, object()) + self.assertRaises(AttributeError, _testlimitedcapi.mapping_keys, []) + self.assertRaises(AttributeError, _testlimitedcapi.mapping_values, []) + self.assertRaises(AttributeError, _testlimitedcapi.mapping_items, []) + self.assertRaises(SystemError, _testlimitedcapi.mapping_keys, NULL) + self.assertRaises(SystemError, _testlimitedcapi.mapping_values, NULL) + self.assertRaises(SystemError, _testlimitedcapi.mapping_items, NULL) + + class BadMapping: + def keys(self): + return None + def values(self): + return None + def items(self): + return None + bad_mapping = BadMapping() + self.assertRaises(TypeError, _testlimitedcapi.mapping_keys, bad_mapping) + self.assertRaises(TypeError, _testlimitedcapi.mapping_values, bad_mapping) + self.assertRaises(TypeError, _testlimitedcapi.mapping_items, bad_mapping) + + def test_sequence_check(self): + check = _testlimitedcapi.sequence_check + self.assertFalse(check({1: 2})) + self.assertTrue(check([1, 2])) + self.assertTrue(check((1, 2))) + self.assertTrue(check('abc')) + self.assertTrue(check(b'abc')) + self.assertFalse(check(42)) + self.assertFalse(check(object())) + # CRASHES check(NULL) + + def test_sequence_size(self): + for size in _testlimitedcapi.sequence_size, _testlimitedcapi.sequence_length: + self.assertEqual(size([1, 2]), 2) + self.assertEqual(size((1, 2)), 2) + self.assertEqual(size('abc'), 3) + self.assertEqual(size(b'abc'), 3) + + self.assertRaises(TypeError, size, {}) + self.assertRaises(TypeError, size, 42) + self.assertRaises(TypeError, size, object()) + self.assertRaises(SystemError, size, NULL) + + def test_sequence_getitem(self): + getitem = _testlimitedcapi.sequence_getitem + lst = ['a', 'b', 'c'] + self.assertEqual(getitem(lst, 1), 'b') + self.assertEqual(getitem(lst, -1), 'c') + self.assertRaises(IndexError, getitem, lst, 3) + self.assertRaises(IndexError, getitem, lst, PY_SSIZE_T_MAX) + self.assertRaises(IndexError, getitem, lst, PY_SSIZE_T_MIN) + + self.assertRaises(TypeError, getitem, 42, 1) + self.assertRaises(TypeError, getitem, {}, 1) + self.assertRaises(SystemError, getitem, NULL, 1) + + def test_sequence_concat(self): + concat = _testlimitedcapi.sequence_concat + self.assertEqual(concat(['a', 'b'], [1, 2]), ['a', 'b', 1, 2]) + self.assertEqual(concat(('a', 'b'), (1, 2)), ('a', 'b', 1, 2)) + + self.assertRaises(TypeError, concat, [], ()) + self.assertRaises(TypeError, concat, (), []) + self.assertRaises(TypeError, concat, [], 42) + self.assertRaises(TypeError, concat, 42, []) + self.assertRaises(TypeError, concat, 42, 43) + self.assertRaises(SystemError, concat, [], NULL) + self.assertRaises(SystemError, concat, NULL, []) + + def test_sequence_repeat(self): + repeat = _testlimitedcapi.sequence_repeat + self.assertEqual(repeat(['a', 'b'], 2), ['a', 'b', 'a', 'b']) + self.assertEqual(repeat(('a', 'b'), 2), ('a', 'b', 'a', 'b')) + self.assertEqual(repeat(['a', 'b'], 0), []) + self.assertEqual(repeat(['a', 'b'], -1), []) + self.assertEqual(repeat(['a', 'b'], PY_SSIZE_T_MIN), []) + self.assertEqual(repeat([], PY_SSIZE_T_MAX), []) + self.assertRaises(MemoryError, repeat, ['a', 'b'], PY_SSIZE_T_MAX) + + self.assertRaises(TypeError, repeat, set(), 2) + self.assertRaises(TypeError, repeat, 42, 2) + self.assertRaises(SystemError, repeat, NULL, 2) + + def test_sequence_inplaceconcat(self): + inplaceconcat = _testlimitedcapi.sequence_inplaceconcat + lst = ['a', 'b'] + res = inplaceconcat(lst, [1, 2]) + self.assertEqual(res, ['a', 'b', 1, 2]) + self.assertIs(res, lst) + lst = ['a', 'b'] + res = inplaceconcat(lst, (1, 2)) + self.assertEqual(res, ['a', 'b', 1, 2]) + self.assertIs(res, lst) + self.assertEqual(inplaceconcat(('a', 'b'), (1, 2)), ('a', 'b', 1, 2)) + + self.assertRaises(TypeError, inplaceconcat, (), []) + self.assertRaises(TypeError, inplaceconcat, [], 42) + self.assertRaises(TypeError, inplaceconcat, 42, []) + self.assertRaises(TypeError, inplaceconcat, 42, 43) + self.assertRaises(SystemError, inplaceconcat, [], NULL) + self.assertRaises(SystemError, inplaceconcat, NULL, []) + + def test_sequence_inplacerepeat(self): + inplacerepeat = _testlimitedcapi.sequence_inplacerepeat + lst = ['a', 'b'] + res = inplacerepeat(lst, 2) + self.assertEqual(res, ['a', 'b', 'a', 'b']) + self.assertIs(res, lst) + self.assertEqual(inplacerepeat(('a', 'b'), 2), ('a', 'b', 'a', 'b')) + self.assertEqual(inplacerepeat(['a', 'b'], 0), []) + self.assertEqual(inplacerepeat(['a', 'b'], -1), []) + self.assertEqual(inplacerepeat(['a', 'b'], PY_SSIZE_T_MIN), []) + self.assertEqual(inplacerepeat([], PY_SSIZE_T_MAX), []) + self.assertRaises(MemoryError, inplacerepeat, ['a', 'b'], PY_SSIZE_T_MAX) + + self.assertRaises(TypeError, inplacerepeat, set(), 2) + self.assertRaises(TypeError, inplacerepeat, 42, 2) + self.assertRaises(SystemError, inplacerepeat, NULL, 2) + + def test_sequence_setitem(self): + setitem = _testlimitedcapi.sequence_setitem + lst = ['a', 'b', 'c'] + setitem(lst, 1, 'x') + self.assertEqual(lst, ['a', 'x', 'c']) + setitem(lst, -1, 'y') + self.assertEqual(lst, ['a', 'x', 'y']) + + setitem(lst, 0, NULL) + self.assertEqual(lst, ['x', 'y']) + self.assertRaises(IndexError, setitem, lst, 3, 'x') + self.assertRaises(IndexError, setitem, lst, PY_SSIZE_T_MAX, 'x') + self.assertRaises(IndexError, setitem, lst, PY_SSIZE_T_MIN, 'x') + + self.assertRaises(TypeError, setitem, 42, 1, 'x') + self.assertRaises(TypeError, setitem, {}, 1, 'x') + self.assertRaises(SystemError, setitem, NULL, 1, 'x') + + def test_sequence_delitem(self): + delitem = _testlimitedcapi.sequence_delitem + lst = ['a', 'b', 'c'] + delitem(lst, 1) + self.assertEqual(lst, ['a', 'c']) + delitem(lst, -1) + self.assertEqual(lst, ['a']) + self.assertRaises(IndexError, delitem, lst, 3) + self.assertRaises(IndexError, delitem, lst, PY_SSIZE_T_MAX) + self.assertRaises(IndexError, delitem, lst, PY_SSIZE_T_MIN) + + self.assertRaises(TypeError, delitem, 42, 1) + self.assertRaises(TypeError, delitem, {}, 1) + self.assertRaises(SystemError, delitem, NULL, 1) + + def test_sequence_setslice(self): + setslice = _testlimitedcapi.sequence_setslice + + # Correct case: + for start in [*range(-6, 7), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX]: + for stop in [*range(-6, 7), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX]: + data = [1, 2, 3, 4, 5] + data_copy = [1, 2, 3, 4, 5] + setslice(data, start, stop, [8, 9]) + data_copy[start:stop] = [8, 9] + self.assertEqual(data, data_copy) + + data = [1, 2, 3, 4, 5] + data_copy = [1, 2, 3, 4, 5] + setslice(data, start, stop, NULL) + del data_copy[start:stop] + self.assertEqual(data, data_copy) + + # Custom class: + class Custom: + def __setitem__(self, index, value): + self.index = index + self.value = value + + c = Custom() + setslice(c, 0, 5, 'abc') + self.assertEqual(c.index, slice(0, 5)) + self.assertEqual(c.value, 'abc') + + # Immutable sequences must raise: + bad_seq1 = (1, 2, 3, 4) + self.assertRaises(TypeError, setslice, bad_seq1, 1, 3, (8, 9)) + self.assertEqual(bad_seq1, (1, 2, 3, 4)) + + bad_seq2 = 'abcd' + self.assertRaises(TypeError, setslice, bad_seq2, 1, 3, 'xy') + self.assertEqual(bad_seq2, 'abcd') + + # Not a sequence: + self.assertRaises(TypeError, setslice, object(), 1, 3, 'xy') + self.assertRaises(SystemError, setslice, NULL, 1, 3, 'xy') + + def test_sequence_delslice(self): + delslice = _testlimitedcapi.sequence_delslice + + # Correct case: + for start in [*range(-6, 7), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX]: + for stop in [*range(-6, 7), PY_SSIZE_T_MIN, PY_SSIZE_T_MAX]: + data = [1, 2, 3, 4, 5] + data_copy = [1, 2, 3, 4, 5] + delslice(data, start, stop) + del data_copy[start:stop] + self.assertEqual(data, data_copy) + + # Custom class: + class Custom: + def __delitem__(self, index): + self.index = index + + c = Custom() + delslice(c, 0, 5) + self.assertEqual(c.index, slice(0, 5)) + + # Immutable sequences must raise: + bad_seq1 = (1, 2, 3, 4) + self.assertRaises(TypeError, delslice, bad_seq1, 1, 3) + self.assertEqual(bad_seq1, (1, 2, 3, 4)) + + bad_seq2 = 'abcd' + self.assertRaises(TypeError, delslice, bad_seq2, 1, 3) + self.assertEqual(bad_seq2, 'abcd') + + # Not a sequence: + self.assertRaises(TypeError, delslice, object(), 1, 3) + self.assertRaises(SystemError, delslice, NULL, 1, 3) + + mapping = {1: 'a', 2: 'b', 3: 'c'} + self.assertRaises(KeyError, delslice, mapping, 1, 3) + self.assertEqual(mapping, {1: 'a', 2: 'b', 3: 'c'}) + + def test_sequence_count(self): + count = _testlimitedcapi.sequence_count + + lst = ['a', 'b', 'a'] + self.assertEqual(count(lst, 'a'), 2) + self.assertEqual(count(lst, 'c'), 0) + self.assertEqual(count(iter(lst), 'a'), 2) + self.assertEqual(count(iter(lst), 'c'), 0) + self.assertEqual(count({'a': 2}, 'a'), 1) + + self.assertRaises(TypeError, count, 42, 'a') + self.assertRaises(SystemError, count, [], NULL) + self.assertRaises(SystemError, count, [1], NULL) + self.assertRaises(SystemError, count, NULL, 'a') + + def test_sequence_contains(self): + contains = _testlimitedcapi.sequence_contains + + lst = ['a', 'b', 'a'] + self.assertEqual(contains(lst, 'a'), 1) + self.assertEqual(contains(lst, 'c'), 0) + self.assertEqual(contains(iter(lst), 'a'), 1) + self.assertEqual(contains(iter(lst), 'c'), 0) + self.assertEqual(contains({'a': 2}, 'a'), 1) + + # XXX Only for empty sequences. Should be SystemError? + self.assertEqual(contains([], NULL), 0) + + self.assertRaises(TypeError, contains, 42, 'a') + self.assertRaises(SystemError, contains, [1], NULL) + # CRASHES contains({}, NULL) + # CRASHES contains(set(), NULL) + # CRASHES contains(NULL, 'a') + + def test_sequence_index(self): + index = _testlimitedcapi.sequence_index + + lst = ['a', 'b', 'a'] + self.assertEqual(index(lst, 'a'), 0) + self.assertEqual(index(lst, 'b'), 1) + self.assertRaises(ValueError, index, lst, 'c') + self.assertEqual(index(iter(lst), 'a'), 0) + self.assertEqual(index(iter(lst), 'b'), 1) + self.assertRaises(ValueError, index, iter(lst), 'c') + dct = {'a': 2, 'b': 3} + self.assertEqual(index(dct, 'a'), 0) + self.assertEqual(index(dct, 'b'), 1) + self.assertRaises(ValueError, index, dct, 'c') + + self.assertRaises(TypeError, index, 42, 'a') + self.assertRaises(SystemError, index, [], NULL) + self.assertRaises(SystemError, index, [1], NULL) + self.assertRaises(SystemError, index, NULL, 'a') + + def test_sequence_list(self): + xlist = _testlimitedcapi.sequence_list + self.assertEqual(xlist(['a', 'b', 'c']), ['a', 'b', 'c']) + self.assertEqual(xlist(('a', 'b', 'c')), ['a', 'b', 'c']) + self.assertEqual(xlist(iter(['a', 'b', 'c'])), ['a', 'b', 'c']) + self.assertEqual(xlist(gen()), ['a', 'b', 'c']) + + self.assertRaises(TypeError, xlist, 42) + self.assertRaises(SystemError, xlist, NULL) + + def test_sequence_tuple(self): + xtuple = _testlimitedcapi.sequence_tuple + self.assertEqual(xtuple(['a', 'b', 'c']), ('a', 'b', 'c')) + self.assertEqual(xtuple(('a', 'b', 'c')), ('a', 'b', 'c')) + self.assertEqual(xtuple(iter(['a', 'b', 'c'])), ('a', 'b', 'c')) + self.assertEqual(xtuple(gen()), ('a', 'b', 'c')) + + self.assertRaises(TypeError, xtuple, 42) + self.assertRaises(SystemError, xtuple, NULL) + + def test_sequence_fast(self): + # Test PySequence_Fast() + sequence_fast = _testlimitedcapi.sequence_fast + sequence_fast_get_size = _testcapi.sequence_fast_get_size + sequence_fast_get_item = _testcapi.sequence_fast_get_item + + tpl = ('a', 'b', 'c') + fast = sequence_fast(tpl, "err_msg") + self.assertIs(fast, tpl) + self.assertEqual(sequence_fast_get_size(fast), 3) + self.assertEqual(sequence_fast_get_item(fast, 2), 'c') + + lst = ['a', 'b', 'c'] + fast = sequence_fast(lst, "err_msg") + self.assertIs(fast, lst) + self.assertEqual(sequence_fast_get_size(fast), 3) + self.assertEqual(sequence_fast_get_item(fast, 2), 'c') + + it = iter(['A', 'B']) + fast = sequence_fast(it, "err_msg") + self.assertEqual(fast, ['A', 'B']) + self.assertEqual(sequence_fast_get_size(fast), 2) + self.assertEqual(sequence_fast_get_item(fast, 1), 'B') + + text = 'fast' + fast = sequence_fast(text, "err_msg") + self.assertEqual(fast, ['f', 'a', 's', 't']) + self.assertEqual(sequence_fast_get_size(fast), 4) + self.assertEqual(sequence_fast_get_item(fast, 0), 'f') + + self.assertRaises(TypeError, sequence_fast, 42, "err_msg") + self.assertRaises(SystemError, sequence_fast, NULL, "err_msg") + + # CRASHES sequence_fast_get_size(NULL) + # CRASHES sequence_fast_get_item(NULL, 0) + + def test_object_generichash(self): + # Test PyObject_GenericHash() + generichash = _testcapi.object_generichash + for obj in object(), 1, 'string', []: + self.assertEqual(generichash(obj), object.__hash__(obj)) + + def run_iter_api_test(self, next_func): + for data in (), [], (1, 2, 3), [1 , 2, 3], "123": + with self.subTest(data=data): + items = [] + it = iter(data) + while (item := next_func(it)) is not None: + items.append(item) + self.assertEqual(items, list(data)) + + class Broken: + def __init__(self): + self.count = 0 + + def __next__(self): + if self.count < 3: + self.count += 1 + return self.count + else: + raise TypeError('bad type') + + it = Broken() + self.assertEqual(next_func(it), 1) + self.assertEqual(next_func(it), 2) + self.assertEqual(next_func(it), 3) + with self.assertRaisesRegex(TypeError, 'bad type'): + next_func(it) + + def test_iter_next(self): + from _testcapi import PyIter_Next + self.run_iter_api_test(PyIter_Next) + # CRASHES PyIter_Next(10) + + def test_iter_nextitem(self): + from _testcapi import PyIter_NextItem + self.run_iter_api_test(PyIter_NextItem) + + regex = "expected.*iterator.*got.*'int'" + with self.assertRaisesRegex(TypeError, regex): + PyIter_NextItem(10) + + def test_object_setattr_null_exc(self): + class Obj: + pass + obj = Obj() + obj.attr = 123 + + exc = ValueError("error") + with self.assertRaises(SystemError) as cm: + _testcapi.object_setattr_null_exc(obj, 'attr', exc) + self.assertIs(cm.exception.__context__, exc) + self.assertIsNone(cm.exception.__cause__) + self.assertHasAttr(obj, 'attr') + + with self.assertRaises(SystemError) as cm: + _testcapi.object_setattrstring_null_exc(obj, 'attr', exc) + self.assertIs(cm.exception.__context__, exc) + self.assertIsNone(cm.exception.__cause__) + self.assertHasAttr(obj, 'attr') + + with self.assertRaises(SystemError) as cm: + # undecodable name + _testcapi.object_setattrstring_null_exc(obj, b'\xff', exc) + self.assertIs(cm.exception.__context__, exc) + self.assertIsNone(cm.exception.__cause__) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_bytearray.py b/Lib/test/test_capi/test_bytearray.py new file mode 100644 index 00000000000..cb7ad8b2225 --- /dev/null +++ b/Lib/test/test_capi/test_bytearray.py @@ -0,0 +1,177 @@ +import sys +import unittest +from test.support import import_helper + +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') +from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX + +NULL = None + +class ByteArraySubclass(bytearray): + pass + +class BytesLike: + def __init__(self, value): + self.value = value + def __bytes__(self): + return self.value + + +class CAPITest(unittest.TestCase): + def test_check(self): + # Test PyByteArray_Check() + check = _testlimitedcapi.bytearray_check + self.assertTrue(check(bytearray(b''))) + self.assertTrue(check(bytearray(b'abc'))) + self.assertFalse(check(b'abc')) + self.assertTrue(check(ByteArraySubclass(b'abc'))) + self.assertFalse(check(BytesLike(b'abc'))) + self.assertFalse(check(3)) + self.assertFalse(check([])) + self.assertFalse(check(object())) + + # CRASHES check(NULL) + + def test_checkexact(self): + # Test PyByteArray_CheckExact() + check = _testlimitedcapi.bytearray_checkexact + self.assertTrue(check(bytearray(b''))) + self.assertTrue(check(bytearray(b'abc'))) + self.assertFalse(check(b'abc')) + self.assertFalse(check(ByteArraySubclass(b'abc'))) + self.assertFalse(check(BytesLike(b'abc'))) + self.assertFalse(check(3)) + self.assertFalse(check([])) + self.assertFalse(check(object())) + + # CRASHES check(NULL) + + def test_fromstringandsize(self): + # Test PyByteArray_FromStringAndSize() + fromstringandsize = _testlimitedcapi.bytearray_fromstringandsize + + self.assertEqual(fromstringandsize(b'abc'), bytearray(b'abc')) + self.assertEqual(fromstringandsize(b'abc', 2), bytearray(b'ab')) + self.assertEqual(fromstringandsize(b'abc\0def'), bytearray(b'abc\0def')) + self.assertEqual(fromstringandsize(b'', 0), bytearray()) + self.assertEqual(fromstringandsize(NULL, 0), bytearray()) + self.assertEqual(len(fromstringandsize(NULL, 3)), 3) + self.assertRaises(OverflowError, fromstringandsize, NULL, PY_SSIZE_T_MAX) + self.assertRaises(OverflowError, fromstringandsize, NULL, + PY_SSIZE_T_MAX-sys.getsizeof(b'') + 1) + + self.assertRaises(SystemError, fromstringandsize, b'abc', -1) + self.assertRaises(SystemError, fromstringandsize, b'abc', PY_SSIZE_T_MIN) + self.assertRaises(SystemError, fromstringandsize, NULL, -1) + self.assertRaises(SystemError, fromstringandsize, NULL, PY_SSIZE_T_MIN) + + def test_fromobject(self): + # Test PyByteArray_FromObject() + fromobject = _testlimitedcapi.bytearray_fromobject + + self.assertEqual(fromobject(b''), bytearray(b'')) + self.assertEqual(fromobject(b'abc'), bytearray(b'abc')) + self.assertEqual(fromobject(bytearray(b'abc')), bytearray(b'abc')) + self.assertEqual(fromobject(ByteArraySubclass(b'abc')), bytearray(b'abc')) + self.assertEqual(fromobject([97, 98, 99]), bytearray(b'abc')) + self.assertEqual(fromobject(3), bytearray(b'\0\0\0')) + self.assertRaises(TypeError, fromobject, BytesLike(b'abc')) + self.assertRaises(TypeError, fromobject, 'abc') + self.assertRaises(TypeError, fromobject, object()) + + # CRASHES fromobject(NULL) + + def test_size(self): + # Test PyByteArray_Size() + size = _testlimitedcapi.bytearray_size + self.assertEqual(size(bytearray(b'')), 0) + self.assertEqual(size(bytearray(b'abc')), 3) + self.assertEqual(size(ByteArraySubclass(b'abc')), 3) + + # CRASHES size(b'abc') + # CRASHES size(object()) + # CRASHES size(NULL) + + def test_asstring(self): + """Test PyByteArray_AsString()""" + asstring = _testlimitedcapi.bytearray_asstring + self.assertEqual(asstring(bytearray(b''), 1), b'\0') + self.assertEqual(asstring(bytearray(b'abc'), 4), b'abc\0') + self.assertEqual(asstring(ByteArraySubclass(b'abc'), 4), b'abc\0') + self.assertEqual(asstring(bytearray(b'abc\0def'), 8), b'abc\0def\0') + + # CRASHES asstring(b'abc', 0) + # CRASHES asstring(object()', 0) + # CRASHES asstring(NULL, 0) + + def test_concat(self): + """Test PyByteArray_Concat()""" + concat = _testlimitedcapi.bytearray_concat + + ba = bytearray(b'abc') + self.assertEqual(concat(ba, b'def'), bytearray(b'abcdef')) + self.assertEqual(ba, b'abc') + self.assertEqual(concat(ba, ba), bytearray(b'abcabc')) + + self.assertEqual(concat(b'abc', b'def'), bytearray(b'abcdef')) + self.assertEqual(concat(b'a\0b', b'c\0d'), bytearray(b'a\0bc\0d')) + self.assertEqual(concat(bytearray(b'abc'), b'def'), bytearray(b'abcdef')) + self.assertEqual(concat(b'abc', bytearray(b'def')), bytearray(b'abcdef')) + self.assertEqual(concat(bytearray(b'abc'), b''), bytearray(b'abc')) + self.assertEqual(concat(b'', bytearray(b'def')), bytearray(b'def')) + self.assertEqual(concat(bytearray(b''), bytearray(b'')), bytearray(b'')) + self.assertEqual(concat(memoryview(b'xabcy')[1:4], b'def'), + bytearray(b'abcdef')) + self.assertEqual(concat(b'abc', memoryview(b'xdefy')[1:4]), + bytearray(b'abcdef')) + + self.assertRaises(TypeError, concat, memoryview(b'axbycz')[::2], b'def') + self.assertRaises(TypeError, concat, b'abc', memoryview(b'dxeyfz')[::2]) + self.assertRaises(TypeError, concat, b'abc', 'def') + self.assertRaises(TypeError, concat, 'abc', b'def') + self.assertRaises(TypeError, concat, 'abc', 'def') + self.assertRaises(TypeError, concat, [], b'def') + self.assertRaises(TypeError, concat, b'abc', []) + self.assertRaises(TypeError, concat, [], []) + + # CRASHES concat(NULL, bytearray(b'def')) + # CRASHES concat(bytearray(b'abc'), NULL) + # CRASHES concat(NULL, object()) + # CRASHES concat(object(), NULL) + + def test_resize(self): + """Test PyByteArray_Resize()""" + resize = _testlimitedcapi.bytearray_resize + + ba = bytearray(b'abcdef') + self.assertEqual(resize(ba, 3), 0) + self.assertEqual(ba, bytearray(b'abc')) + self.assertEqual(resize(ba, 10), 0) + self.assertEqual(len(ba), 10) + self.assertEqual(ba[:3], bytearray(b'abc')) + self.assertEqual(resize(ba, 2**20), 0) + self.assertEqual(len(ba), 2**20) + self.assertEqual(ba[:3], bytearray(b'abc')) + self.assertEqual(resize(ba, 0), 0) + self.assertEqual(ba, bytearray()) + + ba = bytearray(b'') + self.assertEqual(resize(ba, 0), 0) + self.assertEqual(ba, bytearray()) + + ba = ByteArraySubclass(b'abcdef') + self.assertEqual(resize(ba, 3), 0) + self.assertEqual(ba, bytearray(b'abc')) + + self.assertRaises(ValueError, resize, bytearray(), -1) + self.assertRaises(ValueError, resize, bytearray(), -200) + self.assertRaises(MemoryError, resize, bytearray(), PY_SSIZE_T_MAX) + self.assertRaises(MemoryError, resize, bytearray(1000), PY_SSIZE_T_MAX) + + # CRASHES resize(b'abc', 0) + # CRASHES resize(object(), 0) + # CRASHES resize(NULL, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_bytes.py b/Lib/test/test_capi/test_bytes.py new file mode 100644 index 00000000000..eee201b3a75 --- /dev/null +++ b/Lib/test/test_capi/test_bytes.py @@ -0,0 +1,441 @@ +import sys +import unittest +from test.support import import_helper +from test import support + +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') +_testcapi = import_helper.import_module('_testcapi') +from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX + +NULL = None + +class BytesSubclass(bytes): + pass + +class BytesLike: + def __init__(self, value): + self.value = value + def __bytes__(self): + return self.value + + +class CAPITest(unittest.TestCase): + def test_check(self): + # Test PyBytes_Check() + check = _testlimitedcapi.bytes_check + self.assertTrue(check(b'abc')) + self.assertTrue(check(b'')) + self.assertFalse(check('abc')) + self.assertFalse(check(bytearray(b'abc'))) + self.assertTrue(check(BytesSubclass(b'abc'))) + self.assertFalse(check(BytesLike(b'abc'))) + self.assertFalse(check(3)) + self.assertFalse(check([])) + self.assertFalse(check(object())) + + # CRASHES check(NULL) + + def test_checkexact(self): + # Test PyBytes_CheckExact() + check = _testlimitedcapi.bytes_checkexact + self.assertTrue(check(b'abc')) + self.assertTrue(check(b'')) + self.assertFalse(check('abc')) + self.assertFalse(check(bytearray(b'abc'))) + self.assertFalse(check(BytesSubclass(b'abc'))) + self.assertFalse(check(BytesLike(b'abc'))) + self.assertFalse(check(3)) + self.assertFalse(check([])) + self.assertFalse(check(object())) + + # CRASHES check(NULL) + + def test_fromstringandsize(self): + # Test PyBytes_FromStringAndSize() + fromstringandsize = _testlimitedcapi.bytes_fromstringandsize + + self.assertEqual(fromstringandsize(b'abc'), b'abc') + self.assertEqual(fromstringandsize(b'abc', 2), b'ab') + self.assertEqual(fromstringandsize(b'abc\0def'), b'abc\0def') + self.assertEqual(fromstringandsize(b'a'), b'a') + self.assertEqual(fromstringandsize(b'a', 1), b'a') + self.assertEqual(fromstringandsize(b'', 0), b'') + self.assertEqual(fromstringandsize(NULL, 0), b'') + self.assertEqual(len(fromstringandsize(NULL, 3)), 3) + self.assertRaises((MemoryError, OverflowError), + fromstringandsize, NULL, PY_SSIZE_T_MAX) + + self.assertRaises(SystemError, fromstringandsize, b'abc', -1) + self.assertRaises(SystemError, fromstringandsize, b'abc', PY_SSIZE_T_MIN) + self.assertRaises(SystemError, fromstringandsize, NULL, -1) + self.assertRaises(SystemError, fromstringandsize, NULL, PY_SSIZE_T_MIN) + + def test_fromstring(self): + # Test PyBytes_FromString() + fromstring = _testlimitedcapi.bytes_fromstring + + self.assertEqual(fromstring(b'abc\0def'), b'abc') + self.assertEqual(fromstring(b''), b'') + + # CRASHES fromstring(NULL) + + def test_fromobject(self): + # Test PyBytes_FromObject() + fromobject = _testlimitedcapi.bytes_fromobject + + self.assertEqual(fromobject(b''), b'') + self.assertEqual(fromobject(b'abc'), b'abc') + self.assertEqual(fromobject(bytearray(b'abc')), b'abc') + self.assertEqual(fromobject(BytesSubclass(b'abc')), b'abc') + self.assertEqual(fromobject([97, 98, 99]), b'abc') + self.assertRaises(TypeError, fromobject, 3) + self.assertRaises(TypeError, fromobject, BytesLike(b'abc')) + self.assertRaises(TypeError, fromobject, 'abc') + self.assertRaises(TypeError, fromobject, object()) + self.assertRaises(SystemError, fromobject, NULL) + + def test_size(self): + # Test PyBytes_Size() + size = _testlimitedcapi.bytes_size + + self.assertEqual(size(b''), 0) + self.assertEqual(size(b'abc'), 3) + self.assertEqual(size(BytesSubclass(b'abc')), 3) + self.assertRaises(TypeError, size, bytearray(b'abc')) + self.assertRaises(TypeError, size, 'abc') + self.assertRaises(TypeError, size, object()) + + # CRASHES size(NULL) + + def test_asstring(self): + """Test PyBytes_AsString()""" + asstring = _testlimitedcapi.bytes_asstring + + self.assertEqual(asstring(b'abc', 4), b'abc\0') + self.assertEqual(asstring(b'abc\0def', 8), b'abc\0def\0') + self.assertEqual(asstring(b'', 1), b'\0') + self.assertRaises(TypeError, asstring, 'abc', 0) + self.assertRaises(TypeError, asstring, object(), 0) + + # CRASHES asstring(NULL, 0) + + def test_asstringandsize(self): + """Test PyBytes_AsStringAndSize()""" + asstringandsize = _testlimitedcapi.bytes_asstringandsize + asstringandsize_null = _testlimitedcapi.bytes_asstringandsize_null + + self.assertEqual(asstringandsize(b'abc', 4), (b'abc\0', 3)) + self.assertEqual(asstringandsize(b'abc\0def', 8), (b'abc\0def\0', 7)) + self.assertEqual(asstringandsize(b'', 1), (b'\0', 0)) + self.assertEqual(asstringandsize_null(b'abc', 4), b'abc\0') + self.assertRaises(ValueError, asstringandsize_null, b'abc\0def', 8) + self.assertRaises(TypeError, asstringandsize, 'abc', 0) + self.assertRaises(TypeError, asstringandsize_null, 'abc', 0) + self.assertRaises(TypeError, asstringandsize, object(), 0) + self.assertRaises(TypeError, asstringandsize_null, object(), 0) + + # CRASHES asstringandsize(NULL, 0) + # CRASHES asstringandsize_null(NULL, 0) + + def test_repr(self): + # Test PyBytes_Repr() + bytes_repr = _testlimitedcapi.bytes_repr + + self.assertEqual(bytes_repr(b'', 0), r"""b''""") + self.assertEqual(bytes_repr(b'''abc''', 0), r"""b'abc'""") + self.assertEqual(bytes_repr(b'''abc''', 1), r"""b'abc'""") + self.assertEqual(bytes_repr(b'''a'b"c"d''', 0), r"""b'a\'b"c"d'""") + self.assertEqual(bytes_repr(b'''a'b"c"d''', 1), r"""b'a\'b"c"d'""") + self.assertEqual(bytes_repr(b'''a'b"c''', 0), r"""b'a\'b"c'""") + self.assertEqual(bytes_repr(b'''a'b"c''', 1), r"""b'a\'b"c'""") + self.assertEqual(bytes_repr(b'''a'b'c"d''', 0), r"""b'a\'b\'c"d'""") + self.assertEqual(bytes_repr(b'''a'b'c"d''', 1), r"""b'a\'b\'c"d'""") + self.assertEqual(bytes_repr(b'''a'b'c'd''', 0), r"""b'a\'b\'c\'d'""") + self.assertEqual(bytes_repr(b'''a'b'c'd''', 1), r'''b"a'b'c'd"''') + + self.assertEqual(bytes_repr(BytesSubclass(b'abc'), 0), r"""b'abc'""") + + # UDEFINED bytes_repr(object(), 0) + # CRASHES bytes_repr(NULL, 0) + + def test_concat(self, concat=None): + """Test PyBytes_Concat()""" + if concat is None: + concat = _testlimitedcapi.bytes_concat + + self.assertEqual(concat(b'abc', b'def'), b'abcdef') + self.assertEqual(concat(b'a\0b', b'c\0d'), b'a\0bc\0d') + self.assertEqual(concat(bytearray(b'abc'), b'def'), b'abcdef') + self.assertEqual(concat(b'abc', bytearray(b'def')), b'abcdef') + self.assertEqual(concat(bytearray(b'abc'), b''), b'abc') + self.assertEqual(concat(b'', bytearray(b'def')), b'def') + self.assertEqual(concat(memoryview(b'xabcy')[1:4], b'def'), b'abcdef') + self.assertEqual(concat(b'abc', memoryview(b'xdefy')[1:4]), b'abcdef') + self.assertEqual(concat(b'', b''), b'') + + self.assertEqual(concat(b'abc', b'def', True), b'abcdef') + self.assertEqual(concat(b'abc', bytearray(b'def'), True), b'abcdef') + # Check that it does not change the singleton + self.assertEqual(concat(bytes(), b'def', True), b'def') + self.assertEqual(len(bytes()), 0) + + self.assertRaises(TypeError, concat, memoryview(b'axbycz')[::2], b'def') + self.assertRaises(TypeError, concat, b'abc', memoryview(b'dxeyfz')[::2]) + self.assertRaises(TypeError, concat, b'abc', 'def') + self.assertRaises(TypeError, concat, 'abc', b'def') + self.assertRaises(TypeError, concat, 'abc', 'def') + self.assertRaises(TypeError, concat, [], b'def') + self.assertRaises(TypeError, concat, b'abc', []) + self.assertRaises(TypeError, concat, [], []) + + self.assertEqual(concat(NULL, b'def'), NULL) + self.assertEqual(concat(b'abc', NULL), NULL) + self.assertEqual(concat(NULL, object()), NULL) + self.assertEqual(concat(object(), NULL), NULL) + + def test_concatanddel(self): + """Test PyBytes_ConcatAndDel()""" + self.test_concat(_testlimitedcapi.bytes_concatanddel) + + def test_decodeescape(self): + """Test PyBytes_DecodeEscape()""" + decodeescape = _testlimitedcapi.bytes_decodeescape + + self.assertEqual(decodeescape(b''), b'') + self.assertEqual(decodeescape(b'abc'), b'abc') + self.assertEqual(decodeescape(br'\t\n\r\x0b\x0c\x00\\\'\"'), + b'''\t\n\r\v\f\0\\'"''') + self.assertEqual(decodeescape(b'\t\n\r\x0b\x0c\x00'), b'\t\n\r\v\f\0') + self.assertEqual(decodeescape(br'\xa1\xa2'), b'\xa1\xa2') + self.assertEqual(decodeescape(br'\2\24\241'), b'\x02\x14\xa1') + self.assertEqual(decodeescape(b'\xa1\xa2'), b'\xa1\xa2') + with self.assertWarns(DeprecationWarning): + self.assertEqual(decodeescape(br'\u4f60'), br'\u4f60') + with self.assertWarns(DeprecationWarning): + self.assertEqual(decodeescape(br'\z'), br'\z') + with self.assertWarns(DeprecationWarning): + self.assertEqual(decodeescape(br'\541'), b'a') + + for b in b'\\', br'\x', br'\xa', br'\xz', br'\xaz': + self.assertRaises(ValueError, decodeescape, b) + self.assertRaises(ValueError, decodeescape, b, 'strict') + self.assertEqual(decodeescape(br'x\xa', 'replace'), b'x?') + self.assertEqual(decodeescape(br'x\xay', 'replace'), b'x?y') + self.assertEqual(decodeescape(br'x\xa\xy', 'replace'), b'x??y') + self.assertEqual(decodeescape(br'x\xa\xy', 'ignore'), b'xy') + self.assertRaises(ValueError, decodeescape, b'\\', 'spam') + self.assertRaises(OverflowError, decodeescape, b'abc', NULL, PY_SSIZE_T_MAX) + self.assertRaises(OverflowError, decodeescape, NULL, NULL, PY_SSIZE_T_MAX) + + # INVALID decodeescape(NULL) + # CRASHES decodeescape(b'abc', NULL, -1) + # CRASHES decodeescape(NULL, NULL, 1) + + def test_resize(self): + """Test _PyBytes_Resize()""" + _resize = _testcapi.bytes_resize + + def resize(obj, size, new): + result = _resize(obj, size, new) + if 1 <= len(result): + if new or size != len(obj): + # gh-156995: Make sure that the result is a fresh object. + # Previously, _PyBytes_Resize(&obj, 1) returned a singleton + # if _PyObject_IsUniquelyReferenced() is false. + self.assertEqual(sys.getrefcount(result), 1) + self.assertFalse(sys._is_immortal(result)) + else: + # check that the result is the empty bytes string singleton + self.assertTrue(sys._is_immortal(result)) + return result + + for new in True, False: + with self.subTest(new=new): + self.assertEqual(resize(b'abc', 0, new), b'') + self.assertEqual(resize(b'abc', 1, new), b'a') + self.assertEqual(resize(b'abc', 2, new), b'ab') + self.assertEqual(resize(b'abc', 3, new), b'abc') + b = resize(b'abc', 4, new) + self.assertEqual(len(b), 4) + self.assertEqual(b[:3], b'abc') + + self.assertEqual(resize(b'a', 0, new), b'') + self.assertEqual(resize(b'a', 1, new), b'a') + b = resize(b'a', 2, new) + self.assertEqual(len(b), 2) + self.assertEqual(b[:1], b'a') + + self.assertEqual(resize(b'', 0, new), b'') + self.assertEqual(len(resize(b'', 1, new)), 1) + self.assertEqual(len(resize(b'', 2, new)), 2) + + self.assertRaises(SystemError, resize, b'abc', -1, False) + self.assertRaises(SystemError, resize, bytearray(b'abc'), 3, False) + + # CRASHES resize(NULL, 0, False) + # CRASHES resize(NULL, 3, False) + + def test_join(self): + """Test PyBytes_Join()""" + bytes_join = _testcapi.bytes_join + + self.assertEqual(bytes_join(b'', []), b'') + self.assertEqual(bytes_join(b'sep', []), b'') + + self.assertEqual(bytes_join(b'', [b'a', b'b', b'c']), b'abc') + self.assertEqual(bytes_join(b'-', [b'a', b'b', b'c']), b'a-b-c') + self.assertEqual(bytes_join(b' - ', [b'a', b'b', b'c']), b'a - b - c') + self.assertEqual(bytes_join(b'-', [bytearray(b'abc'), + memoryview(b'def')]), + b'abc-def') + + self.assertEqual(bytes_join(b'-', iter([b'a', b'b', b'c'])), b'a-b-c') + + # invalid 'sep' argument + with self.assertRaises(TypeError): + bytes_join(bytearray(b'sep'), []) + with self.assertRaises(TypeError): + bytes_join(memoryview(b'sep'), []) + with self.assertRaises(TypeError): + bytes_join('', []) # empty Unicode string + with self.assertRaises(TypeError): + bytes_join('unicode', []) + with self.assertRaises(TypeError): + bytes_join(123, []) + with self.assertRaises(SystemError): + self.assertEqual(bytes_join(NULL, [b'a', b'b', b'c']), b'abc') + + # invalid 'iterable' argument + with self.assertRaises(TypeError): + bytes_join(b'', [b'bytes', 'unicode']) + with self.assertRaises(TypeError): + bytes_join(b'', [b'bytes', 123]) + with self.assertRaises(TypeError): + bytes_join(b'', 123) + with self.assertRaises(SystemError): + bytes_join(b'', NULL) + + +class BytesWriterTest(unittest.TestCase): + RESULT_TYPE = bytes + + def create_writer(self, alloc=0, string=b''): + return _testcapi.PyBytesWriter(alloc, string, 0) + + def bytes_equal(self, result, expected): + # Similar to assertEqual(), but check also that the result type + # is RESULT_TYPE. + self.assertEqual(result, expected) + self.assertEqual(type(result), self.RESULT_TYPE) + + def test_create(self): + # Test PyBytesWriter_Create() + writer = self.create_writer() + self.assertEqual(writer.get_size(), 0) + self.bytes_equal(writer.finish(), b'') + + writer = self.create_writer(3, b'abc') + self.assertEqual(writer.get_size(), 3) + self.bytes_equal(writer.finish(), b'abc') + + def test_finish_with_size(self): + # Test PyBytesWriter_FinishWithSize() + writer = self.create_writer(10, b'abc') + self.assertEqual(writer.get_size(), 10) + self.bytes_equal(writer.finish_with_size(3), b'abc') + + writer = self.create_writer(3, b'abc') + with self.assertRaises(SystemError): + writer.finish_with_size(-3) + + def test_write_bytes(self): + # Test PyBytesWriter_WriteBytes() + writer = self.create_writer() + writer.write_bytes(b'Hello World!', -1) + self.bytes_equal(writer.finish(), b'Hello World!') + + writer = self.create_writer() + writer.write_bytes(b'Hello ', -1) + writer.write_bytes(b'World! ', 6) + self.bytes_equal(writer.finish(), b'Hello World!') + + def test_resize(self): + # Test PyBytesWriter_Resize() + writer = self.create_writer() + writer.resize(len(b'number=123456'), b'number=123456') + writer.resize(len(b'number=123456'), b'') + self.assertEqual(writer.get_size(), len(b'number=123456')) + self.bytes_equal(writer.finish(), b'number=123456') + + writer = self.create_writer() + writer.resize(0, b'') + writer.resize(len(b'number=123456'), b'number=123456') + self.bytes_equal(writer.finish(), b'number=123456') + + writer = self.create_writer() + writer.resize(len(b'number='), b'number=') + writer.resize(len(b'number=123456'), b'123456') + self.bytes_equal(writer.finish(), b'number=123456') + + writer = self.create_writer() + writer.resize(len(b'number='), b'number=') + writer.resize(len(b'number='), b'') + writer.resize(len(b'number=123456'), b'123456') + self.bytes_equal(writer.finish(), b'number=123456') + + writer = self.create_writer() + writer.resize(len(b'number'), b'number') + writer.resize(len(b'number='), b'=') + writer.resize(len(b'number=123'), b'123') + writer.resize(len(b'number=123456'), b'456') + self.bytes_equal(writer.finish(), b'number=123456') + + def test_format_i(self): + # Test PyBytesWriter_Format() + writer = self.create_writer() + writer.format_i(b'x=%i', 123456) + self.bytes_equal(writer.finish(), b'x=123456') + + writer = self.create_writer() + writer.format_i(b'x=%i, ', 123) + writer.format_i(b'y=%i', 456) + self.bytes_equal(writer.finish(), b'x=123, y=456') + + def test_format_s(self): + # Test PyBytesWriter_Format() + writer = self.create_writer() + writer.format_s(b's=%s', b'Hello World') + self.bytes_equal(writer.finish(), b's=Hello World') + + @support.nomemtest + def test_format_s_memory_error(self): + writer = self.create_writer() + s = b'x' * 500 + with self.assertRaises(MemoryError): + try: + _testcapi.set_nomemory(0, 0) + writer.format_s(b's=%s', s) + finally: + _testcapi.remove_mem_hooks() + writer.write_bytes(b'after', -1) + self.bytes_equal(writer.finish(), b'after') + + def test_example_abc(self): + self.assertEqual(_testcapi.byteswriter_abc(), b'abc') + + def test_example_resize(self): + self.assertEqual(_testcapi.byteswriter_resize(), b'Hello World') + + def test_example_highlevel(self): + self.assertEqual(_testcapi.byteswriter_highlevel(), b'Hello World!') + + +class ByteArrayWriterTest(BytesWriterTest): + RESULT_TYPE = bytearray + + def create_writer(self, alloc=0, string=b''): + return _testcapi.PyBytesWriter(alloc, string, 1) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_capsule.py b/Lib/test/test_capi/test_capsule.py new file mode 100644 index 00000000000..981caf3fad4 --- /dev/null +++ b/Lib/test/test_capi/test_capsule.py @@ -0,0 +1,181 @@ +import importlib +import os +import sys +import textwrap +import unittest +from test.support import import_helper, os_helper + +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') + + +class CapsuleImportTests(unittest.TestCase): + """Tests for PyCapsule_Import().""" + + @classmethod + def setUpClass(cls): + tmp = cls.tmp = cls.enterClassContext(os_helper.temp_dir()) + cls.enterClassContext(import_helper.DirsOnSysPath(tmp)) + cls.write_file(os.path.join(tmp, 'capsule_mod.py'), ''' + import _testlimitedcapi + + capsule = _testlimitedcapi.capsule_new('capsule_mod.capsule') + капсула = _testlimitedcapi.capsule_new('capsule_mod.капсула') + mismatched = _testlimitedcapi.capsule_new('other.name') + nonutf8 = _testlimitedcapi.capsule_new(b'capsule_mod.nonutf8\\xff') + nullname = _testlimitedcapi.capsule_new(None) + not_capsule = 42 + + class ns: + nested = _testlimitedcapi.capsule_new('capsule_mod.ns.nested') + + def __getattr__(name): + if name == 'bad_attr': + raise FloatingPointError('bad attribute') + raise AttributeError(name) + ''') + pkg = os.path.join(tmp, 'capsule_pkg') + os.mkdir(pkg) + cls.write_file(os.path.join(pkg, '__init__.py'), '') + cls.write_file(os.path.join(pkg, 'sub.py'), ''' + import _testlimitedcapi + + capsule = _testlimitedcapi.capsule_new('capsule_pkg.sub.capsule') + ''') + autopkg = os.path.join(tmp, 'capsule_autopkg') + os.mkdir(autopkg) + cls.write_file(os.path.join(autopkg, '__init__.py'), 'from . import sub\n') + cls.write_file(os.path.join(autopkg, 'sub.py'), ''' + import _testlimitedcapi + + capsule = _testlimitedcapi.capsule_new('capsule_autopkg.sub.capsule') + ''') + cls.write_file(os.path.join(tmp, 'capsule_broken.py'), '1/0\n') + importlib.invalidate_caches() + + def setUp(self): + for name in ('capsule_mod', 'capsule_pkg.sub', 'capsule_pkg', + 'capsule_autopkg.sub', 'capsule_autopkg', + 'capsule_broken'): + self.addCleanup(import_helper.unload, name) + + @staticmethod + def write_file(path, source): + with open(path, 'w', encoding='utf-8') as f: + f.write(textwrap.dedent(source)) + + def check_import(self, name, no_block=0): + # _testlimitedcapi.PyCapsule_Import() returns the name stored as the + # pointer by _testlimitedcapi.capsule_new(). + self.assertEqual(_testlimitedcapi.PyCapsule_Import(name, no_block), name) + + def test_import(self): + # The module is imported if not already imported. + self.assertNotIn('capsule_mod', sys.modules) + self.check_import('capsule_mod.capsule') + # Attributes after the first component are plain attribute lookups. + self.check_import('capsule_mod.ns.nested') + # Non-ASCII capsule and attribute name. + self.check_import('capsule_mod.капсула') + # The no_block argument is ignored. + self.check_import('capsule_mod.capsule', 1) + + @unittest.skipUnless(os_helper.TESTFN_NONASCII, + 'requires non-ASCII file name support') + def test_non_ascii_module_name(self): + name = os_helper.TESTFN_NONASCII + self.write_file(os.path.join(self.tmp, name + '.py'), f''' + import _testlimitedcapi + + capsule = _testlimitedcapi.capsule_new('{name}.capsule') + ''') + importlib.invalidate_caches() + self.addCleanup(import_helper.unload, name) + self.check_import(f'{name}.capsule') + + def test_submodule(self): + # Only the first component is imported; a submodule not imported + # by its package is not found. + self.assertRaises(AttributeError, + _testlimitedcapi.PyCapsule_Import, 'capsule_pkg.sub.capsule') + # It is found after explicit import. + importlib.import_module('capsule_pkg.sub') + self.check_import('capsule_pkg.sub.capsule') + # A submodule imported by its package is found. + self.check_import('capsule_autopkg.sub.capsule') + + def test_invalid_name(self): + pycapsule_import = _testlimitedcapi.PyCapsule_Import + # Non-existing module. + self.assertRaisesRegex(ImportError, + 'PyCapsule_Import could not import module "capsule_nonexistent"', + pycapsule_import, 'capsule_nonexistent.capsule') + # Non-UTF-8 module name. + self.assertRaisesRegex(ImportError, + 'PyCapsule_Import could not import module', + pycapsule_import, b'\xff\xfe.capsule') + # Empty module name. + self.assertRaisesRegex(ImportError, + 'PyCapsule_Import could not import module ""', + pycapsule_import, '.capsule_mod.capsule') + # Empty name. + self.assertRaisesRegex(ImportError, + 'PyCapsule_Import could not import module ""', + pycapsule_import, '') + # Only a dot. + self.assertRaisesRegex(ImportError, + 'PyCapsule_Import could not import module ""', + pycapsule_import, '.') + # Non-existing attribute. + self.assertRaises(AttributeError, + pycapsule_import, 'capsule_mod.nonexistent') + # Empty attribute name. + self.assertRaises(AttributeError, pycapsule_import, 'capsule_mod.') + # Consecutive dots. + self.assertRaises(AttributeError, + pycapsule_import, 'capsule_mod..capsule') + # Attribute of an object which is not a module. + self.assertRaises(AttributeError, + pycapsule_import, 'capsule_mod.not_capsule.capsule') + # No attribute name. + self.assertRaisesRegex(AttributeError, 'is not valid', + pycapsule_import, 'capsule_mod') + + # CRASHES pycapsule_import(NULL) + + def test_invalid_capsule(self): + pycapsule_import = _testlimitedcapi.PyCapsule_Import + # The attribute is not a capsule. + self.assertRaisesRegex(AttributeError, 'is not valid', + pycapsule_import, 'capsule_mod.not_capsule') + # The capsule name does not match the requested name. + self.assertRaisesRegex(AttributeError, 'is not valid', + pycapsule_import, 'capsule_mod.mismatched') + # The capsule name contains a byte not decodable from UTF-8. + self.assertRaisesRegex(AttributeError, 'is not valid', + pycapsule_import, 'capsule_mod.nonutf8') + # Even the exactly matching name fails: the attribute lookup + # requires a name decodable from UTF-8. + self.assertRaises(UnicodeDecodeError, + pycapsule_import, b'capsule_mod.nonutf8\xff') + # The capsule name is NULL. + self.assertRaisesRegex(AttributeError, 'is not valid', + pycapsule_import, 'capsule_mod.nullname') + + def test_error_from_import(self): + # The exception raised during importing the module is replaced + # with generic ImportError. + with self.assertRaises(ImportError) as cm: + _testlimitedcapi.PyCapsule_Import('capsule_broken.capsule') + self.assertEqual(str(cm.exception), + 'PyCapsule_Import could not import ' + 'module "capsule_broken"') + + def test_error_from_attribute_lookup(self): + self.assertRaises(FloatingPointError, + _testlimitedcapi.PyCapsule_Import, 'capsule_mod.bad_attr') + self.assertRaises(FloatingPointError, + _testlimitedcapi.PyCapsule_Import, 'capsule_mod.bad_attr.capsule') + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_dict.py b/Lib/test/test_capi/test_dict.py new file mode 100644 index 00000000000..4cf404e9f56 --- /dev/null +++ b/Lib/test/test_capi/test_dict.py @@ -0,0 +1,679 @@ +import contextlib +import unittest +from collections import OrderedDict, UserDict +from types import MappingProxyType +from test import support +from test.support import import_helper + + +_testcapi = import_helper.import_module("_testcapi") +_testlimitedcapi = import_helper.import_module("_testlimitedcapi") + + +NULL = None +INVALID_UTF8 = b'\xff' + +class DictSubclass(dict): + def __getitem__(self, key): + raise RuntimeError('do not get evil') + def __setitem__(self, key, value): + raise RuntimeError('do not set evil') + def __delitem__(self, key): + raise RuntimeError('do not del evil') + +def gen(): + yield 'a' + yield 'b' + yield 'c' + + +class FrozenDictSubclass(frozendict): + pass + + +DICT_TYPES = (dict, DictSubclass, OrderedDict) +FROZENDICT_TYPES = (frozendict, FrozenDictSubclass) +ANYDICT_TYPES = DICT_TYPES + FROZENDICT_TYPES +MAPPING_TYPES = (UserDict,) +NOT_DICT_TYPES = FROZENDICT_TYPES + MAPPING_TYPES +NOT_FROZENDICT_TYPES = DICT_TYPES + MAPPING_TYPES +NOT_ANYDICT_TYPES = MAPPING_TYPES +OTHER_TYPES = (lambda: [1], lambda: 42, object) # (list, int, object) + + +class CAPITest(unittest.TestCase): + + def test_dict_check(self): + # Test PyDict_Check() + check = _testlimitedcapi.dict_check + for dict_type in DICT_TYPES: + self.assertTrue(check(dict_type({1: 2}))) + for test_type in NOT_DICT_TYPES: + self.assertFalse(check(test_type({1: 2}))) + for test_type in OTHER_TYPES: + self.assertFalse(check(test_type())) + # CRASHES check(NULL) + + def test_dict_checkexact(self): + # Test PyDict_CheckExact() + check = _testlimitedcapi.dict_checkexact + for dict_type in DICT_TYPES: + self.assertEqual(check(dict_type({1: 2})), dict_type == dict) + for test_type in NOT_DICT_TYPES: + self.assertFalse(check(test_type({1: 2}))) + for test_type in OTHER_TYPES: + self.assertFalse(check(test_type())) + # CRASHES check(NULL) + + def test_dict_new(self): + # Test PyDict_New() + dict_new = _testlimitedcapi.dict_new + dct = dict_new() + self.assertEqual(dct, {}) + self.assertIs(type(dct), dict) + dct2 = dict_new() + self.assertIsNot(dct2, dct) + + def test_dictproxy_new(self): + # Test PyDictProxy_New() + dictproxy_new = _testlimitedcapi.dictproxy_new + for dict_type in ANYDICT_TYPES + MAPPING_TYPES: + if dict_type == DictSubclass: + continue + dct = dict_type({1: 2}) + proxy = dictproxy_new(dct) + self.assertIs(type(proxy), MappingProxyType) + self.assertEqual(proxy, dct) + with self.assertRaises(TypeError): + proxy[1] = 3 + self.assertEqual(proxy[1], 2) + if not isinstance(dct, frozendict): + dct[1] = 4 + self.assertEqual(proxy[1], 4) + + self.assertRaises(TypeError, dictproxy_new, []) + self.assertRaises(TypeError, dictproxy_new, 42) + # CRASHES dictproxy_new(NULL) + + def test_dict_copy(self): + # Test PyDict_Copy() + copy = _testlimitedcapi.dict_copy + for dict_type in DICT_TYPES: + dct = dict_type({1: 2}) + dct_copy = copy(dct) + self.assertIs(type(dct_copy), dict) + self.assertEqual(dct_copy, dct) + + for test_type in NOT_DICT_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, copy, test_type()) + self.assertRaises(SystemError, copy, NULL) + + def test_dict_clear(self): + # Test PyDict_Clear() + clear = _testlimitedcapi.dict_clear + for dict_type in DICT_TYPES: + if dict_type == OrderedDict: + # NOTE: It is not safe to call it with OrderedDict. + continue + dct = dict_type({1: 2}) + clear(dct) + self.assertEqual(dct, {}) + + # Has no effect for non-dicts. + for test_type in NOT_DICT_TYPES: + dct = test_type({1: 2}) + clear(dct) + self.assertEqual(dct, {1: 2}) + lst = [1, 2] + clear(lst) + self.assertEqual(lst, [1, 2]) + clear(object()) + + # CRASHES clear(NULL) + + def test_dict_size(self): + # Test PyDict_Size() + size = _testlimitedcapi.dict_size + for dict_type in ANYDICT_TYPES: + self.assertEqual(size(dict_type({1: 2, 3: 4})), 2) + + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, size, test_type()) + self.assertRaises(SystemError, size, NULL) + + def test_dict_getitem(self): + # Test PyDict_GetItem() + getitem = _testlimitedcapi.dict_getitem + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, '\U0001f40d': 2}) + self.assertEqual(getitem(dct, 'a'), 1) + self.assertIs(getitem(dct, 'b'), KeyError) + self.assertEqual(getitem(dct, '\U0001f40d'), 2) + + with support.catch_unraisable_exception() as cm: + self.assertIs(getitem({}, []), KeyError) # unhashable + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + "unhashable type: 'list'") + + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertIs(getitem(test_type(), 'a'), KeyError) + + # CRASHES getitem({}, NULL) + # CRASHES getitem(NULL, 'a') + + def test_dict_getitemstring(self): + # Test PyDict_GetItemString() + getitemstring = _testlimitedcapi.dict_getitemstring + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, '\U0001f40d': 2}) + self.assertEqual(getitemstring(dct, b'a'), 1) + self.assertIs(getitemstring(dct, b'b'), KeyError) + self.assertEqual(getitemstring(dct, '\U0001f40d'.encode()), 2) + + with support.catch_unraisable_exception() as cm: + self.assertIs(getitemstring({}, INVALID_UTF8), KeyError) + self.assertEqual(cm.unraisable.exc_type, UnicodeDecodeError) + self.assertRegex(str(cm.unraisable.exc_value), + "'utf-8' codec can't decode") + + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertIs(getitemstring(test_type(), b'a'), KeyError) + # CRASHES getitemstring({}, NULL) + # CRASHES getitemstring(NULL, b'a') + + def test_dict_getitemref(self): + # Test PyDict_GetItemRef() + getitem = _testcapi.dict_getitemref + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, '\U0001f40d': 2}) + self.assertEqual(getitem(dct, 'a'), 1) + self.assertIs(getitem(dct, 'b'), KeyError) + self.assertEqual(getitem(dct, '\U0001f40d'), 2) + + self.assertRaises(TypeError, getitem, {}, []) # unhashable + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, getitem, test_type(), 'a') + # CRASHES getitem({}, NULL) + # CRASHES getitem(NULL, 'a') + + def test_dict_getitemstringref(self): + # Test PyDict_GetItemStringRef() + getitemstring = _testcapi.dict_getitemstringref + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, '\U0001f40d': 2}) + self.assertEqual(getitemstring(dct, b'a'), 1) + self.assertIs(getitemstring(dct, b'b'), KeyError) + self.assertEqual(getitemstring(dct, '\U0001f40d'.encode()), 2) + + self.assertRaises(UnicodeDecodeError, getitemstring, {}, INVALID_UTF8) + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, getitemstring, test_type(), b'a') + # CRASHES getitemstring({}, NULL) + # CRASHES getitemstring(NULL, b'a') + + def test_dict_getitemwitherror(self): + # Test PyDict_GetItemWithError() + getitem = _testlimitedcapi.dict_getitemwitherror + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, '\U0001f40d': 2}) + self.assertEqual(getitem(dct, 'a'), 1) + self.assertIs(getitem(dct, 'b'), KeyError) + self.assertEqual(getitem(dct, '\U0001f40d'), 2) + + self.assertRaises(TypeError, getitem, {}, []) # unhashable + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, getitem, [], 'a') + # CRASHES getitem({}, NULL) + # CRASHES getitem(NULL, 'a') + + def test_dict_contains(self): + # Test PyDict_Contains() + contains = _testlimitedcapi.dict_contains + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, '\U0001f40d': 2}) + self.assertTrue(contains(dct, 'a')) + self.assertFalse(contains(dct, 'b')) + self.assertTrue(contains(dct, '\U0001f40d')) + + self.assertRaises(TypeError, contains, {}, []) # unhashable + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, contains, test_type(), 'a') + + # CRASHES contains({}, NULL) + # CRASHES contains(NULL, 'a') + + def test_dict_contains_string(self): + # Test PyDict_ContainsString() + contains_string = _testcapi.dict_containsstring + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, '\U0001f40d': 2}) + self.assertTrue(contains_string(dct, b'a')) + self.assertFalse(contains_string(dct, b'b')) + self.assertTrue(contains_string(dct, '\U0001f40d'.encode())) + self.assertRaises(UnicodeDecodeError, contains_string, dct, INVALID_UTF8) + + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, contains_string, test_type(), b'a') + + # CRASHES contains({}, NULL) + # CRASHES contains(NULL, b'a') + + @contextlib.contextmanager + def frozendict_does_not_support(self, what): + errmsg = f'frozendict object does not support item {what}' + with self.assertRaisesRegex(TypeError, errmsg): + yield + + def test_dict_setitem(self): + # Test PyDict_SetItem() + setitem = _testlimitedcapi.dict_setitem + for dict_type in DICT_TYPES: + dct = dict_type() + setitem(dct, 'a', 5) + self.assertEqual(dct, {'a': 5}) + setitem(dct, '\U0001f40d', 8) + self.assertEqual(dct, {'a': 5, '\U0001f40d': 8}) + + self.assertRaises(TypeError, setitem, {}, [], 5) # unhashable + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('assignment'): + setitem(test_type(), 'a', 5) + for test_type in MAPPING_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, setitem, test_type(), 'a', 5) + # CRASHES setitem({}, NULL, 5) + # CRASHES setitem({}, 'a', NULL) + # CRASHES setitem(NULL, 'a', 5) + + def test_dict_setitemstring(self): + # Test PyDict_SetItemString() + setitemstring = _testlimitedcapi.dict_setitemstring + for dict_type in DICT_TYPES: + dct = dict_type() + setitemstring(dct, b'a', 5) + self.assertEqual(dct, {'a': 5}) + setitemstring(dct, '\U0001f40d'.encode(), 8) + self.assertEqual(dct, {'a': 5, '\U0001f40d': 8}) + + self.assertRaises(UnicodeDecodeError, setitemstring, {}, INVALID_UTF8, 5) + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('assignment'): + setitemstring(test_type(), b'a', 5) + for test_type in MAPPING_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, setitemstring, test_type(), b'a', 5) + # CRASHES setitemstring({}, NULL, 5) + # CRASHES setitemstring({}, b'a', NULL) + # CRASHES setitemstring(NULL, b'a', 5) + + def test_dict_delitem(self): + # Test PyDict_DelItem() + delitem = _testlimitedcapi.dict_delitem + for dict_type in DICT_TYPES: + dct = dict_type({'a': 1, 'c': 2, '\U0001f40d': 3}) + delitem(dct, 'a') + self.assertEqual(dct, {'c': 2, '\U0001f40d': 3}) + self.assertRaises(KeyError, delitem, dct, 'b') + delitem(dct, '\U0001f40d') + self.assertEqual(dct, {'c': 2}) + + self.assertRaises(TypeError, delitem, {}, []) # unhashable + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('deletion'): + delitem(test_type({'a': 1}), 'a') + for test_type in MAPPING_TYPES: + self.assertRaises(SystemError, delitem, test_type({'a': 1}), 'a') + for test_type in OTHER_TYPES: + self.assertRaises(SystemError, delitem, test_type(), 'a') + # CRASHES delitem({}, NULL) + # CRASHES delitem(NULL, 'a') + + def test_dict_delitemstring(self): + # Test PyDict_DelItemString() + delitemstring = _testlimitedcapi.dict_delitemstring + for dict_type in DICT_TYPES: + dct = dict_type({'a': 1, 'c': 2, '\U0001f40d': 3}) + delitemstring(dct, b'a') + self.assertEqual(dct, {'c': 2, '\U0001f40d': 3}) + self.assertRaises(KeyError, delitemstring, dct, b'b') + delitemstring(dct, '\U0001f40d'.encode()) + self.assertEqual(dct, {'c': 2}) + + self.assertRaises(UnicodeDecodeError, delitemstring, {}, INVALID_UTF8) + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('deletion'): + delitemstring(test_type({'a': 1}), b'a') + for test_type in MAPPING_TYPES: + self.assertRaises(SystemError, delitemstring, test_type({'a': 1}), b'a') + for test_type in OTHER_TYPES: + self.assertRaises(SystemError, delitemstring, test_type(), b'a') + # CRASHES delitemstring({}, NULL) + # CRASHES delitemstring(NULL, b'a') + + def test_dict_setdefault(self): + # Test PyDict_SetDefault() + setdefault = _testcapi.dict_setdefault + for dict_type in DICT_TYPES: + dct = dict_type() + self.assertEqual(setdefault(dct, 'a', 5), 5) + self.assertEqual(dct, {'a': 5}) + self.assertEqual(setdefault(dct, 'a', 8), 5) + self.assertEqual(dct, {'a': 5}) + + self.assertRaises(TypeError, setdefault, {}, [], 5) # unhashable + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('assignment'): + setdefault(test_type(), 'a', 5) + for test_type in MAPPING_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, setdefault, test_type(), 'a', 5) + # CRASHES setdefault({}, NULL, 5) + # CRASHES setdefault({}, 'a', NULL) + # CRASHES setdefault(NULL, 'a', 5) + + def test_dict_setdefaultref(self): + # Test PyDict_SetDefaultRef() + setdefault = _testcapi.dict_setdefaultref + for dict_type in DICT_TYPES: + dct = dict_type() + self.assertEqual(setdefault(dct, 'a', 5), 5) + self.assertEqual(dct, {'a': 5}) + self.assertEqual(setdefault(dct, 'a', 8), 5) + self.assertEqual(dct, {'a': 5}) + + self.assertRaises(TypeError, setdefault, {}, [], 5) # unhashable + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('assignment'): + setdefault(test_type(), 'a', 5) + for test_type in MAPPING_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, setdefault, test_type(), 'a', 5) + # CRASHES setdefault({}, NULL, 5) + # CRASHES setdefault({}, 'a', NULL) + # CRASHES setdefault(NULL, 'a', 5) + + def test_mapping_keys_valuesitems(self): + # Test PyDict_Keys(), PyDict_Values() and PyDict_Items() + class BadMapping(dict): + def keys(self): + return None + def values(self): + return None + def items(self): + return None + dict_obj = {'foo': 1, 'bar': 2, 'spam': 3} + for dict_type in ANYDICT_TYPES + (BadMapping,): + mapping = dict_type(dict_obj) + self.assertListEqual(_testlimitedcapi.dict_keys(mapping), + list(dict_obj.keys())) + self.assertListEqual(_testlimitedcapi.dict_values(mapping), + list(dict_obj.values())) + self.assertListEqual(_testlimitedcapi.dict_items(mapping), + list(dict_obj.items())) + + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + mapping = test_type() + self.assertRaises(SystemError, _testlimitedcapi.dict_keys, mapping) + self.assertRaises(SystemError, _testlimitedcapi.dict_values, mapping) + self.assertRaises(SystemError, _testlimitedcapi.dict_items, mapping) + + def test_dict_next(self): + # Test PyDict_Next() + dict_next = _testlimitedcapi.dict_next + self.assertIsNone(dict_next({}, 0)) + for dict_type in ANYDICT_TYPES: + dct = dict_type({'a': 1, 'b': 2, 'c': 3}) + pos = 0 + pairs = [] + while True: + res = dict_next(dct, pos) + if res is None: + break + rc, pos, key, value = res + self.assertEqual(rc, 1) + pairs.append((key, value)) + self.assertEqual(pairs, list(dct.items())) + + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + dct = test_type() + pos = 0 + self.assertEqual(dict_next(dct, pos), None) + + # CRASHES dict_next(NULL, 0) + + def test_dict_update(self): + # Test PyDict_Update() + update = _testlimitedcapi.dict_update + for cls1 in DICT_TYPES: + for cls2 in ANYDICT_TYPES + MAPPING_TYPES: + dct = cls1({'a': 1, 'b': 2}) + update(dct, cls2({'b': 3, 'c': 4})) + self.assertEqual(dct, {'a': 1, 'b': 3, 'c': 4}) + + self.assertRaises(AttributeError, update, {}, []) + self.assertRaises(AttributeError, update, {}, 42) + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('assignment'): + update(test_type(), {}) + for test_type in MAPPING_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, update, test_type(), {}) + self.assertRaises(SystemError, update, {}, NULL) + self.assertRaises(SystemError, update, NULL, {}) + + def test_dict_merge(self): + # Test PyDict_Merge() + merge = _testlimitedcapi.dict_merge + for cls1 in DICT_TYPES: + for cls2 in ANYDICT_TYPES + MAPPING_TYPES: + dct = cls1({'a': 1, 'b': 2}) + merge(dct, cls2({'b': 3, 'c': 4}), 0) + self.assertEqual(dct, {'a': 1, 'b': 2, 'c': 4}) + dct = cls1({'a': 1, 'b': 2}) + merge(dct, cls2({'b': 3, 'c': 4}), 1) + self.assertEqual(dct, {'a': 1, 'b': 3, 'c': 4}) + + self.assertRaises(AttributeError, merge, {}, [], 0) + self.assertRaises(AttributeError, merge, {}, 42, 0) + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('assignment'): + merge(test_type(), {}, 0) + for test_type in MAPPING_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, merge, test_type(), {}, 0) + self.assertRaises(SystemError, merge, {}, NULL, 0) + self.assertRaises(SystemError, merge, NULL, {}, 0) + + def test_dict_mergefromseq2(self): + # Test PyDict_MergeFromSeq2() + mergefromseq2 = _testlimitedcapi.dict_mergefromseq2 + for cls1 in DICT_TYPES: + for cls2 in list, iter: + dct = cls1({'a': 1, 'b': 2}) + mergefromseq2(dct, cls2([('b', 3), ('c', 4)]), 0) + self.assertEqual(dct, {'a': 1, 'b': 2, 'c': 4}) + dct = cls1({'a': 1, 'b': 2}) + mergefromseq2(dct, cls2([('b', 3), ('c', 4)]), 1) + self.assertEqual(dct, {'a': 1, 'b': 3, 'c': 4}) + + self.assertRaises(ValueError, mergefromseq2, {}, [(1,)], 0) + self.assertRaises(ValueError, mergefromseq2, {}, [(1, 2, 3)], 0) + self.assertRaises(TypeError, mergefromseq2, {}, [1], 0) + self.assertRaises(TypeError, mergefromseq2, {}, 42, 0) + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('assignment'): + mergefromseq2(test_type(), [], 0) + for test_type in MAPPING_TYPES + OTHER_TYPES: + self.assertRaises(SystemError, mergefromseq2, test_type(), [], 0) + # CRASHES mergefromseq2({}, NULL, 0) + # CRASHES mergefromseq2(NULL, {}, 0) + + def test_dict_pop(self): + # Test PyDict_Pop() + dict_pop = _testcapi.dict_pop + dict_pop_null = _testcapi.dict_pop_null + + for dict_type in DICT_TYPES: + # key present, get removed value + mydict = dict_type({"key": "value", "key2": "value2"}) + self.assertEqual(dict_pop(mydict, "key"), (1, "value")) + self.assertEqual(mydict, {"key2": "value2"}) + self.assertEqual(dict_pop(mydict, "key2"), (1, "value2")) + self.assertEqual(mydict, {}) + + # key present, ignore removed value + mydict = dict_type({"key": "value", "key2": "value2"}) + self.assertEqual(dict_pop_null(mydict, "key"), 1) + self.assertEqual(mydict, {"key2": "value2"}) + self.assertEqual(dict_pop_null(mydict, "key2"), 1) + self.assertEqual(mydict, {}) + + # key missing, expect removed value; empty dict has a fast path + mydict = dict_type() + self.assertEqual(dict_pop(mydict, "key"), (0, NULL)) + mydict = dict_type({"a": 1}) + self.assertEqual(dict_pop(mydict, "key"), (0, NULL)) + + # key missing, ignored removed value; empty dict has a fast path + mydict = dict_type() + self.assertEqual(dict_pop_null(mydict, "key"), 0) + mydict = dict_type({"a": 1}) + self.assertEqual(dict_pop_null(mydict, "key"), 0) + + # key error; don't hash key if dict is empty + not_hashable_key = ["list"] + mydict = dict_type() + self.assertEqual(dict_pop(mydict, not_hashable_key), (0, NULL)) + dict_pop(mydict, NULL) # key is not checked if dict is empty + mydict = dict_type({'key': 1}) + with self.assertRaises(TypeError): + dict_pop(mydict, not_hashable_key) + + # wrong dict type + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('deletion'): + dict_pop(test_type(), "key") + for test_type in MAPPING_TYPES + OTHER_TYPES: + not_dict = test_type() + self.assertRaises(SystemError, dict_pop, not_dict, "key") + self.assertRaises(SystemError, dict_pop_null, not_dict, "key") + + # CRASHES dict_pop(NULL, "key") + # CRASHES dict_pop({"a": 1}, NULL) + + def test_dict_popstring(self): + # Test PyDict_PopString() + dict_popstring = _testcapi.dict_popstring + dict_popstring_null = _testcapi.dict_popstring_null + + for dict_type in DICT_TYPES: + # key present, get removed value + mydict = dict_type({"key": "value", "key2": "value2"}) + self.assertEqual(dict_popstring(mydict, "key"), (1, "value")) + self.assertEqual(mydict, {"key2": "value2"}) + self.assertEqual(dict_popstring(mydict, "key2"), (1, "value2")) + self.assertEqual(mydict, {}) + + # key present, ignore removed value + mydict = dict_type({"key": "value", "key2": "value2"}) + self.assertEqual(dict_popstring_null(mydict, "key"), 1) + self.assertEqual(mydict, {"key2": "value2"}) + self.assertEqual(dict_popstring_null(mydict, "key2"), 1) + self.assertEqual(mydict, {}) + + # key missing; empty dict has a fast path + mydict = dict_type() + self.assertEqual(dict_popstring(mydict, "key"), (0, NULL)) + self.assertEqual(dict_popstring_null(mydict, "key"), 0) + mydict = dict_type({"a": 1}) + self.assertEqual(dict_popstring(mydict, "key"), (0, NULL)) + self.assertEqual(dict_popstring_null(mydict, "key"), 0) + + # non-ASCII key + non_ascii = '\U0001f40d' + dct = dict_type({'\U0001f40d': 123}) + self.assertEqual(dict_popstring(dct, '\U0001f40d'.encode()), (1, 123)) + dct = dict_type({'\U0001f40d': 123}) + self.assertEqual(dict_popstring_null(dct, '\U0001f40d'.encode()), 1) + + # key error + mydict = dict_type({1: 2}) + self.assertRaises(UnicodeDecodeError, dict_popstring, mydict, INVALID_UTF8) + self.assertRaises(UnicodeDecodeError, dict_popstring_null, mydict, INVALID_UTF8) + + # wrong dict type + for test_type in FROZENDICT_TYPES: + with self.frozendict_does_not_support('deletion'): + dict_popstring(test_type(), "key") + for test_type in MAPPING_TYPES + OTHER_TYPES: + not_dict = test_type() + self.assertRaises(SystemError, dict_popstring, not_dict, "key") + self.assertRaises(SystemError, dict_popstring_null, not_dict, "key") + + # CRASHES dict_popstring(NULL, "key") + # CRASHES dict_popstring({}, NULL) + # CRASHES dict_popstring({"a": 1}, NULL) + + def test_frozendict_check(self): + # Test PyFrozenDict_Check() + check = _testcapi.frozendict_check + for dict_type in FROZENDICT_TYPES: + self.assertTrue(check(dict_type(x=1))) + for dict_type in NOT_FROZENDICT_TYPES + OTHER_TYPES: + self.assertFalse(check(dict_type())) + # CRASHES check(NULL) + + def test_frozendict_checkexact(self): + # Test PyFrozenDict_CheckExact() + check = _testcapi.frozendict_checkexact + for dict_type in FROZENDICT_TYPES: + self.assertEqual(check(dict_type(x=1)), dict_type == frozendict) + for dict_type in NOT_FROZENDICT_TYPES + OTHER_TYPES: + self.assertFalse(check(dict_type())) + # CRASHES check(NULL) + + def test_anydict_check(self): + # Test PyAnyDict_Check() + check = _testcapi.anydict_check + for dict_type in ANYDICT_TYPES: + self.assertTrue(check(dict_type({1: 2}))) + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertFalse(check(test_type())) + # CRASHES check(NULL) + + def test_anydict_checkexact(self): + # Test PyAnyDict_CheckExact() + check = _testcapi.anydict_checkexact + for dict_type in ANYDICT_TYPES: + self.assertEqual(check(dict_type(x=1)), + dict_type in (dict, frozendict)) + for test_type in NOT_ANYDICT_TYPES + OTHER_TYPES: + self.assertFalse(check(test_type())) + # CRASHES check(NULL) + + def test_frozendict_new(self): + # Test PyFrozenDict_New() + frozendict_new = _testcapi.frozendict_new + + for dict_type in ANYDICT_TYPES: + dct = frozendict_new(dict_type({'x': 1})) + self.assertEqual(dct, frozendict(x=1)) + self.assertIs(type(dct), frozendict) + + dct = frozendict_new([('x', 1), ('y', 2)]) + self.assertEqual(dct, frozendict(x=1, y=2)) + self.assertIs(type(dct), frozendict) + + # PyFrozenDict_New(frozendict) returns the same object unmodified + fd = frozendict(a=1, b=2, c=3) + fd2 = frozendict_new(fd) + self.assertIs(fd2, fd) + + fd = FrozenDictSubclass(a=1, b=2, c=3) + fd2 = frozendict_new(fd) + self.assertIsNot(fd2, fd) + self.assertEqual(fd2, fd) + + # PyFrozenDict_New(NULL) creates an empty dictionary + dct = frozendict_new(NULL) + self.assertEqual(dct, frozendict()) + self.assertIs(type(dct), frozendict) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_eval.py b/Lib/test/test_capi/test_eval.py new file mode 100644 index 00000000000..20ef2695ef3 --- /dev/null +++ b/Lib/test/test_capi/test_eval.py @@ -0,0 +1,103 @@ +import sys +import unittest +from test.support import import_helper + +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') + + +class Tests(unittest.TestCase): + def test_eval_get_func_name(self): + eval_get_func_name = _testlimitedcapi.eval_get_func_name + + def function_example(): ... + + class A: + def method_example(self): ... + + self.assertEqual(eval_get_func_name(function_example), + "function_example") + self.assertEqual(eval_get_func_name(A.method_example), + "method_example") + self.assertEqual(eval_get_func_name(A().method_example), + "method_example") + self.assertEqual(eval_get_func_name(sum), "sum") # c function + self.assertEqual(eval_get_func_name(A), "type") + + def test_eval_get_func_desc(self): + eval_get_func_desc = _testlimitedcapi.eval_get_func_desc + + def function_example(): ... + + class A: + def method_example(self): ... + + self.assertEqual(eval_get_func_desc(function_example), + "()") + self.assertEqual(eval_get_func_desc(A.method_example), + "()") + self.assertEqual(eval_get_func_desc(A().method_example), + "()") + self.assertEqual(eval_get_func_desc(sum), "()") # c function + self.assertEqual(eval_get_func_desc(A), " object") + + def test_eval_getlocals(self): + # Test PyEval_GetLocals() + x = 1 + self.assertEqual(_testlimitedcapi.eval_getlocals(), + {'self': self, + 'x': 1}) + + y = 2 + self.assertEqual(_testlimitedcapi.eval_getlocals(), + {'self': self, + 'x': 1, + 'y': 2}) + + def test_eval_getglobals(self): + # Test PyEval_GetGlobals() + self.assertEqual(_testlimitedcapi.eval_getglobals(), + globals()) + + def test_eval_getbuiltins(self): + # Test PyEval_GetBuiltins() + self.assertEqual(_testlimitedcapi.eval_getbuiltins(), + globals()['__builtins__']) + + def test_eval_getframe(self): + # Test PyEval_GetFrame() + self.assertEqual(_testlimitedcapi.eval_getframe(), + sys._getframe()) + + def test_eval_getframe_builtins(self): + # Test PyEval_GetFrameBuiltins() + self.assertEqual(_testlimitedcapi.eval_getframe_builtins(), + sys._getframe().f_builtins) + + def test_eval_getframe_globals(self): + # Test PyEval_GetFrameGlobals() + self.assertEqual(_testlimitedcapi.eval_getframe_globals(), + sys._getframe().f_globals) + + def test_eval_getframe_locals(self): + # Test PyEval_GetFrameLocals() + self.assertEqual(_testlimitedcapi.eval_getframe_locals(), + sys._getframe().f_locals) + + def test_eval_get_recursion_limit(self): + # Test Py_GetRecursionLimit() + self.assertEqual(_testlimitedcapi.eval_get_recursion_limit(), + sys.getrecursionlimit()) + + def test_eval_set_recursion_limit(self): + # Test Py_SetRecursionLimit() + old_limit = sys.getrecursionlimit() + try: + limit = old_limit + 123 + _testlimitedcapi.eval_set_recursion_limit(limit) + self.assertEqual(sys.getrecursionlimit(), limit) + finally: + sys.setrecursionlimit(old_limit) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_import.py b/Lib/test/test_capi/test_import.py new file mode 100644 index 00000000000..ea845df75ef --- /dev/null +++ b/Lib/test/test_capi/test_import.py @@ -0,0 +1,384 @@ +import importlib.util +import os.path +import sys +import types +import unittest +from test.support import os_helper +from test.support import import_helper +from test.support.warnings_helper import check_warnings + +_testcapi = import_helper.import_module('_testcapi') +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') +NULL = None + + +class ImportTests(unittest.TestCase): + def test_getmagicnumber(self): + # Test PyImport_GetMagicNumber() + magic = _testlimitedcapi.PyImport_GetMagicNumber() + self.assertEqual(magic, + int.from_bytes(importlib.util.MAGIC_NUMBER, 'little')) + + def test_getmagictag(self): + # Test PyImport_GetMagicTag() + tag = _testlimitedcapi.PyImport_GetMagicTag() + self.assertEqual(tag, sys.implementation.cache_tag) + + def test_getmoduledict(self): + # Test PyImport_GetModuleDict() + modules = _testlimitedcapi.PyImport_GetModuleDict() + self.assertIs(modules, sys.modules) + + def check_import_loaded_module(self, import_module): + for name in ('os', 'sys', 'test', 'unittest'): + with self.subTest(name=name): + self.assertIn(name, sys.modules) + old_module = sys.modules[name] + module = import_module(name) + self.assertIsInstance(module, types.ModuleType) + self.assertIs(module, old_module) + + def check_import_fresh_module(self, import_module): + old_modules = dict(sys.modules) + try: + for name in ('colorsys', 'math'): + with self.subTest(name=name): + sys.modules.pop(name, None) + module = import_module(name) + self.assertIsInstance(module, types.ModuleType) + self.assertIs(module, sys.modules[name]) + self.assertEqual(module.__name__, name) + finally: + sys.modules.clear() + sys.modules.update(old_modules) + + def test_getmodule(self): + # Test PyImport_GetModule() + getmodule = _testlimitedcapi.PyImport_GetModule + self.check_import_loaded_module(getmodule) + + nonexistent = 'nonexistent' + self.assertNotIn(nonexistent, sys.modules) + self.assertIs(getmodule(nonexistent), KeyError) + self.assertIs(getmodule(''), KeyError) + self.assertIs(getmodule(object()), KeyError) + + self.assertRaises(TypeError, getmodule, []) # unhashable + # CRASHES getmodule(NULL) + + def check_addmodule(self, add_module, accept_nonstr=False): + # create a new module + names = ['nonexistent'] + if accept_nonstr: + names.append(b'\xff') # non-UTF-8 + # PyImport_AddModuleObject() accepts non-string names + names.append(tuple(['hashable non-string'])) + for name in names: + with self.subTest(name=name): + self.assertNotIn(name, sys.modules) + try: + module = add_module(name) + self.assertIsInstance(module, types.ModuleType) + self.assertEqual(module.__name__, name) + self.assertIs(module, sys.modules[name]) + finally: + sys.modules.pop(name, None) + + # get an existing module + self.check_import_loaded_module(add_module) + + def test_addmoduleobject(self): + # Test PyImport_AddModuleObject() + addmoduleobject = _testlimitedcapi.PyImport_AddModuleObject + self.check_addmodule(addmoduleobject, accept_nonstr=True) + + self.assertRaises(TypeError, addmoduleobject, []) # unhashable + # CRASHES addmoduleobject(NULL) + + def test_addmodule(self): + # Test PyImport_AddModule() + addmodule = _testlimitedcapi.PyImport_AddModule + self.check_addmodule(addmodule) + + self.assertRaises(UnicodeDecodeError, addmodule, b'\xff') + # CRASHES addmodule(NULL) + + def test_addmoduleref(self): + # Test PyImport_AddModuleRef() + addmoduleref = _testlimitedcapi.PyImport_AddModuleRef + self.check_addmodule(addmoduleref) + + self.assertRaises(UnicodeDecodeError, addmoduleref, b'\xff') + # CRASHES addmoduleref(NULL) + + def check_import_func(self, import_module): + self.check_import_loaded_module(import_module) + self.check_import_fresh_module(import_module) + self.assertRaises(ModuleNotFoundError, import_module, 'nonexistent') + self.assertRaises(ValueError, import_module, '') + + def test_import(self): + # Test PyImport_Import() + import_ = _testlimitedcapi.PyImport_Import + self.check_import_func(import_) + + self.assertRaises(TypeError, import_, b'os') + self.assertRaises(SystemError, import_, NULL) + + def test_importmodule(self): + # Test PyImport_ImportModule() + importmodule = _testlimitedcapi.PyImport_ImportModule + self.check_import_func(importmodule) + + self.assertRaises(UnicodeDecodeError, importmodule, b'\xff') + # CRASHES importmodule(NULL) + + def test_importmodulenoblock(self): + # Test deprecated (stable ABI only) PyImport_ImportModuleNoBlock() + importmodulenoblock = _testlimitedcapi.PyImport_ImportModuleNoBlock + with check_warnings(('', DeprecationWarning)): + self.check_import_func(importmodulenoblock) + self.assertRaises(UnicodeDecodeError, importmodulenoblock, b'\xff') + + # CRASHES importmodulenoblock(NULL) + + def check_frozen_import(self, import_frozen_module): + # Importing a frozen module executes its code, so start by unloading + # the module to execute the code in a new (temporary) module. + old_zipimport = sys.modules.pop('zipimport') + try: + self.assertEqual(import_frozen_module('zipimport'), 1) + + # import zipimport again + self.assertEqual(import_frozen_module('zipimport'), 1) + finally: + sys.modules['zipimport'] = old_zipimport + + # not a frozen module + self.assertEqual(import_frozen_module('sys'), 0) + self.assertEqual(import_frozen_module('nonexistent'), 0) + self.assertEqual(import_frozen_module(''), 0) + + def test_importfrozenmodule(self): + # Test PyImport_ImportFrozenModule() + importfrozenmodule = _testlimitedcapi.PyImport_ImportFrozenModule + self.check_frozen_import(importfrozenmodule) + + self.assertRaises(UnicodeDecodeError, importfrozenmodule, b'\xff') + # CRASHES importfrozenmodule(NULL) + + def test_importfrozenmoduleobject(self): + # Test PyImport_ImportFrozenModuleObject() + importfrozenmoduleobject = _testlimitedcapi.PyImport_ImportFrozenModuleObject + self.check_frozen_import(importfrozenmoduleobject) + self.assertEqual(importfrozenmoduleobject(b'zipimport'), 0) + self.assertEqual(importfrozenmoduleobject(NULL), 0) + + def test_importmoduleex(self): + # Test PyImport_ImportModuleEx() + importmoduleex = _testlimitedcapi.PyImport_ImportModuleEx + self.check_import_func(lambda name: importmoduleex(name, NULL, NULL, NULL)) + + self.assertRaises(ModuleNotFoundError, importmoduleex, 'nonexistent', NULL, NULL, NULL) + self.assertRaises(ValueError, importmoduleex, '', NULL, NULL, NULL) + self.assertRaises(UnicodeDecodeError, importmoduleex, b'\xff', NULL, NULL, NULL) + # CRASHES importmoduleex(NULL, NULL, NULL, NULL) + + def check_importmodulelevel(self, importmodulelevel): + self.check_import_func(lambda name: importmodulelevel(name, NULL, NULL, NULL, 0)) + + self.assertRaises(ModuleNotFoundError, importmodulelevel, 'nonexistent', NULL, NULL, NULL, 0) + self.assertRaises(ValueError, importmodulelevel, '', NULL, NULL, NULL, 0) + + if __package__: + self.assertIs(importmodulelevel('test_import', globals(), NULL, NULL, 1), + sys.modules['test.test_capi.test_import']) + self.assertIs(importmodulelevel('test_capi', globals(), NULL, NULL, 2), + sys.modules['test.test_capi']) + self.assertRaises(ValueError, importmodulelevel, 'os', NULL, NULL, NULL, -1) + with self.assertWarns(ImportWarning): + self.assertRaises(KeyError, importmodulelevel, 'test_import', {}, NULL, NULL, 1) + self.assertRaises(TypeError, importmodulelevel, 'test_import', [], NULL, NULL, 1) + + def test_importmodulelevel(self): + # Test PyImport_ImportModuleLevel() + importmodulelevel = _testlimitedcapi.PyImport_ImportModuleLevel + self.check_importmodulelevel(importmodulelevel) + + self.assertRaises(UnicodeDecodeError, importmodulelevel, b'\xff', NULL, NULL, NULL, 0) + # CRASHES importmodulelevel(NULL, NULL, NULL, NULL, 0) + + def test_importmodulelevelobject(self): + # Test PyImport_ImportModuleLevelObject() + importmodulelevel = _testlimitedcapi.PyImport_ImportModuleLevelObject + self.check_importmodulelevel(importmodulelevel) + + self.assertRaises(TypeError, importmodulelevel, b'os', NULL, NULL, NULL, 0) + self.assertRaises(ValueError, importmodulelevel, NULL, NULL, NULL, NULL, 0) + + def check_executecodemodule(self, execute_code, *args): + name = 'test_import_executecode' + try: + # Create a temporary module where the code will be executed + self.assertNotIn(name, sys.modules) + module = _testlimitedcapi.PyImport_AddModuleRef(name) + self.assertNotHasAttr(module, 'attr') + + # Execute the code + code = compile('attr = 1', '', 'exec') + module2 = execute_code(name, code, *args) + self.assertIs(module2, module) + + # Check the function side effects + self.assertEqual(module.attr, 1) + finally: + sys.modules.pop(name, None) + return module.__spec__.origin + + def test_executecodemodule(self): + # Test PyImport_ExecCodeModule() + execcodemodule = _testlimitedcapi.PyImport_ExecCodeModule + self.check_executecodemodule(execcodemodule) + + code = compile('attr = 1', '', 'exec') + self.assertRaises(UnicodeDecodeError, execcodemodule, b'\xff', code) + # CRASHES execcodemodule(NULL, code) + # CRASHES execcodemodule(name, NULL) + + def test_executecodemoduleex(self): + # Test PyImport_ExecCodeModuleEx() + execcodemoduleex = _testlimitedcapi.PyImport_ExecCodeModuleEx + + # Test NULL path (it should not crash) + self.check_executecodemodule(execcodemoduleex, NULL) + + # Test non-NULL path + pathname = b'pathname' + origin = self.check_executecodemodule(execcodemoduleex, pathname) + self.assertEqual(origin, os.path.abspath(os.fsdecode(pathname))) + + pathname = os_helper.TESTFN_UNDECODABLE + if pathname: + origin = self.check_executecodemodule(execcodemoduleex, pathname) + self.assertEqual(origin, os.path.abspath(os.fsdecode(pathname))) + + code = compile('attr = 1', '', 'exec') + self.assertRaises(UnicodeDecodeError, execcodemoduleex, b'\xff', code, NULL) + # CRASHES execcodemoduleex(NULL, code, NULL) + # CRASHES execcodemoduleex(name, NULL, NULL) + + def check_executecode_pathnames(self, execute_code_func, object=False): + # Test non-NULL pathname and NULL cpathname + + # Test NULL paths (it should not crash) + self.check_executecodemodule(execute_code_func, NULL, NULL) + + pathname = 'pathname' + origin = self.check_executecodemodule(execute_code_func, pathname, NULL) + self.assertEqual(origin, os.path.abspath(os.fsdecode(pathname))) + origin = self.check_executecodemodule(execute_code_func, NULL, pathname) + if not object: + self.assertEqual(origin, os.path.abspath(os.fsdecode(pathname))) + + pathname = os_helper.TESTFN_UNDECODABLE + if pathname: + if object: + pathname = os.fsdecode(pathname) + origin = self.check_executecodemodule(execute_code_func, pathname, NULL) + self.assertEqual(origin, os.path.abspath(os.fsdecode(pathname))) + self.check_executecodemodule(execute_code_func, NULL, pathname) + + # Test NULL pathname and non-NULL cpathname + try: + pyc_filename = importlib.util.cache_from_source(__file__) + except NotImplementedError: + return + py_filename = importlib.util.source_from_cache(pyc_filename) + origin = self.check_executecodemodule(execute_code_func, NULL, pyc_filename) + if not object: + self.assertEqual(origin, py_filename) + + def test_executecodemodulewithpathnames(self): + # Test PyImport_ExecCodeModuleWithPathnames() + execute_code_func = _testlimitedcapi.PyImport_ExecCodeModuleWithPathnames + self.check_executecode_pathnames(execute_code_func) + + code = compile('attr = 1', '', 'exec') + self.assertRaises(UnicodeDecodeError, execute_code_func, b'\xff', code, NULL, NULL) + # CRASHES execute_code_func(NULL, code, NULL, NULL) + # CRASHES execute_code_func(name, NULL, NULL, NULL) + + def test_executecodemoduleobject(self): + # Test PyImport_ExecCodeModuleObject() + execute_code_func = _testlimitedcapi.PyImport_ExecCodeModuleObject + self.check_executecode_pathnames(execute_code_func, object=True) + + code = compile('attr = 1', '', 'exec') + self.assertRaises(TypeError, execute_code_func, [], code, NULL, NULL) + nonstring = tuple(['hashable non-string']) + self.assertRaises(AttributeError, execute_code_func, nonstring, code, NULL, NULL) + sys.modules.pop(nonstring, None) + # CRASHES execute_code_func(NULL, code, NULL, NULL) + # CRASHES execute_code_func(name, NULL, NULL, NULL) + + def check_importmoduleattr(self, importmoduleattr): + self.assertIs(importmoduleattr('sys', 'argv'), sys.argv) + self.assertIs(importmoduleattr('types', 'ModuleType'), types.ModuleType) + + # module name containing a dot + attr = importmoduleattr('email.message', 'Message') + from email.message import Message + self.assertIs(attr, Message) + + with self.assertRaises(ImportError): + # nonexistent module + importmoduleattr('nonexistentmodule', 'attr') + with self.assertRaises(AttributeError): + # nonexistent attribute + importmoduleattr('sys', 'nonexistentattr') + with self.assertRaises(AttributeError): + # attribute name containing a dot + importmoduleattr('sys', 'implementation.name') + + def test_importmoduleattr(self): + # Test PyImport_ImportModuleAttr() + importmoduleattr = _testcapi.PyImport_ImportModuleAttr + self.check_importmoduleattr(importmoduleattr) + + # Invalid module name type + for mod_name in (object(), 123, b'bytes'): + with self.subTest(mod_name=mod_name): + with self.assertRaises(TypeError): + importmoduleattr(mod_name, "attr") + + # Invalid attribute name type + for attr_name in (object(), 123, b'bytes'): + with self.subTest(attr_name=attr_name): + with self.assertRaises(TypeError): + importmoduleattr("sys", attr_name) + + with self.assertRaises(SystemError): + importmoduleattr(NULL, "argv") + # CRASHES importmoduleattr("sys", NULL) + + def test_importmoduleattrstring(self): + # Test PyImport_ImportModuleAttrString() + importmoduleattr = _testcapi.PyImport_ImportModuleAttrString + self.check_importmoduleattr(importmoduleattr) + + with self.assertRaises(UnicodeDecodeError): + importmoduleattr(b"sys\xff", "argv") + with self.assertRaises(UnicodeDecodeError): + importmoduleattr("sys", b"argv\xff") + + # CRASHES importmoduleattr(NULL, "argv") + # CRASHES importmoduleattr("sys", NULL) + + # TODO: test PyImport_GetImporter() + # TODO: test PyImport_ReloadModule() + # TODO: test PyImport_ExtendInittab() + # PyImport_AppendInittab() is tested by test_embed + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_list.py b/Lib/test/test_capi/test_list.py new file mode 100644 index 00000000000..b95b8ba960b --- /dev/null +++ b/Lib/test/test_capi/test_list.py @@ -0,0 +1,359 @@ +import unittest +from test.support import import_helper +from collections import UserList +_testcapi = import_helper.import_module('_testcapi') +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') + +NULL = None +PY_SSIZE_T_MIN = _testcapi.PY_SSIZE_T_MIN +PY_SSIZE_T_MAX = _testcapi.PY_SSIZE_T_MAX + +class ListSubclass(list): + pass + + +class DelAppend: + def __init__(self, lst, item): + self.lst = lst + self.item = item + + def __del__(self): + self.lst.append(self.item) + + +class CAPITest(unittest.TestCase): + def test_check(self): + # Test PyList_Check() + check = _testlimitedcapi.list_check + self.assertTrue(check([1, 2])) + self.assertTrue(check([])) + self.assertTrue(check(ListSubclass([1, 2]))) + self.assertFalse(check({1: 2})) + self.assertFalse(check((1, 2))) + self.assertFalse(check(42)) + self.assertFalse(check(object())) + + # CRASHES check(NULL) + + + def test_list_check_exact(self): + # Test PyList_CheckExact() + check = _testlimitedcapi.list_check_exact + self.assertTrue(check([1])) + self.assertTrue(check([])) + self.assertFalse(check(ListSubclass([1]))) + self.assertFalse(check(UserList([1, 2]))) + self.assertFalse(check({1: 2})) + self.assertFalse(check(object())) + + # CRASHES check(NULL) + + def test_list_new(self): + # Test PyList_New() + list_new = _testlimitedcapi.list_new + lst = list_new(0) + self.assertEqual(lst, []) + self.assertIs(type(lst), list) + lst2 = list_new(0) + self.assertIsNot(lst2, lst) + self.assertRaises(SystemError, list_new, NULL) + self.assertRaises(SystemError, list_new, -1) + + def test_list_size(self): + # Test PyList_Size() + size = _testlimitedcapi.list_size + self.assertEqual(size([]), 0) + self.assertEqual(size([1, 2]), 2) + self.assertEqual(size(ListSubclass([1, 2])), 2) + self.assertRaises(SystemError, size, UserList()) + self.assertRaises(SystemError, size, {}) + self.assertRaises(SystemError, size, 23) + self.assertRaises(SystemError, size, object()) + # CRASHES size(NULL) + + def test_list_get_size(self): + # Test PyList_GET_SIZE() + size = _testcapi.list_get_size + self.assertEqual(size([]), 0) + self.assertEqual(size([1, 2]), 2) + self.assertEqual(size(ListSubclass([1, 2])), 2) + # CRASHES size(object()) + # CRASHES size(23) + # CRASHES size({}) + # CRASHES size(UserList()) + # CRASHES size(NULL) + + def check_list_get_item(self, getitem, exctype): + # Common test cases for PyList_GetItem() and PyList_GetItemRef() + lst = [1, 2, 3] + self.assertEqual(getitem(lst, 0), 1) + self.assertEqual(getitem(lst, 2), 3) + self.assertRaises(IndexError, getitem, lst, 3) + self.assertRaises(IndexError, getitem, lst, -1) + self.assertRaises(IndexError, getitem, lst, PY_SSIZE_T_MIN) + self.assertRaises(IndexError, getitem, lst, PY_SSIZE_T_MAX) + self.assertRaises(exctype, getitem, 42, 1) + self.assertRaises(exctype, getitem, (1, 2, 3), 1) + self.assertRaises(exctype, getitem, {1: 2}, 1) + # CRASHES getitem(NULL, 1) + + def test_list_getitem(self): + # Test PyList_GetItem() + self.check_list_get_item(_testlimitedcapi.list_getitem, SystemError) + + def test_list_get_item_ref(self): + # Test PyList_GetItemRef() + self.check_list_get_item(_testlimitedcapi.list_get_item_ref, TypeError) + + def test_list_get_item(self): + # Test PyList_GET_ITEM() + get_item = _testcapi.list_get_item + lst = [1, 2, [1, 2, 3]] + self.assertEqual(get_item(lst, 0), 1) + self.assertEqual(get_item(lst, 2), [1, 2, 3]) + + # CRASHES for out of index: get_item(lst, 3) + # CRASHES for get_item(lst, PY_SSIZE_T_MIN) + # CRASHES for get_item(lst, PY_SSIZE_T_MAX) + # CRASHES get_item(21, 2) + # CRASHES get_item(NULL, 1) + + def test_list_setitem(self): + # Test PyList_SetItem() + setitem = _testlimitedcapi.list_setitem + lst = [1, 2, 3] + setitem(lst, 0, 10) + self.assertEqual(lst, [10, 2, 3]) + setitem(lst, 2, 12) + self.assertEqual(lst, [10, 2, 12]) + self.assertRaises(IndexError, setitem, lst, 3 , 5) + self.assertRaises(IndexError, setitem, lst, -1, 5) + self.assertRaises(IndexError, setitem, lst, PY_SSIZE_T_MIN, 5) + self.assertRaises(IndexError, setitem, lst, PY_SSIZE_T_MAX, 5) + self.assertRaises(SystemError, setitem, (1, 2, 3), 1, 5) + self.assertRaises(SystemError, setitem, {1: 2}, 1, 5) + + # CRASHES setitem(NULL, 'a', 5) + + def test_list_set_item(self): + # Test PyList_SET_ITEM() + set_item = _testcapi.list_set_item + lst = [1, 2, 3] + set_item(lst, 1, 10) + set_item(lst, 2, [1, 2, 3]) + self.assertEqual(lst, [1, 10, [1, 2, 3]]) + + # CRASHES for set_item([1], -1, 5) + # CRASHES for set_item([1], PY_SSIZE_T_MIN, 5) + # CRASHES for set_item([1], PY_SSIZE_T_MAX, 5) + # CRASHES for set_item([], 0, 1) + # CRASHES for set_item(NULL, 0, 1) + + + def test_list_insert(self): + # Test PyList_Insert() + insert = _testlimitedcapi.list_insert + lst = [1, 2, 3] + insert(lst, 0, 23) + self.assertEqual(lst, [23, 1, 2, 3]) + insert(lst, -1, 22) + self.assertEqual(lst, [23, 1, 2, 22, 3]) + insert(lst, PY_SSIZE_T_MIN, 1) + self.assertEqual(lst[0], 1) + insert(lst, len(lst), 123) + self.assertEqual(lst[-1], 123) + insert(lst, len(lst)-1, 124) + self.assertEqual(lst[-2], 124) + insert(lst, PY_SSIZE_T_MAX, 223) + self.assertEqual(lst[-1], 223) + + self.assertRaises(SystemError, insert, (1, 2, 3), 1, 5) + self.assertRaises(SystemError, insert, {1: 2}, 1, 5) + + # CRASHES insert(NULL, 1, 5) + + def test_list_append(self): + # Test PyList_Append() + append = _testlimitedcapi.list_append + lst = [1, 2, 3] + append(lst, 10) + self.assertEqual(lst, [1, 2, 3, 10]) + append(lst, [4, 5]) + self.assertEqual(lst, [1, 2, 3, 10, [4, 5]]) + self.assertRaises(SystemError, append, lst, NULL) + self.assertRaises(SystemError, append, (), 0) + self.assertRaises(SystemError, append, 42, 0) + # CRASHES append(NULL, 0) + + def test_list_getslice(self): + # Test PyList_GetSlice() + getslice = _testlimitedcapi.list_getslice + lst = [1, 2, 3] + + # empty + self.assertEqual(getslice(lst, PY_SSIZE_T_MIN, 0), []) + self.assertEqual(getslice(lst, -1, 0), []) + self.assertEqual(getslice(lst, 3, PY_SSIZE_T_MAX), []) + + # slice + self.assertEqual(getslice(lst, 1, 3), [2, 3]) + + # whole + self.assertEqual(getslice(lst, 0, len(lst)), lst) + self.assertEqual(getslice(lst, 0, 100), lst) + self.assertEqual(getslice(lst, -100, 100), lst) + + self.assertRaises(SystemError, getslice, (1, 2, 3), 0, 0) + self.assertRaises(SystemError, getslice, 'abc', 0, 0) + self.assertRaises(SystemError, getslice, 42, 0, 0) + + # CRASHES getslice(NULL, 0, 0) + + def test_list_setslice(self): + # Test PyList_SetSlice() + list_setslice = _testlimitedcapi.list_setslice + def set_slice(lst, low, high, value): + lst = lst.copy() + self.assertEqual(list_setslice(lst, low, high, value), 0) + return lst + + # insert items + self.assertEqual(set_slice([], 0, 0, list("abc")), list("abc")) + self.assertEqual(set_slice([], PY_SSIZE_T_MIN, PY_SSIZE_T_MIN, list("abc")), list("abc")) + self.assertEqual(set_slice([], PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, list("abc")), list("abc")) + lst = list("abc") + self.assertEqual(set_slice(lst, 0, 0, ["X"]), list("Xabc")) + self.assertEqual(set_slice(lst, 1, 1, list("XY")), list("aXYbc")) + self.assertEqual(set_slice(lst, len(lst), len(lst), ["X"]), list("abcX")) + # self.assertEqual(set_slice(lst, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, ["X"]), list("abcX")) + + # replace items + lst = list("abc") + self.assertEqual(set_slice(lst, -100, 1, list("X")), list("Xbc")) + self.assertEqual(set_slice(lst, 1, 2, list("X")), list("aXc")) + self.assertEqual(set_slice(lst, 1, 3, list("XY")), list("aXY")) + self.assertEqual(set_slice(lst, 0, 3, list("XYZ")), list("XYZ")) + + # delete items + lst = list("abcdef") + self.assertEqual(set_slice(lst, 0, len(lst), []), []) + self.assertEqual(set_slice(lst, -100, 100, []), []) + self.assertEqual(set_slice(lst, 1, 5, []), list("af")) + self.assertEqual(set_slice(lst, 3, len(lst), []), list("abc")) + + # delete items with NULL + lst = list("abcdef") + self.assertEqual(set_slice(lst, 0, len(lst), NULL), []) + self.assertEqual(set_slice(lst, 3, len(lst), NULL), list("abc")) + + self.assertRaises(SystemError, list_setslice, (), 0, 0, []) + self.assertRaises(SystemError, list_setslice, 42, 0, 0, []) + + # Item finalizer modify the list (clear the list) + lst = [] + lst.append(DelAppend(lst, 'zombie')) + self.assertEqual(list_setslice(lst, 0, len(lst), NULL), 0) + self.assertEqual(lst, ['zombie']) + + # Item finalizer modify the list (remove an list item) + lst = [] + lst.append(DelAppend(lst, 'zombie')) + lst.extend("abc") + self.assertEqual(list_setslice(lst, 0, 1, NULL), 0) + self.assertEqual(lst, ['a', 'b', 'c', 'zombie']) + + # CRASHES setslice(NULL, 0, 0, []) + + def test_list_sort(self): + # Test PyList_Sort() + sort = _testlimitedcapi.list_sort + lst = [4, 6, 7, 3, 1, 5, 9, 2, 0, 8] + sort(lst) + self.assertEqual(lst, list(range(10))) + + lst2 = ListSubclass([4, 6, 7, 3, 1, 5, 9, 2, 0, 8]) + sort(lst2) + self.assertEqual(lst2, list(range(10))) + + self.assertRaises(SystemError, sort, ()) + self.assertRaises(SystemError, sort, object()) + self.assertRaises(SystemError, sort, NULL) + + + def test_list_reverse(self): + # Test PyList_Reverse() + reverse = _testlimitedcapi.list_reverse + def list_reverse(lst): + self.assertEqual(reverse(lst), 0) + return lst + + self.assertEqual(list_reverse([]), []) + self.assertEqual(list_reverse([2, 5, 10]), [10, 5, 2]) + self.assertEqual(list_reverse(list_reverse([2, 5, 10])), [2, 5, 10]) + + self.assertRaises(SystemError, reverse, ()) + self.assertRaises(SystemError, reverse, object()) + self.assertRaises(SystemError, reverse, NULL) + + def test_list_astuple(self): + # Test PyList_AsTuple() + astuple = _testlimitedcapi.list_astuple + self.assertEqual(astuple([]), ()) + self.assertEqual(astuple([[]]), ([],)) + self.assertEqual(astuple([2, 5, 10]), (2, 5, 10)) + + self.assertRaises(SystemError, astuple, ()) + self.assertRaises(SystemError, astuple, object()) + self.assertRaises(SystemError, astuple, NULL) + + def test_list_clear(self): + # Test PyList_Clear() + list_clear = _testcapi.list_clear + + lst = [1, 2, 3] + self.assertEqual(list_clear(lst), 0) + self.assertEqual(lst, []) + + lst = [] + self.assertEqual(list_clear(lst), 0) + self.assertEqual(lst, []) + + self.assertRaises(SystemError, list_clear, ()) + self.assertRaises(SystemError, list_clear, object()) + + # Item finalizer modify the list + lst = [] + lst.append(DelAppend(lst, 'zombie')) + list_clear(lst) + self.assertEqual(lst, ['zombie']) + + # CRASHES list_clear(NULL) + + def test_list_extend(self): + # Test PyList_Extend() + list_extend = _testcapi.list_extend + + for other_type in (list, tuple, str, iter): + lst = list("ab") + arg = other_type("def") + self.assertEqual(list_extend(lst, arg), 0) + self.assertEqual(lst, list("abdef")) + + # PyList_Extend(lst, lst) + lst = list("abc") + self.assertEqual(list_extend(lst, lst), 0) + self.assertEqual(lst, list("abcabc")) + + self.assertRaises(TypeError, list_extend, [], object()) + self.assertRaises(SystemError, list_extend, (), list("abc")) + + # CRASHES list_extend(NULL, []) + # CRASHES list_extend([], NULL) + + def test_uninitialized_list_repr(self): + lst = _testlimitedcapi.list_new(3) + self.assertEqual(repr(lst), '[, , ]') + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_long.py b/Lib/test/test_capi/test_long.py new file mode 100644 index 00000000000..d1467caf688 --- /dev/null +++ b/Lib/test/test_capi/test_long.py @@ -0,0 +1,828 @@ +import unittest +import sys +import test.support as support + +from test.support import import_helper + +# Skip this test if the _testcapi and _testlimitedcapi modules isn't available. +_testcapi = import_helper.import_module('_testcapi') +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') + +NULL = None + + +class IntSubclass(int): + pass + +class Index: + def __init__(self, value): + self.value = value + + def __index__(self): + return self.value + +# use __index__(), not __int__() +class MyIndexAndInt: + def __index__(self): + return 10 + def __int__(self): + return 22 + + +class LongTests(unittest.TestCase): + + def test_compact(self): + for n in { + # Edge cases + *(2**n for n in range(66)), + *(-2**n for n in range(66)), + *(2**n - 1 for n in range(66)), + *(-2**n + 1 for n in range(66)), + # Essentially random + *(37**n for n in range(14)), + *(-37**n for n in range(14)), + }: + with self.subTest(n=n): + is_compact, value = _testcapi.call_long_compact_api(n) + if is_compact: + self.assertEqual(n, value) + + def test_compact_known(self): + # Sanity-check some implementation details (we don't guarantee + # that these are/aren't compact) + self.assertEqual(_testcapi.call_long_compact_api(-1), (True, -1)) + self.assertEqual(_testcapi.call_long_compact_api(0), (True, 0)) + self.assertEqual(_testcapi.call_long_compact_api(256), (True, 256)) + self.assertEqual(_testcapi.call_long_compact_api(sys.maxsize), + (False, -1)) + + def test_long_check(self): + # Test PyLong_Check() + check = _testlimitedcapi.pylong_check + self.assertTrue(check(1)) + self.assertTrue(check(123456789012345678901234567890)) + self.assertTrue(check(-1)) + self.assertTrue(check(True)) + self.assertTrue(check(IntSubclass(1))) + self.assertFalse(check(1.0)) + self.assertFalse(check(object())) + # CRASHES check(NULL) + + def test_long_checkexact(self): + # Test PyLong_CheckExact() + check = _testlimitedcapi.pylong_checkexact + self.assertTrue(check(1)) + self.assertTrue(check(123456789012345678901234567890)) + self.assertTrue(check(-1)) + self.assertFalse(check(True)) + self.assertFalse(check(IntSubclass(1))) + self.assertFalse(check(1.0)) + self.assertFalse(check(object())) + # CRASHES check(NULL) + + def test_long_fromdouble(self): + # Test PyLong_FromDouble() + fromdouble = _testlimitedcapi.pylong_fromdouble + float_max = sys.float_info.max + for value in (5.0, 5.1, 5.9, -5.1, -5.9, 0.0, -0.0, float_max, -float_max): + with self.subTest(value=value): + self.assertEqual(fromdouble(value), int(value)) + self.assertRaises(OverflowError, fromdouble, float('inf')) + self.assertRaises(OverflowError, fromdouble, float('-inf')) + self.assertRaises(ValueError, fromdouble, float('nan')) + + def test_long_fromvoidptr(self): + # Test PyLong_FromVoidPtr() + fromvoidptr = _testlimitedcapi.pylong_fromvoidptr + obj = object() + x = fromvoidptr(obj) + y = fromvoidptr(NULL) + self.assertIsInstance(x, int) + self.assertGreaterEqual(x, 0) + self.assertIsInstance(y, int) + self.assertEqual(y, 0) + self.assertNotEqual(x, y) + + def test_long_fromstring(self): + # Test PyLong_FromString() + fromstring = _testlimitedcapi.pylong_fromstring + self.assertEqual(fromstring(b'123', 10), (123, 3)) + self.assertEqual(fromstring(b'cafe', 16), (0xcafe, 4)) + self.assertEqual(fromstring(b'xyz', 36), (44027, 3)) + self.assertEqual(fromstring(b'123', 0), (123, 3)) + self.assertEqual(fromstring(b'0xcafe', 0), (0xcafe, 6)) + self.assertRaises(ValueError, fromstring, b'cafe', 0) + self.assertEqual(fromstring(b'-123', 10), (-123, 4)) + self.assertEqual(fromstring(b' -123 ', 10), (-123, 6)) + self.assertEqual(fromstring(b'1_23', 10), (123, 4)) + self.assertRaises(ValueError, fromstring, b'- 123', 10) + self.assertRaises(ValueError, fromstring, b'', 10) + + self.assertRaises(ValueError, fromstring, b'123', 1) + self.assertRaises(ValueError, fromstring, b'123', -1) + self.assertRaises(ValueError, fromstring, b'123', 37) + + self.assertRaises(ValueError, fromstring, '١٢٣٤٥٦٧٨٩٠'.encode(), 0) + self.assertRaises(ValueError, fromstring, '١٢٣٤٥٦٧٨٩٠'.encode(), 16) + + self.assertEqual(fromstring(b'123\x00', 0), (123, 3)) + self.assertEqual(fromstring(b'123\x00456', 0), (123, 3)) + self.assertEqual(fromstring(b'123\x00', 16), (0x123, 3)) + self.assertEqual(fromstring(b'123\x00456', 16), (0x123, 3)) + + # CRASHES fromstring(NULL, 0) + # CRASHES fromstring(NULL, 16) + + def test_long_fromunicodeobject(self): + # Test PyLong_FromUnicodeObject() + fromunicodeobject = _testcapi.pylong_fromunicodeobject + self.assertEqual(fromunicodeobject('123', 10), 123) + self.assertEqual(fromunicodeobject('cafe', 16), 0xcafe) + self.assertEqual(fromunicodeobject('xyz', 36), 44027) + self.assertEqual(fromunicodeobject('123', 0), 123) + self.assertEqual(fromunicodeobject('0xcafe', 0), 0xcafe) + self.assertRaises(ValueError, fromunicodeobject, 'cafe', 0) + self.assertEqual(fromunicodeobject('-123', 10), -123) + self.assertEqual(fromunicodeobject(' -123 ', 10), -123) + self.assertEqual(fromunicodeobject('1_23', 10), 123) + self.assertRaises(ValueError, fromunicodeobject, '- 123', 10) + self.assertRaises(ValueError, fromunicodeobject, '', 10) + + self.assertRaises(ValueError, fromunicodeobject, '123', 1) + self.assertRaises(ValueError, fromunicodeobject, '123', -1) + self.assertRaises(ValueError, fromunicodeobject, '123', 37) + + self.assertEqual(fromunicodeobject('١٢٣٤٥٦٧٨٩٠', 0), 1234567890) + self.assertEqual(fromunicodeobject('١٢٣٤٥٦٧٨٩٠', 16), 0x1234567890) + + self.assertRaises(ValueError, fromunicodeobject, '123\x00', 0) + self.assertRaises(ValueError, fromunicodeobject, '123\x00456', 0) + self.assertRaises(ValueError, fromunicodeobject, '123\x00', 16) + self.assertRaises(ValueError, fromunicodeobject, '123\x00456', 16) + + # CRASHES fromunicodeobject(NULL, 0) + # CRASHES fromunicodeobject(NULL, 16) + + def check_long_asint(self, func, min_val, max_val, *, + use_index=True, + mask=False, + negative_value_error=OverflowError): + # round trip (object -> C integer -> object) + values = (0, 1, 512, 1234, max_val) + if min_val < 0: + values += (-1, -512, -1234, min_val) + for value in values: + with self.subTest(value=value): + self.assertEqual(func(value), value) + self.assertEqual(func(IntSubclass(value)), value) + if use_index: + self.assertEqual(func(Index(value)), value) + + if use_index: + self.assertEqual(func(MyIndexAndInt()), 10) + else: + self.assertRaises(TypeError, func, Index(42)) + self.assertRaises(TypeError, func, MyIndexAndInt()) + + if mask: + self.assertEqual(func(min_val - 1), max_val) + self.assertEqual(func(max_val + 1), min_val) + self.assertEqual(func(-1 << 1000), 0) + self.assertEqual(func(1 << 1000), 0) + else: + self.assertRaises(negative_value_error, func, min_val - 1) + self.assertRaises(negative_value_error, func, -1 << 1000) + self.assertRaises(OverflowError, func, max_val + 1) + self.assertRaises(OverflowError, func, 1 << 1000) + self.assertRaises(TypeError, func, 1.0) + self.assertRaises(TypeError, func, b'2') + self.assertRaises(TypeError, func, '3') + self.assertRaises(SystemError, func, NULL) + + def check_long_asintandoverflow(self, func, min_val, max_val): + # round trip (object -> C integer -> object) + for value in (min_val, max_val, -1, 0, 1, 1234): + with self.subTest(value=value): + self.assertEqual(func(value), (value, 0)) + self.assertEqual(func(IntSubclass(value)), (value, 0)) + self.assertEqual(func(Index(value)), (value, 0)) + + self.assertEqual(func(MyIndexAndInt()), (10, 0)) + + self.assertEqual(func(min_val - 1), (-1, -1)) + self.assertEqual(func(max_val + 1), (-1, +1)) + self.assertRaises(SystemError, func, None) + self.assertRaises(TypeError, func, 1.0) + + def test_long_asint(self): + # Test PyLong_AsInt() + PyLong_AsInt = _testlimitedcapi.PyLong_AsInt + from _testcapi import INT_MIN, INT_MAX + self.check_long_asint(PyLong_AsInt, INT_MIN, INT_MAX) + + def test_long_aslong(self): + # Test PyLong_AsLong() and PyLong_FromLong() + aslong = _testlimitedcapi.pylong_aslong + from _testcapi import LONG_MIN, LONG_MAX + self.check_long_asint(aslong, LONG_MIN, LONG_MAX) + + def test_long_aslongandoverflow(self): + # Test PyLong_AsLongAndOverflow() + aslongandoverflow = _testlimitedcapi.pylong_aslongandoverflow + from _testcapi import LONG_MIN, LONG_MAX + self.check_long_asintandoverflow(aslongandoverflow, LONG_MIN, LONG_MAX) + + def test_long_asunsignedlong(self): + # Test PyLong_AsUnsignedLong() and PyLong_FromUnsignedLong() + asunsignedlong = _testlimitedcapi.pylong_asunsignedlong + from _testcapi import ULONG_MAX + self.check_long_asint(asunsignedlong, 0, ULONG_MAX, + use_index=False) + + def test_long_asunsignedlongmask(self): + # Test PyLong_AsUnsignedLongMask() + asunsignedlongmask = _testlimitedcapi.pylong_asunsignedlongmask + from _testcapi import ULONG_MAX + self.check_long_asint(asunsignedlongmask, 0, ULONG_MAX, mask=True) + + def test_long_aslonglong(self): + # Test PyLong_AsLongLong() and PyLong_FromLongLong() + aslonglong = _testlimitedcapi.pylong_aslonglong + from _testcapi import LLONG_MIN, LLONG_MAX + self.check_long_asint(aslonglong, LLONG_MIN, LLONG_MAX) + + def test_long_aslonglongandoverflow(self): + # Test PyLong_AsLongLongAndOverflow() + aslonglongandoverflow = _testlimitedcapi.pylong_aslonglongandoverflow + from _testcapi import LLONG_MIN, LLONG_MAX + self.check_long_asintandoverflow(aslonglongandoverflow, LLONG_MIN, LLONG_MAX) + + def test_long_asunsignedlonglong(self): + # Test PyLong_AsUnsignedLongLong() and PyLong_FromUnsignedLongLong() + asunsignedlonglong = _testlimitedcapi.pylong_asunsignedlonglong + from _testcapi import ULLONG_MAX + self.check_long_asint(asunsignedlonglong, 0, ULLONG_MAX, use_index=False) + + def test_long_asunsignedlonglongmask(self): + # Test PyLong_AsUnsignedLongLongMask() + asunsignedlonglongmask = _testlimitedcapi.pylong_asunsignedlonglongmask + from _testcapi import ULLONG_MAX + self.check_long_asint(asunsignedlonglongmask, 0, ULLONG_MAX, mask=True) + + def test_long_as_ssize_t(self): + # Test PyLong_AsSsize_t() and PyLong_FromSsize_t() + as_ssize_t = _testlimitedcapi.pylong_as_ssize_t + from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX + self.check_long_asint(as_ssize_t, PY_SSIZE_T_MIN, PY_SSIZE_T_MAX, + use_index=False) + + def test_long_as_size_t(self): + # Test PyLong_AsSize_t() and PyLong_FromSize_t() + as_size_t = _testlimitedcapi.pylong_as_size_t + from _testcapi import SIZE_MAX + self.check_long_asint(as_size_t, 0, SIZE_MAX, use_index=False) + + def test_long_asdouble(self): + # Test PyLong_AsDouble() + asdouble = _testlimitedcapi.pylong_asdouble + MAX = int(sys.float_info.max) + for value in (-MAX, MAX, -1, 0, 1, 1234): + with self.subTest(value=value): + self.assertEqual(asdouble(value), float(value)) + self.assertIsInstance(asdouble(value), float) + + self.assertEqual(asdouble(IntSubclass(42)), 42.0) + self.assertRaises(TypeError, asdouble, Index(42)) + self.assertRaises(TypeError, asdouble, MyIndexAndInt()) + + self.assertRaises(OverflowError, asdouble, 2 * MAX) + self.assertRaises(OverflowError, asdouble, -2 * MAX) + self.assertRaises(TypeError, asdouble, 1.0) + self.assertRaises(TypeError, asdouble, b'2') + self.assertRaises(TypeError, asdouble, '3') + self.assertRaises(SystemError, asdouble, NULL) + + def test_long_asvoidptr(self): + # Test PyLong_AsVoidPtr() + fromvoidptr = _testlimitedcapi.pylong_fromvoidptr + asvoidptr = _testlimitedcapi.pylong_asvoidptr + obj = object() + x = fromvoidptr(obj) + y = fromvoidptr(NULL) + self.assertIs(asvoidptr(x), obj) + self.assertIs(asvoidptr(y), NULL) + self.assertIs(asvoidptr(IntSubclass(x)), obj) + + # negative values + M = (1 << _testcapi.SIZEOF_VOID_P * 8) + if x >= M//2: + self.assertIs(asvoidptr(x - M), obj) + if y >= M//2: + self.assertIs(asvoidptr(y - M), NULL) + + self.assertRaises(TypeError, asvoidptr, Index(x)) + self.assertRaises(TypeError, asvoidptr, object()) + self.assertRaises(OverflowError, asvoidptr, 2**1000) + self.assertRaises(OverflowError, asvoidptr, -2**1000) + # CRASHES asvoidptr(NULL) + + def _test_long_aspid(self, aspid): + # Test PyLong_AsPid() + from _testcapi import SIZEOF_PID_T + bits = 8 * SIZEOF_PID_T + PID_T_MIN = -2**(bits-1) + PID_T_MAX = 2**(bits-1) - 1 + self.check_long_asint(aspid, PID_T_MIN, PID_T_MAX) + + def test_long_aspid(self): + self._test_long_aspid(_testcapi.pylong_aspid) + + def test_long_aspid_limited(self): + self._test_long_aspid(_testlimitedcapi.pylong_aspid) + + @support.bigmemtest(2**32, memuse=0.35) + def test_long_asnativebytes_huge(self, size): + asnativebytes = _testcapi.pylong_asnativebytes + v = 1 << size + buffer = bytearray(size * 2 // 15 + 10) + r = asnativebytes(v, buffer, 0, -1) + self.assertEqual(r, size // 8 + 1) + self.assertEqual(buffer.count(0), len(buffer)) + r = asnativebytes(v, buffer, len(buffer), -1) + self.assertEqual(r, size // 8 + 1) + self.assertEqual(buffer.count(0), len(buffer) - 1) + + def test_long_asnativebytes(self): + import math + from _testcapi import ( + pylong_asnativebytes as asnativebytes, + SIZE_MAX, + ) + + # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot + SZ = int(math.ceil(math.log(SIZE_MAX + 1) / math.log(2)) / 8) + MAX_SSIZE = 2 ** (SZ * 8 - 1) - 1 + MAX_USIZE = 2 ** (SZ * 8) - 1 + if support.verbose: + print(f"SIZEOF_SIZE={SZ}\n{MAX_SSIZE=:016X}\n{MAX_USIZE=:016X}") + + # These tests check that the requested buffer size is correct. + # This matches our current implementation: We only specify that the + # return value is a size *sufficient* to hold the result when queried + # using n_bytes=0. If our implementation changes, feel free to update + # the expectations here -- or loosen them to be range checks. + # (i.e. 0 *could* be stored in 1 byte and 512 in 2) + for v, expect in [ + (0, SZ), + (512, SZ), + (-512, SZ), + (MAX_SSIZE, SZ), + (MAX_USIZE, SZ + 1), + (-MAX_SSIZE, SZ), + (-MAX_USIZE, SZ + 1), + (2**255-1, 32), + (-(2**255-1), 32), + (2**255, 33), + (-(2**255), 33), # if you ask, we'll say 33, but 32 would do + (2**256-1, 33), + (-(2**256-1), 33), + (2**256, 33), + (-(2**256), 33), + ]: + with self.subTest(f"sizeof-{v:X}"): + buffer = bytearray(b"\x5a") + self.assertEqual(expect, asnativebytes(v, buffer, 0, -1), + "PyLong_AsNativeBytes(v, , 0, -1)") + self.assertEqual(buffer, b"\x5a", + "buffer overwritten when it should not have been") + # Also check via the __index__ path. + # We pass Py_ASNATIVEBYTES_NATIVE_ENDIAN | ALLOW_INDEX + self.assertEqual(expect, asnativebytes(Index(v), buffer, 0, 3 | 16), + "PyLong_AsNativeBytes(Index(v), , 0, -1)") + self.assertEqual(buffer, b"\x5a", + "buffer overwritten when it should not have been") + + # Test that we populate n=2 bytes but do not overwrite more. + buffer = bytearray(b"\x99"*3) + self.assertEqual(2, asnativebytes(4, buffer, 2, 0), # BE + "PyLong_AsNativeBytes(v, <3 byte buffer>, 2, 0) // BE") + self.assertEqual(buffer, b"\x00\x04\x99") + self.assertEqual(2, asnativebytes(4, buffer, 2, 1), # LE + "PyLong_AsNativeBytes(v, <3 byte buffer>, 2, 1) // LE") + self.assertEqual(buffer, b"\x04\x00\x99") + + # We request as many bytes as `expect_be` contains, and always check + # the result (both big and little endian). We check the return value + # independently, since the buffer should always be filled correctly even + # if we need more bytes + for v, expect_be, expect_n in [ + (0, b'\x00', 1), + (0, b'\x00' * 2, 2), + (0, b'\x00' * 8, min(8, SZ)), + (1, b'\x01', 1), + (1, b'\x00' * 10 + b'\x01', min(11, SZ)), + (42, b'\x2a', 1), + (42, b'\x00' * 10 + b'\x2a', min(11, SZ)), + (-1, b'\xff', 1), + (-1, b'\xff' * 10, min(11, SZ)), + (-42, b'\xd6', 1), + (-42, b'\xff' * 10 + b'\xd6', min(11, SZ)), + # Extracts 255 into a single byte, but requests 2 + # (this is currently a special case, and "should" request SZ) + (255, b'\xff', 2), + (255, b'\x00\xff', 2), + (256, b'\x01\x00', 2), + (0x80, b'\x00' * 7 + b'\x80', min(8, SZ)), + # Extracts successfully (unsigned), but requests 9 bytes + (2**63, b'\x80' + b'\x00' * 7, 9), + (2**63, b'\x00\x80' + b'\x00' * 7, 9), + # Extracts into 8 bytes, but if you provide 9 we'll say 9 + (-2**63, b'\x80' + b'\x00' * 7, 8), + (-2**63, b'\xff\x80' + b'\x00' * 7, 9), + + (2**255-1, b'\x7f' + b'\xff' * 31, 32), + (-(2**255-1), b'\x80' + b'\x00' * 30 + b'\x01', 32), + # Request extra bytes, but result says we only needed 32 + (-(2**255-1), b'\xff\x80' + b'\x00' * 30 + b'\x01', 32), + (-(2**255-1), b'\xff\xff\x80' + b'\x00' * 30 + b'\x01', 32), + + # Extracting 256 bits of integer will request 33 bytes, but still + # copy as many bits as possible into the buffer. So we *can* copy + # into a 32-byte buffer, though negative number may be unrecoverable + (2**256-1, b'\xff' * 32, 33), + (2**256-1, b'\x00' + b'\xff' * 32, 33), + (-(2**256-1), b'\x00' * 31 + b'\x01', 33), + (-(2**256-1), b'\xff' + b'\x00' * 31 + b'\x01', 33), + (-(2**256-1), b'\xff\xff' + b'\x00' * 31 + b'\x01', 33), + # However, -2**255 precisely will extract into 32 bytes and return + # success. For bigger buffers, it will still succeed, but will + # return 33 + (-(2**255), b'\x80' + b'\x00' * 31, 32), + (-(2**255), b'\xff\x80' + b'\x00' * 31, 33), + + # The classic "Windows HRESULT as negative number" case + # HRESULT hr; + # PyLong_AsNativeBytes(<-2147467259>, &hr, sizeof(HRESULT), -1) + # assert(hr == E_FAIL) + (-2147467259, b'\x80\x00\x40\x05', 4), + ]: + with self.subTest(f"{v:X}-{len(expect_be)}bytes"): + n = len(expect_be) + # Fill the buffer with dummy data to ensure all bytes + # are overwritten. + buffer = bytearray(b"\xa5"*n) + expect_le = expect_be[::-1] + + self.assertEqual(expect_n, asnativebytes(v, buffer, n, 0), + f"PyLong_AsNativeBytes(v, buffer, {n}, )") + self.assertEqual(expect_be, buffer[:n], "") + self.assertEqual(expect_n, asnativebytes(v, buffer, n, 1), + f"PyLong_AsNativeBytes(v, buffer, {n}, )") + self.assertEqual(expect_le, buffer[:n], "") + + # Test cases that do not request size for a sign bit when we pass the + # Py_ASNATIVEBYTES_UNSIGNED_BUFFER flag + for v, expect_be, expect_n in [ + (255, b'\xff', 1), + # We pass a 2 byte buffer so it just uses the whole thing + (255, b'\x00\xff', 2), + + (2**63, b'\x80' + b'\x00' * 7, 8), + # We pass a 9 byte buffer so it uses the whole thing + (2**63, b'\x00\x80' + b'\x00' * 7, 9), + + (2**256-1, b'\xff' * 32, 32), + # We pass a 33 byte buffer so it uses the whole thing + (2**256-1, b'\x00' + b'\xff' * 32, 33), + ]: + with self.subTest(f"{v:X}-{len(expect_be)}bytes-unsigned"): + n = len(expect_be) + buffer = bytearray(b"\xa5"*n) + self.assertEqual(expect_n, asnativebytes(v, buffer, n, 4), + f"PyLong_AsNativeBytes(v, buffer, {n}, )") + self.assertEqual(expect_n, asnativebytes(v, buffer, n, 5), + f"PyLong_AsNativeBytes(v, buffer, {n}, )") + + # Ensure Py_ASNATIVEBYTES_REJECT_NEGATIVE raises on negative value + with self.assertRaises(ValueError): + asnativebytes(-1, buffer, 0, 8) + + # Ensure omitting Py_ASNATIVEBYTES_ALLOW_INDEX raises on __index__ value + with self.assertRaises(TypeError): + asnativebytes(Index(1), buffer, 0, -1) + with self.assertRaises(TypeError): + asnativebytes(Index(1), buffer, 0, 3) + + # Check a few error conditions. These are validated in code, but are + # unspecified in docs, so if we make changes to the implementation, it's + # fine to just update these tests rather than preserve the behaviour. + with self.assertRaises(TypeError): + asnativebytes('not a number', buffer, 0, -1) + + def test_long_asnativebytes_fuzz(self): + import math + from random import Random + from _testcapi import ( + pylong_asnativebytes as asnativebytes, + SIZE_MAX, + ) + + # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot + SZ = int(math.ceil(math.log(SIZE_MAX + 1) / math.log(2)) / 8) + + rng = Random() + # Allocate bigger buffer than actual values are going to be + buffer = bytearray(260) + + for _ in range(1000): + n = rng.randrange(1, 256) + bytes_be = bytes([ + # Ensure the most significant byte is nonzero + rng.randrange(1, 256), + *[rng.randrange(256) for _ in range(n - 1)] + ]) + bytes_le = bytes_be[::-1] + v = int.from_bytes(bytes_le, 'little') + + expect_1 = expect_2 = (SZ, n) + if bytes_be[0] & 0x80: + # All values are positive, so if MSB is set, expect extra bit + # when we request the size or have a large enough buffer + expect_1 = (SZ, n + 1) + # When passing Py_ASNATIVEBYTES_UNSIGNED_BUFFER, we expect the + # return to be exactly the right size. + expect_2 = (n,) + + try: + actual = asnativebytes(v, buffer, 0, -1) + self.assertIn(actual, expect_1) + + actual = asnativebytes(v, buffer, len(buffer), 0) + self.assertIn(actual, expect_1) + self.assertEqual(bytes_be, buffer[-n:]) + + actual = asnativebytes(v, buffer, len(buffer), 1) + self.assertIn(actual, expect_1) + self.assertEqual(bytes_le, buffer[:n]) + + actual = asnativebytes(v, buffer, n, 4) + self.assertIn(actual, expect_2, bytes_be.hex()) + actual = asnativebytes(v, buffer, n, 5) + self.assertIn(actual, expect_2, bytes_be.hex()) + except AssertionError as ex: + value_hex = ''.join(reversed([ + f'{b:02X}{"" if i % 8 else "_"}' + for i, b in enumerate(bytes_le, start=1) + ])).strip('_') + if support.verbose: + print() + print(n, 'bytes') + print('hex =', value_hex) + print('int =', v) + raise + raise AssertionError(f"Value: 0x{value_hex}") from ex + + def test_long_fromnativebytes(self): + import math + from _testcapi import ( + pylong_fromnativebytes as fromnativebytes, + SIZE_MAX, + ) + + # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot + SZ = int(math.ceil(math.log(SIZE_MAX + 1) / math.log(2)) / 8) + MAX_SSIZE = 2 ** (SZ * 8 - 1) - 1 + MAX_USIZE = 2 ** (SZ * 8) - 1 + + for v_be, expect_s, expect_u in [ + (b'\x00', 0, 0), + (b'\x01', 1, 1), + (b'\xff', -1, 255), + (b'\x00\xff', 255, 255), + (b'\xff\xff', -1, 65535), + ]: + with self.subTest(f"{expect_s}-{expect_u:X}-{len(v_be)}bytes"): + n = len(v_be) + v_le = v_be[::-1] + + self.assertEqual(expect_s, fromnativebytes(v_be, n, 0, 1), + f"PyLong_FromNativeBytes(buffer, {n}, )") + self.assertEqual(expect_s, fromnativebytes(v_le, n, 1, 1), + f"PyLong_FromNativeBytes(buffer, {n}, )") + self.assertEqual(expect_u, fromnativebytes(v_be, n, 0, 0), + f"PyLong_FromUnsignedNativeBytes(buffer, {n}, )") + self.assertEqual(expect_u, fromnativebytes(v_le, n, 1, 0), + f"PyLong_FromUnsignedNativeBytes(buffer, {n}, )") + + # Check native endian when the result would be the same either + # way and we can test it. + if v_be == v_le: + self.assertEqual(expect_s, fromnativebytes(v_be, n, -1, 1), + f"PyLong_FromNativeBytes(buffer, {n}, )") + self.assertEqual(expect_u, fromnativebytes(v_be, n, -1, 0), + f"PyLong_FromUnsignedNativeBytes(buffer, {n}, )") + + # Swap the unsigned request for tests and use the + # Py_ASNATIVEBYTES_UNSIGNED_BUFFER flag instead + self.assertEqual(expect_u, fromnativebytes(v_be, n, 4, 1), + f"PyLong_FromNativeBytes(buffer, {n}, )") + + def test_long_getsign(self): + # Test PyLong_GetSign() + getsign = _testcapi.pylong_getsign + self.assertEqual(getsign(1), 1) + self.assertEqual(getsign(123456), 1) + self.assertEqual(getsign(-2), -1) + self.assertEqual(getsign(0), 0) + self.assertEqual(getsign(True), 1) + self.assertEqual(getsign(IntSubclass(-11)), -1) + self.assertEqual(getsign(False), 0) + + self.assertRaises(TypeError, getsign, 1.0) + self.assertRaises(TypeError, getsign, Index(123)) + + # CRASHES getsign(NULL) + + def test_long_ispositive(self): + # Test PyLong_IsPositive() + ispositive = _testcapi.pylong_ispositive + self.assertEqual(ispositive(1), 1) + self.assertEqual(ispositive(123), 1) + self.assertEqual(ispositive(-1), 0) + self.assertEqual(ispositive(0), 0) + self.assertEqual(ispositive(True), 1) + self.assertEqual(ispositive(False), 0) + self.assertEqual(ispositive(IntSubclass(-1)), 0) + self.assertRaises(TypeError, ispositive, 1.0) + self.assertRaises(TypeError, ispositive, Index(123)) + + # CRASHES ispositive(NULL) + + def test_long_isnegative(self): + # Test PyLong_IsNegative() + isnegative = _testcapi.pylong_isnegative + self.assertEqual(isnegative(1), 0) + self.assertEqual(isnegative(123), 0) + self.assertEqual(isnegative(-1), 1) + self.assertEqual(isnegative(0), 0) + self.assertEqual(isnegative(True), 0) + self.assertEqual(isnegative(False), 0) + self.assertEqual(isnegative(IntSubclass(-1)), 1) + self.assertRaises(TypeError, isnegative, 1.0) + self.assertRaises(TypeError, isnegative, Index(123)) + + # CRASHES isnegative(NULL) + + def test_long_iszero(self): + # Test PyLong_IsZero() + iszero = _testcapi.pylong_iszero + self.assertEqual(iszero(1), 0) + self.assertEqual(iszero(-1), 0) + self.assertEqual(iszero(0), 1) + self.assertEqual(iszero(True), 0) + self.assertEqual(iszero(False), 1) + self.assertEqual(iszero(IntSubclass(-1)), 0) + self.assertEqual(iszero(IntSubclass(0)), 1) + self.assertRaises(TypeError, iszero, 1.0) + self.assertRaises(TypeError, iszero, Index(123)) + + # CRASHES iszero(NULL) + + def test_long_asint32(self): + # Test PyLong_AsInt32() and PyLong_FromInt32() + to_int32 = _testlimitedcapi.pylong_asint32 + from _testcapi import INT32_MIN, INT32_MAX + self.check_long_asint(to_int32, INT32_MIN, INT32_MAX) + + def test_long_asint64(self): + # Test PyLong_AsInt64() and PyLong_FromInt64() + as_int64 = _testlimitedcapi.pylong_asint64 + from _testcapi import INT64_MIN, INT64_MAX + self.check_long_asint(as_int64, INT64_MIN, INT64_MAX) + + def test_long_asuint32(self): + # Test PyLong_AsUInt32() and PyLong_FromUInt32() + as_uint32 = _testlimitedcapi.pylong_asuint32 + from _testcapi import UINT32_MAX + self.check_long_asint(as_uint32, 0, UINT32_MAX, + negative_value_error=ValueError) + + def test_long_asuint64(self): + # Test PyLong_AsUInt64() and PyLong_FromUInt64() + as_uint64 = _testlimitedcapi.pylong_asuint64 + from _testcapi import UINT64_MAX + self.check_long_asint(as_uint64, 0, UINT64_MAX, + negative_value_error=ValueError) + + def test_long_layout(self): + # Test PyLong_GetNativeLayout() + int_info = sys.int_info + layout = _testcapi.get_pylong_layout() + expected = { + 'bits_per_digit': int_info.bits_per_digit, + 'digit_size': int_info.sizeof_digit, + 'digits_order': -1, + 'digit_endianness': -1 if sys.byteorder == 'little' else 1, + } + self.assertEqual(layout, expected) + + def test_long_export(self): + # Test PyLong_Export() + layout = _testcapi.get_pylong_layout() + base = 2 ** layout['bits_per_digit'] + + pylong_export = _testcapi.pylong_export + + # value fits into int64_t + self.assertEqual(pylong_export(0), 0) + self.assertEqual(pylong_export(123), 123) + self.assertEqual(pylong_export(-123), -123) + self.assertEqual(pylong_export(IntSubclass(123)), 123) + + # use an array, doesn't fit into int64_t + self.assertEqual(pylong_export(base**10 * 2 + 1), + (0, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2])) + self.assertEqual(pylong_export(-(base**10 * 2 + 1)), + (1, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2])) + self.assertEqual(pylong_export(IntSubclass(base**10 * 2 + 1)), + (0, [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2])) + + self.assertRaises(TypeError, pylong_export, 1.0) + self.assertRaises(TypeError, pylong_export, 0+1j) + self.assertRaises(TypeError, pylong_export, "abc") + + def test_longwriter_create(self): + # Test PyLongWriter_Create() + layout = _testcapi.get_pylong_layout() + base = 2 ** layout['bits_per_digit'] + + pylongwriter_create = _testcapi.pylongwriter_create + self.assertRaises(ValueError, pylongwriter_create, 0, []) + self.assertRaises(ValueError, pylongwriter_create, -123, []) + self.assertEqual(pylongwriter_create(0, [0]), 0) + self.assertEqual(pylongwriter_create(0, [123]), 123) + self.assertEqual(pylongwriter_create(1, [123]), -123) + self.assertEqual(pylongwriter_create(1, [1, 2]), + -(base * 2 + 1)) + self.assertEqual(pylongwriter_create(0, [1, 2, 3]), + base**2 * 3 + base * 2 + 1) + max_digit = base - 1 + self.assertEqual(pylongwriter_create(0, [max_digit, max_digit, max_digit]), + base**2 * max_digit + base * max_digit + max_digit) + + # normalize + self.assertEqual(pylongwriter_create(0, [123, 0, 0]), 123) + + # test singletons + normalize + for num in (-2, 0, 1, 5, 42, 100): + self.assertIs(pylongwriter_create(bool(num < 0), [abs(num), 0]), + num) + + def to_digits(num): + digits = [] + while True: + num, digit = divmod(num, base) + digits.append(digit) + if not num: + break + return digits + + # round trip: Python int -> export -> Python int + pylong_export = _testcapi.pylong_export + numbers = [*range(0, 10), 12345, 0xdeadbeef, 2**100, 2**100-1] + numbers.extend(-num for num in list(numbers)) + for num in numbers: + with self.subTest(num=num): + data = pylong_export(num) + if isinstance(data, tuple): + negative, digits = data + else: + value = data + negative = int(value < 0) + digits = to_digits(abs(value)) + self.assertEqual(pylongwriter_create(negative, digits), num, + (negative, digits)) + + @unittest.skipUnless(support.Py_DEBUG, "need a debug build (Py_DEBUG)") + def test_longwriter_finish(self): + # Test PyLongWriter_Create(0, 3, &digits) with PyLongWriter_Finish() + # where the last digit is left uninitialized + pylongwriter_finish_bug = _testcapi.pylongwriter_finish_bug + with self.assertRaises(SystemError) as cm: + pylongwriter_finish_bug() + self.assertEqual(str(cm.exception), + 'PyLongWriter_Finish: digit 2 is uninitialized') + + def test_bug_143050(self): + with support.adjust_int_max_str_digits(0): + # Bug coming from using _pylong.int_from_string(), that + # currently requires > 6000 decimal digits. + int('-' + '0' * 7000, 10) + _testcapi.test_immortal_small_ints() + # Test also nonzero small int + int('-' + '0' * 7000 + '123', 10) + _testcapi.test_immortal_small_ints() + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_capi/test_weakref.py b/Lib/test/test_capi/test_weakref.py new file mode 100644 index 00000000000..86ebe92da8d --- /dev/null +++ b/Lib/test/test_capi/test_weakref.py @@ -0,0 +1,136 @@ +import weakref +import unittest +from test.support import import_helper + +_testcapi = import_helper.import_module('_testcapi') +_testlimitedcapi = import_helper.import_module('_testlimitedcapi') +NULL = None + +class Object: + pass + +class Ref(weakref.ReferenceType): + pass + + +class CAPIWeakrefTest(unittest.TestCase): + def test_pyweakref_check(self): + # Test PyWeakref_Check() + check = _testlimitedcapi.pyweakref_check + obj = Object() + self.assertEqual(check(obj), 0) + self.assertEqual(check(weakref.ref(obj)), 1) + self.assertEqual(check(Ref(obj)), 1) + self.assertEqual(check(weakref.proxy(obj)), 1) + + # CRASHES check(NULL) + + def test_pyweakref_checkref(self): + # Test PyWeakref_CheckRef() + checkref = _testlimitedcapi.pyweakref_checkref + obj = Object() + self.assertEqual(checkref(obj), 0) + self.assertEqual(checkref(weakref.ref(obj)), 1) + self.assertEqual(checkref(Ref(obj)), 1) + self.assertEqual(checkref(weakref.proxy(obj)), 0) + + # CRASHES checkref(NULL) + + def test_pyweakref_checkrefexact(self): + # Test PyWeakref_CheckRefExact() + checkrefexact = _testlimitedcapi.pyweakref_checkrefexact + obj = Object() + self.assertEqual(checkrefexact(obj), 0) + self.assertEqual(checkrefexact(weakref.ref(obj)), 1) + self.assertEqual(checkrefexact(Ref(obj)), 0) + self.assertEqual(checkrefexact(weakref.proxy(obj)), 0) + + # CRASHES checkrefexact(NULL) + + def test_pyweakref_checkproxy(self): + # Test PyWeakref_CheckProxy() + checkproxy = _testlimitedcapi.pyweakref_checkproxy + obj = Object() + self.assertEqual(checkproxy(obj), 0) + self.assertEqual(checkproxy(weakref.ref(obj)), 0) + self.assertEqual(checkproxy(Ref(obj)), 0) + self.assertEqual(checkproxy(weakref.proxy(obj)), 1) + + # CRASHES checkproxy(NULL) + + def test_pyweakref_getref(self): + # Test PyWeakref_GetRef() + getref = _testcapi.pyweakref_getref + obj = Object() + wr = weakref.ref(obj) + wp = weakref.proxy(obj) + self.assertEqual(getref(wr), (1, obj)) + self.assertEqual(getref(wp), (1, obj)) + del obj + self.assertEqual(getref(wr), 0) + self.assertEqual(getref(wp), 0) + + self.assertRaises(TypeError, getref, 42) + self.assertRaises(SystemError, getref, NULL) + + def test_pyweakref_isdead(self): + # Test PyWeakref_IsDead() + isdead = _testcapi.pyweakref_isdead + obj = Object() + wr = weakref.ref(obj) + wp = weakref.proxy(obj) + self.assertEqual(isdead(wr), 0) + self.assertEqual(isdead(wp), 0) + del obj + self.assertEqual(isdead(wr), 1) + self.assertEqual(isdead(wp), 1) + + self.assertRaises(TypeError, isdead, 42) + self.assertRaises(SystemError, isdead, NULL) + + def test_pyweakref_newref(self): + # Test PyWeakref_NewRef() + newref = _testlimitedcapi.pyweakref_newref + obj = Object() + wr = newref(obj) + self.assertIs(type(wr), weakref.ReferenceType) + # PyWeakref_NewRef() handles None callback as NULL callback + wr = newref(obj, None) + self.assertIs(type(wr), weakref.ReferenceType) + log = [] + wr = newref(obj, log.append) + self.assertIs(type(wr), weakref.ReferenceType) + self.assertEqual(log, []) + del obj + self.assertEqual(log, [wr]) + + self.assertRaises(TypeError, newref, []) + # CRASHES newref(NULL) + + def test_pyweakref_newproxy(self): + # Test PyWeakref_NewProxy() + newproxy = _testlimitedcapi.pyweakref_newproxy + obj = Object() + wp = newproxy(obj) + self.assertIs(type(wp), weakref.ProxyType) + # PyWeakref_NewProxy() handles None callback as NULL callback + wp = newproxy(obj, None) + self.assertIs(type(wp), weakref.ProxyType) + log = [] + wp = newproxy(obj, log.append) + self.assertIs(type(wp), weakref.ProxyType) + self.assertEqual(log, []) + del obj + self.assertEqual(log, [wp]) + + def func(): + pass + wp = newproxy(func) + self.assertIs(type(wp), weakref.CallableProxyType) + + self.assertRaises(TypeError, newproxy, []) + # CRASHES newproxy(NULL) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py index d36c5231609..2ec9e62330c 100644 --- a/Lib/test/test_class.py +++ b/Lib/test/test_class.py @@ -2,7 +2,7 @@ import unittest from test import support -from test.support import cpython_only, import_helper, script_helper +from test.support import cpython_only, import_helper, isolation testmeths = [ @@ -449,7 +449,6 @@ def __delattr__(self, *args): def testHasAttrString(self): import sys - from test.support import import_helper _testlimitedcapi = import_helper.import_module('_testlimitedcapi') class A: @@ -556,7 +555,7 @@ class Custom: self.assertFalse(hasattr(o, "__call__")) self.assertFalse(hasattr(c, "__call__")) - @unittest.skip("TODO: RUSTPYTHON; segmentation fault") + @support.skip_if_huge_c_stack() @support.skip_emscripten_stack_overflow() @support.skip_wasi_stack_overflow() def testSFBug532646(self): @@ -653,6 +652,7 @@ class B(A): a = A(hash(A.f)^(-1)) hash(a.f) + @cpython_only def testSetattrWrapperNameIntern(self): # Issue #25794: __setattr__ should intern the attribute name class A: @@ -1014,36 +1014,99 @@ class C: C.a = X() C.a = X() - @cpython_only + @support.nomemtest + @isolation.runInSubprocess() def test_detach_materialized_dict_no_memory(self): - # Skip test if _testcapi is not available: - import_helper.import_module('_testcapi') - - code = """if 1: - import test.support - import _testcapi - - class A: - def __init__(self): - self.a = 1 - self.b = 2 + class A: + def __init__(self): + self.a = 1 + self.b = 2 + + # The failing allocation should be the one which detaches the + # dictionary from the object, but other allocations can happen + # first, so try to fail every one of the first allocations. + raised = False + for n in range(20): a = A() d = a.__dict__ - with test.support.catch_unraisable_exception() as ex: - _testcapi.set_nomemory(0, 1) - del a - assert ex.unraisable.exc_type is MemoryError try: - d["a"] - except KeyError: - pass - else: - assert False, "KeyError not raised" - """ - rc, out, err = script_helper.assert_python_ok("-c", code) - self.assertEqual(rc, 0) - self.assertFalse(out, msg=out.decode('utf-8')) - self.assertFalse(err, msg=err.decode('utf-8')) + with support.catch_unraisable_exception() as ex: + with support.inject_memory_error_cm(n, n + 1): + del a + exc_type = ex.unraisable and ex.unraisable.exc_type + except MemoryError: + # The failing allocation was not in the deallocation code. + continue + if exc_type is not MemoryError: + continue + raised = True + if "a" not in d: + # The dictionary was cleared, as expected. + break + else: + if not raised: + self.fail("MemoryError was not raised during deallocation") + self.fail("the dictionary was not cleared") + +class DefinitionOrderTests(unittest.TestCase): + # PEP 520: Preserving Class Attribute Definition Order + + @staticmethod + def defined_names(namespace): + # Skip the names added by the compiler, like __firstlineno__. + return [name for name in namespace if not name.startswith('__')] + + def test_definition_order(self): + class C: + b = 1 + a = 2 + def m(self): pass + @staticmethod + def s(): pass + z = 3 + + self.assertEqual(self.defined_names(C.__dict__), + ['b', 'a', 'm', 's', 'z']) + + def test_definition_order_redefinition(self): + class C: + b = 1 + a = 2 + b = 3 + + self.assertEqual(self.defined_names(C.__dict__), ['b', 'a']) + self.assertEqual(C.b, 3) + + def test_definition_order_after_deletion(self): + class C: + a = 1 + b = 2 + del a + a = 3 + + self.assertEqual(self.defined_names(C.__dict__), ['b', 'a']) + + def test_definition_order_in_namespace(self): + namespaces = [] + class Meta(type): + def __new__(mcls, name, bases, namespace, **kwds): + namespaces.append(list(namespace)) + return super().__new__(mcls, name, bases, namespace, **kwds) + + class C(metaclass=Meta): + b = 1 + a = 2 + def m(self): pass + + self.assertEqual(self.defined_names(namespaces[0]), ['b', 'a', 'm']) + + def test_prepare_preserves_order(self): + namespace = type.__prepare__('C', ()) + namespace['b'] = 1 + namespace['a'] = 2 + namespace['b'] = 3 + self.assertEqual(list(namespace), ['b', 'a']) + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_clinic.py b/Lib/test/test_clinic.py index 73bb942af7c..93c284e5876 100644 --- a/Lib/test/test_clinic.py +++ b/Lib/test/test_clinic.py @@ -4,6 +4,7 @@ from functools import partial from test import support, test_tools +from test.support import force_not_colorized_test_class from test.support import os_helper from test.support.os_helper import TESTFN, unlink, rmtree from textwrap import dedent @@ -357,6 +358,32 @@ def test_vararg_after_star(self): """ self.expect_failure(block, err, lineno=6) + def test_double_star_after_var_keyword(self): + err = "Function 'my_test_func' has an invalid parameter declaration (**kwargs?): '**kwds: dict'" + block = """ + /*[clinic input] + my_test_func + + pos_arg: object + **kwds: dict + ** + [clinic start generated code]*/ + """ + self.expect_failure(block, err, lineno=5) + + def test_var_keyword_after_star(self): + err = "Function 'my_test_func' has an invalid parameter declaration: '**'" + block = """ + /*[clinic input] + my_test_func + + pos_arg: object + ** + **kwds: dict + [clinic start generated code]*/ + """ + self.expect_failure(block, err, lineno=5) + def test_module_already_got_one(self): err = "Already defined module 'm'!" block = """ @@ -748,6 +775,16 @@ def test_ignore_preprocessor_in_comments(self): """) self.clinic.parse(raw) + def test_var_keyword_non_dict(self): + err = "'var_keyword_object' is not a valid converter" + block = """ + /*[clinic input] + my_test_func + + **kwds: object + [clinic start generated code]*/ + """ + self.expect_failure(block, err, lineno=4) class ParseFileUnitTest(TestCase): def expect_parsing_failure( @@ -1789,6 +1826,11 @@ def test_disallowed_grouping__must_be_position_only(self): [ a: object ] + """, """ + with_kwds + [ + **kwds: dict + ] """) err = ( "You cannot use optional groups ('[' and ']') unless all " @@ -2172,6 +2214,44 @@ def test_slash_after_vararg(self): err = "Function 'bar': '/' must precede '*'" self.expect_failure(block, err) + def test_slash_after_var_keyword(self): + block = """ + module foo + foo.bar + x: int + y: int + **kwds: dict + z: int + / + """ + err = "Function 'bar' has an invalid parameter declaration (**kwargs?): '**kwds: dict'" + self.expect_failure(block, err) + + def test_star_after_var_keyword(self): + block = """ + module foo + foo.bar + x: int + y: int + **kwds: dict + z: int + * + """ + err = "Function 'bar' has an invalid parameter declaration (**kwargs?): '**kwds: dict'" + self.expect_failure(block, err) + + def test_parameter_after_var_keyword(self): + block = """ + module foo + foo.bar + x: int + y: int + **kwds: dict + z: int + """ + err = "Function 'bar' has an invalid parameter declaration (**kwargs?): '**kwds: dict'" + self.expect_failure(block, err) + def test_depr_star_must_come_after_slash(self): block = """ module foo @@ -2260,6 +2340,16 @@ def test_parameters_no_more_than_one_vararg(self): """ self.expect_failure(block, err, lineno=3) + def test_parameters_no_more_than_one_var_keyword(self): + err = "Encountered parameter line when not expecting parameters: **var_keyword_2: dict" + block = """ + module foo + foo.bar + **var_keyword_1: dict + **var_keyword_2: dict + """ + self.expect_failure(block, err, lineno=3) + def test_function_not_at_column_0(self): function = self.parse_function(""" module foo @@ -2694,6 +2784,14 @@ def test_vararg_cannot_take_default_value(self): """ self.expect_failure(block, err, lineno=1) + def test_var_keyword_cannot_take_default_value(self): + err = "Function 'fn' has an invalid parameter declaration:" + block = """ + fn + **kwds: dict = None + """ + self.expect_failure(block, err, lineno=1) + def test_default_is_not_of_correct_type(self): err = ("int_converter: default value 2.5 for field 'a' " "is not of type 'int'") @@ -2791,7 +2889,58 @@ def test_disallow_defining_class_at_module_level(self): """ self.expect_failure(block, err, lineno=2) + def test_var_keyword_with_pos_or_kw(self): + block = """ + module foo + foo.bar + x: int + **kwds: dict + """ + err = "Function 'bar' has an invalid parameter declaration (**kwargs?): '**kwds: dict'" + self.expect_failure(block, err) + + def test_var_keyword_with_kw_only(self): + block = """ + module foo + foo.bar + x: int + / + * + y: int + **kwds: dict + """ + err = "Function 'bar' has an invalid parameter declaration (**kwargs?): '**kwds: dict'" + self.expect_failure(block, err) + + def test_var_keyword_with_pos_or_kw_and_kw_only(self): + block = """ + module foo + foo.bar + x: int + / + y: int + * + z: int + **kwds: dict + """ + err = "Function 'bar' has an invalid parameter declaration (**kwargs?): '**kwds: dict'" + self.expect_failure(block, err) + + def test_allow_negative_accepted_by_py_ssize_t_converter_only(self): + errmsg = re.escape("converter_init() got an unexpected keyword argument 'allow_negative'") + unsupported_converters = [converter_name for converter_name in converters.keys() + if converter_name != "Py_ssize_t"] + for converter in unsupported_converters: + with self.subTest(converter=converter): + block = f""" + module m + m.func + a: {converter}(allow_negative=True) + """ + with self.assertRaisesRegex((AssertionError, TypeError), errmsg): + self.parse_function(block) +@force_not_colorized_test_class class ClinicExternalTest(TestCase): maxDiff = None @@ -3228,6 +3377,8 @@ def test_char_converter(self): def test_unsigned_char_converter(self): from _testcapi import UCHAR_MAX + SCHAR_MAX = UCHAR_MAX // 2 + SCHAR_MIN = SCHAR_MAX - UCHAR_MAX with self.assertRaises(OverflowError): ac_tester.unsigned_char_converter(-1) with self.assertRaises(OverflowError): @@ -3237,8 +3388,13 @@ def test_unsigned_char_converter(self): with self.assertRaises(TypeError): ac_tester.unsigned_char_converter([]) self.assertEqual(ac_tester.unsigned_char_converter(), (12, 34, 56)) - self.assertEqual(ac_tester.unsigned_char_converter(0, 0, UCHAR_MAX + 1), (0, 0, 0)) - self.assertEqual(ac_tester.unsigned_char_converter(0, 0, (UCHAR_MAX + 1) * 3 + 123), (0, 0, 123)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_char_converter(0, 0, UCHAR_MAX + 1), (0, 0, 0)) + self.assertEqual(ac_tester.unsigned_char_converter(0, 0, SCHAR_MIN), (0, 0, SCHAR_MAX + 1)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_char_converter(0, 0, SCHAR_MIN - 1), (0, 0, SCHAR_MAX)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_char_converter(0, 0, (UCHAR_MAX + 1) * 3 + 123), (0, 0, 123)) def test_short_converter(self): from _testcapi import SHRT_MIN, SHRT_MAX @@ -3252,7 +3408,7 @@ def test_short_converter(self): self.assertEqual(ac_tester.short_converter(4321), (4321,)) def test_unsigned_short_converter(self): - from _testcapi import USHRT_MAX + from _testcapi import SHRT_MIN, SHRT_MAX, USHRT_MAX with self.assertRaises(ValueError): ac_tester.unsigned_short_converter(-1) with self.assertRaises(OverflowError): @@ -3262,8 +3418,13 @@ def test_unsigned_short_converter(self): with self.assertRaises(TypeError): ac_tester.unsigned_short_converter([]) self.assertEqual(ac_tester.unsigned_short_converter(), (12, 34, 56)) - self.assertEqual(ac_tester.unsigned_short_converter(0, 0, USHRT_MAX + 1), (0, 0, 0)) - self.assertEqual(ac_tester.unsigned_short_converter(0, 0, (USHRT_MAX + 1) * 3 + 123), (0, 0, 123)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_short_converter(0, 0, USHRT_MAX + 1), (0, 0, 0)) + self.assertEqual(ac_tester.unsigned_short_converter(0, 0, SHRT_MIN), (0, 0, SHRT_MAX + 1)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_short_converter(0, 0, SHRT_MIN - 1), (0, 0, SHRT_MAX)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_short_converter(0, 0, (USHRT_MAX + 1) * 3 + 123), (0, 0, 123)) def test_int_converter(self): from _testcapi import INT_MIN, INT_MAX @@ -3279,7 +3440,7 @@ def test_int_converter(self): self.assertEqual(ac_tester.int_converter(1, 2, '3'), (1, 2, ord('3'))) def test_unsigned_int_converter(self): - from _testcapi import UINT_MAX + from _testcapi import INT_MIN, INT_MAX, UINT_MAX with self.assertRaises(ValueError): ac_tester.unsigned_int_converter(-1) with self.assertRaises(OverflowError): @@ -3289,8 +3450,13 @@ def test_unsigned_int_converter(self): with self.assertRaises(TypeError): ac_tester.unsigned_int_converter([]) self.assertEqual(ac_tester.unsigned_int_converter(), (12, 34, 56)) - self.assertEqual(ac_tester.unsigned_int_converter(0, 0, UINT_MAX + 1), (0, 0, 0)) - self.assertEqual(ac_tester.unsigned_int_converter(0, 0, (UINT_MAX + 1) * 3 + 123), (0, 0, 123)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_int_converter(0, 0, UINT_MAX + 1), (0, 0, 0)) + self.assertEqual(ac_tester.unsigned_int_converter(0, 0, INT_MIN), (0, 0, INT_MAX + 1)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_int_converter(0, 0, INT_MIN - 1), (0, 0, INT_MAX)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_int_converter(0, 0, (UINT_MAX + 1) * 3 + 123), (0, 0, 123)) def test_long_converter(self): from _testcapi import LONG_MIN, LONG_MAX @@ -3304,7 +3470,7 @@ def test_long_converter(self): self.assertEqual(ac_tester.long_converter(-1234), (-1234,)) def test_unsigned_long_converter(self): - from _testcapi import ULONG_MAX + from _testcapi import LONG_MIN, LONG_MAX, ULONG_MAX with self.assertRaises(ValueError): ac_tester.unsigned_long_converter(-1) with self.assertRaises(OverflowError): @@ -3314,8 +3480,13 @@ def test_unsigned_long_converter(self): with self.assertRaises(TypeError): ac_tester.unsigned_long_converter([]) self.assertEqual(ac_tester.unsigned_long_converter(), (12, 34, 56)) - self.assertEqual(ac_tester.unsigned_long_converter(0, 0, ULONG_MAX + 1), (0, 0, 0)) - self.assertEqual(ac_tester.unsigned_long_converter(0, 0, (ULONG_MAX + 1) * 3 + 123), (0, 0, 123)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_long_converter(0, 0, ULONG_MAX + 1), (0, 0, 0)) + self.assertEqual(ac_tester.unsigned_long_converter(0, 0, LONG_MIN), (0, 0, LONG_MAX + 1)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_long_converter(0, 0, LONG_MIN - 1), (0, 0, LONG_MAX)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_long_converter(0, 0, (ULONG_MAX + 1) * 3 + 123), (0, 0, 123)) def test_long_long_converter(self): from _testcapi import LLONG_MIN, LLONG_MAX @@ -3329,7 +3500,7 @@ def test_long_long_converter(self): self.assertEqual(ac_tester.long_long_converter(-1234), (-1234,)) def test_unsigned_long_long_converter(self): - from _testcapi import ULLONG_MAX + from _testcapi import LLONG_MIN, LLONG_MAX, ULLONG_MAX with self.assertRaises(ValueError): ac_tester.unsigned_long_long_converter(-1) with self.assertRaises(OverflowError): @@ -3339,8 +3510,13 @@ def test_unsigned_long_long_converter(self): with self.assertRaises(TypeError): ac_tester.unsigned_long_long_converter([]) self.assertEqual(ac_tester.unsigned_long_long_converter(), (12, 34, 56)) - self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, ULLONG_MAX + 1), (0, 0, 0)) - self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, (ULLONG_MAX + 1) * 3 + 123), (0, 0, 123)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, ULLONG_MAX + 1), (0, 0, 0)) + self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, LLONG_MIN), (0, 0, LLONG_MAX + 1)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, LLONG_MIN - 1), (0, 0, LLONG_MAX)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(ac_tester.unsigned_long_long_converter(0, 0, (ULLONG_MAX + 1) * 3 + 123), (0, 0, 123)) def test_py_ssize_t_converter(self): from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX @@ -3350,8 +3526,12 @@ def test_py_ssize_t_converter(self): ac_tester.py_ssize_t_converter(PY_SSIZE_T_MAX + 1) with self.assertRaises(TypeError): ac_tester.py_ssize_t_converter([]) - self.assertEqual(ac_tester.py_ssize_t_converter(), (12, 34, 56)) - self.assertEqual(ac_tester.py_ssize_t_converter(1, 2, None), (1, 2, 56)) + with self.assertRaises(ValueError): + ac_tester.py_ssize_t_converter(12, 34, 56, -1) + with self.assertRaises(ValueError): + ac_tester.py_ssize_t_converter(12, 34, 56, 78, -1) + self.assertEqual(ac_tester.py_ssize_t_converter(), (12, 34, 56, 78, 90, -12, -34)) + self.assertEqual(ac_tester.py_ssize_t_converter(1, 2, None, 3, None, 4, None), (1, 2, 56, 3, 90, 4, -34)) def test_slice_index_converter(self): from _testcapi import PY_SSIZE_T_MIN, PY_SSIZE_T_MAX @@ -4093,6 +4273,49 @@ def test_depr_multi(self): check("a", b="b", c="c", d="d", e="e", f="f", g="g") self.assertRaises(TypeError, fn, a="a", b="b", c="c", d="d", e="e", f="f", g="g") + def test_lone_kwds(self): + with self.assertRaises(TypeError): + ac_tester.lone_kwds(1, 2) + self.assertEqual(ac_tester.lone_kwds(), ({},)) + self.assertEqual(ac_tester.lone_kwds(y='y'), ({'y': 'y'},)) + kwds = {'y': 'y', 'z': 'z'} + self.assertEqual(ac_tester.lone_kwds(y='y', z='z'), (kwds,)) + self.assertEqual(ac_tester.lone_kwds(**kwds), (kwds,)) + + def test_kwds_with_pos_only(self): + with self.assertRaises(TypeError): + ac_tester.kwds_with_pos_only() + with self.assertRaises(TypeError): + ac_tester.kwds_with_pos_only(y='y') + with self.assertRaises(TypeError): + ac_tester.kwds_with_pos_only(1, y='y') + self.assertEqual(ac_tester.kwds_with_pos_only(1, 2), (1, 2, {})) + self.assertEqual(ac_tester.kwds_with_pos_only(1, 2, y='y'), (1, 2, {'y': 'y'})) + kwds = {'y': 'y', 'z': 'z'} + self.assertEqual(ac_tester.kwds_with_pos_only(1, 2, y='y', z='z'), (1, 2, kwds)) + self.assertEqual(ac_tester.kwds_with_pos_only(1, 2, **kwds), (1, 2, kwds)) + + def test_kwds_with_stararg(self): + self.assertEqual(ac_tester.kwds_with_stararg(), ((), {})) + self.assertEqual(ac_tester.kwds_with_stararg(1, 2), ((1, 2), {})) + self.assertEqual(ac_tester.kwds_with_stararg(y='y'), ((), {'y': 'y'})) + args = (1, 2) + kwds = {'y': 'y', 'z': 'z'} + self.assertEqual(ac_tester.kwds_with_stararg(1, 2, y='y', z='z'), (args, kwds)) + self.assertEqual(ac_tester.kwds_with_stararg(*args, **kwds), (args, kwds)) + + def test_kwds_with_pos_only_and_stararg(self): + with self.assertRaises(TypeError): + ac_tester.kwds_with_pos_only_and_stararg() + with self.assertRaises(TypeError): + ac_tester.kwds_with_pos_only_and_stararg(y='y') + self.assertEqual(ac_tester.kwds_with_pos_only_and_stararg(1, 2), (1, 2, (), {})) + self.assertEqual(ac_tester.kwds_with_pos_only_and_stararg(1, 2, y='y'), (1, 2, (), {'y': 'y'})) + args = ('lobster', 'thermidor') + kwds = {'y': 'y', 'z': 'z'} + self.assertEqual(ac_tester.kwds_with_pos_only_and_stararg(1, 2, 'lobster', 'thermidor', y='y', z='z'), (1, 2, args, kwds)) + self.assertEqual(ac_tester.kwds_with_pos_only_and_stararg(1, 2, *args, **kwds), (1, 2, args, kwds)) + class LimitedCAPIOutputTests(unittest.TestCase): diff --git a/Lib/test/test_cmath.py b/Lib/test/test_cmath.py index 389a3fa0e0a..a986fd6b892 100644 --- a/Lib/test/test_cmath.py +++ b/Lib/test/test_cmath.py @@ -516,6 +516,7 @@ def test_isinf(self): self.assertFalse(cmath.isinf(1j)) self.assertFalse(cmath.isinf(NAN)) self.assertTrue(cmath.isinf(INF)) + self.assertTrue(cmath.isinf(-INF)) self.assertTrue(cmath.isinf(complex(INF, 0))) self.assertTrue(cmath.isinf(complex(0, INF))) self.assertTrue(cmath.isinf(complex(INF, INF))) diff --git a/Lib/test/test_cmd.py b/Lib/test/test_cmd.py index dbfec42fc21..ed3336994ed 100644 --- a/Lib/test/test_cmd.py +++ b/Lib/test/test_cmd.py @@ -316,7 +316,10 @@ def default(self, line): for input in [b"! h\t\n", b"!h\t\n"]: with self.subTest(input=input): output = run_pty(script, input) - self.assertIn(b'hello', output) + # libedit redraws only the untyped suffix after a + # cursor-forward escape, unlike GNU readline which retypes + # the whole completed word, so check the common suffix. + self.assertIn(b'ello', output) self.assertIn(b'tab completion success', output) def load_tests(loader, tests, pattern): diff --git a/Lib/test/test_cmd_line.py b/Lib/test/test_cmd_line.py index d6fcfa3b471..a3b7d2f50ad 100644 --- a/Lib/test/test_cmd_line.py +++ b/Lib/test/test_cmd_line.py @@ -2,6 +2,7 @@ # Most tests are executed with environment variables ignored # See test_cmd_line_script.py for testing of script execution +import locale import os import re import subprocess @@ -32,6 +33,17 @@ def _kill_python_and_exit_code(p): return data, returncode +def presite_func(): + print("presite func") + +class Namespace: + pass + +presite = Namespace() +presite.attr = Namespace() +presite.attr.func = presite_func + + class CmdLineTest(unittest.TestCase): def test_directories(self): assert_python_failure('.') @@ -46,6 +58,7 @@ def verify_valid_flag(self, cmd_line): return out @support.cpython_only + @support.force_not_colorized def test_help(self): self.verify_valid_flag('-h') self.verify_valid_flag('-?') @@ -57,6 +70,7 @@ def test_help(self): self.assertLess(len(lines), 50) @support.cpython_only + @support.force_not_colorized def test_help_env(self): out = self.verify_valid_flag('--help-env') self.assertIn(b'PYTHONHOME', out) @@ -70,6 +84,7 @@ def test_help_env(self): "env vars should be sorted alphabetically") @support.cpython_only + @support.force_not_colorized def test_help_xoptions(self): out = self.verify_valid_flag('--help-xoptions') self.assertIn(b'-X dev', out) @@ -78,6 +93,7 @@ def test_help_xoptions(self): "options should be sorted alphabetically") @support.cpython_only + @support.force_not_colorized def test_help_all(self): out = self.verify_valid_flag('--help-all') lines = out.splitlines() @@ -89,6 +105,25 @@ def test_help_all(self): # but the rest should be ASCII-only b''.join(lines[1:]).decode('ascii') + @support.cpython_only + @support.force_colorized + def test_help_colorized(self): + rc, out, err = assert_python_ok("--help", FORCE_COLOR="1") + # Check ANSI color codes are present + self.assertIn(b"\x1b[", out) + # Check that key text elements are still present + self.assertIn(b"usage:", out) + self.assertIn(b"-h", out) + self.assertIn(b"--help-all", out) + self.assertIn(b"cmd", out) + self.assertIn(b"Arguments:", out) + + @support.cpython_only + @support.force_not_colorized + def test_help_not_colorized(self): + rc, out, err = assert_python_ok("--help") + self.assertNotIn(b"\x1b[", out) + def test_optimize(self): self.verify_valid_flag('-O') self.verify_valid_flag('-OO') @@ -259,7 +294,6 @@ def test_coding(self): # command line, but how subprocess does decode bytes to unicode. Python # doesn't decode the command line because Windows provides directly the # arguments as unicode (using wmain() instead of main()). - @unittest.expectedFailure # TODO: RUSTPYTHON @unittest.skipIf(sys.platform == 'win32', 'Windows has a native unicode API') def test_undecodable_code(self): @@ -295,7 +329,6 @@ def test_undecodable_code(self): if not stdout.startswith(pattern): raise AssertionError("%a doesn't start with %a" % (stdout, pattern)) - @unittest.expectedFailure # TODO: RUSTPYTHON @unittest.skipIf(sys.platform == 'win32', 'Windows has a native unicode API') def test_invalid_utf8_arg(self): @@ -322,6 +355,10 @@ def run_utf8_mode(arg): cmd = [sys.executable, '-X', 'utf8', '-c', code, arg] return subprocess.run(cmd, stdout=subprocess.PIPE, text=True) + def run_no_utf8_mode(arg): + cmd = [sys.executable, '-X', 'utf8=0', '-c', code, arg] + return subprocess.run(cmd, stdout=subprocess.PIPE, text=True) + valid_utf8 = 'e:\xe9, euro:\u20ac, non-bmp:\U0010ffff'.encode('utf-8') # invalid UTF-8 byte sequences with a valid UTF-8 sequence # in the middle. @@ -334,8 +371,27 @@ def run_utf8_mode(arg): ) test_args = [valid_utf8, invalid_utf8] - for run_cmd in (run_default, run_c_locale, run_utf8_mode): - with self.subTest(run_cmd=run_cmd): + for run_cmd, encoding in ( + (run_default, sys.getfilesystemencoding()), + (run_c_locale, None), + (run_utf8_mode, None), + (run_no_utf8_mode, locale.getencoding()) + ): + with self.subTest(run_cmd=run_cmd.__name__): + # Arbitrary bytes round-trip through surrogateescape only in + # UTF-8 and single-byte encodings, not in a multibyte encoding + # such as EUC-JP. + if encoding is not None: + try: + lossless = len(bytes(range(256)).decode( + encoding, 'surrogateescape')) == 256 + except UnicodeError: + lossless = False + else: + lossless = True + if not lossless: + self.skipTest(f'{encoding} cannot losslessly ' + f'round-trip arbitrary bytes') for arg in test_args: proc = run_cmd(arg) self.assertEqual(proc.stdout.rstrip(), ascii(arg)) @@ -433,14 +489,12 @@ def test_empty_PYTHONPATH_issue16309(self): path = ":".join(sys.path) path = path.encode("ascii", "backslashreplace") sys.stdout.buffer.write(path)""" - # TODO: RUSTPYTHON we must unset RUSTPYTHONPATH as well rc1, out1, err1 = assert_python_ok('-c', code, PYTHONPATH="", RUSTPYTHONPATH="") rc2, out2, err2 = assert_python_ok('-c', code, __isolated=False) # regarding to Posix specification, outputs should be equal # for empty and unset PYTHONPATH self.assertEqual(out1, out2) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_displayhook_unencodable(self): for encoding in ('ascii', 'latin-1', 'utf-8'): env = os.environ.copy() @@ -508,7 +562,7 @@ def test_unmached_quote(self): self.assertRegex(err.decode('ascii', 'ignore'), 'SyntaxError') self.assertEqual(b'', out) - @unittest.expectedFailure # TODO: RUSTPYTHON + @force_not_colorized def test_stdout_flush_at_shutdown(self): # Issue #5319: if stdout.flush() fails at shutdown, an error should # be printed out. @@ -560,19 +614,23 @@ def preexec(): self.assertEqual(err, b'') self.assertEqual(p.returncode, 42) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailureIf(sys.platform not in ("linux", "darwin"), + "TODO: RUSTPYTHON; pre-runtime stdio snapshot unsupported") def test_no_stdin(self): self._test_no_stdio(['stdin']) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailureIf(sys.platform not in ("linux", "darwin"), + "TODO: RUSTPYTHON; pre-runtime stdio snapshot unsupported") def test_no_stdout(self): self._test_no_stdio(['stdout']) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailureIf(sys.platform not in ("linux", "darwin"), + "TODO: RUSTPYTHON; pre-runtime stdio snapshot unsupported") def test_no_stderr(self): self._test_no_stdio(['stderr']) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailureIf(sys.platform not in ("linux", "darwin"), + "TODO: RUSTPYTHON; pre-runtime stdio snapshot unsupported") def test_no_std_streams(self): self._test_no_stdio(['stdin', 'stdout', 'stderr']) @@ -671,7 +729,6 @@ def test_isolatedmode(self): cwd=tmpdir) self.assertEqual(out.strip(), b"ok") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_sys_flags_set(self): # Issue 31845: a startup refactoring broke reading flags from env vars for value, expected in (("", 0), ("1", 1), ("text", 1), ("2", 2)): @@ -693,7 +750,6 @@ def test_sys_flags_set(self): with self.subTest(envar_value=value): assert_python_ok('-c', code, **env_vars) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_set_pycache_prefix(self): # sys.pycache_prefix can be set from either -X pycache_prefix or # PYTHONPYCACHEPREFIX env var, with the former taking precedence. @@ -822,7 +878,6 @@ def check_warnings_filters(self, cmdline_option, envvar, use_pywarning=False): self.assertEqual(proc.returncode, 0, proc) return proc.stdout.rstrip() - @unittest.expectedFailure # TODO: RUSTPYTHON def test_warnings_filter_precedence(self): expected_filters = ("error::BytesWarning " "once::UserWarning " @@ -901,7 +956,6 @@ def test_pythonmalloc(self): with self.subTest(env_var=env_var, name=name): self.check_pythonmalloc(env_var, name) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_pythondevmode_env(self): # Test the PYTHONDEVMODE environment variable code = "import sys; print(sys.flags.dev_mode)" @@ -992,7 +1046,6 @@ def test_python_executable(self): rc, out, err = assert_python_ok('-c', code, PYTHONEXECUTABLE=expected) self.assertIn(expected.encode(), out) - @unittest.expectedFailureIf(support.MS_WINDOWS, "TODO: RUSTPYTHON") @unittest.skipUnless(support.MS_WINDOWS, 'Test only applicable on Windows') def test_python_legacy_windows_fs_encoding(self): code = "import sys; print(sys.getfilesystemencoding())" @@ -1066,6 +1119,7 @@ def test_argv0_normalization(self): self.assertEqual(proc.stdout.strip(), b'0') @support.cpython_only + @support.force_not_colorized def test_parsing_error(self): args = [sys.executable, '-I', '--unknown-option'] proc = subprocess.run(args, @@ -1207,7 +1261,6 @@ def test_cpu_count_default(self): res = assert_python_ok('-c', code, PYTHON_CPU_COUNT='default') self.assertEqual(self.res2int(res), (os.cpu_count(), os.process_cpu_count())) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_import_time(self): # os is not imported at startup code = 'import os; import os' @@ -1226,6 +1279,24 @@ def test_import_time(self): assert_python_failure('-X', 'importtime=-1', '-c', code) assert_python_failure('-X', 'importtime=3', '-c', code) + def test_import_time_unencodable_module_name(self): + code = textwrap.dedent(""" + import sys, types + name = 'mod\\ud800' + sys.modules[name] = types.ModuleType(name) + __import__(name) + try: + __import__('nonexistent\\ud800') + except ModuleNotFoundError: + pass + """) + res = assert_python_ok('-X', 'importtime=2', '-c', code) + res_err = res.err.decode('utf-8') + self.assertRegex(res_err, + r'import time: cached\s* \| cached\s* \| mod\\ud800') + self.assertRegex(res_err, + r'import time: \s*\d+ \| \s*\d+ \| \s*nonexistent\\ud800') + def res2int(self, res): out = res.out.strip().decode("utf-8") return tuple(int(i) for i in out.split()) @@ -1282,6 +1353,28 @@ def test_invalid_thread_local_bytecode(self): rc, out, err = assert_python_failure(PYTHON_TLBC="2") self.assertIn(b"PYTHON_TLBC=N: N is missing or invalid", err) + @unittest.skipUnless(support.Py_DEBUG, + '-X presite requires a Python debug build') + def test_presite(self): + entrypoint = "test.test_cmd_line:presite_func" + proc = assert_python_ok("-X", f"presite={entrypoint}", "-c", "pass") + self.assertEqual(proc.out.rstrip(), b"presite func") + + entrypoint = "test.test_cmd_line:presite.attr.func" + proc = assert_python_ok("-X", f"presite={entrypoint}", "-c", "pass") + self.assertEqual(proc.out.rstrip(), b"presite func") + + def test_dump_path_config(self): + # gh-151253: At the first import (import encodings) during Python + # startup, if the import fails, dump the Python path configuration. + nonexistent = '/nonexistent-python-path' + # Use -X frozen_modules=off to disable frozen encodings module + # on release build. + cmd = ["-X", "frozen_modules=off", "-c", "pass"] + proc = assert_python_failure(*cmd, PYTHONHOME=nonexistent) + self.assertIn(b'Python path configuration:', proc.err) + self.assertIn(f"PYTHONHOME = '{nonexistent}'".encode(), proc.err) + @unittest.skipIf(interpreter_requires_environment(), 'Cannot run -I tests when PYTHON env vars are required.') @@ -1330,11 +1423,9 @@ def check_string(self, code): self.assertNotEqual(proc.stderr, None) self.assertIn(b"\nSyntaxError", proc.stderr) - @unittest.expectedFailureIf(not support.is_android, "TODO: RUSTPYTHON") def test_tokenizer_error_with_stdin(self): self.check_string(b"(1+2+3") - @unittest.expectedFailureIf(not support.is_android, "TODO: RUSTPYTHON") def test_decoding_error_at_the_end_of_the_line(self): self.check_string(br"'\u1f'") diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py index 8dd64afcc00..1f9ead92bca 100644 --- a/Lib/test/test_cmd_line_script.py +++ b/Lib/test/test_cmd_line_script.py @@ -44,7 +44,6 @@ def f(): _loader = __loader__ if __loader__ is BuiltinImporter else type(__loader__) print('__loader__==%a' % _loader) print('__file__==%a' % __file__) -print('__cached__==%a' % __cached__) print('__package__==%r' % __package__) # Check PEP 451 details import os.path @@ -58,8 +57,6 @@ def f(): assertEqual(__spec__.parent, __package__) assertIdentical(__spec__.submodule_search_locations, None) assertEqual(__spec__.origin, __file__) - if __spec__.cached is not None: - assertEqual(__spec__.cached, __cached__) # Check the sys module import sys assertIdentical(globals(), sys.modules[__name__].__dict__) @@ -243,9 +240,8 @@ def test_script_abspath(self): def test_script_compiled(self): with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, 'script') - py_compile.compile(script_name, doraise=True) + pyc_file = import_helper.make_legacy_pyc(script_name, allow_compile=True) os.remove(script_name) - pyc_file = import_helper.make_legacy_pyc(script_name) self._check_script(pyc_file, pyc_file, pyc_file, script_dir, None, importlib.machinery.SourcelessFileLoader) @@ -260,9 +256,8 @@ def test_directory(self): def test_directory_compiled(self): with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') - py_compile.compile(script_name, doraise=True) + pyc_file = import_helper.make_legacy_pyc(script_name, allow_compile=True) os.remove(script_name) - pyc_file = import_helper.make_legacy_pyc(script_name) self._check_script(script_dir, pyc_file, script_dir, script_dir, '', importlib.machinery.SourcelessFileLoader) @@ -282,8 +277,8 @@ def test_zipfile(self): def test_zipfile_compiled_timestamp(self): with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') - compiled_name = py_compile.compile( - script_name, doraise=True, + compiled_name = script_name + 'c' + py_compile.compile(script_name, compiled_name, doraise=True, invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP) zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, run_name, zip_name, zip_name, '', @@ -292,8 +287,8 @@ def test_zipfile_compiled_timestamp(self): def test_zipfile_compiled_checked_hash(self): with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') - compiled_name = py_compile.compile( - script_name, doraise=True, + compiled_name = script_name + 'c' + py_compile.compile(script_name, compiled_name, doraise=True, invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH) zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, run_name, zip_name, zip_name, '', @@ -302,8 +297,8 @@ def test_zipfile_compiled_checked_hash(self): def test_zipfile_compiled_unchecked_hash(self): with os_helper.temp_dir() as script_dir: script_name = _make_test_script(script_dir, '__main__') - compiled_name = py_compile.compile( - script_name, doraise=True, + compiled_name = script_name + 'c' + py_compile.compile(script_name, compiled_name, doraise=True, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH) zip_name, run_name = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, run_name, zip_name, zip_name, '', @@ -356,9 +351,8 @@ def test_package_compiled(self): pkg_dir = os.path.join(script_dir, 'test_pkg') make_pkg(pkg_dir) script_name = _make_test_script(pkg_dir, '__main__') - compiled_name = py_compile.compile(script_name, doraise=True) + pyc_file = import_helper.make_legacy_pyc(script_name, allow_compile=True) os.remove(script_name) - pyc_file = import_helper.make_legacy_pyc(script_name) self._check_script(["-m", "test_pkg"], pyc_file, pyc_file, script_dir, 'test_pkg', importlib.machinery.SourcelessFileLoader, @@ -557,7 +551,7 @@ def test_pep_409_verbiage(self): self.assertStartsWith(text[1], ' File ') self.assertStartsWith(text[3], 'NameError') - @unittest.expectedFailureIf(sys.platform in ("android", "linux"), "TODO: RUSTPYTHON") + @unittest.expectedFailureIf(sys.platform == "android", "TODO: RUSTPYTHON") def test_non_ascii(self): # Apple platforms deny the creation of a file with an invalid UTF-8 name. # Windows allows creating a name with an arbitrary bytes name, but @@ -811,6 +805,30 @@ def test_script_as_dev_fd(self): out, err = p.communicate() self.assertEqual(out, b"12345678912345678912345\n") + def test_filter_syntax_warnings_by_module(self): + filename = support.findfile('test_import/data/syntax_warnings.py') + rc, out, err = assert_python_ok( + '-Werror', + '-Walways:::__main__', + '-Werror:::test.test_import.data.syntax_warnings', + '-Werror:::syntax_warnings', + filename) + self.assertEqual(err.count(b': SyntaxWarning: '), 6) + + def test_zipfile_run_filter_syntax_warnings_by_module(self): + filename = support.findfile('test_import/data/syntax_warnings.py') + with open(filename, 'rb') as f: + source = f.read() + with os_helper.temp_dir() as script_dir: + zip_name, _ = make_zip_pkg( + script_dir, 'test_zip', 'test_pkg', '__main__', source) + rc, out, err = assert_python_ok( + '-Werror', + '-Walways:::__main__', + '-Werror:::test_pkg.__main__', + os.path.join(zip_name, 'test_pkg') + ) + self.assertEqual(err.count(b': SyntaxWarning: '), 6) def tearDownModule(): diff --git a/Lib/test/test_code.py b/Lib/test/test_code.py index 6c26259cf15..0af191cb5df 100644 --- a/Lib/test/test_code.py +++ b/Lib/test/test_code.py @@ -87,7 +87,7 @@ freevars: () nlocals: 0 flags: 67108867 -consts: ("'doc string'", 'None') +consts: ("'doc string'",) >>> def keywordonly_args(a,b,*,k1): ... return a,b,k1 @@ -161,7 +161,7 @@ freevars: () nlocals: 3 flags: 67108995 -consts: ("'This is a docstring from async function'", 'None') +consts: ("'This is a docstring from async function'",) >>> def no_docstring(x, y, z): ... return x + "hello" + y + z + "world" @@ -423,14 +423,6 @@ def func(): new_code = code = func.__code__.replace(co_linetable=b'') self.assertEqual(list(new_code.co_lines()), []) - @unittest.expectedFailure # TODO: RUSTPYTHON; co_lnotab intentionally not implemented (deprecated since 3.12) - def test_co_lnotab_is_deprecated(self): # TODO: remove in 3.14 - def func(): - pass - - with self.assertWarns(DeprecationWarning): - func.__code__.co_lnotab - @unittest.skipIf(_testinternalcapi is None, '_testinternalcapi is missing') def test_returns_only_none(self): value = True @@ -540,7 +532,7 @@ def test_co_positions_artificial_instructions(self): ], [ ("PUSH_EXC_INFO", None), - ("LOAD_CONST", None), # artificial 'None' + ("LOAD_COMMON_CONSTANT", None), # artificial 'None' ("STORE_NAME", "e"), # XX: we know the location for this ("DELETE_NAME", "e"), ("RERAISE", 1), @@ -1165,6 +1157,18 @@ def test_stateless(self): with self.assertRaises(Exception): _testinternalcapi.verify_stateless_code(func) + def test_code_richcompare_raise_exception(self): + class BadStr(str): + def __eq__(self, _): + raise RuntimeError("Poison!") + + __hash__ = str.__hash__ + + c1 = compile("pass", "test", "exec") + c2 = c1.replace(co_name=BadStr("poison")) + c3 = compile("pass", "poison", "exec") + with self.assertRaises(RuntimeError): + c2 == c3 def isinterned(s): return s is sys.intern(('_' + s + '_')[1:-1]) @@ -1438,6 +1442,7 @@ def f(): co_code=bytes( [ dis.opmap["RESUME"], 0, + dis.opmap["CACHE"], 0, dis.opmap["LOAD_COMMON_CONSTANT"], 0, dis.opmap["RAISE_VARARGS"], 1, ] @@ -1446,7 +1451,7 @@ def f(): [ (1 << 7) | (PY_CODE_LOCATION_INFO_NO_COLUMNS << 3) - | (3 - 1), + | (4 - 1), 0, ] ), @@ -1454,7 +1459,7 @@ def f(): self.assertRaises(AssertionError, f) self.assertEqual( list(f.__code__.co_positions()), - 3 * [(42, 42, None, None)], + 4 * [(42, 42, None, None)], ) @cpython_only diff --git a/Lib/test/test_code_module.py b/Lib/test/test_code_module.py index fb519878cd8..3642b47c2c1 100644 --- a/Lib/test/test_code_module.py +++ b/Lib/test/test_code_module.py @@ -111,7 +111,6 @@ def test_syntax_error(self): self.assertIsNone(self.sysmod.last_value.__traceback__) self.assertIs(self.sysmod.last_exc, self.sysmod.last_value) - @unittest.expectedFailure # TODO: RUSTPYTHON; - 'IndentationError: unexpected indentation'] def test_indentation_error(self): self.infunc.side_effect = [" 1", EOFError('Finished')] self.console.interact() @@ -187,7 +186,6 @@ def test_sysexcepthook_syntax_error(self): ' ^\n', 'SyntaxError: invalid syntax\n']) - @unittest.expectedFailure # TODO: RUSTPYTHON; + 'IndentationError: unexpected indent\n'] def test_sysexcepthook_indentation_error(self): self.infunc.side_effect = [" 1", EOFError('Finished')] hook = mock.Mock() diff --git a/Lib/test/test_codeccallbacks.py b/Lib/test/test_codeccallbacks.py index f6f45b230c1..7ab8eea0142 100644 --- a/Lib/test/test_codeccallbacks.py +++ b/Lib/test/test_codeccallbacks.py @@ -1,3 +1,4 @@ +from _codecs import _unregister_error as _codecs_unregister_error import codecs import html.entities import itertools @@ -754,8 +755,18 @@ def test_badandgoodsurrogatepassexceptions(self): (s[:1], 1 + n) ) - # TODO: RUSTPYTHON - @unittest.expectedFailure + def test_surrogatepass_truncated_encoding_name(self): + handler = codecs.lookup_error('surrogatepass') + for width in (16, 32): + encoding = f'utf-{width}-' + data = (0xd800).to_bytes(width // 8, 'little') + for exc in (UnicodeEncodeError(encoding, '\ud800', 0, 1, 'test'), + UnicodeDecodeError(encoding, data, 0, len(data), 'test')): + with self.subTest(encoding=encoding, error=type(exc).__name__): + with self.assertRaises(type(exc)) as cm: + handler(exc) + self.assertIs(cm.exception, exc) + def test_badhandlerresults(self): results = ( 42, "foo", (1,2,3), ("foo", 1, 3), ("foo", None), ("foo",), ("foo", 1, 3), ("foo", None), ("foo",) ) encs = ("ascii", "latin-1", "iso-8859-1", "iso-8859-15") @@ -798,8 +809,6 @@ def test_lookup(self): codecs.lookup_error("namereplace") ) - # TODO: RUSTPYTHON - @unittest.expectedFailure def test_encode_nonascii_replacement(self): def handle(exc): if isinstance(exc, UnicodeEncodeError): @@ -1041,8 +1050,6 @@ def __getitem__(self, key): self.assertRaises(ValueError, codecs.charmap_encode, "\xff", err, D()) self.assertRaises(TypeError, codecs.charmap_encode, "\xff", err, {0xff: 300}) - # TODO: RUSTPYTHON - @unittest.expectedFailure def test_decodehelper_bug36819(self): handler = RepeatedPosReturn("x") codecs.register_error("test.bug36819", handler.handle) @@ -1130,7 +1137,7 @@ def test_bug828737(self): text = 'abcghi'*n text.translate(charmap) - def test_mutatingdecodehandler(self): + def test_mutating_decode_handler(self): baddata = [ ("ascii", b"\xff"), ("utf-7", b"++"), @@ -1165,6 +1172,42 @@ def mutating(exc): for (encoding, data) in baddata: self.assertEqual(data.decode(encoding, "test.mutating"), "\u4242") + def test_mutating_decode_handler_unicode_escape(self): + decode = codecs.unicode_escape_decode + def mutating(exc): + if isinstance(exc, UnicodeDecodeError): + r = data.get(exc.object[:exc.end]) + if r is not None: + exc.object = r[0] + exc.object[exc.end:] + return ('\u0404', r[1]) + raise AssertionError("don't know how to handle %r" % exc) + + codecs.register_error('test.mutating2', mutating) + data = { + br'\x0': (b'\\', 0), + br'\x3': (b'xxx\\', 3), + br'\x5': (b'x\\', 1), + } + def check(input, expected, msg): + with self.assertWarns(DeprecationWarning) as cm: + self.assertEqual(decode(input, 'test.mutating2'), (expected, len(input))) + self.assertIn(msg, str(cm.warning)) + + check(br'\x0n\z', '\u0404\n\\z', r'"\z" is an invalid escape sequence') + check(br'\x0n\501', '\u0404\n\u0141', r'"\501" is an invalid octal escape sequence') + check(br'\x0z', '\u0404\\z', r'"\z" is an invalid escape sequence') + + check(br'\x3n\zr', '\u0404\n\\zr', r'"\z" is an invalid escape sequence') + check(br'\x3zr', '\u0404\\zr', r'"\z" is an invalid escape sequence') + check(br'\x3z5', '\u0404\\z5', r'"\z" is an invalid escape sequence') + check(memoryview(br'\x3z5x')[:-1], '\u0404\\z5', r'"\z" is an invalid escape sequence') + check(memoryview(br'\x3z5xy')[:-2], '\u0404\\z5', r'"\z" is an invalid escape sequence') + + check(br'\x5n\z', '\u0404\n\\z', r'"\z" is an invalid escape sequence') + check(br'\x5n\501', '\u0404\n\u0141', r'"\501" is an invalid octal escape sequence') + check(br'\x5z', '\u0404\\z', r'"\z" is an invalid escape sequence') + check(memoryview(br'\x5zy')[:-1], '\u0404\\z', r'"\z" is an invalid escape sequence') + # issue32583 def test_crashing_decode_handler(self): # better generating one more character to fill the extra space slot @@ -1216,7 +1259,6 @@ def replace_with_long(exc): '\ufffd\x00\x00' ) - def test_fake_error_class(self): handlers = [ codecs.strict_errors, @@ -1241,6 +1283,31 @@ class FakeUnicodeError(Exception): with self.assertRaises((TypeError, FakeUnicodeError)): handler(FakeUnicodeError()) + def test_reject_unregister_builtin_error_handler(self): + for name in [ + 'strict', 'ignore', 'replace', 'backslashreplace', 'namereplace', + 'xmlcharrefreplace', 'surrogateescape', 'surrogatepass', + ]: + with self.subTest(name): + self.assertRaises(ValueError, _codecs_unregister_error, name) + + def test_unregister_custom_error_handler(self): + def custom_handler(exc): + raise exc + + custom_name = 'test.test_unregister_custom_error_handler' + self.assertRaises(LookupError, codecs.lookup_error, custom_name) + codecs.register_error(custom_name, custom_handler) + self.assertIs(codecs.lookup_error(custom_name), custom_handler) + self.assertTrue(_codecs_unregister_error(custom_name)) + self.assertRaises(LookupError, codecs.lookup_error, custom_name) + + def test_unregister_custom_unknown_error_handler(self): + unknown_name = 'test.test_unregister_custom_unknown_error_handler' + self.assertRaises(LookupError, codecs.lookup_error, unknown_name) + self.assertFalse(_codecs_unregister_error(unknown_name)) + self.assertRaises(LookupError, codecs.lookup_error, unknown_name) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py index fd21c7b05b0..296dfb60070 100644 --- a/Lib/test/test_codecs.py +++ b/Lib/test/test_codecs.py @@ -13,6 +13,7 @@ from test import support from test.support import os_helper +from test.support import warnings_helper try: import _testlimitedcapi @@ -1622,6 +1623,15 @@ def test_builtin_encode(self): self.assertEqual("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org") self.assertEqual("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.") + @support.subTests(['unicode', 'encoded'], [ + ('\N{CHEROKEE LETTER A}\N{CHEROKEE LETTER A}', b"xn--58da"), + ('\N{GEORGIAN CAPITAL LETTER AN}.', b"xn--7md."), + ('\N{CYRILLIC LETTER PALOCHKA}.example', b"xn--d5a.example"), + ('\N{ROMAN NUMERAL REVERSED ONE HUNDRED}.example.', b"xn--q5g.example."), + ]) + def test_new_unicode_case_folding(self, unicode, encoded): + self.assertEqual(unicode.encode("idna"), encoded) + def test_builtin_encode_invalid(self): for case, expected in self.invalid_encode_testcases: with self.subTest(case=case, expected=expected): @@ -2768,7 +2778,6 @@ def test_partial(self): ] ) - class RawUnicodeEscapeTest(ReadTest, unittest.TestCase): encoding = "raw-unicode-escape" @@ -3460,7 +3469,6 @@ def test_cp20106(self): (b'(\xbf)', 'surrogatepass', None), )) - @unittest.expectedFailure # TODO: RUSTPYTHON; # TODO: RUSTPYTHON def test_cp_utf7(self): cp = 65000 self.check_encode(cp, ( @@ -3875,32 +3883,27 @@ def test_rot13_func(self): class CodecNameNormalizationTest(unittest.TestCase): """Test codec name normalization""" def test_codecs_lookup(self): - FOUND = (1, 2, 3, 4) - NOT_FOUND = (None, None, None, None) def search_function(encoding): - if encoding == "aaa_8": - return FOUND + if encoding.startswith("test."): + return (encoding, 2, 3, 4) else: - return NOT_FOUND + return None codecs.register(search_function) self.addCleanup(codecs.unregister, search_function) - self.assertEqual(FOUND, codecs.lookup('aaa_8')) - self.assertEqual(FOUND, codecs.lookup('AAA-8')) - self.assertEqual(FOUND, codecs.lookup('AAA---8')) - self.assertEqual(FOUND, codecs.lookup('AAA 8')) - self.assertEqual(FOUND, codecs.lookup('aaa\xe9\u20ac-8')) - self.assertEqual(NOT_FOUND, codecs.lookup('AAA.8')) - self.assertEqual(NOT_FOUND, codecs.lookup('AAA...8')) - self.assertEqual(NOT_FOUND, codecs.lookup('BBB-8')) - self.assertEqual(NOT_FOUND, codecs.lookup('BBB.8')) - self.assertEqual(NOT_FOUND, codecs.lookup('a\xe9\u20ac-8')) + self.assertEqual(codecs.lookup('test.aaa_8'), ('test.aaa_8', 2, 3, 4)) + self.assertEqual(codecs.lookup('TEST.AAA-8'), ('test.aaa-8', 2, 3, 4)) + self.assertEqual(codecs.lookup('TEST.AAA 8'), ('test.aaa-8', 2, 3, 4)) + self.assertEqual(codecs.lookup('TEST.AAA---8'), ('test.aaa---8', 2, 3, 4)) + self.assertEqual(codecs.lookup('TEST.AAA 8'), ('test.aaa---8', 2, 3, 4)) + self.assertEqual(codecs.lookup('TEST.AAA.8'), ('test.aaa.8', 2, 3, 4)) + self.assertEqual(codecs.lookup('TEST.AAA...8'), ('test.aaa...8', 2, 3, 4)) + with self.assertWarns(DeprecationWarning): + self.assertEqual(codecs.lookup('TEST.AAA\xe9\u20ac-8'), ('test.aaa\xe9\u20ac-8', 2, 3, 4)) def test_encodings_normalize_encoding(self): - # encodings.normalize_encoding() ignores non-ASCII characters. normalize = encodings.normalize_encoding self.assertEqual(normalize('utf_8'), 'utf_8') - self.assertEqual(normalize('utf\xE9\u20AC\U0010ffff-8'), 'utf_8') self.assertEqual(normalize('utf 8'), 'utf_8') # encodings.normalize_encoding() doesn't convert # characters to lower case. @@ -3908,6 +3911,11 @@ def test_encodings_normalize_encoding(self): self.assertEqual(normalize('utf.8'), 'utf.8') self.assertEqual(normalize('utf...8'), 'utf...8') + # Non-ASCII *encoding* is deprecated. + msg = "Support for non-ascii encoding names will be removed in 3.17" + with warnings_helper.check_warnings((msg, DeprecationWarning)): + self.assertEqual(normalize('utf\xE9\u20AC\U0010ffff-8'), 'utf_8') + class CodecCacheTest(unittest.TestCase): def test_cache_bounded(self): diff --git a/Lib/test/test_codeop.py b/Lib/test/test_codeop.py index 5976303ad3c..d57452602ce 100644 --- a/Lib/test/test_codeop.py +++ b/Lib/test/test_codeop.py @@ -373,7 +373,7 @@ def test_syntax_errors(self, compiler): def foo(x,x): pass """) - message = "duplicate argument 'x' in function definition" + message = "duplicate parameter 'x' in function definition" with self.assertRaisesRegex(SyntaxError, message): compiler(code, "", 'exec') diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py index c1dadc4e274..b1b2dd2ca5c 100644 --- a/Lib/test/test_collections.py +++ b/Lib/test/test_collections.py @@ -12,6 +12,7 @@ import string import sys from test import support +from test.support.import_helper import import_fresh_module import types import unittest @@ -26,7 +27,7 @@ from collections.abc import Set, MutableSet from collections.abc import Mapping, MutableMapping, KeysView, ItemsView, ValuesView from collections.abc import Sequence, MutableSequence -from collections.abc import ByteString, Buffer +from collections.abc import Buffer class TestUserObjects(unittest.TestCase): @@ -1935,6 +1936,14 @@ def assert_index_same(seq1, seq2, index_args): nativeseq, seqseq, (letter, start, stop)) def test_ByteString(self): + previous_sys_modules = sys.modules.copy() + self.addCleanup(sys.modules.update, previous_sys_modules) + + for module in "collections", "_collections_abc", "collections.abc": + sys.modules.pop(module, None) + + with self.assertWarns(DeprecationWarning): + from collections.abc import ByteString for sample in [bytes, bytearray]: with self.assertWarns(DeprecationWarning): self.assertIsInstance(sample(), ByteString) @@ -1956,6 +1965,14 @@ class X(ByteString): pass # No metaclass conflict class Z(ByteString, Awaitable): pass + def test_ByteString_attribute_access(self): + collections_abc = import_fresh_module( + "collections.abc", + fresh=("collections", "_collections_abc") + ) + with self.assertWarns(DeprecationWarning): + collections_abc.ByteString + def test_Buffer(self): for sample in [bytes, bytearray, memoryview]: self.assertIsInstance(sample(b"x"), Buffer) @@ -2175,6 +2192,7 @@ def correctly_ordered(seq): self.assertTrue(correctly_ordered(p - q)) self.assertTrue(correctly_ordered(p | q)) self.assertTrue(correctly_ordered(p & q)) + self.assertTrue(correctly_ordered(p ^ q)) p, q = Counter(ps), Counter(qs) p += q @@ -2192,6 +2210,10 @@ def correctly_ordered(seq): p &= q self.assertTrue(correctly_ordered(p)) + p, q = Counter(ps), Counter(qs) + p ^= q + self.assertTrue(correctly_ordered(p)) + p, q = Counter(ps), Counter(qs) p.update(q) self.assertTrue(correctly_ordered(p)) @@ -2274,6 +2296,7 @@ def test_multiset_operations(self): (Counter.__sub__, lambda x, y: max(0, x-y)), (Counter.__or__, lambda x, y: max(0,x,y)), (Counter.__and__, lambda x, y: max(0, min(x,y))), + (Counter.__xor__, lambda x, y: max(0, max(x,y) - min(x,y))), ]: result = counterop(p, q) for x in elements: @@ -2291,6 +2314,7 @@ def test_multiset_operations(self): (Counter.__sub__, set.__sub__), (Counter.__or__, set.__or__), (Counter.__and__, set.__and__), + (Counter.__xor__, set.__xor__), ]: counter_result = counterop(p, q) set_result = setop(set(p.elements()), set(q.elements())) @@ -2309,6 +2333,7 @@ def test_inplace_operations(self): (Counter.__isub__, Counter.__sub__), (Counter.__ior__, Counter.__or__), (Counter.__iand__, Counter.__and__), + (Counter.__ixor__, Counter.__xor__), ]: c = p.copy() c_id = id(c) @@ -2384,6 +2409,7 @@ def test_multiset_operations_equivalent_to_set_operations(self): self.assertEqual(set(cp - cq), sp - sq) self.assertEqual(set(cp | cq), sp | sq) self.assertEqual(set(cp & cq), sp & sq) + self.assertEqual(set(cp ^ cq), sp ^ sq) self.assertEqual(cp == cq, sp == sq) self.assertEqual(cp != cq, sp != sq) self.assertEqual(cp <= cq, sp <= sq) @@ -2397,6 +2423,8 @@ def test_eq(self): def test_le(self): self.assertTrue(Counter(a=3, b=2, c=0) <= Counter('ababa')) + self.assertTrue(Counter() <= Counter(c=1)) + self.assertFalse(Counter() <= Counter(c=-1)) self.assertFalse(Counter(a=3, b=2) <= Counter('babab')) def test_lt(self): @@ -2405,12 +2433,48 @@ def test_lt(self): def test_ge(self): self.assertTrue(Counter(a=2, b=1, c=0) >= Counter('aab')) + self.assertTrue(Counter() >= Counter(c=-1)) + self.assertFalse(Counter() >= Counter(c=1)) self.assertFalse(Counter(a=3, b=2, c=0) >= Counter('aabd')) def test_gt(self): self.assertTrue(Counter(a=3, b=2, c=0) > Counter('aab')) self.assertFalse(Counter(a=2, b=1, c=0) > Counter('aab')) + def test_symmetric_difference(self): + population = (-4, -3, -2, -1, 0, 1, 2, 3, 4) + + for a, b1, b2, c in product(population, repeat=4): + p = Counter(a=a, b=b1) + q = Counter(b=b2, c=c) + r = p ^ q + + # Elementwise invariants + for k in ('a', 'b', 'c'): + self.assertEqual(r[k], max(p[k], q[k]) - min(p[k], q[k])) + self.assertEqual(r[k], abs(p[k] - q[k])) + + # Invariant for all positive, negative, and zero counts + self.assertEqual(r, (p - q) | (q - p)) + + # Invariant for non-negative counts + if a >= 0 and b1 >= 0 and b2 >= 0 and c >= 0: + self.assertEqual(r, (p | q) - (p & q)) + + # Zeros and negatives eliminated + self.assertTrue(all(value > 0 for value in r.values())) + + # Output preserves input order: p first and then q + keys = list(p) + list(q) + indices = [keys.index(k) for k in r] + self.assertEqual(indices, sorted(indices)) + + # Inplace operation matches binary operation + pp = Counter(p) + qq = Counter(q) + pp ^= qq + self.assertEqual(pp, r) + def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite(collections)) diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py index 021c3622566..63edef0405f 100644 --- a/Lib/test/test_compile.py +++ b/Lib/test/test_compile.py @@ -724,8 +724,7 @@ def test_yet_more_evil_still_undecodable(self): @support.cpython_only @unittest.skipIf(support.is_wasi, "exhausts limited stack on WASI") - @support.run_with_limited_c_stack( - 100_000 if sys.platform == "android" else 500_000) + @support.skip_if_huge_c_stack(100_000 if sys.platform == "android" else 500_000) @support.skip_emscripten_stack_overflow() def test_compiler_recursion_limit(self): # Compiler frames are small @@ -841,8 +840,10 @@ def f(): else: return "unused" - self.assertEqual(f.__code__.co_consts, - (f.__doc__, "used")) + if f.__doc__ is None: + self.assertEqual(f.__code__.co_consts, (True, "used")) + else: + self.assertEqual(f.__code__.co_consts, (f.__doc__, "used")) @support.cpython_only def test_remove_unused_consts_no_docstring(self): @@ -887,7 +888,11 @@ def test_strip_unused_None(self): def f1(): "docstring" return 42 - self.assertEqual(f1.__code__.co_consts, (f1.__doc__,)) + + if f1.__doc__ is None: + self.assertEqual(f1.__code__.co_consts, (42,)) + else: + self.assertEqual(f1.__code__.co_consts, (f1.__doc__,)) # This is a regression test for a CPython specific peephole optimizer # implementation bug present in a few releases. It's assertion verifies @@ -1294,7 +1299,7 @@ def return_genexp(): x in y) - genexp_lines = [0, 4, 2, 0, 4] + genexp_lines = [4, 0, 4, 2, 0, 4] genexp_code = return_genexp.__code__.co_consts[0] code_lines = self.get_code_lines(genexp_code) @@ -1377,6 +1382,28 @@ def f(): self.check_line_numbers(f.__code__, 'JUMP_BACKWARD') + def test_backward_jump_conditional_in_loop_in_try(self): + # gh-130279: The jumps in a loop body, including the backward jump + # for the untaken branch of a conditional at the end of the body, + # must be covered by the exception handler of the enclosing try. + def f(items): + try: + for x in items: + if x < 0: + raise ValueError(x) + except KeyboardInterrupt: + return 'handled' + + bytecode = dis.Bytecode(f) + jumps = [instr for instr in bytecode + if instr.opcode in dis.hasjump] + self.assertTrue(jumps) + for instr in jumps: + with self.subTest(instr=instr): + self.assertTrue( + any(entry.start <= instr.offset < entry.end + for entry in bytecode.exception_entries)) + def test_big_dict_literal(self): # The compiler has a flushing point in "compiler_dict" that calls compiles # a portion of the dictionary literal when the loop that iterates over the items @@ -1629,6 +1656,17 @@ def test_remove_redundant_nop_edge_case(self): def f(): a if (1 if b else c) else d + def test_lineno_propagation_empty_blocks(self): + # Smoke test. See gh-138714. + def f(): + while name: + try: + break + except: + pass + else: + 1 if 1 else 1 + def test_global_declaration_in_except_used_in_else(self): # See gh-111123 code = textwrap.dedent("""\ @@ -1733,6 +1771,30 @@ def test_compile_warning_in_finally(self): self.assertEqual(wm.category, SyntaxWarning) self.assertIn("\"is\" with 'int' literal", str(wm.message)) + def test_filter_syntax_warnings_by_module(self): + filename = support.findfile('test_import/data/syntax_warnings.py') + with open(filename, 'rb') as f: + source = f.read() + module_re = r'test\.test_import\.data\.syntax_warnings\z' + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=module_re) + compile(source, filename, 'exec') + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) + + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'package\.module\z') + warnings.filterwarnings('error', module=module_re) + compile(source, filename, 'exec', module='package.module') + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) + @support.subTests('src', [ textwrap.dedent(""" def f(): @@ -2419,8 +2481,8 @@ def test_lambda_return_position(self): for i, pos in enumerate(positions): with self.subTest(i=i, pos=pos): start_line, end_line, start_col, end_col = pos - if i == 0 and start_col == end_col == 0: - # ignore the RESUME in the beginning + if i <= 1: + # ignore the RESUME and CACHE in the beginning continue self.assertEqual(start_line, 1) self.assertEqual(end_line, 1) @@ -2446,12 +2508,13 @@ def f(): start_line, end_line, _, _ = instr.positions self.assertEqual(start_line, end_line) - # Expect four `LOAD_CONST None` instructions: + # Expect four `None`-loading instructions: # three for the no-exception __exit__ call, and one for the return. # They should all have the locations of the context manager ('xyz'). load_none = [instr for instr in dis.get_instructions(f) if - instr.opname == 'LOAD_CONST' and instr.argval is None] + instr.opname in ('LOAD_CONST', 'LOAD_COMMON_CONSTANT') + and instr.argval is None] return_value = [instr for instr in dis.get_instructions(f) if instr.opname == 'RETURN_VALUE'] diff --git a/Lib/test/test_compileall.py b/Lib/test/test_compileall.py index be5e7d7feee..9a6ca2be162 100644 --- a/Lib/test/test_compileall.py +++ b/Lib/test/test_compileall.py @@ -28,11 +28,15 @@ from test import support from test.support import os_helper from test.support import script_helper -from test.test_py_compile import without_source_date_epoch -from test.test_py_compile import SourceDateEpochTestMeta +from test.support.os_helper import without_source_date_epoch +from test.support.os_helper import SourceDateEpochTestMeta from test.support.os_helper import FakePath +if sys.implementation.cache_tag is None: + raise unittest.SkipTest('requires sys.implementation.cache_tag is not None') + + def get_pyc(script, opt): if not opt: # Replace None and 0 with '' @@ -594,7 +598,6 @@ def assertNotCompiled(self, fn): path = importlib.util.cache_from_source(fn) self.assertFalse(os.path.exists(path)) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_no_args_compiles_path(self): # Note that -l is implied for the no args case. bazfn = script_helper.make_script(self.directory, 'baz', '') @@ -604,7 +607,6 @@ def test_no_args_compiles_path(self): self.assertNotCompiled(self.initfn) self.assertNotCompiled(self.barfn) - @unittest.expectedFailure # TODO: RUSTPYTHON @without_source_date_epoch # timestamp invalidation test @support.requires_resource('cpu') def test_no_args_respects_force_flag(self): diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py index 6dc27ff07a3..1916260465c 100644 --- a/Lib/test/test_complex.py +++ b/Lib/test/test_complex.py @@ -1,6 +1,8 @@ +import errno import unittest import sys from test import support +from test.support import import_helper from test.support.testcase import ComplexesAreIdenticalMixin from test.support.numbers import ( VALID_UNDERSCORE_LITERALS, @@ -9,6 +11,7 @@ from random import random from math import isnan, copysign +import cmath import operator INF = float("inf") @@ -244,7 +247,6 @@ def test_richcompare(self): self.assertIs(operator.ne(1+1j, 2+2j), True) self.assertIs(operator.eq(1+1j, 2.0), False) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: True is not False def test_richcompare_boundaries(self): def check(n, deltas, is_equal, imag = 0.0): for delta in deltas: @@ -456,7 +458,6 @@ def test_boolcontext(self): def test_conjugate(self): self.assertEqual(complex(5.3, 9.8).conjugate(), 5.3-9.8j) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: DeprecationWarning not triggered def test_constructor(self): def check(z, x, y): self.assertIs(type(z), complex) @@ -506,17 +507,25 @@ def check(z, x, y): with self.assertWarnsRegex(DeprecationWarning, "argument 'imag' must be a real number, not complex"): check(complex(0.0, 4.25j), -4.25, 0.0) - with self.assertWarnsRegex(DeprecationWarning, - "argument 'real' must be a real number, not complex"): + with (self.assertWarnsRegex(DeprecationWarning, + "argument 'real' must be a real number, not complex"), + self.assertWarnsRegex(DeprecationWarning, + "argument 'imag' must be a real number, not complex")): check(complex(4.25+0j, 0j), 4.25, 0.0) - with self.assertWarnsRegex(DeprecationWarning, - "argument 'real' must be a real number, not complex"): + with (self.assertWarnsRegex(DeprecationWarning, + "argument 'real' must be a real number, not complex"), + self.assertWarnsRegex(DeprecationWarning, + "argument 'imag' must be a real number, not complex")): check(complex(4.25j, 0j), 0.0, 4.25) - with self.assertWarnsRegex(DeprecationWarning, - "argument 'real' must be a real number, not complex"): + with (self.assertWarnsRegex(DeprecationWarning, + "argument 'real' must be a real number, not complex"), + self.assertWarnsRegex(DeprecationWarning, + "argument 'imag' must be a real number, not complex")): check(complex(0j, 4.25+0j), 0.0, 4.25) - with self.assertWarnsRegex(DeprecationWarning, - "argument 'real' must be a real number, not complex"): + with (self.assertWarnsRegex(DeprecationWarning, + "argument 'real' must be a real number, not complex"), + self.assertWarnsRegex(DeprecationWarning, + "argument 'imag' must be a real number, not complex")): check(complex(0j, 4.25j), -4.25, 0.0) check(complex(real=4.25), 4.25, 0.0) @@ -783,8 +792,30 @@ def test_abs(self): for num in nums: self.assertAlmostEqual((num.real**2 + num.imag**2) ** 0.5, abs(num)) + for x in 0.0, -0.0, INF, -INF, NAN: + for y in 0.0, -0.0, INF, -INF, NAN: + with self.subTest(x=x, y=y): + z = complex(x, y) + r = abs(z) + if cmath.isfinite(z): + self.assertFloatsAreIdentical(r, 0.0) + elif cmath.isinf(z): + self.assertEqual(r, INF) + else: + self.assertTrue(cmath.isnan(z)) + self.assertTrue(isnan(r)) + self.assertRaises(OverflowError, abs, complex(DBL_MAX, DBL_MAX)) + def test_abs_errno_handling(self): + _testcapi = import_helper.import_module('_testcapi') + z = complex('nan') + _testcapi.set_errno(errno.ERANGE) + try: + self.assertTrue(isnan(abs(z))) + finally: + _testcapi.set_errno(0) + def test_repr_str(self): def test(v, expected, test_fn=self.assertEqual): test_fn(repr(v), expected) diff --git a/Lib/test/test_concurrent_futures/executor.py b/Lib/test/test_concurrent_futures/executor.py index 6a26d695b0b..a37c4d45f07 100644 --- a/Lib/test/test_concurrent_futures/executor.py +++ b/Lib/test/test_concurrent_futures/executor.py @@ -1,12 +1,11 @@ import itertools import threading import time -import unittest import weakref from concurrent import futures from operator import add from test import support -from test.support import Py_GIL_DISABLED +from test.support import Py_GIL_DISABLED, warnings_helper def mul(x, y): @@ -41,12 +40,15 @@ def __len__(self): class ExecutorTest: + # Executor.shutdown() and context manager usage is tested by # ExecutorShutdownTest. + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_submit(self): future = self.executor.submit(pow, 2, 8) self.assertEqual(256, future.result()) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_submit_keyword(self): future = self.executor.submit(mul, 2, y=8) self.assertEqual(16, future.result()) @@ -57,6 +59,7 @@ def test_submit_keyword(self): with self.assertRaises(TypeError): self.executor.submit(arg=1) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map(self): self.assertEqual( list(self.executor.map(pow, range(10), range(10))), @@ -66,12 +69,15 @@ def test_map(self): list(self.executor.map(pow, range(10), range(10), chunksize=3)), list(map(pow, range(10), range(10)))) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map_exception(self): i = self.executor.map(divmod, [1, 1, 1, 1], [2, 3, 0, 5]) self.assertEqual(i.__next__(), (0, 1)) self.assertEqual(i.__next__(), (0, 1)) - self.assertRaises(ZeroDivisionError, i.__next__) + with self.assertRaises(ZeroDivisionError): + i.__next__() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.requires_resource('walltime') def test_map_timeout(self): results = [] @@ -85,7 +91,9 @@ def test_map_timeout(self): else: self.fail('expected TimeoutError') - self.assertEqual([None, None], results) + # gh-110097: On heavily loaded systems, the launch of the worker may + # take longer than the specified timeout. + self.assertIn(results, ([None, None], [None], [])) def test_map_buffersize_type_validation(self): for buffersize in ("foo", 2.0): @@ -96,7 +104,6 @@ def test_map_buffersize_type_validation(self): ): self.executor.map(str, range(4), buffersize=buffersize) - def test_map_buffersize_value_validation(self): for buffersize in (0, -1): with self.subTest(buffersize=buffersize): @@ -106,7 +113,7 @@ def test_map_buffersize_value_validation(self): ): self.executor.map(str, range(4), buffersize=buffersize) - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map_buffersize(self): ints = range(4) for buffersize in (1, 2, len(ints), len(ints) * 2): @@ -114,7 +121,7 @@ def test_map_buffersize(self): res = self.executor.map(str, ints, buffersize=buffersize) self.assertListEqual(list(res), ["0", "1", "2", "3"]) - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map_buffersize_on_multiple_iterables(self): ints = range(4) for buffersize in (1, 2, len(ints), len(ints) * 2): @@ -122,19 +129,34 @@ def test_map_buffersize_on_multiple_iterables(self): res = self.executor.map(add, ints, ints, buffersize=buffersize) self.assertListEqual(list(res), [0, 2, 4, 6]) - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map_buffersize_on_infinite_iterable(self): res = self.executor.map(str, itertools.count(), buffersize=2) self.assertEqual(next(res, None), "0") self.assertEqual(next(res, None), "1") self.assertEqual(next(res, None), "2") + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_map_buffersize_on_multiple_infinite_iterables(self): + res = self.executor.map( + add, + itertools.count(), + itertools.count(), + buffersize=2 + ) + self.assertEqual(next(res, None), 0) + self.assertEqual(next(res, None), 2) + self.assertEqual(next(res, None), 4) def test_map_buffersize_on_empty_iterable(self): res = self.executor.map(str, [], buffersize=2) self.assertIsNone(next(res, None)) + def test_map_buffersize_without_iterable(self): + res = self.executor.map(str, buffersize=2) + self.assertIsNone(next(res, None)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map_buffersize_when_buffer_is_full(self): ints = iter(range(4)) buffersize = 2 @@ -146,7 +168,7 @@ def test_map_buffersize_when_buffer_is_full(self): msg="should have fetched only `buffersize` elements from `ints`.", ) - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_shutdown_race_issue12456(self): # Issue #12456: race condition at shutdown where trying to post a # sentinel in the call queue blocks (the queue is full while processes @@ -154,6 +176,7 @@ def test_shutdown_race_issue12456(self): self.executor.map(str, [2] * (self.worker_count + 1)) self.executor.shutdown() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.cpython_only def test_no_stale_references(self): # Issue #16284: check that the executors don't unnecessarily hang onto @@ -198,6 +221,7 @@ def test_max_workers_negative(self): "than 0"): self.executor_type(max_workers=number) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_free_reference(self): # Issue #14406: Result iterator should not keep an internal # reference to result objects. @@ -210,6 +234,7 @@ def test_free_reference(self): if wr() is None: break + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_swallows_falsey_exceptions(self): # see gh-132063: Prevent exceptions that evaluate as falsey # from being ignored. diff --git a/Lib/test/test_concurrent_futures/test_as_completed.py b/Lib/test/test_concurrent_futures/test_as_completed.py index c90b0021d85..31c7bb3ebd8 100644 --- a/Lib/test/test_concurrent_futures/test_as_completed.py +++ b/Lib/test/test_concurrent_futures/test_as_completed.py @@ -7,6 +7,7 @@ CANCELLED_AND_NOTIFIED, FINISHED, Future) from test import support +from test.support import warnings_helper from .util import ( PENDING_FUTURE, RUNNING_FUTURE, @@ -19,6 +20,7 @@ def mul(x, y): class AsCompletedTests: + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_no_timeout(self): future1 = self.executor.submit(mul, 2, 21) future2 = self.executor.submit(mul, 7, 6) @@ -35,6 +37,7 @@ def test_no_timeout(self): future1, future2]), completed) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_future_times_out(self): """Test ``futures.as_completed`` timing out before completing it's final future.""" @@ -62,6 +65,7 @@ def test_future_times_out(self): # Check that ``future`` wasn't completed. self.assertEqual(completed_futures, already_completed) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_duplicate_futures(self): # Issue 20367. Duplicate futures should not raise exceptions or give # duplicate responses. diff --git a/Lib/test/test_concurrent_futures/test_deadlock.py b/Lib/test/test_concurrent_futures/test_deadlock.py index dcc1d68563a..5cd84f7e430 100644 --- a/Lib/test/test_concurrent_futures/test_deadlock.py +++ b/Lib/test/test_concurrent_futures/test_deadlock.py @@ -10,6 +10,7 @@ from concurrent.futures.process import BrokenProcessPool, _ThreadWakeup from test import support +from test.support import warnings_helper from .util import ( create_executor_tests, setup_module, @@ -111,9 +112,9 @@ def _fail_on_deadlock(self, executor): print(f"\nTraceback:\n {tb}", file=sys.__stderr__) self.fail(f"Executor deadlock:\n\n{tb}") - - def _check_crash(self, error, func, *args, ignore_stderr=False): - # test for deadlock caused by crashes in a pool + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def _check_error(self, error, func, *args, ignore_stderr=False): + # test for deadlock caused by crashes or exiting in a pool self.executor.shutdown(wait=True) executor = self.executor_type( @@ -138,49 +139,52 @@ def _check_crash(self, error, func, *args, ignore_stderr=False): def test_error_at_task_pickle(self): # Check problem occurring while pickling a task in # the task_handler thread - self._check_crash(PicklingError, id, ErrorAtPickle()) + self._check_error(PicklingError, id, ErrorAtPickle()) def test_exit_at_task_unpickle(self): # Check problem occurring while unpickling a task on workers - self._check_crash(BrokenProcessPool, id, ExitAtUnpickle()) + self._check_error(BrokenProcessPool, id, ExitAtUnpickle()) def test_error_at_task_unpickle(self): # gh-109832: Restore stderr overridden by _raise_error_ignore_stderr() self.addCleanup(setattr, sys, 'stderr', sys.stderr) # Check problem occurring while unpickling a task on workers - self._check_crash(BrokenProcessPool, id, ErrorAtUnpickle()) + self._check_error(BrokenProcessPool, id, ErrorAtUnpickle()) + @support.skip_if_sanitizer("UBSan: explicit SIGSEV not allowed", ub=True) def test_crash_at_task_unpickle(self): # Check problem occurring while unpickling a task on workers - self._check_crash(BrokenProcessPool, id, CrashAtUnpickle()) + self._check_error(BrokenProcessPool, id, CrashAtUnpickle()) + @support.skip_if_sanitizer("UBSan: explicit SIGSEV not allowed", ub=True) def test_crash_during_func_exec_on_worker(self): # Check problem occurring during func execution on workers - self._check_crash(BrokenProcessPool, _crash) + self._check_error(BrokenProcessPool, _crash) def test_exit_during_func_exec_on_worker(self): # Check problem occurring during func execution on workers - self._check_crash(SystemExit, _exit) + self._check_error(SystemExit, _exit) def test_error_during_func_exec_on_worker(self): # Check problem occurring during func execution on workers - self._check_crash(RuntimeError, _raise_error, RuntimeError) + self._check_error(RuntimeError, _raise_error, RuntimeError) + @support.skip_if_sanitizer("UBSan: explicit SIGSEV not allowed", ub=True) def test_crash_during_result_pickle_on_worker(self): # Check problem occurring while pickling a task result # on workers - self._check_crash(BrokenProcessPool, _return_instance, CrashAtPickle) + self._check_error(BrokenProcessPool, _return_instance, CrashAtPickle) def test_exit_during_result_pickle_on_worker(self): # Check problem occurring while pickling a task result # on workers - self._check_crash(SystemExit, _return_instance, ExitAtPickle) + self._check_error(SystemExit, _return_instance, ExitAtPickle) def test_error_during_result_pickle_on_worker(self): # Check problem occurring while pickling a task result # on workers - self._check_crash(PicklingError, _return_instance, ErrorAtPickle) + self._check_error(PicklingError, _return_instance, ErrorAtPickle) def test_error_during_result_unpickle_in_result_handler(self): # gh-109832: Restore stderr overridden by _raise_error_ignore_stderr() @@ -188,15 +192,17 @@ def test_error_during_result_unpickle_in_result_handler(self): # Check problem occurring while unpickling a task in # the result_handler thread - self._check_crash(BrokenProcessPool, + self._check_error(BrokenProcessPool, _return_instance, ErrorAtUnpickle, ignore_stderr=True) def test_exit_during_result_unpickle_in_result_handler(self): # Check problem occurring while unpickling a task in # the result_handler thread - self._check_crash(BrokenProcessPool, _return_instance, ExitAtUnpickle) + self._check_error(BrokenProcessPool, _return_instance, ExitAtUnpickle) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + @support.skip_if_sanitizer("UBSan: explicit SIGSEV not allowed", ub=True) def test_shutdown_deadlock(self): # Test that the pool calling shutdown do not cause deadlock # if a worker fails after the shutdown call. @@ -209,6 +215,7 @@ def test_shutdown_deadlock(self): with self.assertRaises(BrokenProcessPool): f.result() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_shutdown_deadlock_pickle(self): # Test that the pool calling shutdown with wait=False does not cause # a deadlock if a task fails at pickle after the shutdown call. @@ -235,8 +242,10 @@ def test_shutdown_deadlock_pickle(self): # dangling threads executor_manager.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + @support.skip_if_sanitizer("UBSan: explicit SIGSEV not allowed", ub=True) def test_crash_big_data(self): - # Test that there is a clean exception instad of a deadlock when a + # Test that there is a clean exception instead of a deadlock when a # child process crashes while some data is being written into the # queue. # https://github.com/python/cpython/issues/94777 @@ -250,6 +259,7 @@ def test_crash_big_data(self): executor.shutdown(wait=True) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_gh105829_should_not_deadlock_if_wakeup_pipe_full(self): # Issue #105829: The _ExecutorManagerThread wakeup pipe could # fill up and block. See: https://github.com/python/cpython/issues/105829 diff --git a/Lib/test/test_concurrent_futures/test_future.py b/Lib/test/test_concurrent_futures/test_future.py index 4066ea1ee4b..06b11a3bacf 100644 --- a/Lib/test/test_concurrent_futures/test_future.py +++ b/Lib/test/test_concurrent_futures/test_future.py @@ -6,6 +6,7 @@ PENDING, RUNNING, CANCELLED, CANCELLED_AND_NOTIFIED, FINISHED, Future) from test import support +from test.support import threading_helper from .util import ( PENDING_FUTURE, RUNNING_FUTURE, CANCELLED_FUTURE, @@ -282,6 +283,62 @@ def test_multiple_set_exception(self): self.assertEqual(f.exception(), e) + def test_get_snapshot(self): + """Test the _get_snapshot method for atomic state retrieval.""" + # Test with a pending future + f = Future() + done, cancelled, result, exception = f._get_snapshot() + self.assertFalse(done) + self.assertFalse(cancelled) + self.assertIsNone(result) + self.assertIsNone(exception) + + # Test with a finished future (successful result) + f = Future() + f.set_result(42) + done, cancelled, result, exception = f._get_snapshot() + self.assertTrue(done) + self.assertFalse(cancelled) + self.assertEqual(result, 42) + self.assertIsNone(exception) + + # Test with a finished future (exception) + f = Future() + exc = ValueError("test error") + f.set_exception(exc) + done, cancelled, result, exception = f._get_snapshot() + self.assertTrue(done) + self.assertFalse(cancelled) + self.assertIsNone(result) + self.assertIs(exception, exc) + + # Test with a cancelled future + f = Future() + f.cancel() + done, cancelled, result, exception = f._get_snapshot() + self.assertTrue(done) + self.assertTrue(cancelled) + self.assertIsNone(result) + self.assertIsNone(exception) + + # Test concurrent access (basic thread safety check) + f = Future() + f.set_result(100) + results = [] + + def get_snapshot(): + for _ in range(1000): + snapshot = f._get_snapshot() + results.append(snapshot) + + threads = [threading.Thread(target=get_snapshot) for _ in range(4)] + with threading_helper.start_threads(threads): + pass + # All snapshots should be identical for a finished future + expected = (True, False, 100, None) + for result in results: + self.assertEqual(result, expected) + def setUpModule(): setup_module() diff --git a/Lib/test/test_concurrent_futures/test_init.py b/Lib/test/test_concurrent_futures/test_init.py index df640929309..c9fedc72132 100644 --- a/Lib/test/test_concurrent_futures/test_init.py +++ b/Lib/test/test_concurrent_futures/test_init.py @@ -1,5 +1,6 @@ import contextlib import logging +import multiprocessing import queue import time import unittest @@ -11,6 +12,7 @@ from logging.handlers import QueueHandler from test import support +from test.support import warnings_helper from .util import ExecutorMixin, create_executor_tests, setup_module @@ -20,6 +22,10 @@ def init(x): global INITIALIZER_STATUS INITIALIZER_STATUS = x + # InterpreterPoolInitializerTest.test_initializer fails + # if we don't have a LOAD_GLOBAL. (It could be any global.) + # We will address this separately. + INITIALIZER_STATUS def get_init_status(): return INITIALIZER_STATUS @@ -44,6 +50,7 @@ def setUp(self): initargs=('initialized',)) super().setUp() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_initializer(self): futures = [self.executor.submit(get_init_status) for _ in range(self.worker_count)] @@ -70,6 +77,7 @@ def setUp(self): self.executor_kwargs = dict(initializer=init_fail) super().setUp() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_initializer(self): with self._assert_logged('ValueError: error in initializer'): try: @@ -140,6 +148,8 @@ def test_spawn(self): self._test(ProcessPoolSpawnFailingInitializerTest) @support.skip_if_sanitizer("TSAN doesn't support threads after fork", thread=True) + @unittest.skipUnless("forkserver" in multiprocessing.get_all_start_methods(), + "forkserver start method is not available") def test_forkserver(self): self._test(ProcessPoolForkserverFailingInitializerTest) diff --git a/Lib/test/test_concurrent_futures/test_interpreter_pool.py b/Lib/test/test_concurrent_futures/test_interpreter_pool.py index b8f1a0f3a29..853a363f19e 100644 --- a/Lib/test/test_concurrent_futures/test_interpreter_pool.py +++ b/Lib/test/test_concurrent_futures/test_interpreter_pool.py @@ -129,12 +129,12 @@ def test_init_script(self): """ os.write(w, b'\0') - executor = self.executor_type(initializer=initscript) - before_init = os.read(r, 100) - fut = executor.submit(script) - after_init = read_msg(r) - fut.result() - after_run = read_msg(r) + with self.executor_type(initializer=initscript) as executor: + before_init = os.read(r, 100) + fut = executor.submit(script) + after_init = read_msg(r) + fut.result() + after_run = read_msg(r) self.assertEqual(before_init, b'\0') self.assertEqual(after_init, msg1) @@ -151,11 +151,11 @@ def test_init_func(self): r, w = self.pipe() os.write(w, b'\0') - executor = self.executor_type( - initializer=write_msg, initargs=(w, msg)) - before = os.read(r, 100) - executor.submit(mul, 10, 10) - after = read_msg(r) + with self.executor_type( + initializer=write_msg, initargs=(w, msg)) as executor: + before = os.read(r, 100) + executor.submit(mul, 10, 10) + after = read_msg(r) self.assertEqual(before, b'\0') self.assertEqual(after, msg) @@ -261,11 +261,10 @@ def test_submit_script(self): import os os.write({w}, __name__.encode('utf-8') + b'\\0') """ - executor = self.executor_type() - - fut = executor.submit(script) - res = fut.result() - after = read_msg(r) + with self.executor_type() as executor: + fut = executor.submit(script) + res = fut.result() + after = read_msg(r) self.assertEqual(after, b'__main__') self.assertIs(res, None) @@ -279,25 +278,24 @@ def task2(): spam += 1 return spam - executor = self.executor_type() - - fut = executor.submit(task1) - with self.assertRaises(_interpreters.NotShareableError): - fut.result() + with self.executor_type() as executor: + fut = executor.submit(task1) + with self.assertRaises(_interpreters.NotShareableError): + fut.result() - fut = executor.submit(task2) - with self.assertRaises(_interpreters.NotShareableError): - fut.result() + fut = executor.submit(task2) + with self.assertRaises(_interpreters.NotShareableError): + fut.result() def test_submit_local_instance(self): class Spam: def __init__(self): self.value = True - executor = self.executor_type() - fut = executor.submit(Spam) - with self.assertRaises(_interpreters.NotShareableError): - fut.result() + with self.executor_type() as executor: + fut = executor.submit(Spam) + with self.assertRaises(_interpreters.NotShareableError): + fut.result() def test_submit_instance_method(self): class Spam: @@ -305,15 +303,15 @@ def run(self): return True spam = Spam() - executor = self.executor_type() - fut = executor.submit(spam.run) - with self.assertRaises(_interpreters.NotShareableError): - fut.result() + with self.executor_type() as executor: + fut = executor.submit(spam.run) + with self.assertRaises(_interpreters.NotShareableError): + fut.result() def test_submit_func_globals(self): - executor = self.executor_type() - fut = executor.submit(get_current_name) - name = fut.result() + with self.executor_type() as executor: + fut = executor.submit(get_current_name) + name = fut.result() self.assertEqual(name, __name__) self.assertNotEqual(name, '__main__') diff --git a/Lib/test/test_concurrent_futures/test_process_pool.py b/Lib/test/test_concurrent_futures/test_process_pool.py index e99abaf6523..c7d489c4f5b 100644 --- a/Lib/test/test_concurrent_futures/test_process_pool.py +++ b/Lib/test/test_concurrent_futures/test_process_pool.py @@ -3,13 +3,15 @@ import sys import threading import time +import traceback import unittest import unittest.mock +import weakref from concurrent import futures from concurrent.futures.process import BrokenProcessPool from test import support -from test.support import hashlib_helper +from test.support import hashlib_helper, threading_helper, warnings_helper from test.test_importlib.metadata.fixtures import parameterize from .executor import ExecutorTest, mul @@ -25,7 +27,6 @@ def __init__(self, mgr): def __del__(self): self.event.set() - TERMINATE_WORKERS = futures.ProcessPoolExecutor.terminate_workers.__name__ KILL_WORKERS = futures.ProcessPoolExecutor.kill_workers.__name__ FORCE_SHUTDOWN_PARAMS = [ @@ -42,6 +43,12 @@ def _put_wait_put(queue, event): queue.put('finished') +def _report_wait_return(queue, event, value): + """ Used as part of _run_stranded_worker_exit_test """ + queue.put(value) + event.wait() + return value + class ProcessPoolExecutorTest(ExecutorTest): @@ -51,6 +58,7 @@ def test_max_workers_too_large(self): "max_workers must be <= 61"): futures.ProcessPoolExecutor(max_workers=62) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_killed_child(self): # When a child process is abruptly terminated, the whole pool gets # "broken". @@ -63,6 +71,33 @@ def test_killed_child(self): # Submitting other jobs fails as well. self.assertRaises(BrokenProcessPool, self.executor.submit, pow, 2, 8) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + def test_broken_process_pool_traceback(self): + # When a child process is abruptly terminated, the whole pool gets + # "broken", and a BrokenProcessPool exception should be created + # for each future instead of sharing one exception among all futures. + event = self.create_event() + futures = [self.executor.submit(event.wait) for _ in range(3)] + p = next(iter(self.executor._processes.values())) + p.terminate() + for fut in futures: + # Don't use assertRaises(): it clears the traceback off exc. + try: + fut.result() + except BrokenProcessPool as exc: + tb = exc.__traceback__ + else: + self.fail("BrokenProcessPool not raised") + count = sum( + 1 + for frame_summary in traceback.extract_tb(tb) + if frame_summary.filename == __file__ + ) + # This code file should appear exactly once in the traceback. + # A shared exception would accumulate a frame per result() call. + self.assertEqual(count, 1) + + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_map_chunksize(self): def bad_map(): list(self.executor.map(pow, range(40), range(40), chunksize=-1)) @@ -83,6 +118,7 @@ def bad_map(): def _test_traceback(cls): raise RuntimeError(123) # some comment + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_traceback(self): # We want ensure that the traceback from the child process is # contained in the traceback raised in the main process. @@ -105,6 +141,22 @@ def test_traceback(self): self.assertIn('raise RuntimeError(123) # some comment', f1.getvalue()) + def test_traceback_when_child_process_terminates_abruptly(self): + # gh-139462 enhancement - BrokenProcessPool exceptions + # should describe which process terminated. + exit_code = 99 + with self.executor_type(max_workers=1) as executor: + future = executor.submit(os._exit, exit_code) + with self.assertRaises(BrokenProcessPool) as bpe: + future.result() + + cause = bpe.exception.__cause__ + self.assertIsInstance(cause, futures.process._RemoteTraceback) + self.assertIn( + f"terminated abruptly with exit code {exit_code}", cause.tb + ) + + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @hashlib_helper.requires_hashdigest('md5') def test_ressources_gced_in_workers(self): # Ensure that argument for a job are correctly gc-ed after the job @@ -125,6 +177,7 @@ def test_ressources_gced_in_workers(self): mgr.shutdown() mgr.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_saturation(self): executor = self.executor mp_context = self.get_context() @@ -195,6 +248,153 @@ def test_max_tasks_per_child_defaults_to_spawn_context(self): executor = self.executor_type(1, max_tasks_per_child=3) self.assertEqual(executor._mp_context.get_start_method(), "spawn") + def test_max_tasks_per_child_pending_tasks_gh115634(self): + # gh-115634: A worker exiting at its max_tasks_per_child limit left a + # stale token in the idle worker semaphore, so no replacement worker + # was spawned and the remaining queued tasks deadlocked. Submit more + # tasks than the pool can run at once so a backlog is queued while + # workers hit their task limit. + context = self.get_context() + if context.get_start_method(allow_none=False) == "fork": + raise unittest.SkipTest("Incompatible with the fork start method.") + + for max_workers, max_tasks, num_tasks in [(1, 2, 6), (2, 2, 8)]: + with self.subTest(max_workers=max_workers, max_tasks=max_tasks): + executor = self.executor_type( + max_workers, mp_context=context, + max_tasks_per_child=max_tasks) + try: + futures = [executor.submit(mul, i, 2) + for i in range(num_tasks)] + # If the deadlock regresses, the result() calls time out, + # and the shutdown below hangs until the test timeout. + results = [f.result(timeout=support.SHORT_TIMEOUT) + for f in futures] + self.assertEqual(results, + [i * 2 for i in range(num_tasks)]) + finally: + executor.shutdown(wait=True, cancel_futures=True) + + def _run_stranded_worker_exit_test(self, *, shutdown, drop_reference): + # A worker exits upon reaching its max_tasks_per_child limit while + # more submitted work is queued. While the executor object is + # alive a replacement worker must be spawned and the remaining + # work executed; once it has been garbage collected no replacement + # is possible and the remaining futures must fail promptly instead + # of never resolving. + context = self.get_context() + if context.get_start_method(allow_none=False) == "fork": + raise unittest.SkipTest("Incompatible with the fork start method.") + manager = context.Manager() + self.addCleanup(manager.join) + self.addCleanup(manager.shutdown) + started = manager.Queue() + gate = manager.Event() + + executor = self.executor_type( + 1, mp_context=context, max_tasks_per_child=1) + futs = [executor.submit(_report_wait_return, started, gate, i) + for i in range(3)] + self.addCleanup(threading_helper.join_thread, + executor._executor_manager_thread) + # Wait until the worker is inside the first task so that it exits + # at its task limit only after the executor has been shut down + # and/or garbage collected below. + self.assertEqual(started.get(timeout=support.SHORT_TIMEOUT), 0) + if shutdown: + executor.shutdown(wait=False) + if drop_reference: + executor_ref = weakref.ref(executor) + executor = None + for _ in support.sleeping_retry(support.SHORT_TIMEOUT): + support.gc_collect() + if executor_ref() is None: + break + gate.set() + + self.assertEqual(futs[0].result(timeout=support.SHORT_TIMEOUT), 0) + if drop_reference: + for fut in futs[1:]: + with self.assertRaisesRegex(BrokenProcessPool, + "garbage collected"): + fut.result(timeout=support.SHORT_TIMEOUT) + else: + results = [f.result(timeout=support.SHORT_TIMEOUT) + for f in futs[1:]] + self.assertEqual(results, [1, 2]) + + def test_shutdown_no_wait_max_tasks_gh119592(self): + # gh-119592: shutdown(wait=False) used to clear executor state that + # worker replacement relied on. A worker exiting at its + # max_tasks_per_child limit afterwards could not be replaced, so + # the remaining submitted work never ran, and a racing worker exit + # could crash the manager thread on the partially cleared state. + for drop_reference in (False, True): + with self.subTest(drop_reference=drop_reference): + self._run_stranded_worker_exit_test( + shutdown=True, drop_reference=drop_reference) + + def test_gc_during_max_tasks_worker_exit_gh152967(self): + # gh-152967: If the executor was garbage collected without + # shutdown() while its last worker exited at its + # max_tasks_per_child limit, no replacement worker could be + # spawned and the remaining futures were never resolved. + self._run_stranded_worker_exit_test( + shutdown=False, drop_reference=True) + + def _run_unreplaceable_worker_exit_test(self, *, error_regex, + force_shutting_down=False, + failing_spawn=False): + # Drive a max_tasks_per_child worker exit while worker + # replacement is impossible; the queued futures must fail + # promptly with a BrokenProcessPool explaining why. + context = self.get_context() + if context.get_start_method(allow_none=False) == "fork": + raise unittest.SkipTest("Incompatible with the fork start method.") + manager = context.Manager() + self.addCleanup(manager.join) + self.addCleanup(manager.shutdown) + started = manager.Queue() + gate = manager.Event() + + executor = self.executor_type( + 1, mp_context=context, max_tasks_per_child=1) + futs = [executor.submit(_report_wait_return, started, gate, i) + for i in range(3)] + self.addCleanup(threading_helper.join_thread, + executor._executor_manager_thread) + self.assertEqual(started.get(timeout=support.SHORT_TIMEOUT), 0) + if force_shutting_down: + with executor._shutdown_lock: + executor._force_shutting_down = True + if failing_spawn: + spawn_patch = unittest.mock.patch( + "concurrent.futures.process._spawn_worker", + side_effect=OSError("spawn failed")) + spawn_patch.start() + self.addCleanup(spawn_patch.stop) + gate.set() + + self.assertEqual(futs[0].result(timeout=support.SHORT_TIMEOUT), 0) + for fut in futs[1:]: + with self.assertRaisesRegex(BrokenProcessPool, error_regex): + fut.result(timeout=support.SHORT_TIMEOUT) + + def test_force_shutdown_during_max_tasks_worker_exit(self): + # A worker exiting at its max_tasks_per_child limit during + # terminate_workers()/kill_workers() must not be replaced (the + # replacement would escape the kill); queued futures fail instead. + self._run_unreplaceable_worker_exit_test( + force_shutting_down=True, + error_regex="forcefully shut down") + + def test_failed_worker_replacement_breaks_pool(self): + # If no replacement worker can be started and no workers remain, + # the pool must break rather than strand the queued futures. + self._run_unreplaceable_worker_exit_test( + failing_spawn=True, + error_regex="could not be started") + def test_max_tasks_early_shutdown(self): context = self.get_context() if context.get_start_method(allow_none=False) == "fork": @@ -210,6 +410,7 @@ def test_max_tasks_early_shutdown(self): for i, future in enumerate(futures): self.assertEqual(future.result(), mul(i, i)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_python_finalization_error(self): # gh-109047: Catch RuntimeError on thread creation # during Python finalization. @@ -238,7 +439,6 @@ def mock_start_new_thread(func, *args, **kwargs): list(executor.map(mul, [(2, 3)] * 10)) executor.shutdown() - def test_terminate_workers(self): mock_fn = unittest.mock.Mock() with self.executor_type(max_workers=1) as executor: @@ -261,6 +461,7 @@ def test_force_shutdown_workers_invalid_op(self): executor._force_shutdown, operation='invalid operation'), + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @parameterize(*FORCE_SHUTDOWN_PARAMS) def test_force_shutdown_workers(self, function_name): manager = self.get_context().Manager() @@ -350,5 +551,6 @@ def test_force_shutdown_workers_stops_pool(self, function_name): def setUpModule(): setup_module() + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_concurrent_futures/test_shutdown.py b/Lib/test/test_concurrent_futures/test_shutdown.py index 99b315b47e2..129b5cb5057 100644 --- a/Lib/test/test_concurrent_futures/test_shutdown.py +++ b/Lib/test/test_concurrent_futures/test_shutdown.py @@ -6,6 +6,7 @@ from concurrent import futures from test import support +from test.support import warnings_helper from test.support.script_helper import assert_python_ok from .util import ( @@ -49,6 +50,7 @@ def test_interpreter_shutdown(self): self.assertFalse(err) self.assertEqual(out.strip(), b"apple") + @support.force_not_colorized def test_submit_after_interpreter_shutdown(self): # Test the atexit hook for shutdown of worker threads and processes rc, out, err = assert_python_ok('-c', """if 1: @@ -77,12 +79,14 @@ def run_last(): self.assertIn("RuntimeError: cannot schedule new futures", err.decode()) self.assertEqual(out.strip(), b"runtime-error") + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_hang_issue12364(self): fs = [self.executor.submit(time.sleep, 0.1) for _ in range(50)] self.executor.shutdown() for f in fs: f.result() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_cancel_futures(self): assert self.worker_count <= 5, "test needs few workers" fs = [self.executor.submit(time.sleep, .1) for _ in range(50)] @@ -111,23 +115,25 @@ def test_hang_gh83386(self): See https://github.com/python/cpython/issues/83386. """ - if self.executor_type == futures.ProcessPoolExecutor: - raise unittest.SkipTest( - "Hangs, see https://github.com/python/cpython/issues/83386") - rc, out, err = assert_python_ok('-c', """if True: from concurrent.futures import {executor_type} from test.test_concurrent_futures.test_shutdown import sleep_and_print if __name__ == "__main__": - if {context!r}: multiprocessing.set_start_method({context!r}) - t = {executor_type}(max_workers=3) + context = '{context}' + if context == "": + t = {executor_type}(max_workers=3) + else: + from multiprocessing import get_context + t = {executor_type}(max_workers=3, + mp_context=get_context(context)) t.submit(sleep_and_print, 1.0, "apple") t.shutdown(wait=False) """.format(executor_type=self.executor_type.__name__, - context=getattr(self, 'ctx', None))) + context=getattr(self, 'ctx', ''))) self.assertFalse(err) self.assertEqual(out.strip(), b"apple") + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_hang_gh94440(self): """shutdown(wait=True) doesn't hang when a future was submitted and quickly canceled right before shutdown. @@ -171,6 +177,7 @@ def acquire_lock(lock): for t in self.executor._threads: t.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_context_manager_shutdown(self): with futures.ThreadPoolExecutor(max_workers=5) as e: executor = e @@ -180,6 +187,7 @@ def test_context_manager_shutdown(self): for t in executor._threads: t.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_del_shutdown(self): executor = futures.ThreadPoolExecutor(max_workers=5) res = executor.map(abs, range(-5, 5)) @@ -193,6 +201,7 @@ def test_del_shutdown(self): # executor got shutdown. assert all([r == abs(v) for r, v in zip(res, range(-5, 5))]) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_shutdown_no_wait(self): # Ensure that the executor cleans up the threads when calling # shutdown with wait=False @@ -207,7 +216,7 @@ def test_shutdown_no_wait(self): # executor got shutdown. assert all([r == abs(v) for r, v in zip(res, range(-5, 5))]) - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_thread_names_assigned(self): executor = futures.ThreadPoolExecutor( max_workers=5, thread_name_prefix='SpecialPool') @@ -220,6 +229,7 @@ def test_thread_names_assigned(self): self.assertRegex(t.name, r'^SpecialPool_[0-4]$') t.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_thread_names_default(self): executor = futures.ThreadPoolExecutor(max_workers=5) executor.map(abs, range(-5, 5)) @@ -234,8 +244,6 @@ def test_thread_names_default(self): t.join() def test_cancel_futures_wait_false(self): - # Can only be reliably tested for TPE, since PPE often hangs with - # `wait=False` (even without *cancel_futures*). rc, out, err = assert_python_ok('-c', """if True: from concurrent.futures import ThreadPoolExecutor from test.test_concurrent_futures.test_shutdown import sleep_and_print @@ -253,6 +261,7 @@ def test_cancel_futures_wait_false(self): class ProcessPoolShutdownTest(ExecutorShutdownTest): + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_processes_terminate(self): def acquire_lock(lock): lock.acquire() @@ -276,6 +285,7 @@ def acquire_lock(lock): for p in processes.values(): p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_context_manager_shutdown(self): with futures.ProcessPoolExecutor( max_workers=5, mp_context=self.get_context()) as e: @@ -286,6 +296,7 @@ def test_context_manager_shutdown(self): for p in processes.values(): p.join() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_del_shutdown(self): executor = futures.ProcessPoolExecutor( max_workers=5, mp_context=self.get_context()) @@ -308,6 +319,7 @@ def test_del_shutdown(self): # executor got shutdown. assert all([r == abs(v) for r, v in zip(res, range(-5, 5))]) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_shutdown_no_wait(self): # Ensure that the executor cleans up the processes when calling # shutdown with wait=False diff --git a/Lib/test/test_concurrent_futures/test_thread_pool.py b/Lib/test/test_concurrent_futures/test_thread_pool.py index 4324241b374..226b7acb64f 100644 --- a/Lib/test/test_concurrent_futures/test_thread_pool.py +++ b/Lib/test/test_concurrent_futures/test_thread_pool.py @@ -7,6 +7,7 @@ import unittest from concurrent import futures from test import support +from test.support import warnings_helper from .executor import ExecutorTest, mul from .util import BaseTestCase, ThreadPoolMixin, setup_module @@ -53,6 +54,7 @@ def test_idle_thread_reuse(self): @support.requires_fork() @unittest.skipUnless(hasattr(os, 'register_at_fork'), 'need os.register_at_fork') @support.requires_resource('cpu') + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_hang_global_shutdown_lock(self): # bpo-45021: _global_shutdown_lock should be reinitialized in the child # process, otherwise it will never exit @@ -68,6 +70,7 @@ def submit(pool): @support.requires_fork() @unittest.skipUnless(hasattr(os, 'register_at_fork'), 'need os.register_at_fork') + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_process_fork_from_a_threadpool(self): # bpo-43944: clear concurrent.futures.thread._threads_queues after fork, # otherwise child process will try to join parent thread diff --git a/Lib/test/test_concurrent_futures/test_wait.py b/Lib/test/test_concurrent_futures/test_wait.py index 6749a690f6c..b8250cec7ab 100644 --- a/Lib/test/test_concurrent_futures/test_wait.py +++ b/Lib/test/test_concurrent_futures/test_wait.py @@ -3,7 +3,7 @@ import unittest from concurrent import futures from test import support -from test.support import threading_helper +from test.support import threading_helper, warnings_helper from .util import ( CANCELLED_FUTURE, CANCELLED_AND_NOTIFIED_FUTURE, EXCEPTION_FUTURE, @@ -22,6 +22,7 @@ def wait_and_raise(e): class WaitTests: + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_20369(self): # See https://bugs.python.org/issue20369 future = self.executor.submit(mul, 1, 2) @@ -30,7 +31,7 @@ def test_20369(self): self.assertEqual({future}, done) self.assertEqual(set(), not_done) - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_first_completed(self): event = self.create_event() future1 = self.executor.submit(mul, 21, 2) @@ -47,6 +48,7 @@ def test_first_completed(self): event.set() future2.result() # wait for job to finish + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_first_completed_some_already_completed(self): event = self.create_event() future1 = self.executor.submit(event.wait) @@ -64,6 +66,7 @@ def test_first_completed_some_already_completed(self): event.set() future1.result() # wait for job to finish + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_first_exception(self): event1 = self.create_event() event2 = self.create_event() @@ -93,6 +96,7 @@ def wait_for_future1(): event2.set() future3.result() # wait for job to finish + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_first_exception_some_already_complete(self): event = self.create_event() future1 = self.executor.submit(divmod, 21, 0) @@ -114,6 +118,7 @@ def test_first_exception_some_already_complete(self): event.set() future2.result() # wait for job to finish + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_first_exception_one_already_failed(self): event = self.create_event() future1 = self.executor.submit(event.wait) @@ -129,6 +134,7 @@ def test_first_exception_one_already_failed(self): event.set() future1.result() # wait for job to finish + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_all_completed(self): future1 = self.executor.submit(divmod, 2, 0) future2 = self.executor.submit(mul, 2, 21) @@ -148,6 +154,7 @@ def test_all_completed(self): future2]), finished) self.assertEqual(set(), pending) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_timeout(self): short_timeout = 0.050 @@ -200,5 +207,6 @@ def future_func(): def setUpModule(): setup_module() + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_concurrent_futures/util.py b/Lib/test/test_concurrent_futures/util.py index 1ea5a16d8b9..1dad78f08e7 100644 --- a/Lib/test/test_concurrent_futures/util.py +++ b/Lib/test/test_concurrent_futures/util.py @@ -10,7 +10,7 @@ from concurrent.futures.process import _check_system_limits from test import support -from test.support import threading_helper +from test.support import threading_helper, warnings_helper def create_future(state=PENDING, exception=None, result=None): @@ -51,7 +51,8 @@ def setUp(self): max_workers=self.worker_count, mp_context=self.get_context(), **self.executor_kwargs) - self.manager = self.get_context().Manager() + with warnings_helper.ignore_fork_in_thread_deprecation_warnings(): + self.manager = self.get_context().Manager() else: self.executor = self.executor_type( max_workers=self.worker_count, @@ -138,6 +139,8 @@ def get_context(self): self.skipTest("require unix system") if support.check_sanitizer(thread=True): self.skipTest("TSAN doesn't support threads after fork") + if "forkserver" not in multiprocessing.get_all_start_methods(): + self.skipTest("forkserver start method is not available") return super().get_context() def create_event(self): @@ -146,6 +149,7 @@ def create_event(self): def create_executor_tests(remote_globals, mixin, bases=(BaseTestCase,), executor_mixins=(ThreadPoolMixin, + InterpreterPoolMixin, ProcessPoolForkMixin, ProcessPoolForkserverMixin, ProcessPoolSpawnMixin)): diff --git a/Lib/test/test_configparser.py b/Lib/test/test_configparser.py index 4783943f71a..7d1e68fe381 100644 --- a/Lib/test/test_configparser.py +++ b/Lib/test/test_configparser.py @@ -43,7 +43,7 @@ class CfgParserTestCaseClass: default_section = configparser.DEFAULTSECT interpolation = configparser._UNSET - def newconfig(self, defaults=None): + def newconfig(self, defaults=None, **kwargs): arguments = dict( defaults=defaults, allow_no_value=self.allow_no_value, @@ -56,6 +56,7 @@ def newconfig(self, defaults=None): default_section=self.default_section, interpolation=self.interpolation, ) + arguments.update(kwargs) instance = self.config_class(**arguments) return instance @@ -358,6 +359,32 @@ def test_basic(self): the larch {0[1]} 1 """.format(self.delimiters))) + @support.subTests('data', [ + 'foo bar=baz', + 'foo bar=baz', + 'foo=bar=baz', + 'foo = bar=baz', + 'foo\t \t=\t \tbar=baz', + ]) + def test_space_delimiter(self, data): + # gh-156353: Space should be accepted as a delimiter + cf = self.newconfig(delimiters=(' ', '=')) + cf.read_string(f"[all]\n{data}") + self.assertEqual(cf.options('all'), ['foo']) + self.assertEqual(cf.get('all', 'foo'), 'bar=baz') + + @support.subTests('delimiter', ' =:;#x\t\0\N{RS}\N{CEDILLA}\N{CAT}') + @support.subTests('space_before', ['', ' ', '\t', ' \t']) + @support.subTests('space_after', ['', ' ', '\t', ' \t']) + def test_any_delimiter(self, delimiter, space_before, space_after): + cf = self.newconfig( + delimiters=(delimiter,), + inline_comment_prefixes=None, + ) + cf.read_string(f"[all]\nfoo{space_before}{delimiter}{space_after}bar=baz") + self.assertEqual(cf.options('all'), ['foo']) + self.assertEqual(cf.get('all', 'foo'), 'bar=baz') + def test_basic_from_dict(self): config = { "Foo Bar": { @@ -1991,8 +2018,8 @@ class ConvertersTestCase(BasicTestCase, unittest.TestCase): config_class = configparser.ConfigParser - def newconfig(self, defaults=None): - instance = super().newconfig(defaults=defaults) + def newconfig(self, defaults=None, **kwargs): + instance = super().newconfig(defaults=defaults, **kwargs) instance.converters['list'] = lambda v: [e.strip() for e in v.split() if e.strip()] return instance diff --git a/Lib/test/test_context.py b/Lib/test/test_context.py index ef20495dcc0..9df3e126231 100644 --- a/Lib/test/test_context.py +++ b/Lib/test/test_context.py @@ -336,6 +336,19 @@ def fun(): contextvars.copy_context().run(fun) self.assertEqual(c.get(), []) + @isolated_context + def test_reset_with_reentrant_finalizer(self): + var = contextvars.ContextVar('var') + var.set('original') + + class Reenter: + def __del__(self): + var.set('finalizer') + + token = var.set(Reenter()) + var.reset(token) + self.assertEqual(var.get(), 'finalizer') + def test_context_copy_1(self): ctx1 = contextvars.Context() c = contextvars.ContextVar('c', default=42) @@ -1282,6 +1295,31 @@ def test_hamt_gc_2(self): self.assertIsNone(ref()) + def test_hamt_gc_3(self): + # gh-154535: the iterators must be tracked by the GC, otherwise a + # cycle running through one is never collected and the HAMT it + # holds -- and everything in it -- leaks. + A = HashKey(100, 'A') + + container = [] + h = hamt() + h = h.set(A, container) + + hi = h.items() + self.assertTrue(gc.is_tracked(hi)) + + # Close the cycle: hi -> h -> container -> hi. + container.append(hi) + ref = weakref.ref(h) + + del h, hi, container + + gc.collect() + gc.collect() + gc.collect() + + self.assertIsNone(ref()) + def test_hamt_in_1(self): A = HashKey(100, 'A') AA = HashKey(100, 'A') diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py index 6a3329fa5aa..e291f814edb 100644 --- a/Lib/test/test_contextlib.py +++ b/Lib/test/test_contextlib.py @@ -680,6 +680,154 @@ def test(x): self.assertEqual(state, [1, 'something else', 999]) + def test_contextmanager_decorate_generator_function(self): + @contextmanager + def woohoo(y): + state.append(y) + yield + state.append(999) + + state = [] + @woohoo(1) + def test(x): + self.assertEqual(state, [1]) + state.append(x) + yield + state.append("second item") + return "result" + + gen = test("something") + for _ in gen: + self.assertEqual(state, [1, "something"]) + self.assertEqual(state, [1, "something", "second item", 999]) + + # The wrapped generator's return value is preserved. + state = [] + gen = test("something") + with self.assertRaises(StopIteration) as cm: + while True: + next(gen) + self.assertEqual(cm.exception.value, "result") + + + def test_contextmanager_decorate_generator_function_exception(self): + @contextmanager + def woohoo(): + state.append("enter") + try: + yield + finally: + state.append("exit") + + state = [] + @woohoo() + def test(): + state.append("body") + yield + raise ZeroDivisionError + + with self.assertRaises(ZeroDivisionError): + for _ in test(): + pass + self.assertEqual(state, ["enter", "body", "exit"]) + + + def test_contextmanager_decorate_generator_function_early_stop(self): + @contextmanager + def woohoo(): + state.append("enter") + try: + yield + finally: + state.append("exit") + + state = [] + @woohoo() + def test(): + try: + yield 1 + yield 2 + finally: + state.append("inner closed") + + gen = test() + self.assertEqual(next(gen), 1) + gen.close() + # The inner generator is closed before the context manager exits. + self.assertEqual(state, ["enter", "inner closed", "exit"]) + + + def test_contextmanager_decorate_generator_function_send_throw(self): + @contextmanager + def woohoo(): + yield + + @woohoo() + def test(): + received = yield "first" + state.append(("received", received)) + try: + yield "second" + except ValueError as exc: + state.append(("caught", type(exc))) + yield "after throw" + + # .send() and .throw() are forwarded to the wrapped generator. + state = [] + gen = test() + self.assertEqual(next(gen), "first") + self.assertEqual(gen.send("VALUE"), "second") + self.assertEqual(gen.throw(ValueError), "after throw") + gen.close() + self.assertEqual( + state, [("received", "VALUE"), ("caught", ValueError)] + ) + + + def test_contextmanager_decorate_coroutine_function(self): + @contextmanager + def woohoo(y): + state.append(y) + yield + state.append(999) + + state = [] + @woohoo(1) + async def test(x): + self.assertEqual(state, [1]) + state.append(x) + + coro = test("something") + with self.assertRaises(StopIteration): + coro.send(None) + + self.assertEqual(state, [1, "something", 999]) + + + def test_contextmanager_decorate_asyncgen_function(self): + @contextmanager + def woohoo(y): + state.append(y) + yield + state.append(999) + + state = [] + @woohoo(1) + async def test(x): + self.assertEqual(state, [1]) + state.append(x) + yield + state.append("second item") + + agen = test("something") + with self.assertRaises(StopIteration): + agen.asend(None).send(None) + with self.assertRaises(StopAsyncIteration): + agen.asend(None).send(None) + + self.assertEqual(state, [1, "something", "second item", 999]) + + class TestBaseExitStack: exit_stack = None @@ -788,6 +936,75 @@ def _exit(): result.append(2) self.assertEqual(result, [1, 2, 3, 4]) + def test_enter_context_classmethod(self): + class TestCM: + @classmethod + def __enter__(cls): + result.append(('enter', cls)) + @classmethod + def __exit__(cls, *exc_details): + result.append(('exit', cls, *exc_details)) + + cm = TestCM() + result = [] + with self.exit_stack() as stack: + stack.enter_context(cm) + self.assertEqual(result, [('enter', TestCM)]) + self.assertEqual(result, [('enter', TestCM), + ('exit', TestCM, None, None, None)]) + + result = [] + with self.exit_stack() as stack: + stack.push(cm) + self.assertEqual(result, []) + self.assertEqual(result, [('exit', TestCM, None, None, None)]) + + def test_enter_context_staticmethod(self): + class TestCM: + @staticmethod + def __enter__(): + result.append('enter') + @staticmethod + def __exit__(*exc_details): + result.append(('exit', *exc_details)) + + cm = TestCM() + result = [] + with self.exit_stack() as stack: + stack.enter_context(cm) + self.assertEqual(result, ['enter']) + self.assertEqual(result, ['enter', ('exit', None, None, None)]) + + result = [] + with self.exit_stack() as stack: + stack.push(cm) + self.assertEqual(result, []) + self.assertEqual(result, [('exit', None, None, None)]) + + def test_enter_context_slots(self): + class TestCM: + __slots__ = ('__enter__', '__exit__') + def __init__(self): + def enter(): + result.append('enter') + def exit(*exc_details): + result.append(('exit', *exc_details)) + self.__enter__ = enter + self.__exit__ = exit + + cm = TestCM() + result = [] + with self.exit_stack() as stack: + stack.enter_context(cm) + self.assertEqual(result, ['enter']) + self.assertEqual(result, ['enter', ('exit', None, None, None)]) + + result = [] + with self.exit_stack() as stack: + stack.push(cm) + self.assertEqual(result, []) + self.assertEqual(result, [('exit', None, None, None)]) + def test_enter_context_errors(self): class LacksEnterAndExit: pass diff --git a/Lib/test/test_contextlib_async.py b/Lib/test/test_contextlib_async.py index dcd00720379..95bdfdb3d9d 100644 --- a/Lib/test/test_contextlib_async.py +++ b/Lib/test/test_contextlib_async.py @@ -402,6 +402,144 @@ async def test(): await test() self.assertFalse(entered) + @_async_test + async def test_decorator_decorate_sync_function(self): + @asynccontextmanager + async def context(): + state.append(1) + yield + state.append(999) + + state = [] + @context() + def test(x): + self.assertEqual(state, [1]) + state.append(x) + + await test("something") + self.assertEqual(state, [1, "something", 999]) + + @_async_test + async def test_decorator_decorate_generator_function(self): + @asynccontextmanager + async def context(): + state.append(1) + yield + state.append(999) + + state = [] + @context() + def test(x): + self.assertEqual(state, [1]) + state.append(x) + yield + state.append("second item") + + async for _ in test("something"): + self.assertEqual(state, [1, "something"]) + self.assertEqual(state, [1, "something", "second item", 999]) + + @_async_test + async def test_decorator_decorate_asyncgen_function(self): + @asynccontextmanager + async def context(): + state.append(1) + yield + state.append(999) + + state = [] + @context() + async def test(x): + self.assertEqual(state, [1]) + state.append(x) + yield + state.append("second item") + + async for _ in test("something"): + self.assertEqual(state, [1, "something"]) + self.assertEqual(state, [1, "something", "second item", 999]) + + @_async_test + async def test_decorator_decorate_asyncgen_function_exception(self): + @asynccontextmanager + async def context(): + state.append("enter") + try: + yield + finally: + state.append("exit") + + state = [] + @context() + async def test(): + state.append("body") + yield + raise ZeroDivisionError + + with self.assertRaises(ZeroDivisionError): + async for _ in test(): + pass + self.assertEqual(state, ["enter", "body", "exit"]) + + @_async_test + async def test_decorator_decorate_asyncgen_function_early_stop(self): + @asynccontextmanager + async def context(): + state.append("enter") + try: + yield + finally: + state.append("exit") + + state = [] + @context() + async def test(): + try: + yield 1 + yield 2 + finally: + state.append("inner closed") + + agen = test() + async for value in agen: + self.assertEqual(value, 1) + break + await agen.aclose() + # The inner async generator is closed before the context + # manager exits. + self.assertEqual(state, ["enter", "inner closed", "exit"]) + + @_async_test + async def test_decorator_decorate_asyncgen_function_asend_athrow(self): + @asynccontextmanager + async def context(): + yield + + @context() + async def test(): + try: + received = yield "first" + state.append(("received", received)) + yield "second" + except ValueError: + state.append("inner saw ValueError") + raise + finally: + state.append("inner closed") + + # asend() values and athrow() exceptions are not forwarded to the + # wrapped generator (a documented limitation). + state = [] + agen = test() + self.assertEqual(await agen.__anext__(), "first") + self.assertEqual(await agen.asend("VALUE"), "second") + # The inner generator received None, not "VALUE". + self.assertEqual(state, [("received", None)]) + with self.assertRaises(ValueError): + await agen.athrow(ValueError) + # The inner generator was closed, not thrown into. + self.assertEqual(state, [("received", None), "inner closed"]) + @_async_test async def test_decorator_with_exception(self): entered = False @@ -641,6 +779,78 @@ async def _exit(): self.assertEqual(result, [1, 2, 3, 4]) + @_async_test + async def test_enter_async_context_classmethod(self): + class TestCM: + @classmethod + async def __aenter__(cls): + result.append(('enter', cls)) + @classmethod + async def __aexit__(cls, *exc_details): + result.append(('exit', cls, *exc_details)) + + cm = TestCM() + result = [] + async with self.exit_stack() as stack: + await stack.enter_async_context(cm) + self.assertEqual(result, [('enter', TestCM)]) + self.assertEqual(result, [('enter', TestCM), + ('exit', TestCM, None, None, None)]) + + result = [] + async with self.exit_stack() as stack: + stack.push_async_exit(cm) + self.assertEqual(result, []) + self.assertEqual(result, [('exit', TestCM, None, None, None)]) + + @_async_test + async def test_enter_async_context_staticmethod(self): + class TestCM: + @staticmethod + async def __aenter__(): + result.append('enter') + @staticmethod + async def __aexit__(*exc_details): + result.append(('exit', *exc_details)) + + cm = TestCM() + result = [] + async with self.exit_stack() as stack: + await stack.enter_async_context(cm) + self.assertEqual(result, ['enter']) + self.assertEqual(result, ['enter', ('exit', None, None, None)]) + + result = [] + async with self.exit_stack() as stack: + stack.push_async_exit(cm) + self.assertEqual(result, []) + self.assertEqual(result, [('exit', None, None, None)]) + + @_async_test + async def test_enter_async_context_slots(self): + class TestCM: + __slots__ = ('__aenter__', '__aexit__') + def __init__(self): + async def enter(): + result.append('enter') + async def exit(*exc_details): + result.append(('exit', *exc_details)) + self.__aenter__ = enter + self.__aexit__ = exit + + cm = TestCM() + result = [] + async with self.exit_stack() as stack: + await stack.enter_async_context(cm) + self.assertEqual(result, ['enter']) + self.assertEqual(result, ['enter', ('exit', None, None, None)]) + + result = [] + async with self.exit_stack() as stack: + stack.push_async_exit(cm) + self.assertEqual(result, []) + self.assertEqual(result, [('exit', None, None, None)]) + @_async_test async def test_enter_async_context_errors(self): class LacksEnterAndExit: diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py index b452ddbef5c..2a12a6737df 100644 --- a/Lib/test/test_copy.py +++ b/Lib/test/test_copy.py @@ -60,7 +60,7 @@ class C(object): def __reduce_ex__(self, proto): c.append(1) return "" - def __reduce__(self): + def __reduce__(*args): self.fail("shouldn't call this") c = [] x = C() @@ -70,9 +70,15 @@ def __reduce__(self): def test_copy_reduce(self): class C(object): + def __reduce_ex__(*args): + self.fail("shouldn't call this") def __reduce__(self): c.append(1) return "" + def __getattribute__(self, name): + if name == "__reduce_ex__": + raise AttributeError(name) + return object.__getattribute__(self, name) c = [] x = C() y = copy.copy(x) @@ -133,6 +139,12 @@ def test_copy_dict(self): self.assertEqual(y, x) self.assertIsNot(y, x) + def test_copy_frozendict(self): + x = frozendict(x=1, y=2) + self.assertIs(copy.copy(x), x) + x = frozendict() + self.assertIs(copy.copy(x), x) + def test_copy_set(self): x = {1, 2, 3} y = copy.copy(x) @@ -323,7 +335,7 @@ class C(object): def __reduce_ex__(self, proto): c.append(1) return "" - def __reduce__(self): + def __reduce__(*args): self.fail("shouldn't call this") c = [] x = C() @@ -333,9 +345,15 @@ def __reduce__(self): def test_deepcopy_reduce(self): class C(object): + def __reduce_ex__(*args): + self.fail("shouldn't call this") def __reduce__(self): c.append(1) return "" + def __getattribute__(self, name): + if name == "__reduce_ex__": + raise AttributeError(name) + return object.__getattribute__(self, name) c = [] x = C() y = copy.deepcopy(x) @@ -421,6 +439,30 @@ def test_deepcopy_dict(self): self.assertIsNot(x, y) self.assertIsNot(x["foo"], y["foo"]) + def test_deepcopy_frozendict(self): + x = frozendict({"foo": [1, 2], "bar": 3}) + y = copy.deepcopy(x) + self.assertEqual(y, x) + self.assertIsNot(x, y) + self.assertIsNot(x["foo"], y["foo"]) + + # recursive frozendict + x = frozendict(foo=[]) + x['foo'].append(x) + y = copy.deepcopy(x) + self.assertEqual(y.keys(), x.keys()) + self.assertIsNot(x, y) + self.assertIsNot(x["foo"], y["foo"]) + self.assertIs(y['foo'][0], y) + + x = frozendict(foo=[]) + x['foo'].append(x) + x = x['foo'] + y = copy.deepcopy(x) + self.assertIsNot(x, y) + self.assertIsNot(x[0], y[0]) + self.assertIs(y[0]['foo'], y) + @support.skip_if_huge_c_stack() @support.skip_emscripten_stack_overflow() @support.skip_wasi_stack_overflow() @@ -909,6 +951,17 @@ def m(self): self.assertIs(g.b.__self__, g) g.b() + def test_deepcopy_memo_none_result(self): + # Objects whose deepcopy result is None must still be memoized. + class C: + call_count = 0 + def __deepcopy__(self, memo): + C.call_count += 1 + return None + obj = C() + copy.deepcopy([obj, obj, obj]) + self.assertEqual(C.call_count, 1) + class TestReplace(unittest.TestCase): diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index a515e0f5ca9..674273e6cdf 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -1,3 +1,4 @@ +import ast import contextlib import copy import inspect @@ -407,6 +408,118 @@ async def bar(): with self.subTest(code=code), self.assertRaises(SyntaxError): compile(code, "", "exec") + def test_async_comprehension_scope(self): + # List/set/dict comprehensions with await or async for are allowed + # only in async functions, or at module level with top-level await. + allowed = [ + "async def f():\n [await x for x in y]", + "async def f():\n {await x for x in y}", + "async def f():\n {k: await x for k, x in y}", + "async def f():\n [x async for x in y]", + "async def f():\n {x async for x in y}", + "async def f():\n {k: x async for k, x in y}", + "async def f():\n [[await x for x in y] for y in z]", + # Defaults, bases, and genexp iterables are evaluated in the + # enclosing scope. + "async def outer():\n async def f(x=[await y for y in z]): pass", + "async def f():\n class C([await x for x in y]): pass", + "async def f():\n (x for x in [await y for y in z])", + "async def f():\n (x for x in [y async for y in z])", + ] + for code in allowed: + with self.subTest(code=code): + compile(code, "", "exec") + + # Generator expressions with await are async genexps and may appear + # outside async functions. A listcomp nested in a genexp body is also + # allowed (the genexp becomes an async generator). + for code in [ + "(await x for x in y)", + "def f():\n (await x for x in y)", + "class C:\n (await x for x in y)", + "lambda: (await x for x in y)", + "([await x for x in y] for y in z)", + "def f():\n ([await x for x in y] for y in z)", + "class C:\n ([await x for x in y] for y in z)", + "async def f():\n ([await x for x in y] for y in z)", + ]: + with self.subTest(code=code): + compile(code, "", "exec") + + err = "asynchronous comprehension outside of an asynchronous function" + invalid = [ + "[await x for x in y]", + "{await x for x in y}", + "{k: await x for k, x in y}", + "[x async for x in y]", + "{x async for x in y}", + "{k: x async for k, x in y}", + "[[await x for x in y] for y in z]", + "[[x async for x in y] for y in z]", + "def f():\n [await x for x in y]", + "def f():\n [x async for x in y]", + "async def f():\n def g():\n [await x for x in y]", + "class C:\n [await x for x in y]", + "class C:\n {await x for x in y}", + "class C:\n {k: await x for k, x in y}", + "class C:\n [x async for x in y]", + "class C:\n [[await x for x in y] for y in z]", + "async def f():\n class C:\n x = [await y for y in z]", + "async def f():\n class C:\n x = [y async for y in z]", + # Lambdas are never async, even inside async def. + "lambda: [await x for x in y]", + "async def f():\n lambda: [await x for x in y]", + "class C:\n f = lambda: [await x for x in y]", + # Defaults, bases, and genexp iterables run in the enclosing scope. + "(x for x in [await y for y in z])", + "(x for x in [y async for y in z])", + "def f():\n (x for x in [await y for y in z])", + "async def f(x=[await y for y in z]): pass", + "def f(x=[await y for y in z]): pass", + "class C:\n def f(self, x=[await y for y in z]): pass", + "class C([await x for x in y]): pass", + # Type aliases and type-parameter scopes. + "type T = [await x for x in y]", + "type T = [x async for x in y]", + "def f[T=[await x for x in y]](): pass", + "def f[T: [await x for x in y]](): pass", + "async def f[T=[await x for x in y]](): pass", + "async def f(x: [await y for y in z]): pass", + ] + for code in invalid: + with self.subTest(code=code): + support.check_syntax_error(self, code, err) + + support.check_syntax_error( + self, "await x", "'await' outside function") + support.check_syntax_error( + self, "class C:\n await x", "'await' outside function") + support.check_syntax_error( + self, "def f():\n await x", "'await' outside async function") + + flags = ast.PyCF_ALLOW_TOP_LEVEL_AWAIT + for code in [ + "[await x for x in y]", + "async def f(x=[await y for y in z]): pass", + "class C([await x for x in y]): pass", + "f'{[await x for x in y]}'", + "(x for x in [await y for y in z])", + "(x for x in [y async for y in z])", + ]: + with self.subTest(code=code, tla=True): + compile(code, "", "exec", flags=flags) + still_invalid = [ + "lambda: [await x for x in y]", + "def f():\n (x for x in [await y for y in z])", + "class C:\n def f(self, x=[await y for y in z]): pass", + "type T = [await x for x in y]", + "async def f[T=[await x for x in y]](): pass", + ] + for code in still_invalid: + with self.subTest(code=code, tla=True): + with self.assertRaisesRegex(SyntaxError, err): + compile(code, "", "exec", flags=flags) + def test_badsyntax_2(self): samples = [ """def foo(): @@ -1008,7 +1121,7 @@ async def foo(): return (await Awaitable()) with self.assertRaisesRegex( - TypeError, "__await__.*returned non-iterator of type"): + TypeError, "__await__.*must return an iterator, not"): run_async(foo()) @@ -1106,7 +1219,7 @@ async def foo(): return await Awaitable() with self.assertRaisesRegex( - TypeError, r"__await__\(\) returned a coroutine"): + TypeError, r"__await__\(\) must return an iterator, not coroutine"): run_async(foo()) c.close() @@ -1120,7 +1233,7 @@ async def foo(): return await Awaitable() with self.assertRaisesRegex( - TypeError, "__await__.*returned non-iterator of type"): + TypeError, "__await__.*must return an iterator, not"): run_async(foo()) @@ -2265,36 +2378,20 @@ def c(): # before fixing, visible stack from throw would be shorter than from send. self.assertEqual(len_send, len_throw) - def test_call_aiter_once_in_comprehension(self): - - class AsyncIterator: - - def __init__(self): - self.val = 0 - - async def __anext__(self): - if self.val == 2: - raise StopAsyncIteration - self.val += 1 - return self.val - - # No __aiter__ method - - class C: + def test_call_generator_in_frame_clear(self): + # gh-143939: Running a generator while clearing the coroutine's frame + # should not be misinterpreted as a yield. + class CallGeneratorOnDealloc: + def __del__(self): + next(x for x in [1]) - def __aiter__(self): - return AsyncIterator() - - async def run_listcomp(): - return [i async for i in C()] - - async def run_asyncgen(): - ag = (i async for i in C()) - return [i async for i in ag] - - self.assertEqual(run_async(run_listcomp()), ([], [1, 2])) - self.assertEqual(run_async(run_asyncgen()), ([], [1, 2])) + async def coro(): + obj = CallGeneratorOnDealloc() + return 42 + yielded, result = run_async(coro()) + self.assertEqual(yielded, []) + self.assertEqual(result, 42) @unittest.skipIf( support.is_emscripten or support.is_wasi, @@ -2520,7 +2617,7 @@ async def foo(): return (await future) with self.assertRaisesRegex( - TypeError, "__await__.*returned non-iterator of type 'int'"): + TypeError, "__await__.*must return an iterator, not int"): self.assertEqual(foo().send(None), 1) diff --git a/Lib/test/test_crossinterp.py b/Lib/test/test_crossinterp.py new file mode 100644 index 00000000000..f4bf5a66ad2 --- /dev/null +++ b/Lib/test/test_crossinterp.py @@ -0,0 +1,1550 @@ +import contextlib +import itertools +import sys +import traceback +import types +import unittest +import warnings + +from test import support +from test.support import import_helper + +_testinternalcapi = import_helper.import_module('_testinternalcapi') +_interpreters = import_helper.import_module('_interpreters') +from _interpreters import NotShareableError + +from test import _code_definitions as code_defs +from test import _crossinterp_definitions as defs + + +@contextlib.contextmanager +def ignore_byteswarning(): + with warnings.catch_warnings(): + warnings.filterwarnings('ignore', category=BytesWarning) + yield + + +# builtin types + +BUILTINS_TYPES = [o for _, o in __builtins__.items() if isinstance(o, type)] +EXCEPTION_TYPES = [cls for cls in BUILTINS_TYPES + if issubclass(cls, BaseException)] +OTHER_TYPES = [o for n, o in vars(types).items() + if (isinstance(o, type) and + n not in ('DynamicClassAttribute', '_GeneratorWrapper'))] +BUILTIN_TYPES = [ + *BUILTINS_TYPES, + *OTHER_TYPES, +] + +# builtin exceptions + +try: + raise Exception +except Exception as exc: + CAUGHT = exc +EXCEPTIONS_WITH_SPECIAL_SIG = { + BaseExceptionGroup: (lambda msg: (msg, [CAUGHT])), + ExceptionGroup: (lambda msg: (msg, [CAUGHT])), + UnicodeError: (lambda msg: (None, msg, None, None, None)), + UnicodeEncodeError: (lambda msg: ('utf-8', '', 1, 3, msg)), + UnicodeDecodeError: (lambda msg: ('utf-8', b'', 1, 3, msg)), + UnicodeTranslateError: (lambda msg: ('', 1, 3, msg)), +} +BUILTIN_EXCEPTIONS = [ + *(cls(*sig('error!')) for cls, sig in EXCEPTIONS_WITH_SPECIAL_SIG.items()), + *(cls('error!') for cls in EXCEPTION_TYPES + if cls not in EXCEPTIONS_WITH_SPECIAL_SIG), +] + +# other builtin objects + +METHOD = defs.SpamOkay().okay +BUILTIN_METHOD = [].append +METHOD_DESCRIPTOR_WRAPPER = str.join +METHOD_WRAPPER = object().__str__ +WRAPPER_DESCRIPTOR = object.__init__ +BUILTIN_WRAPPERS = { + METHOD: types.MethodType, + BUILTIN_METHOD: types.BuiltinMethodType, + dict.__dict__['fromkeys']: types.ClassMethodDescriptorType, + types.FunctionType.__code__: types.GetSetDescriptorType, + types.FunctionType.__globals__: types.MemberDescriptorType, + METHOD_DESCRIPTOR_WRAPPER: types.MethodDescriptorType, + METHOD_WRAPPER: types.MethodWrapperType, + WRAPPER_DESCRIPTOR: types.WrapperDescriptorType, + staticmethod(defs.SpamOkay.okay): None, + classmethod(defs.SpamOkay.okay): None, + property(defs.SpamOkay.okay): None, +} +BUILTIN_FUNCTIONS = [ + # types.BuiltinFunctionType + len, + sys.is_finalizing, + sys.exit, + _testinternalcapi.get_crossinterp_data, +] +assert 'emptymod' not in sys.modules +with import_helper.ready_to_import('emptymod', ''): + import emptymod as EMPTYMOD +MODULES = [ + sys, + defs, + unittest, + EMPTYMOD, +] +OBJECT = object() +EXCEPTION = Exception() +LAMBDA = (lambda: None) +BUILTIN_SIMPLE = [ + OBJECT, + # singletons + None, + True, + False, + Ellipsis, + NotImplemented, + # bytes + *(i.to_bytes(2, 'little', signed=True) + for i in range(-1, 258)), + # str + 'hello world', + '你好世界', + '', + # int + sys.maxsize + 1, + sys.maxsize, + -sys.maxsize - 1, + -sys.maxsize - 2, + *range(-1, 258), + 2**1000, + # float + 0.0, + 1.1, + -1.0, + 0.12345678, + -0.12345678, +] +TUPLE_EXCEPTION = (0, 1.0, EXCEPTION) +TUPLE_OBJECT = (0, 1.0, OBJECT) +TUPLE_NESTED_EXCEPTION = (0, 1.0, (EXCEPTION,)) +TUPLE_NESTED_OBJECT = (0, 1.0, (OBJECT,)) +MEMORYVIEW_EMPTY = memoryview(b'') +MEMORYVIEW_NOT_EMPTY = memoryview(b'spam'*42) +MAPPING_PROXY_EMPTY = types.MappingProxyType({}) +BUILTIN_CONTAINERS = [ + # tuple (flat) + (), + (1,), + ("hello", "world", ), + (1, True, "hello"), + TUPLE_EXCEPTION, + TUPLE_OBJECT, + # tuple (nested) + ((1,),), + ((1, 2), (3, 4)), + ((1, 2), (3, 4), (5, 6)), + TUPLE_NESTED_EXCEPTION, + TUPLE_NESTED_OBJECT, + # buffer + MEMORYVIEW_EMPTY, + MEMORYVIEW_NOT_EMPTY, + # list + [], + [1, 2, 3], + [[1], (2,), {3: 4}], + # dict + {}, + {1: 7, 2: 8, 3: 9}, + {1: [1], 2: (2,), 3: {3: 4}}, + # frozendict + frozendict(), + frozendict({1: 7, 2: 8, 3: 9}), + frozendict({1: [1], 2: (2,), 3: {3: 4}, 4: frozendict({5: 6})}), + # set + set(), + {1, 2, 3}, + {frozenset({1}), (2,)}, + # frozenset + frozenset([]), + frozenset({frozenset({1}), (2,)}), + # bytearray + bytearray(b''), + # other + MAPPING_PROXY_EMPTY, + types.SimpleNamespace(), +] +ns = {} +exec(""" +try: + raise Exception +except Exception as exc: + TRACEBACK = exc.__traceback__ + FRAME = TRACEBACK.tb_frame +""", ns, ns) +BUILTIN_OTHER = [ + # types.CellType + types.CellType(), + # types.FrameType + ns['FRAME'], + # types.TracebackType + ns['TRACEBACK'], +] +del ns + +# user-defined objects + +USER_TOP_INSTANCES = [c(*a) for c, a in defs.TOP_CLASSES.items()] +USER_NESTED_INSTANCES = [c(*a) for c, a in defs.NESTED_CLASSES.items()] +USER_INSTANCES = [ + *USER_TOP_INSTANCES, + *USER_NESTED_INSTANCES, +] +USER_EXCEPTIONS = [ + defs.MimimalError('error!'), +] + +# shareable objects + +TUPLES_WITHOUT_EQUALITY = [ + TUPLE_EXCEPTION, + TUPLE_OBJECT, + TUPLE_NESTED_EXCEPTION, + TUPLE_NESTED_OBJECT, +] +_UNSHAREABLE_SIMPLE = [ + Ellipsis, + NotImplemented, + OBJECT, + sys.maxsize + 1, + -sys.maxsize - 2, + 2**1000, +] +with ignore_byteswarning(): + _SHAREABLE_SIMPLE = [o for o in BUILTIN_SIMPLE + if o not in _UNSHAREABLE_SIMPLE] + _SHAREABLE_CONTAINERS = [ + *(o for o in BUILTIN_CONTAINERS if type(o) is memoryview), + *(o for o in BUILTIN_CONTAINERS + if type(o) is tuple and o not in TUPLES_WITHOUT_EQUALITY), + ] + _UNSHAREABLE_CONTAINERS = [o for o in BUILTIN_CONTAINERS + if o not in _SHAREABLE_CONTAINERS] +SHAREABLE = [ + *_SHAREABLE_SIMPLE, + *_SHAREABLE_CONTAINERS, +] +NOT_SHAREABLE = [ + *_UNSHAREABLE_SIMPLE, + *_UNSHAREABLE_CONTAINERS, + *BUILTIN_TYPES, + *BUILTIN_WRAPPERS, + *BUILTIN_EXCEPTIONS, + *BUILTIN_FUNCTIONS, + *MODULES, + *BUILTIN_OTHER, + # types.CodeType + *(f.__code__ for f in defs.FUNCTIONS), + *(f.__code__ for f in defs.FUNCTION_LIKE), + # types.FunctionType + *defs.FUNCTIONS, + defs.SpamOkay.okay, + LAMBDA, + *defs.FUNCTION_LIKE, + # coroutines and generators + *defs.FUNCTION_LIKE_APPLIED, + # user classes + *defs.CLASSES, + *USER_INSTANCES, + # user exceptions + *USER_EXCEPTIONS, +] + +# pickleable objects + +PICKLEABLE = [ + *BUILTIN_SIMPLE, + *(o for o in BUILTIN_CONTAINERS if o not in [ + MEMORYVIEW_EMPTY, + MEMORYVIEW_NOT_EMPTY, + MAPPING_PROXY_EMPTY, + ] or type(o) is dict), + *BUILTINS_TYPES, + *BUILTIN_EXCEPTIONS, + *BUILTIN_FUNCTIONS, + *defs.TOP_FUNCTIONS, + defs.SpamOkay.okay, + *defs.FUNCTION_LIKE, + *defs.TOP_CLASSES, + *USER_TOP_INSTANCES, + *USER_EXCEPTIONS, + # from OTHER_TYPES + types.NoneType, + types.EllipsisType, + types.NotImplementedType, + types.GenericAlias, + types.UnionType, + types.SimpleNamespace, + # from BUILTIN_WRAPPERS + METHOD, + BUILTIN_METHOD, + METHOD_DESCRIPTOR_WRAPPER, + METHOD_WRAPPER, + WRAPPER_DESCRIPTOR, +] +assert not any(isinstance(o, types.MappingProxyType) for o in PICKLEABLE) + + +# helpers + +DEFS = defs +with open(code_defs.__file__) as infile: + _code_defs_text = infile.read() +with open(DEFS.__file__) as infile: + _defs_text = infile.read() + _defs_text = _defs_text.replace('from ', '# from ') +DEFS_TEXT = f""" +####################################### +# from {code_defs.__file__} + +{_code_defs_text} + +####################################### +# from {defs.__file__} + +{_defs_text} +""" +del infile, _code_defs_text, _defs_text + + +def load_defs(module=None): + """Return a new copy of the test._crossinterp_definitions module. + + The module's __name__ matches the "module" arg, which is either + a str or a module. + + If the "module" arg is a module then the just-loaded defs are also + copied into that module. + + Note that the new module is not added to sys.modules. + """ + if module is None: + modname = DEFS.__name__ + elif isinstance(module, str): + modname = module + module = None + else: + modname = module.__name__ + # Create the new module and populate it. + defs = import_helper.create_module(modname) + defs.__file__ = DEFS.__file__ + exec(DEFS_TEXT, defs.__dict__) + # Copy the defs into the module arg, if any. + if module is not None: + for name, value in defs.__dict__.items(): + if name.startswith('_'): + continue + assert not hasattr(module, name), (name, getattr(module, name)) + setattr(module, name, value) + return defs + + +@contextlib.contextmanager +def using___main__(): + """Make sure __main__ module exists (and clean up after).""" + modname = '__main__' + if modname not in sys.modules: + with import_helper.isolated_modules(): + yield import_helper.add_module(modname) + else: + with import_helper.module_restored(modname) as mod: + yield mod + + +@contextlib.contextmanager +def temp_module(modname): + """Create the module and add to sys.modules, then remove it after.""" + assert modname not in sys.modules, (modname,) + with import_helper.isolated_modules(): + yield import_helper.add_module(modname) + + +@contextlib.contextmanager +def missing_defs_module(modname, *, prep=False): + assert modname not in sys.modules, (modname,) + if prep: + with import_helper.ready_to_import(modname, DEFS_TEXT): + yield modname + else: + with import_helper.isolated_modules(): + yield modname + + +class _GetXIDataTests(unittest.TestCase): + + MODE = None + + def assert_functions_equal(self, func1, func2): + assert type(func1) is types.FunctionType, repr(func1) + assert type(func2) is types.FunctionType, repr(func2) + self.assertEqual(func1.__name__, func2.__name__) + self.assertEqual(func1.__code__, func2.__code__) + self.assertEqual(func1.__defaults__, func2.__defaults__) + self.assertEqual(func1.__kwdefaults__, func2.__kwdefaults__) + # We don't worry about __globals__ for now. + + def assert_exc_args_equal(self, exc1, exc2): + args1 = exc1.args + args2 = exc2.args + if isinstance(exc1, ExceptionGroup): + self.assertIs(type(args1), type(args2)) + self.assertEqual(len(args1), 2) + self.assertEqual(len(args1), len(args2)) + self.assertEqual(args1[0], args2[0]) + group1 = args1[1] + group2 = args2[1] + self.assertEqual(len(group1), len(group2)) + for grouped1, grouped2 in zip(group1, group2): + # Currently the "extra" attrs are not preserved + # (via __reduce__). + self.assertIs(type(exc1), type(exc2)) + self.assert_exc_equal(grouped1, grouped2) + else: + self.assertEqual(args1, args2) + + def assert_exc_equal(self, exc1, exc2): + self.assertIs(type(exc1), type(exc2)) + + if type(exc1).__eq__ is not object.__eq__: + self.assertEqual(exc1, exc2) + + self.assert_exc_args_equal(exc1, exc2) + # XXX For now we do not preserve tracebacks. + if exc1.__traceback__ is not None: + self.assertEqual(exc1.__traceback__, exc2.__traceback__) + self.assertEqual( + getattr(exc1, '__notes__', None), + getattr(exc2, '__notes__', None), + ) + # We assume there are no cycles. + if exc1.__cause__ is None: + self.assertIs(exc1.__cause__, exc2.__cause__) + else: + self.assert_exc_equal(exc1.__cause__, exc2.__cause__) + if exc1.__context__ is None: + self.assertIs(exc1.__context__, exc2.__context__) + else: + self.assert_exc_equal(exc1.__context__, exc2.__context__) + + def assert_equal_or_equalish(self, obj, expected): + cls = type(expected) + if cls.__eq__ is not object.__eq__: + self.assertEqual(obj, expected) + elif cls is types.FunctionType: + self.assert_functions_equal(obj, expected) + elif isinstance(expected, BaseException): + self.assert_exc_equal(obj, expected) + elif cls is types.MethodType: + raise NotImplementedError(cls) + elif cls is types.BuiltinMethodType: + raise NotImplementedError(cls) + elif cls is types.MethodWrapperType: + raise NotImplementedError(cls) + elif cls.__bases__ == (object,): + self.assertEqual(obj.__dict__, expected.__dict__) + else: + raise NotImplementedError(cls) + + def get_xidata(self, obj, *, mode=None): + mode = self._resolve_mode(mode) + return _testinternalcapi.get_crossinterp_data(obj, mode) + + def get_roundtrip(self, obj, *, mode=None): + mode = self._resolve_mode(mode) + return self._get_roundtrip(obj, mode) + + def _get_roundtrip(self, obj, mode): + xid = _testinternalcapi.get_crossinterp_data(obj, mode) + return _testinternalcapi.restore_crossinterp_data(xid) + + def assert_roundtrip_identical(self, values, *, mode=None): + mode = self._resolve_mode(mode) + for obj in values: + with self.subTest(repr(obj)): + got = self._get_roundtrip(obj, mode) + self.assertIs(got, obj) + + def assert_roundtrip_equal(self, values, *, mode=None, expecttype=None): + mode = self._resolve_mode(mode) + for obj in values: + with self.subTest(repr(obj)): + got = self._get_roundtrip(obj, mode) + if got is obj: + continue + self.assertIs(type(got), + type(obj) if expecttype is None else expecttype) + self.assert_equal_or_equalish(got, obj) + + def assert_roundtrip_equal_not_identical(self, values, *, + mode=None, expecttype=None): + mode = self._resolve_mode(mode) + for obj in values: + with self.subTest(repr(obj)): + got = self._get_roundtrip(obj, mode) + self.assertIsNot(got, obj) + self.assertIs(type(got), + type(obj) if expecttype is None else expecttype) + self.assert_equal_or_equalish(got, obj) + + def assert_roundtrip_not_equal(self, values, *, + mode=None, expecttype=None): + mode = self._resolve_mode(mode) + for obj in values: + with self.subTest(repr(obj)): + got = self._get_roundtrip(obj, mode) + self.assertIsNot(got, obj) + self.assertIs(type(got), + type(obj) if expecttype is None else expecttype) + self.assertNotEqual(got, obj) + + def assert_not_shareable(self, values, exctype=None, *, mode=None): + mode = self._resolve_mode(mode) + for obj in values: + with self.subTest(repr(obj)): + with self.assertRaises(NotShareableError) as cm: + _testinternalcapi.get_crossinterp_data(obj, mode) + if exctype is not None: + self.assertIsInstance(cm.exception.__cause__, exctype) + + def _resolve_mode(self, mode): + if mode is None: + mode = self.MODE + assert mode + return mode + + +class PickleTests(_GetXIDataTests): + + MODE = 'pickle' + + def test_shareable(self): + with ignore_byteswarning(): + for obj in SHAREABLE: + if obj in PICKLEABLE: + self.assert_roundtrip_equal([obj]) + else: + self.assert_not_shareable([obj]) + + def test_not_shareable(self): + with ignore_byteswarning(): + for obj in NOT_SHAREABLE: + if type(obj) is types.MappingProxyType: + self.assert_not_shareable([obj]) + elif obj in PICKLEABLE: + with self.subTest(repr(obj)): + # We don't worry about checking the actual value. + # The other tests should cover that well enough. + got = self.get_roundtrip(obj) + self.assertIs(type(got), type(obj)) + else: + self.assert_not_shareable([obj]) + + def test_list(self): + self.assert_roundtrip_equal_not_identical([ + [], + [1, 2, 3], + [[1], (2,), {3: 4}], + ]) + + def test_dict(self): + self.assert_roundtrip_equal_not_identical([ + {}, + {1: 7, 2: 8, 3: 9}, + {1: [1], 2: (2,), 3: {3: 4}}, + ]) + + def test_set(self): + self.assert_roundtrip_equal_not_identical([ + set(), + {1, 2, 3}, + {frozenset({1}), (2,)}, + ]) + + # classes + + def assert_class_defs_same(self, defs): + # Unpickle relative to the unchanged original module. + self.assert_roundtrip_identical(defs.TOP_CLASSES) + + instances = [] + for cls, args in defs.TOP_CLASSES.items(): + if cls in defs.CLASSES_WITHOUT_EQUALITY: + continue + instances.append(cls(*args)) + self.assert_roundtrip_equal_not_identical(instances) + + # these don't compare equal + instances = [] + for cls, args in defs.TOP_CLASSES.items(): + if cls not in defs.CLASSES_WITHOUT_EQUALITY: + continue + instances.append(cls(*args)) + self.assert_roundtrip_equal(instances) + + def assert_class_defs_other_pickle(self, defs, mod): + # Pickle relative to a different module than the original. + for cls in defs.TOP_CLASSES: + assert not hasattr(mod, cls.__name__), (cls, getattr(mod, cls.__name__)) + self.assert_not_shareable(defs.TOP_CLASSES) + + instances = [] + for cls, args in defs.TOP_CLASSES.items(): + instances.append(cls(*args)) + self.assert_not_shareable(instances) + + def assert_class_defs_other_unpickle(self, defs, mod, *, fail=False): + # Unpickle relative to a different module than the original. + for cls in defs.TOP_CLASSES: + assert not hasattr(mod, cls.__name__), (cls, getattr(mod, cls.__name__)) + + instances = [] + for cls, args in defs.TOP_CLASSES.items(): + with self.subTest(repr(cls)): + setattr(mod, cls.__name__, cls) + xid = self.get_xidata(cls) + inst = cls(*args) + instxid = self.get_xidata(inst) + instances.append( + (cls, xid, inst, instxid)) + + for cls, xid, inst, instxid in instances: + with self.subTest(repr(cls)): + delattr(mod, cls.__name__) + if fail: + with self.assertRaises(NotShareableError): + _testinternalcapi.restore_crossinterp_data(xid) + continue + got = _testinternalcapi.restore_crossinterp_data(xid) + self.assertIsNot(got, cls) + self.assertNotEqual(got, cls) + + gotcls = got + got = _testinternalcapi.restore_crossinterp_data(instxid) + self.assertIsNot(got, inst) + self.assertIs(type(got), gotcls) + if cls in defs.CLASSES_WITHOUT_EQUALITY: + self.assertNotEqual(got, inst) + elif cls in defs.BUILTIN_SUBCLASSES: + self.assertEqual(got, inst) + else: + self.assertNotEqual(got, inst) + + def assert_class_defs_not_shareable(self, defs): + self.assert_not_shareable(defs.TOP_CLASSES) + + instances = [] + for cls, args in defs.TOP_CLASSES.items(): + instances.append(cls(*args)) + self.assert_not_shareable(instances) + + def test_user_class_normal(self): + self.assert_class_defs_same(defs) + + def test_user_class_in___main__(self): + with using___main__() as mod: + defs = load_defs(mod) + self.assert_class_defs_same(defs) + + def test_user_class_not_in___main___with_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + assert defs.__file__ + mod.__file__ = defs.__file__ + self.assert_class_defs_not_shareable(defs) + + def test_user_class_not_in___main___without_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + defs.__file__ = None + mod.__file__ = None + self.assert_class_defs_not_shareable(defs) + + def test_user_class_not_in___main___unpickle_with_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + assert defs.__file__ + mod.__file__ = defs.__file__ + self.assert_class_defs_other_unpickle(defs, mod) + + def test_user_class_not_in___main___unpickle_without_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + defs.__file__ = None + mod.__file__ = None + self.assert_class_defs_other_unpickle(defs, mod, fail=True) + + def test_user_class_in_module(self): + with temp_module('__spam__') as mod: + defs = load_defs(mod) + self.assert_class_defs_same(defs) + + def test_user_class_not_in_module_with_filename(self): + with temp_module('__spam__') as mod: + defs = load_defs(mod.__name__) + assert defs.__file__ + # For now, we only address this case for __main__. + self.assert_class_defs_not_shareable(defs) + + def test_user_class_not_in_module_without_filename(self): + with temp_module('__spam__') as mod: + defs = load_defs(mod.__name__) + defs.__file__ = None + self.assert_class_defs_not_shareable(defs) + + def test_user_class_module_missing_then_imported(self): + with missing_defs_module('__spam__', prep=True) as modname: + defs = load_defs(modname) + # For now, we only address this case for __main__. + self.assert_class_defs_not_shareable(defs) + + def test_user_class_module_missing_not_available(self): + with missing_defs_module('__spam__') as modname: + defs = load_defs(modname) + self.assert_class_defs_not_shareable(defs) + + def test_nested_class(self): + eggs = defs.EggsNested() + with self.assertRaises(NotShareableError): + self.get_roundtrip(eggs) + + # functions + + def assert_func_defs_same(self, defs): + # Unpickle relative to the unchanged original module. + self.assert_roundtrip_identical(defs.TOP_FUNCTIONS) + + def assert_func_defs_other_pickle(self, defs, mod): + # Pickle relative to a different module than the original. + for func in defs.TOP_FUNCTIONS: + assert not hasattr(mod, func.__name__), (getattr(mod, func.__name__),) + self.assert_not_shareable(defs.TOP_FUNCTIONS) + + def assert_func_defs_other_unpickle(self, defs, mod, *, fail=False): + # Unpickle relative to a different module than the original. + for func in defs.TOP_FUNCTIONS: + assert not hasattr(mod, func.__name__), (getattr(mod, func.__name__),) + + captured = [] + for func in defs.TOP_FUNCTIONS: + with self.subTest(func): + setattr(mod, func.__name__, func) + xid = self.get_xidata(func) + captured.append( + (func, xid)) + + for func, xid in captured: + with self.subTest(func): + delattr(mod, func.__name__) + if fail: + with self.assertRaises(NotShareableError): + _testinternalcapi.restore_crossinterp_data(xid) + continue + got = _testinternalcapi.restore_crossinterp_data(xid) + self.assertIsNot(got, func) + self.assertNotEqual(got, func) + + def assert_func_defs_not_shareable(self, defs): + self.assert_not_shareable(defs.TOP_FUNCTIONS) + + def test_user_function_normal(self): + self.assert_roundtrip_equal(defs.TOP_FUNCTIONS) + self.assert_func_defs_same(defs) + + def test_user_func_in___main__(self): + with using___main__() as mod: + defs = load_defs(mod) + self.assert_func_defs_same(defs) + + def test_user_func_not_in___main___with_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + assert defs.__file__ + mod.__file__ = defs.__file__ + self.assert_func_defs_not_shareable(defs) + + def test_user_func_not_in___main___without_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + defs.__file__ = None + mod.__file__ = None + self.assert_func_defs_not_shareable(defs) + + def test_user_func_not_in___main___unpickle_with_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + assert defs.__file__ + mod.__file__ = defs.__file__ + self.assert_func_defs_other_unpickle(defs, mod) + + def test_user_func_not_in___main___unpickle_without_filename(self): + with using___main__() as mod: + defs = load_defs('__main__') + defs.__file__ = None + mod.__file__ = None + self.assert_func_defs_other_unpickle(defs, mod, fail=True) + + def test_user_func_in_module(self): + with temp_module('__spam__') as mod: + defs = load_defs(mod) + self.assert_func_defs_same(defs) + + def test_user_func_not_in_module_with_filename(self): + with temp_module('__spam__') as mod: + defs = load_defs(mod.__name__) + assert defs.__file__ + # For now, we only address this case for __main__. + self.assert_func_defs_not_shareable(defs) + + def test_user_func_not_in_module_without_filename(self): + with temp_module('__spam__') as mod: + defs = load_defs(mod.__name__) + defs.__file__ = None + self.assert_func_defs_not_shareable(defs) + + def test_user_func_module_missing_then_imported(self): + with missing_defs_module('__spam__', prep=True) as modname: + defs = load_defs(modname) + # For now, we only address this case for __main__. + self.assert_func_defs_not_shareable(defs) + + def test_user_func_module_missing_not_available(self): + with missing_defs_module('__spam__') as modname: + defs = load_defs(modname) + self.assert_func_defs_not_shareable(defs) + + def test_nested_function(self): + self.assert_not_shareable(defs.NESTED_FUNCTIONS) + + # exceptions + + def test_user_exception_normal(self): + self.assert_roundtrip_equal([ + defs.MimimalError('error!'), + ]) + self.assert_roundtrip_equal_not_identical([ + defs.RichError('error!', 42), + ]) + + def test_builtin_exception(self): + msg = 'error!' + try: + raise Exception + except Exception as exc: + caught = exc + special = { + BaseExceptionGroup: (msg, [caught]), + ExceptionGroup: (msg, [caught]), + UnicodeError: (None, msg, None, None, None), + UnicodeEncodeError: ('utf-8', '', 1, 3, msg), + UnicodeDecodeError: ('utf-8', b'', 1, 3, msg), + UnicodeTranslateError: ('', 1, 3, msg), + } + exceptions = [] + for cls in EXCEPTION_TYPES: + args = special.get(cls) or (msg,) + exceptions.append(cls(*args)) + + self.assert_roundtrip_equal(exceptions) + + +class MarshalTests(_GetXIDataTests): + + MODE = 'marshal' + + def test_simple_builtin_singletons(self): + self.assert_roundtrip_identical([ + True, + False, + None, + Ellipsis, + ]) + self.assert_not_shareable([ + NotImplemented, + ]) + + def test_simple_builtin_objects(self): + self.assert_roundtrip_equal([ + # int + *range(-1, 258), + sys.maxsize + 1, + sys.maxsize, + -sys.maxsize - 1, + -sys.maxsize - 2, + 2**1000, + # complex + 1+2j, + # float + 0.0, + 1.1, + -1.0, + 0.12345678, + -0.12345678, + # bytes + *(i.to_bytes(2, 'little', signed=True) + for i in range(-1, 258)), + b'hello world', + # str + 'hello world', + '你好世界', + '', + ]) + self.assert_not_shareable([ + OBJECT, + types.SimpleNamespace(), + ]) + + def test_bytearray(self): + # bytearray is special because it unmarshals to bytes, not bytearray. + self.assert_roundtrip_equal([ + bytearray(), + bytearray(b'hello world'), + ], expecttype=bytes) + + def test_compound_immutable_builtin_objects(self): + self.assert_roundtrip_equal([ + # tuple + (), + (1,), + ("hello", "world"), + (1, True, "hello"), + # frozenset + frozenset([1, 2, 3]), + ]) + # nested + self.assert_roundtrip_equal([ + # tuple + ((1,),), + ((1, 2), (3, 4)), + ((1, 2), (3, 4), (5, 6)), + # frozenset + frozenset([frozenset([1]), frozenset([2]), frozenset([3])]), + ]) + + def test_compound_mutable_builtin_objects(self): + self.assert_roundtrip_equal([ + # list + [], + [1, 2, 3], + # dict + {}, + {1: 7, 2: 8, 3: 9}, + # set + set(), + {1, 2, 3}, + ]) + # nested + self.assert_roundtrip_equal([ + [[1], [2], [3]], + {1: {'a': True}, 2: {'b': False}}, + {(1, 2, 3,)}, + ]) + + def test_compound_builtin_objects_with_bad_items(self): + bogus = object() + self.assert_not_shareable([ + (bogus,), + frozenset([bogus]), + [bogus], + {bogus: True}, + {True: bogus}, + {bogus}, + ]) + + def test_builtin_code(self): + self.assert_roundtrip_equal([ + *(f.__code__ for f in defs.FUNCTIONS), + *(f.__code__ for f in defs.FUNCTION_LIKE), + ]) + + def test_builtin_type(self): + shareable = [ + StopIteration, + ] + types = BUILTIN_TYPES + self.assert_not_shareable(cls for cls in types + if cls not in shareable) + self.assert_roundtrip_identical(cls for cls in types + if cls in shareable) + + def test_builtin_function(self): + functions = [ + len, + sys.is_finalizing, + sys.exit, + _testinternalcapi.get_crossinterp_data, + ] + for func in functions: + assert type(func) is types.BuiltinFunctionType, func + + self.assert_not_shareable(functions) + + def test_builtin_exception(self): + msg = 'error!' + try: + raise Exception + except Exception as exc: + caught = exc + special = { + BaseExceptionGroup: (msg, [caught]), + ExceptionGroup: (msg, [caught]), +# UnicodeError: (None, msg, None, None, None), + UnicodeEncodeError: ('utf-8', '', 1, 3, msg), + UnicodeDecodeError: ('utf-8', b'', 1, 3, msg), + UnicodeTranslateError: ('', 1, 3, msg), + } + exceptions = [] + for cls in EXCEPTION_TYPES: + args = special.get(cls) or (msg,) + exceptions.append(cls(*args)) + + self.assert_not_shareable(exceptions) + # Note that StopIteration (the type) can be marshalled, + # but its instances cannot. + + def test_module(self): + assert type(sys) is types.ModuleType, type(sys) + assert type(defs) is types.ModuleType, type(defs) + assert type(unittest) is types.ModuleType, type(defs) + + assert 'emptymod' not in sys.modules + with import_helper.ready_to_import('emptymod', ''): + import emptymod + + self.assert_not_shareable([ + sys, + defs, + unittest, + emptymod, + ]) + + def test_user_class(self): + self.assert_not_shareable(defs.TOP_CLASSES) + + instances = [] + for cls, args in defs.TOP_CLASSES.items(): + instances.append(cls(*args)) + self.assert_not_shareable(instances) + + def test_user_function(self): + self.assert_not_shareable(defs.TOP_FUNCTIONS) + + def test_user_exception(self): + self.assert_not_shareable([ + defs.MimimalError('error!'), + defs.RichError('error!', 42), + ]) + + +class CodeTests(_GetXIDataTests): + + MODE = 'code' + + def test_function_code(self): + self.assert_roundtrip_equal_not_identical([ + *(f.__code__ for f in defs.FUNCTIONS), + *(f.__code__ for f in defs.FUNCTION_LIKE), + ]) + + def test_functions(self): + self.assert_not_shareable([ + *defs.FUNCTIONS, + *defs.FUNCTION_LIKE, + ]) + + def test_other_objects(self): + self.assert_not_shareable([ + None, + True, + False, + Ellipsis, + NotImplemented, + 9999, + 'spam', + b'spam', + (), + [], + {}, + object(), + ]) + + +class ShareableFuncTests(_GetXIDataTests): + + MODE = 'func' + + def test_stateless(self): + self.assert_roundtrip_equal([ + *defs.STATELESS_FUNCTIONS, + # Generators can be stateless too. + *defs.FUNCTION_LIKE, + ]) + + def test_not_stateless(self): + self.assert_not_shareable([ + *(f for f in defs.FUNCTIONS + if f not in defs.STATELESS_FUNCTIONS), + ]) + + def test_other_objects(self): + self.assert_not_shareable([ + None, + True, + False, + Ellipsis, + NotImplemented, + 9999, + 'spam', + b'spam', + (), + [], + {}, + object(), + ]) + + +class PureShareableScriptTests(_GetXIDataTests): + + MODE = 'script-pure' + + VALID_SCRIPTS = [ + '', + 'spam', + '# a comment', + 'print("spam")', + 'raise Exception("spam")', + """if True: + do_something() + """, + """if True: + def spam(x): + return x + class Spam: + def eggs(self): + return 42 + x = Spam().eggs() + raise ValueError(spam(x)) + """, + ] + INVALID_SCRIPTS = [ + ' pass', # IndentationError + '----', # SyntaxError + """if True: + def spam(): + # no body + spam() + """, # IndentationError + ] + + def test_valid_str(self): + self.assert_roundtrip_not_equal([ + *self.VALID_SCRIPTS, + ], expecttype=types.CodeType) + + def test_invalid_str(self): + self.assert_not_shareable([ + *self.INVALID_SCRIPTS, + ]) + + def test_valid_bytes(self): + self.assert_roundtrip_not_equal([ + *(s.encode('utf8') for s in self.VALID_SCRIPTS), + ], expecttype=types.CodeType) + + def test_invalid_bytes(self): + self.assert_not_shareable([ + *(s.encode('utf8') for s in self.INVALID_SCRIPTS), + ]) + + def test_pure_script_code(self): + self.assert_roundtrip_equal_not_identical([ + *(f.__code__ for f in defs.PURE_SCRIPT_FUNCTIONS), + ]) + + def test_impure_script_code(self): + self.assert_not_shareable([ + *(f.__code__ for f in defs.SCRIPT_FUNCTIONS + if f not in defs.PURE_SCRIPT_FUNCTIONS), + ]) + + def test_other_code(self): + self.assert_not_shareable([ + *(f.__code__ for f in defs.FUNCTIONS + if f not in defs.SCRIPT_FUNCTIONS), + *(f.__code__ for f in defs.FUNCTION_LIKE), + ]) + + def test_pure_script_function(self): + self.assert_roundtrip_not_equal([ + *defs.PURE_SCRIPT_FUNCTIONS, + ], expecttype=types.CodeType) + + def test_impure_script_function(self): + self.assert_not_shareable([ + *(f for f in defs.SCRIPT_FUNCTIONS + if f not in defs.PURE_SCRIPT_FUNCTIONS), + ]) + + def test_other_function(self): + self.assert_not_shareable([ + *(f for f in defs.FUNCTIONS + if f not in defs.SCRIPT_FUNCTIONS), + *defs.FUNCTION_LIKE, + ]) + + def test_other_objects(self): + self.assert_not_shareable([ + None, + True, + False, + Ellipsis, + NotImplemented, + (), + [], + {}, + object(), + ]) + + +class ShareableScriptTests(PureShareableScriptTests): + + MODE = 'script' + + def test_impure_script_code(self): + self.assert_roundtrip_equal_not_identical([ + *(f.__code__ for f in defs.SCRIPT_FUNCTIONS + if f not in defs.PURE_SCRIPT_FUNCTIONS), + ]) + + def test_impure_script_function(self): + self.assert_roundtrip_not_equal([ + *(f for f in defs.SCRIPT_FUNCTIONS + if f not in defs.PURE_SCRIPT_FUNCTIONS), + ], expecttype=types.CodeType) + + +class ShareableFallbackTests(_GetXIDataTests): + + MODE = 'fallback' + + def test_shareable(self): + self.assert_roundtrip_equal(SHAREABLE) + + def test_not_shareable(self): + okay = [ + *PICKLEABLE, + *defs.STATELESS_FUNCTIONS, + LAMBDA, + ] + ignored = [ + *TUPLES_WITHOUT_EQUALITY, + OBJECT, + METHOD, + BUILTIN_METHOD, + METHOD_WRAPPER, + ] + with ignore_byteswarning(): + self.assert_roundtrip_equal([ + *(o for o in NOT_SHAREABLE + if o in okay and o not in ignored + and o is not MAPPING_PROXY_EMPTY), + ]) + self.assert_roundtrip_not_equal([ + *(o for o in NOT_SHAREABLE + if o in ignored and o is not MAPPING_PROXY_EMPTY), + ]) + self.assert_not_shareable([ + *(o for o in NOT_SHAREABLE if o not in okay), + MAPPING_PROXY_EMPTY, + ]) + + +class ShareableTypeTests(_GetXIDataTests): + + MODE = 'xidata' + + def test_shareable(self): + self.assert_roundtrip_equal(SHAREABLE) + + def test_singletons(self): + self.assert_roundtrip_identical([ + None, + True, + False, + ]) + self.assert_not_shareable([ + Ellipsis, + NotImplemented, + ]) + + def test_types(self): + self.assert_roundtrip_equal([ + b'spam', + 9999, + ]) + + def test_bytes(self): + values = (i.to_bytes(2, 'little', signed=True) + for i in range(-1, 258)) + self.assert_roundtrip_equal(values) + + def test_strs(self): + self.assert_roundtrip_equal([ + 'hello world', + '你好世界', + '', + ]) + + def test_int(self): + bounds = [sys.maxsize, -sys.maxsize - 1] + values = itertools.chain(range(-1, 258), bounds) + self.assert_roundtrip_equal(values) + + def test_non_shareable_int(self): + ints = [ + sys.maxsize + 1, + -sys.maxsize - 2, + 2**1000, + ] + self.assert_not_shareable(ints, OverflowError) + + def test_float(self): + self.assert_roundtrip_equal([ + 0.0, + 1.1, + -1.0, + 0.12345678, + -0.12345678, + ]) + + def test_tuple(self): + self.assert_roundtrip_equal([ + (), + (1,), + ("hello", "world", ), + (1, True, "hello"), + ]) + # Test nesting + self.assert_roundtrip_equal([ + ((1,),), + ((1, 2), (3, 4)), + ((1, 2), (3, 4), (5, 6)), + ]) + + def test_tuples_containing_non_shareable_types(self): + non_shareables = [ + EXCEPTION, + OBJECT, + ] + for s in non_shareables: + value = tuple([0, 1.0, s]) + with self.subTest(repr(value)): + with self.assertRaises(NotShareableError): + self.get_xidata(value) + # Check nested as well + value = tuple([0, 1., (s,)]) + with self.subTest("nested " + repr(value)): + with self.assertRaises(NotShareableError): + self.get_xidata(value) + + # The rest are not shareable. + + def test_not_shareable(self): + self.assert_not_shareable(NOT_SHAREABLE) + + def test_object(self): + self.assert_not_shareable([ + object(), + ]) + + def test_code(self): + # types.CodeType + self.assert_not_shareable([ + *(f.__code__ for f in defs.FUNCTIONS), + *(f.__code__ for f in defs.FUNCTION_LIKE), + ]) + + def test_function_object(self): + for func in defs.FUNCTIONS: + assert type(func) is types.FunctionType, func + assert type(defs.SpamOkay.okay) is types.FunctionType, func + assert type(LAMBDA) is types.LambdaType + + self.assert_not_shareable([ + *defs.FUNCTIONS, + defs.SpamOkay.okay, + LAMBDA, + ]) + + def test_builtin_function(self): + functions = [ + len, + sys.is_finalizing, + sys.exit, + _testinternalcapi.get_crossinterp_data, + ] + for func in functions: + assert type(func) is types.BuiltinFunctionType, func + + self.assert_not_shareable(functions) + + def test_function_like(self): + self.assert_not_shareable(defs.FUNCTION_LIKE) + self.assert_not_shareable(defs.FUNCTION_LIKE_APPLIED) + + def test_builtin_wrapper(self): + _wrappers = { + defs.SpamOkay().okay: types.MethodType, + [].append: types.BuiltinMethodType, + dict.__dict__['fromkeys']: types.ClassMethodDescriptorType, + types.FunctionType.__code__: types.GetSetDescriptorType, + types.FunctionType.__globals__: types.MemberDescriptorType, + str.join: types.MethodDescriptorType, + object().__str__: types.MethodWrapperType, + object.__init__: types.WrapperDescriptorType, + } + for obj, expected in _wrappers.items(): + assert type(obj) is expected, (obj, expected) + + self.assert_not_shareable([ + *_wrappers, + staticmethod(defs.SpamOkay.okay), + classmethod(defs.SpamOkay.okay), + property(defs.SpamOkay.okay), + ]) + + def test_module(self): + assert type(sys) is types.ModuleType, type(sys) + assert type(defs) is types.ModuleType, type(defs) + assert type(unittest) is types.ModuleType, type(defs) + + assert 'emptymod' not in sys.modules + with import_helper.ready_to_import('emptymod', ''): + import emptymod + + self.assert_not_shareable([ + sys, + defs, + unittest, + emptymod, + ]) + + def test_class(self): + self.assert_not_shareable(defs.CLASSES) + + instances = [] + for cls, args in defs.CLASSES.items(): + instances.append(cls(*args)) + self.assert_not_shareable(instances) + + def test_builtin_type(self): + self.assert_not_shareable(BUILTIN_TYPES) + + def test_exception(self): + self.assert_not_shareable([ + defs.MimimalError('error!'), + ]) + + def test_builtin_exception(self): + msg = 'error!' + try: + raise Exception + except Exception as exc: + caught = exc + special = { + BaseExceptionGroup: (msg, [caught]), + ExceptionGroup: (msg, [caught]), +# UnicodeError: (None, msg, None, None, None), + UnicodeEncodeError: ('utf-8', '', 1, 3, msg), + UnicodeDecodeError: ('utf-8', b'', 1, 3, msg), + UnicodeTranslateError: ('', 1, 3, msg), + } + exceptions = [] + for cls in EXCEPTION_TYPES: + args = special.get(cls) or (msg,) + exceptions.append(cls(*args)) + + self.assert_not_shareable(exceptions) + + def test_builtin_objects(self): + ns = {} + exec("""if True: + try: + raise Exception + except Exception as exc: + TRACEBACK = exc.__traceback__ + FRAME = TRACEBACK.tb_frame + """, ns, ns) + + self.assert_not_shareable([ + MAPPING_PROXY_EMPTY, + types.SimpleNamespace(), + # types.CellType + types.CellType(), + # types.FrameType + ns['FRAME'], + # types.TracebackType + ns['TRACEBACK'], + ]) + + +class CaptureExceptionTests(unittest.TestCase): + + # Prevent crashes with incompatible TracebackException.format(). + # Regression test for https://github.com/python/cpython/issues/143377. + + def capture_with_formatter(self, exc, formatter): + with support.swap_attr(traceback.TracebackException, "format", formatter): + return _interpreters.capture_exception(exc) + + def test_capture_exception(self): + captured = _interpreters.capture_exception(ValueError("hello")) + + self.assertEqual(captured.type.__name__, "ValueError") + self.assertEqual(captured.type.__qualname__, "ValueError") + self.assertEqual(captured.type.__module__, "builtins") + + self.assertEqual(captured.msg, "hello") + self.assertEqual(captured.formatted, "ValueError: hello") + + def test_capture_exception_custom_format(self): + exc = ValueError("good bye!") + formatter = lambda self: ["hello\n", "world\n"] + captured = self.capture_with_formatter(exc, formatter) + self.assertEqual(captured.msg, "good bye!") + self.assertEqual(captured.formatted, "ValueError: good bye!") + self.assertEqual(captured.errdisplay, "hello\nworld") + + @support.subTests("exc_lines", ([], ["x-no-nl"], ["x-no-nl", "y-no-nl"])) + def test_capture_exception_invalid_format(self, exc_lines): + formatter = lambda self: exc_lines + captured = self.capture_with_formatter(ValueError(), formatter) + self.assertEqual(captured.msg, "") + self.assertEqual(captured.formatted, "ValueError: ") + self.assertEqual(captured.errdisplay, "".join(exc_lines)) + + @unittest.skipUnless( + support.Py_DEBUG, + "printing subinterpreter unraisable exceptions requires DEBUG build", + ) + def test_capture_exception_unraisable_exception(self): + formatter = lambda self: 1 + with support.catch_unraisable_exception() as cm: + captured = self.capture_with_formatter(ValueError(), formatter) + self.assertNotHasAttr(captured, "errdisplay") + self.assertEqual(cm.unraisable.exc_type, TypeError) + self.assertEqual(str(cm.unraisable.exc_value), + "can only join an iterable") + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py index 7e76f4bc1cb..5c278963229 100644 --- a/Lib/test/test_csv.py +++ b/Lib/test/test_csv.py @@ -228,7 +228,6 @@ def test_write_quoting(self): self._write_test(['a','',None,1], '"a","",,"1"', quoting = csv.QUOTE_NOTNULL) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_write_escape(self): self._write_test(['a',1,'p,q'], 'a,1,"p,q"', escapechar='\\') @@ -673,7 +672,6 @@ def compare_dialect_123(self, expected, *writeargs, **kwwriteargs): fileobj.seek(0) self.assertEqual(fileobj.read(), expected) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_dialect_apply(self): class testA(csv.excel): delimiter = "\t" @@ -1309,6 +1307,19 @@ class mydialect(csv.Dialect): self.assertRaises(ValueError, create_invalid, field_name, " ", skipinitialspace=True) + def test_dialect_getattr_non_attribute_error_propagates(self): + # gh-145966: non-AttributeError exceptions raised by __getattr__ + # during dialect attribute lookup must propagate, not be silenced. + class BadDialect: + def __getattr__(self, name): + raise RuntimeError("boom") + + with self.assertRaises(RuntimeError): + csv.reader([], dialect=BadDialect()) + + with self.assertRaises(RuntimeError): + csv.writer(StringIO(), dialect=BadDialect()) + class TestSniffer(unittest.TestCase): sample1 = """\ @@ -1503,6 +1514,56 @@ def test_doublequote(self): dialect = sniffer.sniff(self.sample9) self.assertTrue(dialect.doublequote) + def test_guess_delimiter_crlf_not_chosen(self): + # Ensure that we pick the real delimiter ("|") over "\r" in a tie. + sniffer = csv.Sniffer() + sample = "a|b\r\nc|d\r\ne|f\r\n" + self.assertEqual(sniffer.sniff(sample).delimiter, "|") + self.assertNotEqual(sniffer.sniff(sample).delimiter, "\r") + + def test_zero_mode_tie_order_independence(self): + sniffer = csv.Sniffer() + # ":" appears in half the rows (1, 0, 1, 0) - a tie between + # 0 and 1 per line. + # "," appears once every row (true delimiter). + # + # Even if the zero-frequency bucket is appended vs. inserted, the tie + # yields an adjusted score of 0, so ":" should not be promoted and + # "," must be selected. + sample = ( + "a,b:c\n" + "d,e\n" + "f,g:c\n" + "h,i\n" + ) + dialect = sniffer.sniff(sample) + self.assertEqual(dialect.delimiter, ",") + + def test_zero_mode_tie_order_comma_first(self): + sniffer = csv.Sniffer() + pattern = ( + "a,b\n" + "c:d\n" + "e,f\n" + "g:h\n" + ) + sample = pattern * 10 + with self.assertRaisesRegex(csv.Error, "Could not determine delimiter"): + sniffer.sniff(sample) + + def test_zero_mode_tie_order_colon_first(self): + sniffer = csv.Sniffer() + pattern = ( + "a:b\n" + "c,d\n" + "e:f\n" + "g,h\n" + ) + sample = pattern * 10 + with self.assertRaisesRegex(csv.Error, "Could not determine delimiter"): + sniffer.sniff(sample) + + def test_sniff_regex_backtracking(self): # gh-109638: this artificial sample used to take minutes. sniffer = csv.Sniffer() @@ -1720,5 +1781,16 @@ def test_disallow_instantiation(self): with self.subTest(tp=tp): check_disallow_instantiation(self, tp) + +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(csv, "__version__") + self.assertEqual(cm.filename, __file__) + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/__init__.py b/Lib/test/test_ctypes/__init__.py index eb9126cbe18..d848beb1ff1 100644 --- a/Lib/test/test_ctypes/__init__.py +++ b/Lib/test/test_ctypes/__init__.py @@ -1,4 +1,5 @@ import os +import unittest from test import support from test.support import import_helper @@ -6,5 +7,21 @@ # skip tests if the _ctypes extension was not built import_helper.import_module('ctypes') + +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + import ctypes + import _ctypes + + for mod in (ctypes, _ctypes): + with self.subTest(mod=mod): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(mod, "__version__") + self.assertEqual(cm.filename, __file__) + + def load_tests(*args): return support.load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_ctypes/_support.py b/Lib/test/test_ctypes/_support.py index 946d654a19a..700657a4e41 100644 --- a/Lib/test/test_ctypes/_support.py +++ b/Lib/test/test_ctypes/_support.py @@ -3,7 +3,6 @@ import ctypes from _ctypes import Structure, Union, _Pointer, Array, _SimpleCData, CFuncPtr import sys -from test import support _CData = Structure.__base__ diff --git a/Lib/test/test_ctypes/test_as_parameter.py b/Lib/test/test_ctypes/test_as_parameter.py index 2da1acfcf29..abbfb6efdce 100644 --- a/Lib/test/test_ctypes/test_as_parameter.py +++ b/Lib/test/test_ctypes/test_as_parameter.py @@ -5,7 +5,8 @@ c_short, c_int, c_long, c_longlong, c_byte, c_wchar, c_float, c_double, ArgumentError) -from test.support import import_helper, skip_if_sanitizer +from test.support import (import_helper, skip_if_sanitizer, + skip_emscripten_stack_overflow, skip_if_huge_c_stack) _ctypes_test = import_helper.import_module("_ctypes_test") @@ -193,6 +194,8 @@ class S8I(Structure): (9*2, 8*3, 7*4, 6*5, 5*6, 4*7, 3*8, 2*9)) @skip_if_sanitizer('requires deep stack', thread=True) + @skip_if_huge_c_stack() + @skip_emscripten_stack_overflow() def test_recursive_as_param(self): class A: pass diff --git a/Lib/test/test_ctypes/test_c_simple_type_meta.py b/Lib/test/test_ctypes/test_c_simple_type_meta.py index fd261acf497..3b4fcf9c42a 100644 --- a/Lib/test/test_ctypes/test_c_simple_type_meta.py +++ b/Lib/test/test_ctypes/test_c_simple_type_meta.py @@ -213,14 +213,12 @@ def test_bad_type_message(self): class F(metaclass=PyCSimpleType): _type_ = "\0" message = str(cm.exception) - expected_type_chars = list('cbBhHiIlLdDFGfuzZqQPXOv?g') - if not hasattr(ctypes, 'c_float_complex'): - expected_type_chars.remove('F') - expected_type_chars.remove('D') - expected_type_chars.remove('G') + expected_type_chars = list('cbBhHiIlLdfuzZqQPXOv?g') if not MS_WINDOWS: expected_type_chars.remove('X') self.assertIn("'" + ''.join(expected_type_chars) + "'", message) + if hasattr(ctypes, 'c_float_complex'): + self.assertIn("'Zf', 'Zd', 'Zg'", message) def test_creating_pointer_in_dunder_init_3(self): """Check if interfcase subclasses properly creates according internal diff --git a/Lib/test/test_ctypes/test_callbacks.py b/Lib/test/test_ctypes/test_callbacks.py index 6c7c2e52707..d1ac62816eb 100644 --- a/Lib/test/test_ctypes/test_callbacks.py +++ b/Lib/test/test_ctypes/test_callbacks.py @@ -328,6 +328,21 @@ def func(): f"of ctypes callback function {func!r}") self.assertIsNone(cm.unraisable.object) + def test_narrow_int_return_widened(self): + # gh-156933: Narrow integers were not widened on s390x + CALLBACK = CFUNCTYPE(c_int) + + dll = CDLL(_ctypes_test.__file__) + _testfunc_callback_int_to_longlong = dll._testfunc_callback_int_to_longlong + _testfunc_callback_int_to_longlong.argtypes = [CALLBACK] + _testfunc_callback_int_to_longlong.restype = c_longlong + + @CALLBACK + def cb(): + return -1 + + self.assertEqual(_testfunc_callback_int_to_longlong(cb), -1) + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_dlerror.py b/Lib/test/test_ctypes/test_dlerror.py index 5658234f9ec..bb0aec0b3c5 100644 --- a/Lib/test/test_ctypes/test_dlerror.py +++ b/Lib/test/test_ctypes/test_dlerror.py @@ -30,8 +30,9 @@ """ -@unittest.skipUnless(sys.platform.startswith('linux'), - 'test requires GNU IFUNC support') +@unittest.skipIf(not sys.platform.startswith('linux') + or platform.machine().startswith('parisc'), + 'test requires GNU IFUNC support') @unittest.skipIf(test.support.linked_to_musl(), "Requires glibc") class TestNullDlsym(unittest.TestCase): """GH-126554: Ensure that we catch NULL dlsym return values diff --git a/Lib/test/test_ctypes/test_dllist.py b/Lib/test/test_ctypes/test_dllist.py index 53f077be026..10e0f261b57 100644 --- a/Lib/test/test_ctypes/test_dllist.py +++ b/Lib/test/test_ctypes/test_dllist.py @@ -26,7 +26,7 @@ ) class ListSharedLibraries(unittest.TestCase): - @unittest.skipIf(not APPLE, "TODO: RUSTPYTHON") + @unittest.skipIf(not APPLE and sys.platform != "linux", "TODO: RUSTPYTHON") def test_lists_system(self): dlls = ctypes.util.dllist() diff --git a/Lib/test/test_ctypes/test_find.py b/Lib/test/test_ctypes/test_find.py index 8bc84c3d2ef..92175cc38ee 100644 --- a/Lib/test/test_ctypes/test_find.py +++ b/Lib/test/test_ctypes/test_find.py @@ -1,4 +1,5 @@ import os.path +import subprocess import sys import test.support import unittest @@ -78,9 +79,24 @@ def test_shell_injection(self): @unittest.skipUnless(sys.platform.startswith('linux'), 'Test only valid for Linux') class FindLibraryLinux(unittest.TestCase): + @classmethod + def setUpClass(cls): + try: + p = subprocess.run(['ld', '--version'], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + text=True) + except OSError: + pass + else: + if p.stdout.startswith('mold '): + # The mold linker is known to be incompatible with + # the soft-deprecated ctypes.util.find_library + # (which uses `ld -t`). + raise unittest.SkipTest('Fails when ld is mold') + @thread_unsafe('uses setenv') def test_find_on_libpath(self): - import subprocess import tempfile try: diff --git a/Lib/test/test_ctypes/test_generated_structs.py b/Lib/test/test_ctypes/test_generated_structs.py index aa448fad5bb..1cb46a82701 100644 --- a/Lib/test/test_ctypes/test_generated_structs.py +++ b/Lib/test/test_ctypes/test_generated_structs.py @@ -10,7 +10,7 @@ """ import unittest -from test.support import import_helper, verbose +from test.support import import_helper import re from dataclasses import dataclass from functools import cached_property diff --git a/Lib/test/test_ctypes/test_incomplete.py b/Lib/test/test_ctypes/test_incomplete.py index fefdfe9102e..8f6316d6fba 100644 --- a/Lib/test/test_ctypes/test_incomplete.py +++ b/Lib/test/test_ctypes/test_incomplete.py @@ -1,7 +1,6 @@ import ctypes import unittest -import warnings -from ctypes import Structure, POINTER, pointer, c_char_p +from ctypes import Structure, POINTER, pointer, c_char_p, c_int # String-based "incomplete pointers" were implemented in ctypes 0.6.3 (2003, when # ctypes was an external project). They made obsolete by the current @@ -21,9 +20,7 @@ class cell(Structure): _fields_ = [("name", c_char_p), ("next", lpcell)] - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - ctypes.SetPointerType(lpcell, cell) + lpcell.set_type(cell) self.assertIs(POINTER(cell), lpcell) @@ -50,10 +47,32 @@ class cell(Structure): _fields_ = [("name", c_char_p), ("next", lpcell)] + lpcell.set_type(cell) + self.assertIs(POINTER(cell), lpcell) + + def test_set_type_updates_format(self): + # gh-142966: set_type should update StgInfo.format + # to match the element type's format with self.assertWarns(DeprecationWarning): - ctypes.SetPointerType(lpcell, cell) + lp = POINTER("node") + + class node(Structure): + _fields_ = [("value", c_int)] + + # Get the expected format before set_type + node_format = memoryview(node()).format + expected_format = "&" + node_format + + lp.set_type(node) + + # Create instance to check format via memoryview + n = node(42) + p = lp(n) + actual_format = memoryview(p).format + + # After set_type, the pointer's format should be "&" + self.assertEqual(actual_format, expected_format) - self.assertIs(POINTER(cell), lpcell) if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_ctypes/test_macholib.py b/Lib/test/test_ctypes/test_macholib.py index 9d906179956..9a5e18ed589 100644 --- a/Lib/test/test_ctypes/test_macholib.py +++ b/Lib/test/test_ctypes/test_macholib.py @@ -108,5 +108,17 @@ def test_framework_info(self): d('P', 'F.framework/Versions/A/F_debug', 'F', 'A', 'debug')) +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + import ctypes.macholib + + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(ctypes.macholib, "__version__") + self.assertEqual(cm.filename, __file__) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_ctypes/test_numbers.py b/Lib/test/test_ctypes/test_numbers.py index c57c58eb002..b7df08f6079 100644 --- a/Lib/test/test_ctypes/test_numbers.py +++ b/Lib/test/test_ctypes/test_numbers.py @@ -119,8 +119,11 @@ def test_floats(self): @unittest.skipUnless(hasattr(ctypes, "c_double_complex"), "requires C11 complex type") def test_complex(self): - for t in [ctypes.c_double_complex, ctypes.c_float_complex, - ctypes.c_longdouble_complex]: + for format, t in [ + ('Zd', ctypes.c_double_complex), + ('Zf', ctypes.c_float_complex), + ('Zg', ctypes.c_longdouble_complex), + ]: self.assertEqual(t(1).value, 1+0j) self.assertEqual(t(1.0).value, 1+0j) self.assertEqual(t(1+0.125j).value, 1+0.125j) @@ -128,6 +131,12 @@ def test_complex(self): self.assertEqual(t(FloatLike()).value, 2+0j) self.assertEqual(t(ComplexLike()).value, 1+1j) + prefix = '>' if sys.byteorder == 'big' else '<' + num = t(1.0) + self.assertEqual(memoryview(num).format, prefix + format) + array = (t * 3)() + self.assertEqual(memoryview(array).format, prefix + format) + @unittest.skipUnless(hasattr(ctypes, "c_double_complex"), "requires C11 complex type") def test_complex_round_trip(self): diff --git a/Lib/test/test_ctypes/test_parameters.py b/Lib/test/test_ctypes/test_parameters.py index 46f8ff93efa..6dadb7b410d 100644 --- a/Lib/test/test_ctypes/test_parameters.py +++ b/Lib/test/test_ctypes/test_parameters.py @@ -1,6 +1,7 @@ import sys import unittest import test.support +import ctypes from ctypes import (CDLL, PyDLL, ArgumentError, Structure, Array, Union, _Pointer, _SimpleCData, _CFuncPtr, @@ -247,6 +248,13 @@ def test_parameter_repr(self): self.assertRegex(repr(c_char_p.from_param(b'hihi')), r"^$") self.assertRegex(repr(c_wchar_p.from_param('hihi')), r"^$") self.assertRegex(repr(c_void_p.from_param(0x12)), r"^$") + if hasattr(ctypes, 'c_double_complex'): + self.assertRegex(repr(ctypes.c_double_complex.from_param(0)), + r"^$") + self.assertRegex(repr(ctypes.c_float_complex.from_param(0)), + r"^$") + self.assertRegex(repr(ctypes.c_longdouble_complex.from_param(0)), + r"^$") @test.support.cpython_only def test_from_param_result_refcount(self): diff --git a/Lib/test/test_ctypes/test_structures.py b/Lib/test/test_ctypes/test_structures.py index 92d4851d739..65ccc12625f 100644 --- a/Lib/test/test_ctypes/test_structures.py +++ b/Lib/test/test_ctypes/test_structures.py @@ -299,9 +299,16 @@ class X(Structure): self.assertEqual(s.first, got.first) self.assertEqual(s.second, got.second) + @unittest.skipIf(support.is_wasm32, "wasm ABI is incompatible with test expectations") def _test_issue18060(self, Vector): # Regression tests for gh-62260 + # This test passes a struct of two doubles by value to atan2(), whose C + # signature is atan2(double, double), so it only works on platforms + # where the abi of a function that takes a struct with two doubles + # matches the abi of a function that takes two doubles. The wasm32 ABI + # does not satisfy this condition and the test breaks. + # The call to atan2() should succeed if the # class fields were correctly cloned in the # subclasses. Otherwise, it will segfault. diff --git a/Lib/test/test_ctypes/test_unions.py b/Lib/test/test_ctypes/test_unions.py deleted file mode 100644 index e2dff0f22a9..00000000000 --- a/Lib/test/test_ctypes/test_unions.py +++ /dev/null @@ -1,35 +0,0 @@ -import unittest -from ctypes import Union, c_char -from ._support import (_CData, UnionType, Py_TPFLAGS_DISALLOW_INSTANTIATION, - Py_TPFLAGS_IMMUTABLETYPE) - - -class ArrayTestCase(unittest.TestCase): - def test_inheritance_hierarchy(self): - self.assertEqual(Union.mro(), [Union, _CData, object]) - - self.assertEqual(UnionType.__name__, "UnionType") - self.assertEqual(type(UnionType), type) - - def test_type_flags(self): - for cls in Union, UnionType: - with self.subTest(cls=Union): - self.assertTrue(Union.__flags__ & Py_TPFLAGS_IMMUTABLETYPE) - self.assertFalse(Union.__flags__ & Py_TPFLAGS_DISALLOW_INSTANTIATION) - - def test_metaclass_details(self): - # Abstract classes (whose metaclass __init__ was not called) can't be - # instantiated directly - NewUnion = UnionType.__new__(UnionType, 'NewUnion', - (Union,), {}) - for cls in Union, NewUnion: - with self.subTest(cls=cls): - with self.assertRaisesRegex(TypeError, "abstract class"): - obj = cls() - - # Cannot call the metaclass __init__ more than once - class T(Union): - _fields_ = [("x", c_char), - ("y", c_char)] - with self.assertRaisesRegex(SystemError, "already initialized"): - UnionType.__init__(T, 'ptr', (), {}) diff --git a/Lib/test/test_ctypes/test_win32_com_foreign_func.py b/Lib/test/test_ctypes/test_win32_com_foreign_func.py index 01db602149b..7e54f8f6c31 100644 --- a/Lib/test/test_ctypes/test_win32_com_foreign_func.py +++ b/Lib/test/test_ctypes/test_win32_com_foreign_func.py @@ -157,7 +157,6 @@ class IPersist(IUnknown): self.assertEqual(0, ppst.Release()) - @unittest.expectedFailure # TODO: RUSTPYTHON; - COM iid parameter handling not implemented def test_with_paramflags_and_iid(self): class IUnknown(c_void_p): QueryInterface = proto_query_interface(None, IID_IUnknown) diff --git a/Lib/test/test_curses.py b/Lib/test/test_curses.py new file mode 100644 index 00000000000..ae3d7cdc5ea --- /dev/null +++ b/Lib/test/test_curses.py @@ -0,0 +1,2046 @@ +import functools +import inspect +import os +import string +import sys +import tempfile +import unittest +from unittest.mock import MagicMock + +from test.support import (requires, verbose, SaveSignals, cpython_only, + check_disallow_instantiation, MISSING_C_DOCSTRINGS, + gc_collect) +from test.support.import_helper import import_module + +# Optionally test curses module. This currently requires that the +# 'curses' resource be given on the regrtest command line using the -u +# option. If not available, nothing after this line will be executed. +requires('curses') + +# If either of these don't exist, skip the tests. +curses = import_module('curses') +import_module('curses.ascii') +import_module('curses.textpad') +try: + import curses.panel +except ImportError: + pass + +def requires_curses_func(name): + return unittest.skipUnless(hasattr(curses, name), + 'requires curses.%s' % name) + +def requires_curses_window_meth(name): + def deco(test): + @functools.wraps(test) + def wrapped(self, *args, **kwargs): + if not hasattr(self.stdscr, name): + raise unittest.SkipTest('requires curses.window.%s' % name) + test(self, *args, **kwargs) + return wrapped + return deco + + +def requires_colors(test): + @functools.wraps(test) + def wrapped(self, *args, **kwargs): + if not curses.has_colors(): + self.skipTest('requires colors support') + curses.start_color() + test(self, *args, **kwargs) + return wrapped + +term = os.environ.get('TERM') +SHORT_MAX = 0x7fff + +# If newterm was supported we could use it instead of initscr and not exit +@unittest.skipIf(not term or term == 'unknown', + "$TERM=%r, calling initscr() may cause exit" % term) +@unittest.skipIf(sys.platform == "cygwin", + "cygwin's curses mostly just hangs") +class TestCurses(unittest.TestCase): + + @classmethod + def setUpClass(cls): + if verbose: + print(f'TERM={term}', file=sys.stderr, flush=True) + # testing setupterm() inside initscr/endwin + # causes terminal breakage + stdout_fd = sys.__stdout__.fileno() + curses.setupterm(fd=stdout_fd) + + def setUp(self): + self.isatty = True + self.output = sys.__stdout__ + stdout_fd = sys.__stdout__.fileno() + if not sys.__stdout__.isatty(): + # initstr() unconditionally uses C stdout. + # If it is redirected to file or pipe, try to attach it + # to terminal. + # First, save a copy of the file descriptor of stdout, so it + # can be restored after finishing the test. + dup_fd = os.dup(stdout_fd) + self.addCleanup(os.close, dup_fd) + self.addCleanup(os.dup2, dup_fd, stdout_fd) + + if sys.__stderr__.isatty(): + # If stderr is connected to terminal, use it. + tmp = sys.__stderr__ + self.output = sys.__stderr__ + else: + try: + # Try to open the terminal device. + tmp = open('/dev/tty', 'wb', buffering=0) + except OSError: + # As a fallback, use regular file to write control codes. + # Some functions (like savetty) will not work, but at + # least the garbage control sequences will not be mixed + # with the testing report. + tmp = tempfile.TemporaryFile(mode='wb', buffering=0) + self.isatty = False + self.addCleanup(tmp.close) + self.output = None + os.dup2(tmp.fileno(), stdout_fd) + + self.save_signals = SaveSignals() + self.save_signals.save() + self.addCleanup(self.save_signals.restore) + if verbose and self.output is not None: + # just to make the test output a little more readable + sys.stderr.flush() + sys.stdout.flush() + print(file=self.output, flush=True) + self.stdscr = curses.initscr() + if self.isatty: + curses.savetty() + self.addCleanup(curses.endwin) + self.addCleanup(curses.resetty) + self.stdscr.erase() + + @requires_curses_func('filter') + def test_filter(self): + # TODO: Should be called before initscr() or newterm() are called. + # TODO: nofilter() + curses.filter() + + @requires_curses_func('use_env') + def test_use_env(self): + # TODO: Should be called before initscr() or newterm() are called. + # TODO: use_tioctl() + curses.use_env(False) + curses.use_env(True) + + def test_error(self): + self.assertIsSubclass(curses.error, Exception) + + def test_create_windows(self): + win = curses.newwin(5, 10) + self.assertEqual(win.getbegyx(), (0, 0)) + self.assertEqual(win.getparyx(), (-1, -1)) + self.assertEqual(win.getmaxyx(), (5, 10)) + + win = curses.newwin(10, 15, 2, 5) + self.assertEqual(win.getbegyx(), (2, 5)) + self.assertEqual(win.getparyx(), (-1, -1)) + self.assertEqual(win.getmaxyx(), (10, 15)) + + win2 = win.subwin(3, 7) + self.assertEqual(win2.getbegyx(), (3, 7)) + self.assertEqual(win2.getparyx(), (1, 2)) + self.assertEqual(win2.getmaxyx(), (9, 13)) + + win2 = win.subwin(5, 10, 3, 7) + self.assertEqual(win2.getbegyx(), (3, 7)) + self.assertEqual(win2.getparyx(), (1, 2)) + self.assertEqual(win2.getmaxyx(), (5, 10)) + + win3 = win.derwin(2, 3) + self.assertEqual(win3.getbegyx(), (4, 8)) + self.assertEqual(win3.getparyx(), (2, 3)) + self.assertEqual(win3.getmaxyx(), (8, 12)) + + win3 = win.derwin(6, 11, 2, 3) + self.assertEqual(win3.getbegyx(), (4, 8)) + self.assertEqual(win3.getparyx(), (2, 3)) + self.assertEqual(win3.getmaxyx(), (6, 11)) + + win.mvwin(0, 1) + self.assertEqual(win.getbegyx(), (0, 1)) + self.assertEqual(win.getparyx(), (-1, -1)) + self.assertEqual(win.getmaxyx(), (10, 15)) + self.assertEqual(win2.getbegyx(), (3, 7)) + self.assertEqual(win2.getparyx(), (1, 2)) + self.assertEqual(win2.getmaxyx(), (5, 10)) + self.assertEqual(win3.getbegyx(), (4, 8)) + self.assertEqual(win3.getparyx(), (2, 3)) + self.assertEqual(win3.getmaxyx(), (6, 11)) + + win2.mvderwin(2, 1) + self.assertEqual(win2.getbegyx(), (3, 7)) + self.assertEqual(win2.getparyx(), (2, 1)) + self.assertEqual(win2.getmaxyx(), (5, 10)) + + win3.mvderwin(2, 1) + self.assertEqual(win3.getbegyx(), (4, 8)) + self.assertEqual(win3.getparyx(), (2, 1)) + self.assertEqual(win3.getmaxyx(), (6, 11)) + + def test_subwindows_references(self): + win = curses.newwin(5, 10) + win2 = win.subwin(3, 7) + del win + gc_collect() + del win2 + gc_collect() + + def test_move_cursor(self): + stdscr = self.stdscr + win = stdscr.subwin(10, 15, 2, 5) + stdscr.move(1, 2) + win.move(2, 4) + self.assertEqual(stdscr.getyx(), (1, 2)) + self.assertEqual(win.getyx(), (2, 4)) + + win.cursyncup() + self.assertEqual(stdscr.getyx(), (4, 9)) + + def test_refresh_control(self): + stdscr = self.stdscr + # touchwin()/untouchwin()/is_wintouched() + stdscr.refresh() + self.assertIs(stdscr.is_wintouched(), False) + stdscr.touchwin() + self.assertIs(stdscr.is_wintouched(), True) + stdscr.refresh() + self.assertIs(stdscr.is_wintouched(), False) + stdscr.touchwin() + self.assertIs(stdscr.is_wintouched(), True) + stdscr.untouchwin() + self.assertIs(stdscr.is_wintouched(), False) + + # touchline()/untouchline()/is_linetouched() + stdscr.touchline(5, 2) + self.assertIs(stdscr.is_linetouched(5), True) + self.assertIs(stdscr.is_linetouched(6), True) + self.assertIs(stdscr.is_wintouched(), True) + stdscr.touchline(5, 1, False) + self.assertIs(stdscr.is_linetouched(5), False) + + # syncup() + win = stdscr.subwin(10, 15, 2, 5) + win2 = win.subwin(5, 10, 3, 7) + win2.touchwin() + stdscr.untouchwin() + win2.syncup() + self.assertIs(win.is_wintouched(), True) + self.assertIs(stdscr.is_wintouched(), True) + + # syncdown() + stdscr.touchwin() + win.untouchwin() + win2.untouchwin() + win2.syncdown() + self.assertIs(win2.is_wintouched(), True) + + # syncok() + if hasattr(stdscr, 'syncok') and not sys.platform.startswith("sunos"): + win.untouchwin() + stdscr.untouchwin() + for syncok in [False, True]: + win2.syncok(syncok) + win2.addch('a') + self.assertIs(win.is_wintouched(), syncok) + self.assertIs(stdscr.is_wintouched(), syncok) + + # Many tests below use a common set of non-ASCII cases, each applied only + # when the window encoding can represent it -- so the whole suite is meant to + # be run under several locales (e.g. ISO-8859-1, ISO-8859-15, KOI8-U): + # 'A'/'a' ASCII + # 'é' common to the Latin encodings + # '¤'/'€'/'є' byte 0xA4 in ISO-8859-1 / ISO-8859-15 / KOI8-U + # Precomposed characters are used so a round-trip does not depend on the form. + + def _encodable(self, s): + # Wide characters are only supported in a locale that can encode them. + try: + s.encode(self.stdscr.encoding) + except UnicodeEncodeError: + return False + return True + + def _read_char(self, y, x): + # The character written to a cell, read back for output checks. inch() + # is unusable here: on a wide build it returns the low 8 bits of the + # character's code point rather than its locale-encoded byte, mangling + # anything outside Latin-1. in_wch() reads the wide cell directly; + # without it, instr() re-encodes the cell to the window encoding. + stdscr = self.stdscr + if hasattr(stdscr, 'in_wch'): + return str(stdscr.in_wch(y, x)) + return stdscr.instr(y, x, 1).decode(stdscr.encoding) + + def test_output_character(self): + stdscr = self.stdscr + encoding = stdscr.encoding + # addch() + stdscr.refresh() + stdscr.move(0, 0) + stdscr.addch('A') + stdscr.addch(b'A') + stdscr.addch(65) + # See _encodable for the character set. Each is either written (mapped + # to a single byte), or raises UnicodeEncodeError (not in the encoding) + # or OverflowError (a multibyte sequence, e.g. in UTF-8). + for c in ('A', '\u00e9', '\u00a4', '\u20ac', '\u0454'): + try: + stdscr.addch(c) + except UnicodeEncodeError: + self.assertRaises(UnicodeEncodeError, c.encode, encoding) + except OverflowError: + encoded = c.encode(encoding) + self.assertNotEqual(len(encoded), 1, repr(encoded)) + stdscr.addch('A', curses.A_BOLD) + stdscr.addch(1, 2, 'A') + stdscr.addch(2, 3, 'A', curses.A_BOLD) + self.assertIs(stdscr.is_wintouched(), True) + + # The same characters supplied as an int chtype (a byte > 127). The + # cell is read back with _read_char(), not inch(): on a wide build the + # int is stored through the locale as a wide character that inch() + # cannot represent for a character outside Latin-1. + for c in ('é', '¤', '€', 'є'): + try: + b = c.encode(encoding) + except UnicodeEncodeError: + continue + if len(b) != 1: + continue + # A wide build stores a character outside Latin-1 as a wide cell, + # not as its encoded byte, so it cannot round-trip here. + if ord(c) > 0xff and hasattr(stdscr, 'get_wch'): + continue + v = b[0] + with self.subTest(c=c): + stdscr.addch(0, 0, v) + self.assertEqual(self._read_char(0, 0), c) + stdscr.addch(0, 1, v, curses.A_BOLD) + self.assertEqual(self._read_char(0, 1), c) + self.assertTrue(stdscr.inch(0, 1) & curses.A_BOLD) + stdscr.move(2, 0) + stdscr.echochar(v) + self.assertEqual(self._read_char(2, 0), c) + # insch() decodes the byte through the locale like addch(), so + # it round-trips the same character. + stdscr.insch(1, 0, v) + self.assertEqual(self._read_char(1, 0), c) + + # The same characters supplied as a str. Unlike the int path above, a + # str is stored as a wide-character cell on a wide build, so every + # encodable character round-trips, insch() included. A multibyte + # character does not fit a cell on a narrow build and is skipped. + wide = hasattr(stdscr, 'in_wch') + for c in ('é', '¤', '€', 'є'): + if not self._encodable(c): + continue + if not wide and len(c.encode(encoding)) != 1: + continue + # A wide build stores a character outside Latin-1 as a wide cell, + # not as its encoded byte, so it cannot round-trip here. + if ord(c) > 0xff and hasattr(stdscr, 'get_wch'): + continue + with self.subTest(c=c): + stdscr.addch(0, 0, c) + self.assertEqual(self._read_char(0, 0), c) + stdscr.addch(0, 1, c, curses.A_BOLD) + self.assertEqual(self._read_char(0, 1), c) + self.assertTrue(stdscr.inch(0, 1) & curses.A_BOLD) + stdscr.insch(1, 0, c) + self.assertEqual(self._read_char(1, 0), c) + stdscr.move(2, 0) + stdscr.echochar(c) + self.assertEqual(self._read_char(2, 0), c) + + # echochar() + stdscr.refresh() + stdscr.move(0, 0) + stdscr.echochar('A') + stdscr.echochar(b'A') + stdscr.echochar(65) + # See _encodable for the character set; as in the addch() loop above. + for c in ('A', '\u00e9', '\u00a4', '\u20ac', '\u0454'): + try: + stdscr.echochar(c) + except UnicodeEncodeError: + # The character is not encodable with the current encoding. + self.assertRaises(UnicodeEncodeError, c.encode, encoding) + except OverflowError: + # The character is encoded to a multibyte sequence. + encoded = c.encode(encoding) + self.assertNotEqual(len(encoded), 1, repr(encoded)) + stdscr.echochar('A', curses.A_BOLD) + self.assertIs(stdscr.is_wintouched(), False) + + def test_output_string(self): + stdscr = self.stdscr + encoding = stdscr.encoding + # addstr()/insstr() + for func in [stdscr.addstr, stdscr.insstr]: + with self.subTest(func.__qualname__): + func('abcd') + func(b'abcd') + # Common and encoding-distinctive strings (see _encodable for the + # 0xA4 set); 'àßçđ' is UTF-8-only. Each is written if the + # encoding allows, else raises UnicodeEncodeError. + for s in ('soupçon', 'àßçđ', 'soupçon ¤', 'soupçon €', 'дякую'): + stdscr.move(0, 0) + try: + func(s) + except UnicodeEncodeError: + self.assertRaises(UnicodeEncodeError, s.encode, encoding) + stdscr.move(0, 0) + func('abcd', curses.A_BOLD) + func(1, 2, 'abcd') + func(2, 3, 'abcd', curses.A_BOLD) + + # addnstr()/insnstr() + for func in [stdscr.addnstr, stdscr.insnstr]: + with self.subTest(func.__qualname__): + stdscr.move(0, 0) + func('1234', 3) + func(b'1234', 3) + # As above (see _encodable); Arabic-Indic digits are UTF-8-only. + for s in ('caf\u00e9', '\u0661\u0662\u0663\u0664', 'caf\u00e9 \u00a4', 'caf\u00e9 \u20ac', '\u0434\u044f\u043a\u0443\u044e'): + stdscr.move(0, 0) + try: + func(s, 3) + except UnicodeEncodeError: + self.assertRaises(UnicodeEncodeError, s.encode, encoding) + stdscr.move(0, 0) + func('1234', 5) + func('1234', 3, curses.A_BOLD) + func(1, 2, '1234', 3) + func(2, 3, '1234', 3, curses.A_BOLD) + + def test_output_string_embedded_null_chars(self): + # reject embedded null bytes and characters + stdscr = self.stdscr + for arg in ['a\0', b'a\0']: + with self.subTest(arg=arg): + self.assertRaises(ValueError, stdscr.addstr, arg) + self.assertRaises(ValueError, stdscr.addnstr, arg, 1) + self.assertRaises(ValueError, stdscr.insstr, arg) + self.assertRaises(ValueError, stdscr.insnstr, arg, 1) + + def test_output_string_attr_restored(self): + # A write with an attr restores the window rendition afterwards, + # whether it succeeded or failed. + win = curses.newwin(2, 10, 0, 0) + def current_attrs(): + # Write a cell with the window's current rendition and read it + # back, so that the rendition itself is checked. + win.addstr(1, 0, ' ') + return win.inch(1, 0) & curses.A_ATTRIBUTES + for func, args in [(win.addstr, ('x',)), (win.addnstr, ('x', 1)), + (win.insstr, ('x',)), (win.insnstr, ('x', 1))]: + with self.subTest(func.__qualname__): + win.attrset(curses.A_UNDERLINE) + # y=100 is outside the window, so the write fails. + self.assertRaises(curses.error, func, 100, 0, *args, + curses.A_BOLD) + self.assertEqual(current_attrs(), curses.A_UNDERLINE) + func(0, 0, *args, curses.A_BOLD) + self.assertEqual(current_attrs(), curses.A_UNDERLINE) + + def test_add_string_behavior(self): + # addstr() advances the cursor past the written text; addnstr() + # writes at most n characters. + win = curses.newwin(1, 10, 0, 0) + win.addstr(0, 0, 'abc') + self.assertEqual(win.getyx(), (0, 3)) + win.erase() + win.addnstr(0, 0, 'abcdef', 3) + self.assertEqual(win.instr(0, 0), b'abc ') + + def test_insert_string_behavior(self): + # insstr()/insnstr() insert at the cursor, shift the rest of the + # line right (losing characters off the edge), and leave the cursor + # where it was. + win = curses.newwin(1, 10, 0, 0) + win.addstr(0, 0, 'abcde') + win.move(0, 1) + win.insstr('XY') + self.assertEqual(win.getyx(), (0, 1)) # cursor did not advance + self.assertEqual(win.instr(0, 0), b'aXYbcde ') + + win.erase() + win.addstr(0, 0, 'ZZZZZ') + win.move(0, 0) + win.insnstr('abcdef', 3) # at most 3 characters + self.assertEqual(win.instr(0, 0), b'abcZZZZZ ') + + def test_insch(self): + # insch() inserts a single character at the cursor (or at y, x), + # shifting the rest of the line right. + win = curses.newwin(2, 10, 0, 0) + win.addstr(0, 0, 'abc') + win.move(0, 1) + win.insch(ord('X')) + self.assertEqual(win.instr(0, 0), b'aXbc ') + win.insch(1, 0, 'Y', curses.A_BOLD) + self.assertEqual(win.inch(1, 0), b'Y'[0] | curses.A_BOLD) + + def test_pad(self): + pad = curses.newpad(10, 20) + pad.addstr(0, 0, 'PADTEXT') + self.assertEqual(pad.instr(0, 0, 7), b'PADTEXT') + + # subpad() creates a pad within the parent pad. Cell sharing with + # the parent is implementation-defined, so write to the subpad itself. + sub = pad.subpad(3, 5, 0, 0) + self.assertEqual(sub.getmaxyx(), (3, 5)) + sub.addstr(1, 0, 'sub') + self.assertEqual(sub.instr(1, 0, 3), b'sub') + + # A pad is refreshed onto an explicit screen rectangle; the + # 6-argument form is required (and rejected for ordinary windows). + pad.refresh(0, 0, 0, 0, 4, 10) + pad.noutrefresh(0, 0, 0, 0, 4, 10) + curses.doupdate() + self.assertRaises(TypeError, pad.refresh) + win = curses.newwin(5, 5, 0, 0) + self.assertRaises(TypeError, win.refresh, 0, 0, 0, 0, 4, 4) + + def test_read_from_window(self): + stdscr = self.stdscr + stdscr.addstr(0, 1, 'ABCD', curses.A_BOLD) + # inch() + stdscr.move(0, 1) + self.assertEqual(stdscr.inch(), 65 | curses.A_BOLD) + self.assertEqual(stdscr.inch(0, 3), 67 | curses.A_BOLD) + stdscr.move(0, 0) + # instr() + self.assertEqual(stdscr.instr()[:6], b' ABCD ') + self.assertEqual(stdscr.instr(3)[:6], b' AB') + self.assertEqual(stdscr.instr(0, 2)[:4], b'BCD ') + self.assertEqual(stdscr.instr(0, 2, 4), b'BCD ') + self.assertRaises(ValueError, stdscr.instr, -2) + self.assertRaises(ValueError, stdscr.instr, 0, 2, -2) + # A non-ASCII character of an 8-bit locale reads back as its encoded + # byte (see _encodable for the set). Both instr() and inch() return the + # locale byte for any character that fits the locale's single-byte + # encoding. + encoding = stdscr.encoding + for ch in ('A', 'é', '¤', '€', 'є'): + try: + b = ch.encode(encoding) + except UnicodeEncodeError: + continue + if len(b) != 1: + continue + with self.subTest(ch=ch): + stdscr.addstr(2, 0, ch) + self.assertEqual(stdscr.instr(2, 0, 1), b) + self.assertEqual(stdscr.inch(2, 0), b[0]) + + def test_coordinate_errors(self): + # Addressing a cell outside the window raises curses.error. + win = curses.newwin(5, 10, 0, 0) + self.assertRaises(curses.error, win.move, 100, 100) + self.assertRaises(curses.error, win.move, -1, -1) + self.assertRaises(curses.error, win.addch, 100, 100, ord('x')) + self.assertRaises(curses.error, win.inch, 100, 100) + if hasattr(win, 'chgat'): # chgat() requires wchgat() + self.assertRaises(curses.error, win.chgat, 100, 0, curses.A_BOLD) + + def test_argument_errors(self): + win = curses.newwin(5, 10, 0, 0) + # A character argument must be an int, a byte or a one-element string. + self.assertRaises(TypeError, win.addch, []) + self.assertRaises(OverflowError, win.addch, 2**64) + # A string method rejects a non-string, non-bytes argument. + self.assertRaises(TypeError, win.addstr, 5) + self.assertRaises(TypeError, win.addstr) + # Wrong number of positional arguments. + self.assertRaises(TypeError, win.instr, 0, 0, 0, 0) + + def test_getch(self): + win = curses.newwin(5, 12, 5, 2) + + # TODO: Test with real input by writing to master fd. + for c in 'spam\n'[::-1]: + curses.ungetch(c) + self.assertEqual(win.getch(3, 1), b's'[0]) + self.assertEqual(win.getyx(), (3, 1)) + self.assertEqual(win.getch(3, 4), b'p'[0]) + self.assertEqual(win.getyx(), (3, 4)) + self.assertEqual(win.getch(), b'a'[0]) + self.assertEqual(win.getyx(), (3, 4)) + self.assertEqual(win.getch(), b'm'[0]) + self.assertEqual(win.getch(), b'\n'[0]) + + # A key value > 127 is delivered unchanged (it is not locale text). + curses.ungetch(0xE9) + self.assertEqual(win.getch(), 0xE9) + + def test_getstr(self): + win = curses.newwin(5, 12, 5, 2) + curses.echo() + self.addCleanup(curses.noecho) + + self.assertRaises(ValueError, win.getstr, -400) + self.assertRaises(ValueError, win.getstr, 2, 3, -400) + + # TODO: Test with real input by writing to master fd. + for c in 'Lorem\nipsum\ndolor\nsit\namet\n'[::-1]: + curses.ungetch(c) + self.assertEqual(win.getstr(3, 1, 2), b'Lo') + self.assertEqual(win.instr(3, 0), b' Lo ') + self.assertEqual(win.getstr(3, 5, 10), b'ipsum') + self.assertEqual(win.instr(3, 0), b' Lo ipsum ') + self.assertEqual(win.getstr(1, 5), b'dolor') + self.assertEqual(win.instr(1, 0), b' dolor ') + self.assertEqual(win.getstr(2), b'si') + self.assertEqual(win.instr(1, 0), b'si dolor ') + self.assertEqual(win.getstr(), b'amet') + self.assertEqual(win.instr(1, 0), b'amet dolor ') + + def test_clear(self): + win = curses.newwin(5, 15, 5, 2) + lorem_ipsum(win) + + win.move(0, 8) + win.clrtoeol() + self.assertEqual(win.instr(0, 0).rstrip(), b'Lorem ip') + self.assertEqual(win.instr(1, 0).rstrip(), b'dolor sit amet,') + + win.move(0, 3) + win.clrtobot() + self.assertEqual(win.instr(0, 0).rstrip(), b'Lor') + self.assertEqual(win.instr(1, 0).rstrip(), b'') + + for func in [win.erase, win.clear]: + lorem_ipsum(win) + func() + self.assertEqual(win.instr(0, 0).rstrip(), b'') + self.assertEqual(win.instr(1, 0).rstrip(), b'') + + def test_insert_delete(self): + win = curses.newwin(5, 15, 5, 2) + lorem_ipsum(win) + + win.move(0, 2) + win.delch() + self.assertEqual(win.instr(0, 0), b'Loem ipsum ') + win.delch(0, 7) + self.assertEqual(win.instr(0, 0), b'Loem ipum ') + + win.move(1, 5) + win.deleteln() + self.assertEqual(win.instr(0, 0), b'Loem ipum ') + self.assertEqual(win.instr(1, 0), b'consectetur ') + self.assertEqual(win.instr(2, 0), b'adipiscing elit') + self.assertEqual(win.instr(3, 0), b'sed do eiusmod ') + self.assertEqual(win.instr(4, 0), b' ') + + win.move(1, 5) + win.insertln() + self.assertEqual(win.instr(0, 0), b'Loem ipum ') + self.assertEqual(win.instr(1, 0), b' ') + self.assertEqual(win.instr(2, 0), b'consectetur ') + + win.clear() + lorem_ipsum(win) + win.move(1, 5) + win.insdelln(2) + self.assertEqual(win.instr(0, 0), b'Lorem ipsum ') + self.assertEqual(win.instr(1, 0), b' ') + self.assertEqual(win.instr(2, 0), b' ') + self.assertEqual(win.instr(3, 0), b'dolor sit amet,') + + win.clear() + lorem_ipsum(win) + win.move(1, 5) + win.insdelln(-2) + self.assertEqual(win.instr(0, 0), b'Lorem ipsum ') + self.assertEqual(win.instr(1, 0), b'adipiscing elit') + self.assertEqual(win.instr(2, 0), b'sed do eiusmod ') + self.assertEqual(win.instr(3, 0), b' ') + + def test_scroll(self): + win = curses.newwin(5, 15, 5, 2) + lorem_ipsum(win) + win.scrollok(True) + win.scroll() + self.assertEqual(win.instr(0, 0), b'dolor sit amet,') + win.scroll(2) + self.assertEqual(win.instr(0, 0), b'adipiscing elit') + win.scroll(-3) + self.assertEqual(win.instr(0, 0), b' ') + self.assertEqual(win.instr(2, 0), b' ') + self.assertEqual(win.instr(3, 0), b'adipiscing elit') + win.scrollok(False) + + def test_attributes(self): + # TODO: attr_get(), attr_set(), ... + win = curses.newwin(5, 15, 5, 2) + win.attron(curses.A_BOLD) + win.attroff(curses.A_BOLD) + win.attrset(curses.A_BOLD) + + win.standout() + win.standend() + + @requires_curses_window_meth('chgat') + def test_chgat(self): + win = curses.newwin(5, 15, 5, 2) + win.addstr(2, 0, 'Lorem ipsum') + win.addstr(3, 0, 'dolor sit amet') + + win.move(2, 8) + win.chgat(curses.A_BLINK) + self.assertEqual(win.inch(2, 7), b'p'[0]) + self.assertEqual(win.inch(2, 8), b's'[0] | curses.A_BLINK) + self.assertEqual(win.inch(2, 14), b' '[0] | curses.A_BLINK) + + win.move(2, 1) + win.chgat(3, curses.A_BOLD) + self.assertEqual(win.inch(2, 0), b'L'[0]) + self.assertEqual(win.inch(2, 1), b'o'[0] | curses.A_BOLD) + self.assertEqual(win.inch(2, 3), b'e'[0] | curses.A_BOLD) + self.assertEqual(win.inch(2, 4), b'm'[0]) + + win.chgat(3, 2, curses.A_UNDERLINE) + self.assertEqual(win.inch(3, 1), b'o'[0]) + self.assertEqual(win.inch(3, 2), b'l'[0] | curses.A_UNDERLINE) + self.assertEqual(win.inch(3, 14), b' '[0] | curses.A_UNDERLINE) + + win.chgat(3, 4, 7, curses.A_BLINK) + self.assertEqual(win.inch(3, 3), b'o'[0] | curses.A_UNDERLINE) + self.assertEqual(win.inch(3, 4), b'r'[0] | curses.A_BLINK) + self.assertEqual(win.inch(3, 10), b'a'[0] | curses.A_BLINK) + self.assertEqual(win.inch(3, 11), b'm'[0] | curses.A_UNDERLINE) + self.assertEqual(win.inch(3, 14), b' '[0] | curses.A_UNDERLINE) + + def test_background(self): + win = curses.newwin(5, 15, 5, 2) + win.addstr(0, 0, 'Lorem ipsum') + + self.assertIn(win.getbkgd(), (0, 32)) + + # bkgdset() + win.bkgdset('_') + self.assertEqual(win.getbkgd(), b'_'[0]) + win.bkgdset(b'#') + self.assertEqual(win.getbkgd(), b'#'[0]) + win.bkgdset(65) + self.assertEqual(win.getbkgd(), 65) + win.bkgdset(0) + self.assertEqual(win.getbkgd(), 32) + + win.bkgdset('#', curses.A_REVERSE) + self.assertEqual(win.getbkgd(), b'#'[0] | curses.A_REVERSE) + self.assertEqual(win.inch(0, 0), b'L'[0]) + self.assertEqual(win.inch(0, 5), b' '[0]) + win.bkgdset(0) + + # bkgd() + win.bkgd('_') + self.assertEqual(win.getbkgd(), b'_'[0]) + self.assertEqual(win.inch(0, 0), b'L'[0]) + self.assertEqual(win.inch(0, 5), b'_'[0]) + + win.bkgd('#', curses.A_REVERSE) + self.assertEqual(win.getbkgd(), b'#'[0] | curses.A_REVERSE) + self.assertEqual(win.inch(0, 0), b'L'[0] | curses.A_REVERSE) + self.assertEqual(win.inch(0, 5), b'#'[0] | curses.A_REVERSE) + + # A non-ASCII background character of an 8-bit locale reads back as its + # encoded byte. See _encodable for the character set. + win.bkgd(' ') + encoding = win.encoding + for ch in ('é', '¤', '€', 'є'): + try: + b = ch.encode(encoding) + except UnicodeEncodeError: + continue + if len(b) != 1: + continue + # A wide build stores a character outside Latin-1 as a wide cell, + # not as its encoded byte, so it cannot round-trip here. + if ord(ch) > 0xff and hasattr(win, 'get_wch'): + continue + with self.subTest(ch=ch): + win.bkgd(ch) + self.assertEqual(win.getbkgd(), b[0]) + if ord(ch) < 0x100: + # The same byte given as an int. A wide build stores it + # through the locale, so only a Latin-1 byte round-trips. + win.bkgd(' ') + win.bkgdset(b[0]) + self.assertEqual(win.getbkgd(), b[0]) + win.bkgd(b[0]) + self.assertEqual(win.getbkgd(), b[0]) + + def test_overlay(self): + srcwin = curses.newwin(5, 18, 3, 4) + lorem_ipsum(srcwin) + dstwin = curses.newwin(7, 17, 5, 7) + for i in range(6): + dstwin.addstr(i, 0, '_'*17) + + srcwin.overlay(dstwin) + self.assertEqual(dstwin.instr(0, 0), b'sectetur_________') + self.assertEqual(dstwin.instr(1, 0), b'piscing_elit,____') + self.assertEqual(dstwin.instr(2, 0), b'_do_eiusmod______') + self.assertEqual(dstwin.instr(3, 0), b'_________________') + + srcwin.overwrite(dstwin) + self.assertEqual(dstwin.instr(0, 0), b'sectetur __') + self.assertEqual(dstwin.instr(1, 0), b'piscing elit, __') + self.assertEqual(dstwin.instr(2, 0), b' do eiusmod __') + self.assertEqual(dstwin.instr(3, 0), b'_________________') + + srcwin.overlay(dstwin, 1, 4, 3, 2, 4, 11) + self.assertEqual(dstwin.instr(3, 0), b'__r_sit_amet_____') + self.assertEqual(dstwin.instr(4, 0), b'__ectetur________') + self.assertEqual(dstwin.instr(5, 0), b'_________________') + + srcwin.overwrite(dstwin, 1, 4, 3, 2, 4, 11) + self.assertEqual(dstwin.instr(3, 0), b'__r sit amet_____') + self.assertEqual(dstwin.instr(4, 0), b'__ectetur _____') + self.assertEqual(dstwin.instr(5, 0), b'_________________') + + def test_refresh(self): + win = curses.newwin(5, 15, 2, 5) + win.noutrefresh() + win.redrawln(1, 2) + win.redrawwin() + win.refresh() + curses.doupdate() + + @requires_curses_window_meth('resize') + def test_resize(self): + win = curses.newwin(5, 15, 2, 5) + win.resize(4, 20) + self.assertEqual(win.getmaxyx(), (4, 20)) + win.resize(5, 15) + self.assertEqual(win.getmaxyx(), (5, 15)) + + @requires_curses_window_meth('enclose') + def test_enclose(self): + win = curses.newwin(5, 15, 2, 5) + self.assertIs(win.enclose(2, 5), True) + self.assertIs(win.enclose(1, 5), False) + self.assertIs(win.enclose(2, 4), False) + self.assertIs(win.enclose(6, 19), True) + self.assertIs(win.enclose(7, 19), False) + self.assertIs(win.enclose(6, 20), False) + + def test_putwin(self): + win = curses.newwin(5, 12, 1, 2) + win.addstr(2, 1, 'Lorem ipsum') + with tempfile.TemporaryFile() as f: + win.putwin(f) + del win + f.seek(0) + win = curses.getwin(f) + self.assertEqual(win.getbegyx(), (1, 2)) + self.assertEqual(win.getmaxyx(), (5, 12)) + self.assertEqual(win.instr(2, 0), b' Lorem ipsum') + + def test_borders_and_lines(self): + win = curses.newwin(5, 10, 5, 2) + win.border('|', '!', '-', '_', + '+', '\\', '#', '/') + self.assertEqual(win.instr(0, 0), b'+--------\\') + self.assertEqual(win.instr(1, 0), b'| !') + self.assertEqual(win.instr(4, 0), b'#________/') + win.border(b'|', b'!', b'-', b'_', + b'+', b'\\', b'#', b'/') + win.border(65, 66, 67, 68, + 69, 70, 71, 72) + self.assertRaises(TypeError, win.border, + 65, 66, 67, 68, 69, [], 71, 72) + self.assertRaises(TypeError, win.border, + 65, 66, 67, 68, 69, 70, 71, 72, 73) + self.assertRaises(TypeError, win.border, + 65, 66, 67, 68, 69, 70, 71, 72, 73) + win.border(65, 66, 67, 68, 69, 70, 71) + win.border(65, 66, 67, 68, 69, 70) + win.border(65, 66, 67, 68, 69) + win.border(65, 66, 67, 68) + win.border(65, 66, 67) + win.border(65, 66) + win.border(65) + win.border() + # With no arguments, border() fills the edges with ACS line and corner + # characters. + chartext = curses.A_CHARTEXT + maxy, maxx = win.getmaxyx() + self.assertEqual(win.inch(0, 0) & chartext, curses.ACS_ULCORNER & chartext) + self.assertEqual(win.inch(0, maxx-1) & chartext, curses.ACS_URCORNER & chartext) + self.assertEqual(win.inch(maxy-1, 0) & chartext, curses.ACS_LLCORNER & chartext) + self.assertEqual(win.inch(maxy-1, maxx-1) & chartext, curses.ACS_LRCORNER & chartext) + self.assertEqual(win.inch(0, 1) & chartext, curses.ACS_HLINE & chartext) + self.assertEqual(win.inch(1, 0) & chartext, curses.ACS_VLINE & chartext) + + win.box(':', '~') + self.assertEqual(win.instr(0, 1, 8), b'~~~~~~~~') + self.assertEqual(win.instr(1, 0), b': :') + self.assertEqual(win.instr(4, 1, 8), b'~~~~~~~~') + win.box(b':', b'~') + win.box(65, 67) + self.assertRaises(TypeError, win.box, 65, 66, 67) + self.assertRaises(TypeError, win.box, 65) + win.box() + # With no arguments, box() likewise draws ACS corners and lines. + self.assertEqual(win.inch(0, 0) & chartext, curses.ACS_ULCORNER & chartext) + self.assertEqual(win.inch(0, maxx-1) & chartext, curses.ACS_URCORNER & chartext) + self.assertEqual(win.inch(0, 1) & chartext, curses.ACS_HLINE & chartext) + self.assertEqual(win.inch(1, 0) & chartext, curses.ACS_VLINE & chartext) + + win.move(1, 2) + win.hline('-', 5) + self.assertEqual(win.instr(1, 1, 7), b' ----- ') + win.hline(b'-', 5) + win.hline(45, 5) + win.hline('-', 5, curses.A_BOLD) + win.hline(1, 1, '-', 5) + win.hline(1, 1, '-', 5, curses.A_BOLD) + + win.move(1, 2) + win.vline('a', 3) + win.vline(b'a', 3) + win.vline(97, 3) + win.vline('a', 3, curses.A_STANDOUT) + win.vline(1, 1, 'a', 3) + win.vline(1, 1, ';', 2, curses.A_STANDOUT) + self.assertEqual(win.inch(1, 1), b';'[0] | curses.A_STANDOUT) + self.assertEqual(win.inch(2, 1), b';'[0] | curses.A_STANDOUT) + self.assertEqual(win.inch(3, 1), b'a'[0]) + + # A border or line character of an 8-bit locale round-trips as its + # encoded byte. See _encodable for the character set. + encoding = win.encoding + for ch in ('é', '¤', '€', 'є'): + try: + b = ch.encode(encoding) + except UnicodeEncodeError: + continue + if len(b) != 1: + continue + # A wide build stores a character outside Latin-1 as a wide cell, + # not as its encoded byte, so it cannot round-trip here. + if ord(ch) > 0xff and hasattr(win, 'get_wch'): + continue + with self.subTest(ch=ch): + win.erase() + win.hline(2, 0, ch, 5) + self.assertEqual(win.instr(2, 0, 5), b * 5) + win.vline(0, 0, ch, 3) + self.assertEqual(win.instr(0, 0, 1), b) + self.assertEqual(win.instr(1, 0, 1), b) + win.border(ch, ch, ch, ch, ch, ch, ch, ch) + self.assertEqual(win.instr(0, 0), b * maxx) + if ord(ch) < 0x100: + # The same byte given as an int. A wide build stores it + # through the locale, so only a Latin-1 byte round-trips. + v = b[0] + win.erase() + win.hline(2, 0, v, 5) + self.assertEqual(win.instr(2, 0, 5), b * 5) + win.vline(0, 0, v, 3) + self.assertEqual(win.instr(1, 0, 1), b) + win.border(v, v, v, v, v, v, v, v) + self.assertEqual(win.instr(0, 0), b * maxx) + win.box(v, v) + self.assertEqual(win.instr(0, 1, 1), b) + + def test_unctrl(self): + # TODO: wunctrl() + self.assertEqual(curses.unctrl(b'A'), b'A') + self.assertEqual(curses.unctrl('A'), b'A') + self.assertEqual(curses.unctrl(65), b'A') + self.assertEqual(curses.unctrl(b'\n'), b'^J') + self.assertEqual(curses.unctrl('\n'), b'^J') + self.assertEqual(curses.unctrl(10), b'^J') + # A printable non-ASCII byte of an 8-bit locale is returned unchanged. + # See _encodable for the character set. + encoding = self.stdscr.encoding + for ch in ('é', '¤', '€', 'є'): + try: + b = ch.encode(encoding) + except UnicodeEncodeError: + continue + if len(b) != 1: + continue + with self.subTest(ch=ch): + self.assertEqual(curses.unctrl(ch), b) + self.assertEqual(curses.unctrl(b[0]), b) # the byte as an int + self.assertRaises(TypeError, curses.unctrl, b'') + self.assertRaises(TypeError, curses.unctrl, b'AB') + self.assertRaises(TypeError, curses.unctrl, '') + self.assertRaises(TypeError, curses.unctrl, 'AB') + self.assertRaises(OverflowError, curses.unctrl, 2**64) + + def test_endwin(self): + if not self.isatty: + self.skipTest('requires terminal') + self.assertIs(curses.isendwin(), False) + curses.endwin() + self.assertIs(curses.isendwin(), True) + curses.doupdate() + self.assertIs(curses.isendwin(), False) + + def test_terminfo(self): + self.assertIsInstance(curses.tigetflag('hc'), int) + self.assertEqual(curses.tigetflag('cols'), -1) + self.assertEqual(curses.tigetflag('cr'), -1) + + self.assertIsInstance(curses.tigetnum('cols'), int) + self.assertEqual(curses.tigetnum('hc'), -2) + self.assertEqual(curses.tigetnum('cr'), -2) + + self.assertIsInstance(curses.tigetstr('cr'), (bytes, type(None))) + self.assertIsNone(curses.tigetstr('hc')) + self.assertIsNone(curses.tigetstr('cols')) + + cud = curses.tigetstr('cud') + if cud is not None: + # See issue10570. + self.assertIsInstance(cud, bytes) + curses.tparm(cud, 2) + cud_2 = curses.tparm(cud, 2) + self.assertIsInstance(cud_2, bytes) + curses.putp(cud_2) + + curses.putp(b'abc\n') + + def test_misc_module_funcs(self): + curses.delay_output(1) + curses.flushinp() + + curses.doupdate() + self.assertIs(curses.isendwin(), False) + + curses.napms(100) + + curses.newpad(50, 50) + + def test_env_queries(self): + # TODO: term_attrs(), erasewchar(), killwchar() + self.assertIsInstance(curses.termname(), bytes) + self.assertIsInstance(curses.longname(), bytes) + self.assertIsInstance(curses.baudrate(), int) + self.assertIsInstance(curses.has_ic(), bool) + self.assertIsInstance(curses.has_il(), bool) + self.assertIsInstance(curses.termattrs(), int) + + c = curses.killchar() + self.assertIsInstance(c, bytes) + self.assertEqual(len(c), 1) + c = curses.erasechar() + self.assertIsInstance(c, bytes) + self.assertEqual(len(c), 1) + + def test_output_options(self): + stdscr = self.stdscr + + stdscr.clearok(True) + stdscr.clearok(False) + + stdscr.idcok(True) + stdscr.idcok(False) + + stdscr.idlok(False) + stdscr.idlok(True) + + if hasattr(stdscr, 'immedok'): + stdscr.immedok(True) + stdscr.immedok(False) + + stdscr.leaveok(True) + stdscr.leaveok(False) + + stdscr.scrollok(True) + stdscr.scrollok(False) + + stdscr.setscrreg(5, 10) + + curses.nonl() + curses.nl(True) + curses.nl(False) + curses.nl() + + def test_input_options(self): + stdscr = self.stdscr + + if self.isatty: + curses.nocbreak() + curses.cbreak() + curses.cbreak(False) + curses.cbreak(True) + + curses.intrflush(True) + curses.intrflush(False) + + curses.raw() + curses.raw(False) + curses.raw(True) + curses.noraw() + + curses.noecho() + curses.echo() + curses.echo(False) + curses.echo(True) + + curses.halfdelay(255) + curses.halfdelay(1) + + stdscr.keypad(True) + stdscr.keypad(False) + + curses.meta(True) + curses.meta(False) + + stdscr.nodelay(True) + stdscr.nodelay(False) + + curses.noqiflush() + curses.qiflush(True) + curses.qiflush(False) + curses.qiflush() + + stdscr.notimeout(True) + stdscr.notimeout(False) + + stdscr.timeout(-1) + stdscr.timeout(0) + stdscr.timeout(5) + + @requires_curses_func('typeahead') + def test_typeahead(self): + curses.typeahead(sys.__stdin__.fileno()) + curses.typeahead(-1) + + def test_prog_mode(self): + if not self.isatty: + self.skipTest('requires terminal') + curses.def_prog_mode() + curses.reset_prog_mode() + # def_shell_mode()/reset_shell_mode() are intentionally not exercised + # here: they capture and restore curses' "shell mode" terminal state, + # which is only meaningful before initscr(). Calling them mid-suite + # corrupts the modes that endwin() restores and breaks later tests. + + def test_beep(self): + if (curses.tigetstr("bel") is not None + or curses.tigetstr("flash") is not None): + curses.beep() + else: + try: + curses.beep() + except curses.error: + self.skipTest('beep() failed') + + def test_flash(self): + if (curses.tigetstr("bel") is not None + or curses.tigetstr("flash") is not None): + curses.flash() + else: + try: + curses.flash() + except curses.error: + self.skipTest('flash() failed') + + def test_curs_set(self): + for vis, cap in [(0, 'civis'), (2, 'cvvis'), (1, 'cnorm')]: + if curses.tigetstr(cap) is not None: + curses.curs_set(vis) + else: + try: + curses.curs_set(vis) + except curses.error: + pass + + @requires_curses_func('get_escdelay') + def test_escdelay(self): + escdelay = curses.get_escdelay() + self.assertIsInstance(escdelay, int) + curses.set_escdelay(25) + self.assertEqual(curses.get_escdelay(), 25) + curses.set_escdelay(escdelay) + + @requires_curses_func('get_tabsize') + def test_tabsize(self): + tabsize = curses.get_tabsize() + self.assertIsInstance(tabsize, int) + curses.set_tabsize(4) + self.assertEqual(curses.get_tabsize(), 4) + curses.set_tabsize(tabsize) + + @requires_curses_func('getsyx') + def test_getsyx(self): + y, x = curses.getsyx() + self.assertIsInstance(y, int) + self.assertIsInstance(x, int) + curses.setsyx(4, 5) + self.assertEqual(curses.getsyx(), (4, 5)) + + def bad_colors(self): + return (-1, curses.COLORS, -2**31 - 1, 2**31, -2**63 - 1, 2**63, 2**64) + + def bad_colors2(self): + return (curses.COLORS, 2**31, 2**63, 2**64) + + def bad_pairs(self): + return (-1, -2**31 - 1, 2**31, -2**63 - 1, 2**63, 2**64) + + def test_has_colors(self): + self.assertIsInstance(curses.has_colors(), bool) + self.assertIsInstance(curses.can_change_color(), bool) + + def test_start_color(self): + if not curses.has_colors(): + self.skipTest('requires colors support') + curses.start_color() + if verbose: + print(f'COLORS = {curses.COLORS}', file=sys.stderr) + print(f'COLOR_PAIRS = {curses.COLOR_PAIRS}', file=sys.stderr) + + @requires_colors + def test_color_content(self): + self.assertEqual(curses.color_content(curses.COLOR_BLACK), (0, 0, 0)) + curses.color_content(0) + maxcolor = curses.COLORS - 1 + curses.color_content(maxcolor) + + for color in self.bad_colors(): + self.assertRaises(ValueError, curses.color_content, color) + + @requires_colors + def test_init_color(self): + if not curses.can_change_color(): + self.skipTest('cannot change color') + + old = curses.color_content(0) + try: + curses.init_color(0, *old) + except curses.error: + self.skipTest('cannot change color (init_color() failed)') + self.addCleanup(curses.init_color, 0, *old) + curses.init_color(0, 0, 0, 0) + self.assertEqual(curses.color_content(0), (0, 0, 0)) + curses.init_color(0, 1000, 1000, 1000) + self.assertEqual(curses.color_content(0), (1000, 1000, 1000)) + + maxcolor = curses.COLORS - 1 + old = curses.color_content(maxcolor) + curses.init_color(maxcolor, *old) + self.addCleanup(curses.init_color, maxcolor, *old) + curses.init_color(maxcolor, 0, 500, 1000) + self.assertEqual(curses.color_content(maxcolor), (0, 500, 1000)) + + for color in self.bad_colors(): + self.assertRaises(ValueError, curses.init_color, color, 0, 0, 0) + for comp in (-1, 1001): + self.assertRaises(ValueError, curses.init_color, 0, comp, 0, 0) + self.assertRaises(ValueError, curses.init_color, 0, 0, comp, 0) + self.assertRaises(ValueError, curses.init_color, 0, 0, 0, comp) + + def get_pair_limit(self): + pair_limit = curses.COLOR_PAIRS + if hasattr(curses, 'ncurses_version'): + if curses.has_extended_color_support(): + pair_limit += 2*curses.COLORS + 1 + if (not curses.has_extended_color_support() + or (6, 1) <= curses.ncurses_version < (6, 2)): + pair_limit = min(pair_limit, SHORT_MAX) + # If use_default_colors() is called, the upper limit of the extended + # range may be restricted, so we need to check if the limit is still + # correct + try: + curses.init_pair(pair_limit - 1, 0, 0) + except ValueError: + pair_limit = curses.COLOR_PAIRS + return pair_limit + + @requires_colors + def test_pair_content(self): + curses.pair_content(0) + maxpair = self.get_pair_limit() - 1 + if maxpair > 0: + curses.pair_content(maxpair) + + for pair in self.bad_pairs(): + self.assertRaises(ValueError, curses.pair_content, pair) + + @requires_colors + def test_init_pair(self): + old = curses.pair_content(1) + curses.init_pair(1, *old) + self.addCleanup(curses.init_pair, 1, *old) + + curses.init_pair(1, 0, 0) + self.assertEqual(curses.pair_content(1), (0, 0)) + maxcolor = curses.COLORS - 1 + curses.init_pair(1, maxcolor, 0) + self.assertEqual(curses.pair_content(1), (maxcolor, 0)) + curses.init_pair(1, 0, maxcolor) + self.assertEqual(curses.pair_content(1), (0, maxcolor)) + maxpair = self.get_pair_limit() - 1 + if maxpair > 1: + curses.init_pair(maxpair, 0, 0) + self.assertEqual(curses.pair_content(maxpair), (0, 0)) + + for pair in self.bad_pairs(): + self.assertRaises(ValueError, curses.init_pair, pair, 0, 0) + for color in self.bad_colors2(): + self.assertRaises(ValueError, curses.init_pair, 1, color, 0) + self.assertRaises(ValueError, curses.init_pair, 1, 0, color) + + @requires_colors + def test_color_attrs(self): + for pair in 0, 1, 255: + attr = curses.color_pair(pair) + self.assertEqual(curses.pair_number(attr), pair, attr) + self.assertEqual(curses.pair_number(attr | curses.A_BOLD), pair) + self.assertEqual(curses.color_pair(0), 0) + self.assertEqual(curses.pair_number(0), 0) + + @requires_curses_func('use_default_colors') + @requires_colors + def test_use_default_colors(self): + try: + curses.use_default_colors() + except curses.error: + self.skipTest('cannot change color (use_default_colors() failed)') + self.assertEqual(curses.pair_content(0), (-1, -1)) + + @requires_curses_func('assume_default_colors') + @requires_colors + def test_assume_default_colors(self): + try: + curses.assume_default_colors(-1, -1) + except curses.error: + self.skipTest('cannot change color (assume_default_colors() failed)') + self.assertEqual(curses.pair_content(0), (-1, -1)) + curses.assume_default_colors(curses.COLOR_YELLOW, curses.COLOR_BLUE) + self.assertEqual(curses.pair_content(0), (curses.COLOR_YELLOW, curses.COLOR_BLUE)) + curses.assume_default_colors(curses.COLOR_RED, -1) + self.assertEqual(curses.pair_content(0), (curses.COLOR_RED, -1)) + curses.assume_default_colors(-1, curses.COLOR_GREEN) + self.assertEqual(curses.pair_content(0), (-1, curses.COLOR_GREEN)) + curses.assume_default_colors(-1, -1) + + def test_keyname(self): + # TODO: key_name() + self.assertEqual(curses.keyname(65), b'A') + self.assertEqual(curses.keyname(13), b'^M') + self.assertEqual(curses.keyname(127), b'^?') + self.assertEqual(curses.keyname(0), b'^@') + self.assertRaises(ValueError, curses.keyname, -1) + self.assertIsInstance(curses.keyname(256), bytes) + + @requires_curses_func('has_key') + def test_has_key(self): + self.assertIsInstance(curses.has_key(13), bool) + self.assertIsInstance(curses.has_key(curses.KEY_LEFT), bool) + + @requires_curses_func('getmouse') + def test_getmouse(self): + (availmask, oldmask) = curses.mousemask(curses.BUTTON1_PRESSED) + if availmask == 0: + self.skipTest('mouse stuff not available') + curses.mouseinterval(10) + # just verify these don't cause errors + curses.ungetmouse(0, 0, 0, 0, curses.BUTTON1_PRESSED) + m = curses.getmouse() + + @requires_curses_func('panel') + def test_userptr_without_set(self): + w = curses.newwin(10, 10) + p = curses.panel.new_panel(w) + # try to access userptr() before calling set_userptr() -- segfaults + with self.assertRaises(curses.panel.error, + msg='userptr should fail since not set'): + p.userptr() + + @requires_curses_func('panel') + def test_userptr_memory_leak(self): + w = curses.newwin(10, 10) + p = curses.panel.new_panel(w) + obj = object() + nrefs = sys.getrefcount(obj) + for i in range(100): + p.set_userptr(obj) + + p.set_userptr(None) + self.assertEqual(sys.getrefcount(obj), nrefs, + "set_userptr leaked references") + + @requires_curses_func('panel') + def test_userptr_segfault(self): + w = curses.newwin(10, 10) + panel = curses.panel.new_panel(w) + class A: + def __del__(self): + panel.set_userptr(None) + panel.set_userptr(A()) + panel.set_userptr(None) + + @cpython_only + @requires_curses_func('panel') + def test_disallow_instantiation(self): + # Ensure that the type disallows instantiation (bpo-43916) + w = curses.newwin(10, 10) + panel = curses.panel.new_panel(w) + check_disallow_instantiation(self, type(panel)) + + @requires_curses_func('panel') + def test_panel_stack(self): + panel = curses.panel + # new_panel() puts the panel on top of the stack, so the three + # panels end up ordered bottom -> top as p1, p2, p3. + p1 = panel.new_panel(curses.newwin(3, 6, 0, 0)) + p2 = panel.new_panel(curses.newwin(3, 6, 1, 1)) + p3 = panel.new_panel(curses.newwin(3, 6, 2, 2)) + self.addCleanup(self._delete_panels, p1, p2, p3) + + # The most recently created panel is on top. + self.assertIs(panel.top_panel(), p3) + # window() returns the wrapped window. + self.assertEqual(p2.window().getbegyx(), (1, 1)) + + # above()/below() walk the stack one step at a time. + self.assertIs(p1.above(), p2) + self.assertIs(p2.above(), p3) + self.assertIsNone(p3.above()) # nothing above the top panel + self.assertIs(p3.below(), p2) + self.assertIs(p2.below(), p1) + + # top() raises a panel to the top, bottom() lowers it to the bottom. + p1.top() + self.assertIs(panel.top_panel(), p1) + self.assertIsNone(p1.above()) + p1.bottom() + self.assertIs(panel.bottom_panel(), p1) + self.assertIsNone(p1.below()) + + # update_panels() refreshes the virtual screen from the stack. + panel.update_panels() + + @requires_curses_func('panel') + def test_panel_hide_show(self): + p = curses.panel.new_panel(curses.newwin(3, 6, 0, 0)) + self.addCleanup(self._delete_panels, p) + self.assertIs(p.hidden(), False) + p.hide() + self.assertIs(p.hidden(), True) + p.show() + self.assertIs(p.hidden(), False) + + @requires_curses_func('panel') + def test_panel_move(self): + win = curses.newwin(3, 6, 1, 2) + p = curses.panel.new_panel(win) + self.addCleanup(self._delete_panels, p) + self.assertEqual(win.getbegyx(), (1, 2)) + p.move(4, 5) + self.assertEqual(win.getbegyx(), (4, 5)) + + @requires_curses_func('panel') + def test_panel_replace(self): + win1 = curses.newwin(3, 6, 0, 0) + win2 = curses.newwin(4, 8, 1, 1) + p = curses.panel.new_panel(win1) + self.addCleanup(self._delete_panels, p) + self.assertIs(p.window(), win1) + p.replace(win2) + self.assertIs(p.window(), win2) + + @requires_curses_func('panel') + def test_panel_userptr(self): + p = curses.panel.new_panel(curses.newwin(3, 6, 0, 0)) + self.addCleanup(self._delete_panels, p) + obj = ['userptr'] + p.set_userptr(obj) + self.assertIs(p.userptr(), obj) + + def _delete_panels(self, *panels): + # Drop the panels from the global stack so they do not leak into + # later tests that inspect top_panel()/bottom_panel(). + for p in panels: + try: + p.bottom() + except curses.panel.error: + pass + del panels + gc_collect() + + def _make_textbox(self, nlines, ncols, *, insert_mode=False, stripspaces=1): + win = curses.newwin(nlines, ncols, 0, 0) + box = curses.textpad.Textbox(win, insert_mode=insert_mode) + box.stripspaces = stripspaces + return box, win + + def _type(self, box, text): + for ch in text: + box.do_command(ch if isinstance(ch, int) else ord(ch)) + + def test_textbox_gather(self): + # Typed text is read back by gather(). With stripspaces on (the + # default) gather() keeps a single trailing blank on a line and + # drops trailing empty lines. + box, win = self._make_textbox(3, 10) + self._type(box, 'Hello') + self.assertEqual(box.gather(), 'Hello \n') + + def test_textbox_gather_multiline(self): + box, win = self._make_textbox(3, 10) + self._type(box, 'ab') + box.do_command(curses.ascii.NL) # ^j -> start of next line + self._type(box, 'cd') + self.assertEqual(box.gather(), 'ab \ncd \n') + + def test_textbox_stripspaces(self): + box, win = self._make_textbox(1, 8, stripspaces=1) + self._type(box, 'hi') + self.assertEqual(box.gather(), 'hi ') + + box, win = self._make_textbox(1, 8, stripspaces=0) + self._type(box, 'hi') + self.assertEqual(box.gather(), 'hi ') + + def test_textbox_insert_mode(self): + # In insert mode a typed character shifts the rest of the line right. + box, win = self._make_textbox(1, 10, insert_mode=True) + self._type(box, 'aXc') + win.move(0, 1) + self._type(box, 'b') + self.assertEqual(box.gather(), 'abXc ') + + def test_textbox_fill_last_cell(self): + # The lower-right cell can be written, even though addch() there + # cannot advance the cursor past the end of the window. + box, win = self._make_textbox(1, 4, stripspaces=0) + self._type(box, 'abcd') + self.assertEqual(box.gather(), 'abcd') + + def test_textbox_fill_last_cell_multiline(self): + box, win = self._make_textbox(2, 3, stripspaces=0) + self._type(box, 'abc') + box.do_command(curses.ascii.NL) # ^j -> start of next line + self._type(box, 'def') # 'f' lands in the lower-right cell + self.assertEqual(box.gather(), 'abc\ndef\n') + + def test_textbox_fill_last_cell_insert_mode(self): + box, win = self._make_textbox(1, 4, insert_mode=True, stripspaces=0) + self._type(box, 'abcd') + self.assertEqual(box.gather(), 'abcd') + + def test_textbox_fill_last_cell_scrollok(self): + # Writing the lower-right cell must not scroll the window even if it + # has scrolling enabled. + box, win = self._make_textbox(2, 3, stripspaces=0) + win.scrollok(True) + self._type(box, 'abc') + box.do_command(curses.ascii.NL) + self._type(box, 'def') + self.assertEqual(box.gather(), 'abc\ndef\n') + + def test_textbox_8bit(self): + # A character of an 8-bit locale encoding is entered and read back + # through the byte API. The byte path also runs on a wide build, so the + # test is not skipped there. Run the suite under an 8-bit locale + # (ISO-8859-1, ISO-8859-15 or KOI8-U) to reach the non-ASCII cases; each + # string is used only if the encoding maps it to single bytes. 'abc' is + # ASCII, 'café' is common to the Latin encodings, and the rest are + # distinctive (byte 0xA4 is '¤'/'€'/'є' in ISO-8859-1/-15/KOI8-U). + encoding = self.stdscr.encoding + for text in ['abc', 'café', 'naïve ¤¦', 'café €Šž', 'дякую єі']: + try: + data = text.encode(encoding) + except UnicodeEncodeError: + continue + if len(data) != len(text): + continue # a multibyte encoding is not the 8-bit byte path + with self.subTest(text=text): + box, win = self._make_textbox(1, 16) + for byte in data: + box.do_command(byte) + self.assertEqual(box.gather(), text + ' ') + + def test_textbox_8bit_insert(self): + # Insert mode shifts the rest of the line right by reading each cell back + # and rewriting it; a non-ASCII 8-bit-locale character must survive the + # shift, even on a wide build where inch() mangles it. See + # test_textbox_8bit for the character choices. + encoding = self.stdscr.encoding + for ch in ['é', '¤', '€', 'є']: + try: + data = ch.encode(encoding) + except UnicodeEncodeError: + continue + if len(data) != 1: + continue + with self.subTest(ch=ch): + box, win = self._make_textbox(1, 10, insert_mode=True) + for byte in ('a' + ch + 'c').encode(encoding): + box.do_command(byte) + win.move(0, 1) + box.do_command(ord('b')) # insert 'b', shifting ch and 'c' right + self.assertEqual(box.gather(), 'ab' + ch + 'c ') + + def test_textbox_8bit_fill_last_cell(self): + # A non-ASCII 8-bit-locale character must survive being written to the + # lower-right cell, which uses insch() rather than addch(). See + # test_textbox_8bit for the character choices. + encoding = self.stdscr.encoding + for ch in ['é', '¤', '€', 'є']: + try: + data = ch.encode(encoding) + except UnicodeEncodeError: + continue + if len(data) != 1: + continue + with self.subTest(ch=ch): + text = 'ab' + ch # the last character fills the corner + box, win = self._make_textbox(1, len(text), stripspaces=0) + for byte in text.encode(encoding): + box.do_command(byte) + self.assertEqual(box.gather(), text) + + def test_textbox_movement(self): + box, win = self._make_textbox(3, 10) + self._type(box, 'abc') + box.do_command(curses.ascii.SOH) # ^a -> left edge + self.assertEqual(win.getyx(), (0, 0)) + box.do_command(curses.ascii.ENQ) # ^e -> end of line + self.assertEqual(win.getyx(), (0, 3)) + + def test_textbox_kill_to_eol(self): + box, win = self._make_textbox(1, 10) + self._type(box, 'abcdef') + win.move(0, 3) + box.do_command(curses.ascii.VT) # ^k -> clear to end of line + self.assertEqual(box.gather(), 'abc ') + + def test_textbox_backspace(self): + box, win = self._make_textbox(1, 10) + self._type(box, 'abc') + box.do_command(curses.ascii.BS) # ^h -> delete backward + self.assertEqual(box.gather(), 'ab ') + + def test_textbox_edit(self): + # edit() reads characters until Ctrl-G and returns the contents. + box, win = self._make_textbox(1, 10) + for ch in reversed('Hi' + chr(curses.ascii.BEL)): + curses.ungetch(ch) + self.assertEqual(box.edit(), 'Hi ') + + def test_textbox_edit_validate(self): + # The validate hook can rewrite an incoming keystroke. + box, win = self._make_textbox(1, 10) + for ch in reversed('abc' + chr(curses.ascii.BEL)): + curses.ungetch(ch) + box.edit(lambda ch: ord('X') if ch == ord('b') else ch) + self.assertEqual(box.gather(), 'aXc ') + + def test_textpad_rectangle(self): + # rectangle() draws a box with ACS line/corner characters. + win = curses.newwin(6, 12, 0, 0) + curses.textpad.rectangle(win, 0, 0, 4, 8) + chartext = curses.A_CHARTEXT + self.assertEqual(win.inch(0, 0) & chartext, + curses.ACS_ULCORNER & chartext) + self.assertEqual(win.inch(0, 8) & chartext, + curses.ACS_URCORNER & chartext) + self.assertEqual(win.inch(4, 0) & chartext, + curses.ACS_LLCORNER & chartext) + self.assertEqual(win.inch(4, 8) & chartext, + curses.ACS_LRCORNER & chartext) + self.assertEqual(win.inch(0, 1) & chartext, + curses.ACS_HLINE & chartext) + self.assertEqual(win.inch(1, 0) & chartext, + curses.ACS_VLINE & chartext) + + def test_wrapper(self): + # wrapper() sets up curses, passes the screen to the callable along + # with extra arguments, returns its result and restores the terminal. + if not self.isatty: + self.skipTest('requires terminal') + + def body(stdscr, a, b): + self.assertIsInstance(stdscr, type(self.stdscr)) + self.assertIs(curses.isendwin(), False) + return a + b + + self.assertEqual(curses.wrapper(body, 2, 3), 5) + self.assertIs(curses.isendwin(), True) + # wrapper() left the screen ended; revive it so the per-test + # endwin() cleanup does not fail with ERR. + curses.doupdate() + + @requires_curses_func('is_term_resized') + def test_is_term_resized(self): + lines, cols = curses.LINES, curses.COLS + self.assertIs(curses.is_term_resized(lines, cols), False) + self.assertIs(curses.is_term_resized(lines-1, cols-1), True) + + @requires_curses_func('resize_term') + def test_resize_term(self): + curses.update_lines_cols() + lines, cols = curses.LINES, curses.COLS + new_lines = lines - 1 + new_cols = cols + 1 + curses.resize_term(new_lines, new_cols) + self.assertEqual(curses.LINES, new_lines) + self.assertEqual(curses.COLS, new_cols) + + curses.resize_term(lines, cols) + self.assertEqual(curses.LINES, lines) + self.assertEqual(curses.COLS, cols) + + with self.assertRaises(OverflowError): + curses.resize_term(35000, 1) + with self.assertRaises(OverflowError): + curses.resize_term(1, 35000) + # GH-120378: Overflow failure in resize_term() causes refresh to fail + tmp = curses.initscr() + tmp.erase() + + @requires_curses_func('resizeterm') + def test_resizeterm(self): + curses.update_lines_cols() + lines, cols = curses.LINES, curses.COLS + new_lines = lines - 1 + new_cols = cols + 1 + curses.resizeterm(new_lines, new_cols) + self.assertEqual(curses.LINES, new_lines) + self.assertEqual(curses.COLS, new_cols) + + curses.resizeterm(lines, cols) + self.assertEqual(curses.LINES, lines) + self.assertEqual(curses.COLS, cols) + + with self.assertRaises(OverflowError): + curses.resizeterm(35000, 1) + with self.assertRaises(OverflowError): + curses.resizeterm(1, 35000) + # GH-120378: Overflow failure in resizeterm() causes refresh to fail + tmp = curses.initscr() + tmp.erase() + + def test_ungetch(self): + curses.ungetch(b'A') + self.assertEqual(self.stdscr.getkey(), 'A') + curses.ungetch('B') + self.assertEqual(self.stdscr.getkey(), 'B') + curses.ungetch(67) + self.assertEqual(self.stdscr.getkey(), 'C') + + def test_issue6243(self): + curses.ungetch(1025) + self.stdscr.getkey() + + @requires_curses_func('unget_wch') + @unittest.skipIf(getattr(curses, 'ncurses_version', (99,)) < (5, 8), + "unget_wch is broken in ncurses 5.7 and earlier") + def test_unget_wch(self): + stdscr = self.stdscr + encoding = stdscr.encoding + # See _encodable for the character set, plus a non-BMP character. + for ch in ('a', '\xe9', '\xa4', '\u20ac', '\u0454', '\U0010FFFF'): + try: + ch.encode(encoding) + except UnicodeEncodeError: + continue + try: + curses.unget_wch(ch) + except Exception as err: + self.fail("unget_wch(%a) failed with encoding %s: %s" + % (ch, stdscr.encoding, err)) + read = stdscr.get_wch() + self.assertEqual(read, ch) + + code = ord(ch) + curses.unget_wch(code) + read = stdscr.get_wch() + self.assertEqual(read, ch) + + def test_encoding(self): + stdscr = self.stdscr + import codecs + encoding = stdscr.encoding + codecs.lookup(encoding) + with self.assertRaises(TypeError): + stdscr.encoding = 10 + stdscr.encoding = encoding + with self.assertRaises(TypeError): + del stdscr.encoding + + @unittest.skipIf(MISSING_C_DOCSTRINGS, + "Signature information for builtins requires docstrings") + def test_issue21088(self): + stdscr = self.stdscr + # + # http://bugs.python.org/issue21088 + # + # the bug: + # when converting curses.window.addch to Argument Clinic + # the first two parameters were switched. + + # if someday we can represent the signature of addch + # we will need to rewrite this test. + try: + signature = inspect.signature(stdscr.addch) + self.assertFalse(signature) + except ValueError: + # not generating a signature is fine. + pass + + # So. No signature for addch. + # But Argument Clinic gave us a human-readable equivalent + # as the first line of the docstring. So we parse that, + # and ensure that the parameters appear in the correct order. + # Since this is parsing output from Argument Clinic, we can + # be reasonably certain the generated parsing code will be + # correct too. + human_readable_signature = stdscr.addch.__doc__.split("\n")[0] + self.assertIn("[y, x,]", human_readable_signature) + + @requires_curses_window_meth('resize') + def test_issue13051(self): + win = curses.newwin(5, 15, 2, 5) + box = curses.textpad.Textbox(win, insert_mode=True) + lines, cols = win.getmaxyx() + win.resize(lines-2, cols-2) + # this may cause infinite recursion, leading to a RuntimeError + box._insert_printable_char('a') + + +class MiscTests(unittest.TestCase): + + @requires_curses_func('update_lines_cols') + def test_update_lines_cols(self): + curses.update_lines_cols() + lines, cols = curses.LINES, curses.COLS + curses.LINES = curses.COLS = 0 + curses.update_lines_cols() + self.assertEqual(curses.LINES, lines) + self.assertEqual(curses.COLS, cols) + + @requires_curses_func('ncurses_version') + def test_ncurses_version(self): + v = curses.ncurses_version + if verbose: + print(f'ncurses_version = {curses.ncurses_version}', flush=True) + self.assertIsInstance(v[:], tuple) + self.assertEqual(len(v), 3) + self.assertIsInstance(v[0], int) + self.assertIsInstance(v[1], int) + self.assertIsInstance(v[2], int) + self.assertIsInstance(v.major, int) + self.assertIsInstance(v.minor, int) + self.assertIsInstance(v.patch, int) + self.assertEqual(v[0], v.major) + self.assertEqual(v[1], v.minor) + self.assertEqual(v[2], v.patch) + self.assertGreaterEqual(v.major, 0) + self.assertGreaterEqual(v.minor, 0) + self.assertGreaterEqual(v.patch, 0) + + def test_has_extended_color_support(self): + r = curses.has_extended_color_support() + self.assertIsInstance(r, bool) + + +class TestAscii(unittest.TestCase): + + def test_controlnames(self): + for name in curses.ascii.controlnames: + self.assertHasAttr(curses.ascii, name) + + def test_ctypes(self): + def check(func, expected): + with self.subTest(ch=c, func=func): + self.assertEqual(func(i), expected) + self.assertEqual(func(c), expected) + + for i in range(256): + c = chr(i) + b = bytes([i]) + check(curses.ascii.isalnum, b.isalnum()) + check(curses.ascii.isalpha, b.isalpha()) + check(curses.ascii.isdigit, b.isdigit()) + check(curses.ascii.islower, b.islower()) + check(curses.ascii.isspace, b.isspace()) + check(curses.ascii.isupper, b.isupper()) + + check(curses.ascii.isascii, i < 128) + check(curses.ascii.ismeta, i >= 128) + check(curses.ascii.isctrl, i < 32) + check(curses.ascii.iscntrl, i < 32 or i == 127) + check(curses.ascii.isblank, c in ' \t') + check(curses.ascii.isgraph, 32 < i <= 126) + check(curses.ascii.isprint, 32 <= i <= 126) + check(curses.ascii.ispunct, c in string.punctuation) + check(curses.ascii.isxdigit, c in string.hexdigits) + + for i in (-2, -1, 256, sys.maxunicode, sys.maxunicode+1): + self.assertFalse(curses.ascii.isalnum(i)) + self.assertFalse(curses.ascii.isalpha(i)) + self.assertFalse(curses.ascii.isdigit(i)) + self.assertFalse(curses.ascii.islower(i)) + self.assertFalse(curses.ascii.isspace(i)) + self.assertFalse(curses.ascii.isupper(i)) + + self.assertFalse(curses.ascii.isascii(i)) + self.assertFalse(curses.ascii.isctrl(i)) + self.assertFalse(curses.ascii.iscntrl(i)) + self.assertFalse(curses.ascii.isblank(i)) + self.assertFalse(curses.ascii.isgraph(i)) + self.assertFalse(curses.ascii.isprint(i)) + self.assertFalse(curses.ascii.ispunct(i)) + self.assertFalse(curses.ascii.isxdigit(i)) + + self.assertFalse(curses.ascii.ismeta(-1)) + + def test_ascii(self): + ascii = curses.ascii.ascii + self.assertEqual(ascii('\xc1'), 'A') + self.assertEqual(ascii('A'), 'A') + self.assertEqual(ascii(ord('\xc1')), ord('A')) + + def test_ctrl(self): + ctrl = curses.ascii.ctrl + self.assertEqual(ctrl('J'), '\n') + self.assertEqual(ctrl('\n'), '\n') + self.assertEqual(ctrl('@'), '\0') + self.assertEqual(ctrl(ord('J')), ord('\n')) + + def test_alt(self): + alt = curses.ascii.alt + self.assertEqual(alt('\n'), '\x8a') + self.assertEqual(alt('A'), '\xc1') + self.assertEqual(alt(ord('A')), 0xc1) + + def test_unctrl(self): + unctrl = curses.ascii.unctrl + self.assertEqual(unctrl('a'), 'a') + self.assertEqual(unctrl('A'), 'A') + self.assertEqual(unctrl(';'), ';') + self.assertEqual(unctrl(' '), ' ') + self.assertEqual(unctrl('\x7f'), '^?') + self.assertEqual(unctrl('\n'), '^J') + self.assertEqual(unctrl('\0'), '^@') + self.assertEqual(unctrl(ord('A')), 'A') + self.assertEqual(unctrl(ord('\n')), '^J') + # Meta-bit characters + self.assertEqual(unctrl('\x8a'), '!^J') + self.assertEqual(unctrl('\xc1'), '!A') + self.assertEqual(unctrl(ord('\x8a')), '!^J') + self.assertEqual(unctrl(ord('\xc1')), '!A') + + +def lorem_ipsum(win): + text = [ + 'Lorem ipsum', + 'dolor sit amet,', + 'consectetur', + 'adipiscing elit,', + 'sed do eiusmod', + 'tempor incididunt', + 'ut labore et', + 'dolore magna', + 'aliqua.', + ] + maxy, maxx = win.getmaxyx() + for y, line in enumerate(text[:maxy]): + win.addstr(y, 0, line[:maxx - (y == maxy - 1)]) + + +class TextboxTest(unittest.TestCase): + def setUp(self): + self.mock_win = MagicMock(spec=curses.window) + self.mock_win.getyx.return_value = (1, 1) + self.mock_win.getmaxyx.return_value = (10, 20) + self.mock_win.encoding = 'utf-8' + # A non-blank cell so that _end_of_line() reports a full line: instr() + # backs the text reads, inch() the insert-mode shift. + self.mock_win.instr.return_value = b'x' + self.mock_win.inch.return_value = ord('x') + self.textbox = curses.textpad.Textbox(self.mock_win) + + def test_init(self): + """Test textbox initialization.""" + self.mock_win.reset_mock() + tb = curses.textpad.Textbox(self.mock_win) + self.mock_win.getmaxyx.assert_called_once_with() + self.mock_win.keypad.assert_called_once_with(1) + self.assertEqual(tb.insert_mode, False) + self.assertEqual(tb.stripspaces, 1) + self.assertIsNone(tb.lastcmd) + self.mock_win.reset_mock() + + def test_insert(self): + """Test inserting a printable character.""" + self.mock_win.reset_mock() + self.textbox.do_command(ord('a')) + self.mock_win.addch.assert_called_with(ord('a')) + self.textbox.do_command(ord('b')) + self.mock_win.addch.assert_called_with(ord('b')) + self.textbox.do_command(ord('c')) + self.mock_win.addch.assert_called_with(ord('c')) + self.mock_win.reset_mock() + + def test_delete(self): + """Test deleting a character.""" + self.mock_win.reset_mock() + self.textbox.do_command(curses.ascii.BS) + self.textbox.do_command(curses.KEY_BACKSPACE) + self.textbox.do_command(curses.ascii.DEL) + assert self.mock_win.delch.call_count == 3 + self.mock_win.reset_mock() + + def test_move_left(self): + """Test moving the cursor left.""" + self.mock_win.reset_mock() + self.textbox.do_command(curses.KEY_LEFT) + self.mock_win.move.assert_called_with(1, 0) + self.mock_win.reset_mock() + + def test_move_right(self): + """Test moving the cursor right.""" + self.mock_win.reset_mock() + self.textbox.do_command(curses.KEY_RIGHT) + self.mock_win.move.assert_called_with(1, 2) + self.mock_win.reset_mock() + + def test_move_left_and_right(self): + """Test moving the cursor left and then right.""" + self.mock_win.reset_mock() + self.textbox.do_command(curses.KEY_LEFT) + self.mock_win.move.assert_called_with(1, 0) + self.textbox.do_command(curses.KEY_RIGHT) + self.mock_win.move.assert_called_with(1, 2) + self.mock_win.reset_mock() + + def test_move_up(self): + """Test moving the cursor up.""" + self.mock_win.reset_mock() + self.textbox.do_command(curses.KEY_UP) + self.mock_win.move.assert_called_with(0, 1) + self.mock_win.reset_mock() + + def test_move_down(self): + """Test moving the cursor down.""" + self.mock_win.reset_mock() + self.textbox.do_command(curses.KEY_DOWN) + self.mock_win.move.assert_called_with(2, 1) + self.mock_win.reset_mock() + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py index acbbf60ef37..2309ad296f8 100644 --- a/Lib/test/test_dataclasses/__init__.py +++ b/Lib/test/test_dataclasses/__init__.py @@ -27,11 +27,21 @@ import dataclasses # Needed for the string "dataclasses.InitVar[int]" to work as an annotation. from test import support -from test.support import import_helper +from test.support import cpython_only, import_helper # Just any custom exception we can catch. class CustomError(Exception): pass + +class TestImportTime(unittest.TestCase): + + @cpython_only + def test_lazy_import(self): + import_helper.ensure_lazy_imports( + "dataclasses", {"inspect", "re", "copy"} + ) + + class TestCase(unittest.TestCase): def test_no_fields(self): @dataclass @@ -71,7 +81,7 @@ def test_field_repr(self): expected_output = "Field(name='id',type=None," \ f"default=1,default_factory={MISSING!r}," \ "init=True,repr=False,hash=None," \ - "compare=True,metadata=mappingproxy({})," \ + "compare=True,metadata=frozendict()," \ f"kw_only={MISSING!r}," \ "doc='Docstring'," \ "_field_type=None)" @@ -985,7 +995,7 @@ class D: self.assertNotIn('x', D.__dict__) def test_missing_repr(self): - self.assertIn('MISSING_TYPE object', repr(MISSING)) + self.assertEqual(repr(MISSING), 'MISSING') def test_dont_include_other_annotations(self): @dataclass @@ -1693,17 +1703,24 @@ class GroupTuple: class GroupDict: id: int users: Dict[str, User] + @dataclass + class GroupFrozenDict: + id: int + users: frozendict[str, User] a = User('Alice', 1) b = User('Bob', 2) gl = GroupList(0, [a, b]) gt = GroupTuple(0, (a, b)) gd = GroupDict(0, {'first': a, 'second': b}) + gfd = GroupFrozenDict(0, frozendict({'first': a, 'second': b})) self.assertEqual(asdict(gl), {'id': 0, 'users': [{'name': 'Alice', 'id': 1}, {'name': 'Bob', 'id': 2}]}) self.assertEqual(asdict(gt), {'id': 0, 'users': ({'name': 'Alice', 'id': 1}, {'name': 'Bob', 'id': 2})}) - self.assertEqual(asdict(gd), {'id': 0, 'users': {'first': {'name': 'Alice', 'id': 1}, - 'second': {'name': 'Bob', 'id': 2}}}) + expected_dict = {'id': 0, 'users': {'first': {'name': 'Alice', 'id': 1}, + 'second': {'name': 'Bob', 'id': 2}}} + self.assertEqual(asdict(gd), expected_dict) + self.assertEqual(asdict(gfd), expected_dict) def test_helper_asdict_builtin_object_containers(self): @dataclass @@ -1884,14 +1901,21 @@ class GroupTuple: class GroupDict: id: int users: Dict[str, User] + @dataclass + class GroupFrozenDict: + id: int + users: frozendict[str, User] a = User('Alice', 1) b = User('Bob', 2) gl = GroupList(0, [a, b]) gt = GroupTuple(0, (a, b)) gd = GroupDict(0, {'first': a, 'second': b}) + gfd = GroupFrozenDict(0, frozendict({'first': a, 'second': b})) self.assertEqual(astuple(gl), (0, [('Alice', 1), ('Bob', 2)])) self.assertEqual(astuple(gt), (0, (('Alice', 1), ('Bob', 2)))) - self.assertEqual(astuple(gd), (0, {'first': ('Alice', 1), 'second': ('Bob', 2)})) + d = {'first': ('Alice', 1), 'second': ('Bob', 2)} + self.assertEqual(astuple(gd), (0, d)) + self.assertEqual(astuple(gfd), (0, frozendict(d))) def test_helper_astuple_builtin_object_containers(self): @dataclass @@ -2295,6 +2319,20 @@ class C: self.assertDocStrEqual(C.__doc__, "C()") + def test_docstring_slotted(self): + @dataclass(slots=True) + class C: + x: int + + self.assertDocStrEqual(C.__doc__, "C(x:int)") + + def test_docstring_recursive(self): + @dataclass() + class C: + x: list[C] + + self.assertDocStrEqual(C.__doc__, "C(x:list[test.test_dataclasses.TestDocString.test_docstring_recursive..C])") + def test_docstring_one_field(self): @dataclass class C: @@ -4444,10 +4482,17 @@ def test_classvar_module_level_import(self): from test.test_dataclasses import dataclass_module_1_str from test.test_dataclasses import dataclass_module_2 from test.test_dataclasses import dataclass_module_2_str - - for m in (dataclass_module_1, dataclass_module_1_str, - dataclass_module_2, dataclass_module_2_str, - ): + from test.test_dataclasses import dataclass_module_3 + from test.test_dataclasses import dataclass_module_3_str + from test.test_dataclasses import dataclass_module_4 + from test.test_dataclasses import dataclass_module_4_str + + for m in ( + dataclass_module_1, dataclass_module_1_str, + dataclass_module_2, dataclass_module_2_str, + dataclass_module_3, dataclass_module_3_str, + dataclass_module_4, dataclass_module_4_str, + ): with self.subTest(m=m): # There's a difference in how the ClassVars are # interpreted when using string annotations or @@ -4480,6 +4525,11 @@ def test_classvar_module_level_import(self): # won't exist on the instance. self.assertNotIn('not_iv4', c.__dict__) + def test_lazy_import_annotations(self): + from test.test_dataclasses import dataclass_lazy_str as m + self.assertEqual([f.name for f in fields(m.C)], ['x', 'y']) + self.assertNotIsInstance(vars(m)['t'], types.LazyImportType) + def test_text_annotations(self): from test.test_dataclasses import dataclass_textanno @@ -4751,6 +4801,14 @@ def custom_dataclass(cls, *args, **kwargs): self.assertEqual(c.x, 10) self.assertEqual(c.__custom__, True) + def test_empty_annotation_string(self): + @dataclass + class DataclassWithEmptyTypeAnnotation: + x: "" + + c = DataclassWithEmptyTypeAnnotation(10) + self.assertEqual(c.x, 10) + class TestReplace(unittest.TestCase): def test(self): diff --git a/Lib/test/test_dataclasses/_types_proxy.py b/Lib/test/test_dataclasses/_types_proxy.py new file mode 100644 index 00000000000..f4aaeef7aec --- /dev/null +++ b/Lib/test/test_dataclasses/_types_proxy.py @@ -0,0 +1,8 @@ +# We need this to test a case when a type +# is imported via some other package, +# like ClassVar from typing_extensions instead of typing. +# https://github.com/python/cpython/issues/133956 +from typing import ClassVar +from dataclasses import InitVar + +__all__ = ["ClassVar", "InitVar"] diff --git a/Lib/test/test_dataclasses/dataclass_lazy_broken.py b/Lib/test/test_dataclasses/dataclass_lazy_broken.py new file mode 100644 index 00000000000..d9d29834fe1 --- /dev/null +++ b/Lib/test/test_dataclasses/dataclass_lazy_broken.py @@ -0,0 +1 @@ +raise RuntimeError("module fails to import") diff --git a/Lib/test/test_dataclasses/dataclass_lazy_str.py b/Lib/test/test_dataclasses/dataclass_lazy_str.py new file mode 100644 index 00000000000..cd600fb6f38 --- /dev/null +++ b/Lib/test/test_dataclasses/dataclass_lazy_str.py @@ -0,0 +1,12 @@ +from __future__ import annotations + +import dataclasses +lazy import typing as t +lazy from _dataclass_test_missing_module import Missing +lazy from test.test_dataclasses.dataclass_lazy_broken import Broken + +@dataclasses.dataclass +class C: + x: Missing | None = None + y: Broken | None = None + cv: t.ClassVar[int] = 0 diff --git a/Lib/test/dataclass_module_2.py b/Lib/test/test_dataclasses/dataclass_module_3.py similarity index 51% rename from Lib/test/dataclass_module_2.py rename to Lib/test/test_dataclasses/dataclass_module_3.py index 68fb733e299..74abc091f35 100644 --- a/Lib/test/dataclass_module_2.py +++ b/Lib/test/test_dataclasses/dataclass_module_3.py @@ -1,32 +1,32 @@ #from __future__ import annotations USING_STRINGS = False -# dataclass_module_2.py and dataclass_module_2_str.py are identical +# dataclass_module_3.py and dataclass_module_3_str.py are identical # except only the latter uses string annotations. -from dataclasses import dataclass, InitVar -from typing import ClassVar +from dataclasses import dataclass +import test.test_dataclasses._types_proxy as tp -T_CV2 = ClassVar[int] -T_CV3 = ClassVar +T_CV2 = tp.ClassVar[int] +T_CV3 = tp.ClassVar -T_IV2 = InitVar[int] -T_IV3 = InitVar +T_IV2 = tp.InitVar[int] +T_IV3 = tp.InitVar @dataclass class CV: - T_CV4 = ClassVar - cv0: ClassVar[int] = 20 - cv1: ClassVar = 30 + T_CV4 = tp.ClassVar + cv0: tp.ClassVar[int] = 20 + cv1: tp.ClassVar = 30 cv2: T_CV2 cv3: T_CV3 not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. @dataclass class IV: - T_IV4 = InitVar - iv0: InitVar[int] - iv1: InitVar + T_IV4 = tp.InitVar + iv0: tp.InitVar[int] + iv1: tp.InitVar iv2: T_IV2 iv3: T_IV3 not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar. diff --git a/Lib/test/dataclass_module_2_str.py b/Lib/test/test_dataclasses/dataclass_module_3_str.py similarity index 51% rename from Lib/test/dataclass_module_2_str.py rename to Lib/test/test_dataclasses/dataclass_module_3_str.py index b363d17c176..49e5fca6183 100644 --- a/Lib/test/dataclass_module_2_str.py +++ b/Lib/test/test_dataclasses/dataclass_module_3_str.py @@ -1,32 +1,32 @@ from __future__ import annotations USING_STRINGS = True -# dataclass_module_2.py and dataclass_module_2_str.py are identical +# dataclass_module_3.py and dataclass_module_3_str.py are identical # except only the latter uses string annotations. -from dataclasses import dataclass, InitVar -from typing import ClassVar +from dataclasses import dataclass +import test.test_dataclasses._types_proxy as tp -T_CV2 = ClassVar[int] -T_CV3 = ClassVar +T_CV2 = tp.ClassVar[int] +T_CV3 = tp.ClassVar -T_IV2 = InitVar[int] -T_IV3 = InitVar +T_IV2 = tp.InitVar[int] +T_IV3 = tp.InitVar @dataclass class CV: - T_CV4 = ClassVar - cv0: ClassVar[int] = 20 - cv1: ClassVar = 30 + T_CV4 = tp.ClassVar + cv0: tp.ClassVar[int] = 20 + cv1: tp.ClassVar = 30 cv2: T_CV2 cv3: T_CV3 not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. @dataclass class IV: - T_IV4 = InitVar - iv0: InitVar[int] - iv1: InitVar + T_IV4 = tp.InitVar + iv0: tp.InitVar[int] + iv1: tp.InitVar iv2: T_IV2 iv3: T_IV3 not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar. diff --git a/Lib/test/test_dataclasses/dataclass_module_4.py b/Lib/test/test_dataclasses/dataclass_module_4.py new file mode 100644 index 00000000000..7e0c8a18356 --- /dev/null +++ b/Lib/test/test_dataclasses/dataclass_module_4.py @@ -0,0 +1,38 @@ +#from __future__ import annotations +USING_STRINGS = False + +# dataclass_module_4.py and dataclass_module_4_str.py are identical +# except only the latter uses string annotations. + +from dataclasses import dataclass +import dataclasses +import typing + +class TypingProxy: + class Nested: + ClassVar = typing.ClassVar + InitVar = dataclasses.InitVar + +T_CV2 = TypingProxy.Nested.ClassVar[int] +T_CV3 = TypingProxy.Nested.ClassVar + +T_IV2 = TypingProxy.Nested.InitVar[int] +T_IV3 = TypingProxy.Nested.InitVar + +@dataclass +class CV: + T_CV4 = TypingProxy.Nested.ClassVar + cv0: TypingProxy.Nested.ClassVar[int] = 20 + cv1: TypingProxy.Nested.ClassVar = 30 + cv2: T_CV2 + cv3: T_CV3 + not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. + +@dataclass +class IV: + T_IV4 = TypingProxy.Nested.InitVar + iv0: TypingProxy.Nested.InitVar[int] + iv1: TypingProxy.Nested.InitVar + iv2: T_IV2 + iv3: T_IV3 + not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar. diff --git a/Lib/test/test_dataclasses/dataclass_module_4_str.py b/Lib/test/test_dataclasses/dataclass_module_4_str.py new file mode 100644 index 00000000000..876f3dcf7c8 --- /dev/null +++ b/Lib/test/test_dataclasses/dataclass_module_4_str.py @@ -0,0 +1,38 @@ +from __future__ import annotations +USING_STRINGS = True + +# dataclass_module_4.py and dataclass_module_4_str.py are identical +# except only the latter uses string annotations. + +from dataclasses import dataclass +import dataclasses +import typing + +class TypingProxy: + class Nested: + ClassVar = typing.ClassVar + InitVar = dataclasses.InitVar + +T_CV2 = TypingProxy.Nested.ClassVar[int] +T_CV3 = TypingProxy.Nested.ClassVar + +T_IV2 = TypingProxy.Nested.InitVar[int] +T_IV3 = TypingProxy.Nested.InitVar + +@dataclass +class CV: + T_CV4 = TypingProxy.Nested.ClassVar + cv0: TypingProxy.Nested.ClassVar[int] = 20 + cv1: TypingProxy.Nested.ClassVar = 30 + cv2: T_CV2 + cv3: T_CV3 + not_cv4: T_CV4 # When using string annotations, this field is not recognized as a ClassVar. + +@dataclass +class IV: + T_IV4 = TypingProxy.Nested.InitVar + iv0: TypingProxy.Nested.InitVar[int] + iv1: TypingProxy.Nested.InitVar + iv2: T_IV2 + iv3: T_IV3 + not_iv4: T_IV4 # When using string annotations, this field is not recognized as an InitVar. diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py index e68eca29564..24147a8accd 100644 --- a/Lib/test/test_dbm.py +++ b/Lib/test/test_dbm.py @@ -67,7 +67,7 @@ def keys_helper(self, f): return keys def test_error(self): - self.assertTrue(issubclass(self.module.error, OSError)) + self.assertIsSubclass(self.module.error, OSError) def test_anydbm_not_existing(self): self.assertRaises(dbm.error, dbm.open, _fname) @@ -136,6 +136,67 @@ def test_anydbm_access(self): assert(f[key] == b"Python:") f.close() + def test_anydbm_readonly_reorganize(self): + self.init_db() + with dbm.open(_fname, 'r') as d: + # Early stopping. + if not hasattr(d, 'reorganize'): + self.skipTest("method reorganize not available this dbm submodule") + + self.assertRaises(dbm.error, lambda: d.reorganize()) + + def test_anydbm_reorganize_not_changed_content(self): + self.init_db() + with dbm.open(_fname, 'c') as d: + # Early stopping. + if not hasattr(d, 'reorganize'): + self.skipTest("method reorganize not available this dbm submodule") + + keys_before = sorted(d.keys()) + values_before = [d[k] for k in keys_before] + d.reorganize() + keys_after = sorted(d.keys()) + values_after = [d[k] for k in keys_before] + self.assertEqual(keys_before, keys_after) + self.assertEqual(values_before, values_after) + + def test_anydbm_reorganize_decreased_size(self): + + def _calculate_db_size(db_path): + if os.path.isfile(db_path): + return os.path.getsize(db_path) + total_size = 0 + for root, _, filenames in os.walk(db_path): + for filename in filenames: + file_path = os.path.join(root, filename) + total_size += os.path.getsize(file_path) + return total_size + + # This test requires relatively large databases to reliably show difference in size before and after reorganizing. + with dbm.open(_fname, 'n') as f: + # Early stopping. + if not hasattr(f, 'reorganize'): + self.skipTest("method reorganize not available this dbm submodule") + + for k in self._dict: + f[k.encode('ascii')] = self._dict[k] * 100000 + db_keys = list(f.keys()) + + # Make sure to calculate size of database only after file is closed to ensure file content are flushed to disk. + size_before = _calculate_db_size(os.path.dirname(_fname)) + + # Delete some elements from the start of the database. + keys_to_delete = db_keys[:len(db_keys) // 2] + with dbm.open(_fname, 'c') as f: + for k in keys_to_delete: + del f[k] + f.reorganize() + + # Make sure to calculate size of database only after file is closed to ensure file content are flushed to disk. + size_after = _calculate_db_size(os.path.dirname(_fname)) + + self.assertLess(size_after, size_before) + def test_open_with_bytes(self): dbm.open(os.fsencode(_fname), "c").close() @@ -261,5 +322,6 @@ def setUp(self): cls = unittest.skip("TODO: RUSTPYTHON; sqlite3 file locking on Windows")(cls) globals()[testname] = cls + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_dbm_dumb.py b/Lib/test/test_dbm_dumb.py index 672f9092207..a1791a5ada7 100644 --- a/Lib/test/test_dbm_dumb.py +++ b/Lib/test/test_dbm_dumb.py @@ -31,6 +31,7 @@ class DumbDBMTestCase(unittest.TestCase): b'd': b'way', b'f': b'Guido', b'g': b'intended', + b'h': bytearray(b'bytearray_value'), '\u00fc'.encode('utf-8') : b'!', } @@ -114,6 +115,16 @@ def test_write_write_read(self): with contextlib.closing(dumbdbm.open(_fname)) as f: self.assertEqual(f[b'1'], b'hello2') + def test_reorganize_persists_changed_offsets(self): + with dumbdbm.open(_fname, 'n') as f: + f[b'deleted'] = b'x' + f[b'retained'] = b'value' + del f[b'deleted'] + f.reorganize() + + with dumbdbm.open(_fname, 'r') as f: + self.assertEqual(f[b'retained'], b'value') + def test_str_read(self): self.init_db() with contextlib.closing(dumbdbm.open(_fname, 'r')) as f: @@ -368,6 +379,14 @@ def test_nonascii_filename(self): self.assertTrue(b'key' in db) self.assertEqual(db[b'key'], b'value') + def test_bytearray(self): + self.init_db() + with contextlib.closing(dumbdbm.open(_fname, 'r')) as f: + self.assertEqual(f[b'h'], b'bytearray_value') + with contextlib.closing(dumbdbm.open(_fname)) as f: + with self.assertRaises(TypeError): + f[bytearray(b'bytearray_key')] = b'value' + def test_open_with_pathlib_path(self): dumbdbm.open(os_helper.FakePath(_fname), "c").close() diff --git a/Lib/test/test_dbm_gnu.py b/Lib/test/test_dbm_gnu.py new file mode 100644 index 00000000000..66268c42a30 --- /dev/null +++ b/Lib/test/test_dbm_gnu.py @@ -0,0 +1,222 @@ +import os +import unittest +from test import support +from test.support import cpython_only, import_helper +from test.support.os_helper import (TESTFN, TESTFN_NONASCII, FakePath, + create_empty_file, temp_dir, unlink) + +gdbm = import_helper.import_module("dbm.gnu") # skip if not supported + +filename = TESTFN + +class TestGdbm(unittest.TestCase): + @staticmethod + def setUpClass(): + if support.verbose: + try: + from _gdbm import _GDBM_VERSION as version + except ImportError: + pass + else: + print(f"gdbm version: {version}") + + def setUp(self): + self.g = None + + def tearDown(self): + if self.g is not None: + self.g.close() + unlink(filename) + + @cpython_only + def test_disallow_instantiation(self): + # Ensure that the type disallows instantiation (bpo-43916) + self.g = gdbm.open(filename, 'c') + support.check_disallow_instantiation(self, type(self.g)) + + def test_key_methods(self): + self.g = gdbm.open(filename, 'c') + self.assertEqual(self.g.keys(), []) + self.g['a'] = 'b' + self.g['12345678910'] = '019237410982340912840198242' + self.g[b'bytes'] = b'data' + key_set = set(self.g.keys()) + self.assertEqual(key_set, set([b'a', b'bytes', b'12345678910'])) + self.assertIn('a', self.g) + self.assertIn(b'a', self.g) + self.assertEqual(self.g[b'bytes'], b'data') + key = self.g.firstkey() + while key: + self.assertIn(key, key_set) + key_set.remove(key) + key = self.g.nextkey(key) + # get() and setdefault() work as in the dict interface + self.assertEqual(self.g.get(b'a'), b'b') + self.assertIsNone(self.g.get(b'xxx')) + self.assertEqual(self.g.get(b'xxx', b'foo'), b'foo') + with self.assertRaises(KeyError): + self.g['xxx'] + self.assertEqual(self.g.setdefault(b'xxx', b'foo'), b'foo') + self.assertEqual(self.g[b'xxx'], b'foo') + + def test_error_conditions(self): + # Try to open a non-existent database. + unlink(filename) + self.assertRaises(gdbm.error, gdbm.open, filename, 'r') + # Try to access a closed database. + self.g = gdbm.open(filename, 'c') + self.g.close() + self.assertRaises(gdbm.error, lambda: self.g['a']) + # try pass an invalid open flag + self.assertRaises(gdbm.error, lambda: gdbm.open(filename, 'rx').close()) + + def test_flags(self): + # Test the flag parameter open() by trying all supported flag modes. + all = set(gdbm.open_flags) + # Test standard flags (presumably "crwn"). + modes = all - set('fsu') + for mode in sorted(modes): # put "c" mode first + self.g = gdbm.open(filename, mode) + self.g.close() + + # Test additional flags (presumably "fsu"). + flags = all - set('crwn') + for mode in modes: + for flag in flags: + self.g = gdbm.open(filename, mode + flag) + self.g.close() + + def test_reorganize(self): + self.g = gdbm.open(filename, 'c') + size0 = os.path.getsize(filename) + + # bpo-33901: on macOS with gdbm 1.15, an empty database uses 16 MiB + # and adding an entry of 10,000 B has no effect on the file size. + # Add size0 bytes to make sure that the file size changes. + value_size = max(size0, 10000) + self.g['x'] = 'x' * value_size + size1 = os.path.getsize(filename) + self.assertGreater(size1, size0) + + del self.g['x'] + # 'size' is supposed to be the same even after deleting an entry. + self.assertEqual(os.path.getsize(filename), size1) + + self.g.reorganize() + size2 = os.path.getsize(filename) + self.assertLess(size2, size1) + self.assertGreaterEqual(size2, size0) + + def test_context_manager(self): + with gdbm.open(filename, 'c') as db: + db["gdbm context manager"] = "context manager" + + with gdbm.open(filename, 'r') as db: + self.assertEqual(list(db.keys()), [b"gdbm context manager"]) + + with self.assertRaises(gdbm.error) as cm: + db.keys() + self.assertEqual(str(cm.exception), + "GDBM object has already been closed") + + def test_bool_empty(self): + with gdbm.open(filename, 'c') as db: + self.assertFalse(bool(db)) + + def test_bool_not_empty(self): + with gdbm.open(filename, 'c') as db: + db['a'] = 'b' + self.assertTrue(bool(db)) + + def test_bool_on_closed_db_raises(self): + with gdbm.open(filename, 'c') as db: + db['a'] = 'b' + self.assertRaises(gdbm.error, bool, db) + + def test_bytes(self): + with gdbm.open(filename, 'c') as db: + db[b'bytes key \xbd'] = b'bytes value \xbd' + with gdbm.open(filename, 'r') as db: + self.assertEqual(list(db.keys()), [b'bytes key \xbd']) + self.assertTrue(b'bytes key \xbd' in db) + self.assertEqual(db[b'bytes key \xbd'], b'bytes value \xbd') + + def test_unicode(self): + with gdbm.open(filename, 'c') as db: + db['Unicode key \U0001f40d'] = 'Unicode value \U0001f40d' + with gdbm.open(filename, 'r') as db: + self.assertEqual(list(db.keys()), ['Unicode key \U0001f40d'.encode()]) + self.assertTrue('Unicode key \U0001f40d'.encode() in db) + self.assertTrue('Unicode key \U0001f40d' in db) + self.assertEqual(db['Unicode key \U0001f40d'.encode()], + 'Unicode value \U0001f40d'.encode()) + self.assertEqual(db['Unicode key \U0001f40d'], + 'Unicode value \U0001f40d'.encode()) + + def test_write_readonly_file(self): + with gdbm.open(filename, 'c') as db: + db[b'bytes key'] = b'bytes value' + with gdbm.open(filename, 'r') as db: + with self.assertRaises(gdbm.error): + del db[b'not exist key'] + with self.assertRaises(gdbm.error): + del db[b'bytes key'] + with self.assertRaises(gdbm.error): + db[b'not exist key'] = b'not exist value' + + @unittest.skipUnless(TESTFN_NONASCII, + 'requires OS support of non-ASCII encodings') + def test_nonascii_filename(self): + filename = TESTFN_NONASCII + self.addCleanup(unlink, filename) + with gdbm.open(filename, 'c') as db: + db[b'key'] = b'value' + self.assertTrue(os.path.exists(filename)) + with gdbm.open(filename, 'r') as db: + self.assertEqual(list(db.keys()), [b'key']) + self.assertTrue(b'key' in db) + self.assertEqual(db[b'key'], b'value') + + def test_nonexisting_file(self): + nonexisting_file = 'nonexisting-file' + with self.assertRaises(gdbm.error) as cm: + gdbm.open(nonexisting_file) + self.assertIn(nonexisting_file, str(cm.exception)) + self.assertEqual(cm.exception.filename, nonexisting_file) + + def test_open_with_pathlib_path(self): + gdbm.open(FakePath(filename), "c").close() + + def test_open_with_bytes_path(self): + gdbm.open(os.fsencode(filename), "c").close() + + def test_open_with_pathlib_bytes_path(self): + gdbm.open(FakePath(os.fsencode(filename)), "c").close() + + def test_clear(self): + kvs = [('foo', 'bar'), ('1234', '5678')] + with gdbm.open(filename, 'c') as db: + for k, v in kvs: + db[k] = v + self.assertIn(k, db) + self.assertEqual(len(db), len(kvs)) + + db.clear() + for k, v in kvs: + self.assertNotIn(k, db) + self.assertEqual(len(db), 0) + + @support.run_with_locale( + 'LC_ALL', + 'fr_FR.iso88591', 'ja_JP.sjis', 'zh_CN.gbk', + 'fr_FR.utf8', 'en_US.utf8', + '', + ) + def test_localized_error(self): + with temp_dir() as d: + create_empty_file(os.path.join(d, 'test')) + self.assertRaises(gdbm.error, gdbm.open, filename, 'r') + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_dbm_ndbm.py b/Lib/test/test_dbm_ndbm.py new file mode 100644 index 00000000000..e0f31c9a9a3 --- /dev/null +++ b/Lib/test/test_dbm_ndbm.py @@ -0,0 +1,165 @@ +from test.support import import_helper +from test.support import os_helper +import_helper.import_module("dbm.ndbm") #skip if not supported +import os +import unittest +import dbm.ndbm +from dbm.ndbm import error + +class DbmTestCase(unittest.TestCase): + + def setUp(self): + self.filename = os_helper.TESTFN + self.d = dbm.ndbm.open(self.filename, 'c') + self.d.close() + + def tearDown(self): + for suffix in ['', '.pag', '.dir', '.db']: + os_helper.unlink(self.filename + suffix) + + def test_keys(self): + self.d = dbm.ndbm.open(self.filename, 'c') + self.assertEqual(self.d.keys(), []) + self.d['a'] = 'b' + self.d[b'bytes'] = b'data' + self.d['12345678910'] = '019237410982340912840198242' + self.d.keys() + self.assertIn('a', self.d) + self.assertIn(b'a', self.d) + self.assertEqual(self.d[b'bytes'], b'data') + # get() and setdefault() work as in the dict interface + self.assertEqual(self.d.get(b'a'), b'b') + self.assertIsNone(self.d.get(b'xxx')) + self.assertEqual(self.d.get(b'xxx', b'foo'), b'foo') + with self.assertRaises(KeyError): + self.d['xxx'] + self.assertEqual(self.d.setdefault(b'xxx', b'foo'), b'foo') + self.assertEqual(self.d[b'xxx'], b'foo') + self.d.close() + + def test_empty_value(self): + if dbm.ndbm.library == 'Berkeley DB': + self.skipTest("Berkeley DB doesn't distinguish the empty value " + "from the absent one") + self.d = dbm.ndbm.open(self.filename, 'c') + self.assertEqual(self.d.keys(), []) + self.d['empty'] = '' + self.assertEqual(self.d.keys(), [b'empty']) + self.assertIn(b'empty', self.d) + self.assertEqual(self.d[b'empty'], b'') + self.assertEqual(self.d.get(b'empty'), b'') + self.assertEqual(self.d.setdefault(b'empty'), b'') + self.d.close() + + def test_modes(self): + for mode in ['r', 'rw', 'w', 'n']: + try: + self.d = dbm.ndbm.open(self.filename, mode) + self.d.close() + except error: + self.fail() + + def test_context_manager(self): + with dbm.ndbm.open(self.filename, 'c') as db: + db["ndbm context manager"] = "context manager" + + with dbm.ndbm.open(self.filename, 'r') as db: + self.assertEqual(list(db.keys()), [b"ndbm context manager"]) + + with self.assertRaises(dbm.ndbm.error) as cm: + db.keys() + self.assertEqual(str(cm.exception), + "DBM object has already been closed") + + def test_bytes(self): + with dbm.ndbm.open(self.filename, 'c') as db: + db[b'bytes key \xbd'] = b'bytes value \xbd' + with dbm.ndbm.open(self.filename, 'r') as db: + self.assertEqual(list(db.keys()), [b'bytes key \xbd']) + self.assertTrue(b'bytes key \xbd' in db) + self.assertEqual(db[b'bytes key \xbd'], b'bytes value \xbd') + + def test_unicode(self): + with dbm.ndbm.open(self.filename, 'c') as db: + db['Unicode key \U0001f40d'] = 'Unicode value \U0001f40d' + with dbm.ndbm.open(self.filename, 'r') as db: + self.assertEqual(list(db.keys()), ['Unicode key \U0001f40d'.encode()]) + self.assertTrue('Unicode key \U0001f40d'.encode() in db) + self.assertTrue('Unicode key \U0001f40d' in db) + self.assertEqual(db['Unicode key \U0001f40d'.encode()], + 'Unicode value \U0001f40d'.encode()) + self.assertEqual(db['Unicode key \U0001f40d'], + 'Unicode value \U0001f40d'.encode()) + + def test_write_readonly_file(self): + with dbm.ndbm.open(self.filename, 'c') as db: + db[b'bytes key'] = b'bytes value' + with dbm.ndbm.open(self.filename, 'r') as db: + with self.assertRaises(error): + del db[b'not exist key'] + with self.assertRaises(error): + del db[b'bytes key'] + with self.assertRaises(error): + db[b'not exist key'] = b'not exist value' + + @unittest.skipUnless(os_helper.TESTFN_NONASCII, + 'requires OS support of non-ASCII encodings') + def test_nonascii_filename(self): + filename = os_helper.TESTFN_NONASCII + for suffix in ['', '.pag', '.dir', '.db']: + self.addCleanup(os_helper.unlink, filename + suffix) + with dbm.ndbm.open(filename, 'c') as db: + db[b'key'] = b'value' + self.assertTrue(any(os.path.exists(filename + suffix) + for suffix in ['', '.pag', '.dir', '.db'])) + with dbm.ndbm.open(filename, 'r') as db: + self.assertEqual(list(db.keys()), [b'key']) + self.assertTrue(b'key' in db) + self.assertEqual(db[b'key'], b'value') + + def test_nonexisting_file(self): + nonexisting_file = 'nonexisting-file' + with self.assertRaises(dbm.ndbm.error) as cm: + dbm.ndbm.open(nonexisting_file) + self.assertIn(nonexisting_file, str(cm.exception)) + self.assertEqual(cm.exception.filename, nonexisting_file) + + def test_open_with_pathlib_path(self): + dbm.ndbm.open(os_helper.FakePath(self.filename), "c").close() + + def test_open_with_bytes_path(self): + dbm.ndbm.open(os.fsencode(self.filename), "c").close() + + def test_open_with_pathlib_bytes_path(self): + dbm.ndbm.open(os_helper.FakePath(os.fsencode(self.filename)), "c").close() + + def test_bool_empty(self): + with dbm.ndbm.open(self.filename, 'c') as db: + self.assertFalse(bool(db)) + + def test_bool_not_empty(self): + with dbm.ndbm.open(self.filename, 'c') as db: + db['a'] = 'b' + self.assertTrue(bool(db)) + + def test_bool_on_closed_db_raises(self): + with dbm.ndbm.open(self.filename, 'c') as db: + db['a'] = 'b' + self.assertRaises(dbm.ndbm.error, bool, db) + + def test_clear(self): + kvs = [('foo', 'bar'), ('1234', '5678')] + with dbm.ndbm.open(self.filename, 'c') as db: + for k, v in kvs: + db[k] = v + self.assertIn(k, db) + self.assertEqual(len(db), len(kvs)) + + db.clear() + for k, v in kvs: + self.assertNotIn(k, db) + self.assertEqual(len(db), 0) + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_dbm_sqlite3.py b/Lib/test/test_dbm_sqlite3.py index f367a98865d..0e87bb1c6e8 100644 --- a/Lib/test/test_dbm_sqlite3.py +++ b/Lib/test/test_dbm_sqlite3.py @@ -267,6 +267,10 @@ class DataTypes(_SQLiteDbmTests): (3.14, b"3.14"), ("string", b"string"), (b"bytes", b"bytes"), + (True, b"1"), + (False, b"0"), + (bytearray(b"bytearray"), b"bytearray"), + (memoryview(b"memoryview"), b"memoryview"), ) def setUp(self): diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index c621b7ac08c..ad5d87e1418 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -24,11 +24,11 @@ with the corresponding argument. """ +import contextlib import logging import math import os, sys import operator -import warnings import pickle, copy import unittest import numbers @@ -2612,6 +2612,37 @@ def tearDown(self): sys.set_int_max_str_digits(self._previous_int_limit) super().tearDown() + def test_helper__is_less_than_pow10a_use_str_slow_path(self): + # Test the "slow" path of _is_less_than_pow10a_use_str(). + a, b = 2, 7 + + # Choose q1, q2 such that len(str(q1)) <= a < len(str(q2)) + # and q1.bit_length() == q2.bit_length() == b to check that + # we cover the "slow" path correctly even for small values. + q1, q2 = 95, 105 + b1, b2 = q1.bit_length(), q2.bit_length() + + self.assertEqual(b1, b) + self.assertEqual(b2, b) + + # ensure that the first "fast" check doesn't hold + self.assertGreaterEqual(b, a * self.decimal._LOG_10_BASE_2_LO) + # ensure that the second "fast" check doesn't hold + self.assertLess(b, 1 + a * self.decimal._LOG_10_BASE_2_HI) + + cond_q1, str_q1 = self.decimal._is_less_than_pow10a_use_str(q1, a) + self.assertTrue(cond_q1) + self.assertIsNotNone(str_q1) + + cond_q2, str_q2 = self.decimal._is_less_than_pow10a_use_str(q2, a) + self.assertFalse(cond_q2) + self.assertIsNotNone(str_q2) + + def test_helper__is_less_than_pow10a(self): + # TODO(picnixz): find a simple test case with custom ulp_order. + pass + + class PythonAPItests: def test_abc(self): @@ -3964,15 +3995,21 @@ def test_flag_comparisons(self): d.update(c.flags) self.assertEqual(d, c.flags) self.assertEqual(c.flags, d) + self.assertEqual(frozendict(d), c.flags) + self.assertEqual(c.flags, frozendict(d)) d[Inexact] = True self.assertNotEqual(d, c.flags) self.assertNotEqual(c.flags, d) + self.assertNotEqual(frozendict(d), c.flags) + self.assertNotEqual(c.flags, frozendict(d)) # Invalid SignalDict d = {Inexact:False} self.assertNotEqual(d, c.flags) self.assertNotEqual(c.flags, d) + self.assertNotEqual(frozendict(d), c.flags) + self.assertNotEqual(c.flags, frozendict(d)) d = ["xyz"] self.assertNotEqual(d, c.flags) @@ -4142,6 +4179,15 @@ def test_float_operation_default(self): @requires_cdecimal class CContextFlags(ContextFlags, unittest.TestCase): decimal = C + + def test_signaldict_repr(self): + Context = self.decimal.Context + ctx = Context(prec=7) + mapping = ctx.flags + del ctx + with self.assertRaisesRegex(ValueError, 'invalid signal dict'): + repr(mapping) + class PyContextFlags(ContextFlags, unittest.TestCase): decimal = P @@ -4274,7 +4320,7 @@ def test_invalid_context(self): # Attributes cannot be deleted for attr in ['prec', 'Emax', 'Emin', 'rounding', 'capitals', 'clamp', - 'flags', 'traps']: + 'flags', 'traps', '_allcr', '_flags', '_traps']: self.assertRaises(AttributeError, c.__delattr__, attr) # Invalid attributes @@ -4475,7 +4521,7 @@ def test_module_attributes(self): self.assertTrue(C.HAVE_THREADS is True or C.HAVE_THREADS is False) self.assertTrue(P.HAVE_THREADS is True or P.HAVE_THREADS is False) - self.assertEqual(C.__version__, P.__version__) + self.assertEqual(C.SPEC_VERSION, P.SPEC_VERSION) self.assertLessEqual(set(dir(C)), set(dir(P))) self.assertEqual([n for n in dir(C) if n[:2] != '__'], sorted(P.__all__)) @@ -4494,6 +4540,15 @@ def test_decimal_attributes(self): class Coverage: + @contextlib.contextmanager + def unbound_context(self, prec=None, Emax=None, Emin=None): + with self.decimal.localcontext() as c: + c.prec = self.decimal.MAX_PREC if prec is None else prec + c.Emax = self.decimal.MAX_EMAX if Emax is None else Emax + c.Emin = self.decimal.MIN_EMIN if Emin is None else Emin + c.traps[self.decimal.Inexact] = 1 + yield c + def test_adjusted(self): Decimal = self.decimal.Decimal @@ -4661,6 +4716,22 @@ def test_divmod(self): self.assertTrue(c.flags[InvalidOperation] and c.flags[DivisionByZero]) + def test_divide_unbound_context(self): + with self.unbound_context() as c: + x = self.decimal.Decimal('1') + y = x // 1 # should be fast + + def test_remainder_near(self): + L = 1000 + limit = sys.get_int_max_str_digits() + sys.set_int_max_str_digits(L) + self.addCleanup(sys.set_int_max_str_digits, limit) + + with self.unbound_context(prec=2 * L) as c: + self.assertEqual(c.prec, 2 * L) + x = self.decimal.Decimal(f'1e{L}') + y = x.remainder_near(1) # must not raise a ValueError + def test_power(self): Decimal = self.decimal.Decimal localcontext = self.decimal.localcontext @@ -4962,6 +5033,14 @@ def test_c_context(self): self.assertEqual(c._flags, C.DecClamped) self.assertEqual(c._traps, C.DecRounded) + @requires_extra_functionality + def test_c_context_apply(self): + c = C.Context(prec=3) + self.assertEqual(c.apply(C.Decimal('1.23456')), C.Decimal('1.23')) + # A higher precision won't see them as equal. + c = C.Context(prec=5) + self.assertNotEqual(c.apply(C.Decimal('1.23456')), C.Decimal('1.23')) + @requires_extra_functionality def test_constants(self): # Condition flags @@ -5930,6 +6009,23 @@ def doit(ty): doit('Context') +class TestModule: + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(self.decimal, "__version__") + self.assertEqual(cm.filename, __file__) + + +@requires_cdecimal +class CTestModule(TestModule, unittest.TestCase): + decimal = C +class PyTestModule(TestModule, unittest.TestCase): + decimal = P + + def load_tests(loader, tests, pattern): if TODO_TESTS is not None: # Run only Arithmetic tests diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py index a193eb10f16..84a17eca0aa 100644 --- a/Lib/test/test_defaultdict.py +++ b/Lib/test/test_defaultdict.py @@ -37,6 +37,9 @@ def test_basic(self): self.assertIn(42, d2.keys()) self.assertNotIn(12, d2) self.assertNotIn(12, d2.keys()) + d2.default_factory = list + del d2.default_factory + self.assertEqual(d2.default_factory, None) d2.default_factory = None self.assertEqual(d2.default_factory, None) try: @@ -186,6 +189,18 @@ def test_union(self): with self.assertRaises(TypeError): i |= None + # frozendict + i_fd = i | frozendict(s) + self.assertIs(type(i_fd), defaultdict) + self.assertIs(i_fd.default_factory, int) + self.assertDictEqual(i_fd, {1: "one", 2: 2, 0: "zero"}) + self.assertEqual(list(i_fd), [1, 2, 0]) + + fd_i = frozendict(s) | i + self.assertIs(type(fd_i), frozendict) + self.assertEqual(fd_i, {1: "one", 2: 2, 0: "zero"}) + self.assertEqual(list(fd_i), [0, 1, 2]) + def test_factory_conflict_with_set_value(self): key = "conflict_test" count = 0 diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py index 3dab5efa99e..0102f203340 100644 --- a/Lib/test/test_deque.py +++ b/Lib/test/test_deque.py @@ -810,6 +810,12 @@ def __iter__(self): class TestSubclass(unittest.TestCase): + def test_copy_maxlen(self): + original = Deque('abc', maxlen=support.MAX_Py_ssize_t) + copied = original.copy() + self.assertEqual(copied, original) + self.assertEqual(copied.maxlen, original.maxlen) + def test_basics(self): d = Deque(range(25)) d.__init__(range(200)) @@ -856,7 +862,6 @@ def test_copy_pickle(self): self.assertEqual(e.z, d.z) self.assertNotHasAttr(e, 'y') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'Deque' object has no attribute 'x' def test_pickle_recursive(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): for d in Deque('abc'), Deque('abc', 3): diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py index a27eb7399dc..eb0662b8bff 100644 --- a/Lib/test/test_descr.py +++ b/Lib/test/test_descr.py @@ -1329,6 +1329,18 @@ class X(object): with self.assertRaisesRegex(AttributeError, "'X' object has no attribute 'a'"): X().a + def test_slots_after_items(self): + class C(tuple): + __slots__ = ['a'] + x = C((1, 2, 3)) + self.assertNotHasAttr(x, "__dict__") + self.assertNotHasAttr(x, "a") + x.a = 42 + self.assertEqual(x.a, 42) + del x.a + self.assertNotHasAttr(x, "a") + self.assertEqual(x, (1, 2, 3)) + def test_slots_special(self): # Testing __dict__ and __weakref__ in __slots__... class D(object): @@ -1338,18 +1350,17 @@ class D(object): self.assertNotHasAttr(a, "__weakref__") a.foo = 42 self.assertEqual(a.__dict__, {"foo": 42}) + with self.assertRaises(TypeError): + weakref.ref(a) class W(object): __slots__ = ["__weakref__"] a = W() self.assertHasAttr(a, "__weakref__") self.assertNotHasAttr(a, "__dict__") - try: + with self.assertRaises(AttributeError): a.foo = 42 - except AttributeError: - pass - else: - self.fail("shouldn't be allowed to set a.foo") + self.assertIs(weakref.ref(a)(), a) class C1(W, D): __slots__ = [] @@ -1358,6 +1369,7 @@ class C1(W, D): self.assertHasAttr(a, "__weakref__") a.foo = 42 self.assertEqual(a.__dict__, {"foo": 42}) + self.assertIs(weakref.ref(a)(), a) class C2(D, W): __slots__ = [] @@ -1366,6 +1378,80 @@ class C2(D, W): self.assertHasAttr(a, "__weakref__") a.foo = 42 self.assertEqual(a.__dict__, {"foo": 42}) + self.assertIs(weakref.ref(a)(), a) + + @unittest.skipIf(_testcapi is None, 'need the _testcapi module') + def test_slots_special_before_items(self): + class D(_testcapi.HeapCCollection): + __slots__ = ["__dict__"] + a = D(1, 2, 3) + self.assertHasAttr(a, "__dict__") + self.assertNotHasAttr(a, "__weakref__") + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + with self.assertRaises(TypeError): + weakref.ref(a) + del a.__dict__ + self.assertNotHasAttr(a, "foo") + self.assertEqual(a.__dict__, {}) + self.assertEqual(list(a), [1, 2, 3]) + + class W(_testcapi.HeapCCollection): + __slots__ = ["__weakref__"] + a = W(1, 2, 3) + self.assertHasAttr(a, "__weakref__") + self.assertNotHasAttr(a, "__dict__") + with self.assertRaises(AttributeError): + a.foo = 42 + self.assertIs(weakref.ref(a)(), a) + + with self.assertRaises(TypeError): + class X(_testcapi.HeapCCollection): + __slots__ = ['x'] + + with self.assertRaises(TypeError): + class X(_testcapi.HeapCCollection): + __slots__ = ['__dict__', 'x'] + + @support.subTests(('base', 'arg'), [ + (tuple, (1, 2, 3)), + (int, 9876543210**2), + (bytes, b'ab'), + ]) + def test_slots_special_after_items(self, base, arg): + class D(base): + __slots__ = ["__dict__"] + a = D(arg) + self.assertHasAttr(a, "__dict__") + self.assertNotHasAttr(a, "__weakref__") + a.foo = 42 + self.assertEqual(a.__dict__, {"foo": 42}) + with self.assertRaises(TypeError): + weakref.ref(a) + del a.__dict__ + self.assertNotHasAttr(a, "foo") + self.assertEqual(a.__dict__, {}) + self.assertEqual(a, base(arg)) + + class W(base): + __slots__ = ["__weakref__"] + a = W(arg) + self.assertHasAttr(a, "__weakref__") + self.assertNotHasAttr(a, "__dict__") + with self.assertRaises(AttributeError): + a.foo = 42 + self.assertIs(weakref.ref(a)(), a) + self.assertEqual(a, base(arg)) + + @support.subTests('base', [int, bytes] + + ([_testcapi.HeapCCollection] if _testcapi else [])) + def test_unsupported_slots(self, base): + with self.assertRaises(TypeError): + class X(base): + __slots__ = ['x'] + with self.assertRaises(TypeError): + class X(base): + __slots__ = ['__dict__', 'x'] def test_slots_special2(self): # Testing __qualname__ and __classcell__ in __slots__ @@ -1650,6 +1736,18 @@ def annotated(cls) -> int: pass del method.__annotate__ self.assertIs(method.__annotate__, original_annotate) + def test_classmethod_without_dict_access(self): + class Spam: + @classmethod + def method(cls, x, y): + pass + + obj = Spam.__dict__['method'] + self.assertIsInstance(obj, classmethod) + self.assertEqual(obj.__annotations__, {}) + self.assertEqual(obj.__name__, 'method') + self.assertEqual(obj.__module__, __name__) + def test_staticmethod_annotations_without_dict_access(self): # gh-125017: this used to crash class Spam: @@ -1660,15 +1758,8 @@ def __new__(cls, x, y): obj = Spam.__dict__['__new__'] self.assertIsInstance(obj, staticmethod) self.assertEqual(obj.__annotations__, {}) - - @support.refcount_test - def test_refleaks_in_classmethod___init__(self): - gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') - cm = classmethod(None) - refs_before = gettotalrefcount() - for i in range(100): - cm.__init__(None) - self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) + self.assertEqual(obj.__name__, '__new__') + self.assertEqual(obj.__module__, __name__) @support.impl_detail("the module 'xxsubtype' is internal") @unittest.skipIf(xxsubtype is None, "requires xxsubtype module") @@ -1767,15 +1858,6 @@ class D(C): del sm.x self.assertNotHasAttr(sm, "x") - @support.refcount_test - def test_refleaks_in_staticmethod___init__(self): - gettotalrefcount = support.get_attribute(sys, 'gettotalrefcount') - sm = staticmethod(None) - refs_before = gettotalrefcount() - for i in range(100): - sm.__init__(None) - self.assertAlmostEqual(gettotalrefcount() - refs_before, 0, delta=10) - @support.impl_detail("the module 'xxsubtype' is internal") @unittest.skipIf(xxsubtype is None, "requires xxsubtype module") def test_staticmethods_in_c(self): @@ -2151,10 +2233,22 @@ def some_number(self_, key): def swallow(*args): pass def format_impl(self, spec): return "hello" - - # It would be nice to have every special method tested here, but I'm - # only listing the ones I can remember outside of typeobject.c, since it - # does it right. + def do_eq(obj): + return obj == 1 + def do_ne(obj): + return obj != 1 + def do_lt(obj): + return obj < 1 + def do_le(obj): + return obj <= 1 + def do_gt(obj): + return obj > 1 + def do_ge(obj): + return obj >= 1 + + # It would be nice to have every special method tested here. + # gh-131151: the rich comparison operators used to clear any exception + # raised by a descriptor's __get__. specials = [ ("__bytes__", bytes, hello, set(), {}), ("__reversed__", reversed, empty_seq, set(), {}), @@ -2175,6 +2269,12 @@ def format_impl(self, spec): ("__ceil__", math.ceil, zero, set(), {}), ("__dir__", dir, empty_seq, set(), {}), ("__round__", round, zero, set(), {}), + ("__eq__", do_eq, return_true, set(), {}), + ("__ne__", do_ne, return_true, set(), {}), + ("__lt__", do_lt, return_true, set(), {}), + ("__le__", do_le, return_true, set(), {}), + ("__gt__", do_gt, return_true, set(), {}), + ("__ge__", do_ge, return_true, set(), {}), ] class Checker(object): @@ -4111,42 +4211,195 @@ class E(D): self.assertEqual(e.a, 2) self.assertEqual(C2.__subclasses__(), [D]) - try: + with self.assertRaisesRegex(TypeError, + "cannot delete '__bases__' attribute of type 'D'"): del D.__bases__ - except (TypeError, AttributeError): - pass - else: - self.fail("shouldn't be able to delete .__bases__") - - try: + with self.assertRaisesRegex(TypeError, 'can only assign non-empty tuple'): D.__bases__ = () - except TypeError as msg: - if str(msg) == "a new-style class can't have only classic bases": - self.fail("wrong error message for .__bases__ = ()") - else: - self.fail("shouldn't be able to set .__bases__ to ()") - - try: + with self.assertRaisesRegex(TypeError, 'can only assign tuple'): + D.__bases__ = [C] + with self.assertRaisesRegex(TypeError, 'duplicate base class'): + D.__bases__ = (C, C) + with self.assertRaisesRegex(TypeError, 'inheritance cycle'): D.__bases__ = (D,) - except TypeError: - pass - else: - # actually, we'll have crashed by here... - self.fail("shouldn't be able to create inheritance cycles") + with self.assertRaisesRegex(TypeError, 'inheritance cycle'): + D.__bases__ = (E,) - try: - D.__bases__ = (C, C) - except TypeError: - pass - else: - self.fail("didn't detect repeated base classes") + class A: + __slots__ = () + def __repr__(self): + return '' + class A_with_dict: + __slots__ = ('__dict__',) + def __repr__(self): + return '' + class A_with_dict_weakref: + def __repr__(self): + return '' + class A_with_slots: + __slots__ = ('x',) + def __repr__(self): + return '' + class A_with_slots_dict: + __slots__ = ('x', '__dict__') + def __repr__(self): + return '' - try: - D.__bases__ = (E,) - except TypeError: + class B: + __slots__ = () + b = B() + r = repr(b) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B.__bases__ = (int,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B.__bases__ = (A_with_dict_weakref,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B.__bases__ = (A_with_dict,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B.__bases__ = (A_with_slots,) + B.__bases__ = (A,) + self.assertNotHasAttr(b, '__dict__') + self.assertNotHasAttr(b, '__weakref__') + self.assertEqual(repr(b), '') + B.__bases__ = (object,) + self.assertEqual(repr(b), r) + + class B_with_dict_weakref: + pass + b = B_with_dict_weakref() + with self.assertRaisesRegex(TypeError, 'layout differs'): + B.__bases__ = (A_with_slots,) + B_with_dict_weakref.__bases__ = (A_with_dict_weakref,) + self.assertEqual(repr(b), '') + B_with_dict_weakref.__bases__ = (A_with_dict,) + self.assertEqual(repr(b), '') + B_with_dict_weakref.__bases__ = (A,) + self.assertEqual(repr(b), '') + B_with_dict_weakref.__bases__ = (object,) + + class B_with_slots: + __slots__ = ('x',) + b = B_with_slots() + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_with_slots.__bases__ = (A_with_dict_weakref,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_with_slots.__bases__ = (A_with_dict,) + B_with_slots.__bases__ = (A,) + self.assertEqual(repr(b), '') + + class B_with_slots_dict: + __slots__ = ('x', '__dict__') + b = B_with_slots_dict() + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_with_slots_dict.__bases__ = (A_with_dict_weakref,) + B_with_slots_dict.__bases__ = (A_with_dict,) + self.assertEqual(repr(b), '') + B_with_slots_dict.__bases__ = (A,) + self.assertEqual(repr(b), '') + + class B_with_slots_dict_weakref: + __slots__ = ('x', '__dict__', '__weakref__') + b = B_with_slots_dict_weakref() + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_with_slots_dict_weakref.__bases__ = (A_with_slots_dict,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_with_slots_dict_weakref.__bases__ = (A_with_slots,) + B_with_slots_dict_weakref.__bases__ = (A_with_dict_weakref,) + self.assertEqual(repr(b), '') + B_with_slots_dict_weakref.__bases__ = (A_with_dict,) + self.assertEqual(repr(b), '') + B_with_slots_dict_weakref.__bases__ = (A,) + self.assertEqual(repr(b), '') + + class C_with_slots(A_with_slots): + __slots__ = () + c = C_with_slots() + with self.assertRaisesRegex(TypeError, 'layout differs'): + C_with_slots.__bases__ = (A_with_slots_dict,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + C_with_slots.__bases__ = (A_with_dict_weakref,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + C_with_slots.__bases__ = (A_with_dict,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + C_with_slots.__bases__ = (A,) + C_with_slots.__bases__ = (A_with_slots,) + self.assertEqual(repr(c), '') + + class C_with_slots_dict(A_with_slots): + pass + c = C_with_slots_dict() + with self.assertRaisesRegex(TypeError, 'layout differs'): + C_with_slots_dict.__bases__ = (A_with_dict_weakref,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + C_with_slots_dict.__bases__ = (A_with_dict,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + C_with_slots_dict.__bases__ = (A,) + C_with_slots_dict.__bases__ = (A_with_slots_dict,) + self.assertEqual(repr(c), '') + C_with_slots_dict.__bases__ = (A_with_slots,) + self.assertEqual(repr(c), '') + + class A_int(int): + __slots__ = () + def __repr__(self): + return '' + class B_int(int): + __slots__ = () + b = B_int(42) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_int.__bases__ = (object,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_int.__bases__ = (tuple,) + with self.assertRaisesRegex(TypeError, 'is not an acceptable base type'): + B_int.__bases__ = (bool,) + B_int.__bases__ = (A_int,) + self.assertEqual(repr(b), '') + B_int.__bases__ = (int,) + self.assertEqual(repr(b), '42') + + class A_tuple(tuple): + __slots__ = () + def __repr__(self): + return '' + class B_tuple(tuple): + __slots__ = () + b = B_tuple((1, 2)) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_tuple.__bases__ = (object,) + with self.assertRaisesRegex(TypeError, 'layout differs'): + B_tuple.__bases__ = (int,) + B_tuple.__bases__ = (A_tuple,) + self.assertEqual(repr(b), '') + B_tuple.__bases__ = (tuple,) + self.assertEqual(repr(b), '(1, 2)') + + def test_assign_bases_many_subclasses(self): + # This is intended to check that typeobject.c:queue_slot_update() can + # handle updating many subclasses when a slot method is re-assigned. + class A: + x = 'hello' + def __call__(self): + return 123 + def __getitem__(self, index): + return None + + class X: + x = 'bye' + + class B(A): pass - else: - self.fail("shouldn't be able to create inheritance cycles") + + subclasses = [] + for i in range(1000): + sc = type(f'Sub{i}', (B,), {}) + subclasses.append(sc) + + self.assertEqual(subclasses[0]()(), 123) + self.assertEqual(subclasses[0]().x, 'hello') + B.__bases__ = (X,) + with self.assertRaises(TypeError): + subclasses[0]()() + self.assertEqual(subclasses[0]().x, 'bye') def test_builtin_bases(self): # Make sure all the builtin types can have their base queried without @@ -4171,26 +4424,14 @@ class C(object): class D(C): pass - try: + with self.assertRaisesRegex(TypeError, 'layout differs'): L.__bases__ = (dict,) - except TypeError: - pass - else: - self.fail("shouldn't turn list subclass into dict subclass") - try: + with self.assertRaisesRegex(TypeError, 'immutable type'): list.__bases__ = (dict,) - except TypeError: - pass - else: - self.fail("shouldn't be able to assign to list.__bases__") - try: + with self.assertRaisesRegex(TypeError, 'layout differs'): D.__bases__ = (C, list) - except TypeError: - pass - else: - self.fail("best_base calculation found wanting") def test_unsubclassable_types(self): with self.assertRaises(TypeError): @@ -4956,7 +5197,7 @@ class X: with self.assertRaises(TypeError) as cm: type(X).__dict__["__doc__"].__delete__(X) - self.assertIn("cannot delete '__doc__' attribute of immutable type 'X'", str(cm.exception)) + self.assertIn("cannot delete '__doc__' attribute of type 'X'", str(cm.exception)) self.assertEqual(X.__doc__, "banana") def test_qualname(self): @@ -5173,25 +5414,30 @@ def foo(self): with self.assertRaisesRegex(NotImplementedError, "BAR"): B().foo - def test_staticmethod_new(self): - class MyStaticMethod(staticmethod): - def __init__(self, func): - pass - def func(): pass - sm = MyStaticMethod(func) - self.assertEqual(repr(sm), '') - self.assertIsNone(sm.__func__) - self.assertIsNone(sm.__wrapped__) - - def test_classmethod_new(self): - class MyClassMethod(classmethod): - def __init__(self, func): - pass - def func(): pass - cm = MyClassMethod(func) - self.assertEqual(repr(cm), '') - self.assertIsNone(cm.__func__) - self.assertIsNone(cm.__wrapped__) + def test_gh146587(self): + # See https://github.com/python/cpython/issues/146587 + + class A: + def __radd__(self, other): ... + + class B(tuple): ... + + self.assertIsNone(() + A()) + self.assertIsNone(B() + A()) + + from typing import NamedTuple + + class T(NamedTuple): + x: int + + class A: + def __init__(self, *args): + self.lst = list(args) + def __radd__(self, other): + return A(*self.lst, other) + + self.assertEqual(((1,)+A()).lst, [(1,)]) + self.assertEqual((T(x=1)+A()).lst, [T(x=1)]) class DictProxyTests(unittest.TestCase): @@ -5742,7 +5988,6 @@ def __repr__(self): objcopy2 = deepcopy(objcopy) self._assert_is_copy(obj, objcopy2) - @unittest.skip("TODO: RUSTPYTHON") def test_issue24097(self): # Slot name is freed inside __getattr__ and is later used. class S(str): # Not interned @@ -6041,5 +6286,69 @@ class A(metaclass=M): pass +class TestGenericDescriptors(unittest.TestCase): + def test___dict__(self): + class CustomClass: + pass + class SlotClass: + __slots__ = ['foo'] + class SlotSubClass(SlotClass): + pass + class IntSubclass(int): + pass + + dict_descriptor = CustomClass.__dict__['__dict__'] + self.assertEqual(dict_descriptor.__objclass__, object) + + for cls in CustomClass, SlotSubClass, IntSubclass: + with self.subTest(cls=cls): + self.assertIs(cls.__dict__['__dict__'], dict_descriptor) + instance = cls() + instance.attr = 123 + self.assertEqual( + dict_descriptor.__get__(instance, cls), + {'attr': 123}, + ) + with self.assertRaises(AttributeError): + print(dict_descriptor.__get__(True, bool)) + with self.assertRaises(AttributeError): + print(dict_descriptor.__get__(SlotClass(), SlotClass)) + + # delegation to type.__dict__ + self.assertIsInstance( + dict_descriptor.__get__(type, type), + types.MappingProxyType, + ) + + def test___weakref__(self): + class CustomClass: + pass + class SlotClass: + __slots__ = ['foo'] + class SlotSubClass(SlotClass): + pass + class IntSubclass(int): + pass + + weakref_descriptor = CustomClass.__dict__['__weakref__'] + self.assertEqual(weakref_descriptor.__objclass__, object) + + for cls in CustomClass, SlotSubClass: + with self.subTest(cls=cls): + self.assertIs(cls.__dict__['__weakref__'], weakref_descriptor) + instance = cls() + instance.attr = 123 + self.assertEqual( + weakref_descriptor.__get__(instance, cls), + None, + ) + with self.assertRaises(AttributeError): + weakref_descriptor.__get__(True, bool) + with self.assertRaises(AttributeError): + weakref_descriptor.__get__(SlotClass(), SlotClass) + with self.assertRaises(AttributeError): + weakref_descriptor.__get__(IntSubclass(), IntSubclass) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_descrtut.py b/Lib/test/test_descrtut.py index 5374c47507b..828440a993a 100644 --- a/Lib/test/test_descrtut.py +++ b/Lib/test/test_descrtut.py @@ -474,8 +474,7 @@ def m(self): "tut8": test_8} def load_tests(loader, tests, pattern): - from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON - tests.addTest(doctest.DocTestSuite(checker=DocTestChecker())) # TODO: RUSTPYTHON + tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_devpoll.py b/Lib/test/test_devpoll.py index 85e0accb611..5951f8817ab 100644 --- a/Lib/test/test_devpoll.py +++ b/Lib/test/test_devpoll.py @@ -2,6 +2,7 @@ # Initial tests are copied as is from "test_poll.py" +import errno import os import random import select @@ -112,6 +113,15 @@ def test_close(self): self.assertRaises(ValueError, devpoll.register, fd, select.POLLIN) self.assertRaises(ValueError, devpoll.unregister, fd) + def test_close_error(self): + # gh-146205: close() should raise OSError if underlying fd is invalid + devpoll = select.devpoll() + fd = devpoll.fileno() + os.close(fd) + with self.assertRaises(OSError) as cm: + devpoll.close() + self.assertEqual(cm.exception.errno, errno.EBADF) + def test_fd_non_inheritable(self): devpoll = select.devpoll() self.addCleanup(devpoll.close) diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py index e11dd17f1d9..7035e72cdda 100644 --- a/Lib/test/test_dict.py +++ b/Lib/test/test_dict.py @@ -678,7 +678,7 @@ def __repr__(self): d = {1: BadRepr()} self.assertRaises(Exc, repr, d) - @support.run_with_limited_c_stack() + @support.skip_if_huge_c_stack() @support.skip_wasi_stack_overflow() @support.skip_emscripten_stack_overflow() def test_repr_deep(self): @@ -951,7 +951,6 @@ def test_empty_presized_dict_in_freelist(self): 'f': None, 'g': None, 'h': None} d = {} - @unittest.expectedFailure # TODO: RUSTPYTHON def test_container_iterator(self): # Bug #3680: tp_traverse was not implemented for dictiter and # dictview objects. @@ -1264,7 +1263,6 @@ def test_free_after_iterating(self): support.check_free_after_iterating(self, lambda d: iter(d.values()), dict) support.check_free_after_iterating(self, lambda d: iter(d.items()), dict) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_equal_operator_modifying_operand(self): # test fix for seg fault reported in bpo-27945 part 3. class X(): @@ -1405,7 +1403,6 @@ def __init__(self, x, y): self.assertEqual(list(reversed(A(1, 0).__dict__)), ['x']) self.assertEqual(list(reversed(A(0, 1).__dict__)), ['y']) - @unittest.expectedFailure # TODO: RUSTPYTHON; RuntimeError: dictionary changed size during iteration def test_reversed_dict_after_clear_and_restore(self): d = {} for i in range(1000): @@ -1427,6 +1424,31 @@ def test_reversed_dict_after_clear_and_restore(self): for it in iterators: self.assertEqual(list(it), []) + def test_reversed_dict_keys_changed_during_iteration(self): + d = dict.fromkeys(range(10)) + for i in range(7): + del d[i] + + iterators = ( + reversed(d), + reversed(d.keys()), + reversed(d.values()), + reversed(d.items()), + ) + for it in iterators: + next(it) + + # Same size as before, but with different keys below + # the iterators' current position. + d.clear() + d.update(dict.fromkeys(range(10))) + for i in range(3, 10): + del d[i] + + for it in iterators: + with self.assertRaisesRegex(RuntimeError, 'keys changed'): + list(it) + def test_dict_copy_order(self): # bpo-34320 od = collections.OrderedDict([('a', 1), ('b', 2)]) @@ -1614,7 +1636,6 @@ class Shenanigans: self.assertEqual(holds_reference.ref['data'], 42) self.assertEqual(holds_reference.attr, "whatever") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_unhashable_key(self): d = {'a': 1} key = [1, 2, 3] @@ -1636,7 +1657,7 @@ def check_unhashable_key(): with check_unhashable_key(): d.get(key) - # Only TypeError exception is overriden, + # Only TypeError exception is overridden, # other exceptions are left unchanged. class HashError: def __hash__(self): @@ -1832,6 +1853,250 @@ class Dict(dict): class SubclassMappingTests(mapping_tests.BasicTestMappingProtocol): type2test = Dict +class FrozenDictMappingTests(mapping_tests.BasicTestImmutableMappingProtocol): + type2test = frozendict + + +class FrozenDict(frozendict): + pass + + +class FrozenDictSlots(frozendict): + __slots__ = ('slot_attr',) + + +class FrozenDictTests(unittest.TestCase): + def test_constructor(self): + # frozendict.__init__() has no effect + d = frozendict(a=1, b=2, c=3) + d.__init__(x=1) + self.assertEqual(d, frozendict(a=1, b=2, c=3)) + + # dict constructor cannot be used on frozendict + with self.assertRaises(TypeError): + dict.__init__(d, x=1) + + # Avoid copy if it's frozendict type + d2 = frozendict(d) + self.assertIs(d2, d) + d2 = FrozenDict(d) + self.assertIsNot(d2, d) + self.assertEqual(d2, d) + + def test_copy(self): + d = frozendict(x=1, y=2) + d2 = d.copy() + self.assertIs(d2, d) + + d = FrozenDict(x=1, y=2) + d2 = d.copy() + self.assertIsNot(d2, d) + self.assertEqual(d2, frozendict(x=1, y=2)) + self.assertEqual(type(d2), frozendict) + + def test_merge(self): + # test "a | b" operator + self.assertEqual(frozendict(x=1) | frozendict(y=2), + frozendict({'x': 1, 'y': 2})) + self.assertEqual(frozendict(x=1) | dict(y=2), + frozendict({'x': 1, 'y': 2})) + self.assertEqual(frozendict(x=1, y=2) | frozendict(y=5), + frozendict({'x': 1, 'y': 5})) + self.assertEqual(FrozenDict(x=1, y=2) | FrozenDict(y=5), + frozendict({'x': 1, 'y': 5})) + + fd = frozendict(x=1, y=2) + self.assertIs(fd | frozendict(), fd) + self.assertIs(fd | {}, fd) + self.assertIs(frozendict() | fd, fd) + + fd = FrozenDict(x=1, y=2) + self.assertEqual(fd | frozendict(), fd) + self.assertEqual(fd | {}, fd) + self.assertEqual(frozendict() | fd, fd) + + # gh-149676: Test hash(frozendict | frozendict) + a = frozendict({"a": 1}) + b = frozendict({"b": 2}) + self.assertEqual(hash(a | b), hash(frozendict({"a": 1, "b": 2}))) + + def test_update(self): + # test "a |= b" operator + d = frozendict(x=1) + copy = d + self.assertIs(copy, d) + d |= frozendict(y=2) + self.assertIsNot(copy, d) + self.assertEqual(d, frozendict({'x': 1, 'y': 2})) + self.assertEqual(copy, frozendict({'x': 1})) + + def test_items_xor(self): + # test "a ^ b" operator on items views + res = frozendict(a=1, b=2).items() ^ frozendict(b=2, c=3).items() + self.assertEqual(res, {('a', 1), ('c', 3)}) + + def test_repr(self): + d = frozendict() + self.assertEqual(repr(d), "frozendict()") + + d = frozendict(x=1, y=2) + self.assertEqual(repr(d), "frozendict({'x': 1, 'y': 2})") + + d = FrozenDict(x=1, y=2) + self.assertEqual(repr(d), "FrozenDict({'x': 1, 'y': 2})") + + def test_hash(self): + # hash() doesn't rely on the items order + self.assertEqual(hash(frozendict(x=1, y=2)), + hash(frozendict(y=2, x=1))) + + # Check that hash() computes the hash of (key, value) pairs + cases = [ + frozendict(a=False, b=True, c=True), + frozendict(a=True, b=False, c=True), + frozendict(a=True, b=True, c=False), + frozendict({False: "a", "b": True, "c": True}), + frozendict({"a": "b", False: True, True: "c"}), + ] + hashes = {hash(fd) for fd in cases} + self.assertEqual(len(hashes), len(cases)) + + fd = frozendict(x=[1], y=[2]) + with self.assertRaisesRegex(TypeError, "unhashable type: 'list'"): + hash(fd) + + @support.cpython_only + def test_hash_cpython(self): + # Check that hash(frozendict) implementation is: + # hash(frozenset(fd.items())) + for fd in ( + frozendict(), + frozendict(x=1, y=2), + frozendict(y=2, x=1), + frozendict(a=False, b=True, c=True), + frozendict.fromkeys('abc'), + ): + with self.subTest(fd=fd): + self.assertEqual(hash(fd), hash(frozenset(fd.items()))) + + def test_fromkeys(self): + self.assertEqual(frozendict.fromkeys('abc'), + frozendict(a=None, b=None, c=None)) + + # Subclass which overrides the constructor + created = frozendict(x=1) + class FrozenDictSubclass(frozendict): + def __new__(cls, *args, **kwargs): + if args or kwargs: + return super().__new__(cls, *args, **kwargs) + else: + return created + + fd = FrozenDictSubclass.fromkeys("abc") + self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None)) + self.assertEqual(type(fd), FrozenDictSubclass) + self.assertEqual(created, frozendict(x=1)) + + fd = FrozenDictSubclass.fromkeys(frozendict(y=2)) + self.assertEqual(fd, frozendict(x=1, y=None)) + self.assertEqual(type(fd), FrozenDictSubclass) + self.assertEqual(created, frozendict(x=1)) + + # Dict subclass with a constructor which returns a frozendict + # by default + class DictSubclass(dict): + def __new__(cls, *args, **kwargs): + if args or kwargs: + return super().__new__(cls, *args, **kwargs) + else: + return created + + fd = DictSubclass.fromkeys("abc") + self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None)) + self.assertEqual(type(fd), DictSubclass) + self.assertEqual(created, frozendict(x=1)) + + # Subclass which doesn't override the constructor + class FrozenDictSubclass2(frozendict): + pass + + fd = FrozenDictSubclass2.fromkeys("abc") + self.assertEqual(fd, frozendict(a=None, b=None, c=None)) + self.assertEqual(type(fd), FrozenDictSubclass2) + + def test_pickle(self): + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + for fd in ( + frozendict(), + frozendict(x=1, y=2), + FrozenDict(x=1, y=2), + FrozenDictSlots(x=1, y=2), + ): + if type(fd) == FrozenDict: + fd.attr = 123 + if type(fd) == FrozenDictSlots: + fd.slot_attr = 456 + with self.subTest(fd=fd, proto=proto): + if proto >= 2: + p = pickle.dumps(fd, proto) + fd2 = pickle.loads(p) + self.assertEqual(fd2, fd) + self.assertEqual(type(fd2), type(fd)) + if type(fd) == FrozenDict: + self.assertEqual(fd2.attr, 123) + if type(fd) == FrozenDictSlots: + self.assertEqual(fd2.slot_attr, 456) + else: + # protocol 0 and 1 don't support frozendict + with self.assertRaises(TypeError): + pickle.dumps(fd, proto) + + def test_pickle_iter(self): + fd = frozendict(c=1, b=2, a=3, d=4, e=5, f=6) + for method_name in (None, 'keys', 'values', 'items'): + if method_name is not None: + meth = getattr(fd, method_name) + else: + meth = lambda: fd + expected = list(meth())[1:] + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(method_name=method_name, protocol=proto): + it = iter(meth()) + next(it) + p = pickle.dumps(it, proto) + unpickled = pickle.loads(p) + self.assertEqual(list(unpickled), expected) + self.assertEqual(list(it), expected) + + def test_unhashable_key(self): + d = frozendict(a=1) + key = [1, 2, 3] + + def check_unhashable_key(): + msg = "cannot use 'list' as a frozendict key (unhashable type: 'list')" + return self.assertRaisesRegex(TypeError, re.escape(msg)) + + with check_unhashable_key(): + key in d + with check_unhashable_key(): + d[key] + with check_unhashable_key(): + d.get(key) + + # Only TypeError exception is overridden, + # other exceptions are left unchanged. + class HashError: + def __hash__(self): + raise KeyError('error') + + key2 = HashError() + with self.assertRaises(KeyError): + key2 in d + with self.assertRaises(KeyError): + d[key2] + with self.assertRaises(KeyError): + d.get(key2) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_dictcomps.py b/Lib/test/test_dictcomps.py index fc7ebb0f5a6..a7a46216787 100644 --- a/Lib/test/test_dictcomps.py +++ b/Lib/test/test_dictcomps.py @@ -75,7 +75,6 @@ def test_local_visibility(self): self.assertEqual(actual, expected) self.assertEqual(v, "Local variable") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_illegal_assignment(self): with self.assertRaisesRegex(SyntaxError, "cannot assign"): compile("{x: y for y, x in ((1, 2), (3, 4))} = 5", "", @@ -133,7 +132,7 @@ def test_star_expression(self): def test_exception_locations(self): # The location of an exception raised from __init__ or - # __next__ should should be the iterator expression + # __next__ should be the iterator expression def init_raises(): try: {x:x for x in BrokenIter(init_raises=True)} diff --git a/Lib/test/test_dictviews.py b/Lib/test/test_dictviews.py index 024d20a63a1..3af0501765a 100644 --- a/Lib/test/test_dictviews.py +++ b/Lib/test/test_dictviews.py @@ -279,7 +279,6 @@ def test_recursive_repr(self): # Again. self.assertIsInstance(r, str) - @unittest.skip("TODO: RUSTPYTHON; segfault") @run_with_limited_c_stack() @skip_wasi_stack_overflow() @skip_emscripten_stack_overflow() diff --git a/Lib/test/test_difflib.py b/Lib/test/test_difflib.py index 518b8c5278e..4f99b7c91c6 100644 --- a/Lib/test/test_difflib.py +++ b/Lib/test/test_difflib.py @@ -1,5 +1,7 @@ import difflib -from test.support import findfile +from test import support +from test.support import findfile, force_colorized +from test.support.import_helper import ensure_lazy_imports import unittest import doctest import sys @@ -265,21 +267,21 @@ def test_make_file_default_charset(self): html_diff = difflib.HtmlDiff() output = html_diff.make_file(patch914575_from1.splitlines(), patch914575_to1.splitlines()) - self.assertIn('content="text/html; charset=utf-8"', output) + self.assertIn('charset="utf-8"', output) def test_make_file_iso88591_charset(self): html_diff = difflib.HtmlDiff() output = html_diff.make_file(patch914575_from1.splitlines(), patch914575_to1.splitlines(), charset='iso-8859-1') - self.assertIn('content="text/html; charset=iso-8859-1"', output) + self.assertIn('charset="iso-8859-1"', output) def test_make_file_usascii_charset_with_nonascii_input(self): html_diff = difflib.HtmlDiff() output = html_diff.make_file(patch914575_nonascii_from1.splitlines(), patch914575_nonascii_to1.splitlines(), charset='us-ascii') - self.assertIn('content="text/html; charset=us-ascii"', output) + self.assertIn('charset="us-ascii"', output) self.assertIn('ımplıcıt', output) def test_strip_trailing_newlines_before_diff(self): @@ -397,6 +399,22 @@ def test_range_format_context(self): self.assertEqual(fmt(3,6), '4,6') self.assertEqual(fmt(0,0), '0') + @force_colorized + def test_unified_diff_colored_output(self): + args = [['one', 'three'], ['two', 'three'], 'Original', 'Current', + '2005-01-26 23:30:50', '2010-04-02 10:20:52'] + actual = list(difflib.unified_diff(*args, lineterm='', color=True)) + + expect = [ + "\033[1m--- Original\t2005-01-26 23:30:50\033[0m", + "\033[1m+++ Current\t2010-04-02 10:20:52\033[0m", + "\033[36m@@ -1,2 +1,2 @@\033[0m", + "\033[31m-one\033[0m", + "\033[32m+two\033[0m", + "\033[0m three\033[0m", + ] + self.assertEqual(expect, actual) + class TestBytes(unittest.TestCase): # don't really care about the content of the output, just the fact @@ -651,6 +669,12 @@ def setUpModule(): difflib.HtmlDiff._default_prefix = 0 +class LazyImportTest(unittest.TestCase): + @support.cpython_only + def test_lazy_import(self): + ensure_lazy_imports("difflib", {"_colorize"}) + + def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite(difflib)) return tests diff --git a/Lib/test/test_difflib_expect.html b/Lib/test/test_difflib_expect.html index 9f33a9e9c9c..240e2c33368 100644 --- a/Lib/test/test_difflib_expect.html +++ b/Lib/test/test_difflib_expect.html @@ -1,22 +1,42 @@ - - - - + + - - - @@ -37,11 +59,11 @@ - - - - - + + + + + @@ -53,11 +75,11 @@ - - - - - + + + + + @@ -69,11 +91,11 @@ - - - - - + + + + + @@ -111,11 +133,11 @@

Context (first diff within numlines=5(default))

- - - - - + + + + + @@ -128,11 +150,11 @@

Context (first diff within numlines=5(default))

- - - - - + + + + + @@ -145,11 +167,11 @@

Context (first diff within numlines=5(default))

- - - - - + + + + + @@ -170,11 +192,11 @@

Context (first diff after numlines=5(default))

- - - - - + + + + + @@ -187,11 +209,11 @@

Context (first diff after numlines=5(default))

- - - - - + + + + + @@ -204,11 +226,11 @@

Context (first diff after numlines=5(default))

- - - - - + + + + + @@ -225,11 +247,11 @@

Context (numlines=6)

- - - - - + + + + + @@ -241,11 +263,11 @@

Context (numlines=6)

- - - - - + + + + + @@ -257,11 +279,11 @@

Context (numlines=6)

- - - - - + + + + + @@ -278,25 +300,25 @@

Context (numlines=0)

- - - - - + + + + + - - - - - + + + + + - - - - - + + + + +

from
to
f1f1
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
61236123
71237123
81238123
1412314123
1512315123
1616
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
2112321123
2212322123
2312323123
2912329123
3012330123
3131
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.
3612336123
3712337123
3812338123

from
to
f1f1
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
61236123
71237123
81238123
1412314123
1512315123
1616
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
2112321123
2212322123
2312323123
2912329123
3012330123
3131
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.
3612336123
3712337123
3812338123
94569456
1045610456
1111
n12   1. Beautiful is beTTer than ugly.n12   1. Beautiful is better than ugly.
13   2. Explicit is better than implicit.
14   3. Simple is better than complex.13   3.   Simple is better than complex.
15   4. Complex is better than complicated.14   4. Complicated is better than complex.
15   5. Flat is better than nested.
n12   1. Beautiful is beTTer than ugly.n12   1. Beautiful is better than ugly.
13   2. Explicit is better than implicit.
14   3. Simple is better than complex.13   3.   Simple is better than complex.
15   4. Complex is better than complicated.14   4. Complicated is better than complex.
15   5. Flat is better than nested.
1612316123
1712317123
1812318123
2412324123
2512325123
2626
n27   1. Beautiful is beTTer than ugly.n27   1. Beautiful is better than ugly.
28   2. Explicit is better than implicit.
29   3. Simple is better than complex.28   3.   Simple is better than complex.
30   4. Complex is better than complicated.29   4. Complicated is better than complex.
30   5. Flat is better than nested.
n27   1. Beautiful is beTTer than ugly.n27   1. Beautiful is better than ugly.
28   2. Explicit is better than implicit.
29   3. Simple is better than complex.28   3.   Simple is better than complex.
30   4. Complex is better than complicated.29   4. Complicated is better than complex.
30   5. Flat is better than nested.
3112331123
3212332123
3312333123
3912339123
4012340123
4141
t42   1. Beautiful is beTTer than ugly.t42   1. Beautiful is better than ugly.
43   2. Explicit is better than implicit.
44   3. Simple is better than complex.43   3.   Simple is better than complex.
45   4. Complex is better than complicated.44   4. Complicated is better than complex.
45   5. Flat is better than nested.
t42   1. Beautiful is beTTer than ugly.t42   1. Beautiful is better than ugly.
43   2. Explicit is better than implicit.
44   3. Simple is better than complex.43   3.   Simple is better than complex.
45   4. Complex is better than complicated.44   4. Complicated is better than complex.
45   5. Flat is better than nested.
4612346123
4712347123
4812348123

from
to
f1f1
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
61236123
71237123
81238123
1412314123
1512315123
1616
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
2112321123
2212322123
2312323123
2912329123
3012330123
3131
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.
3612336123
3712337123
3812338123

from
to
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
n2   1. Beautiful is beTTer than ugly.n2   1. Beautiful is better than ugly.
3   2. Explicit is better than implicit.
4   3. Simple is better than complex.3   3.   Simple is better than complex.
5   4. Complex is better than complicated.4   4. Complicated is better than complex.
5   5. Flat is better than nested.
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
n17   1. Beautiful is beTTer than ugly.n17   1. Beautiful is better than ugly.
18   2. Explicit is better than implicit.
19   3. Simple is better than complex.18   3.   Simple is better than complex.
20   4. Complex is better than complicated.19   4. Complicated is better than complex.
20   5. Flat is better than nested.
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.
t32   1. Beautiful is beTTer than ugly.t32   1. Beautiful is better than ugly.
33   2. Explicit is better than implicit.
34   3. Simple is better than complex.33   3.   Simple is better than complex.
35   4. Complex is better than complicated.34   4. Complicated is better than complex.
35   5. Flat is better than nested.

Same Context

@@ -396,11 +418,11 @@

tabsize=2

f1f1
t2    Line 1: preceded by from:[tt] to:[ssss]t2    Line 1: preceded by from:[tt] to:[ssss]
3      Line 2: preceded by from:[sstt] to:[sssst]3      Line 2: preceded by from:[sstt] to:[sssst]
4      Line 3: preceded by from:[sstst] to:[ssssss]4      Line 3: preceded by from:[sstst] to:[ssssss]
5Line 4:   has from:[sst] to:[sss] after :5Line 4:   has from:[sst] to:[sss] after :
6Line 5: has from:[t] to:[ss] at end 6Line 5: has from:[t] to:[ss] at end
t2    Line 1: preceded by from:[tt] to:[ssss]t2    Line 1: preceded by from:[tt] to:[ssss]
3      Line 2: preceded by from:[sstt] to:[sssst]3      Line 2: preceded by from:[sstt] to:[sssst]
4      Line 3: preceded by from:[sstst] to:[ssssss]4      Line 3: preceded by from:[sstst] to:[ssssss]
5Line 4:   has from:[sst] to:[sss] after :5Line 4:   has from:[sst] to:[sss] after :
6Line 5: has from:[t] to:[ss] at end 6Line 5: has from:[t] to:[ss] at end

tabsize=default

@@ -412,11 +434,11 @@

tabsize=default

f1f1
t2                Line 1: preceded by from:[tt] to:[ssss]t2    Line 1: preceded by from:[tt] to:[ssss]
3                Line 2: preceded by from:[sstt] to:[sssst]3        Line 2: preceded by from:[sstt] to:[sssst]
4                Line 3: preceded by from:[sstst] to:[ssssss]4      Line 3: preceded by from:[sstst] to:[ssssss]
5Line 4:         has from:[sst] to:[sss] after :5Line 4:   has from:[sst] to:[sss] after :
6Line 5: has from:[t] to:[ss] at end     6Line 5: has from:[t] to:[ss] at end
t2                Line 1: preceded by from:[tt] to:[ssss]t2    Line 1: preceded by from:[tt] to:[ssss]
3                Line 2: preceded by from:[sstt] to:[sssst]3        Line 2: preceded by from:[sstt] to:[sssst]
4                Line 3: preceded by from:[sstst] to:[ssssss]4      Line 3: preceded by from:[sstst] to:[ssssss]
5Line 4:         has from:[sst] to:[sss] after :5Line 4:   has from:[sst] to:[sss] after :
6Line 5: has from:[t] to:[ss] at end     6Line 5: has from:[t] to:[ss] at end

Context (wrapcolumn=14,numlines=0)

@@ -427,31 +449,31 @@

Context (wrapcolumn=14,numlines=0)

n4line 2n4line 2    adde
 >d
n4line 2n4line 2    adde
 >d
n6line 4   changn6line 4   chanG
>ed>Ed
7line 5   chang7line 5a  chanG
>ed>ed
8line 6   chang8line 6a  chang
>ed>Ed
n6line 4   changn6line 4   chanG
>ed>Ed
7line 5   chang7line 5a  chanG
>ed>ed
8line 6   chang8line 6a  chang
>ed>Ed
n10line 8  subtran10line 8
>cted 
n10line 8  subtran10line 8
>cted 
t1212345678901234t121234567890
>56789012345689 
>012345 
13short line13another long l
 >ine that needs
 > to be wrapped
14just fits in!!14just fitS in!!
15just fits in t15just fits in t
>wo lines yup!!>wo lineS yup!!
t1212345678901234t121234567890
>56789012345689 
>012345 
13short line13another long l
 >ine that needs
 > to be wrapped
14just fits in!!14just fitS in!!
15just fits in t15just fits in t
>wo lines yup!!>wo lineS yup!!

wrapcolumn=14,splitlines()

@@ -467,28 +489,28 @@

wrapcolumn=14,splitlines()

>56789012345689>56789012345689
>012345>012345
3line 13line 1
n4line 2n4line 2    adde
 >d
n4line 2n4line 2    adde
 >d
5line 35line 3
n6line 4   changn6line 4   chanG
>ed>Ed
7line 5   chang7line 5a  chanG
>ed>ed
8line 6   chang8line 6a  chang
>ed>Ed
n6line 4   changn6line 4   chanG
>ed>Ed
7line 5   chang7line 5a  chanG
>ed>ed
8line 6   chang8line 6a  chang
>ed>Ed
9line 79line 7
n10line 8  subtran10line 8
>cted 
n10line 8  subtran10line 8
>cted 
11line 911line 9
t1212345678901234t121234567890
>56789012345689 
>012345 
13short line13another long l
 >ine that needs
 > to be wrapped
14just fits in!!14just fitS in!!
15just fits in t15just fits in t
>wo lines yup!!>wo lineS yup!!
t1212345678901234t121234567890
>56789012345689 
>012345 
13short line13another long l
 >ine that needs
 > to be wrapped
14just fits in!!14just fitS in!!
15just fits in t15just fits in t
>wo lines yup!!>wo lineS yup!!
16the end16the end
@@ -505,28 +527,28 @@

wrapcolumn=14,splitlines(True)

>56789012345689>56789012345689
>012345>012345
3line 13line 1
n4line 2n4line 2    adde
 >d
n4line 2n4line 2    adde
 >d
5line 35line 3
n6line 4   changn6line 4   chanG
>ed>Ed
7line 5   chang7line 5a  chanG
>ed>ed
8line 6   chang8line 6a  chang
>ed>Ed
n6line 4   changn6line 4   chanG
>ed>Ed
7line 5   chang7line 5a  chanG
>ed>ed
8line 6   chang8line 6a  chang
>ed>Ed
9line 79line 7
n10line 8  subtran10line 8
>cted 
n10line 8  subtran10line 8
>cted 
11line 911line 9
t1212345678901234t121234567890
>56789012345689 
>012345 
13short line13another long l
 >ine that needs
 > to be wrapped
14just fits in!!14just fitS in!!
15just fits in t15just fits in t
>wo lines yup!!>wo lineS yup!!
t1212345678901234t121234567890
>56789012345689 
>012345 
13short line13another long l
 >ine that needs
 > to be wrapped
14just fits in!!14just fitS in!!
15just fits in t15just fits in t
>wo lines yup!!>wo lineS yup!!
16the end16the end
diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py index 190374fba8c..e15ef577a4f 100644 --- a/Lib/test/test_dis.py +++ b/Lib/test/test_dis.py @@ -56,7 +56,7 @@ def cm(cls, x): COMPARE_OP 72 (==) LOAD_FAST_BORROW 0 (self) STORE_ATTR 0 (x) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ % (_C.__init__.__code__.co_firstlineno, _C.__init__.__code__.co_firstlineno + 1,) @@ -67,7 +67,7 @@ def cm(cls, x): COMPARE_OP 72 (==) LOAD_FAST_BORROW 0 STORE_ATTR 0 - LOAD_CONST 1 + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -79,7 +79,7 @@ def cm(cls, x): COMPARE_OP 72 (==) LOAD_FAST_BORROW 0 (cls) STORE_ATTR 0 (x) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ % (_C.cm.__code__.co_firstlineno, _C.cm.__code__.co_firstlineno + 2,) @@ -90,7 +90,7 @@ def cm(cls, x): LOAD_SMALL_INT 1 COMPARE_OP 72 (==) STORE_FAST 0 (x) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ % (_C.sm.__code__.co_firstlineno, _C.sm.__code__.co_firstlineno + 2,) @@ -127,13 +127,13 @@ def _f(a): dis_f_with_offsets = """\ %3d 0 RESUME 0 -%3d 2 LOAD_GLOBAL 1 (print + NULL) - 12 LOAD_FAST_BORROW 0 (a) - 14 CALL 1 - 22 POP_TOP +%3d 4 LOAD_GLOBAL 1 (print + NULL) + 14 LOAD_FAST_BORROW 0 (a) + 16 CALL 1 + 24 POP_TOP -%3d 24 LOAD_SMALL_INT 1 - 26 RETURN_VALUE +%3d 26 LOAD_SMALL_INT 1 + 28 RETURN_VALUE """ % (_f.__code__.co_firstlineno, _f.__code__.co_firstlineno + 1, _f.__code__.co_firstlineno + 2) @@ -174,7 +174,7 @@ def bug708901(): %3d LOAD_SMALL_INT 10 %3d CALL 2 - GET_ITER + GET_ITER 0 L1: FOR_ITER 3 (to L2) STORE_FAST 0 (res) @@ -182,7 +182,7 @@ def bug708901(): %3d L2: END_FOR POP_ITER - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ % (bug708901.__code__.co_firstlineno, bug708901.__code__.co_firstlineno + 1, @@ -204,7 +204,6 @@ def bug1333982(x=[]): LOAD_CONST 1 ( at 0x..., file "%s", line %d>) MAKE_FUNCTION LOAD_FAST_BORROW 0 (x) - GET_ITER CALL 0 %3d LOAD_SMALL_INT 1 @@ -230,7 +229,7 @@ def bug42562(): dis_bug42562 = """\ RESUME 0 - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -283,7 +282,7 @@ def wrap_func_w_kwargs(): LOAD_CONST 1 (('c',)) CALL_KW 3 POP_TOP - LOAD_CONST 2 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ % (wrap_func_w_kwargs.__code__.co_firstlineno, wrap_func_w_kwargs.__code__.co_firstlineno + 1) @@ -293,10 +292,10 @@ def wrap_func_w_kwargs(): 1 LOAD_SMALL_INT 0 LOAD_CONST 1 (('*',)) - IMPORT_NAME 0 (math) + IMPORT_NAME 2 (math + eager) CALL_INTRINSIC_1 2 (INTRINSIC_IMPORT_STAR) POP_TOP - LOAD_CONST 2 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -323,7 +322,7 @@ def wrap_func_w_kwargs(): %3d LOAD_GLOBAL 0 (spam) POP_TOP - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -332,19 +331,19 @@ def wrap_func_w_kwargs(): %4d LOAD_GLOBAL 0 (spam) POP_TOP - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ dis_module_expected_results = """\ Disassembly of f: 4 RESUME 0 - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE Disassembly of g: 5 RESUME 0 - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -369,7 +368,7 @@ def wrap_func_w_kwargs(): LOAD_SMALL_INT 1 BINARY_OP 0 (+) STORE_NAME 0 (x) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -410,7 +409,7 @@ def wrap_func_w_kwargs(): LOAD_SMALL_INT 0 CALL 1 STORE_SUBSCR - LOAD_CONST 2 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -428,7 +427,7 @@ def foo(a: int, b: str) -> str: MAKE_FUNCTION SET_FUNCTION_ATTRIBUTE 16 (annotate) STORE_NAME 0 (foo) - LOAD_CONST 2 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ @@ -478,14 +477,14 @@ def foo(a: int, b: str) -> str: LOAD_ATTR 2 (__traceback__) STORE_FAST 1 (tb) L5: POP_EXCEPT - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) STORE_FAST 0 (e) DELETE_FAST 0 (e) %4d LOAD_FAST 1 (tb) RETURN_VALUE - -- L6: LOAD_CONST 1 (None) + -- L6: LOAD_COMMON_CONSTANT 7 (None) STORE_FAST 0 (e) DELETE_FAST 0 (e) RERAISE 1 @@ -554,15 +553,15 @@ def _with(c): %4d LOAD_SMALL_INT 1 STORE_FAST 1 (x) -%4d L2: LOAD_CONST 1 (None) - LOAD_CONST 1 (None) - LOAD_CONST 1 (None) +%4d L2: LOAD_COMMON_CONSTANT 7 (None) + LOAD_COMMON_CONSTANT 7 (None) + LOAD_COMMON_CONSTANT 7 (None) CALL 3 POP_TOP %4d LOAD_SMALL_INT 2 STORE_FAST 2 (y) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE %4d L3: PUSH_EXC_INFO @@ -579,7 +578,7 @@ def _with(c): %4d LOAD_SMALL_INT 2 STORE_FAST 2 (y) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE -- L6: COPY 3 @@ -615,83 +614,85 @@ async def _asyncwith(c): LOAD_SPECIAL 2 (__aenter__) CALL 0 GET_AWAITABLE 1 - LOAD_CONST 0 (None) - L2: SEND 3 (to L5) + PUSH_NULL + LOAD_COMMON_CONSTANT 7 (None) + L2: SEND 4 (to L5) L3: YIELD_VALUE 1 L4: RESUME 3 - JUMP_BACKWARD_NO_INTERRUPT 5 (to L2) + JUMP_BACKWARD_NO_INTERRUPT 6 (to L2) L5: END_SEND L6: POP_TOP %4d LOAD_SMALL_INT 1 STORE_FAST 1 (x) -%4d L7: LOAD_CONST 0 (None) - LOAD_CONST 0 (None) - LOAD_CONST 0 (None) +%4d L7: LOAD_COMMON_CONSTANT 7 (None) + LOAD_COMMON_CONSTANT 7 (None) + LOAD_COMMON_CONSTANT 7 (None) CALL 3 GET_AWAITABLE 2 - LOAD_CONST 0 (None) - L8: SEND 3 (to L11) + PUSH_NULL + LOAD_COMMON_CONSTANT 7 (None) + L8: SEND 4 (to L11) L9: YIELD_VALUE 1 L10: RESUME 3 - JUMP_BACKWARD_NO_INTERRUPT 5 (to L8) + JUMP_BACKWARD_NO_INTERRUPT 6 (to L8) L11: END_SEND POP_TOP %4d LOAD_SMALL_INT 2 STORE_FAST 2 (y) - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE %4d L12: CLEANUP_THROW - L13: JUMP_BACKWARD_NO_INTERRUPT 26 (to L5) + L13: JUMP_BACKWARD_NO_INTERRUPT 28 (to L5) L14: CLEANUP_THROW L15: JUMP_BACKWARD_NO_INTERRUPT 10 (to L11) L16: PUSH_EXC_INFO WITH_EXCEPT_START GET_AWAITABLE 2 - LOAD_CONST 0 (None) - L17: SEND 4 (to L21) + PUSH_NULL + LOAD_COMMON_CONSTANT 7 (None) + L17: SEND 5 (to L21) L18: YIELD_VALUE 1 L19: RESUME 3 - JUMP_BACKWARD_NO_INTERRUPT 5 (to L17) + JUMP_BACKWARD_NO_INTERRUPT 6 (to L17) L20: CLEANUP_THROW L21: END_SEND TO_BOOL - POP_JUMP_IF_TRUE 2 (to L24) - L22: NOT_TAKEN - L23: RERAISE 2 - L24: POP_TOP - L25: POP_EXCEPT + POP_JUMP_IF_TRUE 2 (to L22) + NOT_TAKEN + RERAISE 2 + L22: POP_TOP + L23: POP_EXCEPT POP_TOP POP_TOP POP_TOP %4d LOAD_SMALL_INT 2 STORE_FAST 2 (y) - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE - -- L26: COPY 3 + -- L24: COPY 3 POP_EXCEPT RERAISE 1 - L27: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + L25: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) RERAISE 1 ExceptionTable: - L1 to L3 -> L27 [0] lasti - L3 to L4 -> L12 [4] - L4 to L6 -> L27 [0] lasti + L1 to L3 -> L25 [0] lasti + L3 to L4 -> L12 [5] + L4 to L6 -> L25 [0] lasti L6 to L7 -> L16 [2] lasti - L7 to L9 -> L27 [0] lasti - L9 to L10 -> L14 [2] - L10 to L13 -> L27 [0] lasti - L14 to L15 -> L27 [0] lasti - L16 to L18 -> L26 [4] lasti - L18 to L19 -> L20 [7] - L19 to L22 -> L26 [4] lasti - L23 to L25 -> L26 [4] lasti - L25 to L27 -> L27 [0] lasti + L7 to L9 -> L25 [0] lasti + L9 to L10 -> L14 [3] + L10 to L13 -> L25 [0] lasti + L14 to L15 -> L25 [0] lasti + L16 to L18 -> L24 [4] lasti + L18 to L19 -> L20 [8] + L19 to L23 -> L24 [4] lasti + L23 to L25 -> L25 [0] lasti """ % (_asyncwith.__code__.co_firstlineno, _asyncwith.__code__.co_firstlineno + 1, _asyncwith.__code__.co_firstlineno + 2, @@ -826,14 +827,35 @@ def foo(x): %4d RESUME 0 -%4d LOAD_GLOBAL 1 (list + NULL) +%4d LOAD_GLOBAL 0 (list) + COPY 1 + LOAD_COMMON_CONSTANT 5 (list) + IS_OP 0 (is) + POP_JUMP_IF_FALSE 22 (to L3) + NOT_TAKEN + POP_TOP + BUILD_LIST 0 + LOAD_FAST_BORROW 0 (x) + BUILD_TUPLE 1 + LOAD_CONST %d ( at 0x..., file "%s", line %d>) + MAKE_FUNCTION + SET_FUNCTION_ATTRIBUTE 8 (closure) + LOAD_DEREF 1 (y) + CALL 0 + PUSH_NULL + L1: FOR_ITER 3 (to L2) + LIST_APPEND 3 + JUMP_BACKWARD 5 (to L1) + L2: END_FOR + POP_ITER + RETURN_VALUE + L3: PUSH_NULL LOAD_FAST_BORROW 0 (x) BUILD_TUPLE 1 LOAD_CONST 1 ( at 0x..., file "%s", line %d>) MAKE_FUNCTION SET_FUNCTION_ATTRIBUTE 8 (closure) LOAD_DEREF 1 (y) - GET_ITER CALL 0 CALL 1 RETURN_VALUE @@ -842,6 +864,9 @@ def foo(x): _h.__code__.co_firstlineno + 1, _h.__code__.co_firstlineno + 1, _h.__code__.co_firstlineno + 3, + 1 if __debug__ else 0, + __file__, + _h.__code__.co_firstlineno + 3, __file__, _h.__code__.co_firstlineno + 3, ) @@ -849,29 +874,31 @@ def foo(x): dis_nested_2 = """%s Disassembly of at 0x..., file "%s", line %d>: -- COPY_FREE_VARS 1 + RESUME 4 -%4d RETURN_GENERATOR +%4d LOAD_FAST 0 (.0) + GET_ITER 0 + RETURN_GENERATOR POP_TOP L1: RESUME 0 - LOAD_FAST 0 (.0) - L2: FOR_ITER 14 (to L3) + L2: FOR_ITER 15 (to L3) STORE_FAST 1 (z) LOAD_DEREF 2 (x) LOAD_FAST_BORROW 1 (z) BINARY_OP 0 (+) YIELD_VALUE 0 - RESUME 5 + RESUME 9 POP_TOP - JUMP_BACKWARD 16 (to L2) + JUMP_BACKWARD 17 (to L2) L3: END_FOR POP_ITER - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) RERAISE 1 ExceptionTable: - L1 to L4 -> L4 [0] lasti + L1 to L4 -> L4 [2] lasti """ % (dis_nested_1, __file__, _h.__code__.co_firstlineno + 3, @@ -883,7 +910,7 @@ def load_test(x, y=0): return a, b dis_load_test_quickened_code = """\ -%3d RESUME_CHECK 0 +%3d RESUME_CHECK{: <6} 0 %3d LOAD_FAST_LOAD_FAST 1 (x, y) STORE_FAST_STORE_FAST 50 (b, a) @@ -900,14 +927,14 @@ def loop_test(): load_test(i) dis_loop_test_quickened_code = """\ -%3d RESUME_CHECK 0 +%3d RESUME_CHECK{: <6} 0 %3d BUILD_LIST 0 - LOAD_CONST_MORTAL 2 ((1, 2, 3)) + LOAD_CONST 1 ((1, 2, 3)) LIST_EXTEND 1 LOAD_SMALL_INT 3 BINARY_OP 5 (*) - GET_ITER + GET_ITER_VIRTUAL 0 L1: FOR_ITER_LIST 14 (to L2) STORE_FAST 0 (i) @@ -919,7 +946,7 @@ def loop_test(): %3d L2: END_FOR POP_ITER - LOAD_CONST_IMMORTAL 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """ % (loop_test.__code__.co_firstlineno, loop_test.__code__.co_firstlineno + 1, @@ -937,7 +964,7 @@ def extended_arg_quick(): UNPACK_EX 256 POP_TOP STORE_FAST 0 (_) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE """% (extended_arg_quick.__code__.co_firstlineno, extended_arg_quick.__code__.co_firstlineno + 1,) @@ -1009,6 +1036,7 @@ def test_widths(self): long_opcodes = set(['JUMP_BACKWARD_NO_INTERRUPT', 'LOAD_FAST_BORROW_LOAD_FAST_BORROW', 'INSTRUMENTED_CALL_FUNCTION_EX', + 'YIELD_FROM_CORO_CHECK', 'ANNOTATIONS_PLACEHOLDER']) for op, opname in enumerate(dis.opname): if opname in long_opcodes or opname.startswith("INSTRUMENTED"): @@ -1053,7 +1081,7 @@ def test_dis_with_some_positions(self): '', '2:3-3:15 NOP', '', - '3:11-3:15 LOAD_CONST 0 (None)', + '3:11-3:15 LOAD_COMMON_CONSTANT 7 (None)', '3:11-3:15 RETURN_VALUE', '', ' -- L1: PUSH_EXC_INFO', @@ -1084,7 +1112,7 @@ def test_dis_with_linenos_but_no_columns(self): '', '2:5-2:6 LOAD_SMALL_INT 1', '2:?-2:? STORE_FAST 0 (x)', - '2:?-2:? LOAD_CONST 1 (None)', + '2:?-2:? LOAD_COMMON_CONSTANT 7 (None)', '2:?-2:? RETURN_VALUE', '', ]) @@ -1097,7 +1125,7 @@ def f(): f.__code__ = f.__code__.replace(co_linetable=b'') expect = '\n'.join([ ' RESUME 0', - ' LOAD_CONST 0 (None)', + ' LOAD_COMMON_CONSTANT 7 (None)', ' RETURN_VALUE', '', ]) @@ -1297,28 +1325,32 @@ def code_quicken(f): def test_super_instructions(self): self.code_quicken(lambda: load_test(0, 0)) got = self.get_disassembly(load_test, adaptive=True) - self.do_disassembly_compare(got, dis_load_test_quickened_code) + jit = sys._jit.is_enabled() + expected = dis_load_test_quickened_code.format("_JIT" if jit else "") + self.do_disassembly_compare(got, expected) @cpython_only @requires_specialization def test_load_attr_specialize(self): load_attr_quicken = """\ - 0 RESUME_CHECK 0 + 0 RESUME_CHECK{: <6} 0 - 1 LOAD_CONST_IMMORTAL 0 ('a') + 1 LOAD_CONST 0 ('a') LOAD_ATTR_SLOT 0 (__class__) RETURN_VALUE """ co = compile("'a'.__class__", "", "eval") self.code_quicken(lambda: exec(co, {}, {})) got = self.get_disassembly(co, adaptive=True) - self.do_disassembly_compare(got, load_attr_quicken) + jit = sys._jit.is_enabled() + expected = load_attr_quicken.format("_JIT" if jit else "") + self.do_disassembly_compare(got, expected) @cpython_only @requires_specialization def test_call_specialize(self): call_quicken = """\ - 0 RESUME_CHECK 0 + 0 RESUME_CHECK{: <6} 0 1 LOAD_NAME 0 (str) PUSH_NULL @@ -1329,7 +1361,9 @@ def test_call_specialize(self): co = compile("str(1)", "", "eval") self.code_quicken(lambda: exec(co, {}, {})) got = self.get_disassembly(co, adaptive=True) - self.do_disassembly_compare(got, call_quicken) + jit = sys._jit.is_enabled() + expected = call_quicken.format("_JIT" if jit else "") + self.do_disassembly_compare(got, expected) @cpython_only @requires_specialization @@ -1338,7 +1372,9 @@ def test_loop_quicken(self): self.code_quicken(loop_test) got = self.get_disassembly(loop_test, adaptive=True) jit = sys._jit.is_enabled() - expected = dis_loop_test_quickened_code.format("JIT" if jit else "NO_JIT") + resume_str = "_JIT" if jit else "" + jit_str = "JIT " if jit else "NO_JIT" + expected = dis_loop_test_quickened_code.format(resume_str, jit_str) self.do_disassembly_compare(got, expected) @cpython_only @@ -1405,7 +1441,7 @@ def test_show_caches(self): caches = list(self.get_cached_values(quickened, adaptive)) for cache in caches: self.assertRegex(cache, pattern) - total_caches = 21 + total_caches = 23 empty_caches = 7 self.assertEqual(caches.count(""), empty_caches) self.assertEqual(len(caches), total_caches) @@ -1467,7 +1503,7 @@ def get_disassembly(self, func, lasti=-1, wrapper=True, **kwargs): Kw-only arguments: 0 Number of locals: 1 Stack size: \\d+ -Flags: OPTIMIZED, NEWLOCALS, HAS_DOCSTRING +Flags: OPTIMIZED, NEWLOCALS(, HAS_DOCSTRING)? Constants: {code_info_consts} Names: @@ -1494,7 +1530,6 @@ def f(c=c): Flags: OPTIMIZED, NEWLOCALS, VARARGS, VARKEYWORDS, GENERATOR Constants: 0: - 1: None Variable names: 0: a 1: b @@ -1566,7 +1601,6 @@ def f(c=c): Flags: 0x0 Constants: 0: 1 - 1: None Names: 0: x""" @@ -1601,7 +1635,6 @@ async def async_def(): Flags: OPTIMIZED, NEWLOCALS, COROUTINE Constants: 0: 1 - 1: None Names: 0: b 1: c @@ -1750,209 +1783,210 @@ def _prepare_test_cases(): expected_opinfo_outer = [ make_inst(opname='MAKE_CELL', arg=0, argval='a', argrepr='a', offset=0, start_offset=0, starts_line=True, line_number=None), make_inst(opname='MAKE_CELL', arg=1, argval='b', argrepr='b', offset=2, start_offset=2, starts_line=False, line_number=None), - make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=4, start_offset=4, starts_line=True, line_number=1), - make_inst(opname='LOAD_CONST', arg=4, argval=(3, 4), argrepr='(3, 4)', offset=6, start_offset=6, starts_line=True, line_number=2), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='a', argrepr='a', offset=8, start_offset=8, starts_line=False, line_number=2), - make_inst(opname='LOAD_FAST_BORROW', arg=1, argval='b', argrepr='b', offset=10, start_offset=10, starts_line=False, line_number=2), - make_inst(opname='BUILD_TUPLE', arg=2, argval=2, argrepr='', offset=12, start_offset=12, starts_line=False, line_number=2), - make_inst(opname='LOAD_CONST', arg=1, argval=code_object_f, argrepr=repr(code_object_f), offset=14, start_offset=14, starts_line=False, line_number=2), - make_inst(opname='MAKE_FUNCTION', arg=None, argval=None, argrepr='', offset=16, start_offset=16, starts_line=False, line_number=2), - make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=8, argval=8, argrepr='closure', offset=18, start_offset=18, starts_line=False, line_number=2), - make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=1, argval=1, argrepr='defaults', offset=20, start_offset=20, starts_line=False, line_number=2), - make_inst(opname='STORE_FAST', arg=2, argval='f', argrepr='f', offset=22, start_offset=22, starts_line=False, line_number=2), - make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=24, start_offset=24, starts_line=True, line_number=7, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_DEREF', arg=0, argval='a', argrepr='a', offset=34, start_offset=34, starts_line=False, line_number=7), - make_inst(opname='LOAD_DEREF', arg=1, argval='b', argrepr='b', offset=36, start_offset=36, starts_line=False, line_number=7), - make_inst(opname='LOAD_CONST', arg=2, argval='', argrepr="''", offset=38, start_offset=38, starts_line=False, line_number=7), - make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=40, start_offset=40, starts_line=False, line_number=7), - make_inst(opname='BUILD_LIST', arg=0, argval=0, argrepr='', offset=42, start_offset=42, starts_line=False, line_number=7), - make_inst(opname='BUILD_MAP', arg=0, argval=0, argrepr='', offset=44, start_offset=44, starts_line=False, line_number=7), - make_inst(opname='LOAD_CONST', arg=3, argval='Hello world!', argrepr="'Hello world!'", offset=46, start_offset=46, starts_line=False, line_number=7), - make_inst(opname='CALL', arg=7, argval=7, argrepr='', offset=48, start_offset=48, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=56, start_offset=56, starts_line=False, line_number=7), - make_inst(opname='LOAD_FAST_BORROW', arg=2, argval='f', argrepr='f', offset=58, start_offset=58, starts_line=True, line_number=8), - make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=60, start_offset=60, starts_line=False, line_number=8), + make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=4, start_offset=4, starts_line=True, line_number=1, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=3, argval=(3, 4), argrepr='(3, 4)', offset=8, start_offset=8, starts_line=True, line_number=2), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='a', argrepr='a', offset=10, start_offset=10, starts_line=False, line_number=2), + make_inst(opname='LOAD_FAST_BORROW', arg=1, argval='b', argrepr='b', offset=12, start_offset=12, starts_line=False, line_number=2), + make_inst(opname='BUILD_TUPLE', arg=2, argval=2, argrepr='', offset=14, start_offset=14, starts_line=False, line_number=2), + make_inst(opname='LOAD_CONST', arg=1, argval=code_object_f, argrepr=repr(code_object_f), offset=16, start_offset=16, starts_line=False, line_number=2), + make_inst(opname='MAKE_FUNCTION', arg=None, argval=None, argrepr='', offset=18, start_offset=18, starts_line=False, line_number=2), + make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=8, argval=8, argrepr='closure', offset=20, start_offset=20, starts_line=False, line_number=2), + make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=1, argval=1, argrepr='defaults', offset=22, start_offset=22, starts_line=False, line_number=2), + make_inst(opname='STORE_FAST', arg=2, argval='f', argrepr='f', offset=24, start_offset=24, starts_line=False, line_number=2), + make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=26, start_offset=26, starts_line=True, line_number=7, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_DEREF', arg=0, argval='a', argrepr='a', offset=36, start_offset=36, starts_line=False, line_number=7), + make_inst(opname='LOAD_DEREF', arg=1, argval='b', argrepr='b', offset=38, start_offset=38, starts_line=False, line_number=7), + make_inst(opname='LOAD_COMMON_CONSTANT', arg=8, argval='', argrepr="''", offset=40, start_offset=40, starts_line=False, line_number=7), + make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=42, start_offset=42, starts_line=False, line_number=7), + make_inst(opname='BUILD_LIST', arg=0, argval=0, argrepr='', offset=44, start_offset=44, starts_line=False, line_number=7), + make_inst(opname='BUILD_MAP', arg=0, argval=0, argrepr='', offset=46, start_offset=46, starts_line=False, line_number=7), + make_inst(opname='LOAD_CONST', arg=2, argval='Hello world!', argrepr="'Hello world!'", offset=48, start_offset=48, starts_line=False, line_number=7), + make_inst(opname='CALL', arg=7, argval=7, argrepr='', offset=50, start_offset=50, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=58, start_offset=58, starts_line=False, line_number=7), + make_inst(opname='LOAD_FAST_BORROW', arg=2, argval='f', argrepr='f', offset=60, start_offset=60, starts_line=True, line_number=8), + make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=62, start_offset=62, starts_line=False, line_number=8), ] expected_opinfo_f = [ make_inst(opname='COPY_FREE_VARS', arg=2, argval=2, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=None), make_inst(opname='MAKE_CELL', arg=0, argval='c', argrepr='c', offset=2, start_offset=2, starts_line=False, line_number=None), make_inst(opname='MAKE_CELL', arg=1, argval='d', argrepr='d', offset=4, start_offset=4, starts_line=False, line_number=None), - make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=6, start_offset=6, starts_line=True, line_number=2), - make_inst(opname='LOAD_CONST', arg=2, argval=(5, 6), argrepr='(5, 6)', offset=8, start_offset=8, starts_line=True, line_number=3), - make_inst(opname='LOAD_FAST_BORROW', arg=3, argval='a', argrepr='a', offset=10, start_offset=10, starts_line=False, line_number=3), - make_inst(opname='LOAD_FAST_BORROW', arg=4, argval='b', argrepr='b', offset=12, start_offset=12, starts_line=False, line_number=3), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='c', argrepr='c', offset=14, start_offset=14, starts_line=False, line_number=3), - make_inst(opname='LOAD_FAST_BORROW', arg=1, argval='d', argrepr='d', offset=16, start_offset=16, starts_line=False, line_number=3), - make_inst(opname='BUILD_TUPLE', arg=4, argval=4, argrepr='', offset=18, start_offset=18, starts_line=False, line_number=3), - make_inst(opname='LOAD_CONST', arg=1, argval=code_object_inner, argrepr=repr(code_object_inner), offset=20, start_offset=20, starts_line=False, line_number=3), - make_inst(opname='MAKE_FUNCTION', arg=None, argval=None, argrepr='', offset=22, start_offset=22, starts_line=False, line_number=3), - make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=8, argval=8, argrepr='closure', offset=24, start_offset=24, starts_line=False, line_number=3), - make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=1, argval=1, argrepr='defaults', offset=26, start_offset=26, starts_line=False, line_number=3), - make_inst(opname='STORE_FAST', arg=2, argval='inner', argrepr='inner', offset=28, start_offset=28, starts_line=False, line_number=3), - make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=30, start_offset=30, starts_line=True, line_number=5, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_DEREF', arg=3, argval='a', argrepr='a', offset=40, start_offset=40, starts_line=False, line_number=5), - make_inst(opname='LOAD_DEREF', arg=4, argval='b', argrepr='b', offset=42, start_offset=42, starts_line=False, line_number=5), - make_inst(opname='LOAD_DEREF', arg=0, argval='c', argrepr='c', offset=44, start_offset=44, starts_line=False, line_number=5), - make_inst(opname='LOAD_DEREF', arg=1, argval='d', argrepr='d', offset=46, start_offset=46, starts_line=False, line_number=5), - make_inst(opname='CALL', arg=4, argval=4, argrepr='', offset=48, start_offset=48, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=56, start_offset=56, starts_line=False, line_number=5), - make_inst(opname='LOAD_FAST_BORROW', arg=2, argval='inner', argrepr='inner', offset=58, start_offset=58, starts_line=True, line_number=6), - make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=60, start_offset=60, starts_line=False, line_number=6), + make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=6, start_offset=6, starts_line=True, line_number=2, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=2, argval=(5, 6), argrepr='(5, 6)', offset=10, start_offset=10, starts_line=True, line_number=3), + make_inst(opname='LOAD_FAST_BORROW', arg=3, argval='a', argrepr='a', offset=12, start_offset=12, starts_line=False, line_number=3), + make_inst(opname='LOAD_FAST_BORROW', arg=4, argval='b', argrepr='b', offset=14, start_offset=14, starts_line=False, line_number=3), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='c', argrepr='c', offset=16, start_offset=16, starts_line=False, line_number=3), + make_inst(opname='LOAD_FAST_BORROW', arg=1, argval='d', argrepr='d', offset=18, start_offset=18, starts_line=False, line_number=3), + make_inst(opname='BUILD_TUPLE', arg=4, argval=4, argrepr='', offset=20, start_offset=20, starts_line=False, line_number=3), + make_inst(opname='LOAD_CONST', arg=1, argval=code_object_inner, argrepr=repr(code_object_inner), offset=22, start_offset=22, starts_line=False, line_number=3), + make_inst(opname='MAKE_FUNCTION', arg=None, argval=None, argrepr='', offset=24, start_offset=24, starts_line=False, line_number=3), + make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=8, argval=8, argrepr='closure', offset=26, start_offset=26, starts_line=False, line_number=3), + make_inst(opname='SET_FUNCTION_ATTRIBUTE', arg=1, argval=1, argrepr='defaults', offset=28, start_offset=28, starts_line=False, line_number=3), + make_inst(opname='STORE_FAST', arg=2, argval='inner', argrepr='inner', offset=30, start_offset=30, starts_line=False, line_number=3), + make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=32, start_offset=32, starts_line=True, line_number=5, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_DEREF', arg=3, argval='a', argrepr='a', offset=42, start_offset=42, starts_line=False, line_number=5), + make_inst(opname='LOAD_DEREF', arg=4, argval='b', argrepr='b', offset=44, start_offset=44, starts_line=False, line_number=5), + make_inst(opname='LOAD_DEREF', arg=0, argval='c', argrepr='c', offset=46, start_offset=46, starts_line=False, line_number=5), + make_inst(opname='LOAD_DEREF', arg=1, argval='d', argrepr='d', offset=48, start_offset=48, starts_line=False, line_number=5), + make_inst(opname='CALL', arg=4, argval=4, argrepr='', offset=50, start_offset=50, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=58, start_offset=58, starts_line=False, line_number=5), + make_inst(opname='LOAD_FAST_BORROW', arg=2, argval='inner', argrepr='inner', offset=60, start_offset=60, starts_line=True, line_number=6), + make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=62, start_offset=62, starts_line=False, line_number=6), ] expected_opinfo_inner = [ make_inst(opname='COPY_FREE_VARS', arg=4, argval=4, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=None), - make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=2, start_offset=2, starts_line=True, line_number=3), - make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=4, start_offset=4, starts_line=True, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_DEREF', arg=2, argval='a', argrepr='a', offset=14, start_offset=14, starts_line=False, line_number=4), - make_inst(opname='LOAD_DEREF', arg=3, argval='b', argrepr='b', offset=16, start_offset=16, starts_line=False, line_number=4), - make_inst(opname='LOAD_DEREF', arg=4, argval='c', argrepr='c', offset=18, start_offset=18, starts_line=False, line_number=4), - make_inst(opname='LOAD_DEREF', arg=5, argval='d', argrepr='d', offset=20, start_offset=20, starts_line=False, line_number=4), - make_inst(opname='LOAD_FAST_BORROW_LOAD_FAST_BORROW', arg=1, argval=('e', 'f'), argrepr='e, f', offset=22, start_offset=22, starts_line=False, line_number=4), - make_inst(opname='CALL', arg=6, argval=6, argrepr='', offset=24, start_offset=24, starts_line=False, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=32, start_offset=32, starts_line=False, line_number=4), - make_inst(opname='LOAD_CONST', arg=0, argval=None, argrepr='None', offset=34, start_offset=34, starts_line=False, line_number=4), - make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=36, start_offset=36, starts_line=False, line_number=4), + make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=2, start_offset=2, starts_line=True, line_number=3, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='LOAD_GLOBAL', arg=1, argval='print', argrepr='print + NULL', offset=6, start_offset=6, starts_line=True, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_DEREF', arg=2, argval='a', argrepr='a', offset=16, start_offset=16, starts_line=False, line_number=4), + make_inst(opname='LOAD_DEREF', arg=3, argval='b', argrepr='b', offset=18, start_offset=18, starts_line=False, line_number=4), + make_inst(opname='LOAD_DEREF', arg=4, argval='c', argrepr='c', offset=20, start_offset=20, starts_line=False, line_number=4), + make_inst(opname='LOAD_DEREF', arg=5, argval='d', argrepr='d', offset=22, start_offset=22, starts_line=False, line_number=4), + make_inst(opname='LOAD_FAST_BORROW_LOAD_FAST_BORROW', arg=1, argval=('e', 'f'), argrepr='e, f', offset=24, start_offset=24, starts_line=False, line_number=4), + make_inst(opname='CALL', arg=6, argval=6, argrepr='', offset=26, start_offset=26, starts_line=False, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=34, start_offset=34, starts_line=False, line_number=4), + make_inst(opname='LOAD_COMMON_CONSTANT', arg=7, argval=None, argrepr='None', offset=36, start_offset=36, starts_line=False, line_number=4), + make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=38, start_offset=38, starts_line=False, line_number=4), ] expected_opinfo_jumpy = [ - make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=1), - make_inst(opname='LOAD_GLOBAL', arg=1, argval='range', argrepr='range + NULL', offset=2, start_offset=2, starts_line=True, line_number=3, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_SMALL_INT', arg=10, argval=10, argrepr='', offset=12, start_offset=12, starts_line=False, line_number=3), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=14, start_offset=14, starts_line=False, line_number=3, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='GET_ITER', arg=None, argval=None, argrepr='', offset=22, start_offset=22, starts_line=False, line_number=3), - make_inst(opname='FOR_ITER', arg=32, argval=92, argrepr='to L4', offset=24, start_offset=24, starts_line=False, line_number=3, label=1, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='STORE_FAST', arg=0, argval='i', argrepr='i', offset=28, start_offset=28, starts_line=False, line_number=3), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=30, start_offset=30, starts_line=True, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=40, start_offset=40, starts_line=False, line_number=4), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=42, start_offset=42, starts_line=False, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=50, start_offset=50, starts_line=False, line_number=4), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=52, start_offset=52, starts_line=True, line_number=5), - make_inst(opname='LOAD_SMALL_INT', arg=4, argval=4, argrepr='', offset=54, start_offset=54, starts_line=False, line_number=5), - make_inst(opname='COMPARE_OP', arg=18, argval='<', argrepr='bool(<)', offset=56, start_offset=56, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='POP_JUMP_IF_FALSE', arg=3, argval=70, argrepr='to L2', offset=60, start_offset=60, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=64, start_offset=64, starts_line=False, line_number=5), - make_inst(opname='JUMP_BACKWARD', arg=23, argval=24, argrepr='to L1', offset=66, start_offset=66, starts_line=True, line_number=6, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=70, start_offset=70, starts_line=True, line_number=7, label=2), - make_inst(opname='LOAD_SMALL_INT', arg=6, argval=6, argrepr='', offset=72, start_offset=72, starts_line=False, line_number=7), - make_inst(opname='COMPARE_OP', arg=148, argval='>', argrepr='bool(>)', offset=74, start_offset=74, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='POP_JUMP_IF_TRUE', arg=3, argval=88, argrepr='to L3', offset=78, start_offset=78, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=82, start_offset=82, starts_line=False, line_number=7), - make_inst(opname='JUMP_BACKWARD', arg=32, argval=24, argrepr='to L1', offset=84, start_offset=84, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=88, start_offset=88, starts_line=True, line_number=8, label=3), - make_inst(opname='JUMP_FORWARD', arg=13, argval=118, argrepr='to L5', offset=90, start_offset=90, starts_line=False, line_number=8), - make_inst(opname='END_FOR', arg=None, argval=None, argrepr='', offset=92, start_offset=92, starts_line=True, line_number=3, label=4), - make_inst(opname='POP_ITER', arg=None, argval=None, argrepr='', offset=94, start_offset=94, starts_line=False, line_number=3), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=96, start_offset=96, starts_line=True, line_number=10, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_CONST', arg=1, argval='I can haz else clause?', argrepr="'I can haz else clause?'", offset=106, start_offset=106, starts_line=False, line_number=10), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=108, start_offset=108, starts_line=False, line_number=10, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=116, start_offset=116, starts_line=False, line_number=10), - make_inst(opname='LOAD_FAST_CHECK', arg=0, argval='i', argrepr='i', offset=118, start_offset=118, starts_line=True, line_number=11, label=5), - make_inst(opname='TO_BOOL', arg=None, argval=None, argrepr='', offset=120, start_offset=120, starts_line=False, line_number=11, cache_info=[('counter', 1, b'\x00\x00'), ('version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_JUMP_IF_FALSE', arg=40, argval=212, argrepr='to L8', offset=128, start_offset=128, starts_line=False, line_number=11, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=132, start_offset=132, starts_line=False, line_number=11), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=134, start_offset=134, starts_line=True, line_number=12, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=144, start_offset=144, starts_line=False, line_number=12), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=146, start_offset=146, starts_line=False, line_number=12, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=154, start_offset=154, starts_line=False, line_number=12), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=156, start_offset=156, starts_line=True, line_number=13), - make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=158, start_offset=158, starts_line=False, line_number=13), - make_inst(opname='BINARY_OP', arg=23, argval=23, argrepr='-=', offset=160, start_offset=160, starts_line=False, line_number=13, cache_info=[('counter', 1, b'\x00\x00'), ('descr', 4, b'\x00\x00\x00\x00\x00\x00\x00\x00')]), - make_inst(opname='STORE_FAST', arg=0, argval='i', argrepr='i', offset=172, start_offset=172, starts_line=False, line_number=13), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=174, start_offset=174, starts_line=True, line_number=14), - make_inst(opname='LOAD_SMALL_INT', arg=6, argval=6, argrepr='', offset=176, start_offset=176, starts_line=False, line_number=14), - make_inst(opname='COMPARE_OP', arg=148, argval='>', argrepr='bool(>)', offset=178, start_offset=178, starts_line=False, line_number=14, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='POP_JUMP_IF_FALSE', arg=3, argval=192, argrepr='to L6', offset=182, start_offset=182, starts_line=False, line_number=14, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=186, start_offset=186, starts_line=False, line_number=14), - make_inst(opname='JUMP_BACKWARD', arg=37, argval=118, argrepr='to L5', offset=188, start_offset=188, starts_line=True, line_number=15, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=192, start_offset=192, starts_line=True, line_number=16, label=6), - make_inst(opname='LOAD_SMALL_INT', arg=4, argval=4, argrepr='', offset=194, start_offset=194, starts_line=False, line_number=16), - make_inst(opname='COMPARE_OP', arg=18, argval='<', argrepr='bool(<)', offset=196, start_offset=196, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='POP_JUMP_IF_TRUE', arg=3, argval=210, argrepr='to L7', offset=200, start_offset=200, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=204, start_offset=204, starts_line=False, line_number=16), - make_inst(opname='JUMP_BACKWARD', arg=46, argval=118, argrepr='to L5', offset=206, start_offset=206, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='JUMP_FORWARD', arg=11, argval=234, argrepr='to L9', offset=210, start_offset=210, starts_line=True, line_number=17, label=7), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=212, start_offset=212, starts_line=True, line_number=19, label=8, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_CONST', arg=2, argval='Who let lolcatz into this test suite?', argrepr="'Who let lolcatz into this test suite?'", offset=222, start_offset=222, starts_line=False, line_number=19), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=224, start_offset=224, starts_line=False, line_number=19, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=232, start_offset=232, starts_line=False, line_number=19), - make_inst(opname='NOP', arg=None, argval=None, argrepr='', offset=234, start_offset=234, starts_line=True, line_number=20, label=9), - make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=236, start_offset=236, starts_line=True, line_number=21), - make_inst(opname='LOAD_SMALL_INT', arg=0, argval=0, argrepr='', offset=238, start_offset=238, starts_line=False, line_number=21), - make_inst(opname='BINARY_OP', arg=11, argval=11, argrepr='/', offset=240, start_offset=240, starts_line=False, line_number=21, cache_info=[('counter', 1, b'\x00\x00'), ('descr', 4, b'\x00\x00\x00\x00\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=252, start_offset=252, starts_line=False, line_number=21), - make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=254, start_offset=254, starts_line=True, line_number=25), - make_inst(opname='COPY', arg=1, argval=1, argrepr='', offset=256, start_offset=256, starts_line=False, line_number=25), - make_inst(opname='LOAD_SPECIAL', arg=1, argval=1, argrepr='__exit__', offset=258, start_offset=258, starts_line=False, line_number=25), - make_inst(opname='SWAP', arg=2, argval=2, argrepr='', offset=260, start_offset=260, starts_line=False, line_number=25), - make_inst(opname='SWAP', arg=3, argval=3, argrepr='', offset=262, start_offset=262, starts_line=False, line_number=25), - make_inst(opname='LOAD_SPECIAL', arg=0, argval=0, argrepr='__enter__', offset=264, start_offset=264, starts_line=False, line_number=25), - make_inst(opname='CALL', arg=0, argval=0, argrepr='', offset=266, start_offset=266, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='STORE_FAST', arg=1, argval='dodgy', argrepr='dodgy', offset=274, start_offset=274, starts_line=False, line_number=25), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=276, start_offset=276, starts_line=True, line_number=26, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_CONST', arg=3, argval='Never reach this', argrepr="'Never reach this'", offset=286, start_offset=286, starts_line=False, line_number=26), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=288, start_offset=288, starts_line=False, line_number=26, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=296, start_offset=296, starts_line=False, line_number=26), - make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=298, start_offset=298, starts_line=True, line_number=25), - make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=300, start_offset=300, starts_line=False, line_number=25), - make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=302, start_offset=302, starts_line=False, line_number=25), - make_inst(opname='CALL', arg=3, argval=3, argrepr='', offset=304, start_offset=304, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=312, start_offset=312, starts_line=False, line_number=25), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=314, start_offset=314, starts_line=True, line_number=28, label=10, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_CONST', arg=6, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=324, start_offset=324, starts_line=False, line_number=28), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=326, start_offset=326, starts_line=False, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=334, start_offset=334, starts_line=False, line_number=28), - make_inst(opname='LOAD_CONST', arg=4, argval=None, argrepr='None', offset=336, start_offset=336, starts_line=False, line_number=28), - make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=338, start_offset=338, starts_line=False, line_number=28), - make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=340, start_offset=340, starts_line=True, line_number=25), - make_inst(opname='WITH_EXCEPT_START', arg=None, argval=None, argrepr='', offset=342, start_offset=342, starts_line=False, line_number=25), - make_inst(opname='TO_BOOL', arg=None, argval=None, argrepr='', offset=344, start_offset=344, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_JUMP_IF_TRUE', arg=2, argval=360, argrepr='to L11', offset=352, start_offset=352, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=356, start_offset=356, starts_line=False, line_number=25), - make_inst(opname='RERAISE', arg=2, argval=2, argrepr='', offset=358, start_offset=358, starts_line=False, line_number=25), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=360, start_offset=360, starts_line=False, line_number=25, label=11), - make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=362, start_offset=362, starts_line=False, line_number=25), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=364, start_offset=364, starts_line=False, line_number=25), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=366, start_offset=366, starts_line=False, line_number=25), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=368, start_offset=368, starts_line=False, line_number=25), - make_inst(opname='JUMP_BACKWARD_NO_INTERRUPT', arg=29, argval=314, argrepr='to L10', offset=370, start_offset=370, starts_line=False, line_number=25), - make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=372, start_offset=372, starts_line=True, line_number=None), - make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=374, start_offset=374, starts_line=False, line_number=None), - make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=376, start_offset=376, starts_line=False, line_number=None), - make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=378, start_offset=378, starts_line=False, line_number=None), - make_inst(opname='LOAD_GLOBAL', arg=4, argval='ZeroDivisionError', argrepr='ZeroDivisionError', offset=380, start_offset=380, starts_line=True, line_number=22, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='CHECK_EXC_MATCH', arg=None, argval=None, argrepr='', offset=390, start_offset=390, starts_line=False, line_number=22), - make_inst(opname='POP_JUMP_IF_FALSE', arg=15, argval=426, argrepr='to L12', offset=392, start_offset=392, starts_line=False, line_number=22, cache_info=[('counter', 1, b'\x00\x00')]), - make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=396, start_offset=396, starts_line=False, line_number=22), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=398, start_offset=398, starts_line=False, line_number=22), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=400, start_offset=400, starts_line=True, line_number=23, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_CONST', arg=5, argval='Here we go, here we go, here we go...', argrepr="'Here we go, here we go, here we go...'", offset=410, start_offset=410, starts_line=False, line_number=23), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=412, start_offset=412, starts_line=False, line_number=23, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=420, start_offset=420, starts_line=False, line_number=23), - make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=422, start_offset=422, starts_line=False, line_number=23), - make_inst(opname='JUMP_BACKWARD_NO_INTERRUPT', arg=56, argval=314, argrepr='to L10', offset=424, start_offset=424, starts_line=False, line_number=23), - make_inst(opname='RERAISE', arg=0, argval=0, argrepr='', offset=426, start_offset=426, starts_line=True, line_number=22, label=12), - make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=428, start_offset=428, starts_line=True, line_number=None), - make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=430, start_offset=430, starts_line=False, line_number=None), - make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=432, start_offset=432, starts_line=False, line_number=None), - make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=434, start_offset=434, starts_line=False, line_number=None), - make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=436, start_offset=436, starts_line=True, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), - make_inst(opname='LOAD_CONST', arg=6, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=446, start_offset=446, starts_line=False, line_number=28), - make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=448, start_offset=448, starts_line=False, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), - make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=456, start_offset=456, starts_line=False, line_number=28), - make_inst(opname='RERAISE', arg=0, argval=0, argrepr='', offset=458, start_offset=458, starts_line=False, line_number=28), - make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=460, start_offset=460, starts_line=True, line_number=None), - make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=462, start_offset=462, starts_line=False, line_number=None), - make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=464, start_offset=464, starts_line=False, line_number=None), + make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=1, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='LOAD_GLOBAL', arg=1, argval='range', argrepr='range + NULL', offset=4, start_offset=4, starts_line=True, line_number=3, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_SMALL_INT', arg=10, argval=10, argrepr='', offset=14, start_offset=14, starts_line=False, line_number=3), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=16, start_offset=16, starts_line=False, line_number=3, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='GET_ITER', arg=0, argval=0, argrepr='', offset=24, start_offset=24, starts_line=False, line_number=3, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='FOR_ITER', arg=33, argval=98, argrepr='to L4', offset=28, start_offset=28, starts_line=False, line_number=3, label=1, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='STORE_FAST', arg=0, argval='i', argrepr='i', offset=32, start_offset=32, starts_line=False, line_number=3), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=34, start_offset=34, starts_line=True, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=44, start_offset=44, starts_line=False, line_number=4), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=46, start_offset=46, starts_line=False, line_number=4, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=54, start_offset=54, starts_line=False, line_number=4), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=56, start_offset=56, starts_line=True, line_number=5), + make_inst(opname='LOAD_SMALL_INT', arg=4, argval=4, argrepr='', offset=58, start_offset=58, starts_line=False, line_number=5), + make_inst(opname='COMPARE_OP', arg=18, argval='<', argrepr='bool(<)', offset=60, start_offset=60, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='POP_JUMP_IF_FALSE', arg=3, argval=74, argrepr='to L2', offset=64, start_offset=64, starts_line=False, line_number=5, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=68, start_offset=68, starts_line=False, line_number=5), + make_inst(opname='JUMP_BACKWARD', arg=23, argval=28, argrepr='to L1', offset=70, start_offset=70, starts_line=True, line_number=6, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=74, start_offset=74, starts_line=True, line_number=7, label=2), + make_inst(opname='LOAD_SMALL_INT', arg=6, argval=6, argrepr='', offset=76, start_offset=76, starts_line=False, line_number=7), + make_inst(opname='COMPARE_OP', arg=148, argval='>', argrepr='bool(>)', offset=78, start_offset=78, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='POP_JUMP_IF_TRUE', arg=3, argval=92, argrepr='to L3', offset=82, start_offset=82, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=86, start_offset=86, starts_line=False, line_number=7), + make_inst(opname='JUMP_BACKWARD', arg=32, argval=28, argrepr='to L1', offset=88, start_offset=88, starts_line=False, line_number=7, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=92, start_offset=92, starts_line=True, line_number=8, label=3), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=94, start_offset=94, starts_line=False, line_number=8), + make_inst(opname='JUMP_FORWARD', arg=13, argval=124, argrepr='to L5', offset=96, start_offset=96, starts_line=False, line_number=8), + make_inst(opname='END_FOR', arg=None, argval=None, argrepr='', offset=98, start_offset=98, starts_line=True, line_number=3, label=4), + make_inst(opname='POP_ITER', arg=None, argval=None, argrepr='', offset=100, start_offset=100, starts_line=False, line_number=3), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=102, start_offset=102, starts_line=True, line_number=10, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=1, argval='I can haz else clause?', argrepr="'I can haz else clause?'", offset=112, start_offset=112, starts_line=False, line_number=10), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=114, start_offset=114, starts_line=False, line_number=10, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=122, start_offset=122, starts_line=False, line_number=10), + make_inst(opname='LOAD_FAST_CHECK', arg=0, argval='i', argrepr='i', offset=124, start_offset=124, starts_line=True, line_number=11, label=5), + make_inst(opname='TO_BOOL', arg=None, argval=None, argrepr='', offset=126, start_offset=126, starts_line=False, line_number=11, cache_info=[('counter', 1, b'\x00\x00'), ('version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_JUMP_IF_FALSE', arg=40, argval=218, argrepr='to L8', offset=134, start_offset=134, starts_line=False, line_number=11, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=138, start_offset=138, starts_line=False, line_number=11), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=140, start_offset=140, starts_line=True, line_number=12, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=150, start_offset=150, starts_line=False, line_number=12), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=152, start_offset=152, starts_line=False, line_number=12, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=160, start_offset=160, starts_line=False, line_number=12), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=162, start_offset=162, starts_line=True, line_number=13), + make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=164, start_offset=164, starts_line=False, line_number=13), + make_inst(opname='BINARY_OP', arg=23, argval=23, argrepr='-=', offset=166, start_offset=166, starts_line=False, line_number=13, cache_info=[('counter', 1, b'\x00\x00'), ('descr', 4, b'\x00\x00\x00\x00\x00\x00\x00\x00')]), + make_inst(opname='STORE_FAST', arg=0, argval='i', argrepr='i', offset=178, start_offset=178, starts_line=False, line_number=13), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=180, start_offset=180, starts_line=True, line_number=14), + make_inst(opname='LOAD_SMALL_INT', arg=6, argval=6, argrepr='', offset=182, start_offset=182, starts_line=False, line_number=14), + make_inst(opname='COMPARE_OP', arg=148, argval='>', argrepr='bool(>)', offset=184, start_offset=184, starts_line=False, line_number=14, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='POP_JUMP_IF_FALSE', arg=3, argval=198, argrepr='to L6', offset=188, start_offset=188, starts_line=False, line_number=14, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=192, start_offset=192, starts_line=False, line_number=14), + make_inst(opname='JUMP_BACKWARD', arg=37, argval=124, argrepr='to L5', offset=194, start_offset=194, starts_line=True, line_number=15, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=198, start_offset=198, starts_line=True, line_number=16, label=6), + make_inst(opname='LOAD_SMALL_INT', arg=4, argval=4, argrepr='', offset=200, start_offset=200, starts_line=False, line_number=16), + make_inst(opname='COMPARE_OP', arg=18, argval='<', argrepr='bool(<)', offset=202, start_offset=202, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='POP_JUMP_IF_TRUE', arg=3, argval=216, argrepr='to L7', offset=206, start_offset=206, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=210, start_offset=210, starts_line=False, line_number=16), + make_inst(opname='JUMP_BACKWARD', arg=46, argval=124, argrepr='to L5', offset=212, start_offset=212, starts_line=False, line_number=16, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='JUMP_FORWARD', arg=11, argval=240, argrepr='to L9', offset=216, start_offset=216, starts_line=True, line_number=17, label=7), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=218, start_offset=218, starts_line=True, line_number=19, label=8, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=2, argval='Who let lolcatz into this test suite?', argrepr="'Who let lolcatz into this test suite?'", offset=228, start_offset=228, starts_line=False, line_number=19), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=230, start_offset=230, starts_line=False, line_number=19, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=238, start_offset=238, starts_line=False, line_number=19), + make_inst(opname='NOP', arg=None, argval=None, argrepr='', offset=240, start_offset=240, starts_line=True, line_number=20, label=9), + make_inst(opname='LOAD_SMALL_INT', arg=1, argval=1, argrepr='', offset=242, start_offset=242, starts_line=True, line_number=21), + make_inst(opname='LOAD_SMALL_INT', arg=0, argval=0, argrepr='', offset=244, start_offset=244, starts_line=False, line_number=21), + make_inst(opname='BINARY_OP', arg=11, argval=11, argrepr='/', offset=246, start_offset=246, starts_line=False, line_number=21, cache_info=[('counter', 1, b'\x00\x00'), ('descr', 4, b'\x00\x00\x00\x00\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=258, start_offset=258, starts_line=False, line_number=21), + make_inst(opname='LOAD_FAST_BORROW', arg=0, argval='i', argrepr='i', offset=260, start_offset=260, starts_line=True, line_number=25), + make_inst(opname='COPY', arg=1, argval=1, argrepr='', offset=262, start_offset=262, starts_line=False, line_number=25), + make_inst(opname='LOAD_SPECIAL', arg=1, argval=1, argrepr='__exit__', offset=264, start_offset=264, starts_line=False, line_number=25), + make_inst(opname='SWAP', arg=2, argval=2, argrepr='', offset=266, start_offset=266, starts_line=False, line_number=25), + make_inst(opname='SWAP', arg=3, argval=3, argrepr='', offset=268, start_offset=268, starts_line=False, line_number=25), + make_inst(opname='LOAD_SPECIAL', arg=0, argval=0, argrepr='__enter__', offset=270, start_offset=270, starts_line=False, line_number=25), + make_inst(opname='CALL', arg=0, argval=0, argrepr='', offset=272, start_offset=272, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='STORE_FAST', arg=1, argval='dodgy', argrepr='dodgy', offset=280, start_offset=280, starts_line=False, line_number=25), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=282, start_offset=282, starts_line=True, line_number=26, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=3, argval='Never reach this', argrepr="'Never reach this'", offset=292, start_offset=292, starts_line=False, line_number=26), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=294, start_offset=294, starts_line=False, line_number=26, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=302, start_offset=302, starts_line=False, line_number=26), + make_inst(opname='LOAD_COMMON_CONSTANT', arg=7, argval=None, argrepr='None', offset=304, start_offset=304, starts_line=True, line_number=25), + make_inst(opname='LOAD_COMMON_CONSTANT', arg=7, argval=None, argrepr='None', offset=306, start_offset=306, starts_line=False, line_number=25), + make_inst(opname='LOAD_COMMON_CONSTANT', arg=7, argval=None, argrepr='None', offset=308, start_offset=308, starts_line=False, line_number=25), + make_inst(opname='CALL', arg=3, argval=3, argrepr='', offset=310, start_offset=310, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=318, start_offset=318, starts_line=False, line_number=25), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=320, start_offset=320, starts_line=True, line_number=28, label=10, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=5, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=330, start_offset=330, starts_line=False, line_number=28), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=332, start_offset=332, starts_line=False, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=340, start_offset=340, starts_line=False, line_number=28), + make_inst(opname='LOAD_COMMON_CONSTANT', arg=7, argval=None, argrepr='None', offset=342, start_offset=342, starts_line=False, line_number=28), + make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=344, start_offset=344, starts_line=False, line_number=28), + make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=346, start_offset=346, starts_line=True, line_number=25), + make_inst(opname='WITH_EXCEPT_START', arg=None, argval=None, argrepr='', offset=348, start_offset=348, starts_line=False, line_number=25), + make_inst(opname='TO_BOOL', arg=None, argval=None, argrepr='', offset=350, start_offset=350, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00'), ('version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_JUMP_IF_TRUE', arg=2, argval=366, argrepr='to L11', offset=358, start_offset=358, starts_line=False, line_number=25, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=362, start_offset=362, starts_line=False, line_number=25), + make_inst(opname='RERAISE', arg=2, argval=2, argrepr='', offset=364, start_offset=364, starts_line=False, line_number=25), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=366, start_offset=366, starts_line=False, line_number=25, label=11), + make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=368, start_offset=368, starts_line=False, line_number=25), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=370, start_offset=370, starts_line=False, line_number=25), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=372, start_offset=372, starts_line=False, line_number=25), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=374, start_offset=374, starts_line=False, line_number=25), + make_inst(opname='JUMP_BACKWARD_NO_INTERRUPT', arg=29, argval=320, argrepr='to L10', offset=376, start_offset=376, starts_line=False, line_number=25), + make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=378, start_offset=378, starts_line=True, line_number=None), + make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=380, start_offset=380, starts_line=False, line_number=None), + make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=382, start_offset=382, starts_line=False, line_number=None), + make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=384, start_offset=384, starts_line=False, line_number=None), + make_inst(opname='LOAD_GLOBAL', arg=4, argval='ZeroDivisionError', argrepr='ZeroDivisionError', offset=386, start_offset=386, starts_line=True, line_number=22, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='CHECK_EXC_MATCH', arg=None, argval=None, argrepr='', offset=396, start_offset=396, starts_line=False, line_number=22), + make_inst(opname='POP_JUMP_IF_FALSE', arg=15, argval=432, argrepr='to L12', offset=398, start_offset=398, starts_line=False, line_number=22, cache_info=[('counter', 1, b'\x00\x00')]), + make_inst(opname='NOT_TAKEN', arg=None, argval=None, argrepr='', offset=402, start_offset=402, starts_line=False, line_number=22), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=404, start_offset=404, starts_line=False, line_number=22), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=406, start_offset=406, starts_line=True, line_number=23, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=4, argval='Here we go, here we go, here we go...', argrepr="'Here we go, here we go, here we go...'", offset=416, start_offset=416, starts_line=False, line_number=23), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=418, start_offset=418, starts_line=False, line_number=23, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=426, start_offset=426, starts_line=False, line_number=23), + make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=428, start_offset=428, starts_line=False, line_number=23), + make_inst(opname='JUMP_BACKWARD_NO_INTERRUPT', arg=56, argval=320, argrepr='to L10', offset=430, start_offset=430, starts_line=False, line_number=23), + make_inst(opname='RERAISE', arg=0, argval=0, argrepr='', offset=432, start_offset=432, starts_line=True, line_number=22, label=12), + make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=434, start_offset=434, starts_line=True, line_number=None), + make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=436, start_offset=436, starts_line=False, line_number=None), + make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=438, start_offset=438, starts_line=False, line_number=None), + make_inst(opname='PUSH_EXC_INFO', arg=None, argval=None, argrepr='', offset=440, start_offset=440, starts_line=False, line_number=None), + make_inst(opname='LOAD_GLOBAL', arg=3, argval='print', argrepr='print + NULL', offset=442, start_offset=442, starts_line=True, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('index', 1, b'\x00\x00'), ('module_keys_version', 1, b'\x00\x00'), ('builtin_keys_version', 1, b'\x00\x00')]), + make_inst(opname='LOAD_CONST', arg=5, argval="OK, now we're done", argrepr='"OK, now we\'re done"', offset=452, start_offset=452, starts_line=False, line_number=28), + make_inst(opname='CALL', arg=1, argval=1, argrepr='', offset=454, start_offset=454, starts_line=False, line_number=28, cache_info=[('counter', 1, b'\x00\x00'), ('func_version', 2, b'\x00\x00\x00\x00')]), + make_inst(opname='POP_TOP', arg=None, argval=None, argrepr='', offset=462, start_offset=462, starts_line=False, line_number=28), + make_inst(opname='RERAISE', arg=0, argval=0, argrepr='', offset=464, start_offset=464, starts_line=False, line_number=28), + make_inst(opname='COPY', arg=3, argval=3, argrepr='', offset=466, start_offset=466, starts_line=True, line_number=None), + make_inst(opname='POP_EXCEPT', arg=None, argval=None, argrepr='', offset=468, start_offset=468, starts_line=False, line_number=None), + make_inst(opname='RERAISE', arg=1, argval=1, argrepr='', offset=470, start_offset=470, starts_line=False, line_number=None), ] # One last piece of inspect fodder to check the default line number handling def simple(): pass expected_opinfo_simple = [ make_inst(opname='RESUME', arg=0, argval=0, argrepr='', offset=0, start_offset=0, starts_line=True, line_number=simple.__code__.co_firstlineno), - make_inst(opname='LOAD_CONST', arg=0, argval=None, argrepr='None', offset=2, start_offset=2, starts_line=False, line_number=simple.__code__.co_firstlineno), - make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=4, start_offset=4, starts_line=False, line_number=simple.__code__.co_firstlineno), + make_inst(opname='LOAD_COMMON_CONSTANT', arg=7, argval=None, argrepr='None', offset=4, start_offset=4, starts_line=False, line_number=simple.__code__.co_firstlineno), + make_inst(opname='RETURN_VALUE', arg=None, argval=None, argrepr='', offset=6, start_offset=6, starts_line=False, line_number=simple.__code__.co_firstlineno), ] @@ -2343,8 +2377,10 @@ def test_from_traceback_dis(self): @requires_debug_ranges() def test_bytecode_co_positions(self): bytecode = dis.Bytecode("a=1") - for instr, positions in zip(bytecode, bytecode.codeobj.co_positions()): - assert instr.positions == positions + it = bytecode.codeobj.co_positions() + next(it) # Ignore the CACHE for the RESUME + for instr, positions in zip(bytecode, it): + self.assertEqual(instr.positions, positions) class TestBytecodeTestCase(BytecodeTestCase): def test_assert_not_in_with_op_not_in_bytecode(self): @@ -2412,7 +2448,7 @@ def func(): code = func.__code__ offsets = [linestart[0] for linestart in dis.findlinestarts(code)] - self.assertEqual(offsets, [0, 2]) + self.assertEqual(offsets, [0, 4]) class TestDisTraceback(DisTestBase): @@ -2427,7 +2463,6 @@ def setUp(self) -> None: pass return super().setUp() - @unittest.expectedFailure # TODO: RUSTPYTHON def get_disassembly(self, tb): output = io.StringIO() with contextlib.redirect_stdout(output): @@ -2550,6 +2585,7 @@ def test_show_cache(self): source = 'print()' expect = ''' 0 RESUME 0 + CACHE 0 (counter: 0) 1 LOAD_NAME 0 (print) PUSH_NULL @@ -2558,7 +2594,7 @@ def test_show_cache(self): CACHE 0 (func_version: 0) CACHE 0 POP_TOP - LOAD_CONST 0 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE ''' for flag in ['-C', '--show-caches']: @@ -2570,8 +2606,8 @@ def test_show_offsets(self): expect = ''' 0 0 RESUME 0 - 1 2 LOAD_CONST 0 (None) - 4 RETURN_VALUE + 1 4 LOAD_COMMON_CONSTANT 7 (None) + 6 RETURN_VALUE ''' for flag in ['-O', '--show-offsets']: self.check_output(source, expect, flag) @@ -2582,7 +2618,7 @@ def test_show_positions(self): expect = ''' 0:0-1:0 RESUME 0 - 1:0-1:4 LOAD_CONST 0 (None) + 1:0-1:4 LOAD_COMMON_CONSTANT 7 (None) 1:0-1:4 RETURN_VALUE ''' for flag in ['-P', '--show-positions']: @@ -2594,7 +2630,7 @@ def test_specialized_code(self): expect = ''' 0 RESUME 0 - 1 LOAD_CONST 0 (None) + 1 LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE ''' for flag in ['-S', '--specialized']: diff --git a/Lib/test/test_doctest/test_doctest.py b/Lib/test/test_doctest/test_doctest.py index 1945cd3f0dd..b125693ab08 100644 --- a/Lib/test/test_doctest/test_doctest.py +++ b/Lib/test/test_doctest/test_doctest.py @@ -742,7 +742,7 @@ def non_Python_modules(): r""" >>> import builtins >>> tests = doctest.DocTestFinder().find(builtins) - >>> 750 < len(tests) < 800 # approximate number of objects with docstrings + >>> 750 < len(tests) < 850 # approximate number of objects with docstrings True >>> real_tests = [t for t in tests if len(t.examples) > 0] >>> len(real_tests) # objects that actually have doctests @@ -833,6 +833,118 @@ def test_empty_namespace_package(self): self.assertEqual(len(include_empty_finder.find(mod)), 1) self.assertEqual(len(exclude_empty_finder.find(mod)), 0) + def test_lineno_of_test_dict_strings(self): + """Test line numbers are found for __test__ dict strings.""" + module_content = '''\ +"""Module docstring.""" + +def dummy_function(): + """Dummy function docstring.""" + pass + +__test__ = { + 'test_string': """ + This is a test string. + >>> 1 + 1 + 2 + """, +} +''' + with tempfile.TemporaryDirectory() as tmpdir: + module_path = os.path.join(tmpdir, 'test_module_lineno.py') + with open(module_path, 'w') as f: + f.write(module_content) + + sys.path.insert(0, tmpdir) + try: + import test_module_lineno + finder = doctest.DocTestFinder() + tests = finder.find(test_module_lineno) + + test_dict_test = None + for test in tests: + if '__test__' in test.name: + test_dict_test = test + break + + self.assertIsNotNone( + test_dict_test, + "__test__ dict test not found" + ) + # gh-69113: line number should not be None for __test__ strings + self.assertIsNotNone( + test_dict_test.lineno, + "Line number should not be None for __test__ dict strings" + ) + self.assertGreater( + test_dict_test.lineno, + 0, + "Line number should be positive" + ) + finally: + if 'test_module_lineno' in sys.modules: + del sys.modules['test_module_lineno'] + sys.path.pop(0) + + def test_lineno_multiline_matching(self): + """Test multi-line matching when no unique line exists.""" + # gh-69113: test that line numbers are found even when lines + # appear multiple times (e.g., ">>> x = 1" in both test entries) + module_content = '''\ +"""Module docstring.""" + +__test__ = { + 'test_one': """ + >>> x = 1 + >>> x + 1 + """, + 'test_two': """ + >>> x = 1 + >>> x + 2 + """, +} +''' + with tempfile.TemporaryDirectory() as tmpdir: + module_path = os.path.join(tmpdir, 'test_module_multiline.py') + with open(module_path, 'w') as f: + f.write(module_content) + + sys.path.insert(0, tmpdir) + try: + import test_module_multiline + finder = doctest.DocTestFinder() + tests = finder.find(test_module_multiline) + + test_one = None + test_two = None + for test in tests: + if 'test_one' in test.name: + test_one = test + elif 'test_two' in test.name: + test_two = test + + self.assertIsNotNone(test_one, "test_one not found") + self.assertIsNotNone(test_two, "test_two not found") + self.assertIsNotNone( + test_one.lineno, + "Line number should not be None for test_one" + ) + self.assertIsNotNone( + test_two.lineno, + "Line number should not be None for test_two" + ) + self.assertNotEqual( + test_one.lineno, + test_two.lineno, + "test_one and test_two should have different line numbers" + ) + finally: + if 'test_module_multiline' in sys.modules: + del sys.modules['test_module_multiline'] + sys.path.pop(0) + def test_DocTestParser(): r""" Unit tests for the `DocTestParser` class. @@ -2273,20 +2385,22 @@ def test_DocTestSuite(): >>> suite = doctest.DocTestSuite(test.test_doctest.sample_doctest) >>> result = suite.run(unittest.TestResult()) >>> result - + >>> for tst, _ in result.failures: ... print(tst) - bad (test.test_doctest.sample_doctest.__test__) - foo (test.test_doctest.sample_doctest) - test_silly_setup (test.test_doctest.sample_doctest) - y_is_one (test.test_doctest.sample_doctest) + bad (test.test_doctest.sample_doctest.__test__) [0] + foo (test.test_doctest.sample_doctest) [0] + >>> for tst, _ in result.errors: + ... print(tst) + test_silly_setup (test.test_doctest.sample_doctest) [1] + y_is_one (test.test_doctest.sample_doctest) [0] We can also supply the module by name: >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest') >>> result = suite.run(unittest.TestResult()) >>> result - + The module need not contain any doctest examples: @@ -2308,21 +2422,26 @@ def test_DocTestSuite(): >>> result >>> len(result.skipped) - 2 + 7 >>> for tst, _ in result.skipped: ... print(tst) + double_skip (test.test_doctest.sample_doctest_skip) [0] + double_skip (test.test_doctest.sample_doctest_skip) [1] double_skip (test.test_doctest.sample_doctest_skip) + partial_skip_fail (test.test_doctest.sample_doctest_skip) [0] + partial_skip_pass (test.test_doctest.sample_doctest_skip) [0] + single_skip (test.test_doctest.sample_doctest_skip) [0] single_skip (test.test_doctest.sample_doctest_skip) >>> for tst, _ in result.failures: ... print(tst) - no_skip_fail (test.test_doctest.sample_doctest_skip) - partial_skip_fail (test.test_doctest.sample_doctest_skip) + no_skip_fail (test.test_doctest.sample_doctest_skip) [0] + partial_skip_fail (test.test_doctest.sample_doctest_skip) [1] We can use the current module: >>> suite = test.test_doctest.sample_doctest.test_suite() >>> suite.run(unittest.TestResult()) - + We can also provide a DocTestFinder: @@ -2330,7 +2449,7 @@ def test_DocTestSuite(): >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', ... test_finder=finder) >>> suite.run(unittest.TestResult()) - + The DocTestFinder need not return any tests: @@ -2346,7 +2465,7 @@ def test_DocTestSuite(): >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', globs={}) >>> suite.run(unittest.TestResult()) - + Alternatively, we can provide extra globals. Here we'll make an error go away by providing an extra global variable: @@ -2354,7 +2473,7 @@ def test_DocTestSuite(): >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', ... extraglobs={'y': 1}) >>> suite.run(unittest.TestResult()) - + You can pass option flags. Here we'll cause an extra error by disabling the blank-line feature: @@ -2362,7 +2481,7 @@ def test_DocTestSuite(): >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE) >>> suite.run(unittest.TestResult()) - + You can supply setUp and tearDown functions: @@ -2379,7 +2498,7 @@ def test_DocTestSuite(): >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) - + But the tearDown restores sanity: @@ -2397,7 +2516,7 @@ def test_DocTestSuite(): >>> suite = doctest.DocTestSuite('test.test_doctest.sample_doctest', setUp=setUp) >>> suite.run(unittest.TestResult()) - + Here, we didn't need to use a tearDown function because we modified the test globals, which are a copy of the @@ -2413,115 +2532,99 @@ def test_DocTestSuite_errors(): >>> suite = doctest.DocTestSuite(mod) >>> result = suite.run(unittest.TestResult()) >>> result - + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors - File "...sample_doctest_errors.py", line 0, in sample_doctest_errors - - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line 5, in test.test_doctest.sample_doctest_errors - Failed example: + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 5, in test.test_doctest.sample_doctest_errors + >...>> 2 + 2 + AssertionError: Failed example: 2 + 2 Expected: 5 Got: 4 - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line 7, in test.test_doctest.sample_doctest_errors - Failed example: - 1/0 - Exception raised: - Traceback (most recent call last): - File "", line 1, in - 1/0 - ~^~ - ZeroDivisionError: division by zero >>> print(result.failures[1][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors.__test__.bad - File "...sample_doctest_errors.py", line unknown line number, in bad - - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad - Failed example: + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 37, in test.test_doctest.sample_doctest_errors.__test__.bad + >...>> 2 + 2 + AssertionError: Failed example: 2 + 2 Expected: 5 Got: 4 - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad - Failed example: - 1/0 - Exception raised: - Traceback (most recent call last): - File "", line 1, in - 1/0 - ~^~ - ZeroDivisionError: division by zero >>> print(result.failures[2][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors.errors - File "...sample_doctest_errors.py", line 14, in errors - - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line 16, in test.test_doctest.sample_doctest_errors.errors - Failed example: + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 16, in test.test_doctest.sample_doctest_errors.errors + >...>> 2 + 2 + AssertionError: Failed example: 2 + 2 Expected: 5 Got: 4 - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line 18, in test.test_doctest.sample_doctest_errors.errors - Failed example: + + >>> print(result.errors[0][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 7, in test.test_doctest.sample_doctest_errors + >...>> 1/0 + File "", line 1, in + 1/0 + ~^~ + ZeroDivisionError: division by zero + + >>> print(result.errors[1][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 39, in test.test_doctest.sample_doctest_errors.__test__.bad + >...>> 1/0 + File "", line 1, in 1/0 - Exception raised: - Traceback (most recent call last): - File "", line 1, in - 1/0 - ~^~ - ZeroDivisionError: division by zero - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line 23, in test.test_doctest.sample_doctest_errors.errors - Failed example: + ~^~ + ZeroDivisionError: division by zero + + >>> print(result.errors[2][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 18, in test.test_doctest.sample_doctest_errors.errors + >...>> 1/0 + File "", line 1, in + 1/0 + ~^~ + ZeroDivisionError: division by zero + + >>> print(result.errors[3][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 23, in test.test_doctest.sample_doctest_errors.errors + >...>> f() + File "", line 1, in f() - Exception raised: - Traceback (most recent call last): - File "", line 1, in - f() - ~^^ - File "", line 2, in f - 2 + '2' - ~~^~~~~ - TypeError: ... - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line 25, in test.test_doctest.sample_doctest_errors.errors - Failed example: - g() - Exception raised: - Traceback (most recent call last): - File "", line 1, in - g() - ~^^ - File "...sample_doctest_errors.py", line 12, in g - [][0] # line 12 - ~~^^^ - IndexError: list index out of range + ~^^ + File "", line 2, in f + 2 + '2' + ~~^~~~~ + TypeError: ... - >>> print(result.failures[3][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test.test_doctest.sample_doctest_errors.syntax_error - File "...sample_doctest_errors.py", line 29, in syntax_error + >>> print(result.errors[4][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 25, in test.test_doctest.sample_doctest_errors.errors + >...>> g() + File "", line 1, in + g() + ~^^ + File "...sample_doctest_errors.py", line 12, in g + [][0] # line 12 + ~~^^^ + IndexError: list index out of range - ---------------------------------------------------------------------- - File "...sample_doctest_errors.py", line 31, in test.test_doctest.sample_doctest_errors.syntax_error - Failed example: + >>> print(result.errors[5][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...sample_doctest_errors.py", line 31, in test.test_doctest.sample_doctest_errors.syntax_error + >...>> 2+*3 + File "", line 1 2+*3 - Exception raised: - File "", line 1 - 2+*3 - ^ - SyntaxError: invalid syntax + ^ + SyntaxError: invalid syntax """ @@ -2536,7 +2639,7 @@ def test_DocFileSuite(): ... 'test_doctest2.txt', ... 'test_doctest4.txt') >>> suite.run(unittest.TestResult()) - + The test files are looked for in the directory containing the calling module. A package keyword argument can be provided to @@ -2548,14 +2651,14 @@ def test_DocFileSuite(): ... 'test_doctest4.txt', ... package='test.test_doctest') >>> suite.run(unittest.TestResult()) - + '/' should be used as a path separator. It will be converted to a native separator at run time: >>> suite = doctest.DocFileSuite('../test_doctest/test_doctest.txt') >>> suite.run(unittest.TestResult()) - + If DocFileSuite is used from an interactive session, then files are resolved relative to the directory of sys.argv[0]: @@ -2581,7 +2684,7 @@ def test_DocFileSuite(): >>> suite = doctest.DocFileSuite(test_file, module_relative=False) >>> suite.run(unittest.TestResult()) - + It is an error to specify `package` when `module_relative=False`: @@ -2599,12 +2702,15 @@ def test_DocFileSuite(): ... 'test_doctest_skip2.txt') >>> result = suite.run(unittest.TestResult()) >>> result - + >>> len(result.skipped) - 1 + 4 >>> for tst, _ in result.skipped: # doctest: +ELLIPSIS ... print('=', tst) + = ...test_doctest_skip.txt [0] + = ...test_doctest_skip.txt [1] = ...test_doctest_skip.txt + = ...test_doctest_skip2.txt [0] You can specify initial global variables: @@ -2613,7 +2719,7 @@ def test_DocFileSuite(): ... 'test_doctest4.txt', ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) - + In this case, we supplied a missing favorite color. You can provide doctest options: @@ -2624,7 +2730,7 @@ def test_DocFileSuite(): ... optionflags=doctest.DONT_ACCEPT_BLANKLINE, ... globs={'favorite_color': 'blue'}) >>> suite.run(unittest.TestResult()) - + And, you can provide setUp and tearDown functions: @@ -2643,7 +2749,7 @@ def test_DocFileSuite(): ... 'test_doctest4.txt', ... setUp=setUp, tearDown=tearDown) >>> suite.run(unittest.TestResult()) - + But the tearDown restores sanity: @@ -2685,7 +2791,7 @@ def test_DocFileSuite(): ... 'test_doctest4.txt', ... encoding='utf-8') >>> suite.run(unittest.TestResult()) - + """ def test_DocFileSuite_errors(): @@ -2695,52 +2801,49 @@ def test_DocFileSuite_errors(): >>> suite = doctest.DocFileSuite('test_doctest_errors.txt') >>> result = suite.run(unittest.TestResult()) >>> result - + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test_doctest_errors.txt - File "...test_doctest_errors.txt", line 0 - - ---------------------------------------------------------------------- - File "...test_doctest_errors.txt", line 4, in test_doctest_errors.txt - Failed example: + Traceback (most recent call last): + File "...test_doctest_errors.txt", line 4, in test_doctest_errors.txt + >...>> 2 + 2 + AssertionError: Failed example: 2 + 2 Expected: 5 Got: 4 - ---------------------------------------------------------------------- - File "...test_doctest_errors.txt", line 6, in test_doctest_errors.txt - Failed example: + + >>> print(result.errors[0][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...test_doctest_errors.txt", line 6, in test_doctest_errors.txt + >...>> 1/0 + File "", line 1, in 1/0 - Exception raised: - Traceback (most recent call last): - File "", line 1, in - 1/0 - ~^~ - ZeroDivisionError: division by zero - ---------------------------------------------------------------------- - File "...test_doctest_errors.txt", line 11, in test_doctest_errors.txt - Failed example: + ~^~ + ZeroDivisionError: division by zero + + >>> print(result.errors[1][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...test_doctest_errors.txt", line 11, in test_doctest_errors.txt + >...>> f() + File "", line 1, in f() - Exception raised: - Traceback (most recent call last): - File "", line 1, in - f() - ~^^ - File "", line 2, in f - 2 + '2' - ~~^~~~~ - TypeError: ... - ---------------------------------------------------------------------- - File "...test_doctest_errors.txt", line 13, in test_doctest_errors.txt - Failed example: + ~^^ + File "", line 2, in f + 2 + '2' + ~~^~~~~ + TypeError: ... + + >>> print(result.errors[2][1]) # doctest: +ELLIPSIS + Traceback (most recent call last): + File "...test_doctest_errors.txt", line 13, in test_doctest_errors.txt + >...>> 2+*3 + File "", line 1 2+*3 - Exception raised: - File "", line 1 - 2+*3 - ^ - SyntaxError: invalid syntax + ^ + SyntaxError: invalid syntax + """ def test_trailing_space_in_test(): @@ -2811,16 +2914,25 @@ def test_unittest_reportflags(): >>> import unittest >>> result = suite.run(unittest.TestResult()) >>> result - + >>> print(result.failures[0][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test_doctest.txt - ... - Failed example: - favorite_color - ... - Failed example: + Traceback (most recent call last): + File ... + >...>> if 1: + AssertionError: Failed example: if 1: - ... + print('a') + print() + print('b') + Expected: + a + + b + Got: + a + + b + Note that we see both failures displayed. @@ -2829,18 +2941,8 @@ def test_unittest_reportflags(): Now, when we run the test: - >>> result = suite.run(unittest.TestResult()) - >>> result - - >>> print(result.failures[0][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test_doctest.txt - ... - Failed example: - favorite_color - Exception raised: - ... - NameError: name 'favorite_color' is not defined - + >>> suite.run(unittest.TestResult()) + We get only the first failure. @@ -2850,22 +2952,20 @@ def test_unittest_reportflags(): >>> suite = doctest.DocFileSuite('test_doctest.txt', ... optionflags=doctest.DONT_ACCEPT_BLANKLINE | doctest.REPORT_NDIFF) - Then the default eporting options are ignored: + Then the default reporting options are ignored: >>> result = suite.run(unittest.TestResult()) >>> result - + *NOTE*: These doctest are intentionally not placed in raw string to depict the trailing whitespace using `\x20` in the diff below. >>> print(result.failures[0][1]) # doctest: +ELLIPSIS - AssertionError: Failed doctest test for test_doctest.txt - ... - Failed example: - favorite_color - ... - Failed example: + Traceback ... + File ... + >...>> if 1: + AssertionError: Failed example: if 1: print('a') print() @@ -3270,7 +3370,7 @@ def test_testmod_errors(): r""" ~^~ ZeroDivisionError: division by zero ********************************************************************** - File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad + File "...sample_doctest_errors.py", line 37, in test.test_doctest.sample_doctest_errors.__test__.bad Failed example: 2 + 2 Expected: @@ -3278,7 +3378,7 @@ def test_testmod_errors(): r""" Got: 4 ********************************************************************** - File "...sample_doctest_errors.py", line ?, in test.test_doctest.sample_doctest_errors.__test__.bad + File "...sample_doctest_errors.py", line 39, in test.test_doctest.sample_doctest_errors.__test__.bad Failed example: 1/0 Exception raised: @@ -3673,9 +3773,9 @@ def test_run_doctestsuite_multiple_times(): >>> import test.test_doctest.sample_doctest >>> suite = doctest.DocTestSuite(test.test_doctest.sample_doctest) >>> suite.run(unittest.TestResult()) - + >>> suite.run(unittest.TestResult()) - + """ @@ -3855,8 +3955,7 @@ def test_syntax_error_with_incorrect_expected_note(): def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite(doctest)) - from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON - tests.addTest(doctest.DocTestSuite(checker=DocTestChecker())) # TODO: RUSTPYTHON + tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_doctest2.py b/Lib/test/test_doctest2.py deleted file mode 100644 index ab8a0696736..00000000000 --- a/Lib/test/test_doctest2.py +++ /dev/null @@ -1,126 +0,0 @@ -"""A module to test whether doctest recognizes some 2.2 features, -like static and class methods. - ->>> print('yup') # 1 -yup - -We include some (random) encoded (utf-8) text in the text surrounding -the example. It should be ignored: - -ЉЊЈЁЂ - -""" - -import sys -import unittest -if sys.flags.optimize >= 2: - raise unittest.SkipTest("Cannot test docstrings with -O2") - -class C(object): - """Class C. - - >>> print(C()) # 2 - 42 - - - We include some (random) encoded (utf-8) text in the text surrounding - the example. It should be ignored: - - ЉЊЈЁЂ - - """ - - def __init__(self): - """C.__init__. - - >>> print(C()) # 3 - 42 - """ - - def __str__(self): - """ - >>> print(C()) # 4 - 42 - """ - return "42" - - class D(object): - """A nested D class. - - >>> print("In D!") # 5 - In D! - """ - - def nested(self): - """ - >>> print(3) # 6 - 3 - """ - - def getx(self): - """ - >>> c = C() # 7 - >>> c.x = 12 # 8 - >>> print(c.x) # 9 - -12 - """ - return -self._x - - def setx(self, value): - """ - >>> c = C() # 10 - >>> c.x = 12 # 11 - >>> print(c.x) # 12 - -12 - """ - self._x = value - - x = property(getx, setx, doc="""\ - >>> c = C() # 13 - >>> c.x = 12 # 14 - >>> print(c.x) # 15 - -12 - """) - - @staticmethod - def statm(): - """ - A static method. - - >>> print(C.statm()) # 16 - 666 - >>> print(C().statm()) # 17 - 666 - """ - return 666 - - @classmethod - def clsm(cls, val): - """ - A class method. - - >>> print(C.clsm(22)) # 18 - 22 - >>> print(C().clsm(23)) # 19 - 23 - """ - return val - - -class Test(unittest.TestCase): - def test_testmod(self): - import doctest, sys - EXPECTED = 19 - f, t = doctest.testmod(sys.modules[__name__]) - if f: - self.fail("%d of %d doctests failed" % (f, t)) - if t != EXPECTED: - self.fail("expected %d tests to run, not %d" % (EXPECTED, t)) - - -# Pollute the namespace with a bunch of imported functions and classes, -# to make sure they don't get tested. -from doctest import * - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_dtrace.py b/Lib/test/test_dtrace.py index ba2fa99707c..41b52662bd0 100644 --- a/Lib/test/test_dtrace.py +++ b/Lib/test/test_dtrace.py @@ -1,24 +1,57 @@ import dis import os.path import re +import shlex +import signal import subprocess import sys import sysconfig +import tempfile import types import unittest from test import support from test.support import findfile, MS_WINDOWS +from test.support import os_helper if not support.has_subprocess_support: raise unittest.SkipTest("test module requires subprocess") +if not sysconfig.get_config_var('WITH_DTRACE'): + raise unittest.SkipTest( + "CPython must be configured with the --with-dtrace option." + ) def abspath(filename): return os.path.abspath(findfile(filename, subdir="dtracedata")) +def get_probe_binary(): + binary = sys.executable + if sysconfig.get_config_var("Py_ENABLE_SHARED"): + lib_dir = sysconfig.get_config_var("LIBDIR") + if not lib_dir or sysconfig.is_python_build(): + lib_dir = os.path.abspath(os.path.dirname(sys.executable)) + + lib_names = [] + for name in ( + sysconfig.get_config_var("INSTSONAME"), + sysconfig.get_config_var("LDLIBRARY"), + ): + if name and name not in lib_names: + lib_names.append(name) + + if lib_dir: + for name in lib_names: + libpython_path = os.path.join(lib_dir, name) + if os.path.exists(libpython_path): + binary = libpython_path + break + + return binary + + def normalize_trace_output(output): """Normalize DTrace output for comparison. @@ -33,27 +66,93 @@ def normalize_trace_output(output): result = [ row.split("\t") for row in output.splitlines() - if row and not row.startswith('#') + if row and not row.startswith('#') and not row.startswith('@') ] result.sort(key=lambda row: int(row[0])) result = [row[1] for row in result] - return "\n".join(result) + # Normalize paths to basenames (bpftrace outputs full paths) + normalized = [] + for line in result: + # Replace full paths with just the filename + line = re.sub(r'/[^:]+/([^/:]+\.py)', r'\1', line) + normalized.append(line) + return "\n".join(normalized) except (IndexError, ValueError): raise AssertionError( "tracer produced unparsable output:\n{}".format(output) ) +USE_PROCESS_GROUP = (hasattr(os, "setsid") and hasattr(os, "killpg")) +TERMINATE_TIMEOUT = 10 + +def create_process_group(*args, **kwargs): + if USE_PROCESS_GROUP: + kwargs['start_new_session'] = True + return subprocess.Popen(*args, **kwargs) + +def terminate_process_group(proc): + if USE_PROCESS_GROUP: + try: + os.killpg(proc.pid, signal.SIGTERM) + except ProcessLookupError: + pass + else: + proc.terminate() + + try: + proc.communicate(timeout=TERMINATE_TIMEOUT) + except subprocess.TimeoutExpired: + if USE_PROCESS_GROUP: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + else: + proc.kill() + proc.communicate(timeout=TERMINATE_TIMEOUT) # Clean up + + +def run_readelf(cmd): + # Force the C locale to disable localization. + env = dict(os.environ, LC_ALL="C") + try: + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + env=env, + ) + except OSError: + raise unittest.SkipTest("Couldn't find readelf on the path") + + with proc: + stdout, stderr = proc.communicate() + + if proc.returncode: + raise AssertionError( + f"Command {shlex.join(cmd)!r} failed " + f"with exit code {proc.returncode}: " + f"stdout={stdout!r} stderr={stderr!r}" + ) + + return stdout + + class TraceBackend: EXTENSION = None COMMAND = None COMMAND_ARGS = [] def run_case(self, name, optimize_python=None): - actual_output = normalize_trace_output(self.trace_python( - script_file=abspath(name + self.EXTENSION), - python_file=abspath(name + ".py"), - optimize_python=optimize_python)) + try: + actual_output = normalize_trace_output(self.trace_python( + script_file=abspath(name + self.EXTENSION), + python_file=abspath(name + ".py"), + optimize_python=optimize_python)) + except subprocess.TimeoutExpired: + raise AssertionError(f"{self.COMMAND[0]} timed out") with open(abspath(name + self.EXTENSION + ".expected")) as f: expected_output = f.read().rstrip() @@ -66,25 +165,42 @@ def generate_trace_command(self, script_file, subcommand=None): command += ["-c", subcommand] return command - def trace(self, script_file, subcommand=None): + def trace(self, script_file, subcommand=None, *, timeout=None, + check_returncode=False): command = self.generate_trace_command(script_file, subcommand) - stdout, _ = subprocess.Popen(command, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - universal_newlines=True).communicate() + proc = create_process_group(command, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + universal_newlines=True) + try: + stdout, _ = proc.communicate(timeout=timeout) + except subprocess.TimeoutExpired: + terminate_process_group(proc) + raise + if check_returncode and proc.returncode: + raise AssertionError( + f"Command {shlex.join(command)!r} failed " + f"with exit code {proc.returncode}: output={stdout!r}" + ) return stdout def trace_python(self, script_file, python_file, optimize_python=None): python_flags = [] if optimize_python: python_flags.extend(["-O"] * optimize_python) - subcommand = " ".join([sys.executable] + python_flags + [python_file]) - return self.trace(script_file, subcommand) + subcommand = shlex.join([sys.executable] + python_flags + [python_file]) + return self.trace(script_file, subcommand, timeout=60, + check_returncode=True) def assert_usable(self): try: - output = self.trace(abspath("assert_usable" + self.EXTENSION)) + output = self.trace(abspath("assert_usable" + self.EXTENSION), + timeout=10) output = output.strip() + except subprocess.TimeoutExpired: + raise unittest.SkipTest( + f"{self.COMMAND[0]} timed out during usability check" + ) except (FileNotFoundError, NotADirectoryError, PermissionError) as fnfe: output = str(fnfe) if output != "probe: success": @@ -96,11 +212,223 @@ def assert_usable(self): class DTraceBackend(TraceBackend): EXTENSION = ".d" COMMAND = ["dtrace", "-q", "-s"] + if sys.platform == "sunos5": + COMMAND.insert(2, "-Z") class SystemTapBackend(TraceBackend): EXTENSION = ".stp" COMMAND = ["stap", "-g"] + PROBE_PLACEHOLDER = "@PYTHON_SYSTEMTAP_PROBE@" + + @staticmethod + def quote_systemtap_string(value): + return value.replace("\\", "\\\\").replace('"', '\\"') + + def python_probe(self): + executable = self.quote_systemtap_string(sys.executable) + probe_binary = get_probe_binary() + if probe_binary == sys.executable: + return f'process("{executable}").mark' + + # Python built with --enable-shared + probe_binary = self.quote_systemtap_string(probe_binary) + return f'process("{executable}").library("{probe_binary}").mark' + + def render_script(self, filename): + with open(filename) as fp: + script = fp.read() + + return script.replace(self.PROBE_PLACEHOLDER, self.python_probe()) + + def trace(self, script_file, subcommand=None, *, timeout=None, + check_returncode=False): + with tempfile.NamedTemporaryFile( + mode="w", encoding="utf-8", suffix=self.EXTENSION, delete=False + ) as script: + script.write(self.render_script(script_file)) + generated_script_file = script.name + + try: + return super().trace( + generated_script_file, + subcommand, + timeout=timeout, + check_returncode=check_returncode, + ) + finally: + os_helper.unlink(generated_script_file) + + +class BPFTraceBackend(TraceBackend): + EXTENSION = ".bt" + COMMAND = ["bpftrace"] + + # Inline bpftrace programs for each test case + PROGRAMS = { + "call_stack": """ + usdt:{python}:python:function__entry {{ + printf("%lld\\tfunction__entry:%s:%s:%d\\n", + nsecs, str(arg0), str(arg1), arg2); + }} + usdt:{python}:python:function__return {{ + printf("%lld\\tfunction__return:%s:%s:%d\\n", + nsecs, str(arg0), str(arg1), arg2); + }} + """, + "gc": """ + usdt:{python}:python:function__entry {{ + if (str(arg1) == "start") {{ @tracing = 1; }} + }} + usdt:{python}:python:function__return {{ + if (str(arg1) == "start") {{ @tracing = 0; }} + }} + usdt:{python}:python:gc__start {{ + if (@tracing) {{ + printf("%lld\\tgc__start:%d\\n", nsecs, arg0); + }} + }} + usdt:{python}:python:gc__done {{ + if (@tracing) {{ + printf("%lld\\tgc__done:%lld\\n", nsecs, arg0); + }} + }} + END {{ clear(@tracing); }} + """, + } + + # Which test scripts to filter by filename (None = use @tracing flag) + FILTER_BY_FILENAME = {"call_stack": "call_stack.py"} + + @staticmethod + def _filter_probe_rows(output): + return "\n".join( + line for line in output.splitlines() + if line.partition("\t")[0].isdigit() + ) + + # Expected outputs for each test case + # Note: bpftrace captures entry/return and may have slight timing + # differences compared to SystemTap due to probe firing order + EXPECTED = { + "call_stack": """function__entry:call_stack.py::0 +function__entry:call_stack.py:start:23 +function__entry:call_stack.py:function_1:1 +function__entry:call_stack.py:function_3:9 +function__return:call_stack.py:function_3:10 +function__return:call_stack.py:function_1:2 +function__entry:call_stack.py:function_2:5 +function__entry:call_stack.py:function_1:1 +function__entry:call_stack.py:function_3:9 +function__return:call_stack.py:function_3:10 +function__return:call_stack.py:function_1:2 +function__return:call_stack.py:function_2:6 +function__entry:call_stack.py:function_3:9 +function__return:call_stack.py:function_3:10 +function__entry:call_stack.py:function_4:13 +function__return:call_stack.py:function_4:14 +function__entry:call_stack.py:function_5:18 +function__return:call_stack.py:function_5:21 +function__return:call_stack.py:start:28 +function__return:call_stack.py::30""", + "gc": """gc__start:0 +gc__done:0 +gc__start:1 +gc__done:0 +gc__start:2 +gc__done:0 +gc__start:2 +gc__done:1""", + } + + def run_case(self, name, optimize_python=None): + if name not in self.PROGRAMS: + raise unittest.SkipTest(f"No bpftrace program for {name}") + + python_file = abspath(name + ".py") + python_flags = [] + if optimize_python: + python_flags.extend(["-O"] * optimize_python) + + subcommand = [sys.executable] + python_flags + [python_file] + program = self.PROGRAMS[name].format(python=get_probe_binary()) + + try: + proc = create_process_group( + ["bpftrace", "-e", program, "-c", shlex.join(subcommand)], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + ) + stdout, stderr = proc.communicate(timeout=60) + except subprocess.TimeoutExpired: + terminate_process_group(proc) + raise AssertionError("bpftrace timed out") + except (FileNotFoundError, PermissionError) as e: + raise unittest.SkipTest(f"bpftrace not available: {e}") + + if proc.returncode != 0: + raise AssertionError( + f"bpftrace failed with code {proc.returncode}:\n{stderr}" + ) + + stdout = self._filter_probe_rows(stdout) + + # Filter output by filename if specified (bpftrace captures everything) + if name in self.FILTER_BY_FILENAME: + filter_filename = self.FILTER_BY_FILENAME[name] + filtered_lines = [ + line for line in stdout.splitlines() + if filter_filename in line + ] + stdout = "\n".join(filtered_lines) + + actual_output = normalize_trace_output(stdout) + expected_output = self.EXPECTED[name].strip() + + return (expected_output, actual_output) + + def assert_usable(self): + # Check if bpftrace is available and can attach to USDT probes + program = f'usdt:{get_probe_binary()}:python:function__entry {{ printf("probe: success\\n"); exit(); }}' + try: + proc = create_process_group( + ["bpftrace", "-e", program, "-c", + shlex.join([sys.executable, "-c", "pass"])], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + ) + stdout, stderr = proc.communicate(timeout=10) + except subprocess.TimeoutExpired: + terminate_process_group(proc) + raise unittest.SkipTest("bpftrace timed out during usability check") + except OSError as e: + raise unittest.SkipTest(f"bpftrace not available: {e}") + + # Check for permission errors (bpftrace usually requires root) + if proc.returncode != 0: + raise unittest.SkipTest( + f"bpftrace(1) failed with code {proc.returncode}: {stderr}" + ) + + if "probe: success" not in stdout: + raise unittest.SkipTest( + f"bpftrace(1) failed: stdout={stdout!r} stderr={stderr!r}" + ) + + +class BPFTraceOutputTests(unittest.TestCase): + def test_filter_probe_rows_ignores_warnings(self): + output = """stdin:1-19: WARNING: found external warnings +HINT: include/vmlinux.h:1439:3: warning: declaration does not declare anything +4623214882928\tgc__start:0 +4623214885575\tgc__done:0 +""" + self.assertEqual( + BPFTraceBackend._filter_probe_rows(output), + "4623214882928\tgc__start:0\n4623214885575\tgc__done:0", + ) @unittest.skipIf(MS_WINDOWS, "Tests not compliant with trace on Windows.") @@ -127,7 +455,8 @@ def test_function_entry_return(self): def test_verify_call_opcodes(self): """Ensure our call stack test hits all function call opcodes""" - opcodes = set(["CALL_FUNCTION", "CALL_FUNCTION_EX", "CALL_FUNCTION_KW"]) + # Modern Python uses CALL, CALL_KW, and CALL_FUNCTION_EX + opcodes = set(["CALL", "CALL_FUNCTION_EX", "CALL_KW"]) with open(abspath("call_stack.py")) as f: code_string = f.read() @@ -152,9 +481,6 @@ def get_function_instructions(funcname): def test_gc(self): self.run_case("gc") - def test_line(self): - self.run_case("line") - class DTraceNormalTests(TraceTests, unittest.TestCase): backend = DTraceBackend() @@ -175,38 +501,28 @@ class SystemTapOptimizedTests(TraceTests, unittest.TestCase): backend = SystemTapBackend() optimize_python = 2 + +class BPFTraceNormalTests(TraceTests, unittest.TestCase): + backend = BPFTraceBackend() + optimize_python = 0 + + +class BPFTraceOptimizedTests(TraceTests, unittest.TestCase): + backend = BPFTraceBackend() + optimize_python = 2 + + class CheckDtraceProbes(unittest.TestCase): @classmethod def setUpClass(cls): - if sysconfig.get_config_var('WITH_DTRACE'): - readelf_major_version, readelf_minor_version = cls.get_readelf_version() - if support.verbose: - print(f"readelf version: {readelf_major_version}.{readelf_minor_version}") - else: - raise unittest.SkipTest("CPython must be configured with the --with-dtrace option.") + readelf_major_version, readelf_minor_version = cls.get_readelf_version() + if support.verbose: + print(f"readelf version: {readelf_major_version}.{readelf_minor_version}") @staticmethod def get_readelf_version(): - try: - cmd = ["readelf", "--version"] - proc = subprocess.Popen( - cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True, - ) - with proc: - version, stderr = proc.communicate() - - if proc.returncode: - raise Exception( - f"Command {' '.join(cmd)!r} failed " - f"with exit code {proc.returncode}: " - f"stdout={version!r} stderr={stderr!r}" - ) - except OSError: - raise unittest.SkipTest("Couldn't find readelf on the path") + version = run_readelf(["readelf", "--version"]) # Regex to parse: # 'GNU readelf (GNU Binutils) 2.40.0\n' -> 2.40 @@ -217,14 +533,7 @@ def get_readelf_version(): return int(match.group(1)), int(match.group(2)) def get_readelf_output(self): - command = ["readelf", "-n", sys.executable] - stdout, _ = subprocess.Popen( - command, - stdout=subprocess.PIPE, - stderr=subprocess.STDOUT, - universal_newlines=True, - ).communicate() - return stdout + return run_readelf(["readelf", "-n", get_probe_binary()]) def test_check_probes(self): readelf_output = self.get_readelf_output() @@ -235,6 +544,8 @@ def test_check_probes(self): "Name: audit", "Name: gc__start", "Name: gc__done", + "Name: function__entry", + "Name: function__return", ] for probe_name in available_probe_names: @@ -247,8 +558,6 @@ def test_missing_probes(self): # Missing probes will be added in the future. missing_probe_names = [ - "Name: function__entry", - "Name: function__return", "Name: line", ] diff --git a/Lib/test/test_dummy_thread.py b/Lib/test/test_dummy_thread.py deleted file mode 100644 index e654a555c31..00000000000 --- a/Lib/test/test_dummy_thread.py +++ /dev/null @@ -1,278 +0,0 @@ -import _dummy_thread as _thread -import time -import queue -import random -import unittest -from test import support -from unittest import mock - -DELAY = 0 - - -class LockTests(unittest.TestCase): - """Test lock objects.""" - - def setUp(self): - # Create a lock - self.lock = _thread.allocate_lock() - - def test_initlock(self): - #Make sure locks start locked - self.assertFalse(self.lock.locked(), - "Lock object is not initialized unlocked.") - - def test_release(self): - # Test self.lock.release() - self.lock.acquire() - self.lock.release() - self.assertFalse(self.lock.locked(), - "Lock object did not release properly.") - - def test_LockType_context_manager(self): - with _thread.LockType(): - pass - self.assertFalse(self.lock.locked(), - "Acquired Lock was not released") - - def test_improper_release(self): - #Make sure release of an unlocked thread raises RuntimeError - self.assertRaises(RuntimeError, self.lock.release) - - def test_cond_acquire_success(self): - #Make sure the conditional acquiring of the lock works. - self.assertTrue(self.lock.acquire(0), - "Conditional acquiring of the lock failed.") - - def test_cond_acquire_fail(self): - #Test acquiring locked lock returns False - self.lock.acquire(0) - self.assertFalse(self.lock.acquire(0), - "Conditional acquiring of a locked lock incorrectly " - "succeeded.") - - def test_uncond_acquire_success(self): - #Make sure unconditional acquiring of a lock works. - self.lock.acquire() - self.assertTrue(self.lock.locked(), - "Uncondional locking failed.") - - def test_uncond_acquire_return_val(self): - #Make sure that an unconditional locking returns True. - self.assertIs(self.lock.acquire(1), True, - "Unconditional locking did not return True.") - self.assertIs(self.lock.acquire(), True) - - def test_uncond_acquire_blocking(self): - #Make sure that unconditional acquiring of a locked lock blocks. - def delay_unlock(to_unlock, delay): - """Hold on to lock for a set amount of time before unlocking.""" - time.sleep(delay) - to_unlock.release() - - self.lock.acquire() - start_time = int(time.monotonic()) - _thread.start_new_thread(delay_unlock,(self.lock, DELAY)) - if support.verbose: - print() - print("*** Waiting for thread to release the lock "\ - "(approx. %s sec.) ***" % DELAY) - self.lock.acquire() - end_time = int(time.monotonic()) - if support.verbose: - print("done") - self.assertGreaterEqual(end_time - start_time, DELAY, - "Blocking by unconditional acquiring failed.") - - @mock.patch('time.sleep') - def test_acquire_timeout(self, mock_sleep): - """Test invoking acquire() with a positive timeout when the lock is - already acquired. Ensure that time.sleep() is invoked with the given - timeout and that False is returned.""" - - self.lock.acquire() - retval = self.lock.acquire(waitflag=0, timeout=1) - self.assertTrue(mock_sleep.called) - mock_sleep.assert_called_once_with(1) - self.assertEqual(retval, False) - - def test_lock_representation(self): - self.lock.acquire() - self.assertIn("locked", repr(self.lock)) - self.lock.release() - self.assertIn("unlocked", repr(self.lock)) - - -class RLockTests(unittest.TestCase): - """Test dummy RLock objects.""" - - def setUp(self): - self.rlock = _thread.RLock() - - def test_multiple_acquire(self): - self.assertIn("unlocked", repr(self.rlock)) - self.rlock.acquire() - self.rlock.acquire() - self.assertIn("locked", repr(self.rlock)) - self.rlock.release() - self.assertIn("locked", repr(self.rlock)) - self.rlock.release() - self.assertIn("unlocked", repr(self.rlock)) - self.assertRaises(RuntimeError, self.rlock.release) - - -class MiscTests(unittest.TestCase): - """Miscellaneous tests.""" - - def test_exit(self): - self.assertRaises(SystemExit, _thread.exit) - - # TODO: RUSTPYTHON - @unittest.expectedFailure - def test_ident(self): - self.assertIsInstance(_thread.get_ident(), int, - "_thread.get_ident() returned a non-integer") - self.assertGreater(_thread.get_ident(), 0) - - def test_LockType(self): - self.assertIsInstance(_thread.allocate_lock(), _thread.LockType, - "_thread.LockType is not an instance of what " - "is returned by _thread.allocate_lock()") - - def test_set_sentinel(self): - self.assertIsInstance(_thread._set_sentinel(), _thread.LockType, - "_thread._set_sentinel() did not return a " - "LockType instance.") - - def test_interrupt_main(self): - #Calling start_new_thread with a function that executes interrupt_main - # should raise KeyboardInterrupt upon completion. - def call_interrupt(): - _thread.interrupt_main() - - self.assertRaises(KeyboardInterrupt, - _thread.start_new_thread, - call_interrupt, - tuple()) - - def test_interrupt_in_main(self): - self.assertRaises(KeyboardInterrupt, _thread.interrupt_main) - - def test_stack_size_None(self): - retval = _thread.stack_size(None) - self.assertEqual(retval, 0) - - def test_stack_size_not_None(self): - with self.assertRaises(_thread.error) as cm: - _thread.stack_size("") - self.assertEqual(cm.exception.args[0], - "setting thread stack size not supported") - - -class ThreadTests(unittest.TestCase): - """Test thread creation.""" - - def test_arg_passing(self): - #Make sure that parameter passing works. - def arg_tester(queue, arg1=False, arg2=False): - """Use to test _thread.start_new_thread() passes args properly.""" - queue.put((arg1, arg2)) - - testing_queue = queue.Queue(1) - _thread.start_new_thread(arg_tester, (testing_queue, True, True)) - result = testing_queue.get() - self.assertTrue(result[0] and result[1], - "Argument passing for thread creation " - "using tuple failed") - - _thread.start_new_thread( - arg_tester, - tuple(), - {'queue':testing_queue, 'arg1':True, 'arg2':True}) - - result = testing_queue.get() - self.assertTrue(result[0] and result[1], - "Argument passing for thread creation " - "using kwargs failed") - - _thread.start_new_thread( - arg_tester, - (testing_queue, True), - {'arg2':True}) - - result = testing_queue.get() - self.assertTrue(result[0] and result[1], - "Argument passing for thread creation using both tuple" - " and kwargs failed") - - def test_multi_thread_creation(self): - def queue_mark(queue, delay): - time.sleep(delay) - queue.put(_thread.get_ident()) - - thread_count = 5 - testing_queue = queue.Queue(thread_count) - - if support.verbose: - print() - print("*** Testing multiple thread creation " - "(will take approx. %s to %s sec.) ***" % ( - DELAY, thread_count)) - - for count in range(thread_count): - if DELAY: - local_delay = round(random.random(), 1) - else: - local_delay = 0 - _thread.start_new_thread(queue_mark, - (testing_queue, local_delay)) - time.sleep(DELAY) - if support.verbose: - print('done') - self.assertEqual(testing_queue.qsize(), thread_count, - "Not all %s threads executed properly " - "after %s sec." % (thread_count, DELAY)) - - def test_args_not_tuple(self): - """ - Test invoking start_new_thread() with a non-tuple value for "args". - Expect TypeError with a meaningful error message to be raised. - """ - with self.assertRaises(TypeError) as cm: - _thread.start_new_thread(mock.Mock(), []) - self.assertEqual(cm.exception.args[0], "2nd arg must be a tuple") - - def test_kwargs_not_dict(self): - """ - Test invoking start_new_thread() with a non-dict value for "kwargs". - Expect TypeError with a meaningful error message to be raised. - """ - with self.assertRaises(TypeError) as cm: - _thread.start_new_thread(mock.Mock(), tuple(), kwargs=[]) - self.assertEqual(cm.exception.args[0], "3rd arg must be a dict") - - def test_SystemExit(self): - """ - Test invoking start_new_thread() with a function that raises - SystemExit. - The exception should be discarded. - """ - func = mock.Mock(side_effect=SystemExit()) - try: - _thread.start_new_thread(func, tuple()) - except SystemExit: - self.fail("start_new_thread raised SystemExit.") - - @mock.patch('traceback.print_exc') - def test_RaiseException(self, mock_print_exc): - """ - Test invoking start_new_thread() with a function that raises exception. - - The exception should be discarded and the traceback should be printed - via traceback.print_exc() - """ - func = mock.Mock(side_effect=Exception) - _thread.start_new_thread(func, tuple()) - self.assertTrue(mock_print_exc.called) - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_dummy_threading.py b/Lib/test/test_dummy_threading.py deleted file mode 100644 index a0c2972a60e..00000000000 --- a/Lib/test/test_dummy_threading.py +++ /dev/null @@ -1,60 +0,0 @@ -from test import support -import unittest -import dummy_threading as _threading -import time - -class DummyThreadingTestCase(unittest.TestCase): - - class TestThread(_threading.Thread): - - def run(self): - global running - global sema - global mutex - # Uncomment if testing another module, such as the real 'threading' - # module. - #delay = random.random() * 2 - delay = 0 - if support.verbose: - print('task', self.name, 'will run for', delay, 'sec') - sema.acquire() - mutex.acquire() - running += 1 - if support.verbose: - print(running, 'tasks are running') - mutex.release() - time.sleep(delay) - if support.verbose: - print('task', self.name, 'done') - mutex.acquire() - running -= 1 - if support.verbose: - print(self.name, 'is finished.', running, 'tasks are running') - mutex.release() - sema.release() - - def setUp(self): - self.numtasks = 10 - global sema - sema = _threading.BoundedSemaphore(value=3) - global mutex - mutex = _threading.RLock() - global running - running = 0 - self.threads = [] - - def test_tasks(self): - for i in range(self.numtasks): - t = self.TestThread(name=""%i) - self.threads.append(t) - t.start() - - if support.verbose: - print('waiting for all tasks to complete') - for t in self.threads: - t.join() - if support.verbose: - print('all tasks done') - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_dynamic.py b/Lib/test/test_dynamic.py index 948a2029f1e..1df010732c1 100644 --- a/Lib/test/test_dynamic.py +++ b/Lib/test/test_dynamic.py @@ -135,7 +135,7 @@ def test_eval_gives_lambda_custom_globals(self): self.assertEqual(foo(), 7) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailureIf(sys.getrecursionlimit() == 256, "TODO: RUSTPYTHON; default debug recursion limit is 256") @skip_wasi_stack_overflow() def test_load_global_specialization_failure_keeps_oparg(self): # https://github.com/python/cpython/issues/91625 diff --git a/Lib/test/test_email/test__header_value_parser.py b/Lib/test/test_email/test__header_value_parser.py index 8c9601288da..26e9249ba9e 100644 --- a/Lib/test/test_email/test__header_value_parser.py +++ b/Lib/test/test_email/test__header_value_parser.py @@ -1307,17 +1307,6 @@ def test_get_local_part_valid_and_invalid_qp_in_atom_list(self): '@example.com') self.assertEqual(local_part.local_part, r'\example\\ example') - def test_get_local_part_unicode_defect(self): - # Currently this only happens when parsing unicode, not when parsing - # stuff that was originally binary. - local_part = self._test_get_x(parser.get_local_part, - 'exámple@example.com', - 'exámple', - 'exámple', - [errors.NonASCIILocalPartDefect], - '@example.com') - self.assertEqual(local_part.local_part, 'exámple') - # get_dtext def test_get_dtext_only(self): @@ -3347,6 +3336,11 @@ def test_address_list_with_specials_in_encoded_word(self): 'A =?utf-8?q?v=C3=A9ry?= long name\n' ' containing =?utf-8?q?a=2C?= comma\n' ' \n'), + ('=?utf-8?Q?a=2C=20123456789012345678901234567890123456?=' + ' ', + '=?utf-8?q?a=2C?=\n' + ' 123456789012345678901234567890123456\n' + ' \n'), ] for (to, folded) in cases: with self.subTest(to=to): @@ -3462,10 +3456,12 @@ def test_fold_unfoldable_element_stealing_whitespace(self): self._test(token, expected, policy=policy) def test_encoded_word_with_undecodable_bytes(self): - self._test(parser.get_address_list( - ' =?utf-8?Q?=E5=AE=A2=E6=88=B6=E6=AD=A3=E8=A6=8F=E4=BA=A4=E7?=' + self._test( + parser.get_address_list( + ' =?utf-8?Q?=E5=AE=A2=E6=88=B6=E6=AD=A3=E8=A6=8F=E4=BA=A4=E7?=' + ' ' )[0], - ' =?unknown-8bit?b?5a6i5oi25q2j6KaP5Lqk5w==?=\n', + ' =?unknown-8bit?b?5a6i5oi25q2j6KaP5Lqk5w==?= \n', ) diff --git a/Lib/test/test_email/test_asian_codecs.py b/Lib/test/test_email/test_asian_codecs.py index 85979ffd816..59013f08719 100644 --- a/Lib/test/test_email/test_asian_codecs.py +++ b/Lib/test/test_email/test_asian_codecs.py @@ -83,15 +83,15 @@ def test_chinese_codecs(self): h.append(s, Charset('big5hkscs')) eq(h.encode(), """\ Chinese =?gb2312?b?1tDOxA==?= =?gbk?b?1tDOxA==?= =?gb18030?b?1tDOxA==?= - =?hz?b?fntWUE5Efn0=?= =?big5?b?pKSk5Q==?= =?big5hkscs?b?pKSk5Q==?=""") + =?hz-gb-2312?b?fntWUE5Efn0=?= =?big5?b?pKSk5Q==?= =?big5-hkscs?b?pKSk5Q==?=""") eq(decode_header(h.encode()), [(b'Chinese ', None), (b'\xd6\xd0\xce\xc4', 'gb2312'), (b'\xd6\xd0\xce\xc4', 'gbk'), (b'\xd6\xd0\xce\xc4', 'gb18030'), - (b'~{VPND~}', 'hz'), + (b'~{VPND~}', 'hz-gb-2312'), (b'\xa4\xa4\xa4\xe5', 'big5'), - (b'\xa4\xa4\xa4\xe5', 'big5hkscs'), + (b'\xa4\xa4\xa4\xe5', 'big5-hkscs'), ]) def test_korean_codecs(self): diff --git a/Lib/test/test_email/test_contentmanager.py b/Lib/test/test_email/test_contentmanager.py index dceb54f15e4..3115941f870 100644 --- a/Lib/test/test_email/test_contentmanager.py +++ b/Lib/test/test_email/test_contentmanager.py @@ -342,6 +342,66 @@ def test_set_text_charset_latin_1(self): self.assertEqual(m.get_payload(decode=True).decode('utf-8'), content) self.assertEqual(m.get_content(), content) + def test_set_text_charset_cp949(self): + m = self._make_message() + content = "\ud55c\uad6d\uc5b4\n\uac02\n" + raw_data_manager.set_content(m, content, charset='cp949') + self.assertEqual(str(m), textwrap.dedent("""\ + Content-Type: text/plain; charset="ks_c_5601-1987" + Content-Transfer-Encoding: base64 + + x9Gxub7uCoFBCg== + """)) + self.assertEqual(bytes(m), textwrap.dedent("""\ + Content-Type: text/plain; charset="ks_c_5601-1987" + Content-Transfer-Encoding: 8bit + + \ud55c\uad6d\uc5b4 + \uac02 + """).encode('ks_c_5601-1987')) + self.assertEqual(m.get_payload(decode=True), content.encode('ks_c_5601-1987')) + self.assertEqual(m.get_content(), content) + + def test_set_text_charset_shift_jis(self): + m = self._make_message() + content = "\u65e5\u672c\u8a9e\n" + raw_data_manager.set_content(m, content, charset='shift_jis') + self.assertEqual(m['Content-Type'], 'text/plain; charset="iso-2022-jp"') + self.assertEqual(m.get_payload(decode=True), content.encode('iso-2022-jp')) + self.assertEqual(m.get_content(), content) + self.assertEqual(str(m), textwrap.dedent("""\ + Content-Type: text/plain; charset="iso-2022-jp" + Content-Transfer-Encoding: 7bit + + \x1b$BF|K\\8l\x1b(B + """)) + self.assertEqual(bytes(m), textwrap.dedent("""\ + Content-Type: text/plain; charset="iso-2022-jp" + Content-Transfer-Encoding: 7bit + + \u65e5\u672c\u8a9e + """).encode('iso-2022-jp')) + + def test_set_text_charset_euc_jp(self): + m = self._make_message() + content = "\u65e5\u672c\u8a9e\n" + raw_data_manager.set_content(m, content, charset='euc-jp') + self.assertEqual(m['Content-Type'], 'text/plain; charset="iso-2022-jp"') + self.assertEqual(m.get_payload(decode=True), content.encode('iso-2022-jp')) + self.assertEqual(m.get_content(), content) + self.assertEqual(str(m), textwrap.dedent("""\ + Content-Type: text/plain; charset="iso-2022-jp" + Content-Transfer-Encoding: 7bit + + \x1b$BF|K\\8l\x1b(B + """)) + self.assertEqual(bytes(m), textwrap.dedent("""\ + Content-Type: text/plain; charset="iso-2022-jp" + Content-Transfer-Encoding: 7bit + + \u65e5\u672c\u8a9e + """).encode('iso-2022-jp')) + def test_set_text_plain_long_line_heuristics(self): m = self._make_message() content = ("Simple but long message that is over 78 characters" diff --git a/Lib/test/test_email/test_email.py b/Lib/test/test_email/test_email.py index ec0fb2fc2d9..cab641496b9 100644 --- a/Lib/test/test_email/test_email.py +++ b/Lib/test/test_email/test_email.py @@ -41,6 +41,7 @@ from test import support from test.support import threading_helper +from test.support import warnings_helper from test.support.os_helper import unlink from test.test_email import openfile, TestEmailBase @@ -4970,6 +4971,128 @@ def tearDown(self): except KeyError: pass + def test_attributes(self): + from email import charset + c = Charset() + self.assertEqual(c.input_charset, 'us-ascii') + self.assertEqual(c.header_encoding, None) + self.assertEqual(c.body_encoding, None) + self.assertEqual(c.output_charset, 'us-ascii') + self.assertEqual(c.input_codec, None) + self.assertEqual(c.output_codec, None) + + c = Charset('us-ascii') + self.assertEqual(c.input_charset, 'us-ascii') + self.assertEqual(c.header_encoding, None) + self.assertEqual(c.body_encoding, None) + self.assertEqual(c.output_charset, 'us-ascii') + self.assertEqual(c.input_codec, None) + self.assertEqual(c.output_codec, None) + + c = Charset('utf8') + self.assertEqual(c.input_charset, 'utf-8') + self.assertEqual(c.header_encoding, charset.SHORTEST) + self.assertEqual(c.body_encoding, charset.BASE64) + self.assertEqual(c.output_charset, 'utf-8') + self.assertEqual(c.input_codec, 'utf-8') + self.assertEqual(c.output_codec, 'utf-8') + + c = Charset('latin1') + self.assertEqual(c.input_charset, 'iso-8859-1') + self.assertEqual(c.header_encoding, charset.QP) + self.assertEqual(c.body_encoding, charset.QP) + self.assertEqual(c.output_charset, 'iso-8859-1') + self.assertEqual(c.input_codec, 'iso-8859-1') + self.assertEqual(c.output_codec, 'iso-8859-1') + + c = Charset('latin9') + self.assertEqual(c.input_charset, 'iso-8859-15') + self.assertEqual(c.header_encoding, charset.QP) + self.assertEqual(c.body_encoding, charset.QP) + self.assertEqual(c.output_charset, 'iso-8859-15') + self.assertEqual(c.input_codec, 'iso-8859-15') + self.assertEqual(c.output_codec, 'iso-8859-15') + + c = Charset('cyrillic') + self.assertEqual(c.input_charset, 'iso-8859-5') + self.assertEqual(c.header_encoding, charset.SHORTEST) + self.assertEqual(c.body_encoding, charset.BASE64) + self.assertEqual(c.output_charset, 'iso-8859-5') + self.assertEqual(c.input_codec, 'iso-8859-5') + self.assertEqual(c.output_codec, 'iso-8859-5') + + c = Charset('cp1251') + self.assertEqual(c.input_charset, 'windows-1251') + self.assertEqual(c.header_encoding, charset.SHORTEST) + self.assertEqual(c.body_encoding, charset.BASE64) + self.assertEqual(c.output_charset, 'windows-1251') + self.assertEqual(c.input_codec, 'windows-1251') + self.assertEqual(c.output_codec, 'windows-1251') + + c = Charset('cp1252') + self.assertEqual(c.input_charset, 'windows-1252') + self.assertEqual(c.header_encoding, charset.QP) + self.assertEqual(c.body_encoding, charset.QP) + self.assertEqual(c.output_charset, 'windows-1252') + self.assertEqual(c.input_codec, 'windows-1252') + self.assertEqual(c.output_codec, 'windows-1252') + + c = Charset('eucjp') + self.assertEqual(c.input_charset, 'euc-jp') + self.assertEqual(c.header_encoding, charset.BASE64) + self.assertEqual(c.body_encoding, None) + self.assertEqual(c.output_charset, 'iso-2022-jp') + self.assertEqual(c.input_codec, 'euc-jp') + self.assertEqual(c.output_codec, 'iso-2022-jp') + + c = Charset('cp949') + self.assertEqual(c.input_charset, 'ks_c_5601-1987') + self.assertEqual(c.header_encoding, charset.SHORTEST) + self.assertEqual(c.body_encoding, charset.BASE64) + self.assertEqual(c.output_charset, 'ks_c_5601-1987') + self.assertEqual(c.input_codec, 'ks_c_5601-1987') + self.assertEqual(c.output_codec, 'ks_c_5601-1987') + + c = Charset('gb2312') + self.assertEqual(c.input_charset, 'gb2312') + self.assertEqual(c.header_encoding, charset.BASE64) + self.assertEqual(c.body_encoding, charset.BASE64) + self.assertEqual(c.output_charset, 'gb2312') + self.assertEqual(c.input_codec, 'gb2312') + self.assertEqual(c.output_codec, 'gb2312') + + c = Charset('big5') + self.assertEqual(c.input_charset, 'big5') + self.assertEqual(c.header_encoding, charset.BASE64) + self.assertEqual(c.body_encoding, charset.BASE64) + self.assertEqual(c.output_charset, 'big5') + self.assertEqual(c.input_codec, 'big5') + self.assertEqual(c.output_codec, 'big5') + + def test_user_charsets(self): + from email import charset + c = Charset('fake0') + self.assertEqual(c.input_charset, 'fake0') + self.assertEqual(c.header_encoding, charset.SHORTEST) + self.assertEqual(c.body_encoding, charset.BASE64) + self.assertEqual(c.output_charset, 'fake0') + self.assertEqual(c.input_codec, 'fake0') + self.assertEqual(c.output_codec, 'fake0') + + charset.add_alias('fake1', 'mime-fake') + charset.add_alias('output-mime-fake', 'output-mime-fake-alias') + charset.add_codec('mime-fake', 'fakecodec') + charset.add_codec('output-mime-fake-alias', 'outputfakecodec') + charset.add_charset('mime-fake', charset.QP, None, 'output-mime-fake') + + c = Charset('fake1') + self.assertEqual(c.input_charset, 'mime-fake') + self.assertEqual(c.header_encoding, charset.QP) + self.assertEqual(c.body_encoding, None) + self.assertEqual(c.output_charset, 'output-mime-fake-alias') + self.assertEqual(c.input_codec, 'fakecodec') + self.assertEqual(c.output_codec, 'outputfakecodec') + def test_codec_encodeable(self): eq = self.assertEqual # Make sure us-ascii = no Unicode conversion @@ -5010,6 +5133,11 @@ def test_unicode_charset_name(self): self.assertEqual(str(charset), 'us-ascii') self.assertRaises(errors.CharsetError, Charset, 'asc\xffii') + def test_bytes_charset_name(self): + charset = Charset(b'us-ascii') + self.assertEqual(str(charset), 'us-ascii') + self.assertRaises(errors.CharsetError, Charset, b'asc\xffii') + # Test multilingual MIME headers. @@ -5653,7 +5781,8 @@ def test_rfc2231_bad_character_in_encoding(self): """ msg = email.message_from_string(m) - self.assertEqual(msg.get_filename(), 'myfile.txt') + with warnings_helper.check_warnings(('', DeprecationWarning)): + self.assertEqual(msg.get_filename(), 'myfile.txt') def test_rfc2231_single_tick_in_filename_extended(self): eq = self.assertEqual diff --git a/Lib/test/test_email/test_generator.py b/Lib/test/test_email/test_generator.py index 3c9a86f3e8c..8d912738029 100644 --- a/Lib/test/test_email/test_generator.py +++ b/Lib/test/test_email/test_generator.py @@ -1,4 +1,5 @@ import io +import re import textwrap import unittest import random @@ -295,6 +296,69 @@ def test_keep_long_encoded_newlines(self): g.flatten(msg) self.assertEqual(s.getvalue(), self.typ(expected)) + def test_non_ascii_addr_spec_raises(self): + # non-ascii is not permitted in any part of an addr-spec. If the + # programmer generated it, it's an error. (See also + # test_non_ascii_addr_spec_preserved below.) + p = self.policy.clone(utf8=False, max_line_length=20) + g = self.genclass(self.ioclass(), policy=p) + # XXX The particular part detected here isn't part of a behavioral + # spec and may change in the future. + cases = [ + ('wők@example.com', 'wők', 'local-part'), + ('wok@exàmple.com', 'exàmple.com', 'domain'), + ('wők@exàmple.com', 'wők', 'local-part'), + ( + '"Name, for display" ', + 'wők@example.com', + 'addr-spec', + ), + ( + 'Näyttönimi ', + 'wők@example.com', + 'addr-spec', + ), + ( + '"a lőng quoted string as the local part"@example.com', + 'a lőng quoted string as the local part', + 'local-part', + ), + + ] + for address, badtoken, partname in cases: + with self.subTest(address=address): + msg = EmailMessage() + msg['To'] = address + expected_error = ( + fr"(?i)(?=.*non-ascii)" + fr"(?=.*{re.escape(badtoken)})" + fr"(?=.*{partname})" + fr"(?=.*policy.*utf8)" + ) + with self.assertRaisesRegex( + email.errors.HeaderWriteError, expected_error + ): + g.flatten(msg) + + def test_local_part_quoted_string_wrapped_correctly(self): + msg = self.msgmaker(self.typ(textwrap.dedent("""\ + To: <"a long local part in a quoted string"@example.com> + Subject: test + + None + """)), policy=self.policy.clone(max_line_length=20)) + expected = textwrap.dedent("""\ + To: <"a long local part in a + quoted string"@example.com> + Subject: test + + None + """) + s = self.ioclass() + g = self.genclass(s, policy=self.policy.clone(max_line_length=30)) + g.flatten(msg) + self.assertEqual(s.getvalue(), self.typ(expected)) + def _test_boundary_detection(self, linesep): # Generate a boundary token in the same way as _make_boundary token = random.randrange(sys.maxsize) @@ -515,12 +579,12 @@ def test_cte_type_7bit_transforms_8bit_cte(self): def test_smtputf8_policy(self): msg = EmailMessage() - msg['From'] = "Páolo " + msg['From'] = "Páolo " msg['To'] = 'Dinsdale' msg['Subject'] = 'Nudge nudge, wink, wink \u1F609' msg.set_content("oh là là, know what I mean, know what I mean?") expected = textwrap.dedent("""\ - From: Páolo + From: Páolo To: Dinsdale Subject: Nudge nudge, wink, wink \u1F609 Content-Type: text/plain; charset="utf-8" @@ -555,6 +619,37 @@ def test_smtp_policy(self): g.flatten(msg) self.assertEqual(s.getvalue(), expected) + def test_non_ascii_addr_spec_preserved(self): + # A defective non-ASCII addr-spec parsed from the original + # message is left unchanged when flattening. + # (See also test_non_ascii_addr_spec_raises above.) + source = ( + 'To: jörg@example.com, "But a long name still works with refold_source" ' + ).encode() + expected = ( + b'To: j\xc3\xb6rg@example.com,\n' + b' "But a long name still works with refold_source" \n' + b'\n' + ) + msg = message_from_bytes(source, policy=policy.default) + s = io.BytesIO() + g = BytesGenerator(s, policy=policy.default) + g.flatten(msg) + self.assertEqual(s.getvalue(), expected) + + def test_idna_encoding_preserved(self): + # Nothing tries to decode a pre-encoded IDNA domain. + msg = EmailMessage() + msg["To"] = Address( + username='jörg', + domain='☕.example'.encode('idna').decode() # IDNA 2003 + ) + expected = 'To: jörg@xn--53h.example\n\n'.encode() + s = io.BytesIO() + g = BytesGenerator(s, policy=policy.default.clone(utf8=True)) + g.flatten(msg) + self.assertEqual(s.getvalue(), expected) + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_email/test_headerregistry.py b/Lib/test/test_email/test_headerregistry.py index a173b8b2512..c118fd5e20d 100644 --- a/Lib/test/test_email/test_headerregistry.py +++ b/Lib/test/test_email/test_headerregistry.py @@ -8,6 +8,7 @@ from email import headerregistry from email.headerregistry import Address, Group from test.support import ALWAYS_EQ +from test.support import warnings_helper DITTO = object() @@ -165,6 +166,7 @@ def string_as_value(self, } + @parameterize class TestDateHeader(TestHeaderBase): @@ -254,7 +256,15 @@ def content_type_as_value(self, decoded = args[2] if l>2 and args[2] is not DITTO else source header = 'Content-Type:' + ' ' if source else '' folded = args[3] if l>3 else header + decoded + '\n' - h = self.make_header('Content-Type', source) + # Both rfc2231 test cases with utf-8%E2%80%9D raise warnings, + # clear encoding cache to ensure test isolation. + if 'utf-8%E2%80%9D' in source and 'ascii' not in source: + import encodings + encodings._cache.clear() + with warnings_helper.check_warnings(('', DeprecationWarning)): + h = self.make_header('Content-Type', source) + else: + h = self.make_header('Content-Type', source) self.assertEqual(h.content_type, content_type) self.assertEqual(h.maintype, maintype) self.assertEqual(h.subtype, subtype) @@ -1541,17 +1551,19 @@ def test_quoting(self): self.assertEqual(str(a), '"Sara J." <"bad name"@example.com>') def test_il8n(self): - a = Address('Éric', 'wok', 'exàmple.com') + a = Address('Éric', 'wők', 'exàmple.com') self.assertEqual(a.display_name, 'Éric') - self.assertEqual(a.username, 'wok') + self.assertEqual(a.username, 'wők') self.assertEqual(a.domain, 'exàmple.com') - self.assertEqual(a.addr_spec, 'wok@exàmple.com') - self.assertEqual(str(a), 'Éric ') + self.assertEqual(a.addr_spec, 'wők@exàmple.com') + self.assertEqual(str(a), 'Éric ') - # XXX: there is an API design issue that needs to be solved here. - #def test_non_ascii_username_raises(self): - # with self.assertRaises(ValueError): - # Address('foo', 'wők', 'example.com') + def test_i18n_in_addr_spec(self): + a = Address(addr_spec='wők@exàmple.com') + self.assertEqual(a.username, 'wők') + self.assertEqual(a.domain, 'exàmple.com') + self.assertEqual(a.addr_spec, 'wők@exàmple.com') + self.assertEqual(str(a), 'wők@exàmple.com') def test_crlf_in_constructor_args_raises(self): cases = ( @@ -1572,10 +1584,6 @@ def test_crlf_in_constructor_args_raises(self): with self.subTest(kwargs=kwargs), self.assertRaisesRegex(ValueError, "invalid arguments"): Address(**kwargs) - def test_non_ascii_username_in_addr_spec_raises(self): - with self.assertRaises(ValueError): - Address('foo', addr_spec='wők@example.com') - def test_address_addr_spec_and_username_raises(self): with self.assertRaises(TypeError): Address('foo', username='bing', addr_spec='bar@baz') diff --git a/Lib/test/test_email/test_message.py b/Lib/test/test_email/test_message.py index 56ad446694d..974b0ceaafb 100644 --- a/Lib/test/test_email/test_message.py +++ b/Lib/test/test_email/test_message.py @@ -1081,6 +1081,25 @@ def test_get_body_malformed(self): # AttributeError: 'str' object has no attribute 'is_attachment' m.get_body() + def test_get_body_malformed_nested_multipart(self): + # gh-159304: a nested multipart part without a boundary has a + # string payload, which get_body() must not iterate over. + msg = textwrap.dedent("""\ + From: sender@example.com + To: receiver@example.com + Subject: Malformed + Content-Type: multipart/related; boundary=OUTER + + --OUTER + Content-Type: multipart/related + + raw body no boundary + --OUTER-- + """) + m = self._str_msg(msg) + self.assertIsNone(m.get_body(('plain', 'html'))) + self.assertIs(m.get_body(('related',)), m) + def test_get_bytes_payload_with_quoted_printable_encoding(self): # We use a memoryview to avoid directly changing the private payload # and to prevent using the dedicated paths for string or bytes objects. diff --git a/Lib/test/test_embed.py b/Lib/test/test_embed.py index a4a328aa3dd..420eb7e8c2c 100644 --- a/Lib/test/test_embed.py +++ b/Lib/test/test_embed.py @@ -68,6 +68,9 @@ if not os.path.isfile(os.path.join(STDLIB_INSTALL, 'os.py')): STDLIB_INSTALL = None +CODE_EXITCODE_123 = 'raise SystemExit(123)' + + def debug_build(program): program = os.path.basename(program) name = os.path.splitext(program)[0] @@ -117,12 +120,16 @@ def run_embedded_interpreter(self, *args, env=None, env = env.copy() env['SYSTEMROOT'] = os.environ['SYSTEMROOT'] - p = subprocess.Popen(cmd, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - universal_newlines=True, - env=env, - cwd=cwd) + kwargs = dict( + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + universal_newlines=True, + env=env, + cwd=cwd, + ) + if input is not None: + kwargs['stdin'] = subprocess.PIPE + p = subprocess.Popen(cmd, **kwargs) try: (out, err) = p.communicate(input=input, timeout=timeout) except: @@ -239,6 +246,17 @@ def test_repeated_init_and_inittab(self): lines = "\n".join(lines) + "\n" self.assertEqual(out, lines) + def test_create_module_from_initfunc(self): + out, err = self.run_embedded_interpreter("test_create_module_from_initfunc") + self.assertEqual(self._nogil_filtered_err(err, "embedded_ext"), "") + self.assertEqual(out, + "\n" + "my_test_extension.executed='yes'\n" + "my_test_extension.exec_slot_ran='yes'\n" + "\n" + "embedded_ext.executed='yes'\n" + ) + def test_inittab_submodule_multiphase(self): out, err = self.run_embedded_interpreter("test_inittab_submodule_multiphase") self.assertEqual(err, "") @@ -316,7 +334,7 @@ def test_pre_initialization_api(self): if MS_WINDOWS: expected_path = self.test_exe else: - expected_path = os.path.join(os.getcwd(), "spam") + expected_path = os.path.join(os.getcwd(), "_testembed") expected_output = f"sys.executable: {expected_path}\n" self.assertIn(expected_output, out) self.assertEqual(err, '') @@ -554,6 +572,55 @@ def _nogil_filtered_err(err: str, mod_name: str) -> str: ] return "\n".join(filtered_err_lines) + def check_program_exitcode(self, *args, check_stderr=True, **kwargs): + out, err = self.run_embedded_interpreter(*args, **kwargs) + self.assertEqual(out.rstrip(), 'ok! Py_RunMain() returned 123') + if check_stderr: + self.assertEqual(err, '') + + def test_init_run_main_code_exitcode(self): + code = CODE_EXITCODE_123 + self.check_program_exitcode("test_init_run_main_code_exitcode", code) + + def test_init_run_main_script_exitcode(self): + with tempfile.TemporaryDirectory() as tmpdir: + filename = os.path.join(tmpdir, 'script.py') + with open(filename, 'w') as fp: + fp.write(CODE_EXITCODE_123) + + self.check_program_exitcode("test_init_run_main_script_exitcode", + filename) + + def test_init_run_main_interactive_exitcode(self): + code = CODE_EXITCODE_123 + self.check_program_exitcode("test_init_run_main_interactive_exitcode", + input=code, + check_stderr=False) + + def test_init_run_main_startup_exitcode(self): + with tempfile.TemporaryDirectory() as tmpdir: + filename = os.path.join(tmpdir, 'startup.py') + with open(filename, 'x') as fp: + fp.write(CODE_EXITCODE_123) + + env = dict(os.environ) + env['PYTHONSTARTUP'] = filename + self.check_program_exitcode("test_init_run_main_interactive_exitcode", + env=env, + check_stderr=False) + + def test_init_run_main_module_exitcode(self): + with tempfile.TemporaryDirectory() as tmpdir: + modname = '_testembed_testmodule' + filename = os.path.join(tmpdir, modname + '.py') + with open(filename, 'x', encoding='utf8') as fp: + fp.write(CODE_EXITCODE_123) + + env = dict(os.environ) + env['PYTHONPATH'] = tmpdir + self.check_program_exitcode("test_init_run_main_module_exitcode", + modname, env=env) + def config_dev_mode(preconfig, config): preconfig['allocator'] = PYMEM_ALLOCATOR_DEBUG @@ -581,7 +648,7 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase): 'configure_locale': True, 'coerce_c_locale': False, 'coerce_c_locale_warn': False, - 'utf8_mode': False, + 'utf8_mode': True, } if MS_WINDOWS: PRE_CONFIG_COMPAT.update({ @@ -598,7 +665,7 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase): configure_locale=False, isolated=True, use_environment=False, - utf8_mode=False, + utf8_mode=True, dev_mode=False, coerce_c_locale=False, ) @@ -624,6 +691,7 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase): 'tracemalloc': 0, 'perf_profiling': 0, 'import_time': 0, + 'lazy_imports': -1, 'thread_inherit_context': DEFAULT_THREAD_INHERIT_CONTEXT, 'context_aware_warnings': DEFAULT_CONTEXT_AWARE_WARNINGS, 'code_debug_ranges': True, @@ -631,6 +699,7 @@ class InitConfigTests(EmbeddingTestsMixin, unittest.TestCase): 'dump_refs': False, 'dump_refs_file': None, 'malloc_stats': False, + 'pymalloc_hugepages': False, 'filesystem_encoding': GET_DEFAULT_CONFIG, 'filesystem_errors': GET_DEFAULT_CONFIG, @@ -843,12 +912,6 @@ def get_expected_config(self, expected_preconfig, expected, 'stdio_encoding', 'stdio_errors'): expected[key] = self.IGNORE_CONFIG - if not expected_preconfig['configure_locale']: - # UTF-8 Mode depends on the locale. There is no easy way - # to guess if UTF-8 Mode will be enabled or not if the locale - # is not configured. - expected_preconfig['utf8_mode'] = self.IGNORE_CONFIG - if expected_preconfig['utf8_mode'] == 1: if expected['filesystem_encoding'] is self.GET_DEFAULT_CONFIG: expected['filesystem_encoding'] = 'utf-8' @@ -1007,7 +1070,6 @@ def test_init_global_config(self): 'utf8_mode': True, } config = { - 'program_name': './globalvar', 'site_import': False, 'bytes_warning': True, 'warnoptions': ['default::BytesWarning'], @@ -1040,6 +1102,7 @@ def test_init_from_config(self): 'code_debug_ranges': False, 'show_ref_count': True, 'malloc_stats': True, + 'pymalloc_hugepages': True, 'stdio_encoding': 'iso8859-1', 'stdio_errors': 'replace', @@ -1105,6 +1168,7 @@ def test_init_compat_env(self): 'import_time': 1, 'code_debug_ranges': False, 'malloc_stats': True, + 'pymalloc_hugepages': True, 'inspect': True, 'optimization_level': 2, 'pythonpath_env': '/my/path', @@ -1141,6 +1205,7 @@ def test_init_python_env(self): 'import_time': 1, 'code_debug_ranges': False, 'malloc_stats': True, + 'pymalloc_hugepages': True, 'inspect': True, 'optimization_level': 2, 'pythonpath_env': '/my/path', @@ -1277,21 +1342,6 @@ def test_init_dont_configure_locale(self): self.check_all_configs("test_init_dont_configure_locale", {}, preconfig, api=API_PYTHON) - @unittest.skip('as of 3.11 this test no longer works because ' - 'path calculations do not occur on read') - def test_init_read_set(self): - config = { - 'program_name': './init_read_set', - 'executable': 'my_executable', - 'base_executable': 'my_executable', - } - def modify_path(path): - path.insert(1, "test_path_insert1") - path.append("test_path_append") - self.check_all_configs("test_init_read_set", config, - api=API_PYTHON, - modify_path_cb=modify_path) - def test_init_sys_add(self): config = { 'faulthandler': 1, @@ -1325,6 +1375,24 @@ def test_init_run_main(self): } self.check_all_configs("test_init_run_main", config, api=API_PYTHON) + def test_init_main(self): + code = ('import _testinternalcapi, json; ' + 'print(json.dumps(_testinternalcapi.get_configs()))') + config = { + 'argv': ['-c', 'arg2'], + 'orig_argv': ['python3', + '-c', code, + 'arg2'], + 'program_name': './python3', + 'run_command': code + '\n', + 'parse_argv': True, + '_init_main': False, + 'sys_path_0': '', + } + self.check_all_configs("test_init_main", config, + api=API_PYTHON, + stderr="Run Python code before _Py_InitializeMain") + def test_init_parse_argv(self): config = { 'parse_argv': True, @@ -1417,7 +1485,7 @@ def module_search_paths(self, prefix=None, exec_prefix=None): if prefix is None: prefix = config['config']['prefix'] if exec_prefix is None: - exec_prefix = config['config']['prefix'] + exec_prefix = config['config']['exec_prefix'] if MS_WINDOWS: return config['config']['module_search_paths'] else: @@ -1497,8 +1565,12 @@ def test_init_setpythonhome(self): } self.default_program_name(config) env = {'TESTHOME': home, 'PYTHONPATH': paths_str} + # When running from source, TESTHOME will be the build directory, which + # isn't a valid home unless _is_python_build is set. getpath will then + # fail to find the standard library and show a warning, so we need to + # ignore stderr. self.check_all_configs("test_init_setpythonhome", config, - api=API_COMPAT, env=env) + api=API_COMPAT, env=env, ignore_stderr=True) def test_init_is_python_build_with_home(self): # Test _Py_path_config._is_python_build configuration (gh-91985) @@ -1534,15 +1606,26 @@ def test_init_is_python_build_with_home(self): 'exec_prefix': exec_prefix, 'base_exec_prefix': exec_prefix, 'pythonpath_env': paths_str, - 'stdlib_dir': stdlib, + 'stdlib_dir': stdlib, # Only correct on _is_python_build==0! } # The code above is taken from test_init_setpythonhome() env = {'TESTHOME': home, 'PYTHONPATH': paths_str} env['NEGATIVE_ISPYTHONBUILD'] = '1' config['_is_python_build'] = 0 + # This configuration doesn't set a valid stdlibdir/plststdlibdir because + # with _is_python_build=0 getpath doesn't check for the build directory + # landmarks in PYTHONHOME/Py_SetPythonHome. + # getpath correctly shows a warning, which messes up check_all_configs, + # so we need to ignore stderr. self.check_all_configs("test_init_is_python_build", config, - api=API_COMPAT, env=env) + api=API_COMPAT, env=env, ignore_stderr=True) + + # config['stdlib_dir'] = os.path.join(home, 'Lib') + # FIXME: This test does not check if stdlib_dir is calculated correctly. + # test_init_is_python_build runs the initialization twice, + # setting stdlib_dir in _Py_path_config on the first run, which + # then overrides the stdlib_dir calculation (as of GH-108730). env['NEGATIVE_ISPYTHONBUILD'] = '0' config['_is_python_build'] = 1 @@ -1551,14 +1634,22 @@ def test_init_is_python_build_with_home(self): expected_paths[1 if MS_WINDOWS else 2] = os.path.normpath( os.path.join(exedir, f'{f.read()}\n$'.splitlines()[0])) if not MS_WINDOWS: - # PREFIX (default) is set when running in build directory - prefix = exec_prefix = sys.prefix + # PREFIX and EXEC_PREFIX (defaults) are set when running in the + # build directory and may differ with --exec-prefix (gh-151096). + prefix = sys.prefix + exec_prefix = sys.exec_prefix # stdlib calculation (/Lib) is not yet supported expected_paths[0] = self.module_search_paths(prefix=prefix)[0] config.update(prefix=prefix, base_prefix=prefix, exec_prefix=exec_prefix, base_exec_prefix=exec_prefix) + # This also shows the bad stdlib warning, getpath is run twice. The + # first time with _is_python_build=0, which results in the warning just + # as explained above. However, the second time a valid standard library + # should be found, but the stdlib_dir is cached in _Py_path_config from + # the first run, which ovewrites it, so it also shows the warning. + # Also ignore stderr. self.check_all_configs("test_init_is_python_build", config, - api=API_COMPAT, env=env) + api=API_COMPAT, env=env, ignore_stderr=True) def copy_paths_by_env(self, config): all_configs = self._get_expected_config() @@ -1618,6 +1709,7 @@ def test_init_pybuilddir_win32(self): prefix = os.path.normpath(os.path.join(tmpdir, vpath)) # The stdlib dir is dirname(executable) + VPATH + 'Lib' stdlibdir = os.path.normpath(os.path.join(tmpdir, vpath, 'Lib')) + os.mkdir(stdlibdir) filename = os.path.join(tmpdir, 'pybuilddir.txt') with open(filename, "w", encoding="utf8") as fp: @@ -1896,6 +1988,12 @@ def test_init_in_background_thread(self): out, err = self.run_embedded_interpreter("test_init_in_background_thread") self.assertEqual(err, "") + def test_isinitialized_false_during_site_import(self): + # gh-146302: Py_IsInitialized() must not return true during site import. + out, err = self.run_embedded_interpreter( + "test_isinitialized_false_during_site_import") + self.assertEqual(err, "") + class AuditingTests(EmbeddingTestsMixin, unittest.TestCase): def test_open_code_hook(self): @@ -1953,6 +2051,21 @@ def test_audit_run_stdin(self): def test_get_incomplete_frame(self): self.run_embedded_interpreter("test_get_incomplete_frame") + def test_gilstate_after_finalization(self): + self.run_embedded_interpreter("test_gilstate_after_finalization") + + def test_thread_state_ensure(self): + self.run_embedded_interpreter("test_thread_state_ensure") + + def test_main_interpreter_view(self): + self.run_embedded_interpreter("test_main_interpreter_view") + + def test_thread_state_ensure_from_view(self): + self.run_embedded_interpreter("test_thread_state_ensure_from_view") + + def test_concurrent_finalization_stress(self): + self.run_embedded_interpreter("test_concurrent_finalization_stress") + class MiscTests(EmbeddingTestsMixin, unittest.TestCase): def test_unicode_id_init(self): @@ -2013,7 +2126,7 @@ def test_no_memleak(self): def test_presite(self): cmd = [ sys.executable, - "-I", "-X", "presite=test._test_embed_structseq", + "-I", "-X", "presite=test._test_embed_structseq:main", "-c", "print('unique-python-message')", ] proc = subprocess.run( diff --git a/Lib/test/test_ensurepip.py b/Lib/test/test_ensurepip.py index a8bfbcd4abc..20a56ed715d 100644 --- a/Lib/test/test_ensurepip.py +++ b/Lib/test/test_ensurepip.py @@ -13,6 +13,12 @@ import ensurepip._uninstall +if sys.implementation.cache_tag is None: + COMPILE_OPT = ["--no-compile"] +else: + COMPILE_OPT = [] + + class TestPackages(unittest.TestCase): def touch(self, directory, filename): fullname = os.path.join(directory, filename) @@ -70,6 +76,11 @@ def setUp(self): self.run_pip.return_value = 0 self.addCleanup(run_pip_patch.stop) + # Allow testing on zlib-less platforms by avoiding the check for zlib in _bootstrap() + zlib_patch = unittest.mock.patch.dict('sys.modules', {'zlib': unittest.mock.MagicMock()}) + zlib_patch.start() + self.addCleanup(zlib_patch.stop) + # Avoid side effects on the actual os module real_devnull = os.devnull os_patch = unittest.mock.patch("ensurepip.os") @@ -90,7 +101,7 @@ def test_basic_bootstrapping(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "pip", + unittest.mock.ANY, *COMPILE_OPT, "pip", ], unittest.mock.ANY, ) @@ -104,7 +115,7 @@ def test_bootstrapping_with_root(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "--root", "/foo/bar/", + unittest.mock.ANY, "--root", "/foo/bar/", *COMPILE_OPT, "pip", ], unittest.mock.ANY, @@ -116,7 +127,7 @@ def test_bootstrapping_with_user(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "--user", "pip", + unittest.mock.ANY, "--user", *COMPILE_OPT, "pip", ], unittest.mock.ANY, ) @@ -127,7 +138,7 @@ def test_bootstrapping_with_upgrade(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "--upgrade", "pip", + unittest.mock.ANY, "--upgrade", *COMPILE_OPT, "pip", ], unittest.mock.ANY, ) @@ -138,7 +149,7 @@ def test_bootstrapping_with_verbosity_1(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "-v", "pip", + unittest.mock.ANY, "-v", *COMPILE_OPT, "pip", ], unittest.mock.ANY, ) @@ -149,7 +160,7 @@ def test_bootstrapping_with_verbosity_2(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "-vv", "pip", + unittest.mock.ANY, "-vv", *COMPILE_OPT, "pip", ], unittest.mock.ANY, ) @@ -160,7 +171,7 @@ def test_bootstrapping_with_verbosity_3(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "-vvv", "pip", + unittest.mock.ANY, "-vvv", *COMPILE_OPT, "pip", ], unittest.mock.ANY, ) @@ -195,6 +206,16 @@ def test_pip_config_file_disabled(self): ensurepip.bootstrap() self.assertEqual(self.os_environ["PIP_CONFIG_FILE"], os.devnull) + def test_missing_zlib(self): + with unittest.mock.patch.dict('sys.modules', {'zlib': None}): + with self.assertRaises(ModuleNotFoundError) as cm: + ensurepip.bootstrap() + + error_msg = str(cm.exception) + self.assertIn("ensurepip requires the standard library module 'zlib'", error_msg) + + self.assertFalse(self.run_pip.called) + @contextlib.contextmanager def fake_pip(version=ensurepip.version()): if version is None: @@ -307,7 +328,7 @@ def test_basic_bootstrapping(self): self.run_pip.assert_called_once_with( [ "install", "--no-cache-dir", "--no-index", "--find-links", - unittest.mock.ANY, "pip", + unittest.mock.ANY, *COMPILE_OPT, "pip", ], unittest.mock.ANY, ) diff --git a/Lib/test/test_enum.py b/Lib/test/test_enum.py index 57981ccc71b..e0dcc6b8a51 100644 --- a/Lib/test/test_enum.py +++ b/Lib/test/test_enum.py @@ -1002,12 +1002,18 @@ class OpenAB(self.enum_type): self.assertIs(~(A|B), OpenAB(252)) self.assertIs(~AB_MASK, OpenAB(0)) self.assertIs(~OpenAB(0), AB_MASK) + self.assertIs(OpenAB(~4), OpenAB(251)) else: self.assertIs(~A, B) self.assertIs(~B, A) + self.assertIs(OpenAB(~1), B) + self.assertIs(OpenAB(~2), A) self.assertIs(~(A|B), OpenAB(0)) self.assertIs(~AB_MASK, OpenAB(0)) self.assertIs(~OpenAB(0), (A|B)) + self.assertIs(OpenAB(~3), OpenAB(0)) + self.assertIs(OpenAB(~4), OpenAB(3)) + self.assertIs(OpenAB(~33), B) # class OpenXYZ(self.enum_type): X = 4 @@ -1031,6 +1037,9 @@ class OpenXYZ(self.enum_type): self.assertIs(~X, Y|Z) self.assertIs(~Y, X|Z) self.assertIs(~Z, X|Y) + self.assertIs(OpenXYZ(~4), Y|Z) + self.assertIs(OpenXYZ(~2), X|Z) + self.assertIs(OpenXYZ(~1), X|Y) self.assertIs(~(X|Y), Z) self.assertIs(~(X|Z), Y) self.assertIs(~(Y|Z), X) @@ -1038,6 +1047,28 @@ class OpenXYZ(self.enum_type): self.assertIs(~XYZ_MASK, OpenXYZ(0)) self.assertTrue(~OpenXYZ(0), (X|Y|Z)) + def test_assigned_negative_value(self): + class X(self.enum_type): + A = auto() + B = auto() + C = A | B + D = ~A + self.assertEqual(list(X), [X.A, X.B]) + self.assertIs(~X.A, X.B) + self.assertIs(X.D, X.B) + self.assertEqual(X.D.value, 2) + # + class Y(self.enum_type): + A = auto() + B = auto() + C = A | B + D = ~A + E = auto() + self.assertEqual(list(Y), [Y.A, Y.B, Y.E]) + self.assertIs(~Y.A, Y.B|Y.E) + self.assertIs(Y.D, Y.B|Y.E) + self.assertEqual(Y.D.value, 6) + class TestPlainEnumClass(_EnumTests, _PlainOutputTests, unittest.TestCase): enum_type = Enum @@ -1748,7 +1779,6 @@ class ThreePart(Enum): self.assertIs(ThreePart((3, 3.0, 'three')), ThreePart.THREE) self.assertIs(ThreePart(3, 3.0, 'three'), ThreePart.THREE) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: is not @reraise_if_not_enum(IntStooges) def test_intenum_from_bytes(self): self.assertIs(IntStooges.from_bytes(b'\x00\x03', 'big'), IntStooges.MOE) @@ -3036,7 +3066,6 @@ class ThirdFailedStrEnum(StrEnum): one = '1' two = b'2', 'ascii', 9 - @unittest.expectedFailure # TODO: RUSTPYTHON; fails on encoding testing : TypeError: Expected type 'str' but 'builtin_function_or_method' found def test_custom_strenum(self): class CustomStrEnum(str, Enum): pass @@ -3682,6 +3711,8 @@ class SkipFlag(enum.Flag): C = 4 | B # self.assertTrue(SkipFlag.C in (SkipFlag.A|SkipFlag.C)) + self.assertTrue(SkipFlag.B in SkipFlag.C) + self.assertIs(SkipFlag(~1), SkipFlag.B) self.assertRaisesRegex(ValueError, 'SkipFlag.. invalid value 42', SkipFlag, 42) # class SkipIntFlag(enum.IntFlag): @@ -3690,6 +3721,8 @@ class SkipIntFlag(enum.IntFlag): C = 4 | B # self.assertTrue(SkipIntFlag.C in (SkipIntFlag.A|SkipIntFlag.C)) + self.assertTrue(SkipIntFlag.B in SkipIntFlag.C) + self.assertIs(SkipIntFlag(~1), SkipIntFlag.B|SkipIntFlag.C) self.assertEqual(SkipIntFlag(42).value, 42) # class MethodHint(Flag): @@ -4729,6 +4762,8 @@ class Color(Flag): BLUE = 4 WHITE = -1 # no error means success + self.assertEqual(list(Color.WHITE), [Color.RED, Color.GREEN, Color.BLUE]) + self.assertEqual(Color.WHITE.value, 7) class TestInternals(unittest.TestCase): @@ -4852,7 +4887,7 @@ class Color(Enum): def _generate_next_value_(name, start, count, last): return name - def test_auto_order_wierd(self): + def test_auto_order_weird(self): weird_auto = auto() weird_auto.value = 'pathological case' class Color(Enum): @@ -5289,7 +5324,7 @@ def __new__(cls, value, label): class MiscTestCase(unittest.TestCase): def test__all__(self): - support.check__all__(self, enum, not_exported={'bin', 'show_flag_values'}) + support.check__all__(self, enum) @cpython_only def test_lazy_import(self): @@ -5494,12 +5529,16 @@ def test_enum_dict_standalone(self): # helpers def enum_dir(cls): + if issubclass(cls, Flag): + members = list(cls._member_map_.keys()) + else: + members = cls._member_names_ interesting = set([ '__class__', '__contains__', '__doc__', '__getitem__', '__iter__', '__len__', '__members__', '__module__', '__name__', '__qualname__', ] - + cls._member_names_ + + members ) if cls._new_member_ is not object.__new__: interesting.add('__new__') diff --git a/Lib/test/test_epoll.py b/Lib/test/test_epoll.py index c94946a6ae6..51405ca7c9e 100644 --- a/Lib/test/test_epoll.py +++ b/Lib/test/test_epoll.py @@ -25,6 +25,7 @@ import os import select import socket +import sys import time import unittest from test import support @@ -52,12 +53,11 @@ def tearDown(self): def _connected_pair(self): client = socket.socket() client.setblocking(False) + # The connection is either established immediately or in progress. try: client.connect(('127.0.0.1', self.serverSocket.getsockname()[1])) except OSError as e: self.assertEqual(e.args[0], errno.EINPROGRESS) - else: - raise AssertionError("Connect should have raised EINPROGRESS") server, addr = self.serverSocket.accept() self.connections.extend((client, server)) @@ -218,6 +218,9 @@ def test_errors(self): self.assertRaises(ValueError, select.epoll().register, -1, select.EPOLLIN) + @unittest.skipIf(sys.platform.startswith('sunos'), + 'unregistering a closed file descriptor succeeds ' + 'on Solaris') def test_unregister_closed(self): server, client = self._connected_pair() fd = server.fileno() @@ -259,6 +262,15 @@ def test_close(self): self.assertRaises(ValueError, epoll.register, fd, select.EPOLLIN) self.assertRaises(ValueError, epoll.unregister, fd) + def test_close_error(self): + # gh-146205: close() should raise OSError if underlying fd is invalid + epoll = select.epoll() + fd = epoll.fileno() + os.close(fd) + with self.assertRaises(OSError) as cm: + epoll.close() + self.assertEqual(cm.exception.errno, errno.EBADF) + def test_fd_non_inheritable(self): epoll = select.epoll() self.addCleanup(epoll.close) diff --git a/Lib/test/test_exception_group.py b/Lib/test/test_exception_group.py index db6ff9d33b4..ec3b346a8db 100644 --- a/Lib/test/test_exception_group.py +++ b/Lib/test/test_exception_group.py @@ -1,7 +1,9 @@ import collections import types import unittest -from test.support import skip_emscripten_stack_overflow, skip_wasi_stack_overflow, exceeds_recursion_limit +from test.support import (skip_emscripten_stack_overflow, + skip_wasi_stack_overflow, run_with_limited_c_stack, + exceeds_recursion_limit, nomemtest) class TestExceptionGroupTypeHierarchy(unittest.TestCase): def test_exception_group_types(self): @@ -128,6 +130,15 @@ class MyBEG(BaseExceptionGroup): type(MyBEG("eg", [ValueError(12), KeyboardInterrupt(42)])), MyBEG) + @nomemtest + def test_no_memory(self): + import _testcapi + # A tuple of exceptions is not copied, so the first allocation + # is the one of the exception group itself. + excs = (ValueError(1),) + with self.assertRaises(MemoryError): + _testcapi.call_with_nomemory(0, 0, ExceptionGroup, "eg", excs) + class StrAndReprTests(unittest.TestCase): def test_ExceptionGroup(self): @@ -234,6 +245,18 @@ class MyEG(ExceptionGroup): "ExceptionGroup('test', deque([ValueError(1), TypeError(2)]))" ) + def test_repr_small_size_args(self): + eg = ExceptionGroup("msg", [ValueError()]) + eg.args = () + # repr of the ExceptionGroup with empty args should not crash + self.assertEqual(repr(eg), "ExceptionGroup('msg', (ValueError(),))") + + eg.args = (1,) + # repr of the ExceptionGroup with 1-size args should not crash + self.assertEqual(repr(eg), "ExceptionGroup('msg', (ValueError(),))") + + + def test_repr_raises(self): class MySeq(collections.abc.Sequence): def __init__(self, raises): @@ -255,7 +278,7 @@ def __repr__(self): seq = MySeq(None) with self.assertRaisesRegex( TypeError, - r"__repr__ returned non-string \(type NoneType\)" + r".*MySeq\.__repr__\(\) must return a str, not NoneType" ): ExceptionGroup("test", seq) @@ -535,6 +558,7 @@ def make_deep_eg(self): e = ExceptionGroup('eg', [e]) return e + @run_with_limited_c_stack() @skip_emscripten_stack_overflow() @skip_wasi_stack_overflow() def test_deep_split(self): @@ -542,6 +566,7 @@ def test_deep_split(self): with self.assertRaises(RecursionError): e.split(TypeError) + @run_with_limited_c_stack() @skip_emscripten_stack_overflow() @skip_wasi_stack_overflow() def test_deep_subgroup(self): diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py index edea5bc05e1..f01ce31e139 100644 --- a/Lib/test/test_exceptions.py +++ b/Lib/test/test_exceptions.py @@ -232,6 +232,33 @@ def test_error_offset_continuation_characters(self): check = self.check check('"\\\n"(1 for c in I,\\\n\\', 2, 2) + def testSyntaxErrorRange(self): + # gh-156894: the position was reported in bytes, not in characters, + # for the errors which cover a range + for source, offset, end_offset in [ + ('abcd = 00010', 8, 11), + ('\u03b1\u03b2\u03b3\u03b4 = 00010', 8, 11), + ('a\u0301b\u0308c\u20d7d\u1ab0 = 00010', 12, 15), + ("abcd = ub'a'", 8, 10), + ("\u03b1\u03b2\u03b3\u03b4 = ub'a'", 8, 10), + ("a\u0301b\u0308c\u20d7d\u1ab0 = ub'a'", 12, 14), + ]: + with self.subTest(source=source): + with self.assertRaises(SyntaxError) as cm: + compile(source, '', 'exec') + self.assertEqual(cm.exception.offset, offset) + self.assertEqual(cm.exception.end_offset, end_offset) + + def testSyntaxErrorNonUTF8Offset(self): + # gh-157378: the position was reported one column short for each + # multi-byte character preceding the invalid byte on the same line + check = self.check + check(b'X\x80', 1, 2, 1, 2) + check(b'\xc3\xa9X\x80', 1, 3, 1, 3) + check(b'\t\xc3\xa9X\x80', 1, 4, 1, 4) + check(b'a\xc3\xa9b\x80c', 1, 4, 1, 4) + check(b'a\n\xc3\xa9X\x80', 2, 3, 2, 3) + def testSyntaxErrorOffset(self): check = self.check check('def fact(x):\n\treturn x!\n', 2, 10) @@ -252,7 +279,16 @@ def testSyntaxErrorOffset(self): check('[\nfile\nfor str(file)\nin\n[]\n]', 3, 5) check('[file for\n str(file) in []]', 2, 2) check("ages = {'Alice'=22, 'Bob'=23}", 1, 9) - check('match ...:\n case {**rest, "key": value}:\n ...', 2, 19) + check(dedent("""\ + match ...: + case {**rest1, "after": after}: + ... + """), 2, 11) + check(dedent("""\ + match ...: + case {"before": before, **rest2, "after": after}: + ... + """), 2, 29) check("[a b c d e f]", 1, 2) check("for x yfff:", 1, 7) check("f(a for a in b, c)", 1, 3, 1, 15) @@ -328,7 +364,6 @@ def baz(): check('x=1\nfrom __future__ import division', 2, 1) check('foo(1=2)', 1, 5) check('def f():\n x, y: int', 2, 3) - check('[*x for x in xs]', 1, 2) check('foo(x for x in range(10), 100)', 1, 5) check('for 1 in []: pass', 1, 5) check('(yield i) = 2', 1, 2) @@ -668,6 +703,44 @@ def test_invalid_setattr(self): msg = "exception context must be None or derive from BaseException" self.assertRaisesRegex(TE, msg, setattr, exc, '__context__', 1) + def test_object_attributes(self): + # These attributes are implemented as plain object members: + # they accept any object and are reset to None when deleted. + cases = [ + (SyntaxError('msgStr'), 'msg'), + (SyntaxError('msgStr'), 'filename'), + (SyntaxError('msgStr'), 'lineno'), + (SyntaxError('msgStr'), 'offset'), + (SyntaxError('msgStr'), 'end_lineno'), + (SyntaxError('msgStr'), 'end_offset'), + (SyntaxError('msgStr'), 'text'), + (SyntaxError('msgStr'), 'print_file_and_line'), + (SyntaxError('msgStr'), '_metadata'), + (ImportError('msgStr'), 'msg'), + (ImportError('msgStr'), 'name'), + (ImportError('msgStr'), 'path'), + (ImportError('msgStr'), 'name_from'), + (SystemExit(1), 'code'), + (StopIteration(), 'value'), + (NameError('msgStr'), 'name'), + (AttributeError('msgStr'), 'name'), + (AttributeError('msgStr'), 'obj'), + (OSError(2, 'msgStr'), 'errno'), + (OSError(2, 'msgStr'), 'strerror'), + (OSError(2, 'msgStr'), 'filename'), + (OSError(2, 'msgStr'), 'filename2'), + (UnicodeDecodeError('utf-8', b'\xff', 0, 1, 'reasonStr'), 'reason'), + ] + if sys.platform == 'win32': + cases.append((OSError(2, 'msgStr'), 'winerror')) + for exc, name in cases: + with self.subTest(exc=type(exc).__name__, name=name): + for value in 'strValue', 42, [1, 2], None: + setattr(exc, name, value) + self.assertEqual(getattr(exc, name), value) + delattr(exc, name) + self.assertIsNone(getattr(exc, name)) + def test_invalid_delattr(self): TE = TypeError try: @@ -725,6 +798,13 @@ def testChainingDescriptors(self): self.assertTrue(e.__suppress_context__) e.__suppress_context__ = False self.assertFalse(e.__suppress_context__) + with self.assertRaisesRegex(TypeError, + 'attribute value type must be bool'): + e.__suppress_context__ = 1 + with self.assertRaisesRegex(TypeError, + "can't delete numeric/char attribute"): + del e.__suppress_context__ + self.assertFalse(e.__suppress_context__) def testKeywordArgs(self): # test that builtin exception don't take keyword args, @@ -1510,6 +1590,7 @@ def gen(): @cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") @force_not_colorized + @support.skip_if_huge_c_stack() def test_recursion_normalizing_infinite_exception(self): # Issue #30697. Test that a RecursionError is raised when # maximum recursion depth has been exceeded when creating @@ -1576,25 +1657,21 @@ def recurse_in_body_and_except(): sys.setrecursionlimit(recursionlimit) - @cpython_only - # Python built with Py_TRACE_REFS fail with a fatal error in - # _PyRefchain_Trace() on memory allocation error. - @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') - @unittest.skipIf(_testcapi is None, "requires _testcapi") + @support.nomemtest def test_recursion_normalizing_with_no_memory(self): # Issue #30697. Test that in the abort that occurs when there is no # memory left and the size of the Python frames stack is greater than # the size of the list of preallocated MemoryError instances, the # Fatal Python error message mentions MemoryError. code = """if 1: - import _testcapi + from test import support class C(): pass def recurse(cnt): cnt -= 1 if cnt: recurse(cnt) else: - _testcapi.set_nomemory(0) + support.inject_memory_error() C() recurse(16) """ @@ -1707,6 +1784,20 @@ def inner(): gc_collect() # For PyPy or other GCs. self.assertEqual(wr(), None) + def test_oserror_reinit_leak(self): + # gh-150988: Check for memory leak when re-initializing OSError. + # Previously, setting OSError attributes in a subclass + # before calling super().__init__() leaked memory. + class LeakingOSError(OSError): + def __init__(self, code, message, filename, filename2): + self.strerror = message + self.filename = filename + self.filename2 = filename2 + super().__init__(code, message, filename, None, filename2) + + exc = LeakingOSError(1, "some message", "filename.py", "filename2.py") + exc.__init__(2, "another message", "filename3.py", "filename4.py") + def test_errno_ENOTDIR(self): # Issue #12802: "not a directory" errors are ENOTDIR even on Windows with self.assertRaises(OSError) as cm: @@ -1753,16 +1844,13 @@ def test_unhandled(self): self.assertIn("test message", report) self.assertEndsWith(report, "\n") - @cpython_only - # Python built with Py_TRACE_REFS fail with a fatal error in - # _PyRefchain_Trace() on memory allocation error. - @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') - @unittest.skipIf(_testcapi is None, "requires _testcapi") + @support.nomemtest def test_memory_error_in_PyErr_PrintEx(self): code = """if 1: - import _testcapi + from test import support + stop = %d class C(): pass - _testcapi.set_nomemory(0, %d) + support.inject_memory_error(0, stop) C() """ @@ -1915,12 +2003,8 @@ def test_keyerror_context(self): exc2 = None - @cpython_only - # Python built with Py_TRACE_REFS fail with a fatal error in - # _PyRefchain_Trace() on memory allocation error. - @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') + @support.nomemtest def test_exec_set_nomemory_hang(self): - import_module("_testcapi") # gh-134163: A MemoryError inside code that was wrapped by a try/except # block would lead to an infinite loop. @@ -1931,8 +2015,8 @@ def test_exec_set_nomemory_hang(self): warmup_code = "a = list(range(0, 1))\n" * 60 user_input = warmup_code + dedent(""" try: - import _testcapi - _testcapi.set_nomemory(0) + from test import support + support.inject_memory_error() b = list(range(1000, 2000)) except Exception as e: import traceback @@ -2117,6 +2201,50 @@ def test_copy_pickle(self): self.assertEqual(exc.name, orig.name) self.assertEqual(exc.path, orig.path) + def test_repr(self): + exc = ImportError() + self.assertEqual(repr(exc), "ImportError()") + + exc = ImportError('test') + self.assertEqual(repr(exc), "ImportError('test')") + + exc = ImportError('test', 'case') + self.assertEqual(repr(exc), "ImportError('test', 'case')") + + exc = ImportError(name='somemodule') + self.assertEqual(repr(exc), "ImportError(name='somemodule')") + + exc = ImportError('test', name='somemodule') + self.assertEqual(repr(exc), "ImportError('test', name='somemodule')") + + exc = ImportError(path='somepath') + self.assertEqual(repr(exc), "ImportError(path='somepath')") + + exc = ImportError('test', path='somepath') + self.assertEqual(repr(exc), "ImportError('test', path='somepath')") + + exc = ImportError(name='somename', path='somepath') + self.assertEqual(repr(exc), + "ImportError(name='somename', path='somepath')") + + exc = ImportError('test', name='somename', path='somepath') + self.assertEqual(repr(exc), + "ImportError('test', name='somename', path='somepath')") + + exc = ModuleNotFoundError('test', name='somename', path='somepath') + self.assertEqual(repr(exc), + "ModuleNotFoundError('test', name='somename', path='somepath')") + + def test_ModuleNotFoundError_repr_with_failed_import(self): + with self.assertRaises(ModuleNotFoundError) as cm: + import does_not_exist # type: ignore[import] # noqa: F401 + + self.assertEqual(cm.exception.name, "does_not_exist") + self.assertIsNone(cm.exception.path) + + self.assertEqual(repr(cm.exception), + "ModuleNotFoundError(\"No module named 'does_not_exist'\", name='does_not_exist')") + def run_script(source): if isinstance(source, str): @@ -2373,7 +2501,6 @@ class MySyntaxError(SyntaxError): ^^^^^ """, err.getvalue()) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_encodings(self): self.addCleanup(unlink, TESTFN) source = ( @@ -2382,7 +2509,8 @@ def test_encodings(self): ) err = run_script(source.encode('cp437')) self.assertEqual(err[-3], ' "┬ó┬ó┬ó┬ó┬ó┬ó" + f(4, x for x in range(1))') - self.assertEqual(err[-2], ' ^^^') + self.assertEqual(err[-2], ' ^^^^^^^^^^^^^^^^^^^') + self.assertEqual(err[-1], 'SyntaxError: Generator expression must be parenthesized') # Check backwards tokenizer errors source = '# -*- coding: ascii -*-\n\n(\n' @@ -2549,6 +2677,32 @@ def test_except_star_invalid_exception_type(self): except (ValueError, 42): pass + @cpython_only + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_given_exception_matches_nested_tuple(self): + # Nested tuples are searched recursively. + self.assertTrue( + _testcapi.err_givenexceptionmatches(ValueError(), ((ValueError,),))) + self.assertFalse( + _testcapi.err_givenexceptionmatches(TypeError(), ((ValueError,),))) + + @cpython_only + @unittest.skipIf(_testcapi is None, "requires _testcapi") + @support.skip_emscripten_stack_overflow() + @support.skip_wasi_stack_overflow() + @support.run_with_limited_c_stack(depth=500_000) + def test_given_exception_matches_deeply_nested_tuple(self): + # gh-156204: PyErr_GivenExceptionMatches() used to exhaust the C stack + # and crash the interpreter on deeply nested tuples of exception types. + tup = (ValueError,) + for _ in range(500_000): + tup = (tup,) + + with support.catch_unraisable_exception() as cm: + self.assertFalse( + _testcapi.err_givenexceptionmatches(ValueError(), tup)) + self.assertIsInstance(cm.unraisable.exc_value, RecursionError) + class PEP626Tests(unittest.TestCase): diff --git a/Lib/test/test_extcall.py b/Lib/test/test_extcall.py index 483d5ad5f2b..4da5601e802 100644 --- a/Lib/test/test_extcall.py +++ b/Lib/test/test_extcall.py @@ -137,7 +137,7 @@ >>> g(*Nothing()) Traceback (most recent call last): ... - TypeError: test.test_extcall.g() argument after * must be an iterable, not Nothing + TypeError: Value after * must be an iterable, not Nothing >>> class Nothing: ... def __len__(self): return 5 @@ -146,7 +146,7 @@ >>> g(*Nothing()) Traceback (most recent call last): ... - TypeError: test.test_extcall.g() argument after * must be an iterable, not Nothing + TypeError: Value after * must be an iterable, not Nothing >>> class Nothing(): ... def __len__(self): return 5 @@ -266,7 +266,7 @@ >>> h(*h) Traceback (most recent call last): ... - TypeError: test.test_extcall.h() argument after * must be an iterable, not function + TypeError: Value after * must be an iterable, not function >>> h(1, *h) Traceback (most recent call last): @@ -281,55 +281,69 @@ >>> dir(*h) Traceback (most recent call last): ... - TypeError: dir() argument after * must be an iterable, not function + TypeError: Value after * must be an iterable, not function >>> nothing = None >>> nothing(*h) Traceback (most recent call last): ... - TypeError: None argument after * must be an iterable, \ -not function + TypeError: Value after * must be an iterable, not function >>> h(**h) Traceback (most recent call last): ... - TypeError: test.test_extcall.h() argument after ** must be a mapping, not function + TypeError: Value after ** must be a mapping, not function >>> h(**[]) Traceback (most recent call last): ... - TypeError: test.test_extcall.h() argument after ** must be a mapping, not list + TypeError: Value after ** must be a mapping, not list >>> h(a=1, **h) Traceback (most recent call last): ... - TypeError: test.test_extcall.h() argument after ** must be a mapping, not function + TypeError: Value after ** must be a mapping, not function >>> h(a=1, **[]) Traceback (most recent call last): ... - TypeError: test.test_extcall.h() argument after ** must be a mapping, not list + TypeError: Value after ** must be a mapping, not list >>> h(**{'a': 1}, **h) Traceback (most recent call last): ... - TypeError: test.test_extcall.h() argument after ** must be a mapping, not function + TypeError: Value after ** must be a mapping, not function >>> h(**{'a': 1}, **[]) Traceback (most recent call last): ... - TypeError: test.test_extcall.h() argument after ** must be a mapping, not list + TypeError: Value after ** must be a mapping, not list >>> dir(**h) Traceback (most recent call last): ... - TypeError: dir() argument after ** must be a mapping, not function + TypeError: Value after ** must be a mapping, not function >>> nothing(**h) Traceback (most recent call last): ... - TypeError: None argument after ** must be a mapping, \ -not function + TypeError: Value after ** must be a mapping, not function + + >>> class OnlyKeys: + ... def keys(self): + ... return ['key'] + >>> h(**OnlyKeys()) + Traceback (most recent call last): + ... + TypeError: 'OnlyKeys' object is not subscriptable + + >>> class BrokenKeys: + ... def keys(self): + ... return 1 + >>> h(**BrokenKeys()) + Traceback (most recent call last): + ... + TypeError: test.test_extcall.BrokenKeys.keys() must return an iterable, not int >>> dir(b=1, **{'b': 1}) Traceback (most recent call last): @@ -442,7 +456,7 @@ ... False True - >>> id(1, **{'foo': 1}) # TODO: RUSTPYTHON # doctest:+EXPECTED_FAILURE + >>> id(1, **{'foo': 1}) Traceback (most recent call last): ... TypeError: id() takes no keyword arguments @@ -542,18 +556,156 @@ """ +def test_errors_in_iter(): + """ + >>> class A: + ... def __iter__(self): + ... raise exc + ... + >>> def f(*args, **kwargs): pass + >>> exc = ZeroDivisionError('some error') + >>> f(*A()) + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> f(*A()) + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = TypeError('some error') + >>> f(*A()) + Traceback (most recent call last): + ... + TypeError: some error + """ + +def test_errors_in_next(): + """ + >>> class I: + ... def __iter__(self): + ... return self + ... def __next__(self): + ... raise exc + ... + >>> class A: + ... def __iter__(self): + ... return I() + ... + + >>> def f(*args, **kwargs): pass + >>> exc = ZeroDivisionError('some error') + >>> f(*A()) + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> f(*A()) + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = TypeError('some error') + >>> f(*A()) + Traceback (most recent call last): + ... + TypeError: some error + """ + +def test_errors_in_keys(): + """ + >>> class D: + ... def keys(self): + ... raise exc + ... + >>> def f(*args, **kwargs): pass + >>> exc = ZeroDivisionError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = KeyError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + KeyError: 'some error' + """ + +def test_errors_in_keys_next(): + """ + >>> class I: + ... def __iter__(self): + ... return self + ... def __next__(self): + ... raise exc + ... + >>> class D: + ... def keys(self): + ... return I() + ... + >>> def f(*args, **kwargs): pass + >>> exc = ZeroDivisionError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = KeyError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + KeyError: 'some error' + """ + +def test_errors_in_getitem(): + """ + >>> class D: + ... def keys(self): + ... return ['key'] + ... def __getitem__(self, key): + ... raise exc + ... + >>> def f(*args, **kwargs): pass + >>> exc = ZeroDivisionError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = KeyError('some error') + >>> f(**D()) + Traceback (most recent call last): + ... + KeyError: 'some error' + """ + import doctest import unittest -EXPECTED_FAILURE = doctest.register_optionflag('EXPECTED_FAILURE') # TODO: RUSTPYTHON -class CustomOutputChecker(doctest.OutputChecker): # TODO: RUSTPYTHON - def check_output(self, want, got, optionflags): # TODO: RUSTPYTHON - if optionflags & EXPECTED_FAILURE: # TODO: RUSTPYTHON - return not super().check_output(want, got, optionflags) # TODO: RUSTPYTHON - return super().check_output(want, got, optionflags) # TODO: RUSTPYTHON - def load_tests(loader, tests, pattern): - tests.addTest(doctest.DocTestSuite(checker=CustomOutputChecker())) # TODO: RUSTPYTHON + tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_external_inspection.py b/Lib/test/test_external_inspection.py index 08779bdb008..797b13af59f 100644 --- a/Lib/test/test_external_inspection.py +++ b/Lib/test/test_external_inspection.py @@ -1,11 +1,14 @@ +import asyncio import unittest import os import textwrap +import contextlib import importlib import sys import socket import threading import time +from contextlib import contextmanager from asyncio import staggered, taskgroups, base_events, tasks from unittest.mock import ANY from test.support import ( @@ -13,6 +16,7 @@ SHORT_TIMEOUT, busy_retry, requires_gil_enabled, + requires_remote_subprocess_debugging, ) from test.support.import_helper import import_module from test.support.script_helper import make_script @@ -20,6 +24,31 @@ import subprocess +# Profiling mode constants +PROFILING_MODE_WALL = 0 +PROFILING_MODE_CPU = 1 +PROFILING_MODE_GIL = 2 +PROFILING_MODE_ALL = 3 +PROFILING_MODE_EXCEPTION = 4 + +# Thread status flags +THREAD_STATUS_HAS_GIL = 1 << 0 +THREAD_STATUS_ON_CPU = 1 << 1 +THREAD_STATUS_UNKNOWN = 1 << 2 +THREAD_STATUS_HAS_EXCEPTION = 1 << 4 + +# Maximum number of retry attempts for operations that may fail transiently +MAX_TRIES = 10 +RETRY_DELAY = 0.1 + +# Exceptions that can occur transiently when reading from a live process +TRANSIENT_ERRORS = (OSError, RuntimeError, UnicodeDecodeError) + +try: + from concurrent import interpreters +except ImportError: + interpreters = None + PROCESS_VM_READV_SUPPORTED = False try: @@ -32,12 +61,149 @@ ) +# ============================================================================ +# Module-level helper functions +# ============================================================================ + + def _make_test_script(script_dir, script_basename, source): to_return = make_script(script_dir, script_basename, source) importlib.invalidate_caches() return to_return +def _create_server_socket(port, backlog=1): + """Create and configure a server socket for test communication.""" + server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server_socket.bind(("localhost", port)) + server_socket.settimeout(SHORT_TIMEOUT) + server_socket.listen(backlog) + return server_socket + + +def _wait_for_signal(sock, expected_signals, timeout=SHORT_TIMEOUT): + """ + Wait for expected signal(s) from a socket with proper timeout and EOF handling. + + Args: + sock: Connected socket to read from + expected_signals: Single bytes object or list of bytes objects to wait for + timeout: Socket timeout in seconds + + Returns: + bytes: Complete accumulated response buffer + + Raises: + RuntimeError: If connection closed before signal received or timeout + """ + if isinstance(expected_signals, bytes): + expected_signals = [expected_signals] + + sock.settimeout(timeout) + buffer = b"" + + while True: + # Check if all expected signals are in buffer + if all(sig in buffer for sig in expected_signals): + return buffer + + try: + chunk = sock.recv(4096) + if not chunk: + # EOF - connection closed + raise RuntimeError( + f"Connection closed before receiving expected signals. " + f"Expected: {expected_signals}, Got: {buffer[-200:]!r}" + ) + buffer += chunk + except socket.timeout: + raise RuntimeError( + f"Timeout waiting for signals. " + f"Expected: {expected_signals}, Got: {buffer[-200:]!r}" + ) + + +def _wait_for_n_signals(sock, signal_pattern, count, timeout=SHORT_TIMEOUT): + """ + Wait for N occurrences of a signal pattern. + + Args: + sock: Connected socket to read from + signal_pattern: bytes pattern to count (e.g., b"ready") + count: Number of occurrences expected + timeout: Socket timeout in seconds + + Returns: + bytes: Complete accumulated response buffer + + Raises: + RuntimeError: If connection closed or timeout before receiving all signals + """ + sock.settimeout(timeout) + buffer = b"" + found_count = 0 + + while found_count < count: + try: + chunk = sock.recv(4096) + if not chunk: + raise RuntimeError( + f"Connection closed after {found_count}/{count} signals. " + f"Last 200 bytes: {buffer[-200:]!r}" + ) + buffer += chunk + # Count occurrences in entire buffer + found_count = buffer.count(signal_pattern) + except socket.timeout: + raise RuntimeError( + f"Timeout waiting for {count} signals (found {found_count}). " + f"Last 200 bytes: {buffer[-200:]!r}" + ) + + return buffer + + +@contextmanager +def _managed_subprocess(args, timeout=SHORT_TIMEOUT): + """ + Context manager for subprocess lifecycle management. + + Ensures process is properly terminated and cleaned up even on exceptions. + Uses graceful termination first, then forceful kill if needed. + """ + p = subprocess.Popen(args) + try: + yield p + finally: + try: + p.terminate() + try: + p.wait(timeout=timeout) + except subprocess.TimeoutExpired: + p.kill() + try: + p.wait(timeout=timeout) + except subprocess.TimeoutExpired: + pass # Process refuses to die, nothing more we can do + except OSError: + pass # Process already dead + + +def _cleanup_sockets(*sockets): + """Safely close multiple sockets, ignoring errors.""" + for sock in sockets: + if sock is not None: + try: + sock.close() + except OSError: + pass + + +# ============================================================================ +# Decorators and skip conditions +# ============================================================================ + skip_if_not_supported = unittest.skipIf( ( sys.platform != "darwin" @@ -48,36 +214,311 @@ def _make_test_script(script_dir, script_basename, source): ) +def requires_subinterpreters(meth): + """Decorator to skip a test if subinterpreters are not supported.""" + return unittest.skipIf(interpreters is None, "subinterpreters required")( + meth + ) + + +# ============================================================================ +# Simple wrapper functions for RemoteUnwinder +# ============================================================================ + def get_stack_trace(pid): - unwinder = RemoteUnwinder(pid, all_threads=True, debug=True) - return unwinder.get_stack_trace() + for _ in busy_retry(SHORT_TIMEOUT): + try: + unwinder = RemoteUnwinder(pid, all_threads=True, debug=True) + return unwinder.get_stack_trace() + except RuntimeError as e: + continue + raise RuntimeError("Failed to get stack trace after retries") def get_async_stack_trace(pid): - unwinder = RemoteUnwinder(pid, debug=True) - return unwinder.get_async_stack_trace() + for _ in busy_retry(SHORT_TIMEOUT): + try: + unwinder = RemoteUnwinder(pid, debug=True) + return unwinder.get_async_stack_trace() + except RuntimeError as e: + continue + raise RuntimeError("Failed to get async stack trace after retries") def get_all_awaited_by(pid): - unwinder = RemoteUnwinder(pid, debug=True) - return unwinder.get_all_awaited_by() + for _ in busy_retry(SHORT_TIMEOUT): + try: + unwinder = RemoteUnwinder(pid, debug=True) + return unwinder.get_all_awaited_by() + except RuntimeError as e: + continue + raise RuntimeError("Failed to get all awaited_by after retries") + + +def _get_stack_trace_with_retry(unwinder, timeout=SHORT_TIMEOUT, condition=None): + """Get stack trace from an existing unwinder with retry for transient errors. + + This handles the case where we want to reuse an existing RemoteUnwinder + instance but still handle transient failures like "Failed to parse initial + frame in chain" that can occur when sampling at an inopportune moment. + If condition is provided, keeps retrying until condition(traces) is True. + """ + last_error = None + for _ in busy_retry(timeout): + try: + traces = unwinder.get_stack_trace() + if condition is None or condition(traces): + return traces + # Condition not met yet, keep retrying + except TRANSIENT_ERRORS as e: + last_error = e + continue + if last_error: + raise RuntimeError( + f"Failed to get stack trace after retries: {last_error}" + ) + raise RuntimeError("Condition never satisfied within timeout") + + +# ============================================================================ +# Base test class with shared infrastructure +# ============================================================================ + +class RemoteInspectionTestBase(unittest.TestCase): + """Base class for remote inspection tests with common helpers.""" -class TestGetStackTrace(unittest.TestCase): maxDiff = None + def _run_script_and_get_trace( + self, + script, + trace_func, + wait_for_signals=None, + port=None, + backlog=1, + ): + """ + Common pattern: run a script, wait for signals, get trace. + + Args: + script: Script content (will be formatted with port if {port} present) + trace_func: Function to call with pid to get trace (e.g., get_stack_trace) + wait_for_signals: Signal(s) to wait for before getting trace + port: Port to use (auto-selected if None) + backlog: Socket listen backlog + + Returns: + tuple: (trace_result, script_name) + """ + if port is None: + port = find_unused_port() + + # Format script with port if needed + if "{port}" in script or "{{port}}" in script: + script = script.replace("{{port}}", "{port}").format(port=port) + + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + + server_socket = _create_server_socket(port, backlog) + script_name = _make_test_script(script_dir, "script", script) + client_socket = None + + try: + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + if wait_for_signals: + _wait_for_signal(client_socket, wait_for_signals) + + trace = trace_func(p.pid) + return trace, script_name + finally: + _cleanup_sockets(client_socket, server_socket) + + def _find_frame_in_trace(self, stack_trace, predicate): + """ + Find a frame matching predicate in stack trace. + + Args: + stack_trace: List of InterpreterInfo objects + predicate: Function(frame) -> bool + + Returns: + FrameInfo or None + """ + for interpreter_info in stack_trace: + for thread_info in interpreter_info.threads: + for frame in thread_info.frame_info: + if predicate(frame): + return frame + return None + + def _find_thread_by_id(self, stack_trace, thread_id): + """Find a thread by its native thread ID.""" + for interpreter_info in stack_trace: + for thread_info in interpreter_info.threads: + if thread_info.thread_id == thread_id: + return thread_info + return None + + def _find_thread_with_frame(self, stack_trace, frame_predicate): + """Find a thread containing a frame matching predicate.""" + for interpreter_info in stack_trace: + for thread_info in interpreter_info.threads: + for frame in thread_info.frame_info: + if frame_predicate(frame): + return thread_info + return None + + def _get_thread_statuses(self, stack_trace): + """Extract thread_id -> status mapping from stack trace.""" + statuses = {} + for interpreter_info in stack_trace: + for thread_info in interpreter_info.threads: + statuses[thread_info.thread_id] = thread_info.status + return statuses + + def _get_task_id_map(self, stack_trace): + """Create task_id -> task mapping from async stack trace.""" + return {task.task_id: task for task in stack_trace[0].awaited_by} + + def _get_awaited_by_relationships(self, stack_trace): + """Extract task name to awaited_by set mapping.""" + id_to_task = self._get_task_id_map(stack_trace) + return { + task.task_name: set( + id_to_task[awaited.task_name].task_name + for awaited in task.awaited_by + ) + for task in stack_trace[0].awaited_by + } + + def _extract_coroutine_stacks(self, stack_trace): + """Extract and format coroutine stacks from tasks.""" + return { + task.task_name: sorted( + tuple(tuple(frame) for frame in coro.call_stack) + for coro in task.coroutine_stack + ) + for task in stack_trace[0].awaited_by + } + + @staticmethod + def _frame_to_lineno_tuple(frame): + """Convert frame to (filename, lineno, funcname, opcode) tuple. + + This extracts just the line number from the location, ignoring column + offsets which can vary due to sampling timing (e.g., when two statements + are on the same line, the sample might catch either one). + """ + filename, location, funcname, opcode = frame + return (filename, location.lineno, funcname, opcode) + + def _extract_coroutine_stacks_lineno_only(self, stack_trace): + """Extract coroutine stacks with line numbers only (no column offsets). + + Use this for tests where sampling timing can cause column offset + variations (e.g., 'expr1; expr2' on the same line). + """ + return { + task.task_name: sorted( + tuple(self._frame_to_lineno_tuple(frame) for frame in coro.call_stack) + for coro in task.coroutine_stack + ) + for task in stack_trace[0].awaited_by + } + + +# ============================================================================ +# Test classes +# ============================================================================ + + +@requires_remote_subprocess_debugging() +class TestSelfStackTrace(RemoteInspectionTestBase): + @skip_if_not_supported + def test_long_task_name_is_truncated(self): + # gh-157788 + async def main(): + asyncio.create_task(asyncio.sleep(10_000), name="x" * 300) + await asyncio.sleep(0) + names = [ + task.task_name + for info in RemoteUnwinder(os.getpid()).get_all_awaited_by() + for task in info.awaited_by + ] + return asyncio.current_task().get_name(), names + + main_name, names = asyncio.run(main()) + self.assertIn(main_name, names) + self.assertEqual([len(n) for n in names if n.startswith("x")], [255]) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_self_trace_with_large_linetable(self): + script = textwrap.dedent("""\ + import os + import _remote_debugging + + assignments = "\\n".join( + f"value_{i} = {i}" for i in range(1000) + ) + expected_lineno = len(assignments.splitlines()) + 1 + source = ( + f"{assignments}\\n" + "stack_trace = " + "_remote_debugging.RemoteUnwinder(os.getpid()).get_stack_trace()\\n" + ) + code = compile(source, "large_linetable.py", "exec") + assert len(code.co_linetable) > 4096, len(code.co_linetable) + namespace = {"os": os, "_remote_debugging": _remote_debugging} + exec(code, namespace) + large_linetable_frames = [ + frame + for interpreter in namespace["stack_trace"] + for thread in interpreter.threads + for frame in thread.frame_info + if frame.filename == "large_linetable.py" + ] + assert len(large_linetable_frames) == 1, large_linetable_frames + assert large_linetable_frames[0].location.lineno == expected_lineno, ( + large_linetable_frames[0] + ) + """) + + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + timeout=SHORT_TIMEOUT, + ) + self.assertEqual( + result.returncode, 0, + f"stdout: {result.stdout}\nstderr: {result.stderr}" + ) + + +@requires_remote_subprocess_debugging() +class TestGetStackTrace(RemoteInspectionTestBase): @skip_if_not_supported @unittest.skipIf( sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, "Test only runs on Linux with process_vm_readv support", ) def test_remote_stack_trace(self): - # Spawn a process with some realistic Python code port = find_unused_port() script = textwrap.dedent( f"""\ import time, sys, socket, threading - # Connect to the test process + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', {port})) @@ -90,66 +531,59 @@ def baz(): foo() def foo(): - sock.sendall(b"ready:thread\\n"); time.sleep(10_000) # same line number + sock.sendall(b"ready:thread\\n"); time.sleep(10_000) t = threading.Thread(target=bar) t.start() - sock.sendall(b"ready:main\\n"); t.join() # same line number + sock.sendall(b"ready:main\\n"); t.join() """ ) - stack_trace = None + with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) - # Create a socket server to communicate with the target process - server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - server_socket.bind(("localhost", port)) - server_socket.settimeout(SHORT_TIMEOUT) - server_socket.listen(1) - + server_socket = _create_server_socket(port) script_name = _make_test_script(script_dir, "script", script) client_socket = None + try: - p = subprocess.Popen([sys.executable, script_name]) - client_socket, _ = server_socket.accept() - server_socket.close() - response = b"" - while ( - b"ready:main" not in response - or b"ready:thread" not in response - ): - response += client_socket.recv(1024) - stack_trace = get_stack_trace(p.pid) - except PermissionError: - self.skipTest( - "Insufficient permissions to read the stack trace" - ) - finally: - if client_socket is not None: - client_socket.close() - p.kill() - p.terminate() - p.wait(timeout=SHORT_TIMEOUT) + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None - thread_expected_stack_trace = [ - FrameInfo([script_name, 15, "foo"]), - FrameInfo([script_name, 12, "baz"]), - FrameInfo([script_name, 9, "bar"]), - FrameInfo([threading.__file__, ANY, "Thread.run"]), - ] - # Is possible that there are more threads, so we check that the - # expected stack traces are in the result (looking at you Windows!) - self.assertIn((ANY, thread_expected_stack_trace), stack_trace) - - # Check that the main thread stack trace is in the result - frame = FrameInfo([script_name, 19, ""]) - for _, stack in stack_trace: - if frame in stack: - break - else: - self.fail("Main thread stack trace not found in result") + _wait_for_signal( + client_socket, [b"ready:main", b"ready:thread"] + ) + + stack_trace = get_stack_trace(p.pid) + + # Find expected thread stack by funcname + found_thread = self._find_thread_with_frame( + stack_trace, + lambda f: f.funcname == "foo" and f.location.lineno == 15, + ) + self.assertIsNotNone( + found_thread, "Expected thread stack trace not found" + ) + # Check the funcnames in order + funcnames = [f.funcname for f in found_thread.frame_info] + self.assertEqual( + funcnames[:6], + ["foo", "baz", "bar", "Thread.run", "Thread._bootstrap_inner", "Thread._bootstrap"] + ) + + # Check main thread + found_main = self._find_frame_in_trace( + stack_trace, + lambda f: f.funcname == "" and f.location.lineno == 19, + ) + self.assertIsNotNone( + found_main, "Main thread stack trace not found" + ) + finally: + _cleanup_sockets(client_socket, server_socket) @skip_if_not_supported @unittest.skipIf( @@ -193,13 +627,81 @@ def test_self_trace_after_ctypes_import(self): f"stdout: {result.stdout}\nstderr: {result.stderr}" ) + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_remote_stack_trace_non_ascii_names(self): + # Exercise each PyUnicode kind (1-byte non-ASCII, 2-byte BMP, + # 4-byte non-BMP) for both the filename and the function name + # reported in the stack trace. + latin1 = "zażółć" # 1-byte non-ASCII (forces non-ASCII path) + bmp = "λάμβδα" # 2-byte BMP + astral = "𐌀𐌁𐌂𐌃" # 4-byte non-BMP (Old Italic; XID, no NFKC fold) + func_name = f"{latin1}_{bmp}_{astral}" + script_basename = f"mod_{latin1}_{bmp}_{astral}" + + port = find_unused_port() + script = textwrap.dedent( + f"""\ + import socket + import time + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def {func_name}(): + sock.sendall(b"ready") + time.sleep(10_000) + + {func_name}() + """ + ) + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + script_name = _make_test_script(script_dir, script_basename, script) + + server_socket = _create_server_socket(port) + client_socket = None + try: + p = subprocess.Popen([sys.executable, script_name]) + client_socket, _ = server_socket.accept() + server_socket.close() + _wait_for_signal(client_socket, b"ready") + + stack_trace = get_stack_trace(p.pid) + except PermissionError: + self.skipTest("Insufficient permissions to read the stack trace") + finally: + if client_socket is not None: + client_socket.close() + p.kill() + p.wait(timeout=SHORT_TIMEOUT) + + frames = [ + frame + for interp in stack_trace + for thread in interp.threads + for frame in thread.frame_info + ] + target = next( + (f for f in frames if f.funcname == func_name), None + ) + self.assertIsNotNone( + target, + f"Frame for {func_name!r} missing; got " + f"{[(f.filename, f.funcname) for f in frames]}", + ) + self.assertEqual(target.filename, script_name) + @skip_if_not_supported @unittest.skipIf( sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, "Test only runs on Linux with process_vm_readv support", ) def test_async_remote_stack_trace(self): - # Spawn a process with some realistic Python code port = find_unused_port() script = textwrap.dedent( f"""\ @@ -207,12 +709,12 @@ def test_async_remote_stack_trace(self): import time import sys import socket - # Connect to the test process + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', {port})) def c5(): - sock.sendall(b"ready"); time.sleep(10_000) # same line number + sock.sendall(b"ready"); time.sleep(10_000) async def c4(): await asyncio.sleep(0) @@ -243,7 +745,7 @@ def new_eager_loop(): asyncio.run(main(), loop_factory={{TASK_FACTORY}}) """ ) - stack_trace = None + for task_factory_variant in "asyncio.new_event_loop", "new_eager_loop": with ( self.subTest(task_factory_variant=task_factory_variant), @@ -251,203 +753,159 @@ def new_eager_loop(): ): script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) - server_socket = socket.socket( - socket.AF_INET, socket.SOCK_STREAM - ) - server_socket.setsockopt( - socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 - ) - server_socket.bind(("localhost", port)) - server_socket.settimeout(SHORT_TIMEOUT) - server_socket.listen(1) + + server_socket = _create_server_socket(port) script_name = _make_test_script( script_dir, "script", script.format(TASK_FACTORY=task_factory_variant), ) client_socket = None - try: - p = subprocess.Popen([sys.executable, script_name]) - client_socket, _ = server_socket.accept() - server_socket.close() - response = client_socket.recv(1024) - self.assertEqual(response, b"ready") - stack_trace = get_async_stack_trace(p.pid) - except PermissionError: - self.skipTest( - "Insufficient permissions to read the stack trace" - ) - finally: - if client_socket is not None: - client_socket.close() - p.kill() - p.terminate() - p.wait(timeout=SHORT_TIMEOUT) - - # First check all the tasks are present - tasks_names = [ - task.task_name for task in stack_trace[0].awaited_by - ] - for task_name in ["c2_root", "sub_main_1", "sub_main_2"]: - self.assertIn(task_name, tasks_names) - - # Now ensure that the awaited_by_relationships are correct - id_to_task = { - task.task_id: task for task in stack_trace[0].awaited_by - } - task_name_to_awaited_by = { - task.task_name: set( - id_to_task[awaited.task_name].task_name - for awaited in task.awaited_by - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - task_name_to_awaited_by, - { - "c2_root": {"Task-1", "sub_main_1", "sub_main_2"}, - "Task-1": set(), - "sub_main_1": {"Task-1"}, - "sub_main_2": {"Task-1"}, - }, - ) - # Now ensure that the coroutine stacks are correct - coroutine_stacks = { - task.task_name: sorted( - tuple(tuple(frame) for frame in coro.call_stack) - for coro in task.coroutine_stack - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - coroutine_stacks, - { - "Task-1": [ - ( - tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup._aexit", - ] - ), - tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup.__aexit__", - ] - ), - tuple([script_name, 26, "main"]), - ) - ], - "c2_root": [ - ( - tuple([script_name, 10, "c5"]), - tuple([script_name, 14, "c4"]), - tuple([script_name, 17, "c3"]), - tuple([script_name, 20, "c2"]), - ) - ], - "sub_main_1": [(tuple([script_name, 23, "c1"]),)], - "sub_main_2": [(tuple([script_name, 23, "c1"]),)], - }, - ) + try: + with _managed_subprocess( + [sys.executable, script_name] + ) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + response = _wait_for_signal(client_socket, b"ready") + self.assertIn(b"ready", response) + + stack_trace = get_async_stack_trace(p.pid) + + # Check all tasks are present + tasks_names = [ + task.task_name + for task in stack_trace[0].awaited_by + ] + for task_name in [ + "c2_root", + "sub_main_1", + "sub_main_2", + ]: + self.assertIn(task_name, tasks_names) + + # Check awaited_by relationships + relationships = self._get_awaited_by_relationships( + stack_trace + ) + self.assertEqual( + relationships, + { + "c2_root": { + "Task-1", + "sub_main_1", + "sub_main_2", + }, + "Task-1": set(), + "sub_main_1": {"Task-1"}, + "sub_main_2": {"Task-1"}, + }, + ) - # Now ensure the coroutine stacks for the awaited_by relationships are correct. - awaited_by_coroutine_stacks = { - task.task_name: sorted( - ( - id_to_task[coro.task_name].task_name, - tuple(tuple(frame) for frame in coro.call_stack), + # Check coroutine stacks (using line numbers only to avoid + # flakiness from column offset variations when sampling + # catches different statements on the same line) + coroutine_stacks = self._extract_coroutine_stacks_lineno_only( + stack_trace ) - for coro in task.awaited_by - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - awaited_by_coroutine_stacks, - { - "Task-1": [], - "c2_root": [ - ( - "Task-1", - ( - tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup._aexit", - ] - ), - tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup.__aexit__", - ] - ), - tuple([script_name, 26, "main"]), - ), - ), - ("sub_main_1", (tuple([script_name, 23, "c1"]),)), - ("sub_main_2", (tuple([script_name, 23, "c1"]),)), - ], - "sub_main_1": [ - ( - "Task-1", + self.assertEqual( + coroutine_stacks, + { + "Task-1": [ + ( + (taskgroups.__file__, ANY, "TaskGroup._aexit", None), + (taskgroups.__file__, ANY, "TaskGroup.__aexit__", None), + (script_name, 26, "main", None), + ) + ], + "c2_root": [ + ( + (script_name, 10, "c5", None), + (script_name, 14, "c4", None), + (script_name, 17, "c3", None), + (script_name, 20, "c2", None), + ) + ], + "sub_main_1": [ + ((script_name, 23, "c1", None),) + ], + "sub_main_2": [ + ((script_name, 23, "c1", None),) + ], + }, + ) + + # Check awaited_by coroutine stacks (line numbers only) + id_to_task = self._get_task_id_map(stack_trace) + awaited_by_coroutine_stacks = { + task.task_name: sorted( ( + id_to_task[coro.task_name].task_name, tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup._aexit", - ] - ), - tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup.__aexit__", - ] + self._frame_to_lineno_tuple(frame) + for frame in coro.call_stack ), - tuple([script_name, 26, "main"]), - ), + ) + for coro in task.awaited_by ) - ], - "sub_main_2": [ - ( - "Task-1", - ( - tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup._aexit", - ] + for task in stack_trace[0].awaited_by + } + self.assertEqual( + awaited_by_coroutine_stacks, + { + "Task-1": [], + "c2_root": [ + ( + "Task-1", + ( + (taskgroups.__file__, ANY, "TaskGroup._aexit", None), + (taskgroups.__file__, ANY, "TaskGroup.__aexit__", None), + (script_name, 26, "main", None), + ), ), - tuple( - [ - taskgroups.__file__, - ANY, - "TaskGroup.__aexit__", - ] + ( + "sub_main_1", + ((script_name, 23, "c1", None),), ), - tuple([script_name, 26, "main"]), - ), - ) - ], - }, - ) - - @skip_if_not_supported + ( + "sub_main_2", + ((script_name, 23, "c1", None),), + ), + ], + "sub_main_1": [ + ( + "Task-1", + ( + (taskgroups.__file__, ANY, "TaskGroup._aexit", None), + (taskgroups.__file__, ANY, "TaskGroup.__aexit__", None), + (script_name, 26, "main", None), + ), + ) + ], + "sub_main_2": [ + ( + "Task-1", + ( + (taskgroups.__file__, ANY, "TaskGroup._aexit", None), + (taskgroups.__file__, ANY, "TaskGroup.__aexit__", None), + (script_name, 26, "main", None), + ), + ) + ], + }, + ) + finally: + _cleanup_sockets(client_socket, server_socket) + + @skip_if_not_supported @unittest.skipIf( sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, "Test only runs on Linux with process_vm_readv support", ) def test_asyncgen_remote_stack_trace(self): - # Spawn a process with some realistic Python code port = find_unused_port() script = textwrap.dedent( f"""\ @@ -455,12 +913,12 @@ def test_asyncgen_remote_stack_trace(self): import time import sys import socket - # Connect to the test process + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', {port})) async def gen_nested_call(): - sock.sendall(b"ready"); time.sleep(10_000) # same line number + sock.sendall(b"ready"); time.sleep(10_000) async def gen(): for num in range(2): @@ -475,59 +933,53 @@ async def main(): asyncio.run(main()) """ ) - stack_trace = None + with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) - # Create a socket server to communicate with the target process - server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - server_socket.bind(("localhost", port)) - server_socket.settimeout(SHORT_TIMEOUT) - server_socket.listen(1) + + server_socket = _create_server_socket(port) script_name = _make_test_script(script_dir, "script", script) client_socket = None + try: - p = subprocess.Popen([sys.executable, script_name]) - client_socket, _ = server_socket.accept() - server_socket.close() - response = client_socket.recv(1024) - self.assertEqual(response, b"ready") - stack_trace = get_async_stack_trace(p.pid) - except PermissionError: - self.skipTest( - "Insufficient permissions to read the stack trace" - ) - finally: - if client_socket is not None: - client_socket.close() - p.kill() - p.terminate() - p.wait(timeout=SHORT_TIMEOUT) + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None - # For this simple asyncgen test, we only expect one task with the full coroutine stack - self.assertEqual(len(stack_trace[0].awaited_by), 1) - task = stack_trace[0].awaited_by[0] - self.assertEqual(task.task_name, "Task-1") + response = _wait_for_signal(client_socket, b"ready") + self.assertIn(b"ready", response) - # Check the coroutine stack - based on actual output, only shows main - coroutine_stack = sorted( - tuple(tuple(frame) for frame in coro.call_stack) - for coro in task.coroutine_stack - ) - self.assertEqual( - coroutine_stack, - [ - ( - tuple([script_name, 10, "gen_nested_call"]), - tuple([script_name, 16, "gen"]), - tuple([script_name, 19, "main"]), + stack_trace = get_async_stack_trace(p.pid) + + # For this simple asyncgen test, we only expect one task + self.assertEqual(len(stack_trace[0].awaited_by), 1) + task = stack_trace[0].awaited_by[0] + self.assertEqual(task.task_name, "Task-1") + + # Check the coroutine stack (using line numbers only to avoid + # flakiness from column offset variations when sampling + # catches different statements on the same line) + coroutine_stack = sorted( + tuple(self._frame_to_lineno_tuple(frame) for frame in coro.call_stack) + for coro in task.coroutine_stack + ) + self.assertEqual( + coroutine_stack, + [ + ( + (script_name, 10, "gen_nested_call", None), + (script_name, 16, "gen", None), + (script_name, 19, "main", None), + ) + ], ) - ], - ) - # No awaited_by relationships expected for this simple case - self.assertEqual(task.awaited_by, []) + # No awaited_by relationships expected + self.assertEqual(task.awaited_by, []) + finally: + _cleanup_sockets(client_socket, server_socket) @skip_if_not_supported @unittest.skipIf( @@ -535,7 +987,6 @@ async def main(): "Test only runs on Linux with process_vm_readv support", ) def test_async_gather_remote_stack_trace(self): - # Spawn a process with some realistic Python code port = find_unused_port() script = textwrap.dedent( f"""\ @@ -543,13 +994,13 @@ def test_async_gather_remote_stack_trace(self): import time import sys import socket - # Connect to the test process + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', {port})) async def deep(): await asyncio.sleep(0) - sock.sendall(b"ready"); time.sleep(10_000) # same line number + sock.sendall(b"ready"); time.sleep(10_000) async def c1(): await asyncio.sleep(0) @@ -564,103 +1015,89 @@ async def main(): asyncio.run(main()) """ ) - stack_trace = None + with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) - # Create a socket server to communicate with the target process - server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - server_socket.bind(("localhost", port)) - server_socket.settimeout(SHORT_TIMEOUT) - server_socket.listen(1) + + server_socket = _create_server_socket(port) script_name = _make_test_script(script_dir, "script", script) client_socket = None + try: - p = subprocess.Popen([sys.executable, script_name]) - client_socket, _ = server_socket.accept() - server_socket.close() - response = client_socket.recv(1024) - self.assertEqual(response, b"ready") - stack_trace = get_async_stack_trace(p.pid) - except PermissionError: - self.skipTest( - "Insufficient permissions to read the stack trace" - ) - finally: - if client_socket is not None: - client_socket.close() - p.kill() - p.terminate() - p.wait(timeout=SHORT_TIMEOUT) + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None - # First check all the tasks are present - tasks_names = [ - task.task_name for task in stack_trace[0].awaited_by - ] - for task_name in ["Task-1", "Task-2"]: - self.assertIn(task_name, tasks_names) + response = _wait_for_signal(client_socket, b"ready") + self.assertIn(b"ready", response) - # Now ensure that the awaited_by_relationships are correct - id_to_task = { - task.task_id: task for task in stack_trace[0].awaited_by - } - task_name_to_awaited_by = { - task.task_name: set( - id_to_task[awaited.task_name].task_name - for awaited in task.awaited_by - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - task_name_to_awaited_by, - { - "Task-1": set(), - "Task-2": {"Task-1"}, - }, - ) + stack_trace = get_async_stack_trace(p.pid) - # Now ensure that the coroutine stacks are correct - coroutine_stacks = { - task.task_name: sorted( - tuple(tuple(frame) for frame in coro.call_stack) - for coro in task.coroutine_stack - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - coroutine_stacks, - { - "Task-1": [(tuple([script_name, 21, "main"]),)], - "Task-2": [ - ( - tuple([script_name, 11, "deep"]), - tuple([script_name, 15, "c1"]), - ) - ], - }, - ) + # Check all tasks are present + tasks_names = [ + task.task_name for task in stack_trace[0].awaited_by + ] + for task_name in ["Task-1", "Task-2"]: + self.assertIn(task_name, tasks_names) - # Now ensure the coroutine stacks for the awaited_by relationships are correct. - awaited_by_coroutine_stacks = { - task.task_name: sorted( - ( - id_to_task[coro.task_name].task_name, - tuple(tuple(frame) for frame in coro.call_stack), + # Check awaited_by relationships + relationships = self._get_awaited_by_relationships( + stack_trace ) - for coro in task.awaited_by - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - awaited_by_coroutine_stacks, - { - "Task-1": [], - "Task-2": [ - ("Task-1", (tuple([script_name, 21, "main"]),)) - ], - }, - ) + self.assertEqual( + relationships, + { + "Task-1": set(), + "Task-2": {"Task-1"}, + }, + ) + + # Check coroutine stacks (using line numbers only to avoid + # flakiness from column offset variations when sampling + # catches different statements on the same line) + coroutine_stacks = self._extract_coroutine_stacks_lineno_only( + stack_trace + ) + self.assertEqual( + coroutine_stacks, + { + "Task-1": [((script_name, 21, "main", None),)], + "Task-2": [ + ( + (script_name, 11, "deep", None), + (script_name, 15, "c1", None), + ) + ], + }, + ) + + # Check awaited_by coroutine stacks (line numbers only) + id_to_task = self._get_task_id_map(stack_trace) + awaited_by_coroutine_stacks = { + task.task_name: sorted( + ( + id_to_task[coro.task_name].task_name, + tuple( + self._frame_to_lineno_tuple(frame) for frame in coro.call_stack + ), + ) + for coro in task.awaited_by + ) + for task in stack_trace[0].awaited_by + } + self.assertEqual( + awaited_by_coroutine_stacks, + { + "Task-1": [], + "Task-2": [ + ("Task-1", ((script_name, 21, "main", None),)) + ], + }, + ) + finally: + _cleanup_sockets(client_socket, server_socket) @skip_if_not_supported @unittest.skipIf( @@ -668,7 +1105,6 @@ async def main(): "Test only runs on Linux with process_vm_readv support", ) def test_async_staggered_race_remote_stack_trace(self): - # Spawn a process with some realistic Python code port = find_unused_port() script = textwrap.dedent( f"""\ @@ -676,13 +1112,13 @@ def test_async_staggered_race_remote_stack_trace(self): import time import sys import socket - # Connect to the test process + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', {port})) async def deep(): await asyncio.sleep(0) - sock.sendall(b"ready"); time.sleep(10_000) # same line number + sock.sendall(b"ready"); time.sleep(10_000) async def c1(): await asyncio.sleep(0) @@ -700,123 +1136,101 @@ async def main(): asyncio.run(main()) """ ) - stack_trace = None + with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) - # Create a socket server to communicate with the target process - server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - server_socket.bind(("localhost", port)) - server_socket.settimeout(SHORT_TIMEOUT) - server_socket.listen(1) + + server_socket = _create_server_socket(port) script_name = _make_test_script(script_dir, "script", script) client_socket = None + try: - p = subprocess.Popen([sys.executable, script_name]) - client_socket, _ = server_socket.accept() - server_socket.close() - response = client_socket.recv(1024) - self.assertEqual(response, b"ready") - stack_trace = get_async_stack_trace(p.pid) - except PermissionError: - self.skipTest( - "Insufficient permissions to read the stack trace" - ) - finally: - if client_socket is not None: - client_socket.close() - p.kill() - p.terminate() - p.wait(timeout=SHORT_TIMEOUT) + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None - # First check all the tasks are present - tasks_names = [ - task.task_name for task in stack_trace[0].awaited_by - ] - for task_name in ["Task-1", "Task-2"]: - self.assertIn(task_name, tasks_names) + response = _wait_for_signal(client_socket, b"ready") + self.assertIn(b"ready", response) - # Now ensure that the awaited_by_relationships are correct - id_to_task = { - task.task_id: task for task in stack_trace[0].awaited_by - } - task_name_to_awaited_by = { - task.task_name: set( - id_to_task[awaited.task_name].task_name - for awaited in task.awaited_by - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - task_name_to_awaited_by, - { - "Task-1": set(), - "Task-2": {"Task-1"}, - }, - ) + stack_trace = get_async_stack_trace(p.pid) - # Now ensure that the coroutine stacks are correct - coroutine_stacks = { - task.task_name: sorted( - tuple(tuple(frame) for frame in coro.call_stack) - for coro in task.coroutine_stack - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - coroutine_stacks, - { - "Task-1": [ - ( - tuple([staggered.__file__, ANY, "staggered_race"]), - tuple([script_name, 21, "main"]), - ) - ], - "Task-2": [ - ( - tuple([script_name, 11, "deep"]), - tuple([script_name, 15, "c1"]), - tuple( - [ - staggered.__file__, - ANY, - "staggered_race..run_one_coro", - ] - ), - ) - ], - }, - ) + # Check all tasks are present + tasks_names = [ + task.task_name for task in stack_trace[0].awaited_by + ] + for task_name in ["Task-1", "Task-2"]: + self.assertIn(task_name, tasks_names) - # Now ensure the coroutine stacks for the awaited_by relationships are correct. - awaited_by_coroutine_stacks = { - task.task_name: sorted( - ( - id_to_task[coro.task_name].task_name, - tuple(tuple(frame) for frame in coro.call_stack), + # Check awaited_by relationships + relationships = self._get_awaited_by_relationships( + stack_trace ) - for coro in task.awaited_by - ) - for task in stack_trace[0].awaited_by - } - self.assertEqual( - awaited_by_coroutine_stacks, - { - "Task-1": [], - "Task-2": [ - ( - "Task-1", + self.assertEqual( + relationships, + { + "Task-1": set(), + "Task-2": {"Task-1"}, + }, + ) + + # Check coroutine stacks (using line numbers only to avoid + # flakiness from column offset variations when sampling + # catches different statements on the same line) + coroutine_stacks = self._extract_coroutine_stacks_lineno_only( + stack_trace + ) + self.assertEqual( + coroutine_stacks, + { + "Task-1": [ + ( + (staggered.__file__, ANY, "staggered_race", None), + (script_name, 21, "main", None), + ) + ], + "Task-2": [ + ( + (script_name, 11, "deep", None), + (script_name, 15, "c1", None), + (staggered.__file__, ANY, "staggered_race..run_one_coro", None), + ) + ], + }, + ) + + # Check awaited_by coroutine stacks (line numbers only) + id_to_task = self._get_task_id_map(stack_trace) + awaited_by_coroutine_stacks = { + task.task_name: sorted( ( + id_to_task[coro.task_name].task_name, tuple( - [staggered.__file__, ANY, "staggered_race"] + self._frame_to_lineno_tuple(frame) for frame in coro.call_stack ), - tuple([script_name, 21, "main"]), - ), + ) + for coro in task.awaited_by ) - ], - }, - ) + for task in stack_trace[0].awaited_by + } + self.assertEqual( + awaited_by_coroutine_stacks, + { + "Task-1": [], + "Task-2": [ + ( + "Task-1", + ( + (staggered.__file__, ANY, "staggered_race", None), + (script_name, 21, "main", None), + ), + ) + ], + }, + ) + finally: + _cleanup_sockets(client_socket, server_socket) @skip_if_not_supported @unittest.skipIf( @@ -824,6 +1238,10 @@ async def main(): "Test only runs on Linux with process_vm_readv support", ) def test_async_global_awaited_by(self): + # Reduced from 1000 to 100 to avoid file descriptor exhaustion + # when running tests in parallel (e.g., -j 20) + NUM_TASKS = 100 + port = find_unused_port() script = textwrap.dedent( f"""\ @@ -839,7 +1257,6 @@ def test_async_global_awaited_by(self): PORT = socket_helper.find_unused_port() connections = 0 - # Connect to the test process sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', {port})) @@ -862,23 +1279,16 @@ async def echo_client(message): assert message == data.decode() writer.close() await writer.wait_closed() - # Signal we are ready to sleep sock.sendall(b"ready") await asyncio.sleep(SHORT_TIMEOUT) async def echo_client_spam(server): async with asyncio.TaskGroup() as tg: - while connections < 1000: + while connections < {NUM_TASKS}: msg = list(ascii_lowercase + digits) random.shuffle(msg) tg.create_task(echo_client("".join(msg))) await asyncio.sleep(0) - # at least a 1000 tasks created. Each task will signal - # when is ready to avoid the race caused by the fact that - # tasks are waited on tg.__exit__ and we cannot signal when - # that happens otherwise - # at this point all client tasks completed without assertion errors - # let's wrap up the test server.close() await server.wait_closed() @@ -893,323 +1303,243 @@ async def main(): asyncio.run(main()) """ ) - stack_trace = None + with os_helper.temp_dir() as work_dir: script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) - # Create a socket server to communicate with the target process - server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - server_socket.bind(("localhost", port)) - server_socket.settimeout(SHORT_TIMEOUT) - server_socket.listen(1) + + server_socket = _create_server_socket(port) script_name = _make_test_script(script_dir, "script", script) client_socket = None + try: - p = subprocess.Popen([sys.executable, script_name]) - client_socket, _ = server_socket.accept() - server_socket.close() - for _ in range(1000): - expected_response = b"ready" - response = client_socket.recv(len(expected_response)) - self.assertEqual(response, expected_response) - for _ in busy_retry(SHORT_TIMEOUT): + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + # Wait for NUM_TASKS "ready" signals try: - all_awaited_by = get_all_awaited_by(p.pid) - except RuntimeError as re: - # This call reads a linked list in another process with - # no synchronization. That occasionally leads to invalid - # reads. Here we avoid making the test flaky. - msg = str(re) - if msg.startswith("Task list appears corrupted"): - continue - elif msg.startswith( - "Invalid linked list structure reading remote memory" - ): - continue - elif msg.startswith("Unknown error reading memory"): - continue - elif msg.startswith("Unhandled frame owner"): - continue - raise # Unrecognized exception, safest not to ignore it - else: - break - # expected: a list of two elements: 1 thread, 1 interp - self.assertEqual(len(all_awaited_by), 2) - # expected: a tuple with the thread ID and the awaited_by list - self.assertEqual(len(all_awaited_by[0]), 2) - # expected: no tasks in the fallback per-interp task list - self.assertEqual(all_awaited_by[1], (0, [])) - entries = all_awaited_by[0][1] - # expected: at least 1000 pending tasks - self.assertGreaterEqual(len(entries), 1000) - # the first three tasks stem from the code structure - main_stack = [ - FrameInfo([taskgroups.__file__, ANY, "TaskGroup._aexit"]), - FrameInfo( - [taskgroups.__file__, ANY, "TaskGroup.__aexit__"] - ), - FrameInfo([script_name, 60, "main"]), - ] - self.assertIn( - TaskInfo( - [ANY, "Task-1", [CoroInfo([main_stack, ANY])], []] - ), - entries, - ) - self.assertIn( - TaskInfo( - [ - ANY, - "server task", + _wait_for_n_signals(client_socket, b"ready", NUM_TASKS) + except RuntimeError as e: + self.fail(str(e)) + + all_awaited_by = get_all_awaited_by(p.pid) + + # Expected: a list of two elements: 1 thread, 1 interp + self.assertEqual(len(all_awaited_by), 2) + # Expected: a tuple with the thread ID and the awaited_by list + self.assertEqual(len(all_awaited_by[0]), 2) + # Expected: no tasks in the fallback per-interp task list + self.assertEqual(all_awaited_by[1], (0, [])) + + entries = all_awaited_by[0][1] + # Expected: at least NUM_TASKS pending tasks + self.assertGreaterEqual(len(entries), NUM_TASKS) + + # Check the main task structure + main_stack = [ + FrameInfo( + [taskgroups.__file__, ANY, "TaskGroup._aexit", ANY] + ), + FrameInfo( + [taskgroups.__file__, ANY, "TaskGroup.__aexit__", ANY] + ), + FrameInfo([script_name, ANY, "main", ANY]), + ] + self.assertIn( + TaskInfo( + [ANY, "Task-1", [CoroInfo([main_stack, ANY])], []] + ), + entries, + ) + self.assertIn( + TaskInfo( [ - CoroInfo( - [ + ANY, + "server task", + [ + CoroInfo( [ - FrameInfo( - [ - base_events.__file__, - ANY, - "Server.serve_forever", - ] - ) - ], - ANY, - ] - ) - ], - [ - CoroInfo( - [ + [ + FrameInfo( + [ + base_events.__file__, + ANY, + "Server.serve_forever", + ANY, + ] + ) + ], + ANY, + ] + ) + ], + [ + CoroInfo( [ - FrameInfo( - [ - taskgroups.__file__, - ANY, - "TaskGroup._aexit", - ] - ), - FrameInfo( - [ - taskgroups.__file__, - ANY, - "TaskGroup.__aexit__", - ] - ), - FrameInfo( - [script_name, ANY, "main"] - ), - ], - ANY, - ] - ) - ], - ] - ), - entries, - ) - self.assertIn( - TaskInfo( - [ - ANY, - "Task-4", + [ + FrameInfo( + [ + taskgroups.__file__, + ANY, + "TaskGroup._aexit", + ANY, + ] + ), + FrameInfo( + [ + taskgroups.__file__, + ANY, + "TaskGroup.__aexit__", + ANY, + ] + ), + FrameInfo( + [script_name, ANY, "main", ANY] + ), + ], + ANY, + ] + ) + ], + ] + ), + entries, + ) + self.assertIn( + TaskInfo( [ - CoroInfo( - [ + ANY, + "Task-4", + [ + CoroInfo( [ - FrameInfo( - [tasks.__file__, ANY, "sleep"] - ), - FrameInfo( - [ - script_name, - 38, - "echo_client", - ] - ), - ], - ANY, - ] - ) - ], - [ - CoroInfo( - [ + [ + FrameInfo( + [ + tasks.__file__, + ANY, + "sleep", + ANY, + ] + ), + FrameInfo( + [ + script_name, + ANY, + "echo_client", + ANY, + ] + ), + ], + ANY, + ] + ) + ], + [ + CoroInfo( [ - FrameInfo( - [ - taskgroups.__file__, - ANY, - "TaskGroup._aexit", - ] - ), - FrameInfo( - [ - taskgroups.__file__, - ANY, - "TaskGroup.__aexit__", - ] - ), - FrameInfo( - [ - script_name, - 41, - "echo_client_spam", - ] - ), - ], - ANY, - ] - ) - ], - ] - ), - entries, - ) + [ + FrameInfo( + [ + taskgroups.__file__, + ANY, + "TaskGroup._aexit", + ANY, + ] + ), + FrameInfo( + [ + taskgroups.__file__, + ANY, + "TaskGroup.__aexit__", + ANY, + ] + ), + FrameInfo( + [ + script_name, + ANY, + "echo_client_spam", + ANY, + ] + ), + ], + ANY, + ] + ) + ], + ] + ), + entries, + ) - expected_awaited_by = [ - CoroInfo( - [ - [ - FrameInfo( - [ - taskgroups.__file__, - ANY, - "TaskGroup._aexit", - ] - ), - FrameInfo( - [ - taskgroups.__file__, - ANY, - "TaskGroup.__aexit__", - ] - ), - FrameInfo( - [script_name, 41, "echo_client_spam"] - ), - ], - ANY, + # Find tasks awaited by echo_client_spam via TaskGroup + def matches_awaited_by_pattern(task): + if len(task.awaited_by) != 1: + return False + coro = task.awaited_by[0] + if len(coro.call_stack) != 3: + return False + funcnames = [f.funcname for f in coro.call_stack] + return funcnames == [ + "TaskGroup._aexit", + "TaskGroup.__aexit__", + "echo_client_spam", ] - ) - ] - tasks_with_awaited = [ - task - for task in entries - if task.awaited_by == expected_awaited_by - ] - self.assertGreaterEqual(len(tasks_with_awaited), 1000) - - # the final task will have some random number, but it should for - # sure be one of the echo client spam horde (In windows this is not true - # for some reason) - if sys.platform != "win32": - self.assertEqual( - tasks_with_awaited[-1].awaited_by, - entries[-1].awaited_by, - ) - except PermissionError: - self.skipTest( - "Insufficient permissions to read the stack trace" - ) - finally: - if client_socket is not None: - client_socket.close() - p.kill() - p.terminate() - p.wait(timeout=SHORT_TIMEOUT) - @skip_if_not_supported - @unittest.skipIf( - sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, - "Test only runs on Linux with process_vm_readv support", - ) - def test_self_trace(self): - stack_trace = get_stack_trace(os.getpid()) - # Is possible that there are more threads, so we check that the - # expected stack traces are in the result (looking at you Windows!) - this_tread_stack = None - for thread_id, stack in stack_trace: - if thread_id == threading.get_native_id(): - this_tread_stack = stack - break - self.assertIsNotNone(this_tread_stack) - self.assertEqual( - stack[:2], - [ - FrameInfo( - [ - __file__, - get_stack_trace.__code__.co_firstlineno + 2, - "get_stack_trace", - ] - ), - FrameInfo( - [ - __file__, - self.test_self_trace.__code__.co_firstlineno + 6, - "TestGetStackTrace.test_self_trace", + tasks_with_awaited = [ + task + for task in entries + if matches_awaited_by_pattern(task) ] - ), - ], - ) + self.assertGreaterEqual(len(tasks_with_awaited), NUM_TASKS) + + # Final task should be from echo client spam (not on Windows) + if sys.platform != "win32": + self.assertEqual( + tasks_with_awaited[-1].awaited_by, + entries[-1].awaited_by, + ) + finally: + _cleanup_sockets(client_socket, server_socket) @skip_if_not_supported @unittest.skipIf( sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, "Test only runs on Linux with process_vm_readv support", ) - @requires_gil_enabled("Free threaded builds don't have an 'active thread'") - def test_only_active_thread(self): - # Test that only_active_thread parameter works correctly + def test_async_global_awaited_by_from_non_main_thread(self): port = find_unused_port() script = textwrap.dedent( f"""\ - import time, sys, socket, threading + import asyncio + import socket + import threading + import time - # Connect to the test process sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(('localhost', {port})) - def worker_thread(name, barrier, ready_event): - barrier.wait() # Synchronize thread start - ready_event.wait() # Wait for main thread signal - # Sleep to keep thread alive - time.sleep(10_000) - - def main_work(): - # Do busy work to hold the GIL - sock.sendall(b"working\\n") - count = 0 - while count < 100000000: - count += 1 - if count % 10000000 == 0: - pass # Keep main thread busy - sock.sendall(b"done\\n") - - # Create synchronization primitives - num_threads = 3 - barrier = threading.Barrier(num_threads + 1) # +1 for main thread - ready_event = threading.Event() - - # Start worker threads - threads = [] - for i in range(num_threads): - t = threading.Thread(target=worker_thread, args=(f"Worker-{{i}}", barrier, ready_event)) - t.start() - threads.append(t) - - # Wait for all threads to be ready - barrier.wait() - - # Signal ready to parent process - sock.sendall(b"ready\\n") + async def worker_main(): + task = asyncio.create_task( + asyncio.sleep(10_000), + name="worker task", + ) + await asyncio.sleep(0) + sock.sendall(f"ready:{{threading.get_native_id()}}\\n".encode()) + await task - # Signal threads to start waiting - ready_event.set() + def run_worker_loop(): + asyncio.run(worker_main()) - # Now do busy work to hold the GIL - main_work() + threading.Thread( + target=run_worker_loop, + name="async-worker", + daemon=True, + ).start() + time.sleep(10_000) """ ) @@ -1217,88 +1547,2463 @@ def main_work(): script_dir = os.path.join(work_dir, "script_pkg") os.mkdir(script_dir) - # Create a socket server to communicate with the target process - server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - server_socket.bind(("localhost", port)) - server_socket.settimeout(SHORT_TIMEOUT) - server_socket.listen(1) - + server_socket = _create_server_socket(port) script_name = _make_test_script(script_dir, "script", script) client_socket = None + try: - p = subprocess.Popen([sys.executable, script_name]) - client_socket, _ = server_socket.accept() - server_socket.close() + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + response = _wait_for_signal(client_socket, b"ready:") + worker_thread_id = int( + response.split(b"ready:", 1)[1].splitlines()[0] + ) + + for _ in busy_retry(SHORT_TIMEOUT): + all_awaited_by = get_all_awaited_by(p.pid) + if any( + task.task_name == "worker task" + for info in all_awaited_by + if info.thread_id == worker_thread_id + for task in info.awaited_by + ): + break + else: + self.fail( + "get_all_awaited_by() did not report " + "the asyncio task from the non-main thread" + ) + finally: + _cleanup_sockets(client_socket, server_socket) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_async_remote_stack_trace_from_non_main_thread(self): + port = find_unused_port() + script = textwrap.dedent( + f"""\ + import asyncio + import socket + import threading + import time + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def blocking_call(): + sock.sendall(f"ready:{{threading.get_native_id()}}\\n".encode()) + time.sleep(10_000) + + async def worker_task(): + await asyncio.sleep(0) + blocking_call() + + async def worker_main(): + task = asyncio.create_task( + worker_task(), + name="worker task", + ) + await task + + def run_worker_loop(): + asyncio.run(worker_main()) + + threading.Thread( + target=run_worker_loop, + name="async-worker", + daemon=True, + ).start() + time.sleep(10_000) + """ + ) + + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + + server_socket = _create_server_socket(port) + script_name = _make_test_script(script_dir, "script", script) + client_socket = None + + try: + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + response = _wait_for_signal(client_socket, b"ready:") + worker_thread_id = int( + response.split(b"ready:", 1)[1].splitlines()[0] + ) + + for _ in busy_retry(SHORT_TIMEOUT): + stack_trace = get_async_stack_trace(p.pid) + if any( + task.task_name == "worker task" + for info in stack_trace + if info.thread_id == worker_thread_id + for task in info.awaited_by + ): + break + else: + self.fail( + "get_async_stack_trace() did not report " + "the running asyncio task from the non-main thread" + ) + finally: + _cleanup_sockets(client_socket, server_socket) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_self_trace(self): + stack_trace = get_stack_trace(os.getpid()) + + this_thread_stack = None + for interpreter_info in stack_trace: + for thread_info in interpreter_info.threads: + if thread_info.thread_id == threading.get_native_id(): + this_thread_stack = thread_info.frame_info + break + if this_thread_stack: + break + + self.assertIsNotNone(this_thread_stack) + # Check the top two frames + self.assertGreaterEqual(len(this_thread_stack), 2) + self.assertEqual(this_thread_stack[0].funcname, "get_stack_trace") + self.assertTrue(this_thread_stack[0].filename.endswith("test_external_inspection.py")) + self.assertEqual(this_thread_stack[1].funcname, "TestGetStackTrace.test_self_trace") + self.assertTrue(this_thread_stack[1].filename.endswith("test_external_inspection.py")) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + @requires_subinterpreters + def test_subinterpreter_stack_trace(self): + port = find_unused_port() + + import pickle + + subinterp_code = textwrap.dedent(f""" + import socket + import time + + def sub_worker(): + def nested_func(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + sock.sendall(b"ready:sub\\n") + time.sleep(10_000) + nested_func() + + sub_worker() + """).strip() + + pickled_code = pickle.dumps(subinterp_code) + + script = textwrap.dedent( + f""" + from concurrent import interpreters + import time + import sys + import socket + import threading + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def main_worker(): + sock.sendall(b"ready:main\\n") + time.sleep(10_000) + + def run_subinterp(): + subinterp = interpreters.create() + import pickle + pickled_code = {pickled_code!r} + subinterp_code = pickle.loads(pickled_code) + subinterp.exec(subinterp_code) + + sub_thread = threading.Thread(target=run_subinterp) + sub_thread.start() + + main_thread = threading.Thread(target=main_worker) + main_thread.start() + + main_thread.join() + sub_thread.join() + """ + ) + + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + + server_socket = _create_server_socket(port) + script_name = _make_test_script(script_dir, "script", script) + client_sockets = [] + + try: + with _managed_subprocess([sys.executable, script_name]) as p: + # Accept connections from both main and subinterpreter + responses = set() + while len(responses) < 2: + try: + client_socket, _ = server_socket.accept() + client_sockets.append(client_socket) + response = client_socket.recv(1024) + if b"ready:main" in response: + responses.add("main") + if b"ready:sub" in response: + responses.add("sub") + except socket.timeout: + break + + server_socket.close() + server_socket = None + + stack_trace = get_stack_trace(p.pid) + + # Verify we have at least one interpreter + self.assertGreaterEqual(len(stack_trace), 1) + + # Look for main interpreter (ID 0) and subinterpreter (ID > 0) + main_interp = None + sub_interp = None + for interpreter_info in stack_trace: + if interpreter_info.interpreter_id == 0: + main_interp = interpreter_info + elif interpreter_info.interpreter_id > 0: + sub_interp = interpreter_info + + self.assertIsNotNone( + main_interp, "Main interpreter should be present" + ) + + # Check main interpreter has expected stack trace + main_found = self._find_frame_in_trace( + [main_interp], lambda f: f.funcname == "main_worker" + ) + self.assertIsNotNone( + main_found, + "Main interpreter should have main_worker in stack", + ) + + # If subinterpreter is present, check its stack trace + if sub_interp: + sub_found = self._find_frame_in_trace( + [sub_interp], + lambda f: f.funcname + in ("sub_worker", "nested_func"), + ) + self.assertIsNotNone( + sub_found, + "Subinterpreter should have sub_worker or nested_func in stack", + ) + finally: + _cleanup_sockets(*client_sockets, server_socket) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + @requires_subinterpreters + def test_multiple_subinterpreters_with_threads(self): + port = find_unused_port() + + import pickle + + subinterp1_code = textwrap.dedent(f""" + import socket + import time + import threading + + def worker1(): + def nested_func(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + sock.sendall(b"ready:sub1-t1\\n") + time.sleep(10_000) + nested_func() + + def worker2(): + def nested_func(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + sock.sendall(b"ready:sub1-t2\\n") + time.sleep(10_000) + nested_func() + + t1 = threading.Thread(target=worker1) + t2 = threading.Thread(target=worker2) + t1.start() + t2.start() + t1.join() + t2.join() + """).strip() + + subinterp2_code = textwrap.dedent(f""" + import socket + import time + import threading + + def worker1(): + def nested_func(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + sock.sendall(b"ready:sub2-t1\\n") + time.sleep(10_000) + nested_func() + + def worker2(): + def nested_func(): + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + sock.sendall(b"ready:sub2-t2\\n") + time.sleep(10_000) + nested_func() + + t1 = threading.Thread(target=worker1) + t2 = threading.Thread(target=worker2) + t1.start() + t2.start() + t1.join() + t2.join() + """).strip() + + pickled_code1 = pickle.dumps(subinterp1_code) + pickled_code2 = pickle.dumps(subinterp2_code) + + script = textwrap.dedent( + f""" + from concurrent import interpreters + import time + import sys + import socket + import threading + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def main_worker(): + sock.sendall(b"ready:main\\n") + time.sleep(10_000) + + def run_subinterp1(): + subinterp = interpreters.create() + import pickle + pickled_code = {pickled_code1!r} + subinterp_code = pickle.loads(pickled_code) + subinterp.exec(subinterp_code) + + def run_subinterp2(): + subinterp = interpreters.create() + import pickle + pickled_code = {pickled_code2!r} + subinterp_code = pickle.loads(pickled_code) + subinterp.exec(subinterp_code) + + sub1_thread = threading.Thread(target=run_subinterp1) + sub2_thread = threading.Thread(target=run_subinterp2) + sub1_thread.start() + sub2_thread.start() + + main_thread = threading.Thread(target=main_worker) + main_thread.start() + + main_thread.join() + sub1_thread.join() + sub2_thread.join() + """ + ) + + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + + server_socket = _create_server_socket(port, backlog=5) + script_name = _make_test_script(script_dir, "script", script) + client_sockets = [] + + try: + with _managed_subprocess([sys.executable, script_name]) as p: + # Accept connections from main and all subinterpreter threads + expected_responses = { + "ready:main", + "ready:sub1-t1", + "ready:sub1-t2", + "ready:sub2-t1", + "ready:sub2-t2", + } + responses = set() + + while len(responses) < 5: + try: + client_socket, _ = server_socket.accept() + client_sockets.append(client_socket) + response = client_socket.recv(1024) + response_str = response.decode().strip() + if response_str in expected_responses: + responses.add(response_str) + except socket.timeout: + break + + server_socket.close() + server_socket = None + + stack_trace = get_stack_trace(p.pid) + + # Verify we have multiple interpreters + self.assertGreaterEqual(len(stack_trace), 2) + + # Count interpreters by ID + interpreter_ids = { + interp.interpreter_id for interp in stack_trace + } + self.assertIn( + 0, + interpreter_ids, + "Main interpreter should be present", + ) + self.assertGreaterEqual(len(interpreter_ids), 3) + + # Count total threads + total_threads = sum( + len(interp.threads) for interp in stack_trace + ) + self.assertGreaterEqual(total_threads, 5) + + # Look for expected function names + all_funcnames = set() + for interpreter_info in stack_trace: + for thread_info in interpreter_info.threads: + for frame in thread_info.frame_info: + all_funcnames.add(frame.funcname) + + expected_funcs = { + "main_worker", + "worker1", + "worker2", + "nested_func", + } + found_funcs = expected_funcs.intersection(all_funcnames) + self.assertGreater(len(found_funcs), 0) + finally: + _cleanup_sockets(*client_sockets, server_socket) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + @requires_gil_enabled("Free threaded builds don't have an 'active thread'") + def test_only_active_thread(self): + port = find_unused_port() + script = textwrap.dedent( + f"""\ + import time, sys, socket, threading + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def worker_thread(name, barrier, ready_event): + barrier.wait() + ready_event.wait() + time.sleep(10_000) + + def main_work(): + sock.sendall(b"working\\n") + count = 0 + while count < 100000000: + count += 1 + if count % 10000000 == 0: + pass + sock.sendall(b"done\\n") + + num_threads = 3 + barrier = threading.Barrier(num_threads + 1) + ready_event = threading.Event() + + threads = [] + for i in range(num_threads): + t = threading.Thread(target=worker_thread, args=(f"Worker-{{i}}", barrier, ready_event)) + t.start() + threads.append(t) + + barrier.wait() + sock.sendall(b"ready\\n") + ready_event.set() + main_work() + """ + ) + + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + + server_socket = _create_server_socket(port) + script_name = _make_test_script(script_dir, "script", script) + client_socket = None + + try: + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + # Wait for ready and working signals + _wait_for_signal(client_socket, [b"ready", b"working"]) + + # Get stack trace with all threads + unwinder_all = RemoteUnwinder(p.pid, all_threads=True) + for _ in busy_retry(SHORT_TIMEOUT): + with contextlib.suppress(*TRANSIENT_ERRORS): + all_traces = unwinder_all.get_stack_trace() + found = self._find_frame_in_trace( + all_traces, + lambda f: f.funcname == "main_work" + and f.location.lineno > 12, + ) + if found: + break + else: + self.fail( + "Main thread did not start its busy work on time" + ) + + # Get stack trace with only GIL holder + unwinder_gil = RemoteUnwinder( + p.pid, only_active_thread=True + ) + # Use condition to retry until we capture a thread holding the GIL + # (sampling may catch moments with no GIL holder on slow CI) + gil_traces = _get_stack_trace_with_retry( + unwinder_gil, + condition=lambda t: sum(len(i.threads) for i in t) >= 1, + ) + + # Count threads + total_threads = sum( + len(interp.threads) for interp in all_traces + ) + self.assertGreater(total_threads, 1) + + total_gil_threads = sum( + len(interp.threads) for interp in gil_traces + ) + self.assertEqual(total_gil_threads, 1) + + # Get the GIL holder thread ID + gil_thread_id = None + for interpreter_info in gil_traces: + if interpreter_info.threads: + gil_thread_id = interpreter_info.threads[ + 0 + ].thread_id + break + + # Get all thread IDs + all_thread_ids = [] + for interpreter_info in all_traces: + for thread_info in interpreter_info.threads: + all_thread_ids.append(thread_info.thread_id) + + self.assertIn(gil_thread_id, all_thread_ids) + finally: + _cleanup_sockets(client_socket, server_socket) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_opcodes_collection(self): + """Test that opcodes are collected when the opcodes flag is set.""" + script = textwrap.dedent( + """\ + import time, sys, socket + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def foo(): + sock.sendall(b"ready") + time.sleep(10_000) + + foo() + """ + ) + + def get_trace_with_opcodes(pid): + return RemoteUnwinder(pid, opcodes=True).get_stack_trace() + + stack_trace, _ = self._run_script_and_get_trace( + script, get_trace_with_opcodes, wait_for_signals=b"ready" + ) + + # Find our foo frame and verify it has an opcode + foo_frame = self._find_frame_in_trace( + stack_trace, lambda f: f.funcname == "foo" + ) + self.assertIsNotNone(foo_frame, "Could not find foo frame") + self.assertIsInstance(foo_frame.opcode, int) + self.assertGreaterEqual(foo_frame.opcode, 0) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_location_tuple_format(self): + """Test that location is a 4-tuple (lineno, end_lineno, col_offset, end_col_offset).""" + script = textwrap.dedent( + """\ + import time, sys, socket + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def foo(): + sock.sendall(b"ready") + time.sleep(10_000) + + foo() + """ + ) + + def get_trace_with_opcodes(pid): + return RemoteUnwinder(pid, opcodes=True).get_stack_trace() + + stack_trace, _ = self._run_script_and_get_trace( + script, get_trace_with_opcodes, wait_for_signals=b"ready" + ) + + # Find our foo frame + foo_frame = self._find_frame_in_trace( + stack_trace, lambda f: f.funcname == "foo" + ) + self.assertIsNotNone(foo_frame, "Could not find foo frame") + + # Check location is a 4-tuple with valid values + location = foo_frame.location + self.assertIsInstance(location, tuple) + self.assertEqual(len(location), 4) + lineno, end_lineno, col_offset, end_col_offset = location + self.assertIsInstance(lineno, int) + self.assertGreater(lineno, 0) + self.assertIsInstance(end_lineno, int) + self.assertGreaterEqual(end_lineno, lineno) + self.assertIsInstance(col_offset, int) + self.assertGreaterEqual(col_offset, 0) + self.assertIsInstance(end_col_offset, int) + self.assertGreaterEqual(end_col_offset, col_offset) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_location_tuple_exact_values(self): + """Test exact values of location tuple including column offsets.""" + script = textwrap.dedent( + """\ + import time, sys, socket + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def foo(): + sock.sendall(b"ready") + time.sleep(10_000) + + foo() + """ + ) + + def get_trace_with_opcodes(pid): + return RemoteUnwinder(pid, opcodes=True).get_stack_trace() + + stack_trace, _ = self._run_script_and_get_trace( + script, get_trace_with_opcodes, wait_for_signals=b"ready" + ) + + foo_frame = self._find_frame_in_trace( + stack_trace, lambda f: f.funcname == "foo" + ) + self.assertIsNotNone(foo_frame, "Could not find foo frame") + + # Can catch either sock.sendall (line 7) or time.sleep (line 8) + location = foo_frame.location + valid_locations = [ + (7, 7, 4, 26), # sock.sendall(b"ready") + (8, 8, 4, 22), # time.sleep(10_000) + ] + actual = (location.lineno, location.end_lineno, + location.col_offset, location.end_col_offset) + self.assertIn(actual, valid_locations) + + @skip_if_not_supported + @unittest.skipIf(sys._is_gil_enabled(), "Requires free-threading") + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Requires process_vm_readv", + ) + def test_tlbc_cache_refresh_after_growth(self): + # Reproducer from gh-157660. + script = textwrap.dedent("""\ + import os, threading + from _remote_debugging import RemoteUnwinder + from _queue import SimpleQueue + from test import support + + go = threading.Lock() + stop = threading.Lock() + go.acquire() + stop.acquire() + ready = SimpleQueue() + + def leaf(): + ready.put(None) + stop.acquire() + + def start_leaf(): + ready.put(None) + go.acquire() + leaf() + + def park(): + ready.put(None) + stop.acquire() + + def leaf_count(u): + return sum( + f.funcname == "leaf" + for i in u.get_stack_trace() + for t in i.threads for f in t.frame_info + ) + + # SimpleQueue.put() and Lock.acquire() do not push Python frames. + # Once notified, the worker's stack stays stable until go is released. + threading.Thread(target=leaf, daemon=True).start() + ready.get(timeout=support.SHORT_TIMEOUT) + for _ in range(16): + threading.Thread(target=park, daemon=True).start() + ready.get(timeout=support.SHORT_TIMEOUT) + threading.Thread(target=start_leaf, daemon=True).start() + ready.get(timeout=support.SHORT_TIMEOUT) + + u = RemoteUnwinder(os.getpid(), all_threads=True, cache_frames=False) + assert leaf_count(u) == 1 + go.release() + ready.get(timeout=support.SHORT_TIMEOUT) + assert leaf_count(u) == 2 + """) + result = subprocess.run( + [sys.executable, "-X", "gil=0", "-X", "tlbc=1", "-c", script], + capture_output=True, + text=True, + timeout=SHORT_TIMEOUT, + ) + self.assertEqual( + result.returncode, 0, + f"stdout: {result.stdout}\nstderr: {result.stderr}", + ) + + @skip_if_not_supported + @unittest.skipIf(sys._is_gil_enabled(), "Requires free-threading") + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Requires process_vm_readv", + ) + def test_tlbc_cache_refresh_after_slot_fill(self): + # Reproducer from gh-157660. + script = textwrap.dedent("""\ + import os, threading + from _remote_debugging import RemoteUnwinder + from _queue import SimpleQueue + + go = threading.Lock() + stop = threading.Lock() + go.acquire() + stop.acquire() + ready = SimpleQueue() + + def leaf(): + ready.put(None) + stop.acquire() + + def start_leaf(): + ready.put(None) + go.acquire() + leaf() + + from test import support + + def lines(u): + return sorted( + f.location.lineno + for i in u.get_stack_trace() + for t in i.threads for f in t.frame_info + if f.funcname == "leaf" + ) + + # SimpleQueue.put() and Lock.acquire() do not push Python frames. + # Once notified, the worker's stack stays stable until go is released. + threading.Thread(target=leaf, daemon=True).start() + ready.get(timeout=support.SHORT_TIMEOUT) + threading.Thread(target=start_leaf, daemon=True).start() + ready.get(timeout=support.SHORT_TIMEOUT) + u = RemoteUnwinder(os.getpid(), all_threads=True, cache_frames=False) + before = lines(u) + # The notification can be observed before put() returns, so either + # line in leaf() is a valid sample. + assert before in ([12], [13]), before + go.release() + ready.get(timeout=support.SHORT_TIMEOUT) + cached = lines(u) + assert len(cached) == 2, cached + assert all(line in (12, 13) for line in cached), cached + """) + result = subprocess.run( + [sys.executable, "-X", "gil=0", "-X", "tlbc=1", "-c", script], + capture_output=True, + text=True, + timeout=SHORT_TIMEOUT, + ) + self.assertEqual( + result.returncode, 0, + f"stdout: {result.stdout}\nstderr: {result.stderr}", + ) + + +class TestUnsupportedPlatformHandling(unittest.TestCase): + @unittest.skipIf( + sys.platform in ("linux", "darwin", "win32"), + "Test only runs on unsupported platforms (not Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_unsupported_platform_error(self): + with self.assertRaises(RuntimeError) as cm: + RemoteUnwinder(os.getpid()) + + self.assertIn( + "Reading the PyRuntime section is not supported on this platform", + str(cm.exception), + ) + + +@requires_remote_subprocess_debugging() +class TestDetectionOfThreadStatus(RemoteInspectionTestBase): + def _run_thread_status_test(self, mode, check_condition): + """ + Common pattern for thread status detection tests. + + Args: + mode: Profiling mode (PROFILING_MODE_CPU, PROFILING_MODE_GIL, etc.) + check_condition: Function(statuses, sleeper_tid, busy_tid) -> bool + """ + port = find_unused_port() + script = textwrap.dedent( + f"""\ + import time, sys, socket, threading + import os + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('localhost', {port})) + + def sleeper(): + tid = threading.get_native_id() + sock.sendall(f'ready:sleeper:{{tid}}\\n'.encode()) + time.sleep(10000) + + def busy(): + tid = threading.get_native_id() + sock.sendall(f'ready:busy:{{tid}}\\n'.encode()) + x = 0 + while True: + x = x + 1 + time.sleep(0.5) + + t1 = threading.Thread(target=sleeper) + t2 = threading.Thread(target=busy) + t1.start() + t2.start() + sock.sendall(b'ready:main\\n') + t1.join() + t2.join() + sock.close() + """ + ) + + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + + server_socket = _create_server_socket(port) + script_name = _make_test_script( + script_dir, "thread_status_script", script + ) + client_socket = None + + try: + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + # Wait for all ready signals and parse TIDs + response = _wait_for_signal( + client_socket, + [b"ready:main", b"ready:sleeper", b"ready:busy"], + ) + + sleeper_tid = None + busy_tid = None + for line in response.split(b"\n"): + if line.startswith(b"ready:sleeper:"): + try: + sleeper_tid = int(line.split(b":")[-1]) + except (ValueError, IndexError): + pass + elif line.startswith(b"ready:busy:"): + try: + busy_tid = int(line.split(b":")[-1]) + except (ValueError, IndexError): + pass + + self.assertIsNotNone( + sleeper_tid, "Sleeper thread id not received" + ) + self.assertIsNotNone( + busy_tid, "Busy thread id not received" + ) + + # Sample until we see expected thread states + statuses = {} + unwinder = RemoteUnwinder( + p.pid, + all_threads=True, + mode=mode, + skip_non_matching_threads=False, + ) + for _ in busy_retry(SHORT_TIMEOUT): + with contextlib.suppress(*TRANSIENT_ERRORS): + traces = unwinder.get_stack_trace() + statuses = self._get_thread_statuses(traces) + + if check_condition( + statuses, sleeper_tid, busy_tid + ): + break + + return statuses, sleeper_tid, busy_tid + finally: + _cleanup_sockets(client_socket, server_socket) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_thread_status_detection(self): + def check_cpu_status(statuses, sleeper_tid, busy_tid): + return ( + sleeper_tid in statuses + and busy_tid in statuses + and not (statuses[sleeper_tid] & THREAD_STATUS_ON_CPU) + and (statuses[busy_tid] & THREAD_STATUS_ON_CPU) + ) + + statuses, sleeper_tid, busy_tid = self._run_thread_status_test( + PROFILING_MODE_CPU, check_cpu_status + ) + + self.assertIn(sleeper_tid, statuses) + self.assertIn(busy_tid, statuses) + self.assertFalse( + statuses[sleeper_tid] & THREAD_STATUS_ON_CPU, + "Sleeper thread should be off CPU", + ) + self.assertTrue( + statuses[busy_tid] & THREAD_STATUS_ON_CPU, + "Busy thread should be on CPU", + ) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_thread_status_gil_detection(self): + def check_gil_status(statuses, sleeper_tid, busy_tid): + return ( + sleeper_tid in statuses + and busy_tid in statuses + and not (statuses[sleeper_tid] & THREAD_STATUS_HAS_GIL) + and (statuses[busy_tid] & THREAD_STATUS_HAS_GIL) + ) + + statuses, sleeper_tid, busy_tid = self._run_thread_status_test( + PROFILING_MODE_GIL, check_gil_status + ) + + self.assertIn(sleeper_tid, statuses) + self.assertIn(busy_tid, statuses) + self.assertFalse( + statuses[sleeper_tid] & THREAD_STATUS_HAS_GIL, + "Sleeper thread should not have GIL", + ) + self.assertTrue( + statuses[busy_tid] & THREAD_STATUS_HAS_GIL, + "Busy thread should have GIL", + ) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_thread_status_all_mode_detection(self): + port = find_unused_port() + script = textwrap.dedent( + f"""\ + import socket + import threading + import time + import sys + + def sleeper_thread(): + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"sleeper:" + str(threading.get_native_id()).encode()) + while True: + time.sleep(1) + + def busy_thread(): + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"busy:" + str(threading.get_native_id()).encode()) + while True: + sum(range(100000)) + + t1 = threading.Thread(target=sleeper_thread) + t2 = threading.Thread(target=busy_thread) + t1.start() + t2.start() + t1.join() + t2.join() + """ + ) + + with os_helper.temp_dir() as tmp_dir: + script_file = make_script(tmp_dir, "script", script) + server_socket = _create_server_socket(port, backlog=2) + client_sockets = [] + + try: + with _managed_subprocess( + [sys.executable, script_file], + ) as p: + sleeper_tid = None + busy_tid = None + + # Receive thread IDs from the child process + for _ in range(2): + client_socket, _ = server_socket.accept() + client_sockets.append(client_socket) + line = client_socket.recv(1024) + if line: + if line.startswith(b"sleeper:"): + try: + sleeper_tid = int(line.split(b":")[-1]) + except (ValueError, IndexError): + pass + elif line.startswith(b"busy:"): + try: + busy_tid = int(line.split(b":")[-1]) + except (ValueError, IndexError): + pass + + server_socket.close() + server_socket = None + + statuses = {} + unwinder = RemoteUnwinder( + p.pid, + all_threads=True, + mode=PROFILING_MODE_ALL, + skip_non_matching_threads=False, + ) + for _ in busy_retry(SHORT_TIMEOUT): + with contextlib.suppress(*TRANSIENT_ERRORS): + traces = unwinder.get_stack_trace() + statuses = self._get_thread_statuses(traces) + + # Check ALL mode provides both GIL and CPU info + if ( + sleeper_tid in statuses + and busy_tid in statuses + and not ( + statuses[sleeper_tid] + & THREAD_STATUS_ON_CPU + ) + and not ( + statuses[sleeper_tid] + & THREAD_STATUS_HAS_GIL + ) + and (statuses[busy_tid] & THREAD_STATUS_ON_CPU) + and ( + statuses[busy_tid] & THREAD_STATUS_HAS_GIL + ) + ): + break + + self.assertIsNotNone( + sleeper_tid, "Sleeper thread id not received" + ) + self.assertIsNotNone( + busy_tid, "Busy thread id not received" + ) + self.assertIn(sleeper_tid, statuses) + self.assertIn(busy_tid, statuses) + + # Sleeper: off CPU, no GIL + self.assertFalse( + statuses[sleeper_tid] & THREAD_STATUS_ON_CPU, + "Sleeper should be off CPU", + ) + self.assertFalse( + statuses[sleeper_tid] & THREAD_STATUS_HAS_GIL, + "Sleeper should not have GIL", + ) + + # Busy: on CPU, has GIL + self.assertTrue( + statuses[busy_tid] & THREAD_STATUS_ON_CPU, + "Busy should be on CPU", + ) + self.assertTrue( + statuses[busy_tid] & THREAD_STATUS_HAS_GIL, + "Busy should have GIL", + ) + finally: + _cleanup_sockets(*client_sockets, server_socket) + + def _make_exception_test_script(self, port): + """Create script with exception and normal threads for testing.""" + return textwrap.dedent( + f"""\ + import socket + import threading + import time + + def exception_thread(): + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"exception:" + str(threading.get_native_id()).encode()) + try: + raise ValueError("test exception") + except ValueError: + while True: + time.sleep(0.01) + + def normal_thread(): + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"normal:" + str(threading.get_native_id()).encode()) + while True: + sum(range(1000)) + + t1 = threading.Thread(target=exception_thread) + t2 = threading.Thread(target=normal_thread) + t1.start() + t2.start() + t1.join() + t2.join() + """ + ) + + @contextmanager + def _run_exception_test_process(self): + """Context manager to run exception test script and yield thread IDs and process.""" + port = find_unused_port() + script = self._make_exception_test_script(port) + + with os_helper.temp_dir() as tmp_dir: + script_file = make_script(tmp_dir, "script", script) + server_socket = _create_server_socket(port, backlog=2) + client_sockets = [] + + try: + with _managed_subprocess([sys.executable, script_file]) as p: + exception_tid = None + normal_tid = None + + for _ in range(2): + client_socket, _ = server_socket.accept() + client_sockets.append(client_socket) + line = client_socket.recv(1024) + if line: + if line.startswith(b"exception:"): + try: + exception_tid = int(line.split(b":")[-1]) + except (ValueError, IndexError): + pass + elif line.startswith(b"normal:"): + try: + normal_tid = int(line.split(b":")[-1]) + except (ValueError, IndexError): + pass + + server_socket.close() + server_socket = None + + yield p, exception_tid, normal_tid + finally: + _cleanup_sockets(*client_sockets, server_socket) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_thread_status_exception_detection(self): + """Test that THREAD_STATUS_HAS_EXCEPTION is set when thread has an active exception.""" + with self._run_exception_test_process() as (p, exception_tid, normal_tid): + self.assertIsNotNone(exception_tid, "Exception thread id not received") + self.assertIsNotNone(normal_tid, "Normal thread id not received") + + statuses = {} + unwinder = RemoteUnwinder( + p.pid, + all_threads=True, + mode=PROFILING_MODE_ALL, + skip_non_matching_threads=False, + ) + for _ in busy_retry(SHORT_TIMEOUT): + with contextlib.suppress(*TRANSIENT_ERRORS): + traces = unwinder.get_stack_trace() + statuses = self._get_thread_statuses(traces) + + if ( + exception_tid in statuses + and normal_tid in statuses + and (statuses[exception_tid] & THREAD_STATUS_HAS_EXCEPTION) + and not (statuses[normal_tid] & THREAD_STATUS_HAS_EXCEPTION) + ): + break + + self.assertIn(exception_tid, statuses) + self.assertIn(normal_tid, statuses) + self.assertTrue( + statuses[exception_tid] & THREAD_STATUS_HAS_EXCEPTION, + "Exception thread should have HAS_EXCEPTION flag", + ) + self.assertFalse( + statuses[normal_tid] & THREAD_STATUS_HAS_EXCEPTION, + "Normal thread should not have HAS_EXCEPTION flag", + ) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_thread_status_exception_mode_filtering(self): + """Test that PROFILING_MODE_EXCEPTION correctly filters threads.""" + with self._run_exception_test_process() as (p, exception_tid, normal_tid): + self.assertIsNotNone(exception_tid, "Exception thread id not received") + self.assertIsNotNone(normal_tid, "Normal thread id not received") + + unwinder = RemoteUnwinder( + p.pid, + all_threads=True, + mode=PROFILING_MODE_EXCEPTION, + skip_non_matching_threads=True, + ) + for _ in busy_retry(SHORT_TIMEOUT): + with contextlib.suppress(*TRANSIENT_ERRORS): + traces = unwinder.get_stack_trace() + statuses = self._get_thread_statuses(traces) + + if exception_tid in statuses: + self.assertNotIn( + normal_tid, + statuses, + "Normal thread should be filtered out in exception mode", + ) + return + + self.fail("Never found exception thread in exception mode") + +@requires_remote_subprocess_debugging() +class TestExceptionDetectionScenarios(RemoteInspectionTestBase): + """Test exception detection across all scenarios. + + This class verifies the exact conditions under which THREAD_STATUS_HAS_EXCEPTION + is set. Each test covers a specific scenario: + + 1. except_block: Thread inside except block + -> SHOULD have HAS_EXCEPTION (exc_info->exc_value is set) + + 2. finally_propagating: Exception propagating through finally block + -> SHOULD have HAS_EXCEPTION (current_exception is set) + + 3. finally_after_except: Finally block after except handled exception + -> Should NOT have HAS_EXCEPTION (exc_info cleared after except) + + 4. finally_no_exception: Finally block with no exception raised + -> Should NOT have HAS_EXCEPTION (no exception state) + """ + + def _make_single_scenario_script(self, port, scenario): + """Create script for a single exception scenario.""" + scenarios = { + "except_block": f"""\ +import socket +import threading +import time + +def target_thread(): + '''Inside except block - exception info is present''' + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"ready:" + str(threading.get_native_id()).encode()) + try: + raise ValueError("test") + except ValueError: + while True: + time.sleep(0.01) + +t = threading.Thread(target=target_thread) +t.start() +t.join() +""", + "finally_propagating": f"""\ +import socket +import threading +import time + +def target_thread(): + '''Exception propagating through finally - current_exception is set''' + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"ready:" + str(threading.get_native_id()).encode()) + try: + try: + raise ValueError("propagating") + finally: + # Exception is propagating through here + while True: + time.sleep(0.01) + except: + pass # Never reached due to infinite loop + +t = threading.Thread(target=target_thread) +t.start() +t.join() +""", + "finally_after_except": f"""\ +import socket +import threading +import time + +def target_thread(): + '''Finally runs after except handled - exc_info is cleared''' + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"ready:" + str(threading.get_native_id()).encode()) + try: + raise ValueError("test") + except ValueError: + pass # Exception caught and handled + finally: + while True: + time.sleep(0.01) + +t = threading.Thread(target=target_thread) +t.start() +t.join() +""", + "finally_no_exception": f"""\ +import socket +import threading +import time + +def target_thread(): + '''Finally with no exception at all''' + conn = socket.create_connection(("localhost", {port})) + conn.sendall(b"ready:" + str(threading.get_native_id()).encode()) + try: + pass # No exception + finally: + while True: + time.sleep(0.01) + +t = threading.Thread(target=target_thread) +t.start() +t.join() +""", + } + + return scenarios[scenario] + + @contextmanager + def _run_scenario_process(self, scenario): + """Context manager to run a single scenario and yield thread ID and process.""" + port = find_unused_port() + script = self._make_single_scenario_script(port, scenario) + + with os_helper.temp_dir() as tmp_dir: + script_file = make_script(tmp_dir, "script", script) + server_socket = _create_server_socket(port, backlog=1) + client_socket = None + + try: + with _managed_subprocess([sys.executable, script_file]) as p: + thread_tid = None + + client_socket, _ = server_socket.accept() + line = client_socket.recv(1024) + if line and line.startswith(b"ready:"): + try: + thread_tid = int(line.split(b":")[-1]) + except (ValueError, IndexError): + pass + + server_socket.close() + server_socket = None + + yield p, thread_tid + finally: + _cleanup_sockets(client_socket, server_socket) + + def _check_thread_status( + self, p, thread_tid, condition, condition_name="condition" + ): + """Helper to check thread status with a custom condition. + + This waits until we see 3 consecutive samples where the condition + returns True, which confirms the thread has reached and is stable + in the expected state. Samples that don't match are ignored (the + thread may not have reached the expected state yet). + + Args: + p: Process object with pid attribute + thread_tid: Thread ID to check + condition: Callable(statuses, thread_tid) -> bool that returns + True when the thread is in the expected state + condition_name: Description of condition for error messages + """ + unwinder = RemoteUnwinder( + p.pid, + all_threads=True, + mode=PROFILING_MODE_ALL, + skip_non_matching_threads=False, + ) + + # Wait for 3 consecutive samples matching expected state + matching_samples = 0 + for _ in busy_retry(SHORT_TIMEOUT): + with contextlib.suppress(*TRANSIENT_ERRORS): + traces = unwinder.get_stack_trace() + statuses = self._get_thread_statuses(traces) + + if thread_tid in statuses: + if condition(statuses, thread_tid): + matching_samples += 1 + if matching_samples >= 3: + return # Success - confirmed stable in expected state + else: + # Thread not yet in expected state, reset counter + matching_samples = 0 + + self.fail( + f"Thread did not stabilize in expected state " + f"({condition_name}) within timeout" + ) + + def _check_exception_status(self, p, thread_tid, expect_exception): + """Helper to check if thread has expected exception status.""" + def condition(statuses, tid): + has_exc = bool(statuses[tid] & THREAD_STATUS_HAS_EXCEPTION) + return has_exc == expect_exception + + self._check_thread_status( + p, thread_tid, condition, + condition_name=f"expect_exception={expect_exception}" + ) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_except_block_has_exception(self): + """Test that thread inside except block has HAS_EXCEPTION flag. - # Wait for ready signal - response = b"" - while b"ready" not in response: - response += client_socket.recv(1024) - - # Wait for the main thread to start its busy work - while b"working" not in response: - response += client_socket.recv(1024) - - # Get stack trace with all threads - unwinder_all = RemoteUnwinder(p.pid, all_threads=True) - for _ in range(10): - # Wait for the main thread to start its busy work - all_traces = unwinder_all.get_stack_trace() - found = False - for thread_id, stack in all_traces: - if not stack: - continue - current_frame = stack[0] - if ( - current_frame.funcname == "main_work" - and current_frame.lineno > 15 - ): - found = True + When a thread is executing inside an except block, exc_info->exc_value + is set, so THREAD_STATUS_HAS_EXCEPTION should be True. + """ + with self._run_scenario_process("except_block") as (p, thread_tid): + self.assertIsNotNone(thread_tid, "Thread ID not received") + self._check_exception_status(p, thread_tid, expect_exception=True) - if found: - break - # Give a bit of time to take the next sample - time.sleep(0.1) + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_finally_propagating_has_exception(self): + """Test that finally block with propagating exception has HAS_EXCEPTION flag. + + When an exception is propagating through a finally block (not yet caught), + current_exception is set, so THREAD_STATUS_HAS_EXCEPTION should be True. + """ + with self._run_scenario_process("finally_propagating") as (p, thread_tid): + self.assertIsNotNone(thread_tid, "Thread ID not received") + self._check_exception_status(p, thread_tid, expect_exception=True) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_finally_after_except_no_exception(self): + """Test that finally block after except has NO HAS_EXCEPTION flag. + + When a finally block runs after an except block has handled the exception, + Python clears exc_info before entering finally, so THREAD_STATUS_HAS_EXCEPTION + should be False. + """ + with self._run_scenario_process("finally_after_except") as (p, thread_tid): + self.assertIsNotNone(thread_tid, "Thread ID not received") + self._check_exception_status(p, thread_tid, expect_exception=False) + + @unittest.skipIf( + sys.platform not in ("linux", "darwin", "win32"), + "Test only runs on supported platforms (Linux, macOS, or Windows)", + ) + @unittest.skipIf( + sys.platform == "android", "Android raises Linux-specific exception" + ) + def test_finally_no_exception_no_flag(self): + """Test that finally block with no exception has NO HAS_EXCEPTION flag. + + When a finally block runs during normal execution (no exception raised), + there is no exception state, so THREAD_STATUS_HAS_EXCEPTION should be False. + """ + with self._run_scenario_process("finally_no_exception") as (p, thread_tid): + self.assertIsNotNone(thread_tid, "Thread ID not received") + self._check_exception_status(p, thread_tid, expect_exception=False) + + +@requires_remote_subprocess_debugging() +class TestFrameCaching(RemoteInspectionTestBase): + """Test that frame caching produces correct results. + + Uses socket-based synchronization for deterministic testing. + All tests verify cache reuse via object identity checks (assertIs). + """ + + @contextmanager + def _target_process(self, script_body): + """Context manager for running a target process with socket sync.""" + port = find_unused_port() + script = f"""\ +import socket +sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +sock.connect(('localhost', {port})) +{textwrap.dedent(script_body)} +""" + + with os_helper.temp_dir() as work_dir: + script_dir = os.path.join(work_dir, "script_pkg") + os.mkdir(script_dir) + + server_socket = _create_server_socket(port) + script_name = _make_test_script(script_dir, "script", script) + client_socket = None + + try: + with _managed_subprocess([sys.executable, script_name]) as p: + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + def make_unwinder(cache_frames=True): + return RemoteUnwinder( + p.pid, all_threads=True, cache_frames=cache_frames + ) + + yield p, client_socket, make_unwinder + finally: + _cleanup_sockets(client_socket, server_socket) + + def _get_frames_with_retry(self, unwinder, required_funcs): + """Get frames containing required_funcs, with retry for transient errors.""" + for _ in range(MAX_TRIES): + with contextlib.suppress(*TRANSIENT_ERRORS): + traces = unwinder.get_stack_trace() + for interp in traces: + for thread in interp.threads: + funcs = {f.funcname for f in thread.frame_info} + if required_funcs.issubset(funcs): + return thread.frame_info + time.sleep(RETRY_DELAY) + return None + + def _sample_frames( + self, + client_socket, + unwinder, + wait_signal, + send_ack, + required_funcs, + expected_frames=1, + ): + """Wait for signal, sample frames with retry until required funcs present, send ack.""" + _wait_for_signal(client_socket, wait_signal) + frames = None + for _ in range(MAX_TRIES): + frames = self._get_frames_with_retry(unwinder, required_funcs) + if frames and len(frames) >= expected_frames: + break + time.sleep(RETRY_DELAY) + client_socket.sendall(send_ack) + return frames + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_cache_hit_same_stack(self): + """Test that consecutive samples reuse cached parent frame objects. + + The current frame (index 0) is always re-read from memory to get + updated line numbers, so it may be a different object. Parent frames + (index 1+) should be identical objects from cache. + """ + script_body = """\ + def level3(): + sock.sendall(b"sync1") + sock.recv(16) + sock.sendall(b"sync2") + sock.recv(16) + sock.sendall(b"sync3") + sock.recv(16) + + def level2(): + level3() + + def level1(): + level2() + + level1() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder = make_unwinder(cache_frames=True) + expected = {"level1", "level2", "level3"} + + frames1 = self._sample_frames( + client_socket, unwinder, b"sync1", b"ack", expected + ) + frames2 = self._sample_frames( + client_socket, unwinder, b"sync2", b"ack", expected + ) + frames3 = self._sample_frames( + client_socket, unwinder, b"sync3", b"done", expected + ) + + self.assertIsNotNone(frames1) + self.assertIsNotNone(frames2) + self.assertIsNotNone(frames3) + self.assertEqual(len(frames1), len(frames2)) + self.assertEqual(len(frames2), len(frames3)) + + # Current frame (index 0) is always re-read, so check value equality + self.assertEqual(frames1[0].funcname, frames2[0].funcname) + self.assertEqual(frames2[0].funcname, frames3[0].funcname) + + # Parent frames (index 1+) must be identical objects (cache reuse) + for i in range(1, len(frames1)): + f1, f2, f3 = frames1[i], frames2[i], frames3[i] + self.assertIs( + f1, f2, f"Frame {i}: samples 1-2 must be same object" + ) + self.assertIs( + f2, f3, f"Frame {i}: samples 2-3 must be same object" + ) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_line_number_updates_in_same_frame(self): + """Test that line numbers are correctly updated when execution moves within a function. + + When the profiler samples at different points within the same function, + it must report the correct line number for each sample, not stale cached values. + """ + script_body = """\ + def outer(): + inner() + + def inner(): + sock.sendall(b"line_a"); sock.recv(16) + sock.sendall(b"line_b"); sock.recv(16) + sock.sendall(b"line_c"); sock.recv(16) + sock.sendall(b"line_d"); sock.recv(16) + + outer() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder = make_unwinder(cache_frames=True) + + frames_a = self._sample_frames( + client_socket, unwinder, b"line_a", b"ack", {"inner"} + ) + frames_b = self._sample_frames( + client_socket, unwinder, b"line_b", b"ack", {"inner"} + ) + frames_c = self._sample_frames( + client_socket, unwinder, b"line_c", b"ack", {"inner"} + ) + frames_d = self._sample_frames( + client_socket, unwinder, b"line_d", b"done", {"inner"} + ) + + self.assertIsNotNone(frames_a) + self.assertIsNotNone(frames_b) + self.assertIsNotNone(frames_c) + self.assertIsNotNone(frames_d) + + # Get the 'inner' frame from each sample (should be index 0) + inner_a = frames_a[0] + inner_b = frames_b[0] + inner_c = frames_c[0] + inner_d = frames_d[0] + + self.assertEqual(inner_a.funcname, "inner") + self.assertEqual(inner_b.funcname, "inner") + self.assertEqual(inner_c.funcname, "inner") + self.assertEqual(inner_d.funcname, "inner") + + # Line numbers must be different and increasing (execution moves forward) + self.assertLess( + inner_a.location.lineno, inner_b.location.lineno, "Line B should be after line A" + ) + self.assertLess( + inner_b.location.lineno, inner_c.location.lineno, "Line C should be after line B" + ) + self.assertLess( + inner_c.location.lineno, inner_d.location.lineno, "Line D should be after line C" + ) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_cache_invalidation_on_return(self): + """Test cache invalidation when stack shrinks (function returns).""" + script_body = """\ + def inner(): + sock.sendall(b"at_inner") + sock.recv(16) + + def outer(): + inner() + sock.sendall(b"at_outer") + sock.recv(16) + + outer() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder = make_unwinder(cache_frames=True) + + frames_deep = self._sample_frames( + client_socket, + unwinder, + b"at_inner", + b"ack", + {"inner", "outer"}, + ) + frames_shallow = self._sample_frames( + client_socket, unwinder, b"at_outer", b"done", {"outer"} + ) + + self.assertIsNotNone(frames_deep) + self.assertIsNotNone(frames_shallow) + + funcs_deep = [f.funcname for f in frames_deep] + funcs_shallow = [f.funcname for f in frames_shallow] + + self.assertIn("inner", funcs_deep) + self.assertIn("outer", funcs_deep) + self.assertNotIn("inner", funcs_shallow) + self.assertIn("outer", funcs_shallow) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_cache_invalidation_on_call(self): + """Test cache invalidation when stack grows (new function called).""" + script_body = """\ + def deeper(): + sock.sendall(b"at_deeper") + sock.recv(16) + + def middle(): + sock.sendall(b"at_middle") + sock.recv(16) + deeper() + + def top(): + middle() + + top() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder = make_unwinder(cache_frames=True) + + frames_before = self._sample_frames( + client_socket, + unwinder, + b"at_middle", + b"ack", + {"middle", "top"}, + ) + frames_after = self._sample_frames( + client_socket, + unwinder, + b"at_deeper", + b"done", + {"deeper", "middle", "top"}, + ) + + self.assertIsNotNone(frames_before) + self.assertIsNotNone(frames_after) + + funcs_before = [f.funcname for f in frames_before] + funcs_after = [f.funcname for f in frames_after] + + self.assertIn("middle", funcs_before) + self.assertIn("top", funcs_before) + self.assertNotIn("deeper", funcs_before) + + self.assertIn("deeper", funcs_after) + self.assertIn("middle", funcs_after) + self.assertIn("top", funcs_after) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_partial_stack_reuse(self): + """Test that unchanged parent frames are reused from cache when top frame moves.""" + script_body = """\ + def level4(): + sock.sendall(b"sync1") + sock.recv(16) + sock.sendall(b"sync2") + sock.recv(16) + + def level3(): + level4() + + def level2(): + level3() + + def level1(): + level2() + + level1() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder = make_unwinder(cache_frames=True) + + # Sample 1: level4 at first sendall + frames1 = self._sample_frames( + client_socket, + unwinder, + b"sync1", + b"ack", + {"level1", "level2", "level3", "level4"}, + ) + # Sample 2: level4 at second sendall (same stack, different line) + frames2 = self._sample_frames( + client_socket, + unwinder, + b"sync2", + b"done", + {"level1", "level2", "level3", "level4"}, + ) + + self.assertIsNotNone(frames1) + self.assertIsNotNone(frames2) + + def find_frame(frames, funcname): + for f in frames: + if f.funcname == funcname: + return f + return None + + # level4 should have different line numbers (it moved) + l4_1 = find_frame(frames1, "level4") + l4_2 = find_frame(frames2, "level4") + self.assertIsNotNone(l4_1) + self.assertIsNotNone(l4_2) + self.assertNotEqual( + l4_1.location.lineno, + l4_2.location.lineno, + "level4 should be at different lines", + ) + + # Parent frames (level1, level2, level3) should be reused from cache + for name in ["level1", "level2", "level3"]: + f1 = find_frame(frames1, name) + f2 = find_frame(frames2, name) + self.assertIsNotNone(f1, f"{name} missing from sample 1") + self.assertIsNotNone(f2, f"{name} missing from sample 2") + self.assertIs(f1, f2, f"{name} should be reused from cache") + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_recursive_frames(self): + """Test caching with same function appearing multiple times (recursion).""" + script_body = """\ + def recurse(n): + if n <= 0: + sock.sendall(b"sync1") + sock.recv(16) + sock.sendall(b"sync2") + sock.recv(16) else: - self.fail( - "Main thread did not start its busy work on time" - ) + recurse(n - 1) - # Get stack trace with only GIL holder - unwinder_gil = RemoteUnwinder(p.pid, only_active_thread=True) - gil_traces = unwinder_gil.get_stack_trace() + recurse(5) + """ - except PermissionError: - self.skipTest( - "Insufficient permissions to read the stack trace" + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder = make_unwinder(cache_frames=True) + + frames1 = self._sample_frames( + client_socket, unwinder, b"sync1", b"ack", {"recurse"} + ) + frames2 = self._sample_frames( + client_socket, unwinder, b"sync2", b"done", {"recurse"} + ) + + self.assertIsNotNone(frames1) + self.assertIsNotNone(frames2) + + # Should have multiple "recurse" frames (6 total: recurse(5) down to recurse(0)) + recurse_count = sum(1 for f in frames1 if f.funcname == "recurse") + self.assertEqual(recurse_count, 6, "Should have 6 recursive frames") + + self.assertEqual(len(frames1), len(frames2)) + + # Current frame (index 0) is re-read, check value equality + self.assertEqual(frames1[0].funcname, frames2[0].funcname) + + # Parent frames (index 1+) should be identical objects (cache reuse) + for i in range(1, len(frames1)): + self.assertIs( + frames1[i], + frames2[i], + f"Frame {i}: recursive frames must be same object", + ) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_cache_vs_no_cache_equivalence(self): + """Test that cache_frames=True and cache_frames=False produce equivalent results.""" + script_body = """\ + def level3(): + sock.sendall(b"ready"); sock.recv(16) + + def level2(): + level3() + + def level1(): + level2() + + level1() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + _wait_for_signal(client_socket, b"ready") + + # Sample with cache + unwinder_cache = make_unwinder(cache_frames=True) + frames_cached = self._get_frames_with_retry( + unwinder_cache, {"level1", "level2", "level3"} + ) + + # Sample without cache + unwinder_no_cache = make_unwinder(cache_frames=False) + frames_no_cache = self._get_frames_with_retry( + unwinder_no_cache, {"level1", "level2", "level3"} + ) + + client_socket.sendall(b"done") + + self.assertIsNotNone(frames_cached) + self.assertIsNotNone(frames_no_cache) + + # Same number of frames + self.assertEqual(len(frames_cached), len(frames_no_cache)) + + # Same function names in same order + funcs_cached = [f.funcname for f in frames_cached] + funcs_no_cache = [f.funcname for f in frames_no_cache] + self.assertEqual(funcs_cached, funcs_no_cache) + + # For level3 (leaf frame), due to timing races we can be at either + # sock.sendall() or sock.recv() - both are valid. For parent frames, + # the locations should match exactly. + # Valid locations for level3: line 3 has two statements + # sock.sendall(b"ready") -> col 4-26 + # sock.recv(16) -> col 28-41 + level3_valid_cols = {(4, 26), (28, 41)} + + for i in range(len(frames_cached)): + loc_cached = frames_cached[i].location + loc_no_cache = frames_no_cache[i].location + + if frames_cached[i].funcname == "level3": + # Leaf frame: can be at either statement + self.assertIn( + (loc_cached.col_offset, loc_cached.end_col_offset), + level3_valid_cols, ) - finally: - if client_socket is not None: - client_socket.close() - p.kill() - p.terminate() - p.wait(timeout=SHORT_TIMEOUT) + self.assertIn( + (loc_no_cache.col_offset, loc_no_cache.end_col_offset), + level3_valid_cols, + ) + else: + # Parent frames: must match exactly + self.assertEqual(loc_cached, loc_no_cache) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_cache_per_thread_isolation(self): + """Test that frame cache is per-thread and cache invalidation works independently.""" + script_body = """\ + import threading + + lock = threading.Lock() + + def sync(msg): + with lock: + sock.sendall(msg + b"\\n") + sock.recv(1) + + # Thread 1 functions + def baz1(): + sync(b"t1:baz1") + + def bar1(): + baz1() + + def blech1(): + sync(b"t1:blech1") + + def foo1(): + bar1() # Goes down to baz1, syncs + blech1() # Returns up, goes down to blech1, syncs + + # Thread 2 functions + def baz2(): + sync(b"t2:baz2") - # Verify we got multiple threads in all_traces - self.assertGreater( - len(all_traces), 1, "Should have multiple threads" + def bar2(): + baz2() + + def blech2(): + sync(b"t2:blech2") + + def foo2(): + bar2() # Goes down to baz2, syncs + blech2() # Returns up, goes down to blech2, syncs + + t1 = threading.Thread(target=foo1) + t2 = threading.Thread(target=foo2) + t1.start() + t2.start() + t1.join() + t2.join() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder = make_unwinder(cache_frames=True) + + # Message dispatch table: signal -> required functions for that thread + dispatch = { + b"t1:baz1": {"baz1", "bar1", "foo1"}, + b"t2:baz2": {"baz2", "bar2", "foo2"}, + b"t1:blech1": {"blech1", "foo1"}, + b"t2:blech2": {"blech2", "foo2"}, + } + + # Track results for each sync point + results = {} + + # Process 4 sync points (order depends on thread scheduling) + buffer = _wait_for_signal(client_socket, b"\n") + for i in range(4): + # Extract first message from buffer + msg, sep, buffer = buffer.partition(b"\n") + self.assertIn(msg, dispatch, f"Unexpected message: {msg!r}") + + # Sample frames for the thread at this sync point + required_funcs = dispatch[msg] + frames = self._get_frames_with_retry(unwinder, required_funcs) + self.assertIsNotNone(frames, f"Thread not found for {msg!r}") + results[msg] = [f.funcname for f in frames] + + # Release thread and wait for next message (if not last) + client_socket.sendall(b"k") + if i < 3: + buffer += _wait_for_signal(client_socket, b"\n") + + # Validate Phase 1: baz snapshots + t1_baz = results.get(b"t1:baz1") + t2_baz = results.get(b"t2:baz2") + self.assertIsNotNone(t1_baz, "Missing t1:baz1 snapshot") + self.assertIsNotNone(t2_baz, "Missing t2:baz2 snapshot") + + # Thread 1 at baz1: should have foo1->bar1->baz1 + self.assertIn("baz1", t1_baz) + self.assertIn("bar1", t1_baz) + self.assertIn("foo1", t1_baz) + self.assertNotIn("blech1", t1_baz) + # No cross-contamination + self.assertNotIn("baz2", t1_baz) + self.assertNotIn("bar2", t1_baz) + self.assertNotIn("foo2", t1_baz) + + # Thread 2 at baz2: should have foo2->bar2->baz2 + self.assertIn("baz2", t2_baz) + self.assertIn("bar2", t2_baz) + self.assertIn("foo2", t2_baz) + self.assertNotIn("blech2", t2_baz) + # No cross-contamination + self.assertNotIn("baz1", t2_baz) + self.assertNotIn("bar1", t2_baz) + self.assertNotIn("foo1", t2_baz) + + # Validate Phase 2: blech snapshots (cache invalidation test) + t1_blech = results.get(b"t1:blech1") + t2_blech = results.get(b"t2:blech2") + self.assertIsNotNone(t1_blech, "Missing t1:blech1 snapshot") + self.assertIsNotNone(t2_blech, "Missing t2:blech2 snapshot") + + # Thread 1 at blech1: bar1/baz1 should be GONE (cache invalidated) + self.assertIn("blech1", t1_blech) + self.assertIn("foo1", t1_blech) + self.assertNotIn( + "bar1", t1_blech, "Cache not invalidated: bar1 still present" + ) + self.assertNotIn( + "baz1", t1_blech, "Cache not invalidated: baz1 still present" + ) + # No cross-contamination + self.assertNotIn("blech2", t1_blech) + + # Thread 2 at blech2: bar2/baz2 should be GONE (cache invalidated) + self.assertIn("blech2", t2_blech) + self.assertIn("foo2", t2_blech) + self.assertNotIn( + "bar2", t2_blech, "Cache not invalidated: bar2 still present" + ) + self.assertNotIn( + "baz2", t2_blech, "Cache not invalidated: baz2 still present" + ) + # No cross-contamination + self.assertNotIn("blech1", t2_blech) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_new_unwinder_with_stale_last_profiled_frame(self): + """Test that a new unwinder returns complete stack when cache lookup misses.""" + script_body = """\ + def level4(): + sock.sendall(b"sync1") + sock.recv(16) + sock.sendall(b"sync2") + sock.recv(16) + + def level3(): + level4() + + def level2(): + level3() + + def level1(): + level2() + + level1() + """ + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + expected = {"level1", "level2", "level3", "level4"} + + # First unwinder samples - this sets last_profiled_frame in target + unwinder1 = make_unwinder(cache_frames=True) + frames1 = self._sample_frames( + client_socket, unwinder1, b"sync1", b"ack", expected ) - # Verify we got exactly one thread in gil_traces - self.assertEqual( - len(gil_traces), 1, "Should have exactly one GIL holder" + # Create NEW unwinder (empty cache) and sample + # The target still has last_profiled_frame set from unwinder1 + unwinder2 = make_unwinder(cache_frames=True) + frames2 = self._sample_frames( + client_socket, unwinder2, b"sync2", b"done", expected ) - # The GIL holder should be in the all_traces list - gil_thread_id = gil_traces[0][0] - all_thread_ids = [trace[0] for trace in all_traces] - self.assertIn( - gil_thread_id, - all_thread_ids, - "GIL holder should be among all threads", + self.assertIsNotNone(frames1) + self.assertIsNotNone(frames2) + + funcs1 = [f.funcname for f in frames1] + funcs2 = [f.funcname for f in frames2] + + # Both should have all levels + for level in ["level1", "level2", "level3", "level4"]: + self.assertIn(level, funcs1, f"{level} missing from first sample") + self.assertIn(level, funcs2, f"{level} missing from second sample") + + # Should have same stack depth + self.assertEqual( + len(frames1), + len(frames2), + "New unwinder should return complete stack despite stale last_profiled_frame", + ) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_cache_exhaustion(self): + """Test cache works when frame limit (1024) is exceeded. + + FRAME_CACHE_MAX_FRAMES=1024. With 1100 recursive frames, + the cache can't store all of them but should still work. + """ + # Use 1100 to exceed FRAME_CACHE_MAX_FRAMES=1024 + depth = 1100 + script_body = f"""\ +import sys +sys.setrecursionlimit(2000) + +def recurse(n): + if n <= 0: + sock.sendall(b"ready") + sock.recv(16) # wait for ack + sock.sendall(b"ready2") + sock.recv(16) # wait for done + return + recurse(n - 1) + +recurse({depth}) +""" + + with self._target_process(script_body) as ( + p, + client_socket, + make_unwinder, + ): + unwinder_cache = make_unwinder(cache_frames=True) + unwinder_no_cache = make_unwinder(cache_frames=False) + + frames_cached = self._sample_frames( + client_socket, + unwinder_cache, + b"ready", + b"ack", + {"recurse"}, + expected_frames=1102, + ) + # Sample again with no cache for comparison + frames_no_cache = self._sample_frames( + client_socket, + unwinder_no_cache, + b"ready2", + b"done", + {"recurse"}, + expected_frames=1102, ) + self.assertIsNotNone(frames_cached) + self.assertIsNotNone(frames_no_cache) + + # Both should have many recurse frames (> 1024 limit) + cached_count = [f.funcname for f in frames_cached].count("recurse") + no_cache_count = [f.funcname for f in frames_no_cache].count("recurse") + + self.assertGreater( + cached_count, 1000, "Should have >1000 recurse frames" + ) + self.assertGreater( + no_cache_count, 1000, "Should have >1000 recurse frames" + ) + + # Both modes should produce same frame count + self.assertEqual( + len(frames_cached), + len(frames_no_cache), + "Cache exhaustion should not affect stack completeness", + ) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_get_stats(self): + """Test that get_stats() returns statistics when stats=True.""" + script_body = """\ + sock.sendall(b"ready") + sock.recv(16) + """ + + with self._target_process(script_body) as (p, client_socket, _): + unwinder = RemoteUnwinder(p.pid, all_threads=True, stats=True) + _wait_for_signal(client_socket, b"ready") + + # Take a sample + _get_stack_trace_with_retry(unwinder) + + stats = unwinder.get_stats() + client_socket.sendall(b"done") + + # Verify expected keys exist + expected_keys = [ + "total_samples", + "frame_cache_hits", + "frame_cache_misses", + "frame_cache_partial_hits", + "frames_read_from_cache", + "frames_read_from_memory", + "frame_cache_hit_rate", + "batched_read_attempts", + "batched_read_successes", + "batched_read_misses", + "batched_read_segments_requested", + "batched_read_segments_completed", + "batched_read_success_rate", + "batched_read_segment_completion_rate", + ] + for key in expected_keys: + self.assertIn(key, stats) + + self.assertEqual(stats["total_samples"], 1) + + @skip_if_not_supported + @unittest.skipIf( + sys.platform == "linux" and not PROCESS_VM_READV_SUPPORTED, + "Test only runs on Linux with process_vm_readv support", + ) + def test_get_stats_disabled_raises(self): + """Test that get_stats() raises RuntimeError when stats=False.""" + script_body = """\ + sock.sendall(b"ready") + sock.recv(16) + """ + + with self._target_process(script_body) as (p, client_socket, _): + unwinder = RemoteUnwinder( + p.pid, all_threads=True + ) # stats=False by default + _wait_for_signal(client_socket, b"ready") + + with self.assertRaises(RuntimeError): + unwinder.get_stats() + + client_socket.sendall(b"done") + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_faulthandler.py b/Lib/test/test_faulthandler.py index f498085c691..ba891d9882c 100644 --- a/Lib/test/test_faulthandler.py +++ b/Lib/test/test_faulthandler.py @@ -33,6 +33,11 @@ CURRENT_THREAD_HEADER = fr'{CURRENT_THREAD_ID} \(most recent call first\):' +def skip_if_sanitizer_signal(signame): + return support.skip_if_sanitizer(f"TSAN/UBSan itercepts {signame}", + thread=True, ub=True) + + def expected_traceback(lineno1, lineno2, header, min_count=1): regex = header regex += ' File "", line %s in func\n' % lineno1 @@ -166,29 +171,6 @@ def check_windows_exception(self, code, line_number, name_regex, **kw): fatal_error = 'Windows fatal exception: %s' % name_regex self.check_error(code, line_number, fatal_error, **kw) - @unittest.skipIf(sys.platform.startswith('aix'), - "the first page of memory is a mapped read-only on AIX") - def test_read_null(self): - if not MS_WINDOWS: - self.check_fatal_error(""" - import faulthandler - faulthandler.enable() - faulthandler._read_null() - """, - 3, - # Issue #12700: Read NULL raises SIGILL on Mac OS X Lion - '(?:Segmentation fault' - '|Bus error' - '|Illegal instruction)') - else: - self.check_windows_exception(""" - import faulthandler - faulthandler.enable() - faulthandler._read_null() - """, - 3, - 'access violation') - @skip_segfault_on_android def test_sigsegv(self): self.check_fatal_error(""" @@ -248,7 +230,7 @@ def test_fatal_error_c_thread(self): func='faulthandler_fatal_error_thread', py_fatal_error=True) - @support.skip_if_sanitizer("TSAN itercepts SIGABRT", thread=True) + @skip_if_sanitizer_signal("SIGABRT") def test_sigabrt(self): self.check_fatal_error(""" import faulthandler @@ -260,7 +242,7 @@ def test_sigabrt(self): @unittest.skipIf(sys.platform == 'win32', "SIGFPE cannot be caught on Windows") - @support.skip_if_sanitizer("TSAN itercepts SIGFPE", thread=True) + @skip_if_sanitizer_signal("SIGFPE") def test_sigfpe(self): self.check_fatal_error(""" import faulthandler @@ -272,7 +254,7 @@ def test_sigfpe(self): @unittest.skipIf(_testcapi is None, 'need _testcapi') @unittest.skipUnless(hasattr(signal, 'SIGBUS'), 'need signal.SIGBUS') - @support.skip_if_sanitizer("TSAN itercepts SIGBUS", thread=True) + @skip_if_sanitizer_signal("SIGBUS") @skip_segfault_on_android def test_sigbus(self): self.check_fatal_error(""" @@ -287,7 +269,7 @@ def test_sigbus(self): @unittest.skipIf(_testcapi is None, 'need _testcapi') @unittest.skipUnless(hasattr(signal, 'SIGILL'), 'need signal.SIGILL') - @support.skip_if_sanitizer("TSAN itercepts SIGILL", thread=True) + @skip_if_sanitizer_signal("SIGILL") @skip_segfault_on_android def test_sigill(self): self.check_fatal_error(""" @@ -384,6 +366,18 @@ def test_enable_single_thread(self): 'Segmentation fault', all_threads=False) + @unittest.expectedFailure # TODO: RUSTPYTHON; faulthandler.enable() does not support c_stack + @skip_segfault_on_android + def test_enable_without_c_stack(self): + self.check_fatal_error(""" + import faulthandler + faulthandler.enable(c_stack=False) + faulthandler._sigsegv() + """, + 3, + 'Segmentation fault', + c_stack=False) + @skip_segfault_on_android def test_disable(self): code = """ @@ -402,10 +396,11 @@ def test_disable(self): @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: Cannot find 'Extension modules:' in 'Fatal Python error: Segmentation fault\n\nCurrent thread 0x0000000000004284 (most recent call first):\n File "", line 6 in ' @skip_segfault_on_android def test_dump_ext_modules(self): + # Don't filter stdlib module names: disable sys.stdlib_module_names code = """ import faulthandler import sys - # Don't filter stdlib module names + import math sys.stdlib_module_names = frozenset() faulthandler.enable() faulthandler._sigsegv() @@ -417,9 +412,21 @@ def test_dump_ext_modules(self): if not match: self.fail(f"Cannot find 'Extension modules:' in {stderr!r}") modules = set(match.group(1).strip().split(', ')) - for name in ('sys', 'faulthandler'): + for name in ('sys', 'faulthandler', 'math'): self.assertIn(name, modules) + # Ignore "math.integer" sub-module if "math" package is + # in sys.stdlib_module_names + code = """ + import faulthandler + import math.integer + faulthandler.enable() + faulthandler._sigsegv() + """ + stderr, exitcode = self.get_output(code) + stderr = '\n'.join(stderr) + self.assertNotIn('Extension modules:', stderr) + def test_is_enabled(self): orig_stderr = sys.stderr try: @@ -720,6 +727,77 @@ def test_dump_traceback_later_fd(self): def test_dump_traceback_later_twice(self): self.check_dump_traceback_later(loops=2) + def test_dump_traceback_max_threads(self): + # max_threads caps the dump and writes "...\n" when truncated. + # Spawn N worker threads, dump with cap < N, and verify the + # marker is present and exactly CAP thread headers are written. + code = dedent(""" + import faulthandler + import sys + import threading + + NTHREADS = 6 + CAP = 3 + + ready = threading.Barrier(NTHREADS + 1) + stop = threading.Event() + + def worker(): + ready.wait() + stop.wait() + + threads = [threading.Thread(target=worker) for _ in range(NTHREADS)] + for t in threads: + t.start() + ready.wait() + try: + faulthandler.dump_traceback(file=sys.stderr, max_threads=CAP) + finally: + stop.set() + for t in threads: + t.join() + """).strip() + proc = script_helper.assert_python_ok('-c', code) + output = proc.err + # Truncation marker is written on its own line when the cap is hit. + self.assertIn(b"\n...\n", output) + # Cap of 3 means exactly 3 thread headers in the dump. + self.assertEqual(output.count(b"Thread 0x"), 3) + + @unittest.expectedFailure # TODO: RUSTPYTHON; faulthandler.enable() does not support max_threads + @skip_segfault_on_android + @unittest.skipIf(support.Py_GIL_DISABLED, + "fatal-signal handler only dumps the current thread " + "when the GIL is disabled") + def test_enable_max_threads(self): + # enable(max_threads=N) caps the thread dump produced when a + # fatal signal fires. + code = dedent(""" + import faulthandler + import threading + + NTHREADS = 6 + CAP = 3 + + ready = threading.Barrier(NTHREADS + 1) + stop = threading.Event() + + def worker(): + ready.wait() + stop.wait() + + for _ in range(NTHREADS): + threading.Thread(target=worker, daemon=True).start() + ready.wait() + faulthandler.enable(max_threads=CAP) + faulthandler._sigsegv() + """).strip() + output, exitcode = self.get_output(code) + output = '\n'.join(output) + # Cap of 3 means the dump is truncated with "..." on its own line. + self.assertIn("\n...\n", output) + self.assertNotEqual(exitcode, 0) + @unittest.skipIf(not hasattr(faulthandler, "register"), "need faulthandler.register") def check_register(self, filename=False, all_threads=False, @@ -826,6 +904,47 @@ def test_register_threads(self): def test_register_chain(self): self.check_register(chain=True) + @unittest.expectedFailure # TODO: RUSTPYTHON; faulthandler.register() does not support max_threads + @unittest.skipIf(not hasattr(faulthandler, "register"), + "need faulthandler.register") + def test_register_max_threads(self): + # register(max_threads=N) caps the thread dump produced when + # the registered signal fires. + code = dedent(""" + import faulthandler + import signal + import threading + + NTHREADS = 6 + CAP = 3 + + ready = threading.Barrier(NTHREADS + 1) + stop = threading.Event() + + def worker(): + ready.wait() + stop.wait() + + threads = [threading.Thread(target=worker) for _ in range(NTHREADS)] + for t in threads: + t.start() + ready.wait() + try: + faulthandler.register(signal.SIGUSR1, all_threads=True, + max_threads=CAP) + signal.raise_signal(signal.SIGUSR1) + finally: + stop.set() + for t in threads: + t.join() + """).strip() + proc = script_helper.assert_python_ok('-c', code) + output = proc.err + # Cap of 3 means the dump is truncated with "..." on its own line. + self.assertIn(b"\n...\n", output) + # Cap of 3 means exactly 3 thread headers in the dump. + self.assertEqual(output.count(b"Thread 0x"), 3) + @contextmanager def check_stderr_none(self): stderr = sys.stderr @@ -973,7 +1092,6 @@ def check_c_stack(self, output): self.assertRegex(line, C_STACK_REGEX[1]) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: 1 != 0 def test_dump_c_stack(self): code = dedent(""" import faulthandler @@ -984,7 +1102,6 @@ def test_dump_c_stack(self): self.check_c_stack(output) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'faulthandler' has no attribute 'dump_c_stack' def test_dump_c_stack_file(self): import tempfile diff --git a/Lib/test/test_fcntl.py b/Lib/test/test_fcntl.py index 9f1e2e250fe..f20a9d40767 100644 --- a/Lib/test/test_fcntl.py +++ b/Lib/test/test_fcntl.py @@ -151,6 +151,7 @@ def test_fcntl_64_bit(self): except OSError as exc: if exc.errno == errno.EINVAL: self.skipTest("F_NOTIFY not available by this environment") + raise fcntl.fcntl(fd, cmd, flags) finally: os.close(fd) @@ -229,6 +230,54 @@ def test_fcntl_f_pipesize(self): os.close(test_pipe_r) os.close(test_pipe_w) + def _check_fcntl_not_mutate_len(self, nbytes=None): + self.f = open(TESTFN, 'wb') + buf = struct.pack('ii', fcntl.F_OWNER_PID, os.getpid()) + if nbytes is not None: + buf += b' ' * (nbytes - len(buf)) + else: + nbytes = len(buf) + save_buf = bytes(buf) + r = fcntl.fcntl(self.f, fcntl.F_SETOWN_EX, buf) + self.assertIsInstance(r, bytes) + self.assertEqual(len(r), len(save_buf)) + self.assertEqual(buf, save_buf) + type, pid = memoryview(r).cast('i')[:2] + self.assertEqual(type, fcntl.F_OWNER_PID) + self.assertEqual(pid, os.getpid()) + + buf = b' ' * nbytes + r = fcntl.fcntl(self.f, fcntl.F_GETOWN_EX, buf) + self.assertIsInstance(r, bytes) + self.assertEqual(len(r), len(save_buf)) + self.assertEqual(buf, b' ' * nbytes) + type, pid = memoryview(r).cast('i')[:2] + self.assertEqual(type, fcntl.F_OWNER_PID) + self.assertEqual(pid, os.getpid()) + + buf = memoryview(b' ' * nbytes) + r = fcntl.fcntl(self.f, fcntl.F_GETOWN_EX, buf) + self.assertIsInstance(r, bytes) + self.assertEqual(len(r), len(save_buf)) + self.assertEqual(bytes(buf), b' ' * nbytes) + type, pid = memoryview(r).cast('i')[:2] + self.assertEqual(type, fcntl.F_OWNER_PID) + self.assertEqual(pid, os.getpid()) + + @unittest.skipUnless( + hasattr(fcntl, "F_SETOWN_EX") and hasattr(fcntl, "F_GETOWN_EX"), + "requires F_SETOWN_EX and F_GETOWN_EX") + @unittest.skipIf(is_emscripten, "Emscripten doesn't actually support these") + def test_fcntl_small_buffer(self): + self._check_fcntl_not_mutate_len() + + @unittest.skipUnless( + hasattr(fcntl, "F_SETOWN_EX") and hasattr(fcntl, "F_GETOWN_EX"), + "requires F_SETOWN_EX and F_GETOWN_EX") + @unittest.skipIf(is_emscripten, "Emscripten doesn't actually support these") + def test_fcntl_large_buffer(self): + self._check_fcntl_not_mutate_len(2024) + @unittest.skipUnless(hasattr(fcntl, 'F_DUPFD'), 'need fcntl.F_DUPFD') def test_bad_fd(self): # gh-134744: Test error handling @@ -236,7 +285,9 @@ def test_bad_fd(self): with self.assertRaises(OSError): fcntl.fcntl(fd, fcntl.F_DUPFD, 0) with self.assertRaises(OSError): - fcntl.fcntl(fd, fcntl.F_DUPFD, b'\0' * 1024) + fcntl.fcntl(fd, fcntl.F_DUPFD, b'\0' * 10) + with self.assertRaises(OSError): + fcntl.fcntl(fd, fcntl.F_DUPFD, b'\0' * 2048) if __name__ == '__main__': diff --git a/Lib/test/test_file_eintr.py b/Lib/test/test_file_eintr.py index 98f7eb9e2a0..466f94e389f 100644 --- a/Lib/test/test_file_eintr.py +++ b/Lib/test/test_file_eintr.py @@ -186,10 +186,6 @@ def test_readall(self): class CTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase): modname = '_io' - @unittest.expectedFailure # TODO: RUSTPYTHON; - _io.FileIO.readall uses read_to_end which differs from _pyio.FileIO.readall - def test_readall(self): - return super().test_readall() - class PyTestFileIOSignalInterrupt(TestFileIOSignalInterrupt, unittest.TestCase): modname = '_pyio' diff --git a/Lib/test/test_finalization.py b/Lib/test/test_finalization.py index 42871f8a09b..9dd68cf8d57 100644 --- a/Lib/test/test_finalization.py +++ b/Lib/test/test_finalization.py @@ -174,7 +174,7 @@ def test_simple(self): gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) @@ -188,12 +188,12 @@ def test_simple_resurrect(self): gc.collect() self.assert_del_calls(ids) self.assert_survivors(ids) - self.assertIsNot(wr(), None) + self.assertIsNotNone(wr()) self.clear_survivors() gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) @support.cpython_only def test_non_gc(self): @@ -265,7 +265,7 @@ def test_simple(self): gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) @@ -276,19 +276,24 @@ def test_simple_resurrect(self): s = SelfCycleResurrector() ids = [id(s)] wr = weakref.ref(s) + wrc = weakref.ref(s, lambda x: None) del s gc.collect() self.assert_del_calls(ids) self.assert_survivors(ids) - # XXX is this desirable? - self.assertIs(wr(), None) + # This used to be None because weakrefs were cleared before + # calling finalizers. Now they are cleared after. + self.assertIsNotNone(wr()) + # A weakref with a callback is still cleared before calling + # finalizers. + self.assertIsNone(wrc()) # When trying to destroy the object a second time, __del__ # isn't called anymore (and the object isn't resurrected). self.clear_survivors() gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) def test_simple_suicide(self): # Test the GC is able to deal with an object that kills its last @@ -301,11 +306,11 @@ def test_simple_suicide(self): gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) gc.collect() self.assert_del_calls(ids) self.assert_survivors([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) class ChainedBase: @@ -378,18 +383,27 @@ def check_non_resurrecting_chain(self, classes): def check_resurrecting_chain(self, classes): N = len(classes) + def dummy_callback(ref): + pass with SimpleBase.test(): nodes = self.build_chain(classes) N = len(nodes) ids = [id(s) for s in nodes] survivor_ids = [id(s) for s in nodes if isinstance(s, SimpleResurrector)] wrs = [weakref.ref(s) for s in nodes] + wrcs = [weakref.ref(s, dummy_callback) for s in nodes] del nodes gc.collect() self.assert_del_calls(ids) self.assert_survivors(survivor_ids) - # XXX desirable? - self.assertEqual([wr() for wr in wrs], [None] * N) + for wr in wrs: + # These values used to be None because weakrefs were cleared + # before calling finalizers. Now they are cleared after. + self.assertIsNotNone(wr()) + for wr in wrcs: + # Weakrefs with callbacks are still cleared before calling + # finalizers. + self.assertIsNone(wr()) self.clear_survivors() gc.collect() self.assert_del_calls(ids) @@ -491,7 +505,7 @@ def test_legacy(self): self.assert_del_calls(ids) self.assert_tp_del_calls(ids) self.assert_survivors([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) gc.collect() self.assert_del_calls(ids) self.assert_tp_del_calls(ids) @@ -507,13 +521,13 @@ def test_legacy_resurrect(self): self.assert_tp_del_calls(ids) self.assert_survivors(ids) # weakrefs are cleared before tp_del is called. - self.assertIs(wr(), None) + self.assertIsNone(wr()) self.clear_survivors() gc.collect() self.assert_del_calls(ids) self.assert_tp_del_calls(ids * 2) self.assert_survivors(ids) - self.assertIs(wr(), None) + self.assertIsNone(wr()) def test_legacy_self_cycle(self): # Self-cycles with legacy finalizers end up in gc.garbage. @@ -527,11 +541,11 @@ def test_legacy_self_cycle(self): self.assert_tp_del_calls([]) self.assert_survivors([]) self.assert_garbage(ids) - self.assertIsNot(wr(), None) + self.assertIsNotNone(wr()) # Break the cycle to allow collection gc.garbage[0].ref = None self.assert_garbage([]) - self.assertIs(wr(), None) + self.assertIsNone(wr()) if __name__ == "__main__": diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py index dd0ab00d3c7..c03b0a09f71 100644 --- a/Lib/test/test_float.py +++ b/Lib/test/test_float.py @@ -431,7 +431,6 @@ def test_float_mod(self): self.assertEqualAndEqualSign(mod(1e-100, -1.0), -1.0) self.assertEqualAndEqualSign(mod(1.0, -1.0), -0.0) - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: must be real number, not complex @support.requires_IEEE_754 def test_float_pow(self): # test builtin pow and ** operator for IEEE 754 special cases. diff --git a/Lib/test/test_fork1.py b/Lib/test/test_fork1.py index a6523bbc518..550faa8a174 100644 --- a/Lib/test/test_fork1.py +++ b/Lib/test/test_fork1.py @@ -11,6 +11,7 @@ from test.fork_wait import ForkWait from test import support +from test.support import warnings_helper # Skip test if fork does not exist. @@ -19,6 +20,7 @@ class ForkTest(ForkWait): + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_threaded_import_lock_fork(self): """Check fork() in main thread works while a subthread is doing an import""" import_started = threading.Event() @@ -61,7 +63,7 @@ def importer(): except OSError: pass - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_nested_import_lock_fork(self): """Check fork() in main thread works while the main thread is doing an import""" exitcode = 42 diff --git a/Lib/test/test_format.py b/Lib/test/test_format.py index aa28108312e..618c38f3462 100644 --- a/Lib/test/test_format.py +++ b/Lib/test/test_format.py @@ -57,10 +57,6 @@ def testcommon(formatstr, args, output=None, limit=None, overflowok=False): else: b_format = formatstr ba_format = bytearray(b_format) - b_args = [] - if not isinstance(args, tuple): - args = (args, ) - b_args = tuple(args) if output is None: b_output = ba_output = None else: @@ -69,33 +65,23 @@ def testcommon(formatstr, args, output=None, limit=None, overflowok=False): else: b_output = output ba_output = bytearray(b_output) - testformat(b_format, b_args, b_output, limit, overflowok) - testformat(ba_format, b_args, ba_output, limit, overflowok) + testformat(b_format, args, b_output, limit, overflowok) + testformat(ba_format, args, ba_output, limit, overflowok) -def test_exc(formatstr, args, exception, excmsg): - try: - testformat(formatstr, args) - except exception as exc: - if str(exc) == excmsg: - if verbose: - print("yes") - else: - if verbose: print('no') - print('Unexpected ', exception, ':', repr(str(exc))) - except: - if verbose: print('no') - print('Unexpected exception') - raise - else: - raise TestFailed('did not get expected exception: %s' % excmsg) - -def test_exc_common(formatstr, args, exception, excmsg): - # test str and bytes - test_exc(formatstr, args, exception, excmsg) - test_exc(formatstr.encode('ascii'), args, exception, excmsg) class FormatTest(unittest.TestCase): + def check_exc(self, formatstr, args, exception, excmsg): + with self.assertRaisesRegex(exception, re.escape(excmsg)): + testformat(formatstr, args) + + def check_exc_common(self, formatstr, args, exception, excmsg): + # test str and bytes + self.check_exc(formatstr, args, exception, excmsg) + if isinstance(args, dict): + args = {k.encode('ascii'): v for k, v in args.items()} + self.check_exc(formatstr.encode('ascii'), args, exception, excmsg) + def test_common_format(self): # test the format identifiers that work the same across # str, bytes, and bytearrays (integer, float, oct, hex) @@ -272,45 +258,158 @@ def test_common_format(self): if verbose: print('Testing exceptions') - test_exc_common('%', (), ValueError, "incomplete format") - test_exc_common('% %s', 1, ValueError, - "unsupported format character '%' (0x25) at index 2") + test_exc_common = self.check_exc_common + test_exc_common('abc %', (), ValueError, "stray % at position 4") + test_exc_common('abc % %s', 1, ValueError, + "stray % at position 4 or unexpected format character '%' at position 6") + test_exc_common('abc %z', 1, ValueError, + "unsupported format %z at position 4") + test_exc_common("abc %Id", 1, ValueError, + "unsupported format %I at position 4") + test_exc_common("abc %'d", 1, ValueError, + "stray % at position 4 or unexpected format character \"'\" at position 5") + test_exc_common("abc %1 d", 1, ValueError, + "stray % at position 4 or unexpected format character ' ' at position 6") + test_exc_common('abc % (x)r', {}, ValueError, + "stray % at position 4 or unexpected format character '(' at position 6") + test_exc_common('abc %((x)r', {}, ValueError, + "stray % or incomplete format key at position 4") + test_exc_common('%r %r', 1, TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%r %r', (1,), TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%r', (), TypeError, + "not enough arguments for format string (got 0)") + test_exc_common('abc %' + '9'*50 + 'r', 1, ValueError, + "width too big at position 4") + test_exc_common('abc %.' + '9'*50 + 'r', 1, ValueError, + "precision too big at position 4") + test_exc_common('%r %*r', 1, TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%r %*r', (1,), TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%*r', (1,), TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%*r', (), TypeError, + "not enough arguments for format string (got 0)") + test_exc_common('%r %.*r', 1, TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%r %.*r', (1,), TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%.*r', (1,), TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%.*r', (), TypeError, + "not enough arguments for format string (got 0)") + test_exc_common('%(x)r', 1, TypeError, + "format requires a mapping, not int") + test_exc_common('%*r', 1, TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%*r', 3.14, TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%*r', (3.14, 1), TypeError, + "format argument 1: * requires int, not float") + test_exc_common('%.*r', 1, TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%.*r', 3.14, TypeError, + "not enough arguments for format string (got 1)") + test_exc_common('%.*r', (3.14, 1), TypeError, + "format argument 1: * requires int, not float") + test_exc_common('%*r', (2**1000, 1), OverflowError, + "format argument 1: too big for width") + test_exc_common('%*r', (-2**1000, 1), OverflowError, + "format argument 1: too big for width") + test_exc_common('%*r', (-maxsize - 1, 1), OverflowError, + "format argument 1: too big for width") + test_exc_common('%.*r', (2**1000, 1), OverflowError, + "format argument 1: too big for precision") + test_exc_common('%.*r', (-2**1000, 1), OverflowError, + "format argument 1: too big for precision") test_exc_common('%d', '1', TypeError, - "%d format: a real number is required, not str") + "format argument: %d requires a real number, not str") test_exc_common('%d', b'1', TypeError, - "%d format: a real number is required, not bytes") + "format argument: %d requires a real number, not bytes") + test_exc_common('%d', ('1',), TypeError, + "format argument 1: %d requires a real number, not str") test_exc_common('%x', '1', TypeError, - "%x format: an integer is required, not str") + "format argument: %x requires an integer, not str") test_exc_common('%x', 3.14, TypeError, - "%x format: an integer is required, not float") + "format argument: %x requires an integer, not float") + test_exc_common('%x', ('1',), TypeError, + "format argument 1: %x requires an integer, not str") test_exc_common('%i', '1', TypeError, - "%i format: a real number is required, not str") + "format argument: %i requires a real number, not str") test_exc_common('%i', b'1', TypeError, - "%i format: a real number is required, not bytes") + "format argument: %i requires a real number, not bytes") + test_exc_common('%g', '1', TypeError, + "format argument: %g requires a real number, not str") + test_exc_common('%g', ('1',), TypeError, + "format argument 1: %g requires a real number, not str") def test_str_format(self): testformat("%r", "\u0378", "'\\u0378'") # non printable testformat("%a", "\u0378", "'\\u0378'") # non printable testformat("%r", "\u0374", "'\u0374'") # printable testformat("%a", "\u0374", "'\\u0374'") # printable + testformat('%(x)r', {'x': 1}, '1') # Test exception for unknown format characters, etc. if verbose: print('Testing exceptions') + test_exc = self.check_exc test_exc('abc %b', 1, ValueError, - "unsupported format character 'b' (0x62) at index 5") - #test_exc(unicode('abc %\u3000','raw-unicode-escape'), 1, ValueError, - # "unsupported format character '?' (0x3000) at index 5") - test_exc('%g', '1', TypeError, "must be real number, not str") + "unsupported format %b at position 4") + test_exc("abc %\nd", 1, ValueError, + "stray % at position 4 or unexpected format character U+000A at position 5") + test_exc("abc %\x1fd", 1, ValueError, + "stray % at position 4 or unexpected format character U+001F at position 5") + test_exc("abc %\x7fd", 1, ValueError, + "stray % at position 4 or unexpected format character U+007F at position 5") + test_exc("abc %\x80d", 1, ValueError, + "stray % at position 4 or unexpected format character U+0080 at position 5") + test_exc('abc %äd', 1, ValueError, + "stray % at position 4 or unexpected format character 'ä' (U+00E4) at position 5") + test_exc('abc %€d', 1, ValueError, + "stray % at position 4 or unexpected format character '€' (U+20AC) at position 5") test_exc('no format', '1', TypeError, - "not all arguments converted during string formatting") - test_exc('%c', -1, OverflowError, "%c arg not in range(0x110000)") + "not all arguments converted during string formatting (required 0, got 1)") + test_exc('%r', (1, 2), TypeError, + "not all arguments converted during string formatting (required 1, got 2)") + test_exc('%(x)r %r', {'x': 1}, ValueError, + "format requires a parenthesised mapping key at position 6") + test_exc('%(x)*r', {'x': 1}, ValueError, + "* cannot be used with a parenthesised mapping key at position 0") + test_exc('%(x).*r', {'x': 1}, ValueError, + "* cannot be used with a parenthesised mapping key at position 0") + test_exc('%(x)d', {'x': '1'}, TypeError, + "format argument 'x': %d requires a real number, not str") + test_exc('%(x)x', {'x': '1'}, TypeError, + "format argument 'x': %x requires an integer, not str") + test_exc('%(x)g', {'x': '1'}, TypeError, + "format argument 'x': %g requires a real number, not str") + test_exc('%c', -1, OverflowError, + "format argument: %c argument not in range(0x110000)") + test_exc('%c', (-1,), OverflowError, + "format argument 1: %c argument not in range(0x110000)") + test_exc('%(x)c', {'x': -1}, OverflowError, + "format argument 'x': %c argument not in range(0x110000)") test_exc('%c', sys.maxunicode+1, OverflowError, - "%c arg not in range(0x110000)") - #test_exc('%c', 2**128, OverflowError, "%c arg not in range(0x110000)") - test_exc('%c', 3.14, TypeError, "%c requires an int or a unicode character, not float") - test_exc('%c', 'ab', TypeError, "%c requires an int or a unicode character, not a string of length 2") - test_exc('%c', b'x', TypeError, "%c requires an int or a unicode character, not bytes") + "format argument: %c argument not in range(0x110000)") + test_exc('%c', 2**128, OverflowError, + "format argument: %c argument not in range(0x110000)") + test_exc('%c', 3.14, TypeError, + "format argument: %c requires an integer or a unicode character, not float") + test_exc('%c', (3.14,), TypeError, + "format argument 1: %c requires an integer or a unicode character, not float") + test_exc('%(x)c', {'x': 3.14}, TypeError, + "format argument 'x': %c requires an integer or a unicode character, not float") + test_exc('%c', 'ab', TypeError, + "format argument: %c requires an integer or a unicode character, not a string of length 2") + test_exc('%c', ('ab',), TypeError, + "format argument 1: %c requires an integer or a unicode character, not a string of length 2") + test_exc('%(x)c', {'x': 'ab'}, TypeError, + "format argument 'x': %c requires an integer or a unicode character, not a string of length 2") + test_exc('%c', b'x', TypeError, + "format argument: %c requires an integer or a unicode character, not bytes") if maxsize == 2**31-1: # crashes 2.2.1 and earlier: @@ -355,36 +454,84 @@ def __bytes__(self): testcommon(b"%r", b"ghi", b"b'ghi'") testcommon(b"%r", "jkl", b"'jkl'") testcommon(b"%r", "\u0544", b"'\\u0544'") + testcommon(b'%(x)r', {b'x': 1}, b'1') # Test exception for unknown format characters, etc. if verbose: print('Testing exceptions') - test_exc(b'%g', '1', TypeError, "float argument required, not str") - test_exc(b'%g', b'1', TypeError, "float argument required, not bytes") + test_exc = self.check_exc + test_exc(b"abc %\nd", 1, ValueError, + "stray % at position 4 or unexpected format character with code 0x0a at position 5") + test_exc(b"abc %'d", 1, ValueError, + "stray % at position 4 or unexpected format character \"'\" at position 5") + test_exc(b"abc %\x1fd", 1, ValueError, + "stray % at position 4 or unexpected format character with code 0x1f at position 5") + test_exc(b"abc %\x7fd", 1, ValueError, + "stray % at position 4 or unexpected format character with code 0x7f at position 5") + test_exc(b"abc %\x80d", 1, ValueError, + "stray % at position 4 or unexpected format character with code 0x80 at position 5") test_exc(b'no format', 7, TypeError, - "not all arguments converted during bytes formatting") + "not all arguments converted during bytes formatting (required 0, got 1)") test_exc(b'no format', b'1', TypeError, - "not all arguments converted during bytes formatting") + "not all arguments converted during bytes formatting (required 0, got 1)") test_exc(b'no format', bytearray(b'1'), TypeError, - "not all arguments converted during bytes formatting") + "not all arguments converted during bytes formatting (required 0, got 1)") + test_exc(b'%r', (1, 2), TypeError, + "not all arguments converted during bytes formatting (required 1, got 2)") + test_exc(b'%(x)r %r', {b'x': 1}, ValueError, + "format requires a parenthesised mapping key at position 6") + test_exc(b'%(x)*r', {b'x': 1}, ValueError, + "* cannot be used with a parenthesised mapping key at position 0") + test_exc(b'%(x).*r', {b'x': 1}, ValueError, + "* cannot be used with a parenthesised mapping key at position 0") + test_exc(b'%(x)d', {b'x': '1'}, TypeError, + "format argument b'x': %d requires a real number, not str") + test_exc(b'%(x)x', {b'x': '1'}, TypeError, + "format argument b'x': %x requires an integer, not str") + test_exc(b'%(x)g', {b'x': '1'}, TypeError, + "format argument b'x': %g requires a real number, not str") test_exc(b"%c", -1, OverflowError, - "%c arg not in range(256)") + "format argument: %c argument not in range(256)") + test_exc(b"%c", (-1,), OverflowError, + "format argument 1: %c argument not in range(256)") + test_exc(b"%(x)c", {b'x': -1}, OverflowError, + "format argument b'x': %c argument not in range(256)") test_exc(b"%c", 256, OverflowError, - "%c arg not in range(256)") + "format argument: %c argument not in range(256)") test_exc(b"%c", 2**128, OverflowError, - "%c arg not in range(256)") + "format argument: %c argument not in range(256)") test_exc(b"%c", b"Za", TypeError, - "%c requires an integer in range(256) or a single byte, not a bytes object of length 2") + "format argument: %c requires an integer in range(256) or a single byte, not a bytes object of length 2") + test_exc(b"%c", (b"Za",), TypeError, + "format argument 1: %c requires an integer in range(256) or a single byte, not a bytes object of length 2") + test_exc(b"%(x)c", {b'x': b"Za"}, TypeError, + "format argument b'x': %c requires an integer in range(256) or a single byte, not a bytes object of length 2") + test_exc(b"%c", bytearray(b"Za"), TypeError, + "format argument: %c requires an integer in range(256) or a single byte, not a bytearray object of length 2") + test_exc(b"%c", (bytearray(b"Za"),), TypeError, + "format argument 1: %c requires an integer in range(256) or a single byte, not a bytearray object of length 2") + test_exc(b"%(x)c", {b'x': bytearray(b"Za")}, TypeError, + "format argument b'x': %c requires an integer in range(256) or a single byte, not a bytearray object of length 2") test_exc(b"%c", "Y", TypeError, - "%c requires an integer in range(256) or a single byte, not str") + "format argument: %c requires an integer in range(256) or a single byte, not str") test_exc(b"%c", 3.14, TypeError, - "%c requires an integer in range(256) or a single byte, not float") + "format argument: %c requires an integer in range(256) or a single byte, not float") + test_exc(b"%c", (3.14,), TypeError, + "format argument 1: %c requires an integer in range(256) or a single byte, not float") + test_exc(b"%(x)c", {b'x': 3.14}, TypeError, + "format argument b'x': %c requires an integer in range(256) or a single byte, not float") test_exc(b"%b", "Xc", TypeError, - "%b requires a bytes-like object, " - "or an object that implements __bytes__, not 'str'") + "format argument: %b requires a bytes-like object, " + "or an object that implements __bytes__, not str") + test_exc(b"%b", ("Xc",), TypeError, + "format argument 1: %b requires a bytes-like object, " + "or an object that implements __bytes__, not str") + test_exc(b"%(x)b", {b'x': "Xc"}, TypeError, + "format argument b'x': %b requires a bytes-like object, " + "or an object that implements __bytes__, not str") test_exc(b"%s", "Wd", TypeError, - "%b requires a bytes-like object, " - "or an object that implements __bytes__, not 'str'") + "format argument: %b requires a bytes-like object, " + "or an object that implements __bytes__, not str") if maxsize == 2**31-1: # crashes 2.2.1 and earlier: @@ -494,6 +641,28 @@ def test_precision_c_limits(self): with self.assertRaises(ValueError) as cm: format(c, ".%sf" % (INT_MAX + 1)) + @support.cpython_only + def test_precision_near_int_max(self): + # gh-158446: Precisions just below INT_MAX are rejected before any + # output buffer size is computed from them. + _testcapi = import_module("_testcapi") + INT_MAX = _testcapi.INT_MAX + + f = 1e300 + c = complex(f) + for prec in (INT_MAX, INT_MAX - 1023): + for code in "feg": + spec = ".%d%s" % (prec, code) + with self.subTest(spec=spec): + with self.assertRaises(ValueError): + format(f, spec) + with self.assertRaises(ValueError): + format(c, spec) + with self.assertRaises(ValueError): + ("%" + spec) % f + with self.assertRaises(ValueError): + ("%" + spec).encode() % f + def test_g_format_has_no_trailing_zeros(self): # regression test for bugs.python.org/issue40780 self.assertEqual("%.3g" % 1505.0, "1.5e+03") @@ -529,7 +698,6 @@ def test_with_an_underscore_and_a_comma_in_format_specifier(self): with self.assertRaisesRegex(ValueError, error_msg): '{:._,f}'.format(1.1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_better_error_message_format(self): # https://bugs.python.org/issue20524 for value in [12j, 12, 12.0, "12"]: @@ -551,7 +719,6 @@ def test_better_error_message_format(self): with self.assertRaisesRegex(ValueError, err): eval("f'xx{value:{bad_format_spec}}yy'") - @unittest.expectedFailure # TODO: RUSTPYTHON def test_unicode_in_error_message(self): str_err = re.escape( "Invalid format specifier '%ЫйЯЧ' for object of type 'str'") @@ -615,7 +782,6 @@ def test_negative_zero(self): self.assertEqual(f"{-0.:x>z6.1f}", "xxx0.0") self.assertEqual(f"{-0.:🖤>z6.1f}", "🖤🖤🖤0.0") # multi-byte fill char - @unittest.expectedFailure # TODO: RUSTPYTHON def test_specifier_z_error(self): error_msg = re.compile("Invalid format specifier '.*z.*'") with self.assertRaisesRegex(ValueError, error_msg): @@ -629,7 +795,7 @@ def test_specifier_z_error(self): with self.assertRaisesRegex(ValueError, error_msg): f"{'x':zs}" # can't apply to string - error_msg = re.escape("unsupported format character 'z'") + error_msg = re.escape("unsupported format %z at position 0") with self.assertRaisesRegex(ValueError, error_msg): "%z.1f" % 0 # not allowed in old style string interpolation with self.assertRaisesRegex(ValueError, error_msg): diff --git a/Lib/test/test_frame.py b/Lib/test/test_frame.py index ad7eda56637..f7cb33a194a 100644 --- a/Lib/test/test_frame.py +++ b/Lib/test/test_frame.py @@ -222,6 +222,33 @@ def test_f_lineno_del_segfault(self): with self.assertRaises(AttributeError): del f.f_lineno + def test_f_trace(self): + f, _, _ = self.make_frames() + def tracer(*args): + pass + for value in tracer, 42, None: + f.f_trace = value + self.assertEqual(f.f_trace, value) + f.f_trace = tracer + del f.f_trace + self.assertIsNone(f.f_trace) + + def test_f_trace_lines_and_opcodes(self): + f, _, _ = self.make_frames() + for name in 'f_trace_lines', 'f_trace_opcodes': + with self.subTest(name=name): + for value in False, True: + setattr(f, name, value) + self.assertEqual(getattr(f, name), value) + with self.assertRaisesRegex(TypeError, + 'attribute value type must be bool'): + setattr(f, name, 1) + with self.assertRaisesRegex(TypeError, + "can't delete numeric/char attribute"): + del f.f_trace_lines + with self.assertRaisesRegex(AttributeError, 'cannot be deleted'): + del f.f_trace_opcodes + def test_f_generator(self): # Test f_generator in different contexts. @@ -776,7 +803,6 @@ def run(self): ) sneaky_frame_object = sneaky_frame_object.f_back - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'NoneType' object has no attribute 'exc_type' def test_entry_frames_are_invisible_during_teardown(self): class C: """A weakref'able class.""" diff --git a/Lib/test/test_free_threading/__init__.py b/Lib/test/test_free_threading/__init__.py new file mode 100644 index 00000000000..34e1ad30e11 --- /dev/null +++ b/Lib/test/test_free_threading/__init__.py @@ -0,0 +1,11 @@ +import os +import unittest + +from test import support + + +if not support.Py_GIL_DISABLED: + raise unittest.SkipTest("GIL enabled") + +def load_tests(*args): + return support.load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_free_threading/test_bisect.py b/Lib/test/test_free_threading/test_bisect.py new file mode 100644 index 00000000000..bd7732da035 --- /dev/null +++ b/Lib/test/test_free_threading/test_bisect.py @@ -0,0 +1,56 @@ +import unittest +from test.support import import_helper, threading_helper +import random + +py_bisect = import_helper.import_fresh_module('bisect', blocked=['_bisect']) +c_bisect = import_helper.import_fresh_module('bisect', fresh=['_bisect']) + + +NTHREADS = 4 +OBJECT_COUNT = 500 + + +class TestBase: + def do_racing_insort(self, insert_method): + def insert(data): + for _ in range(OBJECT_COUNT): + x = random.randint(-OBJECT_COUNT, OBJECT_COUNT) + insert_method(data, x) + + data = list(range(OBJECT_COUNT)) + threading_helper.run_concurrently( + worker_func=insert, args=(data,), nthreads=NTHREADS + ) + if False: + # These functions are not thread-safe and so the list can become + # unsorted. However, we don't want Python to crash if these + # functions are used concurrently on the same sequence. This + # should also not produce any TSAN warnings. + self.assertTrue(self.is_sorted_ascending(data)) + + def test_racing_insert_right(self): + self.do_racing_insort(self.mod.insort_right) + + def test_racing_insert_left(self): + self.do_racing_insort(self.mod.insort_left) + + @staticmethod + def is_sorted_ascending(lst): + """ + Check if the list is sorted in ascending order (non-decreasing). + """ + return all(lst[i - 1] <= lst[i] for i in range(1, len(lst))) + + +@threading_helper.requires_working_threading() +class TestPyBisect(unittest.TestCase, TestBase): + mod = py_bisect + + +@threading_helper.requires_working_threading() +class TestCBisect(unittest.TestCase, TestBase): + mod = c_bisect + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_bz2.py b/Lib/test/test_free_threading/test_bz2.py new file mode 100644 index 00000000000..3bb531ec04c --- /dev/null +++ b/Lib/test/test_free_threading/test_bz2.py @@ -0,0 +1,64 @@ +import unittest + +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently + +bz2 = import_helper.import_module("bz2") +from bz2 import BZ2Compressor, BZ2Decompressor + +from test.test_bz2 import ext_decompress, BaseTest + + +NTHREADS = 10 +TEXT = BaseTest.TEXT + + +@threading_helper.requires_working_threading() +class TestBZ2(unittest.TestCase): + def test_compressor(self): + bz2c = BZ2Compressor() + + def worker(): + # it should return empty bytes as it buffers data internally + data = bz2c.compress(TEXT) + self.assertEqual(data, b"") + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + data = bz2c.flush() + # The decompressed data should be TEXT repeated NTHREADS times + decompressed = ext_decompress(data) + self.assertEqual(decompressed, TEXT * NTHREADS) + + def test_decompressor(self): + chunk_size = 128 + chunks = [bytes([ord("a") + i]) * chunk_size for i in range(NTHREADS)] + input_data = b"".join(chunks) + compressed = bz2.compress(input_data) + + bz2d = BZ2Decompressor() + output = [] + + def worker(): + data = bz2d.decompress(compressed, chunk_size) + self.assertEqual(len(data), chunk_size) + output.append(data) + # Read attributes concurrently with other threads decompressing + self.assertIsInstance(bz2d.eof, bool) + self.assertIsInstance(bz2d.needs_input, bool) + self.assertIsInstance(bz2d.unused_data, bytes) + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + self.assertEqual(len(output), NTHREADS) + # Verify the expected chunks (order doesn't matter due to append race) + self.assertEqual(set(output), set(chunks)) + self.assertTrue(bz2d.eof) + self.assertFalse(bz2d.needs_input) + # Each thread added full compressed data to the buffer, but only 1 copy + # is consumed to produce the output. The rest remains as unused_data. + self.assertEqual( + len(bz2d.unused_data), len(compressed) * (NTHREADS - 1) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_capi.py b/Lib/test/test_free_threading/test_capi.py new file mode 100644 index 00000000000..2b03312d624 --- /dev/null +++ b/Lib/test/test_free_threading/test_capi.py @@ -0,0 +1,48 @@ +import ctypes +import sys +import unittest + +from test.support import get_attribute, threading_helper +from test.support.threading_helper import run_concurrently + + +# TODO: RUSTPYTHON; executable C API exports are optional. +_PyImport_AddModuleRef = get_attribute(ctypes.pythonapi, "PyImport_AddModuleRef") +_PyImport_AddModuleRef.argtypes = (ctypes.c_char_p,) +_PyImport_AddModuleRef.restype = ctypes.py_object + + +@threading_helper.requires_working_threading() +class TestImportCAPI(unittest.TestCase): + def test_pyimport_addmoduleref_thread_safe(self): + # gh-137422: Concurrent calls to PyImport_AddModuleRef with the same + # module name must return the same module object. + + NUM_ITERS = 10 + NTHREADS = 4 + + module_name = f"test_free_threading_addmoduleref_{id(self)}" + module_name_bytes = module_name.encode() + sys.modules.pop(module_name, None) + results = [] + + def worker(): + module = _PyImport_AddModuleRef(module_name_bytes) + results.append(module) + + for _ in range(NUM_ITERS): + try: + run_concurrently(worker_func=worker, nthreads=NTHREADS) + self.assertEqual(len(results), NTHREADS) + reference = results[0] + for module in results[1:]: + self.assertIs(module, reference) + self.assertIn(module_name, sys.modules) + self.assertIs(sys.modules[module_name], reference) + finally: + results.clear() + sys.modules.pop(module_name, None) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_collections.py b/Lib/test/test_free_threading/test_collections.py new file mode 100644 index 00000000000..849b0480e23 --- /dev/null +++ b/Lib/test/test_free_threading/test_collections.py @@ -0,0 +1,53 @@ +import unittest +from collections import deque +from copy import copy +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) + + +class TestDeque(unittest.TestCase): + def test_copy_race(self): + # gh-144809: Test that deque copy is thread safe. It previously + # could raise a "deque mutated during iteration" error. + d = deque(range(100)) + + def mutate(): + for i in range(1000): + d.append(i) + if len(d) > 200: + d.popleft() + + def copy_loop(): + for _ in range(1000): + copy(d) + + threading_helper.run_concurrently([mutate, copy_loop]) + + def test_index_race_in_ac(self): + # gh-150750: There was a c_default specified as `Py_SIZE(self)`, + # it was used without a critical section. + + d = deque(range(100)) + + def index(): + for _ in range(10000): + try: + d.index(50) + except ValueError: + pass + + def mutate(): + for _ in range(10000): + d.append(0) + d.clear() + d.extend(range(100)) + d.appendleft(-1) + + threading_helper.run_concurrently( + [index, *[mutate for _ in range(3)]], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_context.py b/Lib/test/test_free_threading/test_context.py new file mode 100644 index 00000000000..02701fe25a8 --- /dev/null +++ b/Lib/test/test_free_threading/test_context.py @@ -0,0 +1,57 @@ +import contextvars +import unittest +from threading import Event, Thread + +from test.support import threading_helper + + +@threading_helper.requires_working_threading() +class TestContext(unittest.TestCase): + def test_racing_read_write(self): + # gh-154535: reading a Context object from one thread while another + # thread sets variables in it used to crash. The readers looked at + # Context.ctx_vars without owning a reference to it, so the writer + # could deallocate the mapping while a reader was walking it. + ctx = contextvars.Context() + cvars = [contextvars.ContextVar(f"cvar{i}") for i in range(64)] + done = Event() + errors = [] + + def writer(): + def body(): + i = 0 + while not done.is_set(): + cvars[i % len(cvars)].set(i) + i += 1 + try: + ctx.run(body) + except BaseException as e: + errors.append(e) + + def reader(): + try: + for _ in range(200): + ctx.copy() + len(ctx) + list(ctx) + list(ctx.items()) + list(ctx.keys()) + list(ctx.values()) + cvars[0] in ctx + ctx.get(cvars[0]) + ctx == ctx + except BaseException as e: + errors.append(e) + finally: + done.set() + + threads = [Thread(target=writer)] + threads += [Thread(target=reader) for _ in range(4)] + with threading_helper.start_threads(threads, done.set): + pass + + self.assertEqual(errors, [], msg=f"unexpected errors: {errors}") + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_cprofile.py b/Lib/test/test_free_threading/test_cprofile.py new file mode 100644 index 00000000000..361b800d6b9 --- /dev/null +++ b/Lib/test/test_free_threading/test_cprofile.py @@ -0,0 +1,43 @@ +import unittest + +from test.support import threading_helper + +import cProfile +import pstats + + +NTHREADS = 10 +INSERT_PER_THREAD = 1000 + + +@threading_helper.requires_working_threading() +class TestCProfile(unittest.TestCase): + def test_cprofile_racing_list_insert(self): + def list_insert(lst): + for i in range(INSERT_PER_THREAD): + lst.insert(0, i) + + lst = [] + + with cProfile.Profile() as pr: + threading_helper.run_concurrently( + worker_func=list_insert, nthreads=NTHREADS, args=(lst,) + ) + pr.create_stats() + ps = pstats.Stats(pr) + stats_profile = ps.get_stats_profile() + list_insert_profile = stats_profile.func_profiles[ + "" + ] + # Even though there is no explicit recursive call to insert, + # cProfile may record some calls as recursive due to limitations + # in its handling of multithreaded programs. This issue is not + # directly related to FT Python itself; however, it tends to be + # more noticeable when using FT Python. Therefore, consider only + # the calls section and disregard the recursive part. + list_insert_ncalls = list_insert_profile.ncalls.split("/")[0] + self.assertEqual( + int(list_insert_ncalls), NTHREADS * INSERT_PER_THREAD + ) + + self.assertEqual(len(lst), NTHREADS * INSERT_PER_THREAD) diff --git a/Lib/test/test_free_threading/test_csv.py b/Lib/test/test_free_threading/test_csv.py new file mode 100644 index 00000000000..beb4510a128 --- /dev/null +++ b/Lib/test/test_free_threading/test_csv.py @@ -0,0 +1,50 @@ +import csv +import io +import unittest + +from test.support import threading_helper +from test.support.threading_helper import run_concurrently + + +NTHREADS = 10 + + +@threading_helper.requires_working_threading() +class TestCSV(unittest.TestCase): + def test_concurrent_reader_next(self): + input_rows = [f"{i},{i},{i}" for i in range(50)] + input_stream = io.StringIO("\n".join(input_rows)) + reader = csv.reader(input_stream) + output_rows = [] + + def read_row(): + for row in reader: + self.assertEqual(len(row), 3) + output_rows.append(",".join(row)) + + run_concurrently(worker_func=read_row, nthreads=NTHREADS) + self.assertSetEqual(set(input_rows), set(output_rows)) + + def test_concurrent_writer_writerow(self): + output_stream = io.StringIO() + writer = csv.writer(output_stream) + row_per_thread = 10 + expected_rows = [] + + def write_row(): + for i in range(row_per_thread): + writer.writerow([i, i, i]) + expected_rows.append(f"{i},{i},{i}") + + run_concurrently(worker_func=write_row, nthreads=NTHREADS) + + # Rewind to the start of the stream and parse the rows + output_stream.seek(0) + output_rows = [line.strip() for line in output_stream.readlines()] + + self.assertEqual(len(output_rows), NTHREADS * row_per_thread) + self.assertListEqual(sorted(output_rows), sorted(expected_rows)) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_dict.py b/Lib/test/test_free_threading/test_dict.py new file mode 100644 index 00000000000..4a812275143 --- /dev/null +++ b/Lib/test/test_free_threading/test_dict.py @@ -0,0 +1,360 @@ +import gc +import time +import unittest +import weakref + +from ast import Or +from functools import partial +from threading import Barrier, Thread +from unittest import TestCase + +try: + import _testcapi +except ImportError: + _testcapi = None + +from test.support import threading_helper + + +@threading_helper.requires_working_threading() +class TestDict(TestCase): + def test_racing_creation_shared_keys(self): + """Verify that creating dictionaries is thread safe when we + have a type with shared keys""" + class C(int): + pass + + self.racing_creation(C) + + def test_racing_creation_no_shared_keys(self): + """Verify that creating dictionaries is thread safe when we + have a type with an ordinary dict""" + self.racing_creation(Or) + + def test_racing_creation_inline_values_invalid(self): + """Verify that re-creating a dict after we have invalid inline values + is thread safe""" + class C: + pass + + def make_obj(): + a = C() + # Make object, make inline values invalid, and then delete dict + a.__dict__ = {} + del a.__dict__ + return a + + self.racing_creation(make_obj) + + def test_racing_creation_nonmanaged_dict(self): + """Verify that explicit creation of an unmanaged dict is thread safe + outside of the normal attribute setting code path""" + def make_obj(): + def f(): pass + return f + + def set(func, name, val): + # Force creation of the dict via PyObject_GenericGetDict + func.__dict__[name] = val + + self.racing_creation(make_obj, set) + + def racing_creation(self, cls, set=setattr): + objects = [] + processed = [] + + OBJECT_COUNT = 100 + THREAD_COUNT = 10 + CUR = 0 + + for i in range(OBJECT_COUNT): + objects.append(cls()) + + def writer_func(name): + last = -1 + while True: + if CUR == last: + time.sleep(0.001) + continue + elif CUR == OBJECT_COUNT: + break + + obj = objects[CUR] + set(obj, name, name) + last = CUR + processed.append(name) + + writers = [] + for x in range(THREAD_COUNT): + writer = Thread(target=partial(writer_func, f"a{x:02}")) + writers.append(writer) + writer.start() + + for i in range(OBJECT_COUNT): + CUR = i + while len(processed) != THREAD_COUNT: + time.sleep(0.001) + processed.clear() + + CUR = OBJECT_COUNT + + for writer in writers: + writer.join() + + for obj_idx, obj in enumerate(objects): + assert ( + len(obj.__dict__) == THREAD_COUNT + ), f"{len(obj.__dict__)} {obj.__dict__!r} {obj_idx}" + for i in range(THREAD_COUNT): + assert f"a{i:02}" in obj.__dict__, f"a{i:02} missing at {obj_idx}" + + def test_racing_set_dict(self): + """Races assigning to __dict__ should be thread safe""" + + def f(): pass + l = [] + THREAD_COUNT = 10 + class MyDict(dict): pass + + def writer_func(l): + for i in range(1000): + d = MyDict() + l.append(weakref.ref(d)) + f.__dict__ = d + + lists = [] + writers = [] + for x in range(THREAD_COUNT): + thread_list = [] + lists.append(thread_list) + writer = Thread(target=partial(writer_func, thread_list)) + writers.append(writer) + + for writer in writers: + writer.start() + + for writer in writers: + writer.join() + + f.__dict__ = {} + gc.collect() + + for thread_list in lists: + for ref in thread_list: + self.assertIsNone(ref()) + + def test_racing_get_set_dict(self): + """Races getting and setting a dict should be thread safe""" + THREAD_COUNT = 10 + barrier = Barrier(THREAD_COUNT) + def work(d): + barrier.wait() + for _ in range(1000): + d[10] = 0 + d.get(10, None) + _ = d[10] + + d = {} + worker_threads = [] + for ii in range(THREAD_COUNT): + worker_threads.append(Thread(target=work, args=[d])) + for t in worker_threads: + t.start() + for t in worker_threads: + t.join() + + + def test_racing_set_object_dict(self): + """Races assigning to __dict__ should be thread safe""" + class C: pass + class MyDict(dict): pass + for cyclic in (False, True): + f = C() + f.__dict__ = {"foo": 42} + THREAD_COUNT = 10 + + def writer_func(l): + for i in range(1000): + if cyclic: + other_d = {} + d = MyDict({"foo": 100}) + if cyclic: + d["x"] = other_d + other_d["bar"] = d + l.append(weakref.ref(d)) + f.__dict__ = d + + def reader_func(): + for i in range(1000): + f.foo + + lists = [] + readers = [] + writers = [] + for x in range(THREAD_COUNT): + thread_list = [] + lists.append(thread_list) + writer = Thread(target=partial(writer_func, thread_list)) + writers.append(writer) + + for x in range(THREAD_COUNT): + reader = Thread(target=partial(reader_func)) + readers.append(reader) + + for writer in writers: + writer.start() + for reader in readers: + reader.start() + + for writer in writers: + writer.join() + + for reader in readers: + reader.join() + + f.__dict__ = {} + gc.collect() + gc.collect() + + count = 0 + ids = set() + for thread_list in lists: + for i, ref in enumerate(thread_list): + if ref() is None: + continue + count += 1 + ids.add(id(ref())) + count += 1 + + self.assertEqual(count, 0) + + def test_racing_object_get_set_dict(self): + e = Exception() + + def writer(): + for i in range(10000): + e.__dict__ = {1:2} + + def reader(): + for i in range(10000): + e.__dict__ + + t1 = Thread(target=writer) + t2 = Thread(target=reader) + + with threading_helper.start_threads([t1, t2]): + pass + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_racing_watch_unwatch_dict(self): + # gh-148393: race between PyDict_Watch / PyDict_Unwatch + # and concurrent dict mutation reading _ma_watcher_tag. + wid = _testcapi.add_dict_watcher(0) + try: + d = {} + ITERS = 1000 + + def writer(): + for i in range(ITERS): + d[i] = i + del d[i] + + def watcher(): + for _ in range(ITERS): + _testcapi.watch_dict(wid, d) + _testcapi.unwatch_dict(wid, d) + + threading_helper.run_concurrently([writer, watcher]) + finally: + _testcapi.clear_dict_watcher(wid) + + def test_racing_split_dict_clear_and_lookup(self): + class C: + pass + + keys = [f"a{i}" for i in range(16)] + + def make_split_nonembedded(): + inst = C() + for key in keys: + setattr(inst, key, keys.index(key)) + # dict.copy() of a split instance dict yields a split table + # with non-embedded values + return inst.__dict__.copy() + + d = make_split_nonembedded() + + def clearer(): + for _ in range(1000): + d.clear() + d.update(make_split_nonembedded()) + + def reader(): + for _ in range(1000): + for k in keys: + d.get(k) + + threading_helper.run_concurrently([clearer, reader, reader]) + + def test_racing_embedded_values_clear_and_lookup(self): + class C: + pass + + obj = C() + def writer(): + for _ in range(1000): + obj.x = 1 + obj.y = 2 + obj.z = 3 + obj.__dict__.clear() + + def reader(): + for _ in range(1000): + obj.__dict__.get('x') + + threading_helper.run_concurrently([writer, reader, reader]) + + def test_racing_dict_update_and_method_lookup(self): + # gh-144295: test race between dict modifications and method lookups. + # Uses BytesIO because the race requires a type without Py_TPFLAGS_INLINE_VALUES + # for the _PyDict_GetMethodStackRef code path. + import io + obj = io.BytesIO() + + def writer(): + for _ in range(10000): + obj.x = 1 + del obj.x + + def reader(): + for _ in range(10000): + obj.getvalue() + + t1 = Thread(target=writer) + t2 = Thread(target=reader) + + with threading_helper.start_threads([t1, t2]): + pass + + def test_getstate_race_with_shared_keys(self): + box = [None] + enter = Barrier(2) + leave = Barrier(2) + + def reader(): + for _ in range(1000): + enter.wait() + box[0].__getstate__() + leave.wait() + + def writer(): + for i in range(1000): + box[0] = type(f"C{i}", (), {})() + enter.wait() + setattr(box[0], str(i), 1) + leave.wait() + + threading_helper.run_concurrently([reader, writer]) + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_enumerate.py b/Lib/test/test_free_threading/test_enumerate.py new file mode 100644 index 00000000000..d23f5e9529f --- /dev/null +++ b/Lib/test/test_free_threading/test_enumerate.py @@ -0,0 +1,38 @@ +import unittest +import sys +from threading import Thread, Barrier + +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) + +class EnumerateThreading(unittest.TestCase): + + @threading_helper.reap_threads + def test_threading(self): + number_of_threads = 10 + number_of_iterations = 8 + n = 100 + start = sys.maxsize - 40 + barrier = Barrier(number_of_threads) + def work(enum): + barrier.wait() + while True: + try: + _ = next(enum) + except StopIteration: + break + + for it in range(number_of_iterations): + enum = enumerate(tuple(range(start, start + n))) + worker_threads = [] + for ii in range(number_of_threads): + worker_threads.append( + Thread(target=work, args=[enum])) + with threading_helper.start_threads(worker_threads): + pass + + barrier.reset() + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_exceptions.py b/Lib/test/test_free_threading/test_exceptions.py new file mode 100644 index 00000000000..61146f29c78 --- /dev/null +++ b/Lib/test/test_free_threading/test_exceptions.py @@ -0,0 +1,16 @@ +import unittest +import copy + +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) +class ExceptionTests(unittest.TestCase): + def test_setstate_data_race(self): + E = Exception() + + def func(): + for i in range(100): + setattr(E, 'x', i) + copy.copy(E) + + threading_helper.run_concurrently(func, nthreads=4) diff --git a/Lib/test/test_free_threading/test_func_annotations.py b/Lib/test/test_free_threading/test_func_annotations.py new file mode 100644 index 00000000000..0fde0136d77 --- /dev/null +++ b/Lib/test/test_free_threading/test_func_annotations.py @@ -0,0 +1,67 @@ +import concurrent.futures +import unittest +import inspect +from threading import Barrier +from unittest import TestCase + +from test.support import threading_helper, Py_GIL_DISABLED + +threading_helper.requires_working_threading(module=True) + + +def get_func_annotation(f, b): + b.wait() + return inspect.get_annotations(f) + + +def get_func_annotation_dunder(f, b): + b.wait() + return f.__annotations__ + + +def set_func_annotation(f, b): + b.wait() + f.__annotations__ = {'x': int, 'y': int, 'return': int} + return f.__annotations__ + + +@unittest.skipUnless(Py_GIL_DISABLED, "Enable only in FT build") +class TestFTFuncAnnotations(TestCase): + NUM_THREADS = 4 + + def test_concurrent_read(self): + def f(x: int) -> int: + return x + 1 + + for _ in range(10): + with concurrent.futures.ThreadPoolExecutor(max_workers=self.NUM_THREADS) as executor: + b = Barrier(self.NUM_THREADS) + futures = {executor.submit(get_func_annotation, f, b): i for i in range(self.NUM_THREADS)} + for fut in concurrent.futures.as_completed(futures): + annotate = fut.result() + self.assertIsNotNone(annotate) + self.assertEqual(annotate, {'x': int, 'return': int}) + + with concurrent.futures.ThreadPoolExecutor(max_workers=self.NUM_THREADS) as executor: + b = Barrier(self.NUM_THREADS) + futures = {executor.submit(get_func_annotation_dunder, f, b): i for i in range(self.NUM_THREADS)} + for fut in concurrent.futures.as_completed(futures): + annotate = fut.result() + self.assertIsNotNone(annotate) + self.assertEqual(annotate, {'x': int, 'return': int}) + + def test_concurrent_write(self): + def bar(x: int, y: float) -> float: + return y ** x + + for _ in range(10): + with concurrent.futures.ThreadPoolExecutor(max_workers=self.NUM_THREADS) as executor: + b = Barrier(self.NUM_THREADS) + futures = {executor.submit(set_func_annotation, bar, b): i for i in range(self.NUM_THREADS)} + for fut in concurrent.futures.as_completed(futures): + annotate = fut.result() + self.assertIsNotNone(annotate) + self.assertEqual(annotate, {'x': int, 'y': int, 'return': int}) + + # func_get_annotations returns in-place dict, so bar.__annotations__ should be modified as well + self.assertEqual(bar.__annotations__, {'x': int, 'y': int, 'return': int}) diff --git a/Lib/test/test_free_threading/test_functions.py b/Lib/test/test_free_threading/test_functions.py new file mode 100644 index 00000000000..7a59638d27d --- /dev/null +++ b/Lib/test/test_free_threading/test_functions.py @@ -0,0 +1,104 @@ +import random +import unittest +from unittest import TestCase + +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) + +NUM_THREADS = 8 +ITERS = 200 + + +def random_string(): + return ''.join(random.choice('0123456789ABCDEF') for _ in range(10)) + + +def template_a(): pass +def template_b(): pass + + +class TestFTFunctionAttributes(TestCase): + + def stress_attribute(self, attr, make_value): + def target(x=1): + return x + + def writer(): + for _ in range(ITERS): + setattr(target, attr, make_value()) + getattr(target, attr) + + threading_helper.run_concurrently(writer, NUM_THREADS) + + def test_name(self): + self.stress_attribute("__name__", random_string) + + def test_qualname(self): + self.stress_attribute("__qualname__", random_string) + + def test_code(self): + codes = (template_a.__code__, template_b.__code__) + self.stress_attribute("__code__", lambda: random.choice(codes)) + + def test_defaults(self): + self.stress_attribute("__defaults__", lambda: (random_string(),)) + + def test_kwdefaults(self): + self.stress_attribute("__kwdefaults__", lambda: {"x": random_string()}) + + def test_annotations(self): + self.stress_attribute("__annotations__", + lambda: {"x": random_string()}) + + def test_annotate(self): + self.stress_attribute("__annotate__", + lambda: (lambda format: {"x": str})) + + def test_type_params(self): + self.stress_attribute("__type_params__", lambda: (random_string(),)) + + def test_doc(self): + self.stress_attribute("__doc__", random_string) + + def test_module(self): + self.stress_attribute("__module__", random_string) + + def test_annotations_and_annotate(self): + # The __annotations__ and __annotate__ setters clear each other. + def target(): pass + + def set_annotations(): + for _ in range(ITERS): + target.__annotations__ = {"x": random_string()} + target.__annotations__ + + def set_annotate(): + for _ in range(ITERS): + target.__annotate__ = lambda format: {"x": str} + target.__annotate__ + + threading_helper.run_concurrently( + [set_annotations, set_annotate] * (NUM_THREADS // 2)) + + def test_call_while_replacing_defaults(self): + # The eval loop reads __defaults__ and __kwdefaults__ without holding + # a lock while pushing a frame. + def target(x="init", *, y="init"): + return x, y + + def writer(): + for _ in range(ITERS): + target.__defaults__ = (random_string(),) + target.__kwdefaults__ = {"y": random_string()} + + def caller(): + for _ in range(ITERS): + target() + + threading_helper.run_concurrently( + [writer, caller] * (NUM_THREADS // 2)) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_functools.py b/Lib/test/test_free_threading/test_functools.py new file mode 100644 index 00000000000..a442fe056ce --- /dev/null +++ b/Lib/test/test_free_threading/test_functools.py @@ -0,0 +1,75 @@ +import random +import unittest + +from functools import lru_cache +from threading import Barrier, Thread + +from test.support import threading_helper + +@threading_helper.requires_working_threading() +class TestLRUCache(unittest.TestCase): + + def _test_concurrent_operations(self, maxsize): + num_threads = 10 + b = Barrier(num_threads) + @lru_cache(maxsize=maxsize) + def func(arg=0): + return object() + + + def thread_func(): + b.wait() + for i in range(1000): + r = random.randint(0, 1000) + if i < 800: + func(i) + elif i < 900: + func.cache_info() + else: + func.cache_clear() + + threads = [] + for i in range(num_threads): + t = Thread(target=thread_func) + threads.append(t) + + with threading_helper.start_threads(threads): + pass + + def test_concurrent_operations_unbounded(self): + self._test_concurrent_operations(maxsize=None) + + def test_concurrent_operations_bounded(self): + self._test_concurrent_operations(maxsize=128) + + def _test_reentrant_cache_clear(self, maxsize): + num_threads = 10 + b = Barrier(num_threads) + @lru_cache(maxsize=maxsize) + def func(arg=0): + func.cache_clear() + return object() + + + def thread_func(): + b.wait() + for i in range(1000): + func(random.randint(0, 10000)) + + threads = [] + for i in range(num_threads): + t = Thread(target=thread_func) + threads.append(t) + + with threading_helper.start_threads(threads): + pass + + def test_reentrant_cache_clear_unbounded(self): + self._test_reentrant_cache_clear(maxsize=None) + + def test_reentrant_cache_clear_bounded(self): + self._test_reentrant_cache_clear(maxsize=128) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_generators.py b/Lib/test/test_free_threading/test_generators.py new file mode 100644 index 00000000000..382503eebd1 --- /dev/null +++ b/Lib/test/test_free_threading/test_generators.py @@ -0,0 +1,157 @@ +import concurrent.futures +import itertools +import threading +import unittest +from threading import Barrier +import random +import time + +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) + + +def random_sleep(): + delay_us = random.randint(50, 100) + time.sleep(delay_us * 1e-6) + +def random_string(): + return ''.join(random.choice('0123456789ABCDEF') for _ in range(10)) + +def set_gen_name(g, b): + b.wait() + random_sleep() + g.__name__ = random_string() + return g.__name__ + +def set_gen_qualname(g, b): + b.wait() + random_sleep() + g.__qualname__ = random_string() + return g.__qualname__ + + +class TestFTGenerators(unittest.TestCase): + NUM_THREADS = 4 + + def concurrent_write_with_func(self, func): + gen = (x for x in range(42)) + for j in range(1000): + with concurrent.futures.ThreadPoolExecutor(max_workers=self.NUM_THREADS) as executor: + b = Barrier(self.NUM_THREADS) + futures = {executor.submit(func, gen, b): i for i in range(self.NUM_THREADS)} + for fut in concurrent.futures.as_completed(futures): + gen_name = fut.result() + self.assertEqual(len(gen_name), 10) + + def test_concurrent_write(self): + with self.subTest(func=set_gen_name): + self.concurrent_write_with_func(func=set_gen_name) + with self.subTest(func=set_gen_qualname): + self.concurrent_write_with_func(func=set_gen_qualname) + + def test_concurrent_send(self): + def gen(): + yield 1 + yield 2 + yield 3 + yield 4 + yield 5 + + def run_test(drive_generator): + g = gen() + values = [] + threading_helper.run_concurrently(drive_generator, self.NUM_THREADS, args=(g, values,)) + self.assertEqual(sorted(values), [1, 2, 3, 4, 5]) + + def call_next(g, values): + while True: + try: + values.append(next(g)) + except ValueError: + continue + except StopIteration: + break + + with self.subTest(method='next'): + run_test(call_next) + + def call_send(g, values): + while True: + try: + values.append(g.send(None)) + except ValueError: + continue + except StopIteration: + break + + with self.subTest(method='send'): + run_test(call_send) + + def for_iter_gen(g, values): + while True: + try: + for value in g: + values.append(value) + else: + break + except ValueError: + continue + + with self.subTest(method='for'): + run_test(for_iter_gen) + + def test_concurrent_close(self): + def gen(): + for i in range(10): + yield i + time.sleep(0.001) + + def drive_generator(g): + while True: + try: + for value in g: + if value == 5: + g.close() + else: + return + except ValueError as e: + self.assertEqual(e.args[0], "generator already executing") + + g = gen() + threading_helper.run_concurrently(drive_generator, self.NUM_THREADS, args=(g,)) + + def test_concurrent_gi_yieldfrom(self): + def gen_yield_from(): + yield from itertools.count() + + g = gen_yield_from() + next(g) # Put in FRAME_SUSPENDED_YIELD_FROM state + + def read_yieldfrom(gen): + for _ in range(10000): + self.assertIsNotNone(gen.gi_yieldfrom) + + threading_helper.run_concurrently(read_yieldfrom, self.NUM_THREADS, args=(g,)) + + def test_gi_yieldfrom_close_race(self): + def gen_yield_from(): + yield from itertools.count() + + g = gen_yield_from() + next(g) + + done = threading.Event() + + def reader(): + while not done.is_set(): + g.gi_yieldfrom + + def closer(): + try: + g.close() + except ValueError: + pass + done.set() + + threading_helper.run_concurrently([reader, closer]) diff --git a/Lib/test/test_free_threading/test_grp.py b/Lib/test/test_free_threading/test_grp.py new file mode 100644 index 00000000000..1a47a975770 --- /dev/null +++ b/Lib/test/test_free_threading/test_grp.py @@ -0,0 +1,35 @@ +import unittest + +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently + +grp = import_helper.import_module("grp") + +from test import test_grp + + +NTHREADS = 10 + + +@threading_helper.requires_working_threading() +class TestGrp(unittest.TestCase): + def setUp(self): + self.test_grp = test_grp.GroupDatabaseTestCase() + + def test_racing_test_values(self): + # test_grp.test_values() calls grp.getgrall() and checks the entries + run_concurrently( + worker_func=self.test_grp.test_values, nthreads=NTHREADS + ) + + def test_racing_test_values_extended(self): + # test_grp.test_values_extended() calls grp.getgrall(), grp.getgrgid(), + # grp.getgrnam() and checks the entries + run_concurrently( + worker_func=self.test_grp.test_values_extended, + nthreads=NTHREADS, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_io.py b/Lib/test/test_free_threading/test_io.py new file mode 100644 index 00000000000..fad8339af2e --- /dev/null +++ b/Lib/test/test_free_threading/test_io.py @@ -0,0 +1,200 @@ +import codecs +import io +import _pyio as pyio +import threading +from unittest import TestCase +from test.support import threading_helper +from test.support.threading_helper import run_concurrently +from random import randint +from sys import getsizeof + +threading_helper.requires_working_threading(module=True) + + +class ThreadSafetyMixin: + # Test pretty much everything that can break under free-threading. + # Non-deterministic, but at least one of these things will fail if + # BytesIO object is not free-thread safe. + + def check(self, funcs, *args): + barrier = threading.Barrier(len(funcs)) + threads = [] + + for func in funcs: + thread = threading.Thread(target=func, args=(barrier, *args)) + + threads.append(thread) + + with threading_helper.start_threads(threads): + pass + + @threading_helper.requires_working_threading() + @threading_helper.reap_threads + def test_free_threading(self): + """Test for segfaults and aborts.""" + + def write(barrier, b, *ignore): + barrier.wait() + try: b.write(b'0' * randint(100, 1000)) + except ValueError: pass # ignore write fail to closed file + + def writelines(barrier, b, *ignore): + barrier.wait() + b.write(b'0\n' * randint(100, 1000)) + + def truncate(barrier, b, *ignore): + barrier.wait() + try: b.truncate(0) + except BufferError: pass # ignore exported buffer + + def read(barrier, b, *ignore): + barrier.wait() + b.read() + + def read1(barrier, b, *ignore): + barrier.wait() + b.read1() + + def readline(barrier, b, *ignore): + barrier.wait() + b.readline() + + def readlines(barrier, b, *ignore): + barrier.wait() + b.readlines() + + def readinto(barrier, b, into, *ignore): + barrier.wait() + b.readinto(into) + + def close(barrier, b, *ignore): + barrier.wait() + b.close() + + def getvalue(barrier, b, *ignore): + barrier.wait() + b.getvalue() + + def getbuffer(barrier, b, *ignore): + barrier.wait() + b.getbuffer() + + def iter(barrier, b, *ignore): + barrier.wait() + list(b) + + def getstate(barrier, b, *ignore): + barrier.wait() + b.__getstate__() + + def setstate(barrier, b, st, *ignore): + barrier.wait() + b.__setstate__(st) + + def sizeof(barrier, b, *ignore): + barrier.wait() + getsizeof(b) + + self.check([write] * 10, self.ioclass()) + self.check([writelines] * 10, self.ioclass()) + self.check([write] * 10 + [truncate] * 10, self.ioclass()) + self.check([truncate] + [read] * 10, self.ioclass(b'0\n'*204800)) + self.check([truncate] + [read1] * 10, self.ioclass(b'0\n'*204800)) + self.check([truncate] + [readline] * 10, self.ioclass(b'0\n'*20480)) + self.check([truncate] + [readlines] * 10, self.ioclass(b'0\n'*20480)) + self.check([truncate] + [readinto] * 10, self.ioclass(b'0\n'*204800), bytearray(b'0\n'*204800)) + self.check([close] + [write] * 10, self.ioclass()) + self.check([truncate] + [getvalue] * 10, self.ioclass(b'0\n'*204800)) + self.check([truncate] + [getbuffer] * 10, self.ioclass(b'0\n'*204800)) + self.check([truncate] + [iter] * 10, self.ioclass(b'0\n'*20480)) + self.check([truncate] + [getstate] * 10, self.ioclass(b'0\n'*204800)) + state = self.ioclass(b'123').__getstate__() + self.check([truncate] + [setstate] * 10, self.ioclass(b'0\n'*204800), state) + self.check([truncate] + [sizeof] * 10, self.ioclass(b'0\n'*204800)) + + # no tests for seek or tell because they don't break anything + +class CBytesIOTest(ThreadSafetyMixin, TestCase): + ioclass = io.BytesIO + + @threading_helper.requires_working_threading() + @threading_helper.reap_threads + def test_concurrent_whole_buffer_read_and_resize(self): + shared = self.ioclass(b"x" * 64) + writers = 2 + readers = 8 + loops = 2000 + barrier = threading.Barrier(writers + readers) + + def writer(): + barrier.wait() + for i in range(loops): + shared.seek(0) + shared.write(b"a" * (64 + (i & 63))) + + def reader(): + barrier.wait() + for _ in range(loops): + shared.seek(0) + shared.read() + shared.seek(0) + shared.getvalue() + + threads = [threading.Thread(target=writer) for _ in range(writers)] + threads += [threading.Thread(target=reader) for _ in range(readers)] + with threading_helper.start_threads(threads): + pass + +class PyBytesIOTest(ThreadSafetyMixin, TestCase): + ioclass = pyio.BytesIO + + +class IncrementalNewlineDecoderTest(TestCase): + def make_decoder(self): + utf8_decoder = codecs.getincrementaldecoder('utf-8')() + return io.IncrementalNewlineDecoder(utf8_decoder, translate=True) + + def test_concurrent_reset(self): + decoder = self.make_decoder() + + def worker(): + for _ in range(100): + decoder.reset() + + run_concurrently(worker_func=worker, nthreads=2) + + def test_concurrent_decode(self): + decoder = self.make_decoder() + + def worker(): + for _ in range(100): + decoder.decode(b"line\r\n", final=False) + + run_concurrently(worker_func=worker, nthreads=2) + + def test_concurrent_getstate_setstate(self): + decoder = self.make_decoder() + state = decoder.getstate() + + def getstate_worker(): + for _ in range(100): + decoder.getstate() + + def setstate_worker(): + for _ in range(100): + decoder.setstate(state) + + run_concurrently([getstate_worker] * 2 + [setstate_worker] * 2) + + def test_concurrent_decode_and_reset(self): + decoder = self.make_decoder() + + def decode_worker(): + for _ in range(100): + decoder.decode(b"line\r\n", final=False) + + def reset_worker(): + for _ in range(100): + decoder.reset() + + run_concurrently([decode_worker] * 2 + [reset_worker] * 2) diff --git a/Lib/test/test_free_threading/test_iteration.py b/Lib/test/test_free_threading/test_iteration.py new file mode 100644 index 00000000000..44d3e9ccfdd --- /dev/null +++ b/Lib/test/test_free_threading/test_iteration.py @@ -0,0 +1,127 @@ +import threading +import unittest +from test import support + +# The race conditions these tests were written for only happen every now and +# then, even with the current numbers. To find rare race conditions, bumping +# these up will help, but it makes the test runtime highly variable under +# free-threading. Overhead is much higher under ThreadSanitizer, but it's +# also much better at detecting certain races, so we don't need as many +# items/threads. +if support.check_sanitizer(thread=True): + NUMITEMS = 1000 + NUMTHREADS = 2 +else: + NUMITEMS = 5000 + NUMTHREADS = 5 +NUMMUTATORS = 2 + +class ContendedTupleIterationTest(unittest.TestCase): + def make_testdata(self, n): + return tuple(range(n)) + + def assert_iterator_results(self, results, expected): + # Most iterators are not atomic (yet?) so they can skip or duplicate + # items, but they should not invent new items (like the range + # iterator currently does). + extra_items = set(results) - set(expected) + self.assertEqual(set(), extra_items) + + def run_threads(self, func, *args, numthreads=NUMTHREADS): + threads = [] + for _ in range(numthreads): + t = threading.Thread(target=func, args=args) + t.start() + threads.append(t) + return threads + + def test_iteration(self): + """Test iteration over a shared container""" + seq = self.make_testdata(NUMITEMS) + results = [] + start = threading.Barrier(NUMTHREADS) + def worker(): + idx = 0 + start.wait() + for item in seq: + idx += 1 + results.append(idx) + threads = self.run_threads(worker) + for t in threads: + t.join() + # Each thread has its own iterator, so results should be entirely predictable. + self.assertEqual(results, [NUMITEMS] * NUMTHREADS) + + def test_shared_iterator(self): + """Test iteration over a shared iterator""" + seq = self.make_testdata(NUMITEMS) + it = iter(seq) + results = [] + start = threading.Barrier(NUMTHREADS) + def worker(): + items = [] + start.wait() + # We want a tight loop, so put items in the shared list at the end. + for item in it: + items.append(item) + results.extend(items) + threads = self.run_threads(worker) + for t in threads: + t.join() + self.assert_iterator_results(results, seq) + +class ContendedListIterationTest(ContendedTupleIterationTest): + def make_testdata(self, n): + return list(range(n)) + + def test_iteration_while_mutating(self): + """Test iteration over a shared mutating container.""" + seq = self.make_testdata(NUMITEMS) + results = [] + start = threading.Barrier(NUMTHREADS + NUMMUTATORS) + endmutate = threading.Event() + def mutator(): + orig = seq[:] + # Make changes big enough to cause resizing of the list, with + # items shifted around for good measure. + replacement = (orig * 3)[NUMITEMS//2:] + start.wait() + while not endmutate.is_set(): + seq.extend(replacement) + seq[:0] = orig + seq.__imul__(2) + seq.extend(seq) + seq[:] = orig + def worker(): + items = [] + start.wait() + # We want a tight loop, so put items in the shared list at the end. + for item in seq: + items.append(item) + results.extend(items) + mutators = () + try: + threads = self.run_threads(worker) + mutators = self.run_threads(mutator, numthreads=NUMMUTATORS) + for t in threads: + t.join() + finally: + endmutate.set() + for m in mutators: + m.join() + self.assert_iterator_results(results, list(seq)) + + +class ContendedRangeIterationTest(ContendedTupleIterationTest): + def make_testdata(self, n): + return range(n) + + def assert_iterator_results(self, results, expected): + # Range iterators that are shared between threads will (right now) + # sometimes produce items after the end of the range, sometimes + # _far_ after the end of the range. That should be fixed, but for + # now, let's just check they're integers that could have resulted + # from stepping beyond the range bounds. + extra_items = set(results) - set(expected) + for item in extra_items: + self.assertEqual((item - expected.start) % expected.step, 0) diff --git a/Lib/test/test_free_threading/test_itertools.py b/Lib/test/test_free_threading/test_itertools.py new file mode 100644 index 00000000000..7392bd739ac --- /dev/null +++ b/Lib/test/test_free_threading/test_itertools.py @@ -0,0 +1,146 @@ +import unittest +from itertools import ( + accumulate, + batched, + chain, + combinations_with_replacement, + cycle, + permutations, + tee, + zip_longest, +) +from test.support import threading_helper + + +threading_helper.requires_working_threading(module=True) + + +def work_iterator(it): + while True: + try: + next(it) + except StopIteration: + break + + +class ItertoolsThreading(unittest.TestCase): + @threading_helper.reap_threads + def test_accumulate(self): + number_of_iterations = 10 + for _ in range(number_of_iterations): + it = accumulate(tuple(range(40))) + threading_helper.run_concurrently( + work_iterator, nthreads=10, args=[it] + ) + + @threading_helper.reap_threads + def test_batched(self): + number_of_iterations = 10 + for _ in range(number_of_iterations): + it = batched(tuple(range(1000)), 2) + threading_helper.run_concurrently( + work_iterator, nthreads=10, args=[it] + ) + + @threading_helper.reap_threads + def test_cycle(self): + def work(it): + for _ in range(400): + next(it) + + number_of_iterations = 6 + for _ in range(number_of_iterations): + it = cycle((1, 2, 3, 4)) + threading_helper.run_concurrently(work, nthreads=6, args=[it]) + + @threading_helper.reap_threads + def test_chain(self): + number_of_iterations = 10 + for _ in range(number_of_iterations): + it = chain(*[(1,)] * 200) + threading_helper.run_concurrently( + work_iterator, nthreads=6, args=[it] + ) + + @threading_helper.reap_threads + def test_combinations_with_replacement(self): + number_of_iterations = 6 + for _ in range(number_of_iterations): + it = combinations_with_replacement(tuple(range(2)), 2) + threading_helper.run_concurrently( + work_iterator, nthreads=6, args=[it] + ) + + @threading_helper.reap_threads + def test_permutations(self): + number_of_iterations = 6 + for _ in range(number_of_iterations): + it = permutations(tuple(range(4)), 2) + threading_helper.run_concurrently( + work_iterator, nthreads=6, args=[it] + ) + + @threading_helper.reap_threads + def test_zip_longest(self): + number_of_iterations = 10 + for _ in range(number_of_iterations): + it = zip_longest(list(range(4)), list(range(8)), fillvalue=0) + threading_helper.run_concurrently( + work_iterator, nthreads=10, args=[it] + ) + + +class TestTeeConcurrent(unittest.TestCase): + # itertools.tee branches share a linked list of internal data cells. + # Concurrent iteration must not corrupt that shared state or crash the + # free-threaded build. A crash shows up as the interpreter dying (not as a + # caught exception); tee is documented as not thread-safe, so a + # ``RuntimeError`` from the re-entrancy guard is an allowed outcome and is + # tolerated here. + + def test_same_branch(self): + # Many threads consume the same tee branch. + errors = [] + + def consume(it): + try: + for _ in it: + pass + except RuntimeError: + pass + except Exception as e: + errors.append(e) + + for _ in range(100): + a, _ = tee(iter(range(2000)), 2) + threading_helper.run_concurrently(consume, nthreads=8, args=(a,)) + + self.assertEqual(errors, [], msg=f"unexpected errors: {errors}") + + def test_sibling_branches(self): + # Each thread consumes a different sibling branch of the same tee. + errors = [] + + def make_worker(it): + def consume(): + try: + for _ in it: + pass + except RuntimeError: + pass + except Exception as e: + errors.append(e) + + return consume + + for _ in range(100): + branches = tee(iter(range(4000)), 8) + threading_helper.run_concurrently( + [make_worker(it) for it in branches] + ) + + self.assertEqual(errors, [], msg=f"unexpected errors: {errors}") + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_itertools_combinatoric.py b/Lib/test/test_free_threading/test_itertools_combinatoric.py new file mode 100644 index 00000000000..5b3b88deedd --- /dev/null +++ b/Lib/test/test_free_threading/test_itertools_combinatoric.py @@ -0,0 +1,51 @@ +import unittest +from threading import Thread, Barrier +from itertools import combinations, product +from test.support import threading_helper + + +threading_helper.requires_working_threading(module=True) + +def test_concurrent_iteration(iterator, number_of_threads): + barrier = Barrier(number_of_threads) + def iterator_worker(it): + barrier.wait() + while True: + try: + _ = next(it) + except StopIteration: + return + + worker_threads = [] + for ii in range(number_of_threads): + worker_threads.append( + Thread(target=iterator_worker, args=[iterator])) + + with threading_helper.start_threads(worker_threads): + pass + + barrier.reset() + +class ItertoolsThreading(unittest.TestCase): + + @threading_helper.reap_threads + def test_combinations(self): + number_of_threads = 10 + number_of_iterations = 24 + + for it in range(number_of_iterations): + iterator = combinations((1, 2, 3, 4, 5), 2) + test_concurrent_iteration(iterator, number_of_threads) + + @threading_helper.reap_threads + def test_product(self): + number_of_threads = 10 + number_of_iterations = 24 + + for it in range(number_of_iterations): + iterator = product((1, 2, 3, 4, 5), (10, 20, 30)) + test_concurrent_iteration(iterator, number_of_threads) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_json.py b/Lib/test/test_free_threading/test_json.py new file mode 100644 index 00000000000..7e3adcf0e81 --- /dev/null +++ b/Lib/test/test_free_threading/test_json.py @@ -0,0 +1,81 @@ +from threading import Barrier, Thread +from test.test_json import CTest +from test.support import threading_helper + + +def encode_json_helper( + json, worker, data, number_of_threads=12, number_of_json_encodings=100 +): + worker_threads = [] + barrier = Barrier(number_of_threads) + for index in range(number_of_threads): + worker_threads.append( + Thread(target=worker, args=[barrier, data, index]) + ) + for t in worker_threads: + t.start() + for ii in range(number_of_json_encodings): + json.dumps(data) + data.clear() + for t in worker_threads: + t.join() + + +class MyMapping(dict): + def __init__(self): + self.mapping = [] + + def items(self): + return self.mapping + + +@threading_helper.requires_working_threading() +class TestJsonEncoding(CTest): + # Test encoding json with concurrent threads modifying the data cannot + # corrupt the interpreter + + @threading_helper.reap_threads + def test_json_mutating_list(self): + def worker(barrier, data, index): + barrier.wait() + while data: + for d in data: + if len(d) > 5: + d.clear() + else: + d.append(index) + + data = [[], []] + encode_json_helper(self.json, worker, data) + + @threading_helper.reap_threads + def test_json_mutating_exact_dict(self): + def worker(barrier, data, index): + barrier.wait() + while data: + for d in data: + if len(d) > 5: + try: + key = list(d)[0] + d.pop(key) + except (KeyError, IndexError): + pass + else: + d[index] = index + + data = [{}, {}] + encode_json_helper(self.json, worker, data) + + @threading_helper.reap_threads + def test_json_mutating_mapping(self): + def worker(barrier, data, index): + barrier.wait() + while data: + for d in data: + if len(d.mapping) > 3: + d.mapping.clear() + else: + d.mapping.append((index, index)) + + data = [MyMapping(), MyMapping()] + encode_json_helper(self.json, worker, data) diff --git a/Lib/test/test_free_threading/test_list.py b/Lib/test/test_free_threading/test_list.py new file mode 100644 index 00000000000..0ede4df103f --- /dev/null +++ b/Lib/test/test_free_threading/test_list.py @@ -0,0 +1,175 @@ +import unittest + +from threading import Thread, Barrier +from unittest import TestCase + +from test.support import threading_helper + + +NTHREAD = 10 +OBJECT_COUNT = 5_000 + + +class C: + def __init__(self, v): + self.v = v + + +@threading_helper.requires_working_threading() +class TestList(TestCase): + def test_racing_iter_append(self): + l = [] + + barrier = Barrier(NTHREAD + 1) + def writer_func(l): + barrier.wait() + for i in range(OBJECT_COUNT): + l.append(C(i + OBJECT_COUNT)) + + def reader_func(l): + barrier.wait() + while True: + count = len(l) + for i, x in enumerate(l): + self.assertEqual(x.v, i + OBJECT_COUNT) + if count == OBJECT_COUNT: + break + + writer = Thread(target=writer_func, args=(l,)) + readers = [] + for x in range(NTHREAD): + reader = Thread(target=reader_func, args=(l,)) + readers.append(reader) + reader.start() + + writer.start() + writer.join() + for reader in readers: + reader.join() + + def test_racing_iter_extend(self): + l = [] + + barrier = Barrier(NTHREAD + 1) + def writer_func(): + barrier.wait() + for i in range(OBJECT_COUNT): + l.extend([C(i + OBJECT_COUNT)]) + + def reader_func(): + barrier.wait() + while True: + count = len(l) + for i, x in enumerate(l): + self.assertEqual(x.v, i + OBJECT_COUNT) + if count == OBJECT_COUNT: + break + + writer = Thread(target=writer_func) + readers = [] + for x in range(NTHREAD): + reader = Thread(target=reader_func) + readers.append(reader) + reader.start() + + writer.start() + writer.join() + for reader in readers: + reader.join() + + def test_store_list_int(self): + def copy_back_and_forth(b, l): + b.wait() + for _ in range(100): + l[0] = l[1] + l[1] = l[0] + + l = [0, 1] + barrier = Barrier(NTHREAD) + threads = [Thread(target=copy_back_and_forth, args=(barrier, l)) + for _ in range(NTHREAD)] + with threading_helper.start_threads(threads): + pass + + def test_reverse(self): + def reverse_list(b, l): + b.wait() + for _ in range(100): + l.reverse() + + def reader_list(b, l): + b.wait() + for _ in range(100): + for i in range(10): + self.assertTrue(0 <= l[i] < 10) + + l = list(range(10)) + barrier = Barrier(2) + threads = [Thread(target=reverse_list, args=(barrier, l)), + Thread(target=reader_list, args=(barrier, l))] + with threading_helper.start_threads(threads): + pass + + def test_slice_assignment1(self): + def assign_slice(b, l): + b.wait() + for _ in range(100): + l[2:5] = [7, 8, 9] + + def reader_list(b, l): + b.wait() + for _ in range(100): + self.assertIn(l[2], (2, 7)) + self.assertIn(l[3], (3, 8)) + self.assertIn(l[4], (4, 9)) + + l = list(range(10)) + barrier = Barrier(2) + threads = [Thread(target=assign_slice, args=(barrier, l)), + Thread(target=reader_list, args=(barrier, l))] + with threading_helper.start_threads(threads): + pass + + def test_slice_assignment2(self): + def assign_slice(b, l): + b.wait() + for _ in range(100): + l[::2] = [10, 11, 12, 13, 14] + + def reader_list(b, l): + b.wait() + for _ in range(100): + for i in range(0, 10, 2): + self.assertIn(l[i], (i, 10 + i // 2)) + + l = list(range(10)) + barrier = Barrier(2) + threads = [Thread(target=assign_slice, args=(barrier, l)), + Thread(target=reader_list, args=(barrier, l))] + with threading_helper.start_threads(threads): + pass + + # gh-145036: race condition with list.__sizeof__() + def test_list_sizeof_free_threaded_build(self): + L = [] + + def mutate_function(): + for _ in range(100): + L.append(1) + L.pop() + + def size_function(): + for _ in range(100): + L.__sizeof__() + + threads = [] + for _ in range(4): + threads.append(Thread(target=mutate_function)) + threads.append(Thread(target=size_function)) + + with threading_helper.start_threads(threads): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_lzma.py b/Lib/test/test_free_threading/test_lzma.py new file mode 100644 index 00000000000..3beacf38576 --- /dev/null +++ b/Lib/test/test_free_threading/test_lzma.py @@ -0,0 +1,69 @@ +import unittest + +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently + +lzma = import_helper.import_module("lzma") +from lzma import LZMACompressor, LZMADecompressor + +from test.test_lzma import INPUT + + +NTHREADS = 10 + + +@threading_helper.requires_working_threading() +class TestLZMA(unittest.TestCase): + def test_compressor(self): + lzc = LZMACompressor() + + # First compress() outputs LZMA header + header = lzc.compress(INPUT) + self.assertGreater(len(header), 0) + + def worker(): + # it should return empty bytes as it buffers data internally + data = lzc.compress(INPUT) + self.assertEqual(data, b"") + + run_concurrently(worker_func=worker, nthreads=NTHREADS - 1) + full_compressed = header + lzc.flush() + decompressed = lzma.decompress(full_compressed) + # The decompressed data should be INPUT repeated NTHREADS times + self.assertEqual(decompressed, INPUT * NTHREADS) + + def test_decompressor(self): + chunk_size = 128 + chunks = [bytes([ord("a") + i]) * chunk_size for i in range(NTHREADS)] + input_data = b"".join(chunks) + compressed = lzma.compress(input_data) + + lzd = LZMADecompressor() + output = [] + + def worker(): + data = lzd.decompress(compressed, chunk_size) + self.assertEqual(len(data), chunk_size) + output.append(data) + # Read attributes concurrently with other threads decompressing + self.assertEqual(lzd.check, lzma.CHECK_CRC64) + self.assertIsInstance(lzd.eof, bool) + self.assertIsInstance(lzd.needs_input, bool) + self.assertIsInstance(lzd.unused_data, bytes) + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + self.assertEqual(len(output), NTHREADS) + # Verify the expected chunks (order doesn't matter due to append race) + self.assertSetEqual(set(output), set(chunks)) + self.assertEqual(lzd.check, lzma.CHECK_CRC64) + self.assertTrue(lzd.eof) + self.assertFalse(lzd.needs_input) + # Each thread added full compressed data to the buffer, but only 1 copy + # is consumed to produce the output. The rest remains as unused_data. + self.assertEqual( + len(lzd.unused_data), len(compressed) * (NTHREADS - 1) + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_methodcaller.py b/Lib/test/test_free_threading/test_methodcaller.py new file mode 100644 index 00000000000..0a03e38cf2c --- /dev/null +++ b/Lib/test/test_free_threading/test_methodcaller.py @@ -0,0 +1,32 @@ +import unittest +from threading import Thread +from operator import methodcaller + + +class TestMethodcaller(unittest.TestCase): + def test_methodcaller_threading(self): + number_of_threads = 10 + size = 4_000 + + mc = methodcaller("append", 2) + + def work(mc, l, ii): + for _ in range(ii): + mc(l) + + worker_threads = [] + lists = [] + for ii in range(number_of_threads): + l = [] + lists.append(l) + worker_threads.append(Thread(target=work, args=[mc, l, size])) + for t in worker_threads: + t.start() + for t in worker_threads: + t.join() + for l in lists: + assert len(l) == size + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_mmap.py b/Lib/test/test_free_threading/test_mmap.py new file mode 100644 index 00000000000..ece13d33f3b --- /dev/null +++ b/Lib/test/test_free_threading/test_mmap.py @@ -0,0 +1,315 @@ +import unittest + +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently + +import os +import string +import tempfile +import threading + +from collections import Counter + +mmap = import_helper.import_module("mmap") + +NTHREADS = 10 +ANONYMOUS_MEM = -1 + + +@threading_helper.requires_working_threading() +class MmapTests(unittest.TestCase): + def test_read_and_read_byte(self): + ascii_uppercase = string.ascii_uppercase.encode() + # Choose a total mmap size that evenly divides across threads and the + # read pattern (3 bytes per loop). + mmap_size = 3 * NTHREADS * len(ascii_uppercase) + num_bytes_to_read_per_thread = mmap_size // NTHREADS + bytes_read_from_mmap = [] + + def read(mm_obj): + nread = 0 + while nread < num_bytes_to_read_per_thread: + b = mm_obj.read_byte() + bytes_read_from_mmap.append(b) + b = mm_obj.read(2) + bytes_read_from_mmap.extend(b) + nread += 3 + + with mmap.mmap(ANONYMOUS_MEM, mmap_size) as mm_obj: + for i in range(mmap_size // len(ascii_uppercase)): + mm_obj.write(ascii_uppercase) + + mm_obj.seek(0) + run_concurrently( + worker_func=read, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + self.assertEqual(len(bytes_read_from_mmap), mmap_size) + # Count each letter/byte to verify read correctness + counter = Counter(bytes_read_from_mmap) + self.assertEqual(len(counter), len(ascii_uppercase)) + # Each letter/byte should be read (3 * NTHREADS) times + for letter in ascii_uppercase: + self.assertEqual(counter[letter], 3 * NTHREADS) + + def test_readline(self): + num_lines = 1000 + lines_read_from_mmap = [] + expected_lines = [] + + def readline(mm_obj): + for i in range(num_lines // NTHREADS): + line = mm_obj.readline() + lines_read_from_mmap.append(line) + + # Allocate mmap enough for num_lines (max line 5 bytes including NL) + with mmap.mmap(ANONYMOUS_MEM, num_lines * 5) as mm_obj: + for i in range(num_lines): + line = b"%d\n" % i + mm_obj.write(line) + expected_lines.append(line) + + mm_obj.seek(0) + run_concurrently( + worker_func=readline, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + self.assertEqual(len(lines_read_from_mmap), num_lines) + # Every line should be read once by threads; order is non-deterministic + # Sort numerically by integer value + lines_read_from_mmap.sort(key=lambda x: int(x)) + self.assertEqual(lines_read_from_mmap, expected_lines) + + def test_write_and_write_byte(self): + thread_letters = list(string.ascii_uppercase) + self.assertLessEqual(NTHREADS, len(thread_letters)) + per_thread_write_loop = 100 + + def write(mm_obj): + # Each thread picks a unique letter to write + thread_letter = thread_letters.pop(0) + thread_bytes = (thread_letter * 2).encode() + for _ in range(per_thread_write_loop): + mm_obj.write_byte(thread_bytes[0]) + mm_obj.write(thread_bytes) + + with mmap.mmap( + ANONYMOUS_MEM, per_thread_write_loop * 3 * NTHREADS + ) as mm_obj: + run_concurrently( + worker_func=write, + args=(mm_obj,), + nthreads=NTHREADS, + ) + mm_obj.seek(0) + data = mm_obj.read() + self.assertEqual(len(data), NTHREADS * per_thread_write_loop * 3) + counter = Counter(data) + self.assertEqual(len(counter), NTHREADS) + # Each thread letter should be written `per_thread_write_loop` * 3 + for letter in counter: + self.assertEqual(counter[letter], per_thread_write_loop * 3) + + def test_move(self): + ascii_uppercase = string.ascii_uppercase.encode() + num_letters = len(ascii_uppercase) + + def move(mm_obj): + for i in range(num_letters): + # Move 1 byte from the first half to the second half + mm_obj.move(0 + i, num_letters + i, 1) + + with mmap.mmap(ANONYMOUS_MEM, 2 * num_letters) as mm_obj: + mm_obj.write(ascii_uppercase) + run_concurrently( + worker_func=move, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + def test_seek_and_tell(self): + seek_per_thread = 10 + + def seek(mm_obj): + self.assertTrue(mm_obj.seekable()) + for _ in range(seek_per_thread): + before_seek = mm_obj.tell() + mm_obj.seek(1, os.SEEK_CUR) + self.assertLess(before_seek, mm_obj.tell()) + + with mmap.mmap(ANONYMOUS_MEM, 1024) as mm_obj: + run_concurrently( + worker_func=seek, + args=(mm_obj,), + nthreads=NTHREADS, + ) + # Each thread seeks from current position, the end position should + # be the sum of all seeks from all threads. + self.assertEqual(mm_obj.tell(), NTHREADS * seek_per_thread) + + def test_slice_update_and_slice_read(self): + thread_letters = list(string.ascii_uppercase) + self.assertLessEqual(NTHREADS, len(thread_letters)) + + def slice_update_and_slice_read(mm_obj): + # Each thread picks a unique letter to write + thread_letter = thread_letters.pop(0) + thread_bytes = (thread_letter * 1024).encode() + for _ in range(100): + mm_obj[:] = thread_bytes + read_bytes = mm_obj[:] + # Read bytes should be all the same letter, showing no + # interleaving + self.assertTrue(all_same(read_bytes)) + + with mmap.mmap(ANONYMOUS_MEM, 1024) as mm_obj: + run_concurrently( + worker_func=slice_update_and_slice_read, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + def test_item_update_and_item_read(self): + thread_indexes = [i for i in range(NTHREADS)] + + def item_update_and_item_read(mm_obj): + # Each thread picks a unique index to write + thread_index = thread_indexes.pop() + for i in range(100): + mm_obj[thread_index] = i + self.assertEqual(mm_obj[thread_index], i) + + # Read values set by other threads, all values + # should be less than '100' + for val in mm_obj: + self.assertLess(int.from_bytes(val), 100) + + with mmap.mmap(ANONYMOUS_MEM, NTHREADS + 1) as mm_obj: + run_concurrently( + worker_func=item_update_and_item_read, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + @unittest.skipUnless(os.name == "posix", "requires Posix") + @unittest.skipUnless(hasattr(mmap.mmap, "resize"), "requires mmap.resize") + def test_resize_and_size(self): + thread_indexes = [i for i in range(NTHREADS)] + + def resize_and_item_update(mm_obj): + # Each thread picks a unique index to write + thread_index = thread_indexes.pop() + mm_obj.resize(2048) + self.assertEqual(mm_obj.size(), 2048) + for i in range(100): + mm_obj[thread_index] = i + self.assertEqual(mm_obj[thread_index], i) + + with mmap.mmap(ANONYMOUS_MEM, 1024, flags=mmap.MAP_PRIVATE) as mm_obj: + run_concurrently( + worker_func=resize_and_item_update, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + def test_close_and_closed(self): + def close_mmap(mm_obj): + mm_obj.close() + self.assertTrue(mm_obj.closed) + + with mmap.mmap(ANONYMOUS_MEM, 1) as mm_obj: + run_concurrently( + worker_func=close_mmap, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + def test_find_and_rfind(self): + per_thread_loop = 10 + + def find_and_rfind(mm_obj): + pattern = b'Thread-Ident:"%d"' % threading.get_ident() + mm_obj.write(pattern) + for _ in range(per_thread_loop): + found_at = mm_obj.find(pattern, 0) + self.assertNotEqual(found_at, -1) + # Should not find it after the `found_at` + self.assertEqual(mm_obj.find(pattern, found_at + 1), -1) + found_at_rev = mm_obj.rfind(pattern, 0) + self.assertEqual(found_at, found_at_rev) + # Should not find it after the `found_at` + self.assertEqual(mm_obj.rfind(pattern, found_at + 1), -1) + + with mmap.mmap(ANONYMOUS_MEM, 1024) as mm_obj: + run_concurrently( + worker_func=find_and_rfind, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + @unittest.skipUnless(os.name == "posix", "requires Posix") + @unittest.skipUnless(hasattr(mmap.mmap, "resize"), "requires mmap.resize") + def test_flush(self): + mmap_filename = "test_mmap_file" + resize_to = 1024 + + def resize_and_flush(mm_obj): + mm_obj.resize(resize_to) + mm_obj.flush() + + with tempfile.TemporaryDirectory() as tmpdirname: + file_path = f"{tmpdirname}/{mmap_filename}" + with open(file_path, "wb+") as file: + file.write(b"CPython") + file.flush() + with mmap.mmap(file.fileno(), 1) as mm_obj: + run_concurrently( + worker_func=resize_and_flush, + args=(mm_obj,), + nthreads=NTHREADS, + ) + + self.assertEqual(os.path.getsize(file_path), resize_to) + + def test_mmap_export_as_memoryview(self): + """ + Each thread creates a memoryview and updates the internal state of the + mmap object. + """ + buffer_size = 42 + + def create_memoryview_from_mmap(mm_obj): + memoryviews = [] + for _ in range(100): + mv = memoryview(mm_obj) + memoryviews.append(mv) + self.assertEqual(len(mv), buffer_size) + self.assertEqual(mv[:7], b"CPython") + + # Cannot close the mmap while it is exported as buffers + with self.assertRaisesRegex( + BufferError, "cannot close exported pointers exist" + ): + mm_obj.close() + + with mmap.mmap(ANONYMOUS_MEM, 42) as mm_obj: + mm_obj.write(b"CPython") + run_concurrently( + worker_func=create_memoryview_from_mmap, + args=(mm_obj,), + nthreads=NTHREADS, + ) + # Implicit mm_obj.close() verifies all exports (memoryviews) are + # properly freed. + + +def all_same(lst): + return all(item == lst[0] for item in lst) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_pickle.py b/Lib/test/test_free_threading/test_pickle.py new file mode 100644 index 00000000000..45ea1bf5f26 --- /dev/null +++ b/Lib/test/test_free_threading/test_pickle.py @@ -0,0 +1,78 @@ +import pickle +import threading +import unittest + +from test.support import threading_helper + + +@threading_helper.requires_working_threading() +class TestPickleFreeThreading(unittest.TestCase): + + def test_pickle_dumps_with_concurrent_dict_mutation(self): + # gh-146452: Pickling a dict while another thread mutates it + # used to segfault. batch_dict_exact() iterated dict items via + # PyDict_Next() which returns borrowed references, and a + # concurrent pop/replace could free the value before Py_INCREF + # got to it. + shared = {str(i): list(range(20)) for i in range(50)} + + def dumper(): + for _ in range(1000): + try: + pickle.dumps(shared) + except RuntimeError: + # "dictionary changed size during iteration" is expected + pass + + def mutator(): + for j in range(1000): + key = str(j % 50) + shared[key] = list(range(j % 20)) + if j % 10 == 0: + shared.pop(key, None) + shared[key] = [j] + + threads = [] + for _ in range(10): + threads.append(threading.Thread(target=dumper)) + threads.append(threading.Thread(target=mutator)) + + with threading_helper.start_threads(threads): + pass + + def test_pickle_dumps_with_concurrent_list_mutations(self): + # gh-149816: Pickling a list while another thread mutates it + # used to be a UAF in free-threaded mode. batch_list_exact() + # used PyList_GET_ITEM (borrowed) followed by Py_INCREF, and a + # concurrent replace/pop could free the item between those two + # operations. + shared = [list(range(20)) for _ in range(50)] + + def dumper(): + for _ in range(1000): + try: + pickle.dumps(shared) + except (RuntimeError, IndexError): + pass + + def mutator(): + for i in range(1000): + idx = i % 50 + shared[idx] = list(range(i % 20)) + if i % 10 == 0: + try: + shared.pop() + except IndexError: + pass + shared.append([i]) + + threads = [] + for _ in range(10): + threads.append(threading.Thread(target=dumper)) + threads.append(threading.Thread(target=mutator)) + + with threading_helper.start_threads(threads): + pass + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_re.py b/Lib/test/test_free_threading/test_re.py new file mode 100644 index 00000000000..56f25045d1b --- /dev/null +++ b/Lib/test/test_free_threading/test_re.py @@ -0,0 +1,62 @@ +import re +import unittest + +from test.support import threading_helper +from test.support.threading_helper import run_concurrently + + +NTHREADS = 10 + + +@threading_helper.requires_working_threading() +class TestRe(unittest.TestCase): + def test_pattern_sub(self): + """Pattern substitution should work across threads""" + pattern = re.compile(r"\w+@\w+\.\w+") + text = "e-mail: test@python.org or user@pycon.org. " * 5 + results = [] + + def worker(): + substituted = pattern.sub("(redacted)", text) + results.append(substituted.count("(redacted)")) + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + self.assertEqual(results, [2 * 5] * NTHREADS) + + def test_pattern_search(self): + """Pattern search should work across threads.""" + emails = ["alice@python.org", "bob@pycon.org"] * 10 + pattern = re.compile(r"\w+@\w+\.\w+") + results = [] + + def worker(): + matches = [pattern.search(e).group() for e in emails] + results.append(len(matches)) + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + self.assertEqual(results, [2 * 10] * NTHREADS) + + def test_scanner_concurrent_access(self): + """Shared scanner should reject concurrent access.""" + pattern = re.compile(r"\w+") + scanner = pattern.scanner("word " * 10) + + def worker(): + for _ in range(100): + try: + scanner.search() + except ValueError as e: + if "already executing" in str(e): + pass + else: + raise + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + # This test has no assertions. Its purpose is to catch crashes and + # enable thread sanitizer to detect race conditions. While "already + # executing" errors are very likely, they're not guaranteed due to + # non-deterministic thread scheduling, so we can't assert errors > 0. + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_resource.py b/Lib/test/test_free_threading/test_resource.py new file mode 100644 index 00000000000..ecd0e535c44 --- /dev/null +++ b/Lib/test/test_free_threading/test_resource.py @@ -0,0 +1,41 @@ +import unittest +from test.support import import_helper, threading_helper + +resource = import_helper.import_module("resource") + + +NTHREADS = 10 +LOOP_PER_THREAD = 1000 + + +@threading_helper.requires_working_threading() +class ResourceTest(unittest.TestCase): + @unittest.skipUnless(hasattr(resource, "getrusage"), "needs getrusage") + @unittest.skipUnless( + hasattr(resource, "RUSAGE_THREAD"), "needs RUSAGE_THREAD" + ) + def test_getrusage(self): + ru_utime_lst = [] + + def dummy_work(ru_utime_lst): + for _ in range(LOOP_PER_THREAD): + pass + + usage_process = resource.getrusage(resource.RUSAGE_SELF) + usage_thread = resource.getrusage(resource.RUSAGE_THREAD) + # Process user time should be greater than thread user time + self.assertGreater(usage_process.ru_utime, usage_thread.ru_utime) + ru_utime_lst.append(usage_thread.ru_utime) + + threading_helper.run_concurrently( + worker_func=dummy_work, args=(ru_utime_lst,), nthreads=NTHREADS + ) + + usage_process = resource.getrusage(resource.RUSAGE_SELF) + self.assertEqual(len(ru_utime_lst), NTHREADS) + # Process user time should be greater than sum of all thread user times + self.assertGreater(usage_process.ru_utime, sum(ru_utime_lst)) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_reversed.py b/Lib/test/test_free_threading/test_reversed.py new file mode 100644 index 00000000000..dd6016489c8 --- /dev/null +++ b/Lib/test/test_free_threading/test_reversed.py @@ -0,0 +1,39 @@ +import unittest +from threading import Barrier, Thread +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) + +class TestReversed(unittest.TestCase): + + @threading_helper.reap_threads + def test_reversed(self): + # Iterating over the iterator with multiple threads should not + # emit TSAN warnings + number_of_iterations = 10 + number_of_threads = 10 + size = 1_000 + + barrier = Barrier(number_of_threads) + def work(r): + barrier.wait() + while True: + try: + l = r.__length_hint__() + next(r) + except StopIteration: + break + assert 0 <= l <= size + x = tuple(range(size)) + + for _ in range(number_of_iterations): + r = reversed(x) + worker_threads = [] + for _ in range(number_of_threads): + worker_threads.append(Thread(target=work, args=[r])) + with threading_helper.start_threads(worker_threads): + pass + barrier.reset() + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_set.py b/Lib/test/test_free_threading/test_set.py new file mode 100644 index 00000000000..9dd3d68d5da --- /dev/null +++ b/Lib/test/test_free_threading/test_set.py @@ -0,0 +1,163 @@ +import unittest +from threading import Thread, Barrier, Event +from test.support import threading_helper + + +class TestSetRepr(unittest.TestCase): + def test_repr_clear(self): + """Test repr() of a set while another thread is calling clear()""" + NUM_ITERS = 10 + NUM_REPR_THREADS = 10 + barrier = Barrier(NUM_REPR_THREADS + 1, timeout=2) + s = {1, 2, 3, 4, 5, 6, 7, 8} + + def clear_set(): + barrier.wait() + s.clear() + + def repr_set(): + barrier.wait() + set_reprs.append(repr(s)) + + for _ in range(NUM_ITERS): + set_reprs = [] + threads = [Thread(target=clear_set)] + for _ in range(NUM_REPR_THREADS): + threads.append(Thread(target=repr_set)) + for t in threads: + t.start() + for t in threads: + t.join() + + for set_repr in set_reprs: + self.assertIn(set_repr, ("set()", "{1, 2, 3, 4, 5, 6, 7, 8}")) + + +class RaceTestBase: + def test_contains_mutate(self): + """Test set contains operation combined with mutation.""" + barrier = Barrier(2, timeout=2) + s = set() + done = Event() + + NUM_LOOPS = 1000 + + def read_set(): + barrier.wait() + while not done.is_set(): + for i in range(self.SET_SIZE): + item = i >> 1 + result = item in s + + def mutate_set(): + barrier.wait() + for i in range(NUM_LOOPS): + s.clear() + for j in range(self.SET_SIZE): + s.add(j) + for j in range(self.SET_SIZE): + s.discard(j) + # executes the set_swap_bodies() function + s.__iand__(set(k for k in range(10, 20))) + done.set() + + threads = [Thread(target=read_set), Thread(target=mutate_set)] + for t in threads: + t.start() + for t in threads: + t.join() + + def test_contains_frozenset(self): + barrier = Barrier(3, timeout=2) + done = Event() + + NUM_LOOPS = 1_000 + + # This mutates the key used for contains test, not the container + # itself. This works because frozenset allows the key to be a set(). + s = set() + + def mutate_set(): + barrier.wait() + while not done.is_set(): + s.add(0) + s.add(1) + s.clear() + + def read_set(): + barrier.wait() + container = frozenset([frozenset([0])]) + self.assertTrue(set([0]) in container) + for _ in range(NUM_LOOPS): + # Will return True when {0} is the key and False otherwise + result = s in container + done.set() + + threads = [ + Thread(target=read_set), + Thread(target=read_set), + Thread(target=mutate_set), + ] + for t in threads: + t.start() + for t in threads: + t.join() + + def test_contains_hash_mutate(self): + """Test set contains operation with mutating hash method.""" + barrier = Barrier(2, timeout=2) + + NUM_LOOPS = 1_000 + SET_SIZE = self.SET_SIZE + + s = set(range(SET_SIZE)) + + class Key: + def __init__(self): + self.count = 0 + self.value = 0 + + def __hash__(self): + self.count += 1 + # This intends to trigger the SET_LOOKKEY_CHANGED case + # of set_lookkey_threadsafe() since calling clear() + # will cause the 'table' pointer to change. + if self.count % 2 == 0: + s.clear() + else: + s.update(range(SET_SIZE)) + return hash(self.value) + + def __eq__(self, other): + return self.value == other + + key = Key() + self.assertTrue(key in s) + self.assertFalse(key in s) + self.assertTrue(key in s) + self.assertFalse(key in s) + + def read_set(): + barrier.wait() + for i in range(NUM_LOOPS): + result = key in s + + threads = [Thread(target=read_set), Thread(target=read_set)] + for t in threads: + t.start() + for t in threads: + t.join() + + +@threading_helper.requires_working_threading() +class SmallSetTest(RaceTestBase, unittest.TestCase): + SET_SIZE = 6 # smaller than PySet_MINSIZE + + +@threading_helper.requires_working_threading() +class LargeSetTest(RaceTestBase, unittest.TestCase): + SET_SIZE = 20 # larger than PySet_MINSIZE + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_sqlite3.py b/Lib/test/test_free_threading/test_sqlite3.py new file mode 100644 index 00000000000..456771726f7 --- /dev/null +++ b/Lib/test/test_free_threading/test_sqlite3.py @@ -0,0 +1,54 @@ +import unittest + +from test import support +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently + + +sqlite3 = import_helper.import_module("sqlite3") + + +NAME = "FREE_THREADING_RACE" +NCOLUMNS = 64 +NITER = 3000 +QUERY = "select " + ", ".join( + f"'value' as 'c{i} [{NAME}]'" for i in range(NCOLUMNS) +) + + +@threading_helper.requires_working_threading() +class TestSQLite3(unittest.TestCase): + def test_concurrent_converter_replacement(self): + # gh-155781: Converter lookups must retain a strong reference while + # another thread updates the public converter registry. + class Converter: + __slots__ = ("value",) + + def __init__(self, value): + self.value = value + + def __call__(self, value): + return self.value + + def reader(): + con = sqlite3.connect(":memory:", + detect_types=sqlite3.PARSE_COLNAMES) + try: + for _ in range(NITER): + row = con.execute(QUERY).fetchone() + self.assertEqual(len(row), NCOLUMNS) + finally: + con.close() + + def mutator(): + for i in range(NITER * NCOLUMNS): + sqlite3.register_converter(NAME, Converter(i)) + if i % 3 == 0: + sqlite3.converters.pop(NAME, None) + + with support.swap_item(sqlite3.converters, NAME, Converter(0)): + run_concurrently([reader] * 8 + [mutator] * 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_str.py b/Lib/test/test_free_threading/test_str.py new file mode 100644 index 00000000000..11e04009956 --- /dev/null +++ b/Lib/test/test_free_threading/test_str.py @@ -0,0 +1,110 @@ +import sys +import threading +import unittest + +from itertools import cycle +from threading import Barrier, Event, Thread +from unittest import TestCase + +from test.support import threading_helper + +@threading_helper.requires_working_threading() +class TestStr(TestCase): + def test_racing_join_extend(self): + '''Test joining a string being extended by another thread''' + l = [] + ITERS = 100 + READERS = 10 + done_event = Event() + def writer_func(): + for i in range(ITERS): + l.extend(map(str, range(i))) + l.clear() + done_event.set() + def reader_func(): + while not done_event.is_set(): + ''.join(l) + writer = Thread(target=writer_func) + readers = [] + for x in range(READERS): + reader = Thread(target=reader_func) + readers.append(reader) + reader.start() + + writer.start() + writer.join() + for reader in readers: + reader.join() + + def test_racing_join_replace(self): + ''' + Test joining a string of characters being replaced with ephemeral + strings by another thread. + ''' + l = [*'abcdefg'] + MAX_ORDINAL = 1_000 + READERS = 10 + done_event = Event() + + def writer_func(): + for i, c in zip(cycle(range(len(l))), + map(chr, range(128, MAX_ORDINAL))): + l[i] = c + done_event.set() + + def reader_func(): + while not done_event.is_set(): + ''.join(l) + ''.join(l) + ''.join(l) + ''.join(l) + + writer = Thread(target=writer_func) + readers = [] + for x in range(READERS): + reader = Thread(target=reader_func) + readers.append(reader) + reader.start() + + writer.start() + writer.join() + for reader in readers: + reader.join() + + def test_intern_unowned_string(self): + # Test interning strings owned by various threads. + strings = [f"intern_race_owner_{i}" for i in range(50)] + + NUM_THREADS = 5 + b = Barrier(NUM_THREADS) + + def interner(): + tid = threading.get_ident() + for i in range(20): + strings.append(f"intern_{tid}_{i}") + b.wait() + for s in strings: + r = sys.intern(s) + self.assertTrue(sys._is_interned(r)) + + threading_helper.run_concurrently(interner, nthreads=NUM_THREADS) + + def test_maketrans_dict_concurrent_modification(self): + for _ in range(5): + d = {2000: 'a'} + + def work(dct): + for i in range(100): + str.maketrans(dct) + dct[2000 + i] = chr(i % 16) + dct.pop(2000 + i, None) + + threading_helper.run_concurrently( + work, + nthreads=5, + args=(d,), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_string_template_race.py b/Lib/test/test_free_threading/test_string_template_race.py new file mode 100644 index 00000000000..dc4b4e9f18d --- /dev/null +++ b/Lib/test/test_free_threading/test_string_template_race.py @@ -0,0 +1,35 @@ +import string +import unittest +from string import Template + +from test.support import threading_helper + + +@threading_helper.requires_working_threading() +class TestTemplateCompileRace(unittest.TestCase): + def test_concurrent_first_use(self): + # Racing the lazy pattern compile must not raise a spurious ValueError + # from recompiling an already-compiled pattern. A throwaway subclass, + # re-armed to the sentinel each round, keeps string.Template unmutated + # (subclasses precompile eagerly in __init_subclass__). + uncompiled = string._TemplatePattern + errors = [] + + def use_template(cls): + try: + cls("$x and ${y}").substitute(x=1, y=2) + except Exception as e: + errors.append(e) + + for _ in range(20): + class T(Template): + pass + T.pattern = uncompiled + T.flags = None + threading_helper.run_concurrently(use_template, nthreads=10, args=(T,)) + + self.assertEqual(errors, [], msg=f"unexpected errors: {errors}") + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_suggestions.py b/Lib/test/test_free_threading/test_suggestions.py new file mode 100644 index 00000000000..2c10a511b86 --- /dev/null +++ b/Lib/test/test_free_threading/test_suggestions.py @@ -0,0 +1,24 @@ +import unittest + +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently + +suggestions = import_helper.import_module("_suggestions") + +NTHREADS = 10 + + +@threading_helper.requires_working_threading() +class SuggestionsTests(unittest.TestCase): + def test_generate_suggestions(self): + candidates = [str(i) for i in range(100)] + + def worker(): + _ = suggestions._generate_suggestions(candidates, "42") + candidates.clear() + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_sys.py b/Lib/test/test_free_threading/test_sys.py new file mode 100644 index 00000000000..271fdd13c62 --- /dev/null +++ b/Lib/test/test_free_threading/test_sys.py @@ -0,0 +1,49 @@ +import sys +import unittest +from test.support import threading_helper + + +class SysModuleTest(unittest.TestCase): + @unittest.skipUnless(hasattr(sys, "setdlopenflags"), + "test needs sys.setdlopenflags()") + def test_dlopenflags_concurrent(self): + # gh-151644: getdlopenflags() and setdlopenflags() must be safe to + # call concurrently in free-threaded builds. + original = sys.getdlopenflags() + self.addCleanup(sys.setdlopenflags, original) + + # Use a small set of known-valid flag values to avoid integer overflow. + flag_values = [1, 2, 256, 257] + + def worker(worker_id): + for i in range(20_000): + if worker_id % 2 == 0: + sys.getdlopenflags() + else: + sys.setdlopenflags(flag_values[worker_id % len(flag_values)]) + + workers = [lambda i=i: worker(i) for i in range(6)] + threading_helper.run_concurrently(workers) + + def test_int_max_str_digits_thread(self): + # gh-151218: Check that it's safe to call get_int_max_str_digits() and + # set_int_max_str_digits() in parallel. Previously, this test triggered + # warnings in TSan on a free threaded build. + + old_limit = sys.get_int_max_str_digits() + self.addCleanup(sys.set_int_max_str_digits, old_limit) + + def worker(worker_id): + if not worker_id: + for i in range (20_000): + sys.get_int_max_str_digits() + else: + for i in range (20_000): + sys.set_int_max_str_digits(4300 + (i & 7)) + + workers = [lambda: worker(i) for i in range(5)] + threading_helper.run_concurrently(workers) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_syslog.py b/Lib/test/test_free_threading/test_syslog.py new file mode 100644 index 00000000000..b374a98b96e --- /dev/null +++ b/Lib/test/test_free_threading/test_syslog.py @@ -0,0 +1,44 @@ +import unittest +import threading + +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently + +syslog = import_helper.import_module("syslog") + +NTHREADS = 32 + +# Similar to Lib/test/test_syslog.py, this test's purpose is to verify that +# the code neither crashes nor leaks. + + +@threading_helper.requires_working_threading() +class TestSyslog(unittest.TestCase): + def test_racing_syslog(self): + def worker(): + """ + The syslog module provides the following functions: + openlog(), syslog(), closelog(), and setlogmask(). + """ + thread_id = threading.get_ident() + syslog.openlog(f"thread-id: {thread_id}") + try: + for _ in range(5): + syslog.syslog("logline") + syslog.setlogmask(syslog.LOG_MASK(syslog.LOG_INFO)) + syslog.syslog(syslog.LOG_INFO, "logline LOG_INFO") + syslog.setlogmask(syslog.LOG_MASK(syslog.LOG_ERR)) + syslog.syslog(syslog.LOG_ERR, "logline LOG_ERR") + syslog.setlogmask(syslog.LOG_UPTO(syslog.LOG_DEBUG)) + finally: + syslog.closelog() + + # Run the worker concurrently to exercise all these syslog functions + run_concurrently( + worker_func=worker, + nthreads=NTHREADS, + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_threading.py b/Lib/test/test_free_threading/test_threading.py new file mode 100644 index 00000000000..b5a5ca272b9 --- /dev/null +++ b/Lib/test/test_free_threading/test_threading.py @@ -0,0 +1,26 @@ +import unittest +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) + + +class TestRlock(unittest.TestCase): + def test_repr_race(self): + # gh-153292 + import _thread + r = _thread.RLock() + + def repr_thread(): + for _ in range(2000): + repr(r) + + def mutate_thread(): + for _ in range(2000): + r.acquire() + r.release() + + threading_helper.run_concurrently([repr_thread, mutate_thread]) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_tokenize.py b/Lib/test/test_free_threading/test_tokenize.py new file mode 100644 index 00000000000..860cfec4d71 --- /dev/null +++ b/Lib/test/test_free_threading/test_tokenize.py @@ -0,0 +1,57 @@ +import io +import time +import unittest +import tokenize +from functools import partial +from threading import Thread + +from test.support import threading_helper + + +@threading_helper.requires_working_threading() +class TestTokenize(unittest.TestCase): + def test_tokenizer_iter(self): + source = io.StringIO("for _ in a:\n pass") + it = tokenize._tokenize.TokenizerIter(source.readline, extra_tokens=False) + + tokens = [] + def next_token(it): + while True: + try: + r = next(it) + tokens.append(tokenize.TokenInfo._make(r)) + time.sleep(0.03) + except StopIteration: + return + + threads = [] + for _ in range(5): + threads.append(Thread(target=partial(next_token, it))) + + for thread in threads: + thread.start() + + for thread in threads: + thread.join() + + expected_tokens = [ + tokenize.TokenInfo(type=1, string='for', start=(1, 0), end=(1, 3), line='for _ in a:\n'), + tokenize.TokenInfo(type=1, string='_', start=(1, 4), end=(1, 5), line='for _ in a:\n'), + tokenize.TokenInfo(type=1, string='in', start=(1, 6), end=(1, 8), line='for _ in a:\n'), + tokenize.TokenInfo(type=1, string='a', start=(1, 9), end=(1, 10), line='for _ in a:\n'), + tokenize.TokenInfo(type=11, string=':', start=(1, 10), end=(1, 11), line='for _ in a:\n'), + tokenize.TokenInfo(type=4, string='', start=(1, 11), end=(1, 11), line='for _ in a:\n'), + tokenize.TokenInfo(type=5, string='', start=(2, -1), end=(2, -1), line=' pass'), + tokenize.TokenInfo(type=1, string='pass', start=(2, 2), end=(2, 6), line=' pass'), + tokenize.TokenInfo(type=4, string='', start=(2, 6), end=(2, 6), line=' pass'), + tokenize.TokenInfo(type=6, string='', start=(2, -1), end=(2, -1), line=' pass'), + tokenize.TokenInfo(type=0, string='', start=(2, -1), end=(2, -1), line=' pass'), + ] + + tokens.sort() + expected_tokens.sort() + self.assertListEqual(tokens, expected_tokens) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_type.py b/Lib/test/test_free_threading/test_type.py new file mode 100644 index 00000000000..6dac77f6882 --- /dev/null +++ b/Lib/test/test_free_threading/test_type.py @@ -0,0 +1,264 @@ +import threading +import unittest + +from concurrent.futures import ThreadPoolExecutor +from threading import Thread +from unittest import TestCase + +from test.support import threading_helper + + + +NTHREADS = 6 +BOTTOM = 0 +TOP = 1000 +ITERS = 100 + +class A: + attr = 1 + +@threading_helper.requires_working_threading() +class TestType(TestCase): + def test_attr_cache(self): + def read(id0): + for _ in range(ITERS): + for _ in range(BOTTOM, TOP): + A.attr + + def write(id0): + for _ in range(ITERS): + for _ in range(BOTTOM, TOP): + # Make _PyType_Lookup cache hot first + A.attr + A.attr + x = A.attr + x += 1 + A.attr = x + + + with ThreadPoolExecutor(NTHREADS) as pool: + pool.submit(read, (1,)) + pool.submit(write, (1,)) + pool.shutdown(wait=True) + + def test_attr_cache_consistency(self): + class C: + x = 0 + + def writer_func(): + for _ in range(3000): + C.x + C.x + C.x += 1 + + def reader_func(): + for _ in range(3000): + # We should always see a greater value read from the type than the + # dictionary + a = C.__dict__['x'] + b = C.x + self.assertGreaterEqual(b, a) + + self.run_one(writer_func, reader_func) + + def test_attr_cache_consistency_subclass(self): + class C: + x = 0 + + class D(C): + pass + + def writer_func(): + for _ in range(3000): + D.x + D.x + C.x += 1 + + def reader_func(): + for _ in range(3000): + # We should always see a greater value read from the type than the + # dictionary + a = C.__dict__['x'] + b = D.x + self.assertGreaterEqual(b, a) + + self.run_one(writer_func, reader_func) + + def test___class___modification(self): + loops = 200 + + class Foo: + pass + + class Bar: + pass + + thing = Foo() + def work(): + foo = thing + for _ in range(loops): + foo.__class__ = Bar + type(foo) + foo.__class__ = Foo + type(foo) + + + threads = [] + for i in range(NTHREADS): + thread = threading.Thread(target=work) + thread.start() + threads.append(thread) + + for thread in threads: + thread.join() + + def test_object_class_change(self): + class Base: + def __init__(self): + self.attr = 123 + class ClassA(Base): + pass + class ClassB(Base): + pass + + obj = ClassA() + # keep reference to __dict__ + d = obj.__dict__ + obj.__class__ = ClassB + + + def test_name_change(self): + class Foo: + pass + + def writer(): + for _ in range(1000): + Foo.__name__ = 'Bar' + + def reader(): + for _ in range(1000): + Foo.__name__ + + self.run_one(writer, reader) + + def test_bases_change(self): + class BaseA: + pass + + class Derived(BaseA): + pass + + def writer(): + for _ in range(1000): + class BaseB: + pass + Derived.__bases__ = (BaseB,) + + def reader(): + for _ in range(1000): + Derived.__base__ + + self.run_one(writer, reader) + + def run_one(self, writer_func, reader_func): + barrier = threading.Barrier(NTHREADS) + + def wrap_target(target): + def wrapper(): + barrier.wait() + target() + return wrapper + + writer = Thread(target=wrap_target(writer_func)) + readers = [] + for x in range(NTHREADS - 1): + reader = Thread(target=wrap_target(reader_func)) + readers.append(reader) + reader.start() + + writer.start() + writer.join() + for reader in readers: + reader.join() + + def test_setattr_many_subclasses(self): + # gh-155978: Updating a special method queues a slot update for every + # affected subclass. Keep enough subclasses alive to require + # heap-allocated queue chunks in addition to the stack chunk. + class Base: + pass + + subclasses = [type(f"Sub{i}", (Base,), {}) for i in range(100)] + + def custom_repr(self): + return "custom repr" + + Base.__repr__ = custom_repr + self.assertTrue(all(repr(cls()) == "custom repr" + for cls in subclasses)) + + del Base.__repr__ + self.assertTrue(all(repr(cls()) != "custom repr" + for cls in subclasses)) + + + def test_concurrent_setattr_deadlock(self): + # gh-155400: two threads assigning to a special method of the same + # class could deadlock. One thread held the type lock and waited for + # the type dict mutex, which its critical section had released when it + # blocked on the stop-the-world mutex, while the other held the type + # dict mutex and waited for the type lock. + # This is fairly difficult to trigger the race but this N seems to do + # it at least sometimes. + N = 200 + done = False + + class Base: + pass + + def setter(): + func = lambda self: "x" + barrier.wait() + while not done: + Base.__repr__ = func + try: + del Base.__repr__ + except AttributeError: + pass + + def subclasser(): + barrier.wait() + while not done: + type('Sub', (Base,), {})() + + def lister(): + barrier.wait() + while not done: + Base.__subclasses__() + + def basesetter(): + nonlocal done + barrier.wait() + for _ in range(N): + class A: + pass + class C: + pass + class B(A): + pass + B.__bases__ = (C,) + done = True + + # The setter threads are the ones that deadlock. The others are there + # to keep the type lock and the stop-the-world mutex contended, which + # is what gets the setters into the window where it happens. + targets = (setter, setter, subclasser, subclasser, + lister, lister, basesetter) + barrier = threading.Barrier(len(targets)) + threads = [Thread(target=target) for target in targets] + with threading_helper.start_threads(threads): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_types.py b/Lib/test/test_free_threading/test_types.py new file mode 100644 index 00000000000..76fcf159012 --- /dev/null +++ b/Lib/test/test_free_threading/test_types.py @@ -0,0 +1,33 @@ +import unittest +from typing import TypeVar +from test.support import threading_helper + +threading_helper.requires_working_threading(module=True) + + +class TestGenericAlias(unittest.TestCase): + def test_parameters_race(self): + # gh-153298 + + T = TypeVar('T') + slot = [list[T]] + + def access(): + for _ in range(2000): + try: + _ = slot[0].__parameters__ + except Exception: + pass + + def refresh(): + for _ in range(2000): + slot[0] = list[T] + + threading_helper.run_concurrently([ + *[access for _ in range(6)], + *[refresh for _ in range(2)], + ]) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_uuid.py b/Lib/test/test_free_threading/test_uuid.py new file mode 100644 index 00000000000..d794afc552a --- /dev/null +++ b/Lib/test/test_free_threading/test_uuid.py @@ -0,0 +1,60 @@ +import os +import unittest + +from test.support import import_helper, threading_helper +from test.support.threading_helper import run_concurrently +from uuid import SafeUUID + +c_uuid = import_helper.import_module("_uuid") + +NTHREADS = 10 +UUID_PER_THREAD = 1000 + + +@threading_helper.requires_working_threading() +class UUIDTests(unittest.TestCase): + @unittest.skipUnless(os.name == "posix", "POSIX only") + def test_generate_time_safe(self): + uuids = [] + + def worker(): + local_uuids = [] + for _ in range(UUID_PER_THREAD): + uuid, is_safe = c_uuid.generate_time_safe() + self.assertIs(type(uuid), bytes) + self.assertEqual(len(uuid), 16) + # Collect the UUID only if it is safe. If not, we cannot ensure + # UUID uniqueness. According to uuid_generate_time_safe() man + # page, it is theoretically possible for two concurrently + # running processes to generate the same UUID(s) if the return + # value is not 0. + if is_safe == SafeUUID.safe: + local_uuids.append(uuid) + + # Merge all safe uuids + uuids.extend(local_uuids) + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + self.assertEqual(len(uuids), len(set(uuids))) + + @unittest.skipUnless(os.name == "nt", "Windows only") + def test_UuidCreate(self): + uuids = [] + + def worker(): + local_uuids = [] + for _ in range(UUID_PER_THREAD): + uuid = c_uuid.UuidCreate() + self.assertIs(type(uuid), bytes) + self.assertEqual(len(uuid), 16) + local_uuids.append(uuid) + + # Merge all uuids + uuids.extend(local_uuids) + + run_concurrently(worker_func=worker, nthreads=NTHREADS) + self.assertEqual(len(uuids), len(set(uuids))) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_free_threading/test_zip.py b/Lib/test/test_free_threading/test_zip.py new file mode 100644 index 00000000000..b4c5837b1d8 --- /dev/null +++ b/Lib/test/test_free_threading/test_zip.py @@ -0,0 +1,41 @@ +import unittest +from threading import Thread + +from test.support import threading_helper + + +class ZipThreading(unittest.TestCase): + @staticmethod + def work(enum): + while True: + try: + next(enum) + except StopIteration: + break + + @threading_helper.reap_threads + @threading_helper.requires_working_threading() + def test_threading(self): + number_of_threads = 8 + number_of_iterations = 8 + n = 40_000 + enum = zip(range(n), range(n)) + for _ in range(number_of_iterations): + worker_threads = [] + for ii in range(number_of_threads): + worker_threads.append( + Thread( + target=self.work, + args=[ + enum, + ], + ) + ) + for t in worker_threads: + t.start() + for t in worker_threads: + t.join() + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_fstring.py b/Lib/test/test_fstring.py index b68e356e04d..eefe043f8da 100644 --- a/Lib/test/test_fstring.py +++ b/Lib/test/test_fstring.py @@ -606,6 +606,34 @@ def test_unterminated_string(self): r"""f'{("x}'""", ]) + def test_unclosed_multiline_replacement_field(self): + for prefix in ('f', 't', 'rf', 'rt'): + for quote in ('"', "'"): + triple = quote * 3 + cases = ( + # The apparent closing quotes open a string in the field. + ('var = "abc"\na = PREFIXQUOTE {var} extern "C" { QUOTE\n' + 'b = QUOTE string QUOTE', 2), + # Parentheses and dictionaries inside the field must not + # change which opening brace the diagnostic identifies. + ('a = PREFIXQUOTE{\n(QUOTE', 1), + ('a = PREFIXQUOTE{\n{0: QUOTE', 1), + # Use the innermost format field or formatted string. + ('a = PREFIXQUOTE{0:\n{1\nQUOTE', 2), + ('a = f"{\nPREFIXQUOTE{1\nQUOTE', 2), + # Account for parentheses outside the formatted string. + ('a = (PREFIXQUOTE{1\nQUOTE', 1), + ) + for source, lineno in cases: + source = source.replace('PREFIX', prefix).replace('QUOTE', triple) + with self.subTest(source=source): + with self.assertRaises(SyntaxError) as cm: + compile(source, '', 'exec') + self.assertEqual( + cm.exception.msg, + f"{prefix[-1]}-string: expecting '}}' to close '{{' " + f"on line {lineno}") + @unittest.skipIf(support.is_wasi, "exhausts limited stack on WASI") def test_mismatched_parens(self): self.assertAllRaise(SyntaxError, r"closing parenthesis '\}' " @@ -865,7 +893,6 @@ def __format__(self, spec): x = X() self.assertEqual(f'{x} {x}', '1 2') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_missing_expression(self): self.assertAllRaise(SyntaxError, "f-string: valid expression required before '}'", @@ -1329,6 +1356,9 @@ def test_not_equal(self): self.assertEqual(f'{3!=4:}', 'True') self.assertEqual(f'{3!=4!s}', 'True') self.assertEqual(f'{3!=4!s:.3}', 'Tru') + a = 3 + b = 4 + self.assertEqual(f'{a!=b=:>10}', 'a!=b= 1') def test_equal_equal(self): # Because an expression ending in = has special meaning, @@ -1659,6 +1689,14 @@ def __repr__(self): self.assertEqual(f'{" # nooo "=}', '" # nooo "=\' # nooo \'') self.assertEqual(f'{" \" # nooo \" "=}', '" \\" # nooo \\" "=\' " # nooo " \'') + result = f'''{( + 1, # Force lexer metadata reconstruction. + "\"#")=}''' + self.assertEqual( + result, + '(\n 1, \n "\\"#")=(1, \'"#\')', + ) + self.assertEqual(f'{ # some comment goes here """hello"""=}', ' \n """hello"""=\'hello\'') self.assertEqual(f'{"""# this is not a comment @@ -1697,6 +1735,9 @@ def test_invalid_syntax_error_message(self): with self.assertRaisesRegex(SyntaxError, "f-string: expecting '=', or '!', or ':', or '}'"): compile("f'{a $ b}'", "?", "exec") + with self.assertRaisesRegex(SyntaxError, + "f-string: expecting '!', or ':', or '}'"): + compile("f'{a=b}'", "?", "exec") def test_with_two_commas_in_format_specifier(self): error_msg = re.escape("Cannot specify ',' with ','.") diff --git a/Lib/test/test_funcattrs.py b/Lib/test/test_funcattrs.py index bb9c88efec6..b2fa10d7458 100644 --- a/Lib/test/test_funcattrs.py +++ b/Lib/test/test_funcattrs.py @@ -72,7 +72,6 @@ def test(): pass test.__code__ = self.b.__code__ self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: DeprecationWarning not triggered def test_invalid___code___assignment(self): def A(): pass def B(): yield @@ -267,6 +266,41 @@ def e(): return num_one, num_two self.fail("__code__ with different numbers of free vars should " "not be possible") + def test___kwdefaults__(self): + def func(a=1, *, b=2, c=3): + return a, b, c + self.assertEqual(func.__kwdefaults__, {'b': 2, 'c': 3}) + func.__kwdefaults__ = {'b': 4} + self.assertEqual(func.__kwdefaults__, {'b': 4}) + self.assertEqual(func(c=5), (1, 4, 5)) + func.__kwdefaults__ = None + self.assertIsNone(func.__kwdefaults__) + self.assertRaises(TypeError, func) + with self.assertRaisesRegex(TypeError, + '__kwdefaults__ must be set to a dict object'): + func.__kwdefaults__ = [('b', 4)] + del func.__kwdefaults__ + self.assertIsNone(func.__kwdefaults__) + + def test_invalid___code___deletion(self): + def func(): pass + with self.assertRaisesRegex(TypeError, + '__code__ must be set to a code object'): + func.__code__ = None + with self.assertRaisesRegex(TypeError, + '__code__ must be set to a code object'): + del func.__code__ + + def test___doc__(self): + def func(): + "docstring" + self.assertEqual(func.__doc__, 'docstring') + for value in 'other', 42, None: + func.__doc__ = value + self.assertEqual(func.__doc__, value) + del func.__doc__ + self.assertIsNone(func.__doc__) + def test_blank_func_defaults(self): self.assertEqual(self.b.__defaults__, None) del self.b.__defaults__ @@ -460,6 +494,24 @@ class BuiltinFunctionPropertiesTest(unittest.TestCase): # XXX Not sure where this should really go since I can't find a # test module specifically for builtin_function_or_method. + def test_builtin__module__(self): + import math + + # builtin function: + self.assertEqual(len.__module__, 'builtins') + self.assertEqual(math.sin.__module__, 'math') + + # instance method: + self.assertRaises(AttributeError, getattr, int.to_bytes, '__module__') + self.assertEqual(int.to_bytes.__objclass__.__module__, 'builtins') + + # builtin classmethod: + self.assertEqual(int.from_bytes.__module__, None) + self.assertEqual(int.from_bytes.__self__.__module__, 'builtins') + + # builtin staticmethod: + self.assertEqual(bytes.maketrans.__module__, 'builtins') + def test_builtin__qualname__(self): import time diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py index c06140dbd58..ed3d3b6c511 100644 --- a/Lib/test/test_functools.py +++ b/Lib/test/test_functools.py @@ -438,7 +438,7 @@ def test_setstate_subclasses(self): self.assertIs(type(r[0]), tuple) @support.skip_if_sanitizer("thread sanitizer crashes in __tsan::FuncEntry", thread=True) - @support.skip_if_unlimited_stack_size + @support.skip_if_huge_c_stack() @support.skip_emscripten_stack_overflow() def test_recursive_pickle(self): with replaced_module('functools', self.module): @@ -565,7 +565,53 @@ def __repr__(self): g_partial = functools.partial(func, trigger, None, None, None, None, arg=None) self.assertEqual(repr(g_partial),"functools.partial(Function(old_function), EvilObject, None, None, None, None, arg=None)") + def test_str_subclass_error(self): + class BadStr(str): + def __eq__(self, other): + raise RuntimeError + def __hash__(self): + return str.__hash__(self) + + def f(**kwargs): + return kwargs + + p = functools.partial(f, poison="") + with self.assertRaises(RuntimeError): + result = p(**{BadStr("poison"): "new_value"}) + + def test_call_safety_against_reentrant_mutation(self): + def old_function(*args, **kwargs): + return "old_function", args, kwargs + + def new_function(*args, **kwargs): + return "new_function", args, kwargs + + g_partial = None + + class EvilKey(str): + armed = False + def __hash__(self): + if EvilKey.armed and g_partial is not None: + EvilKey.armed = False + new_args_tuple = ("new_arg",) + new_keywords_dict = {"new_keyword": None} + new_tuple_state = (new_function, new_args_tuple, new_keywords_dict, None) + g_partial.__setstate__(new_tuple_state) + gc.collect() + return str.__hash__(self) + g_partial = functools.partial(old_function, "old_arg", old_keyword=None) + + kwargs = {EvilKey("evil_key"): None} + EvilKey.armed = True + + result = g_partial(**kwargs) + expected = ("old_function", ("old_arg",), {"old_keyword": None, "evil_key": None}) + self.assertEqual(result, expected) + + result = g_partial() + expected = ("new_function", ("new_arg",), {"new_keyword": None}) + self.assertEqual(result, expected) @unittest.skipUnless(c_functools, 'requires the C _functools module') class TestPartialC(TestPartial, unittest.TestCase): @@ -2209,6 +2255,13 @@ def fib(n): with self.assertRaises(RecursionError): fib(support.exceeds_recursion_limit()) + def test_lru_checks_arg_is_callable(self): + with self.assertRaisesRegex( + TypeError, + "the first argument must be callable", + ): + self.module.lru_cache(1)('hello') + @py_functools.lru_cache() def py_cached_func(x, y): @@ -2233,10 +2286,6 @@ def cached_meth(self, x, y): def cached_staticmeth(x, y): return 3 * x + y - @unittest.expectedFailure # TODO: RUSTPYTHON; Python lru_cache impl doesn't cache hash like C impl - def test_lru_hash_only_once(self): - return super().test_lru_hash_only_once() - @unittest.skipUnless(c_functools, 'requires the C _functools module') class TestLRUC(TestLRU, unittest.TestCase): @@ -2843,7 +2892,7 @@ class Slot: @functools.singledispatchmethod @classmethod def go(cls, item, arg): - pass + return item - arg @go.register @classmethod @@ -2852,7 +2901,9 @@ def _(cls, item: int, arg): s = Slot() self.assertEqual(s.go(1, 1), 2) + self.assertEqual(s.go(1.5, 1), 0.5) self.assertEqual(Slot.go(1, 1), 2) + self.assertEqual(Slot.go(1.5, 1), 0.5) def test_staticmethod_slotted_class(self): class A: @@ -3052,6 +3103,57 @@ def static_func(arg: int) -> str: self.assertEqual(A.static_func.__name__, 'static_func') self.assertEqual(A().static_func.__name__, 'static_func') + def test_method_classlevel_calls(self): + """Regression test for GH-143535.""" + class C: + @functools.singledispatchmethod + def generic(self, x: object): + return "generic" + + @generic.register + def special1(self, x: int): + return "special1" + + @generic.register + @classmethod + def special2(self, x: float): + return "special2" + + @generic.register + @staticmethod + def special3(x: complex): + return "special3" + + def special4(self, x): + return "special4" + + class D1: + def __get__(self, _, owner): + return lambda inst, x: owner.special4(inst, x) + + generic.register(D1, D1()) + + def special5(self, x): + return "special5" + + class D2: + def __get__(self, inst, owner): + # Different instance bound to the returned method + # doesn't cause it to receive the original instance + # as a separate argument. + # To work around this, wrap the returned bound method + # with `functools.partial`. + return C().special5 + + generic.register(D2, D2()) + + self.assertEqual(C.generic(C(), "foo"), "generic") + self.assertEqual(C.generic(C(), 1), "special1") + self.assertEqual(C.generic(C(), 2.0), "special2") + self.assertEqual(C.generic(C(), 3j), "special3") + self.assertEqual(C.generic(C(), C.D1()), "special4") + self.assertEqual(C.generic(C(), C.D2()), "special5") + def test_method_repr(self): class Callable: def __call__(self, *args): @@ -3290,6 +3392,21 @@ def t(self, *args, **kwargs): with self.assertRaisesRegex(TypeError, msg): A().t(a=1) + def test_positional_only_argument(self): + @functools.singledispatch + def f(arg, /, extra): + return "base" + @f.register + def f_int(arg: int, /, extra: str): + return "int" + @f.register + def f_str(arg: str, /, extra: int): + return "str" + + self.assertEqual(f(None, "extra"), "base") + self.assertEqual(f(1, "extra"), "int") + self.assertEqual(f("s", "extra"), "str") + def test_union(self): @functools.singledispatch def f(arg): @@ -3538,6 +3655,37 @@ def _(item: int, arg: bytes) -> str: self.assertEqual(str(Signature.from_callable(A.static_func)), '(item, arg: int) -> str') + def test_method_non_descriptor(self): + class Callable: + def __init__(self, value): + self.value = value + def __call__(self, arg): + return self.value, arg + + class A: + t = functools.singledispatchmethod(Callable('general')) + t.register(int, Callable('special')) + + @functools.singledispatchmethod + def u(self, arg): + return 'general', arg + u.register(int, Callable('special')) + + v = functools.singledispatchmethod(Callable('general')) + @v.register(int) + def _(self, arg): + return 'special', arg + + a = A() + self.assertEqual(a.t(0), ('special', 0)) + self.assertEqual(a.t(2.5), ('general', 2.5)) + self.assertEqual(A.t(0), ('special', 0)) + self.assertEqual(A.t(2.5), ('general', 2.5)) + self.assertEqual(a.u(0), ('special', 0)) + self.assertEqual(a.u(2.5), ('general', 2.5)) + self.assertEqual(a.v(0), ('special', 0)) + self.assertEqual(a.v(2.5), ('general', 2.5)) + class CachedCostItem: _cost = 1 diff --git a/Lib/test/test_future_stmt/test_future.py b/Lib/test/test_future_stmt/test_future.py index 71f1e616116..faa3a2bfe12 100644 --- a/Lib/test/test_future_stmt/test_future.py +++ b/Lib/test/test_future_stmt/test_future.py @@ -349,6 +349,8 @@ def test_annotations(self): eq("(i ** 2 + j for i in (1, 2, 3) for j in (1, 2, 3))") eq("{i: 0 for i in (1, 2, 3)}") eq("{i: j for i, j in ((1, 'a'), (2, 'b'), (3, 'c'))}") + eq("{**x for x in ()}") + eq("[*x for x in ()]") eq("[(x, y) for x, y in (a, b)]") eq("[(x,) for x, in (a,)]") eq("Python3 > Python2 > COBOL") diff --git a/Lib/test/test_gc.py b/Lib/test/test_gc.py index 3ed2aabafcb..c477006c9cc 100644 --- a/Lib/test/test_gc.py +++ b/Lib/test/test_gc.py @@ -236,7 +236,6 @@ def test_function(self): # is 3 because it includes f's code object. self.assertIn(gc.collect(), (2, 3)) - @unittest.expectedFailure # TODO: RUSTPYTHON; - weakref clear ordering differs from 3.15+ def test_function_tp_clear_leaves_consistent_state(self): # https://github.com/python/cpython/issues/91636 code = """if 1: @@ -310,6 +309,26 @@ def func(): self.assertRegex(stdout, rb"""\A\s*func=None""") self.assertFalse(stderr) + def test_datetime_weakref_cycle(self): + # https://github.com/python/cpython/issues/132413 + # If the weakref used by the datetime extension gets cleared by the GC (due to being + # in an unreachable cycle) then datetime functions would crash (get_module_state() + # was returning a NULL pointer). This bug is fixed by clearing weakrefs without + # callbacks *after* running finalizers. + code = """if 1: + import _datetime + class C: + def __del__(self): + print('__del__ called') + _datetime.timedelta(days=1) # crash? + + l = [C()] + l.append(l) + """ + rc, stdout, stderr = assert_python_ok("-c", code) + self.assertEqual(rc, 0) + self.assertEqual(stdout.strip(), b'__del__ called') + @refcount_test def test_frame(self): def f(): @@ -667,9 +686,8 @@ def callback(ignored): gc.collect() self.assertEqual(len(ouch), 2) # else the callbacks didn't run for x in ouch: - # If the callback resurrected one of these guys, the instance - # would be damaged, with an empty __dict__. - self.assertEqual(x, None) + # The weakref should be cleared before executing the callback. + self.assertIsNone(x) def test_bug21435(self): # This is a poor test - its only virtue is that it happened to @@ -831,17 +849,20 @@ def __del__(self): rc, out, err = assert_python_ok(TESTFN) self.assertEqual(out.strip(), b'__del__ called') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_get_stats(self): stats = gc.get_stats() self.assertEqual(len(stats), 3) for st in stats: self.assertIsInstance(st, dict) - self.assertEqual(set(st), - {"collected", "collections", "uncollectable"}) + self.assertEqual( + set(st), + {"collected", "collections", "uncollectable", "candidates", "duration"} + ) self.assertGreaterEqual(st["collected"], 0) self.assertGreaterEqual(st["collections"], 0) self.assertGreaterEqual(st["uncollectable"], 0) + self.assertGreaterEqual(st["candidates"], 0) + self.assertGreaterEqual(st["duration"], 0) # Check that collection counts are incremented correctly if gc.isenabled(): self.addCleanup(gc.enable) @@ -852,11 +873,25 @@ def test_get_stats(self): self.assertEqual(new[0]["collections"], old[0]["collections"] + 1) self.assertEqual(new[1]["collections"], old[1]["collections"]) self.assertEqual(new[2]["collections"], old[2]["collections"]) + self.assertGreater(new[0]["duration"], old[0]["duration"]) + self.assertEqual(new[1]["duration"], old[1]["duration"]) + self.assertEqual(new[2]["duration"], old[2]["duration"]) + for stat in ["collected", "uncollectable", "candidates"]: + self.assertGreaterEqual(new[0][stat], old[0][stat]) + self.assertEqual(new[1][stat], old[1][stat]) + self.assertEqual(new[2][stat], old[2][stat]) gc.collect(2) - new = gc.get_stats() - self.assertEqual(new[0]["collections"], old[0]["collections"] + 1) + old, new = new, gc.get_stats() + self.assertEqual(new[0]["collections"], old[0]["collections"]) self.assertEqual(new[1]["collections"], old[1]["collections"]) self.assertEqual(new[2]["collections"], old[2]["collections"] + 1) + self.assertEqual(new[0]["duration"], old[0]["duration"]) + self.assertEqual(new[1]["duration"], old[1]["duration"]) + self.assertGreater(new[2]["duration"], old[2]["duration"]) + for stat in ["collected", "uncollectable", "candidates"]: + self.assertEqual(new[0][stat], old[0][stat]) + self.assertEqual(new[1][stat], old[1][stat]) + self.assertGreaterEqual(new[2][stat], old[2][stat]) def test_freeze(self): gc.freeze() @@ -1204,6 +1239,37 @@ def test_something(self): """) assert_python_ok("-c", source) + def test_do_not_cleanup_type_subclasses_before_finalization(self): + # See https://github.com/python/cpython/issues/135552 + # If we cleanup weakrefs for tp_subclasses before calling + # the finalizer (__del__) then the line `fail = BaseNode.next.next` + # should fail because we are trying to access a subclass + # attribute. But subclass type cache was not properly invalidated. + code = """ + class BaseNode: + def __del__(self): + BaseNode.next = BaseNode.next.next + fail = BaseNode.next.next + + class Node(BaseNode): + pass + + BaseNode.next = Node() + BaseNode.next.next = Node() + """ + # this test checks garbage collection while interp + # finalization + assert_python_ok("-c", textwrap.dedent(code)) + + code_inside_function = textwrap.dedent(F""" + def test(): + {textwrap.indent(code, ' ')} + + test() + """) + # this test checks regular garbage collection + assert_python_ok("-c", code_inside_function) + @unittest.expectedFailure # TODO: RUSTPYTHON; long_lived_total does not count untracked tuples @unittest.skipUnless(Py_GIL_DISABLED, "requires free-threaded GC") @@ -1308,9 +1374,11 @@ def test_collect(self): # Check that we got the right info dict for all callbacks for v in self.visit: info = v[2] - self.assertTrue("generation" in info) - self.assertTrue("collected" in info) - self.assertTrue("uncollectable" in info) + self.assertIn("generation", info) + self.assertIn("collected", info) + self.assertIn("uncollectable", info) + self.assertIn("candidates", info) + self.assertIn("duration", info) def test_collect_generation(self): self.preclean() @@ -1498,6 +1566,7 @@ def callback(ignored): self.assertEqual(x, None) @gc_threshold(1000, 0, 0) + @unittest.skipIf(Py_GIL_DISABLED, "requires GC generations or increments") def test_bug1055820d(self): # Corresponds to temp2d.py in the bug report. This is very much like # test_bug1055820c, but uses a __del__ method instead of a weakref @@ -1595,6 +1664,25 @@ def test_indirect_calls_with_gc_disabled(self): finally: gc.enable() + def test_get_count_nonnegative(self): + xs = [[] for _ in range(1500)] + gc.collect() + del xs[:1000] + self.assertGreaterEqual(gc.get_count()[0], 0) + + @gc_threshold(1000, 0, 0) + def test_get_count_does_not_prevent_collection(self): + junk = [] + gc.collect() + detector = GC_Detector() + for _ in range(10000): + junk.append([]) + gc.get_count() + if detector.gc_happened: + break + else: + self.fail("gc didn't happen after 10000 iterations") + # Ensure that setting *threshold0* to zero disables collection. @gc_threshold(0) def test_threshold_zero(self): diff --git a/Lib/test/test_generated_cases.py b/Lib/test/test_generated_cases.py index fc34ac2fdc9..9915d7be706 100644 --- a/Lib/test/test_generated_cases.py +++ b/Lib/test/test_generated_cases.py @@ -1,11 +1,9 @@ import contextlib import os -import re import sys import tempfile import unittest -from io import StringIO from test import support from test import test_tools @@ -31,13 +29,13 @@ def skip_if_different_mount_drives(): test_tools.skip_if_missing("cases_generator") with test_tools.imports_under_tool("cases_generator"): - from analyzer import analyze_forest, StackItem + from analyzer import StackItem, analyze_files from cwriter import CWriter import parser from stack import Local, Stack import tier1_generator - import opcode_metadata_generator import optimizer_generator + import record_function_generator def handle_stderr(): @@ -59,14 +57,14 @@ class TestEffects(unittest.TestCase): def test_effect_sizes(self): stack = Stack() inputs = [ - x := StackItem("x", None, "1"), - y := StackItem("y", None, "oparg"), - z := StackItem("z", None, "oparg*2"), + x := StackItem("x", "1"), + y := StackItem("y", "oparg"), + z := StackItem("z", "oparg*2"), ] outputs = [ - StackItem("x", None, "1"), - StackItem("b", None, "oparg*4"), - StackItem("c", None, "1"), + StackItem("x", "1"), + StackItem("b", "oparg*4"), + StackItem("c", "1"), ] null = CWriter.null() stack.pop(z, null) @@ -135,7 +133,7 @@ def test_inst_no_args(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -157,7 +155,7 @@ def test_inst_one_pop(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -168,7 +166,7 @@ def test_inst_one_pop(self): value = stack_pointer[-1]; SPAM(value); stack_pointer += -1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -182,7 +180,7 @@ def test_inst_one_push(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -193,7 +191,7 @@ def test_inst_one_push(self): res = SPAM(); stack_pointer[0] = res; stack_pointer += 1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -208,7 +206,7 @@ def test_inst_one_push_one_pop(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -235,7 +233,7 @@ def test_binary_op(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -250,7 +248,7 @@ def test_binary_op(self): res = SPAM(left, right); stack_pointer[-2] = res; stack_pointer += -1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -265,7 +263,7 @@ def test_overlap(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -299,7 +297,7 @@ def test_predictions(self): """ output = """ TARGET(OP1) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP1; (void)(opcode); #endif @@ -316,7 +314,7 @@ def test_predictions(self): } TARGET(OP3) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP3; (void)(opcode); #endif @@ -358,7 +356,7 @@ def test_sync_sp(self): """ output = """ TARGET(A) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = A; (void)(opcode); #endif @@ -369,19 +367,19 @@ def test_sync_sp(self): _PyStackRef res; arg = stack_pointer[-1]; stack_pointer += -1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); escaping_call(); stack_pointer = _PyFrame_GetStackPointer(frame); res = Py_None; stack_pointer[0] = res; stack_pointer += 1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } TARGET(B) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = B; (void)(opcode); #endif @@ -424,7 +422,7 @@ def test_error_if_plain(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -447,7 +445,7 @@ def test_error_if_plain_with_comment(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -473,7 +471,7 @@ def test_error_if_pop(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -492,7 +490,7 @@ def test_error_if_pop(self): res = 0; stack_pointer[-2] = res; stack_pointer += -1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -508,7 +506,7 @@ def test_error_if_pop_with_result(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -526,7 +524,7 @@ def test_error_if_pop_with_result(self): } stack_pointer[-2] = res; stack_pointer += -1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -540,7 +538,7 @@ def test_cache_effect(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -556,7 +554,7 @@ def test_cache_effect(self): uint32_t extra = read_u32(&this_instr[2].cache); (void)extra; stack_pointer += -1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -573,7 +571,7 @@ def test_suppress_dispatch(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -607,7 +605,7 @@ def test_macro_instruction(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -643,12 +641,12 @@ def test_macro_instruction(self): } stack_pointer[-3] = res; stack_pointer += -2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } TARGET(OP1) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP1; (void)(opcode); #endif @@ -670,7 +668,7 @@ def test_macro_instruction(self): } TARGET(OP3) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP3; (void)(opcode); #endif @@ -691,7 +689,7 @@ def test_macro_instruction(self): stack_pointer = _PyFrame_GetStackPointer(frame); stack_pointer[-3] = res; stack_pointer += -2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -705,7 +703,7 @@ def test_unused_caches(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -731,7 +729,7 @@ def test_pseudo_instruction_no_flags(self): """ output = """ TARGET(OP1) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP1; (void)(opcode); #endif @@ -754,7 +752,7 @@ def test_pseudo_instruction_with_flags(self): """ output = """ TARGET(OP1) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP1; (void)(opcode); #endif @@ -780,7 +778,7 @@ def test_pseudo_instruction_as_sequence(self): """ output = """ TARGET(OP1) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP1; (void)(opcode); #endif @@ -791,7 +789,7 @@ def test_pseudo_instruction_as_sequence(self): } TARGET(OP2) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP2; (void)(opcode); #endif @@ -815,7 +813,7 @@ def test_array_input(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -830,7 +828,7 @@ def test_array_input(self): below = stack_pointer[-2 - oparg*2]; SPAM(values, oparg); stack_pointer += -2 - oparg*2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -846,7 +844,7 @@ def test_array_output(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -863,7 +861,7 @@ def test_array_output(self): stack_pointer[-2] = below; stack_pointer[-1 + oparg*3] = above; stack_pointer += oparg*3; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -878,7 +876,7 @@ def test_array_input_output(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -892,7 +890,7 @@ def test_array_input_output(self): above = 0; stack_pointer[0] = above; stack_pointer += 1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -908,7 +906,7 @@ def test_array_error_if(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -921,11 +919,11 @@ def test_array_error_if(self): extra = stack_pointer[-1 - oparg]; if (oparg == 0) { stack_pointer += -1 - oparg; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); JUMP_TO_LABEL(error); } stack_pointer += -1 - oparg; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -943,7 +941,7 @@ def test_macro_push_push(self): """ output = """ TARGET(M) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = M; (void)(opcode); #endif @@ -963,7 +961,7 @@ def test_macro_push_push(self): stack_pointer[0] = val1; stack_pointer[1] = val2; stack_pointer += 2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -980,7 +978,7 @@ def test_override_inst(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1005,7 +1003,7 @@ def test_override_op(self): """ output = """ TARGET(M) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = M; (void)(opcode); #endif @@ -1026,7 +1024,7 @@ def test_annotated_inst(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1048,7 +1046,7 @@ def test_annotated_op(self): """ output = """ TARGET(M) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = M; (void)(opcode); #endif @@ -1089,7 +1087,7 @@ def test_array_of_one(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1106,32 +1104,6 @@ def test_array_of_one(self): """ self.run_cases_test(input, output) - def test_pointer_to_stackref(self): - input = """ - inst(OP, (arg: _PyStackRef * -- out)) { - out = *arg; - DEAD(arg); - } - """ - output = """ - TARGET(OP) { - #if Py_TAIL_CALL_INTERP - int opcode = OP; - (void)(opcode); - #endif - frame->instr_ptr = next_instr; - next_instr += 1; - INSTRUCTION_STATS(OP); - _PyStackRef *arg; - _PyStackRef out; - arg = (_PyStackRef *)stack_pointer[-1].bits; - out = *arg; - stack_pointer[-1] = out; - DISPATCH(); - } - """ - self.run_cases_test(input, output) - def test_unused_cached_value(self): input = """ op(FIRST, (arg1 -- out)) { @@ -1157,7 +1129,7 @@ def test_unused_named_values(self): """ output = """ TARGET(INST) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = INST; (void)(opcode); #endif @@ -1187,7 +1159,7 @@ def test_used_unused_used(self): """ output = """ TARGET(TEST) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = TEST; (void)(opcode); #endif @@ -1231,7 +1203,7 @@ def test_unused_used_used(self): """ output = """ TARGET(TEST) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = TEST; (void)(opcode); #endif @@ -1274,7 +1246,7 @@ def test_flush(self): """ output = """ TARGET(TEST) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = TEST; (void)(opcode); #endif @@ -1292,13 +1264,13 @@ def test_flush(self): stack_pointer[0] = a; stack_pointer[1] = b; stack_pointer += 2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); // SECOND { USE(a, b); } stack_pointer += -2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -1326,7 +1298,7 @@ def test_pop_on_error_peeks(self): """ output = """ TARGET(TEST) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = TEST; (void)(opcode); #endif @@ -1354,7 +1326,7 @@ def test_pop_on_error_peeks(self): } } stack_pointer += -2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -1377,7 +1349,7 @@ def test_push_then_error(self): output = """ TARGET(TEST) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = TEST; (void)(opcode); #endif @@ -1397,14 +1369,14 @@ def test_push_then_error(self): stack_pointer[0] = a; stack_pointer[1] = b; stack_pointer += 2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); JUMP_TO_LABEL(error); } } stack_pointer[0] = a; stack_pointer[1] = b; stack_pointer += 2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -1422,7 +1394,7 @@ def test_error_if_true(self): """ output = """ TARGET(OP1) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP1; (void)(opcode); #endif @@ -1433,7 +1405,7 @@ def test_error_if_true(self): } TARGET(OP2) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP2; (void)(opcode); #endif @@ -1495,7 +1467,7 @@ def test_stack_save_reload(self): output = """ TARGET(BALANCED) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = BALANCED; (void)(opcode); #endif @@ -1521,7 +1493,7 @@ def test_stack_save_reload_paired(self): output = """ TARGET(BALANCED) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = BALANCED; (void)(opcode); #endif @@ -1543,7 +1515,7 @@ def test_stack_reload_only(self): output = """ TARGET(BALANCED) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = BALANCED; (void)(opcode); #endif @@ -1568,7 +1540,7 @@ def test_stack_save_only(self): output = """ TARGET(BALANCED) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = BALANCED; (void)(opcode); #endif @@ -1594,7 +1566,7 @@ def test_instruction_size_macro(self): output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1633,7 +1605,7 @@ def test_escaping_call_next_to_cmacro(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1671,7 +1643,7 @@ def test_pystackref_frompyobject_new_next_to_cmacro(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1690,7 +1662,7 @@ def test_pystackref_frompyobject_new_next_to_cmacro(self): stack_pointer[0] = out1; stack_pointer[1] = out2; stack_pointer += 2; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } """ @@ -1869,7 +1841,7 @@ def test_reassigning_live_inputs(self): output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1896,7 +1868,7 @@ def test_reassigning_dead_inputs(self): """ output = """ TARGET(OP) { - #if Py_TAIL_CALL_INTERP + #if _Py_TAIL_CALL_INTERP int opcode = OP; (void)(opcode); #endif @@ -1910,7 +1882,7 @@ def test_reassigning_dead_inputs(self): stack_pointer = _PyFrame_GetStackPointer(frame); in = temp; stack_pointer += -1; - assert(WITHIN_STACK_BOUNDS()); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); PyStackRef_CLOSE(in); stack_pointer = _PyFrame_GetStackPointer(frame); @@ -1919,6 +1891,441 @@ def test_reassigning_dead_inputs(self): """ self.run_cases_test(input, output) + def test_recording_after_specializing_with_cache(self): + input = """ + specializing op(SPEC, (counter/1 --)) { + spam; + } + + tier2 op(REC, (--)) { + RECORD_VALUE(0); + } + + op(BODY, (--)) { + ham; + } + + macro(OP) = SPEC + unused/2 + REC + BODY; + """ + output = """ + TARGET(OP) { + #if _Py_TAIL_CALL_INTERP + int opcode = OP; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(OP); + // SPEC + { + uint16_t counter = read_u16(&this_instr[1].cache); + (void)counter; + spam; + } + /* Skip 2 cache entries */ + // BODY + { + ham; + } + DISPATCH(); + } + """ + self.run_cases_test(input, output) + + def test_recording_after_non_specializing(self): + input = """ + op(REGULAR, (--)) { + spam; + } + + tier2 op(REC, (--)) { + RECORD_VALUE(0); + } + + macro(OP) = REGULAR + REC; + """ + with self.assertRaisesRegex(SyntaxError, "Recording uop"): + self.run_cases_test(input, "") + + def test_multiple_consecutive_recording_uops(self): + """Multiple consecutive recording uops at the start of a macro are legal.""" + input = """ + tier2 op(_RECORD_A, (a, b -- a, b)) { + RECORD_VALUE(a); + } + tier2 op(_RECORD_B, (a, b -- a, b)) { + RECORD_VALUE(b); + } + op(_DO_STUFF, (a, b -- res)) { + res = a; + INPUTS_DEAD(); + } + macro(OP) = _RECORD_A + _RECORD_B + _DO_STUFF; + """ + output = """ + TARGET(OP) { + #if _Py_TAIL_CALL_INTERP + int opcode = OP; + (void)(opcode); + #endif + frame->instr_ptr = next_instr; + next_instr += 1; + INSTRUCTION_STATS(OP); + _PyStackRef a; + _PyStackRef res; + // _DO_STUFF + { + a = stack_pointer[-2]; + res = a; + } + stack_pointer[-2] = res; + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + """ + self.run_cases_test(input, output) + + def test_multiple_recording_uops_after_specializing(self): + """Multiple recording uops after a specializing uop are legal.""" + input = """ + specializing op(_SPECIALIZE_OP, (counter/1, a, b -- a, b)) { + SPAM(); + } + tier2 op(_RECORD_A, (a, b -- a, b)) { + RECORD_VALUE(a); + } + tier2 op(_RECORD_B, (a, b -- a, b)) { + RECORD_VALUE(b); + } + op(_DO_STUFF, (a, b -- res)) { + res = a; + INPUTS_DEAD(); + } + macro(OP) = _SPECIALIZE_OP + _RECORD_A + _RECORD_B + unused/2 + _DO_STUFF; + """ + output = """ + TARGET(OP) { + #if _Py_TAIL_CALL_INTERP + int opcode = OP; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(OP); + _PyStackRef a; + _PyStackRef res; + // _SPECIALIZE_OP + { + uint16_t counter = read_u16(&this_instr[1].cache); + (void)counter; + SPAM(); + } + /* Skip 2 cache entries */ + // _DO_STUFF + { + a = stack_pointer[-2]; + res = a; + } + stack_pointer[-2] = res; + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + """ + self.run_cases_test(input, output) + + def test_recording_uop_between_real_uops_rejected(self): + """A recording uop sandwiched between real uops is rejected.""" + input = """ + tier2 op(_RECORD_A, (a, b -- a, b)) { + RECORD_VALUE(a); + } + op(_FIRST, (a, b -- a, b)) { + first(a); + } + tier2 op(_RECORD_B, (a, b -- a, b)) { + RECORD_VALUE(b); + } + macro(OP) = _RECORD_A + _FIRST + _RECORD_B; + """ + with self.assertRaisesRegex(SyntaxError, + "must precede all " + "non-recording, non-specializing uops"): + self.run_cases_test(input, "") + + +class TestRecorderTableGeneration(unittest.TestCase): + + def setUp(self) -> None: + super().setUp() + self.maxDiff = None + self.temp_dir = tempfile.gettempdir() + self.temp_input_filename = os.path.join(self.temp_dir, "input.txt") + + def tearDown(self) -> None: + try: + os.remove(self.temp_input_filename) + except FileNotFoundError: + pass + super().tearDown() + + def analyze_input(self, input: str): + with open(self.temp_input_filename, "w+") as f: + f.write(parser.BEGIN_MARKER) + f.write(input) + f.write(parser.END_MARKER) + with handle_stderr(): + return analyze_files([self.temp_input_filename]) + + def generate_tables(self, input: str) -> str: + import io + analysis = self.analyze_input(input) + buf = io.StringIO() + out = CWriter(buf, 0, False) + record_function_generator.generate_recorder_tables(analysis, out) + return buf.getvalue() + + def get_slot_map_section(self, output: str) -> str: + return output.split( + "const _PyOpcodeRecordSlotMap _PyOpcode_RecordSlotMaps[256] = {\n", + 1, + )[1].split("};\n\n", 1)[0] + + def assert_slot_map_lines(self, output: str, *lines: str) -> None: + slot_map_section = self.get_slot_map_section(output) + for line in lines: + self.assertIn(line, slot_map_section) + + def test_single_recording_uop_generates_count(self): + input = """ + tier2 op(_RECORD_TOS, (value -- value)) { + RECORD_VALUE(value); + } + op(_DO_STUFF, (value -- res)) { + res = value; + } + macro(OP) = _RECORD_TOS + _DO_STUFF; + """ + output = self.generate_tables(input) + self.assertIn("_RECORD_TOS_INDEX", output) + self.assertIn("[OP] = {1, {_RECORD_TOS_INDEX}}", output) + + def test_three_recording_uops_generate_count_3_in_order(self): + input = """ + tier2 op(_RECORD_X, (a, b, c -- a, b, c)) { + RECORD_VALUE(a); + } + tier2 op(_RECORD_Y, (a, b, c -- a, b, c)) { + RECORD_VALUE(b); + } + tier2 op(_RECORD_Z, (a, b, c -- a, b, c)) { + RECORD_VALUE(c); + } + op(_DO_STUFF, (a, b, c -- res)) { + res = a; + } + macro(OP) = _RECORD_X + _RECORD_Y + _RECORD_Z + _DO_STUFF; + """ + output = self.generate_tables(input) + self.assertIn( + "[OP] = {3, {_RECORD_X_INDEX, _RECORD_Y_INDEX, _RECORD_Z_INDEX}}", + output, + ) + + def test_four_recording_uops_rejected(self): + input = """ + tier2 op(_RECORD_A, (a, b, c, d -- a, b, c, d)) { + RECORD_VALUE(a); + } + tier2 op(_RECORD_B, (a, b, c, d -- a, b, c, d)) { + RECORD_VALUE(b); + } + tier2 op(_RECORD_C, (a, b, c, d -- a, b, c, d)) { + RECORD_VALUE(c); + } + tier2 op(_RECORD_D, (a, b, c, d -- a, b, c, d)) { + RECORD_VALUE(d); + } + op(_DO_STUFF, (a, b, c, d -- res)) { + res = a; + } + macro(OP) = _RECORD_A + _RECORD_B + _RECORD_C + _RECORD_D + _DO_STUFF; + """ + with self.assertRaisesRegex(ValueError, "exceeds MAX_RECORDED_VALUES"): + self.generate_tables(input) + + def test_family_member_needs_transform_only_when_shape_changes(self): + input = """ + tier2 op(_RECORD_TOS, (value -- value)) { + RECORD_VALUE(value); + } + tier2 op(_RECORD_TOS_TYPE, (value -- value)) { + RECORD_VALUE(Py_TYPE(value)); + } + op(_DO_STUFF, (value -- res)) { + res = value; + } + macro(OP_RAW) = _RECORD_TOS + _DO_STUFF; + macro(OP_RAW_SPECIALIZED) = _RECORD_TOS_TYPE + _DO_STUFF; + family(OP_RAW, INLINE_CACHE_ENTRIES_OP_RAW) = { OP_RAW_SPECIALIZED }; + + macro(OP_TYPED) = _RECORD_TOS_TYPE + _DO_STUFF; + macro(OP_TYPED_SPECIALIZED) = _RECORD_TOS_TYPE + _DO_STUFF; + family(OP_TYPED, INLINE_CACHE_ENTRIES_OP_TYPED) = { OP_TYPED_SPECIALIZED }; + """ + output = self.generate_tables(input) + self.assert_slot_map_lines( + output, + "[OP_RAW] = {1, 0, {0}}", + "[OP_RAW_SPECIALIZED] = {1, 1, {0}}", + "[OP_TYPED] = {1, 0, {0}}", + "[OP_TYPED_SPECIALIZED] = {1, 0, {0}}", + ) + + def test_family_member_maps_positional_recorders_to_family_slots(self): + input = """ + tier2 op(_RECORD_TOS, (sub -- sub)) { + RECORD_VALUE(sub); + } + tier2 op(_RECORD_NOS, (container, sub -- container, sub)) { + RECORD_VALUE(container); + } + op(_DO_STUFF, (container, sub -- res)) { + res = container; + } + macro(OP) = _RECORD_TOS + _RECORD_NOS + _DO_STUFF; + macro(OP_SPECIALIZED) = _RECORD_NOS + _DO_STUFF; + family(OP, INLINE_CACHE_ENTRIES_OP) = { OP_SPECIALIZED }; + """ + output = self.generate_tables(input) + self.assert_slot_map_lines( + output, + "[OP] = {2, 0, {1, 0}}", + "[OP_SPECIALIZED] = {1, 0, {0}}", + ) + + def test_family_member_maps_non_positional_recorders_by_stack_shape(self): + input = """ + tier2 op(_RECORD_CALLABLE, (callable, self, args[oparg] -- callable, self, args[oparg])) { + RECORD_VALUE(callable); + } + tier2 op(_RECORD_BOUND_METHOD, (callable, self, args[oparg] -- callable, self, args[oparg])) { + RECORD_VALUE(callable); + } + op(_DO_STUFF, (callable, self, args[oparg] -- res)) { + res = callable; + } + macro(OP) = _RECORD_CALLABLE + _DO_STUFF; + macro(OP_SPECIALIZED) = _RECORD_BOUND_METHOD + _DO_STUFF; + family(OP, INLINE_CACHE_ENTRIES_OP) = { OP_SPECIALIZED }; + """ + output = self.generate_tables(input) + self.assert_slot_map_lines( + output, + "[OP] = {1, 0, {0}}", + "[OP_SPECIALIZED] = {1, 1, {0}}", + ) + + def test_family_head_records_union_of_member_recorders(self): + input = """ + tier2 op(_RECORD_TOS, (value -- value)) { + RECORD_VALUE(value); + } + op(_DO_STUFF, (value -- res)) { + res = value; + } + macro(OP) = _DO_STUFF; + macro(OP_SPECIALIZED) = _RECORD_TOS + _DO_STUFF; + family(OP, INLINE_CACHE_ENTRIES_OP) = { OP_SPECIALIZED }; + """ + output = self.generate_tables(input) + self.assertIn("[OP] = {1, {_RECORD_TOS_INDEX}}", output) + self.assertIn("[OP_SPECIALIZED] = {1, {_RECORD_TOS_INDEX}}", output) + self.assert_slot_map_lines(output, "[OP_SPECIALIZED] = {1, 0, {0}}") + + def test_family_detects_base_and_specialized_recording_difference(self): + input = """ + tier2 op(_RECORD_TOS, (value -- value)) { + RECORD_VALUE(value); + } + tier2 op(_RECORD_TOS_TYPE, (value -- value)) { + RECORD_VALUE(Py_TYPE(value)); + } + op(_DO_STUFF, (value -- res)) { + res = value; + } + macro(OP) = _RECORD_TOS + _DO_STUFF; + macro(OP_SPECIALIZED) = _RECORD_TOS_TYPE + _DO_STUFF; + family(OP, INLINE_CACHE_ENTRIES_OP) = { OP_SPECIALIZED }; + """ + analysis = self.analyze_input(input) + output = self.generate_tables(input) + self.assertEqual( + record_function_generator.get_instruction_record_names( + analysis.instructions["OP"] + ), + ["_RECORD_TOS"], + ) + self.assertEqual( + record_function_generator.get_instruction_record_names( + analysis.instructions["OP_SPECIALIZED"] + ), + ["_RECORD_TOS_TYPE"], + ) + self.assertIn("[OP] = {1, {_RECORD_TOS_INDEX}}", output) + self.assertIn("[OP_SPECIALIZED] = {1, {_RECORD_TOS_INDEX}}", output) + self.assert_slot_map_lines( + output, + "[OP] = {1, 0, {0}}", + "[OP_SPECIALIZED] = {1, 1, {0}}", + ) + + def test_family_head_falls_back_for_missing_member_slots(self): + input = """ + tier2 op(_RECORD_TOS, (value -- value)) { + RECORD_VALUE(value); + } + op(_DO_STUFF, (value -- res)) { + res = value; + } + macro(OP) = _RECORD_TOS + _DO_STUFF; + macro(OP_SPECIALIZED) = _DO_STUFF; + family(OP, INLINE_CACHE_ENTRIES_OP) = { OP_SPECIALIZED }; + """ + output = self.generate_tables(input) + self.assertIn("[OP] = {1, {_RECORD_TOS_INDEX}}", output) + self.assertIn("[OP_SPECIALIZED] = {1, {_RECORD_TOS_INDEX}}", output) + + def test_family_mixed_slots_only_transform_changed_recorders(self): + input = """ + tier2 op(_RECORD_TOS_TYPE, (left, right -- left, right)) { + RECORD_VALUE(Py_TYPE(right)); + } + tier2 op(_RECORD_NOS_TYPE, (left, right -- left, right)) { + RECORD_VALUE(Py_TYPE(left)); + } + tier2 op(_RECORD_NOS, (left, right -- left, right)) { + RECORD_VALUE(left); + } + op(_DO_STUFF, (left, right -- res)) { + res = left; + } + macro(OP) = _RECORD_TOS_TYPE + _RECORD_NOS_TYPE + _DO_STUFF; + macro(OP_SPECIALIZED) = _RECORD_NOS + _DO_STUFF; + family(OP, INLINE_CACHE_ENTRIES_OP) = { OP_SPECIALIZED }; + """ + output = self.generate_tables(input) + self.assertIn("[OP] = {2, {_RECORD_NOS_INDEX, _RECORD_TOS_TYPE_INDEX}}", output) + self.assert_slot_map_lines( + output, + "[OP] = {2, 2, {1, 0}}", + "[OP_SPECIALIZED] = {1, 0, {0}}", + ) class TestGeneratedAbstractCases(unittest.TestCase): def setUp(self) -> None: @@ -2005,8 +2412,8 @@ def test_overridden_abstract_args(self): """ output = """ case OP: { - JitOptSymbol *arg1; - JitOptSymbol *out; + JitOptRef arg1; + JitOptRef out; arg1 = stack_pointer[-1]; out = EGGS(arg1); stack_pointer[-1] = out; @@ -2014,7 +2421,7 @@ def test_overridden_abstract_args(self): } case OP2: { - JitOptSymbol *out; + JitOptRef out; out = sym_new_not_null(ctx); stack_pointer[-1] = out; break; @@ -2039,14 +2446,14 @@ def test_no_overridden_case(self): """ output = """ case OP: { - JitOptSymbol *out; + JitOptRef out; out = sym_new_not_null(ctx); stack_pointer[-1] = out; break; } case OP2: { - JitOptSymbol *out; + JitOptRef out; out = NULL; stack_pointer[-1] = out; break; @@ -2066,9 +2473,631 @@ def test_missing_override_failure(self): """ output = """ """ - with self.assertRaisesRegex(AssertionError, "All abstract uops"): + with self.assertRaisesRegex(ValueError, "All abstract uops"): + self.run_cases_test(input, input2, output) + + def test_validate_uop_input_length_mismatch(self): + input = """ + op(OP, (arg1 -- out)) { + SPAM(); + } + """ + input2 = """ + op(OP, (arg1, arg2 -- out)) { + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Must have the same number of inputs"): + self.run_cases_test(input, input2, output) + + def test_validate_uop_output_length_mismatch(self): + input = """ + op(OP, (arg1 -- out)) { + SPAM(); + } + """ + input2 = """ + op(OP, (arg1 -- out1, out2)) { + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Must have the same number of outputs"): + self.run_cases_test(input, input2, output) + + def test_validate_uop_input_name_mismatch(self): + input = """ + op(OP, (foo -- out)) { + SPAM(); + } + """ + input2 = """ + op(OP, (bar -- out)) { + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Inputs must have equal names"): + self.run_cases_test(input, input2, output) + + def test_validate_uop_output_name_mismatch(self): + input = """ + op(OP, (arg1 -- foo)) { + SPAM(); + } + """ + input2 = """ + op(OP, (arg1 -- bar)) { + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Outputs must have equal names"): + self.run_cases_test(input, input2, output) + + def test_validate_uop_unused_input(self): + input = """ + op(OP, (unused -- )) { + } + """ + input2 = """ + op(OP, (foo -- )) { + } + """ + output = """ + case OP: { + CHECK_STACK_BOUNDS(-1); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + """ + self.run_cases_test(input, input2, output) + + input = """ + op(OP, (foo -- )) { + } + """ + input2 = """ + op(OP, (unused -- )) { + } + """ + output = """ + case OP: { + CHECK_STACK_BOUNDS(-1); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_validate_uop_unused_output(self): + input = """ + op(OP, ( -- unused)) { + } + """ + input2 = """ + op(OP, ( -- foo)) { + foo = NULL; + } + """ + output = """ + case OP: { + JitOptRef foo; + foo = NULL; + CHECK_STACK_BOUNDS(1); + stack_pointer[0] = foo; + stack_pointer += 1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + """ + self.run_cases_test(input, input2, output) + + input = """ + op(OP, ( -- foo)) { + foo = NULL; + } + """ + input2 = """ + op(OP, ( -- unused)) { + } + """ + output = """ + case OP: { + CHECK_STACK_BOUNDS(1); + stack_pointer += 1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_validate_uop_input_size_mismatch(self): + input = """ + op(OP, (arg1[2] -- )) { + } + """ + input2 = """ + op(OP, (arg1[4] -- )) { + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Inputs must have equal sizes"): + self.run_cases_test(input, input2, output) + + def test_validate_uop_output_size_mismatch(self): + input = """ + op(OP, ( -- out[2])) { + } + """ + input2 = """ + op(OP, ( -- out[4])) { + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Outputs must have equal sizes"): + self.run_cases_test(input, input2, output) + + def test_validate_uop_unused_size_mismatch(self): + input = """ + op(OP, (foo[2] -- )) { + } + """ + input2 = """ + op(OP, (unused[4] -- )) { + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Inputs must have equal sizes"): self.run_cases_test(input, input2, output) + def test_pure_uop_body_copied_in(self): + # Note: any non-escaping call works. + # In this case, we use PyStackRef_IsNone. + input = """ + pure op(OP, (foo -- res)) { + res = PyStackRef_IsNone(foo); + } + """ + input2 = """ + op(OP, (foo -- res)) { + REPLACE_OPCODE_IF_EVALUATES_PURE(foo, res); + res = sym_new_known(ctx, foo); + } + """ + output = """ + case OP: { + JitOptRef foo; + JitOptRef res; + foo = stack_pointer[-1]; + if ( + sym_is_safe_const(ctx, foo) + ) { + JitOptRef foo_sym = foo; + _PyStackRef foo = sym_get_const_as_stackref(ctx, foo_sym); + _PyStackRef res_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + res_stackref = PyStackRef_IsNone(foo); + /* End of uop copied from bytecodes for constant evaluation */ + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + stack_pointer[-1] = res; + break; + } + res = sym_new_known(ctx, foo); + stack_pointer[-1] = res; + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_pure_uop_body_copied_in_deopt(self): + # Note: any non-escaping call works. + # In this case, we use PyStackRef_IsNone. + input = """ + pure op(OP, (foo -- res)) { + DEOPT_IF(PyStackRef_IsNull(foo)); + res = foo; + } + """ + input2 = """ + op(OP, (foo -- res)) { + REPLACE_OPCODE_IF_EVALUATES_PURE(foo, res); + res = foo; + } + """ + output = """ + case OP: { + JitOptRef foo; + JitOptRef res; + foo = stack_pointer[-1]; + if ( + sym_is_safe_const(ctx, foo) + ) { + JitOptRef foo_sym = foo; + _PyStackRef foo = sym_get_const_as_stackref(ctx, foo_sym); + _PyStackRef res_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + if (PyStackRef_IsNull(foo)) { + ctx->done = true; + break; + } + res_stackref = foo; + /* End of uop copied from bytecodes for constant evaluation */ + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + stack_pointer[-1] = res; + break; + } + res = foo; + stack_pointer[-1] = res; + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_pure_uop_body_copied_in_error_if(self): + # Note: any non-escaping call works. + # In this case, we use PyStackRef_IsNone. + input = """ + pure op(OP, (foo -- res)) { + ERROR_IF(PyStackRef_IsNull(foo)); + res = foo; + } + """ + input2 = """ + op(OP, (foo -- res)) { + REPLACE_OPCODE_IF_EVALUATES_PURE(foo, res); + res = foo; + } + """ + output = """ + case OP: { + JitOptRef foo; + JitOptRef res; + foo = stack_pointer[-1]; + if ( + sym_is_safe_const(ctx, foo) + ) { + JitOptRef foo_sym = foo; + _PyStackRef foo = sym_get_const_as_stackref(ctx, foo_sym); + _PyStackRef res_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + if (PyStackRef_IsNull(foo)) { + goto error; + } + res_stackref = foo; + /* End of uop copied from bytecodes for constant evaluation */ + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + stack_pointer[-1] = res; + break; + } + res = foo; + stack_pointer[-1] = res; + break; + } + """ + self.run_cases_test(input, input2, output) + + + def test_replace_opcode_uop_body_copied_in_complex(self): + input = """ + pure op(OP, (foo -- res)) { + if (foo) { + res = PyStackRef_IsNone(foo); + } + else { + res = 1; + } + } + """ + input2 = """ + op(OP, (foo -- res)) { + REPLACE_OPCODE_IF_EVALUATES_PURE(foo, res); + res = sym_new_known(ctx, foo); + } + """ + output = """ + case OP: { + JitOptRef foo; + JitOptRef res; + foo = stack_pointer[-1]; + if ( + sym_is_safe_const(ctx, foo) + ) { + JitOptRef foo_sym = foo; + _PyStackRef foo = sym_get_const_as_stackref(ctx, foo_sym); + _PyStackRef res_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + if (foo) { + res_stackref = PyStackRef_IsNone(foo); + } + else { + res_stackref = 1; + } + /* End of uop copied from bytecodes for constant evaluation */ + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + stack_pointer[-1] = res; + break; + } + res = sym_new_known(ctx, foo); + stack_pointer[-1] = res; + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_replace_opcode_escaping_uop_body_copied_in_complex(self): + input = """ + pure op(OP, (foo -- res)) { + if (foo) { + res = ESCAPING_CODE(foo); + } + else { + res = 1; + } + } + """ + input2 = """ + op(OP, (foo -- res)) { + REPLACE_OPCODE_IF_EVALUATES_PURE(foo, res); + res = sym_new_known(ctx, foo); + } + """ + output = """ + case OP: { + JitOptRef foo; + JitOptRef res; + foo = stack_pointer[-1]; + if ( + sym_is_safe_const(ctx, foo) + ) { + JitOptRef foo_sym = foo; + _PyStackRef foo = sym_get_const_as_stackref(ctx, foo_sym); + _PyStackRef res_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + if (foo) { + res_stackref = ESCAPING_CODE(foo); + } + else { + res_stackref = 1; + } + /* End of uop copied from bytecodes for constant evaluation */ + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + stack_pointer[-1] = res; + break; + } + res = sym_new_known(ctx, foo); + stack_pointer[-1] = res; + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_replace_opcode_binop_one_output(self): + input = """ + pure op(OP, (left, right -- res)) { + res = foo(left, right); + } + """ + input2 = """ + op(OP, (left, right -- res)) { + res = sym_new_non_null(ctx, foo); + REPLACE_OPCODE_IF_EVALUATES_PURE(left, right, res); + } + """ + output = """ + case OP: { + JitOptRef right; + JitOptRef left; + JitOptRef res; + right = stack_pointer[-1]; + left = stack_pointer[-2]; + res = sym_new_non_null(ctx, foo); + if ( + sym_is_safe_const(ctx, left) && + sym_is_safe_const(ctx, right) + ) { + JitOptRef left_sym = left; + JitOptRef right_sym = right; + _PyStackRef left = sym_get_const_as_stackref(ctx, left_sym); + _PyStackRef right = sym_get_const_as_stackref(ctx, right_sym); + _PyStackRef res_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + res_stackref = foo(left, right); + /* End of uop copied from bytecodes for constant evaluation */ + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + CHECK_STACK_BOUNDS(-1); + stack_pointer[-2] = res; + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + CHECK_STACK_BOUNDS(-1); + stack_pointer[-2] = res; + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_replace_opcode_binop_one_output_insert(self): + input = """ + pure op(OP, (left, right -- res, l, r)) { + res = foo(left, right); + l = left; + r = right; + } + """ + input2 = """ + op(OP, (left, right -- res, l, r)) { + res = sym_new_non_null(ctx, foo); + l = left; + r = right; + REPLACE_OPCODE_IF_EVALUATES_PURE(left, right, res); + } + """ + output = """ + case OP: { + JitOptRef right; + JitOptRef left; + JitOptRef res; + JitOptRef l; + JitOptRef r; + right = stack_pointer[-1]; + left = stack_pointer[-2]; + res = sym_new_non_null(ctx, foo); + l = left; + r = right; + if ( + sym_is_safe_const(ctx, left) && + sym_is_safe_const(ctx, right) + ) { + JitOptRef left_sym = left; + JitOptRef right_sym = right; + _PyStackRef left = sym_get_const_as_stackref(ctx, left_sym); + _PyStackRef right = sym_get_const_as_stackref(ctx, right_sym); + _PyStackRef res_stackref; + _PyStackRef l_stackref; + _PyStackRef r_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + res_stackref = foo(left, right); + l_stackref = left; + r_stackref = right; + /* End of uop copied from bytecodes for constant evaluation */ + (void)l_stackref; + (void)r_stackref; + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + CHECK_STACK_BOUNDS(1); + stack_pointer[-2] = res; + stack_pointer[-1] = l; + stack_pointer[0] = r; + stack_pointer += 1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + CHECK_STACK_BOUNDS(1); + stack_pointer[-2] = res; + stack_pointer[-1] = l; + stack_pointer[0] = r; + stack_pointer += 1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_replace_opcode_unaryop_one_output_insert(self): + input = """ + pure op(OP, (left -- res, l)) { + res = foo(left); + l = left; + } + """ + input2 = """ + op(OP, (left -- res, l)) { + res = sym_new_non_null(ctx, foo); + l = left; + REPLACE_OPCODE_IF_EVALUATES_PURE(left, res); + } + """ + output = """ + case OP: { + JitOptRef left; + JitOptRef res; + JitOptRef l; + left = stack_pointer[-1]; + res = sym_new_non_null(ctx, foo); + l = left; + if ( + sym_is_safe_const(ctx, left) + ) { + JitOptRef left_sym = left; + _PyStackRef left = sym_get_const_as_stackref(ctx, left_sym); + _PyStackRef res_stackref; + _PyStackRef l_stackref; + /* Start of uop copied from bytecodes for constant evaluation */ + res_stackref = foo(left); + l_stackref = left; + /* End of uop copied from bytecodes for constant evaluation */ + (void)l_stackref; + res = sym_new_const_steal(ctx, PyStackRef_AsPyObjectSteal(res_stackref)); + CHECK_STACK_BOUNDS(1); + stack_pointer[-1] = res; + stack_pointer[0] = l; + stack_pointer += 1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + CHECK_STACK_BOUNDS(1); + stack_pointer[-1] = res; + stack_pointer[0] = l; + stack_pointer += 1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + """ + self.run_cases_test(input, input2, output) + + def test_replace_opocode_uop_reject_array_effects(self): + input = """ + pure op(OP, (foo[2] -- res)) { + if (foo) { + res = PyStackRef_IsNone(foo); + } + else { + res = 1; + } + } + """ + input2 = """ + op(OP, (foo[2] -- res)) { + REPLACE_OPCODE_IF_EVALUATES_PURE(foo, res); + res = sym_new_unknown(ctx); + } + """ + output = """ + """ + with self.assertRaisesRegex(SyntaxError, + "Pure evaluation cannot take array-like inputs"): + self.run_cases_test(input, input2, output) + + def test_overridden_abstract_with_multiple_caches(self): + input = """ + op(OP, (version/1, unused/1, index/1, value -- res)) { + res = SPAM(version, index, value); + } + """ + input2 = """ + op(OP, (value -- res)) { + res = eggs(version, index, value); + } + """ + output = """ + case OP: { + JitOptRef value; + JitOptRef res; + value = stack_pointer[-1]; + uint16_t version = (uint16_t)this_instr->operand0; + uint16_t index = (uint16_t)this_instr->operand1; + res = eggs(version, index, value); + stack_pointer[-1] = res; + break; + } + """ + self.run_cases_test(input, input2, output) if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_generators.py b/Lib/test/test_generators.py index 037c1bed5fe..6eb25960101 100644 --- a/Lib/test/test_generators.py +++ b/Lib/test/test_generators.py @@ -300,7 +300,7 @@ class C: def __iter__(self): return Iterator() - self.assertEqual([1, 2], list(i for i in C())) + self.assertEqual([1,2], list(i for i in C())) def test_close_clears_frame(self): # gh-142766: Test that closing a generator clears its frame @@ -357,26 +357,25 @@ def gen(it): yield x return gen(range(10)) - def process_tests(self, get_generator, is_expr): - err_iterator = "'.*' object is not an iterator" - err_iterable = "'.*' object is not iterable" - for obj in self.iterables: - g_obj = get_generator(obj) - with self.subTest(g_obj=g_obj, obj=obj): - if is_expr: - self.assertRaisesRegex(TypeError, err_iterator, list, g_obj) - else: + def process_tests(self, get_generator, changes_iterable): + if changes_iterable: + for obj in self.iterables: + g_obj = get_generator(obj) + with self.subTest(g_obj=g_obj, obj=obj): self.assertListEqual(list(g_obj), list(obj)) - g_iter = get_generator(iter(obj)) - with self.subTest(g_iter=g_iter, obj=obj): - self.assertListEqual(list(g_iter), list(obj)) + g_iter = get_generator(iter(obj)) + with self.subTest(g_iter=g_iter, obj=obj): + self.assertListEqual(list(g_iter), list(obj)) + err_regex = "'.*' object is not iterable" for obj in self.non_iterables: g_obj = get_generator(obj) with self.subTest(g_obj=g_obj): - err = err_iterator if is_expr else err_iterable - self.assertRaisesRegex(TypeError, err, list, g_obj) + if changes_iterable: + self.assertRaisesRegex(TypeError, err_regex, list, g_obj) + else: + next(g_obj) def test_modify_f_locals(self): def modify_f_locals(g, local, obj): @@ -389,22 +388,22 @@ def get_generator_genexpr(obj): def get_generator_genfunc(obj): return modify_f_locals(self.genfunc(), 'it', obj) - self.process_tests(get_generator_genexpr, True) - self.process_tests(get_generator_genfunc, False) + self.process_tests(get_generator_genexpr, False) + self.process_tests(get_generator_genfunc, True) def test_new_gen_from_gi_code(self): def new_gen_from_gi_code(g, obj): generator_func = types.FunctionType(g.gi_code, {}) return generator_func(obj) - def get_generator_genexpr(obj): - return new_gen_from_gi_code(self.genexpr(), obj) + for obj in self.non_iterables: + with self.assertRaises(TypeError): + new_gen_from_gi_code(self.genexpr(), obj) def get_generator_genfunc(obj): return new_gen_from_gi_code(self.genfunc(), obj) - self.process_tests(get_generator_genexpr, True) - self.process_tests(get_generator_genfunc, False) + self.process_tests(get_generator_genfunc, True) class ExceptionTest(unittest.TestCase): @@ -1367,7 +1366,7 @@ def b(): >>> type(i) >>> [s for s in dir(i) if not s.startswith('_')] -['close', 'gi_code', 'gi_frame', 'gi_running', 'gi_suspended', 'gi_yieldfrom', 'send', 'throw'] +['close', 'gi_code', 'gi_frame', 'gi_running', 'gi_state', 'gi_suspended', 'gi_yieldfrom', 'send', 'throw'] >>> from test.support import HAVE_DOCSTRINGS >>> print(i.__next__.__doc__ if HAVE_DOCSTRINGS else 'Implement next(self).') Implement next(self). @@ -2878,8 +2877,7 @@ def printsolution(self, x): } def load_tests(loader, tests, pattern): - from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON - tests.addTest(doctest.DocTestSuite(checker=DocTestChecker())) # TODO: RUSTPYTHON + tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_genericalias.py b/Lib/test/test_genericalias.py index 121d169dd07..7816775620b 100644 --- a/Lib/test/test_genericalias.py +++ b/Lib/test/test_genericalias.py @@ -17,7 +17,7 @@ from functools import partial, partialmethod, cached_property from graphlib import TopologicalSorter from logging import LoggerAdapter, StreamHandler -from mailbox import Mailbox, _PartialFile +from mailbox import Mailbox try: import ctypes except ImportError: @@ -100,7 +100,9 @@ class BaseTest(unittest.TestCase): """Test basics.""" - generic_types = [type, tuple, list, dict, set, frozenset, enumerate, memoryview, + generic_types = [type, tuple, list, dict, frozendict, + set, frozenset, enumerate, memoryview, + slice, defaultdict, deque, SequenceMatcher, dircmp, @@ -116,7 +118,7 @@ class BaseTest(unittest.TestCase): Iterable, Iterator, Reversible, Container, Collection, - Mailbox, _PartialFile, + Mailbox, ContextVar, Token, Field, Set, MutableSet, diff --git a/Lib/test/test_genericpath.py b/Lib/test/test_genericpath.py index 1a44cedcd36..10d3f409d88 100644 --- a/Lib/test/test_genericpath.py +++ b/Lib/test/test_genericpath.py @@ -2,8 +2,10 @@ Tests common to genericpath, ntpath and posixpath """ +import copy import genericpath import os +import pickle import sys import unittest import warnings @@ -32,6 +34,10 @@ def test_no_argument(self): .format(self.pathmodule.__name__, attr)) def test_commonprefix(self): + with warnings_helper.check_warnings((".*commonpath().*", DeprecationWarning)): + self.do_test_commonprefix() + + def do_test_commonprefix(self): commonprefix = self.pathmodule.commonprefix self.assertEqual( commonprefix([]), @@ -320,6 +326,21 @@ def test_sameopenfile(self): fd2 = fp2.fileno() self.assertTrue(self.pathmodule.sameopenfile(fd1, fd2)) + def test_realpath_mode_values(self): + for name in 'ALL_BUT_LAST', 'ALLOW_MISSING': + with self.subTest(name): + mode = getattr(self.pathmodule, name) + self.assertEqual(repr(mode), 'os.path.' + name) + self.assertEqual(str(mode), 'os.path.' + name) + self.assertTrue(mode) + self.assertIs(copy.copy(mode), mode) + self.assertIs(copy.deepcopy(mode), mode) + for proto in range(pickle.HIGHEST_PROTOCOL+1): + with self.subTest(protocol=proto): + pickled = pickle.dumps(mode, proto) + unpickled = pickle.loads(pickled) + self.assertIs(unpickled, mode) + class TestGenericTest(GenericTest, unittest.TestCase): # Issue 16852: GenericTest can't inherit from unittest.TestCase @@ -589,8 +610,9 @@ def test_path_isdir(self): self.assertPathEqual(os.path.isdir) def test_path_commonprefix(self): - self.assertEqual(os.path.commonprefix([self.file_path, self.file_name]), - self.file_name) + with warnings_helper.check_warnings((".*commonpath().*", DeprecationWarning)): + self.assertEqual(os.path.commonprefix([self.file_path, self.file_name]), + self.file_name) def test_path_getsize(self): self.assertPathEqual(os.path.getsize) diff --git a/Lib/test/test_genexps.py b/Lib/test/test_genexps.py index 685e3efffe6..fe5f18fa3f8 100644 --- a/Lib/test/test_genexps.py +++ b/Lib/test/test_genexps.py @@ -131,14 +131,6 @@ >>> list(g) [1, 9, 25, 49, 81] -Verify that the outermost for-expression makes an immediate check -for iterability - >>> (i for i in 6) - Traceback (most recent call last): - File "", line 1, in -toplevel- - (i for i in 6) - TypeError: 'int' object is not iterable - Verify late binding for the innermost for-expression >>> g = ((i,j) for i in range(3) for j in range(x)) @@ -285,8 +277,7 @@ __test__ = {'doctests' : doctests} def load_tests(loader, tests, pattern): - from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON - tests.addTest(doctest.DocTestSuite(checker=DocTestChecker())) # TODO: RUSTPYTHON + tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_getpass.py b/Lib/test/test_getpass.py index 9c3def2c3be..272414a6204 100644 --- a/Lib/test/test_getpass.py +++ b/Lib/test/test_getpass.py @@ -88,6 +88,147 @@ def test_trims_trailing_newline(self): input = StringIO('test\n') self.assertEqual('test', getpass._raw_input(input=input)) + def check_raw_input(self, inputs, expect_result, prompt='Password: '): + mock_input = StringIO(inputs) + mock_output = StringIO() + result = getpass._raw_input(prompt, mock_output, mock_input, '*') + self.assertEqual(result, expect_result) + return mock_output.getvalue() + + def test_null_char(self): + self.check_raw_input('pass\x00word\n', 'password') + + def test_raw_input_with_echo_char(self): + output = self.check_raw_input('my1pa$$word!\n', 'my1pa$$word!') + self.assertEqual('Password: ************', output) + + def test_control_chars_with_echo_char(self): + output = self.check_raw_input('pass\twd\b\n', 'pass\tw') + # After backspace: refresh rewrites prompt + 6 echo chars + self.assertEqual( + 'Password: *******' # initial prompt + 7 echo chars + '\r' + ' ' * 17 + '\r' # clear line (10 prompt + 7 prev) + 'Password: ******', # rewrite prompt + 6 echo chars + output + ) + + def test_kill_ctrl_u_with_echo_char(self): + # Ctrl+U (KILL) should clear the entire line + output = self.check_raw_input('foo\x15bar\n', 'bar') + # Should show "***" then refresh to clear, then show "***" for "bar" + self.assertIn('***', output) + # Display refresh uses \r to rewrite the line including prompt + self.assertIn('\r', output) + + def test_werase_ctrl_w_with_echo_char(self): + # Ctrl+W (WERASE) should delete the previous word + self.check_raw_input('hello world\x17end\n', 'hello end') + + def test_ctrl_w_display_preserves_prompt(self): + # Reproducer from gh-138577: type "hello world", Ctrl+W + # Display must show "Password: ******" not "******rd: ***********" + output = self.check_raw_input('hello world\x17\n', 'hello ') + # The final visible state should be "Password: ******" + # Verify prompt is rewritten during refresh, not overwritten by stars + self.assertEndsWith(output, 'Password: ******') + + def test_ctrl_a_insert_display_preserves_prompt(self): + # Reproducer from gh-138577: type "abc", Ctrl+A, type "x" + # Display must show "Password: ****" not "****word: ***" + output = self.check_raw_input('abc\x01x\n', 'xabc') + # The final visible state should be "Password: ****" + self.assertEndsWith(output, 'Password: ****\x08\x08\x08') + + def test_lnext_ctrl_v_with_echo_char(self): + # Ctrl+V (LNEXT) should insert the next character literally + self.check_raw_input('test\x16\x15more\n', 'test\x15more') + + def test_ctrl_a_move_to_start_with_echo_char(self): + # Ctrl+A should move cursor to start + self.check_raw_input('end\x01start\n', 'startend') + + def test_ctrl_a_cursor_position(self): + # After Ctrl+A, cursor is at position 0. + # Refresh writes backspaces to move cursor from end to start. + output = self.check_raw_input('abc\x01\n', 'abc') + self.assertEndsWith(output, 'Password: ***\x08\x08\x08') + + def test_ctrl_a_on_empty(self): + # Ctrl+A on empty line should be a no-op + self.check_raw_input('\x01hello\n', 'hello') + + def test_ctrl_a_already_at_start(self): + # Double Ctrl+A should be same as single Ctrl+A + self.check_raw_input('abc\x01\x01start\n', 'startabc') + + def test_ctrl_a_then_backspace(self): + # Backspace after Ctrl+A should do nothing (cursor at 0) + self.check_raw_input('abc\x01\x7f\n', 'abc') + + def test_ctrl_e_move_to_end_with_echo_char(self): + # Ctrl+E should move cursor to end + self.check_raw_input('start\x01X\x05end\n', 'Xstartend') + + def test_ctrl_e_cursor_position(self): + # After Ctrl+A then Ctrl+E, cursor is back at end. + # Refresh has no backspaces since cursor is at end. + output = self.check_raw_input('abc\x01\x05\n', 'abc') + self.assertEndsWith(output, 'Password: ***') + + def test_ctrl_e_on_empty(self): + # Ctrl+E on empty line should be a no-op + self.check_raw_input('\x05hello\n', 'hello') + + def test_ctrl_e_already_at_end(self): + # Ctrl+E when already at end should be a no-op + self.check_raw_input('abc\x05more\n', 'abcmore') + + def test_ctrl_a_then_ctrl_e(self): + # Ctrl+A then Ctrl+E should return cursor to end, typing appends + self.check_raw_input('abc\x01\x05def\n', 'abcdef') + + def test_ctrl_k_kill_forward_with_echo_char(self): + # Ctrl+K should kill from cursor to end + self.check_raw_input('delete\x01\x0bkeep\n', 'keep') + + def test_ctrl_c_interrupt_with_echo_char(self): + # Ctrl+C should raise KeyboardInterrupt + with self.assertRaises(KeyboardInterrupt): + self.check_raw_input('test\x03more', '') + + def test_ctrl_d_eof_with_echo_char(self): + # Ctrl+D twice should cause EOF + self.check_raw_input('test\x04\x04', 'test') + + def test_backspace_at_start_with_echo_char(self): + # Backspace at start should do nothing + self.check_raw_input('\x7fhello\n', 'hello') + + def test_ctrl_k_at_end_with_echo_char(self): + # Ctrl+K at end should do nothing + self.check_raw_input('hello\x0b\n', 'hello') + + def test_ctrl_w_on_empty_with_echo_char(self): + # Ctrl+W on empty line should do nothing + self.check_raw_input('\x17hello\n', 'hello') + + def test_ctrl_u_on_empty_with_echo_char(self): + # Ctrl+U on empty line should do nothing + self.check_raw_input('\x15hello\n', 'hello') + + def test_multiple_ctrl_operations_with_echo_char(self): + # Test combination: type, move, insert, delete + # "world", Ctrl+A, "hello ", Ctrl+E, "!", Ctrl+A, Ctrl+K, "start" + self.check_raw_input('world\x01hello \x05!\x01\x0bstart\n', 'start') + + def test_ctrl_w_multiple_words_with_echo_char(self): + # Ctrl+W should delete only the last word + self.check_raw_input('one two three\x17\n', 'one two ') + + def test_ctrl_v_then_ctrl_c_with_echo_char(self): + # Ctrl+V should make Ctrl+C literal (not interrupt) + self.check_raw_input('test\x16\x03end\n', 'test\x03end') + # Some of these tests are a bit white-box. The functional requirement is that # the password input be taken directly from the tty, and that it not be echoed @@ -174,33 +315,10 @@ def test_echo_char_replaces_input_with_asterisks(self): result = getpass.unix_getpass(echo_char='*') mock_input.assert_called_once_with('Password: ', textio(), - input=textio(), echo_char='*') + input=textio(), echo_char='*', + term_ctrl_chars=mock.ANY) self.assertEqual(result, mock_result) - def test_raw_input_with_echo_char(self): - passwd = 'my1pa$$word!' - mock_input = StringIO(f'{passwd}\n') - mock_output = StringIO() - with mock.patch('sys.stdin', mock_input), \ - mock.patch('sys.stdout', mock_output): - result = getpass._raw_input('Password: ', mock_output, mock_input, - '*') - self.assertEqual(result, passwd) - self.assertEqual('Password: ************', mock_output.getvalue()) - - def test_control_chars_with_echo_char(self): - passwd = 'pass\twd\b' - expect_result = 'pass\tw' - mock_input = StringIO(f'{passwd}\n') - mock_output = StringIO() - with mock.patch('sys.stdin', mock_input), \ - mock.patch('sys.stdout', mock_output): - result = getpass._raw_input('Password: ', mock_output, mock_input, - '*') - self.assertEqual(result, expect_result) - self.assertEqual('Password: *******\x08 \x08', mock_output.getvalue()) - - class GetpassEchoCharTest(unittest.TestCase): def test_accept_none(self): diff --git a/Lib/test/test_gettext.py b/Lib/test/test_gettext.py index 9ad37909a8e..b18489f34ae 100644 --- a/Lib/test/test_gettext.py +++ b/Lib/test/test_gettext.py @@ -613,6 +613,23 @@ def test_negation(self): self.assertEqual(f(1), 0) self.assertEqual(f(2), 0) + def test_negation_precedence(self): + # gh-157451: in C the unary '!' binds tighter than any binary + # operator, so '!n + 1' is '(!n) + 1', not '!(n + 1)'. + f = gettext.c2py('!n + 1') + self.assertEqual(f(0), 2) + self.assertEqual(f(1), 1) + self.assertEqual(gettext.c2py('!n < 3')(0), 1) + self.assertEqual(gettext.c2py('!n * 2')(0), 2) + self.assertEqual(gettext.c2py('!n * 2')(1), 0) + # Double negation still normalises to 0/1 (C semantics). + self.assertEqual(gettext.c2py('!!n')(5), 1) + self.assertEqual(gettext.c2py('!!n')(0), 0) + # '!' as a right operand also binds tighter than the binary operator, + # so '2 * !n + 1' is '2 * (!n) + 1' rather than a SyntaxError. + self.assertEqual(gettext.c2py('2 * !n + 1')(0), 3) + self.assertEqual(gettext.c2py('2 * !n + 1')(1), 1) + def test_nested_condition_operator(self): self.assertEqual(gettext.c2py('n?1?2:3:4')(0), 4) self.assertEqual(gettext.c2py('n?1?2:3:4')(1), 2) diff --git a/Lib/test/test_glob.py b/Lib/test/test_glob.py index d0ed5129253..9e4e82b2542 100644 --- a/Lib/test/test_glob.py +++ b/Lib/test/test_glob.py @@ -4,7 +4,6 @@ import shutil import sys import unittest -import warnings from test.support import is_wasi, Py_DEBUG from test.support.os_helper import (TESTFN, skip_unless_symlink, @@ -393,36 +392,6 @@ def test_glob_many_open_files(self): for it in iters: self.assertEqual(next(it), p) - def test_glob0(self): - with self.assertWarns(DeprecationWarning): - glob.glob0(self.tempdir, 'a') - - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - eq = self.assertSequencesEqual_noorder - eq(glob.glob0(self.tempdir, 'a'), ['a']) - eq(glob.glob0(self.tempdir, '.bb'), ['.bb']) - eq(glob.glob0(self.tempdir, '.b*'), []) - eq(glob.glob0(self.tempdir, 'b'), []) - eq(glob.glob0(self.tempdir, '?'), []) - eq(glob.glob0(self.tempdir, '*a'), []) - eq(glob.glob0(self.tempdir, 'a*'), []) - - def test_glob1(self): - with self.assertWarns(DeprecationWarning): - glob.glob1(self.tempdir, 'a') - - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - eq = self.assertSequencesEqual_noorder - eq(glob.glob1(self.tempdir, 'a'), ['a']) - eq(glob.glob1(self.tempdir, '.bb'), ['.bb']) - eq(glob.glob1(self.tempdir, '.b*'), ['.bb']) - eq(glob.glob1(self.tempdir, 'b'), []) - eq(glob.glob1(self.tempdir, '?'), ['a']) - eq(glob.glob1(self.tempdir, '*a'), ['a', 'aaa']) - eq(glob.glob1(self.tempdir, 'a*'), ['a', 'aaa', 'aab']) - def test_translate_matching(self): match = re.compile(glob.translate('*')).match self.assertIsNotNone(match('foo')) diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py index cfb24a5c457..ebcd98a0a37 100644 --- a/Lib/test/test_grammar.py +++ b/Lib/test/test_grammar.py @@ -1,8 +1,6 @@ # Python test set -- part 1, grammar. # This just tests whether the parser accepts them all. -from test.support import check_syntax_error, skip_wasi_stack_overflow -from test.support import import_helper import annotationlib import inspect import unittest @@ -18,6 +16,12 @@ import typing from test.typinganndata import ann_module2 import test +from test.support import ( + check_syntax_error, + import_helper, + skip_emscripten_stack_overflow, + skip_wasi_stack_overflow, +) from test.support.numbers import ( VALID_UNDERSCORE_LITERALS, INVALID_UNDERSCORE_LITERALS, @@ -250,6 +254,7 @@ def test_eof_error(self): self.assertIn("was never closed", str(cm.exception)) @skip_wasi_stack_overflow() + @skip_emscripten_stack_overflow() def test_max_level(self): # Macro defined in Parser/lexer/state.h MAXLEVEL = 200 diff --git a/Lib/test/test_grp.py b/Lib/test/test_grp.py index 289228924c7..ed86802f069 100644 --- a/Lib/test/test_grp.py +++ b/Lib/test/test_grp.py @@ -49,7 +49,6 @@ def test_values_extended(self): # Discovered on Ubuntu 5.04 (custom). self.assertEqual(e2.gr_name.lower(), name.lower()) - @unittest.expectedFailure # TODO: RUSTPYTHON; KeyError: 'getgrgid: group id 340282366920938463463374607431768211456 not found' def test_errors(self): self.assertRaises(TypeError, grp.getgrgid) self.assertRaises(TypeError, grp.getgrgid, 3.14) diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py index ccbacc7c19b..cafac9d3c8b 100644 --- a/Lib/test/test_gzip.py +++ b/Lib/test/test_gzip.py @@ -9,10 +9,10 @@ import struct import sys import unittest -import warnings from subprocess import PIPE, Popen +from unittest import mock from test.support import catch_unraisable_exception -from test.support import import_helper +from test.support import force_not_colorized_test_class, import_helper from test.support import os_helper from test.support import _4G, bigmemtest, requires_subprocess from test.support.script_helper import assert_python_ok, assert_python_failure @@ -351,10 +351,30 @@ def test_mtime(self): self.assertEqual(dataRead, data1) self.assertEqual(fRead.mtime, mtime) + def test_mtime_out_of_range(self): + for mtime in (-1, 2**32): + with gzip.GzipFile(self.filename, 'w', mtime=mtime) as fWrite: + fWrite.write(data1) + with gzip.GzipFile(self.filename) as fRead: + fRead.read(1) + self.assertEqual(fRead.mtime, 0) + datac = gzip.compress(data1, mtime=mtime) + with gzip.GzipFile(fileobj=io.BytesIO(datac)) as fRead: + fRead.read(1) + self.assertEqual(fRead.mtime, 0) + + for mtime in (-1, 2**32): + with mock.patch('time.time', return_value=float(mtime)): + with gzip.GzipFile(self.filename, 'w') as fWrite: + fWrite.write(data1) + with gzip.GzipFile(self.filename) as fRead: + fRead.read(1) + self.assertEqual(fRead.mtime, 0) + def test_metadata(self): mtime = 123456789 - with gzip.GzipFile(self.filename, 'w', mtime = mtime) as fWrite: + with gzip.GzipFile(self.filename, 'w', mtime = mtime, compresslevel = 9) as fWrite: fWrite.write(data1) with open(self.filename, 'rb') as fRead: @@ -640,7 +660,7 @@ def test_fileobj_mode(self): with open(self.filename, mode) as f: with gzip.GzipFile(fileobj=f) as g: self.assertEqual(g.mode, gzip.READ) - for mode in "wb", "ab", "xb": + for mode in "wb", "ab", "xb", "wb+", "ab+", "xb+": if "x" in mode: os_helper.unlink(self.filename) with open(self.filename, mode) as f: @@ -796,6 +816,35 @@ def test_decompress_missing_trailer(self): compressed_data = gzip.compress(data1) self.assertRaises(EOFError, gzip.decompress, compressed_data[:-8]) + def test_truncated_header(self): + truncated_headers = [ + b"\x1f\x8b\x08\x00\x00\x00\x00\x00\x00", # Missing OS byte + b"\x1f\x8b\x08\x02\x00\x00\x00\x00\x00\xff", # FHRC, but no checksum + b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff", # FEXTRA, but no xlen + b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\xaa\x00", # FEXTRA, xlen, but no data + b"\x1f\x8b\x08\x08\x00\x00\x00\x00\x00\xff", # FNAME but no fname + b"\x1f\x8b\x08\x10\x00\x00\x00\x00\x00\xff", # FCOMMENT, but no fcomment + ] + for header in truncated_headers: + with self.subTest(header=header): + with self.assertRaises(EOFError): + gzip.decompress(header) + + def test_corrupted_gzip_header(self): + header = (b"\x1f\x8b\x08\x1f\x00\x00\x00\x00\x00\xff" # All flags set + b"\x05\x00" # Xlen = 5 + b"extra" + b"name\x00" + b"comment\x00") + true_crc = zlib.crc32(header) & 0xFFFF + corrupted_crc = true_crc ^ 0xFFFF + corrupted_header = header + corrupted_crc.to_bytes(2, "little") + with self.assertRaises(gzip.BadGzipFile) as err: + gzip.decompress(corrupted_header) + self.assertEqual(str(err.exception), + f"Corrupted gzip header. Checksums do not " + f"match: {true_crc:04x} != {corrupted_crc:04x}") + def test_read_truncated(self): data = data1*50 # Drop the CRC (4 bytes) and file size (4 bytes). @@ -1058,6 +1107,7 @@ def wrapper(*args, **kwargs): return decorator +@force_not_colorized_test_class class TestCommandLine(unittest.TestCase): data = b'This is a simple test with gzip' diff --git a/Lib/test/test_hash.py b/Lib/test/test_hash.py index 11c43ccee19..cf9db66a29a 100644 --- a/Lib/test/test_hash.py +++ b/Lib/test/test_hash.py @@ -263,7 +263,6 @@ def get_expected_hash(self, position, length): platform = 3 if IS_64BIT else 2 return self.known_hashes[algorithm][position][platform] - @unittest.expectedFailure # TODO: RUSTPYTHON def test_null_hash(self): # PYTHONHASHSEED=0 disables the randomized hash known_hash_of_obj = self.get_expected_hash(0, 3) @@ -274,7 +273,6 @@ def test_null_hash(self): # It can also be disabled by setting the seed to 0: self.assertEqual(self.get_hash(self.repr_, seed=0), known_hash_of_obj) - @unittest.expectedFailure # TODO: RUSTPYTHON @skip_unless_internalhash def test_fixed_hash(self): # test a fixed seed for the randomized hash @@ -282,7 +280,6 @@ def test_fixed_hash(self): h = self.get_expected_hash(1, 3) self.assertEqual(self.get_hash(self.repr_, seed=42), h) - @unittest.expectedFailure # TODO: RUSTPYTHON @skip_unless_internalhash def test_long_fixed_hash(self): if self.repr_long is None: @@ -301,7 +298,6 @@ class StrHashRandomizationTests(StringlikeHashRandomizationTests, def test_empty_string(self): self.assertEqual(hash(""), 0) - @unittest.expectedFailure # TODO: RUSTPYTHON @skip_unless_internalhash def test_ucs2_string(self): h = self.get_expected_hash(3, 6) diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py index 6652b829b5a..b511c160c92 100644 --- a/Lib/test/test_hashlib.py +++ b/Lib/test/test_hashlib.py @@ -18,7 +18,8 @@ import tempfile import threading import unittest -import warnings +from functools import partial +from operator import attrgetter from test import support from test.support import _4G, bigmemtest from test.support import hashlib_helper @@ -53,18 +54,39 @@ def get_fips_mode(): return 0 + +try: + import _md5 +except ImportError: + _md5 = None +requires_md5 = unittest.skipUnless(_md5, 'requires _md5') + + try: import _blake2 except ImportError: _blake2 = None - requires_blake2 = unittest.skipUnless(_blake2, 'requires _blake2') + +try: + import _sha1 +except ImportError: + _sha1 = None +requires_sha1 = unittest.skipUnless(_sha1, 'requires _sha1') + + +try: + import _sha2 +except ImportError: + _sha2 = None +requires_sha2 = unittest.skipUnless(_sha2, 'requires _sha2') + + try: import _sha3 except ImportError: _sha3 = None - requires_sha3 = unittest.skipUnless(_sha3, 'requires _sha3') @@ -95,6 +117,14 @@ def read_vectors(hash_name): yield parts +DEPRECATED_STRING_PARAMETER = re.escape( + "the 'string' keyword parameter is deprecated since " + "Python 3.15 and slated for removal in Python 3.19; " + "use the 'data' keyword parameter or pass the data " + "to hash as a positional argument instead" +) + + class HashLibTestCase(unittest.TestCase): supported_hash_names = ( 'md5', 'MD5', 'sha1', 'SHA1', 'sha224', 'SHA224', 'sha256', 'SHA256', @@ -199,6 +229,11 @@ def hash_constructors(self): constructors = self.constructors_to_test.values() return itertools.chain.from_iterable(constructors) + @property + def shake_constructors(self): + for shake_name in self.shakes: + yield from self.constructors_to_test.get(shake_name, ()) + @property def is_fips_mode(self): return get_fips_mode() @@ -260,22 +295,27 @@ def test_clinic_signature(self): with self.subTest(constructor.__name__): constructor(b'') constructor(data=b'') - constructor(string=b'') # should be deprecated in the future + with self.assertWarnsRegex(DeprecationWarning, + DEPRECATED_STRING_PARAMETER): + constructor(string=b'') digest_name = constructor(b'').name with self.subTest(digest_name): hashlib.new(digest_name, b'') hashlib.new(digest_name, data=b'') - hashlib.new(digest_name, string=b'') + with self.assertWarnsRegex(DeprecationWarning, + DEPRECATED_STRING_PARAMETER): + hashlib.new(digest_name, string=b'') # Make sure that _hashlib contains the constructor # to test when using a combination of libcrypto and # interned hash implementations. if self._hashlib and digest_name in self._hashlib._constructors: self._hashlib.new(digest_name, b'') self._hashlib.new(digest_name, data=b'') - self._hashlib.new(digest_name, string=b'') + with self.assertWarnsRegex(DeprecationWarning, + DEPRECATED_STRING_PARAMETER): + self._hashlib.new(digest_name, string=b'') - @unittest.expectedFailure # TODO: RUSTPYTHON; duplicate positional/keyword arg error message differs @unittest.skipIf(get_fips_mode(), "skip in FIPS mode") def test_clinic_signature_errors(self): nomsg = b'' @@ -330,7 +370,9 @@ def test_clinic_signature_errors(self): def test_unknown_hash(self): self.assertRaises(ValueError, hashlib.new, 'spam spam spam spam spam') - self.assertRaises(TypeError, hashlib.new, 1) + # ensure that the exception message remains consistent + err = re.escape("new() argument 'name' must be str, not int") + self.assertRaisesRegex(TypeError, err, hashlib.new, 1) def test_new_upper_to_lower(self): self.assertEqual(hashlib.new("SHA256").name, "sha256") @@ -357,11 +399,23 @@ def test_get_builtin_constructor(self): sys.modules['_md5'] = _md5 else: del sys.modules['_md5'] - self.assertRaises(TypeError, get_builtin_constructor, 3) + # ensure that the exception message remains consistent + err = re.escape("new() argument 'name' must be str, not int") + self.assertRaises(TypeError, err, get_builtin_constructor, 3) constructor = get_builtin_constructor('md5') self.assertIs(constructor, _md5.md5) self.assertEqual(sorted(builtin_constructor_cache), ['MD5', 'md5']) + def test_copy(self): + for cons in self.hash_constructors: + h1 = cons(os.urandom(16), usedforsecurity=False) + h2 = h1.copy() + self.assertIs(type(h1), type(h2)) + self.assertEqual(h1.name, h2.name) + size = (16,) if h1.name in self.shakes else () + self.assertEqual(h1.digest(*size), h2.digest(*size)) + self.assertEqual(h1.hexdigest(*size), h2.hexdigest(*size)) + def test_hexdigest(self): for cons in self.hash_constructors: h = cons(usedforsecurity=False) @@ -372,21 +426,50 @@ def test_hexdigest(self): self.assertIsInstance(h.digest(), bytes) self.assertEqual(hexstr(h.digest()), h.hexdigest()) - def test_digest_length_overflow(self): - # See issue #34922 - large_sizes = (2**29, 2**32-10, 2**32+10, 2**61, 2**64-10, 2**64+10) - for cons in self.hash_constructors: - h = cons(usedforsecurity=False) - if h.name not in self.shakes: - continue - if HASH is not None and isinstance(h, HASH): - # _hashopenssl's take a size_t - continue - for digest in h.digest, h.hexdigest: - self.assertRaises(ValueError, digest, -10) - for length in large_sizes: - with self.assertRaises((ValueError, OverflowError)): - digest(length) + def test_shakes_zero_digest_length(self): + for constructor in self.shake_constructors: + with self.subTest(constructor=constructor): + h = constructor(b'abcdef', usedforsecurity=False) + self.assertEqual(h.digest(0), b'') + self.assertEqual(h.hexdigest(0), '') + + def test_shakes_invalid_digest_length(self): + # See https://github.com/python/cpython/issues/79103. + for constructor in self.shake_constructors: + with self.subTest(constructor=constructor): + h = constructor(usedforsecurity=False) + # Note: digest() and hexdigest() take a signed input and + # raise if it is negative; the rationale is that we use + # internally PyBytes_FromStringAndSize() and _Py_strhex() + # which both take a Py_ssize_t. + for negative_size in (-1, -10, -(1 << 31), -sys.maxsize): + self.assertRaises(ValueError, h.digest, negative_size) + self.assertRaises(ValueError, h.hexdigest, negative_size) + + def test_shakes_overflow_digest_length(self): + # See https://github.com/python/cpython/issues/135759. + + exc_types = (OverflowError, ValueError) + # HACL* accepts an 'uint32_t' while OpenSSL accepts a 'size_t'. + openssl_overflown_sizes = (sys.maxsize + 1, 2 * sys.maxsize) + # https://github.com/python/cpython/issues/79103 restricts + # the accepted built-in lengths to 2 ** 29, even if OpenSSL + # accepts such lengths. + builtin_overflown_sizes = openssl_overflown_sizes + ( + 2 ** 29, 2 ** 32 - 10, 2 ** 32, 2 ** 32 + 10, + 2 ** 61, 2 ** 64 - 10, 2 ** 64, 2 ** 64 + 10, + ) + + for constructor in self.shake_constructors: + with self.subTest(constructor=constructor): + h = constructor(usedforsecurity=False) + if HASH is not None and isinstance(h, HASH): + overflown_sizes = openssl_overflown_sizes + else: + overflown_sizes = builtin_overflown_sizes + for invalid_size in overflown_sizes: + self.assertRaises(exc_types, h.digest, invalid_size) + self.assertRaises(exc_types, h.hexdigest, invalid_size) def test_name_attribute(self): for cons in self.hash_constructors: @@ -490,13 +573,17 @@ def check(self, name, data, hexdigest, shake=False, **kwargs): def check_file_digest(self, name, data, hexdigest): hexdigest = hexdigest.lower() - try: - hashlib.new(name) - except ValueError: - # skip, algorithm is blocked by security policy. - return - digests = [name] - digests.extend(self.constructors_to_test[name]) + digests = [] + for digest in [name, *self.constructors_to_test[name]]: + try: + if callable(digest): + digest(b"") + else: + hashlib.new(digest) + except ValueError: + # skip, algorithm is blocked by security policy. + continue + digests.append(digest) with tempfile.TemporaryFile() as f: f.write(data) @@ -627,12 +714,12 @@ def test_case_md5_2(self): ) @unittest.skipIf(sys.maxsize < _4G + 5, 'test cannot run on 32-bit systems') - @bigmemtest(size=_4G + 5, memuse=1, dry_run=False) + @bigmemtest(size=_4G + 5, memuse=2, dry_run=False) def test_case_md5_huge(self, size): self.check('md5', b'A'*size, 'c9af2dff37468ce5dfee8f2cfc0a9c6d') @unittest.skipIf(sys.maxsize < _4G - 1, 'test cannot run on 32-bit systems') - @bigmemtest(size=_4G - 1, memuse=1, dry_run=False) + @bigmemtest(size=_4G - 1, memuse=2, dry_run=False) def test_case_md5_uintmax(self, size): self.check('md5', b'A'*size, '28138d306ff1b8281f1a9067e1a1a2b3') @@ -1017,49 +1104,73 @@ def test_gil(self): def test_sha256_gil(self): gil_minsize = hashlib_helper.find_gil_minsize(['_sha2', '_hashlib']) + data = b'1' + b'#' * gil_minsize + b'1' + expected = hashlib.sha256(data).hexdigest() + m = hashlib.sha256() m.update(b'1') m.update(b'#' * gil_minsize) m.update(b'1') - self.assertEqual( - m.hexdigest(), - '1cfceca95989f51f658e3f3ffe7f1cd43726c9e088c13ee10b46f57cef135b94' - ) + self.assertEqual(m.hexdigest(), expected) - m = hashlib.sha256(b'1' + b'#' * gil_minsize + b'1') - self.assertEqual( - m.hexdigest(), - '1cfceca95989f51f658e3f3ffe7f1cd43726c9e088c13ee10b46f57cef135b94' - ) + @threading_helper.reap_threads + @threading_helper.requires_working_threading() + def test_threaded_hashing_fast(self): + # Same as test_threaded_hashing_slow() but only tests some functions + # since otherwise test_hashlib.py becomes too slow during development. + algos = ['md5', 'sha1', 'sha256', 'sha3_256', 'blake2s'] + for name in algos: + if constructor := getattr(hashlib, name, None): + with self.subTest(name): + try: + self.do_test_threaded_hashing(constructor, is_shake=False) + except ValueError as exc: + self.skip_if_blake2_not_builtin(name, exc) + raise + + if shake_128 := getattr(hashlib, 'shake_128', None): + self.do_test_threaded_hashing(shake_128, is_shake=True) + @requires_resource('cpu') @threading_helper.reap_threads @threading_helper.requires_working_threading() - def test_threaded_hashing(self): + def test_threaded_hashing_slow(self): + for algorithm, constructors in self.constructors_to_test.items(): + is_shake = algorithm in self.shakes + for constructor in constructors: + with self.subTest(constructor.__name__, is_shake=is_shake): + self.do_test_threaded_hashing(constructor, is_shake) + + def do_test_threaded_hashing(self, constructor, is_shake): # Updating the same hash object from several threads at once # using data chunk sizes containing the same byte sequences. # # If the internal locks are working to prevent multiple # updates on the same object from running at once, the resulting # hash will be the same as doing it single threaded upfront. - hasher = hashlib.sha1() - num_threads = 5 - smallest_data = b'swineflu' - data = smallest_data * 200000 - expected_hash = hashlib.sha1(data*num_threads).hexdigest() - - def hash_in_chunks(chunk_size): - index = 0 - while index < len(data): - hasher.update(data[index:index + chunk_size]) - index += chunk_size + + # The data to hash has length s|M|q^N and the chunk size for the i-th + # thread is s|M|q^(N-i), where N is the number of threads, M is a fixed + # message of small length, and s >= 1 and q >= 2 are small integers. + smallest_size, num_threads, s, q = 8, 5, 2, 10 + + smallest_data = os.urandom(smallest_size) + data = s * smallest_data * (q ** num_threads) + + h1 = constructor(usedforsecurity=False) + h2 = constructor(data * num_threads, usedforsecurity=False) + + def update(chunk_size): + for index in range(0, len(data), chunk_size): + h1.update(data[index:index + chunk_size]) threads = [] - for threadnum in range(num_threads): - chunk_size = len(data) // (10 ** threadnum) + for thread_num in range(num_threads): + # chunk_size = len(data) // (q ** thread_num) + chunk_size = s * smallest_size * q ** (num_threads - thread_num) self.assertGreater(chunk_size, 0) - self.assertEqual(chunk_size % len(smallest_data), 0) - thread = threading.Thread(target=hash_in_chunks, - args=(chunk_size,)) + self.assertEqual(chunk_size % smallest_size, 0) + thread = threading.Thread(target=update, args=(chunk_size,)) threads.append(thread) for thread in threads: @@ -1067,7 +1178,10 @@ def hash_in_chunks(chunk_size): for thread in threads: thread.join() - self.assertEqual(expected_hash, hasher.hexdigest()) + if is_shake: + self.assertEqual(h1.hexdigest(16), h2.hexdigest(16)) + else: + self.assertEqual(h1.hexdigest(), h2.hexdigest()) def test_get_fips_mode(self): fips_mode = self.is_fips_mode @@ -1124,12 +1238,6 @@ class KDFTests(unittest.TestCase): (b'pass\0word', b'sa\0lt', 4096, 16), ] - scrypt_test_vectors = [ - (b'', b'', 16, 1, 1, unhexlify('77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906')), - (b'password', b'NaCl', 1024, 8, 16, unhexlify('fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640')), - (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, unhexlify('7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887')), - ] - pbkdf2_results = { "sha1": [ # official test vectors from RFC 6070 @@ -1221,46 +1329,6 @@ def _test_pbkdf2_hmac(self, pbkdf2, supported): def test_pbkdf2_hmac_c(self): self._test_pbkdf2_hmac(openssl_hashlib.pbkdf2_hmac, openssl_md_meth_names) - @unittest.skipUnless(hasattr(hashlib, 'scrypt'), - ' test requires OpenSSL > 1.1') - @unittest.skipIf(get_fips_mode(), reason="scrypt is blocked in FIPS mode") - def test_scrypt(self): - for password, salt, n, r, p, expected in self.scrypt_test_vectors: - result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p) - self.assertEqual(result, expected) - - # this values should work - hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1) - # password and salt must be bytes-like - with self.assertRaises(TypeError): - hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1) - with self.assertRaises(TypeError): - hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1) - # require keyword args - with self.assertRaises(TypeError): - hashlib.scrypt(b'password') - with self.assertRaises(TypeError): - hashlib.scrypt(b'password', b'salt') - with self.assertRaises(TypeError): - hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt') - for n in [-1, 0, 1, None]: - with self.assertRaises((ValueError, OverflowError, TypeError)): - hashlib.scrypt(b'password', salt=b'salt', n=n, r=8, p=1) - for r in [-1, 0, None]: - with self.assertRaises((ValueError, OverflowError, TypeError)): - hashlib.scrypt(b'password', salt=b'salt', n=2, r=r, p=1) - for p in [-1, 0, None]: - with self.assertRaises((ValueError, OverflowError, TypeError)): - hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=p) - for maxmem in [-1, None]: - with self.assertRaises((ValueError, OverflowError, TypeError)): - hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1, - maxmem=maxmem) - for dklen in [-1, None]: - with self.assertRaises((ValueError, OverflowError, TypeError)): - hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1, - dklen=dklen) - def test_normalized_name(self): self.assertNotIn("blake2b512", hashlib.algorithms_available) self.assertNotIn("sha3-512", hashlib.algorithms_available) @@ -1302,5 +1370,141 @@ def readable(self): hashlib.file_digest(NonBlocking(), hashlib.sha256) +@unittest.skipUnless(hasattr(hashlib, 'scrypt'), 'requires OpenSSL 1.1+') +@unittest.skipIf(get_fips_mode(), reason="scrypt is blocked in FIPS mode") +class TestScrypt(unittest.TestCase): + + scrypt_test_vectors = [ + (b'', b'', 16, 1, 1, unhexlify('77d6576238657b203b19ca42c18a0497f16b4844e3074ae8dfdffa3fede21442fcd0069ded0948f8326a753a0fc81f17e8d3e0fb2e0d3628cf35e20c38d18906')), + (b'password', b'NaCl', 1024, 8, 16, unhexlify('fdbabe1c9d3472007856e7190d01e9fe7c6ad7cbc8237830e77376634b3731622eaf30d92e22a3886ff109279d9830dac727afb94a83ee6d8360cbdfa2cc0640')), + (b'pleaseletmein', b'SodiumChloride', 16384, 8, 1, unhexlify('7023bdcb3afd7348461c06cd81fd38ebfda8fbba904f8e3ea9b543f6545da1f2d5432955613f0fcf62d49705242a9af9e61e85dc0d651e40dfcf017b45575887')), + ] + + def test_scrypt(self): + for password, salt, n, r, p, expected in self.scrypt_test_vectors: + result = hashlib.scrypt(password, salt=salt, n=n, r=r, p=p) + self.assertEqual(result, expected) + + # these parameters must be valid + hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1) + hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1, maxmem=0) + hashlib.scrypt(b'password', salt=b'salt', n=2, r=8, p=1, dklen=1) + + def test_scrypt_types(self): + # password and salt must be bytes-like + with self.assertRaises(TypeError): + hashlib.scrypt('password', salt=b'salt', n=2, r=8, p=1) + with self.assertRaises(TypeError): + hashlib.scrypt(b'password', salt='salt', n=2, r=8, p=1) + # require keyword args + with self.assertRaises(TypeError): + hashlib.scrypt(b'password') + with self.assertRaises(TypeError): + hashlib.scrypt(b'password', b'salt') + with self.assertRaises(TypeError): + hashlib.scrypt(b'password', 2, 8, 1, salt=b'salt') + + def test_scrypt_validate(self): + def scrypt(password=b"password", /, **kwargs): + # overwrite well-defined parameters with bad ones + kwargs = dict(salt=b'salt', n=2, r=8, p=1) | kwargs + return hashlib.scrypt(password, **kwargs) + + for param_name in ('n', 'r', 'p', 'maxmem', 'dklen'): + param = {param_name: None} + with self.subTest(**param): + self.assertRaises(TypeError, scrypt, **param) + + self.assertRaises(ValueError, scrypt, n=0) + self.assertRaises(ValueError, scrypt, n=-1) + self.assertRaises(ValueError, scrypt, n=1) + + self.assertRaises(ValueError, scrypt, r=0) + self.assertRaises(ValueError, scrypt, r=-1) + + self.assertRaises(ValueError, scrypt, p=-1) + self.assertRaises(ValueError, scrypt, p=0) + + self.assertRaises(ValueError, scrypt, maxmem=-1) + # OpenSSL hard limit for 'maxmem' is an 'uint64_t' but for now, + # we do not use the 'uint64' Clinic converter but the 'long' one. + self.assertRaises(OverflowError, scrypt, maxmem=(1 << 64)) + # Historically, Python allowed 'maxmem' to be at most INT_MAX, + # which is at most 2**32-1 (on Windows, sizeof(long) == 4, so + # an OverflowError will be raised instead of a ValueError). + numeric_exc_types = (OverflowError, ValueError) + self.assertRaises(numeric_exc_types, scrypt, maxmem=(1 << 32)) + + self.assertRaises(ValueError, scrypt, dklen=-1) + self.assertRaises(ValueError, scrypt, dklen=0) + MAX_DKLEN = ((1 << 32) - 1) * 32 # see RFC 7914 + self.assertRaises(numeric_exc_types, scrypt, dklen=MAX_DKLEN + 1) + + +@threading_helper.requires_working_threading() +class TestTSAN(unittest.TestCase): + + @threading_helper.reap_threads + def check_attribute(self, write, read, expected, nthreads=8): + ready = threading.Event() + barrier = threading.Barrier(nthreads) + + def writer(): + barrier.wait() + while not ready.is_set(): + write() + + def reader(): + barrier.wait() + while not ready.is_set(): + self.assertEqual(read(), expected) + + targets = [writer if i % 2 else reader for i in range(nthreads)] + workers = [threading.Thread(target=target) for target in targets] + with threading_helper.start_threads(workers, unlock=ready.set): + pass + + def check_HACL_attribute(self, module, version, attrname): + blob = b"A" * 65536 + obj = getattr(module, version)() + update = partial(obj.update, blob) + read = attrgetter(attrname) + self.check_attribute(update, partial(read, obj), read(obj)) + + @requires_md5 + @support.subTests("attrname", ["block_size", "digest_size"]) + def test_HACL_md5_attributes(self, attrname): + self.check_HACL_attribute(_md5, "md5", attrname) + + @requires_sha1 + @support.subTests("attrname", ["block_size", "digest_size"]) + def test_HACL_sha1_attributes(self, attrname): + self.check_HACL_attribute(_sha1, "sha1", attrname) + + @requires_sha2 + @support.subTests("size", [224, 256, 384, 512]) + @support.subTests("attrname", ["block_size", "digest_size"]) + def test_HACL_sha2_attributes(self, size, attrname): + self.check_HACL_attribute(_sha2, f"sha{size}", attrname) + + @requires_sha3 + @support.subTests("size", [224, 256, 384, 512]) + @support.subTests( + "attrname", + ["block_size", "digest_size", "_capacity_bits", "_rate_bits"], + ) + def test_HACL_sha3_attributes(self, size, attrname): + self.check_HACL_attribute(_sha3, f"sha3_{size}", attrname) + + @requires_sha3 + @support.subTests("size", [128, 256]) + @support.subTests( + "attrname", + ["block_size", "digest_size", "_capacity_bits", "_rate_bits"], + ) + def test_HACL_shake_attributes(self, size, attrname): + self.check_HACL_attribute(_sha3, f"shake_{size}", attrname) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py index 1d270b2a43c..722a274e4a4 100644 --- a/Lib/test/test_hmac.py +++ b/Lib/test/test_hmac.py @@ -21,10 +21,10 @@ import hmac import hashlib import random -import types import unittest import warnings from _operator import _compare_digest as operator_compare_digest +from test import support from test.support import _4G, bigmemtest from test.support import check_disallow_instantiation from test.support import hashlib_helper, import_helper @@ -161,7 +161,7 @@ def hmac_digest(self, key, msg=None, digestmod=DIGESTMOD_SENTINEL): return _call_digest_func(self.hmac.digest, key, msg, digestmod) -@hashlib_helper.requires_hashlib() +@hashlib_helper.requires_openssl_hashlib() class ThroughOpenSSLAPIMixin(CreatorMixin, DigestMixin): """Mixin delegating to _hashlib.hmac_new() and _hashlib.hmac_digest().""" @@ -303,7 +303,7 @@ def assert_hmac_new_by_name( def check_hmac_new( self, key, msg, hexdigest, hashname, digest_size, block_size, - hmac_new_func, hmac_new_kwds=types.MappingProxyType({}), + hmac_new_func, hmac_new_kwds=frozendict(), ): """Check that HMAC(key, msg) == digest. @@ -349,7 +349,7 @@ def assert_hmac_hexdigest_by_name( def check_hmac_hexdigest( self, key, msg, hexdigest, digest_size, - hmac_digest_func, hmac_digest_kwds=types.MappingProxyType({}), + hmac_digest_func, hmac_digest_kwds=frozendict(), ): """Check and return a HMAC digest computed by hmac_digest_func(). @@ -965,7 +965,7 @@ def raiser(): with self.assertRaisesRegex(RuntimeError, "custom exception"): func(b'key', b'msg', raiser) - with self.assertRaisesRegex(ValueError, 'hash type'): + with self.assertRaisesRegex(ValueError, 'unsupported hash algorithm'): func(b'key', b'msg', 'unknown') with self.assertRaisesRegex(AttributeError, 'new'): @@ -1025,6 +1025,13 @@ def test_hmac_digest_digestmod_parameter(self): ): self.hmac_digest(b'key', b'msg', value) + @support.subTests("xof_name", ("shake_128", "shake_256")) + def test_hmac_new_xof_digestmod(self, xof_name): + # gh-145200: XOF digests (SHAKE) are not supported by HMAC. + # Verify that the error path does not leak the EVP_MAC_CTX. + with self.assertRaises(_hashlib.UnsupportedDigestmodError): + self.hmac_new(b'key', digestmod=xof_name) + class BuiltinConstructorTestCase(ThroughBuiltinAPIMixin, ExtensionConstructorTestCaseMixin, @@ -1440,7 +1447,7 @@ def test_compare_digest_func(self): self.assertIs(self.compare_digest, operator_compare_digest) -@hashlib_helper.requires_hashlib() +@hashlib_helper.requires_openssl_hashlib() class OpenSSLCompareDigestTestCase(CompareDigestMixin, unittest.TestCase): compare_digest = openssl_compare_digest @@ -1452,19 +1459,25 @@ class OperatorCompareDigestTestCase(CompareDigestMixin, unittest.TestCase): class PyMiscellaneousTests(unittest.TestCase): """Miscellaneous tests for the pure Python HMAC module.""" + @staticmethod + def mock__compute_digest_fallback(hmac): + fn = getattr(hmac, meth := "_compute_digest_fallback") + return patch.object(hmac, meth, wraps=fn) + + @staticmethod + def mock_HMAC_method(hmac, method): + fn = getattr(hmac.HMAC, method) + return patch.object(hmac.HMAC, method, autospec=True, wraps=fn) + @hashlib_helper.requires_builtin_hmac() def test_hmac_constructor_uses_builtin(self): # Block the OpenSSL implementation and check that # HMAC() uses the built-in implementation instead. hmac = import_fresh_module("hmac", blocked=["_hashlib"]) - def watch_method(cls, name): - wraps = getattr(cls, name) - return patch.object(cls, name, autospec=True, wraps=wraps) - with ( - watch_method(hmac.HMAC, '_init_openssl_hmac') as f, - watch_method(hmac.HMAC, '_init_builtin_hmac') as g, + self.mock_HMAC_method(hmac, '_init_openssl_hmac') as f, + self.mock_HMAC_method(hmac, '_init_builtin_hmac') as g, ): _ = hmac.HMAC(b'key', b'msg', digestmod="sha256") f.assert_not_called() @@ -1488,17 +1501,36 @@ def update(self, v): self._x.update(v) def digest(self): return self._x.digest() + def copy(self): + h = MockCrazyHash() + h._x = self._x.copy() + return h with warnings.catch_warnings(): warnings.simplefilter('error', RuntimeWarning) with self.assertRaises(RuntimeWarning): hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) self.fail('Expected warning about missing block_size') + with self.assertRaises(RuntimeWarning): + hmac.digest(b'a', b'b', MockCrazyHash) + self.fail('Expected warning about missing block_size') MockCrazyHash.block_size = 1 with self.assertRaises(RuntimeWarning): hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) self.fail('Expected warning about small block_size') + with self.assertRaises(RuntimeWarning): + hmac.digest(b'a', b'b', MockCrazyHash) + self.fail('Expected warning about small block_size') + + # gh-155428: hmac.HMAC() and hmac.digest() must both + # fall back to the default block size (64 for SHA-256). + expect = hmac.digest(b'a', b'b', 'sha256') + with warnings.catch_warnings(): + warnings.simplefilter('ignore', RuntimeWarning) + h = hmac.HMAC(b'a', b'b', digestmod=MockCrazyHash) + self.assertEqual(h.digest(), expect) + self.assertEqual(hmac.digest(b'a', b'b', MockCrazyHash), expect) @hashlib_helper.requires_hashdigest('sha256') def test_with_fallback(self): @@ -1512,13 +1544,19 @@ def test_with_fallback(self): finally: cache.pop('foo') + @hashlib_helper.requires_hashdigest("md5") + def test_hmac_digest_reject_memoryview_for_key(self): + hmac = import_fresh_module("hmac", blocked=["_hashlib", "_hmac"]) + with self.assertRaises(TypeError): + hmac.digest(memoryview(b"small"), b"world", "md5") + @hashlib_helper.requires_openssl_hashdigest("md5") @bigmemtest(size=_4G + 5, memuse=2, dry_run=False) def test_hmac_digest_overflow_error_openssl_only(self, size): hmac = import_fresh_module("hmac", blocked=["_hmac"]) self.do_test_hmac_digest_overflow_error_switch_to_slow(hmac, size) - @hashlib_helper.requires_builtin_hashdigest("_md5", "md5") + @hashlib_helper.requires_builtin_hashdigest("md5") @bigmemtest(size=_4G + 5, memuse=2, dry_run=False) def test_hmac_digest_overflow_error_builtin_only(self, size): hmac = import_fresh_module("hmac", blocked=["_hashlib"]) @@ -1535,11 +1573,11 @@ def do_test_hmac_digest_overflow_error_switch_to_slow(self, hmac, size): bigkey = b'K' * size bigmsg = b'M' * size - with patch.object(hmac, "_compute_digest_fallback") as slow: + with self.mock__compute_digest_fallback(hmac) as slow: hmac.digest(bigkey, b'm', "md5") slow.assert_called_once() - with patch.object(hmac, "_compute_digest_fallback") as slow: + with self.mock__compute_digest_fallback(hmac) as slow: hmac.digest(b'k', bigmsg, "md5") slow.assert_called_once() @@ -1550,7 +1588,7 @@ def test_hmac_digest_no_overflow_error_in_fallback(self, size): for key, msg in [(b'K' * size, b'm'), (b'k', b'M' * size)]: with self.subTest(keysize=len(key), msgsize=len(msg)): - with patch.object(hmac, "_compute_digest_fallback") as slow: + with self.mock__compute_digest_fallback(hmac) as slow: hmac.digest(key, msg, "md5") slow.assert_called_once() diff --git a/Lib/test/test_http_cookiejar.py b/Lib/test/test_http_cookiejar.py index 04cb440cd4c..f4b53bb1932 100644 --- a/Lib/test/test_http_cookiejar.py +++ b/Lib/test/test_http_cookiejar.py @@ -16,7 +16,7 @@ CookieJar, DefaultCookiePolicy, LWPCookieJar, MozillaCookieJar, LoadError, lwp_cookie_str, DEFAULT_HTTP_PORT, escape_path, reach, is_HDN, domain_match, user_domain_match, request_path, - request_port, request_host) + request_port, request_host, NETSCAPE_HEADER_TEXT) mswindows = (sys.platform == "win32") @@ -459,6 +459,31 @@ def test_bad_magic(self): finally: os_helper.unlink(filename) + def test_magic_ignores_case(self): + filename = os_helper.TESTFN + self.addCleanup(os_helper.unlink, filename) + for magic in ("# Netscape HTTP Cookie File", + "# netscape http cookie file", + "# HTTP Cookie File", + "# http cookie file"): + with self.subTest(magic=magic): + with open(filename, "w") as f: + f.write(magic + "\n") + MozillaCookieJar().load(filename) + + def test_magic_is_not_unicode(self): + # Unicode case folding must not be used: 'ſ' (U+017F) and 'K' + # (U+212A) are case-insensitively equal to 's' and 'k' in Unicode. + filename = os_helper.TESTFN + self.addCleanup(os_helper.unlink, filename) + for magic in ("# Netſcape HTTP Cookie File", + "# Netscape HTTP CooKie File"): + with self.subTest(magic=magic): + with open(filename, "w", encoding="utf-8") as f: + f.write(magic + "\n") + self.assertRaises(LoadError, MozillaCookieJar().load, filename) + + class CookieTests(unittest.TestCase): # XXX # Get rid of string comparisons where not actually testing str / repr. @@ -918,10 +943,37 @@ def test_wrong_domain(self): # XXX far from complete c = CookieJar() - interact_2965(c, "http://www.nasty.com/", - 'foo=bar; domain=friendly.org; Version="1"') + interact_2965(c, "http://www.example.com/", + 'foo=bar; domain=python.org; Version="1"') self.assertEqual(len(c), 0) + def test_negative_version(self): + # A negative version is neither Netscape (0) nor RFC 2965 (> 0), so + # such cookies must be neither set nor returned. + for rfc2965 in False, True: + for interact in interact_netscape, interact_2965: + with self.subTest(rfc2965=rfc2965, interact=interact.__name__): + c = CookieJar(DefaultCookiePolicy(rfc2965=rfc2965)) + interact(c, "http://www.example.com/", + 'foo=bar; domain=python.org; Version=-1') + self.assertEqual(len(c), 0) + interact(c, "http://www.example.com/", 'foo=bar; Version=-1') + self.assertEqual(len(c), 0) + + # Such a header is discarded before the policy is consulted. + c = CookieJar() + req = urllib.request.Request("http://www.example.com/") + res = FakeResponse(["Set-Cookie: foo=bar; Version=-1"], + "http://www.example.com/") + self.assertEqual(c.make_cookies(res, req), []) + + # Not set from a response, for example loaded from an LWP cookie file. + c = CookieJar() + c.set_cookie(Cookie(-1, "foo", "bar", None, False, + ".python.org", True, True, "/", True, + False, None, True, None, None, {})) + self.assertEqual(interact_netscape(c, "http://www.python.org/"), "") + def test_strict_domain(self): # Cookies whose domain is a country-code tld like .co.uk should # not be set if CookiePolicy.strict_domain is true. @@ -1421,6 +1473,7 @@ def cookiejar_from_cookie_headers(headers): ["Set-Cookie: b=foo; max-age=oops"], # bad version ["Set-Cookie: b=foo; version=spam"], + ["Set-Cookie: b=foo; version=-1"], ["Set-Cookie:; Expires=%s" % future], ]: c = cookiejar_from_cookie_headers(headers) @@ -2023,6 +2076,34 @@ def test_session_cookies(self): # we didn't have session cookies in the first place self.assertNotEqual(counter["session_before"], 0) + def test_load_session_cookies(self): + # curl and Wget write 0 in the expires field for session cookies, + # while we write an empty field. Both should be read (gh-61366). + filename = os_helper.TESTFN + self.addCleanup(os_helper.unlink, filename) + expires = int(time.time() + 3600) + with open(filename, "w") as f: + f.write(NETSCAPE_HEADER_TEXT) + f.write("www.foo.com\tFALSE\t/\tFALSE\t%u\tperm\tbar\n" % expires) + f.write("www.foo.com\tFALSE\t/\tFALSE\t0\tcurl_session\tbar\n") + f.write("www.foo.com\tFALSE\t/\tFALSE\t\tour_session\tbar\n") + + c = MozillaCookieJar() + c.revert(filename) + self.assertEqual([cookie.name for cookie in c], ["perm"]) + + c = MozillaCookieJar() + c.revert(filename, ignore_discard=True) + self.assertEqual(sorted(cookie.name for cookie in c), + ["curl_session", "our_session", "perm"]) + for cookie in c: + if cookie.name == "perm": + self.assertEqual(cookie.expires, expires) + self.assertFalse(cookie.discard) + else: + self.assertIsNone(cookie.expires) + self.assertTrue(cookie.discard) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_http_cookies.py b/Lib/test/test_http_cookies.py index 2379dad1976..d1df2ec42f0 100644 --- a/Lib/test/test_http_cookies.py +++ b/Lib/test/test_http_cookies.py @@ -132,7 +132,6 @@ def test_unquote(self): @support.requires_resource('cpu') def test_unquote_large(self): n = 10**6 - n = 10**4 # TODO: RUSTPYTHON; This takes more than 10 minutes to run. lower to 4 for encoded in r'\\', r'\134': with self.subTest(encoded): data = 'a="b=' + encoded*n + ';"' @@ -154,7 +153,8 @@ def test_load(self): self.assertEqual(C.output(['path']), 'Set-Cookie: Customer="WILE_E_COYOTE"; Path=/acme') cookie_encoded = urllib.parse.quote('Customer="WILE_E_COYOTE"; Path=/acme; Version=1', safe='', encoding='utf-8') - self.assertEqual(C.js_output(), fr""" + with self.assertWarnsRegex(DeprecationWarning, r"BaseCookie\.js_output"): + self.assertEqual(C.js_output(), fr""" """) cookie_encoded = urllib.parse.quote('Customer="WILE_E_COYOTE"; Path=/acme', safe='', encoding='utf-8') - self.assertEqual(C.js_output(['path']), fr""" + with self.assertWarnsRegex(DeprecationWarning, r"BaseCookie\.js_output"): + self.assertEqual(C.js_output(['path']), fr""" """ % (expected_encoded_cookie,) - self.assertEqual(M.js_output(), expected_js_output) + with self.assertWarnsRegex(DeprecationWarning, r"Morsel\.js_output"): + self.assertEqual(M.js_output(), expected_js_output) for i in ["foo bar", "foo@bar"]: # Try some illegal characters self.assertRaises(cookies.CookieError, @@ -652,7 +656,8 @@ def test_control_characters_output(self): cookie = cookies.SimpleCookie() cookie["cookie"] = morsel with self.assertRaises(cookies.CookieError): - cookie.js_output() + with self.assertWarnsRegex(DeprecationWarning, r"Morsel\.js_output"): + cookie.js_output() morsel = cookies.Morsel() morsel.set("key", "value", "coded-value") @@ -660,8 +665,29 @@ def test_control_characters_output(self): cookie = cookies.SimpleCookie() cookie["cookie"] = morsel with self.assertRaises(cookies.CookieError): - cookie.js_output() + with self.assertWarnsRegex(DeprecationWarning, r"Morsel\.js_output"): + cookie.js_output() + def test_morsel_js_output_deprecated(self): + morsel = cookies.Morsel() + morsel.set("key", "value", "value") + with self.assertWarnsRegex(DeprecationWarning, r"Morsel\.js_output") as cm: + result = morsel.js_output() + self.assertEqual(cm.filename, __file__) + self.assertIn("document.cookie", result) + + + def test_basecookie_js_output_warns_once(self): + C = cookies.SimpleCookie() + C["key"] = "value" + with self.assertWarns(DeprecationWarning) as cm: + C.js_output() + deprecation_warnings = [ + w for w in cm.warnings if issubclass(w.category, DeprecationWarning) + ] + self.assertEqual(len(deprecation_warnings), 1) + self.assertRegex(str(deprecation_warnings[0].message), r"BaseCookie\.js_output") + self.assertEqual(cm.filename, __file__) def load_tests(loader, tests, pattern): tests.addTest(doctest.DocTestSuite(cookies)) diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py index ab06f3cf054..bd8cdfe55c6 100644 --- a/Lib/test/test_httplib.py +++ b/Lib/test/test_httplib.py @@ -431,6 +431,81 @@ def test_headers_debuglevel(self): self.assertEqual(lines[2], "header: Second: val1") self.assertEqual(lines[3], "header: Second: val2") + def test_max_response_headers(self): + max_headers = client._MAXHEADERS + 20 + headers = [f"Name{i}: Value{i}".encode() for i in range(max_headers)] + body = b"HTTP/1.1 200 OK\r\n" + b"\r\n".join(headers) + + with self.subTest(max_headers=None): + sock = FakeSocket(body) + resp = client.HTTPResponse(sock) + with self.assertRaisesRegex( + client.HTTPException, f"got more than 100 headers" + ): + resp.begin() + + with self.subTest(max_headers=max_headers): + sock = FakeSocket(body) + resp = client.HTTPResponse(sock) + resp.begin(_max_headers=max_headers) + + def test_max_connection_headers(self): + max_headers = client._MAXHEADERS + 20 + headers = ( + f"Name{i}: Value{i}".encode() for i in range(max_headers - 1) + ) + body = ( + b"HTTP/1.1 200 OK\r\n" + + b"\r\n".join(headers) + + b"\r\nContent-Length: 12\r\n\r\nDummy body\r\n" + ) + + with self.subTest(max_headers=None): + conn = client.HTTPConnection("example.com") + conn.sock = FakeSocket(body) + conn.request("GET", "/") + with self.assertRaisesRegex( + client.HTTPException, f"got more than {client._MAXHEADERS} headers" + ): + response = conn.getresponse() + + with self.subTest(max_headers=None): + conn = client.HTTPConnection( + "example.com", max_response_headers=max_headers + ) + conn.sock = FakeSocket(body) + conn.request("GET", "/") + response = conn.getresponse() + response.read() + + def test_max_connection_trailers(self): + # max_response_headers also limits trailer lines of a chunked + # response, which are read and discarded by read(). + max_trailers = client._MAXHEADERS + 20 + trailer_lines = "".join( + f"X-Trailer{i}: {i}\r\n" for i in range(max_trailers - 1) + ) + body = chunked_start + last_chunk + trailer_lines + chunked_end + + with self.subTest(max_response_headers=None): + conn = client.HTTPConnection("example.com") + conn.sock = FakeSocket(body) + conn.request("GET", "/") + response = conn.getresponse() + with self.assertRaisesRegex( + client.HTTPException, + f"got more than {client._MAXHEADERS} trailers", + ): + response.read() + + with self.subTest(max_response_headers=max_trailers): + conn = client.HTTPConnection( + "example.com", max_response_headers=max_trailers + ) + conn.sock = FakeSocket(body) + conn.request("GET", "/") + response = conn.getresponse() + self.assertEqual(response.read(), chunked_expected) class HttpMethodTests(TestCase): def test_invalid_method_names(self): @@ -1332,6 +1407,35 @@ def test_overflowing_header_limit_after_100(self): self.assertIn('got more than ', str(cm.exception)) self.assertIn('headers', str(cm.exception)) + def test_too_many_interim_responses(self): + # A server streaming "100 Continue" responses forever must not + # hang getresponse(). + body = ( + 'HTTP/1.1 100 Continue\r\n\r\n' + * (client._MAXINTERIMRESPONSES + 1) + ) + resp = client.HTTPResponse(FakeSocket(body)) + with self.assertRaises(client.HTTPException) as cm: + resp.begin() + self.assertIn('got more than ', str(cm.exception)) + self.assertIn('interim responses', str(cm.exception)) + + def test_multiple_interim_responses(self): + # A reasonable number of interim responses before the final + # response is skipped as before. + body = ( + 'HTTP/1.1 100 Continue\r\n\r\n' * 3 + + 'HTTP/1.1 200 OK\r\n' + 'Content-Length: 5\r\n' + '\r\n' + 'hello' + ) + resp = client.HTTPResponse(FakeSocket(body), method="GET") + resp.begin() + self.assertEqual(resp.status, 200) + self.assertEqual(resp.read(), b'hello') + resp.close() + def test_overflowing_chunked_line(self): body = ( 'HTTP/1.1 200 OK\r\n' @@ -1403,6 +1507,35 @@ def test_chunked_trailers(self): self.assertEqual(sock.file.read(), b"") #we read to the end resp.close() + def test_chunked_too_many_trailers(self): + """A response streaming endless trailer lines must raise, not hang""" + too_many_trailers = "".join( + f"X-Trailer{i}: {i}\r\n" for i in range(client._MAXHEADERS + 1) + ) + # An unbounded read() reaches the trailers via the final 0 chunk. + sock = FakeSocket( + chunked_start + last_chunk + too_many_trailers + chunked_end) + resp = client.HTTPResponse(sock, method="GET") + resp.begin() + with self.assertRaisesRegex( + client.HTTPException, + f"got more than {client._MAXHEADERS} trailers", + ): + resp.read() + resp.close() + + # A bounded read(amt) larger than the body hits the same limit. + sock = FakeSocket( + chunked_start + last_chunk + too_many_trailers + chunked_end) + resp = client.HTTPResponse(sock, method="GET") + resp.begin() + with self.assertRaisesRegex( + client.HTTPException, + f"got more than {client._MAXHEADERS} trailers", + ): + resp.read(len(chunked_expected) + 1) + resp.close() + def test_chunked_sync(self): """Check that we don't read past the end of the chunked-encoding stream""" expected = chunked_expected @@ -2211,7 +2344,6 @@ def test_host_port(self): self.assertEqual(h, c.host) self.assertEqual(p, c.port) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_tls13_pha(self): import ssl if not ssl.HAS_TLSv1_3 or not ssl.HAS_PHA: @@ -2634,6 +2766,23 @@ def _create_connection(address, timeout=None, source_address=None): self.assertIsNotNone(exc) self.assertTrue(sock.file_closed) + def test_tunnel_nonstr_headers(self): + class CustomObject: + def __str__(self): + return 'custom-str' + + self.conn.set_tunnel('destination.com', headers={ + 'None-Value': None, + 'Integer-Value': 9, + 'Custom-Value': CustomObject(), + }) + + self.conn.request('HEAD', '/', '') + + self.assertIn(b'None-Value: None\r\n', self.conn.sock.data) + self.assertIn(b'Integer-Value: 9\r\n', self.conn.sock.data) + self.assertIn(b'Custom-Value: custom-str\r\n', self.conn.sock.data) + if __name__ == '__main__': unittest.main(verbosity=2) diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py index 7bf4e8279c3..70349c6c886 100644 --- a/Lib/test/test_httpservers.py +++ b/Lib/test/test_httpservers.py @@ -3,9 +3,9 @@ Written by Cody A.W. Somerville , Josip Dzolonga, and Michael Otteneder for the 2007/08 GHOP contest. """ -from collections import OrderedDict + from http.server import BaseHTTPRequestHandler, HTTPServer, HTTPSServer, \ - SimpleHTTPRequestHandler, CGIHTTPRequestHandler + SimpleHTTPRequestHandler from http import server, HTTPStatus import contextlib @@ -13,7 +13,6 @@ import socket import sys import re -import base64 import ntpath import pathlib import shutil @@ -22,18 +21,23 @@ import html import http, http.client import urllib.parse +import urllib.request import tempfile import time import datetime import threading from unittest import mock from io import BytesIO, StringIO +from _colorize import get_theme import unittest from test import support from test.support import ( - is_apple, import_helper, os_helper, requires_subprocess, threading_helper + force_not_colorized, + is_apple, import_helper, os_helper, threading_helper ) +from test.support.script_helper import kill_python, spawn_python +from test.support.socket_helper import find_unused_port try: import ssl @@ -382,6 +386,8 @@ def test_simple_get(self): def test_invalid_request(self): self.sock.send(b'POST /index.html\r\n') res = self.sock.recv(1024) + # The error response is not sent in the bare HTTP/0.9 style. + self.assertStartsWith(res, b'HTTP/1.0 400 ') self.assertIn(b"Bad HTTP/0.9 request type ('POST')", res) def test_single_request(self): @@ -478,6 +484,7 @@ def do_GET(self): def do_ERROR(self): self.send_error(HTTPStatus.NOT_FOUND, 'File not found') + @force_not_colorized def test_get(self): self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() @@ -488,6 +495,7 @@ def test_get(self): self.assertEndsWith(err.getvalue(), '"GET / HTTP/1.1" 200 -\n') + @force_not_colorized def test_err(self): self.con = http.client.HTTPConnection(self.HOST, self.PORT) self.con.connect() @@ -501,8 +509,49 @@ def test_err(self): self.assertEndsWith(lines[1], '"ERROR / HTTP/1.1" 404 -') +@support.force_colorized_test_class +class RequestHandlerColorizedLoggingTestCase(RequestHandlerLoggingTestCase): + + def test_get(self): + t = get_theme(force_color=True).http_server + self.con = http.client.HTTPConnection(self.HOST, self.PORT) + self.con.connect() + + with support.captured_stderr() as err: + self.con.request("GET", "/") + self.con.getresponse() + + output = err.getvalue() + self.assertIn(f"{t.path}/{t.reset}", output) + self.assertIn(f"{t.status_ok}200", output) + self.assertIn(t.reset, output) + + def test_err(self): + t = get_theme(force_color=True).http_server + self.con = http.client.HTTPConnection(self.HOST, self.PORT) + self.con.connect() + + with support.captured_stderr() as err: + self.con.request("ERROR", "/") + self.con.getresponse() + + lines = err.getvalue().split("\n") + self.assertIn( + f"{t.error}code 404, message File not found{t.reset}", lines[0] + ) + self.assertIn(f"{t.status_client_error}404", lines[1]) + + +class CustomHeaderSimpleHTTPRequestHandler(SimpleHTTPRequestHandler): + extra_response_headers = None + + def __init__(self, *args, **kwargs): + kwargs.setdefault('extra_response_headers', self.extra_response_headers) + super().__init__(*args, **kwargs) + + class SimpleHTTPServerTestCase(BaseTestCase): - class request_handler(NoLogRequestHandler, SimpleHTTPRequestHandler): + class request_handler(NoLogRequestHandler, CustomHeaderSimpleHTTPRequestHandler): pass def setUp(self): @@ -529,12 +578,12 @@ def setUp(self): def tearDown(self): try: os.chdir(self.cwd) - try: - shutil.rmtree(self.tempdir) - except: - pass finally: super().tearDown() + try: + shutil.rmtree(self.tempdir) + except: + pass def check_status_and_reason(self, response, status, data=None): def close_conn(): @@ -561,6 +610,15 @@ def close_conn(): reader.close() return body + def check_status_and_headers(self, response, status, headers=None): + # Drain the body so the server-side handler can close the file + # before tearDown removes the tempdir (matters on Windows). + response.read() + self.assertEqual(response.status, status) + if headers: + for name, value in headers.items(): + self.assertEqual(response.getheader(name), value) + def check_list_dir_dirname(self, dirname, quotedname=None): fullpath = os.path.join(self.tempdir, dirname) try: @@ -859,368 +917,66 @@ def test_path_without_leading_slash(self): self.assertEqual(response.getheader("Location"), self.tempdir_name + "/?hi=1") - -cgi_file1 = """\ -#!%s - -print("Content-type: text/html") -print() -print("Hello World") -""" - -cgi_file2 = """\ -#!%s -import os -import sys -import urllib.parse - -print("Content-type: text/html") -print() - -content_length = int(os.environ["CONTENT_LENGTH"]) -query_string = sys.stdin.buffer.read(content_length) -params = {key.decode("utf-8"): val.decode("utf-8") - for key, val in urllib.parse.parse_qsl(query_string)} - -print("%%s, %%s, %%s" %% (params["spam"], params["eggs"], params["bacon"])) -""" - -cgi_file4 = """\ -#!%s -import os - -print("Content-type: text/html") -print() - -print(os.environ["%s"]) -""" - -cgi_file6 = """\ -#!%s -import os - -print("X-ambv: was here") -print("Content-type: text/html") -print() -print("
")
-for k, v in os.environ.items():
-    try:
-        k.encode('ascii')
-        v.encode('ascii')
-    except UnicodeEncodeError:
-        continue  # see: BPO-44647
-    print(f"{k}={v}")
-print("
") -""" - -cgi_file7 = """\ -#!%s -import os -import sys - -print("Content-type: text/plain") -print() - -content_length = int(os.environ["CONTENT_LENGTH"]) -body = sys.stdin.buffer.read(content_length) - -print(f"{content_length} {len(body)}") -""" - - -@unittest.skipIf(hasattr(os, 'geteuid') and os.geteuid() == 0, - "This test can't be run reliably as root (issue #13308).") -@requires_subprocess() -class CGIHTTPServerTestCase(BaseTestCase): - class request_handler(NoLogRequestHandler, CGIHTTPRequestHandler): - _test_case_self = None # populated by each setUp() method call. - - def __init__(self, *args, **kwargs): - with self._test_case_self.assertWarnsRegex( - DeprecationWarning, - r'http\.server\.CGIHTTPRequestHandler'): - # This context also happens to catch and silence the - # threading DeprecationWarning from os.fork(). - super().__init__(*args, **kwargs) - - linesep = os.linesep.encode('ascii') - - def setUp(self): - self.request_handler._test_case_self = self # practical, but yuck. - BaseTestCase.setUp(self) - self.cwd = os.getcwd() - self.parent_dir = tempfile.mkdtemp() - self.cgi_dir = os.path.join(self.parent_dir, 'cgi-bin') - self.cgi_child_dir = os.path.join(self.cgi_dir, 'child-dir') - self.sub_dir_1 = os.path.join(self.parent_dir, 'sub') - self.sub_dir_2 = os.path.join(self.sub_dir_1, 'dir') - self.cgi_dir_in_sub_dir = os.path.join(self.sub_dir_2, 'cgi-bin') - os.mkdir(self.cgi_dir) - os.mkdir(self.cgi_child_dir) - os.mkdir(self.sub_dir_1) - os.mkdir(self.sub_dir_2) - os.mkdir(self.cgi_dir_in_sub_dir) - self.nocgi_path = None - self.file1_path = None - self.file2_path = None - self.file3_path = None - self.file4_path = None - self.file5_path = None - self.file6_path = None - self.file7_path = None - - # The shebang line should be pure ASCII: use symlink if possible. - # See issue #7668. - self._pythonexe_symlink = None - if os_helper.can_symlink(): - self.pythonexe = os.path.join(self.parent_dir, 'python') - self._pythonexe_symlink = support.PythonSymlink(self.pythonexe).__enter__() - else: - self.pythonexe = sys.executable - - try: - # The python executable path is written as the first line of the - # CGI Python script. The encoding cookie cannot be used, and so the - # path should be encodable to the default script encoding (utf-8) - self.pythonexe.encode('utf-8') - except UnicodeEncodeError: - self.tearDown() - self.skipTest("Python executable path is not encodable to utf-8") - - self.nocgi_path = os.path.join(self.parent_dir, 'nocgi.py') - with open(self.nocgi_path, 'w', encoding='utf-8') as fp: - fp.write(cgi_file1 % self.pythonexe) - os.chmod(self.nocgi_path, 0o777) - - self.file1_path = os.path.join(self.cgi_dir, 'file1.py') - with open(self.file1_path, 'w', encoding='utf-8') as file1: - file1.write(cgi_file1 % self.pythonexe) - os.chmod(self.file1_path, 0o777) - - self.file2_path = os.path.join(self.cgi_dir, 'file2.py') - with open(self.file2_path, 'w', encoding='utf-8') as file2: - file2.write(cgi_file2 % self.pythonexe) - os.chmod(self.file2_path, 0o777) - - self.file3_path = os.path.join(self.cgi_child_dir, 'file3.py') - with open(self.file3_path, 'w', encoding='utf-8') as file3: - file3.write(cgi_file1 % self.pythonexe) - os.chmod(self.file3_path, 0o777) - - self.file4_path = os.path.join(self.cgi_dir, 'file4.py') - with open(self.file4_path, 'w', encoding='utf-8') as file4: - file4.write(cgi_file4 % (self.pythonexe, 'QUERY_STRING')) - os.chmod(self.file4_path, 0o777) - - self.file5_path = os.path.join(self.cgi_dir_in_sub_dir, 'file5.py') - with open(self.file5_path, 'w', encoding='utf-8') as file5: - file5.write(cgi_file1 % self.pythonexe) - os.chmod(self.file5_path, 0o777) - - self.file6_path = os.path.join(self.cgi_dir, 'file6.py') - with open(self.file6_path, 'w', encoding='utf-8') as file6: - file6.write(cgi_file6 % self.pythonexe) - os.chmod(self.file6_path, 0o777) - - self.file7_path = os.path.join(self.cgi_dir, 'file7.py') - with open(self.file7_path, 'w', encoding='utf-8') as file7: - file7.write(cgi_file7 % self.pythonexe) - os.chmod(self.file7_path, 0o777) - - os.chdir(self.parent_dir) - - def tearDown(self): - self.request_handler._test_case_self = None - try: - os.chdir(self.cwd) - if self._pythonexe_symlink: - self._pythonexe_symlink.__exit__(None, None, None) - if self.nocgi_path: - os.remove(self.nocgi_path) - if self.file1_path: - os.remove(self.file1_path) - if self.file2_path: - os.remove(self.file2_path) - if self.file3_path: - os.remove(self.file3_path) - if self.file4_path: - os.remove(self.file4_path) - if self.file5_path: - os.remove(self.file5_path) - if self.file6_path: - os.remove(self.file6_path) - if self.file7_path: - os.remove(self.file7_path) - os.rmdir(self.cgi_child_dir) - os.rmdir(self.cgi_dir) - os.rmdir(self.cgi_dir_in_sub_dir) - os.rmdir(self.sub_dir_2) - os.rmdir(self.sub_dir_1) - # The 'gmon.out' file can be written in the current working - # directory if C-level code profiling with gprof is enabled. - os_helper.unlink(os.path.join(self.parent_dir, 'gmon.out')) - os.rmdir(self.parent_dir) - finally: - BaseTestCase.tearDown(self) - - def test_url_collapse_path(self): - # verify tail is the last portion and head is the rest on proper urls - test_vectors = { - '': '//', - '..': IndexError, - '/.//..': IndexError, - '/': '//', - '//': '//', - '/\\': '//\\', - '/.//': '//', - 'cgi-bin/file1.py': '/cgi-bin/file1.py', - '/cgi-bin/file1.py': '/cgi-bin/file1.py', - 'a': '//a', - '/a': '//a', - '//a': '//a', - './a': '//a', - './C:/': '/C:/', - '/a/b': '/a/b', - '/a/b/': '/a/b/', - '/a/b/.': '/a/b/', - '/a/b/c/..': '/a/b/', - '/a/b/c/../d': '/a/b/d', - '/a/b/c/../d/e/../f': '/a/b/d/f', - '/a/b/c/../d/e/../../f': '/a/b/f', - '/a/b/c/../d/e/.././././..//f': '/a/b/f', - '../a/b/c/../d/e/.././././..//f': IndexError, - '/a/b/c/../d/e/../../../f': '/a/f', - '/a/b/c/../d/e/../../../../f': '//f', - '/a/b/c/../d/e/../../../../../f': IndexError, - '/a/b/c/../d/e/../../../../f/..': '//', - '/a/b/c/../d/e/../../../../f/../.': '//', - } - for path, expected in test_vectors.items(): - if isinstance(expected, type) and issubclass(expected, Exception): - self.assertRaises(expected, - server._url_collapse_path, path) - else: - actual = server._url_collapse_path(path) - self.assertEqual(expected, actual, - msg='path = %r\nGot: %r\nWanted: %r' % - (path, actual, expected)) - - def test_headers_and_content(self): - res = self.request('/cgi-bin/file1.py') - self.assertEqual( - (res.read(), res.getheader('Content-type'), res.status), - (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK)) - - def test_issue19435(self): - res = self.request('///////////nocgi.py/../cgi-bin/nothere.sh') - self.assertEqual(res.status, HTTPStatus.NOT_FOUND) - - def test_post(self): - params = urllib.parse.urlencode( - {'spam' : 1, 'eggs' : 'python', 'bacon' : 123456}) - headers = {'Content-type' : 'application/x-www-form-urlencoded'} - res = self.request('/cgi-bin/file2.py', 'POST', params, headers) - - self.assertEqual(res.read(), b'1, python, 123456' + self.linesep) - - def test_large_content_length(self): - for w in range(15, 25): - size = 1 << w - body = b'X' * size - headers = {'Content-Length' : str(size)} - res = self.request('/cgi-bin/file7.py', 'POST', body, headers) - self.assertEqual(res.read(), b'%d %d' % (size, size) + self.linesep) - - @unittest.skipIf(sys.platform == "darwin", "TODO: RUSTPYTHON; flaky: the 1ms handler timeout also bounds reading the request line") - def test_large_content_length_truncated(self): - with support.swap_attr(self.request_handler, 'timeout', 0.001): - for w in range(18, 65): - size = 1 << w - headers = {'Content-Length' : str(size)} - res = self.request('/cgi-bin/file1.py', 'POST', b'x', headers) - self.assertEqual(res.read(), b'Hello World' + self.linesep) - - def test_invaliduri(self): - res = self.request('/cgi-bin/invalid') - res.read() - self.assertEqual(res.status, HTTPStatus.NOT_FOUND) - - def test_authorization(self): - headers = {b'Authorization' : b'Basic ' + - base64.b64encode(b'username:pass')} - res = self.request('/cgi-bin/file1.py', 'GET', headers=headers) - self.assertEqual( - (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - - def test_no_leading_slash(self): - # http://bugs.python.org/issue2254 - res = self.request('cgi-bin/file1.py') - self.assertEqual( - (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - - def test_os_environ_is_not_altered(self): - signature = "Test CGI Server" - os.environ['SERVER_SOFTWARE'] = signature - res = self.request('/cgi-bin/file1.py') - self.assertEqual( - (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - self.assertEqual(os.environ['SERVER_SOFTWARE'], signature) - - def test_urlquote_decoding_in_cgi_check(self): - res = self.request('/cgi-bin%2ffile1.py') - self.assertEqual( - (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - - def test_nested_cgi_path_issue21323(self): - res = self.request('/cgi-bin/child-dir/file3.py') - self.assertEqual( - (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - - def test_query_with_multiple_question_mark(self): - res = self.request('/cgi-bin/file4.py?a=b?c=d') - self.assertEqual( - (b'a=b?c=d' + self.linesep, 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - - def test_query_with_continuous_slashes(self): - res = self.request('/cgi-bin/file4.py?k=aa%2F%2Fbb&//q//p//=//a//b//') - self.assertEqual( - (b'k=aa%2F%2Fbb&//q//p//=//a//b//' + self.linesep, - 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - - def test_cgi_path_in_sub_directories(self): - try: - CGIHTTPRequestHandler.cgi_directories.append('/sub/dir/cgi-bin') - res = self.request('/sub/dir/cgi-bin/file5.py') - self.assertEqual( - (b'Hello World' + self.linesep, 'text/html', HTTPStatus.OK), - (res.read(), res.getheader('Content-type'), res.status)) - finally: - CGIHTTPRequestHandler.cgi_directories.remove('/sub/dir/cgi-bin') - - def test_accept(self): - browser_accept = \ - 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' - tests = ( - ((('Accept', browser_accept),), browser_accept), - ((), ''), - # Hack case to get two values for the one header - ((('Accept', 'text/html'), ('ACCEPT', 'text/plain')), - 'text/html,text/plain'), - ) - for headers, expected in tests: - headers = OrderedDict(headers) - with self.subTest(headers): - res = self.request('/cgi-bin/file6.py', 'GET', headers=headers) - self.assertEqual(http.HTTPStatus.OK, res.status) - expected = f"HTTP_ACCEPT={expected}".encode('ascii') - self.assertIn(expected, res.read()) + def test_extra_response_headers_list_dir(self): + with mock.patch.object(self.request_handler, 'extra_response_headers', [ + ('X-Test1', 'test1'), + ('X-Test2', 'test2'), + ]): + response = self.request(self.base_url + '/') + self.check_status_and_headers(response, HTTPStatus.OK, { + "X-Test1": "test1", + "X-Test2": "test2", + }) + + def test_extra_response_headers_get_file(self): + with mock.patch.object(self.request_handler, 'extra_response_headers', [ + ('Set-Cookie', 'test1=value1'), + ('Set-Cookie', 'test2=value2'), + ('X-Test1', 'value3'), + ]): + data = b"Dummy index file\r\n" + with open(os.path.join(self.tempdir_name, 'index.html'), 'wb') as f: + f.write(data) + response = self.request(self.base_url + '/') + self.check_status_and_headers(response, HTTPStatus.OK, { + "Set-Cookie": "test1=value1, test2=value2", + "X-Test1": "value3", + }) + + def test_extra_response_headers_missing_on_404(self): + with mock.patch.object(self.request_handler, 'extra_response_headers', [ + ('X-Test1', 'value'), + ]): + response = self.request(self.base_url + '/missing.html') + self.check_status_and_headers(response, HTTPStatus.NOT_FOUND, { + "X-Test1": None, + }) + + def test_extra_response_headers_dont_overwrite_default_headers(self): + with mock.patch.object(self.request_handler, 'extra_response_headers', [ + ('Content-Type', 'test/not_allowed'), + ('Server', 'not_allowed'), + ('Set-Cookie', 'test=allowed'), + ]): + # The Content-Type header should not be overwritten by the extra_response_headers + # But cookies in the extra_allowed_duplicate_headers are allowed, + # including Set-Cookie + response = self.request(self.base_url + '/') + self.check_status_and_headers(response, HTTPStatus.OK, { + "Set-Cookie": "test=allowed", + }) + self.assertNotEqual(response.getheader("Content-Type"), 'test/not_allowed') + self.assertNotEqual(response.getheader("Server"), 'not_allowed') + + def test_multiple_requests_dont_duplicate_extra_response_headers(self): + with mock.patch.object(self.request_handler, 'extra_response_headers', [ + ('x-test', 'test-value'), + ]): + for _ in range(2): + response = self.request(self.base_url + '/') + self.check_status_and_headers(response, HTTPStatus.OK, { + "x-test": "test-value", + }) class SocketlessRequestHandler(SimpleHTTPRequestHandler): @@ -1242,6 +998,7 @@ def do_GET(self): def log_message(self, format, *args): pass + class RejectingSocketlessRequestHandler(SocketlessRequestHandler): def handle_expect_100(self): self.send_error(HTTPStatus.EXPECTATION_FAILED) @@ -1295,6 +1052,7 @@ def verify_http_server_response(self, response): match = self.HTTPResponseMatch.search(response) self.assertIsNotNone(match) + @force_not_colorized def test_unprintable_not_logged(self): # We call the method from the class directly as our Socketless # Handler subclass overrode it... nice for everything BUT this test. @@ -1346,6 +1104,19 @@ def test_http_0_9(self): self.assertEqual(result[0], b'Data\r\n') self.verify_get_called() + @support.subTests('request,code', [ + (b'GET / FUBAR\r\n\r\n', 400), # bad version + (b'GET / HTTP/2.0\r\n\r\n', 505), # unsupported version + (b'GET\r\n', 400), # bad syntax + (b'POST /\r\n', 400), # bad HTTP/0.9 request type + ]) + def test_request_line_error_has_status_line(self, request, code): + self.handler = SocketlessRequestHandler() + result = self.send_typical_request(request) + self.assertStartsWith(result[0], b'HTTP/1.1 %d ' % code) + self.verify_expected_headers(result[1:result.index(b'\r\n')]) + self.assertFalse(self.handler.get_called) + def test_extra_space(self): result = self.send_typical_request( b'GET /spaced out HTTP/1.1\r\n' @@ -1683,6 +1454,303 @@ def test_server_test_ipv4(self, _): self.assertEqual(mock_server.address_family, socket.AF_INET) +class CommandLineTestCase(unittest.TestCase): + default_port = 8000 + default_bind = None + default_protocol = 'HTTP/1.0' + default_handler = SimpleHTTPRequestHandler + default_server = unittest.mock.ANY + tls_cert = certdata_file('ssl_cert.pem') + tls_key = certdata_file('ssl_key.pem') + tls_password = 'somepass' + tls_cert_options = ['--tls-cert'] + tls_key_options = ['--tls-key'] + tls_password_options = ['--tls-password-file'] + args = { + 'HandlerClass': default_handler, + 'ServerClass': default_server, + 'protocol': default_protocol, + 'port': default_port, + 'bind': default_bind, + 'content_type': 'application/octet-stream', + 'tls_cert': None, + 'tls_key': None, + 'tls_password': None, + } + + def setUp(self): + super().setUp() + self.tls_password_file = tempfile.mktemp() + with open(self.tls_password_file, 'wb') as f: + f.write(self.tls_password.encode()) + self.addCleanup(os_helper.unlink, self.tls_password_file) + + def invoke_httpd(self, *args, stdout=None, stderr=None): + stdout = StringIO() if stdout is None else stdout + stderr = StringIO() if stderr is None else stderr + with contextlib.redirect_stdout(stdout), \ + contextlib.redirect_stderr(stderr): + server._main(args) + return stdout.getvalue(), stderr.getvalue() + + @mock.patch('http.server.test') + def test_port_flag(self, mock_func): + ports = [8000, 65535] + for port in ports: + with self.subTest(port=port): + self.invoke_httpd(str(port)) + call_args = self.args | dict(port=port) + mock_func.assert_called_once_with(**call_args) + mock_func.reset_mock() + + @mock.patch('http.server.test') + def test_directory_flag(self, mock_func): + options = ['-d', '--directory'] + directories = ['.', '/foo', '\\bar', '/', + 'C:\\', 'C:\\foo', 'C:\\bar', + '/home/user', './foo/foo2', 'D:\\foo\\bar'] + for flag in options: + for directory in directories: + with self.subTest(flag=flag, directory=directory): + self.invoke_httpd(flag, directory) + mock_func.assert_called_once_with(**self.args) + mock_func.reset_mock() + + @mock.patch('http.server.test') + def test_bind_flag(self, mock_func): + options = ['-b', '--bind'] + bind_addresses = ['localhost', '127.0.0.1', '::1', + '0.0.0.0', '8.8.8.8'] + for flag in options: + for bind_address in bind_addresses: + with self.subTest(flag=flag, bind_address=bind_address): + self.invoke_httpd(flag, bind_address) + call_args = self.args | dict(bind=bind_address) + mock_func.assert_called_once_with(**call_args) + mock_func.reset_mock() + + @mock.patch('http.server.test') + def test_protocol_flag(self, mock_func): + options = ['-p', '--protocol'] + protocols = ['HTTP/1.0', 'HTTP/1.1', 'HTTP/2.0', 'HTTP/3.0'] + for flag in options: + for protocol in protocols: + with self.subTest(flag=flag, protocol=protocol): + self.invoke_httpd(flag, protocol) + call_args = self.args | dict(protocol=protocol) + mock_func.assert_called_once_with(**call_args) + mock_func.reset_mock() + + @mock.patch('http.server.test') + def test_content_type_flag(self, mock_func): + content_types = ['text/html', 'text/plain', 'application/json'] + for content_type in content_types: + with self.subTest(content_type=content_type): + self.invoke_httpd('--content-type', content_type) + call_args = self.args | dict(content_type=content_type) + mock_func.assert_called_once_with(**call_args) + mock_func.reset_mock() + + @mock.patch('http.server.test') + def test_header_flag(self, mock_func): + call_args = self.args + self.invoke_httpd('--header', 'h1', 'v1', '-H', 'h2', 'v2') + mock_func.assert_called_once_with(**call_args) + mock_func.reset_mock() + + def test_extra_header_flag_too_few_args(self): + with self.assertRaises(SystemExit): + self.invoke_httpd('--header', 'h1') + + def test_extra_header_flag_too_many_args(self): + with self.assertRaises(SystemExit): + self.invoke_httpd('--header', 'h1', 'v1', 'h2') + + @unittest.skipIf(ssl is None, "requires ssl") + @mock.patch('http.server.test') + def test_tls_cert_and_key_flags(self, mock_func): + for tls_cert_option in self.tls_cert_options: + for tls_key_option in self.tls_key_options: + self.invoke_httpd(tls_cert_option, self.tls_cert, + tls_key_option, self.tls_key) + call_args = self.args | { + 'tls_cert': self.tls_cert, + 'tls_key': self.tls_key, + } + mock_func.assert_called_once_with(**call_args) + mock_func.reset_mock() + + @unittest.skipIf(ssl is None, "requires ssl") + @mock.patch('http.server.test') + def test_tls_cert_and_key_and_password_flags(self, mock_func): + for tls_cert_option in self.tls_cert_options: + for tls_key_option in self.tls_key_options: + for tls_password_option in self.tls_password_options: + self.invoke_httpd(tls_cert_option, + self.tls_cert, + tls_key_option, + self.tls_key, + tls_password_option, + self.tls_password_file) + call_args = self.args | { + 'tls_cert': self.tls_cert, + 'tls_key': self.tls_key, + 'tls_password': self.tls_password, + } + mock_func.assert_called_once_with(**call_args) + mock_func.reset_mock() + + @unittest.skipIf(ssl is None, "requires ssl") + @mock.patch('http.server.test') + def test_missing_tls_cert_flag(self, mock_func): + for tls_key_option in self.tls_key_options: + with self.assertRaises(SystemExit): + self.invoke_httpd(tls_key_option, self.tls_key) + mock_func.reset_mock() + + for tls_password_option in self.tls_password_options: + with self.assertRaises(SystemExit): + self.invoke_httpd(tls_password_option, self.tls_password) + mock_func.reset_mock() + + @unittest.skipIf(ssl is None, "requires ssl") + @mock.patch('http.server.test') + def test_invalid_password_file(self, mock_func): + non_existent_file = 'non_existent_file' + for tls_password_option in self.tls_password_options: + for tls_cert_option in self.tls_cert_options: + with self.assertRaises(SystemExit): + self.invoke_httpd(tls_cert_option, + self.tls_cert, + tls_password_option, + non_existent_file) + + @mock.patch('http.server.test') + def test_no_arguments(self, mock_func): + self.invoke_httpd() + mock_func.assert_called_once_with(**self.args) + mock_func.reset_mock() + + @mock.patch('http.server.test') + def test_help_flag(self, _): + options = ['-h', '--help'] + for option in options: + stdout, stderr = StringIO(), StringIO() + with self.assertRaises(SystemExit): + self.invoke_httpd(option, stdout=stdout, stderr=stderr) + self.assertIn('usage', stdout.getvalue()) + self.assertEqual(stderr.getvalue(), '') + + @mock.patch('http.server.test') + def test_unknown_flag(self, _): + stdout, stderr = StringIO(), StringIO() + with self.assertRaises(SystemExit): + self.invoke_httpd('--unknown-flag', stdout=stdout, stderr=stderr) + self.assertEqual(stdout.getvalue(), '') + self.assertIn('error', stderr.getvalue()) + + @mock.patch('http.server.test') + def test_extra_response_headers_arg(self, mock_test): + # Call the main function with extra response headers cli args + server._main( + ['-H', 'Set-Cookie', 'k=v', '-H', 'Set-Cookie', 'k2=v2:v3 v4', '8080'] + ) + # Get the ServerClass (DualStackServerMixin subclass) that _main() + # passed to test(), and verify its finish_request passes + # extra_response_headers to the handler. + _, kwargs = mock_test.call_args + server_class = kwargs['ServerClass'] + + mock_handler_class = mock.MagicMock() + mock_server = mock.Mock() + mock_server.RequestHandlerClass = mock_handler_class + server_class.finish_request(mock_server, mock.Mock(), '127.0.0.1') + mock_handler_class.assert_called_once_with( + mock.ANY, mock.ANY, mock_server, + directory=mock.ANY, + extra_response_headers=[ + ['Set-Cookie', 'k=v'], ['Set-Cookie', 'k2=v2:v3 v4'] + ] + ) + + +class CommandLineRunTimeTestCase(unittest.TestCase): + served_data = os.urandom(32) + served_filename = 'served_filename' + tls_cert = certdata_file('ssl_cert.pem') + tls_key = certdata_file('ssl_key.pem') + tls_password = b'somepass' + tls_password_file = 'ssl_key_password' + + def setUp(self): + super().setUp() + server_dir_context = os_helper.temp_cwd() + server_dir = self.enterContext(server_dir_context) + with open(self.served_filename, 'wb') as f: + f.write(self.served_data) + with open(self.tls_password_file, 'wb') as f: + f.write(self.tls_password) + + def fetch_file(self, path, context=None): + req = urllib.request.Request(path, method='GET') + with urllib.request.urlopen(req, context=context) as res: + return res.read() + + def parse_cli_output(self, output): + match = re.search(r'Serving (HTTP|HTTPS) on (.+) port (\d+)', output) + if match is None: + return None, None, None + return match.group(1).lower(), match.group(2), int(match.group(3)) + + def wait_for_server(self, proc, protocol, bind, port): + """Check that the server has been successfully started.""" + line = proc.stdout.readline().strip() + if support.verbose: + print() + print('python -m http.server: ', line) + return self.parse_cli_output(line) == (protocol, bind, port) + + def test_http_client(self): + bind, port = '127.0.0.1', find_unused_port() + proc = spawn_python('-u', '-m', 'http.server', str(port), '-b', bind, + bufsize=1, text=True) + self.addCleanup(kill_python, proc) + self.addCleanup(proc.terminate) + self.assertTrue(self.wait_for_server(proc, 'http', bind, port)) + res = self.fetch_file(f'http://{bind}:{port}/{self.served_filename}') + self.assertEqual(res, self.served_data) + + @unittest.skipIf(ssl is None, "requires ssl") + def test_https_client(self): + context = ssl.create_default_context() + # allow self-signed certificates + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + + bind, port = '127.0.0.1', find_unused_port() + proc = spawn_python('-u', '-m', 'http.server', str(port), '-b', bind, + '--tls-cert', self.tls_cert, + '--tls-key', self.tls_key, + '--tls-password-file', self.tls_password_file, + bufsize=1, text=True) + self.addCleanup(kill_python, proc) + self.addCleanup(proc.terminate) + self.assertTrue(self.wait_for_server(proc, 'https', bind, port)) + url = f'https://{bind}:{port}/{self.served_filename}' + res = self.fetch_file(url, context=context) + self.assertEqual(res, self.served_data) + + +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(http.server, "__version__") + self.assertEqual(cm.filename, __file__) + + def setUpModule(): unittest.addModuleCleanup(os.chdir, os.getcwd()) diff --git a/Lib/test/test_idle.py b/Lib/test/test_idle.py index 3d8b7ecc0ec..ebf572ac5ca 100644 --- a/Lib/test/test_idle.py +++ b/Lib/test/test_idle.py @@ -16,7 +16,7 @@ # Unittest.main and test.libregrtest.runtest.runtest_inner # call load_tests, when present here, to discover tests to run. -from idlelib.idle_test import load_tests +from idlelib.idle_test import load_tests # noqa: F401 if __name__ == '__main__': tk.NoDefaultRoot() diff --git a/Lib/test/test_imaplib.py b/Lib/test/test_imaplib.py index 62d4d6e6e9f..1c56ad45979 100644 --- a/Lib/test/test_imaplib.py +++ b/Lib/test/test_imaplib.py @@ -13,8 +13,7 @@ import socket from test.support import verbose, run_with_tz, run_with_locale, cpython_only -from test.support import hashlib_helper -from test.support import threading_helper +from test.support import hashlib_helper, threading_helper import unittest from unittest import mock from datetime import datetime, timezone, timedelta @@ -684,17 +683,12 @@ def test_login_cram_md5_plain_text(self): ret, _ = client.login_cram_md5("tim", "tanstaaftanstaaf") self.assertEqual(ret, "OK") + @hashlib_helper.block_algorithm("md5") def test_login_cram_md5_blocked(self): - def side_effect(*a, **kw): - raise ValueError - client, _ = self._setup(AuthHandler_CRAM_MD5) self.assertIn('AUTH=CRAM-MD5', client.capabilities) msg = re.escape("CRAM-MD5 authentication is not supported") - with ( - mock.patch("hmac.HMAC", side_effect=side_effect), - self.assertRaisesRegex(imaplib.IMAP4.error, msg) - ): + with self.assertRaisesRegex(imaplib.IMAP4.error, msg): client.login_cram_md5("tim", b"tanstaaftanstaaf") def test_aborted_authentication(self): @@ -730,7 +724,6 @@ def test_simple_with_statement(self): with self.imap_class(*server.server_address): pass - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'socket' object has no attribute 'timeout'. Did you mean: 'gettimeout'? def test_imaplib_timeout_test(self): _, server = self._setup(SimpleIMAPHandler, connect=False) with self.imap_class(*server.server_address, timeout=None) as client: @@ -901,6 +894,8 @@ def cmd_ENABLE(self, tag, args): client.login('user', 'pass') self.assertIn('ENABLE', client.capabilities) self.assertIn('UTF8=ACCEPT', client.capabilities) + self.assertEqual(client.response('CAPABILITY'), + ('CAPABILITY', [b'IMAP4rev1 ENABLE UTF8=ACCEPT'])) typ, _ = client.enable('UTF8=ACCEPT') self.assertEqual(typ, 'OK') @@ -919,6 +914,8 @@ def cmd_AUTHENTICATE(self, tag, args): self.assertNotIn('ENABLE', client.capabilities) client.authenticate('MYAUTH', lambda x: b'fake') self.assertIn('ENABLE', client.capabilities) + self.assertEqual(client.response('CAPABILITY'), + ('CAPABILITY', [b'IMAP4rev1 ENABLE'])) def test_greeting_capabilities(self): # Capabilities advertised in the greeting are used directly, @@ -932,6 +929,8 @@ def cmd_CAPABILITY(self, tag, args): client, server = self._setup(GreetingHandler) self.assertEqual(client.capabilities, ('IMAP4REV1', 'ENABLE')) self.assertFalse(getattr(server, 'capability_queried', False)) + # The greeting is not a response to a command, so it is consumed. + self.assertEqual(client.response('CAPABILITY'), ('CAPABILITY', [None])) def test_login_requery_capabilities(self): # If the server does not advertise capabilities after login, @@ -1831,11 +1830,33 @@ def test_control_characters(self): # property tests - def test_file_property_should_not_be_accessed(self): + def test_file_property_getter(self): + client, _ = self._setup(SimpleIMAPHandler) + with self.assertWarns(DeprecationWarning): + self.assertIsInstance(client.file.raw, socket.SocketIO) + + def test_file_property_setter(self): client, _ = self._setup(SimpleIMAPHandler) - # the 'file' property replaced a private attribute that is now unsafe - with self.assertWarns(RuntimeWarning): - client.file + with self.assertWarns(DeprecationWarning): + # ensure that the caller closes the existing file + client.file.close() + for new_file in [mock.Mock(), None]: + with self.assertWarns(DeprecationWarning): + client.file = new_file + with self.assertWarns(DeprecationWarning): + self.assertIs(client.file, new_file) + + def test_file_property_setter_should_not_close_previous_file(self): + client, _ = self._setup(SimpleIMAPHandler) + with mock.patch.object(client, "_imaplib_file", mock.Mock()) as f: + f.close.assert_not_called() + with self.assertWarns(DeprecationWarning): + self.assertIs(client.file, f) + with self.assertWarns(DeprecationWarning): + client.file = None + with self.assertWarns(DeprecationWarning): + self.assertIsNone(client.file) + f.close.assert_not_called() class NewIMAPTests(NewIMAPTestsMixin, unittest.TestCase): @@ -2288,5 +2309,15 @@ def test_ssl_verified(self): client.shutdown() +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(imaplib, "__version__") + self.assertEqual(cm.filename, __file__) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_import/__init__.py b/Lib/test/test_import/__init__.py index 3233a72750b..185c1f1595f 100644 --- a/Lib/test/test_import/__init__.py +++ b/Lib/test/test_import/__init__.py @@ -15,6 +15,7 @@ import os import py_compile import random +import re import shutil import stat import subprocess @@ -23,6 +24,7 @@ import threading import time import types +import warnings import unittest from unittest import mock import _imp @@ -52,7 +54,7 @@ TESTFN, rmtree, temp_umask, TESTFN_UNENCODABLE) from test.support import script_helper from test.support import threading_helper -from test.test_importlib.util import uncache +from test.test_importlib.util import uncache, temporary_pycache_prefix from types import ModuleType try: import _testsinglephase @@ -64,8 +66,10 @@ _testmultiphase = None try: import _interpreters + import concurrent.interpreters except ModuleNotFoundError: _interpreters = None + concurrent = None try: import _testinternalcapi except ImportError: @@ -73,7 +77,7 @@ skip_if_dont_write_bytecode = unittest.skipIf( - sys.dont_write_bytecode, + sys.dont_write_bytecode or sys.implementation.cache_tag is None, "test meaningful only when writing bytecode") @@ -363,11 +367,11 @@ def test_import_raises_ModuleNotFoundError(self): def test_import_null_byte_in_name_raises_ModuleNotFoundError(self): # gh-150633: module names containing null bytes should not # lead to duplicates in sys.modules - before = set(sys.modules.keys()) + before = set(sys.modules) with self.assertRaises(ModuleNotFoundError): __import__('zipimport\x00junk') - self.assertEqual(set(sys.modules.keys()), before) + self.assertEqual(set(sys.modules), before) def test_from_import_missing_module_raises_ModuleNotFoundError(self): with self.assertRaises(ModuleNotFoundError): @@ -422,7 +426,6 @@ def test_from_import_missing_attr_path_is_canonical(self): self.assertIsNotNone(cm.exception) def test_from_import_star_invalid_type(self): - import re with ready_to_import() as (name, path): with open(path, 'w', encoding='utf-8') as f: f.write("__all__ = [b'invalid_type']") @@ -487,6 +490,7 @@ def test_with_extension(ext): forget(TESTFN) unlink(source) unlink(pyc) + rmtree('__pycache__') sys.path.insert(0, os.curdir) try: @@ -511,7 +515,7 @@ def test_module_with_large_stack(self, module='longlist'): try: # Compile & remove .py file; we only need .pyc. # Bytecode must be relocated from the PEP 3147 bytecode-only location. - py_compile.compile(filename) + make_legacy_pyc(filename, allow_compile=True) finally: unlink(filename) @@ -521,7 +525,6 @@ def test_module_with_large_stack(self, module='longlist'): namespace = {} try: - make_legacy_pyc(filename) # This used to crash. exec('import ' + module, None, namespace) finally: @@ -666,6 +669,7 @@ def __del__(self): import importlib sys.argv.insert(0, C()) """)) + self.addCleanup(unlink, testfn) script_helper.assert_python_ok(testfn) @skip_if_dont_write_bytecode @@ -786,7 +790,7 @@ def test_dll_dependency_import(self): pydname = importlib.util.find_spec("_sqlite3").origin depname = os.path.join( os.path.dirname(pydname), - "sqlite3{}.dll".format("_d" if "_d" in pydname else "")) + "sqlite3{}.dll".format("_d" if "_d" in os.path.basename(pydname) else "")) with os_helper.temp_dir() as tmp: tmp2 = os.path.join(tmp, "DLLs") @@ -1261,6 +1265,44 @@ class Spec2: origin = "a\x00b" _imp.create_dynamic(Spec2()) + def test_create_builtin(self): + class Spec: + pass + spec = Spec() + + spec.name = "sys" + self.assertIs(_imp.create_builtin(spec), sys) + + spec.name = None + with self.assertRaisesRegex(TypeError, 'name must be string, not NoneType'): + _imp.create_builtin(spec) + + # gh-142029 + spec.name = "nonexistent_lib" + with self.assertRaises(ModuleNotFoundError): + _imp.create_builtin(spec) + + # gh-142029 + spec.name = "" + with self.assertRaisesRegex(ValueError, 'name must not be empty'): + _imp.create_builtin(spec) + + def test_filter_syntax_warnings_by_module(self): + module_re = r'test\.test_import\.data\.syntax_warnings\z' + unload('test.test_import.data.syntax_warnings') + with (os_helper.temp_dir() as tmpdir, + temporary_pycache_prefix(tmpdir), + warnings.catch_warnings(record=True) as wlog): + warnings.simplefilter('error') + warnings.filterwarnings('always', module=module_re) + warnings.filterwarnings('error', module='syntax_warnings') + import test.test_import.data.syntax_warnings + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + filename = test.test_import.data.syntax_warnings.__file__ + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) + @skip_if_dont_write_bytecode class FilePermissionTests(unittest.TestCase): @@ -1369,7 +1411,10 @@ def func(): """ dir_name = os.path.abspath(TESTFN) file_name = os.path.join(dir_name, module_name) + os.extsep + "py" - compiled_name = importlib.util.cache_from_source(file_name) + try: + compiled_name = importlib.util.cache_from_source(file_name) + except NotImplementedError: + compiled_name = None def setUp(self): self.sys_path = sys.path[:] @@ -1387,7 +1432,8 @@ def tearDown(self): else: unload(self.module_name) unlink(self.file_name) - unlink(self.compiled_name) + if self.compiled_name: + unlink(self.compiled_name) rmtree(self.dir_name) def import_module(self): @@ -1406,6 +1452,8 @@ def test_basics(self): self.assertEqual(mod.code_filename, self.file_name) self.assertEqual(mod.func_filename, self.file_name) + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag is not None') def test_incorrect_code_name(self): py_compile.compile(self.file_name, dfile="another_module.py") mod = self.import_module() @@ -1415,9 +1463,9 @@ def test_incorrect_code_name(self): def test_module_without_source(self): target = "another_module.py" - py_compile.compile(self.file_name, dfile=target) + pyc_file = self.file_name + 'c' + py_compile.compile(self.file_name, pyc_file, dfile=target) os.remove(self.file_name) - pyc_file = make_legacy_pyc(self.file_name) importlib.invalidate_caches() mod = self.import_module() self.assertEqual(mod.module_filename, pyc_file) @@ -1425,8 +1473,9 @@ def test_module_without_source(self): self.assertEqual(mod.func_filename, target) def test_foreign_code(self): - py_compile.compile(self.file_name) - with open(self.compiled_name, "rb") as f: + compiled_name = self.compiled_name or (self.file_name + 'c') + py_compile.compile(self.file_name, compiled_name) + with open(compiled_name, "rb") as f: header = f.read(16) code = marshal.load(f) constants = list(code.co_consts) @@ -1434,9 +1483,11 @@ def test_foreign_code(self): pos = constants.index(1000) constants[pos] = foreign_code code = code.replace(co_consts=tuple(constants)) - with open(self.compiled_name, "wb") as f: + with open(compiled_name, "wb") as f: f.write(header) marshal.dump(code, f) + if not self.compiled_name: + os.remove(self.file_name) mod = self.import_module() self.assertEqual(mod.constant.co_filename, foreign_code.co_filename) @@ -1621,6 +1672,11 @@ def _clean(self): unlink(self.source) def setUp(self): + # These tests assume bytecode is written next to the source in a + # local __pycache__ directory, so neutralize any pycache prefix (e.g. + # when the test suite is run with PYTHONPYCACHEPREFIX set). + self._orig_pycache_prefix = sys.pycache_prefix + sys.pycache_prefix = None self.source = TESTFN + '.py' self._clean() with open(self.source, 'w', encoding='utf-8') as fp: @@ -1632,6 +1688,7 @@ def tearDown(self): assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]' del sys.path[0] self._clean() + sys.pycache_prefix = self._orig_pycache_prefix @skip_if_dont_write_bytecode def test_import_pyc_path(self): @@ -1691,78 +1748,6 @@ def test_missing_source_legacy(self): finally: os.remove(pyc_file) - def test___cached__(self): - # Modules now also have an __cached__ that points to the pyc file. - m = __import__(TESTFN) - pyc_file = importlib.util.cache_from_source(TESTFN + '.py') - self.assertEqual(m.__cached__, os.path.join(os.getcwd(), pyc_file)) - - @skip_if_dont_write_bytecode - def test___cached___legacy_pyc(self): - # Like test___cached__() except that for backward compatibility, - # when the pyc file lives where the py file would have been (and named - # without the tag), it is importable. The __cached__ of the imported - # module is the pyc location. - __import__(TESTFN) - # pyc_file gets removed in _clean() via tearDown(). - pyc_file = make_legacy_pyc(self.source) - os.remove(self.source) - unload(TESTFN) - importlib.invalidate_caches() - m = __import__(TESTFN) - self.assertEqual(m.__cached__, - os.path.join(os.getcwd(), os.path.relpath(pyc_file))) - - @skip_if_dont_write_bytecode - def test_package___cached__(self): - # Like test___cached__ but for packages. - def cleanup(): - rmtree('pep3147') - unload('pep3147.foo') - unload('pep3147') - os.mkdir('pep3147') - self.addCleanup(cleanup) - # Touch the __init__.py - with open(os.path.join('pep3147', '__init__.py'), 'wb'): - pass - with open(os.path.join('pep3147', 'foo.py'), 'wb'): - pass - importlib.invalidate_caches() - m = __import__('pep3147.foo') - init_pyc = importlib.util.cache_from_source( - os.path.join('pep3147', '__init__.py')) - self.assertEqual(m.__cached__, os.path.join(os.getcwd(), init_pyc)) - foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py')) - self.assertEqual(sys.modules['pep3147.foo'].__cached__, - os.path.join(os.getcwd(), foo_pyc)) - - def test_package___cached___from_pyc(self): - # Like test___cached__ but ensuring __cached__ when imported from a - # PEP 3147 pyc file. - def cleanup(): - rmtree('pep3147') - unload('pep3147.foo') - unload('pep3147') - os.mkdir('pep3147') - self.addCleanup(cleanup) - # Touch the __init__.py - with open(os.path.join('pep3147', '__init__.py'), 'wb'): - pass - with open(os.path.join('pep3147', 'foo.py'), 'wb'): - pass - importlib.invalidate_caches() - m = __import__('pep3147.foo') - unload('pep3147.foo') - unload('pep3147') - importlib.invalidate_caches() - m = __import__('pep3147.foo') - init_pyc = importlib.util.cache_from_source( - os.path.join('pep3147', '__init__.py')) - self.assertEqual(m.__cached__, os.path.join(os.getcwd(), init_pyc)) - foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py')) - self.assertEqual(sys.modules['pep3147.foo'].__cached__, - os.path.join(os.getcwd(), foo_pyc)) - def test_recompute_pyc_same_second(self): # Even when the source file doesn't change timestamp, a change in # source size is enough to trigger recomputation of the pyc file. @@ -2031,10 +2016,6 @@ def test_import_bug(self): # away from the traceback. self.create_module("foo", "") importlib = sys.modules['_frozen_importlib_external'] - if 'load_module' in vars(importlib.SourceLoader): - old_exec_module = importlib.SourceLoader.exec_module - else: - old_exec_module = None try: def exec_module(*args): 1/0 @@ -2047,18 +2028,15 @@ def exec_module(*args): self.fail("ZeroDivisionError should have been raised") self.assert_traceback(tb, [__file__, '>> @suppress(KeyError) - ... def key_error(): - ... {}[''] - >>> key_error() - """ diff --git a/Lib/test/test_importlib/_path.py b/Lib/test/test_importlib/_path.py deleted file mode 100644 index 71a704389b9..00000000000 --- a/Lib/test/test_importlib/_path.py +++ /dev/null @@ -1,109 +0,0 @@ -# from jaraco.path 3.5 - -import functools -import pathlib -from typing import Dict, Union - -try: - from typing import Protocol, runtime_checkable -except ImportError: # pragma: no cover - # Python 3.7 - from typing_extensions import Protocol, runtime_checkable # type: ignore - - -FilesSpec = Dict[str, Union[str, bytes, 'FilesSpec']] # type: ignore - - -@runtime_checkable -class TreeMaker(Protocol): - def __truediv__(self, *args, **kwargs): - ... # pragma: no cover - - def mkdir(self, **kwargs): - ... # pragma: no cover - - def write_text(self, content, **kwargs): - ... # pragma: no cover - - def write_bytes(self, content): - ... # pragma: no cover - - -def _ensure_tree_maker(obj: Union[str, TreeMaker]) -> TreeMaker: - return obj if isinstance(obj, TreeMaker) else pathlib.Path(obj) # type: ignore - - -def build( - spec: FilesSpec, - prefix: Union[str, TreeMaker] = pathlib.Path(), # type: ignore -): - """ - Build a set of files/directories, as described by the spec. - - Each key represents a pathname, and the value represents - the content. Content may be a nested directory. - - >>> spec = { - ... 'README.txt': "A README file", - ... "foo": { - ... "__init__.py": "", - ... "bar": { - ... "__init__.py": "", - ... }, - ... "baz.py": "# Some code", - ... } - ... } - >>> target = getfixture('tmp_path') - >>> build(spec, target) - >>> target.joinpath('foo/baz.py').read_text(encoding='utf-8') - '# Some code' - """ - for name, contents in spec.items(): - create(contents, _ensure_tree_maker(prefix) / name) - - -@functools.singledispatch -def create(content: Union[str, bytes, FilesSpec], path): - path.mkdir(exist_ok=True) - build(content, prefix=path) # type: ignore - - -@create.register -def _(content: bytes, path): - path.write_bytes(content) - - -@create.register -def _(content: str, path): - path.write_text(content, encoding='utf-8') - - -@create.register -def _(content: str, path): - path.write_text(content, encoding='utf-8') - - -class Recording: - """ - A TreeMaker object that records everything that would be written. - - >>> r = Recording() - >>> build({'foo': {'foo1.txt': 'yes'}, 'bar.txt': 'abc'}, r) - >>> r.record - ['foo/foo1.txt', 'bar.txt'] - """ - - def __init__(self, loc=pathlib.PurePosixPath(), record=None): - self.loc = loc - self.record = record if record is not None else [] - - def __truediv__(self, other): - return Recording(self.loc / other, self.record) - - def write_text(self, content, **kwargs): - self.record.append(str(self.loc)) - - write_bytes = write_text - - def mkdir(self, **kwargs): - return diff --git a/Lib/test/test_importlib/abc.py b/Lib/test/test_importlib/abc.py index 5d4b9587676..0da98e0c99e 100644 --- a/Lib/test/test_importlib/abc.py +++ b/Lib/test/test_importlib/abc.py @@ -40,22 +40,6 @@ def test_failure(self): class LoaderTests(metaclass=abc.ABCMeta): - @abc.abstractmethod - def test_module(self): - """A module should load without issue. - - After the loader returns the module should be in sys.modules. - - Attributes to verify: - - * __file__ - * __loader__ - * __name__ - * No __path__ - - """ - pass - @abc.abstractmethod def test_package(self): """Loading a package should work. diff --git a/Lib/test/test_importlib/builtin/test_loader.py b/Lib/test/test_importlib/builtin/test_loader.py index 7e9d1b1960f..2a5c2a8f39e 100644 --- a/Lib/test/test_importlib/builtin/test_loader.py +++ b/Lib/test/test_importlib/builtin/test_loader.py @@ -7,70 +7,6 @@ import unittest import warnings -@unittest.skipIf(util.BUILTINS.good_name is None, 'no reasonable builtin module') -class LoaderTests(abc.LoaderTests): - - """Test load_module() for built-in modules.""" - - def setUp(self): - self.verification = {'__name__': 'errno', '__package__': '', - '__loader__': self.machinery.BuiltinImporter} - - def verify(self, module): - """Verify that the module matches against what it should have.""" - self.assertIsInstance(module, types.ModuleType) - for attr, value in self.verification.items(): - self.assertEqual(getattr(module, attr), value) - self.assertIn(module.__name__, sys.modules) - - def load_module(self, name): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - return self.machinery.BuiltinImporter.load_module(name) - - def test_module(self): - # Common case. - with util.uncache(util.BUILTINS.good_name): - module = self.load_module(util.BUILTINS.good_name) - self.verify(module) - - # Built-in modules cannot be a package. - test_package = test_lacking_parent = None - - # No way to force an import failure. - test_state_after_failure = None - - def test_module_reuse(self): - # Test that the same module is used in a reload. - with util.uncache(util.BUILTINS.good_name): - module1 = self.load_module(util.BUILTINS.good_name) - module2 = self.load_module(util.BUILTINS.good_name) - self.assertIs(module1, module2) - - def test_unloadable(self): - name = 'dssdsdfff' - assert name not in sys.builtin_module_names - with self.assertRaises(ImportError) as cm: - self.load_module(name) - self.assertEqual(cm.exception.name, name) - - def test_already_imported(self): - # Using the name of a module already imported but not a built-in should - # still fail. - module_name = 'builtin_reload_test' - assert module_name not in sys.builtin_module_names - with util.uncache(module_name): - module = types.ModuleType(module_name) - sys.modules[module_name] = module - with self.assertRaises(ImportError) as cm: - self.load_module(module_name) - self.assertEqual(cm.exception.name, module_name) - - -(Frozen_LoaderTests, - Source_LoaderTests - ) = util.test_both(LoaderTests, machinery=machinery) - @unittest.skipIf(util.BUILTINS.good_name is None, 'no reasonable builtin module') class InspectLoaderTests: diff --git a/Lib/test/test_importlib/data/example-21.12-py3-none-any.whl b/Lib/test/test_importlib/data/example-21.12-py3-none-any.whl deleted file mode 100644 index 641ab07f7aa..00000000000 Binary files a/Lib/test/test_importlib/data/example-21.12-py3-none-any.whl and /dev/null differ diff --git a/Lib/test/test_importlib/data/example-21.12-py3.6.egg b/Lib/test/test_importlib/data/example-21.12-py3.6.egg deleted file mode 100644 index cdb298a19b0..00000000000 Binary files a/Lib/test/test_importlib/data/example-21.12-py3.6.egg and /dev/null differ diff --git a/Lib/test/test_importlib/data/example2-1.0.0-py3-none-any.whl b/Lib/test/test_importlib/data/example2-1.0.0-py3-none-any.whl deleted file mode 100644 index 5ca93657f81..00000000000 Binary files a/Lib/test/test_importlib/data/example2-1.0.0-py3-none-any.whl and /dev/null differ diff --git a/Lib/test/test_importlib/data01/binary.file b/Lib/test/test_importlib/data01/binary.file deleted file mode 100644 index eaf36c1dacc..00000000000 Binary files a/Lib/test/test_importlib/data01/binary.file and /dev/null differ diff --git a/Lib/test/test_importlib/data01/subdirectory/binary.file b/Lib/test/test_importlib/data01/subdirectory/binary.file deleted file mode 100644 index eaf36c1dacc..00000000000 Binary files a/Lib/test/test_importlib/data01/subdirectory/binary.file and /dev/null differ diff --git a/Lib/test/test_importlib/data01/utf-16.file b/Lib/test/test_importlib/data01/utf-16.file deleted file mode 100644 index 2cb772295ef..00000000000 Binary files a/Lib/test/test_importlib/data01/utf-16.file and /dev/null differ diff --git a/Lib/test/test_importlib/extension/test_finder.py b/Lib/test/test_importlib/extension/test_finder.py index cdc8884d668..e33c0465654 100644 --- a/Lib/test/test_importlib/extension/test_finder.py +++ b/Lib/test/test_importlib/extension/test_finder.py @@ -1,10 +1,11 @@ -from test.support import is_apple_mobile +from test.support import is_apple_mobile, Py_GIL_DISABLED from test.test_importlib import abc, util machinery = util.import_importlib('importlib.machinery') import unittest import sys +import sysconfig class FinderTests(abc.FinderTests): @@ -59,6 +60,28 @@ def test_module(self): def test_failure(self): self.assertIsNone(self.find_spec('asdfjkl;')) + def test_abi3_extension_suffixes(self): + suffixes = self.machinery.EXTENSION_SUFFIXES + platform = sysconfig.get_config_var("SOABI_PLATFORM") + if 'win32' in sys.platform: + # Either "_d.pyd" or ".pyd" must be in suffixes + self.assertTrue({"_d.pyd", ".pyd"}.intersection(suffixes)) + elif 'cygwin' in sys.platform: + pass + else: + if Py_GIL_DISABLED: + self.assertNotIn(".abi3.so", suffixes) + else: + self.assertIn(".abi3.so", suffixes) + self.assertIn(".abi3t.so", suffixes) + + if platform: + if Py_GIL_DISABLED: + self.assertNotIn(f".abi3-{platform}.so", suffixes) + else: + self.assertIn(f".abi3-{platform}.so", suffixes) + self.assertIn(f".abi3t-{platform}.so", suffixes) + (Frozen_FinderTests, Source_FinderTests diff --git a/Lib/test/test_importlib/extension/test_loader.py b/Lib/test/test_importlib/extension/test_loader.py index 0dd21e079eb..15d5a7d4752 100644 --- a/Lib/test/test_importlib/extension/test_loader.py +++ b/Lib/test/test_importlib/extension/test_loader.py @@ -35,11 +35,6 @@ def setUp(self): self.loader = self.LoaderClass(util.EXTENSIONS.name, util.EXTENSIONS.file_path) - def load_module(self, fullname): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - return self.loader.load_module(fullname) - def test_equality(self): other = self.LoaderClass(util.EXTENSIONS.name, util.EXTENSIONS.file_path) self.assertEqual(self.loader, other) @@ -48,25 +43,6 @@ def test_inequality(self): other = self.LoaderClass('_' + util.EXTENSIONS.name, util.EXTENSIONS.file_path) self.assertNotEqual(self.loader, other) - def test_load_module_API(self): - # Test the default argument for load_module(). - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - self.loader.load_module() - self.loader.load_module(None) - with self.assertRaises(ImportError): - self.load_module('XXX') - - def test_module(self): - with util.uncache(util.EXTENSIONS.name): - module = self.load_module(util.EXTENSIONS.name) - for attr, value in [('__name__', util.EXTENSIONS.name), - ('__file__', util.EXTENSIONS.file_path), - ('__package__', '')]: - self.assertEqual(getattr(module, attr), value) - self.assertIn(util.EXTENSIONS.name, sys.modules) - self.assertIsInstance(module.__loader__, self.LoaderClass) - # No extension module as __init__ available for testing. test_package = None @@ -76,18 +52,6 @@ def test_module(self): # No easy way to trigger a failure after a successful import. test_state_after_failure = None - def test_unloadable(self): - name = 'asdfjkl;' - with self.assertRaises(ImportError) as cm: - self.load_module(name) - self.assertEqual(cm.exception.name, name) - - def test_module_reuse(self): - with util.uncache(util.EXTENSIONS.name): - module1 = self.load_module(util.EXTENSIONS.name) - module2 = self.load_module(util.EXTENSIONS.name) - self.assertIs(module1, module2) - def test_is_package(self): self.assertFalse(self.loader.is_package(util.EXTENSIONS.name)) for suffix in self.machinery.EXTENSION_SUFFIXES: @@ -126,11 +90,6 @@ def setUp(self): self.loader = self.LoaderClass(self.name, self.spec.origin) - def load_module(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - return self.loader.load_module(self.name) - def load_module_by_name(self, fullname): # Load a module from the test extension by name. origin = self.spec.origin @@ -140,19 +99,6 @@ def load_module_by_name(self, fullname): loader.exec_module(module) return module - def test_module(self): - # Test loading an extension module. - with util.uncache(self.name): - module = self.load_module() - for attr, value in [('__name__', self.name), - ('__file__', self.spec.origin), - ('__package__', '')]: - self.assertEqual(getattr(module, attr), value) - with self.assertRaises(AttributeError): - module.__path__ - self.assertIs(module, sys.modules[self.name]) - self.assertIsInstance(module.__loader__, self.LoaderClass) - # No extension module as __init__ available for testing. test_package = None @@ -213,12 +159,6 @@ def setUp(self): assert self.spec self.loader = self.LoaderClass(self.name, self.spec.origin) - def load_module(self): - # Load the module from the test extension. - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - return self.loader.load_module(self.name) - def load_module_by_name(self, fullname): # Load a module from the test extension by name. origin = self.spec.origin @@ -237,60 +177,6 @@ def load_module_by_name(self, fullname): # Handling failure on reload is the up to the module. test_state_after_failure = None - def test_module(self): - # Test loading an extension module. - with util.uncache(self.name): - module = self.load_module() - for attr, value in [('__name__', self.name), - ('__file__', self.spec.origin), - ('__package__', '')]: - self.assertEqual(getattr(module, attr), value) - with self.assertRaises(AttributeError): - module.__path__ - self.assertIs(module, sys.modules[self.name]) - self.assertIsInstance(module.__loader__, self.LoaderClass) - - def test_functionality(self): - # Test basic functionality of stuff defined in an extension module. - with util.uncache(self.name): - module = self.load_module() - self.assertIsInstance(module, types.ModuleType) - ex = module.Example() - self.assertEqual(ex.demo('abcd'), 'abcd') - self.assertEqual(ex.demo(), None) - with self.assertRaises(AttributeError): - ex.abc - ex.abc = 0 - self.assertEqual(ex.abc, 0) - self.assertEqual(module.foo(9, 9), 18) - self.assertIsInstance(module.Str(), str) - self.assertEqual(module.Str(1) + '23', '123') - with self.assertRaises(module.error): - raise module.error() - self.assertEqual(module.int_const, 1969) - self.assertEqual(module.str_const, 'something different') - - def test_reload(self): - # Test that reload didn't re-set the module's attributes. - with util.uncache(self.name): - module = self.load_module() - ex_class = module.Example - importlib.reload(module) - self.assertIs(ex_class, module.Example) - - def test_try_registration(self): - # Assert that the PyState_{Find,Add,Remove}Module C API doesn't work. - with util.uncache(self.name): - module = self.load_module() - with self.subTest('PyState_FindModule'): - self.assertEqual(module.call_state_registration_func(0), None) - with self.subTest('PyState_AddModule'): - with self.assertRaises(SystemError): - module.call_state_registration_func(1) - with self.subTest('PyState_RemoveModule'): - with self.assertRaises(SystemError): - module.call_state_registration_func(2) - def test_load_submodule(self): # Test loading a simulated submodule. module = self.load_module_by_name('pkg.' + self.name) diff --git a/Lib/test/test_importlib/fixtures.py b/Lib/test/test_importlib/fixtures.py deleted file mode 100644 index 73e5da2ba92..00000000000 --- a/Lib/test/test_importlib/fixtures.py +++ /dev/null @@ -1,382 +0,0 @@ -import os -import sys -import copy -import shutil -import pathlib -import tempfile -import textwrap -import functools -import contextlib - -from test.support.os_helper import FS_NONASCII -from test.support import requires_zlib - -from . import _path -from ._path import FilesSpec - - -try: - from importlib import resources # type: ignore - - getattr(resources, 'files') - getattr(resources, 'as_file') -except (ImportError, AttributeError): - import importlib_resources as resources # type: ignore - - -@contextlib.contextmanager -def tempdir(): - tmpdir = tempfile.mkdtemp() - try: - yield pathlib.Path(tmpdir) - finally: - shutil.rmtree(tmpdir) - - -@contextlib.contextmanager -def save_cwd(): - orig = os.getcwd() - try: - yield - finally: - os.chdir(orig) - - -@contextlib.contextmanager -def tempdir_as_cwd(): - with tempdir() as tmp: - with save_cwd(): - os.chdir(str(tmp)) - yield tmp - - -@contextlib.contextmanager -def install_finder(finder): - sys.meta_path.append(finder) - try: - yield - finally: - sys.meta_path.remove(finder) - - -class Fixtures: - def setUp(self): - self.fixtures = contextlib.ExitStack() - self.addCleanup(self.fixtures.close) - - -class SiteDir(Fixtures): - def setUp(self): - super().setUp() - self.site_dir = self.fixtures.enter_context(tempdir()) - - -class OnSysPath(Fixtures): - @staticmethod - @contextlib.contextmanager - def add_sys_path(dir): - sys.path[:0] = [str(dir)] - try: - yield - finally: - sys.path.remove(str(dir)) - - def setUp(self): - super().setUp() - self.fixtures.enter_context(self.add_sys_path(self.site_dir)) - - -class DistInfoPkg(OnSysPath, SiteDir): - files: FilesSpec = { - "distinfo_pkg-1.0.0.dist-info": { - "METADATA": """ - Name: distinfo-pkg - Author: Steven Ma - Version: 1.0.0 - Requires-Dist: wheel >= 1.0 - Requires-Dist: pytest; extra == 'test' - Keywords: sample package - - Once upon a time - There was a distinfo pkg - """, - "RECORD": "mod.py,sha256=abc,20\n", - "entry_points.txt": """ - [entries] - main = mod:main - ns:sub = mod:main - """, - }, - "mod.py": """ - def main(): - print("hello world") - """, - } - - def setUp(self): - super().setUp() - build_files(DistInfoPkg.files, self.site_dir) - - def make_uppercase(self): - """ - Rewrite metadata with everything uppercase. - """ - shutil.rmtree(self.site_dir / "distinfo_pkg-1.0.0.dist-info") - files = copy.deepcopy(DistInfoPkg.files) - info = files["distinfo_pkg-1.0.0.dist-info"] - info["METADATA"] = info["METADATA"].upper() - build_files(files, self.site_dir) - - -class DistInfoPkgWithDot(OnSysPath, SiteDir): - files: FilesSpec = { - "pkg_dot-1.0.0.dist-info": { - "METADATA": """ - Name: pkg.dot - Version: 1.0.0 - """, - }, - } - - def setUp(self): - super().setUp() - build_files(DistInfoPkgWithDot.files, self.site_dir) - - -class DistInfoPkgWithDotLegacy(OnSysPath, SiteDir): - files: FilesSpec = { - "pkg.dot-1.0.0.dist-info": { - "METADATA": """ - Name: pkg.dot - Version: 1.0.0 - """, - }, - "pkg.lot.egg-info": { - "METADATA": """ - Name: pkg.lot - Version: 1.0.0 - """, - }, - } - - def setUp(self): - super().setUp() - build_files(DistInfoPkgWithDotLegacy.files, self.site_dir) - - -class DistInfoPkgOffPath(SiteDir): - def setUp(self): - super().setUp() - build_files(DistInfoPkg.files, self.site_dir) - - -class EggInfoPkg(OnSysPath, SiteDir): - files: FilesSpec = { - "egginfo_pkg.egg-info": { - "PKG-INFO": """ - Name: egginfo-pkg - Author: Steven Ma - License: Unknown - Version: 1.0.0 - Classifier: Intended Audience :: Developers - Classifier: Topic :: Software Development :: Libraries - Keywords: sample package - Description: Once upon a time - There was an egginfo package - """, - "SOURCES.txt": """ - mod.py - egginfo_pkg.egg-info/top_level.txt - """, - "entry_points.txt": """ - [entries] - main = mod:main - """, - "requires.txt": """ - wheel >= 1.0; python_version >= "2.7" - [test] - pytest - """, - "top_level.txt": "mod\n", - }, - "mod.py": """ - def main(): - print("hello world") - """, - } - - def setUp(self): - super().setUp() - build_files(EggInfoPkg.files, prefix=self.site_dir) - - -class EggInfoPkgPipInstalledNoToplevel(OnSysPath, SiteDir): - files: FilesSpec = { - "egg_with_module_pkg.egg-info": { - "PKG-INFO": "Name: egg_with_module-pkg", - # SOURCES.txt is made from the source archive, and contains files - # (setup.py) that are not present after installation. - "SOURCES.txt": """ - egg_with_module.py - setup.py - egg_with_module_pkg.egg-info/PKG-INFO - egg_with_module_pkg.egg-info/SOURCES.txt - egg_with_module_pkg.egg-info/top_level.txt - """, - # installed-files.txt is written by pip, and is a strictly more - # accurate source than SOURCES.txt as to the installed contents of - # the package. - "installed-files.txt": """ - ../egg_with_module.py - PKG-INFO - SOURCES.txt - top_level.txt - """, - # missing top_level.txt (to trigger fallback to installed-files.txt) - }, - "egg_with_module.py": """ - def main(): - print("hello world") - """, - } - - def setUp(self): - super().setUp() - build_files(EggInfoPkgPipInstalledNoToplevel.files, prefix=self.site_dir) - - -class EggInfoPkgPipInstalledNoModules(OnSysPath, SiteDir): - files: FilesSpec = { - "egg_with_no_modules_pkg.egg-info": { - "PKG-INFO": "Name: egg_with_no_modules-pkg", - # SOURCES.txt is made from the source archive, and contains files - # (setup.py) that are not present after installation. - "SOURCES.txt": """ - setup.py - egg_with_no_modules_pkg.egg-info/PKG-INFO - egg_with_no_modules_pkg.egg-info/SOURCES.txt - egg_with_no_modules_pkg.egg-info/top_level.txt - """, - # installed-files.txt is written by pip, and is a strictly more - # accurate source than SOURCES.txt as to the installed contents of - # the package. - "installed-files.txt": """ - PKG-INFO - SOURCES.txt - top_level.txt - """, - # top_level.txt correctly reflects that no modules are installed - "top_level.txt": b"\n", - }, - } - - def setUp(self): - super().setUp() - build_files(EggInfoPkgPipInstalledNoModules.files, prefix=self.site_dir) - - -class EggInfoPkgSourcesFallback(OnSysPath, SiteDir): - files: FilesSpec = { - "sources_fallback_pkg.egg-info": { - "PKG-INFO": "Name: sources_fallback-pkg", - # SOURCES.txt is made from the source archive, and contains files - # (setup.py) that are not present after installation. - "SOURCES.txt": """ - sources_fallback.py - setup.py - sources_fallback_pkg.egg-info/PKG-INFO - sources_fallback_pkg.egg-info/SOURCES.txt - """, - # missing installed-files.txt (i.e. not installed by pip) and - # missing top_level.txt (to trigger fallback to SOURCES.txt) - }, - "sources_fallback.py": """ - def main(): - print("hello world") - """, - } - - def setUp(self): - super().setUp() - build_files(EggInfoPkgSourcesFallback.files, prefix=self.site_dir) - - -class EggInfoFile(OnSysPath, SiteDir): - files: FilesSpec = { - "egginfo_file.egg-info": """ - Metadata-Version: 1.0 - Name: egginfo_file - Version: 0.1 - Summary: An example package - Home-page: www.example.com - Author: Eric Haffa-Vee - Author-email: eric@example.coms - License: UNKNOWN - Description: UNKNOWN - Platform: UNKNOWN - """, - } - - def setUp(self): - super().setUp() - build_files(EggInfoFile.files, prefix=self.site_dir) - - -# dedent all text strings before writing -orig = _path.create.registry[str] -_path.create.register(str, lambda content, path: orig(DALS(content), path)) - - -build_files = _path.build - - -def build_record(file_defs): - return ''.join(f'{name},,\n' for name in record_names(file_defs)) - - -def record_names(file_defs): - recording = _path.Recording() - _path.build(file_defs, recording) - return recording.record - - -class FileBuilder: - def unicode_filename(self): - return FS_NONASCII or self.skip("File system does not support non-ascii.") - - -def DALS(str): - "Dedent and left-strip" - return textwrap.dedent(str).lstrip() - - -@requires_zlib() -class ZipFixtures: - root = 'test.test_importlib.data' - - def _fixture_on_path(self, filename): - pkg_file = resources.files(self.root).joinpath(filename) - file = self.resources.enter_context(resources.as_file(pkg_file)) - assert file.name.startswith('example'), file.name - sys.path.insert(0, str(file)) - self.resources.callback(sys.path.pop, 0) - - def setUp(self): - # Add self.zip_name to the front of sys.path. - self.resources = contextlib.ExitStack() - self.addCleanup(self.resources.close) - - -def parameterize(*args_set): - """Run test method with a series of parameters.""" - - def wrapper(func): - @functools.wraps(func) - def _inner(self): - for args in args_set: - with self.subTest(**args): - func(self, **args) - - return _inner - - return wrapper diff --git a/Lib/test/test_importlib/import_/test_api.py b/Lib/test/test_importlib/import_/test_api.py index d6ad590b3d4..ea1e29a4e5f 100644 --- a/Lib/test/test_importlib/import_/test_api.py +++ b/Lib/test/test_importlib/import_/test_api.py @@ -27,13 +27,6 @@ def exec_module(module): raise ImportError('I cannot be loaded!') -class BadLoaderFinder: - @classmethod - def load_module(cls, fullname): - if fullname == SUBMOD_NAME: - raise ImportError('I cannot be loaded!') - - class APITest: """Test API-specific details for __import__ (e.g. raising the right @@ -93,45 +86,6 @@ def test_blocked_fromlist(self): self.assertEqual(cm.exception.name, SUBMOD_NAME) -class OldAPITests(APITest): - bad_finder_loader = BadLoaderFinder - - def test_raises_ModuleNotFoundError(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - super().test_raises_ModuleNotFoundError() - - def test_name_requires_rparition(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - super().test_name_requires_rparition() - - def test_negative_level(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - super().test_negative_level() - - def test_nonexistent_fromlist_entry(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - super().test_nonexistent_fromlist_entry() - - def test_fromlist_load_error_propagates(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - super().test_fromlist_load_error_propagates - - def test_blocked_fromlist(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - super().test_blocked_fromlist() - - -(Frozen_OldAPITests, - Source_OldAPITests - ) = util.test_both(OldAPITests, __import__=util.__import__) - - class SpecAPITests(APITest): bad_finder_loader = BadSpecFinderLoader diff --git a/Lib/test/test_importlib/import_/test_helpers.py b/Lib/test/test_importlib/import_/test_helpers.py index 550f88d1d7a..7587276a41e 100644 --- a/Lib/test/test_importlib/import_/test_helpers.py +++ b/Lib/test/test_importlib/import_/test_helpers.py @@ -19,8 +19,7 @@ def test_no_loader_but_spec(self): ns = {"__spec__": spec} _bootstrap_external._fix_up_module(ns, name, path) - expected = {"__spec__": spec, "__loader__": loader, "__file__": path, - "__cached__": None} + expected = {"__spec__": spec, "__loader__": loader, "__file__": path} self.assertEqual(ns, expected) def test_no_loader_no_spec_but_sourceless(self): @@ -29,7 +28,7 @@ def test_no_loader_no_spec_but_sourceless(self): ns = {} _bootstrap_external._fix_up_module(ns, name, path, path) - expected = {"__file__": path, "__cached__": path} + expected = {"__file__": path} for key, val in expected.items(): with self.subTest(f"{key}: {val}"): @@ -51,7 +50,7 @@ def test_no_loader_no_spec_but_source(self): ns = {} _bootstrap_external._fix_up_module(ns, name, path) - expected = {"__file__": path, "__cached__": None} + expected = {"__file__": path} for key, val in expected.items(): with self.subTest(f"{key}: {val}"): diff --git a/Lib/test/test_importlib/import_/test_packages.py b/Lib/test/test_importlib/import_/test_packages.py index 0c29d608326..10ca5ce2d5a 100644 --- a/Lib/test/test_importlib/import_/test_packages.py +++ b/Lib/test/test_importlib/import_/test_packages.py @@ -1,5 +1,6 @@ from test.test_importlib import util import sys +import types import unittest from test.support import import_helper @@ -100,6 +101,21 @@ def module_injection(): finally: import_helper.unload(subname) + def test_missing_grandparent_not_imported(self): + # Only the immediate parent has to be present. With a hand-made + # 'pkg.sub' package in sys.modules and no 'pkg' at all, importing + # pkg.sub.mod must neither fail nor try to import 'pkg'. + parent = types.ModuleType('pkg.sub') + parent.__path__ = [] + with util.mock_spec('pkg.sub.mod') as mock: + with util.import_state(meta_path=[mock]): + with util.uncache('pkg', 'pkg.sub', 'pkg.sub.mod'): + sys.modules['pkg.sub'] = parent + module = self.__import__('pkg.sub.mod', fromlist=['*']) + self.assertEqual(module.__name__, 'pkg.sub.mod') + self.assertIs(parent.mod, module) + self.assertNotIn('pkg', sys.modules) + (Frozen_ParentTests, Source_ParentTests diff --git a/Lib/test/test_importlib/metadata/__init__.py b/Lib/test/test_importlib/metadata/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/Lib/test/test_importlib/metadata/__init__.py +++ b/Lib/test/test_importlib/metadata/__init__.py @@ -1 +0,0 @@ - diff --git a/Lib/test/test_importlib/metadata/_path.py b/Lib/test/test_importlib/metadata/_path.py index b3cfb9cd549..e63d889f96b 100644 --- a/Lib/test/test_importlib/metadata/_path.py +++ b/Lib/test/test_importlib/metadata/_path.py @@ -1,9 +1,14 @@ -# from jaraco.path 3.7 +# from jaraco.path 3.7.2 + +from __future__ import annotations import functools import pathlib -from typing import Dict, Protocol, Union -from typing import runtime_checkable +from collections.abc import Mapping +from typing import TYPE_CHECKING, Protocol, Union, runtime_checkable + +if TYPE_CHECKING: + from typing_extensions import Self class Symlink(str): @@ -12,29 +17,25 @@ class Symlink(str): """ -FilesSpec = Dict[str, Union[str, bytes, Symlink, 'FilesSpec']] # type: ignore +FilesSpec = Mapping[str, Union[str, bytes, Symlink, 'FilesSpec']] @runtime_checkable class TreeMaker(Protocol): - def __truediv__(self, *args, **kwargs): ... # pragma: no cover - - def mkdir(self, **kwargs): ... # pragma: no cover - - def write_text(self, content, **kwargs): ... # pragma: no cover - - def write_bytes(self, content): ... # pragma: no cover - - def symlink_to(self, target): ... # pragma: no cover + def __truediv__(self, other, /) -> Self: ... + def mkdir(self, *, exist_ok) -> object: ... + def write_text(self, content, /, *, encoding) -> object: ... + def write_bytes(self, content, /) -> object: ... + def symlink_to(self, target, /) -> object: ... -def _ensure_tree_maker(obj: Union[str, TreeMaker]) -> TreeMaker: - return obj if isinstance(obj, TreeMaker) else pathlib.Path(obj) # type: ignore +def _ensure_tree_maker(obj: str | TreeMaker) -> TreeMaker: + return obj if isinstance(obj, TreeMaker) else pathlib.Path(obj) def build( spec: FilesSpec, - prefix: Union[str, TreeMaker] = pathlib.Path(), # type: ignore + prefix: str | TreeMaker = pathlib.Path(), ): """ Build a set of files/directories, as described by the spec. @@ -66,23 +67,24 @@ def build( @functools.singledispatch -def create(content: Union[str, bytes, FilesSpec], path): +def create(content: str | bytes | FilesSpec, path: TreeMaker) -> None: path.mkdir(exist_ok=True) - build(content, prefix=path) # type: ignore + # Mypy only looks at the signature of the main singledispatch method. So it must contain the complete Union + build(content, prefix=path) # type: ignore[arg-type] # python/mypy#11727 @create.register -def _(content: bytes, path): +def _(content: bytes, path: TreeMaker) -> None: path.write_bytes(content) @create.register -def _(content: str, path): +def _(content: str, path: TreeMaker) -> None: path.write_text(content, encoding='utf-8') @create.register -def _(content: Symlink, path): +def _(content: Symlink, path: TreeMaker) -> None: path.symlink_to(content) diff --git a/Lib/test/test_importlib/metadata/data/__init__.py b/Lib/test/test_importlib/metadata/data/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/Lib/test/test_importlib/metadata/data/__init__.py +++ b/Lib/test/test_importlib/metadata/data/__init__.py @@ -1 +0,0 @@ - diff --git a/Lib/test/test_importlib/metadata/fixtures.py b/Lib/test/test_importlib/metadata/fixtures.py index 826b1b3259b..3283697d418 100644 --- a/Lib/test/test_importlib/metadata/fixtures.py +++ b/Lib/test/test_importlib/metadata/fixtures.py @@ -1,11 +1,12 @@ -import sys +import contextlib import copy +import functools import json -import shutil import pathlib +import shutil +import sys import textwrap -import functools -import contextlib +from importlib import resources from test.support import import_helper from test.support import os_helper @@ -15,15 +16,6 @@ from ._path import FilesSpec -try: - from importlib import resources # type: ignore - - getattr(resources, 'files') - getattr(resources, 'as_file') -except (ImportError, AttributeError): - import importlib_resources as resources # type: ignore - - @contextlib.contextmanager def tmp_path(): """ diff --git a/Lib/test/test_importlib/metadata/test_api.py b/Lib/test/test_importlib/metadata/test_api.py index 2256e0c502e..5449f048449 100644 --- a/Lib/test/test_importlib/metadata/test_api.py +++ b/Lib/test/test_importlib/metadata/test_api.py @@ -1,14 +1,12 @@ +import importlib import re import textwrap import unittest -import warnings -import importlib -import contextlib -from . import fixtures from importlib.metadata import ( Distribution, PackageNotFoundError, + Prepared, distribution, entry_points, files, @@ -17,12 +15,7 @@ version, ) - -@contextlib.contextmanager -def suppress_known_deprecation(): - with warnings.catch_warnings(record=True) as ctx: - warnings.simplefilter('default', category=DeprecationWarning) - yield ctx +from . import fixtures class APITests( @@ -153,13 +146,13 @@ def test_metadata_for_this_package(self): classifiers = md.get_all('Classifier') assert 'Topic :: Software Development :: Libraries' in classifiers - def test_missing_key_legacy(self): + def test_missing_key(self): """ - Requesting a missing key will still return None, but warn. + Requesting a missing key raises KeyError. """ md = metadata('distinfo-pkg') - with suppress_known_deprecation(): - assert md['does-not-exist'] is None + with self.assertRaises(KeyError): + md['does-not-exist'] def test_get_key(self): """ @@ -321,3 +314,34 @@ class InvalidateCache(unittest.TestCase): def test_invalidate_cache(self): # No externally observable behavior, but ensures test coverage... importlib.invalidate_caches() + + +class PreparedTests(unittest.TestCase): + @fixtures.parameterize( + # Simple + dict(input='sample', expected='sample'), + # Mixed case + dict(input='Sample', expected='sample'), + dict(input='SAMPLE', expected='sample'), + dict(input='SaMpLe', expected='sample'), + # Separator conversions + dict(input='sample-pkg', expected='sample_pkg'), + dict(input='sample.pkg', expected='sample_pkg'), + dict(input='sample_pkg', expected='sample_pkg'), + # Multiple separators + dict(input='sample---pkg', expected='sample_pkg'), + dict(input='sample___pkg', expected='sample_pkg'), + dict(input='sample...pkg', expected='sample_pkg'), + # Mixed separators + dict(input='sample-._pkg', expected='sample_pkg'), + dict(input='sample_.-pkg', expected='sample_pkg'), + # Complex + dict(input='Sample__Pkg-name.foo', expected='sample_pkg_name_foo'), + dict(input='Sample__Pkg.name__foo', expected='sample_pkg_name_foo'), + # Uppercase with separators + dict(input='SAMPLE-PKG', expected='sample_pkg'), + dict(input='Sample.Pkg', expected='sample_pkg'), + dict(input='SAMPLE_PKG', expected='sample_pkg'), + ) + def test_normalize(self, input, expected): + self.assertEqual(Prepared.normalize(input), expected) diff --git a/Lib/test/test_importlib/metadata/test_main.py b/Lib/test/test_importlib/metadata/test_main.py index e4218076f8c..aae052160d9 100644 --- a/Lib/test/test_importlib/metadata/test_main.py +++ b/Lib/test/test_importlib/metadata/test_main.py @@ -1,23 +1,18 @@ -import re +import importlib import pickle +import re import unittest -import warnings -import importlib -import importlib.metadata -import contextlib -from test.support import os_helper try: import pyfakefs.fake_filesystem_unittest as ffs except ImportError: from .stubs import fake_filesystem_unittest as ffs +from test.support import os_helper -from . import fixtures -from ._context import suppress -from ._path import Symlink from importlib.metadata import ( Distribution, EntryPoint, + MetadataNotFound, PackageNotFoundError, _unique, distributions, @@ -27,12 +22,8 @@ version, ) - -@contextlib.contextmanager -def suppress_known_deprecation(): - with warnings.catch_warnings(record=True) as ctx: - warnings.simplefilter('default', category=DeprecationWarning) - yield ctx +from . import fixtures +from ._path import Symlink class BasicTests(fixtures.DistInfoPkg, unittest.TestCase): @@ -59,9 +50,6 @@ def test_package_not_found_mentions_metadata(self): assert "metadata" in str(ctx.exception) - # expected to fail until ABC is enforced - @suppress(AssertionError) - @suppress_known_deprecation() def test_abc_enforced(self): with self.assertRaises(TypeError): type('DistributionSubclass', (Distribution,), {})() @@ -146,6 +134,43 @@ def test_unique_distributions(self): assert len(after) == len(before) +class InvalidMetadataTests(fixtures.OnSysPath, fixtures.SiteDir, unittest.TestCase): + @staticmethod + def make_pkg(name, files=dict(METADATA="VERSION: 1.0")): + """ + Create metadata for a dist-info package with name and files. + """ + return { + f'{name}.dist-info': files, + } + + def test_valid_dists_preferred(self): + """ + Dists with metadata should be preferred when discovered by name. + + Ref python/importlib_metadata#489. + """ + # create three dists with the valid one in the middle (lexicographically) + # such that on most file systems, the valid one is never naturally first. + fixtures.build_files(self.make_pkg('foo-4.0', files={}), self.site_dir) + fixtures.build_files(self.make_pkg('foo-4.1'), self.site_dir) + fixtures.build_files(self.make_pkg('foo-4.2', files={}), self.site_dir) + dist = Distribution.from_name('foo') + assert dist.version == "1.0" + + def test_missing_metadata(self): + """ + Dists with a missing metadata file should raise ``MetadataNotFound``. + + Ref python/importlib_metadata#493 and python/cpython#143387. + """ + fixtures.build_files(self.make_pkg('foo-4.3', files={}), self.site_dir) + with self.assertRaises(MetadataNotFound): + Distribution.from_name('foo').metadata + with self.assertRaises(MetadataNotFound): + metadata('foo') + + class NonASCIITests(fixtures.OnSysPath, fixtures.SiteDir, unittest.TestCase): @staticmethod def pkg_with_non_ascii_description(site_dir): diff --git a/Lib/test/test_importlib/metadata/test_zip.py b/Lib/test/test_importlib/metadata/test_zip.py index 276f6288c91..97168549667 100644 --- a/Lib/test/test_importlib/metadata/test_zip.py +++ b/Lib/test/test_importlib/metadata/test_zip.py @@ -1,8 +1,12 @@ +import multiprocessing +import os import sys import unittest -from . import fixtures +from test.support import requires_fork, warnings_helper + from importlib.metadata import ( + FastPath, PackageNotFoundError, distribution, distributions, @@ -11,6 +15,8 @@ version, ) +from . import fixtures + class TestZip(fixtures.ZipFixtures, unittest.TestCase): def setUp(self): @@ -46,6 +52,39 @@ def test_one_distribution(self): dists = list(distributions(path=sys.path[:1])) assert len(dists) == 1 + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() + @requires_fork() + @unittest.skipUnless( + hasattr(os, 'register_at_fork') + and 'fork' in multiprocessing.get_all_start_methods(), + 'requires fork-based multiprocessing support', + ) + def test_fastpath_cache_cleared_in_forked_child(self): + zip_path = sys.path[0] + + FastPath(zip_path) + assert FastPath.__new__.cache_info().currsize >= 1 + + ctx = multiprocessing.get_context('fork') + parent_conn, child_conn = ctx.Pipe() + + def child(conn, root): + try: + before = FastPath.__new__.cache_info().currsize + FastPath(root) + after = FastPath.__new__.cache_info().currsize + conn.send((before, after)) + finally: + conn.close() + + proc = ctx.Process(target=child, args=(child_conn, zip_path)) + proc.start() + child_conn.close() + cache_sizes = parent_conn.recv() + proc.join() + + self.assertEqual(cache_sizes, (0, 1)) + class TestEgg(TestZip): def setUp(self): diff --git a/Lib/test/test_importlib/namespace_pkgs/foo/README.md b/Lib/test/test_importlib/namespace_pkgs/foo/README.md new file mode 100644 index 00000000000..9f6bc74941d --- /dev/null +++ b/Lib/test/test_importlib/namespace_pkgs/foo/README.md @@ -0,0 +1,2 @@ +This directory should not be a package, but should share a name with an +unrelated subpackage. diff --git a/Lib/test/test_importlib/namespace_pkgs/not_a_namespace_pkg/foo/__init__.py b/Lib/test/test_importlib/namespace_pkgs/not_a_namespace_pkg/foo/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/Lib/test/test_importlib/namespace_pkgs/not_a_namespace_pkg/foo/__init__.py +++ b/Lib/test/test_importlib/namespace_pkgs/not_a_namespace_pkg/foo/__init__.py @@ -1 +0,0 @@ - diff --git a/Lib/test/test_importlib/namespacedata01/binary.file b/Lib/test/test_importlib/namespacedata01/binary.file deleted file mode 100644 index eaf36c1dacc..00000000000 Binary files a/Lib/test/test_importlib/namespacedata01/binary.file and /dev/null differ diff --git a/Lib/test/test_importlib/namespacedata01/utf-16.file b/Lib/test/test_importlib/namespacedata01/utf-16.file deleted file mode 100644 index 2cb772295ef..00000000000 Binary files a/Lib/test/test_importlib/namespacedata01/utf-16.file and /dev/null differ diff --git a/Lib/test/test_importlib/resources/__init__.py b/Lib/test/test_importlib/resources/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/Lib/test/test_importlib/resources/__init__.py +++ b/Lib/test/test_importlib/resources/__init__.py @@ -1 +0,0 @@ - diff --git a/Lib/test/test_importlib/resources/_path.py b/Lib/test/test_importlib/resources/_path.py index b144628cb73..3720af7c508 100644 --- a/Lib/test/test_importlib/resources/_path.py +++ b/Lib/test/test_importlib/resources/_path.py @@ -1,10 +1,6 @@ -import pathlib import functools - -from typing import Dict, Union -from typing import runtime_checkable -from typing import Protocol - +import pathlib +from typing import Protocol, Union, runtime_checkable #### # from jaraco.path 3.7.1 @@ -16,7 +12,7 @@ class Symlink(str): """ -FilesSpec = Dict[str, Union[str, bytes, Symlink, 'FilesSpec']] +FilesSpec = dict[str, Union[str, bytes, Symlink, 'FilesSpec']] @runtime_checkable @@ -32,13 +28,13 @@ def write_bytes(self, content): ... # pragma: no cover def symlink_to(self, target): ... # pragma: no cover -def _ensure_tree_maker(obj: Union[str, TreeMaker]) -> TreeMaker: +def _ensure_tree_maker(obj: str | TreeMaker) -> TreeMaker: return obj if isinstance(obj, TreeMaker) else pathlib.Path(obj) # type: ignore[return-value] def build( spec: FilesSpec, - prefix: Union[str, TreeMaker] = pathlib.Path(), # type: ignore[assignment] + prefix: str | TreeMaker = pathlib.Path(), # type: ignore[assignment] ): """ Build a set of files/directories, as described by the spec. @@ -70,7 +66,7 @@ def build( @functools.singledispatch -def create(content: Union[str, bytes, FilesSpec], path): +def create(content: str | bytes | FilesSpec, path): path.mkdir(exist_ok=True) build(content, prefix=path) # type: ignore[arg-type] diff --git a/Lib/test/test_importlib/resources/data01/binary.file b/Lib/test/test_importlib/resources/data01/binary.file deleted file mode 100644 index eaf36c1dacc..00000000000 Binary files a/Lib/test/test_importlib/resources/data01/binary.file and /dev/null differ diff --git a/Lib/test/test_importlib/resources/data01/subdirectory/binary.file b/Lib/test/test_importlib/resources/data01/subdirectory/binary.file deleted file mode 100644 index eaf36c1dacc..00000000000 Binary files a/Lib/test/test_importlib/resources/data01/subdirectory/binary.file and /dev/null differ diff --git a/Lib/test/test_importlib/resources/data01/utf-16.file b/Lib/test/test_importlib/resources/data01/utf-16.file deleted file mode 100644 index 2cb772295ef..00000000000 Binary files a/Lib/test/test_importlib/resources/data01/utf-16.file and /dev/null differ diff --git a/Lib/test/test_importlib/resources/data01/utf-8.file b/Lib/test/test_importlib/resources/data01/utf-8.file deleted file mode 100644 index 1c0132ad90a..00000000000 --- a/Lib/test/test_importlib/resources/data01/utf-8.file +++ /dev/null @@ -1 +0,0 @@ -Hello, UTF-8 world! diff --git a/Lib/test/test_importlib/resources/data02/one/resource1.txt b/Lib/test/test_importlib/resources/data02/one/resource1.txt deleted file mode 100644 index 61a813e4017..00000000000 --- a/Lib/test/test_importlib/resources/data02/one/resource1.txt +++ /dev/null @@ -1 +0,0 @@ -one resource diff --git a/Lib/test/test_importlib/resources/data02/subdirectory/subsubdir/resource.txt b/Lib/test/test_importlib/resources/data02/subdirectory/subsubdir/resource.txt deleted file mode 100644 index 48f587a2d0a..00000000000 --- a/Lib/test/test_importlib/resources/data02/subdirectory/subsubdir/resource.txt +++ /dev/null @@ -1 +0,0 @@ -a resource \ No newline at end of file diff --git a/Lib/test/test_importlib/resources/data02/two/__init__.py b/Lib/test/test_importlib/resources/data02/two/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Lib/test/test_importlib/resources/data02/two/resource2.txt b/Lib/test/test_importlib/resources/data02/two/resource2.txt deleted file mode 100644 index a80ce46ea36..00000000000 --- a/Lib/test/test_importlib/resources/data02/two/resource2.txt +++ /dev/null @@ -1 +0,0 @@ -two resource diff --git a/Lib/test/test_importlib/resources/data03/__init__.py b/Lib/test/test_importlib/resources/data03/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Lib/test/test_importlib/resources/data03/namespace/portion1/__init__.py b/Lib/test/test_importlib/resources/data03/namespace/portion1/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Lib/test/test_importlib/resources/data03/namespace/portion2/__init__.py b/Lib/test/test_importlib/resources/data03/namespace/portion2/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Lib/test/test_importlib/resources/data03/namespace/resource1.txt b/Lib/test/test_importlib/resources/data03/namespace/resource1.txt deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Lib/test/test_importlib/resources/namespacedata01/binary.file b/Lib/test/test_importlib/resources/namespacedata01/binary.file deleted file mode 100644 index eaf36c1dacc..00000000000 Binary files a/Lib/test/test_importlib/resources/namespacedata01/binary.file and /dev/null differ diff --git a/Lib/test/test_importlib/resources/namespacedata01/utf-16.file b/Lib/test/test_importlib/resources/namespacedata01/utf-16.file deleted file mode 100644 index 2cb772295ef..00000000000 Binary files a/Lib/test/test_importlib/resources/namespacedata01/utf-16.file and /dev/null differ diff --git a/Lib/test/test_importlib/resources/namespacedata01/utf-8.file b/Lib/test/test_importlib/resources/namespacedata01/utf-8.file deleted file mode 100644 index 1c0132ad90a..00000000000 --- a/Lib/test/test_importlib/resources/namespacedata01/utf-8.file +++ /dev/null @@ -1 +0,0 @@ -Hello, UTF-8 world! diff --git a/Lib/test/test_importlib/resources/test_compatibilty_files.py b/Lib/test/test_importlib/resources/test_compatibilty_files.py index bcf608d9e2c..2fd39bedf25 100644 --- a/Lib/test/test_importlib/resources/test_compatibilty_files.py +++ b/Lib/test/test_importlib/resources/test_compatibilty_files.py @@ -1,8 +1,6 @@ +import importlib.resources as resources import io import unittest - -from importlib import resources - from importlib.resources._adapters import ( CompatibilityFiles, wrap_spec, @@ -26,51 +24,46 @@ def files(self): return resources.files(self.package) def test_spec_path_iter(self): - self.assertEqual( - sorted(path.name for path in self.files.iterdir()), - ['a', 'b', 'c'], - ) + assert sorted(path.name for path in self.files.iterdir()) == ['a', 'b', 'c'] def test_child_path_iter(self): - self.assertEqual(list((self.files / 'a').iterdir()), []) + assert list((self.files / 'a').iterdir()) == [] def test_orphan_path_iter(self): - self.assertEqual(list((self.files / 'a' / 'a').iterdir()), []) - self.assertEqual(list((self.files / 'a' / 'a' / 'a').iterdir()), []) + assert list((self.files / 'a' / 'a').iterdir()) == [] + assert list((self.files / 'a' / 'a' / 'a').iterdir()) == [] def test_spec_path_is(self): - self.assertFalse(self.files.is_file()) - self.assertFalse(self.files.is_dir()) + assert not self.files.is_file() + assert not self.files.is_dir() def test_child_path_is(self): - self.assertTrue((self.files / 'a').is_file()) - self.assertFalse((self.files / 'a').is_dir()) + assert (self.files / 'a').is_file() + assert not (self.files / 'a').is_dir() def test_orphan_path_is(self): - self.assertFalse((self.files / 'a' / 'a').is_file()) - self.assertFalse((self.files / 'a' / 'a').is_dir()) - self.assertFalse((self.files / 'a' / 'a' / 'a').is_file()) - self.assertFalse((self.files / 'a' / 'a' / 'a').is_dir()) + assert not (self.files / 'a' / 'a').is_file() + assert not (self.files / 'a' / 'a').is_dir() + assert not (self.files / 'a' / 'a' / 'a').is_file() + assert not (self.files / 'a' / 'a' / 'a').is_dir() def test_spec_path_name(self): - self.assertEqual(self.files.name, 'testingpackage') + assert self.files.name == 'testingpackage' def test_child_path_name(self): - self.assertEqual((self.files / 'a').name, 'a') + assert (self.files / 'a').name == 'a' def test_orphan_path_name(self): - self.assertEqual((self.files / 'a' / 'b').name, 'b') - self.assertEqual((self.files / 'a' / 'b' / 'c').name, 'c') + assert (self.files / 'a' / 'b').name == 'b' + assert (self.files / 'a' / 'b' / 'c').name == 'c' def test_spec_path_open(self): - self.assertEqual(self.files.read_bytes(), b'Hello, world!') - self.assertEqual(self.files.read_text(encoding='utf-8'), 'Hello, world!') + assert self.files.read_bytes() == b'Hello, world!' + assert self.files.read_text(encoding='utf-8') == 'Hello, world!' def test_child_path_open(self): - self.assertEqual((self.files / 'a').read_bytes(), b'Hello, world!') - self.assertEqual( - (self.files / 'a').read_text(encoding='utf-8'), 'Hello, world!' - ) + assert (self.files / 'a').read_bytes() == b'Hello, world!' + assert (self.files / 'a').read_text(encoding='utf-8') == 'Hello, world!' def test_orphan_path_open(self): with self.assertRaises(FileNotFoundError): @@ -88,7 +81,7 @@ def test_orphan_path_invalid(self): def test_wrap_spec(self): spec = wrap_spec(self.package) - self.assertIsInstance(spec.loader.get_resource_reader(None), CompatibilityFiles) + assert isinstance(spec.loader.get_resource_reader(None), CompatibilityFiles) class CompatibilityFilesNoReaderTests(unittest.TestCase): @@ -101,4 +94,4 @@ def files(self): return resources.files(self.package) def test_spec_path_joinpath(self): - self.assertIsInstance(self.files / 'a', CompatibilityFiles.OrphanPath) + assert isinstance(self.files / 'a', CompatibilityFiles.OrphanPath) diff --git a/Lib/test/test_importlib/resources/test_contents.py b/Lib/test/test_importlib/resources/test_contents.py index 4e4e0e9c337..bdc158d85a2 100644 --- a/Lib/test/test_importlib/resources/test_contents.py +++ b/Lib/test/test_importlib/resources/test_contents.py @@ -1,5 +1,5 @@ +import importlib.resources as resources import unittest -from importlib import resources from . import util diff --git a/Lib/test/test_importlib/resources/test_custom.py b/Lib/test/test_importlib/resources/test_custom.py index 640f90fc0dd..a7fc6bc35c5 100644 --- a/Lib/test/test_importlib/resources/test_custom.py +++ b/Lib/test/test_importlib/resources/test_custom.py @@ -1,12 +1,12 @@ -import unittest import contextlib +import importlib.resources as resources import pathlib +import unittest +from importlib.resources import abc +from importlib.resources.abc import ResourceReader, TraversableResources from test.support import os_helper -from importlib import resources -from importlib.resources import abc -from importlib.resources.abc import TraversableResources, ResourceReader from . import util diff --git a/Lib/test/test_importlib/resources/test_files.py b/Lib/test/test_importlib/resources/test_files.py index 3ce44999f98..c922d32cedc 100644 --- a/Lib/test/test_importlib/resources/test_files.py +++ b/Lib/test/test_importlib/resources/test_files.py @@ -1,15 +1,16 @@ +import contextlib +import importlib +import importlib.resources as resources import pathlib import py_compile import textwrap import unittest import warnings -import importlib -import contextlib - -from importlib import resources from importlib.resources.abc import Traversable + +from test.support import import_helper, os_helper + from . import util -from test.support import os_helper, import_helper @contextlib.contextmanager @@ -36,15 +37,7 @@ def test_traversable(self): def test_joinpath_with_multiple_args(self): files = resources.files(self.data) binfile = files.joinpath('subdirectory', 'binary.file') - self.assertTrue(binfile.is_file()) - - def test_old_parameter(self): - """ - Files used to take a 'package' parameter. Make sure anyone - passing by name is still supported. - """ - with suppress_known_deprecation(): - resources.files(package=self.data) + assert binfile.is_file() class OpenDiskTests(FilesTests, util.DiskSetup, unittest.TestCase): @@ -70,7 +63,7 @@ def test_non_paths_in_dunder_path(self): to cause the ``PathEntryFinder`` to be called when searching for packages. In that case, resources should still be loadable. """ - import namespacedata01 + import namespacedata01 # type: ignore[import-not-found] namespacedata01.__path__.append( '__editable__.sample_namespace-1.0.finder.__path_hook__' @@ -161,7 +154,9 @@ def _compile_importlib(self): sources = pathlib.Path(resources.__file__).parent for source_path in sources.glob('**/*.py'): - c_path = c_resources.joinpath(source_path.relative_to(sources)).with_suffix('.pyc') + c_path = c_resources.joinpath(source_path.relative_to(sources)).with_suffix( + '.pyc' + ) py_compile.compile(source_path, c_path) self.fixtures.enter_context(import_helper.DirsOnSysPath(bin_site)) diff --git a/Lib/test/test_importlib/resources/test_functional.py b/Lib/test/test_importlib/resources/test_functional.py index e8d25fa4d9f..9cec6af9a5d 100644 --- a/Lib/test/test_importlib/resources/test_functional.py +++ b/Lib/test/test_importlib/resources/test_functional.py @@ -1,17 +1,12 @@ -import unittest -import os import importlib +import importlib.resources as resources +import os +import unittest from test.support import warnings_helper -from importlib import resources - from . import util -# Since the functional API forwards to Traversable, we only test -# filesystem resources here -- not zip files, namespace packages etc. -# We do test for two kinds of Anchor, though. - class StringAnchorMixin: anchor01 = 'data01' @@ -28,7 +23,7 @@ def anchor02(self): return importlib.import_module('data02') -class FunctionalAPIBase(util.DiskSetup): +class FunctionalAPIBase: def setUp(self): super().setUp() self.load_fixture('data02') @@ -43,83 +38,90 @@ def _gen_resourcetxt_path_parts(self): with self.subTest(path_parts=path_parts): yield path_parts + @staticmethod + def remove_utf16_bom(string): + """Remove an architecture-specific UTF-16 BOM prefix when present. + + Some platforms surface UTF-16 BOM bytes as escaped text when the + fixture is intentionally decoded as UTF-8 with ``errors='backslashreplace'``. + Strip that prefix so assertions validate content consistently.""" + for bom in ('\\xff\\xfe', '\\xfe\\xff', '\ufeff'): + if string.startswith(bom): + return string[len(bom) :] + return string + def test_read_text(self): - self.assertEqual( - resources.read_text(self.anchor01, 'utf-8.file'), - 'Hello, UTF-8 world!\n', + assert ( + resources.read_text(self.anchor01, 'utf-8.file') == 'Hello, UTF-8 world!\n' ) - self.assertEqual( + assert ( resources.read_text( self.anchor02, 'subdirectory', 'subsubdir', 'resource.txt', encoding='utf-8', - ), - 'a resource', + ) + == 'a resource' ) for path_parts in self._gen_resourcetxt_path_parts(): - self.assertEqual( + assert ( resources.read_text( self.anchor02, *path_parts, encoding='utf-8', - ), - 'a resource', + ) + == 'a resource' ) # Use generic OSError, since e.g. attempting to read a directory can # fail with PermissionError rather than IsADirectoryError with self.assertRaises(OSError): resources.read_text(self.anchor01) - with self.assertRaises(OSError): + with self.assertRaises((OSError, resources.abc.TraversalError)): resources.read_text(self.anchor01, 'no-such-file') with self.assertRaises(UnicodeDecodeError): resources.read_text(self.anchor01, 'utf-16.file') - self.assertEqual( + assert ( resources.read_text( self.anchor01, 'binary.file', encoding='latin1', - ), - '\x00\x01\x02\x03', + ) + == '\x00\x01\x02\x03' ) - self.assertEndsWith( # ignore the BOM + assert self.remove_utf16_bom( resources.read_text( self.anchor01, 'utf-16.file', errors='backslashreplace', ), - 'Hello, UTF-16 world!\n'.encode('utf-16-le').decode( - errors='backslashreplace', - ), + ) == 'Hello, UTF-16 world!\n'.encode('utf-16-le').decode( + errors='backslashreplace', ) def test_read_binary(self): - self.assertEqual( - resources.read_binary(self.anchor01, 'utf-8.file'), - b'Hello, UTF-8 world!\n', + assert ( + resources.read_binary(self.anchor01, 'utf-8.file') + == b'Hello, UTF-8 world!\n' ) for path_parts in self._gen_resourcetxt_path_parts(): - self.assertEqual( - resources.read_binary(self.anchor02, *path_parts), - b'a resource', - ) + assert resources.read_binary(self.anchor02, *path_parts) == b'a resource' def test_open_text(self): with resources.open_text(self.anchor01, 'utf-8.file') as f: - self.assertEqual(f.read(), 'Hello, UTF-8 world!\n') + assert f.read() == 'Hello, UTF-8 world!\n' for path_parts in self._gen_resourcetxt_path_parts(): with resources.open_text( self.anchor02, *path_parts, encoding='utf-8', ) as f: - self.assertEqual(f.read(), 'a resource') + assert f.read() == 'a resource' # Use generic OSError, since e.g. attempting to read a directory can # fail with PermissionError rather than IsADirectoryError with self.assertRaises(OSError): resources.open_text(self.anchor01) - with self.assertRaises(OSError): + with self.assertRaises((OSError, resources.abc.TraversalError)): resources.open_text(self.anchor01, 'no-such-file') with resources.open_text(self.anchor01, 'utf-16.file') as f: with self.assertRaises(UnicodeDecodeError): @@ -129,71 +131,70 @@ def test_open_text(self): 'binary.file', encoding='latin1', ) as f: - self.assertEqual(f.read(), '\x00\x01\x02\x03') + assert f.read() == '\x00\x01\x02\x03' with resources.open_text( self.anchor01, 'utf-16.file', errors='backslashreplace', ) as f: - self.assertEndsWith( # ignore the BOM - f.read(), - 'Hello, UTF-16 world!\n'.encode('utf-16-le').decode( - errors='backslashreplace', - ), + assert self.remove_utf16_bom(f.read()) == 'Hello, UTF-16 world!\n'.encode( + 'utf-16-le' + ).decode( + errors='backslashreplace', ) def test_open_binary(self): with resources.open_binary(self.anchor01, 'utf-8.file') as f: - self.assertEqual(f.read(), b'Hello, UTF-8 world!\n') + assert f.read() == b'Hello, UTF-8 world!\n' for path_parts in self._gen_resourcetxt_path_parts(): with resources.open_binary( self.anchor02, *path_parts, ) as f: - self.assertEqual(f.read(), b'a resource') + assert f.read() == b'a resource' def test_path(self): with resources.path(self.anchor01, 'utf-8.file') as path: with open(str(path), encoding='utf-8') as f: - self.assertEqual(f.read(), 'Hello, UTF-8 world!\n') + assert f.read() == 'Hello, UTF-8 world!\n' with resources.path(self.anchor01) as path: with open(os.path.join(path, 'utf-8.file'), encoding='utf-8') as f: - self.assertEqual(f.read(), 'Hello, UTF-8 world!\n') + assert f.read() == 'Hello, UTF-8 world!\n' def test_is_resource(self): is_resource = resources.is_resource - self.assertTrue(is_resource(self.anchor01, 'utf-8.file')) - self.assertFalse(is_resource(self.anchor01, 'no_such_file')) - self.assertFalse(is_resource(self.anchor01)) - self.assertFalse(is_resource(self.anchor01, 'subdirectory')) + assert is_resource(self.anchor01, 'utf-8.file') + assert not is_resource(self.anchor01, 'no_such_file') + assert not is_resource(self.anchor01) + assert not is_resource(self.anchor01, 'subdirectory') for path_parts in self._gen_resourcetxt_path_parts(): - self.assertTrue(is_resource(self.anchor02, *path_parts)) + assert is_resource(self.anchor02, *path_parts) def test_contents(self): with warnings_helper.check_warnings((".*contents.*", DeprecationWarning)): c = resources.contents(self.anchor01) - self.assertGreaterEqual( - set(c), - {'utf-8.file', 'utf-16.file', 'binary.file', 'subdirectory'}, - ) - with self.assertRaises(OSError), warnings_helper.check_warnings(( - ".*contents.*", - DeprecationWarning, - )): + assert set(c) >= {'utf-8.file', 'utf-16.file', 'binary.file', 'subdirectory'} + with ( + self.assertRaises(OSError), + warnings_helper.check_warnings(( + ".*contents.*", + DeprecationWarning, + )), + ): list(resources.contents(self.anchor01, 'utf-8.file')) for path_parts in self._gen_resourcetxt_path_parts(): - with self.assertRaises(OSError), warnings_helper.check_warnings(( - ".*contents.*", - DeprecationWarning, - )): + with ( + self.assertRaises((OSError, resources.abc.TraversalError)), + warnings_helper.check_warnings(( + ".*contents.*", + DeprecationWarning, + )), + ): list(resources.contents(self.anchor01, *path_parts)) with warnings_helper.check_warnings((".*contents.*", DeprecationWarning)): c = resources.contents(self.anchor01, 'subdirectory') - self.assertGreaterEqual( - set(c), - {'binary.file'}, - ) + assert set(c) >= {'binary.file'} @warnings_helper.ignore_warnings(category=DeprecationWarning) def test_common_errors(self): @@ -233,17 +234,28 @@ def test_text_errors(self): ) -class FunctionalAPITest_StringAnchor( +class FunctionalAPITest_StringAnchor_Disk( StringAnchorMixin, FunctionalAPIBase, + util.DiskSetup, unittest.TestCase, ): pass -class FunctionalAPITest_ModuleAnchor( +class FunctionalAPITest_ModuleAnchor_Disk( ModuleAnchorMixin, FunctionalAPIBase, + util.DiskSetup, + unittest.TestCase, +): + pass + + +class FunctionalAPITest_StringAnchor_Memory( + StringAnchorMixin, + FunctionalAPIBase, + util.MemorySetup, unittest.TestCase, ): pass diff --git a/Lib/test/test_importlib/resources/test_open.py b/Lib/test/test_importlib/resources/test_open.py index 8c00378ad3c..950f71db05a 100644 --- a/Lib/test/test_importlib/resources/test_open.py +++ b/Lib/test/test_importlib/resources/test_open.py @@ -1,6 +1,6 @@ +import importlib.resources as resources import unittest -from importlib import resources from . import util @@ -23,19 +23,19 @@ def test_open_binary(self): target = resources.files(self.data) / 'binary.file' with target.open('rb') as fp: result = fp.read() - self.assertEqual(result, bytes(range(4))) + assert result == bytes(range(4)) def test_open_text_default_encoding(self): target = resources.files(self.data) / 'utf-8.file' with target.open(encoding='utf-8') as fp: result = fp.read() - self.assertEqual(result, 'Hello, UTF-8 world!\n') + assert result == 'Hello, UTF-8 world!\n' def test_open_text_given_encoding(self): target = resources.files(self.data) / 'utf-16.file' with target.open(encoding='utf-16', errors='strict') as fp: result = fp.read() - self.assertEqual(result, 'Hello, UTF-16 world!\n') + assert result == 'Hello, UTF-16 world!\n' def test_open_text_with_errors(self): """ @@ -46,11 +46,10 @@ def test_open_text_with_errors(self): self.assertRaises(UnicodeError, fp.read) with target.open(encoding='utf-8', errors='ignore') as fp: result = fp.read() - self.assertEqual( - result, + assert result == ( 'H\x00e\x00l\x00l\x00o\x00,\x00 ' '\x00U\x00T\x00F\x00-\x001\x006\x00 ' - '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00', + '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00' ) def test_open_binary_FileNotFoundError(self): diff --git a/Lib/test/test_importlib/resources/test_path.py b/Lib/test/test_importlib/resources/test_path.py index 903911f57b3..162344e5d83 100644 --- a/Lib/test/test_importlib/resources/test_path.py +++ b/Lib/test/test_importlib/resources/test_path.py @@ -1,8 +1,8 @@ +import importlib.resources as resources import io import pathlib import unittest -from importlib import resources from . import util @@ -19,9 +19,9 @@ def test_reading(self): """ target = resources.files(self.data) / 'utf-8.file' with resources.as_file(target) as path: - self.assertIsInstance(path, pathlib.Path) - self.assertEndsWith(path.name, "utf-8.file") - self.assertEqual('Hello, UTF-8 world!\n', path.read_text(encoding='utf-8')) + assert isinstance(path, pathlib.Path) + assert path.name.endswith("utf-8.file"), repr(path) + assert 'Hello, UTF-8 world!\n' == path.read_text(encoding='utf-8') class PathDiskTests(PathTests, util.DiskSetup, unittest.TestCase): diff --git a/Lib/test/test_importlib/resources/test_read.py b/Lib/test/test_importlib/resources/test_read.py index 59c237d9641..4085a64b0ee 100644 --- a/Lib/test/test_importlib/resources/test_read.py +++ b/Lib/test/test_importlib/resources/test_read.py @@ -1,6 +1,6 @@ +import importlib.resources as resources import unittest - -from importlib import import_module, resources +from importlib import import_module from . import util @@ -18,23 +18,25 @@ def execute(self, package, path): class ReadTests: def test_read_bytes(self): result = resources.files(self.data).joinpath('binary.file').read_bytes() - self.assertEqual(result, bytes(range(4))) + assert result == bytes(range(4)) def test_read_text_default_encoding(self): result = ( - resources.files(self.data) + resources + .files(self.data) .joinpath('utf-8.file') .read_text(encoding='utf-8') ) - self.assertEqual(result, 'Hello, UTF-8 world!\n') + assert result == 'Hello, UTF-8 world!\n' def test_read_text_given_encoding(self): result = ( - resources.files(self.data) + resources + .files(self.data) .joinpath('utf-16.file') .read_text(encoding='utf-16') ) - self.assertEqual(result, 'Hello, UTF-16 world!\n') + assert result == 'Hello, UTF-16 world!\n' def test_read_text_with_errors(self): """ @@ -43,11 +45,10 @@ def test_read_text_with_errors(self): target = resources.files(self.data) / 'utf-16.file' self.assertRaises(UnicodeError, target.read_text, encoding='utf-8') result = target.read_text(encoding='utf-8', errors='ignore') - self.assertEqual( - result, + assert result == ( 'H\x00e\x00l\x00l\x00o\x00,\x00 ' '\x00U\x00T\x00F\x00-\x001\x006\x00 ' - '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00', + '\x00w\x00o\x00r\x00l\x00d\x00!\x00\n\x00' ) @@ -59,13 +60,13 @@ class ReadZipTests(ReadTests, util.ZipSetup, unittest.TestCase): def test_read_submodule_resource(self): submodule = import_module('data01.subdirectory') result = resources.files(submodule).joinpath('binary.file').read_bytes() - self.assertEqual(result, bytes(range(4, 8))) + assert result == bytes(range(4, 8)) def test_read_submodule_resource_by_name(self): result = ( resources.files('data01.subdirectory').joinpath('binary.file').read_bytes() ) - self.assertEqual(result, bytes(range(4, 8))) + assert result == bytes(range(4, 8)) class ReadNamespaceTests(ReadTests, util.DiskSetup, unittest.TestCase): @@ -78,15 +79,16 @@ class ReadNamespaceZipTests(ReadTests, util.ZipSetup, unittest.TestCase): def test_read_submodule_resource(self): submodule = import_module('namespacedata01.subdirectory') result = resources.files(submodule).joinpath('binary.file').read_bytes() - self.assertEqual(result, bytes(range(12, 16))) + assert result == bytes(range(12, 16)) def test_read_submodule_resource_by_name(self): result = ( - resources.files('namespacedata01.subdirectory') + resources + .files('namespacedata01.subdirectory') .joinpath('binary.file') .read_bytes() ) - self.assertEqual(result, bytes(range(12, 16))) + assert result == bytes(range(12, 16)) if __name__ == '__main__': diff --git a/Lib/test/test_importlib/resources/test_reader.py b/Lib/test/test_importlib/resources/test_reader.py index ed5693ab416..691a78bb060 100644 --- a/Lib/test/test_importlib/resources/test_reader.py +++ b/Lib/test/test_importlib/resources/test_reader.py @@ -1,9 +1,8 @@ import os.path import pathlib import unittest - from importlib import import_module -from importlib.readers import MultiplexedPath, NamespaceReader +from importlib.resources.readers import MultiplexedPath, NamespaceReader from . import util @@ -31,9 +30,7 @@ def test_iterdir(self): contents.remove('__pycache__') except (KeyError, ValueError): pass - self.assertEqual( - contents, {'subdirectory', 'binary.file', 'utf-16.file', 'utf-8.file'} - ) + assert contents == {'subdirectory', 'binary.file', 'utf-16.file', 'utf-8.file'} def test_iterdir_duplicate(self): contents = { @@ -44,16 +41,19 @@ def test_iterdir_duplicate(self): contents.remove(remove) except (KeyError, ValueError): pass - self.assertEqual( - contents, - {'__init__.py', 'binary.file', 'subdirectory', 'utf-16.file', 'utf-8.file'}, - ) + assert contents == { + '__init__.py', + 'binary.file', + 'subdirectory', + 'utf-16.file', + 'utf-8.file', + } def test_is_dir(self): - self.assertEqual(MultiplexedPath(self.folder).is_dir(), True) + assert MultiplexedPath(self.folder).is_dir() def test_is_file(self): - self.assertEqual(MultiplexedPath(self.folder).is_file(), False) + assert not MultiplexedPath(self.folder).is_file() def test_open_file(self): path = MultiplexedPath(self.folder) @@ -67,19 +67,17 @@ def test_open_file(self): def test_join_path(self): prefix = str(self.folder.parent) path = MultiplexedPath(self.folder, self.data01) - self.assertEqual( - str(path.joinpath('binary.file'))[len(prefix) + 1 :], - os.path.join('namespacedata01', 'binary.file'), + assert str(path.joinpath('binary.file'))[len(prefix) + 1 :] == os.path.join( + 'namespacedata01', 'binary.file' ) sub = path.joinpath('subdirectory') assert isinstance(sub, MultiplexedPath) assert 'namespacedata01' in str(sub) assert 'data01' in str(sub) - self.assertEqual( - str(path.joinpath('imaginary'))[len(prefix) + 1 :], - os.path.join('namespacedata01', 'imaginary'), + assert str(path.joinpath('imaginary'))[len(prefix) + 1 :] == os.path.join( + 'namespacedata01', 'imaginary' ) - self.assertEqual(path.joinpath(), path) + assert path.joinpath() == path def test_join_path_compound(self): path = MultiplexedPath(self.folder) @@ -88,23 +86,16 @@ def test_join_path_compound(self): def test_join_path_common_subdir(self): prefix = str(self.data02.parent) path = MultiplexedPath(self.data01, self.data02) - self.assertIsInstance(path.joinpath('subdirectory'), MultiplexedPath) - self.assertEqual( - str(path.joinpath('subdirectory', 'subsubdir'))[len(prefix) + 1 :], - os.path.join('data02', 'subdirectory', 'subsubdir'), + assert isinstance(path.joinpath('subdirectory'), MultiplexedPath) + assert str(path.joinpath('subdirectory', 'subsubdir'))[len(prefix) + 1 :] == ( + os.path.join('data02', 'subdirectory', 'subsubdir') ) def test_repr(self): - self.assertEqual( - repr(MultiplexedPath(self.folder)), - f"MultiplexedPath('{self.folder}')", - ) + assert repr(MultiplexedPath(self.folder)) == f"MultiplexedPath('{self.folder}')" def test_name(self): - self.assertEqual( - MultiplexedPath(self.folder).name, - os.path.basename(self.folder), - ) + assert MultiplexedPath(self.folder).name == os.path.basename(self.folder) class NamespaceReaderTest(util.DiskSetup, unittest.TestCase): @@ -119,18 +110,14 @@ def test_resource_path(self): reader = NamespaceReader(namespacedata01.__spec__.submodule_search_locations) root = self.data.__path__[0] - self.assertEqual( - reader.resource_path('binary.file'), os.path.join(root, 'binary.file') - ) - self.assertEqual( - reader.resource_path('imaginary'), os.path.join(root, 'imaginary') - ) + assert reader.resource_path('binary.file') == os.path.join(root, 'binary.file') + assert reader.resource_path('imaginary') == os.path.join(root, 'imaginary') def test_files(self): reader = NamespaceReader(self.data.__spec__.submodule_search_locations) root = self.data.__path__[0] - self.assertIsInstance(reader.files(), MultiplexedPath) - self.assertEqual(repr(reader.files()), f"MultiplexedPath('{root}')") + assert isinstance(reader.files(), MultiplexedPath) + assert repr(reader.files()) == f"MultiplexedPath('{root}')" if __name__ == '__main__': diff --git a/Lib/test/test_importlib/resources/test_resource.py b/Lib/test/test_importlib/resources/test_resource.py index fcede14b891..b114b1f0d80 100644 --- a/Lib/test/test_importlib/resources/test_resource.py +++ b/Lib/test/test_importlib/resources/test_resource.py @@ -1,7 +1,9 @@ +import importlib.resources as resources +import types import unittest +from importlib import import_module from . import util -from importlib import resources, import_module class ResourceTests: @@ -9,16 +11,16 @@ class ResourceTests: def test_is_file_exists(self): target = resources.files(self.data) / 'binary.file' - self.assertTrue(target.is_file()) + assert target.is_file() def test_is_file_missing(self): target = resources.files(self.data) / 'not-a-file' - self.assertFalse(target.is_file()) + assert not target.is_file() def test_is_dir(self): target = resources.files(self.data) / 'subdirectory' - self.assertFalse(target.is_file()) - self.assertTrue(target.is_dir()) + assert not target.is_file() + assert target.is_dir() class ResourceDiskTests(ResourceTests, util.DiskSetup, unittest.TestCase): @@ -38,7 +40,7 @@ def test_resource_contents(self): package = util.create_package( file=self.data, path=self.data.__file__, contents=['A', 'B', 'C'] ) - self.assertEqual(names(resources.files(package)), {'A', 'B', 'C'}) + assert names(resources.files(package)) == {'A', 'B', 'C'} def test_is_file(self): package = util.create_package( @@ -46,7 +48,7 @@ def test_is_file(self): path=self.data.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F'], ) - self.assertTrue(resources.files(package).joinpath('B').is_file()) + assert resources.files(package).joinpath('B').is_file() def test_is_dir(self): package = util.create_package( @@ -54,7 +56,7 @@ def test_is_dir(self): path=self.data.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F'], ) - self.assertTrue(resources.files(package).joinpath('D').is_dir()) + assert resources.files(package).joinpath('D').is_dir() def test_resource_missing(self): package = util.create_package( @@ -62,7 +64,7 @@ def test_resource_missing(self): path=self.data.__file__, contents=['A', 'B', 'C', 'D/E', 'D/F'], ) - self.assertFalse(resources.files(package).joinpath('Z').is_file()) + assert not resources.files(package).joinpath('Z').is_file() class ResourceCornerCaseTests(util.DiskSetup, unittest.TestCase): @@ -82,30 +84,26 @@ def test_package_has_no_reader_fallback(self): module.__file__ = '/path/which/shall/not/be/named' module.__spec__.loader = module.__loader__ module.__spec__.origin = module.__file__ - self.assertFalse(resources.files(module).joinpath('A').is_file()) + assert not resources.files(module).joinpath('A').is_file() class ResourceFromZipsTest01(util.ZipSetup, unittest.TestCase): def test_is_submodule_resource(self): submodule = import_module('data01.subdirectory') - self.assertTrue(resources.files(submodule).joinpath('binary.file').is_file()) + assert resources.files(submodule).joinpath('binary.file').is_file() def test_read_submodule_resource_by_name(self): - self.assertTrue( - resources.files('data01.subdirectory').joinpath('binary.file').is_file() - ) + assert resources.files('data01.subdirectory').joinpath('binary.file').is_file() def test_submodule_contents(self): submodule = import_module('data01.subdirectory') - self.assertEqual( - names(resources.files(submodule)), {'__init__.py', 'binary.file'} - ) + assert names(resources.files(submodule)) == {'__init__.py', 'binary.file'} def test_submodule_contents_by_name(self): - self.assertEqual( - names(resources.files('data01.subdirectory')), - {'__init__.py', 'binary.file'}, - ) + assert names(resources.files('data01.subdirectory')) == { + '__init__.py', + 'binary.file', + } def test_as_file_directory(self): with resources.as_file(resources.files('data01')) as data: @@ -124,14 +122,8 @@ def test_unrelated_contents(self): Test thata zip with two unrelated subpackages return distinct resources. Ref python/importlib_resources#44. """ - self.assertEqual( - names(resources.files('data02.one')), - {'__init__.py', 'resource1.txt'}, - ) - self.assertEqual( - names(resources.files('data02.two')), - {'__init__.py', 'resource2.txt'}, - ) + assert names(resources.files('data02.one')) == {'__init__.py', 'resource1.txt'} + assert names(resources.files('data02.two')) == {'__init__.py', 'resource2.txt'} class DeletingZipsTest(util.ZipSetup, unittest.TestCase): @@ -168,16 +160,15 @@ def test_read_text_does_not_keep_open(self): class ResourceFromNamespaceTests: def test_is_submodule_resource(self): - self.assertTrue( - resources.files(import_module('namespacedata01')) + assert ( + resources + .files(import_module('namespacedata01')) .joinpath('binary.file') .is_file() ) def test_read_submodule_resource_by_name(self): - self.assertTrue( - resources.files('namespacedata01').joinpath('binary.file').is_file() - ) + assert resources.files('namespacedata01').joinpath('binary.file').is_file() def test_submodule_contents(self): contents = names(resources.files(import_module('namespacedata01'))) @@ -185,9 +176,7 @@ def test_submodule_contents(self): contents.remove('__pycache__') except KeyError: pass - self.assertEqual( - contents, {'subdirectory', 'binary.file', 'utf-8.file', 'utf-16.file'} - ) + assert contents == {'subdirectory', 'binary.file', 'utf-8.file', 'utf-16.file'} def test_submodule_contents_by_name(self): contents = names(resources.files('namespacedata01')) @@ -195,9 +184,7 @@ def test_submodule_contents_by_name(self): contents.remove('__pycache__') except KeyError: pass - self.assertEqual( - contents, {'subdirectory', 'binary.file', 'utf-8.file', 'utf-16.file'} - ) + assert contents == {'subdirectory', 'binary.file', 'utf-8.file', 'utf-16.file'} def test_submodule_sub_contents(self): contents = names(resources.files(import_module('namespacedata01.subdirectory'))) @@ -205,7 +192,7 @@ def test_submodule_sub_contents(self): contents.remove('__pycache__') except KeyError: pass - self.assertEqual(contents, {'binary.file'}) + assert contents == {'binary.file'} def test_submodule_sub_contents_by_name(self): contents = names(resources.files('namespacedata01.subdirectory')) @@ -213,7 +200,7 @@ def test_submodule_sub_contents_by_name(self): contents.remove('__pycache__') except KeyError: pass - self.assertEqual(contents, {'binary.file'}) + assert contents == {'binary.file'} class ResourceFromNamespaceDiskTests( @@ -232,5 +219,24 @@ class ResourceFromNamespaceZipTests( MODULE = 'namespacedata01' +class MainModuleTests(unittest.TestCase): + def test_main_module_with_none_spec(self): + """ + __main__ module with no spec should raise TypeError (for clarity). + + See python/cpython#138531 for details. + """ + # construct a __main__ module with no __spec__. + mainmodule = types.ModuleType("__main__") + + assert mainmodule.__spec__ is None + + with self.assertRaises( + TypeError, + msg="Cannot access resources for '__main__' as it does not appear to correspond to an importable module (its __spec__ is None).", + ): + resources.files(mainmodule) + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_importlib/resources/test_util.py b/Lib/test/test_importlib/resources/test_util.py new file mode 100644 index 00000000000..de304b6f351 --- /dev/null +++ b/Lib/test/test_importlib/resources/test_util.py @@ -0,0 +1,29 @@ +import unittest + +from .util import MemorySetup, Traversable + + +class TestMemoryTraversableImplementation(unittest.TestCase): + def test_concrete_methods_are_not_overridden(self): + """`MemoryTraversable` must not override `Traversable` concrete methods. + + This test is not an attempt to enforce a particular `Traversable` protocol; + it merely catches changes in the `Traversable` abstract/concrete methods + that have not been mirrored in the `MemoryTraversable` subclass. + """ + + traversable_concrete_methods = { + method + for method, value in Traversable.__dict__.items() + if callable(value) and method not in Traversable.__abstractmethods__ + } + memory_traversable_concrete_methods = { + method + for method, value in MemorySetup.MemoryTraversable.__dict__.items() + if callable(value) and not method.startswith("__") + } + overridden_methods = ( + memory_traversable_concrete_methods & traversable_concrete_methods + ) + + assert not overridden_methods diff --git a/Lib/test/test_importlib/resources/update-zips.py b/Lib/test/test_importlib/resources/update-zips.py deleted file mode 100755 index 231334aa7e3..00000000000 --- a/Lib/test/test_importlib/resources/update-zips.py +++ /dev/null @@ -1,53 +0,0 @@ -""" -Generate the zip test data files. - -Run to build the tests/zipdataNN/ziptestdata.zip files from -files in tests/dataNN. - -Replaces the file with the working copy, but does commit anything -to the source repo. -""" - -import contextlib -import os -import pathlib -import zipfile - - -def main(): - """ - >>> from unittest import mock - >>> monkeypatch = getfixture('monkeypatch') - >>> monkeypatch.setattr(zipfile, 'ZipFile', mock.MagicMock()) - >>> print(); main() # print workaround for bpo-32509 - - ...data01... -> ziptestdata/... - ... - ...data02... -> ziptestdata/... - ... - """ - suffixes = '01', '02' - tuple(map(generate, suffixes)) - - -def generate(suffix): - root = pathlib.Path(__file__).parent.relative_to(os.getcwd()) - zfpath = root / f'zipdata{suffix}/ziptestdata.zip' - with zipfile.ZipFile(zfpath, 'w') as zf: - for src, rel in walk(root / f'data{suffix}'): - dst = 'ziptestdata' / pathlib.PurePosixPath(rel.as_posix()) - print(src, '->', dst) - zf.write(src, dst) - - -def walk(datapath): - for dirpath, dirnames, filenames in os.walk(datapath): - with contextlib.suppress(ValueError): - dirnames.remove('__pycache__') - for filename in filenames: - res = pathlib.Path(dirpath) / filename - rel = res.relative_to(datapath) - yield res, rel - - -__name__ == '__main__' and main() diff --git a/Lib/test/test_importlib/resources/util.py b/Lib/test/test_importlib/resources/util.py index e2d995f5963..85b5c61518d 100644 --- a/Lib/test/test_importlib/resources/util.py +++ b/Lib/test/test_importlib/resources/util.py @@ -1,18 +1,18 @@ import abc +import contextlib +import functools import importlib import io +import pathlib import sys import types -import pathlib -import contextlib +from importlib.machinery import ModuleSpec +from importlib.resources.abc import ResourceReader, Traversable, TraversableResources -from importlib.resources.abc import ResourceReader from test.support import import_helper, os_helper -from . import zip as zip_ -from . import _path - -from importlib.machinery import ModuleSpec +from . import _path +from . import zip as zip_ class Reader(ResourceReader): @@ -122,7 +122,7 @@ def test_missing_path(self): bytes_data = io.BytesIO(b'Hello, world!') package = create_package(file=bytes_data, path=FileNotFoundError()) self.execute(package, 'utf-8.file') - self.assertEqual(package.__loader__._path, 'utf-8.file') + assert package.__loader__._path == 'utf-8.file' def test_extant_path(self): # Attempting to open or read or request the path when the @@ -133,7 +133,7 @@ def test_extant_path(self): path = __file__ package = create_package(file=bytes_data, path=path) self.execute(package, 'utf-8.file') - self.assertEqual(package.__loader__._path, 'utf-8.file') + assert package.__loader__._path == 'utf-8.file' def test_useless_loader(self): package = create_package(file=FileNotFoundError(), path=FileNotFoundError()) @@ -202,5 +202,108 @@ def tree_on_path(self, spec): self.fixtures.enter_context(import_helper.DirsOnSysPath(temp_dir)) +class MemorySetup(ModuleSetup): + """Support loading a module in memory.""" + + MODULE = 'data01' + + def load_fixture(self, module): + self.fixtures.enter_context(self.augment_sys_metapath(module)) + return importlib.import_module(module) + + @contextlib.contextmanager + def augment_sys_metapath(self, module): + finder_instance = self.MemoryFinder(module) + sys.meta_path.append(finder_instance) + yield + sys.meta_path.remove(finder_instance) + + class MemoryFinder(importlib.abc.MetaPathFinder): + def __init__(self, module): + self._module = module + + def find_spec(self, fullname, path, target=None): + if fullname != self._module: + return None + + return importlib.machinery.ModuleSpec( + name=fullname, + loader=MemorySetup.MemoryLoader(self._module), + is_package=True, + ) + + class MemoryLoader(importlib.abc.Loader): + def __init__(self, module): + self._module = module + + def exec_module(self, module): + pass + + def get_resource_reader(self, fullname): + return MemorySetup.MemoryTraversableResources(self._module, fullname) + + class MemoryTraversableResources(TraversableResources): + def __init__(self, module, fullname): + self._module = module + self._fullname = fullname + + def files(self): + return MemorySetup.MemoryTraversable(self._module, self._fullname) + + class MemoryTraversable(Traversable): + """Implement only the abstract methods of `Traversable`. + + Besides `.__init__()`, no other methods may be implemented or overridden. + This is critical for validating the concrete `Traversable` implementations. + """ + + def __init__(self, module, fullname): + self._module = module + self._fullname = fullname + + def _resolve(self): + """ + Fully traverse the `fixtures` dictionary. + + This should be wrapped in a `try/except KeyError` + but it is not currently needed and lowers the code coverage numbers. + """ + path = pathlib.PurePosixPath(self._fullname) + return functools.reduce(lambda d, p: d[p], path.parts, fixtures) + + def iterdir(self): + directory = self._resolve() + if not isinstance(directory, dict): + # Filesystem openers raise OSError, and that exception is mirrored here. + raise OSError(f"{self._fullname} is not a directory") + for path in directory: + yield MemorySetup.MemoryTraversable( + self._module, f"{self._fullname}/{path}" + ) + + def is_dir(self) -> bool: + return isinstance(self._resolve(), dict) + + def is_file(self) -> bool: + return not self.is_dir() + + def open(self, mode='r', encoding=None, errors=None, *_, **__): + contents = self._resolve() + if isinstance(contents, dict): + # Filesystem openers raise OSError when attempting to open a directory, + # and that exception is mirrored here. + raise OSError(f"{self._fullname} is a directory") + if isinstance(contents, str): + contents = contents.encode("utf-8") + result = io.BytesIO(contents) + if "b" in mode: + return result + return io.TextIOWrapper(result, encoding=encoding, errors=errors) + + @property + def name(self): + return pathlib.PurePosixPath(self._fullname).name + + class CommonTests(DiskSetup, CommonTestsBase): pass diff --git a/Lib/test/test_importlib/resources/zipdata01/__init__.py b/Lib/test/test_importlib/resources/zipdata01/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Lib/test/test_importlib/resources/zipdata01/ziptestdata.zip b/Lib/test/test_importlib/resources/zipdata01/ziptestdata.zip deleted file mode 100644 index 9a3bb0739f8..00000000000 Binary files a/Lib/test/test_importlib/resources/zipdata01/ziptestdata.zip and /dev/null differ diff --git a/Lib/test/test_importlib/resources/zipdata02/__init__.py b/Lib/test/test_importlib/resources/zipdata02/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/Lib/test/test_importlib/resources/zipdata02/ziptestdata.zip b/Lib/test/test_importlib/resources/zipdata02/ziptestdata.zip deleted file mode 100644 index d63ff512d28..00000000000 Binary files a/Lib/test/test_importlib/resources/zipdata02/ziptestdata.zip and /dev/null differ diff --git a/Lib/test/test_importlib/source/test_file_loader.py b/Lib/test/test_importlib/source/test_file_loader.py index f35adec1a8e..ca2cc045fa6 100644 --- a/Lib/test/test_importlib/source/test_file_loader.py +++ b/Lib/test/test_importlib/source/test_file_loader.py @@ -5,24 +5,21 @@ machinery = util.import_importlib('importlib.machinery') importlib_util = util.import_importlib('importlib.util') -import errno import marshal import os import py_compile -import shutil import stat import sys import types import unittest -import warnings -from test.support.import_helper import make_legacy_pyc, unload +from test.support.import_helper import make_legacy_pyc -from test.test_py_compile import without_source_date_epoch -from test.test_py_compile import SourceDateEpochTestMeta +from test.support.os_helper import without_source_date_epoch +from test.support.os_helper import SourceDateEpochTestMeta -class SimpleTest(abc.LoaderTests): +class SimpleTest: """Should have no issue importing a source module [basic]. And if there is a syntax error, it should raise a SyntaxError [syntax error]. @@ -34,17 +31,6 @@ def setUp(self): self.filepath = os.path.join('ham', self.name + '.py') self.loader = self.machinery.SourceFileLoader(self.name, self.filepath) - def test_load_module_API(self): - class Tester(self.abc.FileLoader): - def get_source(self, _): return 'attr = 42' - def is_package(self, _): return False - - loader = Tester('blah', 'blah.py') - self.addCleanup(unload, 'blah') - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = loader.load_module() # Should not raise an exception. - def test_get_filename_API(self): # If fullname is not set then assume self.path is desired. class Tester(self.abc.FileLoader): @@ -69,173 +55,11 @@ def test_inequality(self): other = self.machinery.SourceFileLoader('_' + self.name, self.filepath) self.assertNotEqual(self.loader, other) - # [basic] - def test_module(self): - with util.create_modules('_temp') as mapping: - loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = loader.load_module('_temp') - self.assertIn('_temp', sys.modules) - check = {'__name__': '_temp', '__file__': mapping['_temp'], - '__package__': ''} - for attr, value in check.items(): - self.assertEqual(getattr(module, attr), value) - - def test_package(self): - with util.create_modules('_pkg.__init__') as mapping: - loader = self.machinery.SourceFileLoader('_pkg', - mapping['_pkg.__init__']) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = loader.load_module('_pkg') - self.assertIn('_pkg', sys.modules) - check = {'__name__': '_pkg', '__file__': mapping['_pkg.__init__'], - '__path__': [os.path.dirname(mapping['_pkg.__init__'])], - '__package__': '_pkg'} - for attr, value in check.items(): - self.assertEqual(getattr(module, attr), value) - - - def test_lacking_parent(self): - with util.create_modules('_pkg.__init__', '_pkg.mod')as mapping: - loader = self.machinery.SourceFileLoader('_pkg.mod', - mapping['_pkg.mod']) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = loader.load_module('_pkg.mod') - self.assertIn('_pkg.mod', sys.modules) - check = {'__name__': '_pkg.mod', '__file__': mapping['_pkg.mod'], - '__package__': '_pkg'} - for attr, value in check.items(): - self.assertEqual(getattr(module, attr), value) def fake_mtime(self, fxn): """Fake mtime to always be higher than expected.""" return lambda name: fxn(name) + 1 - def test_module_reuse(self): - with util.create_modules('_temp') as mapping: - loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = loader.load_module('_temp') - module_id = id(module) - module_dict_id = id(module.__dict__) - with open(mapping['_temp'], 'w', encoding='utf-8') as file: - file.write("testing_var = 42\n") - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = loader.load_module('_temp') - self.assertIn('testing_var', module.__dict__, - "'testing_var' not in " - "{0}".format(list(module.__dict__.keys()))) - self.assertEqual(module, sys.modules['_temp']) - self.assertEqual(id(module), module_id) - self.assertEqual(id(module.__dict__), module_dict_id) - - def test_state_after_failure(self): - # A failed reload should leave the original module intact. - attributes = ('__file__', '__path__', '__package__') - value = '' - name = '_temp' - with util.create_modules(name) as mapping: - orig_module = types.ModuleType(name) - for attr in attributes: - setattr(orig_module, attr, value) - with open(mapping[name], 'w', encoding='utf-8') as file: - file.write('+++ bad syntax +++') - loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) - with self.assertRaises(SyntaxError): - loader.exec_module(orig_module) - for attr in attributes: - self.assertEqual(getattr(orig_module, attr), value) - with self.assertRaises(SyntaxError): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - loader.load_module(name) - for attr in attributes: - self.assertEqual(getattr(orig_module, attr), value) - - # [syntax error] - def test_bad_syntax(self): - with util.create_modules('_temp') as mapping: - with open(mapping['_temp'], 'w', encoding='utf-8') as file: - file.write('=') - loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) - with self.assertRaises(SyntaxError): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - loader.load_module('_temp') - self.assertNotIn('_temp', sys.modules) - - def test_file_from_empty_string_dir(self): - # Loading a module found from an empty string entry on sys.path should - # not only work, but keep all attributes relative. - file_path = '_temp.py' - with open(file_path, 'w', encoding='utf-8') as file: - file.write("# test file for importlib") - try: - with util.uncache('_temp'): - loader = self.machinery.SourceFileLoader('_temp', file_path) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - mod = loader.load_module('_temp') - self.assertEqual(file_path, mod.__file__) - self.assertEqual(self.util.cache_from_source(file_path), - mod.__cached__) - finally: - os.unlink(file_path) - pycache = os.path.dirname(self.util.cache_from_source(file_path)) - if os.path.exists(pycache): - shutil.rmtree(pycache) - - @util.writes_bytecode_files - def test_timestamp_overflow(self): - # When a modification timestamp is larger than 2**32, it should be - # truncated rather than raise an OverflowError. - with util.create_modules('_temp') as mapping: - source = mapping['_temp'] - compiled = self.util.cache_from_source(source) - with open(source, 'w', encoding='utf-8') as f: - f.write("x = 5") - try: - os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5)) - except OverflowError: - self.skipTest("cannot set modification time to large integer") - except OSError as e: - if e.errno != getattr(errno, 'EOVERFLOW', None): - raise - self.skipTest("cannot set modification time to large integer ({})".format(e)) - loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) - # PEP 451 - module = types.ModuleType('_temp') - module.__spec__ = self.util.spec_from_loader('_temp', loader) - loader.exec_module(module) - self.assertEqual(module.x, 5) - self.assertTrue(os.path.exists(compiled)) - os.unlink(compiled) - # PEP 302 - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - mod = loader.load_module('_temp') - # Sanity checks. - self.assertEqual(mod.__cached__, compiled) - self.assertEqual(mod.x, 5) - # The pyc file was created. - self.assertTrue(os.path.exists(compiled)) - - def test_unloadable(self): - loader = self.machinery.SourceFileLoader('good name', {}) - module = types.ModuleType('bad name') - module.__spec__ = self.machinery.ModuleSpec('bad name', loader) - with self.assertRaises(ImportError): - loader.exec_module(module) - with self.assertRaises(ImportError): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - loader.load_module('bad name') - @util.writes_bytecode_files def test_checked_hash_based_pyc(self): with util.create_modules('_temp') as mapping: @@ -386,12 +210,21 @@ def manipulate_bytecode(self, del sys.modules['_temp'] except KeyError: pass - py_compile.compile(mapping[name], invalidation_mode=invalidation_mode) - if not del_source: - bytecode_path = self.util.cache_from_source(mapping[name]) + if sys.implementation.cache_tag is None: + if del_source: + bytecode_path = mapping[name] + 'c' + py_compile.compile(mapping[name], bytecode_path, + invalidation_mode=invalidation_mode) + os.unlink(mapping[name]) + else: + raise unittest.SkipTest('requires sys.implementation.cache_tag') else: - os.unlink(mapping[name]) - bytecode_path = make_legacy_pyc(mapping[name]) + py_compile.compile(mapping[name], invalidation_mode=invalidation_mode) + if not del_source: + bytecode_path = self.util.cache_from_source(mapping[name]) + else: + os.unlink(mapping[name]) + bytecode_path = make_legacy_pyc(mapping[name]) if manipulator: with open(bytecode_path, 'rb') as file: bc = file.read() @@ -511,16 +344,6 @@ def import_(self, file, module_name): loader.exec_module(module) -class BadBytecodeTestPEP302(BadBytecodeTest): - - def import_(self, file, module_name): - loader = self.loader(module_name, file) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = loader.load_module(module_name) - self.assertIn(module_name, sys.modules) - - class SourceLoaderBadBytecodeTest: @classmethod @@ -681,18 +504,6 @@ class SourceLoaderBadBytecodeTestPEP451( util=importlib_util) -class SourceLoaderBadBytecodeTestPEP302( - SourceLoaderBadBytecodeTest, BadBytecodeTestPEP302): - pass - - -(Frozen_SourceBadBytecodePEP302, - Source_SourceBadBytecodePEP302 - ) = util.test_both(SourceLoaderBadBytecodeTestPEP302, importlib=importlib, - machinery=machinery, abc=importlib_abc, - util=importlib_util) - - class SourcelessLoaderBadBytecodeTest: @classmethod @@ -779,17 +590,5 @@ class SourcelessLoaderBadBytecodeTestPEP451(SourcelessLoaderBadBytecodeTest, util=importlib_util) -class SourcelessLoaderBadBytecodeTestPEP302(SourcelessLoaderBadBytecodeTest, - BadBytecodeTestPEP302): - pass - - -(Frozen_SourcelessBadBytecodePEP302, - Source_SourcelessBadBytecodePEP302 - ) = util.test_both(SourcelessLoaderBadBytecodeTestPEP302, importlib=importlib, - machinery=machinery, abc=importlib_abc, - util=importlib_util) - - if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_importlib/source/test_finder.py b/Lib/test/test_importlib/source/test_finder.py index 4de736a6bf3..91865b997ad 100644 --- a/Lib/test/test_importlib/source/test_finder.py +++ b/Lib/test/test_importlib/source/test_finder.py @@ -57,6 +57,8 @@ def run_test(self, test, create=None, *, compile_=None, unlink=None): """ if create is None: create = {test} + if (compile_ or unlink) and sys.implementation.cache_tag is None: + raise unittest.SkipTest('requires sys.implementation.cache_tag') with util.create_modules(*create) as mapping: if compile_: for name in compile_: @@ -73,7 +75,7 @@ def run_test(self, test, create=None, *, compile_=None, unlink=None): if error.errno != errno.ENOENT: raise loader = self.import_(mapping['.root'], test) - self.assertHasAttr(loader, 'load_module') + self.assertHasAttr(loader, 'exec_module') return loader def test_module(self): @@ -100,7 +102,7 @@ def test_module_in_package(self): with util.create_modules('pkg.__init__', 'pkg.sub') as mapping: pkg_dir = os.path.dirname(mapping['pkg.__init__']) loader = self.import_(pkg_dir, 'pkg.sub') - self.assertHasAttr(loader, 'load_module') + self.assertHasAttr(loader, 'exec_module') # [sub package] def test_package_in_package(self): @@ -108,7 +110,7 @@ def test_package_in_package(self): with context as mapping: pkg_dir = os.path.dirname(mapping['pkg.__init__']) loader = self.import_(pkg_dir, 'pkg.sub') - self.assertHasAttr(loader, 'load_module') + self.assertHasAttr(loader, 'exec_module') # [package over modules] def test_package_over_module(self): @@ -129,7 +131,7 @@ def test_empty_string_for_dir(self): file.write("# test file for importlib") try: loader = self._find(finder, 'mod', loader_only=True) - self.assertHasAttr(loader, 'load_module') + self.assertHasAttr(loader, 'exec_module') finally: os.unlink('mod.py') diff --git a/Lib/test/test_importlib/source/test_source_encoding.py b/Lib/test/test_importlib/source/test_source_encoding.py index c09c9aa12b8..fada07877fc 100644 --- a/Lib/test/test_importlib/source/test_source_encoding.py +++ b/Lib/test/test_importlib/source/test_source_encoding.py @@ -102,19 +102,6 @@ def load(self, loader): ) = util.test_both(EncodingTestPEP451, machinery=machinery) -class EncodingTestPEP302(EncodingTest): - - def load(self, loader): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - return loader.load_module(self.module_name) - - -(Frozen_EncodingTestPEP302, - Source_EncodingTestPEP302 - ) = util.test_both(EncodingTestPEP302, machinery=machinery) - - class LineEndingTest: r"""Source written with the three types of line endings (\n, \r\n, \r) @@ -158,18 +145,5 @@ def load(self, loader, module_name): ) = util.test_both(LineEndingTestPEP451, machinery=machinery) -class LineEndingTestPEP302(LineEndingTest): - - def load(self, loader, module_name): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - return loader.load_module(module_name) - - -(Frozen_LineEndingTestPEP302, - Source_LineEndingTestPEP302 - ) = util.test_both(LineEndingTestPEP302, machinery=machinery) - - if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_importlib/stubs.py b/Lib/test/test_importlib/stubs.py deleted file mode 100644 index e5b011c399f..00000000000 --- a/Lib/test/test_importlib/stubs.py +++ /dev/null @@ -1,10 +0,0 @@ -import unittest - - -class fake_filesystem_unittest: - """ - Stubbed version of the pyfakefs module - """ - class TestCase(unittest.TestCase): - def setUpPyfakefs(self): - self.skipTest("pyfakefs not available") diff --git a/Lib/test/test_importlib/test_abc.py b/Lib/test/test_importlib/test_abc.py index dd943210ffc..b24c5766468 100644 --- a/Lib/test/test_importlib/test_abc.py +++ b/Lib/test/test_importlib/test_abc.py @@ -194,10 +194,6 @@ def test_create_module(self): spec = 'a spec' self.assertIsNone(self.ins.create_module(spec)) - def test_load_module(self): - with self.assertRaises(ImportError): - self.ins.load_module('something') - def test_module_repr(self): mod = types.ModuleType('blah') with warnings.catch_warnings(): @@ -358,38 +354,6 @@ def is_package(self, fullname): return SpecLoader() - def test_fresh(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - loader = self.loader() - name = 'blah' - with test_util.uncache(name): - loader.load_module(name) - module = loader.found - self.assertIs(sys.modules[name], module) - self.assertEqual(loader, module.__loader__) - self.assertEqual(loader, module.__spec__.loader) - self.assertEqual(name, module.__name__) - self.assertEqual(name, module.__spec__.name) - self.assertIsNotNone(module.__path__) - self.assertIsNotNone(module.__path__, - module.__spec__.submodule_search_locations) - - def test_reload(self): - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - name = 'blah' - loader = self.loader() - module = types.ModuleType(name) - module.__spec__ = self.util.spec_from_loader(name, loader) - module.__loader__ = loader - with test_util.uncache(name): - sys.modules[name] = module - loader.load_module(name) - found = loader.found - self.assertIs(found, sys.modules[name]) - self.assertIs(module, sys.modules[name]) - (Frozen_LoaderLoadModuleTests, Source_LoaderLoadModuleTests @@ -478,59 +442,6 @@ def test_get_code_source_not_found(self): InspectLoaderSubclass=SPLIT_IL) -class InspectLoaderLoadModuleTests: - - """Test InspectLoader.load_module().""" - - module_name = 'blah' - - def setUp(self): - import_helper.unload(self.module_name) - self.addCleanup(import_helper.unload, self.module_name) - - def load(self, loader): - spec = self.util.spec_from_loader(self.module_name, loader) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - return self.init._bootstrap._load_unlocked(spec) - - def mock_get_code(self): - return mock.patch.object(self.InspectLoaderSubclass, 'get_code') - - def test_get_code_ImportError(self): - # If get_code() raises ImportError, it should propagate. - with self.mock_get_code() as mocked_get_code: - mocked_get_code.side_effect = ImportError - with self.assertRaises(ImportError): - loader = self.InspectLoaderSubclass() - self.load(loader) - - def test_get_code_None(self): - # If get_code() returns None, raise ImportError. - with self.mock_get_code() as mocked_get_code: - mocked_get_code.return_value = None - with self.assertRaises(ImportError): - loader = self.InspectLoaderSubclass() - self.load(loader) - - def test_module_returned(self): - # The loaded module should be returned. - code = compile('attr = 42', '', 'exec') - with self.mock_get_code() as mocked_get_code: - mocked_get_code.return_value = code - loader = self.InspectLoaderSubclass() - module = self.load(loader) - self.assertEqual(module, sys.modules[self.module_name]) - - -(Frozen_ILLoadModuleTests, - Source_ILLoadModuleTests - ) = test_util.test_both(InspectLoaderLoadModuleTests, - InspectLoaderSubclass=SPLIT_IL, - init=init, - util=util) - - ##### ExecutionLoader concrete methods ######################################### class ExecutionLoaderGetCodeTests: @@ -599,8 +510,7 @@ def test_get_code_no_path(self): class SourceOnlyLoader: # Globals that should be defined for all modules. - source = (b"_ = '::'.join([__name__, __file__, __cached__, __package__, " - b"repr(__loader__)])") + source = (b"_ = '::'.join([__name__, __file__, __package__, repr(__loader__)])") def __init__(self, path): self.path = path @@ -623,7 +533,10 @@ class SourceLoader(SourceOnlyLoader): def __init__(self, path, magic=None): super().__init__(path) - self.bytecode_path = self.util.cache_from_source(self.path) + try: + self.bytecode_path = self.util.cache_from_source(self.path) + except NotImplementedError: + self.bytecode_path = None self.source_size = len(self.source) if magic is None: magic = self.util.MAGIC_NUMBER @@ -669,26 +582,26 @@ def setUp(self, *, is_package=True, **kwargs): module_name = 'mod' self.path = os.path.join(self.package, '.'.join(['mod', 'py'])) self.name = '.'.join([self.package, module_name]) - self.cached = self.util.cache_from_source(self.path) + try: + self.cached = self.util.cache_from_source(self.path) + except NotImplementedError: + self.cached = None self.loader = self.loader_mock(self.path, **kwargs) def verify_module(self, module): self.assertEqual(module.__name__, self.name) self.assertEqual(module.__file__, self.path) - self.assertEqual(module.__cached__, self.cached) self.assertEqual(module.__package__, self.package) self.assertEqual(module.__loader__, self.loader) values = module._.split('::') self.assertEqual(values[0], self.name) self.assertEqual(values[1], self.path) - self.assertEqual(values[2], self.cached) - self.assertEqual(values[3], self.package) - self.assertEqual(values[4], repr(self.loader)) + self.assertEqual(values[2], self.package) + self.assertEqual(values[3], repr(self.loader)) def verify_code(self, code_object): module = types.ModuleType(self.name) module.__file__ = self.path - module.__cached__ = self.cached module.__package__ = self.package module.__loader__ = self.loader module.__path__ = [] @@ -729,34 +642,6 @@ def test_source_to_code(self): code = self.loader.source_to_code(self.loader.source, self.path) self.verify_code(code) - def test_load_module(self): - # Loading a module should set __name__, __loader__, __package__, - # __path__ (for packages), __file__, and __cached__. - # The module should also be put into sys.modules. - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - with test_util.uncache(self.name): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = self.loader.load_module(self.name) - self.verify_module(module) - self.assertEqual(module.__path__, [os.path.dirname(self.path)]) - self.assertIn(self.name, sys.modules) - - def test_package_settings(self): - # __package__ needs to be set, while __path__ is set on if the module - # is a package. - # Testing the values for a package are covered by test_load_module. - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - self.setUp(is_package=False) - with test_util.uncache(self.name): - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - module = self.loader.load_module(self.name) - self.verify_module(module) - self.assertNotHasAttr(module, '__path__') - def test_get_source_encoding(self): # Source is considered encoded in UTF-8 by default unless otherwise # specified by an encoding line. @@ -777,6 +662,8 @@ def test_get_source_encoding(self): @unittest.skipIf(sys.dont_write_bytecode, "sys.dont_write_bytecode is true") +@unittest.skipIf(sys.implementation.cache_tag is None, + "sys.implementation.cache_tag is None") class SourceLoaderBytecodeTests(SourceLoaderTestHarness): """Test importlib.abc.SourceLoader's use of bytecode. @@ -904,7 +791,7 @@ def test_universal_newlines(self): mock = self.SourceOnlyLoaderMock('mod.file') source = "x = 42\r\ny = -13\r\n" mock.source = source.encode('utf-8') - expect = io.IncrementalNewlineDecoder(None, True).decode(source) + expect = io.StringIO(source, newline=None).getvalue() self.assertEqual(mock.get_source(name), expect) diff --git a/Lib/test/test_importlib/test_api.py b/Lib/test/test_importlib/test_api.py index 1bc531a2fe3..70d93d693ae 100644 --- a/Lib/test/test_importlib/test_api.py +++ b/Lib/test/test_importlib/test_api.py @@ -231,11 +231,9 @@ def test_reload_location_changed(self): # Start as a plain module. self.init.invalidate_caches() path = os.path.join(cwd, name + '.py') - cached = self.util.cache_from_source(path) expected = {'__name__': name, '__package__': '', '__file__': path, - '__cached__': cached, '__doc__': None, } os_helper.create_empty_file(path) @@ -252,11 +250,9 @@ def test_reload_location_changed(self): # Change to a package. self.init.invalidate_caches() init_path = os.path.join(cwd, name, '__init__.py') - cached = self.util.cache_from_source(init_path) expected = {'__name__': name, '__package__': name, '__file__': init_path, - '__cached__': cached, '__path__': [os.path.dirname(init_path)], '__doc__': None, } @@ -283,7 +279,6 @@ def test_reload_namespace_changed(self): # Start as a namespace package. self.init.invalidate_caches() bad_path = os.path.join(cwd, name, '__init.py') - cached = self.util.cache_from_source(bad_path) expected = {'__name__': name, '__package__': name, '__doc__': None, @@ -312,11 +307,9 @@ def test_reload_namespace_changed(self): # Change to a regular package. self.init.invalidate_caches() init_path = os.path.join(cwd, name, '__init__.py') - cached = self.util.cache_from_source(init_path) expected = {'__name__': name, '__package__': name, '__file__': init_path, - '__cached__': cached, '__path__': [os.path.dirname(init_path)], '__doc__': None, 'eggs': None, diff --git a/Lib/test/test_importlib/test_discover.py b/Lib/test/test_importlib/test_discover.py new file mode 100644 index 00000000000..c4ab7b6982e --- /dev/null +++ b/Lib/test/test_importlib/test_discover.py @@ -0,0 +1,121 @@ +from unittest.mock import Mock + +from test.test_importlib import util + +importlib = util.import_importlib('importlib') +machinery = util.import_importlib('importlib.machinery') + + +class DiscoverableFinder: + def __init__(self, discover=[]): + self._discovered_values = discover + + def find_spec(self, fullname, path=None, target=None): + raise NotImplementedError + + def discover(self, parent=None): + yield from self._discovered_values + + +class TestPathFinder: + """PathFinder implements MetaPathFinder, which uses the PathEntryFinder(s) + registered in sys.path_hooks (and sys.path_importer_cache) to search + sys.path or the parent's __path__. + + PathFinder.discover() should redirect to the .discover() method of the + PathEntryFinder for each path entry. + """ + + def test_search_path_hooks_top_level(self): + modules = [ + self.machinery.ModuleSpec(name='example1', loader=None), + self.machinery.ModuleSpec(name='example2', loader=None), + self.machinery.ModuleSpec(name='example3', loader=None), + ] + + with util.import_state( + path_importer_cache={ + 'discoverable': DiscoverableFinder(discover=modules), + }, + path=['discoverable'], + ): + discovered = list(self.machinery.PathFinder.discover()) + + self.assertEqual(discovered, modules) + + + def test_search_path_hooks_parent(self): + parent = self.machinery.ModuleSpec(name='example', loader=None, is_package=True) + parent.submodule_search_locations.append('discoverable') + + children = [ + self.machinery.ModuleSpec(name='example.child1', loader=None), + self.machinery.ModuleSpec(name='example.child2', loader=None), + self.machinery.ModuleSpec(name='example.child3', loader=None), + ] + + with util.import_state( + path_importer_cache={ + 'discoverable': DiscoverableFinder(discover=children) + }, + path=[], + ): + discovered = list(self.machinery.PathFinder.discover(parent)) + + self.assertEqual(discovered, children) + + def test_invalid_parent(self): + parent = self.machinery.ModuleSpec(name='example', loader=None) + with self.assertRaises(ValueError): + list(self.machinery.PathFinder.discover(parent)) + + +( + Frozen_TestPathFinder, + Source_TestPathFinder, +) = util.test_both(TestPathFinder, importlib=importlib, machinery=machinery) + + +class TestFileFinder: + """FileFinder implements PathEntryFinder and provides the base finder + implementation to search the file system. + """ + + def get_finder(self, path): + loader_details = [ + (self.machinery.SourceFileLoader, self.machinery.SOURCE_SUFFIXES), + (self.machinery.SourcelessFileLoader, self.machinery.BYTECODE_SUFFIXES), + ] + return self.machinery.FileFinder(path, *loader_details) + + def test_discover_top_level(self): + modules = {'example1', 'example2', 'example3'} + with util.create_modules(*modules) as mapping: + finder = self.get_finder(mapping['.root']) + discovered = list(finder.discover()) + self.assertEqual({spec.name for spec in discovered}, modules) + + def test_discover_parent(self): + modules = { + 'example.child1', + 'example.child2', + 'example.child3', + } + with util.create_modules(*modules) as mapping: + example = self.get_finder(mapping['.root']).find_spec('example') + finder = self.get_finder(example.submodule_search_locations[0]) + discovered = list(finder.discover(example)) + self.assertEqual({spec.name for spec in discovered}, modules) + + def test_invalid_parent(self): + with util.create_modules('example') as mapping: + finder = self.get_finder(mapping['.root']) + example = finder.find_spec('example') + with self.assertRaises(ValueError): + list(finder.discover(example)) + + +( + Frozen_TestFileFinder, + Source_TestFileFinder, +) = util.test_both(TestFileFinder, importlib=importlib, machinery=machinery) diff --git a/Lib/test/test_importlib/test_main.py b/Lib/test/test_importlib/test_main.py deleted file mode 100644 index 81f683799cb..00000000000 --- a/Lib/test/test_importlib/test_main.py +++ /dev/null @@ -1,427 +0,0 @@ -import re -import pickle -import unittest -import warnings -import importlib.metadata -import contextlib -import itertools - -try: - import pyfakefs.fake_filesystem_unittest as ffs -except ImportError: - from .stubs import fake_filesystem_unittest as ffs - -from . import fixtures -from ._context import suppress -from importlib.metadata import ( - Distribution, - EntryPoint, - PackageNotFoundError, - _unique, - distributions, - entry_points, - metadata, - packages_distributions, - version, -) - - -@contextlib.contextmanager -def suppress_known_deprecation(): - with warnings.catch_warnings(record=True) as ctx: - warnings.simplefilter('default', category=DeprecationWarning) - yield ctx - - -class BasicTests(fixtures.DistInfoPkg, unittest.TestCase): - version_pattern = r'\d+\.\d+(\.\d)?' - - def test_retrieves_version_of_self(self): - dist = Distribution.from_name('distinfo-pkg') - assert isinstance(dist.version, str) - assert re.match(self.version_pattern, dist.version) - - def test_for_name_does_not_exist(self): - with self.assertRaises(PackageNotFoundError): - Distribution.from_name('does-not-exist') - - def test_package_not_found_mentions_metadata(self): - """ - When a package is not found, that could indicate that the - package is not installed or that it is installed without - metadata. Ensure the exception mentions metadata to help - guide users toward the cause. See #124. - """ - with self.assertRaises(PackageNotFoundError) as ctx: - Distribution.from_name('does-not-exist') - - assert "metadata" in str(ctx.exception) - - # expected to fail until ABC is enforced - @suppress(AssertionError) - @suppress_known_deprecation() - def test_abc_enforced(self): - with self.assertRaises(TypeError): - type('DistributionSubclass', (Distribution,), {})() - - @fixtures.parameterize( - dict(name=None), - dict(name=''), - ) - def test_invalid_inputs_to_from_name(self, name): - with self.assertRaises(ValueError): - Distribution.from_name(name) - - -class ImportTests(fixtures.DistInfoPkg, unittest.TestCase): - def test_import_nonexistent_module(self): - # Ensure that the MetadataPathFinder does not crash an import of a - # non-existent module. - with self.assertRaises(ImportError): - importlib.import_module('does_not_exist') - - def test_resolve(self): - ep = entry_points(group='entries')['main'] - self.assertEqual(ep.load().__name__, "main") - - def test_entrypoint_with_colon_in_name(self): - ep = entry_points(group='entries')['ns:sub'] - self.assertEqual(ep.value, 'mod:main') - - def test_resolve_without_attr(self): - ep = EntryPoint( - name='ep', - value='importlib.metadata', - group='grp', - ) - assert ep.load() is importlib.metadata - - -class NameNormalizationTests(fixtures.OnSysPath, fixtures.SiteDir, unittest.TestCase): - @staticmethod - def make_pkg(name): - """ - Create minimal metadata for a dist-info package with - the indicated name on the file system. - """ - return { - f'{name}.dist-info': { - 'METADATA': 'VERSION: 1.0\n', - }, - } - - def test_dashes_in_dist_name_found_as_underscores(self): - """ - For a package with a dash in the name, the dist-info metadata - uses underscores in the name. Ensure the metadata loads. - """ - fixtures.build_files(self.make_pkg('my_pkg'), self.site_dir) - assert version('my-pkg') == '1.0' - - def test_dist_name_found_as_any_case(self): - """ - Ensure the metadata loads when queried with any case. - """ - pkg_name = 'CherryPy' - fixtures.build_files(self.make_pkg(pkg_name), self.site_dir) - assert version(pkg_name) == '1.0' - assert version(pkg_name.lower()) == '1.0' - assert version(pkg_name.upper()) == '1.0' - - def test_unique_distributions(self): - """ - Two distributions varying only by non-normalized name on - the file system should resolve as the same. - """ - fixtures.build_files(self.make_pkg('abc'), self.site_dir) - before = list(_unique(distributions())) - - alt_site_dir = self.fixtures.enter_context(fixtures.tempdir()) - self.fixtures.enter_context(self.add_sys_path(alt_site_dir)) - fixtures.build_files(self.make_pkg('ABC'), alt_site_dir) - after = list(_unique(distributions())) - - assert len(after) == len(before) - - -class NonASCIITests(fixtures.OnSysPath, fixtures.SiteDir, unittest.TestCase): - @staticmethod - def pkg_with_non_ascii_description(site_dir): - """ - Create minimal metadata for a package with non-ASCII in - the description. - """ - contents = { - 'portend.dist-info': { - 'METADATA': 'Description: pôrˈtend', - }, - } - fixtures.build_files(contents, site_dir) - return 'portend' - - @staticmethod - def pkg_with_non_ascii_description_egg_info(site_dir): - """ - Create minimal metadata for an egg-info package with - non-ASCII in the description. - """ - contents = { - 'portend.dist-info': { - 'METADATA': """ - Name: portend - - pôrˈtend""", - }, - } - fixtures.build_files(contents, site_dir) - return 'portend' - - def test_metadata_loads(self): - pkg_name = self.pkg_with_non_ascii_description(self.site_dir) - meta = metadata(pkg_name) - assert meta['Description'] == 'pôrˈtend' - - def test_metadata_loads_egg_info(self): - pkg_name = self.pkg_with_non_ascii_description_egg_info(self.site_dir) - meta = metadata(pkg_name) - assert meta['Description'] == 'pôrˈtend' - - -class DiscoveryTests( - fixtures.EggInfoPkg, - fixtures.EggInfoPkgPipInstalledNoToplevel, - fixtures.EggInfoPkgPipInstalledNoModules, - fixtures.EggInfoPkgSourcesFallback, - fixtures.DistInfoPkg, - unittest.TestCase, -): - def test_package_discovery(self): - dists = list(distributions()) - assert all(isinstance(dist, Distribution) for dist in dists) - assert any(dist.metadata['Name'] == 'egginfo-pkg' for dist in dists) - assert any(dist.metadata['Name'] == 'egg_with_module-pkg' for dist in dists) - assert any(dist.metadata['Name'] == 'egg_with_no_modules-pkg' for dist in dists) - assert any(dist.metadata['Name'] == 'sources_fallback-pkg' for dist in dists) - assert any(dist.metadata['Name'] == 'distinfo-pkg' for dist in dists) - - def test_invalid_usage(self): - with self.assertRaises(ValueError): - list(distributions(context='something', name='else')) - - -class DirectoryTest(fixtures.OnSysPath, fixtures.SiteDir, unittest.TestCase): - def test_egg_info(self): - # make an `EGG-INFO` directory that's unrelated - self.site_dir.joinpath('EGG-INFO').mkdir() - # used to crash with `IsADirectoryError` - with self.assertRaises(PackageNotFoundError): - version('unknown-package') - - def test_egg(self): - egg = self.site_dir.joinpath('foo-3.6.egg') - egg.mkdir() - with self.add_sys_path(egg): - with self.assertRaises(PackageNotFoundError): - version('foo') - - -class MissingSysPath(fixtures.OnSysPath, unittest.TestCase): - site_dir = '/does-not-exist' - - def test_discovery(self): - """ - Discovering distributions should succeed even if - there is an invalid path on sys.path. - """ - importlib.metadata.distributions() - - -class InaccessibleSysPath(fixtures.OnSysPath, ffs.TestCase): - site_dir = '/access-denied' - - def setUp(self): - super().setUp() - self.setUpPyfakefs() - self.fs.create_dir(self.site_dir, perm_bits=000) - - def test_discovery(self): - """ - Discovering distributions should succeed even if - there is an invalid path on sys.path. - """ - list(importlib.metadata.distributions()) - - -class TestEntryPoints(unittest.TestCase): - def __init__(self, *args): - super().__init__(*args) - self.ep = importlib.metadata.EntryPoint( - name='name', value='value', group='group' - ) - - def test_entry_point_pickleable(self): - revived = pickle.loads(pickle.dumps(self.ep)) - assert revived == self.ep - - def test_positional_args(self): - """ - Capture legacy (namedtuple) construction, discouraged. - """ - EntryPoint('name', 'value', 'group') - - def test_immutable(self): - """EntryPoints should be immutable""" - with self.assertRaises(AttributeError): - self.ep.name = 'badactor' - - def test_repr(self): - assert 'EntryPoint' in repr(self.ep) - assert 'name=' in repr(self.ep) - assert "'name'" in repr(self.ep) - - def test_hashable(self): - """EntryPoints should be hashable""" - hash(self.ep) - - def test_module(self): - assert self.ep.module == 'value' - - def test_attr(self): - assert self.ep.attr is None - - def test_sortable(self): - """ - EntryPoint objects are sortable, but result is undefined. - """ - sorted( - [ - EntryPoint(name='b', value='val', group='group'), - EntryPoint(name='a', value='val', group='group'), - ] - ) - - -class FileSystem( - fixtures.OnSysPath, fixtures.SiteDir, fixtures.FileBuilder, unittest.TestCase -): - def test_unicode_dir_on_sys_path(self): - """ - Ensure a Unicode subdirectory of a directory on sys.path - does not crash. - """ - fixtures.build_files( - {self.unicode_filename(): {}}, - prefix=self.site_dir, - ) - list(distributions()) - - -class PackagesDistributionsPrebuiltTest(fixtures.ZipFixtures, unittest.TestCase): - def test_packages_distributions_example(self): - self._fixture_on_path('example-21.12-py3-none-any.whl') - assert packages_distributions()['example'] == ['example'] - - def test_packages_distributions_example2(self): - """ - Test packages_distributions on a wheel built - by trampolim. - """ - self._fixture_on_path('example2-1.0.0-py3-none-any.whl') - assert packages_distributions()['example2'] == ['example2'] - - -class PackagesDistributionsTest( - fixtures.OnSysPath, fixtures.SiteDir, unittest.TestCase -): - def test_packages_distributions_neither_toplevel_nor_files(self): - """ - Test a package built without 'top-level.txt' or a file list. - """ - fixtures.build_files( - { - 'trim_example-1.0.0.dist-info': { - 'METADATA': """ - Name: trim_example - Version: 1.0.0 - """, - } - }, - prefix=self.site_dir, - ) - packages_distributions() - - def test_packages_distributions_all_module_types(self): - """ - Test top-level modules detected on a package without 'top-level.txt'. - """ - suffixes = importlib.machinery.all_suffixes() - metadata = dict( - METADATA=""" - Name: all_distributions - Version: 1.0.0 - """, - ) - files = { - 'all_distributions-1.0.0.dist-info': metadata, - } - for i, suffix in enumerate(suffixes): - files.update( - { - f'importable-name {i}{suffix}': '', - f'in_namespace_{i}': { - f'mod{suffix}': '', - }, - f'in_package_{i}': { - '__init__.py': '', - f'mod{suffix}': '', - }, - } - ) - metadata.update(RECORD=fixtures.build_record(files)) - fixtures.build_files(files, prefix=self.site_dir) - - distributions = packages_distributions() - - for i in range(len(suffixes)): - assert distributions[f'importable-name {i}'] == ['all_distributions'] - assert distributions[f'in_namespace_{i}'] == ['all_distributions'] - assert distributions[f'in_package_{i}'] == ['all_distributions'] - - assert not any(name.endswith('.dist-info') for name in distributions) - - -class PackagesDistributionsEggTest( - fixtures.EggInfoPkg, - fixtures.EggInfoPkgPipInstalledNoToplevel, - fixtures.EggInfoPkgPipInstalledNoModules, - fixtures.EggInfoPkgSourcesFallback, - unittest.TestCase, -): - def test_packages_distributions_on_eggs(self): - """ - Test old-style egg packages with a variation of 'top_level.txt', - 'SOURCES.txt', and 'installed-files.txt', available. - """ - distributions = packages_distributions() - - def import_names_from_package(package_name): - return { - import_name - for import_name, package_names in distributions.items() - if package_name in package_names - } - - # egginfo-pkg declares one import ('mod') via top_level.txt - assert import_names_from_package('egginfo-pkg') == {'mod'} - - # egg_with_module-pkg has one import ('egg_with_module') inferred from - # installed-files.txt (top_level.txt is missing) - assert import_names_from_package('egg_with_module-pkg') == {'egg_with_module'} - - # egg_with_no_modules-pkg should not be associated with any import names - # (top_level.txt is empty, and installed-files.txt has no .py files) - assert import_names_from_package('egg_with_no_modules-pkg') == set() - - # sources_fallback-pkg has one import ('sources_fallback') inferred from - # SOURCES.txt (top_level.txt and installed-files.txt is missing) - assert import_names_from_package('sources_fallback-pkg') == {'sources_fallback'} diff --git a/Lib/test/test_importlib/test_metadata_api.py b/Lib/test/test_importlib/test_metadata_api.py deleted file mode 100644 index 33c6e85ee94..00000000000 --- a/Lib/test/test_importlib/test_metadata_api.py +++ /dev/null @@ -1,322 +0,0 @@ -import re -import textwrap -import unittest -import warnings -import importlib -import contextlib - -from . import fixtures -from importlib.metadata import ( - Distribution, - PackageNotFoundError, - distribution, - entry_points, - files, - metadata, - requires, - version, -) - - -@contextlib.contextmanager -def suppress_known_deprecation(): - with warnings.catch_warnings(record=True) as ctx: - warnings.simplefilter('default', category=DeprecationWarning) - yield ctx - - -class APITests( - fixtures.EggInfoPkg, - fixtures.EggInfoPkgPipInstalledNoToplevel, - fixtures.EggInfoPkgPipInstalledNoModules, - fixtures.EggInfoPkgSourcesFallback, - fixtures.DistInfoPkg, - fixtures.DistInfoPkgWithDot, - fixtures.EggInfoFile, - unittest.TestCase, -): - version_pattern = r'\d+\.\d+(\.\d)?' - - def test_retrieves_version_of_self(self): - pkg_version = version('egginfo-pkg') - assert isinstance(pkg_version, str) - assert re.match(self.version_pattern, pkg_version) - - def test_retrieves_version_of_distinfo_pkg(self): - pkg_version = version('distinfo-pkg') - assert isinstance(pkg_version, str) - assert re.match(self.version_pattern, pkg_version) - - def test_for_name_does_not_exist(self): - with self.assertRaises(PackageNotFoundError): - distribution('does-not-exist') - - def test_name_normalization(self): - names = 'pkg.dot', 'pkg_dot', 'pkg-dot', 'pkg..dot', 'Pkg.Dot' - for name in names: - with self.subTest(name): - assert distribution(name).metadata['Name'] == 'pkg.dot' - - def test_prefix_not_matched(self): - prefixes = 'p', 'pkg', 'pkg.' - for prefix in prefixes: - with self.subTest(prefix): - with self.assertRaises(PackageNotFoundError): - distribution(prefix) - - def test_for_top_level(self): - tests = [ - ('egginfo-pkg', 'mod'), - ('egg_with_no_modules-pkg', ''), - ] - for pkg_name, expect_content in tests: - with self.subTest(pkg_name): - self.assertEqual( - distribution(pkg_name).read_text('top_level.txt').strip(), - expect_content, - ) - - def test_read_text(self): - tests = [ - ('egginfo-pkg', 'mod\n'), - ('egg_with_no_modules-pkg', '\n'), - ] - for pkg_name, expect_content in tests: - with self.subTest(pkg_name): - top_level = [ - path for path in files(pkg_name) if path.name == 'top_level.txt' - ][0] - self.assertEqual(top_level.read_text(), expect_content) - - def test_entry_points(self): - eps = entry_points() - assert 'entries' in eps.groups - entries = eps.select(group='entries') - assert 'main' in entries.names - ep = entries['main'] - self.assertEqual(ep.value, 'mod:main') - self.assertEqual(ep.extras, []) - - def test_entry_points_distribution(self): - entries = entry_points(group='entries') - for entry in ("main", "ns:sub"): - ep = entries[entry] - self.assertIn(ep.dist.name, ('distinfo-pkg', 'egginfo-pkg')) - self.assertEqual(ep.dist.version, "1.0.0") - - def test_entry_points_unique_packages_normalized(self): - """ - Entry points should only be exposed for the first package - on sys.path with a given name (even when normalized). - """ - alt_site_dir = self.fixtures.enter_context(fixtures.tempdir()) - self.fixtures.enter_context(self.add_sys_path(alt_site_dir)) - alt_pkg = { - "DistInfo_pkg-1.1.0.dist-info": { - "METADATA": """ - Name: distinfo-pkg - Version: 1.1.0 - """, - "entry_points.txt": """ - [entries] - main = mod:altmain - """, - }, - } - fixtures.build_files(alt_pkg, alt_site_dir) - entries = entry_points(group='entries') - assert not any( - ep.dist.name == 'distinfo-pkg' and ep.dist.version == '1.0.0' - for ep in entries - ) - # ns:sub doesn't exist in alt_pkg - assert 'ns:sub' not in entries.names - - def test_entry_points_missing_name(self): - with self.assertRaises(KeyError): - entry_points(group='entries')['missing'] - - def test_entry_points_missing_group(self): - assert entry_points(group='missing') == () - - def test_entry_points_allows_no_attributes(self): - ep = entry_points().select(group='entries', name='main') - with self.assertRaises(AttributeError): - ep.foo = 4 - - def test_metadata_for_this_package(self): - md = metadata('egginfo-pkg') - assert md['author'] == 'Steven Ma' - assert md['LICENSE'] == 'Unknown' - assert md['Name'] == 'egginfo-pkg' - classifiers = md.get_all('Classifier') - assert 'Topic :: Software Development :: Libraries' in classifiers - - def test_missing_key_legacy(self): - """ - Requesting a missing key will still return None, but warn. - """ - md = metadata('distinfo-pkg') - with suppress_known_deprecation(): - assert md['does-not-exist'] is None - - def test_get_key(self): - """ - Getting a key gets the key. - """ - md = metadata('egginfo-pkg') - assert md.get('Name') == 'egginfo-pkg' - - def test_get_missing_key(self): - """ - Requesting a missing key will return None. - """ - md = metadata('distinfo-pkg') - assert md.get('does-not-exist') is None - - @staticmethod - def _test_files(files): - root = files[0].root - for file in files: - assert file.root == root - assert not file.hash or file.hash.value - assert not file.hash or file.hash.mode == 'sha256' - assert not file.size or file.size >= 0 - assert file.locate().exists() - assert isinstance(file.read_binary(), bytes) - if file.name.endswith('.py'): - file.read_text() - - def test_file_hash_repr(self): - util = [p for p in files('distinfo-pkg') if p.name == 'mod.py'][0] - self.assertRegex(repr(util.hash), '') - - def test_files_dist_info(self): - self._test_files(files('distinfo-pkg')) - - def test_files_egg_info(self): - self._test_files(files('egginfo-pkg')) - self._test_files(files('egg_with_module-pkg')) - self._test_files(files('egg_with_no_modules-pkg')) - self._test_files(files('sources_fallback-pkg')) - - def test_version_egg_info_file(self): - self.assertEqual(version('egginfo-file'), '0.1') - - def test_requires_egg_info_file(self): - requirements = requires('egginfo-file') - self.assertIsNone(requirements) - - def test_requires_egg_info(self): - deps = requires('egginfo-pkg') - assert len(deps) == 2 - assert any(dep == 'wheel >= 1.0; python_version >= "2.7"' for dep in deps) - - def test_requires_egg_info_empty(self): - fixtures.build_files( - { - 'requires.txt': '', - }, - self.site_dir.joinpath('egginfo_pkg.egg-info'), - ) - deps = requires('egginfo-pkg') - assert deps == [] - - def test_requires_dist_info(self): - deps = requires('distinfo-pkg') - assert len(deps) == 2 - assert all(deps) - assert 'wheel >= 1.0' in deps - assert "pytest; extra == 'test'" in deps - - def test_more_complex_deps_requires_text(self): - requires = textwrap.dedent( - """ - dep1 - dep2 - - [:python_version < "3"] - dep3 - - [extra1] - dep4 - dep6@ git+https://example.com/python/dep.git@v1.0.0 - - [extra2:python_version < "3"] - dep5 - """ - ) - deps = sorted(Distribution._deps_from_requires_text(requires)) - expected = [ - 'dep1', - 'dep2', - 'dep3; python_version < "3"', - 'dep4; extra == "extra1"', - 'dep5; (python_version < "3") and extra == "extra2"', - 'dep6@ git+https://example.com/python/dep.git@v1.0.0 ; extra == "extra1"', - ] - # It's important that the environment marker expression be - # wrapped in parentheses to avoid the following 'and' binding more - # tightly than some other part of the environment expression. - - assert deps == expected - - def test_as_json(self): - md = metadata('distinfo-pkg').json - assert 'name' in md - assert md['keywords'] == ['sample', 'package'] - desc = md['description'] - assert desc.startswith('Once upon a time\nThere was') - assert len(md['requires_dist']) == 2 - - def test_as_json_egg_info(self): - md = metadata('egginfo-pkg').json - assert 'name' in md - assert md['keywords'] == ['sample', 'package'] - desc = md['description'] - assert desc.startswith('Once upon a time\nThere was') - assert len(md['classifier']) == 2 - - def test_as_json_odd_case(self): - self.make_uppercase() - md = metadata('distinfo-pkg').json - assert 'name' in md - assert len(md['requires_dist']) == 2 - assert md['keywords'] == ['SAMPLE', 'PACKAGE'] - - -class LegacyDots(fixtures.DistInfoPkgWithDotLegacy, unittest.TestCase): - def test_name_normalization(self): - names = 'pkg.dot', 'pkg_dot', 'pkg-dot', 'pkg..dot', 'Pkg.Dot' - for name in names: - with self.subTest(name): - assert distribution(name).metadata['Name'] == 'pkg.dot' - - def test_name_normalization_versionless_egg_info(self): - names = 'pkg.lot', 'pkg_lot', 'pkg-lot', 'pkg..lot', 'Pkg.Lot' - for name in names: - with self.subTest(name): - assert distribution(name).metadata['Name'] == 'pkg.lot' - - -class OffSysPathTests(fixtures.DistInfoPkgOffPath, unittest.TestCase): - def test_find_distributions_specified_path(self): - dists = Distribution.discover(path=[str(self.site_dir)]) - assert any(dist.metadata['Name'] == 'distinfo-pkg' for dist in dists) - - def test_distribution_at_pathlib(self): - """Demonstrate how to load metadata direct from a directory.""" - dist_info_path = self.site_dir / 'distinfo_pkg-1.0.0.dist-info' - dist = Distribution.at(dist_info_path) - assert dist.version == '1.0.0' - - def test_distribution_at_str(self): - dist_info_path = self.site_dir / 'distinfo_pkg-1.0.0.dist-info' - dist = Distribution.at(str(dist_info_path)) - assert dist.version == '1.0.0' - - -class InvalidateCache(unittest.TestCase): - def test_invalidate_cache(self): - # No externally observable behavior, but ensures test coverage... - importlib.invalidate_caches() diff --git a/Lib/test/test_importlib/test_namespace_pkgs.py b/Lib/test/test_importlib/test_namespace_pkgs.py index 6ca0978f9bc..522ed9fa43f 100644 --- a/Lib/test/test_importlib/test_namespace_pkgs.py +++ b/Lib/test/test_importlib/test_namespace_pkgs.py @@ -318,6 +318,17 @@ def test_module_before_namespace_package(self): self.assertEqual(a_test.attr, 'in module') +class NamespaceSubpackageSameName(NamespacePackageTest): + paths = [''] + + def test_namespace_subpackage_shares_name_with_directory(self): + submodule_path = 'project4.foo' + with self.assertRaises(ModuleNotFoundError) as cm: + importlib.machinery.PathFinder.find_spec(submodule_path) + + self.assertEqual(cm.exception.name, 'project4') + + class ReloadTests(NamespacePackageTest): paths = ['portion1'] diff --git a/Lib/test/test_importlib/test_pkg_import.py b/Lib/test/test_importlib/test_pkg_import.py index 5ffae6222ba..287684efc85 100644 --- a/Lib/test/test_importlib/test_pkg_import.py +++ b/Lib/test/test_importlib/test_pkg_import.py @@ -39,9 +39,12 @@ def tearDown(self): self.remove_modules() def rewrite_file(self, contents): - compiled_path = cache_from_source(self.module_path) - if os.path.exists(compiled_path): - os.remove(compiled_path) + try: + compiled_path = cache_from_source(self.module_path) + if os.path.exists(compiled_path): + os.remove(compiled_path) + except NotImplementedError: + pass with open(self.module_path, 'w', encoding='utf-8') as f: f.write(contents) diff --git a/Lib/test/test_importlib/test_spec.py b/Lib/test/test_importlib/test_spec.py index aebeabaf83f..77b6228940c 100644 --- a/Lib/test/test_importlib/test_spec.py +++ b/Lib/test/test_importlib/test_spec.py @@ -52,7 +52,10 @@ class ModuleSpecTests: def setUp(self): self.name = 'spam' self.path = 'spam.py' - self.cached = self.util.cache_from_source(self.path) + try: + self.cached = self.util.cache_from_source(self.path) + except NotImplementedError: + self.cached = None self.loader = TestLoader() self.spec = self.machinery.ModuleSpec(self.name, self.loader) self.loc_spec = self.machinery.ModuleSpec(self.name, self.loader, @@ -184,6 +187,8 @@ def test_cached_with_origin_not_location(self): self.assertIs(spec.cached, None) + @unittest.skipIf(sys.implementation.cache_tag is None, + "sys.implementation.cache_tag is None") def test_cached_source(self): expected = self.util.cache_from_source(self.path) @@ -224,7 +229,10 @@ def bootstrap(self): def setUp(self): self.name = 'spam' self.path = 'spam.py' - self.cached = self.util.cache_from_source(self.path) + try: + self.cached = self.util.cache_from_source(self.path) + except NotImplementedError: + self.cached = None self.loader = TestLoader() self.spec = self.machinery.ModuleSpec(self.name, self.loader) self.loc_spec = self.machinery.ModuleSpec(self.name, self.loader, @@ -287,20 +295,6 @@ def exec_module(self, module): loaded = self.bootstrap._load(self.spec) self.assertNotIn(self.spec.name, sys.modules) - def test_load_legacy_attributes_immutable(self): - module = object() - with warnings.catch_warnings(): - warnings.simplefilter("ignore", ImportWarning) - class ImmutableLoader(TestLoader): - def load_module(self, name): - sys.modules[name] = module - return module - self.spec.loader = ImmutableLoader() - with CleanImport(self.spec.name): - loaded = self.bootstrap._load(self.spec) - - self.assertIs(sys.modules[self.spec.name], module) - # reload() def test_reload(self): @@ -350,7 +344,6 @@ def test_reload_init_module_attrs(self): self.assertIs(loaded.__spec__, self.spec) self.assertNotHasAttr(loaded, '__path__') self.assertNotHasAttr(loaded, '__file__') - self.assertNotHasAttr(loaded, '__cached__') (Frozen_ModuleSpecMethodsTests, @@ -364,7 +357,10 @@ class FactoryTests: def setUp(self): self.name = 'spam' self.path = os.path.abspath('spam.py') - self.cached = self.util.cache_from_source(self.path) + try: + self.cached = self.util.cache_from_source(self.path) + except NotImplementedError: + self.cached = None self.loader = TestLoader() self.fileloader = TestLoader(self.path) self.pkgloader = TestLoader(self.path, True) diff --git a/Lib/test/test_importlib/test_threaded_import.py b/Lib/test/test_importlib/test_threaded_import.py index 0e0d0721eb5..7af1f25000a 100644 --- a/Lib/test/test_importlib/test_threaded_import.py +++ b/Lib/test/test_importlib/test_threaded_import.py @@ -6,12 +6,16 @@ # randrange, and then Python hangs. import _imp as imp +import collections +import faulthandler import os import importlib +import importlib.machinery import sys import time import shutil import threading +import types import unittest from test import support from test.support import verbose @@ -260,7 +264,6 @@ def test_multiprocessing_pool_circular_import(self, size): 'partial', 'pool_in_threads.py') script_helper.assert_python_ok(fn) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_import_failure_race_condition(self): # Regression test for race condition where a thread could receive # a partially-initialized module when another thread's import fails. @@ -326,6 +329,705 @@ def do_import(delay=0): # Neither thread should have errors about stale modules self.assertEqual(errors, [], f"Race condition detected: {errors}") + def test_hierarchical_import_deadlock(self): + # Regression test for bpo-38884 / gh-83065 + # Tests that concurrent imports at different hierarchy levels + # don't deadlock when parent imports child in __init__.py + + # Create package structure: + # package/__init__.py: from package import subpackage + # package/subpackage/__init__.py: from package.subpackage.module import * + # package/subpackage/module.py: class SomeClass: pass + + pkg_dir = os.path.join(TESTFN, 'hier_deadlock_pkg') + os.makedirs(pkg_dir) + self.addCleanup(shutil.rmtree, TESTFN) + + subpkg_dir = os.path.join(pkg_dir, 'subpackage') + os.makedirs(subpkg_dir) + + with open(os.path.join(pkg_dir, "__init__.py"), "w") as f: + f.write("from hier_deadlock_pkg import subpackage\n") + + with open(os.path.join(subpkg_dir, "__init__.py"), "w") as f: + f.write("from hier_deadlock_pkg.subpackage.module import *\n") + + with open(os.path.join(subpkg_dir, "module.py"), "w") as f: + f.write("class SomeClass:\n pass\n") + + sys.path.insert(0, TESTFN) + self.addCleanup(sys.path.remove, TESTFN) + self.addCleanup(forget, 'hier_deadlock_pkg') + self.addCleanup(forget, 'hier_deadlock_pkg.subpackage') + self.addCleanup(forget, 'hier_deadlock_pkg.subpackage.module') + + importlib.invalidate_caches() + + errors = [] + results = [] + barrier = threading.Barrier(2) + + def t1(): + barrier.wait() + try: + import hier_deadlock_pkg.subpackage + results.append('t1_success') + except Exception as e: + errors.append(('t1', type(e).__name__, str(e))) + + def t2(): + barrier.wait() + try: + import hier_deadlock_pkg.subpackage.module + results.append('t2_success') + except Exception as e: + errors.append(('t2', type(e).__name__, str(e))) + + # Run multiple times to increase chance of hitting race condition + for i in range(10): + for mod in ['hier_deadlock_pkg', 'hier_deadlock_pkg.subpackage', + 'hier_deadlock_pkg.subpackage.module']: + sys.modules.pop(mod, None) + + errors.clear() + results.clear() + barrier.reset() + + thread1 = threading.Thread(target=t1) + thread2 = threading.Thread(target=t2) + + thread1.start() + thread2.start() + + thread1.join(timeout=5) + thread2.join(timeout=5) + + if thread1.is_alive() or thread2.is_alive(): + self.fail(f"Threads deadlocked on iteration {i}") + + self.assertEqual( + errors, [], + f"Import(s) failed on iteration {i}: {errors}") + self.assertEqual( + sorted(results), ['t1_success', 't2_success'], + f"Not all imports succeeded on iteration {i}: {results}") + + def test_cross_package_circular_import(self): + # Two packages whose __init__.py each import a submodule of the + # other. Concurrent imports of submodules of each must not raise + # _DeadlockError; the import system accepts a partially-initialised + # parent in this case (see _lock_unlock_module). + os.makedirs(os.path.join(TESTFN, "circ_a")) + os.makedirs(os.path.join(TESTFN, "circ_b")) + self.addCleanup(shutil.rmtree, TESTFN) + with open(os.path.join(TESTFN, "circ_a", "__init__.py"), "w") as f: + f.write("import time; time.sleep(0.03)\nimport circ_b.other\n") + with open(os.path.join(TESTFN, "circ_b", "__init__.py"), "w") as f: + f.write("import time; time.sleep(0.03)\nimport circ_a.other\n") + for pkg in ("circ_a", "circ_b"): + for mod in ("sub.py", "other.py"): + with open(os.path.join(TESTFN, pkg, mod), "w") as f: + f.write("X = 1\n") + + sys.path.insert(0, TESTFN) + self.addCleanup(sys.path.remove, TESTFN) + for mod in ("circ_a", "circ_a.sub", "circ_a.other", + "circ_b", "circ_b.sub", "circ_b.other"): + self.addCleanup(forget, mod) + importlib.invalidate_caches() + + errors = [] + barrier = threading.Barrier(2) + + def do_import(name): + barrier.wait() + try: + importlib.import_module(name) + except Exception as e: + errors.append((name, type(e).__name__, str(e))) + + for i in range(10): + for mod in ("circ_a", "circ_a.sub", "circ_a.other", + "circ_b", "circ_b.sub", "circ_b.other"): + sys.modules.pop(mod, None) + errors.clear() + barrier.reset() + + thread1 = threading.Thread(target=do_import, args=("circ_a.sub",)) + thread2 = threading.Thread(target=do_import, args=("circ_b.sub",)) + thread1.start() + thread2.start() + thread1.join(timeout=5) + thread2.join(timeout=5) + + if thread1.is_alive() or thread2.is_alive(): + self.fail(f"Threads deadlocked on iteration {i}") + self.assertEqual( + errors, [], + f"Import(s) failed on iteration {i}: {errors}") + + # Helpers for the deterministic two-thread tests below. Rather than + # relying on sleeps, a package __init__ calls back into the test and is + # held there until the second thread is observed waiting on a specific + # module lock, so the problematic interleaving happens on every run. + + def _setup_package_tree(self, files): + # These tests are about what happens when one module's body imports + # another. Under -X lazy_imports=all those imports would never run. + self.addCleanup(sys.set_lazy_imports, sys.get_lazy_imports()) + sys.set_lazy_imports("normal") + os.makedirs(TESTFN, exist_ok=True) + self.addCleanup(rmtree, TESTFN) + for relpath, source in files.items(): + path = os.path.join(TESTFN, *relpath.split("/")) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as f: + f.write(source) + sys.path.insert(0, TESTFN) + self.addCleanup(sys.path.remove, TESTFN) + # Forget by top-level name, not by file name: a submodule may come + # from a directory added to __path__ or have no file at all. + tops = {relpath.partition("/")[0].removesuffix(".py") + for relpath in files} + self.addCleanup(self._forget_trees, tops) + importlib.invalidate_caches() + + @staticmethod + def _forget_trees(tops): + for name in list(sys.modules): + if name.partition(".")[0] in tops: + forget(name) + + def _wait_until_blocked_on(self, thread, modname): + # Return once *thread* is waiting to acquire *modname*'s module lock + # (any module lock if *modname* is None) and another thread owns it. + # The owner check matters: a lock is listed in _blocking_on for a + # moment during every acquire(), contended or not. + blocking_on = importlib._bootstrap._blocking_on + for _ in support.sleeping_retry( + support.SHORT_TIMEOUT, + f"thread never waited for the module lock of {modname!r}"): + for lock in list(blocking_on.get(thread.ident, ())): + if (modname in (None, lock.name) + and lock.owner not in (None, thread.ident)): + return + if not thread.is_alive(): + self.fail("thread finished without ever waiting for the " + f"module lock of {modname!r}") + + def _join_import_threads(self, threads): + # Every wait made by the test's own code inside these threads is + # bounded by SHORT_TIMEOUT and reports what it was waiting for, so + # wait longer than their sum here: only a real import deadlock gets + # this far. The threads are daemons so that one cannot also block + # interpreter shutdown. + deadline = time.monotonic() + support.LONG_TIMEOUT + for t in threads: + if t.ident is not None: + t.join(max(deadline - time.monotonic(), 0)) + hung = [t for t in threads if t.is_alive()] + if hung: + faulthandler.dump_traceback(sys.__stderr__) + self.fail(f"import deadlock: unable to join {hung}") + + def _run_two_first_imports(self, files, stmt1, stmt2, *, + sync_name, t2_waits_for): + # Thread 1 runs stmt1. Something it executes calls + # .hold(), which starts thread 2 on stmt2 and returns + # only once thread 2 is blocked on the module lock of t2_waits_for + # (any module lock if None). Module code may also call + # .join_t2() to wait for thread 2 to finish. + # Returns a list of (what, problem) pairs; empty means both imports + # succeeded and no module body ran more than once. + # list.append() is atomic, on free-threaded builds too. + count = f"import {sync_name}; {sync_name}.executed.append(__name__)\n" + self._setup_package_tree({relpath: count + source + for relpath, source in files.items()}) + sync = types.ModuleType(sync_name) + sync.executed = [] + sys.modules[sync_name] = sync + self.addCleanup(sys.modules.pop, sync_name, None) + errors = [] + + def run(stmt): + try: + exec(stmt, {}) + except Exception as e: + errors.append((stmt, f"{type(e).__name__}: {e}")) + + t1 = threading.Thread(target=run, args=(stmt1,), daemon=True) + t2 = threading.Thread(target=run, args=(stmt2,), daemon=True) + + def hold(): + # One-shot: if thread 1's import fails, thread 2 may re-run the + # same code; it must not wait on itself. + if t2.ident is not None: + return + t2.start() + self._wait_until_blocked_on(t2, t2_waits_for) + sync.hold = hold + + def join_t2(): + t2.join(support.SHORT_TIMEOUT) + if t2.is_alive(): + errors.append((stmt2, "still blocked while thread 1's module " + "code waited for it")) + sync.join_t2 = join_t2 + + t1.start() + self._join_import_threads([t1, t2]) + if t2.ident is None: + errors.append((stmt2, "was never started")) + for name, n in collections.Counter(sync.executed).items(): + if n != 1: + errors.append((name, f"executed {n} times")) + return errors + + def _hold_in_create_module(self, modname, sync_name): + # Have the import of *modname* call .hold() from its + # loader's create_module(): the importing thread then owns modname's + # module lock but modname is not in sys.modules yet. (A finder's + # find_spec() would be too early a place to stop: it runs under the + # global import lock, which every other import needs briefly.) + class Loader(importlib.machinery.SourceFileLoader): + def create_module(self, spec): + sys.modules[sync_name].hold() + return super().create_module(spec) + + class Finder: + def find_spec(self, name, path=None, target=None): + if name != modname: + return None + spec = importlib.machinery.PathFinder.find_spec( + name, path, target) + spec.loader = Loader(spec.loader.name, spec.loader.path) + return spec + + finder = Finder() + sys.meta_path.insert(0, finder) + self.addCleanup(sys.meta_path.remove, finder) + + # A first import of {pkg}.mod. The statements call back into C + # (import_ensure_initialized()) for a parent that is in sys.modules; + # import_module() stays in _find_and_load(). + SUBMODULE_IMPORTS = ( + "from {pkg}.mod import X", + "import {pkg}.mod", + "import importlib; importlib.import_module('{pkg}.mod')", + ) + + def test_parent_lock_not_held_while_submodule_executes(self): + # gh-159963: the first `import pkg.mod` in a process also imports pkg. + # Once pkg/__init__.py has finished, pkg's module lock must not stay + # held while mod's body runs; otherwise every thread that began + # waiting for pkg is blocked for the whole of mod's body as well. + self._setup_package_tree({ + "unheld_pkg/__init__.py": "", + "unheld_pkg/mod.py": ( + "import sys, importlib._bootstrap as _b\n" + "def held(name):\n" + " ref = _b._module_locks.get(name)\n" + " lock = ref() if ref is not None else None\n" + " return lock is not None and lock.locked()\n" + "own_lock_held = held(__name__)\n" + "parent_lock_held = held('unheld_pkg')\n" + "parent_initializing = " + "sys.modules['unheld_pkg'].__spec__._initializing\n"), + }) + import unheld_pkg.mod + self.assertTrue(unheld_pkg.mod.own_lock_held) + self.assertFalse(unheld_pkg.mod.parent_initializing) + self.assertFalse(unheld_pkg.mod.parent_lock_held) + + def test_package_init_imports_submodule_deterministic(self): + # gh-83065 (bpo-38884) with the losing interleaving forced: thread 1 + # is inside pkg/__init__.py, about to import pkg.mod, at the moment + # thread 2's first import of pkg.mod has got as far as waiting for + # pkg. Thread 2 must be waiting *without* already owning pkg.mod's + # lock, or thread 1's import of pkg.mod deadlocks against it. + for i, stmt in enumerate(self.SUBMODULE_IMPORTS): + pkg = f"detinit{i}_pkg" + stmt = stmt.format(pkg=pkg) + with self.subTest(stmt=stmt): + errors = self._run_two_first_imports( + { + f"{pkg}/__init__.py": ( + "import detinit_sync; detinit_sync.hold()\n" + f"import {pkg}.mod\n"), + f"{pkg}/mod.py": "X = 1\n", + }, + f"import {pkg}", + stmt, + sync_name="detinit_sync", + t2_waits_for=pkg, + ) + self.assertEqual(errors, []) + self.assertEqual(sys.modules[f"{pkg}.mod"].X, 1) + + def test_submodule_import_while_package_not_yet_in_sys_modules(self): + # gh-83065, the earlier window: thread 1 owns pkg's lock but has not + # put pkg in sys.modules yet when thread 2 first imports pkg.mod. + for i, stmt in enumerate(self.SUBMODULE_IMPORTS): + pkg = f"early{i}_pkg" + stmt = stmt.format(pkg=pkg) + with self.subTest(stmt=stmt): + self._hold_in_create_module(pkg, "early_sync") + errors = self._run_two_first_imports( + { + f"{pkg}/__init__.py": "from . import mod\n", + f"{pkg}/mod.py": "X = 1\n", + }, + f"import {pkg}", + stmt, + sync_name="early_sync", + t2_waits_for=pkg, + ) + self.assertEqual(errors, []) + self.assertEqual(sys.modules[f"{pkg}.mod"].X, 1) + + def test_submodule_found_via_path_set_late_in_package_init(self): + # pkg.mod can only be found once pkg/__init__.py has replaced + # __path__, pkgutil.extend_path() style. Thread 2 must look at + # pkg.__path__ after it has waited for pkg, not before. + extra = os.path.abspath(os.path.join(TESTFN, "latepath_extra")) + errors = self._run_two_first_imports( + { + "latepath_pkg/__init__.py": ( + "import latepath_sync; latepath_sync.hold()\n" + f"__path__ = [*__path__, {extra!r}]\n"), + "latepath_extra/mod.py": "X = 1\n", + }, + "import latepath_pkg", + "from latepath_pkg.mod import X", + sync_name="latepath_sync", + t2_waits_for="latepath_pkg", + ) + self.assertEqual(errors, []) + self.assertEqual(sys.modules["latepath_pkg.mod"].X, 1) + + def test_submodule_put_in_sys_modules_late_in_package_init(self): + # gh-130094: there is no pkg/mod.py; pkg/__init__.py puts pkg.mod in + # sys.modules itself, as collections does for collections.abc. + errors = self._run_two_first_imports( + { + "inject_pkg/__init__.py": ( + "import inject_sync; inject_sync.hold()\n" + "import sys, types\n" + "mod = types.ModuleType('inject_pkg.mod'); mod.X = 1\n" + "sys.modules['inject_pkg.mod'] = mod\n"), + }, + "import inject_pkg", + "from inject_pkg.mod import X", + sync_name="inject_sync", + t2_waits_for="inject_pkg", + ) + self.assertEqual(errors, []) + + def test_concurrent_first_imports_of_sibling_packages(self): + # gh-159963. Thread 1: `import a.leaf`, where a/leaf.py needs b.leaf. + # Thread 2: `import b.leaf`, where b/__init__.py needs a, started + # while thread 1 is still inside a/__init__.py. + # Dependencies are a.leaf -> b.leaf -> b -> a; `a` needs nothing, so + # there is no cycle and either order works in one thread. If the + # importer of a.leaf kept a's lock for the duration of a/leaf.py, + # this would raise _DeadlockError. + errors = self._run_two_first_imports( + { + "sib_a/__init__.py": "import sib_sync; sib_sync.hold()\n", + "sib_a/leaf.py": "from sib_b.leaf import X\n", + "sib_b/__init__.py": "import sib_a\n", + "sib_b/leaf.py": "X = 1\n", + }, + "import sib_a.leaf", + "import sib_b.leaf", + sync_name="sib_sync", + t2_waits_for="sib_a", + ) + self.assertEqual(errors, []) + self.assertEqual(sys.modules["sib_a.leaf"].X, 1) + self.assertEqual(sys.modules["sib_b.leaf"].X, 1) + + def test_finished_package_import_not_blocked_by_submodule_body(self): + # Thread 2 starts waiting for pkg while pkg/__init__.py runs. It + # needs only the finished pkg, so it must be released when that + # __init__ returns and not when thread 1's pkg/main.py does. Here + # main.py waits for thread 2, which no deadlock detector can see. + for i, stmt in enumerate(( + "import {pkg}", + "import {pkg}.other", + "from {pkg}.other import X")): + pkg = f"body{i}_pkg" + stmt = stmt.format(pkg=pkg) + with self.subTest(stmt=stmt): + errors = self._run_two_first_imports( + { + f"{pkg}/__init__.py": ( + "import body_sync; body_sync.hold()\n"), + f"{pkg}/main.py": ( + "import body_sync; body_sync.join_t2()\n"), + f"{pkg}/other.py": "X = 1\n", + }, + f"import {pkg}.main", + stmt, + sync_name="body_sync", + t2_waits_for=pkg, + ) + self.assertEqual(errors, []) + + def test_concurrent_first_imports_of_nested_packages(self): + # Thread 1 does `import g.sub.leaf`; g/sub/__init__.py needs + # module c; c needs g. Thread 2 imports c + # while thread 1 is still inside g/__init__.py. No cycle. If + # thread 1 still held g's lock while it ran g/sub/__init__.py, + # thread 2 (holding c, waiting for g) would look deadlocked to it + # and it would get "cannot import name 'X' from partially + # initialized module". So g's lock must be released before any + # package beneath it executes, not only before the leaf's body. + errors = self._run_two_first_imports( + { + "nest_g/__init__.py": "import nest_sync; nest_sync.hold()\n", + "nest_g/sub/__init__.py": "from nest_c import X\n", + "nest_g/sub/leaf.py": "Y = 2\n", + "nest_c.py": "import nest_g\nX = 1\n", + }, + "import nest_g.sub.leaf", + "import nest_c", + sync_name="nest_sync", + t2_waits_for="nest_g", + ) + self.assertEqual(errors, []) + self.assertEqual(sys.modules["nest_g.sub"].X, 1) + self.assertEqual(sys.modules["nest_g.sub.leaf"].Y, 2) + + def test_submodule_import_waits_for_initializing_top_package(self): + # Thread 1 runs g/__init__.py, which has imported subpackage g.a and + # will next need g.a.other. Thread 2's first import of g.a.other + # starts at that point; other.py needs an attribute of g that is + # already set. Thread 2 must wait for g *before* owning g.a.other: + # if it loaded g.a.other first and only then blocked on g (inside + # other.py), thread 1 would find g.a.other held by a thread waiting + # on itself and be handed the half-executed module ("cannot import + # name 'X'"). Nothing here can fail in a single thread. + errors = self._run_two_first_imports( + { + "topw_g/__init__.py": ( + "Z = 1\n" + "import topw_g.a\n" + "import topw_sync; topw_sync.hold()\n" + "from topw_g.a.other import X\n"), + "topw_g/a/__init__.py": "", + "topw_g/a/other.py": "from topw_g import Z\nX = 1\n", + }, + "import topw_g", + "from topw_g.a.other import X", + sync_name="topw_sync", + t2_waits_for="topw_g", + ) + self.assertEqual(errors, []) + self.assertEqual(sys.modules["topw_g"].X, 1) + + def test_import_module_of_initializing_submodule_waits_for_it_only(self): + # The converse of waiting for an initializing ancestor before + # loading a submodule: pkg/__init__.py has *already* + # imported pkg.leaf and then blocks on thread 2 (any non-import + # wait). Thread 2, started while pkg/leaf.py is still executing, + # asks for pkg.leaf via importlib. It must get it as soon as leaf.py + # finishes, exactly as the import statement would, and not be made + # to wait for pkg/__init__.py -- which is waiting for thread 2. + errors = self._run_two_first_imports( + { + "lfo_pkg/__init__.py": ( + "import lfo_pkg.leaf\n" + "import lfo_sync; lfo_sync.join_t2()\n"), + "lfo_pkg/leaf.py": "import lfo_sync; lfo_sync.hold()\nX = 1\n", + }, + "import lfo_pkg", + "import importlib; importlib.import_module('lfo_pkg.leaf')", + sync_name="lfo_sync", + t2_waits_for=None, + ) + self.assertEqual(errors, []) + + def test_import_module_in_cross_thread_cycle_returns_partial_module(self): + # ax/x.py sets X, then imports by.y; by/y.py does `from ax.x import + # X`. Thread 1 is inside x.py (holding ax.x's lock) when thread 2's + # `import by.y` reaches y.py and blocks on ax.x. Thread 1 then asks + # for by.y and is the one to detect the cycle. The import statement + # resolves this by handing thread 1 the partially + # initialized by.y (import.c -> _lock_unlock_module()); + # importlib.import_module() must do the same rather than raise + # _DeadlockError into x.py. + for i, form in enumerate(( + "import by{i}_cyc.y", + "import importlib; importlib.import_module('by{i}_cyc.y')")): + form = form.format(i=i) + with self.subTest(form=form): + errors = self._run_two_first_imports( + { + f"ax{i}_cyc/__init__.py": "", + f"ax{i}_cyc/x.py": ( + "X = 1\n" + "import cyc_sync; cyc_sync.hold()\n" + f"{form}\n"), + f"by{i}_cyc/__init__.py": "", + f"by{i}_cyc/y.py": ( + f"from ax{i}_cyc.x import X\nassert X == 1\n"), + }, + f"import ax{i}_cyc.x", + f"import by{i}_cyc.y", + sync_name="cyc_sync", + t2_waits_for=f"ax{i}_cyc.x", + ) + self.assertEqual(errors, []) + + def test_submodule_enters_cross_thread_cycle_after_parents_resolved(self): + # Thread 1 is inside m.py and has found pkg.leaf missing, but only + # asks for its lock once thread 2 is inside leaf.py, waiting for m. + # Thread 1 is the one to detect the cycle, and pkg.leaf is in + # sys.modules by now, so it must get the partial module, as if it had + # found it there in the first place. + resolve_parents = importlib._bootstrap._resolve_parents + + def stalling_resolve_parents(name, import_): + resolve_parents(name, import_) + if name == "stall_pkg.leaf": + sys.modules["stall_sync"].hold() + + with support.swap_attr(importlib._bootstrap, "_resolve_parents", + stalling_resolve_parents): + errors = self._run_two_first_imports( + { + "stall_pkg/__init__.py": "", + "stall_pkg/leaf.py": "import stall_m\nX = 1\n", + "stall_m.py": "import stall_pkg.leaf\n", + }, + "import stall_m", + "import stall_pkg.leaf", + sync_name="stall_sync", + t2_waits_for="stall_m", + ) + self.assertEqual(errors, []) + self.assertEqual(sys.modules["stall_pkg.leaf"].X, 1) + + def test_parent_removed_before_submodule_is_loaded(self): + # The parent package leaves sys.modules after it was imported but + # before the submodule is loaded, as when its import failed in + # another thread. The parent must be imported again rather than + # the submodule's import failing with KeyError. + self._setup_package_tree({ + "gone_pkg/__init__.py": "", + "gone_pkg/mod.py": "X = 1\n", + }) + resolve_parents = importlib._bootstrap._resolve_parents + removed = [] + + def removing_resolve_parents(name, import_): + resolve_parents(name, import_) + if name == "gone_pkg.mod": + removed.append(sys.modules.pop("gone_pkg")) + + with support.swap_attr(importlib._bootstrap, "_resolve_parents", + removing_resolve_parents): + import gone_pkg.mod + self.assertEqual(len(removed), 1) + self.assertIsNot(sys.modules["gone_pkg"], removed[0]) + self.assertEqual(sys.modules["gone_pkg"].mod.X, 1) + + def test_waiter_retries_after_failed_submodule_import(self): + # Thread 2 waits for thread 1's import of pkg.mod, whose first + # execution then fails. Thread 2 must load pkg.mod itself and not + # return the discarded module. + for i, stmt in enumerate(self.SUBMODULE_IMPORTS): + pkg = f"retry{i}_pkg" + stmt = stmt.format(pkg=pkg) + with self.subTest(stmt=stmt): + errors = self._run_two_first_imports( + { + f"{pkg}/__init__.py": "", + f"{pkg}/mod.py": ( + "import retry_sync; retry_sync.hold()\n" + "if retry_sync.executed.count(__name__) == 1:\n" + " raise RuntimeError('first attempt fails')\n" + "X = 1\n"), + }, + f"import {pkg}.mod", + stmt, + sync_name="retry_sync", + t2_waits_for=f"{pkg}.mod", + ) + self.assertEqual(errors, [ + (f"import {pkg}.mod", + "RuntimeError: first attempt fails"), + (f"{pkg}.mod", "executed 2 times"), + ]) + self.assertEqual(sys.modules[f"{pkg}.mod"].X, 1) + + def test_waiter_not_given_module_being_retried(self): + # Thread B waits for thread A's import of a module, which fails. + # A retries, so sys.modules may hold A's new, still executing + # module by the time B looks there again. B must wait for that + # attempt too rather than return a half initialized module. + self._setup_package_tree({ + "again_mod.py": "import again_sync; again_sync.body()\nX = 1\n", + }) + sync = types.ModuleType("again_sync") + sys.modules["again_sync"] = sync + self.addCleanup(sys.modules.pop, "again_sync", None) + released = threading.Event() # B stopped waiting for the 1st attempt + retrying = threading.Event() # the 2nd attempt is in sys.modules + errors = [] + results = [] + + def a(): + try: + try: + import again_mod + except RuntimeError: + pass + released.wait(support.SHORT_TIMEOUT) + import again_mod + except Exception as e: + errors.append(f"A: {type(e).__name__}: {e}") + + def b(): + try: + module = importlib.import_module("again_mod") + results.append(hasattr(module, "X")) + except Exception as e: + errors.append(f"B: {type(e).__name__}: {e}") + + ta = threading.Thread(target=a, daemon=True) + tb = threading.Thread(target=b, daemon=True) + + def body(): + if tb.ident is None: + tb.start() + self._wait_until_blocked_on(tb, "again_mod") + raise RuntimeError("first attempt fails") + retrying.set() + if threading.current_thread() is not tb: + # Finish only once B is waiting for this attempt. + self._wait_until_blocked_on(tb, "again_mod") + sync.body = body + + # Hold B back, once it has stopped waiting for the first attempt, + # until the second attempt is under way. + release = importlib._bootstrap._ModuleLock.release + + def stalling_release(lock): + release(lock) + if (lock.name == "again_mod" and not released.is_set() + and threading.current_thread() is tb): + released.set() + retrying.wait(support.SHORT_TIMEOUT) + + with support.swap_attr(importlib._bootstrap._ModuleLock, "release", + stalling_release): + ta.start() + self._join_import_threads([ta, tb]) + self.assertEqual(results, [True]) + self.assertEqual(errors, []) + def setUpModule(): thread_info = threading_helper.threading_setup() diff --git a/Lib/test/test_importlib/test_util.py b/Lib/test/test_importlib/test_util.py index 8c14b96271a..8a911c1b751 100644 --- a/Lib/test/test_importlib/test_util.py +++ b/Lib/test/test_importlib/test_util.py @@ -124,12 +124,6 @@ def test___file__(self): module = self.util.module_from_spec(spec) self.assertEqual(module.__file__, spec.origin) - def test___cached__(self): - spec = self.machinery.ModuleSpec('test', object()) - spec.cached = 'some/path' - spec.has_location = True - module = self.util.module_from_spec(spec) - self.assertEqual(module.__cached__, spec.cached) (Frozen_ModuleFromSpecTests, Source_ModuleFromSpecTests @@ -334,6 +328,17 @@ class PEP3147Tests: tag = sys.implementation.cache_tag + def setUp(self): + # Most of these tests assume the default (unset) pycache prefix, so + # clear it for the duration of the test (e.g. when the test suite is + # run with PYTHONPYCACHEPREFIX set). Tests that need a specific prefix + # set their own via util.temporary_pycache_prefix(). + self._orig_pycache_prefix = sys.pycache_prefix + sys.pycache_prefix = None + + def tearDown(self): + sys.pycache_prefix = self._orig_pycache_prefix + @unittest.skipIf(sys.implementation.cache_tag is None, 'requires sys.implementation.cache_tag not be None') def test_cache_from_source(self): @@ -351,6 +356,8 @@ def test_cache_from_source_no_cache_tag(self): with self.assertRaises(NotImplementedError): self.util.cache_from_source('whatever.py') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_cache_from_source_no_dot(self): # Directory with a dot, filename without dot. path = os.path.join('foo.bar', 'file') @@ -359,47 +366,16 @@ def test_cache_from_source_no_dot(self): self.assertEqual(self.util.cache_from_source(path, optimization=''), expect) - def test_cache_from_source_debug_override(self): - # Given the path to a .py file, return the path to its PEP 3147/PEP 488 - # defined .pyc file (i.e. under __pycache__). - path = os.path.join('foo', 'bar', 'baz', 'qux.py') - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - self.assertEqual(self.util.cache_from_source(path, False), - self.util.cache_from_source(path, optimization=1)) - self.assertEqual(self.util.cache_from_source(path, True), - self.util.cache_from_source(path, optimization='')) - with warnings.catch_warnings(): - warnings.simplefilter('error') - with self.assertRaises(DeprecationWarning): - self.util.cache_from_source(path, False) - with self.assertRaises(DeprecationWarning): - self.util.cache_from_source(path, True) - + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_cache_from_source_cwd(self): path = 'foo.py' expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag)) self.assertEqual(self.util.cache_from_source(path, optimization=''), expect) - def test_cache_from_source_override(self): - # When debug_override is not None, it can be any true-ish or false-ish - # value. - path = os.path.join('foo', 'bar', 'baz.py') - # However if the bool-ishness can't be determined, the exception - # propagates. - class Bearish: - def __bool__(self): raise RuntimeError - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - self.assertEqual(self.util.cache_from_source(path, []), - self.util.cache_from_source(path, optimization=1)) - self.assertEqual(self.util.cache_from_source(path, [17]), - self.util.cache_from_source(path, optimization='')) - with self.assertRaises(RuntimeError): - self.util.cache_from_source('/foo/bar/baz.py', Bearish()) - - + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_cache_from_source_optimization_empty_string(self): # Setting 'optimization' to '' leads to no optimization tag (PEP 488). path = 'foo.py' @@ -407,6 +383,8 @@ def test_cache_from_source_optimization_empty_string(self): self.assertEqual(self.util.cache_from_source(path, optimization=''), expect) + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_cache_from_source_optimization_None(self): # Setting 'optimization' to None uses the interpreter's optimization. # (PEP 488) @@ -423,6 +401,8 @@ def test_cache_from_source_optimization_None(self): self.assertEqual(self.util.cache_from_source(path, optimization=None), expect) + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_cache_from_source_optimization_set(self): # The 'optimization' parameter accepts anything that has a string repr # that passes str.alnum(). @@ -440,6 +420,8 @@ def test_cache_from_source_optimization_set(self): with self.assertRaises(ValueError): self.util.cache_from_source(path, optimization='path/is/bad') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_cache_from_source_debug_override_optimization_both_set(self): # Can only set one of the optimization-related parameters. with warnings.catch_warnings(): @@ -449,6 +431,8 @@ def test_cache_from_source_debug_override_optimization_both_set(self): @unittest.skipUnless(os.sep == '\\' and os.altsep == '/', 'test meaningful only where os.altsep is defined') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_sep_altsep_and_sep_cache_from_source(self): # Windows path and PEP 3147 where sep is right of altsep. self.assertEqual( @@ -481,44 +465,60 @@ def test_source_from_cache_no_cache_tag(self): with self.assertRaises(NotImplementedError): self.util.source_from_cache(path) + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_bad_path(self): # When the path to a pyc file is not in PEP 3147 format, a ValueError # is raised. self.assertRaises( ValueError, self.util.source_from_cache, '/foo/bar/bazqux.pyc') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_no_slash(self): # No slashes at all in path -> ValueError self.assertRaises( ValueError, self.util.source_from_cache, 'foo.cpython-32.pyc') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_too_few_dots(self): # Too few dots in final path component -> ValueError self.assertRaises( ValueError, self.util.source_from_cache, '__pycache__/foo.pyc') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_too_many_dots(self): with self.assertRaises(ValueError): self.util.source_from_cache( '__pycache__/foo.cpython-32.opt-1.foo.pyc') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_not_opt(self): # Non-`opt-` path component -> ValueError self.assertRaises( ValueError, self.util.source_from_cache, '__pycache__/foo.cpython-32.foo.pyc') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_no__pycache__(self): # Another problem with the path -> ValueError self.assertRaises( ValueError, self.util.source_from_cache, '/foo/bar/foo.cpython-32.foo.pyc') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_optimized_bytecode(self): # Optimized bytecode is not an issue. path = os.path.join('__pycache__', 'foo.{}.opt-1.pyc'.format(self.tag)) self.assertEqual(self.util.source_from_cache(path), 'foo.py') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag to not be None') def test_source_from_cache_missing_optimization(self): # An empty optimization level is a no-no. path = os.path.join('__pycache__', 'foo.{}.opt-.pyc'.format(self.tag)) @@ -633,7 +633,7 @@ class MagicNumberTests(unittest.TestCase): 'only applies to candidate or final python release levels' ) def test_magic_number(self): - # Each python minor release should generally have a MAGIC_NUMBER + # Each Python feature release should generally have a MAGIC_NUMBER # that does not change once the release reaches candidate status. # Once a release reaches candidate status, the value of the constant @@ -643,11 +643,11 @@ def test_magic_number(self): # In exceptional cases, it may be required to change the MAGIC_NUMBER # for a maintenance release. In this case the change should be - # discussed in python-dev. If a change is required, community + # discussed in on Discourse. If a change is required, community # stakeholders such as OS package maintainers must be notified # in advance. Such exceptional releases will then require an # adjustment to this test case. - EXPECTED_MAGIC_NUMBER = 3627 + EXPECTED_MAGIC_NUMBER = 3666 actual = int.from_bytes(importlib.util.MAGIC_NUMBER[:2], 'little') msg = ( @@ -659,7 +659,7 @@ def test_magic_number(self): "magic number in this test to the current MAGIC_NUMBER to " "continue with the release.\n\n" "Changing the MAGIC_NUMBER for a maintenance release " - "requires discussion in python-dev and notification of " + "requires discussion on Discourse and notification of " "community stakeholders." ) self.assertEqual(EXPECTED_MAGIC_NUMBER, actual, msg) diff --git a/Lib/test/test_importlib/test_zip.py b/Lib/test/test_importlib/test_zip.py deleted file mode 100644 index 276f6288c91..00000000000 --- a/Lib/test/test_importlib/test_zip.py +++ /dev/null @@ -1,62 +0,0 @@ -import sys -import unittest - -from . import fixtures -from importlib.metadata import ( - PackageNotFoundError, - distribution, - distributions, - entry_points, - files, - version, -) - - -class TestZip(fixtures.ZipFixtures, unittest.TestCase): - def setUp(self): - super().setUp() - self._fixture_on_path('example-21.12-py3-none-any.whl') - - def test_zip_version(self): - self.assertEqual(version('example'), '21.12') - - def test_zip_version_does_not_match(self): - with self.assertRaises(PackageNotFoundError): - version('definitely-not-installed') - - def test_zip_entry_points(self): - scripts = entry_points(group='console_scripts') - entry_point = scripts['example'] - self.assertEqual(entry_point.value, 'example:main') - entry_point = scripts['Example'] - self.assertEqual(entry_point.value, 'example:main') - - def test_missing_metadata(self): - self.assertIsNone(distribution('example').read_text('does not exist')) - - def test_case_insensitive(self): - self.assertEqual(version('Example'), '21.12') - - def test_files(self): - for file in files('example'): - path = str(file.dist.locate_file(file)) - assert '.whl/' in path, path - - def test_one_distribution(self): - dists = list(distributions(path=sys.path[:1])) - assert len(dists) == 1 - - -class TestEgg(TestZip): - def setUp(self): - super().setUp() - self._fixture_on_path('example-21.12-py3.6.egg') - - def test_files(self): - for file in files('example'): - path = str(file.dist.locate_file(file)) - assert '.egg/' in path, path - - def test_normalized_name(self): - dist = distribution('example') - assert dist._normalized_name == 'example' diff --git a/Lib/test/test_importlib/util.py b/Lib/test/test_importlib/util.py index 2eaefd68747..33f82e77396 100644 --- a/Lib/test/test_importlib/util.py +++ b/Lib/test/test_importlib/util.py @@ -294,6 +294,9 @@ def writes_bytecode_files(fxn): tests that require it to be set to False.""" if sys.dont_write_bytecode: return unittest.skip("relies on writing bytecode")(fxn) + if sys.implementation.cache_tag is None: + return unittest.skip("requires sys.implementation.cache_tag to not be None")(fxn) + @functools.wraps(fxn) def wrapper(*args, **kwargs): original = sys.dont_write_bytecode diff --git a/Lib/test/test_importlib/zipdata01/ziptestdata.zip b/Lib/test/test_importlib/zipdata01/ziptestdata.zip deleted file mode 100644 index 9a3bb0739f8..00000000000 Binary files a/Lib/test/test_importlib/zipdata01/ziptestdata.zip and /dev/null differ diff --git a/Lib/test/test_importlib/zipdata02/ziptestdata.zip b/Lib/test/test_importlib/zipdata02/ziptestdata.zip deleted file mode 100644 index d63ff512d28..00000000000 Binary files a/Lib/test/test_importlib/zipdata02/ziptestdata.zip and /dev/null differ diff --git a/Lib/test/test_inspect/inspect_fodder3.py b/Lib/test/test_inspect/inspect_fodder3.py new file mode 100644 index 00000000000..ea2481edf93 --- /dev/null +++ b/Lib/test/test_inspect/inspect_fodder3.py @@ -0,0 +1,39 @@ +from functools import cached_property + +# docstring in parent, inherited in child +class ParentInheritDoc: + @cached_property + def foo(self): + """docstring for foo defined in parent""" + +class ChildInheritDoc(ParentInheritDoc): + pass + +class ChildInheritDefineDoc(ParentInheritDoc): + @cached_property + def foo(self): + pass + +# Redefine foo as something other than cached_property +class ChildPropertyFoo(ParentInheritDoc): + @property + def foo(self): + """docstring for the property foo""" + +class ChildMethodFoo(ParentInheritDoc): + def foo(self): + """docstring for the method foo""" + +# docstring in child but not parent +class ParentNoDoc: + @cached_property + def foo(self): + pass + +class ChildNoDoc(ParentNoDoc): + pass + +class ChildDefineDoc(ParentNoDoc): + @cached_property + def foo(self): + """docstring for foo defined in child""" diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py index c7c9a2930ad..eceebdf32c1 100644 --- a/Lib/test/test_inspect/test_inspect.py +++ b/Lib/test/test_inspect/test_inspect.py @@ -40,13 +40,14 @@ from test.support import MISSING_C_DOCSTRINGS, ALWAYS_EQ from test.support import run_no_yield_async_fn, EqualToForwardRef from test.support.import_helper import DirsOnSysPath, ready_to_import -from test.support.os_helper import TESTFN, temp_cwd +from test.support.os_helper import TESTFN, TESTFN_UNDECODABLE, temp_cwd from test.support.script_helper import assert_python_ok, assert_python_failure, kill_python from test.support import has_subprocess_support from test import support from test.test_inspect import inspect_fodder as mod from test.test_inspect import inspect_fodder2 as mod2 +from test.test_inspect import inspect_fodder3 as mod3 from test.test_inspect import inspect_stringized_annotations from test.test_inspect import inspect_deferred_annotations @@ -173,6 +174,15 @@ def __get__(self, instance, owner): return self.func.__get__(instance, owner) +class TestImportTime(unittest.TestCase): + + @cpython_only + def test_lazy_import(self): + import_helper.ensure_lazy_imports( + "inspect", {"re", "tokenize"} + ) + + class TestPredicates(IsTestBase): def test_excluding_predicates(self): @@ -689,10 +699,56 @@ def test_getdoc_inherited(self): self.assertEqual(inspect.getdoc(mod.FesteringGob.contradiction), 'The automatic gainsaying.') + @unittest.skipIf(sys.flags.optimize >= 2, + "Docstrings are omitted with -O2 and above") + def test_getdoc_inherited_class_doc(self): + class A: + """Common base class""" + class B(A): + pass + + a = A() + self.assertEqual(inspect.getdoc(A), 'Common base class') + self.assertEqual(inspect.getdoc(A, inherit_class_doc=False), + 'Common base class') + self.assertEqual(inspect.getdoc(a), 'Common base class') + self.assertIsNone(inspect.getdoc(a, fallback_to_class_doc=False)) + a.__doc__ = 'Instance' + self.assertEqual(inspect.getdoc(a, fallback_to_class_doc=False), + 'Instance') + + b = B() + self.assertEqual(inspect.getdoc(B), 'Common base class') + self.assertIsNone(inspect.getdoc(B, inherit_class_doc=False)) + self.assertIsNone(inspect.getdoc(b)) + self.assertIsNone(inspect.getdoc(b, fallback_to_class_doc=False)) + b.__doc__ = 'Instance' + self.assertEqual(inspect.getdoc(b, fallback_to_class_doc=False), 'Instance') + + def test_getdoc_inherited_cached_property(self): + doc = inspect.getdoc(mod3.ParentInheritDoc.foo) + self.assertEqual(doc, 'docstring for foo defined in parent') + self.assertEqual(inspect.getdoc(mod3.ChildInheritDoc.foo), doc) + self.assertEqual(inspect.getdoc(mod3.ChildInheritDefineDoc.foo), doc) + + def test_getdoc_redefine_cached_property_as_other(self): + self.assertEqual(inspect.getdoc(mod3.ChildPropertyFoo.foo), + 'docstring for the property foo') + self.assertEqual(inspect.getdoc(mod3.ChildMethodFoo.foo), + 'docstring for the method foo') + + def test_getdoc_define_cached_property(self): + self.assertEqual(inspect.getdoc(mod3.ChildDefineDoc.foo), + 'docstring for foo defined in child') + + def test_getdoc_nodoc_inherited(self): + self.assertIsNone(inspect.getdoc(mod3.ChildNoDoc.foo)) + @unittest.skipIf(MISSING_C_DOCSTRINGS, "test requires docstrings") def test_finddoc(self): finddoc = inspect._finddoc self.assertEqual(finddoc(int), int.__doc__) + self.assertIsNone(finddoc(int, search_in_class=False)) self.assertEqual(finddoc(int.to_bytes), int.to_bytes.__doc__) self.assertEqual(finddoc(int().to_bytes), int.to_bytes.__doc__) self.assertEqual(finddoc(int.from_bytes), int.from_bytes.__doc__) @@ -1300,9 +1356,10 @@ def assertFullArgSpecEquals(self, routine, args_e, varargs_e=None, varkw_e=None, defaults_e=None, posonlyargs_e=[], kwonlyargs_e=[], kwonlydefaults_e=None, - ann_e={}): + ann_e={}, + annotation_format=Format.VALUE): args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = \ - inspect.getfullargspec(routine) + inspect.getfullargspec(routine, annotation_format=annotation_format) self.assertEqual(args, args_e) self.assertEqual(varargs, varargs_e) self.assertEqual(varkw, varkw_e) @@ -1335,6 +1392,19 @@ def test_getfullargspec(self): kwonlyargs_e=['e', 'f'], kwonlydefaults_e={'e': 4, 'f': 5}) + def get_getfullargspec_with_undefined_names_in_annotations(self): + def my_func(a: undefined_name): + pass + + with self.assertRaises(NameError): + inspect.getfullargspec(my_func) + + self.assertFullArgSpecEquals(my_func, ['a'], ann_e={'a': 'undefined_name'}, + annotation_format=Format.STRING) + + arg_spec = inspect.getfullargspec(my_func, annotation_format=Format.FORWARDREF) + self.assertIsInstance(arg_spec.annotations['a'], ForwardRef) + def test_argspec_api_ignores_wrapped(self): # Issue 20684: low level introspection API must ignore __wrapped__ @functools.wraps(mod.spam) @@ -6081,7 +6151,8 @@ def _test_builtin_methods_have_signatures(self, cls, no_signature, unsupported_s self.assertRaises(ValueError, inspect.signature, getattr(cls, name)) def test_builtins_have_signatures(self): - no_signature = {'type', 'super', 'bytearray', 'bytes', 'dict', 'int', 'str'} + no_signature = {'type', 'super', 'bytearray', 'bytes', + 'dict', 'frozendict', 'int', 'str'} # These need PEP 457 groups needs_groups = {"range", "slice", "dir", "getattr", "next", "iter", "vars"} @@ -6113,6 +6184,7 @@ def test_types_module_has_signatures(self): 'AsyncGeneratorType': {'athrow'}, 'CoroutineType': {'throw'}, 'GeneratorType': {'throw'}, + 'FrameLocalsProxyType': {'setdefault', 'pop', 'get'}, } self._test_module_has_signatures(types, unsupported_signature=unsupported_signature, @@ -6157,6 +6229,21 @@ def test_collections_abc_module_has_signatures(self): import collections.abc self._test_module_has_signatures(collections.abc) + def test_datetime_module_has_signatures(self): + # Only test if the C implementation is available. + import_helper.import_module('_datetime') + import datetime + no_signature = {'tzinfo'} + unsupported_signature = {'timezone'} + methods_unsupported_signature = { + 'date': {'replace'}, + 'time': {'replace'}, + 'datetime': {'replace', 'combine'}, + } + self._test_module_has_signatures(datetime, + no_signature, unsupported_signature, + methods_unsupported_signature=methods_unsupported_signature) + def test_errno_module_has_signatures(self): import errno self._test_module_has_signatures(errno) @@ -6169,8 +6256,7 @@ def test_faulthandler_module_has_signatures(self): self._test_module_has_signatures(faulthandler, unsupported_signature=unsupported_signature) def test_functools_module_has_signatures(self): - unsupported_signature = {"reduce"} - self._test_module_has_signatures(functools, unsupported_signature=unsupported_signature) + self._test_module_has_signatures(functools) def test_gc_module_has_signatures(self): import gc @@ -6214,7 +6300,10 @@ def test_pwd_module_has_signatures(self): def test_re_module_has_signatures(self): import re - methods_no_signature = {'Match': {'group'}} + methods_no_signature = { + 'Match': {'group'}, + 'Pattern': {'match'}, # It is now an alias for prefixmatch + } self._test_module_has_signatures(re, methods_no_signature=methods_no_signature, good_exceptions={'error', 'PatternError'}) @@ -6227,6 +6316,10 @@ def test_stat_module_has_signatures(self): import stat self._test_module_has_signatures(stat) + def test_struct_module_has_signatures(self): + import struct + self._test_module_has_signatures(struct) + def test_string_module_has_signatures(self): import string self._test_module_has_signatures(string) @@ -6284,7 +6377,7 @@ def test_typing_module_has_signatures(self): methods_unsupported_signature=methods_unsupported_signature) def test_warnings_module_has_signatures(self): - unsupported_signature = {'warn', 'warn_explicit'} + unsupported_signature = {'warn_explicit'} self._test_module_has_signatures(warnings, unsupported_signature=unsupported_signature) def test_weakref_module_has_signatures(self): @@ -6415,8 +6508,19 @@ def test_wrapped_descriptor(self): self.assertIs(inspect.unwrap(staticmethod(classmethod)), classmethod) self.assertIs(inspect.unwrap(classmethod(staticmethod)), staticmethod) +def _clean_object_ids(text): + # Helper to handle "" details in CLI output checks + import re + detect = r"object at 0x([0-9A-Fa-f]+)>" + replace = "object at 0x...>" + return re.sub(detect, replace, text) + +class TestModuleCLI(unittest.TestCase): + + BUILTIN_ERROR = "No source code available for builtin module" + NO_SOURCE_ERROR = "No source code available for defining module" + NO_SOURCE_TARGET_ERROR = "Failed to retrieve source code for given target" -class TestMain(unittest.TestCase): @staticmethod def _expected_cached(module): # assert_python_ok() runs the subprocess in isolated mode (-I), which @@ -6457,27 +6561,247 @@ def test_qualname_source(self): inspect.getsource(ThreadPoolExecutor).splitlines()) self.assertEqual(err, b'') - def test_builtins(self): + def test_error_builtins(self): _, out, err = assert_python_failure('-m', 'inspect', 'sys') lines = err.decode().splitlines() - self.assertEqual(lines, ["Can't get info for builtin modules."]) + self.assertEqual(lines, [self.BUILTIN_ERROR]) + + @unittest.skipIf(importlib.util.find_spec("_testcapi") is None, "TODO: RUSTPYTHON; _testcapi extension fixture is unavailable") + def test_error_extension(self): + module_name = "_testcapi" + if module_name in sys.builtin_module_names: + # WASI test environment has even _testcapi as a builtin module + expected_error = self.BUILTIN_ERROR + else: + expected_error = self.NO_SOURCE_ERROR + _, out, err = assert_python_failure('-m', 'inspect', + module_name) + lines = err.decode().splitlines() + self.assertEqual(lines, [expected_error]) - def test_details(self): - module = importlib.import_module('unittest') + def test_error_data(self): + _, out, err = assert_python_failure('-m', 'inspect', + 'importlib.machinery:SOURCE_SUFFIXES') + lines = err.decode().splitlines() + self.assertEqual(lines, [self.NO_SOURCE_TARGET_ERROR]) + + @unittest.skipUnless(TESTFN_UNDECODABLE, + 'requires undecodable file names') + def test_details_undecodable_path(self): + # gh-69370: the path of the module is not encodable in the encoding + # of stdout. + with temp_cwd() as test_dir: + subdir = os.path.join(os.fsencode(test_dir), TESTFN_UNDECODABLE) + try: + os.mkdir(subdir) + except OSError: + self.skipTest('undecodable paths are not supported') + with open(os.path.join(subdir, b'undecodable_mod.py'), 'w') as f: + f.write('"""Module docstring."""\n') + rc, out, err = assert_python_ok('-X', 'utf8=0', '-m', 'inspect', + '--details', 'undecodable_mod', + PYTHONPATH=os.fsdecode(subdir)) + self.assertIn(b'Target: undecodable_mod', out) + self.assertEqual(err, b'') + + def test_details_option_with_package(self): + module_name = 'unittest' + module = importlib.import_module(module_name) + args = support.optim_args_from_interpreter_flags() + rc, out, err = assert_python_ok(*args, '-m', 'inspect', + module_name, '--details') + cached = self._expected_cached(module) + # Full rendering check on the expected output + expected_lines = [ + f"Target: {module.__name__}", # No aliasing + f"Origin: {module.__spec__.origin}", + f"Source: {module.__file__}", + f"Cached: {cached}", # None is still displayed + f"Loader: {_clean_object_ids(repr(module.__spec__.loader))}", + f"Submodule search paths: {module.__path__}", + "", + ] + output_lines = _clean_object_ids(out.decode()).splitlines() + self.assertEqual(output_lines, expected_lines) + self.assertEqual(err, b'') + + def test_details_option_with_builtin_module(self): + # Also an end-to-end test of non-package lookups + module_name = 'sys' + module = importlib.import_module(module_name) + args = support.optim_args_from_interpreter_flags() + rc, out, err = assert_python_ok(*args, '-m', 'inspect', + module_name, '--details') + # Full rendering check on the expected output + # No error is reported when just fetching the module details + expected_lines = [ + f"Target: {module.__name__}", # No aliasing + f"Origin: {module.__spec__.origin}", + "Source: None", + "Cached: None", + f"Loader: {_clean_object_ids(repr(module.__spec__.loader))}", + "", + ] + output_lines = _clean_object_ids(out.decode()).splitlines() + self.assertEqual(output_lines, expected_lines) + self.assertEqual(err, b'') + + def test_details_option_with_data_target(self): + # Also an end-to-end test of non-module lookups without aliasing + module_name = 'importlib.machinery' + cli_target = f"{module_name}:SOURCE_SUFFIXES" + module = importlib.import_module(module_name) args = support.optim_args_from_interpreter_flags() rc, out, err = assert_python_ok(*args, '-m', 'inspect', - 'unittest', '--details') - output = out.decode() + cli_target, '--details') cached = self._expected_cached(module) - # Just a quick sanity check on the output - self.assertIn(module.__spec__.name, output) - self.assertIn(module.__name__, output) - self.assertIn(module.__spec__.origin, output) - self.assertIn(module.__file__, output) - self.assertIn(cached, output) + # Full rendering check on the expected output + # The error is only informational when reading source details + expected_lines = [ + f"Target: {cli_target}", # No aliasing + f"Origin: {module.__spec__.origin}", + f"Source: {module.__file__}", + f"Cached: {cached}", # None is still displayed + self.NO_SOURCE_TARGET_ERROR, + "", + ] + output_lines = out.decode().splitlines() + self.assertEqual(output_lines, expected_lines) self.assertEqual(err, b'') + @unittest.skipIf(not os.path.exists(os.path.__file__), "Needs frozen source file") + def test_details_option_with_aliased_target(self): + # Also an end-to-end test of successful non-module lookups + module = importlib.import_module("os.path") + target = module.join + cli_target = "os:path.join" # Defining module is os.path, not os + defining_target = f"{target.__module__}:{target.__qualname__}" + + args = support.optim_args_from_interpreter_flags() + rc, out, err = assert_python_ok(*args, '-m', 'inspect', + cli_target, '--details') + cached = self._expected_cached(module) + # Full rendering check on the expected output + expected_lines = [ + f'Target: {defining_target} (looked up as "{cli_target}")', + f"Origin: {module.__spec__.origin}", + f"Source: {module.__file__}", + f"Cached: {cached}", # None is still displayed + f"Line: {inspect.findsource(target)[1]}", + "", + ] + output_lines = out.decode().splitlines() + self.assertEqual(output_lines, expected_lines) + self.assertEqual(err, b'') + + def _check_details(self, module, details, other_expected_keys=(), *, alias=None, error=None): + expected_keys = {"target", "origin", "source", "cached"} + if other_expected_keys: + expected_keys |= other_expected_keys + if alias is not None: + expected_keys.add("alias") + if error is not None: + expected_keys.add("error") + self.assertEqual(set(details.keys()), expected_keys) + self.assertEqual(module.__spec__.origin, details["origin"]) + try: + expected_source = inspect.getsourcefile(module) + except Exception: + expected_source = None + if expected_source and expected_source.startswith("'. # The directory of argv[0] must match the directory of the Python # executable for the Popen() call to python to succeed as the directory - # path may be used by Py_GetPath() to build the default module search - # path. + # path may be used by PyConfig_Get("module_search_paths") to build the + # default module search path. stdin_fname = os.path.join(os.path.dirname(sys.executable), "") cmd_line = [stdin_fname, '-E', '-i'] cmd_line.extend(args) @@ -6568,7 +6894,5 @@ def f(): self.assertIn(expected, output) - - if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_interpreters/__init__.py b/Lib/test/test_interpreters/__init__.py new file mode 100644 index 00000000000..e3d189c4efc --- /dev/null +++ b/Lib/test/test_interpreters/__init__.py @@ -0,0 +1,9 @@ +import os +from test.support import load_package_tests, Py_GIL_DISABLED +import unittest + +if Py_GIL_DISABLED: + raise unittest.SkipTest("GIL disabled") + +def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_interpreters/__main__.py b/Lib/test/test_interpreters/__main__.py new file mode 100644 index 00000000000..40a23a297ec --- /dev/null +++ b/Lib/test/test_interpreters/__main__.py @@ -0,0 +1,4 @@ +from . import load_tests +import unittest + +unittest.main() diff --git a/Lib/test/test_interpreters/test_api.py b/Lib/test/test_interpreters/test_api.py new file mode 100644 index 00000000000..aac3cdd7176 --- /dev/null +++ b/Lib/test/test_interpreters/test_api.py @@ -0,0 +1,2504 @@ +import contextlib +import os +import pickle +import signal +import sys +from textwrap import dedent +import threading +import types +import unittest + +from test import support +from test.support import os_helper +from test.support import script_helper +from test.support import import_helper +from test.support.script_helper import assert_python_ok, spawn_python +# Raise SkipTest if subinterpreters not supported. +_interpreters = import_helper.import_module('_interpreters') +from concurrent import interpreters +from test.support import Py_GIL_DISABLED +from test.support import force_not_colorized +import test._crossinterp_definitions as defs +from concurrent.interpreters import ( + InterpreterError, InterpreterNotFoundError, ExecutionFailed, +) +from .utils import ( + _captured_script, _run_output, _running, TestBase, + requires_test_modules, _testinternalcapi, +) + + +WHENCE_STR_UNKNOWN = 'unknown' +WHENCE_STR_RUNTIME = 'runtime init' +WHENCE_STR_LEGACY_CAPI = 'legacy C-API' +WHENCE_STR_CAPI = 'C-API' +WHENCE_STR_XI = 'cross-interpreter C-API' +WHENCE_STR_STDLIB = '_interpreters module' + + +def is_pickleable(obj): + try: + pickle.dumps(obj) + except Exception: + return False + return True + + +@contextlib.contextmanager +def defined_in___main__(name, script, *, remove=False): + import __main__ as mainmod + mainns = vars(mainmod) + assert name not in mainns + exec(script, mainns, mainns) + if remove: + yield mainns.pop(name) + else: + try: + yield mainns[name] + finally: + mainns.pop(name, None) + + +def build_excinfo(exctype, msg=None, formatted=None, errdisplay=None): + if isinstance(exctype, type): + assert issubclass(exctype, BaseException), exctype + exctype = types.SimpleNamespace( + __name__=exctype.__name__, + __qualname__=exctype.__qualname__, + __module__=exctype.__module__, + ) + elif isinstance(exctype, str): + module, _, name = exctype.rpartition(exctype) + if not module and name in __builtins__: + module = 'builtins' + exctype = types.SimpleNamespace( + __name__=name, + __qualname__=exctype, + __module__=module or None, + ) + else: + assert isinstance(exctype, types.SimpleNamespace) + assert msg is None or isinstance(msg, str), msg + assert formatted is None or isinstance(formatted, str), formatted + assert errdisplay is None or isinstance(errdisplay, str), errdisplay + return types.SimpleNamespace( + type=exctype, + msg=msg, + formatted=formatted, + errdisplay=errdisplay, + ) + + +class ModuleTests(TestBase): + + def test_queue_aliases(self): + first = [ + interpreters.create_queue, + interpreters.Queue, + interpreters.QueueEmpty, + interpreters.QueueFull, + ] + second = [ + interpreters.create_queue, + interpreters.Queue, + interpreters.QueueEmpty, + interpreters.QueueFull, + ] + self.assertEqual(second, first) + + +class CreateTests(TestBase): + + def test_in_main(self): + interp = interpreters.create() + self.assertIsInstance(interp, interpreters.Interpreter) + self.assertIn(interp, interpreters.list_all()) + + # GH-126221: Passing an invalid Unicode character used to cause a SystemError + self.assertRaises(UnicodeEncodeError, _interpreters.create, '\udc80') + + def test_in_thread(self): + lock = threading.Lock() + interp = None + def f(): + nonlocal interp + interp = interpreters.create() + lock.acquire() + lock.release() + t = threading.Thread(target=f) + with lock: + t.start() + t.join() + self.assertIn(interp, interpreters.list_all()) + + def test_in_subinterpreter(self): + main, = interpreters.list_all() + interp = interpreters.create() + out = _run_output(interp, dedent(""" + from concurrent import interpreters + interp = interpreters.create() + print(interp.id) + """)) + interp2 = interpreters.Interpreter(int(out)) + self.assertEqual(interpreters.list_all(), [main, interp, interp2]) + + def test_after_destroy_all(self): + before = set(interpreters.list_all()) + # Create 3 subinterpreters. + interp_lst = [] + for _ in range(3): + interps = interpreters.create() + interp_lst.append(interps) + # Now destroy them. + for interp in interp_lst: + interp.close() + # Finally, create another. + interp = interpreters.create() + self.assertEqual(set(interpreters.list_all()), before | {interp}) + + def test_after_destroy_some(self): + before = set(interpreters.list_all()) + # Create 3 subinterpreters. + interp1 = interpreters.create() + interp2 = interpreters.create() + interp3 = interpreters.create() + # Now destroy 2 of them. + interp1.close() + interp2.close() + # Finally, create another. + interp = interpreters.create() + self.assertEqual(set(interpreters.list_all()), before | {interp3, interp}) + + +class GetMainTests(TestBase): + + def test_id(self): + main = interpreters.get_main() + self.assertEqual(main.id, 0) + + def test_current(self): + main = interpreters.get_main() + current = interpreters.get_current() + self.assertIs(main, current) + + def test_idempotent(self): + main1 = interpreters.get_main() + main2 = interpreters.get_main() + self.assertIs(main1, main2) + + +class GetCurrentTests(TestBase): + + def test_main(self): + main = interpreters.get_main() + current = interpreters.get_current() + self.assertEqual(current, main) + + def test_subinterpreter(self): + main = interpreters.get_main() + interp = interpreters.create() + out = _run_output(interp, dedent(""" + from concurrent import interpreters + cur = interpreters.get_current() + print(cur.id) + """)) + current = interpreters.Interpreter(int(out)) + self.assertEqual(current, interp) + self.assertNotEqual(current, main) + + def test_idempotent(self): + with self.subTest('main'): + cur1 = interpreters.get_current() + cur2 = interpreters.get_current() + self.assertIs(cur1, cur2) + + with self.subTest('subinterpreter'): + interp = interpreters.create() + out = _run_output(interp, dedent(""" + from concurrent import interpreters + cur = interpreters.get_current() + print(id(cur)) + cur = interpreters.get_current() + print(id(cur)) + """)) + objid1, objid2 = (int(v) for v in out.splitlines()) + self.assertEqual(objid1, objid2) + + with self.subTest('per-interpreter'): + interp = interpreters.create() + out = _run_output(interp, dedent(""" + from concurrent import interpreters + cur = interpreters.get_current() + print(id(cur)) + """)) + id1 = int(out) + id2 = id(interp) + self.assertNotEqual(id1, id2) + + @requires_test_modules + def test_created_with_capi(self): + expected = _testinternalcapi.next_interpreter_id() + text = self.run_temp_from_capi(f""" + import {interpreters.__name__} as interpreters + interp = interpreters.get_current() + print((interp.id, interp.whence)) + """) + interpid, whence = eval(text) + self.assertEqual(interpid, expected) + self.assertEqual(whence, WHENCE_STR_CAPI) + + +class ListAllTests(TestBase): + + def test_initial(self): + interps = interpreters.list_all() + self.assertEqual(1, len(interps)) + + def test_after_creating(self): + main = interpreters.get_current() + first = interpreters.create() + second = interpreters.create() + + ids = [] + for interp in interpreters.list_all(): + ids.append(interp.id) + + self.assertEqual(ids, [main.id, first.id, second.id]) + + def test_after_destroying(self): + main = interpreters.get_current() + first = interpreters.create() + second = interpreters.create() + first.close() + + ids = [] + for interp in interpreters.list_all(): + ids.append(interp.id) + + self.assertEqual(ids, [main.id, second.id]) + + def test_idempotent(self): + main = interpreters.get_current() + first = interpreters.create() + second = interpreters.create() + expected = [main, first, second] + + actual = interpreters.list_all() + + self.assertEqual(actual, expected) + for interp1, interp2 in zip(actual, expected): + self.assertIs(interp1, interp2) + + def test_destroyed_by_gc(self): + # gh-155997: the interpreter is destroyed while list_all() runs. + interp = interpreters.create() + interpid = interp.id + cycle = [] + cycle.append(cycle) + cycle.append(interp) + # The cycle holds the only reference, so only the collector frees it. + with support.disable_gc(): + del interp, cycle + + with support.gc_threshold(1): + ids = [i.id for i in interpreters.list_all()] + self.assertNotIn(interpid, ids) + + def test_created_with_capi(self): + mainid, *_ = _interpreters.get_main() + interpid1 = _interpreters.create() + interpid2 = _interpreters.create() + interpid3 = _interpreters.create() + interpid4 = interpid3 + 1 + interpid5 = interpid4 + 1 + expected = [ + (mainid, WHENCE_STR_RUNTIME), + (interpid1, WHENCE_STR_STDLIB), + (interpid2, WHENCE_STR_STDLIB), + (interpid3, WHENCE_STR_STDLIB), + (interpid4, WHENCE_STR_CAPI), + (interpid5, WHENCE_STR_STDLIB), + ] + expected2 = expected[:-2] + text = self.run_temp_from_capi(f""" + import {interpreters.__name__} as interpreters + interp = interpreters.create() + print( + [(i.id, i.whence) for i in interpreters.list_all()]) + """) + res = eval(text) + res2 = [(i.id, i.whence) for i in interpreters.list_all()] + self.assertEqual(res, expected) + self.assertEqual(res2, expected2) + + +class InterpreterObjectTests(TestBase): + + def test_init_int(self): + interpid = interpreters.get_current().id + interp = interpreters.Interpreter(interpid) + self.assertEqual(interp.id, interpid) + + def test_init_interpreter_id(self): + interpid = interpreters.get_current()._id + interp = interpreters.Interpreter(interpid) + self.assertEqual(interp._id, interpid) + + def test_init_unsupported(self): + actualid = interpreters.get_current().id + for interpid in [ + str(actualid), + float(actualid), + object(), + None, + '', + ]: + with self.subTest(repr(interpid)): + with self.assertRaises(TypeError): + interpreters.Interpreter(interpid) + + def test_idempotent(self): + main = interpreters.get_main() + interp = interpreters.Interpreter(main.id) + self.assertIs(interp, main) + + def test_init_does_not_exist(self): + with self.assertRaises(InterpreterNotFoundError): + interpreters.Interpreter(1_000_000) + + def test_init_bad_id(self): + with self.assertRaises(ValueError): + interpreters.Interpreter(-1) + + def test_id_type(self): + main = interpreters.get_main() + current = interpreters.get_current() + interp = interpreters.create() + self.assertIsInstance(main.id, int) + self.assertIsInstance(current.id, int) + self.assertIsInstance(interp.id, int) + + def test_id_readonly(self): + interp = interpreters.create() + with self.assertRaises(AttributeError): + interp.id = 1_000_000 + + def test_whence(self): + main = interpreters.get_main() + interp = interpreters.create() + + with self.subTest('main'): + self.assertEqual(main.whence, WHENCE_STR_RUNTIME) + + with self.subTest('from _interpreters'): + self.assertEqual(interp.whence, WHENCE_STR_STDLIB) + + with self.subTest('from C-API'): + text = self.run_temp_from_capi(f""" + import {interpreters.__name__} as interpreters + interp = interpreters.get_current() + print(repr(interp.whence)) + """) + whence = eval(text) + self.assertEqual(whence, WHENCE_STR_CAPI) + + with self.subTest('readonly'): + for value in [ + None, + WHENCE_STR_UNKNOWN, + WHENCE_STR_RUNTIME, + WHENCE_STR_STDLIB, + WHENCE_STR_CAPI, + ]: + with self.assertRaises(AttributeError): + interp.whence = value + with self.assertRaises(AttributeError): + main.whence = value + + def test_hashable(self): + interp = interpreters.create() + expected = hash(interp.id) + actual = hash(interp) + self.assertEqual(actual, expected) + + def test_equality(self): + interp1 = interpreters.create() + interp2 = interpreters.create() + self.assertEqual(interp1, interp1) + self.assertNotEqual(interp1, interp2) + + def test_pickle(self): + interp = interpreters.create() + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=protocol): + data = pickle.dumps(interp, protocol) + unpickled = pickle.loads(data) + self.assertEqual(unpickled, interp) + + @support.requires_subprocess() + @force_not_colorized + def test_cleanup_in_repl(self): + # GH-135729: Using a subinterpreter in the REPL would lead to an unraisable + # exception during finalization + repl = script_helper.spawn_python("-i") + script = b"""if True: + from concurrent import interpreters + interpreters.create() + exit()""" + stdout, stderr = repl.communicate(script) + self.assertIsNone(stderr) + self.assertIn(b"Interpreter.close()", stdout) + self.assertNotIn(b"Traceback", stdout) + + @support.requires_subprocess() + @unittest.skipIf(os.name == 'nt', "signals don't work well on windows") + def test_keyboard_interrupt_in_thread_running_interp(self): + import subprocess + source = f"""if True: + from concurrent import interpreters + from threading import Thread + + def test(): + import time + print('a', flush=True, end='') + time.sleep(10) + + interp = interpreters.create() + interp.call_in_thread(test) + """ + + with spawn_python("-c", source, stderr=subprocess.PIPE) as proc: + self.assertEqual(proc.stdout.read(1), b'a') + proc.send_signal(signal.SIGINT) + proc.stderr.flush() + error = proc.stderr.read() + self.assertIn(b"KeyboardInterrupt", error) + retcode = proc.wait() + # Sometimes we send the SIGINT after the subthread yields the GIL to + # the main thread, which results in the main thread getting the + # KeyboardInterrupt before finalization is reached. There's not + # any great way to protect against that, so we just allow a -2 + # return code as well. + self.assertIn(retcode, (0, -signal.SIGINT)) + + +class TestInterpreterIsRunning(TestBase): + + def test_main(self): + main = interpreters.get_main() + self.assertTrue(main.is_running()) + + # XXX Is this still true? + @unittest.skip('Fails on FreeBSD') + def test_subinterpreter(self): + interp = interpreters.create() + self.assertFalse(interp.is_running()) + + with _running(interp): + self.assertTrue(interp.is_running()) + self.assertFalse(interp.is_running()) + + def test_finished(self): + r, w = self.pipe() + interp = interpreters.create() + interp.exec(f"""if True: + import os + os.write({w}, b'x') + """) + self.assertFalse(interp.is_running()) + self.assertEqual(os.read(r, 1), b'x') + + def test_from_subinterpreter(self): + interp = interpreters.create() + out = _run_output(interp, dedent(f""" + import _interpreters + if _interpreters.is_running({interp.id}): + print(True) + else: + print(False) + """)) + self.assertEqual(out.strip(), 'True') + + def test_already_destroyed(self): + interp = interpreters.create() + interp.close() + with self.assertRaises(InterpreterNotFoundError): + interp.is_running() + + def test_with_only_background_threads(self): + r_interp, w_interp = self.pipe() + r_thread, w_thread = self.pipe() + + DONE = b'D' + FINISHED = b'F' + + interp = interpreters.create() + interp.exec(f"""if True: + import os + import threading + + def task(): + v = os.read({r_thread}, 1) + assert v == {DONE!r} + os.write({w_interp}, {FINISHED!r}) + t = threading.Thread(target=task) + t.start() + """) + self.assertFalse(interp.is_running()) + + os.write(w_thread, DONE) + interp.exec('t.join()') + self.assertEqual(os.read(r_interp, 1), FINISHED) + + def test_created_with_capi(self): + script = dedent(f""" + import {interpreters.__name__} as interpreters + interp = interpreters.get_current() + print(interp.is_running()) + """) + def parse_results(text): + self.assertNotEqual(text, "") + try: + return eval(text) + except Exception: + raise Exception(repr(text)) + + with self.subTest('running __main__ (from self)'): + with self.interpreter_from_capi() as interpid: + text = self.run_from_capi(interpid, script, main=True) + running = parse_results(text) + self.assertTrue(running) + + with self.subTest('running, but not __main__ (from self)'): + text = self.run_temp_from_capi(script) + running = parse_results(text) + self.assertFalse(running) + + with self.subTest('running __main__ (from other)'): + with self.interpreter_obj_from_capi() as (interp, interpid): + before = interp.is_running() + with self.running_from_capi(interpid, main=True): + during = interp.is_running() + after = interp.is_running() + self.assertFalse(before) + self.assertTrue(during) + self.assertFalse(after) + + with self.subTest('running, but not __main__ (from other)'): + with self.interpreter_obj_from_capi() as (interp, interpid): + before = interp.is_running() + with self.running_from_capi(interpid, main=False): + during = interp.is_running() + after = interp.is_running() + self.assertFalse(before) + self.assertFalse(during) + self.assertFalse(after) + + with self.subTest('not running (from other)'): + with self.interpreter_obj_from_capi() as (interp, _): + running = interp.is_running() + self.assertFalse(running) + + +class TestInterpreterClose(TestBase): + + def test_basic(self): + main = interpreters.get_main() + interp1 = interpreters.create() + interp2 = interpreters.create() + interp3 = interpreters.create() + self.assertEqual(set(interpreters.list_all()), + {main, interp1, interp2, interp3}) + interp2.close() + self.assertEqual(set(interpreters.list_all()), + {main, interp1, interp3}) + + def test_all(self): + before = set(interpreters.list_all()) + interps = set() + for _ in range(3): + interp = interpreters.create() + interps.add(interp) + self.assertEqual(set(interpreters.list_all()), before | interps) + for interp in interps: + interp.close() + self.assertEqual(set(interpreters.list_all()), before) + + def test_main(self): + main, = interpreters.list_all() + with self.assertRaises(InterpreterError): + main.close() + + def f(): + with self.assertRaises(InterpreterError): + main.close() + + t = threading.Thread(target=f) + t.start() + t.join() + + def test_already_destroyed(self): + interp = interpreters.create() + interp.close() + with self.assertRaises(InterpreterNotFoundError): + interp.close() + + def test_from_current(self): + main, = interpreters.list_all() + interp = interpreters.create() + out = _run_output(interp, dedent(f""" + from concurrent import interpreters + interp = interpreters.Interpreter({interp.id}) + try: + interp.close() + except interpreters.InterpreterError: + print('failed') + """)) + self.assertEqual(out.strip(), 'failed') + self.assertEqual(set(interpreters.list_all()), {main, interp}) + + def test_from_sibling(self): + main, = interpreters.list_all() + interp1 = interpreters.create() + interp2 = interpreters.create() + self.assertEqual(set(interpreters.list_all()), + {main, interp1, interp2}) + interp1.exec(dedent(f""" + from concurrent import interpreters + interp2 = interpreters.Interpreter({interp2.id}) + interp2.close() + interp3 = interpreters.create() + interp3.close() + """)) + self.assertEqual(set(interpreters.list_all()), {main, interp1}) + + def test_from_other_thread(self): + interp = interpreters.create() + def f(): + interp.close() + + t = threading.Thread(target=f) + t.start() + t.join() + + # XXX Is this still true? + @unittest.skip('Fails on FreeBSD') + def test_still_running(self): + main, = interpreters.list_all() + interp = interpreters.create() + with _running(interp): + with self.assertRaises(InterpreterError): + interp.close() + self.assertTrue(interp.is_running()) + + def test_subthreads_still_running(self): + r_interp, w_interp = self.pipe() + r_thread, w_thread = self.pipe() + + FINISHED = b'F' + + interp = interpreters.create() + interp.exec(f"""if True: + import os + import threading + import time + + done = False + + def notify_fini(): + global done + done = True + t.join() + threading._register_atexit(notify_fini) + + def task(): + while not done: + time.sleep(0.1) + os.write({w_interp}, {FINISHED!r}) + t = threading.Thread(target=task) + t.start() + """) + interp.close() + + self.assertEqual(os.read(r_interp, 1), FINISHED) + + def test_created_with_capi(self): + script = dedent(f""" + import {interpreters.__name__} as interpreters + interp = interpreters.get_current() + interp.close() + """) + + with self.subTest('running __main__ (from self)'): + with self.interpreter_from_capi() as interpid: + with self.assertRaisesRegex(ExecutionFailed, + 'InterpreterError.*unrecognized'): + self.run_from_capi(interpid, script, main=True) + + with self.subTest('running, but not __main__ (from self)'): + with self.assertRaisesRegex(ExecutionFailed, + 'InterpreterError.*unrecognized'): + self.run_temp_from_capi(script) + + with self.subTest('running __main__ (from other)'): + with self.interpreter_obj_from_capi() as (interp, interpid): + with self.running_from_capi(interpid, main=True): + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + interp.close() + # Make sure it wssn't closed. + self.assertTrue( + self.interp_exists(interpid)) + + # The rest would be skipped until we deal with running threads when + # interp.close() is called. However, the "whence" restrictions + # trigger first. + + with self.subTest('running, but not __main__ (from other)'): + with self.interpreter_obj_from_capi() as (interp, interpid): + with self.running_from_capi(interpid, main=False): + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + interp.close() + # Make sure it wssn't closed. + self.assertTrue( + self.interp_exists(interpid)) + + with self.subTest('not running (from other)'): + with self.interpreter_obj_from_capi() as (interp, interpid): + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + interp.close() + self.assertTrue( + self.interp_exists(interpid)) + + + def test_remaining_threads(self): + r_interp, w_interp = self.pipe() + + FINISHED = b'F' + + # It's unlikely, but technically speaking, it's possible + # that the thread could've finished before interp.close() is + # reached, so this test might not properly exercise the case. + # However, it's quite unlikely and probably not worth bothering about. + interp = interpreters.create() + interp.exec(f"""if True: + import os + import threading + import time + + def task(): + time.sleep(1) + os.write({w_interp}, {FINISHED!r}) + + threads = (threading.Thread(target=task) for _ in range(3)) + for t in threads: + t.start() + """) + interp.close() + + self.assertEqual(os.read(r_interp, 1), FINISHED) + + def test_remaining_daemon_threads(self): + # Daemon threads leak reference by nature, because they hang threads + # without allowing them to do cleanup (i.e., release refs). + # To prevent that from messing up the refleak hunter and whatnot, we + # run this in a subprocess. + code = '''if True: + import _interpreters + import types + interp = _interpreters.create( + types.SimpleNamespace( + use_main_obmalloc=False, + allow_fork=False, + allow_exec=False, + allow_threads=True, + allow_daemon_threads=True, + check_multi_interp_extensions=True, + gil='own', + ) + ) + _interpreters.exec(interp, f"""if True: + import threading + import time + + def task(): + time.sleep(3) + + threads = (threading.Thread(target=task, daemon=True) for _ in range(3)) + for t in threads: + t.start() + """) + _interpreters.destroy(interp) + ''' + assert_python_ok('-c', code) + + +class TestInterpreterPrepareMain(TestBase): + + def test_empty(self): + interp = interpreters.create() + with self.assertRaises(ValueError): + interp.prepare_main() + + def test_dict(self): + values = {'spam': 42, 'eggs': 'ham'} + interp = interpreters.create() + interp.prepare_main(values) + out = _run_output(interp, dedent(""" + print(spam, eggs) + """)) + self.assertEqual(out.strip(), '42 ham') + + def test_tuple(self): + values = {'spam': 42, 'eggs': 'ham'} + values = tuple(values.items()) + interp = interpreters.create() + interp.prepare_main(values) + out = _run_output(interp, dedent(""" + print(spam, eggs) + """)) + self.assertEqual(out.strip(), '42 ham') + + def test_kwargs(self): + values = {'spam': 42, 'eggs': 'ham'} + interp = interpreters.create() + interp.prepare_main(**values) + out = _run_output(interp, dedent(""" + print(spam, eggs) + """)) + self.assertEqual(out.strip(), '42 ham') + + def test_dict_and_kwargs(self): + values = {'spam': 42, 'eggs': 'ham'} + interp = interpreters.create() + interp.prepare_main(values, foo='bar') + out = _run_output(interp, dedent(""" + print(spam, eggs, foo) + """)) + self.assertEqual(out.strip(), '42 ham bar') + + def test_not_shareable(self): + interp = interpreters.create() + with self.assertRaises(interpreters.NotShareableError): + interp.prepare_main(spam={'spam': 'eggs', 'foo': 'bar'}) + + # Make sure neither was actually bound. + with self.assertRaises(ExecutionFailed): + interp.exec('print(foo)') + with self.assertRaises(ExecutionFailed): + interp.exec('print(spam)') + + def test_running(self): + interp = interpreters.create() + interp.prepare_main({'spam': True}) + with self.running(interp): + with self.assertRaisesRegex(InterpreterError, 'running'): + interp.prepare_main({'spam': False}) + interp.exec('assert spam is True') + + @requires_test_modules + def test_created_with_capi(self): + with self.interpreter_obj_from_capi() as (interp, interpid): + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + interp.prepare_main({'spam': True}) + with self.assertRaisesRegex(ExecutionFailed, 'NameError'): + self.run_from_capi(interpid, 'spam') + + +class TestInterpreterExec(TestBase): + + def test_success(self): + interp = interpreters.create() + script, results = _captured_script('print("it worked!", end="")') + with results: + interp.exec(script) + results = results.final() + results.raise_if_failed() + out = results.stdout + + self.assertEqual(out, 'it worked!') + + def test_failure(self): + interp = interpreters.create() + with self.assertRaises(ExecutionFailed): + interp.exec('raise Exception') + + @force_not_colorized + def test_display_preserved_exception(self): + tempdir = self.temp_dir() + modfile = self.make_module('spam', tempdir, text=""" + def ham(): + raise RuntimeError('uh-oh!') + + def eggs(): + ham() + """) + scriptfile = self.make_script('script.py', tempdir, text=""" + from concurrent import interpreters + + def script(): + import spam + spam.eggs() + + interp = interpreters.create() + try: + interp.exec(script) + finally: + interp.close() + """) + + stdout, stderr = self.assert_python_failure(scriptfile) + self.maxDiff = None + interpmod_line, = (l for l in stderr.splitlines() if ' exec' in l) + # File "{interpreters.__file__}", line 179, in exec + self.assertEqual(stderr, dedent(f"""\ + Traceback (most recent call last): + File "{scriptfile}", line 10, in + interp.exec(script) + ~~~~~~~~~~~^^^^^^^^ + {interpmod_line.strip()} + raise ExecutionFailed(excinfo) + concurrent.interpreters.ExecutionFailed: RuntimeError: uh-oh! + + Uncaught in the interpreter: + + Traceback (most recent call last): + File "{scriptfile}", line 6, in script + spam.eggs() + ~~~~~~~~~^^ + File "{modfile}", line 6, in eggs + ham() + ~~~^^ + File "{modfile}", line 3, in ham + raise RuntimeError('uh-oh!') + RuntimeError: uh-oh! + """)) + self.assertEqual(stdout, '') + + def test_in_thread(self): + interp = interpreters.create() + script, results = _captured_script('print("it worked!", end="")') + with results: + def f(): + interp.exec(script) + + t = threading.Thread(target=f) + t.start() + t.join() + results = results.final() + results.raise_if_failed() + out = results.stdout + + self.assertEqual(out, 'it worked!') + + @support.requires_fork() + def test_fork(self): + interp = interpreters.create() + import tempfile + with tempfile.NamedTemporaryFile('w+', encoding='utf-8') as file: + file.write('') + file.flush() + + expected = 'spam spam spam spam spam' + script = dedent(f""" + import os + try: + os.fork() + except RuntimeError: + with open('{file.name}', 'w', encoding='utf-8') as out: + out.write('{expected}') + """) + interp.exec(script) + + file.seek(0) + content = file.read() + self.assertEqual(content, expected) + + # XXX Is this still true? + @unittest.skip('Fails on FreeBSD') + def test_already_running(self): + interp = interpreters.create() + with _running(interp): + with self.assertRaises(RuntimeError): + interp.exec('print("spam")') + + def test_bad_script(self): + interp = interpreters.create() + with self.assertRaises(TypeError): + interp.exec(10) + + def test_bytes_for_script(self): + r, w = self.pipe() + RAN = b'R' + DONE = b'D' + interp = interpreters.create() + interp.exec(f"""if True: + import os + os.write({w}, {RAN!r}) + """) + os.write(w, DONE) + self.assertEqual(os.read(r, 1), RAN) + + def test_with_background_threads_still_running(self): + r_interp, w_interp = self.pipe() + r_thread, w_thread = self.pipe() + + RAN = b'R' + DONE = b'D' + FINISHED = b'F' + + interp = interpreters.create() + interp.exec(f"""if True: + import os + import threading + + def task(): + v = os.read({r_thread}, 1) + assert v == {DONE!r} + os.write({w_interp}, {FINISHED!r}) + t = threading.Thread(target=task) + t.start() + os.write({w_interp}, {RAN!r}) + """) + interp.exec(f"""if True: + os.write({w_interp}, {RAN!r}) + """) + + os.write(w_thread, DONE) + interp.exec('t.join()') + self.assertEqual(os.read(r_interp, 1), RAN) + self.assertEqual(os.read(r_interp, 1), RAN) + self.assertEqual(os.read(r_interp, 1), FINISHED) + + def test_created_with_capi(self): + with self.interpreter_obj_from_capi() as (interp, _): + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + interp.exec('raise Exception("it worked!")') + + def test_list_comprehension(self): + # gh-135450: List comprehensions caused an assertion failure + # in _PyCode_CheckNoExternalState() + import string + r_interp, w_interp = self.pipe() + + interp = interpreters.create() + interp.exec(f"""if True: + import os + comp = [str(i) for i in range(10)] + os.write({w_interp}, ''.join(comp).encode()) + """) + self.assertEqual(os.read(r_interp, 10).decode(), string.digits) + interp.close() + + + # test__interpreters covers the remaining + # Interpreter.exec() behavior. + + +call_func_noop = defs.spam_minimal +call_func_ident = defs.spam_returns_arg +call_func_failure = defs.spam_raises + + +def call_func_return_shareable(): + return (1, None) + + +def call_func_return_stateless_func(): + return (lambda x: x) + + +def call_func_return_pickleable(): + return [1, 2, 3] + + +def call_func_return_unpickleable(): + x = 42 + return (lambda: x) + + +def get_call_func_closure(value): + def call_func_closure(): + return value + return call_func_closure + + +def call_func_exec_wrapper(script, ns): + res = exec(script, ns, ns) + return res, ns, id(ns) + + +class Spam: + + @staticmethod + def noop(): + pass + + @classmethod + def from_values(cls, *values): + return cls(values) + + def __init__(self, value): + self.value = value + + def __call__(self, *args, **kwargs): + return (self.value, args, kwargs) + + def __eq__(self, other): + if not isinstance(other, Spam): + return NotImplemented + return self.value == other.value + + def run(self, *args, **kwargs): + return (self.value, args, kwargs) + + +def call_func_complex(op, /, value=None, *args, exc=None, **kwargs): + if exc is not None: + raise exc + if op == '': + raise ValueError('missing op') + elif op == 'ident': + if args or kwargs: + raise Exception((args, kwargs)) + return value + elif op == 'full-ident': + return (value, args, kwargs) + elif op == 'globals': + if value is not None or args or kwargs: + raise Exception((value, args, kwargs)) + return __name__ + elif op == 'interpid': + if value is not None or args or kwargs: + raise Exception((value, args, kwargs)) + return interpreters.get_current().id + elif op == 'closure': + if args or kwargs: + raise Exception((args, kwargs)) + return get_call_func_closure(value) + elif op == 'custom': + if args or kwargs: + raise Exception((args, kwargs)) + return Spam(value) + elif op == 'custom-inner': + if args or kwargs: + raise Exception((args, kwargs)) + class Eggs(Spam): + pass + return Eggs(value) + elif not isinstance(op, str): + raise TypeError(op) + else: + raise NotImplementedError(op) + + +class TestInterpreterCall(TestBase): + + # signature + # - blank + # - args + # - kwargs + # - args, kwargs + # return + # - nothing (None) + # - simple + # - closure + # - custom + # ops: + # - do nothing + # - fail + # - echo + # - do complex, relative to interpreter + # scope + # - global func + # - local closure + # - returned closure + # - callable type instance + # - type + # - classmethod + # - staticmethod + # - instance method + # exception + # - builtin + # - custom + # - preserves info (e.g. SyntaxError) + # - matching error display + + @contextlib.contextmanager + def assert_fails(self, expected): + with self.assertRaises(ExecutionFailed) as cm: + yield cm + uncaught = cm.exception.excinfo + self.assertEqual(uncaught.type.__name__, expected.__name__) + + def assert_fails_not_shareable(self): + return self.assert_fails(interpreters.NotShareableError) + + def assert_code_equal(self, code1, code2): + if code1 == code2: + return + self.assertEqual(code1.co_name, code2.co_name) + self.assertEqual(code1.co_flags, code2.co_flags) + self.assertEqual(code1.co_consts, code2.co_consts) + self.assertEqual(code1.co_varnames, code2.co_varnames) + self.assertEqual(code1.co_cellvars, code2.co_cellvars) + self.assertEqual(code1.co_freevars, code2.co_freevars) + self.assertEqual(code1.co_names, code2.co_names) + self.assertEqual( + _testinternalcapi.get_code_var_counts(code1), + _testinternalcapi.get_code_var_counts(code2), + ) + self.assertEqual(code1.co_code, code2.co_code) + + def assert_funcs_equal(self, func1, func2): + if func1 == func2: + return + self.assertIs(type(func1), type(func2)) + self.assertEqual(func1.__name__, func2.__name__) + self.assertEqual(func1.__defaults__, func2.__defaults__) + self.assertEqual(func1.__kwdefaults__, func2.__kwdefaults__) + self.assertEqual(func1.__closure__, func2.__closure__) + self.assert_code_equal(func1.__code__, func2.__code__) + self.assertEqual( + _testinternalcapi.get_code_var_counts(func1), + _testinternalcapi.get_code_var_counts(func2), + ) + + def assert_exceptions_equal(self, exc1, exc2): + assert isinstance(exc1, Exception) + assert isinstance(exc2, Exception) + if exc1 == exc2: + return + self.assertIs(type(exc1), type(exc2)) + self.assertEqual(exc1.args, exc2.args) + + def test_stateless_funcs(self): + interp = interpreters.create() + + func = call_func_noop + with self.subTest('no args, no return'): + res = interp.call(func) + self.assertIsNone(res) + + func = call_func_return_shareable + with self.subTest('no args, returns shareable'): + res = interp.call(func) + self.assertEqual(res, (1, None)) + + func = call_func_return_stateless_func + expected = (lambda x: x) + with self.subTest('no args, returns stateless func'): + res = interp.call(func) + self.assert_funcs_equal(res, expected) + + func = call_func_return_pickleable + with self.subTest('no args, returns pickleable'): + res = interp.call(func) + self.assertEqual(res, [1, 2, 3]) + + func = call_func_return_unpickleable + with self.subTest('no args, returns unpickleable'): + with self.assertRaises(interpreters.NotShareableError): + interp.call(func) + + def test_stateless_func_returns_arg(self): + interp = interpreters.create() + + for arg in [ + None, + 10, + 'spam!', + b'spam!', + (1, 2, 'spam!'), + memoryview(b'spam!'), + ]: + with self.subTest(f'shareable {arg!r}'): + assert _interpreters.is_shareable(arg) + res = interp.call(defs.spam_returns_arg, arg) + self.assertEqual(res, arg) + + for arg in defs.STATELESS_FUNCTIONS: + with self.subTest(f'stateless func {arg!r}'): + res = interp.call(defs.spam_returns_arg, arg) + self.assert_funcs_equal(res, arg) + + for arg in defs.TOP_FUNCTIONS: + if arg in defs.STATELESS_FUNCTIONS: + continue + with self.subTest(f'stateful func {arg!r}'): + res = interp.call(defs.spam_returns_arg, arg) + self.assert_funcs_equal(res, arg) + assert is_pickleable(arg) + + for arg in [ + Ellipsis, + NotImplemented, + object(), + 2**1000, + [1, 2, 3], + {'a': 1, 'b': 2}, + types.SimpleNamespace(x=42), + # builtin types + object, + type, + Exception, + ModuleNotFoundError, + # builtin exceptions + Exception('uh-oh!'), + ModuleNotFoundError('mymodule'), + # builtin fnctions + len, + sys.exit, + # user classes + *defs.TOP_CLASSES, + *(c(*a) for c, a in defs.TOP_CLASSES.items() + if c not in defs.CLASSES_WITHOUT_EQUALITY), + ]: + with self.subTest(f'pickleable {arg!r}'): + res = interp.call(defs.spam_returns_arg, arg) + if type(arg) is object: + self.assertIs(type(res), object) + elif isinstance(arg, BaseException): + self.assert_exceptions_equal(res, arg) + else: + self.assertEqual(res, arg) + assert is_pickleable(arg) + + for arg in [ + types.MappingProxyType({}), + *(f for f in defs.NESTED_FUNCTIONS + if f not in defs.STATELESS_FUNCTIONS), + ]: + with self.subTest(f'unpickleable {arg!r}'): + assert not _interpreters.is_shareable(arg) + assert not is_pickleable(arg) + with self.assertRaises(interpreters.NotShareableError): + interp.call(defs.spam_returns_arg, arg) + + def test_full_args(self): + interp = interpreters.create() + expected = (1, 2, 3, 4, 5, 6, ('?',), {'g': 7, 'h': 8}) + func = defs.spam_full_args + res = interp.call(func, 1, 2, 3, 4, '?', e=5, f=6, g=7, h=8) + self.assertEqual(res, expected) + + def test_full_defaults(self): + # pickleable, but not stateless + interp = interpreters.create() + expected = (-1, -2, -3, -4, -5, -6, (), {'g': 8, 'h': 9}) + res = interp.call(defs.spam_full_args_with_defaults, g=8, h=9) + self.assertEqual(res, expected) + + def test_modified_arg(self): + interp = interpreters.create() + script = dedent(""" + a = 7 + b = 2 + c = a ** b + """) + ns = {} + expected = {'a': 7, 'b': 2, 'c': 49} + res = interp.call(call_func_exec_wrapper, script, ns) + obj, resns, resid = res + del resns['__builtins__'] + self.assertIsNone(obj) + self.assertEqual(ns, {}) + self.assertEqual(resns, expected) + self.assertNotEqual(resid, id(ns)) + self.assertNotEqual(resid, id(resns)) + + def test_func_in___main___valid(self): + # pickleable, already there' + + with os_helper.temp_dir() as tempdir: + def new_mod(name, text): + script_helper.make_script(tempdir, name, dedent(text)) + + def run(text): + name = 'myscript' + text = dedent(f""" + import sys + sys.path.insert(0, {tempdir!r}) + + """) + dedent(text) + filename = script_helper.make_script(tempdir, name, text) + res = script_helper.assert_python_ok(filename) + return res.out.decode('utf-8').strip() + + # no module indirection + with self.subTest('no indirection'): + text = run(f""" + from concurrent import interpreters + + def spam(): + # This a global var... + return __name__ + + if __name__ == '__main__': + interp = interpreters.create() + res = interp.call(spam) + print(res) + """) + self.assertEqual(text, '') + + # indirect as func, direct interp + new_mod('mymod', f""" + def run(interp, func): + return interp.call(func) + """) + with self.subTest('indirect as func, direct interp'): + text = run(f""" + from concurrent import interpreters + import mymod + + def spam(): + # This a global var... + return __name__ + + if __name__ == '__main__': + interp = interpreters.create() + res = mymod.run(interp, spam) + print(res) + """) + self.assertEqual(text, '') + + # indirect as func, indirect interp + new_mod('mymod', f""" + from concurrent import interpreters + def run(func): + interp = interpreters.create() + return interp.call(func) + """) + with self.subTest('indirect as func, indirect interp'): + text = run(f""" + import mymod + + def spam(): + # This a global var... + return __name__ + + if __name__ == '__main__': + res = mymod.run(spam) + print(res) + """) + self.assertEqual(text, '') + + def test_func_in___main___invalid(self): + interp = interpreters.create() + + funcname = f'{__name__.replace(".", "_")}_spam_okay' + script = dedent(f""" + def {funcname}(): + # This a global var... + return __name__ + """) + + with self.subTest('pickleable, added dynamically'): + with defined_in___main__(funcname, script) as arg: + with self.assertRaises(interpreters.NotShareableError): + interp.call(defs.spam_returns_arg, arg) + + with self.subTest('lying about __main__'): + with defined_in___main__(funcname, script, remove=True) as arg: + with self.assertRaises(interpreters.NotShareableError): + interp.call(defs.spam_returns_arg, arg) + + def test_func_in___main___hidden(self): + # When a top-level function that uses global variables is called + # through Interpreter.call(), it will be pickled, sent over, + # and unpickled. That requires that it be found in the other + # interpreter's __main__ module. However, the original script + # that defined the function is only run in the main interpreter, + # so pickle.loads() would normally fail. + # + # We work around this by running the script in the other + # interpreter. However, this is a one-off solution for the sake + # of unpickling, so we avoid modifying that interpreter's + # __main__ module by running the script in a hidden module. + # + # In this test we verify that the function runs with the hidden + # module as its __globals__ when called in the other interpreter, + # and that the interpreter's __main__ module is unaffected. + text = dedent(""" + eggs = True + + def spam(*, explicit=False): + if explicit: + import __main__ + ns = __main__.__dict__ + else: + # For now we have to have a LOAD_GLOBAL in the + # function in order for globals() to actually return + # spam.__globals__. Maybe it doesn't go through pickle? + # XXX We will fix this later. + spam + ns = globals() + + func = ns.get('spam') + return [ + id(ns), + ns.get('__name__'), + ns.get('__file__'), + id(func), + None if func is None else repr(func), + ns.get('eggs'), + ns.get('ham'), + ] + + if __name__ == "__main__": + from concurrent import interpreters + interp = interpreters.create() + + ham = True + print([ + [ + spam(explicit=True), + spam(), + ], + [ + interp.call(spam, explicit=True), + interp.call(spam), + ], + ]) + """) + with os_helper.temp_dir() as tempdir: + filename = script_helper.make_script(tempdir, 'my-script', text) + res = script_helper.assert_python_ok(filename) + stdout = res.out.decode('utf-8').strip() + local, remote = eval(stdout) + + # In the main interpreter. + main, unpickled = local + nsid, _, _, funcid, func, _, _ = main + self.assertEqual(main, [ + nsid, + '__main__', + filename, + funcid, + func, + True, + True, + ]) + self.assertIsNot(func, None) + self.assertRegex(func, '^$') + self.assertEqual(unpickled, main) + + # In the subinterpreter. + main, unpickled = remote + nsid1, _, _, funcid1, _, _, _ = main + self.assertEqual(main, [ + nsid1, + '__main__', + None, + funcid1, + None, + None, + None, + ]) + nsid2, _, _, funcid2, func, _, _ = unpickled + self.assertEqual(unpickled, [ + nsid2, + '', + filename, + funcid2, + func, + True, + None, + ]) + self.assertIsNot(func, None) + self.assertRegex(func, '^$') + self.assertNotEqual(nsid2, nsid1) + self.assertNotEqual(funcid2, funcid1) + + def test_func_in___main___uses_globals(self): + # See the note in test_func_in___main___hidden about pickle + # and the __main__ module. + # + # Additionally, the solution to that problem must provide + # for global variables on which a pickled function might rely. + # + # To check that, we run a script that has two global functions + # and a global variable in the __main__ module. One of the + # functions sets the global variable and the other returns + # the value. + # + # The script calls those functions multiple times in another + # interpreter, to verify the following: + # + # * the global variable is properly initialized + # * the global variable retains state between calls + # * the setter modifies that persistent variable + # * the getter uses the variable + # * the calls in the other interpreter do not modify + # the main interpreter + # * those calls don't modify the interpreter's __main__ module + # * the functions and variable do not actually show up in the + # other interpreter's __main__ module + text = dedent(""" + count = 0 + + def inc(x=1): + global count + count += x + + def get_count(): + return count + + if __name__ == "__main__": + counts = [] + results = [count, counts] + + from concurrent import interpreters + interp = interpreters.create() + + val = interp.call(get_count) + counts.append(val) + + interp.call(inc) + val = interp.call(get_count) + counts.append(val) + + interp.call(inc, 3) + val = interp.call(get_count) + counts.append(val) + + results.append(count) + + modified = {name: interp.call(eval, f'{name!r} in vars()') + for name in ('count', 'inc', 'get_count')} + results.append(modified) + + print(results) + """) + with os_helper.temp_dir() as tempdir: + filename = script_helper.make_script(tempdir, 'my-script', text) + res = script_helper.assert_python_ok(filename) + stdout = res.out.decode('utf-8').strip() + before, counts, after, modified = eval(stdout) + self.assertEqual(modified, { + 'count': False, + 'inc': False, + 'get_count': False, + }) + self.assertEqual(before, 0) + self.assertEqual(after, 0) + self.assertEqual(counts, [0, 1, 4]) + + def test_raises(self): + interp = interpreters.create() + with self.assertRaises(ExecutionFailed): + interp.call(call_func_failure) + + with self.assert_fails(ValueError): + interp.call(call_func_complex, '???', exc=ValueError('spam')) + + def test_call_valid(self): + interp = interpreters.create() + + for i, (callable, args, kwargs, expected) in enumerate([ + (call_func_noop, (), {}, None), + (call_func_ident, ('spamspamspam',), {}, 'spamspamspam'), + (call_func_return_shareable, (), {}, (1, None)), + (call_func_return_pickleable, (), {}, [1, 2, 3]), + (Spam.noop, (), {}, None), + (Spam.from_values, (), {}, Spam(())), + (Spam.from_values, (1, 2, 3), {}, Spam((1, 2, 3))), + (Spam, ('???',), {}, Spam('???')), + (Spam(101), (), {}, (101, (), {})), + (Spam(10101).run, (), {}, (10101, (), {})), + (call_func_complex, ('ident', 'spam'), {}, 'spam'), + (call_func_complex, ('full-ident', 'spam'), {}, ('spam', (), {})), + (call_func_complex, ('full-ident', 'spam', 'ham'), {'eggs': '!!!'}, + ('spam', ('ham',), {'eggs': '!!!'})), + (call_func_complex, ('globals',), {}, __name__), + (call_func_complex, ('interpid',), {}, interp.id), + (call_func_complex, ('custom', 'spam!'), {}, Spam('spam!')), + ]): + with self.subTest(f'success case #{i+1}'): + res = interp.call(callable, *args, **kwargs) + self.assertEqual(res, expected) + + def test_call_invalid(self): + interp = interpreters.create() + + func = get_call_func_closure + with self.subTest(func): + with self.assertRaises(interpreters.NotShareableError): + interp.call(func, 42) + + func = get_call_func_closure(42) + with self.subTest(func): + with self.assertRaises(interpreters.NotShareableError): + interp.call(func) + + func = call_func_complex + op = 'closure' + with self.subTest(f'{func} ({op})'): + with self.assertRaises(interpreters.NotShareableError): + interp.call(func, op, value='~~~') + + op = 'custom-inner' + with self.subTest(f'{func} ({op})'): + with self.assertRaises(interpreters.NotShareableError): + interp.call(func, op, 'eggs!') + + def test_callable_requires_frame(self): + # There are various functions that require a current frame. + interp = interpreters.create() + for call, expected in [ + ((eval, '[1, 2, 3]'), + [1, 2, 3]), + ((eval, 'sum([1, 2, 3])'), + 6), + ((exec, '...'), + None), + ]: + with self.subTest(str(call)): + res = interp.call(*call) + self.assertEqual(res, expected) + + result_not_pickleable = [ + globals, + locals, + vars, + ] + for func, expectedtype in { + globals: dict, + locals: dict, + vars: dict, + dir: list, + }.items(): + with self.subTest(str(func)): + if func in result_not_pickleable: + with self.assertRaises(interpreters.NotShareableError): + interp.call(func) + else: + res = interp.call(func) + self.assertIsInstance(res, expectedtype) + self.assertIn('__builtins__', res) + + def test_globals_from_builtins(self): + # The builtins exec(), eval(), globals(), locals(), vars(), + # and dir() each runs relative to the target interpreter's + # __main__ module, when called directly. However, + # globals(), locals(), and vars() don't work when called + # directly so we don't check them. + from _frozen_importlib import BuiltinImporter + interp = interpreters.create() + + names = interp.call(dir) + self.assertEqual(names, [ + '__builtins__', + '__doc__', + '__loader__', + '__name__', + '__package__', + '__spec__', + ]) + + values = {name: interp.call(eval, name) + for name in names if name != '__builtins__'} + self.assertEqual(values, { + '__name__': '__main__', + '__doc__': None, + '__spec__': None, # It wasn't imported, so no module spec? + '__package__': None, + '__loader__': BuiltinImporter, + }) + with self.assertRaises(ExecutionFailed): + interp.call(eval, 'spam'), + + interp.call(exec, f'assert dir() == {names}') + + # Update the interpreter's __main__. + interp.prepare_main(spam=42) + expected = names + ['spam'] + + names = interp.call(dir) + self.assertEqual(names, expected) + + value = interp.call(eval, 'spam') + self.assertEqual(value, 42) + + interp.call(exec, f'assert dir() == {expected}, dir()') + + def test_globals_from_stateless_func(self): + # A stateless func, which doesn't depend on any globals, + # doesn't go through pickle, so it runs in __main__. + def set_global(name, value): + globals()[name] = value + + def get_global(name): + return globals().get(name) + + interp = interpreters.create() + + modname = interp.call(get_global, '__name__') + self.assertEqual(modname, '__main__') + + res = interp.call(get_global, 'spam') + self.assertIsNone(res) + + interp.exec('spam = True') + res = interp.call(get_global, 'spam') + self.assertTrue(res) + + interp.call(set_global, 'spam', 42) + res = interp.call(get_global, 'spam') + self.assertEqual(res, 42) + + interp.exec('assert spam == 42, repr(spam)') + + def test_call_in_thread(self): + interp = interpreters.create() + + for i, (callable, args, kwargs) in enumerate([ + (call_func_noop, (), {}), + (call_func_return_shareable, (), {}), + (call_func_return_pickleable, (), {}), + (Spam.from_values, (), {}), + (Spam.from_values, (1, 2, 3), {}), + (Spam(101), (), {}), + (Spam(10101).run, (), {}), + (Spam.noop, (), {}), + (call_func_complex, ('ident', 'spam'), {}), + (call_func_complex, ('full-ident', 'spam'), {}), + (call_func_complex, ('full-ident', 'spam', 'ham'), {'eggs': '!!!'}), + (call_func_complex, ('globals',), {}), + (call_func_complex, ('interpid',), {}), + (call_func_complex, ('custom', 'spam!'), {}), + ]): + with self.subTest(f'success case #{i+1}'): + with self.captured_thread_exception() as ctx: + t = interp.call_in_thread(callable, *args, **kwargs) + t.join() + self.assertIsNone(ctx.caught) + + for i, (callable, args, kwargs) in enumerate([ + (get_call_func_closure, (42,), {}), + (get_call_func_closure(42), (), {}), + ]): + with self.subTest(f'invalid case #{i+1}'): + with self.captured_thread_exception() as ctx: + t = interp.call_in_thread(callable, *args, **kwargs) + t.join() + self.assertIsNotNone(ctx.caught) + + with self.captured_thread_exception() as ctx: + t = interp.call_in_thread(call_func_failure) + t.join() + self.assertIsNotNone(ctx.caught) + + +class TestIsShareable(TestBase): + + def test_default_shareables(self): + shareables = [ + # singletons + None, + # builtin objects + b'spam', + 'spam', + 10, + -10, + True, + False, + 100.0, + (), + (1, ('spam', 'eggs'), True), + ] + for obj in shareables: + with self.subTest(obj): + shareable = interpreters.is_shareable(obj) + self.assertTrue(shareable) + + def test_not_shareable(self): + class Cheese: + def __init__(self, name): + self.name = name + def __str__(self): + return self.name + + class SubBytes(bytes): + """A subclass of a shareable type.""" + + not_shareables = [ + # singletons + NotImplemented, + ..., + # builtin types and objects + type, + object, + object(), + Exception(), + # user-defined types and objects + Cheese, + Cheese('Wensleydale'), + SubBytes(b'spam'), + ] + for obj in not_shareables: + with self.subTest(repr(obj)): + self.assertFalse( + interpreters.is_shareable(obj)) + + +class LowLevelTests(TestBase): + + # The behaviors in the low-level module are important in as much + # as they are exercised by the high-level module. Therefore the + # most important testing happens in the high-level tests. + # These low-level tests cover corner cases that are not + # encountered by the high-level module, thus they + # mostly shouldn't matter as much. + + def test_new_config(self): + # This test overlaps with + # test.test_capi.test_misc.InterpreterConfigTests. + + default = _interpreters.new_config('isolated') + with self.subTest('no arg'): + config = _interpreters.new_config() + self.assert_ns_equal(config, default) + self.assertIsNot(config, default) + + with self.subTest('default'): + config1 = _interpreters.new_config('default') + self.assert_ns_equal(config1, default) + self.assertIsNot(config1, default) + + config2 = _interpreters.new_config('default') + self.assert_ns_equal(config2, config1) + self.assertIsNot(config2, config1) + + for arg in ['', 'default']: + with self.subTest(f'default ({arg!r})'): + config = _interpreters.new_config(arg) + self.assert_ns_equal(config, default) + self.assertIsNot(config, default) + + supported = { + 'isolated': types.SimpleNamespace( + use_main_obmalloc=False, + allow_fork=False, + allow_exec=False, + allow_threads=True, + allow_daemon_threads=False, + check_multi_interp_extensions=True, + gil='own', + ), + 'legacy': types.SimpleNamespace( + use_main_obmalloc=True, + allow_fork=True, + allow_exec=True, + allow_threads=True, + allow_daemon_threads=True, + check_multi_interp_extensions=bool(Py_GIL_DISABLED), + gil='shared', + ), + 'empty': types.SimpleNamespace( + use_main_obmalloc=False, + allow_fork=False, + allow_exec=False, + allow_threads=False, + allow_daemon_threads=False, + check_multi_interp_extensions=False, + gil='default', + ), + } + gil_supported = ['default', 'shared', 'own'] + + for name, vanilla in supported.items(): + with self.subTest(f'supported ({name})'): + expected = vanilla + config1 = _interpreters.new_config(name) + self.assert_ns_equal(config1, expected) + self.assertIsNot(config1, expected) + + config2 = _interpreters.new_config(name) + self.assert_ns_equal(config2, config1) + self.assertIsNot(config2, config1) + + with self.subTest(f'noop override ({name})'): + expected = vanilla + overrides = vars(vanilla) + config = _interpreters.new_config(name, **overrides) + self.assert_ns_equal(config, expected) + + with self.subTest(f'override all ({name})'): + overrides = {k: not v for k, v in vars(vanilla).items()} + for gil in gil_supported: + if vanilla.gil == gil: + continue + overrides['gil'] = gil + expected = types.SimpleNamespace(**overrides) + config = _interpreters.new_config(name, **overrides) + self.assert_ns_equal(config, expected) + + # Override individual fields. + for field, old in vars(vanilla).items(): + if field == 'gil': + values = [v for v in gil_supported if v != old] + else: + values = [not old] + for val in values: + with self.subTest(f'{name}.{field} ({old!r} -> {val!r})'): + overrides = {field: val} + expected = types.SimpleNamespace( + **dict(vars(vanilla), **overrides), + ) + config = _interpreters.new_config(name, **overrides) + self.assert_ns_equal(config, expected) + + with self.subTest('extra override'): + with self.assertRaises(ValueError): + _interpreters.new_config(spam=True) + + # Bad values for bool fields. + for field, value in vars(supported['empty']).items(): + if field == 'gil': + continue + assert isinstance(value, bool) + for value in [1, '', 'spam', 1.0, None, object()]: + with self.subTest(f'bad override ({field}={value!r})'): + with self.assertRaises(TypeError): + _interpreters.new_config(**{field: value}) + + # Bad values for .gil. + for value in [True, 1, 1.0, None, object()]: + with self.subTest(f'bad override (gil={value!r})'): + with self.assertRaises(TypeError): + _interpreters.new_config(gil=value) + for value in ['', 'spam']: + with self.subTest(f'bad override (gil={value!r})'): + with self.assertRaises(ValueError): + _interpreters.new_config(gil=value) + + def test_get_main(self): + interpid, whence = _interpreters.get_main() + self.assertEqual(interpid, 0) + self.assertEqual(whence, _interpreters.WHENCE_RUNTIME) + self.assertEqual( + _interpreters.whence(interpid), + _interpreters.WHENCE_RUNTIME) + + def test_get_current(self): + with self.subTest('main'): + main, *_ = _interpreters.get_main() + interpid, whence = _interpreters.get_current() + self.assertEqual(interpid, main) + self.assertEqual(whence, _interpreters.WHENCE_RUNTIME) + + script = f""" + import _interpreters + interpid, whence = _interpreters.get_current() + print((interpid, whence)) + """ + def parse_stdout(text): + interpid, whence = eval(text) + return interpid, whence + + with self.subTest('from _interpreters'): + orig = _interpreters.create() + text = self.run_and_capture(orig, script) + interpid, whence = parse_stdout(text) + self.assertEqual(interpid, orig) + self.assertEqual(whence, _interpreters.WHENCE_STDLIB) + + with self.subTest('from C-API'): + last = 0 + for id, *_ in _interpreters.list_all(): + last = max(last, id) + expected = last + 1 + text = self.run_temp_from_capi(script) + interpid, whence = parse_stdout(text) + self.assertEqual(interpid, expected) + self.assertEqual(whence, _interpreters.WHENCE_CAPI) + + def test_list_all(self): + mainid, *_ = _interpreters.get_main() + interpid1 = _interpreters.create() + interpid2 = _interpreters.create() + interpid3 = _interpreters.create() + expected = [ + (mainid, _interpreters.WHENCE_RUNTIME), + (interpid1, _interpreters.WHENCE_STDLIB), + (interpid2, _interpreters.WHENCE_STDLIB), + (interpid3, _interpreters.WHENCE_STDLIB), + ] + + with self.subTest('main'): + res = _interpreters.list_all() + self.assertEqual(res, expected) + + with self.subTest('via interp from _interpreters'): + text = self.run_and_capture(interpid2, f""" + import _interpreters + print( + _interpreters.list_all()) + """) + + res = eval(text) + self.assertEqual(res, expected) + + with self.subTest('via interp from C-API'): + interpid4 = interpid3 + 1 + interpid5 = interpid4 + 1 + expected2 = expected + [ + (interpid4, _interpreters.WHENCE_CAPI), + (interpid5, _interpreters.WHENCE_STDLIB), + ] + expected3 = expected + [ + (interpid5, _interpreters.WHENCE_STDLIB), + ] + text = self.run_temp_from_capi(f""" + import _interpreters + _interpreters.create() + print( + _interpreters.list_all()) + """) + res2 = eval(text) + res3 = _interpreters.list_all() + self.assertEqual(res2, expected2) + self.assertEqual(res3, expected3) + + def test_create(self): + isolated = _interpreters.new_config('isolated') + legacy = _interpreters.new_config('legacy') + default = isolated + + with self.subTest('no args'): + interpid = _interpreters.create() + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, default) + + with self.subTest('config: None'): + interpid = _interpreters.create(None) + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, default) + + with self.subTest('config: \'empty\''): + with self.assertRaises(InterpreterError): + # The "empty" config isn't viable on its own. + _interpreters.create('empty') + + for arg, expected in { + '': default, + 'default': default, + 'isolated': isolated, + 'legacy': legacy, + }.items(): + with self.subTest(f'str arg: {arg!r}'): + interpid = _interpreters.create(arg) + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, expected) + + with self.subTest('custom'): + orig = _interpreters.new_config('empty') + orig.use_main_obmalloc = True + orig.check_multi_interp_extensions = bool(Py_GIL_DISABLED) + orig.gil = 'shared' + interpid = _interpreters.create(orig) + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, orig) + + with self.subTest('missing fields'): + orig = _interpreters.new_config() + del orig.gil + with self.assertRaises(ValueError): + _interpreters.create(orig) + + with self.subTest('extra fields'): + orig = _interpreters.new_config() + orig.spam = True + with self.assertRaises(ValueError): + _interpreters.create(orig) + + with self.subTest('whence'): + interpid = _interpreters.create() + self.assertEqual( + _interpreters.whence(interpid), + _interpreters.WHENCE_STDLIB) + + @requires_test_modules + def test_destroy(self): + with self.subTest('from _interpreters'): + interpid = _interpreters.create() + before = [id for id, *_ in _interpreters.list_all()] + _interpreters.destroy(interpid) + after = [id for id, *_ in _interpreters.list_all()] + + self.assertIn(interpid, before) + self.assertNotIn(interpid, after) + self.assertFalse( + self.interp_exists(interpid)) + + with self.subTest('main'): + interpid, *_ = _interpreters.get_main() + with self.assertRaises(InterpreterError): + # It is the current interpreter. + _interpreters.destroy(interpid) + + with self.subTest('from C-API'): + interpid = _testinternalcapi.create_interpreter() + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + _interpreters.destroy(interpid, restrict=True) + self.assertTrue( + self.interp_exists(interpid)) + _interpreters.destroy(interpid) + self.assertFalse( + self.interp_exists(interpid)) + + with self.subTest('basic C-API'): + interpid = _testinternalcapi.create_interpreter() + self.assertTrue( + self.interp_exists(interpid)) + _testinternalcapi.destroy_interpreter(interpid, basic=True) + self.assertFalse( + self.interp_exists(interpid)) + + def test_get_config(self): + # This test overlaps with + # test.test_capi.test_misc.InterpreterConfigTests. + + with self.subTest('main'): + expected = _interpreters.new_config('legacy') + expected.gil = 'own' + if Py_GIL_DISABLED: + expected.check_multi_interp_extensions = False + interpid, *_ = _interpreters.get_main() + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, expected) + + with self.subTest('isolated'): + expected = _interpreters.new_config('isolated') + interpid = _interpreters.create('isolated') + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, expected) + + with self.subTest('legacy'): + expected = _interpreters.new_config('legacy') + interpid = _interpreters.create('legacy') + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, expected) + + with self.subTest('from C-API'): + orig = _interpreters.new_config('isolated') + with self.interpreter_from_capi(orig) as interpid: + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + _interpreters.get_config(interpid, restrict=True) + config = _interpreters.get_config(interpid) + self.assert_ns_equal(config, orig) + + @requires_test_modules + def test_whence(self): + with self.subTest('main'): + interpid, *_ = _interpreters.get_main() + whence = _interpreters.whence(interpid) + self.assertEqual(whence, _interpreters.WHENCE_RUNTIME) + + with self.subTest('stdlib'): + interpid = _interpreters.create() + whence = _interpreters.whence(interpid) + self.assertEqual(whence, _interpreters.WHENCE_STDLIB) + + for orig, name in { + _interpreters.WHENCE_UNKNOWN: 'not ready', + _interpreters.WHENCE_LEGACY_CAPI: 'legacy C-API', + _interpreters.WHENCE_CAPI: 'C-API', + _interpreters.WHENCE_XI: 'cross-interpreter C-API', + }.items(): + with self.subTest(f'from C-API ({orig}: {name})'): + with self.interpreter_from_capi(whence=orig) as interpid: + whence = _interpreters.whence(interpid) + self.assertEqual(whence, orig) + + with self.subTest('from C-API, running'): + text = self.run_temp_from_capi(dedent(f""" + import _interpreters + interpid, *_ = _interpreters.get_current() + print(_interpreters.whence(interpid)) + """), + config=True) + whence = eval(text) + self.assertEqual(whence, _interpreters.WHENCE_CAPI) + + with self.subTest('from legacy C-API, running'): + ... + text = self.run_temp_from_capi(dedent(f""" + import _interpreters + interpid, *_ = _interpreters.get_current() + print(_interpreters.whence(interpid)) + """), + config=False) + whence = eval(text) + self.assertEqual(whence, _interpreters.WHENCE_LEGACY_CAPI) + + def test_contextvars_missing(self): + script = f""" + import contextvars + print(getattr(contextvars.Token, "MISSING", "'doesn't exist'")) + """ + + orig = _interpreters.create() + text = self.run_and_capture(orig, script) + self.assertEqual(text.strip(), "") + + def test_is_running(self): + def check(interpid, expected): + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + _interpreters.is_running(interpid, restrict=True) + running = _interpreters.is_running(interpid) + self.assertIs(running, expected) + + with self.subTest('from _interpreters (running)'): + interpid = _interpreters.create() + with self.running(interpid): + running = _interpreters.is_running(interpid) + self.assertTrue(running) + + with self.subTest('from _interpreters (not running)'): + interpid = _interpreters.create() + running = _interpreters.is_running(interpid) + self.assertFalse(running) + + with self.subTest('main'): + interpid, *_ = _interpreters.get_main() + check(interpid, True) + + with self.subTest('from C-API (running __main__)'): + with self.interpreter_from_capi() as interpid: + with self.running_from_capi(interpid, main=True): + check(interpid, True) + + with self.subTest('from C-API (running, but not __main__)'): + with self.interpreter_from_capi() as interpid: + with self.running_from_capi(interpid, main=False): + check(interpid, False) + + with self.subTest('from C-API (not running)'): + with self.interpreter_from_capi() as interpid: + check(interpid, False) + + def test_exec(self): + with self.subTest('run script'): + interpid = _interpreters.create() + script, results = _captured_script('print("it worked!", end="")') + with results: + exc = _interpreters.exec(interpid, script) + results = results.final() + results.raise_if_failed() + out = results.stdout + self.assertEqual(out, 'it worked!') + + with self.subTest('uncaught exception'): + interpid = _interpreters.create() + script, results = _captured_script(""" + raise Exception('uh-oh!') + print("it worked!", end="") + """) + with results: + exc = _interpreters.exec(interpid, script) + out = results.stdout() + expected = build_excinfo( + Exception, 'uh-oh!', + # We check these in other tests. + formatted=exc.formatted, + errdisplay=exc.errdisplay, + ) + self.assertEqual(out, '') + self.assert_ns_equal(exc, expected) + + with self.subTest('from C-API'): + with self.interpreter_from_capi() as interpid: + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + _interpreters.exec(interpid, 'raise Exception("it worked!")', + restrict=True) + exc = _interpreters.exec(interpid, 'raise Exception("it worked!")') + self.assertIsNot(exc, None) + self.assertEqual(exc.msg, 'it worked!') + + def test_call(self): + interpid = _interpreters.create() + + # Here we focus on basic args and return values. + # See TestInterpreterCall for full operational coverage, + # including supported callables. + + with self.subTest('no args, return None'): + func = defs.spam_minimal + res, exc = _interpreters.call(interpid, func) + self.assertIsNone(exc) + self.assertIsNone(res) + + with self.subTest('empty args, return None'): + func = defs.spam_minimal + res, exc = _interpreters.call(interpid, func, (), {}) + self.assertIsNone(exc) + self.assertIsNone(res) + + with self.subTest('no args, return non-None'): + func = defs.script_with_return + res, exc = _interpreters.call(interpid, func) + self.assertIsNone(exc) + self.assertIs(res, True) + + with self.subTest('full args, return non-None'): + expected = (1, 2, 3, 4, 5, 6, (7, 8), {'g': 9, 'h': 0}) + func = defs.spam_full_args + args = (1, 2, 3, 4, 7, 8) + kwargs = dict(e=5, f=6, g=9, h=0) + res, exc = _interpreters.call(interpid, func, args, kwargs) + self.assertIsNone(exc) + self.assertEqual(res, expected) + + with self.subTest('uncaught exception'): + func = defs.spam_raises + res, exc = _interpreters.call(interpid, func) + expected = build_excinfo( + Exception, 'spam!', + # We check these in other tests. + formatted=exc.formatted, + errdisplay=exc.errdisplay, + ) + self.assertIsNone(res) + self.assertEqual(exc, expected) + + @requires_test_modules + def test_set___main___attrs(self): + with self.subTest('from _interpreters'): + interpid = _interpreters.create() + before1 = _interpreters.exec(interpid, 'assert spam == \'eggs\'') + before2 = _interpreters.exec(interpid, 'assert ham == 42') + self.assertEqual(before1.type.__name__, 'NameError') + self.assertEqual(before2.type.__name__, 'NameError') + + _interpreters.set___main___attrs(interpid, dict( + spam='eggs', + ham=42, + )) + after1 = _interpreters.exec(interpid, 'assert spam == \'eggs\'') + after2 = _interpreters.exec(interpid, 'assert ham == 42') + after3 = _interpreters.exec(interpid, 'assert spam == 42') + self.assertIs(after1, None) + self.assertIs(after2, None) + self.assertEqual(after3.type.__name__, 'AssertionError') + + with self.assertRaises(ValueError): + # GH-127165: Embedded NULL characters broke the lookup + _interpreters.set___main___attrs(interpid, {"\x00": 1}) + + with self.subTest('from C-API'): + with self.interpreter_from_capi() as interpid: + with self.assertRaisesRegex(InterpreterError, 'unrecognized'): + _interpreters.set___main___attrs(interpid, {'spam': True}, + restrict=True) + _interpreters.set___main___attrs(interpid, {'spam': True}) + rc = _testinternalcapi.exec_interpreter( + interpid, + 'assert spam is True', + ) + self.assertEqual(rc, 0) + + +if __name__ == '__main__': + # Test needs to be a package, so we can do relative imports. + unittest.main() diff --git a/Lib/test/test_interpreters/test_channels.py b/Lib/test/test_interpreters/test_channels.py new file mode 100644 index 00000000000..5437792b5a7 --- /dev/null +++ b/Lib/test/test_interpreters/test_channels.py @@ -0,0 +1,610 @@ +import importlib +import pickle +import threading +from textwrap import dedent +import unittest +import time + +from test.support import import_helper +# Raise SkipTest if subinterpreters not supported. +_channels = import_helper.import_module('_interpchannels') +from concurrent import interpreters +from test.support import channels +from .utils import _run_output, TestBase + + +class LowLevelTests(TestBase): + + # The behaviors in the low-level module is important in as much + # as it is exercised by the high-level module. Therefore the + # most # important testing happens in the high-level tests. + # These low-level tests cover corner cases that are not + # encountered by the high-level module, thus they + # mostly shouldn't matter as much. + + # Additional tests are found in Lib/test/test__interpchannels.py. + # XXX Those should be either moved to LowLevelTests or eliminated + # in favor of high-level tests in this file. + + def test_highlevel_reloaded(self): + # See gh-115490 (https://github.com/python/cpython/issues/115490). + importlib.reload(channels) + + +class TestChannels(TestBase): + + def test_create(self): + r, s = channels.create() + self.assertIsInstance(r, channels.RecvChannel) + self.assertIsInstance(s, channels.SendChannel) + + def test_list_all(self): + self.assertEqual(channels.list_all(), []) + created = set() + for _ in range(3): + ch = channels.create() + created.add(ch) + after = set(channels.list_all()) + self.assertEqual(after, created) + + def test_list_all_closed(self): + created = [channels.create() for _ in range(3)] + rch, sch = created.pop(1) + rch.close() + self.assertEqual(set(channels.list_all()), set(created)) + + def test_shareable(self): + interp = interpreters.create() + rch, sch = channels.create() + + self.assertTrue( + interpreters.is_shareable(rch)) + self.assertTrue( + interpreters.is_shareable(sch)) + + sch.send_nowait(rch) + sch.send_nowait(sch) + rch2 = rch.recv() + sch2 = rch.recv() + + interp.prepare_main(rch=rch, sch=sch) + sch.send_nowait(rch) + sch.send_nowait(sch) + interp.exec(dedent(""" + rch2 = rch.recv() + sch2 = rch.recv() + assert rch2 == rch + assert sch2 == sch + + sch.send_nowait(rch2) + sch.send_nowait(sch2) + """)) + rch3 = rch.recv() + sch3 = rch.recv() + + self.assertEqual(rch2, rch) + self.assertEqual(sch2, sch) + self.assertEqual(rch3, rch) + self.assertEqual(sch3, sch) + + def test_is_closed(self): + rch, sch = channels.create() + rbefore = rch.is_closed + sbefore = sch.is_closed + rch.close() + rafter = rch.is_closed + safter = sch.is_closed + + self.assertFalse(rbefore) + self.assertFalse(sbefore) + self.assertTrue(rafter) + self.assertTrue(safter) + + +class TestRecvChannelAttrs(TestBase): + + def test_id_type(self): + rch, _ = channels.create() + self.assertIsInstance(rch.id, _channels.ChannelID) + + def test_custom_id(self): + rch = channels.RecvChannel(1) + self.assertEqual(rch.id, 1) + + with self.assertRaises(TypeError): + channels.RecvChannel('1') + + def test_id_readonly(self): + rch = channels.RecvChannel(1) + with self.assertRaises(AttributeError): + rch.id = 2 + + def test_equality(self): + ch1, _ = channels.create() + ch2, _ = channels.create() + self.assertEqual(ch1, ch1) + self.assertNotEqual(ch1, ch2) + + def test_pickle(self): + ch, _ = channels.create() + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=protocol): + data = pickle.dumps(ch, protocol) + unpickled = pickle.loads(data) + self.assertEqual(unpickled, ch) + + +class TestSendChannelAttrs(TestBase): + + def test_id_type(self): + _, sch = channels.create() + self.assertIsInstance(sch.id, _channels.ChannelID) + + def test_custom_id(self): + sch = channels.SendChannel(1) + self.assertEqual(sch.id, 1) + + with self.assertRaises(TypeError): + channels.SendChannel('1') + + def test_id_readonly(self): + sch = channels.SendChannel(1) + with self.assertRaises(AttributeError): + sch.id = 2 + + def test_equality(self): + _, ch1 = channels.create() + _, ch2 = channels.create() + self.assertEqual(ch1, ch1) + self.assertNotEqual(ch1, ch2) + + def test_pickle(self): + _, ch = channels.create() + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=protocol): + data = pickle.dumps(ch, protocol) + unpickled = pickle.loads(data) + self.assertEqual(unpickled, ch) + + +class TestSendRecv(TestBase): + + def test_send_recv_main(self): + r, s = channels.create() + orig = b'spam' + s.send_nowait(orig) + obj = r.recv() + + self.assertEqual(obj, orig) + self.assertIsNot(obj, orig) + + def test_send_recv_same_interpreter(self): + interp = interpreters.create() + interp.exec(dedent(""" + from test.support import channels + r, s = channels.create() + orig = b'spam' + s.send_nowait(orig) + obj = r.recv() + assert obj == orig, 'expected: obj == orig' + assert obj is not orig, 'expected: obj is not orig' + """)) + + @unittest.skip('broken (see BPO-...)') + def test_send_recv_different_interpreters(self): + r1, s1 = channels.create() + r2, s2 = channels.create() + orig1 = b'spam' + s1.send_nowait(orig1) + out = _run_output( + interpreters.create(), + dedent(f""" + obj1 = r.recv() + assert obj1 == b'spam', 'expected: obj1 == orig1' + # When going to another interpreter we get a copy. + assert id(obj1) != {id(orig1)}, 'expected: obj1 is not orig1' + orig2 = b'eggs' + print(id(orig2)) + s.send_nowait(orig2) + """), + channels=dict(r=r1, s=s2), + ) + obj2 = r2.recv() + + self.assertEqual(obj2, b'eggs') + self.assertNotEqual(id(obj2), int(out)) + + def test_send_recv_different_threads(self): + r, s = channels.create() + + def f(): + while True: + try: + obj = r.recv() + break + except channels.ChannelEmptyError: + time.sleep(0.1) + s.send(obj) + t = threading.Thread(target=f) + t.start() + + orig = b'spam' + s.send(orig) + obj = r.recv() + t.join() + + self.assertEqual(obj, orig) + self.assertIsNot(obj, orig) + + def test_send_recv_nowait_main(self): + r, s = channels.create() + orig = b'spam' + s.send_nowait(orig) + obj = r.recv_nowait() + + self.assertEqual(obj, orig) + self.assertIsNot(obj, orig) + + def test_send_recv_nowait_main_with_default(self): + r, _ = channels.create() + obj = r.recv_nowait(None) + + self.assertIsNone(obj) + + def test_send_recv_nowait_same_interpreter(self): + interp = interpreters.create() + interp.exec(dedent(""" + from test.support import channels + r, s = channels.create() + orig = b'spam' + s.send_nowait(orig) + obj = r.recv_nowait() + assert obj == orig, 'expected: obj == orig' + # When going back to the same interpreter we get the same object. + assert obj is not orig, 'expected: obj is not orig' + """)) + + @unittest.skip('broken (see BPO-...)') + def test_send_recv_nowait_different_interpreters(self): + r1, s1 = channels.create() + r2, s2 = channels.create() + orig1 = b'spam' + s1.send_nowait(orig1) + out = _run_output( + interpreters.create(), + dedent(f""" + obj1 = r.recv_nowait() + assert obj1 == b'spam', 'expected: obj1 == orig1' + # When going to another interpreter we get a copy. + assert id(obj1) != {id(orig1)}, 'expected: obj1 is not orig1' + orig2 = b'eggs' + print(id(orig2)) + s.send_nowait(orig2) + """), + channels=dict(r=r1, s=s2), + ) + obj2 = r2.recv_nowait() + + self.assertEqual(obj2, b'eggs') + self.assertNotEqual(id(obj2), int(out)) + + def test_recv_timeout(self): + r, _ = channels.create() + with self.assertRaises(TimeoutError): + r.recv(timeout=1) + + def test_recv_channel_does_not_exist(self): + ch = channels.RecvChannel(1_000_000) + with self.assertRaises(channels.ChannelNotFoundError): + ch.recv() + + def test_send_channel_does_not_exist(self): + ch = channels.SendChannel(1_000_000) + with self.assertRaises(channels.ChannelNotFoundError): + ch.send(b'spam') + + def test_recv_nowait_channel_does_not_exist(self): + ch = channels.RecvChannel(1_000_000) + with self.assertRaises(channels.ChannelNotFoundError): + ch.recv_nowait() + + def test_send_nowait_channel_does_not_exist(self): + ch = channels.SendChannel(1_000_000) + with self.assertRaises(channels.ChannelNotFoundError): + ch.send_nowait(b'spam') + + def test_recv_nowait_empty(self): + ch, _ = channels.create() + with self.assertRaises(channels.ChannelEmptyError): + ch.recv_nowait() + + def test_recv_nowait_default(self): + default = object() + rch, sch = channels.create() + obj1 = rch.recv_nowait(default) + sch.send_nowait(None) + sch.send_nowait(1) + sch.send_nowait(b'spam') + sch.send_nowait(b'eggs') + obj2 = rch.recv_nowait(default) + obj3 = rch.recv_nowait(default) + obj4 = rch.recv_nowait() + obj5 = rch.recv_nowait(default) + obj6 = rch.recv_nowait(default) + + self.assertIs(obj1, default) + self.assertIs(obj2, None) + self.assertEqual(obj3, 1) + self.assertEqual(obj4, b'spam') + self.assertEqual(obj5, b'eggs') + self.assertIs(obj6, default) + + def test_send_buffer(self): + buf = bytearray(b'spamspamspam') + obj = None + rch, sch = channels.create() + + def f(): + nonlocal obj + while True: + try: + obj = rch.recv() + break + except channels.ChannelEmptyError: + time.sleep(0.1) + t = threading.Thread(target=f) + t.start() + + sch.send_buffer(buf) + t.join() + + self.assertIsNot(obj, buf) + self.assertIsInstance(obj, memoryview) + self.assertEqual(obj, buf) + + buf[4:8] = b'eggs' + self.assertEqual(obj, buf) + obj[4:8] = b'ham.' + self.assertEqual(obj, buf) + + def test_send_buffer_nowait(self): + buf = bytearray(b'spamspamspam') + rch, sch = channels.create() + sch.send_buffer_nowait(buf) + obj = rch.recv() + + self.assertIsNot(obj, buf) + self.assertIsInstance(obj, memoryview) + self.assertEqual(obj, buf) + + buf[4:8] = b'eggs' + self.assertEqual(obj, buf) + obj[4:8] = b'ham.' + self.assertEqual(obj, buf) + + def test_send_cleared_with_subinterpreter(self): + def common(rch, sch, unbound=None, presize=0): + if not unbound: + extraargs = '' + elif unbound is channels.UNBOUND: + extraargs = ', unbounditems=channels.UNBOUND' + elif unbound is channels.UNBOUND_ERROR: + extraargs = ', unbounditems=channels.UNBOUND_ERROR' + elif unbound is channels.UNBOUND_REMOVE: + extraargs = ', unbounditems=channels.UNBOUND_REMOVE' + else: + raise NotImplementedError(repr(unbound)) + interp = interpreters.create() + + _run_output(interp, dedent(f""" + from test.support import channels + sch = channels.SendChannel({sch.id}) + obj1 = b'spam' + obj2 = b'eggs' + sch.send_nowait(obj1{extraargs}) + sch.send_nowait(obj2{extraargs}) + """)) + self.assertEqual( + _channels.get_count(rch.id), + presize + 2, + ) + + if presize == 0: + obj1 = rch.recv() + self.assertEqual(obj1, b'spam') + self.assertEqual( + _channels.get_count(rch.id), + presize + 1, + ) + + return interp + + with self.subTest('default'): # UNBOUND + rch, sch = channels.create() + interp = common(rch, sch) + del interp + self.assertEqual(_channels.get_count(rch.id), 1) + obj1 = rch.recv() + self.assertEqual(_channels.get_count(rch.id), 0) + self.assertIs(obj1, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 0) + with self.assertRaises(channels.ChannelEmptyError): + rch.recv_nowait() + + with self.subTest('UNBOUND'): + rch, sch = channels.create() + interp = common(rch, sch, channels.UNBOUND) + del interp + self.assertEqual(_channels.get_count(rch.id), 1) + obj1 = rch.recv() + self.assertIs(obj1, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 0) + with self.assertRaises(channels.ChannelEmptyError): + rch.recv_nowait() + + with self.subTest('UNBOUND_ERROR'): + rch, sch = channels.create() + interp = common(rch, sch, channels.UNBOUND_ERROR) + + del interp + self.assertEqual(_channels.get_count(rch.id), 1) + with self.assertRaises(channels.ItemInterpreterDestroyed): + rch.recv() + + self.assertEqual(_channels.get_count(rch.id), 0) + with self.assertRaises(channels.ChannelEmptyError): + rch.recv_nowait() + + with self.subTest('UNBOUND_REMOVE'): + rch, sch = channels.create() + + interp = common(rch, sch, channels.UNBOUND_REMOVE) + del interp + self.assertEqual(_channels.get_count(rch.id), 0) + with self.assertRaises(channels.ChannelEmptyError): + rch.recv_nowait() + + sch.send_nowait(b'ham', unbounditems=channels.UNBOUND_REMOVE) + self.assertEqual(_channels.get_count(rch.id), 1) + interp = common(rch, sch, channels.UNBOUND_REMOVE, 1) + self.assertEqual(_channels.get_count(rch.id), 3) + sch.send_nowait(42, unbounditems=channels.UNBOUND_REMOVE) + self.assertEqual(_channels.get_count(rch.id), 4) + del interp + self.assertEqual(_channels.get_count(rch.id), 2) + obj1 = rch.recv() + obj2 = rch.recv() + self.assertEqual(obj1, b'ham') + self.assertEqual(obj2, 42) + self.assertEqual(_channels.get_count(rch.id), 0) + with self.assertRaises(channels.ChannelEmptyError): + rch.recv_nowait() + + def test_send_cleared_with_subinterpreter_mixed(self): + rch, sch = channels.create() + interp = interpreters.create() + + # If we don't associate the main interpreter with the channel + # then the channel will be automatically closed when interp + # is destroyed. + sch.send_nowait(None) + rch.recv() + self.assertEqual(_channels.get_count(rch.id), 0) + + _run_output(interp, dedent(f""" + from test.support import channels + sch = channels.SendChannel({sch.id}) + sch.send_nowait(1, unbounditems=channels.UNBOUND) + sch.send_nowait(2, unbounditems=channels.UNBOUND_ERROR) + sch.send_nowait(3) + sch.send_nowait(4, unbounditems=channels.UNBOUND_REMOVE) + sch.send_nowait(5, unbounditems=channels.UNBOUND) + """)) + self.assertEqual(_channels.get_count(rch.id), 5) + + del interp + self.assertEqual(_channels.get_count(rch.id), 4) + + obj1 = rch.recv() + self.assertIs(obj1, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 3) + + with self.assertRaises(channels.ItemInterpreterDestroyed): + rch.recv() + self.assertEqual(_channels.get_count(rch.id), 2) + + obj2 = rch.recv() + self.assertIs(obj2, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 1) + + obj3 = rch.recv() + self.assertIs(obj3, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 0) + + def test_send_cleared_with_subinterpreter_multiple(self): + rch, sch = channels.create() + interp1 = interpreters.create() + interp2 = interpreters.create() + + sch.send_nowait(1) + _run_output(interp1, dedent(f""" + from test.support import channels + rch = channels.RecvChannel({rch.id}) + sch = channels.SendChannel({sch.id}) + obj1 = rch.recv() + sch.send_nowait(2, unbounditems=channels.UNBOUND) + sch.send_nowait(obj1, unbounditems=channels.UNBOUND_REMOVE) + """)) + _run_output(interp2, dedent(f""" + from test.support import channels + rch = channels.RecvChannel({rch.id}) + sch = channels.SendChannel({sch.id}) + obj2 = rch.recv() + obj1 = rch.recv() + """)) + self.assertEqual(_channels.get_count(rch.id), 0) + sch.send_nowait(3) + _run_output(interp1, dedent(""" + sch.send_nowait(4, unbounditems=channels.UNBOUND) + # interp closed here + sch.send_nowait(5, unbounditems=channels.UNBOUND_REMOVE) + sch.send_nowait(6, unbounditems=channels.UNBOUND) + """)) + _run_output(interp2, dedent(""" + sch.send_nowait(7, unbounditems=channels.UNBOUND_ERROR) + # interp closed here + sch.send_nowait(obj1, unbounditems=channels.UNBOUND_ERROR) + sch.send_nowait(obj2, unbounditems=channels.UNBOUND_REMOVE) + sch.send_nowait(8, unbounditems=channels.UNBOUND) + """)) + _run_output(interp1, dedent(""" + sch.send_nowait(9, unbounditems=channels.UNBOUND_REMOVE) + sch.send_nowait(10, unbounditems=channels.UNBOUND) + """)) + self.assertEqual(_channels.get_count(rch.id), 10) + + obj3 = rch.recv() + self.assertEqual(obj3, 3) + self.assertEqual(_channels.get_count(rch.id), 9) + + obj4 = rch.recv() + self.assertEqual(obj4, 4) + self.assertEqual(_channels.get_count(rch.id), 8) + + del interp1 + self.assertEqual(_channels.get_count(rch.id), 6) + + # obj5 was removed + + obj6 = rch.recv() + self.assertIs(obj6, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 5) + + obj7 = rch.recv() + self.assertEqual(obj7, 7) + self.assertEqual(_channels.get_count(rch.id), 4) + + del interp2 + self.assertEqual(_channels.get_count(rch.id), 3) + + # obj1 + with self.assertRaises(channels.ItemInterpreterDestroyed): + rch.recv() + self.assertEqual(_channels.get_count(rch.id), 2) + + # obj2 was removed + + obj8 = rch.recv() + self.assertIs(obj8, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 1) + + # obj9 was removed + + obj10 = rch.recv() + self.assertIs(obj10, channels.UNBOUND) + self.assertEqual(_channels.get_count(rch.id), 0) + + +if __name__ == '__main__': + # Test needs to be a package, so we can do relative imports. + unittest.main() diff --git a/Lib/test/test_interpreters/test_lifecycle.py b/Lib/test/test_interpreters/test_lifecycle.py new file mode 100644 index 00000000000..39c1441b67c --- /dev/null +++ b/Lib/test/test_interpreters/test_lifecycle.py @@ -0,0 +1,194 @@ +import contextlib +import json +import os +import os.path +import sys +from textwrap import dedent +import unittest + +from test import support +from test.support import import_helper +from test.support import os_helper +# Raise SkipTest if subinterpreters not supported. +import_helper.import_module('_interpreters') +from .utils import TestBase + + +class StartupTests(TestBase): + + # We want to ensure the initial state of subinterpreters + # matches expectations. + + _subtest_count = 0 + + @contextlib.contextmanager + def subTest(self, *args): + with super().subTest(*args) as ctx: + self._subtest_count += 1 + try: + yield ctx + finally: + if self._debugged_in_subtest: + if self._subtest_count == 1: + # The first subtest adds a leading newline, so we + # compensate here by not printing a trailing newline. + print('### end subtest debug ###', end='') + else: + print('### end subtest debug ###') + self._debugged_in_subtest = False + + def debug(self, msg, *, header=None): + if header: + self._debug(f'--- {header} ---') + if msg: + if msg.endswith(os.linesep): + self._debug(msg[:-len(os.linesep)]) + else: + self._debug(msg) + self._debug('') + self._debug('------') + else: + self._debug(msg) + + _debugged = False + _debugged_in_subtest = False + def _debug(self, msg): + if not self._debugged: + print() + self._debugged = True + if self._subtest is not None: + if True: + if not self._debugged_in_subtest: + self._debugged_in_subtest = True + print('### start subtest debug ###') + print(msg) + else: + print(msg) + + def create_temp_dir(self): + import tempfile + tmp = tempfile.mkdtemp(prefix='test_interpreters_') + tmp = os.path.realpath(tmp) + self.addCleanup(os_helper.rmtree, tmp) + return tmp + + def write_script(self, *path, text): + filename = os.path.join(*path) + dirname = os.path.dirname(filename) + if dirname: + os.makedirs(dirname, exist_ok=True) + with open(filename, 'w', encoding='utf-8') as outfile: + outfile.write(dedent(text)) + return filename + + @support.requires_subprocess() + def run_python(self, argv, *, cwd=None): + # This method is inspired by + # EmbeddingTestsMixin.run_embedded_interpreter() in test_embed.py. + import shlex + import subprocess + if isinstance(argv, str): + argv = shlex.split(argv) + argv = [sys.executable, *argv] + try: + proc = subprocess.run( + argv, + cwd=cwd, + capture_output=True, + text=True, + ) + except Exception as exc: + self.debug(f'# cmd: {shlex.join(argv)}') + if isinstance(exc, FileNotFoundError) and not exc.filename: + if os.path.exists(argv[0]): + exists = 'exists' + else: + exists = 'does not exist' + self.debug(f'{argv[0]} {exists}') + raise # re-raise + assert proc.stderr == '' or proc.returncode != 0, proc.stderr + if proc.returncode != 0 and support.verbose: + self.debug(f'# python3 {shlex.join(argv[1:])} failed:') + self.debug(proc.stdout, header='stdout') + self.debug(proc.stderr, header='stderr') + self.assertEqual(proc.returncode, 0) + self.assertEqual(proc.stderr, '') + return proc.stdout + + def test_sys_path_0(self): + # The main interpreter's sys.path[0] should be used by subinterpreters. + script = ''' + import sys + from concurrent import interpreters + + orig = sys.path[0] + + interp = interpreters.create() + interp.exec(f"""if True: + import json + import sys + print(json.dumps({{ + 'main': {orig!r}, + 'sub': sys.path[0], + }}, indent=4), flush=True) + """) + interp.close() + ''' + # / + # pkg/ + # __init__.py + # __main__.py + # script.py + # script.py + cwd = self.create_temp_dir() + self.write_script(cwd, 'pkg', '__init__.py', text='') + self.write_script(cwd, 'pkg', '__main__.py', text=script) + self.write_script(cwd, 'pkg', 'script.py', text=script) + self.write_script(cwd, 'script.py', text=script) + + cases = [ + ('script.py', cwd), + ('-m script', cwd), + ('-m pkg', cwd), + ('-m pkg.script', cwd), + ('-c "import script"', ''), + ] + for argv, expected in cases: + with self.subTest(f'python3 {argv}'): + out = self.run_python(argv, cwd=cwd) + data = json.loads(out) + sp0_main, sp0_sub = data['main'], data['sub'] + self.assertEqual(sp0_sub, sp0_main) + self.assertEqual(sp0_sub, expected) + # XXX Also check them all with the -P cmdline flag? + + +class FinalizationTests(TestBase): + + @support.requires_subprocess() + def test_gh_109793(self): + # Make sure finalization finishes and the correct error code + # is reported, even when subinterpreters get cleaned up at the end. + import subprocess + argv = [sys.executable, '-c', '''if True: + from concurrent import interpreters + interp = interpreters.create() + try: + raise Exception + finally: + interp.close() + '''] + proc = subprocess.run(argv, capture_output=True, text=True) + self.assertIn('Traceback', proc.stderr) + if proc.returncode == 0 and support.verbose: + print() + print("--- cmd unexpected succeeded ---") + print(f"stdout:\n{proc.stdout}") + print(f"stderr:\n{proc.stderr}") + print("------") + self.assertEqual(proc.returncode, 1) + + +if __name__ == '__main__': + # Test needs to be a package, so we can do relative imports. + unittest.main() diff --git a/Lib/test/test_interpreters/test_queues.py b/Lib/test/test_interpreters/test_queues.py new file mode 100644 index 00000000000..baa772b3b36 --- /dev/null +++ b/Lib/test/test_interpreters/test_queues.py @@ -0,0 +1,682 @@ +import importlib +import pickle +import threading +from textwrap import dedent +import time +import unittest +from unittest import mock + +from test.support import import_helper, Py_DEBUG +# Raise SkipTest if subinterpreters not supported. +_queues = import_helper.import_module('_interpqueues') +from concurrent import interpreters +from concurrent.interpreters import _queues as queues, _crossinterp +from .utils import _run_output, TestBase as _TestBase + +HUGE_TIMEOUT = 3600 +REPLACE = _crossinterp._UNBOUND_CONSTANT_TO_FLAG[_crossinterp.UNBOUND] + + +def get_num_queues(): + return len(_queues.list_all()) + + +class TestBase(_TestBase): + def tearDown(self): + for qid, _, _ in _queues.list_all(): + try: + _queues.destroy(qid) + except Exception: + pass + + +class LowLevelTests(TestBase): + + # The behaviors in the low-level module are important in as much + # as they are exercised by the high-level module. Therefore the + # most important testing happens in the high-level tests. + # These low-level tests cover corner cases that are not + # encountered by the high-level module, thus they + # mostly shouldn't matter as much. + + def test_highlevel_reloaded(self): + # See gh-115490 (https://github.com/python/cpython/issues/115490). + importlib.reload(queues) + + def test_create_destroy(self): + qid = _queues.create(2, REPLACE, -1) + _queues.destroy(qid) + self.assertEqual(get_num_queues(), 0) + with self.assertRaises(queues.QueueNotFoundError): + _queues.get(qid) + with self.assertRaises(queues.QueueNotFoundError): + _queues.destroy(qid) + + def test_not_destroyed(self): + # It should have cleaned up any remaining queues. + stdout, stderr = self.assert_python_ok( + '-c', + dedent(f""" + import {_queues.__name__} as _queues + _queues.create(2, {REPLACE}, -1) + """), + ) + self.assertEqual(stdout, '') + if Py_DEBUG: + self.assertNotEqual(stderr, '') + else: + self.assertEqual(stderr, '') + + def test_bind_release(self): + with self.subTest('typical'): + qid = _queues.create(2, REPLACE, -1) + _queues.bind(qid) + _queues.release(qid) + self.assertEqual(get_num_queues(), 0) + + with self.subTest('bind too much'): + qid = _queues.create(2, REPLACE, -1) + _queues.bind(qid) + _queues.bind(qid) + _queues.release(qid) + _queues.destroy(qid) + self.assertEqual(get_num_queues(), 0) + + with self.subTest('nested'): + qid = _queues.create(2, REPLACE, -1) + _queues.bind(qid) + _queues.bind(qid) + _queues.release(qid) + _queues.release(qid) + self.assertEqual(get_num_queues(), 0) + + with self.subTest('release without binding'): + qid = _queues.create(2, REPLACE, -1) + with self.assertRaises(queues.QueueError): + _queues.release(qid) + + +class QueueTests(TestBase): + + def test_create(self): + with self.subTest('vanilla'): + queue = queues.create() + self.assertEqual(queue.maxsize, 0) + + with self.subTest('small maxsize'): + queue = queues.create(3) + self.assertEqual(queue.maxsize, 3) + + with self.subTest('big maxsize'): + queue = queues.create(100) + self.assertEqual(queue.maxsize, 100) + + with self.subTest('no maxsize'): + queue = queues.create(0) + self.assertEqual(queue.maxsize, 0) + + with self.subTest('negative maxsize'): + queue = queues.create(-10) + self.assertEqual(queue.maxsize, -10) + + with self.subTest('bad maxsize'): + with self.assertRaises(TypeError): + queues.create('1') + + def test_shareable(self): + queue1 = queues.create() + + interp = interpreters.create() + interp.exec(dedent(f""" + from concurrent.interpreters import _queues as queues + queue1 = queues.Queue({queue1.id}) + """)); + + with self.subTest('same interpreter'): + queue2 = queues.create() + queue1.put(queue2) + queue3 = queue1.get() + self.assertIs(queue3, queue2) + + with self.subTest('from current interpreter'): + queue4 = queues.create() + queue1.put(queue4) + out = _run_output(interp, dedent(""" + queue4 = queue1.get() + print(queue4.id) + """)) + qid = int(out) + self.assertEqual(qid, queue4.id) + + with self.subTest('from subinterpreter'): + out = _run_output(interp, dedent(""" + queue5 = queues.create() + queue1.put(queue5) + print(queue5.id) + """)) + qid = int(out) + queue5 = queue1.get() + self.assertEqual(queue5.id, qid) + + def test_id_type(self): + queue = queues.create() + self.assertIsInstance(queue.id, int) + + def test_custom_id(self): + with self.assertRaises(queues.QueueNotFoundError): + queues.Queue(1_000_000) + + def test_id_readonly(self): + queue = queues.create() + with self.assertRaises(AttributeError): + queue.id = 1_000_000 + + def test_maxsize_readonly(self): + queue = queues.create(10) + with self.assertRaises(AttributeError): + queue.maxsize = 1_000_000 + + def test_hashable(self): + queue = queues.create() + expected = hash(queue.id) + actual = hash(queue) + self.assertEqual(actual, expected) + + def test_equality(self): + queue1 = queues.create() + queue2 = queues.create() + self.assertEqual(queue1, queue1) + self.assertNotEqual(queue1, queue2) + + def test_pickle(self): + queue = queues.create() + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=protocol): + data = pickle.dumps(queue, protocol) + unpickled = pickle.loads(data) + self.assertEqual(unpickled, queue) + + +class TestQueueOps(TestBase): + + def test_empty(self): + queue = queues.create() + before = queue.empty() + queue.put(None) + during = queue.empty() + queue.get() + after = queue.empty() + + self.assertIs(before, True) + self.assertIs(during, False) + self.assertIs(after, True) + + def test_full(self): + for maxsize in [1, 3, 11]: + with self.subTest(f'maxsize={maxsize}'): + num_to_add = maxsize + expected = [False] * (num_to_add * 2 + 3) + expected[maxsize] = True + expected[maxsize + 1] = True + + queue = queues.create(maxsize) + actual = [] + empty = [queue.empty()] + + for _ in range(num_to_add): + actual.append(queue.full()) + queue.put_nowait(None) + actual.append(queue.full()) + with self.assertRaises(queues.QueueFull): + queue.put_nowait(None) + empty.append(queue.empty()) + + for _ in range(num_to_add): + actual.append(queue.full()) + queue.get_nowait() + actual.append(queue.full()) + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + actual.append(queue.full()) + empty.append(queue.empty()) + + self.assertEqual(actual, expected) + self.assertEqual(empty, [True, False, True]) + + # no max size + for args in [(), (0,), (-1,), (-10,)]: + with self.subTest(f'maxsize={args[0]}' if args else ''): + num_to_add = 13 + expected = [False] * (num_to_add * 2 + 3) + + queue = queues.create(*args) + actual = [] + empty = [queue.empty()] + + for _ in range(num_to_add): + actual.append(queue.full()) + queue.put_nowait(None) + actual.append(queue.full()) + empty.append(queue.empty()) + + for _ in range(num_to_add): + actual.append(queue.full()) + queue.get_nowait() + actual.append(queue.full()) + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + actual.append(queue.full()) + empty.append(queue.empty()) + + self.assertEqual(actual, expected) + self.assertEqual(empty, [True, False, True]) + + def test_qsize(self): + expected = [0, 1, 2, 3, 2, 3, 2, 1, 0, 1, 0] + actual = [] + queue = queues.create() + for _ in range(3): + actual.append(queue.qsize()) + queue.put(None) + actual.append(queue.qsize()) + queue.get() + actual.append(queue.qsize()) + queue.put(None) + actual.append(queue.qsize()) + for _ in range(3): + queue.get() + actual.append(queue.qsize()) + queue.put(None) + actual.append(queue.qsize()) + queue.get() + actual.append(queue.qsize()) + + self.assertEqual(actual, expected) + + def test_put_get_main(self): + expected = list(range(20)) + queue = queues.create() + for i in range(20): + queue.put(i) + actual = [queue.get() for _ in range(20)] + + self.assertEqual(actual, expected) + + def test_put_timeout(self): + queue = queues.create(2) + queue.put(None) + queue.put(None) + with self.assertRaises(queues.QueueFull): + queue.put(None, timeout=0.1) + with self.assertRaises(queues.QueueFull): + queue.put(None, HUGE_TIMEOUT, 0.1) + queue.get() + queue.put(None) + + def test_put_nowait(self): + queue = queues.create(2) + queue.put_nowait(None) + queue.put_nowait(None) + with self.assertRaises(queues.QueueFull): + queue.put_nowait(None) + with self.assertRaises(queues.QueueFull): + queue.put(None, False) + with self.assertRaises(queues.QueueFull): + queue.put(None, False, timeout=HUGE_TIMEOUT) + queue.get() + queue.put_nowait(None) + + def test_put_full_fallback(self): + for obj in [ + None, + True, + 10, + 'spam', + b'spam', + (0, 'a'), + # not shareable + [1, 2, 3], + {'a': 13, 'b': 17}, + ]: + with self.subTest(repr(obj)): + queue = queues.create() + + queue.put(obj) + obj2 = queue.get() + self.assertEqual(obj2, obj) + + queue.put(obj) + obj2 = queue.get_nowait() + self.assertEqual(obj2, obj) + + def test_get_timeout(self): + queue = queues.create() + with self.assertRaises(queues.QueueEmpty): + queue.get(timeout=0.1) + with self.assertRaises(queues.QueueEmpty): + queue.get(HUGE_TIMEOUT, 0.1) + + def test_timeout_uses_monotonic_clock(self): + # gh-153005: the deadline must be computed from the monotonic clock, + # since the wall clock can be adjusted while the call is blocked. + queue = queues.create(1) + with mock.patch.object(queues, 'time', wraps=time) as fake_time: + with self.assertRaises(queues.QueueEmpty): + queue.get(timeout=0) + queue.put(None) + with self.assertRaises(queues.QueueFull): + queue.put(None, timeout=0) + fake_time.monotonic.assert_called() + fake_time.time.assert_not_called() + + def test_get_nowait(self): + queue = queues.create() + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + with self.assertRaises(queues.QueueEmpty): + queue.get(False) + with self.assertRaises(queues.QueueEmpty): + queue.get(False, timeout=HUGE_TIMEOUT) + + def test_put_get_full_fallback(self): + expected = list(range(20)) + queue = queues.create() + for methname in ('get', 'get_nowait'): + with self.subTest(f'{methname}()'): + get = getattr(queue, methname) + + for i in range(20): + queue.put(i) + actual = [get() for _ in range(20)] + self.assertEqual(actual, expected) + + obj = [1, 2, 3] # lists are not shareable + queue.put(obj) + obj2 = get() + self.assertEqual(obj, obj2) + self.assertIsNot(obj, obj2) + + def test_put_get_same_interpreter(self): + interp = interpreters.create() + interp.exec(dedent(""" + from concurrent.interpreters import _queues as queues + queue = queues.create() + """)) + for methname in ('get', 'get_nowait'): + with self.subTest(f'{methname}()'): + interp.exec(dedent(f""" + orig = b'spam' + queue.put(orig) + obj = queue.{methname}() + assert obj == orig, 'expected: obj == orig' + assert obj is not orig, 'expected: obj is not orig' + """)) + + def test_put_get_different_interpreters(self): + interp = interpreters.create() + queue1 = queues.create() + queue2 = queues.create() + self.assertEqual(len(queues.list_all()), 2) + + for methname in ('get', 'get_nowait'): + with self.subTest(f'{methname}()'): + obj1 = b'spam' + queue1.put(obj1) + + out = _run_output( + interp, + dedent(f""" + from concurrent.interpreters import _queues as queues + queue1 = queues.Queue({queue1.id}) + queue2 = queues.Queue({queue2.id}) + assert queue1.qsize() == 1, 'expected: queue1.qsize() == 1' + obj = queue1.{methname}() + assert queue1.qsize() == 0, 'expected: queue1.qsize() == 0' + assert obj == b'spam', 'expected: obj == obj1' + # When going to another interpreter we get a copy. + assert id(obj) != {id(obj1)}, 'expected: obj is not obj1' + obj2 = b'eggs' + print(id(obj2)) + assert queue2.qsize() == 0, 'expected: queue2.qsize() == 0' + queue2.put(obj2) + assert queue2.qsize() == 1, 'expected: queue2.qsize() == 1' + """)) + self.assertEqual(len(queues.list_all()), 2) + self.assertEqual(queue1.qsize(), 0) + self.assertEqual(queue2.qsize(), 1) + + get = getattr(queue2, methname) + obj2 = get() + self.assertEqual(obj2, b'eggs') + self.assertNotEqual(id(obj2), int(out)) + + def test_put_cleared_with_subinterpreter(self): + def common(queue, unbound=None, presize=0): + if not unbound: + extraargs = '' + elif unbound is queues.UNBOUND: + extraargs = ', unbounditems=queues.UNBOUND' + elif unbound is queues.UNBOUND_ERROR: + extraargs = ', unbounditems=queues.UNBOUND_ERROR' + elif unbound is queues.UNBOUND_REMOVE: + extraargs = ', unbounditems=queues.UNBOUND_REMOVE' + else: + raise NotImplementedError(repr(unbound)) + interp = interpreters.create() + + _run_output(interp, dedent(f""" + from concurrent.interpreters import _queues as queues + queue = queues.Queue({queue.id}) + obj1 = b'spam' + obj2 = b'eggs' + queue.put(obj1{extraargs}) + queue.put(obj2{extraargs}) + """)) + self.assertEqual(queue.qsize(), presize + 2) + + if presize == 0: + obj1 = queue.get() + self.assertEqual(obj1, b'spam') + self.assertEqual(queue.qsize(), presize + 1) + + return interp + + with self.subTest('default'): # UNBOUND + queue = queues.create() + interp = common(queue) + del interp + obj1 = queue.get() + self.assertIs(obj1, queues.UNBOUND) + self.assertEqual(queue.qsize(), 0) + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + + with self.subTest('UNBOUND'): + queue = queues.create() + interp = common(queue, queues.UNBOUND) + del interp + obj1 = queue.get() + self.assertIs(obj1, queues.UNBOUND) + self.assertEqual(queue.qsize(), 0) + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + + with self.subTest('UNBOUND_ERROR'): + queue = queues.create() + interp = common(queue, queues.UNBOUND_ERROR) + + del interp + self.assertEqual(queue.qsize(), 1) + with self.assertRaises(queues.ItemInterpreterDestroyed): + queue.get() + + self.assertEqual(queue.qsize(), 0) + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + + with self.subTest('UNBOUND_REMOVE'): + queue = queues.create() + + interp = common(queue, queues.UNBOUND_REMOVE) + del interp + self.assertEqual(queue.qsize(), 0) + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + + queue.put(b'ham', unbounditems=queues.UNBOUND_REMOVE) + self.assertEqual(queue.qsize(), 1) + interp = common(queue, queues.UNBOUND_REMOVE, 1) + self.assertEqual(queue.qsize(), 3) + queue.put(42, unbounditems=queues.UNBOUND_REMOVE) + self.assertEqual(queue.qsize(), 4) + del interp + self.assertEqual(queue.qsize(), 2) + obj1 = queue.get() + obj2 = queue.get() + self.assertEqual(obj1, b'ham') + self.assertEqual(obj2, 42) + self.assertEqual(queue.qsize(), 0) + with self.assertRaises(queues.QueueEmpty): + queue.get_nowait() + + def test_put_cleared_with_subinterpreter_mixed(self): + queue = queues.create() + interp = interpreters.create() + _run_output(interp, dedent(f""" + from concurrent.interpreters import _queues as queues + queue = queues.Queue({queue.id}) + queue.put(1, unbounditems=queues.UNBOUND) + queue.put(2, unbounditems=queues.UNBOUND_ERROR) + queue.put(3) + queue.put(4, unbounditems=queues.UNBOUND_REMOVE) + queue.put(5, unbounditems=queues.UNBOUND) + """)) + self.assertEqual(queue.qsize(), 5) + + del interp + self.assertEqual(queue.qsize(), 4) + + obj1 = queue.get() + self.assertIs(obj1, queues.UNBOUND) + self.assertEqual(queue.qsize(), 3) + + with self.assertRaises(queues.ItemInterpreterDestroyed): + queue.get() + self.assertEqual(queue.qsize(), 2) + + obj2 = queue.get() + self.assertIs(obj2, queues.UNBOUND) + self.assertEqual(queue.qsize(), 1) + + obj3 = queue.get() + self.assertIs(obj3, queues.UNBOUND) + self.assertEqual(queue.qsize(), 0) + + def test_put_cleared_with_subinterpreter_multiple(self): + queue = queues.create() + interp1 = interpreters.create() + interp2 = interpreters.create() + + queue.put(1) + _run_output(interp1, dedent(f""" + from concurrent.interpreters import _queues as queues + queue = queues.Queue({queue.id}) + obj1 = queue.get() + queue.put(2, unbounditems=queues.UNBOUND) + queue.put(obj1, unbounditems=queues.UNBOUND_REMOVE) + """)) + _run_output(interp2, dedent(f""" + from concurrent.interpreters import _queues as queues + queue = queues.Queue({queue.id}) + obj2 = queue.get() + obj1 = queue.get() + """)) + self.assertEqual(queue.qsize(), 0) + queue.put(3) + _run_output(interp1, dedent(""" + queue.put(4, unbounditems=queues.UNBOUND) + # interp closed here + queue.put(5, unbounditems=queues.UNBOUND_REMOVE) + queue.put(6, unbounditems=queues.UNBOUND) + """)) + _run_output(interp2, dedent(""" + queue.put(7, unbounditems=queues.UNBOUND_ERROR) + # interp closed here + queue.put(obj1, unbounditems=queues.UNBOUND_ERROR) + queue.put(obj2, unbounditems=queues.UNBOUND_REMOVE) + queue.put(8, unbounditems=queues.UNBOUND) + """)) + _run_output(interp1, dedent(""" + queue.put(9, unbounditems=queues.UNBOUND_REMOVE) + queue.put(10, unbounditems=queues.UNBOUND) + """)) + self.assertEqual(queue.qsize(), 10) + + obj3 = queue.get() + self.assertEqual(obj3, 3) + self.assertEqual(queue.qsize(), 9) + + obj4 = queue.get() + self.assertEqual(obj4, 4) + self.assertEqual(queue.qsize(), 8) + + del interp1 + self.assertEqual(queue.qsize(), 6) + + # obj5 was removed + + obj6 = queue.get() + self.assertIs(obj6, queues.UNBOUND) + self.assertEqual(queue.qsize(), 5) + + obj7 = queue.get() + self.assertEqual(obj7, 7) + self.assertEqual(queue.qsize(), 4) + + del interp2 + self.assertEqual(queue.qsize(), 3) + + # obj1 + with self.assertRaises(queues.ItemInterpreterDestroyed): + queue.get() + self.assertEqual(queue.qsize(), 2) + + # obj2 was removed + + obj8 = queue.get() + self.assertIs(obj8, queues.UNBOUND) + self.assertEqual(queue.qsize(), 1) + + # obj9 was removed + + obj10 = queue.get() + self.assertIs(obj10, queues.UNBOUND) + self.assertEqual(queue.qsize(), 0) + + def test_put_get_different_threads(self): + queue1 = queues.create() + queue2 = queues.create() + + def f(): + while True: + try: + obj = queue1.get(timeout=0.1) + break + except queues.QueueEmpty: + continue + queue2.put(obj) + t = threading.Thread(target=f) + t.start() + + orig = b'spam' + queue1.put(orig) + obj = queue2.get() + t.join() + + self.assertEqual(obj, orig) + self.assertIsNot(obj, orig) + + +if __name__ == '__main__': + # Test needs to be a package, so we can do relative imports. + unittest.main() diff --git a/Lib/test/test_interpreters/test_stress.py b/Lib/test/test_interpreters/test_stress.py new file mode 100644 index 00000000000..50d2444a4c7 --- /dev/null +++ b/Lib/test/test_interpreters/test_stress.py @@ -0,0 +1,94 @@ +import threading +import unittest + +from test import support +from test.support import import_helper +from test.support import threading_helper +# Raise SkipTest if subinterpreters not supported. +_interpreters = import_helper.import_module('_interpreters') +from concurrent import interpreters +from concurrent.interpreters import InterpreterError +from .utils import TestBase + + +class StressTests(TestBase): + + # In these tests we generally want a lot of interpreters, + # but not so many that any test takes too long. + + @support.requires_resource('cpu') + def test_create_many_sequential(self): + alive = [] + for _ in range(100): + interp = interpreters.create() + alive.append(interp) + del alive + support.gc_collect() + + @threading_helper.requires_working_threading() + @support.bigmemtest(size=200, memuse=32*2**20, dry_run=False) + def test_create_many_threaded(self, size): + alive = [] + start = threading.Event() + def task(): + # try to create all interpreters simultaneously + if not start.wait(support.SHORT_TIMEOUT): + raise TimeoutError + interp = interpreters.create() + alive.append(interp) + threads = [threading.Thread(target=task) for _ in range(size)] + with threading_helper.start_threads(threads): + start.set() + del alive + support.gc_collect() + + @threading_helper.requires_working_threading() + @support.bigmemtest(size=200, memuse=34*2**20, dry_run=False) + def test_many_threads_running_interp_in_other_interp(self, size): + start = threading.Event() + interp = interpreters.create() + + script = f"""if True: + import _interpreters + _interpreters.run_string({interp.id}, '1') + """ + + def run(): + interp = interpreters.create() + alreadyrunning = (f'{interpreters.InterpreterError}: ' + 'interpreter already running') + # try to run all interpreters simultaneously + if not start.wait(support.SHORT_TIMEOUT): + raise TimeoutError + success = False + while not success: + try: + interp.exec(script) + except interpreters.ExecutionFailed as exc: + if exc.excinfo.msg != 'interpreter already running': + raise # re-raise + assert exc.excinfo.type.__name__ == 'InterpreterError' + else: + success = True + + threads = [threading.Thread(target=run) for _ in range(size)] + with threading_helper.start_threads(threads): + start.set() + support.gc_collect() + + @support.nomemtest + def test_create_interpreter_no_memory(self): + import _testcapi + + assertion = self.assertRaises(InterpreterError) + try: + _testcapi.set_nomemory(0, 1) + with assertion: + _interpreters.create() + finally: + _testcapi.remove_mem_hooks() + + +if __name__ == '__main__': + # Test needs to be a package, so we can do relative imports. + unittest.main() diff --git a/Lib/test/test_interpreters/utils.py b/Lib/test/test_interpreters/utils.py new file mode 100644 index 00000000000..bb6da52727c --- /dev/null +++ b/Lib/test/test_interpreters/utils.py @@ -0,0 +1,687 @@ +from collections import namedtuple +import contextlib +import errno +import json +import logging +import os +import os.path +#import select +import subprocess +import sys +import tempfile +from textwrap import dedent +import threading +import types +import unittest + +from test import support + +# We would use test.support.import_helper.import_module(), +# but the indirect import of test.support.os_helper causes refleaks. +try: + import _interpreters +except ImportError as exc: + raise unittest.SkipTest(str(exc)) +from concurrent import interpreters + + +try: + import _testinternalcapi + import _testcapi +except ImportError: + _testinternalcapi = None + _testcapi = None + +def requires_test_modules(func): + return unittest.skipIf(_testinternalcapi is None, "test requires _testinternalcapi module")(func) + + +def _dump_script(text): + lines = text.splitlines() + print() + print('-' * 20) + for i, line in enumerate(lines, 1): + print(f' {i:>{len(str(len(lines)))}} {line}') + print('-' * 20) + + +def _close_file(file): + try: + if hasattr(file, 'close'): + file.close() + else: + os.close(file) + except OSError as exc: + if exc.errno != errno.EBADF: + raise # re-raise + # It was closed already. + + +def pack_exception(exc=None): + captured = _interpreters.capture_exception(exc) + data = dict(captured.__dict__) + data['type'] = dict(captured.type.__dict__) + return json.dumps(data) + + +def unpack_exception(packed): + try: + data = json.loads(packed) + except json.decoder.JSONDecodeError as e: + logging.getLogger(__name__).warning('incomplete exception data', exc_info=e) + print(packed if isinstance(packed, str) else packed.decode('utf-8')) + return None + exc = types.SimpleNamespace(**data) + exc.type = types.SimpleNamespace(**exc.type) + return exc; + + +class CapturingResults: + + STDIO = dedent("""\ + with open({w_pipe}, 'wb', buffering=0) as _spipe_{stream}: + _captured_std{stream} = io.StringIO() + with contextlib.redirect_std{stream}(_captured_std{stream}): + ######################### + # begin wrapped script + + {indented} + + # end wrapped script + ######################### + text = _captured_std{stream}.getvalue() + _spipe_{stream}.write(text.encode('utf-8')) + """)[:-1] + EXC = dedent("""\ + with open({w_pipe}, 'wb', buffering=0) as _spipe_exc: + try: + ######################### + # begin wrapped script + + {indented} + + # end wrapped script + ######################### + except Exception as exc: + text = _interp_utils.pack_exception(exc) + _spipe_exc.write(text.encode('utf-8')) + """)[:-1] + + @classmethod + def wrap_script(cls, script, *, stdout=True, stderr=False, exc=False): + script = dedent(script).strip(os.linesep) + imports = [ + f'import {__name__} as _interp_utils', + ] + wrapped = script + + # Handle exc. + if exc: + exc = os.pipe() + r_exc, w_exc = exc + indented = wrapped.replace('\n', '\n ') + wrapped = cls.EXC.format( + w_pipe=w_exc, + indented=indented, + ) + else: + exc = None + + # Handle stdout. + if stdout: + imports.extend([ + 'import contextlib, io', + ]) + stdout = os.pipe() + r_out, w_out = stdout + indented = wrapped.replace('\n', '\n ') + wrapped = cls.STDIO.format( + w_pipe=w_out, + indented=indented, + stream='out', + ) + else: + stdout = None + + # Handle stderr. + if stderr == 'stdout': + stderr = None + elif stderr: + if not stdout: + imports.extend([ + 'import contextlib, io', + ]) + stderr = os.pipe() + r_err, w_err = stderr + indented = wrapped.replace('\n', '\n ') + wrapped = cls.STDIO.format( + w_pipe=w_err, + indented=indented, + stream='err', + ) + else: + stderr = None + + if wrapped == script: + raise NotImplementedError + else: + for line in imports: + wrapped = f'{line}{os.linesep}{wrapped}' + + results = cls(stdout, stderr, exc) + return wrapped, results + + def __init__(self, out, err, exc): + self._rf_out = None + self._rf_err = None + self._rf_exc = None + self._w_out = None + self._w_err = None + self._w_exc = None + + if out is not None: + r_out, w_out = out + self._rf_out = open(r_out, 'rb', buffering=0) + self._w_out = w_out + + if err is not None: + r_err, w_err = err + self._rf_err = open(r_err, 'rb', buffering=0) + self._w_err = w_err + + if exc is not None: + r_exc, w_exc = exc + self._rf_exc = open(r_exc, 'rb', buffering=0) + self._w_exc = w_exc + + self._buf_out = b'' + self._buf_err = b'' + self._buf_exc = b'' + self._exc = None + + self._closed = False + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + @property + def closed(self): + return self._closed + + def close(self): + if self._closed: + return + self._closed = True + + if self._w_out is not None: + _close_file(self._w_out) + self._w_out = None + if self._w_err is not None: + _close_file(self._w_err) + self._w_err = None + if self._w_exc is not None: + _close_file(self._w_exc) + self._w_exc = None + + self._capture() + + if self._rf_out is not None: + _close_file(self._rf_out) + self._rf_out = None + if self._rf_err is not None: + _close_file(self._rf_err) + self._rf_err = None + if self._rf_exc is not None: + _close_file(self._rf_exc) + self._rf_exc = None + + def _capture(self): + # Ideally this is called only after the script finishes + # (and thus has closed the write end of the pipe. + if self._rf_out is not None: + chunk = self._rf_out.read(100) + while chunk: + self._buf_out += chunk + chunk = self._rf_out.read(100) + if self._rf_err is not None: + chunk = self._rf_err.read(100) + while chunk: + self._buf_err += chunk + chunk = self._rf_err.read(100) + if self._rf_exc is not None: + chunk = self._rf_exc.read(100) + while chunk: + self._buf_exc += chunk + chunk = self._rf_exc.read(100) + + def _unpack_stdout(self): + return self._buf_out.decode('utf-8') + + def _unpack_stderr(self): + return self._buf_err.decode('utf-8') + + def _unpack_exc(self): + if self._exc is not None: + return self._exc + if not self._buf_exc: + return None + self._exc = unpack_exception(self._buf_exc) + return self._exc + + def stdout(self): + if self.closed: + return self.final().stdout + self._capture() + return self._unpack_stdout() + + def stderr(self): + if self.closed: + return self.final().stderr + self._capture() + return self._unpack_stderr() + + def exc(self): + if self.closed: + return self.final().exc + self._capture() + return self._unpack_exc() + + def final(self, *, force=False): + try: + return self._final + except AttributeError: + if not self._closed: + if not force: + raise Exception('no final results available yet') + else: + return CapturedResults.Proxy(self) + self._final = CapturedResults( + self._unpack_stdout(), + self._unpack_stderr(), + self._unpack_exc(), + ) + return self._final + + +class CapturedResults(namedtuple('CapturedResults', 'stdout stderr exc')): + + class Proxy: + def __init__(self, capturing): + self._capturing = capturing + def _finish(self): + if self._capturing is None: + return + self._final = self._capturing.final() + self._capturing = None + def __iter__(self): + self._finish() + yield from self._final + def __len__(self): + self._finish() + return len(self._final) + def __getattr__(self, name): + self._finish() + if name.startswith('_'): + raise AttributeError(name) + return getattr(self._final, name) + + def raise_if_failed(self): + if self.exc is not None: + raise interpreters.ExecutionFailed(self.exc) + + +def _captured_script(script, *, stdout=True, stderr=False, exc=False): + return CapturingResults.wrap_script( + script, + stdout=stdout, + stderr=stderr, + exc=exc, + ) + + +def clean_up_interpreters(): + for interp in interpreters.list_all(): + if interp.id == 0: # main + continue + try: + interp.close() + except _interpreters.InterpreterError: + pass # already destroyed + + +def _run_output(interp, request, init=None): + script, results = _captured_script(request) + with results: + if init: + interp.prepare_main(init) + interp.exec(script) + return results.stdout() + + +@contextlib.contextmanager +def _running(interp): + r, w = os.pipe() + def run(): + interp.exec(dedent(f""" + # wait for "signal" + with open({r}) as rpipe: + rpipe.read() + """)) + + t = threading.Thread(target=run) + t.start() + + yield + + with open(w, 'w') as spipe: + spipe.write('done') + t.join() + + +class TestBase(unittest.TestCase): + + def tearDown(self): + clean_up_interpreters() + + def pipe(self): + def ensure_closed(fd): + try: + os.close(fd) + except OSError: + pass + r, w = os.pipe() + self.addCleanup(lambda: ensure_closed(r)) + self.addCleanup(lambda: ensure_closed(w)) + return r, w + + def temp_dir(self): + tempdir = tempfile.mkdtemp() + tempdir = os.path.realpath(tempdir) + from test.support import os_helper + self.addCleanup(lambda: os_helper.rmtree(tempdir)) + return tempdir + + @contextlib.contextmanager + def captured_thread_exception(self): + ctx = types.SimpleNamespace(caught=None) + def excepthook(args): + ctx.caught = args + orig_excepthook = threading.excepthook + threading.excepthook = excepthook + try: + yield ctx + finally: + threading.excepthook = orig_excepthook + + def make_script(self, filename, dirname=None, text=None): + if text: + text = dedent(text) + if dirname is None: + dirname = self.temp_dir() + filename = os.path.join(dirname, filename) + + os.makedirs(os.path.dirname(filename), exist_ok=True) + with open(filename, 'w', encoding='utf-8') as outfile: + outfile.write(text or '') + return filename + + def make_module(self, name, pathentry=None, text=None): + if text: + text = dedent(text) + if pathentry is None: + pathentry = self.temp_dir() + else: + os.makedirs(pathentry, exist_ok=True) + *subnames, basename = name.split('.') + + dirname = pathentry + for subname in subnames: + dirname = os.path.join(dirname, subname) + if os.path.isdir(dirname): + pass + elif os.path.exists(dirname): + raise Exception(dirname) + else: + os.mkdir(dirname) + initfile = os.path.join(dirname, '__init__.py') + if not os.path.exists(initfile): + with open(initfile, 'w'): + pass + filename = os.path.join(dirname, basename + '.py') + + with open(filename, 'w', encoding='utf-8') as outfile: + outfile.write(text or '') + return filename + + @support.requires_subprocess() + def run_python(self, *argv): + proc = subprocess.run( + [sys.executable, *argv], + capture_output=True, + text=True, + ) + return proc.returncode, proc.stdout, proc.stderr + + def assert_python_ok(self, *argv): + exitcode, stdout, stderr = self.run_python(*argv) + self.assertNotEqual(exitcode, 1) + return stdout, stderr + + def assert_python_failure(self, *argv): + exitcode, stdout, stderr = self.run_python(*argv) + self.assertNotEqual(exitcode, 0) + return stdout, stderr + + def assert_ns_equal(self, ns1, ns2, msg=None): + # This is mostly copied from TestCase.assertDictEqual. + self.assertEqual(type(ns1), type(ns2)) + if ns1 == ns2: + return + + import difflib + import pprint + from unittest.util import _common_shorten_repr + standardMsg = '%s != %s' % _common_shorten_repr(ns1, ns2) + diff = ('\n' + '\n'.join(difflib.ndiff( + pprint.pformat(vars(ns1)).splitlines(), + pprint.pformat(vars(ns2)).splitlines()))) + diff = f'namespace({diff})' + standardMsg = self._truncateMessage(standardMsg, diff) + self.fail(self._formatMessage(msg, standardMsg)) + + def _run_string(self, interp, script): + wrapped, results = _captured_script(script, exc=False) + #_dump_script(wrapped) + with results: + if isinstance(interp, interpreters.Interpreter): + interp.exec(script) + else: + err = _interpreters.run_string(interp, wrapped) + if err is not None: + return None, err + return results.stdout(), None + + def run_and_capture(self, interp, script): + text, err = self._run_string(interp, script) + if err is not None: + raise interpreters.ExecutionFailed(err) + else: + return text + + def interp_exists(self, interpid): + try: + _interpreters.whence(interpid) + except _interpreters.InterpreterNotFoundError: + return False + else: + return True + + @requires_test_modules + @contextlib.contextmanager + def interpreter_from_capi(self, config=None, whence=None): + if config is False: + if whence is None: + whence = _interpreters.WHENCE_LEGACY_CAPI + else: + assert whence in (_interpreters.WHENCE_LEGACY_CAPI, + _interpreters.WHENCE_UNKNOWN), repr(whence) + config = None + elif config is True: + config = _interpreters.new_config('default') + elif config is None: + if whence not in ( + _interpreters.WHENCE_LEGACY_CAPI, + _interpreters.WHENCE_UNKNOWN, + ): + config = _interpreters.new_config('legacy') + elif isinstance(config, str): + config = _interpreters.new_config(config) + + if whence is None: + whence = _interpreters.WHENCE_XI + + interpid = _testinternalcapi.create_interpreter(config, whence=whence) + try: + yield interpid + finally: + try: + _testinternalcapi.destroy_interpreter(interpid) + except _interpreters.InterpreterNotFoundError: + pass + + @contextlib.contextmanager + def interpreter_obj_from_capi(self, config='legacy'): + with self.interpreter_from_capi(config) as interpid: + interp = interpreters.Interpreter( + interpid, + _whence=_interpreters.WHENCE_CAPI, + _ownsref=False, + ) + yield interp, interpid + + @contextlib.contextmanager + def capturing(self, script): + wrapped, capturing = _captured_script(script, stdout=True, exc=True) + #_dump_script(wrapped) + with capturing: + yield wrapped, capturing.final(force=True) + + @requires_test_modules + def run_from_capi(self, interpid, script, *, main=False): + with self.capturing(script) as (wrapped, results): + rc = _testinternalcapi.exec_interpreter(interpid, wrapped, main=main) + assert rc == 0, rc + results.raise_if_failed() + return results.stdout + + @contextlib.contextmanager + def _running(self, run_interp, exec_interp): + token = b'\0' + r_in, w_in = self.pipe() + r_out, w_out = self.pipe() + + def close(): + _close_file(r_in) + _close_file(w_in) + _close_file(r_out) + _close_file(w_out) + + # Start running (and wait). + script = dedent(f""" + import os + try: + # handshake + token = os.read({r_in}, 1) + os.write({w_out}, token) + # Wait for the "done" message. + os.read({r_in}, 1) + except BrokenPipeError: + pass + except OSError as exc: + if exc.errno != 9: + raise # re-raise + # It was closed already. + """) + failed = None + def run(): + nonlocal failed + try: + run_interp(script) + except Exception as exc: + failed = exc + close() + t = threading.Thread(target=run) + t.start() + + # handshake + try: + os.write(w_in, token) + token2 = os.read(r_out, 1) + assert token2 == token, (token2, token) + except OSError: + t.join() + if failed is not None: + raise failed + + # CM __exit__() + try: + try: + yield + finally: + # Send "done". + os.write(w_in, b'\0') + finally: + close() + t.join() + if failed is not None: + raise failed + + @contextlib.contextmanager + def running(self, interp): + if isinstance(interp, int): + interpid = interp + def exec_interp(script): + exc = _interpreters.exec(interpid, script) + assert exc is None, exc + run_interp = exec_interp + else: + def run_interp(script): + text = self.run_and_capture(interp, script) + assert text == '', repr(text) + def exec_interp(script): + interp.exec(script) + with self._running(run_interp, exec_interp): + yield + + @requires_test_modules + @contextlib.contextmanager + def running_from_capi(self, interpid, *, main=False): + def run_interp(script): + text = self.run_from_capi(interpid, script, main=main) + assert text == '', repr(text) + def exec_interp(script): + rc = _testinternalcapi.exec_interpreter(interpid, script) + assert rc == 0, rc + with self._running(run_interp, exec_interp): + yield + + @requires_test_modules + def run_temp_from_capi(self, script, config='legacy'): + if config is False: + # Force using Py_NewInterpreter(). + run_in_interp = (lambda s, c: _testcapi.run_in_subinterp(s)) + config = None + else: + run_in_interp = _testinternalcapi.run_in_subinterp_with_config + if config is True: + config = 'default' + if isinstance(config, str): + config = _interpreters.new_config(config) + with self.capturing(script) as (wrapped, results): + rc = run_in_interp(wrapped, config) + assert rc == 0, rc + results.raise_if_failed() + return results.stdout diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py deleted file mode 100644 index 212cbaa324f..00000000000 --- a/Lib/test/test_io.py +++ /dev/null @@ -1,5129 +0,0 @@ -"""Unit tests for the io module.""" - -# Tests of io are scattered over the test suite: -# * test_bufio - tests file buffering -# * test_memoryio - tests BytesIO and StringIO -# * test_fileio - tests FileIO -# * test_file - tests the file interface -# * test_io - tests everything else in the io module -# * test_univnewlines - tests universal newline support -# * test_largefile - tests operations on a file greater than 2**32 bytes -# (only enabled with -ulargefile) - -################################################################################ -# ATTENTION TEST WRITERS!!! -################################################################################ -# When writing tests for io, it's important to test both the C and Python -# implementations. This is usually done by writing a base test that refers to -# the type it is testing as an attribute. Then it provides custom subclasses to -# test both implementations. This file has lots of examples. -################################################################################ - -import abc -import array -import errno -import locale -import os -import pickle -import random -import signal -import sys -import textwrap -import threading -import time -import unittest -import warnings -import weakref -from collections import deque, UserList -from itertools import cycle, count -from test import support -from test.support.script_helper import ( - assert_python_ok, assert_python_failure, run_python_until_end) -from test.support import ( - import_helper, is_apple, os_helper, threading_helper, warnings_helper, -) -from test.support.os_helper import FakePath - -import codecs -import io # C implementation of io -import _pyio as pyio # Python implementation of io - -try: - import ctypes -except ImportError: - def byteslike(*pos, **kw): - return array.array("b", bytes(*pos, **kw)) -else: - def byteslike(*pos, **kw): - """Create a bytes-like object having no string or sequence methods""" - data = bytes(*pos, **kw) - obj = EmptyStruct() - ctypes.resize(obj, len(data)) - memoryview(obj).cast("B")[:] = data - return obj - class EmptyStruct(ctypes.Structure): - pass - - -def _default_chunk_size(): - """Get the default TextIOWrapper chunk size""" - with open(__file__, "r", encoding="latin-1") as f: - return f._CHUNK_SIZE - -requires_alarm = unittest.skipUnless( - hasattr(signal, "alarm"), "test requires signal.alarm()" -) - - -class BadIndex: - def __index__(self): - 1/0 - -class MockRawIOWithoutRead: - """A RawIO implementation without read(), so as to exercise the default - RawIO.read() which calls readinto().""" - - def __init__(self, read_stack=()): - self._read_stack = list(read_stack) - self._write_stack = [] - self._reads = 0 - self._extraneous_reads = 0 - - def write(self, b): - self._write_stack.append(bytes(b)) - return len(b) - - def writable(self): - return True - - def fileno(self): - return 42 - - def readable(self): - return True - - def seekable(self): - return True - - def seek(self, pos, whence): - return 0 # wrong but we gotta return something - - def tell(self): - return 0 # same comment as above - - def readinto(self, buf): - self._reads += 1 - max_len = len(buf) - try: - data = self._read_stack[0] - except IndexError: - self._extraneous_reads += 1 - return 0 - if data is None: - del self._read_stack[0] - return None - n = len(data) - if len(data) <= max_len: - del self._read_stack[0] - buf[:n] = data - return n - else: - buf[:] = data[:max_len] - self._read_stack[0] = data[max_len:] - return max_len - - def truncate(self, pos=None): - return pos - -class CMockRawIOWithoutRead(MockRawIOWithoutRead, io.RawIOBase): - pass - -class PyMockRawIOWithoutRead(MockRawIOWithoutRead, pyio.RawIOBase): - pass - - -class MockRawIO(MockRawIOWithoutRead): - - def read(self, n=None): - self._reads += 1 - try: - return self._read_stack.pop(0) - except: - self._extraneous_reads += 1 - return b"" - -class CMockRawIO(MockRawIO, io.RawIOBase): - pass - -class PyMockRawIO(MockRawIO, pyio.RawIOBase): - pass - - -class MisbehavedRawIO(MockRawIO): - def write(self, b): - return super().write(b) * 2 - - def read(self, n=None): - return super().read(n) * 2 - - def seek(self, pos, whence): - return -123 - - def tell(self): - return -456 - - def readinto(self, buf): - super().readinto(buf) - return len(buf) * 5 - -class CMisbehavedRawIO(MisbehavedRawIO, io.RawIOBase): - pass - -class PyMisbehavedRawIO(MisbehavedRawIO, pyio.RawIOBase): - pass - - -class SlowFlushRawIO(MockRawIO): - def __init__(self): - super().__init__() - self.in_flush = threading.Event() - - def flush(self): - self.in_flush.set() - time.sleep(0.25) - -class CSlowFlushRawIO(SlowFlushRawIO, io.RawIOBase): - pass - -class PySlowFlushRawIO(SlowFlushRawIO, pyio.RawIOBase): - pass - - -class CloseFailureIO(MockRawIO): - closed = 0 - - def close(self): - if not self.closed: - self.closed = 1 - raise OSError - -class CCloseFailureIO(CloseFailureIO, io.RawIOBase): - pass - -class PyCloseFailureIO(CloseFailureIO, pyio.RawIOBase): - pass - - -class MockFileIO: - - def __init__(self, data): - self.read_history = [] - super().__init__(data) - - def read(self, n=None): - res = super().read(n) - self.read_history.append(None if res is None else len(res)) - return res - - def readinto(self, b): - res = super().readinto(b) - self.read_history.append(res) - return res - -class CMockFileIO(MockFileIO, io.BytesIO): - pass - -class PyMockFileIO(MockFileIO, pyio.BytesIO): - pass - - -class MockUnseekableIO: - def seekable(self): - return False - - def seek(self, *args): - raise self.UnsupportedOperation("not seekable") - - def tell(self, *args): - raise self.UnsupportedOperation("not seekable") - - def truncate(self, *args): - raise self.UnsupportedOperation("not seekable") - -class CMockUnseekableIO(MockUnseekableIO, io.BytesIO): - UnsupportedOperation = io.UnsupportedOperation - -class PyMockUnseekableIO(MockUnseekableIO, pyio.BytesIO): - UnsupportedOperation = pyio.UnsupportedOperation - - -class MockCharPseudoDevFileIO(MockFileIO): - # GH-95782 - # ftruncate() does not work on these special files (and CPython then raises - # appropriate exceptions), so truncate() does not have to be accounted for - # here. - def __init__(self, data): - super().__init__(data) - - def seek(self, *args): - return 0 - - def tell(self, *args): - return 0 - -class CMockCharPseudoDevFileIO(MockCharPseudoDevFileIO, io.BytesIO): - pass - -class PyMockCharPseudoDevFileIO(MockCharPseudoDevFileIO, pyio.BytesIO): - pass - - -class MockNonBlockWriterIO: - - def __init__(self): - self._write_stack = [] - self._blocker_char = None - - def pop_written(self): - s = b"".join(self._write_stack) - self._write_stack[:] = [] - return s - - def block_on(self, char): - """Block when a given char is encountered.""" - self._blocker_char = char - - def readable(self): - return True - - def seekable(self): - return True - - def seek(self, pos, whence=0): - # naive implementation, enough for tests - return 0 - - def writable(self): - return True - - def write(self, b): - b = bytes(b) - n = -1 - if self._blocker_char: - try: - n = b.index(self._blocker_char) - except ValueError: - pass - else: - if n > 0: - # write data up to the first blocker - self._write_stack.append(b[:n]) - return n - else: - # cancel blocker and indicate would block - self._blocker_char = None - return None - self._write_stack.append(b) - return len(b) - -class CMockNonBlockWriterIO(MockNonBlockWriterIO, io.RawIOBase): - BlockingIOError = io.BlockingIOError - -class PyMockNonBlockWriterIO(MockNonBlockWriterIO, pyio.RawIOBase): - BlockingIOError = pyio.BlockingIOError - - -class IOTest(unittest.TestCase): - - def setUp(self): - os_helper.unlink(os_helper.TESTFN) - - def tearDown(self): - os_helper.unlink(os_helper.TESTFN) - - def write_ops(self, f): - self.assertEqual(f.write(b"blah."), 5) - f.truncate(0) - self.assertEqual(f.tell(), 5) - f.seek(0) - - self.assertEqual(f.write(b"blah."), 5) - self.assertEqual(f.seek(0), 0) - self.assertEqual(f.write(b"Hello."), 6) - self.assertEqual(f.tell(), 6) - self.assertEqual(f.seek(-1, 1), 5) - self.assertEqual(f.tell(), 5) - buffer = bytearray(b" world\n\n\n") - self.assertEqual(f.write(buffer), 9) - buffer[:] = b"*" * 9 # Overwrite our copy of the data - self.assertEqual(f.seek(0), 0) - self.assertEqual(f.write(b"h"), 1) - self.assertEqual(f.seek(-1, 2), 13) - self.assertEqual(f.tell(), 13) - - self.assertEqual(f.truncate(12), 12) - self.assertEqual(f.tell(), 13) - self.assertRaises(TypeError, f.seek, 0.0) - - def read_ops(self, f, buffered=False): - data = f.read(5) - self.assertEqual(data, b"hello") - data = byteslike(data) - self.assertEqual(f.readinto(data), 5) - self.assertEqual(bytes(data), b" worl") - data = bytearray(5) - self.assertEqual(f.readinto(data), 2) - self.assertEqual(len(data), 5) - self.assertEqual(data[:2], b"d\n") - self.assertEqual(f.seek(0), 0) - self.assertEqual(f.read(20), b"hello world\n") - self.assertEqual(f.read(1), b"") - self.assertEqual(f.readinto(byteslike(b"x")), 0) - self.assertEqual(f.seek(-6, 2), 6) - self.assertEqual(f.read(5), b"world") - self.assertEqual(f.read(0), b"") - self.assertEqual(f.readinto(byteslike()), 0) - self.assertEqual(f.seek(-6, 1), 5) - self.assertEqual(f.read(5), b" worl") - self.assertEqual(f.tell(), 10) - self.assertRaises(TypeError, f.seek, 0.0) - if buffered: - f.seek(0) - self.assertEqual(f.read(), b"hello world\n") - f.seek(6) - self.assertEqual(f.read(), b"world\n") - self.assertEqual(f.read(), b"") - f.seek(0) - data = byteslike(5) - self.assertEqual(f.readinto1(data), 5) - self.assertEqual(bytes(data), b"hello") - - LARGE = 2**31 - - def large_file_ops(self, f): - assert f.readable() - assert f.writable() - try: - self.assertEqual(f.seek(self.LARGE), self.LARGE) - except (OverflowError, ValueError): - self.skipTest("no largefile support") - self.assertEqual(f.tell(), self.LARGE) - self.assertEqual(f.write(b"xxx"), 3) - self.assertEqual(f.tell(), self.LARGE + 3) - self.assertEqual(f.seek(-1, 1), self.LARGE + 2) - self.assertEqual(f.truncate(), self.LARGE + 2) - self.assertEqual(f.tell(), self.LARGE + 2) - self.assertEqual(f.seek(0, 2), self.LARGE + 2) - self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1) - self.assertEqual(f.tell(), self.LARGE + 2) - self.assertEqual(f.seek(0, 2), self.LARGE + 1) - self.assertEqual(f.seek(-1, 2), self.LARGE) - self.assertEqual(f.read(2), b"x") - - def test_invalid_operations(self): - # Try writing on a file opened in read mode and vice-versa. - exc = self.UnsupportedOperation - with self.open(os_helper.TESTFN, "w", encoding="utf-8") as fp: - self.assertRaises(exc, fp.read) - self.assertRaises(exc, fp.readline) - with self.open(os_helper.TESTFN, "wb") as fp: - self.assertRaises(exc, fp.read) - self.assertRaises(exc, fp.readline) - with self.open(os_helper.TESTFN, "wb", buffering=0) as fp: - self.assertRaises(exc, fp.read) - self.assertRaises(exc, fp.readline) - with self.open(os_helper.TESTFN, "rb", buffering=0) as fp: - self.assertRaises(exc, fp.write, b"blah") - self.assertRaises(exc, fp.writelines, [b"blah\n"]) - with self.open(os_helper.TESTFN, "rb") as fp: - self.assertRaises(exc, fp.write, b"blah") - self.assertRaises(exc, fp.writelines, [b"blah\n"]) - with self.open(os_helper.TESTFN, "r", encoding="utf-8") as fp: - self.assertRaises(exc, fp.write, "blah") - self.assertRaises(exc, fp.writelines, ["blah\n"]) - # Non-zero seeking from current or end pos - self.assertRaises(exc, fp.seek, 1, self.SEEK_CUR) - self.assertRaises(exc, fp.seek, -1, self.SEEK_END) - - @support.cpython_only - def test_startup_optimization(self): - # gh-132952: Test that `io` is not imported at startup and that the - # __module__ of UnsupportedOperation is set to "io". - assert_python_ok("-S", "-c", textwrap.dedent( - """ - import sys - assert "io" not in sys.modules - try: - sys.stdin.truncate() - except Exception as e: - typ = type(e) - assert typ.__module__ == "io", (typ, typ.__module__) - assert typ.__name__ == "UnsupportedOperation", (typ, typ.__name__) - else: - raise AssertionError("Expected UnsupportedOperation") - """ - )) - - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def test_optional_abilities(self): - # Test for OSError when optional APIs are not supported - # The purpose of this test is to try fileno(), reading, writing and - # seeking operations with various objects that indicate they do not - # support these operations. - - def pipe_reader(): - [r, w] = os.pipe() - os.close(w) # So that read() is harmless - return self.FileIO(r, "r") - - def pipe_writer(): - [r, w] = os.pipe() - self.addCleanup(os.close, r) - # Guarantee that we can write into the pipe without blocking - thread = threading.Thread(target=os.read, args=(r, 100)) - thread.start() - self.addCleanup(thread.join) - return self.FileIO(w, "w") - - def buffered_reader(): - return self.BufferedReader(self.MockUnseekableIO()) - - def buffered_writer(): - return self.BufferedWriter(self.MockUnseekableIO()) - - def buffered_random(): - return self.BufferedRandom(self.BytesIO()) - - def buffered_rw_pair(): - return self.BufferedRWPair(self.MockUnseekableIO(), - self.MockUnseekableIO()) - - def text_reader(): - class UnseekableReader(self.MockUnseekableIO): - writable = self.BufferedIOBase.writable - write = self.BufferedIOBase.write - return self.TextIOWrapper(UnseekableReader(), "ascii") - - def text_writer(): - class UnseekableWriter(self.MockUnseekableIO): - readable = self.BufferedIOBase.readable - read = self.BufferedIOBase.read - return self.TextIOWrapper(UnseekableWriter(), "ascii") - - tests = ( - (pipe_reader, "fr"), (pipe_writer, "fw"), - (buffered_reader, "r"), (buffered_writer, "w"), - (buffered_random, "rws"), (buffered_rw_pair, "rw"), - (text_reader, "r"), (text_writer, "w"), - (self.BytesIO, "rws"), (self.StringIO, "rws"), - ) - - def do_test(test, obj, abilities): - readable = "r" in abilities - self.assertEqual(obj.readable(), readable) - writable = "w" in abilities - self.assertEqual(obj.writable(), writable) - - if isinstance(obj, self.TextIOBase): - data = "3" - elif isinstance(obj, (self.BufferedIOBase, self.RawIOBase)): - data = b"3" - else: - self.fail("Unknown base class") - - if "f" in abilities: - obj.fileno() - else: - self.assertRaises(OSError, obj.fileno) - - if readable: - obj.read(1) - obj.read() - else: - self.assertRaises(OSError, obj.read, 1) - self.assertRaises(OSError, obj.read) - - if writable: - obj.write(data) - else: - self.assertRaises(OSError, obj.write, data) - - if sys.platform.startswith("win") and test in ( - pipe_reader, pipe_writer): - # Pipes seem to appear as seekable on Windows - return - seekable = "s" in abilities - self.assertEqual(obj.seekable(), seekable) - - if seekable: - obj.tell() - obj.seek(0) - else: - self.assertRaises(OSError, obj.tell) - self.assertRaises(OSError, obj.seek, 0) - - if writable and seekable: - obj.truncate() - obj.truncate(0) - else: - self.assertRaises(OSError, obj.truncate) - self.assertRaises(OSError, obj.truncate, 0) - - for [test, abilities] in tests: - with self.subTest(test): - if test == pipe_writer and not threading_helper.can_start_thread: - self.skipTest("Need threads") - with test() as obj: - do_test(test, obj, abilities) - - - def test_open_handles_NUL_chars(self): - fn_with_NUL = 'foo\0bar' - self.assertRaises(ValueError, self.open, fn_with_NUL, 'w', encoding="utf-8") - - bytes_fn = bytes(fn_with_NUL, 'ascii') - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - self.assertRaises(ValueError, self.open, bytes_fn, 'w', encoding="utf-8") - - def test_raw_file_io(self): - with self.open(os_helper.TESTFN, "wb", buffering=0) as f: - self.assertEqual(f.readable(), False) - self.assertEqual(f.writable(), True) - self.assertEqual(f.seekable(), True) - self.write_ops(f) - with self.open(os_helper.TESTFN, "rb", buffering=0) as f: - self.assertEqual(f.readable(), True) - self.assertEqual(f.writable(), False) - self.assertEqual(f.seekable(), True) - self.read_ops(f) - - def test_buffered_file_io(self): - with self.open(os_helper.TESTFN, "wb") as f: - self.assertEqual(f.readable(), False) - self.assertEqual(f.writable(), True) - self.assertEqual(f.seekable(), True) - self.write_ops(f) - with self.open(os_helper.TESTFN, "rb") as f: - self.assertEqual(f.readable(), True) - self.assertEqual(f.writable(), False) - self.assertEqual(f.seekable(), True) - self.read_ops(f, True) - - def test_readline(self): - with self.open(os_helper.TESTFN, "wb") as f: - f.write(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") - with self.open(os_helper.TESTFN, "rb") as f: - self.assertEqual(f.readline(), b"abc\n") - self.assertEqual(f.readline(10), b"def\n") - self.assertEqual(f.readline(2), b"xy") - self.assertEqual(f.readline(4), b"zzy\n") - self.assertEqual(f.readline(), b"foo\x00bar\n") - self.assertEqual(f.readline(None), b"another line") - self.assertRaises(TypeError, f.readline, 5.3) - with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: - self.assertRaises(TypeError, f.readline, 5.3) - - def test_readline_nonsizeable(self): - # Issue #30061 - # Crash when readline() returns an object without __len__ - class R(self.IOBase): - def readline(self): - return None - self.assertRaises((TypeError, StopIteration), next, R()) - - def test_next_nonsizeable(self): - # Issue #30061 - # Crash when __next__() returns an object without __len__ - class R(self.IOBase): - def __next__(self): - return None - self.assertRaises(TypeError, R().readlines, 1) - - def test_raw_bytes_io(self): - f = self.BytesIO() - self.write_ops(f) - data = f.getvalue() - self.assertEqual(data, b"hello world\n") - f = self.BytesIO(data) - self.read_ops(f, True) - - def test_large_file_ops(self): - # On Windows and Apple platforms this test consumes large resources; It - # takes a long time to build the >2 GiB file and takes >2 GiB of disk - # space therefore the resource must be enabled to run this test. - if sys.platform[:3] == 'win' or is_apple: - support.requires( - 'largefile', - 'test requires %s bytes and a long time to run' % self.LARGE) - with self.open(os_helper.TESTFN, "w+b", 0) as f: - self.large_file_ops(f) - with self.open(os_helper.TESTFN, "w+b") as f: - self.large_file_ops(f) - - def test_with_open(self): - for bufsize in (0, 100): - with self.open(os_helper.TESTFN, "wb", bufsize) as f: - f.write(b"xxx") - self.assertEqual(f.closed, True) - try: - with self.open(os_helper.TESTFN, "wb", bufsize) as f: - 1/0 - except ZeroDivisionError: - self.assertEqual(f.closed, True) - else: - self.fail("1/0 didn't raise an exception") - - # issue 5008 - def test_append_mode_tell(self): - with self.open(os_helper.TESTFN, "wb") as f: - f.write(b"xxx") - with self.open(os_helper.TESTFN, "ab", buffering=0) as f: - self.assertEqual(f.tell(), 3) - with self.open(os_helper.TESTFN, "ab") as f: - self.assertEqual(f.tell(), 3) - with self.open(os_helper.TESTFN, "a", encoding="utf-8") as f: - self.assertGreater(f.tell(), 0) - - def test_destructor(self): - record = [] - class MyFileIO(self.FileIO): - def __del__(self): - record.append(1) - try: - f = super().__del__ - except AttributeError: - pass - else: - f() - def close(self): - record.append(2) - super().close() - def flush(self): - record.append(3) - super().flush() - with warnings_helper.check_warnings(('', ResourceWarning)): - f = MyFileIO(os_helper.TESTFN, "wb") - f.write(b"xxx") - del f - support.gc_collect() - self.assertEqual(record, [1, 2, 3]) - with self.open(os_helper.TESTFN, "rb") as f: - self.assertEqual(f.read(), b"xxx") - - def _check_base_destructor(self, base): - record = [] - class MyIO(base): - def __init__(self): - # This exercises the availability of attributes on object - # destruction. - # (in the C version, close() is called by the tp_dealloc - # function, not by __del__) - self.on_del = 1 - self.on_close = 2 - self.on_flush = 3 - def __del__(self): - record.append(self.on_del) - try: - f = super().__del__ - except AttributeError: - pass - else: - f() - def close(self): - record.append(self.on_close) - super().close() - def flush(self): - record.append(self.on_flush) - super().flush() - f = MyIO() - del f - support.gc_collect() - self.assertEqual(record, [1, 2, 3]) - - def test_IOBase_destructor(self): - self._check_base_destructor(self.IOBase) - - def test_RawIOBase_destructor(self): - self._check_base_destructor(self.RawIOBase) - - def test_BufferedIOBase_destructor(self): - self._check_base_destructor(self.BufferedIOBase) - - def test_TextIOBase_destructor(self): - self._check_base_destructor(self.TextIOBase) - - def test_close_flushes(self): - with self.open(os_helper.TESTFN, "wb") as f: - f.write(b"xxx") - with self.open(os_helper.TESTFN, "rb") as f: - self.assertEqual(f.read(), b"xxx") - - def test_array_writes(self): - a = array.array('i', range(10)) - n = len(a.tobytes()) - def check(f): - with f: - self.assertEqual(f.write(a), n) - f.writelines((a,)) - check(self.BytesIO()) - check(self.FileIO(os_helper.TESTFN, "w")) - check(self.BufferedWriter(self.MockRawIO())) - check(self.BufferedRandom(self.MockRawIO())) - check(self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())) - - def test_closefd(self): - self.assertRaises(ValueError, self.open, os_helper.TESTFN, 'w', - encoding="utf-8", closefd=False) - - def test_read_closed(self): - with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: - f.write("egg\n") - with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: - file = self.open(f.fileno(), "r", encoding="utf-8", closefd=False) - self.assertEqual(file.read(), "egg\n") - file.seek(0) - file.close() - self.assertRaises(ValueError, file.read) - with self.open(os_helper.TESTFN, "rb") as f: - file = self.open(f.fileno(), "rb", closefd=False) - self.assertEqual(file.read()[:3], b"egg") - file.close() - self.assertRaises(ValueError, file.readinto, bytearray(1)) - - def test_no_closefd_with_filename(self): - # can't use closefd in combination with a file name - self.assertRaises(ValueError, self.open, os_helper.TESTFN, "r", - encoding="utf-8", closefd=False) - - def test_closefd_attr(self): - with self.open(os_helper.TESTFN, "wb") as f: - f.write(b"egg\n") - with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: - self.assertEqual(f.buffer.raw.closefd, True) - file = self.open(f.fileno(), "r", encoding="utf-8", closefd=False) - self.assertEqual(file.buffer.raw.closefd, False) - - @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON; cyclic GC not supported, causes file locking") - def test_garbage_collection(self): - # FileIO objects are collected, and collecting them flushes - # all data to disk. - with warnings_helper.check_warnings(('', ResourceWarning)): - f = self.FileIO(os_helper.TESTFN, "wb") - f.write(b"abcxxx") - f.f = f - wr = weakref.ref(f) - del f - support.gc_collect() - self.assertIsNone(wr(), wr) - with self.open(os_helper.TESTFN, "rb") as f: - self.assertEqual(f.read(), b"abcxxx") - - def test_unbounded_file(self): - # Issue #1174606: reading from an unbounded stream such as /dev/zero. - zero = "/dev/zero" - if not os.path.exists(zero): - self.skipTest("{0} does not exist".format(zero)) - if sys.maxsize > 0x7FFFFFFF: - self.skipTest("test can only run in a 32-bit address space") - if support.real_max_memuse < support._2G: - self.skipTest("test requires at least 2 GiB of memory") - with self.open(zero, "rb", buffering=0) as f: - self.assertRaises(OverflowError, f.read) - with self.open(zero, "rb") as f: - self.assertRaises(OverflowError, f.read) - with self.open(zero, "r") as f: - self.assertRaises(OverflowError, f.read) - - def check_flush_error_on_close(self, *args, **kwargs): - # Test that the file is closed despite failed flush - # and that flush() is called before file closed. - f = self.open(*args, **kwargs) - closed = [] - def bad_flush(): - closed[:] = [f.closed] - raise OSError() - f.flush = bad_flush - self.assertRaises(OSError, f.close) # exception not swallowed - self.assertTrue(f.closed) - self.assertTrue(closed) # flush() called - self.assertFalse(closed[0]) # flush() called before file closed - f.flush = lambda: None # break reference loop - - def test_flush_error_on_close(self): - # raw file - # Issue #5700: io.FileIO calls flush() after file closed - self.check_flush_error_on_close(os_helper.TESTFN, 'wb', buffering=0) - fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) - self.check_flush_error_on_close(fd, 'wb', buffering=0) - fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) - self.check_flush_error_on_close(fd, 'wb', buffering=0, closefd=False) - os.close(fd) - # buffered io - self.check_flush_error_on_close(os_helper.TESTFN, 'wb') - fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) - self.check_flush_error_on_close(fd, 'wb') - fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) - self.check_flush_error_on_close(fd, 'wb', closefd=False) - os.close(fd) - # text io - self.check_flush_error_on_close(os_helper.TESTFN, 'w', encoding="utf-8") - fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) - self.check_flush_error_on_close(fd, 'w', encoding="utf-8") - fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) - self.check_flush_error_on_close(fd, 'w', encoding="utf-8", closefd=False) - os.close(fd) - - def test_multi_close(self): - f = self.open(os_helper.TESTFN, "wb", buffering=0) - f.close() - f.close() - f.close() - self.assertRaises(ValueError, f.flush) - - def test_RawIOBase_read(self): - # Exercise the default limited RawIOBase.read(n) implementation (which - # calls readinto() internally). - rawio = self.MockRawIOWithoutRead((b"abc", b"d", None, b"efg", None)) - self.assertEqual(rawio.read(2), b"ab") - self.assertEqual(rawio.read(2), b"c") - self.assertEqual(rawio.read(2), b"d") - self.assertEqual(rawio.read(2), None) - self.assertEqual(rawio.read(2), b"ef") - self.assertEqual(rawio.read(2), b"g") - self.assertEqual(rawio.read(2), None) - self.assertEqual(rawio.read(2), b"") - - def test_RawIOBase_read_bounds_checking(self): - # Make sure a `.readinto` call which returns a value outside - # (0, len(buffer)) raises. - class Misbehaved(self.RawIOBase): - def __init__(self, readinto_return) -> None: - self._readinto_return = readinto_return - def readinto(self, b): - return self._readinto_return - - with self.assertRaises(ValueError) as cm: - Misbehaved(2).read(1) - self.assertEqual(str(cm.exception), "readinto returned 2 outside buffer size 1") - for bad_size in (2147483647, sys.maxsize, -1, -1000): - with self.assertRaises(ValueError): - Misbehaved(bad_size).read() - - def test_types_have_dict(self): - test = ( - self.IOBase(), - self.RawIOBase(), - self.TextIOBase(), - self.StringIO(), - self.BytesIO() - ) - for obj in test: - self.assertHasAttr(obj, "__dict__") - - def test_opener(self): - with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: - f.write("egg\n") - fd = os.open(os_helper.TESTFN, os.O_RDONLY) - def opener(path, flags): - return fd - with self.open("non-existent", "r", encoding="utf-8", opener=opener) as f: - self.assertEqual(f.read(), "egg\n") - - def test_bad_opener_negative_1(self): - # Issue #27066. - def badopener(fname, flags): - return -1 - with self.assertRaises(ValueError) as cm: - self.open('non-existent', 'r', opener=badopener) - self.assertEqual(str(cm.exception), 'opener returned -1') - - def test_bad_opener_other_negative(self): - # Issue #27066. - def badopener(fname, flags): - return -2 - with self.assertRaises(ValueError) as cm: - self.open('non-existent', 'r', opener=badopener) - self.assertEqual(str(cm.exception), 'opener returned -2') - - def test_opener_invalid_fd(self): - # Check that OSError is raised with error code EBADF if the - # opener returns an invalid file descriptor (see gh-82212). - fd = os_helper.make_bad_fd() - with self.assertRaises(OSError) as cm: - self.open('foo', opener=lambda name, flags: fd) - self.assertEqual(cm.exception.errno, errno.EBADF) - - def test_fileio_closefd(self): - # Issue #4841 - with self.open(__file__, 'rb') as f1, \ - self.open(__file__, 'rb') as f2: - fileio = self.FileIO(f1.fileno(), closefd=False) - # .__init__() must not close f1 - fileio.__init__(f2.fileno(), closefd=False) - f1.readline() - # .close() must not close f2 - fileio.close() - f2.readline() - - def test_nonbuffered_textio(self): - with warnings_helper.check_no_resource_warning(self): - with self.assertRaises(ValueError): - self.open(os_helper.TESTFN, 'w', encoding="utf-8", buffering=0) - - def test_invalid_newline(self): - with warnings_helper.check_no_resource_warning(self): - with self.assertRaises(ValueError): - self.open(os_helper.TESTFN, 'w', encoding="utf-8", newline='invalid') - - def test_buffered_readinto_mixin(self): - # Test the implementation provided by BufferedIOBase - class Stream(self.BufferedIOBase): - def read(self, size): - return b"12345" - read1 = read - stream = Stream() - for method in ("readinto", "readinto1"): - with self.subTest(method): - buffer = byteslike(5) - self.assertEqual(getattr(stream, method)(buffer), 5) - self.assertEqual(bytes(buffer), b"12345") - - def test_fspath_support(self): - def check_path_succeeds(path): - with self.open(path, "w", encoding="utf-8") as f: - f.write("egg\n") - - with self.open(path, "r", encoding="utf-8") as f: - self.assertEqual(f.read(), "egg\n") - - check_path_succeeds(FakePath(os_helper.TESTFN)) - check_path_succeeds(FakePath(os.fsencode(os_helper.TESTFN))) - - with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: - bad_path = FakePath(f.fileno()) - with self.assertRaises(TypeError): - self.open(bad_path, 'w', encoding="utf-8") - - bad_path = FakePath(None) - with self.assertRaises(TypeError): - self.open(bad_path, 'w', encoding="utf-8") - - bad_path = FakePath(FloatingPointError) - with self.assertRaises(FloatingPointError): - self.open(bad_path, 'w', encoding="utf-8") - - # ensure that refcounting is correct with some error conditions - with self.assertRaisesRegex(ValueError, 'read/write/append mode'): - self.open(FakePath(os_helper.TESTFN), 'rwxa', encoding="utf-8") - - def test_RawIOBase_readall(self): - # Exercise the default unlimited RawIOBase.read() and readall() - # implementations. - rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) - self.assertEqual(rawio.read(), b"abcdefg") - rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) - self.assertEqual(rawio.readall(), b"abcdefg") - - def test_BufferedIOBase_readinto(self): - # Exercise the default BufferedIOBase.readinto() and readinto1() - # implementations (which call read() or read1() internally). - class Reader(self.BufferedIOBase): - def __init__(self, avail): - self.avail = avail - def read(self, size): - result = self.avail[:size] - self.avail = self.avail[size:] - return result - def read1(self, size): - """Returns no more than 5 bytes at once""" - return self.read(min(size, 5)) - tests = ( - # (test method, total data available, read buffer size, expected - # read size) - ("readinto", 10, 5, 5), - ("readinto", 10, 6, 6), # More than read1() can return - ("readinto", 5, 6, 5), # Buffer larger than total available - ("readinto", 6, 7, 6), - ("readinto", 10, 0, 0), # Empty buffer - ("readinto1", 10, 5, 5), # Result limited to single read1() call - ("readinto1", 10, 6, 5), # Buffer larger than read1() can return - ("readinto1", 5, 6, 5), # Buffer larger than total available - ("readinto1", 6, 7, 5), - ("readinto1", 10, 0, 0), # Empty buffer - ) - UNUSED_BYTE = 0x81 - for test in tests: - with self.subTest(test): - method, avail, request, result = test - reader = Reader(bytes(range(avail))) - buffer = bytearray((UNUSED_BYTE,) * request) - method = getattr(reader, method) - self.assertEqual(method(buffer), result) - self.assertEqual(len(buffer), request) - self.assertSequenceEqual(buffer[:result], range(result)) - unused = (UNUSED_BYTE,) * (request - result) - self.assertSequenceEqual(buffer[result:], unused) - self.assertEqual(len(reader.avail), avail - result) - - def test_close_assert(self): - class R(self.IOBase): - def __setattr__(self, name, value): - pass - def flush(self): - raise OSError() - f = R() - # This would cause an assertion failure. - self.assertRaises(OSError, f.close) - - # Silence destructor error - R.flush = lambda self: None - - @threading_helper.requires_working_threading() - def test_write_readline_races(self): - # gh-134908: Concurrent iteration over a file caused races - thread_count = 2 - write_count = 100 - read_count = 100 - - def writer(file, barrier): - barrier.wait() - for _ in range(write_count): - file.write("x") - - def reader(file, barrier): - barrier.wait() - for _ in range(read_count): - for line in file: - self.assertEqual(line, "") - - with self.open(os_helper.TESTFN, "w+") as f: - barrier = threading.Barrier(thread_count + 1) - reader = threading.Thread(target=reader, args=(f, barrier)) - writers = [threading.Thread(target=writer, args=(f, barrier)) - for _ in range(thread_count)] - with threading_helper.catch_threading_exception() as cm: - with threading_helper.start_threads(writers + [reader]): - pass - self.assertIsNone(cm.exc_type) - - self.assertEqual(os.stat(os_helper.TESTFN).st_size, - write_count * thread_count) - - -class CIOTest(IOTest): - - def test_IOBase_finalize(self): - # Issue #12149: segmentation fault on _PyIOBase_finalize when both a - # class which inherits IOBase and an object of this class are caught - # in a reference cycle and close() is already in the method cache. - class MyIO(self.IOBase): - def close(self): - pass - - # create an instance to populate the method cache - MyIO() - obj = MyIO() - obj.obj = obj - wr = weakref.ref(obj) - del MyIO - del obj - support.gc_collect() - self.assertIsNone(wr(), wr) - -@support.cpython_only -class TestIOCTypes(unittest.TestCase): - def setUp(self): - _io = import_helper.import_module("_io") - self.types = [ - _io.BufferedRWPair, - _io.BufferedRandom, - _io.BufferedReader, - _io.BufferedWriter, - _io.BytesIO, - _io.FileIO, - _io.IncrementalNewlineDecoder, - _io.StringIO, - _io.TextIOWrapper, - _io._BufferedIOBase, - _io._BytesIOBuffer, - _io._IOBase, - _io._RawIOBase, - _io._TextIOBase, - ] - if sys.platform == "win32": - self.types.append(_io._WindowsConsoleIO) - self._io = _io - - def test_immutable_types(self): - for tp in self.types: - with self.subTest(tp=tp): - with self.assertRaisesRegex(TypeError, "immutable"): - tp.foo = "bar" - - def test_class_hierarchy(self): - def check_subs(types, base): - for tp in types: - with self.subTest(tp=tp, base=base): - self.assertIsSubclass(tp, base) - - def recursive_check(d): - for k, v in d.items(): - if isinstance(v, dict): - recursive_check(v) - elif isinstance(v, set): - check_subs(v, k) - else: - self.fail("corrupt test dataset") - - _io = self._io - hierarchy = { - _io._IOBase: { - _io._BufferedIOBase: { - _io.BufferedRWPair, - _io.BufferedRandom, - _io.BufferedReader, - _io.BufferedWriter, - _io.BytesIO, - }, - _io._RawIOBase: { - _io.FileIO, - }, - _io._TextIOBase: { - _io.StringIO, - _io.TextIOWrapper, - }, - }, - } - if sys.platform == "win32": - hierarchy[_io._IOBase][_io._RawIOBase].add(_io._WindowsConsoleIO) - - recursive_check(hierarchy) - - def test_subclassing(self): - _io = self._io - dataset = {k: True for k in self.types} - dataset[_io._BytesIOBuffer] = False - - for tp, is_basetype in dataset.items(): - with self.subTest(tp=tp, is_basetype=is_basetype): - name = f"{tp.__name__}_subclass" - bases = (tp,) - if is_basetype: - _ = type(name, bases, {}) - else: - msg = "not an acceptable base type" - with self.assertRaisesRegex(TypeError, msg): - _ = type(name, bases, {}) - - def test_disallow_instantiation(self): - _io = self._io - support.check_disallow_instantiation(self, _io._BytesIOBuffer) - - def test_stringio_setstate(self): - # gh-127182: Calling __setstate__() with invalid arguments must not crash - obj = self._io.StringIO() - with self.assertRaisesRegex( - TypeError, - 'initial_value must be str or None, not int', - ): - obj.__setstate__((1, '', 0, {})) - - obj.__setstate__((None, '', 0, {})) # should not crash - self.assertEqual(obj.getvalue(), '') - - obj.__setstate__(('', '', 0, {})) - self.assertEqual(obj.getvalue(), '') - -class PyIOTest(IOTest): - pass - - -@support.cpython_only -class APIMismatchTest(unittest.TestCase): - - def test_RawIOBase_io_in_pyio_match(self): - """Test that pyio RawIOBase class has all c RawIOBase methods""" - mismatch = support.detect_api_mismatch(pyio.RawIOBase, io.RawIOBase, - ignore=('__weakref__', '__static_attributes__')) - self.assertEqual(mismatch, set(), msg='Python RawIOBase does not have all C RawIOBase methods') - - def test_RawIOBase_pyio_in_io_match(self): - """Test that c RawIOBase class has all pyio RawIOBase methods""" - mismatch = support.detect_api_mismatch(io.RawIOBase, pyio.RawIOBase) - self.assertEqual(mismatch, set(), msg='C RawIOBase does not have all Python RawIOBase methods') - - -class CommonBufferedTests: - # Tests common to BufferedReader, BufferedWriter and BufferedRandom - - def test_detach(self): - raw = self.MockRawIO() - buf = self.tp(raw) - self.assertIs(buf.detach(), raw) - self.assertRaises(ValueError, buf.detach) - - repr(buf) # Should still work - - def test_fileno(self): - rawio = self.MockRawIO() - bufio = self.tp(rawio) - - self.assertEqual(42, bufio.fileno()) - - def test_invalid_args(self): - rawio = self.MockRawIO() - bufio = self.tp(rawio) - # Invalid whence - self.assertRaises(ValueError, bufio.seek, 0, -1) - self.assertRaises(ValueError, bufio.seek, 0, 9) - - def test_override_destructor(self): - tp = self.tp - record = [] - class MyBufferedIO(tp): - def __del__(self): - record.append(1) - try: - f = super().__del__ - except AttributeError: - pass - else: - f() - def close(self): - record.append(2) - super().close() - def flush(self): - record.append(3) - super().flush() - rawio = self.MockRawIO() - bufio = MyBufferedIO(rawio) - del bufio - support.gc_collect() - self.assertEqual(record, [1, 2, 3]) - - def test_context_manager(self): - # Test usability as a context manager - rawio = self.MockRawIO() - bufio = self.tp(rawio) - def _with(): - with bufio: - pass - _with() - # bufio should now be closed, and using it a second time should raise - # a ValueError. - self.assertRaises(ValueError, _with) - - def test_error_through_destructor(self): - # Test that the exception state is not modified by a destructor, - # even if close() fails. - rawio = self.CloseFailureIO() - with support.catch_unraisable_exception() as cm: - with self.assertRaises(AttributeError): - self.tp(rawio).xyzzy - - self.assertEqual(cm.unraisable.exc_type, OSError) - - def test_repr(self): - raw = self.MockRawIO() - b = self.tp(raw) - clsname = r"(%s\.)?%s" % (self.tp.__module__, self.tp.__qualname__) - self.assertRegex(repr(b), "<%s>" % clsname) - raw.name = "dummy" - self.assertRegex(repr(b), "<%s name='dummy'>" % clsname) - raw.name = b"dummy" - self.assertRegex(repr(b), "<%s name=b'dummy'>" % clsname) - - def test_recursive_repr(self): - # Issue #25455 - raw = self.MockRawIO() - b = self.tp(raw) - with support.swap_attr(raw, 'name', b), support.infinite_recursion(25): - with self.assertRaises(RuntimeError): - repr(b) # Should not crash - - def test_flush_error_on_close(self): - # Test that buffered file is closed despite failed flush - # and that flush() is called before file closed. - raw = self.MockRawIO() - closed = [] - def bad_flush(): - closed[:] = [b.closed, raw.closed] - raise OSError() - raw.flush = bad_flush - b = self.tp(raw) - self.assertRaises(OSError, b.close) # exception not swallowed - self.assertTrue(b.closed) - self.assertTrue(raw.closed) - self.assertTrue(closed) # flush() called - self.assertFalse(closed[0]) # flush() called before file closed - self.assertFalse(closed[1]) - raw.flush = lambda: None # break reference loop - - def test_close_error_on_close(self): - raw = self.MockRawIO() - def bad_flush(): - raise OSError('flush') - def bad_close(): - raise OSError('close') - raw.close = bad_close - b = self.tp(raw) - b.flush = bad_flush - with self.assertRaises(OSError) as err: # exception not swallowed - b.close() - self.assertEqual(err.exception.args, ('close',)) - self.assertIsInstance(err.exception.__context__, OSError) - self.assertEqual(err.exception.__context__.args, ('flush',)) - self.assertFalse(b.closed) - - # Silence destructor error - raw.close = lambda: None - b.flush = lambda: None - - def test_nonnormalized_close_error_on_close(self): - # Issue #21677 - raw = self.MockRawIO() - def bad_flush(): - raise non_existing_flush - def bad_close(): - raise non_existing_close - raw.close = bad_close - b = self.tp(raw) - b.flush = bad_flush - with self.assertRaises(NameError) as err: # exception not swallowed - b.close() - self.assertIn('non_existing_close', str(err.exception)) - self.assertIsInstance(err.exception.__context__, NameError) - self.assertIn('non_existing_flush', str(err.exception.__context__)) - self.assertFalse(b.closed) - - # Silence destructor error - b.flush = lambda: None - raw.close = lambda: None - - def test_multi_close(self): - raw = self.MockRawIO() - b = self.tp(raw) - b.close() - b.close() - b.close() - self.assertRaises(ValueError, b.flush) - - def test_unseekable(self): - bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) - self.assertRaises(self.UnsupportedOperation, bufio.tell) - self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) - - def test_readonly_attributes(self): - raw = self.MockRawIO() - buf = self.tp(raw) - x = self.MockRawIO() - with self.assertRaises(AttributeError): - buf.raw = x - - def test_pickling_subclass(self): - global MyBufferedIO - class MyBufferedIO(self.tp): - def __init__(self, raw, tag): - super().__init__(raw) - self.tag = tag - def __getstate__(self): - return self.tag, self.raw.getvalue() - def __setstate__(slf, state): - tag, value = state - slf.__init__(self.BytesIO(value), tag) - - raw = self.BytesIO(b'data') - buf = MyBufferedIO(raw, tag='ham') - for proto in range(pickle.HIGHEST_PROTOCOL + 1): - with self.subTest(protocol=proto): - pickled = pickle.dumps(buf, proto) - newbuf = pickle.loads(pickled) - self.assertEqual(newbuf.raw.getvalue(), b'data') - self.assertEqual(newbuf.tag, 'ham') - del MyBufferedIO - - -class SizeofTest: - - @support.cpython_only - def test_sizeof(self): - bufsize1 = 4096 - bufsize2 = 8192 - rawio = self.MockRawIO() - bufio = self.tp(rawio, buffer_size=bufsize1) - size = sys.getsizeof(bufio) - bufsize1 - rawio = self.MockRawIO() - bufio = self.tp(rawio, buffer_size=bufsize2) - self.assertEqual(sys.getsizeof(bufio), size + bufsize2) - - @support.cpython_only - def test_buffer_freeing(self) : - bufsize = 4096 - rawio = self.MockRawIO() - bufio = self.tp(rawio, buffer_size=bufsize) - size = sys.getsizeof(bufio) - bufsize - bufio.close() - self.assertEqual(sys.getsizeof(bufio), size) - -class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): - read_mode = "rb" - - def test_constructor(self): - rawio = self.MockRawIO([b"abc"]) - bufio = self.tp(rawio) - bufio.__init__(rawio) - bufio.__init__(rawio, buffer_size=1024) - bufio.__init__(rawio, buffer_size=16) - self.assertEqual(b"abc", bufio.read()) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) - rawio = self.MockRawIO([b"abc"]) - bufio.__init__(rawio) - self.assertEqual(b"abc", bufio.read()) - - def test_uninitialized(self): - bufio = self.tp.__new__(self.tp) - del bufio - bufio = self.tp.__new__(self.tp) - self.assertRaisesRegex((ValueError, AttributeError), - 'uninitialized|has no attribute', - bufio.read, 0) - bufio.__init__(self.MockRawIO()) - self.assertEqual(bufio.read(0), b'') - - def test_read(self): - for arg in (None, 7): - rawio = self.MockRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - self.assertEqual(b"abcdefg", bufio.read(arg)) - # Invalid args - self.assertRaises(ValueError, bufio.read, -2) - - def test_read1(self): - rawio = self.MockRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - self.assertEqual(b"a", bufio.read(1)) - self.assertEqual(b"b", bufio.read1(1)) - self.assertEqual(rawio._reads, 1) - self.assertEqual(b"", bufio.read1(0)) - self.assertEqual(b"c", bufio.read1(100)) - self.assertEqual(rawio._reads, 1) - self.assertEqual(b"d", bufio.read1(100)) - self.assertEqual(rawio._reads, 2) - self.assertEqual(b"efg", bufio.read1(100)) - self.assertEqual(rawio._reads, 3) - self.assertEqual(b"", bufio.read1(100)) - self.assertEqual(rawio._reads, 4) - - def test_read1_arbitrary(self): - rawio = self.MockRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - self.assertEqual(b"a", bufio.read(1)) - self.assertEqual(b"bc", bufio.read1()) - self.assertEqual(b"d", bufio.read1()) - self.assertEqual(b"efg", bufio.read1(-1)) - self.assertEqual(rawio._reads, 3) - self.assertEqual(b"", bufio.read1()) - self.assertEqual(rawio._reads, 4) - - def test_readinto(self): - rawio = self.MockRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - b = bytearray(2) - self.assertEqual(bufio.readinto(b), 2) - self.assertEqual(b, b"ab") - self.assertEqual(bufio.readinto(b), 2) - self.assertEqual(b, b"cd") - self.assertEqual(bufio.readinto(b), 2) - self.assertEqual(b, b"ef") - self.assertEqual(bufio.readinto(b), 1) - self.assertEqual(b, b"gf") - self.assertEqual(bufio.readinto(b), 0) - self.assertEqual(b, b"gf") - rawio = self.MockRawIO((b"abc", None)) - bufio = self.tp(rawio) - self.assertEqual(bufio.readinto(b), 2) - self.assertEqual(b, b"ab") - self.assertEqual(bufio.readinto(b), 1) - self.assertEqual(b, b"cb") - - def test_readinto1(self): - buffer_size = 10 - rawio = self.MockRawIO((b"abc", b"de", b"fgh", b"jkl")) - bufio = self.tp(rawio, buffer_size=buffer_size) - b = bytearray(2) - self.assertEqual(bufio.peek(3), b'abc') - self.assertEqual(rawio._reads, 1) - self.assertEqual(bufio.readinto1(b), 2) - self.assertEqual(b, b"ab") - self.assertEqual(rawio._reads, 1) - self.assertEqual(bufio.readinto1(b), 1) - self.assertEqual(b[:1], b"c") - self.assertEqual(rawio._reads, 1) - self.assertEqual(bufio.readinto1(b), 2) - self.assertEqual(b, b"de") - self.assertEqual(rawio._reads, 2) - b = bytearray(2*buffer_size) - self.assertEqual(bufio.peek(3), b'fgh') - self.assertEqual(rawio._reads, 3) - self.assertEqual(bufio.readinto1(b), 6) - self.assertEqual(b[:6], b"fghjkl") - self.assertEqual(rawio._reads, 4) - - def test_readinto_array(self): - buffer_size = 60 - data = b"a" * 26 - rawio = self.MockRawIO((data,)) - bufio = self.tp(rawio, buffer_size=buffer_size) - - # Create an array with element size > 1 byte - b = array.array('i', b'x' * 32) - assert len(b) != 16 - - # Read into it. We should get as many *bytes* as we can fit into b - # (which is more than the number of elements) - n = bufio.readinto(b) - self.assertGreater(n, len(b)) - - # Check that old contents of b are preserved - bm = memoryview(b).cast('B') - self.assertLess(n, len(bm)) - self.assertEqual(bm[:n], data[:n]) - self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) - - def test_readinto1_array(self): - buffer_size = 60 - data = b"a" * 26 - rawio = self.MockRawIO((data,)) - bufio = self.tp(rawio, buffer_size=buffer_size) - - # Create an array with element size > 1 byte - b = array.array('i', b'x' * 32) - assert len(b) != 16 - - # Read into it. We should get as many *bytes* as we can fit into b - # (which is more than the number of elements) - n = bufio.readinto1(b) - self.assertGreater(n, len(b)) - - # Check that old contents of b are preserved - bm = memoryview(b).cast('B') - self.assertLess(n, len(bm)) - self.assertEqual(bm[:n], data[:n]) - self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) - - def test_readlines(self): - def bufio(): - rawio = self.MockRawIO((b"abc\n", b"d\n", b"ef")) - return self.tp(rawio) - self.assertEqual(bufio().readlines(), [b"abc\n", b"d\n", b"ef"]) - self.assertEqual(bufio().readlines(5), [b"abc\n", b"d\n"]) - self.assertEqual(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"]) - - def test_buffering(self): - data = b"abcdefghi" - dlen = len(data) - - tests = [ - [ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ], - [ 100, [ 3, 3, 3], [ dlen ] ], - [ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ], - ] - - for bufsize, buf_read_sizes, raw_read_sizes in tests: - rawio = self.MockFileIO(data) - bufio = self.tp(rawio, buffer_size=bufsize) - pos = 0 - for nbytes in buf_read_sizes: - self.assertEqual(bufio.read(nbytes), data[pos:pos+nbytes]) - pos += nbytes - # this is mildly implementation-dependent - self.assertEqual(rawio.read_history, raw_read_sizes) - - def test_read_non_blocking(self): - # Inject some None's in there to simulate EWOULDBLOCK - rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None)) - bufio = self.tp(rawio) - self.assertEqual(b"abcd", bufio.read(6)) - self.assertEqual(b"e", bufio.read(1)) - self.assertEqual(b"fg", bufio.read()) - self.assertEqual(b"", bufio.peek(1)) - self.assertIsNone(bufio.read()) - self.assertEqual(b"", bufio.read()) - - rawio = self.MockRawIO((b"a", None, None)) - self.assertEqual(b"a", rawio.readall()) - self.assertIsNone(rawio.readall()) - - def test_read_past_eof(self): - rawio = self.MockRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - - self.assertEqual(b"abcdefg", bufio.read(9000)) - - def test_read_all(self): - rawio = self.MockRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - - self.assertEqual(b"abcdefg", bufio.read()) - - @threading_helper.requires_working_threading() - @support.requires_resource('cpu') - def test_threads(self): - try: - # Write out many bytes with exactly the same number of 0's, - # 1's... 255's. This will help us check that concurrent reading - # doesn't duplicate or forget contents. - N = 1000 - l = list(range(256)) * N - random.shuffle(l) - s = bytes(bytearray(l)) - with self.open(os_helper.TESTFN, "wb") as f: - f.write(s) - with self.open(os_helper.TESTFN, self.read_mode, buffering=0) as raw: - bufio = self.tp(raw, 8) - errors = [] - results = [] - def f(): - try: - # Intra-buffer read then buffer-flushing read - for n in cycle([1, 19]): - s = bufio.read(n) - if not s: - break - # list.append() is atomic - results.append(s) - except Exception as e: - errors.append(e) - raise - threads = [threading.Thread(target=f) for x in range(20)] - with threading_helper.start_threads(threads): - time.sleep(0.02) # yield - self.assertFalse(errors, - "the following exceptions were caught: %r" % errors) - s = b''.join(results) - for i in range(256): - c = bytes(bytearray([i])) - self.assertEqual(s.count(c), N) - finally: - os_helper.unlink(os_helper.TESTFN) - - def test_unseekable(self): - bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) - self.assertRaises(self.UnsupportedOperation, bufio.tell) - self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) - bufio.read(1) - self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) - self.assertRaises(self.UnsupportedOperation, bufio.tell) - - def test_misbehaved_io(self): - rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - self.assertRaises(OSError, bufio.seek, 0) - self.assertRaises(OSError, bufio.tell) - - # Silence destructor error - bufio.close = lambda: None - - def test_no_extraneous_read(self): - # Issue #9550; when the raw IO object has satisfied the read request, - # we should not issue any additional reads, otherwise it may block - # (e.g. socket). - bufsize = 16 - for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2): - rawio = self.MockRawIO([b"x" * n]) - bufio = self.tp(rawio, bufsize) - self.assertEqual(bufio.read(n), b"x" * n) - # Simple case: one raw read is enough to satisfy the request. - self.assertEqual(rawio._extraneous_reads, 0, - "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) - # A more complex case where two raw reads are needed to satisfy - # the request. - rawio = self.MockRawIO([b"x" * (n - 1), b"x"]) - bufio = self.tp(rawio, bufsize) - self.assertEqual(bufio.read(n), b"x" * n) - self.assertEqual(rawio._extraneous_reads, 0, - "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) - - def test_read_on_closed(self): - # Issue #23796 - b = self.BufferedReader(self.BytesIO(b"12")) - b.read(1) - b.close() - with self.subTest('peek'): - self.assertRaises(ValueError, b.peek) - with self.subTest('read1'): - self.assertRaises(ValueError, b.read1, 1) - with self.subTest('read'): - self.assertRaises(ValueError, b.read) - with self.subTest('readinto'): - self.assertRaises(ValueError, b.readinto, bytearray()) - with self.subTest('readinto1'): - self.assertRaises(ValueError, b.readinto1, bytearray()) - with self.subTest('flush'): - self.assertRaises(ValueError, b.flush) - with self.subTest('truncate'): - self.assertRaises(ValueError, b.truncate) - with self.subTest('seek'): - self.assertRaises(ValueError, b.seek, 0) - - def test_truncate_on_read_only(self): - rawio = self.MockFileIO(b"abc") - bufio = self.tp(rawio) - self.assertFalse(bufio.writable()) - self.assertRaises(self.UnsupportedOperation, bufio.truncate) - self.assertRaises(self.UnsupportedOperation, bufio.truncate, 0) - - def test_tell_character_device_file(self): - # GH-95782 - # For the (former) bug in BufferedIO to manifest, the wrapped IO obj - # must be able to produce at least 2 bytes. - raw = self.MockCharPseudoDevFileIO(b"12") - buf = self.tp(raw) - self.assertEqual(buf.tell(), 0) - self.assertEqual(buf.read(1), b"1") - self.assertEqual(buf.tell(), 0) - - def test_seek_character_device_file(self): - raw = self.MockCharPseudoDevFileIO(b"12") - buf = self.tp(raw) - self.assertEqual(buf.seek(0, io.SEEK_CUR), 0) - self.assertEqual(buf.seek(1, io.SEEK_SET), 0) - self.assertEqual(buf.seek(0, io.SEEK_CUR), 0) - self.assertEqual(buf.read(1), b"1") - - # In the C implementation, tell() sets the BufferedIO's abs_pos to 0, - # which means that the next seek() could return a negative offset if it - # does not sanity-check: - self.assertEqual(buf.tell(), 0) - self.assertEqual(buf.seek(0, io.SEEK_CUR), 0) - - -class CBufferedReaderTest(BufferedReaderTest, SizeofTest): - tp = io.BufferedReader - - def test_initialization(self): - rawio = self.MockRawIO([b"abc"]) - bufio = self.tp(rawio) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) - self.assertRaises(ValueError, bufio.read) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) - self.assertRaises(ValueError, bufio.read) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) - self.assertRaises(ValueError, bufio.read) - - def test_misbehaved_io_read(self): - rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) - bufio = self.tp(rawio) - # _pyio.BufferedReader seems to implement reading different, so that - # checking this is not so easy. - self.assertRaises(OSError, bufio.read, 10) - - @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON; cyclic GC not supported, causes file locking") - def test_garbage_collection(self): - # C BufferedReader objects are collected. - # The Python version has __del__, so it ends into gc.garbage instead - self.addCleanup(os_helper.unlink, os_helper.TESTFN) - with warnings_helper.check_warnings(('', ResourceWarning)): - rawio = self.FileIO(os_helper.TESTFN, "w+b") - f = self.tp(rawio) - f.f = f - wr = weakref.ref(f) - del f - support.gc_collect() - self.assertIsNone(wr(), wr) - - def test_args_error(self): - # Issue #17275 - with self.assertRaisesRegex(TypeError, "BufferedReader"): - self.tp(self.BytesIO(), 1024, 1024, 1024) - - def test_bad_readinto_value(self): - rawio = self.tp(self.BytesIO(b"12")) - rawio.readinto = lambda buf: -1 - bufio = self.tp(rawio) - with self.assertRaises(OSError) as cm: - bufio.readline() - self.assertIsNone(cm.exception.__cause__) - - def test_bad_readinto_type(self): - rawio = self.tp(self.BytesIO(b"12")) - rawio.readinto = lambda buf: b'' - bufio = self.tp(rawio) - with self.assertRaises(OSError) as cm: - bufio.readline() - self.assertIsInstance(cm.exception.__cause__, TypeError) - - -class PyBufferedReaderTest(BufferedReaderTest): - tp = pyio.BufferedReader - - -class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): - write_mode = "wb" - - def test_constructor(self): - rawio = self.MockRawIO() - bufio = self.tp(rawio) - bufio.__init__(rawio) - bufio.__init__(rawio, buffer_size=1024) - bufio.__init__(rawio, buffer_size=16) - self.assertEqual(3, bufio.write(b"abc")) - bufio.flush() - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) - bufio.__init__(rawio) - self.assertEqual(3, bufio.write(b"ghi")) - bufio.flush() - self.assertEqual(b"".join(rawio._write_stack), b"abcghi") - - def test_uninitialized(self): - bufio = self.tp.__new__(self.tp) - del bufio - bufio = self.tp.__new__(self.tp) - self.assertRaisesRegex((ValueError, AttributeError), - 'uninitialized|has no attribute', - bufio.write, b'') - bufio.__init__(self.MockRawIO()) - self.assertEqual(bufio.write(b''), 0) - - def test_detach_flush(self): - raw = self.MockRawIO() - buf = self.tp(raw) - buf.write(b"howdy!") - self.assertFalse(raw._write_stack) - buf.detach() - self.assertEqual(raw._write_stack, [b"howdy!"]) - - def test_write(self): - # Write to the buffered IO but don't overflow the buffer. - writer = self.MockRawIO() - bufio = self.tp(writer, 8) - bufio.write(b"abc") - self.assertFalse(writer._write_stack) - buffer = bytearray(b"def") - bufio.write(buffer) - buffer[:] = b"***" # Overwrite our copy of the data - bufio.flush() - self.assertEqual(b"".join(writer._write_stack), b"abcdef") - - def test_write_overflow(self): - writer = self.MockRawIO() - bufio = self.tp(writer, 8) - contents = b"abcdefghijklmnop" - for n in range(0, len(contents), 3): - bufio.write(contents[n:n+3]) - flushed = b"".join(writer._write_stack) - # At least (total - 8) bytes were implicitly flushed, perhaps more - # depending on the implementation. - self.assertStartsWith(flushed, contents[:-8]) - - def check_writes(self, intermediate_func): - # Lots of writes, test the flushed output is as expected. - contents = bytes(range(256)) * 1000 - n = 0 - writer = self.MockRawIO() - bufio = self.tp(writer, 13) - # Generator of write sizes: repeat each N 15 times then proceed to N+1 - def gen_sizes(): - for size in count(1): - for i in range(15): - yield size - sizes = gen_sizes() - while n < len(contents): - size = min(next(sizes), len(contents) - n) - self.assertEqual(bufio.write(contents[n:n+size]), size) - intermediate_func(bufio) - n += size - bufio.flush() - self.assertEqual(contents, b"".join(writer._write_stack)) - - def test_writes(self): - self.check_writes(lambda bufio: None) - - def test_writes_and_flushes(self): - self.check_writes(lambda bufio: bufio.flush()) - - def test_writes_and_seeks(self): - def _seekabs(bufio): - pos = bufio.tell() - bufio.seek(pos + 1, 0) - bufio.seek(pos - 1, 0) - bufio.seek(pos, 0) - self.check_writes(_seekabs) - def _seekrel(bufio): - pos = bufio.seek(0, 1) - bufio.seek(+1, 1) - bufio.seek(-1, 1) - bufio.seek(pos, 0) - self.check_writes(_seekrel) - - def test_writes_and_truncates(self): - self.check_writes(lambda bufio: bufio.truncate(bufio.tell())) - - def test_write_non_blocking(self): - raw = self.MockNonBlockWriterIO() - bufio = self.tp(raw, 8) - - self.assertEqual(bufio.write(b"abcd"), 4) - self.assertEqual(bufio.write(b"efghi"), 5) - # 1 byte will be written, the rest will be buffered - raw.block_on(b"k") - self.assertEqual(bufio.write(b"jklmn"), 5) - - # 8 bytes will be written, 8 will be buffered and the rest will be lost - raw.block_on(b"0") - try: - bufio.write(b"opqrwxyz0123456789") - except self.BlockingIOError as e: - written = e.characters_written - else: - self.fail("BlockingIOError should have been raised") - self.assertEqual(written, 16) - self.assertEqual(raw.pop_written(), - b"abcdefghijklmnopqrwxyz") - - self.assertEqual(bufio.write(b"ABCDEFGHI"), 9) - s = raw.pop_written() - # Previously buffered bytes were flushed - self.assertStartsWith(s, b"01234567A") - - def test_write_and_rewind(self): - raw = self.BytesIO() - bufio = self.tp(raw, 4) - self.assertEqual(bufio.write(b"abcdef"), 6) - self.assertEqual(bufio.tell(), 6) - bufio.seek(0, 0) - self.assertEqual(bufio.write(b"XY"), 2) - bufio.seek(6, 0) - self.assertEqual(raw.getvalue(), b"XYcdef") - self.assertEqual(bufio.write(b"123456"), 6) - bufio.flush() - self.assertEqual(raw.getvalue(), b"XYcdef123456") - - def test_flush(self): - writer = self.MockRawIO() - bufio = self.tp(writer, 8) - bufio.write(b"abc") - bufio.flush() - self.assertEqual(b"abc", writer._write_stack[0]) - - def test_writelines(self): - l = [b'ab', b'cd', b'ef'] - writer = self.MockRawIO() - bufio = self.tp(writer, 8) - bufio.writelines(l) - bufio.flush() - self.assertEqual(b''.join(writer._write_stack), b'abcdef') - - def test_writelines_userlist(self): - l = UserList([b'ab', b'cd', b'ef']) - writer = self.MockRawIO() - bufio = self.tp(writer, 8) - bufio.writelines(l) - bufio.flush() - self.assertEqual(b''.join(writer._write_stack), b'abcdef') - - def test_writelines_error(self): - writer = self.MockRawIO() - bufio = self.tp(writer, 8) - self.assertRaises(TypeError, bufio.writelines, [1, 2, 3]) - self.assertRaises(TypeError, bufio.writelines, None) - self.assertRaises(TypeError, bufio.writelines, 'abc') - - def test_destructor(self): - writer = self.MockRawIO() - bufio = self.tp(writer, 8) - bufio.write(b"abc") - del bufio - support.gc_collect() - self.assertEqual(b"abc", writer._write_stack[0]) - - def test_truncate(self): - # Truncate implicitly flushes the buffer. - self.addCleanup(os_helper.unlink, os_helper.TESTFN) - with self.open(os_helper.TESTFN, self.write_mode, buffering=0) as raw: - bufio = self.tp(raw, 8) - bufio.write(b"abcdef") - self.assertEqual(bufio.truncate(3), 3) - self.assertEqual(bufio.tell(), 6) - with self.open(os_helper.TESTFN, "rb", buffering=0) as f: - self.assertEqual(f.read(), b"abc") - - def test_truncate_after_write(self): - # Ensure that truncate preserves the file position after - # writes longer than the buffer size. - # Issue: https://bugs.python.org/issue32228 - self.addCleanup(os_helper.unlink, os_helper.TESTFN) - with self.open(os_helper.TESTFN, "wb") as f: - # Fill with some buffer - f.write(b'\x00' * 10000) - buffer_sizes = [8192, 4096, 200] - for buffer_size in buffer_sizes: - with self.open(os_helper.TESTFN, "r+b", buffering=buffer_size) as f: - f.write(b'\x00' * (buffer_size + 1)) - # After write write_pos and write_end are set to 0 - f.read(1) - # read operation makes sure that pos != raw_pos - f.truncate() - self.assertEqual(f.tell(), buffer_size + 2) - - @threading_helper.requires_working_threading() - @support.requires_resource('cpu') - def test_threads(self): - try: - # Write out many bytes from many threads and test they were - # all flushed. - N = 1000 - contents = bytes(range(256)) * N - sizes = cycle([1, 19]) - n = 0 - queue = deque() - while n < len(contents): - size = next(sizes) - queue.append(contents[n:n+size]) - n += size - del contents - # We use a real file object because it allows us to - # exercise situations where the GIL is released before - # writing the buffer to the raw streams. This is in addition - # to concurrency issues due to switching threads in the middle - # of Python code. - with self.open(os_helper.TESTFN, self.write_mode, buffering=0) as raw: - bufio = self.tp(raw, 8) - errors = [] - def f(): - try: - while True: - try: - s = queue.popleft() - except IndexError: - return - bufio.write(s) - except Exception as e: - errors.append(e) - raise - threads = [threading.Thread(target=f) for x in range(20)] - with threading_helper.start_threads(threads): - time.sleep(0.02) # yield - self.assertFalse(errors, - "the following exceptions were caught: %r" % errors) - bufio.close() - with self.open(os_helper.TESTFN, "rb") as f: - s = f.read() - for i in range(256): - self.assertEqual(s.count(bytes([i])), N) - finally: - os_helper.unlink(os_helper.TESTFN) - - def test_misbehaved_io(self): - rawio = self.MisbehavedRawIO() - bufio = self.tp(rawio, 5) - self.assertRaises(OSError, bufio.seek, 0) - self.assertRaises(OSError, bufio.tell) - self.assertRaises(OSError, bufio.write, b"abcdef") - - # Silence destructor error - bufio.close = lambda: None - - def test_max_buffer_size_removal(self): - with self.assertRaises(TypeError): - self.tp(self.MockRawIO(), 8, 12) - - def test_write_error_on_close(self): - raw = self.MockRawIO() - def bad_write(b): - raise OSError() - raw.write = bad_write - b = self.tp(raw) - b.write(b'spam') - self.assertRaises(OSError, b.close) # exception not swallowed - self.assertTrue(b.closed) - - @threading_helper.requires_working_threading() - def test_slow_close_from_thread(self): - # Issue #31976 - rawio = self.SlowFlushRawIO() - bufio = self.tp(rawio, 8) - t = threading.Thread(target=bufio.close) - t.start() - rawio.in_flush.wait() - self.assertRaises(ValueError, bufio.write, b'spam') - self.assertTrue(bufio.closed) - t.join() - - - -class CBufferedWriterTest(BufferedWriterTest, SizeofTest): - tp = io.BufferedWriter - - def test_initialization(self): - rawio = self.MockRawIO() - bufio = self.tp(rawio) - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) - self.assertRaises(ValueError, bufio.write, b"def") - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) - self.assertRaises(ValueError, bufio.write, b"def") - self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) - self.assertRaises(ValueError, bufio.write, b"def") - - @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON; cyclic GC not supported, causes file locking") - def test_garbage_collection(self): - # C BufferedWriter objects are collected, and collecting them flushes - # all data to disk. - # The Python version has __del__, so it ends into gc.garbage instead - self.addCleanup(os_helper.unlink, os_helper.TESTFN) - with warnings_helper.check_warnings(('', ResourceWarning)): - rawio = self.FileIO(os_helper.TESTFN, "w+b") - f = self.tp(rawio) - f.write(b"123xxx") - f.x = f - wr = weakref.ref(f) - del f - support.gc_collect() - self.assertIsNone(wr(), wr) - with self.open(os_helper.TESTFN, "rb") as f: - self.assertEqual(f.read(), b"123xxx") - - def test_args_error(self): - # Issue #17275 - with self.assertRaisesRegex(TypeError, "BufferedWriter"): - self.tp(self.BytesIO(), 1024, 1024, 1024) - - -class PyBufferedWriterTest(BufferedWriterTest): - tp = pyio.BufferedWriter - -class BufferedRWPairTest(unittest.TestCase): - - def test_constructor(self): - pair = self.tp(self.MockRawIO(), self.MockRawIO()) - self.assertFalse(pair.closed) - - def test_uninitialized(self): - pair = self.tp.__new__(self.tp) - del pair - pair = self.tp.__new__(self.tp) - self.assertRaisesRegex((ValueError, AttributeError), - 'uninitialized|has no attribute', - pair.read, 0) - self.assertRaisesRegex((ValueError, AttributeError), - 'uninitialized|has no attribute', - pair.write, b'') - pair.__init__(self.MockRawIO(), self.MockRawIO()) - self.assertEqual(pair.read(0), b'') - self.assertEqual(pair.write(b''), 0) - - def test_detach(self): - pair = self.tp(self.MockRawIO(), self.MockRawIO()) - self.assertRaises(self.UnsupportedOperation, pair.detach) - - def test_constructor_max_buffer_size_removal(self): - with self.assertRaises(TypeError): - self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) - - def test_constructor_with_not_readable(self): - class NotReadable(MockRawIO): - def readable(self): - return False - - self.assertRaises(OSError, self.tp, NotReadable(), self.MockRawIO()) - - def test_constructor_with_not_writeable(self): - class NotWriteable(MockRawIO): - def writable(self): - return False - - self.assertRaises(OSError, self.tp, self.MockRawIO(), NotWriteable()) - - def test_read(self): - pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) - - self.assertEqual(pair.read(3), b"abc") - self.assertEqual(pair.read(1), b"d") - self.assertEqual(pair.read(), b"ef") - pair = self.tp(self.BytesIO(b"abc"), self.MockRawIO()) - self.assertEqual(pair.read(None), b"abc") - - def test_readlines(self): - pair = lambda: self.tp(self.BytesIO(b"abc\ndef\nh"), self.MockRawIO()) - self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) - self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) - self.assertEqual(pair().readlines(5), [b"abc\n", b"def\n"]) - - def test_read1(self): - # .read1() is delegated to the underlying reader object, so this test - # can be shallow. - pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) - - self.assertEqual(pair.read1(3), b"abc") - self.assertEqual(pair.read1(), b"def") - - def test_readinto(self): - for method in ("readinto", "readinto1"): - with self.subTest(method): - pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) - - data = byteslike(b'\0' * 5) - self.assertEqual(getattr(pair, method)(data), 5) - self.assertEqual(bytes(data), b"abcde") - - def test_write(self): - w = self.MockRawIO() - pair = self.tp(self.MockRawIO(), w) - - pair.write(b"abc") - pair.flush() - buffer = bytearray(b"def") - pair.write(buffer) - buffer[:] = b"***" # Overwrite our copy of the data - pair.flush() - self.assertEqual(w._write_stack, [b"abc", b"def"]) - - def test_peek(self): - pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) - - self.assertStartsWith(pair.peek(3), b"abc") - self.assertEqual(pair.read(3), b"abc") - - def test_readable(self): - pair = self.tp(self.MockRawIO(), self.MockRawIO()) - self.assertTrue(pair.readable()) - - def test_writeable(self): - pair = self.tp(self.MockRawIO(), self.MockRawIO()) - self.assertTrue(pair.writable()) - - def test_seekable(self): - # BufferedRWPairs are never seekable, even if their readers and writers - # are. - pair = self.tp(self.MockRawIO(), self.MockRawIO()) - self.assertFalse(pair.seekable()) - - # .flush() is delegated to the underlying writer object and has been - # tested in the test_write method. - - def test_close_and_closed(self): - pair = self.tp(self.MockRawIO(), self.MockRawIO()) - self.assertFalse(pair.closed) - pair.close() - self.assertTrue(pair.closed) - - def test_reader_close_error_on_close(self): - def reader_close(): - reader_non_existing - reader = self.MockRawIO() - reader.close = reader_close - writer = self.MockRawIO() - pair = self.tp(reader, writer) - with self.assertRaises(NameError) as err: - pair.close() - self.assertIn('reader_non_existing', str(err.exception)) - self.assertTrue(pair.closed) - self.assertFalse(reader.closed) - self.assertTrue(writer.closed) - - # Silence destructor error - reader.close = lambda: None - - def test_writer_close_error_on_close(self): - def writer_close(): - writer_non_existing - reader = self.MockRawIO() - writer = self.MockRawIO() - writer.close = writer_close - pair = self.tp(reader, writer) - with self.assertRaises(NameError) as err: - pair.close() - self.assertIn('writer_non_existing', str(err.exception)) - self.assertFalse(pair.closed) - self.assertTrue(reader.closed) - self.assertFalse(writer.closed) - - # Silence destructor error - writer.close = lambda: None - writer = None - - # Ignore BufferedWriter (of the BufferedRWPair) unraisable exception - with support.catch_unraisable_exception(): - # Ignore BufferedRWPair unraisable exception - with support.catch_unraisable_exception(): - pair = None - support.gc_collect() - support.gc_collect() - - def test_reader_writer_close_error_on_close(self): - def reader_close(): - reader_non_existing - def writer_close(): - writer_non_existing - reader = self.MockRawIO() - reader.close = reader_close - writer = self.MockRawIO() - writer.close = writer_close - pair = self.tp(reader, writer) - with self.assertRaises(NameError) as err: - pair.close() - self.assertIn('reader_non_existing', str(err.exception)) - self.assertIsInstance(err.exception.__context__, NameError) - self.assertIn('writer_non_existing', str(err.exception.__context__)) - self.assertFalse(pair.closed) - self.assertFalse(reader.closed) - self.assertFalse(writer.closed) - - # Silence destructor error - reader.close = lambda: None - writer.close = lambda: None - - def test_isatty(self): - class SelectableIsAtty(MockRawIO): - def __init__(self, isatty): - MockRawIO.__init__(self) - self._isatty = isatty - - def isatty(self): - return self._isatty - - pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(False)) - self.assertFalse(pair.isatty()) - - pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(False)) - self.assertTrue(pair.isatty()) - - pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(True)) - self.assertTrue(pair.isatty()) - - pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True)) - self.assertTrue(pair.isatty()) - - def test_weakref_clearing(self): - brw = self.tp(self.MockRawIO(), self.MockRawIO()) - ref = weakref.ref(brw) - brw = None - ref = None # Shouldn't segfault. - -class CBufferedRWPairTest(BufferedRWPairTest): - tp = io.BufferedRWPair - -class PyBufferedRWPairTest(BufferedRWPairTest): - tp = pyio.BufferedRWPair - - -class BufferedRandomTest(BufferedReaderTest, BufferedWriterTest): - read_mode = "rb+" - write_mode = "wb+" - - def test_constructor(self): - BufferedReaderTest.test_constructor(self) - BufferedWriterTest.test_constructor(self) - - def test_uninitialized(self): - BufferedReaderTest.test_uninitialized(self) - BufferedWriterTest.test_uninitialized(self) - - def test_read_and_write(self): - raw = self.MockRawIO((b"asdf", b"ghjk")) - rw = self.tp(raw, 8) - - self.assertEqual(b"as", rw.read(2)) - rw.write(b"ddd") - rw.write(b"eee") - self.assertFalse(raw._write_stack) # Buffer writes - self.assertEqual(b"ghjk", rw.read()) - self.assertEqual(b"dddeee", raw._write_stack[0]) - - def test_seek_and_tell(self): - raw = self.BytesIO(b"asdfghjkl") - rw = self.tp(raw) - - self.assertEqual(b"as", rw.read(2)) - self.assertEqual(2, rw.tell()) - rw.seek(0, 0) - self.assertEqual(b"asdf", rw.read(4)) - - rw.write(b"123f") - rw.seek(0, 0) - self.assertEqual(b"asdf123fl", rw.read()) - self.assertEqual(9, rw.tell()) - rw.seek(-4, 2) - self.assertEqual(5, rw.tell()) - rw.seek(2, 1) - self.assertEqual(7, rw.tell()) - self.assertEqual(b"fl", rw.read(11)) - rw.flush() - self.assertEqual(b"asdf123fl", raw.getvalue()) - - self.assertRaises(TypeError, rw.seek, 0.0) - - def check_flush_and_read(self, read_func): - raw = self.BytesIO(b"abcdefghi") - bufio = self.tp(raw) - - self.assertEqual(b"ab", read_func(bufio, 2)) - bufio.write(b"12") - self.assertEqual(b"ef", read_func(bufio, 2)) - self.assertEqual(6, bufio.tell()) - bufio.flush() - self.assertEqual(6, bufio.tell()) - self.assertEqual(b"ghi", read_func(bufio)) - raw.seek(0, 0) - raw.write(b"XYZ") - # flush() resets the read buffer - bufio.flush() - bufio.seek(0, 0) - self.assertEqual(b"XYZ", read_func(bufio, 3)) - - def test_flush_and_read(self): - self.check_flush_and_read(lambda bufio, *args: bufio.read(*args)) - - def test_flush_and_readinto(self): - def _readinto(bufio, n=-1): - b = bytearray(n if n >= 0 else 9999) - n = bufio.readinto(b) - return bytes(b[:n]) - self.check_flush_and_read(_readinto) - - def test_flush_and_peek(self): - def _peek(bufio, n=-1): - # This relies on the fact that the buffer can contain the whole - # raw stream, otherwise peek() can return less. - b = bufio.peek(n) - if n != -1: - b = b[:n] - bufio.seek(len(b), 1) - return b - self.check_flush_and_read(_peek) - - def test_flush_and_write(self): - raw = self.BytesIO(b"abcdefghi") - bufio = self.tp(raw) - - bufio.write(b"123") - bufio.flush() - bufio.write(b"45") - bufio.flush() - bufio.seek(0, 0) - self.assertEqual(b"12345fghi", raw.getvalue()) - self.assertEqual(b"12345fghi", bufio.read()) - - def test_threads(self): - BufferedReaderTest.test_threads(self) - BufferedWriterTest.test_threads(self) - - def test_writes_and_peek(self): - def _peek(bufio): - bufio.peek(1) - self.check_writes(_peek) - def _peek(bufio): - pos = bufio.tell() - bufio.seek(-1, 1) - bufio.peek(1) - bufio.seek(pos, 0) - self.check_writes(_peek) - - def test_writes_and_reads(self): - def _read(bufio): - bufio.seek(-1, 1) - bufio.read(1) - self.check_writes(_read) - - def test_writes_and_read1s(self): - def _read1(bufio): - bufio.seek(-1, 1) - bufio.read1(1) - self.check_writes(_read1) - - def test_writes_and_readintos(self): - def _read(bufio): - bufio.seek(-1, 1) - bufio.readinto(bytearray(1)) - self.check_writes(_read) - - def test_write_after_readahead(self): - # Issue #6629: writing after the buffer was filled by readahead should - # first rewind the raw stream. - for overwrite_size in [1, 5]: - raw = self.BytesIO(b"A" * 10) - bufio = self.tp(raw, 4) - # Trigger readahead - self.assertEqual(bufio.read(1), b"A") - self.assertEqual(bufio.tell(), 1) - # Overwriting should rewind the raw stream if it needs so - bufio.write(b"B" * overwrite_size) - self.assertEqual(bufio.tell(), overwrite_size + 1) - # If the write size was smaller than the buffer size, flush() and - # check that rewind happens. - bufio.flush() - self.assertEqual(bufio.tell(), overwrite_size + 1) - s = raw.getvalue() - self.assertEqual(s, - b"A" + b"B" * overwrite_size + b"A" * (9 - overwrite_size)) - - def test_write_rewind_write(self): - # Various combinations of reading / writing / seeking backwards / writing again - def mutate(bufio, pos1, pos2): - assert pos2 >= pos1 - # Fill the buffer - bufio.seek(pos1) - bufio.read(pos2 - pos1) - bufio.write(b'\x02') - # This writes earlier than the previous write, but still inside - # the buffer. - bufio.seek(pos1) - bufio.write(b'\x01') - - b = b"\x80\x81\x82\x83\x84" - for i in range(0, len(b)): - for j in range(i, len(b)): - raw = self.BytesIO(b) - bufio = self.tp(raw, 100) - mutate(bufio, i, j) - bufio.flush() - expected = bytearray(b) - expected[j] = 2 - expected[i] = 1 - self.assertEqual(raw.getvalue(), expected, - "failed result for i=%d, j=%d" % (i, j)) - - def test_truncate_after_read_or_write(self): - raw = self.BytesIO(b"A" * 10) - bufio = self.tp(raw, 100) - self.assertEqual(bufio.read(2), b"AA") # the read buffer gets filled - self.assertEqual(bufio.truncate(), 2) - self.assertEqual(bufio.write(b"BB"), 2) # the write buffer increases - self.assertEqual(bufio.truncate(), 4) - - def test_misbehaved_io(self): - BufferedReaderTest.test_misbehaved_io(self) - BufferedWriterTest.test_misbehaved_io(self) - - def test_interleaved_read_write(self): - # Test for issue #12213 - with self.BytesIO(b'abcdefgh') as raw: - with self.tp(raw, 100) as f: - f.write(b"1") - self.assertEqual(f.read(1), b'b') - f.write(b'2') - self.assertEqual(f.read1(1), b'd') - f.write(b'3') - buf = bytearray(1) - f.readinto(buf) - self.assertEqual(buf, b'f') - f.write(b'4') - self.assertEqual(f.peek(1), b'h') - f.flush() - self.assertEqual(raw.getvalue(), b'1b2d3f4h') - - with self.BytesIO(b'abc') as raw: - with self.tp(raw, 100) as f: - self.assertEqual(f.read(1), b'a') - f.write(b"2") - self.assertEqual(f.read(1), b'c') - f.flush() - self.assertEqual(raw.getvalue(), b'a2c') - - def test_read1_after_write(self): - with self.BytesIO(b'abcdef') as raw: - with self.tp(raw, 3) as f: - f.write(b"1") - self.assertEqual(f.read1(1), b'b') - f.flush() - self.assertEqual(raw.getvalue(), b'1bcdef') - with self.BytesIO(b'abcdef') as raw: - with self.tp(raw, 3) as f: - f.write(b"1") - self.assertEqual(f.read1(), b'bcd') - f.flush() - self.assertEqual(raw.getvalue(), b'1bcdef') - with self.BytesIO(b'abcdef') as raw: - with self.tp(raw, 3) as f: - f.write(b"1") - # XXX: read(100) returns different numbers of bytes - # in Python and C implementations. - self.assertEqual(f.read1(100)[:3], b'bcd') - f.flush() - self.assertEqual(raw.getvalue(), b'1bcdef') - - def test_interleaved_readline_write(self): - with self.BytesIO(b'ab\ncdef\ng\n') as raw: - with self.tp(raw) as f: - f.write(b'1') - self.assertEqual(f.readline(), b'b\n') - f.write(b'2') - self.assertEqual(f.readline(), b'def\n') - f.write(b'3') - self.assertEqual(f.readline(), b'\n') - f.flush() - self.assertEqual(raw.getvalue(), b'1b\n2def\n3\n') - - # You can't construct a BufferedRandom over a non-seekable stream. - test_unseekable = None - - # writable() returns True, so there's no point to test it over - # a writable stream. - test_truncate_on_read_only = None - - -class CBufferedRandomTest(BufferedRandomTest, SizeofTest): - tp = io.BufferedRandom - - @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON; cyclic GC not supported, causes file locking") - def test_garbage_collection(self): - CBufferedReaderTest.test_garbage_collection(self) - CBufferedWriterTest.test_garbage_collection(self) - - def test_args_error(self): - # Issue #17275 - with self.assertRaisesRegex(TypeError, "BufferedRandom"): - self.tp(self.BytesIO(), 1024, 1024, 1024) - - -class PyBufferedRandomTest(BufferedRandomTest): - tp = pyio.BufferedRandom - - -# To fully exercise seek/tell, the StatefulIncrementalDecoder has these -# properties: -# - A single output character can correspond to many bytes of input. -# - The number of input bytes to complete the character can be -# undetermined until the last input byte is received. -# - The number of input bytes can vary depending on previous input. -# - A single input byte can correspond to many characters of output. -# - The number of output characters can be undetermined until the -# last input byte is received. -# - The number of output characters can vary depending on previous input. - -class StatefulIncrementalDecoder(codecs.IncrementalDecoder): - """ - For testing seek/tell behavior with a stateful, buffering decoder. - - Input is a sequence of words. Words may be fixed-length (length set - by input) or variable-length (period-terminated). In variable-length - mode, extra periods are ignored. Possible words are: - - 'i' followed by a number sets the input length, I (maximum 99). - When I is set to 0, words are space-terminated. - - 'o' followed by a number sets the output length, O (maximum 99). - - Any other word is converted into a word followed by a period on - the output. The output word consists of the input word truncated - or padded out with hyphens to make its length equal to O. If O - is 0, the word is output verbatim without truncating or padding. - I and O are initially set to 1. When I changes, any buffered input is - re-scanned according to the new I. EOF also terminates the last word. - """ - - def __init__(self, errors='strict'): - codecs.IncrementalDecoder.__init__(self, errors) - self.reset() - - def __repr__(self): - return '' % id(self) - - def reset(self): - self.i = 1 - self.o = 1 - self.buffer = bytearray() - - def getstate(self): - i, o = self.i ^ 1, self.o ^ 1 # so that flags = 0 after reset() - return bytes(self.buffer), i*100 + o - - def setstate(self, state): - buffer, io = state - self.buffer = bytearray(buffer) - i, o = divmod(io, 100) - self.i, self.o = i ^ 1, o ^ 1 - - def decode(self, input, final=False): - output = '' - for b in input: - if self.i == 0: # variable-length, terminated with period - if b == ord('.'): - if self.buffer: - output += self.process_word() - else: - self.buffer.append(b) - else: # fixed-length, terminate after self.i bytes - self.buffer.append(b) - if len(self.buffer) == self.i: - output += self.process_word() - if final and self.buffer: # EOF terminates the last word - output += self.process_word() - return output - - def process_word(self): - output = '' - if self.buffer[0] == ord('i'): - self.i = min(99, int(self.buffer[1:] or 0)) # set input length - elif self.buffer[0] == ord('o'): - self.o = min(99, int(self.buffer[1:] or 0)) # set output length - else: - output = self.buffer.decode('ascii') - if len(output) < self.o: - output += '-'*self.o # pad out with hyphens - if self.o: - output = output[:self.o] # truncate to output length - output += '.' - self.buffer = bytearray() - return output - - codecEnabled = False - - -# bpo-41919: This method is separated from StatefulIncrementalDecoder to avoid a resource leak -# when registering codecs and cleanup functions. -def lookupTestDecoder(name): - if StatefulIncrementalDecoder.codecEnabled and name == 'test_decoder': - latin1 = codecs.lookup('latin-1') - return codecs.CodecInfo( - name='test_decoder', encode=latin1.encode, decode=None, - incrementalencoder=None, - streamreader=None, streamwriter=None, - incrementaldecoder=StatefulIncrementalDecoder) - - -class StatefulIncrementalDecoderTest(unittest.TestCase): - """ - Make sure the StatefulIncrementalDecoder actually works. - """ - - test_cases = [ - # I=1, O=1 (fixed-length input == fixed-length output) - (b'abcd', False, 'a.b.c.d.'), - # I=0, O=0 (variable-length input, variable-length output) - (b'oiabcd', True, 'abcd.'), - # I=0, O=0 (should ignore extra periods) - (b'oi...abcd...', True, 'abcd.'), - # I=0, O=6 (variable-length input, fixed-length output) - (b'i.o6.x.xyz.toolongtofit.', False, 'x-----.xyz---.toolon.'), - # I=2, O=6 (fixed-length input < fixed-length output) - (b'i.i2.o6xyz', True, 'xy----.z-----.'), - # I=6, O=3 (fixed-length input > fixed-length output) - (b'i.o3.i6.abcdefghijklmnop', True, 'abc.ghi.mno.'), - # I=0, then 3; O=29, then 15 (with longer output) - (b'i.o29.a.b.cde.o15.abcdefghijabcdefghij.i3.a.b.c.d.ei00k.l.m', True, - 'a----------------------------.' + - 'b----------------------------.' + - 'cde--------------------------.' + - 'abcdefghijabcde.' + - 'a.b------------.' + - '.c.------------.' + - 'd.e------------.' + - 'k--------------.' + - 'l--------------.' + - 'm--------------.') - ] - - def test_decoder(self): - # Try a few one-shot test cases. - for input, eof, output in self.test_cases: - d = StatefulIncrementalDecoder() - self.assertEqual(d.decode(input, eof), output) - - # Also test an unfinished decode, followed by forcing EOF. - d = StatefulIncrementalDecoder() - self.assertEqual(d.decode(b'oiabcd'), '') - self.assertEqual(d.decode(b'', 1), 'abcd.') - -class TextIOWrapperTest(unittest.TestCase): - - def setUp(self): - self.testdata = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n" - self.normalized = b"AAA\nBBB\nCCC\nDDD\nEEE\n".decode("ascii") - os_helper.unlink(os_helper.TESTFN) - codecs.register(lookupTestDecoder) - self.addCleanup(codecs.unregister, lookupTestDecoder) - - def tearDown(self): - os_helper.unlink(os_helper.TESTFN) - - def test_constructor(self): - r = self.BytesIO(b"\xc3\xa9\n\n") - b = self.BufferedReader(r, 1000) - t = self.TextIOWrapper(b, encoding="utf-8") - t.__init__(b, encoding="latin-1", newline="\r\n") - self.assertEqual(t.encoding, "latin-1") - self.assertEqual(t.line_buffering, False) - t.__init__(b, encoding="utf-8", line_buffering=True) - self.assertEqual(t.encoding, "utf-8") - self.assertEqual(t.line_buffering, True) - self.assertEqual("\xe9\n", t.readline()) - invalid_type = TypeError if self.is_C else ValueError - with self.assertRaises(invalid_type): - t.__init__(b, encoding=42) - with self.assertRaises(UnicodeEncodeError): - t.__init__(b, encoding='\udcfe') - with self.assertRaises(ValueError): - t.__init__(b, encoding='utf-8\0') - with self.assertRaises(invalid_type): - t.__init__(b, encoding="utf-8", errors=42) - if support.Py_DEBUG or sys.flags.dev_mode or self.is_C: - with self.assertRaises(UnicodeEncodeError): - t.__init__(b, encoding="utf-8", errors='\udcfe') - if support.Py_DEBUG or sys.flags.dev_mode or self.is_C: - with self.assertRaises(ValueError): - t.__init__(b, encoding="utf-8", errors='replace\0') - with self.assertRaises(TypeError): - t.__init__(b, encoding="utf-8", newline=42) - with self.assertRaises(ValueError): - t.__init__(b, encoding="utf-8", newline='\udcfe') - with self.assertRaises(ValueError): - t.__init__(b, encoding="utf-8", newline='\n\0') - with self.assertRaises(ValueError): - t.__init__(b, encoding="utf-8", newline='xyzzy') - - def test_uninitialized(self): - t = self.TextIOWrapper.__new__(self.TextIOWrapper) - del t - t = self.TextIOWrapper.__new__(self.TextIOWrapper) - self.assertRaises(Exception, repr, t) - self.assertRaisesRegex((ValueError, AttributeError), - 'uninitialized|has no attribute', - t.read, 0) - t.__init__(self.MockRawIO(), encoding="utf-8") - self.assertEqual(t.read(0), '') - - def test_non_text_encoding_codecs_are_rejected(self): - # Ensure the constructor complains if passed a codec that isn't - # marked as a text encoding - # http://bugs.python.org/issue20404 - r = self.BytesIO() - b = self.BufferedWriter(r) - with self.assertRaisesRegex(LookupError, "is not a text encoding"): - self.TextIOWrapper(b, encoding="hex") - - def test_detach(self): - r = self.BytesIO() - b = self.BufferedWriter(r) - t = self.TextIOWrapper(b, encoding="ascii") - self.assertIs(t.detach(), b) - - t = self.TextIOWrapper(b, encoding="ascii") - t.write("howdy") - self.assertFalse(r.getvalue()) - t.detach() - self.assertEqual(r.getvalue(), b"howdy") - self.assertRaises(ValueError, t.detach) - - # Operations independent of the detached stream should still work - repr(t) - self.assertEqual(t.encoding, "ascii") - self.assertEqual(t.errors, "strict") - self.assertFalse(t.line_buffering) - self.assertFalse(t.write_through) - - def test_repr(self): - raw = self.BytesIO("hello".encode("utf-8")) - b = self.BufferedReader(raw) - t = self.TextIOWrapper(b, encoding="utf-8") - modname = self.TextIOWrapper.__module__ - self.assertRegex(repr(t), - r"<(%s\.)?TextIOWrapper encoding='utf-8'>" % modname) - raw.name = "dummy" - self.assertRegex(repr(t), - r"<(%s\.)?TextIOWrapper name='dummy' encoding='utf-8'>" % modname) - t.mode = "r" - self.assertRegex(repr(t), - r"<(%s\.)?TextIOWrapper name='dummy' mode='r' encoding='utf-8'>" % modname) - raw.name = b"dummy" - self.assertRegex(repr(t), - r"<(%s\.)?TextIOWrapper name=b'dummy' mode='r' encoding='utf-8'>" % modname) - - t.buffer.detach() - repr(t) # Should not raise an exception - - def test_recursive_repr(self): - # Issue #25455 - raw = self.BytesIO() - t = self.TextIOWrapper(raw, encoding="utf-8") - with support.swap_attr(raw, 'name', t), support.infinite_recursion(25): - with self.assertRaises(RuntimeError): - repr(t) # Should not crash - - def test_subclass_repr(self): - class TestSubclass(self.TextIOWrapper): - pass - - f = TestSubclass(self.StringIO()) - self.assertIn(TestSubclass.__name__, repr(f)) - - def test_line_buffering(self): - r = self.BytesIO() - b = self.BufferedWriter(r, 1000) - t = self.TextIOWrapper(b, encoding="utf-8", newline="\n", line_buffering=True) - t.write("X") - self.assertEqual(r.getvalue(), b"") # No flush happened - t.write("Y\nZ") - self.assertEqual(r.getvalue(), b"XY\nZ") # All got flushed - t.write("A\rB") - self.assertEqual(r.getvalue(), b"XY\nZA\rB") - - def test_reconfigure_line_buffering(self): - r = self.BytesIO() - b = self.BufferedWriter(r, 1000) - t = self.TextIOWrapper(b, encoding="utf-8", newline="\n", line_buffering=False) - t.write("AB\nC") - self.assertEqual(r.getvalue(), b"") - - t.reconfigure(line_buffering=True) # implicit flush - self.assertEqual(r.getvalue(), b"AB\nC") - t.write("DEF\nG") - self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") - t.write("H") - self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") - t.reconfigure(line_buffering=False) # implicit flush - self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") - t.write("IJ") - self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") - - # Keeping default value - t.reconfigure() - t.reconfigure(line_buffering=None) - self.assertEqual(t.line_buffering, False) - t.reconfigure(line_buffering=True) - t.reconfigure() - t.reconfigure(line_buffering=None) - self.assertEqual(t.line_buffering, True) - - @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled") - def test_default_encoding(self): - with os_helper.EnvironmentVarGuard() as env: - # try to get a user preferred encoding different than the current - # locale encoding to check that TextIOWrapper() uses the current - # locale encoding and not the user preferred encoding - env.unset('LC_ALL', 'LANG', 'LC_CTYPE') - - current_locale_encoding = locale.getencoding() - b = self.BytesIO() - with warnings.catch_warnings(): - warnings.simplefilter("ignore", EncodingWarning) - t = self.TextIOWrapper(b) - self.assertEqual(t.encoding, current_locale_encoding) - - def test_encoding(self): - # Check the encoding attribute is always set, and valid - b = self.BytesIO() - t = self.TextIOWrapper(b, encoding="utf-8") - self.assertEqual(t.encoding, "utf-8") - with warnings.catch_warnings(): - warnings.simplefilter("ignore", EncodingWarning) - t = self.TextIOWrapper(b) - self.assertIsNotNone(t.encoding) - codecs.lookup(t.encoding) - - def test_encoding_errors_reading(self): - # (1) default - b = self.BytesIO(b"abc\n\xff\n") - t = self.TextIOWrapper(b, encoding="ascii") - self.assertRaises(UnicodeError, t.read) - # (2) explicit strict - b = self.BytesIO(b"abc\n\xff\n") - t = self.TextIOWrapper(b, encoding="ascii", errors="strict") - self.assertRaises(UnicodeError, t.read) - # (3) ignore - b = self.BytesIO(b"abc\n\xff\n") - t = self.TextIOWrapper(b, encoding="ascii", errors="ignore") - self.assertEqual(t.read(), "abc\n\n") - # (4) replace - b = self.BytesIO(b"abc\n\xff\n") - t = self.TextIOWrapper(b, encoding="ascii", errors="replace") - self.assertEqual(t.read(), "abc\n\ufffd\n") - - def test_encoding_errors_writing(self): - # (1) default - b = self.BytesIO() - t = self.TextIOWrapper(b, encoding="ascii") - self.assertRaises(UnicodeError, t.write, "\xff") - # (2) explicit strict - b = self.BytesIO() - t = self.TextIOWrapper(b, encoding="ascii", errors="strict") - self.assertRaises(UnicodeError, t.write, "\xff") - # (3) ignore - b = self.BytesIO() - t = self.TextIOWrapper(b, encoding="ascii", errors="ignore", - newline="\n") - t.write("abc\xffdef\n") - t.flush() - self.assertEqual(b.getvalue(), b"abcdef\n") - # (4) replace - b = self.BytesIO() - t = self.TextIOWrapper(b, encoding="ascii", errors="replace", - newline="\n") - t.write("abc\xffdef\n") - t.flush() - self.assertEqual(b.getvalue(), b"abc?def\n") - - def test_newlines(self): - input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ] - - tests = [ - [ None, [ 'unix\n', 'windows\n', 'os9\n', 'last\n', 'nonl' ] ], - [ '', input_lines ], - [ '\n', [ "unix\n", "windows\r\n", "os9\rlast\n", "nonl" ] ], - [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ], - [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ], - ] - encodings = ( - 'utf-8', 'latin-1', - 'utf-16', 'utf-16-le', 'utf-16-be', - 'utf-32', 'utf-32-le', 'utf-32-be', - ) - - # Try a range of buffer sizes to test the case where \r is the last - # character in TextIOWrapper._pending_line. - for encoding in encodings: - # XXX: str.encode() should return bytes - data = bytes(''.join(input_lines).encode(encoding)) - for do_reads in (False, True): - for bufsize in range(1, 10): - for newline, exp_lines in tests: - bufio = self.BufferedReader(self.BytesIO(data), bufsize) - textio = self.TextIOWrapper(bufio, newline=newline, - encoding=encoding) - if do_reads: - got_lines = [] - while True: - c2 = textio.read(2) - if c2 == '': - break - self.assertEqual(len(c2), 2) - got_lines.append(c2 + textio.readline()) - else: - got_lines = list(textio) - - for got_line, exp_line in zip(got_lines, exp_lines): - self.assertEqual(got_line, exp_line) - self.assertEqual(len(got_lines), len(exp_lines)) - - def test_newlines_input(self): - testdata = b"AAA\nBB\x00B\nCCC\rDDD\rEEE\r\nFFF\r\nGGG" - normalized = testdata.replace(b"\r\n", b"\n").replace(b"\r", b"\n") - for newline, expected in [ - (None, normalized.decode("ascii").splitlines(keepends=True)), - ("", testdata.decode("ascii").splitlines(keepends=True)), - ("\n", ["AAA\n", "BB\x00B\n", "CCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), - ("\r\n", ["AAA\nBB\x00B\nCCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), - ("\r", ["AAA\nBB\x00B\nCCC\r", "DDD\r", "EEE\r", "\nFFF\r", "\nGGG"]), - ]: - buf = self.BytesIO(testdata) - txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) - self.assertEqual(txt.readlines(), expected) - txt.seek(0) - self.assertEqual(txt.read(), "".join(expected)) - - def test_newlines_output(self): - testdict = { - "": b"AAA\nBBB\nCCC\nX\rY\r\nZ", - "\n": b"AAA\nBBB\nCCC\nX\rY\r\nZ", - "\r": b"AAA\rBBB\rCCC\rX\rY\r\rZ", - "\r\n": b"AAA\r\nBBB\r\nCCC\r\nX\rY\r\r\nZ", - } - tests = [(None, testdict[os.linesep])] + sorted(testdict.items()) - for newline, expected in tests: - buf = self.BytesIO() - txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) - txt.write("AAA\nB") - txt.write("BB\nCCC\n") - txt.write("X\rY\r\nZ") - txt.flush() - self.assertEqual(buf.closed, False) - self.assertEqual(buf.getvalue(), expected) - - def test_destructor(self): - l = [] - base = self.BytesIO - class MyBytesIO(base): - def close(self): - l.append(self.getvalue()) - base.close(self) - b = MyBytesIO() - t = self.TextIOWrapper(b, encoding="ascii") - t.write("abc") - del t - support.gc_collect() - self.assertEqual([b"abc"], l) - - def test_override_destructor(self): - record = [] - class MyTextIO(self.TextIOWrapper): - def __del__(self): - record.append(1) - try: - f = super().__del__ - except AttributeError: - pass - else: - f() - def close(self): - record.append(2) - super().close() - def flush(self): - record.append(3) - super().flush() - b = self.BytesIO() - t = MyTextIO(b, encoding="ascii") - del t - support.gc_collect() - self.assertEqual(record, [1, 2, 3]) - - def test_error_through_destructor(self): - # Test that the exception state is not modified by a destructor, - # even if close() fails. - rawio = self.CloseFailureIO() - with support.catch_unraisable_exception() as cm: - with self.assertRaises(AttributeError): - self.TextIOWrapper(rawio, encoding="utf-8").xyzzy - - self.assertEqual(cm.unraisable.exc_type, OSError) - - # Systematic tests of the text I/O API - - def test_basic_io(self): - for chunksize in (1, 2, 3, 4, 5, 15, 16, 17, 31, 32, 33, 63, 64, 65): - for enc in "ascii", "latin-1", "utf-8" :# , "utf-16-be", "utf-16-le": - f = self.open(os_helper.TESTFN, "w+", encoding=enc) - f._CHUNK_SIZE = chunksize - self.assertEqual(f.write("abc"), 3) - f.close() - f = self.open(os_helper.TESTFN, "r+", encoding=enc) - f._CHUNK_SIZE = chunksize - self.assertEqual(f.tell(), 0) - self.assertEqual(f.read(), "abc") - cookie = f.tell() - self.assertEqual(f.seek(0), 0) - self.assertEqual(f.read(None), "abc") - f.seek(0) - self.assertEqual(f.read(2), "ab") - self.assertEqual(f.read(1), "c") - self.assertEqual(f.read(1), "") - self.assertEqual(f.read(), "") - self.assertEqual(f.tell(), cookie) - self.assertEqual(f.seek(0), 0) - self.assertEqual(f.seek(0, 2), cookie) - self.assertEqual(f.write("def"), 3) - self.assertEqual(f.seek(cookie), cookie) - self.assertEqual(f.read(), "def") - if enc.startswith("utf"): - self.multi_line_test(f, enc) - f.close() - - def multi_line_test(self, f, enc): - f.seek(0) - f.truncate() - sample = "s\xff\u0fff\uffff" - wlines = [] - for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000): - chars = [] - for i in range(size): - chars.append(sample[i % len(sample)]) - line = "".join(chars) + "\n" - wlines.append((f.tell(), line)) - f.write(line) - f.seek(0) - rlines = [] - while True: - pos = f.tell() - line = f.readline() - if not line: - break - rlines.append((pos, line)) - self.assertEqual(rlines, wlines) - - def test_telling(self): - f = self.open(os_helper.TESTFN, "w+", encoding="utf-8") - p0 = f.tell() - f.write("\xff\n") - p1 = f.tell() - f.write("\xff\n") - p2 = f.tell() - f.seek(0) - self.assertEqual(f.tell(), p0) - self.assertEqual(f.readline(), "\xff\n") - self.assertEqual(f.tell(), p1) - self.assertEqual(f.readline(), "\xff\n") - self.assertEqual(f.tell(), p2) - f.seek(0) - for line in f: - self.assertEqual(line, "\xff\n") - self.assertRaises(OSError, f.tell) - self.assertEqual(f.tell(), p2) - f.close() - - def test_seeking(self): - chunk_size = _default_chunk_size() - prefix_size = chunk_size - 2 - u_prefix = "a" * prefix_size - prefix = bytes(u_prefix.encode("utf-8")) - self.assertEqual(len(u_prefix), len(prefix)) - u_suffix = "\u8888\n" - suffix = bytes(u_suffix.encode("utf-8")) - line = prefix + suffix - with self.open(os_helper.TESTFN, "wb") as f: - f.write(line*2) - with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: - s = f.read(prefix_size) - self.assertEqual(s, str(prefix, "ascii")) - self.assertEqual(f.tell(), prefix_size) - self.assertEqual(f.readline(), u_suffix) - - def test_seeking_too(self): - # Regression test for a specific bug - data = b'\xe0\xbf\xbf\n' - with self.open(os_helper.TESTFN, "wb") as f: - f.write(data) - with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: - f._CHUNK_SIZE # Just test that it exists - f._CHUNK_SIZE = 2 - f.readline() - f.tell() - - def test_seek_and_tell(self): - #Test seek/tell using the StatefulIncrementalDecoder. - # Make test faster by doing smaller seeks - CHUNK_SIZE = 128 - - def test_seek_and_tell_with_data(data, min_pos=0): - """Tell/seek to various points within a data stream and ensure - that the decoded data returned by read() is consistent.""" - f = self.open(os_helper.TESTFN, 'wb') - f.write(data) - f.close() - f = self.open(os_helper.TESTFN, encoding='test_decoder') - f._CHUNK_SIZE = CHUNK_SIZE - decoded = f.read() - f.close() - - for i in range(min_pos, len(decoded) + 1): # seek positions - for j in [1, 5, len(decoded) - i]: # read lengths - f = self.open(os_helper.TESTFN, encoding='test_decoder') - self.assertEqual(f.read(i), decoded[:i]) - cookie = f.tell() - self.assertEqual(f.read(j), decoded[i:i + j]) - f.seek(cookie) - self.assertEqual(f.read(), decoded[i:]) - f.close() - - # Enable the test decoder. - StatefulIncrementalDecoder.codecEnabled = 1 - - # Run the tests. - try: - # Try each test case. - for input, _, _ in StatefulIncrementalDecoderTest.test_cases: - test_seek_and_tell_with_data(input) - - # Position each test case so that it crosses a chunk boundary. - for input, _, _ in StatefulIncrementalDecoderTest.test_cases: - offset = CHUNK_SIZE - len(input)//2 - prefix = b'.'*offset - # Don't bother seeking into the prefix (takes too long). - min_pos = offset*2 - test_seek_and_tell_with_data(prefix + input, min_pos) - - # Ensure our test decoder won't interfere with subsequent tests. - finally: - StatefulIncrementalDecoder.codecEnabled = 0 - - def test_multibyte_seek_and_tell(self): - f = self.open(os_helper.TESTFN, "w", encoding="euc_jp") - f.write("AB\n\u3046\u3048\n") - f.close() - - f = self.open(os_helper.TESTFN, "r", encoding="euc_jp") - self.assertEqual(f.readline(), "AB\n") - p0 = f.tell() - self.assertEqual(f.readline(), "\u3046\u3048\n") - p1 = f.tell() - f.seek(p0) - self.assertEqual(f.readline(), "\u3046\u3048\n") - self.assertEqual(f.tell(), p1) - f.close() - - def test_tell_after_readline_with_cr(self): - # Test for gh-141314: TextIOWrapper.tell() assertion failure - # when dealing with standalone carriage returns - data = b'line1\r' - with self.open(os_helper.TESTFN, "wb") as f: - f.write(data) - - with self.open(os_helper.TESTFN, "r") as f: - # Read line that ends with \r - line = f.readline() - self.assertEqual(line, "line1\n") - # This should not cause an assertion failure - pos = f.tell() - # Verify we can seek back to this position - f.seek(pos) - remaining = f.read() - self.assertEqual(remaining, "") - - def test_seek_with_encoder_state(self): - f = self.open(os_helper.TESTFN, "w", encoding="euc_jis_2004") - f.write("\u00e6\u0300") - p0 = f.tell() - f.write("\u00e6") - f.seek(p0) - f.write("\u0300") - f.close() - - f = self.open(os_helper.TESTFN, "r", encoding="euc_jis_2004") - self.assertEqual(f.readline(), "\u00e6\u0300\u0300") - f.close() - - def test_encoded_writes(self): - data = "1234567890" - tests = ("utf-16", - "utf-16-le", - "utf-16-be", - "utf-32", - "utf-32-le", - "utf-32-be") - for encoding in tests: - buf = self.BytesIO() - f = self.TextIOWrapper(buf, encoding=encoding) - # Check if the BOM is written only once (see issue1753). - f.write(data) - f.write(data) - f.seek(0) - self.assertEqual(f.read(), data * 2) - f.seek(0) - self.assertEqual(f.read(), data * 2) - self.assertEqual(buf.getvalue(), (data * 2).encode(encoding)) - - def test_unreadable(self): - class UnReadable(self.BytesIO): - def readable(self): - return False - txt = self.TextIOWrapper(UnReadable(), encoding="utf-8") - self.assertRaises(OSError, txt.read) - - def test_read_one_by_one(self): - txt = self.TextIOWrapper(self.BytesIO(b"AA\r\nBB"), encoding="utf-8") - reads = "" - while True: - c = txt.read(1) - if not c: - break - reads += c - self.assertEqual(reads, "AA\nBB") - - def test_readlines(self): - txt = self.TextIOWrapper(self.BytesIO(b"AA\nBB\nCC"), encoding="utf-8") - self.assertEqual(txt.readlines(), ["AA\n", "BB\n", "CC"]) - txt.seek(0) - self.assertEqual(txt.readlines(None), ["AA\n", "BB\n", "CC"]) - txt.seek(0) - self.assertEqual(txt.readlines(5), ["AA\n", "BB\n"]) - - # read in amounts equal to TextIOWrapper._CHUNK_SIZE which is 128. - def test_read_by_chunk(self): - # make sure "\r\n" straddles 128 char boundary. - txt = self.TextIOWrapper(self.BytesIO(b"A" * 127 + b"\r\nB"), encoding="utf-8") - reads = "" - while True: - c = txt.read(128) - if not c: - break - reads += c - self.assertEqual(reads, "A"*127+"\nB") - - def test_writelines(self): - l = ['ab', 'cd', 'ef'] - buf = self.BytesIO() - txt = self.TextIOWrapper(buf, encoding="utf-8") - txt.writelines(l) - txt.flush() - self.assertEqual(buf.getvalue(), b'abcdef') - - def test_writelines_userlist(self): - l = UserList(['ab', 'cd', 'ef']) - buf = self.BytesIO() - txt = self.TextIOWrapper(buf, encoding="utf-8") - txt.writelines(l) - txt.flush() - self.assertEqual(buf.getvalue(), b'abcdef') - - def test_writelines_error(self): - txt = self.TextIOWrapper(self.BytesIO(), encoding="utf-8") - self.assertRaises(TypeError, txt.writelines, [1, 2, 3]) - self.assertRaises(TypeError, txt.writelines, None) - self.assertRaises(TypeError, txt.writelines, b'abc') - - def test_issue1395_1(self): - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - - # read one char at a time - reads = "" - while True: - c = txt.read(1) - if not c: - break - reads += c - self.assertEqual(reads, self.normalized) - - def test_issue1395_2(self): - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - txt._CHUNK_SIZE = 4 - - reads = "" - while True: - c = txt.read(4) - if not c: - break - reads += c - self.assertEqual(reads, self.normalized) - - def test_issue1395_3(self): - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - txt._CHUNK_SIZE = 4 - - reads = txt.read(4) - reads += txt.read(4) - reads += txt.readline() - reads += txt.readline() - reads += txt.readline() - self.assertEqual(reads, self.normalized) - - def test_issue1395_4(self): - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - txt._CHUNK_SIZE = 4 - - reads = txt.read(4) - reads += txt.read() - self.assertEqual(reads, self.normalized) - - def test_issue1395_5(self): - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - txt._CHUNK_SIZE = 4 - - reads = txt.read(4) - pos = txt.tell() - txt.seek(0) - txt.seek(pos) - self.assertEqual(txt.read(4), "BBB\n") - - def test_issue2282(self): - buffer = self.BytesIO(self.testdata) - txt = self.TextIOWrapper(buffer, encoding="ascii") - - self.assertEqual(buffer.seekable(), txt.seekable()) - - def test_append_bom(self): - # The BOM is not written again when appending to a non-empty file - filename = os_helper.TESTFN - for charset in ('utf-8-sig', 'utf-16', 'utf-32'): - with self.open(filename, 'w', encoding=charset) as f: - f.write('aaa') - pos = f.tell() - with self.open(filename, 'rb') as f: - self.assertEqual(f.read(), 'aaa'.encode(charset)) - - with self.open(filename, 'a', encoding=charset) as f: - f.write('xxx') - with self.open(filename, 'rb') as f: - self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) - - def test_seek_bom(self): - # Same test, but when seeking manually - filename = os_helper.TESTFN - for charset in ('utf-8-sig', 'utf-16', 'utf-32'): - with self.open(filename, 'w', encoding=charset) as f: - f.write('aaa') - pos = f.tell() - with self.open(filename, 'r+', encoding=charset) as f: - f.seek(pos) - f.write('zzz') - f.seek(0) - f.write('bbb') - with self.open(filename, 'rb') as f: - self.assertEqual(f.read(), 'bbbzzz'.encode(charset)) - - def test_seek_append_bom(self): - # Same test, but first seek to the start and then to the end - filename = os_helper.TESTFN - for charset in ('utf-8-sig', 'utf-16', 'utf-32'): - with self.open(filename, 'w', encoding=charset) as f: - f.write('aaa') - with self.open(filename, 'a', encoding=charset) as f: - f.seek(0) - f.seek(0, self.SEEK_END) - f.write('xxx') - with self.open(filename, 'rb') as f: - self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) - - def test_errors_property(self): - with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: - self.assertEqual(f.errors, "strict") - with self.open(os_helper.TESTFN, "w", encoding="utf-8", errors="replace") as f: - self.assertEqual(f.errors, "replace") - - @support.no_tracing - @threading_helper.requires_working_threading() - def test_threads_write(self): - # Issue6750: concurrent writes could duplicate data - event = threading.Event() - with self.open(os_helper.TESTFN, "w", encoding="utf-8", buffering=1) as f: - def run(n): - text = "Thread%03d\n" % n - event.wait() - f.write(text) - threads = [threading.Thread(target=run, args=(x,)) - for x in range(20)] - with threading_helper.start_threads(threads, event.set): - time.sleep(0.02) - with self.open(os_helper.TESTFN, encoding="utf-8") as f: - content = f.read() - for n in range(20): - self.assertEqual(content.count("Thread%03d\n" % n), 1) - - def test_flush_error_on_close(self): - # Test that text file is closed despite failed flush - # and that flush() is called before file closed. - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - closed = [] - def bad_flush(): - closed[:] = [txt.closed, txt.buffer.closed] - raise OSError() - txt.flush = bad_flush - self.assertRaises(OSError, txt.close) # exception not swallowed - self.assertTrue(txt.closed) - self.assertTrue(txt.buffer.closed) - self.assertTrue(closed) # flush() called - self.assertFalse(closed[0]) # flush() called before file closed - self.assertFalse(closed[1]) - txt.flush = lambda: None # break reference loop - - def test_close_error_on_close(self): - buffer = self.BytesIO(self.testdata) - def bad_flush(): - raise OSError('flush') - def bad_close(): - raise OSError('close') - buffer.close = bad_close - txt = self.TextIOWrapper(buffer, encoding="ascii") - txt.flush = bad_flush - with self.assertRaises(OSError) as err: # exception not swallowed - txt.close() - self.assertEqual(err.exception.args, ('close',)) - self.assertIsInstance(err.exception.__context__, OSError) - self.assertEqual(err.exception.__context__.args, ('flush',)) - self.assertFalse(txt.closed) - - # Silence destructor error - buffer.close = lambda: None - txt.flush = lambda: None - - def test_nonnormalized_close_error_on_close(self): - # Issue #21677 - buffer = self.BytesIO(self.testdata) - def bad_flush(): - raise non_existing_flush - def bad_close(): - raise non_existing_close - buffer.close = bad_close - txt = self.TextIOWrapper(buffer, encoding="ascii") - txt.flush = bad_flush - with self.assertRaises(NameError) as err: # exception not swallowed - txt.close() - self.assertIn('non_existing_close', str(err.exception)) - self.assertIsInstance(err.exception.__context__, NameError) - self.assertIn('non_existing_flush', str(err.exception.__context__)) - self.assertFalse(txt.closed) - - # Silence destructor error - buffer.close = lambda: None - txt.flush = lambda: None - - def test_multi_close(self): - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - txt.close() - txt.close() - txt.close() - self.assertRaises(ValueError, txt.flush) - - def test_unseekable(self): - txt = self.TextIOWrapper(self.MockUnseekableIO(self.testdata), encoding="utf-8") - self.assertRaises(self.UnsupportedOperation, txt.tell) - self.assertRaises(self.UnsupportedOperation, txt.seek, 0) - - def test_readonly_attributes(self): - txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") - buf = self.BytesIO(self.testdata) - with self.assertRaises(AttributeError): - txt.buffer = buf - - def test_rawio(self): - # Issue #12591: TextIOWrapper must work with raw I/O objects, so - # that subprocess.Popen() can have the required unbuffered - # semantics with universal_newlines=True. - raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) - txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') - # Reads - self.assertEqual(txt.read(4), 'abcd') - self.assertEqual(txt.readline(), 'efghi\n') - self.assertEqual(list(txt), ['jkl\n', 'opq\n']) - - def test_rawio_write_through(self): - # Issue #12591: with write_through=True, writes don't need a flush - raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) - txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n', - write_through=True) - txt.write('1') - txt.write('23\n4') - txt.write('5') - self.assertEqual(b''.join(raw._write_stack), b'123\n45') - - def test_bufio_write_through(self): - # Issue #21396: write_through=True doesn't force a flush() - # on the underlying binary buffered object. - flush_called, write_called = [], [] - class BufferedWriter(self.BufferedWriter): - def flush(self, *args, **kwargs): - flush_called.append(True) - return super().flush(*args, **kwargs) - def write(self, *args, **kwargs): - write_called.append(True) - return super().write(*args, **kwargs) - - rawio = self.BytesIO() - data = b"a" - bufio = BufferedWriter(rawio, len(data)*2) - textio = self.TextIOWrapper(bufio, encoding='ascii', - write_through=True) - # write to the buffered io but don't overflow the buffer - text = data.decode('ascii') - textio.write(text) - - # buffer.flush is not called with write_through=True - self.assertFalse(flush_called) - # buffer.write *is* called with write_through=True - self.assertTrue(write_called) - self.assertEqual(rawio.getvalue(), b"") # no flush - - write_called = [] # reset - textio.write(text * 10) # total content is larger than bufio buffer - self.assertTrue(write_called) - self.assertEqual(rawio.getvalue(), data * 11) # all flushed - - def test_reconfigure_write_through(self): - raw = self.MockRawIO([]) - t = self.TextIOWrapper(raw, encoding='ascii', newline='\n') - t.write('1') - t.reconfigure(write_through=True) # implied flush - self.assertEqual(t.write_through, True) - self.assertEqual(b''.join(raw._write_stack), b'1') - t.write('23') - self.assertEqual(b''.join(raw._write_stack), b'123') - t.reconfigure(write_through=False) - self.assertEqual(t.write_through, False) - t.write('45') - t.flush() - self.assertEqual(b''.join(raw._write_stack), b'12345') - # Keeping default value - t.reconfigure() - t.reconfigure(write_through=None) - self.assertEqual(t.write_through, False) - t.reconfigure(write_through=True) - t.reconfigure() - t.reconfigure(write_through=None) - self.assertEqual(t.write_through, True) - - def test_read_nonbytes(self): - # Issue #17106 - # Crash when underlying read() returns non-bytes - t = self.TextIOWrapper(self.StringIO('a'), encoding="utf-8") - self.assertRaises(TypeError, t.read, 1) - t = self.TextIOWrapper(self.StringIO('a'), encoding="utf-8") - self.assertRaises(TypeError, t.readline) - t = self.TextIOWrapper(self.StringIO('a'), encoding="utf-8") - self.assertRaises(TypeError, t.read) - - def test_illegal_encoder(self): - # Issue 31271: Calling write() while the return value of encoder's - # encode() is invalid shouldn't cause an assertion failure. - rot13 = codecs.lookup("rot13") - with support.swap_attr(rot13, '_is_text_encoding', True): - t = self.TextIOWrapper(self.BytesIO(b'foo'), encoding="rot13") - self.assertRaises(TypeError, t.write, 'bar') - - def test_illegal_decoder(self): - # Issue #17106 - # Bypass the early encoding check added in issue 20404 - def _make_illegal_wrapper(): - quopri = codecs.lookup("quopri") - quopri._is_text_encoding = True - try: - t = self.TextIOWrapper(self.BytesIO(b'aaaaaa'), - newline='\n', encoding="quopri") - finally: - quopri._is_text_encoding = False - return t - # Crash when decoder returns non-string - t = _make_illegal_wrapper() - self.assertRaises(TypeError, t.read, 1) - t = _make_illegal_wrapper() - self.assertRaises(TypeError, t.readline) - t = _make_illegal_wrapper() - self.assertRaises(TypeError, t.read) - - # Issue 31243: calling read() while the return value of decoder's - # getstate() is invalid should neither crash the interpreter nor - # raise a SystemError. - def _make_very_illegal_wrapper(getstate_ret_val): - class BadDecoder: - def getstate(self): - return getstate_ret_val - def _get_bad_decoder(dummy): - return BadDecoder() - quopri = codecs.lookup("quopri") - with support.swap_attr(quopri, 'incrementaldecoder', - _get_bad_decoder): - return _make_illegal_wrapper() - t = _make_very_illegal_wrapper(42) - self.assertRaises(TypeError, t.read, 42) - t = _make_very_illegal_wrapper(()) - self.assertRaises(TypeError, t.read, 42) - t = _make_very_illegal_wrapper((1, 2)) - self.assertRaises(TypeError, t.read, 42) - - def _check_create_at_shutdown(self, **kwargs): - # Issue #20037: creating a TextIOWrapper at shutdown - # shouldn't crash the interpreter. - iomod = self.io.__name__ - code = """if 1: - import codecs - import {iomod} as io - - # Avoid looking up codecs at shutdown - codecs.lookup('utf-8') - - class C: - def __del__(self): - io.TextIOWrapper(io.BytesIO(), **{kwargs}) - print("ok") - c = C() - """.format(iomod=iomod, kwargs=kwargs) - return assert_python_ok("-c", code) - - def test_create_at_shutdown_without_encoding(self): - rc, out, err = self._check_create_at_shutdown() - if err: - # Can error out with a RuntimeError if the module state - # isn't found. - self.assertIn(self.shutdown_error, err.decode()) - else: - self.assertEqual("ok", out.decode().strip()) - - def test_create_at_shutdown_with_encoding(self): - rc, out, err = self._check_create_at_shutdown(encoding='utf-8', - errors='strict') - self.assertFalse(err) - self.assertEqual("ok", out.decode().strip()) - - def test_read_byteslike(self): - r = MemviewBytesIO(b'Just some random string\n') - t = self.TextIOWrapper(r, 'utf-8') - - # TextIOwrapper will not read the full string, because - # we truncate it to a multiple of the native int size - # so that we can construct a more complex memoryview. - bytes_val = _to_memoryview(r.getvalue()).tobytes() - - self.assertEqual(t.read(200), bytes_val.decode('utf-8')) - - def test_issue22849(self): - class F(object): - def readable(self): return True - def writable(self): return True - def seekable(self): return True - - for i in range(10): - try: - self.TextIOWrapper(F(), encoding='utf-8') - except Exception: - pass - - F.tell = lambda x: 0 - t = self.TextIOWrapper(F(), encoding='utf-8') - - def test_reconfigure_locale(self): - wrapper = self.TextIOWrapper(self.BytesIO(b"test")) - wrapper.reconfigure(encoding="locale") - - def test_reconfigure_encoding_read(self): - # latin1 -> utf8 - # (latin1 can decode utf-8 encoded string) - data = 'abc\xe9\n'.encode('latin1') + 'd\xe9f\n'.encode('utf8') - raw = self.BytesIO(data) - txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') - self.assertEqual(txt.readline(), 'abc\xe9\n') - with self.assertRaises(self.UnsupportedOperation): - txt.reconfigure(encoding='utf-8') - with self.assertRaises(self.UnsupportedOperation): - txt.reconfigure(newline=None) - - def test_reconfigure_write_fromascii(self): - # ascii has a specific encodefunc in the C implementation, - # but utf-8-sig has not. Make sure that we get rid of the - # cached encodefunc when we switch encoders. - raw = self.BytesIO() - txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') - txt.write('foo\n') - txt.reconfigure(encoding='utf-8-sig') - txt.write('\xe9\n') - txt.flush() - self.assertEqual(raw.getvalue(), b'foo\n\xc3\xa9\n') - - def test_reconfigure_write(self): - # latin -> utf8 - raw = self.BytesIO() - txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') - txt.write('abc\xe9\n') - txt.reconfigure(encoding='utf-8') - self.assertEqual(raw.getvalue(), b'abc\xe9\n') - txt.write('d\xe9f\n') - txt.flush() - self.assertEqual(raw.getvalue(), b'abc\xe9\nd\xc3\xa9f\n') - - # ascii -> utf-8-sig: ensure that no BOM is written in the middle of - # the file - raw = self.BytesIO() - txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') - txt.write('abc\n') - txt.reconfigure(encoding='utf-8-sig') - txt.write('d\xe9f\n') - txt.flush() - self.assertEqual(raw.getvalue(), b'abc\nd\xc3\xa9f\n') - - def test_reconfigure_write_non_seekable(self): - raw = self.BytesIO() - raw.seekable = lambda: False - raw.seek = None - txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') - txt.write('abc\n') - txt.reconfigure(encoding='utf-8-sig') - txt.write('d\xe9f\n') - txt.flush() - - # If the raw stream is not seekable, there'll be a BOM - self.assertEqual(raw.getvalue(), b'abc\n\xef\xbb\xbfd\xc3\xa9f\n') - - def test_reconfigure_defaults(self): - txt = self.TextIOWrapper(self.BytesIO(), 'ascii', 'replace', '\n') - txt.reconfigure(encoding=None) - self.assertEqual(txt.encoding, 'ascii') - self.assertEqual(txt.errors, 'replace') - txt.write('LF\n') - - txt.reconfigure(newline='\r\n') - self.assertEqual(txt.encoding, 'ascii') - self.assertEqual(txt.errors, 'replace') - - txt.reconfigure(errors='ignore') - self.assertEqual(txt.encoding, 'ascii') - self.assertEqual(txt.errors, 'ignore') - txt.write('CRLF\n') - - txt.reconfigure(encoding='utf-8', newline=None) - self.assertEqual(txt.errors, 'strict') - txt.seek(0) - self.assertEqual(txt.read(), 'LF\nCRLF\n') - - self.assertEqual(txt.detach().getvalue(), b'LF\nCRLF\r\n') - - def test_reconfigure_errors(self): - txt = self.TextIOWrapper(self.BytesIO(), 'ascii', 'replace', '\r') - with self.assertRaises(TypeError): # there was a crash - txt.reconfigure(encoding=42) - if self.is_C: - with self.assertRaises(UnicodeEncodeError): - txt.reconfigure(encoding='\udcfe') - with self.assertRaises(LookupError): - txt.reconfigure(encoding='locale\0') - # TODO: txt.reconfigure(encoding='utf-8\0') - # TODO: txt.reconfigure(encoding='nonexisting') - with self.assertRaises(TypeError): - txt.reconfigure(errors=42) - if self.is_C: - with self.assertRaises(UnicodeEncodeError): - txt.reconfigure(errors='\udcfe') - # TODO: txt.reconfigure(errors='ignore\0') - # TODO: txt.reconfigure(errors='nonexisting') - with self.assertRaises(TypeError): - txt.reconfigure(newline=42) - with self.assertRaises(ValueError): - txt.reconfigure(newline='\udcfe') - with self.assertRaises(ValueError): - txt.reconfigure(newline='xyz') - if not self.is_C: - # TODO: Should fail in C too. - with self.assertRaises(ValueError): - txt.reconfigure(newline='\n\0') - if self.is_C: - # TODO: Use __bool__(), not __index__(). - with self.assertRaises(ZeroDivisionError): - txt.reconfigure(line_buffering=BadIndex()) - with self.assertRaises(OverflowError): - txt.reconfigure(line_buffering=2**1000) - with self.assertRaises(ZeroDivisionError): - txt.reconfigure(write_through=BadIndex()) - with self.assertRaises(OverflowError): - txt.reconfigure(write_through=2**1000) - with self.assertRaises(ZeroDivisionError): # there was a crash - txt.reconfigure(line_buffering=BadIndex(), - write_through=BadIndex()) - self.assertEqual(txt.encoding, 'ascii') - self.assertEqual(txt.errors, 'replace') - self.assertIs(txt.line_buffering, False) - self.assertIs(txt.write_through, False) - - txt.reconfigure(encoding='latin1', errors='ignore', newline='\r\n', - line_buffering=True, write_through=True) - self.assertEqual(txt.encoding, 'latin1') - self.assertEqual(txt.errors, 'ignore') - self.assertIs(txt.line_buffering, True) - self.assertIs(txt.write_through, True) - - def test_reconfigure_newline(self): - raw = self.BytesIO(b'CR\rEOF') - txt = self.TextIOWrapper(raw, 'ascii', newline='\n') - txt.reconfigure(newline=None) - self.assertEqual(txt.readline(), 'CR\n') - raw = self.BytesIO(b'CR\rEOF') - txt = self.TextIOWrapper(raw, 'ascii', newline='\n') - txt.reconfigure(newline='') - self.assertEqual(txt.readline(), 'CR\r') - raw = self.BytesIO(b'CR\rLF\nEOF') - txt = self.TextIOWrapper(raw, 'ascii', newline='\r') - txt.reconfigure(newline='\n') - self.assertEqual(txt.readline(), 'CR\rLF\n') - raw = self.BytesIO(b'LF\nCR\rEOF') - txt = self.TextIOWrapper(raw, 'ascii', newline='\n') - txt.reconfigure(newline='\r') - self.assertEqual(txt.readline(), 'LF\nCR\r') - raw = self.BytesIO(b'CR\rCRLF\r\nEOF') - txt = self.TextIOWrapper(raw, 'ascii', newline='\r') - txt.reconfigure(newline='\r\n') - self.assertEqual(txt.readline(), 'CR\rCRLF\r\n') - - txt = self.TextIOWrapper(self.BytesIO(), 'ascii', newline='\r') - txt.reconfigure(newline=None) - txt.write('linesep\n') - txt.reconfigure(newline='') - txt.write('LF\n') - txt.reconfigure(newline='\n') - txt.write('LF\n') - txt.reconfigure(newline='\r') - txt.write('CR\n') - txt.reconfigure(newline='\r\n') - txt.write('CRLF\n') - expected = 'linesep' + os.linesep + 'LF\nLF\nCR\rCRLF\r\n' - self.assertEqual(txt.detach().getvalue().decode('ascii'), expected) - - def test_issue25862(self): - # Assertion failures occurred in tell() after read() and write(). - t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') - t.read(1) - t.read() - t.tell() - t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') - t.read(1) - t.write('x') - t.tell() - - def test_issue35928(self): - p = self.BufferedRWPair(self.BytesIO(b'foo\nbar\n'), self.BytesIO()) - f = self.TextIOWrapper(p) - res = f.readline() - self.assertEqual(res, 'foo\n') - f.write(res) - self.assertEqual(res + f.readline(), 'foo\nbar\n') - - def test_pickling_subclass(self): - global MyTextIO - class MyTextIO(self.TextIOWrapper): - def __init__(self, raw, tag): - super().__init__(raw) - self.tag = tag - def __getstate__(self): - return self.tag, self.buffer.getvalue() - def __setstate__(slf, state): - tag, value = state - slf.__init__(self.BytesIO(value), tag) - - raw = self.BytesIO(b'data') - txt = MyTextIO(raw, 'ham') - for proto in range(pickle.HIGHEST_PROTOCOL + 1): - with self.subTest(protocol=proto): - pickled = pickle.dumps(txt, proto) - newtxt = pickle.loads(pickled) - self.assertEqual(newtxt.buffer.getvalue(), b'data') - self.assertEqual(newtxt.tag, 'ham') - del MyTextIO - - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def test_read_non_blocking(self): - import os - r, w = os.pipe() - try: - os.set_blocking(r, False) - with self.io.open(r, 'rt') as textfile: - r = None - # Nothing has been written so a non-blocking read raises a BlockingIOError exception. - with self.assertRaises(BlockingIOError): - textfile.read() - finally: - if r is not None: - os.close(r) - os.close(w) - - -class MemviewBytesIO(io.BytesIO): - '''A BytesIO object whose read method returns memoryviews - rather than bytes''' - - def read1(self, len_): - return _to_memoryview(super().read1(len_)) - - def read(self, len_): - return _to_memoryview(super().read(len_)) - -def _to_memoryview(buf): - '''Convert bytes-object *buf* to a non-trivial memoryview''' - - arr = array.array('i') - idx = len(buf) - len(buf) % arr.itemsize - arr.frombytes(buf[:idx]) - return memoryview(arr) - - -class CTextIOWrapperTest(TextIOWrapperTest): - io = io - shutdown_error = "LookupError: unknown encoding: ascii" - - def test_initialization(self): - r = self.BytesIO(b"\xc3\xa9\n\n") - b = self.BufferedReader(r, 1000) - t = self.TextIOWrapper(b, encoding="utf-8") - self.assertRaises(ValueError, t.__init__, b, encoding="utf-8", newline='xyzzy') - self.assertRaises(ValueError, t.read) - - t = self.TextIOWrapper.__new__(self.TextIOWrapper) - self.assertRaises(Exception, repr, t) - - @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON; cyclic GC not supported, causes file locking") - def test_garbage_collection(self): - # C TextIOWrapper objects are collected, and collecting them flushes - # all data to disk. - # The Python version has __del__, so it ends in gc.garbage instead. - with warnings_helper.check_warnings(('', ResourceWarning)): - rawio = self.FileIO(os_helper.TESTFN, "wb") - b = self.BufferedWriter(rawio) - t = self.TextIOWrapper(b, encoding="ascii") - t.write("456def") - t.x = t - wr = weakref.ref(t) - del t - support.gc_collect() - self.assertIsNone(wr(), wr) - with self.open(os_helper.TESTFN, "rb") as f: - self.assertEqual(f.read(), b"456def") - - def test_rwpair_cleared_before_textio(self): - # Issue 13070: TextIOWrapper's finalization would crash when called - # after the reference to the underlying BufferedRWPair's writer got - # cleared by the GC. - for i in range(1000): - b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) - t1 = self.TextIOWrapper(b1, encoding="ascii") - b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) - t2 = self.TextIOWrapper(b2, encoding="ascii") - # circular references - t1.buddy = t2 - t2.buddy = t1 - support.gc_collect() - - def test_del__CHUNK_SIZE_SystemError(self): - t = self.TextIOWrapper(self.BytesIO(), encoding='ascii') - with self.assertRaises(AttributeError): - del t._CHUNK_SIZE - - def test_internal_buffer_size(self): - # bpo-43260: TextIOWrapper's internal buffer should not store - # data larger than chunk size. - chunk_size = 8192 # default chunk size, updated later - - class MockIO(self.MockRawIO): - def write(self, data): - if len(data) > chunk_size: - raise RuntimeError - return super().write(data) - - buf = MockIO() - t = self.TextIOWrapper(buf, encoding="ascii") - chunk_size = t._CHUNK_SIZE - t.write("abc") - t.write("def") - # default chunk size is 8192 bytes so t don't write data to buf. - self.assertEqual([], buf._write_stack) - - with self.assertRaises(RuntimeError): - t.write("x"*(chunk_size+1)) - - self.assertEqual([b"abcdef"], buf._write_stack) - t.write("ghi") - t.write("x"*chunk_size) - self.assertEqual([b"abcdef", b"ghi", b"x"*chunk_size], buf._write_stack) - - def test_issue119506(self): - chunk_size = 8192 - - class MockIO(self.MockRawIO): - written = False - def write(self, data): - if not self.written: - self.written = True - t.write("middle") - return super().write(data) - - buf = MockIO() - t = self.TextIOWrapper(buf) - t.write("abc") - t.write("def") - # writing data which size >= chunk_size cause flushing buffer before write. - t.write("g" * chunk_size) - t.flush() - - self.assertEqual([b"abcdef", b"middle", b"g"*chunk_size], - buf._write_stack) - - def test_issue142594(self): - wrapper = None - detached = False - class ReentrantRawIO(self.RawIOBase): - @property - def closed(self): - nonlocal detached - if wrapper is not None and not detached: - detached = True - wrapper.detach() - return False - - raw = ReentrantRawIO() - wrapper = self.TextIOWrapper(raw) - wrapper.close() # should not crash - - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: a bytes-like object is required, not 'NoneType' - def test_read_non_blocking(self): - return super().test_read_non_blocking() - - -class PyTextIOWrapperTest(TextIOWrapperTest): - io = pyio - shutdown_error = "LookupError: unknown encoding: ascii" - - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON; os.set_blocking not available on Windows") - def test_read_non_blocking(self): - return super().test_read_non_blocking() - - -class IncrementalNewlineDecoderTest(unittest.TestCase): - - def check_newline_decoding_utf8(self, decoder): - # UTF-8 specific tests for a newline decoder - def _check_decode(b, s, **kwargs): - # We exercise getstate() / setstate() as well as decode() - state = decoder.getstate() - self.assertEqual(decoder.decode(b, **kwargs), s) - decoder.setstate(state) - self.assertEqual(decoder.decode(b, **kwargs), s) - - _check_decode(b'\xe8\xa2\x88', "\u8888") - - _check_decode(b'\xe8', "") - _check_decode(b'\xa2', "") - _check_decode(b'\x88', "\u8888") - - _check_decode(b'\xe8', "") - _check_decode(b'\xa2', "") - _check_decode(b'\x88', "\u8888") - - _check_decode(b'\xe8', "") - self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True) - - decoder.reset() - _check_decode(b'\n', "\n") - _check_decode(b'\r', "") - _check_decode(b'', "\n", final=True) - _check_decode(b'\r', "\n", final=True) - - _check_decode(b'\r', "") - _check_decode(b'a', "\na") - - _check_decode(b'\r\r\n', "\n\n") - _check_decode(b'\r', "") - _check_decode(b'\r', "\n") - _check_decode(b'\na', "\na") - - _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n") - _check_decode(b'\xe8\xa2\x88', "\u8888") - _check_decode(b'\n', "\n") - _check_decode(b'\xe8\xa2\x88\r', "\u8888") - _check_decode(b'\n', "\n") - - def check_newline_decoding(self, decoder, encoding): - result = [] - if encoding is not None: - encoder = codecs.getincrementalencoder(encoding)() - def _decode_bytewise(s): - # Decode one byte at a time - for b in encoder.encode(s): - result.append(decoder.decode(bytes([b]))) - else: - encoder = None - def _decode_bytewise(s): - # Decode one char at a time - for c in s: - result.append(decoder.decode(c)) - self.assertEqual(decoder.newlines, None) - _decode_bytewise("abc\n\r") - self.assertEqual(decoder.newlines, '\n') - _decode_bytewise("\nabc") - self.assertEqual(decoder.newlines, ('\n', '\r\n')) - _decode_bytewise("abc\r") - self.assertEqual(decoder.newlines, ('\n', '\r\n')) - _decode_bytewise("abc") - self.assertEqual(decoder.newlines, ('\r', '\n', '\r\n')) - _decode_bytewise("abc\r") - self.assertEqual("".join(result), "abc\n\nabcabc\nabcabc") - decoder.reset() - input = "abc" - if encoder is not None: - encoder.reset() - input = encoder.encode(input) - self.assertEqual(decoder.decode(input), "abc") - self.assertEqual(decoder.newlines, None) - - def test_newline_decoder(self): - encodings = ( - # None meaning the IncrementalNewlineDecoder takes unicode input - # rather than bytes input - None, 'utf-8', 'latin-1', - 'utf-16', 'utf-16-le', 'utf-16-be', - 'utf-32', 'utf-32-le', 'utf-32-be', - ) - for enc in encodings: - decoder = enc and codecs.getincrementaldecoder(enc)() - decoder = self.IncrementalNewlineDecoder(decoder, translate=True) - self.check_newline_decoding(decoder, enc) - decoder = codecs.getincrementaldecoder("utf-8")() - decoder = self.IncrementalNewlineDecoder(decoder, translate=True) - self.check_newline_decoding_utf8(decoder) - self.assertRaises(TypeError, decoder.setstate, 42) - - def test_newline_bytes(self): - # Issue 5433: Excessive optimization in IncrementalNewlineDecoder - def _check(dec): - self.assertEqual(dec.newlines, None) - self.assertEqual(dec.decode("\u0D00"), "\u0D00") - self.assertEqual(dec.newlines, None) - self.assertEqual(dec.decode("\u0A00"), "\u0A00") - self.assertEqual(dec.newlines, None) - dec = self.IncrementalNewlineDecoder(None, translate=False) - _check(dec) - dec = self.IncrementalNewlineDecoder(None, translate=True) - _check(dec) - - def test_translate(self): - # issue 35062 - for translate in (-2, -1, 1, 2): - decoder = codecs.getincrementaldecoder("utf-8")() - decoder = self.IncrementalNewlineDecoder(decoder, translate) - self.check_newline_decoding_utf8(decoder) - decoder = codecs.getincrementaldecoder("utf-8")() - decoder = self.IncrementalNewlineDecoder(decoder, translate=0) - self.assertEqual(decoder.decode(b"\r\r\n"), "\r\r\n") - -class CIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): - @support.cpython_only - def test_uninitialized(self): - uninitialized = self.IncrementalNewlineDecoder.__new__( - self.IncrementalNewlineDecoder) - self.assertRaises(ValueError, uninitialized.decode, b'bar') - self.assertRaises(ValueError, uninitialized.getstate) - self.assertRaises(ValueError, uninitialized.setstate, (b'foo', 0)) - self.assertRaises(ValueError, uninitialized.reset) - - -class PyIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): - pass - - -# XXX Tests for open() - -class MiscIOTest(unittest.TestCase): - - # for test__all__, actual values are set in subclasses - name_of_module = None - extra_exported = () - not_exported = () - - def tearDown(self): - os_helper.unlink(os_helper.TESTFN) - - def test___all__(self): - support.check__all__(self, self.io, self.name_of_module, - extra=self.extra_exported, - not_exported=self.not_exported) - - def test_attributes(self): - f = self.open(os_helper.TESTFN, "wb", buffering=0) - self.assertEqual(f.mode, "wb") - f.close() - - f = self.open(os_helper.TESTFN, "w+", encoding="utf-8") - self.assertEqual(f.mode, "w+") - self.assertEqual(f.buffer.mode, "rb+") # Does it really matter? - self.assertEqual(f.buffer.raw.mode, "rb+") - - g = self.open(f.fileno(), "wb", closefd=False) - self.assertEqual(g.mode, "wb") - self.assertEqual(g.raw.mode, "wb") - self.assertEqual(g.name, f.fileno()) - self.assertEqual(g.raw.name, f.fileno()) - f.close() - g.close() - - def test_removed_u_mode(self): - # bpo-37330: The "U" mode has been removed in Python 3.11 - for mode in ("U", "rU", "r+U"): - with self.assertRaises(ValueError) as cm: - self.open(os_helper.TESTFN, mode) - self.assertIn('invalid mode', str(cm.exception)) - - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def test_open_pipe_with_append(self): - # bpo-27805: Ignore ESPIPE from lseek() in open(). - r, w = os.pipe() - self.addCleanup(os.close, r) - f = self.open(w, 'a', encoding="utf-8") - self.addCleanup(f.close) - # Check that the file is marked non-seekable. On Windows, however, lseek - # somehow succeeds on pipes. - if sys.platform != 'win32': - self.assertFalse(f.seekable()) - - def test_io_after_close(self): - for kwargs in [ - {"mode": "w"}, - {"mode": "wb"}, - {"mode": "w", "buffering": 1}, - {"mode": "w", "buffering": 2}, - {"mode": "wb", "buffering": 0}, - {"mode": "r"}, - {"mode": "rb"}, - {"mode": "r", "buffering": 1}, - {"mode": "r", "buffering": 2}, - {"mode": "rb", "buffering": 0}, - {"mode": "w+"}, - {"mode": "w+b"}, - {"mode": "w+", "buffering": 1}, - {"mode": "w+", "buffering": 2}, - {"mode": "w+b", "buffering": 0}, - ]: - if "b" not in kwargs["mode"]: - kwargs["encoding"] = "utf-8" - f = self.open(os_helper.TESTFN, **kwargs) - f.close() - self.assertRaises(ValueError, f.flush) - self.assertRaises(ValueError, f.fileno) - self.assertRaises(ValueError, f.isatty) - self.assertRaises(ValueError, f.__iter__) - if hasattr(f, "peek"): - self.assertRaises(ValueError, f.peek, 1) - self.assertRaises(ValueError, f.read) - if hasattr(f, "read1"): - self.assertRaises(ValueError, f.read1, 1024) - self.assertRaises(ValueError, f.read1) - if hasattr(f, "readall"): - self.assertRaises(ValueError, f.readall) - if hasattr(f, "readinto"): - self.assertRaises(ValueError, f.readinto, bytearray(1024)) - if hasattr(f, "readinto1"): - self.assertRaises(ValueError, f.readinto1, bytearray(1024)) - self.assertRaises(ValueError, f.readline) - self.assertRaises(ValueError, f.readlines) - self.assertRaises(ValueError, f.readlines, 1) - self.assertRaises(ValueError, f.seek, 0) - self.assertRaises(ValueError, f.tell) - self.assertRaises(ValueError, f.truncate) - self.assertRaises(ValueError, f.write, - b"" if "b" in kwargs['mode'] else "") - self.assertRaises(ValueError, f.writelines, []) - self.assertRaises(ValueError, next, f) - - def test_blockingioerror(self): - # Various BlockingIOError issues - class C(str): - pass - c = C("") - b = self.BlockingIOError(1, c) - c.b = b - b.c = c - wr = weakref.ref(c) - del c, b - support.gc_collect() - self.assertIsNone(wr(), wr) - - def test_abcs(self): - # Test the visible base classes are ABCs. - self.assertIsInstance(self.IOBase, abc.ABCMeta) - self.assertIsInstance(self.RawIOBase, abc.ABCMeta) - self.assertIsInstance(self.BufferedIOBase, abc.ABCMeta) - self.assertIsInstance(self.TextIOBase, abc.ABCMeta) - - def _check_abc_inheritance(self, abcmodule): - with self.open(os_helper.TESTFN, "wb", buffering=0) as f: - self.assertIsInstance(f, abcmodule.IOBase) - self.assertIsInstance(f, abcmodule.RawIOBase) - self.assertNotIsInstance(f, abcmodule.BufferedIOBase) - self.assertNotIsInstance(f, abcmodule.TextIOBase) - with self.open(os_helper.TESTFN, "wb") as f: - self.assertIsInstance(f, abcmodule.IOBase) - self.assertNotIsInstance(f, abcmodule.RawIOBase) - self.assertIsInstance(f, abcmodule.BufferedIOBase) - self.assertNotIsInstance(f, abcmodule.TextIOBase) - with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: - self.assertIsInstance(f, abcmodule.IOBase) - self.assertNotIsInstance(f, abcmodule.RawIOBase) - self.assertNotIsInstance(f, abcmodule.BufferedIOBase) - self.assertIsInstance(f, abcmodule.TextIOBase) - - def test_abc_inheritance(self): - # Test implementations inherit from their respective ABCs - self._check_abc_inheritance(self) - - def test_abc_inheritance_official(self): - # Test implementations inherit from the official ABCs of the - # baseline "io" module. - self._check_abc_inheritance(io) - - def _check_warn_on_dealloc(self, *args, **kwargs): - f = self.open(*args, **kwargs) - r = repr(f) - with self.assertWarns(ResourceWarning) as cm: - f = None - support.gc_collect() - self.assertIn(r, str(cm.warning.args[0])) - - def test_warn_on_dealloc(self): - self._check_warn_on_dealloc(os_helper.TESTFN, "wb", buffering=0) - self._check_warn_on_dealloc(os_helper.TESTFN, "wb") - self._check_warn_on_dealloc(os_helper.TESTFN, "w", encoding="utf-8") - - def _check_warn_on_dealloc_fd(self, *args, **kwargs): - fds = [] - def cleanup_fds(): - for fd in fds: - try: - os.close(fd) - except OSError as e: - if e.errno != errno.EBADF: - raise - self.addCleanup(cleanup_fds) - r, w = os.pipe() - fds += r, w - self._check_warn_on_dealloc(r, *args, **kwargs) - # When using closefd=False, there's no warning - r, w = os.pipe() - fds += r, w - with warnings_helper.check_no_resource_warning(self): - self.open(r, *args, closefd=False, **kwargs) - - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def test_warn_on_dealloc_fd(self): - self._check_warn_on_dealloc_fd("rb", buffering=0) - self._check_warn_on_dealloc_fd("rb") - self._check_warn_on_dealloc_fd("r", encoding="utf-8") - - - def test_pickling(self): - # Pickling file objects is forbidden - msg = "cannot pickle" - for kwargs in [ - {"mode": "w"}, - {"mode": "wb"}, - {"mode": "wb", "buffering": 0}, - {"mode": "r"}, - {"mode": "rb"}, - {"mode": "rb", "buffering": 0}, - {"mode": "w+"}, - {"mode": "w+b"}, - {"mode": "w+b", "buffering": 0}, - ]: - if "b" not in kwargs["mode"]: - kwargs["encoding"] = "utf-8" - for protocol in range(pickle.HIGHEST_PROTOCOL + 1): - with self.subTest(protocol=protocol, kwargs=kwargs): - with self.open(os_helper.TESTFN, **kwargs) as f: - with self.assertRaisesRegex(TypeError, msg): - pickle.dumps(f, protocol) - - @unittest.skipIf(support.is_emscripten, "Emscripten corrupts memory when writing to nonblocking fd") - def test_nonblock_pipe_write_bigbuf(self): - self._test_nonblock_pipe_write(16*1024) - - @unittest.skipIf(support.is_emscripten, "Emscripten corrupts memory when writing to nonblocking fd") - def test_nonblock_pipe_write_smallbuf(self): - self._test_nonblock_pipe_write(1024) - - @unittest.skipUnless(hasattr(os, 'set_blocking'), - 'os.set_blocking() required for this test') - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def _test_nonblock_pipe_write(self, bufsize): - sent = [] - received = [] - r, w = os.pipe() - os.set_blocking(r, False) - os.set_blocking(w, False) - - # To exercise all code paths in the C implementation we need - # to play with buffer sizes. For instance, if we choose a - # buffer size less than or equal to _PIPE_BUF (4096 on Linux) - # then we will never get a partial write of the buffer. - rf = self.open(r, mode='rb', closefd=True, buffering=bufsize) - wf = self.open(w, mode='wb', closefd=True, buffering=bufsize) - - with rf, wf: - for N in 9999, 73, 7574: - try: - i = 0 - while True: - msg = bytes([i % 26 + 97]) * N - sent.append(msg) - wf.write(msg) - i += 1 - - except self.BlockingIOError as e: - self.assertEqual(e.args[0], errno.EAGAIN) - self.assertEqual(e.args[2], e.characters_written) - sent[-1] = sent[-1][:e.characters_written] - received.append(rf.read()) - msg = b'BLOCKED' - wf.write(msg) - sent.append(msg) - - while True: - try: - wf.flush() - break - except self.BlockingIOError as e: - self.assertEqual(e.args[0], errno.EAGAIN) - self.assertEqual(e.args[2], e.characters_written) - self.assertEqual(e.characters_written, 0) - received.append(rf.read()) - - received += iter(rf.read, None) - - sent, received = b''.join(sent), b''.join(received) - self.assertEqual(sent, received) - self.assertTrue(wf.closed) - self.assertTrue(rf.closed) - - def test_create_fail(self): - # 'x' mode fails if file is existing - with self.open(os_helper.TESTFN, 'w', encoding="utf-8"): - pass - self.assertRaises(FileExistsError, self.open, os_helper.TESTFN, 'x', encoding="utf-8") - - def test_create_writes(self): - # 'x' mode opens for writing - with self.open(os_helper.TESTFN, 'xb') as f: - f.write(b"spam") - with self.open(os_helper.TESTFN, 'rb') as f: - self.assertEqual(b"spam", f.read()) - - def test_open_allargs(self): - # there used to be a buffer overflow in the parser for rawmode - self.assertRaises(ValueError, self.open, os_helper.TESTFN, 'rwax+', encoding="utf-8") - - def test_check_encoding_errors(self): - # bpo-37388: open() and TextIOWrapper must check encoding and errors - # arguments in dev mode - mod = self.io.__name__ - filename = __file__ - invalid = 'Boom, Shaka Laka, Boom!' - code = textwrap.dedent(f''' - import sys - from {mod} import open, TextIOWrapper - - try: - open({filename!r}, encoding={invalid!r}) - except LookupError: - pass - else: - sys.exit(21) - - try: - open({filename!r}, errors={invalid!r}) - except LookupError: - pass - else: - sys.exit(22) - - fp = open({filename!r}, "rb") - with fp: - try: - TextIOWrapper(fp, encoding={invalid!r}) - except LookupError: - pass - else: - sys.exit(23) - - try: - TextIOWrapper(fp, errors={invalid!r}) - except LookupError: - pass - else: - sys.exit(24) - - sys.exit(10) - ''') - proc = assert_python_failure('-X', 'dev', '-c', code) - self.assertEqual(proc.rc, 10, proc) - - def test_check_encoding_warning(self): - # PEP 597: Raise warning when encoding is not specified - # and sys.flags.warn_default_encoding is set. - mod = self.io.__name__ - filename = __file__ - code = textwrap.dedent(f'''\ - import sys - from {mod} import open, TextIOWrapper - import pathlib - - with open({filename!r}) as f: # line 5 - pass - - pathlib.Path({filename!r}).read_text() # line 8 - ''') - proc = assert_python_ok('-X', 'warn_default_encoding', '-c', code) - warnings = proc.err.splitlines() - self.assertEqual(len(warnings), 2) - self.assertStartsWith(warnings[0], b":5: EncodingWarning: ") - self.assertStartsWith(warnings[1], b":8: EncodingWarning: ") - - def test_text_encoding(self): - # PEP 597, bpo-47000. io.text_encoding() returns "locale" or "utf-8" - # based on sys.flags.utf8_mode - code = "import io; print(io.text_encoding(None))" - - proc = assert_python_ok('-X', 'utf8=0', '-c', code) - self.assertEqual(b"locale", proc.out.strip()) - - proc = assert_python_ok('-X', 'utf8=1', '-c', code) - self.assertEqual(b"utf-8", proc.out.strip()) - - -class CMiscIOTest(MiscIOTest): - io = io - name_of_module = "io", "_io" - extra_exported = "BlockingIOError", - - def test_readinto_buffer_overflow(self): - # Issue #18025 - class BadReader(self.io.BufferedIOBase): - def read(self, n=-1): - return b'x' * 10**6 - bufio = BadReader() - b = bytearray(2) - self.assertRaises(ValueError, bufio.readinto, b) - - def check_daemon_threads_shutdown_deadlock(self, stream_name): - # Issue #23309: deadlocks at shutdown should be avoided when a - # daemon thread and the main thread both write to a file. - code = """if 1: - import sys - import time - import threading - from test.support import SuppressCrashReport - - file = sys.{stream_name} - - def run(): - while True: - file.write('.') - file.flush() - - crash = SuppressCrashReport() - crash.__enter__() - # don't call __exit__(): the crash occurs at Python shutdown - - thread = threading.Thread(target=run) - thread.daemon = True - thread.start() - - time.sleep(0.5) - file.write('!') - file.flush() - """.format_map(locals()) - res, _ = run_python_until_end("-c", code) - err = res.err.decode() - if res.rc != 0: - # Failure: should be a fatal error - pattern = (r"Fatal Python error: _enter_buffered_busy: " - r"could not acquire lock " - r"for <(_io\.)?BufferedWriter name='<{stream_name}>'> " - r"at interpreter shutdown, possibly due to " - r"daemon threads".format_map(locals())) - self.assertRegex(err, pattern) - else: - self.assertFalse(err.strip('.!')) - - @threading_helper.requires_working_threading() - @support.requires_resource('walltime') - def test_daemon_threads_shutdown_stdout_deadlock(self): - self.check_daemon_threads_shutdown_deadlock('stdout') - - @threading_helper.requires_working_threading() - @support.requires_resource('walltime') - def test_daemon_threads_shutdown_stderr_deadlock(self): - self.check_daemon_threads_shutdown_deadlock('stderr') - - -class PyMiscIOTest(MiscIOTest): - io = pyio - name_of_module = "_pyio", "io" - extra_exported = "BlockingIOError", "open_code", - not_exported = "valid_seek_flags", - - -@unittest.skipIf(os.name == 'nt', 'POSIX signals required for this test.') -class SignalsTest(unittest.TestCase): - - def setUp(self): - self.oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) - - def tearDown(self): - signal.signal(signal.SIGALRM, self.oldalrm) - - def alarm_interrupt(self, sig, frame): - 1/0 - - def check_interrupted_write(self, item, bytes, **fdopen_kwargs): - """Check that a partial write, when it gets interrupted, properly - invokes the signal handler, and bubbles up the exception raised - in the latter.""" - - # XXX This test has three flaws that appear when objects are - # XXX not reference counted. - - # - if wio.write() happens to trigger a garbage collection, - # the signal exception may be raised when some __del__ - # method is running; it will not reach the assertRaises() - # call. - - # - more subtle, if the wio object is not destroyed at once - # and survives this function, the next opened file is likely - # to have the same fileno (since the file descriptor was - # actively closed). When wio.__del__ is finally called, it - # will close the other's test file... To trigger this with - # CPython, try adding "global wio" in this function. - - # - This happens only for streams created by the _pyio module, - # because a wio.close() that fails still consider that the - # file needs to be closed again. You can try adding an - # "assert wio.closed" at the end of the function. - - # Fortunately, a little gc.collect() seems to be enough to - # work around all these issues. - support.gc_collect() # For PyPy or other GCs. - - read_results = [] - def _read(): - s = os.read(r, 1) - read_results.append(s) - - t = threading.Thread(target=_read) - t.daemon = True - r, w = os.pipe() - fdopen_kwargs["closefd"] = False - large_data = item * (support.PIPE_MAX_SIZE // len(item) + 1) - try: - wio = self.io.open(w, **fdopen_kwargs) - if hasattr(signal, 'pthread_sigmask'): - # create the thread with SIGALRM signal blocked - signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGALRM]) - t.start() - signal.pthread_sigmask(signal.SIG_UNBLOCK, [signal.SIGALRM]) - else: - t.start() - - # Fill the pipe enough that the write will be blocking. - # It will be interrupted by the timer armed above. Since the - # other thread has read one byte, the low-level write will - # return with a successful (partial) result rather than an EINTR. - # The buffered IO layer must check for pending signal - # handlers, which in this case will invoke alarm_interrupt(). - signal.alarm(1) - try: - self.assertRaises(ZeroDivisionError, wio.write, large_data) - finally: - signal.alarm(0) - t.join() - # We got one byte, get another one and check that it isn't a - # repeat of the first one. - read_results.append(os.read(r, 1)) - self.assertEqual(read_results, [bytes[0:1], bytes[1:2]]) - finally: - os.close(w) - os.close(r) - # This is deliberate. If we didn't close the file descriptor - # before closing wio, wio would try to flush its internal - # buffer, and block again. - try: - wio.close() - except OSError as e: - if e.errno != errno.EBADF: - raise - - @requires_alarm - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def test_interrupted_write_unbuffered(self): - self.check_interrupted_write(b"xy", b"xy", mode="wb", buffering=0) - - @requires_alarm - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def test_interrupted_write_buffered(self): - self.check_interrupted_write(b"xy", b"xy", mode="wb") - - @requires_alarm - @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") - def test_interrupted_write_text(self): - self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii") - - @support.no_tracing - def check_reentrant_write(self, data, **fdopen_kwargs): - def on_alarm(*args): - # Will be called reentrantly from the same thread - wio.write(data) - 1/0 - signal.signal(signal.SIGALRM, on_alarm) - r, w = os.pipe() - wio = self.io.open(w, **fdopen_kwargs) - try: - signal.alarm(1) - # Either the reentrant call to wio.write() fails with RuntimeError, - # or the signal handler raises ZeroDivisionError. - with self.assertRaises((ZeroDivisionError, RuntimeError)) as cm: - while 1: - for i in range(100): - wio.write(data) - wio.flush() - # Make sure the buffer doesn't fill up and block further writes - os.read(r, len(data) * 100) - exc = cm.exception - if isinstance(exc, RuntimeError): - self.assertStartsWith(str(exc), "reentrant call") - finally: - signal.alarm(0) - wio.close() - os.close(r) - - @requires_alarm - def test_reentrant_write_buffered(self): - self.check_reentrant_write(b"xy", mode="wb") - - @requires_alarm - def test_reentrant_write_text(self): - self.check_reentrant_write("xy", mode="w", encoding="ascii") - - def check_interrupted_read_retry(self, decode, **fdopen_kwargs): - """Check that a buffered read, when it gets interrupted (either - returning a partial result or EINTR), properly invokes the signal - handler and retries if the latter returned successfully.""" - r, w = os.pipe() - fdopen_kwargs["closefd"] = False - def alarm_handler(sig, frame): - os.write(w, b"bar") - signal.signal(signal.SIGALRM, alarm_handler) - try: - rio = self.io.open(r, **fdopen_kwargs) - os.write(w, b"foo") - signal.alarm(1) - # Expected behaviour: - # - first raw read() returns partial b"foo" - # - second raw read() returns EINTR - # - third raw read() returns b"bar" - self.assertEqual(decode(rio.read(6)), "foobar") - finally: - signal.alarm(0) - rio.close() - os.close(w) - os.close(r) - - @requires_alarm - @support.requires_resource('walltime') - def test_interrupted_read_retry_buffered(self): - self.check_interrupted_read_retry(lambda x: x.decode('latin1'), - mode="rb") - - @requires_alarm - @support.requires_resource('walltime') - def test_interrupted_read_retry_text(self): - self.check_interrupted_read_retry(lambda x: x, - mode="r", encoding="latin1") - - def check_interrupted_write_retry(self, item, **fdopen_kwargs): - """Check that a buffered write, when it gets interrupted (either - returning a partial result or EINTR), properly invokes the signal - handler and retries if the latter returned successfully.""" - select = import_helper.import_module("select") - - # A quantity that exceeds the buffer size of an anonymous pipe's - # write end. - N = support.PIPE_MAX_SIZE - r, w = os.pipe() - fdopen_kwargs["closefd"] = False - - # We need a separate thread to read from the pipe and allow the - # write() to finish. This thread is started after the SIGALRM is - # received (forcing a first EINTR in write()). - read_results = [] - write_finished = False - error = None - def _read(): - try: - while not write_finished: - while r in select.select([r], [], [], 1.0)[0]: - s = os.read(r, 1024) - read_results.append(s) - except BaseException as exc: - nonlocal error - error = exc - t = threading.Thread(target=_read) - t.daemon = True - def alarm1(sig, frame): - signal.signal(signal.SIGALRM, alarm2) - signal.alarm(1) - def alarm2(sig, frame): - t.start() - - large_data = item * N - signal.signal(signal.SIGALRM, alarm1) - try: - wio = self.io.open(w, **fdopen_kwargs) - signal.alarm(1) - # Expected behaviour: - # - first raw write() is partial (because of the limited pipe buffer - # and the first alarm) - # - second raw write() returns EINTR (because of the second alarm) - # - subsequent write()s are successful (either partial or complete) - written = wio.write(large_data) - self.assertEqual(N, written) - - wio.flush() - write_finished = True - t.join() - - self.assertIsNone(error) - self.assertEqual(N, sum(len(x) for x in read_results)) - finally: - signal.alarm(0) - write_finished = True - os.close(w) - os.close(r) - # This is deliberate. If we didn't close the file descriptor - # before closing wio, wio would try to flush its internal - # buffer, and could block (in case of failure). - try: - wio.close() - except OSError as e: - if e.errno != errno.EBADF: - raise - - @requires_alarm - @support.requires_resource('walltime') - def test_interrupted_write_retry_buffered(self): - self.check_interrupted_write_retry(b"x", mode="wb") - - @requires_alarm - @support.requires_resource('walltime') - def test_interrupted_write_retry_text(self): - self.check_interrupted_write_retry("x", mode="w", encoding="latin1") - - -class CSignalsTest(SignalsTest): - io = io - -class PySignalsTest(SignalsTest): - io = pyio - - # Handling reentrancy issues would slow down _pyio even more, so the - # tests are disabled. - test_reentrant_write_buffered = None - test_reentrant_write_text = None - - -class ProtocolsTest(unittest.TestCase): - class MyReader: - def read(self, sz=-1): - return b"" - - class MyWriter: - def write(self, b: bytes): - pass - - def test_reader_subclass(self): - self.assertIsSubclass(self.MyReader, io.Reader) - self.assertNotIsSubclass(str, io.Reader) - - def test_writer_subclass(self): - self.assertIsSubclass(self.MyWriter, io.Writer) - self.assertNotIsSubclass(str, io.Writer) - - -def load_tests(loader, tests, pattern): - tests = (CIOTest, PyIOTest, APIMismatchTest, - CBufferedReaderTest, PyBufferedReaderTest, - CBufferedWriterTest, PyBufferedWriterTest, - CBufferedRWPairTest, PyBufferedRWPairTest, - CBufferedRandomTest, PyBufferedRandomTest, - StatefulIncrementalDecoderTest, - CIncrementalNewlineDecoderTest, PyIncrementalNewlineDecoderTest, - CTextIOWrapperTest, PyTextIOWrapperTest, - CMiscIOTest, PyMiscIOTest, - CSignalsTest, PySignalsTest, TestIOCTypes, - ProtocolsTest, - ) - - # Put the namespaces of the IO module we are testing and some useful mock - # classes in the __dict__ of each test. - mocks = (MockRawIO, MisbehavedRawIO, MockFileIO, CloseFailureIO, - MockNonBlockWriterIO, MockUnseekableIO, MockRawIOWithoutRead, - SlowFlushRawIO, MockCharPseudoDevFileIO) - all_members = io.__all__ - c_io_ns = {name : getattr(io, name) for name in all_members} - py_io_ns = {name : getattr(pyio, name) for name in all_members} - globs = globals() - c_io_ns.update((x.__name__, globs["C" + x.__name__]) for x in mocks) - py_io_ns.update((x.__name__, globs["Py" + x.__name__]) for x in mocks) - for test in tests: - if test.__name__.startswith("C"): - for name, obj in c_io_ns.items(): - setattr(test, name, obj) - test.is_C = True - elif test.__name__.startswith("Py"): - for name, obj in py_io_ns.items(): - setattr(test, name, obj) - test.is_C = False - - suite = loader.suiteClass() - for test in tests: - suite.addTest(loader.loadTestsFromTestCase(test)) - return suite - -if __name__ == "__main__": - unittest.main() diff --git a/Lib/test/test_io/__init__.py b/Lib/test/test_io/__init__.py new file mode 100644 index 00000000000..c94fad3e779 --- /dev/null +++ b/Lib/test/test_io/__init__.py @@ -0,0 +1,28 @@ +"""Tests for the io module and its implementations (_io and _pyio) + +Tests are split across multiple files to increase +parallelism and focus on specific implementation pieces. + +* test_io + * test_bufferedio - tests file buffering + * test_memoryio - tests BytesIO and StringIO + * test_fileio - tests FileIO + * test_file - tests the file interface + * test_general - tests everything else in the io module + * test_univnewlines - tests universal newline support + * test_largefile - tests operations on a file greater than 2**32 bytes + (only enabled with -ulargefile) +* test_free_threading/test_io - tests thread safety of io objects + +.. attention:: + When writing tests for io, it's important to test both the C and Python + implementations. This is usually done by writing a base test that refers to + the type it is testing as an attribute. Then it provides custom subclasses to + test both implementations. This directory contains lots of examples. +""" + +import os +from test.support import load_package_tests + +def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_io/__main__.py b/Lib/test/test_io/__main__.py new file mode 100644 index 00000000000..40a23a297ec --- /dev/null +++ b/Lib/test/test_io/__main__.py @@ -0,0 +1,4 @@ +from . import load_tests +import unittest + +unittest.main() diff --git a/Lib/test/test_io/test_bufferedio.py b/Lib/test/test_io/test_bufferedio.py new file mode 100644 index 00000000000..e83dd0d4e28 --- /dev/null +++ b/Lib/test/test_io/test_bufferedio.py @@ -0,0 +1,1567 @@ +import array +import pickle +import random +import sys +import threading +import time +import unittest +import warnings +import weakref +from collections import deque, UserList +from itertools import cycle, count +from test import support +from test.support import check_sanitizer, os_helper, threading_helper +from .utils import byteslike, CTestCase, PyTestCase + + +import io # C implementation. +import _pyio as pyio # Python implementation. + + +class CommonBufferedTests: + # Tests common to BufferedReader, BufferedWriter and BufferedRandom + + def test_detach(self): + raw = self.MockRawIO() + buf = self.tp(raw) + self.assertIs(buf.detach(), raw) + self.assertRaises(ValueError, buf.detach) + + repr(buf) # Should still work + + def test_fileno(self): + rawio = self.MockRawIO() + bufio = self.tp(rawio) + + self.assertEqual(42, bufio.fileno()) + + def test_invalid_args(self): + rawio = self.MockRawIO() + bufio = self.tp(rawio) + # Invalid whence + self.assertRaises(ValueError, bufio.seek, 0, -1) + self.assertRaises(ValueError, bufio.seek, 0, 9) + + def test_override_destructor(self): + tp = self.tp + record = [] + class MyBufferedIO(tp): + def __del__(self): + record.append(1) + try: + f = super().__del__ + except AttributeError: + pass + else: + f() + def close(self): + record.append(2) + super().close() + def flush(self): + record.append(3) + super().flush() + rawio = self.MockRawIO() + bufio = MyBufferedIO(rawio) + del bufio + support.gc_collect() + self.assertEqual(record, [1, 2, 3]) + + def test_context_manager(self): + # Test usability as a context manager + rawio = self.MockRawIO() + bufio = self.tp(rawio) + def _with(): + with bufio: + pass + _with() + # bufio should now be closed, and using it a second time should raise + # a ValueError. + self.assertRaises(ValueError, _with) + + def test_error_through_destructor(self): + # Test that the exception state is not modified by a destructor, + # even if close() fails. + rawio = self.CloseFailureIO() + with support.catch_unraisable_exception() as cm: + with self.assertRaises(AttributeError): + self.tp(rawio).xyzzy + + self.assertEqual(cm.unraisable.exc_type, OSError) + + def test_repr(self): + raw = self.MockRawIO() + b = self.tp(raw) + clsname = r"(%s\.)?%s" % (self.tp.__module__, self.tp.__qualname__) + self.assertRegex(repr(b), "<%s>" % clsname) + raw.name = "dummy" + self.assertRegex(repr(b), "<%s name='dummy'>" % clsname) + raw.name = b"dummy" + self.assertRegex(repr(b), "<%s name=b'dummy'>" % clsname) + + def test_recursive_repr(self): + # Issue #25455 + raw = self.MockRawIO() + b = self.tp(raw) + with support.swap_attr(raw, 'name', b), support.infinite_recursion(25): + with self.assertRaises(RuntimeError): + repr(b) # Should not crash + + def test_flush_error_on_close(self): + # Test that buffered file is closed despite failed flush + # and that flush() is called before file closed. + raw = self.MockRawIO() + closed = [] + def bad_flush(): + closed[:] = [b.closed, raw.closed] + raise OSError() + raw.flush = bad_flush + b = self.tp(raw) + self.assertRaises(OSError, b.close) # exception not swallowed + self.assertTrue(b.closed) + self.assertTrue(raw.closed) + self.assertTrue(closed) # flush() called + self.assertFalse(closed[0]) # flush() called before file closed + self.assertFalse(closed[1]) + raw.flush = lambda: None # break reference loop + + def test_close_error_on_close(self): + raw = self.MockRawIO() + def bad_flush(): + raise OSError('flush') + def bad_close(): + raise OSError('close') + raw.close = bad_close + b = self.tp(raw) + b.flush = bad_flush + with self.assertRaises(OSError) as err: # exception not swallowed + b.close() + self.assertEqual(err.exception.args, ('close',)) + self.assertIsInstance(err.exception.__context__, OSError) + self.assertEqual(err.exception.__context__.args, ('flush',)) + self.assertFalse(b.closed) + + # Silence destructor error + raw.close = lambda: None + b.flush = lambda: None + + def test_nonnormalized_close_error_on_close(self): + # Issue #21677 + raw = self.MockRawIO() + def bad_flush(): + raise non_existing_flush + def bad_close(): + raise non_existing_close + raw.close = bad_close + b = self.tp(raw) + b.flush = bad_flush + with self.assertRaises(NameError) as err: # exception not swallowed + b.close() + self.assertIn('non_existing_close', str(err.exception)) + self.assertIsInstance(err.exception.__context__, NameError) + self.assertIn('non_existing_flush', str(err.exception.__context__)) + self.assertFalse(b.closed) + + # Silence destructor error + b.flush = lambda: None + raw.close = lambda: None + + def test_multi_close(self): + raw = self.MockRawIO() + b = self.tp(raw) + b.close() + b.close() + b.close() + self.assertRaises(ValueError, b.flush) + + def test_unseekable(self): + bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) + self.assertRaises(self.UnsupportedOperation, bufio.tell) + self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) + + def test_readonly_attributes(self): + raw = self.MockRawIO() + buf = self.tp(raw) + x = self.MockRawIO() + with self.assertRaises(AttributeError): + buf.raw = x + + def test_pickling_subclass(self): + global MyBufferedIO + class MyBufferedIO(self.tp): + def __init__(self, raw, tag): + super().__init__(raw) + self.tag = tag + def __getstate__(self): + return self.tag, self.raw.getvalue() + def __setstate__(slf, state): + tag, value = state + slf.__init__(self.BytesIO(value), tag) + + raw = self.BytesIO(b'data') + buf = MyBufferedIO(raw, tag='ham') + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=proto): + pickled = pickle.dumps(buf, proto) + newbuf = pickle.loads(pickled) + self.assertEqual(newbuf.raw.getvalue(), b'data') + self.assertEqual(newbuf.tag, 'ham') + del MyBufferedIO + + +class SizeofTest: + + @support.cpython_only + def test_sizeof(self): + bufsize1 = 4096 + bufsize2 = 8192 + rawio = self.MockRawIO() + bufio = self.tp(rawio, buffer_size=bufsize1) + size = sys.getsizeof(bufio) - bufsize1 + rawio = self.MockRawIO() + bufio = self.tp(rawio, buffer_size=bufsize2) + self.assertEqual(sys.getsizeof(bufio), size + bufsize2) + + @support.cpython_only + def test_buffer_freeing(self) : + bufsize = 4096 + rawio = self.MockRawIO() + bufio = self.tp(rawio, buffer_size=bufsize) + size = sys.getsizeof(bufio) - bufsize + bufio.close() + self.assertEqual(sys.getsizeof(bufio), size) + +class BufferedReaderTest(CommonBufferedTests): + read_mode = "rb" + + def test_constructor(self): + rawio = self.MockRawIO([b"abc"]) + bufio = self.tp(rawio) + bufio.__init__(rawio) + bufio.__init__(rawio, buffer_size=1024) + bufio.__init__(rawio, buffer_size=16) + self.assertEqual(b"abc", bufio.read()) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) + rawio = self.MockRawIO([b"abc"]) + bufio.__init__(rawio) + self.assertEqual(b"abc", bufio.read()) + + def test_uninitialized(self): + bufio = self.tp.__new__(self.tp) + del bufio + bufio = self.tp.__new__(self.tp) + self.assertRaisesRegex((ValueError, AttributeError), + 'uninitialized|has no attribute', + bufio.read, 0) + bufio.__init__(self.MockRawIO()) + self.assertEqual(bufio.read(0), b'') + + def test_read(self): + for arg in (None, 7): + rawio = self.MockRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + self.assertEqual(b"abcdefg", bufio.read(arg)) + # Invalid args + self.assertRaises(ValueError, bufio.read, -2) + + def test_read1(self): + rawio = self.MockRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + self.assertEqual(b"a", bufio.read(1)) + self.assertEqual(b"b", bufio.read1(1)) + self.assertEqual(rawio._reads, 1) + self.assertEqual(b"", bufio.read1(0)) + self.assertEqual(b"c", bufio.read1(100)) + self.assertEqual(rawio._reads, 1) + self.assertEqual(b"d", bufio.read1(100)) + self.assertEqual(rawio._reads, 2) + self.assertEqual(b"efg", bufio.read1(100)) + self.assertEqual(rawio._reads, 3) + self.assertEqual(b"", bufio.read1(100)) + self.assertEqual(rawio._reads, 4) + + def test_read1_arbitrary(self): + rawio = self.MockRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + self.assertEqual(b"a", bufio.read(1)) + self.assertEqual(b"bc", bufio.read1()) + self.assertEqual(b"d", bufio.read1()) + self.assertEqual(b"efg", bufio.read1(-1)) + self.assertEqual(rawio._reads, 3) + self.assertEqual(b"", bufio.read1()) + self.assertEqual(rawio._reads, 4) + + def test_readinto(self): + rawio = self.MockRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + b = bytearray(2) + self.assertEqual(bufio.readinto(b), 2) + self.assertEqual(b, b"ab") + self.assertEqual(bufio.readinto(b), 2) + self.assertEqual(b, b"cd") + self.assertEqual(bufio.readinto(b), 2) + self.assertEqual(b, b"ef") + self.assertEqual(bufio.readinto(b), 1) + self.assertEqual(b, b"gf") + self.assertEqual(bufio.readinto(b), 0) + self.assertEqual(b, b"gf") + rawio = self.MockRawIO((b"abc", None)) + bufio = self.tp(rawio) + self.assertEqual(bufio.readinto(b), 2) + self.assertEqual(b, b"ab") + self.assertEqual(bufio.readinto(b), 1) + self.assertEqual(b, b"cb") + + def test_readinto1(self): + buffer_size = 10 + rawio = self.MockRawIO((b"abc", b"de", b"fgh", b"jkl")) + bufio = self.tp(rawio, buffer_size=buffer_size) + b = bytearray(2) + self.assertEqual(bufio.peek(3), b'abc') + self.assertEqual(rawio._reads, 1) + self.assertEqual(bufio.readinto1(b), 2) + self.assertEqual(b, b"ab") + self.assertEqual(rawio._reads, 1) + self.assertEqual(bufio.readinto1(b), 1) + self.assertEqual(b[:1], b"c") + self.assertEqual(rawio._reads, 1) + self.assertEqual(bufio.readinto1(b), 2) + self.assertEqual(b, b"de") + self.assertEqual(rawio._reads, 2) + b = bytearray(2*buffer_size) + self.assertEqual(bufio.peek(3), b'fgh') + self.assertEqual(rawio._reads, 3) + self.assertEqual(bufio.readinto1(b), 6) + self.assertEqual(b[:6], b"fghjkl") + self.assertEqual(rawio._reads, 4) + + def test_readinto_array(self): + buffer_size = 60 + data = b"a" * 26 + rawio = self.MockRawIO((data,)) + bufio = self.tp(rawio, buffer_size=buffer_size) + + # Create an array with element size > 1 byte + b = array.array('i', b'x' * 32) + assert len(b) != 16 + + # Read into it. We should get as many *bytes* as we can fit into b + # (which is more than the number of elements) + n = bufio.readinto(b) + self.assertGreater(n, len(b)) + + # Check that old contents of b are preserved + bm = memoryview(b).cast('B') + self.assertLess(n, len(bm)) + self.assertEqual(bm[:n], data[:n]) + self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) + + def test_readinto1_array(self): + buffer_size = 60 + data = b"a" * 26 + rawio = self.MockRawIO((data,)) + bufio = self.tp(rawio, buffer_size=buffer_size) + + # Create an array with element size > 1 byte + b = array.array('i', b'x' * 32) + assert len(b) != 16 + + # Read into it. We should get as many *bytes* as we can fit into b + # (which is more than the number of elements) + n = bufio.readinto1(b) + self.assertGreater(n, len(b)) + + # Check that old contents of b are preserved + bm = memoryview(b).cast('B') + self.assertLess(n, len(bm)) + self.assertEqual(bm[:n], data[:n]) + self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) + + def test_readlines(self): + def bufio(): + rawio = self.MockRawIO((b"abc\n", b"d\n", b"ef")) + return self.tp(rawio) + self.assertEqual(bufio().readlines(), [b"abc\n", b"d\n", b"ef"]) + self.assertEqual(bufio().readlines(5), [b"abc\n", b"d\n"]) + self.assertEqual(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"]) + + def test_buffering(self): + data = b"abcdefghi" + dlen = len(data) + + tests = [ + [ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ], + [ 100, [ 3, 3, 3], [ dlen ] ], + [ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ], + ] + + for bufsize, buf_read_sizes, raw_read_sizes in tests: + rawio = self.MockFileIO(data) + bufio = self.tp(rawio, buffer_size=bufsize) + pos = 0 + for nbytes in buf_read_sizes: + self.assertEqual(bufio.read(nbytes), data[pos:pos+nbytes]) + pos += nbytes + # this is mildly implementation-dependent + self.assertEqual(rawio.read_history, raw_read_sizes) + + def test_read_non_blocking(self): + # Inject some None's in there to simulate EWOULDBLOCK + rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None)) + bufio = self.tp(rawio) + self.assertEqual(b"abcd", bufio.read(6)) + self.assertEqual(b"e", bufio.read(1)) + self.assertEqual(b"fg", bufio.read()) + self.assertEqual(b"", bufio.peek(1)) + self.assertIsNone(bufio.read()) + self.assertEqual(b"", bufio.read()) + + rawio = self.MockRawIO((b"a", None, None)) + self.assertEqual(b"a", rawio.readall()) + self.assertIsNone(rawio.readall()) + + def test_read_past_eof(self): + rawio = self.MockRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + + self.assertEqual(b"abcdefg", bufio.read(9000)) + + def test_read_all(self): + rawio = self.MockRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + + self.assertEqual(b"abcdefg", bufio.read()) + + @threading_helper.requires_working_threading() + @support.requires_resource('cpu') + def test_threads(self): + try: + # Write out many bytes with exactly the same number of 0's, + # 1's... 255's. This will help us check that concurrent reading + # doesn't duplicate or forget contents. + N = 1000 + l = list(range(256)) * N + random.shuffle(l) + s = bytes(bytearray(l)) + with self.open(os_helper.TESTFN, "wb") as f: + f.write(s) + with self.open(os_helper.TESTFN, self.read_mode, buffering=0) as raw: + bufio = self.tp(raw, 8) + errors = [] + results = [] + def f(): + try: + # Intra-buffer read then buffer-flushing read + for n in cycle([1, 19]): + s = bufio.read(n) + if not s: + break + # list.append() is atomic + results.append(s) + except Exception as e: + errors.append(e) + raise + threads = [threading.Thread(target=f) for x in range(20)] + with threading_helper.start_threads(threads): + time.sleep(0.02) # yield + self.assertFalse(errors, + "the following exceptions were caught: %r" % errors) + s = b''.join(results) + for i in range(256): + c = bytes(bytearray([i])) + self.assertEqual(s.count(c), N) + finally: + os_helper.unlink(os_helper.TESTFN) + + def test_unseekable(self): + bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) + self.assertRaises(self.UnsupportedOperation, bufio.tell) + self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) + bufio.read(1) + self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) + self.assertRaises(self.UnsupportedOperation, bufio.tell) + + def test_misbehaved_io(self): + rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + self.assertRaises(OSError, bufio.seek, 0) + self.assertRaises(OSError, bufio.tell) + + # Silence destructor error + bufio.close = lambda: None + + def test_no_extraneous_read(self): + # Issue #9550; when the raw IO object has satisfied the read request, + # we should not issue any additional reads, otherwise it may block + # (e.g. socket). + bufsize = 16 + for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2): + rawio = self.MockRawIO([b"x" * n]) + bufio = self.tp(rawio, bufsize) + self.assertEqual(bufio.read(n), b"x" * n) + # Simple case: one raw read is enough to satisfy the request. + self.assertEqual(rawio._extraneous_reads, 0, + "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) + # A more complex case where two raw reads are needed to satisfy + # the request. + rawio = self.MockRawIO([b"x" * (n - 1), b"x"]) + bufio = self.tp(rawio, bufsize) + self.assertEqual(bufio.read(n), b"x" * n) + self.assertEqual(rawio._extraneous_reads, 0, + "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) + + def test_read_on_closed(self): + # Issue #23796 + b = self.BufferedReader(self.BytesIO(b"12")) + b.read(1) + b.close() + with self.subTest('peek'): + self.assertRaises(ValueError, b.peek) + with self.subTest('read1'): + self.assertRaises(ValueError, b.read1, 1) + with self.subTest('read'): + self.assertRaises(ValueError, b.read) + with self.subTest('readinto'): + self.assertRaises(ValueError, b.readinto, bytearray()) + with self.subTest('readinto1'): + self.assertRaises(ValueError, b.readinto1, bytearray()) + with self.subTest('flush'): + self.assertRaises(ValueError, b.flush) + with self.subTest('truncate'): + self.assertRaises(ValueError, b.truncate) + with self.subTest('seek'): + self.assertRaises(ValueError, b.seek, 0) + + def test_truncate_on_read_only(self): + rawio = self.MockFileIO(b"abc") + bufio = self.tp(rawio) + self.assertFalse(bufio.writable()) + self.assertRaises(self.UnsupportedOperation, bufio.truncate) + self.assertRaises(self.UnsupportedOperation, bufio.truncate, 0) + + def test_tell_character_device_file(self): + # GH-95782 + # For the (former) bug in BufferedIO to manifest, the wrapped IO obj + # must be able to produce at least 2 bytes. + raw = self.MockCharPseudoDevFileIO(b"12") + buf = self.tp(raw) + self.assertEqual(buf.tell(), 0) + self.assertEqual(buf.read(1), b"1") + self.assertEqual(buf.tell(), 0) + + def test_seek_character_device_file(self): + raw = self.MockCharPseudoDevFileIO(b"12") + buf = self.tp(raw) + self.assertEqual(buf.seek(0, io.SEEK_CUR), 0) + self.assertEqual(buf.seek(1, io.SEEK_SET), 0) + self.assertEqual(buf.seek(0, io.SEEK_CUR), 0) + self.assertEqual(buf.read(1), b"1") + + # In the C implementation, tell() sets the BufferedIO's abs_pos to 0, + # which means that the next seek() could return a negative offset if it + # does not sanity-check: + self.assertEqual(buf.tell(), 0) + self.assertEqual(buf.seek(0, io.SEEK_CUR), 0) + + +class CBufferedReaderTest(BufferedReaderTest, SizeofTest, CTestCase): + tp = io.BufferedReader + + def test_initialization(self): + rawio = self.MockRawIO([b"abc"]) + bufio = self.tp(rawio) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) + self.assertRaises(ValueError, bufio.read) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) + self.assertRaises(ValueError, bufio.read) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) + self.assertRaises(ValueError, bufio.read) + + def test_misbehaved_io_read(self): + rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) + bufio = self.tp(rawio) + # _pyio.BufferedReader seems to implement reading different, so that + # checking this is not so easy. + self.assertRaises(OSError, bufio.read, 10) + + def test_garbage_collection(self): + # C BufferedReader objects are collected. + # The Python version has __del__, so it ends into gc.garbage instead + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + # Note that using warnings_helper.check_warnings() will keep the + # file alive due to the `source` argument to warn(). So, use + # catch_warnings() instead. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + rawio = self.FileIO(os_helper.TESTFN, "w+b") + f = self.tp(rawio) + f.f = f + wr = weakref.ref(f) + del f + support.gc_collect() + self.assertIsNone(wr(), wr) + + def test_args_error(self): + # Issue #17275 + with self.assertRaisesRegex(TypeError, "BufferedReader"): + self.tp(self.BytesIO(), 1024, 1024, 1024) + + def test_bad_readinto_value(self): + rawio = self.tp(self.BytesIO(b"12")) + rawio.readinto = lambda buf: -1 + bufio = self.tp(rawio) + with self.assertRaises(OSError) as cm: + bufio.readline() + self.assertIsNone(cm.exception.__cause__) + + def test_bad_readinto_type(self): + rawio = self.tp(self.BytesIO(b"12")) + rawio.readinto = lambda buf: b'' + bufio = self.tp(rawio) + with self.assertRaises(OSError) as cm: + bufio.readline() + self.assertIsInstance(cm.exception.__cause__, TypeError) + + @unittest.skipUnless(sys.maxsize > 2**32, 'requires 64bit platform') + @unittest.skipIf(check_sanitizer(thread=True), + 'ThreadSanitizer aborts on huge allocations (exit code 66).') + def test_read1_error_does_not_cause_reentrant_failure(self): + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + with self.open(os_helper.TESTFN, "wb") as f: + f.write(b"hello") + + with self.open(os_helper.TESTFN, "rb", buffering=0) as raw: + bufio = self.tp(raw, buffer_size=8) + # To request a size that is far too huge to ever be satisfied, + # so that the internal buffer allocation reliably fails with MemoryError. + huge = sys.maxsize // 2 + 1 + with self.assertRaises(MemoryError): + bufio.read1(huge) + + # Used to crash before gh-143689: + self.assertEqual(bufio.read1(1), b"h") + + +class PyBufferedReaderTest(BufferedReaderTest, PyTestCase): + tp = pyio.BufferedReader + + +class BufferedWriterTest(CommonBufferedTests): + write_mode = "wb" + + def test_constructor(self): + rawio = self.MockRawIO() + bufio = self.tp(rawio) + bufio.__init__(rawio) + bufio.__init__(rawio, buffer_size=1024) + bufio.__init__(rawio, buffer_size=16) + self.assertEqual(3, bufio.write(b"abc")) + bufio.flush() + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) + bufio.__init__(rawio) + self.assertEqual(3, bufio.write(b"ghi")) + bufio.flush() + self.assertEqual(b"".join(rawio._write_stack), b"abcghi") + + def test_uninitialized(self): + bufio = self.tp.__new__(self.tp) + del bufio + bufio = self.tp.__new__(self.tp) + self.assertRaisesRegex((ValueError, AttributeError), + 'uninitialized|has no attribute', + bufio.write, b'') + bufio.__init__(self.MockRawIO()) + self.assertEqual(bufio.write(b''), 0) + + def test_detach_flush(self): + raw = self.MockRawIO() + buf = self.tp(raw) + buf.write(b"howdy!") + self.assertFalse(raw._write_stack) + buf.detach() + self.assertEqual(raw._write_stack, [b"howdy!"]) + + def test_write(self): + # Write to the buffered IO but don't overflow the buffer. + writer = self.MockRawIO() + bufio = self.tp(writer, 8) + bufio.write(b"abc") + self.assertFalse(writer._write_stack) + buffer = bytearray(b"def") + bufio.write(buffer) + buffer[:] = b"***" # Overwrite our copy of the data + bufio.flush() + self.assertEqual(b"".join(writer._write_stack), b"abcdef") + + def test_write_overflow(self): + writer = self.MockRawIO() + bufio = self.tp(writer, 8) + contents = b"abcdefghijklmnop" + for n in range(0, len(contents), 3): + bufio.write(contents[n:n+3]) + flushed = b"".join(writer._write_stack) + # At least (total - 8) bytes were implicitly flushed, perhaps more + # depending on the implementation. + self.assertStartsWith(flushed, contents[:-8]) + + def check_writes(self, intermediate_func): + # Lots of writes, test the flushed output is as expected. + contents = bytes(range(256)) * 1000 + n = 0 + writer = self.MockRawIO() + bufio = self.tp(writer, 13) + # Generator of write sizes: repeat each N 15 times then proceed to N+1 + def gen_sizes(): + for size in count(1): + for i in range(15): + yield size + sizes = gen_sizes() + while n < len(contents): + size = min(next(sizes), len(contents) - n) + self.assertEqual(bufio.write(contents[n:n+size]), size) + intermediate_func(bufio) + n += size + bufio.flush() + self.assertEqual(contents, b"".join(writer._write_stack)) + + def test_writes(self): + self.check_writes(lambda bufio: None) + + def test_writes_and_flushes(self): + self.check_writes(lambda bufio: bufio.flush()) + + def test_writes_and_seeks(self): + def _seekabs(bufio): + pos = bufio.tell() + bufio.seek(pos + 1, 0) + bufio.seek(pos - 1, 0) + bufio.seek(pos, 0) + self.check_writes(_seekabs) + def _seekrel(bufio): + pos = bufio.seek(0, 1) + bufio.seek(+1, 1) + bufio.seek(-1, 1) + bufio.seek(pos, 0) + self.check_writes(_seekrel) + + def test_writes_and_truncates(self): + self.check_writes(lambda bufio: bufio.truncate(bufio.tell())) + + def test_write_non_blocking(self): + raw = self.MockNonBlockWriterIO() + bufio = self.tp(raw, 8) + + self.assertEqual(bufio.write(b"abcd"), 4) + self.assertEqual(bufio.write(b"efghi"), 5) + # 1 byte will be written, the rest will be buffered + raw.block_on(b"k") + self.assertEqual(bufio.write(b"jklmn"), 5) + + # 8 bytes will be written, 8 will be buffered and the rest will be lost + raw.block_on(b"0") + try: + bufio.write(b"opqrwxyz0123456789") + except self.BlockingIOError as e: + written = e.characters_written + else: + self.fail("BlockingIOError should have been raised") + self.assertEqual(written, 16) + self.assertEqual(raw.pop_written(), + b"abcdefghijklmnopqrwxyz") + + self.assertEqual(bufio.write(b"ABCDEFGHI"), 9) + s = raw.pop_written() + # Previously buffered bytes were flushed + self.assertStartsWith(s, b"01234567A") + + def test_write_and_rewind(self): + raw = self.BytesIO() + bufio = self.tp(raw, 4) + self.assertEqual(bufio.write(b"abcdef"), 6) + self.assertEqual(bufio.tell(), 6) + bufio.seek(0, 0) + self.assertEqual(bufio.write(b"XY"), 2) + bufio.seek(6, 0) + self.assertEqual(raw.getvalue(), b"XYcdef") + self.assertEqual(bufio.write(b"123456"), 6) + bufio.flush() + self.assertEqual(raw.getvalue(), b"XYcdef123456") + + def test_flush(self): + writer = self.MockRawIO() + bufio = self.tp(writer, 8) + bufio.write(b"abc") + bufio.flush() + self.assertEqual(b"abc", writer._write_stack[0]) + + def test_writelines(self): + l = [b'ab', b'cd', b'ef'] + writer = self.MockRawIO() + bufio = self.tp(writer, 8) + bufio.writelines(l) + bufio.flush() + self.assertEqual(b''.join(writer._write_stack), b'abcdef') + + def test_writelines_userlist(self): + l = UserList([b'ab', b'cd', b'ef']) + writer = self.MockRawIO() + bufio = self.tp(writer, 8) + bufio.writelines(l) + bufio.flush() + self.assertEqual(b''.join(writer._write_stack), b'abcdef') + + def test_writelines_error(self): + writer = self.MockRawIO() + bufio = self.tp(writer, 8) + self.assertRaises(TypeError, bufio.writelines, [1, 2, 3]) + self.assertRaises(TypeError, bufio.writelines, None) + self.assertRaises(TypeError, bufio.writelines, 'abc') + + def test_destructor(self): + writer = self.MockRawIO() + bufio = self.tp(writer, 8) + bufio.write(b"abc") + del bufio + support.gc_collect() + self.assertEqual(b"abc", writer._write_stack[0]) + + def test_truncate(self): + # Truncate implicitly flushes the buffer. + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + with self.open(os_helper.TESTFN, self.write_mode, buffering=0) as raw: + bufio = self.tp(raw, 8) + bufio.write(b"abcdef") + self.assertEqual(bufio.truncate(3), 3) + self.assertEqual(bufio.tell(), 6) + with self.open(os_helper.TESTFN, "rb", buffering=0) as f: + self.assertEqual(f.read(), b"abc") + + def test_truncate_after_write(self): + # Ensure that truncate preserves the file position after + # writes longer than the buffer size. + # Issue: https://bugs.python.org/issue32228 + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + with self.open(os_helper.TESTFN, "wb") as f: + # Fill with some buffer + f.write(b'\x00' * 10000) + buffer_sizes = [8192, 4096, 200] + for buffer_size in buffer_sizes: + with self.open(os_helper.TESTFN, "r+b", buffering=buffer_size) as f: + f.write(b'\x00' * (buffer_size + 1)) + # After write write_pos and write_end are set to 0 + f.read(1) + # read operation makes sure that pos != raw_pos + f.truncate() + self.assertEqual(f.tell(), buffer_size + 2) + + @threading_helper.requires_working_threading() + @support.requires_resource('cpu') + def test_threads(self): + try: + # Write out many bytes from many threads and test they were + # all flushed. + N = 1000 + contents = bytes(range(256)) * N + sizes = cycle([1, 19]) + n = 0 + queue = deque() + while n < len(contents): + size = next(sizes) + queue.append(contents[n:n+size]) + n += size + del contents + # We use a real file object because it allows us to + # exercise situations where the GIL is released before + # writing the buffer to the raw streams. This is in addition + # to concurrency issues due to switching threads in the middle + # of Python code. + with self.open(os_helper.TESTFN, self.write_mode, buffering=0) as raw: + bufio = self.tp(raw, 8) + errors = [] + def f(): + try: + while True: + try: + s = queue.popleft() + except IndexError: + return + bufio.write(s) + except Exception as e: + errors.append(e) + raise + threads = [threading.Thread(target=f) for x in range(20)] + with threading_helper.start_threads(threads): + time.sleep(0.02) # yield + self.assertFalse(errors, + "the following exceptions were caught: %r" % errors) + bufio.close() + with self.open(os_helper.TESTFN, "rb") as f: + s = f.read() + for i in range(256): + self.assertEqual(s.count(bytes([i])), N) + finally: + os_helper.unlink(os_helper.TESTFN) + + def test_misbehaved_io(self): + rawio = self.MisbehavedRawIO() + bufio = self.tp(rawio, 5) + self.assertRaises(OSError, bufio.seek, 0) + self.assertRaises(OSError, bufio.tell) + self.assertRaises(OSError, bufio.write, b"abcdef") + + # Silence destructor error + bufio.close = lambda: None + + def test_max_buffer_size_removal(self): + with self.assertRaises(TypeError): + self.tp(self.MockRawIO(), 8, 12) + + def test_write_error_on_close(self): + raw = self.MockRawIO() + def bad_write(b): + raise OSError() + raw.write = bad_write + b = self.tp(raw) + b.write(b'spam') + self.assertRaises(OSError, b.close) # exception not swallowed + self.assertTrue(b.closed) + + @threading_helper.requires_working_threading() + def test_slow_close_from_thread(self): + # Issue #31976 + rawio = self.SlowFlushRawIO() + bufio = self.tp(rawio, 8) + t = threading.Thread(target=bufio.close) + t.start() + rawio.in_flush.wait() + self.assertRaises(ValueError, bufio.write, b'spam') + self.assertTrue(bufio.closed) + t.join() + + +class CBufferedWriterTest(BufferedWriterTest, SizeofTest, CTestCase): + tp = io.BufferedWriter + + def test_initialization(self): + rawio = self.MockRawIO() + bufio = self.tp(rawio) + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) + self.assertRaises(ValueError, bufio.write, b"def") + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) + self.assertRaises(ValueError, bufio.write, b"def") + self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) + self.assertRaises(ValueError, bufio.write, b"def") + + def test_garbage_collection(self): + # C BufferedWriter objects are collected, and collecting them flushes + # all data to disk. + # The Python version has __del__, so it ends into gc.garbage instead + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + # Note that using warnings_helper.check_warnings() will keep the + # file alive due to the `source` argument to warn(). So, use + # catch_warnings() instead. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + rawio = self.FileIO(os_helper.TESTFN, "w+b") + f = self.tp(rawio) + f.write(b"123xxx") + f.x = f + wr = weakref.ref(f) + del f + support.gc_collect() + self.assertIsNone(wr(), wr) + with self.open(os_helper.TESTFN, "rb") as f: + self.assertEqual(f.read(), b"123xxx") + + def test_args_error(self): + # Issue #17275 + with self.assertRaisesRegex(TypeError, "BufferedWriter"): + self.tp(self.BytesIO(), 1024, 1024, 1024) + + def test_non_boolean_closed_attr(self): + # gh-140650: check TypeError is raised + class MockRawIOWithoutClosed(self.MockRawIO): + closed = NotImplemented + + bufio = self.tp(MockRawIOWithoutClosed()) + self.assertRaises(TypeError, bufio.write, b"") + self.assertRaises(TypeError, bufio.flush) + self.assertRaises(TypeError, bufio.close) + + def test_closed_attr_raises(self): + class MockRawIOClosedRaises(self.MockRawIO): + @property + def closed(self): + raise ValueError("test") + + bufio = self.tp(MockRawIOClosedRaises()) + self.assertRaisesRegex(ValueError, "test", bufio.write, b"") + self.assertRaisesRegex(ValueError, "test", bufio.flush) + self.assertRaisesRegex(ValueError, "test", bufio.close) + + +class PyBufferedWriterTest(BufferedWriterTest, PyTestCase): + tp = pyio.BufferedWriter + +class BufferedRWPairTest: + + def test_constructor(self): + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertFalse(pair.closed) + + def test_uninitialized(self): + pair = self.tp.__new__(self.tp) + del pair + pair = self.tp.__new__(self.tp) + self.assertRaisesRegex((ValueError, AttributeError), + 'uninitialized|has no attribute', + pair.read, 0) + self.assertRaisesRegex((ValueError, AttributeError), + 'uninitialized|has no attribute', + pair.write, b'') + pair.__init__(self.MockRawIO(), self.MockRawIO()) + self.assertEqual(pair.read(0), b'') + self.assertEqual(pair.write(b''), 0) + + def test_detach(self): + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertRaises(self.UnsupportedOperation, pair.detach) + + def test_constructor_max_buffer_size_removal(self): + with self.assertRaises(TypeError): + self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) + + def test_constructor_with_not_readable(self): + class NotReadable(self.MockRawIO): + def readable(self): + return False + + self.assertRaises(OSError, self.tp, NotReadable(), self.MockRawIO()) + + def test_constructor_with_not_writeable(self): + class NotWriteable(self.MockRawIO): + def writable(self): + return False + + self.assertRaises(OSError, self.tp, self.MockRawIO(), NotWriteable()) + + def test_read(self): + pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) + + self.assertEqual(pair.read(3), b"abc") + self.assertEqual(pair.read(1), b"d") + self.assertEqual(pair.read(), b"ef") + pair = self.tp(self.BytesIO(b"abc"), self.MockRawIO()) + self.assertEqual(pair.read(None), b"abc") + + def test_readlines(self): + pair = lambda: self.tp(self.BytesIO(b"abc\ndef\nh"), self.MockRawIO()) + self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) + self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) + self.assertEqual(pair().readlines(5), [b"abc\n", b"def\n"]) + + def test_read1(self): + # .read1() is delegated to the underlying reader object, so this test + # can be shallow. + pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) + + self.assertEqual(pair.read1(3), b"abc") + self.assertEqual(pair.read1(), b"def") + + def test_readinto(self): + for method in ("readinto", "readinto1"): + with self.subTest(method): + pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) + + data = byteslike(b'\0' * 5) + self.assertEqual(getattr(pair, method)(data), 5) + self.assertEqual(bytes(data), b"abcde") + + # gh-138720: C BufferedRWPair would destruct in a bad order resulting in + # an unraisable exception. + support.gc_collect() + + def test_write(self): + w = self.MockRawIO() + pair = self.tp(self.MockRawIO(), w) + + pair.write(b"abc") + pair.flush() + buffer = bytearray(b"def") + pair.write(buffer) + buffer[:] = b"***" # Overwrite our copy of the data + pair.flush() + self.assertEqual(w._write_stack, [b"abc", b"def"]) + + def test_peek(self): + pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) + + self.assertStartsWith(pair.peek(3), b"abc") + self.assertEqual(pair.read(3), b"abc") + + def test_readable(self): + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertTrue(pair.readable()) + + def test_writeable(self): + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertTrue(pair.writable()) + + def test_seekable(self): + # BufferedRWPairs are never seekable, even if their readers and writers + # are. + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertFalse(pair.seekable()) + + # .flush() is delegated to the underlying writer object and has been + # tested in the test_write method. + + def test_close_and_closed(self): + pair = self.tp(self.MockRawIO(), self.MockRawIO()) + self.assertFalse(pair.closed) + pair.close() + self.assertTrue(pair.closed) + + def test_reader_close_error_on_close(self): + def reader_close(): + reader_non_existing + reader = self.MockRawIO() + reader.close = reader_close + writer = self.MockRawIO() + pair = self.tp(reader, writer) + with self.assertRaises(NameError) as err: + pair.close() + self.assertIn('reader_non_existing', str(err.exception)) + self.assertTrue(pair.closed) + self.assertFalse(reader.closed) + self.assertTrue(writer.closed) + + # Silence destructor error + reader.close = lambda: None + + def test_writer_close_error_on_close(self): + def writer_close(): + writer_non_existing + reader = self.MockRawIO() + writer = self.MockRawIO() + writer.close = writer_close + pair = self.tp(reader, writer) + with self.assertRaises(NameError) as err: + pair.close() + self.assertIn('writer_non_existing', str(err.exception)) + self.assertFalse(pair.closed) + self.assertTrue(reader.closed) + self.assertFalse(writer.closed) + + # Silence destructor error + writer.close = lambda: None + writer = None + + # Ignore BufferedWriter (of the BufferedRWPair) unraisable exception + with support.catch_unraisable_exception(): + # Ignore BufferedRWPair unraisable exception + with support.catch_unraisable_exception(): + pair = None + support.gc_collect() + support.gc_collect() + + def test_reader_writer_close_error_on_close(self): + def reader_close(): + reader_non_existing + def writer_close(): + writer_non_existing + reader = self.MockRawIO() + reader.close = reader_close + writer = self.MockRawIO() + writer.close = writer_close + pair = self.tp(reader, writer) + with self.assertRaises(NameError) as err: + pair.close() + self.assertIn('reader_non_existing', str(err.exception)) + self.assertIsInstance(err.exception.__context__, NameError) + self.assertIn('writer_non_existing', str(err.exception.__context__)) + self.assertFalse(pair.closed) + self.assertFalse(reader.closed) + self.assertFalse(writer.closed) + + # Silence destructor error + reader.close = lambda: None + writer.close = lambda: None + + def test_isatty(self): + class SelectableIsAtty(self.MockRawIO): + def __init__(self, isatty): + super().__init__() + self._isatty = isatty + + def isatty(self): + return self._isatty + + pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(False)) + self.assertFalse(pair.isatty()) + + pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(False)) + self.assertTrue(pair.isatty()) + + pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(True)) + self.assertTrue(pair.isatty()) + + pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True)) + self.assertTrue(pair.isatty()) + + def test_weakref_clearing(self): + brw = self.tp(self.MockRawIO(), self.MockRawIO()) + ref = weakref.ref(brw) + brw = None + ref = None # Shouldn't segfault. + +class CBufferedRWPairTest(BufferedRWPairTest, CTestCase): + tp = io.BufferedRWPair + +class PyBufferedRWPairTest(BufferedRWPairTest, PyTestCase): + tp = pyio.BufferedRWPair + + +class BufferedRandomTest(BufferedReaderTest, BufferedWriterTest): + read_mode = "rb+" + write_mode = "wb+" + + def test_constructor(self): + BufferedReaderTest.test_constructor(self) + BufferedWriterTest.test_constructor(self) + + def test_uninitialized(self): + BufferedReaderTest.test_uninitialized(self) + BufferedWriterTest.test_uninitialized(self) + + def test_read_and_write(self): + raw = self.MockRawIO((b"asdf", b"ghjk")) + rw = self.tp(raw, 8) + + self.assertEqual(b"as", rw.read(2)) + rw.write(b"ddd") + rw.write(b"eee") + self.assertFalse(raw._write_stack) # Buffer writes + self.assertEqual(b"ghjk", rw.read()) + self.assertEqual(b"dddeee", raw._write_stack[0]) + + def test_seek_and_tell(self): + raw = self.BytesIO(b"asdfghjkl") + rw = self.tp(raw) + + self.assertEqual(b"as", rw.read(2)) + self.assertEqual(2, rw.tell()) + rw.seek(0, 0) + self.assertEqual(b"asdf", rw.read(4)) + + rw.write(b"123f") + rw.seek(0, 0) + self.assertEqual(b"asdf123fl", rw.read()) + self.assertEqual(9, rw.tell()) + rw.seek(-4, 2) + self.assertEqual(5, rw.tell()) + rw.seek(2, 1) + self.assertEqual(7, rw.tell()) + self.assertEqual(b"fl", rw.read(11)) + rw.flush() + self.assertEqual(b"asdf123fl", raw.getvalue()) + + self.assertRaises(TypeError, rw.seek, 0.0) + + def check_flush_and_read(self, read_func): + raw = self.BytesIO(b"abcdefghi") + bufio = self.tp(raw) + + self.assertEqual(b"ab", read_func(bufio, 2)) + bufio.write(b"12") + self.assertEqual(b"ef", read_func(bufio, 2)) + self.assertEqual(6, bufio.tell()) + bufio.flush() + self.assertEqual(6, bufio.tell()) + self.assertEqual(b"ghi", read_func(bufio)) + raw.seek(0, 0) + raw.write(b"XYZ") + # flush() resets the read buffer + bufio.flush() + bufio.seek(0, 0) + self.assertEqual(b"XYZ", read_func(bufio, 3)) + + def test_flush_and_read(self): + self.check_flush_and_read(lambda bufio, *args: bufio.read(*args)) + + def test_flush_and_readinto(self): + def _readinto(bufio, n=-1): + b = bytearray(n if n >= 0 else 9999) + n = bufio.readinto(b) + b.resize(n) + return b.take_bytes() + self.check_flush_and_read(_readinto) + + def test_flush_and_peek(self): + def _peek(bufio, n=-1): + # This relies on the fact that the buffer can contain the whole + # raw stream, otherwise peek() can return less. + b = bufio.peek(n) + if n != -1: + b = b[:n] + bufio.seek(len(b), 1) + return b + self.check_flush_and_read(_peek) + + def test_flush_and_write(self): + raw = self.BytesIO(b"abcdefghi") + bufio = self.tp(raw) + + bufio.write(b"123") + bufio.flush() + bufio.write(b"45") + bufio.flush() + bufio.seek(0, 0) + self.assertEqual(b"12345fghi", raw.getvalue()) + self.assertEqual(b"12345fghi", bufio.read()) + + def test_threads(self): + BufferedReaderTest.test_threads(self) + BufferedWriterTest.test_threads(self) + + def test_writes_and_peek(self): + def _peek(bufio): + bufio.peek(1) + self.check_writes(_peek) + def _peek(bufio): + pos = bufio.tell() + bufio.seek(-1, 1) + bufio.peek(1) + bufio.seek(pos, 0) + self.check_writes(_peek) + + def test_writes_and_reads(self): + def _read(bufio): + bufio.seek(-1, 1) + bufio.read(1) + self.check_writes(_read) + + def test_writes_and_read1s(self): + def _read1(bufio): + bufio.seek(-1, 1) + bufio.read1(1) + self.check_writes(_read1) + + def test_writes_and_readintos(self): + def _read(bufio): + bufio.seek(-1, 1) + bufio.readinto(bytearray(1)) + self.check_writes(_read) + + def test_write_after_readahead(self): + # Issue #6629: writing after the buffer was filled by readahead should + # first rewind the raw stream. + for overwrite_size in [1, 5]: + raw = self.BytesIO(b"A" * 10) + bufio = self.tp(raw, 4) + # Trigger readahead + self.assertEqual(bufio.read(1), b"A") + self.assertEqual(bufio.tell(), 1) + # Overwriting should rewind the raw stream if it needs so + bufio.write(b"B" * overwrite_size) + self.assertEqual(bufio.tell(), overwrite_size + 1) + # If the write size was smaller than the buffer size, flush() and + # check that rewind happens. + bufio.flush() + self.assertEqual(bufio.tell(), overwrite_size + 1) + s = raw.getvalue() + self.assertEqual(s, + b"A" + b"B" * overwrite_size + b"A" * (9 - overwrite_size)) + + def test_write_rewind_write(self): + # Various combinations of reading / writing / seeking backwards / writing again + def mutate(bufio, pos1, pos2): + assert pos2 >= pos1 + # Fill the buffer + bufio.seek(pos1) + bufio.read(pos2 - pos1) + bufio.write(b'\x02') + # This writes earlier than the previous write, but still inside + # the buffer. + bufio.seek(pos1) + bufio.write(b'\x01') + + b = b"\x80\x81\x82\x83\x84" + for i in range(0, len(b)): + for j in range(i, len(b)): + raw = self.BytesIO(b) + bufio = self.tp(raw, 100) + mutate(bufio, i, j) + bufio.flush() + expected = bytearray(b) + expected[j] = 2 + expected[i] = 1 + self.assertEqual(raw.getvalue(), expected, + "failed result for i=%d, j=%d" % (i, j)) + + def test_truncate_after_read_or_write(self): + raw = self.BytesIO(b"A" * 10) + bufio = self.tp(raw, 100) + self.assertEqual(bufio.read(2), b"AA") # the read buffer gets filled + self.assertEqual(bufio.truncate(), 2) + self.assertEqual(bufio.write(b"BB"), 2) # the write buffer increases + self.assertEqual(bufio.truncate(), 4) + + def test_misbehaved_io(self): + BufferedReaderTest.test_misbehaved_io(self) + BufferedWriterTest.test_misbehaved_io(self) + + def test_interleaved_read_write(self): + # Test for issue #12213 + with self.BytesIO(b'abcdefgh') as raw: + with self.tp(raw, 100) as f: + f.write(b"1") + self.assertEqual(f.read(1), b'b') + f.write(b'2') + self.assertEqual(f.read1(1), b'd') + f.write(b'3') + buf = bytearray(1) + f.readinto(buf) + self.assertEqual(buf, b'f') + f.write(b'4') + self.assertEqual(f.peek(1), b'h') + f.flush() + self.assertEqual(raw.getvalue(), b'1b2d3f4h') + + with self.BytesIO(b'abc') as raw: + with self.tp(raw, 100) as f: + self.assertEqual(f.read(1), b'a') + f.write(b"2") + self.assertEqual(f.read(1), b'c') + f.flush() + self.assertEqual(raw.getvalue(), b'a2c') + + def test_read1_after_write(self): + with self.BytesIO(b'abcdef') as raw: + with self.tp(raw, 3) as f: + f.write(b"1") + self.assertEqual(f.read1(1), b'b') + f.flush() + self.assertEqual(raw.getvalue(), b'1bcdef') + with self.BytesIO(b'abcdef') as raw: + with self.tp(raw, 3) as f: + f.write(b"1") + self.assertEqual(f.read1(), b'bcd') + f.flush() + self.assertEqual(raw.getvalue(), b'1bcdef') + with self.BytesIO(b'abcdef') as raw: + with self.tp(raw, 3) as f: + f.write(b"1") + # XXX: read(100) returns different numbers of bytes + # in Python and C implementations. + self.assertEqual(f.read1(100)[:3], b'bcd') + f.flush() + self.assertEqual(raw.getvalue(), b'1bcdef') + + def test_interleaved_readline_write(self): + with self.BytesIO(b'ab\ncdef\ng\n') as raw: + with self.tp(raw) as f: + f.write(b'1') + self.assertEqual(f.readline(), b'b\n') + f.write(b'2') + self.assertEqual(f.readline(), b'def\n') + f.write(b'3') + self.assertEqual(f.readline(), b'\n') + f.flush() + self.assertEqual(raw.getvalue(), b'1b\n2def\n3\n') + + # You can't construct a BufferedRandom over a non-seekable stream. + test_unseekable = None + + # writable() returns True, so there's no point to test it over + # a writable stream. + test_truncate_on_read_only = None + + +class CBufferedRandomTest(BufferedRandomTest, SizeofTest, CTestCase): + tp = io.BufferedRandom + + def test_garbage_collection(self): + CBufferedReaderTest.test_garbage_collection(self) + CBufferedWriterTest.test_garbage_collection(self) + + def test_args_error(self): + # Issue #17275 + with self.assertRaisesRegex(TypeError, "BufferedRandom"): + self.tp(self.BytesIO(), 1024, 1024, 1024) + + +class PyBufferedRandomTest(BufferedRandomTest, PyTestCase): + tp = pyio.BufferedRandom + + +# Simple test to ensure that optimizations in the IO library deliver the +# expected results. For best testing, run this under a debug-build Python too +# (to exercise asserts in the C code). + +lengths = list(range(1, 257)) + [512, 1000, 1024, 2048, 4096, 8192, 10000, + 16384, 32768, 65536, 1000000] + +class BufferSizeTest: + def try_one(self, s): + # Write s + "\n" + s to file, then open it and ensure that successive + # .readline()s deliver what we wrote. + + # Ensure we can open TESTFN for writing. + os_helper.unlink(os_helper.TESTFN) + + # Since C doesn't guarantee we can write/read arbitrary bytes in text + # files, use binary mode. + f = self.open(os_helper.TESTFN, "wb") + try: + # write once with \n and once without + f.write(s) + f.write(b"\n") + f.write(s) + f.close() + f = self.open(os_helper.TESTFN, "rb") + line = f.readline() + self.assertEqual(line, s + b"\n") + line = f.readline() + self.assertEqual(line, s) + line = f.readline() + self.assertFalse(line) # Must be at EOF + f.close() + finally: + os_helper.unlink(os_helper.TESTFN) + + def drive_one(self, pattern): + for length in lengths: + # Repeat string 'pattern' as often as needed to reach total length + # 'length'. Then call try_one with that string, a string one larger + # than that, and a string one smaller than that. Try this with all + # small sizes and various powers of 2, so we exercise all likely + # stdio buffer sizes, and "off by one" errors on both sides. + q, r = divmod(length, len(pattern)) + teststring = pattern * q + pattern[:r] + self.assertEqual(len(teststring), length) + self.try_one(teststring) + self.try_one(teststring + b"x") + self.try_one(teststring[:-1]) + + def test_primepat(self): + # A pattern with prime length, to avoid simple relationships with + # stdio buffer sizes. + self.drive_one(b"1234567890\00\01\02\03\04\05\06") + + def test_nullpat(self): + self.drive_one(b'\0' * 1000) + + +class CBufferSizeTest(BufferSizeTest, unittest.TestCase): + open = io.open + +class PyBufferSizeTest(BufferSizeTest, unittest.TestCase): + open = staticmethod(pyio.open) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_file.py b/Lib/test/test_io/test_file.py similarity index 100% rename from Lib/test/test_file.py rename to Lib/test/test_io/test_file.py diff --git a/Lib/test/test_fileio.py b/Lib/test/test_io/test_fileio.py similarity index 96% rename from Lib/test/test_fileio.py rename to Lib/test/test_io/test_fileio.py index 4f195cf045c..a18f6d7d970 100644 --- a/Lib/test/test_fileio.py +++ b/Lib/test/test_io/test_fileio.py @@ -83,6 +83,12 @@ def testBlksize(self): fst = os.fstat(self.f.fileno()) blksize = getattr(fst, 'st_blksize', blksize) self.assertEqual(self.f._blksize, blksize) + # it is read-only + with self.assertRaises(AttributeError): + self.f._blksize = blksize + with self.assertRaises(AttributeError): + del self.f._blksize + # verify readinto def testReadintoByteArray(self): @@ -504,6 +510,21 @@ class CAutoFileTests(AutoFileTests, unittest.TestCase): FileIO = _io.FileIO modulename = '_io' + def testFinalizing(self): + # test the private _finalizing attribute + self.assertIs(self.f._finalizing, False) + self.f._finalizing = True + self.assertIs(self.f._finalizing, True) + with self.assertRaisesRegex(TypeError, + 'attribute value type must be bool'): + self.f._finalizing = 1 + with self.assertRaisesRegex(TypeError, + "can't delete numeric/char attribute"): + del self.f._finalizing + # closing a file which is being finalized emits a ResourceWarning + self.f._finalizing = False + + class PyAutoFileTests(AutoFileTests, unittest.TestCase): FileIO = _pyio.FileIO modulename = '_pyio' @@ -568,8 +589,8 @@ def testModeStrings(self): # test that the mode attribute is correct for various mode strings # given as init args try: - for modes in [('w', 'wb'), ('wb', 'wb'), ('wb+', 'rb+'), - ('w+b', 'rb+'), ('a', 'ab'), ('ab', 'ab'), + for modes in [('w', 'wb'), ('wb', 'wb'), ('wb+', 'wb+'), + ('w+b', 'wb+'), ('a', 'ab'), ('ab', 'ab'), ('ab+', 'ab+'), ('a+b', 'ab+'), ('r', 'rb'), ('rb', 'rb'), ('rb+', 'rb+'), ('r+b', 'rb+')]: # read modes are last so that TESTFN will exist first diff --git a/Lib/test/test_io/test_general.py b/Lib/test/test_io/test_general.py new file mode 100644 index 00000000000..d12c5535b26 --- /dev/null +++ b/Lib/test/test_io/test_general.py @@ -0,0 +1,1447 @@ +"""General tests for the io module. + +New tests should go in more specific modules; see test_io/__init__.py +""" + +import abc +import array +import errno +import os +import pickle +import sys +import textwrap +import threading +import unittest +import warnings +import weakref +from test import support +from test.support.script_helper import ( + assert_python_ok, assert_python_failure, run_python_until_end) +from test.support import ( + import_helper, is_apple, os_helper, threading_helper, warnings_helper, +) +from test.support.os_helper import FakePath +from .utils import byteslike, CTestCase, PyTestCase + +import io # C implementation of io +import _pyio as pyio # Python implementation of io + + +class IOTest: + + def setUp(self): + os_helper.unlink(os_helper.TESTFN) + + def tearDown(self): + os_helper.unlink(os_helper.TESTFN) + + def write_ops(self, f): + self.assertEqual(f.write(b"blah."), 5) + f.truncate(0) + self.assertEqual(f.tell(), 5) + f.seek(0) + + self.assertEqual(f.write(b"blah."), 5) + self.assertEqual(f.seek(0), 0) + self.assertEqual(f.write(b"Hello."), 6) + self.assertEqual(f.tell(), 6) + self.assertEqual(f.seek(-1, 1), 5) + self.assertEqual(f.tell(), 5) + buffer = bytearray(b" world\n\n\n") + self.assertEqual(f.write(buffer), 9) + buffer[:] = b"*" * 9 # Overwrite our copy of the data + self.assertEqual(f.seek(0), 0) + self.assertEqual(f.write(b"h"), 1) + self.assertEqual(f.seek(-1, 2), 13) + self.assertEqual(f.tell(), 13) + + self.assertEqual(f.truncate(12), 12) + self.assertEqual(f.tell(), 13) + self.assertRaises(TypeError, f.seek, 0.0) + + def read_ops(self, f, buffered=False): + data = f.read(5) + self.assertEqual(data, b"hello") + data = byteslike(data) + self.assertEqual(f.readinto(data), 5) + self.assertEqual(bytes(data), b" worl") + data = bytearray(5) + self.assertEqual(f.readinto(data), 2) + self.assertEqual(len(data), 5) + self.assertEqual(data[:2], b"d\n") + self.assertEqual(f.seek(0), 0) + self.assertEqual(f.read(20), b"hello world\n") + self.assertEqual(f.read(1), b"") + self.assertEqual(f.readinto(byteslike(b"x")), 0) + self.assertEqual(f.seek(-6, 2), 6) + self.assertEqual(f.read(5), b"world") + self.assertEqual(f.read(0), b"") + self.assertEqual(f.readinto(byteslike()), 0) + self.assertEqual(f.seek(-6, 1), 5) + self.assertEqual(f.read(5), b" worl") + self.assertEqual(f.tell(), 10) + self.assertRaises(TypeError, f.seek, 0.0) + if buffered: + f.seek(0) + self.assertEqual(f.read(), b"hello world\n") + f.seek(6) + self.assertEqual(f.read(), b"world\n") + self.assertEqual(f.read(), b"") + f.seek(0) + data = byteslike(5) + self.assertEqual(f.readinto1(data), 5) + self.assertEqual(bytes(data), b"hello") + + LARGE = 2**31 + + def large_file_ops(self, f): + assert f.readable() + assert f.writable() + try: + self.assertEqual(f.seek(self.LARGE), self.LARGE) + except (OverflowError, ValueError): + self.skipTest("no largefile support") + self.assertEqual(f.tell(), self.LARGE) + self.assertEqual(f.write(b"xxx"), 3) + self.assertEqual(f.tell(), self.LARGE + 3) + self.assertEqual(f.seek(-1, 1), self.LARGE + 2) + self.assertEqual(f.truncate(), self.LARGE + 2) + self.assertEqual(f.tell(), self.LARGE + 2) + self.assertEqual(f.seek(0, 2), self.LARGE + 2) + self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1) + self.assertEqual(f.tell(), self.LARGE + 2) + self.assertEqual(f.seek(0, 2), self.LARGE + 1) + self.assertEqual(f.seek(-1, 2), self.LARGE) + self.assertEqual(f.read(2), b"x") + + def test_invalid_operations(self): + # Try writing on a file opened in read mode and vice-versa. + exc = self.UnsupportedOperation + with self.open(os_helper.TESTFN, "w", encoding="utf-8") as fp: + self.assertRaises(exc, fp.read) + self.assertRaises(exc, fp.readline) + with self.open(os_helper.TESTFN, "wb") as fp: + self.assertRaises(exc, fp.read) + self.assertRaises(exc, fp.readline) + with self.open(os_helper.TESTFN, "wb", buffering=0) as fp: + self.assertRaises(exc, fp.read) + self.assertRaises(exc, fp.readall) + self.assertRaises(exc, fp.readline) + with self.open(os_helper.TESTFN, "rb", buffering=0) as fp: + self.assertRaises(exc, fp.write, b"blah") + self.assertRaises(exc, fp.writelines, [b"blah\n"]) + with self.open(os_helper.TESTFN, "rb") as fp: + self.assertRaises(exc, fp.write, b"blah") + self.assertRaises(exc, fp.writelines, [b"blah\n"]) + with self.open(os_helper.TESTFN, "r", encoding="utf-8") as fp: + self.assertRaises(exc, fp.write, "blah") + self.assertRaises(exc, fp.writelines, ["blah\n"]) + # Non-zero seeking from current or end pos + self.assertRaises(exc, fp.seek, 1, self.SEEK_CUR) + self.assertRaises(exc, fp.seek, -1, self.SEEK_END) + + @support.cpython_only + def test_startup_optimization(self): + # gh-132952: Test that `io` is not imported at startup and that the + # __module__ of UnsupportedOperation is set to "io". + assert_python_ok("-S", "-c", textwrap.dedent( + """ + import sys + assert "io" not in sys.modules + try: + sys.stdin.truncate() + except Exception as e: + typ = type(e) + assert typ.__module__ == "io", (typ, typ.__module__) + assert typ.__name__ == "UnsupportedOperation", (typ, typ.__name__) + else: + raise AssertionError("Expected UnsupportedOperation") + """ + )) + + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_optional_abilities(self): + # Test for OSError when optional APIs are not supported + # The purpose of this test is to try fileno(), reading, writing and + # seeking operations with various objects that indicate they do not + # support these operations. + + def pipe_reader(): + [r, w] = os.pipe() + os.close(w) # So that read() is harmless + return self.FileIO(r, "r") + + def pipe_writer(): + [r, w] = os.pipe() + self.addCleanup(os.close, r) + # Guarantee that we can write into the pipe without blocking + thread = threading.Thread(target=os.read, args=(r, 100)) + thread.start() + self.addCleanup(thread.join) + return self.FileIO(w, "w") + + def buffered_reader(): + return self.BufferedReader(self.MockUnseekableIO()) + + def buffered_writer(): + return self.BufferedWriter(self.MockUnseekableIO()) + + def buffered_random(): + return self.BufferedRandom(self.BytesIO()) + + def buffered_rw_pair(): + return self.BufferedRWPair(self.MockUnseekableIO(), + self.MockUnseekableIO()) + + def text_reader(): + class UnseekableReader(self.MockUnseekableIO): + writable = self.BufferedIOBase.writable + write = self.BufferedIOBase.write + return self.TextIOWrapper(UnseekableReader(), "ascii") + + def text_writer(): + class UnseekableWriter(self.MockUnseekableIO): + readable = self.BufferedIOBase.readable + read = self.BufferedIOBase.read + return self.TextIOWrapper(UnseekableWriter(), "ascii") + + tests = ( + (pipe_reader, "fr"), (pipe_writer, "fw"), + (buffered_reader, "r"), (buffered_writer, "w"), + (buffered_random, "rws"), (buffered_rw_pair, "rw"), + (text_reader, "r"), (text_writer, "w"), + (self.BytesIO, "rws"), (self.StringIO, "rws"), + ) + + def do_test(test, obj, abilities): + readable = "r" in abilities + self.assertEqual(obj.readable(), readable) + writable = "w" in abilities + self.assertEqual(obj.writable(), writable) + + if isinstance(obj, self.TextIOBase): + data = "3" + elif isinstance(obj, (self.BufferedIOBase, self.RawIOBase)): + data = b"3" + else: + self.fail("Unknown base class") + + if "f" in abilities: + obj.fileno() + else: + self.assertRaises(OSError, obj.fileno) + + if readable: + obj.read(1) + obj.read() + else: + self.assertRaises(OSError, obj.read, 1) + self.assertRaises(OSError, obj.read) + + if writable: + obj.write(data) + else: + self.assertRaises(OSError, obj.write, data) + + if sys.platform.startswith("win") and test in ( + pipe_reader, pipe_writer): + # Pipes seem to appear as seekable on Windows + return + seekable = "s" in abilities + self.assertEqual(obj.seekable(), seekable) + + if seekable: + obj.tell() + obj.seek(0) + else: + self.assertRaises(OSError, obj.tell) + self.assertRaises(OSError, obj.seek, 0) + + if writable and seekable: + obj.truncate() + obj.truncate(0) + else: + self.assertRaises(OSError, obj.truncate) + self.assertRaises(OSError, obj.truncate, 0) + + for [test, abilities] in tests: + with self.subTest(test): + if test == pipe_writer and not threading_helper.can_start_thread: + self.skipTest("Need threads") + with test() as obj: + do_test(test, obj, abilities) + + + def test_open_handles_NUL_chars(self): + fn_with_NUL = 'foo\0bar' + self.assertRaises(ValueError, self.open, fn_with_NUL, 'w', encoding="utf-8") + + bytes_fn = bytes(fn_with_NUL, 'ascii') + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + self.assertRaises(ValueError, self.open, bytes_fn, 'w', encoding="utf-8") + + def test_raw_file_io(self): + with self.open(os_helper.TESTFN, "wb", buffering=0) as f: + self.assertEqual(f.readable(), False) + self.assertEqual(f.writable(), True) + self.assertEqual(f.seekable(), True) + self.write_ops(f) + with self.open(os_helper.TESTFN, "rb", buffering=0) as f: + self.assertEqual(f.readable(), True) + self.assertEqual(f.writable(), False) + self.assertEqual(f.seekable(), True) + self.read_ops(f) + + def test_buffered_file_io(self): + with self.open(os_helper.TESTFN, "wb") as f: + self.assertEqual(f.readable(), False) + self.assertEqual(f.writable(), True) + self.assertEqual(f.seekable(), True) + self.write_ops(f) + with self.open(os_helper.TESTFN, "rb") as f: + self.assertEqual(f.readable(), True) + self.assertEqual(f.writable(), False) + self.assertEqual(f.seekable(), True) + self.read_ops(f, True) + + def test_readline(self): + with self.open(os_helper.TESTFN, "wb") as f: + f.write(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") + with self.open(os_helper.TESTFN, "rb") as f: + self.assertEqual(f.readline(), b"abc\n") + self.assertEqual(f.readline(10), b"def\n") + self.assertEqual(f.readline(2), b"xy") + self.assertEqual(f.readline(4), b"zzy\n") + self.assertEqual(f.readline(), b"foo\x00bar\n") + self.assertEqual(f.readline(None), b"another line") + self.assertRaises(TypeError, f.readline, 5.3) + with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: + self.assertRaises(TypeError, f.readline, 5.3) + + def test_readline_limit_with_short_read(self): + class Reader(self.IOBase): + data = b"abcdef" + + def peek(self, size): + return self.data + + def read(self, size): + data = self.data[:min(size, 2)] + self.data = self.data[len(data):] + return data + + reader = Reader() + self.assertEqual(reader.readline(3), b"abc") + self.assertEqual(reader.data, b"def") + + def test_readline_nonsizeable(self): + # Issue #30061 + # Crash when readline() returns an object without __len__ + class R(self.IOBase): + def readline(self): + return None + self.assertRaises((TypeError, StopIteration), next, R()) + + def test_next_nonsizeable(self): + # Issue #30061 + # Crash when __next__() returns an object without __len__ + class R(self.IOBase): + def __next__(self): + return None + self.assertRaises(TypeError, R().readlines, 1) + + def test_raw_bytes_io(self): + f = self.BytesIO() + self.write_ops(f) + data = f.getvalue() + self.assertEqual(data, b"hello world\n") + f = self.BytesIO(data) + self.read_ops(f, True) + + def test_large_file_ops(self): + # On Windows and Apple platforms this test consumes large resources; It + # takes a long time to build the >2 GiB file and takes >2 GiB of disk + # space therefore the resource must be enabled to run this test. + if sys.platform[:3] == 'win' or is_apple: + support.requires( + 'largefile', + 'test requires %s bytes and a long time to run' % self.LARGE) + with self.open(os_helper.TESTFN, "w+b", 0) as f: + self.large_file_ops(f) + with self.open(os_helper.TESTFN, "w+b") as f: + self.large_file_ops(f) + + def test_with_open(self): + for bufsize in (0, 100): + with self.open(os_helper.TESTFN, "wb", bufsize) as f: + f.write(b"xxx") + self.assertEqual(f.closed, True) + try: + with self.open(os_helper.TESTFN, "wb", bufsize) as f: + 1/0 + except ZeroDivisionError: + self.assertEqual(f.closed, True) + else: + self.fail("1/0 didn't raise an exception") + + # issue 5008 + def test_append_mode_tell(self): + with self.open(os_helper.TESTFN, "wb") as f: + f.write(b"xxx") + with self.open(os_helper.TESTFN, "ab", buffering=0) as f: + self.assertEqual(f.tell(), 3) + with self.open(os_helper.TESTFN, "ab") as f: + self.assertEqual(f.tell(), 3) + with self.open(os_helper.TESTFN, "a", encoding="utf-8") as f: + self.assertGreater(f.tell(), 0) + + def test_destructor(self): + record = [] + class MyFileIO(self.FileIO): + def __del__(self): + record.append(1) + try: + f = super().__del__ + except AttributeError: + pass + else: + f() + def close(self): + record.append(2) + super().close() + def flush(self): + record.append(3) + super().flush() + with warnings_helper.check_warnings(('', ResourceWarning)): + f = MyFileIO(os_helper.TESTFN, "wb") + f.write(b"xxx") + del f + support.gc_collect() + self.assertEqual(record, [1, 2, 3]) + with self.open(os_helper.TESTFN, "rb") as f: + self.assertEqual(f.read(), b"xxx") + + def _check_base_destructor(self, base): + record = [] + class MyIO(base): + def __init__(self): + # This exercises the availability of attributes on object + # destruction. + # (in the C version, close() is called by the tp_dealloc + # function, not by __del__) + self.on_del = 1 + self.on_close = 2 + self.on_flush = 3 + def __del__(self): + record.append(self.on_del) + try: + f = super().__del__ + except AttributeError: + pass + else: + f() + def close(self): + record.append(self.on_close) + super().close() + def flush(self): + record.append(self.on_flush) + super().flush() + f = MyIO() + del f + support.gc_collect() + self.assertEqual(record, [1, 2, 3]) + + def test_IOBase_destructor(self): + self._check_base_destructor(self.IOBase) + + def test_RawIOBase_destructor(self): + self._check_base_destructor(self.RawIOBase) + + def test_BufferedIOBase_destructor(self): + self._check_base_destructor(self.BufferedIOBase) + + def test_TextIOBase_destructor(self): + self._check_base_destructor(self.TextIOBase) + + def test_close_flushes(self): + with self.open(os_helper.TESTFN, "wb") as f: + f.write(b"xxx") + with self.open(os_helper.TESTFN, "rb") as f: + self.assertEqual(f.read(), b"xxx") + + def test_array_writes(self): + a = array.array('i', range(10)) + n = len(a.tobytes()) + def check(f): + with f: + self.assertEqual(f.write(a), n) + f.writelines((a,)) + check(self.BytesIO()) + check(self.FileIO(os_helper.TESTFN, "w")) + check(self.BufferedWriter(self.MockRawIO())) + check(self.BufferedRandom(self.MockRawIO())) + check(self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())) + + def test_closefd(self): + self.assertRaises(ValueError, self.open, os_helper.TESTFN, 'w', + encoding="utf-8", closefd=False) + + def test_read_closed(self): + with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: + f.write("egg\n") + with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: + file = self.open(f.fileno(), "r", encoding="utf-8", closefd=False) + self.assertEqual(file.read(), "egg\n") + file.seek(0) + file.close() + self.assertRaises(ValueError, file.read) + with self.open(os_helper.TESTFN, "rb") as f: + file = self.open(f.fileno(), "rb", closefd=False) + self.assertEqual(file.read()[:3], b"egg") + file.close() + self.assertRaises(ValueError, file.readinto, bytearray(1)) + + def test_no_closefd_with_filename(self): + # can't use closefd in combination with a file name + self.assertRaises(ValueError, self.open, os_helper.TESTFN, "r", + encoding="utf-8", closefd=False) + + def test_closefd_attr(self): + with self.open(os_helper.TESTFN, "wb") as f: + f.write(b"egg\n") + with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: + self.assertEqual(f.buffer.raw.closefd, True) + file = self.open(f.fileno(), "r", encoding="utf-8", closefd=False) + self.assertEqual(file.buffer.raw.closefd, False) + + def test_garbage_collection(self): + # FileIO objects are collected, and collecting them flushes + # all data to disk. + # + # Note that using warnings_helper.check_warnings() will keep the + # file alive due to the `source` argument to warn(). So, use + # catch_warnings() instead. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + f = self.FileIO(os_helper.TESTFN, "wb") + f.write(b"abcxxx") + f.f = f + wr = weakref.ref(f) + del f + support.gc_collect() + self.assertIsNone(wr(), wr) + with self.open(os_helper.TESTFN, "rb") as f: + self.assertEqual(f.read(), b"abcxxx") + + def test_unbounded_file(self): + # Issue #1174606: reading from an unbounded stream such as /dev/zero. + zero = "/dev/zero" + if not os.path.exists(zero): + self.skipTest("{0} does not exist".format(zero)) + if sys.maxsize > 0x7FFFFFFF: + self.skipTest("test can only run in a 32-bit address space") + if support.real_max_memuse < support._2G: + self.skipTest("test requires at least 2 GiB of memory") + with self.open(zero, "rb", buffering=0) as f: + self.assertRaises(OverflowError, f.read) + with self.open(zero, "rb") as f: + self.assertRaises(OverflowError, f.read) + with self.open(zero, "r") as f: + self.assertRaises(OverflowError, f.read) + + def check_flush_error_on_close(self, *args, **kwargs): + # Test that the file is closed despite failed flush + # and that flush() is called before file closed. + f = self.open(*args, **kwargs) + closed = [] + def bad_flush(): + closed[:] = [f.closed] + raise OSError() + f.flush = bad_flush + self.assertRaises(OSError, f.close) # exception not swallowed + self.assertTrue(f.closed) + self.assertTrue(closed) # flush() called + self.assertFalse(closed[0]) # flush() called before file closed + f.flush = lambda: None # break reference loop + + def test_flush_error_on_close(self): + # raw file + # Issue #5700: io.FileIO calls flush() after file closed + self.check_flush_error_on_close(os_helper.TESTFN, 'wb', buffering=0) + fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) + self.check_flush_error_on_close(fd, 'wb', buffering=0) + fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) + self.check_flush_error_on_close(fd, 'wb', buffering=0, closefd=False) + os.close(fd) + # buffered io + self.check_flush_error_on_close(os_helper.TESTFN, 'wb') + fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) + self.check_flush_error_on_close(fd, 'wb') + fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) + self.check_flush_error_on_close(fd, 'wb', closefd=False) + os.close(fd) + # text io + self.check_flush_error_on_close(os_helper.TESTFN, 'w', encoding="utf-8") + fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) + self.check_flush_error_on_close(fd, 'w', encoding="utf-8") + fd = os.open(os_helper.TESTFN, os.O_WRONLY|os.O_CREAT) + self.check_flush_error_on_close(fd, 'w', encoding="utf-8", closefd=False) + os.close(fd) + + def test_multi_close(self): + f = self.open(os_helper.TESTFN, "wb", buffering=0) + f.close() + f.close() + f.close() + self.assertRaises(ValueError, f.flush) + + def test_RawIOBase_read(self): + # Exercise the default limited RawIOBase.read(n) implementation (which + # calls readinto() internally). + rawio = self.MockRawIOWithoutRead((b"abc", b"d", None, b"efg", None)) + self.assertEqual(rawio.read(2), b"ab") + self.assertEqual(rawio.read(2), b"c") + self.assertEqual(rawio.read(2), b"d") + self.assertEqual(rawio.read(2), None) + self.assertEqual(rawio.read(2), b"ef") + self.assertEqual(rawio.read(2), b"g") + self.assertEqual(rawio.read(2), None) + self.assertEqual(rawio.read(2), b"") + + def test_RawIOBase_read_bounds_checking(self): + # Make sure a `.readinto` call which returns a value outside + # (0, len(buffer)) raises. + class Misbehaved(self.io.RawIOBase): + def __init__(self, readinto_return) -> None: + self._readinto_return = readinto_return + def readinto(self, b): + return self._readinto_return + + with self.assertRaises(ValueError) as cm: + Misbehaved(2).read(1) + self.assertEqual(str(cm.exception), "readinto returned 2 outside buffer size 1") + for bad_size in (2147483647, sys.maxsize, -1, -1000): + with self.assertRaises(ValueError): + Misbehaved(bad_size).read() + + def test_RawIOBase_read_gh60107(self): + # gh-60107: Ensure a "Raw I/O" which keeps a reference to the + # mutable memory doesn't allow making a mutable bytes. + class RawIOKeepsReference(self.MockRawIOWithoutRead): + def __init__(self, *args, **kwargs): + self.buf = None + super().__init__(*args, **kwargs) + + def readinto(self, buf): + # buf is the bytearray so keeping a reference to it doesn't keep + # the memory alive; a memoryview does. + self.buf = memoryview(buf) + buf[0:4] = self._read_stack.pop() + return 3 + + with self.assertRaises(BufferError): + rawio = RawIOKeepsReference([b"1234"]) + rawio.read(4) + + def test_types_have_dict(self): + test = ( + self.IOBase(), + self.RawIOBase(), + self.TextIOBase(), + self.StringIO(), + self.BytesIO() + ) + for obj in test: + self.assertHasAttr(obj, "__dict__") + + def test_opener(self): + with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: + f.write("egg\n") + fd = os.open(os_helper.TESTFN, os.O_RDONLY) + def opener(path, flags): + return fd + with self.open("non-existent", "r", encoding="utf-8", opener=opener) as f: + self.assertEqual(f.read(), "egg\n") + + def test_bad_opener_negative_1(self): + # Issue #27066. + def badopener(fname, flags): + return -1 + with self.assertRaises(ValueError) as cm: + self.open('non-existent', 'r', opener=badopener) + self.assertEqual(str(cm.exception), 'opener returned -1') + + def test_bad_opener_other_negative(self): + # Issue #27066. + def badopener(fname, flags): + return -2 + with self.assertRaises(ValueError) as cm: + self.open('non-existent', 'r', opener=badopener) + self.assertEqual(str(cm.exception), 'opener returned -2') + + def test_opener_invalid_fd(self): + # Check that OSError is raised with error code EBADF if the + # opener returns an invalid file descriptor (see gh-82212). + fd = os_helper.make_bad_fd() + with self.assertRaises(OSError) as cm: + self.open('foo', opener=lambda name, flags: fd) + self.assertEqual(cm.exception.errno, errno.EBADF) + + def test_fileio_closefd(self): + # Issue #4841 + with self.open(__file__, 'rb') as f1, \ + self.open(__file__, 'rb') as f2: + fileio = self.FileIO(f1.fileno(), closefd=False) + # .__init__() must not close f1 + fileio.__init__(f2.fileno(), closefd=False) + f1.readline() + # .close() must not close f2 + fileio.close() + f2.readline() + + def test_nonbuffered_textio(self): + with warnings_helper.check_no_resource_warning(self): + with self.assertRaises(ValueError): + self.open(os_helper.TESTFN, 'w', encoding="utf-8", buffering=0) + + def test_invalid_newline(self): + with warnings_helper.check_no_resource_warning(self): + with self.assertRaises(ValueError): + self.open(os_helper.TESTFN, 'w', encoding="utf-8", newline='invalid') + + def test_buffered_readinto_mixin(self): + # Test the implementation provided by BufferedIOBase + class Stream(self.BufferedIOBase): + def read(self, size): + return b"12345" + read1 = read + stream = Stream() + for method in ("readinto", "readinto1"): + with self.subTest(method): + buffer = byteslike(5) + self.assertEqual(getattr(stream, method)(buffer), 5) + self.assertEqual(bytes(buffer), b"12345") + + def test_fspath_support(self): + def check_path_succeeds(path): + with self.open(path, "w", encoding="utf-8") as f: + f.write("egg\n") + + with self.open(path, "r", encoding="utf-8") as f: + self.assertEqual(f.read(), "egg\n") + + check_path_succeeds(FakePath(os_helper.TESTFN)) + check_path_succeeds(FakePath(os.fsencode(os_helper.TESTFN))) + + with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: + bad_path = FakePath(f.fileno()) + with self.assertRaises(TypeError): + self.open(bad_path, 'w', encoding="utf-8") + + bad_path = FakePath(None) + with self.assertRaises(TypeError): + self.open(bad_path, 'w', encoding="utf-8") + + bad_path = FakePath(FloatingPointError) + with self.assertRaises(FloatingPointError): + self.open(bad_path, 'w', encoding="utf-8") + + # ensure that refcounting is correct with some error conditions + with self.assertRaisesRegex(ValueError, 'read/write/append mode'): + self.open(FakePath(os_helper.TESTFN), 'rwxa', encoding="utf-8") + + def test_RawIOBase_readall(self): + # Exercise the default unlimited RawIOBase.read() and readall() + # implementations. + rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) + self.assertEqual(rawio.read(), b"abcdefg") + rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) + self.assertEqual(rawio.readall(), b"abcdefg") + + def test_BufferedIOBase_readinto(self): + # Exercise the default BufferedIOBase.readinto() and readinto1() + # implementations (which call read() or read1() internally). + class Reader(self.BufferedIOBase): + def __init__(self, avail): + self.avail = avail + def read(self, size): + result = self.avail[:size] + self.avail = self.avail[size:] + return result + def read1(self, size): + """Returns no more than 5 bytes at once""" + return self.read(min(size, 5)) + tests = ( + # (test method, total data available, read buffer size, expected + # read size) + ("readinto", 10, 5, 5), + ("readinto", 10, 6, 6), # More than read1() can return + ("readinto", 5, 6, 5), # Buffer larger than total available + ("readinto", 6, 7, 6), + ("readinto", 10, 0, 0), # Empty buffer + ("readinto1", 10, 5, 5), # Result limited to single read1() call + ("readinto1", 10, 6, 5), # Buffer larger than read1() can return + ("readinto1", 5, 6, 5), # Buffer larger than total available + ("readinto1", 6, 7, 5), + ("readinto1", 10, 0, 0), # Empty buffer + ) + UNUSED_BYTE = 0x81 + for test in tests: + with self.subTest(test): + method, avail, request, result = test + reader = Reader(bytes(range(avail))) + buffer = bytearray((UNUSED_BYTE,) * request) + method = getattr(reader, method) + self.assertEqual(method(buffer), result) + self.assertEqual(len(buffer), request) + self.assertSequenceEqual(buffer[:result], range(result)) + unused = (UNUSED_BYTE,) * (request - result) + self.assertSequenceEqual(buffer[result:], unused) + self.assertEqual(len(reader.avail), avail - result) + + def test_close_assert(self): + class R(self.IOBase): + def __setattr__(self, name, value): + pass + def flush(self): + raise OSError() + f = R() + # This would cause an assertion failure. + self.assertRaises(OSError, f.close) + + # Silence destructor error + R.flush = lambda self: None + + @threading_helper.requires_working_threading() + def test_write_readline_races(self): + # gh-134908: Concurrent iteration over a file caused races + thread_count = 2 + write_count = 100 + read_count = 100 + + def writer(file, barrier): + barrier.wait() + for _ in range(write_count): + file.write("x") + + def reader(file, barrier): + barrier.wait() + for _ in range(read_count): + for line in file: + self.assertEqual(line, "") + + with self.open(os_helper.TESTFN, "w+") as f: + barrier = threading.Barrier(thread_count + 1) + reader = threading.Thread(target=reader, args=(f, barrier)) + writers = [threading.Thread(target=writer, args=(f, barrier)) + for _ in range(thread_count)] + with threading_helper.catch_threading_exception() as cm: + with threading_helper.start_threads(writers + [reader]): + pass + self.assertIsNone(cm.exc_type) + + self.assertEqual(os.stat(os_helper.TESTFN).st_size, + write_count * thread_count) + + +class CIOTest(IOTest, CTestCase): + + def test_IOBase_finalize(self): + # Issue #12149: segmentation fault on _PyIOBase_finalize when both a + # class which inherits IOBase and an object of this class are caught + # in a reference cycle and close() is already in the method cache. + class MyIO(self.IOBase): + def close(self): + pass + + # create an instance to populate the method cache + MyIO() + obj = MyIO() + obj.obj = obj + wr = weakref.ref(obj) + del MyIO + del obj + support.gc_collect() + self.assertIsNone(wr(), wr) + +@support.cpython_only +class TestIOCTypes(unittest.TestCase): + def setUp(self): + _io = import_helper.import_module("_io") + self.types = [ + _io.BufferedRWPair, + _io.BufferedRandom, + _io.BufferedReader, + _io.BufferedWriter, + _io.BytesIO, + _io.FileIO, + _io.IncrementalNewlineDecoder, + _io.StringIO, + _io.TextIOWrapper, + _io._BufferedIOBase, + _io._BytesIOBuffer, + _io._IOBase, + _io._RawIOBase, + _io._TextIOBase, + ] + if sys.platform == "win32": + self.types.append(_io._WindowsConsoleIO) + self._io = _io + + def test_immutable_types(self): + for tp in self.types: + with self.subTest(tp=tp): + with self.assertRaisesRegex(TypeError, "immutable"): + tp.foo = "bar" + + def test_class_hierarchy(self): + def check_subs(types, base): + for tp in types: + with self.subTest(tp=tp, base=base): + self.assertIsSubclass(tp, base) + + def recursive_check(d): + for k, v in d.items(): + if isinstance(v, dict): + recursive_check(v) + elif isinstance(v, set): + check_subs(v, k) + else: + self.fail("corrupt test dataset") + + _io = self._io + hierarchy = { + _io._IOBase: { + _io._BufferedIOBase: { + _io.BufferedRWPair, + _io.BufferedRandom, + _io.BufferedReader, + _io.BufferedWriter, + _io.BytesIO, + }, + _io._RawIOBase: { + _io.FileIO, + }, + _io._TextIOBase: { + _io.StringIO, + _io.TextIOWrapper, + }, + }, + } + if sys.platform == "win32": + hierarchy[_io._IOBase][_io._RawIOBase].add(_io._WindowsConsoleIO) + + recursive_check(hierarchy) + + def test_subclassing(self): + _io = self._io + dataset = {k: True for k in self.types} + dataset[_io._BytesIOBuffer] = False + + for tp, is_basetype in dataset.items(): + with self.subTest(tp=tp, is_basetype=is_basetype): + name = f"{tp.__name__}_subclass" + bases = (tp,) + if is_basetype: + _ = type(name, bases, {}) + else: + msg = "not an acceptable base type" + with self.assertRaisesRegex(TypeError, msg): + _ = type(name, bases, {}) + + def test_disallow_instantiation(self): + _io = self._io + support.check_disallow_instantiation(self, _io._BytesIOBuffer) + + def test_stringio_setstate(self): + # gh-127182: Calling __setstate__() with invalid arguments must not crash + obj = self._io.StringIO() + with self.assertRaisesRegex( + TypeError, + 'initial_value must be str or None, not int', + ): + obj.__setstate__((1, '', 0, {})) + + obj.__setstate__((None, '', 0, {})) # should not crash + self.assertEqual(obj.getvalue(), '') + + obj.__setstate__(('', '', 0, {})) + self.assertEqual(obj.getvalue(), '') + +class PyIOTest(IOTest, PyTestCase): + pass + + +@support.cpython_only +class APIMismatchTest(unittest.TestCase): + + def test_RawIOBase_io_in_pyio_match(self): + """Test that pyio RawIOBase class has all c RawIOBase methods""" + mismatch = support.detect_api_mismatch(pyio.RawIOBase, io.RawIOBase, + ignore=('__weakref__', '__static_attributes__')) + self.assertEqual(mismatch, set(), msg='Python RawIOBase does not have all C RawIOBase methods') + + def test_RawIOBase_pyio_in_io_match(self): + """Test that c RawIOBase class has all pyio RawIOBase methods""" + mismatch = support.detect_api_mismatch(io.RawIOBase, pyio.RawIOBase) + self.assertEqual(mismatch, set(), msg='C RawIOBase does not have all Python RawIOBase methods') + + +# XXX Tests for open() + +class MiscIOTest: + + # for test__all__, actual values are set in subclasses + name_of_module = None + extra_exported = () + not_exported = () + + def tearDown(self): + os_helper.unlink(os_helper.TESTFN) + + def test___all__(self): + support.check__all__(self, self.io, self.name_of_module, + extra=self.extra_exported, + not_exported=self.not_exported) + + def test_attributes(self): + f = self.open(os_helper.TESTFN, "wb", buffering=0) + self.assertEqual(f.mode, "wb") + f.close() + + f = self.open(os_helper.TESTFN, "w+", encoding="utf-8") + self.assertEqual(f.mode, "w+") + self.assertEqual(f.buffer.mode, "wb+") + self.assertEqual(f.buffer.raw.mode, "wb+") + + g = self.open(f.fileno(), "wb", closefd=False) + self.assertEqual(g.mode, "wb") + self.assertEqual(g.raw.mode, "wb") + self.assertEqual(g.name, f.fileno()) + self.assertEqual(g.raw.name, f.fileno()) + f.close() + g.close() + + def test_removed_u_mode(self): + # bpo-37330: The "U" mode has been removed in Python 3.11 + for mode in ("U", "rU", "r+U"): + with self.assertRaises(ValueError) as cm: + self.open(os_helper.TESTFN, mode) + self.assertIn('invalid mode', str(cm.exception)) + + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_open_pipe_with_append(self): + # bpo-27805: Ignore ESPIPE from lseek() in open(). + r, w = os.pipe() + self.addCleanup(os.close, r) + f = self.open(w, 'a', encoding="utf-8") + self.addCleanup(f.close) + # Check that the file is marked non-seekable. On Windows, however, lseek + # somehow succeeds on pipes. + if sys.platform != 'win32': + self.assertFalse(f.seekable()) + + def test_io_after_close(self): + for kwargs in [ + {"mode": "w"}, + {"mode": "wb"}, + {"mode": "w", "buffering": 1}, + {"mode": "w", "buffering": 2}, + {"mode": "wb", "buffering": 0}, + {"mode": "r"}, + {"mode": "rb"}, + {"mode": "r", "buffering": 1}, + {"mode": "r", "buffering": 2}, + {"mode": "rb", "buffering": 0}, + {"mode": "w+"}, + {"mode": "w+b"}, + {"mode": "w+", "buffering": 1}, + {"mode": "w+", "buffering": 2}, + {"mode": "w+b", "buffering": 0}, + ]: + if "b" not in kwargs["mode"]: + kwargs["encoding"] = "utf-8" + f = self.open(os_helper.TESTFN, **kwargs) + f.close() + self.assertRaises(ValueError, f.flush) + self.assertRaises(ValueError, f.fileno) + self.assertRaises(ValueError, f.isatty) + self.assertRaises(ValueError, f.__iter__) + if hasattr(f, "peek"): + self.assertRaises(ValueError, f.peek, 1) + self.assertRaises(ValueError, f.read) + if hasattr(f, "read1"): + self.assertRaises(ValueError, f.read1, 1024) + self.assertRaises(ValueError, f.read1) + if hasattr(f, "readall"): + self.assertRaises(ValueError, f.readall) + if hasattr(f, "readinto"): + self.assertRaises(ValueError, f.readinto, bytearray(1024)) + if hasattr(f, "readinto1"): + self.assertRaises(ValueError, f.readinto1, bytearray(1024)) + self.assertRaises(ValueError, f.readline) + self.assertRaises(ValueError, f.readlines) + self.assertRaises(ValueError, f.readlines, 1) + self.assertRaises(ValueError, f.seek, 0) + self.assertRaises(ValueError, f.tell) + self.assertRaises(ValueError, f.truncate) + self.assertRaises(ValueError, f.write, + b"" if "b" in kwargs['mode'] else "") + self.assertRaises(ValueError, f.writelines, []) + self.assertRaises(ValueError, next, f) + + def test_blockingioerror(self): + # Various BlockingIOError issues + class C(str): + pass + c = C("") + b = self.BlockingIOError(1, c) + c.b = b + b.c = c + wr = weakref.ref(c) + del c, b + support.gc_collect() + self.assertIsNone(wr(), wr) + + def test_abcs(self): + # Test the visible base classes are ABCs. + self.assertIsInstance(self.IOBase, abc.ABCMeta) + self.assertIsInstance(self.RawIOBase, abc.ABCMeta) + self.assertIsInstance(self.BufferedIOBase, abc.ABCMeta) + self.assertIsInstance(self.TextIOBase, abc.ABCMeta) + + def _check_abc_inheritance(self, abcmodule): + with self.open(os_helper.TESTFN, "wb", buffering=0) as f: + self.assertIsInstance(f, abcmodule.IOBase) + self.assertIsInstance(f, abcmodule.RawIOBase) + self.assertNotIsInstance(f, abcmodule.BufferedIOBase) + self.assertNotIsInstance(f, abcmodule.TextIOBase) + with self.open(os_helper.TESTFN, "wb") as f: + self.assertIsInstance(f, abcmodule.IOBase) + self.assertNotIsInstance(f, abcmodule.RawIOBase) + self.assertIsInstance(f, abcmodule.BufferedIOBase) + self.assertNotIsInstance(f, abcmodule.TextIOBase) + with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: + self.assertIsInstance(f, abcmodule.IOBase) + self.assertNotIsInstance(f, abcmodule.RawIOBase) + self.assertNotIsInstance(f, abcmodule.BufferedIOBase) + self.assertIsInstance(f, abcmodule.TextIOBase) + + def test_abc_inheritance(self): + # Test implementations inherit from their respective ABCs + self._check_abc_inheritance(self) + + def test_abc_inheritance_official(self): + # Test implementations inherit from the official ABCs of the + # baseline "io" module. + self._check_abc_inheritance(io) + + def _check_warn_on_dealloc(self, *args, **kwargs): + f = self.open(*args, **kwargs) + r = repr(f) + with self.assertWarns(ResourceWarning) as cm: + f = None + support.gc_collect() + self.assertIn(r, str(cm.warning.args[0])) + + def test_warn_on_dealloc(self): + self._check_warn_on_dealloc(os_helper.TESTFN, "wb", buffering=0) + self._check_warn_on_dealloc(os_helper.TESTFN, "wb") + self._check_warn_on_dealloc(os_helper.TESTFN, "w", encoding="utf-8") + + def _check_warn_on_dealloc_fd(self, *args, **kwargs): + fds = [] + def cleanup_fds(): + for fd in fds: + try: + os.close(fd) + except OSError as e: + if e.errno != errno.EBADF: + raise + self.addCleanup(cleanup_fds) + r, w = os.pipe() + fds += r, w + self._check_warn_on_dealloc(r, *args, **kwargs) + # When using closefd=False, there's no warning + r, w = os.pipe() + fds += r, w + with warnings_helper.check_no_resource_warning(self): + self.open(r, *args, closefd=False, **kwargs) + + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_warn_on_dealloc_fd(self): + self._check_warn_on_dealloc_fd("rb", buffering=0) + self._check_warn_on_dealloc_fd("rb") + self._check_warn_on_dealloc_fd("r", encoding="utf-8") + + + def test_pickling(self): + # Pickling file objects is forbidden + msg = "cannot pickle" + for kwargs in [ + {"mode": "w"}, + {"mode": "wb"}, + {"mode": "wb", "buffering": 0}, + {"mode": "r"}, + {"mode": "rb"}, + {"mode": "rb", "buffering": 0}, + {"mode": "w+"}, + {"mode": "w+b"}, + {"mode": "w+b", "buffering": 0}, + ]: + if "b" not in kwargs["mode"]: + kwargs["encoding"] = "utf-8" + for protocol in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=protocol, kwargs=kwargs): + with self.open(os_helper.TESTFN, **kwargs) as f: + with self.assertRaisesRegex(TypeError, msg): + pickle.dumps(f, protocol) + + @unittest.skipIf(support.is_emscripten, "Emscripten corrupts memory when writing to nonblocking fd") + def test_nonblock_pipe_write_bigbuf(self): + self._test_nonblock_pipe_write(16*1024) + + @unittest.skipIf(support.is_emscripten, "Emscripten corrupts memory when writing to nonblocking fd") + def test_nonblock_pipe_write_smallbuf(self): + self._test_nonblock_pipe_write(1024) + + @unittest.skipUnless(hasattr(os, 'set_blocking'), + 'os.set_blocking() required for this test') + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def _test_nonblock_pipe_write(self, bufsize): + sent = [] + received = [] + r, w = os.pipe() + os.set_blocking(r, False) + os.set_blocking(w, False) + + # To exercise all code paths in the C implementation we need + # to play with buffer sizes. For instance, if we choose a + # buffer size less than or equal to _PIPE_BUF (4096 on Linux) + # then we will never get a partial write of the buffer. + rf = self.open(r, mode='rb', closefd=True, buffering=bufsize) + wf = self.open(w, mode='wb', closefd=True, buffering=bufsize) + + with rf, wf: + for N in 9999, 73, 7574: + try: + i = 0 + while True: + msg = bytes([i % 26 + 97]) * N + sent.append(msg) + wf.write(msg) + i += 1 + + except self.BlockingIOError as e: + self.assertEqual(e.args[0], errno.EAGAIN) + self.assertEqual(e.args[2], e.characters_written) + sent[-1] = sent[-1][:e.characters_written] + received.append(rf.read()) + msg = b'BLOCKED' + wf.write(msg) + sent.append(msg) + + while True: + try: + wf.flush() + break + except self.BlockingIOError as e: + self.assertEqual(e.args[0], errno.EAGAIN) + self.assertEqual(e.args[2], e.characters_written) + self.assertEqual(e.characters_written, 0) + received.append(rf.read()) + + received += iter(rf.read, None) + + sent, received = b''.join(sent), b''.join(received) + self.assertEqual(sent, received) + self.assertTrue(wf.closed) + self.assertTrue(rf.closed) + + def test_create_fail(self): + # 'x' mode fails if file is existing + with self.open(os_helper.TESTFN, 'w', encoding="utf-8"): + pass + self.assertRaises(FileExistsError, self.open, os_helper.TESTFN, 'x', encoding="utf-8") + + def test_create_writes(self): + # 'x' mode opens for writing + with self.open(os_helper.TESTFN, 'xb') as f: + f.write(b"spam") + with self.open(os_helper.TESTFN, 'rb') as f: + self.assertEqual(b"spam", f.read()) + + def test_open_allargs(self): + # there used to be a buffer overflow in the parser for rawmode + self.assertRaises(ValueError, self.open, os_helper.TESTFN, 'rwax+', encoding="utf-8") + + def test_check_encoding_errors(self): + # bpo-37388: open() and TextIOWrapper must check encoding and errors + # arguments in dev mode + mod = self.io.__name__ + filename = __file__ + invalid = 'Boom, Shaka Laka, Boom!' + code = textwrap.dedent(f''' + import sys + from {mod} import open, TextIOWrapper + + try: + open({filename!r}, encoding={invalid!r}) + except LookupError: + pass + else: + sys.exit(21) + + try: + open({filename!r}, errors={invalid!r}) + except LookupError: + pass + else: + sys.exit(22) + + fp = open({filename!r}, "rb") + with fp: + try: + TextIOWrapper(fp, encoding={invalid!r}) + except LookupError: + pass + else: + sys.exit(23) + + try: + TextIOWrapper(fp, errors={invalid!r}) + except LookupError: + pass + else: + sys.exit(24) + + sys.exit(10) + ''') + proc = assert_python_failure('-X', 'dev', '-c', code) + self.assertEqual(proc.rc, 10, proc) + + def test_check_encoding_warning(self): + # PEP 597: Raise warning when encoding is not specified + # and sys.flags.warn_default_encoding is set. + mod = self.io.__name__ + filename = __file__ + code = textwrap.dedent(f'''\ + import sys + from {mod} import open, TextIOWrapper + import pathlib + + with open({filename!r}) as f: # line 5 + pass + + pathlib.Path({filename!r}).read_text() # line 8 + ''') + proc = assert_python_ok('-X', 'warn_default_encoding', '-c', code) + warnings = proc.err.splitlines() + self.assertEqual(len(warnings), 2) + self.assertStartsWith(warnings[0], b":5: EncodingWarning: ") + self.assertStartsWith(warnings[1], b":8: EncodingWarning: ") + + def test_text_encoding(self): + # PEP 597, bpo-47000. io.text_encoding() returns "locale" or "utf-8" + # based on sys.flags.utf8_mode + code = "import io; print(io.text_encoding(None))" + + proc = assert_python_ok('-X', 'utf8=0', '-c', code) + self.assertEqual(b"locale", proc.out.strip()) + + proc = assert_python_ok('-X', 'utf8=1', '-c', code) + self.assertEqual(b"utf-8", proc.out.strip()) + + +class CMiscIOTest(MiscIOTest, CTestCase): + name_of_module = "io", "_io" + extra_exported = "BlockingIOError", + + def test_readinto_buffer_overflow(self): + # Issue #18025 + class BadReader(self.io.BufferedIOBase): + def read(self, n=-1): + return b'x' * 10**6 + bufio = BadReader() + b = bytearray(2) + self.assertRaises(ValueError, bufio.readinto, b) + + def check_daemon_threads_shutdown_deadlock(self, stream_name): + # Issue #23309: deadlocks at shutdown should be avoided when a + # daemon thread and the main thread both write to a file. + code = """if 1: + import sys + import time + import threading + from test.support import SuppressCrashReport + + file = sys.{stream_name} + + def run(): + while True: + file.write('.') + file.flush() + + crash = SuppressCrashReport() + crash.__enter__() + # don't call __exit__(): the crash occurs at Python shutdown + + thread = threading.Thread(target=run) + thread.daemon = True + thread.start() + + time.sleep(0.5) + file.write('!') + file.flush() + """.format_map(locals()) + res, _ = run_python_until_end("-c", code) + err = res.err.decode() + if res.rc != 0: + # Failure: should be a fatal error + pattern = (r"Fatal Python error: _enter_buffered_busy: " + r"could not acquire lock " + r"for <(_io\.)?BufferedWriter name='<{stream_name}>'> " + r"at interpreter shutdown, possibly due to " + r"daemon threads".format_map(locals())) + self.assertRegex(err, pattern) + else: + self.assertFalse(err.strip('.!')) + + @threading_helper.requires_working_threading() + @support.requires_resource('walltime') + def test_daemon_threads_shutdown_stdout_deadlock(self): + self.check_daemon_threads_shutdown_deadlock('stdout') + + @threading_helper.requires_working_threading() + @support.requires_resource('walltime') + def test_daemon_threads_shutdown_stderr_deadlock(self): + self.check_daemon_threads_shutdown_deadlock('stderr') + + +class PyMiscIOTest(MiscIOTest, PyTestCase): + name_of_module = "_pyio", "io" + extra_exported = "BlockingIOError", "open_code", + not_exported = "valid_seek_flags", + + +class ProtocolsTest(unittest.TestCase): + class MyReader: + def read(self, sz=-1): + return b"" + + class MyWriter: + def write(self, b: bytes): + pass + + def test_reader_subclass(self): + self.assertIsSubclass(self.MyReader, io.Reader) + self.assertNotIsSubclass(str, io.Reader) + + def test_writer_subclass(self): + self.assertIsSubclass(self.MyWriter, io.Writer) + self.assertNotIsSubclass(str, io.Writer) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_largefile.py b/Lib/test/test_io/test_largefile.py similarity index 98% rename from Lib/test/test_largefile.py rename to Lib/test/test_io/test_largefile.py index 41f7b70e5cf..438a90a92ed 100644 --- a/Lib/test/test_largefile.py +++ b/Lib/test/test_io/test_largefile.py @@ -56,9 +56,7 @@ class TestFileMethods(LargeFileTest): (i.e. > 2 GiB) files. """ - # _pyio.FileIO.readall() uses a temporary bytearray then casted to bytes, - # so memuse=2 is needed - @bigmemtest(size=size, memuse=2, dry_run=False) + @bigmemtest(size=size, memuse=1, dry_run=False) def test_large_read(self, _size): # bpo-24658: Test that a read greater than 2GB does not fail. with self.open(TESTFN, "rb") as f: @@ -154,7 +152,7 @@ def test_seekable(self): f.seek(pos) self.assertTrue(f.seekable()) - @bigmemtest(size=size, memuse=2, dry_run=False) + @bigmemtest(size=size, memuse=1, dry_run=False) def test_seek_readall(self, _size): # Seek which doesn't change position should readall successfully. with self.open(TESTFN, 'rb') as f: diff --git a/Lib/test/test_memoryio.py b/Lib/test/test_io/test_memoryio.py similarity index 94% rename from Lib/test/test_memoryio.py rename to Lib/test/test_io/test_memoryio.py index 43045a981de..c0ea06d1d74 100644 --- a/Lib/test/test_memoryio.py +++ b/Lib/test/test_io/test_memoryio.py @@ -651,6 +651,28 @@ def __buffer__(self, flags): self.assertEqual(memio.getvalue(), b"01AAA56789") self.assertEqual(memio.tell(), 5) + def test_memory_error(self): + # gh-157242: io.BytesIO() must not close the file on MemoryError + + # write() + stream = self.ioclass() + stream.write(self.buftype('abc')) + data = self.buftype('def') + with self.assertRaises(MemoryError): + with support.inject_memory_error_cm(): + stream.write(data) + stream.write(self.buftype('123')) + self.assertEqual(stream.getvalue(), self.buftype('abc123')) + + # truncate() + data = self.buftype('x' * 100) + stream = self.ioclass() + stream.write(data) + with self.assertRaises(MemoryError): + with support.inject_memory_error_cm(): + stream.truncate(5) + self.assertEqual(stream.getvalue(), data) + class TextIOTestMixin: @@ -837,6 +859,34 @@ class CBytesIOTest(PyBytesIOTest): ioclass = io.BytesIO UnsupportedOperation = io.UnsupportedOperation + def test_truncate_size_changes_stream(self): + class Size: + def __init__(self, action): + self.action = action + + def __index__(self): + self.result = self.action() + return 0 + + stream = self.ioclass(b'abc') + with self.assertRaises(ValueError): + stream.truncate(Size(stream.close)) + + with self.ioclass(b'abc') as stream: + size = Size(stream.getbuffer) + try: + with self.assertRaises(BufferError): + stream.truncate(size) + self.assertEqual(stream.getvalue(), b'abc') + finally: + size.result.release() + + def test_readinto_overlapping_buffer(self): + with self.ioclass(b'abcd') as stream: + with stream.getbuffer()[1:] as target: + self.assertEqual(stream.readinto(target), 3) + self.assertEqual(stream.getvalue(), b'aabc') + def test_getstate(self): memio = self.ioclass() state = memio.__getstate__() @@ -848,7 +898,6 @@ def test_getstate(self): memio.close() self.assertRaises(ValueError, memio.__getstate__) - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: Expected type 'bytes' but 'bytearray' found. def test_setstate(self): # This checks whether __setstate__ does proper input validation. memio = self.ioclass() @@ -924,9 +973,17 @@ def test_cow_mutable(self): memio = self.ioclass(ba) self.assertEqual(sys.getrefcount(ba), old_rc) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: ValueError not raised by writable - def test_flags(self): - return super().test_flags() + def test_write_with_export(self): + memio = self.ioclass(b"abcd") + memio.seek(2) + with memio.getbuffer() as view: + self.assertRaises(BufferError, memio.__init__, b"replacement") + self.assertEqual(memio.tell(), 2) + self.assertEqual(memio.getvalue(), b"abcd") + self.assertEqual(bytes(view), b"abcd") + memio.write(b"X") + self.assertEqual(memio.getvalue(), b"abXd") + class CStringIOTest(PyStringIOTest): ioclass = io.StringIO @@ -994,10 +1051,6 @@ def __str__(self): memio2.write(MyStr("world")) self.assertEqual(memio2.getvalue(), "hello world") - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: ValueError not raised by writable - def test_flags(self): - return super().test_flags() - class CStringIOPickleTest(PyStringIOPickleTest): UnsupportedOperation = io.UnsupportedOperation diff --git a/Lib/test/test_io/test_signals.py b/Lib/test/test_io/test_signals.py new file mode 100644 index 00000000000..03f1da1eb1c --- /dev/null +++ b/Lib/test/test_io/test_signals.py @@ -0,0 +1,280 @@ +import errno +import os +import signal +import threading +import unittest +from test import support +from test.support import import_helper +from .utils import PyTestCase, CTestCase + + +requires_alarm = unittest.skipUnless( + hasattr(signal, "alarm"), "test requires signal.alarm()" +) + + +@unittest.skipIf(os.name == 'nt', 'POSIX signals required for this test.') +class SignalsTest: + + def setUp(self): + self.oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) + + def tearDown(self): + signal.signal(signal.SIGALRM, self.oldalrm) + + def alarm_interrupt(self, sig, frame): + 1/0 + + def check_interrupted_write(self, item, bytes, **fdopen_kwargs): + """Check that a partial write, when it gets interrupted, properly + invokes the signal handler, and bubbles up the exception raised + in the latter.""" + + # XXX This test has three flaws that appear when objects are + # XXX not reference counted. + + # - if wio.write() happens to trigger a garbage collection, + # the signal exception may be raised when some __del__ + # method is running; it will not reach the assertRaises() + # call. + + # - more subtle, if the wio object is not destroyed at once + # and survives this function, the next opened file is likely + # to have the same fileno (since the file descriptor was + # actively closed). When wio.__del__ is finally called, it + # will close the other's test file... To trigger this with + # CPython, try adding "global wio" in this function. + + # - This happens only for streams created by the _pyio module, + # because a wio.close() that fails still consider that the + # file needs to be closed again. You can try adding an + # "assert wio.closed" at the end of the function. + + # Fortunately, a little gc.collect() seems to be enough to + # work around all these issues. + support.gc_collect() # For PyPy or other GCs. + + read_results = [] + def _read(): + s = os.read(r, 1) + read_results.append(s) + + t = threading.Thread(target=_read) + t.daemon = True + r, w = os.pipe() + fdopen_kwargs["closefd"] = False + large_data = item * (support.PIPE_MAX_SIZE // len(item) + 1) + try: + wio = self.io.open(w, **fdopen_kwargs) + if hasattr(signal, 'pthread_sigmask'): + # create the thread with SIGALRM signal blocked + signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGALRM]) + t.start() + signal.pthread_sigmask(signal.SIG_UNBLOCK, [signal.SIGALRM]) + else: + t.start() + + # Fill the pipe enough that the write will be blocking. + # It will be interrupted by the timer armed above. Since the + # other thread has read one byte, the low-level write will + # return with a successful (partial) result rather than an EINTR. + # The buffered IO layer must check for pending signal + # handlers, which in this case will invoke alarm_interrupt(). + signal.alarm(1) + try: + self.assertRaises(ZeroDivisionError, wio.write, large_data) + finally: + signal.alarm(0) + t.join() + # We got one byte, get another one and check that it isn't a + # repeat of the first one. + read_results.append(os.read(r, 1)) + self.assertEqual(read_results, [bytes[0:1], bytes[1:2]]) + finally: + os.close(w) + os.close(r) + # This is deliberate. If we didn't close the file descriptor + # before closing wio, wio would try to flush its internal + # buffer, and block again. + try: + wio.close() + except OSError as e: + if e.errno != errno.EBADF: + raise + + @requires_alarm + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_interrupted_write_unbuffered(self): + self.check_interrupted_write(b"xy", b"xy", mode="wb", buffering=0) + + @requires_alarm + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_interrupted_write_buffered(self): + self.check_interrupted_write(b"xy", b"xy", mode="wb") + + @requires_alarm + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_interrupted_write_text(self): + self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii") + + @support.no_tracing + def check_reentrant_write(self, data, **fdopen_kwargs): + def on_alarm(*args): + # Will be called reentrantly from the same thread + wio.write(data) + 1/0 + signal.signal(signal.SIGALRM, on_alarm) + r, w = os.pipe() + wio = self.io.open(w, **fdopen_kwargs) + try: + signal.alarm(1) + # Either the reentrant call to wio.write() fails with RuntimeError, + # or the signal handler raises ZeroDivisionError. + with self.assertRaises((ZeroDivisionError, RuntimeError)) as cm: + while 1: + for i in range(100): + wio.write(data) + wio.flush() + # Make sure the buffer doesn't fill up and block further writes + os.read(r, len(data) * 100) + exc = cm.exception + if isinstance(exc, RuntimeError): + self.assertStartsWith(str(exc), "reentrant call") + finally: + signal.alarm(0) + wio.close() + os.close(r) + + @requires_alarm + def test_reentrant_write_buffered(self): + self.check_reentrant_write(b"xy", mode="wb") + + @requires_alarm + def test_reentrant_write_text(self): + self.check_reentrant_write("xy", mode="w", encoding="ascii") + + def check_interrupted_read_retry(self, decode, **fdopen_kwargs): + """Check that a buffered read, when it gets interrupted (either + returning a partial result or EINTR), properly invokes the signal + handler and retries if the latter returned successfully.""" + r, w = os.pipe() + fdopen_kwargs["closefd"] = False + def alarm_handler(sig, frame): + os.write(w, b"bar") + signal.signal(signal.SIGALRM, alarm_handler) + try: + rio = self.io.open(r, **fdopen_kwargs) + os.write(w, b"foo") + signal.alarm(1) + # Expected behaviour: + # - first raw read() returns partial b"foo" + # - second raw read() returns EINTR + # - third raw read() returns b"bar" + self.assertEqual(decode(rio.read(6)), "foobar") + finally: + signal.alarm(0) + rio.close() + os.close(w) + os.close(r) + + @requires_alarm + @support.requires_resource('walltime') + def test_interrupted_read_retry_buffered(self): + self.check_interrupted_read_retry(lambda x: x.decode('latin1'), + mode="rb") + + @requires_alarm + @support.requires_resource('walltime') + def test_interrupted_read_retry_text(self): + self.check_interrupted_read_retry(lambda x: x, + mode="r", encoding="latin1") + + def check_interrupted_write_retry(self, item, **fdopen_kwargs): + """Check that a buffered write, when it gets interrupted (either + returning a partial result or EINTR), properly invokes the signal + handler and retries if the latter returned successfully.""" + select = import_helper.import_module("select") + + # A quantity that exceeds the buffer size of an anonymous pipe's + # write end. + N = support.PIPE_MAX_SIZE + r, w = os.pipe() + fdopen_kwargs["closefd"] = False + + # We need a separate thread to read from the pipe and allow the + # write() to finish. This thread is started after the SIGALRM is + # received (forcing a first EINTR in write()). + read_results = [] + write_finished = False + error = None + def _read(): + try: + while not write_finished: + while r in select.select([r], [], [], 1.0)[0]: + s = os.read(r, 1024) + read_results.append(s) + except BaseException as exc: + nonlocal error + error = exc + t = threading.Thread(target=_read) + t.daemon = True + def alarm1(sig, frame): + signal.signal(signal.SIGALRM, alarm2) + signal.alarm(1) + def alarm2(sig, frame): + t.start() + + large_data = item * N + signal.signal(signal.SIGALRM, alarm1) + try: + wio = self.io.open(w, **fdopen_kwargs) + signal.alarm(1) + # Expected behaviour: + # - first raw write() is partial (because of the limited pipe buffer + # and the first alarm) + # - second raw write() returns EINTR (because of the second alarm) + # - subsequent write()s are successful (either partial or complete) + written = wio.write(large_data) + self.assertEqual(N, written) + + wio.flush() + write_finished = True + t.join() + + self.assertIsNone(error) + self.assertEqual(N, sum(len(x) for x in read_results)) + finally: + signal.alarm(0) + write_finished = True + os.close(w) + os.close(r) + # This is deliberate. If we didn't close the file descriptor + # before closing wio, wio would try to flush its internal + # buffer, and could block (in case of failure). + try: + wio.close() + except OSError as e: + if e.errno != errno.EBADF: + raise + + @requires_alarm + @support.requires_resource('walltime') + def test_interrupted_write_retry_buffered(self): + self.check_interrupted_write_retry(b"x", mode="wb") + + @requires_alarm + @support.requires_resource('walltime') + def test_interrupted_write_retry_text(self): + self.check_interrupted_write_retry("x", mode="w", encoding="latin1") + + +class CSignalsTest(SignalsTest, CTestCase): + pass + +class PySignalsTest(SignalsTest, PyTestCase): + pass + + # Handling reentrancy issues would slow down _pyio even more, so the + # tests are disabled. + test_reentrant_write_buffered = None + test_reentrant_write_text = None diff --git a/Lib/test/test_io/test_textio.py b/Lib/test/test_io/test_textio.py new file mode 100644 index 00000000000..72dc3ffc0ab --- /dev/null +++ b/Lib/test/test_io/test_textio.py @@ -0,0 +1,1845 @@ +import array +import codecs +import locale +import os +import pickle +import sys +import threading +import time +import unittest +import warnings +import weakref +from collections import UserList +from test import support +from test.support import os_helper, threading_helper +from test.support.script_helper import assert_python_ok +from .utils import CTestCase, PyTestCase + +import io # C implementation of io +import _pyio as pyio # Python implementation of io + + +def _default_chunk_size(): + """Get the default TextIOWrapper chunk size""" + with open(__file__, "r", encoding="latin-1") as f: + return f._CHUNK_SIZE + + +class BadIndex: + def __index__(self): + 1/0 + + +# To fully exercise seek/tell, the StatefulIncrementalDecoder has these +# properties: +# - A single output character can correspond to many bytes of input. +# - The number of input bytes to complete the character can be +# undetermined until the last input byte is received. +# - The number of input bytes can vary depending on previous input. +# - A single input byte can correspond to many characters of output. +# - The number of output characters can be undetermined until the +# last input byte is received. +# - The number of output characters can vary depending on previous input. + +class StatefulIncrementalDecoder(codecs.IncrementalDecoder): + """ + For testing seek/tell behavior with a stateful, buffering decoder. + + Input is a sequence of words. Words may be fixed-length (length set + by input) or variable-length (period-terminated). In variable-length + mode, extra periods are ignored. Possible words are: + - 'i' followed by a number sets the input length, I (maximum 99). + When I is set to 0, words are space-terminated. + - 'o' followed by a number sets the output length, O (maximum 99). + - Any other word is converted into a word followed by a period on + the output. The output word consists of the input word truncated + or padded out with hyphens to make its length equal to O. If O + is 0, the word is output verbatim without truncating or padding. + I and O are initially set to 1. When I changes, any buffered input is + re-scanned according to the new I. EOF also terminates the last word. + """ + + def __init__(self, errors='strict'): + codecs.IncrementalDecoder.__init__(self, errors) + self.reset() + + def __repr__(self): + return '' % id(self) + + def reset(self): + self.i = 1 + self.o = 1 + self.buffer = bytearray() + + def getstate(self): + i, o = self.i ^ 1, self.o ^ 1 # so that flags = 0 after reset() + return bytes(self.buffer), i*100 + o + + def setstate(self, state): + buffer, io = state + self.buffer = bytearray(buffer) + i, o = divmod(io, 100) + self.i, self.o = i ^ 1, o ^ 1 + + def decode(self, input, final=False): + output = '' + for b in input: + if self.i == 0: # variable-length, terminated with period + if b == ord('.'): + if self.buffer: + output += self.process_word() + else: + self.buffer.append(b) + else: # fixed-length, terminate after self.i bytes + self.buffer.append(b) + if len(self.buffer) == self.i: + output += self.process_word() + if final and self.buffer: # EOF terminates the last word + output += self.process_word() + return output + + def process_word(self): + output = '' + if self.buffer[0] == ord('i'): + self.i = min(99, int(self.buffer[1:] or 0)) # set input length + elif self.buffer[0] == ord('o'): + self.o = min(99, int(self.buffer[1:] or 0)) # set output length + else: + output = self.buffer.decode('ascii') + if len(output) < self.o: + output += '-'*self.o # pad out with hyphens + if self.o: + output = output[:self.o] # truncate to output length + output += '.' + self.buffer = bytearray() + return output + + codecEnabled = False + + +# bpo-41919: This method is separated from StatefulIncrementalDecoder to avoid a resource leak +# when registering codecs and cleanup functions. +def lookupTestDecoder(name): + if StatefulIncrementalDecoder.codecEnabled and name == 'test_decoder': + latin1 = codecs.lookup('latin-1') + return codecs.CodecInfo( + name='test_decoder', encode=latin1.encode, decode=None, + incrementalencoder=None, + streamreader=None, streamwriter=None, + incrementaldecoder=StatefulIncrementalDecoder) + + +class StatefulIncrementalDecoderTest(unittest.TestCase): + """ + Make sure the StatefulIncrementalDecoder actually works. + """ + + test_cases = [ + # I=1, O=1 (fixed-length input == fixed-length output) + (b'abcd', False, 'a.b.c.d.'), + # I=0, O=0 (variable-length input, variable-length output) + (b'oiabcd', True, 'abcd.'), + # I=0, O=0 (should ignore extra periods) + (b'oi...abcd...', True, 'abcd.'), + # I=0, O=6 (variable-length input, fixed-length output) + (b'i.o6.x.xyz.toolongtofit.', False, 'x-----.xyz---.toolon.'), + # I=2, O=6 (fixed-length input < fixed-length output) + (b'i.i2.o6xyz', True, 'xy----.z-----.'), + # I=6, O=3 (fixed-length input > fixed-length output) + (b'i.o3.i6.abcdefghijklmnop', True, 'abc.ghi.mno.'), + # I=0, then 3; O=29, then 15 (with longer output) + (b'i.o29.a.b.cde.o15.abcdefghijabcdefghij.i3.a.b.c.d.ei00k.l.m', True, + 'a----------------------------.' + + 'b----------------------------.' + + 'cde--------------------------.' + + 'abcdefghijabcde.' + + 'a.b------------.' + + '.c.------------.' + + 'd.e------------.' + + 'k--------------.' + + 'l--------------.' + + 'm--------------.') + ] + + def test_decoder(self): + # Try a few one-shot test cases. + for input, eof, output in self.test_cases: + d = StatefulIncrementalDecoder() + self.assertEqual(d.decode(input, eof), output) + + # Also test an unfinished decode, followed by forcing EOF. + d = StatefulIncrementalDecoder() + self.assertEqual(d.decode(b'oiabcd'), '') + self.assertEqual(d.decode(b'', 1), 'abcd.') + +class TextIOWrapperTest: + + def setUp(self): + self.testdata = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n" + self.normalized = b"AAA\nBBB\nCCC\nDDD\nEEE\n".decode("ascii") + os_helper.unlink(os_helper.TESTFN) + codecs.register(lookupTestDecoder) + self.addCleanup(codecs.unregister, lookupTestDecoder) + + def tearDown(self): + os_helper.unlink(os_helper.TESTFN) + + def test_constructor(self): + r = self.BytesIO(b"\xc3\xa9\n\n") + b = self.BufferedReader(r, 1000) + t = self.TextIOWrapper(b, encoding="utf-8") + t.__init__(b, encoding="latin-1", newline="\r\n") + self.assertEqual(t.encoding, "latin-1") + self.assertEqual(t.line_buffering, False) + t.__init__(b, encoding="utf-8", line_buffering=True) + self.assertEqual(t.encoding, "utf-8") + self.assertEqual(t.line_buffering, True) + self.assertEqual("\xe9\n", t.readline()) + invalid_type = TypeError if self.is_C else ValueError + with self.assertRaises(invalid_type): + t.__init__(b, encoding=42) + with self.assertRaises(UnicodeEncodeError): + t.__init__(b, encoding='\udcfe') + with self.assertRaises(ValueError): + t.__init__(b, encoding='utf-8\0') + with self.assertRaises(invalid_type): + t.__init__(b, encoding="utf-8", errors=42) + if support.Py_DEBUG or sys.flags.dev_mode or self.is_C: + with self.assertRaises(UnicodeEncodeError): + t.__init__(b, encoding="utf-8", errors='\udcfe') + if support.Py_DEBUG or sys.flags.dev_mode or self.is_C: + with self.assertRaises(ValueError): + t.__init__(b, encoding="utf-8", errors='replace\0') + with self.assertRaises(TypeError): + t.__init__(b, encoding="utf-8", newline=42) + with self.assertRaises(ValueError): + t.__init__(b, encoding="utf-8", newline='\udcfe') + with self.assertRaises(ValueError): + t.__init__(b, encoding="utf-8", newline='\n\0') + with self.assertRaises(ValueError): + t.__init__(b, encoding="utf-8", newline='xyzzy') + + def test_uninitialized(self): + t = self.TextIOWrapper.__new__(self.TextIOWrapper) + del t + t = self.TextIOWrapper.__new__(self.TextIOWrapper) + self.assertRaises(Exception, repr, t) + self.assertRaisesRegex((ValueError, AttributeError), + 'uninitialized|has no attribute', + t.read, 0) + t.__init__(self.MockRawIO(), encoding="utf-8") + self.assertEqual(t.read(0), '') + + def test_non_text_encoding_codecs_are_rejected(self): + # Ensure the constructor complains if passed a codec that isn't + # marked as a text encoding + # http://bugs.python.org/issue20404 + r = self.BytesIO() + b = self.BufferedWriter(r) + with self.assertRaisesRegex(LookupError, "is not a text encoding"): + self.TextIOWrapper(b, encoding="hex") + + def test_detach(self): + r = self.BytesIO() + b = self.BufferedWriter(r) + t = self.TextIOWrapper(b, encoding="ascii") + self.assertIs(t.detach(), b) + + t = self.TextIOWrapper(b, encoding="ascii") + t.write("howdy") + self.assertFalse(r.getvalue()) + t.detach() + self.assertEqual(r.getvalue(), b"howdy") + self.assertRaises(ValueError, t.detach) + + # Operations independent of the detached stream should still work + repr(t) + self.assertEqual(t.encoding, "ascii") + self.assertEqual(t.errors, "strict") + self.assertFalse(t.line_buffering) + self.assertFalse(t.write_through) + + def test_repr(self): + raw = self.BytesIO("hello".encode("utf-8")) + b = self.BufferedReader(raw) + t = self.TextIOWrapper(b, encoding="utf-8") + modname = self.TextIOWrapper.__module__ + self.assertRegex(repr(t), + r"<(%s\.)?TextIOWrapper encoding='utf-8'>" % modname) + raw.name = "dummy" + self.assertRegex(repr(t), + r"<(%s\.)?TextIOWrapper name='dummy' encoding='utf-8'>" % modname) + t.mode = "r" + self.assertRegex(repr(t), + r"<(%s\.)?TextIOWrapper name='dummy' mode='r' encoding='utf-8'>" % modname) + raw.name = b"dummy" + self.assertRegex(repr(t), + r"<(%s\.)?TextIOWrapper name=b'dummy' mode='r' encoding='utf-8'>" % modname) + + t.buffer.detach() + repr(t) # Should not raise an exception + + def test_recursive_repr(self): + # Issue #25455 + raw = self.BytesIO() + t = self.TextIOWrapper(raw, encoding="utf-8") + with support.swap_attr(raw, 'name', t), support.infinite_recursion(25): + with self.assertRaises(RuntimeError): + repr(t) # Should not crash + + def test_subclass_repr(self): + class TestSubclass(self.TextIOWrapper): + pass + + f = TestSubclass(self.StringIO()) + self.assertIn(TestSubclass.__name__, repr(f)) + + def test_line_buffering(self): + r = self.BytesIO() + b = self.BufferedWriter(r, 1000) + t = self.TextIOWrapper(b, encoding="utf-8", newline="\n", line_buffering=True) + t.write("X") + self.assertEqual(r.getvalue(), b"") # No flush happened + t.write("Y\nZ") + self.assertEqual(r.getvalue(), b"XY\nZ") # All got flushed + t.write("A\rB") + self.assertEqual(r.getvalue(), b"XY\nZA\rB") + + def test_reconfigure_line_buffering(self): + r = self.BytesIO() + b = self.BufferedWriter(r, 1000) + t = self.TextIOWrapper(b, encoding="utf-8", newline="\n", line_buffering=False) + t.write("AB\nC") + self.assertEqual(r.getvalue(), b"") + + t.reconfigure(line_buffering=True) # implicit flush + self.assertEqual(r.getvalue(), b"AB\nC") + t.write("DEF\nG") + self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") + t.write("H") + self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") + t.reconfigure(line_buffering=False) # implicit flush + self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") + t.write("IJ") + self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") + + # Keeping default value + t.reconfigure() + t.reconfigure(line_buffering=None) + self.assertEqual(t.line_buffering, False) + t.reconfigure(line_buffering=True) + t.reconfigure() + t.reconfigure(line_buffering=None) + self.assertEqual(t.line_buffering, True) + + @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled") + def test_default_encoding(self): + with os_helper.EnvironmentVarGuard() as env: + # try to get a user preferred encoding different than the current + # locale encoding to check that TextIOWrapper() uses the current + # locale encoding and not the user preferred encoding + env.unset('LC_ALL', 'LANG', 'LC_CTYPE') + + current_locale_encoding = locale.getencoding() + b = self.BytesIO() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", EncodingWarning) + t = self.TextIOWrapper(b) + self.assertEqual(t.encoding, current_locale_encoding) + + def test_encoding(self): + # Check the encoding attribute is always set, and valid + b = self.BytesIO() + t = self.TextIOWrapper(b, encoding="utf-8") + self.assertEqual(t.encoding, "utf-8") + with warnings.catch_warnings(): + warnings.simplefilter("ignore", EncodingWarning) + t = self.TextIOWrapper(b) + self.assertIsNotNone(t.encoding) + codecs.lookup(t.encoding) + + def test_encoding_errors_reading(self): + # (1) default + b = self.BytesIO(b"abc\n\xff\n") + t = self.TextIOWrapper(b, encoding="ascii") + self.assertRaises(UnicodeError, t.read) + # (2) explicit strict + b = self.BytesIO(b"abc\n\xff\n") + t = self.TextIOWrapper(b, encoding="ascii", errors="strict") + self.assertRaises(UnicodeError, t.read) + # (3) ignore + b = self.BytesIO(b"abc\n\xff\n") + t = self.TextIOWrapper(b, encoding="ascii", errors="ignore") + self.assertEqual(t.read(), "abc\n\n") + # (4) replace + b = self.BytesIO(b"abc\n\xff\n") + t = self.TextIOWrapper(b, encoding="ascii", errors="replace") + self.assertEqual(t.read(), "abc\n\ufffd\n") + + def test_encoding_errors_writing(self): + # (1) default + b = self.BytesIO() + t = self.TextIOWrapper(b, encoding="ascii") + self.assertRaises(UnicodeError, t.write, "\xff") + # (2) explicit strict + b = self.BytesIO() + t = self.TextIOWrapper(b, encoding="ascii", errors="strict") + self.assertRaises(UnicodeError, t.write, "\xff") + # (3) ignore + b = self.BytesIO() + t = self.TextIOWrapper(b, encoding="ascii", errors="ignore", + newline="\n") + t.write("abc\xffdef\n") + t.flush() + self.assertEqual(b.getvalue(), b"abcdef\n") + # (4) replace + b = self.BytesIO() + t = self.TextIOWrapper(b, encoding="ascii", errors="replace", + newline="\n") + t.write("abc\xffdef\n") + t.flush() + self.assertEqual(b.getvalue(), b"abc?def\n") + + def test_newlines(self): + input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ] + + tests = [ + [ None, [ 'unix\n', 'windows\n', 'os9\n', 'last\n', 'nonl' ] ], + [ '', input_lines ], + [ '\n', [ "unix\n", "windows\r\n", "os9\rlast\n", "nonl" ] ], + [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ], + [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ], + ] + encodings = ( + 'utf-8', 'latin-1', + 'utf-16', 'utf-16-le', 'utf-16-be', + 'utf-32', 'utf-32-le', 'utf-32-be', + ) + + # Try a range of buffer sizes to test the case where \r is the last + # character in TextIOWrapper._pending_line. + for encoding in encodings: + # XXX: str.encode() should return bytes + data = bytes(''.join(input_lines).encode(encoding)) + for do_reads in (False, True): + for bufsize in range(1, 10): + for newline, exp_lines in tests: + bufio = self.BufferedReader(self.BytesIO(data), bufsize) + textio = self.TextIOWrapper(bufio, newline=newline, + encoding=encoding) + if do_reads: + got_lines = [] + while True: + c2 = textio.read(2) + if c2 == '': + break + self.assertEqual(len(c2), 2) + got_lines.append(c2 + textio.readline()) + else: + got_lines = list(textio) + + for got_line, exp_line in zip(got_lines, exp_lines): + self.assertEqual(got_line, exp_line) + self.assertEqual(len(got_lines), len(exp_lines)) + + def test_newlines_input(self): + testdata = b"AAA\nBB\x00B\nCCC\rDDD\rEEE\r\nFFF\r\nGGG" + normalized = testdata.replace(b"\r\n", b"\n").replace(b"\r", b"\n") + for newline, expected in [ + (None, normalized.decode("ascii").splitlines(keepends=True)), + ("", testdata.decode("ascii").splitlines(keepends=True)), + ("\n", ["AAA\n", "BB\x00B\n", "CCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), + ("\r\n", ["AAA\nBB\x00B\nCCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), + ("\r", ["AAA\nBB\x00B\nCCC\r", "DDD\r", "EEE\r", "\nFFF\r", "\nGGG"]), + ]: + buf = self.BytesIO(testdata) + txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) + self.assertEqual(txt.readlines(), expected) + txt.seek(0) + self.assertEqual(txt.read(), "".join(expected)) + + def test_newlines_output(self): + testdict = { + "": b"AAA\nBBB\nCCC\nX\rY\r\nZ", + "\n": b"AAA\nBBB\nCCC\nX\rY\r\nZ", + "\r": b"AAA\rBBB\rCCC\rX\rY\r\rZ", + "\r\n": b"AAA\r\nBBB\r\nCCC\r\nX\rY\r\r\nZ", + } + tests = [(None, testdict[os.linesep])] + sorted(testdict.items()) + for newline, expected in tests: + buf = self.BytesIO() + txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) + txt.write("AAA\nB") + txt.write("BB\nCCC\n") + txt.write("X\rY\r\nZ") + txt.flush() + self.assertEqual(buf.closed, False) + self.assertEqual(buf.getvalue(), expected) + + def test_destructor(self): + l = [] + base = self.BytesIO + class MyBytesIO(base): + def close(self): + l.append(self.getvalue()) + base.close(self) + b = MyBytesIO() + t = self.TextIOWrapper(b, encoding="ascii") + t.write("abc") + del t + support.gc_collect() + self.assertEqual([b"abc"], l) + + def test_override_destructor(self): + record = [] + class MyTextIO(self.TextIOWrapper): + def __del__(self): + record.append(1) + try: + f = super().__del__ + except AttributeError: + pass + else: + f() + def close(self): + record.append(2) + super().close() + def flush(self): + record.append(3) + super().flush() + b = self.BytesIO() + t = MyTextIO(b, encoding="ascii") + del t + support.gc_collect() + self.assertEqual(record, [1, 2, 3]) + + def test_error_through_destructor(self): + # Test that the exception state is not modified by a destructor, + # even if close() fails. + rawio = self.CloseFailureIO() + with support.catch_unraisable_exception() as cm: + with self.assertRaises(AttributeError): + self.TextIOWrapper(rawio, encoding="utf-8").xyzzy + + self.assertEqual(cm.unraisable.exc_type, OSError) + + # Systematic tests of the text I/O API + + def test_basic_io(self): + for chunksize in (1, 2, 3, 4, 5, 15, 16, 17, 31, 32, 33, 63, 64, 65): + for enc in "ascii", "latin-1", "utf-8" :# , "utf-16-be", "utf-16-le": + f = self.open(os_helper.TESTFN, "w+", encoding=enc) + f._CHUNK_SIZE = chunksize + self.assertEqual(f.write("abc"), 3) + f.close() + f = self.open(os_helper.TESTFN, "r+", encoding=enc) + f._CHUNK_SIZE = chunksize + self.assertEqual(f.tell(), 0) + self.assertEqual(f.read(), "abc") + cookie = f.tell() + self.assertEqual(f.seek(0), 0) + self.assertEqual(f.read(None), "abc") + f.seek(0) + self.assertEqual(f.read(2), "ab") + self.assertEqual(f.read(1), "c") + self.assertEqual(f.read(1), "") + self.assertEqual(f.read(), "") + self.assertEqual(f.tell(), cookie) + self.assertEqual(f.seek(0), 0) + self.assertEqual(f.seek(0, 2), cookie) + self.assertEqual(f.write("def"), 3) + self.assertEqual(f.seek(cookie), cookie) + self.assertEqual(f.read(), "def") + if enc.startswith("utf"): + self.multi_line_test(f, enc) + f.close() + + def multi_line_test(self, f, enc): + f.seek(0) + f.truncate() + sample = "s\xff\u0fff\uffff" + wlines = [] + for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000): + chars = [] + for i in range(size): + chars.append(sample[i % len(sample)]) + line = "".join(chars) + "\n" + wlines.append((f.tell(), line)) + f.write(line) + f.seek(0) + rlines = [] + while True: + pos = f.tell() + line = f.readline() + if not line: + break + rlines.append((pos, line)) + self.assertEqual(rlines, wlines) + + def test_telling(self): + f = self.open(os_helper.TESTFN, "w+", encoding="utf-8") + p0 = f.tell() + f.write("\xff\n") + p1 = f.tell() + f.write("\xff\n") + p2 = f.tell() + f.seek(0) + self.assertEqual(f.tell(), p0) + self.assertEqual(f.readline(), "\xff\n") + self.assertEqual(f.tell(), p1) + self.assertEqual(f.readline(), "\xff\n") + self.assertEqual(f.tell(), p2) + f.seek(0) + for line in f: + self.assertEqual(line, "\xff\n") + self.assertRaises(OSError, f.tell) + self.assertEqual(f.tell(), p2) + f.close() + + def test_seeking(self): + chunk_size = _default_chunk_size() + prefix_size = chunk_size - 2 + u_prefix = "a" * prefix_size + prefix = bytes(u_prefix.encode("utf-8")) + self.assertEqual(len(u_prefix), len(prefix)) + u_suffix = "\u8888\n" + suffix = bytes(u_suffix.encode("utf-8")) + line = prefix + suffix + with self.open(os_helper.TESTFN, "wb") as f: + f.write(line*2) + with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: + s = f.read(prefix_size) + self.assertEqual(s, str(prefix, "ascii")) + self.assertEqual(f.tell(), prefix_size) + self.assertEqual(f.readline(), u_suffix) + + def test_seeking_too(self): + # Regression test for a specific bug + data = b'\xe0\xbf\xbf\n' + with self.open(os_helper.TESTFN, "wb") as f: + f.write(data) + with self.open(os_helper.TESTFN, "r", encoding="utf-8") as f: + f._CHUNK_SIZE # Just test that it exists + f._CHUNK_SIZE = 2 + f.readline() + f.tell() + + def test_seek_and_tell(self): + #Test seek/tell using the StatefulIncrementalDecoder. + # Make test faster by doing smaller seeks + CHUNK_SIZE = 128 + + def test_seek_and_tell_with_data(data, min_pos=0): + """Tell/seek to various points within a data stream and ensure + that the decoded data returned by read() is consistent.""" + f = self.open(os_helper.TESTFN, 'wb') + f.write(data) + f.close() + f = self.open(os_helper.TESTFN, encoding='test_decoder') + f._CHUNK_SIZE = CHUNK_SIZE + decoded = f.read() + f.close() + + for i in range(min_pos, len(decoded) + 1): # seek positions + for j in [1, 5, len(decoded) - i]: # read lengths + f = self.open(os_helper.TESTFN, encoding='test_decoder') + self.assertEqual(f.read(i), decoded[:i]) + cookie = f.tell() + self.assertEqual(f.read(j), decoded[i:i + j]) + f.seek(cookie) + self.assertEqual(f.read(), decoded[i:]) + f.close() + + # Enable the test decoder. + StatefulIncrementalDecoder.codecEnabled = 1 + + # Run the tests. + try: + # Try each test case. + for input, _, _ in StatefulIncrementalDecoderTest.test_cases: + test_seek_and_tell_with_data(input) + + # Position each test case so that it crosses a chunk boundary. + for input, _, _ in StatefulIncrementalDecoderTest.test_cases: + offset = CHUNK_SIZE - len(input)//2 + prefix = b'.'*offset + # Don't bother seeking into the prefix (takes too long). + min_pos = offset*2 + test_seek_and_tell_with_data(prefix + input, min_pos) + + # Ensure our test decoder won't interfere with subsequent tests. + finally: + StatefulIncrementalDecoder.codecEnabled = 0 + + def test_multibyte_seek_and_tell(self): + f = self.open(os_helper.TESTFN, "w", encoding="euc_jp") + f.write("AB\n\u3046\u3048\n") + f.close() + + f = self.open(os_helper.TESTFN, "r", encoding="euc_jp") + self.assertEqual(f.readline(), "AB\n") + p0 = f.tell() + self.assertEqual(f.readline(), "\u3046\u3048\n") + p1 = f.tell() + f.seek(p0) + self.assertEqual(f.readline(), "\u3046\u3048\n") + self.assertEqual(f.tell(), p1) + f.close() + + def test_tell_after_readline_with_cr(self): + # Test for gh-141314: TextIOWrapper.tell() assertion failure + # when dealing with standalone carriage returns + data = b'line1\r' + with self.open(os_helper.TESTFN, "wb") as f: + f.write(data) + + with self.open(os_helper.TESTFN, "r") as f: + # Read line that ends with \r + line = f.readline() + self.assertEqual(line, "line1\n") + # This should not cause an assertion failure + pos = f.tell() + # Verify we can seek back to this position + f.seek(pos) + remaining = f.read() + self.assertEqual(remaining, "") + + + def test_seek_with_encoder_state(self): + f = self.open(os_helper.TESTFN, "w", encoding="euc_jis_2004") + f.write("\u00e6\u0300") + p0 = f.tell() + f.write("\u00e6") + f.seek(p0) + f.write("\u0300") + f.close() + + f = self.open(os_helper.TESTFN, "r", encoding="euc_jis_2004") + self.assertEqual(f.readline(), "\u00e6\u0300\u0300") + f.close() + + def test_encoded_writes(self): + data = "1234567890" + tests = ("utf-16", + "utf-16-le", + "utf-16-be", + "utf-32", + "utf-32-le", + "utf-32-be") + for encoding in tests: + buf = self.BytesIO() + f = self.TextIOWrapper(buf, encoding=encoding) + # Check if the BOM is written only once (see issue1753). + f.write(data) + f.write(data) + f.seek(0) + self.assertEqual(f.read(), data * 2) + f.seek(0) + self.assertEqual(f.read(), data * 2) + self.assertEqual(buf.getvalue(), (data * 2).encode(encoding)) + + def test_unreadable(self): + class UnReadable(self.BytesIO): + def readable(self): + return False + txt = self.TextIOWrapper(UnReadable(), encoding="utf-8") + self.assertRaises(OSError, txt.read) + + def test_read_one_by_one(self): + txt = self.TextIOWrapper(self.BytesIO(b"AA\r\nBB"), encoding="utf-8") + reads = "" + while True: + c = txt.read(1) + if not c: + break + reads += c + self.assertEqual(reads, "AA\nBB") + + def test_readlines(self): + txt = self.TextIOWrapper(self.BytesIO(b"AA\nBB\nCC"), encoding="utf-8") + self.assertEqual(txt.readlines(), ["AA\n", "BB\n", "CC"]) + txt.seek(0) + self.assertEqual(txt.readlines(None), ["AA\n", "BB\n", "CC"]) + txt.seek(0) + self.assertEqual(txt.readlines(5), ["AA\n", "BB\n"]) + + # read in amounts equal to TextIOWrapper._CHUNK_SIZE which is 128. + def test_read_by_chunk(self): + # make sure "\r\n" straddles 128 char boundary. + txt = self.TextIOWrapper(self.BytesIO(b"A" * 127 + b"\r\nB"), encoding="utf-8") + reads = "" + while True: + c = txt.read(128) + if not c: + break + reads += c + self.assertEqual(reads, "A"*127+"\nB") + + def test_writelines(self): + l = ['ab', 'cd', 'ef'] + buf = self.BytesIO() + txt = self.TextIOWrapper(buf, encoding="utf-8") + txt.writelines(l) + txt.flush() + self.assertEqual(buf.getvalue(), b'abcdef') + + def test_writelines_userlist(self): + l = UserList(['ab', 'cd', 'ef']) + buf = self.BytesIO() + txt = self.TextIOWrapper(buf, encoding="utf-8") + txt.writelines(l) + txt.flush() + self.assertEqual(buf.getvalue(), b'abcdef') + + def test_writelines_error(self): + txt = self.TextIOWrapper(self.BytesIO(), encoding="utf-8") + self.assertRaises(TypeError, txt.writelines, [1, 2, 3]) + self.assertRaises(TypeError, txt.writelines, None) + self.assertRaises(TypeError, txt.writelines, b'abc') + + def test_issue1395_1(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + + # read one char at a time + reads = "" + while True: + c = txt.read(1) + if not c: + break + reads += c + self.assertEqual(reads, self.normalized) + + def test_issue1395_2(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt._CHUNK_SIZE = 4 + + reads = "" + while True: + c = txt.read(4) + if not c: + break + reads += c + self.assertEqual(reads, self.normalized) + + def test_issue1395_3(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt._CHUNK_SIZE = 4 + + reads = txt.read(4) + reads += txt.read(4) + reads += txt.readline() + reads += txt.readline() + reads += txt.readline() + self.assertEqual(reads, self.normalized) + + def test_issue1395_4(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt._CHUNK_SIZE = 4 + + reads = txt.read(4) + reads += txt.read() + self.assertEqual(reads, self.normalized) + + def test_issue1395_5(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt._CHUNK_SIZE = 4 + + reads = txt.read(4) + pos = txt.tell() + txt.seek(0) + txt.seek(pos) + self.assertEqual(txt.read(4), "BBB\n") + + def test_issue2282(self): + buffer = self.BytesIO(self.testdata) + txt = self.TextIOWrapper(buffer, encoding="ascii") + + self.assertEqual(buffer.seekable(), txt.seekable()) + + def test_append_bom(self): + # The BOM is not written again when appending to a non-empty file + filename = os_helper.TESTFN + for charset in ('utf-8-sig', 'utf-16', 'utf-32'): + with self.open(filename, 'w', encoding=charset) as f: + f.write('aaa') + pos = f.tell() + with self.open(filename, 'rb') as f: + self.assertEqual(f.read(), 'aaa'.encode(charset)) + + with self.open(filename, 'a', encoding=charset) as f: + f.write('xxx') + with self.open(filename, 'rb') as f: + self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) + + def test_seek_bom(self): + # Same test, but when seeking manually + filename = os_helper.TESTFN + for charset in ('utf-8-sig', 'utf-16', 'utf-32'): + with self.open(filename, 'w', encoding=charset) as f: + f.write('aaa') + pos = f.tell() + with self.open(filename, 'r+', encoding=charset) as f: + f.seek(pos) + f.write('zzz') + f.seek(0) + f.write('bbb') + with self.open(filename, 'rb') as f: + self.assertEqual(f.read(), 'bbbzzz'.encode(charset)) + + def test_seek_append_bom(self): + # Same test, but first seek to the start and then to the end + filename = os_helper.TESTFN + for charset in ('utf-8-sig', 'utf-16', 'utf-32'): + with self.open(filename, 'w', encoding=charset) as f: + f.write('aaa') + with self.open(filename, 'a', encoding=charset) as f: + f.seek(0) + f.seek(0, self.SEEK_END) + f.write('xxx') + with self.open(filename, 'rb') as f: + self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) + + def test_errors_property(self): + with self.open(os_helper.TESTFN, "w", encoding="utf-8") as f: + self.assertEqual(f.errors, "strict") + with self.open(os_helper.TESTFN, "w", encoding="utf-8", errors="replace") as f: + self.assertEqual(f.errors, "replace") + + @support.no_tracing + @threading_helper.requires_working_threading() + def test_threads_write(self): + # Issue6750: concurrent writes could duplicate data + event = threading.Event() + with self.open(os_helper.TESTFN, "w", encoding="utf-8", buffering=1) as f: + def run(n): + text = "Thread%03d\n" % n + event.wait() + f.write(text) + threads = [threading.Thread(target=run, args=(x,)) + for x in range(20)] + with threading_helper.start_threads(threads, event.set): + time.sleep(0.02) + with self.open(os_helper.TESTFN, encoding="utf-8") as f: + content = f.read() + for n in range(20): + self.assertEqual(content.count("Thread%03d\n" % n), 1) + + def test_flush_error_on_close(self): + # Test that text file is closed despite failed flush + # and that flush() is called before file closed. + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + closed = [] + def bad_flush(): + closed[:] = [txt.closed, txt.buffer.closed] + raise OSError() + txt.flush = bad_flush + self.assertRaises(OSError, txt.close) # exception not swallowed + self.assertTrue(txt.closed) + self.assertTrue(txt.buffer.closed) + self.assertTrue(closed) # flush() called + self.assertFalse(closed[0]) # flush() called before file closed + self.assertFalse(closed[1]) + txt.flush = lambda: None # break reference loop + + def test_close_error_on_close(self): + buffer = self.BytesIO(self.testdata) + def bad_flush(): + raise OSError('flush') + def bad_close(): + raise OSError('close') + buffer.close = bad_close + txt = self.TextIOWrapper(buffer, encoding="ascii") + txt.flush = bad_flush + with self.assertRaises(OSError) as err: # exception not swallowed + txt.close() + self.assertEqual(err.exception.args, ('close',)) + self.assertIsInstance(err.exception.__context__, OSError) + self.assertEqual(err.exception.__context__.args, ('flush',)) + self.assertFalse(txt.closed) + + # Silence destructor error + buffer.close = lambda: None + txt.flush = lambda: None + + def test_nonnormalized_close_error_on_close(self): + # Issue #21677 + buffer = self.BytesIO(self.testdata) + def bad_flush(): + raise non_existing_flush + def bad_close(): + raise non_existing_close + buffer.close = bad_close + txt = self.TextIOWrapper(buffer, encoding="ascii") + txt.flush = bad_flush + with self.assertRaises(NameError) as err: # exception not swallowed + txt.close() + self.assertIn('non_existing_close', str(err.exception)) + self.assertIsInstance(err.exception.__context__, NameError) + self.assertIn('non_existing_flush', str(err.exception.__context__)) + self.assertFalse(txt.closed) + + # Silence destructor error + buffer.close = lambda: None + txt.flush = lambda: None + + def test_multi_close(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + txt.close() + txt.close() + txt.close() + self.assertRaises(ValueError, txt.flush) + + def test_unseekable(self): + txt = self.TextIOWrapper(self.MockUnseekableIO(self.testdata), encoding="utf-8") + self.assertRaises(self.UnsupportedOperation, txt.tell) + self.assertRaises(self.UnsupportedOperation, txt.seek, 0) + + def test_readonly_attributes(self): + txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") + buf = self.BytesIO(self.testdata) + with self.assertRaises(AttributeError): + txt.buffer = buf + + def test_rawio(self): + # Issue #12591: TextIOWrapper must work with raw I/O objects, so + # that subprocess.Popen() can have the required unbuffered + # semantics with universal_newlines=True. + raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) + txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') + # Reads + self.assertEqual(txt.read(4), 'abcd') + self.assertEqual(txt.readline(), 'efghi\n') + self.assertEqual(list(txt), ['jkl\n', 'opq\n']) + + def test_rawio_write_through(self): + # Issue #12591: with write_through=True, writes don't need a flush + raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) + txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n', + write_through=True) + txt.write('1') + txt.write('23\n4') + txt.write('5') + self.assertEqual(b''.join(raw._write_stack), b'123\n45') + + def test_bufio_write_through(self): + # Issue #21396: write_through=True doesn't force a flush() + # on the underlying binary buffered object. + flush_called, write_called = [], [] + class BufferedWriter(self.BufferedWriter): + def flush(self, *args, **kwargs): + flush_called.append(True) + return super().flush(*args, **kwargs) + def write(self, *args, **kwargs): + write_called.append(True) + return super().write(*args, **kwargs) + + rawio = self.BytesIO() + data = b"a" + bufio = BufferedWriter(rawio, len(data)*2) + textio = self.TextIOWrapper(bufio, encoding='ascii', + write_through=True) + # write to the buffered io but don't overflow the buffer + text = data.decode('ascii') + textio.write(text) + + # buffer.flush is not called with write_through=True + self.assertFalse(flush_called) + # buffer.write *is* called with write_through=True + self.assertTrue(write_called) + self.assertEqual(rawio.getvalue(), b"") # no flush + + write_called = [] # reset + textio.write(text * 10) # total content is larger than bufio buffer + self.assertTrue(write_called) + self.assertEqual(rawio.getvalue(), data * 11) # all flushed + + def test_reconfigure_write_through(self): + raw = self.MockRawIO([]) + t = self.TextIOWrapper(raw, encoding='ascii', newline='\n') + t.write('1') + t.reconfigure(write_through=True) # implied flush + self.assertEqual(t.write_through, True) + self.assertEqual(b''.join(raw._write_stack), b'1') + t.write('23') + self.assertEqual(b''.join(raw._write_stack), b'123') + t.reconfigure(write_through=False) + self.assertEqual(t.write_through, False) + t.write('45') + t.flush() + self.assertEqual(b''.join(raw._write_stack), b'12345') + # Keeping default value + t.reconfigure() + t.reconfigure(write_through=None) + self.assertEqual(t.write_through, False) + t.reconfigure(write_through=True) + t.reconfigure() + t.reconfigure(write_through=None) + self.assertEqual(t.write_through, True) + + def test_read_nonbytes(self): + # Issue #17106 + # Crash when underlying read() returns non-bytes + t = self.TextIOWrapper(self.StringIO('a'), encoding="utf-8") + self.assertRaises(TypeError, t.read, 1) + t = self.TextIOWrapper(self.StringIO('a'), encoding="utf-8") + self.assertRaises(TypeError, t.readline) + t = self.TextIOWrapper(self.StringIO('a'), encoding="utf-8") + self.assertRaises(TypeError, t.read) + + def test_illegal_encoder(self): + # Issue 31271: Calling write() while the return value of encoder's + # encode() is invalid shouldn't cause an assertion failure. + rot13 = codecs.lookup("rot13") + with support.swap_attr(rot13, '_is_text_encoding', True): + t = self.TextIOWrapper(self.BytesIO(b'foo'), encoding="rot13") + self.assertRaises(TypeError, t.write, 'bar') + + def test_illegal_decoder(self): + # Issue #17106 + # Bypass the early encoding check added in issue 20404 + def _make_illegal_wrapper(): + quopri = codecs.lookup("quopri") + quopri._is_text_encoding = True + try: + t = self.TextIOWrapper(self.BytesIO(b'aaaaaa'), + newline='\n', encoding="quopri") + finally: + quopri._is_text_encoding = False + return t + # Crash when decoder returns non-string + t = _make_illegal_wrapper() + self.assertRaises(TypeError, t.read, 1) + t = _make_illegal_wrapper() + self.assertRaises(TypeError, t.readline) + t = _make_illegal_wrapper() + self.assertRaises(TypeError, t.read) + + # Issue 31243: calling read() while the return value of decoder's + # getstate() is invalid should neither crash the interpreter nor + # raise a SystemError. + def _make_very_illegal_wrapper(getstate_ret_val): + class BadDecoder: + def getstate(self): + return getstate_ret_val + def _get_bad_decoder(dummy): + return BadDecoder() + quopri = codecs.lookup("quopri") + with support.swap_attr(quopri, 'incrementaldecoder', + _get_bad_decoder): + return _make_illegal_wrapper() + t = _make_very_illegal_wrapper(42) + self.assertRaises(TypeError, t.read, 42) + t = _make_very_illegal_wrapper(()) + self.assertRaises(TypeError, t.read, 42) + t = _make_very_illegal_wrapper((1, 2)) + self.assertRaises(TypeError, t.read, 42) + + def _check_create_at_shutdown(self, **kwargs): + # Issue #20037: creating a TextIOWrapper at shutdown + # shouldn't crash the interpreter. + iomod = self.io.__name__ + code = """if 1: + import codecs + import {iomod} as io + + # Avoid looking up codecs at shutdown + codecs.lookup('utf-8') + + class C: + def __del__(self): + io.TextIOWrapper(io.BytesIO(), **{kwargs}) + print("ok") + c = C() + """.format(iomod=iomod, kwargs=kwargs) + return assert_python_ok("-c", code) + + def test_create_at_shutdown_without_encoding(self): + rc, out, err = self._check_create_at_shutdown() + if err: + # Can error out with a RuntimeError if the module state + # isn't found. + self.assertIn(self.shutdown_error, err.decode()) + else: + self.assertEqual("ok", out.decode().strip()) + + def test_create_at_shutdown_with_encoding(self): + rc, out, err = self._check_create_at_shutdown(encoding='utf-8', + errors='strict') + self.assertFalse(err) + self.assertEqual("ok", out.decode().strip()) + + def test_read_byteslike(self): + r = MemviewBytesIO(b'Just some random string\n') + t = self.TextIOWrapper(r, 'utf-8') + + # TextIOwrapper will not read the full string, because + # we truncate it to a multiple of the native int size + # so that we can construct a more complex memoryview. + bytes_val = _to_memoryview(r.getvalue()).tobytes() + + self.assertEqual(t.read(200), bytes_val.decode('utf-8')) + + def test_issue22849(self): + class F(object): + def readable(self): return True + def writable(self): return True + def seekable(self): return True + + for i in range(10): + try: + self.TextIOWrapper(F(), encoding='utf-8') + except Exception: + pass + + F.tell = lambda x: 0 + t = self.TextIOWrapper(F(), encoding='utf-8') + + def test_reconfigure_locale(self): + wrapper = self.TextIOWrapper(self.BytesIO(b"test")) + wrapper.reconfigure(encoding="locale") + + def test_reconfigure_encoding_read(self): + # latin1 -> utf8 + # (latin1 can decode utf-8 encoded string) + data = 'abc\xe9\n'.encode('latin1') + 'd\xe9f\n'.encode('utf8') + raw = self.BytesIO(data) + txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') + self.assertEqual(txt.readline(), 'abc\xe9\n') + with self.assertRaises(self.UnsupportedOperation): + txt.reconfigure(encoding='utf-8') + with self.assertRaises(self.UnsupportedOperation): + txt.reconfigure(newline=None) + + def test_reconfigure_write_fromascii(self): + # ascii has a specific encodefunc in the C implementation, + # but utf-8-sig has not. Make sure that we get rid of the + # cached encodefunc when we switch encoders. + raw = self.BytesIO() + txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') + txt.write('foo\n') + txt.reconfigure(encoding='utf-8-sig') + txt.write('\xe9\n') + txt.flush() + self.assertEqual(raw.getvalue(), b'foo\n\xc3\xa9\n') + + def test_reconfigure_write(self): + # latin -> utf8 + raw = self.BytesIO() + txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') + txt.write('abc\xe9\n') + txt.reconfigure(encoding='utf-8') + self.assertEqual(raw.getvalue(), b'abc\xe9\n') + txt.write('d\xe9f\n') + txt.flush() + self.assertEqual(raw.getvalue(), b'abc\xe9\nd\xc3\xa9f\n') + + # ascii -> utf-8-sig: ensure that no BOM is written in the middle of + # the file + raw = self.BytesIO() + txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') + txt.write('abc\n') + txt.reconfigure(encoding='utf-8-sig') + txt.write('d\xe9f\n') + txt.flush() + self.assertEqual(raw.getvalue(), b'abc\nd\xc3\xa9f\n') + + def test_reconfigure_write_non_seekable(self): + raw = self.BytesIO() + raw.seekable = lambda: False + raw.seek = None + txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') + txt.write('abc\n') + txt.reconfigure(encoding='utf-8-sig') + txt.write('d\xe9f\n') + txt.flush() + + # If the raw stream is not seekable, there'll be a BOM + self.assertEqual(raw.getvalue(), b'abc\n\xef\xbb\xbfd\xc3\xa9f\n') + + def test_reconfigure_defaults(self): + txt = self.TextIOWrapper(self.BytesIO(), 'ascii', 'replace', '\n') + txt.reconfigure(encoding=None) + self.assertEqual(txt.encoding, 'ascii') + self.assertEqual(txt.errors, 'replace') + txt.write('LF\n') + + txt.reconfigure(newline='\r\n') + self.assertEqual(txt.encoding, 'ascii') + self.assertEqual(txt.errors, 'replace') + + txt.reconfigure(errors='ignore') + self.assertEqual(txt.encoding, 'ascii') + self.assertEqual(txt.errors, 'ignore') + txt.write('CRLF\n') + + txt.reconfigure(encoding='utf-8', newline=None) + self.assertEqual(txt.errors, 'strict') + txt.seek(0) + self.assertEqual(txt.read(), 'LF\nCRLF\n') + + self.assertEqual(txt.detach().getvalue(), b'LF\nCRLF\r\n') + + def test_reconfigure_errors(self): + txt = self.TextIOWrapper(self.BytesIO(), 'ascii', 'replace', '\r') + with self.assertRaises(TypeError): # there was a crash + txt.reconfigure(encoding=42) + if self.is_C: + with self.assertRaises(UnicodeEncodeError): + txt.reconfigure(encoding='\udcfe') + with self.assertRaises(LookupError): + txt.reconfigure(encoding='locale\0') + # TODO: txt.reconfigure(encoding='utf-8\0') + # TODO: txt.reconfigure(encoding='nonexisting') + with self.assertRaises(TypeError): + txt.reconfigure(errors=42) + if self.is_C: + with self.assertRaises(UnicodeEncodeError): + txt.reconfigure(errors='\udcfe') + # TODO: txt.reconfigure(errors='ignore\0') + # TODO: txt.reconfigure(errors='nonexisting') + with self.assertRaises(TypeError): + txt.reconfigure(newline=42) + with self.assertRaises(ValueError): + txt.reconfigure(newline='\udcfe') + with self.assertRaises(ValueError): + txt.reconfigure(newline='xyz') + if not self.is_C: + # TODO: Should fail in C too. + with self.assertRaises(ValueError): + txt.reconfigure(newline='\n\0') + if self.is_C: + # TODO: Use __bool__(), not __index__(). + with self.assertRaises(ZeroDivisionError): + txt.reconfigure(line_buffering=BadIndex()) + with self.assertRaises(OverflowError): + txt.reconfigure(line_buffering=2**1000) + with self.assertRaises(ZeroDivisionError): + txt.reconfigure(write_through=BadIndex()) + with self.assertRaises(OverflowError): + txt.reconfigure(write_through=2**1000) + with self.assertRaises(ZeroDivisionError): # there was a crash + txt.reconfigure(line_buffering=BadIndex(), + write_through=BadIndex()) + self.assertEqual(txt.encoding, 'ascii') + self.assertEqual(txt.errors, 'replace') + self.assertIs(txt.line_buffering, False) + self.assertIs(txt.write_through, False) + + txt.reconfigure(encoding='latin1', errors='ignore', newline='\r\n', + line_buffering=True, write_through=True) + self.assertEqual(txt.encoding, 'latin1') + self.assertEqual(txt.errors, 'ignore') + self.assertIs(txt.line_buffering, True) + self.assertIs(txt.write_through, True) + + def test_reconfigure_newline(self): + raw = self.BytesIO(b'CR\rEOF') + txt = self.TextIOWrapper(raw, 'ascii', newline='\n') + txt.reconfigure(newline=None) + self.assertEqual(txt.readline(), 'CR\n') + raw = self.BytesIO(b'CR\rEOF') + txt = self.TextIOWrapper(raw, 'ascii', newline='\n') + txt.reconfigure(newline='') + self.assertEqual(txt.readline(), 'CR\r') + raw = self.BytesIO(b'CR\rLF\nEOF') + txt = self.TextIOWrapper(raw, 'ascii', newline='\r') + txt.reconfigure(newline='\n') + self.assertEqual(txt.readline(), 'CR\rLF\n') + raw = self.BytesIO(b'LF\nCR\rEOF') + txt = self.TextIOWrapper(raw, 'ascii', newline='\n') + txt.reconfigure(newline='\r') + self.assertEqual(txt.readline(), 'LF\nCR\r') + raw = self.BytesIO(b'CR\rCRLF\r\nEOF') + txt = self.TextIOWrapper(raw, 'ascii', newline='\r') + txt.reconfigure(newline='\r\n') + self.assertEqual(txt.readline(), 'CR\rCRLF\r\n') + + txt = self.TextIOWrapper(self.BytesIO(), 'ascii', newline='\r') + txt.reconfigure(newline=None) + txt.write('linesep\n') + txt.reconfigure(newline='') + txt.write('LF\n') + txt.reconfigure(newline='\n') + txt.write('LF\n') + txt.reconfigure(newline='\r') + txt.write('CR\n') + txt.reconfigure(newline='\r\n') + txt.write('CRLF\n') + expected = 'linesep' + os.linesep + 'LF\nLF\nCR\rCRLF\r\n' + self.assertEqual(txt.detach().getvalue().decode('ascii'), expected) + + def test_issue25862(self): + # Assertion failures occurred in tell() after read() and write(). + t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') + t.read(1) + t.read() + t.tell() + t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') + t.read(1) + t.write('x') + t.tell() + + def test_issue35928(self): + p = self.BufferedRWPair(self.BytesIO(b'foo\nbar\n'), self.BytesIO()) + f = self.TextIOWrapper(p) + res = f.readline() + self.assertEqual(res, 'foo\n') + f.write(res) + self.assertEqual(res + f.readline(), 'foo\nbar\n') + + def test_pickling_subclass(self): + global MyTextIO + class MyTextIO(self.TextIOWrapper): + def __init__(self, raw, tag): + super().__init__(raw) + self.tag = tag + def __getstate__(self): + return self.tag, self.buffer.getvalue() + def __setstate__(slf, state): + tag, value = state + slf.__init__(self.BytesIO(value), tag) + + raw = self.BytesIO(b'data') + txt = MyTextIO(raw, 'ham') + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(protocol=proto): + pickled = pickle.dumps(txt, proto) + newtxt = pickle.loads(pickled) + self.assertEqual(newtxt.buffer.getvalue(), b'data') + self.assertEqual(newtxt.tag, 'ham') + del MyTextIO + + @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + def test_read_non_blocking(self): + import os + r, w = os.pipe() + try: + os.set_blocking(r, False) + with self.io.open(r, 'rt') as textfile: + r = None + # Nothing has been written so a non-blocking read raises a BlockingIOError exception. + with self.assertRaises(BlockingIOError): + textfile.read() + finally: + if r is not None: + os.close(r) + os.close(w) + + +class MemviewBytesIO(io.BytesIO): + '''A BytesIO object whose read method returns memoryviews + rather than bytes''' + + def read1(self, len_): + return _to_memoryview(super().read1(len_)) + + def read(self, len_): + return _to_memoryview(super().read(len_)) + +def _to_memoryview(buf): + '''Convert bytes-object *buf* to a non-trivial memoryview''' + + arr = array.array('i') + idx = len(buf) - len(buf) % arr.itemsize + arr.frombytes(buf[:idx]) + return memoryview(arr) + + +class CTextIOWrapperTest(TextIOWrapperTest, CTestCase): + shutdown_error = "LookupError: unknown encoding: ascii" + + def test_chunk_size(self): + t = self.TextIOWrapper(self.BytesIO(), encoding="utf-8") + self.assertGreater(t._CHUNK_SIZE, 0) + t._CHUNK_SIZE = 1024 + self.assertEqual(t._CHUNK_SIZE, 1024) + with self.assertRaisesRegex(ValueError, + 'a strictly positive integer is required'): + t._CHUNK_SIZE = 0 + with self.assertRaises(TypeError): + t._CHUNK_SIZE = 'x' + with self.assertRaises(ValueError): + t._CHUNK_SIZE = sys.maxsize + 1 + with self.assertRaises(ValueError): + t._CHUNK_SIZE = -sys.maxsize - 2 + with self.assertRaises(ValueError): + t._CHUNK_SIZE = 2**1000 + with self.assertRaises(ValueError): + t._CHUNK_SIZE = -2**1000 + with self.assertRaisesRegex(AttributeError, 'cannot be deleted'): + del t._CHUNK_SIZE + # a failed assignment does not change the value + self.assertEqual(t._CHUNK_SIZE, 1024) + + def test_reentrant_seek_during_tell(self): + # gh-153539: reading short of _CHUNK_SIZE leaves residual bytes in the + # snapshot, so tell() re-decodes and calls the decoder's getstate(); a + # reentrant seek() there must not free the snapshot tell() still uses. + # C-only: _pyio binds next_input as a strong local and cannot crash. + wrapper = None + armed = False + + class ReentrantDecoder(codecs.IncrementalDecoder): + def decode(self, input, final=False): + return bytes(input).decode("latin-1") + def getstate(self): + nonlocal armed + if wrapper is not None and armed: + armed = False + wrapper.seek(0) + return (b"", 0) + def setstate(self, state): + pass + + def search(name): + if name != "reentrant_tell_test": + return None + return codecs.CodecInfo( + name=name, + encode=lambda s, e='strict': (s.encode("latin-1"), len(s)), + decode=lambda b, e='strict': (bytes(b).decode("latin-1"), len(b)), + incrementaldecoder=ReentrantDecoder) + + codecs.register(search) + self.addCleanup(codecs.unregister, search) + raw = self.BytesIO(b"abcdefghijklmnop" * 8) + wrapper = self.TextIOWrapper(self.BufferedReader(raw), + encoding="reentrant_tell_test", newline="") + wrapper._CHUNK_SIZE = 8 + wrapper.read(5) + armed = True + self.assertIsInstance(wrapper.tell(), int) + # tell() at the snapshot boundary takes the early return that owns and + # must release next_input; exercise it too (leak-checked under -R). + wrapper.seek(0) + self.assertIsInstance(wrapper.tell(), int) + + def test_initialization(self): + r = self.BytesIO(b"\xc3\xa9\n\n") + b = self.BufferedReader(r, 1000) + t = self.TextIOWrapper(b, encoding="utf-8") + self.assertRaises(ValueError, t.__init__, b, encoding="utf-8", newline='xyzzy') + self.assertRaises(ValueError, t.read) + + t = self.TextIOWrapper.__new__(self.TextIOWrapper) + self.assertRaises(Exception, repr, t) + + def test_garbage_collection(self): + # C TextIOWrapper objects are collected, and collecting them flushes + # all data to disk. + # The Python version has __del__, so it ends in gc.garbage instead. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", ResourceWarning) + rawio = self.FileIO(os_helper.TESTFN, "wb") + b = self.BufferedWriter(rawio) + t = self.TextIOWrapper(b, encoding="ascii") + t.write("456def") + t.x = t + wr = weakref.ref(t) + del t + support.gc_collect() + self.assertIsNone(wr(), wr) + with self.open(os_helper.TESTFN, "rb") as f: + self.assertEqual(f.read(), b"456def") + + def test_rwpair_cleared_before_textio(self): + # Issue 13070: TextIOWrapper's finalization would crash when called + # after the reference to the underlying BufferedRWPair's writer got + # cleared by the GC. + for i in range(1000): + b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) + t1 = self.TextIOWrapper(b1, encoding="ascii") + b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) + t2 = self.TextIOWrapper(b2, encoding="ascii") + # circular references + t1.buddy = t2 + t2.buddy = t1 + support.gc_collect() + + def test_del__CHUNK_SIZE_SystemError(self): + t = self.TextIOWrapper(self.BytesIO(), encoding='ascii') + with self.assertRaises(AttributeError): + del t._CHUNK_SIZE + + def test_internal_buffer_size(self): + # bpo-43260: TextIOWrapper's internal buffer should not store + # data larger than chunk size. + chunk_size = 8192 # default chunk size, updated later + + class MockIO(self.MockRawIO): + def write(self, data): + if len(data) > chunk_size: + raise RuntimeError + return super().write(data) + + buf = MockIO() + t = self.TextIOWrapper(buf, encoding="ascii") + chunk_size = t._CHUNK_SIZE + t.write("abc") + t.write("def") + # default chunk size is 8192 bytes so t don't write data to buf. + self.assertEqual([], buf._write_stack) + + with self.assertRaises(RuntimeError): + t.write("x"*(chunk_size+1)) + + self.assertEqual([b"abcdef"], buf._write_stack) + t.write("ghi") + t.write("x"*chunk_size) + self.assertEqual([b"abcdef", b"ghi", b"x"*chunk_size], buf._write_stack) + + def test_issue119506(self): + chunk_size = 8192 + + class MockIO(self.MockRawIO): + written = False + def write(self, data): + if not self.written: + self.written = True + t.write("middle") + return super().write(data) + + buf = MockIO() + t = self.TextIOWrapper(buf) + t.write("abc") + t.write("def") + # writing data which size >= chunk_size cause flushing buffer before write. + t.write("g" * chunk_size) + t.flush() + + self.assertEqual([b"abcdef", b"middle", b"g"*chunk_size], + buf._write_stack) + + def test_issue142594(self): + wrapper = None + detached = False + class ReentrantRawIO(self.RawIOBase): + @property + def closed(self): + nonlocal detached + if wrapper is not None and not detached: + detached = True + wrapper.detach() + return False + + raw = ReentrantRawIO() + wrapper = self.TextIOWrapper(raw) + wrapper.close() # should not crash + + def test_reentrant_detach_during_flush(self): + # gh-143008: Reentrant detach() during flush should not crash. + + class DetachOnce(self.BufferedRandom): + wrapper = None + + def detach_once(self): + original = self.wrapper + self.wrapper = None + if original is not None: + original.detach() + original.flush() + + class DetachOnFlush(DetachOnce): + def flush(self): + self.detach_once() + + class DetachOnWrite(DetachOnce): + def write(self, b): + self.detach_once() + return len(b) + + # Separate reference for after detach_once. + wrapper = None + + def make_text(buffer): + nonlocal wrapper + buffer.wrapper = self.TextIOWrapper(buffer, encoding='utf-8') + wrapper = buffer.wrapper + + # Many calls could result in the same null self->buffer crash. + tests = [ + ('truncate', lambda: wrapper.truncate(0)), + ('close', lambda: wrapper.close()), + ('detach', lambda: wrapper.detach()), + ('seek', lambda: wrapper.seek(0)), + ('tell', lambda: wrapper.tell()), + ('reconfigure', lambda: wrapper.reconfigure(line_buffering=True)), + ] + for name, method in tests: + with self.subTest(name): + make_text(DetachOnFlush(self.MockRawIO())) + self.assertRaisesRegex(ValueError, "detached", method) + + # Should not crash. + with self.subTest('read via writeflush'): + make_text(DetachOnWrite(self.MockRawIO())) + wrapper.write('x') + self.assertRaisesRegex(ValueError, "detached", wrapper.read) + + def test_reentrant_detach_during_read(self): + # gh-157363, gh-157364: The buffer must stay alive until its active + # read operation returns. + wrapper = None + + class DetachOnRead(self.RawIOBase): + detached = False + + def readable(self): + return True + + def readinto(self, b): + if self.detached: + return 0 + self.detached = True + wrapper.detach() + b[:3] = b"ab\n" + return 3 + + for method_name in ("read", "readline"): + with self.subTest(method_name): + raw = DetachOnRead() + wrapper = self.TextIOWrapper( + self.BufferedReader(raw), encoding="utf-8") + method = getattr(wrapper, method_name) + self.assertEqual(method(), "ab\n") + with self.assertRaisesRegex(ValueError, + "underlying buffer has been detached"): + getattr(wrapper, 'buffer') + + +class PyTextIOWrapperTest(TextIOWrapperTest, PyTestCase): + shutdown_error = "LookupError: unknown encoding: ascii" + + +class IncrementalNewlineDecoderTest: + + def check_newline_decoding_utf8(self, decoder): + # UTF-8 specific tests for a newline decoder + def _check_decode(b, s, **kwargs): + # We exercise getstate() / setstate() as well as decode() + state = decoder.getstate() + self.assertEqual(decoder.decode(b, **kwargs), s) + decoder.setstate(state) + self.assertEqual(decoder.decode(b, **kwargs), s) + + _check_decode(b'\xe8\xa2\x88', "\u8888") + + _check_decode(b'\xe8', "") + _check_decode(b'\xa2', "") + _check_decode(b'\x88', "\u8888") + + _check_decode(b'\xe8', "") + _check_decode(b'\xa2', "") + _check_decode(b'\x88', "\u8888") + + _check_decode(b'\xe8', "") + self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True) + + decoder.reset() + _check_decode(b'\n', "\n") + _check_decode(b'\r', "") + _check_decode(b'', "\n", final=True) + _check_decode(b'\r', "\n", final=True) + + _check_decode(b'\r', "") + _check_decode(b'a', "\na") + + _check_decode(b'\r\r\n', "\n\n") + _check_decode(b'\r', "") + _check_decode(b'\r', "\n") + _check_decode(b'\na', "\na") + + _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n") + _check_decode(b'\xe8\xa2\x88', "\u8888") + _check_decode(b'\n', "\n") + _check_decode(b'\xe8\xa2\x88\r', "\u8888") + _check_decode(b'\n', "\n") + + def check_newline_decoding(self, decoder, encoding): + result = [] + if encoding is not None: + encoder = codecs.getincrementalencoder(encoding)() + def _decode_bytewise(s): + # Decode one byte at a time + for b in encoder.encode(s): + result.append(decoder.decode(bytes([b]))) + else: + encoder = None + def _decode_bytewise(s): + # Decode one char at a time + for c in s: + result.append(decoder.decode(c)) + self.assertEqual(decoder.newlines, None) + _decode_bytewise("abc\n\r") + self.assertEqual(decoder.newlines, '\n') + _decode_bytewise("\nabc") + self.assertEqual(decoder.newlines, ('\n', '\r\n')) + _decode_bytewise("abc\r") + self.assertEqual(decoder.newlines, ('\n', '\r\n')) + _decode_bytewise("abc") + self.assertEqual(decoder.newlines, ('\r', '\n', '\r\n')) + _decode_bytewise("abc\r") + self.assertEqual("".join(result), "abc\n\nabcabc\nabcabc") + decoder.reset() + input = "abc" + if encoder is not None: + encoder.reset() + input = encoder.encode(input) + self.assertEqual(decoder.decode(input), "abc") + self.assertEqual(decoder.newlines, None) + + def test_newline_decoder(self): + encodings = ( + # None meaning the IncrementalNewlineDecoder takes unicode input + # rather than bytes input + None, 'utf-8', 'latin-1', + 'utf-16', 'utf-16-le', 'utf-16-be', + 'utf-32', 'utf-32-le', 'utf-32-be', + ) + for enc in encodings: + decoder = enc and codecs.getincrementaldecoder(enc)() + decoder = self.IncrementalNewlineDecoder(decoder, translate=True) + self.check_newline_decoding(decoder, enc) + decoder = codecs.getincrementaldecoder("utf-8")() + decoder = self.IncrementalNewlineDecoder(decoder, translate=True) + self.check_newline_decoding_utf8(decoder) + self.assertRaises(TypeError, decoder.setstate, 42) + + def test_newline_bytes(self): + # Issue 5433: Excessive optimization in IncrementalNewlineDecoder + def _check(dec): + self.assertEqual(dec.newlines, None) + self.assertEqual(dec.decode("\u0D00"), "\u0D00") + self.assertEqual(dec.newlines, None) + self.assertEqual(dec.decode("\u0A00"), "\u0A00") + self.assertEqual(dec.newlines, None) + dec = self.IncrementalNewlineDecoder(None, translate=False) + _check(dec) + dec = self.IncrementalNewlineDecoder(None, translate=True) + _check(dec) + + def test_translate(self): + # issue 35062 + for translate in (-2, -1, 1, 2): + decoder = codecs.getincrementaldecoder("utf-8")() + decoder = self.IncrementalNewlineDecoder(decoder, translate) + self.check_newline_decoding_utf8(decoder) + decoder = codecs.getincrementaldecoder("utf-8")() + decoder = self.IncrementalNewlineDecoder(decoder, translate=0) + self.assertEqual(decoder.decode(b"\r\r\n"), "\r\r\n") + +class CIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest, unittest.TestCase): + IncrementalNewlineDecoder = io.IncrementalNewlineDecoder + + @support.cpython_only + def test_uninitialized(self): + uninitialized = self.IncrementalNewlineDecoder.__new__( + self.IncrementalNewlineDecoder) + self.assertRaises(ValueError, uninitialized.decode, b'bar') + self.assertRaises(ValueError, uninitialized.getstate) + self.assertRaises(ValueError, uninitialized.setstate, (b'foo', 0)) + self.assertRaises(ValueError, uninitialized.reset) + + +class PyIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest, unittest.TestCase): + IncrementalNewlineDecoder = pyio.IncrementalNewlineDecoder diff --git a/Lib/test/test_univnewlines.py b/Lib/test/test_io/test_univnewlines.py similarity index 100% rename from Lib/test/test_univnewlines.py rename to Lib/test/test_io/test_univnewlines.py diff --git a/Lib/test/test_io/utils.py b/Lib/test/test_io/utils.py new file mode 100644 index 00000000000..3b1faec2140 --- /dev/null +++ b/Lib/test/test_io/utils.py @@ -0,0 +1,318 @@ +import array +import threading +import time +import unittest + +import io # C implementation of io +import _pyio as pyio # Python implementation of io + + +try: + import ctypes +except ImportError: + def byteslike(*pos, **kw): + return array.array("b", bytes(*pos, **kw)) +else: + class EmptyStruct(ctypes.Structure): + pass + + def byteslike(*pos, **kw): + """Create a bytes-like object having no string or sequence methods""" + data = bytes(*pos, **kw) + obj = EmptyStruct() + ctypes.resize(obj, len(data)) + memoryview(obj).cast("B")[:] = data + return obj + + +class MockRawIOWithoutRead: + """A RawIO implementation without read(), so as to exercise the default + RawIO.read() which calls readinto().""" + + def __init__(self, read_stack=()): + self._read_stack = list(read_stack) + self._write_stack = [] + self._reads = 0 + self._extraneous_reads = 0 + + def write(self, b): + self._write_stack.append(bytes(b)) + return len(b) + + def writable(self): + return True + + def fileno(self): + return 42 + + def readable(self): + return True + + def seekable(self): + return True + + def seek(self, pos, whence): + return 0 # wrong but we gotta return something + + def tell(self): + return 0 # same comment as above + + def readinto(self, buf): + self._reads += 1 + max_len = len(buf) + try: + data = self._read_stack[0] + except IndexError: + self._extraneous_reads += 1 + return 0 + if data is None: + del self._read_stack[0] + return None + n = len(data) + if len(data) <= max_len: + del self._read_stack[0] + buf[:n] = data + return n + else: + buf[:] = data[:max_len] + self._read_stack[0] = data[max_len:] + return max_len + + def truncate(self, pos=None): + return pos + +class CMockRawIOWithoutRead(MockRawIOWithoutRead, io.RawIOBase): + pass + +class PyMockRawIOWithoutRead(MockRawIOWithoutRead, pyio.RawIOBase): + pass + + +class MockRawIO(MockRawIOWithoutRead): + + def read(self, n=None): + self._reads += 1 + try: + return self._read_stack.pop(0) + except: + self._extraneous_reads += 1 + return b"" + +class CMockRawIO(MockRawIO, io.RawIOBase): + pass + +class PyMockRawIO(MockRawIO, pyio.RawIOBase): + pass + + +class MisbehavedRawIO(MockRawIO): + def write(self, b): + return super().write(b) * 2 + + def read(self, n=None): + return super().read(n) * 2 + + def seek(self, pos, whence): + return -123 + + def tell(self): + return -456 + + def readinto(self, buf): + super().readinto(buf) + return len(buf) * 5 + +class CMisbehavedRawIO(MisbehavedRawIO, io.RawIOBase): + pass + +class PyMisbehavedRawIO(MisbehavedRawIO, pyio.RawIOBase): + pass + + +class SlowFlushRawIO(MockRawIO): + def __init__(self): + super().__init__() + self.in_flush = threading.Event() + + def flush(self): + self.in_flush.set() + time.sleep(0.25) + +class CSlowFlushRawIO(SlowFlushRawIO, io.RawIOBase): + pass + +class PySlowFlushRawIO(SlowFlushRawIO, pyio.RawIOBase): + pass + + +class CloseFailureIO(MockRawIO): + closed = 0 + + def close(self): + if not self.closed: + self.closed = 1 + raise OSError + +class CCloseFailureIO(CloseFailureIO, io.RawIOBase): + pass + +class PyCloseFailureIO(CloseFailureIO, pyio.RawIOBase): + pass + + +class MockFileIO: + + def __init__(self, data): + self.read_history = [] + super().__init__(data) + + def read(self, n=None): + res = super().read(n) + self.read_history.append(None if res is None else len(res)) + return res + + def readinto(self, b): + res = super().readinto(b) + self.read_history.append(res) + return res + +class CMockFileIO(MockFileIO, io.BytesIO): + pass + +class PyMockFileIO(MockFileIO, pyio.BytesIO): + pass + + +class MockUnseekableIO: + def seekable(self): + return False + + def seek(self, *args): + raise self.UnsupportedOperation("not seekable") + + def tell(self, *args): + raise self.UnsupportedOperation("not seekable") + + def truncate(self, *args): + raise self.UnsupportedOperation("not seekable") + +class CMockUnseekableIO(MockUnseekableIO, io.BytesIO): + UnsupportedOperation = io.UnsupportedOperation + +class PyMockUnseekableIO(MockUnseekableIO, pyio.BytesIO): + UnsupportedOperation = pyio.UnsupportedOperation + + +class MockCharPseudoDevFileIO(MockFileIO): + # GH-95782 + # ftruncate() does not work on these special files (and CPython then raises + # appropriate exceptions), so truncate() does not have to be accounted for + # here. + def __init__(self, data): + super().__init__(data) + + def seek(self, *args): + return 0 + + def tell(self, *args): + return 0 + +class CMockCharPseudoDevFileIO(MockCharPseudoDevFileIO, io.BytesIO): + pass + +class PyMockCharPseudoDevFileIO(MockCharPseudoDevFileIO, pyio.BytesIO): + pass + + +class MockNonBlockWriterIO: + + def __init__(self): + self._write_stack = [] + self._blocker_char = None + + def pop_written(self): + s = b"".join(self._write_stack) + self._write_stack[:] = [] + return s + + def block_on(self, char): + """Block when a given char is encountered.""" + self._blocker_char = char + + def readable(self): + return True + + def seekable(self): + return True + + def seek(self, pos, whence=0): + # naive implementation, enough for tests + return 0 + + def writable(self): + return True + + def write(self, b): + b = bytes(b) + n = -1 + if self._blocker_char: + try: + n = b.index(self._blocker_char) + except ValueError: + pass + else: + if n > 0: + # write data up to the first blocker + self._write_stack.append(b[:n]) + return n + else: + # cancel blocker and indicate would block + self._blocker_char = None + return None + self._write_stack.append(b) + return len(b) + +class CMockNonBlockWriterIO(MockNonBlockWriterIO, io.RawIOBase): + BlockingIOError = io.BlockingIOError + +class PyMockNonBlockWriterIO(MockNonBlockWriterIO, pyio.RawIOBase): + BlockingIOError = pyio.BlockingIOError + + +# Build classes which point to all the right mocks per io implementation +class CTestCase(unittest.TestCase): + io = io + is_C = True + + MockRawIO = CMockRawIO + MisbehavedRawIO = CMisbehavedRawIO + MockFileIO = CMockFileIO + CloseFailureIO = CCloseFailureIO + MockNonBlockWriterIO = CMockNonBlockWriterIO + MockUnseekableIO = CMockUnseekableIO + MockRawIOWithoutRead = CMockRawIOWithoutRead + SlowFlushRawIO = CSlowFlushRawIO + MockCharPseudoDevFileIO = CMockCharPseudoDevFileIO + + # Use the class as a proxy to the io module members. + def __getattr__(self, name): + return getattr(io, name) + + +class PyTestCase(unittest.TestCase): + io = pyio + is_C = False + + MockRawIO = PyMockRawIO + MisbehavedRawIO = PyMisbehavedRawIO + MockFileIO = PyMockFileIO + CloseFailureIO = PyCloseFailureIO + MockNonBlockWriterIO = PyMockNonBlockWriterIO + MockUnseekableIO = PyMockUnseekableIO + MockRawIOWithoutRead = PyMockRawIOWithoutRead + SlowFlushRawIO = PySlowFlushRawIO + MockCharPseudoDevFileIO = PyMockCharPseudoDevFileIO + + # Use the class as a proxy to the _pyio module members. + def __getattr__(self, name): + return getattr(pyio, name) diff --git a/Lib/test/test_ioctl.py b/Lib/test/test_ioctl.py index 01e1bfb42dd..277d2fc99ea 100644 --- a/Lib/test/test_ioctl.py +++ b/Lib/test/test_ioctl.py @@ -127,9 +127,8 @@ def test_ioctl_mutate_1024(self): self._check_ioctl_not_mutate_len(1024) def test_ioctl_mutate_2048(self): - # Test with a larger buffer, just for the record. self._check_ioctl_mutate_len(2048) - self.assertRaises(ValueError, self._check_ioctl_not_mutate_len, 2048) + self._check_ioctl_not_mutate_len(1024) @unittest.skipUnless(hasattr(os, 'openpty'), "need os.openpty()") @@ -209,7 +208,9 @@ def test_bad_fd(self): with self.assertRaises(OSError): fcntl.ioctl(fd, fcntl.FICLONE, fd) with self.assertRaises(OSError): - fcntl.ioctl(fd, fcntl.FICLONE, b'\0' * 1024) + fcntl.ioctl(fd, fcntl.FICLONE, b'\0' * 10) + with self.assertRaises(OSError): + fcntl.ioctl(fd, fcntl.FICLONE, b'\0' * 2048) if __name__ == "__main__": diff --git a/Lib/test/test_ipaddress.py b/Lib/test/test_ipaddress.py index 8af91e857d8..8cb1e654973 100644 --- a/Lib/test/test_ipaddress.py +++ b/Lib/test/test_ipaddress.py @@ -2303,6 +2303,10 @@ def testReservedIpv4(self): self.assertEqual(False, ipaddress.ip_network('240.0.0.0').is_multicast) self.assertEqual(True, ipaddress.ip_network('240.0.0.0').is_reserved) + self.assertTrue(ipaddress.ip_interface('0.0.0.0/32').is_unspecified) + self.assertFalse(ipaddress.ip_interface('0.0.0.0/31').is_unspecified) + self.assertFalse(ipaddress.ip_interface('1.2.3.4/32').is_unspecified) + self.assertEqual(True, ipaddress.ip_interface( '192.168.1.1/17').is_private) self.assertEqual(False, ipaddress.ip_network('192.169.0.0').is_private) @@ -2673,6 +2677,12 @@ def testExplodeShortHandIpStr(self): addr1.exploded) self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001/128', ipaddress.IPv6Interface('::1/128').exploded) + self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0001%1', + ipaddress.IPv6Address('fe80::1%1').exploded) + self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0001%eth0', + ipaddress.IPv6Address('fe80::1%eth0').exploded) + self.assertEqual('fe80:0000:0000:0000:0000:0000:0000:0001%1/64', + ipaddress.IPv6Interface('fe80::1%1/64').exploded) # issue 77 self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1', addr2.exploded) @@ -2851,5 +2861,15 @@ def testNetworkV6HashCollisions(self): ) +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(ipaddress, "__version__") + self.assertEqual(cm.filename, __file__) + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_json/__init__.py b/Lib/test/test_json/__init__.py index f43bded1a54..e58fbee41af 100644 --- a/Lib/test/test_json/__init__.py +++ b/Lib/test/test_json/__init__.py @@ -8,9 +8,7 @@ # import json with and without accelerations -# XXX RUSTPYTHON: we don't import _json as fresh since the fresh module isn't placed -# into the sys.modules cache, and therefore the vm can't recognize the _json.Scanner class -cjson = import_helper.import_fresh_module('json') #, fresh=['_json']) +cjson = import_helper.import_fresh_module('json', fresh=['_json']) pyjson = import_helper.import_fresh_module('json', blocked=['_json']) # JSONDecodeError is cached inside the _json module cjson.JSONDecodeError = cjson.decoder.JSONDecodeError = json.JSONDecodeError @@ -49,6 +47,16 @@ def test_cjson(self): '_json') +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(json, "__version__") + self.assertEqual(cm.filename, __file__) + + def load_tests(loader, _, pattern): suite = unittest.TestSuite() for mod in (json, json.encoder, json.decoder): diff --git a/Lib/test/test_json/test_decode.py b/Lib/test/test_json/test_decode.py index 6d6ca11f673..13938ed3316 100644 --- a/Lib/test/test_json/test_decode.py +++ b/Lib/test/test_json/test_decode.py @@ -1,4 +1,5 @@ import decimal +import unittest.mock from io import StringIO from collections import OrderedDict from test.test_json import PyTest, CTest @@ -49,6 +50,26 @@ def test_empty_objects(self): self.assertEqual(self.loads('[]'), []) self.assertEqual(self.loads('""'), "") + def test_object_hook(self): + s = '{"a":{"b":{}}}' + + expected_result = {"a":{"b":{"x":1}, "x":1}, "x":1} + expected_hook_arguments = [ + {}, {"b": {"x":1}}, {"a": {"b": {"x":1}, "x":1}} + ] + + hook_arguments = [] + + def hook(x): + hook_arguments.append(x) + return {**x, "x":1} + + result = self.loads(s, object_hook=hook) + + self.assertEqual(result, expected_result) + self.assertEqual(hook_arguments, expected_hook_arguments) + + def test_object_pairs_hook(self): s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4), @@ -71,6 +92,31 @@ def test_object_pairs_hook(self): object_pairs_hook=OrderedDict), OrderedDict([('empty', OrderedDict())])) + def test_array_hook(self): + s = '[1, 2, 3]' + t = self.loads(s, array_hook=tuple) + self.assertEqual(t, (1, 2, 3)) + self.assertEqual(type(t), tuple) + + # Nested array in inner structure with object_hook + s = '{"xkd": [[1], [2], [3]]}' + p = frozendict(xkd=((1,), (2,), (3,))) + data = self.loads(s, object_hook=frozendict, array_hook=tuple) + self.assertEqual(data, p) + self.assertEqual(type(data), frozendict) + self.assertEqual(type(data["xkd"]), tuple) + for item in data["xkd"]: + self.assertEqual(type(item), tuple) + + self.assertEqual(self.loads('[]', array_hook=tuple), ()) + + def test_load_array_hook(self): + # json.load must forward array_hook to loads + fp = StringIO('[10, 20, 30]') + result = self.json.load(fp, array_hook=tuple) + self.assertEqual(result, (10, 20, 30)) + self.assertEqual(type(result), tuple) + def test_decoder_optimizations(self): # Several optimizations were made that skip over calls to # the whitespace regex, so this test is designed to try and @@ -125,6 +171,10 @@ def test_negative_index(self): d = self.json.JSONDecoder() self.assertRaises(ValueError, d.raw_decode, 'a'*42, -50000) + def test_unterminated_string(self): + d = self.json.JSONDecoder() + self.assertRaises(self.JSONDecodeError, d.raw_decode, '"\\') + def test_limit_int(self): maxdigits = 5000 with support.adjust_int_max_str_digits(maxdigits): @@ -132,9 +182,20 @@ def test_limit_int(self): with self.assertRaises(ValueError): self.loads('1' * (maxdigits + 1)) + def test_explicit_cls_skips_json_decoder_default(self): + class CustomDecoder: + pass + + with unittest.mock.patch.object( + CustomDecoder, 'decode', create=True) as mock_decode: + self.loads('{}', cls=CustomDecoder) + mock_decode.assert_called_once() + class TestPyDecode(TestDecode, PyTest): pass class TestCDecode(TestDecode, CTest): + pass + @unittest.expectedFailure # TODO: RUSTPYTHON def test_limit_int(self): return super().test_limit_int() diff --git a/Lib/test/test_json/test_dump.py b/Lib/test/test_json/test_dump.py index 39470754003..5bc03085e60 100644 --- a/Lib/test/test_json/test_dump.py +++ b/Lib/test/test_json/test_dump.py @@ -12,6 +12,18 @@ def test_dump(self): def test_dumps(self): self.assertEqual(self.dumps({}), '{}') + def test_dumps_dict(self): + self.assertEqual(self.dumps({'x': 1, 'y': 2}), + '{"x": 1, "y": 2}') + self.assertEqual(self.dumps(frozendict({'x': 1, 'y': 2})), + '{"x": 1, "y": 2}') + lst = [{'x': 1}, frozendict(y=2)] + self.assertEqual(self.dumps(lst), + '[{"x": 1}, {"y": 2}]') + data = {'x': dict(a=1), 'y': frozendict(b=2)} + self.assertEqual(self.dumps(data), + '{"x": {"a": 1}, "y": {"b": 2}}') + def test_dump_skipkeys(self): v = {b'invalid_key': False, 'valid_key': True} with self.assertRaises(TypeError): @@ -65,6 +77,59 @@ def __lt__(self, o): d[1337] = "true.dat" self.assertEqual(self.dumps(d, sort_keys=True), '{"1337": "true.dat"}') + # gh-145244: UAF on borrowed key when default callback mutates dict + def test_default_clears_dict_key_uaf(self): + class Evil: + pass + + class AlsoEvil: + pass + + # Use a non-interned string key so it can actually be freed + key = "A" * 100 + target = {key: Evil()} + del key + + def evil_default(obj): + if isinstance(obj, Evil): + target.clear() + return AlsoEvil() + raise TypeError("not serializable") + + with self.assertRaises(TypeError): + self.json.dumps(target, default=evil_default, + check_circular=False) + + def test_dumps_str_subclass(self): + # Don't call obj.__str__() on str subclasses + + # str subclass which returns a different string on str(obj) + class StrSubclass(str): + def __str__(self): + return "StrSubclass" + + obj = StrSubclass('ascii') + self.assertEqual(self.dumps(obj), '"ascii"') + self.assertEqual(self.dumps([obj]), '["ascii"]') + self.assertEqual(self.dumps({'key': obj}), '{"key": "ascii"}') + + obj = StrSubclass('escape\n') + self.assertEqual(self.dumps(obj), '"escape\\n"') + self.assertEqual(self.dumps([obj]), '["escape\\n"]') + self.assertEqual(self.dumps({'key': obj}), '{"key": "escape\\n"}') + + obj = StrSubclass('nonascii:é') + self.assertEqual(self.dumps(obj, ensure_ascii=False), + '"nonascii:é"') + self.assertEqual(self.dumps([obj], ensure_ascii=False), + '["nonascii:é"]') + self.assertEqual(self.dumps({'key': obj}, ensure_ascii=False), + '{"key": "nonascii:é"}') + self.assertEqual(self.dumps(obj), '"nonascii:\\u00e9"') + self.assertEqual(self.dumps([obj]), '["nonascii:\\u00e9"]') + self.assertEqual(self.dumps({'key': obj}), + '{"key": "nonascii:\\u00e9"}') + class TestPyDump(TestDump, PyTest): pass diff --git a/Lib/test/test_json/test_encode_basestring_ascii.py b/Lib/test/test_json/test_encode_basestring_ascii.py index c90d3e968e5..1b5dfcfde01 100644 --- a/Lib/test/test_json/test_encode_basestring_ascii.py +++ b/Lib/test/test_json/test_encode_basestring_ascii.py @@ -3,6 +3,11 @@ from test.support import bigaddrspacetest +# str subclass which returns a different string on str(obj) +class StrSubclass(str): + def __str__(self): + return "StrSubclass" + CASES = [ ('/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'), ('\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'), @@ -14,6 +19,8 @@ ('\U0001d120', '"\\ud834\\udd20"'), ('\u03b1\u03a9', '"\\u03b1\\u03a9"'), ("`1~!@#$%^&*()_+-={':[,]}|;.?", '"`1~!@#$%^&*()_+-={\':[,]}|;.?"'), + # Don't call obj.__str__() on str subclasses + (StrSubclass('ascii'), '"ascii"'), ] class TestEncodeBasestringAscii: diff --git a/Lib/test/test_json/test_enum.py b/Lib/test/test_json/test_enum.py index 10f414898b8..518c3e11200 100644 --- a/Lib/test/test_json/test_enum.py +++ b/Lib/test/test_json/test_enum.py @@ -26,11 +26,14 @@ class FloatNum(float, Enum): NEG_INF = float('-inf') NAN = float('nan') -class WierdNum(float, Enum): +class WeirdNum(float, Enum): inf = INF neg_inf = NEG_INF nan = NAN +class StringEnum(str, Enum): + COLOR = "color" + class TestEnum: def test_floats(self): @@ -40,7 +43,7 @@ def test_floats(self): self.assertEqual(self.loads(self.dumps(enum)), enum) def test_weird_floats(self): - for enum, expected in zip(WierdNum, ('Infinity', '-Infinity', 'NaN')): + for enum, expected in zip(WeirdNum, ('Infinity', '-Infinity', 'NaN')): self.assertEqual(self.dumps(enum), expected) if not isnan(enum): self.assertEqual(float(self.dumps(enum)), enum) @@ -64,16 +67,16 @@ def test_list(self): str([E, PI, TAU])) self.assertEqual(self.loads(self.dumps(list(FloatNum))), list(FloatNum)) - self.assertEqual(self.dumps(list(WierdNum)), + self.assertEqual(self.dumps(list(WeirdNum)), '[Infinity, -Infinity, NaN]') - self.assertEqual(self.loads(self.dumps(list(WierdNum)))[:2], - list(WierdNum)[:2]) - self.assertTrue(isnan(self.loads(self.dumps(list(WierdNum)))[2])) + self.assertEqual(self.loads(self.dumps(list(WeirdNum)))[:2], + list(WeirdNum)[:2]) + self.assertTrue(isnan(self.loads(self.dumps(list(WeirdNum)))[2])) def test_dict_keys(self): s, b, h, r = BigNum e, p, t = FloatNum - i, j, n = WierdNum + i, j, n = WeirdNum d = { s:'tiny', b:'large', h:'larger', r:'largest', e:"Euler's number", p:'pi', t:'tau', @@ -100,9 +103,9 @@ def test_dict_values(self): e=FloatNum.e, pi=FloatNum.pi, tau=FloatNum.tau, - i=WierdNum.inf, - j=WierdNum.neg_inf, - n=WierdNum.nan, + i=WeirdNum.inf, + j=WeirdNum.neg_inf, + n=WeirdNum.nan, ) nd = self.loads(self.dumps(d)) self.assertEqual(nd['tiny'], SMALL) @@ -116,5 +119,11 @@ def test_dict_values(self): self.assertEqual(nd['j'], NEG_INF) self.assertTrue(isnan(nd['n'])) + def test_str_enum(self): + obj = StringEnum.COLOR + self.assertEqual(self.dumps(obj), '"color"') + self.assertEqual(self.dumps([obj]), '["color"]') + self.assertEqual(self.dumps({'key': obj}), '{"key": "color"}') + class TestPyEnum(TestEnum, PyTest): pass class TestCEnum(TestEnum, CTest): pass diff --git a/Lib/test/test_json/test_fail.py b/Lib/test/test_json/test_fail.py index eec64b528cf..7f99a6331d3 100644 --- a/Lib/test/test_json/test_fail.py +++ b/Lib/test/test_json/test_fail.py @@ -1,7 +1,5 @@ from test.test_json import PyTest, CTest -import unittest # XXX: RUSTPYTHON; importing to be able to skip tests - # 2007-10-05 JSONDOCS = [ # https://json.org/JSON_checker/test/fail1.json @@ -146,6 +144,13 @@ def test_truncated_input(self): ('"', 'Unterminated string starting at', 0), ('"spam', 'Unterminated string starting at', 0), ] + # A complete \uXXXX escape at end of input leaves it unterminated. + test_cases += [ + (r'"\u0041', 'Unterminated string starting at', 0), + (r'"\ud834', 'Unterminated string starting at', 0), + (r'"\ud834\udd1e', 'Unterminated string starting at', 0), + (r'{"a": "\u0041', 'Unterminated string starting at', 6), + ] for data, msg, idx in test_cases: with self.assertRaises(self.JSONDecodeError) as cm: self.loads(data) diff --git a/Lib/test/test_json/test_pickleable.py b/Lib/test/test_json/test_pickleable.py new file mode 100644 index 00000000000..517cfcdd41a --- /dev/null +++ b/Lib/test/test_json/test_pickleable.py @@ -0,0 +1,14 @@ +import json +import pickle +import unittest + +class TestPickleable(unittest.TestCase): + def test_json_decode_error_is_pickleable(self): + e = json.JSONDecodeError(msg="abc", doc="def", pos=7) + + pickled = pickle.dumps(e) + unpickled = pickle.loads(pickled) + + self.assertEqual(unpickled.msg, e.msg) + self.assertEqual(unpickled.doc, e.doc) + self.assertEqual(unpickled.pos, e.pos) diff --git a/Lib/test/test_json/test_recursion.py b/Lib/test/test_json/test_recursion.py index fb8de9447e7..ce1a54fe6c3 100644 --- a/Lib/test/test_json/test_recursion.py +++ b/Lib/test/test_json/test_recursion.py @@ -70,7 +70,8 @@ def default(self, o): self.fail("didn't raise ValueError on default recursion") - @support.skip_if_unlimited_stack_size + @support.skip_if_pgo_task # fails during PGO training w/ some stack sizes + @support.run_with_limited_c_stack(500_000) @support.skip_emscripten_stack_overflow() @support.skip_wasi_stack_overflow() def test_highly_nested_objects_decoding(self): @@ -92,22 +93,35 @@ def test_highly_nested_objects_decoding(self): @support.skip_emscripten_stack_overflow() @support.requires_resource('cpu') def test_highly_nested_objects_encoding(self): - # See #12051 + # See issue gh-56260 + + # With max_depth=2_000 on Linux, the Python implementation takes around + # 2 seconds to raise RecursionError, whereas the C implementation only + # takes around 160 ms. + max_depth = 2_000 l, d = [], {} - for x in range(500_000): + for x in range(max_depth * 10): l, d = [l], {'k':d} - with self.assertRaises(RecursionError): - with support.infinite_recursion(5000): + + # Don't use assertRaises(RecursionError): on FreeBSD 16 with a default + # stack size of 512 MiB, the C implementation doesn't raise + # RecursionError. + try: + with support.infinite_recursion(max_depth): self.dumps(l) - with self.assertRaises(RecursionError): - with support.infinite_recursion(5000): + except RecursionError: + pass + try: + with support.infinite_recursion(max_depth): self.dumps(d) + except RecursionError: + pass - @support.skip_if_unlimited_stack_size + @support.skip_if_huge_c_stack() @support.skip_emscripten_stack_overflow() @support.skip_wasi_stack_overflow() def test_endless_recursion(self): - # See #12051 + # See issue gh-56260 class EndlessJSONEncoder(self.json.JSONEncoder): def default(self, o): """If check_circular is False, this will keep adding another list.""" diff --git a/Lib/test/test_json/test_scanstring.py b/Lib/test/test_json/test_scanstring.py index e77ec152280..a52b01c7113 100644 --- a/Lib/test/test_json/test_scanstring.py +++ b/Lib/test/test_json/test_scanstring.py @@ -1,8 +1,6 @@ import sys from test.test_json import PyTest, CTest -import unittest # XXX: RUSTPYTHON; importing to be able to skip tests - class TestScanstring: def test_scanstring(self): @@ -139,12 +137,14 @@ def test_bad_escapes(self): '"\\ud834\\u-123"', '"\\ud834\\u+123"', '"\\ud834\\u1_23"', + # Truncated or non-hex \uXXXX escape at end of input. + '"\\u004', + '"\\uXYZW', ] for s in bad_escapes: with self.assertRaises(self.JSONDecodeError, msg=s): scanstring(s, 1, True) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_overflow(self): with self.assertRaises(OverflowError): self.json.decoder.scanstring("xxx", sys.maxsize+1) diff --git a/Lib/test/test_json/test_speedups.py b/Lib/test/test_json/test_speedups.py index afe3af440e1..0b22a0bf4b9 100644 --- a/Lib/test/test_json/test_speedups.py +++ b/Lib/test/test_json/test_speedups.py @@ -1,8 +1,6 @@ from test.test_json import CTest from test.support import gc_collect -import unittest # XXX: RUSTPYTHON; importing to be able to skip tests - class BadBool: def __bool__(self): @@ -84,7 +82,6 @@ def test_unsortable_keys(self): with self.assertRaises(TypeError): self.json.encoder.JSONEncoder(sort_keys=True).encode({'a': 1, 1: 'a'}) - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: 'NoneType' object is not callable def test_current_indent_level(self): enc = self.json.encoder.c_make_encoder( markers=None, diff --git a/Lib/test/test_json/test_unicode.py b/Lib/test/test_json/test_unicode.py index 1aa9546dc46..291580cb047 100644 --- a/Lib/test/test_json/test_unicode.py +++ b/Lib/test/test_json/test_unicode.py @@ -44,7 +44,13 @@ def test_ascii_non_printable_decode(self): '\b\t\n\f\r') s = ''.join(map(chr, range(32))) for c in s: - self.assertRaises(self.JSONDecodeError, self.loads, f'"{c}"') + with self.subTest(control_character=ord(c)): + with self.assertRaises(self.JSONDecodeError) as cm: + self.loads(f'"a{c}b"') + error = cm.exception + self.assertEqual(error.pos, 2) + self.assertEqual(error.lineno, 1) + self.assertEqual(error.colno, 3) self.assertEqual(self.loads(f'"{s}"', strict=False), s) self.assertEqual(self.loads('"\x7f"'), '\x7f') diff --git a/Lib/test/test_kqueue.py b/Lib/test/test_kqueue.py index e94edcbc107..2649f3a7aee 100644 --- a/Lib/test/test_kqueue.py +++ b/Lib/test/test_kqueue.py @@ -9,6 +9,8 @@ import time import unittest +from test.support import warnings_helper + if not hasattr(select, "kqueue"): raise unittest.SkipTest("test works only on BSD") @@ -21,6 +23,20 @@ def test_create_queue(self): self.assertTrue(kq.closed) self.assertRaises(ValueError, kq.fileno) + def test_control_overflowing_timeout(self): + # gh-154836: out-of-range timeouts must raise OverflowError, + # not a (misleading) TypeError, like select(), poll() and + # epoll() do. + kq = select.kqueue() + self.addCleanup(kq.close) + for timeout in (1e300, float('inf'), 2**200): + with self.subTest(timeout=timeout): + with self.assertRaises(OverflowError): + kq.control(None, 0, timeout) + # Non-numbers still raise TypeError. + with self.assertRaises(TypeError): + kq.control(None, 0, "0.1") + def test_create_event(self): from operator import lt, le, gt, ge @@ -252,11 +268,21 @@ def test_close(self): # operations must fail with ValueError("I/O operation on closed ...") self.assertRaises(ValueError, kqueue.control, None, 4) + def test_close_error(self): + # gh-146205: close() should raise OSError if underlying fd is invalid + kqueue = select.kqueue() + fd = kqueue.fileno() + os.close(fd) + with self.assertRaises(OSError) as cm: + kqueue.close() + self.assertEqual(cm.exception.errno, errno.EBADF) + def test_fd_non_inheritable(self): kqueue = select.kqueue() self.addCleanup(kqueue.close) self.assertEqual(os.get_inheritable(kqueue.fileno()), False) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.requires_fork() def test_fork(self): # gh-110395: kqueue objects must be closed after fork diff --git a/Lib/test/test_launcher.py b/Lib/test/test_launcher.py index caa1603c78e..795890bd7e4 100644 --- a/Lib/test/test_launcher.py +++ b/Lib/test/test_launcher.py @@ -227,6 +227,8 @@ def run_py(self, args, env=None, allow_fail=False, expect_returncode=0, argv=Non "PYLAUNCHER_LIMIT_TO_COMPANY": "", **{k.upper(): v for k, v in (env or {}).items()}, } + if ini_dir := getattr(self, '_ini_dir', None): + env.setdefault("_PYLAUNCHER_INIDIR", ini_dir) if not argv: argv = [self.py_exe, *args] with subprocess.Popen( @@ -262,11 +264,14 @@ def run_py(self, args, env=None, allow_fail=False, expect_returncode=0, argv=Non return data def py_ini(self, content): - local_appdata = os.environ.get("LOCALAPPDATA") - if not local_appdata: - raise unittest.SkipTest("LOCALAPPDATA environment variable is " - "missing or empty") - return PreservePyIni(Path(local_appdata) / "py.ini", content) + ini_dir = getattr(self, '_ini_dir', None) + if not ini_dir: + local_appdata = os.environ.get("LOCALAPPDATA") + if not local_appdata: + raise unittest.SkipTest("LOCALAPPDATA environment variable is " + "missing or empty") + ini_dir = local_appdata + return PreservePyIni(Path(ini_dir) / "py.ini", content) @contextlib.contextmanager def script(self, content, encoding="utf-8"): @@ -302,6 +307,8 @@ def setUpClass(cls): p = subprocess.check_output("reg query HKCU\\Software\\Python /s") #print(p.decode('mbcs')) + cls._ini_dir = tempfile.mkdtemp() + cls.addClassCleanup(shutil.rmtree, cls._ini_dir, ignore_errors=True) @classmethod def tearDownClass(cls): @@ -462,6 +469,7 @@ def test_search_major_2(self): except subprocess.CalledProcessError: if not is_installed("2.7"): raise unittest.SkipTest("requires at least one Python 2.x install") + raise self.assertEqual("PythonCore", data["env.company"]) self.assertStartsWith(data["env.tag"], "2.") diff --git a/Lib/test/test_lazy_import/__init__.py b/Lib/test/test_lazy_import/__init__.py new file mode 100644 index 00000000000..f805a83820f --- /dev/null +++ b/Lib/test/test_lazy_import/__init__.py @@ -0,0 +1,2839 @@ +"""Tests for PEP 810 lazy imports.""" + +import io +import dis +import subprocess +import sys +import textwrap +import threading +import types +import unittest +import tempfile +import os +import contextlib + +from test import support +from test.support.script_helper import assert_python_ok, assert_python_failure + +try: + import _testcapi +except ImportError: + _testcapi = None + + +class LazyImportTestCase(unittest.TestCase): + def setUp(self): + self.lazy_imports_filter = sys.get_lazy_imports_filter() + self.lazy_imports = sys.get_lazy_imports() + + def tearDown(self): + """Clean up any test modules from sys.modules.""" + for key in list(sys.modules.keys()): + if key.startswith('test.test_lazy_import.data'): + del sys.modules[key] + + sys.set_lazy_imports_filter(self.lazy_imports_filter) + sys.set_lazy_imports(self.lazy_imports) + sys.lazy_modules.clear() + + +class LazyImportTests(LazyImportTestCase): + """Tests for basic lazy import functionality.""" + + def test_basic_unused(self): + """Lazy imported module should not be loaded if never accessed.""" + import test.test_lazy_import.data.basic_unused + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + self.assertIn("test.test_lazy_import.data.basic2", sys.lazy_modules) + + def test_sys_lazy_modules(self): + try: + import test.test_lazy_import.data.basic_from_unused + except ImportError as e: + self.fail('lazy import failed') + + self.assertFalse("test.test_lazy_import.data.basic2" in sys.modules) + # The package is already loaded, so it is not a pending import. + self.assertNotIn("test.test_lazy_import.data", sys.lazy_modules) + self.assertIn("test.test_lazy_import.data.basic2", sys.lazy_modules) + test.test_lazy_import.data.basic_from_unused.basic2 + self.assertNotIn("test.test_import.data", sys.lazy_modules) + + def test_basic_unused_use_externally(self): + """Lazy import should load module when accessed from outside.""" + from test.test_lazy_import.data import basic_unused + + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + x = basic_unused.test.test_lazy_import.data.basic2 + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_basic_from_unused_use_externally(self): + """Lazy 'from' import should load when accessed from outside.""" + from test.test_lazy_import.data import basic_from_unused + + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + x = basic_from_unused.basic2 + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_basic_unused_dir(self): + """dir() on module should not trigger lazy import reification.""" + import test.test_lazy_import.data.basic_unused + + x = dir(test.test_lazy_import.data.basic_unused) + self.assertIn("test", x) + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_basic_dir(self): + """dir() at module scope should not trigger lazy import reification.""" + from test.test_lazy_import.data import basic_dir + + self.assertIn("test", basic_dir.x) + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_basic_used(self): + """Lazy import should load when accessed within the module.""" + import test.test_lazy_import.data.basic_used + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + @support.requires_subprocess() + def test_from_import_with_module_getattr(self): + """Lazy from import should respect module-level __getattr__.""" + code = textwrap.dedent(""" + lazy from test.test_lazy_import.data.module_with_getattr import dynamic_attr + assert dynamic_attr == "from_getattr" + """) + assert_python_ok("-c", code) + + @support.requires_subprocess() + def test_from_import_with_module_getattr_raising(self): + """Lazy from import should respect module-level __getattr__.""" + code = textwrap.dedent(""" + lazy from test.test_lazy_import.data.module_with_getattr import raising_attr + + try: + raising_attr + except ValueError as exc: + assert str(exc) == 'from_getattr', exc + else: + assert False, f'ValueError is not raised: {raising_attr}' + """) + assert_python_ok("-c", code) + + @support.requires_subprocess() + def test_from_import_with_module_getattr_missing(self): + """Lazy from import should respect module-level __getattr__.""" + for attr in ("missing_attr", "import_error_attr"): + with self.subTest(attr=attr): + code = textwrap.dedent(f""" + lazy from test.test_lazy_import.data.module_with_getattr import {attr} + + try: + {attr} + except ImportError as exc: + assert '{attr}' in str(exc), exc + assert exc.__cause__ is not None + else: + assert False, ('ImportError is not raised', {attr}) + """) + assert_python_ok("-c", code) + + @support.requires_subprocess() + def test_from_import_with_module_getattr_warning(self): + """Lazy from import should respect module-level __getattr__.""" + code = textwrap.dedent(""" + import warnings + + with warnings.catch_warnings(record=True) as log: + lazy from test.test_lazy_import.data.module_with_getattr import warning_attr + + assert log == [] + + with warnings.catch_warnings(record=True) as log: + warning_attr + assert warning_attr == 'from_warning_attr', warning_attr + assert len(log) == 1, log + assert isinstance(log[0].message, UserWarning), log + assert str(log[0].message) == 'from_getattr', log + """) + assert_python_ok("-c", code) + + @support.requires_subprocess() + def test_from_import_with_imported_module_getattr(self): + """Lazy from import should not shadow an imported module's __getattr__.""" + code = textwrap.dedent(""" + import test.test_lazy_import.data.module_with_getattr as mod + lazy from test.test_lazy_import.data.module_with_getattr import dynamic_attr + assert dynamic_attr == "from_getattr" + assert mod.dynamic_attr == "from_getattr" + """) + assert_python_ok("-c", code) + + @support.requires_subprocess() + def test_module_getattr_does_not_shadow_own_lazy_import(self): + """Module __getattr__ should not shadow the module's own lazy imports.""" + code = textwrap.dedent(""" + import types + import test.test_lazy_import.data.module_with_lazy_import_and_getattr as mod + assert mod.basic2.__name__ == "test.test_lazy_import.data.basic2" + assert mod.f is mod.basic2.f + assert not isinstance(vars(mod)["basic2"], types.LazyImportType) + assert mod.missing == "from_getattr:missing" + """) + assert_python_ok("-c", code) + + +class GlobalLazyImportModeTests(LazyImportTestCase): + """Tests for sys.set_lazy_imports() global mode control.""" + + def tearDown(self): + for key in list(sys.modules.keys()): + if key.startswith('test.test_lazy_import.data'): + del sys.modules[key] + + sys.set_lazy_imports_filter(None) + sys.set_lazy_imports("normal") + + def test_global_off_rejected(self): + """Mode 'none' is not supported.""" + with self.assertRaises(ValueError): + sys.set_lazy_imports("none") + + def test_global_on(self): + """Mode 'all' should make regular imports lazy.""" + import test.test_lazy_import.data.global_on + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_global_filter(self): + """Filter returning False should prevent lazy loading.""" + import test.test_lazy_import.data.global_filter + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_global_filter_true(self): + """Filter returning True should allow lazy loading.""" + import test.test_lazy_import.data.global_filter_true + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_global_filter_from(self): + """Filter should work with 'from' imports.""" + import test.test_lazy_import.data.global_filter_from + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_global_filter_from_true(self): + """Filter returning True should allow lazy 'from' imports.""" + import test.test_lazy_import.data.global_filter_from_true + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + +class CompatibilityModeTests(LazyImportTestCase): + """Tests for __lazy_modules__ compatibility mode.""" + + def test_compatibility_mode(self): + """__lazy_modules__ should enable lazy imports for listed modules.""" + import test.test_lazy_import.data.basic_compatibility_mode + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_compatibility_mode_used(self): + """Using a lazy import from __lazy_modules__ should load the module.""" + import test.test_lazy_import.data.basic_compatibility_mode_used + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_compatibility_mode_func(self): + """Imports inside functions should be eager even in compatibility mode.""" + import test.test_lazy_import.data.compatibility_mode_func + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_compatibility_mode_try_except(self): + """Imports in try/except should be eager even in compatibility mode.""" + import test.test_lazy_import.data.compatibility_mode_try_except + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_compatibility_mode_relative(self): + """__lazy_modules__ should work with relative imports.""" + import test.test_lazy_import.data.basic_compatibility_mode_relative + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + +class ModuleIntrospectionTests(LazyImportTestCase): + """Tests for module dict and getattr behavior with lazy imports.""" + + def test_modules_dict(self): + """Accessing module.__dict__ should not trigger reification.""" + import test.test_lazy_import.data.modules_dict + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_modules_getattr(self): + """Module __getattr__ for lazy import name should trigger reification.""" + import test.test_lazy_import.data.modules_getattr + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_modules_getattr_other(self): + """Module __getattr__ for other names should not trigger reification.""" + import test.test_lazy_import.data.modules_getattr_other + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + +class LazyImportTypeTests(LazyImportTestCase): + """Tests for the LazyImportType and its resolve() method.""" + + def test_lazy_value_resolve(self): + """resolve() method should force the lazy import to load.""" + import test.test_lazy_import.data.lazy_get_value + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_lazy_import_type_exposed(self): + """LazyImportType should be exposed in types module.""" + self.assertHasAttr(types, 'LazyImportType') + self.assertEqual(types.LazyImportType.__name__, 'lazy_import') + + def test_lazy_import_type_cant_construct(self): + """LazyImportType should not be directly constructible.""" + self.assertRaises(TypeError, types.LazyImportType, {}, "module") + + @support.requires_subprocess() + def test_lazy_import_type_attributes_accessible(self): + """Check that static PyLazyImport_Type is initialized at startup.""" + code = textwrap.dedent(""" + lazy import json + print(globals()["json"].resolve) + """) + proc = assert_python_ok("-c", code) + self.assertIn(b" initial_count + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + +@support.requires_subprocess() +class ErrorHandlingTests(LazyImportTestCase): + """Tests for error handling during lazy import reification.""" + + def test_missing_lazy_submodule_raises_module_not_found_error(self): + """Accessing a nonexistent lazy submodule via parent attr raises ModuleNotFoundError.""" + code = textwrap.dedent(""" + lazy import test.test_lazy_import.data.nonexistent_module + + try: + _ = test.test_lazy_import.data.nonexistent_module + except ModuleNotFoundError: + pass + else: + raise AssertionError("ModuleNotFoundError was not raised") + """) + assert_python_ok("-c", code) + + def test_non_package_lazily_imported(self): + """Accessing a nonexistent lazy name via parent attr raises ModuleNotFoundError.""" + code = textwrap.dedent(""" + lazy import math.pi + + try: + _ = math.pi + except ModuleNotFoundError: + pass + else: + raise AssertionError("ModuleNotFoundError was not raised") + """) + assert_python_ok("-c", code) + + def test_non_package_lazily_imported_as(self): + """A dotted lazy import as raises when the name is not a module.""" + # gh-157757: the eager statement raises, so the lazy one raises too. + code = textwrap.dedent(""" + lazy import math.pi as pi + + try: + pi + except ModuleNotFoundError: + pass + else: + raise AssertionError("ModuleNotFoundError was not raised") + """) + assert_python_ok("-c", code) + + def test_missing_attribute_raises_import_error(self): + """Accessing a nonexistent lazy name via from import raises ImportError.""" + code = textwrap.dedent(""" + lazy from sys import doesnotexist + + try: + _ = doesnotexist + except ImportError: + pass + else: + raise AssertionError("ImportError was not raised") + """) + assert_python_ok("-c", code) + + def test_missing_lazy_from_import_shows_chained_traceback(self): + """Accessing missing attribute from lazy from-import should chain errors.""" + code = textwrap.dedent(""" + lazy from test.test_lazy_import.data.basic2 import nonexistent_name + + try: + _ = nonexistent_name + except ImportError as e: + assert e.__cause__ is not None, "Expected chained exception" + else: + raise AssertionError("ImportError was not raised") + """) + assert_python_ok("-c", code) + + @support.subTests('name', ( + 'test.test_lazy_import.data.broken_module_chained_cause', + 'test.test_lazy_import.data.broken_module_chained_context', + 'test.test_lazy_import.data.broken_module_chained_suppressed', + )) + def test_chained_exception_import_shows_notes(self, name): + """Accessing missing attribute from lazy from-import should chain errors.""" + code = textwrap.dedent(f""" + lazy import {name} + + try: + _ = {name} + except ValueError as e: + assert any( + note.startswith("lazy import of '{name}' declared in ") + for note in e.__notes__ + ), e.__notes__ + else: + raise AssertionError("ImportError was not raised") + """) + assert_python_ok("-c", code) + + def test_reification_retries_on_failure(self): + """Failed reification should allow retry on subsequent access. + + PEP 810: "If reification fails, the lazy object is not reified or replaced. + Subsequent uses of the lazy object will re-try the reification." + """ + code = textwrap.dedent(""" + import sys + + lazy import test.test_lazy_import.data.broken_module + + try: + _ = test.test_lazy_import.data.broken_module + except ValueError as exc: + assert str(exc) == "This module always fails to import", exc + else: + raise AssertionError("ValueError was not raised") + + assert "test.test_lazy_import.data.broken_module" not in sys.modules + + try: + _ = test.test_lazy_import.data.broken_module + except ValueError as exc: + assert str(exc) == "This module always fails to import", exc + else: + raise AssertionError("ValueError was not raised") + """) + assert_python_ok("-c", code) + + def test_lazy_submodule_traceback_hides_importlib_frames(self): + code = textwrap.dedent(""" + import traceback + + lazy import test.test_lazy_import.data.broken_module + + try: + _ = test.test_lazy_import.data.broken_module + except ValueError as exc: + frames = traceback.extract_tb(exc.__traceback__) + assert [frame.name for frame in frames] == ["", ""], frames + assert frames[0].filename == "", frames + assert frames[1].filename.endswith("broken_module.py"), frames + else: + raise AssertionError("ValueError was not raised") + """) + assert_python_ok("-c", code) + + def test_module_not_found_during_module_execution_propagates(self): + code = textwrap.dedent(""" + lazy import test.test_lazy_import.data.missing_dependency + + try: + _ = test.test_lazy_import.data.missing_dependency + except ModuleNotFoundError as exc: + assert exc.name == "missing_dependency_for_lazy_import_test", exc.name + assert str(exc) == "No module named 'missing_dependency_for_lazy_import_test'", exc + else: + raise AssertionError("ModuleNotFoundError was not raised") + """) + assert_python_ok("-c", code) + + def test_self_named_module_not_found_during_module_execution_propagates(self): + code = textwrap.dedent(""" + lazy import test.test_lazy_import.data.self_named_module_not_found + + try: + _ = test.test_lazy_import.data.self_named_module_not_found + except ModuleNotFoundError as exc: + assert exc.name == "test.test_lazy_import.data.self_named_module_not_found", exc.name + assert str(exc) == "boom", exc + else: + raise AssertionError("ModuleNotFoundError was not raised") + """) + assert_python_ok("-c", code) + + def test_none_in_sys_modules_during_submodule_resolution_propagates(self): + code = textwrap.dedent(""" + import sys + + sys.modules["test.test_lazy_import.data.blocked_module"] = None + lazy import test.test_lazy_import.data.blocked_module + + try: + _ = test.test_lazy_import.data.blocked_module + except ModuleNotFoundError as exc: + assert exc.name == "test.test_lazy_import.data.blocked_module", exc.name + assert str(exc) == ( + "import of test.test_lazy_import.data.blocked_module " + "halted; None in sys.modules" + ), exc + else: + raise AssertionError("ModuleNotFoundError was not raised") + """) + assert_python_ok("-c", code) + + def test_circular_lazy_import_does_not_crash_for_gh_144727(self): + with tempfile.TemporaryDirectory() as tmpdir: + a_path = os.path.join(tmpdir, "a.py") + b_path = os.path.join(tmpdir, "b.py") + + with open(a_path, "w") as f: + f.write(textwrap.dedent("""\ + lazy import b + + def something(): + b.hello() + + something() + """)) + + with open(b_path, "w") as f: + f.write(textwrap.dedent("""\ + lazy import a + + def hello(): + print(a) + """)) + + result = subprocess.run( + [sys.executable, a_path], + capture_output=True, + text=True, + cwd=tmpdir, + ) + # Should get a proper Python error, not a crash + self.assertEqual(result.returncode, 1) + self.assertIn("Error", result.stderr) + + +@support.requires_subprocess() +class GlobalsAndDictTests(LazyImportTestCase): + """Tests for globals() and __dict__ behavior with lazy imports. + + PEP 810: "Calling globals() or accessing a module's __dict__ does not trigger + reification – they return the module's dictionary, and accessing lazy objects + through that dictionary still returns lazy proxy objects." + """ + + def test_globals_returns_lazy_proxy_when_accessed_from_function(self): + """globals() accessed from a function should return lazy proxy without reification. + + Note: At module level, accessing globals()['name'] triggers LOAD_NAME which + automatically resolves lazy imports. Inside a function, accessing globals()['name'] + uses BINARY_SUBSCR which returns the lazy proxy without resolution. + """ + code = textwrap.dedent(""" + import sys + import types + + lazy from test.test_lazy_import.data.basic2 import x + + # Check that module is not yet loaded + assert 'test.test_lazy_import.data.basic2' not in sys.modules + + def check_lazy(): + # Access through globals() from inside a function + g = globals() + lazy_obj = g['x'] + return type(lazy_obj) is types.LazyImportType + + # Inside function, should get lazy proxy + is_lazy = check_lazy() + assert is_lazy, "Expected LazyImportType from function scope" + + # Module should STILL not be loaded + assert 'test.test_lazy_import.data.basic2' not in sys.modules + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_globals_dict_access_returns_lazy_proxy_inline(self): + """Accessing globals()['name'] inline should return lazy proxy. + + Note: Assigning g['name'] to a local variable at module level triggers + reification due to STORE_NAME bytecode. Inline access preserves laziness. + """ + code = textwrap.dedent(""" + import sys + import types + lazy import json + # Inline access without assignment to local variable preserves lazy proxy + assert type(globals()['json']) is types.LazyImportType + assert 'json' not in sys.modules + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_module_dict_returns_lazy_proxy_without_reifying(self): + """module.__dict__ access should not trigger reification.""" + import test.test_lazy_import.data.globals_access + + # Module not loaded yet via direct dict access + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + # Access via get_from_globals should return lazy proxy + lazy_obj = test.test_lazy_import.data.globals_access.get_from_globals() + self.assertEqual(type(lazy_obj), types.LazyImportType) + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_direct_access_triggers_reification(self): + """Direct name access (not through globals()) should trigger reification.""" + import test.test_lazy_import.data.globals_access + + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + # Direct access should reify + result = test.test_lazy_import.data.globals_access.get_direct() + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_resolve_method_forces_reification(self): + """Calling resolve() on lazy proxy should force reification. + + Note: Must access lazy proxy from within a function to avoid automatic + reification by LOAD_NAME at module level. + """ + code = textwrap.dedent(""" + import sys + import types + + lazy from test.test_lazy_import.data.basic2 import x + + assert 'test.test_lazy_import.data.basic2' not in sys.modules + + def test_resolve(): + g = globals() + lazy_obj = g['x'] + assert type(lazy_obj) is types.LazyImportType, f"Expected lazy proxy, got {type(lazy_obj)}" + + resolved = lazy_obj.resolve() + + # Now module should be loaded + assert 'test.test_lazy_import.data.basic2' in sys.modules + assert resolved == 42 # x is 42 in basic2.py + return True + + assert test_resolve() + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_add_lazy_to_globals(self): + code = textwrap.dedent(""" + import sys + import types + + lazy from test.test_lazy_import.data import basic2 + + assert 'test.test_lazy_import.data.basic2' not in sys.modules + + class C: pass + sneaky = C() + sneaky.x = 1 + + def f(): + t = 0 + for _ in range(5): + t += sneaky.x + return t + + f() + globals()["sneaky"] = globals()["basic2"] + assert f() == 210 + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_add_lazy_to_exec_globals_after_specialization(self): + code = textwrap.dedent(""" + source = ''' + import sys + import types + + lazy from test.test_lazy_import.data import basic2 + + assert 'test.test_lazy_import.data.basic2' not in sys.modules + + class C: pass + sneaky = C() + sneaky.x = 1 + + def f(): + t = 0 + for _ in range(5): + t += sneaky.x + return t + + f() + globals()["sneaky"] = globals()["basic2"] + assert f() == 210 + print("OK") + ''' + ns = {"__name__": "lazy_exec_globals"} + exec(source, ns) + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_add_lazy_to_exec_builtins_after_specialization(self): + code = textwrap.dedent(""" + import builtins + source = ''' + import sys + import types + + lazy from test.test_lazy_import.data import basic2 + + assert 'test.test_lazy_import.data.basic2' not in sys.modules + + class C: pass + sneaky = C() + sneaky.x = 1 + __builtins__["sneaky"] = sneaky + del sneaky + + def f(): + t = 0 + for _ in range(5): + t += sneaky.x + return t + + f() + __builtins__["sneaky"] = globals()["basic2"] + assert f() == 210 + print("OK") + ''' + ns = {"__name__": "lazy_exec_builtins", "__builtins__": builtins.__dict__.copy()} + exec(source, ns) + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + +@support.requires_subprocess() +class MultipleNameFromImportTests(LazyImportTestCase): + """Tests for lazy from ... import with multiple names. + + PEP 810: "When using lazy from ... import, each imported name is bound to a + lazy proxy object. The first access to any of these names triggers loading + of the entire module and reifies only that specific name to its actual value. + Other names remain as lazy proxies until they are accessed." + """ + + def test_accessing_one_name_leaves_others_as_proxies(self): + """Accessing one name from multi-name import should leave others lazy.""" + code = textwrap.dedent(""" + import sys + import types + + lazy from test.test_lazy_import.data.basic2 import f, x + + # Neither should be loaded yet + assert 'test.test_lazy_import.data.basic2' not in sys.modules + + g = globals() + assert type(g['f']) is types.LazyImportType + assert type(g['x']) is types.LazyImportType + + # Access 'x' - this loads the module and reifies only 'x' + value = x + assert value == 42 + + # Module is now loaded + assert 'test.test_lazy_import.data.basic2' in sys.modules + + # 'x' should be reified (int), 'f' should still be lazy proxy + assert type(g['x']) is int, f"Expected int, got {type(g['x'])}" + assert type(g['f']) is types.LazyImportType, f"Expected LazyImportType, got {type(g['f'])}" + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_accessing_one_name_imports_only_its_submodule(self): + """Accessing one name should not import the other names' submodules.""" + code = textwrap.dedent(""" + import sys + + lazy from test.test_lazy_import.data.pkg import b, bar, broken + + # Importing bar prints, and importing broken raises. + b.foo() + + assert "test.test_lazy_import.data.pkg.bar" not in sys.modules + assert "test.test_lazy_import.data.pkg.broken" not in sys.modules + """) + rc, out, err = assert_python_ok("-c", code) + self.assertEqual(out, b"") + + def test_all_names_reified_after_all_accessed(self): + """All names should be reified after each is accessed.""" + code = textwrap.dedent(""" + import sys + import types + + lazy from test.test_lazy_import.data.basic2 import f, x + + g = globals() + + # Access both + _ = x + _ = f + + # Both should be reified now + assert type(g['x']) is int + assert callable(g['f']) + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + +@support.requires_subprocess() +class SysLazyModulesTrackingTests(LazyImportTestCase): + """Tests for sys.lazy_modules tracking behavior. + + PEP 810: "When the module is reified, it's removed from sys.lazy_modules" + """ + + def test_module_added_to_lazy_modules_on_lazy_import(self): + """Module should be added to sys.lazy_modules when lazily imported.""" + # PEP 810 states lazy_modules tracks modules that have been lazily imported + # Note: The current implementation keeps modules in lazy_modules even after + # reification (primarily for diagnostics and introspection) + code = textwrap.dedent(""" + import sys + + initial_count = len(sys.lazy_modules) + + lazy import test.test_lazy_import.data.basic2 + + # Should be in lazy_modules after lazy import + assert "test.test_lazy_import.data.basic2" in sys.lazy_modules + assert len(sys.lazy_modules) > initial_count + + # Trigger reification + _ = test.test_lazy_import.data.basic2.x + + # Module should still be tracked (for diagnostics per PEP 810) + assert "test.test_lazy_import.data.basic2" not in sys.lazy_modules + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_lazy_modules_is_per_interpreter(self): + """Each interpreter should have independent sys.lazy_modules.""" + # Basic test that sys.lazy_modules exists and is a set + self.assertIsInstance(sys.lazy_modules, set) + + def test_lazy_module_without_children_is_tracked(self): + code = textwrap.dedent(""" + import sys + lazy import json + assert "json" in sys.lazy_modules, ( + f"expected 'json' in sys.lazy_modules, got {set(sys.lazy_modules)}" + ) + print("OK") + """) + assert_python_ok("-c", code) + + def test_already_loaded_module_is_not_tracked(self): + """A lazy import of an already loaded module should not be tracked.""" + code = textwrap.dedent(""" + import sys + + # Loaded by a regular import. + import json + lazy import json as lazy_json + assert "json" not in sys.lazy_modules, ( + f"expected 'json' not in sys.lazy_modules, got {sys.lazy_modules}" + ) + + # Loaded by reifying an earlier lazy import. + lazy import base64 + _ = base64.b64encode + lazy import base64 as lazy_base64 + assert "base64" not in sys.lazy_modules, ( + f"expected 'base64' not in sys.lazy_modules, got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + def test_already_loaded_submodule_is_not_tracked(self): + """`lazy from` a loaded submodule should not be tracked either.""" + code = textwrap.dedent(""" + import sys + import test.test_lazy_import.data.pkg.b + lazy from test.test_lazy_import.data.pkg import b + assert "test.test_lazy_import.data.pkg.b" not in sys.lazy_modules, ( + f"expected 'pkg.b' untracked, got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + def test_attribute_entry_removed_on_reification(self): + """`lazy from x import attr` should untrack "x.attr" once resolved.""" + code = textwrap.dedent(""" + import sys + lazy from test.test_lazy_import.data.basic2 import x + assert "test.test_lazy_import.data.basic2.x" in sys.lazy_modules, ( + f"expected 'basic2.x' tracked, got {sys.lazy_modules}" + ) + _ = x + assert "test.test_lazy_import.data.basic2.x" not in sys.lazy_modules, ( + f"expected 'basic2.x' untracked, got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + def test_already_loaded_attribute_is_not_tracked(self): + code = textwrap.dedent(""" + import sys + import math + + lazy from math import pi + assert "math.pi" not in sys.lazy_modules, sys.lazy_modules + assert pi == math.pi + """) + assert_python_ok("-c", code) + + def test_cached_lazy_attribute_tracks_its_target(self): + code = textwrap.dedent(""" + import sys + import test.test_lazy_import.data.basic_from_unused + + holder = "test.test_lazy_import.data.basic_from_unused" + target = "test.test_lazy_import.data.basic2" + + namespace = {"__name__": "cached_import_test"} + exec(f"lazy from {holder} import basic2", namespace) + assert holder + ".basic2" not in sys.lazy_modules, sys.lazy_modules + assert target in sys.lazy_modules, sys.lazy_modules + exec("assert basic2.x == 42", namespace) + assert target not in sys.lazy_modules, sys.lazy_modules + """) + assert_python_ok("-c", code) + + def test_cached_attribute_keeps_pending_module_tracked(self): + code = textwrap.dedent(""" + import sys + import test.test_lazy_import.data.pkg as pkg + pkg.b = 42 + + lazy import test.test_lazy_import.data.pkg.b as pending + lazy from test.test_lazy_import.data.pkg import b + name = "test.test_lazy_import.data.pkg.b" + assert b == 42, b + assert name not in sys.modules, sys.modules + assert name in sys.lazy_modules, sys.lazy_modules + assert pending.foo() == "foo" + assert name not in sys.lazy_modules, sys.lazy_modules + """) + assert_python_ok("-c", code) + + def test_failed_reification_stays_tracked(self): + """A lazy import that fails to resolve must stay tracked.""" + code = textwrap.dedent(""" + import sys + lazy import test.test_lazy_import.data.broken_module + try: + _ = test.test_lazy_import.data.broken_module + except ValueError: + pass + else: + raise AssertionError("ValueError was not raised") + assert "test.test_lazy_import.data.broken_module" in sys.lazy_modules, ( + f"failed reification must stay tracked, got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + def test_blocked_module_is_still_tracked(self): + """A ``None`` entry in sys.modules must not count as loaded.""" + code = textwrap.dedent(""" + import sys + sys.modules['test.test_lazy_import.data.basic2'] = None + lazy import test.test_lazy_import.data.basic2 + assert "test.test_lazy_import.data.basic2" in sys.lazy_modules, ( + f"blocked module must stay tracked, got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + def test_initializing_module_is_still_tracked(self): + """A module that is still executing must not count as loaded.""" + code = textwrap.dedent(""" + import sys + name = "test.test_lazy_import.data.init_fails" + try: + import test.test_lazy_import.data.init_fails + except ValueError: + pass + else: + raise AssertionError("ValueError was not raised") + assert name not in sys.modules, "failed import left a module behind" + assert name in sys.lazy_modules, ( + f"expected {name!r} tracked, got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + def test_module_spec_descriptor_is_not_run(self): + """Checking whether a module is loaded must not run its descriptors.""" + code = textwrap.dedent(""" + import sys + import types + + class RaisingSpec(types.ModuleType): + @property + def __spec__(self): + raise RuntimeError("__spec__ descriptor was run") + + sys.modules["raising_spec"] = RaisingSpec("raising_spec") + lazy import raising_spec + assert "raising_spec" not in sys.lazy_modules, ( + f"expected 'raising_spec' untracked, got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + def test_spec_initializing_descriptor_is_not_run(self): + code = textwrap.dedent(""" + import sys + import types + + class Spec: + @property + def _initializing(self): + raise RuntimeError("_initializing descriptor was run") + + @property + def __dict__(self): + raise RuntimeError("__dict__ descriptor was run") + + class SlottedSpec: + __slots__ = () + + @property + def _initializing(self): + raise RuntimeError("_initializing descriptor was run") + + for spec in (Spec(), SlottedSpec()): + module = types.ModuleType("custom_spec") + module.__spec__ = spec + sys.modules["custom_spec"] = module + lazy import custom_spec + """) + assert_python_ok("-c", code) + + def test_cached_attribute_does_not_check_spec_twice(self): + code = textwrap.dedent(""" + import sys + import types + + class Spec: + def __init__(self): + self.calls = 0 + + @property + def _initializing(self): + self.calls += 1 + if self.calls == 2: + raise RuntimeError("_initializing was read twice") + return False + + module = types.ModuleType("cached_spec") + module.__spec__ = Spec() + module.attr = 1 + sys.modules["cached_spec"] = module + lazy from cached_spec import attr + assert attr == 1, attr + """) + assert_python_ok("-c", code) + + def test_spec_initializing_truth_conversion_is_not_run(self): + code = textwrap.dedent(""" + import sys + import types + from importlib.machinery import ModuleSpec + + class Flag: + def __bool__(self): + raise RuntimeError("_initializing truth conversion was run") + + released = memoryview(b"") + released.release() + for flag in (Flag(), released): + sys.lazy_modules.discard("custom_spec") + module = types.ModuleType("custom_spec") + module.__spec__ = ModuleSpec("custom_spec", None) + module.__spec__._initializing = flag + sys.modules["custom_spec"] = module + lazy import custom_spec + assert "custom_spec" in sys.lazy_modules, sys.lazy_modules + """) + assert_python_ok("-c", code) + + def test_pending_submodule_is_still_tracked(self): + """`lazy from` a submodule that is not loaded must stay tracked.""" + code = textwrap.dedent(""" + import sys + lazy from test.test_lazy_import.data.pkg import b + assert "test.test_lazy_import.data.pkg.b" in sys.lazy_modules, ( + f"expected 'pkg.b' tracked, got {sys.lazy_modules}" + ) + import test.test_lazy_import.data.pkg + assert "test.test_lazy_import.data.pkg.b" not in sys.modules, ( + "loading the package must not load the submodule" + ) + assert "test.test_lazy_import.data.pkg.b" in sys.lazy_modules, ( + f"loading the package must not untrack the submodule, " + f"got {sys.lazy_modules}" + ) + """) + assert_python_ok("-c", code) + + +@support.requires_subprocess() +class CommandLineAndEnvVarTests(unittest.TestCase): + """Tests for command-line and environment variable control. + + PEP 810: The global lazy imports flag can be controlled through: + - The -X lazy_imports= command-line option + - The PYTHON_LAZY_IMPORTS= environment variable + """ + + def test_cli_lazy_imports_all_makes_regular_imports_lazy(self): + """-X lazy_imports=all should make all imports potentially lazy.""" + code = textwrap.dedent(""" + import sys + # In 'all' mode, regular imports become lazy + import json + # json should not be in sys.modules yet (lazy) + # Actually accessing it triggers reification + if 'json' not in sys.modules: + print("LAZY") + else: + print("EAGER") + """) + result = subprocess.run( + [sys.executable, "-X", "lazy_imports=all", "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}") + self.assertIn("LAZY", result.stdout) + + def test_cli_lazy_imports_none_is_rejected(self): + """-X lazy_imports=none should be rejected.""" + result = subprocess.run( + [sys.executable, "-X", "lazy_imports=none", "-c", "pass"], + capture_output=True, + text=True + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("-X lazy_imports: invalid value", result.stderr) + self.assertIn("expected 'all' or 'normal'", result.stderr) + + def test_cli_lazy_imports_normal_respects_lazy_keyword_only(self): + """-X lazy_imports=normal should respect lazy keyword only.""" + # Note: Use test modules instead of stdlib modules to avoid + # modules already loaded by the interpreter startup + code = textwrap.dedent(""" + import sys + import test.test_lazy_import.data.basic2 # Should be eager + lazy import test.test_lazy_import.data.pkg.b # Should be lazy + + eager_loaded = 'test.test_lazy_import.data.basic2' in sys.modules + lazy_loaded = 'test.test_lazy_import.data.pkg.b' in sys.modules + + if eager_loaded and not lazy_loaded: + print("OK") + else: + print(f"FAIL: eager={eager_loaded}, lazy={lazy_loaded}") + """) + result = subprocess.run( + [sys.executable, "-X", "lazy_imports=normal", "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_env_var_lazy_imports_all_enables_global_lazy(self): + """PYTHON_LAZY_IMPORTS=all should enable global lazy imports.""" + code = textwrap.dedent(""" + import sys + import json + if 'json' not in sys.modules: + print("LAZY") + else: + print("EAGER") + """) + import os + env = os.environ.copy() + env["PYTHON_LAZY_IMPORTS"] = "all" + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True, + env=env + ) + self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}") + self.assertIn("LAZY", result.stdout) + + def test_env_var_lazy_imports_none_is_rejected(self): + """PYTHON_LAZY_IMPORTS=none should be rejected.""" + import os + env = os.environ.copy() + env["PYTHON_LAZY_IMPORTS"] = "none" + result = subprocess.run( + [sys.executable, "-c", "pass"], + capture_output=True, + text=True, + env=env + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("PYTHON_LAZY_IMPORTS: invalid value", result.stderr) + self.assertIn("expected 'all' or 'normal'", result.stderr) + + def test_cli_overrides_env_var(self): + """Command-line option should take precedence over environment variable.""" + # PEP 810: -X lazy_imports takes precedence over PYTHON_LAZY_IMPORTS + code = textwrap.dedent(""" + import sys + import json + if 'json' in sys.modules: + print("EAGER") + else: + print("LAZY") + """) + import os + env = os.environ.copy() + env["PYTHON_LAZY_IMPORTS"] = "all" # env says all imports are lazy + result = subprocess.run( + [sys.executable, "-X", "lazy_imports=normal", "-c", code], + capture_output=True, + text=True, + env=env + ) + self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}") + # CLI should win, so a regular import should stay eager. + self.assertIn("EAGER", result.stdout) + + def test_sys_set_lazy_imports_overrides_cli(self): + """sys.set_lazy_imports() should take precedence over CLI option.""" + code = textwrap.dedent(""" + import sys + sys.set_lazy_imports("normal") # Override CLI + import json + if 'json' in sys.modules: + print("EAGER") + else: + print("LAZY") + """) + result = subprocess.run( + [sys.executable, "-X", "lazy_imports=all", "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}") + self.assertIn("EAGER", result.stdout) + + +@support.requires_subprocess() +class FilterFunctionSignatureTests(LazyImportTestCase): + """Tests for the filter function signature per PEP 810. + + PEP 810: func(importer: str, name: str, fromlist: tuple[str, ...] | None) -> bool + """ + + def _run_subprocess_with_modules(self, code, files): + with tempfile.TemporaryDirectory() as tmpdir: + for relpath, contents in files.items(): + path = os.path.join(tmpdir, relpath) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, "w", encoding="utf-8") as file: + file.write(textwrap.dedent(contents)) + + env = os.environ.copy() + env["PYTHONPATH"] = os.pathsep.join( + entry for entry in (tmpdir, env.get("PYTHONPATH")) if entry + ) + env["PYTHON_LAZY_IMPORTS"] = "normal" + + result = subprocess.run( + [sys.executable, "-c", textwrap.dedent(code)], + capture_output=True, + cwd=tmpdir, + env=env, + text=True, + ) + return result + + def _assert_subprocess_ok(self, code, files): + result = self._run_subprocess_with_modules(code, files) + self.assertEqual( + result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}" + ) + return result + + def test_filter_receives_correct_arguments_for_import(self): + """Filter should receive (importer, name, fromlist=None) for 'import x'.""" + code = textwrap.dedent(""" + import sys + + received_args = [] + + def my_filter(importer, name, fromlist): + received_args.append((importer, name, fromlist)) + return True + + sys.set_lazy_imports_filter(my_filter) + + lazy import json + + assert len(received_args) == 1, f"Expected 1 call, got {len(received_args)}" + importer, name, fromlist = received_args[0] + assert name == "json", f"Expected name='json', got {name!r}" + assert fromlist is None, f"Expected fromlist=None, got {fromlist!r}" + assert isinstance(importer, str), f"Expected str importer, got {type(importer)}" + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_filter_receives_fromlist_for_from_import(self): + """Filter should receive fromlist tuple for 'from x import y, z'.""" + code = textwrap.dedent(""" + import sys + + received_args = [] + + def my_filter(importer, name, fromlist): + received_args.append((importer, name, fromlist)) + return True + + sys.set_lazy_imports_filter(my_filter) + + lazy from json import dumps, loads + + assert len(received_args) == 1, f"Expected 1 call, got {len(received_args)}" + importer, name, fromlist = received_args[0] + assert name == "json", f"Expected name='json', got {name!r}" + assert fromlist == ("dumps", "loads"), f"Expected ('dumps', 'loads'), got {fromlist!r}" + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_filter_returning_false_forces_eager_import(self): + """Filter returning False should make import eager.""" + code = textwrap.dedent(""" + import sys + + def deny_filter(importer, name, fromlist): + return False + + sys.set_lazy_imports_filter(deny_filter) + + lazy import json + + # Should be eager due to filter + if 'json' in sys.modules: + print("EAGER") + else: + print("LAZY") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}") + self.assertIn("EAGER", result.stdout) + + def test_filter_distinguishes_absolute_and_relative_from_imports(self): + """Relative imports should pass resolved module names to the filter.""" + files = { + "target.py": """ + VALUE = "absolute" + """, + "pkg/__init__.py": "", + "pkg/target.py": """ + VALUE = "relative" + """, + "pkg/runner.py": """ + import sys + + seen = [] + + def my_filter(importer, name, fromlist): + seen.append((importer, name, fromlist)) + return True + + sys.set_lazy_imports_filter(my_filter) + + lazy from target import VALUE as absolute_value + lazy from .target import VALUE as relative_value + + assert seen == [ + (__name__, "target", ("VALUE",)), + (__name__, "pkg.target", ("VALUE",)), + ], seen + """, + } + + result = self._assert_subprocess_ok( + """ + import pkg.runner + print("OK") + """, + files, + ) + self.assertIn("OK", result.stdout) + + def test_filter_receives_resolved_name_for_relative_package_import(self): + """'lazy from . import x' should report the resolved package name.""" + files = { + "pkg/__init__.py": "", + "pkg/sibling.py": """ + VALUE = 1 + """, + "pkg/runner.py": """ + import sys + + seen = [] + + def my_filter(importer, name, fromlist): + seen.append((importer, name, fromlist)) + return True + + sys.set_lazy_imports_filter(my_filter) + + lazy from . import sibling + + assert seen == [ + (__name__, "pkg", ("sibling",)), + ], seen + """, + } + + result = self._assert_subprocess_ok( + """ + import pkg.runner + print("OK") + """, + files, + ) + self.assertIn("OK", result.stdout) + + def test_filter_receives_resolved_name_for_parent_relative_import(self): + """Parent relative imports should also use the resolved module name.""" + files = { + "pkg/__init__.py": "", + "pkg/target.py": """ + VALUE = 1 + """, + "pkg/sub/__init__.py": "", + "pkg/sub/runner.py": """ + import sys + + seen = [] + + def my_filter(importer, name, fromlist): + seen.append((importer, name, fromlist)) + return True + + sys.set_lazy_imports_filter(my_filter) + + lazy from ..target import VALUE + + assert seen == [ + (__name__, "pkg.target", ("VALUE",)), + ], seen + """, + } + + result = self._assert_subprocess_ok( + """ + import pkg.sub.runner + print("OK") + """, + files, + ) + self.assertIn("OK", result.stdout) + + def test_filter_can_force_eager_only_for_resolved_relative_target(self): + """Resolved names should let filters treat relative and absolute imports differently.""" + files = { + "target.py": """ + VALUE = "absolute" + """, + "pkg/__init__.py": "", + "pkg/target.py": """ + VALUE = "relative" + """, + "pkg/runner.py": """ + import sys + + def my_filter(importer, name, fromlist): + return name != "pkg.target" + + sys.set_lazy_imports_filter(my_filter) + + lazy from target import VALUE as absolute_value + lazy from .target import VALUE as relative_value + + assert "pkg.target" in sys.modules, sorted( + name for name in sys.modules + if name in {"target", "pkg.target"} + ) + assert "target" not in sys.modules, sorted( + name for name in sys.modules + if name in {"target", "pkg.target"} + ) + assert relative_value == "relative", relative_value + """, + } + + result = self._assert_subprocess_ok( + """ + import pkg.runner + print("OK") + """, + files, + ) + self.assertIn("OK", result.stdout) + + +class AdditionalSyntaxRestrictionTests(LazyImportTestCase): + """Additional syntax restriction tests per PEP 810.""" + + def test_lazy_import_inside_class_raises_syntax_error(self): + """lazy import inside class body should raise SyntaxError.""" + # PEP 810: "The soft keyword is only allowed at the global (module) level, + # not inside functions, class bodies, try blocks, or import *" + with self.assertRaises(SyntaxError): + import test.test_lazy_import.data.badsyntax.lazy_class_body + + +@support.requires_subprocess() +class MixedLazyEagerImportTests(LazyImportTestCase): + """Tests for mixing lazy and eager imports of the same module. + + PEP 810: "If module foo is imported both lazily and eagerly in the same + program, the eager import takes precedence and both bindings resolve to + the same module object." + """ + + def test_eager_import_before_lazy_resolves_to_same_module(self): + """Eager import before lazy should make lazy resolve to same module.""" + code = textwrap.dedent(""" + import sys + import json # Eager import first + + lazy import json as lazy_json # Lazy import same module + + # lazy_json should resolve to the same object + assert json is lazy_json, "Lazy and eager imports should resolve to same module" + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_lazy_import_before_eager_resolves_to_same_module(self): + """Lazy import followed by eager should both point to same module.""" + code = textwrap.dedent(""" + import sys + + lazy import json as lazy_json + + # Lazy not loaded yet + assert 'json' not in sys.modules + + import json # Eager import triggers load + + # Both should be the same object + assert json is lazy_json + print("OK") + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + +class RelativeImportTests(LazyImportTestCase): + """Tests for relative imports with lazy keyword.""" + + def test_relative_lazy_import(self): + """lazy from . import submodule should work.""" + from test.test_lazy_import.data import relative_lazy + + # basic2 should not be loaded yet + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + # Access triggers reification + result = relative_lazy.get_basic2() + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + def test_relative_lazy_from_import(self): + """lazy from .module import name should work.""" + from test.test_lazy_import.data import relative_lazy_from + + # basic2 should not be loaded yet + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + # Access triggers reification + result = relative_lazy_from.get_x() + self.assertEqual(result, 42) + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + +class LazyModulesCompatibilityFromImportTests(LazyImportTestCase): + """Tests for __lazy_modules__ with from imports. + + PEP 810: "When a module is made lazy this way, from-imports using that + module are also lazy" + """ + + def test_lazy_modules_makes_from_imports_lazy(self): + """__lazy_modules__ should make from imports of listed modules lazy.""" + from test.test_lazy_import.data import lazy_compat_from + + # basic2 should not be loaded yet because it's in __lazy_modules__ + self.assertNotIn("test.test_lazy_import.data.basic2", sys.modules) + + # Access triggers reification + result = lazy_compat_from.get_x() + self.assertEqual(result, 42) + self.assertIn("test.test_lazy_import.data.basic2", sys.modules) + + +@support.requires_subprocess() +class ImportStateAtReificationTests(LazyImportTestCase): + """Tests for import system state at reification time. + + PEP 810: "Reification still calls __import__ to resolve the import, which uses + the state of the import system (e.g. sys.path, sys.meta_path, sys.path_hooks + and __import__) at reification time, not the state when the lazy import + statement was evaluated." + """ + + def test_sys_path_at_reification_time_is_used(self): + """sys.path changes after lazy import should affect reification.""" + code = textwrap.dedent(""" + import sys + import tempfile + import os + + # Create a temporary module + with tempfile.TemporaryDirectory() as tmpdir: + mod_path = os.path.join(tmpdir, "dynamic_test_module.py") + with open(mod_path, "w") as f: + f.write("VALUE = 'from_temp_dir'\\n") + + # Lazy import before adding to path + lazy import dynamic_test_module + + # Module cannot be found yet + try: + _ = dynamic_test_module + print("FAIL - should not find module") + except ModuleNotFoundError: + pass + + # Now add temp dir to path + sys.path.insert(0, tmpdir) + + # Now reification should succeed using current sys.path + assert dynamic_test_module.VALUE == 'from_temp_dir' + print("OK") + + sys.path.remove(tmpdir) + """) + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + +@support.requires_subprocess() +class ThreadSafetyTests(LazyImportTestCase): + """Tests for thread-safety of lazy imports.""" + + def test_concurrent_lazy_import_reification(self): + """Multiple threads racing to reify the same lazy import should succeed.""" + from test.test_lazy_import.data import basic_unused + + num_threads = 10 + results = [None] * num_threads + errors = [] + barrier = threading.Barrier(num_threads) + + def access_lazy_import(idx): + try: + barrier.wait() + module = basic_unused.test.test_lazy_import.data.basic2 + results[idx] = module + except Exception as e: + errors.append((idx, e)) + + threads = [ + threading.Thread(target=access_lazy_import, args=(i,)) + for i in range(num_threads) + ] + + for t in threads: + t.start() + for t in threads: + t.join() + + self.assertEqual(errors, [], f"Errors occurred: {errors}") + self.assertTrue(all(r is not None for r in results)) + first_module = results[0] + for r in results[1:]: + self.assertIs(r, first_module) + + def test_concurrent_reification_multiple_modules(self): + """Multiple threads reifying different lazy imports concurrently.""" + code = textwrap.dedent(""" + import sys + import threading + + sys.set_lazy_imports("all") + + lazy import json + lazy import os + lazy import io + lazy import re + + num_threads = 8 + results = {} + errors = [] + barrier = threading.Barrier(num_threads) + + def access_modules(idx): + try: + barrier.wait() + mods = [json, os, io, re] + results[idx] = [type(m).__name__ for m in mods] + except Exception as e: + errors.append((idx, e)) + + threads = [ + threading.Thread(target=access_modules, args=(i,)) + for i in range(num_threads) + ] + + for t in threads: + t.start() + for t in threads: + t.join() + + assert not errors, f"Errors: {errors}" + for idx, mods in results.items(): + assert all(m == 'module' for m in mods), f"Thread {idx} got: {mods}" + + print("OK") + """) + + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_concurrent_lazy_modules_dict_updates(self): + """Multiple threads creating lazy imports should safely update sys.lazy_modules.""" + code = textwrap.dedent(""" + import sys + import threading + + num_threads = 16 + iterations = 50 + errors = [] + barrier = threading.Barrier(num_threads) + + def create_lazy_imports(idx): + try: + barrier.wait() + for i in range(iterations): + exec(f"lazy import json as json_{idx}_{i}", globals()) + exec(f"lazy import os as os_{idx}_{i}", globals()) + except Exception as e: + errors.append((idx, e)) + + threads = [ + threading.Thread(target=create_lazy_imports, args=(i,)) + for i in range(num_threads) + ] + + for t in threads: + t.start() + for t in threads: + t.join() + + assert not errors, f"Errors: {errors}" + assert isinstance(sys.lazy_modules, set), "sys.lazy_modules is not a dict" + print("OK") + """) + + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_concurrent_reification_same_module_high_contention(self): + """High contention: many threads reifying the exact same lazy import.""" + code = textwrap.dedent(""" + import sys + import threading + import types + + sys.set_lazy_imports("all") + + lazy import json + + num_threads = 20 + results = [None] * num_threads + errors = [] + barrier = threading.Barrier(num_threads) + + def access_json(idx): + try: + barrier.wait() + for _ in range(100): + _ = json.dumps + _ = json.loads + results[idx] = json + except Exception as e: + errors.append((idx, e)) + + threads = [ + threading.Thread(target=access_json, args=(i,)) + for i in range(num_threads) + ] + + for t in threads: + t.start() + for t in threads: + t.join() + + assert not errors, f"Errors: {errors}" + assert all(r is not None for r in results), "Some threads got None" + first = results[0] + assert all(r is first for r in results), "Inconsistent module objects" + assert not isinstance(first, types.LazyImportType), "Got lazy import instead of module" + print("OK") + """) + + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + def test_concurrent_reification_with_module_attribute_access(self): + """Threads racing to reify and immediately access module attributes.""" + code = textwrap.dedent(""" + import sys + import threading + + sys.set_lazy_imports("all") + + lazy import collections + lazy import functools + lazy import itertools + + num_threads = 12 + results = {} + errors = [] + barrier = threading.Barrier(num_threads) + + def stress_lazy_imports(idx): + try: + barrier.wait() + for _ in range(50): + _ = collections.OrderedDict + _ = functools.partial + _ = itertools.chain + _ = collections.defaultdict + _ = functools.lru_cache + _ = itertools.islice + results[idx] = ( + type(collections).__name__, + type(functools).__name__, + type(itertools).__name__, + ) + except Exception as e: + errors.append((idx, e)) + + threads = [ + threading.Thread(target=stress_lazy_imports, args=(i,)) + for i in range(num_threads) + ] + + for t in threads: + t.start() + for t in threads: + t.join() + + assert not errors, f"Errors: {errors}" + for idx, types_tuple in results.items(): + assert all(t == 'module' for t in types_tuple), f"Thread {idx}: {types_tuple}" + print("OK") + """) + + result = subprocess.run( + [sys.executable, "-c", code], + capture_output=True, + text=True + ) + self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}") + self.assertIn("OK", result.stdout) + + +class LazyImportDisTests(unittest.TestCase): + def test_lazy_import_dis(self): + """dis should properly show lazy import""" + code = compile("lazy import foo", "exec", "exec") + f = io.StringIO() + dis.dis(code, file=f) + self.assertIn("foo + lazy", f.getvalue()) + + def test_normal_import_dis(self): + """non lazy imports should just show the name""" + code = compile("import foo", "exec", "exec") + f = io.StringIO() + dis.dis(code, file=f) + for line in f.getvalue().split('\n'): + if "IMPORT_NAME" in line: + self.assertIn("(foo)", line) + break + else: + self.assertFail("IMPORT_NAME not found") + + +@unittest.skipIf(_testcapi is None, 'need the _testcapi module') +class LazyCApiTests(LazyImportTestCase): + def test_set_matches_sys(self): + self.assertEqual(_testcapi.PyImport_GetLazyImportsMode(), sys.get_lazy_imports()) + for mode in ("normal", "all"): + _testcapi.PyImport_SetLazyImportsMode(mode) + self.assertEqual(_testcapi.PyImport_GetLazyImportsMode(), sys.get_lazy_imports()) + self.assertRaises(ValueError, _testcapi.PyImport_SetLazyImportsMode, "none") + + def test_filter_matches_sys(self): + self.assertEqual(_testcapi.PyImport_GetLazyImportsFilter(), sys.get_lazy_imports_filter()) + + def filter(*args): + pass + + _testcapi.PyImport_SetLazyImportsFilter(filter) + self.assertEqual(_testcapi.PyImport_GetLazyImportsFilter(), sys.get_lazy_imports_filter()) + + def test_set_bad_filter(self): + self.assertRaises(ValueError, _testcapi.PyImport_SetLazyImportsFilter, 42) + + def test_dunder_lazy_import_without_frame(self): + # gh-151510: __lazy_import__() called with no globals and no running + # Python frame must raise TypeError instead of crashing. + with self.assertRaisesRegex( + TypeError, + r"__lazy_import__\(\) missing globals when called without a frame", + ): + _testcapi.lazy_import_without_frame( + "test.test_lazy_import.data.basic2" + ) + + +class DottedLazyImportTests(unittest.TestCase): + + def test_lazy_import_as_wins_over_variable(self): + """A dotted lazy import as imports the submodule the variable hides.""" + # gh-157757: importing pkg.b rebinds pkg.b from the variable to the + # module, eagerly and lazily alike. + code = textwrap.dedent(""" + import sys + import test.test_lazy_import.data.pkg as pkg + pkg.b = "hides the b submodule" + + lazy import test.test_lazy_import.data.pkg.b as b + lazy import xml.dom.minidom as minidom + + assert b is sys.modules["test.test_lazy_import.data.pkg.b"], b + assert minidom is sys.modules["xml.dom.minidom"], minidom + """) + assert_python_ok("-c", code) + + + def test_dotted_as_of_loaded_module(self): + """A dotted lazy import as binds the module, not a same-named attribute.""" + # importlib.metadata is already loaded and has a `metadata` attribute. + code = textwrap.dedent(""" + import importlib.metadata + import importlib.metadata as eager + + lazy import importlib.metadata as lazily + + assert lazily is eager, lazily + """) + assert_python_ok("-c", code) + + + def test_dotted_as_replays_lookups_on_custom_placeholder(self): + """A dotted lazy import as looks up its names on what the hook returned.""" + code = textwrap.dedent(""" + import builtins + import xml.dom + + # In a list, so the hook reading it does not resolve it. + placeholder = [__lazy_import__("xml")] + default = builtins.__lazy_import__ + builtins.__lazy_import__ = lambda *args: placeholder[0] + lazy import fake.dom as dom + builtins.__lazy_import__ = default + + assert dom is xml.dom, dom + """) + assert_python_ok("-c", code) + + + def test_empty_fromlist_placeholder_matches_no_fromlist(self): + """An empty fromlist behaves like None.""" + code = textwrap.dedent(""" + expected = "" + # In lists, so reading them does not resolve them. + for fromlist in (None, ()): + same = [__lazy_import__("xml.dom", fromlist=fromlist)] + assert repr(same[0]) == expected, (fromlist, repr(same[0])) + bare = [__lazy_import__("xml.dom")] + assert repr(bare[0]) == expected, repr(bare[0]) + """) + assert_python_ok("-c", code) + + + def test_empty_fromlist_preserved_for_custom_import(self): + code = textwrap.dedent(""" + import builtins + import types + + value = object() + module = types.SimpleNamespace(dom=value) + placeholder = [__lazy_import__("xml.dom", fromlist=())] + default_import = builtins.__import__ + default_lazy_import = builtins.__lazy_import__ + calls = [] + + def import_hook(name, globals, locals, fromlist, level): + assert name == "xml.dom", name + assert fromlist == (), fromlist + calls.append(fromlist) + return module + + builtins.__import__ = import_hook + assert placeholder[0].resolve() is module + builtins.__lazy_import__ = lambda *args: placeholder[0] + lazy import fake.dom as dom + assert dom is value + builtins.__import__ = default_import + builtins.__lazy_import__ = default_lazy_import + + assert calls == [(), ()], calls + """) + assert_python_ok("-c", code) + + + def test_dotted_as_replays_lookups_on_dotted_placeholder(self): + """A dotted lazy import as replays its names on the hook's package.""" + # importlib.metadata has a `metadata` attribute of its own, which the + # placeholder for importlib must not answer with. + for target in ("xml.dom", "importlib.metadata"): + with self.subTest(target=target): + leaf = target.rpartition(".")[2] + code = textwrap.dedent(f""" + import builtins + import sys + import {target} + + # In a list, so the hook reading it does not resolve it. + placeholder = [__lazy_import__("{target}", fromlist=())] + default = builtins.__lazy_import__ + builtins.__lazy_import__ = lambda *args: placeholder[0] + lazy import fake.{leaf} as {leaf} + builtins.__lazy_import__ = default + + name = repr(globals()["{leaf}"]) + assert name == "", name + assert {leaf} is sys.modules["{target}"], {leaf} + """) + assert_python_ok("-c", code) + + +class SubmoduleLazinessTests(unittest.TestCase): + """Tests that module-level lazy imports remain lazy until accessed.""" + + def tearDown(self): + for key in list(sys.modules.keys()): + if key.startswith('test.test_lazy_import.data'): + del sys.modules[key] + sys.set_lazy_imports_filter(None) + sys.set_lazy_imports("normal") + + def test_unaccessed_imports_stay_lazy(self): + """Imports in 'all' mode should stay lazy until accessed.""" + sys.set_lazy_imports("all") + from test.test_lazy_import.data.metasyntactic import names + self.assertIsInstance(names.__dict__["Foo"], types.LazyImportType) + self.assertNotIn( + "test.test_lazy_import.data.metasyntactic.foo", sys.modules + ) + _ = names.Foo + self.assertEqual(names.Foo, "Foo") + self.assertIn( + "test.test_lazy_import.data.metasyntactic.foo", sys.modules + ) + self.assertIsInstance(names.__dict__["Ack"], types.LazyImportType) + self.assertNotIn( + "test.test_lazy_import.data.metasyntactic.foo.ack", sys.modules + ) + + +class AttributeSideEffectTests(unittest.TestCase): + """Tests that submodule imports don't overwrite parent attributes.""" + + def tearDown(self): + for key in list(sys.modules.keys()): + if key.startswith('test.test_lazy_import.data'): + del sys.modules[key] + sys.set_lazy_imports_filter(None) + sys.set_lazy_imports("normal") + + def test_version_submodule_does_not_overwrite(self): + """A __version__ submodule should not overwrite the parent's + __version__ attribute imported in __init__.py.""" + import test.test_lazy_import.data.versioned as versioned + self.assertEqual(versioned.__version__, "1.0") + self.assertEqual( + versioned.__copyright__, + "Copyright (c) 2001-2022 Python Software Foundation.", + ) + + +class ModuleVariableNameCollisionTests(unittest.TestCase): + """Tests for name collision between a submodule and a variable.""" + + def tearDown(self): + for key in list(sys.modules.keys()): + if key.startswith('test.test_lazy_import.data'): + del sys.modules[key] + sys.set_lazy_imports_filter(None) + sys.set_lazy_imports("normal") + + def test_variable_after_import_wins(self): + """Variable assigned after import should overwrite the submodule.""" + from test.test_lazy_import.data import module_same_name_var_order1 + self.assertEqual(module_same_name_var_order1.bar, "Blah") + + def test_import_after_variable_wins(self): + """Import after variable assignment should overwrite the variable.""" + from test.test_lazy_import.data import module_same_name_var_order2 + bar_mod = sys.modules[ + "test.test_lazy_import.data.module_same_name_var_order2.bar" + ] + self.assertIs(module_same_name_var_order2.bar, bar_mod) + + +class DeletedModuleReimportTests(unittest.TestCase): + """Tests for reimporting after module deletion from sys.modules.""" + + def tearDown(self): + for key in list(sys.modules.keys()): + if key.startswith('test.test_lazy_import.data'): + del sys.modules[key] + sys.set_lazy_imports_filter(None) + sys.set_lazy_imports("normal") + + def test_reimport_creates_new_module(self): + """Deleting and reimporting should create a new module object.""" + import test.test_lazy_import.data.metasyntactic.foo + import test.test_lazy_import.data.metasyntactic.foo.bar.baz + + first_bar = test.test_lazy_import.data.metasyntactic.foo.bar + + del sys.modules[ + "test.test_lazy_import.data.metasyntactic.foo.bar" + ] + + import test.test_lazy_import.data.metasyntactic.foo.bar.thud + + second_bar = test.test_lazy_import.data.metasyntactic.foo.bar + + self.assertIsNot(first_bar, second_bar) + self.assertIn("baz", dir(first_bar)) + self.assertNotIn("thud", dir(first_bar)) + self.assertIn("thud", dir(second_bar)) + self.assertNotIn("baz", dir(second_bar)) + + +@support.requires_subprocess() +class CircularImportLazyTests(unittest.TestCase): + """Tests that lazy imports can break circular import patterns.""" + + def test_succeeds_with_lazy(self): + """Same-level circular imports should succeed with lazy mode.""" + proc = assert_python_ok( + "-X", "lazy_imports=all", "-c", + "import test.test_lazy_import.data.circular_import_pkg.main;" + "print('OK')", + ) + self.assertIn(b"OK", proc.out) + + def test_fails_without_lazy(self): + """Same-level circular imports should fail without lazy mode.""" + result = subprocess.run( + [sys.executable, "-c", + "import test.test_lazy_import.data.circular_import_pkg.main"], + capture_output=True, text=True, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("ImportError", result.stderr) + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_lazy_import/__main__.py b/Lib/test/test_lazy_import/__main__.py new file mode 100644 index 00000000000..d6c94efaf30 --- /dev/null +++ b/Lib/test/test_lazy_import/__main__.py @@ -0,0 +1,3 @@ +import unittest + +unittest.main('test.test_lazy_import') diff --git a/Lib/test/test_lazy_import/data/badsyntax/lazy_class_body.py b/Lib/test/test_lazy_import/data/badsyntax/lazy_class_body.py new file mode 100644 index 00000000000..e154b78f6cd --- /dev/null +++ b/Lib/test/test_lazy_import/data/badsyntax/lazy_class_body.py @@ -0,0 +1,3 @@ +# SyntaxError: lazy import inside class body is not allowed +class Foo: + lazy import json diff --git a/Lib/test/test_lazy_import/data/badsyntax/lazy_future_import.py b/Lib/test/test_lazy_import/data/badsyntax/lazy_future_import.py new file mode 100644 index 00000000000..8bd258b76b4 --- /dev/null +++ b/Lib/test/test_lazy_import/data/badsyntax/lazy_future_import.py @@ -0,0 +1 @@ +lazy from __future__ import annotations diff --git a/Lib/test/test_lazy_import/data/badsyntax/lazy_import_func.py b/Lib/test/test_lazy_import/data/badsyntax/lazy_import_func.py new file mode 100644 index 00000000000..af758b51127 --- /dev/null +++ b/Lib/test/test_lazy_import/data/badsyntax/lazy_import_func.py @@ -0,0 +1,2 @@ +def f(): + lazy import foo diff --git a/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except.py b/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except.py new file mode 100644 index 00000000000..e58d1f929ca --- /dev/null +++ b/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except.py @@ -0,0 +1,4 @@ +try: + lazy import foo +except: + pass diff --git a/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except_from.py b/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except_from.py new file mode 100644 index 00000000000..8c97553f486 --- /dev/null +++ b/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except_from.py @@ -0,0 +1,4 @@ +try: + lazy from foo import bar +except: + pass diff --git a/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except_from_star.py b/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except_from_star.py new file mode 100644 index 00000000000..b2370eaae77 --- /dev/null +++ b/Lib/test/test_lazy_import/data/badsyntax/lazy_try_except_from_star.py @@ -0,0 +1 @@ +lazy from foo import * diff --git a/Lib/test/test_lazy_import/data/basic2.py b/Lib/test/test_lazy_import/data/basic2.py new file mode 100644 index 00000000000..f93ec89d5ab --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic2.py @@ -0,0 +1,4 @@ +def f(): + pass + +x = 42 diff --git a/Lib/test/test_lazy_import/data/basic_compatibility_mode.py b/Lib/test/test_lazy_import/data/basic_compatibility_mode.py new file mode 100644 index 00000000000..33eeab8879c --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic_compatibility_mode.py @@ -0,0 +1,2 @@ +__lazy_modules__ = ['test.test_lazy_import.data.basic2'] +import test.test_lazy_import.data.basic2 diff --git a/Lib/test/test_lazy_import/data/basic_compatibility_mode_relative.py b/Lib/test/test_lazy_import/data/basic_compatibility_mode_relative.py new file mode 100644 index 00000000000..15c1ea77630 --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic_compatibility_mode_relative.py @@ -0,0 +1,2 @@ +__lazy_modules__ = ['test.test_lazy_import.data.basic2'] +lazy from .basic2 import f diff --git a/Lib/test/test_lazy_import/data/basic_compatibility_mode_used.py b/Lib/test/test_lazy_import/data/basic_compatibility_mode_used.py new file mode 100644 index 00000000000..78bb4ffa523 --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic_compatibility_mode_used.py @@ -0,0 +1,3 @@ +__lazy_modules__ = ['test.test_lazy_import.data.basic2'] +import test.test_lazy_import.data.basic2 +test.test_lazy_import.data.basic2.f() diff --git a/Lib/test/test_lazy_import/data/basic_dir.py b/Lib/test/test_lazy_import/data/basic_dir.py new file mode 100644 index 00000000000..a88c8ed80a1 --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic_dir.py @@ -0,0 +1,2 @@ +lazy import test.test_lazy_import.data.basic2 +x = dir() diff --git a/Lib/test/test_lazy_import/data/basic_from_unused.py b/Lib/test/test_lazy_import/data/basic_from_unused.py new file mode 100644 index 00000000000..62fa04bc8fa --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic_from_unused.py @@ -0,0 +1 @@ +lazy from test.test_lazy_import.data import basic2 diff --git a/Lib/test/test_lazy_import/data/basic_unused.py b/Lib/test/test_lazy_import/data/basic_unused.py new file mode 100644 index 00000000000..f3e502c59e7 --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic_unused.py @@ -0,0 +1 @@ +lazy import test.test_lazy_import.data.basic2 diff --git a/Lib/test/test_lazy_import/data/basic_used.py b/Lib/test/test_lazy_import/data/basic_used.py new file mode 100644 index 00000000000..7234bd2fe02 --- /dev/null +++ b/Lib/test/test_lazy_import/data/basic_used.py @@ -0,0 +1,3 @@ +lazy import test.test_lazy_import.data.basic2 as basic2 + +basic2.f() diff --git a/Lib/test/test_lazy_import/data/broken_attr_module.py b/Lib/test/test_lazy_import/data/broken_attr_module.py new file mode 100644 index 00000000000..a60bca2bad0 --- /dev/null +++ b/Lib/test/test_lazy_import/data/broken_attr_module.py @@ -0,0 +1,3 @@ +# Module that exists but doesn't have expected attributes +x = 42 +# No 'nonexistent_attr' here diff --git a/Lib/test/test_lazy_import/data/broken_module.py b/Lib/test/test_lazy_import/data/broken_module.py new file mode 100644 index 00000000000..b49d4a4a15f --- /dev/null +++ b/Lib/test/test_lazy_import/data/broken_module.py @@ -0,0 +1,2 @@ +# Module that raises an error during import +raise ValueError("This module always fails to import") diff --git a/Lib/test/test_lazy_import/data/broken_module_chained_cause.py b/Lib/test/test_lazy_import/data/broken_module_chained_cause.py new file mode 100644 index 00000000000..786607b7bb5 --- /dev/null +++ b/Lib/test/test_lazy_import/data/broken_module_chained_cause.py @@ -0,0 +1,3 @@ +# Module that raises an exception with explicit cause during import +cause = ValueError("Cause of failure") +raise ValueError("This module always fails to import") from cause diff --git a/Lib/test/test_lazy_import/data/broken_module_chained_context.py b/Lib/test/test_lazy_import/data/broken_module_chained_context.py new file mode 100644 index 00000000000..82640856e3e --- /dev/null +++ b/Lib/test/test_lazy_import/data/broken_module_chained_context.py @@ -0,0 +1,5 @@ +# Module that raises an exception with context during import +try: + raise ValueError("Cause of failure") +except: + raise ValueError("This module always fails to import") diff --git a/Lib/test/test_lazy_import/data/broken_module_chained_suppressed.py b/Lib/test/test_lazy_import/data/broken_module_chained_suppressed.py new file mode 100644 index 00000000000..5c34654afc1 --- /dev/null +++ b/Lib/test/test_lazy_import/data/broken_module_chained_suppressed.py @@ -0,0 +1,2 @@ +# Module that raises an exception with suppressed context during import +raise ValueError("This module always fails to import") from None diff --git a/Lib/test/test_importlib/resources/data02/__init__.py b/Lib/test/test_lazy_import/data/circular_import_pkg/__init__.py similarity index 100% rename from Lib/test/test_importlib/resources/data02/__init__.py rename to Lib/test/test_lazy_import/data/circular_import_pkg/__init__.py diff --git a/Lib/test/test_lazy_import/data/circular_import_pkg/main.py b/Lib/test/test_lazy_import/data/circular_import_pkg/main.py new file mode 100644 index 00000000000..0b897b377e2 --- /dev/null +++ b/Lib/test/test_lazy_import/data/circular_import_pkg/main.py @@ -0,0 +1,2 @@ +from .x import X2 +X2() diff --git a/Lib/test/test_lazy_import/data/circular_import_pkg/x.py b/Lib/test/test_lazy_import/data/circular_import_pkg/x.py new file mode 100644 index 00000000000..b44d5185c9e --- /dev/null +++ b/Lib/test/test_lazy_import/data/circular_import_pkg/x.py @@ -0,0 +1,7 @@ +def X1(): + return "X" + +from .y import Y1 + +def X2(): + return Y1() diff --git a/Lib/test/test_lazy_import/data/circular_import_pkg/y.py b/Lib/test/test_lazy_import/data/circular_import_pkg/y.py new file mode 100644 index 00000000000..d2385f7e67c --- /dev/null +++ b/Lib/test/test_lazy_import/data/circular_import_pkg/y.py @@ -0,0 +1,7 @@ +def Y1(): + return "Y" + +from .x import X2 + +def Y2(): + return X2() diff --git a/Lib/test/test_lazy_import/data/compatibility_mode_func.py b/Lib/test/test_lazy_import/data/compatibility_mode_func.py new file mode 100644 index 00000000000..9405d2f832b --- /dev/null +++ b/Lib/test/test_lazy_import/data/compatibility_mode_func.py @@ -0,0 +1,5 @@ +__lazy_modules__ = ['test.test_lazy_import.data.basic2'] +def f(): + import test.test_lazy_import.data.basic2 + +f() diff --git a/Lib/test/test_lazy_import/data/compatibility_mode_try_except.py b/Lib/test/test_lazy_import/data/compatibility_mode_try_except.py new file mode 100644 index 00000000000..a746c4a34a5 --- /dev/null +++ b/Lib/test/test_lazy_import/data/compatibility_mode_try_except.py @@ -0,0 +1,5 @@ +__lazy_modules__ = ['test.test_lazy_import.data.basic2'] +try: + import test.test_lazy_import.data.basic2 +except: + pass diff --git a/Lib/test/test_lazy_import/data/dunder_lazy_import.py b/Lib/test/test_lazy_import/data/dunder_lazy_import.py new file mode 100644 index 00000000000..c4f4d61623f --- /dev/null +++ b/Lib/test/test_lazy_import/data/dunder_lazy_import.py @@ -0,0 +1 @@ +basic = __lazy_import__('test.test_lazy_import.data.basic2') diff --git a/Lib/test/test_lazy_import/data/dunder_lazy_import_builtins.py b/Lib/test/test_lazy_import/data/dunder_lazy_import_builtins.py new file mode 100644 index 00000000000..8b6dbd7e3f6 --- /dev/null +++ b/Lib/test/test_lazy_import/data/dunder_lazy_import_builtins.py @@ -0,0 +1,14 @@ +import sys + +def myimport(*args): + return sys.modules[__name__] + + +new_globals = dict(globals()) +new_globals["__builtins__"] = { + "__import__": myimport, +} +basic2 = 42 +basic = __lazy_import__("test.test_lazy_import.data.basic2", + globals=new_globals) +basic diff --git a/Lib/test/test_lazy_import/data/dunder_lazy_import_used.py b/Lib/test/test_lazy_import/data/dunder_lazy_import_used.py new file mode 100644 index 00000000000..42c026994b1 --- /dev/null +++ b/Lib/test/test_lazy_import/data/dunder_lazy_import_used.py @@ -0,0 +1,3 @@ +basic = __lazy_import__('test.test_lazy_import.data', + fromlist=("basic2", )) +basic diff --git a/Lib/test/test_lazy_import/data/eager_import_func.py b/Lib/test/test_lazy_import/data/eager_import_func.py new file mode 100644 index 00000000000..1f7130209d4 --- /dev/null +++ b/Lib/test/test_lazy_import/data/eager_import_func.py @@ -0,0 +1,3 @@ +def f(): + import test.test_lazy_import.data.basic2 as basic2 + return basic2 diff --git a/Lib/test/test_lazy_import/data/global_filter.py b/Lib/test/test_lazy_import/data/global_filter.py new file mode 100644 index 00000000000..0e2311842df --- /dev/null +++ b/Lib/test/test_lazy_import/data/global_filter.py @@ -0,0 +1,10 @@ +import sys + +def filter(module_name, imported_name, from_list): + assert module_name == __name__ + assert imported_name == "test.test_lazy_import.data.basic2" + return False + +sys.set_lazy_imports_filter(filter) + +lazy import test.test_lazy_import.data.basic2 as basic2 diff --git a/Lib/test/test_lazy_import/data/global_filter_from.py b/Lib/test/test_lazy_import/data/global_filter_from.py new file mode 100644 index 00000000000..da9d22e8727 --- /dev/null +++ b/Lib/test/test_lazy_import/data/global_filter_from.py @@ -0,0 +1,11 @@ +import sys + +def filter(module_name, imported_name, from_list): + assert module_name == __name__ + assert imported_name == "test.test_lazy_import.data.basic2" + assert from_list == ('f',) + return False + +sys.set_lazy_imports_filter(filter) + +lazy from test.test_lazy_import.data.basic2 import f diff --git a/Lib/test/test_lazy_import/data/global_filter_from_true.py b/Lib/test/test_lazy_import/data/global_filter_from_true.py new file mode 100644 index 00000000000..2d8b1de4c7c --- /dev/null +++ b/Lib/test/test_lazy_import/data/global_filter_from_true.py @@ -0,0 +1,12 @@ +import sys + +def filter(module_name, imported_name, from_list): + assert module_name == __name__ + assert imported_name == "test.test_lazy_import.data.basic2" + assert from_list == ('f',) + return True + +sys.set_lazy_imports("normal") +sys.set_lazy_imports_filter(filter) + +lazy from test.test_lazy_import.data.basic2 import f diff --git a/Lib/test/test_lazy_import/data/global_filter_true.py b/Lib/test/test_lazy_import/data/global_filter_true.py new file mode 100644 index 00000000000..da4abeacf87 --- /dev/null +++ b/Lib/test/test_lazy_import/data/global_filter_true.py @@ -0,0 +1,11 @@ +import sys + +def filter(module_name, imported_name, from_list): + assert module_name == __name__ + assert imported_name == "test.test_lazy_import.data.basic2" + return True + +sys.set_lazy_imports("normal") +sys.set_lazy_imports_filter(filter) + +lazy import test.test_lazy_import.data.basic2 as basic2 diff --git a/Lib/test/test_lazy_import/data/global_on.py b/Lib/test/test_lazy_import/data/global_on.py new file mode 100644 index 00000000000..ddacab5468b --- /dev/null +++ b/Lib/test/test_lazy_import/data/global_on.py @@ -0,0 +1,5 @@ +import sys + +sys.set_lazy_imports("all") + +import test.test_lazy_import.data.basic2 as basic2 diff --git a/Lib/test/test_lazy_import/data/globals_access.py b/Lib/test/test_lazy_import/data/globals_access.py new file mode 100644 index 00000000000..af6fc40115b --- /dev/null +++ b/Lib/test/test_lazy_import/data/globals_access.py @@ -0,0 +1,9 @@ +# Test that globals() returns lazy proxy objects without reifying +lazy import test.test_lazy_import.data.basic2 as basic2 + +def get_from_globals(): + g = globals() + return g['basic2'] + +def get_direct(): + return basic2 diff --git a/Lib/test/test_lazy_import/data/init_fails.py b/Lib/test/test_lazy_import/data/init_fails.py new file mode 100644 index 00000000000..16e7ad363b0 --- /dev/null +++ b/Lib/test/test_lazy_import/data/init_fails.py @@ -0,0 +1,4 @@ +# Imported by test_initializing_module_is_still_tracked. The module it imports +# lazily imports this one back while this one is still initializing. +import test.test_lazy_import.data.lazy_on_init_fails +raise ValueError("initialization failed") diff --git a/Lib/test/test_lazy_import/data/lazy_compat_from.py b/Lib/test/test_lazy_import/data/lazy_compat_from.py new file mode 100644 index 00000000000..d6f7ed9a785 --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazy_compat_from.py @@ -0,0 +1,6 @@ +# Test __lazy_modules__ with from imports +__lazy_modules__ = ['test.test_lazy_import.data.basic2'] +from test.test_lazy_import.data.basic2 import x, f + +def get_x(): + return x diff --git a/Lib/test/test_lazy_import/data/lazy_get_value.py b/Lib/test/test_lazy_import/data/lazy_get_value.py new file mode 100644 index 00000000000..f216dc52f29 --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazy_get_value.py @@ -0,0 +1,7 @@ +lazy import test.test_lazy_import.data.basic2 as basic2 + +def f(): + x = globals() + return x['basic2'].resolve() + +f() diff --git a/Lib/test/test_lazy_import/data/lazy_import_pkg.py b/Lib/test/test_lazy_import/data/lazy_import_pkg.py new file mode 100644 index 00000000000..f237b50fd42 --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazy_import_pkg.py @@ -0,0 +1,2 @@ +lazy import test.test_lazy_import.data.pkg.bar +x = test.test_lazy_import.data.pkg.bar.f diff --git a/Lib/test/test_lazy_import/data/lazy_on_init_fails.py b/Lib/test/test_lazy_import/data/lazy_on_init_fails.py new file mode 100644 index 00000000000..7203fcbb4aa --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazy_on_init_fails.py @@ -0,0 +1 @@ +lazy import test.test_lazy_import.data.init_fails diff --git a/Lib/test/test_lazy_import/data/lazy_with.py b/Lib/test/test_lazy_import/data/lazy_with.py new file mode 100644 index 00000000000..30cf9d37762 --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazy_with.py @@ -0,0 +1,3 @@ +import contextlib +with contextlib.nullcontext(): + lazy import test.test_lazy_import.data.basic2 diff --git a/Lib/test/test_lazy_import/data/lazy_with_from.py b/Lib/test/test_lazy_import/data/lazy_with_from.py new file mode 100644 index 00000000000..794ba33f828 --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazy_with_from.py @@ -0,0 +1,3 @@ +import contextlib +with contextlib.nullcontext(): + lazy import test.test_lazy_import.data.basic2 as basic2 diff --git a/Lib/test/test_lazy_import/data/lazypkg/__init__.py b/Lib/test/test_lazy_import/data/lazypkg/__init__.py new file mode 100644 index 00000000000..276b51823fe --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazypkg/__init__.py @@ -0,0 +1 @@ +lazy from . import bar diff --git a/Lib/test/test_lazy_import/data/lazypkg/bar.py b/Lib/test/test_lazy_import/data/lazypkg/bar.py new file mode 100644 index 00000000000..b8d8b60b886 --- /dev/null +++ b/Lib/test/test_lazy_import/data/lazypkg/bar.py @@ -0,0 +1,2 @@ +print("BAR_MODULE_LOADED") +def f(): pass diff --git a/Lib/test/test_importlib/resources/data02/one/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/__init__.py similarity index 100% rename from Lib/test/test_importlib/resources/data02/one/__init__.py rename to Lib/test/test_lazy_import/data/metasyntactic/__init__.py diff --git a/Lib/test/test_lazy_import/data/metasyntactic/foo/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/foo/__init__.py new file mode 100644 index 00000000000..632a9fb87ac --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/foo/__init__.py @@ -0,0 +1 @@ +Foo = "Foo" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/foo/ack/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/foo/ack/__init__.py new file mode 100644 index 00000000000..c4c249f3b65 --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/foo/ack/__init__.py @@ -0,0 +1 @@ +Ack = "Ack" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/__init__.py new file mode 100644 index 00000000000..03faa550258 --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/__init__.py @@ -0,0 +1 @@ +Bar = "Bar" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/baz/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/baz/__init__.py new file mode 100644 index 00000000000..62d8366b440 --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/baz/__init__.py @@ -0,0 +1 @@ +Baz = "Baz" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/baz/qux/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/baz/qux/__init__.py new file mode 100644 index 00000000000..12389d76a28 --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/baz/qux/__init__.py @@ -0,0 +1 @@ +Qux = "Qux" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/thud/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/thud/__init__.py new file mode 100644 index 00000000000..a4dd8ab0fae --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/foo/bar/thud/__init__.py @@ -0,0 +1 @@ +Thud = "Thud" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/names.py b/Lib/test/test_lazy_import/data/metasyntactic/names.py new file mode 100644 index 00000000000..b2edf13e850 --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/names.py @@ -0,0 +1,9 @@ +from .foo import Foo +from .foo.ack import Ack +from .foo.bar import Bar +from .foo.bar.baz import Baz +from .foo.bar.thud import Thud +from .waldo import Waldo +from .waldo.fred import Fred +from .plugh import Plugh +Metasyntactic = "Metasyntactic" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/plugh/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/plugh/__init__.py new file mode 100644 index 00000000000..5db053204fc --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/plugh/__init__.py @@ -0,0 +1 @@ +Plugh = "Plugh" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/waldo/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/waldo/__init__.py new file mode 100644 index 00000000000..39f5a1b1838 --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/waldo/__init__.py @@ -0,0 +1 @@ +Waldo = "Waldo" diff --git a/Lib/test/test_lazy_import/data/metasyntactic/waldo/fred/__init__.py b/Lib/test/test_lazy_import/data/metasyntactic/waldo/fred/__init__.py new file mode 100644 index 00000000000..8c9dce1b3cf --- /dev/null +++ b/Lib/test/test_lazy_import/data/metasyntactic/waldo/fred/__init__.py @@ -0,0 +1 @@ +Fred = "Fred" diff --git a/Lib/test/test_lazy_import/data/missing_dependency.py b/Lib/test/test_lazy_import/data/missing_dependency.py new file mode 100644 index 00000000000..aa2f2d0f65f --- /dev/null +++ b/Lib/test/test_lazy_import/data/missing_dependency.py @@ -0,0 +1 @@ +import missing_dependency_for_lazy_import_test diff --git a/Lib/test/test_lazy_import/data/module_same_name_var_order1/__init__.py b/Lib/test/test_lazy_import/data/module_same_name_var_order1/__init__.py new file mode 100644 index 00000000000..b815b2a7d6f --- /dev/null +++ b/Lib/test/test_lazy_import/data/module_same_name_var_order1/__init__.py @@ -0,0 +1,3 @@ +from .bar import Bar +bar = "Blah" +Bar diff --git a/Lib/test/test_lazy_import/data/module_same_name_var_order1/bar.py b/Lib/test/test_lazy_import/data/module_same_name_var_order1/bar.py new file mode 100644 index 00000000000..03faa550258 --- /dev/null +++ b/Lib/test/test_lazy_import/data/module_same_name_var_order1/bar.py @@ -0,0 +1 @@ +Bar = "Bar" diff --git a/Lib/test/test_lazy_import/data/module_same_name_var_order2/__init__.py b/Lib/test/test_lazy_import/data/module_same_name_var_order2/__init__.py new file mode 100644 index 00000000000..008d199c73e --- /dev/null +++ b/Lib/test/test_lazy_import/data/module_same_name_var_order2/__init__.py @@ -0,0 +1,3 @@ +bar = "Blah" +from .bar import Bar +Bar diff --git a/Lib/test/test_lazy_import/data/module_same_name_var_order2/bar.py b/Lib/test/test_lazy_import/data/module_same_name_var_order2/bar.py new file mode 100644 index 00000000000..03faa550258 --- /dev/null +++ b/Lib/test/test_lazy_import/data/module_same_name_var_order2/bar.py @@ -0,0 +1 @@ +Bar = "Bar" diff --git a/Lib/test/test_lazy_import/data/module_with_getattr.py b/Lib/test/test_lazy_import/data/module_with_getattr.py new file mode 100644 index 00000000000..db3a2301075 --- /dev/null +++ b/Lib/test/test_lazy_import/data/module_with_getattr.py @@ -0,0 +1,12 @@ +def __getattr__(name): + if name == "dynamic_attr": + return "from_getattr" + elif name == "raising_attr": + raise ValueError("from_getattr") + elif name == "import_error_attr": + raise ImportError(name) + elif name == "warning_attr": + import warnings + warnings.warn("from_getattr", category=UserWarning) + return "from_warning_attr" + raise AttributeError(name) diff --git a/Lib/test/test_lazy_import/data/module_with_lazy_import_and_getattr.py b/Lib/test/test_lazy_import/data/module_with_lazy_import_and_getattr.py new file mode 100644 index 00000000000..e9a1f1a88e9 --- /dev/null +++ b/Lib/test/test_lazy_import/data/module_with_lazy_import_and_getattr.py @@ -0,0 +1,5 @@ +lazy import test.test_lazy_import.data.basic2 as basic2 +lazy from test.test_lazy_import.data.basic2 import f + +def __getattr__(name): + return f"from_getattr:{name}" diff --git a/Lib/test/test_lazy_import/data/modules_dict.py b/Lib/test/test_lazy_import/data/modules_dict.py new file mode 100644 index 00000000000..562a3b9a62f --- /dev/null +++ b/Lib/test/test_lazy_import/data/modules_dict.py @@ -0,0 +1,5 @@ +lazy import test.test_lazy_import.data.basic2 as basic2 + +import sys +mod = sys.modules[__name__] +x = mod.__dict__ diff --git a/Lib/test/test_lazy_import/data/modules_getattr.py b/Lib/test/test_lazy_import/data/modules_getattr.py new file mode 100644 index 00000000000..f0b8e2bd061 --- /dev/null +++ b/Lib/test/test_lazy_import/data/modules_getattr.py @@ -0,0 +1,5 @@ +lazy import test.test_lazy_import.data.basic2 as basic2 + +import sys +mod = sys.modules[__name__] +x = mod.basic2 diff --git a/Lib/test/test_lazy_import/data/modules_getattr_other.py b/Lib/test/test_lazy_import/data/modules_getattr_other.py new file mode 100644 index 00000000000..642840c2872 --- /dev/null +++ b/Lib/test/test_lazy_import/data/modules_getattr_other.py @@ -0,0 +1,5 @@ +lazy import test.test_lazy_import.data.basic2 as basic2 + +import sys +mod = sys.modules[__name__] +x = mod.__name__ diff --git a/Lib/test/test_lazy_import/data/multi_from_import.py b/Lib/test/test_lazy_import/data/multi_from_import.py new file mode 100644 index 00000000000..dfd875975dd --- /dev/null +++ b/Lib/test/test_lazy_import/data/multi_from_import.py @@ -0,0 +1,5 @@ +# Test that lazy from import with multiple names only reifies accessed names +lazy from test.test_lazy_import.data.basic2 import f, x + +def get_globals(): + return globals() diff --git a/Lib/test/test_lazy_import/data/pkg/__init__.py b/Lib/test/test_lazy_import/data/pkg/__init__.py new file mode 100644 index 00000000000..5f7b8662596 --- /dev/null +++ b/Lib/test/test_lazy_import/data/pkg/__init__.py @@ -0,0 +1,14 @@ +x = 42 + +def __getattr__(name): + if name == "dynamic_attr": + return "from_getattr" + elif name == "raising_attr": + raise ValueError("from_getattr") + elif name == "import_error_attr": + raise ImportError(name) + elif name == "warning_attr": + import warnings + warnings.warn("from_getattr", category=UserWarning) + return "from_warning_attr" + raise AttributeError(name) diff --git a/Lib/test/test_lazy_import/data/pkg/b.py b/Lib/test/test_lazy_import/data/pkg/b.py new file mode 100644 index 00000000000..a266b7c7c0d --- /dev/null +++ b/Lib/test/test_lazy_import/data/pkg/b.py @@ -0,0 +1,2 @@ +def foo(): + return 'foo' diff --git a/Lib/test/test_lazy_import/data/pkg/bar.py b/Lib/test/test_lazy_import/data/pkg/bar.py new file mode 100644 index 00000000000..b8d8b60b886 --- /dev/null +++ b/Lib/test/test_lazy_import/data/pkg/bar.py @@ -0,0 +1,2 @@ +print("BAR_MODULE_LOADED") +def f(): pass diff --git a/Lib/test/test_lazy_import/data/pkg/broken.py b/Lib/test/test_lazy_import/data/pkg/broken.py new file mode 100644 index 00000000000..6499aa9e150 --- /dev/null +++ b/Lib/test/test_lazy_import/data/pkg/broken.py @@ -0,0 +1,2 @@ +# Submodule that raises an error during import +raise ValueError("This module always fails to import") diff --git a/Lib/test/test_lazy_import/data/pkg/c.py b/Lib/test/test_lazy_import/data/pkg/c.py new file mode 100644 index 00000000000..0bb03119864 --- /dev/null +++ b/Lib/test/test_lazy_import/data/pkg/c.py @@ -0,0 +1,4 @@ +lazy from . import b, x + +def get_globals(): + return globals() diff --git a/Lib/test/test_lazy_import/data/relative_lazy.py b/Lib/test/test_lazy_import/data/relative_lazy.py new file mode 100644 index 00000000000..6273d3883ab --- /dev/null +++ b/Lib/test/test_lazy_import/data/relative_lazy.py @@ -0,0 +1,5 @@ +# Test relative imports with lazy keyword +lazy from . import basic2 + +def get_basic2(): + return basic2 diff --git a/Lib/test/test_lazy_import/data/relative_lazy_from.py b/Lib/test/test_lazy_import/data/relative_lazy_from.py new file mode 100644 index 00000000000..1bae2d6853d --- /dev/null +++ b/Lib/test/test_lazy_import/data/relative_lazy_from.py @@ -0,0 +1,8 @@ +# Test relative from imports with lazy keyword +lazy from .basic2 import x, f + +def get_x(): + return x + +def get_f(): + return f diff --git a/Lib/test/test_lazy_import/data/self_named_module_not_found.py b/Lib/test/test_lazy_import/data/self_named_module_not_found.py new file mode 100644 index 00000000000..941230d5da2 --- /dev/null +++ b/Lib/test/test_lazy_import/data/self_named_module_not_found.py @@ -0,0 +1 @@ +raise ModuleNotFoundError("boom", name=__name__) diff --git a/Lib/test/test_lazy_import/data/try_except_eager.py b/Lib/test/test_lazy_import/data/try_except_eager.py new file mode 100644 index 00000000000..90b4bc62898 --- /dev/null +++ b/Lib/test/test_lazy_import/data/try_except_eager.py @@ -0,0 +1,4 @@ +try: + import test.test_lazy_import.data.basic2 +except: + pass diff --git a/Lib/test/test_lazy_import/data/try_except_eager_from.py b/Lib/test/test_lazy_import/data/try_except_eager_from.py new file mode 100644 index 00000000000..1e6c650d0d1 --- /dev/null +++ b/Lib/test/test_lazy_import/data/try_except_eager_from.py @@ -0,0 +1,4 @@ +try: + from test.test_lazy_import.data.basic2 import f +except: + pass diff --git a/Lib/test/test_lazy_import/data/versioned/__init__.py b/Lib/test/test_lazy_import/data/versioned/__init__.py new file mode 100644 index 00000000000..be5bb3f8e60 --- /dev/null +++ b/Lib/test/test_lazy_import/data/versioned/__init__.py @@ -0,0 +1,2 @@ +from .__version__ import __version__ +from .__version__ import __copyright__ diff --git a/Lib/test/test_lazy_import/data/versioned/__version__.py b/Lib/test/test_lazy_import/data/versioned/__version__.py new file mode 100644 index 00000000000..37a10438735 --- /dev/null +++ b/Lib/test/test_lazy_import/data/versioned/__version__.py @@ -0,0 +1,2 @@ +__version__ = "1.0" +__copyright__ = "Copyright (c) 2001-2022 Python Software Foundation." diff --git a/Lib/test/test_linecache.py b/Lib/test/test_linecache.py index 02f65338428..202e30e6f6c 100644 --- a/Lib/test/test_linecache.py +++ b/Lib/test/test_linecache.py @@ -1,13 +1,18 @@ """ Tests for the linecache module """ +import importlib import linecache import unittest import os.path +import sys import tempfile import threading import tokenize +import zipfile +import zipimport from importlib.machinery import ModuleSpec from test import support +from test.support import import_helper from test.support import os_helper from test.support import threading_helper from test.support.script_helper import assert_python_ok @@ -259,22 +264,44 @@ def raise_memoryerror(*args, **kwargs): def test_loader(self): filename = 'scheme://path' - for loader in (None, object(), NoSourceLoader()): + linecache.clearcache() + module_globals = {'__name__': 'a.b.c', '__loader__': None} + self.assertEqual(linecache.getlines(filename, module_globals), []) + + for loader in object(), NoSourceLoader(): linecache.clearcache() module_globals = {'__name__': 'a.b.c', '__loader__': loader} - self.assertEqual(linecache.getlines(filename, module_globals), []) + with self.assertWarns(DeprecationWarning) as w: + self.assertEqual(linecache.getlines(filename, module_globals), []) + self.assertEqual(str(w.warning), + 'Module globals is missing a __spec__.loader') linecache.clearcache() module_globals = {'__name__': 'a.b.c', '__loader__': FakeLoader()} - self.assertEqual(linecache.getlines(filename, module_globals), - ['source for a.b.c\n']) + with self.assertWarns(DeprecationWarning) as w: + self.assertEqual(linecache.getlines(filename, module_globals), + ['source for a.b.c\n']) + self.assertEqual(str(w.warning), + 'Module globals is missing a __spec__.loader') - for spec in (None, object(), ModuleSpec('', FakeLoader())): + for spec in None, object(): linecache.clearcache() module_globals = {'__name__': 'a.b.c', '__loader__': FakeLoader(), '__spec__': spec} + with self.assertWarns(DeprecationWarning) as w: + self.assertEqual(linecache.getlines(filename, module_globals), + ['source for a.b.c\n']) + self.assertEqual(str(w.warning), + 'Module globals is missing a __spec__.loader') + + linecache.clearcache() + module_globals = {'__name__': 'a.b.c', '__loader__': FakeLoader(), + '__spec__': ModuleSpec('', FakeLoader())} + with self.assertWarns(DeprecationWarning) as w: self.assertEqual(linecache.getlines(filename, module_globals), ['source for a.b.c\n']) + self.assertEqual(str(w.warning), + 'Module globals; __loader__ != __spec__.loader') linecache.clearcache() spec = ModuleSpec('x.y.z', FakeLoader()) @@ -334,6 +361,17 @@ def test_linecache_python_string(self): self.assertEqual(stdout, b'') self.assertEqual(stderr, b'') + def test_path_importer_cache_None(self): + # sys.path_importer_cache is set to None while the interpreter is + # shutting down, before objects with a __del__ that may end up here + # are released. + filename = os.path.abspath(os_helper.TESTFN + '.py') + with support.swap_attr(sys, 'path_importer_cache', None): + self.assertEqual(linecache.getlines(filename), []) + self.assertEqual(linecache.getline(filename, 1), '') + self.assertNotIn(filename, linecache.cache) + + class LineCacheInvalidationTests(unittest.TestCase): def setUp(self): super().setUp() @@ -376,6 +414,98 @@ def test_checkcache_with_no_parameter(self): self.assertIn(self.unchanged_file, linecache.cache) +class ZipArchiveTests(unittest.TestCase): + """Sources of modules imported from a zip archive on sys.path.""" + + MODULE_SOURCE = ( + '"""A module inside a zip archive."""\n' + '\n' + 'def f():\n' + ' return "from the zip"\n' + ) + PACKAGE_SOURCE = 'value = 42\n' + LATIN1_SOURCE = ( + '# -*- coding: latin-1 -*-\n' + 'value = "caf\xe9"\n' + ) + + def setUp(self): + linecache.clearcache() + self.addCleanup(linecache.clearcache) + tmpdir = self.enterContext(os_helper.temp_dir()) + self.zip_name = os.path.join(tmpdir, 'sources.zip') + with zipfile.ZipFile(self.zip_name, 'w') as zf: + zf.writestr('zipmod.py', self.MODULE_SOURCE) + zf.writestr('zippkg/__init__.py', self.PACKAGE_SOURCE) + zf.writestr('ziplatin1.py', self.LATIN1_SOURCE.encode('latin-1')) + self.enterContext(import_helper.DirsOnSysPath(self.zip_name)) + for name in 'zipmod', 'zippkg', 'ziplatin1': + self.addCleanup(import_helper.unload, name) + self.addCleanup(sys.path_importer_cache.pop, self.zip_name, None) + self.addCleanup(zipimport._zip_directory_cache.pop, + self.zip_name, None) + self.zipmod = importlib.import_module('zipmod') + + def test_getlines_without_module_globals(self): + filename = self.zipmod.__file__ + self.assertEqual(filename, os.path.join(self.zip_name, 'zipmod.py')) + self.assertFalse(os.path.exists(filename)) + lines = self.MODULE_SOURCE.splitlines(keepends=True) + self.assertEqual(linecache.getlines(filename), lines) + self.assertEqual(linecache.getline(filename, 4), + ' return "from the zip"\n') + self.assertEqual(linecache.getline(filename, 5), '') + code = self.zipmod.f.__code__ + self.assertEqual(code.co_filename, filename) + self.assertEqual(linecache.getline(filename, code.co_firstlineno), + 'def f():\n') + + def test_relative_archive_path(self): + # A relative sys.path entry gives its modules a relative __file__. + tmpdir, zip_base = os.path.split(self.zip_name) + self.addCleanup(sys.path_importer_cache.pop, zip_base, None) + self.addCleanup(zipimport._zip_directory_cache.pop, zip_base, None) + sys.path.insert(0, zip_base) + self.addCleanup(sys.path.remove, zip_base) + with os_helper.change_cwd(tmpdir): + zippkg = importlib.import_module('zippkg') + self.assertEqual(zippkg.__file__, + os.path.join(zip_base, 'zippkg', '__init__.py')) + self.assertEqual(linecache.getlines(zippkg.__file__), + ['value = 42\n']) + + def test_package(self): + zippkg = importlib.import_module('zippkg') + self.assertEqual(linecache.getlines(zippkg.__file__), + ['value = 42\n']) + + def test_encoding_declaration(self): + ziplatin1 = importlib.import_module('ziplatin1') + self.assertEqual(linecache.getlines(ziplatin1.__file__), + self.LATIN1_SOURCE.splitlines(keepends=True)) + + def test_missing_file(self): + filename = os.path.join(self.zip_name, 'missing.py') + self.assertEqual(linecache.getlines(filename), []) + self.assertEqual(linecache.getline(filename, 1), '') + self.assertNotIn(filename, linecache.cache) + + def test_checkcache_and_clearcache(self): + filename = self.zipmod.__file__ + lines = linecache.getlines(filename) + self.assertIn(filename, linecache.cache) + # A file inside an archive has no mtime of its own, so checkcache() + # keeps the entry, as it does for entries loaded through a loader. + self.assertIsNone(linecache.cache[filename][1]) + linecache.checkcache(filename) + linecache.checkcache() + self.assertIn(filename, linecache.cache) + self.assertEqual(linecache.getlines(filename), lines) + linecache.clearcache() + self.assertNotIn(filename, linecache.cache) + self.assertEqual(linecache.getlines(filename), lines) + + class MultiThreadingTest(unittest.TestCase): @threading_helper.reap_threads @threading_helper.requires_working_threading() diff --git a/Lib/test/test_listcomps.py b/Lib/test/test_listcomps.py index b7580867ea7..cf3796d9480 100644 --- a/Lib/test/test_listcomps.py +++ b/Lib/test/test_listcomps.py @@ -793,28 +793,6 @@ def iter_raises(): self.assertEqual(f.line[f.colno - indent : f.end_colno - indent], expected) - def test_only_calls_dunder_iter_once(self): - - class Iterator: - - def __init__(self): - self.val = 0 - - def __next__(self): - if self.val == 2: - raise StopIteration - self.val += 1 - return self.val - - # No __iter__ method - - class C: - - def __iter__(self): - return Iterator() - - self.assertEqual([1, 2], [i for i in C()]) - __test__ = {'doctests' : doctests} def load_tests(loader, tests, pattern): diff --git a/Lib/test/test_locale.py b/Lib/test/test_locale.py index f91843562c3..a06c600cf56 100644 --- a/Lib/test/test_locale.py +++ b/Lib/test/test_locale.py @@ -1,4 +1,5 @@ from decimal import Decimal +from test import support from test.support import cpython_only, verbose, is_android, linked_to_musl, os_helper from test.support.import_helper import ensure_lazy_imports, import_fresh_module from unittest import mock @@ -423,8 +424,8 @@ def test_hyphenated_encoding(self): self.check('cs_CZ.ISO8859-2', 'cs_CZ.ISO8859-2') def test_euro_modifier(self): - self.check('de_DE@euro', 'de_DE.ISO8859-15') - self.check('en_US.ISO8859-15@euro', 'en_US.ISO8859-15') + self.check('de_DE@euro', 'de_DE.ISO8859-15@euro') + self.check('en_US.ISO8859-15@euro', 'en_US.ISO8859-15@euro') self.check('de_DE.utf8@euro', 'de_DE.UTF-8') def test_latin_modifier(self): @@ -532,6 +533,105 @@ def test_setlocale_long_encoding(self): with self.assertRaises(locale.Error): locale.setlocale(locale.LC_ALL, loc2) + @support.subTests('localename,localetuple', [ + ('fr_FR.ISO8859-15@euro', ('fr_FR@euro', 'iso885915')), + ('fr_FR.ISO8859-15@euro', ('fr_FR@euro', 'iso88591')), + ('fr_FR.ISO8859-15@euro', ('fr_FR@euro', 'ISO8859-15')), + ('fr_FR.ISO8859-15@euro', ('fr_FR@euro', 'ISO8859-1')), + ('fr_FR.ISO8859-15@euro', ('fr_FR@euro', None)), + ('de_DE.ISO8859-15@euro', ('de_DE@euro', 'iso885915')), + ('de_DE.ISO8859-15@euro', ('de_DE@euro', 'iso88591')), + ('de_DE.ISO8859-15@euro', ('de_DE@euro', 'ISO8859-15')), + ('de_DE.ISO8859-15@euro', ('de_DE@euro', 'ISO8859-1')), + ('de_DE.ISO8859-15@euro', ('de_DE@euro', None)), + ('el_GR.ISO8859-7@euro', ('el_GR@euro', 'iso88597')), + ('el_GR.ISO8859-7@euro', ('el_GR@euro', 'ISO8859-7')), + ('el_GR.ISO8859-7@euro', ('el_GR@euro', None)), + ('ca_ES.ISO8859-15@euro', ('ca_ES@euro', 'iso885915')), + ('ca_ES.ISO8859-15@euro', ('ca_ES@euro', 'iso88591')), + ('ca_ES.ISO8859-15@euro', ('ca_ES@euro', 'ISO8859-15')), + ('ca_ES.ISO8859-15@euro', ('ca_ES@euro', 'ISO8859-1')), + ('ca_ES.ISO8859-15@euro', ('ca_ES@euro', None)), + ('ca_ES.UTF-8@valencia', ('ca_ES@valencia', 'utf8')), + ('ca_ES.UTF-8@valencia', ('ca_ES@valencia', 'UTF-8')), + ('ca_ES.UTF-8@valencia', ('ca_ES@valencia', None)), + ('ks_IN.UTF-8@devanagari', ('ks_IN@devanagari', 'utf8')), + ('ks_IN.UTF-8@devanagari', ('ks_IN@devanagari', 'UTF-8')), + ('ks_IN.UTF-8@devanagari', ('ks_IN@devanagari', None)), + ('sd_IN.UTF-8@devanagari', ('sd_IN@devanagari', 'utf8')), + ('sd_IN.UTF-8@devanagari', ('sd_IN@devanagari', 'UTF-8')), + ('sd_IN.UTF-8@devanagari', ('sd_IN@devanagari', None)), + ('be_BY.UTF-8@latin', ('be_BY@latin', 'utf8')), + ('be_BY.UTF-8@latin', ('be_BY@latin', 'UTF-8')), + ('be_BY.UTF-8@latin', ('be_BY@latin', None)), + ('sr_RS.UTF-8@latin', ('sr_RS@latin', 'utf8')), + ('sr_RS.UTF-8@latin', ('sr_RS@latin', 'UTF-8')), + ('sr_RS.UTF-8@latin', ('sr_RS@latin', None)), + ('ug_CN.UTF-8@latin', ('ug_CN@latin', 'utf8')), + ('ug_CN.UTF-8@latin', ('ug_CN@latin', 'UTF-8')), + ('ug_CN.UTF-8@latin', ('ug_CN@latin', None)), + ('uz_UZ.UTF-8@cyrillic', ('uz_UZ@cyrillic', 'utf8')), + ('uz_UZ.UTF-8@cyrillic', ('uz_UZ@cyrillic', 'UTF-8')), + ('uz_UZ.UTF-8@cyrillic', ('uz_UZ@cyrillic', None)), + ]) + def test_setlocale_with_modifier(self, localename, localetuple): + try: + locale.setlocale(locale.LC_CTYPE, localename) + except locale.Error as exc: + self.skipTest(str(exc)) + loc = locale.setlocale(locale.LC_CTYPE, localetuple) + self.assertEqual(loc, localename) + + loctuple = locale.getlocale(locale.LC_CTYPE) + loc = locale.setlocale(locale.LC_CTYPE, loctuple) + self.assertEqual(loc, localename) + + @support.subTests('localename,localetuple', [ + ('fr_FR.iso885915@euro', ('fr_FR@euro', 'ISO8859-15')), + ('fr_FR.ISO8859-15@euro', ('fr_FR@euro', 'ISO8859-15')), + ('fr_FR@euro', ('fr_FR@euro', 'ISO8859-15')), + ('de_DE.iso885915@euro', ('de_DE@euro', 'ISO8859-15')), + ('de_DE.ISO8859-15@euro', ('de_DE@euro', 'ISO8859-15')), + ('de_DE@euro', ('de_DE@euro', 'ISO8859-15')), + ('el_GR.iso88597@euro', ('el_GR@euro', 'ISO8859-7')), + ('el_GR.ISO8859-7@euro', ('el_GR@euro', 'ISO8859-7')), + ('el_GR@euro', ('el_GR@euro', 'ISO8859-7')), + ('ca_ES.iso885915@euro', ('ca_ES@euro', 'ISO8859-15')), + ('ca_ES.ISO8859-15@euro', ('ca_ES@euro', 'ISO8859-15')), + ('ca_ES@euro', ('ca_ES@euro', 'ISO8859-15')), + ('ca_ES.utf8@valencia', ('ca_ES@valencia', 'UTF-8')), + ('ca_ES.UTF-8@valencia', ('ca_ES@valencia', 'UTF-8')), + ('ca_ES@valencia', ('ca_ES@valencia', 'UTF-8')), + ('ks_IN.utf8@devanagari', ('ks_IN@devanagari', 'UTF-8')), + ('ks_IN.UTF-8@devanagari', ('ks_IN@devanagari', 'UTF-8')), + ('ks_IN@devanagari', ('ks_IN@devanagari', 'UTF-8')), + ('sd_IN.utf8@devanagari', ('sd_IN@devanagari', 'UTF-8')), + ('sd_IN.UTF-8@devanagari', ('sd_IN@devanagari', 'UTF-8')), + ('sd_IN@devanagari', ('sd_IN@devanagari', 'UTF-8')), + ('be_BY.utf8@latin', ('be_BY@latin', 'UTF-8')), + ('be_BY.UTF-8@latin', ('be_BY@latin', 'UTF-8')), + ('be_BY@latin', ('be_BY@latin', 'UTF-8')), + ('sr_RS.utf8@latin', ('sr_RS@latin', 'UTF-8')), + ('sr_RS.UTF-8@latin', ('sr_RS@latin', 'UTF-8')), + ('sr_RS@latin', ('sr_RS@latin', 'UTF-8')), + ('ug_CN.utf8@latin', ('ug_CN@latin', 'UTF-8')), + ('ug_CN.UTF-8@latin', ('ug_CN@latin', 'UTF-8')), + ('ug_CN@latin', ('ug_CN@latin', 'UTF-8')), + ('uz_UZ.utf8@cyrillic', ('uz_UZ@cyrillic', 'UTF-8')), + ('uz_UZ.UTF-8@cyrillic', ('uz_UZ@cyrillic', 'UTF-8')), + ('uz_UZ@cyrillic', ('uz_UZ@cyrillic', 'UTF-8')), + ]) + def test_getlocale_with_modifier(self, localename, localetuple): + try: + locale.setlocale(locale.LC_CTYPE, localename) + except locale.Error as exc: + self.skipTest(str(exc)) + loctuple = locale.getlocale(locale.LC_CTYPE) + self.assertEqual(loctuple, localetuple) + + locale.setlocale(locale.LC_CTYPE, loctuple) + self.assertEqual(locale.getlocale(locale.LC_CTYPE), localetuple) + class TestMiscellaneous(unittest.TestCase): def test_defaults_UTF8(self): diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py index 69364b0575d..0287e527ae4 100644 --- a/Lib/test/test_logging.py +++ b/Lib/test/test_logging.py @@ -62,7 +62,7 @@ import weakref from http.server import HTTPServer, BaseHTTPRequestHandler -from unittest.mock import patch +from unittest.mock import call, Mock, patch from urllib.parse import urlparse, parse_qs from socketserver import (ThreadingUDPServer, DatagramRequestHandler, ThreadingTCPServer, StreamRequestHandler) @@ -404,6 +404,20 @@ def test_empty_filter(self): r = logging.makeLogRecord({'name': 'spam.eggs'}) self.assertTrue(f.filter(r)) + def test_filter_repr(self): + f = logging.Filter('myapp') + self.assertEqual(repr(f), '') + + def test_filter_repr_empty(self): + f = logging.Filter() + self.assertEqual(repr(f), '') + + def test_filter_repr_subclass(self): + class MyFilter(logging.Filter): + pass + f = MyFilter('myapp') + self.assertEqual(repr(f), '') + # # First, we define our levels. There can be as many as you want - the only # limitations are that they should be integers, the lowest should be > 0 and @@ -731,6 +745,7 @@ def remove_loop(fname, tries): # based on os.fork existing because that is what users and this test use. # This helps ensure that when fork exists (the important concept) that the # register_at_fork mechanism is also present and used. + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.requires_fork() @threading_helper.requires_working_threading() @skip_if_asan_fork @@ -799,6 +814,23 @@ def lock_holder_thread_fn(): support.wait_process(pid, exitcode=0) + def test_remove_handler_while_emitting(self): + # Removing a handler while callHandlers() iterates over the handlers + # should not cause the following handlers to be skipped (gh-79366). + logger = logging.Logger('test_remove_handler_while_emitting') + calls = [] + class RemovingHandler(logging.Handler): + def emit(self, record): + calls.append('removing') + logger.removeHandler(self) + class CountingHandler(logging.Handler): + def emit(self, record): + calls.append('counting') + logger.addHandler(RemovingHandler()) + logger.addHandler(CountingHandler()) + logger.error('spam') + self.assertEqual(calls, ['removing', 'counting']) + class BadStream(object): def write(self, data): @@ -2140,6 +2172,24 @@ def tearDown(self): self.server_class.address_family = socket.AF_INET super(IPv6SysLogHandlerTest, self).tearDown() +@support.requires_working_socket() +class UnresolvableSysLogAddressTest(BaseTest): + + """Test for SysLogHandler with a temporarily unresolvable address.""" + + @patch('socket.getaddrinfo') + def test_unresolvable_address(self, mock_getaddrinfo): + # The address can be unresolvable when the handler is created. + mock_getaddrinfo.side_effect = socket.gaierror + hdlr = logging.handlers.SysLogHandler(('localhost', 514)) + self.addCleanup(hdlr.close) + self.assertIsNone(hdlr.socket) + # It is resolved again when a record is emitted. + calls = mock_getaddrinfo.call_count + with support.captured_stderr(): + hdlr.emit(logging.makeLogRecord({'msg': 'sp\xe4m'})) + self.assertGreater(mock_getaddrinfo.call_count, calls) + @support.requires_working_socket() @threading_helper.requires_working_threading() class HTTPHandlerTest(BaseTest): @@ -3634,14 +3684,14 @@ def setup_via_listener(self, text, verify=None): # Ask for a randomly assigned port (by using port 0) t = logging.config.listen(0, verify) t.start() - t.ready.wait() + self.assertTrue(t.ready.wait(support.LONG_TIMEOUT), + msg='the listener did not start') # Now get the port allocated port = t.port t.ready.clear() try: - sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - sock.settimeout(2.0) - sock.connect(('localhost', port)) + # The server can listen on IPv6, so do not force a family. + sock = socket.create_connection(('localhost', port), timeout=2.0) slen = struct.pack('>L', len(text)) s = slen + text @@ -3756,6 +3806,18 @@ def verify_reverse(stuff): ('ERROR', '2'), ], pat=r"^[\w.]+ -> (\w+): (\d+)$") + @support.requires_working_socket() + def test_listen_server_error(self): + # The "ready" event should be set even if the server fails to start. + t = logging.config.listen(-1) + t.daemon = True + with threading_helper.catch_threading_exception() as cm: + t.start() + self.assertTrue(t.ready.wait(support.SHORT_TIMEOUT), + msg='the listener did not report the failure') + threading_helper.join_thread(t) + self.assertIs(cm.exc_type, OverflowError) + def test_bad_format(self): self.assertRaises(ValueError, self.apply_config, self.bad_format) @@ -4046,6 +4108,7 @@ def test_config_queue_handler_invalid_config_does_not_create_multiprocessing_man self._apply_simple_queue_listener_configuration(qspec) manager.assert_not_called() + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @skip_if_tsan_fork @support.requires_subprocess() @unittest.skipUnless(support.Py_DEBUG, "requires a debug build for testing" @@ -4068,6 +4131,7 @@ def test_config_reject_simple_queue_handler_multiprocessing_context(self): with self.assertRaises(ValueError): self._apply_simple_queue_listener_configuration(qspec) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @skip_if_tsan_fork @support.requires_subprocess() @unittest.skipUnless(support.Py_DEBUG, "requires a debug build for testing" @@ -4108,6 +4172,7 @@ def _mpinit_issue121723(qspec, message_to_log): # log a message (this creates a record put in the queue) logging.getLogger().info(message_to_log) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @skip_if_tsan_fork @support.requires_subprocess() def test_multiprocessing_queues(self): @@ -4632,7 +4697,6 @@ def test_dollars(self): f = logging.Formatter('${asctime}--', style='$') self.assertTrue(f.usesTime()) - @unittest.expectedFailure # TODO: RUSTPYTHON; ValueError: Unexpected error parsing format string def test_format_validate(self): # Check correct formatting # Percentage style @@ -4911,6 +4975,20 @@ def test_relativeCreated_has_higher_precision(self): # After PR gh-102412, precision (places) increases from 3 to 7 self.assertAlmostEqual(relativeCreated, offset_ns / 1e6, places=7) + def test_formatter_repr(self): + f = logging.Formatter('%(message)s') + self.assertEqual(repr(f), '') + + def test_formatter_repr_default(self): + f = logging.Formatter() + self.assertEqual(repr(f), '') + + def test_formatter_repr_subclass(self): + class MyFormatter(logging.Formatter): + pass + f = MyFormatter('%(message)s') + self.assertEqual(repr(f), '') + class TestBufferingFormatter(logging.BufferingFormatter): def formatHeader(self, records): @@ -5339,6 +5417,7 @@ def _extract_logrecord_process_name(key, logMultiprocessing, conn=None): else: return results + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @skip_if_tsan_fork def test_multiprocessing(self): support.skip_if_broken_multiprocessing_synchronize() @@ -5574,12 +5653,19 @@ def test_incompatible(self): assertRaises = self.assertRaises handlers = [logging.StreamHandler()] stream = sys.stderr + formatter = logging.Formatter() assertRaises(ValueError, logging.basicConfig, filename='test.log', stream=stream) assertRaises(ValueError, logging.basicConfig, filename='test.log', handlers=handlers) assertRaises(ValueError, logging.basicConfig, stream=stream, handlers=handlers) + assertRaises(ValueError, logging.basicConfig, formatter=formatter, + format='%(message)s') + assertRaises(ValueError, logging.basicConfig, formatter=formatter, + datefmt='%H:%M:%S') + assertRaises(ValueError, logging.basicConfig, formatter=formatter, + style='%') # Issue 23207: test for invalid kwargs assertRaises(ValueError, logging.basicConfig, loglevel=logging.INFO) # Should pop both filename and filemode even if filename is None @@ -5714,6 +5800,20 @@ def dummy_handle_error(record): # didn't write anything due to the encoding error self.assertEqual(data, r'') + def test_formatter_given(self): + mock_formatter = Mock() + mock_handler = Mock(formatter=None) + with patch("logging.Formatter") as mock_formatter_init: + logging.basicConfig(formatter=mock_formatter, handlers=[mock_handler]) + self.assertEqual(mock_handler.setFormatter.call_args_list, [call(mock_formatter)]) + self.assertEqual(mock_formatter_init.call_count, 0) + + def test_formatter_not_given(self): + mock_handler = Mock(formatter=None) + with patch("logging.Formatter") as mock_formatter_init: + logging.basicConfig(handlers=[mock_handler]) + self.assertEqual(mock_formatter_init.call_count, 1) + @support.requires_working_socket() def test_log_taskName(self): async def log_record(): @@ -6276,11 +6376,12 @@ def setUp(self): self.rmfiles = [] def tearDown(self): - for fn in self.rmfiles: - os.unlink(fn) - if os.path.exists(self.fn): - os.unlink(self.fn) - BaseTest.tearDown(self) + try: + for fn in self.rmfiles: + os_helper.unlink(fn) + os_helper.unlink(self.fn) + finally: + BaseTest.tearDown(self) def assertLogFile(self, filename): "Assert a log file is there and register it for deletion" @@ -6314,6 +6415,46 @@ def test_emit_after_closing_in_write_mode(self): with open(self.fn) as fp: self.assertEqual(fp.read().strip(), '1') + def _check_open_error(self, h): + # gh-135683: an error while opening the file in emit() respects + # raiseExceptions, like an error during the actual write. + r = logging.makeLogRecord({}) + old_raise = logging.raiseExceptions + self.addCleanup(setattr, logging, 'raiseExceptions', old_raise) + + logging.raiseExceptions = True + with support.captured_stderr() as stderr: + h.handle(r) + self.assertIn('\nFileNotFoundError:', stderr.getvalue()) + + logging.raiseExceptions = False + with support.captured_stderr() as stderr: + h.handle(r) + self.assertEqual('', stderr.getvalue()) + + def test_emit_open_error(self): + # FileHandler with delay: the failing open happens in emit(). + d = tempfile.mkdtemp() + self.addCleanup(os_helper.rmtree, d) + h = logging.FileHandler(os.path.join(d, 'missing', 'a.log'), + encoding='utf-8', delay=True) + self.addCleanup(h.close) + self._check_open_error(h) + + @unittest.skipIf(os.name == 'nt', + 'WatchedFileHandler not appropriate for Windows.') + def test_emit_reopen_error(self): + # WatchedFileHandler: reopenIfNeeded() fails after the dir is removed. + d = tempfile.mkdtemp() + self.addCleanup(os_helper.rmtree, d) + subdir = os.path.join(d, 'sub') + os.mkdir(subdir) + h = logging.handlers.WatchedFileHandler( + os.path.join(subdir, 'b.log'), encoding='utf-8') + self.addCleanup(h.close) + os_helper.rmtree(subdir) + self._check_open_error(h) + class RotatingFileHandlerTest(BaseFileTest): def test_should_not_rollover(self): # If file is empty rollover never occurs @@ -6596,6 +6737,75 @@ def test_rollover_at_midnight(self, weekly=False): def test_rollover_at_weekday(self): self.test_rollover_at_midnight(weekly=True) + def _make_fake_time_handler(self, now, when='S', **kwargs): + dirname = tempfile.mkdtemp() + self.addCleanup(os_helper.rmtree, dirname) + fn = os.path.join(dirname, 'test.log') + with patch('time.time', lambda: now[0]): + fh = logging.handlers.TimedRotatingFileHandler( + fn, when=when, encoding='utf-8', delay=True, **kwargs) + self.addCleanup(fh.close) + return fh + + def test_rollover_after_failed_rollover(self): + for target in 'os.remove', '_open': + with self.subTest(target=target): + now = [1_000_000_000] + fh = self._make_fake_time_handler(now, backupCount=1) + fn = fh.baseFilename + emit = lambda msg: fh.emit(logging.makeLogRecord({'msg': msg})) + with patch('time.time', lambda: now[0]): + for msg in 'a', 'b': + now[0] += 2 + emit(msg) + now[0] += 2 + if target == '_open': + failure = patch.object(fh, '_open', side_effect=OSError) + fh.delay = False + else: + failure = patch('os.remove', side_effect=OSError) + with failure as failed, support.captured_stderr(): + emit('c') + failed.assert_called_once() + self.assertGreater(fh.rolloverAt, now[0]) + fh.delay = True + for msg in 'd', 'e': + now[0] += 2 + emit(msg) + fh.close() + with open(fn, encoding='utf-8') as f: + self.assertEqual(f.read(), 'e\n') + backups = [f for f in os.listdir(os.path.dirname(fn)) + if f != 'test.log'] + self.assertEqual(len(backups), 1) + + def test_rollover_existing_backup(self): + now = [1_000_000_000] + fh = self._make_fake_time_handler(now) + fn = fh.baseFilename + with patch('time.time', lambda: now[0]): + fh.emit(logging.makeLogRecord({'msg': 'a'})) + t = fh.rolloverAt - fh.interval + dfn = fh.rotation_filename( + fn + '.' + time.strftime(fh.suffix, time.localtime(t))) + with open(dfn, 'w', encoding='utf-8') as f: + f.write('existing\n') + now[0] += 2 + fh.emit(logging.makeLogRecord({'msg': 'b'})) + self.assertGreater(fh.rolloverAt, now[0]) + t = fh.rolloverAt - fh.interval + next_dfn = fh.rotation_filename( + fn + '.' + time.strftime(fh.suffix, time.localtime(t))) + now[0] += 2 + fh.emit(logging.makeLogRecord({'msg': 'c'})) + fh.close() + with open(dfn, encoding='utf-8') as f: + self.assertEqual(f.read(), 'existing\n') + with open(next_dfn, encoding='utf-8') as f: + self.assertEqual(f.read(), 'a\nb\n') + with open(fn, encoding='utf-8') as f: + self.assertEqual(f.read(), 'c\n') + def test_invalid(self): assertRaises = self.assertRaises assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler, @@ -7223,8 +7433,8 @@ def test_compute_rollover(self, when=when, interval=interval, exp=exp): setattr(TimedRotatingFileHandlerTest, name, test_compute_rollover) -@unittest.skipUnless(win32evtlog, 'win32evtlog/win32evtlogutil/pywintypes required for this test.') class NTEventLogHandlerTest(BaseTest): + @unittest.skipUnless(win32evtlog, 'win32evtlog/win32evtlogutil/pywintypes required for this test.') def test_basic(self): logtype = 'Application' elh = win32evtlog.OpenEventLog(None, logtype) @@ -7258,6 +7468,17 @@ def test_basic(self): msg = 'Record not found in event log, went back %d records' % GO_BACK self.assertTrue(found, msg=msg) + @unittest.skipUnless(sys.platform == "win32", "Windows required for this test") + def test_without_pywin32(self): + h = logging.handlers.NTEventLogHandler('python_test') + self.addCleanup(h.close) + + # Verify that the handler uses _winapi module + self.assertIsNotNone(h._winapi, "_winapi module should be available") + + r = logging.makeLogRecord({'msg': 'Hello!'}) + h.emit(r) + class MiscTestCase(unittest.TestCase): def test__all__(self): @@ -7269,6 +7490,16 @@ def test__all__(self): support.check__all__(self, logging, not_exported=not_exported) +class TestModule(unittest.TestCase): + def test_deprecated__version__and__date__(self): + msg = "is deprecated and slated for removal in Python 3.20" + for attr in ("__version__", "__date__"): + with self.subTest(attr=attr): + with self.assertWarnsRegex(DeprecationWarning, msg) as cm: + getattr(logging, attr) + self.assertEqual(cm.filename, __file__) + + # Set the locale to the platform-dependent default. I have no idea # why the test does this, but in any case we save the current locale # first and restore it at the end. diff --git a/Lib/test/test_long.py b/Lib/test/test_long.py index a879c6f5df8..78eb2138550 100644 --- a/Lib/test/test_long.py +++ b/Lib/test/test_long.py @@ -403,7 +403,6 @@ def check_float_conversion(self, n): "Got {}, expected {}.".format(n, actual, expected)) self.assertEqual(actual, expected, msg) - @unittest.expectedFailure # TODO: RUSTPYTHON @support.requires_IEEE_754 def test_float_conversion(self): @@ -870,7 +869,6 @@ def check_truediv(self, a, b, skip_small=True): self.assertEqual(expected, got, "Incorrectly rounded division {}/{}: " "expected {}, got {}".format(a, b, expected, got)) - @unittest.expectedFailure # TODO: RUSTPYTHON @support.requires_IEEE_754 def test_correctly_rounded_true_division(self): # more stringent tests than those above, checking that the @@ -998,6 +996,16 @@ def test_huge_lshift(self, size): self.assertEqual(v.bit_count(), 2) self.assertEqual(v >> size, 5) + @support.cpython_only + def test_huge_lshift_overflow(self): + # The number of digits of the result doesn't fit in Py_ssize_t. + for a in 1, -1, 1 << SHIFT, -1 << SHIFT, 1 << 10*SHIFT: + for ndigits in range(sys.maxsize - 12, sys.maxsize + 1): + for shift in ndigits*SHIFT - 1, ndigits*SHIFT: + with self.subTest(a=a, shift=shift): + with self.assertRaises(OverflowError): + a << shift + def test_huge_rshift(self): huge_shift = 1 << 1000 self.assertEqual(42 >> huge_shift, 0) @@ -1399,7 +1407,6 @@ class SubStr(str): self.assertEqual((0).to_bytes(1, SubStr('big')), b'\x00') self.assertEqual((0).to_bytes(0, SubStr('little')), b'') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_from_bytes(self): def check(tests, byteorder, signed=False): def equivalent_python(byte_array, byteorder, signed=False): diff --git a/Lib/test/test_lzma.py b/Lib/test/test_lzma.py index c7f2662ab0b..e93c3c37354 100644 --- a/Lib/test/test_lzma.py +++ b/Lib/test/test_lzma.py @@ -22,7 +22,6 @@ class CompressorDecompressorTestCase(unittest.TestCase): # Test error cases. - @unittest.expectedFailure # TODO: RUSTPYTHON; lzma.LZMAError: Invalid format def test_simple_bad_args(self): self.assertRaises(TypeError, LZMACompressor, []) self.assertRaises(TypeError, LZMACompressor, format=3.45) @@ -63,7 +62,6 @@ def test_simple_bad_args(self): lzd.decompress(empty) self.assertRaises(EOFError, lzd.decompress, b"quux") - @unittest.expectedFailure # TODO: RUSTPYTHON; lzma.LZMAError: Failed to initialize encoder def test_bad_filter_spec(self): self.assertRaises(TypeError, LZMACompressor, filters=[b"wobsite"]) self.assertRaises(ValueError, LZMACompressor, filters=[{"xyzzy": 3}]) @@ -158,7 +156,6 @@ def test_decompressor_chunks_empty(self): self.assertTrue(lzd.eof) self.assertEqual(lzd.unused_data, b"") - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'LZMADecompressor' object has no attribute 'check' def test_decompressor_chunks_maxsize(self): lzd = LZMADecompressor() max_length = 100 @@ -391,7 +388,6 @@ class CompressDecompressFunctionTestCase(unittest.TestCase): # Test error cases: - @unittest.expectedFailure # TODO: RUSTPYTHON; lzma.LZMAError: Failed to initialize encoder def test_bad_args(self): self.assertRaises(TypeError, lzma.compress) self.assertRaises(TypeError, lzma.compress, []) @@ -634,7 +630,6 @@ def test_init_bad_mode(self): with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), "rw") - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: Invalid check value def test_init_bad_check(self): with self.assertRaises(TypeError): LZMAFile(BytesIO(), "w", check=b"asd") @@ -674,7 +669,6 @@ def test_init_bad_preset(self): with self.assertRaises(ValueError): LZMAFile(BytesIO(COMPRESSED_XZ), preset=3) - @unittest.expectedFailure # TODO: RUSTPYTHON; lzma.LZMAError: Failed to initialize encoder def test_init_bad_filter_spec(self): with self.assertRaises(TypeError): LZMAFile(BytesIO(), "w", filters=[b"wobsite"]) @@ -692,7 +686,6 @@ def test_init_bad_filter_spec(self): LZMAFile(BytesIO(), "w", filters=[{"id": lzma.FILTER_X86, "foo": 0}]) - @unittest.expectedFailure # TODO: RUSTPYTHON; lzma.LZMAError: Invalid format def test_init_with_preset_and_filters(self): with self.assertRaises(ValueError): LZMAFile(BytesIO(), "w", format=lzma.FORMAT_RAW, @@ -1351,7 +1344,6 @@ def test_tell_bad_args(self): f.close() self.assertRaises(ValueError, f.tell) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: True is not false def test_issue21872(self): # sometimes decompress data incompletely @@ -1527,7 +1519,6 @@ def test_is_check_supported(self): # This value should not be a valid check ID. self.assertFalse(lzma.is_check_supported(lzma.CHECK_UNKNOWN)) - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: expected at most 0 arguments, got 1 def test__encode_filter_properties(self): with self.assertRaises(TypeError): lzma._encode_filter_properties(b"not a dict") diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py index 0169948e453..f1100f98ab9 100644 --- a/Lib/test/test_mailbox.py +++ b/Lib/test/test_mailbox.py @@ -8,9 +8,10 @@ import io import tempfile from test import support -from test.support import import_helper +from test.support import import_helper, warnings_helper from test.support import os_helper from test.support import refleak_helper +from test.support import requires_root_user from test.support import socket_helper import unittest import textwrap @@ -542,6 +543,11 @@ def _test_flush_or_close(self, method, should_call_close): self.assertIn(self._box.get_string(key), contents) oldbox.close() + def test_use_context_manager(self): + # Mailboxes are usable as a context manager + with self._box as box: + self.assertIs(self._box, box) + def test_dump_message(self): # Write message representations to disk for input in (email.message_from_string(_sample_message), @@ -1081,6 +1087,7 @@ def test_permissions_after_flush(self): self.assertEqual(os.stat(self._path).st_mode, mode) + @requires_root_user @unittest.skipUnless(hasattr(os, 'chown'), 'requires os.chown') def test_ownership_after_flush(self): # See issue gh-117467 @@ -1103,10 +1110,7 @@ def test_ownership_after_flush(self): else: self.skipTest("test needs more than one group") - try: - os.chown(self._path, other_uid, other_gid) - except OSError: - self.skipTest('test needs root privilege') + os.chown(self._path, other_uid, other_gid) # Change permissions as in test_permissions_after_flush. mode = st.st_mode | 0o666 os.chmod(self._path, mode) @@ -1122,6 +1126,16 @@ def test_ownership_after_flush(self): self.assertEqual(st.st_gid, other_gid) self.assertEqual(st.st_mode, mode) + def test_context_manager_locks_and_closes(self): + # Context manager locks/unlocks and closes. + # (This test uses an implementation detail to get the state.) + self.assertFalse(self._box._locked) + with self._box as context_object: + self.assertIs(self._box, context_object) + self.assertTrue(self._box._locked) + self.assertFalse(self._box._file.closed) + self.assertFalse(self._box._locked) + self.assertTrue(self._box._file.closed) class _TestMboxMMDF(_TestSingleFile): @@ -1212,6 +1226,7 @@ def test_add_and_close(self): self.assertEqual(contents, f.read()) self._box = self._factory(self._path) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.requires_fork() @unittest.skipUnless(hasattr(socket, 'socketpair'), "Test needs socketpair().") def test_lock_conflict(self): @@ -1506,6 +1521,31 @@ def test_labels(self): self._box.remove(key1) self.assertEqual(set(self._box.get_labels()), set(['blah'])) + def test_visible_headers(self): + # gh-157880: visible headers are written to the file and read back + msg = mailbox.BabylMessage(self._template % 0) + msg.update_visible() + key = self._box.add(msg) + for retrieved in (self._box.get_message(key), self._box[key]): + self.assertEqual(retrieved['from'], 'foo') + self.assertEqual(retrieved.get_payload(), '0\n') + self.assertEqual(retrieved.get_visible().keys(), ['From']) + self.assertEqual(retrieved.get_visible()['from'], 'foo') + self.assertEqual(self._box.get_bytes(key), + (self._template % 0).encode('ascii')) + + def test_no_visible_headers(self): + # gh-157880: empty visible headers are written to the file + # and read back + msg = mailbox.BabylMessage(self._template % 0) + key = self._box.add(msg) + for retrieved in (self._box.get_message(key), self._box[key]): + self.assertEqual(retrieved['from'], 'foo') + self.assertEqual(retrieved.get_payload(), '0\n') + self.assertEqual(retrieved.get_visible().keys(), []) + self.assertEqual(self._box.get_bytes(key), + (self._template % 0).encode('ascii')) + class FakeFileLikeObject: diff --git a/Lib/test/test_marshal.py b/Lib/test/test_marshal.py index 9f5cef9be63..e2ef755d04b 100644 --- a/Lib/test/test_marshal.py +++ b/Lib/test/test_marshal.py @@ -116,6 +116,14 @@ def test_bytes(self): for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]: self.helper(s) + @support.cpython_only + def test_bytes_singleton(self): + for version in range(marshal.version + 1): + for sample in [b"", b"x"]: + new = marshal.loads(marshal.dumps(sample, version)) + self.assertIs(new, sample) + + class ExceptionTestCase(unittest.TestCase): def test_exceptions(self): new = marshal.loads(marshal.dumps(StopIteration)) @@ -382,6 +390,22 @@ def test_reference_loop_slice(self): for v in range(marshal.version + 1): self.assertRaises(ValueError, marshal.dumps, a, v) + def test_reference_loop_frozendict(self): + a = frozendict({None: []}) + a[None].append(a) + for v in range(marshal.version + 1): + self.assertRaises(ValueError, marshal.dumps, a, v) + + def test_shared_reference_frozendict(self): + # A frozendict referenced more than once must round-trip with the + # shared identity preserved, like frozenset. + fd = frozendict({'a': 1, 'b': 2}) + out = marshal.loads(marshal.dumps([fd, fd])) + self.assertEqual(out[0], fd) + self.assertIs(out[0], out[1]) + nested = marshal.loads(marshal.dumps(frozendict({'x': fd, 'y': fd}))) + self.assertIs(nested['x'], nested['y']) + def test_loads_reference_loop_list(self): data = b'\xdb\x01\x00\x00\x00r\x00\x00\x00\x00' # [] a = marshal.loads(data) @@ -431,9 +455,13 @@ def test_loads_abnormal_reference_loops(self): b'\xba{Nr\x00\x00\x00\x000NN', # slice({None: }, None) b'\xbaN{Nr\x00\x00\x00\x000N', # slice(None, {None: }) b'\xbaNN{Nr\x00\x00\x00\x000', # slice(None, None, {None: }) + b'\xfdN[\x01\x00\x00\x00r\x00\x00\x00\x000', # frozendict({None: []}) + b'\xfdN{Nr\x00\x00\x00\x0000', # frozendict({None: {None: }) # Direct self-references which cannot be created in Python. b'\xbe\x01\x00\x00\x00r\x00\x00\x00\x00', # frozenset({}) + b'\xfdNr\x00\x00\x00\x000', # frozendict({None: }) + b'\xfdr\x00\x00\x00\x00N0', # frozendict({: None}) b'\xbar\x00\x00\x00\x00NN', # slice(, None) b'\xbaNr\x00\x00\x00\x00N', # slice(None, ) b'\xbaNNr\x00\x00\x00\x00', # slice(None, None, ) @@ -557,6 +585,67 @@ def test_unmarshallable(self): with self.assertRaisesRegex(ValueError, "unmarshallable object"): marshal.dumps((arg, memoryview(b''))) + def test_unorderable_set_items(self): + # Set items are sorted by their marshalled representation, they + # are not compared, even if NaNs which are distinct objects have + # the same marshalled representation. + nan = float('nan') + for kind in set, frozenset: + for version in range(marshal.version + 1): + with self.subTest(kind=kind, version=version): + sample = kind([complex(nan, 0), complex(nan, 0), 1j, + (complex(nan, 0),), (complex(nan, 0),), + float('nan'), float('nan')]) + self.assertEqual(len(sample), 7) + new = marshal.loads(marshal.dumps(sample, version)) + self.assertIs(type(new), kind) + self.assertEqual(sorted(map(repr, new)), + sorted(map(repr, sample))) + + def test_unorderable_set_items_in_code(self): + # A constant set containing NaNs which are distinct objects. + # Run in a subprocess: constants of code objects are immortal + # in the free-threaded build. + script = textwrap.dedent(""" + import marshal + source = 'x in {(1e999-1e999)*1j, (1e999-1e999)*2j, 1.5}' + code = compile(source, '', 'eval') + def consts(code): + return [sorted(map(repr, x)) if isinstance(x, frozenset) else x + for x in code.co_consts] + assert ['(nan+nanj)', '(nan+nanj)', '1.5'] in consts(code) + for version in range(marshal.version + 1): + new = marshal.loads(marshal.dumps(code, version)) + assert new.co_code == code.co_code + assert consts(new) == consts(code) + assert eval(new, {'x': 1.5}) is True + assert eval(new, {'x': complex('nan')}) is False + """) + assert_python_ok('-c', script) + + def test_set_changed_size(self): + # A set is modified while its items are being marshalled. + class Item: + def __hash__(self): + return 0 + def __buffer__(self, flags): + change(sample) + return memoryview(b'abc') + def grow(sample): + sample.update(range(1000, 1400)) + def shrink(sample): + sample.difference_update(range(1, 60)) + for change in grow, shrink: + for version in range(marshal.version + 1): + with self.subTest(change=change.__name__, version=version): + # The first item of the set modifies it. + sample = {Item()} + sample.update(range(1, 60)) + self.assertIsInstance(next(iter(sample)), Item) + with self.assertRaisesRegex(RuntimeError, + "set changed size"): + marshal.dumps(sample, version) + LARGE_SIZE = 2**31 pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4 @@ -695,6 +784,15 @@ def testDict(self): self.helper(dictobj) self.helper3(dictobj) + def testFrozenDict(self): + for obj in self.keys: + dictobj = frozendict({"hello": obj, "goodbye": obj, obj: "hello"}) + self.helper(dictobj) + + for version in range(6): + with self.assertRaises(ValueError): + marshal.dumps(dictobj, version) + def testModule(self): with open(__file__, "rb") as f: code = f.read() @@ -760,7 +858,7 @@ def test_slice(self): with self.subTest(obj=str(obj)): self.helper(obj) - for version in range(4): + for version in range(5): with self.assertRaises(ValueError): marshal.dumps(obj, version) diff --git a/Lib/test/test_math.py b/Lib/test/test_math.py index 943448d69ca..1a470a7aecb 100644 --- a/Lib/test/test_math.py +++ b/Lib/test/test_math.py @@ -17,6 +17,7 @@ eps = 1E-05 NAN = float('nan') +NNAN = float('-nan') INF = float('inf') NINF = float('-inf') FLOAT_MAX = sys.float_info.max @@ -54,56 +55,6 @@ def to_ulps(x): return n -# Here's a pure Python version of the math.factorial algorithm, for -# documentation and comparison purposes. -# -# Formula: -# -# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n)) -# -# where -# -# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j -# -# The outer product above is an infinite product, but once i >= n.bit_length, -# (n >> i) < 1 and the corresponding term of the product is empty. So only the -# finitely many terms for 0 <= i < n.bit_length() contribute anything. -# -# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner -# product in the formula above starts at 1 for i == n.bit_length(); for each i -# < n.bit_length() we get the inner product for i from that for i + 1 by -# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms, -# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). - -def count_set_bits(n): - """Number of '1' bits in binary expansion of a nonnnegative integer.""" - return 1 + count_set_bits(n & n - 1) if n else 0 - -def partial_product(start, stop): - """Product of integers in range(start, stop, 2), computed recursively. - start and stop should both be odd, with start <= stop. - - """ - numfactors = (stop - start) >> 1 - if not numfactors: - return 1 - elif numfactors == 1: - return start - else: - mid = (start + numfactors) | 1 - return partial_product(start, mid) * partial_product(mid, stop) - -def py_factorial(n): - """Factorial of nonnegative integer n, via "Binary Split Factorial Formula" - described at http://www.luschny.de/math/factorial/binarysplitfact.html - - """ - inner = outer = 1 - for i in reversed(range(n.bit_length())): - inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1) - outer *= inner - return outer << (n - count_set_bits(n)) - def ulp_abs_check(expected, got, ulp_tol, abs_tol): """Given finite floats `expected` and `got`, check that they're approximately equal to within the given number of ulps or the @@ -238,18 +189,21 @@ def __init__(self, value): def __index__(self): return self.value -# int subclass with broken arithmetic operators; implementations must -# convert their arguments to exact ints instead of using these. -class BadIntSubclass(int): - def _binop(self, other='ignored', mod=None): - return 42 - __add__ = __radd__ = __sub__ = __rsub__ = _binop - __mul__ = __rmul__ = __mod__ = __rmod__ = _binop - __divmod__ = __rdivmod__ = __pow__ = __rpow__ = _binop - __floordiv__ = __rfloordiv__ = _binop - __lshift__ = __rlshift__ = __rshift__ = __rrshift__ = _binop - __and__ = __rand__ = __or__ = __ror__ = __xor__ = __rxor__ = _binop - __lt__ = __le__ = __gt__ = __ge__ = _binop +class IndexableFloatLike: + def __init__(self, float_value, index_value): + self.float_value = float_value + self.index_value = index_value + + def __float__(self): + if isinstance(self.float_value, BaseException): + raise self.float_value + return self.float_value + + def __index__(self): + if isinstance(self.index_value, BaseException): + raise self.index_value + return self.index_value + class BadDescr: def __get__(self, obj, objtype=None): @@ -490,6 +444,19 @@ def testCopysign(self): # similarly, copysign(2., NAN) could be 2. or -2. self.assertEqual(abs(math.copysign(2., NAN)), 2.) + def test_signbit(self): + self.assertRaises(TypeError, math.signbit) + self.assertRaises(TypeError, math.signbit, '1.0') + + # C11, §7.12.3.6 requires signbit() to return a nonzero value + # if and only if the sign of its argument value is negative, + # but in practice, we are only interested in a boolean value. + self.assertIsInstance(math.signbit(1.0), bool) + + for arg in [0., 1., INF, NAN]: + self.assertFalse(math.signbit(arg)) + self.assertTrue(math.signbit(-arg)) + def testCos(self): self.assertRaises(TypeError, math.cos) self.ftest('cos(-pi/2)', math.cos(-math.pi/2), 0, abs_tol=math.ulp(1)) @@ -548,33 +515,6 @@ def testFabs(self): self.ftest('fabs(0)', math.fabs(0), 0) self.ftest('fabs(1)', math.fabs(1), 1) - def testFactorial(self): - self.assertEqual(math.factorial(0), 1) - total = 1 - for i in range(1, 1000): - total *= i - self.assertEqual(math.factorial(i), total) - self.assertEqual(math.factorial(i), py_factorial(i)) - self.assertRaises(ValueError, math.factorial, -1) - self.assertRaises(ValueError, math.factorial, -10**100) - - def testFactorialNonIntegers(self): - self.assertRaises(TypeError, math.factorial, 5.0) - self.assertRaises(TypeError, math.factorial, 5.2) - self.assertRaises(TypeError, math.factorial, -1.0) - self.assertRaises(TypeError, math.factorial, -1e100) - self.assertRaises(TypeError, math.factorial, decimal.Decimal('5')) - self.assertRaises(TypeError, math.factorial, decimal.Decimal('5.2')) - self.assertRaises(TypeError, math.factorial, "5") - - # Other implementations may place different upper bounds. - @support.cpython_only - def testFactorialHugeInputs(self): - # Currently raises OverflowError for inputs that are too large - # to fit into a C long. - self.assertRaises(OverflowError, math.factorial, 10**100) - self.assertRaises(TypeError, math.factorial, 1e100) - def testFloor(self): self.assertRaises(TypeError, math.floor) self.assertEqual(int, type(math.floor(0.5))) @@ -638,6 +578,92 @@ def testFmod(self): self.assertEqual(math.fmod(0.0, NINF), 0.0) self.assertRaises(ValueError, math.fmod, INF, INF) + def test_fmax(self): + self.assertRaises(TypeError, math.fmax) + self.assertRaises(TypeError, math.fmax, 'x', 'y') + + self.assertEqual(math.fmax(0., 0.), 0.) + self.assertEqual(math.fmax(1., 2.), 2.) + self.assertEqual(math.fmax(2., 1.), 2.) + + self.assertEqual(math.fmax(+1., +0.), 1.) + self.assertEqual(math.fmax(+0., +1.), 1.) + self.assertEqual(math.fmax(+1., -0.), 1.) + self.assertEqual(math.fmax(-0., +1.), 1.) + + self.assertEqual(math.fmax(-1., +0.), 0.) + self.assertEqual(math.fmax(+0., -1.), 0.) + self.assertEqual(math.fmax(-1., -0.), 0.) + self.assertEqual(math.fmax(-0., -1.), 0.) + + for x in [NINF, -1., -0., 0., 1., INF]: + self.assertFalse(math.isnan(x)) + + with self.subTest(x=x, is_negative=math.copysign(1, x) < 0): + self.assertEqual(math.fmax(INF, x), INF) + self.assertEqual(math.fmax(x, INF), INF) + self.assertEqual(math.fmax(NINF, x), x) + self.assertEqual(math.fmax(x, NINF), x) + + @requires_IEEE_754 + def test_fmax_nans(self): + # When exactly one operand is NaN, the other is returned. + for x in [NINF, -1., -0., 0., 1., INF]: + with self.subTest(x=x, is_negative=math.copysign(1, x) < 0): + self.assertFalse(math.isnan(math.fmax(NAN, x))) + self.assertFalse(math.isnan(math.fmax(x, NAN))) + self.assertFalse(math.isnan(math.fmax(NNAN, x))) + self.assertFalse(math.isnan(math.fmax(x, NNAN))) + # When both operands are NaNs, fmax() returns NaN (see C11, F.10.9.2) + # whose sign is implementation-defined (see C11, F.10.0.3). + self.assertTrue(math.isnan(math.fmax(NAN, NAN))) + self.assertTrue(math.isnan(math.fmax(NNAN, NNAN))) + self.assertTrue(math.isnan(math.fmax(NAN, NNAN))) + self.assertTrue(math.isnan(math.fmax(NNAN, NAN))) + + def test_fmin(self): + self.assertRaises(TypeError, math.fmin) + self.assertRaises(TypeError, math.fmin, 'x', 'y') + + self.assertEqual(math.fmin(0., 0.), 0.) + self.assertEqual(math.fmin(1., 2.), 1.) + self.assertEqual(math.fmin(2., 1.), 1.) + + self.assertEqual(math.fmin(+1., +0.), 0.) + self.assertEqual(math.fmin(+0., +1.), 0.) + self.assertEqual(math.fmin(+1., -0.), 0.) + self.assertEqual(math.fmin(-0., +1.), 0.) + + self.assertEqual(math.fmin(-1., +0.), -1.) + self.assertEqual(math.fmin(+0., -1.), -1.) + self.assertEqual(math.fmin(-1., -0.), -1.) + self.assertEqual(math.fmin(-0., -1.), -1.) + + for x in [NINF, -1., -0., 0., 1., INF]: + self.assertFalse(math.isnan(x)) + + with self.subTest(x=x, is_negative=math.copysign(1, x) < 0): + self.assertEqual(math.fmin(INF, x), x) + self.assertEqual(math.fmin(x, INF), x) + self.assertEqual(math.fmin(NINF, x), NINF) + self.assertEqual(math.fmin(x, NINF), NINF) + + @requires_IEEE_754 + def test_fmin_nans(self): + # When exactly one operand is NaN, the other is returned. + for x in [NINF, -1., -0., 0., 1., INF]: + with self.subTest(x=x, is_negative=math.copysign(1, x) < 0): + self.assertFalse(math.isnan(math.fmin(NAN, x))) + self.assertFalse(math.isnan(math.fmin(x, NAN))) + self.assertFalse(math.isnan(math.fmin(NNAN, x))) + self.assertFalse(math.isnan(math.fmin(x, NNAN))) + # When both operands are NaNs, fmin() returns NaN (see C11, F.10.9.3) + # whose sign is implementation-defined (see C11, F.10.0.3). + self.assertTrue(math.isnan(math.fmin(NAN, NAN))) + self.assertTrue(math.isnan(math.fmin(NNAN, NNAN))) + self.assertTrue(math.isnan(math.fmin(NAN, NNAN))) + self.assertTrue(math.isnan(math.fmin(NNAN, NAN))) + def testFrexp(self): self.assertRaises(TypeError, math.frexp) @@ -1090,78 +1116,6 @@ def test_math_dist_leak(self): with self.assertRaises(ValueError): math.dist([1, 2], [3, 4, 5]) - def testIsqrt(self): - # Test a variety of inputs, large and small. - test_values = ( - list(range(1000)) - + list(range(10**6 - 1000, 10**6 + 1000)) - + [2**e + i for e in range(60, 200) for i in range(-40, 40)] - + [3**9999, 10**5001] - ) - - for value in test_values: - with self.subTest(value=value): - s = math.isqrt(value) - self.assertIs(type(s), int) - self.assertLessEqual(s*s, value) - self.assertLess(value, (s+1)*(s+1)) - - # Negative values - with self.assertRaises(ValueError): - math.isqrt(-1) - - # Integer-like things - s = math.isqrt(True) - self.assertIs(type(s), int) - self.assertEqual(s, 1) - - s = math.isqrt(False) - self.assertIs(type(s), int) - self.assertEqual(s, 0) - - class IntegerLike(object): - def __init__(self, value): - self.value = value - - def __index__(self): - return self.value - - s = math.isqrt(IntegerLike(1729)) - self.assertIs(type(s), int) - self.assertEqual(s, 41) - - # Overridden operators of an int subclass must not affect the - # result. - s = math.isqrt(BadIntSubclass(10**20)) - self.assertIs(type(s), int) - self.assertEqual(s, 10**10) - - s = math.isqrt(BadIntSubclass(10**20 - 1)) - self.assertIs(type(s), int) - self.assertEqual(s, 10**10 - 1) - - with self.assertRaises(ValueError): - math.isqrt(IntegerLike(-3)) - - # Non-integer-like things - bad_values = [ - 3.5, "a string", decimal.Decimal("3.5"), 3.5j, - 100.0, -4.0, - ] - for value in bad_values: - with self.subTest(value=value): - with self.assertRaises(TypeError): - math.isqrt(value) - - @support.bigmemtest(2**32, memuse=0.85) - def test_isqrt_huge(self, size): - if size & 1: - size += 1 - v = 1 << size - w = math.isqrt(v) - self.assertEqual(w.bit_length(), size // 2 + 1) - self.assertEqual(w.bit_count(), 1) - def test_lcm(self): lcm = math.lcm self.assertEqual(lcm(0, 0), 0) @@ -1256,13 +1210,32 @@ def testLog(self): self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2) self.ftest('log(10**1000)', math.log(10**1000), 2302.5850929940457) + self.ftest('log(10**2000, 10**1000)', math.log(10**2000, 10**1000), 2) + self.ftest('log(MyIndexable(32), MyIndexable(2))', + math.log(MyIndexable(32), MyIndexable(2)), 5) + self.ftest('log(MyIndexable(10**1000))', + math.log(MyIndexable(10**1000)), + 2302.5850929940457) + self.ftest('log(MyIndexable(10**2000), MyIndexable(10**1000))', + math.log(MyIndexable(10**2000), MyIndexable(10**1000)), + 2) + self.assertRaises(ValueError, math.log, 0.0) + self.assertRaises(ValueError, math.log, 0) + self.assertRaises(ValueError, math.log, MyIndexable(0)) self.assertRaises(ValueError, math.log, -1.5) + self.assertRaises(ValueError, math.log, -1) + self.assertRaises(ValueError, math.log, MyIndexable(-1)) self.assertRaises(ValueError, math.log, -10**1000) + self.assertRaises(ValueError, math.log, MyIndexable(-10**1000)) self.assertRaises(ValueError, math.log, 10, -10) self.assertRaises(ValueError, math.log, NINF) self.assertEqual(math.log(INF), INF) self.assertTrue(math.isnan(math.log(NAN))) + self.assertEqual(math.log(IndexableFloatLike(math.e, 10**1000)), 1.0) + self.assertAlmostEqual(math.log(IndexableFloatLike(OverflowError(), 10**1000)), + 2302.5850929940457) + def testLog1p(self): self.assertRaises(TypeError, math.log1p) for n in [2, 2**90, 2**300]: @@ -1278,16 +1251,28 @@ def testLog2(self): self.assertEqual(math.log2(1), 0.0) self.assertEqual(math.log2(2), 1.0) self.assertEqual(math.log2(4), 2.0) + self.assertEqual(math.log2(MyIndexable(4)), 2.0) # Large integer values self.assertEqual(math.log2(2**1023), 1023.0) self.assertEqual(math.log2(2**1024), 1024.0) self.assertEqual(math.log2(2**2000), 2000.0) + self.assertEqual(math.log2(MyIndexable(2**2000)), 2000.0) + self.assertRaises(ValueError, math.log2, 0.0) + self.assertRaises(ValueError, math.log2, 0) + self.assertRaises(ValueError, math.log2, MyIndexable(0)) self.assertRaises(ValueError, math.log2, -1.5) + self.assertRaises(ValueError, math.log2, -1) + self.assertRaises(ValueError, math.log2, MyIndexable(-1)) + self.assertRaises(ValueError, math.log2, -2**2000) + self.assertRaises(ValueError, math.log2, MyIndexable(-2**2000)) self.assertRaises(ValueError, math.log2, NINF) self.assertTrue(math.isnan(math.log2(NAN))) + self.assertEqual(math.log2(IndexableFloatLike(8.0, 2**2000)), 3.0) + self.assertEqual(math.log2(IndexableFloatLike(OverflowError(), 2**2000)), 2000.0) + @requires_IEEE_754 # log2() is not accurate enough on Mac OS X Tiger (10.4) @support.requires_mac_ver(10, 5) @@ -1303,12 +1288,24 @@ def testLog10(self): self.ftest('log10(1)', math.log10(1), 0) self.ftest('log10(10)', math.log10(10), 1) self.ftest('log10(10**1000)', math.log10(10**1000), 1000.0) + self.ftest('log10(MyIndexable(10))', math.log10(MyIndexable(10)), 1) + self.ftest('log10(MyIndexable(10**1000))', + math.log10(MyIndexable(10**1000)), 1000.0) + self.assertRaises(ValueError, math.log10, 0.0) + self.assertRaises(ValueError, math.log10, 0) + self.assertRaises(ValueError, math.log10, MyIndexable(0)) self.assertRaises(ValueError, math.log10, -1.5) + self.assertRaises(ValueError, math.log10, -1) + self.assertRaises(ValueError, math.log10, MyIndexable(-1)) self.assertRaises(ValueError, math.log10, -10**1000) + self.assertRaises(ValueError, math.log10, MyIndexable(-10**1000)) self.assertRaises(ValueError, math.log10, NINF) self.assertEqual(math.log(INF), INF) self.assertTrue(math.isnan(math.log10(NAN))) + self.assertEqual(math.log10(IndexableFloatLike(100.0, 10**1000)), 2.0) + self.assertEqual(math.log10(IndexableFloatLike(OverflowError(), 10**1000)), 1000.0) + @support.bigmemtest(2**32, memuse=0.2) def test_log_huge_integer(self, size): v = 1 << size @@ -1412,7 +1409,6 @@ def __rmul__(self, other): args = ((-5, -5, 10), (1.5, 4611686018427387904, 2305843009213693952)) self.assertEqual(sumprod(*args), 0.0) - @requires_IEEE_754 @unittest.skipIf(HAVE_DOUBLE_ROUNDING, "sumprod() accuracy not guaranteed on machines with double rounding") @@ -1763,7 +1759,6 @@ def testRadians(self): self.ftest('radians(-45)', math.radians(-45), -math.pi/4) self.ftest('radians(0)', math.radians(0), 0) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON; Error message too long") @requires_IEEE_754 def testRemainder(self): from fractions import Fraction @@ -1999,6 +1994,28 @@ def testIsfinite(self): self.assertFalse(math.isfinite(float("inf"))) self.assertFalse(math.isfinite(float("-inf"))) + def testIsnormal(self): + self.assertTrue(math.isnormal(1.25)) + self.assertTrue(math.isnormal(-1.0)) + self.assertFalse(math.isnormal(0.0)) + self.assertFalse(math.isnormal(-0.0)) + self.assertFalse(math.isnormal(INF)) + self.assertFalse(math.isnormal(NINF)) + self.assertFalse(math.isnormal(NAN)) + self.assertFalse(math.isnormal(FLOAT_MIN/2)) + self.assertFalse(math.isnormal(-FLOAT_MIN/2)) + + def testIssubnormal(self): + self.assertFalse(math.issubnormal(1.25)) + self.assertFalse(math.issubnormal(-1.0)) + self.assertFalse(math.issubnormal(0.0)) + self.assertFalse(math.issubnormal(-0.0)) + self.assertFalse(math.issubnormal(INF)) + self.assertFalse(math.issubnormal(NINF)) + self.assertFalse(math.issubnormal(NAN)) + self.assertTrue(math.issubnormal(FLOAT_MIN/2)) + self.assertTrue(math.issubnormal(-FLOAT_MIN/2)) + def testIsnan(self): self.assertTrue(math.isnan(float("nan"))) self.assertTrue(math.isnan(float("-nan"))) @@ -2297,140 +2314,6 @@ def _naive_prod(iterable, start=1): self.assertEqual(type(prod([1, decimal.Decimal(2.0), 3, 4, 5, 6])), decimal.Decimal) - def testPerm(self): - perm = math.perm - factorial = math.factorial - # Test if factorial definition is satisfied - for n in range(500): - for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)): - self.assertEqual(perm(n, k), - factorial(n) // factorial(n - k)) - - # Test for Pascal's identity - for n in range(1, 100): - for k in range(1, n): - self.assertEqual(perm(n, k), perm(n - 1, k - 1) * k + perm(n - 1, k)) - - # Test corner cases - for n in range(1, 100): - self.assertEqual(perm(n, 0), 1) - self.assertEqual(perm(n, 1), n) - self.assertEqual(perm(n, n), factorial(n)) - - # Test one argument form - for n in range(20): - self.assertEqual(perm(n), factorial(n)) - self.assertEqual(perm(n, None), factorial(n)) - - # Raises TypeError if any argument is non-integer or argument count is - # not 1 or 2 - self.assertRaises(TypeError, perm, 10, 1.0) - self.assertRaises(TypeError, perm, 10, decimal.Decimal(1.0)) - self.assertRaises(TypeError, perm, 10, "1") - self.assertRaises(TypeError, perm, 10.0, 1) - self.assertRaises(TypeError, perm, decimal.Decimal(10.0), 1) - self.assertRaises(TypeError, perm, "10", 1) - - self.assertRaises(TypeError, perm) - self.assertRaises(TypeError, perm, 10, 1, 3) - self.assertRaises(TypeError, perm) - - # Raises Value error if not k or n are negative numbers - self.assertRaises(ValueError, perm, -1, 1) - self.assertRaises(ValueError, perm, -2**1000, 1) - self.assertRaises(ValueError, perm, 1, -1) - self.assertRaises(ValueError, perm, 1, -2**1000) - - # Returns zero if k is greater than n - self.assertEqual(perm(1, 2), 0) - self.assertEqual(perm(1, 2**1000), 0) - - n = 2**1000 - self.assertEqual(perm(n, 0), 1) - self.assertEqual(perm(n, 1), n) - self.assertEqual(perm(n, 2), n * (n-1)) - if support.check_impl_detail(cpython=True): - self.assertRaises(OverflowError, perm, n, n) - - for n, k in (True, True), (True, False), (False, False): - self.assertEqual(perm(n, k), 1) - self.assertIs(type(perm(n, k)), int) - self.assertEqual(perm(IntSubclass(5), IntSubclass(2)), 20) - self.assertEqual(perm(MyIndexable(5), MyIndexable(2)), 20) - for k in range(3): - self.assertIs(type(perm(IntSubclass(5), IntSubclass(k))), int) - self.assertIs(type(perm(MyIndexable(5), MyIndexable(k))), int) - - def testComb(self): - comb = math.comb - factorial = math.factorial - # Test if factorial definition is satisfied - for n in range(500): - for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)): - self.assertEqual(comb(n, k), factorial(n) - // (factorial(k) * factorial(n - k))) - - # Test for Pascal's identity - for n in range(1, 100): - for k in range(1, n): - self.assertEqual(comb(n, k), comb(n - 1, k - 1) + comb(n - 1, k)) - - # Test corner cases - for n in range(100): - self.assertEqual(comb(n, 0), 1) - self.assertEqual(comb(n, n), 1) - - for n in range(1, 100): - self.assertEqual(comb(n, 1), n) - self.assertEqual(comb(n, n - 1), n) - - # Test Symmetry - for n in range(100): - for k in range(n // 2): - self.assertEqual(comb(n, k), comb(n, n - k)) - - # Raises TypeError if any argument is non-integer or argument count is - # not 2 - self.assertRaises(TypeError, comb, 10, 1.0) - self.assertRaises(TypeError, comb, 10, decimal.Decimal(1.0)) - self.assertRaises(TypeError, comb, 10, "1") - self.assertRaises(TypeError, comb, 10.0, 1) - self.assertRaises(TypeError, comb, decimal.Decimal(10.0), 1) - self.assertRaises(TypeError, comb, "10", 1) - - self.assertRaises(TypeError, comb, 10) - self.assertRaises(TypeError, comb, 10, 1, 3) - self.assertRaises(TypeError, comb) - - # Raises Value error if not k or n are negative numbers - self.assertRaises(ValueError, comb, -1, 1) - self.assertRaises(ValueError, comb, -2**1000, 1) - self.assertRaises(ValueError, comb, 1, -1) - self.assertRaises(ValueError, comb, 1, -2**1000) - - # Returns zero if k is greater than n - self.assertEqual(comb(1, 2), 0) - self.assertEqual(comb(1, 2**1000), 0) - - n = 2**1000 - self.assertEqual(comb(n, 0), 1) - self.assertEqual(comb(n, 1), n) - self.assertEqual(comb(n, 2), n * (n-1) // 2) - self.assertEqual(comb(n, n), 1) - self.assertEqual(comb(n, n-1), n) - self.assertEqual(comb(n, n-2), n * (n-1) // 2) - if support.check_impl_detail(cpython=True): - self.assertRaises(OverflowError, comb, n, n//2) - - for n, k in (True, True), (True, False), (False, False): - self.assertEqual(comb(n, k), 1) - self.assertIs(type(comb(n, k)), int) - self.assertEqual(comb(IntSubclass(5), IntSubclass(2)), 10) - self.assertEqual(comb(MyIndexable(5), MyIndexable(2)), 10) - for k in range(3): - self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int) - self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int) - @requires_IEEE_754 def test_nextafter(self): # around 2^52 and 2^63 @@ -2490,7 +2373,6 @@ def test_nextafter(self): with self.assertRaises(ValueError): math.nextafter(1.0, INF, steps=-1) - @requires_IEEE_754 def test_ulp(self): self.assertEqual(math.ulp(1.0), sys.float_info.epsilon) @@ -2805,11 +2687,8 @@ def test_fma_infinities(self): @unittest.skipIf( sys.platform.startswith(("freebsd", "wasi", "netbsd", "emscripten")) or (sys.platform == "android" and platform.machine() == "x86_64") - or support.linked_to_musl(), # gh-131032 + or (support.linked_to_musl() and support.linked_to_musl() < (1, 2, 6)), # gh-131032 f"this platform doesn't implement IEE 754-2008 properly") - # gh-131032: musl is fixed but the fix is not yet released; when the fixed - # version is known change this to: - # or support.linked_to_musl() < (1, ,

) def test_fma_zero_result(self): nonnegative_finites = [0.0, 1e-300, 2.3, 1e300] diff --git a/Lib/test/test_math_integer.py b/Lib/test/test_math_integer.py new file mode 100644 index 00000000000..d1bc776dc42 --- /dev/null +++ b/Lib/test/test_math_integer.py @@ -0,0 +1,421 @@ +from decimal import Decimal +from fractions import Fraction +import unittest +from test import support + + +class IntSubclass(int): + pass + +# Class providing an __index__ method. +class MyIndexable(object): + def __init__(self, value): + self.value = value + + def __index__(self): + return self.value + +# int subclass with broken arithmetic operators; implementations must +# convert their arguments to exact ints instead of using these. +class BadIntSubclass(int): + def _binop(self, other='ignored', mod=None): + return 42 + __add__ = __radd__ = __sub__ = __rsub__ = _binop + __mul__ = __rmul__ = __mod__ = __rmod__ = _binop + __divmod__ = __rdivmod__ = __pow__ = __rpow__ = _binop + __floordiv__ = __rfloordiv__ = _binop + __lshift__ = __rlshift__ = __rshift__ = __rrshift__ = _binop + __and__ = __rand__ = __or__ = __ror__ = __xor__ = __rxor__ = _binop + __lt__ = __le__ = __gt__ = __ge__ = _binop + +# Here's a pure Python version of the math.integer.factorial algorithm, for +# documentation and comparison purposes. +# +# Formula: +# +# factorial(n) = factorial_odd_part(n) << (n - count_set_bits(n)) +# +# where +# +# factorial_odd_part(n) = product_{i >= 0} product_{0 < j <= n >> i; j odd} j +# +# The outer product above is an infinite product, but once i >= n.bit_length, +# (n >> i) < 1 and the corresponding term of the product is empty. So only the +# finitely many terms for 0 <= i < n.bit_length() contribute anything. +# +# We iterate downwards from i == n.bit_length() - 1 to i == 0. The inner +# product in the formula above starts at 1 for i == n.bit_length(); for each i +# < n.bit_length() we get the inner product for i from that for i + 1 by +# multiplying by all j in {n >> i+1 < j <= n >> i; j odd}. In Python terms, +# this set is range((n >> i+1) + 1 | 1, (n >> i) + 1 | 1, 2). + +def count_set_bits(n): + """Number of '1' bits in binary expansion of a nonnnegative integer.""" + return 1 + count_set_bits(n & n - 1) if n else 0 + +def partial_product(start, stop): + """Product of integers in range(start, stop, 2), computed recursively. + start and stop should both be odd, with start <= stop. + + """ + numfactors = (stop - start) >> 1 + if not numfactors: + return 1 + elif numfactors == 1: + return start + else: + mid = (start + numfactors) | 1 + return partial_product(start, mid) * partial_product(mid, stop) + +def py_factorial(n): + """Factorial of nonnegative integer n, via "Binary Split Factorial Formula" + described at http://www.luschny.de/math/factorial/binarysplitfact.html + + """ + inner = outer = 1 + for i in reversed(range(n.bit_length())): + inner *= partial_product((n >> i + 1) + 1 | 1, (n >> i) + 1 | 1) + outer *= inner + return outer << (n - count_set_bits(n)) + + +class IntMathTests(unittest.TestCase): + import math.integer as module + + def assertIntEqual(self, actual, expected): + self.assertEqual(actual, expected) + self.assertIs(type(actual), int) + + def test_factorial(self): + factorial = self.module.factorial + self.assertEqual(factorial(0), 1) + total = 1 + for i in range(1, 1000): + total *= i + self.assertEqual(factorial(i), total) + self.assertEqual(factorial(i), py_factorial(i)) + + self.assertIntEqual(factorial(False), 1) + self.assertIntEqual(factorial(True), 1) + for i in range(3): + expected = factorial(i) + self.assertIntEqual(factorial(IntSubclass(i)), expected) + self.assertIntEqual(factorial(MyIndexable(i)), expected) + + self.assertRaises(ValueError, factorial, -1) + self.assertRaises(ValueError, factorial, -10**1000) + + def test_factorial_non_integers(self): + factorial = self.module.factorial + self.assertRaises(TypeError, factorial, 5.0) + self.assertRaises(TypeError, factorial, 5.2) + self.assertRaises(TypeError, factorial, -1.0) + self.assertRaises(TypeError, factorial, -1e100) + self.assertRaises(TypeError, factorial, Decimal('5')) + self.assertRaises(TypeError, factorial, Decimal('5.2')) + self.assertRaises(TypeError, factorial, Fraction(5, 1)) + self.assertRaises(TypeError, factorial, "5") + + # Other implementations may place different upper bounds. + @support.cpython_only + def test_factorial_huge_inputs(self): + factorial = self.module.factorial + # Currently raises OverflowError for inputs that are too large + # to fit into a C long. + self.assertRaises(OverflowError, factorial, 10**100) + self.assertRaises(TypeError, factorial, 1e100) + + def test_gcd(self): + gcd = self.module.gcd + self.assertEqual(gcd(0, 0), 0) + self.assertEqual(gcd(1, 0), 1) + self.assertEqual(gcd(-1, 0), 1) + self.assertEqual(gcd(0, 1), 1) + self.assertEqual(gcd(0, -1), 1) + self.assertEqual(gcd(7, 1), 1) + self.assertEqual(gcd(7, -1), 1) + self.assertEqual(gcd(-23, 15), 1) + self.assertEqual(gcd(120, 84), 12) + self.assertEqual(gcd(84, -120), 12) + self.assertEqual(gcd(1216342683557601535506311712, + 436522681849110124616458784), 32) + c = 652560 + x = 434610456570399902378880679233098819019853229470286994367836600566 + y = 1064502245825115327754847244914921553977 + a = x * c + b = y * c + self.assertEqual(gcd(a, b), c) + self.assertEqual(gcd(b, a), c) + self.assertEqual(gcd(-a, b), c) + self.assertEqual(gcd(b, -a), c) + self.assertEqual(gcd(a, -b), c) + self.assertEqual(gcd(-b, a), c) + self.assertEqual(gcd(-a, -b), c) + self.assertEqual(gcd(-b, -a), c) + c = 576559230871654959816130551884856912003141446781646602790216406874 + a = x * c + b = y * c + self.assertEqual(gcd(a, b), c) + self.assertEqual(gcd(b, a), c) + self.assertEqual(gcd(-a, b), c) + self.assertEqual(gcd(b, -a), c) + self.assertEqual(gcd(a, -b), c) + self.assertEqual(gcd(-b, a), c) + self.assertEqual(gcd(-a, -b), c) + self.assertEqual(gcd(-b, -a), c) + + self.assertRaises(TypeError, gcd, 120.0, 84) + self.assertRaises(TypeError, gcd, 120, 84.0) + self.assertIntEqual(gcd(IntSubclass(120), IntSubclass(84)), 12) + self.assertIntEqual(gcd(MyIndexable(120), MyIndexable(84)), 12) + + def test_lcm(self): + lcm = self.module.lcm + self.assertEqual(lcm(0, 0), 0) + self.assertEqual(lcm(1, 0), 0) + self.assertEqual(lcm(-1, 0), 0) + self.assertEqual(lcm(0, 1), 0) + self.assertEqual(lcm(0, -1), 0) + self.assertEqual(lcm(7, 1), 7) + self.assertEqual(lcm(7, -1), 7) + self.assertEqual(lcm(-23, 15), 345) + self.assertEqual(lcm(120, 84), 840) + self.assertEqual(lcm(84, -120), 840) + self.assertEqual(lcm(1216342683557601535506311712, + 436522681849110124616458784), + 16592536571065866494401400422922201534178938447014944) + + x = 43461045657039990237 + y = 10645022458251153277 + for c in (652560, + 57655923087165495981): + a = x * c + b = y * c + d = x * y * c + self.assertEqual(lcm(a, b), d) + self.assertEqual(lcm(b, a), d) + self.assertEqual(lcm(-a, b), d) + self.assertEqual(lcm(b, -a), d) + self.assertEqual(lcm(a, -b), d) + self.assertEqual(lcm(-b, a), d) + self.assertEqual(lcm(-a, -b), d) + self.assertEqual(lcm(-b, -a), d) + + self.assertEqual(lcm(), 1) + self.assertEqual(lcm(120), 120) + self.assertEqual(lcm(-120), 120) + self.assertEqual(lcm(120, 84, 102), 14280) + self.assertEqual(lcm(120, 0, 84), 0) + + self.assertRaises(TypeError, lcm, 120.0) + self.assertRaises(TypeError, lcm, 120.0, 84) + self.assertRaises(TypeError, lcm, 120, 84.0) + self.assertRaises(TypeError, lcm, 120, 0, 84.0) + self.assertEqual(lcm(MyIndexable(120), MyIndexable(84)), 840) + + def test_isqrt(self): + isqrt = self.module.isqrt + # Test a variety of inputs, large and small. + test_values = ( + list(range(1000)) + + list(range(10**6 - 1000, 10**6 + 1000)) + + [2**e + i for e in range(60, 200) for i in range(-40, 40)] + + [3**9999, 10**5001] + ) + + for value in test_values: + with self.subTest(value=value): + s = isqrt(value) + self.assertIs(type(s), int) + self.assertLessEqual(s*s, value) + self.assertLess(value, (s+1)*(s+1)) + + # Negative values + with self.assertRaises(ValueError): + isqrt(-1) + + # Integer-like things + self.assertIntEqual(isqrt(True), 1) + self.assertIntEqual(isqrt(False), 0) + self.assertIntEqual(isqrt(MyIndexable(1729)), 41) + + # Overridden operators of an int subclass must not affect the + # result. + self.assertIntEqual(isqrt(BadIntSubclass(10**20)), 10**10) + self.assertIntEqual(isqrt(BadIntSubclass(10**20 - 1)), 10**10 - 1) + + with self.assertRaises(ValueError): + isqrt(MyIndexable(-3)) + + # Non-integer-like things + bad_values = [ + 3.5, "a string", Decimal("3.5"), 3.5j, + 100.0, -4.0, + ] + for value in bad_values: + with self.subTest(value=value): + with self.assertRaises(TypeError): + isqrt(value) + + @support.bigmemtest(2**32, memuse=0.85) + def test_isqrt_huge(self, size): + isqrt = self.module.isqrt + if size & 1: + size += 1 + v = 1 << size + w = isqrt(v) + self.assertEqual(w.bit_length(), size // 2 + 1) + self.assertEqual(w.bit_count(), 1) + + def test_perm(self): + perm = self.module.perm + factorial = self.module.factorial + # Test if factorial definition is satisfied + for n in range(500): + for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)): + self.assertEqual(perm(n, k), + factorial(n) // factorial(n - k)) + + # Test for Pascal's identity + for n in range(1, 100): + for k in range(1, n): + self.assertEqual(perm(n, k), perm(n - 1, k - 1) * k + perm(n - 1, k)) + + # Test corner cases + for n in range(1, 100): + self.assertEqual(perm(n, 0), 1) + self.assertEqual(perm(n, 1), n) + self.assertEqual(perm(n, n), factorial(n)) + + # Test one argument form + for n in range(20): + self.assertEqual(perm(n), factorial(n)) + self.assertEqual(perm(n, None), factorial(n)) + + # Raises TypeError if any argument is non-integer or argument count is + # not 1 or 2 + self.assertRaises(TypeError, perm, 10, 1.0) + self.assertRaises(TypeError, perm, 10, Decimal(1.0)) + self.assertRaises(TypeError, perm, 10, Fraction(1, 1)) + self.assertRaises(TypeError, perm, 10, "1") + self.assertRaises(TypeError, perm, 10.0, 1) + self.assertRaises(TypeError, perm, Decimal(10.0), 1) + self.assertRaises(TypeError, perm, Fraction(10, 1), 1) + self.assertRaises(TypeError, perm, "10", 1) + + self.assertRaises(TypeError, perm) + self.assertRaises(TypeError, perm, 10, 1, 3) + self.assertRaises(TypeError, perm) + + # Raises Value error if not k or n are negative numbers + self.assertRaises(ValueError, perm, -1, 1) + self.assertRaises(ValueError, perm, -2**1000, 1) + self.assertRaises(ValueError, perm, 1, -1) + self.assertRaises(ValueError, perm, 1, -2**1000) + + # Returns zero if k is greater than n + self.assertEqual(perm(1, 2), 0) + self.assertEqual(perm(1, 2**1000), 0) + + n = 2**1000 + self.assertEqual(perm(n, 0), 1) + self.assertEqual(perm(n, 1), n) + self.assertEqual(perm(n, 2), n * (n-1)) + if support.check_impl_detail(cpython=True): + self.assertRaises(OverflowError, perm, n, n) + + for n, k in (True, True), (True, False), (False, False): + self.assertIntEqual(perm(n, k), 1) + self.assertEqual(perm(IntSubclass(5), IntSubclass(2)), 20) + self.assertEqual(perm(MyIndexable(5), MyIndexable(2)), 20) + for k in range(3): + self.assertIs(type(perm(IntSubclass(5), IntSubclass(k))), int) + self.assertIs(type(perm(MyIndexable(5), MyIndexable(k))), int) + + def test_comb(self): + comb = self.module.comb + factorial = self.module.factorial + # Test if factorial definition is satisfied + for n in range(500): + for k in (range(n + 1) if n < 100 else range(30) if n < 200 else range(10)): + self.assertEqual(comb(n, k), factorial(n) + // (factorial(k) * factorial(n - k))) + + # Test for Pascal's identity + for n in range(1, 100): + for k in range(1, n): + self.assertEqual(comb(n, k), comb(n - 1, k - 1) + comb(n - 1, k)) + + # Test corner cases + for n in range(100): + self.assertEqual(comb(n, 0), 1) + self.assertEqual(comb(n, n), 1) + + for n in range(1, 100): + self.assertEqual(comb(n, 1), n) + self.assertEqual(comb(n, n - 1), n) + + # Test Symmetry + for n in range(100): + for k in range(n // 2): + self.assertEqual(comb(n, k), comb(n, n - k)) + + # Raises TypeError if any argument is non-integer or argument count is + # not 2 + self.assertRaises(TypeError, comb, 10, 1.0) + self.assertRaises(TypeError, comb, 10, Decimal(1.0)) + self.assertRaises(TypeError, comb, 10, "1") + self.assertRaises(TypeError, comb, 10.0, 1) + self.assertRaises(TypeError, comb, Decimal(10.0), 1) + self.assertRaises(TypeError, comb, "10", 1) + + self.assertRaises(TypeError, comb, 10) + self.assertRaises(TypeError, comb, 10, 1, 3) + self.assertRaises(TypeError, comb) + + # Raises Value error if not k or n are negative numbers + self.assertRaises(ValueError, comb, -1, 1) + self.assertRaises(ValueError, comb, -2**1000, 1) + self.assertRaises(ValueError, comb, 1, -1) + self.assertRaises(ValueError, comb, 1, -2**1000) + + # Returns zero if k is greater than n + self.assertEqual(comb(1, 2), 0) + self.assertEqual(comb(1, 2**1000), 0) + + n = 2**1000 + self.assertEqual(comb(n, 0), 1) + self.assertEqual(comb(n, 1), n) + self.assertEqual(comb(n, 2), n * (n-1) // 2) + self.assertEqual(comb(n, n), 1) + self.assertEqual(comb(n, n-1), n) + self.assertEqual(comb(n, n-2), n * (n-1) // 2) + if support.check_impl_detail(cpython=True): + self.assertRaises(OverflowError, comb, n, n//2) + + for n, k in (True, True), (True, False), (False, False): + self.assertIntEqual(comb(n, k), 1) + self.assertEqual(comb(IntSubclass(5), IntSubclass(2)), 10) + self.assertEqual(comb(MyIndexable(5), MyIndexable(2)), 10) + for k in range(3): + self.assertIs(type(comb(IntSubclass(5), IntSubclass(k))), int) + self.assertIs(type(comb(MyIndexable(5), MyIndexable(k))), int) + + +class MathTests(IntMathTests): + import math as module + + +class MiscTests(unittest.TestCase): + + def test_module_name(self): + import math.integer + self.assertEqual(math.integer.__name__, 'math.integer') + for name in dir(math.integer): + if not name.startswith('_'): + obj = getattr(math.integer, name) + self.assertEqual(obj.__module__, 'math.integer') + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_memoryview.py b/Lib/test/test_memoryview.py index 7b04a4ddd83..f71b6f53486 100644 --- a/Lib/test/test_memoryview.py +++ b/Lib/test/test_memoryview.py @@ -575,6 +575,79 @@ def test_array_assign(self): m[:] = new_a self.assertEqual(a, new_a) + def test_compare_equal(self): + # A memoryview is equal to itself: there is no need to compare + # individual values. This is not true for float values since they can + # be NaN, and NaN is not equal to itself. + + def check_equal(view, is_equal): + self.assertEqual(view == view, is_equal) + self.assertEqual(view != view, not is_equal) + + # Comparison with a different memoryview doesn't use + # the optimization and should give the same result. + view2 = memoryview(view) + self.assertEqual(view2 == view, is_equal) + self.assertEqual(view2 != view2, not is_equal) + + # Test integer formats + for int_format in 'bBhHiIlLqQ': + with self.subTest(format=int_format): + a = array.array(int_format, [1, 2, 3]) + m = memoryview(a) + check_equal(m, True) + + if int_format in 'bB': + m2 = m.cast('@' + m.format) + check_equal(m2, True) + + # Test 'c' format + a = array.array('B', [1, 2, 3]) + m = memoryview(a.tobytes()).cast('c') + check_equal(m, True) + + # Test 'n' and 'N' formats + if struct.calcsize('L') == struct.calcsize('N'): + int_format = 'L' + elif struct.calcsize('Q') == struct.calcsize('N'): + int_format = 'Q' + else: + int_format = None + if int_format: + a = array.array(int_format, [1, 2, 3]) + m = memoryview(a.tobytes()).cast('N') + check_equal(m, True) + m = memoryview(a.tobytes()).cast('n') + check_equal(m, True) + + # Test '?' format + m = memoryview(b'\0\1\2').cast('?') + check_equal(m, True) + + # Test float formats + for float_format in 'fd': + with self.subTest(format=float_format): + a = array.array(float_format, [1.0, 2.0, float('nan')]) + m = memoryview(a) + # nan is not equal to nan + check_equal(m, False) + + a = array.array(float_format, [1.0, 2.0, 3.0]) + m = memoryview(a) + check_equal(m, True) + + # Test complex formats + for complex_format in ('Zf', 'Zd'): + with self.subTest(format=complex_format): + data = struct.pack(complex_format * 3, 1.0, 2.0, float('nan')) + m = memoryview(data).cast(complex_format) + # nan is not equal to nan + check_equal(m, False) + + data = struct.pack(complex_format * 3, 1.0, 2.0, 3.0) + m = memoryview(data).cast(complex_format) + check_equal(m, True) + def test_boolean_format(self): # Test '?' format (keep all the checks below for UBSan) # See github.com/python/cpython/issues/148390. @@ -643,6 +716,14 @@ def test_half_float(self): self.assertEqual(half_view.nbytes * 2, float_view.nbytes) self.assertListEqual(half_view.tolist(), float_view.tolist()) + def test_complex_types(self): + float_complex_data = struct.pack('FFF', 0.0, -1.5j, 1+2j) + double_complex_data = struct.pack('DDD', 0.0, -1.5j, 1+2j) + float_complex_view = memoryview(float_complex_data).cast('Zf') + double_complex_view = memoryview(double_complex_data).cast('Zd') + self.assertEqual(float_complex_view.nbytes * 2, double_complex_view.nbytes) + self.assertListEqual(float_complex_view.tolist(), double_complex_view.tolist()) + def test_memoryview_hex(self): # Issue #9951: memoryview.hex() segfaults with non-contiguous buffers. x = b'0' * 200000 @@ -659,10 +740,10 @@ def test_memoryview_hex_separator(self): self.assertEqual(m2.hex(':', -2), '6564:6362:61') self.assertEqual(m2.hex(sep=':', bytes_per_sep=2), '65:6463:6261') self.assertEqual(m2.hex(sep=':', bytes_per_sep=-2), '6564:6362:61') - for bytes_per_sep in 5, -5, 2**31-1, -(2**31-1): + for bytes_per_sep in 5, -5, sys.maxsize, -sys.maxsize: with self.subTest(bytes_per_sep=bytes_per_sep): self.assertEqual(m2.hex(':', bytes_per_sep), '6564636261') - for bytes_per_sep in 2**31, -2**31, 2**1000, -2**1000: + for bytes_per_sep in sys.maxsize+1, -sys.maxsize-1, 2**1000, -2**1000: with self.subTest(bytes_per_sep=bytes_per_sep): try: self.assertEqual(m2.hex(':', bytes_per_sep), '6564636261') diff --git a/Lib/test/test_metaclass.py b/Lib/test/test_metaclass.py index dfa6c633a63..627c29fdb18 100644 --- a/Lib/test/test_metaclass.py +++ b/Lib/test/test_metaclass.py @@ -268,17 +268,17 @@ ... >>> Base.value 1 - >>> WeirdClass.value # TODO: RUSTPYTHON; AttributeError: type object 'WeirdClass' has no attribute 'value' # doctest: +SKIP + >>> WeirdClass.value 1 >>> Base.value = 2 >>> Base.value 2 - >>> WeirdClass.value # TODO: RUSTPYTHON; AttributeError: type object 'WeirdClass' has no attribute 'value' # doctest: +SKIP + >>> WeirdClass.value 2 >>> Base.value = 3 >>> Base.value 3 - >>> WeirdClass.value # TODO: RUSTPYTHON; AttributeError: type object 'WeirdClass' has no attribute 'value' # doctest: +SKIP + >>> WeirdClass.value 3 """ @@ -292,8 +292,7 @@ __test__ = {'doctests' : doctests} def load_tests(loader, tests, pattern): - from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON - tests.addTest(doctest.DocTestSuite(checker=DocTestChecker())) + tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py index a7d1d724ff0..f14de5c23d5 100644 --- a/Lib/test/test_mimetypes.py +++ b/Lib/test/test_mimetypes.py @@ -135,9 +135,15 @@ def check_extensions(): for mime_type, ext in ( ("application/epub+zip", ".epub"), ("application/octet-stream", ".bin"), + ("application/dicom", ".dcm"), ("application/gzip", ".gz"), ("application/ogg", ".ogx"), + ("application/pdf", ".pdf"), ("application/postscript", ".ps"), + ("application/rtf", ".rtf"), + ("application/sql", ".sql"), + ("application/texinfo", ".texi"), + ("application/toml", ".toml"), ("application/vnd.apple.mpegurl", ".m3u"), ("application/vnd.ms-excel", ".xls"), ("application/vnd.ms-fontobject", ".eot"), @@ -150,11 +156,11 @@ def check_extensions(): ("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx"), ("application/vnd.openxmlformats-officedocument.wordprocessingml.document", ".docx"), ("application/vnd.rar", ".rar"), + ("application/vnd.sqlite3", ".sqlite3"), ("application/x-7z-compressed", ".7z"), ("application/x-debian-package", ".deb"), ("application/x-httpd-php", ".php"), ("application/x-rpm", ".rpm"), - ("application/x-texinfo", ".texi"), ("application/x-troff", ".roff"), ("application/xml", ".xsl"), ("application/yaml", ".yaml"), @@ -176,6 +182,7 @@ def check_extensions(): ("image/jp2", ".jp2"), ("image/jpeg", ".jpg"), ("image/jpm", ".jpm"), + ("image/jxl", ".jxl"), ("image/t38", ".t38"), ("image/tiff", ".tiff"), ("image/tiff-fx", ".tfx"), @@ -187,7 +194,6 @@ def check_extensions(): ("model/stl", ".stl"), ("text/html", ".html"), ("text/plain", ".txt"), - ("text/rtf", ".rtf"), ("text/x-rst", ".rst"), ("video/matroska", ".mkv"), ("video/matroska-3d", ".mk3d"), @@ -265,6 +271,10 @@ def test_init_knownfiles(self): mimetypes.init() self.assertEqual(guess_file_type("file.test2")[0], "testing/test2") + @unittest.skipIf(sys.platform == "win32", "non-Windows only") + def test_default_knownfiles(self): + self.assertIn("/etc/mime.types", knownfiles) + def test_added_types_are_used(self): mimetypes.add_type('testing/default-type', '') mime_type, _ = mimetypes.guess_type('') @@ -349,13 +359,12 @@ def test_non_standard_types(self): eq = self.assertEqual # First try strict eq(self.db.guess_file_type('foo.xul', strict=True), (None, None)) - eq(self.db.guess_extension('image/jpg', strict=True), None) # And then non-strict eq(self.db.guess_file_type('foo.xul', strict=False), ('text/xul', None)) eq(self.db.guess_file_type('foo.XUL', strict=False), ('text/xul', None)) eq(self.db.guess_file_type('foo.invalid', strict=False), (None, None)) - eq(self.db.guess_extension('image/jpg', strict=False), '.jpg') - eq(self.db.guess_extension('image/JPG', strict=False), '.jpg') + eq(self.db.guess_extension('image/jpeg', strict=False), '.jpg') + eq(self.db.guess_extension('image/JPEG', strict=False), '.jpg') def test_filename_with_url_delimiters(self): # bpo-38449: URL delimiters cases should be handled also. @@ -416,8 +425,8 @@ def test_guess_all_types(self): self.assertTrue(set(all) >= {'.bat', '.c', '.h', '.ksh', '.pl', '.txt'}) self.assertEqual(len(set(all)), len(all)) # no duplicates # And now non-strict - all = self.db.guess_all_extensions('image/jpg', strict=False) - self.assertEqual(all, ['.jpg']) + all = self.db.guess_all_extensions('image/jpeg', strict=False) + self.assertEqual(all, ['.jpg', '.jpe', '.jpeg']) # And now for no hits all = self.db.guess_all_extensions('image/jpg', strict=True) self.assertEqual(all, []) @@ -475,9 +484,7 @@ def test_keywords_args_api(self): self.assertEqual(self.db.guess_type( url="scheme:foo.html", strict=True), ("text/html", None)) self.assertEqual(self.db.guess_all_extensions( - type='image/jpg', strict=True), []) - self.assertEqual(self.db.guess_extension( - type='image/jpg', strict=False), '.jpg') + type='image/jpeg', strict=True), ['.jpg', '.jpe', '.jpeg']) @unittest.skipUnless(sys.platform.startswith("win"), "Windows only") @@ -505,6 +512,9 @@ def test_registry_parsing(self): eq(self.db.guess_type("image.jpg"), ("image/jpeg", None)) eq(self.db.guess_type("image.png"), ("image/png", None)) + def test_default_knownfiles(self): + self.assertEqual(knownfiles, []) + @unittest.skipIf(not hasattr(_winapi, "_mimetypes_read_windows_registry"), "read_windows_registry accelerator unavailable") def test_registry_accelerator(self): @@ -539,15 +549,15 @@ def test_parse_args(self): args, help_text = mimetypes._parse_args("--invalid") self.assertTrue(help_text.startswith("usage: ")) - args, _ = mimetypes._parse_args(shlex.split("-l -e image/jpg")) + args, _ = mimetypes._parse_args(shlex.split("-l -e image/jpeg")) self.assertTrue(args.extension) self.assertTrue(args.lenient) - self.assertEqual(args.type, ["image/jpg"]) + self.assertEqual(args.type, ["image/jpeg"]) - args, _ = mimetypes._parse_args(shlex.split("-e image/jpg")) + args, _ = mimetypes._parse_args(shlex.split("-e image/jpeg")) self.assertTrue(args.extension) self.assertFalse(args.lenient) - self.assertEqual(args.type, ["image/jpg"]) + self.assertEqual(args.type, ["image/jpeg"]) args, _ = mimetypes._parse_args(shlex.split("-l foo.webp")) self.assertFalse(args.extension) @@ -578,7 +588,6 @@ def test_multiple_inputs_error(self): def test_invocation(self): for command, expected in [ - ("-l -e image/jpg", ".jpg"), ("-e image/jpeg", ".jpg"), ("-l foo.webp", "type: image/webp encoding: None"), ]: diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py index 500d8e8bbac..1e75d2a16d2 100644 --- a/Lib/test/test_minidom.py +++ b/Lib/test/test_minidom.py @@ -480,9 +480,16 @@ def testGetAttributeNS(self): self.assertEqual(child2.getAttributeNS("http://www.python.org", "missing"), '') - def testGetAttributeNode(self): pass + def testGetAttributeNode(self): + dom = parseString("") + elem = dom.documentElement + attr = elem.getAttributeNode("a") + self.assertEqual(attr.name, "a") + self.assertEqual(attr.value, "1") + self.assertIs(attr.ownerElement, elem) + self.assertIsNone(elem.getAttributeNode("b")) + dom.unlink() - @unittest.expectedFailure # TODO: RUSTPYTHON def testGetElementsByTagNameNS(self): d=""" @@ -641,7 +648,32 @@ def test_toprettyxml_preserves_content_of_text_node(self): dom.getElementsByTagName('B')[0].childNodes[0].toxml(), dom2.getElementsByTagName('B')[0].childNodes[0].toxml()) - @unittest.expectedFailure # TODO: RUSTPYTHON + @unittest.expectedFailure # TODO: RUSTPYTHON; pyexpat does not report DTD element declarations + def test_isWhitespaceInElementContent(self): + # only " \t\r\n" are whitespace in XML (see XML 1.0, 2.3) + dom = parseString(']>' + ' x\xa0') + children = dom.documentElement.childNodes + self.assertTrue(children[0].isWhitespaceInElementContent) + self.assertFalse(children[2].isWhitespaceInElementContent) + dom.unlink() + + @unittest.expectedFailure # TODO: RUSTPYTHON; pyexpat does not report DTD element declarations + def test_remove_whitespace_in_element_content(self): + from xml.dom.xmlbuilder import DOMBuilder, DOMInputSource + builder = DOMBuilder() + builder.setFeature("whitespace-in-element-content", False) + source = DOMInputSource() + source.byteStream = io.BytesIO( + b']>' + b' x\xc2\xa0') + dom = builder.parse(source) + children = dom.documentElement.childNodes + # ignorable whitespace is removed, other characters are not + self.assertEqual([node.nodeName for node in children], ['b', '#text']) + self.assertEqual(children[1].data, '\xa0') + dom.unlink() + def testProcessingInstruction(self): dom = parseString('') pi = dom.documentElement.firstChild @@ -671,9 +703,34 @@ def testTextRepr(self): self.assertEqual(str(el), repr(el)) self.assertEqual('', str(el)) - def testWriteText(self): pass + def testWriteText(self): + dom = parseString("text<&>") + elem = dom.documentElement + writer = io.StringIO() + elem.writexml(writer) + self.assertEqual(writer.getvalue(), + "text<&>") + writer = io.StringIO() + elem.writexml(writer, indent=" ", addindent=" ", newl="\n") + self.assertEqual(writer.getvalue(), + " \n" + " text\n" + " <&>\n" + " \n") + dom.unlink() - def testDocumentElement(self): pass + def testDocumentElement(self): + dom = parseString("") + elem = dom.documentElement + self.assertEqual(elem.tagName, "doc") + self.assertIs(elem, dom.childNodes[1]) + dom.unlink() + + dom = Document() + self.assertIsNone(dom.documentElement) + elem = dom.appendChild(dom.createElement("doc")) + self.assertIs(dom.documentElement, elem) + dom.unlink() def testTooManyDocumentElements(self): doc = parseString("") @@ -683,25 +740,126 @@ def testTooManyDocumentElements(self): elem.unlink() doc.unlink() - def testCreateElementNS(self): pass + def testCreateElementNS(self): + dom = Document() + elem = dom.createElementNS("http://xml.python.org/ns", "p:elem") + self.assertEqual(elem.nodeType, Node.ELEMENT_NODE) + self.assertEqual(elem.tagName, "p:elem") + self.assertEqual(elem.nodeName, "p:elem") + self.assertEqual(elem.namespaceURI, "http://xml.python.org/ns") + self.assertEqual(elem.prefix, "p") + self.assertEqual(elem.localName, "elem") + self.assertIs(elem.ownerDocument, dom) + self.assertIsNone(elem.parentNode) + + elem = dom.createElementNS("http://xml.python.org/ns", "elem") + self.assertEqual(elem.tagName, "elem") + self.assertIsNone(elem.prefix) + self.assertEqual(elem.localName, "elem") + dom.unlink() + + def testCreateAttributeNS(self): + dom = Document() + attr = dom.createAttributeNS("http://xml.python.org/ns", "p:attr") + self.assertEqual(attr.nodeType, Node.ATTRIBUTE_NODE) + self.assertEqual(attr.name, "p:attr") + self.assertEqual(attr.nodeName, "p:attr") + self.assertEqual(attr.namespaceURI, "http://xml.python.org/ns") + self.assertEqual(attr.prefix, "p") + self.assertEqual(attr.localName, "attr") + self.assertEqual(attr.value, "") + self.assertIs(attr.ownerDocument, dom) + self.assertIsNone(attr.ownerElement) + + elem = dom.appendChild(dom.createElement("doc")) + elem.setAttributeNode(attr) + self.assertIs(attr.ownerElement, elem) + self.assertIs(elem.getAttributeNodeNS("http://xml.python.org/ns", + "attr"), attr) + dom.unlink() + + def testParse(self): + # parsing from a file object is tested in testParseFromBinaryFile + # and testParseFromTextFile + dom = parse(tstfile) + self.assertEqual(dom.nodeType, Node.DOCUMENT_NODE) + self.assertEqual(dom.documentElement.tagName, "HTML") + dom.unlink() + + self.assertRaises(ExpatError, parseString, "") - def testCreateAttributeNS(self): pass + def testParseString(self): + dom = parseString("text") + self.assertEqual(dom.nodeType, Node.DOCUMENT_NODE) + self.assertEqual(dom.documentElement.tagName, "doc") + self.assertEqual(dom.documentElement.firstChild.data, "text") + dom.unlink() - def testParse(self): pass + dom = parseString(b"" + b"\xc3\xa9") + self.assertEqual(dom.documentElement.firstChild.data, "\xe9") + dom.unlink() - def testParseString(self): pass + def testComment(self): + dom = Document() + comment = dom.createComment("comment") + self.assertEqual(comment.nodeType, Node.COMMENT_NODE) + self.assertEqual(comment.nodeName, "#comment") + self.assertEqual(comment.data, "comment") + self.assertEqual(comment.nodeValue, "comment") + self.assertIsNone(comment.attributes) + dom.appendChild(comment) + self.assertEqual(dom.toxml(), + '') + dom.unlink() - def testComment(self): pass + dom = parseString("") + comment = dom.documentElement.firstChild + self.assertEqual(comment.nodeType, Node.COMMENT_NODE) + self.assertEqual(comment.data, "comment") + dom.unlink() - def testAttrListItem(self): pass + def testAttrListItem(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual(attrs.item(0).name, "a") + self.assertEqual(attrs.item(1).name, "b") + self.assertIsNone(attrs.item(2)) + dom.unlink() - def testAttrListItems(self): pass + def testAttrListItems(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual(attrs.items(), [("a", "1"), ("b", "2")]) + dom.unlink() - def testAttrListItemNS(self): pass + def testAttrListItemNS(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual(attrs.itemsNS(), [ + ((xml.dom.XMLNS_NAMESPACE, "p"), "http://xml.python.org/ns"), + (("http://xml.python.org/ns", "a"), "1"), + ((None, "b"), "2"), + ]) + dom.unlink() - def testAttrListKeys(self): pass + def testAttrListKeys(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual(list(attrs.keys()), ["a", "b"]) + dom.unlink() - def testAttrListKeysNS(self): pass + def testAttrListKeysNS(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual(list(attrs.keysNS()), [ + (xml.dom.XMLNS_NAMESPACE, "p"), + ("http://xml.python.org/ns", "a"), + (None, "b"), + ]) + dom.unlink() def testRemoveNamedItem(self): doc = parseString("") @@ -722,29 +880,161 @@ def testRemoveNamedItemNS(self): self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS, "http://xml.python.org/", "b") - def testAttrListValues(self): pass + def testAttrListValues(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual([attr.name for attr in attrs.values()], ["a", "b"]) + self.assertEqual([attr.value for attr in attrs.values()], ["1", "2"]) + dom.unlink() + + def testAttrListLength(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual(attrs.length, 2) + self.assertEqual(len(attrs), 2) + dom.unlink() + + dom = parseString("") + self.assertEqual(dom.documentElement.attributes.length, 0) + dom.unlink() - def testAttrListLength(self): pass + def testAttrList__getitem__(self): + dom = parseString("") + attrs = dom.documentElement.attributes + self.assertEqual(attrs["b"].value, "2") + self.assertEqual(attrs[("http://xml.python.org/ns", "a")].value, "1") + self.assertRaises(KeyError, attrs.__getitem__, "missing") + self.assertRaises(KeyError, attrs.__getitem__, (None, "missing")) + dom.unlink() + + def testAttrList__setitem__(self): + dom = parseString("") + elem = dom.documentElement + attrs = elem.attributes + attrs["a"] = "2" + self.assertEqual(elem.getAttribute("a"), "2") + attrs["b"] = "3" + self.assertEqual(elem.getAttribute("b"), "3") + self.assertEqual(attrs.length, 2) + + attr = dom.createAttribute("c") + attr.value = "4" + attrs["c"] = attr + self.assertIs(elem.getAttributeNode("c"), attr) + self.assertEqual(elem.getAttribute("c"), "4") + dom.unlink() - def testAttrList__getitem__(self): pass + def testSetAttrValueandNodeValue(self): + dom = parseString("") + attr = dom.documentElement.getAttributeNode("a") + self.assertEqual(attr.value, "1") + self.assertEqual(attr.nodeValue, "1") + attr.value = "2" + self.assertEqual(attr.nodeValue, "2") + attr.nodeValue = "3" + self.assertEqual(attr.value, "3") + self.assertEqual(dom.documentElement.getAttribute("a"), "3") + dom.unlink() - def testAttrList__setitem__(self): pass + def testParseElement(self): + dom = parseString("") + elem = dom.documentElement + self.assertEqual(elem.nodeType, Node.ELEMENT_NODE) + self.assertEqual(elem.tagName, "doc") + self.assertIsNone(elem.namespaceURI) + self.assertIs(elem.parentNode, dom) + self.assertIs(elem.ownerDocument, dom) + self.assertEqual([child.tagName for child in elem.childNodes], + ["child", "child"]) + dom.unlink() - def testSetAttrValueandNodeValue(self): pass + def testParseAttributes(self): + dom = parseString("") + elem = dom.documentElement + self.assertEqual(elem.getAttribute("a"), "1") + self.assertEqual(elem.getAttribute("b"), "&") + self.assertEqual(elem.getAttribute("missing"), "") + self.assertTrue(elem.hasAttribute("a")) + self.assertFalse(elem.hasAttribute("missing")) + attr = elem.getAttributeNode("a") + self.assertIsNone(attr.namespaceURI) + dom.unlink() - def testParseElement(self): pass + def testParseElementNamespaces(self): + dom = parseString("" + "") + elem = dom.documentElement + self.assertEqual(elem.tagName, "p:doc") + self.assertEqual(elem.namespaceURI, "http://xml.python.org/ns") + self.assertEqual(elem.prefix, "p") + self.assertEqual(elem.localName, "doc") + child = elem.getElementsByTagName("child")[0] + self.assertEqual(child.namespaceURI, "http://xml.python.org/default") + self.assertIsNone(child.prefix) + self.assertEqual(child.localName, "child") + dom.unlink() - def testParseAttributes(self): pass + def testParseAttributeNamespaces(self): + dom = parseString("") + elem = dom.documentElement + self.assertEqual(elem.getAttributeNS("http://xml.python.org/ns", "a"), + "1") + self.assertEqual(elem.getAttributeNS(None, "b"), "2") + attr = elem.getAttributeNodeNS("http://xml.python.org/ns", "a") + self.assertEqual(attr.name, "p:a") + self.assertEqual(attr.prefix, "p") + self.assertEqual(attr.localName, "a") + declaration = elem.getAttributeNode("xmlns:p") + self.assertEqual(declaration.namespaceURI, xml.dom.XMLNS_NAMESPACE) + self.assertEqual(declaration.value, "http://xml.python.org/ns") + dom.unlink() - def testParseElementNamespaces(self): pass + def testParseProcessingInstructions(self): + # the content of a processing instruction is tested + # in testProcessingInstruction + dom = parseString("") + pi = dom.childNodes[0] + self.assertEqual(pi.nodeType, Node.PROCESSING_INSTRUCTION_NODE) + self.assertEqual(pi.target, "before") + self.assertEqual(pi.data, "data") + self.assertIs(pi.parentNode, dom) + pi = dom.childNodes[2] + self.assertEqual(pi.target, "after") + self.assertEqual(pi.data, "") + dom.unlink() - def testParseAttributeNamespaces(self): pass + def testChildNodes(self): + dom = parseString("text") + children = dom.documentElement.childNodes + self.assertEqual(len(children), 3) + self.assertEqual([child.nodeType for child in children], + [Node.TEXT_NODE, Node.ELEMENT_NODE, Node.COMMENT_NODE]) + for child in children: + self.assertIs(child.parentNode, dom.documentElement) + dom.unlink() - def testParseProcessingInstructions(self): pass + dom = parseString("") + self.assertEqual(len(dom.documentElement.childNodes), 0) + dom.unlink() - def testChildNodes(self): pass + def testFirstChild(self): + dom = parseString("") + elem = dom.documentElement + self.assertEqual(elem.firstChild.tagName, "a") + self.assertEqual(elem.lastChild.tagName, "b") + self.assertIs(elem.firstChild, elem.childNodes[0]) + self.assertIs(elem.lastChild, elem.childNodes[-1]) + self.assertIsNone(elem.firstChild.previousSibling) + self.assertIs(elem.firstChild.nextSibling, elem.lastChild) + dom.unlink() - def testFirstChild(self): pass + dom = parseString("") + self.assertIsNone(dom.documentElement.firstChild) + self.assertIsNone(dom.documentElement.lastChild) + dom.unlink() def testHasChildNodes(self): dom = parseString("") @@ -1250,7 +1540,6 @@ def testNodeListItem(self): "test NodeList.item()") doc.unlink() - @unittest.expectedFailure # TODO: RUSTPYTHON def testEncodings(self): doc = parseString('€') self.assertEqual(doc.toxml(), diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py index 09b44c9ca1b..7801dc55ec9 100644 --- a/Lib/test/test_mmap.py +++ b/Lib/test/test_mmap.py @@ -1,3 +1,4 @@ +from test import support from test.support import ( requires, _2G, _4G, gc_collect, cpython_only, is_emscripten, is_apple, in_systemd_nspawn_sync_suppressed, @@ -5,8 +6,8 @@ from test.support.import_helper import import_module from test.support.os_helper import TESTFN, unlink from test.support.script_helper import assert_python_ok -import unittest import errno +import unittest import os import re import itertools @@ -33,7 +34,6 @@ def random_tagname(length=10): raise unittest.SkipTest("incompatible with Emscripten's mmap emulation.") -@unittest.skipIf(os.name == "nt", "TODO: RUSTPYTHON; Errors on setUp") class MmapTests(unittest.TestCase): def setUp(self): @@ -58,6 +58,7 @@ def test_basic(self): f.write(b'\0'* (PAGESIZE-3) ) f.flush() m = mmap.mmap(f.fileno(), 2 * PAGESIZE) + self.addCleanup(m.close) finally: f.close() @@ -73,7 +74,7 @@ def test_basic(self): # Shouldn't crash on boundary (Issue #5292) self.assertRaises(IndexError, m.__getitem__, len(m)) - self.assertRaises(IndexError, m.__setitem__, len(m), b'\0') + self.assertRaises(IndexError, m.__setitem__, len(m), 0) # Modify the file's content m[0] = b'3'[0] @@ -115,31 +116,28 @@ def test_basic(self): # Try to seek to negative position... self.assertRaises(ValueError, m.seek, -len(m)-1, 2) + @unittest.skipUnless(hasattr(mmap.mmap, 'resize'), 'requires mmap.resize') + def test_resize(self): + # Create a file to be mmap'ed. + with open(TESTFN, 'bw+') as f: + # Write 2 pages worth of data to the file + f.write(b'\0'* 2 * PAGESIZE) + f.flush() + m = mmap.mmap(f.fileno(), 2 * PAGESIZE) + self.addCleanup(m.close) + # Try resizing map - try: - m.resize(512) - except SystemError: - # resize() not supported - # No messages are printed, since the output of this test suite - # would then be different across platforms. - pass - else: - # resize() is supported - self.assertEqual(len(m), 512) - # Check that we can no longer seek beyond the new size. - self.assertRaises(ValueError, m.seek, 513, 0) - - # Check that the underlying file is truncated too - # (bug #728515) - f = open(TESTFN, 'rb') - try: - f.seek(0, 2) - self.assertEqual(f.tell(), 512) - finally: - f.close() - self.assertEqual(m.size(), 512) + m.resize(512) + self.assertEqual(len(m), 512) + # Check that we can no longer seek beyond the new size. + self.assertRaises(ValueError, m.seek, 513, 0) - m.close() + # Check that the underlying file is truncated too + # (bug #728515) + with open(TESTFN, 'rb') as f: + f.seek(0, 2) + self.assertEqual(f.tell(), 512) + self.assertEqual(m.size(), 512) def test_access_parameter(self): # Test for "access" keyword parameter @@ -184,15 +182,10 @@ def test_access_parameter(self): else: self.fail("Able to write to readonly memory map") - # Ensuring that readonly mmap can't be resized - try: - m.resize(2*mapsize) - except SystemError: # resize is not universally supported - pass - except TypeError: - pass - else: - self.fail("Able to resize readonly memory map") + if hasattr(m, 'resize'): + # Ensuring that readonly mmap can't be resized + with self.assertRaises(TypeError): + m.resize(2 * mapsize) with open(TESTFN, "rb") as fp: self.assertEqual(fp.read(), b'a'*mapsize, "Readonly memory map data file was modified") @@ -243,8 +236,9 @@ def test_access_parameter(self): with open(TESTFN, "rb") as fp: self.assertEqual(fp.read(), b'c'*mapsize, "Copy-on-write test data file should not be modified.") - # Ensuring copy-on-write maps cannot be resized - self.assertRaises(TypeError, m.resize, 2*mapsize) + if hasattr(m, 'resize'): + # Ensuring copy-on-write maps cannot be resized + self.assertRaises(TypeError, m.resize, 2 * mapsize) m.close() # Ensuring invalid access parameter raises exception @@ -271,67 +265,61 @@ def test_access_parameter(self): self.assertRaises(TypeError, m.write_byte, 0) m.close() - @unittest.skipIf(os.name == 'nt', 'trackfd not present on Windows') - def test_trackfd_parameter(self): + @support.subTests('close_original_fd', (True, False)) + def test_trackfd_parameter(self, close_original_fd): size = 64 with open(TESTFN, "wb") as f: f.write(b"a"*size) - for close_original_fd in True, False: - with self.subTest(close_original_fd=close_original_fd): - with open(TESTFN, "r+b") as f: - with mmap.mmap(f.fileno(), size, trackfd=False) as m: - if close_original_fd: - f.close() - self.assertEqual(len(m), size) - with self.assertRaises(OSError) as err_cm: - m.size() - self.assertEqual(err_cm.exception.errno, errno.EBADF) - with self.assertRaises(ValueError): - m.resize(size * 2) - with self.assertRaises(ValueError): - m.resize(size // 2) - self.assertEqual(m.closed, False) - - # Smoke-test other API - m.write_byte(ord('X')) - m[2] = ord('Y') - m.flush() - with open(TESTFN, "rb") as f: - self.assertEqual(f.read(4), b'XaYa') - self.assertEqual(m.tell(), 1) - m.seek(0) - self.assertEqual(m.tell(), 0) - self.assertEqual(m.read_byte(), ord('X')) - - self.assertEqual(m.closed, True) - self.assertEqual(os.stat(TESTFN).st_size, size) - - @unittest.skipIf(os.name == 'nt', 'trackfd not present on Windows') + with open(TESTFN, "r+b") as f: + with mmap.mmap(f.fileno(), size, trackfd=False) as m: + if close_original_fd: + f.close() + self.assertEqual(len(m), size) + with self.assertRaises(ValueError): + m.size() + if hasattr(m, 'resize'): + with self.assertRaises(ValueError): + m.resize(size * 2) + with self.assertRaises(ValueError): + m.resize(size // 2) + self.assertIs(m.closed, False) + + # Smoke-test other API + m.write_byte(ord('X')) + m[2] = ord('Y') + m.flush() + with open(TESTFN, "rb") as f: + self.assertEqual(f.read(4), b'XaYa') + self.assertEqual(m.tell(), 1) + m.seek(0) + self.assertEqual(m.tell(), 0) + self.assertEqual(m.read_byte(), ord('X')) + + if os.name == 'nt' and not close_original_fd: + self.assertRaises(PermissionError, os.rename, TESTFN, TESTFN+'1') + else: + os.rename(TESTFN, TESTFN+'1') + os.rename(TESTFN+'1', TESTFN) + + self.assertIs(m.closed, True) + self.assertEqual(os.stat(TESTFN).st_size, size) + def test_trackfd_neg1(self): size = 64 with mmap.mmap(-1, size, trackfd=False) as m: - with self.assertRaises(OSError): - m.size() with self.assertRaises(ValueError): - m.resize(size // 2) + m.size() + if hasattr(m, 'resize'): + with self.assertRaises(ValueError): + m.resize(size // 2) self.assertEqual(len(m), size) m[0] = ord('a') assert m[0] == ord('a') - @unittest.skipIf(os.name != 'nt', 'trackfd only fails on Windows') - def test_no_trackfd_parameter_on_windows(self): - # 'trackffd' is an invalid keyword argument for this function - size = 64 - with self.assertRaises(TypeError): - mmap.mmap(-1, size, trackfd=True) - with self.assertRaises(TypeError): - mmap.mmap(-1, size, trackfd=False) - def test_bad_file_desc(self): # Try opening a bad file descriptor... self.assertRaises(OSError, mmap.mmap, -2, 4096) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_tougher_find(self): # Do a tougher .find() test. SF bug 515943 pointed out that, in 2.2, # searching for data with embedded \0 bytes didn't work. @@ -350,7 +338,6 @@ def test_tougher_find(self): self.assertEqual(m.find(slice + b'x'), -1) m.close() - @unittest.skip("TODO: RUSTPYTHON; panic") def test_find_end(self): # test the new 'end' parameter works as expected with open(TESTFN, 'wb+') as f: @@ -367,6 +354,8 @@ def test_find_end(self): self.assertEqual(m.find(b'one', 1, -1), 8) self.assertEqual(m.find(b'one', 1, -2), -1) self.assertEqual(m.find(bytearray(b'one')), 0) + self.assertEqual(m.find(b'', n + 1), -1) + self.assertEqual(m.rfind(b'', n + 1), -1) for i in range(-n-1, n+1): for j in range(-n-1, n+1): @@ -390,7 +379,6 @@ def test_find_does_not_access_beyond_buffer(self): fm.find(b"fo", -2) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_rfind(self): # test the new 'end' parameter works as expected with open(TESTFN, 'wb+') as f: @@ -451,7 +439,6 @@ def test_length_0_large_offset(self): self.assertRaises(ValueError, mmap.mmap, f.fileno(), 0, offset=2147418112) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_move(self): # make move works everywhere (64-bit format problem earlier) with open(TESTFN, 'wb+') as f: @@ -510,8 +497,8 @@ def test_anonymous(self): b = x & 0xff m[x] = b self.assertEqual(m[x], b) + self.assertEqual(m.size(), PAGESIZE) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_read_all(self): m = mmap.mmap(-1, 16) self.addCleanup(m.close) @@ -533,7 +520,6 @@ def test_read_all(self): m.seek(9) self.assertEqual(m.read(-42), bytes(range(9, 16))) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_read_invalid_arg(self): m = mmap.mmap(-1, 16) self.addCleanup(m.close) @@ -621,13 +607,9 @@ def test_offset (self): self.assertEqual(m[0:3], b'foo') f.close() - # Try resizing map - try: + if hasattr(m, 'resize'): + # Try resizing map m.resize(512) - except SystemError: - pass - else: - # resize() is supported self.assertEqual(len(m), 512) # Check that we can no longer seek beyond the new size. self.assertRaises(ValueError, m.seek, 513, 0) @@ -650,7 +632,6 @@ def test_offset (self): except OSError: pass - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_subclass(self): class anon_mmap(mmap.mmap): def __new__(klass, *args, **kwargs): @@ -703,7 +684,6 @@ def test_io_methods(self): self.assertEqual(m[:], b"012barbaz9") self.assertRaises(ValueError, m.write, b"ba") - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_non_ascii_byte(self): for b in (129, 200, 255): # > 128 m = mmap.mmap(-1, 1) @@ -713,7 +693,6 @@ def test_non_ascii_byte(self): self.assertEqual(m.read_byte(), b) m.close() - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") @unittest.skipUnless(os.name == 'nt', 'requires Windows') def test_tagname(self): data1 = b"0123456789" @@ -806,7 +785,6 @@ def test_context_manager_exception(self): "wrong exception raised in context manager") self.assertTrue(m.closed, "context manager failed") - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_weakref(self): # Check mmap objects are weakrefable mm = mmap.mmap(-1, 16) @@ -816,7 +794,6 @@ def test_weakref(self): gc_collect() self.assertIs(wr(), None) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_write_returning_the_number_of_bytes_written(self): mm = mmap.mmap(-1, 16) self.assertEqual(mm.write(b""), 0) @@ -824,15 +801,12 @@ def test_write_returning_the_number_of_bytes_written(self): self.assertEqual(mm.write(b"yz"), 2) self.assertEqual(mm.write(b"python"), 6) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") + @unittest.skipUnless(hasattr(mmap.mmap, 'resize'), 'requires mmap.resize') def test_resize_past_pos(self): m = mmap.mmap(-1, 8192) self.addCleanup(m.close) m.read(5000) - try: - m.resize(4096) - except SystemError: - self.skipTest("resizing not supported") + m.resize(4096) self.assertEqual(m.read(14), b'') self.assertRaises(ValueError, m.read_byte) self.assertRaises(ValueError, m.write_byte, 42) @@ -845,7 +819,6 @@ def test_concat_repeat_exception(self): with self.assertRaises(TypeError): m * 2 - @unittest.skipIf(sys.platform.startswith("linux"), "TODO: RUSTPYTHON; memmap2 doesn't throw OSError when offset is not a multiple of mmap.PAGESIZE on Linux") def test_flush_return_value(self): # mm.flush() should return None on success, raise an # exception on error under all platforms. @@ -860,7 +833,6 @@ def test_flush_return_value(self): # See bpo-34754 for details. self.assertRaises(OSError, mm.flush, 1, len(b'python')) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON") def test_repr(self): open_mmap_repr_pat = re.compile( r" 1 and sys.argv[1] == '--snapshot-update': diff --git a/Lib/test/test_ordered_dict.py b/Lib/test/test_ordered_dict.py index 04942effa1f..ac24110cf63 100644 --- a/Lib/test/test_ordered_dict.py +++ b/Lib/test/test_ordered_dict.py @@ -74,6 +74,9 @@ def test_update(self): od.update(dict(pairs)) self.assertEqual(sorted(od.items()), pairs) # dict input od = OrderedDict() + od.update(frozendict(pairs)) + self.assertEqual(sorted(od.items()), pairs) # frozendict input + od = OrderedDict() od.update(**dict(pairs)) self.assertEqual(sorted(od.items()), pairs) # kwds input od = OrderedDict() @@ -288,9 +291,11 @@ def test_equality(self): pairs = pairs[2:] + pairs[:2] od2 = OrderedDict(pairs) self.assertNotEqual(od1, od2) # different order implies inequality - # comparison to regular dict is not order sensitive + # comparison to regular (frozen)dict is not order sensitive self.assertEqual(od1, dict(od2)) self.assertEqual(dict(od2), od1) + self.assertEqual(od1, frozendict(od2)) + self.assertEqual(frozendict(od1), od2) # different length implied inequality self.assertNotEqual(od1, OrderedDict(pairs[:-1])) @@ -698,6 +703,7 @@ def test_merge_operator(self): d |= list(b.items()) expected = OrderedDict({0: 0, 1: 1, 2: 2, 3: 3}) self.assertEqual(a | dict(b), expected) + self.assertEqual(a | frozendict(b), expected) self.assertEqual(a | b, expected) self.assertEqual(c, expected) self.assertEqual(d, expected) @@ -706,12 +712,17 @@ def test_merge_operator(self): c |= a expected = OrderedDict({1: 1, 2: 1, 3: 3, 0: 0}) self.assertEqual(dict(b) | a, expected) + self.assertEqual(frozendict(b) | a, expected) + self.assertEqual(a.__ror__(frozendict(b)), expected) self.assertEqual(b | a, expected) self.assertEqual(c, expected) self.assertIs(type(a | b), OrderedDict) self.assertIs(type(dict(a) | b), OrderedDict) + self.assertIs(type(frozendict(a) | b), frozendict) + self.assertIs(type(b.__ror__(frozendict(a))), OrderedDict) self.assertIs(type(a | dict(b)), OrderedDict) + self.assertIs(type(a | frozendict(b)), OrderedDict) expected = a.copy() a |= () diff --git a/Lib/test/test_os/__init__.py b/Lib/test/test_os/__init__.py new file mode 100644 index 00000000000..bc502ef32d2 --- /dev/null +++ b/Lib/test/test_os/__init__.py @@ -0,0 +1,6 @@ +import os.path +from test.support import load_package_tests + + +def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_os.py b/Lib/test/test_os/test_os.py similarity index 88% rename from Lib/test/test_os.py rename to Lib/test/test_os/test_os.py index c9cabd67355..ce8f228046b 100644 --- a/Lib/test/test_os.py +++ b/Lib/test/test_os/test_os.py @@ -7,7 +7,6 @@ import contextlib import decimal import errno -import fnmatch import fractions import itertools import locale @@ -25,18 +24,22 @@ import sysconfig import tempfile import textwrap +import threading import time import types import unittest import uuid import warnings from test import support -from test.support import import_helper from test.support import os_helper from test.support import socket_helper from test.support import infinite_recursion +from test.support import requires_root_user +from test.support import requires_non_root_user +from test.support import threading_helper from test.support import warnings_helper from platform import win32_is_iot +from .utils import create_file try: import resource @@ -46,10 +49,6 @@ import fcntl except ImportError: fcntl = None -try: - import _winapi -except ImportError: - _winapi = None try: import pwd all_users = [u.pw_uid for u in pwd.getpwall()] @@ -72,10 +71,6 @@ from test.support.os_helper import FakePath -root_in_posix = False -if hasattr(os, 'geteuid'): - root_in_posix = (os.geteuid() == 0) - # Detect whether we're on a Linux system that uses the (now outdated # and unmaintained) linuxthreads threading library. There's an issue # when combining linuxthreads with a failed execv call: see @@ -93,11 +88,6 @@ def requires_os_func(name): return unittest.skipUnless(hasattr(os, name), 'requires os.%s' % name) -def create_file(filename, content=b'content'): - with open(filename, "xb", 0) as fp: - fp.write(content) - - # On platforms without a native spawnv(), os.py provides a Python fallback # built on fork()+exec*() that reports argument conversion failures from the # child as exit status 127 instead of raising, so tests of the C @@ -184,6 +174,20 @@ def test_getcwdb(self): self.assertIsInstance(cwd, bytes) self.assertEqual(os.fsdecode(cwd), os.getcwd()) + def test_type_fqdn(self): + def fqdn(obj): + return (obj.__module__, obj.__qualname__) + + native = os.name + self.assertEqual(fqdn(os.stat_result), ("os", "stat_result")) + self.assertEqual(fqdn(os.times_result), (native, "times_result")) + if hasattr(os, "statvfs_result"): + self.assertEqual(fqdn(os.statvfs_result), ("os", "statvfs_result")) + if hasattr(os, "sched_param"): + self.assertEqual(fqdn(os.sched_param), (native, "sched_param")) + if hasattr(os, "waitid_result"): + self.assertEqual(fqdn(os.waitid_result), (native, "waitid_result")) + # Tests creating TESTFN class FileTests(unittest.TestCase): @@ -650,6 +654,15 @@ def setUp(self): self.addCleanup(os_helper.unlink, self.fname) create_file(self.fname, b"ABC") + def check_timestamp_agreement(self, result, names): + # Make sure that the st_?time and st_?time_ns fields roughly agree + # (they should always agree up to around tens-of-microseconds) + for name in names: + with self.subTest(name=name): + floaty = int(getattr(result, name) * 100_000) + nanosecondy = getattr(result, name + "_ns") // 10_000 + self.assertAlmostEqual(floaty, nanosecondy, delta=2, msg=name) + def check_stat_attributes(self, fname): result = os.stat(fname) @@ -670,21 +683,15 @@ def trunc(x): return x result[getattr(stat, name)]) self.assertIn(attr, members) - # Make sure that the st_?time and st_?time_ns fields roughly agree - # (they should always agree up to around tens-of-microseconds) - for name in 'st_atime st_mtime st_ctime'.split(): - floaty = int(getattr(result, name) * 100000) - nanosecondy = getattr(result, name + "_ns") // 10000 - self.assertAlmostEqual(floaty, nanosecondy, delta=2) - - # Ensure both birthtime and birthtime_ns roughly agree, if present + time_attributes = ['st_atime', 'st_mtime', 'st_ctime'] try: - floaty = int(result.st_birthtime * 100000) - nanosecondy = result.st_birthtime_ns // 10000 + result.st_birthtime + result.st_birthtime_ns except AttributeError: pass else: - self.assertAlmostEqual(floaty, nanosecondy, delta=2) + time_attributes.append('st_birthtime') + self.check_timestamp_agreement(result, time_attributes) try: result[200] @@ -745,6 +752,160 @@ def test_stat_result_pickle(self): unpickled = pickle.loads(p) self.assertEqual(result, unpickled) + def check_statx_attributes(self, filename): + maximal_mask = 0 + for name in dir(os): + if name.startswith('STATX_'): + maximal_mask |= getattr(os, name) + result = os.statx(filename, maximal_mask) + stat_result = os.stat(filename) + + time_attributes = ('stx_atime', 'stx_btime', 'stx_ctime', 'stx_mtime') + # gh-83714: stx_btime can be None on tmpfs even if STATX_BTIME mask + # is used + time_attributes = [name for name in time_attributes + if getattr(result, name) is not None] + self.check_timestamp_agreement(result, time_attributes) + + def getmask(name): + return getattr(os, name, 0) + + requirements = ( + ('stx_atime', os.STATX_ATIME), + ('stx_atime_ns', os.STATX_ATIME), + ('stx_atomic_write_segments_max', getmask('STATX_WRITE_ATOMIC')), + ('stx_atomic_write_unit_max', getmask('STATX_WRITE_ATOMIC')), + ('stx_atomic_write_unit_max_opt', getmask('STATX_WRITE_ATOMIC')), + ('stx_atomic_write_unit_min', getmask('STATX_WRITE_ATOMIC')), + ('stx_attributes', 0), + ('stx_attributes_mask', 0), + ('stx_blksize', 0), + ('stx_blocks', os.STATX_BLOCKS), + ('stx_btime', os.STATX_BTIME), + ('stx_btime_ns', os.STATX_BTIME), + ('stx_ctime', os.STATX_CTIME), + ('stx_ctime_ns', os.STATX_CTIME), + ('stx_dev', 0), + ('stx_dev_major', 0), + ('stx_dev_minor', 0), + ('stx_dio_mem_align', getmask('STATX_DIOALIGN')), + ('stx_dio_offset_align', getmask('STATX_DIOALIGN')), + ('stx_dio_read_offset_align', getmask('STATX_DIO_READ_ALIGN')), + ('stx_gid', os.STATX_GID), + ('stx_ino', os.STATX_INO), + ('stx_mask', 0), + ('stx_mnt_id', getmask('STATX_MNT_ID')), + ('stx_mode', os.STATX_TYPE | os.STATX_MODE), + ('stx_mtime', os.STATX_MTIME), + ('stx_mtime_ns', os.STATX_MTIME), + ('stx_nlink', os.STATX_NLINK), + ('stx_rdev', 0), + ('stx_rdev_major', 0), + ('stx_rdev_minor', 0), + ('stx_size', os.STATX_SIZE), + ('stx_subvol', getmask('STATX_SUBVOL')), + ('stx_uid', os.STATX_UID), + ) + optional_members = { + 'stx_atomic_write_segments_max', + 'stx_atomic_write_unit_max', + 'stx_atomic_write_unit_max_opt', + 'stx_atomic_write_unit_min', + 'stx_dio_mem_align', + 'stx_dio_offset_align', + 'stx_dio_read_offset_align', + 'stx_mnt_id', + 'stx_subvol', + } + float_type = { + 'stx_atime', + 'stx_btime', + 'stx_ctime', + 'stx_mtime', + } + + members = set(name for name in dir(result) + if name.startswith('stx_')) + tested = set(name for name, mask in requirements) + if members - tested: + raise ValueError(f"statx members not tested: {members - tested}") + + for name, mask in requirements: + with self.subTest(name=name): + try: + x = getattr(result, name) + except AttributeError: + if name in optional_members: + continue + else: + raise + + if not(result.stx_mask & mask == mask): + self.assertIsNone(x) + continue + + if name in float_type: + self.assertIsInstance(x, float) + else: + self.assertIsInstance(x, int) + + # Compare with stat_result + try: + b = getattr(stat_result, "st_" + name[4:]) + except AttributeError: + pass + else: + self.assertEqual(type(x), type(b)) + if isinstance(x, float): + self.assertAlmostEqual(x, b) + else: + self.assertEqual(x, b) + + self.assertEqual(result.stx_rdev_major, os.major(result.stx_rdev)) + self.assertEqual(result.stx_rdev_minor, os.minor(result.stx_rdev)) + self.assertEqual(result.stx_dev_major, os.major(result.stx_dev)) + self.assertEqual(result.stx_dev_minor, os.minor(result.stx_dev)) + + self.assertEqual(result.stx_attributes & result.stx_attributes_mask, + result.stx_attributes) + + @unittest.skipUnless(hasattr(os, 'statx'), 'test needs os.statx()') + def test_statx_attributes(self): + self.check_statx_attributes(self.fname) + + @unittest.skipUnless(hasattr(os, 'statx'), 'test needs os.statx()') + def test_statx_attributes_bytes(self): + try: + fname = self.fname.encode(sys.getfilesystemencoding()) + except UnicodeEncodeError: + self.skipTest("cannot encode %a for the filesystem" % self.fname) + self.check_statx_attributes(fname) + + @unittest.skipUnless(hasattr(os, 'statx'), 'test needs os.statx()') + def test_statx_attributes_pathlike(self): + self.check_statx_attributes(FakePath(self.fname)) + + @unittest.skipUnless(hasattr(os, 'statx'), 'test needs os.statx()') + def test_statx_result(self): + result = os.statx(self.fname, os.STATX_BASIC_STATS) + + # Check that attributes are read-only + members = [name for name in dir(result) + if name.startswith('stx_')] + for name in members: + try: + setattr(result, name, 1) + except AttributeError: + pass + else: + self.fail("No exception raised") + + # statx_result is not a tuple or tuple-like object. + with self.assertRaisesRegex(TypeError, 'not subscriptable'): + result[0] + with self.assertRaisesRegex(TypeError, 'cannot unpack'): + _, _ = result + @unittest.skipUnless(hasattr(os, 'statvfs'), 'test needs os.statvfs()') def test_statvfs_attributes(self): result = os.statvfs(self.fname) @@ -969,6 +1130,20 @@ def ns_to_sec(ns): # issue, os.utime() rounds towards minus infinity. return (ns * 1e-9) + 0.5e-9 + @staticmethod + def ns_to_sec_decimal(ns): + # Convert a number of nanosecond (int) to a number of seconds (Decimal). + # Round towards infinity by adding 0.5 nanosecond to avoid rounding + # issue, os.utime() rounds towards minus infinity. + return decimal.Decimal('1e-9') * ns + decimal.Decimal('0.5e-9') + + @staticmethod + def ns_to_sec_fraction(ns): + # Convert a number of nanosecond (int) to a number of seconds (Fraction). + # Round towards infinity by adding 0.5 nanosecond to avoid rounding + # issue, os.utime() rounds towards minus infinity. + return fractions.Fraction(ns, 10**9) + fractions.Fraction(1, 2*10**9) + def test_utime_by_indexed(self): # pass times as floating-point seconds as the second indexed parameter def set_time(filename, ns): @@ -989,6 +1164,24 @@ def set_time(filename, ns): os.utime(filename, times=(atime, mtime)) self._test_utime(set_time) + def test_utime_decimal(self): + # pass times as Decimal seconds + def set_time(filename, ns): + atime_ns, mtime_ns = ns + atime = self.ns_to_sec_decimal(atime_ns) + mtime = self.ns_to_sec_decimal(mtime_ns) + os.utime(filename, (atime, mtime)) + self._test_utime(set_time) + + def test_utime_fraction(self): + # pass times as Fraction seconds + def set_time(filename, ns): + atime_ns, mtime_ns = ns + atime = self.ns_to_sec_fraction(atime_ns) + mtime = self.ns_to_sec_fraction(mtime_ns) + os.utime(filename, (atime, mtime)) + self._test_utime(set_time) + @unittest.skipUnless(os.utime in os.supports_follow_symlinks, "follow_symlinks support for utime required " "for this test.") @@ -1085,9 +1278,15 @@ def test_large_time(self): if self.get_file_system(self.dirname) != "NTFS": self.skipTest("requires NTFS") - large = 5000000000 # some day in 2128 - os.utime(self.fname, (large, large)) - self.assertEqual(os.stat(self.fname).st_mtime, large) + times = ( + 5000000000, # some day in 2128 + # boundaries of the fast path cutoff in posixmodule.c:fill_time + -9223372037, -9223372036, 9223372035, 9223372036, + ) + for large in times: + with self.subTest(large=large): + os.utime(self.fname, (large, large)) + self.assertEqual(os.stat(self.fname).st_mtime, large) def test_utime_invalid_arguments(self): # seconds and nanoseconds parameters are mutually exclusive @@ -1487,6 +1686,14 @@ def test_reload_environ(self): self.assertNotIn(b'test_env', os.environb) self.assertNotIn('test_env', os.environ) + def test_clearenv(self): + os.environ['REMOVEME'] = '1' + os.environ.clear() + self.assertEqual(os.environ, {}) + + self.assertRaises(TypeError, os.environ.clear, None) + + class WalkTests(unittest.TestCase): """Tests for os.walk().""" is_fwalk = False @@ -1953,6 +2160,94 @@ def test_mode(self): self.assertEqual(os.stat(path).st_mode & 0o777, 0o555) self.assertEqual(os.stat(parent).st_mode & 0o777, 0o775) + @unittest.skipIf( + support.is_emscripten or support.is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_mode_with_parent_mode(self): + # Test the parent_mode parameter + parent = os.path.join(os_helper.TESTFN, 'dir1') + path = os.path.join(parent, 'dir2') + with os_helper.temp_umask(0o002): + # Specify mode for both leaf and parent directories + os.makedirs(path, 0o770, parent_mode=0o750) + self.assertTrue(os.path.exists(path)) + self.assertTrue(os.path.isdir(path)) + if os.name != 'nt': + # Leaf directory gets the mode parameter + self.assertEqual(os.stat(path).st_mode & 0o777, 0o770) + # Parent directory gets the parent_mode parameter + self.assertEqual(os.stat(parent).st_mode & 0o777, 0o750) + + @unittest.skipIf( + support.is_emscripten or support.is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_parent_mode_deep_hierarchy(self): + # Test parent_mode with deep directory hierarchy + base = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3') + with os_helper.temp_umask(0o002): + os.makedirs(base, 0o755, parent_mode=0o700) + self.assertTrue(os.path.exists(base)) + if os.name != 'nt': + # Check that all parent directories have parent_mode + level1 = os.path.join(os_helper.TESTFN, 'dir1') + level2 = os.path.join(level1, 'dir2') + self.assertEqual(os.stat(level1).st_mode & 0o777, 0o700) + self.assertEqual(os.stat(level2).st_mode & 0o777, 0o700) + # Leaf directory has the regular mode + self.assertEqual(os.stat(base).st_mode & 0o777, 0o755) + + @unittest.skipIf( + support.is_emscripten or support.is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_parent_mode_same_as_mode(self): + # Test emulating Python 3.6 behavior by setting parent_mode=mode + parent = os.path.join(os_helper.TESTFN, 'dir1') + path = os.path.join(parent, 'dir2') + with os_helper.temp_umask(0o002): + os.makedirs(path, 0o705, parent_mode=0o705) + self.assertTrue(os.path.exists(path)) + if os.name != 'nt': + # Both directories should have the same mode + self.assertEqual(os.stat(path).st_mode & 0o777, 0o705) + self.assertEqual(os.stat(parent).st_mode & 0o777, 0o705) + + @unittest.skipIf( + support.is_emscripten or support.is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_parent_mode_combined_with_umask(self): + # parent_mode, like mode, is combined with the process umask; it does + # not bypass it. + parent = os.path.join(os_helper.TESTFN, 'dir1') + path = os.path.join(parent, 'dir2') + with os_helper.temp_umask(0o022): + os.makedirs(path, 0o777, parent_mode=0o777) + self.assertTrue(os.path.isdir(path)) + if os.name != 'nt': + # 0o777 is masked down to 0o755 by the 0o022 umask, for both + # the leaf (mode) and the parent (parent_mode). + self.assertEqual(os.stat(path).st_mode & 0o777, 0o755) + self.assertEqual(os.stat(parent).st_mode & 0o777, 0o755) + @unittest.skipIf( support.is_wasi, "WASI's umask is a stub." @@ -2026,15 +2321,9 @@ def test_win32_mkdir_700(self): ) def tearDown(self): - path = os.path.join(os_helper.TESTFN, 'dir1', 'dir2', 'dir3', - 'dir4', 'dir5', 'dir6') - # If the tests failed, the bottom-most directory ('../dir6') - # may not have been created, so we look for the outermost directory - # that exists. - while not os.path.exists(path) and path != os_helper.TESTFN: - path = os.path.dirname(path) - - os.removedirs(path) + # Remove the whole tree regardless of which sub-directories a test + # created and regardless of their permission bits. + os_helper.rmtree(os_helper.TESTFN) @unittest.skipUnless(hasattr(os, "chown"), "requires os.chown()") @@ -2071,8 +2360,8 @@ def test_chown_gid(self): gid = os.stat(os_helper.TESTFN).st_gid self.assertEqual(gid, gid_2) - @unittest.skipUnless(root_in_posix and len(all_users) > 1, - "test needs root privilege and more than one user") + @requires_root_user + @unittest.skipUnless(len(all_users) > 1, "test needs more than one user") def test_chown_with_root(self): uid_1, uid_2 = all_users[:2] gid = os.stat(os_helper.TESTFN).st_gid @@ -2083,8 +2372,8 @@ def test_chown_with_root(self): uid = os.stat(os_helper.TESTFN).st_uid self.assertEqual(uid, uid_2) - @unittest.skipUnless(not root_in_posix and len(all_users) > 1, - "test needs non-root account and more than one user") + @requires_non_root_user + @unittest.skipUnless(len(all_users) > 1, "test needs and more than one user") def test_chown_without_permission(self): uid_1, uid_2 = all_users[:2] gid = os.stat(os_helper.TESTFN).st_gid @@ -2440,7 +2729,6 @@ def test_execve_invalid_env(self): # See https://github.com/python/cpython/issues/137934 and the other # related issues for the reason why we cannot test this on Windows. - @unittest.expectedFailure # TODO: RUSTPYTHON; TypeError: MyEnv.__getitem__() takes 1 positional argument but 2 were given @unittest.skipIf(os.name == "nt", "POSIX-specific test") @unittest.skipUnless(unix_shell and os.path.exists(unix_shell), "requires a shell") @@ -2489,42 +2777,6 @@ def test_execve_with_empty_path(self): self.fail('No OSError raised') -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") -class Win32ErrorTests(unittest.TestCase): - def setUp(self): - try: - os.stat(os_helper.TESTFN) - except FileNotFoundError: - exists = False - except OSError as exc: - exists = True - self.fail("file %s must not exist; os.stat failed with %s" - % (os_helper.TESTFN, exc)) - else: - self.fail("file %s must not exist" % os_helper.TESTFN) - - def test_rename(self): - self.assertRaises(OSError, os.rename, os_helper.TESTFN, os_helper.TESTFN+".bak") - - def test_remove(self): - self.assertRaises(OSError, os.remove, os_helper.TESTFN) - - def test_chdir(self): - self.assertRaises(OSError, os.chdir, os_helper.TESTFN) - - def test_mkdir(self): - self.addCleanup(os_helper.unlink, os_helper.TESTFN) - - with open(os_helper.TESTFN, "x") as f: - self.assertRaises(OSError, os.mkdir, os_helper.TESTFN) - - def test_utime(self): - self.assertRaises(OSError, os.utime, os_helper.TESTFN, None) - - def test_chmod(self): - self.assertRaises(OSError, os.chmod, os_helper.TESTFN, 0) - - @unittest.skipIf(support.is_wasi, "Cannot create invalid FD on WASI.") class TestInvalidFD(unittest.TestCase): singles = ["fchdir", "dup", "fstat", "fstatvfs", "tcgetpgrp", "ttyname"] @@ -2635,10 +2887,62 @@ def test_fpathconf_bad_fd(self): 'musl fpathconf ignores the file descriptor and returns a constant', ) def test_pathconf_negative_fd_uses_fd_semantics(self): + if os.pathconf not in os.supports_fd: + self.skipTest('needs fpathconf()') + with self.assertRaises(OSError) as ctx: os.pathconf(-1, 1) self.assertEqual(ctx.exception.errno, errno.EBADF) + @support.subTests("fd", [-1, -5]) + def test_negative_fd_ebadf(self, fd): + tests = [(os.stat, fd)] + if hasattr(os, "statx"): + tests.append((os.statx, fd, 0)) + if os.chdir in os.supports_fd: + tests.append((os.chdir, fd)) + if os.chmod in os.supports_fd: + tests.append((os.chmod, fd, 0o777)) + if hasattr(os, "chown") and os.chown in os.supports_fd: + tests.append((os.chown, fd, 0, 0)) + if os.listdir in os.supports_fd: + tests.append((os.listdir, fd)) + if os.utime in os.supports_fd: + tests.append((os.utime, fd, (0, 0))) + if hasattr(os, "truncate") and os.truncate in os.supports_fd: + tests.append((os.truncate, fd, 0)) + if hasattr(os, 'statvfs') and os.statvfs in os.supports_fd: + tests.append((os.statvfs, fd)) + if hasattr(os, "setxattr"): + tests.append((os.getxattr, fd, b"user.test")) + tests.append((os.setxattr, fd, b"user.test", b"1")) + tests.append((os.removexattr, fd, b"user.test")) + tests.append((os.listxattr, fd)) + if os.scandir in os.supports_fd: + tests.append((os.scandir, fd)) + + for func, *args in tests: + with self.subTest(func=func, args=args): + with self.assertRaises(OSError) as ctx: + func(*args) + self.assertEqual(ctx.exception.errno, errno.EBADF) + + if (hasattr(os, "execve") and os.execve in os.supports_fd + and support.has_subprocess_support): + # glibc fails with EINVAL, musl fails with EBADF + with self.assertRaises(OSError) as ctx: + os.execve(fd, [sys.executable, "-c", "pass"], os.environ) + self.assertIn(ctx.exception.errno, (errno.EBADF, errno.EINVAL)) + + if support.MS_WINDOWS: + import nt + self.assertFalse(nt._path_exists(fd)) + self.assertFalse(nt._path_lexists(fd)) + self.assertFalse(nt._path_isdir(fd)) + self.assertFalse(nt._path_isfile(fd)) + self.assertFalse(nt._path_islink(fd)) + self.assertFalse(nt._path_isjunction(fd)) + @unittest.skipUnless(hasattr(os, 'ftruncate'), 'test needs os.ftruncate()') def test_ftruncate(self): self.check(os.truncate, 0) @@ -2869,224 +3173,6 @@ def test_stat(self): for fn in self.unicodefn: os.stat(os.path.join(self.dir, fn)) -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") -class Win32KillTests(unittest.TestCase): - def _kill(self, sig): - # Start sys.executable as a subprocess and communicate from the - # subprocess to the parent that the interpreter is ready. When it - # becomes ready, send *sig* via os.kill to the subprocess and check - # that the return code is equal to *sig*. - import ctypes - from ctypes import wintypes - import msvcrt - - # Since we can't access the contents of the process' stdout until the - # process has exited, use PeekNamedPipe to see what's inside stdout - # without waiting. This is done so we can tell that the interpreter - # is started and running at a point where it could handle a signal. - PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe - PeekNamedPipe.restype = wintypes.BOOL - PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle - ctypes.POINTER(ctypes.c_char), # stdout buf - wintypes.DWORD, # Buffer size - ctypes.POINTER(wintypes.DWORD), # bytes read - ctypes.POINTER(wintypes.DWORD), # bytes avail - ctypes.POINTER(wintypes.DWORD)) # bytes left - msg = "running" - proc = subprocess.Popen([sys.executable, "-c", - "import sys;" - "sys.stdout.write('{}');" - "sys.stdout.flush();" - "input()".format(msg)], - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - stdin=subprocess.PIPE) - self.addCleanup(proc.stdout.close) - self.addCleanup(proc.stderr.close) - self.addCleanup(proc.stdin.close) - - count, max = 0, 100 - while count < max and proc.poll() is None: - # Create a string buffer to store the result of stdout from the pipe - buf = ctypes.create_string_buffer(len(msg)) - # Obtain the text currently in proc.stdout - # Bytes read/avail/left are left as NULL and unused - rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), - buf, ctypes.sizeof(buf), None, None, None) - self.assertNotEqual(rslt, 0, "PeekNamedPipe failed") - if buf.value: - self.assertEqual(msg, buf.value.decode()) - break - time.sleep(0.1) - count += 1 - else: - self.fail("Did not receive communication from the subprocess") - - os.kill(proc.pid, sig) - self.assertEqual(proc.wait(), sig) - - def test_kill_sigterm(self): - # SIGTERM doesn't mean anything special, but make sure it works - self._kill(signal.SIGTERM) - - def test_kill_int(self): - # os.kill on Windows can take an int which gets set as the exit code - self._kill(100) - - @unittest.skipIf(mmap is None, "requires mmap") - def _kill_with_event(self, event, name): - tagname = "test_os_%s" % uuid.uuid1() - m = mmap.mmap(-1, 1, tagname) - m[0] = 0 - - # Run a script which has console control handling enabled. - script = os.path.join(os.path.dirname(__file__), - "win_console_handler.py") - cmd = [sys.executable, script, tagname] - proc = subprocess.Popen(cmd, - creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) - - with proc: - # Let the interpreter startup before we send signals. See #3137. - for _ in support.sleeping_retry(support.SHORT_TIMEOUT): - if proc.poll() is None: - break - else: - # Forcefully kill the process if we weren't able to signal it. - proc.kill() - self.fail("Subprocess didn't finish initialization") - - os.kill(proc.pid, event) - - try: - # proc.send_signal(event) could also be done here. - # Allow time for the signal to be passed and the process to exit. - proc.wait(timeout=support.SHORT_TIMEOUT) - except subprocess.TimeoutExpired: - # Forcefully kill the process if we weren't able to signal it. - proc.kill() - self.fail("subprocess did not stop on {}".format(name)) - - @unittest.skip("subprocesses aren't inheriting Ctrl+C property") - @support.requires_subprocess() - def test_CTRL_C_EVENT(self): - from ctypes import wintypes - import ctypes - - # Make a NULL value by creating a pointer with no argument. - NULL = ctypes.POINTER(ctypes.c_int)() - SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler - SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int), - wintypes.BOOL) - SetConsoleCtrlHandler.restype = wintypes.BOOL - - # Calling this with NULL and FALSE causes the calling process to - # handle Ctrl+C, rather than ignore it. This property is inherited - # by subprocesses. - SetConsoleCtrlHandler(NULL, 0) - - self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT") - - @support.requires_subprocess() - def test_CTRL_BREAK_EVENT(self): - self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") - - -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") -class Win32ListdirTests(unittest.TestCase): - """Test listdir on Windows.""" - - def setUp(self): - self.created_paths = [] - for i in range(2): - dir_name = 'SUB%d' % i - dir_path = os.path.join(os_helper.TESTFN, dir_name) - file_name = 'FILE%d' % i - file_path = os.path.join(os_helper.TESTFN, file_name) - os.makedirs(dir_path) - with open(file_path, 'w', encoding='utf-8') as f: - f.write("I'm %s and proud of it. Blame test_os.\n" % file_path) - self.created_paths.extend([dir_name, file_name]) - self.created_paths.sort() - - def tearDown(self): - shutil.rmtree(os_helper.TESTFN) - - def test_listdir_no_extended_path(self): - """Test when the path is not an "extended" path.""" - # unicode - self.assertEqual( - sorted(os.listdir(os_helper.TESTFN)), - self.created_paths) - - # bytes - self.assertEqual( - sorted(os.listdir(os.fsencode(os_helper.TESTFN))), - [os.fsencode(path) for path in self.created_paths]) - - def test_listdir_extended_path(self): - """Test when the path starts with '\\\\?\\'.""" - # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath - # unicode - path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN) - self.assertEqual( - sorted(os.listdir(path)), - self.created_paths) - - # bytes - path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN)) - self.assertEqual( - sorted(os.listdir(path)), - [os.fsencode(path) for path in self.created_paths]) - - -@unittest.skipUnless(os.name == "nt", "NT specific tests") -class Win32ListdriveTests(unittest.TestCase): - """Test listdrive, listmounts and listvolume on Windows.""" - - def setUp(self): - # Get drives and volumes from fsutil - out = subprocess.check_output( - ["fsutil.exe", "volume", "list"], - cwd=os.path.join(os.getenv("SystemRoot", "\\Windows"), "System32"), - encoding="mbcs", - errors="ignore", - ) - lines = out.splitlines() - self.known_volumes = {l for l in lines if l.startswith('\\\\?\\')} - self.known_drives = {l for l in lines if l[1:] == ':\\'} - self.known_mounts = {l for l in lines if l[1:3] == ':\\'} - - def test_listdrives(self): - drives = os.listdrives() - self.assertIsInstance(drives, list) - self.assertSetEqual( - self.known_drives, - self.known_drives & set(drives), - ) - - def test_listvolumes(self): - volumes = os.listvolumes() - self.assertIsInstance(volumes, list) - self.assertSetEqual( - self.known_volumes, - self.known_volumes & set(volumes), - ) - - def test_listmounts(self): - for volume in os.listvolumes(): - try: - mounts = os.listmounts(volume) - except OSError as ex: - if support.verbose: - print("Skipping", volume, "because of", ex) - else: - self.assertIsInstance(mounts, list) - self.assertSetEqual( - set(mounts), - self.known_mounts & set(mounts), - ) - @unittest.skipUnless(hasattr(os, 'readlink'), 'needs os.readlink()') class ReadlinkTests(unittest.TestCase): @@ -3149,370 +3235,6 @@ def test_bytes(self): self.assertIsInstance(path, bytes) -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") -@os_helper.skip_unless_symlink -class Win32SymlinkTests(unittest.TestCase): - filelink = 'filelinktest' - filelink_target = os.path.abspath(__file__) - dirlink = 'dirlinktest' - dirlink_target = os.path.dirname(filelink_target) - missing_link = 'missing link' - - def setUp(self): - assert os.path.exists(self.dirlink_target) - assert os.path.exists(self.filelink_target) - assert not os.path.exists(self.dirlink) - assert not os.path.exists(self.filelink) - assert not os.path.exists(self.missing_link) - - def tearDown(self): - if os.path.exists(self.filelink): - os.remove(self.filelink) - if os.path.exists(self.dirlink): - os.rmdir(self.dirlink) - if os.path.lexists(self.missing_link): - os.remove(self.missing_link) - - def test_directory_link(self): - os.symlink(self.dirlink_target, self.dirlink) - self.assertTrue(os.path.exists(self.dirlink)) - self.assertTrue(os.path.isdir(self.dirlink)) - self.assertTrue(os.path.islink(self.dirlink)) - self.check_stat(self.dirlink, self.dirlink_target) - - def test_file_link(self): - os.symlink(self.filelink_target, self.filelink) - self.assertTrue(os.path.exists(self.filelink)) - self.assertTrue(os.path.isfile(self.filelink)) - self.assertTrue(os.path.islink(self.filelink)) - self.check_stat(self.filelink, self.filelink_target) - - def _create_missing_dir_link(self): - 'Create a "directory" link to a non-existent target' - linkname = self.missing_link - if os.path.lexists(linkname): - os.remove(linkname) - target = r'c:\\target does not exist.29r3c740' - assert not os.path.exists(target) - target_is_dir = True - os.symlink(target, linkname, target_is_dir) - - def test_remove_directory_link_to_missing_target(self): - self._create_missing_dir_link() - # For compatibility with Unix, os.remove will check the - # directory status and call RemoveDirectory if the symlink - # was created with target_is_dir==True. - os.remove(self.missing_link) - - def test_isdir_on_directory_link_to_missing_target(self): - self._create_missing_dir_link() - self.assertFalse(os.path.isdir(self.missing_link)) - - def test_rmdir_on_directory_link_to_missing_target(self): - self._create_missing_dir_link() - os.rmdir(self.missing_link) - - def check_stat(self, link, target): - self.assertEqual(os.stat(link), os.stat(target)) - self.assertNotEqual(os.lstat(link), os.stat(link)) - - bytes_link = os.fsencode(link) - self.assertEqual(os.stat(bytes_link), os.stat(target)) - self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link)) - - def test_12084(self): - level1 = os.path.abspath(os_helper.TESTFN) - level2 = os.path.join(level1, "level2") - level3 = os.path.join(level2, "level3") - self.addCleanup(os_helper.rmtree, level1) - - os.mkdir(level1) - os.mkdir(level2) - os.mkdir(level3) - - file1 = os.path.abspath(os.path.join(level1, "file1")) - create_file(file1) - - orig_dir = os.getcwd() - try: - os.chdir(level2) - link = os.path.join(level2, "link") - os.symlink(os.path.relpath(file1), "link") - self.assertIn("link", os.listdir(os.getcwd())) - - # Check os.stat calls from the same dir as the link - self.assertEqual(os.stat(file1), os.stat("link")) - - # Check os.stat calls from a dir below the link - os.chdir(level1) - self.assertEqual(os.stat(file1), - os.stat(os.path.relpath(link))) - - # Check os.stat calls from a dir above the link - os.chdir(level3) - self.assertEqual(os.stat(file1), - os.stat(os.path.relpath(link))) - finally: - os.chdir(orig_dir) - - @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users') - and os.path.exists(r'C:\ProgramData'), - 'Test directories not found') - def test_29248(self): - # os.symlink() calls CreateSymbolicLink, which creates - # the reparse data buffer with the print name stored - # first, so the offset is always 0. CreateSymbolicLink - # stores the "PrintName" DOS path (e.g. "C:\") first, - # with an offset of 0, followed by the "SubstituteName" - # NT path (e.g. "\??\C:\"). The "All Users" link, on - # the other hand, seems to have been created manually - # with an inverted order. - target = os.readlink(r'C:\Users\All Users') - self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) - - def test_buffer_overflow(self): - # Older versions would have a buffer overflow when detecting - # whether a link source was a directory. This test ensures we - # no longer crash, but does not otherwise validate the behavior - segment = 'X' * 27 - path = os.path.join(*[segment] * 10) - test_cases = [ - # overflow with absolute src - ('\\' + path, segment), - # overflow dest with relative src - (segment, path), - # overflow when joining src - (path[:180], path[:180]), - ] - for src, dest in test_cases: - try: - os.symlink(src, dest) - except FileNotFoundError: - pass - else: - try: - os.remove(dest) - except OSError: - pass - # Also test with bytes, since that is a separate code path. - try: - os.symlink(os.fsencode(src), os.fsencode(dest)) - except FileNotFoundError: - pass - else: - try: - os.remove(dest) - except OSError: - pass - - def test_appexeclink(self): - root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps') - if not os.path.isdir(root): - self.skipTest("test requires a WindowsApps directory") - - aliases = [os.path.join(root, a) - for a in fnmatch.filter(os.listdir(root), '*.exe')] - - for alias in aliases: - if support.verbose: - print() - print("Testing with", alias) - st = os.lstat(alias) - self.assertEqual(st, os.stat(alias)) - self.assertFalse(stat.S_ISLNK(st.st_mode)) - self.assertEqual(st.st_reparse_tag, stat.IO_REPARSE_TAG_APPEXECLINK) - self.assertTrue(os.path.isfile(alias)) - # testing the first one we see is sufficient - break - else: - self.skipTest("test requires an app execution alias") - -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") -class Win32JunctionTests(unittest.TestCase): - junction = 'junctiontest' - junction_target = os.path.dirname(os.path.abspath(__file__)) - - def setUp(self): - assert os.path.exists(self.junction_target) - assert not os.path.lexists(self.junction) - - def tearDown(self): - if os.path.lexists(self.junction): - os.unlink(self.junction) - - def test_create_junction(self): - _winapi.CreateJunction(self.junction_target, self.junction) - self.assertTrue(os.path.lexists(self.junction)) - self.assertTrue(os.path.exists(self.junction)) - self.assertTrue(os.path.isdir(self.junction)) - self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction)) - self.assertEqual(os.stat(self.junction), os.stat(self.junction_target)) - - # bpo-37834: Junctions are not recognized as links. - self.assertFalse(os.path.islink(self.junction)) - self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target), - os.path.normcase(os.readlink(self.junction))) - - def test_unlink_removes_junction(self): - _winapi.CreateJunction(self.junction_target, self.junction) - self.assertTrue(os.path.exists(self.junction)) - self.assertTrue(os.path.lexists(self.junction)) - - os.unlink(self.junction) - self.assertFalse(os.path.exists(self.junction)) - -@unittest.skipUnless(sys.platform == "win32", "Win32 specific tests") -class Win32NtTests(unittest.TestCase): - def test_getfinalpathname_handles(self): - nt = import_helper.import_module('nt') - ctypes = import_helper.import_module('ctypes') - # Ruff false positive -- it thinks we're redefining `ctypes` here - import ctypes.wintypes # noqa: F811 - - kernel = ctypes.WinDLL('Kernel32.dll', use_last_error=True) - kernel.GetCurrentProcess.restype = ctypes.wintypes.HANDLE - - kernel.GetProcessHandleCount.restype = ctypes.wintypes.BOOL - kernel.GetProcessHandleCount.argtypes = (ctypes.wintypes.HANDLE, - ctypes.wintypes.LPDWORD) - - # This is a pseudo-handle that doesn't need to be closed - hproc = kernel.GetCurrentProcess() - - handle_count = ctypes.wintypes.DWORD() - ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count)) - self.assertEqual(1, ok) - - before_count = handle_count.value - - # The first two test the error path, __file__ tests the success path - filenames = [ - r'\\?\C:', - r'\\?\NUL', - r'\\?\CONIN', - __file__, - ] - - for _ in range(10): - for name in filenames: - try: - nt._getfinalpathname(name) - except Exception: - # Failure is expected - pass - try: - os.stat(name) - except Exception: - pass - - ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count)) - self.assertEqual(1, ok) - - handle_delta = handle_count.value - before_count - - self.assertEqual(0, handle_delta) - - @support.requires_subprocess() - def test_stat_unlink_race(self): - # bpo-46785: the implementation of os.stat() falls back to reading - # the parent directory if CreateFileW() fails with a permission - # error. If reading the parent directory fails because the file or - # directory are subsequently unlinked, or because the volume or - # share are no longer available, then the original permission error - # should not be restored. - filename = os_helper.TESTFN - self.addCleanup(os_helper.unlink, filename) - deadline = time.time() + 5 - command = textwrap.dedent("""\ - import os - import sys - import time - - filename = sys.argv[1] - deadline = float(sys.argv[2]) - - while time.time() < deadline: - try: - with open(filename, "w") as f: - pass - except OSError: - pass - try: - os.remove(filename) - except OSError: - pass - """) - - with subprocess.Popen([sys.executable, '-c', command, filename, str(deadline)]) as proc: - while time.time() < deadline: - try: - os.stat(filename) - except FileNotFoundError as e: - assert e.winerror == 2 # ERROR_FILE_NOT_FOUND - try: - proc.wait(1) - except subprocess.TimeoutExpired: - proc.terminate() - - @support.requires_subprocess() - def test_stat_inaccessible_file(self): - filename = os_helper.TESTFN - ICACLS = os.path.expandvars(r"%SystemRoot%\System32\icacls.exe") - - with open(filename, "wb") as f: - f.write(b'Test data') - - stat1 = os.stat(filename) - - try: - # Remove all permissions from the file - subprocess.check_output([ICACLS, filename, "/inheritance:r"], - stderr=subprocess.STDOUT) - except subprocess.CalledProcessError as ex: - if support.verbose: - print(ICACLS, filename, "/inheritance:r", "failed.") - print(ex.stdout.decode("oem", "replace").rstrip()) - try: - os.unlink(filename) - except OSError: - pass - self.skipTest("Unable to create inaccessible file") - - def cleanup(): - # Give delete permission to the owner (us) - subprocess.check_output([ICACLS, filename, "/grant", "*WD:(D)"], - stderr=subprocess.STDOUT) - os.unlink(filename) - - self.addCleanup(cleanup) - - if support.verbose: - print("File:", filename) - print("stat with access:", stat1) - - # First test - we shouldn't raise here, because we still have access to - # the directory and can extract enough information from its metadata. - stat2 = os.stat(filename) - - if support.verbose: - print(" without access:", stat2) - - # We may not get st_dev/st_ino, so ensure those are 0 or match - self.assertIn(stat2.st_dev, (0, stat1.st_dev)) - self.assertIn(stat2.st_ino, (0, stat1.st_ino)) - - # st_mode and st_size should match (for a normal file, at least) - self.assertEqual(stat1.st_mode, stat2.st_mode) - self.assertEqual(stat1.st_size, stat2.st_size) - - # st_ctime and st_mtime should be the same - self.assertEqual(stat1.st_ctime, stat2.st_ctime) - self.assertEqual(stat1.st_mtime, stat2.st_mtime) - - # st_atime should be the same or later - self.assertGreaterEqual(stat1.st_atime, stat2.st_atime) - - @os_helper.skip_unless_symlink class NonLocalSymlinkTests(unittest.TestCase): @@ -3589,6 +3311,7 @@ def test_getppid(self): self.assertEqual(error, b'') self.assertEqual(int(stdout), os.getpid()) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def check_waitpid(self, code, exitcode, callback=None): if sys.platform == 'win32': # On Windows, os.spawnv() simply joins arguments with spaces: @@ -3691,30 +3414,35 @@ def create_args(self, *, with_env=False, use_bytes=False): return program, args + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnl') def test_spawnl(self): program, args = self.create_args() exitcode = os.spawnl(os.P_WAIT, program, *args) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnle') def test_spawnle(self): program, args = self.create_args(with_env=True) exitcode = os.spawnle(os.P_WAIT, program, *args, self.env) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnlp') def test_spawnlp(self): program, args = self.create_args() exitcode = os.spawnlp(os.P_WAIT, program, *args) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnlpe') def test_spawnlpe(self): program, args = self.create_args(with_env=True) exitcode = os.spawnlpe(os.P_WAIT, program, *args, self.env) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnv') def test_spawnv(self): program, args = self.create_args() @@ -3725,30 +3453,35 @@ def test_spawnv(self): exitcode = os.spawnv(os.P_WAIT, FakePath(program), args) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnve') def test_spawnve(self): program, args = self.create_args(with_env=True) exitcode = os.spawnve(os.P_WAIT, program, args, self.env) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnvp') def test_spawnvp(self): program, args = self.create_args() exitcode = os.spawnvp(os.P_WAIT, program, args) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnvpe') def test_spawnvpe(self): program, args = self.create_args(with_env=True) exitcode = os.spawnvpe(os.P_WAIT, program, args, self.env) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnv') def test_nowait(self): program, args = self.create_args() pid = os.spawnv(os.P_NOWAIT, program, args) support.wait_process(pid, exitcode=self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnve') def test_spawnve_bytes(self): # Test bytes handling in parse_arglist and parse_envlist (#28114) @@ -3756,18 +3489,21 @@ def test_spawnve_bytes(self): exitcode = os.spawnve(os.P_WAIT, program, args, self.env) self.assertEqual(exitcode, self.exitcode) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnl') def test_spawnl_noargs(self): program, __ = self.create_args() self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program) self.assertRaises(ValueError, os.spawnl, os.P_NOWAIT, program, '') + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnle') def test_spawnle_noargs(self): program, __ = self.create_args() self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, {}) self.assertRaises(ValueError, os.spawnle, os.P_NOWAIT, program, '', {}) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnv') def test_spawnv_noargs(self): program, __ = self.create_args() @@ -3776,6 +3512,7 @@ def test_spawnv_noargs(self): self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ('',)) self.assertRaises(ValueError, os.spawnv, os.P_NOWAIT, program, ['']) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnve') def test_spawnve_noargs(self): program, __ = self.create_args() @@ -3784,7 +3521,6 @@ def test_spawnve_noargs(self): self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, ('',), {}) self.assertRaises(ValueError, os.spawnve, os.P_NOWAIT, program, [''], {}) - @unittest.expectedFailureIfWindows('TODO: RUSTPYTHON; AssertionError: "must contain only strings" does not match "expected str, bytes or os.PathLike object, not int"') @requires_native_spawnv def test_spawnv_arg_conversion_errors(self): # A non-path argv item gets a TypeError naming the argument... @@ -3852,22 +3588,28 @@ def _test_invalid_env(self, spawn): exitcode = spawn(os.P_WAIT, program, args, newenv) self.assertEqual(exitcode, 0) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnve') def test_spawnve_invalid_env(self): self._test_invalid_env(os.spawnve) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_os_func('spawnvpe') def test_spawnvpe_invalid_env(self): self._test_invalid_env(os.spawnvpe) -# The introduction of this TestCase caused at least two different errors on -# *nix buildbots. Temporarily skip this to let the buildbots move along. -@unittest.skip("Skip due to platform/environment differences on *NIX buildbots") @unittest.skipUnless(hasattr(os, 'getlogin'), "test needs os.getlogin") class LoginTests(unittest.TestCase): def test_getlogin(self): - user_name = os.getlogin() + try: + user_name = os.getlogin() + except OSError as exc: + # See https://man7.org/linux/man-pages/man3/getlogin.3.html#ERRORS. + if exc.errno in (errno.ENXIO, errno.ENOENT, errno.ENOTTY): + self.skipTest(str(exc)) + else: + raise self.assertNotEqual(len(user_name), 0) @@ -4031,6 +3773,11 @@ async def test_invalid_offset(self): await self.async_sendfile(self.sockno, self.fileno, -1, 4096) self.assertEqual(cm.exception.errno, errno.EINVAL) + async def test_invalid_count(self): + with self.assertRaises(ValueError, msg="count cannot be negative"): + await self.sendfile_wrapper(self.sockno, self.fileno, offset=0, + count=-1) + async def test_keywords(self): # Keyword arguments should be supported await self.async_sendfile(out_fd=self.sockno, in_fd=self.fileno, @@ -4221,12 +3968,7 @@ def test_does_not_crash(self): try: size = os.get_terminal_size() except OSError as e: - known_errnos = [errno.EINVAL, errno.ENOTTY] - if sys.platform == "android": - # The Android testbed redirects the native stdout to a pipe, - # which returns a different error code. - known_errnos.append(errno.EACCES) - if sys.platform == "win32" or e.errno in known_errnos: + if sys.platform == "win32" or e.errno in (errno.EINVAL, errno.ENOTTY): # Under win32 a generic OSError can be thrown if the # handle cannot be retrieved self.skipTest("failed to query terminal size") @@ -4737,6 +4479,7 @@ def test_oserror_filename(self): (self.filenames, os.listdir,), (self.filenames, os.rename, "dst"), (self.filenames, os.replace, "dst"), + (self.filenames, os.utime, None), ] if os_helper.can_chmod(): funcs.append((self.filenames, os.chmod, 0o777)) @@ -4777,6 +4520,19 @@ def test_oserror_filename(self): else: self.fail(f"No exception thrown by {func}") + def test_mkdir(self): + filename = os_helper.TESTFN + subdir = os.path.join(filename, 'subdir') + self.assertRaises(FileNotFoundError, os.mkdir, subdir) + + self.addCleanup(os_helper.unlink, filename) + create_file(filename) + self.assertRaises(FileExistsError, os.mkdir, filename) + + self.assertRaises((NotADirectoryError, FileNotFoundError), + os.mkdir, subdir) + + class CPUCountTests(unittest.TestCase): def check_cpu_count(self, cpus): if cpus is None: @@ -4992,6 +4748,7 @@ def test_posix_pty_functions(self): signal.signal(signal.SIGHUP, old_handler) self.assertEqual(os.ptsname(mother_fd), os.ttyname(son_fd)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(hasattr(os, 'spawnl'), "need os.spawnl()") @support.requires_subprocess() def test_pipe_spawnl(self): @@ -5321,7 +5078,6 @@ def test_current_directory(self): finally: os.chdir(old_dir) - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON; FileNotFoundError") @unittest.skipIf(sys.platform != 'win32', "Win32 specific test") def test_windows_trailing_space_path(self): import pathlib @@ -5539,6 +5295,84 @@ def test_resource_warning(self): with self.check_no_resource_warning(): del iterator + def test_no_resource_warning_when_open_fails(self): + # gh-152754: a scandir() call that never opened a directory owns + # nothing, and must not report an unclosed iterator. + self.create_file("file.txt") + missing = os.path.join(self.path, "missing") + not_a_dir = os.path.join(self.path, "file.txt") + for path in (missing, not_a_dir): + with self.subTest(path=path): + with self.check_no_resource_warning(): + with self.assertRaises(OSError): + os.scandir(path) + + +@threading_helper.requires_working_threading() +class ScandirThreadingTest(unittest.TestCase): + # gh-152754: an os.scandir() iterator shared between threads must not crash. + + if support.check_sanitizer(thread=True): + SCANDIR_NUMITEMS = 200 + SCANDIR_N_NEXT = 2 + SCANDIR_N_CLOSE = 2 + SCANDIR_REPEAT = 10 + else: + SCANDIR_NUMITEMS = 1000 + SCANDIR_N_NEXT = 6 + SCANDIR_N_CLOSE = 3 + SCANDIR_REPEAT = 20 + + def setUp(self): + self.dir = os.path.realpath(os_helper.TESTFN) + self.addCleanup(os_helper.rmtree, self.dir) + os.mkdir(self.dir) + self.names = set() + for i in range(self.SCANDIR_NUMITEMS): + name = f"f{i}" + create_file(os.path.join(self.dir, name)) + self.names.add(name) + + def test_close_racing_next(self): + # One thread's next() racing another's close() must not crash. + def nexter(): + for _ in self.it: + pass + + def closer(): + self.it.close() + + funcs = [nexter] * self.SCANDIR_N_NEXT + [closer] * self.SCANDIR_N_CLOSE + for _ in range(self.SCANDIR_REPEAT): + self.it = os.scandir(self.dir) + try: + threading_helper.run_concurrently(funcs) + finally: + self.it.close() + + def test_shared_next(self): + # Threads sharing one iterator must not crash or lose entries: every + # entry must be handed to exactly one thread. + expected = sorted(self.names) + nthreads = self.SCANDIR_N_NEXT + self.SCANDIR_N_CLOSE + + for _ in range(self.SCANDIR_REPEAT): + self.it = os.scandir(self.dir) + results = [] + results_lock = threading.Lock() + + def worker(): + local = [entry.name for entry in self.it] + with results_lock: + results.extend(local) + + try: + threading_helper.run_concurrently([worker] * nthreads) + finally: + self.it.close() + + self.assertEqual(sorted(results), expected) + class TestPEP519(unittest.TestCase): diff --git a/Lib/test/test_posix.py b/Lib/test/test_os/test_posix.py similarity index 94% rename from Lib/test/test_posix.py rename to Lib/test/test_os/test_posix.py index 265f68902a4..4839b1772a3 100644 --- a/Lib/test/test_posix.py +++ b/Lib/test/test_os/test_posix.py @@ -46,7 +46,8 @@ def _supports_sched(): try: posix.sched_getscheduler(0) except OSError as e: - if e.errno == errno.ENOSYS: + # DragonFly BSD requires privileges to use the scheduler API. + if e.errno in (errno.ENOSYS, errno.EPERM): return False return True @@ -70,7 +71,7 @@ def testNoArgFunctions(self): NO_ARG_FUNCTIONS = [ "ctermid", "getcwd", "getcwdb", "uname", "times", "getloadavg", "getegid", "geteuid", "getgid", "getgroups", - "getpid", "getpgrp", "getppid", "getuid", "sync", + "getpid", "getpgrp", "getppid", "getuid", ] for name in NO_ARG_FUNCTIONS: @@ -80,6 +81,13 @@ def testNoArgFunctions(self): posix_func() self.assertRaises(TypeError, posix_func, 1) + # gh-102184: sync() can block for a long time. + @support.requires_resource('walltime') + @unittest.skipUnless(hasattr(posix, 'sync'), 'test needs posix.sync()') + def test_sync(self): + posix.sync() + self.assertRaises(TypeError, posix.sync, 1) + @unittest.skipUnless(hasattr(posix, 'getresuid'), 'test needs posix.getresuid()') def test_getresuid(self): @@ -415,8 +423,10 @@ def test_posix_fallocate(self): if inst.errno == errno.EINVAL and sys.platform.startswith( ('sunos', 'freebsd', 'openbsd', 'gnukfreebsd')): raise unittest.SkipTest("test may fail on ZFS filesystems") - elif inst.errno == errno.EOPNOTSUPP and sys.platform.startswith("netbsd"): - raise unittest.SkipTest("test may fail on FFS filesystems") + elif inst.errno == errno.EOPNOTSUPP: + # ZFS on FreeBSD, FFS on NetBSD, etc. + raise unittest.SkipTest( + "the file system does not support posix_fallocate()") else: raise finally: @@ -680,22 +690,65 @@ def test_stat_fd_zero_follow_symlinks(self): 'cannot use fd and follow_symlinks together'): posix.stat(1, follow_symlinks=False) - def test_stat(self): - self.assertTrue(posix.stat(os_helper.TESTFN)) - self.assertTrue(posix.stat(os.fsencode(os_helper.TESTFN))) + def check_statlike_path(self, func): + self.assertTrue(func(os_helper.TESTFN)) + self.assertTrue(func(os.fsencode(os_helper.TESTFN))) + self.assertTrue(func(os_helper.FakePath(os_helper.TESTFN))) self.assertRaisesRegex(TypeError, 'should be string, bytes, os.PathLike or integer, not', - posix.stat, bytearray(os.fsencode(os_helper.TESTFN))) + func, bytearray(os.fsencode(os_helper.TESTFN))) self.assertRaisesRegex(TypeError, 'should be string, bytes, os.PathLike or integer, not', - posix.stat, None) + func, None) self.assertRaisesRegex(TypeError, 'should be string, bytes, os.PathLike or integer, not', - posix.stat, list(os_helper.TESTFN)) + func, list(os_helper.TESTFN)) self.assertRaisesRegex(TypeError, 'should be string, bytes, os.PathLike or integer, not', - posix.stat, list(os.fsencode(os_helper.TESTFN))) + func, list(os.fsencode(os_helper.TESTFN))) + + def test_stat(self): + self.check_statlike_path(posix.stat) + + @unittest.skipUnless(hasattr(posix, 'statx'), 'test needs posix.statx()') + def test_statx(self): + def func(path, **kwargs): + return posix.statx(path, posix.STATX_BASIC_STATS, **kwargs) + self.check_statlike_path(func) + + @unittest.skipUnless(hasattr(posix, 'statx'), 'test needs posix.statx()') + def test_statx_flags(self): + # glibc's fallback implementation of statx via the stat family fails + # with EINVAL on the (nonzero) sync flags. If you see this failure, + # update your kernel and/or seccomp syscall filter. + valid_flag_names = ('AT_NO_AUTOMOUNT', 'AT_STATX_SYNC_AS_STAT', + 'AT_STATX_FORCE_SYNC', 'AT_STATX_DONT_SYNC') + for flag_name in valid_flag_names: + flag = getattr(posix, flag_name) + with self.subTest(msg=flag_name, flags=flag): + posix.statx(os_helper.TESTFN, posix.STATX_BASIC_STATS, + flags=flag) + + # These flags are not exposed to Python because their functionality is + # implemented via kwargs instead. + kwarg_equivalent_flags = ( + (0x0100, 'AT_SYMLINK_NOFOLLOW', 'follow_symlinks'), + (0x0400, 'AT_SYMLINK_FOLLOW', 'follow_symlinks'), + (0x1000, 'AT_EMPTY_PATH', 'dir_fd'), + ) + for flag, flag_name, kwarg_name in kwarg_equivalent_flags: + with self.subTest(msg=flag_name, flags=flag): + with self.assertRaisesRegex(ValueError, kwarg_name): + posix.statx(os_helper.TESTFN, posix.STATX_BASIC_STATS, + flags=flag) + + with self.subTest(msg="AT_STATX_FORCE_SYNC | AT_STATX_DONT_SYNC"): + with self.assertRaises(OSError) as ctx: + flags = posix.AT_STATX_FORCE_SYNC | posix.AT_STATX_DONT_SYNC + posix.statx(os_helper.TESTFN, posix.STATX_BASIC_STATS, + flags=flags) + self.assertEqual(ctx.exception.errno, errno.EINVAL) @unittest.skipUnless(hasattr(posix, 'mkfifo'), "don't have mkfifo()") def test_mkfifo(self): @@ -769,12 +822,29 @@ def test_makedev(self): self.assertRaises((ValueError, OverflowError), posix.makedev, x, minor) self.assertRaises((ValueError, OverflowError), posix.makedev, major, x) - if sys.platform == 'linux' and not support.linked_to_musl(): - NODEV = -1 + # The following tests are needed to test functions accepting or + # returning the special value NODEV (if it is defined). major(), minor() + # and makefile() are the only easily reproducible examples, but that + # behavior is platform specific -- on some platforms their code has + # a special case for NODEV, on others this is just an implementation + # artifact. + if (hasattr(posix, 'NODEV') and + sys.platform.startswith(('linux', 'macos', 'freebsd', 'sunos'))): + NODEV = posix.NODEV self.assertEqual(posix.major(NODEV), NODEV) self.assertEqual(posix.minor(NODEV), NODEV) self.assertEqual(posix.makedev(NODEV, NODEV), NODEV) + def test_nodev(self): + # NODEV is not a part of Posix, but is defined on many systems. + if (not hasattr(posix, 'NODEV') + and (not sys.platform.startswith(('linux', 'macos', 'freebsd', + 'dragonfly', 'netbsd', 'openbsd', + 'sunos')) + or support.linked_to_musl())): + self.skipTest('not defined on this platform') + self.assertHasAttr(posix, 'NODEV') + def _test_all_chown_common(self, chown_func, first_param, stat_func): """Common code for chown, fchown and lchown tests.""" def check_stat(uid, gid): @@ -838,7 +908,9 @@ def check_stat(uid, gid): self.assertRaises(OSError, chown_func, first_param, 0, -1) check_stat(uid, gid) if hasattr(os, 'getgroups'): - if 0 not in os.getgroups(): + # Also check the effective gid, which the kernel + # accepts for chown even if not in getgroups(). + if 0 not in os.getgroups() and os.getegid() != 0: self.assertRaises(OSError, chown_func, first_param, -1, 0) check_stat(uid, gid) # test illegal types @@ -1386,6 +1458,7 @@ def test_bug_140634(self): del sched_priority, param # should not crash support.gc_collect() # just to be sure + @requires_sched @unittest.skipUnless(hasattr(posix, "sched_rr_get_interval"), "no function") def test_sched_rr_get_interval(self): try: @@ -1631,33 +1704,47 @@ def test_chown_dir_fd(self): with self.prepare_file() as (dir_fd, name, fullname): posix.chown(name, os.getuid(), os.getgid(), dir_fd=dir_fd) - @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()") - def test_stat_dir_fd(self): + def check_statlike_dir_fd(self, func, prefix): with self.prepare() as (dir_fd, name, fullname): with open(fullname, 'w') as outfile: outfile.write("testline\n") self.addCleanup(posix.unlink, fullname) - s1 = posix.stat(fullname) - s2 = posix.stat(name, dir_fd=dir_fd) - self.assertEqual(s1, s2) - s2 = posix.stat(fullname, dir_fd=None) - self.assertEqual(s1, s2) + def get(result, attr): + return getattr(result, prefix + attr) + + s1 = func(fullname) + s2 = func(name, dir_fd=dir_fd) + self.assertEqual((get(s1, "dev"), get(s1, "ino")), + (get(s2, "dev"), get(s2, "ino"))) + s2 = func(fullname, dir_fd=None) + self.assertEqual((get(s1, "dev"), get(s1, "ino")), + (get(s2, "dev"), get(s2, "ino"))) self.assertRaisesRegex(TypeError, 'should be integer or None, not', - posix.stat, name, dir_fd=posix.getcwd()) + func, name, dir_fd=posix.getcwd()) self.assertRaisesRegex(TypeError, 'should be integer or None, not', - posix.stat, name, dir_fd=float(dir_fd)) + func, name, dir_fd=float(dir_fd)) self.assertRaises(OverflowError, - posix.stat, name, dir_fd=10**20) + func, name, dir_fd=10**20) for fd in False, True: with self.assertWarnsRegex(RuntimeWarning, 'bool is used as a file descriptor') as cm: with self.assertRaises(OSError): - posix.stat('nonexisting', dir_fd=fd) + func('nonexisting', dir_fd=fd) self.assertEqual(cm.filename, __file__) + @unittest.skipUnless(os.stat in os.supports_dir_fd, "test needs dir_fd support in os.stat()") + def test_stat_dir_fd(self): + self.check_statlike_dir_fd(posix.stat, prefix="st_") + + @unittest.skipUnless(hasattr(posix, 'statx'), "test needs os.statx()") + def test_statx_dir_fd(self): + def func(path, **kwargs): + return posix.statx(path, os.STATX_INO, **kwargs) + self.check_statlike_dir_fd(func, prefix="stx_") + @unittest.skipUnless(os.utime in os.supports_dir_fd, "test needs dir_fd support in os.utime()") def test_utime_dir_fd(self): with self.prepare_file() as (dir_fd, name, fullname): @@ -2271,6 +2358,22 @@ def test_pwritev(self): self.assertNotHasAttr(os, "pwritev") self.assertNotHasAttr(os, "preadv") + def test_pipe2(self): + self._verify_available("HAVE_PIPE2") + if self.mac_ver >= (27, 0): + self.assertHasAttr(os, "pipe2") + else: + self.assertNotHasAttr(os, "pipe2") + + def test_dup3(self): + self._verify_available("HAVE_DUP3") + r, w = os.pipe() + self.addCleanup(os.close, r) + self.addCleanup(os.close, w) + # Must not crash even when dup3 unavailable at runtime. + # os.dup2 returns fd2 (here w); do not double-close. + os.dup2(r, w, inheritable=False) + def test_stat(self): self._verify_available("HAVE_FSTATAT") if self.mac_ver >= (10, 10): diff --git a/Lib/test/test_os/test_windows.py b/Lib/test/test_os/test_windows.py new file mode 100644 index 00000000000..89e3dec97bc --- /dev/null +++ b/Lib/test/test_os/test_windows.py @@ -0,0 +1,681 @@ +import sys +import unittest + +if sys.platform != "win32": + raise unittest.SkipTest("Win32 specific tests") + +import _winapi +import fnmatch +import mmap +import os +import shutil +import signal +import stat +import subprocess +import textwrap +import time +import uuid +from test import support +from test.support import import_helper +from test.support import os_helper +from .utils import create_file + + +class Win32KillTests(unittest.TestCase): + def _kill(self, sig): + # Start sys.executable as a subprocess and communicate from the + # subprocess to the parent that the interpreter is ready. When it + # becomes ready, send *sig* via os.kill to the subprocess and check + # that the return code is equal to *sig*. + import ctypes + from ctypes import wintypes + import msvcrt + + # Since we can't access the contents of the process' stdout until the + # process has exited, use PeekNamedPipe to see what's inside stdout + # without waiting. This is done so we can tell that the interpreter + # is started and running at a point where it could handle a signal. + PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe + PeekNamedPipe.restype = wintypes.BOOL + PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle + ctypes.POINTER(ctypes.c_char), # stdout buf + wintypes.DWORD, # Buffer size + ctypes.POINTER(wintypes.DWORD), # bytes read + ctypes.POINTER(wintypes.DWORD), # bytes avail + ctypes.POINTER(wintypes.DWORD)) # bytes left + msg = "running" + proc = subprocess.Popen([sys.executable, "-c", + "import sys;" + "sys.stdout.write('{}');" + "sys.stdout.flush();" + "input()".format(msg)], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.PIPE) + self.addCleanup(proc.stdout.close) + self.addCleanup(proc.stderr.close) + self.addCleanup(proc.stdin.close) + + count, max = 0, 100 + while count < max and proc.poll() is None: + # Create a string buffer to store the result of stdout from the pipe + buf = ctypes.create_string_buffer(len(msg)) + # Obtain the text currently in proc.stdout + # Bytes read/avail/left are left as NULL and unused + rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()), + buf, ctypes.sizeof(buf), None, None, None) + self.assertNotEqual(rslt, 0, "PeekNamedPipe failed") + if buf.value: + self.assertEqual(msg, buf.value.decode()) + break + time.sleep(0.1) + count += 1 + else: + self.fail("Did not receive communication from the subprocess") + + os.kill(proc.pid, sig) + self.assertEqual(proc.wait(), sig) + + def test_kill_sigterm(self): + # SIGTERM doesn't mean anything special, but make sure it works + self._kill(signal.SIGTERM) + + def test_kill_int(self): + # os.kill on Windows can take an int which gets set as the exit code + self._kill(100) + + @unittest.skipIf(mmap is None, "requires mmap") + def _kill_with_event(self, event, name): + tagname = "test_os_%s" % uuid.uuid1() + m = mmap.mmap(-1, 1, tagname) + m[0] = 0 + + # Run a script which has console control handling enabled. + script = os.path.join(os.path.dirname(__file__), + "win_console_handler.py") + cmd = [sys.executable, script, tagname] + proc = subprocess.Popen(cmd, + creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) + + with proc: + # Let the interpreter startup before we send signals. See #3137. + for _ in support.sleeping_retry(support.SHORT_TIMEOUT): + if proc.poll() is None: + break + else: + # Forcefully kill the process if we weren't able to signal it. + proc.kill() + self.fail("Subprocess didn't finish initialization") + + os.kill(proc.pid, event) + + try: + # proc.send_signal(event) could also be done here. + # Allow time for the signal to be passed and the process to exit. + proc.wait(timeout=support.SHORT_TIMEOUT) + except subprocess.TimeoutExpired: + # Forcefully kill the process if we weren't able to signal it. + proc.kill() + self.fail("subprocess did not stop on {}".format(name)) + + @unittest.skip("subprocesses aren't inheriting Ctrl+C property") + @support.requires_subprocess() + def test_CTRL_C_EVENT(self): + from ctypes import wintypes + import ctypes + + # Make a NULL value by creating a pointer with no argument. + NULL = ctypes.POINTER(ctypes.c_int)() + SetConsoleCtrlHandler = ctypes.windll.kernel32.SetConsoleCtrlHandler + SetConsoleCtrlHandler.argtypes = (ctypes.POINTER(ctypes.c_int), + wintypes.BOOL) + SetConsoleCtrlHandler.restype = wintypes.BOOL + + # Calling this with NULL and FALSE causes the calling process to + # handle Ctrl+C, rather than ignore it. This property is inherited + # by subprocesses. + SetConsoleCtrlHandler(NULL, 0) + + self._kill_with_event(signal.CTRL_C_EVENT, "CTRL_C_EVENT") + + @support.requires_subprocess() + def test_CTRL_BREAK_EVENT(self): + self._kill_with_event(signal.CTRL_BREAK_EVENT, "CTRL_BREAK_EVENT") + + +class Win32ListdirTests(unittest.TestCase): + """Test listdir on Windows.""" + + def setUp(self): + self.created_paths = [] + for i in range(2): + dir_name = 'SUB%d' % i + dir_path = os.path.join(os_helper.TESTFN, dir_name) + file_name = 'FILE%d' % i + file_path = os.path.join(os_helper.TESTFN, file_name) + os.makedirs(dir_path) + with open(file_path, 'w', encoding='utf-8') as f: + f.write("I'm %s and proud of it. Blame test_os.\n" % file_path) + self.created_paths.extend([dir_name, file_name]) + self.created_paths.sort() + + def tearDown(self): + shutil.rmtree(os_helper.TESTFN) + + def test_listdir_no_extended_path(self): + """Test when the path is not an "extended" path.""" + # unicode + self.assertEqual( + sorted(os.listdir(os_helper.TESTFN)), + self.created_paths) + + # bytes + self.assertEqual( + sorted(os.listdir(os.fsencode(os_helper.TESTFN))), + [os.fsencode(path) for path in self.created_paths]) + + def test_listdir_extended_path(self): + """Test when the path starts with '\\\\?\\'.""" + # See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath + # unicode + path = '\\\\?\\' + os.path.abspath(os_helper.TESTFN) + self.assertEqual( + sorted(os.listdir(path)), + self.created_paths) + + # bytes + path = b'\\\\?\\' + os.fsencode(os.path.abspath(os_helper.TESTFN)) + self.assertEqual( + sorted(os.listdir(path)), + [os.fsencode(path) for path in self.created_paths]) + + +@unittest.skipUnless(os.name == "nt", "NT specific tests") +class Win32ListdriveTests(unittest.TestCase): + """Test listdrive, listmounts and listvolume on Windows.""" + + def setUp(self): + # Get drives and volumes from fsutil + out = subprocess.check_output( + ["fsutil.exe", "volume", "list"], + cwd=os.path.join(os.getenv("SystemRoot", "\\Windows"), "System32"), + encoding="mbcs", + errors="ignore", + ) + lines = out.splitlines() + self.known_volumes = {l for l in lines if l.startswith('\\\\?\\')} + self.known_drives = {l for l in lines if l[1:] == ':\\'} + self.known_mounts = {l for l in lines if l[1:3] == ':\\'} + + def test_listdrives(self): + drives = os.listdrives() + self.assertIsInstance(drives, list) + self.assertSetEqual( + self.known_drives, + self.known_drives & set(drives), + ) + + def test_listvolumes(self): + volumes = os.listvolumes() + self.assertIsInstance(volumes, list) + self.assertSetEqual( + self.known_volumes, + self.known_volumes & set(volumes), + ) + + def test_listmounts(self): + for volume in os.listvolumes(): + try: + mounts = os.listmounts(volume) + except OSError as ex: + if support.verbose: + print("Skipping", volume, "because of", ex) + else: + self.assertIsInstance(mounts, list) + self.assertSetEqual( + set(mounts), + self.known_mounts & set(mounts), + ) + + +@os_helper.skip_unless_symlink +class Win32SymlinkTests(unittest.TestCase): + filelink = 'filelinktest' + filelink_target = os.path.abspath(__file__) + dirlink = 'dirlinktest' + dirlink_target = os.path.dirname(filelink_target) + missing_link = 'missing link' + + def setUp(self): + assert os.path.exists(self.dirlink_target) + assert os.path.exists(self.filelink_target) + assert not os.path.exists(self.dirlink) + assert not os.path.exists(self.filelink) + assert not os.path.exists(self.missing_link) + + def tearDown(self): + if os.path.exists(self.filelink): + os.remove(self.filelink) + if os.path.exists(self.dirlink): + os.rmdir(self.dirlink) + if os.path.lexists(self.missing_link): + os.remove(self.missing_link) + + def test_directory_link(self): + os.symlink(self.dirlink_target, self.dirlink) + self.assertTrue(os.path.exists(self.dirlink)) + self.assertTrue(os.path.isdir(self.dirlink)) + self.assertTrue(os.path.islink(self.dirlink)) + self.check_stat(self.dirlink, self.dirlink_target) + + def test_file_link(self): + os.symlink(self.filelink_target, self.filelink) + self.assertTrue(os.path.exists(self.filelink)) + self.assertTrue(os.path.isfile(self.filelink)) + self.assertTrue(os.path.islink(self.filelink)) + self.check_stat(self.filelink, self.filelink_target) + + def _create_missing_dir_link(self): + 'Create a "directory" link to a non-existent target' + linkname = self.missing_link + if os.path.lexists(linkname): + os.remove(linkname) + target = r'c:\\target does not exist.29r3c740' + assert not os.path.exists(target) + target_is_dir = True + os.symlink(target, linkname, target_is_dir) + + def test_remove_directory_link_to_missing_target(self): + self._create_missing_dir_link() + # For compatibility with Unix, os.remove will check the + # directory status and call RemoveDirectory if the symlink + # was created with target_is_dir==True. + os.remove(self.missing_link) + + def test_isdir_on_directory_link_to_missing_target(self): + self._create_missing_dir_link() + self.assertFalse(os.path.isdir(self.missing_link)) + + def test_rmdir_on_directory_link_to_missing_target(self): + self._create_missing_dir_link() + os.rmdir(self.missing_link) + + def check_stat(self, link, target): + self.assertEqual(os.stat(link), os.stat(target)) + self.assertNotEqual(os.lstat(link), os.stat(link)) + + bytes_link = os.fsencode(link) + self.assertEqual(os.stat(bytes_link), os.stat(target)) + self.assertNotEqual(os.lstat(bytes_link), os.stat(bytes_link)) + + def test_12084(self): + level1 = os.path.abspath(os_helper.TESTFN) + level2 = os.path.join(level1, "level2") + level3 = os.path.join(level2, "level3") + self.addCleanup(os_helper.rmtree, level1) + + os.mkdir(level1) + os.mkdir(level2) + os.mkdir(level3) + + file1 = os.path.abspath(os.path.join(level1, "file1")) + create_file(file1) + + orig_dir = os.getcwd() + try: + os.chdir(level2) + link = os.path.join(level2, "link") + os.symlink(os.path.relpath(file1), "link") + self.assertIn("link", os.listdir(os.getcwd())) + + # Check os.stat calls from the same dir as the link + self.assertEqual(os.stat(file1), os.stat("link")) + + # Check os.stat calls from a dir below the link + os.chdir(level1) + self.assertEqual(os.stat(file1), + os.stat(os.path.relpath(link))) + + # Check os.stat calls from a dir above the link + os.chdir(level3) + self.assertEqual(os.stat(file1), + os.stat(os.path.relpath(link))) + finally: + os.chdir(orig_dir) + + @unittest.skipUnless(os.path.lexists(r'C:\Users\All Users') + and os.path.exists(r'C:\ProgramData'), + 'Test directories not found') + def test_29248(self): + # os.symlink() calls CreateSymbolicLink, which creates + # the reparse data buffer with the print name stored + # first, so the offset is always 0. CreateSymbolicLink + # stores the "PrintName" DOS path (e.g. "C:\") first, + # with an offset of 0, followed by the "SubstituteName" + # NT path (e.g. "\??\C:\"). The "All Users" link, on + # the other hand, seems to have been created manually + # with an inverted order. + target = os.readlink(r'C:\Users\All Users') + self.assertTrue(os.path.samefile(target, r'C:\ProgramData')) + + def test_buffer_overflow(self): + # Older versions would have a buffer overflow when detecting + # whether a link source was a directory. This test ensures we + # no longer crash, but does not otherwise validate the behavior + segment = 'X' * 27 + path = os.path.join(*[segment] * 10) + test_cases = [ + # overflow with absolute src + ('\\' + path, segment), + # overflow dest with relative src + (segment, path), + # overflow when joining src + (path[:180], path[:180]), + ] + for src, dest in test_cases: + try: + os.symlink(src, dest) + except FileNotFoundError: + pass + else: + try: + os.remove(dest) + except OSError: + pass + # Also test with bytes, since that is a separate code path. + try: + os.symlink(os.fsencode(src), os.fsencode(dest)) + except FileNotFoundError: + pass + else: + try: + os.remove(dest) + except OSError: + pass + + def test_appexeclink(self): + root = os.path.expandvars(r'%LOCALAPPDATA%\Microsoft\WindowsApps') + if not os.path.isdir(root): + self.skipTest("test requires a WindowsApps directory") + + aliases = [os.path.join(root, a) + for a in fnmatch.filter(os.listdir(root), '*.exe')] + + for alias in aliases: + if support.verbose: + print() + print("Testing with", alias) + st = os.lstat(alias) + self.assertEqual(st, os.stat(alias)) + self.assertFalse(stat.S_ISLNK(st.st_mode)) + self.assertEqual(st.st_reparse_tag, stat.IO_REPARSE_TAG_APPEXECLINK) + self.assertTrue(os.path.isfile(alias)) + # testing the first one we see is sufficient + break + else: + self.skipTest("test requires an app execution alias") + + +class Win32JunctionTests(unittest.TestCase): + junction = 'junctiontest' + junction_target = os.path.dirname(os.path.abspath(__file__)) + + def setUp(self): + assert os.path.exists(self.junction_target) + assert not os.path.lexists(self.junction) + + def tearDown(self): + if os.path.lexists(self.junction): + os.unlink(self.junction) + + def test_create_junction(self): + _winapi.CreateJunction(self.junction_target, self.junction) + self.assertTrue(os.path.lexists(self.junction)) + self.assertTrue(os.path.exists(self.junction)) + self.assertTrue(os.path.isdir(self.junction)) + self.assertNotEqual(os.stat(self.junction), os.lstat(self.junction)) + self.assertEqual(os.stat(self.junction), os.stat(self.junction_target)) + + # bpo-37834: Junctions are not recognized as links. + self.assertFalse(os.path.islink(self.junction)) + self.assertEqual(os.path.normcase("\\\\?\\" + self.junction_target), + os.path.normcase(os.readlink(self.junction))) + + def test_unlink_removes_junction(self): + _winapi.CreateJunction(self.junction_target, self.junction) + self.assertTrue(os.path.exists(self.junction)) + self.assertTrue(os.path.lexists(self.junction)) + + os.unlink(self.junction) + self.assertFalse(os.path.exists(self.junction)) + + +class Win32NtTests(unittest.TestCase): + def test_getfinalpathname_handles(self): + nt = import_helper.import_module('nt') + ctypes = import_helper.import_module('ctypes') + # Ruff false positive -- it thinks we're redefining `ctypes` here + import ctypes.wintypes # noqa: F811 + + kernel = ctypes.WinDLL('Kernel32.dll', use_last_error=True) + kernel.GetCurrentProcess.restype = ctypes.wintypes.HANDLE + + kernel.GetProcessHandleCount.restype = ctypes.wintypes.BOOL + kernel.GetProcessHandleCount.argtypes = (ctypes.wintypes.HANDLE, + ctypes.wintypes.LPDWORD) + + # This is a pseudo-handle that doesn't need to be closed + hproc = kernel.GetCurrentProcess() + + handle_count = ctypes.wintypes.DWORD() + ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count)) + self.assertEqual(1, ok) + + before_count = handle_count.value + + # The first two test the error path, __file__ tests the success path + filenames = [ + r'\\?\C:', + r'\\?\NUL', + r'\\?\CONIN', + __file__, + ] + + for _ in range(10): + for name in filenames: + try: + nt._getfinalpathname(name) + except Exception: + # Failure is expected + pass + try: + os.stat(name) + except Exception: + pass + + ok = kernel.GetProcessHandleCount(hproc, ctypes.byref(handle_count)) + self.assertEqual(1, ok) + + handle_delta = handle_count.value - before_count + + self.assertEqual(0, handle_delta) + + @support.requires_subprocess() + def test_stat_unlink_race(self): + # bpo-46785: the implementation of os.stat() falls back to reading + # the parent directory if CreateFileW() fails with a permission + # error. If reading the parent directory fails because the file or + # directory are subsequently unlinked, or because the volume or + # share are no longer available, then the original permission error + # should not be restored. + filename = os_helper.TESTFN + self.addCleanup(os_helper.unlink, filename) + deadline = time.time() + 5 + command = textwrap.dedent("""\ + import os + import sys + import time + + filename = sys.argv[1] + deadline = float(sys.argv[2]) + + while time.time() < deadline: + try: + with open(filename, "w") as f: + pass + except OSError: + pass + try: + os.remove(filename) + except OSError: + pass + """) + + with subprocess.Popen([sys.executable, '-c', command, filename, str(deadline)]) as proc: + while time.time() < deadline: + try: + os.stat(filename) + except FileNotFoundError as e: + assert e.winerror == 2 # ERROR_FILE_NOT_FOUND + try: + proc.wait(1) + except subprocess.TimeoutExpired: + proc.terminate() + + @support.requires_subprocess() + def test_stat_inaccessible_file(self): + filename = os_helper.TESTFN + ICACLS = os.path.expandvars(r"%SystemRoot%\System32\icacls.exe") + + with open(filename, "wb") as f: + f.write(b'Test data') + + stat1 = os.stat(filename) + + try: + # Remove all permissions from the file + subprocess.check_output([ICACLS, filename, "/inheritance:r"], + stderr=subprocess.STDOUT) + except subprocess.CalledProcessError as ex: + if support.verbose: + print(ICACLS, filename, "/inheritance:r", "failed.") + print(ex.stdout.decode("oem", "replace").rstrip()) + try: + os.unlink(filename) + except OSError: + pass + self.skipTest("Unable to create inaccessible file") + + def cleanup(): + # Give delete permission to the owner (us) + subprocess.check_output([ICACLS, filename, "/grant", "*WD:(D)"], + stderr=subprocess.STDOUT) + os.unlink(filename) + + self.addCleanup(cleanup) + + if support.verbose: + print("File:", filename) + print("stat with access:", stat1) + + # First test - we shouldn't raise here, because we still have access to + # the directory and can extract enough information from its metadata. + stat2 = os.stat(filename) + + if support.verbose: + print(" without access:", stat2) + + # We may not get st_dev/st_ino, so ensure those are 0 or match + self.assertIn(stat2.st_dev, (0, stat1.st_dev)) + self.assertIn(stat2.st_ino, (0, stat1.st_ino)) + + # st_mode and st_size should match (for a normal file, at least) + self.assertEqual(stat1.st_mode, stat2.st_mode) + self.assertEqual(stat1.st_size, stat2.st_size) + + # st_ctime and st_mtime should be the same + self.assertEqual(stat1.st_ctime, stat2.st_ctime) + self.assertEqual(stat1.st_mtime, stat2.st_mtime) + + # st_atime should be the same or later + self.assertGreaterEqual(stat1.st_atime, stat2.st_atime) + + +class Win32DeviceEncodingTests(unittest.TestCase): + # gh-87587: any console file descriptor is supported, not only 0, 1 and 2, + # and other character devices are not consoles. + + @staticmethod + def expected_encoding(cp): + return 'utf-8' if cp == 65001 else 'cp%d' % cp + + def test_console(self): + import ctypes + kernel32 = ctypes.WinDLL('kernel32', use_last_error=True) + try: + fin = open('CONIN$') + except OSError: + self.skipTest('no console') + with fin: + self.assertEqual(os.device_encoding(fin.fileno()), + self.expected_encoding(kernel32.GetConsoleCP())) + with open('CONOUT$', 'w') as fout: + self.assertEqual( + os.device_encoding(fout.fileno()), + self.expected_encoding(kernel32.GetConsoleOutputCP())) + + def test_not_a_console(self): + with open('NUL', 'w') as f: + self.assertTrue(os.isatty(f.fileno())) + self.assertIsNone(os.device_encoding(f.fileno())) + # Not a console even if it is a standard file descriptor. + saved = os.dup(1) + try: + os.dup2(f.fileno(), 1) + encoding = os.device_encoding(1) + finally: + os.dup2(saved, 1) + os.close(saved) + self.assertIsNone(encoding) + + +class Win32StatExecutableTests(unittest.TestCase): + # gh-84419: Windows strips trailing dots and spaces from the last + # component of the path, so they should be ignored when guessing + # the execute permissions from the file extension. + + SUFFIXES = ['', ' ', ' ', '.', '..', ' . .'] + + def check(self, ext, mask): + filename = os_helper.TESTFN + ext + create_file(filename) + try: + for suffix in self.SUFFIXES: + with self.subTest(suffix=suffix): + mode = os.stat(filename + suffix).st_mode + self.assertEqual(mode & 0o111, mask) + finally: + os_helper.unlink(filename) + + def test_executable_extension(self): + for ext in '.exe', '.bat', '.cmd', '.com', '.EXE', '.Bat': + with self.subTest(ext=ext): + self.check(ext, 0o111) + + def test_not_executable_extension(self): + for ext in '.txt', '.py', '.exe.txt', '': + with self.subTest(ext=ext): + self.check(ext, 0) + + def test_extended_path(self): + # The \\?\ prefix disables normalization: trailing spaces and dots + # are part of the file name. + filename = os.path.abspath(os_helper.TESTFN + '.exe') + create_file(filename) + self.addCleanup(os_helper.unlink, filename) + self.assertEqual(os.stat('\\\\?\\' + filename).st_mode & 0o111, 0o111) + self.assertRaises(OSError, os.stat, '\\\\?\\' + filename + ' ') + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_os/utils.py b/Lib/test/test_os/utils.py new file mode 100644 index 00000000000..e0c39598c31 --- /dev/null +++ b/Lib/test/test_os/utils.py @@ -0,0 +1,3 @@ +def create_file(filename, content=b'content'): + with open(filename, "xb", 0) as fp: + fp.write(content) diff --git a/Lib/test/test_pathlib/support/lexical_path.py b/Lib/test/test_pathlib/support/lexical_path.py index f29a521af9b..fd7fbf283a6 100644 --- a/Lib/test/test_pathlib/support/lexical_path.py +++ b/Lib/test/test_pathlib/support/lexical_path.py @@ -9,9 +9,10 @@ from . import is_pypi if is_pypi: - from pathlib_abc import _JoinablePath + from pathlib_abc import vfspath, _JoinablePath else: from pathlib.types import _JoinablePath + from pathlib._os import vfspath class LexicalPath(_JoinablePath): @@ -22,20 +23,20 @@ def __init__(self, *pathsegments): self._segments = pathsegments def __hash__(self): - return hash(str(self)) + return hash(vfspath(self)) def __eq__(self, other): if not isinstance(other, LexicalPath): return NotImplemented - return str(self) == str(other) + return vfspath(self) == vfspath(other) - def __str__(self): + def __vfspath__(self): if not self._segments: return '' return self.parser.join(*self._segments) def __repr__(self): - return f'{type(self).__name__}({str(self)!r})' + return f'{type(self).__name__}({vfspath(self)!r})' def with_segments(self, *pathsegments): return type(self)(*pathsegments) diff --git a/Lib/test/test_pathlib/support/local_path.py b/Lib/test/test_pathlib/support/local_path.py index d481fd45ead..ddfd6fd4195 100644 --- a/Lib/test/test_pathlib/support/local_path.py +++ b/Lib/test/test_pathlib/support/local_path.py @@ -97,7 +97,7 @@ class LocalPathInfo(PathInfo): __slots__ = ('_path', '_exists', '_is_dir', '_is_file', '_is_symlink') def __init__(self, path): - self._path = str(path) + self._path = os.fspath(path) self._exists = None self._is_dir = None self._is_file = None @@ -139,15 +139,13 @@ class ReadableLocalPath(_ReadablePath, LexicalPath): Simple implementation of a ReadablePath class for local filesystem paths. """ __slots__ = ('info',) + __fspath__ = LexicalPath.__vfspath__ def __init__(self, *pathsegments): super().__init__(*pathsegments) self.info = LocalPathInfo(self) - def __fspath__(self): - return str(self) - - def __open_rb__(self, buffering=-1): + def __open_reader__(self): return open(self, 'rb') def iterdir(self): @@ -163,12 +161,10 @@ class WritableLocalPath(_WritablePath, LexicalPath): """ __slots__ = () + __fspath__ = LexicalPath.__vfspath__ - def __fspath__(self): - return str(self) - - def __open_wb__(self, buffering=-1): - return open(self, 'wb') + def __open_writer__(self, mode): + return open(self, f'{mode}b') def mkdir(self, mode=0o777): os.mkdir(self, mode) diff --git a/Lib/test/test_pathlib/support/zip_path.py b/Lib/test/test_pathlib/support/zip_path.py index 2905260c9df..90b939b6a59 100644 --- a/Lib/test/test_pathlib/support/zip_path.py +++ b/Lib/test/test_pathlib/support/zip_path.py @@ -16,9 +16,10 @@ from . import is_pypi if is_pypi: - from pathlib_abc import PathInfo, _ReadablePath, _WritablePath + from pathlib_abc import vfspath, PathInfo, _ReadablePath, _WritablePath else: from pathlib.types import PathInfo, _ReadablePath, _WritablePath + from pathlib._os import vfspath class ZipPathGround: @@ -34,16 +35,16 @@ def teardown(self, root): root.zip_file.close() def create_file(self, path, data=b''): - path.zip_file.writestr(str(path), data) + path.zip_file.writestr(vfspath(path), data) def create_dir(self, path): - zip_info = zipfile.ZipInfo(str(path) + '/') + zip_info = zipfile.ZipInfo(vfspath(path) + '/') zip_info.external_attr |= stat.S_IFDIR << 16 zip_info.external_attr |= stat.FILE_ATTRIBUTE_DIRECTORY path.zip_file.writestr(zip_info, '') def create_symlink(self, path, target): - zip_info = zipfile.ZipInfo(str(path)) + zip_info = zipfile.ZipInfo(vfspath(path)) zip_info.external_attr = stat.S_IFLNK << 16 path.zip_file.writestr(zip_info, target.encode()) @@ -62,28 +63,28 @@ def create_hierarchy(self, p): self.create_symlink(p.joinpath('brokenLinkLoop'), 'brokenLinkLoop') def readtext(self, p): - with p.zip_file.open(str(p), 'r') as f: + with p.zip_file.open(vfspath(p), 'r') as f: f = io.TextIOWrapper(f, encoding='utf-8') return f.read() def readbytes(self, p): - with p.zip_file.open(str(p), 'r') as f: + with p.zip_file.open(vfspath(p), 'r') as f: return f.read() readlink = readtext def isdir(self, p): - path_str = str(p) + "/" + path_str = vfspath(p) + "/" return path_str in p.zip_file.NameToInfo def isfile(self, p): - info = p.zip_file.NameToInfo.get(str(p)) + info = p.zip_file.NameToInfo.get(vfspath(p)) if info is None: return False return not stat.S_ISLNK(info.external_attr >> 16) def islink(self, p): - info = p.zip_file.NameToInfo.get(str(p)) + info = p.zip_file.NameToInfo.get(vfspath(p)) if info is None: return False return stat.S_ISLNK(info.external_attr >> 16) @@ -240,20 +241,20 @@ def __init__(self, *pathsegments, zip_file): zip_file.filelist = ZipFileList(zip_file) def __hash__(self): - return hash((str(self), self.zip_file)) + return hash((vfspath(self), self.zip_file)) def __eq__(self, other): if not isinstance(other, ReadableZipPath): return NotImplemented - return str(self) == str(other) and self.zip_file is other.zip_file + return vfspath(self) == vfspath(other) and self.zip_file is other.zip_file - def __str__(self): + def __vfspath__(self): if not self._segments: return '' return self.parser.join(*self._segments) def __repr__(self): - return f'{type(self).__name__}({str(self)!r}, zip_file={self.zip_file!r})' + return f'{type(self).__name__}({vfspath(self)!r}, zip_file={self.zip_file!r})' def with_segments(self, *pathsegments): return type(self)(*pathsegments, zip_file=self.zip_file) @@ -261,15 +262,15 @@ def with_segments(self, *pathsegments): @property def info(self): tree = self.zip_file.filelist.tree - return tree.resolve(str(self), follow_symlinks=False) + return tree.resolve(vfspath(self), follow_symlinks=False) - def __open_rb__(self, buffering=-1): + def __open_reader__(self): info = self.info.resolve() if not info.exists(): raise FileNotFoundError(errno.ENOENT, "File not found", self) elif info.is_dir(): raise IsADirectoryError(errno.EISDIR, "Is a directory", self) - return self.zip_file.open(info.zip_info, 'r') + return self.zip_file.open(info.zip_info) def iterdir(self): info = self.info.resolve() @@ -301,36 +302,36 @@ def __init__(self, *pathsegments, zip_file): self.zip_file = zip_file def __hash__(self): - return hash((str(self), self.zip_file)) + return hash((vfspath(self), self.zip_file)) def __eq__(self, other): if not isinstance(other, WritableZipPath): return NotImplemented - return str(self) == str(other) and self.zip_file is other.zip_file + return vfspath(self) == vfspath(other) and self.zip_file is other.zip_file - def __str__(self): + def __vfspath__(self): if not self._segments: return '' return self.parser.join(*self._segments) def __repr__(self): - return f'{type(self).__name__}({str(self)!r}, zip_file={self.zip_file!r})' + return f'{type(self).__name__}({vfspath(self)!r}, zip_file={self.zip_file!r})' def with_segments(self, *pathsegments): return type(self)(*pathsegments, zip_file=self.zip_file) - def __open_wb__(self, buffering=-1): - return self.zip_file.open(str(self), 'w') + def __open_writer__(self, mode): + return self.zip_file.open(vfspath(self), mode) def mkdir(self, mode=0o777): - zinfo = zipfile.ZipInfo(str(self) + '/') + zinfo = zipfile.ZipInfo(vfspath(self) + '/') zinfo.external_attr |= stat.S_IFDIR << 16 zinfo.external_attr |= stat.FILE_ATTRIBUTE_DIRECTORY self.zip_file.writestr(zinfo, '') def symlink_to(self, target, target_is_directory=False): - zinfo = zipfile.ZipInfo(str(self)) + zinfo = zipfile.ZipInfo(vfspath(self)) zinfo.external_attr = stat.S_IFLNK << 16 if target_is_directory: zinfo.external_attr |= 0x10 - self.zip_file.writestr(zinfo, str(target)) + self.zip_file.writestr(zinfo, target) diff --git a/Lib/test/test_pathlib/test_join.py b/Lib/test/test_pathlib/test_join.py index 6b51a09e5ac..4630210e492 100644 --- a/Lib/test/test_pathlib/test_join.py +++ b/Lib/test/test_pathlib/test_join.py @@ -376,6 +376,61 @@ def test_with_suffix(self): self.assertRaises(ValueError, P('a/b').with_suffix, '.d/.') self.assertRaises(TypeError, P('a/b').with_suffix, None) + def test_relative_to(self): + P = self.cls + p = P('a/b') + self.assertEqual(p.relative_to(P('')), P('a', 'b')) + self.assertEqual(p.relative_to(P('a')), P('b')) + self.assertEqual(p.relative_to(P('a/b')), P('')) + self.assertEqual(p.relative_to(P(''), walk_up=True), P('a', 'b')) + self.assertEqual(p.relative_to(P('a'), walk_up=True), P('b')) + self.assertEqual(p.relative_to(P('a/b'), walk_up=True), P('')) + self.assertEqual(p.relative_to(P('a/c'), walk_up=True), P('..', 'b')) + self.assertEqual(p.relative_to(P('a/b/c'), walk_up=True), P('..')) + self.assertEqual(p.relative_to(P('c'), walk_up=True), P('..', 'a', 'b')) + self.assertRaises(ValueError, p.relative_to, P('c')) + self.assertRaises(ValueError, p.relative_to, P('a/b/c')) + self.assertRaises(ValueError, p.relative_to, P('a/c')) + self.assertRaises(ValueError, p.relative_to, P('/a')) + self.assertRaises(ValueError, p.relative_to, P('../a')) + self.assertRaises(ValueError, p.relative_to, P('a/..')) + self.assertRaises(ValueError, p.relative_to, P('/a/..')) + self.assertRaises(ValueError, p.relative_to, P('/'), walk_up=True) + self.assertRaises(ValueError, p.relative_to, P('/a'), walk_up=True) + self.assertRaises(ValueError, p.relative_to, P('../a'), walk_up=True) + self.assertRaises(ValueError, p.relative_to, P('a/..'), walk_up=True) + self.assertRaises(ValueError, p.relative_to, P('/a/..'), walk_up=True) + class Q(self.cls): + __eq__ = object.__eq__ + __hash__ = object.__hash__ + q = Q('a/b') + self.assertTrue(q.relative_to(q)) + self.assertRaises(ValueError, q.relative_to, Q('')) + self.assertRaises(ValueError, q.relative_to, Q('a')) + self.assertRaises(ValueError, q.relative_to, Q('a'), walk_up=True) + self.assertRaises(ValueError, q.relative_to, Q('a/b')) + self.assertRaises(ValueError, q.relative_to, Q('c')) + + def test_is_relative_to(self): + P = self.cls + p = P('a/b') + self.assertTrue(p.is_relative_to(P(''))) + self.assertTrue(p.is_relative_to(P('a'))) + self.assertTrue(p.is_relative_to(P('a/b'))) + self.assertFalse(p.is_relative_to(P('c'))) + self.assertFalse(p.is_relative_to(P('a/b/c'))) + self.assertFalse(p.is_relative_to(P('a/c'))) + self.assertFalse(p.is_relative_to(P('/a'))) + class Q(self.cls): + __eq__ = object.__eq__ + __hash__ = object.__hash__ + q = Q('a/b') + self.assertTrue(q.is_relative_to(q)) + self.assertFalse(q.is_relative_to(Q(''))) + self.assertFalse(q.is_relative_to(Q('a'))) + self.assertFalse(q.is_relative_to(Q('a/b'))) + self.assertFalse(q.is_relative_to(Q('c'))) + class LexicalPathJoinTest(JoinTestBase, unittest.TestCase): cls = LexicalPath diff --git a/Lib/test/test_pathlib/test_join_windows.py b/Lib/test/test_pathlib/test_join_windows.py index 2cc634f25ef..5afefa61b58 100644 --- a/Lib/test/test_pathlib/test_join_windows.py +++ b/Lib/test/test_pathlib/test_join_windows.py @@ -8,6 +8,11 @@ from .support import is_pypi from .support.lexical_path import LexicalWindowsPath +if is_pypi: + from pathlib_abc import vfspath +else: + from pathlib._os import vfspath + class JoinTestBase: def test_join(self): @@ -70,17 +75,22 @@ def test_div(self): self.assertEqual(p / './dd:s', P(r'C:/a/b\./dd:s')) self.assertEqual(p / 'E:d:s', P('E:d:s')) - def test_str(self): + def test_vfspath(self): p = self.cls(r'a\b\c') - self.assertEqual(str(p), 'a\\b\\c') + self.assertEqual(vfspath(p), 'a\\b\\c') p = self.cls(r'c:\a\b\c') - self.assertEqual(str(p), 'c:\\a\\b\\c') + self.assertEqual(vfspath(p), 'c:\\a\\b\\c') p = self.cls('\\\\a\\b\\') - self.assertEqual(str(p), '\\\\a\\b\\') + self.assertEqual(vfspath(p), '\\\\a\\b\\') p = self.cls(r'\\a\b\c') - self.assertEqual(str(p), '\\\\a\\b\\c') + self.assertEqual(vfspath(p), '\\\\a\\b\\c') p = self.cls(r'\\a\b\c\d') - self.assertEqual(str(p), '\\\\a\\b\\c\\d') + self.assertEqual(vfspath(p), '\\\\a\\b\\c\\d') + + def test_invalid_vspath(self): + msg = "expected JoinablePath object, not NoneType" + with self.assertRaisesRegex(TypeError, msg): + vfspath(None) def test_parts(self): P = self.cls diff --git a/Lib/test/test_pathlib/test_pathlib.py b/Lib/test/test_pathlib/test_pathlib.py index a1ea69a6b90..aff66c8efed 100644 --- a/Lib/test/test_pathlib/test_pathlib.py +++ b/Lib/test/test_pathlib/test_pathlib.py @@ -20,6 +20,8 @@ from test.support import is_emscripten, is_wasi, is_wasm32 from test.support import infinite_recursion from test.support import os_helper +from test.support import requires_root_user +from test.support import requires_non_root_user from test.support.os_helper import TESTFN, FS_NONASCII, FakePath try: import fcntl @@ -35,11 +37,6 @@ posix = None -root_in_posix = False -if hasattr(os, 'geteuid'): - root_in_posix = (os.geteuid() == 0) - - def patch_replace(old_test): def new_replace(self, target): raise OSError(errno.EXDEV, "Cross-device link", self, target) @@ -84,7 +81,7 @@ def test_is_notimplemented(self): class LazyImportTest(unittest.TestCase): @cpython_only def test_lazy_import(self): - import_helper.ensure_lazy_imports("pathlib", {"shutil"}) + import_helper.ensure_lazy_imports("pathlib", {"glob", "shutil"}) # @@ -545,12 +542,6 @@ def test_with_stem_empty(self): self.assertRaises(ValueError, P('a/b').with_stem, '') self.assertRaises(ValueError, P('a/b').with_stem, '.') - def test_is_reserved_deprecated(self): - P = self.cls - p = P('a/b') - with self.assertWarns(DeprecationWarning): - p.is_reserved() - def test_full_match_case_sensitive(self): P = self.cls self.assertFalse(P('A.py').full_match('a.PY', case_sensitive=True)) @@ -1560,7 +1551,7 @@ def raiser(*args, **kwargs): self.assertRaises(FileNotFoundError, source.copy, target) @unittest.skipIf(sys.platform == "win32" or sys.platform == "wasi", "directories are always readable on Windows and WASI") - @unittest.skipIf(root_in_posix, "test fails with root privilege") + @requires_non_root_user def test_copy_dir_no_read_permission(self): base = self.cls(self.base) source = base / 'dirE' @@ -2033,7 +2024,7 @@ def test_owner(self): self.assertEqual(expected_name, p.owner()) @unittest.skipUnless(pwd, "the pwd module is needed for this test") - @unittest.skipUnless(root_in_posix, "test needs root privilege") + @requires_root_user def test_owner_no_follow_symlinks(self): all_users = [u.pw_uid for u in pwd.getpwall()] if len(all_users) < 2: @@ -2068,7 +2059,7 @@ def test_group(self): self.assertEqual(expected_name, p.group()) @unittest.skipUnless(grp, "the grp module is needed for this test") - @unittest.skipUnless(root_in_posix, "test needs root privilege") + @requires_root_user def test_group_no_follow_symlinks(self): all_groups = [g.gr_gid for g in grp.getgrall()] if len(all_groups) < 2: @@ -2501,6 +2492,116 @@ def my_mkdir(path, mode=0o777): self.assertNotIn(str(p12), concurrently_created) self.assertTrue(p.exists()) + @unittest.skipIf( + is_emscripten or is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_mkdir_parents_umask(self): + # Test that parent directories respect umask when parent_mode is not set + p = self.cls(self.base, 'umasktest', 'child') + self.assertFalse(p.exists()) + if os.name != 'nt': + with os_helper.temp_umask(0o002): + p.mkdir(0o755, parents=True) + self.assertTrue(p.exists()) + # Leaf directory gets the specified mode + self.assertEqual(p.stat().st_mode & 0o777, 0o755) + # Parent directory respects umask (0o777 & ~0o002 = 0o775) + self.assertEqual(p.parent.stat().st_mode & 0o777, 0o775) + + @unittest.skipIf( + is_emscripten or is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_mkdir_with_parent_mode(self): + # Test the parent_mode parameter + p = self.cls(self.base, 'newdirPM', 'subdirPM') + self.assertFalse(p.exists()) + if os.name != 'nt': + with os_helper.temp_umask(0o022): + # Specify different modes for parent and leaf directories + p.mkdir(0o755, parents=True, parent_mode=0o750) + self.assertTrue(p.exists()) + self.assertTrue(p.is_dir()) + # Leaf directory gets the mode parameter + self.assertEqual(p.stat().st_mode & 0o777, 0o755) + # Parent directory gets the parent_mode parameter + self.assertEqual(p.parent.stat().st_mode & 0o777, 0o750) + + @unittest.skipIf( + is_emscripten or is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_mkdir_parent_mode_deep_hierarchy(self): + # Test parent_mode with deep directory hierarchy + p = self.cls(self.base, 'level1PM', 'level2PM', 'level3PM') + self.assertFalse(p.exists()) + if os.name != 'nt': + with os_helper.temp_umask(0o022): + p.mkdir(0o755, parents=True, parent_mode=0o700) + self.assertTrue(p.exists()) + # Check that all parent directories have parent_mode + level1 = self.cls(self.base, 'level1PM') + level2 = level1 / 'level2PM' + self.assertEqual(level1.stat().st_mode & 0o777, 0o700) + self.assertEqual(level2.stat().st_mode & 0o777, 0o700) + # Leaf directory has the regular mode + self.assertEqual(p.stat().st_mode & 0o777, 0o755) + + @unittest.skipIf( + is_emscripten or is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_mkdir_parent_mode_combined_with_umask(self): + # parent_mode, like mode, is combined with the process umask; it does + # not bypass it. + p = self.cls(self.base, 'umaskPM', 'child') + self.assertFalse(p.exists()) + if os.name != 'nt': + with os_helper.temp_umask(0o022): + p.mkdir(0o777, parents=True, parent_mode=0o777) + self.assertTrue(p.exists()) + # 0o777 is masked down to 0o755 by the 0o022 umask, for both + # the leaf (mode) and the parent (parent_mode). + self.assertEqual(p.stat().st_mode & 0o777, 0o755) + self.assertEqual(p.parent.stat().st_mode & 0o777, 0o755) + + @unittest.skipIf( + is_emscripten or is_wasi, + "umask is not implemented on Emscripten/WASI." + ) + @unittest.skipIf( + sys.platform == "android", + "Android filesystem may not honor requested permissions." + ) + def test_mkdir_parent_mode_same_as_mode(self): + # Test setting parent_mode same as mode + p = self.cls(self.base, 'samedirPM', 'subdirPM') + self.assertFalse(p.exists()) + if os.name != 'nt': + with os_helper.temp_umask(0o022): + p.mkdir(0o705, parents=True, parent_mode=0o705) + self.assertTrue(p.exists()) + # Both directories should have the same mode + self.assertEqual(p.stat().st_mode & 0o777, 0o705) + self.assertEqual(p.parent.stat().st_mode & 0o777, 0o705) + @needs_symlinks def test_symlink_to(self): P = self.cls(self.base) @@ -2769,6 +2870,7 @@ def test_is_socket_true(self): if (isinstance(e, PermissionError) or "AF_UNIX path too long" in str(e)): self.skipTest("cannot bind Unix socket: " + str(e)) + raise self.assertTrue(P.is_socket()) self.assertFalse(P.is_fifo()) self.assertFalse(P.is_file()) diff --git a/Lib/test/test_pathlib/test_read.py b/Lib/test/test_pathlib/test_read.py index 482203c290a..51eede9d9eb 100644 --- a/Lib/test/test_pathlib/test_read.py +++ b/Lib/test/test_pathlib/test_read.py @@ -13,10 +13,10 @@ if is_pypi: from pathlib_abc import PathInfo, _ReadablePath - from pathlib_abc._os import magic_open + from pathlib_abc._os import vfsopen else: from pathlib.types import PathInfo, _ReadablePath - from pathlib._os import magic_open + from pathlib._os import vfsopen class ReadTestBase: @@ -32,10 +32,16 @@ def test_is_readable(self): def test_open_r(self): p = self.root / 'fileA' - with magic_open(p, 'r', encoding='utf-8') as f: + with vfsopen(p, 'r', encoding='utf-8') as f: self.assertIsInstance(f, io.TextIOBase) self.assertEqual(f.read(), 'this is file A\n') + def test_open_r_buffering_error(self): + p = self.root / 'fileA' + self.assertRaises(ValueError, vfsopen, p, 'r', buffering=0) + self.assertRaises(ValueError, vfsopen, p, 'r', buffering=1) + self.assertRaises(ValueError, vfsopen, p, 'r', buffering=1024) + @unittest.skipIf( not getattr(sys.flags, 'warn_default_encoding', 0), "Requires warn_default_encoding", @@ -43,17 +49,17 @@ def test_open_r(self): def test_open_r_encoding_warning(self): p = self.root / 'fileA' with self.assertWarns(EncodingWarning) as wc: - with magic_open(p, 'r'): + with vfsopen(p, 'r'): pass self.assertEqual(wc.filename, __file__) def test_open_rb(self): p = self.root / 'fileA' - with magic_open(p, 'rb') as f: + with vfsopen(p, 'rb') as f: self.assertEqual(f.read(), b'this is file A\n') - self.assertRaises(ValueError, magic_open, p, 'rb', encoding='utf8') - self.assertRaises(ValueError, magic_open, p, 'rb', errors='strict') - self.assertRaises(ValueError, magic_open, p, 'rb', newline='') + self.assertRaises(ValueError, vfsopen, p, 'rb', encoding='utf8') + self.assertRaises(ValueError, vfsopen, p, 'rb', errors='strict') + self.assertRaises(ValueError, vfsopen, p, 'rb', newline='') def test_read_bytes(self): p = self.root / 'fileA' @@ -323,6 +329,11 @@ def test_info_is_symlink(self): self.assertFalse((p / 'fileA\udfff').info.is_symlink()) self.assertFalse((p / 'fileA\x00').info.is_symlink()) + def test_invalid_mode(self): + p = self.root / 'fileA' + with self.assertRaisesRegex(ValueError, 'invalid mode'): + vfsopen(p, 'q') + class ZipPathReadTest(ReadTestBase, unittest.TestCase): ground = ZipPathGround(ReadableZipPath) diff --git a/Lib/test/test_pathlib/test_write.py b/Lib/test/test_pathlib/test_write.py index 15054e804ec..fa2a81a47b3 100644 --- a/Lib/test/test_pathlib/test_write.py +++ b/Lib/test/test_pathlib/test_write.py @@ -13,10 +13,10 @@ if is_pypi: from pathlib_abc import _WritablePath - from pathlib_abc._os import magic_open + from pathlib_abc._os import vfsopen else: from pathlib.types import _WritablePath - from pathlib._os import magic_open + from pathlib._os import vfsopen class WriteTestBase: @@ -31,11 +31,17 @@ def test_is_writable(self): def test_open_w(self): p = self.root / 'fileA' - with magic_open(p, 'w', encoding='utf-8') as f: + with vfsopen(p, 'w', encoding='utf-8') as f: self.assertIsInstance(f, io.TextIOBase) f.write('this is file A\n') self.assertEqual(self.ground.readtext(p), 'this is file A\n') + def test_open_w_buffering_error(self): + p = self.root / 'fileA' + self.assertRaises(ValueError, vfsopen, p, 'w', buffering=0) + self.assertRaises(ValueError, vfsopen, p, 'w', buffering=1) + self.assertRaises(ValueError, vfsopen, p, 'w', buffering=1024) + @unittest.skipIf( not getattr(sys.flags, 'warn_default_encoding', 0), "Requires warn_default_encoding", @@ -43,19 +49,19 @@ def test_open_w(self): def test_open_w_encoding_warning(self): p = self.root / 'fileA' with self.assertWarns(EncodingWarning) as wc: - with magic_open(p, 'w'): + with vfsopen(p, 'w'): pass self.assertEqual(wc.filename, __file__) def test_open_wb(self): p = self.root / 'fileA' - with magic_open(p, 'wb') as f: + with vfsopen(p, 'wb') as f: #self.assertIsInstance(f, io.BufferedWriter) f.write(b'this is file A\n') self.assertEqual(self.ground.readbytes(p), b'this is file A\n') - self.assertRaises(ValueError, magic_open, p, 'wb', encoding='utf8') - self.assertRaises(ValueError, magic_open, p, 'wb', errors='strict') - self.assertRaises(ValueError, magic_open, p, 'wb', newline='') + self.assertRaises(ValueError, vfsopen, p, 'wb', encoding='utf8') + self.assertRaises(ValueError, vfsopen, p, 'wb', errors='strict') + self.assertRaises(ValueError, vfsopen, p, 'wb', newline='') def test_write_bytes(self): p = self.root / 'fileA' diff --git a/Lib/test/test_patma.py b/Lib/test/test_patma.py index 5d0857b059e..0825d9d980c 100644 --- a/Lib/test/test_patma.py +++ b/Lib/test/test_patma.py @@ -2762,6 +2762,97 @@ def test_patma_255(self): self.assertEqual(y, 1) self.assertIs(z, x) + def test_patma_256(self): + x = 0 + match x: + case +0: + y = 0 + self.assertEqual(x, 0) + self.assertEqual(y, 0) + + def test_patma_257(self): + x = 0 + match x: + case +0.0: + y = 0 + self.assertEqual(x, 0) + self.assertEqual(y, 0) + + def test_patma_258(self): + x = 0 + match x: + case +0j: + y = 0 + self.assertEqual(x, 0) + self.assertEqual(y, 0) + + def test_patma_259(self): + x = 0 + match x: + case +0.0j: + y = 0 + self.assertEqual(x, 0) + self.assertEqual(y, 0) + + def test_patma_260(self): + x = 1 + match x: + case +1: + y = 0 + self.assertEqual(x, 1) + self.assertEqual(y, 0) + + def test_patma_261(self): + x = 1.5 + match x: + case +1.5: + y = 0 + self.assertEqual(x, 1.5) + self.assertEqual(y, 0) + + def test_patma_262(self): + x = 1j + match x: + case +1j: + y = 0 + self.assertEqual(x, 1j) + self.assertEqual(y, 0) + + def test_patma_263(self): + x = 1.5j + match x: + case +1.5j: + y = 0 + self.assertEqual(x, 1.5j) + self.assertEqual(y, 0) + + def test_patma_264(self): + x = 0.25 + 1.75j + match x: + case +0.25 + 1.75j: + y = 0 + self.assertEqual(x, 0.25 + 1.75j) + self.assertEqual(y, 0) + + def test_patma_265(self): + x = 0 + match x: + case +1e1000: + y = 0 + case 0: + y = 1 + self.assertEqual(x, 0) + self.assertEqual(y, 1) + + def test_patma_frozendict_class_self(self): + x = frozendict() + match x: + case frozendict(z): + y = 0 + self.assertEqual(x, frozendict()) + self.assertEqual(y, 0) + self.assertIs(z, x) + def test_patma_runtime_checkable_protocol(self): # Runtime-checkable protocol from typing import Protocol, runtime_checkable @@ -3230,6 +3321,34 @@ def test_mapping_pattern_duplicate_key_edge_case3(self): pass """) + def test_duplicate_sign_in_complex_1(self): + self.assert_syntax_error(""" + match ...: + case 0 ++ 0j: + pass + """) + + def test_duplicate_sign_in_complex_2(self): + self.assert_syntax_error(""" + match ...: + case 0 -+ 0j: + pass + """) + + def test_duplicate_sign_in_complex_3(self): + self.assert_syntax_error(""" + match ...: + case 0 +- 0j: + pass + """) + + def test_duplicate_sign_in_complex_4(self): + self.assert_syntax_error(""" + match ...: + case 0 -- 0j: + pass + """) + class TestTypeErrors(unittest.TestCase): def test_accepts_positional_subpatterns_0(self): diff --git a/Lib/test/test_pdb.py b/Lib/test/test_pdb.py index 471623720bc..d26c68d3421 100644 --- a/Lib/test/test_pdb.py +++ b/Lib/test/test_pdb.py @@ -6,6 +6,7 @@ import io import os import pdb +import re import sys import types import codecs @@ -241,7 +242,7 @@ def test_pdb_breakpoint_commands(): the breakpoint list outputs a tab for the "stop only" and "ignore next" lines, which we don't want to put in here. - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE ... 'break 3', ... 'break 4, +', ... 'disable 1', @@ -416,7 +417,7 @@ def test_pdb_breakpoint_on_annotated_function_def(): ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() ... pass - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE ... 'break foo', ... 'break bar', ... 'break foobar', @@ -443,7 +444,7 @@ def test_pdb_commands(): ... print(2) ... print(3) - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE ... 'b 3', ... 'commands', ... 'silent', # suppress the frame status output @@ -490,7 +491,7 @@ def test_pdb_breakpoint_with_filename(): ... mod2.func88() ... mod2.func114() - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS +SKIP + >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS ... 'break test.test_inspect.inspect_fodder2:90', ... 'continue', # will stop at func88 ... 'break test/test_inspect/inspect_fodder2.py:115', @@ -577,7 +578,7 @@ def test_pdb_breakpoints_preserved_across_interactive_sessions(): 2 breakpoint keep yes at ...test_pdb.py:... (Pdb) continue - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... 'break', ... 'break pdb.find_function', ... 'break', @@ -601,7 +602,7 @@ def test_pdb_breakpoints_preserved_across_interactive_sessions(): Deleted breakpoint 1 at ...test_pdb.py:... (Pdb) continue - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... 'break', ... 'clear 2', ... 'clear 3', @@ -641,7 +642,7 @@ def test_pdb_break_anywhere(): >>> def test_function(): ... caller() - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE ... 'b 3', ... 'c', ... ]): @@ -1754,7 +1755,7 @@ def test_pdb_return_to_different_file(): ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() ... pprint.pprint(A()) - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +ELLIPSIS, +NORMALIZE_WHITESPACE ... 'b A.__repr__', ... 'continue', ... 'return', @@ -1917,7 +1918,7 @@ def test_pdb_continue_in_bottomframe(): ... print(3) ... print(4) - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +ELLIPSIS +SKIP + >>> with PdbTestInput([ # doctest: +ELLIPSIS ... 'step', ... 'next', ... 'break 7', @@ -1960,12 +1961,12 @@ def test_pdb_run_with_incorrect_argument(): """Testing run and runeval with incorrect first argument. >>> pti = PdbTestInput(['continue',]) - >>> with pti: # TODO: RUSTPYTHON # doctest: +EXPECTED_FAILURE + >>> with pti: ... pdb_invoke('run', lambda x: x) Traceback (most recent call last): TypeError: exec() arg 1 must be a string, bytes or code object - >>> with pti: # TODO: RUSTPYTHON # doctest: +EXPECTED_FAILURE + >>> with pti: ... pdb_invoke('runeval', lambda x: x) Traceback (most recent call last): TypeError: eval() arg 1 must be a string, bytes or code object @@ -2008,7 +2009,7 @@ def test_next_until_return_at_return_event(): ... test_function_2() ... end = 1 - >>> with PdbTestInput(['break test_function_2', # TODO: RUSTPYTHON # doctest: +SKIP + >>> with PdbTestInput(['break test_function_2', ... 'continue', ... 'return', ... 'next', @@ -2077,7 +2078,7 @@ def test_pdb_next_command_for_generator(): ... raise AssertionError ... print("finished") - >>> with PdbTestInput(['step', # TODO: RUSTPYTHON # doctest: +EXPECTED_FAILURE + >>> with PdbTestInput(['step', ... 'step', ... 'step', ... 'step', @@ -2227,7 +2228,7 @@ def test_pdb_await_with_breakpoint(): >>> def test_function(): ... asyncio.run(main(), loop_factory=asyncio.EventLoop) - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +ELLIPSIS +SKIP + >>> with PdbTestInput([ # doctest: +ELLIPSIS ... 'b test', ... 'k = await task', ... 'n', @@ -2458,7 +2459,7 @@ def test_pdb_return_command_for_generator(): ... raise AssertionError ... print("finished") - >>> with PdbTestInput(['step', # TODO: RUSTPYTHON # doctest: +EXPECTED_FAILURE + >>> with PdbTestInput(['step', ... 'step', ... 'step', ... 'step', @@ -2650,7 +2651,7 @@ def test_pdb_next_command_in_generator_for_loop(): ... print('value', i) ... x = 123 - >>> with PdbTestInput(['break test_gen', # TODO: RUSTPYTHON # doctest: +SKIP + >>> with PdbTestInput(['break test_gen', ... 'continue', ... 'next', ... 'next', @@ -2953,7 +2954,7 @@ def test_pdb_issue_20766(): ... print('pdb %d: %s' % (i, sess._previous_sigint_handler)) ... i += 1 - >>> with PdbTestInput(['continue', # TODO: RUSTPYTHON # doctest: +SKIP + >>> with PdbTestInput(['continue', ... 'continue']): ... test_function() > (5)test_function() @@ -3265,6 +3266,35 @@ def test_pdb_issue_gh_136057(): """ +def test_pdb_until_skip_comprehension(): + """See GH-152373 + "until" should get over a list comprehension with a breakpoint set on it + >>> def test_function(): + ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() + ... lst = [i for i in range(10)] + ... for i in lst: pass + + >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE + ... 'break 3', + ... 'continue', + ... 'until', + ... 'continue', + ... ]): + ... test_function() + > (2)test_function() + -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() + (Pdb) break 3 + Breakpoint 1 at :3 + (Pdb) continue + > (3)test_function() + -> lst = [i for i in range(10)] + (Pdb) until + > (4)test_function() + -> for i in lst: pass + (Pdb) continue + """ + + def test_pdb_issue_gh_80731(): """See GH-80731 @@ -3408,7 +3438,7 @@ def test_pdb_function_break(): >>> def test_function(): ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() - >>> with PdbTestInput([ # TODO: RUSTPYTHON # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE +SKIP + >>> with PdbTestInput([ # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ... 'break foo', ... 'break bar', ... 'break boo', @@ -3445,7 +3475,7 @@ def test_pdb_issue_gh_65052(): >>> def test_function(): ... A() - >>> with PdbTestInput([ # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE + >>> with PdbTestInput([ # doctest: +ELLIPSIS +NORMALIZE_WHITESPACE ... 's', ... 's', ... 'retval', @@ -3480,6 +3510,49 @@ def test_pdb_issue_gh_65052(): (Pdb) continue """ +def test_pdb_commands_last_breakpoint(): + """See GH-142834 + + >>> def test_function(): + ... import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() + ... foo = 1 + ... bar = 2 + + >>> with PdbTestInput([ # doctest: +NORMALIZE_WHITESPACE + ... 'break 4', + ... 'break 3', + ... 'clear 2', + ... 'commands', + ... 'p "success"', + ... 'end', + ... 'continue', + ... 'clear 1', + ... 'commands', + ... 'continue', + ... ]): + ... test_function() + > (2)test_function() + -> import pdb; pdb.Pdb(nosigint=True, readrc=False).set_trace() + (Pdb) break 4 + Breakpoint 1 at :4 + (Pdb) break 3 + Breakpoint 2 at :3 + (Pdb) clear 2 + Deleted breakpoint 2 at :3 + (Pdb) commands + (com) p "success" + (com) end + (Pdb) continue + 'success' + > (4)test_function() + -> bar = 2 + (Pdb) clear 1 + Deleted breakpoint 1 at :4 + (Pdb) commands + *** cannot set commands: no existing breakpoint + (Pdb) continue + """ + @support.force_not_colorized_test_class @support.requires_subprocess() @@ -3611,6 +3684,20 @@ def quux(): ('bœr', 5), ) + def test_print_stack_entry_uses_dynamic_line_prefix(self): + """Test that pdb.line_prefix binding is dynamic (gh-141781).""" + stdout = io.StringIO() + p = pdb.Pdb(stdout=stdout) + + # Get the current frame to use for printing + frame = sys._getframe() + + with support.swap_attr(pdb, 'line_prefix', 'CUSTOM_PREFIX> '): + p.print_stack_entry((frame, frame.f_lineno)) + + # Check if the custom prefix appeared in the output + self.assertIn('CUSTOM_PREFIX> ', stdout.getvalue()) + def test_find_function_found_with_encoding_cookie(self): self._assert_find_function( """\ @@ -4038,6 +4125,23 @@ def test_readrc_homedir(self): f.write("invalid") self.assertEqual(pdb.Pdb().rcLines[0], "invalid") + def test_readrc_current_dir(self): + with os_helper.temp_cwd() as cwd: + rc_path = os.path.join(cwd, ".pdbrc") + with open(rc_path, "w") as f: + f.write("invalid") + self.assertEqual(pdb.Pdb().rcLines[-1], "invalid") + + def test_readrc_cwd_is_home(self): + with os_helper.EnvironmentVarGuard() as env: + env.unset("HOME") + with os_helper.temp_cwd() as cwd, patch("os.path.expanduser"): + rc_path = os.path.join(cwd, ".pdbrc") + os.path.expanduser.return_value = rc_path + with open(rc_path, "w") as f: + f.write("invalid") + self.assertEqual(pdb.Pdb().rcLines, ["invalid"]) + def test_header(self): stdout = StringIO() header = 'Nobody expects... blah, blah, blah' @@ -4374,7 +4478,6 @@ def test_relative_imports_on_plain_module(self): stdout, _ = self._run_pdb(['-m', self.module_name + '.runme'], commands) self.assertTrue(any("VAR from module" in l for l in stdout.splitlines()), stdout) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_errors_in_command(self): commands = "\n".join([ 'print(]', @@ -4667,6 +4770,25 @@ def test_end_of_options_separator(self): stdout, _ = self._run_pdb(['-m', 'mymod', '--', 'arg'], 'c\nq') self.assertIn("ARGS: ['--', 'arg']", stdout) + @unittest.skipIf(SKIP_CORO_TESTS, "Coroutine tests are skipped") + def test_async_break(self): + script = """ + import asyncio + + async def main(): + pass + + asyncio.run(main()) + """ + commands = """ + break main + continue + quit + """ + stdout, stderr = self.run_pdb_script(script, commands) + self.assertRegex(stdout, r"Breakpoint 1 at .*main\.py:5") + self.assertIn("pass", stdout) + def test_issue_59000(self): script = """ def foo(): @@ -4683,6 +4805,16 @@ def foo(self): stdout, stderr = self.run_pdb_script(script, commands) self.assertIn("The specified object 'C.foo' is not a function", stdout) + def test_pyrepl_available(self): + with patch.dict(os.environ, {"PYTHON_BASIC_REPL": "1"}): + self.assertFalse(pdb._pyrepl_available()) + + with patch.dict(os.environ, {}, clear=True): + mod = types.ModuleType("_pyrepl.main") + mod.CAN_USE_PYREPL = True + with patch.dict("sys.modules", {"_pyrepl.main": mod}): + self.assertTrue(pdb._pyrepl_available()) + class ChecklineTests(unittest.TestCase): def setUp(self): @@ -4758,7 +4890,6 @@ def _run_script(self, script, commands, ) return stdout, stderr - @unittest.expectedFailure # TODO: RUSTPYTHON def test_quit(self): script = """ x = 1 @@ -4785,7 +4916,6 @@ def test_quit(self): # The quit prompt should be printed exactly twice self.assertEqual(stdout.count("Quit anyway"), 2) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_quit_after_interact(self): """ interact command will set sys.ps1 temporarily, we need to make sure @@ -4834,6 +4964,18 @@ def foo(): stdout, _ = self._run_script(script, commands) self.assertIn("42", stdout) + def test_nested_set_trace(self): + # Calling breakpoint() in pdb prompt should just be ignored. + script = "breakpoint()" + commands = """ + breakpoint() + p 40 + 2 + c + """ + stdout, stderr = self._run_script(script, commands) + self.assertIn('42', stdout) + self.assertEqual(stderr, '') + def test_readline_not_imported(self): """GH-138860 Directly or indirectly importing readline might deadlock a subprocess @@ -4856,6 +4998,19 @@ def test_readline_not_imported(self): self.assertNotIn("readline imported", stdout) self.assertEqual(stderr, "") + def test_alternate_stdin(self): + script = textwrap.dedent(""" + import pdb + import io + + input_data = io.StringIO("p 40 + 2\\nc\\n") + pdb.Pdb(stdin=input_data).set_trace() + """) + commands = "" + stdout, stderr = self._run_script(script, commands) + self.assertIn("42", stdout) + self.assertEqual(stderr, "") + @support.force_colorized_test_class class PdbTestColorize(unittest.TestCase): @@ -4884,12 +5039,45 @@ def test_code_display(self): p.set_trace(commands=['ll', 'c']) self.assertNotIn("\x1b", output.getvalue()) + def test_list_does_not_colorize_trailing_newlines(self): + # Keep the marker split so it is not present in the listed source. + caret_newline = "^" + "J" + output = io.StringIO() + p = pdb.Pdb(stdout=output, colorize=True) + p.set_trace(commands=['list', 'continue']) + result = output.getvalue() + self.assertIn("\x1b", result) + self.assertNotIn(caret_newline, result) + def test_stack_entry(self): output = io.StringIO() p = pdb.Pdb(stdout=output, colorize=True) p.set_trace(commands=['w', 'c']) self.assertIn("\x1b", output.getvalue()) + @unittest.skipIf(not pdb._pyrepl_available(), "pyrepl is not available") + def test_gen_colors(self): + p = pdb.Pdb() + gen_colors = p.pyrepl_input.gen_colors + + test_cases = [ + ("longlist", [((0, 7), "soft_keyword")]), + ("!longlist", [((0, 0), "op")]), + ("list", [((0, 3), "soft_keyword")]), + ("list(", [((0, 3), "builtin"), ((4, 4), "op")]), + ("a = 1", [ + ((0, 0), "soft_keyword"), + ((2, 2), "op"), + ((4, 4), "number"), + ]) + ] + + for buffer, expected in test_cases: + for color_span, ((start, end), tag) in zip(gen_colors(buffer), expected, strict=True): + self.assertEqual(color_span.span.start, start) + self.assertEqual(color_span.span.end, end) + self.assertEqual(color_span.tag, tag) + @support.force_not_colorized_test_class @support.requires_subprocess() @@ -4927,6 +5115,20 @@ def setUpClass(cls): if readline.backend == "editline": raise unittest.SkipTest("libedit readline is not supported for pdb") + def _run_pty(self, script, input, env=None): + if env is None: + # By default, we use basic repl for the test. + # Subclass can overwrite this method and set env to use advanced REPL + env = os.environ | {'PYTHON_BASIC_REPL': '1'} + output = run_pty(script, input, env=env) + # filter all control characters + # Strip ANSI CSI sequences (good enough for most REPL/prompt output) + output = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", output.decode("utf-8")) + return output + + def _pyrepl_available(self): + return pdb._pyrepl_available() + def test_basic_completion(self): script = textwrap.dedent(""" import pdb; pdb.Pdb().set_trace() @@ -4938,12 +5140,12 @@ def test_basic_completion(self): # then add ntin and complete 'contin' to 'continue' input = b"co\t\tntin\t\n" - output = run_pty(script, input) + output = self._run_pty(script, input) - self.assertIn(b'commands', output) - self.assertIn(b'condition', output) - self.assertIn(b'continue', output) - self.assertIn(b'hello!', output) + self.assertIn('commands', output) + self.assertIn('condition', output) + self.assertIn('continue', output) + self.assertIn('hello!', output) def test_expression_completion(self): script = textwrap.dedent(""" @@ -4960,11 +5162,11 @@ def test_expression_completion(self): # Continue input += b"c\n" - output = run_pty(script, input) + output = self._run_pty(script, input) - self.assertIn(b'special', output) - self.assertIn(b'species', output) - self.assertIn(b'$_frame', output) + self.assertIn('special', output) + self.assertIn('species', output) + self.assertIn('$_frame', output) def test_builtin_completion(self): script = textwrap.dedent(""" @@ -4978,9 +5180,9 @@ def test_builtin_completion(self): # Continue input += b"c\n" - output = run_pty(script, input) + output = self._run_pty(script, input) - self.assertIn(b'special', output) + self.assertIn('special', output) def test_convvar_completion(self): script = textwrap.dedent(""" @@ -4996,10 +5198,10 @@ def test_convvar_completion(self): # Continue input += b"c\n" - output = run_pty(script, input) + output = self._run_pty(script, input) - self.assertIn(b' LOAD_CONST None/True/False + # LOAD_GLOBAL None/True/False --> LOAD_COMMON_CONSTANT None/True/False def f(): x = None x = None @@ -121,7 +121,7 @@ def h(): for func, elem in ((f, None), (g, True), (h, False)): with self.subTest(func=func): self.assertNotInBytecode(func, 'LOAD_GLOBAL') - self.assertInBytecode(func, 'LOAD_CONST', elem) + self.assertInBytecode(func, 'LOAD_COMMON_CONSTANT', elem) self.check_lnotab(func) def f(): @@ -129,7 +129,7 @@ def f(): return None self.assertNotInBytecode(f, 'LOAD_GLOBAL') - self.assertInBytecode(f, 'LOAD_CONST', None) + self.assertInBytecode(f, 'LOAD_COMMON_CONSTANT', None) self.check_lnotab(f) def test_while_one(self): @@ -146,13 +146,14 @@ def f(): def test_pack_unpack(self): for line, elem in ( - ('a, = a,', 'LOAD_CONST',), + ('a, = a,', None), ('a, b = a, b', 'SWAP',), ('a, b, c = a, b, c', 'SWAP',), ): with self.subTest(line=line): code = compile(line,'','single') - self.assertInBytecode(code, elem) + if elem is not None: + self.assertInBytecode(code, elem) self.assertNotInBytecode(code, 'BUILD_TUPLE') self.assertNotInBytecode(code, 'UNPACK_SEQUENCE') self.check_lnotab(code) @@ -174,10 +175,10 @@ def test_constant_folding_tuples_of_constants(self): # Long tuples should be folded too. code = compile(repr(tuple(range(10000))),'','single') self.assertNotInBytecode(code, 'BUILD_TUPLE') - # One LOAD_CONST for the tuple, one for the None return value + # One LOAD_CONST for the tuple; None return value uses LOAD_COMMON_CONSTANT load_consts = [instr for instr in dis.get_instructions(code) if instr.opname == 'LOAD_CONST'] - self.assertEqual(len(load_consts), 2) + self.assertEqual(len(load_consts), 1) self.check_lnotab(code) # Bug 1053819: Tuple of constants misidentified when presented with: @@ -283,11 +284,11 @@ def test_constant_folding_unaryop(self): ('-0.0', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -0.0), ('-(1.0-1.0)', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -0.0), ('-0.5', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -0.5), - ('---1', 'UNARY_NEGATIVE', None, True, 'LOAD_CONST', -1), + ('---1', 'UNARY_NEGATIVE', None, True, 'LOAD_COMMON_CONSTANT', -1), ('---""', 'UNARY_NEGATIVE', None, False, None, None), ('~~~1', 'UNARY_INVERT', None, True, 'LOAD_CONST', -2), ('~~~""', 'UNARY_INVERT', None, False, None, None), - ('not not True', 'UNARY_NOT', None, True, 'LOAD_CONST', True), + ('not not True', 'UNARY_NOT', None, True, 'LOAD_COMMON_CONSTANT', True), ('not not x', 'UNARY_NOT', None, True, 'LOAD_NAME', 'x'), # this should be optimized regardless of constant or not ('+++1', 'CALL_INTRINSIC_1', intrinsic_positive, True, 'LOAD_SMALL_INT', 1), ('---x', 'UNARY_NEGATIVE', None, False, None, None), @@ -326,7 +327,7 @@ def test_constant_folding_binop(self): ('1 + 2', 'NB_ADD', True, 'LOAD_SMALL_INT', 3), ('1 + 2 + 3', 'NB_ADD', True, 'LOAD_SMALL_INT', 6), ('1 + ""', 'NB_ADD', False, None, None), - ('1 - 2', 'NB_SUBTRACT', True, 'LOAD_CONST', -1), + ('1 - 2', 'NB_SUBTRACT', True, 'LOAD_COMMON_CONSTANT', -1), ('1 - 2 - 3', 'NB_SUBTRACT', True, 'LOAD_CONST', -4), ('1 - ""', 'NB_SUBTRACT', False, None, None), ('2 * 2', 'NB_MULTIPLY', True, 'LOAD_SMALL_INT', 4), @@ -734,22 +735,27 @@ def test_format_errors(self): with self.assertRaisesRegex(TypeError, 'not all arguments converted during string formatting'): eval("'%s' % (x, y)", {'x': 1, 'y': 2}) - with self.assertRaisesRegex(ValueError, 'incomplete format'): + with self.assertRaisesRegex(ValueError, 'stray % at position 2'): eval("'%s%' % (x,)", {'x': 1234}) - with self.assertRaisesRegex(ValueError, 'incomplete format'): + with self.assertRaisesRegex(ValueError, 'stray % at position 4'): eval("'%s%%%' % (x,)", {'x': 1234}) with self.assertRaisesRegex(TypeError, 'not enough arguments for format string'): eval("'%s%z' % (x,)", {'x': 1234}) - with self.assertRaisesRegex(ValueError, 'unsupported format character'): + with self.assertRaisesRegex(ValueError, + 'unsupported format %z at position 2'): eval("'%s%z' % (x, 5)", {'x': 1234}) - with self.assertRaisesRegex(TypeError, 'a real number is required, not str'): + with self.assertRaisesRegex(TypeError, + 'format argument 1: %d requires a real number, not str'): eval("'%d' % (x,)", {'x': '1234'}) - with self.assertRaisesRegex(TypeError, 'an integer is required, not float'): + with self.assertRaisesRegex(TypeError, + 'format argument 1: %x requires an integer, not float'): eval("'%x' % (x,)", {'x': 1234.56}) - with self.assertRaisesRegex(TypeError, 'an integer is required, not str'): + with self.assertRaisesRegex(TypeError, + 'format argument 1: %x requires an integer, not str'): eval("'%x' % (x,)", {'x': '1234'}) - with self.assertRaisesRegex(TypeError, 'must be real number, not str'): + with self.assertRaisesRegex(TypeError, + 'format argument 1: %f requires a real number, not str'): eval("'%f' % (x,)", {'x': '1234'}) with self.assertRaisesRegex(TypeError, 'not enough arguments for format string'): @@ -1117,6 +1123,13 @@ def trace(frame, event, arg): self.assertInBytecode(f, "LOAD_FAST_BORROW") self.assertNotInBytecode(f, "LOAD_FAST_CHECK") + def test_import_from_doesnt_clobber_load_fast_borrow(self): + def f(self): + if x: pass + self.x + from shutil import ExecError + print(ExecError) + self.assertInBytecode(f, "LOAD_FAST_BORROW", "self") class DirectCfgOptimizerTests(CfgOptimizationTestCase): @@ -1506,7 +1519,7 @@ def test_optimize_literal_list_for_iter(self): ('LOAD_SMALL_INT', 1, 0), ('LOAD_SMALL_INT', 2, 0), ('BUILD_LIST', 2, 0), - ('GET_ITER', None, 0), + ('GET_ITER', 0, 0), start := self.Label(), ('FOR_ITER', end := self.Label(), 0), ('STORE_FAST', 0, 0), @@ -1519,7 +1532,7 @@ def test_optimize_literal_list_for_iter(self): ] after = [ ('LOAD_CONST', 1, 0), - ('GET_ITER', None, 0), + ('GET_ITER', 0, 0), start := self.Label(), ('FOR_ITER', end := self.Label(), 0), ('STORE_FAST', 0, 0), @@ -1527,7 +1540,7 @@ def test_optimize_literal_list_for_iter(self): end, ('END_FOR', None, 0), ('POP_ITER', None, 0), - ('LOAD_CONST', 0, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), ('RETURN_VALUE', None, 0), ] self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, (1, 2)]) @@ -1537,7 +1550,7 @@ def test_optimize_literal_list_for_iter(self): ('LOAD_SMALL_INT', 1, 0), ('LOAD_NAME', 0, 0), ('BUILD_LIST', 2, 0), - ('GET_ITER', None, 0), + ('GET_ITER', 0, 0), start := self.Label(), ('FOR_ITER', end := self.Label(), 0), ('STORE_FAST', 0, 0), @@ -1552,7 +1565,7 @@ def test_optimize_literal_list_for_iter(self): ('LOAD_SMALL_INT', 1, 0), ('LOAD_NAME', 0, 0), ('BUILD_TUPLE', 2, 0), - ('GET_ITER', None, 0), + ('GET_ITER', 0, 0), start := self.Label(), ('FOR_ITER', end := self.Label(), 0), ('STORE_FAST', 0, 0), @@ -1560,7 +1573,7 @@ def test_optimize_literal_list_for_iter(self): end, ('END_FOR', None, 0), ('POP_ITER', None, 0), - ('LOAD_CONST', 0, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), ('RETURN_VALUE', None, 0), ] self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None]) @@ -1571,7 +1584,7 @@ def test_optimize_literal_set_for_iter(self): ('LOAD_SMALL_INT', 1, 0), ('LOAD_SMALL_INT', 2, 0), ('BUILD_SET', 2, 0), - ('GET_ITER', None, 0), + ('GET_ITER', 0, 0), start := self.Label(), ('FOR_ITER', end := self.Label(), 0), ('STORE_FAST', 0, 0), @@ -1584,7 +1597,7 @@ def test_optimize_literal_set_for_iter(self): ] after = [ ('LOAD_CONST', 1, 0), - ('GET_ITER', None, 0), + ('GET_ITER', 0, 0), start := self.Label(), ('FOR_ITER', end := self.Label(), 0), ('STORE_FAST', 0, 0), @@ -1592,7 +1605,7 @@ def test_optimize_literal_set_for_iter(self): end, ('END_FOR', None, 0), ('POP_ITER', None, 0), - ('LOAD_CONST', 0, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), ('RETURN_VALUE', None, 0), ] self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, frozenset({1, 2})]) @@ -1603,7 +1616,7 @@ def test_optimize_literal_set_for_iter(self): ('LOAD_SMALL_INT', 1, 0), ('LOAD_NAME', 0, 0), ('BUILD_SET', 2, 0), - ('GET_ITER', None, 0), + ('GET_ITER', 0, 0), start := self.Label(), ('FOR_ITER', end := self.Label(), 0), ('STORE_FAST', 0, 0), @@ -1614,7 +1627,22 @@ def test_optimize_literal_set_for_iter(self): ('LOAD_CONST', 0, 0), ('RETURN_VALUE', None, 0), ] - self.cfg_optimization_test(same, same, consts=[None], expected_consts=[None]) + expected = [ + ('LOAD_SMALL_INT', 1, 0), + ('LOAD_NAME', 0, 0), + ('BUILD_SET', 2, 0), + ('GET_ITER', 0, 0), + start := self.Label(), + ('FOR_ITER', end := self.Label(), 0), + ('STORE_FAST', 0, 0), + ('JUMP', start, 0), + end, + ('END_FOR', None, 0), + ('POP_ITER', None, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), + ('RETURN_VALUE', None, 0), + ] + self.cfg_optimization_test(same, expected, consts=[None], expected_consts=[None]) def test_optimize_literal_list_contains(self): # x in [1, 2] ==> x in (1, 2) @@ -1633,7 +1661,7 @@ def test_optimize_literal_list_contains(self): ('LOAD_CONST', 1, 0), ('CONTAINS_OP', 0, 0), ('POP_TOP', None, 0), - ('LOAD_CONST', 0, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), ('RETURN_VALUE', None, 0), ] self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, (1, 2)]) @@ -1656,7 +1684,7 @@ def test_optimize_literal_list_contains(self): ('BUILD_TUPLE', 2, 0), ('CONTAINS_OP', 0, 0), ('POP_TOP', None, 0), - ('LOAD_CONST', 0, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), ('RETURN_VALUE', None, 0), ] self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None]) @@ -1678,7 +1706,7 @@ def test_optimize_literal_set_contains(self): ('LOAD_CONST', 1, 0), ('CONTAINS_OP', 0, 0), ('POP_TOP', None, 0), - ('LOAD_CONST', 0, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), ('RETURN_VALUE', None, 0), ] self.cfg_optimization_test(before, after, consts=[None], expected_consts=[None, frozenset({1, 2})]) @@ -1695,7 +1723,17 @@ def test_optimize_literal_set_contains(self): ('LOAD_CONST', 0, 0), ('RETURN_VALUE', None, 0), ] - self.cfg_optimization_test(same, same, consts=[None], expected_consts=[None]) + expected = [ + ('LOAD_NAME', 0, 0), + ('LOAD_SMALL_INT', 1, 0), + ('LOAD_NAME', 1, 0), + ('BUILD_SET', 2, 0), + ('CONTAINS_OP', 0, 0), + ('POP_TOP', None, 0), + ('LOAD_COMMON_CONSTANT', 7, 0), + ('RETURN_VALUE', None, 0), + ] + self.cfg_optimization_test(same, expected, consts=[None], expected_consts=[None]) def test_optimize_unary_not(self): # test folding @@ -1706,10 +1744,10 @@ def test_optimize_unary_not(self): ('RETURN_VALUE', None, 0), ] after = [ - ('LOAD_CONST', 1, 0), + ('LOAD_COMMON_CONSTANT', 10, 0), ('RETURN_VALUE', None, 0), ] - self.cfg_optimization_test(before, after, consts=[], expected_consts=[True, False]) + self.cfg_optimization_test(before, after, consts=[], expected_consts=[True]) # test cancel out before = [ @@ -1757,7 +1795,7 @@ def test_optimize_unary_not(self): ('RETURN_VALUE', None, 0), ] after = [ - ('LOAD_CONST', 0, 0), + ('LOAD_COMMON_CONSTANT', 9, 0), ('RETURN_VALUE', None, 0), ] self.cfg_optimization_test(before, after, consts=[], expected_consts=[True]) @@ -1773,10 +1811,10 @@ def test_optimize_unary_not(self): ('RETURN_VALUE', None, 0), ] after = [ - ('LOAD_CONST', 1, 0), + ('LOAD_COMMON_CONSTANT', 10, 0), ('RETURN_VALUE', None, 0), ] - self.cfg_optimization_test(before, after, consts=[], expected_consts=[True, False]) + self.cfg_optimization_test(before, after, consts=[], expected_consts=[True]) # test cancel out & eliminate to bool (to bool stays as we are not iterating to a fixed point) before = [ @@ -2392,7 +2430,7 @@ def test_list_to_tuple_get_iter(self): ("LOAD_FAST", 1, 4), ("LIST_EXTEND", 1, 5), ("CALL_INTRINSIC_1", INTRINSIC_LIST_TO_TUPLE, 6), - ("GET_ITER", None, 7), + ("GET_ITER", 0, 7), top := self.Label(), ("FOR_ITER", end := self.Label(), 8), ("STORE_FAST", 2, 9), @@ -2410,7 +2448,7 @@ def test_list_to_tuple_get_iter(self): ("LOAD_FAST_BORROW", 1, 4), ("LIST_EXTEND", 1, 5), ("NOP", None, 6), # ("CALL_INTRINSIC_1", INTRINSIC_LIST_TO_TUPLE, 6), - ("GET_ITER", None, 7), + ("GET_ITER", 0, 7), top := self.Label(), ("FOR_ITER", end := self.Label(), 8), ("STORE_FAST", 2, 9), @@ -2418,7 +2456,7 @@ def test_list_to_tuple_get_iter(self): end, ("END_FOR", None, 11), ("POP_TOP", None, 12), - ("LOAD_CONST", 0, 13), + ("LOAD_COMMON_CONSTANT", 7, 13), ("RETURN_VALUE", None, 14), ] self.cfg_optimization_test(insts, expected_insts, consts=[None]) @@ -2432,6 +2470,168 @@ def test_list_to_tuple_get_iter_is_safe(self): self.assertEqual(b, [3, 2, 1, 0]) self.assertEqual(items, []) + def test_fold_constant_big_list_for_iter(self): + # for x in [c1, c2, ..., cN] (N > 30) should fold to LOAD_CONST tuple + consts = 35 + before = ( + [("BUILD_LIST", 0, 1)] + + [("LOAD_CONST", 0, 2), ("LIST_APPEND", 1, 3)] * consts + + [("GET_ITER", 0, 4), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 5), + ("STORE_FAST", 0, 6), + ("JUMP", top, 7), + end, + ("END_FOR", None, 8), + ("POP_ITER", None, 9), + ("LOAD_CONST", 0, 10), + ("RETURN_VALUE", None, 11)] + ) + after = [ + ("LOAD_CONST", 1, 3), + ("GET_ITER", 0, 4), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 5), + ("STORE_FAST", 0, 6), + ("JUMP", top, 7), + end, + ("END_FOR", None, 8), + ("POP_ITER", None, 9), + ("LOAD_CONST", 0, 10), + ("RETURN_VALUE", None, 11), + ] + result_const = tuple(["test"] * consts) + self.cfg_optimization_test(before, after, consts=["test"], + expected_consts=["test", result_const]) + + def test_fold_constant_big_set_for_iter(self): + # for x in {c1, c2, ..., cN} (N > 30) should fold to LOAD_CONST frozenset + before = [ + ("BUILD_SET", 0, 1), + ("LOAD_SMALL_INT", 1, 2), ("SET_ADD", 1, 3), + ("LOAD_SMALL_INT", 2, 4), ("SET_ADD", 1, 5), + ("LOAD_SMALL_INT", 3, 6), ("SET_ADD", 1, 7), + ("GET_ITER", 0, 8), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 9), + ("STORE_FAST", 0, 10), + ("JUMP", top, 11), + end, + ("END_FOR", None, 12), + ("POP_ITER", None, 13), + ("LOAD_CONST", 0, 14), + ("RETURN_VALUE", None, 15), + ] + after = [ + ("LOAD_CONST", 1, 7), + ("GET_ITER", 0, 8), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 9), + ("STORE_FAST", 0, 10), + ("JUMP", top, 11), + end, + ("END_FOR", None, 12), + ("POP_ITER", None, 13), + ("LOAD_CONST", 0, 14), + ("RETURN_VALUE", None, 15), + ] + self.cfg_optimization_test(before, after, consts=["test"], + expected_consts=["test", frozenset({1, 2, 3})]) + + def test_fold_constant_list_to_tuple_for_iter(self): + INTRINSIC_LIST_TO_TUPLE = 6 + before = [ + ("BUILD_LIST", 0, 1), + ("LOAD_SMALL_INT", 1, 2), ("LIST_APPEND", 1, 3), + ("LOAD_SMALL_INT", 2, 4), ("LIST_APPEND", 1, 5), + ("LOAD_SMALL_INT", 3, 6), ("LIST_APPEND", 1, 7), + ("CALL_INTRINSIC_1", INTRINSIC_LIST_TO_TUPLE, 8), + ("GET_ITER", 0, 9), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 10), + ("STORE_FAST", 0, 11), + ("JUMP", top, 12), + end, + ("END_FOR", None, 13), + ("POP_ITER", None, 14), + ("LOAD_CONST", 0, 15), + ("RETURN_VALUE", None, 16), + ] + after = [ + ("LOAD_CONST", 1, 8), + ("GET_ITER", 0, 9), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 10), + ("STORE_FAST", 0, 11), + ("JUMP", top, 12), + end, + ("END_FOR", None, 13), + ("POP_ITER", None, 14), + ("LOAD_CONST", 0, 15), + ("RETURN_VALUE", None, 16), + ] + self.cfg_optimization_test(before, after, consts=["test"], + expected_consts=["test", (1, 2, 3)]) + + def test_fold_constant_big_list_contains_op(self): + # x in [c1, c2, ..., cN] (N > 30) should fold to LOAD_CONST tuple + before = [ + ("LOAD_FAST", 0, 1), + ("BUILD_LIST", 0, 2), + ("LOAD_SMALL_INT", 1, 3), ("LIST_APPEND", 1, 4), + ("LOAD_SMALL_INT", 2, 5), ("LIST_APPEND", 1, 6), + ("LOAD_SMALL_INT", 3, 7), ("LIST_APPEND", 1, 8), + ("CONTAINS_OP", 0, 9), + ("RETURN_VALUE", None, 10), + ] + after = [ + ("LOAD_FAST_BORROW", 0, 1), + ("LOAD_CONST", 1, 8), + ("CONTAINS_OP", 0, 9), + ("RETURN_VALUE", None, 10), + ] + self.cfg_optimization_test(before, after, consts=[None], + expected_consts=[None, (1, 2, 3)]) + + def test_fold_constant_big_set_contains_op(self): + # x in {c1, c2, ..., cN} (N > 30) should fold to LOAD_CONST frozenset + before = [ + ("LOAD_FAST", 0, 1), + ("BUILD_SET", 0, 2), + ("LOAD_SMALL_INT", 1, 3), ("SET_ADD", 1, 4), + ("LOAD_SMALL_INT", 2, 5), ("SET_ADD", 1, 6), + ("LOAD_SMALL_INT", 3, 7), ("SET_ADD", 1, 8), + ("CONTAINS_OP", 0, 9), + ("RETURN_VALUE", None, 10), + ] + after = [ + ("LOAD_FAST_BORROW", 0, 1), + ("LOAD_CONST", 1, 8), + ("CONTAINS_OP", 0, 9), + ("RETURN_VALUE", None, 10), + ] + self.cfg_optimization_test(before, after, consts=[None], + expected_consts=[None, frozenset({1, 2, 3})]) + + def test_no_fold_big_list_for_iter_with_non_const(self): + same = [ + ("BUILD_LIST", 0, 1), + ("LOAD_SMALL_INT", 1, 2), ("LIST_APPEND", 1, 3), + ("LOAD_FAST_BORROW", 0, 4), ("LIST_APPEND", 1, 5), + ("LOAD_SMALL_INT", 3, 6), ("LIST_APPEND", 1, 7), + ("GET_ITER", 0, 8), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 9), + ("STORE_FAST", 1, 10), + ("JUMP", top, 11), + end, + ("END_FOR", None, 12), + ("POP_ITER", None, 13), + ("LOAD_CONST", 0, 14), + ("RETURN_VALUE", None, 15), + ] + self.cfg_optimization_test(same, same, consts=["test"]) + class OptimizeLoadFastTestCase(DirectCfgOptimizerTests): def make_bb(self, insts): @@ -2442,7 +2642,7 @@ def make_bb(self, insts): maxconst = max(maxconst, arg) consts = [None for _ in range(maxconst + 1)] return insts + [ - ("LOAD_CONST", 0, last_loc + 1), + ("LOAD_COMMON_CONSTANT", 7, last_loc + 1), ("RETURN_VALUE", None, last_loc + 2), ], consts @@ -2473,7 +2673,7 @@ def test_optimized(self): ] expected = [ ("LOAD_FAST_BORROW", 0, 1), - ("LOAD_CONST", 1, 2), + ("LOAD_COMMON_CONSTANT", 7, 2), ("SWAP", 2, 3), ("POP_TOP", None, 4), ] @@ -2511,7 +2711,13 @@ def test_unoptimized_if_support_killed(self): ("STORE_FAST", 0, 3), ("POP_TOP", None, 4), ] - self.check(insts, insts) + expected = [ + ("LOAD_FAST", 0, 1), + ("LOAD_COMMON_CONSTANT", 7, 2), + ("STORE_FAST", 0, 3), + ("POP_TOP", None, 4), + ] + self.check(insts, expected) insts = [ ("LOAD_FAST", 0, 1), @@ -2520,7 +2726,14 @@ def test_unoptimized_if_support_killed(self): ("STORE_FAST_STORE_FAST", ((0 << 4) | 1), 4), ("POP_TOP", None, 5), ] - self.check(insts, insts) + expected = [ + ("LOAD_FAST", 0, 1), + ("LOAD_COMMON_CONSTANT", 7, 2), + ("LOAD_COMMON_CONSTANT", 7, 3), + ("STORE_FAST_STORE_FAST", ((0 << 4) | 1), 4), + ("POP_TOP", None, 5), + ] + self.check(insts, expected) insts = [ ("LOAD_FAST", 0, 1), @@ -2541,7 +2754,12 @@ def test_unoptimized_if_aliased(self): ("LOAD_CONST", 0, 3), ("STORE_FAST_STORE_FAST", ((0 << 4) | 1), 4), ] - self.check(insts, insts) + expected = [ + ("LOAD_FAST", 0, 1), + ("LOAD_COMMON_CONSTANT", 7, 3), + ("STORE_FAST_STORE_FAST", ((0 << 4) | 1), 4), + ] + self.check(insts, expected) def test_consume_no_inputs(self): insts = [ @@ -2586,7 +2804,19 @@ def test_for_iter(self): ("LOAD_CONST", 0, 7), ("RETURN_VALUE", None, 8), ] - self.cfg_optimization_test(insts, insts, consts=[None]) + expected = [ + ("LOAD_FAST", 0, 1), + top := self.Label(), + ("FOR_ITER", end := self.Label(), 2), + ("STORE_FAST", 2, 3), + ("JUMP", top, 4), + end, + ("END_FOR", None, 5), + ("POP_TOP", None, 6), + ("LOAD_COMMON_CONSTANT", 7, 7), + ("RETURN_VALUE", None, 8), + ] + self.cfg_optimization_test(insts, expected, consts=[None]) def test_load_attr(self): insts = [ @@ -2655,10 +2885,10 @@ def test_send(self): ("LOAD_FAST", 0, 1), ("LOAD_FAST_BORROW", 1, 2), ("SEND", end := self.Label(), 3), - ("LOAD_CONST", 0, 4), + ("LOAD_COMMON_CONSTANT", 7, 4), ("RETURN_VALUE", None, 5), end, - ("LOAD_CONST", 0, 6), + ("LOAD_COMMON_CONSTANT", 7, 6), ("RETURN_VALUE", None, 7) ] self.cfg_optimization_test(insts, expected, consts=[None]) @@ -2696,7 +2926,15 @@ def test_set_function_attribute(self): ("LOAD_CONST", 0, 5), ("RETURN_VALUE", None, 6) ] - self.cfg_optimization_test(insts, insts, consts=[None]) + expected = [ + ("LOAD_COMMON_CONSTANT", 7, 1), + ("LOAD_FAST", 0, 2), + ("SET_FUNCTION_ATTRIBUTE", 2, 3), + ("STORE_FAST", 1, 4), + ("LOAD_COMMON_CONSTANT", 7, 5), + ("RETURN_VALUE", None, 6) + ] + self.cfg_optimization_test(insts, expected, consts=[None]) insts = [ ("LOAD_CONST", 0, 1), @@ -2705,7 +2943,7 @@ def test_set_function_attribute(self): ("RETURN_VALUE", None, 4) ] expected = [ - ("LOAD_CONST", 0, 1), + ("LOAD_COMMON_CONSTANT", 7, 1), ("LOAD_FAST_BORROW", 0, 2), ("SET_FUNCTION_ATTRIBUTE", 2, 3), ("RETURN_VALUE", None, 4) @@ -2713,22 +2951,37 @@ def test_set_function_attribute(self): self.cfg_optimization_test(insts, expected, consts=[None]) def test_get_yield_from_iter(self): - # GET_YIELD_FROM_ITER may leave its operand on the stack insts = [ ("LOAD_FAST", 0, 1), - ("GET_YIELD_FROM_ITER", None, 2), - ("LOAD_CONST", 0, 3), + ("GET_ITER", 1, 2), + ("PUSH_NULL", None, 3), + ("LOAD_CONST", 0, 4), send := self.Label(), - ("SEND", end := self.Label(), 5), - ("YIELD_VALUE", 1, 6), - ("RESUME", 2, 7), - ("JUMP", send, 8), + ("SEND", end := self.Label(), 6), + ("YIELD_VALUE", 1, 7), + ("RESUME", 2, 8), + ("JUMP", send, 9), end, - ("END_SEND", None, 9), - ("LOAD_CONST", 0, 10), - ("RETURN_VALUE", None, 11), + ("END_SEND", None, 10), + ("LOAD_CONST", 0, 11), + ("RETURN_VALUE", None, 12), + ] + expected = [ + ("LOAD_FAST", 0, 1), + ("GET_ITER", 1, 2), + ("PUSH_NULL", None, 3), + ("LOAD_COMMON_CONSTANT", 7, 4), + send := self.Label(), + ("SEND", end := self.Label(), 6), + ("YIELD_VALUE", 1, 7), + ("RESUME", 2, 8), + ("JUMP", send, 9), + end, + ("END_SEND", None, 10), + ("LOAD_COMMON_CONSTANT", 7, 11), + ("RETURN_VALUE", None, 12), ] - self.cfg_optimization_test(insts, insts, consts=[None]) + self.cfg_optimization_test(insts, expected, consts=[None]) def test_push_exc_info(self): insts = [ diff --git a/Lib/test/test_peg_generator/test_c_parser.py b/Lib/test/test_peg_generator/test_c_parser.py index aa01a9b8f7e..dc887693840 100644 --- a/Lib/test/test_peg_generator/test_c_parser.py +++ b/Lib/test/test_peg_generator/test_c_parser.py @@ -100,11 +100,18 @@ def setUpClass(cls): with contextlib.ExitStack() as stack: python_exe = stack.enter_context(support.setup_venv_with_pip_setuptools("venv")) - sitepackages = subprocess.check_output( - [python_exe, "-c", "import sysconfig; print(sysconfig.get_path('platlib'))"], - text=True, - ).strip() - stack.enter_context(import_helper.DirsOnSysPath(sitepackages)) + + def get_sysconfig_path(name): + # Force UTF-8 to emit the non-ASCII venv path in any locale. + return subprocess.check_output( + [python_exe, "-X", "utf8", "-c", + f"import sysconfig; print(sysconfig.get_path({name!r}))"], + encoding="utf-8", + ).strip() + + platlib_path = get_sysconfig_path("platlib") + purelib_path = get_sysconfig_path("purelib") + stack.enter_context(import_helper.DirsOnSysPath(platlib_path, purelib_path)) cls.addClassCleanup(stack.pop_all().close) @support.requires_venv_with_pip() @@ -352,9 +359,9 @@ def test_same_name_different_types(self) -> None: grammar_source = """ start[mod_ty]: a[asdl_stmt_seq*]=import_from+ NEWLINE ENDMARKER { _PyAST_Module(a, NULL, p->arena)} import_from[stmt_ty]: ( a='from' !'import' c=simple_name 'import' d=import_as_names_from { - _PyAST_ImportFrom(c->v.Name.id, d, 0, EXTRA) } + _PyAST_ImportFrom(c->v.Name.id, d, 0, 0, EXTRA) } | a='from' '.' 'import' c=import_as_names_from { - _PyAST_ImportFrom(NULL, c, 1, EXTRA) } + _PyAST_ImportFrom(NULL, c, 1, 0, EXTRA) } ) simple_name[expr_ty]: NAME import_as_names_from[asdl_alias_seq*]: a[asdl_alias_seq*]=','.import_as_name_from+ { a } diff --git a/Lib/test/test_peg_generator/test_pegen.py b/Lib/test/test_peg_generator/test_pegen.py index 58ce558c548..f39fcc2e0d8 100644 --- a/Lib/test/test_peg_generator/test_pegen.py +++ b/Lib/test/test_peg_generator/test_pegen.py @@ -1130,3 +1130,53 @@ def test_deep_nested_rule(self) -> None: ) self.assertEqual(output, expected_output) + + def test_rule_flags(self) -> None: + """Test the new rule flags syntax that accepts arbitrary lists of flags.""" + # Test grammar with various flag combinations + grammar_source = """ + start: simple_rule + + simple_rule (memo): + | "hello" + + multi_flag_rule (memo, custom, test): + | "world" + + single_custom_flag (custom): + | "test" + + no_flags_rule: + | "plain" + """ + + grammar: Grammar = parse_string(grammar_source, GrammarParser) + rules = grammar.rules + + # Test memo-only rule + simple_rule = rules['simple_rule'] + self.assertTrue('memo' in simple_rule.flags, + "simple_rule should have memo") + self.assertEqual(simple_rule.flags, frozenset(['memo']), + f"simple_rule flags should be {'memo'}, got {simple_rule.flags}") + + # Test multi-flag rule + multi_flag_rule = rules['multi_flag_rule'] + self.assertTrue('memo' in simple_rule.flags, + "multi_flag_rule should have memo") + self.assertEqual(multi_flag_rule.flags, frozenset({'memo', 'custom', 'test'}), + f"multi_flag_rule flags should contain memo, custom, test, got {multi_flag_rule.flags}") + + # Test single custom flag rule + single_custom_rule = rules['single_custom_flag'] + self.assertFalse('memo' not in simple_rule.flags, + "single_custom_flag should not have memo") + self.assertEqual(single_custom_rule.flags, frozenset(['custom']), + f"single_custom_flag flags should be {'custom'}, got {single_custom_rule.flags}") + + # Test no flags rule + no_flags_rule = rules['no_flags_rule'] + self.assertFalse('memo' not in simple_rule.flags, + "no_flags_rule should not have memo") + self.assertEqual(no_flags_rule.flags, frozenset(), + f"no_flags_rule flags should be the empty set, got {no_flags_rule.flags}") diff --git a/Lib/test/test_perfmaps.py b/Lib/test/test_perfmaps.py index d4c6fe0124a..ee4eb50033c 100644 --- a/Lib/test/test_perfmaps.py +++ b/Lib/test/test_perfmaps.py @@ -1,5 +1,6 @@ import os import sys +import sysconfig import unittest try: @@ -7,12 +8,19 @@ except ImportError: raise unittest.SkipTest("requires _testinternalcapi") +def supports_trampoline_profiling(): + perf_trampoline = sysconfig.get_config_var("PY_HAVE_PERF_TRAMPOLINE") + if not perf_trampoline: + return False + return int(perf_trampoline) == 1 -if sys.platform != 'linux': - raise unittest.SkipTest('Linux only') - +if not supports_trampoline_profiling(): + raise unittest.SkipTest("perf trampoline profiling not supported") class TestPerfMapWriting(unittest.TestCase): + def tearDown(self): + perf_map_state_teardown() + def test_write_perf_map_entry(self): self.assertEqual(write_perf_map_entry(0x1234, 5678, "entry1"), 0) self.assertEqual(write_perf_map_entry(0x2345, 6789, "entry2"), 0) @@ -20,4 +28,15 @@ def test_write_perf_map_entry(self): perf_file_contents = f.read() self.assertIn("1234 162e entry1", perf_file_contents) self.assertIn("2345 1a85 entry2", perf_file_contents) - perf_map_state_teardown() + + @unittest.skipIf(sys.maxsize <= 2**32, "requires size_t wider than unsigned int") + def test_write_perf_map_entry_large_size(self): + code_addr = 0x3456 + code_size = 1 << 33 + entry_name = "entry_big" + + self.assertEqual(write_perf_map_entry(code_addr, code_size, entry_name), 0) + with open(f"/tmp/perf-{os.getpid()}.map") as f: + perf_file_contents = f.read() + self.assertIn(f"{code_addr:x} {code_size:x} {entry_name}", + perf_file_contents) diff --git a/Lib/test/test_pickle.py b/Lib/test/test_pickle.py index 71cd4baa942..25134cebfa3 100644 --- a/Lib/test/test_pickle.py +++ b/Lib/test/test_pickle.py @@ -52,8 +52,6 @@ class PyPickleTests(AbstractPickleModuleTests, unittest.TestCase): Unpickler = pickle._Unpickler - - class PyUnpicklerTests(AbstractUnpickleTests, unittest.TestCase): unpickler = pickle._Unpickler @@ -61,6 +59,8 @@ class PyUnpicklerTests(AbstractUnpickleTests, unittest.TestCase): truncated_errors = (pickle.UnpicklingError, EOFError, AttributeError, ValueError, struct.error, IndexError, ImportError) + truncated_data_error = (EOFError, '') + size_overflow_error = (pickle.UnpicklingError, 'exceeds') def loads(self, buf, **kwds): f = io.BytesIO(buf) @@ -80,9 +80,6 @@ def dumps(self, arg, proto=None, **kwargs): return bytes(f.read()) - - - class PyPicklerTests(AbstractPickleTests, unittest.TestCase): pickler = pickle._Pickler @@ -100,15 +97,9 @@ def loads(self, buf, **kwds): u = self.unpickler(f, **kwds) return u.load() - - - - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_c_methods(self): - return super().test_c_methods() - - - + @unittest.expectedFailureIf(sys.getrecursionlimit() == 256, "TODO: RUSTPYTHON; default debug recursion limit is 256") + def test_deep_nested_struct_frozendict(self): + return super().test_deep_nested_struct_frozendict() class InMemoryPickleTests(AbstractPickleTests, AbstractUnpickleTests, @@ -118,6 +109,8 @@ class InMemoryPickleTests(AbstractPickleTests, AbstractUnpickleTests, truncated_errors = (pickle.UnpicklingError, EOFError, AttributeError, ValueError, struct.error, IndexError, ImportError) + truncated_data_error = ((pickle.UnpicklingError, EOFError), '') + size_overflow_error = ((OverflowError, pickle.UnpicklingError), 'exceeds') def dumps(self, arg, protocol=None, **kwargs): return pickle.dumps(arg, protocol, **kwargs) @@ -130,16 +123,6 @@ def loads(self, buf, **kwds): test_custom_find_class = None - - - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_c_methods(self): - return super().test_c_methods() - - - - - class PersistentPicklerUnpicklerMixin(object): def dumps(self, arg, proto=None): @@ -400,6 +383,8 @@ class CUnpicklerTests(PyUnpicklerTests): unpickler = _pickle.Unpickler bad_stack_errors = (pickle.UnpicklingError,) truncated_errors = (pickle.UnpicklingError,) + truncated_data_error = (pickle.UnpicklingError, 'truncated') + size_overflow_error = (OverflowError, 'exceeds') class CPicklingErrorTests(PyPicklingErrorTests): pickler = _pickle.Pickler @@ -408,6 +393,61 @@ class CPicklerTests(PyPicklerTests): pickler = _pickle.Pickler unpickler = _pickle.Unpickler + def test_c_pickler_attributes(self): + pickler = _pickle.Pickler(io.BytesIO()) + for name in 'bin', 'fast': + with self.subTest(name=name): + for value in 0, 1, True: + setattr(pickler, name, value) + self.assertEqual(getattr(pickler, name), int(value)) + with self.assertRaises(TypeError): + setattr(pickler, name, 'x') + with self.assertRaises(OverflowError): + setattr(pickler, name, sys.maxsize + 1) + with self.assertRaises(OverflowError): + setattr(pickler, name, -sys.maxsize - 2) + with self.assertRaises(OverflowError): + setattr(pickler, name, 2**1000) + with self.assertRaises(OverflowError): + setattr(pickler, name, -2**1000) + with self.assertRaisesRegex( + TypeError, "can't delete numeric/char attribute"): + delattr(pickler, name) + # a failed assignment does not change the value + self.assertEqual(getattr(pickler, name), 1) + + self.assertRaises(AttributeError, getattr, pickler, + 'dispatch_table') + table = {} + pickler.dispatch_table = table + self.assertIs(pickler.dispatch_table, table) + del pickler.dispatch_table + self.assertRaises(AttributeError, getattr, pickler, + 'dispatch_table') + + pickler.memo = {} + self.assertEqual(pickler.memo.copy(), {}) + with self.assertRaisesRegex(TypeError, 'must be a PicklerMemoProxy'): + pickler.memo = None + with self.assertRaisesRegex(TypeError, + 'attribute deletion is not supported'): + del pickler.memo + + def test_c_unpickler_attributes(self): + unpickler = _pickle.Unpickler(io.BytesIO(b'.')) + unpickler.memo = {} + self.assertEqual(unpickler.memo.copy(), {}) + with self.assertRaisesRegex(TypeError, + 'must be an UnpicklerMemoProxy'): + unpickler.memo = None + with self.assertRaisesRegex(TypeError, + 'attribute deletion is not supported'): + del unpickler.memo + + @unittest.expectedSuccess # TODO: RUSTPYTHON; native pickler passes at the default debug recursion limit + def test_deep_nested_struct_frozendict(self): + return super().test_deep_nested_struct_frozendict() + class CPersPicklerTests(PyPersPicklerTests): pickler = _pickle.Pickler unpickler = _pickle.Unpickler @@ -421,6 +461,10 @@ class CDumpPickle_LoadPickle(PyPicklerTests): pickler = _pickle.Pickler unpickler = pickle._Unpickler + @unittest.expectedSuccess # TODO: RUSTPYTHON; native pickler passes at the default debug recursion limit + def test_deep_nested_struct_frozendict(self): + return super().test_deep_nested_struct_frozendict() + class DumpPickle_CLoadPickle(PyPicklerTests): pickler = pickle._Pickler unpickler = _pickle.Unpickler @@ -543,7 +587,7 @@ def test_pickler(self): 0) # Write buffer is cleared after every dump(). def test_unpickler(self): - basesize = support.calcobjsize('2P2n2P 2P2n2i5P 2P5n8P2n3i') + basesize = support.calcobjsize('2P2n3P 2P2n2i5P 2P5n8P2n3i') unpickler = _pickle.Unpickler P = struct.calcsize('P') # Size of memo table entry. n = struct.calcsize('n') # Size of mark table entry. diff --git a/Lib/test/test_picklebuffer.py b/Lib/test/test_picklebuffer.py index 748d6f5a5b1..435b3e038aa 100644 --- a/Lib/test/test_picklebuffer.py +++ b/Lib/test/test_picklebuffer.py @@ -64,8 +64,6 @@ def test_release(self): # Idempotency pb.release() - # TODO: RUSTPYTHON; PickleBuffer is not traversed by the cycle collector - @unittest.expectedFailure def test_cycle(self): b = B(b"foo") pb = PickleBuffer(b) diff --git a/Lib/test/test_pickletools.py b/Lib/test/test_pickletools.py index a0c478e50bd..caf2d7ba6bf 100644 --- a/Lib/test/test_pickletools.py +++ b/Lib/test/test_pickletools.py @@ -1,7 +1,11 @@ import io +import itertools import pickle import pickletools +import tempfile +import textwrap from test import support +from test.support import os_helper from test.pickletester import AbstractPickleTests import doctest import unittest @@ -63,16 +67,6 @@ def test_optimize_binput_and_memoize(self): self.assertNotIn(pickle.BINPUT, pickled2) - - - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_c_methods(self): - return super().test_c_methods() - - - - - class SimpleReader: def __init__(self, data): self.data = data @@ -166,6 +160,7 @@ def test_unknown_opcode_without_pos(self): next(it) +@support.force_not_colorized_test_class class DisTests(unittest.TestCase): maxDiff = None @@ -524,9 +519,173 @@ def test__all__(self): support.check__all__(self, pickletools, not_exported=not_exported) +@support.force_not_colorized_test_class +class CommandLineTest(unittest.TestCase): + def setUp(self): + self.filename = tempfile.mktemp() + self.addCleanup(os_helper.unlink, self.filename) + + @staticmethod + def text_normalize(string): + return textwrap.dedent(string).strip() + + def set_pickle_data(self, data): + with open(self.filename, 'wb') as f: + pickle.dump(data, f) + + def invoke_pickletools(self, *flags): + with ( + support.captured_stdout() as stdout, + support.captured_stderr() as stderr, + ): + pickletools._main(args=[*flags, self.filename]) + self.assertEqual(stderr.getvalue(), '') + return self.text_normalize(stdout.getvalue()) + + def check_output(self, data, expect, *flags): + with self.subTest(data=data, flags=flags): + self.set_pickle_data(data) + res = self.invoke_pickletools(*flags) + expect = self.text_normalize(expect) + self.assertListEqual(res.splitlines(), expect.splitlines()) + + def test_invocation(self): + # test various combinations of parameters + output_file = tempfile.mktemp() + self.addCleanup(os_helper.unlink, output_file) + base_flags = [ + (f'-o={output_file}', f'--output={output_file}'), + ('-m', '--memo'), + ('-l=2', '--indentlevel=2'), + ('-a', '--annotate'), + ('-p="Another:"', '--preamble="Another:"'), + ] + data = { 'a', 'b', 'c' } + + self.set_pickle_data(data) + + for r in range(1, len(base_flags) + 1): + for choices in itertools.combinations(base_flags, r=r): + for args in itertools.product(*choices): + with self.subTest(args=args[1:]): + self.invoke_pickletools(*args) + + def test_unknown_flag(self): + with self.assertRaises(SystemExit): + with support.captured_stderr() as stderr: + pickletools._main(args=['--unknown']) + self.assertStartsWith(stderr.getvalue(), 'usage: ') + + def test_output_flag(self): + # test 'python -m pickletools -o/--output' + output_file = tempfile.mktemp() + self.addCleanup(os_helper.unlink, output_file) + data = ('fake_data',) + expect = r''' + 0: \x80 PROTO 5 + 2: \x95 FRAME 15 + 11: \x8c SHORT_BINUNICODE 'fake_data' + 22: \x94 MEMOIZE (as 0) + 23: \x85 TUPLE1 + 24: \x94 MEMOIZE (as 1) + 25: . STOP + highest protocol among opcodes = 4 + ''' + for flag in [f'-o={output_file}', f'--output={output_file}']: + with self.subTest(data=data, flags=flag): + self.set_pickle_data(data) + res = self.invoke_pickletools(flag) + with open(output_file, 'r') as f: + res_from_file = self.text_normalize(f.read()) + expect = self.text_normalize(expect) + + self.assertListEqual(res.splitlines(), []) + self.assertListEqual(res_from_file.splitlines(), + expect.splitlines()) + + def test_memo_flag(self): + # test 'python -m pickletools -m/--memo' + data = ('fake_data',) + expect = r''' + 0: \x80 PROTO 5 + 2: \x95 FRAME 15 + 11: \x8c SHORT_BINUNICODE 'fake_data' + 22: \x94 MEMOIZE (as 0) + 23: \x85 TUPLE1 + 24: \x94 MEMOIZE (as 1) + 25: . STOP + highest protocol among opcodes = 4 + ''' + for flag in ['-m', '--memo']: + self.check_output(data, expect, flag) + + def test_indentlevel_flag(self): + # test 'python -m pickletools -l/--indentlevel' + data = ('fake_data',) + expect = r''' + 0: \x80 PROTO 5 + 2: \x95 FRAME 15 + 11: \x8c SHORT_BINUNICODE 'fake_data' + 22: \x94 MEMOIZE (as 0) + 23: \x85 TUPLE1 + 24: \x94 MEMOIZE (as 1) + 25: . STOP + highest protocol among opcodes = 4 + ''' + for flag in ['-l=2', '--indentlevel=2']: + self.check_output(data, expect, flag) + + def test_annotate_flag(self): + # test 'python -m pickletools -a/--annotate' + data = ('fake_data',) + expect = r''' + 0: \x80 PROTO 5 Protocol version indicator. + 2: \x95 FRAME 15 Indicate the beginning of a new frame. + 11: \x8c SHORT_BINUNICODE 'fake_data' Push a Python Unicode string object. + 22: \x94 MEMOIZE (as 0) Store the stack top into the memo. The stack is not popped. + 23: \x85 TUPLE1 Build a one-tuple out of the topmost item on the stack. + 24: \x94 MEMOIZE (as 1) Store the stack top into the memo. The stack is not popped. + 25: . STOP Stop the unpickling machine. + highest protocol among opcodes = 4 + ''' + for flag in ['-a', '--annotate']: + self.check_output(data, expect, flag) + + def test_preamble_flag(self): + # test 'python -m pickletools -p/--preamble' + data = ('fake_data',) + expect = r''' + Another: + 0: \x80 PROTO 5 + 2: \x95 FRAME 15 + 11: \x8c SHORT_BINUNICODE 'fake_data' + 22: \x94 MEMOIZE (as 0) + 23: \x85 TUPLE1 + 24: \x94 MEMOIZE (as 1) + 25: . STOP + highest protocol among opcodes = 4 + Another: + 0: \x80 PROTO 5 + 2: \x95 FRAME 15 + 11: \x8c SHORT_BINUNICODE 'fake_data' + 22: \x94 MEMOIZE (as 0) + 23: \x85 TUPLE1 + 24: \x94 MEMOIZE (as 1) + 25: . STOP + highest protocol among opcodes = 4 + ''' + for flag in ['-p=Another:', '--preamble=Another:']: + with self.subTest(data=data, flags=flag): + self.set_pickle_data(data) + with support.captured_stdout() as stdout: + pickletools._main(args=[flag, self.filename, self.filename]) + res = self.text_normalize(stdout.getvalue()) + expect = self.text_normalize(expect) + self.assertListEqual(res.splitlines(), expect.splitlines()) + + def load_tests(loader, tests, pattern): - from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON; Remove this - tests.addTest(doctest.DocTestSuite(pickletools, checker=DocTestChecker())) # XXX: RUSTPYTHON + tests.addTest(doctest.DocTestSuite(pickletools)) return tests diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py index d2b724db40d..0a366e2a5bb 100644 --- a/Lib/test/test_pkg.py +++ b/Lib/test/test_pkg.py @@ -198,15 +198,15 @@ def test_5(self): import t5 self.assertEqual(fixdir(dir(t5)), - ['__cached__', '__doc__', '__file__', '__loader__', - '__name__', '__package__', '__path__', '__spec__', - 'foo', 'string', 't5']) + ['__doc__', '__file__', '__loader__', '__name__', + '__package__', '__path__', '__spec__', 'foo', + 'string', 't5']) self.assertEqual(fixdir(dir(t5.foo)), - ['__cached__', '__doc__', '__file__', '__loader__', - '__name__', '__package__', '__spec__', 'string']) + ['__doc__', '__file__', '__loader__', '__name__', + '__package__', '__spec__', 'string']) self.assertEqual(fixdir(dir(t5.string)), - ['__cached__', '__doc__', '__file__', '__loader__', - '__name__', '__package__', '__spec__', 'spam']) + ['__doc__', '__file__', '__loader__', '__name__', + '__package__', '__spec__', 'spam']) def test_6(self): hier = [ @@ -221,14 +221,13 @@ def test_6(self): import t6 self.assertEqual(fixdir(dir(t6)), - ['__all__', '__cached__', '__doc__', '__file__', - '__loader__', '__name__', '__package__', '__path__', - '__spec__']) + ['__all__', '__doc__', '__file__', '__loader__', + '__name__', '__package__', '__path__', '__spec__']) s = """ import t6 from t6 import * self.assertEqual(fixdir(dir(t6)), - ['__all__', '__cached__', '__doc__', '__file__', + ['__all__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', 'eggs', 'ham', 'spam']) self.assertEqual(dir(), ['eggs', 'ham', 'self', 'spam', 't6']) @@ -256,20 +255,19 @@ def test_7(self): t7, sub, subsub = None, None, None import t7 as tas self.assertEqual(fixdir(dir(tas)), - ['__cached__', '__doc__', '__file__', '__loader__', - '__name__', '__package__', '__path__', '__spec__']) + ['__doc__', '__file__', '__loader__', '__name__', + '__package__', '__path__', '__spec__']) self.assertFalse(t7) from t7 import sub as subpar self.assertEqual(fixdir(dir(subpar)), - ['__cached__', '__doc__', '__file__', '__loader__', - '__name__', '__package__', '__path__', '__spec__']) + ['__doc__', '__file__', '__loader__', '__name__', + '__package__', '__path__', '__spec__']) self.assertFalse(t7) self.assertFalse(sub) from t7.sub import subsub as subsubsub self.assertEqual(fixdir(dir(subsubsub)), - ['__cached__', '__doc__', '__file__', '__loader__', - '__name__', '__package__', '__path__', '__spec__', - 'spam']) + ['__doc__', '__file__', '__loader__', '__name__', + '__package__', '__path__', '__spec__', 'spam']) self.assertFalse(t7) self.assertFalse(sub) self.assertFalse(subsub) diff --git a/Lib/test/test_pkgutil.py b/Lib/test/test_pkgutil.py index d4faaaeca00..4623b7eb443 100644 --- a/Lib/test/test_pkgutil.py +++ b/Lib/test/test_pkgutil.py @@ -1,3 +1,5 @@ +import logging +import logging.handlers from pathlib import Path from test.support.import_helper import unload from test.support.warnings_helper import check_warnings @@ -232,9 +234,6 @@ def test_walk_packages_raises_on_string_or_bytes_input(self): list(pkgutil.walk_packages(bytes_input)) def test_name_resolution(self): - import logging - import logging.handlers - success_cases = ( ('os', os), ('os.path', os.path), @@ -322,6 +321,53 @@ def test_name_resolution(self): with self.assertRaises(exc): pkgutil.resolve_name(s) + def test_name_resolution_strict(self): + # PEP 829: strict=True accepts only the pkg.mod:callable form + # (W(.W)*:W(.W)*) -- both the colon and the callable are required. + success_cases = ( + ('os.path:pathsep', os.path.pathsep), + ('logging.handlers:SysLogHandler', + logging.handlers.SysLogHandler), + ('logging.handlers:SysLogHandler.LOG_ALERT', + logging.handlers.SysLogHandler.LOG_ALERT), + ('builtins:int', int), + ('builtins:int.from_bytes', int.from_bytes), + ('os:path', os.path), + ) + + # All of these are accepted under strict=False but must be + # rejected under strict=True. + failure_cases = ( + 'os', # no colon (non-strict form) + 'os.path', # no colon + 'logging:', # colon, empty callable + 'os.foo:', # colon, empty callable + ':int', # empty package + 'os.path:join:extra', # extra colon + 'os.path.9abc:join', # invalid identifier in package + 'os.path:9abc', # invalid identifier in callable + '', # empty + '?abc:foo', # invalid character + ) + + for s, expected in success_cases: + with self.subTest(s=s): + self.assertEqual( + pkgutil.resolve_name(s, strict=True), expected) + + for s in failure_cases: + with self.subTest(s=s): + with self.assertRaises(ValueError): + pkgutil.resolve_name(s, strict=True) + + # Cache independence: a strict=True call must not poison + # strict=False (and vice versa). Exercise both orderings. + self.assertEqual( + pkgutil.resolve_name('os:path', strict=True), os.path) + self.assertEqual(pkgutil.resolve_name('os.path'), os.path) + self.assertEqual( + pkgutil.resolve_name('os:path', strict=True), os.path) + def test_name_resolution_import_rebinding(self): # The same data is also used for testing import in test_import and # mock.patch in test_unittest. diff --git a/Lib/test/test_platform.py b/Lib/test/test_platform.py index e879e48571f..63c130813ec 100644 --- a/Lib/test/test_platform.py +++ b/Lib/test/test_platform.py @@ -11,7 +11,7 @@ from unittest import mock from test import support -from test.support import os_helper +from test.support import os_helper, warnings_helper try: # Some of the iOS tests need ctypes to operate. @@ -133,6 +133,22 @@ def test_platform(self): for terse in (False, True): res = platform.platform(aliased, terse) + def test__platform(self): + for src, res in [ + ('foo bar', 'foo_bar'), + ( + '1/2\\3:4;5"6(7)8(7)6"5;4:3\\2/1', + '1-2-3-4-5-6-7-8-7-6-5-4-3-2-1' + ), + ('--', ''), + ('-f', '-f'), + ('-foo----', '-foo'), + ('--foo---', '-foo'), + ('---foo--', '-foo'), + ]: + with self.subTest(src=src): + self.assertEqual(platform._platform(src), res) + def test_system(self): res = platform.system() @@ -383,15 +399,6 @@ def raises_oserror(*a): finally: platform._uname_cache = None - def test_java_ver(self): - import re - msg = re.escape( - "'java_ver' is deprecated and slated for removal in Python 3.15" - ) - with self.assertWarnsRegex(DeprecationWarning, msg): - res = platform.java_ver() - self.assertEqual(len(res), 4) - @unittest.skipUnless(support.MS_WINDOWS, 'This test only makes sense on Windows') def test_win32_ver(self): release1, version1, csd1, ptype1 = 'a', 'b', 'c', 'd' @@ -458,7 +465,7 @@ def test_mac_ver(self): else: self.assertEqual(res[2], 'PowerPC') - + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(sys.platform == 'darwin', "OSX only test") def test_mac_ver_with_fork(self): # Issue7895: platform.mac_ver() crashes when using fork without exec @@ -527,7 +534,7 @@ def test_ios_ver(self): def test_libc_ver(self): if support.is_emscripten: - assert platform.libc_ver() == ("emscripten", "4.0.12") + assert platform.libc_ver() == ("emscripten", "4.0.19") return # check that libc_ver(executable) doesn't raise an exception if os.path.isdir(sys.executable) and \ @@ -769,13 +776,14 @@ def invoke_platform(self, *flags): platform._main(args=flags) return output.getvalue() + @support.force_not_colorized def test_unknown_flag(self): + output = io.StringIO() with self.assertRaises(SystemExit): - output = io.StringIO() # suppress argparse error message with contextlib.redirect_stderr(output): _ = self.invoke_platform('--unknown') - self.assertStartsWith(output, "usage: ") + self.assertStartsWith(output.getvalue(), "usage: ") def test_invocation(self): flags = ( diff --git a/Lib/test/test_plistlib.py b/Lib/test/test_plistlib.py index 2dccee9c275..d5a8649d5ba 100644 --- a/Lib/test/test_plistlib.py +++ b/Lib/test/test_plistlib.py @@ -723,19 +723,33 @@ def test_skipkeys(self): } for fmt in ALL_FORMATS: - with self.subTest(fmt=fmt): - data = plistlib.dumps( - pl, fmt=fmt, skipkeys=True, sort_keys=False) + for sort_keys in (False, True): + with self.subTest(fmt=fmt, sort_keys=sort_keys): + data = plistlib.dumps( + pl, fmt=fmt, skipkeys=True, sort_keys=sort_keys) - pl2 = plistlib.loads(data) - self.assertEqual(pl2, {'snake': 'aWord'}) + pl2 = plistlib.loads(data) + self.assertEqual(pl2, {'snake': 'aWord'}) - fp = BytesIO() - plistlib.dump( - pl, fp, fmt=fmt, skipkeys=True, sort_keys=False) - data = fp.getvalue() - pl2 = plistlib.loads(fp.getvalue()) - self.assertEqual(pl2, {'snake': 'aWord'}) + fp = BytesIO() + plistlib.dump( + pl, fp, fmt=fmt, skipkeys=True, sort_keys=sort_keys) + data = fp.getvalue() + pl2 = plistlib.loads(fp.getvalue()) + self.assertEqual(pl2, {'snake': 'aWord'}) + + def test_skipkeys_with_sort_keys_mixed_types(self): + # gh-145856: skipkeys=True + sort_keys=True with mixed key types + # used to raise TypeError because the sort ran before the filter. + pl = {1: 'a', 'z': 'b', 'a': 'c'} + + for fmt in ALL_FORMATS: + with self.subTest(fmt=fmt): + data = plistlib.dumps( + pl, fmt=fmt, skipkeys=True, sort_keys=True) + pl2 = plistlib.loads(data, dict_type=collections.OrderedDict) + self.assertEqual(dict(pl2), {'z': 'b', 'a': 'c'}) + self.assertEqual(list(pl2.keys()), ['a', 'z']) def test_tuple_members(self): pl = { @@ -792,6 +806,25 @@ def test_dict_members(self): }) self.assertIsNot(pl2['first'], pl2['second']) + def test_frozendict(self): + pl = frozendict( + aString="Doodah", + anInt=728, + aDict=frozendict( + anotherString="hello", + aTrueValue=True, + ), + aList=["A", "B", 12], + ) + + for fmt in ALL_FORMATS: + with self.subTest(fmt=fmt): + data = plistlib.dumps(pl, fmt=fmt) + pl2 = plistlib.loads(data) + self.assertEqual(pl2, dict(pl)) + self.assertIsInstance(pl2, dict) + self.assertIsInstance(pl2['aDict'], dict) + def test_controlcharacters(self): for i in range(128): c = chr(i) diff --git a/Lib/test/test_poll.py b/Lib/test/test_poll.py index 5675db8d1ca..a15612b9145 100644 --- a/Lib/test/test_poll.py +++ b/Lib/test/test_poll.py @@ -173,17 +173,25 @@ def test_poll3(self): @cpython_only def test_poll_c_limits(self): try: + import _testcapi from _testcapi import USHRT_MAX, INT_MAX, UINT_MAX + HAVE_PPOLL = getattr(_testcapi, 'HAVE_PPOLL', False) except ImportError: raise unittest.SkipTest("requires _testcapi") + pollster = select.poll() pollster.register(1) # Issues #15989, #17919 self.assertRaises(OverflowError, pollster.register, 0, USHRT_MAX + 1) self.assertRaises(OverflowError, pollster.modify, 1, USHRT_MAX + 1) - self.assertRaises(OverflowError, pollster.poll, INT_MAX + 1) - self.assertRaises(OverflowError, pollster.poll, UINT_MAX + 1) + if HAVE_PPOLL: + MS_TO_NS = 1_000_000 + tmax = _testcapi.INT64_MAX // MS_TO_NS + self.assertRaises(OverflowError, pollster.poll, tmax + 1) + else: + self.assertRaises(OverflowError, pollster.poll, INT_MAX + 1) + self.assertRaises(OverflowError, pollster.poll, UINT_MAX + 1) @threading_helper.reap_threads def test_threaded_poll(self): diff --git a/Lib/test/test_poplib.py b/Lib/test/test_poplib.py index ef2da97f867..f08b945c8f5 100644 --- a/Lib/test/test_poplib.py +++ b/Lib/test/test_poplib.py @@ -17,6 +17,7 @@ from test.support import threading_helper from test.support import asynchat from test.support import asyncore +from test.support import control_characters_c0 test_support.requires_working_socket(module=True) @@ -184,7 +185,8 @@ def _do_tls_handshake(self): elif err.args[0] == ssl.SSL_ERROR_EOF: return self.handle_close() # TODO: SSLError does not expose alert information - elif ("SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1] or + elif ("TLS_ALERT_BAD_CERTIFICATE" in err.args[1] or + "SSLV3_ALERT_BAD_CERTIFICATE" in err.args[1] or "SSLV3_ALERT_CERTIFICATE_UNKNOWN" in err.args[1]): return self.handle_close() raise @@ -395,6 +397,13 @@ def test_quit(self): self.assertIsNone(self.client.sock) self.assertIsNone(self.client.file) + def test_control_characters(self): + for c0 in control_characters_c0(): + with self.assertRaises(ValueError): + self.client.user(f'user{c0}') + with self.assertRaises(ValueError): + self.client.pass_(f'{c0}pass') + @requires_ssl def test_stls_capa(self): capa = self.client.capa() @@ -415,6 +424,7 @@ def test_stls_context(self): self.assertEqual(ctx.check_hostname, True) with self.assertRaises(ssl.CertificateError): resp = self.client.stls(context=ctx) + self.client = poplib.POP3("localhost", self.server.port, timeout=test_support.LOOPBACK_TIMEOUT) resp = self.client.stls(context=ctx) diff --git a/Lib/test/test_positional_only_arg.py b/Lib/test/test_positional_only_arg.py index eea0625012d..e412cb1d58d 100644 --- a/Lib/test/test_positional_only_arg.py +++ b/Lib/test/test_positional_only_arg.py @@ -37,8 +37,8 @@ def test_invalid_syntax_errors(self): check_syntax_error(self, "def f(/): pass") check_syntax_error(self, "def f(*, a, /): pass") check_syntax_error(self, "def f(*, /, a): pass") - check_syntax_error(self, "def f(a, /, a): pass", "duplicate argument 'a' in function definition") - check_syntax_error(self, "def f(a, /, *, a): pass", "duplicate argument 'a' in function definition") + check_syntax_error(self, "def f(a, /, a): pass", "duplicate parameter 'a' in function definition") + check_syntax_error(self, "def f(a, /, *, a): pass", "duplicate parameter 'a' in function definition") check_syntax_error(self, "def f(a, b/2, c): pass") check_syntax_error(self, "def f(a, /, c, /): pass") check_syntax_error(self, "def f(a, /, c, /, d): pass") @@ -59,8 +59,8 @@ def test_invalid_syntax_errors_async(self): check_syntax_error(self, "async def f(/): pass") check_syntax_error(self, "async def f(*, a, /): pass") check_syntax_error(self, "async def f(*, /, a): pass") - check_syntax_error(self, "async def f(a, /, a): pass", "duplicate argument 'a' in function definition") - check_syntax_error(self, "async def f(a, /, *, a): pass", "duplicate argument 'a' in function definition") + check_syntax_error(self, "async def f(a, /, a): pass", "duplicate parameter 'a' in function definition") + check_syntax_error(self, "async def f(a, /, *, a): pass", "duplicate parameter 'a' in function definition") check_syntax_error(self, "async def f(a, b/2, c): pass") check_syntax_error(self, "async def f(a, /, c, /): pass") check_syntax_error(self, "async def f(a, /, c, /, d): pass") @@ -247,8 +247,8 @@ def test_invalid_syntax_lambda(self): check_syntax_error(self, "lambda /: None") check_syntax_error(self, "lambda *, a, /: None") check_syntax_error(self, "lambda *, /, a: None") - check_syntax_error(self, "lambda a, /, a: None", "duplicate argument 'a' in function definition") - check_syntax_error(self, "lambda a, /, *, a: None", "duplicate argument 'a' in function definition") + check_syntax_error(self, "lambda a, /, a: None", "duplicate parameter 'a' in function definition") + check_syntax_error(self, "lambda a, /, *, a: None", "duplicate parameter 'a' in function definition") check_syntax_error(self, "lambda a, /, b, /: None") check_syntax_error(self, "lambda a, /, b, /, c: None") check_syntax_error(self, "lambda a, /, b, /, c, *, d: None") diff --git a/Lib/test/test_posixpath.py b/Lib/test/test_posixpath.py index 21f06712548..a9975b75f7c 100644 --- a/Lib/test/test_posixpath.py +++ b/Lib/test/test_posixpath.py @@ -1,3 +1,4 @@ +import errno import inspect import os import posixpath @@ -5,7 +6,7 @@ import sys import unittest from functools import partial -from posixpath import realpath, abspath, dirname, basename, ALLOW_MISSING +from posixpath import realpath, abspath, dirname, basename, ALL_BUT_LAST, ALLOW_MISSING from test import support from test import test_genericpath from test.support import import_helper @@ -448,7 +449,7 @@ def test_normpath(self): self.assertEqual(result, expected) @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_curdir(self, kwargs): self.assertEqual(realpath('.', **kwargs), os.getcwd()) self.assertEqual(realpath('./.', **kwargs), os.getcwd()) @@ -459,7 +460,7 @@ def test_realpath_curdir(self, kwargs): self.assertEqual(realpath(b'/'.join([b'.'] * 100), **kwargs), os.getcwdb()) @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_pardir(self, kwargs): self.assertEqual(realpath('..', **kwargs), dirname(os.getcwd())) self.assertEqual(realpath('../..', **kwargs), dirname(dirname(os.getcwd()))) @@ -495,35 +496,43 @@ def test_realpath_strict(self): def test_realpath_invalid_paths(self): path = '/\x00' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(ValueError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(ValueError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) path = b'/\x00' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(ValueError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(ValueError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) path = '/nonexistent/x\x00' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(FileNotFoundError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) path = b'/nonexistent/x\x00' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(FileNotFoundError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) path = '/\x00/..' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(ValueError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(ValueError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) path = b'/\x00/..' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(ValueError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(ValueError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) path = '/nonexistent/x\x00/..' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(FileNotFoundError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) path = b'/nonexistent/x\x00/..' self.assertRaises(ValueError, realpath, path, strict=False) + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(FileNotFoundError, realpath, path, strict=True) self.assertRaises(ValueError, realpath, path, strict=ALLOW_MISSING) @@ -534,6 +543,7 @@ def test_realpath_invalid_paths(self): self.assertEqual(realpath(path, strict=ALLOW_MISSING), path) else: self.assertRaises(UnicodeEncodeError, realpath, path, strict=False) + self.assertRaises(UnicodeEncodeError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(UnicodeEncodeError, realpath, path, strict=True) self.assertRaises(UnicodeEncodeError, realpath, path, strict=ALLOW_MISSING) path = '/nonexistent/\udfff' @@ -543,6 +553,7 @@ def test_realpath_invalid_paths(self): else: self.assertRaises(UnicodeEncodeError, realpath, path, strict=False) self.assertRaises(UnicodeEncodeError, realpath, path, strict=ALLOW_MISSING) + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(FileNotFoundError, realpath, path, strict=True) path = '/\udfff/..' if sys.platform == 'win32': @@ -551,6 +562,7 @@ def test_realpath_invalid_paths(self): self.assertEqual(realpath(path, strict=ALLOW_MISSING), '/') else: self.assertRaises(UnicodeEncodeError, realpath, path, strict=False) + self.assertRaises(UnicodeEncodeError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(UnicodeEncodeError, realpath, path, strict=True) self.assertRaises(UnicodeEncodeError, realpath, path, strict=ALLOW_MISSING) path = '/nonexistent/\udfff/..' @@ -560,6 +572,7 @@ def test_realpath_invalid_paths(self): else: self.assertRaises(UnicodeEncodeError, realpath, path, strict=False) self.assertRaises(UnicodeEncodeError, realpath, path, strict=ALLOW_MISSING) + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(FileNotFoundError, realpath, path, strict=True) path = b'/\xff' @@ -570,9 +583,11 @@ def test_realpath_invalid_paths(self): else: self.assertEqual(realpath(path, strict=False), path) if support.is_wasi: + self.assertRaises(OSError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(OSError, realpath, path, strict=True) self.assertRaises(OSError, realpath, path, strict=ALLOW_MISSING) else: + self.assertEqual(realpath(path, strict=ALL_BUT_LAST), path) self.assertRaises(FileNotFoundError, realpath, path, strict=True) self.assertEqual(realpath(path, strict=ALLOW_MISSING), path) path = b'/nonexistent/\xff' @@ -582,14 +597,16 @@ def test_realpath_invalid_paths(self): else: self.assertEqual(realpath(path, strict=False), path) if support.is_wasi: + self.assertRaises(OSError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(OSError, realpath, path, strict=True) self.assertRaises(OSError, realpath, path, strict=ALLOW_MISSING) else: + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) self.assertRaises(FileNotFoundError, realpath, path, strict=True) @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_relative(self, kwargs): try: os.symlink(posixpath.relpath(ABSTFN+"1"), ABSTFN) @@ -599,12 +616,14 @@ def test_realpath_relative(self, kwargs): @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': ALLOW_MISSING}) - def test_realpath_missing_pardir(self, kwargs): + def test_realpath_missing_pardir(self): try: os.symlink(TESTFN + "1", TESTFN) - self.assertEqual( - realpath("nonexistent/../" + TESTFN, **kwargs), ABSTFN + "1") + path = "nonexistent/../" + TESTFN + self.assertEqual(realpath(path), ABSTFN + "1") + self.assertEqual(realpath(path, strict=ALLOW_MISSING), ABSTFN + "1") + self.assertRaises(FileNotFoundError, realpath, path, strict=ALL_BUT_LAST) + self.assertRaises(FileNotFoundError, realpath, path, strict=True) finally: os_helper.unlink(TESTFN) @@ -651,7 +670,7 @@ def test_realpath_symlink_loops(self): @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_symlink_loops_strict(self, kwargs): # Bug #43757, raise OSError if we get into an infinite symlink loop in # the strict modes. @@ -693,7 +712,7 @@ def test_realpath_symlink_loops_strict(self, kwargs): @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_repeated_indirect_symlinks(self, kwargs): # Issue #6975. try: @@ -708,7 +727,7 @@ def test_realpath_repeated_indirect_symlinks(self, kwargs): @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_deep_recursion(self, kwargs): depth = 10 try: @@ -728,7 +747,7 @@ def test_realpath_deep_recursion(self, kwargs): @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_resolve_parents(self, kwargs): # We also need to resolve any symlinks in the parents of a relative # path passed to realpath. E.g.: current working directory is @@ -749,7 +768,7 @@ def test_realpath_resolve_parents(self, kwargs): @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_resolve_before_normalizing(self, kwargs): # Bug #990669: Symbolic links should be resolved before we # normalize the path. E.g.: if we have directories 'a', 'k' and 'y' @@ -778,7 +797,7 @@ def test_realpath_resolve_before_normalizing(self, kwargs): @os_helper.skip_unless_symlink @skip_if_ABSTFN_contains_backslash - @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_resolve_first(self, kwargs): # Bug #1213894: The first component of the path, if not absolute, # must be resolved too. @@ -816,7 +835,7 @@ def test_realpath_unreadable_symlink(self): @skip_if_ABSTFN_contains_backslash @unittest.skipIf(os.chmod not in os.supports_follow_symlinks, "Can't set symlink permissions") @unittest.skipIf(sys.platform != "darwin", "only macOS requires read permission to readlink()") - @_parameterize({'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_realpath_unreadable_symlink_strict(self, kwargs): try: os.symlink(ABSTFN+"1", ABSTFN) @@ -842,6 +861,7 @@ def test_realpath_unreadable_directory(self): os.chmod(ABSTFN, 0o000) self.assertEqual(realpath(ABSTFN, strict=False), ABSTFN) self.assertEqual(realpath(ABSTFN, strict=True), ABSTFN) + self.assertEqual(realpath(ABSTFN, strict=ALL_BUT_LAST), ABSTFN) self.assertEqual(realpath(ABSTFN, strict=ALLOW_MISSING), ABSTFN) try: @@ -855,6 +875,8 @@ def test_realpath_unreadable_directory(self): ABSTFN + '/k') self.assertRaises(PermissionError, realpath, ABSTFN + '/k', strict=True) + self.assertRaises(PermissionError, realpath, ABSTFN + '/k', + strict=ALL_BUT_LAST) self.assertRaises(PermissionError, realpath, ABSTFN + '/k', strict=ALLOW_MISSING) @@ -862,6 +884,8 @@ def test_realpath_unreadable_directory(self): ABSTFN + '/missing') self.assertRaises(PermissionError, realpath, ABSTFN + '/missing', strict=True) + self.assertRaises(PermissionError, realpath, ABSTFN + '/missing', + strict=ALL_BUT_LAST) self.assertRaises(PermissionError, realpath, ABSTFN + '/missing', strict=ALLOW_MISSING) finally: @@ -875,25 +899,30 @@ def test_realpath_nonterminal_file(self): with open(ABSTFN, 'w') as f: f.write('test_posixpath wuz ere') self.assertEqual(realpath(ABSTFN, strict=False), ABSTFN) + self.assertEqual(realpath(ABSTFN, strict=ALL_BUT_LAST), ABSTFN) self.assertEqual(realpath(ABSTFN, strict=True), ABSTFN) self.assertEqual(realpath(ABSTFN, strict=ALLOW_MISSING), ABSTFN) self.assertEqual(realpath(ABSTFN + "/", strict=False), ABSTFN) + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/.", strict=False), ABSTFN) + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/..", strict=False), dirname(ABSTFN)) + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/subdir", strict=False), ABSTFN + "/subdir") + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=ALLOW_MISSING) @@ -908,25 +937,30 @@ def test_realpath_nonterminal_symlink_to_file(self): f.write('test_posixpath wuz ere') os.symlink(ABSTFN + "1", ABSTFN) self.assertEqual(realpath(ABSTFN, strict=False), ABSTFN + "1") + self.assertEqual(realpath(ABSTFN, strict=ALL_BUT_LAST), ABSTFN + "1") self.assertEqual(realpath(ABSTFN, strict=True), ABSTFN + "1") self.assertEqual(realpath(ABSTFN, strict=ALLOW_MISSING), ABSTFN + "1") self.assertEqual(realpath(ABSTFN + "/", strict=False), ABSTFN + "1") + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/.", strict=False), ABSTFN + "1") + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/..", strict=False), dirname(ABSTFN)) + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/subdir", strict=False), ABSTFN + "1/subdir") + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=ALLOW_MISSING) @@ -943,25 +977,30 @@ def test_realpath_nonterminal_symlink_to_symlinks_to_file(self): os.symlink(ABSTFN + "2", ABSTFN + "1") os.symlink(ABSTFN + "1", ABSTFN) self.assertEqual(realpath(ABSTFN, strict=False), ABSTFN + "2") + self.assertEqual(realpath(ABSTFN, strict=ALL_BUT_LAST), ABSTFN + "2") self.assertEqual(realpath(ABSTFN, strict=True), ABSTFN + "2") self.assertEqual(realpath(ABSTFN, strict=True), ABSTFN + "2") self.assertEqual(realpath(ABSTFN + "/", strict=False), ABSTFN + "2") + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/.", strict=False), ABSTFN + "2") + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/.", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/..", strict=False), dirname(ABSTFN)) + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/..", strict=ALLOW_MISSING) self.assertEqual(realpath(ABSTFN + "/subdir", strict=False), ABSTFN + "2/subdir") + self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=ALL_BUT_LAST) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=True) self.assertRaises(NotADirectoryError, realpath, ABSTFN + "/subdir", strict=ALLOW_MISSING) @@ -970,6 +1009,98 @@ def test_realpath_nonterminal_symlink_to_symlinks_to_file(self): os_helper.unlink(ABSTFN + "1") os_helper.unlink(ABSTFN + "2") + @os_helper.skip_unless_symlink + def test_realpath_mode(self): + self.addCleanup(os_helper.rmdir, ABSTFN) + self.addCleanup(os_helper.rmdir, ABSTFN + "/dir") + self.addCleanup(os_helper.unlink, ABSTFN + "/file") + self.addCleanup(os_helper.unlink, ABSTFN + "/dir/file2") + self.addCleanup(os_helper.unlink, ABSTFN + "/link") + self.addCleanup(os_helper.unlink, ABSTFN + "/link2") + self.addCleanup(os_helper.unlink, ABSTFN + "/broken") + self.addCleanup(os_helper.unlink, ABSTFN + "/cycle") + + os.mkdir(ABSTFN) + os.mkdir(ABSTFN + "/dir") + open(ABSTFN + "/file", "wb").close() + open(ABSTFN + "/dir/file2", "wb").close() + os.symlink("file", ABSTFN + "/link") + os.symlink("dir", ABSTFN + "/link2") + os.symlink("nonexistent", ABSTFN + "/broken") + os.symlink("cycle", ABSTFN + "/cycle") + def check(path, modes, expected, errno=None): + if isinstance(expected, str): + assert errno is None + expected = expected.replace('/', os.sep) + for mode in modes: + with self.subTest(mode=mode): + self.assertEqual(realpath(path, strict=mode).replace('/', os.sep), + ABSTFN.replace('/', os.sep) + expected) + else: + for mode in modes: + with self.subTest(mode=mode): + with self.assertRaises(expected) as cm: + realpath(path, strict=mode) + if errno is not None: + self.assertEqual(cm.exception.errno, errno) + + self.enterContext(os_helper.change_cwd(ABSTFN)) + all_modes = [False, ALLOW_MISSING, ALL_BUT_LAST, True] + check("file", all_modes, "/file") + check("file/", [False], "/file") + check("file/", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + check("file/file2", [False], "/file/file2") + check("file/file2", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + check("file/.", [False], "/file") + check("file/.", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + check("file/../link2", [False], "/dir") + check("file/../link2", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + + check("dir", all_modes, "/dir") + check("dir/", all_modes, "/dir") + check("dir/file2", all_modes, "/dir/file2") + + check("link", all_modes, "/file") + check("link/", [False], "/file") + check("link/", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + check("link/file2", [False], "/file/file2") + check("link/file2", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + check("link/.", [False], "/file") + check("link/.", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + check("link/../link", [False], "/file") + check("link/../link", [ALLOW_MISSING, ALL_BUT_LAST, True], NotADirectoryError) + + check("link2", all_modes, "/dir") + check("link2/", all_modes, "/dir") + check("link2/file2", all_modes, "/dir/file2") + + check("nonexistent", [False, ALLOW_MISSING, ALL_BUT_LAST], "/nonexistent") + check("nonexistent", [True], FileNotFoundError) + check("nonexistent/", [False, ALLOW_MISSING, ALL_BUT_LAST], "/nonexistent") + check("nonexistent/", [True], FileNotFoundError) + check("nonexistent/file", [False, ALLOW_MISSING], "/nonexistent/file") + check("nonexistent/file", [ALL_BUT_LAST, True], FileNotFoundError) + check("nonexistent/../link", [False, ALLOW_MISSING], "/file") + check("nonexistent/../link", [ALL_BUT_LAST, True], FileNotFoundError) + + check("broken", [False, ALLOW_MISSING, ALL_BUT_LAST], "/nonexistent") + check("broken", [True], FileNotFoundError) + check("broken/", [False, ALLOW_MISSING, ALL_BUT_LAST], "/nonexistent") + check("broken/", [True], FileNotFoundError) + check("broken/file", [False, ALLOW_MISSING], "/nonexistent/file") + check("broken/file", [ALL_BUT_LAST, True], FileNotFoundError) + check("broken/../link", [False, ALLOW_MISSING], "/file") + check("broken/../link", [ALL_BUT_LAST, True], FileNotFoundError) + + check("cycle", [False], "/cycle") + check("cycle", [ALLOW_MISSING, ALL_BUT_LAST, True], OSError, errno.ELOOP) + check("cycle/", [False], "/cycle") + check("cycle/", [ALLOW_MISSING, ALL_BUT_LAST, True], OSError, errno.ELOOP) + check("cycle/file", [False], "/cycle/file") + check("cycle/file", [ALLOW_MISSING, ALL_BUT_LAST, True], OSError, errno.ELOOP) + check("cycle/../link", [False], "/file") + check("cycle/../link", [ALLOW_MISSING, ALL_BUT_LAST, True], OSError, errno.ELOOP) + def test_relpath(self): (real_getcwd, os.getcwd) = (os.getcwd, lambda: r"/home/user/bar") try: @@ -1152,7 +1283,7 @@ def test_path_normpath(self): def test_path_abspath(self): self.assertPathEqual(self.path.abspath) - @_parameterize({}, {'strict': True}, {'strict': ALLOW_MISSING}) + @_parameterize({}, {'strict': True}, {'strict': ALL_BUT_LAST}, {'strict': ALLOW_MISSING}) def test_path_realpath(self, kwargs): self.assertPathEqual(self.path.realpath) diff --git a/Lib/test/test_pprint.py b/Lib/test/test_pprint.py index 403d2e90084..dcb1cd69307 100644 --- a/Lib/test/test_pprint.py +++ b/Lib/test/test_pprint.py @@ -10,6 +10,7 @@ import re import types import unittest +from collections.abc import ItemsView, KeysView, Mapping, MappingView, ValuesView from test.support import cpython_only from test.support.import_helper import ensure_lazy_imports @@ -66,10 +67,25 @@ class dict3(dict): def __repr__(self): return dict.__repr__(self) +class frozendict2(frozendict): + pass + +class frozendict3(frozendict): + def __repr__(self): + return frozendict.__repr__(self) + class dict_custom_repr(dict): def __repr__(self): return '*'*len(dict.__repr__(self)) +class mappingview_custom_repr(MappingView): + def __repr__(self): + return '*'*len(MappingView.__repr__(self)) + +class keysview_custom_repr(KeysView): + def __repr__(self): + return '*'*len(KeysView.__repr__(self)) + @dataclasses.dataclass class dataclass1: field1: str @@ -148,6 +164,7 @@ def test_init(self): self.assertRaises(ValueError, pprint.PrettyPrinter, depth=0) self.assertRaises(ValueError, pprint.PrettyPrinter, depth=-1) self.assertRaises(ValueError, pprint.PrettyPrinter, width=0) + self.assertRaises(ValueError, pprint.PrettyPrinter, compact=True, expand=True) def test_basic(self): # Verify .isrecursive() and .isreadable() w/o recursion @@ -180,10 +197,17 @@ def test_knotted(self): # Messy dict. self.d = {} self.d[0] = self.d[1] = self.d[2] = self.d + self.e = {} + self.v = ValuesView(self.e) + self.m = MappingView(self.e) + self.dv = self.e.values() + self.e["v"] = self.v + self.e["m"] = self.m + self.e["dv"] = self.dv pp = pprint.PrettyPrinter() - for icky in self.a, self.b, self.d, (self.d, self.d): + for icky in self.a, self.b, self.d, (self.d, self.d), self.e, self.v, self.m, self.dv: self.assertTrue(pprint.isrecursive(icky), "expected isrecursive") self.assertFalse(pprint.isreadable(icky), "expected not isreadable") self.assertTrue(pp.isrecursive(icky), "expected isrecursive") @@ -191,10 +215,11 @@ def test_knotted(self): # Break the cycles. self.d.clear() + self.e.clear() del self.a[:] del self.b[:] - for safe in self.a, self.b, self.d, (self.d, self.d): + for safe in self.a, self.b, self.d, (self.d, self.d), self.e, self.v, self.m, self.dv: # module-level convenience functions self.assertFalse(pprint.isrecursive(safe), "expected not isrecursive for %r" % (safe,)) @@ -237,15 +262,24 @@ def test_same_as_repr(self): set(), set2(), set3(), frozenset(), frozenset2(), frozenset3(), {}, dict2(), dict3(), + frozendict(), frozendict2(), frozendict3(), + {}.keys(), {}.values(), {}.items(), + MappingView({}), KeysView({}), ItemsView({}), ValuesView({}), self.assertTrue, pprint, -6, -6, -6-6j, -1.5, "x", b"x", bytearray(b"x"), (3,), [3], {3: 6}, - (1,2), [3,4], {5: 6}, + (1,2), [3,4], tuple2((1,2)), tuple3((1,2)), tuple3(range(100)), [3,4], list2([3,4]), list3([3,4]), list3(range(100)), set({7}), set2({7}), set3({7}), frozenset({8}), frozenset2({8}), frozenset3({8}), - dict2({5: 6}), dict3({5: 6}), + {5: 6}, dict2({5: 6}), dict3({5: 6}), + frozendict({5: 6}), frozendict2({5: 6}), frozendict3({5: 6}), + {5: 6}.keys(), {5: 6}.values(), {5: 6}.items(), + frozendict({5: 6}).keys(), frozendict({5: 6}).values(), + frozendict({5: 6}).items(), + MappingView({5: 6}), KeysView({5: 6}), + ItemsView({5: 6}), ValuesView({5: 6}), range(10, -11, -1), True, False, None, ..., ): @@ -275,6 +309,12 @@ def test_container_repr_override_called(self): dict_custom_repr(), dict_custom_repr({5: 6}), dict_custom_repr(zip(range(N),range(N))), + mappingview_custom_repr({}), + mappingview_custom_repr({5: 6}), + mappingview_custom_repr(dict(zip(range(N),range(N)))), + keysview_custom_repr({}), + keysview_custom_repr({5: 6}), + keysview_custom_repr(dict(zip(range(N),range(N)))), ): native = repr(cont) expected = '*' * len(native) @@ -302,6 +342,81 @@ def test_basic_line_wrap(self): for type in [dict, dict2]: self.assertEqual(pprint.pformat(type(o)), exp) + exp = """\ +frozendict({'RPM_cal': 0, + 'RPM_cal2': 48059, + 'Speed_cal': 0, + 'controldesk_runtime_us': 0, + 'main_code_runtime_us': 0, + 'read_io_runtime_us': 0, + 'write_io_runtime_us': 43690})""" + self.assertEqual(pprint.pformat(frozendict(o)), exp) + exp = """\ +frozendict2({'RPM_cal': 0, + 'RPM_cal2': 48059, + 'Speed_cal': 0, + 'controldesk_runtime_us': 0, + 'main_code_runtime_us': 0, + 'read_io_runtime_us': 0, + 'write_io_runtime_us': 43690})""" + self.assertEqual(pprint.pformat(frozendict2(o)), exp) + + o = range(100) + exp = 'dict_keys([%s])' % ',\n '.join(map(str, o)) + keys = dict.fromkeys(o).keys() + self.assertEqual(pprint.pformat(keys), exp) + keys = frozendict.fromkeys(o).keys() + self.assertEqual(pprint.pformat(keys), exp) + + o = range(100) + exp = 'dict_values([%s])' % ',\n '.join(map(str, o)) + values = {v: v for v in o}.values() + self.assertEqual(pprint.pformat(values), exp) + values = frozendict({v: v for v in o}).values() + self.assertEqual(pprint.pformat(values), exp) + + o = range(100) + exp = 'dict_items([%s])' % ',\n '.join("(%s, %s)" % (i, i) for i in o) + items = {v: v for v in o}.items() + self.assertEqual(pprint.pformat(items), exp) + items = frozendict({v: v for v in o}).items() + self.assertEqual(pprint.pformat(items), exp) + + o = range(100) + exp = 'odict_keys([%s])' % ',\n '.join(map(str, o)) + keys = collections.OrderedDict.fromkeys(o).keys() + self.assertEqual(pprint.pformat(keys), exp) + + o = range(100) + exp = 'odict_values([%s])' % ',\n '.join(map(str, o)) + values = collections.OrderedDict({v: v for v in o}).values() + self.assertEqual(pprint.pformat(values), exp) + + o = range(100) + exp = 'odict_items([%s])' % ',\n '.join("(%s, %s)" % (i, i) for i in o) + items = collections.OrderedDict({v: v for v in o}).items() + self.assertEqual(pprint.pformat(items), exp) + + o = range(100) + exp = 'KeysView({%s})' % (': None,\n '.join(map(str, o)) + ': None') + keys_view = KeysView(dict.fromkeys(o)) + self.assertEqual(pprint.pformat(keys_view), exp) + + o = range(100) + exp = 'ItemsView({%s})' % (': None,\n '.join(map(str, o)) + ': None') + items_view = ItemsView(dict.fromkeys(o)) + self.assertEqual(pprint.pformat(items_view), exp) + + o = range(100) + exp = 'MappingView({%s})' % (': None,\n '.join(map(str, o)) + ': None') + mapping_view = MappingView(dict.fromkeys(o)) + self.assertEqual(pprint.pformat(mapping_view), exp) + + o = range(100) + exp = 'ValuesView({%s})' % (': None,\n '.join(map(str, o)) + ': None') + values_view = ValuesView(dict.fromkeys(o)) + self.assertEqual(pprint.pformat(values_view), exp) + o = range(100) exp = '[%s]' % ',\n '.join(map(str, o)) for type in [list, list2]: @@ -425,6 +540,30 @@ def test_ordered_dict(self): ('a', 6), ('lazy', 7), ('dog', 8)])""") + self.assertEqual(pprint.pformat(d.keys(), sort_dicts=False), +"""\ +odict_keys(['the', + 'quick', + 'brown', + 'fox', + 'jumped', + 'over', + 'a', + 'lazy', + 'dog'])""") + self.assertEqual(pprint.pformat(d.items(), sort_dicts=False), +"""\ +odict_items([('the', 0), + ('quick', 1), + ('brown', 2), + ('fox', 3), + ('jumped', 4), + ('over', 5), + ('a', 6), + ('lazy', 7), + ('dog', 8)])""") + self.assertEqual(pprint.pformat(d.values(), sort_dicts=False), + "odict_values([0, 1, 2, 3, 4, 5, 6, 7, 8])") def test_mapping_proxy(self): words = 'the quick brown fox jumped over a lazy dog'.split() @@ -453,6 +592,152 @@ def test_mapping_proxy(self): ('lazy', 7), ('dog', 8)]))""") + def test_dict_views(self): + for dict_class in (dict, collections.OrderedDict, collections.Counter): + empty = dict_class({}) + short = dict_class(dict(zip('edcba', 'edcba'))) + long = dict_class(dict((chr(x), chr(x)) for x in range(90, 64, -1))) + lengths = {"empty": empty, "short": short, "long": long} + prefix = "odict" if dict_class is collections.OrderedDict else "dict" + for name, d in lengths.items(): + with self.subTest(length=name, prefix=prefix): + is_short = len(d) < 6 + joiner = ", " if is_short else ",\n " + k = d.keys() + v = d.values() + i = d.items() + self.assertEqual(pprint.pformat(k, sort_dicts=True), + prefix + "_keys([%s])" % + joiner.join(repr(key) for key in sorted(k))) + self.assertEqual(pprint.pformat(v, sort_dicts=True), + prefix + "_values([%s])" % + joiner.join(repr(val) for val in sorted(v))) + self.assertEqual(pprint.pformat(i, sort_dicts=True), + prefix + "_items([%s])" % + joiner.join(repr(item) for item in sorted(i))) + self.assertEqual(pprint.pformat(k, sort_dicts=False), + prefix + "_keys([%s])" % + joiner.join(repr(key) for key in k)) + self.assertEqual(pprint.pformat(v, sort_dicts=False), + prefix + "_values([%s])" % + joiner.join(repr(val) for val in v)) + self.assertEqual(pprint.pformat(i, sort_dicts=False), + prefix + "_items([%s])" % + joiner.join(repr(item) for item in i)) + + def test_abc_views(self): + empty = {} + short = dict(zip('edcba', 'edcba')) + long = dict((chr(x), chr(x)) for x in range(90, 64, -1)) + lengths = {"empty": empty, "short": short, "long": long} + # Test that a subclass that doesn't replace __repr__ works with different lengths + class MV(MappingView): pass + + for name, d in lengths.items(): + with self.subTest(length=name, name="Views"): + is_short = len(d) < 6 + joiner = ", " if is_short else ",\n " + i = d.items() + s = sorted(i) + joined_items = "({%s})" % joiner.join(["%r: %r" % (k, v) for (k, v) in i]) + sorted_items = "({%s})" % joiner.join(["%r: %r" % (k, v) for (k, v) in s]) + self.assertEqual(pprint.pformat(KeysView(d), sort_dicts=True), + KeysView.__name__ + sorted_items) + self.assertEqual(pprint.pformat(ItemsView(d), sort_dicts=True), + ItemsView.__name__ + sorted_items) + self.assertEqual(pprint.pformat(MappingView(d), sort_dicts=True), + MappingView.__name__ + sorted_items) + self.assertEqual(pprint.pformat(MV(d), sort_dicts=True), + MV.__name__ + sorted_items) + self.assertEqual(pprint.pformat(ValuesView(d), sort_dicts=True), + ValuesView.__name__ + sorted_items) + self.assertEqual(pprint.pformat(KeysView(d), sort_dicts=False), + KeysView.__name__ + joined_items) + self.assertEqual(pprint.pformat(ItemsView(d), sort_dicts=False), + ItemsView.__name__ + joined_items) + self.assertEqual(pprint.pformat(MappingView(d), sort_dicts=False), + MappingView.__name__ + joined_items) + self.assertEqual(pprint.pformat(MV(d), sort_dicts=False), + MV.__name__ + joined_items) + self.assertEqual(pprint.pformat(ValuesView(d), sort_dicts=False), + ValuesView.__name__ + joined_items) + + def test_nested_views(self): + d = {1: MappingView({1: MappingView({1: MappingView({1: 2})})})} + self.assertEqual(repr(d), + "{1: MappingView({1: MappingView({1: MappingView({1: 2})})})}") + self.assertEqual(pprint.pformat(d), + "{1: MappingView({1: MappingView({1: MappingView({1: 2})})})}") + self.assertEqual(pprint.pformat(d, depth=2), + "{1: MappingView({1: {...}})}") + d = {} + d1 = {1: d.values()} + d2 = {1: d1.values()} + d3 = {1: d2.values()} + self.assertEqual(pprint.pformat(d3), + "{1: dict_values([dict_values([dict_values([])])])}") + self.assertEqual(pprint.pformat(d3, depth=2), + "{1: dict_values([{...}])}") + + def test_unorderable_items_views(self): + """Check that views with unorderable items have stable sorting.""" + d = dict((((3+1j), 3), ((1+1j), (1+0j)), (1j, 0j), (500, None), (499, None))) + iv = ItemsView(d) + self.assertEqual(pprint.pformat(iv), + pprint.pformat(iv)) + self.assertTrue(pprint.pformat(iv).endswith(", 499: None, 500: None})"), + pprint.pformat(iv)) + self.assertEqual(pprint.pformat(d.items()), # Won't be equal unless _safe_tuple + pprint.pformat(d.items())) # is used in _safe_repr + self.assertTrue(pprint.pformat(d.items()).endswith(", (499, None), (500, None)])")) + + def test_mapping_view_subclass_no_mapping(self): + class BMV(MappingView): + def __init__(self, d): + super().__init__(d) + self.mapping = self._mapping + del self._mapping + + self.assertRaises(AttributeError, pprint.pformat, BMV({})) + + def test_mapping_subclass_repr(self): + """Test that mapping ABC views use their ._mapping's __repr__.""" + class MyMapping(Mapping): + def __init__(self, keys=None): + self._keys = {} if keys is None else dict.fromkeys(keys) + + def __getitem__(self, item): + return self._keys[item] + + def __len__(self): + return len(self._keys) + + def __iter__(self): + return iter(self._keys) + + def __repr__(self): + return f"{self.__class__.__name__}([{', '.join(map(repr, self._keys.keys()))}])" + + m = MyMapping(["test", 1]) + self.assertEqual(repr(m), "MyMapping(['test', 1])") + short_view_repr = "%s(MyMapping(['test', 1]))" + self.assertEqual(repr(m.keys()), short_view_repr % "KeysView") + self.assertEqual(pprint.pformat(m.items()), short_view_repr % "ItemsView") + self.assertEqual(pprint.pformat(m.keys()), short_view_repr % "KeysView") + self.assertEqual(pprint.pformat(MappingView(m)), short_view_repr % "MappingView") + self.assertEqual(pprint.pformat(m.values()), short_view_repr % "ValuesView") + + alpha = "abcdefghijklmnopqrstuvwxyz" + m = MyMapping(alpha) + alpha_repr = ", ".join(map(repr, list(alpha))) + long_view_repr = "%%s(MyMapping([%s]))" % alpha_repr + self.assertEqual(repr(m), "MyMapping([%s])" % alpha_repr) + self.assertEqual(repr(m.keys()), long_view_repr % "KeysView") + self.assertEqual(pprint.pformat(m.items()), long_view_repr % "ItemsView") + self.assertEqual(pprint.pformat(m.keys()), long_view_repr % "KeysView") + self.assertEqual(pprint.pformat(MappingView(m)), long_view_repr % "MappingView") + self.assertEqual(pprint.pformat(m.values()), long_view_repr % "ValuesView") + def test_empty_simple_namespace(self): ns = types.SimpleNamespace() formatted = pprint.pformat(ns) @@ -768,6 +1053,10 @@ def test_sort_unorderable_values(self): 'frozenset({' + ','.join(map(repr, skeys)) + '})') self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys))), '{' + ','.join('%r:None' % k for k in skeys) + '}') + self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys).keys())), + 'dict_keys([' + ','.join('%r' % k for k in skeys) + '])') + self.assertEqual(clean(pprint.pformat(dict.fromkeys(keys).items())), + 'dict_items([' + ','.join('(%r,None)' % k for k in skeys) + '])') # Issue 10017: TypeError on user-defined types as dict keys. self.assertEqual(pprint.pformat({Unorderable: 0, 1: 0}), @@ -1010,6 +1299,12 @@ def test_counter(self): 'e': 4, 'n': 2, 'l': 1})""") + self.assertEqual(pprint.pformat(d, indent=2, width=1), +"""\ +Counter({ 's': 6, + 'e': 4, + 'n': 2, + 'l': 1})""") def test_chainmap(self): d = collections.ChainMap() @@ -1049,6 +1344,66 @@ def test_chainmap(self): ('a', 6), ('lazy', 7), ('dog', 8)]))""") + self.assertEqual(pprint.pformat(d.keys()), +"""\ +KeysView(ChainMap({'a': 6, + 'brown': 2, + 'dog': 8, + 'fox': 3, + 'jumped': 4, + 'lazy': 7, + 'over': 5, + 'quick': 1, + 'the': 0}, + OrderedDict([('the', 0), + ('quick', 1), + ('brown', 2), + ('fox', 3), + ('jumped', 4), + ('over', 5), + ('a', 6), + ('lazy', 7), + ('dog', 8)])))""") + self.assertEqual(pprint.pformat(d.items()), + """\ +ItemsView(ChainMap({'a': 6, + 'brown': 2, + 'dog': 8, + 'fox': 3, + 'jumped': 4, + 'lazy': 7, + 'over': 5, + 'quick': 1, + 'the': 0}, + OrderedDict([('the', 0), + ('quick', 1), + ('brown', 2), + ('fox', 3), + ('jumped', 4), + ('over', 5), + ('a', 6), + ('lazy', 7), + ('dog', 8)])))""") + self.assertEqual(pprint.pformat(d.values()), + """\ +ValuesView(ChainMap({'a': 6, + 'brown': 2, + 'dog': 8, + 'fox': 3, + 'jumped': 4, + 'lazy': 7, + 'over': 5, + 'quick': 1, + 'the': 0}, + OrderedDict([('the', 0), + ('quick', 1), + ('brown', 2), + ('fox', 3), + ('jumped', 4), + ('over', 5), + ('a', 6), + ('lazy', 7), + ('dog', 8)])))""") def test_deque(self): d = collections.deque() @@ -1096,6 +1451,36 @@ def test_user_dict(self): 'over': 5, 'quick': 1, 'the': 0}""") + self.assertEqual(pprint.pformat(d.keys()), """\ +KeysView({'a': 6, + 'brown': 2, + 'dog': 8, + 'fox': 3, + 'jumped': 4, + 'lazy': 7, + 'over': 5, + 'quick': 1, + 'the': 0})""") + self.assertEqual(pprint.pformat(d.items()), """\ +ItemsView({'a': 6, + 'brown': 2, + 'dog': 8, + 'fox': 3, + 'jumped': 4, + 'lazy': 7, + 'over': 5, + 'quick': 1, + 'the': 0})""") + self.assertEqual(pprint.pformat(d.values()), """\ +ValuesView({'a': 6, + 'brown': 2, + 'dog': 8, + 'fox': 3, + 'jumped': 4, + 'lazy': 7, + 'over': 5, + 'quick': 1, + 'the': 0})""") def test_user_list(self): d = collections.UserList() @@ -1130,6 +1515,564 @@ def test_user_string(self): 'jumped over a ' 'lazy dog'}""") + def test_template(self): + d = t"" + self.assertEqual(pprint.pformat(d), + "Template(strings=('',), interpolations=())") + self.assertEqual(pprint.pformat(d), repr(d)) + self.assertEqual(pprint.pformat(d, width=1), +"""\ +Template(strings=('',), + interpolations=())""") + name = "World" + d = t"Hello {name}" + self.assertEqual(pprint.pformat(d), +"""\ +Template(strings=('Hello ', ''), + interpolations=(Interpolation('World', 'name', None, ''),))""") + ver = {3.13: False, 3.14: True} + d = t"Hello { {"name": "Python", "version": ver}!s:z}!" + self.assertEqual(pprint.pformat(d, width=1), +"""\ +Template(strings=('Hello ', + '!'), + interpolations=(Interpolation({'name': 'Python', + 'version': {3.13: False, + 3.14: True}}, + ' ' + '{"name": ' + '"Python", ' + '"version": ' + 'ver}', + 's', + 'z'),))""") + + def test_expand_template(self): + d = t"" + self.assertEqual( + pprint.pformat(d, expand=True), + "Template(strings=('',), interpolations=())", + ) + name = "World" + d = t"Hello {name}" + self.assertEqual( + pprint.pformat(d, width=40, indent=4, expand=True), + """\ +Template( + strings=('Hello ', ''), + interpolations=( + Interpolation( + value='World', + expression='name', + conversion=None, + format_spec='', + ), + ), +)""", + ) + ver = {3.13: False, 3.14: True} + d = t"Hello { {"name": "Python", "version": ver}!s:z}!" + self.assertEqual( + pprint.pformat(d, width=40, indent=4, expand=True), + """\ +Template( + strings=('Hello ', '!'), + interpolations=( + Interpolation( + value={ + 'name': 'Python', + 'version': { + 3.13: False, + 3.14: True, + }, + }, + expression=' {"name": "Python", ' + '"version": ver}', + conversion='s', + format_spec='z', + ), + ), +)""", + ) + + def test_expand_dataclass(self): + @dataclasses.dataclass + class DummyDataclass: + foo: str + bar: float + baz: bool + qux: dict = dataclasses.field(default_factory=dict) + quux: list = dataclasses.field(default_factory=list) + corge: int = 1 + garply: tuple = (1, 2, 3, 4) + dummy_dataclass = DummyDataclass( + foo="foo", + bar=1.2, + baz=False, + qux={"foo": "bar", "baz": 123}, + quux=["foo", "bar", "baz"], + corge=7, + garply=(1, 2, 3, 4), + ) + self.assertEqual(pprint.pformat(dummy_dataclass, width=40, indent=4, + expand=True), +"""\ +DummyDataclass( + foo='foo', + bar=1.2, + baz=False, + qux={'baz': 123, 'foo': 'bar'}, + quux=['foo', 'bar', 'baz'], + corge=7, + garply=(1, 2, 3, 4), +)""") + + def test_expand_dict(self): + dummy_dict = { + "foo": "bar", + "baz": 123, + "qux": {"foo": "bar", "baz": 123}, + "quux": ["foo", "bar", "baz"], + "corge": 7, + } + self.assertEqual(pprint.pformat(dummy_dict, width=40, indent=4, + expand=True, sort_dicts=False), +"""\ +{ + 'foo': 'bar', + 'baz': 123, + 'qux': {'foo': 'bar', 'baz': 123}, + 'quux': ['foo', 'bar', 'baz'], + 'corge': 7, +}""") + + def test_expand_respects_width_with_long_keys(self): + # gh-155596: in expand mode the width of the "key: " prefix was not + # counted when deciding whether a value fits on the current line, so + # values under long keys could overflow width. + obj = {'a' * 12: 1, 'b' * 20: 2, 'c' * 30: {'d' * 5: 3, 'e' * 40: 3}} + result = pprint.pformat(obj, expand=True) + self.assertEqual(result, +"""\ +{ + 'aaaaaaaaaaaa': 1, + 'bbbbbbbbbbbbbbbbbbbb': 2, + 'cccccccccccccccccccccccccccccc': { + 'ddddd': 3, + 'eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee': 3, + }, +}""") + # The nested value must be broken up rather than overflowing. + self.assertTrue(all(len(line) <= 80 for line in result.splitlines()), + max(result.splitlines(), key=len)) + + def test_expand_ordered_dict(self): + dummy_ordered_dict = collections.OrderedDict( + [ + ("foo", 1), + ("bar", 12), + ("baz", 123), + ] + ) + self.assertEqual(pprint.pformat(dummy_ordered_dict, width=20, indent=4, + expand=True), +"""\ +OrderedDict([ + ('foo', 1), + ('bar', 12), + ('baz', 123), +])""") + + def test_expand_list(self): + dummy_list = [ + "foo", + "bar", + "baz", + "qux", + ] + self.assertEqual(pprint.pformat(dummy_list, width=20, indent=4, + expand=True), +"""\ +[ + 'foo', + 'bar', + 'baz', + 'qux', +]""") + + def test_expand_tuple(self): + dummy_tuple = ( + "foo", + "bar", + "baz", + 4, + 5, + 6, + ) + self.assertEqual(pprint.pformat(dummy_tuple, width=20, indent=4, + expand=True), +"""\ +( + 'foo', + 'bar', + 'baz', + 4, + 5, + 6, +)""") + + def test_expand_single_element_tuple(self): + self.assertEqual( + pprint.pformat((1,), width=1, indent=4, expand=True), + """\ +( + 1, +)""") + + def test_expand_set(self): + dummy_set = { + "foo", + "bar", + "baz", + "qux", + (1, 2, 3), + } + self.assertEqual(pprint.pformat(dummy_set, width=20, indent=4, + expand=True), +"""\ +{ + 'bar', + 'baz', + 'foo', + 'qux', + (1, 2, 3), +}""") + + def test_expand_frozenset(self): + dummy_set = { + (1, 2, 3), + } + dummy_frozenset = frozenset( + { + "foo", + "bar", + "baz", + (1, 2, 3), + frozenset(dummy_set), + } + ) + self.assertEqual(pprint.pformat(dummy_frozenset, width=40, indent=4, + expand=True), +"""\ +frozenset({ + frozenset({(1, 2, 3)}), + 'bar', + 'baz', + 'foo', + (1, 2, 3), +})""") + + def test_expand_frozendict(self): + dummy_frozendict = frozendict( + {"foo": "bar", "baz": 123, "qux": [1, 2]} + ) + self.assertEqual( + pprint.pformat(dummy_frozendict, width=20, indent=4, expand=True), + """\ +frozendict({ + 'baz': 123, + 'foo': 'bar', + 'qux': [1, 2], +})""", + ) + + def test_expand_bytes(self): + dummy_bytes = b"Hello world! foo bar baz 123 456 789" + self.assertEqual(pprint.pformat(dummy_bytes, width=20, indent=4, + expand=True), +"""\ +( + b'Hello world!' + b' foo bar baz' + b' 123 456 789' +)""") + + def test_expand_bytearray(self): + dummy_bytes = b"Hello world! foo bar baz 123 456 789" + dummy_byte_array = bytearray(dummy_bytes) + self.assertEqual(pprint.pformat(dummy_byte_array, width=40, indent=4, + expand=True), +"""\ +bytearray( + b'Hello world! foo bar baz 123 456' + b' 789' +)""") + + def test_expand_mappingproxy(self): + dummy_dict = { + "foo": "bar", + "baz": 123, + "qux": {"foo": "bar", "baz": 123}, + "quux": ["foo", "bar", "baz"], + "corge": 7, + } + dummy_mappingproxy = types.MappingProxyType(dummy_dict) + self.assertEqual(pprint.pformat(dummy_mappingproxy, width=40, indent=4, + expand=True), +"""\ +mappingproxy({ + 'baz': 123, + 'corge': 7, + 'foo': 'bar', + 'quux': ['foo', 'bar', 'baz'], + 'qux': {'baz': 123, 'foo': 'bar'}, +})""") + + def test_expand_namespace(self): + dummy_namespace = types.SimpleNamespace( + foo="bar", + bar=42, + baz=types.SimpleNamespace( + x=321, + y="string", + d={"foo": True, "bar": "baz"}, + ), + ) + + self.assertEqual(pprint.pformat(dummy_namespace, width=40, indent=4, + expand=True), +"""\ +namespace( + foo='bar', + bar=42, + baz=namespace( + x=321, + y='string', + d={'bar': 'baz', 'foo': True}, + ), +)""") + + def test_expand_defaultdict(self): + dummy_defaultdict = collections.defaultdict(list) + dummy_defaultdict["foo"].append("bar") + dummy_defaultdict["foo"].append("baz") + dummy_defaultdict["foo"].append("qux") + dummy_defaultdict["bar"] = {"foo": "bar", "baz": None} + self.assertEqual(pprint.pformat(dummy_defaultdict, width=40, indent=4, + expand=True), +"""\ +defaultdict(, { + 'bar': {'baz': None, 'foo': 'bar'}, + 'foo': ['bar', 'baz', 'qux'], +})""") + + def test_expand_counter(self): + dummy_counter = collections.Counter("abcdeabcdabcaba") + expected = """\ +Counter({ + 'a': 5, + 'b': 4, + 'c': 3, + 'd': 2, + 'e': 1, +})""" + self.assertEqual(pprint.pformat(dummy_counter, width=40, indent=4, + expand=True), expected) + + expected2 = """\ +Counter({ + 'a': 5, + 'b': 4, + 'c': 3, + 'd': 2, + 'e': 1, +})""" + self.assertEqual(pprint.pformat(dummy_counter, width=20, indent=2, + expand=True), expected2) + + def test_expand_chainmap(self): + dummy_dict = { + "foo": "bar", + "baz": 123, + "qux": {"foo": "bar", "baz": 123}, + "quux": ["foo", "bar", "baz"], + "corge": 7, + } + dummy_chainmap = collections.ChainMap( + {"foo": "bar"}, + {"baz": "qux"}, + {"corge": dummy_dict}, + ) + dummy_chainmap.maps.append({"garply": "waldo"}) + self.assertEqual(pprint.pformat(dummy_chainmap, width=40, indent=4, + expand=True), +"""\ +ChainMap( + {'foo': 'bar'}, + {'baz': 'qux'}, + { + 'corge': { + 'baz': 123, + 'corge': 7, + 'foo': 'bar', + 'quux': [ + 'foo', + 'bar', + 'baz', + ], + 'qux': { + 'baz': 123, + 'foo': 'bar', + }, + }, + }, + {'garply': 'waldo'}, +)""") + + def test_expand_deque(self): + dummy_dict = { + "foo": "bar", + "baz": 123, + "qux": {"foo": "bar", "baz": 123}, + "quux": ["foo", "bar", "baz"], + "corge": 7, + } + dummy_list = [ + "foo", + "bar", + "baz", + ] + dummy_set = { + (1, 2, 3), + } + dummy_deque = collections.deque(maxlen=10) + dummy_deque.append("foo") + dummy_deque.append(123) + dummy_deque.append(dummy_dict) + dummy_deque.extend(dummy_list) + dummy_deque.appendleft(dummy_set) + self.assertEqual(pprint.pformat(dummy_deque, width=40, indent=4, + expand=True), +"""\ +deque([ + {(1, 2, 3)}, + 'foo', + 123, + { + 'baz': 123, + 'corge': 7, + 'foo': 'bar', + 'quux': ['foo', 'bar', 'baz'], + 'qux': { + 'baz': 123, + 'foo': 'bar', + }, + }, + 'foo', + 'bar', + 'baz', +], maxlen=10)""") + + def test_expand_userdict(self): + class DummyUserDict(collections.UserDict): + """A custom UserDict with some extra attributes""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.access_count = 0 + dummy_userdict = DummyUserDict({ "foo": "bar", "baz": 123, + "qux": {"foo": "bar", "baz": 123}, + "quux": ["foo", "bar", "baz"], + "corge": 7 }) + dummy_userdict.access_count = 5 + + self.assertEqual(pprint.pformat(dummy_userdict, width=40, indent=4, + expand=True), +"""\ +{ + 'baz': 123, + 'corge': 7, + 'foo': 'bar', + 'quux': ['foo', 'bar', 'baz'], + 'qux': {'baz': 123, 'foo': 'bar'}, +}""") + + def test_expand_userlist(self): + class DummyUserList(collections.UserList): + """A custom UserList with some extra attributes""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.description = "foo" + dummy_userlist = DummyUserList(["first", 2, {"key": "value"}, + [4, 5, 6]]) + + self.assertEqual(pprint.pformat(dummy_userlist, width=40, indent=4, + expand=True), +"""\ +[ + 'first', + 2, + {'key': 'value'}, + [4, 5, 6], +]""") + + def test_expand_dict_keys(self): + d = {"foo": 1, "bar": 2, "baz": 3, "qux": 4, "quux": 5} + self.assertEqual( + pprint.pformat(d.keys(), width=20, indent=4, expand=True), + """\ +dict_keys([ + 'bar', + 'baz', + 'foo', + 'quux', + 'qux', +])""", + ) + + def test_expand_dict_values(self): + d = {"foo": 1, "bar": 2, "baz": 3, "qux": 4, "quux": 5} + self.assertEqual( + pprint.pformat(d.values(), width=20, indent=4, expand=True), + """\ +dict_values([ + 1, + 2, + 3, + 4, + 5, +])""", + ) + + def test_expand_dict_items(self): + d = {"foo": 1, "bar": 2, "baz": 3, "qux": 4, "quux": 5} + self.assertEqual( + pprint.pformat(d.items(), width=20, indent=4, expand=True), + """\ +dict_items([ + ('bar', 2), + ('baz', 3), + ('foo', 1), + ('quux', 5), + ('qux', 4), +])""", + ) + + def test_expand_str(self): + s = "The quick brown fox jumped over the lazy dog " * 3 + self.assertEqual( + pprint.pformat(s, width=40, indent=4, expand=True), + """\ +( + 'The quick brown fox jumped over ' + 'the lazy dog The quick brown fox ' + 'jumped over the lazy dog The ' + 'quick brown fox jumped over the ' + 'lazy dog ' +)""", + ) + class DottedPrettyPrinter(pprint.PrettyPrinter): diff --git a/Lib/test/test_profile.py b/Lib/test/test_profile.py index 56ccc84a2e6..c4b2d7ca05c 100644 --- a/Lib/test/test_profile.py +++ b/Lib/test/test_profile.py @@ -4,12 +4,16 @@ import pstats import unittest import os +import warnings from difflib import unified_diff from io import StringIO from test.support.os_helper import TESTFN, unlink, temp_dir, change_cwd from contextlib import contextmanager, redirect_stdout -import profile +# Suppress deprecation warning for profile module (PEP 799) +with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + import profile from test.profilee import testfunc, timer from test.support.script_helper import assert_python_failure, assert_python_ok @@ -48,7 +52,6 @@ def do_profiling(cls): results.append('\n'.join(output)) return results - @unittest.expectedFailure # TODO: RUSTPYTHON; print_callees output differs from CPython def test_cprofile(self): results = self.do_profiling() expected = self.get_expected_output() diff --git a/Lib/test/test_profiling/__init__.py b/Lib/test/test_profiling/__init__.py new file mode 100644 index 00000000000..4b16ecc3115 --- /dev/null +++ b/Lib/test/test_profiling/__init__.py @@ -0,0 +1,5 @@ +import os +from test.support import load_package_tests + +def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_profiling/__main__.py b/Lib/test/test_profiling/__main__.py new file mode 100644 index 00000000000..40a23a297ec --- /dev/null +++ b/Lib/test/test_profiling/__main__.py @@ -0,0 +1,4 @@ +from . import load_tests +import unittest + +unittest.main() diff --git a/Lib/test/test_profiling/test_heatmap.py b/Lib/test/test_profiling/test_heatmap.py new file mode 100644 index 00000000000..1b4de0caa3d --- /dev/null +++ b/Lib/test/test_profiling/test_heatmap.py @@ -0,0 +1,893 @@ +"""Tests for the heatmap collector (profiling.sampling).""" + +import os +import shutil +import tempfile +import unittest +from unittest import mock +from collections import namedtuple +from pathlib import Path + +# Matches the C structseq LocationInfo from _remote_debugging +LocationInfo = namedtuple('LocationInfo', ['lineno', 'end_lineno', 'col_offset', 'end_col_offset']) + +from profiling.sampling.heatmap_collector import ( + HeatmapCollector, + get_python_path_info, + extract_module_name, +) + +from test.support import captured_stdout, captured_stderr + + +# ============================================================================= +# Unit Tests for Public Helper Functions +# ============================================================================= + +class TestPathInfoFunctions(unittest.TestCase): + """Test public helper functions for path information.""" + + def test_get_python_path_info_returns_dict(self): + """Test that get_python_path_info returns a dictionary with expected keys.""" + path_info = get_python_path_info() + + self.assertIsInstance(path_info, dict) + self.assertIn('stdlib', path_info) + self.assertIn('site_packages', path_info) + self.assertIn('sys_path', path_info) + + def test_get_python_path_info_stdlib_is_path_or_none(self): + """Test that stdlib is either a Path object or None.""" + path_info = get_python_path_info() + + if path_info['stdlib'] is not None: + self.assertIsInstance(path_info['stdlib'], Path) + + def test_get_python_path_info_site_packages_is_list(self): + """Test that site_packages is a list.""" + path_info = get_python_path_info() + + self.assertIsInstance(path_info['site_packages'], list) + for item in path_info['site_packages']: + self.assertIsInstance(item, Path) + + def test_get_python_path_info_sys_path_is_list(self): + """Test that sys_path is a list of Path objects.""" + path_info = get_python_path_info() + + self.assertIsInstance(path_info['sys_path'], list) + for item in path_info['sys_path']: + self.assertIsInstance(item, Path) + + def test_extract_module_name_with_none(self): + """Test extract_module_name with None filename.""" + path_info = get_python_path_info() + module_name, module_type = extract_module_name(None, path_info) + + self.assertEqual(module_name, 'unknown') + self.assertEqual(module_type, 'other') + + def test_extract_module_name_with_empty_string(self): + """Test extract_module_name with empty filename.""" + path_info = get_python_path_info() + module_name, module_type = extract_module_name('', path_info) + + self.assertEqual(module_name, 'unknown') + self.assertEqual(module_type, 'other') + + def test_extract_module_name_with_stdlib_file(self): + """Test extract_module_name with a standard library file.""" + path_info = get_python_path_info() + + # Use os module as a known stdlib file + if path_info['stdlib']: + stdlib_file = str(path_info['stdlib'] / 'os.py') + module_name, module_type = extract_module_name(stdlib_file, path_info) + + self.assertEqual(module_type, 'stdlib') + self.assertIn('os', module_name) + + def test_extract_module_name_with_project_file(self): + """Test extract_module_name with a project file.""" + path_info = get_python_path_info() + + # Create a mock project file path + if path_info['sys_path']: + # Use current directory as project path + project_file = '/some/project/path/mymodule.py' + module_name, module_type = extract_module_name(project_file, path_info) + + # Should classify as 'other' if not in sys.path + self.assertIn(module_type, ['project', 'other']) + + def test_extract_module_name_removes_py_extension(self): + """Test that .py extension is removed from module names.""" + path_info = get_python_path_info() + + # Test with a simple .py file + module_name, module_type = extract_module_name('/path/to/test.py', path_info) + + # Module name should not contain .py + self.assertNotIn('.py', module_name) + + def test_extract_module_name_with_special_files(self): + """Test extract_module_name with special filenames like .""" + path_info = get_python_path_info() + + special_files = ['', '', '[eval]'] + for special_file in special_files: + module_name, module_type = extract_module_name(special_file, path_info) + self.assertEqual(module_type, 'other') + + +# ============================================================================= +# Unit Tests for HeatmapCollector Public API +# ============================================================================= + +class TestHeatmapCollectorInit(unittest.TestCase): + """Test HeatmapCollector initialization.""" + + def test_init_creates_empty_data_structures(self): + """Test that __init__ creates empty data structures.""" + collector = HeatmapCollector(sample_interval_usec=100) + + # Check that data structures are initialized + self.assertIsInstance(collector.line_samples, dict) + self.assertIsInstance(collector.file_samples, dict) + self.assertIsInstance(collector.line_self_samples, dict) + self.assertIsInstance(collector.file_self_samples, dict) + self.assertIsInstance(collector.call_graph, dict) + self.assertIsInstance(collector.callers_graph, dict) + self.assertIsInstance(collector.function_definitions, dict) + self.assertIsInstance(collector.edge_samples, dict) + + # Check that they're empty + self.assertEqual(len(collector.line_samples), 0) + self.assertEqual(len(collector.file_samples), 0) + self.assertEqual(len(collector.line_self_samples), 0) + self.assertEqual(len(collector.file_self_samples), 0) + + def test_init_sets_total_samples_to_zero(self): + """Test that total samples starts at zero.""" + collector = HeatmapCollector(sample_interval_usec=100) + self.assertEqual(collector._total_samples, 0) + + def test_init_gets_path_info(self): + """Test that path info is retrieved during init.""" + collector = HeatmapCollector(sample_interval_usec=100) + self.assertIsNotNone(collector._path_info) + self.assertIn('stdlib', collector._path_info) + + +class TestHeatmapCollectorSetStats(unittest.TestCase): + """Test HeatmapCollector.set_stats() method.""" + + def test_set_stats_stores_all_parameters(self): + """Test that set_stats stores all provided parameters.""" + collector = HeatmapCollector(sample_interval_usec=100) + + collector.set_stats( + sample_interval_usec=500, + duration_sec=10.5, + sample_rate=99.5, + error_rate=0.5 + ) + + self.assertEqual(collector.stats['sample_interval_usec'], 500) + self.assertEqual(collector.stats['duration_sec'], 10.5) + self.assertEqual(collector.stats['sample_rate'], 99.5) + self.assertEqual(collector.stats['error_rate'], 0.5) + + def test_set_stats_includes_system_info(self): + """Test that set_stats includes Python and platform info.""" + collector = HeatmapCollector(sample_interval_usec=100) + collector.set_stats(sample_interval_usec=100, duration_sec=1.0, sample_rate=100.0) + + self.assertIn('python_version', collector.stats) + self.assertIn('python_implementation', collector.stats) + self.assertIn('platform', collector.stats) + + def test_set_stats_accepts_kwargs(self): + """Test that set_stats accepts additional kwargs.""" + collector = HeatmapCollector(sample_interval_usec=100) + + collector.set_stats( + sample_interval_usec=100, + duration_sec=1.0, + sample_rate=100.0, + custom_key='custom_value', + another_key=42 + ) + + self.assertEqual(collector.stats['custom_key'], 'custom_value') + self.assertEqual(collector.stats['another_key'], 42) + + def test_set_stats_with_none_error_rate(self): + """Test set_stats with error_rate=None.""" + collector = HeatmapCollector(sample_interval_usec=100) + collector.set_stats(sample_interval_usec=100, duration_sec=1.0, sample_rate=100.0) + + self.assertIn('error_rate', collector.stats) + self.assertIsNone(collector.stats['error_rate']) + + +class TestHeatmapCollectorProcessFrames(unittest.TestCase): + """Test HeatmapCollector.process_frames() method.""" + + def test_process_frames_increments_total_samples(self): + """Test that process_frames increments total samples count.""" + collector = HeatmapCollector(sample_interval_usec=100) + + initial_count = collector._total_samples + frames = [('file.py', (10, 10, -1, -1), 'func', None)] + collector.process_frames(frames, thread_id=1) + + self.assertEqual(collector._total_samples, initial_count + 1) + + def test_process_frames_records_line_samples(self): + """Test that process_frames records line samples.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [('test.py', (5, 5, -1, -1), 'test_func', None)] + collector.process_frames(frames, thread_id=1) + + # Check that line was recorded + self.assertIn(('test.py', 5), collector.line_samples) + self.assertEqual(collector.line_samples[('test.py', 5)], 1) + + def test_process_frames_records_multiple_lines_in_stack(self): + """Test that process_frames records all lines in a stack.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [ + ('file1.py', (10, 10, -1, -1), 'func1', None), + ('file2.py', (20, 20, -1, -1), 'func2', None), + ('file3.py', (30, 30, -1, -1), 'func3', None) + ] + collector.process_frames(frames, thread_id=1) + + # All frames should be recorded + self.assertIn(('file1.py', 10), collector.line_samples) + self.assertIn(('file2.py', 20), collector.line_samples) + self.assertIn(('file3.py', 30), collector.line_samples) + + def test_process_frames_distinguishes_self_samples(self): + """Test that process_frames distinguishes self (leaf) samples.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [ + ('leaf.py', (5, 5, -1, -1), 'leaf_func', None), # This is the leaf (top of stack) + ('caller.py', (10, 10, -1, -1), 'caller_func', None) + ] + collector.process_frames(frames, thread_id=1) + + # Leaf should have self sample + self.assertIn(('leaf.py', 5), collector.line_self_samples) + self.assertEqual(collector.line_self_samples[('leaf.py', 5)], 1) + + # Caller should NOT have self sample + self.assertNotIn(('caller.py', 10), collector.line_self_samples) + + def test_process_frames_accumulates_samples(self): + """Test that multiple calls accumulate samples.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [('file.py', (10, 10, -1, -1), 'func', None)] + + collector.process_frames(frames, thread_id=1) + collector.process_frames(frames, thread_id=1) + collector.process_frames(frames, thread_id=1) + + self.assertEqual(collector.line_samples[('file.py', 10)], 3) + self.assertEqual(collector._total_samples, 3) + + def test_process_frames_ignores_invalid_frames(self): + """Test that process_frames ignores invalid frames.""" + collector = HeatmapCollector(sample_interval_usec=100) + + # These should be ignored + invalid_frames = [ + ('', (1, 1, -1, -1), 'test', None), + ('[eval]', (1, 1, -1, -1), 'test', None), + ('', (1, 1, -1, -1), 'test', None), + (None, (1, 1, -1, -1), 'test', None), + ('__init__', (0, 0, -1, -1), 'test', None), # Special invalid frame + ] + + for frame in invalid_frames: + collector.process_frames([frame], thread_id=1) + + # Should not record these invalid frames + for frame in invalid_frames: + if frame[0]: + self.assertNotIn((frame[0], frame[1][0]), collector.line_samples) + + def test_process_frames_builds_call_graph(self): + """Test that process_frames builds call graph relationships.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [ + ('callee.py', (5, 5, -1, -1), 'callee_func', None), + ('caller.py', (10, 10, -1, -1), 'caller_func', None) + ] + collector.process_frames(frames, thread_id=1) + + # Check that call relationship was recorded + caller_key = ('caller.py', 10) + self.assertIn(caller_key, collector.call_graph) + + # Check callers graph + callee_key = ('callee.py', 5) + self.assertIn(callee_key, collector.callers_graph) + + def test_process_frames_records_function_definitions(self): + """Test that process_frames records function definition locations.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [('module.py', (42, 42, -1, -1), 'my_function', None)] + collector.process_frames(frames, thread_id=1) + + self.assertIn(('module.py', 'my_function'), collector.function_definitions) + self.assertEqual(collector.function_definitions[('module.py', 'my_function')], 42) + + def test_process_frames_tracks_edge_samples(self): + """Test that process_frames tracks edge sample counts.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [ + ('callee.py', (5, 5, -1, -1), 'callee', None), + ('caller.py', (10, 10, -1, -1), 'caller', None) + ] + + # Process same call stack multiple times + collector.process_frames(frames, thread_id=1) + collector.process_frames(frames, thread_id=1) + + # Check that edge count is tracked + self.assertGreater(len(collector.edge_samples), 0) + + def test_process_frames_weight_applies_to_identical_samples(self): + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [ + ('callee.py', (5, 5, -1, -1), 'callee', None), + ('caller.py', (10, 10, -1, -1), 'caller', None), + ] + + collector.process_frames(frames, thread_id=1, weight=5) + + edge_key = (('caller.py', 10), ('callee.py', 5)) + self.assertEqual(collector.edge_samples[edge_key], 5) + self.assertEqual(collector.line_samples[('callee.py', 5)], 5) + self.assertEqual(collector.line_samples[('caller.py', 10)], 5) + + def test_process_frames_handles_empty_frames(self): + """Test that process_frames handles empty frame list.""" + collector = HeatmapCollector(sample_interval_usec=100) + + initial_count = collector._total_samples + collector.process_frames([], thread_id=1) + + # Should still increment total samples + self.assertEqual(collector._total_samples, initial_count + 1) + + def test_process_frames_with_file_samples_dict(self): + """Test that file_samples dict is properly populated.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [('test.py', (10, 10, -1, -1), 'func', None)] + collector.process_frames(frames, thread_id=1) + + self.assertIn('test.py', collector.file_samples) + self.assertIn(10, collector.file_samples['test.py']) + self.assertEqual(collector.file_samples['test.py'][10], 1) + + +def frame(filename, line, func): + """Create a frame tuple: (filename, location, funcname, opcode).""" + return (filename, (line, line, -1, -1), func, None) + + +class TestHeatmapCollectorNavigationButtons(unittest.TestCase): + """Test navigation button behavior for caller/callee relationships. + + For every call stack: + - Root frames (entry points): only DOWN arrow (callees) + - Middle frames: both UP and DOWN arrows + - Leaf frames: only UP arrow (callers) + """ + + def collect(self, *stacks): + """Create collector and process frame stacks.""" + collector = HeatmapCollector(sample_interval_usec=100) + for stack in stacks: + collector.process_frames(stack, thread_id=1) + return collector + + def test_deep_call_stack_relationships(self): + """Test root/middle/leaf navigation in a 5-level call stack.""" + # Stack: root -> A -> B -> C -> leaf + stack = [ + frame('leaf.py', 5, 'leaf'), + frame('c.py', 10, 'func_c'), + frame('b.py', 15, 'func_b'), + frame('a.py', 20, 'func_a'), + frame('root.py', 25, 'root'), + ] + c = self.collect(stack) + + # Root: only callees (no one calls it) + self.assertIn(('root.py', 25), c.call_graph) + self.assertNotIn(('root.py', 25), c.callers_graph) + + # Middle frames: both callers and callees + for key in [('a.py', 20), ('b.py', 15), ('c.py', 10)]: + self.assertIn(key, c.call_graph) + self.assertIn(key, c.callers_graph) + + # Leaf: only callers (doesn't call anyone) + self.assertNotIn(('leaf.py', 5), c.call_graph) + self.assertIn(('leaf.py', 5), c.callers_graph) + + def test_all_lines_in_function_see_callers(self): + """Test that interior lines map to their function for caller lookup.""" + # Same function sampled at different lines (12, 15, 10) + c = self.collect( + [frame('mod.py', 12, 'my_func'), frame('caller.py', 100, 'caller')], + [frame('mod.py', 15, 'my_func'), frame('caller.py', 100, 'caller')], + [frame('mod.py', 10, 'my_func'), frame('caller.py', 100, 'caller')], + ) + + # All lines should map to same function + for line in [10, 12, 15]: + self.assertEqual(c.line_to_function[('mod.py', line)], 'my_func') + + # Function definition line should have callers + func_def = c.function_definitions[('mod.py', 'my_func')] + self.assertIn(('mod.py', func_def), c.callers_graph) + + def test_multiple_callers_and_callees(self): + """Test multiple callers/callees are recorded correctly.""" + # Two callers -> target, and caller -> two callees + c = self.collect( + [frame('target.py', 10, 'target'), frame('caller1.py', 20, 'c1')], + [frame('target.py', 10, 'target'), frame('caller2.py', 30, 'c2')], + [frame('callee1.py', 5, 'f1'), frame('dispatcher.py', 40, 'dispatch')], + [frame('callee2.py', 6, 'f2'), frame('dispatcher.py', 40, 'dispatch')], + ) + + # Target has 2 callers + callers = c.callers_graph[('target.py', 10)] + self.assertEqual({x[0] for x in callers}, {'caller1.py', 'caller2.py'}) + + # Dispatcher has 2 callees + callees = c.call_graph[('dispatcher.py', 40)] + self.assertEqual({x[0] for x in callees}, {'callee1.py', 'callee2.py'}) + + def test_edge_samples_counted(self): + """Test that repeated calls accumulate edge counts.""" + stack = [frame('callee.py', 10, 'callee'), frame('caller.py', 20, 'caller')] + c = self.collect(stack, stack, stack) + + edge_key = (('caller.py', 20), ('callee.py', 10)) + self.assertEqual(c.edge_samples[edge_key], 3) + + +class TestHeatmapCollectorExport(unittest.TestCase): + """Test HeatmapCollector.export() method.""" + + def setUp(self): + """Set up test directory.""" + self.test_dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, self.test_dir) + + def test_export_creates_output_directory(self): + """Test that export creates the output directory.""" + collector = HeatmapCollector(sample_interval_usec=100) + + # Add some data + frames = [('test.py', (10, 10, -1, -1), 'func', None)] + collector.process_frames(frames, thread_id=1) + + output_path = os.path.join(self.test_dir, 'heatmap_output') + + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + self.assertTrue(os.path.exists(output_path)) + self.assertTrue(os.path.isdir(output_path)) + + def test_export_creates_index_html(self): + """Test that export creates index.html.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [('test.py', (10, 10, -1, -1), 'func', None)] + collector.process_frames(frames, thread_id=1) + + output_path = os.path.join(self.test_dir, 'heatmap_output') + + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + index_path = os.path.join(output_path, 'index.html') + self.assertTrue(os.path.exists(index_path)) + + def test_export_creates_file_htmls(self): + """Test that export creates individual file HTMLs.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [('test.py', (10, 10, -1, -1), 'func', None)] + collector.process_frames(frames, thread_id=1) + + output_path = os.path.join(self.test_dir, 'heatmap_output') + + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + # Check for file_XXXX.html files + html_files = [f for f in os.listdir(output_path) + if f.startswith('file_') and f.endswith('.html')] + self.assertGreater(len(html_files), 0) + + def test_export_with_empty_data(self): + """Test export with no data collected.""" + collector = HeatmapCollector(sample_interval_usec=100) + + output_path = os.path.join(self.test_dir, 'empty_output') + + # Should handle empty data gracefully + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + def test_export_handles_html_suffix(self): + """Test that export handles .html suffix in output path.""" + collector = HeatmapCollector(sample_interval_usec=100) + + frames = [('test.py', (10, 10, -1, -1), 'func', None)] + collector.process_frames(frames, thread_id=1) + + # Path with .html suffix should be stripped + output_path = os.path.join(self.test_dir, 'output.html') + + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + # Should create directory without .html + expected_dir = os.path.join(self.test_dir, 'output') + self.assertTrue(os.path.exists(expected_dir)) + + def test_export_with_multiple_files(self): + """Test export with multiple files.""" + collector = HeatmapCollector(sample_interval_usec=100) + + # Add samples for multiple files + collector.process_frames([('file1.py', (10, 10, -1, -1), 'func1', None)], thread_id=1) + collector.process_frames([('file2.py', (20, 20, -1, -1), 'func2', None)], thread_id=1) + collector.process_frames([('file3.py', (30, 30, -1, -1), 'func3', None)], thread_id=1) + + output_path = os.path.join(self.test_dir, 'multi_file') + + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + # Should create HTML for each file + html_files = [f for f in os.listdir(output_path) + if f.startswith('file_') and f.endswith('.html')] + self.assertGreaterEqual(len(html_files), 3) + + def test_export_index_contains_file_references(self): + """Test that index.html contains references to profiled files.""" + collector = HeatmapCollector(sample_interval_usec=100) + collector.set_stats(sample_interval_usec=100, duration_sec=1.0, sample_rate=100.0) + + frames = [('mytest.py', (10, 10, -1, -1), 'my_func', None)] + collector.process_frames(frames, thread_id=1) + + output_path = os.path.join(self.test_dir, 'test_output') + + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + index_path = os.path.join(output_path, 'index.html') + with open(index_path, 'r', encoding='utf-8') as f: + content = f.read() + + # Should contain reference to the file + self.assertIn('mytest', content) + + def test_export_file_html_has_line_numbers(self): + """Test that exported file HTML contains line numbers.""" + collector = HeatmapCollector(sample_interval_usec=100) + + # Create a temporary Python file + temp_file = os.path.join(self.test_dir, 'temp_source.py') + with open(temp_file, 'w') as f: + f.write('def test():\n pass\n') + + frames = [(temp_file, (1, 1, -1, -1), 'test', None)] + collector.process_frames(frames, thread_id=1) + + output_path = os.path.join(self.test_dir, 'line_test') + + with captured_stdout(), captured_stderr(): + collector.export(output_path) + + # Find the generated file HTML + html_files = [f for f in os.listdir(output_path) + if f.startswith('file_') and f.endswith('.html')] + + self.assertEqual(len(html_files), 1) + with open(os.path.join(output_path, html_files[0]), 'r', encoding='utf-8') as f: + content = f.read() + + # Should have line-related content + self.assertIn('line-', content) + + def test_export_skips_nonexistent_source(self): + self.check_unavailable_source(os.path.join(self.test_dir, 'missing.py')) + + def test_export_skips_directory_source(self): + self.check_unavailable_source(self.test_dir) + + @unittest.skipUnless(hasattr(os, 'mkfifo'), 'requires os.mkfifo') + def test_export_skips_fifo_source(self): + filename = os.path.join(self.test_dir, 'source.fifo') + os.mkfifo(filename) + self.check_unavailable_source(filename) + + def check_unavailable_source(self, filename): + collector = HeatmapCollector(sample_interval_usec=100) + frames = [(filename, (1, 1, -1, -1), 'f', None)] + collector.process_frames(frames, thread_id=1) + output_path = Path(self.test_dir) / 'unavailable_source' + read_text = Path.read_text + + def check_read(path, *args, **kwargs): + self.assertNotEqual(path, Path(filename), + 'Non-regular source must not be opened') + return read_text(path, *args, **kwargs) + + with (captured_stdout(), captured_stderr(), + mock.patch.object(Path, 'read_text', check_read)): + collector.export(output_path) + content = (output_path / collector.file_index[filename]).read_text( + encoding='utf-8') + self.assertIn('Source file not available', content) + +class MockFrameInfo: + """Mock FrameInfo for testing. + + Frame format: (filename, location, funcname, opcode) where: + - location is a tuple (lineno, end_lineno, col_offset, end_col_offset) + - opcode is an int or None + """ + + def __init__(self, filename, lineno, funcname, opcode=None): + self.filename = filename + self.funcname = funcname + self.opcode = opcode + self.location = (lineno, lineno, -1, -1) + + def __iter__(self): + return iter((self.filename, self.location, self.funcname, self.opcode)) + + def __getitem__(self, index): + return (self.filename, self.location, self.funcname, self.opcode)[index] + + def __len__(self): + return 4 + + def __repr__(self): + return f"MockFrameInfo('{self.filename}', {self.location}, '{self.funcname}', {self.opcode})" + + +class MockThreadInfo: + """Mock ThreadInfo for testing since the real one isn't accessible.""" + + def __init__(self, thread_id, frame_info, status=0): + self.thread_id = thread_id + self.frame_info = frame_info + self.status = status # Thread status flags + + def __repr__(self): + return f"MockThreadInfo(thread_id={self.thread_id}, frame_info={self.frame_info})" + + +class MockInterpreterInfo: + """Mock InterpreterInfo for testing since the real one isn't accessible.""" + + def __init__(self, interpreter_id, threads): + self.interpreter_id = interpreter_id + self.threads = threads + + def __repr__(self): + return f"MockInterpreterInfo(interpreter_id={self.interpreter_id}, threads={self.threads})" + + +class TestHeatmapCollector(unittest.TestCase): + """Tests for HeatmapCollector functionality.""" + + def test_heatmap_collector_basic(self): + """Test basic HeatmapCollector functionality.""" + collector = HeatmapCollector(sample_interval_usec=100) + + # Test empty state + self.assertEqual(len(collector.file_samples), 0) + self.assertEqual(len(collector.line_samples), 0) + + # Test collecting sample data - frames are 4-tuples: (filename, location, funcname, opcode) + test_frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo( + 1, + [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")], + )] + ) + ] + collector.collect(test_frames) + + # Should have recorded samples for the file + self.assertGreater(len(collector.line_samples), 0) + self.assertIn("file.py", collector.file_samples) + + # Check that line samples were recorded + file_data = collector.file_samples["file.py"] + self.assertGreater(len(file_data), 0) + + def test_heatmap_collector_export(self): + """Test heatmap HTML export functionality.""" + heatmap_dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, heatmap_dir) + + collector = HeatmapCollector(sample_interval_usec=100) + + # Create test data with multiple files using MockFrameInfo + test_frames1 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")])], + ) + ] + test_frames2 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")])], + ) + ] # Same stack + test_frames3 = [ + MockInterpreterInfo(0, [MockThreadInfo(1, [MockFrameInfo("other.py", 5, "other_func")])]) + ] + + collector.collect(test_frames1) + collector.collect(test_frames2) + collector.collect(test_frames3) + + # Export heatmap + with (captured_stdout(), captured_stderr()): + collector.export(heatmap_dir) + + # Verify index.html was created + index_path = os.path.join(heatmap_dir, "index.html") + self.assertTrue(os.path.exists(index_path)) + self.assertGreater(os.path.getsize(index_path), 0) + + # Check index contains HTML content + with open(index_path, "r", encoding="utf-8") as f: + content = f.read() + + # Should be valid HTML + self.assertIn("", content.lower()) + self.assertIn(" Counter of linenos + self.assertIn("test.py", collector.file_samples) + # Line 10 should have samples + self.assertIn(10, collector.file_samples["test.py"]) + + def test_heatmap_with_none_location(self): + """Test HeatmapCollector handles None location gracefully.""" + collector = HeatmapCollector(sample_interval_usec=1000) + + # Synthetic frame with None location + frame = MockFrameInfo("~", 0, "") + frame.location = None + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame])] + ) + ] + # Should not raise + collector.collect(frames) + + def test_heatmap_export_with_location_data(self): + """Test HeatmapCollector export includes location info.""" + tmp_dir = tempfile.mkdtemp() + self.addCleanup(shutil.rmtree, tmp_dir) + + collector = HeatmapCollector(sample_interval_usec=1000) + + frame = MockFrameInfo("test.py", 10, "process") + frame.location = LocationInfo(10, 12, 0, 30) + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame])] + ) + ] + collector.collect(frames) + + # Export should work + with (captured_stdout(), captured_stderr()): + collector.export(tmp_dir) + self.assertTrue(os.path.exists(os.path.join(tmp_dir, "index.html"))) + + def test_heatmap_collector_frame_format(self): + """Test HeatmapCollector with 4-element frame format.""" + collector = HeatmapCollector(sample_interval_usec=1000) + + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("app.py", 100, "main", opcode=90), + MockFrameInfo("utils.py", 50, "helper", opcode=100), + MockFrameInfo("lib.py", 25, "process", opcode=None), + ], + ) + ], + ) + ] + collector.collect(frames) + + # Should have recorded data for the files + self.assertIn("app.py", collector.file_samples) + self.assertIn("utils.py", collector.file_samples) + self.assertIn("lib.py", collector.file_samples) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/__init__.py b/Lib/test/test_profiling/test_sampling_profiler/__init__.py new file mode 100644 index 00000000000..616ae5b49f0 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/__init__.py @@ -0,0 +1,9 @@ +"""Tests for the sampling profiler (profiling.sampling).""" + +import os +from test.support import load_package_tests + + +def load_tests(*args): + """Load all tests from this subpackage.""" + return load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_profiling/test_sampling_profiler/_live_collector_helpers.py b/Lib/test/test_profiling/test_sampling_profiler/_live_collector_helpers.py new file mode 100644 index 00000000000..2c672895099 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/_live_collector_helpers.py @@ -0,0 +1,62 @@ +"""Common test helpers and mocks for live collector tests.""" + +from collections import namedtuple + +from profiling.sampling.constants import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, +) + + +# Matches the C structseq LocationInfo from _remote_debugging +LocationInfo = namedtuple('LocationInfo', ['lineno', 'end_lineno', 'col_offset', 'end_col_offset']) + + +class MockFrameInfo: + """Mock FrameInfo for testing. + + Frame format: (filename, location, funcname, opcode) where: + - location is a tuple (lineno, end_lineno, col_offset, end_col_offset) + - opcode is an int or None + """ + + def __init__(self, filename, lineno, funcname, opcode=None): + self.filename = filename + self.funcname = funcname + self.opcode = opcode + self.location = LocationInfo(lineno, lineno, -1, -1) + + def __iter__(self): + return iter((self.filename, self.location, self.funcname, self.opcode)) + + def __getitem__(self, index): + return (self.filename, self.location, self.funcname, self.opcode)[index] + + def __len__(self): + return 4 + + def __repr__(self): + return f"MockFrameInfo('{self.filename}', {self.location}, '{self.funcname}', {self.opcode})" + + +class MockThreadInfo: + """Mock ThreadInfo for testing.""" + + def __init__(self, thread_id, frame_info, status=THREAD_STATUS_HAS_GIL | THREAD_STATUS_ON_CPU): + self.thread_id = thread_id + self.frame_info = frame_info + self.status = status + + def __repr__(self): + return f"MockThreadInfo(thread_id={self.thread_id}, frame_info={self.frame_info}, status={self.status})" + + +class MockInterpreterInfo: + """Mock InterpreterInfo for testing.""" + + def __init__(self, interpreter_id, threads): + self.interpreter_id = interpreter_id + self.threads = threads + + def __repr__(self): + return f"MockInterpreterInfo(interpreter_id={self.interpreter_id}, threads={self.threads})" diff --git a/Lib/test/test_profiling/test_sampling_profiler/helpers.py b/Lib/test/test_profiling/test_sampling_profiler/helpers.py new file mode 100644 index 00000000000..b07776d415b --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/helpers.py @@ -0,0 +1,202 @@ +"""Helper utilities for sampling profiler tests.""" + +import contextlib +import socket +import subprocess +import sys +import unittest +from collections import namedtuple + +from test.support import SHORT_TIMEOUT +from test.support.socket_helper import find_unused_port +from test.support.os_helper import unlink + + +PROCESS_VM_READV_SUPPORTED = False + +try: + from _remote_debugging import PROCESS_VM_READV_SUPPORTED # noqa: F401 + import _remote_debugging # noqa: F401 +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) +else: + import profiling.sampling # noqa: F401 + from profiling.sampling.sample import SampleProfiler # noqa: F401 + + +skip_if_not_supported = unittest.skipIf( + ( + sys.platform != "darwin" + and sys.platform != "linux" + and sys.platform != "win32" + ), + "Test only runs on Linux, Windows and MacOS", +) + +SubprocessInfo = namedtuple("SubprocessInfo", ["process", "socket"]) + + +def _wait_for_signal(sock, expected_signals, timeout=SHORT_TIMEOUT): + """ + Wait for expected signal(s) from a socket with proper timeout and EOF handling. + + Args: + sock: Connected socket to read from + expected_signals: Single bytes object or list of bytes objects to wait for + timeout: Socket timeout in seconds + + Returns: + bytes: Complete accumulated response buffer + + Raises: + RuntimeError: If connection closed before signal received or timeout + """ + if isinstance(expected_signals, bytes): + expected_signals = [expected_signals] + + sock.settimeout(timeout) + buffer = b"" + + while True: + # Check if all expected signals are in buffer + if all(sig in buffer for sig in expected_signals): + return buffer + + try: + chunk = sock.recv(4096) + if not chunk: + raise RuntimeError( + f"Connection closed before receiving expected signals. " + f"Expected: {expected_signals}, Got: {buffer[-200:]!r}" + ) + buffer += chunk + except socket.timeout: + raise RuntimeError( + f"Timeout waiting for signals. " + f"Expected: {expected_signals}, Got: {buffer[-200:]!r}" + ) from None + except OSError as e: + raise RuntimeError( + f"Socket error while waiting for signals: {e}. " + f"Expected: {expected_signals}, Got: {buffer[-200:]!r}" + ) from None + + +def _cleanup_sockets(*sockets): + """Safely close multiple sockets, ignoring errors.""" + for sock in sockets: + if sock is not None: + try: + sock.close() + except OSError: + pass + + +def _cleanup_process(proc, timeout=SHORT_TIMEOUT): + """Terminate a process gracefully, escalating to kill if needed.""" + if proc.poll() is not None: + return + proc.terminate() + try: + proc.wait(timeout=timeout) + return + except subprocess.TimeoutExpired: + pass + proc.kill() + try: + proc.wait(timeout=timeout) + except subprocess.TimeoutExpired: + pass # Process refuses to die, nothing more we can do + + +@contextlib.contextmanager +def test_subprocess(script, wait_for_working=False): + """Context manager to create a test subprocess with socket synchronization. + + Args: + script: Python code to execute in the subprocess. If wait_for_working + is True, script should send b"working" after starting work. + wait_for_working: If True, wait for both "ready" and "working" signals. + Default False for backward compatibility. + + Yields: + SubprocessInfo: Named tuple with process and socket objects + """ + # Find an unused port for socket communication + port = find_unused_port() + + # Inject socket connection code at the beginning of the script + socket_code = f""" +import socket +_test_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) +_test_sock.connect(('localhost', {port})) +_test_sock.sendall(b"ready") +""" + + # Combine socket code with user script + full_script = socket_code + script + + # Create server socket to wait for process to be ready + server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server_socket.bind(("localhost", port)) + server_socket.settimeout(SHORT_TIMEOUT) + server_socket.listen(1) + + proc = subprocess.Popen( + [sys.executable, "-c", full_script], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + client_socket = None + try: + # Wait for process to connect and send ready signal + client_socket, _ = server_socket.accept() + server_socket.close() + server_socket = None + + # Wait for ready signal, and optionally working signal + if wait_for_working: + _wait_for_signal(client_socket, [b"ready", b"working"]) + else: + _wait_for_signal(client_socket, b"ready") + + yield SubprocessInfo(proc, client_socket) + finally: + _cleanup_sockets(client_socket, server_socket) + _cleanup_process(proc) + + +def close_and_unlink(file): + """Close a file and unlink it from the filesystem.""" + file.close() + unlink(file.name) + + +def jsonl_tables(records): + """Extract the canonical sections of a parsed JSONL profile. + + Returns ``(meta, str_defs, frame_defs, agg, end)`` where ``str_defs`` is a + ``{str_id: value}`` dict, ``frame_defs`` is a flat list of all frame + definitions across chunks, and ``agg`` is the first agg record (sufficient + for tests that only emit one chunk). + """ + meta = next(record for record in records if record["type"] == "meta") + end = next(record for record in records if record["type"] == "end") + agg = next(record for record in records if record["type"] == "agg") + str_defs = { + item["str_id"]: item["value"] + for record in records + if record["type"] == "string_table" + for item in record["strings"] + } + frame_defs = [ + item + for record in records + if record["type"] == "frame_table" + for item in record["frames"] + ] + return meta, str_defs, frame_defs, agg, end diff --git a/Lib/test/test_profiling/test_sampling_profiler/mocks.py b/Lib/test/test_profiling/test_sampling_profiler/mocks.py new file mode 100644 index 00000000000..128870ffd4d --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/mocks.py @@ -0,0 +1,116 @@ +"""Mock classes for sampling profiler tests.""" + +from collections import namedtuple + +# Matches the C structseq LocationInfo from _remote_debugging +LocationInfo = namedtuple('LocationInfo', ['lineno', 'end_lineno', 'col_offset', 'end_col_offset']) + + +class MockFrameInfo: + """Mock FrameInfo for testing. + + Frame format: (filename, location, funcname, opcode) where: + - location is a tuple (lineno, end_lineno, col_offset, end_col_offset) + - opcode is an int or None + """ + + def __init__(self, filename, lineno, funcname, opcode=None): + self.filename = filename + self.funcname = funcname + self.opcode = opcode + self.location = LocationInfo(lineno, lineno, -1, -1) + + def __iter__(self): + return iter((self.filename, self.location, self.funcname, self.opcode)) + + def __getitem__(self, index): + return (self.filename, self.location, self.funcname, self.opcode)[index] + + def __len__(self): + return 4 + + def __repr__(self): + return f"MockFrameInfo('{self.filename}', {self.location}, '{self.funcname}', {self.opcode})" + + +class MockThreadInfo: + """Mock ThreadInfo for testing since the real one isn't accessible.""" + + def __init__( + self, thread_id, frame_info, status=0 + ): # Default to THREAD_STATE_RUNNING (0) + self.thread_id = thread_id + self.frame_info = frame_info + self.status = status + + def __repr__(self): + return f"MockThreadInfo(thread_id={self.thread_id}, frame_info={self.frame_info}, status={self.status})" + + +class MockInterpreterInfo: + """Mock InterpreterInfo for testing since the real one isn't accessible.""" + + def __init__(self, interpreter_id, threads): + self.interpreter_id = interpreter_id + self.threads = threads + + def __repr__(self): + return f"MockInterpreterInfo(interpreter_id={self.interpreter_id}, threads={self.threads})" + + +class MockCoroInfo: + """Mock CoroInfo for testing async tasks.""" + + def __init__(self, task_name, call_stack): + self.task_name = task_name # In reality, this is the parent task ID + self.call_stack = call_stack + + def __repr__(self): + return f"MockCoroInfo(task_name={self.task_name}, call_stack={self.call_stack})" + + +class MockTaskInfo: + """Mock TaskInfo for testing async tasks.""" + + def __init__(self, task_id, task_name, coroutine_stack, awaited_by=None): + self.task_id = task_id + self.task_name = task_name + self.coroutine_stack = coroutine_stack # List of CoroInfo objects + self.awaited_by = awaited_by or [] # List of CoroInfo objects (parents) + + def __repr__(self): + return f"MockTaskInfo(task_id={self.task_id}, task_name={self.task_name})" + + +class MockAwaitedInfo: + """Mock AwaitedInfo for testing async tasks.""" + + def __init__(self, thread_id, awaited_by): + self.thread_id = thread_id + self.awaited_by = awaited_by # List of TaskInfo objects + + def __repr__(self): + return f"MockAwaitedInfo(thread_id={self.thread_id}, awaited_by={len(self.awaited_by)} tasks)" + + +def make_diff_collector_with_mock_baseline( + baseline_samples, *, baseline_interval=1000, current_interval=1000 +): + """Create a DiffFlamegraphCollector with baseline injected directly, + skipping the binary round-trip that _load_baseline normally does.""" + from profiling.sampling.stack_collector import ( + DiffFlamegraphCollector, + FlamegraphCollector, + ) + + baseline = FlamegraphCollector(baseline_interval) + for sample in baseline_samples: + baseline.collect(sample) + + # Path is unused since we inject _baseline_collector directly; + # use __file__ as a dummy path that passes the existence check. + diff = DiffFlamegraphCollector( + current_interval, baseline_binary_path=__file__ + ) + diff._baseline_collector = baseline + return diff diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_advanced.py b/Lib/test/test_profiling/test_sampling_profiler/test_advanced.py new file mode 100644 index 00000000000..11b1ad84242 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_advanced.py @@ -0,0 +1,236 @@ +"""Tests for advanced sampling profiler features (GC tracking, native frames, ProcessPoolExecutor support).""" + +import io +import os +import subprocess +import tempfile +import unittest +from unittest import mock + +try: + import _remote_debugging # noqa: F401 + import profiling.sampling + import profiling.sampling.sample + from profiling.sampling.pstats_collector import PstatsCollector + from profiling.sampling.stack_collector import CollapsedStackCollector +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from test.support import ( + SHORT_TIMEOUT, + SuppressCrashReport, + os_helper, + requires_remote_subprocess_debugging, + script_helper, +) + +from .helpers import close_and_unlink, test_subprocess + + +@requires_remote_subprocess_debugging() +class TestGCFrameTracking(unittest.TestCase): + """Tests for GC frame tracking in the sampling profiler.""" + + @classmethod + def setUpClass(cls): + """Create a static test script with GC frames and CPU-intensive work.""" + cls.gc_test_script = ''' +import gc + +class ExpensiveGarbage: + def __init__(self): + self.cycle = self + + def __del__(self): + result = 0 + for i in range(100000): + result += i * i + if i % 1000 == 0: + result = result % 1000000 + +_test_sock.sendall(b"working") +while True: + ExpensiveGarbage() + gc.collect() +''' + + def test_gc_frames_enabled(self): + """Test that GC frames appear when gc tracking is enabled.""" + with ( + test_subprocess(self.gc_test_script, wait_for_working=True) as subproc, + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=1, + native=False, + gc=True, + ) + collector.print_stats(show_summary=False) + + output = captured_output.getvalue() + + # Should capture samples + self.assertIn("Captured", output) + self.assertIn("samples", output) + + # GC frames should be present + self.assertIn("", output) + + def test_gc_frames_disabled(self): + """Test that GC frames do not appear when gc tracking is disabled.""" + with ( + test_subprocess(self.gc_test_script, wait_for_working=True) as subproc, + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=1, + native=False, + gc=False, + ) + collector.print_stats(show_summary=False) + + output = captured_output.getvalue() + + # Should capture samples + self.assertIn("Captured", output) + self.assertIn("samples", output) + + # GC frames should NOT be present + self.assertNotIn("", output) + + +@requires_remote_subprocess_debugging() +class TestNativeFrameTracking(unittest.TestCase): + """Tests for native frame tracking in the sampling profiler.""" + + @classmethod + def setUpClass(cls): + """Create a static test script with native frames and CPU-intensive work.""" + cls.native_test_script = """ +import operator + +def inner(): + for _ in range(1_000_0000): + pass + +_test_sock.sendall(b"working") +while True: + operator.call(inner) +""" + + def test_native_frames_enabled(self): + """Test that native frames appear when native tracking is enabled.""" + collapsed_file = tempfile.NamedTemporaryFile( + suffix=".txt", delete=False + ) + self.addCleanup(close_and_unlink, collapsed_file) + + with test_subprocess(self.native_test_script, wait_for_working=True) as subproc: + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = CollapsedStackCollector(1000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=1, + native=True, + ) + collector.export(collapsed_file.name) + + # Verify file was created and contains valid data + self.assertTrue(os.path.exists(collapsed_file.name)) + self.assertGreater(os.path.getsize(collapsed_file.name), 0) + + # Check file format + with open(collapsed_file.name, "r") as f: + content = f.read() + + lines = content.strip().split("\n") + self.assertGreater(len(lines), 0) + + stacks = [line.rsplit(" ", 1)[0] for line in lines] + + # Most samples should have native code in the middle of the stack: + self.assertTrue(any(";;" in stack for stack in stacks)) + + # No samples should have native code at the top of the stack: + self.assertFalse(any(stack.endswith(";") for stack in stacks)) + + def test_native_frames_disabled(self): + """Test that native frames do not appear when native tracking is disabled.""" + with ( + test_subprocess(self.native_test_script, wait_for_working=True) as subproc, + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=1, + ) + collector.print_stats(show_summary=False) + output = captured_output.getvalue() + # Native frames should NOT be present: + self.assertNotIn("", output) + + +@requires_remote_subprocess_debugging() +class TestProcessPoolExecutorSupport(unittest.TestCase): + """ + Test that ProcessPoolExecutor works correctly with profiling.sampling. + """ + + def test_process_pool_executor_pickle(self): + # gh-140729: test use ProcessPoolExecutor.map() can sampling + test_script = """ +import concurrent.futures + +def worker(x): + return x * 2 + +if __name__ == "__main__": + with concurrent.futures.ProcessPoolExecutor() as executor: + results = list(executor.map(worker, [1, 2, 3])) + print(f"Results: {results}") +""" + with os_helper.temp_dir() as temp_dir: + script = script_helper.make_script( + temp_dir, "test_process_pool_executor_pickle", test_script + ) + with SuppressCrashReport(): + with script_helper.spawn_python( + "-m", + "profiling.sampling", + "run", + "-d", + "5", + "-r", + "10", + script, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) as proc: + try: + stdout, stderr = proc.communicate( + timeout=SHORT_TIMEOUT + ) + except subprocess.TimeoutExpired: + proc.kill() + stdout, stderr = proc.communicate() + + self.assertIn("Results: [2, 4, 6]", stdout) + self.assertNotIn("Can't pickle", stderr) diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_async.py b/Lib/test/test_profiling/test_sampling_profiler/test_async.py new file mode 100644 index 00000000000..1f5685717b6 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_async.py @@ -0,0 +1,787 @@ +"""Tests for async stack reconstruction in the sampling profiler. + +Each test covers a distinct algorithm path or edge case: +1. Graph building: _build_task_graph() +2. Leaf identification: _find_leaf_tasks() +3. Stack traversal: _build_linear_stacks() with BFS +""" + +import inspect +import unittest + +try: + import _remote_debugging # noqa: F401 + from profiling.sampling.pstats_collector import PstatsCollector + from profiling.sampling.stack_collector import FlamegraphCollector + from profiling.sampling.sample import sample, sample_live, SampleProfiler +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from .mocks import MockFrameInfo, MockCoroInfo, MockTaskInfo, MockAwaitedInfo + + +class TestAsyncStackReconstruction(unittest.TestCase): + """Test async task tree linear stack reconstruction algorithm.""" + + def test_empty_input(self): + """Test _build_task_graph with empty awaited_info_list.""" + collector = PstatsCollector(sample_interval_usec=1000) + stacks = list(collector._iter_async_frames([])) + self.assertEqual(len(stacks), 0) + + def test_single_root_task(self): + """Test _find_leaf_tasks: root task with no parents is its own leaf.""" + collector = PstatsCollector(sample_interval_usec=1000) + + root = MockTaskInfo( + task_id=123, + task_name="Task-1", + coroutine_stack=[ + MockCoroInfo( + task_name="Task-1", + call_stack=[MockFrameInfo("main.py", 10, "main")] + ) + ], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=100, awaited_by=[root])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # Single root is both leaf and root + self.assertEqual(len(stacks), 1) + frames, thread_id, leaf_id = stacks[0] + self.assertEqual(leaf_id, 123) + self.assertEqual(thread_id, 100) + + def test_parent_child_chain(self): + """Test _build_linear_stacks: BFS follows parent links from leaf to root. + + Task graph: + + Parent (id=1) + | + Child (id=2) + """ + collector = PstatsCollector(sample_interval_usec=1000) + + child = MockTaskInfo( + task_id=2, + task_name="Child", + coroutine_stack=[ + MockCoroInfo(task_name="Child", call_stack=[MockFrameInfo("c.py", 5, "child_fn")]) + ], + awaited_by=[ + MockCoroInfo(task_name=1, call_stack=[MockFrameInfo("p.py", 10, "parent_await")]) + ] + ) + + parent = MockTaskInfo( + task_id=1, + task_name="Parent", + coroutine_stack=[ + MockCoroInfo(task_name="Parent", call_stack=[MockFrameInfo("p.py", 15, "parent_fn")]) + ], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=200, awaited_by=[child, parent])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # Leaf is child, traverses to parent + self.assertEqual(len(stacks), 1) + frames, thread_id, leaf_id = stacks[0] + self.assertEqual(leaf_id, 2) + + # Verify both child and parent frames present + func_names = [f.funcname for f in frames] + self.assertIn("child_fn", func_names) + self.assertIn("parent_fn", func_names) + + def test_multiple_leaf_tasks(self): + """Test _find_leaf_tasks: identifies multiple leaves correctly. + + Task graph (fan-out from root): + + Root (id=1) + / \ + Leaf1 (id=10) Leaf2 (id=20) + + Expected: 2 stacks (one for each leaf). + """ + collector = PstatsCollector(sample_interval_usec=1000) + leaf1 = MockTaskInfo( + task_id=10, + task_name="Leaf1", + coroutine_stack=[MockCoroInfo(task_name="Leaf1", call_stack=[MockFrameInfo("l1.py", 1, "f1")])], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[MockFrameInfo("r.py", 5, "root")])] + ) + + leaf2 = MockTaskInfo( + task_id=20, + task_name="Leaf2", + coroutine_stack=[MockCoroInfo(task_name="Leaf2", call_stack=[MockFrameInfo("l2.py", 2, "f2")])], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[MockFrameInfo("r.py", 5, "root")])] + ) + + root = MockTaskInfo( + task_id=1, + task_name="Root", + coroutine_stack=[MockCoroInfo(task_name="Root", call_stack=[MockFrameInfo("r.py", 10, "main")])], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=300, awaited_by=[leaf1, leaf2, root])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # Two leaves = two stacks + self.assertEqual(len(stacks), 2) + leaf_ids = {leaf_id for _, _, leaf_id in stacks} + self.assertEqual(leaf_ids, {10, 20}) + + def test_cycle_detection(self): + """Test _build_linear_stacks: cycle detection prevents infinite loops. + + Task graph (cyclic dependency): + + A (id=1) <---> B (id=2) + + Neither task is a leaf (both have parents), so no stacks are produced. + """ + collector = PstatsCollector(sample_interval_usec=1000) + task_a = MockTaskInfo( + task_id=1, + task_name="A", + coroutine_stack=[MockCoroInfo(task_name="A", call_stack=[MockFrameInfo("a.py", 1, "a")])], + awaited_by=[MockCoroInfo(task_name=2, call_stack=[MockFrameInfo("b.py", 5, "b")])] + ) + + task_b = MockTaskInfo( + task_id=2, + task_name="B", + coroutine_stack=[MockCoroInfo(task_name="B", call_stack=[MockFrameInfo("b.py", 10, "b")])], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[MockFrameInfo("a.py", 15, "a")])] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=400, awaited_by=[task_a, task_b])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # No leaves (both have parents), should return empty + self.assertEqual(len(stacks), 0) + + def test_orphaned_parent_reference(self): + """Test _build_linear_stacks: handles parent ID not in task_map.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Task references non-existent parent + orphan = MockTaskInfo( + task_id=5, + task_name="Orphan", + coroutine_stack=[MockCoroInfo(task_name="Orphan", call_stack=[MockFrameInfo("o.py", 1, "orphan")])], + awaited_by=[MockCoroInfo(task_name=999, call_stack=[])] # 999 doesn't exist + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=500, awaited_by=[orphan])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # Stops at missing parent, yields what it has + self.assertEqual(len(stacks), 1) + frames, _, leaf_id = stacks[0] + self.assertEqual(leaf_id, 5) + + def test_multiple_coroutines_per_task(self): + """Test _build_linear_stacks: collects frames from all coroutines in task.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Task with multiple coroutines (e.g., nested async generators) + task = MockTaskInfo( + task_id=7, + task_name="Multi", + coroutine_stack=[ + MockCoroInfo(task_name="Multi", call_stack=[MockFrameInfo("g.py", 5, "gen1")]), + MockCoroInfo(task_name="Multi", call_stack=[MockFrameInfo("g.py", 10, "gen2")]), + ], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=600, awaited_by=[task])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + self.assertEqual(len(stacks), 1) + frames, _, _ = stacks[0] + + # Both coroutine frames should be present + func_names = [f.funcname for f in frames] + self.assertIn("gen1", func_names) + self.assertIn("gen2", func_names) + + def test_multiple_threads(self): + """Test _build_task_graph: handles multiple AwaitedInfo (different threads).""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Two threads with separate task trees + thread1_task = MockTaskInfo( + task_id=100, + task_name="T1", + coroutine_stack=[MockCoroInfo(task_name="T1", call_stack=[MockFrameInfo("t1.py", 1, "t1")])], + awaited_by=[] + ) + + thread2_task = MockTaskInfo( + task_id=200, + task_name="T2", + coroutine_stack=[MockCoroInfo(task_name="T2", call_stack=[MockFrameInfo("t2.py", 1, "t2")])], + awaited_by=[] + ) + + awaited_info_list = [ + MockAwaitedInfo(thread_id=1, awaited_by=[thread1_task]), + MockAwaitedInfo(thread_id=2, awaited_by=[thread2_task]), + ] + + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # Two threads = two stacks + self.assertEqual(len(stacks), 2) + + # Verify thread IDs preserved + thread_ids = {thread_id for _, thread_id, _ in stacks} + self.assertEqual(thread_ids, {1, 2}) + + def test_collect_public_interface(self): + """Test collect() method correctly routes to async frame processing.""" + collector = PstatsCollector(sample_interval_usec=1000) + + child = MockTaskInfo( + task_id=50, + task_name="Child", + coroutine_stack=[MockCoroInfo(task_name="Child", call_stack=[MockFrameInfo("c.py", 1, "child")])], + awaited_by=[MockCoroInfo(task_name=51, call_stack=[])] + ) + + parent = MockTaskInfo( + task_id=51, + task_name="Parent", + coroutine_stack=[MockCoroInfo(task_name="Parent", call_stack=[MockFrameInfo("p.py", 1, "parent")])], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=999, awaited_by=[child, parent])] + + # Public interface: collect() + collector.collect(awaited_info_list) + + # Verify stats collected + self.assertGreater(len(collector.result), 0) + func_names = [loc[2] for loc in collector.result.keys()] + self.assertIn("child", func_names) + self.assertIn("parent", func_names) + + def test_diamond_pattern_multiple_parents(self): + """Test _build_linear_stacks: task with 2+ parents picks one deterministically. + + CRITICAL: Tests that when a task has multiple parents, we pick one parent + deterministically (sorted, first one) and annotate the task name with parent count. + """ + collector = PstatsCollector(sample_interval_usec=1000) + + # Diamond pattern: Root spawns A and B, both await Child + # + # Root (id=1) + # / \ + # A (id=2) B (id=3) + # \ / + # Child (id=4) + # + + child = MockTaskInfo( + task_id=4, + task_name="Child", + coroutine_stack=[MockCoroInfo(task_name="Child", call_stack=[MockFrameInfo("c.py", 1, "child_work")])], + awaited_by=[ + MockCoroInfo(task_name=2, call_stack=[MockFrameInfo("a.py", 5, "a_await")]), # Parent A + MockCoroInfo(task_name=3, call_stack=[MockFrameInfo("b.py", 5, "b_await")]), # Parent B + ] + ) + + parent_a = MockTaskInfo( + task_id=2, + task_name="A", + coroutine_stack=[MockCoroInfo(task_name="A", call_stack=[MockFrameInfo("a.py", 10, "a_work")])], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[MockFrameInfo("root.py", 5, "root_spawn")])] + ) + + parent_b = MockTaskInfo( + task_id=3, + task_name="B", + coroutine_stack=[MockCoroInfo(task_name="B", call_stack=[MockFrameInfo("b.py", 10, "b_work")])], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[MockFrameInfo("root.py", 5, "root_spawn")])] + ) + + root = MockTaskInfo( + task_id=1, + task_name="Root", + coroutine_stack=[MockCoroInfo(task_name="Root", call_stack=[MockFrameInfo("root.py", 20, "main")])], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=777, awaited_by=[child, parent_a, parent_b, root])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # Should get 1 stack: Child->A->Root (picks parent with lowest ID: 2) + self.assertEqual(len(stacks), 1, "Diamond should create only 1 path, picking first sorted parent") + + # Verify the single stack + frames, thread_id, leaf_id = stacks[0] + self.assertEqual(leaf_id, 4) + self.assertEqual(thread_id, 777) + + func_names = [f.funcname for f in frames] + # Stack should contain child, parent A (id=2, first when sorted), and root + self.assertIn("child_work", func_names) + self.assertIn("a_work", func_names, "Should use parent A (id=2, first when sorted)") + self.assertNotIn("b_work", func_names, "Should not include parent B") + self.assertIn("main", func_names) + + # Verify Child task is annotated with parent count + self.assertIn("Child (2 parents)", func_names, "Child task should be annotated with parent count") + + def test_empty_coroutine_stack(self): + """Test _build_linear_stacks: handles empty coroutine_stack (line 109 condition false).""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Task with no coroutine_stack + task = MockTaskInfo( + task_id=99, + task_name="EmptyStack", + coroutine_stack=[], # Empty! + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=111, awaited_by=[task])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + self.assertEqual(len(stacks), 1) + frames, _, _ = stacks[0] + + # Should only have task marker, no function frames + func_names = [f.funcname for f in frames] + self.assertEqual(len(func_names), 1, "Should only have task marker") + self.assertIn("EmptyStack", func_names) + + def test_orphaned_parent_with_no_frames_collected(self): + """Test _build_linear_stacks: orphaned parent at start with empty frames (line 94-96).""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Leaf that doesn't exist in task_map (should not happen normally, but test robustness) + # We'll create a scenario where the leaf_id is present but empty + + # Task references non-existent parent, and has no coroutine_stack + orphan = MockTaskInfo( + task_id=88, + task_name="Orphan", + coroutine_stack=[], # No frames + awaited_by=[MockCoroInfo(task_name=999, call_stack=[])] # Parent doesn't exist + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=222, awaited_by=[orphan])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # Should yield because we have the task marker even with no function frames + self.assertEqual(len(stacks), 1) + frames, _, leaf_id = stacks[0] + self.assertEqual(leaf_id, 88) + # Has task marker but no function frames + self.assertGreater(len(frames), 0, "Should have at least task marker") + + def test_frame_ordering(self): + """Test _build_linear_stacks: frames are collected in correct order (leaf->root). + + Task graph (3-level chain): + + Root (id=1) <- root_bottom, root_top + | + Middle (id=2) <- mid_bottom, mid_top + | + Leaf (id=3) <- leaf_bottom, leaf_top + + Expected frame order: leaf_bottom, leaf_top, mid_bottom, mid_top, root_bottom, root_top + (stack is built bottom-up: leaf frames first, then parent frames). + """ + collector = PstatsCollector(sample_interval_usec=1000) + leaf = MockTaskInfo( + task_id=3, + task_name="Leaf", + coroutine_stack=[ + MockCoroInfo(task_name="Leaf", call_stack=[ + MockFrameInfo("leaf.py", 1, "leaf_bottom"), + MockFrameInfo("leaf.py", 2, "leaf_top"), + ]) + ], + awaited_by=[MockCoroInfo(task_name=2, call_stack=[])] + ) + + middle = MockTaskInfo( + task_id=2, + task_name="Middle", + coroutine_stack=[ + MockCoroInfo(task_name="Middle", call_stack=[ + MockFrameInfo("mid.py", 1, "mid_bottom"), + MockFrameInfo("mid.py", 2, "mid_top"), + ]) + ], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[])] + ) + + root = MockTaskInfo( + task_id=1, + task_name="Root", + coroutine_stack=[ + MockCoroInfo(task_name="Root", call_stack=[ + MockFrameInfo("root.py", 1, "root_bottom"), + MockFrameInfo("root.py", 2, "root_top"), + ]) + ], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=333, awaited_by=[leaf, middle, root])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + self.assertEqual(len(stacks), 1) + frames, _, _ = stacks[0] + + func_names = [f.funcname for f in frames] + + # Order should be: leaf frames, leaf marker, middle frames, middle marker, root frames, root marker + leaf_bottom_idx = func_names.index("leaf_bottom") + leaf_top_idx = func_names.index("leaf_top") + mid_bottom_idx = func_names.index("mid_bottom") + root_bottom_idx = func_names.index("root_bottom") + + # Verify leaf comes before middle comes before root + self.assertLess(leaf_bottom_idx, leaf_top_idx, "Leaf frames in order") + self.assertLess(leaf_top_idx, mid_bottom_idx, "Leaf before middle") + self.assertLess(mid_bottom_idx, root_bottom_idx, "Middle before root") + + def test_complex_multi_parent_convergence(self): + """Test _build_linear_stacks: multiple leaves with same parents pick deterministically. + + Tests that when multiple leaves have multiple parents, each leaf picks the same + parent (sorted, first one) and all leaves are annotated with parent count. + + Task graph structure (both leaves awaited by both A and B):: + + Root (id=1) + / \\ + A (id=2) B (id=3) + | \\ / | + | \\ / | + | \\/ | + | /\\ | + | / \\ | + LeafX (id=4) LeafY (id=5) + + Expected behavior: Both leaves pick parent A (lowest id=2) for their stack path. + Result: 2 stacks, both going through A -> Root (B is skipped). + """ + collector = PstatsCollector(sample_interval_usec=1000) + + leaf_x = MockTaskInfo( + task_id=4, + task_name="LeafX", + coroutine_stack=[MockCoroInfo(task_name="LeafX", call_stack=[MockFrameInfo("x.py", 1, "x")])], + awaited_by=[ + MockCoroInfo(task_name=2, call_stack=[]), + MockCoroInfo(task_name=3, call_stack=[]), + ] + ) + + leaf_y = MockTaskInfo( + task_id=5, + task_name="LeafY", + coroutine_stack=[MockCoroInfo(task_name="LeafY", call_stack=[MockFrameInfo("y.py", 1, "y")])], + awaited_by=[ + MockCoroInfo(task_name=2, call_stack=[]), + MockCoroInfo(task_name=3, call_stack=[]), + ] + ) + + parent_a = MockTaskInfo( + task_id=2, + task_name="A", + coroutine_stack=[MockCoroInfo(task_name="A", call_stack=[MockFrameInfo("a.py", 1, "a")])], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[])] + ) + + parent_b = MockTaskInfo( + task_id=3, + task_name="B", + coroutine_stack=[MockCoroInfo(task_name="B", call_stack=[MockFrameInfo("b.py", 1, "b")])], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[])] + ) + + root = MockTaskInfo( + task_id=1, + task_name="Root", + coroutine_stack=[MockCoroInfo(task_name="Root", call_stack=[MockFrameInfo("r.py", 1, "root")])], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=444, awaited_by=[leaf_x, leaf_y, parent_a, parent_b, root])] + stacks = list(collector._iter_async_frames(awaited_info_list)) + + # 2 leaves, each picks same parent (A, id=2) = 2 paths + self.assertEqual(len(stacks), 2, "Should create 2 paths: X->A->Root, Y->A->Root") + + # Verify both leaves pick parent A (id=2, first when sorted) + leaf_ids_seen = set() + for frames, _, leaf_id in stacks: + leaf_ids_seen.add(leaf_id) + func_names = [f.funcname for f in frames] + + # Both stacks should go through parent A only + self.assertIn("a", func_names, "Should use parent A (id=2, first when sorted)") + self.assertNotIn("b", func_names, "Should not include parent B") + self.assertIn("root", func_names, "Should reach root") + + # Check for parent count annotation on the leaf + if leaf_id == 4: + self.assertIn("x", func_names) + self.assertIn("LeafX (2 parents)", func_names, "LeafX should be annotated with parent count") + elif leaf_id == 5: + self.assertIn("y", func_names) + self.assertIn("LeafY (2 parents)", func_names, "LeafY should be annotated with parent count") + + # Both leaves should be represented + self.assertEqual(leaf_ids_seen, {4, 5}, "Both LeafX and LeafY should have paths") + + +class TestFlamegraphCollectorAsync(unittest.TestCase): + """Test FlamegraphCollector with async frames.""" + + def test_flamegraph_with_async_frames(self): + """Test FlamegraphCollector correctly processes async task frames.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + # Build async task tree: Root -> Child + child = MockTaskInfo( + task_id=2, + task_name="ChildTask", + coroutine_stack=[ + MockCoroInfo( + task_name="ChildTask", + call_stack=[MockFrameInfo("child.py", 10, "child_work")] + ) + ], + awaited_by=[MockCoroInfo(task_name=1, call_stack=[])] + ) + + root = MockTaskInfo( + task_id=1, + task_name="RootTask", + coroutine_stack=[ + MockCoroInfo( + task_name="RootTask", + call_stack=[MockFrameInfo("root.py", 20, "root_work")] + ) + ], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=100, awaited_by=[child, root])] + + # Collect async frames + collector.collect(awaited_info_list) + + # Verify samples were collected + self.assertGreater(collector._total_samples, 0) + + # Verify the flamegraph tree structure contains our functions + root_node = collector._root + self.assertGreater(root_node["samples"], 0) + + # Check that thread ID was tracked + self.assertIn(100, collector._all_threads) + + def test_flamegraph_with_task_markers(self): + """Test FlamegraphCollector includes boundary markers.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + task = MockTaskInfo( + task_id=42, + task_name="MyTask", + coroutine_stack=[ + MockCoroInfo( + task_name="MyTask", + call_stack=[MockFrameInfo("work.py", 5, "do_work")] + ) + ], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=200, awaited_by=[task])] + collector.collect(awaited_info_list) + + # Find marker in the tree + def find_task_marker(node, depth=0): + for func, child in node.get("children", {}).items(): + if func[0] == "": + return func + result = find_task_marker(child, depth + 1) + if result: + return result + return None + + task_marker = find_task_marker(collector._root) + self.assertIsNotNone(task_marker, "Should have marker in tree") + self.assertEqual(task_marker[0], "") + self.assertIn("MyTask", task_marker[2]) + + def test_flamegraph_multiple_async_samples(self): + """Test FlamegraphCollector aggregates multiple async samples correctly.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + task = MockTaskInfo( + task_id=1, + task_name="Task", + coroutine_stack=[ + MockCoroInfo( + task_name="Task", + call_stack=[MockFrameInfo("work.py", 10, "work")] + ) + ], + awaited_by=[] + ) + + awaited_info_list = [MockAwaitedInfo(thread_id=300, awaited_by=[task])] + + # Collect multiple samples + for _ in range(5): + collector.collect(awaited_info_list) + + # Verify sample count + self.assertEqual(collector._sample_count, 5) + self.assertEqual(collector._total_samples, 5) + + +class TestAsyncAwareParameterFlow(unittest.TestCase): + """Integration tests for async_aware parameter flow from CLI to unwinder.""" + + def test_sample_function_accepts_async_aware(self): + """Test that sample() function accepts async_aware parameter.""" + sig = inspect.signature(sample) + self.assertIn("async_aware", sig.parameters) + + def test_sample_live_function_accepts_async_aware(self): + """Test that sample_live() function accepts async_aware parameter.""" + sig = inspect.signature(sample_live) + self.assertIn("async_aware", sig.parameters) + + def test_sample_profiler_sample_accepts_async_aware(self): + """Test that SampleProfiler.sample() accepts async_aware parameter.""" + sig = inspect.signature(SampleProfiler.sample) + self.assertIn("async_aware", sig.parameters) + + def test_async_aware_all_sees_sleeping_and_running_tasks(self): + """Test async_aware='all' captures both sleeping and CPU-running tasks.""" + # Sleeping task (awaiting) + sleeping_task = MockTaskInfo( + task_id=1, + task_name="SleepingTask", + coroutine_stack=[ + MockCoroInfo( + task_name="SleepingTask", + call_stack=[MockFrameInfo("sleeper.py", 10, "sleep_work")] + ) + ], + awaited_by=[] + ) + + # CPU-running task (active) + running_task = MockTaskInfo( + task_id=2, + task_name="RunningTask", + coroutine_stack=[ + MockCoroInfo( + task_name="RunningTask", + call_stack=[MockFrameInfo("runner.py", 20, "cpu_work")] + ) + ], + awaited_by=[] + ) + + # Both tasks returned by get_all_awaited_by + awaited_info_list = [MockAwaitedInfo(thread_id=100, awaited_by=[sleeping_task, running_task])] + + collector = PstatsCollector(sample_interval_usec=1000) + collector.collect(awaited_info_list) + collector.create_stats() + + # Both tasks should be visible + sleeping_key = ("sleeper.py", 10, "sleep_work") + running_key = ("runner.py", 20, "cpu_work") + + self.assertIn(sleeping_key, collector.stats) + self.assertIn(running_key, collector.stats) + + # Task markers should also be present + task_keys = [k for k in collector.stats if k[0] == ""] + self.assertGreater(len(task_keys), 0, "Should have markers in stats") + + # Verify task names are in the markers + task_names = [k[2] for k in task_keys] + self.assertTrue( + any("SleepingTask" in name for name in task_names), + "SleepingTask should be in task markers" + ) + self.assertTrue( + any("RunningTask" in name for name in task_names), + "RunningTask should be in task markers" + ) + + def test_async_aware_running_sees_only_running_task(self): + """Test async_aware='running' only shows the currently running task stack.""" + # Only the running task's stack is returned by get_async_stack_trace + running_task = MockTaskInfo( + task_id=2, + task_name="RunningTask", + coroutine_stack=[ + MockCoroInfo( + task_name="RunningTask", + call_stack=[MockFrameInfo("runner.py", 20, "cpu_work")] + ) + ], + awaited_by=[] + ) + + # get_async_stack_trace only returns the running task + awaited_info_list = [MockAwaitedInfo(thread_id=100, awaited_by=[running_task])] + + collector = PstatsCollector(sample_interval_usec=1000) + collector.collect(awaited_info_list) + collector.create_stats() + + # Only running task should be visible + running_key = ("runner.py", 20, "cpu_work") + self.assertIn(running_key, collector.stats) + + # Verify we don't see the sleeping task (it wasn't in the input) + sleeping_key = ("sleeper.py", 10, "sleep_work") + self.assertNotIn(sleeping_key, collector.stats) + + # Task marker for running task should be present + task_keys = [k for k in collector.stats if k[0] == ""] + self.assertGreater(len(task_keys), 0, "Should have markers in stats") + + task_names = [k[2] for k in task_keys] + self.assertTrue( + any("RunningTask" in name for name in task_names), + "RunningTask should be in task markers" + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py b/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py new file mode 100644 index 00000000000..66a9c68a61c --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_binary_format.py @@ -0,0 +1,2018 @@ +"""Tests for binary format round-trip functionality.""" + +import json +import os +import pathlib +import random +import struct +import tempfile +import unittest +from unittest import mock +from collections import defaultdict + +from test.support import captured_stderr + +try: + import _remote_debugging + from _remote_debugging import ( + InterpreterInfo, + ThreadInfo, + FrameInfo, + LocationInfo, + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_UNKNOWN, + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_HAS_EXCEPTION, + THREAD_STATUS_MAIN_THREAD, + ) + from profiling.sampling.binary_collector import BinaryCollector + from profiling.sampling.binary_reader import BinaryReader, convert_binary_to_format + from profiling.sampling.constants import PROFILING_MODE_CPU + from profiling.sampling.gecko_collector import GeckoCollector + + ZSTD_AVAILABLE = _remote_debugging.zstd_available() +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from .helpers import jsonl_tables + + +def make_frame(filename, lineno, funcname, end_lineno=None, column=None, + end_column=None, opcode=None): + """Create a FrameInfo struct sequence with full location info and opcode.""" + if end_lineno is None: + end_lineno = lineno + if column is None: + column = 0 + if end_column is None: + end_column = 0 + location = LocationInfo((lineno, end_lineno, column, end_column)) + return FrameInfo((filename, location, funcname, opcode)) + + +def make_thread(thread_id, frames, status=0): + """Create a ThreadInfo struct sequence.""" + return ThreadInfo((thread_id, status, frames)) + + +def make_interpreter(interp_id, threads): + """Create an InterpreterInfo struct sequence.""" + return InterpreterInfo((interp_id, threads)) + + +def extract_lineno(location): + """Extract line number from location (tuple or int or None).""" + if location is None: + return 0 # Treat None as 0 + if isinstance(location, tuple): + return location[0] if location[0] is not None else 0 + return location + + +def extract_location(location): + """Extract full location info as dict from location tuple or None.""" + if location is None: + return {"lineno": 0, "end_lineno": 0, "column": 0, "end_column": 0} + if isinstance(location, tuple) and len(location) >= 4: + return { + "lineno": location[0] if location[0] is not None else 0, + "end_lineno": location[1] if location[1] is not None else 0, + "column": location[2] if location[2] is not None else 0, + "end_column": location[3] if location[3] is not None else 0, + } + # Fallback for old-style location + lineno = location[0] if isinstance(location, tuple) else location + return {"lineno": lineno or 0, "end_lineno": lineno or 0, "column": 0, "end_column": 0} + + +def frame_to_dict(frame): + """Convert a FrameInfo to a dict.""" + loc = extract_location(frame.location) + return { + "filename": frame.filename, + "funcname": frame.funcname, + "lineno": loc["lineno"], + "end_lineno": loc["end_lineno"], + "column": loc["column"], + "end_column": loc["end_column"], + "opcode": frame.opcode, + } + + +class RawCollector: + """Collector that captures all raw data grouped by thread.""" + + def __init__(self): + # Key: (interpreter_id, thread_id) -> list of samples for that thread + self.by_thread = defaultdict(list) + self.total_count = 0 + + def collect(self, stack_frames, timestamps_us): + """Capture the raw sample data.""" + # timestamps_us is a list; add one sample per timestamp + count = len(timestamps_us) + for interp in stack_frames: + for thread in interp.threads: + frames = [frame_to_dict(f) for f in thread.frame_info] + key = (interp.interpreter_id, thread.thread_id) + sample = {"status": thread.status, "frames": frames} + for _ in range(count): + self.by_thread[key].append(sample) + self.total_count += count + + def export(self, filename): + pass + + +def samples_to_by_thread(samples): + """Convert input samples to by-thread format for comparison.""" + by_thread = defaultdict(list) + for sample in samples: + for interp in sample: + for thread in interp.threads: + frames = [frame_to_dict(f) for f in thread.frame_info] + key = (interp.interpreter_id, thread.thread_id) + by_thread[key].append( + { + "status": thread.status, + "frames": frames, + } + ) + return by_thread + + +class BinaryFormatTestBase(unittest.TestCase): + """Base class with common setup/teardown for binary format tests.""" + + def setUp(self): + self.temp_files = [] + + def tearDown(self): + for f in self.temp_files: + if os.path.exists(f): + os.unlink(f) + + def create_binary_file(self, samples, interval=1000, compression="none", + mode=None, capture_config=None): + """Create a test binary file and track it for cleanup.""" + filename, _ = self.write_binary_file( + samples, interval, compression, mode, capture_config + ) + return filename + + def write_binary_file(self, samples, interval=1000, compression="none", + mode=None, capture_config=None): + """Like create_binary_file but also returns the writer collector.""" + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + collector = BinaryCollector( + filename, interval, compression=compression, mode=mode, + capture_config=capture_config, + ) + for sample in samples: + collector.collect(sample) + collector.export(None) + return filename, collector + + def roundtrip(self, samples, interval=1000, compression="none"): + """Write samples to binary and read back.""" + filename = self.create_binary_file(samples, interval, compression) + collector = RawCollector() + with BinaryReader(filename) as reader: + count = reader.replay_samples(collector) + return collector, count + + def assert_samples_equal(self, expected_samples, collector): + """Assert that roundtripped samples match input exactly, per-thread.""" + expected = samples_to_by_thread(expected_samples) + + # Same threads present + self.assertEqual( + set(expected.keys()), + set(collector.by_thread.keys()), + "Thread set mismatch", + ) + + # For each thread, samples match in order + for key in expected: + exp_samples = expected[key] + act_samples = collector.by_thread[key] + interp_id, thread_id = key + + self.assertEqual( + len(exp_samples), + len(act_samples), + f"Thread ({interp_id}, {thread_id}): sample count mismatch " + f"(expected {len(exp_samples)}, got {len(act_samples)})", + ) + + for i, (exp, act) in enumerate(zip(exp_samples, act_samples)): + self.assertEqual( + exp["status"], + act["status"], + f"Thread ({interp_id}, {thread_id}), sample {i}: " + f"status mismatch (expected {exp['status']}, got {act['status']})", + ) + + self.assertEqual( + len(exp["frames"]), + len(act["frames"]), + f"Thread ({interp_id}, {thread_id}), sample {i}: " + f"frame count mismatch", + ) + + for j, (exp_frame, act_frame) in enumerate( + zip(exp["frames"], act["frames"]) + ): + for field in ("filename", "funcname", "lineno", "end_lineno", + "column", "end_column", "opcode"): + self.assertEqual( + exp_frame[field], + act_frame[field], + f"Thread ({interp_id}, {thread_id}), sample {i}, " + f"frame {j}: {field} mismatch " + f"(expected {exp_frame[field]!r}, got {act_frame[field]!r})", + ) + + +class TestBinaryRoundTrip(BinaryFormatTestBase): + """Tests for exact binary format round-trip.""" + + def test_single_sample_single_frame(self): + """Single sample with one frame roundtrips exactly.""" + samples = [ + [ + make_interpreter( + 0, + [ + make_thread( + 12345, [make_frame("test.py", 42, "myfunc")] + ) + ], + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_single_sample_multi_frame(self): + """Single sample with call stack roundtrips exactly.""" + frames = [ + make_frame("inner.py", 10, "inner"), + make_frame("middle.py", 20, "middle"), + make_frame("outer.py", 30, "outer"), + ] + samples = [[make_interpreter(0, [make_thread(100, frames)])]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_multiple_samples_same_stack(self): + """Multiple identical samples roundtrip exactly (tests RLE).""" + frame = make_frame("hot.py", 99, "hot_func") + samples = [ + [make_interpreter(0, [make_thread(1, [frame])])] + for _ in range(100) + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 100) + self.assert_samples_equal(samples, collector) + + def test_multiple_samples_varying_stacks(self): + """Multiple samples with varying stacks roundtrip exactly.""" + samples = [] + for i in range(20): + depth = i % 5 + 1 + frames = [ + make_frame(f"f{j}.py", j * 10 + i, f"func{j}") + for j in range(depth) + ] + samples.append([make_interpreter(0, [make_thread(1, frames)])]) + collector, count = self.roundtrip(samples) + self.assertEqual(count, 20) + self.assert_samples_equal(samples, collector) + + def test_thread_ids_preserved(self): + """Thread IDs are preserved exactly.""" + thread_ids = [1, 12345, 0x7FFF12345678, 999999] + samples = [] + for tid in thread_ids: + samples.append( + [ + make_interpreter( + 0, [make_thread(tid, [make_frame("t.py", 10, "f")])] + ) + ] + ) + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(thread_ids)) + self.assert_samples_equal(samples, collector) + + def test_interpreter_ids_preserved(self): + """Interpreter IDs are preserved exactly.""" + interp_ids = [0, 1, 5, 100] + samples = [] + for iid in interp_ids: + samples.append( + [ + make_interpreter( + iid, [make_thread(1, [make_frame("i.py", 10, "f")])] + ) + ] + ) + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(interp_ids)) + self.assert_samples_equal(samples, collector) + + def test_status_flags_preserved(self): + """All thread status flags are preserved exactly.""" + statuses = [ + 0, + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_UNKNOWN, + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_HAS_EXCEPTION, + THREAD_STATUS_MAIN_THREAD, + THREAD_STATUS_HAS_GIL | THREAD_STATUS_ON_CPU, + THREAD_STATUS_HAS_GIL | THREAD_STATUS_HAS_EXCEPTION, + THREAD_STATUS_HAS_GIL + | THREAD_STATUS_ON_CPU + | THREAD_STATUS_GIL_REQUESTED, + ] + samples = [] + for i, status in enumerate(statuses): + samples.append( + [ + make_interpreter( + 0, + [ + make_thread( + 1, [make_frame("s.py", 10 + i, "f")], status + ) + ], + ) + ] + ) + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(statuses)) + self.assert_samples_equal(samples, collector) + + def test_binary_replay_preserves_main_thread_for_gecko(self): + """Binary replay preserves main thread identity for GeckoCollector.""" + samples = [ + [ + make_interpreter( + 0, + [ + make_thread( + 1, + [make_frame("main.py", 10, "main")], + THREAD_STATUS_MAIN_THREAD, + ), + make_thread(2, [make_frame("worker.py", 20, "worker")]), + ], + ) + ] + ] + filename = self.create_binary_file(samples) + collector = GeckoCollector(1000) + + with BinaryReader(filename) as reader: + count = reader.replay_samples(collector) + + self.assertEqual(count, 2) + profile = collector._build_profile() + threads = {thread["tid"]: thread for thread in profile["threads"]} + self.assertTrue(threads[1]["isMainThread"]) + self.assertFalse(threads[2]["isMainThread"]) + + def test_multiple_threads_per_sample(self): + """Multiple threads in one sample roundtrip exactly.""" + threads = [ + make_thread( + 1, [make_frame("t1.py", 10, "t1")], THREAD_STATUS_HAS_GIL + ), + make_thread( + 2, [make_frame("t2.py", 20, "t2")], THREAD_STATUS_ON_CPU + ), + make_thread(3, [make_frame("t3.py", 30, "t3")], 0), + ] + samples = [[make_interpreter(0, threads)] for _ in range(10)] + collector, count = self.roundtrip(samples) + # 10 samples × 3 threads = 30 thread-samples + self.assertEqual(count, 30) + self.assert_samples_equal(samples, collector) + + def test_multiple_interpreters_per_sample(self): + """Multiple interpreters in one sample roundtrip exactly.""" + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame("i0.py", 10, "i0")])] + ), + make_interpreter( + 1, [make_thread(2, [make_frame("i1.py", 20, "i1")])] + ), + ] + for _ in range(5) + ] + collector, count = self.roundtrip(samples) + # 5 samples × 2 interpreters × 1 thread = 10 thread-samples + self.assertEqual(count, 10) + self.assert_samples_equal(samples, collector) + + def test_same_thread_id_different_interpreters(self): + """Same thread_id in different interpreters must be tracked separately.""" + # This test catches bugs where thread state is keyed only by thread_id + # without considering interpreter_id + samples = [] + # Interleave samples from interpreter 0 and 1, both using thread_id=1 + for i in range(20): + interp_id = i % 2 # Alternate between interpreter 0 and 1 + frame = make_frame( + f"interp{interp_id}.py", 10 + i, f"func{interp_id}" + ) + samples.append( + [make_interpreter(interp_id, [make_thread(1, [frame])])] + ) + + collector, count = self.roundtrip(samples) + self.assertEqual(count, 20) + self.assert_samples_equal(samples, collector) + + # Verify both interpreters are present + keys = set(collector.by_thread.keys()) + self.assertIn((0, 1), keys) # interpreter 0, thread 1 + self.assertIn((1, 1), keys) # interpreter 1, thread 1 + + # Verify each interpreter got 10 samples + self.assertEqual(len(collector.by_thread[(0, 1)]), 10) + self.assertEqual(len(collector.by_thread[(1, 1)]), 10) + + # Verify the samples are in the right order for each interpreter + for i, sample in enumerate(collector.by_thread[(0, 1)]): + expected_lineno = 10 + i * 2 # 10, 12, 14, ... + self.assertEqual(sample["frames"][0]["lineno"], expected_lineno) + self.assertEqual(sample["frames"][0]["filename"], "interp0.py") + + for i, sample in enumerate(collector.by_thread[(1, 1)]): + expected_lineno = 11 + i * 2 # 11, 13, 15, ... + self.assertEqual(sample["frames"][0]["lineno"], expected_lineno) + self.assertEqual(sample["frames"][0]["filename"], "interp1.py") + + def test_deep_call_stack(self): + """Deep call stack roundtrips exactly.""" + depth = 100 + frames = [ + make_frame(f"f{i}.py", i + 1, f"func{i}") for i in range(depth) + ] + samples = [[make_interpreter(0, [make_thread(1, frames)])]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_line_numbers_preserved(self): + """Various line numbers are preserved exactly.""" + linenos = [1, 100, 1000, 65535, 100000] + samples = [] + for lineno in linenos: + samples.append( + [ + make_interpreter( + 0, [make_thread(1, [make_frame("l.py", lineno, "f")])] + ) + ] + ) + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(linenos)) + self.assert_samples_equal(samples, collector) + + @unittest.skipUnless(ZSTD_AVAILABLE, "zstd compression not available") + def test_zstd_compression_roundtrip(self): + """Zstd compressed data roundtrips exactly.""" + samples = [] + for i in range(200): + frames = [ + make_frame(f"z{j}.py", j * 10 + i + 1, f"zfunc{j}") + for j in range(3) + ] + samples.append([make_interpreter(0, [make_thread(1, frames)])]) + collector, count = self.roundtrip(samples, compression="zstd") + self.assertEqual(count, 200) + self.assert_samples_equal(samples, collector) + + def test_sample_interval_preserved(self): + """Sample interval is preserved in file metadata.""" + intervals = [100, 500, 1000, 5000, 10000] + for interval in intervals: + with self.subTest(interval=interval): + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame("i.py", 1, "f")])] + ) + ] + ] + filename = self.create_binary_file(samples, interval=interval) + with BinaryReader(filename) as reader: + info = reader.get_info() + self.assertEqual(info["sample_interval_us"], interval) + + def test_profiling_mode_preserved(self): + filename = self.create_binary_file([], mode=PROFILING_MODE_CPU) + with BinaryReader(filename) as reader: + self.assertEqual(reader.get_info()["mode"], PROFILING_MODE_CPU) + + def test_missing_profiling_mode_is_unknown(self): + filename = self.create_binary_file([]) + with BinaryReader(filename) as reader: + self.assertIsNone(reader.get_info()["mode"]) + + def test_capture_config_preserved(self): + capture_config = { + "all_threads": True, + "native": True, + "gc": False, + "opcodes": True, + "blocking": False, + } + filename = self.create_binary_file( + [], capture_config=capture_config + ) + with BinaryReader(filename) as reader: + self.assertEqual( + reader.get_info()["capture_config"], capture_config + ) + + def test_missing_capture_config_is_unknown(self): + filename = self.create_binary_file([]) + with BinaryReader(filename) as reader: + self.assertIsNone(reader.get_info()["capture_config"]) + + def test_threads_interleaved_samples(self): + """Multiple threads with interleaved varying samples.""" + samples = [] + for i in range(30): + threads = [ + make_thread( + 1, + [make_frame("t1.py", 10 + i, "t1")], + THREAD_STATUS_HAS_GIL if i % 2 == 0 else 0, + ), + make_thread( + 2, + [make_frame("t2.py", 20 + i, "t2")], + THREAD_STATUS_ON_CPU if i % 3 == 0 else 0, + ), + ] + samples.append([make_interpreter(0, threads)]) + collector, count = self.roundtrip(samples) + self.assertEqual(count, 60) + self.assert_samples_equal(samples, collector) + + def test_full_location_roundtrip(self): + """Full source location (end_lineno, column, end_column) roundtrips.""" + frames = [ + make_frame("test.py", 10, "func1", end_lineno=12, column=4, end_column=20), + make_frame("test.py", 20, "func2", end_lineno=20, column=8, end_column=45), + make_frame("test.py", 30, "func3", end_lineno=35, column=0, end_column=100), + ] + samples = [[make_interpreter(0, [make_thread(1, frames)])]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_opcode_roundtrip(self): + """Opcode values roundtrip exactly.""" + opcodes = [0, 1, 50, 100, 150, 200, 254] # Valid Python opcodes + samples = [] + for opcode in opcodes: + frame = make_frame("test.py", 10, "func", opcode=opcode) + samples.append([make_interpreter(0, [make_thread(1, [frame])])]) + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(opcodes)) + self.assert_samples_equal(samples, collector) + + def test_opcode_none_roundtrip(self): + """Opcode=None (sentinel 255) roundtrips as None.""" + frame = make_frame("test.py", 10, "func", opcode=None) + samples = [[make_interpreter(0, [make_thread(1, [frame])])]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_mixed_location_and_opcode(self): + """Mixed full location and opcode data roundtrips.""" + frames = [ + make_frame("a.py", 10, "a", end_lineno=15, column=4, end_column=30, opcode=100), + make_frame("b.py", 20, "b", end_lineno=20, column=0, end_column=50, opcode=None), + make_frame("c.py", 30, "c", end_lineno=32, column=8, end_column=25, opcode=50), + ] + samples = [[make_interpreter(0, [make_thread(1, frames)])]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_delta_encoding_multiline(self): + """Multi-line spans (large end_lineno delta) roundtrip correctly.""" + # This tests the delta encoding: end_lineno = lineno + delta + frames = [ + make_frame("test.py", 1, "small", end_lineno=1, column=0, end_column=10), + make_frame("test.py", 100, "medium", end_lineno=110, column=0, end_column=50), + make_frame("test.py", 1000, "large", end_lineno=1500, column=0, end_column=200), + ] + samples = [[make_interpreter(0, [make_thread(1, frames)])]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_column_positions_preserved(self): + """Various column positions are preserved exactly.""" + columns = [(0, 10), (4, 50), (8, 100), (100, 200)] + samples = [] + for col, end_col in columns: + frame = make_frame("test.py", 10, "func", column=col, end_column=end_col) + samples.append([make_interpreter(0, [make_thread(1, [frame])])]) + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(columns)) + self.assert_samples_equal(samples, collector) + + def test_same_line_different_opcodes(self): + """Same line with different opcodes creates distinct frames.""" + # This tests that opcode is part of the frame key + frames = [ + make_frame("test.py", 10, "func", opcode=100), + make_frame("test.py", 10, "func", opcode=101), + make_frame("test.py", 10, "func", opcode=102), + ] + samples = [[make_interpreter(0, [make_thread(1, [f])]) for f in frames]] + collector, count = self.roundtrip(samples) + # Verify all three opcodes are preserved distinctly + self.assertEqual(count, 3) + + def test_same_line_different_columns(self): + """Same line with different columns creates distinct frames.""" + frames = [ + make_frame("test.py", 10, "func", column=0, end_column=10), + make_frame("test.py", 10, "func", column=15, end_column=25), + make_frame("test.py", 10, "func", column=30, end_column=40), + ] + samples = [[make_interpreter(0, [make_thread(1, [f])]) for f in frames]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 3) + + def test_synthetic_frames_roundtrip(self): + """Degraded/sentinel frames (location=None) survive the binary format.""" + frames = [ + FrameInfo(("~", None, name, None)) + for name in ( + "", + "", + "", + "", + "", + ) + ] + frames.append(FrameInfo(("app.py", None, "", None))) + frames.append(FrameInfo(("", None, "real_func", None))) + samples = [[make_interpreter(0, [make_thread(1, frames)])]] + + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + +class TestBinaryEdgeCases(BinaryFormatTestBase): + """Tests for edge cases in binary format.""" + + def test_unicode_filenames(self): + """Unicode filenames roundtrip exactly.""" + filenames = [ + "/путь/файл.py", + "/路径/文件.py", + "/パス/ファイル.py", + "/chemin/café.py", + ] + for fname in filenames: + with self.subTest(filename=fname): + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame(fname, 1, "func")])] + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_unicode_funcnames(self): + """Unicode function names roundtrip exactly.""" + funcnames = [ + "функция", + "函数", + "関数", + "función", + ] + for funcname in funcnames: + with self.subTest(funcname=funcname): + samples = [ + [ + make_interpreter( + 0, + [ + make_thread( + 1, [make_frame("test.py", 1, funcname)] + ) + ], + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_special_char_filenames(self): + """Filenames with special characters roundtrip exactly.""" + filenames = [ + "/path/with spaces/file.py", + "/path/with\ttab/file.py", + "/path/with'quote/file.py", + '/path/with"double/file.py', + "/path/with\\backslash/file.py", + ] + for fname in filenames: + with self.subTest(filename=fname): + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame(fname, 1, "func")])] + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_special_funcnames(self): + """Function names with special characters roundtrip exactly.""" + funcnames = [ + "", + "", + "", + "", + "__init__", + "func.inner", + ] + for funcname in funcnames: + with self.subTest(funcname=funcname): + samples = [ + [ + make_interpreter( + 0, + [ + make_thread( + 1, [make_frame("test.py", 1, funcname)] + ) + ], + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_long_filename(self): + """Long filename roundtrips exactly.""" + long_file = "/very/long/path/" + "sub/" * 50 + "file.py" + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame(long_file, 1, "func")])] + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_long_funcname(self): + """Long function name roundtrips exactly.""" + long_func = "very_long_function_name_" + "x" * 200 + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame("test.py", 1, long_func)])] + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_empty_funcname(self): + """Empty function name roundtrips exactly.""" + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame("test.py", 1, "")])] + ) + ] + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + @unittest.skipUnless(ZSTD_AVAILABLE, "zstd compression not available") + def test_large_sample_count(self): + """Large number of samples roundtrips exactly.""" + num = 5000 + samples = [ + [ + make_interpreter( + 0, + [ + make_thread( + 1, [make_frame("test.py", (i % 100) + 1, "func")] + ) + ], + ) + ] + for i in range(num) + ] + collector, count = self.roundtrip(samples, compression="zstd") + self.assertEqual(count, num) + self.assert_samples_equal(samples, collector) + + def test_context_manager_cleanup(self): + """Reader cleans up on context exit.""" + samples = [ + [ + make_interpreter( + 0, [make_thread(1, [make_frame("t.py", 1, "f")])] + ) + ] + ] + filename = self.create_binary_file(samples) + reader = BinaryReader(filename) + with reader: + collector = RawCollector() + count = reader.replay_samples(collector) + self.assertEqual(count, 1) + with self.assertRaises(RuntimeError): + reader.replay_samples(collector) + + def test_invalid_file_path(self): + """Invalid file path raises appropriate error.""" + with self.assertRaises((FileNotFoundError, OSError, ValueError)): + with BinaryReader("/nonexistent/path/file.bin") as reader: + reader.replay_samples(RawCollector()) + + def test_path_arguments_round_trip(self): + """Reader and writer accept str, bytes or os.PathLike.""" + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + for path_arg in (filename, os.fsencode(filename), pathlib.Path(filename)): + with self.subTest(path_type=type(path_arg).__name__): + writer = _remote_debugging.BinaryWriter(path_arg, 1000, 0) + writer.finalize() + reader = _remote_debugging.BinaryReader(path_arg) + info = reader.get_info() + reader.close() + self.assertEqual(info["sample_count"], 0) + + def test_rejects_non_pathlike(self): + """Reader and writer raise TypeError on non-path-like filenames.""" + with self.assertRaises(TypeError): + _remote_debugging.BinaryWriter(123, 1000, 0) + with self.assertRaises(TypeError): + _remote_debugging.BinaryReader(123) + + def test_invalid_path_error_preserves_pathlib(self): + """Missing path: OSError carries the original path object, not a string.""" + missing = pathlib.Path("/i/do/not/exist") + with self.assertRaises(FileNotFoundError) as cm: + _remote_debugging.BinaryReader(missing) + self.assertEqual(os.fspath(cm.exception.filename), os.fspath(missing)) + + def test_writer_handles_empty_stack_first_sample(self): + """BinaryWriter.write_sample tolerates an empty stack on a fresh thread. + + Regression test for the C-level RLE bug in process_thread_sample: a + freshly-created ThreadEntry has prev_stack_depth == 0, so an empty + curr_stack compares as STACK_REPEAT against the zero-initialized + previous stack. Before the fix, this fell through the + `&& !is_new_thread` guard into write_sample_with_encoding, which had + no handler for STACK_REPEAT and raised + RuntimeError("Invalid stack encoding type"). Goes through + BinaryWriter.write_sample directly so the test cannot be masked by + any Python-level filtering. + """ + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + writer = _remote_debugging.BinaryWriter(filename, 1000, 0, compression=0) + empty_sample = [ + make_interpreter( + 0, [make_thread(99, [], status=THREAD_STATUS_UNKNOWN)] + ) + ] + # First sample for a fresh thread has empty frame_info — the exact + # scenario that exposes the bug. + writer.write_sample(empty_sample, 1000) + writer.write_sample(empty_sample, 2000) + # Mix in a real sample to exercise the transition out of the + # empty-stack RLE buffer. + real_sample = [ + make_interpreter(0, [make_thread(1, [make_frame("a.py", 1, "f")])]) + ] + writer.write_sample(real_sample, 3000) + writer.finalize() + + reader_collector = RawCollector() + with BinaryReader(filename) as reader: + count = reader.replay_samples(reader_collector) + # Empty-stack samples are recorded as STACK_REPEAT records with + # depth-0 stacks; the file must replay all three samples. + self.assertEqual(count, 3) + + def test_writer_handles_mixed_empty_and_real_first_sample(self): + """First sample with one empty + one real thread roundtrips through C.""" + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + writer = _remote_debugging.BinaryWriter(filename, 1000, 0, compression=0) + sample = [ + make_interpreter( + 0, + [ + make_thread(1, [make_frame("a.py", 1, "f")]), + make_thread(99, [], status=THREAD_STATUS_UNKNOWN), + ], + ) + ] + # Two samples so RLE state is exercised. + writer.write_sample(sample, 1000) + writer.write_sample(sample, 2000) + writer.finalize() + + # Replay must succeed without raising RuntimeError, and the real + # thread's frames must round-trip. + reader_collector = RawCollector() + with BinaryReader(filename) as reader: + reader.replay_samples(reader_collector) + self.assertIn((0, 1), reader_collector.by_thread) + self.assertEqual(len(reader_collector.by_thread[(0, 1)]), 2) + + def test_writer_total_samples_after_finalize_matches_reader(self): + """BinaryWriter.total_samples after finalize() matches the reader's count.""" + # Five IDENTICAL samples force every sample beyond the first into the + # per-thread RLE buffer. Regression for the cached_total_samples + # ordering bug: capturing the cache BEFORE binary_writer_finalize() + # missed the buffered samples that flush_pending_rle() counts. Keep + # the samples identical to preserve coverage. See gh-149342. + samples = [ + [make_interpreter(0, [make_thread(1, [make_frame("a.py", 1, "f")])])] + ] * 5 + filename, writer_collector = self.write_binary_file(samples) + reader_collector = RawCollector() + with BinaryReader(filename) as reader: + replayed = reader.replay_samples(reader_collector) + self.assertEqual(writer_collector.total_samples, len(samples)) + self.assertEqual(writer_collector.total_samples, replayed) + + def test_rle_buffer_flushes_before_finalize(self): + """RLE buffer flushes before the writer is destroyed during finalize().""" + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + frame = make_frame("rle_boundary.py", 1, "hot") + sample = [make_interpreter(0, [make_thread(1, [frame])])] + + writer = _remote_debugging.BinaryWriter(filename, 1000, 0, compression=0) + for i in range(10_000): + writer.write_sample(sample, i * 1000) + self.assertGreater(writer.get_stats()["repeat_records"], 0) + + writer.finalize() + + reader_collector = RawCollector() + with BinaryReader(filename) as reader: + replayed = reader.replay_samples(reader_collector) + + self.assertEqual(replayed, 10_000) + self.assertEqual(writer.total_samples, 10_000) + + def test_writer_total_samples_after_context_manager_matches_reader(self): + """total_samples after `with BinaryWriter(...)` matches the reader's count. + + Regression for the asymmetry between finalize() and __exit__ in + module.c: __exit__ also calls binary_writer_finalize and must + preserve cached_total_samples like finalize() does, otherwise the + getter returns 0 once self->writer is NULL. + """ + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + sample = [ + make_interpreter(0, [make_thread(1, [make_frame("a.py", 1, "f")])]) + ] + with _remote_debugging.BinaryWriter(filename, 1000, 0, compression=0) as w: + for i in range(5): + w.write_sample(sample, i * 1000) + self.assertEqual(w.total_samples, 5) + + reader_collector = RawCollector() + with BinaryReader(filename) as reader: + self.assertEqual(reader.replay_samples(reader_collector), 5) + + def test_writer_total_samples_after_close_returns_zero(self): + """close() discards data; total_samples reflects no cached count.""" + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + w = _remote_debugging.BinaryWriter(filename, 1000, 0, compression=0) + sample = [ + make_interpreter(0, [make_thread(1, [make_frame("a.py", 1, "f")])]) + ] + for i in range(5): + w.write_sample(sample, i * 1000) + w.close() + self.assertEqual(w.total_samples, 0) + + def test_binary_collector_stops_gracefully_on_overflow(self): + """OverflowError from the writer stops collection via the running + protocol instead of propagating and corrupting the file. + See gh-151292.""" + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + collector = BinaryCollector(filename, 1000, compression="none") + self.assertTrue(collector.running) + + sample = [ + make_interpreter(0, [make_thread(1, [make_frame("a.py", 1, "f")])]) + ] + + # Collect real samples first, then hit the limit. + for i in range(3): + collector.collect(sample, timestamp_us=(i + 1) * 1000) + self.assertTrue(collector.running) + + bad = [make_interpreter(2**32, sample[0].threads)] + with captured_stderr() as stderr: + collector.collect(bad, timestamp_us=4000) + collector.collect(sample, timestamp_us=5000) + + self.assertFalse(collector.running) + self.assertTrue(collector._writer.limit_reached) + self.assertEqual(stderr.getvalue().count("Warning:"), 1) + self.assertIn("interpreter_id", stderr.getvalue()) + + collector.export(None) + + self.assertEqual(collector.total_samples, 3) + + reader_collector = RawCollector() + with BinaryReader(filename) as reader: + self.assertEqual(reader.replay_samples(reader_collector), 3) + + def test_interpreter_id_overflow_rejected(self): + """An interpreter_id wider than u32 raises OverflowError before any + writer state is mutated: subsequent valid samples are still accepted + and finalize produces a readable file.""" + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + good = [ + make_interpreter(0, [make_thread(1, [make_frame("a.py", 1, "f")])]) + ] + bad = [ + make_interpreter(2**32, [make_thread(1, [make_frame("a.py", 1, "f")])]) + ] + + writer = _remote_debugging.BinaryWriter(filename, 1000, 0, compression=0) + writer.write_sample(good, 1000) + with self.assertRaises(OverflowError): + writer.write_sample(bad, 2000) + writer.write_sample(good, 3000) + writer.finalize() + self.assertEqual(writer.total_samples, 2) + + reader_collector = RawCollector() + with BinaryReader(filename) as reader: + self.assertEqual(reader.replay_samples(reader_collector), 2) + + def test_writer_finalizes_after_format_limit(self): + for compression in (0, 1) if ZSTD_AVAILABLE else (0,): + with self.subTest(compression=compression): + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + good = [make_interpreter(0, [ + make_thread(1, [make_frame("a.py", 1, "f")]) + ])] + bad = [make_interpreter(2**32, good[0].threads)] + writer = _remote_debugging.BinaryWriter( + filename, 1000, 0, compression=compression + ) + with self.assertRaises(OverflowError): + with writer: + writer.write_sample(good, 1000) + writer.write_sample(good, 2000) + # The first interpreter is committed before the limit. + writer.write_sample(good + bad, 3000) + self.assertEqual(writer.total_samples, 3) + with BinaryReader(filename) as reader: + self.assertEqual(reader.replay_samples(RawCollector()), 3) + + def test_collector_does_not_swallow_unrelated_overflow(self): + class BadStatus: + def __index__(self): + raise OverflowError("status conversion failed") + + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + collector = BinaryCollector(filename, 1000, compression="none") + self.addCleanup(collector._writer.close) + sample = [make_interpreter(0, [make_thread(1, [], BadStatus())])] + with captured_stderr() as stderr: + with self.assertRaisesRegex(OverflowError, "status conversion failed"): + collector.collect(sample, timestamp_us=1000) + self.assertEqual(stderr.getvalue(), "") + self.assertFalse(collector._writer.limit_reached) + with self.assertRaisesRegex(ValueError, "broken"): + collector.export() + with self.assertRaisesRegex(ValueError, "broken"): + collector._writer.write_sample([], 2000) + # Closing a broken writer must not attempt to finalize it. + collector.__exit__(None, None, None) + + def test_collector_finalizes_after_external_exception(self): + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + with self.assertRaisesRegex(RuntimeError, "sampling failed"): + with BinaryCollector(filename, 1000, compression="none") as collector: + collector.collect([make_interpreter(0, [make_thread(1, [])])]) + raise RuntimeError("sampling failed") + self.assertEqual(collector.total_samples, 1) + with BinaryReader(filename) as reader: + self.assertEqual(reader.replay_samples(RawCollector()), 1) + + @unittest.skipUnless(os.path.exists("/dev/full"), "requires /dev/full") + def test_finalize_failure_breaks_writer(self): + writer = _remote_debugging.BinaryWriter("/dev/full", 1000, 0) + self.addCleanup(writer.close) + writer.write_sample([make_interpreter(0, [make_thread(1, [])])], 1000) + with self.assertRaises(OSError): + writer.finalize() + self.assertFalse(writer.limit_reached) + with self.assertRaisesRegex(ValueError, "broken"): + writer.finalize() + with self.assertRaisesRegex(ValueError, "broken"): + writer.write_sample([], 2000) + + +class TestBinaryFormatValidation(BinaryFormatTestBase): + """Tests for malformed binary files.""" + + HDR_OFF_SAMPLES = 28 + HDR_OFF_THREADS = 36 + HDR_OFF_STR_TABLE = 40 + HDR_OFF_FRAME_TABLE = 48 + FILE_HEADER_PLACEHOLDER_SIZE = 64 + FILE_FOOTER_SIZE = 32 + FTR_OFF_STRINGS = 0 + FTR_OFF_FRAMES = 4 + + def test_replay_rejects_more_threads_than_declared(self): + """Replay rejects files with more unique threads than the header declares.""" + threads = [ + make_thread(1, [make_frame("t1.py", 10, "t1")]), + make_thread(2, [make_frame("t2.py", 20, "t2")]), + ] + samples = [[make_interpreter(0, threads)]] + filename = self.create_binary_file(samples, compression="none") + + with open(filename, "r+b") as raw: + raw.seek(self.HDR_OFF_THREADS) + raw.write(struct.pack("=I", 1)) + + with BinaryReader(filename) as reader: + self.assertEqual(reader.get_info()["thread_count"], 1) + with self.assertRaises(ValueError) as cm: + reader.replay_samples(RawCollector()) + self.assertEqual( + str(cm.exception), + "Invalid thread count: sample data contains more unique " + "threads than declared in header (declared 1, found at least 2)", + ) + + def test_replay_rejects_sample_count_mismatch(self): + """Replay rejects files whose decoded samples disagree with the header.""" + samples = [[make_interpreter(0, [ + make_thread(1, [make_frame("sample.py", 10, "sample")]) + ])]] + filename = self.create_binary_file(samples, compression="none") + + with open(filename, "r+b") as raw: + raw.seek(self.HDR_OFF_SAMPLES) + raw.write(struct.pack("=Q", 2)) + + with BinaryReader(filename) as reader: + self.assertEqual(reader.get_info()["sample_count"], 2) + with self.assertRaises(ValueError) as cm: + reader.replay_samples(RawCollector()) + self.assertEqual( + str(cm.exception), + "Sample count mismatch: header declares 2 samples " + "but replay decoded 1", + ) + + def test_replay_rejects_trailing_partial_sample_header(self): + """Replay rejects partial sample bytes instead of silently stopping.""" + filename = self.create_binary_file([], compression="none") + sample_data_end = self.FILE_HEADER_PLACEHOLDER_SIZE + 1 + + with open(filename, "r+b") as raw: + raw.seek(self.HDR_OFF_STR_TABLE) + raw.write(struct.pack("=Q", sample_data_end)) + raw.seek(self.HDR_OFF_FRAME_TABLE) + raw.write(struct.pack("=Q", sample_data_end)) + + with BinaryReader(filename) as reader: + with self.assertRaises(ValueError) as cm: + reader.replay_samples(RawCollector()) + self.assertEqual(str(cm.exception), "Truncated sample data: 1 trailing bytes") + + # Minimum on-disk size of one table entry (see binary_io.h). + MIN_STRING_ENTRY_SIZE = 1 + MIN_FRAME_ENTRY_SIZE = 7 + + def _read_offset(self, filename, hdr_off): + with open(filename, "rb") as raw: + raw.seek(hdr_off) + return struct.unpack("=Q", raw.read(8))[0] + + def _patch_footer_count(self, filename, ftr_off, value): + size = os.path.getsize(filename) + with open(filename, "r+b") as raw: + raw.seek(size - self.FILE_FOOTER_SIZE + ftr_off) + raw.write(struct.pack("=I", value)) + + def test_open_rejects_string_count_larger_than_file(self): + """Open rejects a footer string count larger than the file.""" + samples = [[make_interpreter(0, [ + make_thread(1, [make_frame("s.py", 10, "s")]) + ])]] + filename = self.create_binary_file(samples, compression="none") + size = os.path.getsize(filename) + str_off = self._read_offset(filename, self.HDR_OFF_STR_TABLE) + max_strings = (size - str_off) // self.MIN_STRING_ENTRY_SIZE + self._patch_footer_count(filename, self.FTR_OFF_STRINGS, 0xFFFFFFFF) + + with self.assertRaises(ValueError) as cm: + with BinaryReader(filename): + pass + self.assertEqual( + str(cm.exception), + f"Invalid string count 4294967295 exceeds maximum " + f"possible {max_strings}", + ) + + def test_open_rejects_frame_count_larger_than_file(self): + """Open rejects a footer frame count larger than the file.""" + samples = [[make_interpreter(0, [ + make_thread(1, [make_frame("f.py", 10, "f")]) + ])]] + filename = self.create_binary_file(samples, compression="none") + size = os.path.getsize(filename) + frame_off = self._read_offset(filename, self.HDR_OFF_FRAME_TABLE) + max_frames = (size - frame_off) // self.MIN_FRAME_ENTRY_SIZE + self._patch_footer_count(filename, self.FTR_OFF_FRAMES, 0xFFFFFFFF) + + # On a 32-bit build this count overflows the allocation size, so the + # size_t overflow guard (OverflowError) fires before the count check. + with self.assertRaises((ValueError, OverflowError)) as cm: + with BinaryReader(filename): + pass + if isinstance(cm.exception, ValueError): + self.assertEqual( + str(cm.exception), + f"Invalid frame count 4294967295 exceeds maximum " + f"possible {max_frames}", + ) + + def test_open_accepts_frame_count_at_capacity_boundary(self): + """A frame count at the file-size cap opens; one more is rejected.""" + samples = [[make_interpreter(0, [ + make_thread(1, [make_frame("f.py", 10, "f")]) + ])]] + filename = self.create_binary_file(samples, compression="none") + size = os.path.getsize(filename) + frame_off = self._read_offset(filename, self.HDR_OFF_FRAME_TABLE) + max_frames = (size - frame_off) // self.MIN_FRAME_ENTRY_SIZE + + self._patch_footer_count(filename, self.FTR_OFF_FRAMES, max_frames) + with BinaryReader(filename): + pass + + self._patch_footer_count(filename, self.FTR_OFF_FRAMES, max_frames + 1) + with self.assertRaises(ValueError) as cm: + with BinaryReader(filename): + pass + self.assertEqual( + str(cm.exception), + f"Invalid frame count {max_frames + 1} exceeds maximum " + f"possible {max_frames}", + ) + + def test_sample_count_reads_full_64_bits(self): + """sample_count values requiring the upper 32 bits decode correctly.""" + filename = self.create_binary_file([], compression="none") + big_count = 0x1_0002_0003 + + with open(filename, "r+b") as raw: + raw.seek(self.HDR_OFF_SAMPLES) + raw.write(struct.pack("=Q", big_count)) + + with BinaryReader(filename) as reader: + self.assertEqual(reader.get_info()["sample_count"], big_count) + + def test_sample_count_boundary_values(self): + """Values above the old u32 ceiling decode fine.""" + filename = self.create_binary_file([], compression="none") + + for value in (0xFFFFFFFF - 1, 0xFFFFFFFF, 0xFFFFFFFF + 1): + with self.subTest(value=value): + with open(filename, "r+b") as raw: + raw.seek(self.HDR_OFF_SAMPLES) + raw.write(struct.pack("=Q", value)) + + with BinaryReader(filename) as reader: + self.assertEqual(reader.get_info()["sample_count"], value) + + +class TestBinaryEncodings(BinaryFormatTestBase): + """Tests specifically targeting different stack encodings.""" + + def test_stack_full_encoding(self): + """First sample uses STACK_FULL encoding and roundtrips.""" + frames = [make_frame(f"f{i}.py", i + 1, f"func{i}") for i in range(5)] + samples = [[make_interpreter(0, [make_thread(1, frames)])]] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1) + self.assert_samples_equal(samples, collector) + + def test_stack_repeat_encoding(self): + """Identical consecutive samples use RLE and roundtrip.""" + frame = make_frame("repeat.py", 42, "repeat_func") + samples = [ + [make_interpreter(0, [make_thread(1, [frame])])] + for _ in range(1000) + ] + collector, count = self.roundtrip(samples) + self.assertEqual(count, 1000) + self.assert_samples_equal(samples, collector) + + def test_stack_suffix_encoding(self): + """Samples sharing suffix use STACK_SUFFIX and roundtrip.""" + samples = [] + for i in range(10): + frames = [make_frame(f"new{i}.py", i + 1, f"new{i}")] + frames.extend( + [ + make_frame(f"shared{j}.py", j + 1, f"shared{j}") + for j in range(5) + ] + ) + samples.append([make_interpreter(0, [make_thread(1, frames)])]) + collector, count = self.roundtrip(samples) + self.assertEqual(count, 10) + self.assert_samples_equal(samples, collector) + + def test_stack_pop_push_encoding(self): + """Samples with pop+push pattern roundtrip.""" + samples = [] + base_frames = [make_frame("base.py", 10, "base")] + + # Call deeper + samples.append([make_interpreter(0, [make_thread(1, base_frames)])]) + samples.append( + [ + make_interpreter( + 0, + [ + make_thread( + 1, + [make_frame("call1.py", 20, "call1")] + + base_frames, + ) + ], + ) + ] + ) + samples.append( + [ + make_interpreter( + 0, + [ + make_thread( + 1, + [ + make_frame("call2.py", 30, "call2"), + make_frame("call1.py", 20, "call1"), + ] + + base_frames, + ) + ], + ) + ] + ) + # Return + samples.append( + [ + make_interpreter( + 0, + [ + make_thread( + 1, + [make_frame("call1.py", 25, "call1")] + + base_frames, + ) + ], + ) + ] + ) + samples.append([make_interpreter(0, [make_thread(1, base_frames)])]) + + collector, count = self.roundtrip(samples) + self.assertEqual(count, 5) + self.assert_samples_equal(samples, collector) + + def test_mixed_encodings(self): + """Mix of different encoding patterns roundtrips.""" + samples = [] + # Some repeated samples (RLE) + frame1 = make_frame("hot.py", 1, "hot") + for _ in range(20): + samples.append([make_interpreter(0, [make_thread(1, [frame1])])]) + # Some varying samples + for i in range(20): + frames = [make_frame(f"vary{i}.py", i + 1, f"vary{i}")] + samples.append([make_interpreter(0, [make_thread(1, frames)])]) + # More repeated + for _ in range(20): + samples.append([make_interpreter(0, [make_thread(1, [frame1])])]) + + collector, count = self.roundtrip(samples) + self.assertEqual(count, 60) + self.assert_samples_equal(samples, collector) + + def test_alternating_threads_status_changes(self): + """Alternating thread status changes roundtrip correctly.""" + samples = [] + for i in range(50): + status1 = THREAD_STATUS_HAS_GIL if i % 2 == 0 else 0 + status2 = ( + THREAD_STATUS_ON_CPU if i % 3 == 0 else THREAD_STATUS_HAS_GIL + ) + threads = [ + make_thread(1, [make_frame("t1.py", 10, "t1")], status1), + make_thread(2, [make_frame("t2.py", 20, "t2")], status2), + ] + samples.append([make_interpreter(0, threads)]) + collector, count = self.roundtrip(samples) + self.assertEqual(count, 100) + self.assert_samples_equal(samples, collector) + + def test_rle_alternating_status_batches_correctly(self): + """A repeat record whose status alternates every sample replays as N + single-status batches with the right cumulative timestamps.""" + class BatchCollector: + def __init__(self): + self.batches = [] + + def collect(self, stack_frames, timestamps_us): + for interp in stack_frames: + for thread in interp.threads: + self.batches.append( + (thread.status, list(timestamps_us)) + ) + + def export(self, filename): + pass + + num_samples = 2000 + frame = make_frame("rle.py", 42, "rle_func") + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + writer = BinaryCollector(filename, 1000, compression="none") + expected = [] + for i in range(num_samples): + status = THREAD_STATUS_HAS_GIL if i % 2 else 0 + ts = 1000 + i + expected.append((status, [ts])) + sample = [ + make_interpreter(0, [make_thread(1, [frame], status)]) + ] + writer.collect(sample, timestamp_us=ts) + writer.export(None) + + collector = BatchCollector() + with BinaryReader(filename) as reader: + count = reader.replay_samples(collector) + + self.assertEqual(count, num_samples) + self.assertEqual(len(collector.batches), num_samples) + self.assertEqual(collector.batches, expected) + + + def test_rle_long_run_splits_batches(self): + # Construct a single repeat record larger than the writer's buffer. + num_samples = 8193 + filename = self.create_binary_file([], compression="none") + data = bytearray(pathlib.Path(filename).read_bytes()) + record = (struct.pack("=QIB", 1, 0, 0) # STACK_REPEAT + + b"\x81\x40" # 8193 as a varint + + b"\x01\x00" * num_samples) # delta=1, status=0 + data[64:64] = record + struct.pack_into("=Q", data, 12, 0) # start timestamp + struct.pack_into("=Q", data, 28, num_samples) + struct.pack_into("=I", data, 36, 1) # thread count + for offset in (40, 48): # string and frame table offsets + old_offset = struct.unpack_from("=Q", data, offset)[0] + struct.pack_into("=Q", data, offset, old_offset + len(record)) + struct.pack_into("=Q", data, len(data) - 24, len(data)) + pathlib.Path(filename).write_bytes(data) + + collector = mock.Mock() + with BinaryReader(filename) as reader: + count = reader.replay_samples(collector) + batches = [call.args[1] for call in collector.collect.call_args_list] + self.assertEqual(count, num_samples) + self.assertEqual([len(batch) for batch in batches], [8192, 1]) + self.assertEqual([ts for batch in batches for ts in batch], + list(range(1, num_samples + 1))) + + +class TestBinaryStress(BinaryFormatTestBase): + """Randomized stress tests for binary format.""" + + @unittest.skipUnless(ZSTD_AVAILABLE, "zstd compression not available") + def test_random_samples_stress(self): + """Stress test with random samples - exercises hash table resizing.""" + random.seed(42) # Reproducible + + # Large pools to force hash table resizing (exceeds initial 8192/4096 sizes) + filenames = [f"file{i}.py" for i in range(200)] + funcnames = [f"func{i}" for i in range(300)] + thread_ids = list(range(1, 50)) + interp_ids = list(range(10)) + statuses = [ + 0, + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_HAS_GIL | THREAD_STATUS_ON_CPU, + THREAD_STATUS_HAS_EXCEPTION, + ] + + samples = [] + for _ in range(1000): + num_interps = random.randint(1, 3) + interps = [] + for _ in range(num_interps): + iid = random.choice(interp_ids) + num_threads = random.randint(1, 5) + threads = [] + for _ in range(num_threads): + tid = random.choice(thread_ids) + status = random.choice(statuses) + depth = random.randint(1, 15) + frames = [] + for _ in range(depth): + fname = random.choice(filenames) + func = random.choice(funcnames) + # Wide line number range to create many unique frames + lineno = random.randint(1, 5000) + frames.append(make_frame(fname, lineno, func)) + threads.append(make_thread(tid, frames, status)) + interps.append(make_interpreter(iid, threads)) + samples.append(interps) + + collector, count = self.roundtrip(samples, compression="zstd") + self.assertGreater(count, 0) + self.assert_samples_equal(samples, collector) + + def test_rle_stress(self): + """Stress test RLE encoding with identical samples.""" + random.seed(123) + + # Create a few distinct stacks + stacks = [] + for i in range(5): + depth = random.randint(1, 8) + frames = [ + make_frame(f"rle{j}.py", j * 10, f"rle{j}") + for j in range(depth) + ] + stacks.append(frames) + + # Generate samples with repeated stacks (should trigger RLE) + samples = [] + for _ in range(100): + stack = random.choice(stacks) + repeat = random.randint(1, 50) + for _ in range(repeat): + samples.append([make_interpreter(0, [make_thread(1, stack)])]) + + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(samples)) + self.assert_samples_equal(samples, collector) + + @unittest.skipUnless(ZSTD_AVAILABLE, "zstd compression not available") + def test_multi_thread_stress(self): + """Stress test with many threads and interleaved samples.""" + random.seed(456) + + thread_ids = list(range(1, 20)) + samples = [] + + for i in range(300): + # Randomly select 1-5 threads for this sample + num_threads = random.randint(1, 5) + selected = random.sample(thread_ids, num_threads) + threads = [] + for tid in selected: + status = random.choice( + [0, THREAD_STATUS_HAS_GIL, THREAD_STATUS_ON_CPU] + ) + depth = random.randint(1, 5) + frames = [ + make_frame(f"mt{tid}_{j}.py", i + j, f"f{j}") + for j in range(depth) + ] + threads.append(make_thread(tid, frames, status)) + samples.append([make_interpreter(0, threads)]) + + collector, count = self.roundtrip(samples, compression="zstd") + self.assertGreater(count, 0) + self.assert_samples_equal(samples, collector) + + def test_encoding_transitions_stress(self): + """Stress test stack encoding transitions.""" + random.seed(789) + + base_frames = [ + make_frame(f"base{i}.py", i, f"base{i}") for i in range(5) + ] + samples = [] + + for i in range(200): + choice = random.randint(0, 4) + if choice == 0: + # Full new stack + depth = random.randint(1, 8) + frames = [ + make_frame(f"new{i}_{j}.py", j, f"new{j}") + for j in range(depth) + ] + elif choice == 1: + # Repeat previous (will use RLE if identical) + frames = base_frames[: random.randint(1, 5)] + elif choice == 2: + # Add frames on top (suffix encoding) + extra = random.randint(1, 3) + frames = [ + make_frame(f"top{i}_{j}.py", j, f"top{j}") + for j in range(extra) + ] + frames.extend(base_frames[: random.randint(2, 4)]) + else: + # Pop and push (pop-push encoding) + keep = random.randint(1, 3) + push = random.randint(0, 2) + frames = [ + make_frame(f"push{i}_{j}.py", j, f"push{j}") + for j in range(push) + ] + frames.extend(base_frames[:keep]) + + samples.append([make_interpreter(0, [make_thread(1, frames)])]) + + collector, count = self.roundtrip(samples) + self.assertEqual(count, len(samples)) + self.assert_samples_equal(samples, collector) + + @unittest.skipUnless(ZSTD_AVAILABLE, "zstd compression not available") + def test_same_thread_id_multiple_interpreters_stress(self): + """Stress test: same thread_id across multiple interpreters with interleaved samples. + + This test catches bugs where thread state is keyed only by thread_id + without considering interpreter_id (both in writer and reader). + """ + random.seed(999) + + # Multiple interpreters, each with overlapping thread_ids + interp_ids = [0, 1, 2, 3] + # Same thread_ids used across all interpreters + shared_thread_ids = [1, 2, 3] + + filenames = [f"file{i}.py" for i in range(10)] + funcnames = [f"func{i}" for i in range(15)] + statuses = [0, THREAD_STATUS_HAS_GIL, THREAD_STATUS_ON_CPU] + + samples = [] + for i in range(1000): + # Randomly pick an interpreter + iid = random.choice(interp_ids) + # Randomly pick 1-3 threads (from shared pool) + num_threads = random.randint(1, 3) + selected_tids = random.sample(shared_thread_ids, num_threads) + + threads = [] + for tid in selected_tids: + status = random.choice(statuses) + depth = random.randint(1, 6) + frames = [] + for d in range(depth): + # Include interpreter and thread info in frame data for verification + fname = f"i{iid}_t{tid}_{random.choice(filenames)}" + func = random.choice(funcnames) + lineno = i * 10 + d + 1 # Unique per sample + frames.append(make_frame(fname, lineno, func)) + threads.append(make_thread(tid, frames, status)) + + samples.append([make_interpreter(iid, threads)]) + + collector, count = self.roundtrip(samples, compression="zstd") + self.assertGreater(count, 0) + self.assert_samples_equal(samples, collector) + + # Verify that we have samples from multiple (interpreter, thread) combinations + # with the same thread_id + keys = set(collector.by_thread.keys()) + # Should have samples for same thread_id in different interpreters + for tid in shared_thread_ids: + interps_with_tid = [iid for (iid, t) in keys if t == tid] + self.assertGreater( + len(interps_with_tid), + 1, + f"Thread {tid} should appear in multiple interpreters", + ) + + +class TimestampCollector: + """Collector that captures timestamps for verification.""" + + def __init__(self): + self.all_timestamps = [] + + def collect(self, stack_frames, timestamps_us=None): + if timestamps_us is not None: + self.all_timestamps.extend(timestamps_us) + + def export(self, filename): + pass + + +class TestTimestampPreservation(BinaryFormatTestBase): + """Tests for timestamp preservation during binary round-trip.""" + + def test_timestamp_preservation(self): + """Timestamps are preserved during round-trip.""" + frame = make_frame("test.py", 10, "func") + timestamps = [1000000, 2000000, 3000000] + + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + collector = BinaryCollector(filename, 1000, compression="none") + for ts in timestamps: + sample = [make_interpreter(0, [make_thread(1, [frame])])] + collector.collect(sample, timestamp_us=ts) + collector.export(None) + + ts_collector = TimestampCollector() + with BinaryReader(filename) as reader: + count = reader.replay_samples(ts_collector) + + self.assertEqual(count, 3) + self.assertEqual(ts_collector.all_timestamps, timestamps) + + def test_timestamp_preservation_with_rle(self): + """RLE-batched samples preserve individual timestamps.""" + frame = make_frame("rle.py", 42, "rle_func") + + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + filename = f.name + self.temp_files.append(filename) + + # Identical samples (triggers RLE) with different timestamps + collector = BinaryCollector(filename, 1000, compression="none") + expected_timestamps = [] + for i in range(50): + ts = 1000000 + i * 100 + expected_timestamps.append(ts) + sample = [make_interpreter(0, [make_thread(1, [frame])])] + collector.collect(sample, timestamp_us=ts) + collector.export(None) + + ts_collector = TimestampCollector() + with BinaryReader(filename) as reader: + count = reader.replay_samples(ts_collector) + + self.assertEqual(count, 50) + self.assertEqual(ts_collector.all_timestamps, expected_timestamps) + + +class TestBinaryReplayToFlamegraph(BinaryFormatTestBase): + def test_replay_includes_persisted_stats(self): + frames = [ + make_frame("hot.py", 99, "hot_func"), + make_frame("main.py", 1, "main"), + ] + samples = [ + [ + make_interpreter( + 0, + [make_thread(1, frames, THREAD_STATUS_HAS_GIL)], + ) + ] + for _ in range(5) + ] + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as file: + bin_path = file.name + self.temp_files.append(bin_path) + collector = BinaryCollector(bin_path, 2000, compression="none") + for sample in samples: + collector.collect(sample) + collector.set_stats( + 2000, 1.25, 4.0, error_rate=2.5, missed_samples=1.5 + ) + collector.export(None) + + with BinaryReader(bin_path) as reader: + info = reader.get_info() + self.assertEqual(info["duration_sec"], 1.25) + self.assertEqual(info["sample_rate"], 4.0) + self.assertEqual(info["error_rate"], 2.5) + self.assertEqual(info["missed_samples"], 1.5) + + with tempfile.NamedTemporaryFile(suffix=".html", delete=False) as file: + html_path = file.name + self.temp_files.append(html_path) + + convert_binary_to_format(bin_path, html_path, "flamegraph") + + with open(html_path, encoding="utf-8") as file: + content = file.read() + self.assertIn('"duration_sec": 1.25', content) + self.assertIn('"sample_rate": 4.0', content) + self.assertIn('"error_rate": 2.5', content) + self.assertIn('"missed_samples": 1.5', content) + + def test_legacy_binary_has_no_measured_stats(self): + frame = make_frame("hot.py", 99, "hot_func") + bin_path = self.create_binary_file([ + [make_interpreter(0, [make_thread(1, [frame])])] + ]) + + with BinaryReader(bin_path) as reader: + info = reader.get_info() + + self.assertIsNone(info["duration_sec"]) + self.assertIsNone(info["sample_rate"]) + self.assertIsNone(info["error_rate"]) + self.assertIsNone(info["missed_samples"]) + + def test_original_stats_extension_remains_readable(self): + frame = make_frame("hot.py", 99, "hot_func") + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as file: + bin_path = file.name + self.temp_files.append(bin_path) + collector = BinaryCollector(bin_path, 2000, compression="none") + collector.collect([ + make_interpreter(0, [make_thread(1, [frame])]) + ]) + collector.set_stats(2000, 1.25, 4.0) + collector.export(None) + + with open(bin_path, "rb") as file: + data = file.read() + stats = data[-88:-32] + footer = bytearray(data[-32:]) + old_stats = stats[:16] + b"TACHSTAT" + struct.pack("=II", 1, 32) + old_data = bytearray(data[:-88] + old_stats + footer) + struct.pack_into("=Q", old_data, -24, len(old_data)) + with open(bin_path, "wb") as file: + file.write(old_data) + + with BinaryReader(bin_path) as reader: + info = reader.get_info() + self.assertEqual(info["duration_sec"], 1.25) + self.assertEqual(info["sample_rate"], 4.0) + self.assertIsNone(info["error_rate"]) + self.assertIsNone(info["missed_samples"]) + + +class TestBinaryReplayToJsonl(BinaryFormatTestBase): + """Tests for binary -> JSONL replay via convert_binary_to_format.""" + + def _replay_to_jsonl(self, samples, interval=1000, mode=None): + bin_path = self.create_binary_file( + samples, interval=interval, mode=mode + ) + with tempfile.NamedTemporaryFile(suffix=".jsonl", delete=False) as f: + jsonl_path = f.name + self.temp_files.append(jsonl_path) + + convert_binary_to_format(bin_path, jsonl_path, "jsonl") + + with open(jsonl_path, "r", encoding="utf-8") as f: + return [json.loads(line) for line in f] + + def test_binary_replay_to_jsonl_basic(self): + """Replay a small .bin to JSONL: meta/end shape, samples_total, run_id.""" + frame = make_frame("hot.py", 99, "hot_func") + samples = [ + [make_interpreter(0, [make_thread(1, [frame])])] + for _ in range(5) + ] + records = self._replay_to_jsonl(samples, interval=2000) + meta, _, frame_defs, _, end = jsonl_tables(records) + + self.assertEqual(meta["sample_interval_usec"], 2000) + self.assertEqual(end["samples_total"], 5) + + run_ids = {r["run_id"] for r in records} + self.assertEqual(len(run_ids), 1) + self.assertRegex(next(iter(run_ids)), r"^[0-9a-f]{32}$") + + self.assertEqual(len(frame_defs), 1) + self.assertEqual(frame_defs[0]["line"], 99) + + def test_binary_replay_to_jsonl_preserves_mode(self): + frame = make_frame("hot.py", 99, "hot_func") + records = self._replay_to_jsonl( + [[make_interpreter(0, [make_thread(1, [frame])])]], + mode=PROFILING_MODE_CPU, + ) + + meta = next(record for record in records if record["type"] == "meta") + self.assertEqual(meta["mode"], "cpu") + + def test_binary_replay_to_jsonl_rle_weight_propagation(self): + """RLE-batched identical samples land as a single agg entry with the right total.""" + frame = make_frame("rle.py", 42, "rle_func") + samples = [ + [make_interpreter(0, [make_thread(1, [frame])])] + for _ in range(50) + ] + records = self._replay_to_jsonl(samples) + _, _, _, agg, end = jsonl_tables(records) + + self.assertEqual(end["samples_total"], 50) + self.assertEqual(agg["entries"], [ + {"frame_id": 0, "self": 50, "cumulative": 50}, + ]) + + def test_binary_replay_to_jsonl_omits_unavailable_columns(self): + """Columns the binary recorder did not capture are omitted, not 0.""" + # make_frame defaults column/end_column to 0; pass column=-1 / end_column=-1 + # so the binary side records LOCATION_NOT_AVAILABLE. + frame = make_frame("nocol.py", 7, "no_col", column=-1, end_column=-1) + samples = [[make_interpreter(0, [make_thread(1, [frame])])]] + records = self._replay_to_jsonl(samples) + _, _, frame_defs, _, _ = jsonl_tables(records) + + self.assertEqual(len(frame_defs), 1) + fd = frame_defs[0] + self.assertEqual(fd["line"], 7) + self.assertNotIn("col", fd) + self.assertNotIn("end_col", fd) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_blocking.py b/Lib/test/test_profiling/test_sampling_profiler/test_blocking.py new file mode 100644 index 00000000000..84b9e7aca0f --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_blocking.py @@ -0,0 +1,272 @@ +"""Tests for blocking mode sampling profiler.""" + +import io +import os +import subprocess +import sys +import textwrap +import time +import unittest +from unittest import mock + +try: + import _remote_debugging # noqa: F401 + import profiling.sampling + import profiling.sampling.sample + from profiling.sampling.stack_collector import CollapsedStackCollector +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from test.support import ( + SHORT_TIMEOUT, + os_helper, + requires_remote_subprocess_debugging, +) + +from .helpers import test_subprocess + +# Duration for profiling in tests +PROFILING_DURATION_SEC = 1 + + +@requires_remote_subprocess_debugging() +class TestBlockingModeStackAccuracy(unittest.TestCase): + """Test that blocking mode produces accurate stack traces. + + When using blocking mode, the target process is stopped during sampling. + This ensures that we see accurate stack traces where functions appear + in the correct caller/callee relationship. + + These tests verify that generator functions are correctly shown at the + top of the stack when they are actively executing, and not incorrectly + shown under their caller's code. + """ + + @classmethod + def setUpClass(cls): + # Test script that uses a generator consumed in a loop. + # When consume_generator is the executing leaf frame on the arithmetic + # lines (temp1, temp2, etc.), fibonacci_generator should NOT be in the + # stack at all. + # Line numbers are important here - see ARITHMETIC_LINES below. + cls.generator_script = textwrap.dedent(''' + def fibonacci_generator(n): + a, b = 0, 1 + for _ in range(n): + yield a + a, b = b, a + b + + def consume_generator(): + gen = fibonacci_generator(10000) + for value in gen: + temp1 = value + 1 + temp2 = value * 2 + temp3 = value - 1 + result = temp1 + temp2 + temp3 + + def main(): + while True: + consume_generator() + + _test_sock.sendall(b"working") + main() + ''') + # Line numbers of the arithmetic operations in consume_generator. + # These are the lines where fibonacci_generator should NOT be in the + # stack when consume_generator is the executing leaf frame. They account + # for the socket prelude added by test_subprocess(). + # temp1 = value + 1 -> line 16 + # temp2 = value * 2 -> line 17 + # temp3 = value - 1 -> line 18 + # result = ... -> line 19 + cls.ARITHMETIC_LINES = {16, 17, 18, 19} + + def test_generator_not_under_consumer_arithmetic(self): + """Test that fibonacci_generator doesn't appear when consume_generator does arithmetic. + + When consume_generator is the leaf frame on arithmetic lines (temp1, + temp2, etc.), fibonacci_generator should NOT be anywhere in the stack - + it's not being called at that point. Non-leaf frame line numbers are + caller/resume metadata, not proof that the frame is executing. + + Valid stacks: + - fibonacci_generator at the top (generator is executing), with + consume_generator below it + - consume_generator at arithmetic lines WITHOUT fibonacci_generator + (we're just doing math, not calling the generator) + + Invalid stacks (indicate torn/inconsistent reads): + - consume_generator leaf frame at arithmetic lines WITH + fibonacci_generator + anywhere in the stack + + Note: call_tree is ordered from bottom (index 0) to top (index -1). + """ + with test_subprocess(self.generator_script, wait_for_working=True) as subproc: + collector = CollapsedStackCollector(sample_interval_usec=100, skip_idle=False) + + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=PROFILING_DURATION_SEC, + blocking=True, + ) + + # Analyze collected stacks + total_samples = 0 + invalid_stacks = 0 + arithmetic_samples = 0 + generator_samples = 0 + generator_not_leaf_samples = 0 + + for (call_tree, _thread_id), count in collector.stack_counter.items(): + total_samples += count + + if not call_tree: + continue + + # Non-leaf frame line numbers can point at resume locations while + # a callee is the executing leaf frame. + _, lineno, funcname = call_tree[-1] + func_names = [frame[2] for frame in call_tree] + + if "fibonacci_generator" in func_names: + generator_samples += count + if funcname != "fibonacci_generator": + generator_not_leaf_samples += count + + if funcname == "consume_generator" and lineno in self.ARITHMETIC_LINES: + arithmetic_samples += count + # Check if fibonacci_generator appears anywhere in this stack. + if "fibonacci_generator" in func_names: + invalid_stacks += count + + self.assertGreater(total_samples, 10, + f"Expected at least 10 samples, got {total_samples}") + + # We should have some samples on the arithmetic lines + self.assertGreater(arithmetic_samples, 0, + f"Expected some samples on arithmetic lines, got {arithmetic_samples}") + + self.assertGreater(generator_samples, 0, + f"Expected some samples in fibonacci_generator, got {generator_samples}") + + self.assertEqual(generator_not_leaf_samples, 0, + f"Found {generator_not_leaf_samples}/{generator_samples} stacks where " + f"fibonacci_generator appears but is not the leaf frame.") + + self.assertEqual(invalid_stacks, 0, + f"Found {invalid_stacks}/{arithmetic_samples} invalid stacks where " + f"fibonacci_generator appears in the stack when consume_generator " + f"is the leaf frame on an arithmetic line. This indicates " + f"torn/inconsistent stack traces are being captured.") + + +@requires_remote_subprocess_debugging() +@unittest.skipUnless(sys.platform == "win32", "Windows only") +class TestBlockingModeCLI(unittest.TestCase): + def test_run_blocking_exits_after_target_process_exits(self): + script = 'print("done")\n' + + tmpdir = os.path.abspath(os_helper.TESTFN + "_profiling_blocking") + with os_helper.temp_dir(tmpdir) as tmpdir: + script_path = os.path.join(tmpdir, "tiny_target.py") + profile_path = os.path.join(tmpdir, "blocking.bin") + with open(script_path, "w", encoding="utf-8") as file: + file.write(script) + + cmd = [ + sys.executable, "-m", "profiling.sampling", "run", + "--binary", "-o", profile_path, + "--mode=cpu", "--blocking", "-r", "100", + script_path, + ] + result = subprocess.run( + cmd, + cwd=tmpdir, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=SHORT_TIMEOUT, + ) + + self.assertEqual( + result.returncode, 0, + f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}", + ) + self.assertGreater(os.path.getsize(profile_path), 0) + + replay = subprocess.run( + [sys.executable, "-m", "profiling.sampling", "replay", + profile_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + timeout=SHORT_TIMEOUT, + ) + self.assertEqual( + replay.returncode, 0, + f"stdout:\n{replay.stdout}\nstderr:\n{replay.stderr}", + ) + + +@requires_remote_subprocess_debugging() +@unittest.skipUnless(sys.platform == "win32", "Windows only") +class TestBlockingModeSuspension(unittest.TestCase): + def test_all_threads_stop_before_pause_returns(self): + import mmap + + tag = f"cpython_blocking_{os.getpid()}_{id(self)}" + script = textwrap.dedent(f''' + import mmap + import struct + import threading + + memory = mmap.mmap(-1, 16, tagname={tag!r}) + + def worker(offset): + counter = 0 + while True: + counter += 1 + struct.pack_into("q", memory, offset, counter) + + for offset in (0, 8): + threading.Thread(target=worker, args=(offset,), daemon=True).start() + _test_sock.sendall(b"working") + _test_sock.recv(1) + ''') + with mmap.mmap(-1, 16, tagname=tag) as memory: + with test_subprocess(script, wait_for_working=True) as subproc: + unwinder = _remote_debugging.RemoteUnwinder( + subproc.process.pid, all_threads=True) + deadline = time.monotonic() + SHORT_TIMEOUT + while not all(memory[offset:offset + 8] != bytes(8) + for offset in (0, 8)): + self.assertLess(time.monotonic(), deadline, + "Worker threads did not start") + time.sleep(0.001) + for _ in range(100): + self.assertTrue(unwinder.pause_threads()) + try: + before = memory[:] + self.assertFalse(unwinder.pause_threads()) + unwinder.get_stack_trace() + time.sleep(0.001) + self.assertEqual(memory[:], before, + "Target memory changed while paused") + finally: + unwinder.resume_threads() + self.assertFalse(unwinder.resume_threads()) + before = memory[:] + deadline = time.monotonic() + SHORT_TIMEOUT + while any(memory[offset:offset + 8] == before[offset:offset + 8] + for offset in (0, 8)): + self.assertLess(time.monotonic(), deadline, + "Worker threads did not resume") + time.sleep(0.001) diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_children.py b/Lib/test/test_profiling/test_sampling_profiler/test_children.py new file mode 100644 index 00000000000..4b27c6dbb18 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_children.py @@ -0,0 +1,1063 @@ +"""Tests for --subprocesses subprocess profiling support.""" + +import argparse +import io +import os +import signal +import subprocess +import sys +import tempfile +import threading +import time +import unittest +from unittest.mock import MagicMock, patch + +from test.support import ( + SHORT_TIMEOUT, + reap_children, + requires_remote_subprocess_debugging, + sleeping_retry, +) + +# Guard imports that require _remote_debugging module. +# This module is not available on all platforms (e.g., WASI). +try: + from profiling.sampling._child_monitor import ( + get_child_pids, + ChildProcessMonitor, + is_python_process, + _MAX_CHILD_PROFILERS, + _CLEANUP_INTERVAL_CYCLES, + ) +except ImportError: + # Module will be skipped via @requires_remote_subprocess_debugging decorators + get_child_pids = None + ChildProcessMonitor = None + is_python_process = None + _MAX_CHILD_PROFILERS = None + _CLEANUP_INTERVAL_CYCLES = None + +try: + from profiling.sampling.cli import ( + _add_sampling_options, + _validate_args, + _build_child_profiler_args, + _build_output_pattern, + _setup_child_monitor, + ) +except ImportError: + # cli module imports sample module which requires _remote_debugging + _add_sampling_options = None + _validate_args = None + _build_child_profiler_args = None + _build_output_pattern = None + _setup_child_monitor = None + +from .helpers import _cleanup_process + +# String to check for in stderr when profiler lacks permissions (e.g., macOS) +_PERMISSION_ERROR_MSG = "Permission Error" + + +def _readline_with_timeout(file_obj, timeout): + # Thread-based readline with timeout - works across all platforms + # including Windows where select() doesn't work with pipes. + # Returns the line read, or None if timeout occurred. + result = [None] + exception = [None] + + def reader(): + try: + result[0] = file_obj.readline() + except Exception as e: + exception[0] = e + + thread = threading.Thread(target=reader, daemon=True) + thread.start() + thread.join(timeout=timeout) + + if thread.is_alive(): + return None + + if exception[0] is not None: + raise exception[0] + + return result[0] + + +def _wait_for_process_exec(proc, name, timeout): + # Wait until a child process calls exec() to replace the forked process + # executable. Raise AssertionError on timeout. + for _ in sleeping_retry(timeout, max_delay=0.1): + exe = os.readlink(f"/proc/{proc.pid}/exe") + if os.path.basename(exe) == name: + break + + +@unittest.skipIf( + _build_child_profiler_args is None, + "profiling.sampling.cli unavailable", +) +class TestChildProfilerArgBuilder(unittest.TestCase): + """Tests for child profiler CLI argument construction.""" + + def test_build_child_profiler_args_diff_flamegraph(self): + """Test child args use the real --diff-flamegraph flag.""" + args = argparse.Namespace( + sample_interval_usec=1000, + duration=None, + all_threads=False, + realtime_stats=False, + native=False, + gc=True, + opcodes=False, + async_aware=False, + mode="wall", + format="diff_flamegraph", + diff_baseline="baseline.bin", + ) + + child_args = _build_child_profiler_args(args) + + self.assertIn("--diff-flamegraph", child_args) + self.assertNotIn("--diff_flamegraph", child_args) + + flag_index = child_args.index("--diff-flamegraph") + self.assertGreater(len(child_args), flag_index + 1) + self.assertEqual(child_args[flag_index + 1], "baseline.bin") + + +@requires_remote_subprocess_debugging() +class TestGetChildPids(unittest.TestCase): + """Tests for the get_child_pids function.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_get_child_pids_from_remote_debugging(self): + """Test get_child_pids from _remote_debugging module.""" + try: + import _remote_debugging + + # Test that the function exists + self.assertTrue(hasattr(_remote_debugging, "get_child_pids")) + + # Test with current process (should return empty or have children if any) + result = _remote_debugging.get_child_pids(os.getpid()) + self.assertIsInstance(result, list) + except (ImportError, AttributeError): + self.skipTest("_remote_debugging.get_child_pids not available") + + def test_get_child_pids_fallback(self): + """Test the fallback implementation for get_child_pids.""" + # Test with current process + result = get_child_pids(os.getpid()) + self.assertIsInstance(result, list) + + @unittest.skipUnless(sys.platform == "linux", "Linux only") + def test_discover_child_process_linux(self): + """Test that we can discover child processes on Linux.""" + # Create a child process + proc = subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(10)"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + try: + # Poll until child appears + deadline = time.time() + SHORT_TIMEOUT + children = [] + while time.time() < deadline: + children = get_child_pids(os.getpid()) + if proc.pid in children: + break + time.sleep(0.05) + + self.assertIn( + proc.pid, + children, + f"Child PID {proc.pid} not discovered within {SHORT_TIMEOUT}s. " + f"Found PIDs: {children}", + ) + finally: + _cleanup_process(proc) + + def test_recursive_child_discovery(self): + """Test that recursive=True finds grandchildren.""" + # Create a child that spawns a grandchild and keeps a reference to it + # so we can clean it up via the child process + code = """ +import subprocess +import sys +import threading +grandchild = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(60)']) +print(grandchild.pid, flush=True) +# Wait for parent to send signal byte (cross-platform) +# Using threading with timeout so test doesn't hang if something goes wrong +# Timeout is 60s (2x test timeout) to ensure child outlives test in worst case +def wait_for_signal(): + try: + sys.stdin.buffer.read(1) + except: + pass +t = threading.Thread(target=wait_for_signal, daemon=True) +t.start() +t.join(timeout=60) +# Clean up grandchild before exiting +if grandchild.poll() is None: + grandchild.terminate() + try: + grandchild.wait(timeout=2) + except subprocess.TimeoutExpired: + grandchild.kill() + try: + grandchild.wait(timeout=2) + except subprocess.TimeoutExpired: + grandchild.wait() +""" + proc = subprocess.Popen( + [sys.executable, "-c", code], + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + + grandchild_pid = None + try: + # Read grandchild PID with thread-based timeout + # This prevents indefinite blocking on all platforms + grandchild_pid_line = _readline_with_timeout( + proc.stdout, SHORT_TIMEOUT + ) + if grandchild_pid_line is None: + self.fail( + f"Timeout waiting for grandchild PID from child process " + f"(child PID: {proc.pid})" + ) + if not grandchild_pid_line: + self.fail( + f"Child process {proc.pid} closed stdout without printing " + f"grandchild PID" + ) + grandchild_pid = int(grandchild_pid_line.strip()) + + # Poll until grandchild is visible + deadline = time.time() + SHORT_TIMEOUT + pids_recursive = [] + while time.time() < deadline: + pids_recursive = get_child_pids(os.getpid(), recursive=True) + if grandchild_pid in pids_recursive: + break + time.sleep(0.05) + + self.assertIn( + proc.pid, + pids_recursive, + f"Child PID {proc.pid} not found in recursive discovery. " + f"Found: {pids_recursive}", + ) + self.assertIn( + grandchild_pid, + pids_recursive, + f"Grandchild PID {grandchild_pid} not found in recursive discovery. " + f"Found: {pids_recursive}", + ) + + # Non-recursive should find only direct child + pids_direct = get_child_pids(os.getpid(), recursive=False) + self.assertIn( + proc.pid, + pids_direct, + f"Child PID {proc.pid} not found in non-recursive discovery. " + f"Found: {pids_direct}", + ) + self.assertNotIn( + grandchild_pid, + pids_direct, + f"Grandchild PID {grandchild_pid} should NOT be in non-recursive " + f"discovery. Found: {pids_direct}", + ) + finally: + # Send signal byte to child to trigger cleanup, then close stdin + try: + proc.stdin.write(b"x") + proc.stdin.flush() + proc.stdin.close() + except OSError: + pass + proc.stdout.close() + _cleanup_process(proc) + # The grandchild may not have been cleaned up by the child process + # (e.g., if the child was killed). Explicitly terminate the + # grandchild to prevent PermissionError on Windows when removing + # temp directories. + if grandchild_pid is not None: + try: + os.kill(grandchild_pid, signal.SIGTERM) + except (OSError, ProcessLookupError): + pass # Process already exited + + def test_nonexistent_pid_returns_empty(self): + """Test that nonexistent PID returns empty list.""" + # Use a very high PID that's unlikely to exist + result = get_child_pids(999999999) + self.assertEqual(result, []) + + +@requires_remote_subprocess_debugging() +class TestChildProcessMonitor(unittest.TestCase): + """Tests for the ChildProcessMonitor class.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_monitor_creation(self): + """Test that ChildProcessMonitor can be created.""" + monitor = ChildProcessMonitor( + pid=os.getpid(), + cli_args=["-r", "10khz", "-d", "5"], + output_pattern="test_{pid}.pstats", + ) + self.assertEqual(monitor.parent_pid, os.getpid()) + self.assertEqual(monitor.cli_args, ["-r", "10khz", "-d", "5"]) + self.assertEqual(monitor.output_pattern, "test_{pid}.pstats") + + def test_monitor_lifecycle(self): + """Test monitor lifecycle via context manager.""" + monitor = ChildProcessMonitor( + pid=os.getpid(), cli_args=[], output_pattern=None + ) + + # Before entering context, thread should not exist + self.assertIsNone(monitor._monitor_thread) + + with monitor: + # Inside context, thread should be running + self.assertIsNotNone(monitor._monitor_thread) + self.assertTrue(monitor._monitor_thread.is_alive()) + + # After exiting context, thread should be stopped + self.assertFalse(monitor._monitor_thread.is_alive()) + + def test_spawned_profilers_property(self): + """Test that spawned_profilers returns a copy of the list.""" + monitor = ChildProcessMonitor( + pid=os.getpid(), cli_args=[], output_pattern=None + ) + + # Should return empty list initially + profilers = monitor.spawned_profilers + self.assertEqual(profilers, []) + self.assertIsNot(profilers, monitor._spawned_profilers) + + def test_context_manager(self): + """Test that ChildProcessMonitor works as a context manager.""" + with ChildProcessMonitor( + pid=os.getpid(), cli_args=[], output_pattern=None + ) as monitor: + self.assertIsNotNone(monitor._monitor_thread) + self.assertTrue(monitor._monitor_thread.is_alive()) + + # After exiting context, thread should be stopped + self.assertFalse(monitor._monitor_thread.is_alive()) + + +@requires_remote_subprocess_debugging() +class TestCLIChildrenFlag(unittest.TestCase): + """Tests for the --subprocesses CLI flag.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_subprocesses_flag_parsed(self): + """Test that --subprocesses flag is recognized.""" + parser = argparse.ArgumentParser() + _add_sampling_options(parser) + + # Parse with --subprocesses + args = parser.parse_args(["--subprocesses"]) + self.assertTrue(args.subprocesses) + + # Parse without --subprocesses + args = parser.parse_args([]) + self.assertFalse(args.subprocesses) + + def test_subprocesses_incompatible_with_live(self): + """Test that --subprocesses is incompatible with --live.""" + # Create mock args with both subprocesses and live + args = argparse.Namespace( + subprocesses=True, + live=True, + async_aware=False, + format="pstats", + mode="wall", + sort=None, + limit=None, + no_summary=False, + opcodes=False, + blocking=False, + interval=1000, + ) + + parser = argparse.ArgumentParser() + + with self.assertRaises(SystemExit): + _validate_args(args, parser) + + def test_build_child_profiler_args(self): + """Test building CLI args for child profilers.""" + args = argparse.Namespace( + sample_interval_usec=200, + duration=15, + all_threads=True, + realtime_stats=False, + native=True, + gc=True, + opcodes=False, + async_aware=False, + mode="cpu", + format="flamegraph", + ) + + child_args = _build_child_profiler_args(args) + + # Verify flag-value pairs are correctly paired (flag followed by value) + def assert_flag_value_pair(flag, value): + self.assertIn( + flag, + child_args, + f"Flag '{flag}' not found in args: {child_args}", + ) + flag_index = child_args.index(flag) + self.assertGreater( + len(child_args), + flag_index + 1, + f"No value after flag '{flag}' in args: {child_args}", + ) + self.assertEqual( + child_args[flag_index + 1], + str(value), + f"Flag '{flag}' should be followed by '{value}', got " + f"'{child_args[flag_index + 1]}' in args: {child_args}", + ) + + assert_flag_value_pair("-r", 5000) + assert_flag_value_pair("-d", 15) + assert_flag_value_pair("--mode", "cpu") + + # Verify standalone flags are present + self.assertIn( + "-a", child_args, f"Flag '-a' not found in args: {child_args}" + ) + self.assertIn( + "--native", + child_args, + f"Flag '--native' not found in args: {child_args}", + ) + self.assertIn( + "--flamegraph", + child_args, + f"Flag '--flamegraph' not found in args: {child_args}", + ) + self.assertNotIn( + "--browser", + child_args, + f"Flag '--browser' should not be in child args: {child_args}", + ) + + def test_build_child_profiler_args_no_gc(self): + """Test building CLI args with --no-gc.""" + args = argparse.Namespace( + sample_interval_usec=100, + duration=5, + all_threads=False, + realtime_stats=False, + native=False, + gc=False, # Explicitly disabled + opcodes=False, + async_aware=False, + mode="wall", + format="pstats", + ) + + child_args = _build_child_profiler_args(args) + + self.assertIn( + "--no-gc", + child_args, + f"Flag '--no-gc' not found when gc=False. Args: {child_args}", + ) + + def test_build_output_pattern_with_outfile(self): + """Test output pattern generation with user-specified output.""" + # With extension + args = argparse.Namespace(outfile="output.html", format="flamegraph") + pattern = _build_output_pattern(args) + self.assertEqual(pattern, "output_{pid}.html") + + # Without extension + args = argparse.Namespace(outfile="output", format="pstats") + pattern = _build_output_pattern(args) + self.assertEqual(pattern, "output_{pid}") + + def test_build_output_pattern_default(self): + """Test output pattern generation with default output.""" + # Flamegraph format + args = argparse.Namespace(outfile=None, format="flamegraph") + pattern = _build_output_pattern(args) + self.assertIn("{pid}", pattern) + self.assertIn("flamegraph", pattern) + self.assertTrue(pattern.endswith(".html")) + + # Heatmap format + args = argparse.Namespace(outfile=None, format="heatmap") + pattern = _build_output_pattern(args) + self.assertEqual(pattern, "heatmap_{pid}") + + +@requires_remote_subprocess_debugging() +class TestChildrenIntegration(unittest.TestCase): + """Integration tests for --subprocesses functionality.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_setup_child_monitor(self): + """Test setting up a child monitor from args.""" + args = argparse.Namespace( + sample_interval_usec=100, + duration=5, + all_threads=False, + realtime_stats=False, + native=False, + gc=True, + opcodes=False, + async_aware=False, + mode="wall", + format="pstats", + outfile=None, + ) + + monitor = _setup_child_monitor(args, os.getpid()) + # Use addCleanup to ensure monitor is properly cleaned up even if + # assertions fail + self.addCleanup(monitor.__exit__, None, None, None) + + self.assertIsNotNone(monitor) + self.assertEqual( + monitor.parent_pid, + os.getpid(), + f"Monitor parent_pid should be {os.getpid()}, got {monitor.parent_pid}", + ) + + +@requires_remote_subprocess_debugging() +class TestIsPythonProcess(unittest.TestCase): + """Tests for the is_python_process function.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_is_python_process_current_process(self): + """Test that current process is detected as Python.""" + # Current process should be Python + result = is_python_process(os.getpid()) + self.assertTrue( + result, + f"Current process (PID {os.getpid()}) should be detected as Python", + ) + + def test_is_python_process_python_subprocess(self): + """Test that a Python subprocess is detected as Python.""" + # Start a Python subprocess + proc = subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(10)"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + try: + # Poll until Python runtime structures are initialized + # (is_python_process probes for runtime structures which take + # time to initialize after process start) + deadline = time.time() + SHORT_TIMEOUT + detected = False + while time.time() < deadline: + if proc.poll() is not None: + self.fail(f"Process {proc.pid} exited unexpectedly") + if is_python_process(proc.pid): + detected = True + break + time.sleep(0.05) + + self.assertTrue( + detected, + f"Python subprocess (PID {proc.pid}) should be detected as Python " + f"within {SHORT_TIMEOUT}s", + ) + finally: + _cleanup_process(proc) + + @unittest.skipUnless(sys.platform == "linux", "Linux only test") + def test_is_python_process_non_python_subprocess(self): + """Test that a non-Python subprocess is not detected as Python.""" + # Start a non-Python subprocess (sleep command) + proc = subprocess.Popen( + ["sleep", "60"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + try: + _wait_for_process_exec(proc, "sleep", SHORT_TIMEOUT) + + self.assertFalse( + is_python_process(proc.pid), + f"Non-Python subprocess 'sleep' (PID {proc.pid}) should NOT be " + f"detected as Python", + ) + finally: + _cleanup_process(proc) + + def test_is_python_process_nonexistent_pid(self): + """Test that nonexistent PID returns False.""" + # Use a very high PID that's unlikely to exist + result = is_python_process(999999999) + self.assertFalse( + result, + "Nonexistent PID 999999999 should return False", + ) + + def test_is_python_process_exited_process(self): + """Test handling of a process that exits quickly.""" + # Start a process that exits immediately + proc = subprocess.Popen( + [sys.executable, "-c", "pass"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + # Wait for it to exit + proc.wait(timeout=SHORT_TIMEOUT) + + # Should return False for exited process (not raise) + result = is_python_process(proc.pid) + self.assertFalse( + result, f"Exited process (PID {proc.pid}) should return False" + ) + + +@requires_remote_subprocess_debugging() +class TestMaxChildProfilersLimit(unittest.TestCase): + """Tests for the _MAX_CHILD_PROFILERS limit.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_max_profilers_constant_exists(self): + """Test that _MAX_CHILD_PROFILERS constant is defined.""" + self.assertEqual( + _MAX_CHILD_PROFILERS, + 100, + f"_MAX_CHILD_PROFILERS should be 100, got {_MAX_CHILD_PROFILERS}", + ) + + def test_cleanup_interval_constant_exists(self): + """Test that _CLEANUP_INTERVAL_CYCLES constant is defined.""" + self.assertEqual( + _CLEANUP_INTERVAL_CYCLES, + 10, + f"_CLEANUP_INTERVAL_CYCLES should be 10, got {_CLEANUP_INTERVAL_CYCLES}", + ) + + def test_monitor_respects_max_limit(self): + """Test that monitor refuses to spawn more than _MAX_CHILD_PROFILERS.""" + # Create a monitor + monitor = ChildProcessMonitor( + pid=os.getpid(), + cli_args=["-r", "10khz", "-d", "5"], + output_pattern="test_{pid}.pstats", + ) + + # Manually fill up the profilers list to the limit + mock_profilers = [MagicMock() for _ in range(_MAX_CHILD_PROFILERS)] + for mock_proc in mock_profilers: + mock_proc.poll.return_value = None # Simulate running process + monitor._spawned_profilers = mock_profilers + + # Try to spawn another profiler - should be rejected + stderr_capture = io.StringIO() + with patch("sys.stderr", stderr_capture): + monitor._spawn_profiler_for_child(99999) + + # Verify warning was printed + stderr_output = stderr_capture.getvalue() + self.assertIn( + "Max child profilers", + stderr_output, + f"Expected warning about max profilers, got: {stderr_output}", + ) + self.assertIn( + str(_MAX_CHILD_PROFILERS), + stderr_output, + f"Warning should mention limit ({_MAX_CHILD_PROFILERS}): {stderr_output}", + ) + + # Verify no new profiler was added + self.assertEqual( + len(monitor._spawned_profilers), + _MAX_CHILD_PROFILERS, + f"Should still have {_MAX_CHILD_PROFILERS} profilers, got " + f"{len(monitor._spawned_profilers)}", + ) + + +@requires_remote_subprocess_debugging() +class TestWaitForProfilers(unittest.TestCase): + """Tests for the wait_for_profilers method.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_wait_for_profilers_empty_list(self): + """Test that wait_for_profilers returns immediately with no profilers.""" + monitor = ChildProcessMonitor( + pid=os.getpid(), cli_args=[], output_pattern=None + ) + + # Should return immediately without printing anything + stderr_capture = io.StringIO() + with unittest.mock.patch("sys.stderr", stderr_capture): + start = time.time() + monitor.wait_for_profilers(timeout=10.0) + elapsed = time.time() - start + + # Should complete very quickly (less than 1 second) + self.assertLess( + elapsed, + 1.0, + f"wait_for_profilers with empty list took {elapsed:.2f}s, expected < 1s", + ) + # No "Waiting for..." message should be printed + self.assertNotIn( + "Waiting for", + stderr_capture.getvalue(), + "Should not print waiting message when no profilers", + ) + + def test_wait_for_profilers_with_completed_process(self): + """Test waiting for profilers that complete quickly.""" + monitor = ChildProcessMonitor( + pid=os.getpid(), cli_args=[], output_pattern=None + ) + + # Start a process that exits quickly + proc = subprocess.Popen( + [sys.executable, "-c", "pass"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + # Add to spawned profilers + monitor._spawned_profilers.append(proc) + + try: + stderr_capture = io.StringIO() + with unittest.mock.patch("sys.stderr", stderr_capture): + start = time.time() + monitor.wait_for_profilers(timeout=SHORT_TIMEOUT) + elapsed = time.time() - start + + # Should complete quickly since process exits fast + self.assertLess( + elapsed, + 5.0, + f"wait_for_profilers took {elapsed:.2f}s for quick process", + ) + # Should print waiting message + self.assertIn( + "Waiting for 1 child profiler", + stderr_capture.getvalue(), + "Should print waiting message", + ) + finally: + _cleanup_process(proc) + + def test_wait_for_profilers_timeout(self): + """Test that wait_for_profilers respects timeout.""" + monitor = ChildProcessMonitor( + pid=os.getpid(), cli_args=[], output_pattern=None + ) + + # Start a process that runs for a long time + proc = subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(60)"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + + # Add to spawned profilers + monitor._spawned_profilers.append(proc) + + try: + stderr_capture = io.StringIO() + with unittest.mock.patch("sys.stderr", stderr_capture): + start = time.time() + # Use short timeout + monitor.wait_for_profilers(timeout=0.5) + elapsed = time.time() - start + + # Should timeout after approximately 0.5 seconds + self.assertGreater( + elapsed, + 0.4, + f"wait_for_profilers returned too quickly ({elapsed:.2f}s)", + ) + self.assertLess( + elapsed, + 2.0, + f"wait_for_profilers took too long ({elapsed:.2f}s), timeout not respected", + ) + finally: + _cleanup_process(proc) + + def test_wait_for_profilers_multiple(self): + """Test waiting for multiple profilers.""" + monitor = ChildProcessMonitor( + pid=os.getpid(), cli_args=[], output_pattern=None + ) + + # Start multiple processes + procs = [] + for _ in range(3): + proc = subprocess.Popen( + [sys.executable, "-c", "import time; time.sleep(0.1)"], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + procs.append(proc) + monitor._spawned_profilers.append(proc) + + try: + stderr_capture = io.StringIO() + with unittest.mock.patch("sys.stderr", stderr_capture): + monitor.wait_for_profilers(timeout=SHORT_TIMEOUT) + + # Should report correct count + self.assertIn( + "Waiting for 3 child profiler", + stderr_capture.getvalue(), + "Should report correct profiler count", + ) + finally: + for proc in procs: + _cleanup_process(proc) + + +@requires_remote_subprocess_debugging() +class TestEndToEndChildrenCLI(unittest.TestCase): + """End-to-end tests for --subprocesses CLI flag.""" + + def setUp(self): + reap_children() + + def tearDown(self): + reap_children() + + def test_subprocesses_flag_spawns_child_and_creates_output(self): + """Test that --subprocesses flag works end-to-end with actual subprocesses.""" + # Create a temporary directory for output files + with tempfile.TemporaryDirectory() as tmpdir: + # Create a script that spawns a child Python process + parent_script = f""" +import subprocess +import sys +import time + +# Spawn a child that does some work +child = subprocess.Popen([ + sys.executable, '-c', + 'import time; [i**2 for i in range(1000)]; time.sleep(2)' +]) +# Do some work in parent +for i in range(1000): + _ = i ** 2 +time.sleep(2) +child.wait() +""" + script_file = os.path.join(tmpdir, "parent_script.py") + with open(script_file, "w") as f: + f.write(parent_script) + + output_file = os.path.join(tmpdir, "profile.pstats") + + # Run the profiler with --subprocesses flag + result = subprocess.run( + [ + sys.executable, + "-m", + "profiling.sampling", + "run", + "--subprocesses", + "-d", + "3", + "-r", + "100", + "-o", + output_file, + script_file, + ], + capture_output=True, + text=True, + timeout=SHORT_TIMEOUT, + ) + + # Check that parent output file was created + self.assertTrue( + os.path.exists(output_file), + f"Parent profile output not created. " + f"stdout: {result.stdout}, stderr: {result.stderr}", + ) + + # Check for child profiler output files (pattern: profile_{pid}.pstats) + output_files = os.listdir(tmpdir) + child_profiles = [ + f + for f in output_files + if f.startswith("profile_") and f.endswith(".pstats") + ] + + # Note: Child profiling is best-effort; the child may exit before + # profiler attaches, or the process may not be detected as Python. + # We just verify the mechanism doesn't crash. + if result.returncode != 0: + self.fail( + f"Profiler exited with code {result.returncode}. " + f"stdout: {result.stdout}, stderr: {result.stderr}" + ) + + def test_subprocesses_flag_with_flamegraph_output(self): + """Test --subprocesses with flamegraph output format.""" + with tempfile.TemporaryDirectory() as tmpdir: + # Simple parent that spawns a child + parent_script = f""" +import subprocess +import sys +import time +child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(1)']) +time.sleep(1) +child.wait() +""" + script_file = os.path.join(tmpdir, "parent.py") + with open(script_file, "w") as f: + f.write(parent_script) + + output_file = os.path.join(tmpdir, "flame.html") + + result = subprocess.run( + [ + sys.executable, + "-m", + "profiling.sampling", + "run", + "--subprocesses", + "-d", + "2", + "-r", + "100", + "--flamegraph", + "-o", + output_file, + script_file, + ], + capture_output=True, + text=True, + timeout=SHORT_TIMEOUT, + ) + + self.assertTrue( + os.path.exists(output_file), + f"Flamegraph output not created. stderr: {result.stderr}", + ) + + # Verify it's valid HTML + with open(output_file, "r") as f: + content = f.read() + self.assertIn( + " 'jsonl' so default filenames work.""" + self.assertEqual(FORMAT_EXTENSIONS["jsonl"], "jsonl") + self.assertEqual(_generate_output_filename("jsonl", 12345), "jsonl_12345.jsonl") + + def test_cli_jsonl_create_collector_propagates_mode(self): + """_create_collector('jsonl', ..., mode=X) lands X in the meta record.""" + collector = _create_collector( + "jsonl", + sample_interval_usec=1000, + skip_idle=False, + mode=PROFILING_MODE_CPU, + ) + self.assertIsInstance(collector, JsonlCollector) + + with tempfile.NamedTemporaryFile(suffix=".jsonl", delete=False) as f: + jsonl_path = f.name + self.addCleanup(os.unlink, jsonl_path) + collector.export(jsonl_path) + with open(jsonl_path, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + meta = next(r for r in records if r["type"] == "meta") + self.assertEqual(meta["mode"], "cpu") + + def test_cli_binary_create_collector_propagates_mode(self): + with tempfile.NamedTemporaryFile(suffix=".bin", delete=False) as f: + binary_path = f.name + self.addCleanup(os.unlink, binary_path) + collector = _create_collector( + "binary", + sample_interval_usec=1000, + skip_idle=True, + mode=PROFILING_MODE_CPU, + output_file=binary_path, + compression="none", + capture_config={"native": True}, + ) + collector.export(None) + + with BinaryReader(binary_path) as reader: + info = reader.get_info() + self.assertEqual(info["mode"], PROFILING_MODE_CPU) + self.assertTrue(info["capture_config"]["native"]) + + def test_cli_jsonl_rejects_opcodes_combination(self): + """--opcodes is incompatible with --jsonl per opcodes_compatible_formats.""" + test_args = [ + "profiling.sampling.cli", + "attach", + "12345", + "--jsonl", + "--opcodes", + ] + with ( + mock.patch("sys.argv", test_args), + mock.patch("sys.stderr", io.StringIO()) as mock_stderr, + mock.patch("profiling.sampling.cli.sample"), + self.assertRaises(SystemExit) as cm, + ): + main() + + self.assertEqual(cm.exception.code, 2) + self.assertIn("--opcodes", mock_stderr.getvalue()) diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_collectors.py b/Lib/test/test_profiling/test_sampling_profiler/test_collectors.py new file mode 100644 index 00000000000..53bdc99d9e6 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_collectors.py @@ -0,0 +1,3670 @@ +"""Tests for sampling profiler collector components.""" + +import json +import marshal +import opcode +import os +import sys +import tempfile +import unittest + +from test.support import is_emscripten, run_with_limited_c_stack, set_recursion_limit + +try: + import _remote_debugging # noqa: F401 + from profiling.sampling import gecko_collector + from profiling.sampling.pstats_collector import PstatsCollector + from profiling.sampling.stack_collector import ( + CollapsedStackCollector, + FlamegraphCollector, + ) + from profiling.sampling.jsonl_collector import JsonlCollector + from profiling.sampling.gecko_collector import GeckoCollector + from profiling.sampling.heatmap_collector import _TemplateLoader + from profiling.sampling.collector import extract_lineno, normalize_location + from profiling.sampling.opcode_utils import get_opcode_info, format_opcode + from profiling.sampling.constants import ( + PROFILING_MODE_WALL, + PROFILING_MODE_CPU, + DEFAULT_LOCATION, + ) + from _remote_debugging import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_MAIN_THREAD, + ) +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from test.support import captured_stdout, captured_stderr + +from .mocks import ( + MockAwaitedInfo, + MockCoroInfo, + MockFrameInfo, + MockInterpreterInfo, + MockTaskInfo, + MockThreadInfo, + LocationInfo, + make_diff_collector_with_mock_baseline, +) +from .helpers import close_and_unlink, jsonl_tables + + +def resolve_name(node, strings): + """Resolve a flamegraph node's name from the string table.""" + idx = node.get("name", 0) + if isinstance(idx, int) and 0 <= idx < len(strings): + return strings[idx] + return str(idx) + + +def find_child_by_name(children, strings, substr): + """Find a child node whose resolved name contains substr.""" + for child in children: + if substr in resolve_name(child, strings): + return child + return None + + +def export_gecko_profile(testcase, collector): + gecko_out = tempfile.NamedTemporaryFile(suffix=".json", delete=False) + testcase.addCleanup(close_and_unlink, gecko_out) + # We cannot overwrite an open file on Windows. + gecko_out.close() + + with captured_stdout(), captured_stderr(): + collector.export(gecko_out.name) + + testcase.assertGreater(os.path.getsize(gecko_out.name), 0) + with open(gecko_out.name, encoding="utf-8") as file: + return json.load(file) + + +def assert_gecko_column_lengths(testcase, table, columns): + expected = table["length"] + for column in columns: + testcase.assertEqual( + len(table[column]), expected, + f"{column!r} has wrong length", + ) + + +def gecko_marker_names(profile, markers): + string_array = profile["shared"]["stringArray"] + return [string_array[idx] for idx in markers["name"]] + + +def gecko_opcode_marker_data(profile): + markers = profile["threads"][0]["markers"] + return [ + data for data in markers["data"] + if data.get("type") == "Opcode" + ] + + +class TestSampleProfilerComponents(unittest.TestCase): + """Unit tests for individual profiler components.""" + + def test_mock_frame_info_with_empty_and_unicode_values(self): + """Test MockFrameInfo handles empty strings, unicode characters, and very long names correctly.""" + # Test with empty strings + frame = MockFrameInfo("", 0, "") + self.assertEqual(frame.filename, "") + self.assertEqual(frame.location.lineno, 0) + self.assertEqual(frame.funcname, "") + + # Test with unicode characters + frame = MockFrameInfo("文件.py", 42, "函数名") + self.assertEqual(frame.filename, "文件.py") + self.assertEqual(frame.funcname, "函数名") + + # Test with very long names + long_filename = "x" * 1000 + ".py" + long_funcname = "func_" + "x" * 1000 + frame = MockFrameInfo(long_filename, 999999, long_funcname) + self.assertEqual(frame.filename, long_filename) + self.assertEqual(frame.location.lineno, 999999) + self.assertEqual(frame.funcname, long_funcname) + + def test_heatmap_navigation_restarts_line_highlight(self): + """Test heatmap navigation can replay target line highlights.""" + loader = _TemplateLoader() + + self.assertIn(".code-line:target", loader.file_css) + self.assertIn("function restartLineHighlight(target)", loader.file_js) + self.assertIn("target.style.animation = 'none'", loader.file_js) + self.assertIn("void target.offsetWidth", loader.file_js) + self.assertIn("url.href === window.location.href", loader.file_js) + self.assertIn("navigateToLine(JSON.parse(navData).link)", loader.file_js) + self.assertIn("navigateToLine(linkData.link)", loader.file_js) + + def test_pstats_collector_with_extreme_intervals_and_empty_data(self): + """Test PstatsCollector handles zero/large intervals, empty frames, None thread IDs, and duplicate frames.""" + # Test with zero interval + collector = PstatsCollector(sample_interval_usec=0) + self.assertEqual(collector.sample_interval_usec, 0) + + # Test with very large interval + collector = PstatsCollector(sample_interval_usec=1000000000) + self.assertEqual(collector.sample_interval_usec, 1000000000) + + # Test collecting empty frames list + collector = PstatsCollector(sample_interval_usec=1000) + collector.collect([]) + self.assertEqual(len(collector.result), 0) + + # Test collecting frames with None thread id + test_frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(None, [MockFrameInfo("file.py", 10, "func", None)])], + ) + ] + collector.collect(test_frames) + # Should still process the frames + self.assertEqual(len(collector.result), 1) + + # Test collecting duplicate frames in same sample (recursive function) + test_frames = [ + MockInterpreterInfo( + 0, # interpreter_id + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 10, "func1"), # Duplicate (recursion) + ], + ) + ], + ) + ] + collector = PstatsCollector(sample_interval_usec=1000) + collector.collect(test_frames) + # Should count only once per sample to avoid over-counting recursive functions + self.assertEqual( + collector.result[("file.py", 10, "func1")]["cumulative_calls"], 1 + ) + + def test_pstats_collector_single_frame_stacks(self): + """Test PstatsCollector with single-frame call stacks to trigger len(frames) <= 1 branch.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Test with exactly one frame (should trigger the <= 1 condition) + single_frame = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("single.py", 10, "single_func")] + ) + ], + ) + ] + collector.collect(single_frame) + + # Should record the single frame with inline call + self.assertEqual(len(collector.result), 1) + single_key = ("single.py", 10, "single_func") + self.assertIn(single_key, collector.result) + self.assertEqual(collector.result[single_key]["direct_calls"], 1) + self.assertEqual(collector.result[single_key]["cumulative_calls"], 1) + + # Test with empty frames (should also trigger <= 1 condition) + empty_frames = [MockInterpreterInfo(0, [MockThreadInfo(1, [])])] + collector.collect(empty_frames) + + # Should not add any new entries + self.assertEqual( + len(collector.result), 1 + ) # Still just the single frame + + # Test mixed single and multi-frame stacks + mixed_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [MockFrameInfo("single2.py", 20, "single_func2")], + ), # Single frame + MockThreadInfo( + 2, + [ # Multi-frame stack + MockFrameInfo("multi.py", 30, "multi_func1"), + MockFrameInfo("multi.py", 40, "multi_func2"), + ], + ), + ], + ), + ] + collector.collect(mixed_frames) + + # Should have recorded all functions + self.assertEqual( + len(collector.result), 4 + ) # single + single2 + multi1 + multi2 + + # Verify single frame handling + single2_key = ("single2.py", 20, "single_func2") + self.assertIn(single2_key, collector.result) + self.assertEqual(collector.result[single2_key]["direct_calls"], 1) + self.assertEqual(collector.result[single2_key]["cumulative_calls"], 1) + + # Verify multi-frame handling still works + multi1_key = ("multi.py", 30, "multi_func1") + multi2_key = ("multi.py", 40, "multi_func2") + self.assertIn(multi1_key, collector.result) + self.assertIn(multi2_key, collector.result) + self.assertEqual(collector.result[multi1_key]["direct_calls"], 1) + self.assertEqual( + collector.result[multi2_key]["cumulative_calls"], 1 + ) # Called from multi1 + + def test_collapsed_stack_collector_with_empty_and_deep_stacks(self): + """Test CollapsedStackCollector handles empty frames, single-frame stacks, and very deep call stacks.""" + collector = CollapsedStackCollector(1000) + + # Test with empty frames + collector.collect([]) + self.assertEqual(len(collector.stack_counter), 0) + + # Test with single frame stack + test_frames = [ + MockInterpreterInfo( + 0, [MockThreadInfo(1, [MockFrameInfo("file.py", 10, "func")])] + ) + ] + collector.collect(test_frames) + self.assertEqual(len(collector.stack_counter), 1) + (((path, thread_id), count),) = collector.stack_counter.items() + self.assertEqual(path, (("file.py", 10, "func"),)) + self.assertEqual(thread_id, 1) + self.assertEqual(count, 1) + + # Test with very deep stack + deep_stack = [MockFrameInfo(f"file{i}.py", i, f"func{i}") for i in range(100)] + test_frames = [MockInterpreterInfo(0, [MockThreadInfo(1, deep_stack)])] + collector = CollapsedStackCollector(1000) + collector.collect(test_frames) + # One aggregated path with 100 frames (reversed) + (((path_tuple, thread_id),),) = (collector.stack_counter.keys(),) + self.assertEqual(len(path_tuple), 100) + self.assertEqual(path_tuple[0], ("file99.py", 99, "func99")) + self.assertEqual(path_tuple[-1], ("file0.py", 0, "func0")) + self.assertEqual(thread_id, 1) + + def test_pstats_collector_basic(self): + """Test basic PstatsCollector functionality.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Test empty state + self.assertEqual(len(collector.result), 0) + self.assertEqual(len(collector.stats), 0) + + # Test collecting sample data + test_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ], + ) + ], + ) + ] + collector.collect(test_frames) + + # Should have recorded calls for both functions + self.assertEqual(len(collector.result), 2) + self.assertIn(("file.py", 10, "func1"), collector.result) + self.assertIn(("file.py", 20, "func2"), collector.result) + + # Top-level function should have direct call + self.assertEqual( + collector.result[("file.py", 10, "func1")]["direct_calls"], 1 + ) + self.assertEqual( + collector.result[("file.py", 10, "func1")]["cumulative_calls"], 1 + ) + + # Calling function should have cumulative call but no direct calls + self.assertEqual( + collector.result[("file.py", 20, "func2")]["cumulative_calls"], 1 + ) + self.assertEqual( + collector.result[("file.py", 20, "func2")]["direct_calls"], 0 + ) + + def test_pstats_collector_create_stats(self): + """Test PstatsCollector stats creation.""" + collector = PstatsCollector( + sample_interval_usec=1000000 + ) # 1 second intervals + + test_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ], + ) + ], + ) + ] + collector.collect(test_frames) + collector.collect(test_frames) # Collect twice + + collector.create_stats() + + # Check stats format: (direct_calls, cumulative_calls, tt, ct, callers) + func1_stats = collector.stats[("file.py", 10, "func1")] + self.assertEqual(func1_stats[0], 2) # direct_calls (top of stack) + self.assertEqual(func1_stats[1], 2) # cumulative_calls + self.assertEqual( + func1_stats[2], 2.0 + ) # tt (total time - 2 samples * 1 sec) + self.assertEqual(func1_stats[3], 2.0) # ct (cumulative time) + + func2_stats = collector.stats[("file.py", 20, "func2")] + self.assertEqual( + func2_stats[0], 0 + ) # direct_calls (never top of stack) + self.assertEqual( + func2_stats[1], 2 + ) # cumulative_calls (appears in stack) + self.assertEqual(func2_stats[2], 0.0) # tt (no direct calls) + self.assertEqual(func2_stats[3], 2.0) # ct (cumulative time) + + def test_collapsed_stack_collector_basic(self): + collector = CollapsedStackCollector(1000) + + # Test empty state + self.assertEqual(len(collector.stack_counter), 0) + + # Test collecting sample data + test_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")] + ) + ], + ) + ] + collector.collect(test_frames) + + # Should store one reversed path + self.assertEqual(len(collector.stack_counter), 1) + (((path, thread_id), count),) = collector.stack_counter.items() + expected_tree = (("file.py", 20, "func2"), ("file.py", 10, "func1")) + self.assertEqual(path, expected_tree) + self.assertEqual(thread_id, 1) + self.assertEqual(count, 1) + + def test_collapsed_stack_collector_export(self): + collapsed_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, collapsed_out) + + collector = CollapsedStackCollector(1000) + + test_frames1 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")] + ) + ], + ) + ] + test_frames2 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")] + ) + ], + ) + ] # Same stack + test_frames3 = [ + MockInterpreterInfo( + 0, [MockThreadInfo(1, [MockFrameInfo("other.py", 5, "other_func")])] + ) + ] + + collector.collect(test_frames1) + collector.collect(test_frames2) + collector.collect(test_frames3) + + with captured_stdout(), captured_stderr(): + collector.export(collapsed_out.name) + # Check file contents + with open(collapsed_out.name, "r") as f: + content = f.read() + + lines = content.strip().split("\n") + self.assertEqual(len(lines), 2) # Two unique stacks + + # Check collapsed format: tid:X;file:func:line;file:func:line count + stack1_expected = "tid:1;file.py:func2:20;file.py:func1:10 2" + stack2_expected = "tid:1;other.py:other_func:5 1" + + self.assertIn(stack1_expected, lines) + self.assertIn(stack2_expected, lines) + + def test_collapsed_stack_collector_export_non_ascii_names(self): + # gh-156810: frame names are written verbatim, so the output must be + # opened with an encoding that can represent non-ASCII and + # surrogate-escaped (undecodable-path) names. + collapsed_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, collapsed_out) + + collector = CollapsedStackCollector(1000) + frame = MockFrameInfo("/tmp/ba\udc80d.py", 5, "计算") + collector.collect([ + MockInterpreterInfo(0, [MockThreadInfo(1, [frame])]) + ]) + + with captured_stdout(), captured_stderr(): + collector.export(collapsed_out.name) + + with open(collapsed_out.name, encoding="utf-8", + errors="surrogatepass") as f: + content = f.read() + self.assertIn("计算", content) + self.assertIn("ba\udc80d.py", content) + + def test_flamegraph_collector_basic(self): + """Test basic FlamegraphCollector functionality.""" + collector = FlamegraphCollector(1000) + + # Empty collector should produce 'No Data' + data = collector._convert_to_flamegraph_format() + # With string table, name is now an index - resolve it using the strings array + strings = data.get("strings", []) + self.assertIn(resolve_name(data, strings), ("No Data", "No significant data")) + + # Test collecting sample data + test_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")] + ) + ], + ) + ] + collector.collect(test_frames) + + # Convert and verify structure: func2 -> func1 with counts = 1 + data = collector._convert_to_flamegraph_format() + # Expect promotion: root is the single child (func2), with func1 as its only child + strings = data.get("strings", []) + name = resolve_name(data, strings) + self.assertTrue(name.startswith("Program Root: ")) + self.assertIn("func2 (file.py:20)", name) + label = strings[data["label"]] + self.assertTrue(label.startswith("Program Root: ")) + self.assertEqual(data["self"], 0) # non-leaf: no self time + children = data.get("children", []) + self.assertEqual(len(children), 1) + child = children[0] + self.assertIn("func1 (file.py:10)", resolve_name(child, strings)) + self.assertEqual(child["value"], 1) + self.assertEqual(child["self"], 1) # leaf: all time is self + self.assertEqual(data["stats"]["sample_interval_usec"], 1000) + + def test_flamegraph_collector_export(self): + """Test flamegraph HTML export functionality.""" + flamegraph_out = tempfile.NamedTemporaryFile( + suffix=".html", delete=False + ) + self.addCleanup(close_and_unlink, flamegraph_out) + + collector = FlamegraphCollector(10000) + + # Create some test data (use Interpreter/Thread objects like runtime) + test_frames1 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")] + ) + ], + ) + ] + test_frames2 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("file.py", 10, "func1"), MockFrameInfo("file.py", 20, "func2")] + ) + ], + ) + ] # Same stack + test_frames3 = [ + MockInterpreterInfo( + 0, [MockThreadInfo(1, [MockFrameInfo("other.py", 5, "other_func")])] + ) + ] + + collector.collect(test_frames1) + collector.collect(test_frames2) + collector.collect(test_frames3) + + # Export flamegraph + with captured_stdout(), captured_stderr(): + export_ok = collector.export(flamegraph_out.name) + + # Verify file was created and contains valid data + self.assertTrue(export_ok) + self.assertTrue(os.path.exists(flamegraph_out.name)) + self.assertGreater(os.path.getsize(flamegraph_out.name), 0) + + # Check file contains HTML content + with open(flamegraph_out.name, "r", encoding="utf-8") as f: + content = f.read() + + # Should be valid HTML + self.assertIn("", content.lower()) + self.assertIn("")], status=THREAD_STATUS_HAS_GIL), + ], + ) + ] + collector.collect(stack_frames_gc) + self.assertEqual(collector.samples_with_gc_frames, 1) + + # Another sample without GC + collector.collect(stack_frames_1) + self.assertEqual(collector.samples_with_gc_frames, 1) # Still 1 + + # Another GC sample + collector.collect(stack_frames_gc) + self.assertEqual(collector.samples_with_gc_frames, 2) + + def test_flamegraph_collector_restores_replay_stats(self): + """Replay restores measured values from binary metadata.""" + collector = FlamegraphCollector(1000) + collector.set_replay_stats({ + "duration_sec": 1.25, + "sample_rate": 4.0, + "error_rate": 2.5, + "missed_samples": 1.5, + }) + + self.assertEqual(collector.stats["duration_sec"], 1.25) + self.assertEqual(collector.stats["sample_rate"], 4.0) + self.assertEqual(collector.stats["error_rate"], 2.5) + self.assertEqual(collector.stats["missed_samples"], 1.5) + + def test_flamegraph_collector_leaves_legacy_replay_stats_unavailable(self): + collector = FlamegraphCollector(1000) + original_stats = collector.stats.copy() + collector.set_replay_stats({ + "duration_sec": None, + "sample_rate": None, + }) + self.assertEqual(collector.stats, original_stats) + + def test_flamegraph_collector_per_thread_stats(self): + """Test per-thread statistics tracking in FlamegraphCollector.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + # Multiple threads with different states + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func_a")], status=THREAD_STATUS_HAS_GIL), + MockThreadInfo(2, [MockFrameInfo("b.py", 2, "func_b")], status=THREAD_STATUS_ON_CPU), + MockThreadInfo(3, [MockFrameInfo("c.py", 3, "func_c")], status=THREAD_STATUS_GIL_REQUESTED), + ], + ) + ] + collector.collect(stack_frames) + + # Check per-thread stats + self.assertIn(1, collector.per_thread_stats) + self.assertIn(2, collector.per_thread_stats) + self.assertIn(3, collector.per_thread_stats) + + # Thread 1: has GIL + self.assertEqual(collector.per_thread_stats[1]["has_gil"], 1) + self.assertEqual(collector.per_thread_stats[1]["on_cpu"], 0) + self.assertEqual(collector.per_thread_stats[1]["total"], 1) + + # Thread 2: on CPU + self.assertEqual(collector.per_thread_stats[2]["has_gil"], 0) + self.assertEqual(collector.per_thread_stats[2]["on_cpu"], 1) + self.assertEqual(collector.per_thread_stats[2]["total"], 1) + + # Thread 3: waiting + self.assertEqual(collector.per_thread_stats[3]["gil_requested"], 1) + self.assertEqual(collector.per_thread_stats[3]["total"], 1) + + # Test accumulation across samples + stack_frames_2 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 2, "func_b")], status=THREAD_STATUS_ON_CPU), + ], + ) + ] + collector.collect(stack_frames_2) + + self.assertEqual(collector.per_thread_stats[1]["has_gil"], 1) + self.assertEqual(collector.per_thread_stats[1]["on_cpu"], 1) + self.assertEqual(collector.per_thread_stats[1]["total"], 2) + + def test_flamegraph_collector_percentage_calculations(self): + """Test that percentage calculations are correct in exported data.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + # Create scenario: 60% GIL held, 40% not held + for i in range(6): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func")], status=THREAD_STATUS_HAS_GIL), + ], + ) + ] + collector.collect(stack_frames) + + for i in range(4): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func")], status=THREAD_STATUS_ON_CPU), + ], + ) + ] + collector.collect(stack_frames) + + # Export to get calculated percentages + data = collector._convert_to_flamegraph_format() + thread_stats = data["stats"]["thread_stats"] + + self.assertAlmostEqual(thread_stats["has_gil_pct"], 60.0, places=1) + self.assertAlmostEqual(thread_stats["on_cpu_pct"], 40.0, places=1) + self.assertEqual(thread_stats["total"], 10) + + def test_flamegraph_collector_mode_handling(self): + """Test that profiling mode is correctly passed through to exported data.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + # Collect some data + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func")], status=THREAD_STATUS_HAS_GIL), + ], + ) + ] + collector.collect(stack_frames) + + # Set stats with mode + collector.set_stats( + sample_interval_usec=1000, + duration_sec=1.0, + sample_rate=1000.0, + mode=PROFILING_MODE_CPU + ) + + data = collector._convert_to_flamegraph_format() + self.assertEqual(data["stats"]["mode"], PROFILING_MODE_CPU) + + def test_flamegraph_collector_zero_samples_edge_case(self): + """Test that collector handles zero samples gracefully.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + # Export without collecting any samples + data = collector._convert_to_flamegraph_format() + + # Should return a valid structure with no data + self.assertIn("name", data) + self.assertEqual(data["value"], 0) + self.assertIn("children", data) + self.assertEqual(len(data["children"]), 0) + + def test_flamegraph_collector_json_structure_includes_stats(self): + """Test that exported JSON includes thread_stats and per_thread_stats.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + # Collect some data with multiple threads + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func_a")], status=THREAD_STATUS_HAS_GIL), + MockThreadInfo(2, [MockFrameInfo("b.py", 2, "func_b")], status=THREAD_STATUS_ON_CPU), + ], + ) + ] + collector.collect(stack_frames) + + # Set stats + collector.set_stats( + sample_interval_usec=1000, + duration_sec=1.0, + sample_rate=1000.0, + mode=PROFILING_MODE_WALL + ) + + # Export and verify structure + data = collector._convert_to_flamegraph_format() + + # Check that stats object exists and contains expected fields + self.assertIn("stats", data) + stats = data["stats"] + + # Verify thread_stats exists and has expected structure + self.assertIn("thread_stats", stats) + thread_stats = stats["thread_stats"] + self.assertIn("has_gil_pct", thread_stats) + self.assertIn("on_cpu_pct", thread_stats) + self.assertIn("gil_requested_pct", thread_stats) + self.assertIn("gc_pct", thread_stats) + self.assertIn("total", thread_stats) + + # Verify per_thread_stats exists and has data for both threads + self.assertIn("per_thread_stats", stats) + per_thread_stats = stats["per_thread_stats"] + self.assertIn(1, per_thread_stats) + self.assertIn(2, per_thread_stats) + + # Check per-thread structure + for thread_id in [1, 2]: + thread_data = per_thread_stats[thread_id] + self.assertIn("has_gil_pct", thread_data) + self.assertIn("on_cpu_pct", thread_data) + self.assertIn("gil_requested_pct", thread_data) + self.assertIn("gc_pct", thread_data) + self.assertIn("total", thread_data) + + def test_flamegraph_nodes_include_per_thread_values(self): + collector = FlamegraphCollector(sample_interval_usec=1000) + root = MockFrameInfo("app.py", 1, "main") + collector.process_frames( + [MockFrameInfo("app.py", 10, "worker_a"), root], + thread_id=1, + weight=2, + ) + collector.process_frames( + [MockFrameInfo("app.py", 20, "worker_b"), root], + thread_id=2, + weight=3, + ) + + data = collector._convert_to_flamegraph_format() + + self.assertEqual(data["thread_values"], {1: [2, 0], 2: [3, 0]}) + children_by_line = {child["lineno"]: child for child in data["children"]} + self.assertEqual(children_by_line[10]["thread_values"], {1: [2, 2]}) + self.assertEqual(children_by_line[20]["thread_values"], {2: [3, 3]}) + + def test_flamegraph_pruning_preserves_low_volume_thread(self): + collector = FlamegraphCollector(sample_interval_usec=1000) + collector.process_frames( + [MockFrameInfo("app.py", 10, "busy")], + thread_id=1, + weight=1999, + ) + collector.process_frames( + [MockFrameInfo("app.py", 20, "rare")], + thread_id=2, + ) + + data = collector._convert_to_flamegraph_format() + + self.assertEqual(data["thread_values"], {1: [1999, 0], 2: [1, 0]}) + children_by_line = {child["lineno"]: child for child in data["children"]} + self.assertEqual(children_by_line[10]["thread_values"], {1: [1999, 1999]}) + self.assertEqual(children_by_line[20]["thread_values"], {2: [1, 1]}) + + def test_flamegraph_does_not_promote_incomplete_root(self): + collector = FlamegraphCollector(sample_interval_usec=1000) + collector.process_frames( + [MockFrameInfo("app.py", 1, "busy")], + thread_id=1, + weight=2000, + ) + for line in range(2, 2002): + collector.process_frames( + [MockFrameInfo("app.py", line, f"fragment_{line}")], + thread_id=2, + ) + + data = collector._convert_to_flamegraph_format() + + self.assertNotIn("filename", data) + self.assertEqual(data["thread_values"], {1: [2000, 0], 2: [2000, 0]}) + self.assertEqual(len(data["children"]), 1) + self.assertEqual(data["children"][0]["thread_values"], {1: [2000, 2000]}) + + def test_flamegraph_nodes_include_per_thread_opcodes(self): + collector = FlamegraphCollector(sample_interval_usec=1000) + collector.process_frames( + [MockFrameInfo("app.py", 10, "worker", opcode=100)], + thread_id=1, + weight=2, + ) + collector.process_frames( + [MockFrameInfo("app.py", 10, "worker", opcode=101)], + thread_id=2, + weight=3, + ) + + data = collector._convert_to_flamegraph_format() + + self.assertEqual(data["opcodes"], {100: 2, 101: 3}) + self.assertEqual( + data["thread_opcodes"], + {1: {100: 2}, 2: {101: 3}}, + ) + + def test_flamegraph_collector_per_thread_gc_percentage(self): + """Test that per-thread GC percentage uses total samples as denominator.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + # Create 10 samples total: + # - Thread 1 appears in all 10 samples, has GC in 2 of them + # - Thread 2 appears in only 5 samples, has GC in 1 of them + + # First 5 samples: both threads, thread 1 has GC in 2 + for i in range(5): + has_gc = i < 2 # First 2 samples have GC for thread 1 + frames_1 = [MockFrameInfo("~", 0, "")] if has_gc else [MockFrameInfo("a.py", 1, "func_a")] + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, frames_1, status=THREAD_STATUS_HAS_GIL), + MockThreadInfo(2, [MockFrameInfo("b.py", 2, "func_b")], status=THREAD_STATUS_ON_CPU), + ], + ) + ] + collector.collect(stack_frames) + + # Next 5 samples: only thread 1, thread 2 appears in first of these with GC + for i in range(5): + if i == 0: + # Thread 2 appears in this sample with GC + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func_a")], status=THREAD_STATUS_HAS_GIL), + MockThreadInfo(2, [MockFrameInfo("~", 0, "")], status=THREAD_STATUS_ON_CPU), + ], + ) + ] + else: + # Only thread 1 + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo(1, [MockFrameInfo("a.py", 1, "func_a")], status=THREAD_STATUS_HAS_GIL), + ], + ) + ] + collector.collect(stack_frames) + + # Set stats and export + collector.set_stats( + sample_interval_usec=1000, + duration_sec=1.0, + sample_rate=1000.0, + mode=PROFILING_MODE_WALL + ) + + data = collector._convert_to_flamegraph_format() + per_thread_stats = data["stats"]["per_thread_stats"] + + # Thread 1: appeared in 10 samples, had GC in 2 + # GC percentage should be 2/10 = 20% (using total samples, not thread appearances) + self.assertEqual(collector.per_thread_stats[1]["gc_samples"], 2) + self.assertEqual(collector.per_thread_stats[1]["total"], 10) + self.assertAlmostEqual(per_thread_stats[1]["gc_pct"], 20.0, places=1) + + # Thread 2: appeared in 6 samples, had GC in 1 + # GC percentage should be 1/10 = 10% (using total samples, not thread appearances) + self.assertEqual(collector.per_thread_stats[2]["gc_samples"], 1) + self.assertEqual(collector.per_thread_stats[2]["total"], 6) + self.assertAlmostEqual(per_thread_stats[2]["gc_pct"], 10.0, places=1) + + def test_diff_flamegraph_identical_profiles(self): + """When baseline and current are identical, diff should be ~0.""" + test_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([test_frames] * 3) + for _ in range(3): + diff.collect(test_frames) + + data = diff._convert_to_flamegraph_format() + strings = data.get("strings", []) + + self.assertTrue(data["stats"]["is_differential"]) + self.assertEqual(data["stats"]["baseline_samples"], 3) + self.assertEqual(data["stats"]["current_samples"], 3) + self.assertAlmostEqual(data["stats"]["baseline_scale"], 1.0) + + children = data.get("children", []) + self.assertEqual(len(children), 1) + child = children[0] + self.assertIn("func1", resolve_name(child, strings)) + self.assertEqual(child["self_time"], 3) + self.assertAlmostEqual(child["baseline"], 3.0) + self.assertAlmostEqual(child["diff"], 0.0, places=1) + self.assertAlmostEqual(child["diff_pct"], 0.0, places=1) + + self.assertEqual(data["stats"]["elided_count"], 0) + self.assertNotIn("elided_flamegraph", data["stats"]) + + def test_diff_flamegraph_new_function(self): + """A function only in current should have diff_pct=100 and baseline=0.""" + baseline_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([baseline_frames]) + diff.collect([ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "new_func"), + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ]) + + data = diff._convert_to_flamegraph_format() + strings = data.get("strings", []) + + children = data.get("children", []) + self.assertEqual(len(children), 1) + func1_node = children[0] + self.assertIn("func1", resolve_name(func1_node, strings)) + + func1_children = func1_node.get("children", []) + self.assertEqual(len(func1_children), 1) + new_func_node = func1_children[0] + self.assertIn("new_func", resolve_name(new_func_node, strings)) + self.assertEqual(new_func_node["baseline"], 0) + self.assertGreater(new_func_node["self_time"], 0) + self.assertEqual(new_func_node["diff"], new_func_node["self_time"]) + self.assertAlmostEqual(new_func_node["diff_pct"], 100.0) + + def test_diff_flamegraph_changed_functions(self): + """Functions with different sample counts should have correct diff and diff_pct.""" + hot_leaf_sample = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "hot_leaf"), + MockFrameInfo("file.py", 20, "caller"), + ]) + ]) + ] + cold_leaf_sample = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "cold_leaf"), + MockFrameInfo("file.py", 20, "caller"), + ]) + ]) + ] + + # Baseline: 2 samples, current: 4. Profiles are compared in absolute + # time rather than normalized to the same total duration. + diff = make_diff_collector_with_mock_baseline( + [hot_leaf_sample, cold_leaf_sample] + ) + for _ in range(3): + diff.collect(hot_leaf_sample) + diff.collect(cold_leaf_sample) + + data = diff._convert_to_flamegraph_format() + strings = data.get("strings", []) + self.assertAlmostEqual(data["stats"]["baseline_scale"], 1.0) + + children = data.get("children", []) + hot_node = find_child_by_name(children, strings, "hot_leaf") + cold_node = find_child_by_name(children, strings, "cold_leaf") + self.assertIsNotNone(hot_node) + self.assertIsNotNone(cold_node) + + # hot_leaf regressed (+200%) + self.assertAlmostEqual(hot_node["baseline"], 1.0) + self.assertEqual(hot_node["self_time"], 3) + self.assertAlmostEqual(hot_node["diff"], 2.0) + self.assertAlmostEqual(hot_node["diff_pct"], 200.0) + + # cold_leaf is unchanged + self.assertAlmostEqual(cold_node["baseline"], 1.0) + self.assertEqual(cold_node["self_time"], 1) + self.assertAlmostEqual(cold_node["diff"], 0.0) + self.assertAlmostEqual(cold_node["diff_pct"], 0.0) + + def test_diff_flamegraph_rejects_mismatched_profiling_modes(self): + from profiling.sampling.binary_collector import BinaryCollector + from profiling.sampling.stack_collector import DiffFlamegraphCollector + + bin_file = tempfile.NamedTemporaryFile(suffix=".bin", delete=False) + self.addCleanup(close_and_unlink, bin_file) + writer = BinaryCollector( + bin_file.name, + sample_interval_usec=1000, + compression="none", + mode=PROFILING_MODE_CPU, + ) + writer.export(None) + + diff = DiffFlamegraphCollector( + 1000, + baseline_binary_path=bin_file.name, + mode=PROFILING_MODE_WALL, + ) + with self.assertRaisesRegex(ValueError, "profiling mode"): + diff._convert_to_flamegraph_format() + + def test_diff_flamegraph_rejects_mismatched_capture_config(self): + from profiling.sampling.binary_collector import BinaryCollector + from profiling.sampling.stack_collector import DiffFlamegraphCollector + + bin_file = tempfile.NamedTemporaryFile(suffix=".bin", delete=False) + self.addCleanup(close_and_unlink, bin_file) + writer = BinaryCollector( + bin_file.name, + sample_interval_usec=1000, + compression="none", + capture_config={"all_threads": True}, + ) + writer.export(None) + + diff = DiffFlamegraphCollector( + 1000, + baseline_binary_path=bin_file.name, + capture_config={"all_threads": False}, + ) + with self.assertRaisesRegex(ValueError, "all_threads"): + diff._convert_to_flamegraph_format() + + def test_diff_flamegraph_does_not_normalize_duration(self): + """A longer current run is compared in absolute time.""" + baseline_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([baseline_frames]) + for _ in range(4): + diff.collect(baseline_frames) + + data = diff._convert_to_flamegraph_format() + self.assertAlmostEqual(data["stats"]["baseline_scale"], 1.0) + + children = data.get("children", []) + self.assertEqual(len(children), 1) + func1_node = children[0] + self.assertEqual(func1_node["self_time"], 4) + self.assertAlmostEqual(func1_node["baseline"], 1.0) + self.assertAlmostEqual(func1_node["diff"], 3.0) + self.assertAlmostEqual(func1_node["diff_pct"], 300.0) + + def test_diff_flamegraph_scale_factor_uses_sample_intervals(self): + """Baseline samples are converted to current sample units.""" + frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [MockFrameInfo("file.py", 10, "func1")]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline( + [frames] * 10, + baseline_interval=1000, + current_interval=10000, + ) + diff.collect(frames) + + data = diff._convert_to_flamegraph_format() + self.assertAlmostEqual(data["stats"]["baseline_scale"], 0.1) + self.assertAlmostEqual(data["baseline"], 1.0) + self.assertEqual(data["self_time"], 1) + self.assertAlmostEqual(data["diff"], 0.0) + self.assertAlmostEqual(data["diff_pct"], 0.0) + + def test_diff_flamegraph_elided_values_use_current_interval(self): + """Elided geometry and metadata use the same sample units.""" + baseline_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "old_func"), + MockFrameInfo("file.py", 30, "parent"), + ]) + ]) + ] + current_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 20, "new_func"), + MockFrameInfo("file.py", 30, "parent"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline( + [baseline_frames] * 10, + baseline_interval=1000, + current_interval=10000, + ) + diff.collect(current_frames) + + data = diff._convert_to_flamegraph_format() + elided = data["stats"]["elided_flamegraph"] + self.assertAlmostEqual(elided["value"], 1.0) + self.assertEqual(elided["self"], 0) + self.assertAlmostEqual(elided["baseline_total"], 1.0) + child, = elided["children"] + self.assertAlmostEqual(child["value"], 1.0) + self.assertAlmostEqual(child["self"], 1.0) + self.assertAlmostEqual(child["baseline"], 1.0) + self.assertAlmostEqual(child["diff"], -1.0) + + def test_diff_flamegraph_elided_stacks(self): + """Paths in baseline but not current produce elided stacks.""" + baseline_frames_1 = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ] + baseline_frames_2 = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "old_func"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([baseline_frames_1, baseline_frames_2]) + for _ in range(2): + diff.collect(baseline_frames_1) + + data = diff._convert_to_flamegraph_format() + + self.assertEqual(data["stats"]["elided_count"], 1) + self.assertIn("elided_flamegraph", data["stats"]) + elided = data["stats"]["elided_flamegraph"] + self.assertTrue(elided["stats"]["is_differential"]) + self.assertIn("strings", elided) + + elided_strings = elided.get("strings", []) + children = elided.get("children", []) + self.assertEqual(len(children), 1) + child = children[0] + self.assertIn("old_func", resolve_name(child, elided_strings)) + self.assertEqual(child["self_time"], 0) + self.assertAlmostEqual(child["diff_pct"], -100.0) + self.assertGreater(child["baseline"], 0) + self.assertAlmostEqual(child["diff"], -child["baseline"]) + + def test_diff_flamegraph_counts_elided_stacks_not_paths(self): + """Internal and leaf stack endings are counted separately.""" + internal_stack = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 20, "old_mid"), + MockFrameInfo("file.py", 10, "root"), + ]) + ]) + ] + leaf_stack = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "old_leaf"), + MockFrameInfo("file.py", 20, "old_mid"), + MockFrameInfo("file.py", 10, "root"), + ]) + ]) + ] + current_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [MockFrameInfo("file.py", 10, "root")]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline( + [internal_stack, leaf_stack] + ) + diff.collect(current_frames) + + data = diff._convert_to_flamegraph_format() + self.assertEqual(data["stats"]["elided_count"], 2) + + def test_diff_flamegraph_renders_small_elided_stack(self): + """Elided stacks are not removed by the significance filter.""" + common_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 20, "common"), + MockFrameInfo("file.py", 10, "root"), + ]) + ]) + ] + old_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "old_tiny"), + MockFrameInfo("file.py", 10, "root"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline( + [common_frames] * 1999 + [old_frames] + ) + for _ in range(1999): + diff.collect(common_frames) + + data = diff._convert_to_flamegraph_format() + self.assertEqual(data["stats"]["elided_count"], 1) + self.assertIn("elided_flamegraph", data["stats"]) + + elided = data["stats"]["elided_flamegraph"] + strings = elided["strings"] + self.assertIsNotNone( + find_child_by_name(elided.get("children", []), strings, "old_tiny") + ) + + def test_diff_flamegraph_elided_top_level_root(self): + """Elided top-level roots do not crash metadata generation.""" + baseline_frames_1 = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "kept_leaf"), + MockFrameInfo("file.py", 20, "kept_root"), + ]) + ]) + ] + baseline_frames_2 = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "old_leaf"), + MockFrameInfo("file.py", 40, "old_root"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([ + baseline_frames_1, + baseline_frames_2, + ]) + diff.collect(baseline_frames_1) + + data = diff._convert_to_flamegraph_format() + elided = data["stats"]["elided_flamegraph"] + elided_strings = elided.get("strings", []) + children = elided.get("children", []) + + self.assertEqual(len(children), 1) + self.assertIn("old_root", resolve_name(children[0], elided_strings)) + + def test_diff_flamegraph_function_matched_despite_line_change(self): + """Functions match by (filename, funcname), ignoring lineno.""" + baseline_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([baseline_frames]) + # Same functions but different line numbers + diff.collect([ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 99, "func1"), + MockFrameInfo("file.py", 55, "func2"), + ]) + ]) + ]) + + data = diff._convert_to_flamegraph_format() + strings = data.get("strings", []) + + children = data.get("children", []) + self.assertEqual(len(children), 1) + child = children[0] + self.assertIn("func1", resolve_name(child, strings)) + self.assertGreater(child["baseline"], 0) + self.assertGreater(child["self_time"], 0) + self.assertAlmostEqual(child["diff"], 0.0, places=1) + self.assertAlmostEqual(child["diff_pct"], 0.0, places=1) + + def test_diff_flamegraph_does_not_duplicate_line_values(self): + """Function aggregates are apportioned across line nodes.""" + def sample(line): + return [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", line, "func"), + MockFrameInfo("file.py", 1, "caller"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline( + [sample(10), sample(20)] + ) + diff.collect(sample(10)) + diff.collect(sample(20)) + + data = diff._convert_to_flamegraph_format() + children = data["children"] + self.assertEqual(sum(node["self"] for node in children), 2) + self.assertEqual(sum(node["self_time"] for node in children), 2) + self.assertEqual(sum(node["baseline"] for node in children), 2) + for node in children: + self.assertEqual(node["self"], 1) + self.assertEqual(node["self_time"], 1) + self.assertAlmostEqual(node["baseline"], 1.0) + self.assertAlmostEqual(node["diff"], 0.0) + + def test_diff_flamegraph_line_totals_include_allocated_self(self): + """A line's baseline self time cannot exceed its inclusive time.""" + def sample(*frames): + return [ + MockInterpreterInfo(0, [MockThreadInfo(1, list(frames))]) + ] + + target_10 = MockFrameInfo("file.py", 10, "target") + target_20 = MockFrameInfo("file.py", 20, "target") + child = MockFrameInfo("file.py", 30, "child") + + diff = make_diff_collector_with_mock_baseline( + [sample(target_10)] * 100 + ) + for _ in range(10): + diff.collect(sample(target_10)) + for _ in range(90): + diff.collect(sample(child, target_20)) + + data = diff._convert_to_flamegraph_format() + nodes = data["children"] + self.assertEqual(sum(node["baseline"] for node in nodes), 100) + self.assertEqual(sum(node["baseline_total"] for node in nodes), 100) + for node in nodes: + self.assertGreaterEqual(node["baseline"], 0) + self.assertLessEqual(node["baseline"], node["baseline_total"]) + + def test_diff_flamegraph_does_not_duplicate_elided_line_values(self): + """Elided metadata uses each rendered line node's samples.""" + def sample(line, funcname="old_func"): + return [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", line, funcname), + MockFrameInfo("file.py", 1, "caller"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline( + [sample(10), sample(20)] + ) + diff.collect(sample(30, "new_func")) + + data = diff._convert_to_flamegraph_format() + elided = data["stats"]["elided_flamegraph"] + children = elided["children"] + scale = data["stats"]["baseline_scale"] + self.assertEqual(sum(node["self"] for node in children), 2) + self.assertEqual(sum(node["baseline"] for node in children), 2 * scale) + for node in children: + self.assertEqual(node["self"], 1) + self.assertAlmostEqual(node["baseline"], scale) + self.assertAlmostEqual(node["diff"], -scale) + + def test_diff_flamegraph_elided_ancestors_have_no_lost_self_time(self): + """Matched ancestors only carry inclusive elided geometry.""" + root = MockFrameInfo("file.py", 10, "root") + common = MockFrameInfo("file.py", 20, "common", opcode=100) + old = MockFrameInfo("file.py", 30, "old") + + common_sample = [ + MockInterpreterInfo(0, [MockThreadInfo(1, [common, root])]) + ] + old_sample = [ + MockInterpreterInfo(0, [MockThreadInfo(1, [old, common, root])]) + ] + + diff = make_diff_collector_with_mock_baseline( + [common_sample] * 3 + [old_sample] + ) + diff.collect(common_sample) + + data = diff._convert_to_flamegraph_format() + elided_root = data["stats"]["elided_flamegraph"] + common_node = elided_root["children"][0] + old_node = common_node["children"][0] + + for ancestor in (elided_root, common_node): + self.assertEqual(ancestor["self"], 0) + self.assertEqual(ancestor["baseline"], 0) + self.assertNotIn("opcodes", ancestor) + self.assertLessEqual( + ancestor["baseline"], ancestor["baseline_total"] + ) + self.assertEqual(old_node["self"], 1) + self.assertEqual(old_node["baseline"], old_node["baseline_total"]) + + def test_diff_flamegraph_empty_current(self): + """Empty current profile still produces differential metadata and elided paths.""" + baseline_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [MockFrameInfo("file.py", 10, "func1")]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline( + [baseline_frames] * 10, + baseline_interval=1000, + current_interval=10000, + ) + # Don't collect anything in current + + data = diff._convert_to_flamegraph_format() + self.assertIn("name", data) + self.assertEqual(data["value"], 0) + # Differential metadata should still be populated + self.assertTrue(data["stats"]["is_differential"]) + # All baseline paths should be elided since current is empty + self.assertGreater(data["stats"]["elided_count"], 0) + self.assertAlmostEqual(data["stats"]["baseline_scale"], 0.1) + elided = data["stats"]["elided_flamegraph"] + self.assertAlmostEqual(elided["value"], 1.0) + self.assertAlmostEqual(elided["baseline"], 1.0) + self.assertAlmostEqual(elided["diff"], -1.0) + + def test_diff_flamegraph_empty_baseline(self): + """Empty baseline with non-empty current uses scale=1.0 fallback.""" + diff = make_diff_collector_with_mock_baseline([]) + diff.collect([ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ]) + + data = diff._convert_to_flamegraph_format() + strings = data.get("strings", []) + + self.assertTrue(data["stats"]["is_differential"]) + self.assertEqual(data["stats"]["baseline_samples"], 0) + self.assertEqual(data["stats"]["current_samples"], 1) + self.assertAlmostEqual(data["stats"]["baseline_scale"], 1.0) + self.assertEqual(data["stats"]["elided_count"], 0) + + children = data.get("children", []) + self.assertEqual(len(children), 1) + child = children[0] + self.assertIn("func1", resolve_name(child, strings)) + self.assertEqual(child["self_time"], 1) + self.assertAlmostEqual(child["baseline"], 0.0) + self.assertAlmostEqual(child["diff"], 1.0) + self.assertAlmostEqual(child["diff_pct"], 100.0) + + def test_diff_flamegraph_export(self): + """DiffFlamegraphCollector export produces differential HTML.""" + test_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ]) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([test_frames]) + diff.collect(test_frames) + + flamegraph_out = tempfile.NamedTemporaryFile( + suffix=".html", delete=False + ) + self.addCleanup(close_and_unlink, flamegraph_out) + + with captured_stdout(), captured_stderr(): + export_ok = diff.export(flamegraph_out.name) + + self.assertTrue(export_ok) + self.assertTrue(os.path.exists(flamegraph_out.name)) + self.assertGreater(os.path.getsize(flamegraph_out.name), 0) + + with open(flamegraph_out.name, "r", encoding="utf-8") as f: + content = f.read() + + self.assertIn("", content.lower()) + self.assertIn("Differential Flamegraph", content) + self.assertIn('"is_differential": true', content) + self.assertIn("d3-flame-graph", content) + self.assertIn('id="diff-legend-section"', content) + self.assertIn("Differential Colors", content) + + def test_diff_flamegraph_preserves_metadata(self): + """Differential mode preserves threads and opcodes metadata.""" + test_frames = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [MockFrameInfo("a.py", 10, "func_a", opcode=100)]), + MockThreadInfo(2, [MockFrameInfo("b.py", 20, "func_b", opcode=200)]), + ]) + ] + + diff = make_diff_collector_with_mock_baseline([test_frames]) + diff.collect(test_frames) + + data = diff._convert_to_flamegraph_format() + strings = data.get("strings", []) + + self.assertTrue(data["stats"]["is_differential"]) + + self.assertIn("threads", data) + self.assertEqual(len(data["threads"]), 2) + + children = data.get("children", []) + self.assertEqual(len(children), 2) + + opcodes_found = set() + for child in children: + self.assertIn("diff", child) + self.assertIn("diff_pct", child) + self.assertIn("baseline", child) + self.assertIn("self_time", child) + self.assertIn("threads", child) + + if "opcodes" in child: + opcodes_found.update(child["opcodes"].keys()) + + self.assertIn(100, opcodes_found) + self.assertIn(200, opcodes_found) + + self.assertIn("per_thread_stats", data["stats"]) + per_thread_stats = data["stats"]["per_thread_stats"] + self.assertIn(1, per_thread_stats) + self.assertIn(2, per_thread_stats) + + def test_diff_flamegraph_elided_preserves_metadata(self): + """Elided flamegraph preserves thread_stats, per_thread_stats, and opcodes.""" + baseline_frames_1 = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "func1", opcode=100), + MockFrameInfo("file.py", 20, "func2", opcode=101), + ], status=THREAD_STATUS_HAS_GIL) + ]) + ] + baseline_frames_2 = [ + MockInterpreterInfo(0, [ + MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "old_func", opcode=200), + MockFrameInfo("file.py", 20, "func2", opcode=101), + ], status=THREAD_STATUS_HAS_GIL) + ]) + ] + + diff = make_diff_collector_with_mock_baseline([baseline_frames_1, baseline_frames_2]) + for _ in range(2): + diff.collect(baseline_frames_1) + + data = diff._convert_to_flamegraph_format() + elided = data["stats"]["elided_flamegraph"] + + self.assertTrue(elided["stats"]["is_differential"]) + self.assertIn("thread_stats", elided["stats"]) + self.assertIn("per_thread_stats", elided["stats"]) + self.assertIn("baseline_samples", elided["stats"]) + self.assertIn("current_samples", elided["stats"]) + self.assertIn("strings", elided) + + elided_strings = elided.get("strings", []) + children = elided.get("children", []) + self.assertEqual(len(children), 1) + old_func_node = children[0] + if "opcodes" in old_func_node: + self.assertIn(200, old_func_node["opcodes"]) + self.assertEqual(old_func_node["self_time"], 0) + self.assertAlmostEqual(old_func_node["diff_pct"], -100.0) + + def test_diff_flamegraph_load_baseline(self): + """Diff annotations work when baseline is loaded from a binary file.""" + from profiling.sampling.binary_collector import BinaryCollector + from profiling.sampling.stack_collector import DiffFlamegraphCollector + from .test_binary_format import make_frame, make_thread, make_interpreter + + hot_sample = [make_interpreter(0, [make_thread(1, [ + make_frame("file.py", 10, "hot_leaf"), + make_frame("file.py", 20, "caller"), + ])])] + cold_sample = [make_interpreter(0, [make_thread(1, [ + make_frame("file.py", 30, "cold_leaf"), + make_frame("file.py", 20, "caller"), + ])])] + + # Baseline: 2 samples, current: 4. Profiles are compared in absolute + # time rather than normalized to the same total duration. + bin_file = tempfile.NamedTemporaryFile(suffix=".bin", delete=False) + self.addCleanup(close_and_unlink, bin_file) + + writer = BinaryCollector( + bin_file.name, sample_interval_usec=1000, compression='none' + ) + writer.collect(hot_sample) + writer.collect(cold_sample) + writer.export(None) + + diff = DiffFlamegraphCollector( + 1000, baseline_binary_path=bin_file.name + ) + hot_mock = [MockInterpreterInfo(0, [MockThreadInfo(1, [ + MockFrameInfo("file.py", 10, "hot_leaf"), + MockFrameInfo("file.py", 20, "caller"), + ])])] + cold_mock = [MockInterpreterInfo(0, [MockThreadInfo(1, [ + MockFrameInfo("file.py", 30, "cold_leaf"), + MockFrameInfo("file.py", 20, "caller"), + ])])] + for _ in range(3): + diff.collect(hot_mock) + diff.collect(cold_mock) + + data = diff._convert_to_flamegraph_format() + strings = data.get("strings", []) + + self.assertTrue(data["stats"]["is_differential"]) + self.assertAlmostEqual(data["stats"]["baseline_scale"], 1.0) + + children = data.get("children", []) + hot_node = find_child_by_name(children, strings, "hot_leaf") + cold_node = find_child_by_name(children, strings, "cold_leaf") + self.assertIsNotNone(hot_node) + self.assertIsNotNone(cold_node) + + # hot_leaf regressed (+200%) + self.assertAlmostEqual(hot_node["baseline"], 1.0) + self.assertEqual(hot_node["self_time"], 3) + self.assertAlmostEqual(hot_node["diff"], 2.0) + self.assertAlmostEqual(hot_node["diff_pct"], 200.0) + + # cold_leaf is unchanged + self.assertAlmostEqual(cold_node["baseline"], 1.0) + self.assertEqual(cold_node["self_time"], 1) + self.assertAlmostEqual(cold_node["diff"], 0.0) + self.assertAlmostEqual(cold_node["diff_pct"], 0.0) + + def test_jsonl_collector_export_exact_output(self): + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + collector.run_id = "run-123" + + test_frames1 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ], + ) + ], + ) + ] + test_frames2 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("file.py", 10, "func1"), + MockFrameInfo("file.py", 20, "func2"), + ], + ) + ], + ) + ] # Same stack + test_frames3 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("other.py", 5, "other_func")] + ) + ], + ) + ] + + collector.collect(test_frames1) + collector.collect(test_frames2) + collector.collect(test_frames3) + + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + content = f.read() + + self.assertEqual( + content, + ( + '{"type":"meta","v":0,"run_id":"run-123","sample_interval_usec":1000}\n' + '{"type":"string_table","v":0,"run_id":"run-123","strings":[{"str_id":0,"value":"func1"},{"str_id":1,"value":"file.py"},{"str_id":2,"value":"func2"},{"str_id":3,"value":"other_func"},{"str_id":4,"value":"other.py"}]}\n' + '{"type":"frame_table","v":0,"run_id":"run-123","frames":[{"frame_id":0,"path_str_id":1,"func_str_id":0,"line":10,"end_line":10},{"frame_id":1,"path_str_id":1,"func_str_id":2,"line":20,"end_line":20},{"frame_id":2,"path_str_id":4,"func_str_id":3,"line":5,"end_line":5}]}\n' + '{"type":"agg","v":0,"run_id":"run-123","kind":"frame","scope":"final","samples_total":3,"entries":[{"frame_id":0,"self":2,"cumulative":2},{"frame_id":1,"self":0,"cumulative":2},{"frame_id":2,"self":1,"cumulative":1}]}\n' + '{"type":"end","v":0,"run_id":"run-123","samples_total":3}\n' + ), + ) + + def test_jsonl_collector_export_includes_mode_in_meta(self): + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000, mode=PROFILING_MODE_CPU) + collector.collect( + [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, [MockFrameInfo("file.py", 10, "func")] + ) + ], + ) + ] + ) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + meta_record = next( + record for record in records if record["type"] == "meta" + ) + self.assertEqual(meta_record["mode"], "cpu") + + def test_jsonl_collector_export_empty_profile(self): + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + collector.run_id = "run-123" + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + self.assertEqual( + [record["type"] for record in records], ["meta", "end"] + ) + self.assertEqual(records[0]["sample_interval_usec"], 1000) + self.assertEqual(records[0]["run_id"], "run-123") + self.assertEqual(records[1]["samples_total"], 0) + self.assertEqual(records[1]["run_id"], "run-123") + + def test_jsonl_collector_recursive_frames_counted_once_per_sample(self): + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + collector.collect( + [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo( + "recursive.py", 10, "recursive_func" + ), + MockFrameInfo( + "recursive.py", 10, "recursive_func" + ), + MockFrameInfo( + "recursive.py", 10, "recursive_func" + ), + ], + ) + ], + ) + ] + ) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + _, _, frame_defs, agg_record, end_record = jsonl_tables(records) + self.assertEqual(len(frame_defs), 1) + self.assertEqual( + agg_record["entries"], + [ + { + "frame_id": frame_defs[0]["frame_id"], + "self": 1, + "cumulative": 1, + } + ], + ) + self.assertEqual(agg_record["samples_total"], 1) + self.assertEqual(end_record["samples_total"], 1) + + def test_jsonl_collector_skip_idle_filters_threads(self): + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + active_status = THREAD_STATUS_HAS_GIL | THREAD_STATUS_ON_CPU + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [MockFrameInfo("active1.py", 10, "active_func1")], + status=active_status, + ), + MockThreadInfo( + 2, + [MockFrameInfo("idle.py", 20, "idle_func")], + status=0, + ), + MockThreadInfo( + 3, + [MockFrameInfo("active2.py", 30, "active_func2")], + status=active_status, + ), + ], + ) + ] + + def export_summary(skip_idle): + collector = JsonlCollector(1000, skip_idle=skip_idle) + collector.collect(frames) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + _, str_defs, frame_defs, agg_record, _ = jsonl_tables(records) + paths = {str_defs[item["path_str_id"]] for item in frame_defs} + funcs = {str_defs[item["func_str_id"]] for item in frame_defs} + return paths, funcs, agg_record["samples_total"] + + paths, funcs, samples_total = export_summary(skip_idle=True) + self.assertEqual(paths, {"active1.py", "active2.py"}) + self.assertEqual(funcs, {"active_func1", "active_func2"}) + self.assertEqual(samples_total, 2) + + paths, funcs, samples_total = export_summary(skip_idle=False) + self.assertEqual(paths, {"active1.py", "idle.py", "active2.py"}) + self.assertEqual(funcs, {"active_func1", "idle_func", "active_func2"}) + self.assertEqual(samples_total, 3) + + def test_jsonl_collector_splits_large_exports_into_chunks(self): + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + + for i in range(257): + collector.collect( + [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo( + f"file{i}.py", i + 1, f"func{i}" + ) + ], + ) + ], + ) + ] + ) + + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + run_ids = {record["run_id"] for record in records} + self.assertEqual(len(run_ids), 1) + self.assertRegex(next(iter(run_ids)), r"^[0-9a-f]{32}$") + + _, str_defs, frame_defs, agg_record, end_record = jsonl_tables( + records + ) + str_chunks = [ + record for record in records if record["type"] == "string_table" + ] + frame_chunks = [ + record for record in records if record["type"] == "frame_table" + ] + agg_chunks = [record for record in records if record["type"] == "agg"] + + self.assertEqual( + [len(record["strings"]) for record in str_chunks], + [256, 256, 2], + ) + self.assertEqual( + [len(record["frames"]) for record in frame_chunks], [256, 1] + ) + self.assertEqual( + [len(record["entries"]) for record in agg_chunks], [256, 1] + ) + self.assertEqual(len(str_defs), 514) + self.assertEqual(len(frame_defs), 257) + self.assertEqual(agg_record["samples_total"], 257) + self.assertEqual(end_record["samples_total"], 257) + + def test_jsonl_collector_respects_weight_for_rle_batched_samples(self): + """weight>1 (from binary replay RLE) is honored in self/cumulative.""" + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + leaf = MockFrameInfo("file.py", 10, "leaf") + non_leaf = MockFrameInfo("file.py", 20, "non_leaf") + + collector.process_frames([leaf, non_leaf], _thread_id=1, weight=5) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + _, str_defs, frame_defs, agg, end = jsonl_tables(records) + self.assertEqual(end["samples_total"], 5) + self.assertEqual(agg["samples_total"], 5) + self.assertEqual( + {str_defs[fd["func_str_id"]]: fd["frame_id"] for fd in frame_defs}, + {"leaf": 0, "non_leaf": 1}, + ) + self.assertEqual(agg["entries"], [ + {"frame_id": 0, "self": 5, "cumulative": 5}, + {"frame_id": 1, "self": 0, "cumulative": 5}, + ]) + + def test_jsonl_collector_recursion_with_weight(self): + """Recursion dedup respects weight, not occurrence count.""" + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + recursive = MockFrameInfo("rec.py", 10, "f") + + collector.process_frames([recursive] * 3, _thread_id=1, weight=3) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + _, _, frame_defs, agg, _ = jsonl_tables(records) + self.assertEqual(len(frame_defs), 1) + self.assertEqual(agg["entries"], [ + {"frame_id": 0, "self": 3, "cumulative": 3}, + ]) + + def test_jsonl_collector_emits_col_and_end_col_when_present(self): + """All four location fields are emitted when col/end_col are >= 0.""" + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + frame = MockFrameInfo("test.py", 0, "f") + frame.location = LocationInfo(42, 45, 4, 12) + frames = [ + MockInterpreterInfo( + 0, [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + _, str_defs, frame_defs, _, _ = jsonl_tables(records) + self.assertEqual(frame_defs, [ + { + "frame_id": 0, + "path_str_id": 1, + "func_str_id": 0, + "line": 42, + "end_line": 45, + "col": 4, + "end_col": 12, + }, + ]) + self.assertEqual(str_defs, {0: "f", 1: "test.py"}) + + def test_jsonl_collector_partial_location_elision(self): + """Negative col/end_col/end_line fields are individually elided.""" + # _get_or_create_frame_id interns funcname before filename, so + # func_str_id=0 ("f") and path_str_id=1 ("test.py"). + common = {"frame_id": 0, "path_str_id": 1, "func_str_id": 0} + cases = [ + (LocationInfo(42, 45, -1, 12), + {**common, "line": 42, "end_line": 45, "end_col": 12}), + (LocationInfo(42, 45, 4, -1), + {**common, "line": 42, "end_line": 45, "col": 4}), + (LocationInfo(42, 0, 4, 8), + {**common, "line": 42, "col": 4, "end_col": 8}), + ] + for loc, expected_frame_def in cases: + with self.subTest(location=loc): + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(1000) + frame = MockFrameInfo("test.py", 0, "f") + frame.location = loc + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)], + ) + ] + collector.collect(frames) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + _, _, frame_defs, _, _ = jsonl_tables(records) + self.assertEqual(frame_defs, [expected_frame_def]) + + +class TestRecursiveFunctionHandling(unittest.TestCase): + """Tests for correct handling of recursive functions in cumulative stats.""" + + def test_pstats_collector_recursive_function_single_sample(self): + """Test that recursive functions are counted once per sample, not per occurrence.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Simulate a recursive function appearing 5 times in one sample + recursive_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + ], + ) + ], + ) + ] + collector.collect(recursive_frames) + + location = ("test.py", 10, "recursive_func") + # Should count as 1 cumulative call (present in 1 sample), not 5 + self.assertEqual(collector.result[location]["cumulative_calls"], 1) + # Direct calls should be 1 (top of stack) + self.assertEqual(collector.result[location]["direct_calls"], 1) + + def test_pstats_collector_recursive_function_multiple_samples(self): + """Test cumulative counting across multiple samples with recursion.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Sample 1: recursive function at depth 3 + sample1 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + ], + ) + ], + ) + ] + # Sample 2: recursive function at depth 2 + sample2 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + ], + ) + ], + ) + ] + # Sample 3: recursive function at depth 4 + sample3 = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + ], + ) + ], + ) + ] + + collector.collect(sample1) + collector.collect(sample2) + collector.collect(sample3) + + location = ("test.py", 10, "recursive_func") + # Should count as 3 cumulative calls (present in 3 samples) + # Not 3+2+4=9 which would be the buggy behavior + self.assertEqual(collector.result[location]["cumulative_calls"], 3) + self.assertEqual(collector.result[location]["direct_calls"], 3) + + def test_pstats_collector_mixed_recursive_and_nonrecursive(self): + """Test a call stack with both recursive and non-recursive functions.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Stack: main -> foo (recursive x3) -> bar + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("test.py", 50, "bar"), # top of stack + MockFrameInfo("test.py", 20, "foo"), # recursive + MockFrameInfo("test.py", 20, "foo"), # recursive + MockFrameInfo("test.py", 20, "foo"), # recursive + MockFrameInfo("test.py", 10, "main"), # bottom + ], + ) + ], + ) + ] + collector.collect(frames) + + # bar: 1 cumulative (in stack), 1 direct (top) + self.assertEqual(collector.result[("test.py", 50, "bar")]["cumulative_calls"], 1) + self.assertEqual(collector.result[("test.py", 50, "bar")]["direct_calls"], 1) + + # foo: 1 cumulative (counted once despite 3 occurrences), 0 direct + self.assertEqual(collector.result[("test.py", 20, "foo")]["cumulative_calls"], 1) + self.assertEqual(collector.result[("test.py", 20, "foo")]["direct_calls"], 0) + + # main: 1 cumulative, 0 direct + self.assertEqual(collector.result[("test.py", 10, "main")]["cumulative_calls"], 1) + self.assertEqual(collector.result[("test.py", 10, "main")]["direct_calls"], 0) + + def test_pstats_collector_cumulative_percentage_cannot_exceed_100(self): + """Test that cumulative percentage stays <= 100% even with deep recursion.""" + collector = PstatsCollector(sample_interval_usec=1000000) # 1 second for easy math + + # Collect 10 samples, each with recursive function at depth 100 + for _ in range(10): + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [MockFrameInfo("test.py", 10, "deep_recursive")] * 100, + ) + ], + ) + ] + collector.collect(frames) + + location = ("test.py", 10, "deep_recursive") + # Cumulative calls should be 10 (number of samples), not 1000 + self.assertEqual(collector.result[location]["cumulative_calls"], 10) + + # Verify stats calculation gives correct percentage + collector.create_stats() + stats = collector.stats[location] + # stats format: (direct_calls, cumulative_calls, total_time, cumulative_time, callers) + cumulative_calls = stats[1] + self.assertEqual(cumulative_calls, 10) + + def test_pstats_collector_different_lines_same_function_counted_separately(self): + """Test that different line numbers in same function are tracked separately.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Function with multiple line numbers (e.g., different call sites within recursion) + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("test.py", 15, "func"), # line 15 + MockFrameInfo("test.py", 12, "func"), # line 12 + MockFrameInfo("test.py", 15, "func"), # line 15 again + MockFrameInfo("test.py", 10, "func"), # line 10 + ], + ) + ], + ) + ] + collector.collect(frames) + + # Each unique (file, line, func) should be counted once + self.assertEqual(collector.result[("test.py", 15, "func")]["cumulative_calls"], 1) + self.assertEqual(collector.result[("test.py", 12, "func")]["cumulative_calls"], 1) + self.assertEqual(collector.result[("test.py", 10, "func")]["cumulative_calls"], 1) + + +class TestLocationHelpers(unittest.TestCase): + """Tests for location handling helper functions.""" + + def test_extract_lineno_from_location_info(self): + """Test extracting lineno from LocationInfo namedtuple.""" + loc = LocationInfo(42, 45, 0, 10) + self.assertEqual(extract_lineno(loc), 42) + + def test_extract_lineno_from_tuple(self): + """Test extracting lineno from plain tuple.""" + loc = (100, 105, 5, 20) + self.assertEqual(extract_lineno(loc), 100) + + def test_extract_lineno_from_none(self): + """Test extracting lineno from None (synthetic frames).""" + self.assertEqual(extract_lineno(None), 0) + + def test_extract_lineno_from_int(self): + """Test extracting lineno from a bare integer line number. + + Mirrors normalize_location's int contract so callers like the + collapsed/flamegraph collectors do not crash on a bare-int location. + """ + self.assertEqual(extract_lineno(42), 42) + self.assertEqual(extract_lineno(0), 0) + + def test_normalize_location_with_int(self): + """Test normalize_location expands a legacy integer line number.""" + result = normalize_location(42) + self.assertEqual(result, (42, 42, -1, -1)) + + def test_normalize_location_with_location_info(self): + """Test normalize_location passes through LocationInfo.""" + loc = LocationInfo(10, 15, 0, 5) + result = normalize_location(loc) + self.assertEqual(result, loc) + + def test_normalize_location_with_tuple(self): + """Test normalize_location passes through tuple.""" + loc = (10, 15, 0, 5) + result = normalize_location(loc) + self.assertEqual(result, loc) + + def test_normalize_location_with_none(self): + """Test normalize_location returns DEFAULT_LOCATION for None.""" + result = normalize_location(None) + self.assertEqual(result, DEFAULT_LOCATION) + self.assertEqual(result, (0, 0, -1, -1)) + + +class TestOpcodeFormatting(unittest.TestCase): + """Tests for opcode formatting utilities.""" + + def test_get_opcode_info_standard_opcode(self): + """Test get_opcode_info for a standard opcode.""" + # LOAD_CONST is a standard opcode + load_const = opcode.opmap.get('LOAD_CONST') + if load_const is not None: + info = get_opcode_info(load_const) + self.assertEqual(info['opname'], 'LOAD_CONST') + self.assertEqual(info['base_opname'], 'LOAD_CONST') + self.assertFalse(info['is_specialized']) + + def test_get_opcode_info_unknown_opcode(self): + """Test get_opcode_info for an unknown opcode.""" + info = get_opcode_info(999) + self.assertEqual(info['opname'], '<999>') + self.assertEqual(info['base_opname'], '<999>') + self.assertFalse(info['is_specialized']) + + def test_format_opcode_standard(self): + """Test format_opcode for a standard opcode.""" + load_const = opcode.opmap.get('LOAD_CONST') + if load_const is not None: + formatted = format_opcode(load_const) + self.assertEqual(formatted, 'LOAD_CONST') + + def test_format_opcode_specialized(self): + """Test format_opcode for a specialized opcode shows base in parens.""" + if not hasattr(opcode, '_specialized_opmap'): + self.skipTest("No specialized opcodes in this Python version") + if not hasattr(opcode, '_specializations'): + self.skipTest("No specialization info in this Python version") + + # Find any specialized opcode to test + for base_name, variants in opcode._specializations.items(): + if not variants: + continue + variant_name = variants[0] + variant_opcode = opcode._specialized_opmap.get(variant_name) + if variant_opcode is None: + continue + formatted = format_opcode(variant_opcode) + # Should show: VARIANT_NAME (BASE_NAME) + self.assertIn(variant_name, formatted) + self.assertIn(f'({base_name})', formatted) + return + + self.skipTest("No specialized opcodes found") + + def test_format_opcode_unknown(self): + """Test format_opcode for an unknown opcode.""" + formatted = format_opcode(999) + self.assertEqual(formatted, '<999>') + + +class TestLocationInCollectors(unittest.TestCase): + """Tests for location tuple handling in each collector.""" + + def _make_frames_with_location(self, location, opcode=None): + """Create test frames with a specific location.""" + frame = MockFrameInfo("test.py", 0, "test_func", opcode) + # Override the location + frame.location = location + return [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + + def test_pstats_collector_with_location_info(self): + """Test PstatsCollector handles LocationInfo properly.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Frame with LocationInfo + frame = MockFrameInfo("test.py", 42, "my_function") + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + # Should extract lineno from location + key = ("test.py", 42, "my_function") + self.assertIn(key, collector.result) + self.assertEqual(collector.result[key]["direct_calls"], 1) + + def test_pstats_collector_with_none_location(self): + """Test PstatsCollector handles None location (synthetic frames).""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Create frame with None location (like GC frame) + frame = MockFrameInfo("~", 0, "") + frame.location = None # Synthetic frame has no location + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + # Should use lineno=0 for None location + key = ("~", 0, "") + self.assertIn(key, collector.result) + + def test_collapsed_stack_with_location_info(self): + """Test CollapsedStackCollector handles LocationInfo properly.""" + collector = CollapsedStackCollector(1000) + + frame1 = MockFrameInfo("main.py", 10, "main") + frame2 = MockFrameInfo("utils.py", 25, "helper") + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame1, frame2], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + # Check that linenos were extracted correctly + self.assertEqual(len(collector.stack_counter), 1) + (path, _), count = list(collector.stack_counter.items())[0] + # Reversed order: helper at top, main at bottom + self.assertEqual(path[0], ("utils.py", 25, "helper")) + self.assertEqual(path[1], ("main.py", 10, "main")) + + def test_flamegraph_collector_with_location_info(self): + """Test FlamegraphCollector handles LocationInfo properly.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + frame = MockFrameInfo("app.py", 100, "process_data") + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + data = collector._convert_to_flamegraph_format() + # Verify the function name includes lineno from location + strings = data.get("strings", []) + name_found = any("process_data" in s and "100" in s for s in strings if isinstance(s, str)) + self.assertTrue(name_found, f"Expected to find 'process_data' with line 100 in {strings}") + + def test_gecko_collector_with_location_info(self): + """Test GeckoCollector handles LocationInfo properly.""" + collector = GeckoCollector(sample_interval_usec=1000) + + frame = MockFrameInfo("server.py", 50, "handle_request") + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + profile = collector._build_profile() + # Check that the function was recorded + self.assertEqual(len(profile["threads"]), 1) + thread_data = profile["threads"][0] + string_array = profile["shared"]["stringArray"] + + # Verify function name is in string table + self.assertIn("handle_request", string_array) + + def test_jsonl_collector_with_location_info(self): + """Test JsonlCollector handles LocationInfo properly.""" + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(sample_interval_usec=1000) + + # Frame with LocationInfo + frame = MockFrameInfo("test.py", 42, "my_function") + frames = [ + MockInterpreterInfo( + 0, [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + meta, str_defs, frame_defs, agg, end = jsonl_tables(records) + self.assertEqual(meta["sample_interval_usec"], 1000) + self.assertEqual(agg["samples_total"], 1) + self.assertEqual(end["samples_total"], 1) + self.assertEqual(len(frame_defs), 1) + self.assertEqual(str_defs[frame_defs[0]["path_str_id"]], "test.py") + self.assertEqual(str_defs[frame_defs[0]["func_str_id"]], "my_function") + self.assertEqual( + frame_defs[0], + { + "frame_id": 0, + "path_str_id": frame_defs[0]["path_str_id"], + "func_str_id": frame_defs[0]["func_str_id"], + "line": 42, + "end_line": 42, + }, + ) + + def test_jsonl_collector_with_none_location(self): + """Test JsonlCollector handles None location (synthetic frames).""" + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + collector = JsonlCollector(sample_interval_usec=1000) + + # Create frame with None location (like GC frame) + frame = MockFrameInfo("~", 0, "") + frame.location = None # Synthetic frame has no location + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + meta, str_defs, frame_defs, agg, end = jsonl_tables(records) + self.assertEqual(meta["sample_interval_usec"], 1000) + self.assertEqual(agg["samples_total"], 1) + self.assertEqual(end["samples_total"], 1) + self.assertEqual(len(frame_defs), 1) + self.assertEqual(str_defs[frame_defs[0]["path_str_id"]], "~") + self.assertEqual(str_defs[frame_defs[0]["func_str_id"]], "") + self.assertEqual( + frame_defs[0], + { + "frame_id": 0, + "path_str_id": frame_defs[0]["path_str_id"], + "func_str_id": frame_defs[0]["func_str_id"], + "line": 0, + }, + ) + + +class TestOpcodeHandling(unittest.TestCase): + """Tests for opcode field handling in collectors.""" + + def test_frame_with_opcode(self): + """Test MockFrameInfo properly stores opcode.""" + frame = MockFrameInfo("test.py", 10, "my_func", opcode=90) + self.assertEqual(frame.opcode, 90) + # Verify tuple representation includes opcode + self.assertEqual(frame[3], 90) + self.assertEqual(len(frame), 4) + + def test_frame_without_opcode(self): + """Test MockFrameInfo with no opcode defaults to None.""" + frame = MockFrameInfo("test.py", 10, "my_func") + self.assertIsNone(frame.opcode) + self.assertIsNone(frame[3]) + + def test_collectors_ignore_opcode_for_key_generation(self): + """Test that collectors use (filename, lineno, funcname) as key, not opcode.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Same function, different opcodes + frame1 = MockFrameInfo("test.py", 10, "func", opcode=90) + frame2 = MockFrameInfo("test.py", 10, "func", opcode=100) + + frames1 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame1], status=THREAD_STATUS_HAS_GIL)] + ) + ] + frames2 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame2], status=THREAD_STATUS_HAS_GIL)] + ) + ] + + collector.collect(frames1) + collector.collect(frames2) + + # Should be counted as same function (opcode not in key) + key = ("test.py", 10, "func") + self.assertIn(key, collector.result) + self.assertEqual(collector.result[key]["direct_calls"], 2) + + +class TestGeckoOpcodeMarkers(unittest.TestCase): + """Tests for GeckoCollector opcode interval markers.""" + + def test_gecko_collector_opcodes_disabled_by_default(self): + """Test that opcode tracking is disabled by default.""" + collector = GeckoCollector(sample_interval_usec=1000) + self.assertFalse(collector.opcodes_enabled) + + def test_gecko_collector_opcodes_enabled(self): + """Test that opcode tracking can be enabled.""" + collector = GeckoCollector(sample_interval_usec=1000, opcodes=True) + self.assertTrue(collector.opcodes_enabled) + + def test_gecko_opcode_state_tracking(self): + """Test that GeckoCollector tracks opcode state changes.""" + collector = GeckoCollector(sample_interval_usec=1000, opcodes=True) + self.addCleanup(collector._cleanup_spills) + + # First sample with opcode 90 (RAISE_VARARGS) + frame1 = MockFrameInfo("test.py", 10, "func", opcode=90) + frames1 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame1], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames1) + + # Should start tracking this opcode state + self.assertIn(1, collector.opcode_state) + state = collector.opcode_state[1] + self.assertEqual(state[0], 90) # opcode + self.assertEqual(state[1], 10) # lineno + self.assertEqual(state[3], "func") # funcname + + def test_gecko_opcode_state_change_emits_marker(self): + """Test that opcode state change emits an interval marker.""" + collector = GeckoCollector(sample_interval_usec=1000, opcodes=True) + + # First sample: opcode 90 + frame1 = MockFrameInfo("test.py", 10, "func", opcode=90) + frames1 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame1], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames1) + + # Second sample: different opcode 100 + frame2 = MockFrameInfo("test.py", 10, "func", opcode=100) + frames2 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame2], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames2) + + # Should have emitted a marker for the first opcode + profile = collector._build_profile() + markers = profile["threads"][0]["markers"] + assert_gecko_column_lengths( + self, markers, + ("data", "name", "startTime", "endTime", "phase", "category"), + ) + opcode_markers = gecko_opcode_marker_data(profile) + self.assertIn( + { + "opcode": 90, + "line": 10, + "function": "func", + }, + [ + { + "opcode": marker["opcode"], + "line": marker["line"], + "function": marker["function"], + } + for marker in opcode_markers + ], + ) + + def test_gecko_opcode_markers_not_emitted_when_disabled(self): + """Test that no opcode markers when opcodes=False.""" + collector = GeckoCollector(sample_interval_usec=1000, opcodes=False) + + frame1 = MockFrameInfo("test.py", 10, "func", opcode=90) + frames1 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame1], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames1) + + frame2 = MockFrameInfo("test.py", 10, "func", opcode=100) + frames2 = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame2], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames2) + + profile = collector._build_profile() + self.assertEqual(gecko_opcode_marker_data(profile), []) + self.assertEqual(profile["meta"]["markerSchema"], []) + + def test_gecko_opcode_with_none_opcode(self): + """Test that None opcode doesn't cause issues.""" + collector = GeckoCollector(sample_interval_usec=1000, opcodes=True) + + # Frame with no opcode (None) + frame = MockFrameInfo("test.py", 10, "func", opcode=None) + frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(1, [frame], status=THREAD_STATUS_HAS_GIL)] + ) + ] + collector.collect(frames) + + profile = collector._build_profile() + self.assertEqual(gecko_opcode_marker_data(profile), []) + + +class TestCollectorFrameFormat(unittest.TestCase): + """Tests verifying all collectors handle the 4-element frame format.""" + + def _make_sample_frames(self): + """Create sample frames with full format: (filename, location, funcname, opcode).""" + return [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("app.py", 100, "main", opcode=90), + MockFrameInfo("utils.py", 50, "helper", opcode=100), + MockFrameInfo("lib.py", 25, "process", opcode=None), + ], + status=THREAD_STATUS_HAS_GIL, + ) + ], + ) + ] + + def test_pstats_collector_frame_format(self): + """Test PstatsCollector with 4-element frame format.""" + collector = PstatsCollector(sample_interval_usec=1000) + collector.collect(self._make_sample_frames()) + + # All three functions should be recorded + self.assertEqual(len(collector.result), 3) + self.assertIn(("app.py", 100, "main"), collector.result) + self.assertIn(("utils.py", 50, "helper"), collector.result) + self.assertIn(("lib.py", 25, "process"), collector.result) + + def test_collapsed_stack_frame_format(self): + """Test CollapsedStackCollector with 4-element frame format.""" + collector = CollapsedStackCollector(sample_interval_usec=1000) + collector.collect(self._make_sample_frames()) + + self.assertEqual(len(collector.stack_counter), 1) + (path, _), _ = list(collector.stack_counter.items())[0] + # 3 frames in the path (reversed order) + self.assertEqual(len(path), 3) + + def test_flamegraph_collector_frame_format(self): + """Test FlamegraphCollector with 4-element frame format.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + collector.collect(self._make_sample_frames()) + + data = collector._convert_to_flamegraph_format() + # Should have processed the frames + self.assertIn("children", data) + + def test_gecko_collector_frame_format(self): + """Test GeckoCollector with 4-element frame format.""" + collector = GeckoCollector(sample_interval_usec=1000) + collector.collect(self._make_sample_frames()) + + profile = collector._build_profile() + # Should have one thread with the frames + self.assertEqual(len(profile["threads"]), 1) + thread = profile["threads"][0] + # Should have recorded 3 functions + self.assertEqual(thread["funcTable"]["length"], 3) + + def test_jsonl_collector_frame_format(self): + """Test JsonlCollector with 4-element frame format.""" + collector = JsonlCollector(sample_interval_usec=1000) + collector.collect(self._make_sample_frames()) + + with tempfile.NamedTemporaryFile(delete=False) as f: + self.addClassCleanup(close_and_unlink, f) + collector.export(f.name) + + with open(f.name, "r", encoding="utf-8") as fp: + records = [json.loads(line) for line in fp] + + _, str_defs, frame_defs, _, _ = jsonl_tables(records) + + self.assertEqual(len(frame_defs), 3) + + paths = {str_defs[item["path_str_id"]] for item in frame_defs} + funcs = {str_defs[item["func_str_id"]] for item in frame_defs} + + self.assertEqual(paths, {"app.py", "utils.py", "lib.py"}) + self.assertEqual(funcs, {"main", "helper", "process"}) + + +class TestInternalFrameFiltering(unittest.TestCase): + """Tests for filtering internal profiler frames from output.""" + + def test_filter_internal_frames(self): + """Test that _sync_coordinator frames are filtered from anywhere in stack.""" + from profiling.sampling.collector import filter_internal_frames + + # Stack with _sync_coordinator in the middle (realistic scenario) + frames = [ + MockFrameInfo("user_script.py", 10, "user_func"), + MockFrameInfo("/path/to/_sync_coordinator.py", 100, "main"), + MockFrameInfo("", 87, "_run_code"), + ] + + filtered = filter_internal_frames(frames) + self.assertEqual(len(filtered), 2) + self.assertEqual(filtered[0].filename, "user_script.py") + self.assertEqual(filtered[1].filename, "") + + def test_pstats_collector_filters_internal_frames(self): + """Test that PstatsCollector filters out internal frames.""" + collector = PstatsCollector(sample_interval_usec=1000) + + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("user_script.py", 10, "user_func"), + MockFrameInfo("/path/to/_sync_coordinator.py", 100, "main"), + MockFrameInfo("", 87, "_run_code"), + ], + status=THREAD_STATUS_HAS_GIL, + ) + ], + ) + ] + collector.collect(frames) + + self.assertEqual(len(collector.result), 2) + self.assertIn(("user_script.py", 10, "user_func"), collector.result) + self.assertIn(("", 87, "_run_code"), collector.result) + + def test_gecko_collector_filters_internal_frames(self): + """Test that GeckoCollector filters out internal frames.""" + collector = GeckoCollector(sample_interval_usec=1000) + + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("app.py", 50, "run"), + MockFrameInfo("/lib/_sync_coordinator.py", 100, "main"), + ], + status=THREAD_STATUS_HAS_GIL, + ) + ], + ) + ] + collector.collect(frames) + + profile = collector._build_profile() + string_array = profile["shared"]["stringArray"] + + # Should not contain _sync_coordinator functions + for s in string_array: + self.assertNotIn("_sync_coordinator", s) + + def test_flamegraph_collector_filters_internal_frames(self): + """Test that FlamegraphCollector filters out internal frames.""" + collector = FlamegraphCollector(sample_interval_usec=1000) + + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("app.py", 50, "run"), + MockFrameInfo("/lib/_sync_coordinator.py", 100, "main"), + MockFrameInfo("", 87, "_run_code"), + ], + status=THREAD_STATUS_HAS_GIL, + ) + ], + ) + ] + collector.collect(frames) + + data = collector._convert_to_flamegraph_format() + strings = data.get("strings", []) + + for s in strings: + self.assertNotIn("_sync_coordinator", s) + + def test_collapsed_stack_collector_filters_internal_frames(self): + """Test that CollapsedStackCollector filters out internal frames.""" + collector = CollapsedStackCollector(sample_interval_usec=1000) + + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("app.py", 50, "run"), + MockFrameInfo("/lib/_sync_coordinator.py", 100, "main"), + ], + status=THREAD_STATUS_HAS_GIL, + ) + ], + ) + ] + collector.collect(frames) + + # Check that no stack contains _sync_coordinator + for (call_tree, _), _ in collector.stack_counter.items(): + for filename, _, _ in call_tree: + self.assertNotIn("_sync_coordinator", filename) + + def test_jsonl_collector_filters_internal_frames(self): + """Test that JsonlCollector filters out internal frames.""" + jsonl_out = tempfile.NamedTemporaryFile(delete=False) + self.addCleanup(close_and_unlink, jsonl_out) + + frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("app.py", 50, "run"), + MockFrameInfo("/lib/_sync_coordinator.py", 100, "main"), + MockFrameInfo("", 87, "_run_code"), + ], + status=THREAD_STATUS_HAS_GIL, + ) + ], + ) + ] + + collector = JsonlCollector(sample_interval_usec=1000) + collector.collect(frames) + collector.export(jsonl_out.name) + + with open(jsonl_out.name, "r", encoding="utf-8") as f: + records = [json.loads(line) for line in f] + + _, str_defs, frame_defs, _, _ = jsonl_tables(records) + + paths = {str_defs[item["path_str_id"]] for item in frame_defs} + + self.assertIn("app.py", paths) + self.assertIn("", paths) + + for path in paths: + self.assertNotIn("_sync_coordinator", path) diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_dump.py b/Lib/test/test_profiling/test_sampling_profiler/test_dump.py new file mode 100644 index 00000000000..7a0f8df38a8 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_dump.py @@ -0,0 +1,454 @@ +"""Tests for one-shot sampling profiler stack dumps.""" + +from collections import namedtuple +import os +import opcode +import tempfile +import unittest + +import _colorize + +from profiling.sampling.constants import ( + THREAD_STATUS_GIL_REQUESTED, + THREAD_STATUS_HAS_EXCEPTION, + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_MAIN_THREAD, + THREAD_STATUS_ON_CPU, + THREAD_STATUS_UNKNOWN, +) +from profiling.sampling.dump import format_stack_dump + +from .mocks import ( + LocationInfo as StructseqLocationInfo, + MockAwaitedInfo, + MockCoroInfo, + MockFrameInfo, + MockInterpreterInfo, + MockTaskInfo, + MockThreadInfo, +) + +try: + import _remote_debugging # noqa: F401 +except ImportError: + _remote_debugging = None + + +StructseqInterpreterInfo = namedtuple( + "StructseqInterpreterInfo", + ["interpreter_id", "threads"], +) +StructseqThreadInfo = namedtuple( + "StructseqThreadInfo", + ["thread_id", "status", "frame_info"], +) +StructseqFrameInfo = namedtuple( + "StructseqFrameInfo", + ["filename", "location", "funcname", "opcode"], +) + + +class TestStackDumpFormatting(unittest.TestCase): + def test_format_stack_dump_single_thread(self): + frames = [ + MockFrameInfo("leaf.py", 10, "leaf"), + MockFrameInfo("root.py", 1, "root"), + ] + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + frames, + status=( + THREAD_STATUS_MAIN_THREAD + | THREAD_STATUS_HAS_GIL + | THREAD_STATUS_ON_CPU + ), + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 123 " + "(main thread, has GIL, on CPU; most recent call last):", + output, + ) + self.assertNotIn("Interpreter 0", output) + self.assertLess( + output.index('File "root.py", line 1, in root'), + output.index('File "leaf.py", line 10, in leaf'), + ) + self.assertIn(' File "root.py", line 1, in root', output) + self.assertIn(' File "leaf.py", line 10, in leaf', output) + self.assertNotIn("\x1b[", output) + + def test_format_stack_dump_with_structseq_tuples(self): + stack_frames = [ + StructseqInterpreterInfo( + 0, + [ + StructseqThreadInfo( + 123, + THREAD_STATUS_HAS_GIL, + [ + StructseqFrameInfo( + "file.py", + StructseqLocationInfo(5, 5, -1, -1), + "func", + None, + ) + ], + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 123 " + "(has GIL; most recent call last):", + output, + ) + self.assertIn(' File "file.py", line 5, in func', output) + + def test_format_stack_dump_shows_interpreter_ids_when_multiple(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(100, [MockFrameInfo("main.py", 1, "main")])], + ), + MockInterpreterInfo( + 1, + [MockThreadInfo(200, [MockFrameInfo("sub.py", 2, "sub")])], + ), + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 100 " + "(interpreter 0; idle; most recent call last):", + output, + ) + self.assertIn( + "Stack dump, thread 200 " + "(interpreter 1; idle; most recent call last):", + output, + ) + + def test_format_stack_dump_omits_unknown_status(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [MockFrameInfo("file.py", 5, "func")], + status=THREAD_STATUS_UNKNOWN, + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 123 (most recent call last):", + output, + ) + self.assertNotIn("unknown", output) + + def test_format_stack_dump_omits_unknown_when_other_status_exists(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [MockFrameInfo("file.py", 5, "func")], + status=THREAD_STATUS_UNKNOWN | THREAD_STATUS_ON_CPU, + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 123 " + "(on CPU; most recent call last):", + output, + ) + self.assertNotIn("unknown", output) + + def test_format_stack_dump_labels_known_idle_status(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [MockFrameInfo("file.py", 5, "func")], + status=0, + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 123 " + "(idle; most recent call last):", + output, + ) + + def test_format_stack_dump_status_does_not_add_idle_to_waiting_thread(self): + status = ( + THREAD_STATUS_MAIN_THREAD + | THREAD_STATUS_GIL_REQUESTED + | THREAD_STATUS_HAS_EXCEPTION + ) + stack_frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(123, [MockFrameInfo("file.py", 5, "func")], status=status)], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 123 " + "(main thread, waiting for GIL, has exception; most recent call last):", + output, + ) + self.assertNotIn("idle", output) + + def test_format_stack_dump_formats_opcode_name(self): + load_const = opcode.opmap["LOAD_CONST"] + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [ + StructseqFrameInfo( + "file.py", + StructseqLocationInfo(5, 5, -1, -1), + "func", + load_const, + ) + ], + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn("opcode=LOAD_CONST", output) + self.assertNotIn(f"opcode={load_const}", output) + + def test_format_stack_dump_formats_unknown_opcode(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [ + StructseqFrameInfo( + "file.py", + StructseqLocationInfo(5, 5, -1, -1), + "func", + 999, + ) + ], + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn("opcode=<999>", output) + + def test_format_stack_dump_prefers_qualname_attribute(self): + class Frame: + filename = "file.py" + location = StructseqLocationInfo(5, 5, -1, -1) + funcname = "inner" + qualname = "Outer.inner" + opcode = None + + stack_frames = [ + MockInterpreterInfo(0, [MockThreadInfo(123, [Frame()])]) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn(' File "file.py", line 5, in Outer.inner', output) + self.assertNotIn("in inner", output) + + def test_format_stack_dump_filters_internal_frames(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [ + MockFrameInfo("user.py", 10, "user"), + MockFrameInfo("_sync_coordinator.py", 20, "internal"), + ], + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn(' File "user.py", line 10, in user', output) + self.assertNotIn("_sync_coordinator.py", output) + + @unittest.skipIf(_remote_debugging is None, "requires _remote_debugging") + def test_format_stack_dump_async_task(self): + task = MockTaskInfo( + task_id=1, + task_name="Task-1", + coroutine_stack=[ + MockCoroInfo( + "Task-1", + [MockFrameInfo("task.py", 5, "waiter")], + ) + ], + ) + stack_frames = [MockAwaitedInfo(thread_id=123, awaited_by=[task])] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn( + "Stack dump for PID 42, thread 123 " + "(task 1; most recent call last):", + output, + ) + self.assertIn(' File "task.py", line 5, in waiter', output) + + def test_format_stack_dump_strips_source_like_traceback(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [ + StructseqFrameInfo( + __file__, + StructseqLocationInfo(1, 1, -1, -1), + "", + None, + ) + ], + ) + ], + ) + ] + + output = format_stack_dump(stack_frames, pid=42, colorize=False) + + self.assertIn(' File "', output) + self.assertIn('", line 1, in ', output) + self.assertIn('"""Tests for one-shot sampling profiler stack dumps."""', output) + self.assertNotIn("^^^^^^^^", output) + + def test_format_stack_dump_highlights_source_range(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [ + StructseqFrameInfo( + __file__, + StructseqLocationInfo(1, 1, 0, 3), + "", + None, + ) + ], + ) + ], + ) + ] + theme = _colorize.get_theme(force_color=True).profiler_dump + + output = format_stack_dump(stack_frames, pid=42, colorize=True) + + self.assertIn( + f"{theme.source_highlight}\"\"\"{theme.reset}", + output, + ) + self.assertNotIn("^^^^^^^^", _colorize.decolor(output)) + + def test_format_stack_dump_highlights_source_range_after_trimming(self): + with tempfile.TemporaryDirectory() as tmp_dir: + filename = os.path.join(tmp_dir, "target.py") + with open(filename, "w", encoding="utf-8") as file: + file.write(" result = call(arg)\n") + stack_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 123, + [ + StructseqFrameInfo( + filename, + StructseqLocationInfo(1, 1, 13, 17), + "", + None, + ) + ], + ) + ], + ) + ] + theme = _colorize.get_theme(force_color=True).profiler_dump + + output = format_stack_dump(stack_frames, pid=42, colorize=True) + + self.assertIn(f"{theme.source_highlight}call{theme.reset}", output) + self.assertIn("\n result = call(arg)\n", _colorize.decolor(output)) + self.assertNotIn("\n result = call(arg)\n", _colorize.decolor(output)) + + def test_format_stack_dump_empty(self): + output = format_stack_dump([], pid=42, colorize=False) + + self.assertEqual("No Python stacks found for PID 42\n", output) + + def test_format_stack_dump_colorized(self): + stack_frames = [ + MockInterpreterInfo( + 0, + [MockThreadInfo(123, [MockFrameInfo("file.py", 5, "func")])], + ) + ] + theme = _colorize.get_theme(force_color=True).profiler_dump + + output = format_stack_dump(stack_frames, pid=42, colorize=True) + + self.assertIn(theme.header, output) + self.assertIn(theme.filename, output) + self.assertIn(theme.reset, output) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_integration.py b/Lib/test/test_profiling/test_sampling_profiler/test_integration.py new file mode 100644 index 00000000000..3487647b766 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_integration.py @@ -0,0 +1,953 @@ +"""Tests for sampling profiler integration and error handling.""" + +import contextlib +import io +import marshal +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from unittest import mock + +try: + import _remote_debugging + import profiling.sampling + import profiling.sampling.sample + from profiling.sampling.pstats_collector import PstatsCollector + from profiling.sampling.stack_collector import CollapsedStackCollector + from profiling.sampling.sample import SampleProfiler, _is_process_running + from profiling.sampling.cli import main +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from test.support import ( + requires_remote_subprocess_debugging, + SHORT_TIMEOUT, +) + +from .helpers import ( + test_subprocess, + close_and_unlink, +) +from .mocks import MockFrameInfo, MockThreadInfo, MockInterpreterInfo + +# Duration for profiling tests - long enough for process to complete naturally +PROFILING_TIMEOUT = str(int(SHORT_TIMEOUT)) + +# Duration for profiling in tests - short enough to complete quickly +PROFILING_DURATION_SEC = 2 + + +@requires_remote_subprocess_debugging() +class TestRecursiveFunctionProfiling(unittest.TestCase): + """Test profiling of recursive functions and complex call patterns.""" + + def test_recursive_function_call_counting(self): + """Test that recursive function calls are counted correctly.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Simulate a recursive call pattern: fibonacci(5) calling itself + recursive_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ # First sample: deep in recursion + MockFrameInfo("fib.py", 10, "fibonacci"), + MockFrameInfo( + "fib.py", 10, "fibonacci" + ), # recursive call + MockFrameInfo( + "fib.py", 10, "fibonacci" + ), # deeper recursion + MockFrameInfo( + "fib.py", 10, "fibonacci" + ), # even deeper + MockFrameInfo("main.py", 5, "main"), # main caller + ], + ) + ], + ), + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ # Second sample: different recursion depth + MockFrameInfo("fib.py", 10, "fibonacci"), + MockFrameInfo( + "fib.py", 10, "fibonacci" + ), # recursive call + MockFrameInfo("main.py", 5, "main"), # main caller + ], + ) + ], + ), + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ # Third sample: back to deeper recursion + MockFrameInfo("fib.py", 10, "fibonacci"), + MockFrameInfo("fib.py", 10, "fibonacci"), + MockFrameInfo("fib.py", 10, "fibonacci"), + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + ] + + for frames in recursive_frames: + collector.collect([frames]) + + collector.create_stats() + + # Check that recursive calls are counted properly + fib_key = ("fib.py", 10, "fibonacci") + main_key = ("main.py", 5, "main") + + self.assertIn(fib_key, collector.stats) + self.assertIn(main_key, collector.stats) + + # Fibonacci: counted once per sample, not per occurrence + fib_stats = collector.stats[fib_key] + direct_calls, cumulative_calls, tt, ct, callers = fib_stats + + # Should count 3 (present in 3 samples), not 9 (total occurrences) + self.assertEqual(cumulative_calls, 3) + self.assertEqual(direct_calls, 3) # Top of stack in all samples + self.assertGreater(tt, 0) + self.assertGreater(ct, 0) + + # Main should also have 3 cumulative calls (in all 3 samples) + main_stats = collector.stats[main_key] + main_direct_calls, main_cumulative_calls = main_stats[0], main_stats[1] + self.assertEqual(main_direct_calls, 0) # Never directly executing + self.assertEqual(main_cumulative_calls, 3) # Appears in all 3 samples + + def test_nested_function_hierarchy(self): + """Test profiling of deeply nested function calls.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Simulate a deep call hierarchy + deep_call_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("level1.py", 10, "level1_func"), + MockFrameInfo("level2.py", 20, "level2_func"), + MockFrameInfo("level3.py", 30, "level3_func"), + MockFrameInfo("level4.py", 40, "level4_func"), + MockFrameInfo("level5.py", 50, "level5_func"), + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ # Same hierarchy sampled again + MockFrameInfo("level1.py", 10, "level1_func"), + MockFrameInfo("level2.py", 20, "level2_func"), + MockFrameInfo("level3.py", 30, "level3_func"), + MockFrameInfo("level4.py", 40, "level4_func"), + MockFrameInfo("level5.py", 50, "level5_func"), + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + ] + + for frames in deep_call_frames: + collector.collect([frames]) + + collector.create_stats() + + # All levels should be recorded + for level in range(1, 6): + key = (f"level{level}.py", level * 10, f"level{level}_func") + self.assertIn(key, collector.stats) + + stats = collector.stats[key] + direct_calls, cumulative_calls, tt, ct, callers = stats + + # Each level should appear in stack twice (2 samples) + self.assertEqual(cumulative_calls, 2) + + # Only level1 (deepest) should have direct calls + if level == 1: + self.assertEqual(direct_calls, 2) + else: + self.assertEqual(direct_calls, 0) + + # Deeper levels should have lower cumulative time than higher levels + # (since they don't include time from functions they call) + if level == 1: # Deepest level with most time + self.assertGreater(ct, 0) + + def test_alternating_call_patterns(self): + """Test profiling with alternating call patterns.""" + collector = PstatsCollector(sample_interval_usec=1000) + + # Simulate alternating execution paths + pattern_frames = [ + # Pattern A: path through func_a + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("module.py", 10, "func_a"), + MockFrameInfo("module.py", 30, "shared_func"), + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + # Pattern B: path through func_b + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("module.py", 20, "func_b"), + MockFrameInfo("module.py", 30, "shared_func"), + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + # Pattern A again + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("module.py", 10, "func_a"), + MockFrameInfo("module.py", 30, "shared_func"), + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + # Pattern B again + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("module.py", 20, "func_b"), + MockFrameInfo("module.py", 30, "shared_func"), + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + ] + + for frames in pattern_frames: + collector.collect([frames]) + + collector.create_stats() + + # Check that both paths are recorded equally + func_a_key = ("module.py", 10, "func_a") + func_b_key = ("module.py", 20, "func_b") + shared_key = ("module.py", 30, "shared_func") + main_key = ("main.py", 5, "main") + + # func_a and func_b should each be directly executing twice + self.assertEqual(collector.stats[func_a_key][0], 2) # direct_calls + self.assertEqual(collector.stats[func_a_key][1], 2) # cumulative_calls + self.assertEqual(collector.stats[func_b_key][0], 2) # direct_calls + self.assertEqual(collector.stats[func_b_key][1], 2) # cumulative_calls + + # shared_func should appear in all samples (4 times) but never directly executing + self.assertEqual(collector.stats[shared_key][0], 0) # direct_calls + self.assertEqual(collector.stats[shared_key][1], 4) # cumulative_calls + + # main should appear in all samples but never directly executing + self.assertEqual(collector.stats[main_key][0], 0) # direct_calls + self.assertEqual(collector.stats[main_key][1], 4) # cumulative_calls + + def test_collapsed_stack_with_recursion(self): + """Test collapsed stack collector with recursive patterns.""" + collector = CollapsedStackCollector(1000) + + # Recursive call pattern + recursive_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("factorial.py", 10, "factorial"), + MockFrameInfo("factorial.py", 10, "factorial"), # recursive + MockFrameInfo("factorial.py", 10, "factorial"), # deeper + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + MockInterpreterInfo( + 0, + [ + MockThreadInfo( + 1, + [ + MockFrameInfo("factorial.py", 10, "factorial"), + MockFrameInfo("factorial.py", 10, "factorial"), # different depth + MockFrameInfo("main.py", 5, "main"), + ], + ) + ], + ), + ] + + for frames in recursive_frames: + collector.collect([frames]) + + # Should capture both call paths + self.assertEqual(len(collector.stack_counter), 2) + + # First path should be longer (deeper recursion) than the second + path_tuples = list(collector.stack_counter.keys()) + paths = [p[0] for p in path_tuples] # Extract just the call paths + lengths = [len(p) for p in paths] + self.assertNotEqual(lengths[0], lengths[1]) + + # Both should contain factorial calls + self.assertTrue( + any(any(f[2] == "factorial" for f in p) for p in paths) + ) + + # Verify total occurrences via aggregation + factorial_key = ("factorial.py", 10, "factorial") + main_key = ("main.py", 5, "main") + + def total_occurrences(func): + total = 0 + for (path, thread_id), count in collector.stack_counter.items(): + total += sum(1 for f in path if f == func) * count + return total + + self.assertEqual(total_occurrences(factorial_key), 5) + self.assertEqual(total_occurrences(main_key), 2) + + +# Shared workload functions for test scripts +_WORKLOAD_FUNCTIONS = ''' +def slow_fibonacci(n): + if n <= 1: + return n + return slow_fibonacci(n-1) + slow_fibonacci(n-2) + +def cpu_intensive_work(): + result = 0 + for i in range(10000): + result += i * i + if i % 100 == 0: + result = result % 1000000 + return result + +def do_work(): + iteration = 0 + while True: + if iteration % 2 == 0: + slow_fibonacci(15) + else: + cpu_intensive_work() + iteration += 1 +''' + + +@requires_remote_subprocess_debugging() +class TestSampleProfilerIntegration(unittest.TestCase): + @classmethod + def setUpClass(cls): + # Test script for use with test_subprocess() - signals when work starts + cls.test_script = _WORKLOAD_FUNCTIONS + ''' +_test_sock.sendall(b"working") +do_work() +''' + # CLI test script - runs for fixed duration (no socket sync) + cls.cli_test_script = ''' +import time +''' + _WORKLOAD_FUNCTIONS.replace( + 'while True:', 'end_time = time.time() + 30\n while time.time() < end_time:' +) + ''' +do_work() +''' + + def test_sampling_basic_functionality(self): + with ( + test_subprocess(self.test_script, wait_for_working=True) as subproc, + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=1000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=PROFILING_DURATION_SEC, + ) + collector.print_stats(show_summary=False) + + output = captured_output.getvalue() + + # Basic checks on output + self.assertIn("Captured", output) + self.assertIn("samples", output) + self.assertIn("Profile Stats", output) + + # Should see some of our test functions + self.assertIn("slow_fibonacci", output) + + def test_sampling_with_pstats_export(self): + pstats_out = tempfile.NamedTemporaryFile( + suffix=".pstats", delete=False + ) + self.addCleanup(close_and_unlink, pstats_out) + + with test_subprocess(self.test_script, wait_for_working=True) as subproc: + # Suppress profiler output when testing file export + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=10000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=PROFILING_DURATION_SEC, + ) + collector.export(pstats_out.name) + + # Verify file was created and contains valid data + self.assertTrue(os.path.exists(pstats_out.name)) + self.assertGreater(os.path.getsize(pstats_out.name), 0) + + # Try to load the stats file + with open(pstats_out.name, "rb") as f: + stats_data = marshal.load(f) + + # Should be a dictionary with the sampled marker + self.assertIsInstance(stats_data, dict) + self.assertIn(("__sampled__",), stats_data) + self.assertTrue(stats_data[("__sampled__",)]) + + # Should have some function data + function_entries = [ + k for k in stats_data.keys() if k != ("__sampled__",) + ] + self.assertGreater(len(function_entries), 0) + + def test_sampling_with_collapsed_export(self): + collapsed_file = tempfile.NamedTemporaryFile( + suffix=".txt", delete=False + ) + self.addCleanup(close_and_unlink, collapsed_file) + + with ( + test_subprocess(self.test_script, wait_for_working=True) as subproc, + ): + # Suppress profiler output when testing file export + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = CollapsedStackCollector(1000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=PROFILING_DURATION_SEC, + ) + collector.export(collapsed_file.name) + + # Verify file was created and contains valid data + self.assertTrue(os.path.exists(collapsed_file.name)) + self.assertGreater(os.path.getsize(collapsed_file.name), 0) + + # Check file format + with open(collapsed_file.name, "r") as f: + content = f.read() + + lines = content.strip().split("\n") + self.assertGreater(len(lines), 0) + + # Each line should have format: stack_trace count + for line in lines: + parts = line.rsplit(" ", 1) + self.assertEqual(len(parts), 2) + + stack_trace, count_str = parts + self.assertGreater(len(stack_trace), 0) + self.assertTrue(count_str.isdigit()) + self.assertGreater(int(count_str), 0) + + # Stack trace should contain semicolon-separated entries + if ";" in stack_trace: + stack_parts = stack_trace.split(";") + for part in stack_parts: + # Each part should be file:function:line + self.assertIn(":", part) + + def test_sampling_all_threads(self): + with ( + test_subprocess(self.test_script, wait_for_working=True) as subproc, + # Suppress profiler output + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=10000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=PROFILING_DURATION_SEC, + all_threads=True, + ) + collector.print_stats(show_summary=False) + + # Just verify that sampling completed without error + # We're not testing output format here + + def test_sample_target_script(self): + script_file = tempfile.NamedTemporaryFile(delete=False) + script_file.write(self.cli_test_script.encode("utf-8")) + script_file.flush() + self.addCleanup(close_and_unlink, script_file) + + # Sample for PROFILING_DURATION_SEC seconds + test_args = [ + "profiling.sampling.sample", "run", + "-d", str(PROFILING_DURATION_SEC), + script_file.name + ] + + with ( + mock.patch("sys.argv", test_args), + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + main() + + output = captured_output.getvalue() + + # Basic checks on output + self.assertIn("Captured", output) + self.assertIn("samples", output) + self.assertIn("Profile Stats", output) + + # Should see some of our test functions + self.assertIn("slow_fibonacci", output) + + def test_sample_target_module(self): + tempdir = tempfile.TemporaryDirectory(delete=False) + self.addCleanup(lambda x: shutil.rmtree(x), tempdir.name) + + module_path = os.path.join(tempdir.name, "test_module.py") + + with open(module_path, "w") as f: + f.write(self.cli_test_script) + + test_args = [ + "profiling.sampling.cli", + "run", + "-d", + str(PROFILING_DURATION_SEC), + "-m", + "test_module", + ] + + with ( + mock.patch("sys.argv", test_args), + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + # Change to temp directory so subprocess can find the module + contextlib.chdir(tempdir.name), + ): + main() + + output = captured_output.getvalue() + + # Basic checks on output + self.assertIn("Captured", output) + self.assertIn("samples", output) + self.assertIn("Profile Stats", output) + + # Should see some of our test functions + self.assertIn("slow_fibonacci", output) + + +@requires_remote_subprocess_debugging() +class TestSampleProfilerErrorHandling(unittest.TestCase): + def test_invalid_pid(self): + with self.assertRaises((SystemExit, PermissionError)): + collector = PstatsCollector(sample_interval_usec=100, skip_idle=False) + profiling.sampling.sample.sample(-1, collector, duration_sec=1) + + def test_process_dies_during_sampling(self): + # Use wait_for_working=False since this simple script doesn't send "working" + with test_subprocess( + "import time; time.sleep(0.5); exit()", + wait_for_working=False + ) as subproc: + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=50000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=2, # Longer than process lifetime + ) + + output = captured_output.getvalue() + + self.assertIn("Error rate", output) + + def test_is_process_running(self): + # Use wait_for_working=False since this simple script doesn't send "working" + with test_subprocess( + "import time; time.sleep(1000)", + wait_for_working=False + ) as subproc: + profiler = SampleProfiler( + pid=subproc.process.pid, + sample_interval_usec=1000, + all_threads=False, + ) + self.assertTrue(_is_process_running(profiler.pid)) + self.assertIsNotNone(profiler.unwinder.get_stack_trace()) + subproc.process.kill() + subproc.process.wait() + self.assertRaises( + ProcessLookupError, profiler.unwinder.get_stack_trace + ) + + # Exit the context manager to ensure the process is terminated + self.assertFalse(_is_process_running(profiler.pid)) + self.assertRaises( + ProcessLookupError, profiler.unwinder.get_stack_trace + ) + + @unittest.skipUnless(sys.platform == "linux", "Only valid on Linux") + def test_esrch_signal_handling(self): + # Use wait_for_working=False since this simple script doesn't send "working" + with test_subprocess( + "import time; time.sleep(1000)", + wait_for_working=False + ) as subproc: + unwinder = _remote_debugging.RemoteUnwinder( + subproc.process.pid + ) + initial_trace = unwinder.get_stack_trace() + self.assertIsNotNone(initial_trace) + + subproc.process.kill() + + # Wait for the process to die and try to get another trace + subproc.process.wait() + + with self.assertRaises(ProcessLookupError): + unwinder.get_stack_trace() + + def test_script_error_treatment(self): + script_file = tempfile.NamedTemporaryFile( + "w", delete=False, suffix=".py" + ) + script_file.write("open('nonexistent_file.txt')\n") + script_file.close() + self.addCleanup(os.unlink, script_file.name) + + result = subprocess.run( + [ + sys.executable, + "-m", + "profiling.sampling.cli", + "run", + script_file.name, + ], + capture_output=True, + text=True, + ) + output = result.stdout + result.stderr + + self.assertNotIn("Script file not found", output) + self.assertIn( + "No such file or directory: 'nonexistent_file.txt'", output + ) + + def test_live_incompatible_with_pstats_options(self): + """Test that --live is incompatible with individual pstats options.""" + test_cases = [ + (["--sort", "tottime"], "--sort"), + (["--limit", "30"], "--limit"), + (["--no-summary"], "--no-summary"), + ] + + for args, expected_flag in test_cases: + with self.subTest(args=args): + test_args = ["profiling.sampling.cli", "run", "--live"] + args + ["test.py"] + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as cm: + main() + self.assertNotEqual(cm.exception.code, 0) + + def test_live_incompatible_with_multiple_pstats_options(self): + """Test that --live is incompatible with multiple pstats options.""" + test_args = [ + "profiling.sampling.cli", "run", "--live", + "--sort", "cumtime", "--limit", "25", "--no-summary", "test.py" + ] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as cm: + main() + self.assertNotEqual(cm.exception.code, 0) + + def test_live_incompatible_with_pstats_default_values(self): + """Test that --live blocks pstats options even with default values.""" + # Test with --sort=nsamples (the default value) + test_args = ["profiling.sampling.cli", "run", "--live", "--sort=nsamples", "test.py"] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as cm: + main() + self.assertNotEqual(cm.exception.code, 0) + + # Test with --limit=15 (the default value) + test_args = ["profiling.sampling.cli", "run", "--live", "--limit=15", "test.py"] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as cm: + main() + self.assertNotEqual(cm.exception.code, 0) + + +@requires_remote_subprocess_debugging() +class TestAsyncAwareProfilingIntegration(unittest.TestCase): + """Integration tests for async-aware profiling mode.""" + + @classmethod + def setUpClass(cls): + # Async test script that runs indefinitely until killed. + # Sends "working" signal AFTER tasks are created and scheduled. + cls.async_script = ''' +import asyncio + +async def sleeping_leaf(): + while True: + await asyncio.sleep(0.02) + +async def cpu_leaf(): + total = 0 + while True: + for i in range(10000): + total += i * i + await asyncio.sleep(0) + +async def supervisor(): + tasks = [ + asyncio.create_task(sleeping_leaf(), name="Sleeper-0"), + asyncio.create_task(sleeping_leaf(), name="Sleeper-1"), + asyncio.create_task(sleeping_leaf(), name="Sleeper-2"), + asyncio.create_task(cpu_leaf(), name="Worker"), + ] + await asyncio.sleep(0) # Let tasks get scheduled + _test_sock.sendall(b"working") + await asyncio.gather(*tasks) + +asyncio.run(supervisor()) +''' + + def _collect_async_samples(self, async_aware_mode): + """Helper to collect samples and count function occurrences. + + Returns a dict mapping function names to their sample counts. + """ + with test_subprocess(self.async_script, wait_for_working=True) as subproc: + collector = CollapsedStackCollector(1000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=PROFILING_DURATION_SEC, + async_aware=async_aware_mode, + ) + + # Count samples per function from collapsed stacks + # stack_counter keys are (call_tree, thread_id) where call_tree + # is a tuple of (file, line, func) tuples + func_samples = {} + total = 0 + for (call_tree, _thread_id), count in collector.stack_counter.items(): + total += count + for _file, _line, func in call_tree: + func_samples[func] = func_samples.get(func, 0) + count + + func_samples["_total"] = total + return func_samples + + def test_async_aware_all_sees_sleeping_and_running_tasks(self): + """Test that async_aware='all' captures both sleeping and CPU-running tasks. + + Task tree structure: + main + └── supervisor + ├── Sleeper-0 (sleeping_leaf) + ├── Sleeper-1 (sleeping_leaf) + ├── Sleeper-2 (sleeping_leaf) + └── Worker (cpu_leaf) + + async_aware='all' should see ALL 4 leaf tasks in the output. + """ + samples = self._collect_async_samples("all") + + self.assertGreater(samples["_total"], 0, "Should have collected samples") + self.assertIn("sleeping_leaf", samples) + self.assertIn("cpu_leaf", samples) + self.assertIn("supervisor", samples) + + def test_async_aware_running_sees_only_cpu_task(self): + """Test that async_aware='running' only captures the actively running task. + + Task tree structure: + main + └── supervisor + ├── Sleeper-0 (sleeping_leaf) - NOT visible in 'running' + ├── Sleeper-1 (sleeping_leaf) - NOT visible in 'running' + ├── Sleeper-2 (sleeping_leaf) - NOT visible in 'running' + └── Worker (cpu_leaf) - VISIBLE in 'running' + + async_aware='running' should only see the Worker task doing CPU work. + """ + samples = self._collect_async_samples("running") + + total = samples["_total"] + cpu_leaf_samples = samples.get("cpu_leaf", 0) + + self.assertGreater(total, 0, "Should have collected some samples") + self.assertGreater(cpu_leaf_samples, 0, "cpu_leaf should appear in samples") + + # cpu_leaf should have at least 90% of samples (typically 99%+) + # sleeping_leaf may occasionally appear with very few samples (< 1%) + # when tasks briefly wake up to check sleep timers + cpu_percentage = (cpu_leaf_samples / total) * 100 + self.assertGreater(cpu_percentage, 90.0, + f"cpu_leaf should dominate samples in 'running' mode, " + f"got {cpu_percentage:.1f}% ({cpu_leaf_samples}/{total})") + + +def _generate_deep_generators_script(chain_depth=20, recurse_depth=150): + """Generate a script with deep nested generators for stress testing.""" + lines = [ + 'import sys', + 'sys.setrecursionlimit(5000)', + '', + ] + # Generate chain of yield-from functions + for i in range(chain_depth - 1): + lines.extend([ + f'def deep_yield_chain_{i}(n):', + f' yield ("L{i}", n)', + f' yield from deep_yield_chain_{i + 1}(n)', + '', + ]) + # Last chain function calls recursive_diver + lines.extend([ + f'def deep_yield_chain_{chain_depth - 1}(n):', + f' yield ("L{chain_depth - 1}", n)', + f' yield from recursive_diver(n, {chain_depth})', + '', + 'def recursive_diver(n, depth):', + ' yield (f"DIVE_{depth}", n)', + f' if depth < {recurse_depth}:', + ' yield from recursive_diver(n, depth + 1)', + ' else:', + ' for i in range(5):', + ' yield (f"BOTTOM_{depth}", i)', + '', + 'def oscillating_generator(iterations=1000):', + ' for i in range(iterations):', + ' yield ("OSCILLATE", i)', + ' yield from deep_yield_chain_0(i)', + '', + 'def run_forever():', + ' while True:', + ' for _ in oscillating_generator(10):', + ' pass', + '', + '_test_sock.sendall(b"working")', + 'run_forever()', + ]) + return '\n'.join(lines) + + +@requires_remote_subprocess_debugging() +class TestDeepGeneratorFrameCache(unittest.TestCase): + """Test frame cache consistency with deep oscillating generator stacks.""" + + def test_all_stacks_share_same_base_frame(self): + """Verify all sampled stacks reach the entry point function. + + When profiling deep generators that oscillate up and down the call + stack, every sample should include the entry point function + (run_forever) in its call chain. If the frame cache stores + incomplete stacks, some samples will be missing this base function, + causing broken flamegraphs. + """ + script = _generate_deep_generators_script() + with test_subprocess(script, wait_for_working=True) as subproc: + collector = CollapsedStackCollector(sample_interval_usec=1, skip_idle=False) + + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=2, + ) + + samples_with_entry_point = 0 + samples_without_entry_point = 0 + total_samples = 0 + + for (call_tree, _thread_id), count in collector.stack_counter.items(): + total_samples += count + if call_tree: + has_entry_point = call_tree and call_tree[0][2] == "" + if has_entry_point: + samples_with_entry_point += count + else: + samples_without_entry_point += count + + self.assertGreater(total_samples, 100, + f"Expected at least 100 samples, got {total_samples}") + + self.assertEqual(samples_without_entry_point, 0, + f"Found {samples_without_entry_point}/{total_samples} samples " + f"missing the entry point function 'run_forever'. This indicates " + f"incomplete stacks are being returned, likely due to frame cache " + f"storing partial stack traces.") diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_core.py b/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_core.py new file mode 100644 index 00000000000..f67a900822c --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_core.py @@ -0,0 +1,698 @@ +"""Core functionality tests for LiveStatsCollector. + +Tests for path simplification, frame processing, collect method, +statistics building, sorting, and formatting. +""" + +import os +import unittest +from test.support import requires +from test.support.import_helper import import_module + +# Only run these tests if curses is available +requires("curses") +curses = import_module("curses") + +from profiling.sampling.live_collector import LiveStatsCollector, MockDisplay +from profiling.sampling.constants import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, +) +from ._live_collector_helpers import ( + MockFrameInfo, + MockThreadInfo, + MockInterpreterInfo, +) + + +class TestLiveStatsCollectorPathSimplification(unittest.TestCase): + """Tests for path simplification functionality.""" + + def test_simplify_stdlib_path(self): + """Test simplification of standard library paths.""" + collector = LiveStatsCollector(1000) + # Get actual os module path + os_file = os.__file__ + if os_file: + stdlib_dir = os.path.dirname(os.path.abspath(os_file)) + test_path = os.path.join(stdlib_dir, "json", "decoder.py") + simplified = collector.simplify_path(test_path) + # Should remove the stdlib prefix + self.assertNotIn(stdlib_dir, simplified) + self.assertIn("json", simplified) + + def test_simplify_unknown_path(self): + """Test that unknown paths are returned unchanged.""" + collector = LiveStatsCollector(1000) + test_path = "/some/unknown/path/file.py" + simplified = collector.simplify_path(test_path) + self.assertEqual(simplified, test_path) + + +class TestLiveStatsCollectorFrameProcessing(unittest.TestCase): + """Tests for frame processing functionality.""" + + def test_process_single_frame(self): + """Test processing a single frame.""" + collector = LiveStatsCollector(1000) + frames = [MockFrameInfo("test.py", 10, "test_func")] + collector.process_frames(frames) + + location = ("test.py", 10, "test_func") + self.assertEqual(collector.result[location]["direct_calls"], 1) + self.assertEqual(collector.result[location]["cumulative_calls"], 1) + + def test_process_multiple_frames(self): + """Test processing a stack of multiple frames.""" + collector = LiveStatsCollector(1000) + frames = [ + MockFrameInfo("test.py", 10, "inner_func"), + MockFrameInfo("test.py", 20, "middle_func"), + MockFrameInfo("test.py", 30, "outer_func"), + ] + collector.process_frames(frames) + + # Top frame (inner_func) should have both direct and cumulative + inner_loc = ("test.py", 10, "inner_func") + self.assertEqual(collector.result[inner_loc]["direct_calls"], 1) + self.assertEqual(collector.result[inner_loc]["cumulative_calls"], 1) + + # Other frames should only have cumulative + middle_loc = ("test.py", 20, "middle_func") + self.assertEqual(collector.result[middle_loc]["direct_calls"], 0) + self.assertEqual(collector.result[middle_loc]["cumulative_calls"], 1) + + outer_loc = ("test.py", 30, "outer_func") + self.assertEqual(collector.result[outer_loc]["direct_calls"], 0) + self.assertEqual(collector.result[outer_loc]["cumulative_calls"], 1) + + def test_process_empty_frames(self): + """Test processing empty frames list.""" + collector = LiveStatsCollector(1000) + collector.process_frames([]) + # Should not raise an error and result should remain empty + self.assertEqual(len(collector.result), 0) + + def test_process_frames_accumulation(self): + """Test that multiple calls accumulate correctly.""" + collector = LiveStatsCollector(1000) + frames = [MockFrameInfo("test.py", 10, "test_func")] + + collector.process_frames(frames) + collector.process_frames(frames) + collector.process_frames(frames) + + location = ("test.py", 10, "test_func") + self.assertEqual(collector.result[location]["direct_calls"], 3) + self.assertEqual(collector.result[location]["cumulative_calls"], 3) + + def test_process_frames_with_thread_id(self): + """Test processing frames with per-thread tracking.""" + collector = LiveStatsCollector(1000) + frames = [MockFrameInfo("test.py", 10, "test_func")] + + # Process frames with thread_id + collector.process_frames(frames, thread_id=123) + + # Check aggregated result + location = ("test.py", 10, "test_func") + self.assertEqual(collector.result[location]["direct_calls"], 1) + self.assertEqual(collector.result[location]["cumulative_calls"], 1) + + # Check per-thread result + self.assertIn(123, collector.per_thread_data) + self.assertEqual( + collector.per_thread_data[123].result[location]["direct_calls"], 1 + ) + self.assertEqual( + collector.per_thread_data[123].result[location]["cumulative_calls"], 1 + ) + + def test_process_frames_multiple_threads(self): + """Test processing frames from multiple threads.""" + collector = LiveStatsCollector(1000) + frames1 = [MockFrameInfo("test.py", 10, "test_func")] + frames2 = [MockFrameInfo("test.py", 20, "other_func")] + + # Process frames from different threads + collector.process_frames(frames1, thread_id=123) + collector.process_frames(frames2, thread_id=456) + + # Check that both threads have their own data + self.assertIn(123, collector.per_thread_data) + self.assertIn(456, collector.per_thread_data) + + loc1 = ("test.py", 10, "test_func") + loc2 = ("test.py", 20, "other_func") + + # Thread 123 should only have func1 + self.assertEqual( + collector.per_thread_data[123].result[loc1]["direct_calls"], 1 + ) + self.assertNotIn(loc2, collector.per_thread_data[123].result) + + # Thread 456 should only have func2 + self.assertEqual( + collector.per_thread_data[456].result[loc2]["direct_calls"], 1 + ) + self.assertNotIn(loc1, collector.per_thread_data[456].result) + + def test_process_recursive_frames_counted_once(self): + """Test that recursive functions are counted once per sample.""" + collector = LiveStatsCollector(1000) + # Simulate recursive function appearing 5 times in stack + frames = [ + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + ] + collector.process_frames(frames) + + location = ("test.py", 10, "recursive_func") + # Should count as 1 cumulative (present in 1 sample), not 5 + self.assertEqual(collector.result[location]["cumulative_calls"], 1) + self.assertEqual(collector.result[location]["direct_calls"], 1) + + def test_process_recursive_frames_multiple_samples(self): + """Test cumulative counting across multiple samples with recursion.""" + collector = LiveStatsCollector(1000) + + # Sample 1: depth 3 + frames1 = [ + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + ] + # Sample 2: depth 2 + frames2 = [ + MockFrameInfo("test.py", 10, "recursive_func"), + MockFrameInfo("test.py", 10, "recursive_func"), + ] + + collector.process_frames(frames1) + collector.process_frames(frames2) + + location = ("test.py", 10, "recursive_func") + # Should count as 2 (present in 2 samples), not 5 + self.assertEqual(collector.result[location]["cumulative_calls"], 2) + self.assertEqual(collector.result[location]["direct_calls"], 2) + + def test_process_mixed_recursive_nonrecursive(self): + """Test stack with both recursive and non-recursive functions.""" + collector = LiveStatsCollector(1000) + + # Stack: main -> foo (recursive x3) -> bar + frames = [ + MockFrameInfo("test.py", 50, "bar"), + MockFrameInfo("test.py", 20, "foo"), + MockFrameInfo("test.py", 20, "foo"), + MockFrameInfo("test.py", 20, "foo"), + MockFrameInfo("test.py", 10, "main"), + ] + collector.process_frames(frames) + + # foo: 1 cumulative despite 3 occurrences + self.assertEqual(collector.result[("test.py", 20, "foo")]["cumulative_calls"], 1) + self.assertEqual(collector.result[("test.py", 20, "foo")]["direct_calls"], 0) + + # bar and main: 1 cumulative each + self.assertEqual(collector.result[("test.py", 50, "bar")]["cumulative_calls"], 1) + self.assertEqual(collector.result[("test.py", 10, "main")]["cumulative_calls"], 1) + + +class TestLiveStatsCollectorCollect(unittest.TestCase): + """Tests for the collect method.""" + + def test_collect_initializes_start_time(self): + """Test that collect initializes start_time on first call.""" + collector = LiveStatsCollector(1000) + self.assertIsNone(collector.start_time) + + # Create mock stack frames + thread_info = MockThreadInfo(123, []) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + + collector.collect(stack_frames) + self.assertIsNotNone(collector.start_time) + + def test_collect_increments_sample_count(self): + """Test that collect increments total_samples.""" + collector = LiveStatsCollector(1000) + thread_info = MockThreadInfo(123, []) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + + self.assertEqual(collector.total_samples, 0) + collector.collect(stack_frames) + self.assertEqual(collector.total_samples, 1) + collector.collect(stack_frames) + self.assertEqual(collector.total_samples, 2) + + def test_collect_with_frames(self): + """Test collect with actual frame data.""" + collector = LiveStatsCollector(1000) + frames = [MockFrameInfo("test.py", 10, "test_func")] + thread_info = MockThreadInfo(123, frames) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + + collector.collect(stack_frames) + + location = ("test.py", 10, "test_func") + self.assertEqual(collector.result[location]["direct_calls"], 1) + self.assertEqual(collector.successful_samples, 1) + self.assertEqual(collector.failed_samples, 0) + + def test_collect_with_empty_frames(self): + """Test collect with empty frames counts as successful. + + A sample is considered successful if the profiler could read from the + target process, even if no frames matched the current filter (e.g., + --mode exception when no thread has an active exception). The sample + itself worked; it just didn't produce frame data. + """ + collector = LiveStatsCollector(1000) + thread_info = MockThreadInfo(123, []) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + + collector.collect(stack_frames) + + # Empty frames still count as successful - the sample worked even + # though no frames matched the filter + self.assertEqual(collector.successful_samples, 1) + self.assertEqual(collector.total_samples, 1) + self.assertEqual(collector.failed_samples, 0) + + def test_sample_counts_invariant(self): + """Test that total_samples == successful_samples + failed_samples. + + Empty frame data (e.g., from --mode exception with no active exception) + still counts as successful since the profiler could read process state. + """ + collector = LiveStatsCollector(1000) + + # Mix of samples with and without frame data + frames = [MockFrameInfo("test.py", 10, "func")] + thread_with_frames = MockThreadInfo(123, frames) + thread_empty = MockThreadInfo(456, []) + interp_with_frames = MockInterpreterInfo(0, [thread_with_frames]) + interp_empty = MockInterpreterInfo(0, [thread_empty]) + + # Collect various samples + collector.collect([interp_with_frames]) # Has frames + collector.collect([interp_empty]) # No frames (filtered) + collector.collect([interp_with_frames]) # Has frames + collector.collect([interp_empty]) # No frames (filtered) + collector.collect([interp_empty]) # No frames (filtered) + + # All 5 samples are successful (profiler could read process state) + self.assertEqual(collector.total_samples, 5) + self.assertEqual(collector.successful_samples, 5) + self.assertEqual(collector.failed_samples, 0) + + # Invariant must hold + self.assertEqual( + collector.total_samples, + collector.successful_samples + collector.failed_samples + ) + + def test_collect_skip_idle_threads(self): + """Test that idle threads are skipped when skip_idle=True.""" + collector = LiveStatsCollector(1000, skip_idle=True) + + frames = [MockFrameInfo("test.py", 10, "test_func")] + running_thread = MockThreadInfo( + 123, frames, status=THREAD_STATUS_HAS_GIL | THREAD_STATUS_ON_CPU + ) + idle_thread = MockThreadInfo(124, frames, status=0) # No flags = idle + interpreter_info = MockInterpreterInfo( + 0, [running_thread, idle_thread] + ) + stack_frames = [interpreter_info] + + collector.collect(stack_frames) + + # Only one thread should be processed + location = ("test.py", 10, "test_func") + self.assertEqual(collector.result[location]["direct_calls"], 1) + + def test_collect_multiple_threads(self): + """Test collect with multiple threads.""" + collector = LiveStatsCollector(1000) + + frames1 = [MockFrameInfo("test1.py", 10, "func1")] + frames2 = [MockFrameInfo("test2.py", 20, "func2")] + thread1 = MockThreadInfo(123, frames1) + thread2 = MockThreadInfo(124, frames2) + interpreter_info = MockInterpreterInfo(0, [thread1, thread2]) + stack_frames = [interpreter_info] + + collector.collect(stack_frames) + + loc1 = ("test1.py", 10, "func1") + loc2 = ("test2.py", 20, "func2") + self.assertEqual(collector.result[loc1]["direct_calls"], 1) + self.assertEqual(collector.result[loc2]["direct_calls"], 1) + + # Check thread IDs are tracked + self.assertIn(123, collector.thread_ids) + self.assertIn(124, collector.thread_ids) + + def test_collect_filtered_mode_percentage_calculation(self): + """Test that percentages use successful_samples, not total_samples. + + With the current behavior, all samples are considered successful + (the profiler could read from the process), even when filters result + in no frame data. This means percentages are relative to all sampling + attempts that succeeded in reading process state. + """ + collector = LiveStatsCollector(1000) + + # Simulate 10 samples where only 2 had matching data (e.g., exception mode) + frames_with_data = [MockFrameInfo("test.py", 10, "exception_handler")] + thread_with_data = MockThreadInfo(123, frames_with_data) + interpreter_with_data = MockInterpreterInfo(0, [thread_with_data]) + + # Empty thread simulates filtered-out data at C level + thread_empty = MockThreadInfo(456, []) + interpreter_empty = MockInterpreterInfo(0, [thread_empty]) + + # 2 samples with data + collector.collect([interpreter_with_data]) + collector.collect([interpreter_with_data]) + + # 8 samples without data (filtered out at C level, but sample still succeeded) + for _ in range(8): + collector.collect([interpreter_empty]) + + # All 10 samples are successful - the profiler could read from the process + self.assertEqual(collector.total_samples, 10) + self.assertEqual(collector.successful_samples, 10) + + # Build stats and check percentage + stats_list = collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + + # The function appeared in 2 out of 10 successful samples = 20% + location = ("test.py", 10, "exception_handler") + self.assertEqual(collector.result[location]["direct_calls"], 2) + + def test_percentage_values_use_successful_samples(self): + """Test that percentages are calculated from successful_samples. + + This verifies the fix where percentages use successful_samples (samples with + frame data) instead of total_samples (all sampling attempts). Critical for + filtered modes like --mode exception. + """ + collector = LiveStatsCollector(1000) + + # Simulate scenario: 100 total samples, only 20 had frame data + collector.total_samples = 100 + collector.successful_samples = 20 + + # Function appeared in 10 out of 20 successful samples + collector.result[("test.py", 10, "handler")] = { + "direct_calls": 10, + "cumulative_calls": 15, + "total_rec_calls": 0, + } + + stats_list = collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + + stat = stats_list[0] + # Calculate expected percentages using successful_samples + expected_sample_pct = stat["direct_calls"] / collector.successful_samples * 100 + expected_cumul_pct = stat["cumulative_calls"] / collector.successful_samples * 100 + + # Percentage should be 10/20 * 100 = 50%, NOT 10/100 * 100 = 10% + self.assertAlmostEqual(expected_sample_pct, 50.0) + # Cumulative percentage should be 15/20 * 100 = 75%, NOT 15/100 * 100 = 15% + self.assertAlmostEqual(expected_cumul_pct, 75.0) + + # Verify sorting by percentage works correctly + collector.result[("test.py", 20, "other")] = { + "direct_calls": 5, # 25% of successful samples + "cumulative_calls": 8, + "total_rec_calls": 0, + } + collector.sort_by = "sample_pct" + stats_list = collector.build_stats_list() + # handler (50%) should come before other (25%) + self.assertEqual(stats_list[0]["func"][2], "handler") + self.assertEqual(stats_list[1]["func"][2], "other") + + def test_build_stats_list_zero_successful_samples(self): + """Test build_stats_list handles zero successful_samples without division by zero. + + When all samples are filtered out (e.g., exception mode with no exceptions), + percentage calculations should return 0 without raising ZeroDivisionError. + """ + collector = LiveStatsCollector(1000) + + # Edge case: data exists but no successful samples + collector.result[("test.py", 10, "func")] = { + "direct_calls": 10, + "cumulative_calls": 10, + "total_rec_calls": 0, + } + collector.total_samples = 100 + collector.successful_samples = 0 # All samples filtered out + + # Should not raise ZeroDivisionError + stats_list = collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + + # Verify percentage-based sorting also works with zero successful_samples + collector.sort_by = "sample_pct" + stats_list = collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + + collector.sort_by = "cumul_pct" + stats_list = collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + + +class TestLiveStatsCollectorStatisticsBuilding(unittest.TestCase): + """Tests for statistics building and sorting.""" + + def setUp(self): + """Set up test fixtures.""" + self.collector = LiveStatsCollector(1000) + # Add some test data + self.collector.result[("file1.py", 10, "func1")] = { + "direct_calls": 100, + "cumulative_calls": 150, + "total_rec_calls": 0, + } + self.collector.result[("file2.py", 20, "func2")] = { + "direct_calls": 50, + "cumulative_calls": 200, + "total_rec_calls": 0, + } + self.collector.result[("file3.py", 30, "func3")] = { + "direct_calls": 75, + "cumulative_calls": 75, + "total_rec_calls": 0, + } + self.collector.total_samples = 300 + # successful_samples is used for percentage calculations + self.collector.successful_samples = 300 + + def test_build_stats_list(self): + """Test that stats list is built correctly.""" + stats_list = self.collector.build_stats_list() + self.assertEqual(len(stats_list), 3) + + # Check that all expected keys are present + for stat in stats_list: + self.assertIn("func", stat) + self.assertIn("direct_calls", stat) + self.assertIn("cumulative_calls", stat) + self.assertIn("total_time", stat) + self.assertIn("cumulative_time", stat) + + def test_sort_by_nsamples(self): + """Test sorting by number of samples.""" + self.collector.sort_by = "nsamples" + stats_list = self.collector.build_stats_list() + + # Should be sorted by direct_calls descending + self.assertEqual(stats_list[0]["func"][2], "func1") # 100 samples + self.assertEqual(stats_list[1]["func"][2], "func3") # 75 samples + self.assertEqual(stats_list[2]["func"][2], "func2") # 50 samples + + def test_sort_by_tottime(self): + """Test sorting by total time.""" + self.collector.sort_by = "tottime" + stats_list = self.collector.build_stats_list() + + # Should be sorted by total_time descending + # total_time = direct_calls * sample_interval_sec + self.assertEqual(stats_list[0]["func"][2], "func1") + self.assertEqual(stats_list[1]["func"][2], "func3") + self.assertEqual(stats_list[2]["func"][2], "func2") + + def test_sort_by_cumtime(self): + """Test sorting by cumulative time.""" + self.collector.sort_by = "cumtime" + stats_list = self.collector.build_stats_list() + + # Should be sorted by cumulative_time descending + self.assertEqual(stats_list[0]["func"][2], "func2") # 200 cumulative + self.assertEqual(stats_list[1]["func"][2], "func1") # 150 cumulative + self.assertEqual(stats_list[2]["func"][2], "func3") # 75 cumulative + + def test_sort_by_sample_pct(self): + """Test sorting by sample percentage.""" + self.collector.sort_by = "sample_pct" + stats_list = self.collector.build_stats_list() + + # Should be sorted by percentage of direct_calls + self.assertEqual(stats_list[0]["func"][2], "func1") # 33.3% + self.assertEqual(stats_list[1]["func"][2], "func3") # 25% + self.assertEqual(stats_list[2]["func"][2], "func2") # 16.7% + + def test_sort_by_cumul_pct(self): + """Test sorting by cumulative percentage.""" + self.collector.sort_by = "cumul_pct" + stats_list = self.collector.build_stats_list() + + # Should be sorted by percentage of cumulative_calls + self.assertEqual(stats_list[0]["func"][2], "func2") # 66.7% + self.assertEqual(stats_list[1]["func"][2], "func1") # 50% + self.assertEqual(stats_list[2]["func"][2], "func3") # 25% + + +class TestLiveStatsCollectorSortCycle(unittest.TestCase): + """Tests for sort mode cycling.""" + + def test_cycle_sort_from_nsamples(self): + """Test cycling from nsamples.""" + collector = LiveStatsCollector(1000, sort_by="nsamples") + collector._cycle_sort() + self.assertEqual(collector.sort_by, "sample_pct") + + def test_cycle_sort_from_sample_pct(self): + """Test cycling from sample_pct.""" + collector = LiveStatsCollector(1000, sort_by="sample_pct") + collector._cycle_sort() + self.assertEqual(collector.sort_by, "tottime") + + def test_cycle_sort_from_tottime(self): + """Test cycling from tottime.""" + collector = LiveStatsCollector(1000, sort_by="tottime") + collector._cycle_sort() + self.assertEqual(collector.sort_by, "cumul_pct") + + def test_cycle_sort_from_cumul_pct(self): + """Test cycling from cumul_pct.""" + collector = LiveStatsCollector(1000, sort_by="cumul_pct") + collector._cycle_sort() + self.assertEqual(collector.sort_by, "cumtime") + + def test_cycle_sort_from_cumtime(self): + """Test cycling from cumtime back to nsamples.""" + collector = LiveStatsCollector(1000, sort_by="cumtime") + collector._cycle_sort() + self.assertEqual(collector.sort_by, "nsamples") + + def test_cycle_sort_invalid_mode(self): + """Test cycling from invalid mode resets to nsamples.""" + collector = LiveStatsCollector(1000) + collector.sort_by = "invalid_mode" + collector._cycle_sort() + self.assertEqual(collector.sort_by, "nsamples") + + def test_cycle_sort_backward_from_nsamples(self): + """Test cycling backward from nsamples goes to cumtime.""" + collector = LiveStatsCollector(1000, sort_by="nsamples") + collector._cycle_sort(reverse=True) + self.assertEqual(collector.sort_by, "cumtime") + + def test_cycle_sort_backward_from_cumtime(self): + """Test cycling backward from cumtime goes to cumul_pct.""" + collector = LiveStatsCollector(1000, sort_by="cumtime") + collector._cycle_sort(reverse=True) + self.assertEqual(collector.sort_by, "cumul_pct") + + def test_cycle_sort_backward_from_sample_pct(self): + """Test cycling backward from sample_pct goes to nsamples.""" + collector = LiveStatsCollector(1000, sort_by="sample_pct") + collector._cycle_sort(reverse=True) + self.assertEqual(collector.sort_by, "nsamples") + + def test_input_lowercase_s_cycles_forward(self): + """Test that lowercase 's' cycles forward.""" + display = MockDisplay() + collector = LiveStatsCollector( + 1000, sort_by="nsamples", display=display + ) + + display.simulate_input(ord("s")) + collector._handle_input() + + self.assertEqual(collector.sort_by, "sample_pct") + + def test_input_uppercase_s_cycles_backward(self): + """Test that uppercase 'S' cycles backward.""" + display = MockDisplay() + collector = LiveStatsCollector( + 1000, sort_by="nsamples", display=display + ) + + display.simulate_input(ord("S")) + collector._handle_input() + + self.assertEqual(collector.sort_by, "cumtime") + + +class TestLiveStatsCollectorFormatting(unittest.TestCase): + """Tests for formatting methods.""" + + def test_format_uptime_seconds(self): + """Test uptime formatting for seconds only.""" + collector = LiveStatsCollector(1000, display=MockDisplay()) + colors = collector._setup_colors() + collector._initialize_widgets(colors) + self.assertEqual(collector.header_widget.format_uptime(45), "0m45s") + + def test_format_uptime_minutes(self): + """Test uptime formatting for minutes.""" + collector = LiveStatsCollector(1000, display=MockDisplay()) + colors = collector._setup_colors() + collector._initialize_widgets(colors) + self.assertEqual(collector.header_widget.format_uptime(125), "2m05s") + + def test_format_uptime_hours(self): + """Test uptime formatting for hours.""" + collector = LiveStatsCollector(1000, display=MockDisplay()) + colors = collector._setup_colors() + collector._initialize_widgets(colors) + self.assertEqual( + collector.header_widget.format_uptime(3661), "1h01m01s" + ) + + def test_format_uptime_large_values(self): + """Test uptime formatting for large time values.""" + collector = LiveStatsCollector(1000, display=MockDisplay()) + colors = collector._setup_colors() + collector._initialize_widgets(colors) + self.assertEqual( + collector.header_widget.format_uptime(86400), "24h00m00s" + ) + + def test_format_uptime_zero(self): + """Test uptime formatting for zero.""" + collector = LiveStatsCollector(1000, display=MockDisplay()) + colors = collector._setup_colors() + collector._initialize_widgets(colors) + self.assertEqual(collector.header_widget.format_uptime(0), "0m00s") + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_interaction.py b/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_interaction.py new file mode 100644 index 00000000000..6dfdb9a192e --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_interaction.py @@ -0,0 +1,1234 @@ +"""Interactive controls tests for LiveStatsCollector. + +Tests for interactive controls, filtering, filter input, and thread navigation. +""" + +import time +import unittest +from test.support import requires +from test.support.import_helper import import_module + +# Only run these tests if curses is available +requires("curses") +curses = import_module("curses") + +from profiling.sampling.live_collector import LiveStatsCollector, MockDisplay +from profiling.sampling.constants import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, +) +from ._live_collector_helpers import ( + MockFrameInfo, + MockThreadInfo, + MockInterpreterInfo, +) + + +class TestLiveCollectorInteractiveControls(unittest.TestCase): + """Tests for interactive control features.""" + + def setUp(self): + """Set up collector with mock display.""" + self.display = MockDisplay(height=40, width=160) + self.collector = LiveStatsCollector( + 1000, pid=12345, display=self.display + ) + self.collector.start_time = time.perf_counter() + # Set a consistent display update interval for tests + self.collector.display_update_interval_sec = 0.1 + + def tearDown(self): + """Clean up after test.""" + pass + + def test_pause_functionality(self): + """Test pause/resume functionality.""" + self.assertFalse(self.collector.paused) + + # Simulate 'p' key press + self.display.simulate_input(ord("p")) + self.collector._handle_input() + + self.assertTrue(self.collector.paused) + + # Press 'p' again to resume + self.display.simulate_input(ord("p")) + self.collector._handle_input() + + self.assertFalse(self.collector.paused) + + def test_pause_stops_ui_updates(self): + """Test that pausing stops UI updates but profiling continues.""" + # Add some data + self.collector.total_samples = 10 + self.collector.result[("test.py", 1, "func")] = { + "direct_calls": 5, + "cumulative_calls": 10, + "total_rec_calls": 0, + } + + # Pause + self.collector.paused = True + + # Simulate a collect call (profiling continues) + thread_info = MockThreadInfo(123, []) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + + initial_samples = self.collector.total_samples + self.collector.collect(stack_frames) + + # Samples should still increment + self.assertEqual(self.collector.total_samples, initial_samples + 1) + + # But display should not have been updated (buffer stays clear) + self.display.cleared = False + self.collector.collect(stack_frames) + self.assertFalse( + self.display.cleared, "Display should not update when paused" + ) + + def test_reset_stats(self): + """Test reset statistics functionality.""" + # Add some stats + self.collector.total_samples = 100 + self.collector.successful_samples = 90 + self.collector.failed_samples = 10 + self.collector.result[("test.py", 1, "func")] = { + "direct_calls": 50, + "cumulative_calls": 75, + "total_rec_calls": 0, + } + self.collector.opcode_stats[("test.py", 1, "func")][100] = 5 + + # Reset + self.collector.reset_stats() + + self.assertEqual(self.collector.total_samples, 0) + self.assertEqual(self.collector.successful_samples, 0) + self.assertEqual(self.collector.failed_samples, 0) + self.assertEqual(len(self.collector.result), 0) + self.assertEqual(len(self.collector.opcode_stats), 0) + + def test_increase_refresh_rate(self): + """Test increasing refresh rate (faster updates).""" + initial_interval = self.collector.display_update_interval_sec + + # Simulate '+' key press (faster = smaller interval) + self.display.simulate_input(ord("+")) + self.collector._handle_input() + + self.assertLess(self.collector.display_update_interval_sec, initial_interval) + + def test_decrease_refresh_rate(self): + """Test decreasing refresh rate (slower updates).""" + initial_interval = self.collector.display_update_interval_sec + + # Simulate '-' key press (slower = larger interval) + self.display.simulate_input(ord("-")) + self.collector._handle_input() + + self.assertGreater(self.collector.display_update_interval_sec, initial_interval) + + def test_refresh_rate_minimum(self): + """Test that refresh rate has a minimum (max speed).""" + self.collector.display_update_interval_sec = 0.05 # Set to minimum + + # Try to go faster + self.display.simulate_input(ord("+")) + self.collector._handle_input() + + # Should stay at minimum + self.assertEqual(self.collector.display_update_interval_sec, 0.05) + + def test_refresh_rate_maximum(self): + """Test that refresh rate has a maximum (min speed).""" + self.collector.display_update_interval_sec = 1.0 # Set to maximum + + # Try to go slower + self.display.simulate_input(ord("-")) + self.collector._handle_input() + + # Should stay at maximum + self.assertEqual(self.collector.display_update_interval_sec, 1.0) + + def test_help_toggle(self): + """Test help screen toggle.""" + self.assertFalse(self.collector.show_help) + + # Show help + self.display.simulate_input(ord("h")) + self.collector._handle_input() + + self.assertTrue(self.collector.show_help) + + # Pressing any key closes help + self.display.simulate_input(ord("x")) + self.collector._handle_input() + + self.assertFalse(self.collector.show_help) + + def test_help_with_question_mark(self): + """Test help screen with '?' key.""" + self.display.simulate_input(ord("?")) + self.collector._handle_input() + + self.assertTrue(self.collector.show_help) + + def test_help_dismiss_with_q_does_not_quit(self): + """Test that pressing 'q' while help is shown only closes help, not quit""" + self.assertFalse(self.collector.show_help) + self.display.simulate_input(ord("h")) + self.collector._handle_input() + self.assertTrue(self.collector.show_help) + + self.display.simulate_input(ord("q")) + self.collector._handle_input() + + self.assertFalse(self.collector.show_help) + self.assertTrue(self.collector.running) + + def test_filter_clear(self): + """Test clearing filter.""" + self.collector.filter_pattern = "test" + + # Clear filter + self.display.simulate_input(ord("c")) + self.collector._handle_input() + + self.assertIsNone(self.collector.filter_pattern) + + def test_filter_clear_when_none(self): + """Test clearing filter when no filter is set.""" + self.assertIsNone(self.collector.filter_pattern) + + # Should not crash + self.display.simulate_input(ord("c")) + self.collector._handle_input() + + self.assertIsNone(self.collector.filter_pattern) + + def test_paused_status_in_footer(self): + """Test that paused status appears in footer.""" + self.collector.total_samples = 10 + self.collector.paused = True + + self.collector._update_display() + + # Check that PAUSED appears in display + self.assertTrue(self.display.contains_text("PAUSED")) + + def test_filter_status_in_footer(self): + """Test that filter status appears in footer.""" + self.collector.total_samples = 10 + self.collector.filter_pattern = "mytest" + + self.collector._update_display() + + # Check that filter info appears + self.assertTrue(self.display.contains_text("Filter")) + + def test_help_screen_display(self): + """Test that help screen is displayed.""" + self.collector.show_help = True + + self.collector._update_display() + + # Check for help content + self.assertTrue(self.display.contains_text("Interactive Commands")) + + def test_pause_uppercase(self): + """Test pause with uppercase 'P' key.""" + self.assertFalse(self.collector.paused) + + self.display.simulate_input(ord("P")) + self.collector._handle_input() + + self.assertTrue(self.collector.paused) + + def test_help_uppercase(self): + """Test help with uppercase 'H' key.""" + self.assertFalse(self.collector.show_help) + + self.display.simulate_input(ord("H")) + self.collector._handle_input() + + self.assertTrue(self.collector.show_help) + + def test_reset_lowercase(self): + """Test reset with lowercase 'r' key.""" + # Add some stats + self.collector.total_samples = 100 + self.collector.result[("test.py", 1, "func")] = { + "direct_calls": 50, + "cumulative_calls": 75, + "total_rec_calls": 0, + } + + self.display.simulate_input(ord("r")) + self.collector._handle_input() + + self.assertEqual(self.collector.total_samples, 0) + self.assertEqual(len(self.collector.result), 0) + + def test_reset_uppercase(self): + """Test reset with uppercase 'R' key.""" + self.collector.total_samples = 100 + + self.display.simulate_input(ord("R")) + self.collector._handle_input() + + self.assertEqual(self.collector.total_samples, 0) + + def test_filter_clear_uppercase(self): + """Test clearing filter with uppercase 'C' key.""" + self.collector.filter_pattern = "test" + + self.display.simulate_input(ord("C")) + self.collector._handle_input() + + self.assertIsNone(self.collector.filter_pattern) + + def test_increase_refresh_rate_with_equals(self): + """Test increasing refresh rate with '=' key.""" + initial_interval = self.collector.display_update_interval_sec + + # Simulate '=' key press (alternative to '+') + self.display.simulate_input(ord("=")) + self.collector._handle_input() + + self.assertLess(self.collector.display_update_interval_sec, initial_interval) + + def test_decrease_refresh_rate_with_underscore(self): + """Test decreasing refresh rate with '_' key.""" + initial_interval = self.collector.display_update_interval_sec + + # Simulate '_' key press (alternative to '-') + self.display.simulate_input(ord("_")) + self.collector._handle_input() + + self.assertGreater(self.collector.display_update_interval_sec, initial_interval) + + def test_finished_state_displays_banner(self): + """Test that finished state shows prominent banner.""" + # Add some sample data + thread_info = MockThreadInfo( + 123, + [ + MockFrameInfo("test.py", 10, "work"), + MockFrameInfo("test.py", 20, "main"), + ], + ) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + self.collector.collect(stack_frames) + + # Mark as finished + self.collector.mark_finished() + + # Check that finished flag is set + self.assertTrue(self.collector.finished) + + # Check that the banner message is displayed + self.assertTrue(self.display.contains_text("PROFILING COMPLETE")) + self.assertTrue(self.display.contains_text("Press 'q' to Quit")) + + def test_finished_state_allows_ui_controls(self): + """Test that finished state allows UI controls but prioritizes quit.""" + self.collector.finished = True + self.collector.running = True + + # Try pressing 's' (sort) - should work and trigger display update + original_sort = self.collector.sort_by + self.display.simulate_input(ord("s")) + self.collector._handle_input() + self.assertTrue(self.collector.running) # Still running + self.assertNotEqual(self.collector.sort_by, original_sort) # Sort changed + + # Try pressing 'p' (pause) - should work + self.display.simulate_input(ord("p")) + self.collector._handle_input() + self.assertTrue(self.collector.running) # Still running + self.assertTrue(self.collector.paused) # Now paused + + # Try pressing 'r' (reset) - should be ignored when finished + self.collector.total_samples = 100 + self.display.simulate_input(ord("r")) + self.collector._handle_input() + self.assertTrue(self.collector.running) # Still running + self.assertEqual(self.collector.total_samples, 100) # NOT reset when finished + + # Press 'q' - should stop + self.display.simulate_input(ord("q")) + self.collector._handle_input() + self.assertFalse(self.collector.running) # Stopped + + def test_finished_state_footer_message(self): + """Test that footer shows appropriate message when finished.""" + # Add some sample data + thread_info = MockThreadInfo( + 123, + [ + MockFrameInfo("test.py", 10, "work"), + MockFrameInfo("test.py", 20, "main"), + ], + ) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + self.collector.collect(stack_frames) + + # Mark as finished + self.collector.mark_finished() + + # Check that footer contains finished message + self.assertTrue(self.display.contains_text("PROFILING FINISHED")) + + def test_finished_state_freezes_time(self): + """Test that time displays are frozen when finished.""" + + # Set up collector with known start time + self.collector.start_time = time.perf_counter() - 10.0 # 10 seconds ago + + # Mark as finished - this should freeze the time + self.collector.mark_finished() + + # Get the frozen elapsed time + frozen_elapsed = self.collector.elapsed_time + frozen_time_display = self.collector.current_time_display + + # Wait a bit to ensure time would advance + time.sleep(0.1) + + # Time should remain frozen + self.assertEqual(self.collector.elapsed_time, frozen_elapsed) + self.assertEqual(self.collector.current_time_display, frozen_time_display) + + # Verify finish timestamp was set + self.assertIsNotNone(self.collector.finish_timestamp) + + # Reset should clear the frozen state + self.collector.reset_stats() + self.assertFalse(self.collector.finished) + self.assertIsNone(self.collector.finish_timestamp) + + +class TestLiveCollectorFiltering(unittest.TestCase): + """Tests for filtering functionality.""" + + def setUp(self): + """Set up collector with test data.""" + self.display = MockDisplay(height=40, width=160) + self.collector = LiveStatsCollector( + 1000, pid=12345, display=self.display + ) + self.collector.start_time = time.perf_counter() + self.collector.total_samples = 100 + + # Add test data + self.collector.result[("app/models.py", 10, "save")] = { + "direct_calls": 50, + "cumulative_calls": 75, + "total_rec_calls": 0, + } + self.collector.result[("app/views.py", 20, "render")] = { + "direct_calls": 30, + "cumulative_calls": 40, + "total_rec_calls": 0, + } + self.collector.result[("lib/utils.py", 30, "helper")] = { + "direct_calls": 20, + "cumulative_calls": 25, + "total_rec_calls": 0, + } + + def test_filter_by_filename(self): + """Test filtering by filename pattern.""" + self.collector.filter_pattern = "models" + + stats_list = self.collector.build_stats_list() + + # Only models.py should be included + self.assertEqual(len(stats_list), 1) + self.assertIn("models.py", stats_list[0]["func"][0]) + + def test_filter_by_function_name(self): + """Test filtering by function name.""" + self.collector.filter_pattern = "render" + + stats_list = self.collector.build_stats_list() + + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], "render") + + def test_filter_case_insensitive(self): + """Test that filtering is case-insensitive.""" + self.collector.filter_pattern = "MODELS" + + stats_list = self.collector.build_stats_list() + + # Should still match models.py + self.assertEqual(len(stats_list), 1) + + def test_filter_substring_matching(self): + """Test substring filtering.""" + self.collector.filter_pattern = "app/" + + stats_list = self.collector.build_stats_list() + + # Should match both app files + self.assertEqual(len(stats_list), 2) + + def test_no_filter(self): + """Test with no filter applied.""" + self.collector.filter_pattern = None + + stats_list = self.collector.build_stats_list() + + # All items should be included + self.assertEqual(len(stats_list), 3) + + def test_filter_partial_function_name(self): + """Test filtering by partial function name.""" + self.collector.filter_pattern = "save" + + stats_list = self.collector.build_stats_list() + + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], "save") + + def test_filter_combined_filename_funcname(self): + """Test filtering matches filename:funcname pattern.""" + self.collector.filter_pattern = "views.py:render" + + stats_list = self.collector.build_stats_list() + + # Should match the combined pattern + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], "render") + + def test_filter_no_matches(self): + """Test filter that matches nothing.""" + self.collector.filter_pattern = "nonexistent" + + stats_list = self.collector.build_stats_list() + + self.assertEqual(len(stats_list), 0) + + +class TestLiveCollectorFilterInput(unittest.TestCase): + """Tests for filter input mode.""" + + def setUp(self): + """Set up collector with mock display.""" + self.display = MockDisplay(height=40, width=160) + self.collector = LiveStatsCollector( + 1000, pid=12345, display=self.display + ) + self.collector.start_time = time.perf_counter() + + def test_enter_filter_mode(self): + """Test entering filter input mode.""" + self.assertFalse(self.collector.filter_input_mode) + + # Press '/' to enter filter mode + self.display.simulate_input(ord("/")) + self.collector._handle_input() + + self.assertTrue(self.collector.filter_input_mode) + + def test_filter_input_typing(self): + """Test typing characters in filter input mode.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "" + + # Type 't', 'e', 's', 't' + for ch in "test": + self.display.simulate_input(ord(ch)) + self.collector._handle_input() + + self.assertEqual(self.collector.filter_input_buffer, "test") + + def test_filter_input_backspace(self): + """Test backspace in filter input mode.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "test" + + # Press backspace (127) + self.display.simulate_input(127) + self.collector._handle_input() + + self.assertEqual(self.collector.filter_input_buffer, "tes") + + def test_filter_input_backspace_alt(self): + """Test alternative backspace key (263) in filter input mode.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "test" + + # Press backspace (263) + self.display.simulate_input(263) + self.collector._handle_input() + + self.assertEqual(self.collector.filter_input_buffer, "tes") + + def test_filter_input_backspace_empty(self): + """Test backspace on empty buffer.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "" + + # Press backspace - should not crash + self.display.simulate_input(127) + self.collector._handle_input() + + self.assertEqual(self.collector.filter_input_buffer, "") + + def test_filter_input_enter_applies_filter(self): + """Test pressing Enter applies the filter.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "myfilter" + + # Press Enter (10) + self.display.simulate_input(10) + self.collector._handle_input() + + self.assertFalse(self.collector.filter_input_mode) + self.assertEqual(self.collector.filter_pattern, "myfilter") + self.assertEqual(self.collector.filter_input_buffer, "") + + def test_filter_input_enter_alt(self): + """Test alternative Enter key (13) applies filter.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "myfilter" + + # Press Enter (13) + self.display.simulate_input(13) + self.collector._handle_input() + + self.assertFalse(self.collector.filter_input_mode) + self.assertEqual(self.collector.filter_pattern, "myfilter") + + def test_filter_input_enter_empty_clears_filter(self): + """Test pressing Enter with empty buffer clears filter.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "" + self.collector.filter_pattern = "oldfilter" + + # Press Enter + self.display.simulate_input(10) + self.collector._handle_input() + + self.assertFalse(self.collector.filter_input_mode) + self.assertIsNone(self.collector.filter_pattern) + + def test_filter_input_escape_cancels(self): + """Test pressing ESC cancels filter input.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "newfilter" + self.collector.filter_pattern = "oldfilter" + + # Press ESC (27) + self.display.simulate_input(27) + self.collector._handle_input() + + self.assertFalse(self.collector.filter_input_mode) + self.assertEqual( + self.collector.filter_pattern, "oldfilter" + ) # Unchanged + self.assertEqual(self.collector.filter_input_buffer, "") + + def test_filter_input_start_with_existing_filter(self): + """Test entering filter mode with existing filter pre-fills buffer.""" + self.collector.filter_pattern = "existing" + + # Enter filter mode + self.display.simulate_input(ord("/")) + self.collector._handle_input() + + # Buffer should be pre-filled with existing pattern + self.assertEqual(self.collector.filter_input_buffer, "existing") + + def test_filter_input_start_without_filter(self): + """Test entering filter mode with no existing filter.""" + self.collector.filter_pattern = None + + # Enter filter mode + self.display.simulate_input(ord("/")) + self.collector._handle_input() + + # Buffer should be empty + self.assertEqual(self.collector.filter_input_buffer, "") + + def test_filter_input_mode_blocks_other_commands(self): + """Test that filter input mode blocks other commands.""" + self.collector.filter_input_mode = True + initial_sort = self.collector.sort_by + + # Try to press 's' (sort) - should be captured as input + self.display.simulate_input(ord("s")) + self.collector._handle_input() + + # Sort should not change, 's' should be in buffer + self.assertEqual(self.collector.sort_by, initial_sort) + self.assertEqual(self.collector.filter_input_buffer, "s") + + def test_filter_input_non_printable_ignored(self): + """Test that non-printable characters are ignored.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "test" + + # Try to input a control character (< 32) + self.display.simulate_input(1) # Ctrl-A + self.collector._handle_input() + + # Buffer should be unchanged + self.assertEqual(self.collector.filter_input_buffer, "test") + + def test_filter_input_high_ascii_ignored(self): + """Test that high ASCII characters (>= 127, except backspace) are ignored.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "test" + + # Try to input high ASCII (128) + self.display.simulate_input(128) + self.collector._handle_input() + + # Buffer should be unchanged + self.assertEqual(self.collector.filter_input_buffer, "test") + + def test_filter_prompt_displayed(self): + """Test that filter prompt is displayed when in input mode.""" + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "myfilter" + self.collector.total_samples = 10 + + self.collector._update_display() + + # Should show the filter prompt + self.assertTrue(self.display.contains_text("Function filter")) + self.assertTrue(self.display.contains_text("myfilter")) + + +class TestLiveCollectorThreadNavigation(unittest.TestCase): + """Tests for thread navigation functionality.""" + + def setUp(self): + """Set up collector with mock display and multiple threads.""" + self.mock_display = MockDisplay(height=40, width=160) + self.collector = LiveStatsCollector( + 1000, pid=12345, display=self.mock_display + ) + self.collector.start_time = time.perf_counter() + + # Simulate data from multiple threads + frames1 = [MockFrameInfo("file1.py", 10, "func1")] + frames2 = [MockFrameInfo("file2.py", 20, "func2")] + frames3 = [MockFrameInfo("file3.py", 30, "func3")] + + thread1 = MockThreadInfo(111, frames1) + thread2 = MockThreadInfo(222, frames2) + thread3 = MockThreadInfo(333, frames3) + + interpreter_info = MockInterpreterInfo(0, [thread1, thread2, thread3]) + stack_frames = [interpreter_info] + + # Collect data to populate thread IDs + self.collector.collect(stack_frames) + + def test_initial_view_mode_is_all(self): + """Test that collector starts in ALL mode.""" + self.assertEqual(self.collector.view_mode, "ALL") + self.assertEqual(self.collector.current_thread_index, 0) + + def test_thread_ids_are_tracked(self): + """Test that thread IDs are tracked during collection.""" + self.assertIn(111, self.collector.thread_ids) + self.assertIn(222, self.collector.thread_ids) + self.assertIn(333, self.collector.thread_ids) + self.assertEqual(len(self.collector.thread_ids), 3) + + def test_toggle_to_per_thread_mode(self): + """Test toggling from ALL to PER_THREAD mode with 't' key.""" + self.assertEqual(self.collector.view_mode, "ALL") + + self.mock_display.simulate_input(ord("t")) + self.collector._handle_input() + + self.assertEqual(self.collector.view_mode, "PER_THREAD") + self.assertEqual(self.collector.current_thread_index, 0) + + def test_toggle_back_to_all_mode(self): + """Test toggling back from PER_THREAD to ALL mode.""" + # Switch to PER_THREAD + self.mock_display.simulate_input(ord("t")) + self.collector._handle_input() + self.assertEqual(self.collector.view_mode, "PER_THREAD") + + # Switch back to ALL + self.mock_display.simulate_input(ord("T")) + self.collector._handle_input() + self.assertEqual(self.collector.view_mode, "ALL") + + def test_arrow_right_navigates_threads_in_per_thread_mode(self): + """Test that arrow keys navigate threads in PER_THREAD mode.""" + # Switch to PER_THREAD mode + self.mock_display.simulate_input(ord("t")) + self.collector._handle_input() + + # Navigate forward + self.assertEqual(self.collector.current_thread_index, 0) + + self.mock_display.simulate_input(curses.KEY_RIGHT) + self.collector._handle_input() + self.assertEqual(self.collector.current_thread_index, 1) + + self.mock_display.simulate_input(curses.KEY_RIGHT) + self.collector._handle_input() + self.assertEqual(self.collector.current_thread_index, 2) + + def test_arrow_left_navigates_threads_backward(self): + """Test that left arrow navigates threads backward.""" + # Switch to PER_THREAD mode + self.mock_display.simulate_input(ord("t")) + self.collector._handle_input() + + # Navigate backward (should wrap around) + self.mock_display.simulate_input(curses.KEY_LEFT) + self.collector._handle_input() + self.assertEqual( + self.collector.current_thread_index, 2 + ) # Wrapped to last + + self.mock_display.simulate_input(curses.KEY_LEFT) + self.collector._handle_input() + self.assertEqual(self.collector.current_thread_index, 1) + + def test_arrow_down_navigates_like_right(self): + """Test that down arrow works like right arrow.""" + # Switch to PER_THREAD mode + self.mock_display.simulate_input(ord("t")) + self.collector._handle_input() + + self.mock_display.simulate_input(curses.KEY_DOWN) + self.collector._handle_input() + self.assertEqual(self.collector.current_thread_index, 1) + + def test_arrow_up_navigates_like_left(self): + """Test that up arrow works like left arrow.""" + # Switch to PER_THREAD mode + self.mock_display.simulate_input(ord("t")) + self.collector._handle_input() + + self.mock_display.simulate_input(curses.KEY_UP) + self.collector._handle_input() + self.assertEqual(self.collector.current_thread_index, 2) # Wrapped + + def test_arrow_keys_switch_to_per_thread_mode(self): + """Test that arrow keys switch from ALL mode to PER_THREAD mode.""" + self.assertEqual(self.collector.view_mode, "ALL") + + self.mock_display.simulate_input(curses.KEY_RIGHT) + self.collector._handle_input() + self.assertEqual(self.collector.view_mode, "PER_THREAD") + self.assertEqual(self.collector.current_thread_index, 0) + + def test_stats_list_in_all_mode(self): + """Test that stats list uses aggregated data in ALL mode.""" + stats_list = self.collector.build_stats_list() + + # Should have all 3 functions + self.assertEqual(len(stats_list), 3) + func_names = {stat["func"][2] for stat in stats_list} + self.assertEqual(func_names, {"func1", "func2", "func3"}) + + def test_stats_list_in_per_thread_mode(self): + """Test that stats list filters by thread in PER_THREAD mode.""" + # Switch to PER_THREAD mode + self.collector.view_mode = "PER_THREAD" + self.collector.current_thread_index = 0 # First thread (111) + + stats_list = self.collector.build_stats_list() + + # Should only have func1 from thread 111 + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], "func1") + + def test_stats_list_switches_with_thread_navigation(self): + """Test that stats list updates when navigating threads.""" + self.collector.view_mode = "PER_THREAD" + + # Thread 0 (111) -> func1 + self.collector.current_thread_index = 0 + stats_list = self.collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], "func1") + + # Thread 1 (222) -> func2 + self.collector.current_thread_index = 1 + stats_list = self.collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], "func2") + + # Thread 2 (333) -> func3 + self.collector.current_thread_index = 2 + stats_list = self.collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], "func3") + + def test_reset_stats_clears_thread_data(self): + """Test that reset_stats clears thread tracking data.""" + self.assertGreater(len(self.collector.thread_ids), 0) + self.assertGreater(len(self.collector.per_thread_data), 0) + + self.collector.reset_stats() + + self.assertEqual(len(self.collector.thread_ids), 0) + self.assertEqual(len(self.collector.per_thread_data), 0) + self.assertEqual(self.collector.view_mode, "ALL") + self.assertEqual(self.collector.current_thread_index, 0) + + def test_toggle_with_no_threads_stays_in_all_mode(self): + """Test that toggle does nothing when no threads exist.""" + collector = LiveStatsCollector(1000, display=MockDisplay()) + self.assertEqual(len(collector.thread_ids), 0) + + collector.display.simulate_input(ord("t")) + collector._handle_input() + + # Should remain in ALL mode since no threads + self.assertEqual(collector.view_mode, "ALL") + + def test_per_thread_data_isolation(self): + """Test that per-thread data is properly isolated.""" + # Check that each thread has its own isolated data + self.assertIn(111, self.collector.per_thread_data) + self.assertIn(222, self.collector.per_thread_data) + self.assertIn(333, self.collector.per_thread_data) + + # Thread 111 should only have func1 + thread1_funcs = list(self.collector.per_thread_data[111].result.keys()) + self.assertEqual(len(thread1_funcs), 1) + self.assertEqual(thread1_funcs[0][2], "func1") + + # Thread 222 should only have func2 + thread2_funcs = list(self.collector.per_thread_data[222].result.keys()) + self.assertEqual(len(thread2_funcs), 1) + self.assertEqual(thread2_funcs[0][2], "func2") + + def test_aggregated_data_sums_all_threads(self): + """Test that ALL mode shows aggregated data from all threads.""" + # All three functions should be in the aggregated result + self.assertEqual(len(self.collector.result), 3) + + # Each function should have 1 direct call + for func_location, counts in self.collector.result.items(): + self.assertEqual(counts["direct_calls"], 1) + + def test_per_thread_status_tracking(self): + """Test that per-thread status statistics are tracked.""" + # Each thread should have status counts + self.assertIn(111, self.collector.per_thread_data) + self.assertIn(222, self.collector.per_thread_data) + self.assertIn(333, self.collector.per_thread_data) + + # Each thread should have the expected attributes + for thread_id in [111, 222, 333]: + thread_data = self.collector.per_thread_data[thread_id] + self.assertIsNotNone(thread_data.has_gil) + self.assertIsNotNone(thread_data.on_cpu) + self.assertIsNotNone(thread_data.gil_requested) + self.assertIsNotNone(thread_data.unknown) + self.assertIsNotNone(thread_data.total) + # Each thread was sampled once + self.assertEqual(thread_data.total, 1) + + def test_reset_stats_clears_thread_status(self): + """Test that reset_stats clears per-thread status data.""" + self.assertGreater(len(self.collector.per_thread_data), 0) + + self.collector.reset_stats() + + self.assertEqual(len(self.collector.per_thread_data), 0) + + def test_per_thread_sample_counts(self): + """Test that per-thread sample counts are tracked correctly.""" + # Each thread should have exactly 1 sample (we collected once) + for thread_id in [111, 222, 333]: + self.assertIn(thread_id, self.collector.per_thread_data) + self.assertEqual(self.collector.per_thread_data[thread_id].sample_count, 1) + + def test_per_thread_gc_samples(self): + """Test that per-thread GC samples are tracked correctly.""" + # Initially no threads have GC frames + for thread_id in [111, 222, 333]: + self.assertIn(thread_id, self.collector.per_thread_data) + self.assertEqual( + self.collector.per_thread_data[thread_id].gc_frame_samples, 0 + ) + + # Now collect a sample with a GC frame in thread 222 + gc_frames = [MockFrameInfo("gc.py", 100, "gc_collect")] + thread_with_gc = MockThreadInfo(222, gc_frames) + interpreter_info = MockInterpreterInfo(0, [thread_with_gc]) + stack_frames = [interpreter_info] + + self.collector.collect(stack_frames) + + # Thread 222 should now have 1 GC sample + self.assertEqual(self.collector.per_thread_data[222].gc_frame_samples, 1) + # Other threads should still have 0 + self.assertEqual(self.collector.per_thread_data[111].gc_frame_samples, 0) + self.assertEqual(self.collector.per_thread_data[333].gc_frame_samples, 0) + + def test_only_threads_with_frames_are_tracked(self): + """Test that only threads with actual frame data are added to thread_ids.""" + # Create a new collector + collector = LiveStatsCollector(1000, display=MockDisplay()) + + # Create threads: one with frames, one without + frames = [MockFrameInfo("test.py", 10, "test_func")] + thread_with_frames = MockThreadInfo(111, frames) + thread_without_frames = MockThreadInfo(222, None) # No frames + interpreter_info = MockInterpreterInfo( + 0, [thread_with_frames, thread_without_frames] + ) + stack_frames = [interpreter_info] + + collector.collect(stack_frames) + + # Only thread 111 should be tracked (it has frames) + self.assertIn(111, collector.thread_ids) + self.assertNotIn(222, collector.thread_ids) + + def test_per_thread_status_isolation(self): + """Test that per-thread status counts are isolated per thread.""" + # Create threads with different status flags + + frames1 = [MockFrameInfo("file1.py", 10, "func1")] + frames2 = [MockFrameInfo("file2.py", 20, "func2")] + + # Thread 444: has GIL but not on CPU + thread1 = MockThreadInfo(444, frames1, status=THREAD_STATUS_HAS_GIL) + # Thread 555: on CPU but not has GIL + thread2 = MockThreadInfo(555, frames2, status=THREAD_STATUS_ON_CPU) + + interpreter_info = MockInterpreterInfo(0, [thread1, thread2]) + stack_frames = [interpreter_info] + + collector = LiveStatsCollector(1000, display=MockDisplay()) + collector.collect(stack_frames) + + # Check thread 444 status + self.assertEqual(collector.per_thread_data[444].has_gil, 1) + self.assertEqual(collector.per_thread_data[444].on_cpu, 0) + + # Check thread 555 status + self.assertEqual(collector.per_thread_data[555].has_gil, 0) + self.assertEqual(collector.per_thread_data[555].on_cpu, 1) + + def test_display_uses_per_thread_stats_in_per_thread_mode(self): + """Test that display widget uses per-thread stats when in PER_THREAD mode.""" + + # Create collector with mock display + collector = LiveStatsCollector(1000, display=MockDisplay()) + collector.start_time = time.perf_counter() + + # Create 2 threads with different characteristics + # Thread 111: always has GIL (10 samples) + # Thread 222: never has GIL (10 samples) + for _ in range(10): + frames1 = [MockFrameInfo("file1.py", 10, "func1")] + frames2 = [MockFrameInfo("file2.py", 20, "func2")] + thread1 = MockThreadInfo( + 111, frames1, status=THREAD_STATUS_HAS_GIL + ) + thread2 = MockThreadInfo(222, frames2, status=0) # No flags + interpreter_info = MockInterpreterInfo(0, [thread1, thread2]) + collector.collect([interpreter_info]) + + # In ALL mode, should show mixed stats (50% on GIL, 50% off GIL) + self.assertEqual(collector.view_mode, "ALL") + total_has_gil = collector.thread_status_counts["has_gil"] + total_threads = collector.thread_status_counts["total"] + self.assertEqual(total_has_gil, 10) # Only thread 111 has GIL + self.assertEqual(total_threads, 20) # 10 samples * 2 threads + + # Switch to PER_THREAD mode and select thread 111 + collector.view_mode = "PER_THREAD" + collector.current_thread_index = 0 # Thread 111 + + # Thread 111 should show 100% on GIL + thread_111_data = collector.per_thread_data[111] + self.assertEqual(thread_111_data.has_gil, 10) + self.assertEqual(thread_111_data.total, 10) + + # Switch to thread 222 + collector.current_thread_index = 1 # Thread 222 + + # Thread 222 should show 0% on GIL + thread_222_data = collector.per_thread_data[222] + self.assertEqual(thread_222_data.has_gil, 0) + self.assertEqual(thread_222_data.total, 10) + + def test_display_uses_per_thread_gc_stats_in_per_thread_mode(self): + """Test that GC percentage uses per-thread data in PER_THREAD mode.""" + # Create collector with mock display + collector = LiveStatsCollector(1000, display=MockDisplay()) + collector.start_time = time.perf_counter() + + # Thread 111: 5 samples, 2 with GC + # Thread 222: 5 samples, 0 with GC + for i in range(5): + if i < 2: + # First 2 samples for thread 111 have GC + frames1 = [MockFrameInfo("gc.py", 100, "gc_collect")] + else: + frames1 = [MockFrameInfo("file1.py", 10, "func1")] + + frames2 = [MockFrameInfo("file2.py", 20, "func2")] # No GC + + thread1 = MockThreadInfo(111, frames1) + thread2 = MockThreadInfo(222, frames2) + interpreter_info = MockInterpreterInfo(0, [thread1, thread2]) + collector.collect([interpreter_info]) + + # Check aggregated GC stats (ALL mode) + # 2 GC samples out of 10 total = 20% + self.assertEqual(collector.gc_frame_samples, 2) + self.assertEqual(collector.total_samples, 5) # 5 collect() calls + + # Check per-thread GC stats + # Thread 111: 2 GC samples out of 5 = 40% + self.assertEqual(collector.per_thread_data[111].gc_frame_samples, 2) + self.assertEqual(collector.per_thread_data[111].sample_count, 5) + + # Thread 222: 0 GC samples out of 5 = 0% + self.assertEqual(collector.per_thread_data[222].gc_frame_samples, 0) + self.assertEqual(collector.per_thread_data[222].sample_count, 5) + + # Now verify the display would use the correct stats + collector.view_mode = "PER_THREAD" + + # For thread 111 + collector.current_thread_index = 0 + thread_id = collector.thread_ids[0] + self.assertEqual(thread_id, 111) + thread_gc_pct = ( + collector.per_thread_data[111].gc_frame_samples + / collector.per_thread_data[111].sample_count + ) * 100 + self.assertEqual(thread_gc_pct, 40.0) + + # For thread 222 + collector.current_thread_index = 1 + thread_id = collector.thread_ids[1] + self.assertEqual(thread_id, 222) + thread_gc_pct = ( + collector.per_thread_data[222].gc_frame_samples + / collector.per_thread_data[222].sample_count + ) * 100 + self.assertEqual(thread_gc_pct, 0.0) + + def test_function_counts_are_per_thread_in_per_thread_mode(self): + """Test that function counts (total/exec/stack) are per-thread in PER_THREAD mode.""" + # Create collector with mock display + collector = LiveStatsCollector(1000, display=MockDisplay()) + collector.start_time = time.perf_counter() + + # Thread 111: calls func1, func2, func3 (3 functions) + # Thread 222: calls func4, func5 (2 functions) + frames1 = [ + MockFrameInfo("file1.py", 10, "func1"), + MockFrameInfo("file1.py", 20, "func2"), + MockFrameInfo("file1.py", 30, "func3"), + ] + frames2 = [ + MockFrameInfo("file2.py", 40, "func4"), + MockFrameInfo("file2.py", 50, "func5"), + ] + + thread1 = MockThreadInfo(111, frames1) + thread2 = MockThreadInfo(222, frames2) + interpreter_info = MockInterpreterInfo(0, [thread1, thread2]) + collector.collect([interpreter_info]) + + # In ALL mode, should have 5 total functions + self.assertEqual(len(collector.result), 5) + + # In PER_THREAD mode for thread 111, should have 3 functions + collector.view_mode = "PER_THREAD" + collector.current_thread_index = 0 # Thread 111 + thread_111_result = collector.per_thread_data[111].result + self.assertEqual(len(thread_111_result), 3) + + # Verify the functions are the right ones + thread_111_funcs = {loc[2] for loc in thread_111_result.keys()} + self.assertEqual(thread_111_funcs, {"func1", "func2", "func3"}) + + # In PER_THREAD mode for thread 222, should have 2 functions + collector.current_thread_index = 1 # Thread 222 + thread_222_result = collector.per_thread_data[222].result + self.assertEqual(len(thread_222_result), 2) + + # Verify the functions are the right ones + thread_222_funcs = {loc[2] for loc in thread_222_result.keys()} + self.assertEqual(thread_222_funcs, {"func4", "func5"}) + + +class TestLiveCollectorNewFeatures(unittest.TestCase): + """Tests for new features added to live collector.""" + + def setUp(self): + """Set up test fixtures.""" + self.display = MockDisplay() + self.collector = LiveStatsCollector(1000, display=self.display) + self.collector.start_time = time.perf_counter() + + def test_filter_input_takes_precedence_over_commands(self): + """Test that filter input mode blocks command keys like 'h' and 'p'.""" + # Enter filter input mode + self.collector.filter_input_mode = True + self.collector.filter_input_buffer = "" + + # Press 'h' - should add to filter buffer, not show help + self.display.simulate_input(ord("h")) + self.collector._handle_input() + + self.assertFalse(self.collector.show_help) # Help not triggered + self.assertEqual(self.collector.filter_input_buffer, "h") # Added to filter + self.assertTrue(self.collector.filter_input_mode) # Still in filter mode + + def test_reset_blocked_when_finished(self): + """Test that reset command is blocked when profiling is finished.""" + # Set up some sample data and mark as finished + self.collector.total_samples = 100 + self.collector.finished = True + + # Press 'r' for reset + self.display.simulate_input(ord("r")) + self.collector._handle_input() + + # Should NOT have been reset + self.assertEqual(self.collector.total_samples, 100) + self.assertTrue(self.collector.finished) + + def test_time_display_fix_when_finished(self): + """Test that time display shows correct frozen time when finished.""" + + # Mark as finished to freeze time + self.collector.mark_finished() + + # Should have set both timestamps correctly + self.assertIsNotNone(self.collector.finish_timestamp) + self.assertIsNotNone(self.collector.finish_wall_time) + + # Get the frozen time display + frozen_time = self.collector.current_time_display + + # Wait a bit + time.sleep(0.1) + + # Should still show the same frozen time (not jump to wrong time) + self.assertEqual(self.collector.current_time_display, frozen_time) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_ui.py b/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_ui.py new file mode 100644 index 00000000000..ae4ee969f34 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_live_collector_ui.py @@ -0,0 +1,906 @@ +"""UI and display tests for LiveStatsCollector. + +Tests for MockDisplay, curses integration, display methods, +edge cases, update display, and display helpers. +""" + +import functools +import io +import sys +import tempfile +import time +import unittest +from unittest import mock +from test.support import requires, requires_remote_subprocess_debugging +from test.support.import_helper import import_module + +# Only run these tests if curses is available +requires("curses") +curses = import_module("curses") + +from profiling.sampling.live_collector import LiveStatsCollector, MockDisplay +from profiling.sampling.cli import main +from ._live_collector_helpers import ( + MockThreadInfo, + MockInterpreterInfo, +) +from .helpers import close_and_unlink + + +class TestLiveStatsCollectorWithMockDisplay(unittest.TestCase): + """Tests for display functionality using MockDisplay.""" + + def setUp(self): + """Set up collector with mock display.""" + self.mock_display = MockDisplay(height=40, width=160) + self.collector = LiveStatsCollector( + 1000, pid=12345, display=self.mock_display + ) + self.collector.start_time = time.perf_counter() + + def test_update_display_with_mock(self): + """Test that update_display works with MockDisplay.""" + self.collector.total_samples = 100 + self.collector.result[("test.py", 10, "test_func")] = { + "direct_calls": 50, + "cumulative_calls": 75, + "total_rec_calls": 0, + } + + self.collector._update_display() + + # Verify display operations were called + self.assertTrue(self.mock_display.cleared) + self.assertTrue(self.mock_display.refreshed) + self.assertTrue(self.mock_display.redrawn) + + # Verify some content was written + self.assertGreater(len(self.mock_display.buffer), 0) + + def test_handle_input_quit(self): + """Test that 'q' input stops the collector.""" + self.mock_display.simulate_input(ord("q")) + self.collector._handle_input() + self.assertFalse(self.collector.running) + + def test_handle_input_sort_cycle(self): + """Test that 's' input cycles sort mode.""" + self.collector.sort_by = "tottime" + self.mock_display.simulate_input(ord("s")) + self.collector._handle_input() + self.assertEqual(self.collector.sort_by, "cumul_pct") + + def test_draw_methods_with_mock_display(self): + """Test that draw methods write to mock display.""" + self.collector.total_samples = 500 + self.collector.successful_samples = 450 + self.collector.failed_samples = 50 + + colors = self.collector._setup_colors() + self.collector._initialize_widgets(colors) + + # Test individual widget methods + line = self.collector.header_widget.draw_header_info(0, 160, 100.5) + self.assertEqual(line, 2) # Title + header info line + self.assertGreater(len(self.mock_display.buffer), 0) + + # Clear buffer and test next method + self.mock_display.buffer.clear() + line = self.collector.header_widget.draw_sample_stats(0, 160, 10.0) + self.assertEqual(line, 1) + self.assertGreater(len(self.mock_display.buffer), 0) + + def test_terminal_too_small_message(self): + """Test terminal too small warning.""" + small_display = MockDisplay(height=10, width=50) + self.collector.display = small_display + + self.collector._show_terminal_too_small(10, 50) + + # Should have written warning message + text = small_display.get_text_at(3, 15) # Approximate center + self.assertIsNotNone(text) + + def test_full_display_rendering_with_data(self): + """Test complete display rendering with realistic data.""" + # Add multiple functions with different call counts + self.collector.total_samples = 1000 + self.collector.successful_samples = 950 + self.collector.failed_samples = 50 + + self.collector.result[("app.py", 10, "main")] = { + "direct_calls": 100, + "cumulative_calls": 500, + "total_rec_calls": 0, + } + self.collector.result[("utils.py", 20, "helper")] = { + "direct_calls": 300, + "cumulative_calls": 400, + "total_rec_calls": 0, + } + self.collector.result[("db.py", 30, "query")] = { + "direct_calls": 50, + "cumulative_calls": 100, + "total_rec_calls": 0, + } + + self.collector._update_display() + + # Verify the display has content + self.assertGreater(len(self.mock_display.buffer), 10) + + # Verify PID is shown + found_pid = False + for (line, col), (text, attr) in self.mock_display.buffer.items(): + if "12345" in text: + found_pid = True + break + self.assertTrue(found_pid, "PID should be displayed") + + def test_efficiency_bar_visualization(self): + """Test that efficiency bar shows correct proportions.""" + self.collector.total_samples = 100 + self.collector.successful_samples = 75 + self.collector.failed_samples = 25 + + colors = self.collector._setup_colors() + self.collector._initialize_widgets(colors) + self.collector.header_widget.draw_efficiency_bar(0, 160) + + # Check that something was drawn to the display + self.assertGreater(len(self.mock_display.buffer), 0) + + def test_stats_display_with_different_sort_modes(self): + """Test that stats are displayed correctly with different sort modes.""" + self.collector.total_samples = 100 + self.collector.successful_samples = 100 # For percentage calculations + self.collector.result[("a.py", 1, "func_a")] = { + "direct_calls": 10, + "cumulative_calls": 20, + "total_rec_calls": 0, + } + self.collector.result[("b.py", 2, "func_b")] = { + "direct_calls": 30, + "cumulative_calls": 40, + "total_rec_calls": 0, + } + + # Test each sort mode + for sort_mode in [ + "nsamples", + "tottime", + "cumtime", + "sample_pct", + "cumul_pct", + ]: + self.mock_display.buffer.clear() + self.collector.sort_by = sort_mode + + stats_list = self.collector.build_stats_list() + self.assertEqual(len(stats_list), 2) + + # Verify sorting worked (func_b should be first for most modes) + if sort_mode in ["nsamples", "tottime", "sample_pct"]: + self.assertEqual(stats_list[0]["func"][2], "func_b") + + def test_narrow_terminal_column_hiding(self): + """Test that columns are hidden on narrow terminals.""" + narrow_display = MockDisplay(height=40, width=70) + collector = LiveStatsCollector(1000, pid=12345, display=narrow_display) + collector.start_time = time.perf_counter() + + colors = collector._setup_colors() + collector._initialize_widgets(colors) + line, show_sample_pct, show_tottime, show_cumul_pct, show_cumtime = ( + collector.table_widget.draw_column_headers(0, 70) + ) + + # On narrow terminal, some columns should be hidden + self.assertFalse( + show_cumul_pct or show_cumtime, + "Some columns should be hidden on narrow terminal", + ) + + def test_very_narrow_terminal_minimal_columns(self): + """Test minimal display on very narrow terminal.""" + very_narrow = MockDisplay(height=40, width=60) + collector = LiveStatsCollector(1000, pid=12345, display=very_narrow) + collector.start_time = time.perf_counter() + + colors = collector._setup_colors() + collector._initialize_widgets(colors) + line, show_sample_pct, show_tottime, show_cumul_pct, show_cumtime = ( + collector.table_widget.draw_column_headers(0, 60) + ) + + # Very narrow should hide even more columns + self.assertFalse( + show_sample_pct, + "Sample % should be hidden on very narrow terminal", + ) + + def test_display_updates_only_at_interval(self): + """Test that display updates respect the update interval.""" + # Create collector with display + collector = LiveStatsCollector(1000, display=self.mock_display) + + # Simulate multiple rapid collections + thread_info = MockThreadInfo(123, []) + interpreter_info = MockInterpreterInfo(0, [thread_info]) + stack_frames = [interpreter_info] + + # First collect should update display + collector.collect(stack_frames) + first_cleared = self.mock_display.cleared + + # Reset flags + self.mock_display.cleared = False + self.mock_display.refreshed = False + + # Immediate second collect should NOT update display (too soon) + collector.collect(stack_frames) + self.assertFalse( + self.mock_display.cleared, + "Display should not update too frequently", + ) + + def test_top_functions_display(self): + """Test that top functions are highlighted correctly.""" + self.collector.total_samples = 1000 + + # Create functions with different sample counts + for i in range(10): + self.collector.result[(f"file{i}.py", i * 10, f"func{i}")] = { + "direct_calls": (10 - i) * 10, # Decreasing counts + "cumulative_calls": (10 - i) * 20, + "total_rec_calls": 0, + } + + colors = self.collector._setup_colors() + self.collector._initialize_widgets(colors) + stats_list = self.collector.build_stats_list() + + self.collector.header_widget.draw_top_functions(0, 160, stats_list) + + # Top functions section should have written something + self.assertGreater(len(self.mock_display.buffer), 0) + + +class TestLiveStatsCollectorCursesIntegration(unittest.TestCase): + """Tests for curses-related functionality using mocks.""" + + def setUp(self): + """Set up mock curses screen.""" + self.mock_stdscr = mock.MagicMock() + self.mock_stdscr.getmaxyx.return_value = (40, 160) # height, width + self.mock_stdscr.getch.return_value = -1 # No input + # Save original stdout/stderr + self._orig_stdout = sys.stdout + self._orig_stderr = sys.stderr + + def tearDown(self): + """Restore stdout/stderr if changed.""" + sys.stdout = self._orig_stdout + sys.stderr = self._orig_stderr + + def test_init_curses(self): + """Test curses initialization.""" + collector = LiveStatsCollector(1000) + + with ( + mock.patch("curses.curs_set"), + mock.patch("curses.has_colors", return_value=True), + mock.patch("curses.start_color"), + mock.patch("curses.use_default_colors"), + mock.patch("builtins.open", mock.mock_open()) as mock_open_func, + ): + collector.init_curses(self.mock_stdscr) + + self.assertIsNotNone(collector.stdscr) + self.mock_stdscr.nodelay.assert_called_with(True) + self.mock_stdscr.scrollok.assert_called_with(False) + + # Clean up properly + if collector._devnull: + collector._devnull.close() + collector._saved_stdout = None + collector._saved_stderr = None + + def test_cleanup_curses(self): + """Test curses cleanup.""" + mock_display = MockDisplay() + collector = LiveStatsCollector(1000, display=mock_display) + collector.stdscr = self.mock_stdscr + + # Mock devnull file to avoid resource warnings + mock_devnull = mock.MagicMock() + mock_saved_stdout = mock.MagicMock() + mock_saved_stderr = mock.MagicMock() + + collector._devnull = mock_devnull + collector._saved_stdout = mock_saved_stdout + collector._saved_stderr = mock_saved_stderr + + with mock.patch("curses.curs_set"): + collector.cleanup_curses() + + mock_devnull.close.assert_called_once() + # Verify stdout/stderr were set back to the saved values + self.assertEqual(sys.stdout, mock_saved_stdout) + self.assertEqual(sys.stderr, mock_saved_stderr) + # Verify the saved values were cleared + self.assertIsNone(collector._saved_stdout) + self.assertIsNone(collector._saved_stderr) + self.assertIsNone(collector._devnull) + + def test_add_str_with_mock_display(self): + """Test safe_addstr with MockDisplay.""" + mock_display = MockDisplay(height=40, width=160) + collector = LiveStatsCollector(1000, display=mock_display) + colors = collector._setup_colors() + collector._initialize_widgets(colors) + + collector.header_widget.add_str(5, 10, "Test", 0) + # Verify it was added to the buffer + self.assertIn((5, 10), mock_display.buffer) + + def test_setup_colors_with_color_support(self): + """Test color setup when colors are supported.""" + mock_display = MockDisplay(height=40, width=160) + mock_display.colors_supported = True + collector = LiveStatsCollector(1000, display=mock_display) + + colors = collector._setup_colors() + + self.assertIn("header", colors) + self.assertIn("cyan", colors) + self.assertIn("yellow", colors) + self.assertIn("green", colors) + self.assertIn("magenta", colors) + self.assertIn("red", colors) + + def test_setup_colors_without_color_support(self): + """Test color setup when colors are not supported.""" + mock_display = MockDisplay(height=40, width=160) + mock_display.colors_supported = False + collector = LiveStatsCollector(1000, display=mock_display) + + colors = collector._setup_colors() + + # Should still have all keys but with fallback values + self.assertIn("header", colors) + self.assertIn("cyan", colors) + + def test_handle_input_quit(self): + """Test handling 'q' key to quit.""" + mock_display = MockDisplay() + mock_display.simulate_input(ord("q")) + collector = LiveStatsCollector(1000, display=mock_display) + + self.assertTrue(collector.running) + collector._handle_input() + self.assertFalse(collector.running) + + def test_handle_input_quit_uppercase(self): + """Test handling 'Q' key to quit.""" + mock_display = MockDisplay() + mock_display.simulate_input(ord("Q")) + collector = LiveStatsCollector(1000, display=mock_display) + + self.assertTrue(collector.running) + collector._handle_input() + self.assertFalse(collector.running) + + def test_handle_input_cycle_sort(self): + """Test handling 's' key to cycle sort.""" + mock_display = MockDisplay() + mock_display.simulate_input(ord("s")) + collector = LiveStatsCollector( + 1000, sort_by="nsamples", display=mock_display + ) + + collector._handle_input() + self.assertEqual(collector.sort_by, "sample_pct") + + def test_handle_input_cycle_sort_uppercase(self): + """Test handling 'S' key to cycle sort backward.""" + mock_display = MockDisplay() + mock_display.simulate_input(ord("S")) + collector = LiveStatsCollector( + 1000, sort_by="nsamples", display=mock_display + ) + + collector._handle_input() + self.assertEqual(collector.sort_by, "cumtime") + + def test_handle_input_no_key(self): + """Test handling when no key is pressed.""" + mock_display = MockDisplay() + collector = LiveStatsCollector(1000, display=mock_display) + + collector._handle_input() + # Should not change state + self.assertTrue(collector.running) + + +class TestLiveStatsCollectorDisplayMethods(unittest.TestCase): + """Tests for display-related methods.""" + + def setUp(self): + """Set up collector with mock display.""" + self.mock_display = MockDisplay(height=40, width=160) + self.collector = LiveStatsCollector( + 1000, pid=12345, display=self.mock_display + ) + self.collector.start_time = time.perf_counter() + + def test_show_terminal_too_small(self): + """Test terminal too small message display.""" + self.collector._show_terminal_too_small(10, 50) + # Should have written some content to the display buffer + self.assertGreater(len(self.mock_display.buffer), 0) + + def test_draw_header_info(self): + """Test drawing header information.""" + colors = { + "cyan": curses.A_BOLD, + "green": curses.A_BOLD, + "yellow": curses.A_BOLD, + "magenta": curses.A_BOLD, + } + self.collector._initialize_widgets(colors) + + line = self.collector.header_widget.draw_header_info(0, 160, 100.5) + self.assertEqual(line, 2) # Title + header info line + + def test_draw_sample_stats(self): + """Test drawing sample statistics.""" + self.collector.total_samples = 1000 + colors = {"cyan": curses.A_BOLD, "green": curses.A_BOLD} + self.collector._initialize_widgets(colors) + + line = self.collector.header_widget.draw_sample_stats(0, 160, 10.0) + self.assertEqual(line, 1) + self.assertGreater(self.collector.max_sample_rate, 0) + + def test_progress_bar_uses_target_rate(self): + """Test that progress bar uses target rate instead of max rate.""" + # Set up collector with specific sampling interval + collector = LiveStatsCollector( + 10000, pid=12345, display=self.mock_display + ) # 10ms = 100Hz target + collector.start_time = time.perf_counter() + collector.total_samples = 500 + collector.max_sample_rate = ( + 150 # Higher than target to test we don't use this + ) + + colors = {"cyan": curses.A_BOLD, "green": curses.A_BOLD} + collector._initialize_widgets(colors) + + # Clear the display buffer to capture only our progress bar content + self.mock_display.buffer.clear() + + # Draw sample stats with a known elapsed time that gives us a specific sample rate + elapsed = 10.0 # 500 samples in 10 seconds = 50 samples/second + line = collector.header_widget.draw_sample_stats(0, 160, elapsed) + + # Verify display was updated + self.assertEqual(line, 1) + self.assertGreater(len(self.mock_display.buffer), 0) + + # Verify the label shows current/target format with units instead of "max" + found_current_target_label = False + found_max_label = False + for (line_num, col), (text, attr) in self.mock_display.buffer.items(): + # Should show "50.0Hz/100.0Hz (50.0%)" since we're at 50% of target (50/100) + if "50.0Hz/100.0Hz" in text and "50.0%" in text: + found_current_target_label = True + if "max:" in text: + found_max_label = True + + self.assertTrue( + found_current_target_label, + "Should display current/target rate with percentage", + ) + self.assertFalse(found_max_label, "Should not display max rate label") + + def test_progress_bar_different_intervals(self): + """Test that progress bar adapts to different sampling intervals.""" + test_cases = [ + ( + 1000, + "1.0KHz", + "100.0Hz", + ), # 1ms interval -> 1000Hz target (1.0KHz), 100Hz current + ( + 5000, + "200.0Hz", + "100.0Hz", + ), # 5ms interval -> 200Hz target, 100Hz current + ( + 20000, + "50.0Hz", + "100.0Hz", + ), # 20ms interval -> 50Hz target, 100Hz current + ( + 100000, + "10.0Hz", + "100.0Hz", + ), # 100ms interval -> 10Hz target, 100Hz current + ] + + for ( + interval_usec, + expected_target_formatted, + expected_current_formatted, + ) in test_cases: + with self.subTest(interval=interval_usec): + collector = LiveStatsCollector( + interval_usec, display=MockDisplay() + ) + collector.start_time = time.perf_counter() + collector.total_samples = 100 + + colors = {"cyan": curses.A_BOLD, "green": curses.A_BOLD} + collector._initialize_widgets(colors) + + # Clear buffer + collector.display.buffer.clear() + + # Draw with 1 second elapsed time (gives us current rate of 100Hz) + collector.header_widget.draw_sample_stats(0, 160, 1.0) + + # Check that the current/target format appears in the display with proper units + found_current_target_format = False + for (line_num, col), ( + text, + attr, + ) in collector.display.buffer.items(): + # Looking for format like "100.0Hz/1.0KHz" or "100.0Hz/200.0Hz" + expected_format = f"{expected_current_formatted}/{expected_target_formatted}" + if expected_format in text and "%" in text: + found_current_target_format = True + break + + self.assertTrue( + found_current_target_format, + f"Should display current/target rate format with units for {interval_usec}µs interval", + ) + + def test_draw_efficiency_bar(self): + """Test drawing efficiency bar.""" + self.collector.successful_samples = 900 + self.collector.failed_samples = 100 + self.collector.total_samples = 1000 + colors = {"green": curses.A_BOLD, "red": curses.A_BOLD} + self.collector._initialize_widgets(colors) + + line = self.collector.header_widget.draw_efficiency_bar(0, 160) + self.assertEqual(line, 1) + + def test_draw_function_stats(self): + """Test drawing function statistics.""" + self.collector.result[("test.py", 10, "func1")] = { + "direct_calls": 100, + "cumulative_calls": 150, + "total_rec_calls": 0, + } + self.collector.result[("test.py", 20, "func2")] = { + "direct_calls": 0, + "cumulative_calls": 50, + "total_rec_calls": 0, + } + + stats_list = self.collector.build_stats_list() + colors = { + "cyan": curses.A_BOLD, + "green": curses.A_BOLD, + "yellow": curses.A_BOLD, + "magenta": curses.A_BOLD, + } + self.collector._initialize_widgets(colors) + + line = self.collector.header_widget.draw_function_stats( + 0, 160, stats_list + ) + self.assertEqual(line, 1) + + def test_draw_top_functions(self): + """Test drawing top functions.""" + self.collector.total_samples = 300 + self.collector.result[("test.py", 10, "hot_func")] = { + "direct_calls": 100, + "cumulative_calls": 150, + "total_rec_calls": 0, + } + + stats_list = self.collector.build_stats_list() + colors = { + "red": curses.A_BOLD, + "yellow": curses.A_BOLD, + "green": curses.A_BOLD, + } + self.collector._initialize_widgets(colors) + + line = self.collector.header_widget.draw_top_functions( + 0, 160, stats_list + ) + self.assertEqual(line, 1) + + def test_draw_column_headers(self): + """Test drawing column headers.""" + colors = { + "sorted_header": curses.A_BOLD, + "normal_header": curses.A_NORMAL, + } + self.collector._initialize_widgets(colors) + + ( + line, + show_sample_pct, + show_tottime, + show_cumul_pct, + show_cumtime, + ) = self.collector.table_widget.draw_column_headers(0, 160) + self.assertEqual(line, 1) + self.assertTrue(show_sample_pct) + self.assertTrue(show_tottime) + self.assertTrue(show_cumul_pct) + self.assertTrue(show_cumtime) + + def test_draw_column_headers_narrow_terminal(self): + """Test column headers adapt to narrow terminal.""" + colors = { + "sorted_header": curses.A_BOLD, + "normal_header": curses.A_NORMAL, + } + self.collector._initialize_widgets(colors) + + ( + line, + show_sample_pct, + show_tottime, + show_cumul_pct, + show_cumtime, + ) = self.collector.table_widget.draw_column_headers(0, 70) + self.assertEqual(line, 1) + # Some columns should be hidden on narrow terminal + self.assertFalse(show_cumul_pct) + + def test_draw_footer(self): + """Test drawing footer.""" + colors = self.collector._setup_colors() + self.collector._initialize_widgets(colors) + self.collector.footer_widget.render(38, 160) + # Should have written some content to the display buffer + self.assertGreater(len(self.mock_display.buffer), 0) + + def test_draw_progress_bar(self): + """Test progress bar drawing.""" + colors = self.collector._setup_colors() + self.collector._initialize_widgets(colors) + bar, length = self.collector.header_widget.progress_bar.render_bar( + 50, 100, 30 + ) + + self.assertIn("[", bar) + self.assertIn("]", bar) + self.assertGreater(length, 0) + # Should be roughly 50% filled + self.assertIn("█", bar) + self.assertIn("░", bar) + + +class TestLiveStatsCollectorEdgeCases(unittest.TestCase): + """Tests for edge cases and error handling.""" + + def test_very_long_function_name(self): + """Test handling of very long function names.""" + collector = LiveStatsCollector(1000) + long_name = "x" * 200 + collector.result[("test.py", 10, long_name)] = { + "direct_calls": 10, + "cumulative_calls": 20, + "total_rec_calls": 0, + } + + stats_list = collector.build_stats_list() + self.assertEqual(len(stats_list), 1) + self.assertEqual(stats_list[0]["func"][2], long_name) + + +class TestLiveStatsCollectorUpdateDisplay(unittest.TestCase): + """Tests for the _update_display method.""" + + def setUp(self): + """Set up collector with mock display.""" + self.mock_display = MockDisplay(height=40, width=160) + self.collector = LiveStatsCollector( + 1000, pid=12345, display=self.mock_display + ) + self.collector.start_time = time.perf_counter() + + def test_update_display_terminal_too_small(self): + """Test update_display when terminal is too small.""" + small_display = MockDisplay(height=10, width=50) + self.collector.display = small_display + + with mock.patch.object( + self.collector, "_show_terminal_too_small" + ) as mock_show: + self.collector._update_display() + mock_show.assert_called_once() + + def test_update_display_normal(self): + """Test normal update_display operation.""" + self.collector.total_samples = 100 + self.collector.successful_samples = 90 + self.collector.failed_samples = 10 + self.collector.result[("test.py", 10, "func")] = { + "direct_calls": 50, + "cumulative_calls": 75, + "total_rec_calls": 0, + } + + self.collector._update_display() + + self.assertTrue(self.mock_display.cleared) + self.assertTrue(self.mock_display.refreshed) + + def test_update_display_handles_exception(self): + """Test that update_display handles exceptions gracefully.""" + # Make one of the methods raise an exception + with mock.patch.object( + self.collector, + "_prepare_display_data", + side_effect=Exception("Test error"), + ): + # Should not raise an exception (it catches and logs via trace_exception) + try: + self.collector._update_display() + except Exception: + self.fail( + "_update_display should handle exceptions gracefully" + ) + + +class TestLiveCollectorWithMockDisplayHelpers(unittest.TestCase): + """Tests using the new MockDisplay helper methods.""" + + def test_verify_pid_display_with_contains(self): + """Test verifying PID is displayed using contains_text helper.""" + display = MockDisplay(height=40, width=160) + collector = LiveStatsCollector(1000, pid=99999, display=display) + collector.start_time = time.perf_counter() + collector.total_samples = 10 + + collector._update_display() + + # Use the helper method + self.assertTrue( + display.contains_text("99999"), "PID should be visible in display" + ) + + def test_verify_function_names_displayed(self): + """Test verifying function names appear in display.""" + display = MockDisplay(height=40, width=160) + collector = LiveStatsCollector(1000, pid=12345, display=display) + collector.start_time = time.perf_counter() + + collector.total_samples = 100 + collector.result[("mymodule.py", 42, "my_special_function")] = { + "direct_calls": 50, + "cumulative_calls": 75, + "total_rec_calls": 0, + } + + collector._update_display() + + # Verify function name appears + self.assertTrue( + display.contains_text("my_special_function"), + "Function name should be visible", + ) + + def test_get_all_lines_full_display(self): + """Test getting all lines from a full display render.""" + display = MockDisplay(height=40, width=160) + collector = LiveStatsCollector(1000, pid=12345, display=display) + collector.start_time = time.perf_counter() + collector.total_samples = 100 + + collector._update_display() + + lines = display.get_all_lines() + + # Should have multiple lines of content + self.assertGreater(len(lines), 5) + + # Should have header content + self.assertTrue(any("PID" in line for line in lines)) + + +@requires_remote_subprocess_debugging() +class TestLiveModeErrors(unittest.TestCase): + """Tests running error commands in the live mode fails gracefully.""" + + class QuitWhenFinishedDisplay(MockDisplay): + def __init__(self, collector): + super().__init__() + self.collector = collector + + def get_input(self): + ch = super().get_input() + if ch != -1: + return ch + # Sampling only stops once the target process has exited, at + # which point the collector is marked finished. Quit then so the + # run can surface the target's stderr. We must not rely on the + # target's pid still being signalable: once it exits it lingers + # as a zombie (it is reaped after sample_live returns), so a + # liveness check would never observe it gone and would hang. + if self.collector.finished: + return ord('q') + return -1 + + def mock_curses_wrapper(self, func): + func(mock.MagicMock()) + + def mock_init_curses_side_effect(self, n_times, mock_self, stdscr): + mock_self.display = self.QuitWhenFinishedDisplay(mock_self) + # Feed non-input events so live mode keeps polling while the target + # process is still running; once it exits the display quits on its own. + for _ in range(n_times): + mock_self.display.simulate_input(-1) + + def test_run_failed_module_live(self): + """Test that running a existing module that fails exits with clean error.""" + + args = [ + "profiling.sampling.cli", "run", "--live", "-m", "test", + "test_asdasd" + ] + + with ( + mock.patch( + 'profiling.sampling.live_collector.collector.LiveStatsCollector.init_curses', + autospec=True, + side_effect=functools.partial(self.mock_init_curses_side_effect, 1000) + ), + mock.patch('curses.wrapper', side_effect=self.mock_curses_wrapper), + mock.patch("sys.argv", args), + mock.patch('sys.stderr', new=io.StringIO()) as fake_stderr + ): + main() + self.assertIn( + 'test test_asdasd crashed -- Traceback (most recent call last):', + fake_stderr.getvalue() + ) + + def test_run_failed_script_live(self): + """Test that running a failing script exits with clean error.""" + script = tempfile.NamedTemporaryFile(suffix=".py") + self.addCleanup(close_and_unlink, script) + script.write(b'1/0\n') + script.seek(0) + + args = ["profiling.sampling.cli", "run", "--live", script.name] + + with ( + mock.patch( + 'profiling.sampling.live_collector.collector.LiveStatsCollector.init_curses', + autospec=True, + side_effect=functools.partial(self.mock_init_curses_side_effect, 200) + ), + mock.patch('curses.wrapper', side_effect=self.mock_curses_wrapper), + mock.patch("sys.argv", args), + mock.patch('sys.stderr', new=io.StringIO()) as fake_stderr + ): + main() + stderr = fake_stderr.getvalue() + self.assertIn('ZeroDivisionError', stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_modes.py b/Lib/test/test_profiling/test_sampling_profiler/test_modes.py new file mode 100644 index 00000000000..0b38fb4ad4b --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_modes.py @@ -0,0 +1,587 @@ +"""Tests for sampling profiler mode filtering (CPU and GIL modes).""" + +import io +import unittest +from unittest import mock + +try: + import _remote_debugging # noqa: F401 + import profiling.sampling + import profiling.sampling.sample + from profiling.sampling.pstats_collector import PstatsCollector + from profiling.sampling.cli import main, _parse_mode + from profiling.sampling.constants import PROFILING_MODE_EXCEPTION + from _remote_debugging import ( + THREAD_STATUS_HAS_GIL, + THREAD_STATUS_ON_CPU, + ) +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from test.support import requires_remote_subprocess_debugging + +from .helpers import test_subprocess +from .mocks import MockFrameInfo, MockInterpreterInfo + + +@requires_remote_subprocess_debugging() +class TestCpuModeFiltering(unittest.TestCase): + """Test CPU mode filtering functionality (--mode=cpu).""" + + def test_mode_validation(self): + """Test that CLI validates mode choices correctly.""" + # Invalid mode choice should raise SystemExit + test_args = [ + "profiling.sampling.cli", + "attach", + "12345", + "--mode", + "invalid", + ] + + with ( + mock.patch("sys.argv", test_args), + mock.patch("sys.stderr", io.StringIO()) as mock_stderr, + self.assertRaises(SystemExit) as cm, + ): + main() + + self.assertEqual(cm.exception.code, 2) # argparse error + error_msg = mock_stderr.getvalue() + self.assertIn("invalid choice", error_msg) + + def test_frames_filtered_with_skip_idle(self): + """Test that frames are actually filtered when skip_idle=True.""" + # Create mock frames with different thread statuses + class MockThreadInfoWithStatus: + def __init__(self, thread_id, frame_info, status): + self.thread_id = thread_id + self.frame_info = frame_info + self.status = status + + # Create test data: active thread (HAS_GIL | ON_CPU), idle thread (neither), and another active thread + ACTIVE_STATUS = ( + THREAD_STATUS_HAS_GIL | THREAD_STATUS_ON_CPU + ) # Has GIL and on CPU + IDLE_STATUS = 0 # Neither has GIL nor on CPU + + test_frames = [ + MockInterpreterInfo( + 0, + [ + MockThreadInfoWithStatus( + 1, + [MockFrameInfo("active1.py", 10, "active_func1")], + ACTIVE_STATUS, + ), + MockThreadInfoWithStatus( + 2, + [MockFrameInfo("idle.py", 20, "idle_func")], + IDLE_STATUS, + ), + MockThreadInfoWithStatus( + 3, + [MockFrameInfo("active2.py", 30, "active_func2")], + ACTIVE_STATUS, + ), + ], + ) + ] + + # Test with skip_idle=True - should only process running threads + collector_skip = PstatsCollector( + sample_interval_usec=1000, skip_idle=True + ) + collector_skip.collect(test_frames) + + # Should only have functions from running threads (status 0) + active1_key = ("active1.py", 10, "active_func1") + active2_key = ("active2.py", 30, "active_func2") + idle_key = ("idle.py", 20, "idle_func") + + self.assertIn(active1_key, collector_skip.result) + self.assertIn(active2_key, collector_skip.result) + self.assertNotIn( + idle_key, collector_skip.result + ) # Idle thread should be filtered out + + # Test with skip_idle=False - should process all threads + collector_no_skip = PstatsCollector( + sample_interval_usec=1000, skip_idle=False + ) + collector_no_skip.collect(test_frames) + + # Should have functions from all threads + self.assertIn(active1_key, collector_no_skip.result) + self.assertIn(active2_key, collector_no_skip.result) + self.assertIn( + idle_key, collector_no_skip.result + ) # Idle thread should be included + + def test_cpu_mode_integration_filtering(self): + """Integration test: CPU mode should only capture active threads, not idle ones.""" + # Script with one mostly-idle thread and one CPU-active thread + cpu_vs_idle_script = """ +import time +import threading + +cpu_ready = threading.Event() + +def idle_worker(): + time.sleep(999999) + +def cpu_active_worker(): + cpu_ready.set() + x = 1 + while True: + x += 1 + +idle_thread = threading.Thread(target=idle_worker) +cpu_thread = threading.Thread(target=cpu_active_worker) +idle_thread.start() +cpu_thread.start() +cpu_ready.wait() +_test_sock.sendall(b"working") +idle_thread.join() +cpu_thread.join() +""" + with test_subprocess(cpu_vs_idle_script, wait_for_working=True) as subproc: + + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=True) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=2.0, + mode=1, # CPU mode + all_threads=True, + ) + collector.print_stats(show_summary=False, mode=1) + + cpu_mode_output = captured_output.getvalue() + + # Test wall-clock mode (mode=0) - should capture both functions + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=2.0, + mode=0, # Wall-clock mode + all_threads=True, + ) + collector.print_stats(show_summary=False) + + wall_mode_output = captured_output.getvalue() + + # Verify both modes captured samples + self.assertIn("Captured", cpu_mode_output) + self.assertIn("samples", cpu_mode_output) + self.assertIn("Captured", wall_mode_output) + self.assertIn("samples", wall_mode_output) + + # CPU mode should strongly favor cpu_active_worker over mostly_idle_worker + self.assertIn("cpu_active_worker", cpu_mode_output) + self.assertNotIn("idle_worker", cpu_mode_output) + + # Wall-clock mode should capture both types of work + self.assertIn("cpu_active_worker", wall_mode_output) + self.assertIn("idle_worker", wall_mode_output) + + def test_cpu_mode_with_no_samples(self): + """Test that CPU mode handles no samples gracefully when no samples are collected.""" + # Mock a collector that returns empty stats + mock_collector = PstatsCollector(sample_interval_usec=5000, skip_idle=True) + mock_collector.stats = {} + + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + mock.patch( + "profiling.sampling.sample.SampleProfiler" + ) as mock_profiler_class, + ): + mock_profiler = mock.MagicMock() + mock_profiler_class.return_value = mock_profiler + + profiling.sampling.sample.sample( + 12345, # dummy PID + mock_collector, + duration_sec=0.5, + mode=1, # CPU mode + all_threads=True, + ) + + mock_collector.print_stats(show_summary=False, mode=1) + + output = captured_output.getvalue() + + # Should see the "No samples were collected" message + self.assertIn("No samples were collected", output) + self.assertIn("CPU mode", output) + + +@requires_remote_subprocess_debugging() +class TestGilModeFiltering(unittest.TestCase): + """Test GIL mode filtering functionality (--mode=gil).""" + + def test_gil_mode_validation(self): + """Test that CLI accepts gil mode choice correctly.""" + + test_args = [ + "profiling.sampling.cli", + "attach", + "12345", + "--mode", + "gil", + ] + + with ( + mock.patch("sys.argv", test_args), + mock.patch("profiling.sampling.cli._is_process_running", return_value=True), + mock.patch("profiling.sampling.cli.sample") as mock_sample, + ): + try: + main() + except (SystemExit, OSError, RuntimeError): + pass # Expected due to invalid PID + + # Should have attempted to call sample with mode=2 (GIL mode) + mock_sample.assert_called_once() + call_args = mock_sample.call_args + # Check the mode parameter (should be in kwargs) + self.assertEqual(call_args.kwargs.get("mode"), 2) # PROFILING_MODE_GIL + + def test_gil_mode_sample_function_call(self): + """Test that sample() function correctly uses GIL mode.""" + with ( + mock.patch( + "profiling.sampling.sample.SampleProfiler" + ) as mock_profiler, + ): + # Mock the profiler instance + mock_instance = mock.Mock() + mock_profiler.return_value = mock_instance + + # Create a real collector instance + collector = PstatsCollector(sample_interval_usec=1000, skip_idle=True) + + # Call sample with GIL mode + profiling.sampling.sample.sample( + 12345, + collector, + mode=2, # PROFILING_MODE_GIL + duration_sec=1, + ) + + # Verify SampleProfiler was created with correct mode + mock_profiler.assert_called_once() + call_args = mock_profiler.call_args + self.assertEqual(call_args[1]["mode"], 2) # mode parameter + + # Verify profiler.sample was called + mock_instance.sample.assert_called_once() + + def test_gil_mode_cli_argument_parsing(self): + """Test CLI argument parsing for GIL mode with various options.""" + + test_args = [ + "profiling.sampling.cli", + "attach", + "12345", + "--mode", + "gil", + "-r", + "2000", + "-d", + "5", + ] + + with ( + mock.patch("sys.argv", test_args), + mock.patch("profiling.sampling.cli._is_process_running", return_value=True), + mock.patch("profiling.sampling.cli.sample") as mock_sample, + ): + try: + main() + except (SystemExit, OSError, RuntimeError): + pass # Expected due to invalid PID + + # Verify all arguments were parsed correctly + mock_sample.assert_called_once() + call_args = mock_sample.call_args + self.assertEqual(call_args.kwargs.get("mode"), 2) # GIL mode + self.assertEqual(call_args.kwargs.get("duration_sec"), 5) + + def test_gil_mode_integration_behavior(self): + """Integration test: GIL mode should capture GIL-holding threads.""" + # Create a test script with GIL-releasing operations + gil_test_script = """ +import time +import threading + +gil_ready = threading.Event() + +def gil_releasing_work(): + time.sleep(999999) + +def gil_holding_work(): + gil_ready.set() + x = 1 + while True: + x += 1 + +idle_thread = threading.Thread(target=gil_releasing_work) +cpu_thread = threading.Thread(target=gil_holding_work) +idle_thread.start() +cpu_thread.start() +gil_ready.wait() +_test_sock.sendall(b"working") +idle_thread.join() +cpu_thread.join() +""" + with test_subprocess(gil_test_script, wait_for_working=True) as subproc: + + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=True) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=2.0, + mode=2, # GIL mode + all_threads=True, + ) + collector.print_stats(show_summary=False) + + gil_mode_output = captured_output.getvalue() + + # Test wall-clock mode for comparison + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=0.5, + mode=0, # Wall-clock mode + all_threads=True, + ) + collector.print_stats(show_summary=False) + + wall_mode_output = captured_output.getvalue() + + # GIL mode should primarily capture GIL-holding work + # (Note: actual behavior depends on threading implementation) + self.assertIn("gil_holding_work", gil_mode_output) + + # Wall-clock mode should capture both types of work + self.assertIn("gil_holding_work", wall_mode_output) + + def test_mode_constants_are_defined(self): + """Test that all profiling mode constants are properly defined.""" + self.assertEqual(profiling.sampling.sample.PROFILING_MODE_WALL, 0) + self.assertEqual(profiling.sampling.sample.PROFILING_MODE_CPU, 1) + self.assertEqual(profiling.sampling.sample.PROFILING_MODE_GIL, 2) + + def test_parse_mode_function(self): + """Test the _parse_mode function with all valid modes.""" + self.assertEqual(_parse_mode("wall"), 0) + self.assertEqual(_parse_mode("cpu"), 1) + self.assertEqual(_parse_mode("gil"), 2) + self.assertEqual(_parse_mode("exception"), 4) + + # Test invalid mode raises KeyError + with self.assertRaises(KeyError): + _parse_mode("invalid") + + +@requires_remote_subprocess_debugging() +class TestExceptionModeFiltering(unittest.TestCase): + """Test exception mode filtering functionality (--mode=exception).""" + + def test_exception_mode_validation(self): + """Test that CLI accepts exception mode choice correctly.""" + + test_args = [ + "profiling.sampling.cli", + "attach", + "12345", + "--mode", + "exception", + ] + + with ( + mock.patch("sys.argv", test_args), + mock.patch("profiling.sampling.cli._is_process_running", return_value=True), + mock.patch("profiling.sampling.cli.sample") as mock_sample, + ): + try: + main() + except (SystemExit, OSError, RuntimeError): + pass # Expected due to invalid PID + + # Should have attempted to call sample with mode=4 (exception mode) + mock_sample.assert_called_once() + call_args = mock_sample.call_args + # Check the mode parameter (should be in kwargs) + self.assertEqual(call_args.kwargs.get("mode"), 4) # PROFILING_MODE_EXCEPTION + + def test_exception_mode_sample_function_call(self): + """Test that sample() function correctly uses exception mode.""" + with ( + mock.patch( + "profiling.sampling.sample.SampleProfiler" + ) as mock_profiler, + ): + # Mock the profiler instance + mock_instance = mock.Mock() + mock_profiler.return_value = mock_instance + + # Create a real collector instance + collector = PstatsCollector(sample_interval_usec=1000, skip_idle=True) + + # Call sample with exception mode + profiling.sampling.sample.sample( + 12345, + collector, + mode=4, # PROFILING_MODE_EXCEPTION + duration_sec=1, + ) + + # Verify SampleProfiler was created with correct mode + mock_profiler.assert_called_once() + call_args = mock_profiler.call_args + self.assertEqual(call_args[1]["mode"], 4) # mode parameter + + # Verify profiler.sample was called + mock_instance.sample.assert_called_once() + + def test_exception_mode_cli_argument_parsing(self): + """Test CLI argument parsing for exception mode with various options.""" + + test_args = [ + "profiling.sampling.cli", + "attach", + "12345", + "--mode", + "exception", + "-r", + "2000", + "-d", + "5", + ] + + with ( + mock.patch("sys.argv", test_args), + mock.patch("profiling.sampling.cli._is_process_running", return_value=True), + mock.patch("profiling.sampling.cli.sample") as mock_sample, + ): + try: + main() + except (SystemExit, OSError, RuntimeError): + pass # Expected due to invalid PID + + # Verify all arguments were parsed correctly + mock_sample.assert_called_once() + call_args = mock_sample.call_args + self.assertEqual(call_args.kwargs.get("mode"), 4) # exception mode + self.assertEqual(call_args.kwargs.get("duration_sec"), 5) + + def test_exception_mode_constants_are_defined(self): + """Test that exception mode constant is properly defined.""" + self.assertEqual(PROFILING_MODE_EXCEPTION, 4) + + def test_exception_mode_integration_filtering(self): + """Integration test: Exception mode should only capture threads with active exceptions.""" + # Script with one thread handling an exception and one normal thread + exception_vs_normal_script = """ +import time +import threading + +exception_ready = threading.Event() + +def normal_worker(): + x = 0 + while True: + x += 1 + +def exception_handling_worker(): + try: + raise ValueError("test exception") + except ValueError: + # Signal AFTER entering except block, then do CPU work + exception_ready.set() + x = 0 + while True: + x += 1 + +normal_thread = threading.Thread(target=normal_worker) +exception_thread = threading.Thread(target=exception_handling_worker) +normal_thread.start() +exception_thread.start() +exception_ready.wait() +_test_sock.sendall(b"working") +normal_thread.join() +exception_thread.join() +""" + with test_subprocess(exception_vs_normal_script, wait_for_working=True) as subproc: + + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=True) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=2.0, + mode=4, # Exception mode + all_threads=True, + ) + collector.print_stats(show_summary=False, mode=4) + + exception_mode_output = captured_output.getvalue() + + # Test wall-clock mode (mode=0) - should capture both functions + with ( + io.StringIO() as captured_output, + mock.patch("sys.stdout", captured_output), + ): + collector = PstatsCollector(sample_interval_usec=5000, skip_idle=False) + profiling.sampling.sample.sample( + subproc.process.pid, + collector, + duration_sec=2.0, + mode=0, # Wall-clock mode + all_threads=True, + ) + collector.print_stats(show_summary=False) + + wall_mode_output = captured_output.getvalue() + + # Verify both modes captured samples + self.assertIn("Captured", exception_mode_output) + self.assertIn("samples", exception_mode_output) + self.assertIn("Captured", wall_mode_output) + self.assertIn("samples", wall_mode_output) + + # Exception mode should strongly favor exception_handling_worker over normal_worker + self.assertIn("exception_handling_worker", exception_mode_output) + self.assertNotIn("normal_worker", exception_mode_output) + + # Wall-clock mode should capture both types of work + self.assertIn("exception_handling_worker", wall_mode_output) + self.assertIn("normal_worker", wall_mode_output) diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_profiler.py b/Lib/test/test_profiling/test_sampling_profiler/test_profiler.py new file mode 100644 index 00000000000..b1fbfb5a0de --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_profiler.py @@ -0,0 +1,888 @@ +"""Tests for sampling profiler core functionality.""" + +import contextlib +import io +import re +import types +from unittest import mock +import unittest + +try: + import _remote_debugging # noqa: F401 + from profiling.sampling.constants import PROFILING_MODE_ALL, PROFILING_MODE_WALL + from profiling.sampling.sample import SampleProfiler, dump_stack + from profiling.sampling.pstats_collector import PstatsCollector +except ImportError: + raise unittest.SkipTest( + "Test only runs when _remote_debugging is available" + ) + +from test.support import force_colorized, force_not_colorized_test_class + + +def print_sampled_stats(stats, sort=-1, limit=None, show_summary=True, sample_interval_usec=100): + """Helper function to maintain compatibility with old test API. + + This wraps the new PstatsCollector.print_stats() API to work with the + existing test infrastructure. + """ + # Create a mock collector that populates stats correctly + collector = PstatsCollector(sample_interval_usec=sample_interval_usec) + + # Override create_stats to populate self.stats with the provided stats + def mock_create_stats(): + collector.stats = stats.stats + collector.create_stats = mock_create_stats + + # Call the new print_stats method + collector.print_stats(sort=sort, limit=limit, show_summary=show_summary) + + +class TestSampleProfiler(unittest.TestCase): + """Test the SampleProfiler class.""" + + def test_sample_profiler_initialization(self): + """Test SampleProfiler initialization with various parameters.""" + + # Mock RemoteUnwinder to avoid permission issues + with mock.patch( + "_remote_debugging.RemoteUnwinder" + ) as mock_unwinder_class: + mock_unwinder_class.return_value = mock.MagicMock() + + # Test basic initialization + profiler = SampleProfiler( + pid=12345, sample_interval_usec=1000, all_threads=False + ) + self.assertEqual(profiler.pid, 12345) + self.assertEqual(profiler.sample_interval_usec, 1000) + self.assertEqual(profiler.all_threads, False) + + # Test with all_threads=True + profiler = SampleProfiler( + pid=54321, sample_interval_usec=5000, all_threads=True + ) + self.assertEqual(profiler.pid, 54321) + self.assertEqual(profiler.sample_interval_usec, 5000) + self.assertEqual(profiler.all_threads, True) + + @staticmethod + @contextlib.contextmanager + def _patched_unwinder(): + """Yield a namespace exposing the mock unwinder ``instance`` and ``cls``.""" + instance = mock.MagicMock() + with mock.patch( + "_remote_debugging.RemoteUnwinder", return_value=instance + ) as cls: + yield types.SimpleNamespace(instance=instance, cls=cls) + + def test_dump_stack_uses_single_unwinder_snapshot(self): + stack_frames = [mock.sentinel.stack_frames] + with self._patched_unwinder() as u: + u.instance.get_stack_trace.return_value = stack_frames + result = dump_stack(12345) + + self.assertIs(result, stack_frames) + self.assertEqual(u.cls.call_args.kwargs["mode"], PROFILING_MODE_ALL) + u.instance.get_stack_trace.assert_called_once_with() + + def test_dump_stack_returns_empty_async_snapshot(self): + with self._patched_unwinder() as u: + u.instance.get_async_stack_trace.return_value = [] + result = dump_stack(12345, async_aware="running") + + self.assertEqual(result, []) + u.instance.get_async_stack_trace.assert_called_once_with() + u.instance.get_stack_trace.assert_not_called() + + def test_dump_stack_async_all_uses_all_awaited_by(self): + stack_frames = [mock.sentinel.awaited_info] + with self._patched_unwinder() as u: + u.instance.get_all_awaited_by.return_value = stack_frames + result = dump_stack(12345, async_aware="all") + + self.assertIs(result, stack_frames) + u.instance.get_all_awaited_by.assert_called_once_with() + u.instance.get_stack_trace.assert_not_called() + u.instance.get_async_stack_trace.assert_not_called() + + def test_dump_stack_passes_unwinder_options(self): + with self._patched_unwinder() as u: + u.instance.get_stack_trace.return_value = [] + dump_stack( + 12345, + all_threads=True, + native=True, + gc=False, + opcodes=True, + ) + + call_kwargs = u.cls.call_args.kwargs + self.assertTrue(call_kwargs["all_threads"]) + self.assertEqual(call_kwargs["mode"], PROFILING_MODE_ALL) + self.assertTrue(call_kwargs["native"]) + self.assertFalse(call_kwargs["gc"]) + self.assertTrue(call_kwargs["opcodes"]) + self.assertFalse(call_kwargs["skip_non_matching_threads"]) + self.assertTrue(call_kwargs["cache_frames"]) + + def test_dump_stack_wall_mode_skips_non_matching_threads(self): + with self._patched_unwinder() as u: + u.instance.get_stack_trace.return_value = [] + dump_stack(12345, mode=PROFILING_MODE_WALL) + + self.assertTrue(u.cls.call_args.kwargs["skip_non_matching_threads"]) + + def test_dump_stack_blocking_pauses_and_resumes_threads(self): + stack_frames = [mock.sentinel.stack_frames] + with self._patched_unwinder() as u: + u.instance.get_stack_trace.return_value = stack_frames + result = dump_stack(12345, blocking=True) + + self.assertIs(result, stack_frames) + u.instance.pause_threads.assert_called_once_with() + u.instance.resume_threads.assert_called_once_with() + + def test_dump_stack_blocking_resumes_threads_after_failure(self): + with self._patched_unwinder() as u: + u.instance.get_stack_trace.side_effect = RuntimeError("boom") + with self.assertRaises(RuntimeError): + dump_stack(12345, blocking=True) + + u.instance.pause_threads.assert_called_once_with() + u.instance.resume_threads.assert_called_once_with() + + def test_sample_profiler_sample_method_timing(self): + """Test that the sample method respects duration and handles timing correctly.""" + + # Mock the unwinder to avoid needing a real process + mock_unwinder = mock.MagicMock() + mock_unwinder.get_stack_trace.return_value = [ + ( + 1, + [ + mock.MagicMock( + filename="test.py", lineno=10, funcname="test_func" + ) + ], + ) + ] + + with mock.patch( + "_remote_debugging.RemoteUnwinder" + ) as mock_unwinder_class: + mock_unwinder_class.return_value = mock_unwinder + + profiler = SampleProfiler( + pid=12345, sample_interval_usec=100000, all_threads=False + ) # 100ms interval + + # Mock collector + mock_collector = mock.MagicMock() + + # Mock time to control the sampling loop + start_time = 1000.0 + times = [ + start_time + i * 0.1 for i in range(12) + ] # 0, 0.1, 0.2, ..., 1.1 seconds + + with mock.patch("time.perf_counter", side_effect=times): + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + profiler.sample(mock_collector, duration_sec=1) + + result = output.getvalue() + + # Should have captured approximately 10 samples (1 second / 0.1 second interval) + self.assertIn("Captured", result) + self.assertIn("samples", result) + + # Verify collector was called multiple times + total_weight = sum( + len(c.kwargs.get("timestamps_us") or [None]) + for c in mock_collector.collect.call_args_list + ) + self.assertGreaterEqual(total_weight, 5) + self.assertLessEqual(total_weight, 11) + + def test_sample_profiler_does_not_buffer_non_aggregating_collectors(self): + """Test that non-aggregating collectors get each sample immediately.""" + + stack_frames = [mock.sentinel.stack_frames] + mock_collector = mock.MagicMock() + mock_collector.aggregating = False + + with self._patched_unwinder() as u: + u.instance.get_stack_trace.return_value = stack_frames + + manager = mock.Mock() + manager.attach_mock(u.instance.get_stack_trace, "unwind") + manager.attach_mock(mock_collector.collect, "collect") + + profiler = SampleProfiler( + pid=12345, sample_interval_usec=10000, all_threads=False + ) + + times = [0.0, 0.01, 0.011, 0.02, 0.03] + with mock.patch("time.perf_counter", side_effect=times): + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + profiler.sample(mock_collector, duration_sec=0.025) + + self.assertEqual( + manager.mock_calls, + [ + mock.call.unwind(), + mock.call.collect(stack_frames), + mock.call.unwind(), + mock.call.collect(stack_frames), + ], + ) + + def test_sample_profiler_flushes_aggregated_batches_at_limit(self): + """Test that aggregating collectors flush after MAX_PENDING_SAMPLES samples.""" + + stack_frames = [mock.sentinel.stack_frames] + mock_collector = mock.MagicMock() + mock_collector.aggregating = True + + with self._patched_unwinder() as u: + u.instance.get_stack_trace.return_value = stack_frames + + profiler = SampleProfiler( + pid=12345, sample_interval_usec=10000, all_threads=False + ) + + times = [ + 0.0, + 0.01, 0.011, + 0.02, 0.021, + 0.03, 0.031, + 0.04, 0.041, + 0.05, 0.051, + ] + with mock.patch("profiling.sampling.sample.MAX_PENDING_SAMPLES", 2): + with mock.patch("time.perf_counter", side_effect=times): + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + profiler.sample(mock_collector, duration_sec=0.045) + + batches = [ + (c.args[0], len(c.kwargs["timestamps_us"])) + for c in mock_collector.collect.call_args_list + ] + self.assertEqual( + batches, + [(stack_frames, 2), (stack_frames, 2), (stack_frames, 1)], + ) + + def test_sample_profiler_error_handling(self): + """Test that the sample method handles errors gracefully.""" + + # Mock unwinder that raises errors + mock_unwinder = mock.MagicMock() + error_sequence = [ + RuntimeError("Process died"), + [ + ( + 1, + [ + mock.MagicMock( + filename="test.py", lineno=10, funcname="test_func" + ) + ], + ) + ], + UnicodeDecodeError("utf-8", b"", 0, 1, "invalid"), + [ + ( + 1, + [ + mock.MagicMock( + filename="test.py", + lineno=20, + funcname="test_func2", + ) + ], + ) + ], + OSError("Permission denied"), + ] + mock_unwinder.get_stack_trace.side_effect = error_sequence + + with mock.patch( + "_remote_debugging.RemoteUnwinder" + ) as mock_unwinder_class: + mock_unwinder_class.return_value = mock_unwinder + + profiler = SampleProfiler( + pid=12345, sample_interval_usec=10000, all_threads=False + ) + + mock_collector = mock.MagicMock() + + # Control timing to run exactly 5 samples + times = [0.0, 0.01, 0.02, 0.03, 0.04, 0.05, 0.06] + + with mock.patch("time.perf_counter", side_effect=times): + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + profiler.sample(mock_collector, duration_sec=0.05) + + result = output.getvalue() + + # Should report error rate + self.assertIn("Error rate:", result) + self.assertIn("%", result) + + # Collector should have been called only for successful samples (should be > 0) + self.assertGreater(mock_collector.collect.call_count, 0) + self.assertLessEqual(mock_collector.collect.call_count, 3) + + def test_sample_profiler_missed_samples_warning(self): + """Test that the profiler warns about missed samples when sampling is too slow.""" + + mock_unwinder = mock.MagicMock() + mock_unwinder.get_stack_trace.return_value = [ + ( + 1, + [ + mock.MagicMock( + filename="test.py", lineno=10, funcname="test_func" + ) + ], + ) + ] + + with mock.patch( + "_remote_debugging.RemoteUnwinder" + ) as mock_unwinder_class: + mock_unwinder_class.return_value = mock_unwinder + + # Use very short interval that we'll miss + profiler = SampleProfiler( + pid=12345, sample_interval_usec=1000, all_threads=False + ) # 1ms interval + + mock_collector = mock.MagicMock() + + # Simulate slow sampling where we miss many samples + times = [ + 0.0, + 0.1, + 0.2, + 0.3, + 0.4, + 0.5, + 0.6, + 0.7, + ] # Extra time points to avoid StopIteration + + with mock.patch("time.perf_counter", side_effect=times): + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + profiler.sample(mock_collector, duration_sec=0.5) + + result = output.getvalue() + + # Should warn about missed samples + self.assertIn("Warning: missed", result) + self.assertIn("samples from the expected total", result) + + def test_sample_profiler_keyboard_interrupt(self): + mock_unwinder = mock.MagicMock() + mock_unwinder.get_stack_trace.side_effect = [ + [ + ( + 1, + [ + mock.MagicMock( + filename="test.py", lineno=10, funcname="test_func" + ) + ], + ) + ], + KeyboardInterrupt(), + ] + + with mock.patch( + "_remote_debugging.RemoteUnwinder" + ) as mock_unwinder_class: + mock_unwinder_class.return_value = mock_unwinder + profiler = SampleProfiler( + pid=12345, sample_interval_usec=10000, all_threads=False + ) + mock_collector = mock.MagicMock() + times = [0.0, 0.01, 0.02, 0.03, 0.04] + with mock.patch("time.perf_counter", side_effect=times): + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + try: + profiler.sample(mock_collector, duration_sec=1.0) + except KeyboardInterrupt: + self.fail( + "KeyboardInterrupt was not handled by the profiler" + ) + result = output.getvalue() + self.assertIn("Interrupted by user.", result) + self.assertIn("Captured", result) + self.assertIn("samples", result) + self.assertNotIn("Warning: missed", result) + + +@force_not_colorized_test_class +class TestPrintSampledStats(unittest.TestCase): + """Test the print_sampled_stats function.""" + + def setUp(self): + """Set up test data.""" + # Mock stats data + self.mock_stats = mock.MagicMock() + self.mock_stats.stats = { + ("file1.py", 10, "func1"): ( + 100, + 100, + 0.5, + 0.5, + {}, + ), # cc, nc, tt, ct, callers + ("file2.py", 20, "func2"): (50, 50, 0.25, 0.3, {}), + ("file3.py", 30, "func3"): (200, 200, 1.5, 2.0, {}), + ("file4.py", 40, "func4"): ( + 10, + 10, + 0.001, + 0.001, + {}, + ), # millisecond range + ("file5.py", 50, "func5"): ( + 5, + 5, + 0.000001, + 0.000002, + {}, + ), # microsecond range + } + + def test_print_sampled_stats_basic(self): + """Test basic print_sampled_stats functionality.""" + + # Capture output + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats(self.mock_stats, sample_interval_usec=100) + + result = output.getvalue() + + # Check header is present + self.assertIn("Profile Stats:", result) + self.assertIn("nsamples", result) + self.assertIn("tottime", result) + self.assertIn("cumtime", result) + + # Check functions are present + self.assertIn("func1", result) + self.assertIn("func2", result) + self.assertIn("func3", result) + self.assertNotIn("\x1b[", result) + + @force_colorized + def test_print_sampled_stats_colorized(self): + with io.StringIO() as output, mock.patch("sys.stdout", output): + print_sampled_stats(self.mock_stats) + result = output.getvalue() + + self.assertIn("\x1b[1;34mProfile Stats:", result) + + def test_print_sampled_stats_sorting(self): + """Test different sorting options.""" + + # Test sort by calls + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + self.mock_stats, sort=0, sample_interval_usec=100 + ) + + result = output.getvalue() + lines = result.strip().split("\n") + + # Find the data lines (skip header) + data_lines = [l for l in lines if "file" in l and ".py" in l] + # func3 should be first (200 calls) + self.assertIn("func3", data_lines[0]) + + # Test sort by time + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + self.mock_stats, sort=1, sample_interval_usec=100 + ) + + result = output.getvalue() + lines = result.strip().split("\n") + + data_lines = [l for l in lines if "file" in l and ".py" in l] + # func3 should be first (1.5s time) + self.assertIn("func3", data_lines[0]) + + def test_print_sampled_stats_limit(self): + """Test limiting output rows.""" + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + self.mock_stats, limit=2, sample_interval_usec=100 + ) + + result = output.getvalue() + + # Count function entries in the main stats section (not in summary) + lines = result.split("\n") + # Find where the main stats section ends (before summary) + main_section_lines = [] + for line in lines: + if "Summary of Interesting Functions:" in line: + break + main_section_lines.append(line) + + # Count function entries only in main section + func_count = sum( + 1 + for line in main_section_lines + if "func" in line and ".py" in line + ) + self.assertEqual(func_count, 2) + + def test_print_sampled_stats_time_units(self): + """Test proper time unit selection.""" + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats(self.mock_stats, sample_interval_usec=100) + + result = output.getvalue() + + # Should use seconds for the header since max time is > 1s + self.assertIn("tottime (s)", result) + self.assertIn("cumtime (s)", result) + + # Test with only microsecond-range times + micro_stats = mock.MagicMock() + micro_stats.stats = { + ("file1.py", 10, "func1"): (100, 100, 0.000005, 0.000010, {}), + } + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats(micro_stats, sample_interval_usec=100) + + result = output.getvalue() + + # Should use microseconds + self.assertIn("tottime (μs)", result) + self.assertIn("cumtime (μs)", result) + + def test_print_sampled_stats_summary(self): + """Test summary section generation.""" + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + self.mock_stats, + show_summary=True, + sample_interval_usec=100, + ) + + result = output.getvalue() + + # Check summary sections are present + self.assertIn("Summary of Interesting Functions:", result) + self.assertIn( + "Functions with Highest Direct/Cumulative Ratio (Hot Spots):", + result, + ) + self.assertIn( + "Functions with Highest Call Frequency (Indirect Calls):", result + ) + self.assertIn( + "Functions with Highest Call Magnification (Cumulative/Direct):", + result, + ) + + def test_print_sampled_stats_no_summary(self): + """Test disabling summary output.""" + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + self.mock_stats, + show_summary=False, + sample_interval_usec=100, + ) + + result = output.getvalue() + + # Summary should not be present + self.assertNotIn("Summary of Interesting Functions:", result) + + def test_print_sampled_stats_empty_stats(self): + """Test with empty stats.""" + + empty_stats = mock.MagicMock() + empty_stats.stats = {} + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats(empty_stats, sample_interval_usec=100) + + result = output.getvalue() + + # Should print message about no samples + self.assertIn("No samples were collected.", result) + + def test_print_sampled_stats_sample_percentage_sorting(self): + """Test sample percentage sorting options.""" + + # Add a function with high sample percentage (more direct calls than func3's 200) + self.mock_stats.stats[("expensive.py", 60, "expensive_func")] = ( + 300, # direct calls (higher than func3's 200) + 300, # cumulative calls + 1.0, # total time + 1.0, # cumulative time + {}, + ) + + # Test sort by sample percentage + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + self.mock_stats, sort=3, sample_interval_usec=100 + ) # sample percentage + + result = output.getvalue() + lines = result.strip().split("\n") + + data_lines = [l for l in lines if ".py" in l and "func" in l] + # expensive_func should be first (highest sample percentage) + self.assertIn("expensive_func", data_lines[0]) + + def test_print_sampled_stats_with_recursive_calls(self): + """Test print_sampled_stats with recursive calls where nc != cc.""" + + # Create stats with recursive calls (nc != cc) + recursive_stats = mock.MagicMock() + recursive_stats.stats = { + # (direct_calls, cumulative_calls, tt, ct, callers) - recursive function + ("recursive.py", 10, "factorial"): ( + 5, # direct_calls + 10, # cumulative_calls (appears more times in stack due to recursion) + 0.5, + 0.6, + {}, + ), + ("normal.py", 20, "normal_func"): ( + 3, # direct_calls + 3, # cumulative_calls (same as direct for non-recursive) + 0.2, + 0.2, + {}, + ), + } + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats(recursive_stats, sample_interval_usec=100) + + result = output.getvalue() + + # Should display recursive calls as "5/10" format + self.assertIn("5/10", result) # nc/cc format for recursive calls + self.assertIn("3", result) # just nc for non-recursive calls + self.assertIn("factorial", result) + self.assertIn("normal_func", result) + + def test_print_sampled_stats_with_zero_call_counts(self): + """Test print_sampled_stats with zero call counts to trigger division protection.""" + + # Create stats with zero call counts + zero_stats = mock.MagicMock() + zero_stats.stats = { + ("file.py", 10, "zero_calls"): (0, 0, 0.0, 0.0, {}), # Zero calls + ("file.py", 20, "normal_func"): ( + 5, + 5, + 0.1, + 0.1, + {}, + ), # Normal function + } + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats(zero_stats, sample_interval_usec=100) + + result = output.getvalue() + + # Should handle zero call counts gracefully + self.assertIn("zero_calls", result) + self.assertIn("zero_calls", result) + self.assertIn("normal_func", result) + + def test_print_sampled_stats_sort_by_name(self): + """Test sort by function name option.""" + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + self.mock_stats, sort=-1, sample_interval_usec=100 + ) # sort by name + + result = output.getvalue() + lines = result.strip().split("\n") + + # Find the data lines (skip header and summary) + # Data lines start with whitespace and numbers, and contain filename:lineno(function) + data_lines = [] + for line in lines: + # Skip header lines and summary sections + if ( + line.startswith(" ") + and "(" in line + and ")" in line + and not line.startswith( + " 1." + ) # Skip summary lines that start with times + and not line.startswith( + " 0." + ) # Skip summary lines that start with times + and not "per call" in line # Skip summary lines + and not "calls" in line # Skip summary lines + and not "total time" in line # Skip summary lines + and not "cumulative time" in line + and not "filename:lineno(function)" in line # Skip header line + ): # Skip summary lines + data_lines.append(line) + + # Extract just the function names for comparison + func_names = [] + + for line in data_lines: + # Function name is between the last ( and ), accounting for ANSI color codes + match = re.search(r"\(([^)]+)\)$", line) + if match: + func_name = match.group(1) + # Remove ANSI color codes + func_name = re.sub(r"\x1b\[[0-9;]*m", "", func_name) + func_names.append(func_name) + + # Verify we extracted function names and they are sorted + self.assertGreater( + len(func_names), 0, "Should have extracted some function names" + ) + self.assertEqual( + func_names, + sorted(func_names), + f"Function names {func_names} should be sorted alphabetically", + ) + + def test_print_sampled_stats_with_zero_time_functions(self): + """Test summary sections with functions that have zero time.""" + + # Create stats with zero-time functions + zero_time_stats = mock.MagicMock() + zero_time_stats.stats = { + ("file1.py", 10, "zero_time_func"): ( + 5, + 5, + 0.0, + 0.0, + {}, + ), # Zero time + ("file2.py", 20, "normal_func"): ( + 3, + 3, + 0.1, + 0.1, + {}, + ), # Normal time + } + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + zero_time_stats, + show_summary=True, + sample_interval_usec=100, + ) + + result = output.getvalue() + + # Should handle zero-time functions gracefully in summary + self.assertIn("Summary of Interesting Functions:", result) + self.assertIn("zero_time_func", result) + self.assertIn("normal_func", result) + + def test_print_sampled_stats_with_malformed_qualified_names(self): + """Test summary generation with function names that don't contain colons.""" + + # Create stats with function names that would create malformed qualified names + malformed_stats = mock.MagicMock() + malformed_stats.stats = { + # Function name without clear module separation + ("no_colon_func", 10, "func"): (3, 3, 0.1, 0.1, {}), + ("", 20, "empty_filename_func"): (2, 2, 0.05, 0.05, {}), + ("normal.py", 30, "normal_func"): (5, 5, 0.2, 0.2, {}), + } + + with io.StringIO() as output: + with mock.patch("sys.stdout", output): + print_sampled_stats( + malformed_stats, + show_summary=True, + sample_interval_usec=100, + ) + + result = output.getvalue() + + # Should handle malformed names gracefully in summary aggregation + self.assertIn("Summary of Interesting Functions:", result) + # All function names should appear somewhere in the output + self.assertIn("func", result) + self.assertIn("empty_filename_func", result) + self.assertIn("normal_func", result) + + def test_print_sampled_stats_with_recursive_call_stats_creation(self): + """Test create_stats with recursive call data to trigger total_rec_calls branch.""" + collector = PstatsCollector(sample_interval_usec=1000000) # 1 second + + # Simulate recursive function data where total_rec_calls would be set + # We need to manually manipulate the collector result to test this branch + collector.result = { + ("recursive.py", 10, "factorial"): { + "total_rec_calls": 3, # Non-zero recursive calls + "direct_calls": 5, + "cumulative_calls": 10, + }, + ("normal.py", 20, "normal_func"): { + "total_rec_calls": 0, # Zero recursive calls + "direct_calls": 2, + "cumulative_calls": 5, + }, + } + + collector.create_stats() + + # Check that recursive calls are handled differently from non-recursive + factorial_stats = collector.stats[("recursive.py", 10, "factorial")] + normal_stats = collector.stats[("normal.py", 20, "normal_func")] + + # factorial should use cumulative_calls (10) as nc + self.assertEqual( + factorial_stats[1], 10 + ) # nc should be cumulative_calls + self.assertEqual(factorial_stats[0], 5) # cc should be direct_calls + + # normal_func should use cumulative_calls as nc + self.assertEqual(normal_stats[1], 5) # nc should be cumulative_calls + self.assertEqual(normal_stats[0], 2) # cc should be direct_calls diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_sync_coordinator.py b/Lib/test/test_profiling/test_sampling_profiler/test_sync_coordinator.py new file mode 100644 index 00000000000..936c01e206f --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_sync_coordinator.py @@ -0,0 +1,113 @@ +"""Tests for the sampling profiler's synchronization coordinator.""" + +import os +import socket +import subprocess +import sys +import tempfile +import unittest + +from test.support import SHORT_TIMEOUT, os_helper, requires_subprocess + + +@requires_subprocess() +class TestSyncCoordinatorScriptExecution(unittest.TestCase): + """Tests for how the coordinator executes a target script.""" + + def run_coordinator(self, cwd, target, *target_args): + """Execute *target* from *cwd* with the sync coordinator. + + Returns the ``(stdout, stderr)`` captured from the coordinator. + """ + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server: + server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + server.bind(("127.0.0.1", 0)) + server.listen(1) + server.settimeout(SHORT_TIMEOUT) + port = server.getsockname()[1] + + cmd = ( + sys.executable, + "-m", + "profiling.sampling._sync_coordinator", + str(port), + cwd, + target, + ) + tuple(target_args) + process = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True, + ) + try: + conn, _ = server.accept() + with conn: + # _signal_readiness() sends b"ready" before running target. + self.assertEqual(conn.recv(64), b"ready") + stdout, stderr = process.communicate(timeout=SHORT_TIMEOUT) + finally: + if process.poll() is None: + process.kill() + process.wait() + return stdout, stderr + + def test_script_directory_on_sys_path(self): + # gh-158540: The coordinator must put the directory containing the + # script (not the working directory) on sys.path, matching + # ``python script.py``, so that modules next to the script can be + # imported even when the coordinator runs from another directory. + with tempfile.TemporaryDirectory() as tmpdir: + script_dir = os.path.join(tmpdir, "sub") + os.mkdir(script_dir) + with open(os.path.join(script_dir, "helper.py"), "w") as f: + f.write("message = 'helper imported'\n") + with open(os.path.join(script_dir, "where.py"), "w") as f: + f.write( + "import os\n" + "import sys\n" + "print('PATH0:', os.path.realpath(sys.path[0]))\n" + "import helper\n" + "print('HELPER:', helper.message)\n" + ) + + stdout, stderr = self.run_coordinator( + tmpdir, os.path.join("sub", "where.py") + ) + + self.assertNotIn("ModuleNotFoundError", stderr) + self.assertIn("HELPER: helper imported", stdout) + self.assertIn(f"PATH0: {os.path.realpath(script_dir)}", stdout) + + @os_helper.skip_unless_symlink + def test_symlinked_script_uses_real_directory(self): + # gh-158540: ``python script.py`` resolves symlinks when computing + # sys.path[0], so a symlinked script must import modules next to the + # real script, not next to the link. + with tempfile.TemporaryDirectory() as tmpdir: + script_dir = os.path.join(tmpdir, "sub") + os.mkdir(script_dir) + with open(os.path.join(script_dir, "helper.py"), "w") as f: + f.write("message = 'helper imported'\n") + with open(os.path.join(script_dir, "where.py"), "w") as f: + f.write( + "import os\n" + "import sys\n" + "print('PATH0:', os.path.realpath(sys.path[0]))\n" + "import helper\n" + "print('HELPER:', helper.message)\n" + ) + os.symlink( + os.path.join("sub", "where.py"), + os.path.join(tmpdir, "link.py"), + ) + + stdout, stderr = self.run_coordinator(tmpdir, "link.py") + + self.assertNotIn("ModuleNotFoundError", stderr) + self.assertIn("HELPER: helper imported", stdout) + self.assertIn(f"PATH0: {os.path.realpath(script_dir)}", stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_profiling/test_sampling_profiler/test_trend_tracker.py b/Lib/test/test_profiling/test_sampling_profiler/test_trend_tracker.py new file mode 100644 index 00000000000..43b23be0fe3 --- /dev/null +++ b/Lib/test/test_profiling/test_sampling_profiler/test_trend_tracker.py @@ -0,0 +1,97 @@ +"""Simple unit tests for TrendTracker.""" + +import unittest +from test.support import requires +from test.support.import_helper import import_module + +# Only run these tests if curses is available +requires("curses") +curses = import_module("curses") + +from profiling.sampling.live_collector.trend_tracker import TrendTracker + + +class TestTrendTracker(unittest.TestCase): + """Tests for TrendTracker class.""" + + def setUp(self): + """Set up test fixtures.""" + self.colors = { + "trend_up": curses.A_BOLD, + "trend_down": curses.A_REVERSE, + "trend_stable": curses.A_NORMAL, + } + + def test_basic_trend_detection(self): + """Test basic up/down/stable trend detection.""" + tracker = TrendTracker(self.colors, enabled=True) + + # First value is always stable + self.assertEqual(tracker.update("func1", "nsamples", 10), "stable") + + # Increasing value + self.assertEqual(tracker.update("func1", "nsamples", 20), "up") + + # Decreasing value + self.assertEqual(tracker.update("func1", "nsamples", 15), "down") + + # Small change (within threshold) is stable + self.assertEqual(tracker.update("func1", "nsamples", 15.0001), "stable") + + def test_multiple_metrics(self): + """Test tracking multiple metrics simultaneously.""" + tracker = TrendTracker(self.colors, enabled=True) + + trends = tracker.update_metrics("func1", { + "nsamples": 10, + "tottime": 5.0, + }) + + self.assertEqual(trends["nsamples"], "stable") + self.assertEqual(trends["tottime"], "stable") + + # Update with changes + trends = tracker.update_metrics("func1", { + "nsamples": 15, + "tottime": 3.0, + }) + + self.assertEqual(trends["nsamples"], "up") + self.assertEqual(trends["tottime"], "down") + + def test_toggle_enabled(self): + """Test enable/disable toggle.""" + tracker = TrendTracker(self.colors, enabled=True) + self.assertTrue(tracker.enabled) + + tracker.toggle() + self.assertFalse(tracker.enabled) + + # When disabled, should return A_NORMAL + self.assertEqual(tracker.get_color("up"), curses.A_NORMAL) + + def test_get_color(self): + """Test color selection for trends.""" + tracker = TrendTracker(self.colors, enabled=True) + + self.assertEqual(tracker.get_color("up"), curses.A_BOLD) + self.assertEqual(tracker.get_color("down"), curses.A_REVERSE) + self.assertEqual(tracker.get_color("stable"), curses.A_NORMAL) + + def test_clear(self): + """Test clearing tracked values.""" + tracker = TrendTracker(self.colors, enabled=True) + + # Add some data + tracker.update("func1", "nsamples", 10) + tracker.update("func1", "nsamples", 20) + + # Clear + tracker.clear() + + # After clear, first update should be stable + self.assertEqual(tracker.update("func1", "nsamples", 30), "stable") + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_cprofile.py b/Lib/test/test_profiling/test_tracing_profiler.py similarity index 77% rename from Lib/test/test_cprofile.py rename to Lib/test/test_profiling/test_tracing_profiler.py index 48057e8f035..50de9af86e8 100644 --- a/Lib/test/test_cprofile.py +++ b/Lib/test/test_profiling/test_tracing_profiler.py @@ -1,14 +1,10 @@ """Test suite for the cProfile module.""" - +import multiprocessing import sys import unittest # rip off all interesting stuff from test_profile -try: - import cProfile -except ImportError: - # TODO: RUSTPYTHON; _lsprof not implemented - raise unittest.SkipTest('cProfile requires _lsprof') +import profiling.tracing as cProfile import tempfile import textwrap from test.test_profile import ProfileTest, regenerate_expected_output @@ -89,6 +85,27 @@ def __call__(self): profiler_with_evil_timer.clear() self.assertEqual(cm.unraisable.exc_type, RuntimeError) + def test_enable_in_external_timer(self): + # gh-157639: Enabling the profiler from an external timer should not crash + import _lsprof + + # the timer re-arms monitoring from inside disable(), so the tool + # id stays claimed once the profiler is torn down + self.addCleanup(sys.monitoring.free_tool_id, sys.monitoring.PROFILER_ID) + + def timer(): + try: + profiler.enable() + except Exception: + pass + return 0 + + profiler = _lsprof.Profiler(timer=timer) + profiler.enable() + (lambda: None)() + profiler.disable() + profiler.clear() + def test_profile_enable_disable(self): prof = self.profilerclass() # Make sure we clean ourselves up if the test fails for some reason. @@ -122,8 +139,9 @@ def test_second_profiler(self): pr = self.profilerclass() pr2 = self.profilerclass() pr.enable() - self.assertRaises(ValueError, pr2.enable) - pr.disable() + self.addCleanup(pr.disable) + msg = f"tool {sys.monitoring.PROFILER_ID} is already in use" + self.assertRaisesRegex(ValueError, msg, pr2.enable) def test_throw(self): """ @@ -146,6 +164,28 @@ def gen(): self.assertTrue(any("throw" in func[2] for func in pr.stats.keys())), + def test_clear_with_nested_calls(self): + # Calling clear() during nested profiled calls should not leak + # ProfilerContexts. clearEntries() must walk the entire linked list, + # not just free the top context. + import _lsprof + + def level3(profiler): + profiler.clear() + + def level2(profiler): + level3(profiler) + + def level1(profiler): + level2(profiler) + + profiler = _lsprof.Profiler() + profiler.enable() + for _ in range(100): + level1(profiler) + profiler.disable() + profiler.clear() + def test_bad_descriptor(self): # gh-132250 # cProfile should not crash when the profiler callback fails to locate @@ -174,6 +214,40 @@ class Foo: f.close() assert_python_ok('-m', "cProfile", f.name) + def _test_process_run_pickle(self, start_method): + val = 10 + with tempfile.NamedTemporaryFile("w+", delete_on_close=False) as f: + f.write(textwrap.dedent( + f'''\ + import multiprocessing + + def worker(x): + print(__name__) + exit(x ** 2) + + if __name__ == "__main__": + multiprocessing.set_start_method('{start_method}') + p = multiprocessing.Process(target=worker, args=({val},)) + p.start() + p.join() + print("p.exitcode =", p.exitcode) + ''')) + f.close() + _, out, err = assert_python_ok('-m', "cProfile", f.name) + self.assertIn(b"__mp_main__", out) + self.assertIn(bytes(f"exitcode = {val**2}", encoding='utf8'), out) + self.assertNotIn(b"Can't pickle", err) + + def test_process_spawn_pickle(self): + # gh-140729: test use Process in cProfile. + self._test_process_run_pickle('spawn') + + @unittest.skipUnless("forkserver" in multiprocessing.get_all_start_methods(), + "forkserver start method is not available") + def test_process_forkserver_pickle(self): + # gh-140729: test use Process in cProfile. + self._test_process_run_pickle('forkserver') + def main(): if '-r' not in sys.argv: diff --git a/Lib/test/test_pstats.py b/Lib/test/test_pstats.py index b99a66052ee..a1874651f66 100644 --- a/Lib/test/test_pstats.py +++ b/Lib/test/test_pstats.py @@ -9,10 +9,7 @@ import os import pstats import tempfile -try: - import cProfile # XXX: RUSTPYTHON -except ImportError: - cProfile = None +import cProfile class LazyImportTest(unittest.TestCase): @support.cpython_only diff --git a/Lib/test/test_pty.py b/Lib/test/test_pty.py index b5407642f82..7e4f4828ce0 100644 --- a/Lib/test/test_pty.py +++ b/Lib/test/test_pty.py @@ -1,6 +1,6 @@ import unittest from test.support import ( - is_android, is_apple_mobile, is_wasm32, reap_children, verbose + is_android, is_apple_mobile, is_wasm32, reap_children, verbose, warnings_helper ) from test.support.import_helper import import_module @@ -19,7 +19,6 @@ import signal import socket import io # readline -import warnings TEST_STRING_1 = b"I wish to buy a fish license.\n" TEST_STRING_2 = b"For my pet fish, Eric.\n" @@ -194,6 +193,7 @@ def test_openpty(self): s2 = _readline(master_fd) self.assertEqual(b'For my pet fish, Eric.\n', normalize_output(s2)) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_fork(self): debug("calling pty.fork()") pid, master_fd = pty.fork() @@ -229,6 +229,7 @@ def test_fork(self): os._exit(2) os._exit(4) else: + self.assertFalse(os.get_inheritable(master_fd)) debug("Waiting for child (%d) to finish." % pid) # In verbose mode, we have to consume the debug output from the # child or the child will block, causing this test to hang in the @@ -295,6 +296,7 @@ def test_master_read(self): self.assertEqual(data, b"") + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() def test_spawn_doesnt_hang(self): # gh-140482: Do the test in a pty.fork() child to avoid messing # with the interactive test runner's terminal settings. @@ -314,7 +316,7 @@ def test_spawn_doesnt_hang(self): (pid, status) = os.waitpid(pid, 0) self.assertEqual(status, 0) - self.assertEqual(bytes(buf), b"hi there\r\n") + self.assertEqual(buf.take_bytes(), b"hi there\r\n") finally: os.close(fd) diff --git a/Lib/test/test_pulldom.py b/Lib/test/test_pulldom.py index 435b52d33eb..3c8ed251aca 100644 --- a/Lib/test/test_pulldom.py +++ b/Lib/test/test_pulldom.py @@ -40,7 +40,6 @@ def test_parse(self): with open(tstfile, "rb") as fin: list(pulldom.parse(fin)) - @unittest.expectedFailure # TODO: RUSTPYTHON; implement DOM semantic def test_parse_semantics(self): """Test DOMEventStream parsing semantics.""" @@ -103,7 +102,6 @@ def test_parse_semantics(self): #evt, node = next(items) #self.assertEqual(pulldom.END_DOCUMENT, evt) - @unittest.expectedFailure # TODO: RUSTPYTHON; pulldom.parseString(SMALL_SAMPLE) return iterator with tuple with 2 elements def test_expandItem(self): """Ensure expandItem works as expected.""" items = pulldom.parseString(SMALL_SAMPLE) @@ -300,7 +298,6 @@ class SAX2DOMTestCase(unittest.TestCase): def confirm(self, test, testname="Test"): self.assertTrue(test, testname) - @unittest.expectedFailure # TODO: RUSTPYTHON; read from stream io def test_basic(self): """Ensure SAX2DOM can parse from a stream.""" with io.StringIO(SMALL_SAMPLE) as fin: diff --git a/Lib/test/test_py_compile.py b/Lib/test/test_py_compile.py index acd2dde8867..6eb01ce7bbc 100644 --- a/Lib/test/test_py_compile.py +++ b/Lib/test/test_py_compile.py @@ -1,4 +1,3 @@ -import functools import importlib.util import os import py_compile @@ -11,43 +10,7 @@ from test import support from test.support import os_helper, script_helper - - -def without_source_date_epoch(fxn): - """Runs function with SOURCE_DATE_EPOCH unset.""" - @functools.wraps(fxn) - def wrapper(*args, **kwargs): - with os_helper.EnvironmentVarGuard() as env: - env.unset('SOURCE_DATE_EPOCH') - return fxn(*args, **kwargs) - return wrapper - - -def with_source_date_epoch(fxn): - """Runs function with SOURCE_DATE_EPOCH set.""" - @functools.wraps(fxn) - def wrapper(*args, **kwargs): - with os_helper.EnvironmentVarGuard() as env: - env['SOURCE_DATE_EPOCH'] = '123456789' - return fxn(*args, **kwargs) - return wrapper - - -# Run tests with SOURCE_DATE_EPOCH set or unset explicitly. -class SourceDateEpochTestMeta(type(unittest.TestCase)): - def __new__(mcls, name, bases, dct, *, source_date_epoch): - cls = super().__new__(mcls, name, bases, dct) - - for attr in dir(cls): - if attr.startswith('test_'): - meth = getattr(cls, attr) - if source_date_epoch: - wrapper = with_source_date_epoch(meth) - else: - wrapper = without_source_date_epoch(meth) - setattr(cls, attr, wrapper) - - return cls +from test.support.os_helper import SourceDateEpochTestMeta class PyCompileTestsBase: @@ -56,7 +19,10 @@ def setUp(self): self.directory = tempfile.mkdtemp(dir=os.getcwd()) self.source_path = os.path.join(self.directory, '_test.py') self.pyc_path = self.source_path + 'c' - self.cache_path = importlib.util.cache_from_source(self.source_path) + try: + self.cache_path = importlib.util.cache_from_source(self.source_path) + except NotImplementedError: + self.cache_path = None self.cwd_drive = os.path.splitdrive(os.getcwd())[0] # In these tests we compute relative paths. When using Windows, the # current working directory path and the 'self.source_path' might be @@ -73,10 +39,31 @@ def tearDown(self): if self.cwd_drive: os.chdir(self.cwd_drive) + def assert_cache_path_exists(self, should_exist=True): + if self.cache_path: + if should_exist: + self.assertTrue(os.path.exists(self.cache_path)) + else: + self.assertFalse(os.path.exists(self.cache_path)) + return + cache_dir = os.path.join(self.directory, '__pycache__') + if not os.path.isdir(cache_dir): + if should_exist: + self.fail('no __pycache__ directory exists') + return + for f in os.listdir(cache_dir): + if f.startswith('_test.') and f.endswith('.pyc'): + if should_exist: + return + self.fail(f'__pycache__/{f} was created') + else: + if should_exist: + self.fail('no __pycache__/_test.*.pyc file exists') + def test_absolute_path(self): py_compile.compile(self.source_path, self.pyc_path) self.assertTrue(os.path.exists(self.pyc_path)) - self.assertFalse(os.path.exists(self.cache_path)) + self.assert_cache_path_exists(False) def test_do_not_overwrite_symlinks(self): # In the face of a cfile argument being a symlink, bail out. @@ -98,23 +85,25 @@ def test_do_not_overwrite_nonregular_files(self): with self.assertRaises(FileExistsError): py_compile.compile(self.source_path, os.devnull) + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag is not None') def test_cache_path(self): py_compile.compile(self.source_path) - self.assertTrue(os.path.exists(self.cache_path)) + self.assert_cache_path_exists(True) def test_cwd(self): with os_helper.change_cwd(self.directory): py_compile.compile(os.path.basename(self.source_path), os.path.basename(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path)) - self.assertFalse(os.path.exists(self.cache_path)) + self.assert_cache_path_exists(False) @unittest.expectedFailureIf(sys.platform == "darwin" and int(__import__("platform").release().split(".")[0]) < 20, "TODO: RUSTPYTHON") def test_relative_path(self): py_compile.compile(os.path.relpath(self.source_path), os.path.relpath(self.pyc_path)) self.assertTrue(os.path.exists(self.pyc_path)) - self.assertFalse(os.path.exists(self.cache_path)) + self.assert_cache_path_exists(False) @os_helper.skip_if_dac_override @unittest.skipIf(os.name == 'nt', @@ -137,14 +126,14 @@ def test_bad_coding(self): 'tokenizedata', 'bad_coding2.py') with support.captured_stderr(): - self.assertIsNone(py_compile.compile(bad_coding, doraise=False)) - self.assertFalse(os.path.exists( - importlib.util.cache_from_source(bad_coding))) + self.assertIsNone(py_compile.compile(bad_coding, self.pyc_path, + doraise=False)) + self.assertFalse(os.path.exists(self.pyc_path)) def test_source_date_epoch(self): py_compile.compile(self.source_path, self.pyc_path) self.assertTrue(os.path.exists(self.pyc_path)) - self.assertFalse(os.path.exists(self.cache_path)) + self.assert_cache_path_exists(False) with open(self.pyc_path, 'rb') as fp: flags = importlib._bootstrap_external._classify_pyc( fp.read(), 'test', {}) @@ -156,6 +145,8 @@ def test_source_date_epoch(self): self.assertEqual(flags, expected_flags) @unittest.skipIf(sys.flags.optimize > 0, 'test does not work with -O') + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag is not None') def test_double_dot_no_clobber(self): # http://bugs.python.org/issue22966 # py_compile foo.bar.py -> __pycache__/foo.cpython-34.pyc @@ -178,6 +169,8 @@ def test_double_dot_no_clobber(self): self.assertTrue(os.path.exists(cache_path)) self.assertFalse(os.path.exists(pyc_path)) + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag is not None') def test_optimization_path(self): # Specifying optimized bytecode should lead to a path reflecting that. self.assertIn('opt-2', py_compile.compile(self.source_path, optimize=2)) @@ -185,17 +178,19 @@ def test_optimization_path(self): def test_invalidation_mode(self): py_compile.compile( self.source_path, + self.pyc_path, invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH, ) - with open(self.cache_path, 'rb') as fp: + with open(self.pyc_path, 'rb') as fp: flags = importlib._bootstrap_external._classify_pyc( fp.read(), 'test', {}) self.assertEqual(flags, 0b11) py_compile.compile( self.source_path, + self.pyc_path, invalidation_mode=py_compile.PycInvalidationMode.UNCHECKED_HASH, ) - with open(self.cache_path, 'rb') as fp: + with open(self.pyc_path, 'rb') as fp: flags = importlib._bootstrap_external._classify_pyc( fp.read(), 'test', {}) self.assertEqual(flags, 0b1) @@ -205,11 +200,11 @@ def test_quiet(self): 'tokenizedata', 'bad_coding2.py') with support.captured_stderr() as stderr: - self.assertIsNone(py_compile.compile(bad_coding, doraise=False, quiet=2)) - self.assertIsNone(py_compile.compile(bad_coding, doraise=True, quiet=2)) + self.assertIsNone(py_compile.compile(bad_coding, self.pyc_path, doraise=False, quiet=2)) + self.assertIsNone(py_compile.compile(bad_coding, self.pyc_path, doraise=True, quiet=2)) self.assertEqual(stderr.getvalue(), '') with self.assertRaises(py_compile.PyCompileError): - py_compile.compile(bad_coding, doraise=True, quiet=1) + py_compile.compile(bad_coding, self.pyc_path, doraise=True, quiet=1) def test_utf7_decoded_cr_compiles(self): with open(self.source_path, 'wb') as file: @@ -239,8 +234,12 @@ class PyCompileCLITestCase(unittest.TestCase): def setUp(self): self.directory = tempfile.mkdtemp() self.source_path = os.path.join(self.directory, '_test.py') - self.cache_path = importlib.util.cache_from_source(self.source_path, - optimization='' if __debug__ else 1) + try: + self.cache_path = importlib.util.cache_from_source(self.source_path, + optimization='' if __debug__ else 1) + except NotImplementedError: + # py_compile.main() assumes legacy pyc path if there is no cache_tag + self.cache_path = self.source_path + 'c' with open(self.source_path, 'w') as file: file.write('x = 123\n') diff --git a/Lib/test/test_pyclbr.py b/Lib/test/test_pyclbr.py index 17a19b21307..b5ec41b17f7 100644 --- a/Lib/test/test_pyclbr.py +++ b/Lib/test/test_pyclbr.py @@ -11,9 +11,6 @@ import pyclbr from unittest import TestCase, main as unittest_main from test.test_importlib import util as test_importlib_util -import warnings - -import unittest # XXX: RUSTPYTHON; importing to be able to skip tests StaticMethodType = type(staticmethod(lambda: None)) @@ -248,9 +245,6 @@ def test_others(self): # These were once some of the longest modules. cm('random', ignore=('Random',)) # from _random import Random as CoreGenerator cm('pickle', ignore=('partial', 'PickleBuffer')) - with warnings.catch_warnings(): - warnings.simplefilter('ignore', DeprecationWarning) - cm('sre_parse', ignore=('dump', 'groups', 'pos')) # from sre_constants import *; property with temporary_main_spec(): cm( 'pdb', @@ -258,7 +252,8 @@ def test_others(self): ignore=('Union', '_ModuleTarget', '_ScriptTarget', '_ZipTarget', 'curframe_locals', '_InteractState', 'rlcompleter'), ) - cm('pydoc', ignore=('input', 'output',)) # properties + cm('pydoc', ignore=('input', 'output', # properties + 'getpager', 'plainpager', )) # aliases # Tests for modules inside packages cm('email.parser') diff --git a/Lib/test/test_pydoc/test_pydoc.py b/Lib/test/test_pydoc/test_pydoc.py index bac96087a64..5e19576b890 100644 --- a/Lib/test/test_pydoc/test_pydoc.py +++ b/Lib/test/test_pydoc/test_pydoc.py @@ -8,10 +8,7 @@ import pydoc import py_compile import keyword -try: # TODO: RUSTPYTHON; Implement `_pickle` - import _pickle -except ImportError: - _pickle = None +import _pickle import pkgutil import re import tempfile @@ -22,6 +19,7 @@ import unittest import unittest.mock import urllib.parse +import urllib.request import xml.etree import xml.etree.ElementTree import textwrap @@ -432,7 +430,7 @@ def test_html_doc(self): expected_lines = [line.strip() for line in expected_lines if line] self.assertEqual(text_lines, expected_lines) mod_file = inspect.getabsfile(pydoc_mod) - mod_url = urllib.parse.quote(mod_file) + mod_url = urllib.request.pathname2url(mod_file) self.assertIn(mod_url, result) self.assertIn(mod_file, result) self.assertIn(doc_loc, result) @@ -581,7 +579,7 @@ class object # of the known subclasses of object. (doc.docclass() used to # fail if HeapType was imported before running this test, like # when running tests sequentially.) - from _testcapi import HeapType + from _testcapi import HeapType # noqa: F401 except ImportError: pass text = doc.docclass(object) @@ -1009,6 +1007,8 @@ def test_synopsis_sourceless(self): os = import_helper.import_fresh_module('os') expected = os.__doc__.splitlines()[0] filename = os.__spec__.cached + if not filename: + raise unittest.SkipTest('requires .pyc files') synopsis = pydoc.synopsis(filename) self.assertEqual(synopsis, expected) @@ -1016,15 +1016,40 @@ def test_synopsis_sourceless(self): def test_synopsis_sourceless_empty_doc(self): with os_helper.temp_cwd() as test_dir: init_path = os.path.join(test_dir, 'foomod42.py') - cached_path = importlib.util.cache_from_source(init_path) + cached_path = init_path + 'c' with open(init_path, 'w') as fobj: fobj.write("foo = 1") - py_compile.compile(init_path) + py_compile.compile(init_path, cached_path) synopsis = pydoc.synopsis(init_path, {}) self.assertIsNone(synopsis) synopsis_cached = pydoc.synopsis(cached_path, {}) self.assertIsNone(synopsis_cached) + @unittest.skipUnless(os_helper.TESTFN_UNDECODABLE, + 'requires undecodable file names') + def test_html_doc_undecodable_path(self): + # gh-69371: the path of the module is not encodable in UTF-8. + with os_helper.temp_cwd() as test_dir: + subdir = os.path.join(os.fsencode(test_dir), + os_helper.TESTFN_UNDECODABLE) + try: + os.mkdir(subdir) + except OSError: + self.skipTest('undecodable paths are not supported') + with open(os.path.join(subdir, b'undecodable_mod.py'), 'w') as f: + f.write('"""Module docstring."""\n') + with import_helper.DirsOnSysPath(os.fsdecode(subdir)): + mod = import_helper.import_fresh_module('undecodable_mod') + doc = pydoc.HTMLDoc().docmodule(mod) + with captured_stdout(): + pydoc.writedoc(mod) + # The link contains the percent-encoded path... + path = inspect.getabsfile(mod) + self.assertIn(urllib.request.pathname2url(path), doc) + # ...and the page can be written and served as UTF-8. + with open('undecodable_mod.html', encoding='utf-8') as f: + self.assertIn('undecodable_mod', f.read()) + def test_splitdoc_with_description(self): example_string = "I Am A Doc\n\n\nHere is my description" self.assertEqual(pydoc.splitdoc(example_string), @@ -1363,47 +1388,6 @@ def test_url_search_package_error(self): finally: sys.path[:] = saved_paths - @unittest.skip('causes undesirable side-effects (#20128)') - def test_modules(self): - # See Helper.listmodules(). - num_header_lines = 2 - num_module_lines_min = 5 # Playing it safe. - num_footer_lines = 3 - expected = num_header_lines + num_module_lines_min + num_footer_lines - - output = StringIO() - helper = pydoc.Helper(output=output) - helper('modules') - result = output.getvalue().strip() - num_lines = len(result.splitlines()) - - self.assertGreaterEqual(num_lines, expected) - - @unittest.skip('causes undesirable side-effects (#20128)') - def test_modules_search(self): - # See Helper.listmodules(). - expected = 'pydoc - ' - - output = StringIO() - helper = pydoc.Helper(output=output) - with captured_stdout() as help_io: - helper('modules pydoc') - result = help_io.getvalue() - - self.assertIn(expected, result) - - @unittest.skip('some buildbots are not cooperating (#20128)') - def test_modules_search_builtin(self): - expected = 'gc - ' - - output = StringIO() - helper = pydoc.Helper(output=output) - with captured_stdout() as help_io: - helper('modules garbage') - result = help_io.getvalue() - - self.assertStartsWith(result, expected) - def test_importfile(self): try: loaded_pydoc = pydoc.importfile(pydoc.__file__) @@ -1483,7 +1467,7 @@ def test_special_form(self): self.assertIn('NoReturn = typing.NoReturn', doc) self.assertIn(typing.NoReturn.__doc__.strip().splitlines()[0], doc) else: - self.assertIn('NoReturn = class _SpecialForm(_Final)', doc) + self.assertIn('NoReturn = class _SpecialForm(_Final, _NotIterable)', doc) def test_typing_pydoc(self): def foo(data: typing.List[typing.Any], @@ -2215,7 +2199,7 @@ def mock_getline(prompt): def test_keywords(self): self.assertEqual(sorted(pydoc.Helper.keywords), - sorted(keyword.kwlist + ['case', 'match'])) + sorted(keyword.kwlist + ['case', 'match', 'lazy'])) def test_interact_empty_line_continues(self): # gh-138568: test pressing Enter without input should continue in help session @@ -2238,7 +2222,6 @@ class PydocWithMetaClasses(unittest.TestCase): def tearDown(self): self.assertIs(sys.modules['pydoc'], pydoc) - @unittest.expectedFailure # TODO: RUSTPYTHON @unittest.skipIf(hasattr(sys, 'gettrace') and sys.gettrace(), 'trace function introduces __locals__ unexpectedly') @requires_docstrings @@ -2414,6 +2397,32 @@ def test_sys_path_adjustment_when_curdir_already_included(self): trailing_argv0dir = trailing_curdir + [self.argv0dir] self.assertIsNone(self._get_revised_path(trailing_argv0dir)) + def test__get_version(self): + import json + import warnings + + class MyModule: + __name__ = 'my_module' + + @property + def __version__(self): + warnings._deprecated("__version__", remove=(3, 20)) + return "1.2.3" + + module = MyModule() + doc = pydoc.Doc() + with warnings.catch_warnings(record=True) as w: # TODO: remove in 3.20 + warnings.simplefilter("always") + version = doc._get_version(json) + self.assertEqual(version, "2.0.9") + self.assertEqual(len(w), 0) + + with warnings.catch_warnings(record=True) as w: + warnings.simplefilter("always") + version = doc._get_version(module) + self.assertEqual(version, "1.2.3") + self.assertEqual(len(w), 1) + def setUpModule(): thread_info = threading_helper.threading_setup() diff --git a/Lib/test/test_pyexpat.py b/Lib/test/test_pyexpat.py index 144acb7afd7..0ccb50b1ec6 100644 --- a/Lib/test/test_pyexpat.py +++ b/Lib/test/test_pyexpat.py @@ -13,12 +13,11 @@ from io import BytesIO from test import support from test.support import import_helper, os_helper - +from test.support import sortdict +from unittest import mock from xml.parsers import expat from xml.parsers.expat import errors -from test.support import sortdict - class SetAttributeTest(unittest.TestCase): def setUp(self): @@ -280,6 +279,93 @@ def test_parse_again(self): self.assertEqual(expat.ErrorString(cm.exception.code), expat.errors.XML_ERROR_FINISHED) + @unittest.expectedFailure # TODO: RUSTPYTHON; incomplete document error precedes reentrant character callback + @support.subTests("encoding", ("utf-8", "utf-16")) + def test_parse_reentrancy_with_encoding(self, encoding): + # See https://github.com/python/cpython/issues/146169. + parser = expat.ParserCreate(encoding=encoding) + + def CharacterDataHandler(data): + return parser.Parse(data, False) + CharacterDataHandler = mock.Mock(wraps=CharacterDataHandler) + parser.CharacterDataHandler = CharacterDataHandler + + payload = "x".encode(encoding) + msg = re.escape("cannot call Parse() from within a handler") + with self.assertRaisesRegex(RuntimeError, msg): + for i in range(len(payload)): + parser.Parse(payload[i:i+1], i == len(payload) - 1) + CharacterDataHandler.assert_called_once_with("x") + + @unittest.expectedFailure # TODO: RUSTPYTHON; incomplete document error precedes reentrant character callback + @support.subTests("encoding", ("utf-8", "utf-16")) + def test_parse_file_reentrancy_with_encoding(self, encoding): + # See https://github.com/python/cpython/issues/146169. + parser = expat.ParserCreate(encoding=encoding) + + def CharacterDataHandler(data): + return parser.ParseFile(BytesIO(data.encode(encoding))) + CharacterDataHandler = mock.Mock(wraps=CharacterDataHandler) + parser.CharacterDataHandler = CharacterDataHandler + + payload = "x".encode(encoding) + payload_buffer = BytesIO(payload) + msg = re.escape("cannot call ParseFile() from within a handler") + with self.assertRaisesRegex(RuntimeError, msg): + parser.ParseFile(payload_buffer) + CharacterDataHandler.assert_called_once_with("x") + + @unittest.expectedFailure # TODO: RUSTPYTHON; external entity callbacks are not dispatched + @support.subTests("encoding", ("utf-8", "utf-16")) + def test_parse_reentrancy_allowed_for_external_parser(self, encoding): + parser = expat.ParserCreate(encoding=encoding) + subparser = parser.ExternalEntityParserCreate(None, encoding) + payload_extstr = '' + + def ExternalEntityRefHandler(*args): + subparser.Parse(payload_extstr, True) + # return a nonzero integer to indicate that parsing continues + return 1 + ExternalEntityRefHandler = mock.Mock(wraps=ExternalEntityRefHandler) + parser.ExternalEntityRefHandler = ExternalEntityRefHandler + + payload = textwrap.dedent(f"""\ + + + &ext; + """).encode(encoding) + + # Check that external parsers be called from parent's handlers. + for i in range(len(payload)): + parser.Parse(payload[i:i+1], i == len(payload) - 1) + external_ref_args = ('ext', None, 'entity.file', None) + ExternalEntityRefHandler.assert_called_once_with(*external_ref_args) + + @unittest.expectedFailure # TODO: RUSTPYTHON; external entity callbacks are not dispatched + @support.subTests("encoding", ("utf-8", "utf-16")) + def test_parse_file_reentrancy_allowed_for_external_parser(self, encoding): + parser = expat.ParserCreate(encoding=encoding) + subparser = parser.ExternalEntityParserCreate(None, encoding) + payload_extstr = '' + + def ExternalEntityRefHandler(*args): + subparser.ParseFile(BytesIO(payload_extstr.encode(encoding))) + # return a nonzero integer to indicate that parsing continues + return 1 + ExternalEntityRefHandler = mock.Mock(wraps=ExternalEntityRefHandler) + parser.ExternalEntityRefHandler = ExternalEntityRefHandler + + payload = textwrap.dedent(f"""\ + + + &ext; + """).encode(encoding) + + # Check that external parsers be called from parent's handlers. + parser.ParseFile(BytesIO(payload)) + external_ref_args = ('ext', None, 'entity.file', None) + ExternalEntityRefHandler.assert_called_once_with(*external_ref_args) + @unittest.expectedFailure # TODO: RUSTPYTHON @support.subTests('encoding', [ 'utf-8', 'utf-16', 'utf-16be', 'utf-16le', @@ -331,7 +417,6 @@ def test_supported_encodings2(self, encoding): "End element: 'корінь'", ]) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: ValueError not raised @support.subTests('encoding', [ 'UTF-7', "Big5-HKSCS", "Big5", @@ -355,7 +440,6 @@ def test_unsupported_encodings(self, encoding): with self.assertRaises(ValueError): parser.Parse(data, True) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: ExpatError not raised @support.subTests('encoding', [ 'cp037', 'cp273', 'cp424', 'cp500', 'cp864', 'cp875', 'cp1026', 'cp1140', @@ -374,7 +458,6 @@ def test_incompatible_encodings(self, encoding): with self.assertRaisesRegex(expat.ExpatError, 'unknown encoding'): parser.Parse(data, True) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: LookupError not raised @support.subTests('encoding', [ 'hex_codec', 'rot_13', ]) @@ -385,14 +468,12 @@ def test_non_text_encodings(self, encoding): with self.assertRaises(LookupError): parser.Parse(data, True) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: UnicodeError not raised def test_undefined_encoding(self): parser = expat.ParserCreate() data = b'\n' with self.assertRaises(UnicodeError): parser.Parse(data, True) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: LookupError not raised def test_unknown_encoding(self): parser = expat.ParserCreate() data = b'\n' @@ -408,7 +489,6 @@ def test_legal(self): expat.ParserCreate(namespace_separator=None) expat.ParserCreate(namespace_separator=' ') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_illegal(self): with self.assertRaisesRegex(TypeError, r"ParserCreate\(\) argument (2|'namespace_separator') " @@ -508,7 +588,6 @@ def test_default_to_disabled(self): parser = expat.ParserCreate() self.assertFalse(parser.buffer_text) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_buffering_enabled(self): # Make sure buffering is turned on self.assertTrue(self.parser.buffer_text) @@ -526,7 +605,6 @@ def test1(self): ["", "1", "", "2", "\n", "3", "", "4\n5"], "buffering control not reacting as expected") - @unittest.expectedFailure # TODO: RUSTPYTHON def test2(self): self.parser.Parse(b"1<2> \n 3", True) self.assertEqual(self.stuff, ["1<2> \n 3"], @@ -568,6 +646,19 @@ def test7(self): "", "4", "", "5", ""], "buffered text not properly split") + def test_change_character_data_handler_in_callback(self): + # Test that xmlparse_handler_setter() properly handles + # the special case "parser.CharacterDataHandler = None". + def handler(*args): + parser.CharacterDataHandler = None + + handler_wrapper = mock.Mock(wraps=handler) + parser = expat.ParserCreate() + parser.CharacterDataHandler = handler_wrapper + parser.Parse(b"12345 ", True) + handler_wrapper.assert_called_once() + self.assertIsNone(parser.CharacterDataHandler) + # Test handling of exception from callback: class HandlerExceptionTest(unittest.TestCase): @@ -626,6 +717,34 @@ def _test_exception(self, have_source): self.assertIn('call_with_frame("StartElement"', entries[1].line) + def test_invalid_NotStandalone(self): + parser = expat.ParserCreate() + parser.NotStandaloneHandler = mock.Mock(return_value="bad value") + parser.ElementDeclHandler = lambda _1, _2: None + + payload = b"""\ +]> +""" + with self.assertRaises(TypeError) as cm: + parser.Parse(payload, True) + parser.NotStandaloneHandler.assert_called_once() + + notes = ["invalid 'NotStandalone' event handler return value"] + self.assertEqual(cm.exception.__notes__, notes) + + def test_invalid_ExternalEntityRefHandler(self): + parser = expat.ParserCreate() + parser.UseForeignDTD() + parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) + parser.ExternalEntityRefHandler = mock.Mock(return_value=None) + + with self.assertRaises(TypeError) as cm: + parser.Parse(b"", True) + parser.ExternalEntityRefHandler.assert_called_once() + + notes = ["invalid 'ExternalEntityRef' event handler return value"] + self.assertEqual(cm.exception.__notes__, notes) + # Test Current* members: class PositionTest(unittest.TestCase): @@ -648,9 +767,6 @@ def check_pos(self, event): self.upto += 1 @unittest.expectedFailure # TODO: RUSTPYTHON; the xml-rs backend reports a - # token's *current parse cursor* position rather than libexpat's *start of - # token* position, so exact byte/column offsets for StartElementHandler - # don't match upstream expat. def test(self): self.parser = expat.ParserCreate() self.parser.StartElementHandler = self.StartElementHandler @@ -696,7 +812,6 @@ def test_1025_bytes(self): def test_1000_bytes(self): self.assertEqual(self.small_buffer_test(1000), 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_wrong_size(self): parser = expat.ParserCreate() parser.buffer_text = 1 @@ -737,7 +852,7 @@ def test_unchanged_size(self): def test_disabling_buffer(self): xml1 = b"" + b'a' * 512 xml2 = b'b' * 1024 - xml3 = b'c' * 1024 + b''; + xml3 = b'c' * 1024 + b'' parser = expat.ParserCreate() parser.CharacterDataHandler = self.counting_handler parser.buffer_text = 1 @@ -764,6 +879,34 @@ def test_disabling_buffer(self): parser.Parse(xml3, True) self.assertEqual(self.n, 12) + def test_disable_buffer_in_character_handler(self): + parser = expat.ParserCreate() + parser.buffer_size = 2 + parser.buffer_text = True + seen = [] + + def consume(text): + seen.append(text) + if len(seen) == 1: + parser.buffer_text = False + + parser.CharacterDataHandler = consume + parser.Parse(b'aAbc', True) + self.assertEqual(''.join(seen), 'aAbc') + + def test_clear_element_handler_during_flush(self): + parser = expat.ParserCreate() + parser.buffer_text = True + elements = [] + + def consume(text): + parser.StartElementHandler = None + + parser.CharacterDataHandler = consume + parser.StartElementHandler = lambda name, attrs: elements.append(name) + parser.Parse(b'abc', True) + self.assertEqual(elements, ['r']) + def counting_handler(self, text): self.n += 1 @@ -815,7 +958,7 @@ def test_change_size_2(self): @support.requires_resource('cpu') @support.requires_resource('walltime') @support.bigmemtest(size=2**31, memuse=4, dry_run=False) - def test_large_character_data_does_not_crash(self): + def test_large_character_data_does_not_crash(self, size): # See https://github.com/python/cpython/issues/148441 parser = expat.ParserCreate() parser.buffer_text = True @@ -827,7 +970,6 @@ def test_large_character_data_does_not_crash(self): self.assertEqual(parser.Parse(xml_data, True), 1) class ElementDeclHandlerTest(unittest.TestCase): - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: TypeError not raised by Parse def test_trigger_leak(self): # Unfixed, this test would leak the memory of the so-called # "content model" in function ``my_ElementDeclHandler`` of pyexpat. @@ -845,7 +987,7 @@ def test_trigger_leak(self): self.assertRaises(TypeError, parser.Parse, data, True) @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: RecursionError not raised - @support.skip_if_unlimited_stack_size + @support.run_with_limited_c_stack(800_000) @support.skip_emscripten_stack_overflow() @support.skip_wasi_stack_overflow() def test_deeply_nested_content_model(self): @@ -885,13 +1027,11 @@ def test2(self): parser.Parse(xml, True) class ErrorMessageTest(unittest.TestCase): - @unittest.expectedFailure # TODO: RUSTPYTHON def test_codes(self): # verify mapping of errors.codes and errors.messages self.assertEqual(errors.XML_ERROR_SYNTAX, errors.messages[errors.codes[errors.XML_ERROR_SYNTAX]]) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_expaterror(self): xml = b'<' parser = expat.ParserCreate() @@ -907,7 +1047,6 @@ class ForeignDTDTests(unittest.TestCase): """ Tests for the UseForeignDTD method of expat parser objects. """ - @unittest.expectedFailure # TODO: RUSTPYTHON def test_use_foreign_dtd(self): """ If UseForeignDTD is passed True and a document without an external @@ -936,7 +1075,6 @@ def resolve_entity(context, base, system_id, public_id): parser.Parse(b"") self.assertEqual(handler_call_args, [(None, None)]) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_ignore_use_foreign_dtd(self): """ If UseForeignDTD is passed True and a document with an external @@ -965,7 +1103,6 @@ class ParentParserLifetimeTest(unittest.TestCase): See https://github.com/python/cpython/issues/139400. """ - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'ExternalEntityParserCreate' def test_parent_parser_outlives_its_subparsers__single(self): parser = expat.ParserCreate() subparser = parser.ExternalEntityParserCreate(None) @@ -974,7 +1111,6 @@ def test_parent_parser_outlives_its_subparsers__single(self): # while it's still being referenced by a related subparser. del parser - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'ExternalEntityParserCreate' def test_parent_parser_outlives_its_subparsers__multiple(self): parser = expat.ParserCreate() subparser_one = parser.ExternalEntityParserCreate(None) @@ -984,7 +1120,6 @@ def test_parent_parser_outlives_its_subparsers__multiple(self): # while it's still being referenced by a related subparser. del parser - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'ExternalEntityParserCreate' def test_parent_parser_outlives_its_subparsers__chain(self): parser = expat.ParserCreate() subparser = parser.ExternalEntityParserCreate(None) @@ -995,6 +1130,16 @@ def test_parent_parser_outlives_its_subparsers__chain(self): del parser del subparser + # gh-155485: GetReparseDeferralEnabled always returns False with Expat <2.6.0. + @unittest.skipIf(not expat.ParserCreate().GetReparseDeferralEnabled(), + "requires Python compiled with Expat >= 2.6.0") + def test_subparser_inherits_reparse_deferral(self): + for enabled in (True, False): + parser = expat.ParserCreate() + parser.SetReparseDeferralEnabled(enabled) + subparser = parser.ExternalEntityParserCreate(None) + self.assertEqual(subparser.GetReparseDeferralEnabled(), enabled) + class ExternalEntityParserCreateErrorTest(unittest.TestCase): """ExternalEntityParserCreate error paths should not crash or leak @@ -1007,8 +1152,7 @@ class ExternalEntityParserCreateErrorTest(unittest.TestCase): def setUpClass(cls): cls.testcapi = import_helper.import_module('_testcapi') - @unittest.skipIf(support.Py_TRACE_REFS, - 'Py_TRACE_REFS conflicts with testcapi.set_nomemory') + @support.nomemtest def test_error_path_no_crash(self): # When an allocation inside ExternalEntityParserCreate fails, # the partially-initialized subparser is deallocated. This @@ -1018,25 +1162,15 @@ def test_error_path_no_crash(self): parser.buffer_text = True rc_before = sys.getrefcount(parser) - # We avoid self.assertRaises(MemoryError) here because the - # context manager itself needs memory allocations that fail - # while the nomemory hook is active. - self.testcapi.set_nomemory(1, 10) - raised = False - try: - parser.ExternalEntityParserCreate(None) - except MemoryError: - raised = True - finally: - self.testcapi.remove_mem_hooks() - self.assertTrue(raised, "MemoryError not raised") + with self.assertRaises(MemoryError): + with support.inject_memory_error_cm(1, 10): + parser.ExternalEntityParserCreate(None) rc_after = sys.getrefcount(parser) self.assertEqual(rc_after, rc_before) class ReparseDeferralTest(unittest.TestCase): - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'GetReparseDeferralEnabled' def test_getter_setter_round_trip(self): parser = expat.ParserCreate() enabled = (expat.version_info >= (2, 6, 0)) @@ -1072,7 +1206,6 @@ def start_element(name, _): self.assertEqual(started, ['doc']) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetReparseDeferralEnabled' def test_reparse_deferral_disabled(self): started = [] diff --git a/Lib/test/test_pyrepl/__init__.py b/Lib/test/test_pyrepl/__init__.py index 2f37bff6df8..1534d63352c 100644 --- a/Lib/test/test_pyrepl/__init__.py +++ b/Lib/test/test_pyrepl/__init__.py @@ -3,6 +3,9 @@ from test.support import import_helper, load_package_tests +import_helper.import_module("_pyrepl") + + if sys.platform != "win32": import_helper.import_module("termios") diff --git a/Lib/test/test_pyrepl/support.py b/Lib/test/test_pyrepl/support.py index 307bf450555..c879a2f93b6 100644 --- a/Lib/test/test_pyrepl/support.py +++ b/Lib/test/test_pyrepl/support.py @@ -4,6 +4,7 @@ from unittest.mock import MagicMock from _pyrepl.console import Console, Event +from _pyrepl.render import RenderLine, RenderedScreen from _pyrepl.readline import ReadlineAlikeReader, ReadlineConfig from _pyrepl.simple_interact import _strip_final_indent from _pyrepl.utils import unbracket, ANSI_ESCAPE_SEQUENCE @@ -15,7 +16,13 @@ def assert_screen_equal( ): actual = clean_screen(reader) if clean else reader.screen expected = expected.split("\n") - self.assertListEqual(actual, expected) + if clean: + self.assertListEqual(actual, expected) + return + + actual_lines = [RenderLine.from_rendered_text(line) for line in actual] + expected_lines = [RenderLine.from_rendered_text(line) for line in expected] + self.assertListEqual(actual_lines, expected_lines) def multiline_input(reader: ReadlineAlikeReader, namespace: dict | None = None): @@ -120,9 +127,11 @@ class FakeConsole(Console): def __init__(self, events, encoding="utf-8") -> None: self.events = iter(events) self.encoding = encoding - self.screen = [] + self._rendered_screen = RenderedScreen.empty() self.height = 100 self.width = 80 + self.posxy = (0, 0) + self._redraw_visual_cycle = 0 def get_event(self, block: bool = True) -> Event | None: return next(self.events) @@ -133,7 +142,7 @@ def getpending(self) -> Event: def getheightwidth(self) -> tuple[int, int]: return self.height, self.width - def refresh(self, screen: list[str], xy: tuple[int, int]) -> None: + def refresh(self, rendered_screen: RenderedScreen) -> None: pass def prepare(self) -> None: diff --git a/Lib/test/test_pyrepl/test_fancycompleter.py b/Lib/test/test_pyrepl/test_fancycompleter.py new file mode 100644 index 00000000000..0ffc1ed97b5 --- /dev/null +++ b/Lib/test/test_pyrepl/test_fancycompleter.py @@ -0,0 +1,250 @@ +import importlib +import inspect +import os +import types +import unittest + +from _colorize import ANSIColors, get_theme +from _pyrepl.completing_reader import stripcolor +from _pyrepl.fancycompleter import ( + Completer, + colorize_matches, + commonprefix, + _color_for_obj, +) +from test.support.import_helper import ready_to_import + +class MockPatch: + def __init__(self): + self.original_values = {} + + def setattr(self, obj, name, value): + if obj not in self.original_values: + self.original_values[obj] = {} + if name not in self.original_values[obj]: + self.original_values[obj][name] = getattr(obj, name) + setattr(obj, name, value) + + def restore_all(self): + for obj, attrs in self.original_values.items(): + for name, value in attrs.items(): + setattr(obj, name, value) + +class FancyCompleterTests(unittest.TestCase): + def setUp(self): + self.mock_patch = MockPatch() + + def tearDown(self): + self.mock_patch.restore_all() + + def test_commonprefix(self): + self.assertEqual(commonprefix(['isalpha', 'isdigit', 'foo']), '') + self.assertEqual(commonprefix(['isalpha', 'isdigit']), 'is') + self.assertEqual(commonprefix([]), '') + + def test_colorize_matches_signature(self): + signature = inspect.signature(colorize_matches) + + self.assertEqual(list(signature.parameters), ["names", "values", "theme"]) + + def test_complete_attribute(self): + compl = Completer({'a': None}, use_colors=False) + self.assertEqual(compl.attr_matches('a.'), ['a.__']) + matches = compl.attr_matches('a.__') + self.assertNotIn('__class__', matches) + self.assertIn('a.__class__', matches) + match = compl.attr_matches('a.__class') + self.assertEqual(len(match), 1) + self.assertTrue(match[0].startswith('a.__class__')) + + def test_complete_attribute_prefix(self): + class C(object): + attr = 1 + _attr = 2 + __attr__attr = 3 + compl = Completer({'a': C}, use_colors=False) + self.assertEqual(compl.attr_matches('a.'), ['a.attr', 'a.mro']) + self.assertEqual( + compl.attr_matches('a._'), + ['a._C__attr__attr', 'a._attr'], + ) + matches = compl.attr_matches('a.__') + self.assertNotIn('__class__', matches) + self.assertIn('a.__class__', matches) + match = compl.attr_matches('a.__class') + self.assertEqual(len(match), 1) + self.assertTrue(match[0].startswith('a.__class__')) + + compl = Completer({'a': None}, use_colors=False) + self.assertEqual(compl.attr_matches('a._'), ['a.__']) + + def test_complete_attribute_colored(self): + theme = get_theme() + compl = Completer({'a': 42}, use_colors=True) + matches = compl.attr_matches('a.__') + self.assertGreater(len(matches), 2) + expected_color = theme.fancycompleter.type + expected_part = f'{expected_color}a.__class__{ANSIColors.RESET}' + for match in matches: + if expected_part in match: + break + else: + self.assertFalse(True, matches) + self.assertNotIn(' ', matches) + + def test_preserves_callable_postfix_for_single_attribute_match(self): + compl = Completer({'os': os}, use_colors=False) + self.assertEqual(compl.attr_matches('os.getpid'), ['os.getpid()']) + + def test_property_method_not_called(self): + class Foo: + property_called = False + + @property + def bar(self): + self.property_called = True + return 1 + + foo = Foo() + compl = Completer({'foo': foo}, use_colors=False) + self.assertEqual(compl.attr_matches('foo.b'), ['foo.bar']) + self.assertFalse(foo.property_called) + + def test_excessive_getattr(self): + class Foo: + calls = 0 + bar = '' + + def __getattribute__(self, name): + if name == 'bar': + self.calls += 1 + return None + return super().__getattribute__(name) + + foo = Foo() + compl = Completer({'foo': foo}, use_colors=False) + self.assertEqual(compl.complete('foo.b', 0), 'foo.bar') + self.assertEqual(foo.calls, 1) + + def test_uncreated_attr(self): + class Foo: + __slots__ = ('bar',) + + compl = Completer({'foo': Foo()}, use_colors=False) + self.assertEqual(compl.complete('foo.', 0), 'foo.bar') + + def test_module_attributes_do_not_reify_lazy_imports(self): + with ready_to_import("test_pyrepl_lazy_mod", "lazy import json\n") as (name, _): + module = importlib.import_module(name) + self.assertIs(type(module.__dict__["json"]), types.LazyImportType) + + compl = Completer({name: module}, use_colors=False) + self.assertEqual(compl.attr_matches(f"{name}.j"), [f"{name}.json"]) + self.assertIs(type(module.__dict__["json"]), types.LazyImportType) + + def test_complete_colored_single_match(self): + """No coloring, via commonprefix.""" + compl = Completer({'foobar': 42}, use_colors=True) + matches = compl.global_matches('foob') + self.assertEqual(matches, ['foobar']) + + def test_does_not_color_single_match(self): + class obj: + msgs = [] + + compl = Completer({'obj': obj}, use_colors=True) + matches = compl.attr_matches('obj.msgs') + self.assertEqual(matches, ['obj.msgs']) + + def test_complete_global(self): + compl = Completer({'foobar': 1, 'foobazzz': 2}, use_colors=False) + self.assertEqual(compl.global_matches('foo'), ['fooba']) + matches = compl.global_matches('fooba') + self.assertEqual(set(matches), set(['foobar', 'foobazzz'])) + self.assertEqual(compl.global_matches('foobaz'), ['foobazzz']) + self.assertEqual(compl.global_matches('nothing'), []) + + def test_complete_global_colored(self): + theme = get_theme() + compl = Completer({'foobar': 1, 'foobazzz': 2}, use_colors=True) + self.assertEqual(compl.global_matches('foo'), ['fooba']) + matches = compl.global_matches('fooba') + + int_color = theme.fancycompleter.int + self.assertEqual(matches, [ + f'{int_color}foobar{ANSIColors.RESET}', + f'{int_color}foobazzz{ANSIColors.RESET}', + ]) + self.assertEqual(compl.global_matches('foobaz'), ['foobazzz']) + self.assertEqual(compl.global_matches('nothing'), []) + + def test_colorized_match_is_stripped(self): + theme = get_theme() + match = _color_for_obj('spam', 1, theme) + self.assertEqual(stripcolor(match), 'spam') + + def test_complete_with_indexer(self): + compl = Completer({'lst': [None, 2, 3]}, use_colors=False) + self.assertEqual(compl.attr_matches('lst[0].'), ['lst[0].__']) + matches = compl.attr_matches('lst[0].__') + self.assertNotIn('__class__', matches) + self.assertIn('lst[0].__class__', matches) + match = compl.attr_matches('lst[0].__class') + self.assertEqual(len(match), 1) + self.assertTrue(match[0].startswith('lst[0].__class__')) + + def test_autocomplete(self): + class A: + aaa = None + abc_1 = None + abc_2 = None + abc_3 = None + bbb = None + compl = Completer({'A': A}, use_colors=False) + # + # In this case, we want to display all attributes which start with + # 'a'. + matches = compl.attr_matches('A.a') + self.assertEqual( + sorted(matches), + ['A.aaa', 'A.abc_1', 'A.abc_2', 'A.abc_3'], + ) + # + # If there is an actual common prefix, we return just it, so that readline + # will insert it into place + matches = compl.attr_matches('A.ab') + self.assertEqual(matches, ['A.abc_']) + # + # Finally, at the next tab, we display again all the completions + # available for this common prefix. + matches = compl.attr_matches('A.abc_') + self.assertEqual( + sorted(matches), + ['A.abc_1', 'A.abc_2', 'A.abc_3'], + ) + + def test_complete_exception(self): + compl = Completer({}, use_colors=False) + self.assertEqual(compl.attr_matches('xxx.'), []) + + def test_complete_invalid_attr(self): + compl = Completer({'str': str}, use_colors=False) + self.assertEqual(compl.attr_matches('str.xx'), []) + + def test_complete_function_skipped(self): + compl = Completer({'str': str}, use_colors=False) + self.assertEqual(compl.attr_matches('str.split().'), []) + + def test_unicode_in___dir__(self): + class Foo(object): + def __dir__(self): + return ['hello', 'world'] + + compl = Completer({'a': Foo()}, use_colors=False) + matches = compl.attr_matches('a.') + self.assertEqual(matches, ['a.hello', 'a.world']) + self.assertIs(type(matches[0]), str) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_pyrepl/test_interact.py b/Lib/test/test_pyrepl/test_interact.py index 7cbe523a92f..fd4530ebc00 100644 --- a/Lib/test/test_pyrepl/test_interact.py +++ b/Lib/test/test_pyrepl/test_interact.py @@ -102,7 +102,6 @@ def test_runsource_returns_false_for_failed_compilation(self): self.assertFalse(result) self.assertIn('SyntaxError', f.getvalue()) - @unittest.expectedFailure # TODO: RUSTPYTHON @force_not_colorized def test_runsource_show_syntax_error_location(self): console = InteractiveColoredConsole() @@ -114,7 +113,7 @@ def test_runsource_show_syntax_error_location(self): r = """ def f(x, x): ... ^ -SyntaxError: duplicate argument 'x' in function definition""" +SyntaxError: duplicate parameter 'x' in function definition""" self.assertIn(r, f.getvalue()) def test_runsource_shows_syntax_error_for_failed_compilation(self): diff --git a/Lib/test/test_pyrepl/test_layout.py b/Lib/test/test_pyrepl/test_layout.py new file mode 100644 index 00000000000..6825659b772 --- /dev/null +++ b/Lib/test/test_pyrepl/test_layout.py @@ -0,0 +1,309 @@ +from unittest import TestCase +from _pyrepl.content import ( + ContentFragment, + ContentLine, + PromptContent, + SourceLine, +) +from _pyrepl.layout import ( + LayoutMap, + LayoutRow, + layout_content_lines, +) + + +def _source(text, lineno=0, start_offset=0, has_newline=True, cursor_index=None): + return SourceLine(lineno, text, start_offset, has_newline, cursor_index) + + +def _prompt(text=">>> ", width=4): + return PromptContent((), text, width) + + +def _body_from_text(text): + return tuple(ContentFragment(ch, 1) for ch in text) + + +def _content_line(text, prompt=None, has_newline=True, start_offset=0): + if prompt is None: + prompt = _prompt() + body = _body_from_text(text) + source = _source(text, start_offset=start_offset, has_newline=has_newline) + return ContentLine(source, prompt, body) + + +class TestLayoutRow(TestCase): + def test_width_basic(self): + row = LayoutRow(4, (1, 1, 1)) + self.assertEqual(row.width, 7) + + def test_width_with_suffix(self): + row = LayoutRow(4, (1, 1), suffix_width=1) + self.assertEqual(row.width, 7) + + def test_screeninfo_without_suffix(self): + row = LayoutRow(4, (1, 1, 1)) + prompt_w, widths = row.screeninfo + self.assertEqual(prompt_w, 4) + self.assertEqual(widths, [1, 1, 1]) + + def test_screeninfo_with_suffix(self): + row = LayoutRow(4, (1, 1), suffix_width=1) + prompt_w, widths = row.screeninfo + self.assertEqual(prompt_w, 4) + self.assertEqual(widths, [1, 1, 1]) + + +class TestLayoutMap(TestCase): + def test_empty(self): + lm = LayoutMap.empty() + self.assertEqual(len(lm.rows), 1) + self.assertEqual(lm.max_row(), 0) + self.assertEqual(lm.max_column(0), 0) + + def test_screeninfo(self): + lm = LayoutMap(( + LayoutRow(4, (1, 1, 1)), + LayoutRow(0, (1, 1)), + )) + info = lm.screeninfo + self.assertEqual(len(info), 2) + self.assertEqual(info[0], (4, [1, 1, 1])) + self.assertEqual(info[1], (0, [1, 1])) + + def test_max_column(self): + lm = LayoutMap((LayoutRow(4, (1, 1, 1)),)) + self.assertEqual(lm.max_column(0), 7) + + def test_max_row(self): + lm = LayoutMap((LayoutRow(0, ()), LayoutRow(0, ()))) + self.assertEqual(lm.max_row(), 1) + + def test_pos_to_xy_empty_rows(self): + lm = LayoutMap(()) + self.assertEqual(lm.pos_to_xy(0), (0, 0)) + + def test_pos_to_xy_single_row(self): + lm = LayoutMap((LayoutRow(4, (1, 1, 1), buffer_advance=3),)) + self.assertEqual(lm.pos_to_xy(0), (4, 0)) + self.assertEqual(lm.pos_to_xy(1), (5, 0)) + self.assertEqual(lm.pos_to_xy(2), (6, 0)) + self.assertEqual(lm.pos_to_xy(3), (7, 0)) + + def test_pos_to_xy_multi_row(self): + lm = LayoutMap(( + LayoutRow(4, (1, 1, 1), buffer_advance=4), + LayoutRow(4, (1, 1), buffer_advance=2), + )) + # First row: pos 0-3 + self.assertEqual(lm.pos_to_xy(0), (4, 0)) + self.assertEqual(lm.pos_to_xy(3), (7, 0)) + # Second row: pos 4-5 + self.assertEqual(lm.pos_to_xy(4), (4, 1)) + self.assertEqual(lm.pos_to_xy(5), (5, 1)) + + def test_pos_to_xy_past_end_clamps(self): + lm = LayoutMap((LayoutRow(4, (1, 1), buffer_advance=2),)) + self.assertEqual(lm.pos_to_xy(99), (6, 0)) + + def test_pos_to_xy_skips_prompt_only_leading_rows(self): + lm = LayoutMap(( + LayoutRow(0, (), buffer_advance=0), # leading prompt-only row + LayoutRow(4, (1, 1), buffer_advance=3), + )) + # pos 0 should skip the leading row and land on the real row + self.assertEqual(lm.pos_to_xy(0), (4, 1)) + + def test_pos_to_xy_with_suffix(self): + lm = LayoutMap(( + LayoutRow(4, (1, 1), suffix_width=1, buffer_advance=2), + LayoutRow(0, (1,), buffer_advance=2), + )) + # pos=2 fits within first row's char_widths (len=2), cursor at end + self.assertEqual(lm.pos_to_xy(2), (6, 0)) + # pos=3 exceeds first row, lands on second row + self.assertEqual(lm.pos_to_xy(3), (1, 1)) + + def test_xy_to_pos_empty_rows(self): + lm = LayoutMap(()) + self.assertEqual(lm.xy_to_pos(0, 0), 0) + + def test_xy_to_pos_single_row(self): + lm = LayoutMap((LayoutRow(4, (1, 1, 1), buffer_advance=3),)) + self.assertEqual(lm.xy_to_pos(4, 0), 0) + self.assertEqual(lm.xy_to_pos(5, 0), 1) + self.assertEqual(lm.xy_to_pos(6, 0), 2) + self.assertEqual(lm.xy_to_pos(7, 0), 3) + + def test_xy_to_pos_multi_row(self): + lm = LayoutMap(( + LayoutRow(4, (1, 1, 1), buffer_advance=4), + LayoutRow(4, (1, 1), buffer_advance=2), + )) + self.assertEqual(lm.xy_to_pos(4, 0), 0) + self.assertEqual(lm.xy_to_pos(4, 1), 4) + self.assertEqual(lm.xy_to_pos(5, 1), 5) + + def test_xy_to_pos_before_prompt_returns_zero(self): + lm = LayoutMap((LayoutRow(4, (1, 1), buffer_advance=2),)) + self.assertEqual(lm.xy_to_pos(0, 0), 0) + + def test_xy_to_pos_with_zero_width_chars(self): + # Simulates combining characters (zero-width) after a base char + lm = LayoutMap((LayoutRow(4, (1, 0, 1), buffer_advance=3),)) + # x=5 is past the first char; trailing zero-width combining is included + self.assertEqual(lm.xy_to_pos(5, 0), 2) + + def test_xy_to_pos_zero_width_skipped(self): + lm = LayoutMap((LayoutRow(0, (0, 1, 1), buffer_advance=3),)) + # x=0: the zero-width char at index 0 is skipped, pos advances + self.assertEqual(lm.xy_to_pos(0, 0), 1) + + def test_xy_to_pos_zero_width_before_target(self): + # Zero-width char between two normal chars; target x is past it + lm = LayoutMap((LayoutRow(0, (1, 0, 1), buffer_advance=3),)) + # x=2: passes char at x=0 (w=1), skips zero-width at x=1, lands at x=2 + self.assertEqual(lm.xy_to_pos(2, 0), 3) + + def test_xy_to_pos_trailing_all_zero_width(self): + # All remaining chars from cursor position are zero-width + lm = LayoutMap((LayoutRow(0, (1, 0), buffer_advance=2),)) + # x=1: past first char, trailing loop exhausts (all remaining are 0-width) + self.assertEqual(lm.xy_to_pos(1, 0), 2) + + +class TestLayoutContentLines(TestCase): + def test_zero_width_returns_empty(self): + result = layout_content_lines((), 0, 0) + self.assertEqual(result.wrapped_rows, ()) + self.assertEqual(result.layout_map.rows, ()) + + def test_negative_width_returns_empty(self): + result = layout_content_lines((), -1, 0) + self.assertEqual(result.wrapped_rows, ()) + + def test_single_short_line(self): + line = _content_line("abc") + result = layout_content_lines((line,), 80, 0) + + self.assertEqual(len(result.wrapped_rows), 1) + row = result.wrapped_rows[0] + self.assertEqual(row.prompt_text, ">>> ") + self.assertEqual(row.prompt_width, 4) + self.assertEqual(row.suffix, "") + self.assertEqual(row.buffer_advance, 4) # 3 chars + newline + + def test_single_line_no_newline(self): + line = _content_line("ab", has_newline=False) + result = layout_content_lines((line,), 80, 0) + + self.assertEqual(len(result.wrapped_rows), 1) + self.assertEqual(result.wrapped_rows[0].buffer_advance, 2) + + def test_empty_body(self): + source = _source("", has_newline=True) + prompt = _prompt() + line = ContentLine(source, prompt, ()) + result = layout_content_lines((line,), 80, 0) + + self.assertEqual(len(result.wrapped_rows), 1) + self.assertEqual(result.wrapped_rows[0].buffer_advance, 1) # just newline + + def test_line_wraps(self): + # prompt ">>> " is 4 wide, terminal is 10 wide, so 6 chars fit per row + line = _content_line("abcdefgh") # 8 chars, needs 2 rows + result = layout_content_lines((line,), 10, 0) + + self.assertEqual(len(result.wrapped_rows), 2) + first, second = result.wrapped_rows + self.assertEqual(first.prompt_text, ">>> ") + self.assertEqual(first.suffix, "\\") + self.assertEqual(first.suffix_width, 1) + # First row: 10 - 4(prompt) - 1(suffix) = 5 chars + self.assertEqual(first.buffer_advance, 5) + # Second row: continuation with no prompt + self.assertEqual(second.prompt_text, "") + self.assertEqual(second.prompt_width, 0) + self.assertEqual(second.buffer_advance, 4) # remaining 3 + newline + self.assertEqual(second.suffix, "") + + def test_wrapping_forces_progress(self): + # When a single character is wider than available space, force 1 char + prompt = _prompt("P", 1) + body = (ContentFragment("W", 1),) + source = _source("W", has_newline=False) + line = ContentLine(source, prompt, body) + # width=2 means prompt(1) + char(1) = 2, which fits (< width would be + # false for width=2 since 1+1 >= 2), so it wraps but forces progress + result = layout_content_lines((line,), 2, 0) + + self.assertEqual(len(result.wrapped_rows), 1) + self.assertEqual(result.wrapped_rows[0].buffer_advance, 1) + + def test_layout_map_matches_wrapped_rows(self): + line = _content_line("abc") + result = layout_content_lines((line,), 80, 0) + + self.assertEqual(len(result.layout_map.rows), len(result.wrapped_rows)) + self.assertEqual(result.layout_map.rows[0].prompt_width, 4) + self.assertEqual(result.layout_map.rows[0].char_widths, (1, 1, 1)) + + def test_line_end_offsets(self): + line1 = _content_line("ab") + line2 = _content_line("cd") + result = layout_content_lines((line1, line2), 80, 0) + + self.assertEqual(len(result.line_end_offsets), 2) + # line1: 2 chars + 1 newline = offset 3 + self.assertEqual(result.line_end_offsets[0], 3) + # line2: offset 3 + 2 chars + 1 newline = 6 + self.assertEqual(result.line_end_offsets[1], 6) + + def test_start_offset_shifts_offsets(self): + line = _content_line("ab") + result = layout_content_lines((line,), 80, 10) + + self.assertEqual(result.line_end_offsets[0], 13) + + def test_multiple_lines(self): + line1 = _content_line("abc") + line2 = _content_line("de") + result = layout_content_lines((line1, line2), 80, 0) + + self.assertEqual(len(result.wrapped_rows), 2) + self.assertEqual(result.wrapped_rows[0].buffer_advance, 4) # abc + \n + self.assertEqual(result.wrapped_rows[1].buffer_advance, 3) # de + \n + + def test_leading_prompt_lines(self): + leading = (ContentFragment("header", 6),) + prompt = PromptContent(leading, ">>> ", 4) + body = _body_from_text("x") + source = _source("x", has_newline=False) + line = ContentLine(source, prompt, body) + result = layout_content_lines((line,), 80, 0) + + # Leading line + body line + self.assertEqual(len(result.wrapped_rows), 2) + # Leading row has the fragment but no prompt + self.assertEqual(result.wrapped_rows[0].fragments, leading) + # Body row has prompt and content + self.assertEqual(result.wrapped_rows[1].prompt_text, ">>> ") + + def test_wrapped_line_layout_rows_have_suffix(self): + line = _content_line("abcdefgh") + result = layout_content_lines((line,), 10, 0) + + first_layout = result.layout_map.rows[0] + self.assertEqual(first_layout.suffix_width, 1) + second_layout = result.layout_map.rows[1] + self.assertEqual(second_layout.suffix_width, 0) + + def test_pos_to_xy_through_layout(self): + line = _content_line("abc") + result = layout_content_lines((line,), 80, 0) + lm = result.layout_map + + self.assertEqual(lm.pos_to_xy(0), (4, 0)) # after prompt + self.assertEqual(lm.pos_to_xy(1), (5, 0)) + self.assertEqual(lm.pos_to_xy(2), (6, 0)) + self.assertEqual(lm.pos_to_xy(3), (7, 0)) # end of line diff --git a/Lib/test/test_pyrepl/test_pyrepl.py b/Lib/test/test_pyrepl/test_pyrepl.py index 4b7579d821c..1f3069f9383 100644 --- a/Lib/test/test_pyrepl/test_pyrepl.py +++ b/Lib/test/test_pyrepl/test_pyrepl.py @@ -1,3 +1,4 @@ +import contextlib import importlib import io import itertools @@ -10,10 +11,18 @@ import subprocess import sys import tempfile +from functools import partial from pkgutil import ModuleInfo -from unittest import TestCase, skipUnless, skipIf, SkipTest +from unittest import TestCase, skipUnless, SkipTest from unittest.mock import Mock, patch -from test.support import force_not_colorized, make_clean_env, Py_DEBUG +import warnings +from test.support import ( + captured_stdout, + captured_stderr, + force_not_colorized, + make_clean_env, + Py_DEBUG, +) from test.support import has_subprocess_support, SHORT_TIMEOUT, STDLIB_DIR from test.support.import_helper import import_module from test.support.os_helper import EnvironmentVarGuard, unlink @@ -27,12 +36,17 @@ multiline_input, code_to_events, ) +from _colorize import ANSIColors, get_theme +from _pyrepl import terminfo from _pyrepl.console import Event +from _pyrepl.completing_reader import stripcolor from _pyrepl._module_completer import ( ImportParser, ModuleCompleter, HARDCODED_SUBMODULES, ) +from _pyrepl.fancycompleter import Completer as FancyCompleter, colorize_matches +import _pyrepl.readline as pyrepl_readline from _pyrepl.readline import ( ReadlineAlikeReader, ReadlineConfig, @@ -50,6 +64,10 @@ import readline as readline_module except ImportError: readline_module = None +try: + import tkinter +except ImportError: + tkinter = None class ReplTestCase(TestCase): @@ -674,6 +692,64 @@ def test_get_line_buffer_returns_str(self): wrapper = _ReadlineWrapper(f_in=None, f_out=None, reader=reader) self.assertIs(type(wrapper.get_line_buffer()), str) + def test_input_does_not_add_history(self): + for history in ([], ["previous input"]): + with self.subTest(history=history): + reader = self.prepare_reader( + code_to_events("first input\nsecond input\n1+1\n") + ) + reader.history[:] = history + wrapper = _ReadlineWrapper(f_in=None, f_out=None, reader=reader) + + self.assertEqual(wrapper.input(), "first input") + self.assertEqual(reader.history, history) + self.assertEqual(wrapper.input(), "second input") + self.assertEqual(reader.history, history) + self.assertEqual(multiline_input(reader), "1+1") + self.assertEqual(reader.history, [*history, "1+1"]) + + def test_input_can_read_history(self): + events = [ + Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), + Event(evt="key", data="\n", raw=bytearray(b"\n")), + ] + reader = self.prepare_reader(events) + reader.history.append("previous input") + wrapper = _ReadlineWrapper(f_in=None, f_out=None, reader=reader) + + self.assertEqual(wrapper.input(), "previous input") + self.assertEqual(reader.history, ["previous input"]) + + def test_input_does_not_modify_history(self): + events = itertools.chain( + [Event(evt="key", data="up", raw=bytearray(b"\x1bOA"))], + code_to_events(" edited"), + [Event(evt="key", data="down", raw=bytearray(b"\x1bOB"))], + code_to_events("new input\n"), + ) + reader = self.prepare_reader(events) + reader.history.append("previous input") + wrapper = _ReadlineWrapper(f_in=None, f_out=None, reader=reader) + + self.assertEqual(wrapper.input(), "new input") + self.assertEqual(reader.history, ["previous input"]) + + def test_input_error_does_not_modify_history(self): + for text, exception in ( + ("partial input\x03", KeyboardInterrupt), + ("\x04", EOFError), + ): + with self.subTest(exception=exception): + reader = self.prepare_reader(code_to_events(text + "1+1\n")) + reader.history.append("previous input") + wrapper = _ReadlineWrapper(f_in=None, f_out=None, reader=reader) + + with self.assertRaises(exception): + wrapper.input() + self.assertEqual(reader.history, ["previous input"]) + self.assertEqual(multiline_input(reader), "1+1") + self.assertEqual(reader.history, ["previous input", "1+1"]) + def test_multiline_edit(self): events = itertools.chain( code_to_events("def f():\n...\n\n"), @@ -758,6 +834,64 @@ def test_history_with_multiline_entries(self): self.assert_screen_equal(reader, expected, clean=True) self.assertEqual(output, expected) + def test_up_arrow_stays_within_recalled_multiline_entry(self): + code = ( + "def fo():\n" + "...\n" + "...\n" + "a = 1\n" + "b = 2\n" + "x = 1\n" + "\n" + "def fo():\n" + "...\n" + "...\n" + "a = 1\n" + "b = 2\n" + "x = 1\n" + "z = 2\n" + "\n" + ) + events = list(itertools.chain( + code_to_events(code), + [ + Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), + Event(evt="key", data="up", raw=bytearray(b"\x1bOA")), + ] + )) + + reader = self.prepare_reader(events) + multiline_input(reader) + multiline_input(reader) + + expected = ( + "def fo():\n" + " ...\n" + " ...\n" + " a = 1\n" + " b = 2\n" + " x = 1\n" + " z = 2" + ) + reader.more_lines = partial(more_lines, namespace=None) + reader.ps1 = reader.ps2 = ">>> " + reader.ps3 = reader.ps4 = "... " + try: + reader.prepare() + reader.refresh() + + reader.handle1() + self.assertEqual(reader.historyi, 1) + self.assertEqual(reader.get_unicode(), expected) + first_cxy = reader.cxy + + reader.handle1() + self.assertEqual(reader.historyi, 1) + self.assertEqual(reader.get_unicode(), expected) + self.assertLess(reader.cxy[1], first_cxy[1]) + finally: + reader.restore() + def test_history_navigation_with_down_arrow(self): events = itertools.chain( @@ -803,12 +937,28 @@ def test_history_search(self): self.assertEqual(output, "1+1") self.assert_screen_equal(reader, "1+1", clean=True) + def test_history_file_embedded_nuls_are_sanitized(self): + reader = self.prepare_reader([]) + wrapper = _ReadlineWrapper(reader=reader, f_in=0, f_out=1) + with tempfile.NamedTemporaryFile("wb", delete=False) as history_file: + history_file.write(b"good\n") + history_file.write(b"ba\0d\n") + history_file.write(b"line1\r\nline2\0\n") + filename = history_file.name + + try: + wrapper.read_history_file(filename) + finally: + unlink(filename) + + self.assertEqual(reader.history, ["good", "bad", "line1\nline2"]) + def test_control_character(self): events = code_to_events("c\x1d\n") reader = self.prepare_reader(events) output = multiline_input(reader) self.assertEqual(output, "c\x1d") - self.assert_screen_equal(reader, "c\x1d", clean=True) + self.assert_screen_equal(reader, "c^]", clean=True) def test_history_search_backward(self): # Test history search backward with "imp" input @@ -943,6 +1093,115 @@ def test_func(self): self.assertEqual(mock_stderr.getvalue(), "") +class TestPyReplFancyCompleter(TestCase): + def prepare_reader(self, events, namespace, *, use_colors): + console = FakeConsole(events) + config = ReadlineConfig() + config.readline_completer = FancyCompleter( + namespace, use_colors=use_colors + ).complete + reader = ReadlineAlikeReader(console=console, config=config) + return reader + + def test_simple_completion_preserves_callable_postfix(self): + events = code_to_events("os.getpid\t\n") + + namespace = {"os": os} + reader = self.prepare_reader(events, namespace, use_colors=False) + + output = multiline_input(reader, namespace) + self.assertEqual(output, "os.getpid()") + + def test_attribute_menu_tracks_typed_stem(self): + class Obj: + apple = 1 + apricot = 2 + banana = 3 + + namespace = {"obj": Obj} + reader = self.prepare_reader( + code_to_events("obj.\t\ta"), + namespace, + use_colors=True, + ) + + with self.assertRaises(StopIteration): + while True: + reader.handle1() + + self.assertEqual("".join(reader.buffer), "obj.a") + self.assertTrue(reader.cmpltn_menu_visible) + menu = "\n".join(reader.cmpltn_menu) + self.assertIn("apple", menu) + self.assertIn("apricot", menu) + self.assertNotIn("banana", menu) + self.assertNotIn("mro", menu) + + def test_get_completions_sorts_colored_matches_by_visible_text(self): + console = FakeConsole(iter(())) + config = ReadlineConfig() + config.readline_completer = FancyCompleter( + { + "foo_str": "value", + "foo_int": 1, + "foo_none": None, + }, + use_colors=True, + ).complete + reader = ReadlineAlikeReader(console=console, config=config) + + matches, action = reader.get_completions("foo_") + + self.assertIsNone(action) + self.assertEqual( + [stripcolor(match) for match in matches], + ["foo_int", "foo_none", "foo_str"], + ) + + +class TestPyReplReadlineSetup(TestCase): + def test_setup_ignores_basic_completer_env_when_env_is_disabled(self): + class FakeFancyCompleter: + def __init__(self, namespace): + self.namespace = namespace + self.use_colors = Mock() + self.theme = Mock() + + def complete(self, text, state): + return None + + class FakeBasicCompleter(FakeFancyCompleter): + pass + + wrapper = Mock() + wrapper.config = ReadlineConfig() + stdin = Mock() + stdout = Mock() + stdin.fileno.return_value = 0 + stdout.fileno.return_value = 1 + + with ( + patch.object(pyrepl_readline, "_wrapper", wrapper), + patch.object(pyrepl_readline, "raw_input", None), + patch.object(pyrepl_readline, "FancyCompleter", FakeFancyCompleter), + patch.object(pyrepl_readline, "RLCompleter", FakeBasicCompleter), + patch.object(pyrepl_readline.sys, "stdin", stdin), + patch.object(pyrepl_readline.sys, "stdout", stdout), + patch.object(pyrepl_readline.sys, "flags", Mock(ignore_environment=True)), + patch.object(pyrepl_readline.os, "isatty", return_value=True), + patch.object(pyrepl_readline.os, "getenv") as mock_getenv, + patch("builtins.input", lambda prompt="": prompt), + ): + mock_getenv.return_value = "1" + pyrepl_readline._setup({}) + + self.assertIsInstance( + wrapper.config.readline_completer.__self__, + FakeFancyCompleter, + ) + mock_getenv.assert_not_called() + + class TestPyReplModuleCompleter(TestCase): def setUp(self): # Make iter_modules() search only the standard library. @@ -964,7 +1223,9 @@ def prepare_reader(self, events, namespace): reader = ReadlineAlikeReader(console=console, config=config) return reader - def test_import_completions(self): + @patch.dict(sys.modules, + {"importlib.resources": object()}) # don't propose to import it + def test_completions(self): cases = ( ("import path\t\n", "import pathlib"), ("import importlib.\t\tres\t\n", "import importlib.resources"), @@ -979,6 +1240,12 @@ def test_import_completions(self): ("from importlib import res\t\n", "from importlib import resources"), ("from importlib.res\t import a\t\n", "from importlib.resources import abc"), ("from __phello__ import s\t\n", "from __phello__ import spam"), # frozen module + ("import importlib .res\t\n", "import importlib .resources"), + ("import importlib. res\t\n", "import importlib. resources"), + ("import importlib . res\t\n", "import importlib . resources"), + ("import importlib .metadata.\t\n", "import importlib .metadata.diagnose"), + ("import importlib .metadata .\t\n", "import importlib .metadata .diagnose"), + ("from importlib .resources .a\t\n", "from importlib .resources .abc"), ) for code, expected in cases: with self.subTest(code=code): @@ -1018,7 +1285,7 @@ def test_sub_module_private_completions(self): # Return public methods by default ("from foo import \t\n", "from foo import public"), # Return private methods if explicitly specified - ("from foo import _\t\n", "from foo import _private"), + ("from foo import _p\t\n", "from foo import _private"), ) for code, expected in cases: with self.subTest(code=code): @@ -1039,12 +1306,13 @@ def test_builtin_completion_top_level(self): output = reader.readline() self.assertEqual(output, expected) - def test_relative_import_completions(self): + def test_relative_completions(self): cases = ( (None, "from .readl\t\n", "from .readl"), (None, "from . import readl\t\n", "from . import readl"), ("_pyrepl", "from .readl\t\n", "from .readline"), ("_pyrepl", "from . import readl\t\n", "from . import readline"), + ("_pyrepl", "from .readline import mul\t\n", "from .readline import multiline_input"), ("_pyrepl", "from .. import toodeep\t\n", "from .. import toodeep"), ("concurrent", "from .futures.i\t\n", "from .futures.interpreter"), ) @@ -1076,7 +1344,7 @@ def test_no_fallback_on_regular_completion(self): cases = ( ("import pri\t\n", "import pri"), ("from pri\t\n", "from pri"), - ("from typing import Na\t\n", "from typing import Na"), + ("from typong import Na\t\n", "from typong import Na"), ) for code, expected in cases: with self.subTest(code=code): @@ -1089,8 +1357,8 @@ def test_global_cache(self): with (tempfile.TemporaryDirectory() as _dir1, patch.object(sys, "path", [_dir1, *sys.path])): dir1 = pathlib.Path(_dir1) - (dir1 / "mod_aa.py").mkdir() - (dir1 / "mod_bb.py").mkdir() + (dir1 / "mod_aa.py").touch() + (dir1 / "mod_bb.py").touch() events = code_to_events("import mod_a\t\nimport mod_b\t\n") reader = self.prepare_reader(events, namespace={}) output_1, output_2 = reader.readline(), reader.readline() @@ -1100,7 +1368,8 @@ def test_global_cache(self): def test_hardcoded_stdlib_submodules(self): cases = ( ("import collections.\t\n", "import collections.abc"), - ("from os import \t\n", "from os import path"), + ("import os.\t\n", "import os.path"), + ("import math.\t\n", "import math.integer"), ("import xml.parsers.expat.\t\te\t\n\n", "import xml.parsers.expat.errors"), ("from xml.parsers.expat import \t\tm\t\n\n", "from xml.parsers.expat import model"), ) @@ -1111,7 +1380,6 @@ def test_hardcoded_stdlib_submodules(self): output = reader.readline() self.assertEqual(output, expected) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_hardcoded_stdlib_submodules_not_proposed_if_local_import(self): with (tempfile.TemporaryDirectory() as _dir, patch.object(sys, "modules", {})): # hide imported module @@ -1214,6 +1482,118 @@ def test_already_imported_module_without_origin_or_spec(self): self.assertEqual(output, f"import {mod}.") del sys.modules[mod] + @patch.dict(sys.modules) + def test_attribute_completion(self): + with tempfile.TemporaryDirectory() as _dir: + dir = pathlib.Path(_dir) + (dir / "foo.py").write_text("bar = 42") + (dir / "bar.py").write_text("baz = 42") + (dir / "pack").mkdir() + (dir / "pack" / "__init__.py").write_text("attr = 42") + (dir / "pack" / "foo.py").touch() + (dir / "pack" / "bar.py").touch() + (dir / "pack" / "baz.py").touch() + sys.modules.pop("graphlib", None) # test modules may have been imported by previous tests + sys.modules.pop("antigravity", None) + sys.modules.pop("unittest.__main__", None) + with patch.object(sys, "path", [_dir, *sys.path]): + pkgutil.get_importer(_dir).invalidate_caches() + importlib.import_module("bar") + cases = ( + # needs 2 tabs to import (show prompt, then import) + ("from foo import \t\n", "from foo import ", set()), + ("from foo import \t\t\n", "from foo import bar", {"foo"}), + ("from foo import ba\t\n", "from foo import ba", set()), + ("from foo import ba\t\t\n", "from foo import bar", {"foo"}), + # reset if a character is inserted between tabs + ("from foo import \tb\ta\t\n", "from foo import ba", set()), + # packages: needs 3 tabs ([ not unique ], prompt, import) + ("from pack import \t\t\n", "from pack import ", set()), + ("from pack import \t\t\t\n", "from pack import ", {"pack"}), + ("from pack import \t\t\ta\t\n", "from pack import attr", {"pack"}), + # one match: needs 2 tabs (insert + show prompt, import) + ("from pack import f\t\n", "from pack import foo", set()), + ("from pack import f\t\t\n", "from pack import foo", {"pack"}), + # common prefix: needs 3 tabs (insert + [ not unique ], prompt, import) + ("from pack import b\t\n", "from pack import ba", set()), + ("from pack import b\t\t\n", "from pack import ba", set()), + ("from pack import b\t\t\t\n", "from pack import ba", {"pack"}), + # module already imported + ("from bar import b\t\n", "from bar import baz", set()), + # stdlib modules are automatically imported + ("from graphlib import T\t\n", "from graphlib import TopologicalSorter", {"graphlib"}), + # except those with known side-effects + ("from antigravity import g\t\n", "from antigravity import g", set()), + ("from unittest.__main__ import \t\n", "from unittest.__main__ import ", set()), + ) + for code, expected, expected_imports in cases: + with self.subTest(code=code), patch.dict(sys.modules): + _imported = set(sys.modules.keys()) + events = code_to_events(code) + reader = self.prepare_reader(events, namespace={}) + output = reader.readline() + self.assertEqual(output, expected) + # The reader imports its own helpers lazily. + new_imports = {name for name in + sys.modules.keys() - _imported + if not name.startswith('_pyrepl.')} + self.assertEqual(new_imports, expected_imports) + + @patch.dict(sys.modules) + def test_attribute_completion_error_on_import(self): + with tempfile.TemporaryDirectory() as _dir: + dir = pathlib.Path(_dir) + (dir / "foo.py").write_text("bar = 42") + (dir / "boom.py").write_text("1 <> 2") + with patch.object(sys, "path", [_dir, *sys.path]): + cases = ( + ("from boom import \t\t\n", "from boom import "), + ("from foo import \t\t\n", "from foo import bar"), # still working + ) + for code, expected in cases: + with self.subTest(code=code): + events = code_to_events(code) + reader = self.prepare_reader(events, namespace={}) + output = reader.readline() + self.assertEqual(output, expected) + self.assertNotIn("boom", sys.modules) + + @patch.dict(sys.modules) + def test_attribute_completion_error_on_attributes_access(self): + with tempfile.TemporaryDirectory() as _dir: + dir = pathlib.Path(_dir) + (dir / "boom").mkdir() + (dir / "boom"/"__init__.py").write_text("def __dir__(): raise ValueError()") + (dir / "boom"/"submodule.py").touch() + with patch.object(sys, "path", [_dir, *sys.path]): + events = code_to_events("from boom import \t\t\n") # trigger import + reader = self.prepare_reader(events, namespace={}) + output = reader.readline() + self.assertIn("boom", sys.modules) + # ignore attributes, just propose submodule + self.assertEqual(output, "from boom import submodule") + + @patch.dict(sys.modules) + def test_attribute_completion_private_and_invalid_names(self): + with tempfile.TemporaryDirectory() as _dir: + dir = pathlib.Path(_dir) + (dir / "foo.py").write_text("_secret = 'bar'") + with patch.object(sys, "path", [_dir, *sys.path]): + mod = importlib.import_module("foo") + mod.__dict__["invalid-identifier"] = "baz" + cases = ( + ("from foo import \t\n", "from foo import "), + ("from foo import _s\t\n", "from foo import _secret"), + ("from foo import inv\t\n", "from foo import inv"), + ) + for code, expected in cases: + with self.subTest(code=code): + events = code_to_events(code) + reader = self.prepare_reader(events, namespace={}) + output = reader.readline() + self.assertEqual(output, expected) + + def test_get_path_and_prefix(self): cases = ( ('', ('', '')), @@ -1236,7 +1616,6 @@ def test_get_path_and_prefix(self): with self.subTest(name=name): self.assertEqual(completer.get_path_and_prefix(name), expected) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_parse(self): cases = ( ('import ', (None, '')), @@ -1258,8 +1637,13 @@ def test_parse(self): ('import a.b.c, foo.bar, ', (None, '')), ('from foo', ('foo', None)), ('from a.', ('a.', None)), + ('from a .', ('a.', None)), + ('from a .', ('a.', None)), + ('from a .', ('a.', None)), ('from a.b', ('a.b', None)), ('from a.b.', ('a.b.', None)), + ('from a. b.', ('a.b.', None)), + ('from a . b .', ('a.b.', None)), ('from a.b.c', ('a.b.c', None)), ('from foo import ', ('foo', '')), ('from foo import a', ('foo', 'a')), @@ -1346,8 +1730,163 @@ def test_parse_error(self): with self.subTest(code=code): self.assertEqual(actual, None) + @patch.dict(sys.modules) + def test_suggestions_and_messages(self) -> None: + # more unitary tests checking the exact suggestions provided + # (sorting, de-duplication, import action...) + _prompt = ("[ module not imported, press again to import it " + "and propose attributes ]") + _error = "[ error during import: division by zero ]" + with tempfile.TemporaryDirectory() as _dir: + dir = pathlib.Path(_dir) + (dir / "foo.py").write_text("bar = 42") + (dir / "boom.py").write_text("1/0") + (dir / "pack").mkdir() + (dir / "pack" / "__init__.py").write_text("foo = 1; bar = 2;") + (dir / "pack" / "bar.py").touch() + sys.modules.pop("graphlib", None) # test modules may have been imported by previous tests + sys.modules.pop("string.templatelib", None) + with patch.object(sys, "path", [_dir, *sys.path]): + pkgutil.get_importer(_dir).invalidate_caches() + # NOTE: Cases are intentionally sequential and share completer + # state. Earlier cases may import modules that later cases + # depend on. Do NOT reorder without understanding dependencies. + cases = ( + # no match != not an import + ("import nope", ([], None), set()), + ("improt nope", None, set()), + # names sorting + ("import col", (["collections", "colorsys"], None), set()), + # module auto-import + ("import fo", (["foo"], None), set()), + ("from foo import ", ([], (_prompt, None)), {"foo"}), + ("from foo import ", (["bar"], None), set()), # now imported + ("from foo import ba", (["bar"], None), set()), + # error during import + ("from boom import ", ([], (_prompt, _error)), set()), + ("from boom import ", ([], None), set()), # do not retry + # packages + ("from collections import a", (["abc"], None), set()), + ("from pack import ", (["bar"], (_prompt, None)), {"pack"}), + ("from pack import ", (["bar", "foo"], None), set()), + ("from pack.bar import ", ([], (_prompt, None)), {"pack.bar"}), + ("from pack.bar import ", ([], None), set()), + # stdlib = auto-imported + ("from graphlib import T", (["TopologicalSorter"], None), {"graphlib"}), + ("from string.templatelib import c", (["convert"], None), {"string.templatelib"}), + ) + completer = ModuleCompleter() + for i, (code, expected, expected_imports) in enumerate(cases): + with self.subTest(code=code, i=i): + _imported = set(sys.modules.keys()) + result = completer.get_completions(code) + self.assertEqual(result is None, expected is None) + if result: + compl, _values, act = result + self.assertEqual(compl, expected[0]) + self.assertEqual(act is None, expected[1] is None) + if act: + msg, func = act + self.assertEqual(msg, expected[1][0]) + act_result = func() + self.assertEqual(act_result, expected[1][1]) + + new_imports = sys.modules.keys() - _imported + self.assertSetEqual(new_imports, expected_imports) + + def test_colorize_import_completions(self) -> None: + theme = get_theme() + type_color = theme.fancycompleter.type + module_color = theme.fancycompleter.module + R = ANSIColors.RESET + + colorize = lambda names, values: colorize_matches(names, values, theme) + config = ReadlineConfig(colorize_completions=colorize) + reader = ReadlineAlikeReader( + console=FakeConsole(events=[]), + config=config, + ) + + # "from collections import de" -> defaultdict (type) and deque (type) + reader.buffer = list("from collections import de") + reader.pos = len(reader.buffer) + names, action = reader.get_module_completions() + self.assertEqual(names, [ + f"{type_color}defaultdict{R}", + f"{type_color}deque{R}", + ]) + self.assertIsNone(action) + + # "from importlib.m" has submodule completions colored as modules + reader.buffer = list("from importlib.m") + reader.pos = len(reader.buffer) + names, action = reader.get_module_completions() + self.assertEqual(names, [ + f"{module_color}importlib.machinery{R}", + f"{module_color}importlib.metadata{R}", + ]) + self.assertIsNone(action) + + # Make sure attributes take precedence over submodules when both exist + # Here we're using `unittest.main` which happens to be both a module and an attribute + reader.buffer = list("from unittest import m") + reader.pos = len(reader.buffer) + names, action = reader.get_module_completions() + self.assertEqual(names, [ + f"{type_color}main{R}", # Ensure that `main` is colored as an attribute (class in this case) + f"{module_color}mock{R}", + ]) + self.assertIsNone(action) + + +# Audit hook used to check for stdlib modules import side-effects +# Defined globally to avoid adding one hook per test run (refleak) +_audit_events: set[str] | None = None + + +def _hook(name: str, _args: tuple): + if _audit_events is not None: # No-op when not activated + _audit_events.add(name) +sys.addaudithook(_hook) + + +@contextlib.contextmanager +def _capture_audit_events(): + global _audit_events + _audit_events = set() + try: + yield _audit_events + finally: + _audit_events = None + + +class TestModuleCompleterAutomaticImports(TestCase): + def test_no_side_effects(self): + from test.test___all__ import AllTest # TODO: extract to a helper? + + completer = ModuleCompleter() + for _, modname in AllTest().walk_modules(completer._stdlib_path, ""): + with self.subTest(modname=modname): + with (captured_stdout() as out, + captured_stderr() as err, + _capture_audit_events() as audit_events, + (patch("tkinter._tkinter.create") if tkinter + else contextlib.nullcontext()) as tk_mock, + warnings.catch_warnings(action="ignore")): + completer._maybe_import_module(modname) + # Test no module is imported that + # 1. prints any text + self.assertEqual(out.getvalue(), "") + self.assertEqual(err.getvalue(), "") + # 2. spawn any subprocess (eg. webbrowser.open) + self.assertNotIn("subprocess.Popen", audit_events) + # 3. launch a Tk window + if tk_mock is not None: + tk_mock.assert_not_called() + class TestHardcodedSubmodules(TestCase): + @patch.dict(sys.modules) def test_hardcoded_stdlib_submodules_are_importable(self): for parent_path, submodules in HARDCODED_SUBMODULES.items(): for module_name in submodules: @@ -1534,8 +2073,20 @@ def test_dumb_terminal_exits_cleanly(self): self.assertNotIn("Traceback", output) +def supports_pyrepl(): + # pyrepl falls back to the basic REPL if the terminal lacks any of the + # capabilities which UnixConsole requires. This covers an unset or + # "dumb" TERM as well, they are resolved to the "dumb" capabilities. + try: + info = terminfo.TermInfo(None) + except Exception: + return False + return all(info.get(cap) is not None + for cap in ("bel", "clear", "cup", "el")) + + @skipUnless(pty, "requires pty") -@skipIf((os.environ.get("TERM") or "dumb") == "dumb", "can't use pyrepl in dumb terminal") +@skipUnless(supports_pyrepl(), "can't use pyrepl in this terminal") class TestMain(ReplTestCase): def setUp(self): # Cleanup from PYTHON* variables to isolate from local @@ -1560,10 +2111,10 @@ def test_exposed_globals_in_repl(self): case2 = f"{pre}, '__doc__', '__file__', {post}" in output # if `__main__` is a cached .pyc file and the .py source exists - case3 = f"{pre}, '__cached__', '__doc__', '__file__', {post}" in output + case3 = f"{pre}, '__doc__', '__file__', {post}" in output # if `__main__` is a cached .pyc file but there's no .py source file - case4 = f"{pre}, '__cached__', '__doc__', {post}" in output + case4 = f"{pre}, '__doc__', {post}" in output self.assertTrue(case1 or case2 or case3 or case4, output) @@ -1935,12 +2486,24 @@ def test_showrefcount(self): matches = re.findall(r'\[-?\d+ refs, \d+ blocks\]', output) self.assertEqual(len(matches), 3) + def test_detect_pip_usage_in_repl(self): + for pip_cmd in ("pip", "pip3", "python -m pip", "python3 -m pip"): + with self.subTest(pip_cmd=pip_cmd): + output, exit_code = self.run_repl([f"{pip_cmd} install sampleproject", "exit"]) + self.assertIn("SyntaxError", output) + hint = ( + "The Python package manager (pip) can only be used" + " outside of the Python REPL" + ) + self.assertIn(hint, output) @force_not_colorized def test_no_newline(self): env = os.environ.copy() env.pop("PYTHON_BASIC_REPL", "") env["PYTHON_BASIC_REPL"] = "1" + # Ensure user's .inputrc doesn't interfere with basic REPL output + env["INPUTRC"] = "/dev/null" commands = "print('Something pretty long', end='')\nexit()\n" expected_output_sequence = "Something pretty long>>> exit()" @@ -2112,12 +2675,13 @@ def test_ctrl_d_single_line_end_no_newline(self): class TestWindowsConsoleEolWrap(TestCase): def _make_mock_console(self, width=80): from _pyrepl import windows_console as wc + from _pyrepl.render import RenderedScreen console = object.__new__(wc.WindowsConsole) console.width = width console.posxy = (0, 0) - console.screen = [""] + console._rendered_screen = RenderedScreen.from_screen_lines([""], (0, 0)) console._hide_cursor = Mock() console._show_cursor = Mock() @@ -2128,25 +2692,29 @@ def _make_mock_console(self, width=80): return console, wc + def _apply_changed_line(self, console, wc, y, old_line, new_line, px=0): + from _pyrepl.render import RenderLine + + old_render = RenderLine.from_rendered_text(old_line) + new_render = RenderLine.from_rendered_text(new_line) + update = wc.WindowsConsole._WindowsConsole__plan_changed_line( + console, y, old_render, new_render, px + ) + if update is not None: + wc.WindowsConsole._WindowsConsole__apply_line_update( + console, update + ) + def test_short_line_sets_posxy_normally(self): width = 10 y = 3 console, wc = self._make_mock_console(width=width) - old_line = "" - new_line = "a" * 3 - wc.WindowsConsole._WindowsConsole__write_changed_line( - console, y, old_line, new_line, 0 - ) + self._apply_changed_line(console, wc, y, "", "a" * 3) self.assertEqual(console.posxy, (3, y)) def test_exact_width_line_does_not_wrap(self): width = 10 y = 3 console, wc = self._make_mock_console(width=width) - old_line = "" - new_line = "a" * width - - wc.WindowsConsole._WindowsConsole__write_changed_line( - console, y, old_line, new_line, 0 - ) + self._apply_changed_line(console, wc, y, "", "a" * width) self.assertEqual(console.posxy, (width - 1, y)) diff --git a/Lib/test/test_pyrepl/test_reader.py b/Lib/test/test_pyrepl/test_reader.py index 51644ec7ce4..8796e6d23ba 100644 --- a/Lib/test/test_pyrepl/test_reader.py +++ b/Lib/test/test_pyrepl/test_reader.py @@ -10,6 +10,8 @@ from .support import ScreenEqualMixin, code_to_events from .support import prepare_reader, prepare_console from _pyrepl.console import Event +from _pyrepl.layout import LayoutMap +from _pyrepl.readline import ReadlineAlikeReader, ReadlineConfig from _pyrepl.reader import Reader from _colorize import default_theme @@ -20,8 +22,48 @@ colors = {overrides.get(k, k[0].lower()): v for k, v in default_theme.syntax.items()} +def prepare_reader_multiline_prompt(*args, **kwargs): + reader = prepare_reader(*args, **kwargs) + del reader.get_prompt + reader.ps1 = "Python 3.15\n>>> " + reader.ps2 = "Python 3.15\n>>> " + reader.ps3 = "Python 3.15\n... " + reader.ps4 = "Python 3.15\n... " + reader.can_colorize = False + reader.paste_mode = False + return reader + + @force_not_colorized_test_class class TestReader(ScreenEqualMixin, TestCase): + def assert_multiline_prompt_screen(self, code, expected_screen, expected_cxy): + reader, _ = handle_all_events( + code_to_events(code), + prepare_reader=prepare_reader_multiline_prompt, + ) + + self.assertEqual(reader.screen, expected_screen) + self.assertEqual(reader.cxy, expected_cxy) + + def test_multiline_prompt_does_not_duplicate_leading_lines(self): + self.assert_multiline_prompt_screen( + "abc", + ["Python 3.15", ">>> abc"], + (7, 1), + ) + + def test_multiline_prompt_does_not_duplicate_leading_lines_across_buffer_lines(self): + self.assert_multiline_prompt_screen( + "if x:\n y", + [ + "Python 3.15", + ">>> if x:", + "Python 3.15", + "... y", + ], + (13, 3), + ) + def test_calc_screen_wrap_simple(self): events = code_to_events(10 * "a") reader, _ = handle_events_narrow_console(events) @@ -104,6 +146,22 @@ def test_calc_screen_backspace(self): reader, _ = handle_all_events(events) self.assert_screen_equal(reader, "aa") + def test_refresh_escapes_control_bytes_in_buffer(self): + console = prepare_console(()) + config = ReadlineConfig(readline_completer=None) + reader = ReadlineAlikeReader(console=console, config=config) + reader.can_colorize = False + reader.ps1 = reader.ps2 = ">>> " + reader.ps3 = reader.ps4 = "... " + reader.buffer = ["\x00", "\x1b"] + reader.pos = len(reader.buffer) + reader.invalidate_full() + + reader.refresh() + + self.assert_screen_equal(reader, ">>> ^@^[") + self.assertEqual(reader.cxy, (8, 0)) + def test_calc_screen_wrap_removes_after_backspace(self): events = itertools.chain( code_to_events(10 * "a"), @@ -178,7 +236,7 @@ def test_up_arrow_after_ctrl_r(self): ) reader, _ = handle_all_events(events) - self.assert_screen_equal(reader, "") + self.assertIn(reader.screen, ([], [""])) def test_newline_within_block_trailing_whitespace(self): # fmt: off @@ -303,6 +361,21 @@ def test_prompt_length(self): self.assertEqual(prompt, "\033[0;32m樂>\033[0m> ") self.assertEqual(l, 5) + def test_prepare_with_zero_width_does_not_crash(self): + console = prepare_console([], width=0) + reader = ReadlineAlikeReader(console=console, config=ReadlineConfig()) + reader.ps1 = ">>> " + reader.ps2 = ">>> " + reader.ps3 = "... " + reader.ps4 = "" + reader.can_colorize = False + reader.paste_mode = False + + reader.prepare() + + self.assertEqual(reader.cxy, (0, 0)) + self.assertEqual(reader.screen, []) + def test_completions_updated_on_key_press(self): namespace = {"itertools": itertools} code = "itertools." @@ -349,8 +422,7 @@ def test_key_press_on_tab_press_once(self): def test_pos2xy_with_no_columns(self): console = prepare_console([]) reader = prepare_reader(console) - # Simulate a resize to 0 columns - reader.screeninfo = [] + reader.layout = LayoutMap(()) self.assertEqual(reader.pos2xy(), (0, 0)) def test_setpos_from_xy_for_non_printing_char(self): @@ -524,7 +596,6 @@ def unfinished_function(): self.assert_screen_equal(reader, code, clean=True) self.assert_screen_equal(reader, expected) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: Lists differ def test_syntax_highlighting_literal_brace_in_fstring_or_tstring(self): code = dedent( """\ diff --git a/Lib/test/test_pyrepl/test_render.py b/Lib/test/test_pyrepl/test_render.py new file mode 100644 index 00000000000..5479f2eb4ba --- /dev/null +++ b/Lib/test/test_pyrepl/test_render.py @@ -0,0 +1,311 @@ +from unittest import TestCase +from _pyrepl.render import ( + LineUpdate, + RenderCell, + RenderLine, + RenderedScreen, + ScreenOverlay, + StyleRef, + diff_render_lines, + render_cells, + requires_cursor_resync, +) + + +class TestRenderLine(TestCase): + def test_from_rendered_text_parses_style_state(self): + line = RenderLine.from_rendered_text("\x1b[31ma\x1b[0mb") + + self.assertEqual(line.width, 2) + self.assertEqual([cell.text for cell in line.cells], ["a", "b"]) + self.assertEqual([cell.style.sgr for cell in line.cells], ["\x1b[31m", ""]) + self.assertEqual([cell.controls for cell in line.cells], [(), ()]) + + def test_from_rendered_text_round_trips_trailing_reset(self): + line = RenderLine.from_rendered_text("\x1b[31ma\x1b[0m") + + self.assertEqual([cell.text for cell in line.cells], ["a"]) + self.assertEqual([cell.style.sgr for cell in line.cells], ["\x1b[31m"]) + self.assertEqual(line.text, "\x1b[31ma\x1b[0m") + + def test_from_parts_accepts_style_refs(self): + line = RenderLine.from_parts( + ["d", "e", "f", " "], + [1, 1, 1, 1], + [StyleRef.from_sgr("\x1b[1;34m")] * 3 + [None], + ) + + self.assertEqual([cell.text for cell in line.cells], ["d", "e", "f", " "]) + self.assertEqual( + [cell.style.sgr for cell in line.cells], + ["\x1b[1;34m", "\x1b[1;34m", "\x1b[1;34m", ""], + ) + self.assertEqual(line.text, "\x1b[1;34mdef\x1b[0m ") + + def test_from_parts_without_styles(self): + line = RenderLine.from_parts(["a", "b"], [1, 1]) + + self.assertEqual(line.text, "ab") + self.assertEqual(line.width, 2) + + def test_from_rendered_text_empty_string(self): + line = RenderLine.from_rendered_text("") + + self.assertEqual(line.cells, ()) + self.assertEqual(line.text, "") + self.assertEqual(line.width, 0) + + def test_from_rendered_text_with_non_sgr_controls(self): + # \x1b[H is a cursor-home control (not SGR since it doesn't end with 'm') + line = RenderLine.from_rendered_text("\x1b[Hx") + + self.assertEqual(len(line.cells), 2) + self.assertEqual(line.cells[0].controls, ("\x1b[H",)) + self.assertEqual(line.cells[0].text, "") + self.assertEqual(line.cells[1].text, "x") + + def test_from_rendered_text_trailing_non_sgr_control(self): + line = RenderLine.from_rendered_text("a\x1b[K") + + self.assertEqual(len(line.cells), 2) + self.assertEqual(line.cells[0].text, "a") + self.assertEqual(line.cells[1].controls, ("\x1b[K",)) + self.assertEqual(line.cells[1].text, "") + + def test_from_rendered_text_non_sgr_before_text(self): + # Non-SGR control immediately before text should produce a control cell + # then text cells. + line = RenderLine.from_rendered_text("\x1b[Kab") + + texts = [c.text for c in line.cells] + self.assertEqual(texts, ["", "a", "b"]) + self.assertEqual(line.cells[0].controls, ("\x1b[K",)) + + +class TestLineDiff(TestCase): + def test_diff_render_lines_ignores_unchanged_ansi_prefix(self): + old = RenderLine.from_rendered_text("\x1b[31ma\x1b[0mb") + new = RenderLine.from_rendered_text("\x1b[31ma\x1b[0mc") + + diff = diff_render_lines(old, new) + + self.assertIsNotNone(diff) + assert diff is not None + self.assertEqual(diff.start_x, 1) + self.assertEqual(diff.old_text, "b") + self.assertEqual(diff.new_text, "c") + + def test_diff_render_lines_detects_single_cell_insertion(self): + old = RenderLine.from_rendered_text("ab") + new = RenderLine.from_rendered_text("acb") + + diff = diff_render_lines(old, new) + + self.assertIsNotNone(diff) + assert diff is not None + self.assertEqual(diff.start_x, 1) + self.assertEqual(diff.old_text, "") + self.assertEqual(diff.new_text, "c") + + def test_colored_append_only_emits_new_character_and_reset(self): + old = RenderLine.from_rendered_text("\x1b[1mabc\x1b[0m") + new = RenderLine.from_rendered_text("\x1b[1mabcd\x1b[0m") + + diff = diff_render_lines(old, new) + + self.assertIsNotNone(diff) + assert diff is not None + self.assertEqual(diff.start_x, 3) + self.assertEqual(render_cells(diff.new_cells), "\x1b[1md\x1b[0m") + + def test_keyword_space_inserts_only_space_after_reset(self): + old = RenderLine.from_parts( + ["d", "e", "f"], + [1, 1, 1], + ["keyword", "keyword", "keyword"], + ) + new = RenderLine.from_parts( + ["d", "e", "f", " "], + [1, 1, 1, 1], + ["keyword", "keyword", "keyword", None], + ) + + diff = diff_render_lines(old, new) + + self.assertIsNotNone(diff) + assert diff is not None + self.assertEqual(diff.start_x, 3) + self.assertEqual(render_cells(diff.new_cells), " ") + + def test_diff_render_lines_returns_none_for_identical(self): + line = RenderLine.from_rendered_text("abc") + self.assertIsNone(diff_render_lines(line, line)) + + def test_diff_render_lines_breaks_on_controls_in_prefix(self): + old = RenderLine.from_cells([ + RenderCell("a", 1), + RenderCell("", 0, controls=("\x1b[K",)), + RenderCell("b", 1), + ]) + new = RenderLine.from_cells([ + RenderCell("a", 1), + RenderCell("", 0, controls=("\x1b[K",)), + RenderCell("c", 1), + ]) + + diff = diff_render_lines(old, new) + + self.assertIsNotNone(diff) + assert diff is not None + # Prefix scan stops at control cell, so diff starts at cell 1 + self.assertEqual(diff.start_cell, 1) + self.assertEqual(diff.start_x, 1) + + def test_diff_render_lines_extends_past_combining_chars(self): + # \u0301 is a combining acute accent (zero-width) + old = RenderLine.from_parts(["a", "b", "\u0301"], [1, 1, 0]) + new = RenderLine.from_parts(["a", "c", "\u0301"], [1, 1, 0]) + + diff = diff_render_lines(old, new) + + self.assertIsNotNone(diff) + assert diff is not None + # The combining char is included since it's zero-width + self.assertEqual(len(diff.new_cells), 2) + + def test_diff_old_and_new_changed_width(self): + old = RenderLine.from_rendered_text("ab") + new = RenderLine.from_rendered_text("acd") + + diff = diff_render_lines(old, new) + + self.assertIsNotNone(diff) + assert diff is not None + self.assertEqual(diff.old_changed_width, 1) + self.assertEqual(diff.new_changed_width, 2) + + def test_rendered_screen_round_trips_screen_lines(self): + screen = RenderedScreen.from_screen_lines( + ["a", "\x1b[31mb\x1b[0m"], + (0, 1), + ) + + self.assertEqual(screen.screen_lines, ("a", "\x1b[31mb\x1b[0m")) + + +class TestRenderedScreen(TestCase): + def test_empty(self): + screen = RenderedScreen.empty() + + self.assertEqual(screen.lines, ()) + self.assertEqual(screen.cursor, (0, 0)) + self.assertEqual(screen.overlays, ()) + self.assertEqual(screen.composed_lines, ()) + + def test_with_overlay(self): + screen = RenderedScreen.from_screen_lines(["aaa", "bbb"], (0, 0)) + overlay_line = RenderLine.from_rendered_text("xxx") + result = screen.with_overlay(1, [overlay_line]) + + self.assertEqual(len(result.overlays), 1) + self.assertEqual(result.composed_lines[0].text, "aaa") + self.assertEqual(result.composed_lines[1].text, "xxx") + + def test_compose_replace_overlay(self): + base = RenderedScreen.from_screen_lines(["aa", "bb", "cc"], (0, 0)) + overlay_line = RenderLine.from_rendered_text("XX") + screen = RenderedScreen( + base.lines, + (0, 0), + (ScreenOverlay(y=1, lines=(overlay_line,)),), + ) + + self.assertEqual(screen.composed_lines[0].text, "aa") + self.assertEqual(screen.composed_lines[1].text, "XX") + self.assertEqual(screen.composed_lines[2].text, "cc") + + def test_compose_insert_overlay(self): + base = RenderedScreen.from_screen_lines(["aa", "bb"], (0, 0)) + overlay_line = RenderLine.from_rendered_text("INS") + screen = RenderedScreen( + base.lines, + (0, 0), + (ScreenOverlay(y=1, lines=(overlay_line,), insert=True),), + ) + + self.assertEqual(len(screen.composed_lines), 3) + self.assertEqual(screen.composed_lines[0].text, "aa") + self.assertEqual(screen.composed_lines[1].text, "INS") + self.assertEqual(screen.composed_lines[2].text, "bb") + + def test_compose_replace_extends_beyond_lines(self): + base = RenderedScreen.from_screen_lines(["aa"], (0, 0)) + overlay_line = RenderLine.from_rendered_text("XX") + screen = RenderedScreen( + base.lines, + (0, 0), + (ScreenOverlay(y=1, lines=(overlay_line,)),), + ) + + self.assertEqual(len(screen.composed_lines), 2) + self.assertEqual(screen.composed_lines[1].text, "XX") + + +class TestRenderCell(TestCase): + def test_terminal_text(self): + cell = RenderCell("x", 1, style=StyleRef.from_sgr("\x1b[32m")) + self.assertEqual(cell.terminal_text, "\x1b[32mx\x1b[0m") + + def test_terminal_text_plain(self): + cell = RenderCell("y", 1) + self.assertEqual(cell.terminal_text, "y") + + +class TestRenderCells(TestCase): + def test_render_cells_with_controls(self): + cells = [ + RenderCell("", 0, controls=("\x1b[K",)), + RenderCell("a", 1), + ] + result = render_cells(cells) + self.assertEqual(result, "\x1b[Ka") + + def test_render_cells_skips_empty_text(self): + cells = [ + RenderCell("", 0), + RenderCell("a", 1), + ] + result = render_cells(cells) + self.assertEqual(result, "a") + + def test_render_cells_with_visual_style(self): + cells = [RenderCell("a", 1)] + result = render_cells(cells, visual_style="\x1b[7m") + self.assertEqual(result, "\x1b[7ma\x1b[0m") + + +class TestLineUpdate(TestCase): + def test_post_init_renders_text(self): + cells = (RenderCell("a", 1), RenderCell("b", 1)) + update = LineUpdate( + kind="insert_char", + y=0, + start_cell=0, + start_x=0, + cells=cells, + ) + self.assertEqual(update.text, "ab") + + +class TestRequiresCursorResync(TestCase): + def test_no_controls(self): + cells = [RenderCell("a", 1)] + self.assertFalse(requires_cursor_resync(cells)) + + def test_sgr_only_does_not_require_resync(self): + cells = [RenderCell("", 0, controls=("\x1b[31m",))] + self.assertFalse(requires_cursor_resync(cells)) + + def test_non_sgr_requires_resync(self): + cells = [RenderCell("", 0, controls=("\x1b[H",))] + self.assertTrue(requires_cursor_resync(cells)) diff --git a/Lib/test/test_pyrepl/test_unix_console.py b/Lib/test/test_pyrepl/test_unix_console.py index 0a25cf5efbb..21baeb84bdd 100644 --- a/Lib/test/test_pyrepl/test_unix_console.py +++ b/Lib/test/test_pyrepl/test_unix_console.py @@ -1,18 +1,21 @@ import errno import itertools import os +import select import signal import sys import threading import unittest from functools import partial -from test.support import os_helper, force_not_colorized_test_class +from _colorize import ANSIColors +from test.support import force_color, os_helper, force_not_colorized_test_class +from test.support import is_android, is_apple_mobile, is_wasm32 from test.support import threading_helper from unittest import TestCase from unittest.mock import MagicMock, call, patch, ANY, Mock -from .support import handle_all_events, code_to_events +from .support import handle_all_events, code_to_events, more_lines try: from _pyrepl.console import Event @@ -57,12 +60,15 @@ def unix_console(events, **kwargs): handle_all_events, prepare_console=partial(unix_console, height=3) ) -def __rustpython_patch_terminfo_tparm(s, *args): - return s + b":" + b",".join(str(i).encode() for i in args) - -def __rustpython_patch_termios_tcgetattr(_): - return [ +@unittest.skipIf(sys.platform == "win32", "No Unix event queue on Windows") +@patch( + "_pyrepl.terminfo.tparm", + lambda s, *args: s + b":" + b",".join(str(i).encode() for i in args), +) +@patch( + "termios.tcgetattr", + lambda _: [ 27394, 3, 19200, @@ -91,63 +97,52 @@ def __rustpython_patch_termios_tcgetattr(_): b"\x14", b"\x00", ], - ] - - -def __rustpython_patch_termios_tcsetattr(a, b, c): - return None - -@unittest.skipIf(sys.platform == "win32", "No Unix event queue on Windows") -@patch( - "_pyrepl.terminfo.tparm", - # TODO: RUSTPYTHON; SyntaxError: the symbol 's' must be present in the symbol table - # lambda s, *args: s + b":" + b",".join(str(i).encode() for i in args), - __rustpython_patch_terminfo_tparm, -) -# TODO: RUSTPYTHON; SyntaxError: no symbol table available in lambda (type: Lambda) -# @patch( -# "termios.tcgetattr", -# lambda _: [ -# 27394, -# 3, -# 19200, -# 536872399, -# 38400, -# 38400, -# [ -# b"\x04", -# b"\xff", -# b"\xff", -# b"\x7f", -# b"\x17", -# b"\x15", -# b"\x12", -# b"\x00", -# b"\x03", -# b"\x1c", -# b"\x1a", -# b"\x19", -# b"\x11", -# b"\x13", -# b"\x16", -# b"\x0f", -# b"\x01", -# b"\x00", -# b"\x14", -# b"\x00", -# ], -# ], -# ) -@patch("termios.tcgetattr", __rustpython_patch_termios_tcgetattr) -@patch( - "termios.tcsetattr", - # TODO: RUSTPYTHON; SyntaxError: no symbol table available in lambda (type: Lambda) - # lambda a, b, c: None - __rustpython_patch_termios_tcsetattr, + ], ) +@patch("termios.tcsetattr", lambda a, b, c: None) @patch("os.write") @force_not_colorized_test_class class TestConsole(TestCase): + @staticmethod + def _prepare_reader_with_prompts(console, **kwargs): + from _pyrepl.readline import ReadlineAlikeReader, ReadlineConfig + + config = ReadlineConfig( + readline_completer=kwargs.pop("readline_completer", None) + ) + reader = ReadlineAlikeReader(console=console, config=config) + reader.paste_mode = False + for key, val in kwargs.items(): + setattr(reader, key, val) + return reader + + def test_colorized_multiline_typing_does_not_redraw_previous_line(self, _os_write): + def prepare_reader_with_prompts(console, **kwargs): + reader = self._prepare_reader_with_prompts(console, **kwargs) + reader.more_lines = partial(more_lines, namespace=None) + return reader + + with force_color(True): + events = itertools.chain( + code_to_events("def foo():"), + [Event(evt="key", data="\n", raw=bytearray(b"\n"))], + code_to_events("x = 1"), + [Event(evt="key", data="\n", raw=bytearray(b"\n"))], + code_to_events("y"), + ) + _, con = handle_all_events( + events, + prepare_console=unix_console, + prepare_reader=prepare_reader_with_prompts, + ) + con.restore() + + self.assertNotIn( + call(ANY, b" \x1b[0m x \x1b[0m=\x1b[0m "), + _os_write.mock_calls, + ) + self.assertIn(call(ANY, b"y"), _os_write.mock_calls) + def test_no_newline(self, _os_write): code = "1" events = code_to_events(code) @@ -155,6 +150,24 @@ def test_no_newline(self, _os_write): self.assertNotIn(call(ANY, b'\n'), _os_write.mock_calls) con.restore() + def test_reset_on_finish(self, _os_write): + # gh-152068: finish() must emit the ANSI reset sequence so any + # active color does not leak past the prompt. + code = "1" + events = code_to_events(code) + _, con = handle_events_unix_console(events) + con.finish() + _os_write.assert_any_call(ANY, ANSIColors.RESET.encode(con.encoding)) + con.restore() + + def test_reset_on_restore(self, _os_write): + # gh-152068: restore() must emit the ANSI reset sequence. + code = "1" + events = code_to_events(code) + _, con = handle_events_unix_console(events) + con.restore() + _os_write.assert_any_call(ANY, ANSIColors.RESET.encode(con.encoding)) + def test_newline(self, _os_write): code = "\n" events = code_to_events(code) @@ -414,3 +427,93 @@ def test_eio_error_handling_in_restore(self, mock_tcgetattr, mock_tcsetattr): # EIO error should be handled gracefully in restore() console.restore() + + +try: + import pty + import termios as _termios +except ImportError: + pty = None + + +@unittest.skipIf(sys.platform == "win32", "No Unix console on Windows") +@unittest.skipUnless(pty, "requires pty") +@unittest.skipIf(is_android or is_apple_mobile or is_wasm32, + "pty is not available on this platform") +class TestUnixConsoleInputHook(TestCase): + # gh-152907: the console must restore cooked output (OPOST) around + # input-hook calls, then re-enter raw mode. + + def test_input_hook_output_is_cooked(self): + master_fd, slave_fd = pty.openpty() + self.addCleanup(os.close, master_fd) + + # tcsetattr(TCSADRAIN) blocks on some platforms (e.g. macOS) while the + # master still holds unread output, so empty it before each mode switch. + def drain(): + out = b"" + while select.select([master_fd], [], [], 0)[0]: + try: + data = os.read(master_fd, 4096) + except OSError: + break + if not data: + break + out += data + return out + + # Start from a cooked terminal so there are saved flags to restore. + attr = _termios.tcgetattr(slave_fd) + attr[1] |= _termios.OPOST | _termios.ONLCR + _termios.tcsetattr(slave_fd, _termios.TCSANOW, attr) + + console = UnixConsole(slave_fd, slave_fd, term="xterm") + console.prepare() + try: + drain() # discard prepare()'s own setup sequences + # pyrepl's own rendering runs with OPOST cleared. + self.assertFalse(_termios.tcgetattr(slave_fd)[1] & _termios.OPOST) + + observed = {} + + def fake_hook(): + observed["oflag"] = _termios.tcgetattr(slave_fd)[1] + os.write(slave_fd, b"line1\nline2\n") + observed["output"] = drain() + return 0 + + with patch("_pyrepl.unix_console.posix") as mock_posix: + mock_posix._is_inputhook_installed.return_value = True + mock_posix._inputhook.side_effect = fake_hook + hook = console.input_hook + self.assertIsNotNone(hook) + self.assertEqual(hook(), 0) + + # The hook ran with cooked output (OPOST on)... + self.assertTrue(observed["oflag"] & _termios.OPOST) + # ...and raw mode was restored afterwards. + self.assertFalse(_termios.tcgetattr(slave_fd)[1] & _termios.OPOST) + # The tty translated the hook's bare '\n' into '\r\n'. + self.assertEqual(observed["output"], b"line1\r\nline2\r\n") + finally: + # restore() writes and only then switches modes, so there is no + # point left to drain from here; keep the master empty elsewhere. + stop = threading.Event() + + def pump(): + while not stop.is_set(): + if select.select([master_fd], [], [], 0.05)[0]: + try: + if not os.read(master_fd, 4096): + break + except OSError: + break + + pump_thread = threading.Thread(target=pump) + pump_thread.start() + try: + console.restore() + finally: + stop.set() + pump_thread.join() + os.close(slave_fd) diff --git a/Lib/test/test_pyrepl/test_utils.py b/Lib/test/test_pyrepl/test_utils.py index 656a1e441e0..e8157f164b3 100644 --- a/Lib/test/test_pyrepl/test_utils.py +++ b/Lib/test/test_pyrepl/test_utils.py @@ -89,10 +89,58 @@ def test_gen_colors_keyword_highlighting(self): ("obj.list", [(".", "op")]), ("obj.match", [(".", "op")]), ("b. \\\n format", [(".", "op")]), + ("lazy", []), + ("lazy()", [('(', 'op'), (')', 'op')]), # highlights ("set", [("set", "builtin")]), ("list", [("list", "builtin")]), (" \n dict", [("dict", "builtin")]), + ( + " lazy import", + [("lazy", "soft_keyword"), ("import", "keyword")], + ), + ( + "lazy from cool_people import pablo", + [ + ("lazy", "soft_keyword"), + ("from", "keyword"), + ("import", "keyword"), + ], + ), + ( + "if sad: lazy import happy", + [ + ("if", "keyword"), + (":", "op"), + ("lazy", "soft_keyword"), + ("import", "keyword"), + ], + ), + ( + "pass; lazy import z", + [ + ("pass", "keyword"), + (";", "op"), + ("lazy", "soft_keyword"), + ("import", "keyword"), + ], + ), + ( + "match +1", + [ + ("match", "soft_keyword"), + ("+", "op"), + ("1", "number"), + ], + ), + ( + "match -1", + [ + ("match", "soft_keyword"), + ("-", "op"), + ("1", "number"), + ], + ), ] for code, expected_highlights in cases: with self.subTest(code=code): diff --git a/Lib/test/test_pyrepl/test_windows_console.py b/Lib/test/test_pyrepl/test_windows_console.py index 52a6f3e595c..32c4255aa6b 100644 --- a/Lib/test/test_pyrepl/test_windows_console.py +++ b/Lib/test/test_pyrepl/test_windows_console.py @@ -6,11 +6,12 @@ import itertools +from _colorize import ANSIColors from functools import partial from test.support import force_not_colorized_test_class from typing import Iterable from unittest import TestCase -from unittest.mock import MagicMock, call +from unittest.mock import MagicMock, call, patch from .support import handle_all_events, code_to_events from .support import prepare_reader as default_prepare_reader @@ -30,7 +31,20 @@ pass +def _mock_console_init(self, f_in=0, f_out=1, term="", encoding="utf-8"): + """Mock __init__ to avoid real Windows API calls in headless environments.""" + super(WindowsConsole, self).__init__(f_in, f_out, term, encoding) + self.width = 80 + self.height = 25 + self._WindowsConsole__offset = 0 + self.posxy = (0, 0) + self._WindowsConsole__vt_support = False + self._WindowsConsole_original_input_mode = 0 + self.event_queue = wc.EventQueue('utf-8') + + @force_not_colorized_test_class +@patch.object(WindowsConsole, '__init__', _mock_console_init) class WindowsConsoleTests(TestCase): def console(self, events, **kwargs) -> Console: console = WindowsConsole() @@ -293,7 +307,8 @@ def same_console(events): call(self.move_left(5)), call(self.move_up()), call(b"def f():"), - call(self.move_left(3)), + call(self.move_left(8)), + call(self.move_right(5)), call(self.move_down()), ] ) @@ -366,7 +381,30 @@ def test_multiline_ctrl_z(self): self.assertEqual(reader.cxy, (2, 3)) con.restore() + def test_reset_on_finish(self): + # gh-152068: finish() must emit the ANSI reset sequence so any + # active color does not leak past the prompt. + code = "1" + events = code_to_events(code) + _, con = self.handle_events(events) + con.finish() + con.out.write.assert_any_call(ANSIColors.RESET.encode(con.encoding)) + con.restore() + + def test_reset_on_restore(self): + # gh-152068: restore() must emit the ANSI reset sequence when VT + # support is enabled. + code = "1" + events = code_to_events(code) + _, con = self.handle_events(events) + con._WindowsConsole__vt_support = True + con._WindowsConsole__original_input_mode = 0 + with patch.object(wc, "SetConsoleMode", return_value=1): + con.restore() + con.out.write.assert_any_call(ANSIColors.RESET.encode(con.encoding)) + +@patch.object(WindowsConsole, '__init__', _mock_console_init) class WindowsConsoleGetEventTests(TestCase): # Virtual-Key Codes: https://learn.microsoft.com/en-us/windows/win32/inputdev/virtual-key-codes VK_BACK = 0x08 @@ -442,7 +480,6 @@ def test_unhandled_events(self): self.assertEqual(self.get_event([ir]), None) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_enter(self): ir = self.get_input_record("\r", self.VK_RETURN) self.assertEqual(self.get_event([ir]), Event("key", "\n")) @@ -454,13 +491,11 @@ def test_backspace(self): self.get_event([ir]), Event("key", "backspace")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_m(self): ir = self.get_input_record("m", self.VK_M) self.assertEqual(self.get_event([ir]), Event("key", "m")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_M(self): ir = self.get_input_record("M", self.VK_M, self.SHIFT_PRESSED) self.assertEqual(self.get_event([ir]), Event("key", "M")) @@ -516,7 +551,6 @@ def test_m_LEFT_ALT_PRESSED_and_LEFT_CTRL_PRESSED(self): self.assertEqual(self.get_event([ir]), None) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_m_LEFT_ALT_PRESSED(self): ir = self.get_input_record( "m", vcode=self.VK_M, control=self.LEFT_ALT_PRESSED) @@ -524,7 +558,6 @@ def test_m_LEFT_ALT_PRESSED(self): self.assertEqual(self.console.get_event(), Event("key", "m")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_m_RIGHT_ALT_PRESSED(self): ir = self.get_input_record( "m", vcode=self.VK_M, control=self.RIGHT_ALT_PRESSED) @@ -532,7 +565,6 @@ def test_m_RIGHT_ALT_PRESSED(self): self.assertEqual(self.console.get_event(), Event("key", "m")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_AltGr_7(self): # E.g. on a German keyboard layout, '{' is entered via # AltGr + 7, where AltGr is the right Alt key on the keyboard. @@ -549,7 +581,6 @@ def test_AltGr_7(self): self.assertEqual(self.get_event([ir]), Event("key", "{")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_AltGr_m(self): # E.g. on a German keyboard layout, this yields 'µ' # Let's use LEFT_ALT_PRESSED and RIGHT_CTRL_PRESSED this @@ -559,7 +590,6 @@ def test_AltGr_m(self): self.assertEqual(self.get_event([ir]), Event("key", "µ")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_umlaut_a_german(self): ir = self.get_input_record("ä", self.VK_OEM_7) self.assertEqual(self.get_event([ir]), Event("key", "ä")) @@ -574,21 +604,18 @@ def test_umlaut_a_german(self): # are sufficient to test here, the real tests happen in test_eventqueue # and test_keymap. - @unittest.expectedFailure # TODO: RUSTPYTHON def test_enter_vt(self): ir = self.get_input_record("\r") self.assertEqual(self.get_event([ir], vt_support=True), Event("key", "\n")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_backspace_vt(self): ir = self.get_input_record("\x7f") self.assertEqual(self.get_event([ir], vt_support=True), Event("key", "backspace", b"\x7f")) self.assertEqual(self.mock.call_count, 1) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_up_vt(self): irs = [self.get_input_record(x) for x in "\x1b[A"] self.assertEqual(self.get_event(irs, vt_support=True), diff --git a/Lib/test/test_queue.py b/Lib/test/test_queue.py index c855fb8fe2b..0bcf326adcc 100644 --- a/Lib/test/test_queue.py +++ b/Lib/test/test_queue.py @@ -2,6 +2,7 @@ # to ensure the Queue locks remain stable. import itertools import random +import struct import threading import time import unittest @@ -9,6 +10,7 @@ from test.support import gc_collect, bigmemtest from test.support import import_helper from test.support import threading_helper +from test import support # queue module depends on threading primitives threading_helper.requires_working_threading(module=True) @@ -954,6 +956,11 @@ def test_negative_timeout_raises_exception(self): with self.assertRaises(ValueError): q.get(timeout=-1) + def test_nonblocking_ignores_timeout(self): + q = self.q + with self.assertRaises(self.queue.Empty): + q.get(block=False, timeout=-1) + def test_order(self): # Test a pair of concurrent put() and get() q = self.q @@ -1031,6 +1038,15 @@ def test_is_default(self): self.assertIs(self.type2test, self.queue.SimpleQueue) self.assertIs(self.type2test, self.queue.SimpleQueue) + @unittest.expectedFailure # TODO: RUSTPYTHON; Rust queue and semaphore layout differs from CPython simplequeueobject + def test_simplequeue_sizeof(self): + q = self.type2test() + basesize = support.calcobjsize('?nnPnnP') + support.check_sizeof(self, q, basesize + struct.calcsize(8 * 'P')) + for _ in range(1000): + q.put(object()) + support.check_sizeof(self, q, basesize + struct.calcsize(1024 * 'P')) + def test_reentrancy(self): # bpo-14976: put() may be called reentrantly in an asynchronous # callback. diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py index c231126d58c..8d093ab1b70 100644 --- a/Lib/test/test_random.py +++ b/Lib/test/test_random.py @@ -14,6 +14,8 @@ from fractions import Fraction from collections import abc, Counter +from test.support import warnings_helper + class MyIndex: def __init__(self, value): @@ -1073,10 +1075,9 @@ def test_avg_std(self): msg='%s%r' % (variate.__name__, args)) self.assertAlmostEqual(s2/(N-1), sigmasqrd, places=2, msg='%s%r' % (variate.__name__, args)) - def test_binomialvariate_log_zero(self): # gh-149222: Variety random() return 0.0 no input Error - with unittest.mock.patch.object(random.Random, 'random', side_effect=[0.0] + [0.5] * 20): + with unittest.mock.patch.object(random.Random, 'random', side_effect= [0.0] + [0.5] * 20): result = random.binomialvariate(10, 0.5) self.assertIsInstance(result, int) self.assertIn(result, range(11)) @@ -1414,6 +1415,7 @@ def test__all__(self): # tests validity but not completeness of the __all__ list self.assertTrue(set(random.__all__) <= set(dir(random))) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @test.support.requires_fork() def test_after_fork(self): # Test the global Random instance gets reseeded in child diff --git a/Lib/test/test_range.py b/Lib/test/test_range.py index c08234a5179..2c9c290e890 100644 --- a/Lib/test/test_range.py +++ b/Lib/test/test_range.py @@ -438,7 +438,6 @@ def test_large_exhausted_iterator_pickling(self): self.assertEqual(list(i), []) self.assertEqual(list(i2), []) - @unittest.skip("TODO: RUSTPYTHON; crash") def test_iterator_unpickle_compat(self): testcases = [ b'c__builtin__\niter\n(c__builtin__\nxrange\n(I10\nI20\nI2\ntRtRI2\nb.', @@ -457,7 +456,6 @@ def test_iterator_unpickle_compat(self): it = pickle.loads(t) self.assertEqual(list(it), [14, 16, 18]) - @unittest.skip("TODO: RUSTPYTHON; crash") def test_iterator_setstate(self): it = iter(range(10, 20, 2)) it.__setstate__(2) diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index 80c21f6b198..062d812c822 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -66,7 +66,6 @@ def checkTemplateError(self, pattern, repl, string, errmsg, pos=None): def test_error_is_PatternError_alias(self): assert re.error is re.PatternError - @unittest.expectedFailure # TODO: RUSTPYTHON def test_keep_buffer(self): # See bug 14212 b = bytearray(b'x') @@ -91,10 +90,13 @@ def test_search_star_plus(self): self.assertEqual(re.search('x+', 'axx').span(), (1, 3)) self.assertIsNone(re.search('x', 'aaa')) self.assertEqual(re.match('a*', 'xxx').span(0), (0, 0)) + self.assertEqual(re.prefixmatch('a*', 'xxx').span(0), (0, 0)) self.assertEqual(re.match('a*', 'xxx').span(), (0, 0)) self.assertEqual(re.match('x*', 'xxxa').span(0), (0, 3)) + self.assertEqual(re.prefixmatch('x*', 'xxxa').span(0), (0, 3)) self.assertEqual(re.match('x*', 'xxxa').span(), (0, 3)) self.assertIsNone(re.match('a+', 'xxx')) + self.assertIsNone(re.prefixmatch('a+', 'xxx')) def test_branching(self): """Test Branching @@ -181,6 +183,7 @@ def test_bug_449000(self): def test_bug_1661(self): # Verify that flags do not get silently ignored with compiled patterns pattern = re.compile('.') + self.assertRaises(ValueError, re.prefixmatch, pattern, 'A', re.I) self.assertRaises(ValueError, re.match, pattern, 'A', re.I) self.assertRaises(ValueError, re.search, pattern, 'A', re.I) self.assertRaises(ValueError, re.findall, pattern, 'A', re.I) @@ -518,6 +521,8 @@ def test_re_match(self): self.assertEqual(re.match(b'(a)', string).group(0), b'a') self.assertEqual(re.match(b'(a)', string).group(1), b'a') self.assertEqual(re.match(b'(a)', string).group(1, 1), (b'a', b'a')) + self.assertEqual(re.prefixmatch(b'(a)', string).group(1, 1), + (b'a', b'a')) for a in ("\xe0", "\u0430", "\U0001d49c"): self.assertEqual(re.match(a, a).groups(), ()) self.assertEqual(re.match('(%s)' % a, a).groups(), (a,)) @@ -559,10 +564,8 @@ def __index__(self): self.assertEqual(m.group(2, 1), ('b', 'a')) self.assertEqual(m.group(Index(2), Index(1)), ('b', 'a')) - def test_match_getitem(self): - pat = re.compile('(?:(?Pa)|(?Pb))(?Pc)?') - - m = pat.match('a') + def do_test_match_getitem(self, match_fn): + m = match_fn('a') self.assertEqual(m['a1'], 'a') self.assertEqual(m['b2'], None) self.assertEqual(m['c3'], None) @@ -586,7 +589,7 @@ def test_match_getitem(self): with self.assertRaisesRegex(IndexError, 'no such group'): 'a1={a2}'.format_map(m) - m = pat.match('ac') + m = match_fn('ac') self.assertEqual(m['a1'], 'a') self.assertEqual(m['b2'], None) self.assertEqual(m['c3'], 'c') @@ -603,6 +606,14 @@ def test_match_getitem(self): # No len(). self.assertRaises(TypeError, len, m) + def test_match_getitem(self): + pat = re.compile('(?:(?Pa)|(?Pb))(?Pc)?') + self.do_test_match_getitem(pat.match) + + def test_prefixmatch_getitem(self): + pat = re.compile('(?:(?Pa)|(?Pb))(?Pc)?') + self.do_test_match_getitem(pat.prefixmatch) + def test_re_fullmatch(self): # Issue 16203: Proposal: add re.fullmatch() method. self.assertEqual(re.fullmatch(r"a", "a").span(), (0, 1)) @@ -1423,7 +1434,6 @@ def test_pickling(self): # current pickle expects the _compile() reconstructor in re module from re import _compile # noqa: F401 - @unittest.expectedFailure # TODO: RUSTPYTHON def test_copying(self): import copy p = re.compile(r'(?P\d+)(?:\.(?P\d*))?') @@ -1641,6 +1651,24 @@ def s_int(scanner, token): return int(token) (['sum', 'op=', 3, 'op*', 'foo', 'op+', 312.5, 'op+', 'bar'], '')) + def test_bug_gh140797(self): + # gh140797: Capturing groups are not allowed in re.Scanner + + msg = r"Cannot use capturing groups in re\.Scanner" + # Capturing group throws an error + with self.assertRaisesRegex(ValueError, msg): + Scanner([("(a)b", None)]) + + # Named Group + with self.assertRaisesRegex(ValueError, msg): + Scanner([("(?Pa)", None)]) + + # Non-capturing groups should pass normally + s = Scanner([("(?:a)b", lambda scanner, token: token)]) + result, rem = s.scan("ab") + self.assertEqual(result,['ab']) + self.assertEqual(rem,'') + def test_bug_448951(self): # bug 448951 (similar to 429357, but with single char match) # (Also test greedy matches.) @@ -1922,6 +1950,28 @@ def test_locale_flag(self): self.assertRaises(ValueError, re.compile, b'(?a)', re.LOCALE) self.assertRaises(re.PatternError, re.compile, b'(?aL)') + def test_locale_ignorecase_negated_set(self): + IL = re.LOCALE | re.IGNORECASE + # [bc] matches b'B', so [^bc] must not. + self.assertTrue(re.fullmatch(rb'[bc]', b'B', IL)) + self.assertIsNone(re.fullmatch(rb'[^bc]', b'B', IL)) + self.assertIsNone(re.fullmatch(rb'[^b-c]', b'C', IL)) + self.assertIsNone(re.fullmatch(rb'[^bc]', b'c', IL)) + self.assertTrue(re.fullmatch(rb'[^bc]', b'a', IL)) + # A one-member set compiles to NOT_LITERAL_LOC_IGNORE. + self.assertIsNone(re.fullmatch(rb'[^b]', b'B', IL)) + self.assertTrue(re.fullmatch(rb'[^b]', b'a', IL)) + self.assertIsNone(re.fullmatch(rb'[^\wq]', b'Q', IL)) + # A sparse set compiles to a bitmap instead of ranges. + self.assertTrue(re.fullmatch(rb'[ace]', b'C', IL)) + self.assertIsNone(re.fullmatch(rb'[^ace]', b'C', IL)) + self.assertTrue(re.fullmatch(rb'[^ace]', b'b', IL)) + # An alternation folded into a set puts NEGATE in the middle of it. + self.assertIsNone(re.fullmatch(rb'(?:a|[^bc])', b'B', IL)) + self.assertTrue(re.fullmatch(rb'(?:a|[^bc])', b'A', IL)) + self.assertIsNone(re.fullmatch(rb'\w(? "t\xEBxt" + input += b"\r" + output = run_pty(script, input) + self.assertIn(b"text 't\\xeb'\r\n", output) + self.assertIn(b"line '[\\xefnserted]|t\\xeb[after]'\r\n", output) + if sys.platform == "darwin" or not is_editline: + self.assertIn(b"indexes 11 13\r\n", output) + # Non-macOS libedit does not handle non-ASCII bytes + # the same way and generates character indices + # rather than byte indices via get_begidx() and + # get_endidx(). Ex: libedit2 3.1-20191231-2 on Debian + # winds up with "indexes 10 12". Stemming from the + # start and end values calls back into readline.c's + # rl_attempted_completion_function = flex_complete with: + # (11, 13) instead of libreadline's (12, 15). + + if not is_editline and hasattr(readline, "set_pre_input_hook"): + self.assertIn(b"substitution 't\\xeb'\r\n", output) + self.assertIn(b"matches ['t\\xebnt', 't\\xebxt']\r\n", output) + expected = br"'[\xefnserted]|t\xebxt[after]'" + self.assertIn(b"result " + expected + b"\r\n", output) + # bpo-45195: Sometimes, the newline character is not written at the + # end, so don't expect it in the output. + self.assertIn(b"history " + expected, output) + + # We have 2 reasons to skip this test: + # - readline: history size was added in 6.0 + # See https://cnswww.cns.cwru.edu/php/chet/readline/CHANGES + # - editline: history size is broken on OS X 10.11.6. + # Newer versions were not tested yet. + @unittest.skipIf(readline._READLINE_VERSION < 0x600, + "this readline version does not support history-size") + @unittest.skipIf(is_editline, + "editline history size configuration is broken") + def test_history_size(self): + history_size = 10 + with temp_dir() as test_dir: + inputrc = os.path.join(test_dir, "inputrc") + with open(inputrc, "wb") as f: + f.write(b"set history-size %d\n" % history_size) + + history_file = os.path.join(test_dir, "history") + with open(history_file, "wb") as f: + # history_size * 2 items crashes readline + data = b"".join(b"item %d\n" % i + for i in range(history_size * 2)) + f.write(data) + + script = """ +import os +import readline + +history_file = os.environ["HISTORY_FILE"] +readline.read_history_file(history_file) +input() +readline.write_history_file(history_file) +""" + + env = dict(os.environ) + env["INPUTRC"] = inputrc + env["HISTORY_FILE"] = history_file + + run_pty(script, input=b"last input\r", env=env) + + with open(history_file, "rb") as f: + lines = f.readlines() + self.assertEqual(len(lines), history_size) + self.assertEqual(lines[-1].strip(), b"last input") + + @requires_working_threading() + def test_gh123321_threadsafe(self): + """gh-123321: readline should be thread-safe and not crash""" + script = textwrap.dedent(r""" + import threading + from test.support.threading_helper import join_thread + + def func(): + input() + + thread1 = threading.Thread(target=func) + thread2 = threading.Thread(target=func) + thread1.start() + thread2.start() + join_thread(thread1) + join_thread(thread2) + print("done") + """) + + output = run_pty(script, input=b"input1\rinput2\r") + + self.assertIn(b"done", output) + + + def test_write_read_limited_history(self): + previous_length = readline.get_history_length() + self.addCleanup(readline.set_history_length, previous_length) + + readline.add_history("first line") + readline.add_history("second line") + readline.add_history("third line") + + readline.set_history_length(2) + self.assertEqual(readline.get_history_length(), 2) + readline.write_history_file(TESTFN) + self.addCleanup(os.remove, TESTFN) + + readline.read_history_file(TESTFN) + # Without clear_history() there's no good way to test if + # the correct entries are present (we're combining history limiting and + # possible deduplication with arbitrary previous content). + # So, we've only tested that the read did not fail. + # See TestHistoryManipulation for the full test. + + @unittest.skipUnless(hasattr(readline, "get_pre_input_hook"), + "get_pre_input_hook not available") + def test_get_pre_input_hook(self): + # Save and restore the original hook to avoid side effects + original_hook = readline.get_pre_input_hook() + self.addCleanup(readline.set_pre_input_hook, original_hook) + + # Test that get_pre_input_hook returns None when no hook is set + readline.set_pre_input_hook(None) + self.assertIsNone(readline.get_pre_input_hook()) + + # Set a hook and verify we can retrieve it + def my_hook(): + pass + + readline.set_pre_input_hook(my_hook) + self.assertIs(readline.get_pre_input_hook(), my_hook) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_regrtest.py b/Lib/test/test_regrtest.py index 6f465b73f4b..60463c7803f 100644 --- a/Lib/test/test_regrtest.py +++ b/Lib/test/test_regrtest.py @@ -166,21 +166,20 @@ def test_randomize(self): ns = self.parse_args([opt]) self.assertTrue(ns.randomize) - with os_helper.EnvironmentVarGuard() as env: - # with SOURCE_DATE_EPOCH - env['SOURCE_DATE_EPOCH'] = '1697839080' - ns = self.parse_args(['--randomize']) - regrtest = main.Regrtest(ns) - self.assertFalse(regrtest.randomize) - self.assertIsInstance(regrtest.random_seed, str) - self.assertEqual(regrtest.random_seed, '1697839080') - - # without SOURCE_DATE_EPOCH - del env['SOURCE_DATE_EPOCH'] - ns = self.parse_args(['--randomize']) - regrtest = main.Regrtest(ns) - self.assertTrue(regrtest.randomize) - self.assertIsInstance(regrtest.random_seed, int) + @os_helper.with_source_date_epoch(epoch=1697839080) + def test_randomize_with_source_date_epoch(self): + ns = self.parse_args(['--randomize']) + regrtest = main.Regrtest(ns) + self.assertFalse(regrtest.randomize) + self.assertIsInstance(regrtest.random_seed, str) + self.assertEqual(regrtest.random_seed, '1697839080') + + @os_helper.without_source_date_epoch + def test_randomize_without_source_date_epoch(self): + ns = self.parse_args(['--randomize']) + regrtest = main.Regrtest(ns) + self.assertTrue(regrtest.randomize) + self.assertIsInstance(regrtest.random_seed, int) def test_no_randomize(self): ns = self.parse_args([]) @@ -571,6 +570,13 @@ def test_single_process(self): self.assertEqual(regrtest.num_workers, 0) self.assertTrue(regrtest.single_process) + def test_pythoninfo(self): + ns = self.parse_args([]) + self.assertFalse(ns.pythoninfo) + + ns = self.parse_args(['--pythoninfo']) + self.assertTrue(ns.pythoninfo) + @dataclasses.dataclass(slots=True) class Rerun: @@ -705,9 +711,13 @@ def list_regex(line_format, tests): self.check_line(output, regex) if env_changed: - regex = list_regex(r'%s test%s altered the execution environment ' - r'\(env changed\)', - env_changed) + # Every test is listed on a separate line, followed by the + # reasons why the environment was altered, one per line. + count = len(env_changed) + regex = (r'%s test%s altered the execution environment ' + r'\(env changed\):\n' % (count, plural(count))) + regex += ''.join(r' %s:?\n(?: .*\n)*' % re.escape(name) + for name in sorted(env_changed)) self.check_line(output, regex) if omitted: @@ -796,7 +806,8 @@ def list_regex(line_format, tests): state = ', '.join(state) if rerun is not None: new_state = 'SUCCESS' if rerun.success else 'FAILURE' - state = f'{state} then {new_state}' + if new_state != state: + state = f'{state} then {new_state}' self.check_line(output, f'Result: {state}', full=True) def parse_random_seed(self, output: str) -> str: @@ -1896,7 +1907,6 @@ def test_sleep(self): self.assertRegex(output, re.compile('%s timed out' % testname, re.MULTILINE)) - @unittest.expectedFailure # TODO: RUSTPYTHON; test_unraisable_exc (test_regrtest_noop39.Tests.test_unraisable_exc) ... ok def test_unraisable_exc(self): # --fail-env-changed must catch unraisable exception. # The exception must be displayed even if sys.stderr is redirected. @@ -2141,7 +2151,7 @@ def load_tests(loader, tests, pattern): self.check_executed_tests(output, [testname], failed=[testname], parallel=True, - stats=TestStats(1, 1, 0)) + stats=TestStats(1, 2, 1)) def _check_random_seed(self, run_workers: bool): # gh-109276: When -r/--randomize is used, random.seed() is called @@ -2281,7 +2291,6 @@ def test_python_opts(self): env=support.make_clean_env()) self.assertEqual(proc.returncode, 0, proc) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_add_python_opts(self): for opt in ("--fast-ci", "--slow-ci"): with self.subTest(opt=opt): @@ -2428,6 +2437,11 @@ def test_pgo_exclude(self): self.assertNotIn('test_re', tests) self.assertEqual(len(tests), len(pgo_tests) - 1) + def test_pythoninfo(self): + testname = self.create_test() + output = self.run_tests('--pythoninfo', testname) + self.assertIn("Python build information", output) + class TestUtils(unittest.TestCase): def test_format_duration(self): diff --git a/Lib/test/test_remote_pdb.py b/Lib/test/test_remote_pdb.py new file mode 100644 index 00000000000..e5387526090 --- /dev/null +++ b/Lib/test/test_remote_pdb.py @@ -0,0 +1,1754 @@ +import io +import itertools +import json +import os +import re +import signal +import socket +import subprocess +import sys +import textwrap +import threading +import unittest +import unittest.mock +from contextlib import closing, contextmanager, redirect_stdout, redirect_stderr, ExitStack +from test.support import is_wasi, cpython_only, force_color, requires_subprocess, SHORT_TIMEOUT, subTests +from test.support.os_helper import TESTFN, unlink +from typing import List + +import pdb +from pdb import _PdbServer, _PdbClient + +try: + import pty +except ImportError: + pty = None + + +if not sys.is_remote_debug_enabled(): + raise unittest.SkipTest('remote debugging is disabled') + + +@contextmanager +def kill_on_error(proc): + """Context manager killing the subprocess if a Python exception is raised.""" + with proc: + try: + yield proc + except: + proc.kill() + raise + + +class MockSocketFile: + """Mock socket file for testing _PdbServer without actual socket connections.""" + + def __init__(self): + self.input_queue = [] + self.output_buffer = [] + + def write(self, data: bytes) -> None: + """Simulate write to socket.""" + self.output_buffer.append(data) + + def flush(self) -> None: + """No-op flush implementation.""" + pass + + def readline(self) -> bytes: + """Read a line from the prepared input queue.""" + if not self.input_queue: + return b"" + return self.input_queue.pop(0) + + def close(self) -> None: + """Close the mock socket file.""" + pass + + def add_input(self, data: dict) -> None: + """Add input that will be returned by readline.""" + self.input_queue.append(json.dumps(data).encode() + b"\n") + + def get_output(self) -> List[dict]: + """Get the output that was written by the object being tested.""" + results = [] + for data in self.output_buffer: + if isinstance(data, bytes) and data.endswith(b"\n"): + try: + results.append(json.loads(data.decode().strip())) + except json.JSONDecodeError: + pass # Ignore non-JSON output + self.output_buffer = [] + return results + + +class PdbClientTestCase(unittest.TestCase): + """Tests for the _PdbClient class.""" + + def do_test( + self, + *, + incoming, + simulate_send_failure=False, + simulate_sigint_during_stdout_write=False, + use_interrupt_socket=False, + expected_outgoing=None, + expected_outgoing_signals=None, + expected_completions=None, + expected_exception=None, + expected_stdout="", + expected_stdout_substring="", + expected_state=None, + ): + if expected_outgoing is None: + expected_outgoing = [] + if expected_outgoing_signals is None: + expected_outgoing_signals = [] + if expected_completions is None: + expected_completions = [] + if expected_state is None: + expected_state = {} + + expected_state.setdefault("write_failed", False) + messages = [m for source, m in incoming if source == "server"] + prompts = [m["prompt"] for source, m in incoming if source == "user"] + + input_iter = (m for source, m in incoming if source == "user") + completions = [] + + def mock_input(prompt): + message = next(input_iter, None) + if message is None: + raise EOFError + + if req := message.get("completion_request"): + readline_mock = unittest.mock.Mock() + readline_mock.get_line_buffer.return_value = req["line"] + readline_mock.get_begidx.return_value = req["begidx"] + readline_mock.get_endidx.return_value = req["endidx"] + unittest.mock.seal(readline_mock) + with unittest.mock.patch.dict(sys.modules, {"readline": readline_mock}): + for param in itertools.count(): + prefix = req["line"][req["begidx"] : req["endidx"]] + completion = client.complete(prefix, param) + if completion is None: + break + completions.append(completion) + + reply = message["input"] + if isinstance(reply, BaseException): + raise reply + if isinstance(reply, str): + return reply + return reply() + + with ExitStack() as stack: + client_sock, server_sock = socket.socketpair() + stack.enter_context(closing(client_sock)) + stack.enter_context(closing(server_sock)) + + server_sock = unittest.mock.Mock(wraps=server_sock) + + client_sock.sendall( + b"".join( + (m if isinstance(m, bytes) else json.dumps(m).encode()) + b"\n" + for m in messages + ) + ) + client_sock.shutdown(socket.SHUT_WR) + + if simulate_send_failure: + server_sock.sendall = unittest.mock.Mock( + side_effect=OSError("sendall failed") + ) + client_sock.shutdown(socket.SHUT_RD) + + stdout = io.StringIO() + + if simulate_sigint_during_stdout_write: + orig_stdout_write = stdout.write + + def sigint_stdout_write(s): + signal.raise_signal(signal.SIGINT) + return orig_stdout_write(s) + + stdout.write = sigint_stdout_write + + input_mock = stack.enter_context( + unittest.mock.patch("pdb.input", side_effect=mock_input) + ) + stack.enter_context(redirect_stdout(stdout)) + + if use_interrupt_socket: + interrupt_sock = unittest.mock.Mock(spec=socket.socket) + mock_kill = None + else: + interrupt_sock = None + mock_kill = stack.enter_context( + unittest.mock.patch("os.kill", spec=os.kill) + ) + + client = _PdbClient( + pid=12345, + server_socket=server_sock, + interrupt_sock=interrupt_sock, + ) + + if expected_exception is not None: + exception = expected_exception["exception"] + msg = expected_exception["msg"] + stack.enter_context(self.assertRaises(exception, msg=msg)) + + client.cmdloop() + + sent_msgs = [msg.args[0] for msg in server_sock.sendall.mock_calls] + for msg in sent_msgs: + assert msg.endswith(b"\n") + actual_outgoing = [json.loads(msg) for msg in sent_msgs] + + self.assertEqual(actual_outgoing, expected_outgoing) + self.assertEqual(completions, expected_completions) + if expected_stdout_substring and not expected_stdout: + self.assertIn(expected_stdout_substring, stdout.getvalue()) + else: + self.assertEqual(stdout.getvalue(), expected_stdout) + input_mock.assert_has_calls([unittest.mock.call(p) for p in prompts]) + actual_state = {k: getattr(client, k) for k in expected_state} + self.assertEqual(actual_state, expected_state) + + if use_interrupt_socket: + outgoing_signals = [ + signal.Signals(int.from_bytes(call.args[0])) + for call in interrupt_sock.sendall.call_args_list + ] + else: + assert mock_kill is not None + outgoing_signals = [] + for call in mock_kill.call_args_list: + pid, signum = call.args + self.assertEqual(pid, 12345) + outgoing_signals.append(signal.Signals(signum)) + self.assertEqual(outgoing_signals, expected_outgoing_signals) + + def test_remote_immediately_closing_the_connection(self): + """Test the behavior when the remote closes the connection immediately.""" + incoming = [] + expected_outgoing = [] + self.do_test( + incoming=incoming, + expected_outgoing=expected_outgoing, + ) + + def test_handling_command_list(self): + """Test handling the command_list message.""" + incoming = [ + ("server", {"command_list": ["help", "list", "continue"]}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_state={ + "pdb_commands": {"help", "list", "continue"}, + }, + ) + + def test_handling_info_message(self): + """Test handling a message payload with type='info'.""" + incoming = [ + ("server", {"message": "Some message or other\n", "type": "info"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_stdout="Some message or other\n", + ) + + def test_handling_error_message(self): + """Test handling a message payload with type='error'.""" + incoming = [ + ("server", {"message": "Some message or other.", "type": "error"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_stdout="*** Some message or other.\n", + ) + + def test_handling_other_message(self): + """Test handling a message payload with an unrecognized type.""" + incoming = [ + ("server", {"message": "Some message.\n", "type": "unknown"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_stdout="Some message.\n", + ) + + @unittest.skipIf(sys.flags.optimize >= 2, "Help not available for -OO") + @subTests( + "help_request,expected_substring", + [ + # a request to display help for a command + ({"help": "ll"}, "Usage: ll | longlist"), + # a request to display a help overview + ({"help": ""}, "type help "), + # a request to display the full PDB manual + ({"help": "pdb"}, ">>> import pdb"), + ], + ) + def test_handling_help_when_available(self, help_request, expected_substring): + """Test handling help requests when help is available.""" + incoming = [ + ("server", help_request), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_stdout_substring=expected_substring, + ) + + @unittest.skipIf(sys.flags.optimize < 2, "Needs -OO") + @subTests( + "help_request,expected_substring", + [ + # a request to display help for a command + ({"help": "ll"}, "No help for 'll'"), + # a request to display a help overview + ({"help": ""}, "Undocumented commands"), + # a request to display the full PDB manual + ({"help": "pdb"}, "No help for 'pdb'"), + ], + ) + def test_handling_help_when_not_available(self, help_request, expected_substring): + """Test handling help requests when help is not available.""" + incoming = [ + ("server", help_request), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_stdout_substring=expected_substring, + ) + + def test_handling_pdb_prompts(self): + """Test responding to pdb's normal prompts.""" + incoming = [ + ("server", {"command_list": ["b"]}), + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": "lst ["}), + ("user", {"prompt": "... ", "input": "0 ]"}), + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": ""}), + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": "b ["}), + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": "! b ["}), + ("user", {"prompt": "... ", "input": "b ]"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"reply": "lst [\n0 ]"}, + {"reply": ""}, + {"reply": "b ["}, + {"reply": "!b [\nb ]"}, + ], + expected_state={"state": "pdb"}, + ) + + def test_handling_interact_prompts(self): + """Test responding to pdb's interact mode prompts.""" + incoming = [ + ("server", {"command_list": ["b"]}), + ("server", {"prompt": ">>> ", "state": "interact"}), + ("user", {"prompt": ">>> ", "input": "lst ["}), + ("user", {"prompt": "... ", "input": "0 ]"}), + ("server", {"prompt": ">>> ", "state": "interact"}), + ("user", {"prompt": ">>> ", "input": ""}), + ("server", {"prompt": ">>> ", "state": "interact"}), + ("user", {"prompt": ">>> ", "input": "b ["}), + ("user", {"prompt": "... ", "input": "b ]"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"reply": "lst [\n0 ]"}, + {"reply": ""}, + {"reply": "b [\nb ]"}, + ], + expected_state={"state": "interact"}, + ) + + def test_retry_pdb_prompt_on_syntax_error(self): + """Test re-prompting after a SyntaxError in a Python expression.""" + incoming = [ + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": " lst ["}), + ("user", {"prompt": "(Pdb) ", "input": "lst ["}), + ("user", {"prompt": "... ", "input": " 0 ]"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"reply": "lst [\n 0 ]"}, + ], + expected_stdout_substring="*** IndentationError", + expected_state={"state": "pdb"}, + ) + + def test_retry_interact_prompt_on_syntax_error(self): + """Test re-prompting after a SyntaxError in a Python expression.""" + incoming = [ + ("server", {"prompt": ">>> ", "state": "interact"}), + ("user", {"prompt": ">>> ", "input": "!lst ["}), + ("user", {"prompt": ">>> ", "input": "lst ["}), + ("user", {"prompt": "... ", "input": " 0 ]"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"reply": "lst [\n 0 ]"}, + ], + expected_stdout_substring="*** SyntaxError", + expected_state={"state": "interact"}, + ) + + def test_handling_unrecognized_prompt_type(self): + """Test fallback to "dumb" single-line mode for unknown states.""" + incoming = [ + ("server", {"prompt": "Do it? ", "state": "confirm"}), + ("user", {"prompt": "Do it? ", "input": "! ["}), + ("server", {"prompt": "Do it? ", "state": "confirm"}), + ("user", {"prompt": "Do it? ", "input": "echo hello"}), + ("server", {"prompt": "Do it? ", "state": "confirm"}), + ("user", {"prompt": "Do it? ", "input": ""}), + ("server", {"prompt": "Do it? ", "state": "confirm"}), + ("user", {"prompt": "Do it? ", "input": "echo goodbye"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"reply": "! ["}, + {"reply": "echo hello"}, + {"reply": ""}, + {"reply": "echo goodbye"}, + ], + expected_state={"state": "dumb"}, + ) + + def test_sigint_at_prompt(self): + """Test signaling when a prompt gets interrupted.""" + incoming = [ + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ( + "user", + { + "prompt": "(Pdb) ", + "input": lambda: signal.raise_signal(signal.SIGINT), + }, + ), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"signal": "INT"}, + ], + expected_state={"state": "pdb"}, + ) + + def test_sigint_at_continuation_prompt(self): + """Test signaling when a continuation prompt gets interrupted.""" + incoming = [ + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": "if True:"}), + ( + "user", + { + "prompt": "... ", + "input": lambda: signal.raise_signal(signal.SIGINT), + }, + ), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"signal": "INT"}, + ], + expected_state={"state": "pdb"}, + ) + + def test_sigint_when_writing(self): + """Test siginaling when sys.stdout.write() gets interrupted.""" + incoming = [ + ("server", {"message": "Some message or other\n", "type": "info"}), + ] + for use_interrupt_socket in [False, True]: + with self.subTest(use_interrupt_socket=use_interrupt_socket): + self.do_test( + incoming=incoming, + simulate_sigint_during_stdout_write=True, + use_interrupt_socket=use_interrupt_socket, + expected_outgoing=[], + expected_outgoing_signals=[signal.SIGINT], + expected_stdout="Some message or other\n", + ) + + def test_eof_at_prompt(self): + """Test signaling when a prompt gets an EOFError.""" + incoming = [ + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": EOFError()}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"signal": "EOF"}, + ], + expected_state={"state": "pdb"}, + ) + + def test_unrecognized_json_message(self): + """Test failing after getting an unrecognized payload.""" + incoming = [ + ("server", {"monty": "python"}), + ("server", {"message": "Some message or other\n", "type": "info"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_exception={ + "exception": RuntimeError, + "msg": 'Unrecognized payload b\'{"monty": "python"}\'', + }, + ) + + def test_continuing_after_getting_a_non_json_payload(self): + """Test continuing after getting a non JSON payload.""" + incoming = [ + ("server", b"spam"), + ("server", {"message": "Something", "type": "info"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[], + expected_stdout="\n".join( + [ + "*** Invalid JSON from remote: b'spam\\n'", + "Something", + ] + ), + ) + + def test_write_failing(self): + """Test terminating if write fails due to a half closed socket.""" + incoming = [ + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": KeyboardInterrupt()}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[{"signal": "INT"}], + simulate_send_failure=True, + expected_state={"write_failed": True}, + ) + + def test_completion_in_pdb_state(self): + """Test requesting tab completions at a (Pdb) prompt.""" + # GIVEN + incoming = [ + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ( + "user", + { + "prompt": "(Pdb) ", + "completion_request": { + "line": " mod._", + "begidx": 8, + "endidx": 9, + }, + "input": "print(\n mod.__name__)", + }, + ), + ("server", {"completions": ["__name__", "__file__"]}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + { + "complete": { + "text": "_", + "line": "mod._", + "begidx": 4, + "endidx": 5, + } + }, + {"reply": "print(\n mod.__name__)"}, + ], + expected_completions=["__name__", "__file__"], + expected_state={"state": "pdb"}, + ) + + def test_multiline_completion_in_pdb_state(self): + """Test requesting tab completions at a (Pdb) continuation prompt.""" + # GIVEN + incoming = [ + ("server", {"prompt": "(Pdb) ", "state": "pdb"}), + ("user", {"prompt": "(Pdb) ", "input": "if True:"}), + ( + "user", + { + "prompt": "... ", + "completion_request": { + "line": " b", + "begidx": 4, + "endidx": 5, + }, + "input": " bool()", + }, + ), + ("server", {"completions": ["bin", "bool", "bytes"]}), + ("user", {"prompt": "... ", "input": ""}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + { + "complete": { + "text": "b", + "line": "! b", + "begidx": 2, + "endidx": 3, + } + }, + {"reply": "if True:\n bool()\n"}, + ], + expected_completions=["bin", "bool", "bytes"], + expected_state={"state": "pdb"}, + ) + + def test_completion_in_interact_state(self): + """Test requesting tab completions at a >>> prompt.""" + incoming = [ + ("server", {"prompt": ">>> ", "state": "interact"}), + ( + "user", + { + "prompt": ">>> ", + "completion_request": { + "line": " mod.__", + "begidx": 8, + "endidx": 10, + }, + "input": "print(\n mod.__name__)", + }, + ), + ("server", {"completions": ["__name__", "__file__"]}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + { + "complete": { + "text": "__", + "line": "mod.__", + "begidx": 4, + "endidx": 6, + } + }, + {"reply": "print(\n mod.__name__)"}, + ], + expected_completions=["__name__", "__file__"], + expected_state={"state": "interact"}, + ) + + def test_completion_in_unknown_state(self): + """Test requesting tab completions at an unrecognized prompt.""" + incoming = [ + ("server", {"command_list": ["p"]}), + ("server", {"prompt": "Do it? ", "state": "confirm"}), + ( + "user", + { + "prompt": "Do it? ", + "completion_request": { + "line": "_", + "begidx": 0, + "endidx": 1, + }, + "input": "__name__", + }, + ), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + {"reply": "__name__"}, + ], + expected_state={"state": "dumb"}, + ) + + def test_write_failure_during_completion(self): + """Test failing to write to the socket to request tab completions.""" + incoming = [ + ("server", {"prompt": ">>> ", "state": "interact"}), + ( + "user", + { + "prompt": ">>> ", + "completion_request": { + "line": "xy", + "begidx": 0, + "endidx": 2, + }, + "input": "xyz", + }, + ), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + { + "complete": { + "text": "xy", + "line": "xy", + "begidx": 0, + "endidx": 2, + } + }, + {"reply": "xyz"}, + ], + simulate_send_failure=True, + expected_completions=[], + expected_state={"state": "interact", "write_failed": True}, + ) + + def test_read_failure_during_completion(self): + """Test failing to read tab completions from the socket.""" + incoming = [ + ("server", {"prompt": ">>> ", "state": "interact"}), + ( + "user", + { + "prompt": ">>> ", + "completion_request": { + "line": "xy", + "begidx": 0, + "endidx": 2, + }, + "input": "xyz", + }, + ), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + { + "complete": { + "text": "xy", + "line": "xy", + "begidx": 0, + "endidx": 2, + } + }, + {"reply": "xyz"}, + ], + expected_completions=[], + expected_state={"state": "interact"}, + ) + + def test_reading_invalid_json_during_completion(self): + """Test receiving invalid JSON when getting tab completions.""" + incoming = [ + ("server", {"prompt": ">>> ", "state": "interact"}), + ( + "user", + { + "prompt": ">>> ", + "completion_request": { + "line": "xy", + "begidx": 0, + "endidx": 2, + }, + "input": "xyz", + }, + ), + ("server", b'{"completions": '), + ("user", {"prompt": ">>> ", "input": "xyz"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + { + "complete": { + "text": "xy", + "line": "xy", + "begidx": 0, + "endidx": 2, + } + }, + {"reply": "xyz"}, + ], + expected_stdout_substring="*** json.decoder.JSONDecodeError", + expected_completions=[], + expected_state={"state": "interact"}, + ) + + def test_reading_empty_json_during_completion(self): + """Test receiving an empty JSON object when getting tab completions.""" + incoming = [ + ("server", {"prompt": ">>> ", "state": "interact"}), + ( + "user", + { + "prompt": ">>> ", + "completion_request": { + "line": "xy", + "begidx": 0, + "endidx": 2, + }, + "input": "xyz", + }, + ), + ("server", {}), + ("user", {"prompt": ">>> ", "input": "xyz"}), + ] + self.do_test( + incoming=incoming, + expected_outgoing=[ + { + "complete": { + "text": "xy", + "line": "xy", + "begidx": 0, + "endidx": 2, + } + }, + {"reply": "xyz"}, + ], + expected_stdout=( + "*** RuntimeError: Failed to get valid completions." + " Got: {}\n" + ), + expected_completions=[], + expected_state={"state": "interact"}, + ) + + +class RemotePdbTestCase(unittest.TestCase): + """Tests for the _PdbServer class.""" + + def setUp(self): + self.sockfile = MockSocketFile() + self.pdb = _PdbServer(self.sockfile) + + # Mock some Bdb attributes that are lazily created when tracing starts + self.pdb.botframe = None + self.pdb.quitting = False + + # Create a frame for testing + self.test_globals = {'a': 1, 'b': 2, '__pdb_convenience_variables': {'x': 100}} + self.test_locals = {'c': 3, 'd': 4} + + # Create a simple test frame + frame_info = unittest.mock.Mock() + frame_info.f_globals = self.test_globals + frame_info.f_locals = self.test_locals + frame_info.f_lineno = 42 + frame_info.f_code = unittest.mock.Mock() + frame_info.f_code.co_filename = "test_file.py" + frame_info.f_code.co_name = "test_function" + + self.pdb.curframe = frame_info + + def test_message_and_error(self): + """Test message and error methods send correct JSON.""" + self.pdb.message("Test message") + self.pdb.error("Test error") + + outputs = self.sockfile.get_output() + self.assertEqual(len(outputs), 2) + self.assertEqual(outputs[0], {"message": "Test message\n", "type": "info"}) + self.assertEqual(outputs[1], {"message": "Test error", "type": "error"}) + + def test_read_command(self): + """Test reading commands from the socket.""" + # Add test input + self.sockfile.add_input({"reply": "help"}) + + # Read the command + cmd = self.pdb._read_reply() + self.assertEqual(cmd, "help") + + def test_read_command_EOF(self): + """Test reading EOF command.""" + # Simulate socket closure + self.pdb._write_failed = True + with self.assertRaises(EOFError): + self.pdb._read_reply() + + def test_completion(self): + """Test handling completion requests.""" + # Mock completenames to return specific values + with unittest.mock.patch.object(self.pdb, 'completenames', + return_value=["continue", "clear"]): + + # Add a completion request + self.sockfile.add_input({ + "complete": { + "text": "c", + "line": "c", + "begidx": 0, + "endidx": 1 + } + }) + + # Add a regular command to break the loop + self.sockfile.add_input({"reply": "help"}) + + # Read command - this should process the completion request first + cmd = self.pdb._read_reply() + + # Verify completion response was sent + outputs = self.sockfile.get_output() + self.assertEqual(len(outputs), 1) + self.assertEqual(outputs[0], {"completions": ["continue", "clear"]}) + + # The actual command should be returned + self.assertEqual(cmd, "help") + + def test_do_help(self): + """Test that do_help sends the help message.""" + self.pdb.do_help("break") + + outputs = self.sockfile.get_output() + self.assertEqual(len(outputs), 1) + self.assertEqual(outputs[0], {"help": "break"}) + + def test_interact_mode(self): + """Test interaction mode setup and execution.""" + # First set up interact mode + self.pdb.do_interact("") + + # Verify _interact_state is properly initialized + self.assertIsNotNone(self.pdb._interact_state) + self.assertIsInstance(self.pdb._interact_state, dict) + + # Test running code in interact mode + with unittest.mock.patch.object(self.pdb, '_error_exc') as mock_error: + self.pdb._run_in_python_repl("print('test')") + mock_error.assert_not_called() + + # Test with syntax error + self.pdb._run_in_python_repl("if:") + mock_error.assert_called_once() + + def test_registering_commands(self): + """Test registering breakpoint commands.""" + # Mock get_bpbynumber + with unittest.mock.patch.object(self.pdb, 'get_bpbynumber'): + # Queue up some input to send + self.sockfile.add_input({"reply": "commands 1"}) + self.sockfile.add_input({"reply": "silent"}) + self.sockfile.add_input({"reply": "print('hi')"}) + self.sockfile.add_input({"reply": "end"}) + self.sockfile.add_input({"signal": "EOF"}) + + # Run the PDB command loop + self.pdb.cmdloop() + + outputs = self.sockfile.get_output() + self.assertIn('command_list', outputs[0]) + self.assertEqual(outputs[1], {"prompt": "(Pdb) ", "state": "pdb"}) + self.assertEqual(outputs[2], {"prompt": "(com) ", "state": "commands"}) + self.assertEqual(outputs[3], {"prompt": "(com) ", "state": "commands"}) + self.assertEqual(outputs[4], {"prompt": "(com) ", "state": "commands"}) + self.assertEqual(outputs[5], {"prompt": "(Pdb) ", "state": "pdb"}) + self.assertEqual(outputs[6], {"message": "\n", "type": "info"}) + self.assertEqual(len(outputs), 7) + + self.assertEqual( + self.pdb.commands[1], + ["_pdbcmd_silence_frame_status", "print('hi')"], + ) + + def test_detach(self): + """Test the detach method.""" + with unittest.mock.patch.object(self.sockfile, 'close') as mock_close: + self.pdb.detach() + mock_close.assert_called_once() + self.assertFalse(self.pdb.quitting) + + def test_cmdloop(self): + """Test the command loop with various commands.""" + # Mock onecmd to track command execution + with unittest.mock.patch.object(self.pdb, 'onecmd', return_value=False) as mock_onecmd: + # Add commands to the queue + self.pdb.cmdqueue = ['help', 'list'] + + # Add a command from the socket for when cmdqueue is empty + self.sockfile.add_input({"reply": "next"}) + + # Add a second command to break the loop + self.sockfile.add_input({"reply": "quit"}) + + # Configure onecmd to exit the loop on "quit" + def side_effect(line): + return line == 'quit' + mock_onecmd.side_effect = side_effect + + # Run the command loop + self.pdb.quitting = False # Set this by hand because we don't want to really call set_trace() + self.pdb.cmdloop() + + # Should have processed 4 commands: 2 from cmdqueue, 2 from socket + self.assertEqual(mock_onecmd.call_count, 4) + mock_onecmd.assert_any_call('help') + mock_onecmd.assert_any_call('list') + mock_onecmd.assert_any_call('next') + mock_onecmd.assert_any_call('quit') + + # Check if prompt was sent to client + outputs = self.sockfile.get_output() + prompts = [o for o in outputs if 'prompt' in o] + self.assertEqual(len(prompts), 2) # Should have sent 2 prompts + + +@requires_subprocess() +@unittest.skipIf(is_wasi, "WASI does not support TCP sockets") +class PdbConnectTestCase(unittest.TestCase): + """Tests for the _connect mechanism using direct socket communication.""" + + def setUp(self): + # Create a server socket that will wait for the debugger to connect + self.server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.server_sock.bind(('127.0.0.1', 0)) # Let OS assign port + self.server_sock.listen(1) + self.port = self.server_sock.getsockname()[1] + + def _create_script(self, script=None): + # Create a file for subprocess script + if script is None: + script = textwrap.dedent( + f""" + import pdb + import sys + import time + + def foo(): + x = 42 + return bar() + + def bar(): + return 42 + + def connect_to_debugger(): + # Create a frame to debug + def dummy_function(): + x = 42 + # Call connect to establish connection + # with the test server + frame = sys._getframe() # Get the current frame + pdb._connect( + host='127.0.0.1', + port={self.port}, + frame=frame, + commands="", + version=pdb._PdbServer.protocol_version(), + signal_raising_thread=False, + colorize=False, + ) + return x # This line won't be reached in debugging + + return dummy_function() + + result = connect_to_debugger() + foo() + print(f"Function returned: {{result}}") + """) + + self.script_path = TESTFN + "_connect_test.py" + with open(self.script_path, 'w') as f: + f.write(script) + + def tearDown(self): + self.server_sock.close() + try: + unlink(self.script_path) + except OSError: + pass + + def _connect_and_get_client_file(self): + """Helper to start subprocess and get connected client file.""" + # Start the subprocess that will connect to our socket + process = subprocess.Popen( + [sys.executable, self.script_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True + ) + + # Accept the connection from the subprocess + client_sock, _ = self.server_sock.accept() + client_file = client_sock.makefile('rwb') + self.addCleanup(client_file.close) + self.addCleanup(client_sock.close) + + return process, client_file + + def _connect_and_get_client_file_via_pty(self): + """Like _connect_and_get_client_file, but run the target under a pty. + + With a real terminal on stdin/stdout, PyREPL is available *inside the + target process*, which is the condition that exercises pdb's PyREPL + input handling in the remote server. + """ + controller, worker = pty.openpty() + self.addCleanup(os.close, controller) + env = dict(os.environ, TERM="xterm-256color") + env.pop("PYTHON_BASIC_REPL", None) # don't opt out of PyREPL + process = subprocess.Popen( + [sys.executable, self.script_path], + stdin=worker, stdout=worker, stderr=worker, env=env, close_fds=True, + ) + os.close(worker) # only the child keeps the worker end open + + # Continuously drain the terminal so the child never blocks on a write. + drainer = threading.Thread( + target=self._drain_until_eof, args=(controller,), daemon=True + ) + drainer.start() + self.addCleanup(drainer.join, SHORT_TIMEOUT) + + client_sock, _ = self.server_sock.accept() + client_file = client_sock.makefile('rwb') + self.addCleanup(client_file.close) + self.addCleanup(client_sock.close) + + return process, client_file + + @staticmethod + def _drain_until_eof(fd): + try: + while os.read(fd, 1024): + pass + except OSError: + pass # controller closed, or the pty went away with the child + + def _read_until_prompt(self, client_file): + """Helper to read messages until a prompt is received.""" + messages = [] + while True: + data = client_file.readline() + if not data: + break + msg = json.loads(data.decode()) + messages.append(msg) + if 'prompt' in msg: + break + return messages + + def _send_command(self, client_file, command): + """Helper to send a command to the debugger.""" + client_file.write(json.dumps({"reply": command}).encode() + b"\n") + client_file.flush() + + def test_connect_and_basic_commands(self): + """Test connecting to a remote debugger and sending basic commands.""" + self._create_script() + process, client_file = self._connect_and_get_client_file() + + with kill_on_error(process): + # We should receive initial data from the debugger + data = client_file.readline() + initial_data = json.loads(data.decode()) + self.assertIn('message', initial_data) + self.assertIn('pdb._connect', initial_data['message']) + + # First, look for command_list message + data = client_file.readline() + command_list = json.loads(data.decode()) + self.assertIn('command_list', command_list) + + # Then, look for the first prompt + data = client_file.readline() + prompt_data = json.loads(data.decode()) + self.assertIn('prompt', prompt_data) + self.assertEqual(prompt_data['state'], 'pdb') + + # Send 'bt' (backtrace) command + self._send_command(client_file, "bt") + + # Check for response - we should get some stack frames + messages = self._read_until_prompt(client_file) + + # Extract text messages containing stack info + text_msg = [msg['message'] for msg in messages + if 'message' in msg and 'connect_to_debugger' in msg['message']] + got_stack_info = bool(text_msg) + + expected_stacks = [ + "", + "connect_to_debugger", + ] + + for stack, msg in zip(expected_stacks, text_msg, strict=True): + self.assertIn(stack, msg) + + self.assertTrue(got_stack_info, "Should have received stack trace information") + + # Send 'c' (continue) command to let the program finish + self._send_command(client_file, "c") + + # Wait for process to finish + stdout, _ = process.communicate(timeout=SHORT_TIMEOUT) + + # Check if we got the expected output + self.assertIn("Function returned: 42", stdout) + self.assertEqual(process.returncode, 0) + + def test_breakpoints(self): + """Test setting and hitting breakpoints.""" + self._create_script() + process, client_file = self._connect_and_get_client_file() + with kill_on_error(process): + # Skip initial messages until we get to the prompt + self._read_until_prompt(client_file) + + # Set a breakpoint at the return statement + self._send_command(client_file, "break bar") + messages = self._read_until_prompt(client_file) + bp_msg = next(msg['message'] for msg in messages if 'message' in msg) + self.assertIn("Breakpoint", bp_msg) + + # Continue execution until breakpoint + self._send_command(client_file, "c") + messages = self._read_until_prompt(client_file) + + # Verify we hit the breakpoint + hit_msg = next(msg['message'] for msg in messages if 'message' in msg) + self.assertIn("bar()", hit_msg) + + # Check breakpoint list + self._send_command(client_file, "b") + messages = self._read_until_prompt(client_file) + list_msg = next(msg['message'] for msg in reversed(messages) if 'message' in msg) + self.assertIn("1 breakpoint", list_msg) + self.assertIn("breakpoint already hit 1 time", list_msg) + + # Clear breakpoint + self._send_command(client_file, "clear 1") + messages = self._read_until_prompt(client_file) + clear_msg = next(msg['message'] for msg in reversed(messages) if 'message' in msg) + self.assertIn("Deleted breakpoint", clear_msg) + + # Continue to end + self._send_command(client_file, "c") + stdout, _ = process.communicate(timeout=SHORT_TIMEOUT) + + self.assertIn("Function returned: 42", stdout) + self.assertEqual(process.returncode, 0) + + def test_keyboard_interrupt(self): + """Test that sending keyboard interrupt breaks into pdb.""" + + script = textwrap.dedent(f""" + import time + import sys + import socket + import pdb + def bar(): + frame = sys._getframe() # Get the current frame + pdb._connect( + host='127.0.0.1', + port={self.port}, + frame=frame, + commands="", + version=pdb._PdbServer.protocol_version(), + signal_raising_thread=True, + colorize=False, + ) + print("Connected to debugger") + iterations = 50 + while iterations > 0: + print("Iteration", iterations, flush=True) + time.sleep(0.2) + iterations -= 1 + return 42 + + if __name__ == "__main__": + print("Function returned:", bar()) + """) + self._create_script(script=script) + process, client_file = self._connect_and_get_client_file() + + # Accept a 2nd connection from the subprocess to tell it about signals + signal_sock, _ = self.server_sock.accept() + self.addCleanup(signal_sock.close) + + with kill_on_error(process): + # Skip initial messages until we get to the prompt + self._read_until_prompt(client_file) + + # Continue execution + self._send_command(client_file, "c") + + # Confirm that the remote is already in the while loop. We know + # it's in bar() and we can exit the loop immediately by setting + # iterations to 0. + while line := process.stdout.readline(): + if line.startswith("Iteration"): + break + + # Inject a script to interrupt the running process + signal_sock.sendall(signal.SIGINT.to_bytes()) + messages = self._read_until_prompt(client_file) + + # Verify we got the keyboard interrupt message. + interrupt_msgs = [msg['message'] for msg in messages if 'message' in msg] + expected_msg = [msg for msg in interrupt_msgs if "bar()" in msg] + self.assertGreater(len(expected_msg), 0) + + # Continue to end as fast as we can + self._send_command(client_file, "iterations = 0") + self._send_command(client_file, "c") + stdout, _ = process.communicate(timeout=SHORT_TIMEOUT) + self.assertIn("Function returned: 42", stdout) + self.assertEqual(process.returncode, 0) + + def test_handle_eof(self): + """Test that EOF signal properly exits the debugger.""" + self._create_script() + process, client_file = self._connect_and_get_client_file() + + with kill_on_error(process): + # Skip initial messages until we get to the prompt + self._read_until_prompt(client_file) + + # Send EOF signal to exit the debugger + client_file.write(json.dumps({"signal": "EOF"}).encode() + b"\n") + client_file.flush() + + # The process should complete normally after receiving EOF + stdout, stderr = process.communicate(timeout=SHORT_TIMEOUT) + + # Verify process completed correctly + self.assertIn("Function returned: 42", stdout) + self.assertEqual(process.returncode, 0) + self.assertEqual(stderr, "") + + def test_colorized_list_has_no_caret_encoded_newlines(self): + """A colorized ``list`` must not append "^J" to each source line. + + The remote server colorizes the source it sends to the client. The + colorizer renders control characters in caret notation, so a source + line's trailing newline has to be stripped *before* it is colorized; + otherwise every listed line ends with a spurious "^J". ``where`` was + unaffected because it strips the line before colorizing. See + gh-154470. + """ + # colorize=True is what attaching from a color-capable terminal passes + # to the server, and it is what makes the server colorize ``list``. + script = textwrap.dedent(f""" + import pdb, sys + def helper(): + x = 42 + return x + def connect(): + frame = sys._getframe() + pdb._connect( + host='127.0.0.1', + port={self.port}, + frame=frame, + commands="", + version=pdb._PdbServer.protocol_version(), + signal_raising_thread=False, + colorize=True, + ) + return helper() + connect() + """) + self._create_script(script=script) + process, client_file = self._connect_and_get_client_file() + + with kill_on_error(process): + self._read_until_prompt(client_file) + self._send_command(client_file, "l 1, 15") + messages = self._read_until_prompt(client_file) + source = "".join(m["message"] for m in messages if "message" in m) + + # Sanity: we really did receive colorized source ... + self.assertIn("helper", source) + self.assertIn("\x1b[", source) # ANSI color escapes are present + # ... and no trailing newline leaked through as caret notation. + self.assertNotIn("^J", source) + self._send_command(client_file, "c") + process.wait(timeout=SHORT_TIMEOUT) + self.assertEqual(process.returncode, 0) + + @unittest.skipUnless(pty, "requires pty") + def test_prompt_with_interactive_terminal(self): + """The server must send "(Pdb) " even when the target owns a terminal. + + The remote server transmits its prompt string to the client, which + displays it. When the target process has an interactive terminal, + PyREPL is enabled inside it; the base pdb machinery then blanks + ``self.prompt`` (a local PyREPL would draw the prompt itself). The + remote server has no local PyREPL -- it reads input from the socket -- + so it must keep the real prompt rather than transmit an empty one. + Regression test for gh-154467, where attaching with ``pdb -p`` to a + process running at an interactive prompt showed a blank prompt. + """ + self._create_script() + process, client_file = self._connect_and_get_client_file_via_pty() + + with kill_on_error(process): + messages = self._read_until_prompt(client_file) + # The message that ended the read is the prompt request. + self.assertEqual(messages[-1], {"prompt": "(Pdb) ", "state": "pdb"}) + + # Let the target run to completion so nothing is left attached. + self._send_command(client_file, "c") + process.wait(timeout=SHORT_TIMEOUT) + self.assertEqual(process.returncode, 0) + + def test_protocol_version(self): + """Test that incompatible protocol versions are properly detected.""" + # Create a script using an incompatible protocol version + script = textwrap.dedent(f''' + import sys + import pdb + + def run_test(): + frame = sys._getframe() + + # Use a fake version number that's definitely incompatible + fake_version = 0x01010101 # A fake version that doesn't match any real Python version + + # Connect with the wrong version + pdb._connect( + host='127.0.0.1', + port={self.port}, + frame=frame, + commands="", + version=fake_version, + signal_raising_thread=False, + colorize=False, + ) + + # This should print if the debugger detaches correctly + print("Debugger properly detected version mismatch") + return True + + if __name__ == "__main__": + print("Test result:", run_test()) + ''') + self._create_script(script=script) + process, client_file = self._connect_and_get_client_file() + + with kill_on_error(process): + # First message should be an error about protocol version mismatch + data = client_file.readline() + message = json.loads(data.decode()) + + self.assertIn('message', message) + self.assertEqual(message['type'], 'error') + self.assertIn('incompatible', message['message']) + self.assertIn('protocol version', message['message']) + + # The process should complete normally + stdout, stderr = process.communicate(timeout=SHORT_TIMEOUT) + + # Verify the process completed successfully + self.assertIn("Test result: True", stdout) + self.assertIn("Debugger properly detected version mismatch", stdout) + self.assertEqual(process.returncode, 0) + + def test_help_system(self): + """Test that the help system properly sends help text to the client.""" + self._create_script() + process, client_file = self._connect_and_get_client_file() + + with kill_on_error(process): + # Skip initial messages until we get to the prompt + self._read_until_prompt(client_file) + + # Request help for different commands + help_commands = ["help", "help break", "help continue", "help pdb"] + + for cmd in help_commands: + self._send_command(client_file, cmd) + + # Look for help message + data = client_file.readline() + message = json.loads(data.decode()) + + self.assertIn('help', message) + + if cmd == "help": + # Should just contain the command itself + self.assertEqual(message['help'], "") + else: + # Should contain the specific command we asked for help with + command = cmd.split()[1] + self.assertEqual(message['help'], command) + + # Skip to the next prompt + self._read_until_prompt(client_file) + + # Continue execution to finish the program + self._send_command(client_file, "c") + + stdout, stderr = process.communicate(timeout=SHORT_TIMEOUT) + self.assertIn("Function returned: 42", stdout) + self.assertEqual(process.returncode, 0) + + def test_multi_line_commands(self): + """Test that multi-line commands work properly over remote connection.""" + self._create_script() + process, client_file = self._connect_and_get_client_file() + + with kill_on_error(process): + # Skip initial messages until we get to the prompt + self._read_until_prompt(client_file) + + # Send a multi-line command + multi_line_commands = [ + # Define a function + "def test_func():\n return 42", + + # For loop + "for i in range(3):\n print(i)", + + # If statement + "if True:\n x = 42\nelse:\n x = 0", + + # Try/except + "try:\n result = 10/2\n print(result)\nexcept ZeroDivisionError:\n print('Error')", + + # Class definition + "class TestClass:\n def __init__(self):\n self.value = 100\n def get_value(self):\n return self.value" + ] + + for cmd in multi_line_commands: + self._send_command(client_file, cmd) + self._read_until_prompt(client_file) + + # Test executing the defined function + self._send_command(client_file, "test_func()") + messages = self._read_until_prompt(client_file) + + # Find the result message + result_msg = next(msg['message'] for msg in messages if 'message' in msg) + self.assertIn("42", result_msg) + + # Test creating an instance of the defined class + self._send_command(client_file, "obj = TestClass()") + self._read_until_prompt(client_file) + + # Test calling a method on the instance + self._send_command(client_file, "obj.get_value()") + messages = self._read_until_prompt(client_file) + + # Find the result message + result_msg = next(msg['message'] for msg in messages if 'message' in msg) + self.assertIn("100", result_msg) + + # Continue execution to finish + self._send_command(client_file, "c") + + stdout, stderr = process.communicate(timeout=SHORT_TIMEOUT) + self.assertIn("Function returned: 42", stdout) + self.assertEqual(process.returncode, 0) + + def test_exec_in_closure_result_uses_pdb_stdout(self): + """ + Expression results executed via _exec_in_closure() should be written + to the debugger output stream (pdb stdout), not to sys.stdout. + """ + self._create_script() + process, client_file = self._connect_and_get_client_file() + + with kill_on_error(process): + self._read_until_prompt(client_file) + + self._send_command(client_file, "(lambda: 123)()") + messages = self._read_until_prompt(client_file) + result_msg = "".join(msg.get("message", "") for msg in messages) + self.assertIn("123", result_msg) + + self._send_command(client_file, "sum(i for i in (1, 2, 3))") + messages = self._read_until_prompt(client_file) + result_msg = "".join(msg.get("message", "") for msg in messages) + self.assertIn("6", result_msg) + + self._send_command(client_file, "c") + stdout, _ = process.communicate(timeout=SHORT_TIMEOUT) + + self.assertNotIn("\n123\n", stdout) + self.assertNotIn("\n6\n", stdout) + self.assertEqual(process.returncode, 0) + + +def _supports_remote_attaching(): + PROCESS_VM_READV_SUPPORTED = False + + try: + from _remote_debugging import PROCESS_VM_READV_SUPPORTED + except ImportError: + pass + + return PROCESS_VM_READV_SUPPORTED + + +@unittest.skipIf(not sys.is_remote_debug_enabled(), "Remote debugging is not enabled") +@unittest.skipIf(sys.platform != "darwin" and sys.platform != "linux" and sys.platform != "win32", + "Test only runs on Linux, Windows and MacOS") +@unittest.skipIf(sys.platform == "linux" and not _supports_remote_attaching(), + "Testing on Linux requires process_vm_readv support") +@cpython_only +@requires_subprocess() +class PdbAttachTestCase(unittest.TestCase): + def setUp(self): + # Create a server socket that will wait for the debugger to connect + self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.sock.bind(('127.0.0.1', 0)) # Let OS assign port + self.sock.listen(1) + self.port = self.sock.getsockname()[1] + self._create_script() + + def _create_script(self, script=None): + # Create a file for subprocess script + script = textwrap.dedent( + f""" + import socket + import time + + def foo(): + return bar() + + def bar(): + return baz() + + def baz(): + x = 1 + # Trigger attach + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.connect(('127.0.0.1', {self.port})) + sock.close() + count = 0 + while x == 1 and count < 100: + count += 1 + time.sleep(0.1) + return x + + result = foo() + print(f"Function returned: {{result}}") + """ + ) + + self.script_path = TESTFN + "_connect_test.py" + with open(self.script_path, 'w') as f: + f.write(script) + + def tearDown(self): + self.sock.close() + try: + unlink(self.script_path) + except OSError: + pass + + def do_integration_test(self, client_stdin): + process = subprocess.Popen( + [sys.executable, self.script_path], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + text=True + ) + self.addCleanup(process.stdout.close) + self.addCleanup(process.stderr.close) + + # Wait for the process to reach our attachment point + self.sock.settimeout(10) + conn, _ = self.sock.accept() + conn.close() + + client_stdin = io.StringIO(client_stdin) + client_stdout = io.StringIO() + client_stderr = io.StringIO() + + self.addCleanup(client_stdin.close) + self.addCleanup(client_stdout.close) + self.addCleanup(client_stderr.close) + self.addCleanup(process.wait) + + with ( + unittest.mock.patch("sys.stdin", client_stdin), + redirect_stdout(client_stdout), + redirect_stderr(client_stderr), + unittest.mock.patch("sys.argv", ["pdb", "-p", str(process.pid)]), + unittest.mock.patch( + "pdb.exit_with_permission_help_text", side_effect=PermissionError + ), + ): + try: + pdb.main() + except PermissionError: + self.skipTest("Insufficient permissions for remote execution") + + process.wait() + server_stdout = process.stdout.read() + server_stderr = process.stderr.read() + + if process.returncode != 0: + print("server failed") + print(f"server stdout:\n{server_stdout}") + print(f"server stderr:\n{server_stderr}") + + self.assertEqual(process.returncode, 0) + return { + "client": { + "stdout": client_stdout.getvalue(), + "stderr": client_stderr.getvalue(), + }, + "server": { + "stdout": server_stdout, + "stderr": server_stderr, + }, + } + + def test_attach_to_process_without_colors(self): + with force_color(False): + output = self.do_integration_test("ll\nx=42\n") + self.assertEqual(output["client"]["stderr"], "") + self.assertEqual(output["server"]["stderr"], "") + + self.assertEqual(output["server"]["stdout"], "Function returned: 42\n") + self.assertIn("while x == 1", output["client"]["stdout"]) + self.assertNotIn("\x1b", output["client"]["stdout"]) + + def test_attach_to_process_with_colors(self): + with force_color(True): + output = self.do_integration_test("ll\nx=42\n") + self.assertEqual(output["client"]["stderr"], "") + self.assertEqual(output["server"]["stderr"], "") + + self.assertEqual(output["server"]["stdout"], "Function returned: 42\n") + self.assertIn("\x1b", output["client"]["stdout"]) + self.assertNotIn("while x == 1", output["client"]["stdout"]) + self.assertIn("while x == 1", re.sub("\x1b[^m]*m", "", output["client"]["stdout"])) + + def test_attach_to_non_existent_process(self): + with force_color(False): + result = subprocess.run([sys.executable, "-m", "pdb", "-p", "999999"], text=True, capture_output=True) + self.assertNotEqual(result.returncode, 0) + if sys.platform == "darwin": + # On MacOS, attaching to a non-existent process gives PermissionError + error = "The specified process cannot be attached to due to insufficient permissions" + else: + error = "Cannot attach to pid 999999, please make sure that the process exists" + self.assertIn(error, result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_repl.py b/Lib/test/test_repl.py index 71dab8c3876..a0abcc0f0ba 100644 --- a/Lib/test/test_repl.py +++ b/Lib/test/test_repl.py @@ -17,7 +17,6 @@ SHORT_TIMEOUT, ) from test.support.script_helper import kill_python -from test.support.import_helper import import_module try: import pty @@ -40,8 +39,8 @@ def spawn_repl(*args, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, custom=F # line option '-i' and the process name set to ''. # The directory of argv[0] must match the directory of the Python # executable for the Popen() call to python to succeed as the directory - # path may be used by Py_GetPath() to build the default module search - # path. + # path may be used by PyConfig_Get("module_search_paths") to build the + # default module search path. stdin_fname = os.path.join(os.path.dirname(sys.executable), "") cmd_line = [stdin_fname] # Isolated mode implies -EPs and ignores PYTHON* variables. @@ -99,12 +98,8 @@ def run_on_interactive_mode(source): @support.force_not_colorized_test_class class TestInteractiveInterpreter(unittest.TestCase): - @cpython_only - # Python built with Py_TRACE_REFS fail with a fatal error in - # _PyRefchain_Trace() on memory allocation error. - @unittest.skipIf(support.Py_TRACE_REFS, 'cannot test Py_TRACE_REFS build') + @support.nomemtest def test_no_memory(self): - import_module("_testcapi") # Issue #30696: Fix the interactive interpreter looping endlessly when # no memory. Check also that the fix does not break the interactive # loop when an exception is raised. @@ -189,7 +184,6 @@ def test_close_stdin(self): self.assertEqual(process.returncode, 0) self.assertIn('before close', output) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: 101 != 0 def test_interactive_traceback_reporting(self): user_input = "1 / 0 / 3 / 4" p = spawn_repl() @@ -232,7 +226,6 @@ def foo(x): ] self.assertEqual(traceback_lines, expected_lines) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_pythonstartup_error_reporting(self): # errors based on https://github.com/python/cpython/issues/137576 @@ -303,7 +296,7 @@ def test_runsource_show_syntax_error_location(self): expected_lines = [ ' def f(x, x): ...', ' ^', - "SyntaxError: duplicate argument 'x' in function definition" + "SyntaxError: duplicate parameter 'x' in function definition" ] self.assertEqual(output.splitlines()[4:-1], expected_lines) @@ -443,6 +436,13 @@ def test_toplevel_contextvars_async(self): p = spawn_asyncio_repl() p.stdin.write(user_input) user_input2 = "async def set_var(): var.set('ok')\n" + try: + import _pyrepl # noqa: F401 + except ModuleNotFoundError: + # If we're going to be forced into the regular REPL, then we need an + # extra newline here. Omit it by default to catch any breakage to + # the new REPL's behavior. + user_input2 += "\n" p.stdin.write(user_input2) user_input3 = "await set_var()\n" p.stdin.write(user_input3) diff --git a/Lib/test/test_reprlib.py b/Lib/test/test_reprlib.py index 22a55b57c07..5a95a05c649 100644 --- a/Lib/test/test_reprlib.py +++ b/Lib/test/test_reprlib.py @@ -695,8 +695,11 @@ def _check_path_limitations(self, module_name): source_path_len += 2 * (len(self.longname) + 1) # a path separator + `module_name` + ".py" source_path_len += len(module_name) + 1 + len(".py") - cached_path_len = (source_path_len + - len(importlib.util.cache_from_source("x.py")) - len("x.py")) + try: + cached_path_len = (source_path_len + + len(importlib.util.cache_from_source("x.py")) - len("x.py")) + except NotImplementedError: + cached_path_len = source_path_len if os.name == 'nt' and cached_path_len >= 258: # Under Windows, the max path len is 260 including C's terminating # NUL character. diff --git a/Lib/test/test_resource.py b/Lib/test/test_resource.py index 2302716a131..4ccbef72a8d 100644 --- a/Lib/test/test_resource.py +++ b/Lib/test/test_resource.py @@ -4,7 +4,6 @@ from test import support from test.support import import_helper from test.support import os_helper -import time resource = import_helper.import_module('resource') @@ -40,7 +39,10 @@ def test_fsize_ismax(self): # we need to test that the get/setrlimit functions properly convert # the number to a C long long and that the conversion doesn't raise # an error. - self.assertEqual(resource.RLIM_INFINITY, max) + self.assertGreater(resource.RLIM_INFINITY, 0) + self.assertGreaterEqual(max, 0) + self.assertLessEqual(cur, max) + resource.setrlimit(resource.RLIMIT_FSIZE, (max, max)) resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) @unittest.skip("TODO: RUSTPYTHON; crash") @@ -48,47 +50,24 @@ def test_fsize_ismax(self): "setting RLIMIT_FSIZE is not supported on VxWorks") @unittest.skipUnless(hasattr(resource, 'RLIMIT_FSIZE'), 'requires resource.RLIMIT_FSIZE') def test_fsize_enforced(self): - (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) - # Check to see what happens when the RLIMIT_FSIZE is small. Some - # versions of Python were terminated by an uncaught SIGXFSZ, but - # pythonrun.c has been fixed to ignore that exception. If so, the - # write() should return EFBIG when the limit is exceeded. - - # At least one platform has an unlimited RLIMIT_FSIZE and attempts - # to change it raise ValueError instead. + self.addCleanup(os_helper.unlink, os_helper.TESTFN) try: + (cur, max_lim) = resource.getrlimit(resource.RLIMIT_FSIZE) + except OSError as e: + self.skipTest(f"getrlimit(RLIMIT_FSIZE) failed: {e}") + if max_lim != resource.RLIM_INFINITY and max_lim < 1025: + self.skipTest(f"system RLIMIT_FSIZE hard limit ({max_lim}) is too small for this test") + with open(os_helper.TESTFN, "wb", buffering=0) as f: try: - resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max)) - limit_set = True - except ValueError: - limit_set = False - f = open(os_helper.TESTFN, "wb") - try: + resource.setrlimit(resource.RLIMIT_FSIZE, (1024, max_lim)) f.write(b"X" * 1024) - try: + with self.assertRaises(OSError, msg="f.write() did not raise OSError when exceeding RLIMIT_FSIZE"): f.write(b"Y") f.flush() - # On some systems (e.g., Ubuntu on hppa) the flush() - # doesn't always cause the exception, but the close() - # does eventually. Try flushing several times in - # an attempt to ensure the file is really synced and - # the exception raised. - for i in range(5): - time.sleep(.1) - f.flush() - except OSError: - if not limit_set: - raise - if limit_set: - # Close will attempt to flush the byte we wrote - # Restore limit first to avoid getting a spurious error - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) finally: - f.close() - finally: - if limit_set: - resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max)) - os_helper.unlink(os_helper.TESTFN) + # Close will attempt to flush the byte we wrote + # Restore limit first to avoid getting a spurious error + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, max_lim)) @unittest.skipIf(sys.platform == "vxworks", "setting RLIMIT_FSIZE is not supported on VxWorks") @@ -114,29 +93,33 @@ def test_fsize_not_too_big(self): self.addCleanup(resource.setrlimit, resource.RLIMIT_FSIZE, (cur, max)) def expected(cur): - if resource.RLIM_INFINITY < 0: - return [(cur, max), (resource.RLIM_INFINITY, max)] - elif resource.RLIM_INFINITY < cur: - return [(resource.RLIM_INFINITY, max)] - else: - return [(cur, max)] + # The glibc wrapper functions use a 64-bit rlim_t data type, + # even on 32-bit platforms. If a program tried to set a resource + # limit to a value larger than can be represented in a 32-bit + # unsigned long, then the glibc setrlimit() wrapper function + # silently converted the limit value to RLIM_INFINITY. + if sys.maxsize < 2**32 <= cur <= resource.RLIM_INFINITY: + return [(resource.RLIM_INFINITY, max), (cur, max)] + # Solaris silently converts limits that do not fit in a signed + # 64-bit integer to RLIM_INFINITY. + if cur >= 2**63-1: + return [(resource.RLIM_INFINITY, max), + (min(cur, resource.RLIM_INFINITY), max)] + return [(min(cur, resource.RLIM_INFINITY), max)] resource.setrlimit(resource.RLIMIT_FSIZE, (2**31-5, max)) self.assertEqual(resource.getrlimit(resource.RLIMIT_FSIZE), (2**31-5, max)) + resource.setrlimit(resource.RLIMIT_FSIZE, (2**31, max)) + self.assertIn(resource.getrlimit(resource.RLIMIT_FSIZE), expected(2**31)) + resource.setrlimit(resource.RLIMIT_FSIZE, (2**32-5, max)) + self.assertIn(resource.getrlimit(resource.RLIMIT_FSIZE), expected(2**32-5)) try: resource.setrlimit(resource.RLIMIT_FSIZE, (2**32, max)) except OverflowError: - resource.setrlimit(resource.RLIMIT_FSIZE, (2**31, max)) - self.assertIn(resource.getrlimit(resource.RLIMIT_FSIZE), expected(2**31)) - resource.setrlimit(resource.RLIMIT_FSIZE, (2**32-5, max)) - self.assertIn(resource.getrlimit(resource.RLIMIT_FSIZE), expected(2**32-5)) + pass else: self.assertIn(resource.getrlimit(resource.RLIMIT_FSIZE), expected(2**32)) - resource.setrlimit(resource.RLIMIT_FSIZE, (2**31, max)) - self.assertEqual(resource.getrlimit(resource.RLIMIT_FSIZE), (2**31, max)) - resource.setrlimit(resource.RLIMIT_FSIZE, (2**32-5, max)) - self.assertEqual(resource.getrlimit(resource.RLIMIT_FSIZE), (2**32-5, max)) resource.setrlimit(resource.RLIMIT_FSIZE, (2**63-5, max)) self.assertIn(resource.getrlimit(resource.RLIMIT_FSIZE), expected(2**63-5)) @@ -154,16 +137,21 @@ def expected(cur): "setting RLIMIT_FSIZE is not supported on VxWorks") @unittest.skipUnless(hasattr(resource, 'RLIMIT_FSIZE'), 'requires resource.RLIMIT_FSIZE') def test_fsize_negative(self): + self.assertGreater(resource.RLIM_INFINITY, 0) (cur, max) = resource.getrlimit(resource.RLIMIT_FSIZE) for value in -5, -2**31, -2**32-5, -2**63, -2**64-5, -2**1000: with self.subTest(value=value): - # This test assumes that the values don't map to RLIM_INFINITY, - # though Posix doesn't guarantee it. - self.assertNotEqual(value, resource.RLIM_INFINITY) - self.assertRaises(ValueError, resource.setrlimit, resource.RLIMIT_FSIZE, (value, max)) self.assertRaises(ValueError, resource.setrlimit, resource.RLIMIT_FSIZE, (cur, value)) + if resource.RLIM_INFINITY in (2**32-3, 2**32-1, 2**64-3, 2**64-1): + value = (resource.RLIM_INFINITY & 0xffff) - 0x10000 + with self.assertWarnsRegex(DeprecationWarning, "RLIM_INFINITY"): + resource.setrlimit(resource.RLIMIT_FSIZE, (value, max)) + with self.assertWarnsRegex(DeprecationWarning, "RLIM_INFINITY"): + resource.setrlimit(resource.RLIMIT_FSIZE, (cur, value)) + + @unittest.skipUnless(hasattr(resource, "getrusage"), "needs getrusage") def test_getrusage(self): self.assertRaises(TypeError, resource.getrusage) @@ -201,6 +189,15 @@ def test_pagesize(self): self.assertIsInstance(pagesize, int) self.assertGreaterEqual(pagesize, 0) + def test_contants(self): + self.assertIsInstance(resource.RLIM_INFINITY, int) + if sys.platform.startswith(('freebsd', 'solaris', 'sunos', 'aix')): + self.assertHasAttr(resource, 'RLIM_SAVED_CUR') + self.assertHasAttr(resource, 'RLIM_SAVED_MAX') + if hasattr(resource, 'RLIM_SAVED_CUR'): + self.assertIsInstance(resource.RLIM_SAVED_CUR, int) + self.assertIsInstance(resource.RLIM_SAVED_MAX, int) + @unittest.skipUnless(sys.platform in ('linux', 'android'), 'Linux only') def test_linux_constants(self): for attr in ['MSGQUEUE', 'NICE', 'RTPRIO', 'RTTIME', 'SIGPENDING']: @@ -208,7 +205,7 @@ def test_linux_constants(self): self.assertIsInstance(getattr(resource, 'RLIMIT_' + attr), int) def test_freebsd_contants(self): - for attr in ['SWAP', 'SBSIZE', 'NPTS']: + for attr in ['SWAP', 'SBSIZE', 'NPTS', 'UMTXP', 'VMEM', 'PIPEBUF']: with contextlib.suppress(AttributeError): self.assertIsInstance(getattr(resource, 'RLIMIT_' + attr), int) diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py index 0fb7f73da11..55b9673ef6c 100644 --- a/Lib/test/test_runpy.py +++ b/Lib/test/test_runpy.py @@ -20,9 +20,11 @@ requires_subprocess, verbose, ) +from test import support from test.support.import_helper import forget, make_legacy_pyc, unload from test.support.os_helper import create_empty_file, temp_dir, FakePath from test.support.script_helper import make_script, make_zip_script +from test.test_importlib.util import temporary_pycache_prefix import runpy @@ -55,7 +57,6 @@ def f(): implicit_namespace = { "__name__": None, "__file__": None, - "__cached__": None, "__package__": None, "__doc__": None, "__spec__": None @@ -303,7 +304,6 @@ def _del_pkg(self, top): def _fix_ns_for_legacy_pyc(self, ns, alter_sys): char_to_add = "c" ns["__file__"] += char_to_add - ns["__cached__"] = ns["__file__"] spec = ns["__spec__"] new_spec = importlib.util.spec_from_file_location(spec.name, ns["__file__"]) @@ -323,7 +323,6 @@ def _check_module(self, depth, alter_sys=False, expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, - "__cached__": mod_spec.cached, "__package__": mod_name.rpartition(".")[0], "__spec__": mod_spec, }) @@ -340,14 +339,16 @@ def create_ns(init_globals): self.check_code_execution(create_ns, expected_ns) importlib.invalidate_caches() __import__(mod_name) - os.remove(mod_fname) if not sys.dont_write_bytecode: - make_legacy_pyc(mod_fname) + make_legacy_pyc(mod_fname, allow_compile=True) unload(mod_name) # In case loader caches paths + os.remove(mod_fname) importlib.invalidate_caches() if verbose > 1: print("Running from compiled:", mod_name) self._fix_ns_for_legacy_pyc(expected_ns, alter_sys) self.check_code_execution(create_ns, expected_ns) + else: + os.remove(mod_fname) finally: self._del_pkg(pkg_dir) if verbose > 1: print("Module executed successfully") @@ -364,7 +365,6 @@ def _check_package(self, depth, alter_sys=False, expected_ns.update({ "__name__": mod_name, "__file__": mod_fname, - "__cached__": importlib.util.cache_from_source(mod_fname), "__package__": pkg_name, "__spec__": mod_spec, }) @@ -381,14 +381,16 @@ def create_ns(init_globals): self.check_code_execution(create_ns, expected_ns) importlib.invalidate_caches() __import__(mod_name) - os.remove(mod_fname) if not sys.dont_write_bytecode: - make_legacy_pyc(mod_fname) + make_legacy_pyc(mod_fname, allow_compile=True) unload(mod_name) # In case loader caches paths + os.remove(mod_fname) if verbose > 1: print("Running from compiled:", pkg_name) importlib.invalidate_caches() self._fix_ns_for_legacy_pyc(expected_ns, alter_sys) self.check_code_execution(create_ns, expected_ns) + else: + os.remove(mod_fname) finally: self._del_pkg(pkg_dir) if verbose > 1: print("Package executed successfully") @@ -441,7 +443,7 @@ def _check_relative_imports(self, depth, run_name=None): importlib.invalidate_caches() __import__(mod_name) os.remove(mod_fname) - if not sys.dont_write_bytecode: + if not sys.dont_write_bytecode and sys.implementation.cache_tag: make_legacy_pyc(mod_fname) unload(mod_name) # In case the loader caches paths if verbose > 1: print("Running from compiled:", mod_name) @@ -569,7 +571,6 @@ def test_run_name(self): expected_ns.update({ "__name__": run_name, "__file__": mod_fname, - "__cached__": importlib.util.cache_from_source(mod_fname), "__package__": mod_name.rpartition(".")[0], "__spec__": mod_spec, }) @@ -649,7 +650,6 @@ def create_ns(init_globals): expected_ns.update({ "__name__": expected_name, "__file__": expected_file, - "__cached__": mod_cached, "__package__": "", "__spec__": mod_spec, "run_argv0": expected_argv0, @@ -699,6 +699,8 @@ def test_basic_script_no_suffix(self): self._check_script(script_name, "", script_name, script_name, expect_spec=False) + @unittest.skipIf(sys.implementation.cache_tag is None, + 'requires sys.implementation.cache_tag') def test_script_compiled(self): with temp_dir() as script_dir: mod_name = 'script' @@ -719,12 +721,10 @@ def test_directory_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) - compiled_name = py_compile.compile(script_name, doraise=True) + legacy_pyc = make_legacy_pyc(script_name, allow_compile=True) os.remove(script_name) - if not sys.dont_write_bytecode: - legacy_pyc = make_legacy_pyc(script_name) - self._check_script(script_dir, "", legacy_pyc, - script_dir, mod_name=mod_name) + self._check_script(script_dir, "", legacy_pyc, + script_dir, mod_name=mod_name) def test_directory_error(self): with temp_dir() as script_dir: @@ -756,7 +756,8 @@ def test_zipfile_compiled(self): with temp_dir() as script_dir: mod_name = '__main__' script_name = self._make_test_script(script_dir, mod_name) - compiled_name = py_compile.compile(script_name, doraise=True) + compiled_name = script_name + 'c' + py_compile.compile(script_name, compiled_name, doraise=True) zip_name, fname = make_zip_script(script_dir, 'test_zip', compiled_name) self._check_script(zip_name, "", fname, zip_name, @@ -793,6 +794,47 @@ def test_encoding(self): result = run_path(filename) self.assertEqual(result['s'], "non-ASCII: h\xe9") + def test_run_module_filter_syntax_warnings_by_module(self): + module_re = r'test\.test_import\.data\.syntax_warnings\z' + with (temp_dir() as tmpdir, + temporary_pycache_prefix(tmpdir), + warnings.catch_warnings(record=True) as wlog): + warnings.simplefilter('error') + warnings.filterwarnings('always', module=module_re) + warnings.filterwarnings('error', module='syntax_warnings') + ns = run_module('test.test_import.data.syntax_warnings') + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + filename = ns['__file__'] + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) + + def test_run_path_filter_syntax_warnings_by_module(self): + filename = support.findfile('test_import/data/syntax_warnings.py') + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'\z') + warnings.filterwarnings('error', module='test') + warnings.filterwarnings('error', module='syntax_warnings') + warnings.filterwarnings('error', + module=r'test\.test_import\.data\.syntax_warnings') + run_path(filename) + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) + + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'package\.script\z') + warnings.filterwarnings('error', module='') + warnings.filterwarnings('error', module='test') + warnings.filterwarnings('error', module='syntax_warnings') + warnings.filterwarnings('error', + module=r'test\.test_import\.data\.syntax_warnings') + run_path(filename, run_name='package.script') + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10, 13, 14, 21]) + @force_not_colorized_test_class class TestExit(unittest.TestCase): @@ -867,7 +909,6 @@ def test_pymain_run_command_run_module(self): def test_pymain_run_command(self): self.assertSigInt(["-c", "import ham"], cwd=self.ham.parent) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_pymain_run_stdin(self): self.assertSigInt([], input="import ham", cwd=self.ham.parent) diff --git a/Lib/test/test_sax.py b/Lib/test/test_sax.py index 4abb4eb70b4..634eba6a02e 100644 --- a/Lib/test/test_sax.py +++ b/Lib/test/test_sax.py @@ -133,7 +133,6 @@ def check_parse(self, f): parse(f, XMLGenerator(result, 'utf-8')) self.assertEqual(result.getvalue(), xml_str(self.data, 'utf-8')) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_parse_text(self): encodings = ('us-ascii', 'iso-8859-1', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') @@ -147,7 +146,6 @@ def test_parse_text(self): with open(TESTFN, 'r', encoding=encoding) as f: self.check_parse(f) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_parse_bytes(self): # UTF-8 is default encoding, US-ASCII is compatible with UTF-8, # UTF-16 is autodetected @@ -194,7 +192,6 @@ def test_parse_path_object(self): make_xml_file(self.data, 'utf-8', None) self.check_parse(FakePath(TESTFN)) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_parse_InputSource(self): # accept data without declared but with explicitly specified encoding make_xml_file(self.data, 'iso-8859-1', None) @@ -204,7 +201,6 @@ def test_parse_InputSource(self): input.setEncoding('iso-8859-1') self.check_parse(input) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_parse_close_source(self): builtin_open = open fileobj = None @@ -227,7 +223,6 @@ def check_parseString(self, s): parseString(s, XMLGenerator(result, 'utf-8')) self.assertEqual(result.getvalue(), xml_str(self.data, 'utf-8')) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_parseString_text(self): encodings = ('us-ascii', 'iso-8859-1', 'utf-8', 'utf-16', 'utf-16le', 'utf-16be') @@ -235,7 +230,6 @@ def test_parseString_text(self): self.check_parseString(xml_str(self.data, encoding)) self.check_parseString(self.data) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_parseString_bytes(self): # UTF-8 is default encoding, US-ASCII is compatible with UTF-8, # UTF-16 is autodetected @@ -621,6 +615,22 @@ def test_xmlgen_ns(self): '' % ns_uri)) + def test_xmlgen_ns_escaped_uri(self): + uri = 'http://example.org/?a="1"&b=<2>' + result = self.ioclass() + gen = XMLGenerator(result) + + gen.startDocument() + gen.startPrefixMapping("ns1", uri) + gen.startElementNS((uri, "doc"), "ns1:doc", {}) + gen.endElementNS((uri, "doc"), "ns1:doc") + gen.endPrefixMapping("ns1") + gen.endDocument() + + self.assertEqual(result.getvalue(), self.xml( + """""" + "")) + def test_xmlgen_ns_empty(self): result = self.ioclass() gen = XMLGenerator(result, short_empty_elements=True) @@ -715,7 +725,6 @@ def test_1463026_3_empty(self): self.assertEqual(result.getvalue(), self.xml('')) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_5027_1(self): # The xml prefix (as in xml:lang below) is reserved and bound by # definition to http://www.w3.org/XML/1998/namespace. XMLGenerator had @@ -999,7 +1008,6 @@ def test_expat_dtdhandler(self): [("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)]) self.assertEqual(handler._entities, [("img", None, "expat.gif", "GIF")]) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_expat_external_dtd_enabled(self): # clear _opener global variable self.addCleanup(urllib.request.urlcleanup) @@ -1111,7 +1119,6 @@ def test_expat_nsattrs_empty(self): self.verify_empty_nsattrs(gather._attrs) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_expat_nsattrs_wattr(self): parser = create_parser(1) gather = self.AttrGatherer() @@ -1339,7 +1346,6 @@ def test_expat_locator_withinfo_nonascii(self): # =========================================================================== class ErrorReportingTest(unittest.TestCase): - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_expat_inpsource_location(self): parser = create_parser() parser.setContentHandler(ContentHandler()) # do nothing @@ -1353,7 +1359,6 @@ def test_expat_inpsource_location(self): except SAXException as e: self.assertEqual(e.getSystemId(), name) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'xmlparser' object has no attribute 'SetParamEntityParsing' def test_expat_incomplete(self): parser = create_parser() parser.setContentHandler(ContentHandler()) # do nothing @@ -1601,5 +1606,17 @@ def test_all(self): check__all__(self, sax, extra=extra) +class TestModule(unittest.TestCase): + def test_deprecated__version__and__date__(self): + for module in (sax.expatreader, sax.handler): + with self.subTest(module=module): + with self.assertWarnsRegex( + DeprecationWarning, + "'version' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(module, "version") + self.assertEqual(cm.filename, __file__) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py index 40997a34e15..9bfd4bc7d63 100644 --- a/Lib/test/test_set.py +++ b/Lib/test/test_set.py @@ -188,7 +188,10 @@ def test_symmetric_difference(self): self.assertEqual(type(i), self.basetype) self.assertRaises(PassThru, self.s.symmetric_difference, check_pass_thru()) self.assertRaises(TypeError, self.s.symmetric_difference, [[]]) - for C in set, frozenset, dict.fromkeys, str, list, tuple: + constructors = (set, frozenset, + dict.fromkeys, frozendict.fromkeys, + str, list, tuple) + for C in constructors: self.assertEqual(self.thetype('abcba').symmetric_difference(C('cdc')), set('abd')) self.assertEqual(self.thetype('abcba').symmetric_difference(C('efgfe')), set('abcefg')) self.assertEqual(self.thetype('abcba').symmetric_difference(C('ccb')), set('a')) @@ -349,7 +352,6 @@ def test_do_not_rehash_dict_keys(self): self.assertEqual(sum(elem.hash_count for elem in d), n) self.assertEqual(d3, dict.fromkeys(d, 123)) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_container_iterator(self): # Bug #3680: tp_traverse was not implemented for set iterator object class C(object): @@ -670,7 +672,7 @@ def check_unhashable_element(): with check_unhashable_element(): myset.discard(elem) - # Only TypeError exception is overriden, + # Only TypeError exception is overridden, # other exceptions are left unchanged. class HashError: def __hash__(self): @@ -887,10 +889,6 @@ class TestSetSubclassWithSlots(unittest.TestCase): setUp = TestJointOps.setUp test_pickling = TestJointOps.test_pickling - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_pickling(self): - return super().test_pickling() - class FrozenSetSubclassWithSlots(frozenset): __slots__ = ('x', 'y', '__dict__') @@ -1596,6 +1594,14 @@ def setUp(self): #------------------------------------------------------------------------------ +class TestOnlySetsFrozenDict(TestOnlySetsInBinaryOps, unittest.TestCase): + def setUp(self): + self.set = set((1, 2, 3)) + self.other = frozendict({1:2, 3:4}) + self.otherIsIterable = True + +#------------------------------------------------------------------------------ + class TestOnlySetsOperator(TestOnlySetsInBinaryOps, unittest.TestCase): def setUp(self): self.set = set((1, 2, 3)) diff --git a/Lib/test/test_setcomps.py b/Lib/test/test_setcomps.py index 0bb02ef11f6..6fc5bb74036 100644 --- a/Lib/test/test_setcomps.py +++ b/Lib/test/test_setcomps.py @@ -154,7 +154,7 @@ class SetComprehensionTest(unittest.TestCase): def test_exception_locations(self): # The location of an exception raised from __init__ or - # __next__ should should be the iterator expression + # __next__ should be the iterator expression def init_raises(): try: diff --git a/Lib/test/test_shelve.py b/Lib/test/test_shelve.py index 08c6562f2a2..5f6a030e018 100644 --- a/Lib/test/test_shelve.py +++ b/Lib/test/test_shelve.py @@ -1,10 +1,11 @@ +import array import unittest import dbm import shelve import pickle import os -from test.support import os_helper +from test.support import import_helper, os_helper, subTests from collections.abc import MutableMapping from test.test_dbm import dbm_iterator @@ -165,6 +166,255 @@ def test_default_protocol(self): with shelve.Shelf({}) as s: self.assertEqual(s._protocol, pickle.DEFAULT_PROTOCOL) + def test_custom_serializer_and_deserializer(self): + os.mkdir(self.dirname) + self.addCleanup(os_helper.rmtree, self.dirname) + + def serializer(obj, protocol): + if isinstance(obj, (bytes, bytearray, str)): + if protocol == 5: + if isinstance(obj, bytearray): + return bytes(obj) # DBM backends expect bytes + return obj + return type(obj).__name__ + elif isinstance(obj, array.array): + return obj.tobytes() + raise TypeError(f"Unsupported type for serialization: {type(obj)}") + + def deserializer(data): + if isinstance(data, (bytes, bytearray, str)): + return data.decode("utf-8") + elif isinstance(data, array.array): + return array.array("b", data) + raise TypeError( + f"Unsupported type for deserialization: {type(data)}" + ) + + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto), shelve.open( + self.fn, + protocol=proto, + serializer=serializer, + deserializer=deserializer + ) as s: + bar = "bar" + bytes_data = b"Hello, world!" + bytearray_data = bytearray(b"\x00\x01\x02\x03\x04") + array_data = array.array("i", [1, 2, 3, 4, 5]) + + s["foo"] = bar + s["bytes_data"] = bytes_data + s["bytearray_data"] = bytearray_data + s["array_data"] = array_data + + if proto == 5: + self.assertEqual(s["foo"], str(bar)) + self.assertEqual(s["bytes_data"], "Hello, world!") + self.assertEqual( + s["bytearray_data"], bytearray_data.decode() + ) + self.assertEqual( + s["array_data"], array_data.tobytes().decode() + ) + else: + self.assertEqual(s["foo"], "str") + self.assertEqual(s["bytes_data"], "bytes") + self.assertEqual(s["bytearray_data"], "bytearray") + self.assertEqual( + s["array_data"], array_data.tobytes().decode() + ) + + @subTests("serialized", [None, ["invalid type"]]) + def test_custom_invalid_serializer(self, serialized): + test_dir = f"{self.dirname}_{id(serialized)}" + os.mkdir(test_dir) + self.addCleanup(os_helper.rmtree, test_dir) + test_fn = os.path.join(test_dir, "shelftemp.db") + + def serializer(obj, protocol=None): + return serialized + + def deserializer(data): + return data.decode("utf-8") + + # Since the serializer returns an invalid type or None, + # dbm.error is raised by dbm.sqlite3 and TypeError is raised + # by other backends. + with self.assertRaises((TypeError, dbm.error)): + with shelve.open(test_fn, serializer=serializer, + deserializer=deserializer) as s: + s["foo"] = "bar" + + def test_custom_incomplete_deserializer(self): + os.mkdir(self.dirname) + self.addCleanup(os_helper.rmtree, self.dirname) + + def serializer(obj, protocol=None): + return type(obj).__name__.encode("utf-8") + + def deserializer(data): + pass + + with shelve.open(self.fn, serializer=serializer, + deserializer=deserializer) as s: + s["foo"] = "bar" + self.assertNotEqual(s["foo"], "bar") + self.assertIsNone(s["foo"]) + + def test_custom_serializer_and_deserializer_bsd_db_shelf(self): + berkeleydb = import_helper.import_module("berkeleydb") + os.mkdir(self.dirname) + self.addCleanup(os_helper.rmtree, self.dirname) + + def serializer(obj, protocol=None): + data = obj.__class__.__name__ + if protocol == 5: + data = str(len(data)) + return data.encode("utf-8") + + def deserializer(data): + return data.decode("utf-8") + + def type_name_len(obj): + return f"{(len(type(obj).__name__))}" + + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + with self.subTest(proto=proto), shelve.BsdDbShelf( + berkeleydb.btopen(self.fn), + protocol=proto, + serializer=serializer, + deserializer=deserializer, + ) as s: + bar = "bar" + bytes_obj = b"Hello, world!" + bytearray_obj = bytearray(b"\x00\x01\x02\x03\x04") + arr_obj = array.array("i", [1, 2, 3, 4, 5]) + + s["foo"] = bar + s["bytes_data"] = bytes_obj + s["bytearray_data"] = bytearray_obj + s["array_data"] = arr_obj + + if proto == 5: + self.assertEqual(s["foo"], type_name_len(bar)) + self.assertEqual(s["bytes_data"], type_name_len(bytes_obj)) + self.assertEqual(s["bytearray_data"], + type_name_len(bytearray_obj)) + self.assertEqual(s["array_data"], type_name_len(arr_obj)) + + k, v = s.set_location(b"foo") + self.assertEqual(k, "foo") + self.assertEqual(v, type_name_len(bar)) + + k, v = s.previous() + self.assertEqual(k, "bytes_data") + self.assertEqual(v, type_name_len(bytes_obj)) + + k, v = s.previous() + self.assertEqual(k, "bytearray_data") + self.assertEqual(v, type_name_len(bytearray_obj)) + + k, v = s.previous() + self.assertEqual(k, "array_data") + self.assertEqual(v, type_name_len(arr_obj)) + + k, v = s.next() + self.assertEqual(k, "bytearray_data") + self.assertEqual(v, type_name_len(bytearray_obj)) + + k, v = s.next() + self.assertEqual(k, "bytes_data") + self.assertEqual(v, type_name_len(bytes_obj)) + + k, v = s.first() + self.assertEqual(k, "array_data") + self.assertEqual(v, type_name_len(arr_obj)) + else: + k, v = s.set_location(b"foo") + self.assertEqual(k, "foo") + self.assertEqual(v, "str") + + k, v = s.previous() + self.assertEqual(k, "bytes_data") + self.assertEqual(v, "bytes") + + k, v = s.previous() + self.assertEqual(k, "bytearray_data") + self.assertEqual(v, "bytearray") + + k, v = s.previous() + self.assertEqual(k, "array_data") + self.assertEqual(v, "array") + + k, v = s.next() + self.assertEqual(k, "bytearray_data") + self.assertEqual(v, "bytearray") + + k, v = s.next() + self.assertEqual(k, "bytes_data") + self.assertEqual(v, "bytes") + + k, v = s.first() + self.assertEqual(k, "array_data") + self.assertEqual(v, "array") + + self.assertEqual(s["foo"], "str") + self.assertEqual(s["bytes_data"], "bytes") + self.assertEqual(s["bytearray_data"], "bytearray") + self.assertEqual(s["array_data"], "array") + + def test_custom_incomplete_deserializer_bsd_db_shelf(self): + berkeleydb = import_helper.import_module("berkeleydb") + os.mkdir(self.dirname) + self.addCleanup(os_helper.rmtree, self.dirname) + + def serializer(obj, protocol=None): + return type(obj).__name__.encode("utf-8") + + def deserializer(data): + pass + + with shelve.BsdDbShelf(berkeleydb.btopen(self.fn), + serializer=serializer, + deserializer=deserializer) as s: + s["foo"] = "bar" + self.assertIsNone(s["foo"]) + self.assertNotEqual(s["foo"], "bar") + + def test_custom_incomplete_serializer_bsd_db_shelf(self): + berkeleydb = import_helper.import_module("berkeleydb") + os.mkdir(self.dirname) + self.addCleanup(os_helper.rmtree, self.dirname) + + def serializer(obj, protocol=None): + pass + + def deserializer(data): + return data.decode("utf-8") + + with shelve.BsdDbShelf(berkeleydb.btopen(self.fn), + serializer=serializer, + deserializer=deserializer) as s: + s["foo"] = "bar" + self.assertEqual(s["foo"], "") + self.assertNotEqual(s["foo"], "bar") + + def test_missing_custom_deserializer(self): + def serializer(obj, protocol=None): + pass + + kwargs = dict(protocol=2, writeback=False, serializer=serializer) + self.assertRaises(shelve.ShelveError, shelve.Shelf, {}, **kwargs) + self.assertRaises(shelve.ShelveError, shelve.BsdDbShelf, {}, **kwargs) + + def test_missing_custom_serializer(self): + def deserializer(data): + pass + + kwargs = dict(protocol=2, writeback=False, deserializer=deserializer) + self.assertRaises(shelve.ShelveError, shelve.Shelf, {}, **kwargs) + self.assertRaises(shelve.ShelveError, shelve.BsdDbShelf, {}, **kwargs) + class TestShelveBase: type2test = shelve.Shelf diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py index 8813cc46cb6..02bc920702b 100644 --- a/Lib/test/test_shutil.py +++ b/Lib/test/test_shutil.py @@ -493,6 +493,37 @@ def check_args_to_onexc(self, func, arg, exc): self.assertTrue(isinstance(exc, OSError)) self.errorState = 3 + @os_helper.skip_if_dac_override + @os_helper.skip_unless_working_chmod + @unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks, + 'requires the fd based implementation of rmtree()') + def test_on_exc_kwargs(self): + os.mkdir(TESTFN) + self.addCleanup(shutil.rmtree, TESTFN) + + child_dir_path = os.path.join(TESTFN, 'b') + child_file_path = os.path.join(child_dir_path, 'a') + os.mkdir(child_dir_path) + os_helper.create_empty_file(child_file_path) + old_child_dir_mode = os.stat(child_dir_path).st_mode + # Make unwritable. + new_mode = stat.S_IREAD|stat.S_IEXEC + os.chmod(child_dir_path, new_mode) + + self.addCleanup(os.chmod, child_dir_path, old_child_dir_mode) + + calls = [] + def onexc(func, path, err, direntry=None, dir_fd=None): + calls.append((func, path, err)) + if func is os.unlink: + self.assertEqual(direntry.name, os.path.basename(path)) + self.assertTrue(os.path.samestat( + os.stat(path), os.stat(direntry.name, dir_fd=dir_fd))) + + shutil.rmtree(TESTFN, onexc=onexc, _onexc_kwargs=True) + self.assertIn((os.unlink, child_file_path), + [(func, path) for func, path, err in calls]) + @unittest.skipIf(sys.platform[:6] == 'cygwin', "This test can't be run on Cygwin (issue #1071513).") @os_helper.skip_if_dac_override @@ -2042,6 +2073,32 @@ def test_make_zipfile_in_curdir(self): self.assertEqual(make_archive('test', 'zip'), 'test.zip') self.assertTrue(os.path.isfile('test.zip')) + def test_make_archive_pathlike_cwd_default(self): + called_args = [] + def archiver(base_name, base_dir, **kw): + called_args.append((base_name, kw.get('root_dir'))) + + register_archive_format('xxx', archiver, [], 'xxx file') + self.addCleanup(unregister_archive_format, 'xxx') + with no_chdir: + make_archive(FakePath('basename'), 'xxx') + self.assertEqual(called_args, [('basename', None)]) + + def test_make_archive_pathlike_cwd_supports_root_dir(self): + root_dir = self.mkdtemp() + called_args = [] + def archiver(base_name, base_dir, **kw): + called_args.append((base_name, base_dir, kw.get('root_dir'))) + archiver.supports_root_dir = True + + register_archive_format('xxx', archiver, [], 'xxx file') + self.addCleanup(unregister_archive_format, 'xxx') + with no_chdir: + make_archive(FakePath('basename'), 'xxx', + root_dir=FakePath(root_dir), + base_dir=FakePath('basedir')) + self.assertEqual(called_args, [('basename', 'basedir', root_dir)]) + def test_register_archive_format(self): self.assertRaises(TypeError, register_archive_format, 'xxx', 1) @@ -3572,7 +3629,7 @@ def test_module_all_attribute(self): target_api.append('disk_usage') self.assertEqual(set(shutil.__all__), set(target_api)) with self.assertWarns(DeprecationWarning): - from shutil import ExecError + from shutil import ExecError # noqa: F401 if __name__ == '__main__': diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py index a4af92d52eb..82274a57005 100644 --- a/Lib/test/test_signal.py +++ b/Lib/test/test_signal.py @@ -14,7 +14,7 @@ import unittest from test import support from test.support import ( - is_apple, is_apple_mobile, os_helper, threading_helper + force_not_colorized, is_apple, is_apple_mobile, os_helper, threading_helper ) from test.support.script_helper import assert_python_ok, spawn_python try: @@ -355,6 +355,7 @@ def check_signum(signals): @unittest.skipIf(_testcapi is None, 'need _testcapi') @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()") + @force_not_colorized def test_wakeup_write_error(self): # Issue #16105: write() errors in the C signal handler should not # pass silently. @@ -1443,7 +1444,6 @@ def handler(a, b): signal.raise_signal(signal.SIGINT) self.assertTrue(is_ok) - @unittest.expectedFailure # TODO: RUSTPYTHON def test__thread_interrupt_main(self): # See https://github.com/python/cpython/issues/102397 code = """if 1: diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py index 3c6d48568da..40dcd319e87 100644 --- a/Lib/test/test_site.py +++ b/Lib/test/test_site.py @@ -16,6 +16,7 @@ from test.support.script_helper import spawn_python, kill_python import ast import builtins +import contextlib import glob import io import os @@ -27,6 +28,7 @@ import sysconfig import tempfile from textwrap import dedent +from types import SimpleNamespace import urllib.error import urllib.request from unittest import mock @@ -123,14 +125,11 @@ def test_addpackage(self): # comment or import that is a valid directory name for where the .pth # file resides; invalid directories are not added pth_file = PthFile() - pth_file.cleanup(prep=True) # to make sure that nothing is - # pre-existing that shouldn't be - try: - pth_file.create() + # Ensure we have a clean slate. + pth_file.cleanup(prep=True) + with pth_file.create(): site.addpackage(pth_file.base_dir, pth_file.filename, set()) self.pth_file_tests(pth_file) - finally: - pth_file.cleanup() def make_pth(self, contents, pth_dir='.', pth_name=TESTFN): # Create a .pth file and return its (abspath, basename). @@ -150,9 +149,6 @@ def test_addpackage_import_bad_syntax(self): self.assertRegex(err_out.getvalue(), "line 1") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) - # XXX: the previous two should be independent checks so that the - # order doesn't matter. The next three could be a single check - # but my regex foo isn't good enough to write it. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), r'import bad-syntax') self.assertRegex(err_out.getvalue(), 'SyntaxError') @@ -162,10 +158,8 @@ def test_addpackage_import_bad_exec(self): pth_dir, pth_fn = self.make_pth("randompath\nimport nosuchmodule\n") with captured_stderr() as err_out: site.addpackage(pth_dir, pth_fn, set()) - self.assertRegex(err_out.getvalue(), "line 2") self.assertRegex(err_out.getvalue(), re.escape(os.path.join(pth_dir, pth_fn))) - # XXX: ditto previous XXX comment. self.assertRegex(err_out.getvalue(), 'Traceback') self.assertRegex(err_out.getvalue(), 'ModuleNotFoundError') @@ -178,65 +172,97 @@ def test_addpackage_empty_lines(self): def test_addpackage_import_bad_pth_file(self): # Issue 5258 pth_dir, pth_fn = self.make_pth("abc\x00def\n") - with captured_stderr() as err_out: - self.assertFalse(site.addpackage(pth_dir, pth_fn, set())) - self.maxDiff = None - self.assertEqual(err_out.getvalue(), "") for path in sys.path: if isinstance(path, str): self.assertNotIn("abc\x00def", path) def test_addsitedir(self): - # Same tests for test_addpackage since addsitedir() essentially just - # calls addpackage() for every .pth file in the directory + # addsitedir() reads .pth files and, when called standalone + # (known_paths=None), flushes paths and import lines immediately. pth_file = PthFile() - pth_file.cleanup(prep=True) # Make sure that nothing is pre-existing - # that is tested for - try: - pth_file.create() - site.addsitedir(pth_file.base_dir, set()) + # Ensure we have a clean slate. + pth_file.cleanup(prep=True) + with pth_file.create(): + site.addsitedir(pth_file.base_dir) + self.pth_file_tests(pth_file) + + def test_addsitedir_explicit_flush(self): + # StartupState.addsitedir() reads .pth files and accumulates pending + # state without flushing. A subsequent state.process() call then + # applies the paths and runs the import lines. + pth_file = PthFile() + # Ensure we have a clean slate. + pth_file.cleanup(prep=True) + with pth_file.create(): + state = site.StartupState(known_paths=set()) + state.addsitedir(pth_file.base_dir) + self.assertNotIn(pth_file.imported, sys.modules) + state.process() self.pth_file_tests(pth_file) - finally: - pth_file.cleanup() def test_addsitedir_dotfile(self): pth_file = PthFile('.dotfile') + # Ensure we have a clean slate. pth_file.cleanup(prep=True) - try: - pth_file.create() - site.addsitedir(pth_file.base_dir, set()) + with pth_file.create(): + site.addsitedir(pth_file.base_dir) self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path) self.assertIn(pth_file.base_dir, sys.path) - finally: - pth_file.cleanup() @unittest.skipUnless(hasattr(os, 'chflags'), 'test needs os.chflags()') def test_addsitedir_hidden_flags(self): pth_file = PthFile() + # Ensure we have a clean slate. pth_file.cleanup(prep=True) - try: - pth_file.create() + with pth_file.create(): st = os.stat(pth_file.file_path) os.chflags(pth_file.file_path, st.st_flags | stat.UF_HIDDEN) - site.addsitedir(pth_file.base_dir, set()) + site.addsitedir(pth_file.base_dir) self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path) self.assertIn(pth_file.base_dir, sys.path) - finally: - pth_file.cleanup() @unittest.skipUnless(sys.platform == 'win32', 'test needs Windows') @support.requires_subprocess() def test_addsitedir_hidden_file_attribute(self): pth_file = PthFile() + # Ensure we have a clean slate. pth_file.cleanup(prep=True) - try: - pth_file.create() + with pth_file.create(): subprocess.check_call(['attrib', '+H', pth_file.file_path]) - site.addsitedir(pth_file.base_dir, set()) + site.addsitedir(pth_file.base_dir) self.assertNotIn(site.makepath(pth_file.good_dir_path)[0], sys.path) self.assertIn(pth_file.base_dir, sys.path) - finally: - pth_file.cleanup() + + def test_sitedir_variable(self): + # gh-149671: setuptools use of `-nspkg.pth` files in Python < 3.15. + code = '; '.join(( + # Code used by "-nspkg.pth" files generated by setuptools. + "import sys", + "sitedir = sys._getframe(1).f_locals['sitedir']", + "print(sitedir)", + )) + pth_dir, pth_fn = self.make_pth(code) + with support.captured_stdout() as stdout: + known_paths = site.addpackage(pth_dir, pth_fn, set()) + sitedir = stdout.getvalue().rstrip() + self.assertEqual(sitedir, pth_dir) + + def test_fullname_variable(self): + # gh-156404: ".pth" files generated before Python 3.15 read the path + # of the file being processed from the frame executing the import + # line, under the name "fullname". For example, "wheel-axle" + # generates: "import wheel_axle.runtime; + # wheel_axle.runtime.finalize(fullname);" + code = '; '.join(( + "import sys", + "print(fullname)", + "print(filename)", + )) + pth_dir, pth_fn = self.make_pth(code) + with support.captured_stdout() as stdout: + site.addpackage(pth_dir, pth_fn, set()) + expected = os.path.join(pth_dir, pth_fn) + self.assertEqual(stdout.getvalue().splitlines(), [expected, expected]) # This tests _getuserbase, hence the double underline # to distinguish from a test for getuserbase @@ -402,7 +428,7 @@ def test_trace(self): self.assertEqual(sys.stderr.getvalue(), out) -class PthFile(object): +class PthFile: """Helper class for handling testing of .pth files""" def __init__(self, filename_base=TESTFN, imported="time", @@ -417,6 +443,7 @@ def __init__(self, filename_base=TESTFN, imported="time", self.good_dir_path = os.path.join(self.base_dir, self.good_dirname) self.bad_dir_path = os.path.join(self.base_dir, self.bad_dirname) + @contextlib.contextmanager def create(self): """Create a .pth file with a comment, blank lines, an ``import ``, a line with self.good_dirname, and a line with @@ -425,19 +452,21 @@ def create(self): Creation of the directory for self.good_dir_path (based off of self.good_dirname) is also performed. - Make sure to call self.cleanup() to undo anything done by this method. - + Used as a context manager: self.cleanup() is called on exit. """ - FILE = open(self.file_path, 'w') + with open(self.file_path, 'w') as fp: + print(f"""\ +#import @bad module name +import {self.imported} +{self.good_dirname} +{self.bad_dirname} +""", file=fp) + + os.mkdir(self.good_dir_path) try: - print("#import @bad module name", file=FILE) - print("\n", file=FILE) - print("import %s" % self.imported, file=FILE) - print(self.good_dirname, file=FILE) - print(self.bad_dirname, file=FILE) + yield self finally: - FILE.close() - os.mkdir(self.good_dir_path) + self.cleanup() def cleanup(self, prep=False): """Make sure that the .pth file is deleted, self.imported is not in @@ -457,6 +486,7 @@ def cleanup(self, prep=False): if os.path.exists(self.bad_dir_path): os.rmdir(self.bad_dir_path) + class ImportSideEffectTests(unittest.TestCase): """Test side-effects from importing 'site'.""" @@ -468,17 +498,6 @@ def tearDown(self): """Restore sys.path""" sys.path[:] = self.sys_path - def test_abs_paths_cached_None(self): - """Test for __cached__ is None. - - Regarding to PEP 3147, __cached__ can be None. - - See also: https://bugs.python.org/issue30167 - """ - sys.modules['test'].__cached__ = None - site.abs_paths() - self.assertIsNone(sys.modules['test'].__cached__) - def test_no_duplicate_paths(self): # No duplicate paths should exist in sys.path # Handled by removeduppaths() @@ -557,7 +576,6 @@ def test_customization_modules_on_startup(self): output = subprocess.check_output([sys.executable, '-s', '-c', '""']) self.assertNotIn(eyecatcher, output.decode('utf-8')) - @unittest.skipUnless(hasattr(urllib.request, "HTTPSHandler"), 'need SSL support to download license') @test.support.requires_resource('network') @@ -723,7 +741,6 @@ def _get_pth_lines(self, libpath: str, *, import_site: bool): pth_lines.append('import site') return pth_lines - @unittest.expectedFailure # TODO: RUSTPYTHON @support.requires_subprocess() def test_underpth_basic(self): pth_lines = ['#.', '# ..', *sys.path, '.', '..'] @@ -743,7 +760,6 @@ def test_underpth_basic(self): "sys.path is incorrect" ) - @unittest.expectedFailure # TODO: RUSTPYTHON @support.requires_subprocess() def test_underpth_nosite_file(self): libpath = test.support.STDLIB_DIR @@ -768,7 +784,6 @@ def test_underpth_nosite_file(self): "sys.path is incorrect" ) - @unittest.expectedFailure # TODO: RUSTPYTHON @support.requires_subprocess() def test_underpth_file(self): libpath = test.support.STDLIB_DIR @@ -789,7 +804,6 @@ def test_underpth_file(self): )], env=env) self.assertTrue(rc, "sys.path is incorrect") - @unittest.expectedFailure # TODO: RUSTPYTHON @support.requires_subprocess() def test_underpth_dll_file(self): libpath = test.support.STDLIB_DIR @@ -810,6 +824,15 @@ def test_underpth_dll_file(self): )], env=env) self.assertTrue(rc, "sys.path is incorrect") + @support.requires_subprocess() + def test_underpth_no_user_site(self): + pth_lines = [test.support.STDLIB_DIR, 'import site'] + exe_file = self._create_underpth_exe(pth_lines) + p = subprocess.run([exe_file, '-X', 'utf8', '-c', + 'import sys; ' + 'sys.exit(not sys.flags.no_user_site)']) + self.assertEqual(p.returncode, 0, "sys.flags.no_user_site was 0") + class CommandLineTests(unittest.TestCase): def exists(self, path): @@ -916,5 +939,837 @@ def test_both_args(self): self.assertEqual(output, excepted_output) +class StartFileTests(unittest.TestCase): + """Tests for .start file processing (PEP 829).""" + + def setUp(self): + self.enterContext(import_helper.DirsOnSysPath()) + self.tmpdir = self.sitedir = self.enterContext(os_helper.temp_dir()) + # Each test gets its own StartupState to batch the parsing and + # explicitly invoke the processing. Seed with an empty known_paths + # so dedup is not influenced by the current sys.path. + self.state = site.StartupState(known_paths=set()) + + def _make_start(self, content, name='testpkg', basedir=None): + """Write a .start file and return its basename. + + ``basedir`` defaults to ``self.tmpdir``. Pass an explicit directory + when the .start file needs to live somewhere other than the test's + primary tmpdir (e.g. a nested user-site). + """ + basename = f"{name}.start" + filepath = os.path.join(self.tmpdir if basedir is None else basedir, basename) + with open(filepath, 'w', encoding='utf-8') as f: + f.write(content) + return basename + + def _make_pth(self, content, name='testpkg', basedir=None): + """Write a .pth file and return its basename. + + ``basedir`` defaults to ``self.tmpdir``. Pass an explicit directory + when the .pth file needs to live somewhere other than the test's + primary tmpdir (e.g. a nested user-site). + """ + basename = f"{name}.pth" + filepath = os.path.join(self.tmpdir if basedir is None else basedir, basename) + with open(filepath, 'w', encoding='utf-8') as f: + f.write(content) + return basename + + def _make_mod(self, contents, name='mod', *, package=False, on_path=False): + """Write an importable module (or package), returning its parent dir.""" + extdir = os.path.join(self.sitedir, 'extdir') + os.makedirs(extdir, exist_ok=True) + + # Put the code in a package's dunder-init or flat module. + if package: + pkgdir = os.path.join(extdir, name) + os.mkdir(pkgdir) + modpath = os.path.join(pkgdir, '__init__.py') + else: + modpath = os.path.join(extdir, f'{name}.py') + + with open(modpath, 'w') as fp: + fp.write(contents) + + self.addCleanup(sys.modules.pop, name, None) + if on_path: + # Don't worry, DirsOnSysPath() in setUp() will clean this up. + sys.path.insert(0, extdir) + return extdir + + def _all_entrypoints(self, state=None): + """Flatten state._entrypoints into a list of (filename, entry) tuples.""" + result = [] + state = self.state if state is None else state + for filename, entries in state._entrypoints.items(): + for entry in entries: + result.append((filename, entry)) + return result + + def _just_entrypoints(self, state=None): + return [entry for filename, entry in self._all_entrypoints(state)] + + # There are two classes of tests here. Tests that start with `test_impl_` + # know details about the implementation and they access non-public methods + # and data structures to perform focused functional tests. + # + # Tests that start with `test_addsitedir_` are end-to-end tests that ensure + # integration semantics and functionality as a caller of the public + # surfaces would see. + + # --- Basic StartupState implementation tests --- + + def test_impl_startupstate_defaults_to_sys_path(self): + sys.path.insert(0, self.sitedir) + state = site.StartupState() + self.assertIn(site.makepath(self.sitedir)[1], state._known_paths) + + def test_impl_startupstate_uses_supplied_known_paths(self): + known_paths = set() + state = site.StartupState(known_paths) + state.addsitedir(self.sitedir) + self.assertIs(state._known_paths, known_paths) + self.assertIn(site.makepath(self.sitedir)[1], known_paths) + + # --- StartupState._read_start_file tests --- + + def test_impl_read_start_file_basic(self): + self._make_start("os.path:join\n", name='foo') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual( + self.state._entrypoints[fullname], ['os.path:join'] + ) + + def test_impl_read_start_file_multiple_entries(self): + self._make_start("os.path:join\nos.path:exists\n", name='foo') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual( + self.state._entrypoints[fullname], + ['os.path:join', 'os.path:exists'], + ) + + def test_impl_read_start_file_comments_and_blanks(self): + self._make_start("# a comment\n\nos.path:join\n \n", name='foo') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual( + self.state._entrypoints[fullname], ['os.path:join'] + ) + + def test_impl_read_start_file_accepts_all_non_blank_lines(self): + # Syntax validation is deferred to entry-point execution time + # (where pkgutil.resolve_name(strict=True) enforces the strict + # pkg.mod:callable form), so parsing accepts every non-blank, + # non-comment line, including syntactically invalid ones. + content = ( + "os.path\n" # no colon + "pkg.mod:\n" # empty callable + ":callable\n" # empty module + "pkg.mod:callable:extra\n" # multiple colons + "os.path:join\n" # valid + ) + self._make_start(content, name='foo') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual(self.state._entrypoints[fullname], [ + 'os.path', + 'pkg.mod:', + ':callable', + 'pkg.mod:callable:extra', + 'os.path:join', + ]) + + def test_impl_read_start_file_empty(self): + # PEP 829: an empty .start file is still registered as present + # (with an empty entry point list) so that it suppresses `import` + # lines in any matching .pth file. + self._make_start("", name='foo') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual(self.state._entrypoints, {fullname: []}) + + def test_impl_read_start_file_comments_only(self): + # As with an empty file, a comments-only .start file is registered + # as present so it can suppress matching .pth `import` lines. + self._make_start("# just a comment\n# another\n", name='foo') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual(self.state._entrypoints, {fullname: []}) + + def test_impl_read_start_file_nonexistent(self): + with captured_stderr(): + self.state._read_start_file(self.tmpdir, 'nonexistent.start') + self.assertEqual(self.state._entrypoints, {}) + + @unittest.skipUnless(hasattr(os, 'chflags'), 'test needs os.chflags()') + def test_impl_read_start_file_hidden_flags(self): + self._make_start("os.path:join\n", name='foo') + filepath = os.path.join(self.tmpdir, 'foo.start') + st = os.stat(filepath) + os.chflags(filepath, st.st_flags | stat.UF_HIDDEN) + self.state._read_start_file(self.sitedir, 'foo.start') + self.assertEqual(self.state._entrypoints, {}) + + def test_impl_one_start_file_with_duplicates_not_deduplicated(self): + # PEP 829: duplicate entry points are NOT deduplicated. + self._make_start("os.path:join\nos.path:join\n", name='foo') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual( + self.state._entrypoints[fullname], + ['os.path:join', 'os.path:join'], + ) + + def test_impl_two_start_files_with_duplicates_not_deduplicated(self): + self._make_start("os.path:join", name="foo") + self._make_start("os.path:join", name="bar") + self.state._read_start_file(self.sitedir, 'foo.start') + self.state._read_start_file(self.sitedir, 'bar.start') + self.assertEqual( + self._just_entrypoints(), + ['os.path:join', 'os.path:join'], + ) + + def test_impl_read_start_file_accepts_utf8_bom(self): + # PEP 829: .start files MUST be utf-8-sig (UTF-8 with optional BOM). + filepath = os.path.join(self.tmpdir, 'foo.start') + with open(filepath, 'wb') as f: + f.write(b'\xef\xbb\xbf' + b'os.path:join\n') + self.state._read_start_file(self.sitedir, 'foo.start') + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertEqual( + self.state._entrypoints[fullname], ['os.path:join'] + ) + + def test_impl_read_start_file_invalid_utf8_silently_skipped(self): + # PEP 829: .start files MUST be utf-8-sig. Unlike .pth files, there + # is no locale-encoding fallback. A .start file that is not valid + # UTF-8 is silently skipped, with no key registered in + # state._entrypoints and no output to stderr (parsing errors are + # reported only under -v). + filepath = os.path.join(self.tmpdir, 'foo.start') + with open(filepath, 'wb') as f: + # Bare continuation byte -- invalid as a UTF-8 start byte. + f.write(b'\x80\x80\x80\n') + with captured_stderr() as err: + self.state._read_start_file(self.sitedir, 'foo.start') + self.assertEqual(self.state._entrypoints, {}) + self.assertEqual(err.getvalue(), "") + + # --- StartupState._read_pth_file tests --- + + def test_impl_read_pth_file_paths(self): + subdir = os.path.join(self.sitedir, 'mylib') + os.mkdir(subdir) + self._make_pth("mylib\n", name='foo') + self.state._read_pth_file(self.sitedir, 'foo.pth') + fullname = os.path.join(self.sitedir, 'foo.pth') + self.assertIn((fullname, subdir), self.state._path_entries) + + def test_impl_read_pth_file_imports_collected(self): + self._make_pth("import sys\n", name='foo') + self.state._read_pth_file(self.sitedir, 'foo.pth') + fullname = os.path.join(self.sitedir, 'foo.pth') + self.assertEqual( + self.state._importexecs[fullname], ['import sys'] + ) + + def test_impl_read_pth_file_comments_and_blanks(self): + self._make_pth("# comment\n\n \n", name='foo') + self.state._read_pth_file(self.sitedir, 'foo.pth') + self.assertEqual(self.state._path_entries, []) + self.assertEqual(self.state._importexecs, {}) + + def test_impl_read_pth_file_deduplication(self): + subdir = os.path.join(self.sitedir, 'mylib') + os.mkdir(subdir) + # self.state._known_paths acts as the deduplication ledger across + # both reads. + self._make_pth("mylib\n", name='a') + self._make_pth("mylib\n", name='b') + self.state._read_pth_file(self.sitedir, 'a.pth') + self.state._read_pth_file(self.sitedir, 'b.pth') + # There is only one entry across both files. + all_dirs = [dir_ for filename, dir_ in self.state._path_entries] + self.assertEqual(all_dirs, [subdir]) + + def test_impl_read_pth_file_bad_line_continues(self): + # PEP 829: errors on individual lines don't abort processing the file. + subdir = os.path.join(self.sitedir, 'goodpath') + os.mkdir(subdir) + self._make_pth("abc\x00def\ngoodpath\n", name='foo') + with captured_stderr(): + self.state._read_pth_file(self.sitedir, 'foo.pth') + fullname = os.path.join(self.sitedir, 'foo.pth') + self.assertIn((fullname, subdir), self.state._path_entries) + + def _flags_with_verbose(self, verbose): + # Build a sys.flags clone with verbose overridden but every + # other field preserved, so unrelated reads like + # sys.flags.optimize during io.open_code() continue to work. + attrs = { + name: getattr(sys.flags, name) + for name in sys.flags.__match_args__ + } + attrs['verbose'] = verbose + return SimpleNamespace(**attrs) + + def test_impl_read_pth_file_parse_error_silent_by_default(self): + # PEP 829: parse-time errors are silent unless -v is given. + # Force the error path by making makepath() raise an exception. + self._make_pth("badline\n", name='foo') + with ( + mock.patch('site.makepath', side_effect=ValueError("boom")), + mock.patch('sys.flags', self._flags_with_verbose(False)), + captured_stderr() as err, + ): + self.state._read_pth_file(self.sitedir, 'foo.pth') + self.assertEqual(err.getvalue(), "") + + def test_impl_read_pth_file_parse_error_reported_under_verbose(self): + # PEP 829: parse-time errors are reported when -v is given. + self._make_pth("badline\n", name='foo') + with ( + mock.patch('site.makepath', side_effect=ValueError("boom")), + mock.patch('sys.flags', self._flags_with_verbose(True)), + captured_stderr() as err, + ): + self.state._read_pth_file(self.sitedir, 'foo.pth') + out = err.getvalue() + self.assertIn('Error in', out) + self.assertIn('foo.pth', out) + + def test_impl_read_pth_file_locale_fallback(self): + # PEP 829: .pth files that fail UTF-8 decoding fall back to the + # locale encoding for backward compatibility (deprecated in + # 3.15, to be removed in 3.20). Mock locale.getencoding() so + # the test does not depend on the host's actual locale. + subdir = os.path.join(self.sitedir, 'mylib') + os.mkdir(subdir) + filepath = os.path.join(self.tmpdir, 'foo.pth') + # \xe9 is invalid UTF-8 but valid in latin-1. + with open(filepath, 'wb') as f: + f.write(b'# caf\xe9 comment\nmylib\n') + with ( + mock.patch('locale.getencoding', return_value='latin-1'), + captured_stderr(), + ): + self.state._read_pth_file(self.sitedir, 'foo.pth') + fullname = os.path.join(self.sitedir, 'foo.pth') + self.assertIn((fullname, subdir), self.state._path_entries) + + # --- StartupState._execute_start_entrypoints tests --- + + def test_impl_execute_entrypoints_with_callable(self): + # An entry point with a callable. + self._make_mod("""\ +called = False +def startup(): + global called + called = True +""", name='epmod', package=True, on_path=True) + fullname = os.path.join(self.sitedir, 'epmod.start') + self.state._entrypoints[fullname] = ['epmod:startup'] + self.state._execute_start_entrypoints() + import epmod + self.assertTrue(epmod.called) + + def test_impl_execute_entrypoints_import_error(self): + # Import errors print a traceback and continue. + fullname = os.path.join(self.sitedir, 'bad.start') + self.state._entrypoints[fullname] = [ + 'nosuchmodule_xyz:func', 'os.path:join', + ] + with captured_stderr() as err: + self.state._execute_start_entrypoints() + self.assertIn('nosuchmodule_xyz', err.getvalue()) + # os.path:join should still have been called (no exception for it) + + def test_impl_execute_entrypoints_strict_syntax_rejection(self): + # PEP 829: only the strict pkg.mod:callable form is valid. At entry + # point execution time, pkgutil.resolve_name(strict=True) raises a + # ValueError for the invalid syntax. The invalid entry is reported + # and execution continues with the next one. + fullname = os.path.join(self.sitedir, 'bad.start') + self.state._entrypoints[fullname] = [ + 'os.path', # no colon + 'pkg.mod:', # empty callable + ':callable', # empty module + 'pkg.mod:callable:extra', # multiple colons + ] + with captured_stderr() as err: + self.state._execute_start_entrypoints() + out = err.getvalue() + self.assertIn('Invalid entry point syntax', out) + for bad in ( + 'os.path', + 'pkg.mod:', + ':callable', + 'pkg.mod:callable:extra', + ): + self.assertIn(bad, out) + + def test_impl_execute_entrypoints_callable_error(self): + # A callable that errors prints a traceback but continues. + self._make_mod("""\ +def fail(): + raise RuntimeError("boom") +""", name='badmod', package=True, on_path=True) + fullname = os.path.join(self.sitedir, 'badmod.start') + self.state._entrypoints[fullname] = ['badmod:fail'] + with captured_stderr() as err: + self.state._execute_start_entrypoints() + self.assertIn('RuntimeError', err.getvalue()) + self.assertIn('boom', err.getvalue()) + + def test_impl_execute_entrypoints_duplicates_called_twice(self): + # PEP 829: duplicate entry points execute multiple times. + self._make_mod("""\ +call_count = 0 +def bump(): + global call_count + call_count += 1 +""", name='countmod', package=False, on_path=True) + fullname = os.path.join(self.sitedir, 'countmod.start') + self.state._entrypoints[fullname] = [ + 'countmod:bump', 'countmod:bump', + ] + self.state._execute_start_entrypoints() + import countmod + self.assertEqual(countmod.call_count, 2) + + # --- StartupState._exec_imports tests --- + + def test_impl_exec_imports_suppressed_by_matching_start(self): + # Import lines from foo.pth are suppressed when foo.start exists. + self._make_mod("""\ +call_count = 0 +def bump(incr=2): + global call_count + call_count += incr +""", name='countmod', package=False, on_path=True) + self._make_start("countmod:bump\n", name='foo') + self._make_pth("import countmod; countmod.bump(1)\n", name='foo') + self.state._read_pth_file(self.sitedir, 'foo.pth') + self.state._read_start_file(self.sitedir, 'foo.start') + self.state._exec_imports() + self.state._execute_start_entrypoints() + import countmod + # This will be 2 because the entry point is called with no + # arguments, and the .pth import line is never exec'd. + self.assertEqual(countmod.call_count, 2) + + def test_impl_exec_imports_not_suppressed_by_different_start(self): + # Import lines from foo.pth are NOT suppressed by bar.start. + self._make_mod("""\ +call_count = 0 +def bump(): + global call_count + call_count += 1 +""", name='countmod', package=False, on_path=True) + pth_fullname = os.path.join(self.sitedir, 'foo.pth') + start_fullname = os.path.join(self.sitedir, 'bar.start') + self.state._importexecs[pth_fullname] = ['import countmod; countmod.bump()'] + self.state._entrypoints[start_fullname] = ['os.path:join'] + self.state._exec_imports() + import countmod + self.assertEqual(countmod.call_count, 1) + + def test_impl_exec_imports_suppressed_by_empty_matching_start(self): + self._make_start("", name='foo') + self._make_pth("import epmod; epmod.startup()", name='foo') + self._make_mod("""\ +called = False +def startup(): + global called + called = True +""", name='epmod', package=True, on_path=True) + self.state._read_pth_file(self.sitedir, 'foo.pth') + self.state._read_start_file(self.sitedir, 'foo.start') + self.state._exec_imports() + import epmod + self.assertFalse(epmod.called) + + # --- StartupState._extend_syspath tests --- + + def test_impl_extend_syspath_existing_dir(self): + subdir = os.path.join(self.sitedir, 'extlib') + os.mkdir(subdir) + self.state._path_entries.append(('test.pth', subdir)) + self.state._extend_syspath() + self.assertIn(subdir, sys.path) + + def test_impl_extend_syspath_nonexistent_dir(self): + nonesuch = os.path.join(self.sitedir, 'nosuchdir') + self.state._path_entries.append(('test.pth', nonesuch)) + with captured_stderr() as err: + self.state._extend_syspath() + self.assertNotIn(nonesuch, sys.path) + self.assertIn('does not exist', err.getvalue()) + + # --- addsitedir integration tests --- + + def test_addsitedir_pth_import_skipped_when_matching_start_exists(self): + # PEP 829: an empty .start file disables the matching .pth's import + # lines, even when the .start has no entry points of its own. + self._make_mod("flag = False\n", name='suppressed', on_path=True) + self._make_start("", name='foo') + self._make_pth( + "import suppressed; suppressed.flag = True\n", + name='foo') + site.addsitedir(self.sitedir, set()) + import suppressed + self.assertFalse( + suppressed.flag, + "import line in foo.pth should be suppressed by foo.start") + + def test_addsitedir_dotfile_start_entrypoint_not_executed(self): + # .start files starting with '.' are skipped, so their entry + # points must not run. + self._make_mod("""\ +called = False +def hook(): + global called + called = True +""", + name='dotted', on_path=True) + self._make_start("dotted:hook\n", name='.hidden') + site.addsitedir(self.sitedir, set()) + import dotted + self.assertFalse(dotted.called) + + def test_addsitedir_dedups_paths_across_pth_files(self): + # PEP 829: when multiple .pth files reference the same path within + # a single addsitedir() invocation, the path is appended to + # sys.path exactly once. + subdir = os.path.join(self.sitedir, 'shared') + os.mkdir(subdir) + self._make_pth("shared\n", name='a') + self._make_pth("shared\n", name='b') + before = sys.path.count(subdir) + site.addsitedir(self.sitedir, set()) + self.assertEqual(sys.path.count(subdir), before + 1) + + def test_addsitedir_discovers_start_files(self): + # addsitedir() should discover .start files and accumulate entries. + self._make_start("os.path:join\n", name='foo') + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + fullname = os.path.join(self.sitedir, 'foo.start') + self.assertIn( + 'os.path:join', state._entrypoints[fullname] + ) + + def test_addsitedir_pth_paths_still_work_with_start(self): + # Path lines in .pth files still work even when a .start file exists. + subdir = os.path.join(self.sitedir, 'mylib') + os.mkdir(subdir) + self._make_start("os.path:join\n", name='foo') + self._make_pth("mylib\n", name='foo') + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + fullname = os.path.join(self.sitedir, 'foo.pth') + self.assertIn((fullname, subdir), state._path_entries) + + def test_addsitedir_start_alphabetical_order(self): + # Multiple .start files are discovered alphabetically. + self._make_start("os.path:join\n", name='zzz') + self._make_start("os.path:exists\n", name='aaa') + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + entries = self._just_entrypoints(state) + idx_a = entries.index('os.path:exists') + idx_z = entries.index('os.path:join') + self.assertLess(idx_a, idx_z) + + def test_addsitedir_pth_and_start(self): + # Create a .pth and .start with the same basename; verify both the + # .pth data and .start data is collected. + subdir = os.path.join(self.sitedir, 'mylib') + os.mkdir(subdir) + self._make_pth("mylib\n", name='foo') + self._make_start("os.path:join\n", name='foo') + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + # Both should be collected. + pth_fullname = os.path.join(self.sitedir, 'foo.pth') + start_fullname = os.path.join(self.sitedir, 'foo.start') + self.assertIn((pth_fullname, subdir), state._path_entries) + self.assertIn( + 'os.path:join', + state._entrypoints.get(start_fullname, []), + ) + + def test_impl_addsitedir_skips_dotfile_start(self): + # .start files starting with '.' are skipped. + # This will create `.hidden.start`. + self._make_start("os.path:join\n", name='.hidden') + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + self.assertEqual(state._entrypoints, {}) + + def test_addsitedir_standalone_flushes(self): + # Standalone addsitedir creates a per-call StartupState and processes + # it before returning, so the caller sees the effect immediately. + subdir = os.path.join(self.sitedir, 'flushlib') + os.mkdir(subdir) + self._make_pth("flushlib\n", name='foo') + # No arguments means state is implied and processing is eager. + site.addsitedir(self.sitedir) + self.assertIn(subdir, sys.path) + + def test_addsitedir_explicit_startup_state_does_not_flush(self): + # With an explicit StartupState, addsitedir accumulates pending state + # but does not flush it; sys.path is updated only when process() is + # called explicitly. + subdir = os.path.join(self.sitedir, 'acclib') + os.mkdir(subdir) + self._make_pth("acclib\n", name='foo') + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + # Path is pending, not yet on sys.path. + self.assertNotIn(subdir, sys.path) + fullname = os.path.join(self.sitedir, 'foo.pth') + self.assertIn((fullname, subdir), state._path_entries) + + def test_addsitedir_startup_state_preserves_site_relative_order(self): + # As pointed out by @ncoghlan in + # https://github.com/python/cpython/issues/150228#issuecomment-4528614952 + # a subtle ordering change was inadvertently introduced where the + # interspersing of the sitedirs with the sys.path extensions they defined + # was lost during batch mode. You'd see all the sitedirs, then all path + # extensions. This test ensures that the old interspersing behavior + # has been restored. + # + # Let's start by creating two sitedirs, each with an extension directory + # which will be added to sys.path by .pth files in the respective sitedirs. + sitedir2 = self.enterContext(os_helper.temp_dir()) + extdir1 = os.path.join(self.sitedir, 'ext1') + extdir2 = os.path.join(sitedir2, 'ext2') + os.mkdir(extdir1) + os.mkdir(extdir2) + self._make_pth(extdir1 + "\n", name='one') + self._make_pth(extdir2 + "\n", name='two', basedir=sitedir2) + # Now create an explicit batch, add each sitedir, then process the + # entire batch. + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + state.addsitedir(sitedir2) + state.process() + # Ensure that on sys.path we see this interspersed order: + # [sitedir1, extdir1, sitedir2, extdir2] + indexes = [ + sys.path.index(path) + for path in (self.sitedir, extdir1, sitedir2, extdir2) + ] + # If the index ordering is the same, we preserved the intersperse. + self.assertEqual(indexes, sorted(indexes)) + + def test_addsitedir_startup_state_paths_before_entrypoints(self): + # Ensure that sys.path extensions are available by the time + # .start file entry points are called. + extdir = self._make_mod("""\ +called = False +def hook(): + global called + called = True +""") + self.assertNotIn(extdir, sys.path) + self._make_pth("extdir\n", name='extlib') + self._make_start("mod:hook\n", name='extlib') + # Before the startup state is explicitly processed, neither + # the path extension is added, nor the entry point called. + state = site.StartupState(known_paths=set()) + state.addsitedir(self.sitedir) + self.assertNotIn(extdir, sys.path) + self.assertNotIn('mod', sys.modules) + # After processing the batch, sys.path is extended and + # the entry point was called. + state.process() + self.assertIn(extdir, sys.path) + import mod + self.assertTrue(mod.called) + + def test_pth_path_is_available_to_start_entrypoint(self): + # Core PEP 829 invariant: all .pth path extensions are applied to + # sys.path *before* any .start entry point runs, so an entry + # point may live in a module reachable only via a .pth-extended + # path. If the flush phases were inverted, resolving the entry + # point would fail with ModuleNotFoundError. + extdir = self._make_mod("""\ +called = False +def hook(): + global called + called = True +""") + # extdir is not on sys.path; only the .pth file makes it so. + self.assertNotIn(extdir, sys.path) + self._make_pth("extdir\n", name='extlib') + self._make_start("mod:hook\n", name='extlib') + + # Standalone addsitedir() triggers the full flush sequence. + site.addsitedir(self.sitedir) + + self.assertIn(extdir, sys.path) + import mod + self.assertTrue( + mod.called, + "entry point did not run; .pth path was likely not applied " + "before .start entry-point execution") + + # --- bugs --- + + # gh-75723 + def test_addsitdir_idempotent_pth(self): + # Adding the same sitedir twice with a known_paths, should not + # process .pth files twice. + extdir = self._make_mod("""\ +_pth_count = 0 +""") + self._make_pth(f"""\ +{extdir} +import mod; mod._pth_count += 1 +""") + dirs = set() + dirs = site.addsitedir(self.sitedir, dirs) + dirs = site.addsitedir(self.sitedir, dirs) + import mod + self.assertEqual(mod._pth_count, 1) + + def test_addsitdir_idempotent_start(self): + # Adding the same sitedir twice with a known_paths, should not + # process .pth files twice. + extdir = self._make_mod("""\ +_pth_count = 0 +def increment(): + global _pth_count + _pth_count += 1 +""") + self._make_pth(f"""\ +{extdir} +""") + self._make_start("""\ +mod:increment +""") + dirs = set() + dirs = site.addsitedir(self.sitedir, dirs) + dirs = site.addsitedir(self.sitedir, dirs) + import mod + self.assertEqual(mod._pth_count, 1) + + # gh-149504 + def test_reentrant_addsitedir_pth(self): + # An import line in a .pth file that calls site.addsitedir() + # must not crash or re-execute outer entries while the outer + # call is still processing its pending startup state. + overlay = self.enterContext(os_helper.temp_dir()) + overlay_pth = os.path.join(overlay, 'overlay.pth') + pkgdir = self.enterContext(os_helper.temp_dir()) + with open(overlay_pth, 'w', encoding='utf-8') as fp: + print(pkgdir, file=fp) + self._make_pth(f"import site; site.addsitedir({overlay!r})\n") + site.addsitedir(self.sitedir, set()) + self.assertIn(overlay, sys.path) + self.assertIn(pkgdir, sys.path) + + # gh-149504 + def test_reentrant_addsitedir_start(self): + # As above, but the re-entry happens from a .start entry point + # instead of a .pth import line. The entry point execution + # phase is vulnerable to the same class of bug. + overlay = self.enterContext(os_helper.temp_dir()) + overlay_pth = os.path.join(overlay, 'overlay.pth') + pkgdir = self.enterContext(os_helper.temp_dir()) + with open(overlay_pth, 'w', encoding='utf-8') as fp: + print(pkgdir, file=fp) + self._make_mod(f"""\ +import site +def bootstrap(): + site.addsitedir({overlay!r}) +""", + name='reenter_helper', on_path=True) + self._make_start("reenter_helper:bootstrap\n") + site.addsitedir(self.sitedir, set()) + self.assertIn(overlay, sys.path) + self.assertIn(pkgdir, sys.path) + + # gh-149819 + @unittest.skipUnless(site.ENABLE_USER_SITE, "requires user-site") + @support.requires_subprocess() + def test_pth_processed_when_sitedir_already_on_path(self): + # A .pth file in a site-packages directory must still be processed by + # site.main() when that directory is already on sys.path at + # interpreter start up, for example in a subprocess that inherits + # PYTHONPATH from its parent. Before the fix, main() seeded + # known_paths with all entries derived from removeduppaths(), and + # addsitedir() then skipped .pth processing for any directory already + # in known_paths. + user_base = self.tmpdir + user_site = site._get_path(user_base) + os.makedirs(user_site) + sentinel = "GH149819_PTH_RAN" + # Writing some text to stderr is the simplest observable side effect. + self._make_pth(f"""\ +import sys; sys.stderr.write({sentinel!r}); sys.stderr.flush() +""", + name='gh149819', + basedir=user_site) + with EnvironmentVarGuard() as env: + # PYTHONUSERBASE points USER_SITE at our temp directory so + # site.main() will call addsitedir() on it, rather than on the + # host interpreter's real user-site. + env['PYTHONUSERBASE'] = user_base + # PYTHONPATH puts that same directory on sys.path before + # site.main() runs in the subprocess. This is what triggers the + # bug: removeduppaths() records it in known_paths, and the unfixed + # addsitedir() then skips .pth processing. + env['PYTHONPATH'] = user_site + result = subprocess.run( + [sys.executable, '-c', ''], + capture_output=True, + check=True, + ) + self.assertIn(sentinel.encode(), result.stderr) + + @unittest.skipUnless(site.ENABLE_USER_SITE, "requires user-site") + @support.requires_subprocess() + def test_start_processed_when_sitedir_already_on_path(self): + # Companion to test_pth_processed_when_sitedir_already_on_path: + # the same dedup-guard skip in addsitedir() suppressed both .pth + # and .start file processing, so verify .start entry points also + # run for a site-packages directory inherited via PYTHONPATH. + user_base = self.tmpdir + user_site = site._get_path(user_base) + os.makedirs(user_site) + sentinel = "GH149819_START_RAN" + # The .start entry point resolves to a callable, so we write a + # tiny importable module that outputs the sentinel text. It lands in + # /extdir. That path is added to PYTHONPATH below so + # the subprocess can import it. + extdir = self._make_mod(f"""\ +import sys +def run(): + sys.stderr.write({sentinel!r}) + sys.stderr.flush() +""", name='gh149819mod') + self._make_start( + 'gh149819mod:run\n', name='gh149819', basedir=user_site + ) + with EnvironmentVarGuard() as env: + # See above for details. + env['PYTHONUSERBASE'] = user_base + env['PYTHONPATH'] = os.pathsep.join([user_site, extdir]) + result = subprocess.run( + [sys.executable, '-c', ''], + capture_output=True, + check=True, + ) + self.assertIn(sentinel.encode(), result.stderr) + + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_smtplib.py b/Lib/test/test_smtplib.py index fb3ea34d766..b8aac8c2020 100644 --- a/Lib/test/test_smtplib.py +++ b/Lib/test/test_smtplib.py @@ -1185,9 +1185,9 @@ def testAUTH_CRAM_MD5(self): self.assertEqual(resp, (235, b'Authentication Succeeded')) smtp.close() - @mock.patch("hmac.HMAC") + @hashlib_helper.block_algorithm('md5') @mock.patch("smtplib._have_cram_md5_support", False) - def testAUTH_CRAM_MD5_blocked(self, hmac_constructor): + def testAUTH_CRAM_MD5_blocked(self): # CRAM-MD5 is the only "known" method by the server, # but it is not supported by the client. In particular, # no challenge will ever be sent. @@ -1198,8 +1198,8 @@ def testAUTH_CRAM_MD5_blocked(self, hmac_constructor): msg = re.escape("No suitable authentication method found.") with self.assertRaisesRegex(smtplib.SMTPException, msg): smtp.login(sim_auth[0], sim_auth[1]) - hmac_constructor.assert_not_called() # call has been bypassed + @hashlib_helper.block_algorithm('md5') @mock.patch("smtplib._have_cram_md5_support", False) def testAUTH_CRAM_MD5_blocked_and_fallback(self): # Test that PLAIN is tried after CRAM-MD5 failed @@ -1215,7 +1215,7 @@ def testAUTH_CRAM_MD5_blocked_and_fallback(self): ): resp = smtp.login(sim_auth[0], sim_auth[1]) smtp_auth_plain.assert_called_once() - smtp_auth_cram_md5.assert_not_called() # no call to HMAC constructor + smtp_auth_cram_md5.assert_not_called() self.assertEqual(resp, (235, b'Authentication Succeeded')) @hashlib_helper.requires_hashdigest('md5', openssl=True) diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py index 0e20723b6f3..100b71074bf 100644 --- a/Lib/test/test_socket.py +++ b/Lib/test/test_socket.py @@ -8,7 +8,9 @@ import _thread as thread import array import contextlib +import decimal import errno +import fractions import gc import io import itertools @@ -1349,10 +1351,20 @@ def testDefaultTimeout(self): self.assertEqual(s.gettimeout(), None) # Set the default timeout to 10, and see if it propagates - with socket_setdefaulttimeout(10): - self.assertEqual(socket.getdefaulttimeout(), 10) + with socket_setdefaulttimeout(10.125): + self.assertEqual(socket.getdefaulttimeout(), 10.125) with socket.socket() as sock: - self.assertEqual(sock.gettimeout(), 10) + self.assertEqual(sock.gettimeout(), 10.125) + + socket.setdefaulttimeout(decimal.Decimal('11.125')) + self.assertEqual(socket.getdefaulttimeout(), 11.125) + with socket.socket() as sock: + self.assertEqual(sock.gettimeout(), 11.125) + + socket.setdefaulttimeout(fractions.Fraction(97, 8)) + self.assertEqual(socket.getdefaulttimeout(), 12.125) + with socket.socket() as sock: + self.assertEqual(sock.gettimeout(), 12.125) # Reset the default timeout to None, and see if it propagates socket.setdefaulttimeout(None) @@ -1580,6 +1592,40 @@ def testSetSockOpt(self): reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) self.assertFalse(reuse == 0, "failed to set reuse mode") + def test_setsockopt_errors(self): + # See issue #107546. + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.addCleanup(sock.close) + + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # No error expected. + + with self.assertRaises(OverflowError): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 2 ** 100) + + with self.assertRaises(OverflowError): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, - 2 ** 100) + + with self.assertRaises(OverflowError): + sock.setsockopt(socket.SOL_SOCKET, 2 ** 100, 1) + + with self.assertRaises(OverflowError): + sock.setsockopt(2 ** 100, socket.SO_REUSEADDR, 1) + + with self.assertRaisesRegex(TypeError, "socket option should be int, bytes-like object or None"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, dict()) + + with self.assertRaisesRegex(TypeError, "requires 4 arguments when the third argument is None"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, None) + + with self.assertRaisesRegex(TypeError, "only takes 4 arguments when the third argument is None"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, 2) + + with self.assertRaisesRegex(TypeError, "takes at least 3 arguments"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR) + + with self.assertRaisesRegex(TypeError, "takes at most 4 arguments"): + sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1, 2, 3) + def testSendAfterClose(self): # testing send() after close() with timeout with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: @@ -2435,6 +2481,45 @@ def testCrucialConstants(self): socket.CAN_ISOTP socket.SOCK_DGRAM + @unittest.skipUnless(hasattr(socket, "SOL_CAN_ISOTP"), + "missing ") + def testISOTP(self): + socket.SOL_CAN_ISOTP + + socket.CAN_ISOTP_OPTS + socket.CAN_ISOTP_RECV_FC + + socket.CAN_ISOTP_TX_STMIN + socket.CAN_ISOTP_RX_STMIN + socket.CAN_ISOTP_LL_OPTS + + socket.CAN_ISOTP_LISTEN_MODE + socket.CAN_ISOTP_EXTEND_ADDR + socket.CAN_ISOTP_TX_PADDING + socket.CAN_ISOTP_RX_PADDING + socket.CAN_ISOTP_CHK_PAD_LEN + socket.CAN_ISOTP_CHK_PAD_DATA + socket.CAN_ISOTP_HALF_DUPLEX + socket.CAN_ISOTP_FORCE_TXSTMIN + socket.CAN_ISOTP_FORCE_RXSTMIN + socket.CAN_ISOTP_RX_EXT_ADDR + socket.CAN_ISOTP_WAIT_TX_DONE + # This constant is not always available + # socket.CAN_ISOTP_SF_BROADCAST + + socket.CAN_ISOTP_DEFAULT_FLAGS + socket.CAN_ISOTP_DEFAULT_EXT_ADDRESS + socket.CAN_ISOTP_DEFAULT_PAD_CONTENT + socket.CAN_ISOTP_DEFAULT_FRAME_TXTIME + socket.CAN_ISOTP_DEFAULT_RECV_BS + socket.CAN_ISOTP_DEFAULT_EXT_ADDRESS + socket.CAN_ISOTP_DEFAULT_RECV_STMIN + socket.CAN_ISOTP_DEFAULT_RECV_WFTMAX + + socket.CAN_ISOTP_DEFAULT_LL_MTU + socket.CAN_ISOTP_DEFAULT_LL_TX_DL + socket.CAN_ISOTP_DEFAULT_LL_TX_FLAGS + def testCreateSocket(self): with socket.socket(socket.PF_CAN, socket.SOCK_RAW, socket.CAN_RAW) as s: pass @@ -7075,7 +7160,6 @@ def create_alg(self, typ, name): # bpo-31705: On kernel older than 4.5, sendto() failed with ENOKEY, # at least on ppc64le architecture - @unittest.expectedFailure # TODO: RUSTPYTHON; - AF_ALG not fully implemented @support.requires_linux_version(4, 5) def test_sha256(self): expected = bytes.fromhex("ba7816bf8f01cfea414140de5dae2223b00361a396" @@ -7094,7 +7178,6 @@ def test_sha256(self): op.send(b'') self.assertEqual(op.recv(512), expected) - @unittest.expectedFailure # TODO: RUSTPYTHON; - AF_ALG not fully implemented def test_hmac_sha1(self): # gh-109396: In FIPS mode, Linux 6.5 requires a key # of at least 112 bits. Use a key of 152 bits. @@ -7110,7 +7193,6 @@ def test_hmac_sha1(self): # Although it should work with 3.19 and newer the test blocks on # Ubuntu 15.10 with Kernel 4.2.0-19. - @unittest.expectedFailure # TODO: RUSTPYTHON; - AF_ALG not fully implemented @support.requires_linux_version(4, 3) def test_aes_cbc(self): key = bytes.fromhex('06a9214036b8a15b512e03d534120006') @@ -7152,7 +7234,6 @@ def test_aes_cbc(self): self.assertEqual(len(dec), msglen * multiplier) self.assertEqual(dec, msg * multiplier) - @unittest.expectedFailure # TODO: RUSTPYTHON; - AF_ALG not fully implemented @support.requires_linux_version(4, 9) # see gh-73510 def test_aead_aes_gcm(self): kernel_version = support._get_kernel_version("Linux") @@ -7222,7 +7303,6 @@ def test_aead_aes_gcm(self): res = op.recv(len(msg) - taglen) self.assertEqual(plain, res[assoclen:]) - @unittest.expectedFailure # TODO: RUSTPYTHON; - AF_ALG not fully implemented @support.requires_linux_version(4, 3) # see test_aes_cbc def test_drbg_pr_sha256(self): # deterministic random bit generator, prediction resistance, sha256 diff --git a/Lib/test/test_socketserver.py b/Lib/test/test_socketserver.py index 2ca356606b2..ca33a9a6dac 100644 --- a/Lib/test/test_socketserver.py +++ b/Lib/test/test_socketserver.py @@ -17,6 +17,7 @@ from test.support import os_helper from test.support import socket_helper from test.support import threading_helper +from test.support import warnings_helper test.support.requires("network") @@ -43,6 +44,7 @@ def receive(sock, n, timeout=test.support.SHORT_TIMEOUT): raise RuntimeError("timed out on %r" % (sock,)) +@warnings_helper.ignore_fork_in_thread_deprecation_warnings() @test.support.requires_fork() @contextlib.contextmanager def simple_subprocess(testcase): @@ -173,6 +175,7 @@ def test_ThreadingTCPServer(self): socketserver.StreamRequestHandler, self.stream_examine) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_forking def test_ForkingTCPServer(self): with simple_subprocess(self): @@ -192,6 +195,7 @@ def test_ThreadingUnixStreamServer(self): socketserver.StreamRequestHandler, self.stream_examine) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_unix_sockets @requires_forking def test_ForkingUnixStreamServer(self): @@ -210,6 +214,7 @@ def test_ThreadingUDPServer(self): socketserver.DatagramRequestHandler, self.dgram_examine) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_forking def test_ForkingUDPServer(self): with simple_subprocess(self): @@ -233,6 +238,7 @@ def test_ThreadingUnixDatagramServer(self): socketserver.DatagramRequestHandler, self.dgram_examine) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_unix_sockets @requires_forking def test_ForkingUnixDatagramServer(self): @@ -318,11 +324,13 @@ def test_threading_not_handled(self): self.assertIs(cm.exc_type, SystemExit) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_forking def test_forking_handled(self): ForkingErrorTestServer(ValueError) self.check_result(handled=True) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @requires_forking def test_forking_not_handled(self): ForkingErrorTestServer(SystemExit) @@ -507,5 +515,15 @@ class MyServer(socketserver.ThreadingMixIn, socketserver.TCPServer): server.server_close() +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(socketserver, "__version__") + self.assertEqual(cm.filename, __file__) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_sort.py b/Lib/test/test_sort.py index 3a6f4f1c05b..2a7cfb7affa 100644 --- a/Lib/test/test_sort.py +++ b/Lib/test/test_sort.py @@ -326,7 +326,6 @@ def test_safe_object_compare(self): for L in float_int_lists: check_against_PyObject_RichCompareBool(self, L) - @unittest.skip("TODO: RUSTPYTHON; not really a todo, it seems like an implementation detail") def test_unsafe_object_compare(self): # This test is by ppperry. It ensures that unsafe_object_compare is diff --git a/Lib/test/test_source_encoding.py b/Lib/test/test_source_encoding.py new file mode 100644 index 00000000000..53fffe7cfb5 --- /dev/null +++ b/Lib/test/test_source_encoding.py @@ -0,0 +1,559 @@ +# -*- coding: utf-8 -*- + +import unittest +from test import support +from test.support import script_helper +from test.support.os_helper import TESTFN, unlink, rmtree +from test.support.import_helper import unload +import importlib +import os +import sys +import subprocess +import tempfile + +class MiscSourceEncodingTest(unittest.TestCase): + + def test_import_encoded_module(self): + from test.encoded_modules import test_strings + # Make sure we're actually testing something + self.assertGreaterEqual(len(test_strings), 1) + for modname, encoding, teststr in test_strings: + mod = importlib.import_module('test.encoded_modules.' + 'module_' + modname) + self.assertEqual(teststr, mod.test) + + def test_compilestring(self): + # see #1882 + c = compile(b"\n# coding: utf-8\nu = '\xc3\xb3'\n", "dummy", "exec") + d = {} + exec(c, d) + self.assertEqual(d['u'], '\xf3') + + def test_issue2301(self): + try: + compile(b"# coding: cp932\nprint '\x94\x4e'", "dummy", "exec") + except SyntaxError as v: + self.assertEqual(v.text.rstrip('\n'), "print '\u5e74'") + else: + self.fail() + + def test_issue4626(self): + c = compile("# coding=latin-1\n\u00c6 = '\u00c6'", "dummy", "exec") + d = {} + exec(c, d) + self.assertEqual(d['\xc6'], '\xc6') + + def test_issue3297(self): + c = compile("a, b = '\U0001010F', '\\U0001010F'", "dummy", "exec") + d = {} + exec(c, d) + self.assertEqual(d['a'], d['b']) + self.assertEqual(len(d['a']), len(d['b'])) + self.assertEqual(ascii(d['a']), ascii(d['b'])) + + def test_issue7820(self): + # Ensure that check_bom() restores all bytes in the right order if + # check_bom() fails in pydebug mode: a buffer starts with the first + # byte of a valid BOM, but next bytes are different + + # one byte in common with the UTF-16-LE BOM + self.assertRaises(SyntaxError, eval, b'\xff\x20') + + # one byte in common with the UTF-8 BOM + self.assertRaises(SyntaxError, eval, b'\xef\x20') + + # two bytes in common with the UTF-8 BOM + self.assertRaises(SyntaxError, eval, b'\xef\xbb\x20') + + def test_truncated_utf8_at_eof(self): + # Regression test for https://issues.oss-fuzz.com/issues/451112368 + # Truncated multi-byte UTF-8 sequences at end of input caused an + # out-of-bounds read in Parser/tokenizer/helpers.c:valid_utf8(). + truncated = [ + b'\xc2', # 2-byte lead, missing 1 continuation + b'\xdf', # 2-byte lead, missing 1 continuation + b'\xe0', # 3-byte lead, missing 2 continuations + b'\xe0\xa0', # 3-byte lead, missing 1 continuation + b'\xf0\x90', # 4-byte lead, missing 2 continuations + b'\xf0\x90\x80', # 4-byte lead, missing 1 continuation + b'\xf3', # 4-byte lead, missing 3 (the oss-fuzz reproducer) + ] + for seq in truncated: + with self.subTest(seq=seq): + self.assertRaises(SyntaxError, compile, seq, '', 'exec') + + @support.requires_subprocess() + def test_20731(self): + sub = subprocess.Popen([sys.executable, + os.path.join(os.path.dirname(__file__), + 'tokenizedata', + 'coding20731.py')], + stderr=subprocess.PIPE) + err = sub.communicate()[1] + self.assertEqual(sub.returncode, 0) + self.assertNotIn(b'SyntaxError', err) + + def test_error_message(self): + compile(b'# -*- coding: iso-8859-15 -*-\n', 'dummy', 'exec') + compile(b'\xef\xbb\xbf\n', 'dummy', 'exec') + compile(b'\xef\xbb\xbf# -*- coding: utf-8 -*-\n', 'dummy', 'exec') + with self.assertRaisesRegex(SyntaxError, 'fake'): + compile(b'# -*- coding: fake -*-\n', 'dummy', 'exec') + with self.assertRaisesRegex(SyntaxError, 'iso-8859-15'): + compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n', + 'dummy', 'exec') + with self.assertRaisesRegex(SyntaxError, 'BOM'): + compile(b'\xef\xbb\xbf# -*- coding: iso-8859-15 -*-\n', + 'dummy', 'exec') + with self.assertRaisesRegex(SyntaxError, 'fake'): + compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec') + with self.assertRaisesRegex(SyntaxError, 'BOM'): + compile(b'\xef\xbb\xbf# -*- coding: fake -*-\n', 'dummy', 'exec') + + def test_bad_coding(self): + module_name = 'bad_coding' + self.verify_bad_module(module_name) + + def test_bad_coding2(self): + module_name = 'bad_coding2' + self.verify_bad_module(module_name) + + def verify_bad_module(self, module_name): + self.assertRaises(SyntaxError, __import__, 'test.tokenizedata.' + module_name) + + path = os.path.dirname(__file__) + filename = os.path.join(path, 'tokenizedata', module_name + '.py') + with open(filename, "rb") as fp: + bytes = fp.read() + self.assertRaises(SyntaxError, compile, bytes, filename, 'exec') + + def test_exec_valid_coding(self): + d = {} + exec(b'# coding: cp949\na = "\xaa\xa7"\n', d) + self.assertEqual(d['a'], '\u3047') + + def test_file_parse(self): + # issue1134: all encodings outside latin-1 and utf-8 fail on + # multiline strings and long lines (>512 columns) + unload(TESTFN) + filename = TESTFN + ".py" + f = open(filename, "w", encoding="cp1252") + sys.path.insert(0, os.curdir) + try: + with f: + f.write("# -*- coding: cp1252 -*-\n") + f.write("'''A short string\n") + f.write("'''\n") + f.write("'A very long string %s'\n" % ("X" * 1000)) + + importlib.invalidate_caches() + __import__(TESTFN) + finally: + del sys.path[0] + unlink(filename) + unlink(filename + "c") + unlink(filename + "o") + unload(TESTFN) + rmtree('__pycache__') + + def test_error_from_string(self): + # See http://bugs.python.org/issue6289 + input = "# coding: ascii\n\N{SNOWMAN}".encode('utf-8') + with self.assertRaises(SyntaxError) as c: + compile(input, "", "exec") + expected = "'ascii' codec can't decode byte 0xe2 in position 16: " \ + "ordinal not in range(128)" + self.assertStartsWith(c.exception.args[0], expected) + + def test_file_parse_error_multiline(self): + # gh96611: + with open(TESTFN, "wb") as fd: + fd.write(b'print("""\n\xb1""")\n') + + try: + retcode, stdout, stderr = script_helper.assert_python_failure(TESTFN) + + self.assertGreater(retcode, 0) + self.assertIn(b"Non-UTF-8 code starting with '\\xb1'", stderr) + finally: + os.unlink(TESTFN) + + def test_tokenizer_fstring_warning_in_first_line(self): + source = "0b1and 2" + with open(TESTFN, "w") as fd: + fd.write("{}".format(source)) + try: + retcode, stdout, stderr = script_helper.assert_python_ok(TESTFN) + self.assertIn(b"SyntaxWarning: invalid binary litera", stderr) + self.assertEqual(stderr.count(source.encode()), 1) + finally: + os.unlink(TESTFN) + + +BUFSIZ = 2**13 + +class AbstractSourceEncodingTest: + + def test_default_coding(self): + src = (b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xe4'") + + def test_first_coding_line(self): + src = (b'#coding:iso8859-15\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_second_coding_line(self): + src = (b'#!/usr/bin/python\n' + b'#coding:iso8859-15\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_second_coding_line_empty_first_line(self): + src = (b'\n' + b'#coding:iso8859-15\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_third_coding_line(self): + # Only first two lines are tested for a magic comment. + src = (b'#!/usr/bin/python\n' + b'#\n' + b'#coding:iso8859-15\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xe4'") + + def test_double_coding_line(self): + # If the first line matches the second line is ignored. + src = (b'#coding:iso8859-15\n' + b'#coding:latin1\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_double_coding_same_line(self): + src = (b'#coding:iso8859-15 coding:latin1\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_double_coding_utf8(self): + src = (b'#coding:utf-8\n' + b'#coding:latin1\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xe4'") + + def test_long_first_coding_line(self): + src = (b'#' + b' '*BUFSIZ + b'coding:iso8859-15\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_long_second_coding_line(self): + src = (b'#!/usr/bin/python\n' + b'#' + b' '*BUFSIZ + b'coding:iso8859-15\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_long_coding_line(self): + src = (b'#coding:iso-8859-15' + b' '*BUFSIZ + b'\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_long_coding_name(self): + src = (b'#coding:iso-8859-1-' + b'x'*BUFSIZ + b'\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\xa4'") + + def test_long_first_utf8_line(self): + src = b'#' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n' + self.check_script_output(src, b'') + src = b'# ' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n' + self.check_script_output(src, b'') + + def test_long_second_utf8_line(self): + src = b'\n#' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n' + self.check_script_output(src, b'') + src = b'\n# ' + b'\xc3\xa4'*(BUFSIZ//2) + b'\n' + self.check_script_output(src, b'') + + def test_first_non_utf8_coding_line(self): + src = (b'#coding:iso-8859-15 \xa4\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_second_non_utf8_coding_line(self): + src = (b'#!/usr/bin/python\n' + b'#coding:iso-8859-15 \xa4\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_first_utf8_coding_line_error(self): + src = (b'#coding:ascii \xc3\xa4\n' + b'raise RuntimeError\n') + self.check_script_error(src, br"(\(unicode error\) )?'ascii' codec can't decode byte") + + def test_second_utf8_coding_line_error(self): + src = (b'#!/usr/bin/python\n' + b'#coding:ascii \xc3\xa4\n' + b'raise RuntimeError\n') + self.check_script_error(src, br"(\(unicode error\) )?'ascii' codec can't decode byte") + + def test_utf8_bom(self): + src = (b'\xef\xbb\xbfprint(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xe4'") + + def test_utf8_bom_utf8_comments(self): + src = (b'\xef\xbb\xbf#\xc3\xa4\n' + b'#\xc3\xa4\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xe4'") + + def test_utf8_bom_and_utf8_coding_line(self): + src = (b'\xef\xbb\xbf#coding:utf-8\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xe4'") + + def test_utf8_bom_and_non_utf8_first_coding_line(self): + src = (b'\xef\xbb\xbf#coding:iso-8859-15\n' + b'raise RuntimeError\n') + self.check_script_error(src, + br"encoding problem: iso-8859-15 with BOM", + lineno=1) + + def test_utf8_bom_and_non_utf8_second_coding_line(self): + src = (b'\xef\xbb\xbf#first\n' + b'#coding:iso-8859-15\n' + b'raise RuntimeError\n') + self.check_script_error(src, + br"encoding problem: iso-8859-15 with BOM", + lineno=2) + + def test_non_utf8_shebang(self): + src = (b'#!/home/\xa4/bin/python\n' + b'#coding:iso-8859-15\n' + b'print(ascii("\xc3\xa4"))\n') + self.check_script_output(src, br"'\xc3\u20ac'") + + def test_utf8_shebang_error(self): + src = (b'#!/home/\xc3\xa4/bin/python\n' + b'#coding:ascii\n' + b'raise RuntimeError\n') + self.check_script_error(src, br"(\(unicode error\) )?'ascii' codec can't decode byte") + + def test_non_utf8_shebang_error(self): + src = (b'#!/home/\xa4/bin/python\n' + b'raise RuntimeError\n') + self.check_script_error(src, br"Non-UTF-8 code starting with .* on line 1", + lineno=1) + + def test_non_utf8_second_line_error(self): + src = (b'#first\n' + b'#second\xa4\n' + b'raise RuntimeError\n') + self.check_script_error(src, + br"Non-UTF-8 code starting with .* on line 2", + lineno=2) + + def test_non_utf8_third_line_error(self): + src = (b'#first\n' + b'#second\n' + b'#third\xa4\n' + b'raise RuntimeError\n') + self.check_script_error(src, + br"Non-UTF-8 code starting with .* on line 3", + lineno=3) + + def test_utf8_bom_non_utf8_third_line_error(self): + src = (b'\xef\xbb\xbf#first\n' + b'#second\n' + b'#third\xa4\n' + b'raise RuntimeError\n') + self.check_script_error(src, + br"Non-UTF-8 code starting with .* on line 3|" + br"'utf-8' codec can't decode byte", + lineno=3) + + def test_utf_8_non_utf8_third_line_error(self): + src = (b'#coding: utf-8\n' + b'#second\n' + b'#third\xa4\n' + b'raise RuntimeError\n') + self.check_script_error(src, + br"Non-UTF-8 code starting with .* on line 3|" + br"'utf-8' codec can't decode byte", + lineno=3) + + def test_utf8_non_utf8_third_line_error(self): + src = (b'#coding: utf8\n' + b'#second\n' + b'#third\xa4\n' + b'raise RuntimeError\n') + self.check_script_error(src, + br"'utf-8' codec can't decode byte") + + def test_crlf(self): + src = (b'print(ascii("""\r\n"""))\n') + self.check_script_output(src, br"'\n'") + + def test_crcrlf(self): + src = (b'print(ascii("""\r\r\n"""))\n') + self.check_script_output(src, br"'\n\n'") + + def test_crcrcrlf(self): + src = (b'print(ascii("""\r\r\r\n"""))\n') + self.check_script_output(src, br"'\n\n\n'") + + def test_crcrcrlf2(self): + src = (b'#coding:iso-8859-1\n' + b'print(ascii("""\r\r\r\n"""))\n') + self.check_script_output(src, br"'\n\n\n'") + + def test_nul_in_first_coding_line(self): + src = (b'#coding:iso8859-15\x00\n' + b'\n' + b'\n' + b'raise RuntimeError\n') + self.check_script_error(src, br"source code (string )?cannot contain null bytes") + + def test_nul_in_second_coding_line(self): + src = (b'#!/usr/bin/python\n' + b'#coding:iso8859-15\x00\n' + b'\n' + b'raise RuntimeError\n') + self.check_script_error(src, br"source code (string )?cannot contain null bytes") + + +class UTF8ValidatorTest(unittest.TestCase): + @unittest.skipIf(not sys.platform.startswith("linux"), + "Too slow to run on non-Linux platforms") + @support.requires_resource('cpu') + def test_invalid_utf8(self): + # This is a port of test_utf8_decode_invalid_sequences in + # test_unicode.py to exercise the separate utf8 validator in + # Parser/tokenizer/helpers.c used when reading source files. + + # That file is written using low-level C file I/O, so the only way to + # test it is to write actual files to disk. + + # Each example is put inside a string at the top of the file so + # it's an otherwise valid Python source file. Put some newlines + # beforehand so we can assert that the error is reported on the + # correct line. + template = b'\n\n\n"%s"\n' + + fn = TESTFN + self.addCleanup(unlink, fn) + + def check(content): + with open(fn, 'wb') as fp: + fp.write(template % content) + rc, stdout, stderr = script_helper.assert_python_failure(fn) + # We want to assert that the python subprocess failed gracefully, + # not via a signal. + self.assertGreaterEqual(rc, 1) + self.assertIn(b"Non-UTF-8 code starting with", stderr) + self.assertIn(b"on line 4", stderr) + + # continuation bytes in a sequence of 2, 3, or 4 bytes + continuation_bytes = [bytes([x]) for x in range(0x80, 0xC0)] + # start bytes of a 2-byte sequence equivalent to code points < 0x7F + invalid_2B_seq_start_bytes = [bytes([x]) for x in range(0xC0, 0xC2)] + # start bytes of a 4-byte sequence equivalent to code points > 0x10FFFF + invalid_4B_seq_start_bytes = [bytes([x]) for x in range(0xF5, 0xF8)] + invalid_start_bytes = ( + continuation_bytes + invalid_2B_seq_start_bytes + + invalid_4B_seq_start_bytes + [bytes([x]) for x in range(0xF7, 0x100)] + ) + + for byte in invalid_start_bytes: + check(byte) + + for sb in invalid_2B_seq_start_bytes: + for cb in continuation_bytes: + check(sb + cb) + + for sb in invalid_4B_seq_start_bytes: + for cb1 in continuation_bytes[:3]: + for cb3 in continuation_bytes[:3]: + check(sb+cb1+b'\x80'+cb3) + + for cb in [bytes([x]) for x in range(0x80, 0xA0)]: + check(b'\xE0'+cb+b'\x80') + check(b'\xE0'+cb+b'\xBF') + # surrogates + for cb in [bytes([x]) for x in range(0xA0, 0xC0)]: + check(b'\xED'+cb+b'\x80') + check(b'\xED'+cb+b'\xBF') + for cb in [bytes([x]) for x in range(0x80, 0x90)]: + check(b'\xF0'+cb+b'\x80\x80') + check(b'\xF0'+cb+b'\xBF\xBF') + for cb in [bytes([x]) for x in range(0x90, 0xC0)]: + check(b'\xF4'+cb+b'\x80\x80') + check(b'\xF4'+cb+b'\xBF\xBF') + + +@support.force_not_colorized_test_class +class BytesSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase): + + def check_script_output(self, src, expected): + with support.captured_stdout() as stdout: + exec(src) + out = stdout.getvalue().encode('latin1') + self.assertEqual(out.rstrip(), expected) + + def check_script_error(self, src, expected, lineno=...): + with self.assertRaises(SyntaxError) as cm: + exec(src) + exc = cm.exception + self.assertRegex(str(exc), expected.decode()) + if lineno is not ...: + self.assertEqual(exc.lineno, lineno) + line = src.splitlines()[lineno-1].decode(errors='replace') + if lineno == 1: + line = line.removeprefix('\ufeff') + self.assertEqual(line, exc.text) + + +@support.force_not_colorized_test_class +class FileSourceEncodingTest(AbstractSourceEncodingTest, unittest.TestCase): + + def check_script_output(self, src, expected): + with tempfile.TemporaryDirectory() as tmpd: + fn = os.path.join(tmpd, 'test.py') + with open(fn, 'wb') as fp: + fp.write(src) + res = script_helper.assert_python_ok(fn) + self.assertEqual(res.out.rstrip(), expected) + + def check_script_error(self, src, expected, lineno=...): + with tempfile.TemporaryDirectory() as tmpd: + fn = os.path.join(tmpd, 'test.py') + with open(fn, 'wb') as fp: + fp.write(src) + res = script_helper.assert_python_failure(fn) + err = res.err.rstrip() + self.assertRegex(err.splitlines()[-1], b'SyntaxError: ' + expected) + if lineno is not ...: + self.assertIn(f', line {lineno}\n'.encode(), + err.replace(os.linesep.encode(), b'\n')) + line = src.splitlines()[lineno-1].decode(errors='replace') + if lineno == 1: + line = line.removeprefix('\ufeff') + self.assertIn(line.encode(), err) + + def test_coding_spec_unknown_encoding(self): + src = (b'# coding: c1252\n' + b'print("Hi!")\n') + self.check_script_error(src, br"unknown encoding: c1252") + + def test_coding_spec_decode_error(self): + src = (b'# coding: shift-jis\n' + b'print("\xc4\x85")\n') + self.check_script_error(src, br"'shift_jis' codec can't decode byte") + + def test_coding_spec_non_text_encoding(self): + src = (b'# coding: hex_codec\n' + b'print("eggs")\n') + self.check_script_error(src, br"'hex_codec' is not a text encoding") + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_sqlite3/test_backup.py b/Lib/test/test_sqlite3/test_backup.py index bc24831a0c7..c7400d8b216 100644 --- a/Lib/test/test_sqlite3/test_backup.py +++ b/Lib/test/test_sqlite3/test_backup.py @@ -103,7 +103,6 @@ def progress(status, remaining, total): self.assertEqual(len(journal), 1) self.assertEqual(journal[0], 0) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_non_callable_progress(self): with self.assertRaises(TypeError) as cm: with memory_database() as bck: diff --git a/Lib/test/test_sqlite3/test_cli.py b/Lib/test/test_sqlite3/test_cli.py index a03d7cbe16b..0d235d90f11 100644 --- a/Lib/test/test_sqlite3/test_cli.py +++ b/Lib/test/test_sqlite3/test_cli.py @@ -1,17 +1,26 @@ """sqlite3 CLI tests.""" import sqlite3 +import sys +import textwrap import unittest +import unittest.mock +import os from sqlite3.__main__ import main as cli +from test.support.import_helper import import_module from test.support.os_helper import TESTFN, unlink +from test.support.pty_helper import run_pty from test.support import ( captured_stdout, captured_stderr, captured_stdin, - force_not_colorized, + force_not_colorized_test_class, + requires_subprocess, + verbose, ) +@force_not_colorized_test_class class CommandLineInterface(unittest.TestCase): def _do_test(self, *args, expect_success=True): @@ -37,7 +46,6 @@ def expect_failure(self, *args): self.assertEqual(out, "") return err - @force_not_colorized def test_cli_help(self): out = self.expect_success("-h") self.assertIn("usage: ", out) @@ -69,10 +77,11 @@ def test_cli_on_disk_db(self): self.assertIn("(0,)", out) +@force_not_colorized_test_class class InteractiveSession(unittest.TestCase): MEMORY_DB_MSG = "Connected to a transient in-memory database" - PS1 = "sqlite> " - PS2 = "... " + PS1 = "\001\002sqlite> \001\002" + PS2 = "\001\002 ... \001\002" def run_cli(self, *args, commands=()): with ( @@ -129,7 +138,7 @@ def test_interact_dot_commands_unknown(self): self.assertEndsWith(out, self.PS1) self.assertEqual(out.count(self.PS1), 2) self.assertEqual(out.count(self.PS2), 0) - self.assertIn("Error", err) + self.assertIn('Error: unknown command: "', err) # test "unknown_command" is pointed out in the error message self.assertIn("unknown_command", err) @@ -190,6 +199,247 @@ def test_interact_on_disk_file(self): out, _ = self.run_cli(TESTFN, commands=("SELECT count(t) FROM t;",)) self.assertIn("(0,)\n", out) + def test_color(self): + with unittest.mock.patch("_colorize.can_colorize", return_value=True): + out, err = self.run_cli(commands="TEXT\n") + self.assertIn("\x01\x1b[1;35m\x02sqlite> \x01\x1b[0m\x02", out) + self.assertIn("\x01\x1b[1;35m\x02 ... \x01\x1b[0m\x02\x01\x1b", out) + out, err = self.run_cli(commands=("sel;",)) + self.assertIn('\x1b[1;35mOperationalError (SQLITE_ERROR)\x1b[0m: ' + '\x1b[35mnear "sel": syntax error\x1b[0m', err) + + +@requires_subprocess() +@force_not_colorized_test_class +class Completion(unittest.TestCase): + # run_pty() creates a real terminal environment, where sqlite3 CLI + # SqliteInteractiveConsole invokes GNU Readline for input. Readline's + # _rl_strip_prompt() strips \001 and \002 from the output, so test + # assertions use the plain prompt. + PS1 = "sqlite> " + + @classmethod + def setUpClass(cls): + readline = import_module("readline") + if readline.backend == "editline": + raise unittest.SkipTest("libedit readline is not supported") + if sys.platform.startswith("openbsd"): + # OpenBSD's readline does not honor "completion-query-items 0". + raise unittest.SkipTest("OpenBSD readline hangs on completion") + + def write_input(self, input_, env=None): + script = textwrap.dedent(""" + import readline + from sqlite3.__main__ import main + + # Configure readline to ...: + # - hide control sequences surrounding each candidate + # - hide "Display all xxx possibilities? (y or n)" + # - show candidates one per line + readline.parse_and_bind("set colored-completion-prefix off") + readline.parse_and_bind("set completion-query-items 0") + readline.parse_and_bind("set page-completions off") + readline.parse_and_bind("set completion-display-width 0") + + main() + """) + return run_pty(script, input_, env) + + def test_complete_sql_keywords(self): + _sqlite3 = import_module("_sqlite3") + if not hasattr(_sqlite3, "SQLITE_KEYWORDS"): + raise unittest.SkipTest("unable to determine SQLite keywords") + + # List candidates starting with 'S', there should be multiple matches. + input_ = b"S\t\tEL\t 1;\n.quit\n" + output = self.write_input(input_) + self.assertIn(b"SELECT", output) + self.assertIn(b"SET", output) + self.assertIn(b"SAVEPOINT", output) + self.assertIn(b"(1,)", output) + + # Keywords are completed in upper case for even lower case user input. + input_ = b"sel\t\t 1;\n.quit\n" + output = self.write_input(input_) + self.assertIn(b"SELECT", output) + self.assertIn(b"(1,)", output) + + # .commands are completed without changing case + input_ = b".ver\t\n.quit\n" + output = self.write_input(input_) + self.assertIn(b".version", output) + + def test_complete_table_indexes_triggers_views(self): + input_ = textwrap.dedent("""\ + CREATE TABLE _Table (id); + CREATE INDEX _Index ON _table (id); + CREATE TRIGGER _Trigger BEFORE INSERT + ON _Table BEGIN SELECT 1; END; + CREATE VIEW _View AS SELECT 1; + + CREATE TEMP TABLE _Temp_table (id); + CREATE INDEX temp._Temp_index ON _Temp_table (id); + CREATE TEMP TRIGGER _Temp_trigger BEFORE INSERT + ON _Table BEGIN SELECT 1; END; + CREATE TEMP VIEW _Temp_view AS SELECT 1; + + ATTACH ':memory:' AS attached; + CREATE TABLE attached._Attached_table (id); + CREATE INDEX attached._Attached_index ON _Attached_table (id); + CREATE TRIGGER attached._Attached_trigger BEFORE INSERT + ON _Attached_table BEGIN SELECT 1; END; + CREATE VIEW attached._Attached_view AS SELECT 1; + + SELECT id FROM _\t\tta\t; + .quit\n""").encode() + output = self.write_input(input_) + lines = output.decode().splitlines() + indices = [i for i, line in enumerate(lines) + if line.startswith(self.PS1)] + start, end = indices[-3], indices[-2] + candidates = [l.strip() for l in lines[start+1:end]] + self.assertEqual(candidates, + [ + "_Attached_index", + "_Attached_table", + "_Attached_trigger", + "_Attached_view", + "_Index", + "_Table", + "_Temp_index", + "_Temp_table", + "_Temp_trigger", + "_Temp_view", + "_Trigger", + "_View", + ], + ) + start, end = indices[-2], indices[-1] + # direct match with '_Table' completed, no candidates displayed + candidates = [l.strip() for l in lines[start+1:end]] + self.assertEqual(len(candidates), 0) + + @unittest.skipIf(sqlite3.sqlite_version_info < (3, 16, 0), + "PRAGMA table-valued function is not available until " + "SQLite 3.16.0") + def test_complete_columns(self): + input_ = textwrap.dedent("""\ + CREATE TABLE _table (_col_table); + CREATE TEMP TABLE _temp_table (_col_temp); + ATTACH ':memory:' AS attached; + CREATE TABLE attached._attached_table (_col_attached); + + SELECT _col_\t\tta\tFROM _table; + .quit\n""").encode() + output = self.write_input(input_) + lines = output.decode().splitlines() + indices = [ + i for i, line in enumerate(lines) if line.startswith(self.PS1) + ] + start, end = indices[-3], indices[-2] + candidates = [l.strip() for l in lines[start+1:end]] + + self.assertEqual( + candidates, ["_col_attached", "_col_table", "_col_temp"] + ) + + @unittest.skipIf(sqlite3.sqlite_version_info < (3, 30, 0), + "PRAGMA function_list is not available until " + "SQLite 3.30.0") + def test_complete_functions(self): + input_ = b"SELECT AV\t1);\n.quit\n" + output = self.write_input(input_) + self.assertIn(b"AVG(1);", output) + self.assertIn(b"(1.0,)", output) + + # Functions are completed in upper case for even lower case user input. + input_ = b"SELECT av\t1);\n.quit\n" + output = self.write_input(input_) + self.assertIn(b"AVG(1);", output) + self.assertIn(b"(1.0,)", output) + + def test_complete_schemata(self): + input_ = textwrap.dedent("""\ + ATTACH ':memory:' AS MixedCase; + -- Test '_' is escaped in Like pattern filtering + ATTACH ':memory:' AS _underscore; + -- Let database_list pragma have a 'temp' schema entry + CREATE TEMP TABLE _table (id); + + SELECT * FROM \t\tmIX\t.sqlite_master; + SELECT * FROM _und\t.sqlite_master; + .quit\n""").encode() + output = self.write_input(input_) + lines = output.decode().splitlines() + indices = [ + i for i, line in enumerate(lines) if line.startswith(self.PS1) + ] + start, end = indices[-4], indices[-3] + candidates = [l.strip() for l in lines[start+1:end]] + self.assertIn("MixedCase", candidates) + self.assertIn("_underscore", candidates) + self.assertIn("main", candidates) + self.assertIn("temp", candidates) + + @unittest.skipIf(sys.platform.startswith(("freebsd", "dragonfly", "sunos")), + "Two actual tabs are inserted when there are no matching" + " completions in the pseudo-terminal opened by run_pty()" + " on this platform") + def test_complete_no_match(self): + input_ = b"xyzzy\t\t\b\b\b\b\b\b\b.quit\n" + # Set NO_COLOR to disable coloring for self.PS1. + output = self.write_input(input_, env={**os.environ, "NO_COLOR": "1"}) + lines = output.decode().splitlines() + indices = ( + i for i, line in enumerate(lines, 1) + if line.startswith(f"{self.PS1}xyzzy") + ) + line_num = next(indices, -1) + self.assertNotEqual(line_num, -1) + # Completions occupy lines, assert no extra lines when there is nothing + # to complete. + self.assertEqual(line_num, len(lines)) + + def test_complete_no_input(self): + script = textwrap.dedent(""" + import readline + from sqlite3.__main__ import main + + # Configure readline to ...: + # - hide control sequences surrounding each candidate + # - hide "Display all xxx possibilities? (y or n)" + # - hide "--More--" + # - show candidates one per line + readline.parse_and_bind("set colored-completion-prefix off") + readline.parse_and_bind("set colored-stats off") + readline.parse_and_bind("set completion-query-items 0") + readline.parse_and_bind("set page-completions off") + readline.parse_and_bind("set completion-display-width 0") + readline.parse_and_bind("set show-all-if-ambiguous off") + readline.parse_and_bind("set show-all-if-unmodified off") + + main() + """) + input_ = b"\t\t.quit\n" + output = run_pty(script, input_, env={**os.environ, "NO_COLOR": "1"}) + try: + lines = output.decode().splitlines() + indices = [ + i for i, line in enumerate(lines) + if line.startswith(self.PS1) + ] + self.assertEqual(len(indices), 2) + start, end = indices + candidates = [l.strip() for l in lines[start+1:end]] + self.assertEqual(candidates, sorted(candidates)) + except: + if verbose: + print(' PTY output: '.center(30, '-')) + print(output.decode(errors='replace')) + print(' end PTY output '.center(30, '-')) + raise + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_sqlite3/test_dbapi.py b/Lib/test/test_sqlite3/test_dbapi.py index ef8acd0f338..59a1a4770ed 100644 --- a/Lib/test/test_sqlite3/test_dbapi.py +++ b/Lib/test/test_sqlite3/test_dbapi.py @@ -487,6 +487,13 @@ def test_connection_init_good_isolation_levels(self): cx.isolation_level = level self.assertEqual(cx.isolation_level, level) + def test_connection_delete_isolation_level(self): + with memory_database() as cx: + with self.assertRaisesRegex(AttributeError, + "cannot delete attribute"): + del cx.isolation_level + self.assertEqual(cx.isolation_level, "") + def test_connection_reinit(self): with memory_database() as cx: cx.text_factory = bytes @@ -549,21 +556,11 @@ def test_connection_config(self): with self.assertRaisesRegex(sqlite.IntegrityError, "constraint"): cx.execute("insert into u values(0)") - @unittest.expectedFailure # TODO: RUSTPYTHON; deprecation warning not emitted for positional args def test_connect_positional_arguments(self): - regex = ( - r"Passing more than 1 positional argument to sqlite3.connect\(\)" - " is deprecated. Parameters 'timeout', 'detect_types', " - "'isolation_level', 'check_same_thread', 'factory', " - "'cached_statements' and 'uri' will become keyword-only " - "parameters in Python 3.15." - ) - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: - cx = sqlite.connect(":memory:", 1.0) - cx.close() - self.assertEqual(cm.filename, __file__) + with self.assertRaisesRegex(TypeError, + r'connect\(\) takes at most 1 positional arguments'): + sqlite.connect(":memory:", 1.0) - @unittest.expectedFailure # TODO: RUSTPYTHON; ResourceWarning not emitted def test_connection_resource_warning(self): with self.assertWarns(ResourceWarning): cx = sqlite.connect(":memory:") @@ -723,7 +720,6 @@ def test_open_undecodable_uri(self): self.assertTrue(os.path.exists(path)) cx.execute(self._sql) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_factory_database_arg(self): def factory(database, *args, **kwargs): nonlocal database_arg @@ -1088,9 +1084,16 @@ def test_invalid_array_size(self): UINT32_MAX = (1 << 32) - 1 setter = functools.partial(setattr, self.cu, 'arraysize') + self.cu.arraysize = 2 self.assertRaises(TypeError, setter, 1.0) self.assertRaises(ValueError, setter, -3) self.assertRaises(OverflowError, setter, UINT32_MAX + 1) + self.assertRaises(OverflowError, setter, 2**1000) + self.assertRaises(ValueError, setter, -2**1000) + self.assertRaisesRegex(AttributeError, 'cannot be deleted', + delattr, self.cu, 'arraysize') + # a failed assignment does not change the value + self.assertEqual(self.cu.arraysize, 2) def test_fetchmany(self): # no active SQL statement @@ -1409,6 +1412,31 @@ def test_blob_set_slice(self): actual = self.cx.execute("select b from test").fetchone()[0] self.assertEqual(actual, expected) + def test_blob_slice_with_negative_step(self): + # gh-150449: this used to raise SystemError + for sl in (slice(9, 0, -2), slice(None, None, -1), slice(9, None, -2)): + with self.subTest(slice=sl): + with self.assertRaises(ValueError): + self.blob[sl] + with self.assertRaises(ValueError): + self.blob[sl] = b"1" * len(self.data[sl]) + # an empty slice selects nothing and is still allowed + self.assertEqual(self.blob[3:8:-1], b"") + self.blob[3:8:-1] = b"" + self.assertEqual(self.blob[:], self.data) + + def test_blob_set_slice_with_step_keeps_bytes_intact(self): + # The buffer used for the read-patch-write cycle must not be the + # bytes object read from the blob: for a single byte it is an + # immortal singleton. + old_byte = self.data[5] + self.blob[5:6:2] = b"\xab" + self.assertEqual(bytes([old_byte])[0], old_byte) + self.assertEqual(self.blob[5:6], b"\xab") + expected = self.data[:5] + b"\xab" + self.data[6:] + actual = self.cx.execute("select b from test").fetchone()[0] + self.assertEqual(actual, expected) + def test_blob_set_empty_slice(self): self.blob[0:0] = b"" self.assertEqual(self.blob[:], self.data) @@ -1616,7 +1644,6 @@ def test_check_connection_thread(self): with self.subTest(fn=fn): self._run_test(fn) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_check_cursor_thread(self): fns = [ lambda: self.cur.execute("insert into test(name) values('a')"), diff --git a/Lib/test/test_sqlite3/test_dump.py b/Lib/test/test_sqlite3/test_dump.py index e18a207e9f6..7841b610cd2 100644 --- a/Lib/test/test_sqlite3/test_dump.py +++ b/Lib/test/test_sqlite3/test_dump.py @@ -56,6 +56,24 @@ def test_table_dump(self): [self.assertEqual(expected_sqls[i], actual_sqls[i]) for i in range(len(expected_sqls))] + def test_dump_single_quote_in_identifier(self): + # A single quote in a table or column name must not break the dump. + self.cu.execute("""CREATE TABLE "a'b" ("c'd" text);""") + self.cu.execute("""INSERT INTO "a'b" VALUES('x''y');""") + expected = [ + "BEGIN TRANSACTION;", + """CREATE TABLE "a'b" ("c'd" text);""", + """INSERT INTO "a'b" VALUES('x''y');""", + "COMMIT;", + ] + actual = list(self.cx.iterdump()) + self.assertEqual(expected, actual) + # The dump restores into a fresh database. + with memory_database() as cx2: + cx2.executescript("".join(actual)) + row = cx2.execute("""SELECT "c'd" FROM "a'b";""").fetchone() + self.assertEqual(row[0], "x'y") + def test_table_dump_filter(self): all_table_sqls = [ """CREATE TABLE "some_table_2" ("id_1" INTEGER);""", diff --git a/Lib/test/test_sqlite3/test_factory.py b/Lib/test/test_sqlite3/test_factory.py index 81170c653ae..2dd42921d31 100644 --- a/Lib/test/test_sqlite3/test_factory.py +++ b/Lib/test/test_sqlite3/test_factory.py @@ -40,7 +40,6 @@ def __init__(self, *args, **kwargs): self.row_factory = dict_factory class ConnectionFactoryTests(unittest.TestCase): - @unittest.expectedFailure # TODO: RUSTPYTHON def test_connection_factories(self): class DefectFactory(sqlite.Connection): def __init__(self, *args, **kwargs): @@ -56,7 +55,6 @@ def __init__(self, *args, **kwargs): with memory_database(factory=DefectFactory) as con: self.assertIsInstance(con, DefectFactory) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_connection_factory_relayed_call(self): # gh-95132: keyword args must not be passed as positional args class Factory(sqlite.Connection): @@ -68,24 +66,14 @@ def __init__(self, *args, **kwargs): self.assertIsNone(con.isolation_level) self.assertIsInstance(con, Factory) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_connection_factory_as_positional_arg(self): class Factory(sqlite.Connection): def __init__(self, *args, **kwargs): super(Factory, self).__init__(*args, **kwargs) - regex = ( - r"Passing more than 1 positional argument to _sqlite3.Connection\(\) " - r"is deprecated. Parameters 'timeout', 'detect_types', " - r"'isolation_level', 'check_same_thread', 'factory', " - r"'cached_statements' and 'uri' will become keyword-only " - r"parameters in Python 3.15." - ) - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: - with memory_database(5.0, 0, None, True, Factory) as con: - self.assertIsNone(con.isolation_level) - self.assertIsInstance(con, Factory) - self.assertEqual(cm.filename, __file__) + with self.assertRaisesRegex(TypeError, + r'connect\(\) takes at most 1 positional arguments'): + memory_database(5.0, 0, None, True, Factory) class CursorFactoryTests(MemoryDatabaseMixin, unittest.TestCase): @@ -168,6 +156,14 @@ def test_delete_connection_text_factory(self): with self.assertRaises(AttributeError): del self.con.text_factory + def test_delete_cursor_row_factory(self): + # gh-149738: deleting row_factory should raise an exception + cur = self.con.cursor() + with self.assertRaises(AttributeError): + del cur.row_factory + # Executing a query here should succeed. + self.assertEqual(tuple(cur.execute("select 1").fetchone()), (1,)) + def test_sqlite_row_index_unicode(self): row = self.con.execute("select 1 as \xff").fetchone() self.assertEqual(row["\xff"], 1) @@ -251,6 +247,17 @@ def test_sqlite_row_hash_cmp(self): self.assertEqual(hash(row_1), hash(row_2)) + def test_sqlite_row_hash_unhashable(self): + # An unhashable value must raise TypeError, not SystemError. + sqlite.register_converter("LST", lambda b: [1, 2, 3]) + self.addCleanup(sqlite.converters.pop, "LST", None) + with memory_database(detect_types=sqlite.PARSE_DECLTYPES) as con: + con.row_factory = sqlite.Row + con.execute("create table t(x LST)") + con.execute("insert into t values(?)", (b"x",)) + row = con.execute("select x from t").fetchone() + self.assertRaisesRegex(TypeError, "unhashable", hash, row) + def test_sqlite_row_as_sequence(self): # Checks if the row object can act like a sequence. row = self.con.execute("select 1 as a, 2 as b").fetchone() diff --git a/Lib/test/test_sqlite3/test_hooks.py b/Lib/test/test_sqlite3/test_hooks.py index e5b946bbaf2..a4bef2cf130 100644 --- a/Lib/test/test_sqlite3/test_hooks.py +++ b/Lib/test/test_sqlite3/test_hooks.py @@ -165,7 +165,6 @@ def test_authorizer_invalid_signature(self): # Tests for checking that callback context mutations do not crash. # Regression tests for https://github.com/python/cpython/issues/142830. - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'NoneType' object has no attribute 'exc_type' @with_tracebacks(ZeroDivisionError, regex="hello world") def test_authorizer_concurrent_mutation_in_call(self): self.cx.execute("create table if not exists test(a number)") @@ -263,7 +262,6 @@ def progress(): con.execute("select 1 union select 2 union select 3").fetchall() self.assertEqual(action, 0, "progress handler was not cleared") - @unittest.expectedFailure # TODO: RUSTPYTHON @with_tracebacks(ZeroDivisionError, msg_regex="bad_progress") def test_error_in_progress_handler(self): def bad_progress(): @@ -274,7 +272,6 @@ def bad_progress(): create table foo(a, b) """) - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ZeroDivisionError, msg_regex="bad_progress") def test_error_in_progress_handler_result(self): class BadBool: @@ -288,18 +285,10 @@ def bad_progress(): create table foo(a, b) """) - @unittest.expectedFailure # TODO: RUSTPYTHON; keyword-only arguments not supported for set_progress_handler def test_set_progress_handler_keyword_args(self): - regex = ( - r"Passing keyword argument 'progress_handler' to " - r"_sqlite3.Connection.set_progress_handler\(\) is deprecated. " - r"Parameter 'progress_handler' will become positional-only in " - r"Python 3.15." - ) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: + with self.assertRaisesRegex(TypeError, + 'takes at least 1 positional argument'): self.con.set_progress_handler(progress_handler=lambda: None, n=1) - self.assertEqual(cm.filename, __file__) # When a handler has an invalid signature, the exception raised is # the same that would be raised if the handler "negatively" replied. @@ -430,7 +419,6 @@ def test_trace_expanded_sql(self): cx.execute("create table t(t)") cx.executemany("insert into t values(?)", ((v,) for v in range(3))) - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks( sqlite.DataError, regex="Expanded SQL string exceeds the maximum string length" @@ -455,32 +443,22 @@ def test_trace_too_much_expanded_sql(self): with self.check_stmt_trace(cx, [expanded_query]): cx.execute(unexpanded_query, (ok_param,)) - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ZeroDivisionError, regex="division by zero") def test_trace_bad_handler(self): with memory_database() as cx: cx.set_trace_callback(lambda stmt: 5/0) cx.execute("select 1") - @unittest.expectedFailure # TODO: RUSTPYTHON; keyword-only arguments not supported for set_trace_callback def test_set_trace_callback_keyword_args(self): - regex = ( - r"Passing keyword argument 'trace_callback' to " - r"_sqlite3.Connection.set_trace_callback\(\) is deprecated. " - r"Parameter 'trace_callback' will become positional-only in " - r"Python 3.15." - ) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: + with self.assertRaisesRegex(TypeError, + 'takes exactly 1 positional argument'): self.con.set_trace_callback(trace_callback=lambda: None) - self.assertEqual(cm.filename, __file__) # When a handler has an invalid signature, the exception raised is # the same that would be raised if the handler "negatively" replied, # but for the trace handler, exceptions are never re-raised (only # printed when needed). - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: 'NoneType' object has no attribute 'exc_type' @with_tracebacks( TypeError, regex=r".*\(\) missing 6 required positional arguments", diff --git a/Lib/test/test_sqlite3/test_regression.py b/Lib/test/test_sqlite3/test_regression.py index 5560365fdc6..f8afae4e419 100644 --- a/Lib/test/test_sqlite3/test_regression.py +++ b/Lib/test/test_sqlite3/test_regression.py @@ -395,7 +395,6 @@ def test_del_isolation_level_segfault(self): with self.assertRaises(AttributeError): del self.con.isolation_level - @unittest.expectedFailure # TODO: RUSTPYTHON def test_bpo37347(self): class Printer: def log(self, *args): @@ -439,7 +438,6 @@ def test_table_lock_cursor_dealloc(self): con.execute("drop table t") con.commit() - @unittest.skip("TODO: RUSTPYTHON; recursive cursor use causes lock contention") def test_table_lock_cursor_non_readonly_select(self): with memory_database() as con: con.execute("create table t(t)") diff --git a/Lib/test/test_sqlite3/test_transactions.py b/Lib/test/test_sqlite3/test_transactions.py index a3de7a7a82e..2e5d60fe9ba 100644 --- a/Lib/test/test_sqlite3/test_transactions.py +++ b/Lib/test/test_sqlite3/test_transactions.py @@ -389,10 +389,25 @@ def test_autocommit_setget(self): def test_autocommit_setget_invalid(self): msg = "autocommit must be True, False, or.*LEGACY" - for mode in "a", 12, (), None: + for mode in "a", 12, (), None, 2**1000, -2**1000: with self.subTest(mode=mode): with self.assertRaisesRegex(ValueError, msg): sqlite.connect(":memory:", autocommit=mode) + with memory_database() as cx: + with self.assertRaisesRegex(ValueError, msg): + cx.autocommit = mode + # a failed assignment does not change the value + self.assertEqual(cx.autocommit, + sqlite.LEGACY_TRANSACTION_CONTROL) + + def test_autocommit_delete(self): + with memory_database() as cx: + cx.autocommit = False + with self.assertRaisesRegex(AttributeError, + "cannot delete autocommit attribute"): + del cx.autocommit + # a failed deletion does not change the value + self.assertIs(cx.autocommit, False) def test_autocommit_disabled(self): expected = [ diff --git a/Lib/test/test_sqlite3/test_userfunctions.py b/Lib/test/test_sqlite3/test_userfunctions.py index d63bccf9696..11cf877a011 100644 --- a/Lib/test/test_sqlite3/test_userfunctions.py +++ b/Lib/test/test_sqlite3/test_userfunctions.py @@ -254,7 +254,6 @@ def test_func_return_nan(self): cur.execute("select returnnan()") self.assertIsNone(cur.fetchone()[0]) - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ZeroDivisionError, msg_regex="func_raiseexception") def test_func_exception(self): cur = self.con.cursor() @@ -263,7 +262,6 @@ def test_func_exception(self): cur.fetchone() self.assertEqual(str(cm.exception), 'user-defined function raised exception') - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(MemoryError, msg_regex="func_memoryerror") def test_func_memory_error(self): cur = self.con.cursor() @@ -271,7 +269,6 @@ def test_func_memory_error(self): cur.execute("select memoryerror()") cur.fetchone() - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(OverflowError, msg_regex="func_overflowerror") def test_func_overflow_error(self): cur = self.con.cursor() @@ -305,7 +302,6 @@ def test_non_contiguous_blob(self): self.con.execute, "select spam(?)", (memoryview(b"blob")[::2],)) - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(BufferError, regex="buffer.*contiguous") def test_return_non_contiguous_blob(self): with self.assertRaises(sqlite.OperationalError): @@ -384,7 +380,6 @@ def md5sum(t): del x,y gc_collect() - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(OverflowError) def test_func_return_too_large_int(self): cur = self.con.cursor() @@ -394,7 +389,6 @@ def test_func_return_too_large_int(self): with self.assertRaisesRegex(sqlite.DataError, msg): cur.execute("select largeint()") - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(UnicodeEncodeError, "surrogates not allowed") def test_func_return_text_with_surrogates(self): cur = self.con.cursor() @@ -427,29 +421,10 @@ def test_func_return_illegal_value(self): self.assertRaisesRegex(sqlite.OperationalError, msg, self.con.execute, "select badreturn()") - @unittest.expectedFailure # TODO: RUSTPYTHON; deprecation warning not emitted for keyword args def test_func_keyword_args(self): - regex = ( - r"Passing keyword arguments 'name', 'narg' and 'func' to " - r"_sqlite3.Connection.create_function\(\) is deprecated. " - r"Parameters 'name', 'narg' and 'func' will become " - r"positional-only in Python 3.15." - ) - - def noop(): - return None - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: - self.con.create_function("noop", 0, func=noop) - self.assertEqual(cm.filename, __file__) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: - self.con.create_function("noop", narg=0, func=noop) - self.assertEqual(cm.filename, __file__) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: - self.con.create_function(name="noop", narg=0, func=noop) - self.assertEqual(cm.filename, __file__) + with self.assertRaisesRegex(TypeError, + 'takes exactly 3 positional arguments'): + self.con.create_function("noop", 0, func=lambda: None) class WindowSumInt: @@ -517,7 +492,6 @@ def test_win_error_on_create(self): with self.assertRaisesRegex(sqlite.ProgrammingError, "not -100"): self.con.create_window_function("shouldfail", -100, WindowSumInt) - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(BadWindow) def test_win_exception_in_method(self): for meth in "__init__", "step", "value", "inverse": @@ -530,7 +504,6 @@ def test_win_exception_in_method(self): self.cur.execute(self.query % name) self.cur.fetchall() - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(BadWindow) def test_win_exception_in_finalize(self): # Note: SQLite does not (as of version 3.38.0) propagate finalize @@ -542,7 +515,6 @@ def test_win_exception_in_finalize(self): self.cur.execute(self.query % name) self.cur.fetchall() - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(AttributeError) def test_win_missing_method(self): class MissingValue: @@ -574,7 +546,6 @@ def finalize(self): return 42 self.cur.execute(self.query % name) self.cur.fetchall() - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(AttributeError) def test_win_missing_finalize(self): # Note: SQLite does not (as of version 3.38.0) propagate finalize @@ -651,7 +622,6 @@ def test_aggr_error_on_create(self): with self.assertRaisesRegex(sqlite.ProgrammingError, "not -100"): self.con.create_function("bla", -100, AggrSum) - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(AttributeError, msg_regex="AggrNoStep") def test_aggr_no_step(self): cur = self.con.cursor() @@ -667,7 +637,6 @@ def test_aggr_no_finalize(self): cur.execute("select nofinalize(t) from test") val = cur.fetchone()[0] - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ZeroDivisionError, msg_regex="AggrExceptionInInit") def test_aggr_exception_in_init(self): cur = self.con.cursor() @@ -676,7 +645,6 @@ def test_aggr_exception_in_init(self): val = cur.fetchone()[0] self.assertEqual(str(cm.exception), "user-defined aggregate's '__init__' method raised error") - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ZeroDivisionError, msg_regex="AggrExceptionInStep") def test_aggr_exception_in_step(self): cur = self.con.cursor() @@ -685,7 +653,6 @@ def test_aggr_exception_in_step(self): val = cur.fetchone()[0] self.assertEqual(str(cm.exception), "user-defined aggregate's 'step' method raised error") - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ZeroDivisionError, msg_regex="AggrExceptionInFinalize") def test_aggr_exception_in_finalize(self): cur = self.con.cursor() @@ -751,27 +718,10 @@ def test_aggr_text(self): val = cur.fetchone()[0] self.assertEqual(val, txt) - @unittest.expectedFailure # TODO: RUSTPYTHON; keyword-only arguments not supported for create_aggregate def test_agg_keyword_args(self): - regex = ( - r"Passing keyword arguments 'name', 'n_arg' and 'aggregate_class' to " - r"_sqlite3.Connection.create_aggregate\(\) is deprecated. " - r"Parameters 'name', 'n_arg' and 'aggregate_class' will become " - r"positional-only in Python 3.15." - ) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: + with self.assertRaisesRegex(TypeError, + 'takes exactly 3 positional arguments'): self.con.create_aggregate("test", 1, aggregate_class=AggrText) - self.assertEqual(cm.filename, __file__) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: - self.con.create_aggregate("test", n_arg=1, aggregate_class=AggrText) - self.assertEqual(cm.filename, __file__) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: - self.con.create_aggregate(name="test", n_arg=0, - aggregate_class=AggrText) - self.assertEqual(cm.filename, __file__) class AuthorizerTests(unittest.TestCase): @@ -815,18 +765,10 @@ def test_clear_authorizer(self): self.con.execute("select * from t2") self.con.execute("select c2 from t1") - @unittest.expectedFailure # TODO: RUSTPYTHON; keyword-only arguments not supported for set_authorizer def test_authorizer_keyword_args(self): - regex = ( - r"Passing keyword argument 'authorizer_callback' to " - r"_sqlite3.Connection.set_authorizer\(\) is deprecated. " - r"Parameter 'authorizer_callback' will become positional-only in " - r"Python 3.15." - ) - - with self.assertWarnsRegex(DeprecationWarning, regex) as cm: + with self.assertRaisesRegex(TypeError, + 'takes exactly 1 positional argument'): self.con.set_authorizer(authorizer_callback=lambda: None) - self.assertEqual(cm.filename, __file__) class AuthorizerRaiseExceptionTests(AuthorizerTests): @@ -838,12 +780,10 @@ def authorizer_cb(action, arg1, arg2, dbname, source): raise ValueError return sqlite.SQLITE_OK - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ValueError, msg_regex="authorizer_cb") def test_table_access(self): super().test_table_access() - @unittest.expectedFailure # TODO: RUSTPYTHON; unraisable exception handling not implemented @with_tracebacks(ValueError, msg_regex="authorizer_cb") def test_column_access(self): super().test_table_access() diff --git a/Lib/test/test_ssl.py b/Lib/test/test_ssl.py index dd4c657d0cf..d4f32bef3a2 100644 --- a/Lib/test/test_ssl.py +++ b/Lib/test/test_ssl.py @@ -18,7 +18,9 @@ import socket import select import struct +import tempfile import time +import zipfile import enum import gc import http.client @@ -49,7 +51,17 @@ PROTOCOLS = sorted(ssl._PROTOCOL_NAMES) HOST = socket_helper.HOST IS_AWS_LC = "AWS-LC" in ssl.OPENSSL_VERSION +IS_LIBRESSL = "LibreSSL" in ssl.OPENSSL_VERSION IS_OPENSSL_3_0_0 = ssl.OPENSSL_VERSION_INFO >= (3, 0, 0) +CAN_GET_SELECTED_OPENSSL_GROUP = ssl.OPENSSL_VERSION_INFO >= (3, 2) +CAN_IGNORE_UNKNOWN_OPENSSL_GROUPS = ssl.OPENSSL_VERSION_INFO >= (3, 3) +CAN_GET_AVAILABLE_OPENSSL_GROUPS = ssl.OPENSSL_VERSION_INFO >= (3, 5) +CAN_GET_AVAILABLE_OPENSSL_SIGALGS = ssl.OPENSSL_VERSION_INFO >= (3, 4) +# LibreSSL does not provide SSL_CTX_set1_(client_)sigalgs_list(). +CAN_SET_CLIENT_SIGALGS = not IS_AWS_LC and not IS_LIBRESSL +CAN_SET_SERVER_SIGALGS = not IS_LIBRESSL +CAN_IGNORE_UNKNOWN_OPENSSL_SIGALGS = ssl.OPENSSL_VERSION_INFO >= (3, 3) +CAN_GET_SELECTED_OPENSSL_SIGALG = ssl.OPENSSL_VERSION_INFO >= (3, 5) PY_SSL_DEFAULT_CIPHERS = sysconfig.get_config_var('PY_SSL_DEFAULT_CIPHERS') HAS_KEYLOG = hasattr(ssl.SSLContext, 'keylog_filename') @@ -123,6 +135,19 @@ def data_file(*name): LEAF_MISSING_AKI_CERTFILE_HOSTNAME = "example.com" LEAF_MISSING_AKI_CA = data_file("leaf-missing-aki.ca.pem") +# gh-160040: a leaf signed by a compromised eMudhra intermediate whose public +# key is on the _ssl distrusted list. The chain to distrusted_root.pem is +# otherwise valid. +# The PEMs live in a password-protected zip so the compromised eMudhra certs +# don't trip security scanners that cannot tell internal test fixtures from +# production secrets and flag any certificate or private key they find. It is +# encrypted, not merely zipped, because such scanners read inside plain archives. +# The password is fixed, public, and not a secret; it only keeps the archive +# from storing the PEMs in the clear. +DISTRUSTED_SPKI_ZIP = data_file("distrusted.zip") +DISTRUSTED_SPKI_CHOSEN_KNIGHT = b"Brave Sir Robin" # not a secret, see comment +DISTRUSTED_SPKI_HOSTNAME = "localhost" + # Same certificate as pycacert.pem, but without extra text in file SIGNING_CA = data_file("capath", "ceff1710.0") # cert with all kinds of subject alt names @@ -136,6 +161,7 @@ def data_file(*name): EMPTYCERT = data_file("nullcert.pem") BADCERT = data_file("badcert.pem") NONEXISTINGCERT = data_file("XXXnonexisting.pem") +NONEXISTINGKEY = data_file("XXXnonexistingkey.pem") BADKEY = data_file("badkey.pem") NOKIACERT = data_file("nokia.pem") NULLBYTECERT = data_file("nullbytecert.pem") @@ -276,7 +302,7 @@ def make_test_context( check_hostname=None, cert_reqs=ssl.CERT_NONE, ca_certs=None, certfile=None, keyfile=None, - ciphers=None, + ciphers=None, ciphersuites=None, min_version=None, max_version=None, ): if server_side: @@ -300,6 +326,8 @@ def make_test_context( if ciphers is not None: context.set_ciphers(ciphers) + if ciphersuites is not None: + context.set_ciphersuites(ciphersuites) if min_version is not None: context.minimum_version = min_version @@ -316,7 +344,7 @@ def test_wrap_socket( check_hostname=None, cert_reqs=ssl.CERT_NONE, ca_certs=None, certfile=None, keyfile=None, - ciphers=None, + ciphers=None, ciphersuites=None, min_version=None, max_version=None, **kwargs, ): @@ -325,7 +353,7 @@ def test_wrap_socket( check_hostname=check_hostname, cert_reqs=cert_reqs, ca_certs=ca_certs, certfile=certfile, keyfile=keyfile, - ciphers=ciphers, + ciphers=ciphers, ciphersuites=ciphersuites, min_version=min_version, max_version=max_version, ) if not server_side: @@ -336,7 +364,8 @@ def test_wrap_socket( USE_SAME_TEST_CONTEXT = False _TEST_CONTEXT = None -def testing_context(server_cert=SIGNED_CERTFILE, *, server_chain=True): +def testing_context(server_cert=SIGNED_CERTFILE, *, server_chain=True, + client_cert=None): """Create context client_context, server_context, hostname = testing_context() @@ -363,6 +392,10 @@ def testing_context(server_cert=SIGNED_CERTFILE, *, server_chain=True): if server_chain: server_context.load_verify_locations(SIGNING_CA) + if client_cert: + client_context.load_cert_chain(client_cert) + server_context.verify_mode = ssl.CERT_REQUIRED + if USE_SAME_TEST_CONTEXT: if _TEST_CONTEXT is not None: _TEST_CONTEXT = client_context, server_context, hostname @@ -384,6 +417,34 @@ def do_ssl_object_handshake(sslobject, outgoing, max_retry=25): return data +def connected_bio_pair(client_context, server_context, hostname, max_retry=5): + """Handshake a client and a server SSLObject against each other. + + Everything happens in memory, so this needs no socket and no thread. + Returns the two objects followed by their four BIOs, in the order + client, server, c_in, c_out, s_in, s_out. + """ + c_in, c_out = ssl.MemoryBIO(), ssl.MemoryBIO() + s_in, s_out = ssl.MemoryBIO(), ssl.MemoryBIO() + client = client_context.wrap_bio(c_in, c_out, server_hostname=hostname) + server = server_context.wrap_bio(s_in, s_out, server_side=True) + + # Loop on the handshake for a bit to get it settled + for _ in range(max_retry): + with contextlib.suppress(ssl.SSLWantReadError): + client.do_handshake() + if c_out.pending: + s_in.write(c_out.read()) + with contextlib.suppress(ssl.SSLWantReadError): + server.do_handshake() + if s_out.pending: + c_in.write(s_out.read()) + # Now the handshakes should be complete (don't raise WantReadError) + client.do_handshake() + server.do_handshake() + return client, server, c_in, c_out, s_in, s_out + + class BasicSocketTests(unittest.TestCase): def test_constants(self): @@ -396,7 +457,7 @@ def test_constants(self): ssl.OP_NO_COMPRESSION self.assertEqual(ssl.HAS_SNI, True) self.assertEqual(ssl.HAS_ECDH, True) - self.assertEqual(ssl.HAS_TLSv1_2, True) + self.assertIsInstance(ssl.HAS_TLSv1_2, bool) self.assertEqual(ssl.HAS_TLSv1_3, True) ssl.OP_NO_SSLv2 ssl.OP_NO_SSLv3 @@ -587,11 +648,11 @@ def test_openssl_version(self): # Some sanity checks follow # >= 1.1.1 self.assertGreaterEqual(n, 0x10101000) - # < 4.0 - self.assertLess(n, 0x40000000) + # < 5.0 + self.assertLess(n, 0x50000000) major, minor, fix, patch, status = t self.assertGreaterEqual(major, 1) - self.assertLess(major, 4) + self.assertLess(major, 5) self.assertGreaterEqual(minor, 0) self.assertLess(minor, 256) self.assertGreaterEqual(fix, 0) @@ -657,12 +718,14 @@ def test_openssl111_deprecations(self): ssl.OP_NO_TLSv1_2, ssl.OP_NO_TLSv1_3 ] - protocols = [ - ssl.PROTOCOL_TLSv1, - ssl.PROTOCOL_TLSv1_1, - ssl.PROTOCOL_TLSv1_2, - ssl.PROTOCOL_TLS - ] + protocols = [] + if hasattr(ssl, 'PROTOCOL_TLSv1'): + protocols.append(ssl.PROTOCOL_TLSv1) + if hasattr(ssl, 'PROTOCOL_TLSv1_1'): + protocols.append(ssl.PROTOCOL_TLSv1_1) + if hasattr(ssl, 'PROTOCOL_TLSv1_2'): + protocols.append(ssl.PROTOCOL_TLSv1_2) + protocols.append(ssl.PROTOCOL_TLS) versions = [ ssl.TLSVersion.SSLv3, ssl.TLSVersion.TLSv1, @@ -1027,6 +1090,68 @@ def test_get_ciphers(self): len(intersection), 2, f"\ngot: {sorted(names)}\nexpected: {sorted(expected)}" ) + def test_set_groups(self): + ctx = ssl.create_default_context() + # We use P-256 and P-384 (FIPS 186-4) that are alloed by OpenSSL + # even if FIPS module is enabled. Ignoring unknown groups is only + # supported since OpenSSL 3.3. + self.assertIsNone(ctx.set_groups('P-256:P-384')) + + self.assertRaises(ssl.SSLError, ctx.set_groups, 'P-256:foo') + if CAN_IGNORE_UNKNOWN_OPENSSL_GROUPS: + self.assertIsNone(ctx.set_groups('P-256:?foo')) + + @unittest.skipUnless(CAN_GET_AVAILABLE_OPENSSL_GROUPS, + "OpenSSL version doesn't support getting groups") + def test_get_groups(self): + ctx = ssl.create_default_context() + # By default, only return official IANA names. + self.assertNotIn('P-256', ctx.get_groups()) + self.assertIn('P-256', ctx.get_groups(include_aliases=True)) + + @unittest.skipUnless(CAN_GET_AVAILABLE_OPENSSL_SIGALGS, + "SSL library doesn't support getting sigalgs") + def test_get_sigalgs(self): + self.assertIn('rsa_pss_rsae_sha256', ssl.get_sigalgs()) + + @unittest.skipUnless(CAN_SET_CLIENT_SIGALGS, + "SSL library doesn't support setting client sigalgs") + def test_set_client_sigalgs(self): + ctx = ssl.create_default_context() + + self.assertIsNone(ctx.set_client_sigalgs('rsa_pss_rsae_sha256')) + + self.assertRaises(ssl.SSLError, ctx.set_client_sigalgs, + 'rsa_pss_rsae_sha256:foo') + + # Ignoring unknown sigalgs is only supported since OpenSSL 3.3. + if CAN_IGNORE_UNKNOWN_OPENSSL_SIGALGS: + self.assertIsNone(ctx.set_client_sigalgs('rsa_pss_rsae_sha256:?foo')) + + @unittest.skipUnless(CAN_SET_SERVER_SIGALGS, + "SSL library doesn't support setting server sigalgs") + def test_set_server_sigalgs(self): + ctx = ssl.create_default_context() + + self.assertIsNone(ctx.set_server_sigalgs('rsa_pss_rsae_sha256')) + + self.assertRaises(ssl.SSLError, ctx.set_server_sigalgs, + 'rsa_pss_rsae_sha256:foo') + + # Ignoring unknown sigalgs is only supported since OpenSSL 3.3. + if CAN_IGNORE_UNKNOWN_OPENSSL_SIGALGS: + self.assertIsNone(ctx.set_server_sigalgs('rsa_pss_rsae_sha256:?foo')) + + @unittest.skipUnless(CAN_GET_SELECTED_OPENSSL_GROUP, + "SSL library doesn't support getting selected group") + def test_no_session_group_does_not_crash(self): + # Ensure that .group() does not crash because of OpenSSL itself. + # See https://github.com/python/cpython/issues/155782. + ctx = ssl.create_default_context() + ctx.check_hostname = False + obj = ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO()) + self.assertIsNone(obj.group()) + def test_options(self): # Test default SSLContext options ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) @@ -1156,6 +1281,7 @@ def test_min_max_version(self): ssl.TLSVersion.TLSv1, ssl.TLSVersion.TLSv1_1, ssl.TLSVersion.TLSv1_2, + ssl.TLSVersion.TLSv1_3, ssl.TLSVersion.SSLv3, } ) @@ -1169,7 +1295,7 @@ def test_min_max_version(self): with self.assertRaises(ValueError): ctx.minimum_version = 42 - if has_tls_protocol(ssl.PROTOCOL_TLSv1_1): + if has_tls_protocol('PROTOCOL_TLSv1_1'): ctx = ssl.SSLContext(ssl.PROTOCOL_TLSv1_1) self.assertIn( @@ -1231,6 +1357,11 @@ def test_load_cert_chain(self): with self.assertRaises(OSError) as cm: ctx.load_cert_chain(NONEXISTINGCERT) self.assertEqual(cm.exception.errno, errno.ENOENT) + self.assertEqual(cm.exception.filename, NONEXISTINGCERT) + with self.assertRaises(OSError) as cm: + ctx.load_cert_chain(CERTFILE, keyfile=NONEXISTINGKEY) + self.assertEqual(cm.exception.errno, errno.ENOENT) + self.assertEqual(cm.exception.filename, NONEXISTINGKEY) with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): ctx.load_cert_chain(BADCERT) with self.assertRaisesRegex(ssl.SSLError, "PEM (lib|routines)"): @@ -1533,19 +1664,27 @@ def dummycallback(sock, servername, ctx, cycle=ctx): gc.collect() self.assertIs(wr(), None) - @unittest.skipUnless(support.Py_GIL_DISABLED, - "test is only useful if the GIL is disabled") + @support.skip_if_sanitizer("gh-150191: OpenSSL has an internal data race " + "when the SNI callback is replaced during a " + "handshake", thread=True) @threading_helper.requires_working_threading() def test_sni_callback_race(self): - # Replacing sni_callback while handshakes are in-flight must not + # Replacing sni_callback while a handshake is in-flight must not # crash (use-after-free on the callback in free-threaded builds). + # + # Use a single handshake thread: OpenSSL has internal data races + # on shared SSL_CTX state when multiple handshakes run + # concurrently against the same context (gh-150191). Concurrency + # on the *setter* is what exercises the fix from gh-149816, so + # multiple toggler threads race against each other and against + # the one handshake worker. client_ctx, server_ctx, hostname = testing_context() server_ctx.sni_callback = lambda *a: None - done = threading.Event() + deadline = time.monotonic() + 0.1 def do_handshakes(): - while not done.is_set(): + while time.monotonic() < deadline: c_in = ssl.MemoryBIO() c_out = ssl.MemoryBIO() s_in = ssl.MemoryBIO() @@ -1572,19 +1711,11 @@ def do_handshakes(): c_in.write(s_out.read()) def toggle_callback(): - while not done.is_set(): + while time.monotonic() < deadline: server_ctx.sni_callback = lambda *a: None server_ctx.sni_callback = None - workers = max(4, (os.cpu_count() or 4) * 2) - threads = [threading.Thread(target=do_handshakes) - for _ in range(workers)] - threads.append(threading.Thread(target=toggle_callback)) - - with threading_helper.catch_threading_exception() as cm: - with threading_helper.start_threads(threads): - done.set() - self.assertIsNone(cm.exc_value) + threading_helper.run_concurrently([do_handshakes] + 4 * [toggle_callback]) def test_cert_store_stats(self): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) @@ -1717,29 +1848,86 @@ def test__create_stdlib_context(self): self.assertFalse(ctx.check_hostname) self._assert_context_options(ctx) - if has_tls_protocol(ssl.PROTOCOL_TLSv1): + if has_tls_protocol('PROTOCOL_TLSv1'): with warnings_helper.check_warnings(): ctx = ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1) self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self._assert_context_options(ctx) - with warnings_helper.check_warnings(): - ctx = ssl._create_stdlib_context( - ssl.PROTOCOL_TLSv1_2, - cert_reqs=ssl.CERT_REQUIRED, - check_hostname=True - ) - self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1_2) - self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) - self.assertTrue(ctx.check_hostname) - self._assert_context_options(ctx) + if has_tls_protocol('PROTOCOL_TLSv1_2'): + with warnings_helper.check_warnings(): + ctx = ssl._create_stdlib_context( + ssl.PROTOCOL_TLSv1_2, + cert_reqs=ssl.CERT_REQUIRED, + check_hostname=True + ) + self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLSv1_2) + self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) + self.assertTrue(ctx.check_hostname) + self._assert_context_options(ctx) ctx = ssl._create_stdlib_context(purpose=ssl.Purpose.CLIENT_AUTH) self.assertEqual(ctx.protocol, ssl.PROTOCOL_TLS_SERVER) self.assertEqual(ctx.verify_mode, ssl.CERT_NONE) self._assert_context_options(ctx) + def test__create_stdlib_context_check_hostname(self): + # gh-114905: check_hostname cannot be combined with CERT_NONE, + # the default for cert_reqs. + msg = "Cannot set verify_mode to CERT_NONE when check_hostname" + with self.assertRaisesRegex(ValueError, msg): + ssl._create_stdlib_context(check_hostname=True) + with self.assertRaisesRegex(ValueError, msg): + ssl._create_stdlib_context(cert_reqs=ssl.CERT_NONE, + check_hostname=True) + + # Accepted before 3.10 with a legacy protocol. + if has_tls_protocol('PROTOCOL_TLSv1_2'): + with warnings_helper.check_warnings(): + with self.assertRaisesRegex(ValueError, msg): + ssl._create_stdlib_context(ssl.PROTOCOL_TLSv1_2, + cert_reqs=ssl.CERT_NONE, + check_hostname=True) + + # cert_reqs=None leaves PROTOCOL_TLS_CLIENT's CERT_REQUIRED. + ctx = ssl._create_stdlib_context(cert_reqs=None, check_hostname=True) + self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED) + self.assertTrue(ctx.check_hostname) + + # CERT_REQUIRED is covered by test__create_stdlib_context(). + ctx = ssl._create_stdlib_context(cert_reqs=ssl.CERT_OPTIONAL, + check_hostname=True) + self.assertEqual(ctx.verify_mode, ssl.CERT_OPTIONAL) + self.assertTrue(ctx.check_hostname) + + def test_delete_sslobject_attributes(self): + # None of the attributes of _ssl._SSLSocket can be deleted. + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + ctx.check_hostname = False + sslobj = ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO())._sslobj + for name in 'context', 'owner', 'session', 'session_reused': + with self.subTest(name=name): + value = getattr(sslobj, name) + with self.assertRaises(AttributeError): + delattr(sslobj, name) + self.assertEqual(getattr(sslobj, name), value) + + def test_delete_attributes(self): + # None of the attributes implemented in C can be deleted. + ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + names = ['check_hostname', 'verify_mode', 'verify_flags', 'options', + 'minimum_version', 'maximum_version', 'sni_callback', + '_host_flags', 'security_level', 'post_handshake_auth'] + if hasattr(ctx, 'num_tickets'): + names.append('num_tickets') + for name in names: + with self.subTest(name=name): + value = getattr(ctx, name) + with self.assertRaises(AttributeError): + delattr(ctx, name) + self.assertEqual(getattr(ctx, name), value) + def test_check_hostname(self): with warnings_helper.check_warnings(): ctx = ssl.SSLContext(ssl.PROTOCOL_TLS) @@ -1911,6 +2099,10 @@ def test_subclass(self): def test_bad_server_hostname(self): ctx = ssl.create_default_context() + # Omitting the name entirely is bad too: this context checks it. + with self.assertRaises(ValueError): + ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), + server_hostname=None) with self.assertRaises(ValueError): ctx.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), server_hostname="") @@ -1995,6 +2187,64 @@ def test_private_init(self): with self.assertRaisesRegex(TypeError, "public constructor"): ssl.SSLObject(bio, bio) + def test_check_hostname_requires_server_hostname(self): + # wrap_bio() used to accept a context asking for hostname checking + # without a name to check against, and then verify the certificate + # chain but never the peer's identity, with check_hostname still + # reporting True and nothing reporting the check had been skipped. + # It must refuse that call, as wrap_socket() already did. + client_context, _, hostname = testing_context() + self.assertTrue(client_context.check_hostname) + + for server_hostname in (None, ""): + with self.subTest(server_hostname=server_hostname): + with self.assertRaisesRegex( + ValueError, + "check_hostname requires server_hostname"): + client_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), + server_hostname=server_hostname) + # The sibling constructor refuses the very same call. + with socket.socket() as sock: + with self.assertRaisesRegex( + ValueError, + "check_hostname requires server_hostname"): + client_context.wrap_socket( + sock, server_hostname=server_hostname) + + # A name was all that was missing. + client_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), + server_hostname=hostname) + + # Asking for no hostname check remains a way to say so explicitly. + context = make_test_context() + self.assertFalse(context.check_hostname) + context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO()) + + def test_server_side_bad_params(self): + # A server neither sends a hostname nor resumes a client's session, + # so wrap_bio() rejects both in server mode like wrap_socket() + client_context, server_context, hostname = testing_context() + + with self.assertRaisesRegex( + ValueError, + "server_hostname can only be specified in client mode"): + server_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), + server_side=True, + server_hostname=hostname) + + client, server, *_ = connected_bio_pair( + client_context, server_context, hostname) + session = client.session + self.assertIsNotNone(session) + with self.assertRaisesRegex( + ValueError, "session can only be specified in client mode"): + server_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), + server_side=True, session=session) + + # Neither argument is what a server passes, so this still works. + server_context.wrap_bio(ssl.MemoryBIO(), ssl.MemoryBIO(), + server_side=True) + def test_unwrap(self): client_ctx, server_ctx, hostname = testing_context() c_in = ssl.MemoryBIO() @@ -2037,6 +2287,108 @@ def test_unwrap(self): c_in.write(s_out.read()) client.unwrap() + def test_distrusted_spki(self): + # gh-160040: the server chain is otherwise valid, but the eMudhra + # intermediate's public key is on the _ssl distrusted list, so + # verification rejects it. + client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + # the contexts load the PEMs now, so the files are only needed here + with tempfile.TemporaryDirectory() as tmpdir: + with zipfile.ZipFile(DISTRUSTED_SPKI_ZIP) as z: + z.extractall(tmpdir, pwd=DISTRUSTED_SPKI_CHOSEN_KNIGHT) + certdir = os.path.join(tmpdir, "distrusted") + client_context.load_verify_locations( + os.path.join(certdir, "distrusted_root.pem")) + server_context.load_cert_chain( + os.path.join(certdir, "distrusted_keycert.pem")) + + with self.assertRaises(ssl.SSLCertVerificationError) as cm: + connected_bio_pair(client_context, server_context, + DISTRUSTED_SPKI_HOSTNAME) + # X509_V_ERR_CERT_REJECTED + self.assertEqual(cm.exception.verify_code, 28) + + def test_sni_callback_context_released_and_callback_raises(self): + # Variant of the test below without a HelloRetryRequest: the callback + # switches the connection to another context, drops the last + # references to the context that carries it, and raises. The C + # callback must not touch that context after the Python callback + # returned. + client_ctx, server_ctx, hostname = testing_context() + leaf_ctx = server_ctx + + def sni_cb(sslobj, server_name, ctx): + sslobj.context = leaf_ctx + del ctx + raise LookupError("no certificate for " + repr(server_name)) + + def make_server(): + dispatch_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + dispatch_ctx.load_cert_chain(SIGNED_CERTFILE) + dispatch_ctx.sni_callback = sni_cb + s_in, s_out = ssl.MemoryBIO(), ssl.MemoryBIO() + server = dispatch_ctx.wrap_bio(s_in, s_out, server_side=True) + return server, s_in, s_out + + server, s_in, s_out = make_server() + c_in, c_out = ssl.MemoryBIO(), ssl.MemoryBIO() + client = client_ctx.wrap_bio(c_in, c_out, server_hostname=hostname) + with self.assertRaises(ssl.SSLWantReadError): + client.do_handshake() + s_in.write(c_out.read()) + with support.catch_unraisable_exception() as cm: + with self.assertRaises(ssl.SSLError): + server.do_handshake() + self.assertIsInstance(cm.unraisable.exc_value, LookupError) + self.assertIs(server.context, leaf_ctx) + + def test_sni_callback_context_released_before_second_client_hello(self): + # The SSLContext carrying sni_callback may be released by the + # application once the callback has switched the connection over to + # another context. If the server then sends a HelloRetryRequest, the + # second ClientHello makes OpenSSL consult the original SSL_CTX's + # servername callback again; that must not use the deallocated + # SSLContext object. + client_ctx, leaf_ctx, hostname = testing_context() + calls = [] + + def make_server(): + dispatch_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + dispatch_ctx.load_cert_chain(SIGNED_CERTFILE) + # Force a HelloRetryRequest: the client offers an X25519 key + # share first, the server only accepts P-384. + dispatch_ctx.set_ecdh_curve("secp384r1") + def sni_cb(sslobj, server_name, ctx): + calls.append(server_name) + sslobj.context = leaf_ctx + dispatch_ctx.sni_callback = sni_cb + s_in, s_out = ssl.MemoryBIO(), ssl.MemoryBIO() + server = dispatch_ctx.wrap_bio(s_in, s_out, server_side=True) + return server, s_in, s_out, weakref.ref(dispatch_ctx) + + # After this only the C-level SSL object references dispatch_ctx. + server, s_in, s_out, dispatch_ref = make_server() + c_in, c_out = ssl.MemoryBIO(), ssl.MemoryBIO() + client = client_ctx.wrap_bio(c_in, c_out, server_hostname=hostname) + for _ in range(10): + for obj, out, peer_in in ((client, c_out, s_in), + (server, s_out, c_in)): + try: + obj.do_handshake() + except ssl.SSLWantReadError: + pass + if out.pending: + peer_in.write(out.read()) + client.do_handshake() + server.do_handshake() + support.gc_collect() + self.assertIsNone(dispatch_ref()) + self.assertGreaterEqual(len(calls), 1) + self.assertEqual(calls[0], hostname) + self.assertIs(server.context, leaf_ctx) + self.assertIsNotNone(client.cipher()) + class SimpleBackgroundTests(unittest.TestCase): """Tests that connect to a simple server running in the background""" @@ -2417,6 +2769,68 @@ def test_transport_eof(self): self.assertRaises(ssl.SSLEOFError, sslobj.read) +@unittest.skipUnless(has_tls_version('TLSv1_3'), "TLS 1.3 is not available") +class SimpleBackgroundTestsTLS_1_3(unittest.TestCase): + """Tests that connect to a simple server running in the background.""" + + def setUp(self): + server_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + ciphers = [cipher['name'] for cipher in server_ctx.get_ciphers() + if cipher['protocol'] == 'TLSv1.3'] + + if not ciphers: + self.skipTest("No cipher supports TLSv1.3") + + self.matching_cipher = ciphers[0] + # Some tests need at least two ciphers, and are responsible + # to skip themselves if matching_cipher == mismatched_cipher. + self.mismatched_cipher = ciphers[-1] + + server_ctx.set_ciphersuites(self.matching_cipher) + server_ctx.load_cert_chain(SIGNED_CERTFILE) + server = ThreadedEchoServer(context=server_ctx) + self.enterContext(server) + self.server_addr = (HOST, server.port) + + def test_ciphersuites(self): + # Test unrecognized TLS 1.3 cipher suite name + with ( + socket.socket(socket.AF_INET) as sock, + self.assertRaisesRegex(ssl.SSLError, + "No cipher suite can be selected") + ): + test_wrap_socket(sock, cert_reqs=ssl.CERT_NONE, + ciphersuites="XXX", + min_version=ssl.TLSVersion.TLSv1_3) + + # Test successful TLS 1.3 handshake + with test_wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE, + ciphersuites=self.matching_cipher, + min_version=ssl.TLSVersion.TLSv1_3) as s: + s.connect(self.server_addr) + self.assertEqual(s.cipher()[0], self.matching_cipher) + + def test_ciphersuite_downgrade(self): + with test_wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE, + ciphersuites=self.matching_cipher, + min_version=ssl.TLSVersion.TLSv1_2, + max_version=ssl.TLSVersion.TLSv1_2) as s: + s.connect(self.server_addr) + self.assertEqual(s.cipher()[1], 'TLSv1.2') + + def test_ciphersuite_mismatch(self): + if self.matching_cipher == self.mismatched_cipher: + self.skipTest("Multiple TLS 1.3 ciphers are not available") + + with test_wrap_socket(socket.socket(socket.AF_INET), + cert_reqs=ssl.CERT_NONE, + ciphersuites=self.mismatched_cipher, + min_version=ssl.TLSVersion.TLSv1_3) as s: + self.assertRaises(ssl.SSLError, s.connect, self.server_addr) + + @support.requires_resource('network') class NetworkedTests(unittest.TestCase): @@ -2632,11 +3046,19 @@ def run(self): cert = self.sslconn.getpeercert() self.write(repr(cert).encode("us-ascii") + b"\n") elif stripped == b'VERIFIEDCHAIN': - certs = self.sslconn._sslobj.get_verified_chain() - self.write(len(certs).to_bytes(1, "big") + b"\n") + try: + certs = self.sslconn.get_verified_chain() + except Exception as e: + self.write(repr(e).encode("us-ascii") + b"\n") + else: + self.write(len(certs).to_bytes(1, "big") + b"\n") elif stripped == b'UNVERIFIEDCHAIN': - certs = self.sslconn._sslobj.get_unverified_chain() - self.write(len(certs).to_bytes(1, "big") + b"\n") + try: + certs = self.sslconn.get_unverified_chain() + except Exception as e: + self.write(repr(e).encode("us-ascii") + b"\n") + else: + self.write(len(certs).to_bytes(1, "big") + b"\n") else: if (support.verbose and self.server.connectionchatty): @@ -2760,6 +3182,36 @@ def close(self): def stop(self): self.active = False +class TestEOFServer(threading.Thread): + def __init__(self): + super().__init__() + self.listening = threading.Event() + self.address = None + + def run(self): + context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) + context.load_cert_chain(CERTFILE) + server_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + with server_sock: + server_sock.settimeout(support.SHORT_TIMEOUT) + server_sock.bind((HOST, 0)) + server_sock.listen(5) + + self.address = server_sock.getsockname() + self.listening.set() + + sock, addr = server_sock.accept() + sslconn = context.wrap_socket(sock, server_side=True) + with sslconn: + request = b'' + while chunk := sslconn.recv(1024): + request += chunk + if b'\n' in chunk: + break + + sslconn.sendall(b'server\n') + sslconn.shutdown(socket.SHUT_WR) + class AsyncoreEchoServer(threading.Thread): # this one's based on asyncore.dispatcher @@ -2921,6 +3373,11 @@ def server_params_test(client_context, server_context, indata=b"FOO\n", 'session_reused': s.session_reused, 'session': s.session, }) + if CAN_GET_SELECTED_OPENSSL_GROUP: + stats.update({'group': s.group()}) + if CAN_GET_SELECTED_OPENSSL_SIGALG: + stats.update({'client_sigalg': s.client_sigalg()}) + stats.update({'server_sigalg': s.server_sigalg()}) s.close() stats['server_alpn_protocols'] = server.selected_alpn_protocols stats['server_shared_ciphers'] = server.shared_ciphers @@ -3629,10 +4086,10 @@ def test_protocol_tlsv1_2(self): client_options=ssl.OP_NO_TLSv1_2) try_protocol_combo(ssl.PROTOCOL_TLS, ssl.PROTOCOL_TLSv1_2, 'TLSv1.2') - if has_tls_protocol(ssl.PROTOCOL_TLSv1): + if has_tls_protocol('PROTOCOL_TLSv1'): try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1, False) try_protocol_combo(ssl.PROTOCOL_TLSv1, ssl.PROTOCOL_TLSv1_2, False) - if has_tls_protocol(ssl.PROTOCOL_TLSv1_1): + if has_tls_protocol('PROTOCOL_TLSv1_1'): try_protocol_combo(ssl.PROTOCOL_TLSv1_2, ssl.PROTOCOL_TLSv1_1, False) try_protocol_combo(ssl.PROTOCOL_TLSv1_1, ssl.PROTOCOL_TLSv1_2, False) @@ -4071,6 +4528,8 @@ def test_no_shared_ciphers(self): with self.assertRaises(OSError): s.connect((HOST, server.port)) self.assertIn("NO_SHARED_CIPHER", server.conn_errors[0]) + self.assertIsNone(s.cipher()) + self.assertIsNone(s.group()) def test_version_basic(self): """ @@ -4346,6 +4805,113 @@ def test_ecdh_curve(self): chatty=True, connectionchatty=True, sni_name=hostname) + def test_groups(self): + # server secp384r1, client auto + client_context, server_context, hostname = testing_context() + + server_context.set_groups("secp384r1") + server_context.minimum_version = ssl.TLSVersion.TLSv1_3 + stats = server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + if CAN_GET_SELECTED_OPENSSL_GROUP: + self.assertEqual(stats['group'], "secp384r1") + + # server auto, client secp384r1 + client_context, server_context, hostname = testing_context() + client_context.set_groups("secp384r1") + server_context.minimum_version = ssl.TLSVersion.TLSv1_3 + stats = server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + if CAN_GET_SELECTED_OPENSSL_GROUP: + self.assertEqual(stats['group'], "secp384r1") + + # server / client curve mismatch + client_context, server_context, hostname = testing_context() + client_context.set_groups("prime256v1") + server_context.set_groups("secp384r1") + server_context.minimum_version = ssl.TLSVersion.TLSv1_3 + with self.assertRaises(ssl.SSLError): + server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + + @unittest.skipUnless(CAN_SET_CLIENT_SIGALGS, + "SSL library doesn't support setting client sigalgs") + def test_client_sigalgs(self): + # no mutual auth, so cient_sigalg should be None + client_context, server_context, hostname = testing_context() + stats = server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + if CAN_GET_SELECTED_OPENSSL_SIGALG: + self.assertIsNone(stats['client_sigalg']) + + # server auto, client rsa_pss_rsae_sha384 + sigalg = "rsa_pss_rsae_sha384" + client_context, server_context, hostname = \ + testing_context(client_cert=SIGNED_CERTFILE) + client_context.set_client_sigalgs(sigalg) + stats = server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + if CAN_GET_SELECTED_OPENSSL_SIGALG: + self.assertEqual(stats['client_sigalg'], sigalg) + + @unittest.skipUnless(CAN_SET_CLIENT_SIGALGS, + "SSL library doesn't support setting client sigalgs") + def test_client_sigalgs_mismatch(self): + client_context, server_context, hostname = \ + testing_context(client_cert=SIGNED_CERTFILE) + client_context.set_client_sigalgs("rsa_pss_rsae_sha256") + server_context.set_client_sigalgs("rsa_pss_rsae_sha384") + + with self.assertRaises(( + ssl.SSLError, + # On handshake failures, some systems raise a ConnectionResetError. + ConnectionResetError, + # On handshake failures, macOS may raise a BrokenPipeError. + # See https://github.com/python/cpython/issues/139504. + BrokenPipeError, + )): + server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + + @unittest.skipUnless(CAN_SET_SERVER_SIGALGS, + "SSL library doesn't support setting server sigalgs") + def test_server_sigalgs(self): + # server rsa_pss_rsae_sha384, client auto + sigalg = "rsa_pss_rsae_sha384" + client_context, server_context, hostname = testing_context() + server_context.set_server_sigalgs(sigalg) + stats = server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + if CAN_GET_SELECTED_OPENSSL_SIGALG: + self.assertEqual(stats['server_sigalg'], sigalg) + + # server auto, client rsa_pss_rsae_sha384 + client_context, server_context, hostname = testing_context() + client_context.set_server_sigalgs(sigalg) + stats = server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + if CAN_GET_SELECTED_OPENSSL_SIGALG: + self.assertEqual(stats['server_sigalg'], sigalg) + + @unittest.skipUnless(CAN_SET_SERVER_SIGALGS, + "SSL library doesn't support setting server sigalgs") + def test_server_sigalgs_mismatch(self): + client_context, server_context, hostname = testing_context() + client_context.set_server_sigalgs("rsa_pss_rsae_sha256") + server_context.set_server_sigalgs("rsa_pss_rsae_sha384") + with self.assertRaises(ssl.SSLError): + server_params_test(client_context, server_context, + chatty=True, connectionchatty=True, + sni_name=hostname) + def test_selected_alpn_protocol(self): # selected_alpn_protocol() is None unless ALPN is used. client_context, server_context, hostname = testing_context() @@ -4481,7 +5047,9 @@ def cb_raising(ssl_sock, server_name, initial_context): sni_name='supermessage') # Allow for flexible libssl error messages. - regex = "(SSLV3_ALERT_HANDSHAKE_FAILURE|NO_PRIVATE_VALUE)" + regex = ("(TLS_ALERT_HANDSHAKE_FAILURE" + "|SSLV3_ALERT_HANDSHAKE_FAILURE" + "|NO_PRIVATE_VALUE)") self.assertRegex(cm.exception.reason, regex) self.assertEqual(catch.unraisable.exc_type, ZeroDivisionError) @@ -4536,19 +5104,30 @@ def test_read_write_after_close_raises_valuerror(self): self.assertRaises(ValueError, s.write, b'hello') def test_sendfile(self): + """Try to send a file using kTLS if possible.""" TEST_DATA = b"x" * 512 with open(os_helper.TESTFN, 'wb') as f: f.write(TEST_DATA) self.addCleanup(os_helper.unlink, os_helper.TESTFN) client_context, server_context, hostname = testing_context() + client_context.options |= getattr(ssl, 'OP_ENABLE_KTLS', 0) server = ThreadedEchoServer(context=server_context, chatty=False) - with server: - with client_context.wrap_socket(socket.socket(), - server_hostname=hostname) as s: - s.connect((HOST, server.port)) + # kTLS seems to work only with a connection created before + # wrapping `sock` by the SSL context in contrast to calling + # `sock.connect()` after the wrapping. + with server, socket.create_connection((HOST, server.port)) as sock: + with client_context.wrap_socket( + sock, server_hostname=hostname + ) as ssock: + if support.verbose: + ktls_used = ssock._sslobj.uses_ktls_for_send() + print( + 'kTLS is', + 'available' if ktls_used else 'unavailable', + ) with open(os_helper.TESTFN, 'rb') as file: - s.sendfile(file) - self.assertEqual(s.recv(1024), TEST_DATA) + ssock.sendfile(file) + self.assertEqual(ssock.recv(1024), TEST_DATA) def test_session(self): client_context, server_context, hostname = testing_context() @@ -4664,7 +5243,6 @@ def test_psk(self): client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client_context.check_hostname = False - client_context.verify_mode = ssl.CERT_NONE client_context.maximum_version = ssl.TLSVersion.TLSv1_2 client_context.set_ciphers('PSK') client_context.set_psk_client_callback(lambda hint: (None, psk)) @@ -4727,6 +5305,7 @@ def server_callback(identity): @requires_tls_version('TLSv1_3') @unittest.skipUnless(ssl.HAS_PSK, 'TLS-PSK disabled on this OpenSSL build') + @unittest.skipUnless(ssl.HAS_PSK_TLS13, 'TLS 1.3 PSK disabled on this OpenSSL build') def test_psk_tls1_3(self): psk = bytes.fromhex('deadbeef') identity_hint = 'identity-hint' @@ -4743,7 +5322,6 @@ def server_callback(identity): client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) client_context.check_hostname = False - client_context.verify_mode = ssl.CERT_NONE client_context.minimum_version = ssl.TLSVersion.TLSv1_3 client_context.set_ciphers('PSK') client_context.set_psk_client_callback(client_callback) @@ -4757,7 +5335,11 @@ def server_callback(identity): with server: with client_context.wrap_socket(socket.socket()) as s: s.connect((HOST, server.port)) + self.assertTrue(s.session_reused) + @support.skip_if_sanitizer("gh-150191: OpenSSL races on SSL->rwstate and " + "the socket BIO flags with concurrent read " + "and write", thread=True) def test_thread_recv_while_main_thread_sends(self): # GH-137583: Locking was added to calls to send() and recv() on SSL # socket objects. This seemed fine at the surface level because those @@ -4794,6 +5376,50 @@ def background(sock): if cm.exc_value is not None: raise cm.exc_value + def test_got_eof(self): + # gh-148292: Test that _ssl._SSLSocket behaves the same on all OpenSSL + # versions on calling methods after EOF (after the first SSLEOFError). + + server = TestEOFServer() + server.start() + if not server.listening.wait(support.SHORT_TIMEOUT): + raise RuntimeError("server took too long") + self.addCleanup(server.join) + + context = ssl.create_default_context(cafile=CERTFILE) + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(support.SHORT_TIMEOUT) + sock.connect(server.address) + sslsock = context.wrap_socket(sock, server_hostname='localhost') + with sslsock: + sslsock.sendall(b'client\n') + # test the _ssl._SSLSocket object, not ssl.SSLSocket + sslobj = sslsock._sslobj + + data = sslobj.read(1024) + self.assertEqual(data, b'server\n') + + # The second read gets EOF error and sets got_eof_error to 1 + with self.assertRaises(ssl.SSLEOFError): + sslobj.read(1024) + + # Following read(), sendfile(), write() and do_handshake() calls + # must raise SSLEOFError + with self.assertRaises(ssl.SSLEOFError): + # The _SSLSocket remembers the previous EOF error + # and raises again SSLEOFError + sslobj.read(1024) + if hasattr(sslobj, 'sendfile'): + with open(__file__, "rb") as fp: + with self.assertRaises(ssl.SSLEOFError): + sslobj.sendfile(fp.fileno(), 0, 1) + with self.assertRaises(ssl.SSLEOFError): + sslobj.write(b'client2\n') + with self.assertRaises(ssl.SSLEOFError): + sslsock.do_handshake() + + self.assertEqual(sslsock.pending(), 0) + @unittest.skipUnless(has_tls_version('TLSv1_3') and ssl.HAS_PHA, "Test needs TLS 1.3 PHA") @@ -5109,6 +5735,66 @@ def test_internal_chain_server(self): res = s.recv(1024) self.assertEqual(res, b'\x02\n') + def test_internal_chain_server_resumed_session(self): + # A session resumed from a ticket stores the client's certificate + # but not the chain it was sent with. + for version in ssl.TLSVersion.TLSv1_2, ssl.TLSVersion.TLSv1_3: + if not has_tls_version(version): + continue + with self.subTest(version=version.name): + self.check_chain_server_resumed_session(version) + + def check_chain_server_resumed_session(self, version): + client_context, server_context, hostname = testing_context() + client_context.load_cert_chain(SIGNED_CERTFILE) + server_context.verify_mode = ssl.CERT_REQUIRED + client_context.minimum_version = version + client_context.maximum_version = version + + server = ThreadedEchoServer(context=server_context, chatty=False) + with server: + with client_context.wrap_socket( + socket.socket(), + server_hostname=hostname + ) as s: + s.connect((HOST, server.port)) + s.write(b'UNVERIFIEDCHAIN\n') + res = s.recv(1024) + self.assertEqual(res, b'\x02\n') + # TLS 1.3 sends the ticket after the handshake, so only + # get the session once data was received. + session = s.session + self.assertTrue(session.has_ticket) + with client_context.wrap_socket( + socket.socket(), + server_hostname=hostname, + session=session + ) as s: + s.connect((HOST, server.port)) + self.assertTrue(s.session_reused) + s.write(b'UNVERIFIEDCHAIN\n') + res = s.recv(1024) + self.assertEqual(res, b'\x01\n') + # The verified chain is not stored with the session at all. + s.write(b'VERIFIEDCHAIN\n') + res = s.recv(1024) + self.assertEqual(res, b'\x00\n') + + def test_internal_chain_server_no_client_cert(self): + client_context, server_context, hostname = testing_context() + server_context.verify_mode = ssl.CERT_OPTIONAL + + server = ThreadedEchoServer(context=server_context, chatty=False) + with server: + with client_context.wrap_socket( + socket.socket(), + server_hostname=hostname + ) as s: + s.connect((HOST, server.port)) + s.write(b'UNVERIFIEDCHAIN\n') + res = s.recv(1024) + self.assertEqual(res, b'\x00\n') + class TestSSLDebug(unittest.TestCase): @@ -5144,6 +5830,12 @@ def test_keylog_defaults(self): with self.assertRaises(TypeError): ctx.keylog_filename = 1 + ctx.keylog_filename = os_helper.TESTFN + with self.assertRaisesRegex(AttributeError, 'cannot be deleted'): + del ctx.keylog_filename + # a failed deletion does not change the value + self.assertEqual(ctx.keylog_filename, os_helper.TESTFN) + @requires_keylog def test_keylog_filename(self): self.addCleanup(os_helper.unlink, os_helper.TESTFN) @@ -5220,6 +5912,32 @@ def msg_cb(conn, direction, version, content_type, msg_type, data): with self.assertRaises(TypeError): client_context._msg_callback = object() + # the attribute of the underlying C type accepts only a callable + # and cannot be deleted + descr = _ssl._SSLContext.__dict__['_msg_callback'] + with self.assertRaises(TypeError): + descr.__set__(client_context, object()) + # a failed assignment does not change the value + self.assertIs(client_context._msg_callback, msg_cb) + with self.assertRaisesRegex(AttributeError, 'cannot be deleted'): + descr.__delete__(client_context) + # a failed deletion does not change the value + self.assertIs(client_context._msg_callback, msg_cb) + + def test_msg_callback_exception(self): + client_context, server_context, hostname = testing_context() + + def msg_cb(conn, direction, version, content_type, msg_type, data): + raise RuntimeError("msg_cb exception") + + client_context._msg_callback = msg_cb + server = ThreadedEchoServer(context=server_context, chatty=False) + with server: + with client_context.wrap_socket(socket.socket(), + server_hostname=hostname) as s: + with self.assertRaisesRegex(RuntimeError, "msg_cb exception"): + s.connect((HOST, server.port)) + def test_msg_callback_tls12(self): client_context, server_context, hostname = testing_context() client_context.maximum_version = ssl.TLSVersion.TLSv1_2 @@ -5306,7 +6024,11 @@ def __exit__(self, *args): self.listener.close() except OSError: pass - self.join() + timeout = support.SHORT_TIMEOUT + self.join(timeout=timeout) + if self.is_alive(): + raise AssertionError("failed to join the server thread " + f"in {timeout} seconds") self.wrap_error = None # avoid dangling references def start(self): @@ -5512,28 +6234,30 @@ def call_after_accept(conn_to_client): call_after_accept=call_after_accept, name="non_tls_http_RST_responder", timeout=timeout) - self.enterContext(server) # starts it & unittest.TestCase stops it. - # Redundant; call_after_accept sets SO_LINGER on the accepted conn. - set_socket_so_linger_on_with_zero_timeout(server.listener) - - connection = SynchronizedHTTPSConnection( - server.listener.getsockname()[0], - port=server.port, - context=ssl.create_default_context(), - timeout=timeout, - ) - # There are lots of reasons this raises as desired, long before this - # test was added. Sending the request requires a successful TLS wrapped - # socket; that fails if the connection is broken. It may seem pointless - # to test this. It serves as an illustration of something that we never - # want to happen... properly not happening. - with warnings_helper.check_no_resource_warning(self), \ - self.assertRaises(OSError): - connection.request("HEAD", "/test", headers={"Host": "localhost"}) - response = connection.getresponse() + with server: + # Redundant; call_after_accept sets SO_LINGER on the accepted conn. + set_socket_so_linger_on_with_zero_timeout(server.listener) + + connection = SynchronizedHTTPSConnection( + server.listener.getsockname()[0], + port=server.port, + context=ssl.create_default_context(), + timeout=timeout, + ) - server.join() + # There are lots of reasons this raises as desired, long before this + # test was added. Sending the request requires a successful TLS wrapped + # socket; that fails if the connection is broken. It may seem pointless + # to test this. It serves as an illustration of something that we never + # want to happen... properly not happening. + with warnings_helper.check_no_resource_warning(self), \ + self.assertRaises(OSError): + try: + connection.request("HEAD", "/test", headers={"Host": "localhost"}) + response = connection.getresponse() + finally: + connection.close() class TestEnumerations(unittest.TestCase): diff --git a/Lib/test/test_stable_abi_ctypes.py b/Lib/test/test_stable_abi_ctypes.py index 1e6f69d49e9..09ee2d53f98 100644 --- a/Lib/test/test_stable_abi_ctypes.py +++ b/Lib/test/test_stable_abi_ctypes.py @@ -45,6 +45,7 @@ def test_windows_feature_macros(self): SYMBOL_NAMES = ( + "PyABIInfo_Check", "PyAIter_Check", "PyArg_Parse", "PyArg_ParseTuple", @@ -133,6 +134,10 @@ def test_windows_feature_macros(self): "PyComplex_ImagAsDouble", "PyComplex_RealAsDouble", "PyComplex_Type", + "PyCriticalSection2_Begin", + "PyCriticalSection2_End", + "PyCriticalSection_Begin", + "PyCriticalSection_End", "PyDescr_NewClassMethod", "PyDescr_NewGetSet", "PyDescr_NewMember", @@ -164,6 +169,7 @@ def test_windows_feature_macros(self): "PyDict_MergeFromSeq2", "PyDict_New", "PyDict_Next", + "PyDict_SetDefaultRef", "PyDict_SetItem", "PyDict_SetItemString", "PyDict_Size", @@ -363,12 +369,18 @@ def test_windows_feature_macros(self): "PyImport_ImportModuleNoBlock", "PyImport_ReloadModule", "PyIndex_Check", + "PyInterpreterGuard_Close", + "PyInterpreterGuard_FromCurrent", + "PyInterpreterGuard_FromView", "PyInterpreterState_Clear", "PyInterpreterState_Delete", "PyInterpreterState_Get", "PyInterpreterState_GetDict", "PyInterpreterState_GetID", "PyInterpreterState_New", + "PyInterpreterView_Close", + "PyInterpreterView_FromCurrent", + "PyInterpreterView_FromMain", "PyIter_Check", "PyIter_Next", "PyIter_NextItem", @@ -389,6 +401,9 @@ def test_windows_feature_macros(self): "PyList_Sort", "PyList_Type", "PyLongRangeIter_Type", + "PyLongWriter_Create", + "PyLongWriter_Discard", + "PyLongWriter_Finish", "PyLong_AsDouble", "PyLong_AsInt", "PyLong_AsInt32", @@ -407,6 +422,8 @@ def test_windows_feature_macros(self): "PyLong_AsUnsignedLongLongMask", "PyLong_AsUnsignedLongMask", "PyLong_AsVoidPtr", + "PyLong_Export", + "PyLong_FreeExport", "PyLong_FromDouble", "PyLong_FromInt32", "PyLong_FromInt64", @@ -423,6 +440,7 @@ def test_windows_feature_macros(self): "PyLong_FromUnsignedNativeBytes", "PyLong_FromVoidPtr", "PyLong_GetInfo", + "PyLong_GetNativeLayout", "PyLong_Type", "PyMap_Type", "PyMapping_Check", @@ -468,8 +486,10 @@ def test_windows_feature_macros(self): "PyModule_AddStringConstant", "PyModule_AddType", "PyModule_Create2", + "PyModule_Exec", "PyModule_ExecDef", "PyModule_FromDefAndSpec2", + "PyModule_FromSlotsAndSpec", "PyModule_GetDef", "PyModule_GetDict", "PyModule_GetFilename", @@ -477,6 +497,10 @@ def test_windows_feature_macros(self): "PyModule_GetName", "PyModule_GetNameObject", "PyModule_GetState", + "PyModule_GetStateSize", + "PyModule_GetState_DuringGC", + "PyModule_GetToken", + "PyModule_GetToken_DuringGC", "PyModule_New", "PyModule_NewObject", "PyModule_SetDocString", @@ -538,6 +562,7 @@ def test_windows_feature_macros(self): "PyObject_AsWriteBuffer", "PyObject_Bytes", "PyObject_Call", + "PyObject_CallFinalizerFromDealloc", "PyObject_CallFunction", "PyObject_CallFunctionObjArgs", "PyObject_CallMethod", @@ -574,6 +599,7 @@ def test_windows_feature_macros(self): "PyObject_GetOptionalAttr", "PyObject_GetOptionalAttrString", "PyObject_GetTypeData", + "PyObject_GetTypeData_DuringGC", "PyObject_HasAttr", "PyObject_HasAttrString", "PyObject_HasAttrStringWithError", @@ -658,7 +684,11 @@ def test_windows_feature_macros(self): "PySys_AuditTuple", "PySys_FormatStderr", "PySys_FormatStdout", + "PySys_GetAttr", + "PySys_GetAttrString", "PySys_GetObject", + "PySys_GetOptionalAttr", + "PySys_GetOptionalAttrString", "PySys_GetXOptions", "PySys_HasWarnOptions", "PySys_ResetWarnOptions", @@ -671,12 +701,15 @@ def test_windows_feature_macros(self): "PyThreadState_Clear", "PyThreadState_Delete", "PyThreadState_DeleteCurrent", + "PyThreadState_Ensure", + "PyThreadState_EnsureFromView", "PyThreadState_Get", "PyThreadState_GetDict", "PyThreadState_GetFrame", "PyThreadState_GetID", "PyThreadState_GetInterpreter", "PyThreadState_New", + "PyThreadState_Release", "PyThreadState_SetAsyncExc", "PyThreadState_Swap", "PyThread_GetInfo", @@ -719,17 +752,23 @@ def test_windows_feature_macros(self): "PyType_Freeze", "PyType_FromMetaclass", "PyType_FromModuleAndSpec", + "PyType_FromSlots", "PyType_FromSpec", "PyType_FromSpecWithBases", "PyType_GenericAlloc", "PyType_GenericNew", "PyType_GetBaseByToken", + "PyType_GetBaseByToken_DuringGC", "PyType_GetFlags", "PyType_GetFullyQualifiedName", "PyType_GetModule", "PyType_GetModuleByDef", + "PyType_GetModuleByToken", + "PyType_GetModuleByToken_DuringGC", "PyType_GetModuleName", "PyType_GetModuleState", + "PyType_GetModuleState_DuringGC", + "PyType_GetModule_DuringGC", "PyType_GetName", "PyType_GetQualName", "PyType_GetSlot", @@ -890,6 +929,7 @@ def test_windows_feature_macros(self): "Py_GetRecursionLimit", "Py_GetVersion", "Py_HasFileSystemDefaultEncoding", + "Py_IS_TYPE", "Py_IncRef", "Py_Initialize", "Py_InitializeEx", @@ -909,6 +949,8 @@ def test_windows_feature_macros(self): "Py_REFCNT", "Py_ReprEnter", "Py_ReprLeave", + "Py_SET_SIZE", + "Py_SIZE", "Py_SetPath", "Py_SetProgramName", "Py_SetPythonHome", diff --git a/Lib/test/test_startfile.py b/Lib/test/test_startfile.py new file mode 100644 index 00000000000..8c642998625 --- /dev/null +++ b/Lib/test/test_startfile.py @@ -0,0 +1,45 @@ +# Ridiculously simple test of the os.startfile function for Windows. +# +# empty.vbs is an empty file (except for a comment), which does +# nothing when run with cscript or wscript. +# +# A possible improvement would be to have empty.vbs do something that +# we can detect here, to make sure that not only the os.startfile() +# call succeeded, but also the script actually has run. + +import unittest +from test import support +from test.support import os_helper +import os +import platform +import sys +from os import path + +startfile = support.get_attribute(os, 'startfile') + + +@unittest.skipIf(platform.win32_is_iot(), "starting files is not supported on Windows IoT Core or nanoserver") +class TestCase(unittest.TestCase): + def test_nonexisting(self): + self.assertRaises(OSError, startfile, "nonexisting.vbs") + + def test_empty(self): + # We need to make sure the child process starts in a directory + # we're not about to delete. If we're running under -j, that + # means the test harness provided directory isn't a safe option. + # See http://bugs.python.org/issue15526 for more details + with os_helper.change_cwd(path.dirname(sys.executable)): + empty = path.join(path.dirname(__file__), "empty.vbs") + startfile(empty) + startfile(empty, "open") + startfile(empty, cwd=path.dirname(sys.executable)) + + def test_python(self): + # Passing "-V" ensures that it closes quickly, though still not + # quickly enough that we can run in the test directory + cwd, name = path.split(sys.executable) + startfile(name, arguments="-V", cwd=cwd) + startfile(name, arguments="-V", cwd=cwd, show_cmd=0) + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_statistics.py b/Lib/test/test_statistics.py index e0b74432c94..677a87b51b9 100644 --- a/Lib/test/test_statistics.py +++ b/Lib/test/test_statistics.py @@ -2496,8 +2496,7 @@ def test_kde_random(self): data = [-2.1, -1.3, -0.4, 1.9, 5.1, 6.2, 7.8, 14.3, 15.1, 15.3, 15.8, 17.0] xarr = [x / 10 for x in range(-100, 250)] - # TODO: RUSTPYTHON - n originally 1_000_000 in CPython implementation but sorting is slow - n = 30_000 + n = 1_000_000 h = 1.75 dx = 0.1 @@ -2519,8 +2518,7 @@ def p_expected(x): F_hat = statistics.kde(data, h, kernel, cumulative=True) for x in xarr: - # TODO : RUSTPYTHON - abs_tol=0.0005 in CPython implementation but smaller `n` increases variance - self.assertTrue(math.isclose(p_observed(x), p_expected(x), abs_tol=0.005)) + self.assertTrue(math.isclose(p_observed(x), p_expected(x), abs_tol=0.0005)) # Test online updates to data diff --git a/Lib/test/test_str.py b/Lib/test/test_str.py index 4869c5ca9b0..996a74d23de 100644 --- a/Lib/test/test_str.py +++ b/Lib/test/test_str.py @@ -454,6 +454,13 @@ def test_maketrans_translate(self): self.assertEqual("[a\xe9]".translate(str.maketrans({'a': '<\u20ac>'})), "[<\u20ac>\xe9]") + # with frozendict + tbl = self.type2test.maketrans(frozendict({'s': 'S', 'T': 't'})) + self.assertEqual(tbl, {ord('s'): 'S', ord('T'): 't'}) + self.assertEqual('sTan'.translate(tbl), 'Stan') + tbl = self.type2test.maketrans(frozendict({'a': None, 'b': ''})) + self.checkequalnofix('c', 'abababc', 'translate', tbl) + # invalid Unicode characters invalid_char = 0x10ffff+1 for before in "a\xe9\u20ac\U0010ffff": @@ -600,6 +607,21 @@ def test_replace_id(self): text = 'abc def' self.assertIs(text.replace(pattern, pattern), text) + @support.nomemtest + def test_replace_oom(self): + # https://github.com/python/cpython/issues/152228 + s1 = "轘" * 4 + s2 = "&" + s3 = "&" + assertion = self.assertRaises(MemoryError) + _testcapi.set_nomemory(0, 0) + try: + # No allocations made in the test itself: + with assertion: + s1.replace(s2, s3) # this line used to crash before + finally: + _testcapi.remove_mem_hooks() + def test_repeat_id_preserving(self): a = '123abc1@' b = '456zyx-+' @@ -1070,7 +1092,6 @@ def test_issue18183(self): '\U00100000'.ljust(3, '\U00010000') '\U00100000'.rjust(3, '\U00010000') - @unittest.expectedFailure # TODO: RUSTPYTHON; '{0.}'.format() raises ValueError instead of IndexError def test_format(self): self.assertEqual(''.format(), '') self.assertEqual('a'.format(), 'a') @@ -1499,7 +1520,6 @@ def __format__(self, spec): self.assertEqual('{:{f}}{g}{}'.format(1, 3, g='g', f=2), ' 1g3') self.assertEqual('{f:{}}{}{g}'.format(2, 4, f=1, g='g'), ' 14g') - @unittest.expectedFailure # TODO: RUSTPYTHON; %c error wording uses bare class name; CPython uses fully qualified module.qualname (e.g. test.test_str.PseudoFloat) def test_formatting(self): string_tests.StringLikeTest.test_formatting(self) # Testing Unicode formatting strings... @@ -1580,17 +1600,40 @@ def __int__(self): self.assertEqual('%X' % letter_m, '6D') self.assertEqual('%o' % letter_m, '155') self.assertEqual('%c' % letter_m, 'm') - self.assertRaisesRegex(TypeError, '%x format: an integer is required, not float', operator.mod, '%x', 3.14) - self.assertRaisesRegex(TypeError, '%X format: an integer is required, not float', operator.mod, '%X', 2.11) - self.assertRaisesRegex(TypeError, '%o format: an integer is required, not float', operator.mod, '%o', 1.79) - self.assertRaisesRegex(TypeError, '%x format: an integer is required, not PseudoFloat', operator.mod, '%x', pi) - self.assertRaisesRegex(TypeError, '%x format: an integer is required, not complex', operator.mod, '%x', 3j) - self.assertRaisesRegex(TypeError, '%X format: an integer is required, not complex', operator.mod, '%X', 2j) - self.assertRaisesRegex(TypeError, '%o format: an integer is required, not complex', operator.mod, '%o', 1j) - self.assertRaisesRegex(TypeError, '%u format: a real number is required, not complex', operator.mod, '%u', 3j) - self.assertRaisesRegex(TypeError, '%i format: a real number is required, not complex', operator.mod, '%i', 2j) - self.assertRaisesRegex(TypeError, '%d format: a real number is required, not complex', operator.mod, '%d', 1j) - self.assertRaisesRegex(TypeError, r'%c requires an int or a unicode character, not .*\.PseudoFloat', operator.mod, '%c', pi) + with self.assertRaisesRegex(TypeError, + 'format argument: %x requires an integer, not float'): + '%x' % 3.14 + with self.assertRaisesRegex(TypeError, + 'format argument: %X requires an integer, not float'): + '%X' % 2.11 + with self.assertRaisesRegex(TypeError, + 'format argument: %o requires an integer, not float'): + '%o' % 1.79 + with self.assertRaisesRegex(TypeError, + r'format argument: %x requires an integer, not .*\.PseudoFloat'): + '%x' % pi + with self.assertRaisesRegex(TypeError, + 'format argument: %x requires an integer, not complex'): + '%x' % 3j + with self.assertRaisesRegex(TypeError, + 'format argument: %X requires an integer, not complex'): + '%X' % 2j + with self.assertRaisesRegex(TypeError, + 'format argument: %o requires an integer, not complex'): + '%o' % 1j + with self.assertRaisesRegex(TypeError, + 'format argument: %u requires a real number, not complex'): + '%u' % 3j + with self.assertRaisesRegex(TypeError, + 'format argument: %i requires a real number, not complex'): + '%i' % 2j + with self.assertRaisesRegex(TypeError, + 'format argument: %d requires a real number, not complex'): + '%d' % 1j + with self.assertRaisesRegex(TypeError, + r'format argument: %c requires an integer or a unicode character, ' + r'not .*\.PseudoFloat'): + '%c' % pi class RaisingNumber: def __int__(self): @@ -2611,7 +2654,6 @@ def test_free_after_iterating(self): if not support.Py_GIL_DISABLED: support.check_free_after_iterating(self, reversed, str) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: 22 != 10 : _PythonRunResult(rc=22, out=b'', err=b'') def test_check_encoding_errors(self): # bpo-37388: str(bytes) and str.decode() must check encoding and errors # arguments in dev mode @@ -2672,7 +2714,6 @@ def test_check_encoding_errors(self): proc = assert_python_failure('-X', 'dev', '-c', code) self.assertEqual(proc.rc, 10, proc) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: "str expected at most 3 arguments, got 4" does not match "expected at most 3 arguments, got 4" def test_str_invalid_call(self): # too many args with self.assertRaisesRegex(TypeError, r"str expected at most 3 arguments, got 4"): diff --git a/Lib/test/test_string/_support.py b/Lib/test/test_string/_support.py index cfead782b7d..e1d7f6f6500 100644 --- a/Lib/test/test_string/_support.py +++ b/Lib/test/test_string/_support.py @@ -1,4 +1,3 @@ -import unittest from string.templatelib import Interpolation diff --git a/Lib/test/test_strptime.py b/Lib/test/test_strptime.py index e277e7f4ef7..5ac28870455 100644 --- a/Lib/test/test_strptime.py +++ b/Lib/test/test_strptime.py @@ -8,7 +8,6 @@ import platform import sys from test import support -from test.support import warnings_helper from test.support import skip_if_buggy_ucrt_strfptime, run_with_locales from datetime import date as datetime_date @@ -286,7 +285,7 @@ def test_ValueError(self): def test_strptime_exception_context(self): # check that this doesn't chain exceptions needlessly (see #17572) with self.assertRaises(ValueError) as e: - _strptime._strptime_time('', '%D') + _strptime._strptime_time('', '%!') self.assertTrue(e.exception.__suppress_context__) # additional check for stray % branch with self.assertRaises(ValueError) as e: @@ -406,37 +405,50 @@ def test_offset(self): (*_, offset), _, offset_fraction = _strptime._strptime("-013030.000001", "%z") self.assertEqual(offset, -(one_hour + half_hour + half_minute)) self.assertEqual(offset_fraction, -1) - (*_, offset), _, offset_fraction = _strptime._strptime("+01:00", "%z") - self.assertEqual(offset, one_hour) - self.assertEqual(offset_fraction, 0) - (*_, offset), _, offset_fraction = _strptime._strptime("-01:30", "%z") - self.assertEqual(offset, -(one_hour + half_hour)) - self.assertEqual(offset_fraction, 0) - (*_, offset), _, offset_fraction = _strptime._strptime("-01:30:30", "%z") - self.assertEqual(offset, -(one_hour + half_hour + half_minute)) - self.assertEqual(offset_fraction, 0) - (*_, offset), _, offset_fraction = _strptime._strptime("-01:30:30.000001", "%z") - self.assertEqual(offset, -(one_hour + half_hour + half_minute)) - self.assertEqual(offset_fraction, -1) - (*_, offset), _, offset_fraction = _strptime._strptime("+01:30:30.001", "%z") - self.assertEqual(offset, one_hour + half_hour + half_minute) - self.assertEqual(offset_fraction, 1000) - (*_, offset), _, offset_fraction = _strptime._strptime("Z", "%z") - self.assertEqual(offset, 0) - self.assertEqual(offset_fraction, 0) + + cases = [ + ("+01:00", one_hour, 0), + ("-01:30", -(one_hour + half_hour), 0), + ("-01:30:30", -(one_hour + half_hour + half_minute), 0), + ("-01:30:30.000001", -(one_hour + half_hour + half_minute), -1), + ("+01:30:30.001", +(one_hour + half_hour + half_minute), 1000), + ("Z", 0, 0), + ] + for directive in ("%z", "%:z"): + for offset_str, expected_offset, expected_fraction in cases: + with self.subTest(offset_str=offset_str, directive=directive): + (*_, offset), _, offset_fraction = _strptime._strptime( + offset_str, directive + ) + self.assertEqual(offset, expected_offset) + self.assertEqual(offset_fraction, expected_fraction) def test_bad_offset(self): - with self.assertRaises(ValueError): - _strptime._strptime("-01:30:30.", "%z") - with self.assertRaises(ValueError): - _strptime._strptime("-0130:30", "%z") - with self.assertRaises(ValueError): - _strptime._strptime("-01:30:30.1234567", "%z") - with self.assertRaises(ValueError): - _strptime._strptime("-01:30:30:123456", "%z") + error_cases_any_z = [ + "-01:30:30.", # Decimal point not followed with digits + "-01:30:30.1234567", # Too many digits after decimal point + "-01:30:30:123456", # Colon as decimal separator + "-0130:30", # Incorrect use of colons + ] + for directive in ("%z", "%:z"): + for timestr in error_cases_any_z: + with self.subTest(timestr=timestr, directive=directive): + with self.assertRaises(ValueError): + _strptime._strptime(timestr, directive) + + required_colons_cases = ["-013030", "+0130", "-01:3030.123456"] + for timestr in required_colons_cases: + with self.subTest(timestr=timestr): + with self.assertRaises(ValueError): + _strptime._strptime(timestr, "%:z") + with self.assertRaises(ValueError) as err: _strptime._strptime("-01:3030", "%z") self.assertEqual("Inconsistent use of : in -01:3030", str(err.exception)) + with self.assertRaises(ValueError) as err: + _strptime._strptime("-01:3030", "%:z") + self.assertEqual("Missing colon in %:z before '30', got '-01:3030'", + str(err.exception)) @skip_if_buggy_ucrt_strfptime def test_timezone(self): @@ -626,15 +638,49 @@ def test_escaping(self): need_escaping = r".^$*+?{}\[]|)(" self.assertTrue(_strptime._strptime_time(need_escaping, need_escaping)) - @warnings_helper.ignore_warnings(category=DeprecationWarning) # gh-70647 def test_feb29_on_leap_year_without_year(self): - time.strptime("Feb 29", "%b %d") + with self.assertRaises(ValueError): + time.strptime("Feb 29", "%b %d") + with self.assertRaises(ValueError): + time.strptime("Mar 1", "%b %d") + + def test_strptime_F_format(self): + test_date = "2025-10-26" + self.assertEqual( + time.strptime(test_date, "%F"), + time.strptime(test_date, "%Y-%m-%d") + ) + + def test_strptime_T_format(self): + test_time = "15:00:00" + self.assertEqual( + time.strptime(test_time, "%T"), + time.strptime(test_time, "%H:%M:%S") + ) + + def test_strptime_D_format(self): + test_date = "11/28/25" + self.assertEqual( + time.strptime(test_date, "%D"), + time.strptime(test_date, "%m/%d/%y") + ) - @warnings_helper.ignore_warnings(category=DeprecationWarning) # gh-70647 - def test_mar1_comes_after_feb29_even_when_omitting_the_year(self): - self.assertLess( - time.strptime("Feb 29", "%b %d"), - time.strptime("Mar 1", "%b %d")) + def test_strptime_n_and_t_format(self): + format_directives = ('%n', '%t', '%n%t', '%t%n') + whitespaces = ('', ' ', '\t', '\r', '\v', '\n', '\f') + for fd in format_directives: + for ws in (*whitespaces, ''.join(whitespaces)): + with self.subTest(format_directive=fd, whitespace=ws): + self.assertEqual( + time.strptime( + f"2026{ws}02{ws}03", + f"%Y{fd}%m{fd}%d", + ), + time.strptime( + f'2026-02-03', + "%Y-%m-%d", + ), + ) class Strptime12AMPMTests(unittest.TestCase): """Test a _strptime regression in '%I %p' at 12 noon (12 PM)""" diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py index e18bad9c990..934012784de 100644 --- a/Lib/test/test_struct.py +++ b/Lib/test/test_struct.py @@ -503,9 +503,9 @@ def _test_pack_into(self, pack_into): pack_into(writable_buf, None, test_string) with self.assertRaises(TypeError): pack_into(writable_buf, 0.0, test_string) - with self.assertRaises((IndexError, OverflowError)): + with self.assertRaises(OverflowError): pack_into(writable_buf, 2**1000, test_string) - with self.assertRaises((IndexError, OverflowError)): + with self.assertRaises(OverflowError): pack_into(writable_buf, -2**1000, test_string) def test_pack_into(self): @@ -616,27 +616,36 @@ def test_Struct_reinitialization(self): # Struct instance. This test can be used to detect the leak # when running with regrtest -L. s = struct.Struct('>h') - s.__init__('>hh') + msg = 'Re-initialization .* will not work' + with self.assertWarnsRegex(FutureWarning, msg): + s.__init__('>hh') self.assertEqual(s.format, '>hh') packed = b'\x00\x01\x00\x02' self.assertEqual(s.pack(1, 2), packed) self.assertEqual(s.unpack(packed), (1, 2)) - with self.assertRaises(UnicodeEncodeError): - s.__init__('\udc00') + s.__init__('>hh') # same format self.assertEqual(s.format, '>hh') self.assertEqual(s.pack(1, 2), packed) self.assertEqual(s.unpack(packed), (1, 2)) - with self.assertRaises(struct.error): - s.__init__('$') + with self.assertWarnsRegex(FutureWarning, msg): + with self.assertRaises(ValueError): + s.__init__('\udc00') + self.assertEqual(s.format, '>hh') + self.assertEqual(s.pack(1, 2), packed) + self.assertEqual(s.unpack(packed), (1, 2)) + + with self.assertWarnsRegex(FutureWarning, msg): + with self.assertRaises(struct.error): + s.__init__('$') self.assertEqual(s.format, '>hh') self.assertEqual(s.pack(1, 2), packed) self.assertEqual(s.unpack(packed), (1, 2)) def check_sizeof(self, format_str, number_of_codes): # The size of 'PyStructObject' - totalsize = support.calcobjsize('2n3P') + totalsize = support.calcobjsize('2n3P?0P') # The size taken up by the 'formatcode' dynamic array totalsize += struct.calcsize('P3n0P') * (number_of_codes + 1) support.check_sizeof(self, struct.Struct(format_str), totalsize) @@ -834,15 +843,160 @@ def test_error_propagation(fmt_str): test_error_propagation('N') test_error_propagation('n') - def test_struct_subclass_instantiation(self): + def test_custom_struct_init(self): # Regression test for https://github.com/python/cpython/issues/112358 class MyStruct(struct.Struct): - def __init__(self): + def __init__(self, *args, **kwargs): super().__init__('>h') + my_struct = MyStruct('>h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + my_struct = MyStruct(format='>h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + + warnmsg = r"Different format arguments for __new__\(\) and __init__\(\) methods of Struct" + with self.assertWarnsRegex(FutureWarning, warnmsg): + my_struct = MyStruct('h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + + warnmsg = r"Struct\(\) takes at most 1 argument \(2 given\)" + with self.assertWarnsRegex(DeprecationWarning, warnmsg): + my_struct = MyStruct('>h', 42) + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg): + my_struct = MyStruct('>h', arg=42) + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg): + my_struct = MyStruct('>h', format=42) + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg): + my_struct = MyStruct(format='>h', arg=42) + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + + warnmsg = r"Invalid 'format' argument for Struct\.__new__\(\): " + with self.assertWarnsRegex(DeprecationWarning, warnmsg + '.*must be'): + my_struct = MyStruct(42) + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg + '.*must be'): + my_struct = MyStruct(format=42) + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg + 'bad char'): + my_struct = MyStruct('$') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg + 'bad char'): + my_struct = MyStruct(format='$') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg + "non-ASCII"): + my_struct = MyStruct('\udc00') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertWarnsRegex(DeprecationWarning, warnmsg + "non-ASCII"): + my_struct = MyStruct(format='\udc00') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + + def test_custom_struct_new(self): + # New way, no warnings: + class MyStruct(struct.Struct): + def __new__(cls, *args, **kwargs): + return super().__new__(cls, '>h') + + for format in '>h', 'h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + my_struct = MyStruct(format='h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') my_struct = MyStruct() + self.assertEqual(my_struct.format, '>h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + my_struct = MyStruct('h') self.assertEqual(my_struct.pack(12345), b'\x30\x39') + def test_custom_struct_new_and_init(self): + # New way, no warnings: + class MyStruct(struct.Struct): + def __new__(cls, newargs, initargs): + return super().__new__(cls, *newargs) + def __init__(self, newargs, initargs): + if initargs is not None: + super().__init__(*initargs) + + my_struct = MyStruct(('>h',), ('>h',)) + self.assertEqual(my_struct.format, '>h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertRaises(TypeError): + MyStruct((), ()) + with self.assertRaises(TypeError): + MyStruct(('>h',), ()) + with self.assertRaises(TypeError): + MyStruct((), ('>h',)) + with self.assertRaises(TypeError): + MyStruct((42,), ('>h',)) + with self.assertWarns(FutureWarning): + with self.assertRaises(TypeError): + MyStruct(('>h',), (42,)) + with self.assertRaises(struct.error): + MyStruct(('$',), ('>h',)) + with self.assertWarns(FutureWarning): + with self.assertRaises(struct.error): + MyStruct(('>h',), ('$',)) + with self.assertRaises(ValueError): + MyStruct(('\udc00',), ('>h',)) + with self.assertRaises(ValueError): + MyStruct((b'\xa4',), ('>h',)) + with self.assertWarns(FutureWarning): + with self.assertRaises(ValueError): + MyStruct(('>h',), ('\udc00',)) + with self.assertWarns(FutureWarning): + with self.assertRaises(ValueError): + MyStruct(('>h',), (b'\xa4',)) + with self.assertWarns(FutureWarning): + my_struct = MyStruct(('>h',), ('h') + self.assertEqual(my_struct.format, '>h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + my_struct = MyStruct(format='>h') + self.assertEqual(my_struct.format, '>h') + self.assertEqual(my_struct.pack(12345), b'\x30\x39') + with self.assertRaises(TypeError): + MyStruct() + with self.assertRaises(TypeError): + MyStruct(42) + with self.assertRaises(struct.error): + MyStruct('$') + with self.assertRaises(ValueError): + MyStruct('\udc00') + with self.assertRaises(ValueError): + MyStruct(b'\xa4') + with self.assertRaises(TypeError): + MyStruct('>h', 42) + with self.assertRaises(TypeError): + MyStruct('>h', arg=42) + with self.assertRaises(TypeError): + MyStruct(arg=42) + with self.assertRaises(TypeError): + MyStruct('>h', format='>h') + def test_repr(self): s = struct.Struct('=i2H') self.assertEqual(repr(s), f'Struct({s.format!r})') @@ -851,7 +1005,11 @@ def test_c_complex_round_trip(self): values = [complex(*_) for _ in combinations([1, -1, 0.0, -0.0, 2, -3, INF, -INF, NAN], 2)] for z in values: - for f in ['F', 'D', '>F', '>D', 'F', '>D', '>Zf', '>Zd', + ':2: EncodingWarning: ") @@ -2415,6 +2451,16 @@ def test_CalledProcessError_str_non_zero(self): error_string = str(err) self.assertIn("non-zero exit status 2.", error_string) + # returncode which is not an integer, which happens for example when + # Popen is mocked: str() must not fail + for returncode in (None, "2", 2.5, [2]): + with self.subTest(returncode=returncode): + err = subprocess.CalledProcessError(returncode, "fake cmd") + self.assertEqual( + str(err), + f"Command 'fake cmd' returned non-zero " + f"exit status {returncode}.") + def test_preexec(self): # DISCLAIMER: Setting environment variables is *not* a good use # of a preexec_fn. This is merely a test. @@ -4139,5 +4185,148 @@ def test_broken_pipe_cleanup(self): self.assertTrue(proc.stdin.closed) + +class FastWaitTestCase(BaseTestCase): + """Tests for efficient (pidfd_open() + poll() / kqueue()) process + waiting in subprocess.Popen.wait(). + """ + CAN_USE_PIDFD_OPEN = subprocess._CAN_USE_PIDFD_OPEN + CAN_USE_KQUEUE = subprocess._CAN_USE_KQUEUE + COMMAND = [sys.executable, "-c", "import time; time.sleep(0.3)"] + WAIT_TIMEOUT = 0.0001 # 0.1 ms + + def assert_fast_waitpid_error(self, patch_point): + # Emulate a case where pidfd_open() or kqueue() fails. + # Busy-poll wait should be used as fallback. + exc = OSError(errno.EMFILE, os.strerror(errno.EMFILE)) + with mock.patch(patch_point, side_effect=exc) as m: + p = subprocess.Popen(self.COMMAND) + with self.assertRaises(subprocess.TimeoutExpired): + p.wait(self.WAIT_TIMEOUT) + self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0) + self.assertTrue(m.called) + + @unittest.skipIf(not CAN_USE_PIDFD_OPEN, reason="needs pidfd_open()") + def test_wait_pidfd_open_error(self): + self.assert_fast_waitpid_error("os.pidfd_open") + + @unittest.skipIf(not CAN_USE_KQUEUE, reason="needs kqueue() for proc") + def test_wait_kqueue_error(self): + self.assert_fast_waitpid_error("select.kqueue") + + @unittest.skipIf(not CAN_USE_KQUEUE, reason="needs kqueue() for proc") + def test_kqueue_control_error(self): + # Emulate a case where kqueue.control() fails. Busy-poll wait + # should be used as fallback. + p = subprocess.Popen(self.COMMAND) + kq_mock = mock.Mock() + kq_mock.control.side_effect = OSError( + errno.EPERM, os.strerror(errno.EPERM) + ) + kq_mock.close = mock.Mock() + + with mock.patch("select.kqueue", return_value=kq_mock) as m: + with self.assertRaises(subprocess.TimeoutExpired): + p.wait(self.WAIT_TIMEOUT) + self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0) + self.assertTrue(m.called) + + def assert_wait_race_condition(self, patch_target, real_func): + # Call pidfd_open() / kqueue(), then terminate the process. + # Make sure that the wait call (poll() / kqueue.control()) + # still works for a terminated PID. + p = subprocess.Popen(self.COMMAND) + + def wrapper(*args, **kwargs): + ret = real_func(*args, **kwargs) + try: + os.kill(p.pid, signal.SIGTERM) + os.waitpid(p.pid, 0) + except OSError: + pass + return ret + + with mock.patch(patch_target, side_effect=wrapper) as m: + status = p.wait(timeout=support.SHORT_TIMEOUT) + self.assertTrue(m.called) + self.assertEqual(status, 0) + + @unittest.skipIf(not CAN_USE_PIDFD_OPEN, reason="needs pidfd_open()") + def test_pidfd_open_race(self): + self.assert_wait_race_condition("os.pidfd_open", os.pidfd_open) + + @unittest.skipIf(not CAN_USE_KQUEUE, reason="needs kqueue() for proc") + def test_kqueue_race(self): + self.assert_wait_race_condition("select.kqueue", select.kqueue) + + def assert_notification_without_immediate_reap(self, patch_target): + # Verify fallback to busy polling when poll() / kqueue() + # succeeds, but waitpid(pid, WNOHANG) returns (0, 0). + def waitpid_wrapper(pid, flags): + nonlocal ncalls + ncalls += 1 + if ncalls == 1: + return (0, 0) + return real_waitpid(pid, flags) + + ncalls = 0 + real_waitpid = os.waitpid + with mock.patch.object(subprocess.Popen, patch_target, return_value=True) as m1: + with mock.patch("os.waitpid", side_effect=waitpid_wrapper) as m2: + p = subprocess.Popen(self.COMMAND) + with self.assertRaises(subprocess.TimeoutExpired): + p.wait(self.WAIT_TIMEOUT) + self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0) + self.assertTrue(m1.called) + self.assertTrue(m2.called) + + @unittest.skipIf(not CAN_USE_PIDFD_OPEN, reason="needs pidfd_open()") + def test_pidfd_open_notification_without_immediate_reap(self): + self.assert_notification_without_immediate_reap("_wait_pidfd") + + @unittest.skipIf(not CAN_USE_KQUEUE, reason="needs kqueue() for proc") + def test_kqueue_notification_without_immediate_reap(self): + self.assert_notification_without_immediate_reap("_wait_kqueue") + + @unittest.skipUnless( + CAN_USE_PIDFD_OPEN or CAN_USE_KQUEUE, + "fast wait mechanism not available" + ) + def test_fast_path_avoid_busy_loop(self): + # assert that the busy loop is not called as long as the fast + # wait is available + with mock.patch('time.sleep') as m: + p = subprocess.Popen(self.COMMAND) + with self.assertRaises(subprocess.TimeoutExpired): + p.wait(self.WAIT_TIMEOUT) + self.assertEqual(p.wait(timeout=support.LONG_TIMEOUT), 0) + self.assertFalse(m.called) + + @unittest.skipIf(mswindows, "requires the POSIX wait implementation") + def test_wait_huge_timeout(self): + # gh-154836: very large timeout values used to overflow the C + # timestamp conversion in poll() / kqueue.control() and raise + # OverflowError / TypeError. + for timeout in (10**10, sys.maxsize, float('inf')): + with self.subTest(timeout=timeout): + p = subprocess.Popen(ZERO_RETURN_CMD) + self.assertEqual(p.wait(timeout=timeout), 0) + + @unittest.skipIf(mswindows, "requires the POSIX wait implementation") + def test_run_huge_timeout(self): + # gh-154836: same as test_wait_huge_timeout, via the + # subprocess.run() / communicate() code path. + cp = subprocess.run(ZERO_RETURN_CMD, timeout=1e10) + self.assertEqual(cp.returncode, 0) + + @unittest.skipIf(mswindows, "requires the POSIX wait implementation") + def test_wait_slices_do_not_expire_early(self): + # A clamped wait slice must not raise TimeoutExpired before the + # real deadline: with a tiny slice limit, a process that + # outlives many slices must still be waited for successfully. + with mock.patch.object(subprocess, "_MAXIMUM_WAIT_TIMEOUT", 0.01): + p = subprocess.Popen(self.COMMAND) # sleeps 0.3s + self.assertEqual(p.wait(timeout=support.SHORT_TIMEOUT), 0) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py index 5885ab238ae..ef9e89fa157 100644 --- a/Lib/test/test_support.py +++ b/Lib/test/test_support.py @@ -1,6 +1,8 @@ import contextlib import errno import importlib +import itertools +import inspect import io import logging import os @@ -18,6 +20,7 @@ from test import support from test.support import isolation +from test.support import hashlib_helper from test.support import import_helper from test.support import os_helper from test.support import script_helper @@ -94,9 +97,15 @@ def test_get_attribute(self): self.test_get_attribute) self.assertRaises(unittest.SkipTest, support.get_attribute, self, "foo") - @unittest.skip("failing buildbots") + @unittest.skipIf(support.is_android or support.is_apple_mobile, + 'Mobile platforms redirect stdout to system log') def test_get_original_stdout(self): - self.assertEqual(support.get_original_stdout(), sys.stdout) + if isinstance(sys.stdout, io.StringIO): + # gh-55258: When --junit-xml is used, stdout is a StringIO: + # use sys.__stdout__ in this case. + self.assertEqual(support.get_original_stdout(), sys.__stdout__) + else: + self.assertEqual(support.get_original_stdout(), sys.stdout) def test_unload(self): import sched # noqa: F401 @@ -483,6 +492,7 @@ def test_check__all__(self): self.assertRaises(AssertionError, support.check__all__, self, unittest) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @unittest.skipUnless(hasattr(os, 'waitpid') and hasattr(os, 'WNOHANG'), 'need os.waitpid() and os.WNOHANG') @support.requires_fork() @@ -675,7 +685,6 @@ def test_recursive(depth, limit): """) script_helper.assert_python_ok("-c", code) - @unittest.skip("TODO: RUSTPYTHON; - causes segfault in debug builds") @support.skip_if_unlimited_stack_size def test_recursion(self): # Test infinite_recursion() and get_recursion_available() functions. @@ -811,6 +820,10 @@ def test_linked_to_musl(self): for v in linked: self.assertIsInstance(v, int) + def test_built_with_c_assertions(self): + # Check that calling the function doesn't raise an exception + result = support.built_with_c_assertions() + self.assertIsInstance(result, bool) # XXX -follows a list of untested API # make_legacy_pyc @@ -834,6 +847,239 @@ def test_linked_to_musl(self): # SuppressCrashReport +@hashlib_helper.requires_builtin_hashes() +class TestHashlibSupport(unittest.TestCase): + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.hashlib = import_helper.import_module("hashlib") + cls.hmac = import_helper.import_module("hmac") + + # All C extension modules must be present since blocking + # the built-in implementation while allowing OpenSSL or vice-versa + # may result in failures depending on the exposed built-in hashes. + cls._hashlib = import_helper.import_module("_hashlib") + cls._hmac = import_helper.import_module("_hmac") + cls._md5 = import_helper.import_module("_md5") + + def skip_if_fips_mode(self): + if self._hashlib.get_fips_mode(): + self.skipTest("disabled in FIPS mode") + + def skip_if_not_fips_mode(self): + if not self._hashlib.get_fips_mode(): + self.skipTest("requires FIPS mode") + + def check_context(self, disabled=True): + if disabled: + return self.assertRaises(ValueError) + return contextlib.nullcontext() + + def try_import_attribute(self, fullname, default=None): + if fullname is None: + return default + assert fullname.count('.') == 1, fullname + module_name, attribute = fullname.split('.', maxsplit=1) + try: + module = importlib.import_module(module_name) + except ImportError: + return default + try: + return getattr(module, attribute, default) + except TypeError: + return default + + def fetch_hash_function(self, name, implementation): + info = hashlib_helper.get_hash_func_info(name) + match hashlib_helper.Implementation(implementation): + case hashlib_helper.Implementation.hashlib: + method_name = info.hashlib.member_name + assert isinstance(method_name, str), method_name + return getattr(self.hashlib, method_name) + case hashlib_helper.Implementation.openssl: + method_name = info.openssl.member_name + assert isinstance(method_name, str | None), method_name + return getattr(self._hashlib, method_name or "", None) + fullname = info[implementation].fullname + return self.try_import_attribute(fullname) + + def fetch_hmac_function(self, name): + target = hashlib_helper.get_hmac_item_info(name) + return target.import_member() + + def check_openssl_hash(self, name, *, disabled=True): + """Check that OpenSSL HASH interface is enabled/disabled.""" + with self.check_context(disabled): + _ = self._hashlib.new(name) + if do_hash := self.fetch_hash_function(name, "openssl"): + self.assertStartsWith(do_hash.__name__, 'openssl_') + with self.check_context(disabled): + _ = do_hash(b"") + + def check_openssl_hmac(self, name, *, disabled=True): + """Check that OpenSSL HMAC interface is enabled/disabled.""" + if name in hashlib_helper.NON_HMAC_DIGEST_NAMES: + # HMAC-BLAKE and HMAC-SHAKE raise a ValueError as they are not + # supported at all (they do not make any sense in practice). + with self.assertRaises(ValueError): + self._hashlib.hmac_digest(b"", b"", name) + else: + with self.check_context(disabled): + _ = self._hashlib.hmac_digest(b"", b"", name) + # OpenSSL does not provide one-shot explicit HMAC functions + + def check_builtin_hash(self, name, *, disabled=True): + """Check that HACL* HASH interface is enabled/disabled.""" + if do_hash := self.fetch_hash_function(name, "builtin"): + self.assertEqual(do_hash.__name__, name) + with self.check_context(disabled): + _ = do_hash(b"") + + def check_builtin_hmac(self, name, *, disabled=True): + """Check that HACL* HMAC interface is enabled/disabled.""" + if name in hashlib_helper.NON_HMAC_DIGEST_NAMES: + # HMAC-BLAKE and HMAC-SHAKE raise a ValueError as they are not + # supported at all (they do not make any sense in practice). + with self.assertRaises(ValueError): + self._hmac.compute_digest(b"", b"", name) + else: + with self.check_context(disabled): + _ = self._hmac.compute_digest(b"", b"", name) + + with self.check_context(disabled): + _ = self._hmac.new(b"", b"", name) + + if do_hmac := self.fetch_hmac_function(name): + self.assertStartsWith(do_hmac.__name__, 'compute_') + with self.check_context(disabled): + _ = do_hmac(b"", b"") + else: + self.assertIn(name, hashlib_helper.NON_HMAC_DIGEST_NAMES) + + @support.subTests( + ('name', 'allow_openssl', 'allow_builtin'), + itertools.product( + hashlib_helper.CANONICAL_DIGEST_NAMES, + [True, False], + [True, False], + ) + ) + def test_disable_hash(self, name, allow_openssl, allow_builtin): + # In FIPS mode, the function may be available but would still need + # to raise a ValueError, so we will test the helper separately. + self.skip_if_fips_mode() + flags = dict(allow_openssl=allow_openssl, allow_builtin=allow_builtin) + is_fully_disabled = not allow_builtin and not allow_openssl + + with hashlib_helper.block_algorithm(name, **flags): + # OpenSSL's blake2s and blake2b are unknown names + # when only the OpenSSL interface is available. + if allow_openssl and not allow_builtin: + aliases = {'blake2s': 'blake2s256', 'blake2b': 'blake2b512'} + name_for_hashlib_new = aliases.get(name, name) + else: + name_for_hashlib_new = name + + with self.check_context(is_fully_disabled): + _ = self.hashlib.new(name_for_hashlib_new) + + # Since _hashlib is present, explicit blake2b/blake2s constructors + # use the built-in implementation, while others (since we are not + # in FIPS mode and since _hashlib exists) use the OpenSSL function. + with self.check_context(is_fully_disabled): + _ = getattr(self.hashlib, name)() + + self.check_openssl_hash(name, disabled=not allow_openssl) + self.check_builtin_hash(name, disabled=not allow_builtin) + + if name not in hashlib_helper.NON_HMAC_DIGEST_NAMES: + with self.check_context(is_fully_disabled): + _ = self.hmac.new(b"", b"", name) + with self.check_context(is_fully_disabled): + _ = self.hmac.HMAC(b"", b"", name) + with self.check_context(is_fully_disabled): + _ = self.hmac.digest(b"", b"", name) + + self.check_openssl_hmac(name, disabled=not allow_openssl) + self.check_builtin_hmac(name, disabled=not allow_builtin) + + @hashlib_helper.block_algorithm("md5") + def test_disable_hash_md5_in_fips_mode(self): + self.skip_if_not_fips_mode() + + self.assertRaises(ValueError, self.hashlib.new, "md5") + self.assertRaises(ValueError, self._hashlib.new, "md5") + self.assertRaises(ValueError, self.hashlib.md5) + self.assertRaises(ValueError, self._hashlib.openssl_md5) + + kwargs = dict(usedforsecurity=True) + self.assertRaises(ValueError, self.hashlib.new, "md5", **kwargs) + self.assertRaises(ValueError, self._hashlib.new, "md5", **kwargs) + self.assertRaises(ValueError, self.hashlib.md5, **kwargs) + self.assertRaises(ValueError, self._hashlib.openssl_md5, **kwargs) + + @hashlib_helper.block_algorithm("md5", allow_openssl=True) + def test_disable_hash_md5_in_fips_mode_allow_openssl(self): + self.skip_if_not_fips_mode() + # Allow the OpenSSL interface to be used but not the HACL* one. + # hashlib.new("md5") is dispatched to hashlib.openssl_md5() + self.assertRaises(ValueError, self.hashlib.new, "md5") + # dispatched to hashlib.openssl_md5() in FIPS mode + h2 = self.hashlib.new("md5", usedforsecurity=False) + self.assertIsInstance(h2, self._hashlib.HASH) + + # block_algorithm() does not mock hashlib.md5 and _hashlib.openssl_md5 + self.assertNotHasAttr(self.hashlib.md5, "__wrapped__") + self.assertNotHasAttr(self._hashlib.openssl_md5, "__wrapped__") + + hashlib_md5 = inspect.unwrap(self.hashlib.md5) + self.assertIs(hashlib_md5, self._hashlib.openssl_md5) + self.assertRaises(ValueError, self.hashlib.md5) + # allow MD5 to be used in FIPS mode if usedforsecurity=False + h3 = self.hashlib.md5(usedforsecurity=False) + self.assertIsInstance(h3, self._hashlib.HASH) + + @hashlib_helper.block_algorithm("md5", allow_builtin=True) + def test_disable_hash_md5_in_fips_mode_allow_builtin(self): + self.skip_if_not_fips_mode() + # Allow the HACL* interface to be used but not the OpenSSL one. + h1 = self.hashlib.new("md5") # dispatched to _md5.md5() + self.assertNotIsInstance(h1, self._hashlib.HASH) + h2 = self.hashlib.new("md5", usedforsecurity=False) + self.assertIsInstance(h2, type(h1)) + + # block_algorithm() mocks hashlib.md5 and _hashlib.openssl_md5 + self.assertHasAttr(self.hashlib.md5, "__wrapped__") + self.assertHasAttr(self._hashlib.openssl_md5, "__wrapped__") + + hashlib_md5 = inspect.unwrap(self.hashlib.md5) + openssl_md5 = inspect.unwrap(self._hashlib.openssl_md5) + self.assertIs(hashlib_md5, openssl_md5) + self.assertRaises(ValueError, self.hashlib.md5) + self.assertRaises(ValueError, self.hashlib.md5, + usedforsecurity=False) + + @hashlib_helper.block_algorithm("md5", + allow_openssl=True, + allow_builtin=True) + def test_disable_hash_md5_in_fips_mode_allow_all(self): + self.skip_if_not_fips_mode() + # hashlib.new() isn't blocked as it falls back to _md5.md5 + self.assertIsInstance(self.hashlib.new("md5"), self._md5.MD5Type) + self.assertRaises(ValueError, self._hashlib.new, "md5") + h = self._hashlib.new("md5", usedforsecurity=False) + self.assertIsInstance(h, self._hashlib.HASH) + + self.assertNotHasAttr(self.hashlib.md5, "__wrapped__") + self.assertNotHasAttr(self._hashlib.openssl_md5, "__wrapped__") + + self.assertIs(self.hashlib.md5, self._hashlib.openssl_md5) + self.assertRaises(ValueError, self.hashlib.md5) + h = self.hashlib.md5(usedforsecurity=False) + self.assertIsInstance(h, self._hashlib.HASH) + + class TestIsolated(unittest.TestCase): # Drive the sample tests in test._isolated_sample (which really spawn # subprocesses through @isolation.runInSubprocess()) under a private @@ -963,21 +1209,124 @@ def test_class_subprocess_dying_after_the_tests_is_reported(self): self.assertIn('tearDownClass', str(result.errors[0][0])) self.assertIn(f'exited with code {EXIT_CODE}', result.errors[0][1]) + @support.requires_subprocess() + def test_options_passed_to_subprocess(self): + result = self._run('OptionsSample') + self.assertEqual(result.testsRun, 1) + self.assertEqual(result.failures, []) + self.assertEqual(result.errors, []) + + @support.requires_subprocess() + def test_env_passed_to_subprocess(self): + # The samples check the variable, so set it here to let them tell + # env= from the inherited environment. + with os_helper.EnvironmentVarGuard() as env: + env['_PYTHON_ISOLATION_PROBE'] = 'set-by-parent' + result = self._run('EnvSample') + self.assertEqual(result.testsRun, 3) + self.assertEqual(result.failures, []) + self.assertEqual(result.errors, []) + + @support.requires_subprocess() + def test_timeout_reported_as_error(self): + from test._isolated_sample import TIMEOUT + result = self._run('TimeoutSample') + self.assertEqual(result.testsRun, 1) + self.assertEqual(len(result.errors), 1) + self.assertIn(f'within {TIMEOUT} seconds', result.errors[0][1]) + + @support.requires_subprocess() + def test_bigmemtest_isolates_a_real_run(self): + # A dummy run (no -M) stays in this process, a real run does not. + for memlimit in (0, support._1G): + with self.subTest(real_max_memuse=memlimit): + with support.swap_attr(support, 'real_max_memuse', memlimit): + result = self._run('BigmemSample') + self.assertEqual(result.testsRun, 1) + self.assertEqual(self._names(result.failures), []) + self.assertEqual(self._names(result.errors), []) + def test_skipped_without_subprocess_support(self): # On a platform without subprocess support the test is skipped in the # parent, before any subprocess is spawned. calls = [] - orig = isolation._run_in_subprocess + orig = isolation._start_test with support.swap_attr(support, 'has_subprocess_support', False): - isolation._run_in_subprocess = lambda *a, **k: calls.append(a) + isolation._start_test = lambda *a, **k: calls.append(a) try: result = self._run('MethodSample.test_pass') finally: - isolation._run_in_subprocess = orig + isolation._start_test = orig self.assertEqual(result.testsRun, 1) self.assertEqual(len(result.skipped), 1) self.assertEqual(calls, []) +class TestSubTests(unittest.TestCase): + + def run_test(self, cls): + result = unittest.TestResult() + cls('test_it').run(result) + return result + + def test_sync(self): + ran = [] + + class Sample(unittest.TestCase): + @support.subTests('a', [1, 2, 3]) + def test_it(self, a): + ran.append(a) + self.assertNotEqual(a, 2) + + result = self.run_test(Sample) + self.assertEqual(ran, [1, 2, 3]) + self.assertEqual(result.testsRun, 1) + self.assertEqual(len(result.failures), 1) + self.assertEndsWith(result.failures[0][0].id(), 'test_it (a=2)') + + # Running an asyncio event loop needs a working socket. + @support.requires_working_socket() + def test_async(self): + # Running an event loop sets the event loop policy, which regrtest + # reports as a change of the environment. + import asyncio.events + self.enterContext( + support.swap_attr(asyncio.events, '_event_loop_policy', None)) + + # An asynchronous test must be awaited: a synchronous wrapper would + # make it silently not run at all. + ran = [] + + class Sample(unittest.IsolatedAsyncioTestCase): + @support.subTests('a', [1, 2, 3]) + async def test_it(self, a): + ran.append(a) + self.assertNotEqual(a, 2) + + result = self.run_test(Sample) + self.assertEqual(ran, [1, 2, 3]) + self.assertEqual(result.testsRun, 1) + self.assertEqual(len(result.failures), 1) + self.assertEndsWith(result.failures[0][0].id(), 'test_it (a=2)') + + def test_multiple_parameters(self): + ran = [] + + class Sample(unittest.TestCase): + @support.subTests('a,b', [(1, 'x'), (2, 'y')]) + def test_it(self, a, b): + ran.append((a, b)) + + result = self.run_test(Sample) + self.assertTrue(result.wasSuccessful(), result.errors) + self.assertEqual(ran, [(1, 'x'), (2, 'y')]) + + def test_cannot_decorate_class(self): + with self.assertRaises(TypeError): + @support.subTests('a', [1]) + class Sample(unittest.TestCase): + pass + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_symtable.py b/Lib/test/test_symtable.py index 9537de3756f..4d435f152b0 100644 --- a/Lib/test/test_symtable.py +++ b/Lib/test/test_symtable.py @@ -5,6 +5,7 @@ import re import textwrap import symtable +import warnings import unittest from test import support @@ -254,6 +255,7 @@ def test_function_info(self): self.assertEqual(sorted(func.get_locals()), expected) self.assertEqual(sorted(func.get_globals()), ["bar", "glob", "some_assigned_global_var"]) self.assertEqual(self.internal.get_frees(), ("x",)) + self.assertEqual(self.spam.get_cells(), ("some_var", "x",)) def test_globals(self): self.assertTrue(self.spam.lookup("glob").is_global()) @@ -283,6 +285,9 @@ def test_local(self): def test_free(self): self.assertTrue(self.internal.lookup("x").is_free()) + def test_cells(self): + self.assertTrue(self.spam.lookup("x").is_cell()) + def test_referenced(self): self.assertTrue(self.internal.lookup("x").is_referenced()) self.assertTrue(self.spam.lookup("internal").is_referenced()) @@ -527,6 +532,58 @@ def test_symtable_entry_repr(self): expected = f"" self.assertEqual(repr(self.top._table), expected) + def test_lambda(self): + st = symtable.symtable("lambda x: x", "?", "exec") + self.assertEqual(len(st.get_children()), 1) + st = st.get_children()[0] + self.assertIs(st.get_type(), symtable.SymbolTableType.FUNCTION) + self.assertEqual(st.get_name(), "") + self.assertFalse(st.is_nested()) + self.assertEqual(sorted(st.get_identifiers()), ["x"]) + self.assertEqual(st.get_children(), []) + + def test_nested_lambda(self): + st = symtable.symtable("lambda x: lambda y=x: y", "?", "exec") + self.assertEqual(len(st.get_children()), 1) + st = st.get_children()[0] + self.assertIs(st.get_type(), symtable.SymbolTableType.FUNCTION) + self.assertEqual(st.get_name(), "") + self.assertFalse(st.is_nested()) + self.assertEqual(sorted(st.get_identifiers()), ["x"]) + self.assertEqual(len(st.get_children()), 1) + st = st.get_children()[0] + self.assertIs(st.get_type(), symtable.SymbolTableType.FUNCTION) + self.assertEqual(st.get_name(), "") + self.assertTrue(st.is_nested()) + self.assertEqual(sorted(st.get_identifiers()), ["y"]) + self.assertEqual(st.get_children(), []) + + def test_genexpr(self): + st = symtable.symtable("(x for x in a)", "?", "exec") + self.assertEqual(len(st.get_children()), 1) + st = st.get_children()[0] + self.assertIs(st.get_type(), symtable.SymbolTableType.FUNCTION) + self.assertEqual(st.get_name(), "") + self.assertFalse(st.is_nested()) + self.assertEqual(sorted(st.get_identifiers()), [".0", "x"]) + self.assertEqual(st.get_children(), []) + + def test_nested_genexpr(self): + st = symtable.symtable("((y for y in x) for x in a)", "?", "exec") + self.assertEqual(len(st.get_children()), 1) + st = st.get_children()[0] + self.assertIs(st.get_type(), symtable.SymbolTableType.FUNCTION) + self.assertEqual(st.get_name(), "") + self.assertFalse(st.is_nested()) + self.assertEqual(sorted(st.get_identifiers()), [".0", "x"]) + self.assertEqual(len(st.get_children()), 1) + st = st.get_children()[0] + self.assertIs(st.get_type(), symtable.SymbolTableType.FUNCTION) + self.assertEqual(st.get_name(), "") + self.assertTrue(st.is_nested()) + self.assertEqual(sorted(st.get_identifiers()), [".0", "y"]) + self.assertEqual(st.get_children(), []) + def test__symtable_refleak(self): # Regression test for reference leak in PyUnicode_FSDecoder. # See https://github.com/python/cpython/issues/139748. @@ -534,8 +591,84 @@ def test__symtable_refleak(self): # check error path when 'compile_type' AC conversion failed self.assertRaises(TypeError, symtable.symtable, '', mortal_str, 1) + def test_filter_syntax_warnings_by_module(self): + filename = support.findfile('test_import/data/syntax_warnings.py') + with open(filename, 'rb') as f: + source = f.read() + module_re = r'test\.test_import\.data\.syntax_warnings\z' + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=module_re) + symtable.symtable(source, filename, 'exec') + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10]) + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) + + with warnings.catch_warnings(record=True) as wlog: + warnings.simplefilter('error') + warnings.filterwarnings('always', module=r'package\.module\z') + warnings.filterwarnings('error', module=module_re) + symtable.symtable(source, filename, 'exec', module='package.module') + self.assertEqual(sorted(wm.lineno for wm in wlog), [4, 7, 10]) + for wm in wlog: + self.assertEqual(wm.filename, filename) + self.assertIs(wm.category, SyntaxWarning) + class ComprehensionTests(unittest.TestCase): + def test_referenced_in_comprehension(self): + comps = [ + "[x + k + local for x in xs]", + "{x + k + local for x in xs}", + "{x: k + local for x in xs}", + "[[x + k + local for x in xs] for _ in xs]", + ] + for comp in comps: + with self.subTest(comp=comp): + st = symtable.symtable( + "def f(xs, k):\n" + " local = 1\n" + f" return {comp}\n", "?", "exec") + f = find_block(st, "f") + self.assertTrue(f.lookup("k").is_referenced()) + self.assertTrue(f.lookup("local").is_referenced()) + self.assertEqual(f.get_children(), []) + + def test_nonlocal_referenced_in_comprehension(self): + st = symtable.symtable( + "def outer(k):\n" + " def f(xs):\n" + " nonlocal k\n" + " return [x + k for x in xs]\n", "?", "exec") + f = find_block(find_block(st, "outer"), "f") + self.assertTrue(f.lookup("k").is_referenced()) + self.assertTrue(f.lookup("k").is_nonlocal()) + + def test_not_referenced_in_comprehension(self): + comps = [ + "[k for k in xs]", # The iteration variable shadows the parameter. + "[[k for _ in ()] for k in xs]", # Shadowing in a nested comprehension. + "[(lambda: k) for x in xs]", # The load is in a nested function. + "(x + k for x in xs)", # Generator expressions are not inlined. + ] + for comp in comps: + with self.subTest(comp=comp): + st = symtable.symtable( + "def f(xs, k):\n" + f" return {comp}\n", "?", "exec") + self.assertFalse(find_block(st, "f").lookup("k").is_referenced()) + + def test_class_local_not_referenced_in_comprehension(self): + st = symtable.symtable( + "def outer(k):\n" + " class C:\n" + " k = 1\n" + " values = [k for _ in ()]\n", "?", "exec") + cls = find_block(find_block(st, "outer"), "C") + # The comprehension refers to outer's k, not the class attribute. + self.assertFalse(cls.lookup("k").is_referenced()) + def get_identifiers_recursive(self, st, res): res.extend(st.get_identifiers()) for ch in st.get_children(): diff --git a/Lib/test/test_syntax.py b/Lib/test/test_syntax.py index d3cb80bbb70..c416e7b04ed 100644 --- a/Lib/test/test_syntax.py +++ b/Lib/test/test_syntax.py @@ -326,7 +326,7 @@ # Incorrectly closed strings ->>> "The interesting object "The important object" is very important" # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE +>>> "The interesting object "The important object" is very important" Traceback (most recent call last): SyntaxError: invalid syntax. Is this intended to be part of the string? @@ -353,7 +353,7 @@ # Make sure soft keywords constructs don't raise specialized # errors regarding missing commas or other spezialiced errors ->>> match x: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE +>>> match x: ... y = 3 Traceback (most recent call last): SyntaxError: invalid syntax @@ -382,6 +382,42 @@ Traceback (most recent call last): SyntaxError: invalid syntax +# Check incorrect "case" placement with specialized error messages + +>>> case "pattern": ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + +>>> case 1 | 2: ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + +>>> case klass(attr=1) | {}: ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + +>>> case [] if x > 1: ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + +>>> case match: ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + +>>> case case: ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + +>>> if some: +... case 1: ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + +>>> case some: +... case 1: ... +Traceback (most recent call last): +SyntaxError: case statement must be inside match statement + # But prefixes of soft keywords should # still raise specialized errors @@ -423,10 +459,10 @@ Traceback (most recent call last): SyntaxError: invalid syntax ->>> def foo(/,a,b=,c): # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE +>>> def foo(/,a,b=,c): ... pass Traceback (most recent call last): -SyntaxError: at least one argument must precede / +SyntaxError: at least one parameter must precede / >>> def foo(a,/,/,b,c): ... pass @@ -461,67 +497,67 @@ >>> def foo(a,*b=3,c): ... pass Traceback (most recent call last): -SyntaxError: var-positional argument cannot have default value +SyntaxError: var-positional parameter cannot have default value >>> def foo(a,*b: int=,c): ... pass Traceback (most recent call last): -SyntaxError: var-positional argument cannot have default value +SyntaxError: var-positional parameter cannot have default value >>> def foo(a,**b=3): ... pass Traceback (most recent call last): -SyntaxError: var-keyword argument cannot have default value +SyntaxError: var-keyword parameter cannot have default value >>> def foo(a,**b: int=3): ... pass Traceback (most recent call last): -SyntaxError: var-keyword argument cannot have default value +SyntaxError: var-keyword parameter cannot have default value >>> def foo(a,*a, b, **c, d): ... pass Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> def foo(a,*a, b, **c, d=4): ... pass Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> def foo(a,*a, b, **c, *d): ... pass Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> def foo(a,*a, b, **c, **d): ... pass Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> def foo(a=1,/,**b,/,c): ... pass Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> def foo(*b,*d): ... pass Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> def foo(a,*b,c,*d,*e,c): ... pass Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> def foo(a,b,/,c,*b,c,*d,*e,c): ... pass Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> def foo(a,b,/,c,*b,c,*d,**e): ... pass Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> def foo(a=1,/*,b,c): ... pass @@ -545,7 +581,7 @@ >>> lambda /,a,b,c: None Traceback (most recent call last): -SyntaxError: at least one argument must precede / +SyntaxError: at least one parameter must precede / >>> lambda a,/,/,b,c: None Traceback (most recent call last): @@ -577,47 +613,47 @@ >>> lambda a,*b=3,c: None Traceback (most recent call last): -SyntaxError: var-positional argument cannot have default value +SyntaxError: var-positional parameter cannot have default value >>> lambda a,**b=3: None Traceback (most recent call last): -SyntaxError: var-keyword argument cannot have default value +SyntaxError: var-keyword parameter cannot have default value >>> lambda a, *a, b, **c, d: None Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> lambda a,*a, b, **c, d=4: None Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> lambda a,*a, b, **c, *d: None Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> lambda a,*a, b, **c, **d: None Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> lambda a=1,/,**b,/,c: None Traceback (most recent call last): -SyntaxError: arguments cannot follow var-keyword argument +SyntaxError: parameters cannot follow var-keyword parameter >>> lambda *b,*d: None Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> lambda a,*b,c,*d,*e,c: None Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> lambda a,b,/,c,*b,c,*d,*e,c: None Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> lambda a,b,/,c,*b,c,*d,**e: None Traceback (most recent call last): -SyntaxError: * argument may appear only once +SyntaxError: * may appear only once >>> lambda a=1,d=,c: None Traceback (most recent call last): @@ -860,7 +896,7 @@ >>> __debug__ += 1 Traceback (most recent call last): SyntaxError: cannot assign to __debug__ ->>> f() += 1 # TODO: RUSTPYTHON; Raises an exception # doctest: +SKIP +>>> f() += 1 Traceback (most recent call last): SyntaxError: 'function call' is an illegal expression for augmented assignment @@ -1045,7 +1081,7 @@ a complex 'if' (one with 'elif') would fail to notice an invalid suite, leading to spurious errors. - >>> if 1: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> if 1: ... x() = 1 ... elif 1: ... pass @@ -1053,7 +1089,7 @@ ... SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? - >>> if 1: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> if 1: ... pass ... elif 1: ... x() = 1 @@ -1061,7 +1097,7 @@ ... SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? - >>> if 1: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> if 1: ... x() = 1 ... elif 1: ... pass @@ -1071,7 +1107,7 @@ ... SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? - >>> if 1: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> if 1: ... pass ... elif 1: ... x() = 1 @@ -1081,7 +1117,7 @@ ... SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='? - >>> if 1: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> if 1: ... pass ... elif 1: ... pass @@ -1185,7 +1221,7 @@ Traceback (most recent call last): SyntaxError: expected ':' - >>> with (blech as something) # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> with (blech as something) ... pass Traceback (most recent call last): SyntaxError: expected ':' @@ -1195,12 +1231,12 @@ Traceback (most recent call last): SyntaxError: expected ':' - >>> with (blech, block as something) # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> with (blech, block as something) ... pass Traceback (most recent call last): SyntaxError: expected ':' - >>> with (blech, block as something, bluch) # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> with (blech, block as something, bluch) ... pass Traceback (most recent call last): SyntaxError: expected ':' @@ -1440,20 +1476,20 @@ Regression tests for gh-133999: - >>> try: pass # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> try: pass ... except TypeError as name: raise from None Traceback (most recent call last): - SyntaxError: invalid syntax + SyntaxError: did you forget an expression between 'raise' and 'from'? - >>> try: pass # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> try: pass ... except* TypeError as name: raise from None Traceback (most recent call last): - SyntaxError: invalid syntax + SyntaxError: did you forget an expression between 'raise' and 'from'? - >>> match 1: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> match 1: ... case 1 | 2 as abc: raise from None Traceback (most recent call last): - SyntaxError: invalid syntax + SyntaxError: did you forget an expression between 'raise' and 'from'? Ensure that early = are not matched by the parser as invalid comparisons >>> f(2, 4, x=34); 1 $ 2 @@ -1464,7 +1500,7 @@ Traceback (most recent call last): SyntaxError: invalid syntax - >>> dict(x=34, (x for x in range 10), 1); x $ y # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> dict(x=34, (x for x in range 10), 1); x $ y Traceback (most recent call last): SyntaxError: invalid syntax @@ -1693,15 +1729,37 @@ IndentationError: expected an indented block after 'case' statement on line 4 Make sure that the old "raise X, Y[, Z]" form is gone: - >>> raise X, Y # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> raise X, Y Traceback (most recent call last): ... SyntaxError: invalid syntax - >>> raise X, Y, Z # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> raise X, Y, Z Traceback (most recent call last): ... SyntaxError: invalid syntax +Better errors for `raise` statement: + + >>> raise ValueError from + Traceback (most recent call last): + SyntaxError: did you forget an expression after 'from'? + + >>> raise mod.ValueError() from + Traceback (most recent call last): + SyntaxError: did you forget an expression after 'from'? + + >>> raise from exc + Traceback (most recent call last): + SyntaxError: did you forget an expression between 'raise' and 'from'? + + >>> raise from None + Traceback (most recent call last): + SyntaxError: did you forget an expression between 'raise' and 'from'? + + >>> raise from + Traceback (most recent call last): + SyntaxError: did you forget an expression between 'raise' and 'from'? + Check that an multiple exception types with missing parentheses raise a custom exception only when using 'as' @@ -2009,6 +2067,30 @@ Traceback (most recent call last): SyntaxError: trailing comma not allowed without surrounding parentheses +>>> with item,: pass +Traceback (most recent call last): +SyntaxError: the last 'with' item has a trailing comma + +>>> with item as x,: pass +Traceback (most recent call last): +SyntaxError: the last 'with' item has a trailing comma + +>>> with item1, item2,: pass +Traceback (most recent call last): +SyntaxError: the last 'with' item has a trailing comma + +>>> with item1 as x, item2,: pass +Traceback (most recent call last): +SyntaxError: the last 'with' item has a trailing comma + +>>> with item1 as x, item2 as y,: pass +Traceback (most recent call last): +SyntaxError: the last 'with' item has a trailing comma + +>>> with item1, item2 as y,: pass +Traceback (most recent call last): +SyntaxError: the last 'with' item has a trailing comma + >>> import a from b Traceback (most recent call last): SyntaxError: Did you mean to use 'from ... import ...' instead? @@ -2077,7 +2159,7 @@ Traceback (most recent call last): SyntaxError: cannot use literal as import target ->>> from a import (b as c.d) # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE +>>> from a import (b as c.d) Traceback (most recent call last): SyntaxError: cannot use attribute as import target @@ -2085,18 +2167,18 @@ Traceback (most recent call last): SyntaxError: cannot use literal as import target ->>> from a import ( # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE +>>> from a import ( ... b as f()) Traceback (most recent call last): SyntaxError: cannot use function call as import target ->>> from a import ( # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE +>>> from a import ( ... b as [], ... ) Traceback (most recent call last): SyntaxError: cannot use list as import target ->>> from a import ( # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE +>>> from a import ( ... b, ... c as () ... ) @@ -2162,6 +2244,16 @@ Traceback (most recent call last): SyntaxError: only single target (not list) can be annotated +>>> 1: int +Traceback (most recent call last): +SyntaxError: illegal target for annotation +>>> -x: int = 1 +Traceback (most recent call last): +SyntaxError: illegal target for annotation +>>> (x for x in y): int +Traceback (most recent call last): +SyntaxError: illegal target for annotation + # 'not' after operators: >>> 3 + not 3 @@ -2221,7 +2313,7 @@ >>> with (lambda *:0): pass Traceback (most recent call last): - SyntaxError: named arguments must follow bare * + SyntaxError: named parameters must follow bare * Corner-cases that used to crash: @@ -2233,7 +2325,7 @@ Traceback (most recent call last): SyntaxError: cannot assign to __debug__ - >>> import ä £ # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> import ä £ Traceback (most recent call last): SyntaxError: invalid character '£' (U+00A3) @@ -2245,7 +2337,7 @@ Traceback (most recent call last): SyntaxError: cannot use '_' as a target - >>> match ...: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> match ...: ... case 42 as 1+2+4: ... ... Traceback (most recent call last): @@ -2263,13 +2355,13 @@ Traceback (most recent call last): SyntaxError: cannot use tuple as pattern target - >>> match ...: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> match ...: ... case 42 as (a + 1): ... ... Traceback (most recent call last): SyntaxError: cannot use expression as pattern target - >>> match ...: # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> match ...: ... case (32 as x) | (42 as a()): ... ... Traceback (most recent call last): @@ -2293,12 +2385,36 @@ Traceback (most recent call last): SyntaxError: positional patterns follow keyword patterns + >>> match ...: + ... case Foo(y=1, x=2, y=3): + ... ... + Traceback (most recent call last): + SyntaxError: attribute name repeated in class pattern: y + >>> match ...: ... case C(a=b, c, d=e, f, g=h, i, j=k, ...): ... ... Traceback (most recent call last): SyntaxError: positional patterns follow keyword patterns + >>> match ...: + ... case {**double_star, "spam": "eggs"}: + ... ... + Traceback (most recent call last): + SyntaxError: double star pattern must be the last (right-most) subpattern in the mapping pattern + + >>> match ...: + ... case {"foo": 1, **double_star, "spam": "eggs"}: + ... ... + Traceback (most recent call last): + SyntaxError: double star pattern must be the last (right-most) subpattern in the mapping pattern + + >>> match ...: + ... case {"spam": "eggs", "b": {**d, "ham": "bacon"}}: + ... ... + Traceback (most recent call last): + SyntaxError: double star pattern must be the last (right-most) subpattern in the mapping pattern + Uses of the star operator which should fail: A[:*b] @@ -2375,7 +2491,7 @@ A[*:] and A[:*] - >>> A[*:] # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> A[*:] Traceback (most recent call last): ... SyntaxError: Invalid star expression @@ -2386,7 +2502,7 @@ A[*] - >>> A[*] # TODO: RUSTPYTHON; Wrong error message # doctest: +EXPECTED_FAILURE + >>> A[*] Traceback (most recent call last): ... SyntaxError: Invalid star expression @@ -2683,6 +2799,76 @@ def f(x: *b) >>> f(x = 5, *:) Traceback (most recent call last): SyntaxError: Invalid star expression + +Asserts: + + >>> assert (a := 1) # ok + >>> assert 1, (a := 1) # ok + + >>> assert a := 1 + Traceback (most recent call last): + SyntaxError: cannot use named expression without parentheses here + + >>> assert 1, a := 1 + Traceback (most recent call last): + SyntaxError: cannot use named expression without parentheses here + + >>> assert 1 = 2 = 3 + Traceback (most recent call last): + SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? + + >>> assert 1 = 2 + Traceback (most recent call last): + SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? + + >>> assert (1 = 2) + Traceback (most recent call last): + SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? + + >>> assert 'a' = a + Traceback (most recent call last): + SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? + + >>> assert x[0] = 1 + Traceback (most recent call last): + SyntaxError: cannot assign to subscript here. Maybe you meant '==' instead of '='? + + >>> assert (yield a) = 2 + Traceback (most recent call last): + SyntaxError: cannot assign to yield expression here. Maybe you meant '==' instead of '='? + + >>> assert a = 2 + Traceback (most recent call last): + SyntaxError: cannot assign to name here. Maybe you meant '==' instead of '='? + + >>> assert (a = 2) + Traceback (most recent call last): + SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? + + >>> assert a = b + Traceback (most recent call last): + SyntaxError: cannot assign to name here. Maybe you meant '==' instead of '='? + + >>> assert 1, 1 = b + Traceback (most recent call last): + SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? + + >>> assert 1, (1 = b) + Traceback (most recent call last): + SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? + + >>> assert 1, a = 1 + Traceback (most recent call last): + SyntaxError: cannot assign to name here. Maybe you meant '==' instead of '='? + + >>> assert 1, (a = 1) + Traceback (most recent call last): + SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='? + + >>> assert 1 = a, a = 1 + Traceback (most recent call last): + SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='? + """ import re @@ -2702,6 +2888,14 @@ def check_warning(self, code, errtext, filename="", mode="exec"): with self.assertWarnsRegex(SyntaxWarning, errtext): compile(code, filename, mode) + def check_no_warning(self, code, filename="", mode="exec"): + """Check that compiling code does not raise any warnings.""" + import warnings + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + compile(code, filename, mode) + self.assertEqual(caught, []) + def test_return_in_finally(self): source = textwrap.dedent(""" def f(): @@ -2772,6 +2966,75 @@ def test_break_and_continue_in_finally(self): """) self.check_warning(source, f"'{kw}' in a 'finally' block") + def test_from_lazy_imports(self): + # gh-150459 + self.check_warning( + "from . lazy import x", + "did you mean 'lazy from . import'?", + ) + self.check_warning( + "from . lazy import x as y", + "did you mean 'lazy from . import'?", + ) + self.check_warning( + "from . lazy import *", + "did you mean 'lazy from . import'?", + ) + self.check_warning( + "from .. lazy import x", + "did you mean 'lazy from .. import'?", + ) + self.check_warning( + "from ... lazy import x", + "did you mean 'lazy from ... import'?", + ) + self.check_warning( + "from .... lazy import x", + "did you mean 'lazy from .... import'?", + ) + self.check_warning( + "from . \\\n lazy import x", + "did you mean 'lazy from . import'?", + ) + self.check_warning( + "from .\\\nlazy import x", + "did you mean 'lazy from . import'?", + ) + self.check_warning( + "from .\tlazy import x", + "did you mean 'lazy from . import'?", + ) + + def test_not_from_lazy_imports(self): + self.check_no_warning("from .lazy import x") + self.check_no_warning("from .lazy import *") + self.check_no_warning("from ..lazy import x") + self.check_no_warning("from ...lazy import x") + self.check_no_warning("from .lazy.sub import x") + self.check_no_warning("from ..lazy.sub import x") + self.check_no_warning("from ...lazy.sub import x") + self.check_no_warning("from . lazier import x") + self.check_no_warning("from . lazy_module import x") + self.check_no_warning("from . lazy.sub import x") + self.check_no_warning("from . sub.lazy import x") + self.check_no_warning("from lazy import x") + self.check_no_warning("from lazy.sub import x") + self.check_no_warning("lazy from . lazy import x") + self.check_no_warning("from . import lazy") + + def test_from_lazy_imports_as_error(self): + import warnings + with warnings.catch_warnings(): + warnings.simplefilter("error", SyntaxWarning) + with self.assertRaisesRegex( + SyntaxError, + re.escape("did you mean 'lazy from . import'?"), + ) as cm: + compile("from . lazy import x", "", "exec") + self.assertEqual(cm.exception.lineno, 1) + self.assertEqual(cm.exception.offset, 8) + self.assertEqual(cm.exception.end_offset, 12) + class SyntaxErrorTestCase(unittest.TestCase): @@ -2869,6 +3132,14 @@ def error2(): """ self._check_error(source, "parameter and nonlocal", lineno=3) + def test_raise_from_error_message(self): + source = """if 1: + raise AssertionError() from None + print(1,,2) + """ + self._check_error(source, "invalid syntax", lineno=3) + + def test_yield_outside_function(self): self._check_error("if 0: yield", "outside function") self._check_error("if 0: yield\nelse: x=1", "outside function") @@ -3189,6 +3460,21 @@ def test_multiline_compiler_error_points_to_the_end(self): lineno=3 ) + def test_multiline_string_concat_missing_comma_points_to_last_string(self): + # gh-142236: For multi-line string concatenations with a missing comma, + # the error should point to the last string, not the first. + self._check_error( + "print(\n" + ' "line1"\n' + ' "line2"\n' + ' "line3"\n' + " x=1\n" + ")", + "Perhaps you forgot a comma", + lineno=4, # Points to "line3", the last string + ) + + @support.cpython_only def test_syntax_error_on_deeply_nested_blocks(self): # This raises a SyntaxError, it used to raise a SystemError. Context @@ -3313,6 +3599,169 @@ def test_ifexp_body_stmt_else_stmt(self): ("continue", "import ast") ]: self._check_error(f"x = {lhs_stmt} if 1 else {rhs_stmt}", msg) + def test_diamond_operator(self): + self._check_error( + "1<>2", + r"Maybe you meant '!=' instead of '<>'\?", + lineno=1, + end_lineno=1, + offset=2, + end_offset=4, + ) + + + def test_diamond_operator_barry_as_flufl(self): + compile( + "from __future__ import barry_as_FLUFL\n1<>2", + "", "exec", + ) + self._check_error( + "from __future__ import barry_as_FLUFL\na != b", + "with Barry as BDFL, use '<>' instead of '!='", + lineno=2, + end_lineno=2, + offset=3, + end_offset=5, + ) + + + +class LazyImportRestrictionTestCase(SyntaxErrorTestCase): + """Test syntax restrictions for lazy imports.""" + + def test_lazy_import_in_try_block(self): + """Test that lazy imports are not allowed inside try blocks.""" + self._check_error("""\ +try: + lazy import os +except: + pass +""", "lazy import not allowed inside try/except blocks") + + self._check_error("""\ +try: + lazy from sys import path +except ImportError: + pass +""", "lazy from ... import not allowed inside try/except blocks") + + def test_lazy_import_in_trystar_block(self): + """Test that lazy imports are not allowed inside try* blocks.""" + self._check_error("""\ +try: + lazy import json +except* Exception: + pass +""", "lazy import not allowed inside try/except blocks") + + self._check_error("""\ +try: + lazy from collections import defaultdict +except* ImportError: + pass +""", "lazy from ... import not allowed inside try/except blocks") + + def test_lazy_import_in_except_block(self): + """Test that lazy imports are not allowed inside except blocks.""" + self._check_error("""\ +try: + sys.modules # trigger the except block +except* Exception: + lazy import sys +""", "lazy import not allowed inside try/except blocks") + + def test_lazy_import_in_function(self): + """Test that lazy imports are not allowed inside functions.""" + self._check_error("""\ +def func(): + lazy import math +""", "lazy import not allowed inside functions") + + self._check_error("""\ +def func(): + lazy from datetime import datetime +""", "lazy from ... import not allowed inside functions") + + def test_lazy_import_in_async_function(self): + """Test that lazy imports are not allowed inside async functions.""" + self._check_error("""\ +async def async_func(): + lazy import asyncio +""", "lazy import not allowed inside functions") + + self._check_error("""\ +async def async_func(): + lazy from json import loads +""", "lazy from ... import not allowed inside functions") + + def test_lazy_import_in_class(self): + """Test that lazy imports are not allowed inside classes.""" + self._check_error("""\ +class MyClass: + lazy import typing +""", "lazy import not allowed inside classes") + + self._check_error("""\ +class MyClass: + lazy from abc import ABC +""", "lazy from ... import not allowed inside classes") + + def test_lazy_import_star_forbidden(self): + """Test that 'lazy from ... import *' is forbidden everywhere.""" + # At module level should also be forbidden + self._check_error("lazy from os import *", + "lazy from ... import \\* is not allowed") + + # Inside function should give lazy function error first + self._check_error("""\ +def func(): + lazy from sys import * +""", "lazy from ... import not allowed inside functions") + + def test_lazy_import_nested_scopes(self): + """Test lazy imports in nested scopes.""" + self._check_error("""\ +class Outer: + def method(self): + lazy import sys +""", "lazy import not allowed inside functions") + + self._check_error("""\ +def outer(): + class Inner: + lazy import json +""", "lazy import not allowed inside classes") + + self._check_error("""\ +def outer(): + def inner(): + lazy from collections import deque +""", "lazy from ... import not allowed inside functions") + + self._check_error("""\ +from os lazy import path +""", "use 'lazy from ... ' instead of 'from ... lazy import'") + self._check_error("""\ +from os.path lazy import join +""", "use 'lazy from ... ' instead of 'from ... lazy import'") + self._check_error("""\ +from .mod lazy import join +""", "use 'lazy from ... ' instead of 'from ... lazy import'") + self._check_error("""\ +from ..mod lazy import join +""", "use 'lazy from ... ' instead of 'from ... lazy import'") + self._check_error("""\ +from ...mod lazy import join +""", "use 'lazy from ... ' instead of 'from ... lazy import'") + + def test_lazy_import_valid_cases(self): + """Test that lazy imports work at module level.""" + # These should compile without errors + compile("lazy import os", "", "exec") + compile("lazy from sys import path", "", "exec") + compile("lazy import json as j", "", "exec") + compile("lazy from datetime import datetime as dt", "", "exec") + def load_tests(loader, tests, pattern): from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py index f30b609afa6..0d81f986763 100644 --- a/Lib/test/test_sys.py +++ b/Lib/test/test_sys.py @@ -6,6 +6,7 @@ import operator import os import random +import shutil import socket import struct import subprocess @@ -494,7 +495,7 @@ def test_getframemodulename(self): self.assertIs(f, f2) self.assertIsNone(sys._getframemodulename(i)) - # sys._current_frames() is a CPython-only gimmick. + @support.cpython_only # sys._current_frames() is a CPython-only gimmick. @threading_helper.reap_threads @threading_helper.requires_working_threading() def test_current_frames(self): @@ -562,6 +563,38 @@ def g456(): leave_g.set() t.join() + @support.cpython_only + @requires_subinterpreters + @threading_helper.requires_working_threading() + def test_current_frames_other_interpreters(self): + # gh-158364: sys._current_frames() would access frames of another + # interpreter and crash + import threading + + entered = threading.Event() + left = threading.Event() + + def park(): + entered.set() + left.wait() + + t = threading.Thread(target=park) + with threading_helper.start_threads([t], unlock=left.set): + entered.wait() + interp = interpreters.create() + try: + interp.exec(f"""if True: + import sys + import threading + + frames = sys._current_frames() + assert threading.get_ident() in frames, frames + assert frames[threading.get_ident()].f_globals is globals() + assert {t.ident} not in frames, frames + """) + finally: + interp.close() + @threading_helper.reap_threads @threading_helper.requires_working_threading() def test_current_exceptions(self): @@ -628,6 +661,39 @@ def g456(): leave_g.set() t.join() + @support.cpython_only + @requires_subinterpreters + @threading_helper.requires_working_threading() + def test_current_exceptions_other_interpreters(self): + # gh-158364: sys._current_exceptions() would hand out exceptions of + # another interpreter and crash + import threading + + entered = threading.Event() + left = threading.Event() + + def hold(): + # The thread has to be handling an exception, otherwise + # sys._current_exceptions() has nothing to report for it. + try: + raise ValueError + except ValueError: + entered.set() + left.wait() + + t = threading.Thread(target=hold) + with threading_helper.start_threads([t], unlock=left.set): + entered.wait() + interp = interpreters.create() + try: + interp.exec(f"""if True: + import sys + + assert {t.ident} not in sys._current_exceptions() + """) + finally: + interp.close() + def test_attributes(self): self.assertIsInstance(sys.api_version, int) self.assertIsInstance(sys.argv, list) @@ -729,15 +795,25 @@ def test_thread_info(self): info = sys.thread_info self.assertEqual(len(info), 3) self.assertIn(info.name, ('nt', 'pthread', 'pthread-stubs', 'solaris', None)) - self.assertIn(info.lock, ('semaphore', 'mutex+cond', None)) - if sys.platform.startswith(("linux", "android", "freebsd")): + self.assertIn(info.lock, ('pymutex', None)) + if sys.platform.startswith(("linux", "android", "freebsd", "wasi")): self.assertEqual(info.name, "pthread") elif sys.platform == "win32": self.assertEqual(info.name, "nt") elif sys.platform == "emscripten": self.assertIn(info.name, {"pthread", "pthread-stubs"}) - elif sys.platform == "wasi": - self.assertEqual(info.name, "pthread-stubs") + + def test_abi_info(self): + info = sys.abi_info + info_keys = {'pointer_bits', 'free_threaded', 'debug', 'byteorder'} + self.assertEqual(set(vars(info)), info_keys) + pointer_bits = 64 if sys.maxsize > 2**32 else 32 + self.assertEqual(info.pointer_bits, pointer_bits) + self.assertEqual(info.free_threaded, + bool(sysconfig.get_config_var('Py_GIL_DISABLED'))) + self.assertEqual(info.debug, + bool(sysconfig.get_config_var('Py_DEBUG'))) + self.assertEqual(info.byteorder, sys.byteorder) @unittest.skipUnless(support.is_emscripten, "only available on Emscripten") def test_emscripten_info(self): @@ -849,23 +925,35 @@ def test_subinterp_intern_singleton(self): ''')) self.assertTrue(sys._is_interned(s)) - def test_sys_flags(self): + def test_sys_flags_indexable_attributes(self): self.assertTrue(sys.flags) - attrs = ("debug", + # We've stopped assigning sequence indices to new sys.flags attributes: + # https://github.com/python/cpython/issues/122575#issuecomment-2416497086 + indexable_attrs = ("debug", "inspect", "interactive", "optimize", "dont_write_bytecode", "no_user_site", "no_site", "ignore_environment", "verbose", "bytes_warning", "quiet", "hash_randomization", "isolated", "dev_mode", "utf8_mode", "warn_default_encoding", "safe_path", "int_max_str_digits") - for attr in attrs: + for attr_idx, attr in enumerate(indexable_attrs): self.assertHasAttr(sys.flags, attr) attr_type = bool if attr in ("dev_mode", "safe_path") else int self.assertEqual(type(getattr(sys.flags, attr)), attr_type, attr) + attr_value = getattr(sys.flags, attr) + self.assertEqual(sys.flags[attr_idx], attr_value, + msg=f"sys.flags .{attr} vs [{attr_idx}]") self.assertTrue(repr(sys.flags)) - self.assertEqual(len(sys.flags), len(attrs)) + self.assertEqual(len(sys.flags), 18, msg="Do not increase, see GH-122575") self.assertIn(sys.flags.utf8_mode, {0, 1, 2}) + def test_sys_flags_name_only_attributes(self): + # non-tuple sequence fields (name only sys.flags attributes) + self.assertIsInstance(sys.flags.gil, int|type(None)) + self.assertIsInstance(sys.flags.thread_inherit_context, int|type(None)) + self.assertIsInstance(sys.flags.context_aware_warnings, int|type(None)) + self.assertIsInstance(sys.flags.lazy_imports, int|type(None)) + def assert_raise_on_new_sys_type(self, sys_attr): # Users are intentionally prevented from creating new instances of # sys.flags, sys.version_info, and sys.getwindowsversion. @@ -1295,6 +1383,7 @@ def test_module_names(self): for name in sys.stdlib_module_names: self.assertIsInstance(name, str) + @unittest.skipUnless(hasattr(sys, '_stdlib_dir'), 'need sys._stdlib_dir') def test_stdlib_dir(self): os = import_helper.import_fresh_module('os') marker = getattr(os, '__file__', None) @@ -1339,8 +1428,29 @@ def test_pystats(self): def test_disable_gil_abi(self): self.assertEqual('t' in sys.abiflags, support.Py_GIL_DISABLED) + def test_int_max_str_digits(self): + old_limit = sys.get_int_max_str_digits() + self.assertIsInstance(old_limit, int) + self.assertGreaterEqual(old_limit, 0) + self.addCleanup(sys.set_int_max_str_digits, old_limit) + + sys.set_int_max_str_digits(0) + self.assertEqual(sys.get_int_max_str_digits(), 0) + + sys.set_int_max_str_digits(2_048) + self.assertEqual(sys.get_int_max_str_digits(), 2_048) + + with self.assertRaises(ValueError): + # the minimum is 640 digits + sys.set_int_max_str_digits(5) + with self.assertRaises(ValueError): + sys.set_int_max_str_digits(-2) + with self.assertRaises(TypeError): + sys.set_int_max_str_digits(2_048.0) + @test.support.cpython_only +@test.support.force_not_colorized_test_class class UnraisableHookTest(unittest.TestCase): def test_original_unraisablehook(self): _testcapi = import_helper.import_module('_testcapi') @@ -1572,7 +1682,7 @@ def test_objecttypes(self): samples = [b'', b'u'*100000] for sample in samples: x = bytearray(sample) - check(x, vsize('n2Pi') + x.__alloc__()) + check(x, vsize('n2PiP') + x.__alloc__()) # bytearray_iterator check(iter(bytearray()), size('nP')) # bytes @@ -1714,9 +1824,10 @@ def get_gen(): yield 1 check(int(PyLong_BASE**2), vsize('') + 3*self.longdigit) # module if support.Py_GIL_DISABLED: - check(unittest, size('PPPPPP')) + md_gil = '?' else: - check(unittest, size('PPPPP')) + md_gil = '' + check(unittest, size('PPPP?' + md_gil + 'NPPPPP')) # None check(None, size('')) # NotImplementedType @@ -1776,7 +1887,7 @@ def delx(self): del self.__x check((1,2,3), vsize('') + self.P + 3*self.P) # type # static type: PyTypeObject - fmt = 'P2nPI13Pl4Pn9Pn12PIPc' + fmt = 'P2nPI13Pl4Pn9Pn12PI2Pc' s = vsize(fmt) check(int, s) typeid = 'n' if support.Py_GIL_DISABLED else '' @@ -1870,7 +1981,10 @@ class S(set): check(S(), set(), '3P') class FS(frozenset): __slots__ = 'a', 'b', 'c' - check(FS(), frozenset(), '3P') + + class mytuple(tuple): + pass + check(FS([mytuple()]), frozenset([mytuple()]), '3P') from collections import OrderedDict class OD(OrderedDict): __slots__ = 'a', 'b', 'c' @@ -1883,7 +1997,7 @@ def test_pythontypes(self): check = self.check_sizeof # _ast.AST import _ast - check(_ast.AST(), size('P')) + check(_ast.Module(), size('3P')) try: raise TypeError except TypeError as e: @@ -1894,10 +2008,16 @@ def test_pythontypes(self): # symtable entry # XXX # sys.flags - # FIXME: The +3 is for the 'gil', 'thread_inherit_context' and - # 'context_aware_warnings' flags and will not be necessary once - # gh-122575 is fixed - check(sys.flags, vsize('') + self.P + self.P * (3 + len(sys.flags))) + # FIXME: The non_sequence_fields adjustment is for these flags: + # - 'gil' + # - 'thread_inherit_context' + # - 'context_aware_warnings' + # - 'lazy_imports' + # Not needing to increment this every time we add a new field + # per GH-122575 would be nice... + # Q: What is the actual point of this sys.flags C size derived from PyStructSequence_Field array assertion? + non_sequence_fields = 4 + check(sys.flags, vsize('') + self.P + self.P * (non_sequence_fields + len(sys.flags))) def test_asyncgen_hooks(self): old = sys.get_asyncgen_hooks() @@ -1962,7 +2082,8 @@ def tearDown(self): test.support.reap_children() def _run_remote_exec_test(self, script_code, python_args=None, env=None, - prologue='', + python_executable=None, prologue='', + after_ready=None, script_path=os_helper.TESTFN + '_remote.py'): # Create the script that will be remotely executed self.addCleanup(os_helper.unlink, script_path) @@ -2010,7 +2131,10 @@ def _run_remote_exec_test(self, script_code, python_args=None, env=None, ''') # Start the target process and capture its output - cmd = [sys.executable] + if python_executable is None: + python_executable = sys.executable + + cmd = [python_executable] if python_args: cmd.extend(python_args) cmd.append(target) @@ -2035,6 +2159,9 @@ def _run_remote_exec_test(self, script_code, python_args=None, env=None, response = client_socket.recv(1024) self.assertEqual(response, b"ready") + if after_ready is not None: + after_ready(proc) + # Try remote exec on the target process sys.remote_exec(proc.pid, script_path) @@ -2057,6 +2184,19 @@ def _run_remote_exec_test(self, script_code, python_args=None, env=None, proc.terminate() proc.wait(timeout=SHORT_TIMEOUT) + def _run_remote_exec_with_deleted_mapping(self, deleted_path, **kwargs): + def delete_loaded_mapping(proc): + os_helper.unlink(deleted_path) + with open(f'/proc/{proc.pid}/maps', encoding='utf-8') as maps: + self.assertIn(f'{deleted_path} (deleted)', maps.read()) + + script = 'print("Remote script executed successfully!")' + returncode, stdout, stderr = self._run_remote_exec_test( + script, after_ready=delete_loaded_mapping, **kwargs) + self.assertEqual(returncode, 0) + self.assertIn(b"Remote script executed successfully!", stdout) + self.assertEqual(stderr, b"") + def test_remote_exec(self): """Test basic remote exec functionality""" script = 'print("Remote script executed successfully!")' @@ -2183,6 +2323,74 @@ def test_remote_exec_invalid_script_path(self): with self.assertRaises(OSError): sys.remote_exec(os.getpid(), "invalid_script_path") + @unittest.skipUnless(sys.platform == 'linux', 'Linux-only regression test') + @unittest.skipUnless( + sysconfig.get_config_var('Py_ENABLE_SHARED') == 1, + 'requires a shared libpython build') + def test_remote_exec_deleted_libpython(self): + """Test remote exec when the target libpython was deleted.""" + build_dir = sysconfig.get_config_var('abs_builddir') + ldlibrary = sysconfig.get_config_var('LDLIBRARY') + instsoname = sysconfig.get_config_var('INSTSONAME') + if not build_dir or not ldlibrary or not instsoname: + self.skipTest('cannot determine shared libpython location') + + source_libpython = os.path.join(build_dir, instsoname) + if not os.path.exists(source_libpython): + self.skipTest(f'{source_libpython!r} does not exist') + + with os_helper.temp_dir() as lib_dir: + copied_libpython = os.path.join(lib_dir, instsoname) + shutil.copy2(source_libpython, copied_libpython) + if ldlibrary != instsoname: + os.symlink(instsoname, os.path.join(lib_dir, ldlibrary)) + + env = os.environ.copy() + ld_library_path = env.get('LD_LIBRARY_PATH') + env['LD_LIBRARY_PATH'] = lib_dir if not ld_library_path else ( + lib_dir + os.pathsep + ld_library_path) + + self._run_remote_exec_with_deleted_mapping(copied_libpython, + env=env) + + @unittest.skipUnless(sys.platform == 'linux', 'Linux-only regression test') + @unittest.skipUnless( + sysconfig.get_config_var('Py_ENABLE_SHARED') == 0, + 'requires a static Python build') + def test_remote_exec_deleted_static_executable(self): + """Test remote exec when the target static executable was deleted.""" + build_dir = sysconfig.get_config_var('abs_builddir') + stdlib_dir = os.path.dirname(os.path.abspath(os.__file__)) + if not build_dir or not os.path.isdir(stdlib_dir): + self.skipTest('cannot determine build-tree locations') + + pybuilddir_txt = os.path.join(build_dir, 'pybuilddir.txt') + if not os.path.exists(pybuilddir_txt): + self.skipTest(f'{pybuilddir_txt!r} does not exist') + + with open(pybuilddir_txt, encoding='utf-8') as pybuilddir_file: + pybuilddir = pybuilddir_file.read().strip() + source_ext_dir = os.path.join(build_dir, pybuilddir) + if not os.path.isdir(source_ext_dir): + self.skipTest(f'{source_ext_dir!r} does not exist') + + with os_helper.temp_dir() as copied_root: + copied_build_dir = os.path.join(copied_root, 'build') + copied_pybuilddir = os.path.join(copied_build_dir, pybuilddir) + os.makedirs(os.path.dirname(copied_pybuilddir)) + os.symlink(stdlib_dir, os.path.join(copied_root, 'Lib')) + os.symlink(source_ext_dir, copied_pybuilddir) + shutil.copy2(pybuilddir_txt, + os.path.join(copied_build_dir, 'pybuilddir.txt')) + + copied_python = os.path.join(copied_build_dir, + os.path.basename(sys.executable)) + shutil.copy2(sys.executable, copied_python) + + self._run_remote_exec_with_deleted_mapping( + copied_python, python_args=['-S'], + python_executable=copied_python) + def test_remote_exec_in_process_without_debug_fails_envvar(self): """Test remote exec in a process without remote debugging enabled""" script = os_helper.TESTFN + '_remote.py' @@ -2247,9 +2455,10 @@ def frame_2_jit(expected: bool) -> None: def frame_3_jit() -> None: # JITs just before the last loop: - for i in range(_testinternalcapi.TIER2_THRESHOLD + 1): + # 1 extra iteration for tracing. + for i in range(_testinternalcapi.TIER2_THRESHOLD + 2): # Careful, doing this in the reverse order breaks tracing: - expected = {enabled} and i == _testinternalcapi.TIER2_THRESHOLD + expected = {enabled} and i >= _testinternalcapi.TIER2_THRESHOLD assert sys._jit.is_active() is expected frame_2_jit(expected) assert sys._jit.is_active() is expected diff --git a/Lib/test/test_sys_setprofile.py b/Lib/test/test_sys_setprofile.py index 18607a733ce..a22b728b569 100644 --- a/Lib/test/test_sys_setprofile.py +++ b/Lib/test/test_sys_setprofile.py @@ -481,7 +481,6 @@ def f(): sys.setprofile(lambda *args: None) f() - @unittest.expectedFailure # TODO: RUSTPYTHON def test_method_with_c_function(self): # gh-122029 # When we have a PyMethodObject whose im_func is a C function, we diff --git a/Lib/test/test_sys_settrace.py b/Lib/test/test_sys_settrace.py index 640240935de..a5e7bbbfad5 100644 --- a/Lib/test/test_sys_settrace.py +++ b/Lib/test/test_sys_settrace.py @@ -360,6 +360,8 @@ class TraceTestCase(unittest.TestCase): # Disable gc collection when tracing, otherwise the # deallocators may be traced as well. def setUp(self): + if os.environ.get('PYTHON_UOPS_OPTIMIZE') == '0': + self.skipTest("Line tracing behavior differs when JIT optimizer is disabled") self.using_gc = gc.isenabled() gc.disable() self.addCleanup(sys.settrace, sys.gettrace()) @@ -664,21 +666,18 @@ async def f(): (-2, 'line'), (-1, 'line'), (-1, 'return'), - (1, 'exception'), (2, 'line'), (1, 'line'), (-1, 'call'), (-2, 'line'), (-1, 'line'), (-1, 'return'), - (1, 'exception'), (2, 'line'), (1, 'line'), (-1, 'call'), (-2, 'line'), (-1, 'line'), (-1, 'return'), - (1, 'exception'), (2, 'line'), (1, 'line'), (-1, 'call'), @@ -1799,9 +1798,6 @@ def compare_events(self, line_offset, events, expected_events): def make_tracer(): return Tracer(trace_line_events=False) - def test_12_tighterloop(self): - TraceTestCase.test_12_tighterloop(self) - @support.cpython_only class TraceOpcodesTestCase(TraceTestCase): diff --git a/Lib/test/test_sysconfig.py b/Lib/test/test_sysconfig.py index 9502e2dead5..18bfe7ce6ea 100644 --- a/Lib/test/test_sysconfig.py +++ b/Lib/test/test_sysconfig.py @@ -1,3 +1,4 @@ +import itertools import platform import re import unittest @@ -7,6 +8,7 @@ import shutil import json import textwrap +from unittest.mock import patch from copy import copy from test import support @@ -20,7 +22,8 @@ ) from test.support.import_helper import import_module from test.support.os_helper import (TESTFN, unlink, skip_unless_symlink, - change_cwd) + change_cwd, temp_dir, + EnvironmentVarGuard) from test.support.venv import VirtualEnvironmentMixin import sysconfig @@ -28,11 +31,10 @@ get_path, get_path_names, _INSTALL_SCHEMES, get_default_scheme, get_scheme_names, get_config_var, _expand_vars, _get_preferred_schemes, - is_python_build, _PROJECT_BASE) + is_python_build, _PROJECT_BASE, parse_config_h) from sysconfig.__main__ import _main, _parse_makefile, _get_pybuilddir, _get_json_data_name import _imp import _osx_support -import _sysconfig HAS_USER_BASE = sysconfig._HAS_USER_BASE @@ -249,19 +251,15 @@ def test_get_platform(self): self.assertIsInstance(actual_platform, str) self.assertTrue(actual_platform) - # windows XP, 32bits + # Windows os.name = 'nt' - sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' - '[MSC v.1310 32 bit (Intel)]') - sys.platform = 'win32' - self.assertEqual(get_platform(), 'win32') - - # windows XP, amd64 - os.name = 'nt' - sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' - '[MSC v.1310 32 bit (Amd64)]') - sys.platform = 'win32' - self.assertEqual(get_platform(), 'win-amd64') + with patch('_sysconfig.get_platform', create=True, return_value='win32'): + self.assertEqual(get_platform(), 'win32') + with patch('_sysconfig.get_platform', create=True, return_value='win-amd64'): + self.assertEqual(get_platform(), 'win-amd64') + sys.platform = 'test-plaform' + with patch('_sysconfig.get_platform', create=True, return_value=None): + self.assertEqual(get_platform(), 'test-plaform') # macbook os.name = 'posix' @@ -463,6 +461,15 @@ def test_soabi(self): soabi = sysconfig.get_config_var('SOABI') self.assertIn(soabi, _imp.extension_suffixes()[0]) + @unittest.skipIf(not _imp.extension_suffixes(), "stub loader has no suffixes") + @unittest.skipIf(sys.platform == "win32", "Does not apply to Windows") + @unittest.skipIf(sysconfig.get_config_var('SOABI_PLATFORM') == 0, + "SOABI_PLATFORM is undefined") + def test_soabi_platform(self): + soabi_platform = sysconfig.get_config_var('SOABI_PLATFORM') + soabi = sysconfig.get_config_var('SOABI') + self.assertIn(soabi_platform, soabi) + @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: Expected str, not NoneType def test_library(self): library = sysconfig.get_config_var('LIBRARY') @@ -584,6 +591,12 @@ def test_linux_ext_suffix(self): expected_suffixes = 'x86_64-linux-gnu.so', 'x86_64-linux-musl.so' self.assertEndsWith(suffix, expected_suffixes) + @unittest.skipIf(sysconfig.get_config_var('PY_BUILTIN_HASHLIB_HASHES') is None, + 'PY_BUILTIN_HASHLIB_HASHES required for this test') + def test_PY_BUILTIN_HASHLIB_HASHES_in_vars(self): + vars = sysconfig.get_config_vars() + self.assertFalse(vars['PY_BUILTIN_HASHLIB_HASHES'].startswith('"')) + @unittest.skipUnless(sys.platform == 'android', 'Android-specific test') def test_android_ext_suffix(self): machine = platform.machine() @@ -755,6 +768,139 @@ def test_sysconfig_config_vars_no_prefix_cache(self): self.assertEqual(config_vars['exec_prefix'], sys.exec_prefix) self.assertEqual(config_vars['platbase'], sys.exec_prefix) + @unittest.skipUnless(os.name == 'posix', 'python-config.sh is POSIX only') + @unittest.skipIf(is_wasi, "Incompatible with WASI mapdir and OOT builds") + @unittest.skipIf(is_android or is_apple_mobile, + 'Android and iOS do not ship python-config') + @requires_subprocess() + def test_python_config_sh_prefix_special_characters(self): + # gh-159819: the shell variant of python-config must report the + # directory it was installed to even if that path contains spaces or + # characters special to the shell, sed or echo. + if is_python_build(): + script = os.path.join(_PROJECT_BASE, 'python-config') + else: + ldversion = get_config_var('LDVERSION') + script = os.path.join(os.path.dirname(sys.executable), + f'python{ldversion}-config') + if not os.path.isfile(script): + self.skipTest(f'{script!r} does not exist') + with open(script, encoding='utf-8') as f: + if f.readline().rstrip() != '#!/bin/sh': + self.skipTest('python-config is not the shell script variant') + + with open(script, encoding='utf-8') as f: + script_text = f.read() + makefile_vars = _parse_makefile(sysconfig.get_makefile_filename()) + configured_prefix = makefile_vars['prefix'] + + def check(script_copy, option, expected): + proc = subprocess.run(['/bin/sh', script_copy, option], + capture_output=True, text=True) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertEqual(proc.stdout.rstrip('\n'), expected) + self.assertEqual(proc.stderr, '') + + # '#', '&' and '\' were special to the sed replacement, and '\c' makes + # some echo implementations stop printing. + names = ['path with spaces', 'path#with&', r'back\slash\cdir'] + # The configured prefix is also matched literally. Simulate a build + # configured with special characters in its prefix by substituting + # them into a copy of the script. + fake_prefixes = [None] + if configured_prefix != '/': + fake_prefixes.append('/conf#with&special\\chars') + for name, fake_prefix in itertools.product(names, fake_prefixes): + with (self.subTest(name=name, configured_prefix=fake_prefix), + temp_dir() as tmpdir): + prefix = os.path.realpath(os.path.join(tmpdir, name)) + bindir = os.path.join(prefix, 'bin') + os.mkdir(prefix) + os.mkdir(bindir) + script_copy = os.path.join(bindir, 'python-config') + text = script_text + if fake_prefix is not None: + text = text.replace(configured_prefix, fake_prefix) + with open(script_copy, 'w', encoding='utf-8') as f: + f.write(text) + + check(script_copy, '--prefix', prefix) + check(script_copy, '--exec-prefix', prefix) + + # The script rewrites the configured include directory by + # replacing the configured prefix with the actual one. + includedir = makefile_vars['INCLUDEDIR'].replace( + configured_prefix, prefix, 1) + incdir = os.path.join(includedir, 'python{VERSION}{ABIFLAGS}' + .format_map(makefile_vars)) + check(script_copy, '--includes', f'-I{incdir} -I{incdir}') + + def test_parse_config_h(self): + config = textwrap.dedent(''' + #ifndef Py_PYCONFIG_H + #define Py_PYCONFIG_H + + /* C comment */ + + #define ALIGNOF_LONG 8 + #define HAVE_ACCEPT 1 + #define _Py_HAVE_COSPI 1 + #define INVALID_NUMBER abc + #define ALT_SOABI "cpython-316t-x86_64-linux-gnu" + + // Undef macros must be written as "/* #undef NAME */": + // name must be valid and there is not value. + /* #undef ANDROID_API_LEVEL */ + #undef IGNORE_UNDEF + /* #undef IGNORE_VALUE 1 */ + + # _ALWAYS_STR: don't convert values to an integer, + # but quotes are removed + #define IPHONEOS_DEPLOYMENT_TARGET "13.0" + #define MACOSX_DEPLOYMENT_TARGET 10 + + // Spaces are tolerated after the name, not before + #define SPACES_AFTER 1 + #define IGNORED_SPACES_BEFORE 1 + + // Ignore macro without value + #define IGNORE_NO_VALUE + + // Ignore macros with an invalid name + #define _PRIVATE_IGNORED 1 + #define aLOWER_IGNORED 1 + #define 123IGNORED 1 + #define INVALID-NAME 1 + #define INVALID#NAME 1 + #define NONASCII_NAME_é 1 + + // Ignore single letter names + #define A 1 + /* #undef A */ + + #endif /*Py_PYCONFIG_H*/ + ''') + + filename = TESTFN + self.addCleanup(unlink, filename) + with open(filename, "w", encoding="utf-8") as fp: + fp.write(config) + vars = {} + with open(filename, encoding="utf-8") as fp: + parse_config_h(fp, vars) + expected = { + 'ALIGNOF_LONG': 8, + 'HAVE_ACCEPT': 1, + '_Py_HAVE_COSPI': 1, + 'INVALID_NUMBER': 'abc', + 'ALT_SOABI': 'cpython-316t-x86_64-linux-gnu', + 'ANDROID_API_LEVEL': 0, + 'IPHONEOS_DEPLOYMENT_TARGET': '13.0', + 'MACOSX_DEPLOYMENT_TARGET': '10', # str, not int + 'SPACES_AFTER': 1, + } + self.assertEqual(vars, expected) + class MakefileTests(unittest.TestCase): @@ -776,8 +922,13 @@ def test_parse_makefile(self): print("var3=42", file=makefile) print("var4=$/invalid", file=makefile) print("var5=dollar$$5", file=makefile) - print("var6=${var3}/lib/python3.5/config-$(VAR2)$(var5)" + print("var6=${var7}/lib/python3.5/config-$(VAR2)$(var5)" "-x86_64-linux-gnu", file=makefile) + print("var7=${var3}", file=makefile) + print("var8=$$(var3)", file=makefile) + print("var9=$(var10)(var3)", file=makefile) + print("var10=$$", file=makefile) + print("var11=$${ORIGIN}${var5}", file=makefile) vars = _parse_makefile(TESTFN) self.assertEqual(vars, { 'var1': 'ab42', @@ -786,6 +937,74 @@ def test_parse_makefile(self): 'var4': '$/invalid', 'var5': 'dollar$5', 'var6': '42/lib/python3.5/config-b42dollar$5-x86_64-linux-gnu', + 'var7': 42, + 'var8': '$(var3)', + 'var9': '$(var3)', + 'var10': '$', + 'var11': '${ORIGIN}dollar$5', + }) + + def _test_parse_makefile_recursion(self): + self.addCleanup(unlink, TESTFN) + with open(TESTFN, "w") as makefile: + print("var1=var1=$(var1)", file=makefile) + print("var2=var3=$(var3)", file=makefile) + print("var3=var2=$(var2)", file=makefile) + vars = _parse_makefile(TESTFN) + self.assertEqual(vars, { + 'var1': 'var1=', + 'var2': 'var3=var2=', + 'var3': 'var2=', + }) + + def test_parse_makefile_renamed_vars(self): + self.addCleanup(unlink, TESTFN) + with open(TESTFN, "w") as makefile: + print("var1=$(CFLAGS)", file=makefile) + print("PY_CFLAGS=-Wall $(CPPFLAGS)", file=makefile) + print("PY_LDFLAGS=-lm", file=makefile) + print("var2=$(LDFLAGS)", file=makefile) + print("var3=$(CPPFLAGS)", file=makefile) + with EnvironmentVarGuard() as env: + env.clear() + vars = _parse_makefile(TESTFN) + self.assertEqual(vars, { + 'var1': '-Wall', + 'CFLAGS': '-Wall', + 'PY_CFLAGS': '-Wall', + 'LDFLAGS': '-lm', + 'PY_LDFLAGS': '-lm', + 'var2': '-lm', + 'var3': '', + }) + + def test_parse_makefile_keep_unresolved(self): + self.addCleanup(unlink, TESTFN) + with open(TESTFN, "w") as makefile: + print("var1=value", file=makefile) + print("var2=$/", file=makefile) + print("var3=$/$(var1)", file=makefile) + print("var4=var5=$(var5)", file=makefile) + print("var5=$/$(var1)", file=makefile) + print("var6=$(var1)$/", file=makefile) + print("var7=var8=$(var8)", file=makefile) + print("var8=$(var1)$/", file=makefile) + vars = _parse_makefile(TESTFN) + self.assertEqual(vars, { + 'var1': 'value', + 'var2': '$/', + 'var3': '$/value', + 'var4': 'var5=$/value', + 'var5': '$/value', + 'var6': 'value$/', + 'var7': 'var8=value$/', + 'var8': 'value$/', + }) + vars = _parse_makefile(TESTFN, keep_unresolved=False) + self.assertEqual(vars, { + 'var1': 'value', + 'var4': 'var5=', + 'var7': 'var8=', }) diff --git a/Lib/test/test_syslog.py b/Lib/test/test_syslog.py index 54db80fa9df..e6e3ccab35f 100644 --- a/Lib/test/test_syslog.py +++ b/Lib/test/test_syslog.py @@ -142,6 +142,29 @@ def test_subinterpreter_closelog(self): finally: syslog.closelog() + @threading_helper.requires_working_threading() + def test_subinterpreter_concurrent_syslog(self): + # gh-158929: This used to crash. + from concurrent import interpreters + + interp = interpreters.create() + try: + def in_interpreter(): + import syslog + + for _ in range(40000): + try: + syslog.syslog('my hovercraft is full of eels') + except RuntimeError: + pass + thread = interp.call_in_thread(in_interpreter) + for i in range(40000): + syslog.openlog(f"python{i}") + syslog.closelog() + thread.join() + finally: + interp.close() + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_tabnanny.py b/Lib/test/test_tabnanny.py index d7a77eb26e4..85e3e76e900 100644 --- a/Lib/test/test_tabnanny.py +++ b/Lib/test/test_tabnanny.py @@ -3,19 +3,18 @@ Glossary: * errored : Whitespace related problems present in file. """ -from unittest import TestCase, mock + +from unittest import TestCase, main, mock import errno import os +import sys import tabnanny import tokenize import tempfile import textwrap -from test.support import (captured_stderr, captured_stdout, script_helper, - findfile) +from test.support import captured_stderr, captured_stdout, script_helper from test.support.os_helper import unlink -import unittest # XXX: RUSTPYTHON; importing to be able to skip tests - SOURCE_CODES = { "incomplete_expression": ( @@ -217,7 +216,6 @@ def test_when_tokenize_tokenerror(self): with self.assertRaises(SystemExit): self.verify_tabnanny_check(file_path, err=err) - @unittest.expectedFailure # TODO: RUSTPYTHON; A python source code file eligible for raising `tabnanny.NannyNag`. def test_when_nannynag_error_verbose(self): """A python source code file eligible for raising `tabnanny.NannyNag`. @@ -231,7 +229,6 @@ def test_when_nannynag_error_verbose(self): tabnanny.verbose = 1 self.verify_tabnanny_check(file_path, out=out) - @unittest.expectedFailure # TODO: RUSTPYTHON; A python source code file eligible for raising `tabnanny.NannyNag`. def test_when_nannynag_error(self): """A python source code file eligible for raising `tabnanny.NannyNag`.""" with TemporaryPyFile(SOURCE_CODES["nannynag_errored"]) as file_path: @@ -331,8 +328,7 @@ def test_with_error_free_file(self): def test_command_usage(self): """Should display usage on no arguments.""" - path = findfile('tabnanny.py') - stderr = f"Usage: {path} [-v] file_or_directory ..." + stderr = f"Usage: {sys.executable} -m tabnanny [-v] file_or_directory ..." self.validate_cmd(stderr=stderr, expect_failure=True) def test_quiet_flag(self): @@ -341,7 +337,6 @@ def test_quiet_flag(self): stdout = f"{file_path}\n" self.validate_cmd("-q", file_path, stdout=stdout) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_verbose_mode(self): """Should display more error information if verbose mode is on.""" with TemporaryPyFile(SOURCE_CODES["nannynag_errored"]) as path: @@ -350,7 +345,6 @@ def test_verbose_mode(self): ).strip() self.validate_cmd("-v", path, stdout=stdout, partial=True) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_double_verbose_mode(self): """Should display detailed error information if double verbose is on.""" with TemporaryPyFile(SOURCE_CODES["nannynag_errored"]) as path: @@ -358,3 +352,17 @@ def test_double_verbose_mode(self): "offending line: '\\tprint(\"world\")'" ).strip() self.validate_cmd("-vv", path, stdout=stdout, partial=True) + + +class TestModule(TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(tabnanny, "__version__") + self.assertEqual(cm.filename, __file__) + + +if __name__ == "__main__": + main() diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py index f3b61d9fbad..646112f184b 100644 --- a/Lib/test/test_tarfile.py +++ b/Lib/test/test_tarfile.py @@ -10,6 +10,7 @@ import re import warnings import stat +import time import unittest import unittest.mock @@ -253,6 +254,19 @@ def test_add_dir_getmember(self): self.add_dir_and_getmember('bar') self.add_dir_and_getmember('a'*101) + def test_extract_name_with_trailing_slash(self): + # gh-127636: './mydir/' is deliberately a regular-file member + # (REGTYPE, not DIRTYPE) whose stored name ends in a slash. It + # extracts as a file. Do not "fix" this by setting DIRTYPE; the + # trailing-slash name on a non-directory is what is being tested. + with tarfile.open(tmpname, 'w') as tar: + tar.addfile(tarfile.TarInfo('./mydir/')) + with os_helper.temp_dir() as tmpdir, tarfile.open(tmpname) as tar: + names = tar.getnames() + self.assertEqual(names, ['./mydir/']) + tar.extract(names[0], tmpdir, filter='fully_trusted') + self.assertTrue(os.path.isfile(os.path.join(tmpdir, 'mydir'))) + @unittest.skipUnless(hasattr(os, "getuid") and hasattr(os, "getgid"), "Missing getuid or getgid implementation") def add_dir_and_getmember(self, name): @@ -1366,6 +1380,37 @@ def test_sparse_file_01(self): def test_sparse_file_10(self): self._test_sparse_file("gnu/sparse-1.0") + def test_sparse_file_10_pax_size(self): + # gh-83869: when the pax header replaces the size field, the offset + # of the next header must be computed from the size of the data in + # the archive, not from the apparent size of the sparse file. + data = b"payload!" * 4 + realsize = 1 << 20 + smap = b"1\n%d\n%d\n" % (realsize - len(data), len(data)) + smap += b"\0" * (-len(smap) % tarfile.BLOCKSIZE) + + sparse = tarfile.TarInfo("sparse") + sparse.size = len(smap) + len(data) + sparse.pax_headers = { + "GNU.sparse.major": "1", + "GNU.sparse.minor": "0", + "GNU.sparse.name": "sparse", + "GNU.sparse.realsize": str(realsize), + "size": str(sparse.size), + } + buf = sparse.tobuf(tarfile.PAX_FORMAT) + buf += smap + data + b"\0" * (-len(data) % tarfile.BLOCKSIZE) + + last = tarfile.TarInfo("last") + last.size = len(data) + buf += last.tobuf(tarfile.PAX_FORMAT) + buf += data + b"\0" * (-len(data) % tarfile.BLOCKSIZE) + buf += b"\0" * (tarfile.BLOCKSIZE * 2) + + with tarfile.open(fileobj=io.BytesIO(buf)) as tar: + self.assertEqual(tar.getnames(), ["sparse", "last"]) + self.assertEqual(tar.extractfile("last").read(), data) + @staticmethod def _fs_supports_holes(): # Return True if the platform knows the st_blocks stat attribute and @@ -1418,6 +1463,31 @@ def test_pax_global_headers(self): finally: tar.close() + def test_offset_after_global_header(self): + # gh-83869: a global header is a member of its own, the member which + # follows it keeps the offset of its own header. + rec = b"30 comment=global header here\n" + glob = tarfile.TarInfo("././@PaxHeader") + glob.type = tarfile.XGLTYPE + glob.size = len(rec) + buf = glob.tobuf(tarfile.USTAR_FORMAT) + buf += rec + b"\0" * (-len(rec) % tarfile.BLOCKSIZE) + + member = tarfile.TarInfo("member") + data = b"hello\n" + member.size = len(data) + offset = len(buf) + buf += member.tobuf(tarfile.USTAR_FORMAT) + buf += data + b"\0" * (-len(data) % tarfile.BLOCKSIZE) + buf += b"\0" * (tarfile.BLOCKSIZE * 2) + + with tarfile.open(fileobj=io.BytesIO(buf)) as tar: + tarinfo = tar.getmember("member") + self.assertEqual(tarinfo.offset, offset) + self.assertEqual(tarinfo.pax_headers.get("comment"), + "global header here") + self.assertEqual(tar.extractfile(tarinfo).read(), data) + def test_pax_number_fields(self): # All following number fields are read from the pax header. tar = tarfile.open(tarname, encoding="iso8859-1") @@ -1646,6 +1716,22 @@ def test_symlink_size(self): finally: os_helper.unlink(path) + @os_helper.skip_unless_symlink + def test_symlink_target_normalization(self): + # Test for gh-151669. + path = os.path.join(TEMPDIR, "symlink") + target = "subdir/link/target" + os.symlink(target.replace("/", os.sep), path) + try: + tar = tarfile.open(tmpname, self.mode) + try: + tarinfo = tar.gettarinfo(path) + self.assertEqual(tarinfo.linkname, target) + finally: + tar.close() + finally: + os_helper.unlink(path) + def test_add_self(self): # Test for #1257255. dstname = os.path.abspath(tmpname) @@ -1904,6 +1990,57 @@ def test_source_directory_not_leaked(self): payload = pathlib.Path(tmpname).read_text(encoding='latin-1') assert os.path.dirname(tmpname) not in payload + def test_create_with_mtime(self): + tarfile.open(tmpname, self.mode, mtime=0).close() + with self.open(tmpname, 'r') as fobj: + fobj.read() + self.assertEqual(fobj.mtime, 0) + + def test_create_with_mtime_out_of_range(self): + # gh-133998: an mtime outside the gzip header's 32-bit range is + # stored as 0 rather than raising struct.error. + self.addCleanup(os_helper.unlink, tmpname) + for mtime in (-1, 2**32): + with self.subTest(mtime=mtime): + tarfile.open(tmpname, self.mode, mtime=mtime).close() + with self.open(tmpname, 'r') as fobj: + fobj.read() + self.assertEqual(fobj.mtime, 0) + + def test_create_with_mtime_at_boundary(self): + # gh-133998: the largest in-range mtime is preserved, not clamped. + mtime = 2**32 - 1 + tarfile.open(tmpname, self.mode, mtime=mtime).close() + with self.open(tmpname, 'r') as fobj: + fobj.read() + self.assertEqual(fobj.mtime, mtime) + + def test_create_with_out_of_range_clock(self): + # gh-133998: an out-of-range system clock (mtime defaulting to + # time.time()) is stored as 0 rather than raising struct.error. + for clock in (-1, 2**32): + with self.subTest(clock=clock): + with unittest.mock.patch('time.time', return_value=float(clock)): + tarfile.open(tmpname, self.mode).close() + with self.open(tmpname, 'r') as fobj: + fobj.read() + self.assertEqual(fobj.mtime, 0) + os_helper.unlink(tmpname) + + def test_create_with_float_mtime(self): + # gh-133998: a float mtime is truncated like gzip, not rejected. + tarfile.open(tmpname, self.mode, mtime=123456789.9).close() + with self.open(tmpname, 'r') as fobj: + fobj.read() + self.assertEqual(fobj.mtime, 123456789) + + def test_create_without_mtime(self): + before = int(time.time()) + tarfile.open(tmpname, self.mode).close() + after = int(time.time()) + with self.open(tmpname, 'r') as fobj: + fobj.read() + self.assertTrue(before <= fobj.mtime <= after) class Bz2StreamWriteTest(Bz2Test, StreamWriteTest): decompressor = bz2.BZ2Decompressor if bz2 else None @@ -2210,6 +2347,19 @@ def test_create_with_compresslevel(self): with tarfile.open(tmpname, 'r:gz', compresslevel=1) as tobj: pass + def test_create_with_mtime(self): + tarfile.open(tmpname, self.mode, mtime=0).close() + with self.open(tmpname, 'rb') as fobj: + fobj.read() + self.assertEqual(fobj.mtime, 0) + + def test_create_without_mtime(self): + before = int(time.time()) + tarfile.open(tmpname, self.mode).close() + after = int(time.time()) + with self.open(tmpname, 'r') as fobj: + fobj.read() + self.assertTrue(before <= fobj.mtime <= after) class Bz2CreateTest(Bz2Test, CreateTest): @@ -2872,7 +3022,7 @@ def test_useful_error_message_when_modules_missing(self): str(excinfo.exception), ) - @unittest.skipUnless(os_helper.can_symlink(), 'requires symlink support') + @os_helper.skip_unless_symlink @unittest.skipUnless(hasattr(os, 'chmod'), "missing os.chmod") @unittest.mock.patch('os.chmod') def test_deferred_directory_attributes_update(self, mock_chmod): @@ -3925,6 +4075,20 @@ def test_absolute(self): tarfile.AbsolutePathError, """['"].*escaped.evil['"] has an absolute path""") + def test_parent_dir_out_and_back(self): + # Test a member that leaves the destination and comes back. + # The containment check looks at the resolved path, which stays + # inside, but the intermediate directories are created from the + # name as given, which does not. + with ArchiveMaker() as arc: + arc.add(f'../escaped.evil/../{self.destdir.name}/sub/file', + content='content') + + for filter in 'tar', 'data': + with self.subTest(filter): + with self.check_context(arc.open(), filter): + self.expect_file('sub/file', content='content') + @symlink_test def test_parent_symlink(self): # Test interplaying symlinks @@ -3937,23 +4101,21 @@ def test_parent_symlink(self): arc.add('current', symlink_to='.') # effectively points to ./../ - arc.add('parent', symlink_to='current/..') + if self.dotdot_resolves_early and os_helper.can_symlink(): + arc.add('parent', symlink_to='current/../..') + else: + arc.add('parent', symlink_to='current/..') arc.add('parent/evil') if os_helper.can_symlink(): with self.check_context(arc.open(), 'fully_trusted'): - if self.raised_exception is not None: - # Windows will refuse to create a file that's a symlink to itself - # (and tarfile doesn't swallow that exception) - self.expect_exception(FileExistsError) - # The other cases will fail with this error too. - # Skip the rest of this test. - return + self.expect_file('current', symlink_to='.') + if self.dotdot_resolves_early: + self.expect_file('parent', symlink_to='current/../..') else: - self.expect_file('current', symlink_to='.') self.expect_file('parent', symlink_to='current/..') - self.expect_file('../evil') + self.expect_file('../evil') with self.check_context(arc.open(), 'tar'): self.expect_exception( @@ -4147,6 +4309,21 @@ def test_absolute_symlink(self): tarfile.AbsoluteLinkError, "'parent' is a link to an absolute path") + @symlink_test + @os_helper.skip_unless_symlink + def test_symlink_target_seperator_rewrite_on_windows(self): + with ArchiveMaker() as arc: + arc.add('link', symlink_to="relative/test/path") + + with self.check_context(arc.open(), 'fully_trusted'): + self.expect_file('link', type=tarfile.SYMTYPE) + link_path = os.path.normpath(self.destdir / "link") + link_target = os.readlink(link_path) + if os.name == "nt": + self.assertEqual(link_target, "relative\\test\\path") + else: + self.assertEqual(link_target, "relative/test/path") + def test_absolute_hardlink(self): # Test hardlink to an absolute path # Inspired by 'dirsymlink' in https://github.com/jwilk/traversal-archives @@ -4267,8 +4444,10 @@ def test_link_at_destination(self): t.linkname = '.' arc.tar_w.addfile(t) - with self.check_context(arc.open(), 'data'): - self.expect_exception(tarfile.OutsideDestinationError) + for filter in 'tar', 'data': + with self.subTest(name=name, filter=filter): + with self.check_context(arc.open(), filter): + self.expect_exception(tarfile.OutsideDestinationError) @symlink_test @os_helper.skip_unless_symlink @@ -4381,9 +4560,15 @@ def test_sneaky_hardlink_fallback(self): for filter in 'tar', 'fully_trusted': with self.subTest(filter), self.check_context(arc.open(), filter): if not os_helper.can_symlink(): - self.expect_file("a/t/dummy") - self.expect_file("b/") - self.expect_file("c/") + if filter == 'fully_trusted' or sys.platform == "win32": + self.expect_file("a/t/dummy") + self.expect_file("b/") + self.expect_file("c/") + else: + self.expect_exception( + tarfile.LinkFallbackError, + "link 'boom' would be extracted as a copy of " + + "'c/escape', which was rejected") else: self.expect_file("a/t/dummy") self.expect_file("b/") @@ -4415,6 +4600,24 @@ def test_sneaky_hardlink_fallback_deep(self): self.expect_file("a/b/s", symlink_to=os.path.join('..', 'escape')) self.expect_file("s", symlink_to=os.path.join('..', 'escape')) + @symlink_test + @os_helper.skip_unless_hardlink + def test_sneaky_hardlink_relocation(self): + with ArchiveMaker() as arc: + arc.add("a/escape", content="decoy") + arc.add("a/b/s", symlink_to=os.path.join("..", "escape")) + arc.add("s", hardlink_to=os.path.join("a", "b", "s")) + + for filter in 'data', 'tar': + with self.subTest(filter), self.check_context(arc.open(), filter): + self.expect_file("a/escape", content="decoy") + if os_helper.can_symlink(): + self.expect_file("a/b/s", symlink_to=os.path.join('..', 'escape')) + else: + self.expect_file("a/b/s", content="decoy") + self.expect_file("s", content="decoy") + self.assertFalse((self.destdir / "s").is_symlink()) + @symlink_test def test_exfiltration_via_symlink(self): # (CVE-2025-4138) @@ -4562,6 +4765,25 @@ def testing_filter(member, path): if os_helper.can_chmod(): self.assertFalse(path.stat().st_mode & stat.S_IWUSR) + @symlink_test + def test_extract_filters_target_none(self): + # Test that when extract() falls back to extracting (rather than + # linking) a hardlink target, the member is skipped if the filter + # returns None. + with ArchiveMaker() as arc: + arc.add('a/b/s', symlink_to='../escape') + arc.add('q', hardlink_to='a/b/s') + def filter_unsafe_members(member, path): + try: + return tarfile.data_filter(member, path) + except tarfile.FilterError as error: + return None + with self.check_context(arc.open(), filter_unsafe_members): + if os_helper.can_symlink(): + self.expect_file('a/b/s', symlink_to='../escape') + else: + self.expect_file('a/b/') # symlink is not extracted + def test_link_fallback_normalizes(self): # Make sure hardlink fallbacks work for non-normalized paths for all # filters @@ -5129,6 +5351,16 @@ def test_ignore_invalid_offset_headers(self): self.assertEqual(members[0].offset, expected_offset) +class TestModule(unittest.TestCase): + def test_deprecated_version(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'version' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(tarfile, "version") + self.assertEqual(cm.filename, __file__) + + def setUpModule(): os_helper.unlink(TEMPDIR) os.makedirs(TEMPDIR) diff --git a/Lib/test/test_tcl.py b/Lib/test/test_tcl.py new file mode 100644 index 00000000000..f6e49840d06 --- /dev/null +++ b/Lib/test/test_tcl.py @@ -0,0 +1,838 @@ +import unittest +import subprocess +import sys +import os +from test import support +from test.support import import_helper +from test.support import os_helper + +# Skip this test if the _tkinter module wasn't built. +_tkinter = import_helper.import_module('_tkinter') + +import tkinter +from tkinter import Tcl +from _tkinter import TclError + +try: + from _testcapi import INT_MAX, PY_SSIZE_T_MAX +except ImportError: + INT_MAX = PY_SSIZE_T_MAX = sys.maxsize + +tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.'))) + + +class TkinterTest(unittest.TestCase): + + def testFlattenLen(self): + # Object without length. + self.assertRaises(TypeError, _tkinter._flatten, True) + # Object with length, but not sequence. + self.assertRaises(TypeError, _tkinter._flatten, {}) + # Sequence or set, but not tuple or list. + # (issue44608: there were leaks in the following cases) + self.assertRaises(TypeError, _tkinter._flatten, 'string') + self.assertRaises(TypeError, _tkinter._flatten, {'set'}) + + +class TclTest(unittest.TestCase): + + def setUp(self): + self.interp = Tcl() + self.wantobjects = self.interp.tk.wantobjects() + + def passValue(self, value): + return self.interp.call('set', '_', value) + + def testEval(self): + tcl = self.interp + tcl.eval('set a 1') + self.assertEqual(tcl.eval('set a'),'1') + + def test_eval_null_in_result(self): + tcl = self.interp + self.assertEqual(tcl.eval('set a "a\\0b"'), 'a\x00b') + + def test_eval_surrogates_in_result(self): + tcl = self.interp + result = tcl.eval(r'set a "<\ud83d\udcbb>"') + if sys.platform == 'win32' and tcl_version >= (9, 0): + self.assertEqual('<\ud83d\udcbb>', result) + else: + self.assertEqual('<\U0001f4bb>', result) + + def testEvalException(self): + tcl = self.interp + self.assertRaises(TclError,tcl.eval,'set a') + + def testEvalException2(self): + tcl = self.interp + self.assertRaises(TclError,tcl.eval,'this is wrong') + + def test_eval_returns_tcl_obj(self): + tcl = self.interp.tk + tcl.eval(r'set a "\u20ac \ud83d\udcbb \0 \udcab"; regexp -about $a') + a = tcl.eval('set a') + expected = '\u20ac \U0001f4bb \0 \udced\udcb2\udcab' + self.assertEqual(a, expected) + + def testCall(self): + tcl = self.interp + tcl.call('set','a','1') + self.assertEqual(tcl.call('set','a'),'1') + + def test_call_passing_null(self): + tcl = self.interp + tcl.call('set', 'a', 'a\0b') # ASCII-only + self.assertEqual(tcl.getvar('a'), 'a\x00b') + self.assertEqual(tcl.call('set', 'a'), 'a\x00b') + self.assertEqual(tcl.eval('set a'), 'a\x00b') + + tcl.call('set', 'a', '\u20ac\0') # non-ASCII + self.assertEqual(tcl.getvar('a'), '\u20ac\x00') + self.assertEqual(tcl.call('set', 'a'), '\u20ac\x00') + self.assertEqual(tcl.eval('set a'), '\u20ac\x00') + + def testCallException(self): + tcl = self.interp + self.assertRaises(TclError,tcl.call,'set','a') + + def testCallException2(self): + tcl = self.interp + self.assertRaises(TclError,tcl.call,'this','is','wrong') + + def test_call_returns_tcl_obj(self): + tcl = self.interp.tk + tcl.eval(r'set a "\u20ac \ud83d\udcbb \0 \udcab"; regexp -about $a') + a = tcl.call('set', 'a') + expected = '\u20ac \U0001f4bb \0 \udced\udcb2\udcab' + if self.wantobjects: + self.assertEqual(str(a), expected) + self.assertEqual(a.string, expected) + self.assertEqual(a.typename, 'regexp') + else: + self.assertEqual(a, expected) + + def testSetVar(self): + tcl = self.interp + tcl.setvar('a','1') + self.assertEqual(tcl.eval('set a'),'1') + + def test_setvar_passing_null(self): + tcl = self.interp + tcl.setvar('a', 'a\0b') # ASCII-only + self.assertEqual(tcl.getvar('a'), 'a\x00b') + self.assertEqual(tcl.call('set', 'a'), 'a\x00b') + self.assertEqual(tcl.eval('set a'), 'a\x00b') + + tcl.setvar('a', '\u20ac\0') # non-ASCII + self.assertEqual(tcl.getvar('a'), '\u20ac\x00') + self.assertEqual(tcl.call('set', 'a'), '\u20ac\x00') + self.assertEqual(tcl.eval('set a'), '\u20ac\x00') + + def testSetVarArray(self): + tcl = self.interp + tcl.setvar('a(1)','1') + self.assertEqual(tcl.eval('set a(1)'),'1') + + def testGetVar(self): + tcl = self.interp + tcl.eval('set a 1') + self.assertEqual(tcl.getvar('a'),'1') + + def testGetVarArray(self): + tcl = self.interp + tcl.eval('set a(1) 1') + self.assertEqual(tcl.getvar('a(1)'),'1') + + def testGetVarException(self): + tcl = self.interp + self.assertRaises(TclError,tcl.getvar,'a') + + def testGetVarArrayException(self): + tcl = self.interp + self.assertRaises(TclError,tcl.getvar,'a(1)') + + def test_getvar_returns_tcl_obj(self): + tcl = self.interp.tk + tcl.eval(r'set a "\u20ac \ud83d\udcbb \0 \udcab"; regexp -about $a') + a = tcl.getvar('a') + expected = '\u20ac \U0001f4bb \0 \udced\udcb2\udcab' + if self.wantobjects: + self.assertEqual(str(a), expected) + self.assertEqual(a.string, expected) + self.assertEqual(a.typename, 'regexp') + else: + self.assertEqual(a, expected) + + def testUnsetVar(self): + tcl = self.interp + tcl.setvar('a',1) + self.assertEqual(tcl.eval('info exists a'),'1') + tcl.unsetvar('a') + self.assertEqual(tcl.eval('info exists a'),'0') + + def testUnsetVarArray(self): + tcl = self.interp + tcl.setvar('a(1)',1) + tcl.setvar('a(2)',2) + self.assertEqual(tcl.eval('info exists a(1)'),'1') + self.assertEqual(tcl.eval('info exists a(2)'),'1') + tcl.unsetvar('a(1)') + self.assertEqual(tcl.eval('info exists a(1)'),'0') + self.assertEqual(tcl.eval('info exists a(2)'),'1') + + def testUnsetVarException(self): + tcl = self.interp + self.assertRaises(TclError,tcl.unsetvar,'a') + + def get_integers(self): + return (0, 1, -1, + 2**31-1, -2**31, 2**31, -2**31-1, + 2**63-1, -2**63, 2**63, -2**63-1, + 2**1000, -2**1000) + + def test_getint(self): + tcl = self.interp.tk + for i in self.get_integers(): + self.assertEqual(tcl.getint(' %d ' % i), i) + self.assertEqual(tcl.getint(' %#o ' % i), i) + # Numbers starting with 0 are parsed as decimal in Tcl 9.0 + # and as octal in older versions. + self.assertEqual(tcl.getint((' %#o ' % i).replace('o', '')), + i if tcl_version < (9, 0) else int('%o' % i)) + self.assertEqual(tcl.getint(' %#x ' % i), i) + self.assertEqual(tcl.getint(42), 42) + self.assertRaises(TypeError, tcl.getint) + self.assertRaises(TypeError, tcl.getint, '42', '10') + self.assertRaises(TypeError, tcl.getint, b'42') + self.assertRaises(TypeError, tcl.getint, 42.0) + self.assertRaises(TclError, tcl.getint, 'a') + self.assertRaises((TypeError, ValueError, TclError), + tcl.getint, '42\0') + self.assertRaises((UnicodeEncodeError, ValueError, TclError), + tcl.getint, '42\ud800') + + def test_getdouble(self): + tcl = self.interp.tk + self.assertEqual(tcl.getdouble(' 42 '), 42.0) + self.assertEqual(tcl.getdouble(' 42.5 '), 42.5) + self.assertEqual(tcl.getdouble(42.5), 42.5) + self.assertEqual(tcl.getdouble(42), 42.0) + self.assertRaises(TypeError, tcl.getdouble) + self.assertRaises(TypeError, tcl.getdouble, '42.5', '10') + self.assertRaises(TypeError, tcl.getdouble, b'42.5') + self.assertRaises(TclError, tcl.getdouble, 'a') + self.assertRaises((TypeError, ValueError, TclError), + tcl.getdouble, '42.5\0') + self.assertRaises((UnicodeEncodeError, ValueError, TclError), + tcl.getdouble, '42.5\ud800') + + def test_getboolean(self): + tcl = self.interp.tk + self.assertIs(tcl.getboolean('on'), True) + self.assertIs(tcl.getboolean('1'), True) + self.assertIs(tcl.getboolean(42), True) + self.assertIs(tcl.getboolean(0), False) + self.assertRaises(TypeError, tcl.getboolean) + self.assertRaises(TypeError, tcl.getboolean, 'on', '1') + self.assertRaises(TypeError, tcl.getboolean, b'on') + self.assertRaises(TypeError, tcl.getboolean, 1.0) + self.assertRaises(TclError, tcl.getboolean, 'a') + self.assertRaises((TypeError, ValueError, TclError), + tcl.getboolean, 'on\0') + self.assertRaises((UnicodeEncodeError, ValueError, TclError), + tcl.getboolean, 'on\ud800') + + def testEvalFile(self): + tcl = self.interp + filename = os_helper.TESTFN_ASCII + self.addCleanup(os_helper.unlink, filename) + with open(filename, 'w') as f: + f.write("""set a 1 + set b 2 + set c [ expr $a + $b ] + """) + tcl.evalfile(filename) + self.assertEqual(tcl.eval('set a'),'1') + self.assertEqual(tcl.eval('set b'),'2') + self.assertEqual(tcl.eval('set c'),'3') + + def test_evalfile_null_in_result(self): + tcl = self.interp + filename = os_helper.TESTFN_ASCII + self.addCleanup(os_helper.unlink, filename) + with open(filename, 'w') as f: + f.write(""" + set a "a\0b" + set b "a\\0b" + """) + tcl.evalfile(filename) + self.assertEqual(tcl.eval('set a'), 'a\x00b') + self.assertEqual(tcl.eval('set b'), 'a\x00b') + + def test_evalfile_surrogates_in_result(self): + tcl = self.interp + encoding = tcl.call('encoding', 'system') + self.addCleanup(tcl.call, 'encoding', 'system', encoding) + tcl.call('encoding', 'system', 'utf-8') + + filename = os_helper.TESTFN_ASCII + self.addCleanup(os_helper.unlink, filename) + with open(filename, 'wb') as f: + f.write(b""" + set a "<\xed\xa0\xbd\xed\xb2\xbb>" + """) + if tcl_version >= (9, 0): + self.assertRaises(TclError, tcl.evalfile, filename) + else: + tcl.evalfile(filename) + self.assertEqual(tcl.eval('set a'), '<\U0001f4bb>') + + with open(filename, 'wb') as f: + f.write(b""" + set b "<\\ud83d\\udcbb>" + """) + tcl.evalfile(filename) + result = tcl.eval('set b') + if sys.platform == 'win32' and tcl_version >= (9, 0): + self.assertEqual('<\ud83d\udcbb>', result) + else: + self.assertEqual('<\U0001f4bb>', result) + + def testEvalFileException(self): + tcl = self.interp + filename = "doesnotexists" + try: + os.remove(filename) + except Exception as e: + pass + self.assertRaises(TclError,tcl.evalfile,filename) + + def testPackageRequireException(self): + tcl = self.interp + self.assertRaises(TclError,tcl.eval,'package require DNE') + + @unittest.skipUnless(sys.platform == 'win32', 'Requires Windows') + def testLoadWithUNC(self): + # Build a UNC path from the regular path. + # Something like + # \\%COMPUTERNAME%\c$\python27\python.exe + + fullname = os.path.abspath(sys.executable) + if fullname[1] != ':': + raise unittest.SkipTest('Absolute path should have drive part') + unc_name = r'\\%s\%s$\%s' % (os.environ['COMPUTERNAME'], + fullname[0], + fullname[3:]) + if not os.path.exists(unc_name): + raise unittest.SkipTest('Cannot connect to UNC Path') + + with os_helper.EnvironmentVarGuard() as env: + env.unset("TCL_LIBRARY") + stdout = subprocess.check_output( + [unc_name, '-c', 'import tkinter; print(tkinter)']) + + self.assertIn(b'tkinter', stdout) + + def test_exprstring(self): + tcl = self.interp + tcl.call('set', 'a', 3) + tcl.call('set', 'b', 6) + def check(expr, expected): + result = tcl.exprstring(expr) + self.assertEqual(result, expected) + self.assertIsInstance(result, str) + + self.assertRaises(TypeError, tcl.exprstring) + self.assertRaises(TypeError, tcl.exprstring, '8.2', '+6') + self.assertRaises(TypeError, tcl.exprstring, b'8.2 + 6') + self.assertRaises(TclError, tcl.exprstring, 'spam') + check('', '0') + check('8.2 + 6', '14.2') + check('3.1 + $a', '6.1') + check('2 + "$a.$b"', '5.6') + check('4*[llength "6 2"]', '8') + check('{word one} < "word $a"', '0') + check('4*2 < 7', '0') + check('hypot($a, 4)', '5.0') + check('5 / 4', '1') + check('5 / 4.0', '1.25') + check('5 / ( [string length "abcd"] + 0.0 )', '1.25') + check('20.0/5.0', '4.0') + check('"0x03" > "2"', '1') + check('[string length "a\xbd\u20ac"]', '3') + check(r'[string length "a\xbd\u20ac"]', '3') + check('"abc"', 'abc') + check('"a\xbd\u20ac"', 'a\xbd\u20ac') + check(r'"a\xbd\u20ac"', 'a\xbd\u20ac') + check(r'"a\0b"', 'a\x00b') + check('2**64', str(2**64)) + + def test_exprdouble(self): + tcl = self.interp + tcl.call('set', 'a', 3) + tcl.call('set', 'b', 6) + def check(expr, expected): + result = tcl.exprdouble(expr) + self.assertEqual(result, expected) + self.assertIsInstance(result, float) + + self.assertRaises(TypeError, tcl.exprdouble) + self.assertRaises(TypeError, tcl.exprdouble, '8.2', '+6') + self.assertRaises(TypeError, tcl.exprdouble, b'8.2 + 6') + self.assertRaises(TclError, tcl.exprdouble, 'spam') + check('', 0.0) + check('8.2 + 6', 14.2) + check('3.1 + $a', 6.1) + check('2 + "$a.$b"', 5.6) + check('4*[llength "6 2"]', 8.0) + check('{word one} < "word $a"', 0.0) + check('4*2 < 7', 0.0) + check('hypot($a, 4)', 5.0) + check('5 / 4', 1.0) + check('5 / 4.0', 1.25) + check('5 / ( [string length "abcd"] + 0.0 )', 1.25) + check('20.0/5.0', 4.0) + check('"0x03" > "2"', 1.0) + check('[string length "a\xbd\u20ac"]', 3.0) + check(r'[string length "a\xbd\u20ac"]', 3.0) + self.assertRaises(TclError, tcl.exprdouble, '"abc"') + check('2**64', float(2**64)) + + def test_exprlong(self): + tcl = self.interp + tcl.call('set', 'a', 3) + tcl.call('set', 'b', 6) + def check(expr, expected): + result = tcl.exprlong(expr) + self.assertEqual(result, expected) + self.assertIsInstance(result, int) + + self.assertRaises(TypeError, tcl.exprlong) + self.assertRaises(TypeError, tcl.exprlong, '8.2', '+6') + self.assertRaises(TypeError, tcl.exprlong, b'8.2 + 6') + self.assertRaises(TclError, tcl.exprlong, 'spam') + check('', 0) + check('8.2 + 6', 14) + check('3.1 + $a', 6) + check('2 + "$a.$b"', 5) + check('4*[llength "6 2"]', 8) + check('{word one} < "word $a"', 0) + check('4*2 < 7', 0) + check('hypot($a, 4)', 5) + check('5 / 4', 1) + check('5 / 4.0', 1) + check('5 / ( [string length "abcd"] + 0.0 )', 1) + check('20.0/5.0', 4) + check('"0x03" > "2"', 1) + check('[string length "a\xbd\u20ac"]', 3) + check(r'[string length "a\xbd\u20ac"]', 3) + self.assertRaises(TclError, tcl.exprlong, '"abc"') + self.assertRaises(TclError, tcl.exprlong, '2**64') + + def test_exprboolean(self): + tcl = self.interp + tcl.call('set', 'a', 3) + tcl.call('set', 'b', 6) + def check(expr, expected): + result = tcl.exprboolean(expr) + self.assertEqual(result, expected) + self.assertIsInstance(result, int) + self.assertNotIsInstance(result, bool) + + self.assertRaises(TypeError, tcl.exprboolean) + self.assertRaises(TypeError, tcl.exprboolean, '8.2', '+6') + self.assertRaises(TypeError, tcl.exprboolean, b'8.2 + 6') + self.assertRaises(TclError, tcl.exprboolean, 'spam') + check('', False) + for value in ('0', 'false', 'no', 'off'): + check(value, False) + check('"%s"' % value, False) + check('{%s}' % value, False) + for value in ('1', 'true', 'yes', 'on'): + check(value, True) + check('"%s"' % value, True) + check('{%s}' % value, True) + check('8.2 + 6', True) + check('3.1 + $a', True) + check('2 + "$a.$b"', True) + check('4*[llength "6 2"]', True) + check('{word one} < "word $a"', False) + check('4*2 < 7', False) + check('hypot($a, 4)', True) + check('5 / 4', True) + check('5 / 4.0', True) + check('5 / ( [string length "abcd"] + 0.0 )', True) + check('20.0/5.0', True) + check('"0x03" > "2"', True) + check('[string length "a\xbd\u20ac"]', True) + check(r'[string length "a\xbd\u20ac"]', True) + self.assertRaises(TclError, tcl.exprboolean, '"abc"') + check('2**64', True) + + def test_booleans(self): + tcl = self.interp + def check(expr, expected): + result = tcl.call('expr', expr) + if tcl.wantobjects(): + self.assertEqual(result, expected) + self.assertIsInstance(result, int) + else: + self.assertIn(result, (expr, str(int(expected)))) + self.assertIsInstance(result, str) + check('true', True) + check('yes', True) + check('on', True) + check('false', False) + check('no', False) + check('off', False) + check('1 < 2', True) + check('1 > 2', False) + + def test_expr_bignum(self): + tcl = self.interp + for i in self.get_integers(): + result = tcl.call('expr', str(i)) + if self.wantobjects: + self.assertEqual(result, i) + self.assertIsInstance(result, int) + else: + self.assertEqual(result, str(i)) + self.assertIsInstance(result, str) + + def test_passing_values(self): + passValue = self.passValue + + self.assertEqual(passValue(True), True if self.wantobjects else '1') + self.assertEqual(passValue(False), False if self.wantobjects else '0') + self.assertEqual(passValue('string'), 'string') + self.assertEqual(passValue('string\u20ac'), 'string\u20ac') + self.assertEqual(passValue('string\U0001f4bb'), 'string\U0001f4bb') + self.assertEqual(passValue('str\x00ing'), 'str\x00ing') + self.assertEqual(passValue('str\x00ing\xbd'), 'str\x00ing\xbd') + self.assertEqual(passValue('str\x00ing\u20ac'), 'str\x00ing\u20ac') + self.assertEqual(passValue('str\x00ing\U0001f4bb'), + 'str\x00ing\U0001f4bb') + if sys.platform != 'win32': + self.assertEqual(passValue('<\udce2\udc82\udcac>'), + '<\u20ac>') + self.assertEqual(passValue('<\udced\udca0\udcbd\udced\udcb2\udcbb>'), + '<\U0001f4bb>') + self.assertEqual(passValue(b'str\x00ing'), + b'str\x00ing' if self.wantobjects else 'str\x00ing') + self.assertEqual(passValue(b'str\xc0\x80ing'), + b'str\xc0\x80ing' if self.wantobjects else 'str\xc0\x80ing') + self.assertEqual(passValue(b'str\xbding'), + b'str\xbding' if self.wantobjects else 'str\xbding') + for i in self.get_integers(): + self.assertEqual(passValue(i), i if self.wantobjects else str(i)) + for f in (0.0, 1.0, -1.0, 1/3, + sys.float_info.min, sys.float_info.max, + -sys.float_info.min, -sys.float_info.max): + if self.wantobjects: + self.assertEqual(passValue(f), f) + else: + self.assertEqual(float(passValue(f)), f) + if self.wantobjects: + f = passValue(float('nan')) + self.assertNotEqual(f, f) + self.assertEqual(passValue(float('inf')), float('inf')) + self.assertEqual(passValue(-float('inf')), -float('inf')) + else: + self.assertEqual(float(passValue(float('inf'))), float('inf')) + self.assertEqual(float(passValue(-float('inf'))), -float('inf')) + # XXX NaN representation can be not parsable by float() + self.assertEqual(passValue((1, '2', (3.4,))), + (1, '2', (3.4,)) if self.wantobjects else '1 2 3.4') + self.assertEqual(passValue(['a', ['b', 'c']]), + ('a', ('b', 'c')) if self.wantobjects else 'a {b c}') + + def test_set_object_concurrent_mutation_in_sequence_conversion(self): + # Prevent SIGSEV when the object to convert is concurrently mutated. + # See: https://github.com/python/cpython/issues/143310. + + string = "value" + + class Value: + def __str__(self): + values.clear() + return string + + class List(list): + pass + + expect = (string, "pad") if self.wantobjects else f"{string} pad" + self.assertEqual(self.passValue(values := [Value(), "pad"]), expect) + self.assertEqual(self.passValue(values := List([Value(), "pad"])), expect) + + def test_user_command(self): + result = None + def testfunc(arg): + nonlocal result + result = arg + return arg + self.interp.createcommand('testfunc', testfunc) + self.addCleanup(self.interp.tk.deletecommand, 'testfunc') + def check(value, expected1=None, expected2=None, *, eq=self.assertEqual): + expected = value + if self.wantobjects >= 2: + if expected2 is not None: + expected = expected2 + expected_type = type(expected) + else: + if expected1 is not None: + expected = expected1 + expected_type = str + nonlocal result + result = None + r = self.interp.call('testfunc', value) + self.assertIsInstance(result, expected_type) + eq(result, expected) + self.assertIsInstance(r, expected_type) + eq(r, expected) + def float_eq(actual, expected): + self.assertAlmostEqual(float(actual), expected, + delta=abs(expected) * 1e-10) + + check(True, '1', 1) + check(False, '0', 0) + check('string') + check('string\xbd') + check('string\u20ac') + check('string\U0001f4bb') + if sys.platform != 'win32': + check('<\udce2\udc82\udcac>', '<\u20ac>', '<\u20ac>') + check('<\udced\udca0\udcbd\udced\udcb2\udcbb>', '<\U0001f4bb>', '<\U0001f4bb>') + check('') + check(b'string', 'string') + check(b'string\xe2\x82\xac', 'string\xe2\x82\xac') + check(b'string\xbd', 'string\xbd') + check(b'', '') + check('str\x00ing') + check('str\x00ing\xbd') + check('str\x00ing\u20ac') + check(b'str\x00ing', 'str\x00ing') + check(b'str\xc0\x80ing', 'str\xc0\x80ing') + check(b'str\xc0\x80ing\xe2\x82\xac', 'str\xc0\x80ing\xe2\x82\xac') + for i in self.get_integers(): + check(i, str(i)) + for f in (0.0, 1.0, -1.0): + check(f, repr(f)) + for f in (1/3.0, sys.float_info.min, sys.float_info.max, + -sys.float_info.min, -sys.float_info.max): + check(f, eq=float_eq) + check(float('inf'), eq=float_eq) + check(-float('inf'), eq=float_eq) + # XXX NaN representation can be not parsable by float() + check((), '', '') + check((1, (2,), (3, 4), '5 6', ()), + '1 2 {3 4} {5 6} {}', + (1, (2,), (3, 4), '5 6', '')) + check([1, [2,], [3, 4], '5 6', []], + '1 2 {3 4} {5 6} {}', + (1, (2,), (3, 4), '5 6', '')) + + def test_passing_tcl_obj(self): + tcl = self.interp.tk + a = None + def testfunc(arg): + nonlocal a + a = arg + self.interp.createcommand('testfunc', testfunc) + self.addCleanup(self.interp.tk.deletecommand, 'testfunc') + tcl.eval(r'set a "\u20ac \ud83d\udcbb \0 \udcab"; regexp -about $a') + tcl.eval(r'testfunc $a') + expected = '\u20ac \U0001f4bb \0 \udced\udcb2\udcab' + if self.wantobjects >= 2: + self.assertEqual(str(a), expected) + self.assertEqual(a.string, expected) + self.assertEqual(a.typename, 'regexp') + else: + self.assertEqual(a, expected) + + def test_splitlist(self): + splitlist = self.interp.tk.splitlist + call = self.interp.tk.call + self.assertRaises(TypeError, splitlist) + self.assertRaises(TypeError, splitlist, 'a', 'b') + self.assertRaises(TypeError, splitlist, 2) + testcases = [ + ('2', ('2',)), + ('', ()), + ('{}', ('',)), + ('""', ('',)), + ('a\n b\t\r c\n ', ('a', 'b', 'c')), + (b'a\n b\t\r c\n ', ('a', 'b', 'c')), + ('a \u20ac', ('a', '\u20ac')), + ('a \U0001f4bb', ('a', '\U0001f4bb')), + (b'a \xe2\x82\xac', ('a', '\u20ac')), + (b'a \xf0\x9f\x92\xbb', ('a', '\U0001f4bb')), + (b'a \xed\xa0\xbd\xed\xb2\xbb', ('a', '\U0001f4bb')), + (b'a\xc0\x80b c\xc0\x80d', ('a\x00b', 'c\x00d')), + ('a {b c}', ('a', 'b c')), + (r'a b\ c', ('a', 'b c')), + (('a', 'b c'), ('a', 'b c')), + ('a 2', ('a', '2')), + (('a', 2), ('a', 2)), + ('a 3.4', ('a', '3.4')), + (('a', 3.4), ('a', 3.4)), + ((), ()), + ([], ()), + (['a', ['b', 'c']], ('a', ['b', 'c'])), + (call('list', 1, '2', (3.4,)), + (1, '2', (3.4,)) if self.wantobjects else + ('1', '2', '3.4')), + ] + if not self.wantobjects: + expected = ('12', '\u20ac', '\xe2\x82\xac', '3.4') + else: + expected = (12, '\u20ac', b'\xe2\x82\xac', (3.4,)) + testcases += [ + (call('dict', 'create', 12, '\u20ac', b'\xe2\x82\xac', (3.4,)), + expected), + ] + dbg_info = ('want objects? %s, Tcl version: %s, Tcl patchlevel: %s' + % (self.wantobjects, tcl_version, self.interp.info_patchlevel())) + for arg, res in testcases: + self.assertEqual(splitlist(arg), res, + 'arg=%a, %s' % (arg, dbg_info)) + self.assertRaises(TclError, splitlist, '{') + + def test_splitdict(self): + splitdict = tkinter._splitdict + tcl = self.interp.tk + + arg = '-a {1 2 3} -something foo status {}' + self.assertEqual(splitdict(tcl, arg, False), + {'-a': '1 2 3', '-something': 'foo', 'status': ''}) + self.assertEqual(splitdict(tcl, arg), + {'a': '1 2 3', 'something': 'foo', 'status': ''}) + + arg = ('-a', (1, 2, 3), '-something', 'foo', 'status', '{}') + self.assertEqual(splitdict(tcl, arg, False), + {'-a': (1, 2, 3), '-something': 'foo', 'status': '{}'}) + self.assertEqual(splitdict(tcl, arg), + {'a': (1, 2, 3), 'something': 'foo', 'status': '{}'}) + + self.assertRaises(RuntimeError, splitdict, tcl, '-a b -c ') + self.assertRaises(RuntimeError, splitdict, tcl, ('-a', 'b', '-c')) + + arg = tcl.call('list', + '-a', (1, 2, 3), '-something', 'foo', 'status', ()) + self.assertEqual(splitdict(tcl, arg), + {'a': (1, 2, 3) if self.wantobjects else '1 2 3', + 'something': 'foo', 'status': ''}) + + arg = tcl.call('dict', 'create', + '-a', (1, 2, 3), '-something', 'foo', 'status', ()) + if not self.wantobjects: + expected = {'a': '1 2 3', 'something': 'foo', 'status': ''} + else: + expected = {'a': (1, 2, 3), 'something': 'foo', 'status': ''} + self.assertEqual(splitdict(tcl, arg), expected) + + def test_join(self): + join = tkinter._join + tcl = self.interp.tk + def unpack(s): + return tcl.call('lindex', s, 0) + def check(value): + self.assertEqual(unpack(join([value])), value) + self.assertEqual(unpack(join([value, 0])), value) + self.assertEqual(unpack(unpack(join([[value]]))), value) + self.assertEqual(unpack(unpack(join([[value, 0]]))), value) + self.assertEqual(unpack(unpack(join([[value], 0]))), value) + self.assertEqual(unpack(unpack(join([[value, 0], 0]))), value) + check('') + check('spam') + check('sp am') + check('sp\tam') + check('sp\nam') + check(' \t\n') + check('{spam}') + check('{sp am}') + check('"spam"') + check('"sp am"') + check('{"spam"}') + check('"{spam}"') + check('sp\\am') + check('"sp\\am"') + check('"{}" "{}"') + check('"\\') + check('"{') + check('"}') + check('\n\\') + check('\n{') + check('\n}') + check('\\\n') + check('{\n') + check('}\n') + + @support.cpython_only + def test_new_tcl_obj(self): + support.check_disallow_instantiation(self, _tkinter.Tcl_Obj) + support.check_disallow_instantiation(self, _tkinter.TkttType) + support.check_disallow_instantiation(self, _tkinter.TkappType) + + +class BigmemTclTest(unittest.TestCase): + + def setUp(self): + self.interp = Tcl() + + @support.cpython_only + @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") + @support.bigmemtest(size=INT_MAX + 1, memuse=5, dry_run=False) + def test_huge_string_call(self, size): + value = ' ' * size + self.assertRaises(OverflowError, self.interp.call, 'string', 'index', value, 0) + + @support.cpython_only + @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") + @support.bigmemtest(size=INT_MAX + 1, memuse=3, dry_run=False) + def test_huge_string_builtins(self, size): + tk = self.interp.tk + value = '1' + ' ' * size + self.assertRaises(OverflowError, tk.getint, value) + self.assertRaises(OverflowError, tk.getdouble, value) + self.assertRaises(OverflowError, tk.getboolean, value) + self.assertRaises(OverflowError, tk.eval, value) + self.assertRaises(OverflowError, tk.evalfile, value) + self.assertRaises(OverflowError, tk.record, value) + self.assertRaises(OverflowError, tk.adderrorinfo, value) + self.assertRaises(OverflowError, tk.setvar, value, 'x', 'a') + self.assertRaises(OverflowError, tk.setvar, 'x', value, 'a') + self.assertRaises(OverflowError, tk.unsetvar, value) + self.assertRaises(OverflowError, tk.unsetvar, 'x', value) + self.assertRaises(OverflowError, tk.adderrorinfo, value) + self.assertRaises(OverflowError, tk.exprstring, value) + self.assertRaises(OverflowError, tk.exprlong, value) + self.assertRaises(OverflowError, tk.exprboolean, value) + self.assertRaises(OverflowError, tk.splitlist, value) + self.assertRaises(OverflowError, tk.createcommand, value, max) + self.assertRaises(OverflowError, tk.deletecommand, value) + + @support.cpython_only + @unittest.skipUnless(INT_MAX < PY_SSIZE_T_MAX, "needs UINT_MAX < SIZE_MAX") + @support.bigmemtest(size=INT_MAX + 1, memuse=6, dry_run=False) + def test_huge_string_builtins2(self, size): + # These commands require larger memory for possible error messages + tk = self.interp.tk + value = '1' + ' ' * size + self.assertRaises(OverflowError, tk.evalfile, value) + self.assertRaises(OverflowError, tk.unsetvar, value) + self.assertRaises(OverflowError, tk.unsetvar, 'x', value) + + +def setUpModule(): + wantobjects = support.get_resource_value('wantobjects') + if wantobjects is not None: + unittest.enterModuleContext( + support.swap_attr(tkinter, 'wantobjects', int(wantobjects))) + if support.verbose: + tcl = Tcl() + print('patchlevel =', tcl.call('info', 'patchlevel'), flush=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py index 6fac921f629..4bb7d95a903 100644 --- a/Lib/test/test_tempfile.py +++ b/Lib/test/test_tempfile.py @@ -14,6 +14,7 @@ import gc import shutil import subprocess +import sysconfig from unittest import mock import unittest @@ -1409,7 +1410,7 @@ def test_properties(self): f.write(b'x') self.assertTrue(f._rolled) - self.assertEqual(f.mode, 'rb+') + self.assertEqual(f.mode, 'wb+') self.assertIsNotNone(f.name) with self.assertRaises(AttributeError): f.newlines @@ -1848,6 +1849,54 @@ def test(target, target_is_directory): new_flags = os.stat(dir1).st_flags self.assertEqual(new_flags, old_flags) + @os_helper.skip_unless_symlink + @os_helper.skip_unless_working_chmod + @support.requires_non_root_user + @unittest.skipIf(support.is_emscripten, 'Fails due to Emscripten bug:' + 'emscripten-core/emscripten#27761') + @unittest.skipUnless(shutil.rmtree.avoids_symlink_attacks, + 'requires the fd based implementation of rmtree()') + def test_cleanup_with_symlink_race(self): + # cleanup() should not operate on files outside of the temporary + # directory when a directory is replaced with a symlink while it + # recovers from a PermissionError (CVE-2026-12345). + with self.do_create(recurse=0) as target: + target_file = os.path.join(target, 'file1') + open(target_file, 'wb').close() + target_mode = os.stat(target_file).st_mode + + d1 = self.do_create(recurse=0) + dir1 = os.path.join(d1.name, 'dir1') + os.mkdir(dir1) + open(os.path.join(dir1, 'file1'), 'wb').close() + # Removing contents of dir1 fails with a PermissionError, and + # dir1 is replaced with a symlink to target at the very moment + # cleanup() starts to recover from that error. + os.chmod(dir1, 0o500) + unlink = os.unlink + def hook(path, *, dir_fd=None): + try: + return unlink(path, dir_fd=dir_fd) + except PermissionError: + if not os.path.islink(dir1): + os.chmod(dir1, 0o700) + os.rename(dir1, dir1 + '_moved') + os.symlink(target, dir1) + raise + try: + with mock.patch('os.unlink', hook): + with contextlib.suppress(OSError): + d1.cleanup() + finally: + if os.path.islink(dir1): + os.unlink(dir1) + os.rename(dir1 + '_moved', dir1) + os.chmod(dir1, 0o700) + d1.cleanup() + + self.assertTrue(os.path.exists(target_file)) + self.assertEqual(os.stat(target_file).st_mode, target_mode) + @support.cpython_only def test_del_on_collection(self): # A TemporaryDirectory is deleted when garbage collected @@ -2020,6 +2069,29 @@ def test_modes(self): d.cleanup() self.assertFalse(os.path.exists(d.name)) + @support.subTests('ignore_errors', (True, False)) + def test_parent_mode_preserved(self, ignore_errors): + # Test that cleanup does not touch the parent directory, + # even if that prevents removal. + for mode in range(8): + mode <<= 6 + with self.subTest(mode=format(mode, '03o')): + outer = self.do_create() + with outer: + d = self.do_create(dir=outer.name, dirs=2, files=2, + ignore_cleanup_errors=ignore_errors) + with d: + os.chmod(outer.name, mode) + orig_mode = os.stat(outer.name).st_mode + try: + d.cleanup() + except PermissionError: + if ignore_errors: + raise + self.assertEqual(os.stat(outer.name).st_mode, orig_mode) + outer.cleanup() + self.assertFalse(os.path.exists(outer.name)) + def check_flags(self, flags): # skip the test if these flags are not supported (ex: FreeBSD 13) filename = os_helper.TESTFN @@ -2057,5 +2129,17 @@ def test_delete_false(self): self.assertTrue(os.path.exists(working_dir)) shutil.rmtree(working_dir) + @unittest.skipUnless( + sysconfig.get_config_var('PY_SUPPORT_TIER') + and sysconfig.get_config_var('PY_SUPPORT_TIER') <= 3, + 'regression test for supported platforms') + @unittest.skipIf(support.MS_WINDOWS, 'dirfd not used on Windows') + @unittest.skipIf(support.is_wasi, 'WASI has no chmod') + def test_cleanup_safe(self): + """Verify that cleanup uses the safer code path""" + # This is a regression test. Feel free to add exceptions for new + # platforms, but don't forget to update the docs. + self.assertTrue(tempfile._rmtree_use_dir_fd) + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_termios.py b/Lib/test/test_termios.py index ce8392a6ccd..aa8927c1ba7 100644 --- a/Lib/test/test_termios.py +++ b/Lib/test/test_termios.py @@ -104,7 +104,7 @@ def test_tcsendbreak(self): try: termios.tcsendbreak(self.fd, 1) except termios.error as exc: - if exc.args[0] == errno.ENOTTY and sys.platform.startswith(('freebsd', "netbsd")): + if exc.args[0] == errno.ENOTTY and sys.platform.startswith(('freebsd', 'netbsd', 'openbsd', 'dragonfly')): self.skipTest('termios.tcsendbreak() is not supported ' 'with pseudo-terminals (?) on this platform') raise @@ -180,6 +180,9 @@ def test_tcflow(self): termios.tcflow(self.fd, termios.TCOON) termios.tcflow(self.fd, termios.TCIOFF) termios.tcflow(self.fd, termios.TCION) + # Discard the transmitted STOP and START characters, + # otherwise closing the pseudo-terminal can block. + termios.tcflush(self.fd, termios.TCOFLUSH) @support.skip_android_selinux('tcflow') def test_tcflow_errors(self): diff --git a/Lib/test/test_thread_local_bytecode.py b/Lib/test/test_thread_local_bytecode.py index d5c56db8d5d..6f76f1bc335 100644 --- a/Lib/test/test_thread_local_bytecode.py +++ b/Lib/test/test_thread_local_bytecode.py @@ -3,7 +3,7 @@ import unittest from test import support -from test.support import cpython_only, import_helper, requires_specialization_ft +from test.support import cpython_only, import_helper, requires_specialization from test.support.script_helper import assert_python_ok from test.support.threading_helper import requires_working_threading @@ -15,7 +15,7 @@ @requires_working_threading() @unittest.skipUnless(support.Py_GIL_DISABLED, "only in free-threaded builds") class TLBCTests(unittest.TestCase): - @requires_specialization_ft + @requires_specialization def test_new_threads_start_with_unspecialized_code(self): code = textwrap.dedent(""" import dis @@ -46,7 +46,7 @@ def f(a, b, q=None): """) assert_python_ok("-X", "tlbc=1", "-c", code) - @requires_specialization_ft + @requires_specialization def test_threads_specialize_independently(self): code = textwrap.dedent(""" import dis @@ -108,7 +108,6 @@ def f(a, b, q=None): """) assert_python_ok("-X", "tlbc=1", "-c", code) - @support.skip_if_sanitizer("gh-129752: data race on adaptive counter", thread=True) def test_no_copies_if_tlbc_disabled(self): code = textwrap.dedent(""" import queue diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py index 605dffa5214..0e3c3b3fa7c 100644 --- a/Lib/test/test_threading.py +++ b/Lib/test/test_threading.py @@ -6,7 +6,7 @@ from test.support import threading_helper, requires_subprocess, requires_gil_enabled from test.support import verbose, cpython_only, os_helper from test.support.import_helper import ensure_lazy_imports, import_module -from test.support.script_helper import assert_python_ok, assert_python_failure +from test.support.script_helper import assert_python_ok, assert_python_failure, spawn_python from test.support import force_not_colorized import random @@ -324,6 +324,7 @@ def f(mutex): # PyThreadState_SetAsyncExc() is a CPython-only gimmick, not (currently) # exposed at the Python level. This test relies on ctypes to get at it. @unittest.expectedFailure # TODO: RUSTPYTHON + @cpython_only def test_PyThreadState_SetAsyncExc(self): ctypes = import_module("ctypes") @@ -412,7 +413,53 @@ def run(self): t.join() # else the thread is still running, and we have no way to kill it - @unittest.skip("TODO: RUSTPYTHON; threading._start_new_thread not exposed") + @cpython_only + @unittest.skipUnless(hasattr(signal, "pthread_kill"), "need pthread_kill") + @unittest.skipUnless(hasattr(signal, "SIGUSR1"), "need SIGUSR1") + def test_PyThreadState_SetAsyncExc_interrupts_sleep(self): + _testcapi = import_module("_testlimitedcapi") + + worker_started = threading.Event() + + class InjectedException(Exception): + """Custom exception for testing""" + + caught_exception = None + + def catch_exception(): + nonlocal caught_exception + day_as_seconds = 60 * 60 * 24 + try: + worker_started.set() + time.sleep(day_as_seconds) + except InjectedException as exc: + caught_exception = exc + + thread = threading.Thread(target=catch_exception) + thread.start() + worker_started.wait() + + signal.signal(signal.SIGUSR1, lambda sig, frame: None) + + result = _testcapi.threadstate_set_async_exc( + thread.ident, InjectedException) + self.assertEqual(result, 1) + + for _ in support.sleeping_retry(support.SHORT_TIMEOUT): + if not thread.is_alive(): + break + try: + signal.pthread_kill(thread.ident, signal.SIGUSR1) + except OSError: + # The thread might have terminated between the is_alive check + # and the pthread_kill + break + + thread.join() + signal.signal(signal.SIGUSR1, signal.SIG_DFL) + + self.assertIsInstance(caught_exception, InjectedException) + def test_limbo_cleanup(self): # Issue 7481: Failure to start thread should cleanup the limbo map. def fail_new_thread(*args, **kwargs): @@ -1250,13 +1297,68 @@ def __del__(self): self.assertEqual(err, b"") self.assertIn(b"all clear", out) + @support.subTests('lock_class_name', ['Lock', 'RLock']) + def test_acquire_daemon_thread_lock_in_finalization(self, lock_class_name): + # gh-123940: Py_Finalize() prevents other threads from running Python + # code (and so, releasing locks), so acquiring a locked lock can not + # succeed. + # We raise an exception rather than hang. + code = textwrap.dedent(f""" + import threading + import time + + thread_started_event = threading.Event() + + lock = threading.{lock_class_name}() + def loop(): + if {lock_class_name!r} == 'RLock': + lock.acquire() + with lock: + thread_started_event.set() + while True: + time.sleep(1) + + uncontested_lock = threading.{lock_class_name}() + + class Cycle: + def __init__(self): + self.self_ref = self + self.thr = threading.Thread( + target=loop, daemon=True) + self.thr.start() + thread_started_event.wait() + + def __del__(self): + assert self.thr.is_alive() + + # We *can* acquire an unlocked lock + uncontested_lock.acquire() + if {lock_class_name!r} == 'RLock': + uncontested_lock.acquire() + + # Acquiring a locked one fails + try: + lock.acquire() + except PythonFinalizationError: + assert self.thr.is_alive() + print('got the correct exception!') + + # Cycle holds a reference to itself, which ensures it is + # cleaned up during the GC that runs after daemon threads + # have been forced to exit during finalization. + Cycle() + """) + rc, out, err = assert_python_ok("-c", code) + self.assertEqual(err, b"") + self.assertIn(b"got the correct exception", out) + def test_start_new_thread_failed(self): # gh-109746: if Python fails to start newly created thread # due to failure of underlying PyThread_start_new_thread() call, # its state should be removed from interpreter' thread states list # to avoid its double cleanup try: - from resource import setrlimit, RLIMIT_NPROC + from resource import setrlimit, RLIMIT_NPROC # noqa: F401 except ImportError as err: self.skipTest(err) # RLIMIT_NPROC is specific to Linux and BSD code = """if 1: @@ -1287,12 +1389,6 @@ def f(): @cpython_only def test_finalize_daemon_thread_hang(self): - if support.check_sanitizer(thread=True, memory=True): - # the thread running `time.sleep(100)` below will still be alive - # at process exit - self.skipTest( - "https://github.com/python/cpython/issues/124878 - Known" - " race condition that TSAN identifies.") # gh-87135: tests that daemon threads hang during finalization script = textwrap.dedent(''' import os @@ -1411,10 +1507,6 @@ def run_in_bg(): self.assertEqual(err, b"") self.assertEqual(out.strip(), b"Exiting...") - @unittest.skip("TODO: RUSTPYTHON; Thread._tstate_lock not implemented") - def test_tstate_lock(self): - return super().test_tstate_lock() - class ThreadJoinOnShutdown(BaseTestCase): def _run_and_join(self, script): @@ -2044,6 +2136,32 @@ def test_dummy_thread_on_interpreter_shutdown(self): self.assertEqual(out, b"") self.assertEqual(err, b"") + @requires_subprocess() + @unittest.skipIf(os.name == 'nt', "signals don't work well on windows") + def test_keyboard_interrupt_during_threading_shutdown(self): + import subprocess + source = f""" + from threading import Thread + import time + import os + + + def test(): + print('a', flush=True, end='') + time.sleep(10) + + + for _ in range(3): + Thread(target=test).start() + """ + + with spawn_python("-c", source, stderr=subprocess.PIPE) as proc: + self.assertEqual(proc.stdout.read(3), b'aaa') + proc.send_signal(signal.SIGINT) + proc.stderr.flush() + error = proc.stderr.read() + self.assertIn(b"KeyboardInterrupt", error) + class ThreadRunFail(threading.Thread): def run(self): @@ -2217,8 +2335,7 @@ def test_signature(self): # gh-102029 ] for args, kwargs in arg_types: with self.subTest(args=args, kwargs=kwargs): - with self.assertWarns(DeprecationWarning): - threading.RLock(*args, **kwargs) + self.assertRaises(TypeError, threading.RLock, *args, **kwargs) # Subtypes with custom `__init__` are allowed (but, not recommended): class CustomRLock(self.locktype): @@ -2236,6 +2353,9 @@ class ConditionAsRLockTests(lock_tests.RLockTests): # Condition uses an RLock by default and exports its API. locktype = staticmethod(threading.Condition) + def test_constructor_noargs(self): + self.skipTest("Condition allows positional arguments") + def test_recursion_count(self): self.skipTest("Condition does not expose _recursion_count()") @@ -2252,6 +2372,231 @@ class BarrierTests(lock_tests.BarrierTests): barriertype = staticmethod(threading.Barrier) +## Test Synchronization tools for iterators ################ + +class ThreadingIteratorToolsTests(BaseTestCase): + def test_serialize_serializes_concurrent_iteration(self): + limit = 10_000 + workers_count = 10 + result = 0 + result_lock = threading.Lock() + start = threading.Event() + + def producer(limit): + for x in range(limit): + yield x + + def consumer(iterator): + nonlocal result + start.wait() + total = 0 + for x in iterator: + total += x + with result_lock: + result += total + + iterator = threading.serialize_iterator(producer(limit)) + workers = [ + threading.Thread(target=consumer, args=(iterator,)) + for _ in range(workers_count) + ] + with threading_helper.wait_threads_exit(): + for worker in workers: + worker.start() + for worker in workers: + # Wait for the worker thread to actually start. + while worker.ident is None: + time.sleep(0.1) + start.set() + for worker in workers: + worker.join() + + self.assertEqual(result, limit * (limit - 1) // 2) + + def test_serialize_generator_methods(self): + # A generator that yields and receives + def echo(): + try: + while True: + val = yield "ready" + yield f"received {val}" + except ValueError: + yield "caught" + + it = threading.serialize_iterator(echo()) + + # Test __next__ + self.assertEqual(next(it), "ready") + + # Test send() + self.assertEqual(it.send("hello"), "received hello") + self.assertEqual(next(it), "ready") + + # Test throw() + self.assertEqual(it.throw(ValueError), "caught") + + # Test close() + it.close() + with self.assertRaises(StopIteration): + next(it) + + def test_serialize_methods_attribute_error(self): + # A standard iterator that does not have send/throw/close + # should raise AttributeError when called. + standard_it = threading.serialize_iterator([1, 2, 3]) + + with self.assertRaises(AttributeError): + standard_it.send("foo") + + with self.assertRaises(AttributeError): + standard_it.throw(ValueError) + + with self.assertRaises(AttributeError): + standard_it.close() + + def test_serialize_generator_methods_locking(self): + # Verifies that generator methods also acquire the lock. + # We can test this by checking if the lock is held during the call. + + class LockCheckingGenerator: + def __init__(self, lock): + self.lock = lock + def __iter__(self): + return self + def send(self, value): + if not self.lock.locked(): + raise RuntimeError("Lock not held during send()") + return value + def throw(self, *args): + if not self.lock.locked(): + raise RuntimeError("Lock not held during throw()") + def close(self): + if not self.lock.locked(): + raise RuntimeError("Lock not held during close()") + + # Manually create the serialize object to inspect the lock + it = threading.serialize_iterator([]) + mock_gen = LockCheckingGenerator(it._lock) + it._iterator = mock_gen + + # These should not raise RuntimeError + it.send(1) + it.throw(ValueError) + it.close() + + def test_serialize_next_exception(self): + # Verify exception pass through for calls to next() + + def f(): + raise RuntimeError + yield None + + g = threading.serialize_iterator(f()) + with self.assertRaises(RuntimeError): + next(g) + + def test_synchronized_serializes_generator_instances(self): + unique = 10 + repetitions = 5 + limit = 100 + start = threading.Event() + + @threading.synchronized_iterator + def atomic_counter(): + # The sleep widens the race window that would exist without + # synchronization between yielding a value and advancing state. + i = 0 + while True: + yield i + time.sleep(0.0005) + i += 1 + + def consumer(counter): + start.wait() + for _ in range(limit): + next(counter) + + unique_counters = [atomic_counter() for _ in range(unique)] + counters = unique_counters * repetitions + workers = [ + threading.Thread(target=consumer, args=(counter,)) + for counter in counters + ] + with threading_helper.wait_threads_exit(): + for worker in workers: + worker.start() + start.set() + for worker in workers: + worker.join() + + self.assertEqual( + {next(counter) for counter in unique_counters}, + {limit * repetitions}, + ) + + def test_synchronized_preserves_wrapped_metadata(self): + def gen(): + yield 1 + + wrapped = threading.synchronized_iterator(gen) + + self.assertEqual(wrapped.__name__, gen.__name__) + self.assertIs(wrapped.__wrapped__, gen) + self.assertEqual(list(wrapped()), [1]) + + def test_concurrent_tee_supports_concurrent_consumers(self): + limit = 5_000 + num_threads = 25 + successes = 0 + failures = [] + result_lock = threading.Lock() + start = threading.Event() + expected = list(range(limit)) + + def producer(limit): + for x in range(limit): + yield x + + def consumer(iterator): + nonlocal successes + start.wait() + items = list(iterator) + with result_lock: + if items == expected: + successes += 1 + else: + failures.append(items[:20]) + + tees = threading.concurrent_tee(producer(limit), n=num_threads) + workers = [ + threading.Thread(target=consumer, args=(iterator,)) + for iterator in tees + ] + with threading_helper.wait_threads_exit(): + for worker in workers: + worker.start() + start.set() + for worker in workers: + worker.join() + + self.assertEqual(failures, []) + self.assertEqual(successes, len(tees)) + + # Verify that locks are shared + self.assertEqual(len({id(t_obj.lock) for t_obj in tees}), 1) + + def test_concurrent_tee_zero_iterators(self): + self.assertEqual(threading.concurrent_tee(range(10), n=0), ()) + + def test_concurrent_tee_negative_n(self): + with self.assertRaises(ValueError): + threading.concurrent_tee(range(10), n=-1) + + +################# + + + class MiscTestCase(unittest.TestCase): def test__all__(self): restore_default_excepthook(self) @@ -2485,6 +2830,7 @@ def test_atexit_called_once(self): self.assertFalse(err) + @force_not_colorized def test_atexit_after_shutdown(self): # The only way to do this is by registering an atexit within # an atexit, which is intended to raise an exception. diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py index f66a37edb4c..985984b5512 100644 --- a/Lib/test/test_time.py +++ b/Lib/test/test_time.py @@ -2,6 +2,7 @@ from test.support import warnings_helper import decimal import enum +import fractions import math import platform import sys @@ -170,10 +171,12 @@ def test_sleep_exceptions(self): # Improved exception #81267 with self.assertRaises(TypeError) as errmsg: time.sleep([]) - self.assertIn("integer or float", str(errmsg.exception)) + self.assertIn("real number", str(errmsg.exception)) def test_sleep(self): - for value in [-0.0, 0, 0.0, 1e-100, 1e-9, 1e-6, 1, 1.2]: + for value in [-0.0, 0, 0.0, 1e-100, 1e-9, 1e-6, 1, 1.2, + decimal.Decimal('0.02'), + fractions.Fraction(1, 50)]: with self.subTest(value=value): time.sleep(value) @@ -184,6 +187,38 @@ def test_epoch(self): # Only test the date and time, ignore other gmtime() members self.assertEqual(tuple(epoch)[:6], (1970, 1, 1, 0, 0, 0), epoch) + def test_gmtime(self): + # expected format: + # (tm_year, tm_mon, tm_mday, + # tm_hour, tm_min, tm_sec, + # tm_wday, tm_yday) + tests = [ + (-13262400, (1969, 7, 31, 12, 0, 0, 3, 212)), + (-6177600, (1969, 10, 21, 12, 0, 0, 1, 294)), + # leap years (pre epoch) + (-2077660800, (1904, 3, 1, 0, 0, 0, 1, 61)), + (-2077833600, (1904, 2, 28, 0, 0, 0, 6, 59)), + ] + + try: + from _testinternalcapi import SIZEOF_TIME_T + except ImportError: + pass + else: + if SIZEOF_TIME_T >= 8: + tests.extend(( + # non-leap years (pre epoch) + (-2203891200, (1900, 3, 1, 0, 0, 0, 3, 60)), + (-2203977600, (1900, 2, 28, 0, 0, 0, 2, 59)), + (-5359564800, (1800, 3, 1, 0, 0, 0, 5, 60)), + (-5359651200, (1800, 2, 28, 0, 0, 0, 4, 59)), + )) + + for t, expected in tests: + with self.subTest(t=t, expected=expected): + res = time.gmtime(t) + self.assertEqual(tuple(res)[:8], expected, res) + def test_strftime(self): tt = time.gmtime(self.t) for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', @@ -323,11 +358,11 @@ def test_strptime(self): # Should be able to go round-trip from strftime to strptime without # raising an exception. tt = time.gmtime(self.t) - for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I', - 'j', 'm', 'M', 'p', 'S', + for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'D', 'e', 'F', 'H', 'I', + 'j', 'm', 'M', 'n', 'p', 'S', 't', 'T', 'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'): format = '%' + directive - if directive == 'd': + if directive in ('d', 'e'): format += ',%Y' # Avoid GH-70647. strf_output = time.strftime(format, tt) try: @@ -344,7 +379,7 @@ def test_strptime_bytes(self): def test_strptime_exception_context(self): # check that this doesn't chain exceptions needlessly (see #17572) with self.assertRaises(ValueError) as e: - time.strptime('', '%D') + time.strptime('', '%!') self.assertTrue(e.exception.__suppress_context__) # additional check for stray % branch with self.assertRaises(ValueError) as e: @@ -352,10 +387,13 @@ def test_strptime_exception_context(self): self.assertTrue(e.exception.__suppress_context__) def test_strptime_leap_year(self): - # GH-70647: warns if parsing a format with a day and no year. + # GH-70647: %d errors if parsing a format with a day and no year. + with self.assertRaises(ValueError): + time.strptime('02-07 18:28', '%m-%d %H:%M') + # %e without a year is deprecated, scheduled for removal in 3.17. with self.assertWarnsRegex(DeprecationWarning, r'.*day of month without a year.*'): - time.strptime('02-07 18:28', '%m-%d %H:%M') + time.strptime('02-07 18:28', '%m-%e %H:%M') def test_asctime(self): time.asctime(time.gmtime(self.t)) @@ -498,12 +536,13 @@ def test_localtime_without_arg(self): def test_mktime(self): # Issue #1726687 for t in (-2, -1, 0, 1): + t_struct = time.localtime(t) try: - tt = time.localtime(t) + t1 = time.mktime(t_struct) except (OverflowError, OSError): pass else: - self.assertEqual(time.mktime(tt), t) + self.assertEqual(t1, t) # Issue #13309: passing extreme values to mktime() or localtime() # borks the glibc's internal timezone data. @@ -755,7 +794,6 @@ class TestStrftime4dyear(_TestStrftimeYear, _Test4dYear, unittest.TestCase): class TestPytime(unittest.TestCase): @skip_if_buggy_ucrt_strfptime - @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_localtime_timezone(self): # Get the localtime and examine it for the offset and zone. @@ -790,14 +828,12 @@ def test_localtime_timezone(self): self.assertEqual(new_lt.tm_gmtoff, lt.tm_gmtoff) self.assertEqual(new_lt9.tm_zone, lt.tm_zone) - @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_strptime_timezone(self): t = time.strptime("UTC", "%Z") self.assertEqual(t.tm_zone, 'UTC') t = time.strptime("+0500", "%z") self.assertEqual(t.tm_gmtoff, 5 * 3600) - @unittest.skipUnless(time._STRUCT_TM_ITEMS == 11, "needs tm_zone support") def test_short_times(self): import pickle @@ -977,6 +1013,17 @@ def test_FromSecondsObject(self): with self.assertRaises(ValueError): _PyTime_FromSecondsObject(float('nan'), time_rnd) + def test_FromSecondsObject_float_overflow_message(self): + # Float path must report a PyTime_t overflow, like the integer path. + from _testinternalcapi import _PyTime_FromSecondsObject + for value in (PyTime_MAX, PyTime_MIN): + for time_rnd, _ in ROUNDING_MODES: + with self.subTest(value=value, time_rnd=time_rnd): + with self.assertRaisesRegex( + OverflowError, + "timestamp out of range for C PyTime_t"): + _PyTime_FromSecondsObject(value, time_rnd) + def test_AsSecondsDouble(self): from _testcapi import PyTime_AsSecondsDouble diff --git a/Lib/test/test_timeit.py b/Lib/test/test_timeit.py index 2b0745e947c..a2a09f9de61 100644 --- a/Lib/test/test_timeit.py +++ b/Lib/test/test_timeit.py @@ -4,8 +4,14 @@ import io from textwrap import dedent -from test.support import captured_stdout -from test.support import captured_stderr +from test.support import ( + captured_stderr, + captured_stdout, + force_colorized, + force_not_colorized_test_class, +) + +from _colorize import get_theme # timeit's default number of iterations. DEFAULT_NUMBER = 1000000 @@ -41,6 +47,7 @@ def wrap_timer(self, timer): self.saved_timer = timer return self +@force_not_colorized_test_class class TestTimeit(unittest.TestCase): def tearDown(self): @@ -252,11 +259,12 @@ def run_main(self, seconds_per_increment=1.0, switches=None, timer=None): return s.getvalue() def test_main_bad_switch(self): - s = self.run_main(switches=['--bad-switch']) - self.assertEqual(s, dedent("""\ - option --bad-switch not recognized - use -h/--help for command line help - """)) + with captured_stderr() as error_stringio: + s = self.run_main(switches=["--bad-switch"]) + self.assertEqual(s, "") + self.assertIn( + "unrecognized arguments: --bad-switch", error_stringio.getvalue() + ) def test_main_seconds(self): s = self.run_main(seconds_per_increment=5.5) @@ -294,10 +302,11 @@ def test_main_negative_reps(self): s = self.run_main(seconds_per_increment=60.0, switches=['-r-5']) self.assertEqual(s, "1 loop, best of 1: 60 sec per loop\n") - @unittest.skipIf(sys.flags.optimize >= 2, "need __doc__") def test_main_help(self): s = self.run_main(switches=['-h']) - self.assertEqual(s, timeit.__doc__) + self.assertIn("Tool for measuring execution time", s) + self.assertIn("-n", s) + self.assertIn("--number", s) def test_main_verbose(self): s = self.run_main(switches=['-v']) @@ -346,10 +355,12 @@ def test_main_with_time_unit(self): "100 loops, best of 5: 3e+03 usec per loop\n") # Test invalid unit input with captured_stderr() as error_stringio: - invalid = self.run_main(seconds_per_increment=0.003, - switches=['-u', 'parsec']) - self.assertEqual(error_stringio.getvalue(), - "Unrecognized unit. Please select nsec, usec, msec, or sec.\n") + invalid = self.run_main( + seconds_per_increment=0.003, switches=["-u", "parsec"] + ) + self.assertIn( + "choose from 'nsec', 'usec', 'msec', 'sec'", error_stringio.getvalue() + ) def test_main_exception(self): with captured_stderr() as error_stringio: @@ -361,10 +372,10 @@ def test_main_exception_fixed_reps(self): s = self.run_main(switches=['-n1', '1/0']) self.assert_exc_string(error_stringio.getvalue(), 'ZeroDivisionError') - def autorange(self, seconds_per_increment=1/1024, callback=None): + def autorange(self, seconds_per_increment=1/1024, callback=None, target_time=0.2): timer = FakeTimer(seconds_per_increment=seconds_per_increment) t = timeit.Timer(stmt=self.fake_stmt, setup=self.fake_setup, timer=timer) - return t.autorange(callback) + return t.autorange(callback, target_time=target_time) def test_autorange(self): num_loops, time_taken = self.autorange() @@ -376,6 +387,11 @@ def test_autorange_second(self): self.assertEqual(num_loops, 1) self.assertEqual(time_taken, 1.0) + def test_autorange_with_target_time(self): + num_loops, time_taken = self.autorange(target_time=1.0) + self.assertEqual(num_loops, 2000) + self.assertEqual(time_taken, 2000/1024) + def test_autorange_with_callback(self): def callback(a, b): print("{} {:.3f}".format(a, b)) @@ -395,5 +411,39 @@ def callback(a, b): self.assertEqual(s.getvalue(), expected) -if __name__ == '__main__': +class TestTimeitColor(unittest.TestCase): + + fake_stmt = TestTimeit.fake_stmt + run_main = TestTimeit.run_main + + @force_colorized + def test_main_colorized(self): + t = get_theme(force_color=True).timeit + s = self.run_main(seconds_per_increment=5.5) + self.assertEqual( + s, + "1 loop, best of 5: " + f"{t.best}5.5 sec{t.reset} " + f"{t.per_loop}per loop{t.reset}\n", + ) + + @force_colorized + def test_main_verbose_colorized(self): + t = get_theme(force_color=True).timeit + s = self.run_main(switches=["-v"]) + self.assertEqual( + s, + f"1 loop {t.punctuation}-> {t.timing}1 sec{t.reset}\n\n" + "raw times: " + f"{t.timing}1 sec{t.punctuation}, " + f"{t.timing}1 sec{t.punctuation}, " + f"{t.timing}1 sec{t.punctuation}, " + f"{t.timing}1 sec{t.punctuation}, " + f"{t.timing}1 sec{t.reset}\n\n" + f"1 loop, best of 5: {t.best}1 sec{t.reset} " + f"{t.per_loop}per loop{t.reset}\n", + ) + + +if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_tkinter/README b/Lib/test/test_tkinter/README new file mode 100644 index 00000000000..79cd16c74d7 --- /dev/null +++ b/Lib/test/test_tkinter/README @@ -0,0 +1,14 @@ +Writing new tests +================= + +Precaution +---------- + + New tests should always use only one Tk window at once, like all the + current tests do. This means that you have to destroy the current window + before creating another one, and clean up after the test. The motivation + behind this is that some tests may depend on having its window focused + while it is running to work properly, and it may be hard to force focus + on your window across platforms (right now only test_traversal at + test_ttk.test_widgets.NotebookTest depends on this). + diff --git a/Lib/test/test_tkinter/__init__.py b/Lib/test/test_tkinter/__init__.py new file mode 100644 index 00000000000..62890c705a6 --- /dev/null +++ b/Lib/test/test_tkinter/__init__.py @@ -0,0 +1,30 @@ +import os.path +import unittest + +from test.support import ( + check_sanitizer, + import_helper, + load_package_tests, + requires, + ) + + +if check_sanitizer(address=True, memory=True): + # See gh-90791 for details + raise unittest.SkipTest("Tests involving libX11 can SEGFAULT on ASAN/MSAN builds") + +# Skip test if _tkinter wasn't built. +import_helper.import_module('_tkinter') + +# Skip test if tk cannot be initialized. +requires('gui') + + +def load_tests(*args): + return load_package_tests(os.path.dirname(__file__), *args) + +def setUpModule(): + wantobjects = support.get_resource_value('wantobjects') + if wantobjects is not None: + unittest.enterModuleContext( + support.swap_attr(tkinter, 'wantobjects', int(wantobjects))) diff --git a/Lib/test/test_tkinter/__main__.py b/Lib/test/test_tkinter/__main__.py new file mode 100644 index 00000000000..40a23a297ec --- /dev/null +++ b/Lib/test/test_tkinter/__main__.py @@ -0,0 +1,4 @@ +from . import load_tests +import unittest + +unittest.main() diff --git a/Lib/test/test_tkinter/support.py b/Lib/test/test_tkinter/support.py new file mode 100644 index 00000000000..8d4ad2345a1 --- /dev/null +++ b/Lib/test/test_tkinter/support.py @@ -0,0 +1,211 @@ +import functools +import time +import tkinter +import unittest +from test import support + + +def setUpModule(): + wantobjects = support.get_resource_value('wantobjects') + if wantobjects is not None: + unittest.enterModuleContext( + support.swap_attr(tkinter, 'wantobjects', int(wantobjects))) + +class AbstractTkTest: + + @classmethod + def setUpClass(cls): + cls._old_support_default_root = tkinter._support_default_root + destroy_default_root() + tkinter.NoDefaultRoot() + cls.root = tkinter.Tk() + cls.wantobjects = cls.root.wantobjects() + if support.is_resource_enabled('wantobjects'): + assert cls.wantobjects == int(support.get_resource_value('wantobjects')) + # De-maximize main window. + # Some window managers can maximize new windows. + cls.root.wm_state('normal') + try: + cls.root.wm_attributes(zoomed=False) + except tkinter.TclError: + pass + + @classmethod + def tearDownClass(cls): + cls.root.update_idletasks() + cls.root.destroy() + del cls.root + tkinter._default_root = None + tkinter._support_default_root = cls._old_support_default_root + + def setUp(self): + self.root.deiconify() + + def tearDown(self): + for w in self.root.winfo_children(): + w.destroy() + self.root.withdraw() + + def require_mapped(self, widget, timeout=None): + """Realize *widget*, or skip the test if the window manager will + not map it (e.g. a tiling WM or a headless/contended display). + + Use this instead of a bare update() before querying realized + geometry (winfo_width(), identify(), coords(), place_info(), ...). + See gh-69134, gh-74941 and bpo-40722. + """ + if timeout is None: + timeout = support.LOOPBACK_TIMEOUT + if not wait_until_mapped(widget, timeout): + self.skipTest('widget was not mapped by the window manager ' + f'(timed out after {timeout:g}s)') + + +class AbstractDialogTest(AbstractTkTest): + # Tk delivers generated keyboard events to the focused window. Hide the + # root window, otherwise the window manager can take the focus back from + # the dialog (gh-154357). + + def setUp(self): + super().setUp() + self.root.withdraw() + + +class AbstractDefaultRootTest: + + def setUp(self): + self._old_support_default_root = tkinter._support_default_root + destroy_default_root() + tkinter._support_default_root = True + self.wantobjects = tkinter.wantobjects + + def tearDown(self): + destroy_default_root() + tkinter._default_root = None + tkinter._support_default_root = self._old_support_default_root + + def _test_widget(self, constructor): + # no master passing + x = constructor() + self.assertIsNotNone(tkinter._default_root) + self.assertIs(x.master, tkinter._default_root) + self.assertIs(x.tk, tkinter._default_root.tk) + x.destroy() + destroy_default_root() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, constructor) + self.assertNotHasAttr(tkinter, '_default_root') + + +def destroy_default_root(): + if getattr(tkinter, '_default_root', None): + tkinter._default_root.update_idletasks() + tkinter._default_root.destroy() + tkinter._default_root = None + +def wait_until_mapped(widget, timeout=None, *, full_size=False): + """Wait until *widget* is actually mapped and laid out by the window + manager, so that realized-geometry queries (winfo_width(), identify(), + coords(), ...) return meaningful values. + + Return True once the widget is mapped with a non-trivial size, or False + if that has not happened within *timeout* seconds (default: + ``support.LOOPBACK_TIMEOUT``). Unlike Misc.wait_visibility(), this + never blocks indefinitely, so it is safe under a window manager that + never maps the window (see gh-69134, gh-74941, bpo-40722). + + If *full_size* is true, also wait until the realized size reaches the + requested size, so that per-pixel queries near an edge (e.g. identify()) + are reliable even under load. + """ + if timeout is None: + timeout = support.LOOPBACK_TIMEOUT + deadline = time.monotonic() + timeout + widget.update_idletasks() + reset = False + while True: + widget.update() # drain pending Map/Configure events + if widget.winfo_ismapped(): + if full_size: + w_ok = widget.winfo_width() >= widget.winfo_reqwidth() > 1 + h_ok = widget.winfo_height() >= widget.winfo_reqheight() > 1 + else: + w_ok = widget.winfo_width() > 1 + h_ok = widget.winfo_height() > 1 + if w_ok and h_ok: + return True + if full_size and not reset: + # Tk no longer resizes the toplevel to fit its content if + # the window manager has resized it. Undo this. + widget.winfo_toplevel().wm_geometry('') + reset = True + if time.monotonic() >= deadline: + return False + time.sleep(0.01) + + +def simulate_mouse_click(widget, x, y): + """Generate proper events to click at the x, y position (tries to act + like an X server).""" + widget.event_generate('', x=0, y=0) + widget.event_generate('', x=x, y=y) + widget.event_generate('', x=x, y=y) + widget.event_generate('', x=x, y=y) + + +import _tkinter +tcl_version = tuple(map(int, _tkinter.TCL_VERSION.split('.'))) +tk_version = tuple(map(int, _tkinter.TK_VERSION.split('.'))) + +def requires_tk(*version): + if len(version) <= 2 and tk_version >= version: + return lambda test: test + + def deco(test): + @functools.wraps(test) + def newtest(self): + root = getattr(self, 'root', None) + if get_tk_patchlevel(root) < version: + self.skipTest('requires Tk version >= ' + + '.'.join(map(str, version))) + test(self) + return newtest + return deco + +_tk_patchlevel = None +def get_tk_patchlevel(root): + global _tk_patchlevel + if _tk_patchlevel is None: + _tk_patchlevel = tkinter._parse_version(root.tk.globalgetvar('tk_patchLevel')) + return _tk_patchlevel + +units = { + 'c': 72 / 2.54, # centimeters + 'i': 72, # inches + 'm': 72 / 25.4, # millimeters + 'p': 1, # points +} + +def pixels_conv(value): + return float(value[:-1]) * units[value[-1:]] + +def tcl_obj_eq(actual, expected): + if actual == expected: + return True + if isinstance(actual, _tkinter.Tcl_Obj): + if isinstance(expected, str): + return str(actual) == expected + if isinstance(actual, tuple): + if isinstance(expected, tuple): + return (len(actual) == len(expected) and + all(tcl_obj_eq(act, exp) + for act, exp in zip(actual, expected))) + return False + +def widget_eq(actual, expected): + if actual == expected: + return True + if isinstance(actual, (str, tkinter.Widget)): + if isinstance(expected, (str, tkinter.Widget)): + return str(actual) == str(expected) + return False diff --git a/Lib/test/test_tkinter/test_colorchooser.py b/Lib/test/test_tkinter/test_colorchooser.py new file mode 100644 index 00000000000..8a7e97f207a --- /dev/null +++ b/Lib/test/test_tkinter/test_colorchooser.py @@ -0,0 +1,69 @@ +import unittest +import tkinter +from test.support import requires, swap_attr +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractDefaultRootTest, AbstractTkTest +from tkinter import colorchooser +from tkinter.colorchooser import askcolor +from tkinter.commondialog import Dialog + +requires('gui') + + +class ChooserTest(AbstractTkTest, unittest.TestCase): + + @classmethod + def setUpClass(cls): + AbstractTkTest.setUpClass.__func__(cls) + cls.cc = colorchooser.Chooser(initialcolor='dark blue slate') + + def test_fixoptions(self): + cc = self.cc + cc._fixoptions() + self.assertEqual(cc.options['initialcolor'], 'dark blue slate') + + cc.options['initialcolor'] = '#D2D269691E1E' + cc._fixoptions() + self.assertEqual(cc.options['initialcolor'], '#D2D269691E1E') + + cc.options['initialcolor'] = (210, 105, 30) + cc._fixoptions() + self.assertEqual(cc.options['initialcolor'], '#d2691e') + + def test_fixresult(self): + cc = self.cc + self.assertEqual(cc._fixresult(self.root, ()), (None, None)) + self.assertEqual(cc._fixresult(self.root, ''), (None, None)) + self.assertEqual(cc._fixresult(self.root, 'chocolate'), + ((210, 105, 30), 'chocolate')) + self.assertEqual(cc._fixresult(self.root, '#4a3c8c'), + ((74, 60, 140), '#4a3c8c')) + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_askcolor(self): + def test_callback(dialog, master): + nonlocal ismapped + master.update() + ismapped = master.winfo_ismapped() + raise ZeroDivisionError + + with swap_attr(Dialog, '_test_callback', test_callback): + ismapped = None + self.assertRaises(ZeroDivisionError, askcolor) + #askcolor() + self.assertEqual(ismapped, False) + + root = tkinter.Tk() + ismapped = None + self.assertRaises(ZeroDivisionError, askcolor) + self.assertEqual(ismapped, True) + root.destroy() + + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, askcolor) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_dnd.py b/Lib/test/test_tkinter/test_dnd.py new file mode 100644 index 00000000000..fe3685aefe4 --- /dev/null +++ b/Lib/test/test_tkinter/test_dnd.py @@ -0,0 +1,171 @@ +import unittest +import tkinter +from tkinter import dnd +from test.support import requires +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractTkTest + +requires('gui') + + +class Target: + def __init__(self, widget, log): + self.widget = widget + self.log = log + widget.dnd_accept = self.dnd_accept + + def dnd_accept(self, source, event): + self.log.append('accept') + return self + + def dnd_enter(self, source, event): + self.log.append('enter') + + def dnd_motion(self, source, event): + self.log.append('motion') + + def dnd_leave(self, source, event): + self.log.append('leave') + + def dnd_commit(self, source, event): + self.log.append('commit') + + +class Source: + def __init__(self, log): + self.log = log + + def dnd_end(self, target, event): + self.log.append('end') + + +class FakeEvent: + def __init__(self, widget, num=1): + self.num = num + self.widget = widget + self.x = self.y = self.x_root = self.y_root = 0 + + +class DndTest(AbstractTkTest, unittest.TestCase): + + def setUp(self): + super().setUp() + self.canvas = tkinter.Canvas(self.root) + self.canvas.pack() + # on_motion() locates the target with winfo_containing(). Bypass that + # real screen lookup, which depends on the window being visible and + # unobscured, so the test does not hinge on the window manager. + self.canvas.winfo_containing = lambda x, y: self.canvas + self.log = [] + self.source = Source(self.log) + self.target = Target(self.canvas, self.log) + + def tearDown(self): + # Make sure no drag-and-drop is left active between tests: the + # recursion guard is a name-mangled attribute on the root. + try: + del self.root._DndHandler__dnd + except AttributeError: + pass + super().tearDown() + + def test_drag_and_drop(self): + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + self.assertIsNotNone(handler) + handler.on_motion(FakeEvent(self.canvas)) # Enter the target. + handler.on_motion(FakeEvent(self.canvas)) # Move within the target. + handler.on_release(FakeEvent(self.canvas)) # Drop on the target. + self.assertEqual(self.log, + ['accept', 'enter', 'accept', 'motion', 'commit', 'end']) + + def test_cancel(self): + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + handler.on_motion(FakeEvent(self.canvas)) # Enter the target. + handler.cancel() # Leaves the target without committing. + self.assertEqual(self.log, ['accept', 'enter', 'leave', 'end']) + + def test_no_target(self): + # Nothing under the pointer accepts the drag. + self.canvas.winfo_containing = lambda x, y: None + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + handler.on_motion(FakeEvent(self.canvas)) + handler.on_release(FakeEvent(self.canvas)) + self.assertEqual(self.log, ['end']) + + def test_no_recursive_start(self): + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + self.assertIsNotNone(handler) + # A drag is already in progress, so a second start is ignored. + self.assertIsNone(dnd.dnd_start(self.source, FakeEvent(self.canvas))) + handler.cancel() + + def test_high_button_number_ignored(self): + self.assertIsNone(dnd.dnd_start(self.source, FakeEvent(self.canvas, num=6))) + + def test_restart_after_finish(self): + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + handler.cancel() + # Once a drag has finished a new one can start. + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + self.assertIsNotNone(handler) + handler.cancel() + + def test_drag_cursor(self): + self.canvas['cursor'] = 'watch' + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + # The drag cursor is shown while dragging, the original restored after. + self.assertEqual(handler.save_cursor, 'watch') + self.assertEqual(str(self.canvas['cursor']), 'hand2') + handler.cancel() + self.assertEqual(str(self.canvas['cursor']), 'watch') + + def test_bindings_added_and_removed(self): + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + self.assertIn('', self.canvas.bind()) + self.assertIn('', self.canvas.bind()) + handler.cancel() + self.assertNotIn('', self.canvas.bind()) + self.assertNotIn('', self.canvas.bind()) + + def test_switch_target(self): + log1, log2 = [], [] + w1, w2 = tkinter.Frame(self.root), tkinter.Frame(self.root) + target1, target2 = Target(w1, log1), Target(w2, log2) + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + self.canvas.winfo_containing = lambda x, y: w1 + handler.on_motion(FakeEvent(self.canvas)) # Enter target1. + self.canvas.winfo_containing = lambda x, y: w2 + handler.on_motion(FakeEvent(self.canvas)) # Leave target1, enter target2. + self.assertIs(handler.target, target2) + self.assertEqual(log1, ['accept', 'enter', 'leave']) + self.assertEqual(log2, ['accept', 'enter']) + handler.cancel() + + def test_target_in_ancestor(self): + # The widget under the pointer has no dnd_accept, but an ancestor + # does: the search walks up the master chain to find it. + parent = tkinter.Frame(self.root) + target = Target(parent, self.log) + child = tkinter.Frame(parent) + self.canvas.winfo_containing = lambda x, y: child + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + handler.on_motion(FakeEvent(self.canvas)) + self.assertIs(handler.target, target) + self.assertEqual(self.log, ['accept', 'enter']) + handler.cancel() + + def test_accept_returning_none_continues(self): + # dnd_accept() returning None means "not me, keep looking up". + parent = tkinter.Frame(self.root) + target = Target(parent, self.log) + child = tkinter.Frame(parent) + child.dnd_accept = lambda source, event: None + self.canvas.winfo_containing = lambda x, y: child + handler = dnd.dnd_start(self.source, FakeEvent(self.canvas)) + handler.on_motion(FakeEvent(self.canvas)) + self.assertIs(handler.target, target) + handler.cancel() + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_filedialog.py b/Lib/test/test_tkinter/test_filedialog.py new file mode 100644 index 00000000000..e4e0f2b26c3 --- /dev/null +++ b/Lib/test/test_tkinter/test_filedialog.py @@ -0,0 +1,73 @@ +import os +import unittest +from tkinter import filedialog +from tkinter.commondialog import Dialog +from test.support import requires, swap_attr +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractDialogTest, AbstractTkTest + +requires('gui') + + +class NativeDialogTest(AbstractTkTest, unittest.TestCase): + # Open, SaveAs and Directory wrap modal native dialogs. The _test_callback + # seam is called by show() just before the dialog would open; replacing it + # with a function that raises exercises show() without blocking on the + # dialog. + + def check(self, dialog_class, command): + self.assertEqual(dialog_class.command, command) + master = None + def test_callback(dialog, parent): + nonlocal master + master = parent + raise ZeroDivisionError + with swap_attr(Dialog, '_test_callback', test_callback): + d = dialog_class(self.root, title='Test') + self.assertRaises(ZeroDivisionError, d.show) + self.assertIs(master, self.root) + + def test_open(self): + self.check(filedialog.Open, 'tk_getOpenFile') + + def test_saveas(self): + self.check(filedialog.SaveAs, 'tk_getSaveFile') + + def test_directory(self): + self.check(filedialog.Directory, 'tk_chooseDirectory') + + +class FileDialogTest(AbstractDialogTest, unittest.TestCase): + # The pure-Python FileDialog runs its own modal loop in go(); its logic is + # exercised here without entering the loop. + + def test_selection(self): + d = filedialog.FileDialog(self.root) + d.directory = os.path.abspath(os.sep) + d.set_selection('spam.txt') + self.assertEqual(os.path.basename(d.get_selection()), 'spam.txt') + + def test_filter(self): + d = filedialog.FileDialog(self.root) + d.set_filter(os.getcwd(), '*.py') + self.assertEqual(d.get_filter(), (os.getcwd(), '*.py')) + + def test_ok_cancel(self): + d = filedialog.FileDialog(self.root) + d.directory = os.getcwd() + d.set_selection('spam.txt') + d.ok_command() # Accepts the current selection. + self.assertEqual(os.path.basename(d.how), 'spam.txt') + d.cancel_command() # Returns no selection. + self.assertIsNone(d.how) + + def test_subclasses(self): + for cls in filedialog.LoadFileDialog, filedialog.SaveFileDialog: + with self.subTest(cls=cls.__name__): + d = cls(self.root) + self.assertIsInstance(d, filedialog.FileDialog) + self.assertEqual(d.top.title(), cls.title) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_font.py b/Lib/test/test_tkinter/test_font.py new file mode 100644 index 00000000000..db9fc35934c --- /dev/null +++ b/Lib/test/test_tkinter/test_font.py @@ -0,0 +1,281 @@ +import collections.abc +import unittest +import tkinter +from tkinter import font +from test.support import requires, gc_collect, ALWAYS_EQ +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractTkTest, AbstractDefaultRootTest + +requires('gui') + +fontname = "TkDefaultFont" + +class FontTest(AbstractTkTest, unittest.TestCase): + + @classmethod + def setUpClass(cls): + AbstractTkTest.setUpClass.__func__(cls) + try: + cls.font = font.Font(root=cls.root, name=fontname, exists=True) + except tkinter.TclError: + cls.font = font.Font(root=cls.root, name=fontname, exists=False) + + def tcl_font_object(self, desc): + # Return a font name or description as a Tcl object representing a + # font, as Tk returns for example from ttk.Style().lookup(). + tk = self.root.tk + tk.call('set', '_font', desc) + tk.eval('font measure $_font x') # convert the Tcl object to a font + obj = tk.call('set', '_font') + tk.call('unset', '_font') + return obj + + def test_configure(self): + self.assertEqual(self.font.config, self.font.configure) + options = self.font.configure() + self.assertGreaterEqual(set(options), + {'family', 'size', 'weight', 'slant', 'underline', 'overstrike'}) + for key in options: + self.assertEqual(self.font.cget(key), options[key]) + self.assertEqual(self.font[key], options[key]) + for key in 'family', 'weight', 'slant': + self.assertIsInstance(options[key], str) + self.assertIsInstance(self.font.cget(key), str) + self.assertIsInstance(self.font[key], str) + sizetype = int if self.wantobjects else str + for key in 'size', 'underline', 'overstrike': + self.assertIsInstance(options[key], sizetype) + self.assertIsInstance(self.font.cget(key), sizetype) + self.assertIsInstance(self.font[key], sizetype) + self.assertRaisesRegex(tkinter.TclError, 'bad option "-spam"', + self.font.cget, 'spam') + self.assertRaisesRegex(tkinter.TclError, 'bad option "-spam"', + self.font.configure, spam='x') + self.assertRaises(TypeError, self.font.cget) + self.assertRaises(TypeError, self.font.cget, 'size', 'weight') + + def test_create_from_named_font(self): + # gh-143990: a font created from a named font copies its configured + # options, preserving a size specified in pixels (a negative size). + sizetype = int if self.wantobjects else str + named = font.Font(root=self.root, name='my named font', # name with spaces + family='Times', size=-20, weight='bold') + # The source is the name of a named font or a Font representing one. + for source in ['my named font', named]: + with self.subTest(source=source): + f = font.Font(root=self.root, font=source) + self.assertEqual(f.cget('size'), sizetype(-20)) + self.assertEqual(f.actual('family'), named.actual('family')) + self.assertEqual(f.actual('weight'), 'bold') + + def test_create_from_description(self): + # gh-143990: a font created from a font description is resolved via + # "font actual", so a size in pixels (negative) becomes a size in points. + descriptions = [ + ('Times', -20), # tuple + ('Times', -20, 'bold'), # tuple with a style + 'Times -20', # string + 'Times -20 bold', # string with a style + '{Times New Roman} -20', # string, family with spaces + ] + for desc in descriptions: + with self.subTest(font=desc): + f = font.Font(root=self.root, font=desc) + self.assertGreater(int(f.cget('size')), 0) # pixels -> points + + def test_tcl_object(self): + # Tk can return a font as a Tcl object (gh-156961). + if not self.wantobjects: + self.skipTest('Tcl objects are converted to strings') + obj = self.tcl_font_object(fontname) + self.assertEqual(obj.typename, 'font') + + # It can be used as the name of an existing named font. + for f in (font.Font(root=self.root, name=obj, exists=True), + font.nametofont(obj, root=self.root)): + # The Tcl object is kept as is, so that it is passed back to Tk. + self.assertIs(f.name, obj) + self.assertEqual(str(f), fontname) + self.assertEqual(f.actual(), self.font.actual()) + self.assertEqual(f, self.font) + self.assertEqual(self.font, f) + # Referring to a non-existent named font still fails. + self.assertRaisesRegex(tkinter.TclError, 'named font nosuchfont', + font.Font, root=self.root, exists=True, + name=self.tcl_font_object('nosuchfont')) + + def test_copy(self): + # size=-20 (pixels): copy() copies the configured options, so the + # size is preserved rather than resolved (gh-143990). + f = font.Font(root=self.root, family='Times', size=-20, weight='bold') + copied = f.copy() + self.assertIsInstance(copied, font.Font) + self.assertIsNot(copied, f) + self.assertNotEqual(copied.name, f.name) + self.assertEqual(copied.actual(), f.actual()) + sizetype = int if self.wantobjects else str + self.assertEqual(copied.cget('size'), sizetype(-20)) + # The copy is independent of the original. + copied.configure(size=20) + self.assertEqual(f.cget('size'), sizetype(-20)) + self.assertEqual(copied.cget('size'), sizetype(20)) + self.assertRaises(TypeError, f.copy, 'x') + + def test_unicode_family(self): + family = 'MS \u30b4\u30b7\u30c3\u30af' + try: + f = font.Font(root=self.root, family=family, exists=True) + except tkinter.TclError: + f = font.Font(root=self.root, family=family, exists=False) + self.assertEqual(f.cget('family'), family) + del f + gc_collect() + + def test_actual(self): + options = self.font.actual() + self.assertGreaterEqual(set(options), + {'family', 'size', 'weight', 'slant', 'underline', 'overstrike'}) + for key in options: + self.assertEqual(self.font.actual(key), options[key]) + for key in 'family', 'weight', 'slant': + self.assertIsInstance(options[key], str) + self.assertIsInstance(self.font.actual(key), str) + sizetype = int if self.wantobjects else str + for key in 'size', 'underline', 'overstrike': + self.assertIsInstance(options[key], sizetype) + self.assertIsInstance(self.font.actual(key), sizetype) + self.assertRaisesRegex(tkinter.TclError, 'bad option "-spam"', + self.font.actual, 'spam') + self.assertRaises(TypeError, self.font.actual, 'size', 'weight', 'slant') + + def test_name(self): + self.assertEqual(self.font.name, fontname) + self.assertEqual(str(self.font), fontname) + + def test_equality(self): + font1 = font.Font(root=self.root, name=fontname, exists=True) + font2 = font.Font(root=self.root, name=fontname, exists=True) + self.assertIsNot(font1, font2) + self.assertEqual(font1, font2) + self.assertNotEqual(font1, font1.copy()) + + self.assertNotEqual(font1, 0) + self.assertEqual(font1, ALWAYS_EQ) + + root2 = tkinter.Tk() + self.addCleanup(root2.destroy) + font3 = font.Font(root=root2, name=fontname, exists=True) + self.assertEqual(str(font1), str(font3)) + self.assertNotEqual(font1, font3) + + def test_measure(self): + self.assertIsInstance(self.font.measure('abc'), int) + self.assertEqual(self.font.measure(''), 0) + self.assertIsInstance( + self.font.measure('abc', displayof=self.root), int) + self.assertRaises(TypeError, self.font.measure) + self.assertRaises(TypeError, self.font.measure, 'a', 'b', 'c') + + def test_metrics(self): + metrics = self.font.metrics() + self.assertGreaterEqual(set(metrics), + {'ascent', 'descent', 'linespace', 'fixed'}) + for key in metrics: + self.assertEqual(self.font.metrics(key), metrics[key]) + self.assertEqual(self.font.metrics(key, displayof=self.root), + metrics[key]) + self.assertIsInstance(metrics[key], int) + self.assertIsInstance(self.font.metrics(key), int) + self.assertRaisesRegex(tkinter.TclError, 'bad metric "-spam"', + self.font.metrics, 'spam') + + def test_families(self): + families = font.families(self.root) + self.assertIsInstance(families, tuple) + self.assertTrue(families) + for family in families: + self.assertIsInstance(family, str) + self.assertTrue(family) + + def test_names(self): + names = font.names(self.root) + self.assertIsInstance(names, tuple) + self.assertTrue(names) + for name in names: + self.assertIsInstance(name, str) + self.assertTrue(name) + self.assertIn(fontname, names) + + def test_nametofont(self): + testfont = font.nametofont(fontname, root=self.root) + self.assertIsInstance(testfont, font.Font) + self.assertEqual(testfont.name, fontname) + + def test_repr(self): + self.assertEqual( + repr(self.font), f'' + ) + + def test_iterable_protocol(self): + self.assertNotIsSubclass(font.Font, collections.abc.Iterable) + self.assertNotIsSubclass(font.Font, collections.abc.Container) + self.assertNotIsInstance(self.font, collections.abc.Iterable) + self.assertNotIsInstance(self.font, collections.abc.Container) + with self.assertRaisesRegex(TypeError, 'is not iterable'): + iter(self.font) + with self.assertRaisesRegex(TypeError, 'is not a container or iterable'): + self.font in self.font + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_families(self): + self.assertRaises(RuntimeError, font.families) + root = tkinter.Tk() + families = font.families() + self.assertIsInstance(families, tuple) + self.assertTrue(families) + for family in families: + self.assertIsInstance(family, str) + self.assertTrue(family) + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, font.families) + + def test_names(self): + self.assertRaises(RuntimeError, font.names) + root = tkinter.Tk() + names = font.names() + self.assertIsInstance(names, tuple) + self.assertTrue(names) + for name in names: + self.assertIsInstance(name, str) + self.assertTrue(name) + self.assertIn(fontname, names) + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, font.names) + + def test_nametofont(self): + self.assertRaises(RuntimeError, font.nametofont, fontname) + root = tkinter.Tk() + testfont = font.nametofont(fontname) + self.assertIsInstance(testfont, font.Font) + self.assertEqual(testfont.name, fontname) + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, font.nametofont, fontname) + + +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(font, "__version__") + self.assertEqual(cm.filename, __file__) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_geometry_managers.py b/Lib/test/test_tkinter/test_geometry_managers.py new file mode 100644 index 00000000000..e98a6af060e --- /dev/null +++ b/Lib/test/test_tkinter/test_geometry_managers.py @@ -0,0 +1,1001 @@ +import unittest +import re +import tkinter +from tkinter import TclError +from test.support import requires + +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import pixels_conv +from test.test_tkinter.widget_tests import AbstractWidgetTest + +requires('gui') + + +EXPECTED_FLOAT_ERRMSG = 'expected floating-point number but got "{}"' +EXPECTED_FLOAT_OR_EMPTY_ERRMSG = 'expected floating-point number (or "" )?but got "{}"' +EXPECTED_SCREEN_DISTANCE_ERRMSG = '(bad|expected) screen distance (but got )?"{}"' +EXPECTED_SCREEN_DISTANCE_OR_EMPTY_ERRMSG = '(bad|expected) screen distance (or "" but got )?"{}"' + +class PackTest(AbstractWidgetTest, unittest.TestCase): + + test_keys = None + test_options_in_docstring = None + + def create2(self): + pack = tkinter.Toplevel(self.root, name='pack') + pack.wm_geometry('300x200+0+0') + pack.wm_minsize(1, 1) + a = tkinter.Frame(pack, name='a', width=20, height=40, bg='red') + b = tkinter.Frame(pack, name='b', width=50, height=30, bg='blue') + c = tkinter.Frame(pack, name='c', width=80, height=80, bg='green') + d = tkinter.Frame(pack, name='d', width=40, height=30, bg='yellow') + return pack, a, b, c, d + + def test_pack_configure_after(self): + pack, a, b, c, d = self.create2() + with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b): + a.pack_configure(after=b) + with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'): + a.pack_configure(after='.foo') + a.pack_configure(side='top') + b.pack_configure(side='top') + c.pack_configure(side='top') + d.pack_configure(side='top') + self.assertEqual(pack.pack_content(), [a, b, c, d]) + a.pack_configure(after=b) + self.assertEqual(pack.pack_content(), [b, a, c, d]) + a.pack_configure(after=a) + self.assertEqual(pack.pack_content(), [b, a, c, d]) + + def test_pack_configure_anchor(self): + pack, a, b, c, d = self.create2() + def check(anchor, geom): + a.pack_configure(side='top', ipadx=5, padx=10, ipady=15, pady=20, + expand=True, anchor=anchor) + self.root.update() + self.assertEqual(a.winfo_geometry(), geom) + check('n', '30x70+135+20') + check('ne', '30x70+260+20') + check('e', '30x70+260+65') + check('se', '30x70+260+110') + check('s', '30x70+135+110') + check('sw', '30x70+10+110') + check('w', '30x70+10+65') + check('nw', '30x70+10+20') + check('center', '30x70+135+65') + + def test_pack_configure_before(self): + pack, a, b, c, d = self.create2() + with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % b): + a.pack_configure(before=b) + with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'): + a.pack_configure(before='.foo') + a.pack_configure(side='top') + b.pack_configure(side='top') + c.pack_configure(side='top') + d.pack_configure(side='top') + self.assertEqual(pack.pack_content(), [a, b, c, d]) + a.pack_configure(before=d) + self.assertEqual(pack.pack_content(), [b, c, a, d]) + a.pack_configure(before=a) + self.assertEqual(pack.pack_content(), [b, c, a, d]) + + def test_pack_configure_expand(self): + pack, a, b, c, d = self.create2() + def check(*geoms): + self.root.update() + self.assertEqual(a.winfo_geometry(), geoms[0]) + self.assertEqual(b.winfo_geometry(), geoms[1]) + self.assertEqual(c.winfo_geometry(), geoms[2]) + self.assertEqual(d.winfo_geometry(), geoms[3]) + a.pack_configure(side='left') + b.pack_configure(side='top') + c.pack_configure(side='right') + d.pack_configure(side='bottom') + check('20x40+0+80', '50x30+135+0', '80x80+220+75', '40x30+100+170') + a.pack_configure(side='left', expand='yes') + b.pack_configure(side='top', expand='on') + c.pack_configure(side='right', expand=True) + d.pack_configure(side='bottom', expand=1) + check('20x40+40+80', '50x30+175+35', '80x80+180+110', '40x30+100+135') + a.pack_configure(side='left', expand='yes', fill='both') + b.pack_configure(side='top', expand='on', fill='both') + c.pack_configure(side='right', expand=True, fill='both') + d.pack_configure(side='bottom', expand=1, fill='both') + check('100x200+0+0', '200x100+100+0', '160x100+140+100', '40x100+100+100') + + def test_pack_configure_in(self): + pack, a, b, c, d = self.create2() + a.pack_configure(side='top') + b.pack_configure(side='top') + c.pack_configure(side='top') + d.pack_configure(side='top') + a.pack_configure(in_=pack) + self.assertEqual(pack.pack_content(), [b, c, d, a]) + a.pack_configure(in_=c) + self.assertEqual(pack.pack_content(), [b, c, d]) + self.assertEqual(c.pack_content(), [a]) + with self.assertRaisesRegex( + TclError, """can't pack "?%s"? inside itself""" % (a,)): + a.pack_configure(in_=a) + with self.assertRaisesRegex(TclError, 'bad window path name ".foo"'): + a.pack_configure(in_='.foo') + + def test_pack_configure_padx_ipadx_fill(self): + pack, a, b, c, d = self.create2() + def check(geom1, geom2, **kwargs): + a.pack_forget() + b.pack_forget() + a.pack_configure(**kwargs) + b.pack_configure(expand=True, fill='both') + self.root.update() + self.assertEqual(a.winfo_geometry(), geom1) + self.assertEqual(b.winfo_geometry(), geom2) + check('20x40+260+80', '240x200+0+0', side='right', padx=20) + check('20x40+250+80', '240x200+0+0', side='right', padx=(10, 30)) + check('60x40+240+80', '240x200+0+0', side='right', ipadx=20) + check('30x40+260+80', '250x200+0+0', side='right', ipadx=5, padx=10) + check('20x40+260+80', '240x200+0+0', side='right', padx=20, fill='x') + check('20x40+249+80', '240x200+0+0', + side='right', padx=(9, 31), fill='x') + check('60x40+240+80', '240x200+0+0', side='right', ipadx=20, fill='x') + check('30x40+260+80', '250x200+0+0', + side='right', ipadx=5, padx=10, fill='x') + check('30x40+255+80', '250x200+0+0', + side='right', ipadx=5, padx=(5, 15), fill='x') + check('20x40+140+0', '300x160+0+40', side='top', padx=20) + check('20x40+120+0', '300x160+0+40', side='top', padx=(0, 40)) + check('60x40+120+0', '300x160+0+40', side='top', ipadx=20) + check('30x40+135+0', '300x160+0+40', side='top', ipadx=5, padx=10) + check('30x40+130+0', '300x160+0+40', side='top', ipadx=5, padx=(5, 15)) + check('260x40+20+0', '300x160+0+40', side='top', padx=20, fill='x') + check('260x40+25+0', '300x160+0+40', + side='top', padx=(25, 15), fill='x') + check('300x40+0+0', '300x160+0+40', side='top', ipadx=20, fill='x') + check('280x40+10+0', '300x160+0+40', + side='top', ipadx=5, padx=10, fill='x') + check('280x40+5+0', '300x160+0+40', + side='top', ipadx=5, padx=(5, 15), fill='x') + a.pack_configure(padx='1c') + self.assertEqual(a.pack_info()['padx'], + self._str(pack.winfo_pixels('1c'))) + a.pack_configure(ipadx='1c') + self.assertEqual(a.pack_info()['ipadx'], + self._str(pack.winfo_pixels('1c'))) + + def test_pack_configure_pady_ipady_fill(self): + pack, a, b, c, d = self.create2() + def check(geom1, geom2, **kwargs): + a.pack_forget() + b.pack_forget() + a.pack_configure(**kwargs) + b.pack_configure(expand=True, fill='both') + self.root.update() + self.assertEqual(a.winfo_geometry(), geom1) + self.assertEqual(b.winfo_geometry(), geom2) + check('20x40+280+80', '280x200+0+0', side='right', pady=20) + check('20x40+280+70', '280x200+0+0', side='right', pady=(10, 30)) + check('20x80+280+60', '280x200+0+0', side='right', ipady=20) + check('20x50+280+75', '280x200+0+0', side='right', ipady=5, pady=10) + check('20x40+280+80', '280x200+0+0', side='right', pady=20, fill='x') + check('20x40+280+69', '280x200+0+0', + side='right', pady=(9, 31), fill='x') + check('20x80+280+60', '280x200+0+0', side='right', ipady=20, fill='x') + check('20x50+280+75', '280x200+0+0', + side='right', ipady=5, pady=10, fill='x') + check('20x50+280+70', '280x200+0+0', + side='right', ipady=5, pady=(5, 15), fill='x') + check('20x40+140+20', '300x120+0+80', side='top', pady=20) + check('20x40+140+0', '300x120+0+80', side='top', pady=(0, 40)) + check('20x80+140+0', '300x120+0+80', side='top', ipady=20) + check('20x50+140+10', '300x130+0+70', side='top', ipady=5, pady=10) + check('20x50+140+5', '300x130+0+70', side='top', ipady=5, pady=(5, 15)) + check('300x40+0+20', '300x120+0+80', side='top', pady=20, fill='x') + check('300x40+0+25', '300x120+0+80', + side='top', pady=(25, 15), fill='x') + check('300x80+0+0', '300x120+0+80', side='top', ipady=20, fill='x') + check('300x50+0+10', '300x130+0+70', + side='top', ipady=5, pady=10, fill='x') + check('300x50+0+5', '300x130+0+70', + side='top', ipady=5, pady=(5, 15), fill='x') + a.pack_configure(pady='1c') + self.assertEqual(a.pack_info()['pady'], + self._str(pack.winfo_pixels('1c'))) + a.pack_configure(ipady='1c') + self.assertEqual(a.pack_info()['ipady'], + self._str(pack.winfo_pixels('1c'))) + + def test_pack_configure_side(self): + pack, a, b, c, d = self.create2() + def check(side, geom1, geom2): + a.pack_configure(side=side) + self.assertEqual(a.pack_info()['side'], side) + b.pack_configure(expand=True, fill='both') + self.root.update() + self.assertEqual(a.winfo_geometry(), geom1) + self.assertEqual(b.winfo_geometry(), geom2) + check('top', '20x40+140+0', '300x160+0+40') + check('bottom', '20x40+140+160', '300x160+0+0') + check('left', '20x40+0+80', '280x200+20+0') + check('right', '20x40+280+80', '280x200+0+0') + + def test_pack_forget(self): + pack, a, b, c, d = self.create2() + a.pack_configure() + b.pack_configure() + c.pack_configure() + self.assertEqual(pack.pack_content(), [a, b, c]) + b.pack_forget() + self.assertEqual(pack.pack_content(), [a, c]) + b.pack_forget() + self.assertEqual(pack.pack_content(), [a, c]) + d.pack_forget() + + def test_pack_info(self): + pack, a, b, c, d = self.create2() + with self.assertRaisesRegex(TclError, 'window "%s" isn\'t packed' % a): + a.pack_info() + a.pack_configure() + b.pack_configure(side='right', in_=a, anchor='s', expand=True, fill='x', + ipadx=5, padx=10, ipady=2, pady=(5, 15)) + info = a.pack_info() + self.assertIsInstance(info, dict) + self.assertEqual(info['anchor'], 'center') + self.assertEqual(info['expand'], self._str(0)) + self.assertEqual(info['fill'], 'none') + self.assertEqual(info['in'], pack) + self.assertEqual(info['ipadx'], self._str(0)) + self.assertEqual(info['ipady'], self._str(0)) + self.assertEqual(info['padx'], self._str(0)) + self.assertEqual(info['pady'], self._str(0)) + self.assertEqual(info['side'], 'top') + info = b.pack_info() + self.assertIsInstance(info, dict) + self.assertEqual(info['anchor'], 's') + self.assertEqual(info['expand'], self._str(1)) + self.assertEqual(info['fill'], 'x') + self.assertEqual(info['in'], a) + self.assertEqual(info['ipadx'], self._str(5)) + self.assertEqual(info['ipady'], self._str(2)) + self.assertEqual(info['padx'], self._str(10)) + self.assertEqual(info['pady'], self._str((5, 15))) + self.assertEqual(info['side'], 'right') + + def test_pack_propagate(self): + pack, a, b, c, d = self.create2() + pack.configure(width=300, height=200) + a.pack_configure() + pack.pack_propagate(False) + self.root.update() + self.assertEqual(pack.winfo_reqwidth(), 300) + self.assertEqual(pack.winfo_reqheight(), 200) + pack.pack_propagate(True) + self.root.update() + self.assertEqual(pack.winfo_reqwidth(), 20) + self.assertEqual(pack.winfo_reqheight(), 40) + + def test_pack_content(self): + pack, a, b, c, d = self.create2() + self.assertEqual(pack.pack_content(), []) + a.pack_configure() + self.assertEqual(pack.pack_content(), [a]) + b.pack_configure() + self.assertEqual(pack.pack_content(), [a, b]) + + def test_pack_slaves(self): + pack, a, b, c, d = self.create2() + self.assertEqual(pack.pack_slaves(), []) + a.pack_configure() + self.assertEqual(pack.pack_slaves(), [a]) + b.pack_configure() + self.assertEqual(pack.pack_slaves(), [a, b]) + + def test_pack_short_aliases(self): + # slaves, content and propagate are aliases of the pack_* methods + # (Misc precedes Pack, Place and Grid in the method resolution order). + pack, a, b, c, d = self.create2() + self.assertEqual(pack.slaves, pack.pack_slaves) + self.assertEqual(pack.content, pack.pack_content) + self.assertEqual(pack.propagate, pack.pack_propagate) + + self.assertEqual(pack.slaves(), []) + a.pack_configure() + self.assertEqual(pack.slaves(), [a]) + self.assertEqual(pack.content(), [a]) + + pack.configure(width=300, height=200) + pack.propagate(False) + self.root.update() + self.assertEqual(pack.winfo_reqwidth(), 300) + self.assertEqual(pack.winfo_reqheight(), 200) + + +class PlaceTest(AbstractWidgetTest, unittest.TestCase): + + test_keys = None + test_options_in_docstring = None + + def create2(self): + t = tkinter.Toplevel(self.root, width=300, height=200, bd=0) + t.wm_geometry('300x200+0+0') + f = tkinter.Frame(t, width=154, height=84, bd=2, relief='raised') + f.place_configure(x=48, y=38) + f2 = tkinter.Frame(t, width=30, height=60, bd=2, relief='raised') + self.root.update() + return t, f, f2 + + def test_place_configure_in(self): + t, f, f2 = self.create2() + self.assertEqual(f2.winfo_manager(), '') + with self.assertRaisesRegex( + TclError, + """can't place "?%s"? relative to itself""" + % re.escape(str(f2))): + f2.place_configure(in_=f2) + self.assertEqual(f2.winfo_manager(), '') + with self.assertRaisesRegex(TclError, 'bad window path name'): + f2.place_configure(in_='spam') + f2.place_configure(in_=f) + self.assertEqual(f2.winfo_manager(), 'place') + + def test_place_configure_x(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f) + self.assertEqual(f2.place_info()['x'], '0') + self.root.update() + self.assertEqual(f2.winfo_x(), 50) + f2.place_configure(x=100) + self.assertEqual(f2.place_info()['x'], '100') + self.root.update() + self.assertEqual(f2.winfo_x(), 150) + f2.place_configure(x=-10, relx=1) + self.assertEqual(f2.place_info()['x'], '-10') + self.root.update() + self.assertEqual(f2.winfo_x(), 190) + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('spam')): + f2.place_configure(in_=f, x='spam') + + def test_place_configure_y(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f) + self.assertEqual(f2.place_info()['y'], '0') + self.root.update() + self.assertEqual(f2.winfo_y(), 40) + f2.place_configure(y=50) + self.assertEqual(f2.place_info()['y'], '50') + self.root.update() + self.assertEqual(f2.winfo_y(), 90) + f2.place_configure(y=-10, rely=1) + self.assertEqual(f2.place_info()['y'], '-10') + self.root.update() + self.assertEqual(f2.winfo_y(), 110) + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('spam')): + f2.place_configure(in_=f, y='spam') + + def test_place_configure_relx(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f) + self.assertEqual(f2.place_info()['relx'], '0') + self.root.update() + self.assertEqual(f2.winfo_x(), 50) + f2.place_configure(relx=0.5) + self.assertEqual(f2.place_info()['relx'], '0.5') + self.root.update() + self.assertEqual(f2.winfo_x(), 125) + f2.place_configure(relx=1) + self.assertEqual(f2.place_info()['relx'], '1') + self.root.update() + self.assertEqual(f2.winfo_x(), 200) + with self.assertRaisesRegex(TclError, EXPECTED_FLOAT_ERRMSG.format('spam')): + f2.place_configure(in_=f, relx='spam') + + def test_place_configure_rely(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f) + self.assertEqual(f2.place_info()['rely'], '0') + self.root.update() + self.assertEqual(f2.winfo_y(), 40) + f2.place_configure(rely=0.5) + self.assertEqual(f2.place_info()['rely'], '0.5') + self.root.update() + self.assertEqual(f2.winfo_y(), 80) + f2.place_configure(rely=1) + self.assertEqual(f2.place_info()['rely'], '1') + self.root.update() + self.assertEqual(f2.winfo_y(), 120) + with self.assertRaisesRegex(TclError, EXPECTED_FLOAT_ERRMSG.format('spam')): + f2.place_configure(in_=f, rely='spam') + + def test_place_configure_anchor(self): + f = tkinter.Frame(self.root) + with self.assertRaisesRegex(TclError, 'bad anchor "j"'): + f.place_configure(anchor='j') + with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'): + f.place_configure(anchor='') + for value in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center': + f.place_configure(anchor=value) + self.assertEqual(f.place_info()['anchor'], value) + + def test_place_configure_width(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f, width=120) + self.root.update() + self.assertEqual(f2.winfo_width(), 120) + f2.place_configure(width='') + self.root.update() + self.assertEqual(f2.winfo_width(), 30) + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_OR_EMPTY_ERRMSG.format('abcd')): + f2.place_configure(width='abcd') + + def test_place_configure_height(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f, height=120) + self.root.update() + self.assertEqual(f2.winfo_height(), 120) + f2.place_configure(height='') + self.root.update() + self.assertEqual(f2.winfo_height(), 60) + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_OR_EMPTY_ERRMSG.format('abcd')): + f2.place_configure(height='abcd') + + def test_place_configure_relwidth(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f, relwidth=0.5) + self.root.update() + self.assertEqual(f2.winfo_width(), 75) + f2.place_configure(relwidth='') + self.root.update() + self.assertEqual(f2.winfo_width(), 30) + with self.assertRaisesRegex(TclError, EXPECTED_FLOAT_OR_EMPTY_ERRMSG.format('abcd')): + f2.place_configure(relwidth='abcd') + + def test_place_configure_relheight(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f, relheight=0.5) + self.root.update() + self.assertEqual(f2.winfo_height(), 40) + f2.place_configure(relheight='') + self.root.update() + self.assertEqual(f2.winfo_height(), 60) + with self.assertRaisesRegex(TclError, EXPECTED_FLOAT_OR_EMPTY_ERRMSG.format('abcd')): + f2.place_configure(relheight='abcd') + + def test_place_configure_bordermode(self): + f = tkinter.Frame(self.root) + with self.assertRaisesRegex(TclError, 'bad bordermode "j"'): + f.place_configure(bordermode='j') + with self.assertRaisesRegex(TclError, 'ambiguous bordermode ""'): + f.place_configure(bordermode='') + for value in 'inside', 'outside', 'ignore': + f.place_configure(bordermode=value) + self.assertEqual(f.place_info()['bordermode'], value) + + def test_place_forget(self): + foo = tkinter.Frame(self.root) + foo.place_configure(width=50, height=50) + self.root.update() + foo.place_forget() + self.root.update() + self.assertFalse(foo.winfo_ismapped()) + with self.assertRaises(TypeError): + foo.place_forget(0) + + def test_place_info(self): + t, f, f2 = self.create2() + f2.place_configure(in_=f, x=1, y=2, width=3, height=4, + relx=0.1, rely=0.2, relwidth=0.3, relheight=0.4, + anchor='se', bordermode='outside') + info = f2.place_info() + self.assertIsInstance(info, dict) + self.assertEqual(info['x'], '1') + self.assertEqual(info['y'], '2') + self.assertEqual(info['width'], '3') + self.assertEqual(info['height'], '4') + self.assertEqual(info['relx'], '0.1') + self.assertEqual(info['rely'], '0.2') + self.assertEqual(info['relwidth'], '0.3') + self.assertEqual(info['relheight'], '0.4') + self.assertEqual(info['anchor'], 'se') + self.assertEqual(info['bordermode'], 'outside') + self.assertEqual(info['x'], '1') + self.assertEqual(info['x'], '1') + with self.assertRaises(TypeError): + f2.place_info(0) + + def test_place_content(self): + foo = tkinter.Frame(self.root) + bar = tkinter.Frame(self.root) + self.assertEqual(foo.place_content(), []) + bar.place_configure(in_=foo) + self.assertEqual(foo.place_content(), [bar]) + with self.assertRaises(TypeError): + foo.place_content(0) + + def test_place_slaves(self): + foo = tkinter.Frame(self.root) + bar = tkinter.Frame(self.root) + self.assertEqual(foo.place_slaves(), []) + bar.place_configure(in_=foo) + self.assertEqual(foo.place_slaves(), [bar]) + with self.assertRaises(TypeError): + foo.place_slaves(0) + + def test_place_method_aliases(self): + # The Place manager defines configure, info, forget, slaves and + # content as aliases of its place_* methods. On a real widget the + # short names are provided by Misc and Pack (earlier in the method + # resolution order), so the aliases are checked on the class itself. + self.assertIs(tkinter.Place.configure, tkinter.Place.place_configure) + self.assertIs(tkinter.Place.config, tkinter.Place.place_configure) + self.assertIs(tkinter.Place.info, tkinter.Place.place_info) + self.assertIs(tkinter.Place.forget, tkinter.Place.place_forget) + self.assertIs(tkinter.Place.slaves, tkinter.Misc.place_slaves) + self.assertIs(tkinter.Place.content, tkinter.Misc.place_content) + + +class GridTest(AbstractWidgetTest, unittest.TestCase): + + test_keys = None + test_options_in_docstring = None + + def tearDown(self): + cols, rows = self.root.grid_size() + for i in range(cols + 1): + self.root.grid_columnconfigure(i, weight=0, minsize=0, pad=0, uniform='') + for i in range(rows + 1): + self.root.grid_rowconfigure(i, weight=0, minsize=0, pad=0, uniform='') + self.root.grid_propagate(1) + self.root.grid_anchor('nw') + super().tearDown() + + def test_grid_configure(self): + b = tkinter.Button(self.root) + self.assertEqual(b.grid_info(), {}) + b.grid_configure() + self.assertEqual(b.grid_info()['in'], self.root) + self.assertEqual(b.grid_info()['column'], self._str(0)) + self.assertEqual(b.grid_info()['row'], self._str(0)) + b.grid_configure({'column': 1}, row=2) + self.assertEqual(b.grid_info()['column'], self._str(1)) + self.assertEqual(b.grid_info()['row'], self._str(2)) + + def test_grid_configure_column(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad column value "-1": ' + 'must be a non-negative integer'): + b.grid_configure(column=-1) + b.grid_configure(column=2) + self.assertEqual(b.grid_info()['column'], self._str(2)) + + def test_grid_configure_columnspan(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad columnspan value "0": ' + 'must be a positive integer'): + b.grid_configure(columnspan=0) + b.grid_configure(columnspan=2) + self.assertEqual(b.grid_info()['columnspan'], self._str(2)) + + def test_grid_configure_in(self): + f = tkinter.Frame(self.root) + b = tkinter.Button(self.root) + self.assertEqual(b.grid_info(), {}) + b.grid_configure() + self.assertEqual(b.grid_info()['in'], self.root) + b.grid_configure(in_=f) + self.assertEqual(b.grid_info()['in'], f) + b.grid_configure({'in': self.root}) + self.assertEqual(b.grid_info()['in'], self.root) + + def test_grid_configure_ipadx(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad ipadx value "-1": ' + 'must be positive screen distance'): + b.grid_configure(ipadx=-1) + b.grid_configure(ipadx=1) + self.assertEqual(b.grid_info()['ipadx'], self._str(1)) + b.grid_configure(ipadx='.5c') + self.assertEqual(b.grid_info()['ipadx'], + self._str(round(pixels_conv('.5c') * self.scaling))) + + def test_grid_configure_ipady(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad ipady value "-1": ' + 'must be positive screen distance'): + b.grid_configure(ipady=-1) + b.grid_configure(ipady=1) + self.assertEqual(b.grid_info()['ipady'], self._str(1)) + b.grid_configure(ipady='.5c') + self.assertEqual(b.grid_info()['ipady'], + self._str(round(pixels_conv('.5c') * self.scaling))) + + def test_grid_configure_padx(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad pad value "-1": ' + 'must be positive screen distance'): + b.grid_configure(padx=-1) + b.grid_configure(padx=1) + self.assertEqual(b.grid_info()['padx'], self._str(1)) + b.grid_configure(padx=(10, 5)) + self.assertEqual(b.grid_info()['padx'], self._str((10, 5))) + b.grid_configure(padx='.5c') + self.assertEqual(b.grid_info()['padx'], + self._str(round(pixels_conv('.5c') * self.scaling))) + + def test_grid_configure_pady(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad pad value "-1": ' + 'must be positive screen distance'): + b.grid_configure(pady=-1) + b.grid_configure(pady=1) + self.assertEqual(b.grid_info()['pady'], self._str(1)) + b.grid_configure(pady=(10, 5)) + self.assertEqual(b.grid_info()['pady'], self._str((10, 5))) + b.grid_configure(pady='.5c') + self.assertEqual(b.grid_info()['pady'], + self._str(round(pixels_conv('.5c') * self.scaling))) + + def test_grid_configure_row(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad (row|grid) value "-1": ' + 'must be a non-negative integer'): + b.grid_configure(row=-1) + b.grid_configure(row=2) + self.assertEqual(b.grid_info()['row'], self._str(2)) + + def test_grid_configure_rownspan(self): + b = tkinter.Button(self.root) + with self.assertRaisesRegex(TclError, 'bad rowspan value "0": ' + 'must be a positive integer'): + b.grid_configure(rowspan=0) + b.grid_configure(rowspan=2) + self.assertEqual(b.grid_info()['rowspan'], self._str(2)) + + def test_grid_configure_sticky(self): + f = tkinter.Frame(self.root, bg='red') + with self.assertRaisesRegex(TclError, 'bad stickyness value "glue"'): + f.grid_configure(sticky='glue') + f.grid_configure(sticky='ne') + self.assertEqual(f.grid_info()['sticky'], 'ne') + f.grid_configure(sticky='n,s,e,w') + self.assertEqual(f.grid_info()['sticky'], 'nesw') + + def test_grid_columnconfigure(self): + with self.assertRaises(TypeError): + self.root.grid_columnconfigure() + self.assertEqual(self.root.grid_columnconfigure(0), + {'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0}) + with self.assertRaisesRegex(TclError, 'bad option "-foo"'): + self.root.grid_columnconfigure(0, 'foo') + self.root.grid_columnconfigure((0, 3), weight=2) + with self.assertRaisesRegex(TclError, + 'must specify a single element on retrieval'): + self.root.grid_columnconfigure((0, 3)) + b = tkinter.Button(self.root) + b.grid_configure(column=0, row=0) + self.root.grid_columnconfigure('all', weight=3) + with self.assertRaisesRegex(TclError, 'expected integer but got "all"'): + self.root.grid_columnconfigure('all') + self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3) + self.assertEqual(self.root.grid_columnconfigure(3, 'weight'), 2) + self.assertEqual(self.root.grid_columnconfigure(265, 'weight'), 0) + self.root.grid_columnconfigure(b, weight=4) + self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 4) + + def test_grid_columnconfigure_minsize(self): + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('foo')): + self.root.grid_columnconfigure(0, minsize='foo') + self.root.grid_columnconfigure(0, minsize=10) + self.assertEqual(self.root.grid_columnconfigure(0, 'minsize'), 10) + self.assertEqual(self.root.grid_columnconfigure(0)['minsize'], 10) + + def test_grid_columnconfigure_weight(self): + with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'): + self.root.grid_columnconfigure(0, weight='bad') + with self.assertRaisesRegex(TclError, 'invalid arg "-weight": ' + 'should be non-negative'): + self.root.grid_columnconfigure(0, weight=-3) + self.root.grid_columnconfigure(0, weight=3) + self.assertEqual(self.root.grid_columnconfigure(0, 'weight'), 3) + self.assertEqual(self.root.grid_columnconfigure(0)['weight'], 3) + + def test_grid_columnconfigure_pad(self): + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('foo')): + self.root.grid_columnconfigure(0, pad='foo') + with self.assertRaisesRegex(TclError, 'invalid arg "-pad": ' + 'should be non-negative'): + self.root.grid_columnconfigure(0, pad=-3) + self.root.grid_columnconfigure(0, pad=3) + self.assertEqual(self.root.grid_columnconfigure(0, 'pad'), 3) + self.assertEqual(self.root.grid_columnconfigure(0)['pad'], 3) + + def test_grid_columnconfigure_uniform(self): + self.root.grid_columnconfigure(0, uniform='foo') + self.assertEqual(self.root.grid_columnconfigure(0, 'uniform'), 'foo') + self.assertEqual(self.root.grid_columnconfigure(0)['uniform'], 'foo') + + def test_grid_rowconfigure(self): + with self.assertRaises(TypeError): + self.root.grid_rowconfigure() + self.assertEqual(self.root.grid_rowconfigure(0), + {'minsize': 0, 'pad': 0, 'uniform': None, 'weight': 0}) + with self.assertRaisesRegex(TclError, 'bad option "-foo"'): + self.root.grid_rowconfigure(0, 'foo') + self.root.grid_rowconfigure((0, 3), weight=2) + with self.assertRaisesRegex(TclError, + 'must specify a single element on retrieval'): + self.root.grid_rowconfigure((0, 3)) + b = tkinter.Button(self.root) + b.grid_configure(column=0, row=0) + self.root.grid_rowconfigure('all', weight=3) + with self.assertRaisesRegex(TclError, 'expected integer but got "all"'): + self.root.grid_rowconfigure('all') + self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3) + self.assertEqual(self.root.grid_rowconfigure(3, 'weight'), 2) + self.assertEqual(self.root.grid_rowconfigure(265, 'weight'), 0) + self.root.grid_rowconfigure(b, weight=4) + self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 4) + + def test_grid_rowconfigure_minsize(self): + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('foo')): + self.root.grid_rowconfigure(0, minsize='foo') + self.root.grid_rowconfigure(0, minsize=10) + self.assertEqual(self.root.grid_rowconfigure(0, 'minsize'), 10) + self.assertEqual(self.root.grid_rowconfigure(0)['minsize'], 10) + + def test_grid_rowconfigure_weight(self): + with self.assertRaisesRegex(TclError, 'expected integer but got "bad"'): + self.root.grid_rowconfigure(0, weight='bad') + with self.assertRaisesRegex(TclError, 'invalid arg "-weight": ' + 'should be non-negative'): + self.root.grid_rowconfigure(0, weight=-3) + self.root.grid_rowconfigure(0, weight=3) + self.assertEqual(self.root.grid_rowconfigure(0, 'weight'), 3) + self.assertEqual(self.root.grid_rowconfigure(0)['weight'], 3) + + def test_grid_rowconfigure_pad(self): + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('foo')): + self.root.grid_rowconfigure(0, pad='foo') + with self.assertRaisesRegex(TclError, 'invalid arg "-pad": ' + 'should be non-negative'): + self.root.grid_rowconfigure(0, pad=-3) + self.root.grid_rowconfigure(0, pad=3) + self.assertEqual(self.root.grid_rowconfigure(0, 'pad'), 3) + self.assertEqual(self.root.grid_rowconfigure(0)['pad'], 3) + + def test_grid_rowconfigure_uniform(self): + self.root.grid_rowconfigure(0, uniform='foo') + self.assertEqual(self.root.grid_rowconfigure(0, 'uniform'), 'foo') + self.assertEqual(self.root.grid_rowconfigure(0)['uniform'], 'foo') + + def test_grid_forget(self): + b = tkinter.Button(self.root) + c = tkinter.Button(self.root) + b.grid_configure(row=2, column=2, rowspan=2, columnspan=2, + padx=3, pady=4, sticky='ns') + self.assertEqual(self.root.grid_content(), [b]) + b.grid_forget() + c.grid_forget() + self.assertEqual(self.root.grid_content(), []) + self.assertEqual(b.grid_info(), {}) + b.grid_configure(row=0, column=0) + info = b.grid_info() + self.assertEqual(info['row'], self._str(0)) + self.assertEqual(info['column'], self._str(0)) + self.assertEqual(info['rowspan'], self._str(1)) + self.assertEqual(info['columnspan'], self._str(1)) + self.assertEqual(info['padx'], self._str(0)) + self.assertEqual(info['pady'], self._str(0)) + self.assertEqual(info['sticky'], '') + + def test_grid_remove(self): + b = tkinter.Button(self.root) + c = tkinter.Button(self.root) + b.grid_configure(row=2, column=2, rowspan=2, columnspan=2, + padx=3, pady=4, sticky='ns') + self.assertEqual(self.root.grid_content(), [b]) + b.grid_remove() + c.grid_remove() + self.assertEqual(self.root.grid_content(), []) + self.assertEqual(b.grid_info(), {}) + b.grid_configure(row=0, column=0) + info = b.grid_info() + self.assertEqual(info['row'], self._str(0)) + self.assertEqual(info['column'], self._str(0)) + self.assertEqual(info['rowspan'], self._str(2)) + self.assertEqual(info['columnspan'], self._str(2)) + self.assertEqual(info['padx'], self._str(3)) + self.assertEqual(info['pady'], self._str(4)) + self.assertEqual(info['sticky'], 'ns') + + def test_grid_info(self): + b = tkinter.Button(self.root) + self.assertEqual(b.grid_info(), {}) + b.grid_configure(row=2, column=2, rowspan=2, columnspan=2, + padx=3, pady=4, sticky='ns') + info = b.grid_info() + self.assertIsInstance(info, dict) + self.assertEqual(info['in'], self.root) + self.assertEqual(info['row'], self._str(2)) + self.assertEqual(info['column'], self._str(2)) + self.assertEqual(info['rowspan'], self._str(2)) + self.assertEqual(info['columnspan'], self._str(2)) + self.assertEqual(info['padx'], self._str(3)) + self.assertEqual(info['pady'], self._str(4)) + self.assertEqual(info['sticky'], 'ns') + + def test_grid_anchor(self): + with self.assertRaisesRegex(TclError, 'bad anchor "x"'): + self.root.grid_anchor('x') + with self.assertRaisesRegex(TclError, 'ambiguous anchor ""'): + self.root.grid_anchor('') + with self.assertRaises(TypeError): + self.root.grid_anchor('se', 'nw') + self.root.grid_anchor('se') + self.assertEqual(self.root.tk.call('grid', 'anchor', self.root), 'se') + + def test_grid_bbox(self): + self.assertEqual(self.root.grid_bbox(), (0, 0, 0, 0)) + self.assertEqual(self.root.grid_bbox(0, 0), (0, 0, 0, 0)) + self.assertEqual(self.root.grid_bbox(0, 0, 1, 1), (0, 0, 0, 0)) + with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): + self.root.grid_bbox('x', 0) + with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): + self.root.grid_bbox(0, 'x') + with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): + self.root.grid_bbox(0, 0, 'x', 0) + with self.assertRaisesRegex(TclError, 'expected integer but got "x"'): + self.root.grid_bbox(0, 0, 0, 'x') + with self.assertRaises(TypeError): + self.root.grid_bbox(0, 0, 0, 0, 0) + t = self.root + # de-maximize + t.wm_geometry('1x1+0+0') + t.wm_geometry('') + f1 = tkinter.Frame(t, width=75, height=75, bg='red') + f2 = tkinter.Frame(t, width=90, height=90, bg='blue') + f1.grid_configure(row=0, column=0) + f2.grid_configure(row=1, column=1) + self.root.update() + self.assertEqual(t.grid_bbox(), (0, 0, 165, 165)) + self.assertEqual(t.grid_bbox(0, 0), (0, 0, 75, 75)) + self.assertEqual(t.grid_bbox(0, 0, 1, 1), (0, 0, 165, 165)) + self.assertEqual(t.grid_bbox(1, 1), (75, 75, 90, 90)) + self.assertEqual(t.grid_bbox(10, 10, 0, 0), (0, 0, 165, 165)) + self.assertEqual(t.grid_bbox(-2, -2, -1, -1), (0, 0, 0, 0)) + self.assertEqual(t.grid_bbox(10, 10, 12, 12), (165, 165, 0, 0)) + + def test_grid_location(self): + with self.assertRaises(TypeError): + self.root.grid_location() + with self.assertRaises(TypeError): + self.root.grid_location(0) + with self.assertRaises(TypeError): + self.root.grid_location(0, 0, 0) + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('x')): + self.root.grid_location('x', 'y') + with self.assertRaisesRegex(TclError, + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('y')): + self.root.grid_location('1c', 'y') + t = self.root + # de-maximize + t.wm_geometry('1x1+0+0') + t.wm_geometry('') + f = tkinter.Frame(t, width=200, height=100, + highlightthickness=0, bg='red') + self.assertEqual(f.grid_location(10, 10), (-1, -1)) + f.grid_configure() + self.root.update() + self.assertEqual(t.grid_location(-10, -10), (-1, -1)) + self.assertEqual(t.grid_location(-10, 0), (-1, 0)) + self.assertEqual(t.grid_location(-1, 0), (-1, 0)) + self.assertEqual(t.grid_location(0, -10), (0, -1)) + self.assertEqual(t.grid_location(0, -1), (0, -1)) + self.assertEqual(t.grid_location(0, 0), (0, 0)) + self.assertEqual(t.grid_location(200, 0), (0, 0)) + self.assertEqual(t.grid_location(201, 0), (1, 0)) + self.assertEqual(t.grid_location(0, 100), (0, 0)) + self.assertEqual(t.grid_location(0, 101), (0, 1)) + self.assertEqual(t.grid_location(201, 101), (1, 1)) + + def test_grid_propagate(self): + self.assertEqual(self.root.grid_propagate(), True) + with self.assertRaises(TypeError): + self.root.grid_propagate(False, False) + self.root.grid_propagate(False) + self.assertFalse(self.root.grid_propagate()) + f = tkinter.Frame(self.root, width=100, height=100, bg='red') + f.grid_configure(row=0, column=0) + self.root.update() + self.assertEqual(f.winfo_width(), 100) + self.assertEqual(f.winfo_height(), 100) + f.grid_propagate(False) + g = tkinter.Frame(self.root, width=75, height=85, bg='green') + g.grid_configure(in_=f, row=0, column=0) + self.root.update() + self.assertEqual(f.winfo_width(), 100) + self.assertEqual(f.winfo_height(), 100) + f.grid_propagate(True) + self.root.update() + self.assertEqual(f.winfo_width(), 75) + self.assertEqual(f.winfo_height(), 85) + + def test_grid_size(self): + with self.assertRaises(TypeError): + self.root.grid_size(0) + self.assertEqual(self.root.grid_size(), (0, 0)) + f = tkinter.Scale(self.root) + f.grid_configure(row=0, column=0) + self.assertEqual(self.root.grid_size(), (1, 1)) + f.grid_configure(row=4, column=5) + self.assertEqual(self.root.grid_size(), (6, 5)) + + def test_grid_content(self): + self.assertEqual(self.root.grid_content(), []) + a = tkinter.Label(self.root) + a.grid_configure(row=0, column=1) + b = tkinter.Label(self.root) + b.grid_configure(row=1, column=0) + c = tkinter.Label(self.root) + c.grid_configure(row=1, column=1) + d = tkinter.Label(self.root) + d.grid_configure(row=1, column=1) + self.assertEqual(self.root.grid_content(), [d, c, b, a]) + self.assertEqual(self.root.grid_content(row=0), [a]) + self.assertEqual(self.root.grid_content(row=1), [d, c, b]) + self.assertEqual(self.root.grid_content(column=0), [b]) + self.assertEqual(self.root.grid_content(column=1), [d, c, a]) + self.assertEqual(self.root.grid_content(row=1, column=1), [d, c]) + + def test_grid_slaves(self): + self.assertEqual(self.root.grid_slaves(), []) + a = tkinter.Label(self.root) + a.grid_configure(row=0, column=1) + b = tkinter.Label(self.root) + b.grid_configure(row=1, column=0) + c = tkinter.Label(self.root) + c.grid_configure(row=1, column=1) + d = tkinter.Label(self.root) + d.grid_configure(row=1, column=1) + self.assertEqual(self.root.grid_slaves(), [d, c, b, a]) + self.assertEqual(self.root.grid_slaves(row=0), [a]) + self.assertEqual(self.root.grid_slaves(row=1), [d, c, b]) + self.assertEqual(self.root.grid_slaves(column=0), [b]) + self.assertEqual(self.root.grid_slaves(column=1), [d, c, a]) + self.assertEqual(self.root.grid_slaves(row=1, column=1), [d, c]) + + def test_grid_short_aliases(self): + # columnconfigure, rowconfigure, size, anchor and bbox are aliases of + # the corresponding grid_* methods (Misc precedes Pack, Place and Grid + # in the method resolution order). + root = self.root + self.assertEqual(root.columnconfigure, root.grid_columnconfigure) + self.assertEqual(root.rowconfigure, root.grid_rowconfigure) + self.assertEqual(root.size, root.grid_size) + self.assertEqual(root.anchor, root.grid_anchor) + self.assertEqual(root.bbox, root.grid_bbox) + + self.assertEqual(root.size(), (0, 0)) + b = tkinter.Button(root) + b.grid_configure(column=2, row=3) + self.assertEqual(root.size(), (3, 4)) + + root.columnconfigure(0, weight=2) + self.assertEqual(root.grid_columnconfigure(0, 'weight'), 2) + root.rowconfigure(0, weight=3) + self.assertEqual(root.grid_rowconfigure(0, 'weight'), 3) + + root.anchor('se') + self.assertEqual(root.tk.call('grid', 'anchor', root), 'se') + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_tkinter/test_images.py b/Lib/test/test_tkinter/test_images.py new file mode 100644 index 00000000000..db399d66c35 --- /dev/null +++ b/Lib/test/test_tkinter/test_images.py @@ -0,0 +1,675 @@ +import collections.abc +import unittest +import tkinter +from test import support +from test.support import os_helper +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractTkTest, AbstractDefaultRootTest, requires_tk + +support.requires('gui') + + +class MiscTest(AbstractTkTest, unittest.TestCase): + + def test_image_types(self): + image_types = self.root.image_types() + self.assertIsInstance(image_types, tuple) + self.assertIn('photo', image_types) + self.assertIn('bitmap', image_types) + + def test_image_names(self): + image_names = self.root.image_names() + self.assertIsInstance(image_names, tuple) + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_image_types(self): + self.assertRaises(RuntimeError, tkinter.image_types) + root = tkinter.Tk() + image_types = tkinter.image_types() + self.assertIsInstance(image_types, tuple) + self.assertIn('photo', image_types) + self.assertIn('bitmap', image_types) + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, tkinter.image_types) + + def test_image_names(self): + self.assertRaises(RuntimeError, tkinter.image_names) + root = tkinter.Tk() + image_names = tkinter.image_names() + self.assertIsInstance(image_names, tuple) + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, tkinter.image_names) + + def test_image_create_bitmap(self): + self.assertRaises(RuntimeError, tkinter.BitmapImage) + root = tkinter.Tk() + image = tkinter.BitmapImage() + self.assertIn(image.name, tkinter.image_names()) + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, tkinter.BitmapImage) + + def test_image_create_photo(self): + self.assertRaises(RuntimeError, tkinter.PhotoImage) + root = tkinter.Tk() + image = tkinter.PhotoImage() + self.assertIn(image.name, tkinter.image_names()) + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, tkinter.PhotoImage) + + +class BaseImageTest: + def create(self): + return self.image_class('::img::test', master=self.root, + file=self.testfile) + + def test_bug_100814(self): + # gh-100814: Passing a callable option value causes AttributeError. + with self.assertRaises(tkinter.TclError): + self.image_class('::img::test', master=self.root, spam=print) + image = self.image_class('::img::test', master=self.root) + with self.assertRaises(tkinter.TclError): + image.configure(spam=print) + + def test_iterable_protocol(self): + image = self.create() + self.assertNotIsSubclass(self.image_class, collections.abc.Iterable) + self.assertNotIsSubclass(self.image_class, collections.abc.Container) + self.assertNotIsInstance(image, collections.abc.Iterable) + self.assertNotIsInstance(image, collections.abc.Container) + with self.assertRaisesRegex(TypeError, 'is not iterable'): + iter(image) + with self.assertRaisesRegex(TypeError, 'is not a container or iterable'): + image in image + + +class BitmapImageTest(BaseImageTest, AbstractTkTest, unittest.TestCase): + image_class = tkinter.BitmapImage + + @classmethod + def setUpClass(cls): + AbstractTkTest.setUpClass.__func__(cls) + cls.testfile = support.findfile('python.xbm', subdir='tkinterdata') + + def test_create_from_file(self): + image = tkinter.BitmapImage('::img::test', master=self.root, + foreground='yellow', background='blue', + file=self.testfile) + self.assertEqual(str(image), '::img::test') + self.assertEqual(image.type(), 'bitmap') + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + self.assertIn('::img::test', self.root.image_names()) + del image + support.gc_collect() # For PyPy or other GCs. + self.assertNotIn('::img::test', self.root.image_names()) + + def test_create_from_data(self): + with open(self.testfile, 'rb') as f: + data = f.read() + image = tkinter.BitmapImage('::img::test', master=self.root, + foreground='yellow', background='blue', + data=data) + self.assertEqual(str(image), '::img::test') + self.assertEqual(image.type(), 'bitmap') + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + self.assertIn('::img::test', self.root.image_names()) + del image + support.gc_collect() # For PyPy or other GCs. + self.assertNotIn('::img::test', self.root.image_names()) + + def assertEqualStrList(self, actual, expected): + self.assertIsInstance(actual, str) + self.assertEqual(self.root.splitlist(actual), expected) + + def test_configure_data(self): + image = tkinter.BitmapImage('::img::test', master=self.root) + self.assertEqual(image['data'], '-data {} {} {} {}') + with open(self.testfile, 'rb') as f: + data = f.read() + image.configure(data=data) + self.assertEqualStrList(image['data'], + ('-data', '', '', '', data.decode('ascii'))) + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + + self.assertEqual(image['maskdata'], '-maskdata {} {} {} {}') + image.configure(maskdata=data) + self.assertEqualStrList(image['maskdata'], + ('-maskdata', '', '', '', data.decode('ascii'))) + + def test_configure_file(self): + image = tkinter.BitmapImage('::img::test', master=self.root) + self.assertEqual(image['file'], '-file {} {} {} {}') + image.configure(file=self.testfile) + self.assertEqualStrList(image['file'], + ('-file', '', '', '',self.testfile)) + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + + self.assertEqual(image['maskfile'], '-maskfile {} {} {} {}') + image.configure(maskfile=self.testfile) + self.assertEqualStrList(image['maskfile'], + ('-maskfile', '', '', '', self.testfile)) + + def test_configure_background(self): + image = tkinter.BitmapImage('::img::test', master=self.root) + self.assertEqual(image['background'], '-background {} {} {} {}') + image.configure(background='blue') + self.assertEqual(image['background'], '-background {} {} {} blue') + + def test_configure_foreground(self): + image = tkinter.BitmapImage('::img::test', master=self.root) + self.assertEqual(image['foreground'], + '-foreground {} {} #000000 #000000') + image.configure(foreground='yellow') + self.assertEqual(image['foreground'], + '-foreground {} {} #000000 yellow') + + +class PhotoImageTest(BaseImageTest, AbstractTkTest, unittest.TestCase): + image_class = tkinter.PhotoImage + + @classmethod + def setUpClass(cls): + AbstractTkTest.setUpClass.__func__(cls) + cls.testfile = support.findfile('python.gif', subdir='tkinterdata') + + def colorlist(self, *args): + if tkinter.TkVersion >= 8.6 and self.wantobjects: + return args + else: + return tkinter._join(args) + + def check_create_from_file(self, ext): + testfile = support.findfile('python.' + ext, subdir='tkinterdata') + image = tkinter.PhotoImage('::img::test', master=self.root, + file=testfile) + self.assertEqual(str(image), '::img::test') + self.assertEqual(image.type(), 'photo') + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + self.assertEqual(image['data'], '') + self.assertEqual(image['file'], testfile) + self.assertIn('::img::test', self.root.image_names()) + del image + support.gc_collect() # For PyPy or other GCs. + self.assertNotIn('::img::test', self.root.image_names()) + + def check_create_from_data(self, ext): + testfile = support.findfile('python.' + ext, subdir='tkinterdata') + with open(testfile, 'rb') as f: + data = f.read() + image = tkinter.PhotoImage('::img::test', master=self.root, + data=data) + self.assertEqual(str(image), '::img::test') + self.assertEqual(image.type(), 'photo') + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + self.assertEqual(image['data'], data if self.wantobjects + else data.decode('latin1')) + self.assertEqual(image['file'], '') + self.assertIn('::img::test', self.root.image_names()) + del image + support.gc_collect() # For PyPy or other GCs. + self.assertNotIn('::img::test', self.root.image_names()) + + def test_create_from_ppm_file(self): + self.check_create_from_file('ppm') + + def test_create_from_ppm_data(self): + self.check_create_from_data('ppm') + + def test_create_from_pgm_file(self): + self.check_create_from_file('pgm') + + def test_create_from_pgm_data(self): + self.check_create_from_data('pgm') + + def test_create_from_gif_file(self): + self.check_create_from_file('gif') + + def test_create_from_gif_data(self): + self.check_create_from_data('gif') + + @requires_tk(8, 6) + def test_create_from_png_file(self): + self.check_create_from_file('png') + + @requires_tk(8, 6) + def test_create_from_png_data(self): + self.check_create_from_data('png') + + def test_configure_data(self): + image = tkinter.PhotoImage('::img::test', master=self.root) + self.assertEqual(image['data'], '') + with open(self.testfile, 'rb') as f: + data = f.read() + image.configure(data=data) + self.assertEqual(image['data'], data if self.wantobjects + else data.decode('latin1')) + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + + def test_configure_format(self): + image = tkinter.PhotoImage('::img::test', master=self.root) + self.assertEqual(image['format'], '') + image.configure(file=self.testfile, format='gif') + self.assertEqual(image['format'], ('gif',) if self.wantobjects + else 'gif') + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + + def test_configure_file(self): + image = tkinter.PhotoImage('::img::test', master=self.root) + self.assertEqual(image['file'], '') + image.configure(file=self.testfile) + self.assertEqual(image['file'], self.testfile) + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + + def test_configure_gamma(self): + image = tkinter.PhotoImage('::img::test', master=self.root) + self.assertEqual(image['gamma'], '1.0') + image.configure(gamma=2.0) + self.assertEqual(image['gamma'], '2.0') + + def test_configure_width_height(self): + image = tkinter.PhotoImage('::img::test', master=self.root) + self.assertEqual(image['width'], '0') + self.assertEqual(image['height'], '0') + image.configure(width=20) + image.configure(height=10) + self.assertEqual(image['width'], '20') + self.assertEqual(image['height'], '10') + self.assertEqual(image.cget('width'), image['width']) + self.assertEqual(image.cget('height'), image['height']) + self.assertRaises(TypeError, image.cget) + self.assertRaises(TypeError, image.cget, 'width', 'height') + self.assertEqual(image.config, image.configure) + self.assertEqual(image.width(), 20) + self.assertEqual(image.height(), 10) + + def test_configure_palette(self): + image = tkinter.PhotoImage('::img::test', master=self.root) + self.assertEqual(image['palette'], '') + image.configure(palette=256) + self.assertEqual(image['palette'], '256') + image.configure(palette='3/4/2') + self.assertEqual(image['palette'], '3/4/2') + + def test_blank(self): + image = self.create() + image.blank() + self.assertEqual(image.width(), 16) + self.assertEqual(image.height(), 16) + self.assertEqual(image.get(4, 6), self.colorlist(0, 0, 0)) + + def test_copy(self): + image = self.create() + image2 = image.copy() + self.assertEqual(image2.width(), 16) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(4, 6), image.get(4, 6)) + + image2 = image.copy(from_coords=(2, 3, 14, 11)) + self.assertEqual(image2.width(), 12) + self.assertEqual(image2.height(), 8) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(11, 7), image.get(13, 10)) + self.assertEqual(image2.get(2, 4), image.get(2+2, 4+3)) + + image2 = image.copy(from_coords=(2, 3, 14, 11), zoom=2) + self.assertEqual(image2.width(), 24) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(23, 15), image.get(13, 10)) + self.assertEqual(image2.get(2*2, 4*2), image.get(2+2, 4+3)) + self.assertEqual(image2.get(2*2+1, 4*2+1), image.get(6+2, 2+3)) + + image2 = image.copy(from_coords=(2, 3, 14, 11), subsample=2) + self.assertEqual(image2.width(), 6) + self.assertEqual(image2.height(), 4) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(5, 3), image.get(12, 9)) + self.assertEqual(image2.get(3, 2), image.get(3*2+2, 2*2+3)) + + image2 = image.copy(from_coords=(2, 3, 14, 11), subsample=2, zoom=3) + self.assertEqual(image2.width(), 18) + self.assertEqual(image2.height(), 12) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(17, 11), image.get(12, 9)) + self.assertEqual(image2.get(1*3, 2*3), image.get(1*2+2, 2*2+3)) + self.assertEqual(image2.get(1*3+2, 2*3+2), image.get(1*2+2, 2*2+3)) + + def test_subsample(self): + image = self.create() + image2 = image.subsample(2, 3) + self.assertEqual(image2.width(), 8) + self.assertEqual(image2.height(), 6) + self.assertEqual(image2.get(2, 2), image.get(4, 6)) + + image2 = image.subsample(2) + self.assertEqual(image2.width(), 8) + self.assertEqual(image2.height(), 8) + self.assertEqual(image2.get(2, 3), image.get(4, 6)) + + image2 = image.subsample(2, from_coords=(2, 3, 14, 11)) + self.assertEqual(image2.width(), 6) + self.assertEqual(image2.height(), 4) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(5, 3), image.get(12, 9)) + self.assertEqual(image2.get(1, 2), image.get(1*2+2, 2*2+3)) + + def test_zoom(self): + image = self.create() + image2 = image.zoom(2, 3) + self.assertEqual(image2.width(), 32) + self.assertEqual(image2.height(), 48) + self.assertEqual(image2.get(8, 18), image.get(4, 6)) + self.assertEqual(image2.get(9, 20), image.get(4, 6)) + + image2 = image.zoom(2) + self.assertEqual(image2.width(), 32) + self.assertEqual(image2.height(), 32) + self.assertEqual(image2.get(8, 12), image.get(4, 6)) + self.assertEqual(image2.get(9, 13), image.get(4, 6)) + + image2 = image.zoom(2, from_coords=(2, 3, 14, 11)) + self.assertEqual(image2.width(), 24) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(23, 15), image.get(13, 10)) + self.assertEqual(image2.get(2*2, 4*2), image.get(2+2, 4+3)) + self.assertEqual(image2.get(2*2+1, 4*2+1), image.get(6+2, 2+3)) + + def test_copy_replace(self): + image = self.create() + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image) + self.assertEqual(image2.width(), 16) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(4, 6), image.get(4, 6)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image, from_coords=(2, 3, 14, 11)) + self.assertEqual(image2.width(), 12) + self.assertEqual(image2.height(), 8) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(11, 7), image.get(13, 10)) + self.assertEqual(image2.get(2, 4), image.get(2+2, 4+3)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image) + image2.copy_replace(image, from_coords=(2, 3, 14, 11), shrink=True) + self.assertEqual(image2.width(), 12) + self.assertEqual(image2.height(), 8) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(11, 7), image.get(13, 10)) + self.assertEqual(image2.get(2, 4), image.get(2+2, 4+3)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image, from_coords=(2, 3, 14, 11), to=(3, 6)) + self.assertEqual(image2.width(), 15) + self.assertEqual(image2.height(), 14) + self.assertEqual(image2.get(0+3, 0+6), image.get(2, 3)) + self.assertEqual(image2.get(11+3, 7+6), image.get(13, 10)) + self.assertEqual(image2.get(2+3, 4+6), image.get(2+2, 4+3)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image, from_coords=(2, 3, 14, 11), to=(0, 0, 100, 50)) + self.assertEqual(image2.width(), 100) + self.assertEqual(image2.height(), 50) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(11, 7), image.get(13, 10)) + self.assertEqual(image2.get(2, 4), image.get(2+2, 4+3)) + self.assertEqual(image2.get(2+12, 4+8), image.get(2+2, 4+3)) + self.assertEqual(image2.get(2+12*2, 4), image.get(2+2, 4+3)) + self.assertEqual(image2.get(2, 4+8*3), image.get(2+2, 4+3)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image, from_coords=(2, 3, 14, 11), zoom=2) + self.assertEqual(image2.width(), 24) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(23, 15), image.get(13, 10)) + self.assertEqual(image2.get(2*2, 4*2), image.get(2+2, 4+3)) + self.assertEqual(image2.get(2*2+1, 4*2+1), image.get(6+2, 2+3)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image, from_coords=(2, 3, 14, 11), subsample=2) + self.assertEqual(image2.width(), 6) + self.assertEqual(image2.height(), 4) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(5, 3), image.get(12, 9)) + self.assertEqual(image2.get(1, 2), image.get(1*2+2, 2*2+3)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.copy_replace(image, from_coords=(2, 3, 14, 11), subsample=2, zoom=3) + self.assertEqual(image2.width(), 18) + self.assertEqual(image2.height(), 12) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(17, 11), image.get(12, 9)) + self.assertEqual(image2.get(3*3, 2*3), image.get(3*2+2, 2*2+3)) + self.assertEqual(image2.get(3*3+2, 2*3+2), image.get(3*2+2, 2*2+3)) + self.assertEqual(image2.get(1*3, 2*3), image.get(1*2+2, 2*2+3)) + self.assertEqual(image2.get(1*3+2, 2*3+2), image.get(1*2+2, 2*2+3)) + + def checkImgTrans(self, image, expected): + actual = {(x, y) + for x in range(image.width()) + for y in range(image.height()) + if image.transparency_get(x, y)} + self.assertEqual(actual, expected) + + def test_copy_replace_compositingrule(self): + image1 = tkinter.PhotoImage(master=self.root, width=2, height=2) + image1.blank() + image1.put('black', to=(0, 0, 2, 2)) + image1.transparency_set(0, 0, True) + + # default compositingrule + image2 = tkinter.PhotoImage(master=self.root, width=3, height=3) + image2.blank() + image2.put('white', to=(0, 0, 2, 2)) + image2.copy_replace(image1, to=(1, 1)) + self.checkImgTrans(image2, {(0, 2), (2, 0)}) + + image3 = tkinter.PhotoImage(master=self.root, width=3, height=3) + image3.blank() + image3.put('white', to=(0, 0, 2, 2)) + image3.copy_replace(image1, to=(1, 1), compositingrule='overlay') + self.checkImgTrans(image3, {(0, 2), (2, 0)}) + + image4 = tkinter.PhotoImage(master=self.root, width=3, height=3) + image4.blank() + image4.put('white', to=(0, 0, 2, 2)) + image4.copy_replace(image1, to=(1, 1), compositingrule='set') + self.checkImgTrans(image4, {(0, 2), (1, 1), (2, 0)}) + + def test_put(self): + image = self.create() + image.put('{red green} {blue yellow}', to=(4, 6)) + self.assertEqual(image.get(4, 6), self.colorlist(255, 0, 0)) + self.assertEqual(image.get(5, 6), + self.colorlist(0, 128 if tkinter.TkVersion >= 8.6 + else 255, 0)) + self.assertEqual(image.get(4, 7), self.colorlist(0, 0, 255)) + self.assertEqual(image.get(5, 7), self.colorlist(255, 255, 0)) + + image.put((('#f00', '#00ff00'), ('#000000fff', '#ffffffff0000'))) + self.assertEqual(image.get(0, 0), self.colorlist(255, 0, 0)) + self.assertEqual(image.get(1, 0), self.colorlist(0, 255, 0)) + self.assertEqual(image.get(0, 1), self.colorlist(0, 0, 255)) + self.assertEqual(image.get(1, 1), self.colorlist(255, 255, 0)) + + def test_get(self): + image = self.create() + self.assertEqual(image.get(4, 6), self.colorlist(62, 116, 162)) + self.assertEqual(image.get(0, 0), self.colorlist(0, 0, 0)) + self.assertEqual(image.get(15, 15), self.colorlist(0, 0, 0)) + self.assertRaises(tkinter.TclError, image.get, -1, 0) + self.assertRaises(tkinter.TclError, image.get, 0, -1) + self.assertRaises(tkinter.TclError, image.get, 16, 15) + self.assertRaises(tkinter.TclError, image.get, 15, 16) + + def test_read(self): + # Due to the Tk bug https://core.tcl-lang.org/tk/tktview/1576528 + # the -from option does not work correctly for GIF and PNG files. + # Use the PPM file for this test. + testfile = support.findfile('python.ppm', subdir='tkinterdata') + image = tkinter.PhotoImage(master=self.root, file=testfile) + + image2 = tkinter.PhotoImage(master=self.root) + image2.read(testfile) + self.assertEqual(image2.type(), 'photo') + self.assertEqual(image2.width(), 16) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(0, 0), image.get(0, 0)) + self.assertEqual(image2.get(4, 6), image.get(4, 6)) + + self.assertRaises(tkinter.TclError, image2.read, self.testfile, 'ppm') + + image2 = tkinter.PhotoImage(master=self.root) + image2.read(testfile, from_coords=(2, 3, 14, 11)) + self.assertEqual(image2.width(), 12) + self.assertEqual(image2.height(), 8) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(11, 7), image.get(13, 10)) + self.assertEqual(image2.get(2, 4), image.get(2+2, 4+3)) + + image2 = tkinter.PhotoImage(master=self.root, file=testfile) + self.assertEqual(image2.width(), 16) + self.assertEqual(image2.height(), 16) + image2.read(testfile, from_coords=(2, 3, 14, 11), shrink=True) + self.assertEqual(image2.width(), 12) + self.assertEqual(image2.height(), 8) + self.assertEqual(image2.get(0, 0), image.get(2, 3)) + self.assertEqual(image2.get(11, 7), image.get(13, 10)) + self.assertEqual(image2.get(2, 4), image.get(2+2, 4+3)) + + image2 = tkinter.PhotoImage(master=self.root) + image2.read(testfile, from_coords=(2, 3, 14, 11), to=(3, 6)) + self.assertEqual(image2.type(), 'photo') + self.assertEqual(image2.width(), 15) + self.assertEqual(image2.height(), 14) + self.assertEqual(image2.get(0+3, 0+6), image.get(2, 3)) + self.assertEqual(image2.get(11+3, 7+6), image.get(13, 10)) + self.assertEqual(image2.get(2+3, 4+6), image.get(2+2, 4+3)) + + def test_write(self): + filename = os_helper.TESTFN + import locale + if locale.getlocale()[0] is None: + # Tcl uses Latin1 in the C locale + filename = os_helper.TESTFN_ASCII + image = self.create() + self.addCleanup(os_helper.unlink, filename) + + image.write(filename) + image2 = tkinter.PhotoImage('::img::test2', master=self.root, + format='ppm', file=filename) + self.assertEqual(str(image2), '::img::test2') + self.assertEqual(image2.type(), 'photo') + self.assertEqual(image2.width(), 16) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(0, 0), image.get(0, 0)) + self.assertEqual(image2.get(4, 6), image.get(4, 6)) + + image.write(filename, format='gif', from_coords=(4, 6, 6, 9)) + image3 = tkinter.PhotoImage('::img::test3', master=self.root, + format='gif', file=filename) + self.assertEqual(str(image3), '::img::test3') + self.assertEqual(image3.type(), 'photo') + self.assertEqual(image3.width(), 2) + self.assertEqual(image3.height(), 3) + self.assertEqual(image3.get(0, 0), image.get(4, 6)) + self.assertEqual(image3.get(1, 2), image.get(5, 8)) + + image.write(filename, background='#ff0000') + image4 = tkinter.PhotoImage('::img::test4', master=self.root, + format='ppm', file=filename) + self.assertEqual(image4.get(0, 0), (255, 0, 0) if self.wantobjects else '255 0 0') + self.assertEqual(image4.get(4, 6), image.get(4, 6)) + + image.write(filename, grayscale=True) + image5 = tkinter.PhotoImage('::img::test5', master=self.root, + format='ppm', file=filename) + c = image5.get(4, 6) + if not self.wantobjects: + c = c.split() + self.assertTrue(c[0] == c[1] == c[2], c) + + def test_data(self): + image = self.create() + + data = image.data() + self.assertIsInstance(data, tuple) + for row in data: + self.assertIsInstance(row, str) + c = image.get(4, 6) + if not self.wantobjects: + c = tuple(map(int, c.split())) + self.assertEqual(data[6].split()[4], '#%02x%02x%02x' % c) + + data = image.data('ppm') + image2 = tkinter.PhotoImage('::img::test2', master=self.root, + format='ppm', data=data) + self.assertEqual(str(image2), '::img::test2') + self.assertEqual(image2.type(), 'photo') + self.assertEqual(image2.width(), 16) + self.assertEqual(image2.height(), 16) + self.assertEqual(image2.get(0, 0), image.get(0, 0)) + self.assertEqual(image2.get(4, 6), image.get(4, 6)) + + data = image.data(format='gif', from_coords=(4, 6, 6, 9)) + image3 = tkinter.PhotoImage('::img::test3', master=self.root, + format='gif', data=data) + self.assertEqual(str(image3), '::img::test3') + self.assertEqual(image3.type(), 'photo') + self.assertEqual(image3.width(), 2) + self.assertEqual(image3.height(), 3) + self.assertEqual(image3.get(0, 0), image.get(4, 6)) + self.assertEqual(image3.get(1, 2), image.get(5, 8)) + + data = image.data('ppm', background='#ff0000') + image4 = tkinter.PhotoImage('::img::test4', master=self.root, + format='ppm', data=data) + self.assertEqual(image4.get(0, 0), (255, 0, 0) if self.wantobjects else '255 0 0') + self.assertEqual(image4.get(4, 6), image.get(4, 6)) + + data = image.data('ppm', grayscale=True) + image5 = tkinter.PhotoImage('::img::test5', master=self.root, + format='ppm', data=data) + c = image5.get(4, 6) + if not self.wantobjects: + c = c.split() + self.assertTrue(c[0] == c[1] == c[2], c) + + + def test_transparency(self): + image = self.create() + self.assertIs(image.transparency_get(0, 0), True) + self.assertIs(image.transparency_get(4, 6), False) + image.transparency_set(4, 6, True) + self.assertIs(image.transparency_get(4, 6), True) + image.transparency_set(4, 6, False) + self.assertIs(image.transparency_get(4, 6), False) + self.assertRaises(tkinter.TclError, image.transparency_get, -1, 0) + self.assertRaises(tkinter.TclError, image.transparency_get, 16, 0) + self.assertRaises(tkinter.TclError, image.transparency_set, -1, 0, True) + self.assertRaises(tkinter.TclError, image.transparency_set, 16, 0, True) + self.assertRaises(TypeError, image.transparency_get, 0) + self.assertRaises(TypeError, image.transparency_get, 0, 0, 0) + self.assertRaises(TypeError, image.transparency_set, 0, 0) + self.assertRaises(TypeError, image.transparency_set, 0, 0, True, 0) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_loadtk.py b/Lib/test/test_tkinter/test_loadtk.py new file mode 100644 index 00000000000..7cff654621e --- /dev/null +++ b/Lib/test/test_tkinter/test_loadtk.py @@ -0,0 +1,47 @@ +import os +import sys +import unittest +import test.support as test_support +from test.support import os_helper +from test.test_tkinter.support import setUpModule # noqa: F401 +from tkinter import Tcl, TclError + +test_support.requires('gui') + +class TkLoadTest(unittest.TestCase): + + @unittest.skipIf('DISPLAY' not in os.environ, 'No $DISPLAY set.') + def testLoadTk(self): + tcl = Tcl() + self.assertRaises(TclError,tcl.winfo_geometry) + tcl.loadtk() + self.assertEqual('1x1+0+0', tcl.winfo_geometry()) + tcl.destroy() + + def testLoadTkFailure(self): + old_display = None + if sys.platform.startswith(('win', 'darwin', 'cygwin')): + # no failure possible on windows? + + # XXX Maybe on tk older than 8.4.13 it would be possible, + # see tkinter.h. + return + with os_helper.EnvironmentVarGuard() as env: + if 'DISPLAY' in os.environ: + del env['DISPLAY'] + # on some platforms, deleting environment variables + # doesn't actually carry through to the process level + # because they don't support unsetenv + # If that's the case, abort. + with os.popen('echo $DISPLAY') as pipe: + display = pipe.read().strip() + if display: + return + + tcl = Tcl() + self.assertRaises(TclError, tcl.winfo_geometry) + self.assertRaises(TclError, tcl.loadtk) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_messagebox.py b/Lib/test/test_tkinter/test_messagebox.py new file mode 100644 index 00000000000..f29f0c7ba59 --- /dev/null +++ b/Lib/test/test_tkinter/test_messagebox.py @@ -0,0 +1,37 @@ +import unittest +import tkinter +from test.support import requires, swap_attr +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractDefaultRootTest +from tkinter.commondialog import Dialog +from tkinter.messagebox import showinfo + +requires('gui') + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_showinfo(self): + def test_callback(dialog, master): + nonlocal ismapped + master.update() + ismapped = master.winfo_ismapped() + raise ZeroDivisionError + + with swap_attr(Dialog, '_test_callback', test_callback): + ismapped = None + self.assertRaises(ZeroDivisionError, showinfo, "Spam", "Egg Information") + self.assertEqual(ismapped, False) + + root = tkinter.Tk() + ismapped = None + self.assertRaises(ZeroDivisionError, showinfo, "Spam", "Egg Information") + self.assertEqual(ismapped, True) + root.destroy() + + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, showinfo, "Spam", "Egg Information") + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_misc.py b/Lib/test/test_tkinter/test_misc.py new file mode 100644 index 00000000000..ba5225c3a9b --- /dev/null +++ b/Lib/test/test_tkinter/test_misc.py @@ -0,0 +1,1996 @@ +import collections.abc +import functools +import os +import platform +import signal +import sys +import textwrap +import unittest +import weakref +import tkinter +from tkinter import TclError +import enum +from test import support +from test.support import os_helper +from test.support.isolation import runInSubprocess +from test.support.script_helper import assert_python_ok +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import (AbstractTkTest, AbstractDefaultRootTest, + requires_tk, get_tk_patchlevel, + tcl_version) + +support.requires('gui') + +class MiscTest(AbstractTkTest, unittest.TestCase): + + def test_all(self): + self.assertIn("Widget", tkinter.__all__) + # Check that variables from tkinter.constants are also in tkinter.__all__ + self.assertIn("CASCADE", tkinter.__all__) + self.assertIsNotNone(tkinter.CASCADE) + # Check that sys, re, and constants are not in tkinter.__all__ + self.assertNotIn("re", tkinter.__all__) + self.assertNotIn("sys", tkinter.__all__) + self.assertNotIn("constants", tkinter.__all__) + # Check that an underscored functions is not in tkinter.__all__ + self.assertNotIn("_tkerror", tkinter.__all__) + # Check that wantobjects is not in tkinter.__all__ + self.assertNotIn("wantobjects", tkinter.__all__) + + def test_repr(self): + t = tkinter.Toplevel(self.root, name='top') + f = tkinter.Frame(t, name='child') + self.assertEqual(repr(f), '') + + def test_generated_names(self): + class Button2(tkinter.Button): + pass + + t = tkinter.Toplevel(self.root) + f = tkinter.Frame(t) + f2 = tkinter.Frame(t) + self.assertNotEqual(str(f), str(f2)) + b = tkinter.Button(f2) + b2 = Button2(f2) + for name in str(b).split('.') + str(b2).split('.'): + self.assertFalse(name.isidentifier(), msg=repr(name)) + b3 = tkinter.Button(f2) + b4 = Button2(f2) + self.assertEqual(len({str(b), str(b2), str(b3), str(b4)}), 4) + + def test_dealloc_in_wrong_thread(self): + # gh-83274: deallocating the interpreter in the wrong thread must not + # crash. + script = textwrap.dedent(""" + import threading + import tkinter + root = tkinter.Tk() + root.destroy() + # Let another thread drop the last reference. + ready = threading.Event() + t = threading.Thread(target=lambda obj: ready.wait(), args=(root,)) + t.start() + del root + ready.set() + t.join() + print('ok') + """) + rc, out, err = assert_python_ok('-c', script) + self.assertEqual(out.strip(), b'ok') + if not support.Py_GIL_DISABLED: + # On the free-threaded build the interpreter may instead be + # deallocated in its own thread (deferred reference counting), so + # the warning is not necessarily emitted. The crucial guarantee -- + # no crash -- is already checked by assert_python_ok() above. + self.assertIn(b'RuntimeWarning', err) + self.assertIn(b'gh-83274', err) + + @requires_tk(8, 6, 6) + def test_tk_busy(self): + root = self.root + f = tkinter.Frame(root, name='myframe') + f2 = tkinter.Frame(root) + f.pack() + f2.pack() + b = tkinter.Button(f) + b.pack() + f.tk_busy_hold() + with self.assertRaisesRegex(TclError, 'unknown option "-spam"'): + f.tk_busy_configure(spam='eggs') + with self.assertRaisesRegex(TclError, 'unknown option "-spam"'): + f.tk_busy_cget('spam') + with self.assertRaisesRegex(TclError, 'unknown option "-spam"'): + f.tk_busy_configure('spam') + self.assertIsInstance(f.tk_busy_configure(), dict) + + self.assertTrue(f.tk_busy_status()) + self.assertFalse(root.tk_busy_status()) + self.assertFalse(f2.tk_busy_status()) + self.assertFalse(b.tk_busy_status()) + self.assertIn(f, f.tk_busy_current()) + self.assertIn(f, f.tk_busy_current('*.m?f*me')) + self.assertNotIn(f, f.tk_busy_current('*spam')) + + f.tk_busy_forget() + self.assertFalse(f.tk_busy_status()) + self.assertFalse(f.tk_busy_current()) + errmsg = r"can(no|')t find busy window.*" + with self.assertRaisesRegex(TclError, errmsg): + f.tk_busy_configure() + with self.assertRaisesRegex(TclError, errmsg): + f.tk_busy_forget() + + @requires_tk(8, 6, 6) + def test_tk_busy_with_cursor(self): + root = self.root + if root._windowingsystem == 'aqua': + self.skipTest('the cursor option is not supported on OSX/Aqua') + f = tkinter.Frame(root, name='myframe') + f.pack() + f.tk_busy_hold(cursor='gumby') + + self.assertEqual(f.tk_busy_cget('cursor'), 'gumby') + f.tk_busy_configure(cursor='heart') + self.assertEqual(f.tk_busy_cget('cursor'), 'heart') + self.assertEqual(f.tk_busy_configure()['cursor'][4], 'heart') + self.assertEqual(f.tk_busy_configure('cursor')[4], 'heart') + + f.tk_busy_forget() + errmsg = r"can(no|')t find busy window.*" + with self.assertRaisesRegex(TclError, errmsg): + f.tk_busy_cget('cursor') + + def test_tk_setPalette(self): + root = self.root + root.tk_setPalette('black') + self.assertEqual(root['background'], 'black') + root.tk_setPalette('white') + self.assertEqual(root['background'], 'white') + self.assertRaisesRegex(tkinter.TclError, + '^unknown color name "spam"$', + root.tk_setPalette, 'spam') + + root.tk_setPalette(background='black') + self.assertEqual(root['background'], 'black') + root.tk_setPalette(background='blue', highlightColor='yellow') + self.assertEqual(root['background'], 'blue') + self.assertEqual(root['highlightcolor'], 'yellow') + root.tk_setPalette(background='yellow', highlightColor='blue') + self.assertEqual(root['background'], 'yellow') + self.assertEqual(root['highlightcolor'], 'blue') + self.assertRaisesRegex(tkinter.TclError, + '^unknown color name "spam"$', + root.tk_setPalette, background='spam') + self.assertRaisesRegex(tkinter.TclError, + '^must specify a background color$', + root.tk_setPalette, spam='white') + self.assertRaisesRegex(tkinter.TclError, + '^must specify a background color$', + root.tk_setPalette, highlightColor='blue') + + def test_after(self): + root = self.root + + def callback(start=0, step=1, *, end=0): + nonlocal count + count = start + step + end + + # Without function, sleeps for ms. + self.assertIsNone(root.after(1)) + + # Set up with callback with no args. + count = 0 + timer1 = root.after(0, callback) + self.assertIn(timer1, root.tk.call('after', 'info')) + (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) + root.update() # Process all pending events. + self.assertEqual(count, 1) + with self.assertRaises(tkinter.TclError): + root.tk.call(script) + + # Set up with callback with args. + count = 0 + timer1 = root.after(0, callback, 42, 11) + root.update() # Process all pending events. + self.assertEqual(count, 53) + + # Cancel before called. + timer1 = root.after(1000, callback) + self.assertIn(timer1, root.tk.call('after', 'info')) + (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) + root.after_cancel(timer1) # Cancel this event. + self.assertEqual(count, 53) + with self.assertRaises(tkinter.TclError): + root.tk.call(script) + + # Call with a callable class + count = 0 + timer1 = root.after(0, functools.partial(callback, 42, 11)) + root.update() # Process all pending events. + self.assertEqual(count, 53) + + # Set up with callback with keyword args. + count = 0 + timer1 = root.after(0, callback, 42, step=11, end=1) + root.update() # Process all pending events. + self.assertEqual(count, 54) + + def test_after_idle(self): + root = self.root + + def callback(start=0, step=1, *, end=0): + nonlocal count + count = start + step + end + + # Set up with callback with no args. + count = 0 + idle1 = root.after_idle(callback) + self.assertIn(idle1, root.tk.call('after', 'info')) + (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) + root.update_idletasks() # Process all pending events. + self.assertEqual(count, 1) + with self.assertRaises(tkinter.TclError): + root.tk.call(script) + + # Set up with callback with args. + count = 0 + idle1 = root.after_idle(callback, 42, 11) + root.update_idletasks() # Process all pending events. + self.assertEqual(count, 53) + + # Cancel before called. + idle1 = root.after_idle(callback) + self.assertIn(idle1, root.tk.call('after', 'info')) + (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) + root.after_cancel(idle1) # Cancel this event. + self.assertEqual(count, 53) + with self.assertRaises(tkinter.TclError): + root.tk.call(script) + + # Set up with callback with keyword args. + count = 0 + idle1 = root.after_idle(callback, 42, step=11, end=1) + root.update() # Process all pending events. + self.assertEqual(count, 54) + + def test_after_cancel(self): + root = self.root + + def callback(): + nonlocal count + count += 1 + + timer1 = root.after(5000, callback) + idle1 = root.after_idle(callback) + + # No value for id raises a ValueError. + with self.assertRaises(ValueError): + root.after_cancel(None) + + # Cancel timer event. + count = 0 + (script, _) = root.tk.splitlist(root.tk.call('after', 'info', timer1)) + root.tk.call(script) + self.assertEqual(count, 1) + root.after_cancel(timer1) + with self.assertRaises(tkinter.TclError): + root.tk.call(script) + self.assertEqual(count, 1) + with self.assertRaises(tkinter.TclError): + root.tk.call('after', 'info', timer1) + + # Cancel same event - nothing happens. + root.after_cancel(timer1) + + # Cancel idle event. + count = 0 + (script, _) = root.tk.splitlist(root.tk.call('after', 'info', idle1)) + root.tk.call(script) + self.assertEqual(count, 1) + root.after_cancel(idle1) + with self.assertRaises(tkinter.TclError): + root.tk.call(script) + self.assertEqual(count, 1) + with self.assertRaises(tkinter.TclError): + root.tk.call('after', 'info', idle1) + + def test_after_info(self): + root = self.root + + # No events. + self.assertEqual(root.after_info(), ()) + + # Add timer. + timer = root.after(1, lambda: 'break') + + # With no parameter, it returns a tuple of the event handler ids. + self.assertEqual(root.after_info(), (timer, )) + root.after_cancel(timer) + + timer1 = root.after(5000, lambda: 'break') + timer2 = root.after(5000, lambda: 'break') + idle1 = root.after_idle(lambda: 'break') + # Only contains new events and not 'timer'. + self.assertEqual(root.after_info(), (idle1, timer2, timer1)) + + # With a parameter returns a tuple of (script, type). + timer1_info = root.after_info(timer1) + self.assertEqual(len(timer1_info), 2) + self.assertEqual(timer1_info[1], 'timer') + idle1_info = root.after_info(idle1) + self.assertEqual(len(idle1_info), 2) + self.assertEqual(idle1_info[1], 'idle') + + root.after_cancel(timer1) + with self.assertRaises(tkinter.TclError): + root.after_info(timer1) + root.after_cancel(timer2) + with self.assertRaises(tkinter.TclError): + root.after_info(timer2) + root.after_cancel(idle1) + with self.assertRaises(tkinter.TclError): + root.after_info(idle1) + + # No events. + self.assertEqual(root.after_info(), ()) + + def test_clipboard(self): + root = self.root + root.clipboard_clear() + root.clipboard_append('Ùñî') + self.assertEqual(root.clipboard_get(), 'Ùñî') + root.clipboard_append('çōđě') + self.assertEqual(root.clipboard_get(), 'Ùñîçōđě') + root.clipboard_clear() + with self.assertRaises(tkinter.TclError): + root.clipboard_get() + + def test_clipboard_astral(self): + root = self.root + root.clipboard_clear() + root.clipboard_append('𝔘𝔫𝔦') + self.assertEqual(root.clipboard_get(), '𝔘𝔫𝔦') + root.clipboard_append('𝔠𝔬𝔡𝔢') + self.assertEqual(root.clipboard_get(), '𝔘𝔫𝔦𝔠𝔬𝔡𝔢') + root.clipboard_clear() + with self.assertRaises(tkinter.TclError): + root.clipboard_get() + + def test_getint(self): + self.assertEqual(self.root.getint('42'), 42) + self.assertEqual(self.root.getint(42), 42) + self.assertEqual(self.root.getint('-5'), -5) + self.assertRaises(ValueError, self.root.getint, 'spam') + + def test_getdouble(self): + self.assertEqual(self.root.getdouble('3.5'), 3.5) + self.assertEqual(self.root.getdouble(3), 3.0) + self.assertRaises(ValueError, self.root.getdouble, 'spam') + + def test_getvar(self): + self.root.setvar('test_var', 'hello') + self.assertEqual(self.root.getvar('test_var'), 'hello') + + def test_register(self): + result = [] + def callback(): + result.append(1) + return 'spam' + name = self.root.register(callback) + self.assertIsInstance(name, str) + self.assertEqual(self.root.tk.call(name), 'spam') + self.assertEqual(result, [1]) + self.root.deletecommand(name) + self.assertRaises(TclError, self.root.tk.call, name) + + def test_createcommand_no_leak(self): + # gh-80937: dropping the interpreter must release a command's callback, + # even without an explicit deletecommand(). + interp = tkinter.Tcl() + callback = lambda: '' + ref = weakref.ref(callback) + interp.tk.createcommand('cb', callback) + del callback, interp + support.gc_collect() + self.assertIsNone(ref()) + + def test_option(self): + self.addCleanup(self.root.option_clear) + self.root.option_add('*Button.background', 'red') + b = tkinter.Button(self.root) + self.assertEqual(b.option_get('background', 'Background'), 'red') + self.assertEqual(b.option_get('foreground', 'Foreground'), '') + self.root.option_clear() + self.assertEqual(b.option_get('background', 'Background'), '') + + def test_option_readfile(self): + self.addCleanup(self.root.option_clear) + self.addCleanup(os_helper.unlink, os_helper.TESTFN) + with open(os_helper.TESTFN, 'w') as f: + f.write('*Button.background: red\n') + self.root.option_readfile(os_helper.TESTFN) + b = tkinter.Button(self.root) + self.assertEqual(b.option_get('background', 'Background'), 'red') + self.assertRaises(TclError, self.root.option_readfile, + os_helper.TESTFN + '.nonexistent') + self.assertRaises(TypeError, self.root.option_readfile) + self.assertRaises(TypeError, self.root.option_readfile, 'a', 'b', 'c') + + def test_nametowidget(self): + b = tkinter.Button(self.root, name='btn') + self.assertIs(self.root.nametowidget('btn'), b) + self.assertIs(self.root.nametowidget(str(b)), b) + self.assertRaises(KeyError, self.root.nametowidget, '.nonexistent') + + def test_nametowidget_menu_clone(self): + # A menu used as a menubar or cascade is cloned by Tk under an + # auto-generated name (each path component is the original name + # prefixed with one or more '#' clone markers). nametowidget() + # maps such a name back to the original widget (gh-38464). + menubar = tkinter.Menu(self.root) + filemenu = tkinter.Menu(menubar, tearoff=0) + menubar.add_cascade(label='File', menu=filemenu) + submenu = tkinter.Menu(filemenu, tearoff=0) + filemenu.add_cascade(label='More', menu=submenu) + self.root['menu'] = menubar + self.root.update_idletasks() + + originals = {menubar, filemenu, submenu} + clones = [] + def collect(parent): + for name in self.root.tk.splitlist( + self.root.tk.call('winfo', 'children', parent)): + clones.append(name) + collect(name) + collect('.') + # Every menu (originals and clones) resolves to an original widget. + self.assertTrue(any('#' in name for name in clones)) + for name in clones: + self.assertIn(self.root.nametowidget(name), originals) + + def test_focus_methods(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + f.focus_force() + self.root.update() + # The window manager can take the focus away, and then focus_get() + # and focus_displayof() return None. + if self.root.focus_displayof() is not None: + self.assertIs(self.root.focus_get(), f) + self.assertIs(self.root.focus_displayof(), f) + self.assertIs(f.focus_lastfor(), f) + b = tkinter.Button(f) + b.pack() + self.root.update() + b.focus_set() + self.root.update() + if self.root.focus_displayof() is not None: + self.assertIs(self.root.focus_get(), b) + self.assertIs(f.focus_lastfor(), b) + + def test_focus_methods_unresolvable(self): + # The focus may be on a widget that tkinter did not create and so + # cannot map to an instance (e.g. a torn-off menu). The focus + # methods return None instead of raising KeyError (gh-88758). + menu = tkinter.Menu(self.root, tearoff=1) + menu.add_command(label='Hello') + tearoff = self.root.tk.call('tk::TearOffMenu', str(menu), 0, 0) + self.addCleanup(self.root.tk.call, 'destroy', tearoff) + self.root.update() + self.assertRaises(KeyError, self.root.nametowidget, tearoff) + + self.root.tk.call('focus', '-force', tearoff) + self.root.update() + self.assertIsNone(self.root.focus_get()) + self.assertIsNone(self.root.focus_displayof()) + + def test_grab(self): + f = tkinter.Frame(self.root) + f.pack() + self.root.wait_visibility() + self.assertIsNone(self.root.grab_current()) + self.assertIsNone(f.grab_status()) + f.grab_set() + self.assertEqual(f.grab_status(), 'local') + self.assertIs(self.root.grab_current(), f) + f.grab_release() + self.assertIsNone(f.grab_status()) + self.assertIsNone(self.root.grab_current()) + + def test_selection_own(self): + self.root.selection_own() + self.assertIs(self.root.selection_own_get(), self.root) + f = tkinter.Frame(self.root) + f.selection_own() + self.assertIs(self.root.selection_own_get(), f) + + def test_event_add_delete_info(self): + self.addCleanup(self.root.event_delete, '<>') + self.root.event_add('<>', '', '') + self.assertEqual(self.root.event_info('<>'), + ('', '')) + self.assertIn('<>', self.root.event_info()) + self.root.event_delete('<>', '') + self.assertEqual(self.root.event_info('<>'), + ('',)) + self.root.event_delete('<>') + self.assertEqual(self.root.event_info('<>'), ()) + self.assertRaises(TypeError, self.root.event_delete) + + def test_bell(self): + self.root.bell() # No exception. + self.root.bell(displayof=self.root) + + def test_tk_focusNext_focusPrev(self): + f = tkinter.Frame(self.root) + f.pack() + entries = [tkinter.Entry(f) for _ in range(3)] + for entry in entries: + entry.pack() + # tk_focusNext skips widgets that are not viewable. + entries[-1].wait_visibility() + self.assertIs(entries[0].tk_focusNext(), entries[1]) + self.assertIs(entries[1].tk_focusNext(), entries[2]) + self.assertIs(entries[2].tk_focusPrev(), entries[1]) + self.assertIs(entries[1].tk_focusPrev(), entries[0]) + self.assertRaises(TypeError, entries[0].tk_focusNext, 'x') + self.assertRaises(TypeError, entries[0].tk_focusPrev, 'x') + + def test_tk_strictMotif(self): + self.addCleanup(self.root.tk_strictMotif, False) + self.assertIs(self.root.tk_strictMotif(), False) + self.assertIs(self.root.tk_strictMotif(True), True) + self.assertIs(self.root.tk_strictMotif(), True) + self.assertIs(self.root.tk_strictMotif(False), False) + self.assertRaises(TypeError, self.root.tk_strictMotif, 1, 2) + + def test_tk_bisque(self): + # tk_bisque resets the color palette; use a separate root so that + # the shared one is not affected. + root = tkinter.Tk() + self.addCleanup(root.destroy) + root.tk_bisque() + self.assertEqual(root['background'], '#ffe4c4') + self.assertRaises(TypeError, root.tk_bisque, 'x') + + def test_wait_variable(self): + var = tkinter.StringVar(self.root) + self.assertEqual(self.root.waitvar, self.root.wait_variable) + self.root.after(1, var.set, 'done') + self.root.wait_variable(var) # Returns once the variable is set. + self.assertEqual(var.get(), 'done') + + def test_wait_window(self): + top = tkinter.Toplevel(self.root) + self.root.after(1, top.destroy) + self.root.wait_window(top) # Returns once the window is destroyed. + self.assertFalse(top.winfo_exists()) + + def test_tk_focusFollowsMouse(self): + self.root.tk_focusFollowsMouse() # No exception. + + def test_selection_handle(self): + f = tkinter.Frame(self.root) + def handler(offset, length): + return 'PAYLOAD'[int(offset):int(offset) + int(length)] + f.selection_handle(handler) + f.selection_own() + self.assertEqual(f.selection_get(), 'PAYLOAD') + + def test_grab_set_global(self): + # A successful global grab directs all events on the display to this + # application, so only the error paths are tested here. + self.assertRaises(TypeError, self.root.grab_set_global, 'extra') + with self.subTest('non-viewable window'): + if self.root._windowingsystem != 'x11': + # Grabbing a non-viewable window fails only on X11; elsewhere + # it would actually grab the whole display. + self.skipTest('only X11 fails the grab') + f = tkinter.Frame(self.root) # not yet viewable + self.assertRaisesRegex(TclError, 'grab failed', f.grab_set_global) + + def test_send(self): + if self.root._windowingsystem != 'x11': + self.skipTest('send is only supported on X11') + self.assertRaisesRegex(TclError, 'no application named', + self.root.send, 'no_such_interp_xyzzy', 'set x 1') + + def test_event_repr_defaults(self): + e = tkinter.Event() + e.serial = 12345 + e.num = '??' + e.height = '??' + e.keycode = '??' + e.state = 0 + e.time = 123456789 + e.width = '??' + e.x = '??' + e.y = '??' + e.char = '' + e.keysym = '??' + e.keysym_num = '??' + e.type = '100' + e.widget = '??' + e.x_root = '??' + e.y_root = '??' + e.delta = 0 + self.assertEqual(repr(e), '<100 event>') + + def test_event_repr(self): + e = tkinter.Event() + e.serial = 12345 + e.num = 3 + e.focus = True + e.height = 200 + e.keycode = 65 + e.state = 0x30405 + e.time = 123456789 + e.width = 300 + e.x = 10 + e.y = 20 + e.char = 'A' + e.send_event = True + e.keysym = 'Key-A' + e.keysym_num = ord('A') + e.type = tkinter.EventType.Configure + e.widget = '.text' + e.x_root = 1010 + e.y_root = 1020 + e.delta = -1 + self.assertEqual(repr(e), + "") + + def test_eventtype_enum(self): + class CheckedEventType(enum.StrEnum): + KeyPress = '2' + Key = KeyPress + KeyRelease = '3' + ButtonPress = '4' + Button = ButtonPress + ButtonRelease = '5' + Motion = '6' + Enter = '7' + Leave = '8' + FocusIn = '9' + FocusOut = '10' + Keymap = '11' # undocumented + Expose = '12' + GraphicsExpose = '13' # undocumented + NoExpose = '14' # undocumented + Visibility = '15' + Create = '16' + Destroy = '17' + Unmap = '18' + Map = '19' + MapRequest = '20' + Reparent = '21' + Configure = '22' + ConfigureRequest = '23' + Gravity = '24' + ResizeRequest = '25' + Circulate = '26' + CirculateRequest = '27' + Property = '28' + SelectionClear = '29' # undocumented + SelectionRequest = '30' # undocumented + Selection = '31' # undocumented + Colormap = '32' + ClientMessage = '33' # undocumented + Mapping = '34' # undocumented + VirtualEvent = '35' # undocumented + Activate = '36' + Deactivate = '37' + MouseWheel = '38' + enum._test_simple_enum(CheckedEventType, tkinter.EventType) + + def test_getboolean(self): + for v in 'true', 'yes', 'on', '1', 't', 'y', 1, True: + self.assertIs(self.root.getboolean(v), True) + for v in 'false', 'no', 'off', '0', 'f', 'n', 0, False: + self.assertIs(self.root.getboolean(v), False) + self.assertRaises(ValueError, self.root.getboolean, 'yea') + self.assertRaises(ValueError, self.root.getboolean, '') + self.assertRaises(TypeError, self.root.getboolean, None) + self.assertRaises(TypeError, self.root.getboolean, ()) + + def test_mainloop(self): + log = [] + def callback(): + log.append(1) + self.root.after(100, self.root.quit) + self.root.after(100, callback) + self.root.mainloop(1) + self.assertEqual(log, []) + self.root.mainloop(0) + self.assertEqual(log, [1]) + self.assertTrue(self.root.winfo_exists()) + + def test_info_patchlevel(self): + vi = self.root.info_patchlevel() + f = tkinter.Frame(self.root) + self.assertEqual(f.info_patchlevel(), vi) + # The following is almost a copy of tests for sys.version_info. + self.assertIsInstance(vi[:], tuple) + self.assertEqual(len(vi), 5) + self.assertIsInstance(vi[0], int) + self.assertIsInstance(vi[1], int) + self.assertIsInstance(vi[2], int) + self.assertIn(vi[3], ("alpha", "beta", "candidate", "final")) + self.assertIsInstance(vi[4], int) + self.assertIsInstance(vi.major, int) + self.assertIsInstance(vi.minor, int) + self.assertIsInstance(vi.micro, int) + self.assertIn(vi.releaselevel, ("alpha", "beta", "final")) + self.assertIsInstance(vi.serial, int) + self.assertEqual(vi[0], vi.major) + self.assertEqual(vi[1], vi.minor) + self.assertEqual(vi[2], vi.micro) + self.assertEqual(vi[3], vi.releaselevel) + self.assertEqual(vi[4], vi.serial) + self.assertTrue(vi > (1,0,0)) + if vi.releaselevel == 'final': + self.assertEqual(vi.serial, 0) + else: + self.assertEqual(vi.micro, 0) + self.assertStartsWith(str(vi), f'{vi.major}.{vi.minor}') + + def test_embedded_null(self): + widget = tkinter.Entry(self.root) + widget.insert(0, 'abc\0def') # ASCII-only + widget.selection_range(0, 'end') + self.assertEqual(widget.selection_get(), 'abc\x00def') + widget.insert(0, '\u20ac\0') # non-ASCII + widget.selection_range(0, 'end') + self.assertEqual(widget.selection_get(), '\u20ac\0abc\x00def') + + def test_iterable_protocol(self): + widget = tkinter.Entry(self.root) + self.assertNotIsSubclass(tkinter.Entry, collections.abc.Iterable) + self.assertNotIsSubclass(tkinter.Entry, collections.abc.Container) + self.assertNotIsInstance(widget, collections.abc.Iterable) + self.assertNotIsInstance(widget, collections.abc.Container) + with self.assertRaisesRegex(TypeError, 'is not iterable'): + iter(widget) + with self.assertRaisesRegex(TypeError, 'is not a container or iterable'): + widget in widget + + +class TkTest(AbstractTkTest, unittest.TestCase): + + def test_readprofile(self): + # gh-153333: profile scripts are decoded with their own coding cookie, + # not the locale encoding. Two cookies so no locale can mask the bug. + profiles = { + '.RpClass.py': ('latin-1', "self._rp_latin1 = 'caf\xe9'"), + '.rpbase.py': ('utf-8', "self._rp_utf8 = 'caf\xe9'"), + } + self.addCleanup(self.root.__dict__.pop, '_rp_latin1', None) + self.addCleanup(self.root.__dict__.pop, '_rp_utf8', None) + with (os_helper.temp_dir() as home, + os_helper.EnvironmentVarGuard() as env): + env['HOME'] = home + for filename, (encoding, body) in profiles.items(): + script = '# -*- coding: %s -*-\n%s\n' % (encoding, body) + with open(os.path.join(home, filename), 'wb') as f: + f.write(script.encode(encoding)) + self.root.readprofile('rpbase', 'RpClass') + self.assertEqual(self.root._rp_latin1, 'caf\xe9') + self.assertEqual(self.root._rp_utf8, 'caf\xe9') + + def test_className(self): + # The className argument sets the class of the root window. Tk + # title-cases it: the first letter is upper-cased, the rest lower-cased. + cases = [ + ('fooBAR', 'Foobar'), + ('éÉ', 'Éé'), # small and capital E WITH ACUTE + ] + if tcl_version >= (9, 0): + # small and capital DESERET LETTER LONG I (a non-BMP script) + cases.append(('\U00010428\U00010400', '\U00010400\U00010428')) + for className, klass in cases: + root = tkinter.Tk(className=className) + try: + self.assertEqual(root.winfo_class(), klass) + finally: + root.destroy() + if tcl_version < (9, 0): + # gh-126219: title-casing a non-BMP first letter crashed Tcl 8.x; + # such a class name is now rejected. + self.assertRaises(ValueError, tkinter.Tk, className='\U00010428') + + +class WinfoTest(AbstractTkTest, unittest.TestCase): + + def test_winfo_rgb(self): + + def assertApprox(col1, col2): + # A small amount of flexibility is required (bpo-45496) + # 33 is ~0.05% of 65535, which is a reasonable margin + for col1_channel, col2_channel in zip(col1, col2): + self.assertAlmostEqual(col1_channel, col2_channel, delta=33) + + root = self.root + rgb = root.winfo_rgb + + # Color name. + self.assertEqual(rgb('red'), (65535, 0, 0)) + self.assertEqual(rgb('dark slate blue'), (18504, 15677, 35723)) + # #RGB - extends each 4-bit hex value to be 16-bit. + self.assertEqual(rgb('#F0F'), (0xFFFF, 0x0000, 0xFFFF)) + # #RRGGBB - extends each 8-bit hex value to be 16-bit. + assertApprox(rgb('#4a3c8c'), (0x4a4a, 0x3c3c, 0x8c8c)) + # #RRRRGGGGBBBB + assertApprox(rgb('#dede14143939'), (0xdede, 0x1414, 0x3939)) + # Invalid string. + with self.assertRaises(tkinter.TclError): + rgb('#123456789a') + # RGB triplet is invalid input. + with self.assertRaises(tkinter.TclError): + rgb((111, 78, 55)) + + def test_winfo_pathname(self): + t = tkinter.Toplevel(self.root) + w = tkinter.Button(t) + wid = w.winfo_id() + self.assertIsInstance(wid, int) + self.assertEqual(self.root.winfo_pathname(hex(wid)), str(w)) + self.assertEqual(self.root.winfo_pathname(hex(wid), displayof=None), str(w)) + self.assertEqual(self.root.winfo_pathname(hex(wid), displayof=t), str(w)) + self.assertEqual(self.root.winfo_pathname(wid), str(w)) + self.assertEqual(self.root.winfo_pathname(wid, displayof=None), str(w)) + self.assertEqual(self.root.winfo_pathname(wid, displayof=t), str(w)) + + def test_winfo_class_name_parent(self): + f = tkinter.Frame(self.root) + b = tkinter.Button(f) + self.assertEqual(f.winfo_class(), 'Frame') + self.assertEqual(b.winfo_class(), 'Button') + self.assertEqual(b.winfo_name(), str(b).rsplit('.', 1)[-1]) + self.assertEqual(b.winfo_parent(), str(f)) + self.assertEqual(f.winfo_parent(), str(self.root)) + self.assertIs(f.winfo_toplevel(), self.root) + t = tkinter.Toplevel(self.root) + self.assertIs(tkinter.Button(t).winfo_toplevel(), t) + self.assertEqual(self.root.nametowidget(b.winfo_parent()), f) + + def test_winfo_children(self): + self.assertEqual(self.root.winfo_children(), []) + f = tkinter.Frame(self.root) + b = tkinter.Button(f) + self.assertEqual(self.root.winfo_children(), [f]) + self.assertEqual(f.winfo_children(), [b]) + + def test_winfo_visual_info(self): + f = tkinter.Frame(self.root) + self.assertIsInstance(f.winfo_depth(), int) + self.assertIsInstance(f.winfo_cells(), int) + self.assertIsInstance(f.winfo_visual(), str) + self.assertIsInstance(f.winfo_visualid(), str) + self.assertIsInstance(f.winfo_colormapfull(), bool) + visuals = self.root.winfo_visualsavailable() + self.assertIsInstance(visuals, list) + for name, depth in visuals: + self.assertIsInstance(name, str) + self.assertIsInstance(depth, int) + + def test_winfo_viewable(self): + f = tkinter.Frame(self.root) + self.assertFalse(f.winfo_viewable()) + f.pack() + f.wait_visibility() + self.root.update() + self.assertTrue(f.winfo_viewable()) + + def test_winfo_atom(self): + atom = self.root.winfo_atom('PRIMARY') + self.assertIsInstance(atom, int) + self.assertEqual(self.root.winfo_atomname(atom), 'PRIMARY') + self.assertEqual( + self.root.winfo_atomname(atom, displayof=self.root), 'PRIMARY') + self.assertEqual( + self.root.winfo_atom('PRIMARY', displayof=self.root), atom) + self.assertRaisesRegex(TclError, 'no atom exists', + self.root.winfo_atomname, 10 ** 9) + + def test_winfo_pointer(self): + self.assertIsInstance(self.root.winfo_pointerx(), int) + self.assertIsInstance(self.root.winfo_pointery(), int) + xy = self.root.winfo_pointerxy() + self.assertIsInstance(xy, tuple) + self.assertEqual(len(xy), 2) + self.assertTrue(all(isinstance(v, int) for v in xy)) + + def test_winfo_containing(self): + self.root.update() + # No window contains a point far off the screen. + self.assertIsNone(self.root.winfo_containing(-10000, -10000)) + self.assertIsNone( + self.root.winfo_containing(-10000, -10000, displayof=self.root)) + + def test_winfo_fpixels(self): + self.assertIsInstance(self.root.winfo_fpixels('1i'), float) + self.assertAlmostEqual(self.root.winfo_fpixels('1i'), + self.root.winfo_fpixels('72p')) + # Tk < 9 reports 'bad screen distance "spam"', Tk 9 reports + # 'expected screen distance ... but got "spam"'. + self.assertRaisesRegex(TclError, + r'(bad|expected) screen distance.*"spam"', + self.root.winfo_fpixels, 'spam') + + def test_winfo_screen(self): + for name in ('winfo_screenwidth', 'winfo_screenheight', + 'winfo_screenmmwidth', 'winfo_screenmmheight', + 'winfo_screencells', 'winfo_screendepth'): + value = getattr(self.root, name)() + self.assertIsInstance(value, int) + self.assertGreater(value, 0) + self.assertIsInstance(self.root.winfo_screenvisual(), str) + self.assertIsInstance(self.root.winfo_screen(), str) + self.assertIsInstance(self.root.winfo_server(), str) + + def test_winfo_vroot(self): + for name in ('winfo_vrootwidth', 'winfo_vrootheight', + 'winfo_vrootx', 'winfo_vrooty'): + self.assertIsInstance(getattr(self.root, name)(), int) + + def test_winfo_interps(self): + interps = self.root.winfo_interps() + self.assertIsInstance(interps, tuple) + # The registry of interpreters is only populated where "send" is + # supported (i.e. X11), so do not require this interpreter's name. + if self.root._windowingsystem == 'x11': + self.assertIn(self.root.tk.call('tk', 'appname'), interps) + self.assertEqual(self.root.winfo_interps(displayof=self.root), interps) + + +class WmTest(AbstractTkTest, unittest.TestCase): + + def test_wm_attribute(self): + w = self.root + attributes = w.wm_attributes(return_python_dict=True) + self.assertIsInstance(attributes, dict) + attributes2 = w.wm_attributes() + self.assertIsInstance(attributes2, tuple) + self.assertEqual(attributes2[::2], + tuple('-' + k for k in attributes)) + self.assertEqual(attributes2[1::2], tuple(attributes.values())) + # silently deprecated + attributes3 = w.wm_attributes(None) + if self.wantobjects: + self.assertEqual(attributes3, attributes2) + else: + self.assertIsInstance(attributes3, str) + + for name in attributes: + self.assertEqual(w.wm_attributes(name), attributes[name]) + # silently deprecated + for name in attributes: + self.assertEqual(w.wm_attributes('-' + name), attributes[name]) + + self.assertIn('alpha', attributes) + self.assertIn('fullscreen', attributes) + self.assertIn('topmost', attributes) + if w._windowingsystem == "win32": + self.assertIn('disabled', attributes) + self.assertIn('toolwindow', attributes) + self.assertIn('transparentcolor', attributes) + if w._windowingsystem == "aqua": + self.assertIn('modified', attributes) + self.assertIn('notify', attributes) + self.assertIn('titlepath', attributes) + self.assertIn('transparent', attributes) + if w._windowingsystem == "x11": + self.assertIn('type', attributes) + self.assertIn('zoomed', attributes) + + w.wm_attributes(alpha=0.5) + self.assertEqual(w.wm_attributes('alpha'), + 0.5 if self.wantobjects else '0.5') + w.wm_attributes(alpha=1.0) + self.assertEqual(w.wm_attributes('alpha'), + 1.0 if self.wantobjects else '1.0') + # silently deprecated + w.wm_attributes('-alpha', 0.5) + self.assertEqual(w.wm_attributes('alpha'), + 0.5 if self.wantobjects else '0.5') + w.wm_attributes(alpha=1.0) + self.assertEqual(w.wm_attributes('alpha'), + 1.0 if self.wantobjects else '1.0') + + def test_wm_iconbitmap(self): + t = tkinter.Toplevel(self.root) + patchlevel = get_tk_patchlevel(t) + + if ( + t._windowingsystem == 'aqua' + and sys.platform == 'darwin' + and platform.machine() == 'x86_64' + and platform.mac_ver()[0].startswith('26.') + ): + # https://github.com/python/cpython/issues/146531 + # Tk bug 4a2070f0d3a99aa412bc582d386d575ca2f37323 + # Not fixed as of Tk 8.6.18 and 9.0.4. + self.skipTest('wm iconbitmap hangs on macOS 26 Intel') + + self.assertEqual(t.wm_iconbitmap(), '') + t.wm_iconbitmap('hourglass') + bug = False + if t._windowingsystem == 'aqua': + # Tk bug 13ac26b35dc55f7c37f70b39d59d7ef3e63017c8. + if patchlevel < (8, 6, 17) or (9, 0) <= patchlevel < (9, 0, 2): + bug = True + if not bug: + self.assertEqual(t.wm_iconbitmap(), 'hourglass') + self.assertEqual(self.root.wm_iconbitmap(), '') + t.wm_iconbitmap('') + self.assertEqual(t.wm_iconbitmap(), '') + + if t._windowingsystem == 'win32': + t.wm_iconbitmap(default='hourglass') + self.assertEqual(t.wm_iconbitmap(), 'hourglass') + self.assertEqual(self.root.wm_iconbitmap(), '') + t.wm_iconbitmap(default='') + self.assertEqual(t.wm_iconbitmap(), '') + + t.destroy() + + def test_wm_iconphoto(self): + t = tkinter.Toplevel(self.root) + img = tkinter.PhotoImage(master=t, width=16, height=16) + t.wm_iconphoto(False, img) # No exception. + t.wm_iconphoto(True, img) + self.assertRaises(tkinter.TclError, t.wm_iconphoto, False, 'spam') + + def test_wm_title(self): + t = tkinter.Toplevel(self.root) + t.title('Hello') + self.assertEqual(t.title(), 'Hello') + self.assertEqual(t.wm_title(), 'Hello') + t.wm_title('Spam') + self.assertEqual(t.title(), 'Spam') + + def test_wm_geometry(self): + t = tkinter.Toplevel(self.root) + t.geometry('200x100+10+20') + t.update() + self.assertRegex(t.geometry(), r'^200x100\+-?\d+\+-?\d+$') + self.assertEqual(t.wm_geometry(), t.geometry()) + + def test_wm_minsize_maxsize(self): + t = tkinter.Toplevel(self.root) + # Use a width above the minimum enforced by some platforms (72 on Aqua). + t.minsize(150, 100) + self.assertEqual(t.minsize(), (150, 100)) + t.maxsize(500, 600) + self.assertEqual(t.maxsize(), (500, 600)) + + def test_wm_resizable(self): + t = tkinter.Toplevel(self.root) + t.resizable(False, True) + self.assertEqual(t.resizable(), (0, 1)) + self.assertRaisesRegex(TclError, 'expected boolean value', + t.resizable, 'spam', True) + + def test_wm_aspect(self): + t = tkinter.Toplevel(self.root) + self.assertEqual(t.aspect(), None) + t.aspect(1, 2, 3, 4) + self.assertEqual(t.aspect(), (1, 2, 3, 4)) + + def test_wm_grid(self): + t = tkinter.Toplevel(self.root) + t.wm_grid(10, 10, 5, 5) + self.assertEqual(t.wm_grid(), (10, 10, 5, 5)) + + def test_wm_positionfrom_sizefrom(self): + # These set X11 size hints and may be no-ops on other platforms. + t = tkinter.Toplevel(self.root) + t.positionfrom('user') + self.assertIn(t.positionfrom(), ('user', '')) + t.sizefrom('program') + self.assertIn(t.sizefrom(), ('program', '')) + + def test_wm_focusmodel(self): + t = tkinter.Toplevel(self.root) + self.assertEqual(t.focusmodel(), 'passive') + t.focusmodel('active') + self.assertEqual(t.focusmodel(), 'active') + self.assertRaises(TclError, t.focusmodel, 'spam') + + def test_wm_iconname(self): + # WM_ICON_NAME is an X11 property and may be a no-op elsewhere. + t = tkinter.Toplevel(self.root) + t.iconname('Icon') + self.assertIn(t.iconname(), ('Icon', '')) + + def test_wm_iconposition(self): + t = tkinter.Toplevel(self.root) + t.wm_iconposition(3, 4) # An X11 hint; may be a no-op elsewhere. + if t._windowingsystem == 'x11': + self.assertEqual(t.wm_iconposition(), (3, 4)) + + def test_wm_iconmask_iconwindow(self): + if self.root._windowingsystem != 'x11': + self.skipTest('iconmask and iconwindow are X11-specific') + t = tkinter.Toplevel(self.root) + t.wm_iconmask('gray50') # No exception. + icon = tkinter.Toplevel(self.root) + t.wm_iconwindow(icon) + self.assertEqual(str(t.wm_iconwindow()), str(icon)) + + def test_wm_colormapwindows(self): + if self.root._windowingsystem != 'x11': + self.skipTest('colormapwindows is X11-specific') + t = tkinter.Toplevel(self.root) + self.assertEqual(t.wm_colormapwindows(), []) + f = tkinter.Frame(t) + t.wm_colormapwindows(f) + self.assertEqual([str(w) for w in t.wm_colormapwindows()], [str(f)]) + + def test_wm_manage_forget(self): + f = tkinter.Frame(self.root) + self.root.wm_manage(f) # Make the frame a top-level window. + self.root.wm_forget(f) # Revert it; no exception either way. + + def test_wm_client_command(self): + t = tkinter.Toplevel(self.root) + t.client('myhost') + t.wm_command('myapp -x') + # WM_CLIENT_MACHINE and WM_COMMAND are X11 properties; elsewhere the + # setters may be no-ops and wm_command may return a split list. + if t._windowingsystem == 'x11': + self.assertEqual(t.client(), 'myhost') + self.assertEqual(t.wm_command(), 'myapp -x') + + def test_wm_overrideredirect(self): + t = tkinter.Toplevel(self.root) + self.assertFalse(t.overrideredirect()) + t.overrideredirect(True) + self.assertTrue(t.overrideredirect()) + + def test_wm_state(self): + t = tkinter.Toplevel(self.root) + t.update() + self.assertEqual(t.state(), 'normal') + t.withdraw() + self.assertEqual(t.state(), 'withdrawn') + t.deiconify() + t.update() + self.assertEqual(t.state(), 'normal') + self.assertRaises(TclError, t.state, 'spam') + + def test_wm_frame(self): + t = tkinter.Toplevel(self.root) + t.update() + self.assertIsInstance(t.frame(), str) + + def test_wm_group(self): + # The window group is an X11 concept and may be a no-op elsewhere. + t = tkinter.Toplevel(self.root) + t.group(self.root) + self.assertIn(t.group(), (str(self.root), '')) + + def test_wm_protocol(self): + t = tkinter.Toplevel(self.root) + self.assertIsInstance(t.protocol(), tuple) + t.protocol('WM_SAVE_YOURSELF', lambda: None) + self.assertIn('WM_SAVE_YOURSELF', t.protocol()) + # Querying a single protocol returns the bound command name. + self.assertTrue(t.protocol('WM_SAVE_YOURSELF')) + + def test_wm_transient(self): + t = tkinter.Toplevel(self.root) + self.assertEqual(t.transient(), '') + t.transient(self.root) + self.assertEqual(str(t.transient()), str(self.root)) + + +class EventTest(AbstractTkTest, unittest.TestCase): + + def test_focus(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('', events.append) + + f.focus_force() + self.root.update() + # The window manager can take the focus away and give it back, + # which makes Tk generate additional focus events. + self.assertGreaterEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.FocusIn) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertEqual(e.time, '??') + self.assertIs(e.send_event, False) + self.assertNotHasAttr(e, 'focus') + self.assertEqual(e.num, '??') + self.assertEqual(e.state, '??') + self.assertEqual(e.char, '??') + self.assertEqual(e.keycode, '??') + self.assertEqual(e.keysym, '??') + self.assertEqual(e.keysym_num, '??') + self.assertEqual(e.width, '??') + self.assertEqual(e.height, '??') + self.assertEqual(e.x, '??') + self.assertEqual(e.y, '??') + self.assertEqual(e.x_root, '??') + self.assertEqual(e.y_root, '??') + self.assertEqual(e.delta, 0) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, 'NotifyAncestor') + self.assertEqual(repr(e), '') + + def test_configure(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('', events.append) + + f.configure(height=120, borderwidth=10) + self.assertEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.Configure) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertEqual(e.time, '??') + self.assertIs(e.send_event, False) + self.assertNotHasAttr(e, 'focus') + self.assertEqual(e.num, '??') + self.assertEqual(e.state, '??') + self.assertEqual(e.char, '??') + self.assertEqual(e.keycode, '??') + self.assertEqual(e.keysym, '??') + self.assertEqual(e.keysym_num, '??') + self.assertEqual(e.width, 150) + self.assertEqual(e.height, 100) + self.assertEqual(e.x, 0) + self.assertEqual(e.y, 0) + self.assertEqual(e.x_root, '??') + self.assertEqual(e.y_root, '??') + self.assertEqual(e.delta, 0) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, '??') + self.assertEqual(repr(e), '') + + def test_event_generate_key_press(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('', events.append) + f.focus_force() + + f.event_generate('') + self.assertEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.KeyPress) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertEqual(e.time, 0) + self.assertIs(e.send_event, False) + self.assertNotHasAttr(e, 'focus') + self.assertEqual(e.num, '??') + self.assertIsInstance(e.state, int) + self.assertNotEqual(e.state, 0) + self.assertEqual(e.char, 'z') + self.assertIsInstance(e.keycode, int) + self.assertNotEqual(e.keycode, 0) + self.assertEqual(e.keysym, 'z') + self.assertEqual(e.keysym_num, ord('z')) + self.assertEqual(e.width, '??') + self.assertEqual(e.height, '??') + self.assertEqual(e.x, -1 - f.winfo_rootx()) + self.assertEqual(e.y, -1 - f.winfo_rooty()) + self.assertEqual(e.x_root, -1) + self.assertEqual(e.y_root, -1) + self.assertEqual(e.delta, 0) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, '??') + self.assertEqual(repr(e), + f"") + + def test_event_generate_enter(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('', events.append) + + f.event_generate('', x=100, y=50) + self.assertEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.Enter) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertEqual(e.time, 0) + self.assertIs(e.send_event, False) + self.assertIs(e.focus, False) + self.assertEqual(e.num, '??') + self.assertEqual(e.state, 0) + self.assertEqual(e.char, '??') + self.assertEqual(e.keycode, '??') + self.assertEqual(e.keysym, '??') + self.assertEqual(e.keysym_num, '??') + self.assertEqual(e.width, '??') + self.assertEqual(e.height, '??') + self.assertEqual(e.x, 100) + self.assertEqual(e.y, 50) + self.assertEqual(e.x_root, 100 + f.winfo_rootx()) + self.assertEqual(e.y_root, 50 + f.winfo_rooty()) + self.assertEqual(e.delta, 0) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, 'NotifyAncestor') + self.assertEqual(repr(e), '') + + f.event_generate('', x=100, y=50, detail='NotifyPointer') + self.assertEqual(len(events), 2, events) + e = events[1] + self.assertIs(e.type, tkinter.EventType.Enter) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, 'NotifyPointer') + + def test_event_generate_button_press(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('', events.append) + f.focus_force() + + f.event_generate('', x=100, y=50) + self.assertEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.ButtonPress) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertEqual(e.time, 0) + self.assertIs(e.send_event, False) + self.assertNotHasAttr(e, 'focus') + self.assertEqual(e.num, 1) + self.assertEqual(e.state, 0) + self.assertEqual(e.char, '??') + self.assertEqual(e.keycode, '??') + self.assertEqual(e.keysym, '??') + self.assertEqual(e.keysym_num, '??') + self.assertEqual(e.width, '??') + self.assertEqual(e.height, '??') + self.assertEqual(e.x, 100) + self.assertEqual(e.y, 50) + self.assertEqual(e.x_root, f.winfo_rootx() + 100) + self.assertEqual(e.y_root, f.winfo_rooty() + 50) + self.assertEqual(e.delta, 0) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, '??') + self.assertEqual(repr(e), '') + + def test_event_generate_motion(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('', events.append) + f.focus_force() + + f.event_generate('', x=100, y=50) + self.assertEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.Motion) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertEqual(e.time, 0) + self.assertIs(e.send_event, False) + self.assertNotHasAttr(e, 'focus') + self.assertEqual(e.num, '??') + self.assertEqual(e.state, 0x100) + self.assertEqual(e.char, '??') + self.assertEqual(e.keycode, '??') + self.assertEqual(e.keysym, '??') + self.assertEqual(e.keysym_num, '??') + self.assertEqual(e.width, '??') + self.assertEqual(e.height, '??') + self.assertEqual(e.x, 100) + self.assertEqual(e.y, 50) + self.assertEqual(e.x_root, f.winfo_rootx() + 100) + self.assertEqual(e.y_root, f.winfo_rooty() + 50) + self.assertEqual(e.delta, 0) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, '??') + self.assertEqual(repr(e), '') + + def test_event_generate_mouse_wheel(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('', events.append) + f.focus_force() + + f.event_generate('', x=100, y=50, delta=-5) + self.assertEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.MouseWheel) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertIs(e.send_event, False) + self.assertNotHasAttr(e, 'focus') + self.assertEqual(e.time, 0) + self.assertEqual(e.num, '??') + self.assertEqual(e.state, 0) + self.assertEqual(e.char, '??') + self.assertEqual(e.keycode, '??') + self.assertEqual(e.keysym, '??') + self.assertEqual(e.keysym_num, '??') + self.assertEqual(e.width, '??') + self.assertEqual(e.height, '??') + self.assertEqual(e.x, 100) + self.assertEqual(e.y, 50) + self.assertEqual(e.x_root, f.winfo_rootx() + 100) + self.assertEqual(e.y_root, f.winfo_rooty() + 50) + self.assertEqual(e.delta, -5) + self.assertEqual(e.user_data, '??') + self.assertEqual(e.detail, '??') + self.assertEqual(repr(e), '') + + def test_event_generate_virtual_event(self): + f = tkinter.Frame(self.root, width=150, height=100) + f.pack() + self.root.wait_visibility() # needed on Windows + self.root.update_idletasks() + + events = [] + f.bind('<>', events.append) + f.focus_force() + + f.event_generate('<>', x=50) + self.assertEqual(len(events), 1, events) + e = events[0] + self.assertIs(e.type, tkinter.EventType.VirtualEvent) + self.assertIs(e.widget, f) + self.assertIsInstance(e.serial, int) + self.assertEqual(e.time, 0) + self.assertIs(e.send_event, False) + self.assertNotHasAttr(e, 'focus') + self.assertEqual(e.num, '??') + self.assertEqual(e.state, 0) + self.assertEqual(e.char, '??') + self.assertEqual(e.keycode, '??') + self.assertEqual(e.keysym, '??') + self.assertEqual(e.keysym_num, '??') + self.assertEqual(e.width, '??') + self.assertEqual(e.height, '??') + self.assertEqual(e.x, 50) + self.assertEqual(e.y, 0) + self.assertEqual(e.x_root, f.winfo_rootx() + 50) + self.assertEqual(e.y_root, -1) + self.assertEqual(e.delta, 0) + self.assertEqual(e.user_data, '') + self.assertEqual(e.detail, '??') + self.assertEqual(repr(e), + f"") + + f.event_generate('<>', data='spam') + self.assertEqual(len(events), 2, events) + e = events[1] + self.assertIs(e.type, tkinter.EventType.VirtualEvent) + self.assertEqual(e.user_data, 'spam') + self.assertEqual(e.detail, '??') + + +class BindTest(AbstractTkTest, unittest.TestCase): + + def setUp(self): + super().setUp() + root = self.root + self.frame = tkinter.Frame(self.root, class_='Test', + width=150, height=100) + self.frame.pack() + + def assertCommandExist(self, funcid): + self.assertEqual(_info_commands(self.root, funcid), (funcid,)) + + def assertCommandNotExist(self, funcid): + self.assertEqual(_info_commands(self.root, funcid), ()) + + def test_bind(self): + event = '' + f = self.frame + self.assertEqual(f.bind(), ()) + self.assertEqual(f.bind(event), '') + def test1(e): pass + def test2(e): pass + + funcid = f.bind(event, test1) + self.assertEqual(f.bind(), (event,)) + script = f.bind(event) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + + funcid2 = f.bind(event, test2, add=True) + script = f.bind(event) + self.assertIn(funcid, script) + self.assertIn(funcid2, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + def test_unbind(self): + event = '' + f = self.frame + self.assertEqual(f.bind(), ()) + self.assertEqual(f.bind(event), '') + def test1(e): pass + def test2(e): pass + + funcid = f.bind(event, test1) + funcid2 = f.bind(event, test2, add=True) + + self.assertRaises(TypeError, f.unbind) + f.unbind(event) + self.assertEqual(f.bind(event), '') + self.assertEqual(f.bind(), ()) + + def test_unbind2(self): + f = self.frame + f.wait_visibility() + f.focus_force() + f.update_idletasks() + event = '' + self.assertEqual(f.bind(), ()) + self.assertEqual(f.bind(event), '') + def test1(e): events.append('a') + def test2(e): events.append('b') + def test3(e): events.append('c') + + funcid = f.bind(event, test1) + funcid2 = f.bind(event, test2, add=True) + funcid3 = f.bind(event, test3, add=True) + events = [] + f.event_generate(event) + self.assertEqual(events, ['a', 'b', 'c']) + + f.unbind(event, funcid2) + script = f.bind(event) + self.assertNotIn(funcid2, script) + self.assertIn(funcid, script) + self.assertIn(funcid3, script) + self.assertEqual(f.bind(), (event,)) + self.assertCommandNotExist(funcid2) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid3) + events = [] + f.event_generate(event) + self.assertEqual(events, ['a', 'c']) + + f.unbind(event, funcid) + f.unbind(event, funcid3) + self.assertEqual(f.bind(event), '') + self.assertEqual(f.bind(), ()) + self.assertCommandNotExist(funcid) + self.assertCommandNotExist(funcid2) + self.assertCommandNotExist(funcid3) + events = [] + f.event_generate(event) + self.assertEqual(events, []) + + # non-idempotent + self.assertRaises(tkinter.TclError, f.unbind, event, funcid2) + + def test_bind_rebind(self): + event = '' + f = self.frame + self.assertEqual(f.bind(), ()) + self.assertEqual(f.bind(event), '') + def test1(e): pass + def test2(e): pass + def test3(e): pass + + funcid = f.bind(event, test1) + funcid2 = f.bind(event, test2, add=True) + script = f.bind(event) + self.assertIn(funcid2, script) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + funcid3 = f.bind(event, test3) + script = f.bind(event) + self.assertNotIn(funcid, script) + self.assertNotIn(funcid2, script) + self.assertIn(funcid3, script) + self.assertCommandNotExist(funcid) + self.assertCommandNotExist(funcid2) + self.assertCommandExist(funcid3) + + def test_bind_class(self): + event = '' + bind_class = self.root.bind_class + unbind_class = self.root.unbind_class + self.assertRaises(TypeError, bind_class) + self.assertEqual(bind_class('Test'), ()) + self.assertEqual(bind_class('Test', event), '') + self.addCleanup(unbind_class, 'Test', event) + def test1(e): pass + def test2(e): pass + + funcid = bind_class('Test', event, test1) + self.assertEqual(bind_class('Test'), (event,)) + script = bind_class('Test', event) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + + funcid2 = bind_class('Test', event, test2, add=True) + script = bind_class('Test', event) + self.assertIn(funcid, script) + self.assertIn(funcid2, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + def test_unbind_class(self): + event = '' + bind_class = self.root.bind_class + unbind_class = self.root.unbind_class + self.assertEqual(bind_class('Test'), ()) + self.assertEqual(bind_class('Test', event), '') + self.addCleanup(unbind_class, 'Test', event) + def test1(e): pass + def test2(e): pass + + funcid = bind_class('Test', event, test1) + funcid2 = bind_class('Test', event, test2, add=True) + + self.assertRaises(TypeError, unbind_class) + self.assertRaises(TypeError, unbind_class, 'Test') + unbind_class('Test', event) + self.assertEqual(bind_class('Test', event), '') + self.assertEqual(bind_class('Test'), ()) + self.assertCommandNotExist(funcid) + self.assertCommandNotExist(funcid2) + + unbind_class('Test', event) # idempotent + + def test_bind_class_rebind(self): + event = '' + bind_class = self.root.bind_class + unbind_class = self.root.unbind_class + self.assertEqual(bind_class('Test'), ()) + self.assertEqual(bind_class('Test', event), '') + self.addCleanup(unbind_class, 'Test', event) + def test1(e): pass + def test2(e): pass + def test3(e): pass + + funcid = bind_class('Test', event, test1) + funcid2 = bind_class('Test', event, test2, add=True) + script = bind_class('Test', event) + self.assertIn(funcid2, script) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + funcid3 = bind_class('Test', event, test3) + script = bind_class('Test', event) + self.assertNotIn(funcid, script) + self.assertNotIn(funcid2, script) + self.assertIn(funcid3, script) + self.assertCommandNotExist(funcid) + self.assertCommandNotExist(funcid2) + self.assertCommandExist(funcid3) + + def test_bind_all(self): + event = '' + bind_all = self.root.bind_all + unbind_all = self.root.unbind_all + self.assertNotIn(event, bind_all()) + self.assertEqual(bind_all(event), '') + self.addCleanup(unbind_all, event) + def test1(e): pass + def test2(e): pass + + funcid = bind_all(event, test1) + self.assertIn(event, bind_all()) + script = bind_all(event) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + + funcid2 = bind_all(event, test2, add=True) + script = bind_all(event) + self.assertIn(funcid, script) + self.assertIn(funcid2, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + def test_unbind_all(self): + event = '' + bind_all = self.root.bind_all + unbind_all = self.root.unbind_all + self.assertNotIn(event, bind_all()) + self.assertEqual(bind_all(event), '') + self.addCleanup(unbind_all, event) + def test1(e): pass + def test2(e): pass + + funcid = bind_all(event, test1) + funcid2 = bind_all(event, test2, add=True) + + unbind_all(event) + self.assertEqual(bind_all(event), '') + self.assertNotIn(event, bind_all()) + self.assertCommandNotExist(funcid) + self.assertCommandNotExist(funcid2) + + unbind_all(event) # idempotent + + def test_bind_all_rebind(self): + event = '' + bind_all = self.root.bind_all + unbind_all = self.root.unbind_all + self.assertNotIn(event, bind_all()) + self.assertEqual(bind_all(event), '') + self.addCleanup(unbind_all, event) + def test1(e): pass + def test2(e): pass + def test3(e): pass + + funcid = bind_all(event, test1) + funcid2 = bind_all(event, test2, add=True) + script = bind_all(event) + self.assertIn(funcid2, script) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + funcid3 = bind_all(event, test3) + script = bind_all(event) + self.assertNotIn(funcid, script) + self.assertNotIn(funcid2, script) + self.assertIn(funcid3, script) + self.assertCommandNotExist(funcid) + self.assertCommandNotExist(funcid2) + self.assertCommandExist(funcid3) + + def _test_tag_bind(self, w): + tag = 'sel' + event = '' + w.pack() + self.assertRaises(TypeError, w.tag_bind) + tag_bind = w._tag_bind if isinstance(w, tkinter.Text) else w.tag_bind + if isinstance(w, tkinter.Text): + self.assertRaises(TypeError, w.tag_bind, tag) + self.assertRaises(TypeError, w.tag_bind, tag, event) + self.assertEqual(tag_bind(tag), ()) + self.assertEqual(tag_bind(tag, event), '') + def test1(e): pass + def test2(e): pass + + funcid = w.tag_bind(tag, event, test1) + self.assertEqual(tag_bind(tag), (event,)) + script = tag_bind(tag, event) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + + funcid2 = w.tag_bind(tag, event, test2, add=True) + script = tag_bind(tag, event) + self.assertIn(funcid, script) + self.assertIn(funcid2, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + def _test_tag_unbind(self, w): + tag = 'sel' + event = '' + w.pack() + tag_bind = w._tag_bind if isinstance(w, tkinter.Text) else w.tag_bind + self.assertEqual(tag_bind(tag), ()) + self.assertEqual(tag_bind(tag, event), '') + def test1(e): pass + def test2(e): pass + + funcid = w.tag_bind(tag, event, test1) + funcid2 = w.tag_bind(tag, event, test2, add=True) + + self.assertRaises(TypeError, w.tag_unbind, tag) + w.tag_unbind(tag, event) + self.assertEqual(tag_bind(tag, event), '') + self.assertEqual(tag_bind(tag), ()) + + def _test_tag_bind_rebind(self, w): + tag = 'sel' + event = '' + w.pack() + tag_bind = w._tag_bind if isinstance(w, tkinter.Text) else w.tag_bind + self.assertEqual(tag_bind(tag), ()) + self.assertEqual(tag_bind(tag, event), '') + def test1(e): pass + def test2(e): pass + def test3(e): pass + + funcid = w.tag_bind(tag, event, test1) + funcid2 = w.tag_bind(tag, event, test2, add=True) + script = tag_bind(tag, event) + self.assertIn(funcid2, script) + self.assertIn(funcid, script) + self.assertCommandExist(funcid) + self.assertCommandExist(funcid2) + + funcid3 = w.tag_bind(tag, event, test3) + script = tag_bind(tag, event) + self.assertNotIn(funcid, script) + self.assertNotIn(funcid2, script) + self.assertIn(funcid3, script) + self.assertCommandExist(funcid3) + + def test_canvas_tag_bind(self): + c = tkinter.Canvas(self.frame) + self._test_tag_bind(c) + + def test_canvas_tag_unbind(self): + c = tkinter.Canvas(self.frame) + self._test_tag_unbind(c) + + def test_canvas_tag_bind_rebind(self): + c = tkinter.Canvas(self.frame) + self._test_tag_bind_rebind(c) + + def test_text_tag_bind(self): + t = tkinter.Text(self.frame) + self._test_tag_bind(t) + + def test_text_tag_unbind(self): + t = tkinter.Text(self.frame) + self._test_tag_unbind(t) + + def test_text_tag_bind_rebind(self): + t = tkinter.Text(self.frame) + self._test_tag_bind_rebind(t) + + def test_bindtags(self): + f = self.frame + self.assertEqual(self.root.bindtags(), ('.', 'Tk', 'all')) + self.assertEqual(f.bindtags(), (str(f), 'Test', '.', 'all')) + f.bindtags(('a', 'b c')) + self.assertEqual(f.bindtags(), ('a', 'b c')) + + def test_bind_events(self): + event = '' + root = self.root + t = tkinter.Toplevel(root) + f = tkinter.Frame(t, class_='Test', width=150, height=100) + f.pack() + root.wait_visibility() # needed on Windows + root.update_idletasks() + self.addCleanup(root.unbind_class, 'Test', event) + self.addCleanup(root.unbind_class, 'Toplevel', event) + self.addCleanup(root.unbind_class, 'tag', event) + self.addCleanup(root.unbind_class, 'tag2', event) + self.addCleanup(root.unbind_all, event) + def test(what): + return lambda e: events.append((what, e.widget)) + + root.bind_all(event, test('all')) + root.bind_class('Test', event, test('frame class')) + root.bind_class('Toplevel', event, test('toplevel class')) + root.bind_class('tag', event, test('tag')) + root.bind_class('tag2', event, test('tag2')) + f.bind(event, test('frame')) + t.bind(event, test('toplevel')) + + events = [] + f.event_generate(event) + self.assertEqual(events, [ + ('frame', f), + ('frame class', f), + ('toplevel', f), + ('all', f), + ]) + + events = [] + t.event_generate(event) + self.assertEqual(events, [ + ('toplevel', t), + ('toplevel class', t), + ('all', t), + ]) + + f.bindtags(('tag', 'tag3')) + events = [] + f.event_generate(event) + self.assertEqual(events, [('tag', f)]) + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_default_root(self): + self.assertIs(tkinter._support_default_root, True) + self.assertIsNone(tkinter._default_root) + root = tkinter.Tk() + root2 = tkinter.Tk() + root3 = tkinter.Tk() + self.assertIs(tkinter._default_root, root) + root2.destroy() + self.assertIs(tkinter._default_root, root) + root.destroy() + self.assertIsNone(tkinter._default_root) + root3.destroy() + self.assertIsNone(tkinter._default_root) + + def test_no_default_root(self): + self.assertIs(tkinter._support_default_root, True) + self.assertIsNone(tkinter._default_root) + root = tkinter.Tk() + self.assertIs(tkinter._default_root, root) + tkinter.NoDefaultRoot() + self.assertIs(tkinter._support_default_root, False) + self.assertNotHasAttr(tkinter, '_default_root') + # repeated call is no-op + tkinter.NoDefaultRoot() + self.assertIs(tkinter._support_default_root, False) + self.assertNotHasAttr(tkinter, '_default_root') + root.destroy() + self.assertIs(tkinter._support_default_root, False) + self.assertNotHasAttr(tkinter, '_default_root') + root = tkinter.Tk() + self.assertIs(tkinter._support_default_root, False) + self.assertNotHasAttr(tkinter, '_default_root') + root.destroy() + + def test_getboolean(self): + self.assertRaises(RuntimeError, tkinter.getboolean, '1') + root = tkinter.Tk() + self.assertIs(tkinter.getboolean('1'), True) + self.assertRaises(ValueError, tkinter.getboolean, 'yea') + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, tkinter.getboolean, '1') + + def test_mainloop(self): + self.assertRaises(RuntimeError, tkinter.mainloop) + root = tkinter.Tk() + root.after_idle(root.quit) + tkinter.mainloop() + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, tkinter.mainloop) + + +def _info_commands(widget, pattern=None): + return widget.tk.splitlist(widget.tk.call('info', 'commands', pattern)) + + +class SignalTest(unittest.TestCase): + + @runInSubprocess() + def test_sigint_handler(self): + # gh-157672: Tk on macOS replaced the SIGINT handler with its own, + # which exits the process. + root = tkinter.Tk() + self.addCleanup(root.destroy) + with self.assertRaises(KeyboardInterrupt): + signal.raise_signal(signal.SIGINT) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_scrolledtext.py b/Lib/test/test_tkinter/test_scrolledtext.py new file mode 100644 index 00000000000..913e7d8aab6 --- /dev/null +++ b/Lib/test/test_tkinter/test_scrolledtext.py @@ -0,0 +1,65 @@ +import unittest +import tkinter +from tkinter.scrolledtext import ScrolledText +from test.support import requires +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractTkTest + +requires('gui') + + +class ScrolledTextTest(AbstractTkTest, unittest.TestCase): + + def create(self, **kwargs): + st = ScrolledText(self.root, **kwargs) + self.addCleanup(st.destroy) + return st + + def test_create(self): + st = self.create(background='red', height=5) + # It is a Text widget held in a Frame together with a Scrollbar. + self.assertIsInstance(st, tkinter.Text) + self.assertIsInstance(st.frame, tkinter.Frame) + self.assertIsInstance(st.vbar, tkinter.Scrollbar) + self.assertEqual(st.winfo_parent(), str(st.frame)) + # str() returns the frame, so that geometry managers manage it. + self.assertEqual(str(st), str(st.frame)) + # Keyword options configure the Text. + self.assertEqual(str(st['background']), 'red') + self.assertEqual(st['height'], 5 if self.wantobjects else '5') + + def test_text_methods(self): + st = self.create() + st.insert('1.0', 'hello\nworld') + self.assertEqual(st.get('1.0', 'end-1c'), 'hello\nworld') + self.assertEqual(st.index('end-1c'), '2.5') + st.delete('1.0', 'end') + self.assertEqual(st.get('1.0', 'end-1c'), '') + + def test_geometry_methods(self): + st = self.create() + # configure is not redirected; it configures the Text. + st.configure(height=8) + self.assertEqual(st['height'], 8 if self.wantobjects else '8') + # Pack, Grid and Place methods are redirected to the frame. + st.pack() + self.root.update() + self.assertEqual(st.frame.winfo_manager(), 'pack') + self.assertEqual(st.pack_info(), st.frame.pack_info()) + st.pack_forget() + self.assertEqual(st.frame.winfo_manager(), '') + + def test_scrollbar(self): + st = self.create(height=5) + st.pack() + st.insert('1.0', '\n'.join(map(str, range(100)))) + self.root.update() + # The scrollbar tracks the text view. + self.assertEqual(st.vbar.get(), st.yview()) + st.yview_moveto(1.0) + self.root.update() + self.assertEqual(st.vbar.get()[1], 1.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_simpledialog.py b/Lib/test/test_tkinter/test_simpledialog.py new file mode 100644 index 00000000000..1cb03074d89 --- /dev/null +++ b/Lib/test/test_tkinter/test_simpledialog.py @@ -0,0 +1,279 @@ +import unittest +import tkinter +from tkinter import messagebox +from test.support import requires, swap_attr +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import (AbstractDefaultRootTest, + AbstractDialogTest, AbstractTkTest) +from tkinter.simpledialog import (Dialog, SimpleDialog, + askinteger, askfloat, askstring, + _QueryInteger, _QueryFloat, _QueryString) + +requires('gui') + + +class SimpleDialogTest(AbstractTkTest, unittest.TestCase): + # The root window is not hidden here (cf. AbstractDialogTest): SimpleDialog + # makes its window transient for the master unconditionally, and a + # transient of a hidden window is never mapped on Windows, so that go() + # would block in wait_visibility(). + # SimpleDialog's modal loop is in go(); its bindings are exercised here by + # generating events on the constructed dialog, without entering the loop. + + def create(self, **kw): + kw.setdefault('text', 'Question?') + kw.setdefault('buttons', ['Yes', 'No']) + kw.setdefault('default', 0) + kw.setdefault('cancel', 1) + d = SimpleDialog(self.root, **kw) + self.addCleanup(lambda: d.root.winfo_exists() and d.root.destroy()) + return d + + def test_message(self): + # The text is shown in a message widget. + d = self.create(text='Hello?') + self.assertEqual(d.message.winfo_class(), 'Message') + self.assertEqual(str(d.message.cget('text')), 'Hello?') + + def test_class_name(self): + # class_ sets the Tk class of the dialog window. + d = self.create(class_='MyDialog') + self.assertEqual(d.root.winfo_class(), 'MyDialog') + + def test_button(self): + # Pressing a button records its index. + d = self.create(buttons=['Yes', 'No']) + d.frame.winfo_children()[1].invoke() # "No" + self.assertEqual(d.num, 1) + + def test_default_button(self): + # The default button is drawn with a raised border. + d = self.create(buttons=['Yes', 'No'], default=0) + self.assertEqual(str(d.frame.winfo_children()[0].cget('relief')), 'ridge') + + def test_return_activates_default(self): + # invokes the default button. + d = self.create() # default 0 + self.require_mapped(d.root) + d.root.update() + d.root.focus_force() + d.root.event_generate('') + d.root.update() + self.assertEqual(d.num, 0) + + def test_return_no_default(self): + # With no default button, rings the bell and leaves the dialog + # open instead of activating a button. + d = self.create(default=None) + self.require_mapped(d.root) + bells = [] + with swap_attr(d.root, 'bell', lambda *a, **k: bells.append(True)): + d.root.focus_force() + d.root.event_generate('') + d.root.update() + self.assertTrue(bells) # rang the bell + self.assertIsNone(d.num) + self.assertTrue(d.root.winfo_exists()) + + def test_wm_delete_cancels(self): + # Closing the window through the window manager records the cancel index. + d = self.create() # cancel 1 + d.wm_delete_window() + self.assertEqual(d.num, 1) + + def test_wm_delete_no_cancel(self): + # With no cancel index, closing the window through the window manager + # rings the bell and leaves the dialog open instead of recording an + # index. + d = self.create(default=None, cancel=None) + d.root.update() + bells = [] + with swap_attr(d.root, 'bell', lambda *a, **k: bells.append(True)): + d.wm_delete_window() + d.root.update() + self.assertTrue(bells) # rang the bell + self.assertIsNone(d.num) + self.assertTrue(d.root.winfo_exists()) + + def test_go(self): + # go() runs the modal loop and returns the chosen button's index. + d = self.create() + d.root.after(1, lambda: d.done(0)) + self.assertEqual(d.go(), 0) + + +class DialogTest(AbstractDialogTest, unittest.TestCase): + # Dialog is a base class for custom dialogs; exercise it via _QueryInteger. + + def open(self, **kw): + with swap_attr(Dialog, 'wait_window', staticmethod(lambda w: None)): + d = _QueryInteger('Title', 'Prompt', parent=self.root, **kw) + self.addCleanup(lambda: d.winfo_exists() and d.destroy()) + return d + + def buttons(self, d): + # Map the button box's buttons by their label. + return {str(b.cget('text')): b + for frame in d.winfo_children() + for b in frame.winfo_children() + if b.winfo_class() == 'Button'} + + def test_background(self): + # The classic dialog keeps the default Toplevel background. + d = self.open() + ref = tkinter.Toplevel(self.root) + self.addCleanup(ref.destroy) + self.assertEqual(str(d.cget('background')), str(ref.cget('background'))) + + def test_buttons(self): + # The button box has OK (the default) and Cancel buttons. + buttons = self.buttons(self.open()) + self.assertEqual(set(buttons), {'OK', 'Cancel'}) + self.assertEqual(str(buttons['OK'].cget('default')), 'active') + + def test_ok(self): + # The OK button validates the entry and stores the result. + d = self.open() + d.entry.insert(0, '42') + self.buttons(d)['OK'].invoke() + self.assertEqual(d.result, 42) + self.assertFalse(d.winfo_exists()) # The dialog closed. + + def test_cancel(self): + # The Cancel button closes the dialog without a result. + d = self.open() + self.buttons(d)['Cancel'].invoke() + self.assertIsNone(d.result) + self.assertFalse(d.winfo_exists()) + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_askinteger(self): + @staticmethod + def mock_wait_window(w): + nonlocal ismapped + ismapped = w.master.winfo_ismapped() + w.destroy() + + with swap_attr(Dialog, 'wait_window', mock_wait_window): + ismapped = None + askinteger("Go To Line", "Line number") + self.assertEqual(ismapped, False) + + root = tkinter.Tk() + ismapped = None + askinteger("Go To Line", "Line number") + self.assertEqual(ismapped, True) + root.destroy() + + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, askinteger, "Go To Line", "Line number") + + +class QueryDialogTest(AbstractDialogTest, unittest.TestCase): + # The query dialogs are modal: their __init__ blocks in wait_window(). + # Mock that out so the dialog stays alive and can be driven with generated + # events, exercising the / bindings and the validation. + + def open(self, query, **kw): + with swap_attr(Dialog, 'wait_window', staticmethod(lambda w: None)): + d = query("Title", "Prompt", parent=self.root, **kw) + self.addCleanup(lambda: d.winfo_exists() and d.destroy()) + d.focus_force() + d.update() + return d + + def enter(self, d, value, key=''): + d.entry.delete(0, 'end') + d.entry.insert(0, value) + d.event_generate(key) + d.update() + + def test_initialvalue(self): + # The entry is pre-filled with the initial value, which is accepted. + d = self.open(_QueryInteger, initialvalue=42) + self.assertEqual(d.entry.get(), '42') + d.event_generate('') + d.update() + self.assertEqual(d.result, 42) + + def test_show(self): + # _QueryString hides the entered text when show is given. + d = self.open(_QueryString, show='*') + self.assertEqual(str(d.entry.cget('show')), '*') + + def test_return_accepts(self): + for query, value, expected in [ + (_QueryInteger, '42', 42), + (_QueryFloat, '1.5', 1.5), + (_QueryString, 'spam', 'spam'), + ]: + with self.subTest(query=query.__name__): + d = self.open(query) + self.enter(d, value) + self.assertEqual(d.result, expected) + self.assertFalse(d.winfo_exists()) # The dialog closed. + + def test_escape_cancels(self): + d = self.open(_QueryString) + self.enter(d, 'spam', '') + self.assertIsNone(d.result) + self.assertFalse(d.winfo_exists()) + + def test_invalid_value(self): + warnings = [] + d = self.open(_QueryInteger) + with swap_attr(messagebox, 'showwarning', + lambda *a, **k: warnings.append(a)): + self.enter(d, 'not a number') + self.assertIsNone(d.result) + self.assertTrue(d.winfo_exists()) # The dialog stays open. + self.assertTrue(warnings) + + def test_out_of_range(self): + warnings = [] + d = self.open(_QueryInteger, minvalue=10, maxvalue=20) + with swap_attr(messagebox, 'showwarning', + lambda *a, **k: warnings.append(a)): + self.enter(d, '5') # Below the minimum. + self.assertIsNone(d.result) + self.enter(d, '25') # Above the maximum. + self.assertIsNone(d.result) + self.assertTrue(d.winfo_exists()) + self.assertEqual(len(warnings), 2) + + def test_boundary_values_accepted(self): + # The min/max checks are inclusive: a value equal to a bound passes. + d = self.open(_QueryInteger, minvalue=10, maxvalue=20) + self.enter(d, '10') # Exactly the minimum. + self.assertEqual(d.result, 10) + self.assertFalse(d.winfo_exists()) + + d = self.open(_QueryInteger, minvalue=10, maxvalue=20) + self.enter(d, '20') # Exactly the maximum. + self.assertEqual(d.result, 20) + self.assertFalse(d.winfo_exists()) + + def run_ask(self, ask, value, **kw): + # Drive a modal ask* function: enter a value and accept it. + def accept(d): + d.entry.delete(0, 'end') + d.entry.insert(0, value) + d.ok() + with swap_attr(Dialog, 'wait_window', staticmethod(accept)): + return ask('Title', 'Prompt', parent=self.root, **kw) + + def test_ask_functions(self): + self.assertEqual(self.run_ask(askinteger, '42'), 42) + self.assertEqual(self.run_ask(askfloat, '1.5'), 1.5) + self.assertEqual(self.run_ask(askstring, 'spam'), 'spam') + + def test_ask_cancelled(self): + # A cancelled ask* returns None. + with swap_attr(Dialog, 'wait_window', staticmethod(lambda d: d.cancel())): + self.assertIsNone(askstring('Title', 'Prompt', parent=self.root)) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_text.py b/Lib/test/test_tkinter/test_text.py new file mode 100644 index 00000000000..7331bbc3b21 --- /dev/null +++ b/Lib/test/test_tkinter/test_text.py @@ -0,0 +1,753 @@ +import unittest +import tkinter +from tkinter import TclError +from test.support import requires +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractTkTest, requires_tk + +requires('gui') + +class TextTest(AbstractTkTest, unittest.TestCase): + + def setUp(self): + super().setUp() + self.text = tkinter.Text(self.root) + self.text.pack() + + def test_debug(self): + text = self.text + olddebug = text.debug() + try: + text.debug(False) + self.assertIs(text.debug(), False) + text.debug(True) + self.assertIs(text.debug(), True) + finally: + text.debug(olddebug) + self.assertEqual(text.debug(), olddebug) + + def test_index(self): + text = self.text + text.insert('1.0', 'Lorem ipsum\ndolor sit amet') + self.assertEqual(text.index('1.0'), '1.0') + self.assertEqual(text.index('1.end'), '1.11') + self.assertEqual(text.index('end'), '3.0') + self.assertEqual(text.index('2.5'), '2.5') + # Index past the end of a line is clamped to its end. + self.assertEqual(text.index('1.100'), '1.11') + self.assertRaises(TclError, text.index, 'invalid') + self.assertRaises(TypeError, text.index) + self.assertRaises(TypeError, text.index, '1.0', '2.5') + + def test_compare(self): + text = self.text + text.insert('1.0', 'Lorem ipsum\ndolor sit amet') + self.assertIs(text.compare('1.0', '<', '2.0'), True) + self.assertIs(text.compare('2.0', '<', '1.0'), False) + self.assertIs(text.compare('1.5', '==', '1.5'), True) + self.assertIs(text.compare('1.5', '!=', '1.5'), False) + self.assertIs(text.compare('2.0', '>=', '2.0'), True) + self.assertIs(text.compare('1.0', '<=', 'end'), True) + self.assertRaises(TclError, text.compare, '1.0', 'invalid', '2.0') + self.assertRaises(TypeError, text.compare, '1.0', '<') + self.assertRaises(TypeError, text.compare, '1.0', '<', '2.0', '3.0') + + def test_insert_get_delete(self): + text = self.text + text.insert('1.0', 'Lorem ipsum') + self.assertEqual(text.get('1.0', 'end'), 'Lorem ipsum\n') + self.assertEqual(text.get('1.0', '1.5'), 'Lorem') + self.assertEqual(text.get('1.6'), 'i') # single character + + # insert before an existing index + text.insert('1.0', '*** ') + self.assertEqual(text.get('1.0', 'end'), '*** Lorem ipsum\n') + + text.delete('1.0', '1.4') + self.assertEqual(text.get('1.0', 'end'), 'Lorem ipsum\n') + text.delete('1.5') # delete a single character + self.assertEqual(text.get('1.0', 'end'), 'Loremipsum\n') + self.assertRaises(TypeError, text.get) + self.assertRaises(TypeError, text.get, '1.0', '1.5', 'end') + self.assertRaises(TypeError, text.delete, '1.0', '1.5', 'end') + + def test_insert_with_tags(self): + text = self.text + text.insert('1.0', 'hello', 'a', ' ', ('a', 'b'), 'world', 'b') + self.assertEqual(text.get('1.0', 'end'), 'hello world\n') + self.assertEqual([str(i) for i in text.tag_ranges('a')], + ['1.0', '1.6']) + self.assertEqual([str(i) for i in text.tag_ranges('b')], + ['1.5', '1.11']) + + def test_replace(self): + text = self.text + text.insert('1.0', 'Lorem ipsum') + text.replace('1.0', '1.5', 'Hello') + self.assertEqual(text.get('1.0', 'end'), 'Hello ipsum\n') + text.replace('1.6', 'end - 1 char', 'world') + self.assertEqual(text.get('1.0', 'end'), 'Hello world\n') + self.assertRaises(TclError, text.replace, 'invalid', '1.5', 'x') + # The first index must not be after the second. + self.assertRaises(TclError, text.replace, '1.5', '1.0', 'x') + self.assertRaises(TypeError, text.replace, '1.0', '1.5') + + def test_mark(self): + text = self.text + text.insert('1.0', 'Lorem ipsum\ndolor sit amet') + # 'insert' and 'current' marks always exist. + self.assertIn('insert', text.mark_names()) + self.assertIn('current', text.mark_names()) + + text.mark_set('here', '1.5') + self.assertIn('here', text.mark_names()) + self.assertEqual(text.index('here'), '1.5') + text.mark_set('here', '2.3') + self.assertEqual(text.index('here'), '2.3') + + text.mark_unset('here') + self.assertNotIn('here', text.mark_names()) + + # Unsetting a non-existent mark is not an error. + text.mark_unset('nonexistent') + self.assertRaises(TclError, text.mark_set, 'm', 'invalid') + self.assertRaises(TypeError, text.mark_set, 'm') + self.assertRaises(TypeError, text.mark_set, 'm', '1.0', '2.0') + + def test_mark_gravity(self): + text = self.text + text.insert('1.0', 'Lorem ipsum') + text.mark_set('here', '1.5') + # The default gravity is right. + self.assertEqual(text.mark_gravity('here'), 'right') + text.mark_gravity('here', 'left') + self.assertEqual(text.mark_gravity('here'), 'left') + # With left gravity the mark stays before inserted text. + text.insert('here', 'XXX') + self.assertEqual(text.index('here'), '1.5') + # With right gravity the mark moves after inserted text. + text.mark_gravity('here', 'right') + text.insert('here', 'YYY') + self.assertEqual(text.index('here'), '1.8') + + self.assertRaises(TclError, text.mark_gravity, 'nonexistent') + self.assertRaises(TclError, text.mark_gravity, 'here', 'invalid') + self.assertRaises(TypeError, text.mark_gravity) + self.assertRaises(TypeError, text.mark_gravity, 'here', 'left', 'extra') + + def test_mark_next_previous(self): + text = self.text + text.insert('1.0', 'Lorem ipsum') + # Keep the builtin 'insert' and 'current' marks at 1.0 so they do + # not interfere with the queries below. + text.mark_set('insert', '1.0') + text.mark_set('current', '1.0') + text.mark_set('m1', '1.3') + text.mark_set('m2', '1.7') + # mark_next finds a mark at a position at or after the index, + # mark_previous finds one at a position strictly before it. + self.assertEqual(text.mark_next('1.1'), 'm1') + self.assertEqual(text.mark_next('1.3'), 'm1') + self.assertEqual(text.mark_next('1.4'), 'm2') + self.assertIsNone(text.mark_next('1.8')) + self.assertEqual(text.mark_previous('1.4'), 'm1') + self.assertEqual(text.mark_previous('1.7'), 'm1') + self.assertEqual(text.mark_previous('end'), 'm2') + self.assertIsNone(text.mark_previous('1.0')) + + self.assertRaises(TclError, text.mark_next, 'invalid') + self.assertRaises(TclError, text.mark_previous, 'invalid') + self.assertRaises(TypeError, text.mark_next) + self.assertRaises(TypeError, text.mark_previous) + self.assertRaises(TypeError, text.mark_next, '1.0', '2.0') + self.assertRaises(TypeError, text.mark_previous, '1.0', '2.0') + + def test_tag_add_remove_ranges(self): + text = self.text + text.insert('1.0', 'Lorem ipsum\ndolor sit amet') + self.assertEqual(text.tag_ranges('sel'), ()) + + text.tag_add('big', '1.0', '1.5') + self.assertEqual([str(i) for i in text.tag_ranges('big')], + ['1.0', '1.5']) + # Add a second, disjoint range. + text.tag_add('big', '2.0', '2.5') + self.assertEqual([str(i) for i in text.tag_ranges('big')], + ['1.0', '1.5', '2.0', '2.5']) + + text.tag_remove('big', '1.0', '1.3') + self.assertEqual([str(i) for i in text.tag_ranges('big')], + ['1.3', '1.5', '2.0', '2.5']) + + # tag_ranges of an undefined tag is empty, not an error. + self.assertEqual(text.tag_ranges('nonexistent'), ()) + self.assertRaises(TclError, text.tag_add, 'big', 'invalid') + self.assertRaises(TypeError, text.tag_add, 'big') + self.assertRaises(TclError, text.tag_remove, 'big', 'invalid') + self.assertRaises(TypeError, text.tag_remove, 'big', '1.0', '2.0', '3.0') + self.assertRaises(TypeError, text.tag_ranges, 'big', 'extra') + + def test_tag_names(self): + text = self.text + text.insert('1.0', 'Lorem ipsum') + text.tag_add('a', '1.0', '1.5') + text.tag_add('b', '1.3', '1.8') + # 'sel' always exists; order reflects priority (creation order). + self.assertEqual(set(text.tag_names()), {'sel', 'a', 'b'}) + # Tags applied to the character at the given index. + self.assertEqual(set(text.tag_names('1.4')), {'a', 'b'}) + self.assertEqual(set(text.tag_names('1.0')), {'a'}) + self.assertEqual(set(text.tag_names('1.10')), set()) + self.assertRaises(TclError, text.tag_names, 'invalid') + self.assertRaises(TypeError, text.tag_names, '1.0', '2.0') + + def test_tag_nextrange_prevrange(self): + text = self.text + text.insert('1.0', 'Lorem ipsum dolor') + text.tag_add('a', '1.0', '1.5') + text.tag_add('a', '1.12', '1.17') + + self.assertEqual([str(i) for i in text.tag_nextrange('a', '1.0')], + ['1.0', '1.5']) + self.assertEqual([str(i) for i in text.tag_nextrange('a', '1.5')], + ['1.12', '1.17']) + self.assertEqual(text.tag_nextrange('a', '1.17'), ()) + + self.assertEqual([str(i) for i in text.tag_prevrange('a', 'end')], + ['1.12', '1.17']) + self.assertEqual([str(i) for i in text.tag_prevrange('a', '1.12')], + ['1.0', '1.5']) + self.assertEqual(text.tag_prevrange('a', '1.0'), ()) + + # An undefined tag has no ranges, but the index must be valid. + self.assertEqual(text.tag_nextrange('nonexistent', '1.0'), ()) + self.assertRaises(TclError, text.tag_nextrange, 'a', 'invalid') + self.assertRaises(TclError, text.tag_prevrange, 'a', 'invalid') + self.assertRaises(TypeError, text.tag_nextrange, 'a') + self.assertRaises(TypeError, text.tag_prevrange, 'a') + self.assertRaises(TypeError, text.tag_nextrange, 'a', '1.0', '2.0', '3.0') + self.assertRaises(TypeError, text.tag_prevrange, 'a', '1.0', '2.0', '3.0') + + def test_tag_delete(self): + text = self.text + text.insert('1.0', 'Lorem ipsum') + text.tag_add('a', '1.0', '1.5') + text.tag_add('b', '1.6', '1.11') + self.assertEqual(set(text.tag_names()), {'sel', 'a', 'b'}) + text.tag_delete('a', 'b') + self.assertEqual(set(text.tag_names()), {'sel'}) + self.assertEqual(text.tag_ranges('a'), ()) + + def test_tag_raise_lower(self): + text = self.text + text.tag_configure('a', foreground='red') + text.tag_configure('b', foreground='green') + text.tag_configure('c', foreground='blue') + # Creation order is lowest-to-highest priority; tag_names lists + # them in increasing priority order. + self.assertEqual(text.tag_names(), ('sel', 'a', 'b', 'c')) + text.tag_raise('a') + self.assertEqual(text.tag_names(), ('sel', 'b', 'c', 'a')) + text.tag_lower('a') + self.assertEqual(text.tag_names(), ('a', 'sel', 'b', 'c')) + text.tag_raise('a', 'b') + self.assertEqual(text.tag_names(), ('sel', 'b', 'a', 'c')) + text.tag_lower('c', 'b') + self.assertEqual(text.tag_names(), ('sel', 'c', 'b', 'a')) + + self.assertRaises(TclError, text.tag_raise, 'nonexistent') + self.assertRaises(TclError, text.tag_lower, 'nonexistent') + self.assertRaises(TclError, text.tag_raise, 'a', 'nonexistent') + self.assertRaises(TypeError, text.tag_raise) + self.assertRaises(TypeError, text.tag_raise, 'a', 'b', 'c') + self.assertRaises(TypeError, text.tag_lower, 'a', 'b', 'c') + + def test_tag_cget_configure(self): + text = self.text + text.tag_configure('a', foreground='red', underline=True) + self.assertEqual(str(text.tag_cget('a', 'foreground')), 'red') + self.assertIn(text.tag_cget('a', 'underline'), (1, '1', True)) + # tag_cget normalizes the option name (no leading hyphen needed). + self.assertEqual(str(text.tag_cget('a', '-foreground')), 'red') + # configure() query returns the full option spec. + self.assertEqual(text.tag_configure('a', 'foreground')[-1], 'red') + text.tag_configure('a', foreground='blue') + self.assertEqual(str(text.tag_cget('a', 'foreground')), 'blue') + + self.assertRaises(TclError, text.tag_cget, 'nonexistent', + 'foreground') + self.assertRaises(TypeError, text.tag_cget, 'a') + self.assertRaises(TypeError, text.tag_cget, 'a', 'foreground', 'extra') + + def test_edit_modified(self): + text = self.text + self.assertEqual(text.edit_modified(), 0) + text.insert('1.0', 'spam') + self.assertEqual(text.edit_modified(), 1) + text.edit_modified(False) + self.assertEqual(text.edit_modified(), 0) + text.edit_modified(True) + self.assertEqual(text.edit_modified(), 1) + + def test_edit_undo_redo(self): + text = self.text + text.configure(undo=True) + text.insert('1.0', 'spam') + text.edit_separator() + text.insert('end', ' eggs') + self.assertEqual(text.get('1.0', 'end'), 'spam eggs\n') + + text.edit_undo() + self.assertEqual(text.get('1.0', 'end'), 'spam\n') + text.edit_redo() + self.assertEqual(text.get('1.0', 'end'), 'spam eggs\n') + + # An empty undo stack raises. + text.edit_reset() + self.assertRaises(TclError, text.edit_undo) + + def test_dump(self): + text = self.text + text.insert('1.0', 'hello') + text.tag_add('a', '1.0', '1.3') + text.mark_set('here', '1.2') + + dump = text.dump('1.0', 'end') + self.assertIsInstance(dump, list) + for item in dump: + self.assertIsInstance(item, tuple) + self.assertEqual(len(item), 3) + kinds = {item[0] for item in dump} + self.assertIn('text', kinds) + self.assertIn('tagon', kinds) + self.assertIn('mark', kinds) + + # Filtering by kind. + text_only = text.dump('1.0', 'end', text=True) + self.assertEqual({item[0] for item in text_only}, {'text'}) + self.assertEqual(''.join(item[1] for item in text_only), 'hello\n') + + # The command callback receives each triple and suppresses the result. + collected = [] + result = text.dump('1.0', 'end', text=True, + command=lambda *a: collected.append(a)) + self.assertIsNone(result) + self.assertEqual(''.join(key_value_index[1] + for key_value_index in collected), 'hello\n') + + self.assertRaises(TclError, text.dump, 'invalid') + self.assertRaises(TypeError, text.dump) + self.assertRaises(TypeError, text.dump, '1.0', 'end', None, 'extra') + + def test_image(self): + text = self.text + image = tkinter.PhotoImage(master=self.root, width=10, height=10) + text.insert('1.0', 'AB') + name = text.image_create('1.1', image=image) + self.assertIsInstance(name, str) + self.assertIn(name, self.root.splitlist(text.image_names())) + self.assertEqual(str(text.image_cget(name, 'image')), str(image)) + + text.image_configure(name, align='top') + self.assertEqual(str(text.image_cget(name, 'align')), 'top') + + # An embedded image occupies a single index position. + self.assertEqual(text.index('end - 1 char'), '1.3') + + # Either a name or an image is required, and the index must be valid. + self.assertRaises(TclError, text.image_create, '1.0') + self.assertRaises(TclError, text.image_create, 'invalid', + image=image) + self.assertRaises(TypeError, text.image_cget, name) + self.assertRaises(TypeError, text.image_cget, name, 'image', 'extra') + + def test_window(self): + text = self.text + button = tkinter.Button(text, text='ok') + text.insert('1.0', 'AB') + text.window_create('1.1', window=button) + self.assertEqual(self.root.splitlist(text.window_names()), + (str(button),)) + self.assertEqual(text.window_cget('1.1', 'window'), str(button)) + + text.window_configure('1.1', padx=5) + self.assertEqual(text.window_cget('1.1', 'padx'), 5) + + # No embedded window at this index, and the index must be valid. + self.assertRaises(TclError, text.window_cget, '1.0', 'window') + self.assertRaises(TclError, text.window_cget, 'invalid', 'window') + self.assertRaises(TypeError, text.window_cget, '1.1') + self.assertRaises(TypeError, text.window_cget, '1.1', 'window', 'extra') + button.destroy() + + def test_tag_configure(self): + text = self.text + tag = 'a' + getint = text.tk.getint + getboolean = text.tk.getboolean + + # Color options. + for opt in ('foreground', 'background'): + text.tag_configure(tag, **{opt: '#ff0000'}) + self.assertEqual(str(text.tag_cget(tag, opt)), '#ff0000') + + # Stipple (bitmap) options. + for opt in ('bgstipple', 'fgstipple'): + text.tag_configure(tag, **{opt: 'gray50'}) + self.assertEqual(str(text.tag_cget(tag, opt)), 'gray50') + + # Enumerated options. + for opt, value in (('justify', 'center'), ('wrap', 'word'), + ('relief', 'raised'), ('tabstyle', 'wordprocessor'), + ('offset', '5')): + text.tag_configure(tag, **{opt: value}) + self.assertEqual(str(text.tag_cget(tag, 'justify')), 'center') + self.assertEqual(str(text.tag_cget(tag, 'wrap')), 'word') + self.assertEqual(str(text.tag_cget(tag, 'relief')), 'raised') + self.assertEqual(str(text.tag_cget(tag, 'tabstyle')), 'wordprocessor') + + # Boolean options. + for opt in ('underline', 'overstrike', 'elide'): + text.tag_configure(tag, **{opt: True}) + self.assertIs(getboolean(text.tag_cget(tag, opt)), True) + text.tag_configure(tag, **{opt: False}) + self.assertIs(getboolean(text.tag_cget(tag, opt)), False) + + # Screen-distance (pixel) options. + for opt in ('borderwidth', 'lmargin1', 'lmargin2', 'rmargin', + 'spacing1', 'spacing2', 'spacing3'): + text.tag_configure(tag, **{opt: 7}) + self.assertEqual(getint(text.tag_cget(tag, opt)), 7) + + # Other options. + text.tag_configure(tag, font='Helvetica 12') + self.assertEqual(str(text.tag_cget(tag, 'font')), 'Helvetica 12') + text.tag_configure(tag, tabs=(10.2, '1i')) + self.assertEqual([str(x) for x in text.tag_ranges('sel')], []) + + self.assertRaises(TclError, text.tag_cget, tag, 'spam') + + @requires_tk(8, 6, 6) + def test_tag_configure_colors(self): + # Tag color options added in Tk 8.6.6. + text = self.text + tag = 'a' + for opt in ('selectforeground', 'selectbackground', + 'lmargincolor', 'rmargincolor', + 'underlinefg', 'overstrikefg'): + text.tag_configure(tag, **{opt: '#00ff00'}) + self.assertEqual(str(text.tag_cget(tag, opt)), '#00ff00') + + def test_tag_configure_query(self): + text = self.text + tag = 'a' + # Querying all options returns a dict keyed by option name. + cnf = text.tag_configure(tag) + self.assertIsInstance(cnf, dict) + self.assertIn('foreground', cnf) + # The value is the full 5-tuple option specification. + self.assertEqual(len(cnf['foreground']), 5) + + # Querying a single option returns its specification. + spec = text.tag_configure(tag, 'foreground') + self.assertEqual(spec[0], 'foreground') + self.assertEqual(spec[-1], '') # unset by default + + # Setting via keyword arguments and via a dict are equivalent. + text.tag_configure(tag, foreground='red') + self.assertEqual(str(text.tag_configure(tag, 'foreground')[-1]), 'red') + text.tag_configure(tag, {'foreground': 'blue'}) + self.assertEqual(str(text.tag_cget(tag, 'foreground')), 'blue') + + # tag_config is an alias of tag_configure. + self.assertEqual(text.tag_config, text.tag_configure) + + def test_image_configure(self): + text = self.text + image = tkinter.PhotoImage(master=self.root, width=10, height=10) + text.insert('1.0', 'AB') + name = text.image_create('1.1', image=image, name='img') + self.assertEqual(name, 'img') + + self.assertEqual(str(text.image_cget(name, 'name')), 'img') + self.assertEqual(str(text.image_cget(name, 'image')), str(image)) + for value in ('top', 'center', 'bottom', 'baseline'): + text.image_configure(name, align=value) + self.assertEqual(str(text.image_cget(name, 'align')), value) + text.image_configure(name, padx=3, pady=4) + self.assertEqual(text.tk.getint(text.image_cget(name, 'padx')), 3) + self.assertEqual(text.tk.getint(text.image_cget(name, 'pady')), 4) + + # Querying returns the full option set. + cnf = text.image_configure(name) + self.assertIsInstance(cnf, dict) + self.assertIn('align', cnf) + self.assertRaises(TclError, text.image_cget, name, 'spam') + + def test_window_configure(self): + text = self.text + button = tkinter.Button(text, text='ok') + text.insert('1.0', 'AB') + text.window_create('1.1', window=button) + + self.assertEqual(text.window_cget('1.1', 'window'), str(button)) + for value in ('top', 'center', 'bottom', 'baseline'): + text.window_configure('1.1', align=value) + self.assertEqual(str(text.window_cget('1.1', 'align')), value) + text.window_configure('1.1', padx=3, pady=4) + self.assertEqual(text.tk.getint(text.window_cget('1.1', 'padx')), 3) + self.assertEqual(text.tk.getint(text.window_cget('1.1', 'pady')), 4) + text.window_configure('1.1', stretch=True) + self.assertIs(text.tk.getboolean(text.window_cget('1.1', 'stretch')), + True) + + cnf = text.window_configure('1.1') + self.assertIsInstance(cnf, dict) + self.assertIn('stretch', cnf) + self.assertRaises(TclError, text.window_cget, '1.1', 'spam') + self.assertEqual(text.window_config, text.window_configure) + button.destroy() + + def test_peer(self): + text = self.text + text.insert('1.0', 'Lorem ipsum') + self.assertEqual(text.peer_names(), ()) + + text.peer_create('.peer1') + names = self.root.splitlist(text.tk.call('winfo', 'children', '.')) + self.assertIn('.peer1', [str(n) for n in names]) + self.assertEqual([str(p) for p in text.peer_names()], ['.peer1']) + # Peers share content. + self.assertEqual(text.tk.call('.peer1', 'get', '1.0', 'end'), + 'Lorem ipsum\n') + text.tk.call('destroy', '.peer1') + + def test_bbox(self): + text = self.text + text.insert('1.0', 'hello') + text.update() + bbox = text.bbox('1.0') + self.assertIsInstance(bbox, tuple) + self.assertEqual(len(bbox), 4) + for v in bbox: + self.assertIsInstance(v, int) + # A character that is not displayed has no bounding box. + self.assertIsNone(text.bbox('end')) + self.assertRaises(TclError, text.bbox, 'invalid') + self.assertRaises(TypeError, text.bbox) + self.assertRaises(TypeError, text.bbox, '1.0', '2.0') + + def test_dlineinfo(self): + text = self.text + text.insert('1.0', 'hello\nworld') + text.update() + info = text.dlineinfo('1.0') + self.assertIsInstance(info, tuple) + self.assertEqual(len(info), 5) + for v in info: + self.assertIsInstance(v, int) + self.assertRaises(TclError, text.dlineinfo, 'invalid') + self.assertRaises(TypeError, text.dlineinfo) + self.assertRaises(TypeError, text.dlineinfo, '1.0', '2.0') + + def test_see(self): + text = self.text + text.insert('1.0', '\n'.join('line %d' % i for i in range(200))) + text.update() + # Initially the last line is not visible. + self.assertIsNone(text.bbox('200.0')) + text.see('200.0') + text.update() + self.assertIsNotNone(text.bbox('200.0')) + self.assertRaises(TclError, text.see, 'invalid') + self.assertRaises(TypeError, text.see) + self.assertRaises(TypeError, text.see, '1.0', '2.0') + + # yview_pickplace is a deprecated way to make an index visible. + text.yview_pickplace('1.0') + text.update() + self.assertIsNotNone(text.bbox('1.0')) + + def test_search(self): + text = self.text + + # pattern and index are obligatory arguments. + self.assertRaises(TclError, text.search, None, '1.0') + self.assertRaises(TclError, text.search, 'a', None) + self.assertRaises(TclError, text.search, None, None) + + # Invalid text index. + self.assertRaises(TclError, text.search, '', 0) + self.assertRaises(TclError, text.search, '', '') + self.assertRaises(TclError, text.search, '', 'invalid') + self.assertRaises(TclError, text.search, '', '1.0', 0) + self.assertRaises(TclError, text.search, '', '1.0', '') + self.assertRaises(TclError, text.search, '', '1.0', 'invalid') + + text.insert('1.0', + 'This is a test. This is only a test.\n' + 'Another line.\n' + 'Yet another line.\n' + '64-bit') + + self.assertEqual(text.search('test', '1.0'), '1.10') + self.assertEqual(text.search('test', '1.0', 'end'), '1.10') + self.assertEqual(text.search('test', '1.0', '1.10'), '') + self.assertEqual(text.search('test', '1.11'), '1.31') + self.assertEqual(text.search('test', '1.32', 'end'), '') + self.assertEqual(text.search('test', '1.32'), '1.10') + + self.assertEqual(text.search('', '1.0'), '1.0') # empty pattern + self.assertEqual(text.search('nonexistent', '1.0'), '') + self.assertEqual(text.search('-bit', '1.0'), '4.2') # starts with a hyphen + + self.assertEqual(text.search('line', '3.0'), '3.12') + self.assertEqual(text.search('line', '3.0', forwards=True), '3.12') + self.assertEqual(text.search('line', '3.0', backwards=True), '2.8') + self.assertEqual(text.search('line', '3.0', forwards=True, backwards=True), '2.8') + + self.assertEqual(text.search('t.', '1.0'), '1.13') + self.assertEqual(text.search('t.', '1.0', exact=True), '1.13') + self.assertEqual(text.search('t.', '1.0', regexp=True), '1.10') + self.assertEqual(text.search('t.', '1.0', exact=True, regexp=True), '1.10') + + self.assertEqual(text.search('TEST', '1.0'), '') + self.assertEqual(text.search('TEST', '1.0', nocase=True), '1.10') + + self.assertEqual(text.search('.*line', '1.0', regexp=True), '2.0') + self.assertEqual(text.search('.*line', '1.0', regexp=True, nolinestop=True), '1.0') + + self.assertEqual(text.search('test', '1.0', '1.13'), '1.10') + self.assertEqual(text.search('test', '1.0', '1.13', strictlimits=True), '') + self.assertEqual(text.search('test', '1.0', '1.14', strictlimits=True), '1.10') + + var = tkinter.Variable(self.root) + self.assertEqual(text.search('test', '1.0', count=var), '1.10') + self.assertEqual(var.get(), 4 if self.wantobjects else '4') + + # TODO: Add test for elide=True + + def test_search_all(self): + text = self.text + + # pattern and index are obligatory arguments. + self.assertRaises(TclError, text.search_all, None, '1.0') + self.assertRaises(TclError, text.search_all, 'a', None) + self.assertRaises(TclError, text.search_all, None, None) + + # Keyword-only arguments + self.assertRaises(TypeError, text.search_all, 'a', '1.0', 'end', None) + + # Invalid text index. + self.assertRaises(TclError, text.search_all, '', 0) + self.assertRaises(TclError, text.search_all, '', '') + self.assertRaises(TclError, text.search_all, '', 'invalid') + self.assertRaises(TclError, text.search_all, '', '1.0', 0) + self.assertRaises(TclError, text.search_all, '', '1.0', '') + self.assertRaises(TclError, text.search_all, '', '1.0', 'invalid') + + def eq(res, expected): + self.assertIsInstance(res, tuple) + self.assertEqual([str(i) for i in res], expected) + + text.insert('1.0', 'ababa\naba\n64-bit') + + eq(text.search_all('aba', '1.0'), ['1.0', '2.0']) + eq(text.search_all('aba', '1.0', 'end'), ['1.0', '2.0']) + eq(text.search_all('aba', '1.1', 'end'), ['1.2', '2.0']) + eq(text.search_all('aba', '1.1'), ['1.2', '2.0', '1.0']) + + res = text.search_all('', '1.0') # empty pattern + eq(res[:5], ['1.0', '1.1', '1.2', '1.3', '1.4']) + eq(res[-5:], ['3.2', '3.3', '3.4', '3.5', '3.6']) + eq(text.search_all('nonexistent', '1.0'), []) + eq(text.search_all('-bit', '1.0'), ['3.2']) # starts with a hyphen + + eq(text.search_all('aba', '1.0', 'end', forwards=True), ['1.0', '2.0']) + eq(text.search_all('aba', 'end', '1.0', backwards=True), ['2.0', '1.2']) + + eq(text.search_all('aba', '1.0', overlap=True), ['1.0', '1.2', '2.0']) + eq(text.search_all('aba', 'end', '1.0', overlap=True, backwards=True), ['2.0', '1.2', '1.0']) + + eq(text.search_all('aba', '1.0', exact=True), ['1.0', '2.0']) + eq(text.search_all('a.a', '1.0', exact=True), []) + eq(text.search_all('a.a', '1.0', regexp=True), ['1.0', '2.0']) + + eq(text.search_all('ABA', '1.0'), []) + eq(text.search_all('ABA', '1.0', nocase=True), ['1.0', '2.0']) + + eq(text.search_all('a.a', '1.0', regexp=True), ['1.0', '2.0']) + eq(text.search_all('a.a', '1.0', regexp=True, nolinestop=True), ['1.0', '1.4']) + + eq(text.search_all('aba', '1.0', '2.2'), ['1.0', '2.0']) + eq(text.search_all('aba', '1.0', '2.2', strictlimits=True), ['1.0']) + eq(text.search_all('aba', '1.0', '2.3', strictlimits=True), ['1.0', '2.0']) + + var = tkinter.Variable(self.root) + eq(text.search_all('aba', '1.0', count=var), ['1.0', '2.0']) + self.assertEqual(var.get(), (3, 3) if self.wantobjects else '3 3') + + # TODO: Add test for elide=True + + def test_count(self): + text = self.text + text.insert('1.0', + 'Lorem ipsum dolor sit amet,\n' + 'consectetur adipiscing elit,\n' + 'sed do eiusmod tempor incididunt\n' + 'ut labore et dolore magna aliqua.') + + options = ('chars', 'indices', 'lines', + 'displaychars', 'displayindices', 'displaylines', + 'xpixels', 'ypixels') + self.assertEqual(len(text.count('1.0', 'end', *options, return_ints=True)), 8) + self.assertEqual(len(text.count('1.0', 'end', *options)), 8) + self.assertEqual(text.count('1.0', 'end', 'chars', 'lines', return_ints=True), + (124, 4)) + self.assertEqual(text.count('1.3', '4.5', 'chars', 'lines'), (92, 3)) + self.assertEqual(text.count('4.5', '1.3', 'chars', 'lines', return_ints=True), + (-92, -3)) + self.assertEqual(text.count('4.5', '1.3', 'chars', 'lines'), (-92, -3)) + self.assertEqual(text.count('1.3', '1.3', 'chars', 'lines', return_ints=True), + (0, 0)) + self.assertEqual(text.count('1.3', '1.3', 'chars', 'lines'), (0, 0)) + self.assertEqual(text.count('1.0', 'end', 'lines', return_ints=True), 4) + self.assertEqual(text.count('1.0', 'end', 'lines'), (4,)) + self.assertEqual(text.count('end', '1.0', 'lines', return_ints=True), -4) + self.assertEqual(text.count('end', '1.0', 'lines'), (-4,)) + self.assertEqual(text.count('1.3', '1.5', 'lines', return_ints=True), 0) + self.assertEqual(text.count('1.3', '1.5', 'lines'), None) + self.assertEqual(text.count('1.3', '1.3', 'lines', return_ints=True), 0) + self.assertEqual(text.count('1.3', '1.3', 'lines'), None) + # Count 'indices' by default. + self.assertEqual(text.count('1.0', 'end', return_ints=True), 124) + self.assertEqual(text.count('1.0', 'end'), (124,)) + self.assertEqual(text.count('1.0', 'end', 'indices', return_ints=True), 124) + self.assertEqual(text.count('1.0', 'end', 'indices'), (124,)) + self.assertRaises(TclError, text.count, '1.0', 'end', 'spam') + self.assertRaises(TclError, text.count, '1.0', 'end', '-lines') + + # The ypixels counts depend on the widget geometry. + text.update() + + # Indices on the same display line have zero vertical distance. + self.assertEqual(text.count('1.3', '1.5', 'ypixels', return_ints=True), 0) + self.assertIsNone(text.count('1.3', '1.5', 'ypixels')) + self.assertIsInstance(text.count('1.3', '2.5', 'ypixels', return_ints=True), int) + self.assertIsInstance(text.count('1.3', '2.5', 'ypixels'), tuple) + self.assertIsInstance(text.count('1.3', '2.5', 'update', 'ypixels', return_ints=True), int) + self.assertIsInstance(text.count('1.3', '2.5', 'update', 'ypixels'), int) + self.assertEqual(text.count('1.3', '1.3', 'update', 'ypixels', return_ints=True), 0) + self.assertEqual(text.count('1.3', '1.3', 'update', 'ypixels'), None) + self.assertEqual(text.count('1.3', '1.5', 'update', 'indices', return_ints=True), 2) + self.assertEqual(text.count('1.3', '1.5', 'update', 'indices'), 2) + self.assertEqual(text.count('1.3', '1.3', 'update', 'indices', return_ints=True), 0) + self.assertEqual(text.count('1.3', '1.3', 'update', 'indices'), None) + self.assertEqual(text.count('1.3', '1.5', 'update', return_ints=True), 2) + self.assertEqual(text.count('1.3', '1.5', 'update'), (2,)) + self.assertEqual(text.count('1.3', '1.3', 'update', return_ints=True), 0) + self.assertEqual(text.count('1.3', '1.3', 'update'), None) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_tkinter_pipe.py b/Lib/test/test_tkinter/test_tkinter_pipe.py new file mode 100644 index 00000000000..775d0ff5e19 --- /dev/null +++ b/Lib/test/test_tkinter/test_tkinter_pipe.py @@ -0,0 +1,55 @@ +# test_tkinter_pipe.py +import unittest +import subprocess +import sys +from test import support + + +@unittest.skipUnless(support.has_subprocess_support, "test requires subprocess") +class TkinterPipeTest(unittest.TestCase): + + def test_tkinter_pipe_buffered(self): + args = [sys.executable, "-i"] + proc = subprocess.Popen(args, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + proc.stdin.write(b"import tkinter\n") + proc.stdin.write(b"interpreter = tkinter.Tcl()\n") + proc.stdin.write(b"print('hello')\n") + proc.stdin.write(b"print('goodbye')\n") + proc.stdin.write(b"quit()\n") + stdout, stderr = proc.communicate(timeout=support.SHORT_TIMEOUT) + stdout = stdout.decode() + self.assertEqual(stdout.split(), ['hello', 'goodbye']) + + def test_tkinter_pipe_unbuffered(self): + args = [sys.executable, "-i", "-u"] + proc = subprocess.Popen(args, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + proc.stdin.write(b"import tkinter\n") + proc.stdin.write(b"interpreter = tkinter.Tcl()\n") + + proc.stdin.write(b"print('hello')\n") + proc.stdin.flush() + stdout = proc.stdout.readline() + stdout = stdout.decode() + self.assertEqual(stdout.strip(), 'hello') + + proc.stdin.write(b"print('hello again')\n") + proc.stdin.flush() + stdout = proc.stdout.readline() + stdout = stdout.decode() + self.assertEqual(stdout.strip(), 'hello again') + + proc.stdin.write(b"print('goodbye')\n") + proc.stdin.write(b"quit()\n") + stdout, stderr = proc.communicate(timeout=support.SHORT_TIMEOUT) + stdout = stdout.decode() + self.assertEqual(stdout.strip(), 'goodbye') + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_variables.py b/Lib/test/test_tkinter/test_variables.py new file mode 100644 index 00000000000..5ee4e9467dd --- /dev/null +++ b/Lib/test/test_tkinter/test_variables.py @@ -0,0 +1,363 @@ +import unittest +from test import support + +import gc +import tkinter +from tkinter import (Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl, + TclError) +from test.support import ALWAYS_EQ +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractDefaultRootTest, tcl_version + + +class Var(Variable): + + _default = "default" + side_effect = False + + def set(self, value): + self.side_effect = True + super().set(value) + + +class TestBase(unittest.TestCase): + + def setUp(self): + self.root = Tcl() + + def tearDown(self): + del self.root + + +class TestVariable(TestBase): + + def info_exists(self, *args): + return self.root.getboolean(self.root.call("info", "exists", *args)) + + def test_default(self): + v = Variable(self.root) + self.assertEqual("", v.get()) + self.assertRegex(str(v), r"^PY_VAR(\d+)$") + + def test_name_and_value(self): + v = Variable(self.root, "sample string", "varname") + self.assertEqual("sample string", v.get()) + self.assertEqual("varname", str(v)) + + def test___del__(self): + self.assertFalse(self.info_exists("varname")) + v = Variable(self.root, "sample string", "varname") + self.assertTrue(self.info_exists("varname")) + del v + support.gc_collect() # For PyPy or other GCs. + self.assertFalse(self.info_exists("varname")) + + def test_dont_unset_not_existing(self): + self.assertFalse(self.info_exists("varname")) + v1 = Variable(self.root, name="name") + v2 = Variable(self.root, name="name") + del v1 + support.gc_collect() # For PyPy or other GCs. + self.assertFalse(self.info_exists("name")) + # shouldn't raise exception + del v2 + support.gc_collect() # For PyPy or other GCs. + self.assertFalse(self.info_exists("name")) + + def test_equality(self): + # values doesn't matter, only class and name are checked + v1 = Variable(self.root, name="abc") + v2 = Variable(self.root, name="abc") + self.assertIsNot(v1, v2) + self.assertEqual(v1, v2) + + v3 = Variable(self.root, name="cba") + self.assertNotEqual(v1, v3) + + v4 = StringVar(self.root, name="abc") + self.assertEqual(str(v1), str(v4)) + self.assertNotEqual(v1, v4) + + V = type('Variable', (), {}) + self.assertNotEqual(v1, V()) + + self.assertNotEqual(v1, object()) + self.assertEqual(v1, ALWAYS_EQ) + + root2 = tkinter.Tk() + self.addCleanup(root2.destroy) + v5 = Variable(root2, name="abc") + self.assertEqual(str(v1), str(v5)) + self.assertNotEqual(v1, v5) + + def test_invalid_name(self): + with self.assertRaises(TypeError): + Variable(self.root, name=123) + + def test_null_in_name(self): + with self.assertRaises(ValueError): + Variable(self.root, name='var\x00name') + with self.assertRaises(ValueError): + self.root.globalsetvar('var\x00name', "value") + with self.assertRaises(ValueError): + self.root.globalsetvar(b'var\x00name', "value") + with self.assertRaises(ValueError): + self.root.setvar('var\x00name', "value") + with self.assertRaises(ValueError): + self.root.setvar(b'var\x00name', "value") + + def test_initialize(self): + v = Var(self.root) + self.assertFalse(v.side_effect) + v.set("value") + self.assertTrue(v.side_effect) + self.assertEqual(Variable.initialize, Variable.set) + + def test_trace_old(self): + if tcl_version >= (9, 0): + self.skipTest('requires Tcl version < 9.0') + # Old interface + v = Variable(self.root) + vname = str(v) + self.assertEqual(v.trace, v.trace_variable) + trace = [] + def read_tracer(*args): + trace.append(('read',) + args) + def write_tracer(*args): + trace.append(('write',) + args) + with self.assertWarns(DeprecationWarning) as cm: + cb1 = v.trace_variable('r', read_tracer) + self.assertEqual(cm.filename, __file__) + with self.assertWarns(DeprecationWarning): + cb2 = v.trace_variable('wu', write_tracer) + with self.assertWarns(DeprecationWarning) as cm: + self.assertEqual(sorted(v.trace_vinfo()), [('r', cb1), ('wu', cb2)]) + self.assertEqual(cm.filename, __file__) + self.assertEqual(trace, []) + + v.set('spam') + self.assertEqual(trace, [('write', vname, '', 'w')]) + + trace = [] + v.get() + self.assertEqual(trace, [('read', vname, '', 'r')]) + + trace = [] + with self.assertWarns(DeprecationWarning): + info = sorted(v.trace_vinfo()) + with self.assertWarns(DeprecationWarning): + v.trace_vdelete('w', cb1) # Wrong mode + with self.assertWarns(DeprecationWarning): + self.assertEqual(sorted(v.trace_vinfo()), info) + with self.assertRaises(TclError): + with self.assertWarns(DeprecationWarning): + v.trace_vdelete('r', 'spam') # Wrong command name + with self.assertWarns(DeprecationWarning): + self.assertEqual(sorted(v.trace_vinfo()), info) + with self.assertWarns(DeprecationWarning): + v.trace_vdelete('r', (cb1, 43)) # Wrong arguments + with self.assertWarns(DeprecationWarning): + self.assertEqual(sorted(v.trace_vinfo()), info) + v.get() + self.assertEqual(trace, [('read', vname, '', 'r')]) + + trace = [] + with self.assertWarns(DeprecationWarning) as cm: + v.trace_vdelete('r', cb1) + self.assertEqual(cm.filename, __file__) + with self.assertWarns(DeprecationWarning): + self.assertEqual(v.trace_vinfo(), [('wu', cb2)]) + v.get() + self.assertEqual(trace, []) + + trace = [] + del write_tracer + gc.collect() + v.set('eggs') + self.assertEqual(trace, [('write', vname, '', 'w')]) + + trace = [] + del v + gc.collect() + self.assertEqual(trace, [('write', vname, '', 'u')]) + + def test_trace(self): + v = Variable(self.root) + vname = str(v) + trace = [] + def read_tracer(*args): + trace.append(('read',) + args) + def write_tracer(*args): + trace.append(('write',) + args) + tr1 = v.trace_add('read', read_tracer) + tr2 = v.trace_add(['write', 'unset'], write_tracer) + self.assertEqual(sorted(v.trace_info()), [ + (('read',), tr1), + (('write', 'unset'), tr2)]) + self.assertEqual(trace, []) + + v.set('spam') + self.assertEqual(trace, [('write', vname, '', 'write')]) + + trace = [] + v.get() + self.assertEqual(trace, [('read', vname, '', 'read')]) + + trace = [] + info = sorted(v.trace_info()) + v.trace_remove('write', tr1) # Wrong mode + self.assertEqual(sorted(v.trace_info()), info) + with self.assertRaises(TclError): + v.trace_remove('read', 'spam') # Wrong command name + self.assertEqual(sorted(v.trace_info()), info) + v.get() + self.assertEqual(trace, [('read', vname, '', 'read')]) + + trace = [] + v.trace_remove('read', tr1) + self.assertEqual(v.trace_info(), [(('write', 'unset'), tr2)]) + v.get() + self.assertEqual(trace, []) + + trace = [] + del write_tracer + gc.collect() + v.set('eggs') + self.assertEqual(trace, [('write', vname, '', 'write')]) + + trace = [] + del v + gc.collect() + self.assertEqual(trace, [('write', vname, '', 'unset')]) + + +class TestStringVar(TestBase): + + def test_default(self): + v = StringVar(self.root) + self.assertEqual("", v.get()) + + def test_get(self): + v = StringVar(self.root, "abc", "name") + self.assertEqual("abc", v.get()) + self.root.globalsetvar("name", "value") + self.assertEqual("value", v.get()) + + def test_get_null(self): + v = StringVar(self.root, "abc\x00def", "name") + self.assertEqual("abc\x00def", v.get()) + self.root.globalsetvar("name", "val\x00ue") + self.assertEqual("val\x00ue", v.get()) + + +class TestIntVar(TestBase): + + def test_default(self): + v = IntVar(self.root) + self.assertEqual(0, v.get()) + + def test_get(self): + v = IntVar(self.root, 123, "name") + self.assertEqual(123, v.get()) + self.root.globalsetvar("name", "345") + self.assertEqual(345, v.get()) + self.root.globalsetvar("name", "876.5") + self.assertEqual(876, v.get()) + + def test_invalid_value(self): + v = IntVar(self.root, name="name") + self.root.globalsetvar("name", "value") + with self.assertRaises((ValueError, TclError)): + v.get() + + +class TestDoubleVar(TestBase): + + def test_default(self): + v = DoubleVar(self.root) + self.assertEqual(0.0, v.get()) + + def test_get(self): + v = DoubleVar(self.root, 1.23, "name") + self.assertAlmostEqual(1.23, v.get()) + self.root.globalsetvar("name", "3.45") + self.assertAlmostEqual(3.45, v.get()) + + def test_get_from_int(self): + v = DoubleVar(self.root, 1.23, "name") + self.assertAlmostEqual(1.23, v.get()) + self.root.globalsetvar("name", "3.45") + self.assertAlmostEqual(3.45, v.get()) + self.root.globalsetvar("name", "456") + self.assertAlmostEqual(456, v.get()) + + def test_invalid_value(self): + v = DoubleVar(self.root, name="name") + self.root.globalsetvar("name", "value") + with self.assertRaises((ValueError, TclError)): + v.get() + + +class TestBooleanVar(TestBase): + + def test_default(self): + v = BooleanVar(self.root) + self.assertIs(v.get(), False) + + def test_get(self): + v = BooleanVar(self.root, True, "name") + self.assertIs(v.get(), True) + self.root.globalsetvar("name", "0") + self.assertIs(v.get(), False) + self.root.globalsetvar("name", 42 if self.root.wantobjects() else 1) + self.assertIs(v.get(), True) + self.root.globalsetvar("name", 0) + self.assertIs(v.get(), False) + self.root.globalsetvar("name", "on") + self.assertIs(v.get(), True) + + def test_set(self): + true = 1 if self.root.wantobjects() else "1" + false = 0 if self.root.wantobjects() else "0" + v = BooleanVar(self.root, name="name") + v.set(True) + self.assertEqual(self.root.globalgetvar("name"), true) + v.set("0") + self.assertEqual(self.root.globalgetvar("name"), false) + v.set(42) + self.assertEqual(self.root.globalgetvar("name"), true) + v.set(0) + self.assertEqual(self.root.globalgetvar("name"), false) + v.set("on") + self.assertEqual(self.root.globalgetvar("name"), true) + self.assertEqual(BooleanVar.initialize, BooleanVar.set) + + def test_invalid_value_domain(self): + false = 0 if self.root.wantobjects() else "0" + v = BooleanVar(self.root, name="name") + with self.assertRaises(TclError): + v.set("value") + self.assertEqual(self.root.globalgetvar("name"), false) + self.root.globalsetvar("name", "value") + with self.assertRaises(ValueError): + v.get() + self.root.globalsetvar("name", "1.0") + with self.assertRaises(ValueError): + v.get() + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_variable(self): + self.assertRaises(RuntimeError, Variable) + root = tkinter.Tk() + v = Variable() + v.set("value") + self.assertEqual(v.get(), "value") + root.destroy() + tkinter.NoDefaultRoot() + self.assertRaises(RuntimeError, Variable) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_tkinter/test_widgets.py b/Lib/test/test_tkinter/test_widgets.py new file mode 100644 index 00000000000..14c06ee913d --- /dev/null +++ b/Lib/test/test_tkinter/test_widgets.py @@ -0,0 +1,2644 @@ +import unittest +import tkinter +from tkinter import TclError +import os +from test.support import requires + +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import (requires_tk, tk_version, + get_tk_patchlevel, widget_eq, + wait_until_mapped, + AbstractDefaultRootTest) + +from test.test_tkinter.widget_tests import ( + add_configure_tests, + AbstractWidgetTest, + StandardOptionsTests, + IntegerSizeTests, + PixelSizeTests) + +requires('gui') + + +EXPECTED_SCREEN_DISTANCE_ERRMSG = '(bad|expected) screen distance (but got )?"{}"' +EXPECTED_SCREEN_DISTANCE_OR_EMPTY_ERRMSG = '(bad|expected) screen distance (or "" but got )?"{}"' + +def float_round(x): + return float(round(x)) + +class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests): + _no_round = {'padx', 'pady'} + if tk_version < (8, 7): + _clipped = {'highlightthickness'} + else: + _clipped = {'borderwidth', 'height', 'highlightthickness', 'padx', + 'pady', 'width'} + + def test_configure_class(self): + widget = self.create() + self.assertEqual(widget['class'], + widget.__class__.__name__.title()) + self.checkInvalidParam(widget, 'class', 'Foo', + errmsg="can't modify -class option after widget is created") + widget2 = self.create(class_='Foo') + self.assertEqual(widget2['class'], 'Foo') + + def test_configure_colormap(self): + widget = self.create() + self.assertEqual(widget['colormap'], '') + self.checkInvalidParam(widget, 'colormap', 'new', + errmsg="can't modify -colormap option after widget is created") + widget2 = self.create(colormap='new') + self.assertEqual(widget2['colormap'], 'new') + + def test_configure_container(self): + widget = self.create() + self.assertEqual(widget['container'], 0 if self.wantobjects else '0') + self.checkInvalidParam(widget, 'container', 1, + errmsg="can't modify -container option after widget is created") + widget2 = self.create(container=True) + self.assertEqual(widget2['container'], 1 if self.wantobjects else '1') + + def test_configure_visual(self): + widget = self.create() + self.assertEqual(widget['visual'], '') + self.checkInvalidParam(widget, 'visual', 'default', + errmsg="can't modify -visual option after widget is created") + widget2 = self.create(visual='default') + self.assertEqual(widget2['visual'], 'default') + + +@add_configure_tests(StandardOptionsTests) +class ToplevelTest(AbstractToplevelTest, unittest.TestCase): + OPTIONS = ( + 'background', 'backgroundimage', 'borderwidth', + 'class', 'colormap', 'container', 'cursor', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'menu', 'padx', 'pady', 'relief', 'screen', + 'takefocus', 'tile', 'use', 'visual', 'width', + ) + + def create(self, **kwargs): + return tkinter.Toplevel(self.root, **kwargs) + + def test_configure_menu(self): + widget = self.create() + menu = tkinter.Menu(self.root) + self.checkParam(widget, 'menu', menu, eq=widget_eq) + self.checkParam(widget, 'menu', '') + + def test_configure_screen(self): + widget = self.create() + if widget._windowingsystem != 'x11': + self.skipTest('Not using Tk for X11') + self.assertEqual(widget['screen'], '') + try: + display = os.environ['DISPLAY'] + except KeyError: + self.skipTest('No $DISPLAY set.') + self.checkInvalidParam(widget, 'screen', display, + errmsg="can't modify -screen option after widget is created") + widget2 = self.create(screen=display) + self.assertEqual(widget2['screen'], display) + + def test_configure_use(self): + widget = self.create() + self.assertEqual(widget['use'], '') + parent = self.create(container=True) + wid = hex(parent.winfo_id()) + with self.subTest(wid=wid): + widget2 = self.create(use=wid) + self.assertEqual(widget2['use'], wid) + + +@add_configure_tests(StandardOptionsTests) +class FrameTest(AbstractToplevelTest, unittest.TestCase): + OPTIONS = ( + 'background', 'backgroundimage', 'borderwidth', + 'class', 'colormap', 'container', 'cursor', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'padx', 'pady', 'relief', 'takefocus', 'tile', 'visual', 'width', + ) + + def create(self, **kwargs): + return tkinter.Frame(self.root, **kwargs) + + +@add_configure_tests(StandardOptionsTests) +class LabelFrameTest(AbstractToplevelTest, unittest.TestCase): + OPTIONS = ( + 'background', 'borderwidth', + 'class', 'colormap', 'container', 'cursor', + 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'labelanchor', 'labelwidget', 'padx', 'pady', 'relief', + 'takefocus', 'text', 'visual', 'width', + ) + + def create(self, **kwargs): + return tkinter.LabelFrame(self.root, **kwargs) + + def test_configure_labelanchor(self): + widget = self.create() + self.checkEnumParam(widget, 'labelanchor', + 'e', 'en', 'es', 'n', 'ne', 'nw', + 's', 'se', 'sw', 'w', 'wn', 'ws') + self.checkInvalidParam(widget, 'labelanchor', 'center') + + def test_configure_labelwidget(self): + widget = self.create() + label = tkinter.Label(self.root, text='Mupp', name='foo') + self.checkParam(widget, 'labelwidget', label, expected='.foo') + label.destroy() + +# Label, Button, Checkbutton, Radiobutton, MenuButton +class AbstractLabelTest(AbstractWidgetTest, IntegerSizeTests): + _rounds_pixels = False + if tk_version < (8, 7): + _clipped = {} + elif tk_version < (9, 0): + _clipped = {'borderwidth', 'height', 'highlightthickness', 'padx', 'pady', 'width'} + else: + _clipped = {'borderwidth', 'height', 'highlightthickness', + 'insertborderwidth', 'padx', 'pady', 'width'} + + def setUp(self): + super().setUp() + if tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 2): + self._clipped = self._clipped - {'height', 'width'} + + +@add_configure_tests(StandardOptionsTests) +class LabelTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'activeforeground', 'anchor', + 'background', 'bitmap', 'borderwidth', 'compound', 'cursor', + 'disabledforeground', 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'image', 'justify', 'padx', 'pady', 'relief', 'state', + 'takefocus', 'text', 'textvariable', + 'underline', 'width', 'wraplength', + ) + + def create(self, **kwargs): + return tkinter.Label(self.root, **kwargs) + + +@add_configure_tests(StandardOptionsTests) +class ButtonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'activeforeground', 'anchor', + 'background', 'bitmap', 'borderwidth', + 'command', 'compound', 'cursor', 'default', + 'disabledforeground', 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'image', 'justify', 'overrelief', 'padx', 'pady', 'relief', + 'repeatdelay', 'repeatinterval', + 'state', 'takefocus', 'text', 'textvariable', + 'underline', 'width', 'wraplength') + if tk_version < (8, 7): + _clipped = {} + else: + _clipped = {'borderwidth', 'height', 'highlightthickness', + 'padx', 'pady', 'width'} + + def create(self, **kwargs): + return tkinter.Button(self.root, **kwargs) + + def test_configure_default(self): + widget = self.create() + self.checkEnumParam(widget, 'default', 'active', 'disabled', 'normal') + + def test_invoke(self): + success = [] + widget = self.create(command=lambda: success.append(1)) + widget.pack() + widget.invoke() + self.assertEqual(success, [1]) + # invoke does nothing for a disabled button. + widget.configure(state='disabled') + widget.invoke() + self.assertEqual(success, [1]) + + def test_flash(self): + widget = self.create() + widget.pack() + widget.update_idletasks() + widget.flash() # No exception. + + +@add_configure_tests(StandardOptionsTests) +class CheckbuttonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'activeforeground', 'anchor', + 'background', 'bitmap', 'borderwidth', + 'command', 'compound', 'cursor', + 'disabledforeground', 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'image', 'indicatoron', 'justify', + 'offrelief', 'offvalue', 'onvalue', 'overrelief', + 'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state', + 'takefocus', 'text', 'textvariable', + 'tristateimage', 'tristatevalue', + 'underline', 'variable', 'width', 'wraplength', + ) + + def create(self, **kwargs): + return tkinter.Checkbutton(self.root, **kwargs) + + + def test_configure_offvalue(self): + widget = self.create() + self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string') + + def test_configure_onvalue(self): + widget = self.create() + self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string') + + def test_unique_variables(self): + frames = [] + buttons = [] + for i in range(2): + f = tkinter.Frame(self.root) + f.pack() + frames.append(f) + for j in 'AB': + b = tkinter.Checkbutton(f, text=j) + b.pack() + buttons.append(b) + variables = [str(b['variable']) for b in buttons] + self.assertEqual(len(set(variables)), 4, variables) + + def test_same_name(self): + f1 = tkinter.Frame(self.root) + f2 = tkinter.Frame(self.root) + b1 = tkinter.Checkbutton(f1, name='test', text='Test1') + b2 = tkinter.Checkbutton(f2, name='test', text='Test2') + + v = tkinter.IntVar(self.root, name='test') + b1.select() + self.assertEqual(v.get(), 1) + b2.deselect() + self.assertEqual(v.get(), 0) + + def test_invoke(self): + success = [] + v = tkinter.IntVar(self.root) + widget = self.create(variable=v, onvalue=1, offvalue=0, + command=lambda: success.append(v.get())) + widget.pack() + widget.invoke() + self.assertEqual(v.get(), 1) + self.assertEqual(success, [1]) + widget.invoke() + self.assertEqual(v.get(), 0) + self.assertEqual(success, [1, 0]) + # A disabled checkbutton is not toggled and its command is not called. + widget.configure(state='disabled') + widget.invoke() + self.assertEqual(v.get(), 0) + self.assertEqual(success, [1, 0]) + + def test_toggle(self): + v = tkinter.IntVar(self.root) + widget = self.create(variable=v, onvalue=1, offvalue=0) + self.assertEqual(v.get(), 0) + widget.toggle() + self.assertEqual(v.get(), 1) + widget.toggle() + self.assertEqual(v.get(), 0) + + def test_flash(self): + widget = self.create() + widget.pack() + widget.update_idletasks() + widget.flash() # No exception. + +@add_configure_tests(StandardOptionsTests) +class RadiobuttonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'activeforeground', 'anchor', + 'background', 'bitmap', 'borderwidth', + 'command', 'compound', 'cursor', + 'disabledforeground', 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'image', 'indicatoron', 'justify', 'offrelief', 'overrelief', + 'padx', 'pady', 'relief', 'selectcolor', 'selectimage', 'state', + 'takefocus', 'text', 'textvariable', + 'tristateimage', 'tristatevalue', + 'underline', 'value', 'variable', 'width', 'wraplength', + ) + + def create(self, **kwargs): + return tkinter.Radiobutton(self.root, **kwargs) + + def test_configure_value(self): + widget = self.create() + self.checkParams(widget, 'value', 1, 2.3, '', 'any string') + + def test_invoke(self): + success = [] + v = tkinter.StringVar(self.root) + widget = self.create(variable=v, value='on', + command=lambda: success.append(v.get())) + widget.pack() + widget.invoke() + self.assertEqual(v.get(), 'on') + self.assertEqual(success, ['on']) + # invoke does nothing for a disabled radiobutton. + v.set('') + widget.configure(state='disabled') + widget.invoke() + self.assertEqual(v.get(), '') + self.assertEqual(success, ['on']) + + def test_flash(self): + widget = self.create() + widget.pack() + widget.update_idletasks() + widget.flash() # No exception. + + +@add_configure_tests(StandardOptionsTests) +class MenubuttonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'activeforeground', 'anchor', + 'background', 'bitmap', 'borderwidth', + 'compound', 'cursor', 'direction', + 'disabledforeground', 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'image', 'indicatoron', 'justify', 'menu', + 'padx', 'pady', 'relief', 'state', + 'takefocus', 'text', 'textvariable', + 'underline', 'width', 'wraplength', + ) + _rounds_pixels = (tk_version < (9, 0)) + if tk_version < (8, 7): + _clipped = {'highlightthickness', 'padx', 'pady'} + elif tk_version < (9, 0): + _clipped = {'borderwidth', 'highlightthickness', 'padx', 'pady'} + else: + _clipped = {'borderwidth', 'highlightthickness', 'insertborderwidth', 'padx', 'pady'} + + def setUp(self): + super().setUp() + if tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 1): + self._clipped = self._clipped - {'borderwidth'} + + def create(self, **kwargs): + return tkinter.Menubutton(self.root, **kwargs) + + def test_configure_direction(self): + widget = self.create() + self.checkEnumParam(widget, 'direction', + 'above', 'below', 'flush', 'left', 'right') + + def test_configure_height(self): + widget = self.create() + if tk_version < (8, 7) or (tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 1)): + conv = str + else: + conv = False + self.checkIntegerParam(widget, 'height', 100, -100, 0, conv=conv) + + def test_configure_image(self): + widget = self.create() + image = tkinter.PhotoImage(master=self.root, name='image1') + self.checkParam(widget, 'image', image, conv=str) + if tk_version < (8, 7): + errmsg = 'image "spam" doesn\'t exist' + else: + errmsg = 'image "spam" does not exist' + with self.assertRaises(tkinter.TclError) as cm: + widget['image'] = 'spam' + if errmsg is not None: + self.assertEqual(str(cm.exception), errmsg) + with self.assertRaises(tkinter.TclError) as cm: + widget.configure({'image': 'spam'}) + if errmsg is not None: + self.assertEqual(str(cm.exception), errmsg) + + def test_configure_menu(self): + widget = self.create() + menu = tkinter.Menu(widget, name='menu') + self.checkParam(widget, 'menu', menu, eq=widget_eq) + menu.destroy() + + def test_configure_width(self): + widget = self.create() + if tk_version < (8, 7) or (tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 1)): + conv = str + else: + conv = False + self.checkIntegerParam(widget, 'width', 402, -402, 0, conv=conv) + + +class OptionMenuTest(MenubuttonTest, unittest.TestCase): + + def create(self, default='b', values=('a', 'b', 'c'), **kwargs): + return tkinter.OptionMenu(self.root, None, default, *values, **kwargs) + + def test_bad_kwarg(self): + with self.assertRaisesRegex(TclError, r"^unknown option -image$"): + tkinter.OptionMenu(self.root, None, 'b', image='') + + def test_specify_name(self): + widget = tkinter.OptionMenu(self.root, None, ':)', name="option_menu") + self.assertEqual(str(widget), ".option_menu") + self.assertIs(self.root.children["option_menu"], widget) + +@add_configure_tests(IntegerSizeTests, StandardOptionsTests) +class EntryTest(AbstractWidgetTest, unittest.TestCase): + if tk_version < (8, 7): + _clipped = {'highlightthickness'} + else: + _clipped = {'borderwidth', 'highlightthickness', 'insertborderwidth', + 'insertwidth', 'selectborderwidth'} + + OPTIONS = ( + 'background', 'borderwidth', 'cursor', + 'disabledbackground', 'disabledforeground', + 'exportselection', 'font', 'foreground', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'insertbackground', 'insertborderwidth', + 'insertofftime', 'insertontime', 'insertwidth', + 'invalidcommand', 'justify', 'placeholder', 'placeholderforeground', + 'readonlybackground', 'relief', + 'selectbackground', 'selectborderwidth', 'selectforeground', + 'show', 'state', 'takefocus', 'textvariable', + 'validate', 'validatecommand', 'width', 'xscrollcommand', + ) + + def create(self, **kwargs): + return tkinter.Entry(self.root, **kwargs) + + def test_configure_disabledbackground(self): + widget = self.create() + self.checkColorParam(widget, 'disabledbackground') + + def test_configure_insertborderwidth(self): + widget = self.create(insertwidth=100) + self.checkPixelsParam(widget, 'insertborderwidth', + 0, 1.3, 2.6, 6, -2, '10p') + # insertborderwidth is bounded above by a half of insertwidth. + expected = 100 // 2 if tk_version < (8, 7) else 60 + self.checkParam(widget, 'insertborderwidth', 60, expected=expected) + + def test_configure_insertwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'insertwidth', 1.3, 3.6, 0.9, '10p') + if tk_version < (8, 7): + self.checkParam(widget, 'insertwidth', 0, expected=2) + self.checkParam(widget, 'insertwidth', 0.1, expected=2) + self.checkParam(widget, 'insertwidth', -2, expected=2) + else: + self.checkPixelsParam(widget, 'insertwidth', 0, 0.1, -2) + + def test_configure_invalidcommand(self): + widget = self.create() + self.checkCommandParam(widget, 'invalidcommand') + self.checkCommandParam(widget, 'invcmd') + + def test_configure_readonlybackground(self): + widget = self.create() + self.checkColorParam(widget, 'readonlybackground') + + def test_configure_show(self): + widget = self.create() + self.checkParam(widget, 'show', '*') + self.checkParam(widget, 'show', '') + self.checkParam(widget, 'show', ' ') + + def test_configure_state(self): + widget = self.create() + self.checkEnumParam(widget, 'state', + 'disabled', 'normal', 'readonly') + + def test_configure_validate(self): + widget = self.create() + self.checkEnumParam(widget, 'validate', + 'all', 'key', 'focus', 'focusin', 'focusout', 'none') + + def test_configure_validatecommand(self): + widget = self.create() + self.checkCommandParam(widget, 'validatecommand') + self.checkCommandParam(widget, 'vcmd') + + def test_selection_methods(self): + widget = self.create() + widget.insert(0, '12345') + self.assertFalse(widget.selection_present()) + widget.selection_range(0, 'end') + self.assertEqual(widget.selection_get(), '12345') + self.assertTrue(widget.selection_present()) + widget.selection_from(1) + widget.selection_to(2) + self.assertEqual(widget.selection_get(), '2') + widget.selection_range(3, 4) + self.assertEqual(widget.selection_get(), '4') + widget.selection_clear() + self.assertFalse(widget.selection_present()) + widget.selection_range(0, 'end') + widget.selection_adjust(4) + self.assertEqual(widget.selection_get(), '1234') + widget.selection_adjust(1) + self.assertEqual(widget.selection_get(), '234') + widget.selection_adjust(5) + self.assertEqual(widget.selection_get(), '2345') + widget.selection_adjust(0) + self.assertEqual(widget.selection_get(), '12345') + widget.selection_adjust(0) + + def test_delete(self): + widget = self.create() + widget.insert(0, 'abcdef') + widget.delete(1, 3) + self.assertEqual(widget.get(), 'adef') + widget.delete(1) + self.assertEqual(widget.get(), 'aef') + widget.delete(0, 'end') + self.assertEqual(widget.get(), '') + self.assertRaisesRegex(TclError, r'bad (entry|spinbox) index "xyz"', + widget.delete, 'xyz') + self.assertRaises(TypeError, widget.delete) + + def test_icursor(self): + widget = self.create() + widget.insert(0, 'abcdef') + widget.icursor(3) + widget.insert('insert', 'XYZ') + self.assertEqual(widget.get(), 'abcXYZdef') + self.assertRaisesRegex(TclError, r'bad (entry|spinbox) index "xyz"', + widget.icursor, 'xyz') + self.assertRaises(TypeError, widget.icursor) + + def test_select_aliases(self): + # The select_* methods are aliases of the selection_* methods. + widget = self.create() + widget.insert(0, '12345') + self.assertFalse(widget.select_present()) + widget.select_range(0, 'end') + self.assertTrue(widget.select_present()) + self.assertEqual(widget.selection_get(), '12345') + widget.select_from(1) + widget.select_to(3) + self.assertEqual(widget.selection_get(), '23') + widget.select_adjust(4) + self.assertEqual(widget.selection_get(), '234') + widget.select_clear() + self.assertFalse(widget.select_present()) + self.assertRaisesRegex(TclError, 'bad entry index "xyz"', + widget.select_range, 'xyz', 'end') + + +@add_configure_tests(StandardOptionsTests) +class SpinboxTest(EntryTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'background', 'borderwidth', + 'buttonbackground', 'buttoncursor', 'buttondownrelief', 'buttonuprelief', + 'command', 'cursor', 'disabledbackground', 'disabledforeground', + 'exportselection', 'font', 'foreground', 'format', 'from', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'increment', + 'insertbackground', 'insertborderwidth', + 'insertofftime', 'insertontime', 'insertwidth', + 'invalidcommand', 'justify', 'placeholder', 'placeholderforeground', + 'relief', 'readonlybackground', 'repeatdelay', 'repeatinterval', + 'selectbackground', 'selectborderwidth', 'selectforeground', + 'state', 'takefocus', 'textvariable', 'to', + 'validate', 'validatecommand', 'values', + 'width', 'wrap', 'xscrollcommand', + ) + + def create(self, **kwargs): + return tkinter.Spinbox(self.root, **kwargs) + + test_configure_show = None + + def test_configure_buttonbackground(self): + widget = self.create() + self.checkColorParam(widget, 'buttonbackground') + + def test_configure_buttoncursor(self): + widget = self.create() + self.checkCursorParam(widget, 'buttoncursor') + + def test_configure_buttondownrelief(self): + widget = self.create() + self.checkReliefParam(widget, 'buttondownrelief') + + def test_configure_buttonuprelief(self): + widget = self.create() + self.checkReliefParam(widget, 'buttonuprelief') + + def test_configure_format(self): + widget = self.create() + self.checkParam(widget, 'format', '%2f') + self.checkParam(widget, 'format', '%2.2f') + self.checkParam(widget, 'format', '%.2f') + self.checkParam(widget, 'format', '%2.f') + self.checkInvalidParam(widget, 'format', '%2e-1f') + self.checkInvalidParam(widget, 'format', '2.2') + self.checkInvalidParam(widget, 'format', '%2.-2f') + self.checkParam(widget, 'format', '%-2.02f') + self.checkParam(widget, 'format', '% 2.02f') + self.checkParam(widget, 'format', '% -2.200f') + self.checkParam(widget, 'format', '%09.200f') + self.checkInvalidParam(widget, 'format', '%d') + + def test_configure_from(self): + widget = self.create() + self.checkParam(widget, 'to', 100.0) + self.checkFloatParam(widget, 'from', -10, 10.2, 11.7) + if tk_version >= (8, 7): + self.checkFloatParam(widget, 'from', 200, expected=100) + else: + self.checkInvalidParam( + widget, 'from', 200, + errmsg='-to value must be greater than -from value') + + def test_configure_increment(self): + widget = self.create() + self.checkFloatParam(widget, 'increment', -1, 1, 10.2, 12.8, 0) + + def test_configure_to(self): + widget = self.create() + self.checkParam(widget, 'from', -100.0) + self.checkFloatParam(widget, 'to', -10, 10.2, 11.7) + if tk_version >= (8, 7): + self.checkFloatParam(widget, 'to', -200, expected=-100) + else: + self.checkInvalidParam( + widget, 'to', -200, + errmsg='-to value must be greater than -from value') + + def test_configure_values(self): + # XXX + widget = self.create() + self.assertEqual(widget['values'], '') + if tk_version < (8, 7) or (tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 1)): + expected = 'mon tue wed thur' + else: + expected = ('mon', 'tue', 'wed', 'thur') + self.checkParam(widget, 'values', 'mon tue wed thur', + expected=expected) + self.checkParam(widget, 'values', ('mon', 'tue', 'wed', 'thur'), + expected=expected) + + if tk_version < (8, 7) or (tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 1)): + expected = '42 3.14 {} {any string}' + else: + expected = (42, 3.14, '', 'any string') + self.checkParam(widget, 'values', (42, 3.14, '', 'any string'), + expected=expected) + + self.checkParam(widget, 'values', '') + + def test_configure_wrap(self): + widget = self.create() + self.checkBooleanParam(widget, 'wrap') + + def test_bbox(self): + widget = self.create() + self.assertIsBoundingBox(widget.bbox(0)) + self.assertRaises(tkinter.TclError, widget.bbox, 'noindex') + self.assertRaises(tkinter.TclError, widget.bbox, None) + self.assertRaises(TypeError, widget.bbox) + self.assertRaises(TypeError, widget.bbox, 0, 1) + + def test_selection_methods(self): + widget = self.create() + widget.insert(0, '12345') + self.assertFalse(widget.selection_present()) + widget.selection_range(0, 'end') + self.assertEqual(widget.selection_get(), '12345') + self.assertTrue(widget.selection_present()) + widget.selection_from(1) + widget.selection_to(2) + self.assertEqual(widget.selection_get(), '2') + widget.selection_range(3, 4) + self.assertEqual(widget.selection_get(), '4') + widget.selection_clear() + self.assertFalse(widget.selection_present()) + widget.selection_range(0, 'end') + widget.selection_adjust(4) + self.assertEqual(widget.selection_get(), '1234') + widget.selection_adjust(1) + self.assertEqual(widget.selection_get(), '234') + widget.selection_adjust(5) + self.assertEqual(widget.selection_get(), '2345') + widget.selection_adjust(0) + self.assertEqual(widget.selection_get(), '12345') + + def test_selection_element(self): + widget = self.create() + self.assertEqual(widget.selection_element(), "none") + widget.selection_element("buttonup") + self.assertEqual(widget.selection_element(), "buttonup") + widget.selection_element("buttondown") + self.assertEqual(widget.selection_element(), "buttondown") + + # Spinbox has no select_* aliases, unlike Entry. + test_select_aliases = None + + def test_invoke(self): + widget = self.create(from_=0, to=10) + widget.delete(0, 'end') + widget.insert(0, '5') + widget.invoke('buttonup') + self.assertEqual(widget.get(), '6') + widget.invoke('buttondown') + self.assertEqual(widget.get(), '5') + self.assertRaisesRegex(TclError, 'bad element "spam"', + widget.invoke, 'spam') + + def test_identify(self): + widget = self.create() + widget.pack() + # Identifying the element under a point requires the widget to be + # mapped with a real size. + if wait_until_mapped(widget): + self.assertIn(widget.identify(5, 5), + ('entry', 'buttonup', 'buttondown', 'none')) + self.assertRaises(TclError, widget.identify, 'a', 'b') + + def test_scan(self): + widget = self.create() + widget.insert(0, 'a' * 100) + widget.pack() + widget.update_idletasks() + self.assertEqual(widget.scan_mark(10), ()) + self.assertEqual(widget.scan_dragto(0), ()) + self.assertRaises(TypeError, widget.scan_mark) + + +@add_configure_tests(StandardOptionsTests) +class TextTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'autoseparators', 'background', 'blockcursor', 'borderwidth', + 'cursor', 'endline', 'exportselection', + 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'inactiveselectbackground', 'insertbackground', 'insertborderwidth', + 'insertofftime', 'insertontime', 'insertunfocussed', 'insertwidth', + 'maxundo', 'padx', 'pady', 'relief', + 'selectbackground', 'selectborderwidth', 'selectforeground', + 'setgrid', 'spacing1', 'spacing2', 'spacing3', 'startline', 'state', + 'tabs', 'tabstyle', 'takefocus', 'undo', 'width', 'wrap', + 'xscrollcommand', 'yscrollcommand', + ) + _no_round = {'selectborderwidth'} + if tk_version < (9, 0): + _clipped = {'highlightthickness', 'spacing1', 'spacing2', 'spacing3'} + else: + _clipped = {'borderwidth', 'height', 'highlightthickness', + 'insertborderwidth', 'insertwidth', 'padx', 'pady', + 'selectborderwidth', 'spacing1', 'spacing2', 'spacing3'} + + def setUp(self): + super().setUp() + if tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 2): + self._clipped = self._clipped - {'borderwidth', 'height', 'padx', 'pady'} + if tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 1): + self._clipped = self._clipped - {'insertborderwidth', 'insertwidth', 'selectborderwidth'} + + def create(self, **kwargs): + return tkinter.Text(self.root, **kwargs) + + def test_configure_autoseparators(self): + widget = self.create() + self.checkBooleanParam(widget, 'autoseparators') + + def test_configure_blockcursor(self): + widget = self.create() + self.checkBooleanParam(widget, 'blockcursor') + + def test_configure_endline(self): + widget = self.create() + text = '\n'.join('Line %d' for i in range(100)) + widget.insert('end', text) + self.checkParam(widget, 'endline', 200, expected='') + self.checkParam(widget, 'endline', -10, expected='') + self.checkInvalidParam(widget, 'endline', 'spam', + errmsg='expected integer but got "spam"') + self.checkParam(widget, 'endline', 50) + self.checkParam(widget, 'startline', 15) + self.checkInvalidParam(widget, 'endline', 10, + errmsg='-startline must be less than or equal to -endline') + + def test_configure_height(self): + widget = self.create() + self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, '3c') + if tk_version < (9, 0): + self.checkParam(widget, 'height', 0, expected=1) + self.checkParam(widget, 'height', -100, expected=1) + else: + self.checkPixelsParam(widget, 'height', 0, -100) + + def test_configure_maxundo(self): + widget = self.create() + self.checkIntegerParam(widget, 'maxundo', 0, 5, -1) + + def test_configure_inactiveselectbackground(self): + widget = self.create() + self.checkColorParam(widget, 'inactiveselectbackground') + + @requires_tk(8, 6) + def test_configure_insertunfocussed(self): + widget = self.create() + self.checkEnumParam(widget, 'insertunfocussed', + 'hollow', 'none', 'solid') + + def test_configure_spacing1(self): + widget = self.create() + self.checkPixelsParam(widget, 'spacing1', 20, 21.4, 22.6, -5, '0.5c') + + def test_configure_spacing2(self): + widget = self.create() + self.checkPixelsParam(widget, 'spacing2', 5, 6.4, 7.6, -1, '0.1c') + + def test_configure_spacing3(self): + widget = self.create() + self.checkPixelsParam(widget, 'spacing3', 20, 21.4, 22.6, -10, '0.5c') + + def test_configure_startline(self): + widget = self.create() + text = '\n'.join('Line %d' for i in range(100)) + widget.insert('end', text) + self.checkParam(widget, 'startline', 200, expected='') + self.checkParam(widget, 'startline', -10, expected='') + self.checkInvalidParam(widget, 'startline', 'spam', + errmsg='expected integer but got "spam"') + self.checkParam(widget, 'startline', 10) + self.checkParam(widget, 'endline', 50) + self.checkInvalidParam(widget, 'startline', 70, + errmsg='-startline must be less than or equal to -endline') + + def test_configure_state(self): + widget = self.create() + self.checkEnumParam(widget, 'state', 'disabled', 'normal') + + def test_configure_tabs(self): + widget = self.create() + self.checkParam(widget, 'tabs', (10.2, 20.7, '1i', '2i')) + self.checkParam(widget, 'tabs', '10.2 20.7 1i 2i', + expected=(10.2, 20.7, '1i', '2i') + if get_tk_patchlevel(self.root) >= (8, 6, 14) + else ('10.2', '20.7', '1i', '2i')) + self.checkParam(widget, 'tabs', '2c left 4c 6c center', + expected=('2c', 'left', '4c', '6c', 'center')) + self.checkInvalidParam(widget, 'tabs', 'spam', + errmsg=EXPECTED_SCREEN_DISTANCE_ERRMSG.format('spam')) + + def test_configure_tabstyle(self): + widget = self.create() + self.checkEnumParam(widget, 'tabstyle', 'tabular', 'wordprocessor') + + def test_configure_undo(self): + widget = self.create() + self.checkBooleanParam(widget, 'undo') + + def test_configure_width(self): + widget = self.create() + self.checkIntegerParam(widget, 'width', 402) + self.checkParam(widget, 'width', -402, expected=1) + self.checkParam(widget, 'width', 0, expected=1) + + def test_configure_wrap(self): + widget = self.create() + self.checkEnumParam(widget, 'wrap', 'char', 'none', 'word') + + def test_bbox(self): + widget = self.create() + self.assertIsBoundingBox(widget.bbox('1.1')) + self.assertIsNone(widget.bbox('end')) + self.assertRaises(tkinter.TclError, widget.bbox, 'noindex') + self.assertRaises(tkinter.TclError, widget.bbox, None) + self.assertRaises(TypeError, widget.bbox) + self.assertRaises(TypeError, widget.bbox, '1.1', 'end') + + +@add_configure_tests(PixelSizeTests, StandardOptionsTests) +class CanvasTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'background', 'borderwidth', + 'closeenough', 'confine', 'cursor', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'insertbackground', 'insertborderwidth', + 'insertofftime', 'insertontime', 'insertwidth', + 'offset', 'relief', 'scrollregion', + 'selectbackground', 'selectborderwidth', 'selectforeground', + 'state', 'takefocus', + 'xscrollcommand', 'xscrollincrement', + 'yscrollcommand', 'yscrollincrement', 'width', + ) + if tk_version < (8, 7): + _clipped = {'highlightthickness'} + else: + _clipped = {'borderwidth', 'height', 'highlightthickness', + 'insertborderwidth', 'insertwidth', 'selectborderwidth', + 'width', 'xscrollincrement', 'yscrollincrement'} + _stringify = True + + def setUp(self): + super().setUp() + if tk_version[:2] == (9, 0) and get_tk_patchlevel(self.root) < (9, 0, 1): + self._rounds_pixels = True + self._no_round = {'borderwidth', 'height', 'highlightthickness', + 'width', 'xscrollincrement', 'yscrollincrement'} + self._clipped = self._clipped - {'insertborderwidth', 'insertwidth', 'selectborderwidth'} + + def create(self, **kwargs): + return tkinter.Canvas(self.root, **kwargs) + + def test_configure_closeenough(self): + widget = self.create() + self.checkFloatParam(widget, 'closeenough', 24, 2.4, 3.6, -3, + conv=float) + + def test_configure_confine(self): + widget = self.create() + self.checkBooleanParam(widget, 'confine') + + def test_configure_offset(self): + widget = self.create() + self.assertEqual(widget['offset'], '0,0') + self.checkParams(widget, 'offset', + 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center') + self.checkParam(widget, 'offset', '10,20') + self.checkParam(widget, 'offset', '#5,6') + self.checkInvalidParam(widget, 'offset', 'spam') + + def test_configure_scrollregion(self): + widget = self.create() + self.checkParam(widget, 'scrollregion', '0 0 200 150') + self.checkParam(widget, 'scrollregion', (0, 0, 200, 150), + expected='0 0 200 150') + self.checkParam(widget, 'scrollregion', '') + self.checkInvalidParam(widget, 'scrollregion', 'spam', + errmsg='bad scrollRegion "spam"') + self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 'spam')) + self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200)) + self.checkInvalidParam(widget, 'scrollregion', (0, 0, 200, 150, 0)) + + def test_configure_state(self): + widget = self.create() + self.checkEnumParam(widget, 'state', 'disabled', 'normal', + errmsg='bad state value "{}": must be normal or disabled') + + def test_configure_xscrollincrement(self): + widget = self.create() + self.checkPixelsParam(widget, 'xscrollincrement', + 40, 0, 41.2, 43.6, -40, '0.5i') + + def test_configure_yscrollincrement(self): + widget = self.create() + self.checkPixelsParam(widget, 'yscrollincrement', + 10, 0, 11.2, 13.6, -10, '0.1i') + + def _test_option_joinstyle(self, c, factory): + for joinstyle in 'bevel', 'miter', 'round': + i = factory(joinstyle=joinstyle) + self.assertEqual(c.itemcget(i, 'joinstyle'), joinstyle) + self.assertRaises(TclError, factory, joinstyle='spam') + + def _test_option_smooth(self, c, factory): + for smooth in 1, True, '1', 'true', 'yes', 'on': + i = factory(smooth=smooth) + self.assertEqual(c.itemcget(i, 'smooth'), 'true') + for smooth in 0, False, '0', 'false', 'no', 'off': + i = factory(smooth=smooth) + self.assertEqual(c.itemcget(i, 'smooth'), '0') + i = factory(smooth=True, splinestep=30) + self.assertEqual(c.itemcget(i, 'smooth'), 'true') + self.assertEqual(c.itemcget(i, 'splinestep'), '30') + i = factory(smooth='raw', splinestep=30) + self.assertEqual(c.itemcget(i, 'smooth'), 'raw') + self.assertEqual(c.itemcget(i, 'splinestep'), '30') + self.assertRaises(TclError, factory, smooth='spam') + + def test_create_rectangle(self): + c = self.create() + i1 = c.create_rectangle(20, 30, 60, 10) + self.assertEqual(c.coords(i1), [20.0, 10.0, 60.0, 30.0]) + self.assertEqual(c.bbox(i1), (19, 9, 61, 31)) + + i2 = c.create_rectangle([21, 31, 61, 11]) + self.assertEqual(c.coords(i2), [21.0, 11.0, 61.0, 31.0]) + self.assertEqual(c.bbox(i2), (20, 10, 62, 32)) + + i3 = c.create_rectangle((22, 32), (62, 12)) + self.assertEqual(c.coords(i3), [22.0, 12.0, 62.0, 32.0]) + self.assertEqual(c.bbox(i3), (21, 11, 63, 33)) + + i4 = c.create_rectangle([(23, 33), (63, 13)]) + self.assertEqual(c.coords(i4), [23.0, 13.0, 63.0, 33.0]) + self.assertEqual(c.bbox(i4), (22, 12, 64, 34)) + + self.assertRaises(TclError, c.create_rectangle, 20, 30, 60) + self.assertRaises(TclError, c.create_rectangle, [20, 30, 60]) + self.assertRaises(TclError, c.create_rectangle, 20, 30, 40, 50, 60, 10) + self.assertRaises(TclError, c.create_rectangle, [20, 30, 40, 50, 60, 10]) + self.assertRaises(TclError, c.create_rectangle, 20, 30) + self.assertRaises(TclError, c.create_rectangle, [20, 30]) + self.assertRaises(IndexError, c.create_rectangle) + self.assertRaises(IndexError, c.create_rectangle, []) + + def test_create_line(self): + c = self.create() + i1 = c.create_line(20, 30, 40, 50, 60, 10) + self.assertEqual(c.coords(i1), [20.0, 30.0, 40.0, 50.0, 60.0, 10.0]) + self.assertEqual(c.bbox(i1), (18, 8, 62, 52)) + self.assertEqual(c.itemcget(i1, 'arrow'), 'none') + self.assertEqual(c.itemcget(i1, 'arrowshape'), '8 10 3') + self.assertEqual(c.itemcget(i1, 'capstyle'), 'butt') + self.assertEqual(c.itemcget(i1, 'joinstyle'), 'round') + self.assertEqual(c.itemcget(i1, 'smooth'), '0') + self.assertEqual(c.itemcget(i1, 'splinestep'), '12') + + i2 = c.create_line([21, 31, 41, 51, 61, 11]) + self.assertEqual(c.coords(i2), [21.0, 31.0, 41.0, 51.0, 61.0, 11.0]) + self.assertEqual(c.bbox(i2), (19, 9, 63, 53)) + + i3 = c.create_line((22, 32), (42, 52), (62, 12)) + self.assertEqual(c.coords(i3), [22.0, 32.0, 42.0, 52.0, 62.0, 12.0]) + self.assertEqual(c.bbox(i3), (20, 10, 64, 54)) + + i4 = c.create_line([(23, 33), (43, 53), (63, 13)]) + self.assertEqual(c.coords(i4), [23.0, 33.0, 43.0, 53.0, 63.0, 13.0]) + self.assertEqual(c.bbox(i4), (21, 11, 65, 55)) + + self.assertRaises(TclError, c.create_line, 20, 30, 60) + self.assertRaises(TclError, c.create_line, [20, 30, 60]) + self.assertRaises(TclError, c.create_line, 20, 30) + self.assertRaises(TclError, c.create_line, [20, 30]) + self.assertRaises(IndexError, c.create_line) + self.assertRaises(IndexError, c.create_line, []) + + for arrow in 'none', 'first', 'last', 'both': + i = c.create_line(20, 30, 60, 10, arrow=arrow) + self.assertEqual(c.itemcget(i, 'arrow'), arrow) + i = c.create_line(20, 30, 60, 10, arrow='first', arrowshape=[10, 15, 5]) + self.assertEqual(c.itemcget(i, 'arrowshape'), '10 15 5') + self.assertRaises(TclError, c.create_line, 20, 30, 60, 10, arrow='spam') + + for capstyle in 'butt', 'projecting', 'round': + i = c.create_line(20, 30, 60, 10, capstyle=capstyle) + self.assertEqual(c.itemcget(i, 'capstyle'), capstyle) + self.assertRaises(TclError, c.create_line, 20, 30, 60, 10, capstyle='spam') + + self._test_option_joinstyle(c, + lambda **kwargs: c.create_line(20, 30, 40, 50, 60, 10, **kwargs)) + self._test_option_smooth(c, + lambda **kwargs: c.create_line(20, 30, 60, 10, **kwargs)) + + def test_create_polygon(self): + c = self.create() + # In Tk < 8.7 polygons are filled, but has no outline by default. + # This affects its size, so always explicitly specify outline. + i1 = c.create_polygon(20, 30, 40, 50, 60, 10, outline='red') + self.assertEqual(c.coords(i1), [20.0, 30.0, 40.0, 50.0, 60.0, 10.0]) + self.assertEqual(c.bbox(i1), (18, 8, 62, 52)) + self.assertEqual(c.itemcget(i1, 'joinstyle'), 'round') + self.assertEqual(c.itemcget(i1, 'smooth'), '0') + self.assertEqual(c.itemcget(i1, 'splinestep'), '12') + + i2 = c.create_polygon([21, 31, 41, 51, 61, 11], outline='red') + self.assertEqual(c.coords(i2), [21.0, 31.0, 41.0, 51.0, 61.0, 11.0]) + self.assertEqual(c.bbox(i2), (19, 9, 63, 53)) + + i3 = c.create_polygon((22, 32), (42, 52), (62, 12), outline='red') + self.assertEqual(c.coords(i3), [22.0, 32.0, 42.0, 52.0, 62.0, 12.0]) + self.assertEqual(c.bbox(i3), (20, 10, 64, 54)) + + i4 = c.create_polygon([(23, 33), (43, 53), (63, 13)], outline='red') + self.assertEqual(c.coords(i4), [23.0, 33.0, 43.0, 53.0, 63.0, 13.0]) + self.assertEqual(c.bbox(i4), (21, 11, 65, 55)) + + self.assertRaises(TclError, c.create_polygon, 20, 30, 60) + self.assertRaises(TclError, c.create_polygon, [20, 30, 60]) + self.assertRaises(IndexError, c.create_polygon) + self.assertRaises(IndexError, c.create_polygon, []) + + self._test_option_joinstyle(c, + lambda **kwargs: c.create_polygon(20, 30, 40, 50, 60, 10, **kwargs)) + self._test_option_smooth(c, + lambda **kwargs: c.create_polygon(20, 30, 40, 50, 60, 10, **kwargs)) + + def test_create_arc(self): + c = self.create() + i = c.create_arc(10, 20, 30, 40) + self.assertEqual(c.coords(i), [10.0, 20.0, 30.0, 40.0]) + self.assertEqual(c.itemcget(i, 'style'), 'pieslice') + self.assertEqual(float(c.itemcget(i, 'start')), 0.0) + self.assertEqual(float(c.itemcget(i, 'extent')), 90.0) + + for style in 'pieslice', 'chord', 'arc': + i = c.create_arc(10, 20, 30, 40, style=style) + self.assertEqual(c.itemcget(i, 'style'), style) + self.assertRaises(TclError, c.create_arc, 10, 20, 30, 40, style='spam') + + i = c.create_arc(10, 20, 30, 40, start=45, extent=120, + outline='red', fill='blue', width=3) + self.assertEqual(float(c.itemcget(i, 'start')), 45.0) + self.assertEqual(float(c.itemcget(i, 'extent')), 120.0) + self.assertEqual(str(c.itemcget(i, 'outline')), 'red') + self.assertEqual(str(c.itemcget(i, 'fill')), 'blue') + self.assertEqual(float(c.itemcget(i, 'width')), 3.0) + self.assertRaises(TclError, c.create_arc, 10, 20, 30, 40, extent='spam') + + def test_create_oval(self): + c = self.create() + i = c.create_oval(10, 20, 30, 40) + self.assertEqual(c.coords(i), [10.0, 20.0, 30.0, 40.0]) + self.assertEqual(c.bbox(i), (9, 19, 31, 41)) + self.assertEqual(c.itemcget(i, 'stipple'), '') + + i = c.create_oval(10, 20, 30, 40, fill='red', outline='blue', width=2) + self.assertEqual(str(c.itemcget(i, 'fill')), 'red') + self.assertEqual(str(c.itemcget(i, 'outline')), 'blue') + self.assertEqual(float(c.itemcget(i, 'width')), 2.0) + self.assertRaises(TclError, c.create_oval, 10, 20, 30, 40, width='spam') + + def test_create_bitmap(self): + c = self.create() + i = c.create_bitmap(10, 20, bitmap='gray50') + self.assertEqual(c.coords(i), [10.0, 20.0]) + self.assertEqual(c.itemcget(i, 'bitmap'), 'gray50') + self.assertEqual(c.itemcget(i, 'anchor'), 'center') + + for anchor in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center': + i = c.create_bitmap(10, 20, bitmap='gray50', anchor=anchor) + self.assertEqual(c.itemcget(i, 'anchor'), anchor) + self.assertRaises(TclError, c.create_bitmap, 10, 20, + bitmap='gray50', anchor='spam') + + i = c.create_bitmap(10, 20, bitmap='gray50', + foreground='red', background='blue') + self.assertEqual(str(c.itemcget(i, 'foreground')), 'red') + self.assertEqual(str(c.itemcget(i, 'background')), 'blue') + if c._windowingsystem != 'aqua': + # Aqua resolves bitmaps lazily and does not report a bad name here. + self.assertRaises(TclError, c.create_bitmap, 10, 20, bitmap='spam') + + def test_create_image(self): + c = self.create() + image = tkinter.PhotoImage(master=self.root, width=10, height=10) + i = c.create_image(10, 20, image=image) + self.assertEqual(c.coords(i), [10.0, 20.0]) + self.assertEqual(str(c.itemcget(i, 'image')), str(image)) + self.assertEqual(c.itemcget(i, 'anchor'), 'center') + + for anchor in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center': + i = c.create_image(10, 20, image=image, anchor=anchor) + self.assertEqual(c.itemcget(i, 'anchor'), anchor) + self.assertRaises(TclError, c.create_image, 10, 20, + image=image, anchor='spam') + + def test_create_text(self): + c = self.create() + i = c.create_text(10, 20, text='Hello') + self.assertEqual(c.coords(i), [10.0, 20.0]) + self.assertEqual(c.itemcget(i, 'text'), 'Hello') + self.assertEqual(c.itemcget(i, 'anchor'), 'center') + self.assertEqual(c.itemcget(i, 'justify'), 'left') + + for justify in 'left', 'right', 'center': + i = c.create_text(10, 20, text='Hello', justify=justify) + self.assertEqual(c.itemcget(i, 'justify'), justify) + self.assertRaises(TclError, c.create_text, 10, 20, justify='spam') + + for anchor in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center': + i = c.create_text(10, 20, text='Hello', anchor=anchor) + self.assertEqual(c.itemcget(i, 'anchor'), anchor) + self.assertRaises(TclError, c.create_text, 10, 20, anchor='spam') + + i = c.create_text(10, 20, text='Hello', fill='red', angle=45, + font='TkFixedFont') + self.assertEqual(str(c.itemcget(i, 'fill')), 'red') + self.assertEqual(float(c.itemcget(i, 'angle')), 45.0) + self.assertEqual(str(c.itemcget(i, 'font')), 'TkFixedFont') + self.assertRaises(TclError, c.create_text, 10, 20, angle='spam') + + def test_create_window(self): + c = self.create() + button = tkinter.Button(c, text='ok') + i = c.create_window(10, 20, window=button) + self.assertEqual(c.coords(i), [10.0, 20.0]) + self.assertEqual(c.itemcget(i, 'window'), str(button)) + self.assertEqual(c.itemcget(i, 'anchor'), 'center') + + for anchor in 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center': + i = c.create_window(10, 20, window=tkinter.Button(c), anchor=anchor) + self.assertEqual(c.itemcget(i, 'anchor'), anchor) + self.assertRaises(TclError, c.create_window, 10, 20, + window=button, anchor='spam') + + i = c.create_window(10, 20, window=tkinter.Button(c), + width=30, height=40) + self.assertEqual(int(c.itemcget(i, 'width')), 30) + self.assertEqual(int(c.itemcget(i, 'height')), 40) + self.assertRaises(TclError, c.create_window, 10, 20, + window=button, width='spam') + + def test_coords(self): + c = self.create() + i = c.create_line(20, 30, 40, 50, 60, 10, tags='x') + self.assertEqual(c.coords(i), [20.0, 30.0, 40.0, 50.0, 60.0, 10.0]) + self.assertEqual(c.coords('x'), [20.0, 30.0, 40.0, 50.0, 60.0, 10.0]) + self.assertEqual(c.bbox(i), (18, 8, 62, 52)) + + c.coords(i, 50, 60, 70, 80, 90, 40) + self.assertEqual(c.coords(i), [50.0, 60.0, 70.0, 80.0, 90.0, 40.0]) + self.assertEqual(c.bbox(i), (48, 38, 92, 82)) + + c.coords(i, [21, 31, 41, 51, 61, 11]) + self.assertEqual(c.coords(i), [21.0, 31.0, 41.0, 51.0, 61.0, 11.0]) + + c.coords(i, (22, 32), (42, 52), (62, 12)) + self.assertEqual(c.coords(i), [22.0, 32.0, 42.0, 52.0, 62.0, 12.0]) + + c.coords(i, [(23, 33), (43, 53), (63, 13)]) + self.assertEqual(c.coords(i), [23.0, 33.0, 43.0, 53.0, 63.0, 13.0]) + + c.coords(i, 20, 30, 60, 10) + self.assertEqual(c.coords(i), [20.0, 30.0, 60.0, 10.0]) + self.assertEqual(c.bbox(i), (18, 8, 62, 32)) + + self.assertRaises(TclError, c.coords, i, 20, 30, 60) + self.assertRaises(TclError, c.coords, i, [20, 30, 60]) + self.assertRaises(TclError, c.coords, i, 20, 30) + self.assertRaises(TclError, c.coords, i, [20, 30]) + + c.coords(i, '20', '30c', '60i', '10p') + coords = c.coords(i) + self.assertIsInstance(coords, list) + self.assertEqual(len(coords), 4) + self.assertEqual(coords[0], 20) + for i in range(4): + self.assertIsInstance(coords[i], float) + + @requires_tk(8, 6) + def test_moveto(self): + widget = self.create() + i1 = widget.create_rectangle(1, 1, 20, 20, tags='group') + i2 = widget.create_rectangle(30, 30, 50, 70, tags='group') + x1, y1, _, _ = widget.bbox(i1) + x2, y2, _, _ = widget.bbox(i2) + widget.moveto('group', 200, 100) + x1_2, y1_2, _, _ = widget.bbox(i1) + x2_2, y2_2, _, _ = widget.bbox(i2) + self.assertEqual(x1_2, 200) + self.assertEqual(y1_2, 100) + self.assertEqual(x2 - x1, x2_2 - x1_2) + self.assertEqual(y2 - y1, y2_2 - y1_2) + widget.tag_lower(i2, i1) + widget.moveto('group', y=50) + x1_3, y1_3, _, _ = widget.bbox(i1) + x2_3, y2_3, _, _ = widget.bbox(i2) + self.assertEqual(y2_3, 50) + self.assertEqual(x2_3, x2_2) + self.assertEqual(x2_2 - x1_2, x2_3 - x1_3) + self.assertEqual(y2_2 - y1_2, y2_3 - y1_3) + + def test_create_items(self): + c = self.create() + image = tkinter.PhotoImage(master=self.root, width=10, height=10) + button = tkinter.Button(c, text='ok') + items = { + 'arc': c.create_arc(10, 20, 30, 40), + 'bitmap': c.create_bitmap(10, 20, bitmap='gray50'), + 'image': c.create_image(10, 20, image=image), + 'line': c.create_line(10, 20, 30, 40), + 'oval': c.create_oval(10, 20, 30, 40), + 'polygon': c.create_polygon(10, 20, 30, 40, 50, 20), + 'rectangle': c.create_rectangle(10, 20, 30, 40), + 'text': c.create_text(10, 20, text='hello'), + 'window': c.create_window(10, 20, window=button), + } + for itemtype, item in items.items(): + self.assertIsInstance(item, int) + self.assertEqual(c.type(item), itemtype) + # All items are reported by find_all in creation (stacking) order. + self.assertEqual(c.find_all(), tuple(sorted(items.values()))) + + # No coordinates at all is an IndexError; a bad number is a TclError. + self.assertRaises(IndexError, c.create_arc) + self.assertRaises(TclError, c.create_arc, 1, 2, 3) + self.assertRaises(TclError, c.create_oval, 1, 2) + + def test_type(self): + c = self.create() + rect = c.create_rectangle(10, 20, 30, 40) + self.assertEqual(c.type(rect), 'rectangle') + # An unmatched tag or id is not an error. + self.assertIsNone(c.type('nonexistent')) + self.assertIsNone(c.type(9999)) + self.assertRaises(TypeError, c.type) + self.assertRaises(TypeError, c.type, rect, 'extra') + + def test_bbox(self): + c = self.create() + rect = c.create_rectangle(10, 10, 30, 30) + bbox = c.bbox(rect) + self.assertIsInstance(bbox, tuple) + self.assertEqual(len(bbox), 4) + for v in bbox: + self.assertIsInstance(v, int) + # The bounding box encloses the item (with a small margin). + self.assertEqual(bbox, (9, 9, 31, 31)) + # bbox over several items is their union. + rect2 = c.create_rectangle(50, 50, 70, 70) + self.assertEqual(c.bbox(rect, rect2), (9, 9, 71, 71)) + # An unmatched tag has no bounding box. + self.assertIsNone(c.bbox('nonexistent')) + # At least one tag or id is required. + self.assertRaises(TclError, c.bbox) + + def test_canvasx_canvasy(self): + c = self.create(borderwidth=0, highlightthickness=0) + self.assertEqual(c.canvasx(0), 0.0) + self.assertEqual(c.canvasx(10), 10.0) + self.assertIsInstance(c.canvasx(10), float) + # gridspacing rounds to the nearest multiple. + self.assertEqual(c.canvasx(13, 5), 15.0) + self.assertEqual(c.canvasy(0), 0.0) + self.assertEqual(c.canvasy(10), 10.0) + self.assertRaises(TypeError, c.canvasx) + self.assertRaises(TypeError, c.canvasx, 0, 5, 1) + self.assertRaises(TypeError, c.canvasy) + self.assertRaises(TypeError, c.canvasy, 0, 5, 1) + self.assertRaises(TclError, c.canvasx, 'spam') + self.assertRaises(TclError, c.canvasy, 'spam') + + def test_move(self): + c = self.create() + rect = c.create_rectangle(10, 10, 30, 30) + c.move(rect, 5, 7) + self.assertEqual(c.coords(rect), [15.0, 17.0, 35.0, 37.0]) + c.move(rect, -5, -7) + self.assertEqual(c.coords(rect), [10.0, 10.0, 30.0, 30.0]) + # move() takes variable arguments; bad or missing values reach Tcl. + self.assertRaises(TclError, c.move, rect, 'spam', 0) + self.assertRaises(TclError, c.move, rect) + + def test_scale(self): + c = self.create() + rect = c.create_rectangle(10, 10, 30, 30) + c.scale(rect, 0, 0, 2, 2) + self.assertEqual(c.coords(rect), [20.0, 20.0, 60.0, 60.0]) + c.scale(rect, 0, 0, 0.5, 0.5) + self.assertEqual(c.coords(rect), [10.0, 10.0, 30.0, 30.0]) + self.assertRaises(TclError, c.scale, rect, 0, 0, 'spam', 2) + self.assertRaises(TclError, c.scale, rect, 0, 0) # missing factors + + def test_delete(self): + c = self.create() + r1 = c.create_rectangle(10, 10, 30, 30) + r2 = c.create_rectangle(50, 50, 70, 70) + r3 = c.create_rectangle(90, 90, 110, 110) + self.assertEqual(c.find_all(), (r1, r2, r3)) + c.delete(r2) + self.assertEqual(c.find_all(), (r1, r3)) + # Deleting a non-existent item is not an error. + c.delete(9999) + c.delete('all') + self.assertEqual(c.find_all(), ()) + + def test_find(self): + c = self.create() + r1 = c.create_rectangle(10, 10, 30, 30) + r2 = c.create_rectangle(50, 50, 70, 70) + r3 = c.create_rectangle(100, 100, 120, 120) + + self.assertEqual(c.find_all(), (r1, r2, r3)) + # find_above/find_below return the single adjacent item. + self.assertEqual(c.find_above(r1), (r2,)) + self.assertEqual(c.find_below(r3), (r2,)) + self.assertEqual(c.find_above(r3), ()) # nothing above the top item + self.assertEqual(c.find_withtag(r2), (r2,)) + self.assertEqual(c.find_closest(60, 60), (r2,)) + self.assertEqual(c.find_enclosed(0, 0, 80, 80), (r1, r2)) + self.assertEqual(c.find_overlapping(0, 0, 20, 20), (r1,)) + # An unmatched query returns an empty tuple. + self.assertEqual(c.find_withtag('nonexistent'), ()) + for result in (c.find_all(), c.find_withtag(r1)): + self.assertIsInstance(result, tuple) + + self.assertRaises(TclError, c.find_closest, 'spam', 0) + self.assertRaises(TclError, c.find_enclosed, 0, 0, 'spam', 0) + self.assertRaises(TclError, c.find_overlapping, 0, 0, 'spam', 0) + self.assertRaises(TypeError, c.find_withtag) + self.assertRaises(TypeError, c.find_withtag, r1, 'extra') + self.assertRaises(TypeError, c.find_above) + self.assertRaises(TypeError, c.find_above, r1, 'extra') + self.assertRaises(TypeError, c.find_below) + self.assertRaises(TypeError, c.find_closest) + self.assertRaises(TypeError, c.find_closest, 0, 0, 1, 2, 3) + self.assertRaises(TypeError, c.find_enclosed, 0, 0, 1) + self.assertRaises(TypeError, c.find_enclosed, 0, 0, 1, 2, 3) + + def test_addtag_gettags_dtag(self): + c = self.create() + r1 = c.create_rectangle(10, 10, 30, 30) + r2 = c.create_rectangle(50, 50, 70, 70) + + self.assertEqual(c.gettags(r1), ()) + c.addtag_withtag('spam', r1) + self.assertEqual(c.gettags(r1), ('spam',)) + self.assertEqual(c.find_withtag('spam'), (r1,)) + + c.addtag_all('all') + self.assertIn('all', c.gettags(r1)) + self.assertIn('all', c.gettags(r2)) + + c.addtag_above('above1', r1) + self.assertIn('above1', c.gettags(r2)) + c.addtag_below('below2', r2) + self.assertIn('below2', c.gettags(r1)) + + c.addtag_enclosed('enc', 0, 0, 40, 40) + self.assertEqual(c.find_withtag('enc'), (r1,)) + c.addtag_overlapping('ov', 0, 0, 20, 20) + self.assertEqual(c.find_withtag('ov'), (r1,)) + c.addtag_closest('close', 60, 60) + self.assertEqual(c.find_withtag('close'), (r2,)) + + # gettags of an unmatched tag is empty. + self.assertEqual(c.gettags('nonexistent'), ()) + + # dtag removes a tag from an item. + c.dtag(r1, 'spam') + self.assertNotIn('spam', c.gettags(r1)) + + self.assertRaises(TypeError, c.addtag_withtag, 'tag') + self.assertRaises(TypeError, c.addtag_withtag, 'tag', r1, 'extra') + self.assertRaises(TypeError, c.addtag_all) + self.assertRaises(TypeError, c.addtag_enclosed, 'tag', 0, 0, 1) + self.assertRaises(TypeError, c.addtag_enclosed, 'tag', 0, 0, 1, 2, 3) + self.assertRaises(TclError, c.addtag_closest, 'tag', 'spam', 0) + self.assertRaises(TclError, c.addtag_enclosed, 'tag', 0, 0, 'spam', 0) + self.assertRaises(TclError, c.gettags) # needs an item + + def test_itemconfigure(self): + c = self.create() + rect = c.create_rectangle(10, 10, 30, 30) + c.itemconfigure(rect, fill='red', width=3) + self.assertEqual(str(c.itemcget(rect, 'fill')), 'red') + self.assertEqual(float(c.itemcget(rect, 'width')), 3.0) + + # Querying all options returns a dict; a single one returns its spec. + cnf = c.itemconfigure(rect) + self.assertIsInstance(cnf, dict) + self.assertIn('fill', cnf) + self.assertEqual(c.itemconfigure(rect, 'fill')[-1], 'red') + + # itemconfig is an alias of itemconfigure. + self.assertEqual(c.itemconfig, c.itemconfigure) + + self.assertRaises(TclError, c.itemcget, rect, 'badoption') + self.assertRaises(TclError, c.itemconfigure, rect, badoption='x') + self.assertRaises(TypeError, c.itemcget, rect) + self.assertRaises(TypeError, c.itemcget, rect, 'fill', 'extra') + + def test_tag_raise_lower(self): + c = self.create() + r1 = c.create_rectangle(10, 10, 30, 30) + r2 = c.create_rectangle(50, 50, 70, 70) + r3 = c.create_rectangle(90, 90, 110, 110) + self.assertEqual(c.find_all(), (r1, r2, r3)) + + c.tag_raise(r1) + self.assertEqual(c.find_all(), (r2, r3, r1)) + c.tag_lower(r1) + self.assertEqual(c.find_all(), (r1, r2, r3)) + # Raise above / lower below a specific item. + c.tag_raise(r1, r2) + self.assertEqual(c.find_all(), (r2, r1, r3)) + c.tag_lower(r3, r2) + self.assertEqual(c.find_all(), (r3, r2, r1)) + + # lower/lift are aliases of tag_lower/tag_raise. + self.assertEqual(c.lower, c.tag_lower) + self.assertEqual(c.lift, c.tag_raise) + + # raise/lower need at least an item; an unmatched tag is not an error. + self.assertRaises(TclError, c.tag_raise) + self.assertRaises(TclError, c.tag_lower) + self.assertIsNone(c.tag_raise('nonexistent')) + + def test_text_item(self): + c = self.create() + item = c.create_text(10, 10, text='Hello') + self.assertEqual(c.index(item, 'end'), 5) + self.assertIsInstance(c.index(item, 'end'), int) + + c.insert(item, 'end', ' world') + self.assertEqual(c.itemcget(item, 'text'), 'Hello world') + self.assertEqual(c.index(item, 'end'), 11) + c.insert(item, 0, '>> ') + self.assertEqual(c.itemcget(item, 'text'), '>> Hello world') + + c.dchars(item, 0, 2) + self.assertEqual(c.itemcget(item, 'text'), 'Hello world') + c.icursor(item, 3) + + # index requires an indexable (text) item and a valid index. + self.assertRaises(TclError, c.index, item, 'badspec') + self.assertRaises(TclError, c.index, item) # missing index + self.assertRaises(TclError, c.dchars, item, 'badspec', 'end') + rect = c.create_rectangle(10, 10, 30, 30) + self.assertRaises(TclError, c.index, rect, 'end') + + def test_select(self): + c = self.create() + item = c.create_text(10, 10, text='Hello world') + self.assertIsNone(c.select_item()) + + c.select_from(item, 0) + c.select_to(item, 4) + self.assertEqual(int(c.select_item()), item) + c.select_adjust(item, 6) + + c.select_clear() + self.assertIsNone(c.select_item()) + self.assertRaises(TypeError, c.select_from, item) + self.assertRaises(TypeError, c.select_from, item, 0, 'extra') + # A bad index reaches Tcl; selection applies only to text items. + self.assertRaises(TclError, c.select_from, item, 'badspec') + rect = c.create_rectangle(10, 10, 30, 30) + self.assertRaises(TclError, c.select_from, rect, 0) + + def test_focus(self): + c = self.create() + item = c.create_text(10, 10, text='Hello') + # Only text items can take the focus. + c.focus(item) + self.assertEqual(int(c.focus()), item) + c.focus('') + self.assertIn(c.focus(), ('', None)) + + def test_scan(self): + c = self.create() + c.create_rectangle(10, 10, 300, 300) + c.scan_mark(0, 0) + c.scan_dragto(5, 5) # default gain=10 + c.scan_dragto(5, 5, 1) + self.assertRaises(TypeError, c.scan_mark) + self.assertRaises(TypeError, c.scan_mark, 0, 0, 0) + self.assertRaises(TclError, c.scan_mark, 'spam', 0) + + def test_postscript(self): + c = self.create() + c.create_rectangle(10, 10, 30, 30, fill='black') + ps = c.postscript() + self.assertIsInstance(ps, str) + self.assertStartsWith(ps, '%!PS-Adobe') + self.assertRaises(TclError, c.postscript, badoption='spam') + + def assertCommandExist(self, widget, funcid): + self.assertEqual( + widget.tk.splitlist(widget.tk.call('info', 'commands', funcid)), + (funcid,)) + + def assertCommandNotExist(self, widget, funcid): + self.assertEqual( + widget.tk.splitlist(widget.tk.call('info', 'commands', funcid)), + ()) + + def test_tag_bind(self): + c = self.create() + c.pack() + item = c.create_rectangle(20, 20, 100, 100, fill='red') + self.assertEqual(c.tag_bind(item), ()) + self.assertEqual(c.tag_bind(item, ''), '') + + events = [] + def test1(e): events.append('a') + def test2(e): events.append('b') + + funcid = c.tag_bind(item, '', test1) + self.assertEqual(c.tag_bind(item), ('',)) + script = c.tag_bind(item, '') + self.assertIn(funcid, script) + self.assertCommandExist(c, funcid) + + funcid2 = c.tag_bind(item, '', test2, add=True) + script = c.tag_bind(item, '') + self.assertIn(funcid, script) + self.assertIn(funcid2, script) + self.assertCommandExist(c, funcid) + self.assertCommandExist(c, funcid2) + + c.wait_visibility() + c.focus_force() + c.update() + c.event_generate('', x=50, y=50) + c.update() + self.assertEqual(events, ['a', 'b']) + + # Binding to a tag applies to all items carrying it. + c.addtag_withtag('spam', item) + events.clear() + c.tag_bind('spam', '', test1) + c.event_generate('', x=50, y=50) + c.update() + self.assertEqual(events, ['a']) + + def test_tag_unbind(self): + c = self.create() + c.pack() + item = c.create_rectangle(20, 20, 100, 100, fill='red') + + events = [] + def test1(e): events.append('a') + def test2(e): events.append('b') + + funcid = c.tag_bind(item, '', test1) + funcid2 = c.tag_bind(item, '', test2, add=True) + c.wait_visibility() + c.focus_force() + c.update() + c.event_generate('', x=50, y=50) + c.update() + self.assertEqual(events, ['a', 'b']) + + # Removing one function leaves the other in place. + c.tag_unbind(item, '', funcid) + script = c.tag_bind(item, '') + self.assertNotIn(funcid, script) + self.assertIn(funcid2, script) + self.assertCommandNotExist(c, funcid) + self.assertCommandExist(c, funcid2) + events.clear() + c.event_generate('', x=50, y=50) + c.update() + self.assertEqual(events, ['b']) + + # Without a funcid all bindings for the sequence are removed. + c.tag_unbind(item, '') + self.assertEqual(c.tag_bind(item, ''), '') + self.assertEqual(c.tag_bind(item), ()) + events.clear() + c.event_generate('', x=50, y=50) + c.update() + self.assertEqual(events, []) + + self.assertRaises(TypeError, c.tag_unbind, item) + + +@add_configure_tests(IntegerSizeTests, StandardOptionsTests) +class ListboxTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'activestyle', 'background', 'borderwidth', 'cursor', + 'disabledforeground', 'exportselection', + 'font', 'foreground', 'height', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'justify', 'listvariable', 'relief', + 'selectbackground', 'selectborderwidth', 'selectforeground', + 'selectmode', 'setgrid', 'state', + 'takefocus', 'width', 'xscrollcommand', 'yscrollcommand', + ) + if tk_version < (8, 7): + _clipped = {'highlightthickness'} + else: + _clipped = {'borderwidth', 'highlightthickness', 'selectborderwidth'} + + def create(self, **kwargs): + return tkinter.Listbox(self.root, **kwargs) + + def test_configure_activestyle(self): + widget = self.create() + self.checkEnumParam(widget, 'activestyle', + 'dotbox', 'none', 'underline') + + test_configure_justify = requires_tk(8, 6, 5)(StandardOptionsTests.test_configure_justify) + + def test_configure_listvariable(self): + widget = self.create() + var = tkinter.DoubleVar(self.root) + self.checkVariableParam(widget, 'listvariable', var) + + def test_configure_selectmode(self): + widget = self.create() + self.checkParam(widget, 'selectmode', 'single') + self.checkParam(widget, 'selectmode', 'browse') + self.checkParam(widget, 'selectmode', 'multiple') + self.checkParam(widget, 'selectmode', 'extended') + + def test_configure_state(self): + widget = self.create() + self.checkEnumParam(widget, 'state', 'disabled', 'normal') + + def test_itemconfigure(self): + widget = self.create() + with self.assertRaisesRegex(TclError, 'item number "0" out of range'): + widget.itemconfigure(0) + colors = 'red orange yellow green blue white violet'.split() + widget.insert('end', *colors) + for i, color in enumerate(colors): + widget.itemconfigure(i, background=color) + with self.assertRaises(TypeError): + widget.itemconfigure() + with self.assertRaisesRegex(TclError, 'bad listbox index "red"'): + widget.itemconfigure('red') + if get_tk_patchlevel(self.root) >= (8, 6, 14): + prefix = ('background', '', '', '') + else: + prefix = ('background', 'background', 'Background', '') + self.assertEqual(widget.itemconfigure(0, 'background'), + (*prefix, 'red')) + self.assertEqual(widget.itemconfigure('end', 'background'), + (*prefix, 'violet')) + self.assertEqual(widget.itemconfigure('@0,0', 'background'), + (*prefix, 'red')) + + d = widget.itemconfigure(0) + self.assertIsInstance(d, dict) + for k, v in d.items(): + self.assertIn(len(v), (2, 5)) + if len(v) == 5: + self.assertEqual(v, widget.itemconfigure(0, k)) + self.assertEqual(v[4], widget.itemcget(0, k)) + + def check_itemconfigure(self, name, value): + widget = self.create() + widget.insert('end', 'a', 'b', 'c', 'd') + widget.itemconfigure(0, **{name: value}) + self.assertEqual(widget.itemconfigure(0, name)[4], value) + self.assertEqual(widget.itemcget(0, name), value) + with self.assertRaisesRegex(TclError, 'unknown color name "spam"'): + widget.itemconfigure(0, **{name: 'spam'}) + + def test_itemconfigure_background(self): + self.check_itemconfigure('background', '#ff0000') + + def test_itemconfigure_bg(self): + self.check_itemconfigure('bg', '#ff0000') + + def test_itemconfigure_fg(self): + self.check_itemconfigure('fg', '#110022') + + def test_itemconfigure_foreground(self): + self.check_itemconfigure('foreground', '#110022') + + def test_itemconfigure_selectbackground(self): + self.check_itemconfigure('selectbackground', '#110022') + + def test_itemconfigure_selectforeground(self): + self.check_itemconfigure('selectforeground', '#654321') + + def test_box(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + lb.pack() + self.assertIsBoundingBox(lb.bbox(0)) + self.assertIsNone(lb.bbox(-1)) + self.assertIsNone(lb.bbox(10)) + self.assertRaises(TclError, lb.bbox, 'noindex') + self.assertRaises(TclError, lb.bbox, None) + self.assertRaises(TypeError, lb.bbox) + self.assertRaises(TypeError, lb.bbox, 0, 1) + + def test_curselection(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + lb.selection_clear(0, tkinter.END) + lb.selection_set(2, 4) + lb.selection_set(6) + self.assertEqual(lb.curselection(), (2, 3, 4, 6)) + self.assertRaises(TypeError, lb.curselection, 0) + + def test_get(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + self.assertEqual(lb.get(0), 'el0') + self.assertEqual(lb.get(3), 'el3') + self.assertEqual(lb.get('end'), 'el7') + self.assertEqual(lb.get(8), '') + self.assertEqual(lb.get(-1), '') + self.assertEqual(lb.get(3, 5), ('el3', 'el4', 'el5')) + self.assertEqual(lb.get(5, 'end'), ('el5', 'el6', 'el7')) + self.assertEqual(lb.get(5, 0), ()) + self.assertEqual(lb.get(0, 0), ('el0',)) + self.assertRaises(TclError, lb.get, 'noindex') + self.assertRaises(TclError, lb.get, None) + self.assertRaises(TypeError, lb.get) + self.assertRaises(TclError, lb.get, 'end', 'noindex') + self.assertRaises(TypeError, lb.get, 1, 2, 3) + self.assertRaises(TclError, lb.get, 2.4) + + def test_size(self): + lb = self.create() + self.assertEqual(lb.size(), 0) + lb.insert(0, *('el%d' % i for i in range(8))) + self.assertEqual(lb.size(), 8) + lb.delete(0, 2) + self.assertEqual(lb.size(), 5) + self.assertRaises(TypeError, lb.size, 0) + + def test_delete(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + lb.delete(0) + self.assertEqual(lb.get(0, 'end'), + ('el1', 'el2', 'el3', 'el4', 'el5', 'el6', 'el7')) + lb.delete(2, 4) + self.assertEqual(lb.get(0, 'end'), ('el1', 'el2', 'el6', 'el7')) + lb.delete(0, 'end') + self.assertEqual(lb.size(), 0) + self.assertRaises(TclError, lb.delete, 'noindex') + self.assertRaises(TypeError, lb.delete) + + def test_index(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + self.assertEqual(lb.index(3), 3) + self.assertEqual(lb.index('end'), 8) # the number of elements + lb.activate(4) + self.assertEqual(lb.index('active'), 4) + lb.selection_anchor(2) + self.assertEqual(lb.index('anchor'), 2) + self.assertRaisesRegex(TclError, 'bad listbox index "spam"', + lb.index, 'spam') + + def test_nearest(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + lb.pack() + lb.wait_visibility() + lb.update() + # Derive the line height from the first item, which is always + # displayed (bbox() returns None for items that are not). + x, y, w, h = lb.bbox(0) + self.assertEqual(lb.nearest(y + h // 2), 0) + self.assertEqual(lb.nearest(y + 3 * h + h // 2), 3) + self.assertRaises(TclError, lb.nearest, 'spam') + self.assertRaises(TypeError, lb.nearest) + + def test_see(self): + lb = self.create(height=5) + lb.insert(0, *('el%d' % i for i in range(20))) + lb.pack() + lb.update_idletasks() + lb.see('end') + lb.update_idletasks() + self.assertEqual(lb.yview()[1], 1.0) + lb.see(0) + lb.update_idletasks() + self.assertEqual(lb.yview()[0], 0.0) + self.assertRaises(TclError, lb.see, 'spam') + + def test_activate(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + lb.activate(3) + self.assertEqual(lb.index('active'), 3) + lb.activate('end') + self.assertEqual(lb.index('active'), 7) + self.assertRaises(TclError, lb.activate, 'spam') + self.assertRaises(TypeError, lb.activate) + + def test_selection(self): + lb = self.create() + lb.insert(0, *('el%d' % i for i in range(8))) + self.assertEqual(lb.curselection(), ()) + self.assertFalse(lb.selection_includes(0)) + + lb.selection_set(2, 4) + lb.selection_set(6) + self.assertEqual(lb.curselection(), (2, 3, 4, 6)) + self.assertTrue(lb.selection_includes(3)) + self.assertFalse(lb.selection_includes(5)) + + lb.selection_clear(3, 4) + self.assertEqual(lb.curselection(), (2, 6)) + + lb.selection_anchor(5) + self.assertEqual(lb.index('anchor'), 5) + + # select_* are aliases of the selection_* methods. + lb.select_clear(0, 'end') + self.assertEqual(lb.curselection(), ()) + lb.select_set(1) + self.assertTrue(lb.select_includes(1)) + lb.select_anchor(1) + self.assertEqual(lb.index('anchor'), 1) + + self.assertRaisesRegex(TclError, 'bad listbox index "spam"', + lb.selection_includes, 'spam') + + def test_selection_event(self): + # Keyboard navigation changes the selection and fires the + # <> virtual event. + lb = self.create(selectmode='browse', exportselection=False) + lb.insert(0, *('el%d' % i for i in range(5))) + lb.pack() + self.require_mapped(lb) + events = [] + lb.bind('<>', lambda e: events.append(lb.curselection())) + lb.focus_force() + lb.activate(0) + lb.event_generate('') + lb.event_generate('') + lb.update() + self.assertEqual(events, [(1,), (2,)]) + self.assertEqual(lb.curselection(), (2,)) + + +@add_configure_tests(PixelSizeTests, StandardOptionsTests) +class ScaleTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'background', 'bigincrement', 'borderwidth', + 'command', 'cursor', 'digits', 'font', 'foreground', 'from', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'label', 'length', 'orient', 'relief', + 'repeatdelay', 'repeatinterval', + 'resolution', 'showvalue', 'sliderlength', 'sliderrelief', 'state', + 'takefocus', 'tickinterval', 'to', 'troughcolor', 'variable', 'width', + ) + _clipped = {'highlightthickness'} + default_orient = 'vertical' + + def create(self, **kwargs): + return tkinter.Scale(self.root, **kwargs) + + def test_configure_bigincrement(self): + widget = self.create() + self.checkFloatParam(widget, 'bigincrement', 12.4, 23.6, -5) + + def test_configure_digits(self): + widget = self.create() + self.checkIntegerParam(widget, 'digits', 5, 0) + + def test_configure_from(self): + widget = self.create() + conv = float if get_tk_patchlevel(self.root) >= (8, 6, 10) else float_round + self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=conv) + + def test_configure_label(self): + widget = self.create() + self.checkParam(widget, 'label', 'any string') + self.checkParam(widget, 'label', '') + + def test_configure_length(self): + widget = self.create() + self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i') + + def test_configure_resolution(self): + widget = self.create() + self.checkFloatParam(widget, 'resolution', 4.2, 0, 6.7, -2) + + def test_configure_showvalue(self): + widget = self.create() + self.checkBooleanParam(widget, 'showvalue') + + def test_configure_sliderlength(self): + widget = self.create() + self.checkPixelsParam(widget, 'sliderlength', + 10, 11.2, 15.6, -3, '3m') + + def test_configure_sliderrelief(self): + widget = self.create() + self.checkReliefParam(widget, 'sliderrelief') + + def test_configure_tickinterval(self): + widget = self.create() + self.checkFloatParam(widget, 'tickinterval', 1, 4.3, 7.6, 0, + conv=float_round) + self.checkParam(widget, 'tickinterval', -2, expected=2, + conv=float_round) + + def test_configure_to(self): + widget = self.create() + self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, + conv=float_round) + + def test_identify(self): + widget = self.create() + widget.pack() + # Probe a point on the trough centreline (Scale.coords()) rather than + # a fixed pixel: (5, 5) lies outside the trough and always identifies + # as '', so it would not actually exercise identify(). + if wait_until_mapped(widget): + x, y = widget.coords() + self.assertIn(widget.identify(int(x), int(y)), + ('slider', 'trough1', 'trough2')) + self.assertRaises(TclError, widget.identify, 'a', 'b') + + +@add_configure_tests(PixelSizeTests, StandardOptionsTests) +class ScrollbarTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'activerelief', + 'background', 'borderwidth', + 'command', 'cursor', 'elementborderwidth', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'jump', 'orient', 'relief', + 'repeatdelay', 'repeatinterval', + 'takefocus', 'troughcolor', 'width', + ) + if tk_version < (8, 7): + _clipped = {'highlightthickness'} + elif tk_version < (9, 0): + _clipped = {'borderwidth', 'elementborderwidth', 'highlightthickness'} + else: + _clipped = {'borderwidth', 'elementborderwidth', 'highlightthickness', 'width'} + _clipped_to_default = {'elementborderwidth'} + _stringify = True + default_orient = 'vertical' + + def create(self, **kwargs): + return tkinter.Scrollbar(self.root, **kwargs) + + def test_configure_elementborderwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'elementborderwidth', 4.3, 5.6, -2, '1m') + + def test_configure_orient(self): + widget = self.create() + self.checkEnumParam(widget, 'orient', 'vertical', 'horizontal', + fullname='orientation', allow_empty=True) + + def test_activate(self): + sb = self.create() + for e in ('arrow1', 'slider', 'arrow2'): + sb.activate(e) + self.assertEqual(sb.activate(), e) + sb.activate('') + self.assertIsNone(sb.activate()) + self.assertRaises(TypeError, sb.activate, 'arrow1', 'arrow2') + + def test_set(self): + sb = self.create() + sb.set(0.2, 0.4) + self.assertEqual(sb.get(), (0.2, 0.4)) + self.assertRaises(TclError, sb.set, 'abc', 'def') + self.assertRaises(TclError, sb.set, 0.6, 'def') + self.assertRaises(TclError, sb.set, 0.6, None) + self.assertRaises(TypeError, sb.set, 0.6) + self.assertRaises(TypeError, sb.set, 0.6, 0.7, 0.8) + + def test_fraction(self): + sb = self.create() + sb.pack(fill='y', expand=True) + sb.update_idletasks() + self.assertIsInstance(sb.fraction(0, 0), float) + f = sb.fraction(0, 1000) + self.assertIsInstance(f, float) + self.assertGreaterEqual(f, 0.0) + self.assertLessEqual(f, 1.0) + self.assertRaises(TclError, sb.fraction, 'a', 'b') + self.assertRaises(TypeError, sb.fraction, 0) + + def test_delta(self): + sb = self.create() + sb.pack(fill='y', expand=True) + sb.update_idletasks() + self.assertIsInstance(sb.delta(0, 10), float) + self.assertRaises(TclError, sb.delta, 'a', 'b') + self.assertRaises(TypeError, sb.delta, 0) + + def test_identify(self): + sb = self.create() + sb.pack(fill='y', expand=True) + # Identifying the element under a point requires the widget to be + # mapped with a real size. + if wait_until_mapped(sb): + self.assertIn(sb.identify(5, 5), + ('arrow1', 'arrow2', 'slider', 'trough1', 'trough2')) + self.assertRaises(TclError, sb.identify, 'a', 'b') + + +@add_configure_tests(PixelSizeTests, StandardOptionsTests) +class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'background', 'borderwidth', 'cursor', + 'handlepad', 'handlesize', 'height', + 'opaqueresize', 'orient', + 'proxybackground', 'proxyborderwidth', 'proxyrelief', + 'relief', + 'sashcursor', 'sashpad', 'sashrelief', 'sashwidth', + 'showhandle', 'width', + ) + _no_round = {'handlesize', 'height', 'proxyborderwidth', 'sashwidth', + 'selectborderwidth', 'width'} + _clipped = {} + default_orient = 'horizontal' + + def create(self, **kwargs): + return tkinter.PanedWindow(self.root, **kwargs) + + def test_configure_handlepad(self): + widget = self.create() + self.checkPixelsParam(widget, 'handlepad', 5, 6.4, 7.6, -3, '1m') + + def test_configure_handlesize(self): + widget = self.create() + self.checkPixelsParam(widget, 'handlesize', 8, 9.4, 10.6, -3, '2m') + + def test_configure_opaqueresize(self): + widget = self.create() + self.checkBooleanParam(widget, 'opaqueresize') + + @requires_tk(8, 6, 5) + def test_configure_proxybackground(self): + widget = self.create() + self.checkColorParam(widget, 'proxybackground') + + @requires_tk(8, 6, 5) + def test_configure_proxyborderwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'proxyborderwidth', + 0, 1.3, 2.9, 6, -2, '10p') + + @requires_tk(8, 6, 5) + def test_configure_proxyrelief(self): + widget = self.create() + self.checkReliefParam(widget, 'proxyrelief', + allow_empty=(tk_version >= (8, 7))) + + def test_configure_sashcursor(self): + widget = self.create() + self.checkCursorParam(widget, 'sashcursor') + + def test_configure_sashpad(self): + widget = self.create() + self.checkPixelsParam(widget, 'sashpad', 8, 1.3, 2.6, -2, '2m') + + def test_configure_sashrelief(self): + widget = self.create() + self.checkReliefParam(widget, 'sashrelief') + + def test_configure_sashwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'sashwidth', 10, 11.1, 15.6, -3, '1m') + + def test_configure_showhandle(self): + widget = self.create() + self.checkBooleanParam(widget, 'showhandle') + + def create2(self): + p = self.create() + b = tkinter.Button(p) + c = tkinter.Button(p) + p.add(b) + p.add(c) + return p, b, c + + def test_panes(self): + p, b, c = self.create2() + self.assertEqual([str(x) for x in p.panes()], [str(b), str(c)]) + + def test_remove(self): + p, b, c = self.create2() + p.remove(b) + self.assertEqual([str(x) for x in p.panes()], [str(c)]) + p.forget(c) # forget is an alias of remove. + self.assertEqual(p.panes(), ()) + + def test_sash(self): + p, b, c = self.create2() + p.configure(width=200, height=50) + p.pack() + p.update() + x, y = p.sash_coord(0) + self.assertIsInstance(x, int) + self.assertIsInstance(y, int) + p.sash_place(0, 120, 0) + p.update() + self.assertEqual(p.sash_coord(0)[0], 120) + p.sash_mark(0) # No exception. + self.assertRaises(TclError, p.sash_coord, 5) + + def test_proxy(self): + p, b, c = self.create2() + p.configure(width=200, height=50) + p.pack() + p.update() + p.proxy_place(100, 10) + p.update() + self.assertEqual(p.proxy_coord()[0], 100) + p.proxy_forget() + p.update() + + def test_identify(self): + p, b, c = self.create2() + p.configure(width=200, height=50) + p.pack() + # Locating the sash requires the widget to be mapped with a real + # size; the rest of the checks do not. + if wait_until_mapped(p): + x, y = p.sash_coord(0) + # A point over the sash reports the sash. + self.assertIn('sash', p.identify(x + 1, y + 5)) + # A point over a pane reports nothing. + self.assertFalse(p.identify(2, 2)) + self.assertRaises(TclError, p.identify, 'a', 'b') + + def test_add_options(self): + p = self.create() + b = tkinter.Button(p) + p.add(b, minsize=40, padx=3, sticky='ns') + self.assertEqual(p.panecget(b, 'minsize'), + 40 if self.wantobjects else '40') + self.assertEqual(p.panecget(b, 'padx'), + 3 if self.wantobjects else '3') + self.assertEqual(p.panecget(b, 'sticky'), 'ns') + self.assertRaisesRegex(TclError, 'unknown option "-spam"', + p.add, tkinter.Button(p), spam='x') + self.assertRaisesRegex(TclError, 'bad window path name "spam"', + p.add, 'spam') + + def test_paneconfigure_errors(self): + p, b, c = self.create2() + self.assertRaisesRegex(TclError, 'unknown option "-spam"', + p.paneconfigure, b, spam='x') + self.assertRaises(TclError, p.panecget, b, 'spam') + self.assertRaises(TclError, p.paneconfigure, 'spam') + + def test_paneconfigure(self): + p, b, c = self.create2() + self.assertRaises(TypeError, p.paneconfigure) + d = p.paneconfigure(b) + self.assertIsInstance(d, dict) + for k, v in d.items(): + self.assertEqual(len(v), 5) + self.assertEqual(v, p.paneconfigure(b, k)) + self.assertEqual(v[4], p.panecget(b, k)) + + def check_paneconfigure(self, p, b, name, value, expected): + if not self.wantobjects: + expected = str(expected) + p.paneconfigure(b, **{name: value}) + self.assertEqual(p.paneconfigure(b, name)[4], expected) + self.assertEqual(p.panecget(b, name), expected) + + def check_paneconfigure_bad(self, p, b, name, msg): + with self.assertRaisesRegex(TclError, msg): + p.paneconfigure(b, **{name: 'badValue'}) + + def test_paneconfigure_after(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'after', c, str(c)) + self.check_paneconfigure_bad(p, b, 'after', + 'bad window path name "badValue"') + + def test_paneconfigure_before(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'before', c, str(c)) + self.check_paneconfigure_bad(p, b, 'before', + 'bad window path name "badValue"') + + def test_paneconfigure_height(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'height', 10, 10) + self.check_paneconfigure_bad(p, b, 'height', + EXPECTED_SCREEN_DISTANCE_OR_EMPTY_ERRMSG.format('badValue')) + + def test_paneconfigure_hide(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'hide', False, 0) + self.check_paneconfigure_bad(p, b, 'hide', + 'expected boolean value but got "badValue"') + + def test_paneconfigure_minsize(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'minsize', 10, 10) + self.check_paneconfigure_bad(p, b, 'minsize', + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('badValue')) + + def test_paneconfigure_padx(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'padx', 1.3, 1 if tk_version < (9, 0) else 1.3) + self.check_paneconfigure_bad(p, b, 'padx', + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('badValue')) + + def test_paneconfigure_pady(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'pady', 1.3, 1 if tk_version < (9, 0) else 1.3) + self.check_paneconfigure_bad(p, b, 'pady', + EXPECTED_SCREEN_DISTANCE_ERRMSG.format('badValue')) + + def test_paneconfigure_sticky(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'sticky', 'nsew', 'nesw') + self.check_paneconfigure_bad(p, b, 'sticky', + 'bad stickyness value "badValue": must ' + 'be a string containing zero or more of ' + 'n, e, s, and w') + + def test_paneconfigure_stretch(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'stretch', 'alw', 'always') + self.check_paneconfigure_bad(p, b, 'stretch', + 'bad stretch "badValue": must be ' + 'always, first, last, middle, or never') + + def test_paneconfigure_width(self): + p, b, c = self.create2() + self.check_paneconfigure(p, b, 'width', 10, 10) + self.check_paneconfigure_bad(p, b, 'width', + EXPECTED_SCREEN_DISTANCE_OR_EMPTY_ERRMSG.format('badValue')) + + +@add_configure_tests(StandardOptionsTests) +class MenuTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'activebackground', 'activeborderwidth', 'activeforeground', + 'activerelief', 'background', 'borderwidth', 'cursor', + 'disabledforeground', 'font', 'foreground', + 'postcommand', 'relief', 'selectcolor', 'takefocus', + 'tearoff', 'tearoffcommand', 'title', 'type', + ) + _rounds_pixels = False + _clipped = {} + + def create(self, **kwargs): + return tkinter.Menu(self.root, **kwargs) + + def test_indexcommand_none(self): + widget = self.create() + i = widget.index('none') + self.assertIsNone(i) + + test_configure_activerelief = requires_tk(8, 7)(StandardOptionsTests.test_configure_activerelief) + + def test_configure_postcommand(self): + widget = self.create() + self.checkCommandParam(widget, 'postcommand') + + def test_configure_tearoff(self): + widget = self.create() + self.checkBooleanParam(widget, 'tearoff') + + def test_configure_tearoffcommand(self): + widget = self.create() + self.checkCommandParam(widget, 'tearoffcommand') + + def test_configure_title(self): + widget = self.create() + self.checkParam(widget, 'title', 'any string') + + def test_configure_type(self): + widget = self.create() + values = ('normal', 'tearoff', 'menubar') + self.checkEnumParam(widget, 'type', *values, + allow_empty=tk_version < (8, 7), + sort=tk_version >= (8, 7)) + + def test_entryconfigure(self): + m1 = self.create() + m1.add_command(label='test') + self.assertRaises(TypeError, m1.entryconfigure) + with self.assertRaisesRegex(TclError, 'bad menu entry index "foo"'): + m1.entryconfigure('foo') + d = m1.entryconfigure(1) + self.assertIsInstance(d, dict) + for k, v in d.items(): + self.assertIsInstance(k, str) + self.assertIsInstance(v, tuple) + self.assertEqual(len(v), 5) + self.assertEqual(v[0], k) + self.assertEqual(m1.entrycget(1, k), v[4]) + m1.destroy() + + def test_entryconfigure_label(self): + m1 = self.create() + m1.add_command(label='test') + self.assertEqual(m1.entrycget(1, 'label'), 'test') + m1.entryconfigure(1, label='changed') + self.assertEqual(m1.entrycget(1, 'label'), 'changed') + + def test_entryconfigure_variable(self): + m1 = self.create() + v1 = tkinter.BooleanVar(self.root) + v2 = tkinter.BooleanVar(self.root) + m1.add_checkbutton(variable=v1, onvalue=True, offvalue=False, + label='Nonsense') + self.assertEqual(str(m1.entrycget(1, 'variable')), str(v1)) + m1.entryconfigure(1, variable=v2) + self.assertEqual(str(m1.entrycget(1, 'variable')), str(v2)) + + def test_add(self): + m = self.create(tearoff=False) + m.add_command(label='Command') + m.add_checkbutton(label='Checkbutton') + m.add_radiobutton(label='Radiobutton') + m.add_separator() + m.add_cascade(label='Cascade', menu=tkinter.Menu(m, tearoff=False)) + self.assertEqual(m.index('end'), 4) + self.assertEqual([m.type(i) for i in range(5)], + ['command', 'checkbutton', 'radiobutton', + 'separator', 'cascade']) + self.assertEqual(m.entrycget(0, 'label'), 'Command') + self.assertRaisesRegex(TclError, 'bad menu entry type "spam"', + m.add, 'spam') + + def test_insert(self): + m = self.create(tearoff=False) + m.add_command(label='A') + m.add_command(label='C') + m.insert_command(1, label='B') + m.insert_separator(0) + m.insert_checkbutton('end', label='D') + m.insert_radiobutton(0, label='top') + m.insert_cascade(2, label='sub', + menu=tkinter.Menu(m, tearoff=False)) + self.assertEqual( + [m.type(i) for i in range(m.index('end') + 1)], + ['radiobutton', 'separator', 'cascade', 'command', + 'command', 'command', 'checkbutton']) + self.assertEqual( + [m.entrycget(i, 'label') for i in (3, 4, 5)], + ['A', 'B', 'C']) + self.assertRaisesRegex(TclError, 'bad menu entry type "spam"', + m.insert, 0, 'spam') + self.assertRaisesRegex(TclError, 'bad menu entry index "spam"', + m.insert_command, 'spam', label='z') + + def test_delete(self): + m = self.create(tearoff=False) + commands = [] + for label in 'ABCDE': + m.add_command(label=label, + command=lambda label=label: commands.append(label)) + # The Tcl command for a deleted item is cleaned up. + funcid = str(m.entrycget(2, 'command')) + self.assertEqual( + m.tk.splitlist(m.tk.call('info', 'commands', funcid)), (funcid,)) + + m.delete(2) # Delete a single item ('C'). + self.assertEqual([m.entrycget(i, 'label') for i in range(4)], + ['A', 'B', 'D', 'E']) + self.assertEqual( + m.tk.splitlist(m.tk.call('info', 'commands', funcid)), ()) + + m.delete(1, 2) # Delete a range ('B' and 'D'). + self.assertEqual([m.entrycget(i, 'label') for i in range(2)], + ['A', 'E']) + self.assertRaises(TypeError, m.delete) + + def test_index(self): + m = self.create(tearoff=False) + self.assertIsNone(m.index('end')) + m.add_command(label='First') + m.add_command(label='Second') + self.assertEqual(m.index('end'), 1) + self.assertEqual(m.index('last'), 1) + self.assertEqual(m.index('Second'), 1) + self.assertEqual(m.index(0), 0) + # 'active' and 'none' map to None when no item is active. + self.assertIsNone(m.index('active')) + self.assertIsNone(m.index('none')) + self.assertRaisesRegex(TclError, 'bad menu entry index "spam"', + m.index, 'spam') + + def test_invoke(self): + m = self.create(tearoff=False) + commands = [] + m.add_command(label='Command', + command=lambda: commands.append('invoked')) + var = tkinter.IntVar(self.root) + m.add_checkbutton(label='Check', variable=var, + onvalue=1, offvalue=0) + rvar = tkinter.StringVar(self.root) + m.add_radiobutton(label='Radio', variable=rvar, value='on') + + m.invoke(0) + self.assertEqual(commands, ['invoked']) + m.invoke(1) + self.assertEqual(var.get(), 1) + m.invoke(1) + self.assertEqual(var.get(), 0) + m.invoke(2) + self.assertEqual(rvar.get(), 'on') + self.assertRaisesRegex(TclError, 'bad menu entry index "spam"', + m.invoke, 'spam') + + def test_xposition_yposition(self): + m = self.create(tearoff=False) + m.add_command(label='First') + m.add_command(label='Second') + m.update_idletasks() + self.assertIsInstance(m.xposition(0), int) + y0 = m.yposition(0) + y1 = m.yposition(1) + self.assertIsInstance(y0, int) + self.assertLess(y0, y1) + # An out-of-range index gives the position past the last item. + self.assertEqual(m.xposition('end'), m.xposition(1)) + self.assertRaisesRegex(TclError, 'bad menu entry index "spam"', + m.xposition, 'spam') + self.assertRaisesRegex(TclError, 'bad menu entry index "spam"', + m.yposition, 'spam') + + def test_post_unpost(self): + m = self.create(tearoff=False) + if m._windowingsystem != 'x11': + # Posting a menu is modal on Windows and uses a native, unmapped + # menu on Aqua, so it cannot be tested synchronously there. + self.skipTest('menu posting is not testable on this platform') + m.add_command(label='First') + m.add_command(label='Second') + self.assertFalse(m.winfo_ismapped()) + + m.post(0, 0) + m.update() + self.assertTrue(m.winfo_ismapped()) + m.unpost() + m.update() + self.assertFalse(m.winfo_ismapped()) + + m.tk_popup(0, 0) + m.update() + self.assertTrue(m.winfo_ismapped()) + m.unpost() + m.update() + self.assertFalse(m.winfo_ismapped()) + + def check_entry_option(self, m, index, option, value, expected=None): + if expected is None: + expected = value + m.entryconfigure(index, **{option: value}) + self.assertEqual(str(m.entrycget(index, option)), str(expected)) + self.assertEqual(str(m.entryconfigure(index, option)[4]), str(expected)) + + def test_entry_options(self): + m = self.create(tearoff=False) + m.add_command(label='Command') + self.check_entry_option(m, 0, 'accelerator', 'Ctrl+O') + self.check_entry_option(m, 0, 'underline', 2) + self.check_entry_option(m, 0, 'state', 'disabled') + self.check_entry_option(m, 0, 'background', 'red') + self.check_entry_option(m, 0, 'foreground', 'blue') + self.check_entry_option(m, 0, 'columnbreak', 1) + self.check_entry_option(m, 0, 'hidemargin', 1) + + m.add_checkbutton(label='Checkbutton') + self.check_entry_option(m, 1, 'onvalue', 'Y') + self.check_entry_option(m, 1, 'offvalue', 'N') + self.check_entry_option(m, 1, 'indicatoron', 0) + + m.add_radiobutton(label='Radiobutton') + self.check_entry_option(m, 2, 'value', 'V') + self.check_entry_option(m, 2, 'selectcolor', 'green') + + def test_entry_options_invalid(self): + m = self.create(tearoff=False) + m.add_command(label='Command') + self.assertRaisesRegex(TclError, 'unknown option "-spam"', + m.entrycget, 0, 'spam') + self.assertRaisesRegex(TclError, 'unknown option "-spam"', + m.entryconfigure, 0, spam='x') + self.assertRaisesRegex(TclError, 'bad state "spam"', + m.entryconfigure, 0, state='spam') + # Tk < 9 reports "expected integer but got ...", while Tk 9, where + # underline accepts an index, reports "bad index ...". + self.assertRaisesRegex(TclError, + r'(expected integer but got|bad index) "spam"', + m.entryconfigure, 0, underline='spam') + self.assertRaisesRegex(TclError, 'unknown color name "spam"', + m.entryconfigure, 0, background='spam') + self.assertRaisesRegex(TclError, 'expected boolean value but got "spam"', + m.entryconfigure, 0, columnbreak='spam') + # onvalue applies only to checkbutton and radiobutton entries. + self.assertRaisesRegex(TclError, 'unknown option "-onvalue"', + m.entrycget, 0, 'onvalue') + + +@add_configure_tests(PixelSizeTests, StandardOptionsTests) +class MessageTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'anchor', 'aspect', 'background', 'borderwidth', + 'cursor', 'font', 'foreground', + 'highlightbackground', 'highlightcolor', 'highlightthickness', + 'justify', 'padx', 'pady', 'relief', + 'takefocus', 'text', 'textvariable', 'width', + ) + _no_round = {'padx', 'pady'} + if tk_version < (8, 7): + _clipped = {'highlightthickness'} + else: + _clipped = {'borderwidth', 'highlightthickness', 'padx', 'pady', 'width'} + _clipped_to_default = {'padx', 'pady'} + + def create(self, **kwargs): + return tkinter.Message(self.root, **kwargs) + + def test_configure_aspect(self): + widget = self.create() + self.checkIntegerParam(widget, 'aspect', 250, 0, -300) + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_frame(self): + self._test_widget(tkinter.Frame) + + def test_label(self): + self._test_widget(tkinter.Label) + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_tkinter/widget_tests.py b/Lib/test/test_tkinter/widget_tests.py new file mode 100644 index 00000000000..014906cba29 --- /dev/null +++ b/Lib/test/test_tkinter/widget_tests.py @@ -0,0 +1,628 @@ +# Common tests for test_tkinter/test_widgets.py and test_ttk/test_widgets.py + +import re +import tkinter +from test.test_tkinter.support import (AbstractTkTest, requires_tk, tk_version, + pixels_conv, tcl_obj_eq) +import test.support + +_sentinel = object() + +# Abbreviated option names accepted by Tk in addition to the full names. +_OPTION_ALIASES = { + 'bd': 'borderwidth', + 'bg': 'background', + 'bgimg': 'backgroundimage', + 'fg': 'foreground', + 'invcmd': 'invalidcommand', + 'vcmd': 'validatecommand', +} + +# Options which accept all values allowed by Tk_GetPixels +# borderwidth = bd + +class AbstractWidgetTest(AbstractTkTest): + _default_pixels = '' if tk_version >= (9, 0) else -1 # Value for unset pixel options. + _rounds_pixels = (tk_version < (9, 0)) # True if some pixel options are rounded. + _no_round = set() # Pixel options which are not rounded nonetheless + _stringify = False # Whether to convert tuples to strings + _allow_empty_justify = False + _clipped_to_default = set() + + @property + def scaling(self): + try: + return self._scaling + except AttributeError: + self._scaling = float(self.root.call('tk', 'scaling')) + return self._scaling + + def _str(self, value): + if not self._stringify and self.wantobjects and tk_version >= (8, 6): + return value + if isinstance(value, tuple): + return ' '.join(map(self._str, value)) + return str(value) + + def assertEqual2(self, actual, expected, msg=None, eq=object.__eq__): + if eq(actual, expected): + return + self.assertEqual(actual, expected, msg) + + def checkParam(self, widget, name, value, *, expected=_sentinel, + conv=False, eq=None): + widget[name] = value + if expected is _sentinel: + expected = value + if name in self._clipped: + if not isinstance(expected, str) and expected < 0: + if tk_version >= (8, 7) and name in self._clipped_to_default: + expected = self._default_pixels + else: + expected = 0 + if conv: + expected = conv(expected) + if self._stringify or not self.wantobjects: + if isinstance(expected, tuple): + expected = tkinter._join(expected) + else: + expected = str(expected) + if eq is None: + eq = tcl_obj_eq + self.assertEqual2(widget[name], expected, eq=eq) + self.assertEqual2(widget.cget(name), expected, eq=eq) + t = widget.configure(name) + self.assertEqual(len(t), 5) + self.assertEqual2(t[4], expected, eq=eq) + + def checkInvalidParam(self, widget, name, value, errmsg=None): + orig = widget[name] + if errmsg is not None: + errmsg = errmsg.format(re.escape(str(value))) + errmsg = fr'\A{errmsg}\z' + with self.assertRaisesRegex(tkinter.TclError, errmsg or ''): + widget[name] = value + self.assertEqual(widget[name], orig) + with self.assertRaisesRegex(tkinter.TclError, errmsg or ''): + widget.configure({name: value}) + self.assertEqual(widget[name], orig) + + def checkParams(self, widget, name, *values, **kwargs): + for value in values: + self.checkParam(widget, name, value, **kwargs) + + def checkIntegerParam(self, widget, name, *values, **kwargs): + self.checkParams(widget, name, *values, **kwargs) + errmsg = 'expected integer but got "{}"' + self.checkInvalidParam(widget, name, '', errmsg=errmsg) + self.checkInvalidParam(widget, name, '10p', errmsg=errmsg) + self.checkInvalidParam(widget, name, 3.2, errmsg=errmsg) + + def checkFloatParam(self, widget, name, *values, conv=float, **kwargs): + for value in values: + self.checkParam(widget, name, value, conv=conv, **kwargs) + errmsg = 'expected floating-point number but got "{}"' + self.checkInvalidParam(widget, name, '', errmsg=errmsg) + self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) + + def checkBooleanParam(self, widget, name): + for value in (False, 0, 'false', 'no', 'off'): + self.checkParam(widget, name, value, expected=0) + for value in (True, 1, 'true', 'yes', 'on'): + self.checkParam(widget, name, value, expected=1) + errmsg = 'expected boolean value but got "{}"' + self.checkInvalidParam(widget, name, '', errmsg=errmsg) + self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) + + def checkColorParam(self, widget, name, *, allow_empty=None, **kwargs): + self.checkParams(widget, name, + '#ff0000', '#00ff00', '#0000ff', '#123456', + 'red', 'green', 'blue', 'white', 'black', 'grey', + **kwargs) + self.checkInvalidParam(widget, name, 'spam', + errmsg='unknown color name "spam"') + + def checkCursorParam(self, widget, name, **kwargs): + self.checkParams(widget, name, 'arrow', 'watch', 'cross', '',**kwargs) + self.checkParam(widget, name, 'none') + self.checkInvalidParam(widget, name, 'spam', + errmsg='bad cursor spec "spam"') + + def checkCommandParam(self, widget, name): + def command(*args): + pass + widget[name] = command + self.assertTrue(widget[name]) + self.checkParams(widget, name, '') + + def checkEnumParam(self, widget, name, *values, + errmsg=None, allow_empty=False, fullname=None, + sort=False, **kwargs): + self.checkParams(widget, name, *values, **kwargs) + if errmsg is None: + if sort: + if values[-1]: + values = tuple(sorted(values)) + else: + values = tuple(sorted(values[:-1])) + ('',) + errmsg2 = ' %s "{}": must be %s%s or %s' % ( + fullname or name, + ', '.join(values[:-1]), + ',' if len(values) > 2 else '', + values[-1] or '""') + if '' not in values and not allow_empty: + self.checkInvalidParam(widget, name, '', + errmsg='ambiguous' + errmsg2) + errmsg = 'bad' + errmsg2 + self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) + + def checkPixelsParam(self, widget, name, *values, conv=None, **kwargs): + if conv is None: + if self._rounds_pixels and name not in self._no_round: + conv = round + alow_neg = tk_version < (9, 1) + for value in values: + expected = _sentinel + conv1 = conv + if isinstance(value, str): + if not getattr(self, '_converts_pixels', True): + conv1 = str + if conv1 and conv1 is not str: + expected = pixels_conv(value) * self.scaling + conv1 = round + elif not alow_neg and isinstance(value, (int, float)) and value < 0: + self.checkInvalidParam(widget, name, value) + continue + self.checkParam(widget, name, value, expected=expected, + conv=conv1, **kwargs) + errmsg = '(bad|expected) screen distance ((or "" )?but got )?"{}"' + self.checkInvalidParam(widget, name, '6x', errmsg=errmsg) + self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) + + def checkReliefParam(self, widget, name, *, allow_empty=False): + values = ('flat', 'groove', 'raised', 'ridge', 'solid', 'sunken') + if allow_empty: + values += ('',) + self.checkParams(widget, name, *values) + errmsg = 'bad relief "{}": must be %s, or %s' % ( + ', '.join(values[:-1]), + values[-1] or '""') + if tk_version < (8, 6): + errmsg = None + self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) + + def checkImageParam(self, widget, name): + image = tkinter.PhotoImage(master=self.root, name='image1') + self.checkParam(widget, name, image, conv=str) + if tk_version < (8, 7): + errmsg = 'image "spam" doesn\'t exist' + else: + errmsg = 'image "spam" does not exist' + self.checkInvalidParam(widget, name, 'spam', + errmsg=errmsg) + widget[name] = '' + + def checkVariableParam(self, widget, name, var): + self.checkParam(widget, name, var, conv=str) + + def assertIsBoundingBox(self, bbox): + self.assertIsNotNone(bbox) + self.assertIsInstance(bbox, tuple) + if len(bbox) != 4: + self.fail('Invalid bounding box: %r' % (bbox,)) + for item in bbox: + if not isinstance(item, int): + self.fail('Invalid bounding box: %r' % (bbox,)) + break + + + def test_keys(self): + widget = self.create() + keys = widget.keys() + self.assertEqual(sorted(keys), sorted(widget.configure())) + for k in keys: + widget[k] + # Test if OPTIONS contains all keys + if test.support.verbose: + keys = set(keys) + expected = set(self.OPTIONS) + for k in sorted(keys - expected): + if not (k in _OPTION_ALIASES and + _OPTION_ALIASES[k] in keys and + _OPTION_ALIASES[k] in expected): + print('%s.OPTIONS doesn\'t contain "%s"' % + (self.__class__.__name__, k)) + + def test_options_in_docstring(self): + # Every option in OPTIONS must be listed in the docstring of the + # __init__ method (see gh-78335). Options reported by keys() but + # missing from the docstring are only printed in verbose mode, as + # some of them depend on the Tk version. + widget = self.create() + doc = type(widget).__init__.__doc__ + if doc is None: + self.skipTest('docstrings are not available (run with -OO)') + # Look at the option list only, not the leading description. + start = doc.find('Valid option names') + if start < 0: + start = doc.find('OPTIONS') + if start < 0: + self.skipTest('the __init__ docstring does not list options') + documented = set(re.findall(r'[a-z][a-z0-9]+', doc[start:])) + def is_documented(option): + return (option in documented or + _OPTION_ALIASES.get(option) in documented) + missing = sorted(o for o in self.OPTIONS if not is_documented(o)) + self.assertEqual(missing, [], + '%s options missing from the __init__ docstring: %s' + % (type(widget).__name__, missing)) + if test.support.verbose: + for key in sorted(set(widget.keys())): + if not is_documented(key): + print('%s.__init__ docstring doesn\'t contain "%s"' + % (type(widget).__name__, key)) + +class PixelOptionsTests: + """Standard options that accept all formats acceptable to Tk_GetPixels. + + In addition to numbers, these options can be set with distances + specified as a string consisting of a number followed by a single + character giving the unit of distance. The allowed units are: + millimeters ('m'), centimeters ('c'), inches ('i') or points ('p'). + In Tk 9 a cget call for one of these options returns a Tcl_Obj of + type "pixels", whose string representation is the distance string + passed to configure. + """ + PIXEL_OPTIONS = ('activeborderwidth', 'borderwidth', 'highlightthickness', + 'insertborderwidth', 'insertwidth', 'padx', 'pady', 'selectborderwidth') + + def test_configure_activeborderwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'activeborderwidth', + 0, 1.3, 2.9, 6, -2, '10p') + + def test_configure_borderwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'borderwidth', + 0, 1.3, 2.6, 6, -2, '10p') + + if 'bd' in self.OPTIONS: + self.checkPixelsParam(widget, 'bd', 0, 1.3, 2.6, 6, '10p') + self.checkParam(widget, 'bd', -2, expected=expected) + + def test_configure_highlightthickness(self): + widget = self.create() + self.checkPixelsParam(widget, 'highlightthickness', + 0, 1.3, 2.6, 6, -2, '10p') + + def test_configure_insertborderwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'insertborderwidth', 0, 1.3, 2.6, 6, -2, '10p') + + def test_configure_insertwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'insertwidth', 1.3, 2.6, -2, '10p') + + def test_configure_padx(self): + widget = self.create() + self.checkPixelsParam(widget, 'padx', 3, 4.4, 5.6, -2, '12m') + + def test_configure_pady(self): + widget = self.create() + self.checkPixelsParam(widget, 'pady', 3, 4.4, 5.6, -2, '12m') + + def test_configure_selectborderwidth(self): + widget = self.create() + self.checkPixelsParam(widget, 'selectborderwidth', 1.3, 2.6, -2, '10p') + + +class StandardOptionsTests(PixelOptionsTests): + + STANDARD_OPTIONS = ( 'activebackground', 'activeforeground', + 'anchor', 'background', 'bitmap', 'compound', 'cursor', + 'disabledforeground', 'exportselection', 'font', 'foreground', + 'highlightbackground', 'highlightcolor', 'image', + 'insertbackground', 'insertofftime', 'insertontime', 'jump', + 'justify', 'orient', 'relief', 'repeatdelay', 'repeatinterval', + 'selectbackground', 'selectforeground', 'setgrid', 'takefocus', + 'text', 'textvariable', 'troughcolor', 'underline', 'wraplength', + 'xscrollcommand', 'yscrollcommand', ) + PixelOptionsTests.PIXEL_OPTIONS + + def test_configure_activebackground(self): + widget = self.create() + self.checkColorParam(widget, 'activebackground') + + def test_configure_activeforeground(self): + widget = self.create() + self.checkColorParam(widget, 'activeforeground') + + def test_configure_activerelief(self): + widget = self.create() + self.checkReliefParam(widget, 'activerelief') + + def test_configure_anchor(self): + widget = self.create() + self.checkEnumParam(widget, 'anchor', + 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center') + + def test_configure_background(self): + widget = self.create() + self.checkColorParam(widget, 'background') + if 'bg' in self.OPTIONS: + self.checkColorParam(widget, 'bg') + + @requires_tk(8, 7) + def test_configure_backgroundimage(self): + widget = self.create() + self.checkImageParam(widget, 'backgroundimage') + + def test_configure_bitmap(self): + widget = self.create() + self.checkParam(widget, 'bitmap', 'questhead') + self.checkParam(widget, 'bitmap', 'gray50') + filename = test.support.findfile('python.xbm', subdir='tkinterdata') + self.checkParam(widget, 'bitmap', '@' + filename) + # Cocoa Tk widgets don't detect invalid -bitmap values + # See https://core.tcl.tk/tk/info/31cd33dbf0 + if not ('aqua' in self.root.tk.call('tk', 'windowingsystem') and + 'AppKit' in self.root.winfo_server()): + self.checkInvalidParam(widget, 'bitmap', 'spam', + errmsg='bitmap "spam" not defined') + + def test_configure_compound(self): + widget = self.create() + self.checkEnumParam(widget, 'compound', + 'bottom', 'center', 'left', 'none', 'right', 'top') + + def test_configure_cursor(self): + widget = self.create() + self.checkCursorParam(widget, 'cursor') + + def test_configure_disabledforeground(self): + widget = self.create() + self.checkColorParam(widget, 'disabledforeground') + + def test_configure_exportselection(self): + widget = self.create() + self.checkBooleanParam(widget, 'exportselection') + + def test_configure_font(self): + widget = self.create() + self.checkParam(widget, 'font', + '-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*') + is_ttk = widget.__class__.__module__ == 'tkinter.ttk' + if not is_ttk: + errmsg = 'font "" does ?n[o\']t exist' + self.checkInvalidParam(widget, 'font', '', errmsg=errmsg) + + def test_configure_foreground(self): + widget = self.create() + self.checkColorParam(widget, 'foreground') + if 'fg' in self.OPTIONS: + self.checkColorParam(widget, 'fg') + + def test_configure_highlightbackground(self): + widget = self.create() + self.checkColorParam(widget, 'highlightbackground') + + def test_configure_highlightcolor(self): + widget = self.create() + self.checkColorParam(widget, 'highlightcolor') + + def test_configure_image(self): + widget = self.create() + self.checkImageParam(widget, 'image') + + def test_configure_insertbackground(self): + widget = self.create() + self.checkColorParam(widget, 'insertbackground') + + def test_configure_insertofftime(self): + widget = self.create() + self.checkIntegerParam(widget, 'insertofftime', 100) + + def test_configure_insertontime(self): + widget = self.create() + self.checkIntegerParam(widget, 'insertontime', 100) + + def test_configure_jump(self): + widget = self.create() + self.checkBooleanParam(widget, 'jump') + + def test_configure_justify(self): + widget = self.create() + values = ('left', 'right', 'center') + if self._allow_empty_justify: + values += ('',) + self.checkEnumParam(widget, 'justify', *values, + fullname='justification') + + def test_configure_orient(self): + widget = self.create() + self.assertEqual(str(widget['orient']), self.default_orient) + self.checkEnumParam(widget, 'orient', 'horizontal', 'vertical') + + @requires_tk(8, 7) + def test_configure_placeholder(self): + widget = self.create() + self.checkParam(widget, 'placeholder', 'xxx') + + @requires_tk(8, 7) + def test_configure_placeholderforeground(self): + widget = self.create() + self.checkColorParam(widget, 'placeholderforeground') + + def test_configure_relief(self): + widget = self.create() + self.checkReliefParam(widget, 'relief') + + def test_configure_repeatdelay(self): + widget = self.create() + self.checkIntegerParam(widget, 'repeatdelay', -500, 500) + + def test_configure_repeatinterval(self): + widget = self.create() + self.checkIntegerParam(widget, 'repeatinterval', -500, 500) + + def test_configure_selectbackground(self): + widget = self.create() + self.checkColorParam(widget, 'selectbackground') + + def test_configure_selectforeground(self): + widget = self.create() + self.checkColorParam(widget, 'selectforeground') + + def test_configure_setgrid(self): + widget = self.create() + self.checkBooleanParam(widget, 'setgrid') + + def test_configure_state(self): + widget = self.create() + self.checkEnumParam(widget, 'state', 'active', 'disabled', 'normal') + + def test_configure_takefocus(self): + widget = self.create() + self.checkParams(widget, 'takefocus', '0', '1', '') + + def test_configure_text(self): + widget = self.create() + self.checkParams(widget, 'text', '', 'any string') + + def test_configure_textvariable(self): + widget = self.create() + var = tkinter.StringVar(self.root) + self.checkVariableParam(widget, 'textvariable', var) + + @requires_tk(8, 7) + def test_configure_tile(self): + widget = self.create() + self.checkBooleanParam(widget, 'tile') + + def test_configure_troughcolor(self): + widget = self.create() + self.checkColorParam(widget, 'troughcolor') + + def test_configure_underline(self): + widget = self.create() + self.checkParams(widget, 'underline', 0, 1, 10) + if tk_version >= (8, 7): + is_ttk = widget.__class__.__module__ == 'tkinter.ttk' + self.checkParam(widget, 'underline', '', + expected='' if is_ttk else self._default_pixels) + self.checkParam(widget, 'underline', '5+2', + expected='5+2' if is_ttk else 7) + self.checkParam(widget, 'underline', '5-2', + expected='5-2' if is_ttk else 3) + self.checkParam(widget, 'underline', 'end', expected='end') + self.checkParam(widget, 'underline', 'end-2', expected='end-2') + errmsg = (r'bad index "{}": must be integer\?\[\+-\]integer\?, ' + r'end\?\[\+-\]integer\?, or ""') + else: + errmsg = 'expected integer but got "{}"' + self.checkInvalidParam(widget, 'underline', '', errmsg=errmsg) + self.checkInvalidParam(widget, 'underline', '10p', errmsg=errmsg) + self.checkInvalidParam(widget, 'underline', 3.2, errmsg=errmsg) + + def test_configure_wraplength(self): + widget = self.create() + self.checkPixelsParam(widget, 'wraplength', 100) + + def test_configure_xscrollcommand(self): + widget = self.create() + self.checkCommandParam(widget, 'xscrollcommand') + + def test_configure_yscrollcommand(self): + widget = self.create() + self.checkCommandParam(widget, 'yscrollcommand') + + # non-standard but common options + + def test_configure_command(self): + widget = self.create() + self.checkCommandParam(widget, 'command') + + def test_configure_indicatoron(self): + widget = self.create() + self.checkBooleanParam(widget, 'indicatoron') + + def test_configure_offrelief(self): + widget = self.create() + self.checkReliefParam(widget, 'offrelief') + + def test_configure_overrelief(self): + widget = self.create() + self.checkReliefParam(widget, 'overrelief', + allow_empty=(tk_version >= (8, 7))) + + def test_configure_selectcolor(self): + widget = self.create() + self.checkColorParam(widget, 'selectcolor') + + def test_configure_selectimage(self): + widget = self.create() + self.checkImageParam(widget, 'selectimage') + + def test_configure_tristateimage(self): + widget = self.create() + self.checkImageParam(widget, 'tristateimage') + + def test_configure_tristatevalue(self): + widget = self.create() + self.checkParam(widget, 'tristatevalue', 'unknowable') + + def test_configure_variable(self): + widget = self.create() + var = tkinter.DoubleVar(self.root) + self.checkVariableParam(widget, 'variable', var) + + +class IntegerSizeTests: + """ Tests widgets which only accept integral width and height.""" + def test_configure_height(self): + widget = self.create() + self.checkIntegerParam(widget, 'height', 100, -100, 0) + + def test_configure_width(self): + widget = self.create() + self.checkIntegerParam(widget, 'width', 402, -402, 0) + + +class PixelSizeTests: + """ Tests widgets which accept screen distances for width and height.""" + def test_configure_height(self): + widget = self.create() + self.checkPixelsParam(widget, 'height', 100, 101.2, 102.6, -100, 0, '3c') + + def test_configure_width(self): + widget = self.create() + self.checkPixelsParam(widget, 'width', 402, 403.4, 404.6, -402, 0, '5i') + + +def add_configure_tests(*source_classes): + # This decorator adds test_configure_xxx methods from source classes for + # every xxx option in the OPTIONS class attribute if they are not defined + # explicitly. + def decorator(cls): + for option in cls.OPTIONS: + methodname = 'test_configure_' + option + if not hasattr(cls, methodname): + for source_class in source_classes: + if hasattr(source_class, methodname): + setattr(cls, methodname, + getattr(source_class, methodname)) + break + else: + def test(self, option=option): + widget = self.create() + widget[option] + raise AssertionError('Option "%s" is not tested in %s' % + (option, cls.__name__)) + test.__name__ = methodname + setattr(cls, methodname, test) + return cls + return decorator + +def setUpModule(): + if test.support.verbose: + tcl = tkinter.Tcl() + print('patchlevel =', tcl.call('info', 'patchlevel'), flush=True) diff --git a/Lib/test/test_tokenize.py b/Lib/test/test_tokenize.py index 0e81c6f6db2..62b73da225a 100644 --- a/Lib/test/test_tokenize.py +++ b/Lib/test/test_tokenize.py @@ -1233,6 +1233,20 @@ def test_multiline_non_ascii_fstring_with_expr(self): FSTRING_END \'"\' (2, 2) (2, 3) """) + def test_ineq_tokens(self): + self.check_tokenize("1 != 2", """\ + NUMBER '1' (1, 0) (1, 1) + OP '!=' (1, 2) (1, 4) + NUMBER '2' (1, 5) (1, 6) +""") + self.check_tokenize("1 <> 2", """\ + NUMBER '1' (1, 0) (1, 1) + OP '<' (1, 2) (1, 3) + OP '>' (1, 3) (1, 4) + NUMBER '2' (1, 5) (1, 6) +""") + + class GenerateTokensTest(TokenizeTest): def check_tokenize(self, s, expected): # Format the tokens in s in a table format. @@ -1907,7 +1921,6 @@ def test_comment_at_the_end_of_the_source_without_newline(self): tokens = list(tokenize.tokenize(BytesIO(source.encode('utf-8')).readline)) self.assertEqual(tokens, expected_tokens) - @unittest.expectedFailure # TODO: RUSTPYTHON; Diff is 869 characters long. Set self.maxDiff to None to see it. def test_newline_and_space_at_the_end_of_the_source_without_newline(self): # See https://github.com/python/cpython/issues/105435 source = 'a\n ' @@ -2226,7 +2239,6 @@ def test_number_followed_by_name(self): tokens = list(tokenize.generate_tokens(StringIO(source).readline)) self.assertEqual(tokens, expected_tokens) - @unittest.expectedFailure # TODO: RUSTPYTHON; Diff is 855 characters long. Set self.maxDiff to None to see it. def test_number_starting_with_zero(self): source = "01234" expected_tokens = [ @@ -2867,7 +2879,6 @@ def test_tabs(self): NAME 'pass' (2, 14) (2, 18) """) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_async(self): self.check_tokenize('async = 1', """\ @@ -3193,7 +3204,6 @@ def get_tokens(string): with self.subTest(case=case): self.assertRaises(tokenize.TokenError, get_tokens, case) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: IndentationError not raised by @support.skip_wasi_stack_overflow() def test_max_indent(self): MAXINDENT = 100 @@ -3217,7 +3227,6 @@ def generate_source(indents): IndentationError, compile, invalid, "", "exec" ) - @unittest.expectedFailure # TODO: RUSTPYTHON; (0, '')] def test_continuation_lines_indentation(self): def get_tokens(string): the_string = StringIO(string) @@ -3333,6 +3342,7 @@ def test_newline_at_the_end_of_buffer(self): run_test_script(file_name) +@support.force_not_colorized_test_class class CommandLineTest(unittest.TestCase): def setUp(self): self.filename = tempfile.mktemp() diff --git a/Lib/test/test_tomllib/burntsushi.py b/Lib/test/test_tomllib/burntsushi.py index 71228c65369..0ec50eb1a98 100644 --- a/Lib/test/test_tomllib/burntsushi.py +++ b/Lib/test/test_tomllib/burntsushi.py @@ -7,19 +7,8 @@ import datetime from typing import Any -# Aliases for converting TOML compliance format [1] to BurntSushi format [2] -# [1] https://github.com/toml-lang/compliance/blob/db7c3211fda30ff9ddb10292f4aeda7e2e10abc4/docs/json-encoding.md # noqa: E501 -# [2] https://github.com/BurntSushi/toml-test/blob/4634fdf3a6ecd6aaea5f4cdcd98b2733c2694993/README.md # noqa: E501 -_aliases = { - "boolean": "bool", - "offset datetime": "datetime", - "local datetime": "datetime-local", - "local date": "date-local", - "local time": "time-local", -} - - -def convert(obj): # noqa: C901 + +def convert(obj): if isinstance(obj, str): return {"type": "string", "value": obj} elif isinstance(obj, bool): @@ -53,31 +42,25 @@ def convert(obj): # noqa: C901 def normalize(obj: Any) -> Any: """Normalize test objects. - This normalizes primitive values (e.g. floats), and also converts from - TOML compliance format [1] to BurntSushi format [2]. - - [1] https://github.com/toml-lang/compliance/blob/db7c3211fda30ff9ddb10292f4aeda7e2e10abc4/docs/json-encoding.md # noqa: E501 - [2] https://github.com/BurntSushi/toml-test/blob/4634fdf3a6ecd6aaea5f4cdcd98b2733c2694993/README.md # noqa: E501 - """ + This normalizes primitive values (e.g. floats).""" if isinstance(obj, list): return [normalize(item) for item in obj] if isinstance(obj, dict): if "type" in obj and "value" in obj: type_ = obj["type"] - norm_type = _aliases.get(type_, type_) value = obj["value"] - if norm_type == "float": + if type_ == "float": norm_value = _normalize_float_str(value) - elif norm_type in {"datetime", "datetime-local"}: + elif type_ in {"datetime", "datetime-local"}: norm_value = _normalize_datetime_str(value) - elif norm_type == "time-local": + elif type_ == "time-local": norm_value = _normalize_localtime_str(value) else: norm_value = value - if norm_type == "array": + if type_ == "array": return [normalize(item) for item in value] - return {"type": norm_type, "value": norm_value} + return {"type": type_, "value": norm_value} return {k: normalize(v) for k, v in obj.items()} raise AssertionError("Burntsushi fixtures should be dicts/lists only") diff --git a/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.json b/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.json index 99aca873480..09a7c083d14 100644 --- a/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.json +++ b/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.json @@ -1,4 +1,5 @@ { "local-dt": {"type":"datetime-local","value":"1988-10-27t01:01:01"}, + "local-dt-no-seconds": {"type":"datetime-local","value":"2025-04-18t20:05:00"}, "zulu-dt": {"type":"datetime","value":"1988-10-27t01:01:01z"} } diff --git a/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.toml b/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.toml index cf84159de46..5dc4b318256 100644 --- a/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.toml +++ b/Lib/test/test_tomllib/data/valid/dates-and-times/datetimes.toml @@ -1,2 +1,3 @@ local-dt=1988-10-27t01:01:01 +local-dt-no-seconds=2025-04-18T20:05 zulu-dt=1988-10-27t01:01:01z diff --git a/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.json b/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.json index 4d96abcbc79..1f66348b237 100644 --- a/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.json +++ b/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.json @@ -1,2 +1,4 @@ {"t": - {"type":"time-local","value":"00:00:00.999999"}} + {"type":"time-local","value":"00:00:00.999999"}, +"t2": + {"type":"time-local","value":"00:00:00"}} diff --git a/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.toml b/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.toml index 87547c1cf3b..6579b30c94f 100644 --- a/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.toml +++ b/Lib/test/test_tomllib/data/valid/dates-and-times/localtime.toml @@ -1 +1,2 @@ -t=00:00:00.99999999999999 \ No newline at end of file +t=00:00:00.99999999999999 +t2=00:00 \ No newline at end of file diff --git a/Lib/test/test_tomllib/data/valid/empty-inline-table.json b/Lib/test/test_tomllib/data/valid/inline-table/empty-inline-table.json similarity index 100% rename from Lib/test/test_tomllib/data/valid/empty-inline-table.json rename to Lib/test/test_tomllib/data/valid/inline-table/empty-inline-table.json diff --git a/Lib/test/test_tomllib/data/valid/empty-inline-table.toml b/Lib/test/test_tomllib/data/valid/inline-table/empty-inline-table.toml similarity index 100% rename from Lib/test/test_tomllib/data/valid/empty-inline-table.toml rename to Lib/test/test_tomllib/data/valid/inline-table/empty-inline-table.toml diff --git a/Lib/test/test_tomllib/data/valid/inline-table/multiline-inline-table.json b/Lib/test/test_tomllib/data/valid/inline-table/multiline-inline-table.json new file mode 100644 index 00000000000..d253884fbac --- /dev/null +++ b/Lib/test/test_tomllib/data/valid/inline-table/multiline-inline-table.json @@ -0,0 +1,35 @@ +{ + "multiline": { + "a": { + "type": "integer", + "value": "1" + }, + "b": { + "type": "integer", + "value": "2" + }, + "c": [ + { + "type": "integer", + "value": "1" + }, + { + "type": "integer", + "value": "2" + }, + { + "type": "integer", + "value": "3" + } + ], + "d": { + "type": "integer", + "value": "3" + }, + "e": { + "type": "integer", + "value": "4" + }, + "f": {} + } +} \ No newline at end of file diff --git a/Lib/test/test_tomllib/data/valid/inline-table/multiline-inline-table.toml b/Lib/test/test_tomllib/data/valid/inline-table/multiline-inline-table.toml new file mode 100644 index 00000000000..6a98a08a576 --- /dev/null +++ b/Lib/test/test_tomllib/data/valid/inline-table/multiline-inline-table.toml @@ -0,0 +1,12 @@ +multiline = { + "a" = 1, "b" = 2, + c = [ + 1, + 2, + 3, + ],# comment + d = 3, + e = 4, f = { + # comment + }, +} diff --git a/Lib/test/test_tomllib/data/valid/multiline-basic-str/replacements.json b/Lib/test/test_tomllib/data/valid/multiline-basic-str/replacements.json new file mode 100644 index 00000000000..699f556248d --- /dev/null +++ b/Lib/test/test_tomllib/data/valid/multiline-basic-str/replacements.json @@ -0,0 +1,6 @@ +{ + "escape": {"type":"string","value":"\u001B"}, + "tab": {"type":"string","value":"\t"}, + "upper-j": {"type":"string","value":"J"}, + "upper-j-2": {"type":"string","value":"J"} +} diff --git a/Lib/test/test_tomllib/data/valid/multiline-basic-str/replacements.toml b/Lib/test/test_tomllib/data/valid/multiline-basic-str/replacements.toml new file mode 100644 index 00000000000..fa5647e5938 --- /dev/null +++ b/Lib/test/test_tomllib/data/valid/multiline-basic-str/replacements.toml @@ -0,0 +1,4 @@ +escape = "\e" +tab = "\x09" +upper-j = "\x4a" +upper-j-2 = "\x4A" diff --git a/Lib/test/test_tomllib/test_data.py b/Lib/test/test_tomllib/test_data.py index 3483d93022b..9db1a37466e 100644 --- a/Lib/test/test_tomllib/test_data.py +++ b/Lib/test/test_tomllib/test_data.py @@ -8,12 +8,6 @@ from . import burntsushi, tomllib - -class MissingFile: - def __init__(self, path: Path): - self.path = path - - DATA_DIR = Path(__file__).parent / "data" VALID_FILES = tuple((DATA_DIR / "valid").glob("**/*.toml")) @@ -22,10 +16,7 @@ def __init__(self, path: Path): _expected_files = [] for p in VALID_FILES: json_path = p.with_suffix(".json") - try: - text = json.loads(json_path.read_bytes().decode()) - except FileNotFoundError: - text = MissingFile(json_path) + text = json.loads(json_path.read_bytes().decode()) _expected_files.append(text) VALID_FILES_EXPECTED = tuple(_expected_files) @@ -49,14 +40,6 @@ def test_invalid(self): def test_valid(self): for valid, expected in zip(VALID_FILES, VALID_FILES_EXPECTED): with self.subTest(msg=valid.stem): - if isinstance(expected, MissingFile): - # For a poor man's xfail, assert that this is one of the - # test cases where expected data is known to be missing. - assert valid.stem in { - "qa-array-inline-nested-1000", - "qa-table-inline-nested-1000", - } - continue toml_str = valid.read_bytes().decode() actual = tomllib.loads(toml_str) actual = burntsushi.convert(actual) diff --git a/Lib/test/test_tomllib/test_misc.py b/Lib/test/test_tomllib/test_misc.py index 85526ed8015..af7ab91bba7 100644 --- a/Lib/test/test_tomllib/test_misc.py +++ b/Lib/test/test_tomllib/test_misc.py @@ -9,8 +9,10 @@ from pathlib import Path import sys import tempfile +import textwrap import unittest from test import support +from test.support.script_helper import assert_python_ok from . import tomllib @@ -137,3 +139,20 @@ def test_types_import(self): never imported by tests. """ importlib.import_module(f"{tomllib.__name__}._types") + + def test_lazy_import(self): + # Test the TOML file can be parsed without importing regular + # expressions (tomllib._re) + code = textwrap.dedent(""" + import sys, tomllib, textwrap + document = textwrap.dedent(''' + [metadata] + key = "text" + array = ["array", "of", "text"] + booleans = [true, false] + ''') + tomllib.loads(document) + print("lazy import?", 'tomllib._re' not in sys.modules) + """) + proc = assert_python_ok("-c", code) + self.assertIn(b"lazy import? True", proc.out) diff --git a/Lib/test/test_tools/i18n_data/docstrings.py b/Lib/test/test_tools/i18n_data/docstrings.py index 151a55a4b56..14559a632da 100644 --- a/Lib/test/test_tools/i18n_data/docstrings.py +++ b/Lib/test/test_tools/i18n_data/docstrings.py @@ -1,7 +1,7 @@ """Module docstring""" # Test docstring extraction -from gettext import gettext as _ +from gettext import gettext as _ # noqa: F401 # Empty docstring diff --git a/Lib/test/test_tools/test_compute_changes.py b/Lib/test/test_tools/test_compute_changes.py index b20ff975fc2..eb1ecd447a7 100644 --- a/Lib/test/test_tools/test_compute_changes.py +++ b/Lib/test/test_tools/test_compute_changes.py @@ -6,7 +6,8 @@ from pathlib import Path from unittest.mock import patch -from test.test_tools import skip_if_missing, imports_under_tool +from test.support import os_helper +from test.test_tools import basepath, skip_if_missing, imports_under_tool skip_if_missing("build") @@ -15,6 +16,7 @@ compute_changes = importlib.import_module("compute-changes") process_changed_files = compute_changes.process_changed_files +is_fuzzable_library_file = compute_changes.is_fuzzable_library_file Outputs = compute_changes.Outputs ANDROID_DIRS = compute_changes.ANDROID_DIRS IOS_DIRS = compute_changes.IOS_DIRS @@ -45,16 +47,18 @@ def test_docs(self): self.assertFalse(result.run_tests) def test_ci_fuzz_stdlib(self): - for p in LIBRARY_FUZZER_PATHS: - with self.subTest(p=p): - if p.is_dir(): - f = p / "file" - elif p.is_file(): - f = p - else: - continue - result = process_changed_files({f}) - self.assertTrue(result.run_ci_fuzz_stdlib) + with os_helper.change_cwd(basepath): + for p in LIBRARY_FUZZER_PATHS: + with self.subTest(p=p): + if p.is_dir(): + f = p / "file" + elif p.is_file(): + f = p + else: + continue + result = process_changed_files({f}) + self.assertTrue(result.run_ci_fuzz_stdlib) + self.assertTrue(is_fuzzable_library_file(f)) def test_android(self): for d in ANDROID_DIRS: diff --git a/Lib/test/test_trace.py b/Lib/test/test_trace.py index d0e51c5c305..721e28885cf 100644 --- a/Lib/test/test_trace.py +++ b/Lib/test/test_trace.py @@ -142,6 +142,8 @@ def test_traced_func_linear(self): self.assertEqual(self.tracer.results().counts, expected) + @unittest.skipIf(os.environ.get('PYTHON_UOPS_OPTIMIZE') == '0', + "Line counts differ when JIT optimizer is disabled") def test_traced_func_loop(self): self.tracer.runfunc(traced_func_loop, 2, 3) @@ -166,6 +168,8 @@ def test_traced_func_importing(self): self.assertEqual(self.tracer.results().counts, expected) + @unittest.skipIf(os.environ.get('PYTHON_UOPS_OPTIMIZE') == '0', + "Line counts differ when JIT optimizer is disabled") def test_trace_func_generator(self): self.tracer.runfunc(traced_func_calling_generator) @@ -236,6 +240,8 @@ def setUp(self): self.my_py_filename = fix_ext_py(__file__) self.addCleanup(sys.settrace, sys.gettrace()) + @unittest.skipIf(os.environ.get('PYTHON_UOPS_OPTIMIZE') == '0', + "Line counts differ when JIT optimizer is disabled") def test_exec_counts(self): self.tracer = Trace(count=1, trace=0, countfuncs=0, countcallers=0) code = r'''traced_func_loop(2, 5)''' @@ -463,7 +469,6 @@ def tearDown(self): unlink(self.codefile) unlink(self.coverfile) - @unittest.expectedFailure # TODO: RUSTPYTHON; --- def test_cover_files_written_no_highlight(self): # Test also that the cover file for the trace module is not created # (issue #34171). @@ -484,7 +489,6 @@ def test_cover_files_written_no_highlight(self): " print('unreachable')\n" ) - @unittest.expectedFailure # TODO: RUSTPYTHON; --- def test_cover_files_written_with_highlight(self): argv = '-m trace --count --missing'.split() + [self.codefile] status, stdout, stderr = assert_python_ok(*argv) diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index 88e39145c9b..34219b7ea4a 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -9,18 +9,21 @@ import builtins import unittest import unittest.mock +import os import re import tempfile import random import string +import importlib.machinery +import sysconfig from test import support import shutil from test.support import (Error, captured_output, cpython_only, ALWAYS_EQ, requires_debug_ranges, has_no_debug_ranges, - requires_subprocess) + requires_subprocess, os_helper) from test.support.os_helper import TESTFN, temp_dir, unlink from test.support.script_helper import assert_python_ok, assert_python_failure, make_script -from test.support.import_helper import forget +from test.support.import_helper import ensure_lazy_imports, forget from test.support import force_not_colorized, force_not_colorized_test_class import json @@ -37,7 +40,7 @@ test_frame = namedtuple('frame', ['f_code', 'f_globals', 'f_locals']) test_tb = namedtuple('tb', ['tb_frame', 'tb_lineno', 'tb_next', 'tb_lasti']) -color_overrides = {"reset": "z", "filename": "fn", "error_highlight": "E"} +color_overrides = {"reset": "z", "filename": "fn", "error_highlight": "E", "note": "n"} colors = { color_overrides.get(k, k[0].lower()): v for k, v in _colorize.default_theme.traceback.items() @@ -88,6 +91,12 @@ def syntax_error_bad_indentation2(self): def tokenizer_error_with_caret_range(self): compile("blech ( ", "?", "exec") + def syntax_error_with_caret_wide_char(self): + compile("女女女=1; 女女女/", "?", "exec") + + def syntax_error_with_caret_wide_char_range(self): + compile("f(x, 女女女 for 女女女 in range(30), z)", "?", "exec") + def test_caret(self): err = self.get_exception_format(self.syntax_error_with_caret, SyntaxError) @@ -125,6 +134,20 @@ def test_caret(self): self.assertEqual(err[1].find("("), err[2].find("^")) # in the right place self.assertEqual(err[2].count("^"), 1) + def test_caret_wide_char(self): + err = self.get_exception_format(self.syntax_error_with_caret_wide_char, + SyntaxError) + self.assertIn("^", err[2]) + # "女女女=1; 女女女/" has display width 17 + self.assertEqual(err[2].find("^"), 4 + 17) + + err = self.get_exception_format(self.syntax_error_with_caret_wide_char_range, + SyntaxError) + self.assertIn("^", err[2]) + self.assertEqual(err[2].find("^"), 4 + 5) + # "女女女 for 女女女 in range(30)" has display width 30 + self.assertEqual(err[2].count("^"), 30) + def test_nocaret(self): exc = SyntaxError("error", ("x.py", 23, None, "bad syntax")) err = traceback.format_exception_only(SyntaxError, exc) @@ -564,6 +587,13 @@ def test_format_exception_only_exc(self): output = traceback.format_exception_only(Exception("projector")) self.assertEqual(output, ["Exception: projector\n"]) + @support.subTests("arg", [NotImplemented, "invalid syntax"]) + def test_format_syntax_error_message(self, arg): + exc = SyntaxError(arg) + lines = traceback.format_exception_only(type(exc), exc) + result = "".join(lines) + self.assertIn(str(arg), result) + def test_exception_is_None(self): NONE_EXC_STRING = 'NoneType: None\n' excfile = StringIO() @@ -1767,6 +1797,7 @@ def f(): ] self.assertEqual(result_lines, expected) + class TestKeywordTypoSuggestions(unittest.TestCase): TYPO_CASES = [ ("with block ad something:\n pass", "and"), @@ -1811,6 +1842,23 @@ def test_keyword_suggestions_from_command_string(self): stderr_text = stderr.decode('utf-8') self.assertIn(f"Did you mean '{expected_kw}'", stderr_text) + def test_no_keyword_suggestion_for_comma_errors(self): + # When the parser identifies a missing comma, don't suggest + # bogus keyword replacements like 'print' -> 'not' + code = '''\ +import sys +print( + "line1" + "line2" + file=sys.stderr +) +''' + source = textwrap.dedent(code).strip() + rc, stdout, stderr = assert_python_failure('-c', source) + stderr_text = stderr.decode('utf-8') + self.assertIn("Perhaps you forgot a comma", stderr_text) + self.assertNotIn("Did you mean", stderr_text) + @requires_debug_ranges() @force_not_colorized_test_class class PurePythonTracebackErrorCaretTests( @@ -3019,7 +3067,6 @@ def exc(): report = self.get_report(exc) self.assertEqual(report, expected) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_exception_group_wrapped_naked(self): # See gh-128799 @@ -3852,7 +3899,7 @@ def f(): def test_dont_swallow_cause_or_context_of_falsey_exception(self): # see gh-132308: Ensure that __cause__ or __context__ attributes of exceptions # that evaluate as falsey are included in the output. For falsey term, - # see https://docs.python.org/3/library/stdtypes.html#truth-value-testing. + # see https://docs.python.org/3/builtins/stdtypes.html#truth-value-testing. try: raise FalseyException from KeyError @@ -4071,7 +4118,7 @@ def test_comparison(self): def test_dont_swallow_subexceptions_of_falsey_exceptiongroup(self): # see gh-132308: Ensure that subexceptions of exception groups # that evaluate as falsey are displayed in the output. For falsey term, - # see https://docs.python.org/3/library/stdtypes.html#truth-value-testing. + # see https://docs.python.org/3/builtins/stdtypes.html#truth-value-testing. try: raise FalseyExceptionGroup("Gih", (KeyError(), NameError())) @@ -4092,11 +4139,13 @@ def test_dont_swallow_subexceptions_of_falsey_exceptiongroup(self): global_for_suggestions = None -class SuggestionFormattingTestBase: +class SuggestionFormattingTestMixin: + attr_function = getattr + def get_suggestion(self, obj, attr_name=None): if attr_name is not None: def callable(): - getattr(obj, attr_name) + self.attr_function(obj, attr_name) else: callable = obj @@ -4105,7 +4154,9 @@ def callable(): ) return result_lines[0] - def test_getattr_suggestions(self): + +class BaseSuggestionTests(SuggestionFormattingTestMixin): + def test_suggestions(self): class Substitution: noise = more_noise = a = bc = None blech = None @@ -4136,40 +4187,41 @@ class CaseChangeOverSubstitution: BLuch = None for cls, suggestion in [ - (Addition, "'bluchin'?"), - (Substitution, "'blech'?"), - (Elimination, "'blch'?"), - (Addition, "'bluchin'?"), - (SubstitutionOverElimination, "'blach'?"), - (SubstitutionOverAddition, "'blach'?"), - (EliminationOverAddition, "'bluc'?"), - (CaseChangeOverSubstitution, "'BLuch'?"), + (Addition, "'.bluchin'"), + (Substitution, "'.blech'"), + (Elimination, "'.blch'"), + (Addition, "'.bluchin'"), + (SubstitutionOverElimination, "'.blach'"), + (SubstitutionOverAddition, "'.blach'"), + (EliminationOverAddition, "'.bluc'"), + (CaseChangeOverSubstitution, "'.BLuch'"), ]: actual = self.get_suggestion(cls(), 'bluch') - self.assertIn(suggestion, actual) + self.assertIn('Did you mean ' + suggestion, actual) - def test_getattr_suggestions_underscored(self): + def test_suggestions_underscored(self): class A: bluch = None - self.assertIn("'bluch'", self.get_suggestion(A(), 'blach')) - self.assertIn("'bluch'", self.get_suggestion(A(), '_luch')) - self.assertIn("'bluch'", self.get_suggestion(A(), '_bluch')) + self.assertIn("'.bluch'", self.get_suggestion(A(), 'blach')) + self.assertIn("'.bluch'", self.get_suggestion(A(), '_luch')) + self.assertIn("'.bluch'", self.get_suggestion(A(), '_bluch')) + attr_function = self.attr_function class B: _bluch = None def method(self, name): - getattr(self, name) + attr_function(self, name) - self.assertIn("'_bluch'", self.get_suggestion(B(), '_blach')) - self.assertIn("'_bluch'", self.get_suggestion(B(), '_luch')) - self.assertNotIn("'_bluch'", self.get_suggestion(B(), 'bluch')) + self.assertIn("'._bluch'", self.get_suggestion(B(), '_blach')) + self.assertIn("'._bluch'", self.get_suggestion(B(), '_luch')) + self.assertNotIn("'._bluch'", self.get_suggestion(B(), 'bluch')) - self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, '_blach'))) - self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, '_luch'))) - self.assertIn("'_bluch'", self.get_suggestion(partial(B().method, 'bluch'))) + self.assertIn("'._bluch'", self.get_suggestion(partial(B().method, '_blach'))) + self.assertIn("'._bluch'", self.get_suggestion(partial(B().method, '_luch'))) + self.assertIn("'._bluch'", self.get_suggestion(partial(B().method, 'bluch'))) - def test_getattr_suggestions_with_custom___dir__(self): + def test_suggestions_with_custom___dir__(self): class M(type): def __dir__(cls): return [None, "fox"] @@ -4181,29 +4233,30 @@ def __dir__(self): class C1(C0, metaclass=M): pass - self.assertNotIn("'bluch'", self.get_suggestion(C0, "blach")) - self.assertIn("'bluch'", self.get_suggestion(C0(), "blach")) + self.assertNotIn("'.bluch'", self.get_suggestion(C0, "blach")) + self.assertIn("'.bluch'", self.get_suggestion(C0(), "blach")) - self.assertIn("'fox'", self.get_suggestion(C1, "foo")) - self.assertNotIn("'fox'", self.get_suggestion(C1(), "foo")) + self.assertIn("'.fox'", self.get_suggestion(C1, "foo")) + self.assertNotIn("'.fox'", self.get_suggestion(C1(), "foo")) - self.assertNotIn("'bluch'", self.get_suggestion(C1, "blach")) - self.assertIn("'bluch'", self.get_suggestion(C1(), "blach")) + self.assertNotIn("'.bluch'", self.get_suggestion(C1, "blach")) + self.assertIn("'.bluch'", self.get_suggestion(C1(), "blach")) - def test_getattr_suggestions_do_not_trigger_for_long_attributes(self): + + def test_do_not_trigger_for_long_attributes(self): class A: blech = None actual = self.get_suggestion(A(), 'somethingverywrong') self.assertNotIn("blech", actual) - def test_getattr_error_bad_suggestions_do_not_trigger_for_small_names(self): + def test_do_not_trigger_for_small_names(self): class MyClass: vvv = mom = w = id = pytho = None for name in ("b", "v", "m", "py"): with self.subTest(name=name): - actual = self.get_suggestion(MyClass, name) + actual = self.get_suggestion(MyClass(), name) self.assertNotIn("Did you mean", actual) self.assertNotIn("'vvv", actual) self.assertNotIn("'mom'", actual) @@ -4211,7 +4264,7 @@ class MyClass: self.assertNotIn("'w'", actual) self.assertNotIn("'pytho'", actual) - def test_getattr_suggestions_do_not_trigger_for_big_dicts(self): + def test_do_not_trigger_for_big_dicts(self): class A: blech = None # A class with a very big __dict__ will not be considered @@ -4222,7 +4275,36 @@ class A: actual = self.get_suggestion(A(), 'bluch') self.assertNotIn("blech", actual) - def test_getattr_suggestions_no_args(self): + def test_suggestions_for_same_name(self): + class A: + def __dir__(self): + return ['blech'] + actual = self.get_suggestion(A(), 'blech') + self.assertNotIn("Did you mean", actual) + + def test_suggestions_not_normalized(self): + class A: + analization = None + fiⁿₐˡᵢᶻₐᵗᵢᵒₙ = None + + suggestion = self.get_suggestion(A(), 'fiⁿₐˡᵢᶻₐᵗᵢᵒₙ') + self.assertIn("'.finalization'", suggestion) + self.assertNotIn("analization", suggestion) + + class B: + attr_a = None + attr_µ = None # attr_\xb5 + + suggestion = self.get_suggestion(B(), 'attr_\xb5') + self.assertIn( + "'.attr_\u03bc' ('attr_\\u03bc') " + "instead of '.attr_\xb5' ('attr_\\xb5')", + suggestion) + self.assertNotIn("attr_a", suggestion) + + +class GetattrSuggestionTests(BaseSuggestionTests): + def test_suggestions_no_args(self): class A: blech = None def __getattr__(self, attr): @@ -4239,7 +4321,7 @@ def __getattr__(self, attr): actual = self.get_suggestion(A(), 'bluch') self.assertIn("blech", actual) - def test_getattr_suggestions_invalid_args(self): + def test_suggestions_invalid_args(self): class NonStringifyClass: __str__ = None __repr__ = None @@ -4263,13 +4345,12 @@ def __getattr__(self, attr): actual = self.get_suggestion(cls(), 'bluch') self.assertIn("blech", actual) - def test_getattr_suggestions_for_same_name(self): - class A: - def __dir__(self): - return ['blech'] - actual = self.get_suggestion(A(), 'blech') - self.assertNotIn("Did you mean", actual) +class DelattrSuggestionTests(BaseSuggestionTests): + attr_function = delattr + + +class SuggestionFormattingTestBase(SuggestionFormattingTestMixin): def test_attribute_error_with_failing_dict(self): class T: bluch = 1 @@ -4311,6 +4392,275 @@ def __getattribute__(self, attr): self.assertIn("Did you mean", actual) self.assertIn("bluch", actual) + def test_getattr_nested_attribute_suggestions(self): + # Test that nested attributes are suggested when no direct match + class Inner: + def __init__(self): + self.value = 42 + self.data = "test" + + class Outer: + def __init__(self): + self.inner = Inner() + + # Should suggest 'inner.value' + actual = self.get_suggestion(Outer(), 'value') + self.assertIn("Did you mean '.inner.value' instead of '.value'", actual) + + # Should suggest 'inner.data' + actual = self.get_suggestion(Outer(), 'data') + self.assertIn("Did you mean '.inner.data' instead of '.data'", actual) + + def test_getattr_nested_prioritizes_direct_matches(self): + # Test that direct attribute matches are prioritized over nested ones + class Inner: + def __init__(self): + self.foo = 42 + + class Outer: + def __init__(self): + self.inner = Inner() + self.fooo = 100 # Similar to 'foo' + + # Should suggest 'fooo' (direct) not 'inner.foo' (nested) + actual = self.get_suggestion(Outer(), 'foo') + self.assertIn("Did you mean '.fooo'", actual) + self.assertNotIn("inner.foo", actual) + + def test_getattr_nested_with_property(self): + # Property suggestions should not execute the property getter. + class Inner: + @property + def computed(self): + return missing_name + + class Outer: + def __init__(self): + self.inner = Inner() + + actual = self.get_suggestion(Outer(), 'computed') + self.assertIn( + "Did you mean '.inner.computed' instead of '.computed'", + actual, + ) + + def test_getattr_nested_no_suggestion_for_deep_nesting(self): + # Test that deeply nested attributes (2+ levels) are not suggested + class Deep: + def __init__(self): + self.value = 42 + + class Middle: + def __init__(self): + self.deep = Deep() + + class Outer: + def __init__(self): + self.middle = Middle() + + # Should not suggest 'middle.deep.value' (too deep) + actual = self.get_suggestion(Outer(), 'value') + self.assertNotIn("Did you mean", actual) + + def test_getattr_nested_ignores_private_attributes(self): + # Test that nested suggestions ignore private attributes + class Inner: + def __init__(self): + self.public_value = 42 + + class Outer: + def __init__(self): + self._private_inner = Inner() + + # Should not suggest '_private_inner.public_value' + actual = self.get_suggestion(Outer(), 'public_value') + self.assertNotIn("Did you mean", actual) + + def test_getattr_nested_limits_attribute_checks(self): + # Test that nested suggestions are limited to checking first 20 non-private attributes + class Inner: + def __init__(self): + self.target_value = 42 + + class Outer: + def __init__(self): + # Add many attributes before 'inner' + for i in range(25): + setattr(self, f'attr_{i:02d}', i) + # Add the inner object after 20+ attributes + self.inner = Inner() + + obj = Outer() + # Verify that 'inner' is indeed present but after position 20 + attrs = [x for x in sorted(dir(obj)) if not x.startswith('_')] + inner_position = attrs.index('inner') + self.assertGreater(inner_position, 19, "inner should be after position 20 in sorted attributes") + + # Should not suggest 'inner.target_value' because inner is beyond the first 20 attributes checked + actual = self.get_suggestion(obj, 'target_value') + self.assertNotIn("inner.target_value", actual) + + def test_getattr_nested_returns_first_match_only(self): + # Test that only the first nested match is returned (not multiple) + class Inner1: + def __init__(self): + self.value = 1 + + class Inner2: + def __init__(self): + self.value = 2 + + class Inner3: + def __init__(self): + self.value = 3 + + class Outer: + def __init__(self): + # Multiple inner objects with same attribute + self.a_inner = Inner1() + self.b_inner = Inner2() + self.c_inner = Inner3() + + # Should suggest only the first match (alphabetically) + actual = self.get_suggestion(Outer(), 'value') + self.assertIn("'.a_inner.value'", actual) + # Verify it's a single suggestion, not multiple + self.assertEqual(actual.count("Did you mean"), 1) + + def test_getattr_nested_handles_attribute_access_exceptions(self): + # Test that exceptions raised when accessing attributes don't crash the suggestion system + class ExplodingProperty: + @property + def exploding_attr(self): + raise RuntimeError("BOOM! This property always explodes") + + def __repr__(self): + raise RuntimeError("repr also explodes") + + class SafeInner: + def __init__(self): + self.target = 42 + + class Outer: + def __init__(self): + self.exploder = ExplodingProperty() # Accessing attributes will raise + self.safe_inner = SafeInner() + + # Should still suggest '.safe_inner.target' without crashing + # even though accessing exploder.target would raise an exception + actual = self.get_suggestion(Outer(), 'target') + self.assertIn("'.safe_inner.target'", actual) + + def test_getattr_nested_handles_hasattr_exceptions(self): + # Test that exceptions in hasattr don't crash the system + class WeirdObject: + def __getattr__(self, name): + if name == 'target': + raise RuntimeError("Can't check for target attribute") + raise AttributeError(f"No attribute {name}") + + class NormalInner: + def __init__(self): + self.target = 100 + + class Outer: + def __init__(self): + self.weird = WeirdObject() # hasattr will raise for 'target' + self.normal = NormalInner() + + # Should still find 'normal.target' even though weird.target check fails + actual = self.get_suggestion(Outer(), 'target') + self.assertIn("'.normal.target'", actual) + + @force_not_colorized + def test_cross_language(self): + cases = [ + # (type, attr, hint_attr) + (list, 'push', 'append'), + (list, 'concat', 'extend'), + (list, 'addAll', 'extend'), + (str, 'toUpperCase', 'upper'), + (str, 'toLowerCase', 'lower'), + (str, 'trimStart', 'lstrip'), + (str, 'trimEnd', 'rstrip'), + (dict, 'keySet', 'keys'), + (dict, 'entrySet', 'items'), + (dict, 'entries', 'items'), + (dict, 'putAll', 'update'), + ] + for test_type, attr, hint_attr in cases: + with self.subTest(type=test_type.__name__, attr=attr): + obj = test_type() + actual = self.get_suggestion(obj, attr) + self.assertEndsWith(actual, f"Did you mean '.{hint_attr}'?") + + cases = [ + # (type, attr, hint) + (list, 'contains', "Use 'x in list'."), + (list, 'add', "Did you mean to use a 'set' object?"), + (dict, 'put', "Use d[k] = v."), + ] + for test_type, attr, expected in cases: + with self.subTest(type=test_type, attr=attr): + obj = test_type() + actual = self.get_suggestion(obj, attr) + self.assertEndsWith(actual, expected) + + @force_not_colorized + def test_cross_language_levenshtein_fallback(self): + # When no cross-language entry exists, Levenshtein still works + # (e.g., trim->strip is not in the table but Levenshtein catches it) + actual = self.get_suggestion('', 'trim') + self.assertIn("strip", actual) + + @force_not_colorized + def test_cross_language_no_hint_for_unknown_attr(self): + actual = self.get_suggestion([], 'completely_unknown_method') + self.assertNotIn("Did you mean", actual) + + @force_not_colorized + def test_cross_language_works_for_subclasses(self): + # isinstance() check means subclasses also get hints + class MyList(list): + pass + actual = self.get_suggestion(MyList(), 'push') + self.assertEndsWith(actual, "Did you mean '.append'?") + + class MyDict(dict): + pass + actual = self.get_suggestion(MyDict(), 'keySet') + self.assertEndsWith(actual, "Did you mean '.keys'?") + + @force_not_colorized + def test_cross_language_mutable_on_immutable(self): + # Mutable method on immutable type suggests the mutable counterpart + cases = [ + (tuple, 'append', "Did you mean to use a 'list' object?"), + (tuple, 'extend', "Did you mean to use a 'list' object?"), + (tuple, 'insert', "Did you mean to use a 'list' object?"), + (tuple, 'remove', "Did you mean to use a 'list' object?"), + (frozenset, 'add', "Did you mean to use a 'set' object?"), + (frozenset, 'discard', "Did you mean to use a 'set' object?"), + (frozenset, 'remove', "Did you mean to use a 'set' object?"), + (frozenset, 'update', "Did you mean to use a 'set' object?"), + (frozendict, 'update', "Did you mean to use a 'dict' object?"), + ] + for test_type, attr, expected in cases: + with self.subTest(type=test_type.__name__, attr=attr): + obj = test_type() + actual = self.get_suggestion(obj, attr) + self.assertEndsWith(actual, expected) + + @force_not_colorized + def test_cross_language_float_bitwise(self): + # Bitwise operators on float suggest using int + cases = ['__or__', '__and__', '__xor__', '__lshift__', '__rshift__'] + for attr in cases: + with self.subTest(attr=attr): + actual = self.get_suggestion(1.0, attr) + self.assertIn("'int'", actual) + self.assertIn("Bitwise operators", actual) + def make_module(self, code): tmpdir = Path(tempfile.mkdtemp()) self.addCleanup(shutil.rmtree, tmpdir) @@ -4665,6 +5015,34 @@ def foo(self): actual = self.get_suggestion(instance.foo) self.assertIn("self.blech", actual) + def test_name_error_with_instance_not_normalized(self): + class A: + def __init__(self): + self.fiⁿₐˡᵢᶻₐᵗᵢᵒₙ = None + def foo(self): + analization = 1 + x = fiⁿₐˡᵢᶻₐᵗᵢᵒₙ + + instance = A() + actual = self.get_suggestion(instance.foo) + self.assertIn("self.finalization", actual) + self.assertNotIn("fiⁿₐˡᵢᶻₐᵗᵢᵒₙ", actual) + self.assertNotIn("analization", actual) + + class B: + def __init__(self): + self.attr_µ = None # attr_\xb5 + def foo(self): + attr_a = 1 + x = attr_µ # attr_\xb5 + + instance = B() + actual = self.get_suggestion(instance.foo) + self.assertIn("self.attr_\u03bc", actual) + self.assertIn(r"self.attr_\u03bc", actual) + self.assertNotIn("attr_\xb5", actual) + self.assertNotIn("attr_a", actual) + def test_unbound_local_error_with_instance(self): class A: def __init__(self): @@ -4723,6 +5101,32 @@ def func(): actual = self.get_suggestion(func) self.assertIn("forget to import '_io'", actual) + def test_name_error_with_bad_getattr(self): + class A: + def __getattr__(self, x): + spam + + actual = self.get_suggestion(A(), "eggs") + self.assertIn("name 'spam' is not defined", actual) + + def test_name_error_with_bad_getattribute(self): + + class A: + def __getattribute__(self, x): + spam + + actual = self.get_suggestion(A(), "eggs") + self.assertIn("name 'spam' is not defined", actual) + + def test_name_error_with_bad_property(self): + class A: + @property + def eggs(self): + eggs + + actual = self.get_suggestion(A(), "eggs") + self.assertIn("name 'eggs' is not defined", actual) + class PurePythonSuggestionFormattingTests( @@ -4747,6 +5151,51 @@ class CPythonSuggestionFormattingTests( """ +class PurePythonGetattrSuggestionFormattingTests( + PurePythonExceptionFormattingMixin, + GetattrSuggestionTests, + unittest.TestCase, +): + """ + Same set of tests (for attribute access) as above using the pure Python + implementation of traceback printing in traceback.py. + """ + + +class PurePythonDelattrSuggestionFormattingTests( + PurePythonExceptionFormattingMixin, + DelattrSuggestionTests, + unittest.TestCase, +): + """ + Same set of tests (for attribute deletion) as above using the pure Python + implementation of traceback printing in traceback.py. + """ + + +@cpython_only +class CPythonGetattrSuggestionFormattingTests( + CAPIExceptionFormattingMixin, + GetattrSuggestionTests, + unittest.TestCase, +): + """ + Same set of tests (for attribute access) as above but with Python's + internal traceback printing. + """ + + +@cpython_only +class CPythonDelattrSuggestionFormattingTests( + CAPIExceptionFormattingMixin, + DelattrSuggestionTests, + unittest.TestCase, +): + """ + Same set of tests (for attribute deletion) as above but with Python's + internal traceback printing. + """ + class MiscTest(unittest.TestCase): def test_all(self): @@ -4788,7 +5237,6 @@ def CHECK(a, b, expected): CHECK("AttributeError", "AttributeErrorTests", 10) CHECK("ABA", "AAB", 4) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: crates/pylib/Lib/test/levenshtein_examples.json is missing. Run `make regen-test-levenshtein` @support.requires_resource('cpu') def test_levenshtein_distance_short_circuit(self): if not LEVENSHTEIN_DATA_FILE.is_file(): @@ -4841,7 +5289,109 @@ class MyList(list): with self.assertRaises(TypeError): _suggestions._generate_suggestions(MyList(), "") + def test_no_site_package_flavour(self): + code = """import boo""" + _, _, stderr = assert_python_failure('-S', '-c', code) + + self.assertIn( + (b"Site initialization is disabled, did you forget to " + b"add the site-packages directory to sys.path " + b"or to enable your virtual environment?"), stderr + ) + + code = """ + import sys + sys.stdlib_module_names = sys.stdlib_module_names + ("boo",) + import boo + """ + _, _, stderr = assert_python_failure('-S', '-c', code) + + self.assertNotIn( + (b"Site initialization is disabled, did you forget to " + b"add the site-packages directory to sys.path " + b"or to enable your virtual environment?"), stderr + ) + + def test_missing_stdlib_module(self): + code = """ + import sys + sys.stdlib_module_names |= {'spam'} + import spam + """ + _, _, stderr = assert_python_failure('-S', '-c', code) + self.assertIn(b"Standard library module 'spam' was not found", stderr) + + code = """ + import sys + import traceback + traceback._MISSING_STDLIB_MODULE_MESSAGES = {'spam': "Install 'spam4life' for 'spam'"} + sys.stdlib_module_names |= {'spam'} + import spam + """ + _, _, stderr = assert_python_failure('-S', '-c', code) + + self.assertIn(b"Install 'spam4life' for 'spam'", stderr) + + @unittest.skipIf(sys.platform == "win32", "Non-Windows test") + def test_windows_only_module_error(self): + try: + import msvcrt # noqa: F401 + except ModuleNotFoundError: + formatted = traceback.format_exc() + self.assertIn("Unsupported platform for Windows-only standard library module 'msvcrt'", formatted) + else: + self.fail("ModuleNotFoundError was not raised") + + @unittest.skipIf(not importlib.machinery.EXTENSION_SUFFIXES, 'Platform does not support extension modules') + def test_find_incompatible_extension_modules(self): + """_find_incompatible_extension_modules assumes the last extension in + importlib.machinery.EXTENSION_SUFFIXES (defined in Python/dynload_*.c) + is untagged (eg. .so, .pyd). + + This test exists to make sure that assumption is correct. + """ + last_extension_suffix = importlib.machinery.EXTENSION_SUFFIXES[-1] + if shlib_suffix := sysconfig.get_config_var('SHLIB_SUFFIX'): + self.assertEqual(last_extension_suffix, shlib_suffix) + else: + before_dot, *extensions = last_extension_suffix.split('.') + expected_prefixes = [''] + if os.name == 'nt': + # Windows puts the debug tag in the module file stem (eg. foo_d.pyd) + expected_prefixes.append('_d') + self.assertIn(before_dot, expected_prefixes, msg=( + f'Unexpected prefix {before_dot!r} in extension module ' + f'suffix {last_extension_suffix!r}. ' + 'traceback._find_incompatible_extension_module needs to be ' + 'updated to take this into account!' + )) + # if SHLIB_SUFFIX is not define, we assume the native + # shared library suffix only contains one extension + # (eg. '.so', bad eg. '.cpython-315-x86_64-linux-gnu.so') + self.assertEqual(len(extensions), 1, msg=( + 'The last suffix in importlib.machinery.EXTENSION_SUFFIXES ' + 'contains more than one extension, so it is probably different ' + 'than SHLIB_SUFFIX. It probably contains an ABI tag! ' + 'If this is a false positive, define SHLIB_SUFFIX in sysconfig.' + )) + + @unittest.skipIf(not importlib.machinery.EXTENSION_SUFFIXES, 'Platform does not support extension modules') + def test_incompatible_extension_modules_hint(self): + untagged_suffix = importlib.machinery.EXTENSION_SUFFIXES[-1] + with os_helper.temp_dir() as tmp: + # create a module with a incompatible ABI tag + incompatible_module = f'foo.some-abi{untagged_suffix}' + open(os.path.join(tmp, incompatible_module), "wb").close() + # try importing it + code = f''' + import sys + sys.path.insert(0, {tmp!r}) + import foo + ''' + _, _, stderr = assert_python_failure('-c', code, __cwd=tmp) + hint = f'Although a module with this name was found for a different Python version ({incompatible_module}).' + self.assertIn(hint, stderr.decode()) class TestColorizedTraceback(unittest.TestCase): @@ -4879,6 +5429,23 @@ def bar(): self.assertIn("return baz1(1,\n 2,3\n ,4)", lines) self.assertIn(red + "bar" + reset + boldr + "()" + reset, lines) + def test_colorized_exception_notes(self): + def foo(): + raise ValueError() + + try: + foo() + except Exception as e: + e.add_note("First note") + e.add_note("Second note") + exc = traceback.TracebackException.from_exception(e) + + lines = "".join(exc.format(colorize=True)) + note = colors["n"] + reset = colors["z"] + self.assertIn(note + "First note" + reset, lines) + self.assertIn(note + "Second note" + reset, lines) + def test_colorized_syntax_error(self): try: compile("a $ b", "", "exec") @@ -4887,7 +5454,7 @@ def test_colorized_syntax_error(self): e, capture_locals=True ) actual = "".join(exc.format(colorize=True)) - def expected(t, m, fn, l, f, E, e, z): + def expected(t, m, fn, l, f, E, e, z, n): return "".join( [ f' File {fn}""{z}, line {l}1{z}\n', @@ -4914,7 +5481,7 @@ def foo(): actual = tbstderr.getvalue().splitlines() lno_foo = foo.__code__.co_firstlineno - def expected(t, m, fn, l, f, E, e, z): + def expected(t, m, fn, l, f, E, e, z, n): return [ 'Traceback (most recent call last):', f' File {fn}"{__file__}"{z}, ' @@ -4947,7 +5514,7 @@ def foo(): lno_foo = foo.__code__.co_firstlineno actual = "".join(exc.format(colorize=True)).splitlines() - def expected(t, m, fn, l, f, E, e, z): + def expected(t, m, fn, l, f, E, e, z, n): return [ f" + Exception Group Traceback (most recent call last):", f' | File {fn}"{__file__}"{z}, line {l}{lno_foo+9}{z}, in {f}test_colorized_traceback_from_exception_group{z}', @@ -4971,5 +5538,139 @@ def expected(t, m, fn, l, f, E, e, z): ] self.assertEqual(actual, expected(**colors)) + def test_colorized_traceback_unicode(self): + try: + 啊哈=1; 啊哈/0#### + except Exception as e: + exc = traceback.TracebackException.from_exception(e) + + actual = "".join(exc.format(colorize=True)).splitlines() + def expected(t, m, fn, l, f, E, e, z, n): + return [ + f" 啊哈=1; {e}啊哈{z}{E}/{z}{e}0{z}####", + f" {e}~~~~{z}{E}^{z}{e}~{z}", + ] + self.assertEqual(actual[2:4], expected(**colors)) + + try: + ééééé/0 + except Exception as e: + exc = traceback.TracebackException.from_exception(e) + + actual = "".join(exc.format(colorize=True)).splitlines() + def expected(t, m, fn, l, f, E, e, z, n): + return [ + f" {E}ééééé{z}/0", + f" {E}^^^^^{z}", + ] + self.assertEqual(actual[2:4], expected(**colors)) + + def test_colorized_syntax_error_ascii_display_width(self): + """Caret alignment for ASCII edge cases handled by _wlen. + + The old ASCII fast track in _display_width returned the raw character + offset for ASCII strings, which is wrong for CTRL-Z (display width 2) + and ANSI escape sequences (display width 0). + """ + E = colors["E"] + z = colors["z"] + t = colors["t"] + m = colors["m"] + fn = colors["fn"] + l = colors["l"] + + def _make_syntax_error(text, offset, end_offset): + err = SyntaxError("invalid syntax") + err.filename = "" + err.lineno = 1 + err.end_lineno = 1 + err.text = text + err.offset = offset + err.end_offset = end_offset + return err + + # CTRL-Z (\x1a) is ASCII but displayed as ^Z (2 columns). + # Verify caret aligns when CTRL-Z precedes the error. + err = _make_syntax_error("a\x1a$\n", offset=3, end_offset=4) + exc = traceback.TracebackException.from_exception(err) + actual = "".join(exc.format(colorize=True)) + # 'a' (1 col) + '\x1a' (2 cols) = 3 cols before '$' + self.assertIn( + f' File {fn}""{z}, line {l}1{z}\n' + f' a\x1a{E}${z}\n' + f' {" " * 3}{E}^{z}\n' + f'{t}SyntaxError{z}: {m}invalid syntax{z}\n', + actual, + ) + + # CTRL-Z in the highlighted (error) region counts as 2 columns. + err = _make_syntax_error("$\x1a\n", offset=1, end_offset=3) + exc = traceback.TracebackException.from_exception(err) + actual = "".join(exc.format(colorize=True)) + # '$' (1 col) + '\x1a' (2 cols) = 3 columns of carets + self.assertIn( + f' {E}$\x1a{z}\n' + f' {E}{"^" * 3}{z}\n', + actual, + ) + + # ANSI escape sequences are ASCII but take 0 display columns. + err = _make_syntax_error("a\x1b[1mb$\n", offset=7, end_offset=8) + exc = traceback.TracebackException.from_exception(err) + actual = "".join(exc.format(colorize=True)) + # 'a' (1 col) + '\x1b[1m' (0 cols) + 'b' (1 col) = 2 before '$' + self.assertIn( + f' a\x1b[1mb{E}${z}\n' + f' {" " * 2}{E}^{z}\n', + actual, + ) + +class TestLazyImportSuggestions(unittest.TestCase): + """Test that lazy imports are not reified when computing AttributeError suggestions.""" + + def test_attribute_error_does_not_reify_lazy_imports(self): + """Printing an AttributeError should not trigger lazy import reification.""" + # lazypkg.bar prints "BAR_MODULE_LOADED" when imported. + # If lazy import is reified during suggestion computation, we'll see it. + code = textwrap.dedent(""" + lazy import test.test_lazy_import.data.lazypkg + test.test_lazy_import.data.lazypkg.nonexistent + """) + rc, stdout, stderr = assert_python_failure('-c', code) + self.assertNotIn(b"BAR_MODULE_LOADED", stdout) + + def test_traceback_formatting_does_not_reify_lazy_imports(self): + """Formatting a traceback should not trigger lazy import reification.""" + code = textwrap.dedent(""" + import traceback + lazy import test.test_lazy_import.data.lazypkg + try: + test.test_lazy_import.data.lazypkg.nonexistent + except AttributeError: + traceback.format_exc() + print("OK") + """) + rc, stdout, stderr = assert_python_ok('-c', code) + self.assertIn(b"OK", stdout) + self.assertNotIn(b"BAR_MODULE_LOADED", stdout) + + def test_suggestion_still_works_for_non_lazy_attributes(self): + """Suggestions should still work for non-lazy module attributes.""" + code = textwrap.dedent(""" + lazy import test.test_lazy_import.data.lazypkg + # Typo for __name__ + test.test_lazy_import.data.lazypkg.__nme__ + """) + rc, stdout, stderr = assert_python_failure('-c', code) + self.assertIn(b"__name__", stderr) + self.assertNotIn(b"BAR_MODULE_LOADED", stdout) + + +class LazyImportTest(unittest.TestCase): + @support.cpython_only + def test_lazy_import(self): + ensure_lazy_imports("traceback", {"_colorize"}) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_tracemalloc.py b/Lib/test/test_tracemalloc.py index e6634f89d56..47081f2b593 100644 --- a/Lib/test/test_tracemalloc.py +++ b/Lib/test/test_tracemalloc.py @@ -12,7 +12,7 @@ from test.support.script_helper import (assert_python_ok, assert_python_failure, interpreter_requires_environment) from test import support -from test.support import force_not_colorized +from test.support import force_not_colorized, warnings_helper from test.support import os_helper from test.support import threading_helper @@ -358,6 +358,7 @@ def fork_child(self): # everything is fine return 0 + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.requires_fork() def test_fork(self): # check that tracemalloc is still working after fork @@ -1059,8 +1060,8 @@ def test_track(self): self.check_track(False) def test_track_without_gil(self): - # check that calling _PyTraceMalloc_Track() without holding the GIL - # works too + # check that calling PyTraceMalloc_Track() without the GIL + # (detached thread state) still captures the Python traceback self.check_track(True) def test_track_already_tracked(self): diff --git a/Lib/test/test_tstring.py b/Lib/test/test_tstring.py index 74653c77c55..1e5f14ca007 100644 --- a/Lib/test/test_tstring.py +++ b/Lib/test/test_tstring.py @@ -1,5 +1,9 @@ +import subprocess import unittest +from test import support +from test.support.os_helper import temp_cwd +from test.support.script_helper import assert_python_ok, spawn_python from test.test_string._support import TStringBaseCase, fstring @@ -79,6 +83,44 @@ def upper(self): ) self.assertEqual(fstring(t), "Name: Bob, Age: 30") + @support.requires_subprocess() + def test_expression_in_interactive_after_buffer_resize(self): + expression = "(\n" + (" " * 64 + "\n") * 256 + "1\n)" + source = ( + f"result = t'''{{{expression}}}'''\n" + "print(repr(result.interpolations[0].expression))\n" + ) + with spawn_python('-i', '-q', stderr=subprocess.PIPE) as process: + stdout, stderr = process.communicate( + source.encode(), timeout=support.SHORT_TIMEOUT) + self.assertEqual(process.returncode, 0, stderr) + self.assertEqual(stdout.decode().strip(), repr(expression)) + + def test_interpolation_expression_in_file_after_buffer_resize(self): + expression = "(\n" + (" " * 64 + "\n") * 256 + "1\n)" + with temp_cwd(): + script = 'script.py' + source = ( + f"template = t'''{{{expression}}}'''\n" + "interpolation = template.interpolations[0]\n" + f"assert interpolation.expression == {expression!r}\n" + ) + with open(script, 'w') as f: + f.write(source) + assert_python_ok(script) + + @support.requires_resource('cpu') + def test_many_tstrings_in_module(self): + fields = ''.join(f'{{x{i}}}' for i in range(100)) + source = ''.join( + f"value_{i} = t'{fields}'\n" for i in range(1_000) + ) + namespace = {f'x{i}': str(i) for i in range(100)} + expected = ''.join(str(i) for i in range(100)) + exec(source, namespace) + self.assertEqual(fstring(namespace['value_0']), expected) + self.assertEqual(fstring(namespace['value_999']), expected) + def test_format_specifiers(self): # Test basic format specifiers value = 3.14159 @@ -88,6 +130,14 @@ def test_format_specifiers(self): ) self.assertEqual(fstring(t), "Pi: 3.14") + a = 3 + b = 4 + t = t"{a!=b:>10}" + self.assertTStringEqual( + t, ("", ""), [(a != b, "a!=b", None, ">10")] + ) + self.assertEqual(fstring(t), " 1") + def test_conversions(self): # Test !s conversion (str) obj = object() @@ -136,10 +186,82 @@ def test_debug_specifier(self): # Test white space in debug specifier t = t"Value: {value = }" self.assertTStringEqual( - t, ("Value: value = ", ""), [(value, "value", "r")] + t, ("Value: value = ", ""), [(value, "value ", "r")] ) self.assertEqual(fstring(t), "Value: value = 42") + # Explicit line continuations after the debug marker are part of + # the debug text, not the interpolation expression. + for template, strings, interpolation, rendered in ( + ( + t"""Value: {value =\ +}""", + ("Value: value =\\\n", ""), + (value, "value ", "r"), + "Value: value =\\\n42", + ), + ( + t"""Value: {value =\ +!r}""", + ("Value: value =\\\n", ""), + (value, "value ", "r"), + "Value: value =\\\n42", + ), + ( + t"""Value: {value =\ +:04}""", + ("Value: value =\\\n", ""), + (value, "value ", None, "04"), + "Value: value =\\\n0042", + ), + ( + t"""Value: {value =\ +\ +}""", + ("Value: value =\\\n\\\n", ""), + (value, "value ", "r"), + "Value: value =\\\n\\\n42", + ), + ): + with self.subTest(template=template): + self.assertTStringEqual(template, strings, [interpolation]) + self.assertEqual(fstring(template), rendered) + + def test_interpolation_expression_whitespace(self): + x = 42 + for template, expected in ( + (t"{x}", "x"), + (t"{x }", "x "), + (t"{ x}", " x"), + (t"{ x }", " x "), + (t"{ x }", " x "), + (t"""{ + x +}""", "\n x\n"), + (t"{ x !r}", " x "), + (t"{ x :.2f}", " x "), + (t"{ x = }", " x "), + (t"{ x = !r}", " x "), + (t"{ x = :.2f}", " x "), + (t"{x == 42 = }", "x == 42 "), + ): + with self.subTest(template=template): + self.assertEqual( + template.interpolations[0].expression, + expected, + ) + + def test_interpolation_expression_with_reconstructed_metadata(self): + regular = t'''{( + 1, # Force lexer metadata reconstruction. + "\"#")}''' + debug = t'''{( + 1, # Force lexer metadata reconstruction. + "\"#")=}''' + expected = '(\n 1, \n "\\"#")' + self.assertEqual(regular.interpolations[0].expression, expected) + self.assertEqual(debug.interpolations[0].expression, expected) + def test_raw_tstrings(self): path = r"C:\Users" t = rt"{path}\Documents" diff --git a/Lib/test/test_ttk/__init__.py b/Lib/test/test_ttk/__init__.py new file mode 100644 index 00000000000..7a47f44ca38 --- /dev/null +++ b/Lib/test/test_ttk/__init__.py @@ -0,0 +1,53 @@ +import os.path +import unittest +from test import support +from test.support import import_helper + + +if support.check_sanitizer(address=True, memory=True): + raise unittest.SkipTest("Tests involving libX11 can SEGFAULT on ASAN/MSAN builds") + +# Skip this test if _tkinter wasn't built. +import_helper.import_module('_tkinter') + +# Skip test if tk cannot be initialized. +support.requires('gui') + + +import tkinter +from _tkinter import TclError +from tkinter import ttk + + +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(ttk, "__version__") + self.assertEqual(cm.filename, __file__) + + +def setUpModule(): + wantobjects = support.get_resource_value('wantobjects') + if wantobjects is not None: + unittest.enterModuleContext( + support.swap_attr(tkinter, 'wantobjects', int(wantobjects))) + root = None + try: + root = tkinter.Tk() + button = ttk.Button(root) + button.destroy() + del button + except TclError as msg: + # assuming ttk is not available + raise unittest.SkipTest("ttk not available: %s" % msg) + finally: + if root is not None: + root.destroy() + del root + + +def load_tests(*args): + return support.load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_ttk/__main__.py b/Lib/test/test_ttk/__main__.py new file mode 100644 index 00000000000..40a23a297ec --- /dev/null +++ b/Lib/test/test_ttk/__main__.py @@ -0,0 +1,4 @@ +from . import load_tests +import unittest + +unittest.main() diff --git a/Lib/test/test_ttk/test_extensions.py b/Lib/test/test_ttk/test_extensions.py new file mode 100644 index 00000000000..f6ca5e97610 --- /dev/null +++ b/Lib/test/test_ttk/test_extensions.py @@ -0,0 +1,404 @@ +import sys +import unittest +import tkinter +from tkinter import ttk +from test.support import requires, gc_collect +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import (AbstractTkTest, AbstractDefaultRootTest, + get_tk_patchlevel, widget_eq) + +requires('gui') + +from test.test_ttk import test_widgets + + +class LabeledScaleTest(AbstractTkTest, unittest.TestCase): + + def tearDown(self): + self.root.update_idletasks() + super().tearDown() + + def test_widget_destroy(self): + # automatically created variable + x = ttk.LabeledScale(self.root) + var = x._variable._name + x.destroy() + gc_collect() # For PyPy or other GCs. + self.assertRaises(tkinter.TclError, x.tk.globalgetvar, var) + + # manually created variable + myvar = tkinter.DoubleVar(self.root) + name = myvar._name + x = ttk.LabeledScale(self.root, variable=myvar) + x.destroy() + if self.wantobjects: + self.assertEqual(x.tk.globalgetvar(name), myvar.get()) + else: + self.assertEqual(float(x.tk.globalgetvar(name)), myvar.get()) + del myvar + gc_collect() # For PyPy or other GCs. + self.assertRaises(tkinter.TclError, x.tk.globalgetvar, name) + + # checking that the tracing callback is properly removed + myvar = tkinter.IntVar(self.root) + # LabeledScale will start tracing myvar + x = ttk.LabeledScale(self.root, variable=myvar) + x.destroy() + # Unless the tracing callback was removed, creating a new + # LabeledScale with the same var will cause an error now. This + # happens because the variable will be set to (possibly) a new + # value which causes the tracing callback to be called and then + # it tries calling instance attributes not yet defined. + ttk.LabeledScale(self.root, variable=myvar) + if hasattr(sys, 'last_exc'): + self.assertNotEqual(type(sys.last_exc), tkinter.TclError) + elif hasattr(sys, 'last_type'): + self.assertNotEqual(sys.last_type, tkinter.TclError) + + def test_initialization(self): + # master passing + master = tkinter.Frame(self.root) + x = ttk.LabeledScale(master) + self.assertEqual(x.master, master) + x.destroy() + + # variable initialization/passing + passed_expected = (('0', 0), (0, 0), (10, 10), + (-1, -1), (sys.maxsize + 1, sys.maxsize + 1), + (2.5, 2), ('2.5', 2)) + for pair in passed_expected: + x = ttk.LabeledScale(self.root, from_=pair[0]) + self.assertEqual(x.value, pair[1]) + x.destroy() + x = ttk.LabeledScale(self.root, from_=None) + self.assertRaises((ValueError, tkinter.TclError), x._variable.get) + x.destroy() + # variable should have its default value set to the from_ value + myvar = tkinter.DoubleVar(self.root, value=20) + x = ttk.LabeledScale(self.root, variable=myvar) + self.assertEqual(x.value, 0) + x.destroy() + # check that it is really using a DoubleVar + x = ttk.LabeledScale(self.root, variable=myvar, from_=0.5) + self.assertEqual(x.value, 0.5) + self.assertEqual(x._variable._name, myvar._name) + x.destroy() + + # widget positionment + def check_positions(scale, scale_pos, label, label_pos): + self.assertEqual(scale.pack_info()['side'], scale_pos) + self.assertEqual(label.place_info()['anchor'], label_pos) + x = ttk.LabeledScale(self.root, compound='top') + check_positions(x.scale, 'bottom', x.label, 'n') + x.destroy() + x = ttk.LabeledScale(self.root, compound='bottom') + check_positions(x.scale, 'top', x.label, 's') + x.destroy() + # invert default positions + x = ttk.LabeledScale(self.root, compound='unknown') + check_positions(x.scale, 'top', x.label, 's') + x.destroy() + x = ttk.LabeledScale(self.root) # take default positions + check_positions(x.scale, 'bottom', x.label, 'n') + x.destroy() + + # extra, and invalid, kwargs + self.assertRaises(tkinter.TclError, ttk.LabeledScale, master, a='b') + + + def test_horizontal_range(self): + lscale = ttk.LabeledScale(self.root, from_=0, to=10) + lscale.pack() + self.require_mapped(lscale) + + linfo_1 = lscale.label.place_info() + prev_xcoord = lscale.scale.coords()[0] + self.assertEqual(prev_xcoord, int(linfo_1['x'])) + # change range to: from -5 to 5. This should change the x coord of + # the scale widget, since 0 is at the middle of the new + # range. + lscale.scale.configure(from_=-5, to=5) + # The following update is needed since the test doesn't use mainloop, + # at the same time this shouldn't affect test outcome + lscale.update() + curr_xcoord = lscale.scale.coords()[0] + self.assertNotEqual(prev_xcoord, curr_xcoord) + # the label widget should have been repositioned too + linfo_2 = lscale.label.place_info() + self.assertEqual(lscale.label['text'], 0 if self.wantobjects else '0') + self.assertEqual(curr_xcoord, int(linfo_2['x'])) + # change the range back + lscale.scale.configure(from_=0, to=10) + self.assertNotEqual(prev_xcoord, curr_xcoord) + self.assertEqual(prev_xcoord, int(linfo_1['x'])) + + lscale.destroy() + + + def test_variable_change(self): + x = ttk.LabeledScale(self.root) + x.pack() + self.require_mapped(x) + + curr_xcoord = x.scale.coords()[0] + newval = x.value + 1 + x.value = newval + # The following update is needed since the test doesn't use mainloop, + # at the same time this shouldn't affect test outcome + x.update() + self.assertEqual(x.value, newval) + self.assertEqual(x.label['text'], + newval if self.wantobjects else str(newval)) + self.assertEqual(float(x.scale.get()), newval) + self.assertGreater(x.scale.coords()[0], curr_xcoord) + self.assertEqual(x.scale.coords()[0], + int(x.label.place_info()['x'])) + + # value outside range + if self.wantobjects: + conv = lambda x: x + else: + conv = int + x.value = conv(x.scale['to']) + 1 # no changes shouldn't happen + x.update() + self.assertEqual(x.value, newval) + self.assertEqual(conv(x.label['text']), newval) + self.assertEqual(float(x.scale.get()), newval) + self.assertEqual(x.scale.coords()[0], + int(x.label.place_info()['x'])) + + # non-integer value + x.value = newval = newval + 1.5 + x.update() + self.assertEqual(x.value, int(newval)) + self.assertEqual(conv(x.label['text']), int(newval)) + self.assertEqual(float(x.scale.get()), newval) + + x.destroy() + + + def test_resize(self): + x = ttk.LabeledScale(self.root) + x.pack(expand=True, fill='both') + gc_collect() # For PyPy or other GCs. + self.require_mapped(x) + + width, height = x.master.winfo_width(), x.master.winfo_height() + width_new, height_new = width * 2, height * 2 + + x.value = 3 + x.update() + x.master.wm_geometry("%dx%d" % (width_new, height_new)) + self.assertEqual(int(x.label.place_info()['x']), + x.scale.coords()[0]) + + # Reset geometry + x.master.wm_geometry("%dx%d" % (width, height)) + x.destroy() + + +class OptionMenuTest(test_widgets.MenubuttonTest, unittest.TestCase): + + # OptionMenu documents only its own options, not the inherited + # Menubutton options (like the classic tkinter.OptionMenu). + test_options_in_docstring = None + + def setUp(self): + super().setUp() + self.textvar = tkinter.StringVar(self.root) + + def tearDown(self): + del self.textvar + super().tearDown() + + def create(self, default='b', values=('a', 'b', 'c'), **kwargs): + return ttk.OptionMenu(self.root, self.textvar, default, *values, **kwargs) + + def test_bad_kwarg(self): + with self.assertRaisesRegex(tkinter.TclError, r"^unknown option -image$"): + ttk.OptionMenu(self.root, self.textvar, 'b', image='') + + def test_configure_class(self): + # Unlike a plain Menubutton, OptionMenu does not accept a class at + # construction, so only the read-only nature of the option is tested. + widget = self.create() + self.assertEqual(widget['class'], '') + errmsg = 'attempt to change read-only option' + if get_tk_patchlevel(self.root) < (8, 6, 0, 'beta', 3): + errmsg = 'Attempt to change read-only option' + self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg) + + def test_configure_style(self): + # Like Menubutton, but OptionMenu does not accept a class at + # construction, so the custom-class part of the standard test is omitted. + widget = self.create() + self.assertEqual(widget['style'], '') + self.checkInvalidParam(widget, 'style', 'Foo', + errmsg='Layout Foo not found') + style = ttk.Style(self.root) + style.configure('Custom.TMenubutton') + self.checkParam(widget, 'style', 'Custom.TMenubutton') + + def test_configure_menu(self): + # OptionMenu manages its own menu; ['menu'] returns that Menu widget. + widget = self.create() + self.assertIsInstance(widget['menu'], tkinter.Menu) + self.checkParam(widget, 'menu', widget['menu'], eq=widget_eq) + + def test_configure_text(self): + # The displayed text is governed by the textvariable. + widget = self.create() + self.textvar.set('a') + self.assertEqual(widget['text'], 'a') + self.textvar.set('c') + self.assertEqual(widget['text'], 'c') + + def test_widget_destroy(self): + var = tkinter.StringVar(self.root) + optmenu = ttk.OptionMenu(self.root, var) + name = var._name + optmenu.update_idletasks() + optmenu.destroy() + self.assertEqual(optmenu.tk.globalgetvar(name), var.get()) + del var + gc_collect() # For PyPy or other GCs. + self.assertRaises(tkinter.TclError, optmenu.tk.globalgetvar, name) + + + def test_initialization(self): + self.assertRaises(tkinter.TclError, + ttk.OptionMenu, self.root, self.textvar, invalid='thing') + + optmenu = ttk.OptionMenu(self.root, self.textvar, 'b', 'a', 'b') + self.assertEqual(optmenu._variable.get(), 'b') + + self.assertTrue(optmenu['menu']) + self.assertTrue(optmenu['textvariable']) + + optmenu.destroy() + + + def test_menu(self): + items = ('a', 'b', 'c') + default = 'a' + optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) + found_default = False + for i in range(len(items)): + value = optmenu['menu'].entrycget(i, 'value') + self.assertEqual(value, items[i]) + if value == default: + found_default = True + self.assertTrue(found_default) + optmenu.destroy() + + # default shouldn't be in menu if it is not part of values + default = 'd' + optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) + curr = None + i = 0 + while True: + last, curr = curr, optmenu['menu'].entryconfigure(i, 'value') + if last == curr: + # no more menu entries + break + self.assertNotEqual(curr, default) + i += 1 + self.assertEqual(i, len(items)) + + # check that variable is updated correctly + optmenu.pack() + gc_collect() # For PyPy or other GCs. + optmenu['menu'].invoke(0) + self.assertEqual(optmenu._variable.get(), items[0]) + + # changing to an invalid index shouldn't change the variable + self.assertRaises(tkinter.TclError, optmenu['menu'].invoke, -1) + self.assertEqual(optmenu._variable.get(), items[0]) + + optmenu.destroy() + + # specifying a callback + success = [] + def cb_test(item): + self.assertEqual(item, items[1]) + success.append(True) + optmenu = ttk.OptionMenu(self.root, self.textvar, 'a', command=cb_test, + *items) + optmenu['menu'].invoke(1) + if not success: + self.fail("Menu callback not invoked") + + optmenu.destroy() + + def test_set_menu(self): + optmenu = ttk.OptionMenu(self.root, self.textvar, 'a', 'a', 'b', 'c') + menu = optmenu['menu'] + self.assertEqual(menu.index('end'), 2) + + # set_menu rebuilds the menu with new values and an optional default. + optmenu.set_menu('y', 'x', 'y', 'z') + self.assertEqual(self.textvar.get(), 'y') + self.assertEqual([menu.entrycget(i, 'label') for i in range(3)], + ['x', 'y', 'z']) + + # Without a default the variable is left unchanged. + optmenu.set_menu(None, 'p', 'q') + self.assertEqual(self.textvar.get(), 'y') + self.assertEqual([menu.entrycget(i, 'label') for i in range(2)], + ['p', 'q']) + optmenu.destroy() + + def test_unique_radiobuttons(self): + # check that radiobuttons are unique across instances (bpo25684) + items = ('a', 'b', 'c') + default = 'a' + optmenu = ttk.OptionMenu(self.root, self.textvar, default, *items) + textvar2 = tkinter.StringVar(self.root) + optmenu2 = ttk.OptionMenu(self.root, textvar2, default, *items) + optmenu.pack() + optmenu2.pack() + optmenu['menu'].invoke(1) + optmenu2['menu'].invoke(2) + optmenu_stringvar_name = optmenu['menu'].entrycget(0, 'variable') + optmenu2_stringvar_name = optmenu2['menu'].entrycget(0, 'variable') + self.assertNotEqual(optmenu_stringvar_name, + optmenu2_stringvar_name) + self.assertEqual(self.root.tk.globalgetvar(optmenu_stringvar_name), + items[1]) + self.assertEqual(self.root.tk.globalgetvar(optmenu2_stringvar_name), + items[2]) + + optmenu.destroy() + optmenu2.destroy() + + def test_trace_variable(self): + # prior to bpo45160, tracing a variable would cause the callback to be made twice + success = [] + items = ('a', 'b', 'c') + textvar = tkinter.StringVar(self.root) + def cb_test(*args): + success.append(textvar.get()) + optmenu = ttk.OptionMenu(self.root, textvar, "a", *items) + optmenu.pack() + cb_name = textvar.trace_add("write", cb_test) + optmenu['menu'].invoke(1) + self.assertEqual(success, ['b']) + self.assertEqual(textvar.get(), 'b') + textvar.trace_remove("write", cb_name) + optmenu.destroy() + + def test_specify_name(self): + textvar = tkinter.StringVar(self.root) + widget = ttk.OptionMenu(self.root, textvar, ":)", name="option_menu_ex") + self.assertEqual(str(widget), ".option_menu_ex") + self.assertIs(self.root.children["option_menu_ex"], widget) + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_labeledscale(self): + self._test_widget(ttk.LabeledScale) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_ttk/test_style.py b/Lib/test/test_ttk/test_style.py new file mode 100644 index 00000000000..56d8a5931fd --- /dev/null +++ b/Lib/test/test_ttk/test_style.py @@ -0,0 +1,464 @@ +import unittest +import sys +import tkinter +from tkinter import ttk +from tkinter import TclError +from test import support +from test.support import requires +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import AbstractTkTest, get_tk_patchlevel + +requires('gui') + +CLASS_NAMES = [ + '.', 'ComboboxPopdownFrame', 'Heading', + 'Horizontal.TProgressbar', 'Horizontal.TScale', 'Item', 'Sash', + 'TButton', 'TCheckbutton', 'TCombobox', 'TEntry', + 'TLabelframe', 'TLabelframe.Label', 'TMenubutton', + 'TNotebook', 'TNotebook.Tab', 'Toolbutton', 'TProgressbar', + 'TRadiobutton', 'Treeview', 'TScale', 'TScrollbar', 'TSpinbox', + 'Vertical.TProgressbar', 'Vertical.TScale' +] + +class StyleTest(AbstractTkTest, unittest.TestCase): + + def setUp(self): + super().setUp() + self.style = ttk.Style(self.root) + + + def test_configure(self): + style = self.style + style.configure('TButton', background='yellow') + self.assertEqual(style.configure('TButton', 'background'), + 'yellow') + self.assertIsInstance(style.configure('TButton'), dict) + + + def test_map(self): + style = self.style + + # Single state + for states in ['active'], [('active',)]: + with self.subTest(states=states): + style.map('TButton', background=[(*states, 'white')]) + expected = [('active', 'white')] + self.assertEqual(style.map('TButton', 'background'), expected) + m = style.map('TButton') + self.assertIsInstance(m, dict) + self.assertEqual(m['background'], expected) + + # Multiple states + for states in ['pressed', '!disabled'], ['pressed !disabled'], [('pressed', '!disabled')]: + with self.subTest(states=states): + style.map('TButton', background=[(*states, 'black')]) + expected = [('pressed', '!disabled', 'black')] + self.assertEqual(style.map('TButton', 'background'), expected) + m = style.map('TButton') + self.assertIsInstance(m, dict) + self.assertEqual(m['background'], expected) + + # Default state + for states in [], [''], [()]: + with self.subTest(states=states): + style.map('TButton', background=[(*states, 'grey')]) + expected = [('grey',)] + self.assertEqual(style.map('TButton', 'background'), expected) + m = style.map('TButton') + self.assertIsInstance(m, dict) + self.assertEqual(m['background'], expected) + + + def test_lookup(self): + style = self.style + style.configure('TButton', background='yellow') + style.map('TButton', background=[('active', 'background', 'blue')]) + + self.assertEqual(style.lookup('TButton', 'background'), 'yellow') + self.assertEqual(style.lookup('TButton', 'background', + ['active', 'background']), 'blue') + self.assertEqual(style.lookup('TButton', 'optionnotdefined', + default='iknewit'), 'iknewit') + + + def test_layout(self): + style = self.style + self.assertRaises(tkinter.TclError, style.layout, 'NotALayout') + tv_style = style.layout('Treeview') + + # "erase" Treeview layout + style.layout('Treeview', '') + self.assertEqual(style.layout('Treeview'), + [('null', {'sticky': 'nswe'})] + ) + + # restore layout + style.layout('Treeview', tv_style) + self.assertEqual(style.layout('Treeview'), tv_style) + + # should return a list + self.assertIsInstance(style.layout('TButton'), list) + + # correct layout, but "option" doesn't exist as option + self.assertRaises(tkinter.TclError, style.layout, 'Treeview', + [('name', {'option': 'inexistent'})]) + + + def test_theme_use(self): + self.assertRaises(tkinter.TclError, self.style.theme_use, + 'nonexistingname') + + curr_theme = self.style.theme_use() + new_theme = None + for theme in self.style.theme_names(): + if theme != curr_theme: + new_theme = theme + self.style.theme_use(theme) + break + else: + # just one theme available, can't go on with tests + return + + self.assertFalse(curr_theme == new_theme) + self.assertFalse(new_theme != self.style.theme_use()) + + self.style.theme_use(curr_theme) + + def test_theme_settings(self): + style = self.style + theme = style.theme_use() + style.theme_settings(theme, { + 'Test.TLabel': { + 'configure': {'foreground': 'red', 'background': 'blue'}, + 'map': {'foreground': [('active', 'green')]}, + }, + }) + self.assertEqual(style.lookup('Test.TLabel', 'foreground'), 'red') + self.assertEqual(style.lookup('Test.TLabel', 'background'), 'blue') + self.assertEqual(style.map('Test.TLabel', 'foreground'), + [('active', 'green')]) + self.assertRaises(tkinter.TclError, style.theme_settings, + 'nonexistingname', {}) + + def test_configure_custom_copy(self): + style = self.style + + curr_theme = self.style.theme_use() + self.addCleanup(self.style.theme_use, curr_theme) + for theme in self.style.theme_names(): + self.style.theme_use(theme) + for name in CLASS_NAMES: + default = style.configure(name) + if not default: + continue + with self.subTest(theme=theme, name=name): + if support.verbose >= 2: + print('configure', theme, name, default) + if (theme in ('vista', 'xpnative') + and sys.getwindowsversion()[:2] == (6, 1)): + # Fails on the Windows 7 buildbot + continue + newname = f'C.{name}' + self.assertEqual(style.configure(newname), None) + style.configure(newname, **default) + self.assertEqual(style.configure(newname), default) + for key, value in default.items(): + self.assertEqual(style.configure(newname, key), value) + + + def test_map_custom_copy(self): + style = self.style + + curr_theme = self.style.theme_use() + self.addCleanup(self.style.theme_use, curr_theme) + for theme in self.style.theme_names(): + self.style.theme_use(theme) + for name in CLASS_NAMES: + default = style.map(name) + if not default: + continue + with self.subTest(theme=theme, name=name): + if support.verbose >= 2: + print('map', theme, name, default) + if (theme in ('vista', 'xpnative') + and sys.getwindowsversion()[:2] == (6, 1)): + # Fails on the Windows 7 buildbot + continue + newname = f'C.{name}' + self.assertEqual(style.map(newname), {}) + style.map(newname, **default) + if theme == 'alt' and name == '.' and get_tk_patchlevel(self.root) < (8, 6, 1): + default['embossed'] = [('disabled', '1')] + self.assertEqual(style.map(newname), default) + for key, value in default.items(): + self.assertEqual(style.map(newname, key), value) + + def test_element_options(self): + style = self.style + element_names = style.element_names() + self.assertNotIsInstance(element_names, str) + for name in element_names: + self.assertIsInstance(name, str) + element_options = style.element_options(name) + self.assertNotIsInstance(element_options, str) + for optname in element_options: + self.assertIsInstance(optname, str) + + def test_element_create_errors(self): + style = self.style + with self.assertRaises(TypeError): + style.element_create('plain.newelem') + with self.assertRaisesRegex(TclError, 'No such element type spam'): + style.element_create('plain.newelem', 'spam') + + def test_element_create_from(self): + style = self.style + style.element_create('plain.background', 'from', 'default') + self.assertIn('plain.background', style.element_names()) + style.element_create('plain.arrow', 'from', 'default', 'rightarrow') + self.assertIn('plain.arrow', style.element_names()) + + def test_element_create_from_errors(self): + style = self.style + with self.assertRaises(IndexError): + style.element_create('plain.newelem', 'from') + with self.assertRaisesRegex(TclError, + 'theme "spam" (does not|doesn\'t) exist'): + style.element_create('plain.newelem', 'from', 'spam') + + def test_element_create_image(self): + style = self.style + image = tkinter.PhotoImage(master=self.root, width=12, height=10) + style.element_create('block', 'image', image) + self.assertIn('block', style.element_names()) + + style.layout('TestLabel1', [('block', {'sticky': 'news'})]) + a = ttk.Label(self.root, style='TestLabel1') + a.pack(expand=True, fill='both') + self.assertEqual(a.winfo_reqwidth(), 12) + self.assertEqual(a.winfo_reqheight(), 10) + + imgfile = support.findfile('python.xbm', subdir='tkinterdata') + img1 = tkinter.BitmapImage(master=self.root, file=imgfile, + foreground='yellow', background='blue') + img2 = tkinter.BitmapImage(master=self.root, file=imgfile, + foreground='blue', background='yellow') + img3 = tkinter.BitmapImage(master=self.root, file=imgfile, + foreground='white', background='black') + style.element_create('TestButton.button', 'image', + img1, ('pressed', img2), ('active', img3), + border=(2, 4), sticky='we') + self.assertIn('TestButton.button', style.element_names()) + + style.layout('TestButton', [('TestButton.button', {'sticky': 'news'})]) + b = ttk.Button(self.root, style='TestButton') + b.pack(expand=True, fill='both') + self.assertEqual(b.winfo_reqwidth(), 16) + self.assertEqual(b.winfo_reqheight(), 16) + + def test_element_create_image_errors(self): + style = self.style + image = tkinter.PhotoImage(master=self.root, width=10, height=10) + with self.assertRaises(IndexError): + style.element_create('block2', 'image') + with self.assertRaises(TypeError): + style.element_create('block2', 'image', image, 1) + with self.assertRaises(ValueError): + style.element_create('block2', 'image', image, ()) + with self.assertRaisesRegex(TclError, 'Invalid state name'): + style.element_create('block2', 'image', image, ('spam', image)) + with self.assertRaisesRegex(TclError, 'Invalid state name'): + style.element_create('block2', 'image', image, (1, image)) + with self.assertRaises(TypeError): + style.element_create('block2', 'image', image, ('pressed', 1, image)) + with self.assertRaises(TypeError): + style.element_create('block2', 'image', image, (1, 'selected', image)) + with self.assertRaisesRegex(TclError, 'bad option'): + style.element_create('block2', 'image', image, spam=1) + + def test_element_create_vsapi_1(self): + style = self.style + if 'xpnative' not in style.theme_names(): + self.skipTest("requires 'xpnative' theme") + style.element_create('smallclose', 'vsapi', 'WINDOW', 19, [ + ('disabled', 4), + ('pressed', 3), + ('active', 2), + ('', 1)]) + style.layout('CloseButton', + [('CloseButton.smallclose', {'sticky': 'news'})]) + b = ttk.Button(self.root, style='CloseButton') + b.pack(expand=True, fill='both') + self.assertEqual(b.winfo_reqwidth(), 13) + self.assertEqual(b.winfo_reqheight(), 13) + + def test_element_create_vsapi_2(self): + style = self.style + if 'xpnative' not in style.theme_names(): + self.skipTest("requires 'xpnative' theme") + style.element_create('pin', 'vsapi', 'EXPLORERBAR', 3, [ + ('pressed', '!selected', 3), + ('active', '!selected', 2), + ('pressed', 'selected', 6), + ('active', 'selected', 5), + ('selected', 4), + ('', 1)]) + style.layout('Explorer.Pin', + [('Explorer.Pin.pin', {'sticky': 'news'})]) + pin = ttk.Checkbutton(self.root, style='Explorer.Pin') + pin.pack(expand=True, fill='both') + self.assertEqual(pin.winfo_reqwidth(), 16) + self.assertEqual(pin.winfo_reqheight(), 16) + + def test_element_create_vsapi_3(self): + style = self.style + if 'xpnative' not in style.theme_names(): + self.skipTest("requires 'xpnative' theme") + style.element_create('headerclose', 'vsapi', 'EXPLORERBAR', 2, [ + ('pressed', 3), + ('active', 2), + ('', 1)]) + style.layout('Explorer.CloseButton', + [('Explorer.CloseButton.headerclose', {'sticky': 'news'})]) + b = ttk.Button(self.root, style='Explorer.CloseButton') + b.pack(expand=True, fill='both') + self.assertEqual(b.winfo_reqwidth(), 16) + self.assertEqual(b.winfo_reqheight(), 16) + + def test_theme_create(self): + style = self.style + curr_theme = style.theme_use() + curr_layout = style.layout('TLabel') + style.theme_create('testtheme1') + self.assertIn('testtheme1', style.theme_names()) + + style.theme_create('testtheme2', settings={ + 'elem' : {'element create': ['from', 'default'],}, + 'TLabel' : { + 'configure': {'padding': 10}, + 'layout': [('elem', {'sticky': 'we'})], + }, + }) + self.assertIn('testtheme2', style.theme_names()) + + style.theme_create('testtheme3', 'testtheme2') + self.assertIn('testtheme3', style.theme_names()) + + style.theme_use('testtheme1') + self.assertEqual(style.element_names(), ()) + self.assertEqual(style.layout('TLabel'), curr_layout) + + style.theme_use('testtheme2') + self.assertEqual(style.element_names(), ('elem',)) + self.assertEqual(style.lookup('TLabel', 'padding'), '10') + self.assertEqual(style.layout('TLabel'), [('elem', {'sticky': 'we'})]) + + style.theme_use('testtheme3') + self.assertEqual(style.element_names(), ()) + self.assertEqual(style.lookup('TLabel', 'padding'), '') + self.assertEqual(style.layout('TLabel'), [('elem', {'sticky': 'we'})]) + + style.theme_use(curr_theme) + + def test_theme_create_image(self): + style = self.style + curr_theme = style.theme_use() + image = tkinter.PhotoImage(master=self.root, width=10, height=10) + new_theme = 'testtheme4' + style.theme_create(new_theme, settings={ + 'block' : { + 'element create': ['image', image, {'width': 120, 'height': 100}], + }, + 'TestWidget.block2' : { + 'element create': ['image', image], + }, + 'TestWidget' : { + 'configure': { + 'anchor': 'left', + 'padding': (3, 0, 0, 2), + 'foreground': 'yellow', + }, + 'map': { + 'foreground': [ + ('pressed', 'red'), + ('active', 'disabled', 'blue'), + ], + }, + 'layout': [ + ('TestWidget.block', {'sticky': 'we', 'side': 'left'}), + ('TestWidget.border', { + 'sticky': 'nsw', + 'border': 1, + 'children': [ + ('TestWidget.block2', {'sticky': 'nswe'}) + ] + }) + ], + }, + }) + + style.theme_use(new_theme) + self.assertIn('block', style.element_names()) + self.assertEqual(style.lookup('TestWidget', 'anchor'), 'left') + self.assertEqual(style.lookup('TestWidget', 'padding'), '3 0 0 2') + self.assertEqual(style.lookup('TestWidget', 'foreground'), 'yellow') + self.assertEqual(style.lookup('TestWidget', 'foreground', + ['active']), 'yellow') + self.assertEqual(style.lookup('TestWidget', 'foreground', + ['active', 'pressed']), 'red') + self.assertEqual(style.lookup('TestWidget', 'foreground', + ['active', 'disabled']), 'blue') + self.assertEqual(style.layout('TestWidget'), + [ + ('TestWidget.block', {'side': 'left', 'sticky': 'we'}), + ('TestWidget.border', { + 'sticky': 'nsw', + 'border': '1', + 'children': [('TestWidget.block2', {'sticky': 'nswe'})] + }) + ]) + + b = ttk.Label(self.root, style='TestWidget') + b.pack(expand=True, fill='both') + # The exact width varies with the Tk version and display scaling. + self.assertGreater(b.winfo_reqwidth(), 130) + self.assertEqual(b.winfo_reqheight(), 100) + + style.theme_use(curr_theme) + + def test_theme_create_vsapi(self): + style = self.style + if 'xpnative' not in style.theme_names(): + self.skipTest("requires 'xpnative' theme") + curr_theme = style.theme_use() + new_theme = 'testtheme5' + style.theme_create(new_theme, settings={ + 'pin' : { + 'element create': ['vsapi', 'EXPLORERBAR', 3, [ + ('pressed', '!selected', 3), + ('active', '!selected', 2), + ('pressed', 'selected', 6), + ('active', 'selected', 5), + ('selected', 4), + ('', 1)]], + }, + 'Explorer.Pin' : { + 'layout': [('Explorer.Pin.pin', {'sticky': 'news'})], + }, + }) + + style.theme_use(new_theme) + self.assertIn('pin', style.element_names()) + self.assertEqual(style.layout('Explorer.Pin'), + [('Explorer.Pin.pin', {'sticky': 'nswe'})]) + + pin = ttk.Checkbutton(self.root, style='Explorer.Pin') + pin.pack(expand=True, fill='both') + self.assertEqual(pin.winfo_reqwidth(), 16) + self.assertEqual(pin.winfo_reqheight(), 16) + + style.theme_use(curr_theme) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_ttk/test_widgets.py b/Lib/test/test_ttk/test_widgets.py new file mode 100644 index 00000000000..216f5304bba --- /dev/null +++ b/Lib/test/test_ttk/test_widgets.py @@ -0,0 +1,2202 @@ +import unittest +import tkinter +from tkinter import ttk, TclError +from test.support import requires, gc_collect +import sys + +from test.test_ttk_textonly import MockTclObj +from test.test_tkinter.support import setUpModule # noqa: F401 +from test.test_tkinter.support import ( + AbstractTkTest, requires_tk, tk_version, get_tk_patchlevel, + simulate_mouse_click, wait_until_mapped, AbstractDefaultRootTest) +from test.test_tkinter.widget_tests import (add_configure_tests, + AbstractWidgetTest, StandardOptionsTests, IntegerSizeTests, PixelSizeTests) + +requires('gui') + + +class StandardTtkOptionsTests(StandardOptionsTests): + + def test_configure_class(self): + widget = self.create() + self.assertEqual(widget['class'], '') + errmsg='attempt to change read-only option' + if get_tk_patchlevel(self.root) < (8, 6, 0, 'beta', 3): + errmsg='Attempt to change read-only option' + self.checkInvalidParam(widget, 'class', 'Foo', errmsg=errmsg) + widget2 = self.create(class_='Foo') + self.assertEqual(widget2['class'], 'Foo') + + def test_configure_padding(self): + widget = self.create() + if get_tk_patchlevel(self.root) < (8, 6, 14): + def padding_conv(value): + self.assertIsInstance(value, tuple) + return tuple(map(str, value)) + else: + padding_conv = None + self.checkParam(widget, 'padding', 0, expected=(0,), conv=padding_conv) + self.checkParam(widget, 'padding', 5, expected=(5,), conv=padding_conv) + self.checkParam(widget, 'padding', (5, 6), + expected=(5, 6), conv=padding_conv) + self.checkParam(widget, 'padding', (5, 6, 7), + expected=(5, 6, 7), conv=padding_conv) + self.checkParam(widget, 'padding', (5, 6, 7, 8), + expected=(5, 6, 7, 8), conv=padding_conv) + self.checkParam(widget, 'padding', ('5p', '6p', '7p', '8p')) + self.checkParam(widget, 'padding', (), expected='') + + def test_configure_state(self): + widget = self.create() + self.checkParams(widget, 'state', 'active', 'disabled', 'readonly') + + def test_configure_style(self): + widget = self.create() + self.assertEqual(widget['style'], '') + errmsg = 'Layout Foo not found' + if hasattr(self, 'default_orient'): + errmsg = ('Layout %s.Foo not found' % + getattr(self, 'default_orient').title()) + self.checkInvalidParam(widget, 'style', 'Foo', + errmsg=errmsg) + widget2 = self.create(class_='Foo') + self.assertEqual(widget2['class'], 'Foo') + # XXX + + def test_configure_relief(self): + widget = self.create() + self.checkReliefParam(widget, 'relief', + allow_empty=(tk_version >= (8, 7))) + + +class WidgetTest(AbstractTkTest, unittest.TestCase): + """Tests methods available in every ttk widget.""" + + def setUp(self): + super().setUp() + self.widget = ttk.Button(self.root, width=0, text="Text") + self.widget.pack() + + def test_identify(self): + # Identifying the element under a point requires the widget to be + # mapped with a real size; the rest of the checks do not. + if wait_until_mapped(self.widget): + self.assertEqual(self.widget.identify( + int(self.widget.winfo_width() / 2), + int(self.widget.winfo_height() / 2) + ), "label") + self.assertEqual(self.widget.identify(-1, -1), "") + + self.assertRaises(tkinter.TclError, self.widget.identify, None, 5) + self.assertRaises(tkinter.TclError, self.widget.identify, 5, None) + self.assertRaises(tkinter.TclError, self.widget.identify, 5, '') + + def test_widget_state(self): + # XXX not sure about the portability of all these tests + self.assertEqual(self.widget.state(), ()) + self.assertEqual(self.widget.instate(['!disabled']), True) + + # changing from !disabled to disabled + self.assertEqual(self.widget.state(['disabled']), ('!disabled', )) + # no state change + self.assertEqual(self.widget.state(['disabled']), ()) + # change back to !disable but also active + self.assertEqual(self.widget.state(['!disabled', 'active']), + ('!active', 'disabled')) + # no state changes, again + self.assertEqual(self.widget.state(['!disabled', 'active']), ()) + self.assertEqual(self.widget.state(['active', '!disabled']), ()) + + def test_cb(arg1, **kw): + return arg1, kw + self.assertEqual(self.widget.instate(['!disabled'], + test_cb, "hi", **{"msg": "there"}), + ('hi', {'msg': 'there'})) + + # attempt to set invalid statespec + currstate = self.widget.state() + self.assertRaises(tkinter.TclError, self.widget.instate, + ['badstate']) + self.assertRaises(tkinter.TclError, self.widget.instate, + ['disabled', 'badstate']) + # verify that widget didn't change its state + self.assertEqual(currstate, self.widget.state()) + + # ensuring that passing None as state doesn't modify current state + self.widget.state(['active', '!disabled']) + self.assertEqual(self.widget.state(), ('active', )) + + +class AbstractToplevelTest(AbstractWidgetTest, PixelSizeTests): + _rounds_pixels = False + _clipped = {} + + +@add_configure_tests(StandardTtkOptionsTests) +class FrameTest(AbstractToplevelTest, unittest.TestCase): + OPTIONS = ( + 'borderwidth', 'class', 'cursor', 'height', + 'padding', 'relief', 'style', 'takefocus', + 'width', + ) + + def create(self, **kwargs): + return ttk.Frame(self.root, **kwargs) + + +@add_configure_tests(StandardTtkOptionsTests) +class LabelFrameTest(AbstractToplevelTest, unittest.TestCase): + OPTIONS = ( + 'borderwidth', 'class', 'cursor', 'height', + 'labelanchor', 'labelwidget', + 'padding', 'relief', 'style', 'takefocus', + 'text', 'underline', 'width', + ) + + def create(self, **kwargs): + return ttk.LabelFrame(self.root, **kwargs) + + def test_configure_labelanchor(self): + widget = self.create() + self.checkEnumParam(widget, 'labelanchor', + 'e', 'en', 'es', 'n', 'ne', 'nw', 's', 'se', 'sw', 'w', 'wn', 'ws', + errmsg='Bad label anchor specification {}') + self.checkInvalidParam(widget, 'labelanchor', 'center') + + def test_configure_labelwidget(self): + widget = self.create() + label = ttk.Label(self.root, text='Mupp', name='foo') + self.checkParam(widget, 'labelwidget', label, expected='.foo') + label.destroy() + + +class AbstractLabelTest(AbstractWidgetTest): + _allow_empty_justify = True + _rounds_pixels = False + _clipped = {} + + def checkImageParam(self, widget, name): + image = tkinter.PhotoImage(master=self.root, name='image1') + image2 = tkinter.PhotoImage(master=self.root, name='image2') + self.checkParam(widget, name, image, expected=('image1',)) + self.checkParam(widget, name, 'image1', expected=('image1',)) + self.checkParam(widget, name, (image,), expected=('image1',)) + self.checkParam(widget, name, (image, 'active', image2), + expected=('image1', 'active', 'image2')) + self.checkParam(widget, name, 'image1 active image2', + expected=('image1', 'active', 'image2')) + if tk_version < (8, 7): + errmsg = 'image "spam" doesn\'t exist' + else: + errmsg = 'image "spam" does not exist' + self.checkInvalidParam(widget, name, 'spam', errmsg=errmsg) + + def test_configure_compound(self): + values = ('none', 'text', 'image', 'center', 'top', 'bottom', 'left', 'right') + if tk_version >= (8, 7): + values += ('',) + widget = self.create() + self.checkEnumParam(widget, 'compound', *values, allow_empty=True) + + test_configure_justify = requires_tk(8, 7)(StandardOptionsTests.test_configure_justify) + + def test_configure_width(self): + widget = self.create() + self.checkParams(widget, 'width', 402, -402, 0) + + +@add_configure_tests(StandardTtkOptionsTests) +class LabelTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'anchor', 'background', 'borderwidth', + 'class', 'compound', 'cursor', 'font', 'foreground', + 'image', 'justify', 'padding', 'relief', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'width', 'wraplength', + ) + _conv_pixels = False + _allow_empty_justify = tk_version >= (8, 7) + + def create(self, **kwargs): + return ttk.Label(self.root, **kwargs) + + def test_configure_anchor(self): + widget = self.create() + values = ('n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center') + if get_tk_patchlevel(self.root) >= (9, 0, 5): + values += ('',) + self.checkEnumParam(widget, 'anchor', *values) + + test_configure_justify = StandardOptionsTests.test_configure_justify + + +@add_configure_tests(StandardTtkOptionsTests) +class ButtonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'class', 'command', 'compound', 'cursor', 'default', + 'image', 'justify', 'padding', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'width', + ) + + def create(self, **kwargs): + return ttk.Button(self.root, **kwargs) + + def test_configure_default(self): + widget = self.create() + values = ('normal', 'active', 'disabled') + self.checkEnumParam(widget, 'default', *values, + sort=tk_version >= (8, 7)) + + def test_invoke(self): + success = [] + btn = ttk.Button(self.root, command=lambda: success.append(1)) + btn.invoke() + self.assertTrue(success) + + +@add_configure_tests(StandardTtkOptionsTests) +class CheckbuttonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'class', 'command', 'compound', 'cursor', + 'image', 'justify', + 'offvalue', 'onvalue', + 'padding', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'variable', 'width', + ) + + def create(self, **kwargs): + return ttk.Checkbutton(self.root, **kwargs) + + def test_configure_offvalue(self): + widget = self.create() + self.checkParams(widget, 'offvalue', 1, 2.3, '', 'any string') + + def test_configure_onvalue(self): + widget = self.create() + self.checkParams(widget, 'onvalue', 1, 2.3, '', 'any string') + + def test_invoke(self): + success = [] + def cb_test(): + success.append(1) + return "cb test called" + + cbtn = ttk.Checkbutton(self.root, command=cb_test) + # the variable automatically created by ttk.Checkbutton is actually + # undefined till we invoke the Checkbutton + self.assertEqual(cbtn.state(), ('alternate', )) + self.assertRaises(tkinter.TclError, cbtn.tk.globalgetvar, + cbtn['variable']) + + res = cbtn.invoke() + self.assertEqual(res, "cb test called") + self.assertEqual(cbtn['onvalue'], + cbtn.tk.globalgetvar(cbtn['variable'])) + self.assertTrue(success) + + cbtn['command'] = '' + res = cbtn.invoke() + if tk_version >= (8, 7) and self.wantobjects: + self.assertEqual(res, ()) + else: + self.assertEqual(str(res), '') + self.assertLessEqual(len(success), 1) + self.assertEqual(cbtn['offvalue'], + cbtn.tk.globalgetvar(cbtn['variable'])) + + def test_unique_variables(self): + frames = [] + buttons = [] + for i in range(2): + f = ttk.Frame(self.root) + f.pack() + frames.append(f) + for j in 'AB': + b = ttk.Checkbutton(f, text=j) + b.pack() + buttons.append(b) + variables = [str(b['variable']) for b in buttons] + self.assertEqual(len(set(variables)), 4, variables) + + def test_unique_variables2(self): + buttons = [] + f = ttk.Frame(self.root) + f.pack() + f = ttk.Frame(self.root) + f.pack() + for j in 'AB': + b = tkinter.Checkbutton(f, text=j) + b.pack() + buttons.append(b) + # Should be larger than the number of all previously created + # tkinter.Checkbutton widgets: + for j in range(100): + b = ttk.Checkbutton(f, text=str(j)) + b.pack() + buttons.append(b) + names = [str(b) for b in buttons] + self.assertEqual(len(set(names)), len(buttons), names) + variables = [str(b['variable']) for b in buttons] + self.assertEqual(len(set(variables)), len(buttons), variables) + + +@add_configure_tests(IntegerSizeTests, StandardTtkOptionsTests) +class EntryTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'background', 'class', 'cursor', + 'exportselection', 'font', 'foreground', + 'invalidcommand', 'justify', + 'placeholder', 'placeholderforeground', + 'show', 'state', 'style', 'takefocus', 'textvariable', + 'validate', 'validatecommand', 'width', 'xscrollcommand', + ) + _rounds_pixels = False + _clipped = {} + # bpo-27313: macOS Tk/Tcl may or may not report 'Entry.field'. + IDENTIFY_AS = {'Entry.field', 'textarea'} + + def setUp(self): + super().setUp() + self.entry = self.create() + self._allow_empty_justify = get_tk_patchlevel(self.root) >= (9, 0, 5) + + def create(self, **kwargs): + return ttk.Entry(self.root, **kwargs) + + def _arrow_x(self, widget, y, arrow): + # Return an x coordinate on the up/down *arrow* element in row y, + # found by scanning inward from the right edge of the widget. A + # fixed inset such as width - 5 lands in the arrow element's + # right-hand border, which scales with the display scaling, so at a + # high DPI identify() there returns 'field' instead of the arrow. + self.assertTrue(wait_until_mapped(widget, full_size=True)) + width = widget.winfo_width() + for x in range(width - 1, width // 2, -1): + if widget.identify(x, y).endswith(arrow): + return x + self.fail(f'no {arrow} found in row {y}') + + def test_configure_invalidcommand(self): + widget = self.create() + self.checkCommandParam(widget, 'invalidcommand') + + def test_configure_show(self): + widget = self.create() + self.checkParam(widget, 'show', '*') + self.checkParam(widget, 'show', '') + self.checkParam(widget, 'show', ' ') + + def test_configure_validate(self): + widget = self.create() + self.checkEnumParam(widget, 'validate', + 'all', 'key', 'focus', 'focusin', 'focusout', 'none') + + def test_configure_validatecommand(self): + widget = self.create() + self.checkCommandParam(widget, 'validatecommand') + + def test_bbox(self): + self.assertIsBoundingBox(self.entry.bbox(0)) + self.assertRaises(tkinter.TclError, self.entry.bbox, 'noindex') + self.assertRaises(tkinter.TclError, self.entry.bbox, None) + + def test_identify(self): + if (tk_version >= (9, 0) and sys.platform == 'darwin' + and isinstance(self.entry, ttk.Combobox)): + self.skipTest('Test does not work on macOS Tk 9.') + # https://core.tcl-lang.org/tk/tktview/8b49e9cfa6 + self.entry.pack() + + # Identifying the element under a point requires the widget to be + # mapped with a real size; the rest of the checks do not. + if wait_until_mapped(self.entry): + # Probe the centre of the widget: a fixed pixel such as (5, 5) + # lands in the field at a normal scaling but in the surrounding + # padding at a high DPI. + x = self.entry.winfo_width() // 2 + y = self.entry.winfo_height() // 2 + self.assertIn(self.entry.identify(x, y), self.IDENTIFY_AS) + self.assertEqual(self.entry.identify(-1, -1), "") + + self.assertRaises(tkinter.TclError, self.entry.identify, None, 5) + self.assertRaises(tkinter.TclError, self.entry.identify, 5, None) + self.assertRaises(tkinter.TclError, self.entry.identify, 5, '') + + def test_validation_options(self): + success = [] + test_invalid = lambda: success.append(True) + + self.entry['validate'] = 'none' + self.entry['validatecommand'] = lambda: False + + self.entry['invalidcommand'] = test_invalid + self.entry.validate() + self.assertTrue(success) + + self.entry['invalidcommand'] = '' + self.entry.validate() + self.assertEqual(len(success), 1) + + self.entry['invalidcommand'] = test_invalid + self.entry['validatecommand'] = lambda: True + self.entry.validate() + self.assertEqual(len(success), 1) + + self.entry['validatecommand'] = '' + self.entry.validate() + self.assertEqual(len(success), 1) + + self.entry['validatecommand'] = True + self.assertRaises(tkinter.TclError, self.entry.validate) + + def test_validation(self): + validation = [] + def validate(to_insert): + if not 'a' <= to_insert.lower() <= 'z': + validation.append(False) + return False + validation.append(True) + return True + + self.entry['validate'] = 'key' + self.entry['validatecommand'] = self.entry.register(validate), '%S' + + self.entry.insert('end', 1) + self.entry.insert('end', 'a') + self.assertEqual(validation, [False, True]) + self.assertEqual(self.entry.get(), 'a') + + def test_revalidation(self): + def validate(content): + for letter in content: + if not 'a' <= letter.lower() <= 'z': + return False + return True + + self.entry['validatecommand'] = self.entry.register(validate), '%P' + + self.entry.insert('end', 'avocado') + self.assertEqual(self.entry.validate(), True) + self.assertEqual(self.entry.state(), ()) + + self.entry.delete(0, 'end') + self.assertEqual(self.entry.get(), '') + + self.entry.insert('end', 'a1b') + self.assertEqual(self.entry.validate(), False) + self.assertEqual(self.entry.state(), ('invalid', )) + + self.entry.delete(1) + self.assertEqual(self.entry.validate(), True) + self.assertEqual(self.entry.state(), ()) + + +@add_configure_tests(IntegerSizeTests, StandardTtkOptionsTests) +class ComboboxTest(EntryTest, unittest.TestCase): + OPTIONS = ( + 'background', 'class', 'cursor', 'exportselection', + 'font', 'foreground', 'height', 'invalidcommand', + 'justify', 'placeholder', 'placeholderforeground', 'postcommand', + 'show', 'state', 'style', + 'takefocus', 'textvariable', + 'validate', 'validatecommand', 'values', + 'width', 'xscrollcommand', + ) + IDENTIFY_AS = {'Combobox.button', 'textarea'} + + def setUp(self): + super().setUp() + self.combo = self.create() + + def create(self, **kwargs): + return ttk.Combobox(self.root, **kwargs) + + def test_configure_height(self): + widget = self.create() + self.checkParams(widget, 'height', 100, 101.2, 102.6, -100, 0, '1i') + + def _show_drop_down_listbox(self): + y = 5 + if sys.platform != 'darwin': # there's no down arrow on macOS + x = self._arrow_x(self.combo, y, 'downarrow') + else: + x = self.combo.winfo_width() - 5 + self.combo.event_generate('', x=x, y=y) + self.combo.event_generate('', x=x, y=y) + + def test_virtual_event(self): + if (tk_version >= (9, 0) and sys.platform == 'darwin' + and isinstance(self.entry, ttk.Combobox)): + self.skipTest('Test does not work on macOS Tk 9.') + # https://core.tcl-lang.org/tk/tktview/8b49e9cfa6 + success = [] + + self.combo['values'] = [1] + self.combo.bind('<>', + lambda evt: success.append(True)) + self.combo.pack() + self.require_mapped(self.combo) + + height = self.combo.winfo_height() + self._show_drop_down_listbox() + self.combo.update() + self.combo.event_generate('') + self.combo.update() + + self.assertTrue(success) + + def test_configure_postcommand(self): + if (tk_version >= (9, 0) and sys.platform == 'darwin' + and isinstance(self.entry, ttk.Combobox)): + self.skipTest('Test does not work on macOS Tk 9.') + # https://core.tcl-lang.org/tk/tktview/8b49e9cfa6 + success = [] + + self.combo['postcommand'] = lambda: success.append(True) + self.combo.pack() + self.require_mapped(self.combo) + + self._show_drop_down_listbox() + self.assertTrue(success) + + # testing postcommand removal + self.combo['postcommand'] = '' + self._show_drop_down_listbox() + self.assertEqual(len(success), 1) + + def test_configure_values(self): + def check_get_current(getval, currval): + self.assertEqual(self.combo.get(), getval) + self.assertEqual(self.combo.current(), currval) + + self.assertIn(self.combo['values'], ((), '')) + check_get_current('', -1) + + self.checkParam(self.combo, 'values', 'mon tue wed thur', + expected=('mon', 'tue', 'wed', 'thur')) + self.checkParam(self.combo, 'values', ('mon', 'tue', 'wed', 'thur')) + self.checkParam(self.combo, 'values', (42, 3.14, '', 'any string')) + self.checkParam(self.combo, 'values', '') + + self.combo['values'] = ['a', 1, 'c'] + + self.combo.set('c') + check_get_current('c', 2) + + self.combo.current(0) + check_get_current('a', 0) + + self.combo.set('d') + check_get_current('d', -1) + + # testing values with empty string + self.combo.set('') + self.combo['values'] = (1, 2, '', 3) + check_get_current('', 2) + + # testing values with empty string set through configure + self.combo.configure(values=[1, '', 2]) + self.assertEqual(self.combo['values'], + ('1', '', '2') if self.wantobjects else + '1 {} 2') + + # testing values with spaces + self.combo['values'] = ['a b', 'a\tb', 'a\nb'] + self.assertEqual(self.combo['values'], + ('a b', 'a\tb', 'a\nb') if self.wantobjects else + '{a b} {a\tb} {a\nb}') + + # testing values with special characters + self.combo['values'] = [r'a\tb', '"a"', '} {'] + self.assertEqual(self.combo['values'], + (r'a\tb', '"a"', '} {') if self.wantobjects else + r'a\\tb {"a"} \}\ \{') + + # out of range + self.assertRaises(tkinter.TclError, self.combo.current, + len(self.combo['values'])) + # it expects an integer (or something that can be converted to int) + self.assertRaises(tkinter.TclError, self.combo.current, '') + + # testing creating combobox with empty string in values + combo2 = ttk.Combobox(self.root, values=[1, 2, '']) + self.assertEqual(combo2['values'], + ('1', '2', '') if self.wantobjects else '1 2 {}') + combo2.destroy() + + +@add_configure_tests(IntegerSizeTests, StandardTtkOptionsTests) +class PanedWindowTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'cursor', 'height', + 'orient', 'style', 'takefocus', 'width', + ) + _rounds_pixels = False + _clipped = {} + + def setUp(self): + super().setUp() + self.paned = self.create() + + def create(self, **kwargs): + return ttk.PanedWindow(self.root, **kwargs) + + def test_configure_orient(self): + widget = self.create() + self.assertEqual(str(widget['orient']), 'vertical') + errmsg='attempt to change read-only option' + if get_tk_patchlevel(self.root) < (8, 6, 0, 'beta', 3): + errmsg='Attempt to change read-only option' + self.checkInvalidParam(widget, 'orient', 'horizontal', + errmsg=errmsg) + widget2 = self.create(orient='horizontal') + self.assertEqual(str(widget2['orient']), 'horizontal') + + def test_add(self): + # attempt to add a child that is not a direct child of the paned window + label = ttk.Label(self.paned) + child = ttk.Label(label) + self.assertRaises(tkinter.TclError, self.paned.add, child) + label.destroy() + child.destroy() + # another attempt + label = ttk.Label(self.root) + child = ttk.Label(label) + self.assertRaises(tkinter.TclError, self.paned.add, child) + child.destroy() + label.destroy() + + good_child = ttk.Label(self.root) + self.paned.add(good_child) + # re-adding a child is not accepted + self.assertRaises(tkinter.TclError, self.paned.add, good_child) + + other_child = ttk.Label(self.paned) + self.paned.add(other_child) + self.assertEqual(self.paned.pane(0), self.paned.pane(1)) + self.assertRaises(tkinter.TclError, self.paned.pane, 2) + good_child.destroy() + other_child.destroy() + self.assertRaises(tkinter.TclError, self.paned.pane, 0) + + def test_forget(self): + self.assertRaises(tkinter.TclError, self.paned.forget, None) + self.assertRaises(tkinter.TclError, self.paned.forget, 0) + + self.paned.add(ttk.Label(self.root)) + self.paned.forget(0) + self.assertRaises(tkinter.TclError, self.paned.forget, 0) + + def test_insert(self): + self.assertRaises(tkinter.TclError, self.paned.insert, None, 0) + self.assertRaises(tkinter.TclError, self.paned.insert, 0, None) + self.assertRaises(tkinter.TclError, self.paned.insert, 0, 0) + + child = ttk.Label(self.root) + child2 = ttk.Label(self.root) + child3 = ttk.Label(self.root) + + if tk_version >= (8, 7): + self.paned.insert(0, child) + self.assertEqual(self.paned.panes(), (str(child),)) + self.paned.forget(0) + else: + self.assertRaises(tkinter.TclError, self.paned.insert, 0, child) + + self.assertEqual(self.paned.panes(), ()) + self.paned.insert('end', child2) + self.paned.insert(0, child) + self.assertEqual(self.paned.panes(), (str(child), str(child2))) + + self.paned.insert(0, child2) + self.assertEqual(self.paned.panes(), (str(child2), str(child))) + + self.paned.insert('end', child3) + self.assertEqual(self.paned.panes(), + (str(child2), str(child), str(child3))) + + # reinserting a child should move it to its current position + panes = self.paned.panes() + self.paned.insert('end', child3) + self.assertEqual(panes, self.paned.panes()) + + # moving child3 to child2 position should result in child2 ending up + # in previous child position and child ending up in previous child3 + # position + self.paned.insert(child2, child3) + self.assertEqual(self.paned.panes(), + (str(child3), str(child2), str(child))) + + def test_pane(self): + self.assertRaises(tkinter.TclError, self.paned.pane, 0) + + child = ttk.Label(self.root) + self.paned.add(child) + self.assertIsInstance(self.paned.pane(0), dict) + self.assertEqual(self.paned.pane(0, weight=None), + 0 if self.wantobjects else '0') + # newer form for querying a single option + self.assertEqual(self.paned.pane(0, 'weight'), + 0 if self.wantobjects else '0') + self.assertEqual(self.paned.pane(0), self.paned.pane(str(child))) + + self.assertRaises(tkinter.TclError, self.paned.pane, 0, + badoption='somevalue') + + def test_sashpos(self): + self.assertRaises(tkinter.TclError, self.paned.sashpos, None) + self.assertRaises(tkinter.TclError, self.paned.sashpos, '') + self.assertRaises(tkinter.TclError, self.paned.sashpos, 0) + + child = ttk.Label(self.paned, text='a') + self.paned.add(child, weight=1) + self.assertRaises(tkinter.TclError, self.paned.sashpos, 0) + child2 = ttk.Label(self.paned, text='b') + self.paned.add(child2) + self.assertRaises(tkinter.TclError, self.paned.sashpos, 1) + + self.paned.pack(expand=True, fill='both') + + curr_pos = self.paned.sashpos(0) + self.paned.sashpos(0, 1000) + self.assertNotEqual(curr_pos, self.paned.sashpos(0)) + self.assertIsInstance(self.paned.sashpos(0), int) + + +@add_configure_tests(StandardTtkOptionsTests) +class RadiobuttonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'class', 'command', 'compound', 'cursor', + 'image', 'justify', + 'padding', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'value', 'variable', 'width', + ) + + def create(self, **kwargs): + return ttk.Radiobutton(self.root, **kwargs) + + def test_configure_value(self): + widget = self.create() + self.checkParams(widget, 'value', 1, 2.3, '', 'any string') + + def test_configure_invoke(self): + success = [] + def cb_test(): + success.append(1) + return "cb test called" + + myvar = tkinter.IntVar(self.root) + cbtn = ttk.Radiobutton(self.root, command=cb_test, + variable=myvar, value=0) + cbtn2 = ttk.Radiobutton(self.root, command=cb_test, + variable=myvar, value=1) + + if self.wantobjects: + conv = lambda x: x + else: + conv = int + + res = cbtn.invoke() + self.assertEqual(res, "cb test called") + self.assertEqual(conv(cbtn['value']), myvar.get()) + self.assertEqual(myvar.get(), + conv(cbtn.tk.globalgetvar(cbtn['variable']))) + self.assertTrue(success) + + cbtn2['command'] = '' + res = cbtn2.invoke() + if tk_version >= (8, 7) and self.wantobjects: + self.assertEqual(res, ()) + else: + self.assertEqual(str(res), '') + self.assertLessEqual(len(success), 1) + self.assertEqual(conv(cbtn2['value']), myvar.get()) + self.assertEqual(myvar.get(), + conv(cbtn.tk.globalgetvar(cbtn['variable']))) + + self.assertEqual(str(cbtn['variable']), str(cbtn2['variable'])) + + +@add_configure_tests(StandardTtkOptionsTests) +class MenubuttonTest(AbstractLabelTest, unittest.TestCase): + OPTIONS = ( + 'class', 'compound', 'cursor', 'direction', + 'image', 'justify', 'menu', 'padding', 'state', 'style', + 'takefocus', 'text', 'textvariable', + 'underline', 'width', + ) + + def create(self, **kwargs): + return ttk.Menubutton(self.root, **kwargs) + + def test_configure_direction(self): + widget = self.create() + values = ('above', 'below', 'left', 'right', 'flush') + self.checkEnumParam(widget, 'direction', *values, + sort=tk_version >= (8, 7)) + + def test_configure_menu(self): + widget = self.create() + menu = tkinter.Menu(widget, name='menu') + self.checkParam(widget, 'menu', menu, conv=str) + menu.destroy() + + +@add_configure_tests(StandardTtkOptionsTests) +class ScaleTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'command', 'cursor', 'from', 'length', + 'orient', 'state', 'style', 'takefocus', 'to', 'value', 'variable', + ) + _rounds_pixels = False + _clipped = {} + default_orient = 'horizontal' + + def setUp(self): + super().setUp() + self.scale = self.create() + self.scale.pack() + self.scale.update() + + def create(self, **kwargs): + return ttk.Scale(self.root, **kwargs) + + def test_configure_from(self): + widget = self.create() + self.checkFloatParam(widget, 'from', 100, 14.9, 15.1, conv=False) + + def test_configure_length(self): + widget = self.create() + self.checkPixelsParam(widget, 'length', 130, 131.2, 135.6, '5i') + + test_configure_state = requires_tk(8, 6, 9)(StandardTtkOptionsTests.test_configure_state) + + def test_configure_to(self): + widget = self.create() + self.checkFloatParam(widget, 'to', 300, 14.9, 15.1, -10, conv=False) + + def test_configure_value(self): + widget = self.create() + self.checkFloatParam(widget, 'value', 300, 14.9, 15.1, -10, conv=False) + + def test_custom_event(self): + failure = [1, 1, 1] # will need to be empty + + funcid = self.scale.bind('<>', lambda evt: failure.pop()) + + self.scale['from'] = 10 + self.scale['from_'] = 10 + self.scale['to'] = 3 + + self.assertFalse(failure) + + failure = [1, 1, 1] + self.scale.configure(from_=2, to=5) + self.scale.configure(from_=0, to=-2) + self.scale.configure(to=10) + + self.assertFalse(failure) + + def test_get(self): + if self.wantobjects: + conv = lambda x: x + else: + conv = float + + # Reading the value at the far edge needs the realized width. + if wait_until_mapped(self.scale): + scale_width = self.scale.winfo_width() + self.assertEqual(self.scale.get(scale_width, 0), self.scale['to']) + + self.assertEqual(conv(self.scale.get(0, 0)), conv(self.scale['from'])) + self.assertEqual(self.scale.get(), self.scale['value']) + self.scale['value'] = 30 + self.assertEqual(self.scale.get(), self.scale['value']) + + self.assertRaises(tkinter.TclError, self.scale.get, '', 0) + self.assertRaises(tkinter.TclError, self.scale.get, 0, '') + + def test_set(self): + if self.wantobjects: + conv = lambda x: x + else: + conv = float + + # set restricts the max/min values according to the current range + max = conv(self.scale['to']) + new_max = max + 10 + self.scale.set(new_max) + self.assertEqual(conv(self.scale.get()), max) + min = conv(self.scale['from']) + self.scale.set(min - 1) + self.assertEqual(conv(self.scale.get()), min) + + # changing directly the variable doesn't impose this limitation tho + var = tkinter.DoubleVar(self.root) + self.scale['variable'] = var + var.set(max + 5) + self.assertEqual(conv(self.scale.get()), var.get()) + self.assertEqual(conv(self.scale.get()), max + 5) + del var + gc_collect() # For PyPy or other GCs. + + # the same happens with the value option + self.scale['value'] = max + 10 + self.assertEqual(conv(self.scale.get()), max + 10) + self.assertEqual(conv(self.scale.get()), conv(self.scale['value'])) + + # nevertheless, note that the max/min values we can get specifying + # x, y coords are the ones according to the current range + self.assertEqual(conv(self.scale.get(0, 0)), min) + # Reading the value at the far edge needs the realized width. + if wait_until_mapped(self.scale): + self.assertEqual( + conv(self.scale.get(self.scale.winfo_width(), 0)), max) + + self.assertRaises(tkinter.TclError, self.scale.set, None) + + +@add_configure_tests(StandardTtkOptionsTests) +class ProgressbarTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'anchor', 'class', 'cursor', 'font', 'foreground', 'justify', + 'orient', 'length', + 'mode', 'maximum', 'phase', 'text', 'wraplength', + 'style', 'takefocus', 'value', 'variable', + ) + _rounds_pixels = False + _clipped = {} + _allow_empty_justify = True + default_orient = 'horizontal' + + def create(self, **kwargs): + return ttk.Progressbar(self.root, **kwargs) + + @requires_tk(8, 7) + def test_configure_anchor(self): + widget = self.create() + self.checkEnumParam(widget, 'anchor', + 'n', 'ne', 'e', 'se', 's', 'sw', 'w', 'nw', 'center', '') + + test_configure_font = requires_tk(8, 7)(StandardOptionsTests.test_configure_font) + test_configure_foreground = requires_tk(8, 7)(StandardOptionsTests.test_configure_foreground) + test_configure_justify = requires_tk(8, 7)(StandardTtkOptionsTests.test_configure_justify) + + def test_configure_length(self): + widget = self.create() + self.checkPixelsParam(widget, 'length', 100.1, 56.7, '2i') + + def test_configure_maximum(self): + widget = self.create() + self.checkFloatParam(widget, 'maximum', 150.2, 77.7, 0, -10, conv=False) + + def test_configure_mode(self): + widget = self.create() + self.checkEnumParam(widget, 'mode', 'determinate', 'indeterminate') + + def test_configure_phase(self): + # XXX + pass + + test_configure_text = requires_tk(8, 7)(StandardOptionsTests.test_configure_text) + + def test_configure_value(self): + widget = self.create() + self.checkFloatParam(widget, 'value', 150.2, 77.7, 0, -10, + conv=False) + + test_configure_wraplength = requires_tk(8, 7)(StandardOptionsTests.test_configure_wraplength) + + def test_step(self): + widget = self.create(maximum=100, mode='determinate') + self.assertEqual(float(widget['value']), 0.0) + widget.step() # The default increment is 1.0. + self.assertEqual(float(widget['value']), 1.0) + widget.step(5) + self.assertEqual(float(widget['value']), 6.0) + widget.step(-2) + self.assertEqual(float(widget['value']), 4.0) + + def test_start_stop(self): + widget = self.create(maximum=100, mode='determinate') + widget.pack() + widget.start() # Schedule autoincrement; no exception. + widget.update() + widget.stop() # Cancel it. + # After stopping, the value no longer changes. + value = float(widget['value']) + widget.update() + self.assertEqual(float(widget['value']), value) + + +@unittest.skipIf(sys.platform == 'darwin', + 'ttk.Scrollbar is special on MacOSX') +@add_configure_tests(StandardTtkOptionsTests) +class ScrollbarTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'command', 'cursor', 'orient', 'style', 'takefocus', + ) + _rounds_pixels = False + _clipped = {} + default_orient = 'vertical' + + def create(self, **kwargs): + return ttk.Scrollbar(self.root, **kwargs) + + +@add_configure_tests(StandardTtkOptionsTests) +class NotebookTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'cursor', 'height', 'padding', 'style', 'takefocus', 'width', + ) + _rounds_pixels = (tk_version < (9,0)) + _converts_pixels = False + _clipped = {} + + def setUp(self): + super().setUp() + self.nb = self.create(padding=0) + self.child1 = ttk.Label(self.root) + self.child2 = ttk.Label(self.root) + self.nb.add(self.child1, text='a') + self.nb.add(self.child2, text='b') + + def create(self, **kwargs): + return ttk.Notebook(self.root, **kwargs) + + def test_configure_height(self): + widget = self.create() + if get_tk_patchlevel(self.root) < (8, 6, 15): + self.checkIntegerParam(widget, 'height', 402, -402, 0) + else: + self.checkPixelsParam(widget, 'height', '10c', 402, -402, 0) + + def test_configure_width(self): + widget = self.create() + if get_tk_patchlevel(self.root) < (8, 6, 15): + self.checkIntegerParam(widget, 'width', 402, -402, 0) + else: + self.checkPixelsParam(widget, 'width', '10c', 402, -402, 0) + + def test_tab_identifiers(self): + self.nb.forget(0) + self.nb.hide(self.child2) + self.assertRaises(tkinter.TclError, self.nb.tab, self.child1) + self.assertEqual(self.nb.index('end'), 1) + self.nb.add(self.child2) + self.assertEqual(self.nb.index('end'), 1) + self.nb.select(self.child2) + + self.assertTrue(self.nb.tab('current')) + self.nb.add(self.child1, text='a') + + self.nb.pack() + self.nb.update() + # Address a tab by a point taken from Tk's own geometry rather than a + # fixed pixel, which can land on a different tab or miss the tabs + # entirely (e.g. on Aqua the tabs are inset) as the display scaling + # changes. + x, y = self._tab_point(self.nb.index('current')) + self.assertEqual(self.nb.tab(f'@{x},{y}'), self.nb.tab('current')) + + x, y = self._tab_point(self.nb.index(self.child1)) + self.assertEqual(self.nb.tab(f'@{x},{y}', text=None), 'a') + + def test_add_and_hidden(self): + self.assertRaises(tkinter.TclError, self.nb.hide, -1) + self.assertRaises(tkinter.TclError, self.nb.hide, 'hi') + self.assertRaises(tkinter.TclError, self.nb.hide, None) + self.assertRaises(tkinter.TclError, self.nb.add, None) + self.assertRaises(tkinter.TclError, self.nb.add, ttk.Label(self.root), + unknown='option') + + tabs = self.nb.tabs() + self.nb.hide(self.child1) + self.nb.add(self.child1) + self.assertEqual(self.nb.tabs(), tabs) + + child = ttk.Label(self.root) + self.nb.add(child, text='c') + tabs = self.nb.tabs() + + curr = self.nb.index('current') + # verify that the tab gets re-added at its previous position + child2_index = self.nb.index(self.child2) + self.nb.hide(self.child2) + self.nb.add(self.child2) + self.assertEqual(self.nb.tabs(), tabs) + self.assertEqual(self.nb.index(self.child2), child2_index) + self.assertEqual(str(self.child2), self.nb.tabs()[child2_index]) + # but the tab next to it (not hidden) is the one selected now + self.assertEqual(self.nb.index('current'), curr + 1) + + def test_forget(self): + self.assertRaises(tkinter.TclError, self.nb.forget, -1) + self.assertRaises(tkinter.TclError, self.nb.forget, 'hi') + self.assertRaises(tkinter.TclError, self.nb.forget, None) + + tabs = self.nb.tabs() + child1_index = self.nb.index(self.child1) + self.nb.forget(self.child1) + self.assertNotIn(str(self.child1), self.nb.tabs()) + self.assertEqual(len(tabs) - 1, len(self.nb.tabs())) + + self.nb.add(self.child1) + self.assertEqual(self.nb.index(self.child1), 1) + self.assertNotEqual(child1_index, self.nb.index(self.child1)) + + def test_index(self): + self.assertRaises(tkinter.TclError, self.nb.index, -1) + self.assertRaises(tkinter.TclError, self.nb.index, None) + + self.assertIsInstance(self.nb.index('end'), int) + self.assertEqual(self.nb.index(self.child1), 0) + self.assertEqual(self.nb.index(self.child2), 1) + self.assertEqual(self.nb.index('end'), 2) + + def test_insert(self): + # moving tabs + tabs = self.nb.tabs() + self.nb.insert(1, tabs[0]) + self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) + self.nb.insert(self.child1, self.child2) + self.assertEqual(self.nb.tabs(), tabs) + self.nb.insert('end', self.child1) + self.assertEqual(self.nb.tabs(), (tabs[1], tabs[0])) + self.nb.insert('end', 0) + self.assertEqual(self.nb.tabs(), tabs) + # bad moves + self.assertRaises(tkinter.TclError, self.nb.insert, 2, tabs[0]) + self.assertRaises(tkinter.TclError, self.nb.insert, -1, tabs[0]) + + # new tab + child3 = ttk.Label(self.root) + self.nb.insert(1, child3) + self.assertEqual(self.nb.tabs(), (tabs[0], str(child3), tabs[1])) + self.nb.forget(child3) + self.assertEqual(self.nb.tabs(), tabs) + self.nb.insert(self.child1, child3) + self.assertEqual(self.nb.tabs(), (str(child3), ) + tabs) + self.nb.forget(child3) + if tk_version >= (8, 7): + self.nb.insert(2, child3) + self.assertEqual(self.nb.tabs(), (*tabs, str(child3))) + else: + self.assertRaises(tkinter.TclError, self.nb.insert, 2, child3) + self.assertRaises(tkinter.TclError, self.nb.insert, -1, child3) + + # bad inserts + self.assertRaises(tkinter.TclError, self.nb.insert, 'end', None) + self.assertRaises(tkinter.TclError, self.nb.insert, None, 0) + self.assertRaises(tkinter.TclError, self.nb.insert, None, None) + + def test_select(self): + self.nb.pack() + self.nb.update() + + success = [] + tab_changed = [] + + self.child1.bind('', lambda evt: success.append(True)) + self.nb.bind('<>', + lambda evt: tab_changed.append(True)) + + self.assertEqual(self.nb.select(), str(self.child1)) + self.nb.select(self.child2) + self.assertTrue(success) + self.assertEqual(self.nb.select(), str(self.child2)) + + self.nb.update() + self.assertTrue(tab_changed) + + def test_tab(self): + self.assertRaises(tkinter.TclError, self.nb.tab, -1) + self.assertRaises(tkinter.TclError, self.nb.tab, 'notab') + self.assertRaises(tkinter.TclError, self.nb.tab, None) + + self.assertIsInstance(self.nb.tab(self.child1), dict) + self.assertEqual(self.nb.tab(self.child1, text=None), 'a') + # newer form for querying a single option + self.assertEqual(self.nb.tab(self.child1, 'text'), 'a') + self.nb.tab(self.child1, text='abc') + self.assertEqual(self.nb.tab(self.child1, text=None), 'abc') + self.assertEqual(self.nb.tab(self.child1, 'text'), 'abc') + + def test_configure_tabs(self): + self.assertEqual(len(self.nb.tabs()), 2) + + self.nb.forget(self.child1) + self.nb.forget(self.child2) + + self.assertEqual(self.nb.tabs(), ()) + + def _tab_point(self, index): + # Return a window coordinate that really lies on tab *index*, taken + # from Tk's own geometry (ttk::notebook index @x,y), so that it is + # correct regardless of the theme, platform and display scaling. A + # fixed pixel such as (5, 5) can land on a different tab element + # depending on the DPI, or miss the tabs entirely (e.g. on Aqua the + # tabs are inset), which would make a click there test nothing. + self.assertTrue(wait_until_mapped(self.nb, full_size=True)) + w, h = self.nb.winfo_width(), self.nb.winfo_height() + # The selected pane fills the widget except for the tab strip, so skip + # that large tab-free region instead of querying every pixel in it. + pane = self.nb.nametowidget(self.nb.select()) + px, py = pane.winfo_x(), pane.winfo_y() + pw, ph = pane.winfo_width(), pane.winfo_height() + for y in range(h): + inside_y = py <= y < py + ph + for x in range(w): + if inside_y and px <= x < px + pw: + continue + try: + if self.nb.index(f'@{x},{y}') == index: + return x, y + except TclError: + continue + self.fail(f'no point found on tab {index}') + + def test_traversal(self): + self.nb.pack() + self.nb.update() + + # A mouse click selects the tab it lands on. + self.nb.select(1) + self.assertEqual(self.nb.select(), str(self.child2)) + simulate_mouse_click(self.nb, *self._tab_point(0)) + self.assertEqual(self.nb.select(), str(self.child1)) + + # Control-Tab and Shift-Control-Tab traverse the tabs. + self.nb.focus_force() + self.nb.event_generate('') + self.assertEqual(self.nb.select(), str(self.child2)) + self.nb.focus_force() + self.nb.event_generate('') + self.assertEqual(self.nb.select(), str(self.child1)) + self.nb.focus_force() + self.nb.event_generate('') + self.assertEqual(self.nb.select(), str(self.child2)) + + self.nb.tab(self.child1, text='a', underline=0) + self.nb.tab(self.child2, text='e', underline=0) + self.nb.enable_traversal() + self.nb.focus_force() + + # A click still selects the tab it lands on after enable_traversal(). + self.nb.select(1) + self.assertEqual(self.nb.select(), str(self.child2)) + simulate_mouse_click(self.nb, *self._tab_point(0)) + self.assertEqual(self.nb.select(), str(self.child1)) + + # Mnemonics traverse the tabs (macOS uses region-dependent + # Emacs-style shortcuts, so use the regular arrow keys there). + if sys.platform == 'darwin': + begin = '' + end = '' + else: + begin = '' + end = '' + self.nb.event_generate(end) + self.assertEqual(self.nb.select(), str(self.child2)) + self.nb.event_generate(begin) + self.assertEqual(self.nb.select(), str(self.child1)) + + +@add_configure_tests(IntegerSizeTests, StandardTtkOptionsTests) +class SpinboxTest(EntryTest, unittest.TestCase): + OPTIONS = ( + 'background', 'class', 'command', 'cursor', 'exportselection', + 'font', 'foreground', 'format', 'from', 'increment', + 'invalidcommand', 'justify', + 'placeholder', 'placeholderforeground', + 'show', 'state', 'style', + 'takefocus', 'textvariable', 'to', 'validate', 'validatecommand', + 'values', 'width', 'wrap', 'xscrollcommand', + ) + IDENTIFY_AS = {'Spinbox.field', 'textarea'} + + def setUp(self): + super().setUp() + self.spin = self.create() + self.spin.pack() + + def create(self, **kwargs): + return ttk.Spinbox(self.root, **kwargs) + + def _click_increment_arrow(self): + self.require_mapped(self.spin) + y = self.spin.winfo_height()//2 - 5 + x = self._arrow_x(self.spin, y, 'uparrow') + self.spin.event_generate('', x=x, y=y) + self.spin.event_generate('', x=x, y=y) + self.spin.update_idletasks() + + def _click_decrement_arrow(self): + self.require_mapped(self.spin) + y = self.spin.winfo_height()//2 + 4 + x = self._arrow_x(self.spin, y, 'downarrow') + self.spin.event_generate('', x=x, y=y) + self.spin.event_generate('', x=x, y=y) + self.spin.update_idletasks() + + def test_configure_command(self): + success = [] + + self.spin['command'] = lambda: success.append(True) + self.spin.update() + self._click_increment_arrow() + self.spin.update() + self.assertTrue(success) + + self._click_decrement_arrow() + self.assertEqual(len(success), 2) + + # testing postcommand removal + self.spin['command'] = '' + self.spin.update_idletasks() + self._click_increment_arrow() + self._click_decrement_arrow() + self.spin.update() + self.assertEqual(len(success), 2) + + def test_increment_decrement_events(self): + # Clicking the arrows fires the <> and <> + # virtual events. + events = [] + self.spin.bind('<>', lambda e: events.append('increment')) + self.spin.bind('<>', lambda e: events.append('decrement')) + self.spin.update() + self._click_increment_arrow() + self.spin.update() + self._click_decrement_arrow() + self.spin.update() + self.assertEqual(events, ['increment', 'decrement']) + + def test_configure_to(self): + self.spin['from'] = 0 + self.spin['to'] = 5 + self.spin.set(4) + self.spin.update() + self._click_increment_arrow() # 5 + + self.assertEqual(self.spin.get(), '5') + + self._click_increment_arrow() # 5 + self.assertEqual(self.spin.get(), '5') + + def test_configure_from(self): + self.spin['from'] = 1 + self.spin['to'] = 10 + self.spin.set(2) + self.spin.update() + self._click_decrement_arrow() # 1 + self.assertEqual(self.spin.get(), '1') + self._click_decrement_arrow() # 1 + self.assertEqual(self.spin.get(), '1') + + def test_configure_increment(self): + self.spin['from'] = 0 + self.spin['to'] = 10 + self.spin['increment'] = 4 + self.spin.set(1) + self.spin.update() + + self._click_increment_arrow() # 5 + self.assertEqual(self.spin.get(), '5') + self.spin['increment'] = 2 + self.spin.update() + self._click_decrement_arrow() # 3 + self.assertEqual(self.spin.get(), '3') + + def test_configure_format(self): + self.spin.set(1) + self.spin['format'] = '%10.3f' + self.spin.update() + self._click_increment_arrow() + value = self.spin.get() + + self.assertEqual(len(value), 10) + self.assertEqual(value.index('.'), 6) + + self.spin['format'] = '' + self.spin.update() + self._click_increment_arrow() + value = self.spin.get() + self.assertTrue('.' not in value) + self.assertEqual(len(value), 1) + + def test_configure_wrap(self): + self.spin['to'] = 10 + self.spin['from'] = 1 + self.spin.set(1) + self.spin['wrap'] = True + self.spin.update() + + self._click_decrement_arrow() + self.assertEqual(self.spin.get(), '10') + + self._click_increment_arrow() + self.assertEqual(self.spin.get(), '1') + + self.spin['wrap'] = False + self.spin.update() + + self._click_decrement_arrow() + self.assertEqual(self.spin.get(), '1') + + def test_configure_values(self): + self.assertEqual(self.spin['values'], '') + self.checkParam(self.spin, 'values', 'mon tue wed thur', + expected=('mon', 'tue', 'wed', 'thur')) + self.checkParam(self.spin, 'values', ('mon', 'tue', 'wed', 'thur')) + self.checkParam(self.spin, 'values', (42, 3.14, '', 'any string')) + self.checkParam(self.spin, 'values', '') + + self.spin['values'] = ['a', 1, 'c'] + + # test incrementing / decrementing values + self.spin.set('a') + self.spin.update() + self._click_increment_arrow() + self.assertEqual(self.spin.get(), '1') + + self._click_decrement_arrow() + self.assertEqual(self.spin.get(), 'a') + + # testing values with empty string set through configure + self.spin.configure(values=[1, '', 2]) + self.assertEqual(self.spin['values'], + ('1', '', '2') if self.wantobjects else + '1 {} 2') + + # testing values with spaces + self.spin['values'] = ['a b', 'a\tb', 'a\nb'] + self.assertEqual(self.spin['values'], + ('a b', 'a\tb', 'a\nb') if self.wantobjects else + '{a b} {a\tb} {a\nb}') + + # testing values with special characters + self.spin['values'] = [r'a\tb', '"a"', '} {'] + self.assertEqual(self.spin['values'], + (r'a\tb', '"a"', '} {') if self.wantobjects else + r'a\\tb {"a"} \}\ \{') + + # testing creating spinbox with empty string in values + spin2 = ttk.Spinbox(self.root, values=[1, 2, '']) + self.assertEqual(spin2['values'], + ('1', '2', '') if self.wantobjects else '1 2 {}') + spin2.destroy() + + +@add_configure_tests(StandardTtkOptionsTests) +class TreeviewTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'columns', 'cursor', 'displaycolumns', + 'height', 'padding', 'selectmode', 'selecttype', 'show', 'striped', + 'style', 'takefocus', 'titlecolumns', 'titleitems', + 'xscrollcommand', 'yscrollcommand', + ) + _rounds_pixels = False + _clipped = {} + + def setUp(self): + super().setUp() + self.tv = self.create(padding=0) + + def create(self, **kwargs): + return ttk.Treeview(self.root, **kwargs) + + def test_configure_columns(self): + widget = self.create() + self.checkParam(widget, 'columns', 'a b c', + expected=('a', 'b', 'c')) + self.checkParam(widget, 'columns', ('a', 'b', 'c')) + self.checkParam(widget, 'columns', '', + expected=() if tk_version >= (8, 7) else '') + + def test_configure_displaycolumns(self): + widget = self.create() + widget['columns'] = ('a', 'b', 'c') + self.checkParam(widget, 'displaycolumns', 'b a c', + expected=('b', 'a', 'c')) + self.checkParam(widget, 'displaycolumns', ('b', 'a', 'c')) + self.checkParam(widget, 'displaycolumns', '#all', + expected=('#all',)) + self.checkParam(widget, 'displaycolumns', (2, 1, 0)) + self.checkInvalidParam(widget, 'displaycolumns', ('a', 'b', 'd'), + errmsg='Invalid column index "?d"?') + errmsg = 'Column index "?{}"? out of bounds' + self.checkInvalidParam(widget, 'displaycolumns', (1, 2, 3), + errmsg=errmsg.format(3)) + self.checkInvalidParam(widget, 'displaycolumns', (1, -2), + errmsg=errmsg.format(-2)) + + def test_configure_height(self): + widget = self.create() + self.checkPixelsParam(widget, 'height', 100, -100, 0, '3c', + conv=False) + self.checkPixelsParam(widget, 'height', 101.2, 102.6, '3c', + conv=False) + + def test_configure_selectmode(self): + widget = self.create() + if tk_version >= (9, 1): + self.checkEnumParam(widget, 'selectmode', + 'none', 'single', 'browse', 'extended', + 'multiple') + else: + self.checkEnumParam(widget, 'selectmode', + 'none', 'browse', 'extended') + + @requires_tk(8, 7) + def test_configure_selecttype(self): + widget = self.create() + self.checkEnumParam(widget, 'selecttype', 'item', 'cell') + + def test_configure_show(self): + widget = self.create() + self.checkParam(widget, 'show', 'tree headings', + expected=('tree', 'headings')) + self.checkParam(widget, 'show', ('tree', 'headings')) + self.checkParam(widget, 'show', ('headings', 'tree')) + self.checkParam(widget, 'show', 'tree', expected=('tree',)) + self.checkParam(widget, 'show', 'headings', expected=('headings',)) + + @requires_tk(8, 7) + def test_configure_striped(self): + widget = self.create() + self.checkBooleanParam(widget, 'striped') + + @requires_tk(8, 7) + def test_configure_titlecolumns(self): + widget = self.create() + self.checkIntegerParam(widget, 'titlecolumns', 0, 1, 5) + self.checkInvalidParam(widget, 'titlecolumns', -2) + + @requires_tk(8, 7) + def test_configure_titleitems(self): + widget = self.create() + self.checkIntegerParam(widget, 'titleitems', 0, 1, 5) + self.checkInvalidParam(widget, 'titleitems', -2) + + def test_bbox(self): + self.tv.pack() + self.assertEqual(self.tv.bbox(''), '') + self.tv.update() + + item_id = self.tv.insert('', 'end') + children = self.tv.get_children() + self.assertTrue(children) + + bbox = self.tv.bbox(children[0]) + self.assertIsBoundingBox(bbox) + + # compare width in bboxes + self.tv['columns'] = ['test'] + self.tv.column('test', width=50) + bbox_column0 = self.tv.bbox(children[0], 0) + root_width = self.tv.column('#0', width=None) + if not self.wantobjects: + root_width = int(root_width) + self.assertEqual(bbox_column0[0], bbox[0] + root_width) + + # verify that bbox of a closed item is the empty string + child1 = self.tv.insert(item_id, 'end') + self.assertEqual(self.tv.bbox(child1), '') + + def test_children(self): + # no children yet, should get an empty tuple + self.assertEqual(self.tv.get_children(), ()) + + item_id = self.tv.insert('', 'end') + self.assertIsInstance(self.tv.get_children(), tuple) + self.assertEqual(self.tv.get_children()[0], item_id) + + # add item_id and child3 as children of child2 + child2 = self.tv.insert('', 'end') + child3 = self.tv.insert('', 'end') + self.tv.set_children(child2, item_id, child3) + self.assertEqual(self.tv.get_children(child2), (item_id, child3)) + + # child3 has child2 as parent, thus trying to set child2 as a children + # of child3 should result in an error + self.assertRaises(tkinter.TclError, + self.tv.set_children, child3, child2) + + # remove child2 children + self.tv.set_children(child2) + self.assertEqual(self.tv.get_children(child2), ()) + + # remove root's children + self.tv.set_children('') + self.assertEqual(self.tv.get_children(), ()) + + def test_column(self): + # return a dict with all options/values + self.assertIsInstance(self.tv.column('#0'), dict) + # return a single value of the given option + if self.wantobjects: + self.assertIsInstance(self.tv.column('#0', width=None), int) + # set a new value for an option + self.tv.column('#0', width=10) + # testing new way to get option value + self.assertEqual(self.tv.column('#0', 'width'), + 10 if self.wantobjects else '10') + self.assertEqual(self.tv.column('#0', width=None), + 10 if self.wantobjects else '10') + # check read-only option + self.assertRaises(tkinter.TclError, self.tv.column, '#0', id='X') + + self.assertRaises(tkinter.TclError, self.tv.column, 'invalid') + invalid_kws = [ + {'unknown_option': 'some value'}, {'stretch': 'wrong'}, + {'anchor': 'wrong'}, {'width': 'wrong'}, {'minwidth': 'wrong'} + ] + for kw in invalid_kws: + self.assertRaises(tkinter.TclError, self.tv.column, '#0', + **kw) + + def test_delete(self): + self.assertRaises(tkinter.TclError, self.tv.delete, '#0') + + item_id = self.tv.insert('', 'end') + item2 = self.tv.insert(item_id, 'end') + self.assertEqual(self.tv.get_children(), (item_id, )) + self.assertEqual(self.tv.get_children(item_id), (item2, )) + + self.tv.delete(item_id) + self.assertFalse(self.tv.get_children()) + + # reattach should fail + self.assertRaises(tkinter.TclError, + self.tv.reattach, item_id, '', 'end') + + # test multiple item delete + item1 = self.tv.insert('', 'end') + item2 = self.tv.insert('', 'end') + self.assertEqual(self.tv.get_children(), (item1, item2)) + + self.tv.delete(item1, item2) + self.assertFalse(self.tv.get_children()) + + def test_detach_reattach(self): + item_id = self.tv.insert('', 'end') + item2 = self.tv.insert(item_id, 'end') + + # calling detach without items is valid, although it does nothing + prev = self.tv.get_children() + self.tv.detach() # this should do nothing + self.assertEqual(prev, self.tv.get_children()) + + self.assertEqual(self.tv.get_children(), (item_id, )) + self.assertEqual(self.tv.get_children(item_id), (item2, )) + + # detach item with children + self.tv.detach(item_id) + self.assertFalse(self.tv.get_children()) + + # reattach item with children + self.tv.reattach(item_id, '', 'end') + self.assertEqual(self.tv.get_children(), (item_id, )) + self.assertEqual(self.tv.get_children(item_id), (item2, )) + + # move a children to the root + self.tv.move(item2, '', 'end') + self.assertEqual(self.tv.get_children(), (item_id, item2)) + self.assertEqual(self.tv.get_children(item_id), ()) + + # bad values + self.assertRaises(tkinter.TclError, + self.tv.reattach, 'nonexistent', '', 'end') + self.assertRaises(tkinter.TclError, + self.tv.detach, 'nonexistent') + self.assertRaises(tkinter.TclError, + self.tv.reattach, item2, 'otherparent', 'end') + self.assertRaises(tkinter.TclError, + self.tv.reattach, item2, '', 'invalid') + + # multiple detach + self.tv.detach(item_id, item2) + self.assertEqual(self.tv.get_children(), ()) + self.assertEqual(self.tv.get_children(item_id), ()) + + def test_exists(self): + self.assertIs(self.tv.exists('something'), False) + self.assertIs(self.tv.exists(''), True) + self.assertIs(self.tv.exists({}), False) + + # the following will make a tk.call equivalent to + # tk.call(treeview, "exists") which should result in an error + # in the tcl interpreter since tk requires an item. + self.assertRaises(tkinter.TclError, self.tv.exists, None) + + def test_parent(self): + a = self.tv.insert('', 'end') + b = self.tv.insert(a, 'end') + self.assertEqual(self.tv.parent(b), a) + self.assertEqual(self.tv.parent(a), '') + self.assertRaises(tkinter.TclError, self.tv.parent, 'nonexistent') + + def test_next_prev(self): + a = self.tv.insert('', 'end') + b = self.tv.insert('', 'end') + c = self.tv.insert('', 'end') + self.assertEqual(self.tv.next(a), b) + self.assertEqual(self.tv.next(b), c) + self.assertEqual(self.tv.next(c), '') + self.assertEqual(self.tv.prev(c), b) + self.assertEqual(self.tv.prev(b), a) + self.assertEqual(self.tv.prev(a), '') + self.assertRaises(tkinter.TclError, self.tv.next, 'nonexistent') + self.assertRaises(tkinter.TclError, self.tv.prev, 'nonexistent') + + def test_see(self): + a = self.tv.insert('', 'end') + b = self.tv.insert(a, 'end') + # see() opens all of the item's ancestors. + self.assertFalse(self.tv.tk.getboolean(self.tv.item(a, 'open'))) + self.tv.see(b) + self.assertTrue(self.tv.tk.getboolean(self.tv.item(a, 'open'))) + self.assertRaises(tkinter.TclError, self.tv.see, 'nonexistent') + + def test_identify_element(self): + self.tv.pack() + self.tv.wait_visibility() + parent = self.tv.insert('', 'end', text='parent') + self.tv.insert(parent, 'end', text='child') + self.tv.update() + x, y, w, h = self.tv.bbox(parent) + # The Treeitem.indicator element is packed at the left of the row in + # the Item layout on every platform and theme. + element = self.tv.identify_element(x + 8, y + h // 2) + self.assertRegex(element, r'.*indicator\z') + # The empty string is returned outside the widget. + self.assertEqual(self.tv.identify_element(-1, -1), '') + self.assertRaises(tkinter.TclError, self.tv.identify_element, None, 5) + + def test_focus(self): + # nothing is focused right now + self.assertEqual(self.tv.focus(), '') + + item1 = self.tv.insert('', 'end') + self.tv.focus(item1) + self.assertEqual(self.tv.focus(), item1) + + self.tv.delete(item1) + self.assertEqual(self.tv.focus(), '') + + # try focusing inexistent item + self.assertRaises(tkinter.TclError, self.tv.focus, 'hi') + + def test_heading(self): + # check a dict is returned + self.assertIsInstance(self.tv.heading('#0'), dict) + + # check a value is returned + self.tv.heading('#0', text='hi') + self.assertEqual(self.tv.heading('#0', 'text'), 'hi') + self.assertEqual(self.tv.heading('#0', text=None), 'hi') + + # invalid option + self.assertRaises(tkinter.TclError, self.tv.heading, '#0', + background=None) + # invalid value + self.assertRaises(tkinter.TclError, self.tv.heading, '#0', + anchor=1) + + def test_heading_callback(self): + def simulate_heading_click(x, y): + if tk_version >= (8, 6): + self.assertEqual(self.tv.identify_column(x), '#0') + self.assertEqual(self.tv.identify_region(x, y), 'heading') + simulate_mouse_click(self.tv, x, y) + self.tv.update() + + success = [] # no success for now + + self.tv.pack() + self.tv.heading('#0', command=lambda: success.append(True)) + self.tv.column('#0', width=100) + self.tv.update() + + # assuming that the coords (5, 5) fall into heading #0 + simulate_heading_click(5, 5) + if not success: + self.fail("The command associated to the treeview heading wasn't " + "invoked.") + + success = [] + commands = self.tv.master._tclCommands + self.tv.heading('#0', command=str(self.tv.heading('#0', command=None))) + self.assertEqual(commands, self.tv.master._tclCommands) + # Click elsewhere first, so the second heading click is not reported + # as a double click (which does not invoke the command). + simulate_mouse_click(self.tv, 5, 50) + simulate_heading_click(5, 5) + if not success: + self.fail("The command associated to the treeview heading wasn't " + "invoked.") + + # XXX The following raises an error in a tcl interpreter, but not in + # Python + #self.tv.heading('#0', command='I dont exist') + #simulate_heading_click(5, 5) + + def test_index(self): + # item 'what' doesn't exist + self.assertRaises(tkinter.TclError, self.tv.index, 'what') + + self.assertEqual(self.tv.index(''), 0) + + item1 = self.tv.insert('', 'end') + item2 = self.tv.insert('', 'end') + c1 = self.tv.insert(item1, 'end') + c2 = self.tv.insert(item1, 'end') + self.assertEqual(self.tv.index(item1), 0) + self.assertEqual(self.tv.index(c1), 0) + self.assertEqual(self.tv.index(c2), 1) + self.assertEqual(self.tv.index(item2), 1) + + self.tv.move(item2, '', 0) + self.assertEqual(self.tv.index(item2), 0) + self.assertEqual(self.tv.index(item1), 1) + + # check that index still works even after its parent and siblings + # have been detached + self.tv.detach(item1) + self.assertEqual(self.tv.index(c2), 1) + self.tv.detach(c1) + self.assertEqual(self.tv.index(c2), 0) + + # but it fails after item has been deleted + self.tv.delete(item1) + self.assertRaises(tkinter.TclError, self.tv.index, c2) + + def test_insert_item(self): + # parent 'none' doesn't exist + self.assertRaises(tkinter.TclError, self.tv.insert, 'none', 'end') + + # open values + self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', + open='') + self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', + open='please') + self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=True))) + self.assertFalse(self.tv.delete(self.tv.insert('', 'end', open=False))) + + # invalid index + self.assertRaises(tkinter.TclError, self.tv.insert, '', 'middle') + + # trying to duplicate item id is invalid + itemid = self.tv.insert('', 'end', 'first-item') + self.assertEqual(itemid, 'first-item') + self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', + 'first-item') + self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', + MockTclObj('first-item')) + + # unicode values + value = '\xe1ba' + item = self.tv.insert('', 'end', values=(value, )) + self.assertEqual(self.tv.item(item, 'values'), + (value,) if self.wantobjects else value) + self.assertEqual(self.tv.item(item, values=None), + (value,) if self.wantobjects else value) + + self.tv.item(item, values=self.root.splitlist(self.tv.item(item, values=None))) + self.assertEqual(self.tv.item(item, values=None), + (value,) if self.wantobjects else value) + + self.assertIsInstance(self.tv.item(item), dict) + + # erase item values + self.tv.item(item, values='') + self.assertFalse(self.tv.item(item, values=None)) + + # item tags + item = self.tv.insert('', 'end', tags=[1, 2, value]) + self.assertEqual(self.tv.item(item, tags=None), + ('1', '2', value) if self.wantobjects else + '1 2 %s' % value) + self.tv.item(item, tags=[]) + self.assertFalse(self.tv.item(item, tags=None)) + self.tv.item(item, tags=(1, 2)) + self.assertEqual(self.tv.item(item, tags=None), + ('1', '2') if self.wantobjects else '1 2') + + # values with spaces + item = self.tv.insert('', 'end', values=('a b c', + '%s %s' % (value, value))) + self.assertEqual(self.tv.item(item, values=None), + ('a b c', '%s %s' % (value, value)) if self.wantobjects else + '{a b c} {%s %s}' % (value, value)) + + # text + self.assertEqual(self.tv.item( + self.tv.insert('', 'end', text="Label here"), text=None), + "Label here") + self.assertEqual(self.tv.item( + self.tv.insert('', 'end', text=value), text=None), + value) + + # test for values which are not None + keep_type = self.wantobjects and tk_version >= (9, 1) + itemid = self.tv.insert('', 'end', 0) + self.assertEqual(itemid, 0 if keep_type else '0') + itemid = self.tv.insert('', 'end', 0.0) + self.assertEqual(itemid, 0.0 if keep_type else '0.0') + # this is because False resolves to 0 and element with 0 iid is already present + self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', False) + self.assertRaises(tkinter.TclError, self.tv.insert, '', 'end', '') + + def test_selection(self): + self.assertRaises(TypeError, self.tv.selection, 'spam') + # item 'none' doesn't exist + self.assertRaises(tkinter.TclError, self.tv.selection_set, 'none') + self.assertRaises(tkinter.TclError, self.tv.selection_add, 'none') + self.assertRaises(tkinter.TclError, self.tv.selection_remove, 'none') + self.assertRaises(tkinter.TclError, self.tv.selection_toggle, 'none') + + item1 = self.tv.insert('', 'end') + item2 = self.tv.insert('', 'end') + c1 = self.tv.insert(item1, 'end') + c2 = self.tv.insert(item1, 'end') + c3 = self.tv.insert(item1, 'end') + self.assertEqual(self.tv.selection(), ()) + + self.tv.selection_set(c1, item2) + self.assertEqual(self.tv.selection(), (c1, item2)) + self.tv.selection_set(c2) + self.assertEqual(self.tv.selection(), (c2,)) + + self.tv.selection_add(c1, item2) + self.assertEqual(self.tv.selection(), (c1, c2, item2)) + self.tv.selection_add(item1) + self.assertEqual(self.tv.selection(), (item1, c1, c2, item2)) + self.tv.selection_add() + self.assertEqual(self.tv.selection(), (item1, c1, c2, item2)) + + self.tv.selection_remove(item1, c3) + self.assertEqual(self.tv.selection(), (c1, c2, item2)) + self.tv.selection_remove(c2) + self.assertEqual(self.tv.selection(), (c1, item2)) + self.tv.selection_remove() + self.assertEqual(self.tv.selection(), (c1, item2)) + + self.tv.selection_toggle(c1, c3) + self.assertEqual(self.tv.selection(), (c3, item2)) + self.tv.selection_toggle(item2) + self.assertEqual(self.tv.selection(), (c3,)) + self.tv.selection_toggle() + self.assertEqual(self.tv.selection(), (c3,)) + + self.tv.insert('', 'end', id='with spaces') + self.tv.selection_set('with spaces') + self.assertEqual(self.tv.selection(), ('with spaces',)) + + self.tv.insert('', 'end', id='{brace') + self.tv.selection_set('{brace') + self.assertEqual(self.tv.selection(), ('{brace',)) + + self.tv.insert('', 'end', id='unicode\u20ac') + self.tv.selection_set('unicode\u20ac') + self.assertEqual(self.tv.selection(), ('unicode\u20ac',)) + + self.tv.insert('', 'end', id=b'bytes\xe2\x82\xac') + self.tv.selection_set(b'bytes\xe2\x82\xac') + self.assertEqual(self.tv.selection(), + (b'bytes\xe2\x82\xac',) + if self.wantobjects and tk_version >= (9, 1) + else ('bytes\xe2\x82\xac',)) + + self.tv.selection_set() + self.assertEqual(self.tv.selection(), ()) + + # Old interface + self.tv.selection_set((c1, item2)) + self.assertEqual(self.tv.selection(), (c1, item2)) + self.tv.selection_add((c1, item1)) + self.assertEqual(self.tv.selection(), (item1, c1, item2)) + self.tv.selection_remove((item1, c3)) + self.assertEqual(self.tv.selection(), (c1, item2)) + self.tv.selection_toggle((c1, c3)) + self.assertEqual(self.tv.selection(), (c3, item2)) + + def test_virtual_events(self): + # Keyboard navigation fires the <>, <> + # and <> virtual events. + parent = self.tv.insert('', 'end') + self.tv.insert(parent, 'end') + item2 = self.tv.insert('', 'end') + self.tv.pack() + self.require_mapped(self.tv) + selects, opens, closes = [], [], [] + self.tv.bind('<>', + lambda e: selects.append(self.tv.selection())) + self.tv.bind('<>', lambda e: opens.append(self.tv.focus())) + self.tv.bind('<>', lambda e: closes.append(self.tv.focus())) + self.tv.focus(parent) + self.tv.selection_set(parent) + self.tv.update() + + # Force the focus right before generating the event: the window + # manager can take it back. + self.tv.focus_force() + self.tv.event_generate('') # Open the focused parent. + self.tv.update() + self.assertEqual(opens, [parent]) + + self.tv.focus_force() + self.tv.event_generate('') # Close it again. + self.tv.update() + self.assertEqual(closes, [parent]) + + self.tv.focus_force() + self.tv.event_generate('') # Move the selection. + self.tv.update() + self.assertEqual(self.tv.selection(), (item2,)) + self.assertIn((item2,), selects) + + def test_set(self): + self.tv['columns'] = ['A', 'B'] + item = self.tv.insert('', 'end', values=['a', 'b']) + values = self.tv.set(item) + if tk_version >= (9, 1): + self.assertEqual(values.pop('#0'), '') + self.assertEqual(values, {'A': 'a', 'B': 'b'}) + + self.tv.set(item, 'B', 'a') + self.assertEqual(self.tv.item(item, values=None), + ('a', 'a') if self.wantobjects else 'a a') + + self.tv['columns'] = ['B'] + values = self.tv.set(item) + values.pop('#0', None) + self.assertEqual(values, {'B': 'a'}) + + self.tv.set(item, 'B', 'b') + self.assertEqual(self.tv.set(item, column='B'), 'b') + self.assertEqual(self.tv.item(item, values=None), + ('b', 'a') if self.wantobjects else 'b a') + + self.tv.set(item, 'B', 123) + self.assertEqual(self.tv.set(item, 'B'), + 123 if self.wantobjects else '123') + self.assertEqual(self.tv.item(item, values=None), + (123, 'a') if self.wantobjects else '123 a') + values = self.tv.set(item) + values.pop('#0', None) + self.assertEqual(values, + {'B': 123} if self.wantobjects else {'B': '123'}) + + # inexistent column + self.assertRaises(tkinter.TclError, self.tv.set, item, 'A') + self.assertRaises(tkinter.TclError, self.tv.set, item, 'A', 'b') + + # inexistent item + self.assertRaises(tkinter.TclError, self.tv.set, 'notme') + + def test_tag_bind(self): + events = [] + item1 = self.tv.insert('', 'end', tags=['call']) + item2 = self.tv.insert('', 'end', tags=['call']) + self.tv.tag_bind('call', '', + lambda evt: events.append(1)) + self.tv.tag_bind('call', '', + lambda evt: events.append(2)) + + self.tv.pack() + self.tv.update() + + # Find the y coordinate of each item. Scan the whole height of the + # widget rather than a fixed pixel range, since the row height grows + # with the display scaling. + pos_y = set() + found = set() + for y in range(self.tv.winfo_height()): + if len(found) == 2: # item1 and item2 already found + break + item_id = self.tv.identify_row(y) + if item_id and item_id not in found: + pos_y.add(y) + found.add(item_id) + + self.assertEqual(len(pos_y), 2) # item1 and item2 y pos + for y in pos_y: + simulate_mouse_click(self.tv, 0, y) + + # by now there should be 4 things in the events list, since each + # item had a bind for two events that were simulated above + self.assertEqual(len(events), 4) + for evt in zip(events[::2], events[1::2]): + self.assertEqual(evt, (1, 2)) + + def test_tag_configure(self): + # Just testing parameter passing for now + self.assertRaises(TypeError, self.tv.tag_configure) + self.assertRaises(tkinter.TclError, self.tv.tag_configure, + 'test', sky='blue') + self.tv.tag_configure('test', foreground='blue') + self.assertEqual(str(self.tv.tag_configure('test', 'foreground')), + 'blue') + self.assertEqual(str(self.tv.tag_configure('test', foreground=None)), + 'blue') + self.assertIsInstance(self.tv.tag_configure('test'), dict) + + def test_tag_has(self): + item1 = self.tv.insert('', 'end', text='Item 1', tags=['tag1']) + item2 = self.tv.insert('', 'end', text='Item 2', tags=['tag2']) + self.assertRaises(TypeError, self.tv.tag_has) + self.assertRaises(TclError, self.tv.tag_has, 'tag1', 'non-existing') + self.assertTrue(self.tv.tag_has('tag1', item1)) + self.assertFalse(self.tv.tag_has('tag1', item2)) + self.assertFalse(self.tv.tag_has('tag2', item1)) + self.assertTrue(self.tv.tag_has('tag2', item2)) + self.assertFalse(self.tv.tag_has('tag3', item1)) + self.assertFalse(self.tv.tag_has('tag3', item2)) + self.assertEqual(self.tv.tag_has('tag1'), (item1,)) + self.assertEqual(self.tv.tag_has('tag2'), (item2,)) + self.assertEqual(self.tv.tag_has('tag3'), ()) + + +@add_configure_tests(StandardTtkOptionsTests) +class SeparatorTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'cursor', 'orient', 'style', 'takefocus', + # 'state'? + ) + _rounds_pixels = False + _clipped = {} + default_orient = 'horizontal' + + def create(self, **kwargs): + return ttk.Separator(self.root, **kwargs) + + +@add_configure_tests(StandardTtkOptionsTests) +class SizegripTest(AbstractWidgetTest, unittest.TestCase): + OPTIONS = ( + 'class', 'cursor', 'style', 'takefocus', + # 'state'? + ) + _rounds_pixels = False + _clipped = {} + + def create(self, **kwargs): + return ttk.Sizegrip(self.root, **kwargs) + + +class DefaultRootTest(AbstractDefaultRootTest, unittest.TestCase): + + def test_frame(self): + self._test_widget(ttk.Frame) + + def test_label(self): + self._test_widget(ttk.Label) + + +if __name__ == "__main__": + unittest.main() diff --git a/Lib/test/test_ttk_textonly.py b/Lib/test/test_ttk_textonly.py new file mode 100644 index 00000000000..e6525c4d6c6 --- /dev/null +++ b/Lib/test/test_ttk_textonly.py @@ -0,0 +1,481 @@ +from test.support import import_helper + +# Skip this test if _tkinter does not exist. +import_helper.import_module('_tkinter') + +import unittest +from tkinter import ttk + + +class MockTkApp: + + def splitlist(self, arg): + if isinstance(arg, tuple): + return arg + return arg.split(':') + + def wantobjects(self): + return True + + +class MockTclObj(object): + typename = 'test' + + def __init__(self, val): + self.val = val + + def __str__(self): + return str(self.val) + + +class MockStateSpec(object): + typename = 'StateSpec' + + def __init__(self, *args): + self.val = args + + def __str__(self): + return ' '.join(self.val) + + +class InternalFunctionsTest(unittest.TestCase): + + def test_format_optdict(self): + def check_against(fmt_opts, result): + for i in range(0, len(fmt_opts), 2): + self.assertEqual(result.pop(fmt_opts[i]), fmt_opts[i + 1]) + if result: + self.fail("result still got elements: %s" % result) + + # passing an empty dict should return an empty object (tuple here) + self.assertFalse(ttk._format_optdict({})) + + # check list formatting + check_against( + ttk._format_optdict({'fg': 'blue', 'padding': [1, 2, 3, 4]}), + {'-fg': 'blue', '-padding': '1 2 3 4'}) + + # check tuple formatting (same as list) + check_against( + ttk._format_optdict({'test': (1, 2, '', 0)}), + {'-test': '1 2 {} 0'}) + + # check untouched values + check_against( + ttk._format_optdict({'test': {'left': 'as is'}}), + {'-test': {'left': 'as is'}}) + + # check script formatting + check_against( + ttk._format_optdict( + {'test': [1, -1, '', '2m', 0], 'test2': 3, + 'test3': '', 'test4': 'abc def', + 'test5': '"abc"', 'test6': '{}', + 'test7': '} -spam {'}, script=True), + {'-test': '{1 -1 {} 2m 0}', '-test2': '3', + '-test3': '{}', '-test4': '{abc def}', + '-test5': '{"abc"}', '-test6': r'\{\}', + '-test7': r'\}\ -spam\ \{'}) + + opts = {'αβγ': True, 'á': False} + orig_opts = opts.copy() + # check if giving unicode keys is fine + check_against(ttk._format_optdict(opts), {'-αβγ': True, '-á': False}) + # opts should remain unchanged + self.assertEqual(opts, orig_opts) + + # passing values with spaces inside a tuple/list + check_against( + ttk._format_optdict( + {'option': ('one two', 'three')}), + {'-option': '{one two} three'}) + check_against( + ttk._format_optdict( + {'option': ('one\ttwo', 'three')}), + {'-option': '{one\ttwo} three'}) + + # passing empty strings inside a tuple/list + check_against( + ttk._format_optdict( + {'option': ('', 'one')}), + {'-option': '{} one'}) + + # passing values with braces inside a tuple/list + check_against( + ttk._format_optdict( + {'option': ('one} {two', 'three')}), + {'-option': r'one\}\ \{two three'}) + + # passing quoted strings inside a tuple/list + check_against( + ttk._format_optdict( + {'option': ('"one"', 'two')}), + {'-option': '{"one"} two'}) + check_against( + ttk._format_optdict( + {'option': ('{one}', 'two')}), + {'-option': r'\{one\} two'}) + + # ignore an option + amount_opts = len(ttk._format_optdict(opts, ignore=('á'))) / 2 + self.assertEqual(amount_opts, len(opts) - 1) + + # ignore non-existing options + amount_opts = len(ttk._format_optdict(opts, ignore=('á', 'b'))) / 2 + self.assertEqual(amount_opts, len(opts) - 1) + + # ignore every option + self.assertFalse(ttk._format_optdict(opts, ignore=list(opts.keys()))) + + + def test_format_mapdict(self): + opts = {'a': [('b', 'c', 'val'), ('d', 'otherval'), ('', 'single')]} + result = ttk._format_mapdict(opts) + self.assertEqual(len(result), len(list(opts.keys())) * 2) + self.assertEqual(result, ('-a', '{b c} val d otherval {} single')) + self.assertEqual(ttk._format_mapdict(opts, script=True), + ('-a', '{{b c} val d otherval {} single}')) + + self.assertEqual(ttk._format_mapdict({2: []}), ('-2', '')) + + opts = {'üñíćódè': [('á', 'vãl')]} + result = ttk._format_mapdict(opts) + self.assertEqual(result, ('-üñíćódè', 'á vãl')) + + self.assertEqual(ttk._format_mapdict({'opt': [('value',)]}), + ('-opt', '{} value')) + + # empty states + valid = {'opt': [('', '', 'hi')]} + self.assertEqual(ttk._format_mapdict(valid), ('-opt', '{ } hi')) + + # when passing multiple states, they all must be strings + invalid = {'opt': [(1, 2, 'valid val')]} + self.assertRaises(TypeError, ttk._format_mapdict, invalid) + invalid = {'opt': [([1], '2', 'valid val')]} + self.assertRaises(TypeError, ttk._format_mapdict, invalid) + # but when passing a single state, it can be anything + valid = {'opt': [[1, 'value']]} + self.assertEqual(ttk._format_mapdict(valid), ('-opt', '1 value')) + # special attention to single states which evaluate to False + for stateval in (None, 0, False, '', set()): # just some samples + valid = {'opt': [(stateval, 'value')]} + self.assertEqual(ttk._format_mapdict(valid), + ('-opt', '{} value')) + + # values must be iterable + opts = {'a': None} + self.assertRaises(TypeError, ttk._format_mapdict, opts) + + + def test_format_elemcreate(self): + self.assertTrue(ttk._format_elemcreate(None), (None, ())) + + ## Testing type = image + # image type expects at least an image name, so this should raise + # IndexError since it tries to access the index 0 of an empty tuple + self.assertRaises(IndexError, ttk._format_elemcreate, 'image') + + # don't format returned values as a tcl script + # minimum acceptable for image type + self.assertEqual(ttk._format_elemcreate('image', False, 'test'), + ("test", ())) + # specifying a state spec + self.assertEqual(ttk._format_elemcreate('image', False, 'test', + ('', 'a')), ("test {} a", ())) + # state spec with multiple states + self.assertEqual(ttk._format_elemcreate('image', False, 'test', + ('a', 'b', 'c')), ("test {a b} c", ())) + # state spec and options + self.assertEqual(ttk._format_elemcreate('image', False, 'test', + ('a', 'b'), a='x'), ("test a b", ("-a", "x"))) + # format returned values as a tcl script + # state spec with multiple states and an option with a multivalue + self.assertEqual(ttk._format_elemcreate('image', True, 'test', + ('a', 'b', 'c', 'd'), x=[2, 3]), ("{test {a b c} d}", "-x {2 3}")) + + ## Testing type = vsapi + # vsapi type expects at least a class name and a part_id, so this + # should raise a ValueError since it tries to get two elements from + # an empty tuple + self.assertRaises(ValueError, ttk._format_elemcreate, 'vsapi') + + # don't format returned values as a tcl script + # minimum acceptable for vsapi + self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b'), + ('a', 'b', ('', 1), ())) + # now with a state spec with multiple states + self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', + [('a', 'b', 'c')]), ('a', 'b', ('a b', 'c'), ())) + # state spec and option + self.assertEqual(ttk._format_elemcreate('vsapi', False, 'a', 'b', + [('a', 'b')], opt='x'), ('a', 'b', ('a', 'b'), ("-opt", "x"))) + # format returned values as a tcl script + # state spec with a multivalue and an option + self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b', + opt='x'), ("a b {{} 1}", "-opt x")) + self.assertEqual(ttk._format_elemcreate('vsapi', True, 'a', 'b', + [('a', 'b', [1, 2])], opt='x'), ("a b {{a b} {1 2}}", "-opt x")) + + # Testing type = from + # from type expects at least a type name + self.assertRaises(IndexError, ttk._format_elemcreate, 'from') + + self.assertEqual(ttk._format_elemcreate('from', False, 'a'), + ('a', ())) + self.assertEqual(ttk._format_elemcreate('from', False, 'a', 'b'), + ('a', ('b',))) + self.assertEqual(ttk._format_elemcreate('from', True, 'a', 'b'), + ('a', 'b')) + + + def test_format_layoutlist(self): + def sample(indent=0, indent_size=2): + return ttk._format_layoutlist( + [('a', {'other': [1, 2, 3], 'children': + [('b', {'children': + [('c', {'children': + [('d', {'nice': 'opt'})], 'something': (1, 2) + })] + })] + })], indent=indent, indent_size=indent_size)[0] + + def sample_expected(indent=0, indent_size=2): + spaces = lambda amount=0: ' ' * (amount + indent) + return ( + "%sa -other {1 2 3} -children {\n" + "%sb -children {\n" + "%sc -something {1 2} -children {\n" + "%sd -nice opt\n" + "%s}\n" + "%s}\n" + "%s}" % (spaces(), spaces(indent_size), + spaces(2 * indent_size), spaces(3 * indent_size), + spaces(2 * indent_size), spaces(indent_size), spaces())) + + # empty layout + self.assertEqual(ttk._format_layoutlist([])[0], '') + + # _format_layoutlist always expects the second item (in every item) + # to act like a dict (except when the value evaluates to False). + self.assertRaises(AttributeError, + ttk._format_layoutlist, [('a', 'b')]) + + smallest = ttk._format_layoutlist([('a', None)], indent=0) + self.assertEqual(smallest, + ttk._format_layoutlist([('a', '')], indent=0)) + self.assertEqual(smallest[0], 'a') + + # testing indentation levels + self.assertEqual(sample(), sample_expected()) + for i in range(4): + self.assertEqual(sample(i), sample_expected(i)) + self.assertEqual(sample(i, i), sample_expected(i, i)) + + # invalid layout format, different kind of exceptions will be + # raised by internal functions + + # plain wrong format + self.assertRaises(ValueError, ttk._format_layoutlist, + ['bad', 'format']) + # will try to use iteritems in the 'bad' string + self.assertRaises(AttributeError, ttk._format_layoutlist, + [('name', 'bad')]) + # bad children formatting + self.assertRaises(ValueError, ttk._format_layoutlist, + [('name', {'children': {'a': None}})]) + + + def test_script_from_settings(self): + # empty options + self.assertFalse(ttk._script_from_settings({'name': + {'configure': None, 'map': None, 'element create': None}})) + + # empty layout + self.assertEqual( + ttk._script_from_settings({'name': {'layout': None}}), + "ttk::style layout name {\nnull\n}") + + configdict = {'αβγ': True, 'á': False} + self.assertTrue( + ttk._script_from_settings({'name': {'configure': configdict}})) + + mapdict = {'üñíćódè': [('á', 'vãl')]} + self.assertTrue( + ttk._script_from_settings({'name': {'map': mapdict}})) + + # invalid image element + self.assertRaises(IndexError, + ttk._script_from_settings, {'name': {'element create': ['image']}}) + + # minimal valid image + self.assertTrue(ttk._script_from_settings({'name': + {'element create': ['image', 'name']}})) + + image = {'thing': {'element create': + ['image', 'name', ('state1', 'state2', 'val')]}} + self.assertEqual(ttk._script_from_settings(image), + "ttk::style element create thing image {name {state1 state2} val} ") + + image['thing']['element create'].append({'opt': 30}) + self.assertEqual(ttk._script_from_settings(image), + "ttk::style element create thing image {name {state1 state2} val} " + "-opt 30") + + image['thing']['element create'][-1]['opt'] = [MockTclObj(3), + MockTclObj('2m')] + self.assertEqual(ttk._script_from_settings(image), + "ttk::style element create thing image {name {state1 state2} val} " + "-opt {3 2m}") + + vsapi = {'pin': {'element create': + ['vsapi', 'EXPLORERBAR', 3, [ + ('pressed', '!selected', 3), + ('active', '!selected', 2), + ('pressed', 'selected', 6), + ('active', 'selected', 5), + ('selected', 4), + ('', 1)]]}} + self.assertEqual(ttk._script_from_settings(vsapi), + "ttk::style element create pin vsapi EXPLORERBAR 3 {" + "{pressed !selected} 3 " + "{active !selected} 2 " + "{pressed selected} 6 " + "{active selected} 5 " + "selected 4 " + "{} 1} ") + + def test_tclobj_to_py(self): + self.assertEqual( + ttk._tclobj_to_py((MockStateSpec('a', 'b'), 'val')), + [('a', 'b', 'val')]) + self.assertEqual( + ttk._tclobj_to_py([MockTclObj('1'), 2, MockTclObj('3m')]), + [1, 2, '3m']) + + + def test_list_from_statespec(self): + def test_it(sspec, value, res_value, states): + self.assertEqual(ttk._list_from_statespec( + (sspec, value)), [states + (res_value, )]) + + states_even = tuple('state%d' % i for i in range(6)) + statespec = MockStateSpec(*states_even) + test_it(statespec, 'val', 'val', states_even) + test_it(statespec, MockTclObj('val'), 'val', states_even) + + states_odd = tuple('state%d' % i for i in range(5)) + statespec = MockStateSpec(*states_odd) + test_it(statespec, 'val', 'val', states_odd) + + test_it(('a', 'b', 'c'), MockTclObj('val'), 'val', ('a', 'b', 'c')) + + + def test_list_from_layouttuple(self): + tk = MockTkApp() + + # empty layout tuple + self.assertFalse(ttk._list_from_layouttuple(tk, ())) + + # shortest layout tuple + self.assertEqual(ttk._list_from_layouttuple(tk, ('name', )), + [('name', {})]) + + # not so interesting ltuple + sample_ltuple = ('name', '-option', 'value') + self.assertEqual(ttk._list_from_layouttuple(tk, sample_ltuple), + [('name', {'option': 'value'})]) + + # empty children + self.assertEqual(ttk._list_from_layouttuple(tk, + ('something', '-children', ())), + [('something', {'children': []})] + ) + + # more interesting ltuple + ltuple = ( + 'name', '-option', 'niceone', '-children', ( + ('otherone', '-children', ( + ('child', )), '-otheropt', 'othervalue' + ) + ) + ) + self.assertEqual(ttk._list_from_layouttuple(tk, ltuple), + [('name', {'option': 'niceone', 'children': + [('otherone', {'otheropt': 'othervalue', 'children': + [('child', {})] + })] + })] + ) + + # bad tuples + self.assertRaises(ValueError, ttk._list_from_layouttuple, tk, + ('name', 'no_minus')) + self.assertRaises(ValueError, ttk._list_from_layouttuple, tk, + ('name', 'no_minus', 'value')) + self.assertRaises(ValueError, ttk._list_from_layouttuple, tk, + ('something', '-children')) # no children + + + def test_val_or_dict(self): + def func(res, opt=None, val=None): + if opt is None: + return res + if val is None: + return "test val" + return (opt, val) + + tk = MockTkApp() + tk.call = func + + self.assertEqual(ttk._val_or_dict(tk, {}, '-test:3'), + {'test': '3'}) + self.assertEqual(ttk._val_or_dict(tk, {}, ('-test', 3)), + {'test': 3}) + + self.assertEqual(ttk._val_or_dict(tk, {'test': None}, 'x:y'), + 'test val') + + self.assertEqual(ttk._val_or_dict(tk, {'test': 3}, 'x:y'), + {'test': 3}) + + + def test_convert_stringval(self): + tests = ( + (0, 0), ('09', 9), ('a', 'a'), ('áÚ', 'áÚ'), ([], '[]'), + (None, 'None') + ) + for orig, expected in tests: + self.assertEqual(ttk._convert_stringval(orig), expected) + + +class TclObjsToPyTest(unittest.TestCase): + + def test_unicode(self): + adict = {'opt': 'välúè'} + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'}) + + adict['opt'] = MockTclObj(adict['opt']) + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': 'välúè'}) + + def test_multivalues(self): + adict = {'opt': [1, 2, 3, 4]} + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 2, 3, 4]}) + + adict['opt'] = [1, 'xm', 3] + self.assertEqual(ttk.tclobjs_to_py(adict), {'opt': [1, 'xm', 3]}) + + adict['opt'] = (MockStateSpec('a', 'b'), 'válũè') + self.assertEqual(ttk.tclobjs_to_py(adict), + {'opt': [('a', 'b', 'válũè')]}) + + self.assertEqual(ttk.tclobjs_to_py({'x': ['y z']}), + {'x': ['y z']}) + + def test_nosplit(self): + self.assertEqual(ttk.tclobjs_to_py({'text': 'some text'}), + {'text': 'some text'}) + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_turtle.py b/Lib/test/test_turtle.py index 12d2eed8741..78b5386353d 100644 --- a/Lib/test/test_turtle.py +++ b/Lib/test/test_turtle.py @@ -577,6 +577,28 @@ def test_no_animation_calls_update_at_exit(self): s.update.assert_not_called() s.update.assert_called_once() + def test_update_is_not_reentrant(self): + # ondrag(goto) reenters _update() while cv.update() processes events; + # without a guard this recurses without bound (gh-50966). + s = turtle.TurtleScreen(cv=unittest.mock.MagicMock()) + depth = max_depth = 0 + + def reenter(): + nonlocal depth, max_depth + depth += 1 + max_depth = max(max_depth, depth) + if depth < 50: + s._update() # as an event handler would + depth -= 1 + + s.cv.update.reset_mock() # ignore calls made during construction + s.cv.update.side_effect = reenter + s._update() + # cv.update() runs once; reentrant calls only flush idle tasks. + self.assertEqual(s.cv.update.call_count, 1) + self.assertEqual(max_depth, 1) + self.assertTrue(s.cv.update_idletasks.called) + class TestTurtle(unittest.TestCase): def setUp(self): @@ -671,6 +693,34 @@ def test_dot_signature(self): self.assertRaises(turtle.TurtleGraphicsError, self.turtle.dot, 0, (0, 257, 0)) self.assertRaises(turtle.TurtleGraphicsError, self.turtle.dot, 0, 0, 257, 0) + def test_circle_undo(self): + self.turtle.circle(50, 90) + self.turtle.undo() + self.assertEqual(self.turtle.pos(), (0, 0)) + self.assertEqual(self.turtle.undobufferentries(), 0) + + def test_undo_sequence_resets_after_exception(self): + with unittest.mock.patch.object(self.turtle, "_write", + side_effect=ValueError): + self.assertRaises(ValueError, self.turtle.write, "spam") + self.assertFalse(self.turtle.undobuffer.cumulate) + + def test_nested_undo_sequence(self): + with self.turtle._undo_sequence(): + self.turtle.teleport(10, 20) + self.turtle.forward(10) + self.assertEqual(self.turtle.undobufferentries(), 1) + self.turtle.undo() + self.assertEqual(self.turtle.pos(), (0, 0)) + + def test_stamp_without_undobuffer(self): + shape = turtle.Shape("polygon", ((0, 0), (5, 9), (-5, 9))) + self.turtle.screen._shapes = {self.turtle.shape(): shape} + self.turtle.setundobuffer(None) + stamp = self.turtle.stamp() + self.turtle.clearstamp(stamp) + self.assertEqual(self.turtle.stampItems, []) + class TestModuleLevel(unittest.TestCase): def test_all_signatures(self): import inspect diff --git a/Lib/test/test_type_aliases.py b/Lib/test/test_type_aliases.py index ee1791bc1d0..d80a7fbfd18 100644 --- a/Lib/test/test_type_aliases.py +++ b/Lib/test/test_type_aliases.py @@ -1,13 +1,19 @@ import pickle import types import unittest -from test.support import check_syntax_error, run_code +import weakref +from test.support import check_syntax_error, gc_collect, run_code from test.typinganndata import mod_generics_cache from typing import ( Callable, TypeAliasType, TypeVar, TypeVarTuple, ParamSpec, Unpack, get_args, ) +type GlobalTypeAlias = int + +def get_type_alias(): + type TypeAliasInFunc = str + return TypeAliasInFunc class TypeParamsInvalidTest(unittest.TestCase): def test_name_collisions(self): @@ -70,6 +76,8 @@ def inner[B](self): class TypeParamsAliasValueTest(unittest.TestCase): + type TypeAliasInClass = dict + def test_alias_value_01(self): type TA1 = int @@ -124,6 +132,24 @@ def more_generic[T, *Ts, **P](): T, Ts, P = more_generic.__type_params__ self.assertEqual(alias.__value__, tuple[Callable[P, tuple[T, *Ts]], Callable[P2, tuple[T2, *Ts2]]]) + def test_reentrant_value_does_not_leak(self): + class Value: + pass + + refs = [] + + def compute(): + value = Value() + refs.append(weakref.ref(value)) + if len(refs) == 1: + Alias.__value__ + return value + + type Alias = compute() + self.assertIs(Alias.__value__, refs[0]()) + gc_collect() + self.assertIsNone(refs[1]()) + def test_subscripting(self): type NonGeneric = int type Generic[A] = dict[A, A] @@ -142,33 +168,67 @@ def test_subscripting(self): self.assertIs(specialized2.__origin__, VeryGeneric) self.assertEqual(specialized2.__args__, (int, str, float, [bool, range])) + def test___name__(self): + type TypeAliasLocal = GlobalTypeAlias + + self.assertEqual(GlobalTypeAlias.__name__, 'GlobalTypeAlias') + self.assertEqual(get_type_alias().__name__, 'TypeAliasInFunc') + self.assertEqual(self.TypeAliasInClass.__name__, 'TypeAliasInClass') + self.assertEqual(TypeAliasLocal.__name__, 'TypeAliasLocal') + + with self.assertRaisesRegex( + AttributeError, + "readonly attribute", + ): + setattr(TypeAliasLocal, '__name__', 'TA') + + def test___qualname__(self): + type TypeAliasLocal = GlobalTypeAlias + + self.assertEqual(GlobalTypeAlias.__qualname__, + 'GlobalTypeAlias') + self.assertEqual(get_type_alias().__qualname__, + 'get_type_alias..TypeAliasInFunc') + self.assertEqual(self.TypeAliasInClass.__qualname__, + 'TypeParamsAliasValueTest.TypeAliasInClass') + self.assertEqual(TypeAliasLocal.__qualname__, + 'TypeParamsAliasValueTest.test___qualname__..TypeAliasLocal') + + with self.assertRaisesRegex( + AttributeError, + "readonly attribute", + ): + setattr(TypeAliasLocal, '__qualname__', 'TA') + def test_repr(self): type Simple = int - type VeryGeneric[T, *Ts, **P] = Callable[P, tuple[T, *Ts]] + self.assertEqual(repr(Simple), Simple.__qualname__) - self.assertEqual(repr(Simple), "Simple") - self.assertEqual(repr(VeryGeneric), "VeryGeneric") + type VeryGeneric[T, *Ts, **P] = Callable[P, tuple[T, *Ts]] + self.assertEqual(repr(VeryGeneric), VeryGeneric.__qualname__) + fullname = f"{VeryGeneric.__module__}.{VeryGeneric.__qualname__}" self.assertEqual(repr(VeryGeneric[int, bytes, str, [float, object]]), - "VeryGeneric[int, bytes, str, [float, object]]") + f"{fullname}[int, bytes, str, [float, object]]") self.assertEqual(repr(VeryGeneric[int, []]), - "VeryGeneric[int, []]") + f"{fullname}[int, []]") self.assertEqual(repr(VeryGeneric[int, [VeryGeneric[int], list[str]]]), - "VeryGeneric[int, [VeryGeneric[int], list[str]]]") + f"{fullname}[int, [{fullname}[int], list[str]]]") def test_recursive_repr(self): type Recursive = Recursive - self.assertEqual(repr(Recursive), "Recursive") + self.assertEqual(repr(Recursive), Recursive.__qualname__) type X = list[Y] type Y = list[X] - self.assertEqual(repr(X), "X") - self.assertEqual(repr(Y), "Y") + self.assertEqual(repr(X), X.__qualname__) + self.assertEqual(repr(Y), Y.__qualname__) type GenericRecursive[X] = list[X | GenericRecursive[X]] - self.assertEqual(repr(GenericRecursive), "GenericRecursive") - self.assertEqual(repr(GenericRecursive[int]), "GenericRecursive[int]") + self.assertEqual(repr(GenericRecursive), GenericRecursive.__qualname__) + fullname = f"{GenericRecursive.__module__}.{GenericRecursive.__qualname__}" + self.assertEqual(repr(GenericRecursive[int]), f"{fullname}[int]") self.assertEqual(repr(GenericRecursive[GenericRecursive[int]]), - "GenericRecursive[GenericRecursive[int]]") + f"{fullname}[{fullname}[int]]") def test_raising(self): type MissingName = list[_My_X] @@ -193,15 +253,25 @@ class TypeAliasConstructorTest(unittest.TestCase): def test_basic(self): TA = TypeAliasType("TA", int) self.assertEqual(TA.__name__, "TA") + self.assertEqual(TA.__qualname__, "TA") self.assertIs(TA.__value__, int) self.assertEqual(TA.__type_params__, ()) self.assertEqual(TA.__module__, __name__) + def test_with_qualname(self): + TA = TypeAliasType("TA", str, qualname="Class.TA") + self.assertEqual(TA.__name__, "TA") + self.assertEqual(TA.__qualname__, "Class.TA") + self.assertIs(TA.__value__, str) + self.assertEqual(TA.__type_params__, ()) + self.assertEqual(TA.__module__, __name__) + def test_attributes_with_exec(self): ns = {} exec("type TA = int", ns, ns) TA = ns["TA"] self.assertEqual(TA.__name__, "TA") + self.assertEqual(TA.__qualname__, "TA") self.assertIs(TA.__value__, int) self.assertEqual(TA.__type_params__, ()) self.assertIs(TA.__module__, None) @@ -210,6 +280,7 @@ def test_generic(self): T = TypeVar("T") TA = TypeAliasType("TA", list[T], type_params=(T,)) self.assertEqual(TA.__name__, "TA") + self.assertEqual(TA.__qualname__, "TA") self.assertEqual(TA.__value__, list[T]) self.assertEqual(TA.__type_params__, (T,)) self.assertEqual(TA.__module__, __name__) @@ -218,6 +289,7 @@ def test_generic(self): def test_not_generic(self): TA = TypeAliasType("TA", list[int], type_params=()) self.assertEqual(TA.__name__, "TA") + self.assertEqual(TA.__qualname__, "TA") self.assertEqual(TA.__value__, list[int]) self.assertEqual(TA.__type_params__, ()) self.assertEqual(TA.__module__, __name__) @@ -268,8 +340,9 @@ def test_expects_type_like(self): TypeAliasType("A", int, type_params=(T, 2)) def test_keywords(self): - TA = TypeAliasType(name="TA", value=int) + TA = TypeAliasType(name="TA", value=int, type_params=(), qualname=None) self.assertEqual(TA.__name__, "TA") + self.assertEqual(TA.__qualname__, "TA") self.assertIs(TA.__value__, int) self.assertEqual(TA.__type_params__, ()) self.assertEqual(TA.__module__, __name__) @@ -283,6 +356,8 @@ def test_errors(self): TypeAliasType("TA", list, ()) with self.assertRaises(TypeError): TypeAliasType("TA", list, type_params=42) + with self.assertRaises(TypeError): + TypeAliasType("TA", list, qualname=range(5)) class TypeAliasTypeTest(unittest.TestCase): @@ -316,6 +391,8 @@ def test_module(self): mod_generics_cache.__name__) self.assertEqual(mod_generics_cache.OldStyle.__module__, mod_generics_cache.__name__) + Alias.__module__ = "ham.spam.eggs" + self.assertEqual(Alias.__module__, "ham.spam.eggs") def test_unpack(self): type Alias = tuple[int, int] diff --git a/Lib/test/test_type_annotations.py b/Lib/test/test_type_annotations.py index c98b99e98e9..54db123a5dc 100644 --- a/Lib/test/test_type_annotations.py +++ b/Lib/test/test_type_annotations.py @@ -1,5 +1,6 @@ import annotationlib import inspect +import itertools import textwrap import types import unittest @@ -309,7 +310,7 @@ def check_annotations(self, f): print(f.__annotations__) f.__annotate__ = lambda x: 42 - with self.assertRaisesRegex(TypeError, r"__annotate__ returned non-dict of type 'int'"): + with self.assertRaisesRegex(TypeError, r"__annotate__\(\) must return a dict, not int"): print(f.__annotations__) f.__annotate__ = lambda x: {"x": x} @@ -855,9 +856,9 @@ def method(self, x: int): """ ns = run_code(code) method = ns["Outer"].method + self.assertEqual(method.__annotate__.__qualname__, "Outer.method.__annotate__") self.assertEqual(ns["f"].__annotate__.__qualname__, "f.__annotate__") self.assertEqual(ns["f"]().__annotate__.__qualname__, "f..nested.__annotate__") - self.assertEqual(method.__annotate__.__qualname__, "Outer.method.__annotate__") self.assertEqual(ns["Outer"].__annotate__.__qualname__, "Outer.__annotate__") # gh-138349 @@ -896,3 +897,18 @@ class Generic: mod = build_module(code) annos = mod.__annotations__ self.assertEqual(annos, {"annotated_name": 0}) + + # gh-154902 + def test_conditional_annotations_rebound(self): + # user code can rebind __conditional_annotations__ to any object + lefts = ("__conditional_annotations__", + 'globals()["__conditional_annotations__"]') + values = ("0", "{}", "[]", "''", "object()", "frozenset()") + for left, value in itertools.product(lefts, values): + with self.subTest(left=left, value=value): + code = f""" + {left} = {value} + x: int + """ + with self.assertRaises(TypeError): + run_code(code) diff --git a/Lib/test/test_type_cache.py b/Lib/test/test_type_cache.py index 7469a1047f8..849a2afd8ed 100644 --- a/Lib/test/test_type_cache.py +++ b/Lib/test/test_type_cache.py @@ -1,9 +1,10 @@ """ Tests for the internal type cache in CPython. """ +import collections.abc import dis import unittest import warnings from test import support -from test.support import import_helper, requires_specialization, requires_specialization_ft +from test.support import import_helper, requires_specialization try: from sys import _clear_type_cache except ImportError: @@ -114,6 +115,25 @@ class HolderSub(Holder): Holder.set_value() HolderSub.value + def test_abc_register_invalidates_subclass_versions(self): + class Parent: + pass + + class Child(Parent): + pass + + type_assign_version(Parent) + type_assign_version(Child) + parent_version = type_get_version(Parent) + child_version = type_get_version(Child) + if parent_version == 0 or child_version == 0: + self.skipTest("Could not assign valid type versions") + + collections.abc.Mapping.register(Parent) + + self.assertEqual(type_get_version(Parent), 0) + self.assertEqual(type_get_version(Child), 0) + @support.cpython_only class TypeCacheWithSpecializationTests(unittest.TestCase): def tearDown(self): @@ -219,7 +239,7 @@ def store_bar_2(type_): self._check_specialization(store_bar_2, B(), "STORE_ATTR", should_specialize=False) - @requires_specialization_ft + @requires_specialization def test_class_call_specialization_user_type(self): class F: def __init__(self): diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py index e07fa568a86..4d8227bc81c 100644 --- a/Lib/test/test_types.py +++ b/Lib/test/test_types.py @@ -8,13 +8,9 @@ from test.support.import_helper import import_fresh_module import collections.abc -from collections import namedtuple, UserDict +from collections import namedtuple, UserDict, OrderedDict import copy -# XXX: RUSTPYTHON -try: - import _datetime -except ImportError: - _datetime = None +import _datetime import gc import inspect import pickle @@ -25,6 +21,7 @@ import unittest.mock import weakref import typing +import re import unittest # XXX: RUSTPYTHON; importing to be able to skip tests @@ -46,7 +43,7 @@ def clear_typing_caches(): class TypesTests(unittest.TestCase): def test_names(self): - c_only_names = {'CapsuleType'} + c_only_names = {'CapsuleType', 'LazyImportType'} ignored = {'new_class', 'resolve_bases', 'prepare_class', 'get_original_bases', 'DynamicClassAttribute', 'coroutine'} @@ -58,11 +55,13 @@ def test_names(self): 'AsyncGeneratorType', 'BuiltinFunctionType', 'BuiltinMethodType', 'CapsuleType', 'CellType', 'ClassMethodDescriptorType', 'CodeType', 'CoroutineType', 'EllipsisType', 'FrameType', 'FunctionType', + 'FrameLocalsProxyType', 'GeneratorType', 'GenericAlias', 'GetSetDescriptorType', - 'LambdaType', 'MappingProxyType', 'MemberDescriptorType', - 'MethodDescriptorType', 'MethodType', 'MethodWrapperType', - 'ModuleType', 'NoneType', 'NotImplementedType', 'SimpleNamespace', - 'TracebackType', 'UnionType', 'WrapperDescriptorType', + 'LambdaType', 'LazyImportType', 'MappingProxyType', + 'MemberDescriptorType', 'MethodDescriptorType', 'MethodType', + 'MethodWrapperType', 'ModuleType', 'NoneType', + 'NotImplementedType', 'SimpleNamespace', 'TracebackType', + 'UnionType', 'WrapperDescriptorType', } self.assertEqual(all_names, set(c_types.__all__)) self.assertEqual(all_names - c_only_names, set(py_types.__all__)) @@ -717,6 +716,19 @@ def call(part): """ assert_python_ok("-c", code) + def test_frame_locals_proxy_type(self): + self.assertIsInstance(types.FrameLocalsProxyType, type) + if MISSING_C_DOCSTRINGS: + self.assertIsNone(types.FrameLocalsProxyType.__doc__) + else: + self.assertIsInstance(types.FrameLocalsProxyType.__doc__, str) + self.assertEqual(types.FrameLocalsProxyType.__module__, 'builtins') + self.assertEqual(types.FrameLocalsProxyType.__name__, 'FrameLocalsProxy') + + frame = inspect.currentframe() + self.assertIsNotNone(frame) + self.assertIsInstance(frame.f_locals, types.FrameLocalsProxyType) + class UnionTests(unittest.TestCase): @@ -1382,6 +1394,128 @@ def __hash__(self): view = self.mappingproxy(mapping) self.assertEqual(hash(view), hash(mapping)) + def check_richcompare(self, mapping_type): + data1 = mapping_type({'a': 1}) + data2 = mapping_type({'a': 2}) + mp1 = self.mappingproxy(data1) + copy1 = self.mappingproxy(data1) + mp2 = self.mappingproxy(data2) + + self.assertTrue(mp1 == data1) + self.assertTrue(data1 == mp1) + self.assertTrue(copy1 == data1) + + self.assertTrue(mp1 == copy1) + self.assertFalse(mp1 != copy1) + + self.assertFalse(mp1 == mp2) + self.assertTrue(mp1 != mp2) + self.assertFalse(mp2 == data1) + self.assertTrue(mp2 != data1) + self.assertTrue(data1 != mp2) + + msg = "not supported between instances of 'mappingproxy' and 'mappingproxy'" + with self.assertRaisesRegex(TypeError, msg): + mp1 > mp2 + with self.assertRaisesRegex(TypeError, msg): + mp1 < copy1 + with self.assertRaisesRegex(TypeError, msg): + mp2 >= mp2 + with self.assertRaisesRegex(TypeError, msg): + copy1 <= mp1 + + if mapping_type.__module__ == 'collections': + mapping_name = f'{mapping_type.__module__}.{mapping_type.__name__}' + else: + mapping_name = mapping_type.__name__ + with self.assertRaisesRegex( + TypeError, + f"not supported between instances of 'mappingproxy' and '{mapping_name}'", + ): + copy1 <= data1 + + class Evil: + def __eq__(self, other): + return other + + result = (mp1 == Evil()) + self.assertIs(type(result), mapping_type) + if mapping_type == dict: + # Evil.__eq__() gets a copy of the mapping + self.assertEqual(result, data1) + else: + self.assertIs(result, data1) + + def test_richcompare_dict(self): + self.check_richcompare(dict) + + def test_richcompare_custom_mapping(self): + class CustomMapping(collections.abc.Mapping): + def __init__(self, data): + self._data = data + + def __getitem__(self, key): + return self._data[key] + + def __iter__(self): + return iter(self._data) + + def __len__(self): + return len(self._data) + + def __contains__(self, item): + return item in self._data + + self.check_richcompare(CustomMapping) + + class CustomMapping2(CustomMapping): + def __eq__(self, other): + return ( + isinstance(other, CustomMapping) + and self._data == other._data + ) + + mp1 = self.mappingproxy(CustomMapping({'a': 1})) + self.assertEqual(mp1, CustomMapping2({'a': 1})) + self.assertNotEqual(CustomMapping2({'a': 1}), mp1) + + def test_richcompare_odict(self): + self.check_richcompare(OrderedDict) + + def test_richcompare_frozendict(self): + self.check_richcompare(frozendict) + + def test_richcompare_evil(self): + # This test used to mutate the list dictionary, + # but MappingProxyType now creates a copy to call `__eq__`: + # https://github.com/python/cpython/issues/152405 + key = "__mappingproxy_crash_key__" + + class Evil: + def __eq__(self, other): + other[key] = 1 + return other + + # Checks that it does not mutate the internals of `MappingProxyType`: + dc = {} + leaked = self.mappingproxy(dc) == Evil() + self.assertIs(type(leaked), dict) + self.assertIn(key, leaked) + self.assertNotIn(key, dc) + + # Exposes the internals of `MappingProxyType` via richcompare: + leaked = vars(list) == Evil() + self.assertIs(type(leaked), dict) + self.assertIn(key, leaked) + name = "__mappingproxy_crash_probe__" + leaked[name] = lambda self: "probe" + self.assertIn(name, leaked) + self.assertNotHasAttr(list, key) + self.assertNotHasAttr(list, name) # it used to return `True` + del leaked[name] + self.assertNotIn(name, leaked) + self.assertNotHasAttr(list, name) # it used to crash + class ClassCreationTests(unittest.TestCase): @@ -2016,6 +2150,24 @@ def test_equal(self): self.assertEqual(ns1, ns2) self.assertNotEqual(ns2, types.SimpleNamespace()) + def test_richcompare_unsupported(self): + ns1 = types.SimpleNamespace(x=1) + ns2 = types.SimpleNamespace(y=2) + + msg = re.escape( + "not supported between instances of " + "'types.SimpleNamespace' and 'types.SimpleNamespace'" + ) + + with self.assertRaisesRegex(TypeError, msg): + ns1 > ns2 + with self.assertRaisesRegex(TypeError, msg): + ns1 >= ns2 + with self.assertRaisesRegex(TypeError, msg): + ns1 < ns2 + with self.assertRaisesRegex(TypeError, msg): + ns1 <= ns2 + def test_nested(self): ns1 = types.SimpleNamespace(a=1, b=2) ns2 = types.SimpleNamespace() diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py index b5974c72ab7..78dcdbd1795 100644 --- a/Lib/test/test_typing.py +++ b/Lib/test/test_typing.py @@ -13,6 +13,7 @@ import pickle import re import sys +import warnings from unittest import TestCase, main from unittest.mock import patch from copy import copy, deepcopy @@ -28,30 +29,29 @@ from typing import assert_type, cast, runtime_checkable from typing import get_type_hints from typing import get_origin, get_args, get_protocol_members -from typing import override +from typing import override, disjoint_base from typing import is_typeddict, is_protocol from typing import reveal_type from typing import dataclass_transform -from typing import no_type_check, no_type_check_decorator +from typing import no_type_check from typing import Type -from typing import NamedTuple, NotRequired, Required, ReadOnly, TypedDict +from typing import NamedTuple, NotRequired, Required, ReadOnly, TypedDict, NoExtraItems from typing import IO, TextIO, BinaryIO from typing import Pattern, Match from typing import Annotated, ForwardRef from typing import Self, LiteralString from typing import TypeAlias from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs -from typing import TypeGuard, TypeIs, NoDefault +from typing import TypeForm, TypeGuard, TypeIs, NoDefault import abc import textwrap import typing import weakref -import warnings import types from test.support import ( - captured_stderr, cpython_only, infinite_recursion, requires_docstrings, import_helper, run_code, - EqualToForwardRef, + captured_stderr, cpython_only, requires_docstrings, import_helper, run_code, + subTests, EqualToForwardRef, exceeds_recursion_limit, run_with_limited_c_stack, skip_wasi_stack_overflow, skip_emscripten_stack_overflow, ) @@ -60,8 +60,6 @@ ann_module, ann_module2, ann_module3, ann_module5, ann_module6, ann_module8 ) -import unittest # XXX: RUSTPYTHON; importing to be able to skip tests - CANNOT_SUBCLASS_TYPE = 'Cannot subclass special typing classes' NOT_A_BASE_TYPE = "type 'typing.%s' is not an acceptable base type" @@ -784,7 +782,7 @@ def test_typevartuple_none(self): self.assertIs(U_None.__default__, None) self.assertIs(U_None.has_default(), True) - class X[**Ts]: ... + class X[*Ts]: ... Ts, = X.__type_params__ self.assertIs(Ts.__default__, NoDefault) self.assertIs(Ts.has_default(), False) @@ -1085,7 +1083,6 @@ class C(Generic[T1, T2, T3]): pass eval(expected_str) ) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_variadic_parameters(self): T1 = TypeVar('T1') T2 = TypeVar('T2') @@ -1293,6 +1290,62 @@ def test_cannot_call_instance(self): with self.assertRaises(TypeError): Ts() + def test_default_variance(self): + Ts = TypeVarTuple('Ts') + self.assertIs(Ts.__covariant__, False) + self.assertIs(Ts.__contravariant__, False) + self.assertIs(Ts.__infer_variance__, False) + self.assertIsNone(Ts.__bound__) + + def test_covariant(self): + Ts_co = TypeVarTuple('Ts_co', covariant=True) + self.assertIs(Ts_co.__covariant__, True) + self.assertIs(Ts_co.__contravariant__, False) + self.assertIs(Ts_co.__infer_variance__, False) + + def test_contravariant(self): + Ts_contra = TypeVarTuple('Ts_contra', contravariant=True) + self.assertIs(Ts_contra.__covariant__, False) + self.assertIs(Ts_contra.__contravariant__, True) + self.assertIs(Ts_contra.__infer_variance__, False) + + def test_infer_variance(self): + Ts = TypeVarTuple('Ts', infer_variance=True) + self.assertIs(Ts.__covariant__, False) + self.assertIs(Ts.__contravariant__, False) + self.assertIs(Ts.__infer_variance__, True) + + def test_bound(self): + Ts_bound = TypeVarTuple('Ts_bound', bound=int) + self.assertIs(Ts_bound.__bound__, int) + Ts_tuple_bound = TypeVarTuple('Ts_tuple_bound', bound=(int, str)) + self.assertEqual(Ts_tuple_bound.__bound__, (int, str)) + obj = object() + Ts_object = TypeVarTuple('Ts_object', bound=obj) + self.assertIs(Ts_object.__bound__, obj) + Ts_no_bound = TypeVarTuple('Ts_no_bound') + self.assertIsNone(Ts_no_bound.__bound__) + + def test_no_bivariant(self): + with self.assertRaises(ValueError): + TypeVarTuple('Ts', covariant=True, contravariant=True) + + def test_cannot_combine_explicit_and_infer(self): + with self.assertRaises(ValueError): + TypeVarTuple('Ts', covariant=True, infer_variance=True) + with self.assertRaises(ValueError): + TypeVarTuple('Ts', contravariant=True, infer_variance=True) + + def test_repr_with_variance(self): + Ts = TypeVarTuple('Ts') + self.assertEqual(repr(Ts), '~Ts') + Ts_co = TypeVarTuple('Ts_co', covariant=True) + self.assertEqual(repr(Ts_co), '+Ts_co') + Ts_contra = TypeVarTuple('Ts_contra', contravariant=True) + self.assertEqual(repr(Ts_contra), '-Ts_contra') + Ts_infer = TypeVarTuple('Ts_infer', infer_variance=True) + self.assertEqual(repr(Ts_infer), 'Ts_infer') + def test_unpacked_typevartuple_is_equal_to_itself(self): Ts = TypeVarTuple('Ts') self.assertEqual((*Ts,)[0], (*Ts,)[0]) @@ -1432,16 +1485,16 @@ def test_repr_is_correct(self): class G1(Generic[*Ts]): pass class G2(Generic[Unpack[Ts]]): pass - self.assertEqual(repr(Ts), 'Ts') + self.assertEqual(repr(Ts), '~Ts') - self.assertEqual(repr((*Ts,)[0]), 'typing.Unpack[Ts]') - self.assertEqual(repr(Unpack[Ts]), 'typing.Unpack[Ts]') + self.assertEqual(repr((*Ts,)[0]), 'typing.Unpack[~Ts]') + self.assertEqual(repr(Unpack[Ts]), 'typing.Unpack[~Ts]') - self.assertEqual(repr(tuple[*Ts]), 'tuple[typing.Unpack[Ts]]') - self.assertEqual(repr(Tuple[Unpack[Ts]]), 'typing.Tuple[typing.Unpack[Ts]]') + self.assertEqual(repr(tuple[*Ts]), 'tuple[typing.Unpack[~Ts]]') + self.assertEqual(repr(Tuple[Unpack[Ts]]), 'typing.Tuple[typing.Unpack[~Ts]]') - self.assertEqual(repr(*tuple[*Ts]), '*tuple[typing.Unpack[Ts]]') - self.assertEqual(repr(Unpack[Tuple[Unpack[Ts]]]), 'typing.Unpack[typing.Tuple[typing.Unpack[Ts]]]') + self.assertEqual(repr(*tuple[*Ts]), '*tuple[typing.Unpack[~Ts]]') + self.assertEqual(repr(Unpack[Tuple[Unpack[Ts]]]), 'typing.Unpack[typing.Tuple[typing.Unpack[~Ts]]]') def test_variadic_class_repr_is_correct(self): Ts = TypeVarTuple('Ts') @@ -1480,61 +1533,61 @@ def test_variadic_class_alias_repr_is_correct(self): class A(Generic[Unpack[Ts]]): pass B = A[*Ts] - self.assertEndsWith(repr(B), 'A[typing.Unpack[Ts]]') + self.assertEndsWith(repr(B), 'A[typing.Unpack[~Ts]]') self.assertEndsWith(repr(B[()]), 'A[()]') self.assertEndsWith(repr(B[float]), 'A[float]') self.assertEndsWith(repr(B[float, str]), 'A[float, str]') C = A[Unpack[Ts]] - self.assertEndsWith(repr(C), 'A[typing.Unpack[Ts]]') + self.assertEndsWith(repr(C), 'A[typing.Unpack[~Ts]]') self.assertEndsWith(repr(C[()]), 'A[()]') self.assertEndsWith(repr(C[float]), 'A[float]') self.assertEndsWith(repr(C[float, str]), 'A[float, str]') D = A[*Ts, int] - self.assertEndsWith(repr(D), 'A[typing.Unpack[Ts], int]') + self.assertEndsWith(repr(D), 'A[typing.Unpack[~Ts], int]') self.assertEndsWith(repr(D[()]), 'A[int]') self.assertEndsWith(repr(D[float]), 'A[float, int]') self.assertEndsWith(repr(D[float, str]), 'A[float, str, int]') E = A[Unpack[Ts], int] - self.assertEndsWith(repr(E), 'A[typing.Unpack[Ts], int]') + self.assertEndsWith(repr(E), 'A[typing.Unpack[~Ts], int]') self.assertEndsWith(repr(E[()]), 'A[int]') self.assertEndsWith(repr(E[float]), 'A[float, int]') self.assertEndsWith(repr(E[float, str]), 'A[float, str, int]') F = A[int, *Ts] - self.assertEndsWith(repr(F), 'A[int, typing.Unpack[Ts]]') + self.assertEndsWith(repr(F), 'A[int, typing.Unpack[~Ts]]') self.assertEndsWith(repr(F[()]), 'A[int]') self.assertEndsWith(repr(F[float]), 'A[int, float]') self.assertEndsWith(repr(F[float, str]), 'A[int, float, str]') G = A[int, Unpack[Ts]] - self.assertEndsWith(repr(G), 'A[int, typing.Unpack[Ts]]') + self.assertEndsWith(repr(G), 'A[int, typing.Unpack[~Ts]]') self.assertEndsWith(repr(G[()]), 'A[int]') self.assertEndsWith(repr(G[float]), 'A[int, float]') self.assertEndsWith(repr(G[float, str]), 'A[int, float, str]') H = A[int, *Ts, str] - self.assertEndsWith(repr(H), 'A[int, typing.Unpack[Ts], str]') + self.assertEndsWith(repr(H), 'A[int, typing.Unpack[~Ts], str]') self.assertEndsWith(repr(H[()]), 'A[int, str]') self.assertEndsWith(repr(H[float]), 'A[int, float, str]') self.assertEndsWith(repr(H[float, str]), 'A[int, float, str, str]') I = A[int, Unpack[Ts], str] - self.assertEndsWith(repr(I), 'A[int, typing.Unpack[Ts], str]') + self.assertEndsWith(repr(I), 'A[int, typing.Unpack[~Ts], str]') self.assertEndsWith(repr(I[()]), 'A[int, str]') self.assertEndsWith(repr(I[float]), 'A[int, float, str]') self.assertEndsWith(repr(I[float, str]), 'A[int, float, str, str]') J = A[*Ts, *tuple[str, ...]] - self.assertEndsWith(repr(J), 'A[typing.Unpack[Ts], *tuple[str, ...]]') + self.assertEndsWith(repr(J), 'A[typing.Unpack[~Ts], *tuple[str, ...]]') self.assertEndsWith(repr(J[()]), 'A[*tuple[str, ...]]') self.assertEndsWith(repr(J[float]), 'A[float, *tuple[str, ...]]') self.assertEndsWith(repr(J[float, str]), 'A[float, str, *tuple[str, ...]]') K = A[Unpack[Ts], Unpack[Tuple[str, ...]]] - self.assertEndsWith(repr(K), 'A[typing.Unpack[Ts], typing.Unpack[typing.Tuple[str, ...]]]') + self.assertEndsWith(repr(K), 'A[typing.Unpack[~Ts], typing.Unpack[typing.Tuple[str, ...]]]') self.assertEndsWith(repr(K[()]), 'A[typing.Unpack[typing.Tuple[str, ...]]]') self.assertEndsWith(repr(K[float]), 'A[float, typing.Unpack[typing.Tuple[str, ...]]]') self.assertEndsWith(repr(K[float, str]), 'A[float, str, typing.Unpack[typing.Tuple[str, ...]]]') @@ -1555,9 +1608,9 @@ class G(type(Unpack[Ts])): pass with self.assertRaisesRegex(TypeError, r'Cannot subclass typing\.Unpack'): class H(Unpack): pass - with self.assertRaisesRegex(TypeError, r'Cannot subclass typing.Unpack\[Ts\]'): + with self.assertRaisesRegex(TypeError, r'Cannot subclass typing.Unpack\[~Ts\]'): class I(*Ts): pass - with self.assertRaisesRegex(TypeError, r'Cannot subclass typing.Unpack\[Ts\]'): + with self.assertRaisesRegex(TypeError, r'Cannot subclass typing.Unpack\[~Ts\]'): class J(Unpack[Ts]): pass def test_variadic_class_args_are_correct(self): @@ -1621,7 +1674,10 @@ def func1(*args: *Ts): pass self.assertEqual(gth(func1), {'args': Unpack[Ts]}) def func2(*args: *tuple[int, str]): pass - self.assertEqual(gth(func2), {'args': Unpack[tuple[int, str]]}) + hint = gth(func2)['args'] + self.assertIsInstance(hint, types.GenericAlias) + self.assertEqual(hint.__args__[0], int) + self.assertIs(hint.__unpacked__, True) class CustomVariadic(Generic[*Ts]): pass @@ -1636,7 +1692,10 @@ def func1(*args: '*Ts'): pass {'args': Unpack[Ts]}) def func2(*args: '*tuple[int, str]'): pass - self.assertEqual(gth(func2), {'args': Unpack[tuple[int, str]]}) + hint = gth(func2)['args'] + self.assertIsInstance(hint, types.GenericAlias) + self.assertEqual(hint.__args__[0], int) + self.assertIs(hint.__unpacked__, True) class CustomVariadic(Generic[*Ts]): pass @@ -3890,8 +3949,8 @@ def meth(self): pass self.assertIsNot(get_protocol_members(PR), P.__protocol_attrs__) acceptable_extra_attrs = { - '_is_protocol', '_is_runtime_protocol', '__parameters__', - '__init__', '__annotations__', '__subclasshook__', '__annotate__', + '_is_protocol', '_is_runtime_protocol', '__typing_is_deprecated_inherited_runtime_protocol__', + '__parameters__', '__init__', '__annotations__', '__subclasshook__', '__annotate__', '__annotations_cache__', '__annotate_func__', } self.assertLessEqual(vars(NonP).keys(), vars(C).keys() | acceptable_extra_attrs) @@ -3983,6 +4042,7 @@ class C: pass def test_defining_generic_protocols(self): T = TypeVar('T') + T2 = TypeVar('T2') S = TypeVar('S') @runtime_checkable @@ -3992,17 +4052,26 @@ def meth(self): pass class P(PR[int, T], Protocol[T]): y = 1 + self.assertEqual(P.__parameters__, (T,)) + with self.assertRaises(TypeError): PR[int] with self.assertRaises(TypeError): P[int, str] + with self.assertRaisesRegex( + TypeError, + re.escape('Some type variables (~S) are not listed in Protocol[~T, ~T2]'), + ): + class ExtraTypeVars(P[S], Protocol[T, T2]): ... class C(PR[int, T]): pass + self.assertEqual(C.__parameters__, (T,)) self.assertIsInstance(C[str](), C) def test_defining_generic_protocols_old_style(self): T = TypeVar('T') + T2 = TypeVar('T2') S = TypeVar('S') @runtime_checkable @@ -4021,9 +4090,19 @@ class P(PR[int, str], Protocol): class P1(Protocol, Generic[T]): def bar(self, x: T) -> str: ... + self.assertEqual(P1.__parameters__, (T,)) + class P2(Generic[T], Protocol): def bar(self, x: T) -> str: ... + self.assertEqual(P2.__parameters__, (T,)) + + msg = re.escape('Some type variables (~S) are not listed in Protocol[~T, ~T2]') + with self.assertRaisesRegex(TypeError, msg): + class ExtraTypeVars(P1[S], Protocol[T, T2]): ... + with self.assertRaisesRegex(TypeError, msg): + class ExtraTypeVars(P2[S], Protocol[T, T2]): ... + @runtime_checkable class PSub(P1[str], Protocol): x = 1 @@ -4036,6 +4115,28 @@ def bar(self, x: str) -> str: self.assertIsInstance(Test(), PSub) + def test_protocol_parameter_order(self): + # https://github.com/python/cpython/issues/137191 + T1 = TypeVar("T1") + T2 = TypeVar("T2", default=object) + + class A(Protocol[T1]): ... + + class B0(A[T2], Generic[T1, T2]): ... + self.assertEqual(B0.__parameters__, (T1, T2)) + + class B1(A[T2], Protocol, Generic[T1, T2]): ... + self.assertEqual(B1.__parameters__, (T1, T2)) + + class B2(A[T2], Protocol[T1, T2]): ... + self.assertEqual(B2.__parameters__, (T1, T2)) + + class B3[T1, T2](A[T2], Protocol): + @staticmethod + def get_typeparams(): + return (T1, T2) + self.assertEqual(B3.__parameters__, B3.get_typeparams()) + def test_pep695_generic_protocol_callable_members(self): @runtime_checkable class Foo[T](Protocol): @@ -4421,6 +4522,70 @@ class P(Protocol): with self.assertRaisesRegex(TypeError, "@runtime_checkable"): isinstance(1, P) + @subTests(['check_obj', 'check_func'], ([42, isinstance], [frozenset, issubclass])) + def test_inherited_runtime_protocol_deprecated(self, check_obj, check_func): + """See GH-132604.""" + + class BareProto(Protocol): + """I am not runtime-checkable.""" + + @runtime_checkable + class RCProto1(Protocol): + """I am runtime-checkable.""" + + class InheritedRCProto1(RCProto1, Protocol): + """I am accidentally runtime-checkable (by inheritance).""" + + @runtime_checkable + class RCProto2(InheritedRCProto1, Protocol): + """Explicit RC -> inherited RC -> explicit RC.""" + def spam(self): ... + + @runtime_checkable + class RCProto3(BareProto, Protocol): + """Not RC -> explicit RC.""" + + class InheritedRCProto2(RCProto3, Protocol): + """Not RC -> explicit RC -> inherited RC.""" + def eggs(self): ... + + class InheritedRCProto3(RCProto2, Protocol): + """Explicit RC -> inherited RC -> explicit RC -> inherited RC.""" + + class Concrete1(BareProto): + pass + + class Concrete2(InheritedRCProto2): + pass + + class Concrete3(InheritedRCProto3): + pass + + depr_message_re = ( + r" isn't explicitly decorated " + r"with @runtime_checkable but it is used in issubclass\(\) or " + r"isinstance\(\). Instance and class checks can only be used with " + r"@runtime_checkable protocols. This will raise a TypeError in Python 3.20." + ) + + for inherited_runtime_proto in InheritedRCProto1, InheritedRCProto2, InheritedRCProto3: + with self.assertWarnsRegex(DeprecationWarning, depr_message_re): + check_func(check_obj, inherited_runtime_proto) + + # Don't warn for explicitly checkable protocols and concrete implementations. + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + + for checkable in RCProto1, RCProto2, RCProto3, Concrete1, Concrete2, Concrete3: + check_func(check_obj, checkable) + + # Don't warn for uncheckable protocols. + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + + with self.assertRaises(TypeError): # Self-test. Protocol below can't be runtime-checkable. + check_func(check_obj, BareProto) + def test_super_call_init(self): class P(Protocol): x: int @@ -5506,13 +5671,13 @@ class TsP(Generic[*Ts, P]): MyCallable[[int], bool]: "MyCallable[[int], bool]", MyCallable[[int, str], bool]: "MyCallable[[int, str], bool]", MyCallable[[int, list[int]], bool]: "MyCallable[[int, list[int]], bool]", - MyCallable[Concatenate[*Ts, P], T]: "MyCallable[typing.Concatenate[typing.Unpack[Ts], ~P], ~T]", + MyCallable[Concatenate[*Ts, P], T]: "MyCallable[typing.Concatenate[typing.Unpack[~Ts], ~P], ~T]", DoubleSpec[P2, P, T]: "DoubleSpec[~P2, ~P, ~T]", DoubleSpec[[int], [str], bool]: "DoubleSpec[[int], [str], bool]", DoubleSpec[[int, int], [str, str], bool]: "DoubleSpec[[int, int], [str, str], bool]", - TsP[*Ts, P]: "TsP[typing.Unpack[Ts], ~P]", + TsP[*Ts, P]: "TsP[typing.Unpack[~Ts], ~P]", TsP[int, str, list[int], []]: "TsP[int, str, list[int], []]", TsP[int, [str, list[int]]]: "TsP[int, [str, list[int]]]", @@ -5821,6 +5986,7 @@ def test_subclass_special_form(self): Final[int], Literal[1, 2], Concatenate[int, ParamSpec("P")], + TypeForm[int], TypeGuard[int], TypeIs[range], ): @@ -5887,6 +6053,22 @@ class A: with self.assertRaises(TypeError): a[int] + def test_parameter_added_after_parameters_cached(self): + # gh-155752: GenericAlias parameters are cached before substitution, so + # an argument can gain __typing_subst__ after the tuple is calculated. + class Parameter: + pass + + first = Parameter() + first.__typing_subst__ = lambda value: value + late = Parameter() + alias = types.GenericAlias(dict, (first, late)) + self.assertEqual(alias.__parameters__, (first,)) + late.__typing_subst__ = lambda value: value + + with self.assertRaisesRegex(TypeError, "not found in __parameters__"): + alias[0] + def test_return_non_tuple_while_unpacking(self): # GH-138497: GenericAlias objects didn't ensure that __typing_subst__ actually # returned a tuple @@ -6380,62 +6562,8 @@ class F: for clazz in [C, D, E, F]: self.assertEqual(get_type_hints(clazz), expected_result) - def test_meta_no_type_check(self): - depr_msg = ( - "'typing.no_type_check_decorator' is deprecated " - "and slated for removal in Python 3.15" - ) - with self.assertWarnsRegex(DeprecationWarning, depr_msg): - @no_type_check_decorator - def magic_decorator(func): - return func - - self.assertEqual(magic_decorator.__name__, 'magic_decorator') - - @magic_decorator - def foo(a: 'whatevers') -> {}: - pass - - @magic_decorator - class C: - def foo(a: 'whatevers') -> {}: - pass - - self.assertEqual(foo.__name__, 'foo') - th = get_type_hints(foo) - self.assertEqual(th, {}) - cth = get_type_hints(C.foo) - self.assertEqual(cth, {}) - ith = get_type_hints(C().foo) - self.assertEqual(ith, {}) - class InternalsTests(BaseTestCase): - def test_deprecation_for_no_type_params_passed_to__evaluate(self): - with self.assertWarnsRegex( - DeprecationWarning, - ( - "Failing to pass a value to the 'type_params' parameter " - "of 'typing._eval_type' is deprecated" - ) - ) as cm: - self.assertEqual(typing._eval_type(list["int"], globals(), {}), list[int]) - - self.assertEqual(cm.filename, __file__) - - f = ForwardRef("int") - - with self.assertWarnsRegex( - DeprecationWarning, - ( - "Failing to pass a value to the 'type_params' parameter " - "of 'typing.ForwardRef._evaluate' is deprecated" - ) - ) as cm: - self.assertIs(f._evaluate(globals(), {}, recursive_guard=frozenset()), int) - - self.assertEqual(cm.filename, __file__) - def test_collect_parameters(self): typing = import_helper.import_fresh_module("typing") with self.assertWarnsRegex( @@ -7236,6 +7364,24 @@ def add_right(self, node: 'Node[T]' = None): right_hints = get_type_hints(t.add_right, globals(), locals()) self.assertEqual(right_hints['node'], Node[T]) + def test_get_type_hints_preserve_generic_alias_subclasses(self): + # https://github.com/python/cpython/issues/130870 + # A real world example of this is `collections.abc.Callable`. When parameterized, + # the result is a subclass of `types.GenericAlias`. + class MyAlias(types.GenericAlias): + pass + + class MyClass: + def __class_getitem__(cls, args): + return MyAlias(cls, args) + + # Using a forward reference is important, otherwise it works as expected. + # `y` tests that the `GenericAlias` subclass is preserved when stripping `Annotated`. + def func(x: MyClass['int'], y: MyClass[Annotated[int, ...]]): ... + + assert isinstance(get_type_hints(func)['x'], MyAlias) + assert isinstance(get_type_hints(func)['y'], MyAlias) + def test_stringified_typeddict(self): ns = run_code( """ @@ -7249,6 +7395,13 @@ class TD[UniqueT](TypedDict): self.assertEqual(TD.__annotations__, {'a': EqualToForwardRef('UniqueT', owner=TD, module=TD.__module__)}) self.assertEqual(get_type_hints(TD), {'a': TD.__type_params__[0]}) + def test_get_type_hints_order(self): + """Ensure that the order of function annotations matches the order they're defined""" + def f(positional: int, /, normal: str, *args: bytes, kwarg: list, **kwargs: bool) -> tuple: + pass + + self.assertEqual(list(gth(f)), ["positional", "normal", "args", "kwarg", "kwargs", "return"]) + class GetUtilitiesTestCase(TestCase): def test_get_origin(self): @@ -7339,6 +7492,7 @@ class C(Generic[T]): pass self.assertEqual(get_args(Required[int]), (int,)) self.assertEqual(get_args(NotRequired[int]), (int,)) self.assertEqual(get_args(TypeAlias), ()) + self.assertEqual(get_args(TypeForm[int]), (int,)) self.assertEqual(get_args(TypeGuard[int]), (int,)) self.assertEqual(get_args(TypeIs[range]), (range,)) Ts = TypeVarTuple('Ts') @@ -7576,14 +7730,23 @@ def test_mutablesequence(self): self.assertNotIsInstance((), typing.MutableSequence) def test_bytestring(self): + previous_typing_module = sys.modules.pop("typing", None) + self.addCleanup(sys.modules.__setitem__, "typing", previous_typing_module) + + with self.assertWarns(DeprecationWarning): + from typing import ByteString with self.assertWarns(DeprecationWarning): - self.assertIsInstance(b'', typing.ByteString) + self.assertIsInstance(b'', ByteString) with self.assertWarns(DeprecationWarning): - self.assertIsInstance(bytearray(b''), typing.ByteString) + self.assertIsInstance(bytearray(b''), ByteString) with self.assertWarns(DeprecationWarning): - class Foo(typing.ByteString): ... + self.assertIsSubclass(bytes, ByteString) with self.assertWarns(DeprecationWarning): - class Bar(typing.ByteString, typing.Awaitable): ... + self.assertIsSubclass(bytearray, ByteString) + with self.assertWarns(DeprecationWarning): + class Foo(ByteString): ... + with self.assertWarns(DeprecationWarning): + class Bar(ByteString, typing.Awaitable): ... def test_list(self): self.assertIsSubclass(list, typing.List) @@ -8326,78 +8489,13 @@ class Group(NamedTuple): self.assertIs(type(a), Group) self.assertEqual(a, (1, [2])) - def test_namedtuple_keyword_usage(self): - with self.assertWarnsRegex( - DeprecationWarning, - "Creating NamedTuple classes using keyword arguments is deprecated" - ): - LocalEmployee = NamedTuple("LocalEmployee", name=str, age=int) - - nick = LocalEmployee('Nick', 25) - self.assertIsInstance(nick, tuple) - self.assertEqual(nick.name, 'Nick') - self.assertEqual(LocalEmployee.__name__, 'LocalEmployee') - self.assertEqual(LocalEmployee._fields, ('name', 'age')) - self.assertEqual(LocalEmployee.__annotations__, dict(name=str, age=int)) - - with self.assertRaisesRegex( - TypeError, - "Either list of fields or keywords can be provided to NamedTuple, not both" - ): - NamedTuple('Name', [('x', int)], y=str) - - with self.assertRaisesRegex( - TypeError, - "Either list of fields or keywords can be provided to NamedTuple, not both" - ): - NamedTuple('Name', [], y=str) - - with self.assertRaisesRegex( - TypeError, - ( - r"Cannot pass `None` as the 'fields' parameter " - r"and also specify fields using keyword arguments" - ) - ): - NamedTuple('Name', None, x=int) - - def test_namedtuple_special_keyword_names(self): - with self.assertWarnsRegex( - DeprecationWarning, - "Creating NamedTuple classes using keyword arguments is deprecated" - ): - NT = NamedTuple("NT", cls=type, self=object, typename=str, fields=list) - - self.assertEqual(NT.__name__, 'NT') - self.assertEqual(NT._fields, ('cls', 'self', 'typename', 'fields')) - a = NT(cls=str, self=42, typename='foo', fields=[('bar', tuple)]) - self.assertEqual(a.cls, str) - self.assertEqual(a.self, 42) - self.assertEqual(a.typename, 'foo') - self.assertEqual(a.fields, [('bar', tuple)]) - def test_empty_namedtuple(self): - expected_warning = re.escape( - "Failing to pass a value for the 'fields' parameter is deprecated " - "and will be disallowed in Python 3.15. " - "To create a NamedTuple class with 0 fields " - "using the functional syntax, " - "pass an empty list, e.g. `NT1 = NamedTuple('NT1', [])`." - ) - with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"): - NT1 = NamedTuple('NT1') - - expected_warning = re.escape( - "Passing `None` as the 'fields' parameter is deprecated " - "and will be disallowed in Python 3.15. " - "To create a NamedTuple class with 0 fields " - "using the functional syntax, " - "pass an empty list, e.g. `NT2 = NamedTuple('NT2', [])`." - ) - with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"): - NT2 = NamedTuple('NT2', None) + with self.assertRaisesRegex(TypeError, "missing.*required.*argument"): + BAD = NamedTuple('BAD') - NT3 = NamedTuple('NT2', []) + NT1 = NamedTuple('NT1', {}) + NT2 = NamedTuple('NT2', ()) + NT3 = NamedTuple('NT3', []) class CNT(NamedTuple): pass # empty body @@ -8412,16 +8510,18 @@ class CNT(NamedTuple): def test_namedtuple_errors(self): with self.assertRaises(TypeError): NamedTuple.__new__() + with self.assertRaisesRegex(TypeError, "object is not iterable"): + NamedTuple('Name', None) with self.assertRaisesRegex( TypeError, - "missing 1 required positional argument" + "missing 2 required positional arguments" ): NamedTuple() with self.assertRaisesRegex( TypeError, - "takes from 1 to 2 positional arguments but 3 were given" + "takes 2 positional arguments but 3 were given" ): NamedTuple('Emp', [('name', str)], None) @@ -8433,10 +8533,22 @@ def test_namedtuple_errors(self): with self.assertRaisesRegex( TypeError, - "missing 1 required positional argument: 'typename'" + "got some positional-only arguments passed as keyword arguments" ): NamedTuple(typename='Emp', name=str, id=int) + with self.assertRaisesRegex( + TypeError, + "got an unexpected keyword argument" + ): + NamedTuple('Name', [('x', int)], y=str) + + with self.assertRaisesRegex( + TypeError, + "got an unexpected keyword argument" + ): + NamedTuple('Name', [], y=str) + def test_copy_and_pickle(self): global Emp # pickle wants to reference the class by name Emp = NamedTuple('Emp', [('name', str), ('cool', int)]) @@ -8567,6 +8679,15 @@ class ThisWontWorkEither(NamedTuple): def name(self): return __class__.__name__ + def test_named_tuple_non_sequence_input(self): + field_names = ["x", "y"] + field_values = [int, int] + Point = NamedTuple("Point", zip(field_names, field_values)) + p = Point(1, 2) + self.assertEqual(p.x, 1) + self.assertEqual(p.y, 2) + self.assertEqual(repr(p),"Point(x=1, y=2)") + class TypedDictTests(BaseTestCase): def test_basics_functional_syntax(self): @@ -8937,6 +9058,32 @@ class ChildWithInlineAndOptional(Untotal, Inline): class Wrong(*bases): pass + def test_closed_values(self): + class Implicit(TypedDict): ... + class ExplicitTrue(TypedDict, closed=True): ... + class ExplicitFalse(TypedDict, closed=False): ... + + self.assertIsNone(Implicit.__closed__) + self.assertIs(ExplicitTrue.__closed__, True) + self.assertIs(ExplicitFalse.__closed__, False) + + def test_extra_items_class_arg(self): + class TD(TypedDict, extra_items=int): + a: str + + self.assertIs(TD.__extra_items__, int) + self.assertEqual(TD.__annotations__, {'a': str}) + self.assertEqual(TD.__required_keys__, frozenset({'a'})) + self.assertEqual(TD.__optional_keys__, frozenset()) + + class NoExtra(TypedDict): + a: str + + self.assertIs(NoExtra.__extra_items__, NoExtraItems) + self.assertEqual(NoExtra.__annotations__, {'a': str}) + self.assertEqual(NoExtra.__required_keys__, frozenset({'a'})) + self.assertEqual(NoExtra.__optional_keys__, frozenset()) + def test_is_typeddict(self): self.assertIs(is_typeddict(Point2D), True) self.assertIs(is_typeddict(Union[str, int]), False) @@ -9180,39 +9327,27 @@ class MultipleGenericBases(GenericParent[int], GenericParent[float]): self.assertEqual(CallTypedDict.__orig_bases__, (TypedDict,)) def test_zero_fields_typeddicts(self): - T1 = TypedDict("T1", {}) + T1a = TypedDict("T1a", {}) + T1b = TypedDict("T1b", []) + T1c = TypedDict("T1c", ()) class T2(TypedDict): pass class T3[tvar](TypedDict): pass S = TypeVar("S") class T4(TypedDict, Generic[S]): pass - expected_warning = re.escape( - "Failing to pass a value for the 'fields' parameter is deprecated " - "and will be disallowed in Python 3.15. " - "To create a TypedDict class with 0 fields " - "using the functional syntax, " - "pass an empty dictionary, e.g. `T5 = TypedDict('T5', {})`." - ) - with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"): - T5 = TypedDict('T5') - - expected_warning = re.escape( - "Passing `None` as the 'fields' parameter is deprecated " - "and will be disallowed in Python 3.15. " - "To create a TypedDict class with 0 fields " - "using the functional syntax, " - "pass an empty dictionary, e.g. `T6 = TypedDict('T6', {})`." - ) - with self.assertWarnsRegex(DeprecationWarning, fr"^{expected_warning}$"): - T6 = TypedDict('T6', None) - - for klass in T1, T2, T3, T4, T5, T6: + for klass in T1a, T1b, T1c, T2, T3, T4: with self.subTest(klass=klass.__name__): self.assertEqual(klass.__annotations__, {}) self.assertEqual(klass.__required_keys__, set()) self.assertEqual(klass.__optional_keys__, set()) self.assertIsInstance(klass(), dict) + def test_errors(self): + with self.assertRaisesRegex(TypeError, "missing 1 required.*argument"): + TypedDict('TD') + with self.assertRaisesRegex(TypeError, "object is not iterable"): + TypedDict('TD', None) + def test_readonly_inheritance(self): class Base1(TypedDict): a: ReadOnly[int] @@ -9276,6 +9411,71 @@ class AllTheThings(TypedDict): }, ) + def test_closed_inheritance(self): + class Base(TypedDict, extra_items=ReadOnly[Union[str, None]]): + a: int + + self.assertEqual(Base.__required_keys__, frozenset({"a"})) + self.assertEqual(Base.__optional_keys__, frozenset({})) + self.assertEqual(Base.__readonly_keys__, frozenset({})) + self.assertEqual(Base.__mutable_keys__, frozenset({"a"})) + self.assertEqual(Base.__annotations__, {"a": int}) + self.assertEqual(Base.__extra_items__, ReadOnly[Union[str, None]]) + self.assertIsNone(Base.__closed__) + + class Child(Base, extra_items=int): + a: str + + self.assertEqual(Child.__required_keys__, frozenset({'a'})) + self.assertEqual(Child.__optional_keys__, frozenset({})) + self.assertEqual(Child.__readonly_keys__, frozenset({})) + self.assertEqual(Child.__mutable_keys__, frozenset({'a'})) + self.assertEqual(Child.__annotations__, {"a": str}) + self.assertIs(Child.__extra_items__, int) + self.assertIsNone(Child.__closed__) + + class GrandChild(Child, closed=True): + a: float + + self.assertEqual(GrandChild.__required_keys__, frozenset({'a'})) + self.assertEqual(GrandChild.__optional_keys__, frozenset({})) + self.assertEqual(GrandChild.__readonly_keys__, frozenset({})) + self.assertEqual(GrandChild.__mutable_keys__, frozenset({'a'})) + self.assertEqual(GrandChild.__annotations__, {"a": float}) + self.assertIs(GrandChild.__extra_items__, NoExtraItems) + self.assertIs(GrandChild.__closed__, True) + + class GrandGrandChild(GrandChild): + ... + self.assertEqual(GrandGrandChild.__required_keys__, frozenset({'a'})) + self.assertEqual(GrandGrandChild.__optional_keys__, frozenset({})) + self.assertEqual(GrandGrandChild.__readonly_keys__, frozenset({})) + self.assertEqual(GrandGrandChild.__mutable_keys__, frozenset({'a'})) + self.assertEqual(GrandGrandChild.__annotations__, {"a": float}) + self.assertIs(GrandGrandChild.__extra_items__, NoExtraItems) + self.assertIsNone(GrandGrandChild.__closed__) + + def test_implicit_extra_items(self): + class Base(TypedDict): + a: int + + self.assertIs(Base.__extra_items__, NoExtraItems) + self.assertIsNone(Base.__closed__) + + class ChildA(Base, closed=True): + ... + + self.assertEqual(ChildA.__extra_items__, NoExtraItems) + self.assertIs(ChildA.__closed__, True) + + def test_cannot_combine_closed_and_extra_items(self): + with self.assertRaisesRegex( + TypeError, + "Cannot combine closed=True and extra_items" + ): + class TD(TypedDict, closed=True, extra_items=range): + x: str + def test_annotations(self): # _type_check is applied with self.assertRaisesRegex(TypeError, "Plain typing.Final is not valid as type argument"): @@ -9505,6 +9705,12 @@ class A(typing.Match): class B(typing.Pattern): pass + def test_typed_dict_signature(self): + self.assertListEqual( + list(inspect.signature(TypedDict).parameters), + ['typename', 'fields', 'total', 'closed', 'extra_items'] + ) + class AnnotatedTests(BaseTestCase): @@ -10079,6 +10285,17 @@ def test_args_kwargs(self): self.assertEqual(repr(P.args), "P.args") self.assertEqual(repr(P.kwargs), "P.kwargs") + def test_args_kwargs_weakrefs(self): + P = ParamSpec('P') + for attr_name in ('args', 'kwargs'): + with self.subTest(attr_name=attr_name): + callback_fired = [] + attr = getattr(P, attr_name) + ref = weakref.ref(attr, lambda _: callback_fired.append(True)) + del attr + self.assertEqual(callback_fired, [True]) + self.assertIsNone(ref()) + def test_stringized(self): P = ParamSpec('P') class C(Generic[P]): @@ -10380,6 +10597,17 @@ def test_paramspec_in_nested_generics(self): self.assertEqual(G2[[int, str], float], list[C]) self.assertEqual(G3[[int, str], float], list[C] | int) + def test_paramspec_bound(self): + P = ParamSpec('P', bound=[int, str]) + self.assertEqual(P.__bound__, [int, str]) + P2 = ParamSpec('P2', bound=(int, str)) + self.assertEqual(P2.__bound__, (int, str)) + obj = object() + P3 = ParamSpec('P3', bound=obj) + self.assertIs(P3.__bound__, obj) + P4 = ParamSpec('P4') + self.assertIs(P4.__bound__, None) + def test_paramspec_gets_copied(self): # bpo-46581 P = ParamSpec('P') @@ -10587,6 +10815,72 @@ def test_no_isinstance(self): issubclass(int, TypeIs) +class TypeFormTests(BaseTestCase): + def test_basics(self): + TypeForm[int] # OK + self.assertEqual(TypeForm[int], TypeForm[int]) + + def foo(arg) -> TypeForm[int]: ... + self.assertEqual(gth(foo), {'return': TypeForm[int]}) + + with self.assertRaises(TypeError): + TypeForm[int, str] + + def test_repr(self): + self.assertEqual(repr(TypeForm), 'typing.TypeForm') + cv = TypeForm[int] + self.assertEqual(repr(cv), 'typing.TypeForm[int]') + cv = TypeForm[Employee] + self.assertEqual(repr(cv), 'typing.TypeForm[%s.Employee]' % __name__) + cv = TypeForm[tuple[int]] + self.assertEqual(repr(cv), 'typing.TypeForm[tuple[int]]') + + def test_cannot_subclass(self): + with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE): + class C(type(TypeForm)): + pass + with self.assertRaisesRegex(TypeError, CANNOT_SUBCLASS_TYPE): + class D(type(TypeForm[int])): + pass + with self.assertRaisesRegex(TypeError, + r'Cannot subclass typing\.TypeForm'): + class E(TypeForm): + pass + with self.assertRaisesRegex(TypeError, + r'Cannot subclass typing\.TypeForm\[int\]'): + class F(TypeForm[int]): + pass + + def test_call(self): + objs = [ + 1, + "int", + int, + tuple[int, str], + Tuple[int, str], + ] + for obj in objs: + with self.subTest(obj=obj): + self.assertIs(TypeForm(obj), obj) + + with self.assertRaises(TypeError): + TypeForm() + with self.assertRaises(TypeError): + TypeForm("too", "many") + + def test_cannot_init_type(self): + with self.assertRaises(TypeError): + type(TypeForm)() + with self.assertRaises(TypeError): + type(TypeForm[Optional[int]])() + + def test_no_isinstance(self): + with self.assertRaises(TypeError): + isinstance(1, TypeForm[int]) + with self.assertRaises(TypeError): + issubclass(int, TypeForm) + + SpecialAttrsP = typing.ParamSpec('SpecialAttrsP') SpecialAttrsT = typing.TypeVar('SpecialAttrsT', int, float, complex) @@ -10594,6 +10888,10 @@ def test_no_isinstance(self): class SpecialAttrsTests(BaseTestCase): def test_special_attrs(self): + with warnings.catch_warnings( + action='ignore', category=DeprecationWarning + ): + typing_ByteString = typing.ByteString cls_to_check = { # ABC classes typing.AbstractSet: 'AbstractSet', @@ -10602,7 +10900,7 @@ def test_special_attrs(self): typing.AsyncIterable: 'AsyncIterable', typing.AsyncIterator: 'AsyncIterator', typing.Awaitable: 'Awaitable', - typing.ByteString: 'ByteString', + typing_ByteString: 'ByteString', typing.Callable: 'Callable', typing.ChainMap: 'ChainMap', typing.Collection: 'Collection', @@ -10684,6 +10982,7 @@ def test_special_attrs(self): typing.Never: 'Never', typing.Optional: 'Optional', typing.TypeAlias: 'TypeAlias', + typing.TypeForm: 'TypeForm', typing.TypeGuard: 'TypeGuard', typing.TypeIs: 'TypeIs', typing.TypeVar: 'TypeVar', @@ -10698,6 +10997,7 @@ def test_special_attrs(self): typing.Literal[1, 2]: 'Literal', typing.Literal[True, 2]: 'Literal', typing.Optional[Any]: 'Union', + typing.TypeForm[Any]: 'TypeForm', typing.TypeGuard[Any]: 'TypeGuard', typing.TypeIs[Any]: 'TypeIs', typing.Union[Any]: 'Any', @@ -10780,6 +11080,18 @@ def bar(self): self.assertNotIn('__magic__', dir_items) +class DisjointBaseTests(BaseTestCase): + def test_disjoint_base_unmodified(self): + class C: ... + self.assertIs(C, disjoint_base(C)) + + def test_dunder_disjoint_base(self): + @disjoint_base + class C: ... + + self.assertIs(C.__disjoint_base__, True) + + class RevealTypeTests(BaseTestCase): def test_reveal_type(self): obj = object() @@ -10959,7 +11271,8 @@ def test_all_exported_names(self): # there's a few types and metaclasses that aren't exported not k.endswith(('Meta', '_contra', '_co')) and not k.upper() == k and - # but export all things that have __module__ == 'typing' + k not in {"ByteString"} and + # but export all other things that have __module__ == 'typing' getattr(v, '__module__', None) == typing.__name__ ) } diff --git a/Lib/test/test_ucn.py b/Lib/test/test_ucn.py index 2a4496769cf..e50a8535359 100644 --- a/Lib/test/test_ucn.py +++ b/Lib/test/test_ucn.py @@ -114,10 +114,10 @@ def test_cjk_unified_ideographs(self): @unittest.expectedFailure # TODO: RUSTPYTHON; SyntaxError: got unexpected unicode def test_tangut_ideographs(self): self.checkletter("TANGUT IDEOGRAPH-17000", "\U00017000") - self.checkletter("TANGUT IDEOGRAPH-187F7", "\U000187f7") + self.checkletter("TANGUT IDEOGRAPH-187FF", "\U000187ff") self.checkletter("TANGUT IDEOGRAPH-18D00", "\U00018D00") - self.checkletter("TANGUT IDEOGRAPH-18D08", "\U00018d08") - self.checkletter("tangut ideograph-18d08", "\U00018d08") + self.checkletter("TANGUT IDEOGRAPH-18D1E", "\U00018d1e") + self.checkletter("tangut ideograph-18d1e", "\U00018d1e") def test_egyptian_hieroglyphs(self): self.checkletter("EGYPTIAN HIEROGLYPH-13460", "\U00013460") diff --git a/Lib/test/test_unicode_identifiers.py b/Lib/test/test_unicode_identifiers.py index 27749a0805c..3680072d643 100644 --- a/Lib/test/test_unicode_identifiers.py +++ b/Lib/test/test_unicode_identifiers.py @@ -17,7 +17,6 @@ def test_non_bmp_normalized(self): 𝔘𝔫𝔦𝔠𝔬𝔡𝔢 = 1 self.assertIn("Unicode", dir()) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_invalid(self): try: from test.tokenizedata import badsyntax_3131 # noqa: F401 diff --git a/Lib/test/test_unicodedata.py b/Lib/test/test_unicodedata.py index aeb1835f6cc..611fe3bcae8 100644 --- a/Lib/test/test_unicodedata.py +++ b/Lib/test/test_unicodedata.py @@ -107,7 +107,6 @@ def test_method_checksum(self): class BaseUnicodeFunctionsTest: - @unittest.skip # TODO: RUSTPYTHON; AssertionError: '7bda75e48a961a01ab328358980cefc5c0a1666d' != '68cd01e2c680b851c1fcab012efb5635' def test_function_checksum(self): db = self.db data = [] @@ -199,7 +198,6 @@ def test_no_names_in_pua(self): char = chr(i) self.assertRaises(ValueError, self.db.name, char) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: KeyError not raised by lookup def test_lookup_nonexistant(self): # just make sure that lookup can fail for nonexistent in [ @@ -360,7 +358,6 @@ def test_bidirectional_unassigned(self): self.assertEqual(self.db.bidirectional('\U0001FFFE'), '' if self.old else 'BN') self.assertEqual(self.db.bidirectional('\U00010D01'), '' if self.old else 'AL') - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: ' 03A3 != '' def test_decomposition(self): self.assertEqual(self.db.decomposition('\uFFFE'),'') self.assertEqual(self.db.decomposition('\u00bc'), ' 0031 2044 0034') @@ -700,7 +697,6 @@ def test_east_asian_width(self): # New in 17.0.0 self.assertEqual(eaw('\U00016FF2'), 'N' if self.old else 'W') - @unittest.skip # TODO: RUSTPYTHON; AssertionError: 'N' != 'W' (passed on latest, fails on 3.2) def test_east_asian_width_unassigned(self): eaw = self.db.east_asian_width # unassigned @@ -769,7 +765,6 @@ def parse_cp(s): for cp in range(0, sys.maxunicode + 1): self.assertEqual(self.db.name(chr(cp), None), names_ref.get(cp)) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'isxidstart' def test_isxidstart(self): self.assertTrue(self.db.isxidstart('S')) self.assertTrue(self.db.isxidstart('\u0AD0')) # GUJARATI OM @@ -783,7 +778,6 @@ def test_isxidstart(self): self.assertRaises(TypeError, self.db.isxidstart) self.assertRaises(TypeError, self.db.isxidstart, 'xx') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'isxidcontinue' def test_isxidcontinue(self): self.assertTrue(self.db.isxidcontinue('S')) self.assertTrue(self.db.isxidcontinue('_')) @@ -798,7 +792,6 @@ def test_isxidcontinue(self): self.assertRaises(TypeError, self.db.isxidcontinue) self.assertRaises(TypeError, self.db.isxidcontinue, 'xx') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'grapheme_cluster_break' def test_grapheme_cluster_break(self): gcb = self.db.grapheme_cluster_break self.assertEqual(gcb(' '), 'Other') @@ -896,7 +889,6 @@ def test_grapheme_cluster_break(self): self.assertRaises(TypeError, gcb, '') self.assertRaises(TypeError, gcb, 'xx') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'indic_conjunct_break' def test_indic_conjunct_break(self): incb = self.db.indic_conjunct_break self.assertEqual(incb(' '), 'None') @@ -925,7 +917,6 @@ def test_indic_conjunct_break(self): self.assertRaises(TypeError, incb, '') self.assertRaises(TypeError, incb, 'xx') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'extended_pictographic' def test_extended_pictographic(self): ext_pict = self.db.extended_pictographic self.assertIs(ext_pict(' '), False) @@ -946,7 +937,6 @@ def test_extended_pictographic(self): self.assertRaises(TypeError, ext_pict, '') self.assertRaises(TypeError, ext_pict, 'xx') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'iter_graphemes' def test_grapheme_break(self): def graphemes(*args): return list(map(str, self.db.iter_graphemes(*args))) @@ -1017,7 +1007,6 @@ def graphemes(*args): 'a\U0001F1FA\U0001F1E6\U0001F1FA\U0001F1F3'), ['a', '\U0001F1FA\U0001F1E6', '\U0001F1FA\U0001F1F3']) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'block' def test_block(self): self.assertEqual(self.db.block('\u0000'), 'Basic Latin') self.assertEqual(self.db.block('\u0041'), 'Basic Latin') @@ -1102,7 +1091,6 @@ def test_block(self): self.assertEqual(self.db.block('\U00100000'), 'Supplementary Private Use Area-B') self.assertEqual(self.db.block('\U0010FFFF'), 'Supplementary Private Use Area-B') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'block' def test_block_invalid_input(self): self.assertRaises(TypeError, self.db.block) self.assertRaises(TypeError, self.db.block, b'x') @@ -1110,22 +1098,6 @@ def test_block_invalid_input(self): self.assertRaises(TypeError, self.db.block, '') self.assertRaises(TypeError, self.db.block, 'xx') - @unittest.expectedFailure # TODO: RUSTPYTHON; + N - def test_east_asian_width_9_0_changes(self): - return super().test_east_asian_width_9_0_changes() - - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: 'D4CC 11B6' != '1111 1171 11B6' - def test_decomposition(self): - return super().test_decomposition() - - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: KeyError not raised by lookup - def test_lookup_nonexistant(self): - return super().test_lookup_nonexistant() - - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'digit' - def test_function_checksum(self): - return super().test_function_checksum() - class Unicode_3_2_0_FunctionsTest(unittest.TestCase, BaseUnicodeFunctionsTest): db = unicodedata.ucd_3_2_0 @@ -1134,10 +1106,6 @@ class Unicode_3_2_0_FunctionsTest(unittest.TestCase, BaseUnicodeFunctionsTest): if quicktest else '68cd01e2c680b851c1fcab012efb5635b2229c2b') - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_normalization(self): - return super().test_normalization() - @unittest.expectedSuccess # TODO: RUSTPYTHON def test_combining(self): return super().test_combining() @@ -1169,7 +1137,6 @@ def test_failed_import_during_compiling(self): "(can't load unicodedata module)" self.assertIn(error, result.err.decode("ascii")) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError Process return code is 1 def test_unicodedata_unload_reload(self): # gh-149449: dropping unicodedata and running gc must not leave the # cached _ucnhash_CAPI pointer dangling. @@ -1262,7 +1229,6 @@ def test_linebreak_7643(self): self.assertEqual(len(lines), 1, r"%a should not be a linebreak" % c) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'iter_graphemes' def test_segment_object(self): segments = list(unicodedata.iter_graphemes('spa\u0300m')) self.assertEqual(len(segments), 4, segments) @@ -1290,7 +1256,6 @@ def test_normalization(self): with testdata: self.run_normalization_tests(testdata, unicodedata) - @unittest.expectedFailure # TODO: RUSTPYTHON; AssertionError: False is not true : 2F868;2136A;2136A;2136A;2136A @requires_resource('cpu') def test_normalization_3_2_0(self): testdatafile = findfile('NormalizationTest-3.2.0.txt') @@ -1384,7 +1349,6 @@ class MyStr(str): class GraphemeBreakTest(unittest.TestCase): @requires_resource('network') - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError module 'unicodedata' has no attribute 'iter_graphemes' def test_grapheme_break(self): TESTDATAFILE = "GraphemeBreakTest.txt" testdata = download_test_data_file(TESTDATAFILE) @@ -1423,7 +1387,6 @@ def run_grapheme_break_tests(self, testdata): self.assertEqual([x.start for x in result], breaks[i:-1], comment) self.assertEqual([x.end for x in result], breaks[i+1:], comment) - @unittest.expectedFailure # TODO: RUSTPYTHON; AttributeError: module 'unicodedata' has no attribute 'iter_graphemes' def test_reference_loops(self): # Test that reference loops involving GraphemeBreakIterator or # Segment can be broken by the garbage collector. diff --git a/Lib/test/test_unittest/test_assertions.py b/Lib/test/test_unittest/test_assertions.py index 1dec947ea76..df95e558949 100644 --- a/Lib/test/test_unittest/test_assertions.py +++ b/Lib/test/test_unittest/test_assertions.py @@ -406,11 +406,12 @@ def testAssertWarnsRegex(self): # test warning raised but with wrong message def raise_wrong_message(): warnings.warn('foo') - self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'regex'), - raise_wrong_message, - ['^"regex" does not match "foo"$', '^oops$', - '^"regex" does not match "foo"$', - '^"regex" does not match "foo" : oops$']) + with self.assertWarnsRegex(UserWarning, 'foo'): + self.assertMessagesCM('assertWarnsRegex', (UserWarning, 'regex'), + raise_wrong_message, + ['^"regex" does not match "foo"$', '^oops$', + '^"regex" does not match "foo"$', + '^"regex" does not match "foo" : oops$']) if __name__ == "__main__": diff --git a/Lib/test/test_unittest/test_case.py b/Lib/test/test_unittest/test_case.py index d66cab146af..83b42918e1e 100644 --- a/Lib/test/test_unittest/test_case.py +++ b/Lib/test/test_unittest/test_case.py @@ -1631,11 +1631,11 @@ def testAssertRaisesRegexNoExceptionType(self): self.assertRaisesRegex((ValueError, object), 'expect') def testAssertWarnsCallable(self): - def _runtime_warn(): - warnings.warn("foo", RuntimeWarning) + def _runtime_warn(categories=(RuntimeWarning,)): + for category in categories: + warnings.warn("foo", category) # Success when the right warning is triggered, even several times - self.assertWarns(RuntimeWarning, _runtime_warn) - self.assertWarns(RuntimeWarning, _runtime_warn) + self.assertWarns(RuntimeWarning, _runtime_warn, (RuntimeWarning, RuntimeWarning)) # A tuple of warning classes is accepted self.assertWarns((DeprecationWarning, RuntimeWarning), _runtime_warn) # *args and **kwargs also work @@ -1648,22 +1648,35 @@ def _runtime_warn(): with self.assertRaises(TypeError): self.assertWarns(RuntimeWarning, None) # Failure when another warning is triggered - with warnings.catch_warnings(): + with warnings.catch_warnings(record=True) as log: # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): - self.assertWarns(DeprecationWarning, _runtime_warn) + self.assertWarns(DeprecationWarning, _runtime_warn, + (RuntimeWarning, RuntimeWarning)) + self.assertEqual(len(log), 1, log) + self.assertIsInstance(log[0].message, RuntimeWarning) # Filters for other warnings are not modified with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises(RuntimeWarning): self.assertWarns(DeprecationWarning, _runtime_warn) + # Warnings that do not match the category are not swallowed. + with self.assertWarns(RuntimeWarning): + with self.assertRaises(self.failureException): + self.assertWarns(DeprecationWarning, _runtime_warn) + with self.assertWarns(RuntimeWarning): + self.assertWarns(DeprecationWarning, _runtime_warn, + (RuntimeWarning, DeprecationWarning)) + with self.assertWarns(RuntimeWarning): + self.assertWarns(DeprecationWarning, _runtime_warn, + (DeprecationWarning, RuntimeWarning)) def testAssertWarnsContext(self): # Believe it or not, it is preferable to duplicate all tests above, # to make sure the __warningregistry__ $@ is circumvented correctly. - def _runtime_warn(): - warnings.warn("foo", RuntimeWarning) + def _runtime_warn(category=RuntimeWarning): + warnings.warn("foo", category) _runtime_warn_lineno = inspect.getsourcelines(_runtime_warn)[1] with self.assertWarns(RuntimeWarning) as cm: _runtime_warn() @@ -1694,18 +1707,58 @@ def _runtime_warn(): with self.assertWarns(RuntimeWarning, foobar=42): pass # Failure when another warning is triggered - with warnings.catch_warnings(): + with warnings.catch_warnings(record=True) as log: # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): with self.assertWarns(DeprecationWarning): _runtime_warn() + _runtime_warn() + self.assertEqual(len(log), 1, log) + self.assertIsInstance(log[0].message, RuntimeWarning) + with warnings.catch_warnings(record=True) as log: + # Force default filter (in case tests are run with -We) + warnings.simplefilter("error", RuntimeWarning) + warnings.filterwarnings("default", category=RuntimeWarning, + module=__name__) + with self.assertRaises(self.failureException): + with self.assertWarns(DeprecationWarning): + _runtime_warn() + _runtime_warn() + self.assertEqual(len(log), 1, log) + self.assertIsInstance(log[0].message, RuntimeWarning) # Filters for other warnings are not modified with warnings.catch_warnings(): warnings.simplefilter("error", RuntimeWarning) with self.assertRaises(RuntimeWarning): with self.assertWarns(DeprecationWarning): _runtime_warn() + # Warnings that do not match the category are not swallowed. + with self.assertWarns(RuntimeWarning): + with self.assertRaises(self.failureException): + with self.assertWarns(DeprecationWarning): + _runtime_warn() + with self.assertWarns(RuntimeWarning): + with self.assertWarns(DeprecationWarning): + _runtime_warn() + _runtime_warn(DeprecationWarning) + with self.assertWarns(RuntimeWarning): + with self.assertWarns(DeprecationWarning): + _runtime_warn(DeprecationWarning) + _runtime_warn() + # Filters by module name work for other warnings. + with warnings.catch_warnings(record=True) as log: + warnings.filterwarnings("error", category=RuntimeWarning) + warnings.filterwarnings("default", category=RuntimeWarning, + module=re.escape(__name__)) + warnings.filterwarnings("error", category=RuntimeWarning, + module='test_case') + with self.assertWarns(DeprecationWarning): + _runtime_warn(DeprecationWarning) + _runtime_warn() + _runtime_warn() + self.assertEqual(len(log), 1, log) + self.assertIsInstance(log[0].message, RuntimeWarning) def testAssertWarnsNoExceptionType(self): with self.assertRaises(TypeError): @@ -1722,8 +1775,9 @@ def testAssertWarnsNoExceptionType(self): self.assertWarns((UserWarning, Exception)) def testAssertWarnsRegexCallable(self): - def _runtime_warn(msg): - warnings.warn(msg, RuntimeWarning) + def _runtime_warn(*msgs): + for msg in msgs: + warnings.warn(msg, RuntimeWarning) self.assertWarnsRegex(RuntimeWarning, "o+", _runtime_warn, "foox") # Failure when no warning is triggered @@ -1734,16 +1788,26 @@ def _runtime_warn(msg): with self.assertRaises(TypeError): self.assertWarnsRegex(RuntimeWarning, "o+", None) # Failure when another warning is triggered - with warnings.catch_warnings(): + with warnings.catch_warnings(record=True) as log: # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): self.assertWarnsRegex(DeprecationWarning, "o+", - _runtime_warn, "foox") - # Failure when message doesn't match - with self.assertRaises(self.failureException): + _runtime_warn, "foox", "foox") + self.assertEqual(len(log), 1, log) + self.assertIsInstance(log[0].message, RuntimeWarning) + # Failure when message doesn't match. + # Warnings that do not match the regex are not swallowed. + with self.assertWarnsRegex(RuntimeWarning, "ar"): + with self.assertRaises(self.failureException): + self.assertWarnsRegex(RuntimeWarning, "o+", + _runtime_warn, "barz") + with self.assertWarnsRegex(RuntimeWarning, "ar"): + self.assertWarnsRegex(RuntimeWarning, "o+", + _runtime_warn, "barz", "foox") + with self.assertWarnsRegex(RuntimeWarning, "ar"): self.assertWarnsRegex(RuntimeWarning, "o+", - _runtime_warn, "barz") + _runtime_warn, "foox", "barz") # A little trickier: we ask RuntimeWarnings to be raised, and then # check for some of them. It is implementation-defined whether # non-matching RuntimeWarnings are simply re-raised, or produce a @@ -1778,16 +1842,29 @@ def _runtime_warn(msg): with self.assertWarnsRegex(RuntimeWarning, 'o+', foobar=42): pass # Failure when another warning is triggered - with warnings.catch_warnings(): + with warnings.catch_warnings(record=True) as log: # Force default filter (in case tests are run with -We) warnings.simplefilter("default", RuntimeWarning) with self.assertRaises(self.failureException): with self.assertWarnsRegex(DeprecationWarning, "o+"): _runtime_warn("foox") - # Failure when message doesn't match - with self.assertRaises(self.failureException): + _runtime_warn("foox") + self.assertEqual(len(log), 1, log) + self.assertIsInstance(log[0].message, RuntimeWarning) + # Failure when message doesn't match. + # Warnings that do not match the regex are not swallowed. + with self.assertWarnsRegex(RuntimeWarning, "ar"): + with self.assertRaises(self.failureException): + with self.assertWarnsRegex(RuntimeWarning, "o+"): + _runtime_warn("barz") + with self.assertWarnsRegex(RuntimeWarning, "ar"): with self.assertWarnsRegex(RuntimeWarning, "o+"): _runtime_warn("barz") + _runtime_warn("foox") + with self.assertWarnsRegex(RuntimeWarning, "ar"): + with self.assertWarnsRegex(RuntimeWarning, "o+"): + _runtime_warn("foox") + _runtime_warn("barz") # A little trickier: we ask RuntimeWarnings to be raised, and then # check for some of them. It is implementation-defined whether # non-matching RuntimeWarnings are simply re-raised, or produce a @@ -1797,6 +1874,19 @@ def _runtime_warn(msg): with self.assertRaises((RuntimeWarning, self.failureException)): with self.assertWarnsRegex(RuntimeWarning, "o+"): _runtime_warn("barz") + # Filters by module name work for warnings with other message. + with warnings.catch_warnings(record=True) as log: + warnings.filterwarnings("error", category=RuntimeWarning) + warnings.filterwarnings("default", category=RuntimeWarning, + module=re.escape(__name__)) + warnings.filterwarnings("error", category=RuntimeWarning, + module='test_case') + with self.assertWarnsRegex(RuntimeWarning, "ar"): + _runtime_warn("bar") + _runtime_warn("foox") + _runtime_warn("foox") + self.assertEqual(len(log), 1, log) + self.assertIsInstance(log[0].message, RuntimeWarning) def testAssertWarnsRegexNoExceptionType(self): with self.assertRaises(TypeError): @@ -1920,6 +2010,22 @@ def testAssertLogsUnexpectedException(self): with self.assertLogs(): raise ZeroDivisionError("Unexpected") + def testAssertLogsWithFormatter(self): + # Check alternative formats will be respected + format = "[No.1: the larch] %(levelname)s:%(name)s:%(message)s" + formatter = logging.Formatter(format) + with self.assertNoStderr(): + with self.assertLogs() as cm: + log_foo.info("1") + log_foobar.debug("2") + self.assertEqual(cm.output, ["INFO:foo:1"]) + self.assertLogRecords(cm.records, [{'name': 'foo'}]) + with self.assertLogs(formatter=formatter) as cm: + log_foo.info("1") + log_foobar.debug("2") + self.assertEqual(cm.output, ["[No.1: the larch] INFO:foo:1"]) + self.assertLogRecords(cm.records, [{'name': 'foo'}]) + def testAssertNoLogsDefault(self): with self.assertRaises(self.failureException) as cm: with self.assertNoLogs(): diff --git a/Lib/test/test_unittest/test_loader.py b/Lib/test/test_unittest/test_loader.py index cdff6d1a20c..f4e50a3dccb 100644 --- a/Lib/test/test_unittest/test_loader.py +++ b/Lib/test/test_unittest/test_loader.py @@ -1,3 +1,4 @@ +import abc import functools import sys import types @@ -98,6 +99,22 @@ def test_loadTestsFromTestCase__from_FunctionTestCase(self): self.assertIsInstance(suite, loader.suiteClass) self.assertEqual(list(suite), []) + # "Do not load any tests from a TestCase-derived class that is an abstract + # base class." + def test_loadTestsFromTestCase__from_abc_TestCase(self): + class FooBase(unittest.TestCase, metaclass=abc.ABCMeta): + @abc.abstractmethod + def test(self): ... + class Foo(FooBase): + def test(self): pass + + empty_suite = unittest.TestSuite() + + loader = unittest.TestLoader() + suite = loader.loadTestsFromTestCase(Foo) + self.assertEqual(loader.loadTestsFromTestCase(FooBase), empty_suite) + self.assertEqual(list(suite), [Foo('test')]) + ################################################################ ### /Tests for TestLoader.loadTestsFromTestCase @@ -252,6 +269,24 @@ def load_tests(loader, tests, pattern): self.assertRaisesRegex(TypeError, "some failure", test.m) + # Check that loadTestsFromModule skips abstract base classes derived from + # TestCase, which can't be instantiated. + def test_loadTestsFromModule__skip_abc_TestCase(self): + m = types.ModuleType('m') + class MyTestCaseBase(unittest.TestCase, metaclass=abc.ABCMeta): + @abc.abstractmethod + def test(self): + ... + class MyTestCase(MyTestCaseBase): + def test(self): + pass + m.testcase_1 = MyTestCaseBase + m.testcase_2 = MyTestCase + loader = unittest.TestLoader() + suite = loader.loadTestsFromModule(m) + expected = [loader.suiteClass([MyTestCase('test')])] + self.assertEqual(list(suite), expected) + ################################################################ ### /Tests for TestLoader.loadTestsFromModule() @@ -1052,6 +1087,22 @@ def test_loadTestsFromNames__module_not_loaded(self): if module_name in sys.modules: del sys.modules[module_name] + # "The specifier should not refer to a test method in a TestCase-derived + # subclass that is an abstract base class" + def test_loadTestsFromNames__testmethod_in_abc_TestCase(self): + m = types.ModuleType('m') + class Foo(unittest.TestCase, metaclass=abc.ABCMeta): + @abc.abstractmethod + def test_1(self): ... + def test_2(self): pass + m.Foo = Foo + + loader = unittest.TestLoader() + for name in 'Foo.test_1', 'Foo.test_2': + with self.subTest(name=name), self.assertRaisesRegex(TypeError, + "Cannot instantiate abstract test case Foo"): + loader.loadTestsFromNames([name], m) + ################################################################ ### /Tests for TestLoader.loadTestsFromNames() diff --git a/Lib/test/test_unittest/test_result.py b/Lib/test/test_unittest/test_result.py index 9ac4c52449c..3f44e617303 100644 --- a/Lib/test/test_unittest/test_result.py +++ b/Lib/test/test_unittest/test_result.py @@ -1282,14 +1282,22 @@ def setUpModule(): suite(result) expected_out = '\nStdout:\ndo cleanup2\ndo cleanup1\n' self.assertEqual(stdout.getvalue(), expected_out) - self.assertEqual(len(result.errors), 1) + self.assertEqual(len(result.errors), 2) description = 'tearDownModule (Module)' test_case, formatted_exc = result.errors[0] self.assertEqual(test_case.description, description) self.assertIn('ValueError: bad cleanup2', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) self.assertNotIn('TypeError', formatted_exc) self.assertIn(expected_out, formatted_exc) + test_case, formatted_exc = result.errors[1] + self.assertEqual(test_case.description, description) + self.assertIn('TypeError: bad cleanup1', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) + self.assertNotIn('ValueError', formatted_exc) + self.assertIn(expected_out, formatted_exc) + def testBufferSetUpModule_DoModuleCleanups(self): with captured_stdout() as stdout: result = unittest.TestResult() @@ -1313,22 +1321,34 @@ def setUpModule(): suite(result) expected_out = '\nStdout:\nset up module\ndo cleanup2\ndo cleanup1\n' self.assertEqual(stdout.getvalue(), expected_out) - self.assertEqual(len(result.errors), 2) + self.assertEqual(len(result.errors), 3) description = 'setUpModule (Module)' test_case, formatted_exc = result.errors[0] self.assertEqual(test_case.description, description) self.assertIn('ZeroDivisionError: division by zero', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) self.assertNotIn('ValueError', formatted_exc) self.assertNotIn('TypeError', formatted_exc) self.assertIn('\nStdout:\nset up module\n', formatted_exc) + test_case, formatted_exc = result.errors[1] self.assertIn(expected_out, formatted_exc) self.assertEqual(test_case.description, description) self.assertIn('ValueError: bad cleanup2', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) self.assertNotIn('ZeroDivisionError', formatted_exc) self.assertNotIn('TypeError', formatted_exc) self.assertIn(expected_out, formatted_exc) + test_case, formatted_exc = result.errors[2] + self.assertIn(expected_out, formatted_exc) + self.assertEqual(test_case.description, description) + self.assertIn('TypeError: bad cleanup1', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) + self.assertNotIn('ZeroDivisionError', formatted_exc) + self.assertNotIn('ValueError', formatted_exc) + self.assertIn(expected_out, formatted_exc) + def testBufferTearDownModule_DoModuleCleanups(self): with captured_stdout() as stdout: result = unittest.TestResult() @@ -1355,21 +1375,32 @@ def tearDownModule(): suite(result) expected_out = '\nStdout:\ntear down module\ndo cleanup2\ndo cleanup1\n' self.assertEqual(stdout.getvalue(), expected_out) - self.assertEqual(len(result.errors), 2) + self.assertEqual(len(result.errors), 3) description = 'tearDownModule (Module)' test_case, formatted_exc = result.errors[0] self.assertEqual(test_case.description, description) self.assertIn('ZeroDivisionError: division by zero', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) self.assertNotIn('ValueError', formatted_exc) self.assertNotIn('TypeError', formatted_exc) self.assertIn('\nStdout:\ntear down module\n', formatted_exc) + test_case, formatted_exc = result.errors[1] self.assertEqual(test_case.description, description) self.assertIn('ValueError: bad cleanup2', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) self.assertNotIn('ZeroDivisionError', formatted_exc) self.assertNotIn('TypeError', formatted_exc) self.assertIn(expected_out, formatted_exc) + test_case, formatted_exc = result.errors[2] + self.assertEqual(test_case.description, description) + self.assertIn('TypeError: bad cleanup1', formatted_exc) + self.assertNotIn('ExceptionGroup', formatted_exc) + self.assertNotIn('ZeroDivisionError', formatted_exc) + self.assertNotIn('ValueError', formatted_exc) + self.assertIn(expected_out, formatted_exc) + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_unittest/test_runner.py b/Lib/test/test_unittest/test_runner.py index 4d3cfd60b8d..a47e2ebb59d 100644 --- a/Lib/test/test_unittest/test_runner.py +++ b/Lib/test/test_unittest/test_runner.py @@ -13,6 +13,7 @@ LoggingResult, ResultWithNoStartTestRunStopTestRun, ) +from test.support.testcase import ExceptionIsLikeMixin def resultFactory(*_): @@ -604,7 +605,7 @@ class EmptyTest(unittest.TestCase): @support.force_not_colorized_test_class -class TestModuleCleanUp(unittest.TestCase): +class TestModuleCleanUp(ExceptionIsLikeMixin, unittest.TestCase): def test_add_and_do_ModuleCleanup(self): module_cleanups = [] @@ -646,11 +647,50 @@ class Module(object): [(module_cleanup_good, (1, 2, 3), dict(four='hello', five='goodbye')), (module_cleanup_bad, (), {})]) - with self.assertRaises(CustomError) as e: + with self.assertRaises(Exception) as e: unittest.case.doModuleCleanups() - self.assertEqual(str(e.exception), 'CleanUpExc') + self.assertExceptionIsLike(e.exception, + ExceptionGroup('module cleanup failed', + [CustomError('CleanUpExc')])) self.assertEqual(unittest.case._module_cleanups, []) + def test_doModuleCleanup_with_multiple_errors_in_addModuleCleanup(self): + def module_cleanup_bad1(): + raise TypeError('CleanUpExc1') + + def module_cleanup_bad2(): + raise ValueError('CleanUpExc2') + + class Module: + unittest.addModuleCleanup(module_cleanup_bad1) + unittest.addModuleCleanup(module_cleanup_bad2) + with self.assertRaises(ExceptionGroup) as e: + unittest.case.doModuleCleanups() + self.assertExceptionIsLike(e.exception, + ExceptionGroup('module cleanup failed', [ + ValueError('CleanUpExc2'), + TypeError('CleanUpExc1'), + ])) + + def test_doModuleCleanup_with_exception_group_in_addModuleCleanup(self): + def module_cleanup_bad(): + raise ExceptionGroup('CleanUpExc', [ + ValueError('CleanUpExc2'), + TypeError('CleanUpExc1'), + ]) + + class Module: + unittest.addModuleCleanup(module_cleanup_bad) + with self.assertRaises(ExceptionGroup) as e: + unittest.case.doModuleCleanups() + self.assertExceptionIsLike(e.exception, + ExceptionGroup('module cleanup failed', [ + ExceptionGroup('CleanUpExc', [ + ValueError('CleanUpExc2'), + TypeError('CleanUpExc1'), + ]), + ])) + def test_addModuleCleanup_arg_errors(self): cleanups = [] def cleanup(*args, **kwargs): @@ -871,9 +911,11 @@ def tearDownClass(cls): ordering = [] blowUp = True suite = unittest.defaultTestLoader.loadTestsFromTestCase(TestableTest) - with self.assertRaises(CustomError) as cm: + with self.assertRaises(Exception) as cm: suite.debug() - self.assertEqual(str(cm.exception), 'CleanUpExc') + self.assertExceptionIsLike(cm.exception, + ExceptionGroup('module cleanup failed', + [CustomError('CleanUpExc')])) self.assertEqual(ordering, ['setUpModule', 'setUpClass', 'test', 'tearDownClass', 'tearDownModule', 'cleanup_exc']) self.assertEqual(unittest.case._module_cleanups, []) diff --git a/Lib/test/test_unittest/test_util.py b/Lib/test/test_unittest/test_util.py index d590a333930..09ce09b91b7 100644 --- a/Lib/test/test_unittest/test_util.py +++ b/Lib/test/test_unittest/test_util.py @@ -26,6 +26,39 @@ def test_sorted_list_difference(self): self.assertEqual(sorted_list_difference([2], [1, 1]), ([2], [1])) self.assertEqual(sorted_list_difference([1, 2], [1, 1]), ([2], [])) + def test_sorted_list_difference_tail_deduplication(self): + # Tail deduplication when one list is exhausted before the other. + # These exercise the except-IndexError path in sorted_list_difference. + self.assertEqual(sorted_list_difference([], [0, 0]), ([], [0])) + self.assertEqual(sorted_list_difference([0, 0], []), ([0], [])) + self.assertEqual(sorted_list_difference([], [1, 1, 2, 2]), ([], [1, 2])) + self.assertEqual(sorted_list_difference([1, 1, 2, 2], []), ([1, 2], [])) + # One list exhausts mid-way, leaving duplicated tail in the other. + self.assertEqual(sorted_list_difference([1], [1, 2, 2, 3, 3]), ([], [2, 3])) + self.assertEqual(sorted_list_difference([1, 2, 2, 3, 3], [1]), ([2, 3], [])) + + def test_sorted_list_difference_strings(self): + self.assertEqual( + sorted_list_difference(['a', 'b'], ['b', 'c']), + (['a'], ['c'])) + self.assertEqual( + sorted_list_difference([], ['a', 'a', 'b']), + ([], ['a', 'b'])) + self.assertEqual( + sorted_list_difference(['a', 'a', 'b'], []), + (['a', 'b'], [])) + + def test_sorted_list_difference_unhashable(self): + self.assertEqual( + sorted_list_difference([[1], [2]], [[2], [3]]), + ([[1]], [[3]])) + self.assertEqual( + sorted_list_difference([], [[0], [0]]), + ([], [[0]])) + self.assertEqual( + sorted_list_difference([[0], [0]], []), + ([[0]], [])) + def test_unorderable_list_difference(self): self.assertEqual(unorderable_list_difference([], []), ([], [])) self.assertEqual(unorderable_list_difference([1, 2], []), ([2, 1], [])) diff --git a/Lib/test/test_unittest/testmock/testhelpers.py b/Lib/test/test_unittest/testmock/testhelpers.py index bcae14c5b3c..0e82c723ec3 100644 --- a/Lib/test/test_unittest/testmock/testhelpers.py +++ b/Lib/test/test_unittest/testmock/testhelpers.py @@ -45,7 +45,6 @@ def test_any_and_datetime(self): mock.assert_called_with(ANY, foo=ANY) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_any_mock_calls_comparison_order(self): mock = Mock() class Foo(object): diff --git a/Lib/test/test_unittest/testmock/testpatch.py b/Lib/test/test_unittest/testmock/testpatch.py index bd85fdcfc47..bd2a7fb6d67 100644 --- a/Lib/test/test_unittest/testmock/testpatch.py +++ b/Lib/test/test_unittest/testmock/testpatch.py @@ -5,6 +5,7 @@ import os import sys from collections import OrderedDict +from types import LazyImportType, ModuleType import unittest import test @@ -2101,5 +2102,39 @@ def test(_): test() +class PatchLazyImportTest(unittest.TestCase): + + def lazy_module(self): + # `lazy from` binds eagerly when the module it imports from is already + # imported, so publish the target only once the statement has run. + self.enterContext(uncache('lazy_patch_user', 'lazy_patch_target')) + user = ModuleType('lazy_patch_user') + exec('lazy from lazy_patch_target import function', user.__dict__) + sys.modules['lazy_patch_user'] = user + target = ModuleType('lazy_patch_target') + exec('def function(arg): pass', target.__dict__) + sys.modules['lazy_patch_target'] = target + + self.assertIsInstance(user.__dict__['function'], LazyImportType) + return user + + def test_autospec(self): + module = self.lazy_module() + with patch.object(module, 'function', autospec=True) as mock_function: + mock_function('arg') + with self.assertRaises(TypeError): + mock_function('arg', 'extra') + + def test_spec(self): + module = self.lazy_module() + with patch.object(module, 'function', spec=True) as mock_function: + mock_function('arg') + + def test_spec_set(self): + module = self.lazy_module() + with patch.object(module, 'function', spec_set=True) as mock_function: + mock_function('arg') + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_unpack_ex.py b/Lib/test/test_unpack_ex.py index a5a20025930..4fe19765cac 100644 --- a/Lib/test/test_unpack_ex.py +++ b/Lib/test/test_unpack_ex.py @@ -134,6 +134,22 @@ ... TypeError: 'list' object is not a mapping + >>> class OnlyKeys: + ... def keys(self): + ... return ['key'] + >>> {**OnlyKeys()} + Traceback (most recent call last): + ... + TypeError: 'OnlyKeys' object is not subscriptable + + >>> class BrokenKeys: + ... def keys(self): + ... return 1 + >>> {**BrokenKeys()} + Traceback (most recent call last): + ... + TypeError: test.test_unpack_ex.BrokenKeys.keys() must return an iterable, not int + >>> len(eval("{" + ", ".join("**{{{}: {}}}".format(i, i) ... for i in range(1000)) + "}")) 1000 @@ -141,7 +157,7 @@ >>> {0:1, **{0:2}, 0:3, 0:4} {0: 4} -List comprehension element unpacking +Comprehension element unpacking >>> a, b, c = [0, 1, 2], 3, 4 >>> [*a, b, c] @@ -149,46 +165,220 @@ >>> l = [a, (3, 4), {5}, {6: None}, (i for i in range(7, 10))] >>> [*item for item in l] + [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + + >>> [*[0, 1] for i in range(5)] + [0, 1, 0, 1, 0, 1, 0, 1, 0, 1] + + >>> [*'a' for i in range(5)] + ['a', 'a', 'a', 'a', 'a'] + + >>> [*[] for i in range(10)] + [] + + >>> [*(x*2) for x in [[1, 2, 3], [], 'cat']] + [1, 2, 3, 1, 2, 3, 'c', 'a', 't', 'c', 'a', 't'] + + >>> {**{} for a in [1]} + {} + + >>> {**{7: i} for i in range(10)} + {7: 9} + + >>> dicts = [{1: 2}, {3: 4}, {5: 6, 7: 8}, {}, {9: 10}, {1: 0}] + >>> {**d for d in dicts} + {1: 0, 3: 4, 5: 6, 7: 8, 9: 10} + + >>> gen = (*(0, 1) for i in range(5)) + >>> next(gen) + 0 + >>> list(gen) + [1, 0, 1, 0, 1, 0, 1, 0, 1] + +Comprehension unpacking with conditionals and double loops + + >>> [*[i, i+1] for i in range(5) if i % 2 == 0] + [0, 1, 2, 3, 4, 5] + + >>> [*y for x in [[[0], [1, 2, 3], [], [4, 5]], [[6, 7]]] for y in x] + [0, 1, 2, 3, 4, 5, 6, 7] + + >>> [*y for x in [[[0], [1, 2, 3], [], [4, 5]], [[6, 7]]] for y in x if y and y[0]>0] + [1, 2, 3, 4, 5, 6, 7] + + >>> dicts = [{1: 2}, {3: 4}, {5: 6, 7: 8}, {}, {9: 10}, {1: 0}] + >>> {**d for d in dicts if len(d) != 2} + {1: 0, 3: 4, 9: 10} + +Scoping of assignment expressions in comprehensions + + >>> [*((y := i**2), 2*y) for i in range(4)] + [0, 0, 1, 2, 4, 8, 9, 18] + >>> y + 9 + + >>> [*(y := [i, i+1, i+2]) for i in range(4)] + [0, 1, 2, 1, 2, 3, 2, 3, 4, 3, 4, 5] + >>> y + [3, 4, 5] + + >>> g = (*(z := [i, i+1, i+2]) for i in range(4)) + >>> z Traceback (most recent call last): ... - SyntaxError: iterable unpacking cannot be used in comprehension + NameError: name 'z' is not defined + >>> next(g) + 0 + >>> z + [0, 1, 2] + >>> next(g) + 1 + >>> z + [0, 1, 2] + >>> next(g) + 2 + >>> z + [0, 1, 2] + >>> next(g) + 1 + >>> z + [1, 2, 3] + + >>> x = [1, 2, 3] + >>> y = [4, 5, 6] + >>> def f(*args): + ... print(args) + + >>> f(*x if x else y) + (1, 2, 3) + + +Malformed comperehension element unpacking + + >>> [*x for x in [1, 2, 3]] + Traceback (most recent call last): + ... + [*x for x in [1, 2, 3]] + ^^ + TypeError: Value after * must be an iterable, not int + - >>> [*[0, 1] for i in range(10)] +Error messages for specific failure modes of unpacking + + >>> [*x if x else y for x in z] Traceback (most recent call last): ... - SyntaxError: iterable unpacking cannot be used in comprehension + [*x if x else y for x in z] + ^^^^^^^^^^^^^^ + SyntaxError: invalid starred expression. Did you forget to wrap the conditional expression in parentheses? - >>> [*'a' for i in range(10)] + >>> [*x if x else y] Traceback (most recent call last): ... - SyntaxError: iterable unpacking cannot be used in comprehension + [*x if x else y] + ^^^^^^^^^^^^^^ + SyntaxError: invalid starred expression. Did you forget to wrap the conditional expression in parentheses? - >>> [*[] for i in range(10)] + >>> [x if x else *y for x in z] Traceback (most recent call last): ... - SyntaxError: iterable unpacking cannot be used in comprehension + [x if x else *y for x in z] + ^ + SyntaxError: cannot unpack only part of a conditional expression - >>> {**{} for a in [1]} + >>> [x if x else *y] Traceback (most recent call last): ... - SyntaxError: dict unpacking cannot be used in dict comprehension + [x if x else *y] + ^ + SyntaxError: cannot unpack only part of a conditional expression -# Pegen is better here. -# Generator expression in function arguments + >>> {**x if x else y} + Traceback (most recent call last): + ... + {**x if x else y} + ^^^^^^^^^^^^^^^^ + SyntaxError: invalid double starred expression. Did you forget to wrap the conditional expression in parentheses? + >>> {x if x else **y} + Traceback (most recent call last): + ... + {x if x else **y} + ^^ + SyntaxError: cannot use dict unpacking on only part of a conditional expression -# >>> list(*x for x in (range(5) for i in range(3))) -# Traceback (most recent call last): -# ... -# list(*x for x in (range(5) for i in range(3))) -# ^ -# SyntaxError: invalid syntax + >>> [**x for x in [{1: 2}]] + Traceback (most recent call last): + ... + [**x for x in [{1: 2}]] + ^^^ + SyntaxError: cannot use dict unpacking in list comprehension + + >>> (**x for x in [{1:2}]) + Traceback (most recent call last): + ... + (**x for x in [{1:2}]) + ^^^ + SyntaxError: cannot use dict unpacking in generator expression >>> dict(**x for x in [{1:2}]) Traceback (most recent call last): ... dict(**x for x in [{1:2}]) - ^ - SyntaxError: invalid syntax + ^^^ + SyntaxError: cannot use dict unpacking in generator expression + + >>> {*a: b for a, b in {1: 2}.items()} + Traceback (most recent call last): + ... + {*a: b for a, b in {1: 2}.items()} + ^^ + SyntaxError: cannot use a starred expression in a dictionary key + + >>> {**a: b for a, b in {1: 2}.items()} + Traceback (most recent call last): + ... + {**a: b for a, b in {1: 2}.items()} + ^^^ + SyntaxError: cannot use dict unpacking in a dictionary key + + >>> {a: *b for a, b in {1: 2}.items()} + Traceback (most recent call last): + ... + {a: *b for a, b in {1: 2}.items()} + ^^ + SyntaxError: cannot use a starred expression in a dictionary value + + >>> {a: **b for a, b in {1: 2}.items()} + Traceback (most recent call last): + ... + {a: **b for a, b in {1: 2}.items()} + ^^^ + SyntaxError: cannot use dict unpacking in a dictionary value + + >>> (**a) + Traceback (most recent call last): + ... + (**a) + ^^ + SyntaxError: cannot use dict unpacking here + + >>> {**a for a in {1: 2}.items(): b} + Traceback (most recent call last): + ... + {**a for a in {1: 2}.items(): b} + ^^ + SyntaxError: cannot use dict unpacking here + + +# Generator expression in function arguments + + >>> list(*x for x in (range(5) for i in range(3))) + [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4] + + >>> def f(arg): + ... print(type(arg), list(arg), list(arg)) + >>> f(*x for x in [[1,2,3]]) + [1, 2, 3] [] Iterable argument unpacking @@ -356,40 +546,40 @@ ... SyntaxError: can't use starred expression here - >>> (*x),y = 1, 2 + >>> (*x),y = 1, 2 # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: cannot use starred expression here - >>> (((*x))),y = 1, 2 # TODO: RUSTPYTHON # doctest:+ELLIPSIS +EXPECTED_FAILURE + >>> (((*x))),y = 1, 2 # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: cannot use starred expression here - >>> z,(*x),y = 1, 2, 4 + >>> z,(*x),y = 1, 2, 4 # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: cannot use starred expression here - >>> z,(*x) = 1, 2 + >>> z,(*x) = 1, 2 # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: cannot use starred expression here - >>> ((*x),y) = 1, 2 # TODO: RUSTPYTHON # doctest:+ELLIPSIS +EXPECTED_FAILURE + >>> ((*x),y) = 1, 2 # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: cannot use starred expression here Some size constraints (all fail.) - >>> s = ", ".join("a%d" % i for i in range(1<<8)) + ", *rest = range(1<<8 + 1)" + >>> s = ", ".join("a%d" % i for i in range(1<<8)) + ", *rest = range((1<<8) + 1)" >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS Traceback (most recent call last): ... SyntaxError: too many expressions in star-unpacking assignment - >>> s = ", ".join("a%d" % i for i in range(1<<8 + 1)) + ", *rest = range(1<<8 + 2)" + >>> s = ", ".join("a%d" % i for i in range((1<<8) + 1)) + ", *rest = range((1<<8) + 2)" >>> compile(s, 'test', 'exec') # doctest:+ELLIPSIS Traceback (most recent call last): ... @@ -400,12 +590,180 @@ """ -__test__ = {'doctests' : doctests} +def test_errors_in_iter(): + """ + >>> class A: + ... def __iter__(self): + ... raise exc + ... + >>> exc = ZeroDivisionError('some error') + >>> [*A()] + Traceback (most recent call last): + ... + ZeroDivisionError: some error + >>> {*A()} + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> [*A()] + Traceback (most recent call last): + ... + AttributeError: some error + + >>> {*A()} + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = TypeError('some error') + >>> [*A()] + Traceback (most recent call last): + ... + TypeError: some error + + >>> {*A()} + Traceback (most recent call last): + ... + TypeError: some error + """ + +def test_errors_in_next(): + """ + >>> class I: + ... def __iter__(self): + ... return self + ... def __next__(self): + ... raise exc + ... + >>> class A: + ... def __iter__(self): + ... return I() + ... + + >>> exc = ZeroDivisionError('some error') + >>> [*A()] + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> {*A()} + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> [*A()] + Traceback (most recent call last): + ... + AttributeError: some error + + >>> {*A()} + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = TypeError('some error') + >>> [*A()] + Traceback (most recent call last): + ... + TypeError: some error + + >>> {*A()} + Traceback (most recent call last): + ... + TypeError: some error + """ + +def test_errors_in_keys(): + """ + >>> class D: + ... def keys(self): + ... raise exc + ... + >>> exc = ZeroDivisionError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = KeyError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + KeyError: 'some error' + """ + +def test_errors_in_keys_next(): + """ + >>> class I: + ... def __iter__(self): + ... return self + ... def __next__(self): + ... raise exc + ... + >>> class D: + ... def keys(self): + ... return I() + ... + >>> exc = ZeroDivisionError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = KeyError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + KeyError: 'some error' + """ + +def test_errors_in_getitem(): + """ + >>> class D: + ... def keys(self): + ... return ['key'] + ... def __getitem__(self, key): + ... raise exc + ... + >>> exc = ZeroDivisionError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + ZeroDivisionError: some error + + >>> exc = AttributeError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + AttributeError: some error + + >>> exc = KeyError('some error') + >>> {**D()} + Traceback (most recent call last): + ... + KeyError: 'some error' + """ + +__test__ = {'doctests' : doctests} def load_tests(loader, tests, pattern): - from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON - tests.addTest(doctest.DocTestSuite(checker=DocTestChecker())) # XXX: RUSTPYTHON + tests.addTest(doctest.DocTestSuite()) return tests diff --git a/Lib/test/test_unparse.py b/Lib/test/test_unparse.py index 35e4652a87b..9bc04fc8e0a 100644 --- a/Lib/test/test_unparse.py +++ b/Lib/test/test_unparse.py @@ -216,6 +216,15 @@ def test_tstrings(self): self.check_ast_roundtrip('t""') self.check_ast_roundtrip("t'{(lambda x: x)}'") self.check_ast_roundtrip("t'{t'{x}'}'") + self.check_ast_roundtrip( + r"""t'''{( + 1, # Force lexer metadata reconstruction. + "\"#")}'''""" + ) + self.check_ast_roundtrip( + r'''t"""Value: {value =\ +}"""''' + ) def test_tstring_with_nonsensical_str_field(self): # `value` suggests that the original code is `t'{test1}`, but `str` suggests otherwise @@ -403,6 +412,11 @@ def test_set_comprehension(self): def test_dict_comprehension(self): self.check_ast_roundtrip("{x: x*x for x in range(10)}") + def test_dict_comprehension_unpacking(self): + self.check_ast_roundtrip("{**x for x in ()}") + self.check_ast_roundtrip("{**x for x in range(10)}") + self.check_ast_roundtrip("[*x for x in ()]") + def test_class_decorators(self): self.check_ast_roundtrip(class_decorator) @@ -679,6 +693,24 @@ def test_unparse_interactive_integrity_3(self): self.check_src_roundtrip(src, out, mode='single') + @test.support.subTests('case', [ + "case 'a string':", + "case True:", + "case _:", + "case [*_]:", + "case tuple():", + "case cls(arg, more=arg2):", + "case tuple() | list():", + "case [tuple() as obj, _, {'a': a, **more}]:", + "case -2:", + "case +2:", + "case 2 + 3j:", + "case +2 - 3j:", + ]) + def test_unparse_match(self, case): + src = 'match x:\n ' + case + '\n pass' + self.check_src_roundtrip(src) + class CosmeticTestCase(ASTTestCase): """Test if there are cosmetic issues caused by unnecessary additions""" diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py index 1e5f79998e7..ab59727a8fd 100644 --- a/Lib/test/test_urllib.py +++ b/Lib/test/test_urllib.py @@ -807,6 +807,61 @@ def test_short_content_raises_ContentTooShortError_without_reporthook(self): self.unfakehttp() +class urlcleanup_Tests(unittest.TestCase, FakeHTTPMixin): + """Test urllib.request.urlcleanup()""" + + def setUp(self): + self.addCleanup(urllib.request.urlcleanup) + + def urlretrieve(self): + self.fakehttp(b'HTTP/1.1 200 OK\r\n\r\ndata') + try: + filename, headers = urllib.request.urlretrieve( + support.TEST_HTTP_URL) + finally: + self.unfakehttp() + self.addCleanup(os_helper.unlink, filename) + return filename + + def fake_urlopen(self, data): + self.fakehttp(b'HTTP/1.1 200 OK\r\n\r\n' + data) + try: + with urllib.request.urlopen(support.TEST_HTTP_URL) as fp: + return fp.read() + finally: + self.unfakehttp() + + def test_temporary_files(self): + filename = self.urlretrieve() + self.assertTrue(os.path.exists(filename)) + + urllib.request.urlcleanup() + self.assertFalse(os.path.exists(filename)) + + # A file created after the cleanup is not deleted. + os_helper.create_empty_file(filename) + urllib.request.urlcleanup() + self.assertTrue(os.path.exists(filename)) + + def test_opener(self): + # The implicitly created opener supports http. + self.assertEqual(self.fake_urlopen(b'first'), b'first') + + # An installed opener replaces it and supports only its handlers. + opener = urllib.request.OpenerDirector() + opener.add_handler(urllib.request.DataHandler()) + opener.add_handler(urllib.request.UnknownHandler()) + urllib.request.install_opener(opener) + with urllib.request.urlopen('data:,hello') as fp: + self.assertEqual(fp.read(), b'hello') + with self.assertRaises(urllib.error.URLError): + self.fake_urlopen(b'') + + # urlcleanup() resets the opener. + urllib.request.urlcleanup() + self.assertEqual(self.fake_urlopen(b'second'), b'second') + + class QuotingTests(unittest.TestCase): r"""Tests for urllib.quote() and urllib.quote_plus() diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py index eeea9cda2f4..7efbc81a160 100644 --- a/Lib/test/test_urllib2.py +++ b/Lib/test/test_urllib2.py @@ -270,6 +270,50 @@ def test_password_manager_default_port(self): self.assertEqual(find_user_pass("i", "http://j.example.com:80"), (None, None)) + def test_password_manager_scheme(self): + mgr = urllib.request.HTTPPasswordMgr() + mgr.add_password( + "realm", "https://example.com/", "user", "password") + + self.assertEqual( + mgr.find_user_password("realm", "https://example.com/"), + ("user", "password")) + self.assertEqual( + mgr.find_user_password("realm", "http://example.com/"), + (None, None)) + # Support an authority without a scheme. + self.assertEqual( + mgr.find_user_password("realm", "example.com"), + ("user", "password")) + # An authority without a scheme continues to match any scheme. + mgr.add_password( + "realm", "schemeless.example.com", "user", "password") + for scheme in "http", "https": + with self.subTest(scheme=scheme): + self.assertEqual( + mgr.find_user_password( + "realm", f"{scheme}://schemeless.example.com/"), + ("user", "password")) + + # A network-path reference also has no scheme. + mgr.add_password( + "realm", "//network-path.example.com/", "user", "password") + self.assertEqual( + mgr.find_user_password( + "realm", "https://network-path.example.com/"), + ("user", "password")) + + def test_password_manager_reduced_uri(self): + mgr = urllib.request.HTTPPasswordMgr() + + self.assertEqual( + mgr.reduce_uri("http://example.com/path"), + ("example.com:80", "/path")) + self.assertTrue( + mgr.is_suburi( + ("example.com", "/path"), + ("example.com", "/path/subpath"))) + class MockOpener: addheaders = [] @@ -577,6 +621,23 @@ class NonHandler(object): self.assertRaises(TypeError, OpenerDirector().add_handler, NonHandler()) + def test_no_protocol_methods(self): + # test the case that methods starts with handler type without the protocol + # like open*() or _open*(). + # These methods should be ignored + + o = OpenerDirector() + meth_spec = [ + ["open"], + ["_open"], + ["error"] + ] + + add_ordered_mock_handlers(o, meth_spec) + + self.assertEqual(len(o.handle_open), 0) + self.assertEqual(len(o.handle_error), 0) + def test_badly_named_methods(self): # test work-around for three methods that accidentally follow the # naming conventions for handler methods @@ -1808,6 +1869,18 @@ def test_basic_prior_auth_auto_send(self): # expect request to be sent with auth header self.assertTrue(http_handler.has_auth_header) + def test_basic_prior_auth_different_scheme(self): + pwd_manager = HTTPPasswordMgrWithPriorAuth() + auth_handler = HTTPBasicAuthHandler(pwd_manager) + auth_handler.add_password( + None, "https://example.com/", "user", "password", + is_authenticated=True) + + request = Request("http://example.com/") + auth_handler.http_request(request) + + self.assertFalse(request.has_header("Authorization")) + def test_basic_prior_auth_send_after_first_success(self): # Auto send auth header after authentication is successful once diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py index d015267cefd..17db686942f 100644 --- a/Lib/test/test_urllib2net.py +++ b/Lib/test/test_urllib2net.py @@ -259,27 +259,6 @@ def test_custom_headers(self): opener.open(request) self.assertEqual(request.get_header('User-agent'),'Test-Agent') - @unittest.skip('XXX: http://www.imdb.com is gone') - def test_sites_no_connection_close(self): - # Some sites do not send Connection: close header. - # Verify that those work properly. (#issue12576) - - URL = 'http://www.imdb.com' # mangles Connection:close - - with socket_helper.transient_internet(URL): - try: - with urllib.request.urlopen(URL) as res: - pass - except ValueError: - self.fail("urlopen failed for site not sending \ - Connection:close") - else: - self.assertTrue(res) - - req = urllib.request.urlopen(URL) - res = req.read() - self.assertTrue(res) - def _test_urls(self, urls, handlers, retry=True): import time import logging diff --git a/Lib/test/test_urlparse.py b/Lib/test/test_urlparse.py index 98f0b190ee7..a5b7966c778 100644 --- a/Lib/test/test_urlparse.py +++ b/Lib/test/test_urlparse.py @@ -1,7 +1,10 @@ +import copy +import pickle import sys import unicodedata import unittest import urllib.parse +from urllib.parse import urldefrag, urlparse, urlsplit, urlunparse, urlunsplit from test import support RFC1808_BASE = "http://a/b/c/d;p?q#f" @@ -107,19 +110,46 @@ class UrlParseTestCase(unittest.TestCase): def checkRoundtrips(self, url, parsed, split, url2=None): if url2 is None: url2 = url - result = urllib.parse.urlparse(url) + self.checkRoundtrips1(url, parsed, split, missing_as_none=True) + empty = url[:0] + parsed = tuple(x or empty for x in parsed) + split = tuple(x or empty for x in split) + self.checkRoundtrips1(url, parsed, split, url2, missing_as_none=False) + + result = urlparse(url, missing_as_none=True) + self.assertEqual(urlunparse(result, keep_empty=False), url2) + self.assertEqual(urlunparse(tuple(result), keep_empty=False), url2) + result = urlparse(url, missing_as_none=False) + with self.assertRaises(ValueError): + urlunparse(result, keep_empty=True) + urlunparse(tuple(result), keep_empty=True) + + result = urlsplit(url, missing_as_none=True) + self.assertEqual(urlunsplit(result, keep_empty=False), url2) + self.assertEqual(urlunsplit(tuple(result), keep_empty=False), url2) + result = urlsplit(url, missing_as_none=False) + with self.assertRaises(ValueError): + urlunsplit(result, keep_empty=True) + urlunsplit(tuple(result), keep_empty=True) + + def checkRoundtrips1(self, url, parsed, split, url2=None, *, missing_as_none): + if url2 is None: + url2 = url + result = urlparse(url, missing_as_none=missing_as_none) self.assertSequenceEqual(result, parsed) t = (result.scheme, result.netloc, result.path, result.params, result.query, result.fragment) self.assertSequenceEqual(t, parsed) # put it back together and it should be the same - result2 = urllib.parse.urlunparse(result) - self.assertSequenceEqual(result2, url2) - self.assertSequenceEqual(result2, result.geturl()) + result2 = urlunparse(result) + self.assertEqual(result2, url2) + self.assertEqual(result2, result.geturl()) + self.assertEqual(urlunparse(result, keep_empty=missing_as_none), url2) + self.assertEqual(urlunparse(tuple(result), keep_empty=missing_as_none), result2) # the result of geturl() is a fixpoint; we can always parse it # again to get the same result: - result3 = urllib.parse.urlparse(result.geturl()) + result3 = urlparse(result.geturl(), missing_as_none=missing_as_none) self.assertEqual(result3.geturl(), result.geturl()) self.assertSequenceEqual(result3, result) self.assertEqual(result3.scheme, result.scheme) @@ -134,17 +164,18 @@ def checkRoundtrips(self, url, parsed, split, url2=None): self.assertEqual(result3.port, result.port) # check the roundtrip using urlsplit() as well - result = urllib.parse.urlsplit(url) + result = urlsplit(url, missing_as_none=missing_as_none) self.assertSequenceEqual(result, split) t = (result.scheme, result.netloc, result.path, - result.query, result.fragment) + result.query, result.fragment) self.assertSequenceEqual(t, split) - result2 = urllib.parse.urlunsplit(result) - self.assertSequenceEqual(result2, url2) - self.assertSequenceEqual(result2, result.geturl()) + result2 = urlunsplit(result) + self.assertEqual(result2, url2) + self.assertEqual(result2, result.geturl()) + self.assertEqual(urlunsplit(tuple(result), keep_empty=missing_as_none), result2) # check the fixpoint property of re-parsing the result of geturl() - result3 = urllib.parse.urlsplit(result.geturl()) + result3 = urlsplit(result.geturl(), missing_as_none=missing_as_none) self.assertEqual(result3.geturl(), result.geturl()) self.assertSequenceEqual(result3, result) self.assertEqual(result3.scheme, result.scheme) @@ -177,94 +208,94 @@ def test_qs(self, orig, expect): @support.subTests('bytes', (False, True)) @support.subTests('url,parsed,split', [ ('path/to/file', - ('', '', 'path/to/file', '', '', ''), - ('', '', 'path/to/file', '', '')), + (None, None, 'path/to/file', None, None, None), + (None, None, 'path/to/file', None, None)), ('/path/to/file', - ('', '', '/path/to/file', '', '', ''), - ('', '', '/path/to/file', '', '')), + (None, None, '/path/to/file', None, None, None), + (None, None, '/path/to/file', None, None)), ('//path/to/file', - ('', 'path', '/to/file', '', '', ''), - ('', 'path', '/to/file', '', '')), + (None, 'path', '/to/file', None, None, None), + (None, 'path', '/to/file', None, None)), ('////path/to/file', - ('', '', '//path/to/file', '', '', ''), - ('', '', '//path/to/file', '', '')), + (None, '', '//path/to/file', None, None, None), + (None, '', '//path/to/file', None, None)), ('/////path/to/file', - ('', '', '///path/to/file', '', '', ''), - ('', '', '///path/to/file', '', '')), + (None, '', '///path/to/file', None, None, None), + (None, '', '///path/to/file', None, None)), ('scheme:path/to/file', - ('scheme', '', 'path/to/file', '', '', ''), - ('scheme', '', 'path/to/file', '', '')), + ('scheme', None, 'path/to/file', None, None, None), + ('scheme', None, 'path/to/file', None, None)), ('scheme:/path/to/file', - ('scheme', '', '/path/to/file', '', '', ''), - ('scheme', '', '/path/to/file', '', '')), + ('scheme', None, '/path/to/file', None, None, None), + ('scheme', None, '/path/to/file', None, None)), ('scheme://path/to/file', - ('scheme', 'path', '/to/file', '', '', ''), - ('scheme', 'path', '/to/file', '', '')), + ('scheme', 'path', '/to/file', None, None, None), + ('scheme', 'path', '/to/file', None, None)), ('scheme:////path/to/file', - ('scheme', '', '//path/to/file', '', '', ''), - ('scheme', '', '//path/to/file', '', '')), + ('scheme', '', '//path/to/file', None, None, None), + ('scheme', '', '//path/to/file', None, None)), ('scheme://///path/to/file', - ('scheme', '', '///path/to/file', '', '', ''), - ('scheme', '', '///path/to/file', '', '')), + ('scheme', '', '///path/to/file', None, None, None), + ('scheme', '', '///path/to/file', None, None)), ('file:tmp/junk.txt', - ('file', '', 'tmp/junk.txt', '', '', ''), - ('file', '', 'tmp/junk.txt', '', '')), + ('file', None, 'tmp/junk.txt', None, None, None), + ('file', None, 'tmp/junk.txt', None, None)), ('file:///tmp/junk.txt', - ('file', '', '/tmp/junk.txt', '', '', ''), - ('file', '', '/tmp/junk.txt', '', '')), + ('file', '', '/tmp/junk.txt', None, None, None), + ('file', '', '/tmp/junk.txt', None, None)), ('file:////tmp/junk.txt', - ('file', '', '//tmp/junk.txt', '', '', ''), - ('file', '', '//tmp/junk.txt', '', '')), + ('file', '', '//tmp/junk.txt', None, None, None), + ('file', '', '//tmp/junk.txt', None, None)), ('file://///tmp/junk.txt', - ('file', '', '///tmp/junk.txt', '', '', ''), - ('file', '', '///tmp/junk.txt', '', '')), + ('file', '', '///tmp/junk.txt', None, None, None), + ('file', '', '///tmp/junk.txt', None, None)), ('http:tmp/junk.txt', - ('http', '', 'tmp/junk.txt', '', '', ''), - ('http', '', 'tmp/junk.txt', '', '')), + ('http', None, 'tmp/junk.txt', None, None, None), + ('http', None, 'tmp/junk.txt', None, None)), ('http://example.com/tmp/junk.txt', - ('http', 'example.com', '/tmp/junk.txt', '', '', ''), - ('http', 'example.com', '/tmp/junk.txt', '', '')), + ('http', 'example.com', '/tmp/junk.txt', None, None, None), + ('http', 'example.com', '/tmp/junk.txt', None, None)), ('http:///example.com/tmp/junk.txt', - ('http', '', '/example.com/tmp/junk.txt', '', '', ''), - ('http', '', '/example.com/tmp/junk.txt', '', '')), + ('http', '', '/example.com/tmp/junk.txt', None, None, None), + ('http', '', '/example.com/tmp/junk.txt', None, None)), ('http:////example.com/tmp/junk.txt', - ('http', '', '//example.com/tmp/junk.txt', '', '', ''), - ('http', '', '//example.com/tmp/junk.txt', '', '')), + ('http', '', '//example.com/tmp/junk.txt', None, None, None), + ('http', '', '//example.com/tmp/junk.txt', None, None)), ('imap://mail.python.org/mbox1', - ('imap', 'mail.python.org', '/mbox1', '', '', ''), - ('imap', 'mail.python.org', '/mbox1', '', '')), + ('imap', 'mail.python.org', '/mbox1', None, None, None), + ('imap', 'mail.python.org', '/mbox1', None, None)), ('mms://wms.sys.hinet.net/cts/Drama/09006251100.asf', ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf', - '', '', ''), + None, None, None), ('mms', 'wms.sys.hinet.net', '/cts/Drama/09006251100.asf', - '', '')), + None, None)), ('nfs://server/path/to/file.txt', - ('nfs', 'server', '/path/to/file.txt', '', '', ''), - ('nfs', 'server', '/path/to/file.txt', '', '')), + ('nfs', 'server', '/path/to/file.txt', None, None, None), + ('nfs', 'server', '/path/to/file.txt', None, None)), ('svn+ssh://svn.zope.org/repos/main/ZConfig/trunk/', ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '', ''), + None, None, None), ('svn+ssh', 'svn.zope.org', '/repos/main/ZConfig/trunk/', - '', '')), + None, None)), ('git+ssh://git@github.com/user/project.git', ('git+ssh', 'git@github.com','/user/project.git', - '','',''), + None,None,None), ('git+ssh', 'git@github.com','/user/project.git', - '', '')), + None, None)), ('itms-services://?action=download-manifest&url=https://example.com/app', - ('itms-services', '', '', '', - 'action=download-manifest&url=https://example.com/app', ''), + ('itms-services', '', '', None, + 'action=download-manifest&url=https://example.com/app', None), ('itms-services', '', '', - 'action=download-manifest&url=https://example.com/app', '')), + 'action=download-manifest&url=https://example.com/app', None)), ('+scheme:path/to/file', - ('', '', '+scheme:path/to/file', '', '', ''), - ('', '', '+scheme:path/to/file', '', '')), + (None, None, '+scheme:path/to/file', None, None, None), + (None, None, '+scheme:path/to/file', None, None)), ('sch_me:path/to/file', - ('', '', 'sch_me:path/to/file', '', '', ''), - ('', '', 'sch_me:path/to/file', '', '')), + (None, None, 'sch_me:path/to/file', None, None, None), + (None, None, 'sch_me:path/to/file', None, None)), ('schème:path/to/file', - ('', '', 'schème:path/to/file', '', '', ''), - ('', '', 'schème:path/to/file', '', '')), + (None, None, 'schème:path/to/file', None, None, None), + (None, None, 'schème:path/to/file', None, None)), ]) def test_roundtrips(self, bytes, url, parsed, split): if bytes: @@ -279,24 +310,24 @@ def test_roundtrips(self, bytes, url, parsed, split): @support.subTests('url,url2,parsed,split', [ ('///path/to/file', '/path/to/file', - ('', '', '/path/to/file', '', '', ''), - ('', '', '/path/to/file', '', '')), + (None, '', '/path/to/file', None, None, None), + (None, '', '/path/to/file', None, None)), ('scheme:///path/to/file', 'scheme:/path/to/file', - ('scheme', '', '/path/to/file', '', '', ''), - ('scheme', '', '/path/to/file', '', '')), + ('scheme', '', '/path/to/file', None, None, None), + ('scheme', '', '/path/to/file', None, None)), ('file:/tmp/junk.txt', 'file:///tmp/junk.txt', - ('file', '', '/tmp/junk.txt', '', '', ''), - ('file', '', '/tmp/junk.txt', '', '')), + ('file', None, '/tmp/junk.txt', None, None, None), + ('file', None, '/tmp/junk.txt', None, None)), ('http:/tmp/junk.txt', 'http:///tmp/junk.txt', - ('http', '', '/tmp/junk.txt', '', '', ''), - ('http', '', '/tmp/junk.txt', '', '')), + ('http', None, '/tmp/junk.txt', None, None, None), + ('http', None, '/tmp/junk.txt', None, None)), ('https:/tmp/junk.txt', 'https:///tmp/junk.txt', - ('https', '', '/tmp/junk.txt', '', '', ''), - ('https', '', '/tmp/junk.txt', '', '')), + ('https', None, '/tmp/junk.txt', None, None, None), + ('https', None, '/tmp/junk.txt', None, None)), ]) def test_roundtrips_normalization(self, bytes, url, url2, parsed, split): if bytes: @@ -310,17 +341,17 @@ def test_roundtrips_normalization(self, bytes, url, url2, parsed, split): @support.subTests('scheme', ('http', 'https')) @support.subTests('url,parsed,split', [ ('://www.python.org', - ('www.python.org', '', '', '', ''), - ('www.python.org', '', '', '')), + ('www.python.org', '', None, None, None), + ('www.python.org', '', None, None)), ('://www.python.org#abc', - ('www.python.org', '', '', '', 'abc'), - ('www.python.org', '', '', 'abc')), + ('www.python.org', '', None, None, 'abc'), + ('www.python.org', '', None, 'abc')), ('://www.python.org?q=abc', - ('www.python.org', '', '', 'q=abc', ''), - ('www.python.org', '', 'q=abc', '')), + ('www.python.org', '', None, 'q=abc', None), + ('www.python.org', '', 'q=abc', None)), ('://www.python.org/#abc', - ('www.python.org', '/', '', '', 'abc'), - ('www.python.org', '/', '', 'abc')), + ('www.python.org', '/', None, None, 'abc'), + ('www.python.org', '/', None, 'abc')), ('://a/b/c/d;p?q#f', ('a', '/b/c/d', 'p', 'q', 'f'), ('a', '/b/c/d;p', 'q', 'f')), @@ -342,16 +373,21 @@ def test_http_roundtrips(self, bytes, scheme, url, parsed, split): def checkJoin(self, base, relurl, expected, *, relroundtrip=True): with self.subTest(base=base, relurl=relurl): self.assertEqual(urllib.parse.urljoin(base, relurl), expected) - baseb = base.encode('ascii') - relurlb = relurl.encode('ascii') - expectedb = expected.encode('ascii') + baseb = str_encode(base) + relurlb = str_encode(relurl) + expectedb = str_encode(expected) self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb) if relroundtrip: - relurl = urllib.parse.urlunsplit(urllib.parse.urlsplit(relurl)) - self.assertEqual(urllib.parse.urljoin(base, relurl), expected) - relurlb = urllib.parse.urlunsplit(urllib.parse.urlsplit(relurlb)) - self.assertEqual(urllib.parse.urljoin(baseb, relurlb), expectedb) + relurl2 = urlunsplit(urlsplit(relurl)) + self.assertEqual(urllib.parse.urljoin(base, relurl2), expected) + relurlb2 = urlunsplit(urlsplit(relurlb)) + self.assertEqual(urllib.parse.urljoin(baseb, relurlb2), expectedb) + + relurl3 = urlunsplit(urlsplit(relurl, missing_as_none=True)) + self.assertEqual(urllib.parse.urljoin(base, relurl3), expected) + relurlb3 = urlunsplit(urlsplit(relurlb, missing_as_none=True)) + self.assertEqual(urllib.parse.urljoin(baseb, relurlb3), expectedb) @support.subTests('bytes', (False, True)) @support.subTests('u', ['Python', './Python','x-newscheme://foo.com/stuff','x://y','x:/y','x:/','/',]) @@ -387,7 +423,7 @@ def test_RFC1808(self): self.checkJoin(RFC1808_BASE, '../../g', 'http://a/g') # "abnormal" cases from RFC 1808: - self.checkJoin(RFC1808_BASE, '', 'http://a/b/c/d;p?q#f') + self.checkJoin(RFC1808_BASE, None, 'http://a/b/c/d;p?q#f') self.checkJoin(RFC1808_BASE, 'g.', 'http://a/b/c/g.') self.checkJoin(RFC1808_BASE, '.g', 'http://a/b/c/.g') self.checkJoin(RFC1808_BASE, 'g..', 'http://a/b/c/g..') @@ -411,8 +447,10 @@ def test_RFC1808(self): def test_RFC2368(self): # Issue 11467: path that starts with a number is not parsed correctly - self.assertEqual(urllib.parse.urlparse('mailto:1337@example.org'), + self.assertEqual(urlparse('mailto:1337@example.org'), ('mailto', '', '1337@example.org', '', '', '')) + self.assertEqual(urlparse('mailto:1337@example.org', missing_as_none=True), + ('mailto', None, '1337@example.org', None, None, None)) def test_RFC2396(self): # cases from RFC 2396 @@ -741,18 +779,18 @@ def test_RFC2732_invalid(self, bytes, invalid_url): @support.subTests('bytes', (False, True)) @support.subTests('url,defrag,frag', [ ('http://python.org#frag', 'http://python.org', 'frag'), - ('http://python.org', 'http://python.org', ''), + ('http://python.org', 'http://python.org', None), ('http://python.org/#frag', 'http://python.org/', 'frag'), - ('http://python.org/', 'http://python.org/', ''), + ('http://python.org/', 'http://python.org/', None), ('http://python.org/?q#frag', 'http://python.org/?q', 'frag'), - ('http://python.org/?q', 'http://python.org/?q', ''), + ('http://python.org/?q', 'http://python.org/?q', None), ('http://python.org/p#frag', 'http://python.org/p', 'frag'), - ('http://python.org/p?q', 'http://python.org/p?q', ''), + ('http://python.org/p?q', 'http://python.org/p?q', None), (RFC1808_BASE, 'http://a/b/c/d;p?q', 'f'), - (RFC2396_BASE, 'http://a/b/c/d;p?q', ''), + (RFC2396_BASE, 'http://a/b/c/d;p?q', None), ('http://a/b/c;p?q#f', 'http://a/b/c;p?q', 'f'), ('http://a/b/c;p?q#', 'http://a/b/c;p?q', ''), - ('http://a/b/c;p?q', 'http://a/b/c;p?q', ''), + ('http://a/b/c;p?q', 'http://a/b/c;p?q', None), ('http://a/b/c;p?#f', 'http://a/b/c;p?', 'f'), ('http://a/b/c;p#f', 'http://a/b/c;p', 'f'), ('http://a/b/c;?q#f', 'http://a/b/c;?q', 'f'), @@ -764,14 +802,19 @@ def test_RFC2732_invalid(self, bytes, invalid_url): ('//a/b/c;p?q#f', '//a/b/c;p?q', 'f'), ('://a/b/c;p?q#f', '://a/b/c;p?q', 'f'), ]) - def test_urldefrag(self, bytes, url, defrag, frag): + @support.subTests('missing_as_none', (False, True)) + def test_urldefrag(self, bytes, url, defrag, frag, missing_as_none): if bytes: url = str_encode(url) defrag = str_encode(defrag) frag = str_encode(frag) - result = urllib.parse.urldefrag(url) - hash = '#' if isinstance(url, str) else b'#' - self.assertEqual(result.geturl(), url.rstrip(hash)) + result = urllib.parse.urldefrag(url, missing_as_none=missing_as_none) + if not missing_as_none: + hash = '#' if isinstance(url, str) else b'#' + url = url.rstrip(hash) + if frag is None: + frag = url[:0] + self.assertEqual(result.geturl(), url) self.assertEqual(result, (defrag, frag)) self.assertEqual(result.url, defrag) self.assertEqual(result.fragment, frag) @@ -1001,26 +1044,27 @@ def test_attributes_bad_scheme(self, bytes, parse, scheme): if not url.isascii(): self.skipTest('non-ASCII bytes') url = url.encode("ascii") - p = parse(url) - self.assertEqual(p.scheme, b"" if bytes else "") + p = parse(url, missing_as_none=True) + self.assertIsNone(p.scheme) - def test_attributes_without_netloc(self): + @support.subTests('missing_as_none', (False, True)) + def test_attributes_without_netloc(self, missing_as_none): # This example is straight from RFC 3261. It looks like it # should allow the username, hostname, and port to be filled # in, but doesn't. Since it's a URI and doesn't use the # scheme://netloc syntax, the netloc and related attributes # should be left empty. uri = "sip:alice@atlanta.com;maddr=239.255.255.1;ttl=15" - p = urllib.parse.urlsplit(uri) - self.assertEqual(p.netloc, "") + p = urllib.parse.urlsplit(uri, missing_as_none=missing_as_none) + self.assertEqual(p.netloc, None if missing_as_none else "") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None) self.assertEqual(p.port, None) self.assertEqual(p.geturl(), uri) - p = urllib.parse.urlparse(uri) - self.assertEqual(p.netloc, "") + p = urllib.parse.urlparse(uri, missing_as_none=missing_as_none) + self.assertEqual(p.netloc, None if missing_as_none else "") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None) @@ -1029,16 +1073,16 @@ def test_attributes_without_netloc(self): # You guessed it, repeating the test with bytes input uri = b"sip:alice@atlanta.com;maddr=239.255.255.1;ttl=15" - p = urllib.parse.urlsplit(uri) - self.assertEqual(p.netloc, b"") + p = urllib.parse.urlsplit(uri, missing_as_none=missing_as_none) + self.assertEqual(p.netloc, None if missing_as_none else b"") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None) self.assertEqual(p.port, None) self.assertEqual(p.geturl(), uri) - p = urllib.parse.urlparse(uri) - self.assertEqual(p.netloc, b"") + p = urllib.parse.urlparse(uri, missing_as_none=missing_as_none) + self.assertEqual(p.netloc, None if missing_as_none else b"") self.assertEqual(p.username, None) self.assertEqual(p.password, None) self.assertEqual(p.hostname, None) @@ -1052,67 +1096,86 @@ def test_noslash(self): self.assertEqual(urllib.parse.urlparse(b"http://example.com?blahblah=/foo"), (b'http', b'example.com', b'', b'', b'blahblah=/foo', b'')) - def test_withoutscheme(self): + @support.subTests('missing_as_none', (False, True)) + def test_withoutscheme(self, missing_as_none): # Test urlparse without scheme # Issue 754016: urlparse goes wrong with IP:port without scheme # RFC 1808 specifies that netloc should start with //, urlparse expects # the same, otherwise it classifies the portion of url as path. - self.assertEqual(urllib.parse.urlparse("path"), - ('','','path','','','')) - self.assertEqual(urllib.parse.urlparse("//www.python.org:80"), - ('','www.python.org:80','','','','')) - self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"), - ('http','www.python.org:80','','','','')) + none = None if missing_as_none else '' + self.assertEqual(urlparse("path", missing_as_none=missing_as_none), + (none, none, 'path', none, none, none)) + self.assertEqual(urlparse("//www.python.org:80", missing_as_none=missing_as_none), + (none, 'www.python.org:80', '', none, none, none)) + self.assertEqual(urlparse("http://www.python.org:80", missing_as_none=missing_as_none), + ('http', 'www.python.org:80', '', none, none, none)) # Repeat for bytes input - self.assertEqual(urllib.parse.urlparse(b"path"), - (b'',b'',b'path',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"//www.python.org:80"), - (b'',b'www.python.org:80',b'',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"), - (b'http',b'www.python.org:80',b'',b'',b'',b'')) - - def test_portseparator(self): + none = None if missing_as_none else b'' + self.assertEqual(urlparse(b"path", missing_as_none=missing_as_none), + (none, none, b'path', none, none, none)) + self.assertEqual(urlparse(b"//www.python.org:80", missing_as_none=missing_as_none), + (none, b'www.python.org:80', b'', none, none, none)) + self.assertEqual(urlparse(b"http://www.python.org:80", missing_as_none=missing_as_none), + (b'http', b'www.python.org:80', b'', none, none, none)) + + @support.subTests('missing_as_none', (False, True)) + def test_portseparator(self, missing_as_none): # Issue 754016 makes changes for port separator ':' from scheme separator - self.assertEqual(urllib.parse.urlparse("http:80"), ('http','','80','','','')) - self.assertEqual(urllib.parse.urlparse("https:80"), ('https','','80','','','')) - self.assertEqual(urllib.parse.urlparse("path:80"), ('path','','80','','','')) - self.assertEqual(urllib.parse.urlparse("http:"),('http','','','','','')) - self.assertEqual(urllib.parse.urlparse("https:"),('https','','','','','')) - self.assertEqual(urllib.parse.urlparse("http://www.python.org:80"), - ('http','www.python.org:80','','','','')) + none = None if missing_as_none else '' + self.assertEqual(urlparse("http:80", missing_as_none=missing_as_none), + ('http', none, '80', none, none, none)) + self.assertEqual(urlparse("https:80", missing_as_none=missing_as_none), + ('https', none, '80', none, none, none)) + self.assertEqual(urlparse("path:80", missing_as_none=missing_as_none), + ('path', none, '80', none, none, none)) + self.assertEqual(urlparse("http:", missing_as_none=missing_as_none), + ('http', none, '', none, none, none)) + self.assertEqual(urlparse("https:", missing_as_none=missing_as_none), + ('https', none, '', none, none, none)) + self.assertEqual(urlparse("http://www.python.org:80", missing_as_none=missing_as_none), + ('http', 'www.python.org:80', '', none, none, none)) # As usual, need to check bytes input as well - self.assertEqual(urllib.parse.urlparse(b"http:80"), (b'http',b'',b'80',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"https:80"), (b'https',b'',b'80',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"path:80"), (b'path',b'',b'80',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"http:"),(b'http',b'',b'',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"https:"),(b'https',b'',b'',b'',b'',b'')) - self.assertEqual(urllib.parse.urlparse(b"http://www.python.org:80"), - (b'http',b'www.python.org:80',b'',b'',b'',b'')) + none = None if missing_as_none else b'' + self.assertEqual(urlparse(b"http:80", missing_as_none=missing_as_none), + (b'http', none, b'80', none, none, none)) + self.assertEqual(urlparse(b"https:80", missing_as_none=missing_as_none), + (b'https', none, b'80', none, none, none)) + self.assertEqual(urlparse(b"path:80", missing_as_none=missing_as_none), + (b'path', none, b'80', none, none, none)) + self.assertEqual(urlparse(b"http:", missing_as_none=missing_as_none), + (b'http', none, b'', none, none, none)) + self.assertEqual(urlparse(b"https:", missing_as_none=missing_as_none), + (b'https', none, b'', none, none, none)) + self.assertEqual(urlparse(b"http://www.python.org:80", missing_as_none=missing_as_none), + (b'http', b'www.python.org:80', b'', none, none, none)) def test_usingsys(self): # Issue 3314: sys module is used in the error self.assertRaises(TypeError, urllib.parse.urlencode, "foo") - def test_anyscheme(self): + @support.subTests('missing_as_none', (False, True)) + def test_anyscheme(self, missing_as_none): # Issue 7904: s3://foo.com/stuff has netloc "foo.com". - self.assertEqual(urllib.parse.urlparse("s3://foo.com/stuff"), - ('s3', 'foo.com', '/stuff', '', '', '')) - self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff"), - ('x-newscheme', 'foo.com', '/stuff', '', '', '')) - self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query#fragment"), - ('x-newscheme', 'foo.com', '/stuff', '', 'query', 'fragment')) - self.assertEqual(urllib.parse.urlparse("x-newscheme://foo.com/stuff?query"), - ('x-newscheme', 'foo.com', '/stuff', '', 'query', '')) + none = None if missing_as_none else '' + self.assertEqual(urlparse("s3://foo.com/stuff", missing_as_none=missing_as_none), + ('s3', 'foo.com', '/stuff', none, none, none)) + self.assertEqual(urlparse("x-newscheme://foo.com/stuff", missing_as_none=missing_as_none), + ('x-newscheme', 'foo.com', '/stuff', none, none, none)) + self.assertEqual(urlparse("x-newscheme://foo.com/stuff?query#fragment", missing_as_none=missing_as_none), + ('x-newscheme', 'foo.com', '/stuff', none, 'query', 'fragment')) + self.assertEqual(urlparse("x-newscheme://foo.com/stuff?query", missing_as_none=missing_as_none), + ('x-newscheme', 'foo.com', '/stuff', none, 'query', none)) # And for bytes... - self.assertEqual(urllib.parse.urlparse(b"s3://foo.com/stuff"), - (b's3', b'foo.com', b'/stuff', b'', b'', b'')) - self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff"), - (b'x-newscheme', b'foo.com', b'/stuff', b'', b'', b'')) - self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query#fragment"), - (b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b'fragment')) - self.assertEqual(urllib.parse.urlparse(b"x-newscheme://foo.com/stuff?query"), - (b'x-newscheme', b'foo.com', b'/stuff', b'', b'query', b'')) + none = None if missing_as_none else b'' + self.assertEqual(urlparse(b"s3://foo.com/stuff", missing_as_none=missing_as_none), + (b's3', b'foo.com', b'/stuff', none, none, none)) + self.assertEqual(urlparse(b"x-newscheme://foo.com/stuff", missing_as_none=missing_as_none), + (b'x-newscheme', b'foo.com', b'/stuff', none, none, none)) + self.assertEqual(urlparse(b"x-newscheme://foo.com/stuff?query#fragment", missing_as_none=missing_as_none), + (b'x-newscheme', b'foo.com', b'/stuff', none, b'query', b'fragment')) + self.assertEqual(urlparse(b"x-newscheme://foo.com/stuff?query", missing_as_none=missing_as_none), + (b'x-newscheme', b'foo.com', b'/stuff', none, b'query', none)) @support.subTests('func', (urllib.parse.urlparse, urllib.parse.urlsplit)) def test_default_scheme(self, func): @@ -1125,8 +1188,11 @@ def test_default_scheme(self, func): self.assertEqual(func("path", scheme="ftp").scheme, "ftp") self.assertEqual(func(b"path", scheme=b"ftp").scheme, b"ftp") self.assertEqual(func("path").scheme, "") + self.assertEqual(func("path", missing_as_none=True).scheme, None) self.assertEqual(func(b"path").scheme, b"") + self.assertEqual(func(b"path", missing_as_none=True).scheme, None) self.assertEqual(func(b"path", "").scheme, b"") + self.assertEqual(func(b"path", "", missing_as_none=True).scheme, b"") @support.subTests('url,attr,expected_frag', ( ("http:#frag", "path", "frag"), @@ -1151,9 +1217,16 @@ def test_parse_fragments(self, url, attr, expected_frag, func): "#" + expected_frag) self.assertEqual(func(url, "", False).fragment, "") + result = func(url, allow_fragments=False, missing_as_none=True) + self.assertIsNone(result.fragment) + self.assertTrue( + getattr(result, attr).endswith("#" + expected_frag)) + self.assertIsNone(func(url, "", False, missing_as_none=True).fragment) + result = func(url, allow_fragments=True) self.assertEqual(result.fragment, expected_frag) - self.assertNotEndsWith(getattr(result, attr), expected_frag) + self.assertFalse( + getattr(result, attr).endswith(expected_frag)) self.assertEqual(func(url, "", True).fragment, expected_frag) self.assertEqual(func(url).fragment, expected_frag) @@ -1182,19 +1255,10 @@ def test_mixed_types_rejected(self): with self.assertRaisesRegex(TypeError, "Cannot mix str"): urllib.parse.urljoin(b"http://python.org", "http://python.org") - @support.subTests('result_type', [ - urllib.parse.DefragResult, - urllib.parse.SplitResult, - urllib.parse.ParseResult, - ]) - def test_result_pairs(self, result_type): - # Check encoding and decoding between result pairs - str_type = result_type - num_args = len(str_type._fields) + def _check_result_type(self, str_type, str_args): bytes_type = str_type._encoded_counterpart self.assertIs(bytes_type._decoded_counterpart, str_type) - str_args = ('',) * num_args - bytes_args = (b'',) * num_args + bytes_args = tuple_encode(str_args) str_result = str_type(*str_args) bytes_result = bytes_type(*bytes_args) encoding = 'ascii' @@ -1213,6 +1277,169 @@ def test_result_pairs(self, result_type): self.assertEqual(str_result.encode(encoding), bytes_result) self.assertEqual(str_result.encode(encoding, errors), bytes_args) self.assertEqual(str_result.encode(encoding, errors), bytes_result) + for result in str_result, bytes_result: + self.assertEqual(copy.copy(result), result) + self.assertEqual(copy.deepcopy(result), result) + self.assertEqual(copy.replace(result), result) + self.assertEqual(result._replace(), result) + + def test_result_pairs__(self): + # Check encoding and decoding between result pairs + self._check_result_type(urllib.parse.DefragResult, ('', '')) + self._check_result_type(urllib.parse.DefragResult, ('', None)) + self._check_result_type(urllib.parse.SplitResult, ('', '', '', '', '')) + self._check_result_type(urllib.parse.SplitResult, (None, None, '', None, None)) + self._check_result_type(urllib.parse.ParseResult, ('', '', '', '', '', '')) + self._check_result_type(urllib.parse.ParseResult, (None, None, '', None, None, None)) + + def test_result_encoding_decoding(self): + def check(str_result, bytes_result): + self.assertEqual(str_result.encode(), bytes_result) + self.assertEqual(str_result.encode().geturl(), bytes_result.geturl()) + self.assertEqual(bytes_result.decode(), str_result) + self.assertEqual(bytes_result.decode().geturl(), str_result.geturl()) + + url = 'http://example.com/?#' + burl = url.encode() + for func in urldefrag, urlsplit, urlparse: + check(func(url, missing_as_none=True), func(burl, missing_as_none=True)) + check(func(url), func(burl)) + + def test_result_copying(self): + def check(result): + result2 = copy.copy(result) + self.assertEqual(result2, result) + self.assertEqual(result2.geturl(), result.geturl()) + result2 = copy.deepcopy(result) + self.assertEqual(result2, result) + self.assertEqual(result2.geturl(), result.geturl()) + result2 = copy.replace(result) + self.assertEqual(result2, result) + self.assertEqual(result2.geturl(), result.geturl()) + result2 = result._replace() + self.assertEqual(result2, result) + self.assertEqual(result2.geturl(), result.geturl()) + + url = 'http://example.com/?#' + burl = url.encode() + for func in urldefrag, urlsplit, urlparse: + check(func(url)) + check(func(url, missing_as_none=True)) + check(func(burl)) + check(func(burl, missing_as_none=True)) + + def test_result_pickling(self): + def check(result): + for proto in range(pickle.HIGHEST_PROTOCOL + 1): + pickled = pickle.dumps(result, proto) + result2 = pickle.loads(pickled) + self.assertEqual(result2, result) + self.assertEqual(result2.geturl(), result.geturl()) + + url = 'http://example.com/?#' + burl = url.encode() + for func in urldefrag, urlsplit, urlparse: + check(func(url)) + check(func(url, missing_as_none=True)) + check(func(burl)) + check(func(burl, missing_as_none=True)) + + def test_result_compat_unpickling(self): + def check(result, pickles): + for pickled in pickles: + result2 = pickle.loads(pickled) + self.assertEqual(result2, result) + self.assertEqual(result2.geturl(), result.geturl()) + + url = 'http://example.com/?#' + burl = url.encode() + # Pre-3.15 data. + check(urldefrag(url), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResult\nc__builtin__\ntuple\n(Vhttp://example.com/?\nV\nttR.', + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResult\nc__builtin__\ntuple\n(X\x14\x00\x00\x00http://example.com/?X\x00\x00\x00\x00ttR.', + b'\x80\x02curlparse\nDefragResult\nX\x14\x00\x00\x00http://example.com/?X\x00\x00\x00\x00\x86\x81.', + b'\x80\x03curllib.parse\nDefragResult\nX\x14\x00\x00\x00http://example.com/?X\x00\x00\x00\x00\x86\x81.', + b'\x80\x04\x958\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x0cDefragResult\x93\x8c\x14http://example.com/?\x8c\x00\x86\x81.', + )) + check(urldefrag(burl), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\n(Vhttp://example.com/?\nVlatin1\ntRc__builtin__\nbytes\n(tRttR.', + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\n(X\x14\x00\x00\x00http://example.com/?X\x06\x00\x00\x00latin1tRc__builtin__\nbytes\n)RttR.', + b'\x80\x02curlparse\nDefragResultBytes\nc_codecs\nencode\nX\x14\x00\x00\x00http://example.com/?X\x06\x00\x00\x00latin1\x86Rc__builtin__\nbytes\n)R\x86\x81.', + b'\x80\x03curllib.parse\nDefragResultBytes\nC\x14http://example.com/?C\x00\x86\x81.', + b'\x80\x04\x95=\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x11DefragResultBytes\x93C\x14http://example.com/?C\x00\x86\x81.', + )) + check(urlsplit(url), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResult\nc__builtin__\ntuple\n(Vhttp\nVexample.com\nV/\nV\np0\ng0\nttR.', + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResult\nc__builtin__\ntuple\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00ttR.', + b'\x80\x02curlparse\nSplitResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00t\x81.', + b'\x80\x03curllib.parse\nSplitResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00t\x81.', + b'\x80\x04\x95;\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x0bSplitResult\x93(\x8c\x04http\x8c\x0bexample.com\x8c\x01/\x8c\x00\x94h\x00t\x81.', + )) + check(urlsplit(burl), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\np0\n(Vhttp\nVlatin1\np1\ntRg0\n(Vexample.com\ng1\ntRg0\n(V/\ng1\ntRc__builtin__\nbytes\n(tRp2\ng2\nttR.', + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\nq\x00(X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01tRh\x00(X\x0b\x00\x00\x00example.comh\x01tRh\x00(X\x01\x00\x00\x00/h\x01tRc__builtin__\nbytes\n)Rq\x02h\x02ttR.', + b'\x80\x02curlparse\nSplitResultBytes\n(c_codecs\nencode\nq\x00X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01\x86Rh\x00X\x0b\x00\x00\x00example.comh\x01\x86Rh\x00X\x01\x00\x00\x00/h\x01\x86Rc__builtin__\nbytes\n)Rq\x02h\x02t\x81.', + b'\x80\x03curllib.parse\nSplitResultBytes\n(C\x04httpC\x0bexample.comC\x01/C\x00q\x00h\x00t\x81.', + b'\x80\x04\x95@\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x10SplitResultBytes\x93(C\x04httpC\x0bexample.comC\x01/C\x00\x94h\x00t\x81.', + )) + check(urlparse(url), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResult\nc__builtin__\ntuple\n(Vhttp\nVexample.com\nV/\nV\np0\ng0\ng0\nttR.', + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResult\nc__builtin__\ntuple\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00h\x00ttR.', + b'\x80\x02curlparse\nParseResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00h\x00t\x81.', + b'\x80\x03curllib.parse\nParseResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00h\x00t\x81.', + b'\x80\x04\x95=\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x0bParseResult\x93(\x8c\x04http\x8c\x0bexample.com\x8c\x01/\x8c\x00\x94h\x00h\x00t\x81.', + )) + check(urlparse(burl), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\np0\n(Vhttp\nVlatin1\np1\ntRg0\n(Vexample.com\ng1\ntRg0\n(V/\ng1\ntRc__builtin__\nbytes\n(tRp2\ng2\ng2\nttR.', + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\nq\x00(X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01tRh\x00(X\x0b\x00\x00\x00example.comh\x01tRh\x00(X\x01\x00\x00\x00/h\x01tRc__builtin__\nbytes\n)Rq\x02h\x02h\x02ttR.', + b'\x80\x02curlparse\nParseResultBytes\n(c_codecs\nencode\nq\x00X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01\x86Rh\x00X\x0b\x00\x00\x00example.comh\x01\x86Rh\x00X\x01\x00\x00\x00/h\x01\x86Rc__builtin__\nbytes\n)Rq\x02h\x02h\x02t\x81.', + b'\x80\x03curllib.parse\nParseResultBytes\n(C\x04httpC\x0bexample.comC\x01/C\x00q\x00h\x00h\x00t\x81.', + b'\x80\x04\x95B\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x10ParseResultBytes\x93(C\x04httpC\x0bexample.comC\x01/C\x00\x94h\x00h\x00t\x81.', + )) + + # 3.15 data with missing_as_none=True. + check(urldefrag(url, missing_as_none=True), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResult\nc__builtin__\ntuple\n(Vhttp://example.com/?\nV\nttR(N(dV_keep_empty\nI01\nstb.', + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResult\nc__builtin__\ntuple\n(X\x14\x00\x00\x00http://example.com/?X\x00\x00\x00\x00ttR(N}X\x0b\x00\x00\x00_keep_emptyI01\nstb.', + b'\x80\x02curlparse\nDefragResult\nX\x14\x00\x00\x00http://example.com/?X\x00\x00\x00\x00\x86\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x03curllib.parse\nDefragResult\nX\x14\x00\x00\x00http://example.com/?X\x00\x00\x00\x00\x86\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x04\x95K\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x0cDefragResult\x93\x8c\x14http://example.com/?\x8c\x00\x86\x81N}\x8c\x0b_keep_empty\x88s\x86b.', + )) + check(urldefrag(burl, missing_as_none=True), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\n(Vhttp://example.com/?\nVlatin1\ntRc__builtin__\nbytes\n(tRttR(N(dV_keep_empty\nI01\nstb.', + b'ccopy_reg\n_reconstructor\n(curlparse\nDefragResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\n(X\x14\x00\x00\x00http://example.com/?X\x06\x00\x00\x00latin1tRc__builtin__\nbytes\n)RttR(N}X\x0b\x00\x00\x00_keep_emptyI01\nstb.', + b'\x80\x02curlparse\nDefragResultBytes\nc_codecs\nencode\nX\x14\x00\x00\x00http://example.com/?X\x06\x00\x00\x00latin1\x86Rc__builtin__\nbytes\n)R\x86\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x03curllib.parse\nDefragResultBytes\nC\x14http://example.com/?C\x00\x86\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x04\x95P\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x11DefragResultBytes\x93C\x14http://example.com/?C\x00\x86\x81N}\x8c\x0b_keep_empty\x88s\x86b.', + )) + check(urlsplit(url, missing_as_none=True), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResult\nc__builtin__\ntuple\n(Vhttp\nVexample.com\nV/\nV\np0\ng0\nttR(N(dV_keep_empty\nI01\nstb.', + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResult\nc__builtin__\ntuple\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00ttR(N}X\x0b\x00\x00\x00_keep_emptyI01\nstb.', + b'\x80\x02curlparse\nSplitResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x03curllib.parse\nSplitResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/X\x00\x00\x00\x00q\x00h\x00t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x04\x95N\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x0bSplitResult\x93(\x8c\x04http\x8c\x0bexample.com\x8c\x01/\x8c\x00\x94h\x00t\x81N}\x8c\x0b_keep_empty\x88s\x86b.', + )) + check(urlsplit(burl, missing_as_none=True), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\np0\n(Vhttp\nVlatin1\np1\ntRg0\n(Vexample.com\ng1\ntRg0\n(V/\ng1\ntRc__builtin__\nbytes\n(tRp2\ng2\nttR(N(dV_keep_empty\nI01\nstb.', + b'ccopy_reg\n_reconstructor\n(curlparse\nSplitResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\nq\x00(X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01tRh\x00(X\x0b\x00\x00\x00example.comh\x01tRh\x00(X\x01\x00\x00\x00/h\x01tRc__builtin__\nbytes\n)Rq\x02h\x02ttR(N}X\x0b\x00\x00\x00_keep_emptyI01\nstb.', + b'\x80\x02curlparse\nSplitResultBytes\n(c_codecs\nencode\nq\x00X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01\x86Rh\x00X\x0b\x00\x00\x00example.comh\x01\x86Rh\x00X\x01\x00\x00\x00/h\x01\x86Rc__builtin__\nbytes\n)Rq\x02h\x02t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x03curllib.parse\nSplitResultBytes\n(C\x04httpC\x0bexample.comC\x01/C\x00q\x00h\x00t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x04\x95S\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x10SplitResultBytes\x93(C\x04httpC\x0bexample.comC\x01/C\x00\x94h\x00t\x81N}\x8c\x0b_keep_empty\x88s\x86b.', + )) + check(urlparse(url, missing_as_none=True), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResult\nc__builtin__\ntuple\n(Vhttp\nVexample.com\nV/\nNV\np0\ng0\nttR(N(dV_keep_empty\nI01\nstb.', + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResult\nc__builtin__\ntuple\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/NX\x00\x00\x00\x00q\x00h\x00ttR(N}X\x0b\x00\x00\x00_keep_emptyI01\nstb.', + b'\x80\x02curlparse\nParseResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/NX\x00\x00\x00\x00q\x00h\x00t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x03curllib.parse\nParseResult\n(X\x04\x00\x00\x00httpX\x0b\x00\x00\x00example.comX\x01\x00\x00\x00/NX\x00\x00\x00\x00q\x00h\x00t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x04\x95O\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x0bParseResult\x93(\x8c\x04http\x8c\x0bexample.com\x8c\x01/N\x8c\x00\x94h\x00t\x81N}\x8c\x0b_keep_empty\x88s\x86b.', + )) + check(urlparse(burl, missing_as_none=True), ( + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\np0\n(Vhttp\nVlatin1\np1\ntRg0\n(Vexample.com\ng1\ntRg0\n(V/\ng1\ntRNc__builtin__\nbytes\n(tRp2\ng2\nttR(N(dV_keep_empty\nI01\nstb.', + b'ccopy_reg\n_reconstructor\n(curlparse\nParseResultBytes\nc__builtin__\ntuple\n(c_codecs\nencode\nq\x00(X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01tRh\x00(X\x0b\x00\x00\x00example.comh\x01tRh\x00(X\x01\x00\x00\x00/h\x01tRNc__builtin__\nbytes\n)Rq\x02h\x02ttR(N}X\x0b\x00\x00\x00_keep_emptyI01\nstb.', + b'\x80\x02curlparse\nParseResultBytes\n(c_codecs\nencode\nq\x00X\x04\x00\x00\x00httpX\x06\x00\x00\x00latin1q\x01\x86Rh\x00X\x0b\x00\x00\x00example.comh\x01\x86Rh\x00X\x01\x00\x00\x00/h\x01\x86RNc__builtin__\nbytes\n)Rq\x02h\x02t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x03curllib.parse\nParseResultBytes\n(C\x04httpC\x0bexample.comC\x01/NC\x00q\x00h\x00t\x81N}X\x0b\x00\x00\x00_keep_empty\x88s\x86b.', + b'\x80\x04\x95T\x00\x00\x00\x00\x00\x00\x00\x8c\x0curllib.parse\x8c\x10ParseResultBytes\x93(C\x04httpC\x0bexample.comC\x01/NC\x00\x94h\x00t\x81N}\x8c\x0b_keep_empty\x88s\x86b.', + )) def test_parse_qs_encoding(self): result = urllib.parse.parse_qs("key=\u0141%E9", encoding="latin-1") @@ -1462,6 +1689,11 @@ def test_telurl_params(self): self.assertEqual(p1.path, '+1-201-555-0123') self.assertEqual(p1.params, '') + p1 = urllib.parse.urlparse('tel:+1-201-555-0123', missing_as_none=True) + self.assertEqual(p1.scheme, 'tel') + self.assertEqual(p1.path, '+1-201-555-0123') + self.assertEqual(p1.params, None) + p1 = urllib.parse.urlparse('tel:7042;phone-context=example.com') self.assertEqual(p1.scheme, 'tel') self.assertEqual(p1.path, '7042') @@ -1689,63 +1921,63 @@ def test_splittype_deprecation(self): urllib.parse.splittype('') self.assertEqual(str(cm.warning), 'urllib.parse.splittype() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splithost_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splithost('') self.assertEqual(str(cm.warning), 'urllib.parse.splithost() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splituser_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splituser('') self.assertEqual(str(cm.warning), 'urllib.parse.splituser() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splitpasswd_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splitpasswd('') self.assertEqual(str(cm.warning), 'urllib.parse.splitpasswd() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splitport_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splitport('') self.assertEqual(str(cm.warning), 'urllib.parse.splitport() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splitnport_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splitnport('') self.assertEqual(str(cm.warning), 'urllib.parse.splitnport() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splitquery_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splitquery('') self.assertEqual(str(cm.warning), 'urllib.parse.splitquery() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splittag_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splittag('') self.assertEqual(str(cm.warning), 'urllib.parse.splittag() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splitattr_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: urllib.parse.splitattr('') self.assertEqual(str(cm.warning), 'urllib.parse.splitattr() is deprecated as of 3.8, ' - 'use urllib.parse.urlparse() instead') + 'use urllib.parse.urlsplit() instead') def test_splitvalue_deprecation(self): with self.assertWarns(DeprecationWarning) as cm: @@ -1762,6 +1994,8 @@ def test_to_bytes_deprecation(self): def str_encode(s): + if s is None: + return None return s.encode('ascii') def tuple_encode(t): diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py index 13285c9b2a3..c60135ca5a1 100644 --- a/Lib/test/test_userdict.py +++ b/Lib/test/test_userdict.py @@ -245,7 +245,7 @@ class G(collections.UserDict): test_repr_deep = mapping_tests.TestHashMappingProtocol.test_repr_deep def test_mixed_or(self): - for t in UserDict, dict, types.MappingProxyType: + for t in UserDict, dict, frozendict, types.MappingProxyType: with self.subTest(t.__name__): u = UserDict({0: 'a', 1: 'b'}) | t({1: 'c', 2: 'd'}) self.assertEqual(u, {0: 'a', 1: 'c', 2: 'd'}) @@ -276,7 +276,7 @@ def test_mixed_or(self): self.assertIs(type(u), UserDictSubclass) def test_mixed_ior(self): - for t in UserDict, dict, types.MappingProxyType: + for t in UserDict, dict, frozendict, types.MappingProxyType: with self.subTest(t.__name__): u = u2 = UserDict({0: 'a', 1: 'b'}) u |= t({1: 'c', 2: 'd'}) diff --git a/Lib/test/test_userlist.py b/Lib/test/test_userlist.py index bb9429ce53f..3e5c5ff1945 100644 --- a/Lib/test/test_userlist.py +++ b/Lib/test/test_userlist.py @@ -167,6 +167,8 @@ def test_userlist_copy(self): self.assertEqual(u, v) self.assertEqual(type(u), type(v)) + # Decorate existing test with recursion limit, because + # the test is for C structure, but `UserList` is a Python structure. test_repr_deep = list_tests.CommonTest.test_repr_deep if __name__ == "__main__": diff --git a/Lib/test/test_utf8_mode.py b/Lib/test/test_utf8_mode.py index 3990eb8be20..b8e49440c9f 100644 --- a/Lib/test/test_utf8_mode.py +++ b/Lib/test/test_utf8_mode.py @@ -45,7 +45,6 @@ def test_posix_locale(self): out = self.get_output('-c', code, LC_ALL=loc) self.assertEqual(out, '1') - @unittest.expectedFailureIf(MS_WINDOWS, "TODO: RUSTPYTHON") def test_xoption(self): code = 'import sys; print(sys.flags.utf8_mode)' @@ -66,7 +65,6 @@ def test_xoption(self): PYTHONLEGACYWINDOWSFSENCODING='1') self.assertEqual(out, '0') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_env_var(self): code = 'import sys; print(sys.flags.utf8_mode)' @@ -91,15 +89,14 @@ def test_env_var(self): # the UTF-8 mode if not self.posix_locale(): # PYTHONUTF8 should be ignored if -E is used - out = self.get_output('-E', '-c', code, PYTHONUTF8='1') - self.assertEqual(out, '0') + out = self.get_output('-E', '-c', code, PYTHONUTF8='0') + self.assertEqual(out, '1') # invalid mode out = self.get_output('-c', code, PYTHONUTF8='xxx', failure=True) self.assertIn('invalid PYTHONUTF8 environment variable value', out.rstrip()) - @unittest.expectedFailureIf(MS_WINDOWS, "TODO: RUSTPYTHON") def test_filesystemencoding(self): code = textwrap.dedent(''' import sys @@ -119,11 +116,10 @@ def test_filesystemencoding(self): # PYTHONLEGACYWINDOWSFSENCODING disables the UTF-8 mode # and has the priority over -X utf8 and PYTHONUTF8 out = self.get_output('-X', 'utf8', '-c', code, - PYTHONUTF8='strict', + PYTHONUTF8='xxx', PYTHONLEGACYWINDOWSFSENCODING='1') self.assertEqual(out, 'mbcs/replace') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_stdio(self): code = textwrap.dedent(''' import sys @@ -213,7 +209,6 @@ def test_locale_getpreferredencoding(self): out = self.get_output('-X', 'utf8', '-c', code, LC_ALL=loc) self.assertEqual(out, 'utf-8 utf-8') - @unittest.expectedFailureIf(sys.platform.startswith("linux"), "TODO: RUSTPYTHON") @unittest.skipIf(MS_WINDOWS, 'test specific to Unix') def test_cmd_line(self): arg = 'h\xe9\u20ac'.encode('utf-8') @@ -256,7 +251,6 @@ def test_optim_level(self): out = self.get_output('-X', 'utf8', '-E', '-c', code) self.assertEqual(out, '1') - @unittest.expectedFailure # TODO: RUSTPYTHON @unittest.skipIf(MS_WINDOWS, "os.device_encoding() doesn't implement " "the UTF-8 Mode on Windows") diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py old mode 100644 new mode 100755 index c8400da3ae9..055be2994bf --- a/Lib/test/test_uuid.py +++ b/Lib/test/test_uuid.py @@ -13,7 +13,7 @@ from unittest import mock from test import support -from test.support import import_helper +from test.support import force_not_colorized_test_class, import_helper, warnings_helper from test.support.script_helper import assert_python_ok py_uuid = import_helper.import_fresh_module('uuid', blocked=['_uuid']) @@ -590,6 +590,7 @@ def test_uuid1_safe(self): # dependent on the underlying platform support. At least it cannot be # unknown (unless I suppose the platform is buggy). self.assertNotEqual(u.is_safe, self.uuid.SafeUUID.unknown) + self.assertEqual(u.version, 1) @contextlib.contextmanager def mock_generate_time_safe(self, safe_value): @@ -612,24 +613,28 @@ def test_uuid1_unknown(self): with self.mock_generate_time_safe(None): u = self.uuid.uuid1() self.assertEqual(u.is_safe, self.uuid.SafeUUID.unknown) + self.assertEqual(u.version, 1) @unittest.skipUnless(os.name == 'posix', 'POSIX-only test') def test_uuid1_is_safe(self): with self.mock_generate_time_safe(0): u = self.uuid.uuid1() self.assertEqual(u.is_safe, self.uuid.SafeUUID.safe) + self.assertEqual(u.version, 1) @unittest.skipUnless(os.name == 'posix', 'POSIX-only test') def test_uuid1_is_unsafe(self): with self.mock_generate_time_safe(-1): u = self.uuid.uuid1() self.assertEqual(u.is_safe, self.uuid.SafeUUID.unsafe) + self.assertEqual(u.version, 1) @unittest.skipUnless(os.name == 'posix', 'POSIX-only test') def test_uuid1_bogus_return_value(self): with self.mock_generate_time_safe(3): u = self.uuid.uuid1() self.assertEqual(u.is_safe, self.uuid.SafeUUID.unknown) + self.assertEqual(u.version, 1) def test_uuid1_time(self): with mock.patch.object(self.uuid, '_generate_time_safe', None), \ @@ -1112,6 +1117,7 @@ def test_uuid8_uniqueness(self): versions = {u.version for u in uuids} self.assertSetEqual(versions, {8}) + @warnings_helper.ignore_fork_in_thread_deprecation_warnings() @support.requires_fork() def testIssue8621(self): # On at least some versions of OSX self.uuid.uuid4 generates @@ -1298,10 +1304,12 @@ def test_cli_uuid8(self): self.do_test_standalone_uuid(8) +@force_not_colorized_test_class class TestUUIDWithoutExtModule(CommandLineTestCases, BaseTestUUID, unittest.TestCase): uuid = py_uuid +@force_not_colorized_test_class @unittest.skipUnless(c_uuid, 'requires the C _uuid module') class TestUUIDWithExtModule(CommandLineTestCases, BaseTestUUID, unittest.TestCase): uuid = c_uuid diff --git a/Lib/test/test_venv.py b/Lib/test/test_venv.py index 2ea5f502247..ed40d60832e 100644 --- a/Lib/test/test_venv.py +++ b/Lib/test/test_venv.py @@ -13,7 +13,6 @@ import re import shlex import shutil -import struct import subprocess import sys import sysconfig @@ -140,14 +139,9 @@ def _check_output_of_default_create(self): self.isdir(self.bindir) self.isdir(self.include) self.isdir(*self.lib) - # Issue 21197 p = self.get_env_file('lib64') - conditions = ((struct.calcsize('P') == 8) and (os.name == 'posix') and - (sys.platform != 'darwin')) - if conditions: - self.assertTrue(os.path.islink(p)) - else: - self.assertFalse(os.path.exists(p)) + if os.path.exists(p): + self.assertFalse(os.path.islink(p)) data = self.get_text_file_contents('pyvenv.cfg') executable = sys._base_executable path = os.path.dirname(executable) @@ -311,9 +305,9 @@ def test_sysconfig(self): self.assertEqual(out.strip(), expected, err) for attr, expected in ( ('executable', self.envpy()), - # Usually compare to sys.executable, but if we're running in our own - # venv then we really need to compare to our base executable - ('_base_executable', sys._base_executable), + # Usually compare to sys.prefix, but if we're running in our own + # venv then we really need to compare to our base prefix + ('base_prefix', sys.base_prefix), ): with self.subTest(attr): cmd[2] = f'import sys; print(sys.{attr})' @@ -609,6 +603,51 @@ def test_unicode_in_batch_file(self): ) self.assertEqual(out.strip(), '0') + @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows') + def test_activate_bat_respects_disable_prompt(self): + rmtree(self.env_dir) + env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv') + builder = venv.EnvBuilder(clear=True) + builder.create(env_dir) + activate = os.path.join(env_dir, self.bindir, 'activate.bat') + test_batch = os.path.join(self.env_dir, 'test_disable_prompt.bat') + with open(test_batch, "w") as f: + f.write('@echo off\n' + 'set "PROMPT=base$G"\n' + 'set "VIRTUAL_ENV_DISABLE_PROMPT=1"\n' + f'call "{activate}"\n' + 'echo ACTIVE_PROMPT:%PROMPT%\n' + 'echo VIRTUAL_ENV:%VIRTUAL_ENV%\n' + 'set "PROMPT=changed$G"\n' + 'call deactivate\n' + 'echo FINAL_PROMPT:%PROMPT%\n') + out, err = check_output([test_batch]) + lines = out.splitlines() + self.assertEqual(lines[0], b'ACTIVE_PROMPT:base$G') + self.assertEndsWith(lines[1], os.fsencode(env_dir)) + self.assertEqual(lines[2], b'FINAL_PROMPT:changed$G') + + @unittest.skipUnless(os.name == 'nt', 'only relevant on Windows') + def test_activate_bat_prefixes_prompt_by_default(self): + rmtree(self.env_dir) + env_dir = os.path.join(os.path.realpath(self.env_dir), 'venv') + builder = venv.EnvBuilder(clear=True) + builder.create(env_dir) + activate = os.path.join(env_dir, self.bindir, 'activate.bat') + test_batch = os.path.join(self.env_dir, 'test_enable_prompt.bat') + with open(test_batch, "w") as f: + f.write('@echo off\n' + 'set "PROMPT=base) $G"\n' + 'set "VIRTUAL_ENV_DISABLE_PROMPT="\n' + f'call "{activate}"\n' + 'echo ACTIVE_PROMPT:%PROMPT%\n' + 'call deactivate\n' + 'echo FINAL_PROMPT:%PROMPT%\n') + out, err = check_output([test_batch]) + lines = out.splitlines() + self.assertEqual(lines[0], b'ACTIVE_PROMPT:(venv) base) $G') + self.assertEqual(lines[1], b'FINAL_PROMPT:base) $G') + @unittest.skipUnless(os.name == 'nt' and can_symlink(), 'symlinks on Windows') def test_failed_symlink(self): @@ -937,10 +976,10 @@ def test_venvwlauncher(self): exename = exename.replace("python", "pythonw") envpyw = os.path.join(self.env_dir, self.bindir, exename) try: - subprocess.check_call([envpyw, "-c", "import sys; " - "assert sys._base_executable.endswith('%s')" % exename]) + subprocess.check_call([envpyw, "-c", "import fnmatch, sys; " + "assert fnmatch.fnmatch(sys._base_executable, '**/pythonw*.exe')"]) except subprocess.CalledProcessError: - self.fail("venvwlauncher.exe did not run %s" % exename) + self.fail("venvwlauncher.exe did not run pythonw.exe") @requireVenvCreate @@ -1057,7 +1096,7 @@ def do_test_with_pip(self, system_site_packages): err, flags=re.MULTILINE) # Ignore warning about missing optional module: try: - import ssl + import ssl # noqa: F401 except ImportError: err = re.sub( "^WARNING: Disabling truststore since ssl support is missing$", diff --git a/Lib/test/test_warnings/__init__.py b/Lib/test/test_warnings/__init__.py index bbb64faa4a7..e6b97dad309 100644 --- a/Lib/test/test_warnings/__init__.py +++ b/Lib/test/test_warnings/__init__.py @@ -14,6 +14,7 @@ from test import support from test.support import import_helper from test.support import os_helper +from test.support import threading_helper from test.support import warnings_helper from test.support import force_not_colorized from test.support.script_helper import assert_python_ok, assert_python_failure @@ -250,10 +251,23 @@ def test_filter_module(self): self.module.warn_explicit('msg', UserWarning, 'filename', 42, module='package.module') self.assertEqual(len(w), 1) + self.module.warn_explicit('msg', UserWarning, '/path/to/package/module', 42) + self.assertEqual(len(w), 2) + self.module.warn_explicit('msg', UserWarning, '/path/to/package/module.py', 42) + self.assertEqual(len(w), 3) + self.module.warn_explicit('msg', UserWarning, '/path/to/package/module/__init__.py', 42) + self.assertEqual(len(w), 4) with self.assertRaises(UserWarning): - self.module.warn_explicit('msg', UserWarning, '/path/to/package/module', 42) - with self.assertRaises(UserWarning): - self.module.warn_explicit('msg', UserWarning, '/path/to/package/module.py', 42) + self.module.warn_explicit('msg', UserWarning, '/path/to/package/module/__init__', 42) + if MS_WINDOWS: + self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.PY', 42) + self.assertEqual(len(w), 5) + self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module\__INIT__.PY', 42) + self.assertEqual(len(w), 6) + self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.PYW', 42) + self.assertEqual(len(w), 7) + self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module\__INIT__.PYW', 42) + self.assertEqual(len(w), 8) with self.module.catch_warnings(record=True) as w: self.module.simplefilter('error') @@ -277,9 +291,8 @@ def test_filter_module(self): with self.assertRaises(UserWarning): self.module.warn_explicit('msg', UserWarning, '/PATH/TO/PACKAGE/MODULE', 42) if MS_WINDOWS: - if self.module is py_warnings: - self.module.warn_explicit('msg', UserWarning, r'/path/to/package/module.PY', 42) - self.assertEqual(len(w), 3) + self.module.warn_explicit('msg', UserWarning, r'/path/to/package/module.PY', 42) + self.assertEqual(len(w), 3) with self.assertRaises(UserWarning): self.module.warn_explicit('msg', UserWarning, r'/path/to/package/module/__init__.py', 42) with self.assertRaises(UserWarning): @@ -303,9 +316,8 @@ def test_filter_module(self): self.assertEqual(len(w), 1) self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.py', 42) self.assertEqual(len(w), 2) - if self.module is py_warnings: - self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.PY', 42) - self.assertEqual(len(w), 3) + self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.PY', 42) + self.assertEqual(len(w), 3) with self.assertRaises(UserWarning): self.module.warn_explicit('msg', UserWarning, r'C:\path\to\package\module.pyw', 42) with self.assertRaises(UserWarning): @@ -400,7 +412,7 @@ def test_message_matching(self): def test_mutate_filter_list(self): class X: - def match(self, a): + def match(self, a, start=0): L[:] = [] L = [("default",X(),UserWarning,X(),0) for i in range(2)] @@ -571,15 +583,19 @@ def test_warn_nonstandard_types(self): # ``Warning() != Warning()``. self.assertEqual(str(w[-1].message), str(UserWarning(ob))) - def test_filename(self): + def test_filename_module(self): with warnings_state(self.module): with self.module.catch_warnings(record=True) as w: warning_tests.inner("spam1") self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") + self.assertEqual(w[-1].module, + "test.test_warnings.data.stacklevel") warning_tests.outer("spam2") self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") + self.assertEqual(w[-1].module, + "test.test_warnings.data.stacklevel") def test_stacklevel(self): # Test stacklevel argument @@ -589,23 +605,32 @@ def test_stacklevel(self): warning_tests.inner("spam3", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") + self.assertEqual(w[-1].module, + "test.test_warnings.data.stacklevel") warning_tests.outer("spam4", stacklevel=1) self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") + self.assertEqual(w[-1].module, + "test.test_warnings.data.stacklevel") warning_tests.inner("spam5", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "__init__.py") + self.assertEqual(w[-1].module, __name__) warning_tests.outer("spam6", stacklevel=2) self.assertEqual(os.path.basename(w[-1].filename), "stacklevel.py") + self.assertEqual(w[-1].module, + "test.test_warnings.data.stacklevel") warning_tests.outer("spam6.5", stacklevel=3) self.assertEqual(os.path.basename(w[-1].filename), "__init__.py") + self.assertEqual(w[-1].module, __name__) warning_tests.inner("spam7", stacklevel=9999) self.assertEqual(os.path.basename(w[-1].filename), "") + self.assertEqual(w[-1].module, "sys") def test_stacklevel_import(self): # Issue #24305: With stacklevel=2, module-level warnings should work. @@ -616,6 +641,7 @@ def test_stacklevel_import(self): import test.test_warnings.data.import_warning # noqa: F401 self.assertEqual(len(w), 1) self.assertEqual(w[0].filename, __file__) + self.assertEqual(w[0].module, __name__) def test_skip_file_prefixes(self): with warnings_state(self.module): @@ -627,20 +653,27 @@ def test_skip_file_prefixes(self): "inner_api", stacklevel=2, warnings_module=warning_tests.warnings) self.assertEqual(w[-1].filename, __file__) + self.assertEqual(w[-1].module, __name__) warning_tests.package("package api", stacklevel=2) self.assertEqual(w[-1].filename, __file__) + self.assertEqual(w[-1].module, __name__) self.assertEqual(w[-2].filename, w[-1].filename) + self.assertEqual(w[-2].module, w[-1].module) # Low stacklevels are overridden to 2 behavior. warning_tests.package("package api 1", stacklevel=1) self.assertEqual(w[-1].filename, __file__) + self.assertEqual(w[-1].module, __name__) warning_tests.package("package api 0", stacklevel=0) self.assertEqual(w[-1].filename, __file__) + self.assertEqual(w[-1].module, __name__) warning_tests.package("package api -99", stacklevel=-99) self.assertEqual(w[-1].filename, __file__) + self.assertEqual(w[-1].module, __name__) # The stacklevel still goes up out of the package. warning_tests.package("prefix02", stacklevel=3) self.assertIn("unittest", w[-1].filename) + self.assertStartsWith(w[-1].module, "unittest") def test_skip_file_prefixes_file_path(self): # see: gh-126209 @@ -651,6 +684,8 @@ def test_skip_file_prefixes_file_path(self): self.assertEqual(len(w), 1) self.assertNotEqual(w[-1].filename, skipped) + self.assertEqual(w[-1].filename, __file__) + self.assertEqual(w[-1].module, __name__) def test_skip_file_prefixes_type_errors(self): with warnings_state(self.module): @@ -662,7 +697,21 @@ def test_skip_file_prefixes_type_errors(self): with self.assertRaises(TypeError): warn("msg", skip_file_prefixes="a sequence of strs") - def test_exec_filename(self): + def test_skip_file_prefixes_empty_tuple_subclass(self): + with warnings_state(self.module): + self.module.simplefilter("always") + warn = warning_tests.warnings.warn + class EmptyTuple(tuple): + pass + # Passing an empty tuple subclass used to lead to a crash. + for _ in range(3): + with self.module.catch_warnings(record=True) as w: + warn("msg", skip_file_prefixes=EmptyTuple()) + self.assertEqual(len(w), 1) + self.assertEqual(w[-1].filename, __file__) + self.assertEqual(w[-1].module, __name__) + + def test_exec_filename_module(self): filename = "" codeobj = compile(("import warnings\n" "warnings.warn('hello', UserWarning)"), @@ -671,6 +720,12 @@ def test_exec_filename(self): self.module.simplefilter("always", category=UserWarning) exec(codeobj) self.assertEqual(w[0].filename, filename) + self.assertEqual(w[0].module, __name__) + with self.module.catch_warnings(record=True) as w: + self.module.simplefilter("always", category=UserWarning) + exec(codeobj, {}) + self.assertEqual(w[0].filename, filename) + self.assertEqual(w[0].module, '') def test_warn_explicit_non_ascii_filename(self): with self.module.catch_warnings(record=True) as w: @@ -717,25 +772,19 @@ def test_warning_classes(self): class MyWarningClass(Warning): pass - class NonWarningSubclass: - pass - # passing a non-subclass of Warning should raise a TypeError - with self.assertRaises(TypeError) as cm: + expected = "category must be a Warning subclass, not 'str'" + with self.assertRaisesRegex(TypeError, expected): self.module.warn('bad warning category', '') - self.assertIn('category must be a Warning subclass, not ', - str(cm.exception)) - with self.assertRaises(TypeError) as cm: - self.module.warn('bad warning category', NonWarningSubclass) - self.assertIn('category must be a Warning subclass, not ', - str(cm.exception)) + expected = "category must be a Warning subclass, not class 'int'" + with self.assertRaisesRegex(TypeError, expected): + self.module.warn('bad warning category', int) # check that warning instances also raise a TypeError - with self.assertRaises(TypeError) as cm: + expected = "category must be a Warning subclass, not '.*MyWarningClass'" + with self.assertRaisesRegex(TypeError, expected): self.module.warn('bad warning category', MyWarningClass()) - self.assertIn('category must be a Warning subclass, not ', - str(cm.exception)) with self.module.catch_warnings(): self.module.resetwarnings() @@ -764,7 +813,7 @@ def check_module_globals(self, module_globals): def check_module_globals_error(self, module_globals, errmsg, errtype=ValueError): if self.module is py_warnings: - self.check_module_globals(module_globals) + self.check_module_globals_deprecated(module_globals, errmsg) return with self.module.catch_warnings(record=True) as w: self.module.filterwarnings('always') @@ -775,9 +824,6 @@ def check_module_globals_error(self, module_globals, errmsg, errtype=ValueError) self.assertEqual(len(w), 0) def check_module_globals_deprecated(self, module_globals, msg): - if self.module is py_warnings: - self.check_module_globals(module_globals) - return with self.module.catch_warnings(record=True) as w: self.module.filterwarnings('always') self.module.warn_explicit( @@ -882,6 +928,10 @@ def test_improper_input(self): self.module._setoption('ignore::===') with self.assertRaisesRegex(self.module._OptionError, 'Wärning'): self.module._setoption('ignore::Wärning') + with self.assertRaisesRegex(self.module._OptionError, 'message'): + self.module._setoption('ignore:/?/:Warning') + with self.assertRaisesRegex(self.module._OptionError, 'module'): + self.module._setoption('ignore::Warning:/?/') self.module._setoption('error::Warning::0') self.assertRaises(UserWarning, self.module.warn, 'convert to error') @@ -896,6 +946,31 @@ def test_import_from_module(self): with self.assertRaises(TestWarning): self.module.warn('test warning', TestWarning) + def test_message(self): + # Match prefix, case-insensitive. + with self.module.catch_warnings(): + self.module._setoption('error:TEST WARN:UserWarning') + with self.assertRaises(UserWarning): + self.module.warn('Test Warning') + with self.module.catch_warnings(): + self.module._setoption(r'error:/TE.*WARN/:UserWarning') + with self.assertRaises(UserWarning): + self.module.warn('Test Warning') + + def test_module(self): + with self.module.catch_warnings(): + self.module._setoption(f'error::UserWarning:{__name__}') + with self.assertRaises(UserWarning): + self.module.warn('test warning') + # Only full match. + self.module._setoption(f'ignore::UserWarning:{__name__[:-2]}') + with self.assertRaises(UserWarning): + self.module.warn('test warning') + with self.module.catch_warnings(): + self.module._setoption(f'error::UserWarning:/{re.escape(__name__[:-2])}./') + with self.assertRaises(UserWarning): + self.module.warn('test warning') + class CWCmdLineTests(WCmdLineTests, unittest.TestCase): module = c_warnings @@ -1562,6 +1637,105 @@ def test_release_lock_no_lock(self): ): c_warnings._release_lock() + @support.cpython_only + @unittest.skipUnless(support.has_fork_support, 'requires working os.fork') + @threading_helper.requires_working_threading() + def test_fork_other_thread_holds_lock(self): + code = textwrap.dedent(''' + import _warnings + import os + import threading + import warnings + from test import support + + parent_pid = os.getpid() + read_fd, write_fd = os.pipe() + local = threading.local() + ready = threading.Event() + release = threading.Event() + warnings.simplefilter('ignore', DeprecationWarning) + warnings.simplefilter('ignore', ResourceWarning) + + class WarnOnDelete: + def __del__(self): + if os.getpid() != parent_pid: + # Even an ignored warning must acquire the lock. + warnings.warn('child cleanup', ResourceWarning) + os.write(write_fd, b'finalized') + + def worker(): + local.obj = WarnOnDelete() + _warnings._acquire_lock() + _warnings._acquire_lock() + try: + ready.set() + release.wait() + finally: + _warnings._release_lock() + _warnings._release_lock() + + thread = threading.Thread(target=worker) + thread.start() + # Release the worker before fork's parent-side warning attempts + # to acquire the warnings lock. + os.register_at_fork(after_in_parent=release.set) + try: + assert ready.wait(support.LONG_TIMEOUT) + pid = os.fork() + if pid == 0: + # The finalizer must run before os.fork() returns. + os._exit(0) + support.wait_process(pid, exitcode=0) + finally: + release.set() + thread.join() + os.close(write_fd) + assert os.read(read_fd, 100) == b'finalized' + os.close(read_fd) + ''') + assert_python_ok('-c', code) + + @support.cpython_only + @unittest.skipUnless(support.has_fork_support, 'requires working os.fork') + def test_fork_current_thread_holds_lock(self): + code = textwrap.dedent(''' + import _warnings + import os + import warnings + from test import support + + warnings.simplefilter('ignore') + for _ in range(3): + _warnings._acquire_lock() + pid = os.fork() + if pid == 0: + # Ownership must also survive a second fork in the child. + child_pid = os.fork() + if child_pid != 0: + support.wait_process(child_pid, exitcode=0) + try: + # A warning must not change the inherited recursion depth. + warnings.warn('after fork') + for _ in range(3): + _warnings._release_lock() + try: + _warnings._release_lock() + except RuntimeError: + pass + else: + raise AssertionError('unexpected recursion depth') + _warnings._acquire_lock() + _warnings._release_lock() + except BaseException: + if pid == 0: + os._exit(1) + raise + if pid == 0: + os._exit(0) + support.wait_process(pid, exitcode=0) + ''') + assert_python_ok('-c', code) + class _DeprecatedTest(BaseTest, unittest.TestCase): @@ -1602,6 +1776,37 @@ def test_RuntimeError(self): _version=version) +class WarnExplicitSourceTests(BaseTest): + # gh-155319: the source line is taken from the loader of the module + # whose globals are passed as module_globals, if the file which name + # is passed as filename cannot be read. + + def warn_explicit(self, lineno): + with support.captured_stderr() as stderr: + with self.module.catch_warnings(): + self.module.simplefilter("always") + self.module.warn_explicit( + 'eggs', UserWarning, 'nonexistent', lineno, + module_globals=warning_tests.__dict__) + return stderr.getvalue() + + def test_source_line(self): + source = warning_tests.__loader__.get_source(warning_tests.__name__) + expected = source.splitlines()[0].strip() + self.assertEqual(self.warn_explicit(1), + f'nonexistent:1: UserWarning: eggs\n {expected}\n') + + def test_source_line_out_of_range(self): + self.assertEqual(self.warn_explicit(1000), + 'nonexistent:1000: UserWarning: eggs\n') + +class CWarnExplicitSourceTests(WarnExplicitSourceTests, unittest.TestCase): + module = c_warnings + +class PyWarnExplicitSourceTests(WarnExplicitSourceTests, unittest.TestCase): + module = py_warnings + + class BootstrapTest(unittest.TestCase): def test_issue_8766(self): @@ -1616,6 +1821,59 @@ def test_issue_8766(self): assert_python_ok('-c', 'pass', '-W', 'always', PYTHONPATH=cwd) +class WarnExplicitMainTests(BaseTest): + # gh-123011: warn_explicit() with module globals of the __main__ module, + # no matter how it is executed. + code = ('import warnings\n' + 'warnings.warn_explicit("eggs", UserWarning, "bar", 1,\n' + ' module_globals=globals())\n') + + def prepare_code(self): + """Make the subprocess use the tested implementation.""" + if self.module is py_warnings: + return ("import sys\n" + "sys.modules['_warnings'] = None\n") + self.code + return self.code + + def check(self, err): + lines = err.decode().splitlines() + # Only the Python implementation adds the source line. + if len(lines) > 1 and lines[1].startswith(' '): + del lines[1] + self.assertEqual(lines, ['bar:1: UserWarning: eggs']) + + def make_script(self, dirname): + filename = os.path.join(dirname, 'spam.py') + with open(filename, 'w', encoding='utf-8') as f: + f.write(self.prepare_code()) + return filename + + def test_script(self): + # __main__ has __spec__ set to None. + with os_helper.temp_dir() as dirname: + filename = self.make_script(dirname) + rc, out, err = assert_python_ok(filename) + self.check(err) + + def test_module(self): + # __main__ has __spec__ of the module executed with -m. + with os_helper.temp_dir() as dirname: + self.make_script(dirname) + rc, out, err = assert_python_ok('-m', 'spam', PYTHONPATH=dirname) + self.check(err) + + def test_command(self): + # __main__ has the built-in importer as a loader. + rc, out, err = assert_python_ok('-c', self.prepare_code()) + self.check(err) + +class CWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase): + module = c_warnings + +class PyWarnExplicitMainTests(WarnExplicitMainTests, unittest.TestCase): + module = py_warnings + + class FinalizationTest(unittest.TestCase): def test_finalization(self): # Issue #19421: warnings.warn() should not crash diff --git a/Lib/test/test_wave.py b/Lib/test/test_wave.py index 346a343761a..d3723c04820 100644 --- a/Lib/test/test_wave.py +++ b/Lib/test/test_wave.py @@ -1,9 +1,11 @@ import unittest from test import audiotests from test import support +from test.support.os_helper import FakePath, unlink import io import os import struct +import tempfile import sys import wave @@ -20,6 +22,7 @@ class WavePCM8Test(WaveTest, unittest.TestCase): sampwidth = 1 framerate = 11025 nframes = 48 + format = wave.WAVE_FORMAT_PCM comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ @@ -37,6 +40,7 @@ class WavePCM16Test(WaveTest, unittest.TestCase): sampwidth = 2 framerate = 11025 nframes = 48 + format = wave.WAVE_FORMAT_PCM comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ @@ -58,6 +62,7 @@ class WavePCM24Test(WaveTest, unittest.TestCase): sampwidth = 3 framerate = 11025 nframes = 48 + format = wave.WAVE_FORMAT_PCM comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ @@ -85,6 +90,8 @@ class WavePCM24ExtTest(WaveTest, unittest.TestCase): sampwidth = 3 framerate = 11025 nframes = 48 + format = wave.WAVE_FORMAT_EXTENSIBLE + readonly = True # Writing EXTENSIBLE wave format is not supported. comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ @@ -112,6 +119,7 @@ class WavePCM32Test(WaveTest, unittest.TestCase): sampwidth = 4 framerate = 11025 nframes = 48 + format = wave.WAVE_FORMAT_PCM comptype = 'NONE' compname = 'not compressed' frames = bytes.fromhex("""\ @@ -132,40 +140,142 @@ class WavePCM32Test(WaveTest, unittest.TestCase): frames = wave._byteswap(frames, 4) +class WaveIeeeFloatingPointTest(WaveTest, unittest.TestCase): + sndfilename = 'pluck-float32.wav' + sndfilenframes = 3307 + nchannels = 2 + sampwidth = 4 + framerate = 11025 + nframes = 48 + format = wave.WAVE_FORMAT_IEEE_FLOAT + comptype = 'NONE' + compname = 'not compressed' + frames = bytes.fromhex("""\ + 3C8B5960BA231400 3F16B41F3BFA5480 3EC44F0E3D1DC580 BF7E46533D843040 \ + BED084FC3D564C30 3F1153303CFCBE40 BF002FB73C583EC0 3CDAFEE0BC425180 \ + BF0F5154BD3826E0 BF169F56BDCAFD40 3EA660C0BE21A4EC 3E52E53CBE49332C \ + BE102E0CBE5B7214 BEE76852BE6C3BDC 3DE05A98BE7A4980 BE06B6B4BE7EB6EC \ + 3F2EB1B0BE6C7CC8 BD195500BE3E0F4C 3E1BBDF8BE03DFEC BE9F4E92BD8D8D58 \ + BF50E1D4BD111750 BDA079B0BCFBFB20 3D866358BD0C7640 BE833C0EBD17E240 \ + 3E0BFF04BD3978F0 3EFB9AE2BD14A780 BF0710B9BCD342E0 3F4DADB5BBA0CD80 \ + BEC3B11A3D024EB0 3F063AD33D97A8C0 BEF912803DEC74E0 3F2241733E1515D4 \ + BE0904D83E3AA604 BF7BF2003E3325BC 3F8000003E2229FC BF8000003E14A738 \ + 3F1338363DEB3B28 3F256E7C3DDBCA00 BE026A683DF5FD88 BEC70C923DFBE128 \ + BE5A5B183DCEA2D8 3F4689513DA5A7C8 3D8C8FE83DA1FFF0 3EAEE61C3DB0A0E0 \ + 3F2290DF3DE44E18 BF6867373E09D82C BF1216283DEEB360 3F08262F3DA5B488 \ + """) + if sys.byteorder != 'big': + frames = wave._byteswap(frames, 4) + class MiscTestCase(unittest.TestCase): def test__all__(self): - not_exported = {'WAVE_FORMAT_PCM', 'WAVE_FORMAT_EXTENSIBLE', 'KSDATAFORMAT_SUBTYPE_PCM'} + not_exported = {'KSDATAFORMAT_SUBTYPE_PCM'} support.check__all__(self, wave, not_exported=not_exported) - def test_read_deprecations(self): - filename = support.findfile('pluck-pcm8.wav', subdir='audiodata') - with wave.open(filename) as reader: - with self.assertWarns(DeprecationWarning): - with self.assertRaises(wave.Error): - reader.getmark('mark') - with self.assertWarns(DeprecationWarning): - self.assertIsNone(reader.getmarkers()) - - def test_write_deprecations(self): - with io.BytesIO(b'') as tmpfile: - with wave.open(tmpfile, 'wb') as writer: - writer.setnchannels(1) - writer.setsampwidth(1) - writer.setframerate(1) - writer.setcomptype('NONE', 'not compressed') - - with self.assertWarns(DeprecationWarning): - with self.assertRaises(wave.Error): - writer.setmark(0, 0, 'mark') - with self.assertWarns(DeprecationWarning): - with self.assertRaises(wave.Error): - writer.getmark('mark') - with self.assertWarns(DeprecationWarning): - self.assertIsNone(writer.getmarkers()) - class WaveLowLevelTest(unittest.TestCase): + def test_setparams_6_tuple_defaults_to_pcm(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setformat(wave.WAVE_FORMAT_IEEE_FLOAT) + w.setparams((1, 2, 22050, 0, 'NONE', 'not compressed')) + self.assertEqual(w.getformat(), wave.WAVE_FORMAT_PCM) + + def test_setparams_7_tuple_uses_format(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setparams((1, 4, 22050, 0, 'NONE', 'not compressed', + wave.WAVE_FORMAT_IEEE_FLOAT)) + self.assertEqual(w.getformat(), wave.WAVE_FORMAT_IEEE_FLOAT) + + def test_setparams_7_tuple_ieee_64bit_sampwidth(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setparams((1, 8, 22050, 0, 'NONE', 'not compressed', + wave.WAVE_FORMAT_IEEE_FLOAT)) + self.assertEqual(w.getformat(), wave.WAVE_FORMAT_IEEE_FLOAT) + self.assertEqual(w.getsampwidth(), 8) + + def test_getparams_backward_compatible_shape(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setparams((1, 4, 22050, 0, 'NONE', 'not compressed', + wave.WAVE_FORMAT_IEEE_FLOAT)) + params = w.getparams() + self.assertEqual(params, (1, 4, 22050, 0, 'NONE', 'not compressed')) + + def test_getformat_setformat(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setnchannels(1) + w.setsampwidth(4) + w.setframerate(22050) + self.assertEqual(w.getformat(), wave.WAVE_FORMAT_PCM) + w.setformat(wave.WAVE_FORMAT_IEEE_FLOAT) + self.assertEqual(w.getformat(), wave.WAVE_FORMAT_IEEE_FLOAT) + + def test_setformat_ieee_requires_32_or_64_bit_sampwidth(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(22050) + with self.assertRaisesRegex(wave.Error, + 'unsupported sample width for IEEE float format'): + w.setformat(wave.WAVE_FORMAT_IEEE_FLOAT) + + def test_setsampwidth_ieee_requires_32_or_64_bit(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setnchannels(1) + w.setframerate(22050) + w.setformat(wave.WAVE_FORMAT_IEEE_FLOAT) + with self.assertRaisesRegex(wave.Error, + 'unsupported sample width for IEEE float format'): + w.setsampwidth(2) + w.setsampwidth(4) + + def test_setsampwidth_ieee_accepts_64_bit(self): + with tempfile.NamedTemporaryFile(delete_on_close=False) as fp: + filename = fp.name + self.addCleanup(unlink, filename) + + with wave.open(filename, 'wb') as w: + w.setnchannels(1) + w.setframerate(22050) + w.setformat(wave.WAVE_FORMAT_IEEE_FLOAT) + w.setsampwidth(8) + self.assertEqual(w.getsampwidth(), 8) + + def test_read_getformat(self): + b = b'RIFF' + struct.pack('') - @unittest.skip("TODO: RUSTPYTHON; occasionally crash (malloc corruption)") @threading_helper.requires_working_threading() def test_threaded_weak_valued_setdefault(self): d = weakref.WeakValueDictionary() @@ -1938,7 +1991,6 @@ def test_threaded_weak_valued_pop(self): x = d.pop(10, 10) self.assertIsNot(x, None) # we never put None in there! - @unittest.skip("TODO: RUSTPYTHON; race condition between GC and WeakValueDictionary callback") @threading_helper.requires_working_threading() def test_threaded_weak_valued_consistency(self): # Issue #28427: old keys should not remove new values from @@ -2032,7 +2084,6 @@ def pop_and_collect(lst): if exc: raise exc[0] - @unittest.skip("TODO: RUSTPYTHON; occasionally crash (malloc corruption)") @threading_helper.requires_working_threading() @support.requires_resource('cpu') def test_threaded_weak_key_dict_copy(self): @@ -2040,7 +2091,6 @@ def test_threaded_weak_key_dict_copy(self): # copying should not result in a crash. self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, False) - @unittest.skip("TODO: RUSTPYTHON; occasionally crash (malloc corruption)") @threading_helper.requires_working_threading() @support.requires_resource('cpu') def test_threaded_weak_key_dict_deepcopy(self): @@ -2048,7 +2098,6 @@ def test_threaded_weak_key_dict_deepcopy(self): # copying should not result in a crash. self.check_threaded_weak_dict_copy(weakref.WeakKeyDictionary, True) - @unittest.skip("TODO: RUSTPYTHON; occasionally crash (malloc corruption)") @threading_helper.requires_working_threading() @support.requires_resource('cpu') def test_threaded_weak_value_dict_copy(self): @@ -2056,7 +2105,6 @@ def test_threaded_weak_value_dict_copy(self): # copying should not result in a crash. self.check_threaded_weak_dict_copy(weakref.WeakValueDictionary, False) - @unittest.skip("TODO: RUSTPYTHON; occasionally crash (malloc corruption)") @threading_helper.requires_working_threading() @support.requires_resource('cpu') def test_threaded_weak_value_dict_deepcopy(self): @@ -2251,7 +2299,6 @@ def test_atexit(self): class ModuleTestCase(unittest.TestCase): - @unittest.expectedFailure # TODO: RUSTPYTHON def test_names(self): for name in ('ReferenceType', 'ProxyType', 'CallableProxyType', 'WeakMethod', 'WeakSet', 'WeakKeyDictionary', 'WeakValueDictionary'): diff --git a/Lib/test/test_webbrowser.py b/Lib/test/test_webbrowser.py index bfbcf112b0b..82f14ca968f 100644 --- a/Lib/test/test_webbrowser.py +++ b/Lib/test/test_webbrowser.py @@ -5,9 +5,10 @@ import subprocess import sys import unittest +import warnings import webbrowser -from functools import partial from test import support +from test.support import force_not_colorized_test_class from test.support import import_helper from test.support import is_apple_mobile from test.support import os_helper @@ -335,6 +336,87 @@ def close(self): return None +@unittest.skipUnless(sys.platform == "darwin", "macOS specific test") +@requires_subprocess() +class MacOSTest(unittest.TestCase): + + def setUp(self): + env = self.enterContext(os_helper.EnvironmentVarGuard()) + env.unset("BROWSER") + + def test_default(self): + browser = webbrowser.get() + self.assertIsInstance(browser, webbrowser.MacOS) + self.assertEqual(browser.name, 'default') + + def test_default_http_open(self): + # http/https URLs use /usr/bin/open directly — no bundle ID needed. + browser = webbrowser.MacOS('default') + with mock.patch('subprocess.run') as mock_run: + mock_run.return_value = mock.Mock(returncode=0) + result = browser.open(URL) + mock_run.assert_called_once_with( + ['/usr/bin/open', URL], + stderr=subprocess.DEVNULL, + ) + self.assertTrue(result) + + def test_default_non_http_uses_bundle_id(self): + # Non-http(s) URLs (e.g. file://) must be routed through the browser + # via -b to prevent OS file handler dispatch. + file_url = 'file:///tmp/test.html' + browser = webbrowser.MacOS('default') + with mock.patch('webbrowser._macos_default_browser_bundle_id', + return_value='com.google.Chrome'), \ + mock.patch('subprocess.run') as mock_run: + mock_run.return_value = mock.Mock(returncode=0) + result = browser.open(file_url) + mock_run.assert_called_once_with( + ['/usr/bin/open', '-b', 'com.google.Chrome', file_url], + stderr=subprocess.DEVNULL, + ) + self.assertTrue(result) + + def test_named_known_browser_uses_bundle_id(self): + # Named browsers with a known bundle ID use /usr/bin/open -b. + browser = webbrowser.MacOS('safari') + with mock.patch('subprocess.run') as mock_run: + mock_run.return_value = mock.Mock(returncode=0) + result = browser.open(URL) + mock_run.assert_called_once_with( + ['/usr/bin/open', '-b', 'com.apple.Safari', URL], + stderr=subprocess.DEVNULL, + ) + self.assertTrue(result) + + def test_named_unknown_browser_falls_back_to_dash_a(self): + # Named browsers not in the bundle ID map fall back to -a. + browser = webbrowser.MacOS('lynx') + with mock.patch('subprocess.run') as mock_run: + mock_run.return_value = mock.Mock(returncode=0) + browser.open(URL) + mock_run.assert_called_once_with( + ['/usr/bin/open', '-a', 'lynx', URL], + stderr=subprocess.DEVNULL, + ) + + def test_open_failure(self): + browser = webbrowser.MacOS('default') + with mock.patch('subprocess.run') as mock_run: + mock_run.return_value = mock.Mock(returncode=1) + result = browser.open(URL) + self.assertFalse(result) + + +@unittest.skipUnless(sys.platform == "darwin", "macOS specific test") +@requires_subprocess() +class MacOSXOSAScriptDeprecationTest(unittest.TestCase): + + def test_deprecation_warning(self): + with self.assertWarns(DeprecationWarning): + webbrowser.MacOSXOSAScript('default') + + @unittest.skipUnless(sys.platform == "darwin", "macOS specific test") @requires_subprocess() class MacOSXOSAScriptTest(unittest.TestCase): @@ -345,17 +427,14 @@ def setUp(self): env.unset("BROWSER") support.patch(self, os, "popen", self.mock_popen) + self.enterContext(warnings.catch_warnings()) + warnings.simplefilter("ignore", DeprecationWarning) self.browser = webbrowser.MacOSXOSAScript("default") def mock_popen(self, cmd, mode): self.popen_pipe = MockPopenPipe(cmd, mode) return self.popen_pipe - def test_default(self): - browser = webbrowser.get() - assert isinstance(browser, webbrowser.MacOSXOSAScript) - self.assertEqual(browser.name, "default") - def test_default_open(self): url = "https://python.org" self.browser.open(url) @@ -381,7 +460,9 @@ def test_default_browser_lookup(self): self.assertIn(f'open location "{url}"', script) def test_explicit_browser(self): - browser = webbrowser.MacOSXOSAScript("safari") + with warnings.catch_warnings(): + warnings.simplefilter("ignore", DeprecationWarning) + browser = webbrowser.MacOSXOSAScript("safari") browser.open("https://python.org") script = self.popen_pipe.pipe.getvalue() self.assertIn('tell application "safari"', script) @@ -527,6 +608,7 @@ def test_environment_preferred(self): self.assertEqual(webbrowser.get().name, sys.executable) +@force_not_colorized_test_class class CliTest(unittest.TestCase): def test_parse_args(self): for command, url, new_win in [ diff --git a/Lib/test/test_winapi.py b/Lib/test/test_winapi.py index e64208330ad..0ae03a3bf50 100644 --- a/Lib/test/test_winapi.py +++ b/Lib/test/test_winapi.py @@ -1,5 +1,6 @@ # Test the Windows-only _winapi module +import errno import os import pathlib import re @@ -11,9 +12,16 @@ MAXIMUM_WAIT_OBJECTS = 64 MAXIMUM_BATCHED_WAIT_OBJECTS = (MAXIMUM_WAIT_OBJECTS - 1) ** 2 + +def close_events(events): + for handle in events: + _winapi.CloseHandle(handle) + + class WinAPIBatchedWaitForMultipleObjectsTests(unittest.TestCase): def _events_waitall_test(self, n): evts = [_winapi.CreateEventW(0, False, False, None) for _ in range(n)] + self.addCleanup(close_events, evts) with self.assertRaises(TimeoutError): _winapi.BatchedWaitForMultipleObjects(evts, True, 100) @@ -41,6 +49,7 @@ def _events_waitall_test(self, n): def _events_waitany_test(self, n): evts = [_winapi.CreateEventW(0, False, False, None) for _ in range(n)] + self.addCleanup(close_events, evts) with self.assertRaises(TimeoutError): _winapi.BatchedWaitForMultipleObjects(evts, False, 100) @@ -156,3 +165,38 @@ def test_namedpipe(self): pipe2.write(b'testdata') pipe2.flush() self.assertEqual((b'testdata', 8), _winapi.PeekNamedPipe(pipe, 8)[:2]) + + def test_event_source_registration(self): + source_name = "PythonTestEventSource" + + handle = _winapi.RegisterEventSource(None, source_name) + self.addCleanup(_winapi.DeregisterEventSource, handle) + self.assertNotEqual(handle, _winapi.INVALID_HANDLE_VALUE) + + with self.assertRaises(OSError) as cm: + _winapi.RegisterEventSource(None, "") + self.assertEqual(cm.exception.errno, errno.EINVAL) + + with self.assertRaises(OSError) as cm: + _winapi.DeregisterEventSource(_winapi.INVALID_HANDLE_VALUE) + self.assertEqual(cm.exception.errno, errno.EBADF) + + def test_report_event(self): + source_name = "PythonTestEventSource" + + handle = _winapi.RegisterEventSource(None, source_name) + self.assertNotEqual(handle, _winapi.INVALID_HANDLE_VALUE) + self.addCleanup(_winapi.DeregisterEventSource, handle) + + _winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002, + "Test message 1") + + with self.assertRaises(TypeError): + _winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002, 42) + + with self.assertRaises(TypeError): + _winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002, None) + + with self.assertRaises(ValueError): + _winapi.ReportEvent(handle, _winapi.EVENTLOG_SUCCESS, 1, 1002, + "Test message \0 with embedded null character") diff --git a/Lib/test/test_winreg.py b/Lib/test/test_winreg.py index 1bc830c02c3..fc0533c6e15 100644 --- a/Lib/test/test_winreg.py +++ b/Lib/test/test_winreg.py @@ -210,6 +210,33 @@ def _test_named_args(self, key, sub_key): access=KEY_ALL_ACCESS) as okey: self.assertTrue(okey.handle != 0) + def test_hkey_comparison(self): + """Test HKEY comparison by handle value rather than object identity.""" + key1 = OpenKey(HKEY_CURRENT_USER, None) + key2 = OpenKey(HKEY_CURRENT_USER, None) + key3 = OpenKey(HKEY_LOCAL_MACHINE, None) + + self.addCleanup(CloseKey, key1) + self.addCleanup(CloseKey, key2) + self.addCleanup(CloseKey, key3) + + self.assertEqual(key1.handle, key2.handle) + self.assertTrue(key1 == key2) + self.assertFalse(key1 != key2) + + self.assertTrue(key1 != key3) + self.assertFalse(key1 == key3) + + # Closed keys should be equal (all have handle=0) + CloseKey(key1) + CloseKey(key2) + CloseKey(key3) + + self.assertEqual(key1.handle, 0) + self.assertEqual(key2.handle, 0) + self.assertEqual(key3.handle, 0) + self.assertEqual(key2, key3) + class LocalWinregTests(BaseWinregTests): @@ -549,6 +576,21 @@ def test_exception_numbers(self): with self.assertRaises(FileNotFoundError) as ctx: QueryValue(HKEY_CLASSES_ROOT, 'some_value_that_does_not_exist') + def test_delete_tree(self): + with CreateKey(HKEY_CURRENT_USER, test_key_name) as main_key: + with CreateKey(main_key, "subkey1") as subkey1: + SetValueEx(subkey1, "value1", 0, REG_SZ, "test_value1") + with CreateKey(subkey1, "subsubkey1") as subsubkey1: + SetValueEx(subsubkey1, "value2", 0, REG_DWORD, 42) + + with CreateKey(main_key, "subkey2") as subkey2: + SetValueEx(subkey2, "value3", 0, REG_SZ, "test_value3") + + DeleteTree(HKEY_CURRENT_USER, test_key_name) + + with self.assertRaises(OSError): + OpenKey(HKEY_CURRENT_USER, test_key_name) + if __name__ == "__main__": if not REMOTE_NAME: diff --git a/Lib/test/test_winsound.py b/Lib/test/test_winsound.py index d013d8396cb..9724d830ade 100644 --- a/Lib/test/test_winsound.py +++ b/Lib/test/test_winsound.py @@ -100,7 +100,6 @@ def test_keyword_args(self): class PlaySoundTest(unittest.TestCase): - @unittest.expectedFailureIfWindows("TODO: RUSTPYTHON; TypeError: a bytes-like object is required, not 'str'") def test_errors(self): self.assertRaises(TypeError, winsound.PlaySound) self.assertRaises(TypeError, winsound.PlaySound, "bad", "bad") diff --git a/Lib/test/test_with.py b/Lib/test/test_with.py index f16611b29a2..60aaa5cd548 100644 --- a/Lib/test/test_with.py +++ b/Lib/test/test_with.py @@ -10,6 +10,7 @@ import unittest from collections import deque from contextlib import _GeneratorContextManager, contextmanager, nullcontext +from _testinternalcapi import SelfInterruptingContextManager def do_with(obj): @@ -850,5 +851,21 @@ def exit_raises(): expected) +class InterruptDuringEnter(unittest.TestCase): + + def test_exit_called_after_interrupt(self): + cm = SelfInterruptingContextManager() + self.assertFalse(cm.within()) + try: + with cm: + self.assertTrue(cm.within()) + except KeyboardInterrupt: + self.assertFalse(cm.within()) + return + except: + self.fail("Wrong exception raised") + self.fail("No exception raised") + + if __name__ == '__main__': unittest.main() diff --git a/Lib/test/test_wsgiref.py b/Lib/test/test_wsgiref.py index d84e7647adb..484a2db1637 100644 --- a/Lib/test/test_wsgiref.py +++ b/Lib/test/test_wsgiref.py @@ -1,6 +1,6 @@ from unittest import mock from test import support -from test.support import socket_helper, control_characters_c0 +from test.support import force_not_colorized, socket_helper, control_characters_c0 from test.test_httpservers import NoLogRequestHandler from unittest import TestCase from wsgiref.util import setup_testing_defaults @@ -66,6 +66,26 @@ def header_app(environ, start_response): ]).encode('iso-8859-1')] +def input_app(func_name, *args): + def app(e,s): + req = getattr(e['wsgi.input'], func_name)(*args) + s("200 OK", [("Content-Type", "text/plain; charset=utf-8")]) + if type(req) is list: + resp = b";".join(req) + else: + resp = req + return [resp] + return app + + +def errors_app(func_name, *args): + def app(e,s): + getattr(e['wsgi.errors'], func_name)(*args) + s("200 OK", [("Content-Type", "text/plain; charset=utf-8")]) + return [b"data"] + return app + + def run_amock(app=hello_app, data=b"GET / HTTP/1.0\n\n"): server = make_server("", 80, app, MockServer, MockHandler) inp = BufferedReader(BytesIO(data)) @@ -109,7 +129,7 @@ def check_hello(self, out, has_length=True): sys.version.split()[0]) self.assertEqual(out, ("HTTP/1.0 200 OK\r\n" - "Server: WSGIServer/0.2 " + pyver +"\r\n" + "Server: WSGIServer " + pyver + "\r\n" "Content-Type: text/plain\r\n" "Date: Mon, 05 Jun 2006 18:49:54 GMT\r\n" + (has_length and "Content-Length: 13\r\n" or "") + @@ -192,6 +212,96 @@ def bad_app(e,s): err.splitlines()[-2], "AssertionError" ) + def test_wsgi_input_read(self): + bad_app = input_app("read") + good_app = input_app("read", 5) + + out, err = run_amock(validator(bad_app)) + self.assertEndsWith(out, + b"A server error occurred. Please contact the administrator." + ) + + self.assertEqual( + err.splitlines()[-2], "AssertionError" + ) + + out, err = run_amock(validator(good_app), b"GET / HTTP/1.0\n\nTest 1\nTest 2\n") + self.assertEndsWith(out, b"Test ") + + def test_wsgi_input_readlines(self): + bad_app = input_app("readlines", 3, 5) + good_app = input_app("readlines", 1) + + out, err = run_amock(validator(bad_app)) + self.assertEndsWith(out, + b"A server error occurred. Please contact the administrator." + ) + self.assertEqual( + err.splitlines()[-2], "AssertionError" + ) + out, err = run_amock(validator(good_app), b"GET / HTTP/1.0\n\nTest Line 1\nTest Line 2\n") + self.assertEndsWith(out, b"Test Line 1\n") + + def test_wsgi_input_readline(self): + bad_app = input_app("readline", 3, 4) + good_app = input_app("readline", 2) + + out, err = run_amock(validator(bad_app)) + self.assertEndsWith(out, + b"A server error occurred. Please contact the administrator." + ) + self.assertEqual( + err.splitlines()[-2], "AssertionError" + ) + + out, err = run_amock(validator(good_app), b"GET / HTTP/1.0\n\nTest 1\nTest 2\n") + self.assertEndsWith(out, b"Te") + + def test_wsgi_input_close(self): + app = input_app("close") + out, err = run_amock(validator(app), b"GET / HTTP/1.0\n\nTest 1\nTest 2\n") + self.assertEqual(err.splitlines()[-2], 'AssertionError: input.close() must not be called') + self.assertEndsWith(out, b"A server error occurred. Please contact the administrator.") + + def test_wsgi_input_iter(self): + def app(e,s): + req = [] + for line in e['wsgi.input']: + req.append(line) + s("200 OK", [('Content-Type', 'text/plain; charser=utf-8')]) + return [b';'.join(req)] + + out, err = run_amock(validator(app), b"GET / HTTP/1.0\n\nTest 1\nTest 2\n") + self.assertEndsWith(out, b"Test 1\n;Test 2\n") + + def test_wsgi_errors_write(self): + bad_app = errors_app("write", b"Test") + good_app = errors_app("write", "Test") + + out, err = run_amock(validator(bad_app), b"GET / HTTP/1.0\n\n") + self.assertEqual(err.splitlines()[-2], 'AssertionError') + + out, err = run_amock(validator(good_app), b"GET / HTTP/1.0\n\n") + self.assertStartsWith(err, "Test") + + def test_wsgi_errors_writelines(self): + bad_app = errors_app("writelines", [1, "Test"]) + good_app = errors_app("writelines", ["Test", "Test"]) + + out, err = run_amock(validator(bad_app), b"GET / HTTP/1.0\n\n") + self.assertEqual(err.splitlines()[-2], 'AssertionError') + + out, err = run_amock(validator(good_app), b"GET / HTTP/1.0\n\n") + self.assertStartsWith(err, "TestTest") + + def test_wsgi_errors_close(self): + app = errors_app("close") + + out, err = run_amock(validator(app), b"GET / HTTP/1.0\n\n") + self.assertEqual(err.splitlines()[-2], + 'AssertionError: errors.close() must not be called') + + @force_not_colorized def test_bytes_validation(self): def app(e, s): s("200 OK", [ @@ -206,7 +316,7 @@ def app(e, s): pyver = py + b"/" + ver self.assertEqual( b"HTTP/1.0 200 OK\r\n" - b"Server: WSGIServer/0.2 "+ pyver + b"\r\n" + b"Server: WSGIServer " + pyver + b"\r\n" b"Content-Type: text/plain; charset=utf-8\r\n" b"Date: Wed, 24 Dec 2008 13:29:32 GMT\r\n" b"\r\n" @@ -448,10 +558,6 @@ def testHopByHop(self): for alt in hop, hop.title(), hop.upper(), hop.lower(): self.assertFalse(util.is_hop_by_hop(alt)) - @unittest.expectedFailure # TODO: RUSTPYTHON - def test_filewrapper_getitem_deprecation(self): - return super().test_filewrapper_getitem_deprecation() - class HeaderTests(TestCase): def testMappingInterface(self): @@ -879,5 +985,17 @@ def testRaisesControlCharacters(self): base.start_response('200 OK', [('x', c0)]) +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + from wsgiref import simple_server + + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(simple_server, "__version__") + self.assertEqual(cm.filename, __file__) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_xml.py b/Lib/test/test_xml.py new file mode 100644 index 00000000000..3a8b9204816 --- /dev/null +++ b/Lib/test/test_xml.py @@ -0,0 +1,43 @@ +import xml +import unittest + + +class TestUtils(unittest.TestCase): + + def test_is_valid_name(self): + is_valid_name = xml.is_valid_name + self.assertFalse(is_valid_name('')) + self.assertTrue(is_valid_name('name')) + self.assertTrue(is_valid_name('NAME')) + self.assertTrue(is_valid_name('name0:-._·')) + self.assertTrue(is_valid_name('_')) + self.assertTrue(is_valid_name(':')) + self.assertTrue(is_valid_name('Ñàḿĕ')) + self.assertTrue(is_valid_name('\U000EFFFF')) + self.assertFalse(is_valid_name('0')) + self.assertFalse(is_valid_name('-')) + self.assertFalse(is_valid_name('.')) + self.assertFalse(is_valid_name('·')) + self.assertFalse(is_valid_name('na me')) + for c in '<>/!?=\x00\x01\x7f\ud800\udfff\ufffe\uffff\U000F0000': + self.assertFalse(is_valid_name('name' + c)) + + def test_is_valid_text(self): + is_valid_text = xml.is_valid_text + self.assertTrue(is_valid_text('')) + self.assertTrue(is_valid_text('!0Aa_~ \r\n\t\x85\xa0')) + self.assertTrue(is_valid_text('\ud7ff\ue000\ufffd\U00010000\U0010ffff')) + self.assertFalse(is_valid_text('\x00')) + self.assertFalse(is_valid_text('\x01')) + self.assertFalse(is_valid_text('\x1f')) + self.assertTrue(is_valid_text('\x7f')) + self.assertTrue(is_valid_text('\x80')) + self.assertTrue(is_valid_text('\x9f')) + self.assertFalse(is_valid_text('\ud800')) + self.assertFalse(is_valid_text('\udfff')) + self.assertFalse(is_valid_text('\ufffe')) + self.assertFalse(is_valid_text('\uffff')) + + +if __name__ == '__main__': + unittest.main() diff --git a/Lib/test/test_xml_etree.py b/Lib/test/test_xml_etree.py index 7aa7d7ef480..2029d9954b0 100644 --- a/Lib/test/test_xml_etree.py +++ b/Lib/test/test_xml_etree.py @@ -370,8 +370,7 @@ def test_simpleops(self): self.serialize_check(element, '') # 4 element.remove(subelement) self.serialize_check(element, '') # 5 - with self.assertRaisesRegex(ValueError, - r'Element\.remove\(.+\): element not found'): + with self.assertRaises(ValueError): element.remove(subelement) self.serialize_check(element, '') # 6 element[0:0] = [subelement, subelement, subelement] @@ -382,6 +381,19 @@ def test_simpleops(self): self.serialize_check(element, '') + def test_positional_only_parameter(self): + # Test Element positional-only parameters (gh-144846). + + # 'tag' is positional-only + with self.assertRaises(TypeError): + ET.Element(tag='fail') + + # 'tag' and 'attrib' as kwarg/attribute names + e = ET.Element('e', attrib={'attrib': 'foo'}, tag='bar') + self.assertEqual(e.tag, 'e') + self.assertEqual(e.get('attrib'), 'foo') + self.assertEqual(e.get('tag'), 'bar') + def test_cdata(self): # Test CDATA handling (etc). @@ -485,6 +497,28 @@ def test_attrib(self): self.assertEqual(ET.tostring(elem), b'') + def test_subelement_positional_only_parameter(self): + # Test SubElement positional-only parameters (gh-144270). + parent = ET.Element('parent') + + # 'parent' and 'tag' are positional-only + with self.assertRaises(TypeError): + ET.SubElement(parent=parent, tag='fail') + with self.assertRaises(TypeError): + ET.SubElement(parent, tag='fail') + + # 'attrib' can be passed as keyword + sub1 = ET.SubElement(parent, 'sub1', attrib={'key': 'value'}) + self.assertEqual(sub1.get('key'), 'value') + + # 'tag' and 'parent' as kwargs become XML attributes, not func params + sub2 = ET.SubElement(parent, 'sub2', attrib={'attrib': 'foo'}, + tag='bar', parent='baz') + self.assertEqual(sub2.tag, 'sub2') + self.assertEqual(sub2.get('attrib'), 'foo') + self.assertEqual(sub2.get('tag'), 'bar') + self.assertEqual(sub2.get('parent'), 'baz') + def test_makeelement(self): # Test makeelement handling. @@ -591,7 +625,6 @@ def test_writefile(self): elem[0] = ET.PI("key", "value") self.serialize_check(elem, 'textsubtext') - @unittest.expectedFailure # TODO: RUSTPYTHON def test_custom_builder(self): # Test parser w. custom builder. @@ -813,6 +846,15 @@ def test_indent_space_caching(self): len({id(el.tail) for el in elem.iter()}), ) + def test_indent_non_xml_whitespace(self): + # only " \t\r\n" are whitespace in XML (see XML 1.0, 2.3) + elem = ET.XML('\xa0

text

\xa0') + ET.indent(elem) + self.assertEqual( + ET.tostring(elem), + b' \n

text

 \n' + ) + def test_indent_level(self): elem = ET.XML("

pre
post

text

") with self.assertRaises(ValueError): @@ -1027,6 +1069,69 @@ def bxml(encoding, body=''): self.assertRaises(ValueError, ET.XML, xml('undefined').encode('ascii')) self.assertRaises(LookupError, ET.XML, xml('xxx').encode('ascii')) + def test_parse_input_larger_than_chunk(self): + # gh-83895: the C implementation feeds Expat in chunks of 1 MiB + size = 3 * (1 << 20) + xml = '%s' % ('x' * size) + for source in xml, xml.encode(): + with self.subTest(type=type(source).__name__): + root = ET.fromstring(source) + self.assertEqual(len(root[0].text), size) + self.assertEqual(root[1].tag, 'b') + + # gh-83895: input larger than INT_MAX is fed to Expat in chunks. + # memuse is 3 for the Python implementation, which joins the collected + # data, 2 would be enough for the C implementation. + @support.bigmemtest(size=support._2G + 100, memuse=3, dry_run=False) + def test_large_input(self, size): + data = b'' + b'x' * size + b'' + root = None + try: + parser = ET.XMLParser() + parser.feed(data) + data = None + root = parser.close() + self.assertEqual(len(root.text), size) + finally: + data = None + root = None + + @unittest.expectedFailure # TODO: RUSTPYTHON; pyexpat error column is one byte early + def test_parse_error_after_chunk_boundary(self): + # the reported position accounts for the preceding chunks + size = 2 * (1 << 20) + with self.assertRaises(ET.ParseError) as cm: + ET.fromstring('%s<' % ('x' * size)) + self.assertEqual(cm.exception.position, (1, size + 4)) + + def test_parse_text_source(self): + # gh-99064: The encoding declared in the document does not apply + # to a source which is already decoded. + def check(encoding, body): + xml = (f"" + f"{body}") + with self.subTest(encoding=encoding): + self.assertEqual(ET.parse(io.StringIO(xml)).getroot().text, + body) + # the same with an explicitly created parser + self.assertEqual( + ET.parse(io.StringIO(xml), ET.XMLParser()).getroot().text, + body) + check("ascii", 'a') + check("iso-8859-1", '\xbd') + check("iso-8859-15", '\u20ac') + check("cp437", '\u221a') + check("utf-8", '\u4e2d') + # not ASCII compatible, unsupported for a bytes source + check("utf-16", '\u4e2d') + check("utf-32", '\u4e2d') + + def test_parse_text_source_multiple_chunks(self): + # the encoding is overridden before the first chunk is parsed + body = '\xe4' * 100_000 + xml = "%s" % body + self.assertEqual(ET.parse(io.StringIO(xml)).getroot().text, body) + def test_methods(self): # Test serialization methods. @@ -1255,6 +1360,9 @@ def test_comment_serialization(self): comm = ET.Comment(' & ham') # comments are not escaped self.assertEqual(ET.tostring(comm), b'') + self.assertEqual(ET.tostring(comm, method='html'), b'') + # no comments in text serialization + self.assertEqual(ET.tostring(comm, method='text'), b'') def test_processinginstruction_serialization(self): # Test ProcessingInstruction directly @@ -1271,6 +1379,17 @@ def test_processinginstruction_serialization(self): self.assertEqual(ET.tostring(ET.PI('test', '\xe3'), 'latin-1'), b"\n" b"\xe3?>") + pi = ET.PI('test', 'ham & eggs < spam') + self.assertEqual(ET.tostring(pi), b'') + self.assertEqual(ET.tostring(pi, method='html'), b'') + # no processing instructions in text serialization + self.assertEqual(ET.tostring(pi, method='text'), b'') + + def test_empty_attribute_serialization(self): + # empty attrs only work in html + elem = ET.Element('tag', attrib={'attr': None}) + self.assertRaises(TypeError, ET.tostring, elem) + self.assertEqual(ET.tostring(elem, method='html'), b'') @support.subTests('tag', ("script", "style", "xmp", "iframe", "noembed", "noframes")) def test_html_cdata_elems_serialization(self, tag): @@ -1439,7 +1558,6 @@ def test_unknown_events(self): del cm gc_collect() - @unittest.expectedFailure # TODO: RUSTPYTHON def test_non_utf8(self): source = io.BytesIO( b"\n" @@ -1452,7 +1570,6 @@ def test_non_utf8(self): ('start-ns', ('cl\xe9', 'http://effbot.org/ns')), ]) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_parsing_error(self): source = io.BytesIO(b"junk") it = ET.iterparse(source) @@ -1469,19 +1586,40 @@ def test_nonexistent_file(self): def test_resource_warnings_not_exhausted(self): # Not exhausting the iterator still closes the underlying file (bpo-43292) + # Not closing before del should emit ResourceWarning it = ET.iterparse(SIMPLE_XMLFILE) with warnings_helper.check_no_resource_warning(self): + it.close() del it gc_collect() + it = ET.iterparse(SIMPLE_XMLFILE) + with self.assertWarns(ResourceWarning) as wm: + del it + gc_collect() + # Not 'unclosed file'. + self.assertIn('unclosed iterparse iterator', str(wm.warning)) + self.assertIn(repr(SIMPLE_XMLFILE), str(wm.warning)) + self.assertEqual(wm.filename, __file__) + it = ET.iterparse(SIMPLE_XMLFILE) with warnings_helper.check_no_resource_warning(self): action, elem = next(it) + it.close() self.assertEqual((action, elem.tag), ('end', 'element')) del it, elem gc_collect() - @unittest.expectedFailure # TODO: RUSTPYTHON + it = ET.iterparse(SIMPLE_XMLFILE) + with self.assertWarns(ResourceWarning) as wm: + action, elem = next(it) + self.assertEqual((action, elem.tag), ('end', 'element')) + del it, elem + gc_collect() + self.assertIn('unclosed iterparse iterator', str(wm.warning)) + self.assertIn(repr(SIMPLE_XMLFILE), str(wm.warning)) + self.assertEqual(wm.filename, __file__) + def test_resource_warnings_failed_iteration(self): self.addCleanup(os_helper.unlink, TESTFN) with open(TESTFN, "wb") as f: @@ -1495,15 +1633,40 @@ def test_resource_warnings_failed_iteration(self): next(it) self.assertEqual(str(cm.exception), 'junk after document element: line 1, column 12') + it.close() del cm, it gc_collect() + it = ET.iterparse(TESTFN) + action, elem = next(it) + self.assertEqual((action, elem.tag), ('end', 'document')) + with self.assertWarns(ResourceWarning) as wm: + with self.assertRaises(ET.ParseError) as cm: + next(it) + self.assertEqual(str(cm.exception), + 'junk after document element: line 1, column 12') + del cm, it + gc_collect() + self.assertIn('unclosed iterparse iterator', str(wm.warning)) + self.assertIn(repr(TESTFN), str(wm.warning)) + self.assertEqual(wm.filename, __file__) + def test_resource_warnings_exhausted(self): it = ET.iterparse(SIMPLE_XMLFILE) with warnings_helper.check_no_resource_warning(self): + list(it) + it.close() + del it + gc_collect() + + it = ET.iterparse(SIMPLE_XMLFILE) + with self.assertWarns(ResourceWarning) as wm: list(it) del it gc_collect() + self.assertIn('unclosed iterparse iterator', str(wm.warning)) + self.assertIn(repr(SIMPLE_XMLFILE), str(wm.warning)) + self.assertEqual(wm.filename, __file__) def test_close_not_exhausted(self): iterparse = ET.iterparse @@ -1607,11 +1770,9 @@ def test_simple_xml(self, chunk_size=None, flush=False): self.assert_event_tags(parser, [('end', 'root')]) self.assertIsNone(parser.close()) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_simple_xml_chunk_1(self): self.test_simple_xml(chunk_size=1, flush=True) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_simple_xml_chunk_5(self): self.test_simple_xml(chunk_size=5, flush=True) @@ -1651,7 +1812,6 @@ def test_simple_xml_with_ns(self): self.assert_event_tags(parser, [('end', '{namespace}root')]) self.assertIsNone(parser.close()) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_ns_events(self): parser = ET.XMLPullParser(events=('start-ns', 'end-ns')) self._feed(parser, "\n") @@ -1667,7 +1827,6 @@ def test_ns_events(self): self.assertEqual(list(parser.read_events()), [('end-ns', None)]) self.assertIsNone(parser.close()) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_ns_events_start(self): parser = ET.XMLPullParser(events=('start-ns', 'start', 'end')) self._feed(parser, "\n") @@ -1691,7 +1850,6 @@ def test_ns_events_start(self): ('end', '{abc}tag'), ]) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_ns_events_start_end(self): parser = ET.XMLPullParser(events=('start-ns', 'start', 'end', 'end-ns')) self._feed(parser, "\n") @@ -2520,7 +2678,6 @@ def test_expat224_utf8_bug(self): text = b'x' + b'\xc3\xa0' * 1024 self.check_expat224_utf8_bug(text) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_expat224_utf8_bug_file(self): with open(UTF8_BUG_XMLFILE, 'rb') as fp: raw = fp.read() @@ -2755,6 +2912,17 @@ def test_pickle_issue18997(self): self.assertEqual(e2.tag, 'group') self.assertEqual(e2[0].tag, 'dogs') + def test_remove_errors(self): + e = ET.Element('tag') + with self.assertRaisesRegex(ValueError, + r" not in "): + e.remove(ET.Element('subtag')) + with self.assertRaisesRegex(TypeError, + r".*\bElement, not type"): + e.remove(ET.Element) + with self.assertRaisesRegex(TypeError, + r".*\bElement, not int"): + e.remove(1) class BadElementTest(ElementTestCase, unittest.TestCase): @@ -3143,7 +3311,7 @@ def __deepcopy__(self, memo): [a.tag, b.tag, a.tag, b.tag]) @unittest.skipIf(sys.platform == "win32", "TODO: RUSTPYTHON; stack overflow on Windows") - @support.skip_if_unlimited_stack_size + @support.run_with_limited_c_stack(500_000) @support.skip_emscripten_stack_overflow() @support.skip_wasi_stack_overflow() def test_deeply_nested_deepcopy(self): @@ -3374,6 +3542,37 @@ def test_find_xpath(self): self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()-0]') self.assertRaisesRegex(SyntaxError, 'XPath', e.find, './tag[last()+1]') + def test_find_xpath_index_no_quadratic_complexity(self): + class CountingElement(ET.Element): + findall_calls = 0 + def findall(self, *args, **kwargs): + type(self).findall_calls += 1 + return super().findall(*args, **kwargs) + + def work(n, pattern): + root = CountingElement("root") + for _ in range(n): + ET.SubElement(root, "a") + CountingElement.findall_calls = 0 + root.findall(pattern) + return CountingElement.findall_calls + + for pattern in [".//a[1]", ".//a[last()]"]: + w1 = work(1024, pattern) + w2 = work(2048, pattern) + w3 = work(4096, pattern) + + self.assertGreater(w1, 0) + r1 = w2 / w1 + r2 = w3 / w2 + # Doubling N must not ~double the parent.findall calls. + # Linear-in-N call counts indicate the cache is missing. + self.assertLess( + max(r1, r2), 1.5, + msg=f"Possible quadratic behavior on {pattern!r}: " + f"calls={w1, w2, w3} ratios={r1, r2}", + ) + def test_findall(self): e = ET.XML(SAMPLE_XML) e[2] = ET.XML(SAMPLE_SECTION) @@ -3902,7 +4101,6 @@ class MyElement(base, ValueError): pass self._check_element_factory_class(MyElement) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_doctype(self): class DoctypeParser: _doctype = None @@ -3920,6 +4118,21 @@ def close(self): ('html', '-//W3C//DTD XHTML 1.0 Transitional//EN', 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd')) + for doctype, expected in [ + ('', ('html', None, None)), + (']>', ('html', None, None)), + ('', ('html', None, 'a.dtd')), + (']>', + ('html', None, 'a.dtd')), + ('', ('html', '-//P', 'a.dtd')), + ("", + ('html', '-//P', 'a.dtd')), + ]: + with self.subTest(doctype=doctype): + parser = ET.XMLParser(target=DoctypeParser()) + parser.feed(doctype + '') + self.assertEqual(parser.close(), expected) + def test_builder_lookup_errors(self): class RaisingBuilder: def __init__(self, raise_in=None, what=ValueError): @@ -3980,7 +4193,6 @@ def test_doctype_warning(self): parser.feed(self.sample2) parser.close() - @unittest.expectedFailure # TODO: RUSTPYTHON def test_subclass_doctype(self): _doctype = None class MyParserWithDoctype(ET.XMLParser): @@ -4022,7 +4234,6 @@ class MyParserWithoutDoctype(ET.XMLParser): parser.feed(self.sample2) parser.close() - @unittest.expectedFailure # TODO: RUSTPYTHON def test_parse_string(self): parser = ET.XMLParser(target=ET.TreeBuilder()) parser.feed(self.sample3) @@ -4486,7 +4697,6 @@ def test_error_position(self): self.assertEqual(self._get_error('&foo;').position, (1, 5)) self.assertEqual(self._get_error('foobar<').position, (1, 6)) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_error_code(self): import xml.parsers.expat.errors as ERRORS self.assertEqual(self._get_error('foo').code, @@ -4514,6 +4724,9 @@ def test_issue14818(self): ET.Element('a', dict(href="#"), id="foo"), ET.Element('a', href="#", id="foo"), ET.Element('a', dict(href="#", id="foo"), href="#", id="foo"), + ET.Element('a', frozendict(href="#", id="foo")), + ET.Element('a', frozendict(href="#"), id="foo"), + ET.Element('a', attrib=frozendict(href="#", id="foo")), ] for e in elements: self.assertEqual(e.tag, 'a') @@ -4521,10 +4734,14 @@ def test_issue14818(self): e2 = ET.SubElement(elements[0], 'foobar', attrib={'key1': 'value1'}) self.assertEqual(e2.attrib['key1'], 'value1') + e3 = ET.SubElement(elements[0], 'foobar', + attrib=frozendict({'key1': 'value1'})) + self.assertEqual(e3.attrib['key1'], 'value1') - with self.assertRaisesRegex(TypeError, 'must be dict, not str'): + errmsg = 'must be dict or frozendict, not str' + with self.assertRaisesRegex(TypeError, errmsg): ET.Element('a', "I'm not a dict") - with self.assertRaisesRegex(TypeError, 'must be dict, not str'): + with self.assertRaisesRegex(TypeError, errmsg): ET.Element('a', attrib="I'm not a dict") # -------------------------------------------------------------------- @@ -4575,7 +4792,6 @@ class C14NTest(unittest.TestCase): # # simple roundtrip tests (from c14n.py) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_simple_roundtrip(self): # Basics self.assertEqual(c14n_roundtrip(""), '') @@ -4616,7 +4832,11 @@ def test_simple_roundtrip(self): xml = '' self.assertEqual(c14n_roundtrip(xml), xml) - @unittest.expectedFailure # TODO: RUSTPYTHON + def test_c14n_strip_non_xml_whitespace(self): + # only " \t\r\n" are whitespace in XML (see XML 1.0, 2.3) + self.assertEqual(c14n_roundtrip(" \xa0x\xa0 ", strip_text=True), + "\xa0x\xa0") + def test_c14n_exclusion(self): xml = textwrap.dedent("""\ @@ -4800,6 +5020,19 @@ def get_option(config, option_name, default=None): # -------------------------------------------------------------------- + +class TestModule(unittest.TestCase): + def test_deprecated_version(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'VERSION' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(ET, "VERSION") + self.assertEqual(cm.filename, __file__) + + +# -------------------------------------------------------------------- + def setUpModule(module=None): # When invoked without a module, runs the Python ET tests by loading pyET. # Otherwise, uses the given module as the ET. diff --git a/Lib/test/test_xml_etree_c.py b/Lib/test/test_xml_etree_c.py index f27056cca07..7f9cecbc450 100644 --- a/Lib/test/test_xml_etree_c.py +++ b/Lib/test/test_xml_etree_c.py @@ -15,16 +15,6 @@ @unittest.skipUnless(cET, 'requires _elementtree') class MiscTests(unittest.TestCase): - # Issue #8651. - @support.bigmemtest(size=support._2G + 100, memuse=1, dry_run=False) - def test_length_overflow(self, size): - data = b'x' * size - parser = cET.XMLParser() - try: - self.assertRaises(OverflowError, parser.feed, data) - finally: - data = None - def test_del_attribute(self): element = cET.Element('tag') @@ -271,16 +261,6 @@ class Temp(base): install_tests() -# The Python ET still fails these; the native accelerator does not. -class XMLPullParserTest(XMLPullParserTest): - @unittest.expectedSuccess - def test_simple_xml_chunk_1(self): - return super().test_simple_xml_chunk_1() - - @unittest.expectedSuccess - def test_simple_xml_chunk_5(self): - return super().test_simple_xml_chunk_5() - def setUpModule(): from test import test_xml_etree test_xml_etree.setUpModule(module=cET) diff --git a/Lib/test/test_xxlimited.py b/Lib/test/test_xxlimited.py index b52e78bc4fb..c6e9dc375d9 100644 --- a/Lib/test/test_xxlimited.py +++ b/Lib/test/test_xxlimited.py @@ -1,19 +1,39 @@ import unittest from test.support import import_helper -import types xxlimited = import_helper.import_module('xxlimited') -xxlimited_35 = import_helper.import_module('xxlimited_35') - -class CommonTests: - module: types.ModuleType - - def test_xxo_new(self): - xxo = self.module.Xxo() - - def test_xxo_attributes(self): - xxo = self.module.Xxo() +# if import of xxlimited succeeded, the other ones should be importable. +import xxlimited_3_13 +import xxlimited_35 + +MODULES = { + (3, 15): xxlimited, + (3, 13): xxlimited_3_13, + (3, 5): xxlimited_35, +} + +def test_with_xxlimited_modules(since=None, until=None): + def _decorator(func): + def _wrapper(self, *args, **kwargs): + for version, module in MODULES.items(): + if since and version < since: + continue + if until and version >= until: + continue + with self.subTest(version=version): + func(self, module, *args, **kwargs) + return _wrapper + return _decorator + +class XXLimitedTests(unittest.TestCase): + @test_with_xxlimited_modules() + def test_xxo_new(self, module): + xxo = module.Xxo() + + @test_with_xxlimited_modules() + def test_xxo_attributes(self, module): + xxo = module.Xxo() with self.assertRaises(AttributeError): xxo.foo with self.assertRaises(AttributeError): @@ -26,40 +46,61 @@ def test_xxo_attributes(self): with self.assertRaises(AttributeError): xxo.foo - def test_foo(self): + @test_with_xxlimited_modules() + def test_foo(self, module): # the foo function adds 2 numbers - self.assertEqual(self.module.foo(1, 2), 3) + self.assertEqual(module.foo(1, 2), 3) - def test_str(self): - self.assertIsSubclass(self.module.Str, str) - self.assertIsNot(self.module.Str, str) + @test_with_xxlimited_modules() + def test_str(self, module): + self.assertIsSubclass(module.Str, str) + self.assertIsNot(module.Str, str) - custom_string = self.module.Str("abcd") + custom_string = module.Str("abcd") self.assertEqual(custom_string, "abcd") self.assertEqual(custom_string.upper(), "ABCD") - def test_new(self): - xxo = self.module.new() + @test_with_xxlimited_modules() + def test_new(self, module): + xxo = module.new() self.assertEqual(xxo.demo("abc"), "abc") - -class TestXXLimited(CommonTests, unittest.TestCase): - module = xxlimited - - def test_xxo_demo(self): - xxo = self.module.Xxo() - other = self.module.Xxo() + @test_with_xxlimited_modules() + def test_xxo_demo(self, module): + xxo = module.Xxo() self.assertEqual(xxo.demo("abc"), "abc") + self.assertEqual(xxo.demo(0), None) + self.assertEqual(xxo.__module__, module.__name__) + with self.assertRaises(TypeError): + module.Xxo('arg') + with self.assertRaises(TypeError): + module.Xxo(kwarg='arg') + + @test_with_xxlimited_modules(since=(3, 13)) + def test_xxo_demo_extra(self, module): + xxo = module.Xxo() + other = module.Xxo() self.assertEqual(xxo.demo(xxo), xxo) self.assertEqual(xxo.demo(other), other) - self.assertEqual(xxo.demo(0), None) - def test_error(self): - with self.assertRaises(self.module.Error): - raise self.module.Error - - def test_buffer(self): - xxo = self.module.Xxo() + @test_with_xxlimited_modules(since=(3, 15)) + def test_xxo_subclass(self, module): + class Sub(module.Xxo): + pass + sub = Sub() + sub.a = 123 + self.assertEqual(sub.a, 123) + with self.assertRaisesRegex(AttributeError, "cannot set 'reserved'"): + sub.reserved = 123 + + @test_with_xxlimited_modules(since=(3, 13)) + def test_error(self, module): + with self.assertRaises(module.Error): + raise module.Error + + @test_with_xxlimited_modules(since=(3, 13)) + def test_buffer(self, module): + xxo = module.Xxo() self.assertEqual(xxo.x_exports, 0) b1 = memoryview(xxo) self.assertEqual(xxo.x_exports, 1) @@ -69,21 +110,13 @@ def test_buffer(self): self.assertEqual(b1[0], 1) self.assertEqual(b2[0], 1) - -class TestXXLimited35(CommonTests, unittest.TestCase): - module = xxlimited_35 - - def test_xxo_demo(self): - xxo = self.module.Xxo() - other = self.module.Xxo() - self.assertEqual(xxo.demo("abc"), "abc") - self.assertEqual(xxo.demo(0), None) - + @test_with_xxlimited_modules(until=(3, 5)) def test_roj(self): # the roj function always fails with self.assertRaises(SystemError): self.module.roj(0) + @test_with_xxlimited_modules(until=(3, 5)) def test_null(self): null1 = self.module.Null() null2 = self.module.Null() diff --git a/Lib/test/test_zipapp.py b/Lib/test/test_zipapp.py index 8fb0a68deba..88cc55716f5 100644 --- a/Lib/test/test_zipapp.py +++ b/Lib/test/test_zipapp.py @@ -366,6 +366,24 @@ def test_shebang_is_executable(self): zipapp.create_archive(str(source), str(target), interpreter='python') self.assertTrue(target.stat().st_mode & stat.S_IEXEC) + @unittest.skipIf(sys.platform == 'win32', + 'Windows does not support an executable bit') + @os_helper.skip_unless_working_chmod + def test_copied_archive_with_pathlike_target_is_executable(self): + # Test that copying an archive to a PathLike target makes it executable. + source = self.tmpdir / 'source' + source.mkdir() + (source / '__main__.py').touch() + target = self.tmpdir / 'source.pyz' + zipapp.create_archive(source, target, interpreter='python') + # Copying an archive uses a different code path than creating + # one from scratch. Ensure that the executable bit is set + # even if the target is a path-like object. + # See https://github.com/python/cpython/issues/156568 + new_target = self.tmpdir / 'changed.pyz' + zipapp.create_archive(target, new_target, interpreter='python') + self.assertTrue(new_target.stat().st_mode & stat.S_IEXEC) + @unittest.skipIf(sys.platform == 'win32', 'Windows does not support an executable bit') def test_no_shebang_is_not_executable(self): diff --git a/Lib/test/test_zipfile/__main__.py b/Lib/test/test_zipfile/__main__.py index e25ac946edf..90da74ade38 100644 --- a/Lib/test/test_zipfile/__main__.py +++ b/Lib/test/test_zipfile/__main__.py @@ -1,6 +1,6 @@ import unittest -from . import load_tests # noqa: F401 +from . import load_tests if __name__ == "__main__": diff --git a/Lib/test/test_zipfile/_path/__init__.py b/Lib/test/test_zipfile/_path/__init__.py index 8b137891791..e69de29bb2d 100644 --- a/Lib/test/test_zipfile/_path/__init__.py +++ b/Lib/test/test_zipfile/_path/__init__.py @@ -1 +0,0 @@ - diff --git a/Lib/test/test_zipfile/_path/test_path.py b/Lib/test/test_zipfile/_path/test_path.py index 351d9eefeb0..a6755ffa337 100644 --- a/Lib/test/test_zipfile/_path/test_path.py +++ b/Lib/test/test_zipfile/_path/test_path.py @@ -317,7 +317,7 @@ def test_mutability(self, alpharep): HUGE_ZIPFILE_NUM_ENTRIES = 2**13 def huge_zipfile(self): - """Create a read-only zipfile with a huge number of entries entries.""" + """Create a read-only zipfile with a huge number of entries.""" strm = io.BytesIO() zf = zipfile.ZipFile(strm, "w") for entry in map(str, range(self.HUGE_ZIPFILE_NUM_ENTRIES)): @@ -351,6 +351,21 @@ class Subclass(zipfile.Path): root = Subclass(alpharep) assert isinstance(root / 'b', Subclass) + def test_at(self): + zip_file = self.enterContext(zipfile.ZipFile(io.BytesIO(), 'w')) + root = zipfile.Path(zip_file) + assert root.at == '' + assert (root / 'foo' / 'bar').at == 'foo/bar' + + def test_str(self): + """ + An unnamed zip file is indicated by ":zipfile:" + """ + zip_file = self.enterContext(zipfile.ZipFile(io.BytesIO(), 'w')) + root = zipfile.Path(zip_file) + assert str(root) == ':zipfile:' + assert str(root / 'foo' / 'bar') == ':zipfile:/foo/bar' + @pass_alpharep def test_filename(self, alpharep): root = zipfile.Path(alpharep) diff --git a/Lib/test/test_zipfile/test_core.py b/Lib/test/test_zipfile/test_core.py index f9ad28ea04d..a969f9d5d9e 100644 --- a/Lib/test/test_zipfile/test_core.py +++ b/Lib/test/test_zipfile/test_core.py @@ -1,6 +1,7 @@ import _pyio import array import contextlib +import errno import importlib.util import io import itertools @@ -20,14 +21,15 @@ from random import randint, random, randbytes from test import archiver_tests -from test.support import script_helper, os_helper +from test.support import script_helper from test.support import ( findfile, requires_zlib, requires_bz2, requires_lzma, requires_zstd, captured_stdout, captured_stderr, requires_subprocess, cpython_only ) from test.support.os_helper import ( - TESTFN, unlink, rmtree, temp_dir, temp_cwd, fd_count, FakePath + TESTFN, unlink, rmtree, temp_dir, temp_cwd, fd_count, FakePath, + with_source_date_epoch, without_source_date_epoch, ) from test.support.import_helper import ensure_lazy_imports @@ -654,6 +656,12 @@ def test_add_file_after_2107(self): os.utime(TESTFN, (ts, ts)) except OverflowError: self.skipTest('Host fs cannot set timestamp to required value.') + except OSError as exc: + # Some file systems (e.g. UFS and ZFS on illumos) do not + # support timestamps that do not fit in 32 bits. + if exc.errno != errno.EOVERFLOW: + raise + self.skipTest('Host fs cannot set timestamp to required value.') mtime_ns = os.stat(TESTFN).st_mtime_ns if mtime_ns != (4386268800 * 10**9): @@ -1452,7 +1460,6 @@ def requiresWriteAccess(self, path): self.skipTest('requires write access to the installed location') unlink(filename) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_write_pyfile(self): self.requiresWriteAccess(os.path.dirname(__file__)) with TemporaryFile() as t, zipfile.PyZipFile(t, "w") as zipfp: @@ -1483,7 +1490,6 @@ def test_write_pyfile(self): self.assertNotIn(bn, zipfp.namelist()) self.assertCompiledIn(bn, zipfp.namelist()) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_write_python_package(self): import email packagedir = os.path.dirname(email.__file__) @@ -1498,7 +1504,6 @@ def test_write_python_package(self): self.assertCompiledIn('email/__init__.py', names) self.assertCompiledIn('email/mime/text.py', names) - @unittest.expectedFailure # TODO: RUSTPYTHON; - AttributeError: module 'os' has no attribute 'supports_effective_ids' def test_write_filtered_python_package(self): import test packagedir = os.path.dirname(test.__file__) @@ -1529,7 +1534,6 @@ def filter(path): print(reportStr) self.assertTrue('SyntaxError' not in reportStr) - @unittest.expectedFailure # TODO: RUSTPYTHON def test_write_with_optimization(self): import email packagedir = os.path.dirname(email.__file__) @@ -1880,29 +1884,24 @@ def test_writestr_extended_local_header_issue1202(self): zinfo.flag_bits |= zipfile._MASK_USE_DATA_DESCRIPTOR # Include an extended local header. orig_zip.writestr(zinfo, data) + @with_source_date_epoch(epoch=1735715999) def test_write_with_source_date_epoch(self): - with os_helper.EnvironmentVarGuard() as env: - # Set the SOURCE_DATE_EPOCH environment variable to a specific timestamp - env['SOURCE_DATE_EPOCH'] = "1735715999" - - with zipfile.ZipFile(TESTFN, "w") as zf: - zf.writestr("test_source_date_epoch.txt", "Testing SOURCE_DATE_EPOCH") + with zipfile.ZipFile(TESTFN, "w") as zf: + zf.writestr("test_source_date_epoch.txt", "Testing SOURCE_DATE_EPOCH") - with zipfile.ZipFile(TESTFN, "r") as zf: - zip_info = zf.getinfo("test_source_date_epoch.txt") - expected_utc = (2025, 1, 1, 7, 19, 58) - self.assertEqual(zip_info.date_time, expected_utc) + with zipfile.ZipFile(TESTFN, "r") as zf: + zip_info = zf.getinfo("test_source_date_epoch.txt") + expected_utc = (2025, 1, 1, 7, 19, 58) + self.assertEqual(zip_info.date_time, expected_utc) + @without_source_date_epoch def test_write_without_source_date_epoch(self): - with os_helper.EnvironmentVarGuard() as env: - del env['SOURCE_DATE_EPOCH'] - - with zipfile.ZipFile(TESTFN, "w") as zf: - zf.writestr("test_no_source_date_epoch.txt", "Testing without SOURCE_DATE_EPOCH") + with zipfile.ZipFile(TESTFN, "w") as zf: + zf.writestr("test_no_source_date_epoch.txt", "Testing without SOURCE_DATE_EPOCH") - with zipfile.ZipFile(TESTFN, "r") as zf: - zip_info = zf.getinfo("test_no_source_date_epoch.txt") - self.assertTimestampAlmostEqual(time.localtime(), zip_info.date_time, tolerance=2) + with zipfile.ZipFile(TESTFN, "r") as zf: + zip_info = zf.getinfo("test_no_source_date_epoch.txt") + self.assertTimestampAlmostEqual(time.localtime(), zip_info.date_time, tolerance=2) def assertTimestampAlmostEqual(self, time1, time2, tolerance): import datetime @@ -2444,6 +2443,8 @@ def test_open_conflicting_handles(self): zipf.writestr('str', 'abcde') with self.assertRaises(ValueError): zipf.write(__file__, 'file') + with self.assertRaises(ValueError): + zipf.mkdir('directory') with self.assertRaises(ValueError): zipf.close() w1.write(msg2) @@ -2720,6 +2721,115 @@ def tearDown(self): unlink(TESTFN2) +class AbstractBoundedDecompressTests: + # ZipExtFile._read1() bounds the output of each decompress() call so that a + # small member declaring a large uncompressed size cannot expand into one + # unbounded read. + def test_read1_output_is_bounded(self): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", compression=self.compression) as zf: + zf.writestr("big", b"\0" * (4 * 1024 * 1024)) + with zipfile.ZipFile(io.BytesIO(buf.getvalue())) as zf: + with zf.open("big") as f: + self.assertLessEqual(len(f._read1(100)), f.MIN_READ_SIZE) + + +class StoredBoundedDecompressTests(AbstractBoundedDecompressTests, + unittest.TestCase): + compression = zipfile.ZIP_STORED + + +@requires_zlib() +class DeflateBoundedDecompressTests(AbstractBoundedDecompressTests, + unittest.TestCase): + compression = zipfile.ZIP_DEFLATED + + +@requires_bz2() +class Bzip2BoundedDecompressTests(AbstractBoundedDecompressTests, + unittest.TestCase): + compression = zipfile.ZIP_BZIP2 + + +@requires_lzma() +class LzmaBoundedDecompressTests(AbstractBoundedDecompressTests, + unittest.TestCase): + compression = zipfile.ZIP_LZMA + + +@requires_zstd() +class ZstdBoundedDecompressTests(AbstractBoundedDecompressTests, + unittest.TestCase): + compression = zipfile.ZIP_ZSTANDARD + + +class MonkeypatchedDecompressorTests(unittest.TestCase): + # Some third-party projects monkey-patch _get_decompressor() to add + # additional compression schemes. This can break at any time as the + # internal compressor objects change. + # To protect users, we try to keep this case working. + # See also: GH-156002 and GH-113767. + COMPRESSION = 99 + + class Compressor: + """Compressor with only the original BZ2Compressor API""" + def compress(self, data): + return data.swapcase() + + def flush(self): + return b'' + + class Decompressor: + """Decompressor with only the 3.3+ BZ2Decompressor API""" + eof = False + + def decompress(self, data): + return data.swapcase() + + def setUp(self): + orig_check_compression = zipfile._check_compression + orig_get_compressor = zipfile._get_compressor + orig_get_decompressor = zipfile._get_decompressor + + def check_compression(compression): + if compression != self.COMPRESSION: + orig_check_compression(compression) + + def get_compressor(compress_type, compresslevel=None): + if compress_type == self.COMPRESSION: + return self.Compressor() + return orig_get_compressor(compress_type, compresslevel) + + def get_decompressor(compress_type): + if compress_type == self.COMPRESSION: + return self.Decompressor() + return orig_get_decompressor(compress_type) + + self.enterContext(mock.patch.object( + zipfile, '_check_compression', check_compression)) + self.enterContext(mock.patch.object( + zipfile, '_get_compressor', get_compressor)) + self.enterContext(mock.patch.object( + zipfile, '_get_decompressor', get_decompressor)) + + def test_roundtrip_monkeypatched_decompressor(self): + data = bytes(range(256)) * 8 + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w", compression=self.COMPRESSION) as zf: + zf.writestr("member", data) + self.assertIn(data.swapcase(), buf.getvalue()) + with zipfile.ZipFile(io.BytesIO(buf.getvalue())) as zf: + self.assertEqual(zf.read("member"), data) + with zf.open("member") as f: + self.assertEqual(f.read(100), data[:100]) + self.assertEqual(f.read1(100), data[100:200]) + f.seek(-100, os.SEEK_END) + self.assertEqual(f.read(), data[-100:]) + # Rewinding past the read buffer re-creates the decompressor. + f.seek(0) + self.assertEqual(f.read(), data) + + class AbstractBadCrcTests: def test_testzip_with_bad_crc(self): """Tests that files with bad CRCs return their name from testzip.""" @@ -3364,6 +3474,9 @@ def test_mkdir(self): zf.extractall(target) self.assertEqual(set(os.listdir(target)), {"directory", "directory2", "directory3", "directory4"}) + with self.assertRaises(ValueError): + zf.mkdir("closed") + def test_create_directory_with_write(self): with zipfile.ZipFile(TESTFN, "w") as zf: zf.writestr(zipfile.ZipInfo('directory/'), '') diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py index d448e3df5d7..46e9a256811 100644 --- a/Lib/test/test_zipimport.py +++ b/Lib/test/test_zipimport.py @@ -15,7 +15,7 @@ from test.support import import_helper from test.support import os_helper -from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED +from zipfile import ZipFile, ZipInfo, ZIP_STORED, ZIP_DEFLATED, ZIP_ZSTANDARD import zipimport import linecache @@ -61,7 +61,6 @@ def module_path_to_dotted_name(path): TEMP_ZIP = os.path.abspath("junk95142.zip") TEST_DATA_DIR = os.path.join(os.path.dirname(__file__), "zipimport_data") -pyc_file = importlib.util.cache_from_source(TESTMOD + '.py') pyc_ext = '.pyc' @@ -194,24 +193,118 @@ def testAFakeZlib(self): # occur in that case (builtin modules are always found first), # so we'll simply skip it then. Bug #765456. # - if "zlib" in sys.builtin_module_names: - self.skipTest('zlib is a builtin module') - if "zlib" in sys.modules: - del sys.modules["zlib"] - files = {"zlib.py": test_src} + if self.compression == ZIP_DEFLATED: + mod_name = "zlib" + if zipimport._zlib_decompress: # validate attr name + # reset the cached import to avoid test order dependencies + zipimport._zlib_decompress = None # reset cache + elif self.compression == ZIP_ZSTANDARD: + mod_name = "_zstd" + if zipimport._zstd_decompressor_class: # validate attr name + # reset the cached import to avoid test order dependencies + zipimport._zstd_decompressor_class = None + else: + mod_name = "zlib" # the ZIP_STORED case below + + if mod_name in sys.builtin_module_names: + self.skipTest(f"{mod_name} is a builtin module") + if mod_name in sys.modules: + del sys.modules[mod_name] + files = {f"{mod_name}.py": test_src} try: - self.doTest(".py", files, "zlib") + self.doTest(".py", files, mod_name) except ImportError: - if self.compression != ZIP_DEFLATED: - self.fail("expected test to not raise ImportError") - else: if self.compression != ZIP_STORED: - self.fail("expected test to raise ImportError") + # Expected - fake compression module can't decompress + pass + else: + self.fail("expected test to not raise ImportError for uncompressed") + else: + if self.compression == ZIP_STORED: + # Expected - no compression needed, so fake module works + pass + else: + self.fail("expected test to raise ImportError for compressed zip with fake compression module") def testPy(self): files = {TESTMOD + ".py": test_src} self.doTest(".py", files, TESTMOD) + def test_syntax_warning(self): + files = {TESTMOD + ".py": "x = 1 is 1\n"} + self.makeZip(files) + zi = zipimport.zipimporter(TEMP_ZIP) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", SyntaxWarning) + spec = zi.find_spec(TESTMOD) + self.assertIsNotNone(spec) + self.assertEqual(caught, []) + + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + + self.assertEqual(len(caught), 1) + self.assertIsInstance(caught[0].message, SyntaxWarning) + + def test_syntax_error_defers_to_exec(self): + files = {TESTMOD + ".py": "x =\n"} + self.makeZip(files) + zi = zipimport.zipimporter(TEMP_ZIP) + expected_path = os.path.join(TEMP_ZIP, TESTMOD + ".py") + + spec = zi.find_spec(TESTMOD) + self.assertIsNotNone(spec) + self.assertEqual(spec.origin, expected_path) + self.assertEqual(zi.get_filename(TESTMOD), expected_path) + + mod = importlib.util.module_from_spec(spec) + with self.assertRaises(SyntaxError): + spec.loader.exec_module(mod) + + def test_get_filename_no_warnings(self): + files = {TESTMOD + ".py": "x = 1 is 1\n"} + self.makeZip(files) + zi = zipimport.zipimporter(TEMP_ZIP) + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", SyntaxWarning) + zi.get_filename(TESTMOD) + + self.assertEqual(caught, []) + + def test_syntax_error_in_source_with_valid_pyc(self): + bad_src = "x =\n" + files = {TESTMOD + ".py": bad_src, + TESTMOD + pyc_ext: make_pyc(test_co, NOW, len(bad_src))} + self.makeZip(files) + zi = zipimport.zipimporter(TEMP_ZIP) + expected_path = os.path.join(TEMP_ZIP, TESTMOD + pyc_ext) + + spec = zi.find_spec(TESTMOD) + self.assertIsNotNone(spec) + self.assertEqual(spec.origin, expected_path) + + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + self.assertEqual(mod.get_file(), expected_path) + + def test_syntax_error_in_package_init_no_fallthrough(self): + packdir = TESTPACK + os.sep + files = {packdir + "__init__.py": "x =\n", + TESTPACK + ".py": test_src} + self.makeZip(files) + zi = zipimport.zipimporter(TEMP_ZIP) + expected_path = os.path.join(TEMP_ZIP, TESTPACK, "__init__.py") + + spec = zi.find_spec(TESTPACK) + self.assertIsNotNone(spec) + self.assertEqual(spec.origin, expected_path) + + mod = importlib.util.module_from_spec(spec) + with self.assertRaises(SyntaxError): + spec.loader.exec_module(mod) + def testPyc(self): files = {TESTMOD + pyc_ext: test_pyc} self.doTest(pyc_ext, files, TESTMOD) @@ -556,13 +649,6 @@ def testZipImporterMethods(self): self.assertEqual(zi.archive, TEMP_ZIP) self.assertTrue(zi.is_package(TESTPACK)) - # PEP 302 - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - - mod = zi.load_module(TESTPACK) - self.assertEqual(zi.get_filename(TESTPACK), mod.__file__) - # PEP 451 spec = zi.find_spec('spam') self.assertIsNotNone(spec) @@ -577,6 +663,8 @@ def testZipImporterMethods(self): spec.loader.exec_module(mod) self.assertEqual(zi.get_filename(TESTPACK), mod.__file__) + sys.path.insert(0, TEMP_ZIP) + existing_pack_path = importlib.import_module(TESTPACK).__path__[0] expected_path_path = os.path.join(TEMP_ZIP, TESTPACK) self.assertEqual(existing_pack_path, expected_path_path) @@ -675,11 +763,6 @@ def testZipImporterMethodsInSubDirectory(self): self.assertEqual(zi.archive, TEMP_ZIP) self.assertEqual(zi.prefix, packdir) self.assertTrue(zi.is_package(TESTPACK2)) - # PEP 302 - with warnings.catch_warnings(): - warnings.simplefilter("ignore", DeprecationWarning) - mod = zi.load_module(TESTPACK2) - self.assertEqual(zi.get_filename(TESTPACK2), mod.__file__) # PEP 451 spec = zi.find_spec(TESTPACK2) mod = importlib.util.module_from_spec(spec) @@ -702,9 +785,12 @@ def testZipImporterMethodsInSubDirectory(self): self.assertEqual( spec.loader.get_filename(TESTMOD), load_mod.__file__) + sys.path.insert(0, TEMP_ZIP + os.sep + TESTPACK) + mod_path = TESTPACK2 + os.sep + TESTMOD mod_name = module_path_to_dotted_name(mod_path) mod = importlib.import_module(mod_name) + self.assertTrue(mod_name in sys.modules) self.assertIsNone(zi.get_source(TESTPACK2)) self.assertIsNone(zi.get_source(mod_path)) @@ -1010,10 +1096,71 @@ def assertDataEntry(name): @support.requires_zlib() -class CompressedZipImportTestCase(UncompressedZipImportTestCase): +class DeflateCompressedZipImportTestCase(UncompressedZipImportTestCase): compression = ZIP_DEFLATED +@support.requires_zstd() +class ZStdCompressedZipImportTestCase(UncompressedZipImportTestCase): + compression = ZIP_ZSTANDARD + + def test_concatenated_frames(self): + from compression import zstd + import zipfile + + class ConcatenatedFrameCompressor: + def compress(self, data): + return b"".join(zstd.compress(bytes([byte])) for byte in data) + + def flush(self): + return b"" + + with unittest.mock.patch.object( + zipfile, + "_get_compressor", + return_value=ConcatenatedFrameCompressor(), + ): + self.doTest(".py", {TESTMOD + ".py": test_src}, TESTMOD) + + def test_concatenated_frames_linear_input(self): + from compression import zstd + + frame_count = 100 + frame = zstd.compress(b"x") + compressed = frame * frame_count + input_sizes = [] + decompressor_class = zipimport._get_zstd_decompressor_class() + + class RecordingDecompressor: + def __init__(self): + self._decompressor = decompressor_class() + + def __getattr__(self, name): + return getattr(self._decompressor, name) + + def decompress(self, data, max_length=-1): + input_sizes.append(memoryview(data).nbytes) + return self._decompressor.decompress(data, max_length) + + with unittest.mock.patch.object( + zipimport, "_zstd_decompressor_class", RecordingDecompressor + ): + self.assertEqual( + zipimport._zstd_decompress(compressed), b"x" * frame_count + ) + + self.assertEqual(sum(input_sizes), len(compressed)) + + def test_truncated_frame(self): + from compression import zstd + + compressed = zstd.compress(b"x") + for data in (b"", compressed[:-1]): + with self.subTest(data=data): + with self.assertRaises(zipimport.ZipImportError): + zipimport._zstd_decompress(data) + + class BadFileZipImportTestCase(unittest.TestCase): def assertZipFailure(self, filename): self.assertRaises(zipimport.ZipImportError, @@ -1061,6 +1208,24 @@ def testNotZipFile(self): fp.close() self.assertZipFailure(TESTMOD) + def testInvalidUTF8FileName(self): + # A UTF-8-flagged file name that is not valid UTF-8 raises ZipImportError. + UTF8_FLAG = 0x800 + name = b'\xff\xfe\xff' + cdh = b'PK\x01\x02' + struct.pack( + '=4 GiB are handled correctly. class ChecksumBigBufferTestCase(unittest.TestCase): @@ -611,6 +722,20 @@ def test_decompress_eof_incomplete_stream(self): dco.flush() self.assertFalse(dco.eof) + def test_decompress_flush_corrupt_stream(self): + x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo' + corrupt = x[:-1] + b'\x00' + dco = zlib.decompressobj() + self.assertEqual(dco.decompress(corrupt, 1), b'f') + self.assertRaises(zlib.error, dco.flush) + + def test_decompress_flush_twice(self): + x = b'x\x9cK\xcb\xcf\x07\x00\x02\x82\x01E' # 'foo' + dco = zlib.decompressobj() + self.assertEqual(dco.decompress(x), b'foo') + self.assertEqual(dco.flush(), b'') + self.assertEqual(dco.flush(), b'') + def test_decompress_unused_data(self): # Repeated calls to decompress() after EOF should accumulate data in # dco.unused_data, instead of just storing the arg to the last call. @@ -637,6 +762,18 @@ def test_decompress_unused_data(self): self.assertEqual(dco.unconsumed_tail, b'') self.assertEqual(dco.unused_data, remainder) + def test_decompress_unconsumed_tail_after_eof(self): + source = b'abcdefghijklmnopqrstuvwxyz' + remainder = b'0123456789' + dco = zlib.decompressobj() + data = dco.decompress(zlib.compress(source) + remainder, 1) + data += dco.decompress(dco.unconsumed_tail) + + self.assertTrue(dco.eof) + self.assertEqual(data, source) + self.assertEqual(dco.unconsumed_tail, b'') + self.assertEqual(dco.unused_data, remainder) + # issue27164 def test_decompress_raw_with_dictionary(self): zdict = b'abcdefghijklmnopqrstuvwxyz' @@ -982,7 +1119,7 @@ def testEOFError(self): self.assertRaises(EOFError, zlibd.decompress, b"") @support.skip_if_pgo_task - @bigmemtest(size=_4G + 100, memuse=3.3) + @bigmemtest(size=_4G + 100, memuse=4.5) def testDecompress4G(self, size): # "Test zlib._ZlibDecompressor.decompress() with >4GiB input" blocksize = min(10 * 1024 * 1024, size) @@ -1114,5 +1251,15 @@ def __index__(self): return 100 +class TestModule(unittest.TestCase): + def test_deprecated__version__(self): + with self.assertWarnsRegex( + DeprecationWarning, + "'__version__' is deprecated and slated for removal in Python 3.20", + ) as cm: + getattr(zlib, "__version__") + self.assertEqual(cm.filename, __file__) + + if __name__ == "__main__": unittest.main() diff --git a/Lib/test/test_zoneinfo/data/update_test_data.py b/Lib/test/test_zoneinfo/data/update_test_data.py index f531ab316a1..cf1b1eff4fe 100644 --- a/Lib/test/test_zoneinfo/data/update_test_data.py +++ b/Lib/test/test_zoneinfo/data/update_test_data.py @@ -120,3 +120,6 @@ def update_test_data(fname: str = "zoneinfo_data.json") -> None: if __name__ == "__main__": update_test_data() + + print("Remember to update the HAS_TZDATA_PKG version requirement in " + "test_zoneinfo.py!") diff --git a/Lib/test/test_zoneinfo/data/zoneinfo_data.json b/Lib/test/test_zoneinfo/data/zoneinfo_data.json index ec4414a0cde..6c9bf09e12f 100644 --- a/Lib/test/test_zoneinfo/data/zoneinfo_data.json +++ b/Lib/test/test_zoneinfo/data/zoneinfo_data.json @@ -1,190 +1,218 @@ { "data": { "Africa/Abidjan": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j-~f{VGF<>F7KxBg5R*{Ksocg8-YYVul=v7vZzaHN", - "uC=da5UI2rH18c!OnjV{y4u(+A!!VBKmY&$ORw>7UO^(500B;v0RR91bXh%WvBYQl0ssI2", - "00dcD" + "{Wp48S^xk9=GL@E0stWa761SMbT8$j-~f{VGF<>F7KxBg5R*{Ksocg8-", + "YYVul=v7vZzaHNuC=da5UI2rH18c!OnjV{y4u(+A!!VBKmY&$ORw>7UO^(500B;v0RR91b", + "Xh%WvBYQl0ssI200dcD" ], "Africa/Casablanca": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j;0b&Kz+C_;7KxBg5R*{N&yjMUR~;C-fDaSOU;q-~", - "FqW+4{YBjbcw}`a!dW>b)R2-0a+uwf`P3{_Y@HuCz}S$J$ZJ>R_V<~|Fk>sgX4=%0vUrh-", - "lt@YP^Wrus;j?`Th#xRPzf<<~Hp4DH^gZX>d{+WOp~HNu8!{uWu}&XphAd{j1;rB4|9?R!", - "pqruAFUMt8#*WcrVS{;kLlY(cJRV$w?d2car%Rs>q9BgTU4", - "Ht-tQKZ7Z`9QqOb?R#b%z?rk>!CkH7jy3wja4NG2q)H}fNRKg8v{);Em;K3Cncf4C6&Oaj", - "V+DbX%o4+)CV3+e!Lm6dutu(0BQpH1T?W(~cQtKV*^_Pdx!LirjpTs?Bmt@vktjLq4;)O!", - "rrly=c*rwTwMJFd0I57`hgkc?=nyI4RZf9W$6DCWugmf&)wk^tWH17owj=#PGH7Xv-?9$j", - "njwDlkOE+BFNR9YXEmBpO;rqEw=e2IR-8^(W;8ma?M3JVd($2T>IW+0tk|Gm8>ftukRQ9J", - "8k3brzqMnVyjsLI-CKneFa)Lxvp_aq40f}0J3VVoWL5rox", - "`Kptivcp}o5xA^@>qNI%?zo=Yj4AMV?kbAA)j(1%)+Pp)bSn+7Yk`M{oE}L-Z!G6OMr5G+h", - "p)$3Lg{ono{4cN>Vr&>L4kXH;_VnBL5U!LgzqE%P7QQ*tue}O`3(TZ0`aKn&~8trOQ-rBXCp)f@P6RMO4l0+;b|5-pk9_ryNh}Zc*v%mvz_#", - "yd6fjB0g9{MmMnu8bG%#C~ugXK^S^k@?ab#", - "O|aE>dDTt4s4n69(~@t~!wniV%g7khFx~I*4>Y|V$4j5%KPF*-FyKIi@!Ho&", - "x8QQsksYt8)D+W)Ni!=G`ogSu^vLL-l#7A7=iIAKL2SuZk9F}NfNk86VI)9WZE?%2wC-ya", - "F~z#Qsq)LH0|_D8^5fU8X%GeQ4TB>R-dlziA&tZe&1ada208!$nk`7bOFO2S00Gb)R2-", + "0a+uwf`P3{_Y@HuCz}S$J$ZJ>R_V<~|Fk>sgX4=%0vUrh-lt@YP^Wrus;j?`Th#xRPzf<<", + "~Hp4DH^gZX>d{+WOp~HNu8!{uWu}&XphAd{j1;rB4|9?R!pqruAFUMt8#*WcrVS{;kLlY(", + "cJRV$w?d2car%Rs>q9BgTU4Ht-tQKZ7Z`9QqOb?R#b%z?rk", + ">!CkH7jy3wja4NG2q)H}fNRKg8v{);Em;K3Cncf4C6&OajV+DbX%o4+)CV3+e!Lm6dutu(", + "0BQpH1T?W(~cQtKV*^_Pdx!LirjpTs?Bmt@vktjLq4;)O!rrly=c*rwTwMJFd0I57`hgkc", + "?=nyI4RZf9W$6DCWugmf&)wk^tWH17owj=#PGH7Xv-", + "?9$jnjwDlkOE+BFNR9YXEmBpO;rqEw=e2IR-", + "8^(W;8ma?M3JVd($2T>IW+0tk|Gm8>ftukRQ9J8k3brzqMnVyjsLI-CKneFa)Lxvp_aq40f}0J3VVoWL5rox`Kptivcp}o5", + "xA^@>qNI%?zo=Yj4AMV?kbAA)j(1%)+Pp)bSn+7Yk`M{oE}L-Z!G6OMr5G+hp)$", + "3Lg{ono{4cN>Vr&>L4kXH;_VnBL5U!LgzqE%P7QQ*tue}O`3(TZ0`aKn&~8trOQ-rBXCp)f@P6RMO4l0+;b|5-", + "pk9_ryNh}Zc*v%mvz_#yd6fjB0g9{MmMnu8bG%#C~ugXK^S^k@?ab#O|aE>dDTt4s4n69(~@t~!wni", + "V%g7khFx~I*4>Y|V$4j5%KPF*-", + "FyKIi@!Ho&x8QQsksYt8)D+W)Ni!=G`ogSu^vLL-", + "l#7A7=iIAKL2SuZk9F}NfNk86VI)9WZE?%2wC-yaF~z#Qsq)LH0|_D8^5fU8X%GeQ4TB>R", + "-dlziA&tZe&1ada208!$nk`7bOFO2S00GH)lhRYu$%jt%!jv+I", "JxhE=%W1?wYb!37Rb?(rgwFIAQI{L#8r*zy!$TMtER_1(vn(Zix^{AVB1(jwr$iL6h0Z!2", "8Gb~UW@0~e512{Z%8}Qzdnjl~wJ1{c2>`Z@1A~t&lyL{p{eM{5)QGf7Mo5FW9==mlyXJt2", - "UwpntR7H0eSq!(aYq#aqUz&RM*tvuMI)AsM?K3-dV3-TT{t)!Iy#JTo=tXkzAM9~j2YbiO", - "ls3(H8Dc>Y|D1aqL51vjLbpYG;GvGTQB4bXuJ%mA;(B4eUpu$$@zv2vVcq-Y)VKbzp^tei", - "uzy}R{LuvDjpuVb`79O+CBmg{Wx!bvx$eu4zRE&", - "PehMb=&G<9$>iZ|bFE)0=4I?KLFGBC0I(0_svgw0%FiMsT%koo*!nEYc6GY@QnU}&4Isg;", - "l=|khi(!VaiSE2=Ny`&&tpi~~;{$uN}%f|7mBhAy;s3YT^sy!$eG~?`9mNJC9@4Bac_p^BZh)Yd_rWW5qh-?tKY(>5VHO", - "L*iT8P@wCavLj^yYbnDR+4ukhS+xPrpl)iqB?u)bj9a2aW==g6G3lCJd>(+Blfr)~^40F4f>cRZ^UF;RibfZ>0m73hR", - "C{$vTfC(STN`g7(B<=Z2556{}0`?p&|Akkst!4Xy4OT;A@c$XTUI3FRRjy*KA7uC56FD)z", - "^X{WV*sr(w!c$W357o!&eLO2wTDNOyw@gf(&R<t;=-Tu1TV{>%8ZVATC9tjD8|(&`$9YHvZ9bVe#>w", - "|8c;Tg|xE&)`*}LwM*E}q}q8^Qja%p`_U)*5DdLI9O@!e=3jFjOCrCq28b_bb;s>%D#iJB", - "CWJi{JH!Js;6nfayos$kq^OEX00HO-lokL0!mqm{vBYQl0ssI200dcD" + "UwpntR7H0eSq!(aYq#aqUz&RM*tvuMI)AsM?K3-dV3-", + "TT{t)!Iy#JTo=tXkzAM9~j2YbiOls3(H8Dc>Y|D1aqL51vjLbpYG;GvGTQB4bXuJ%mA;(B", + "4eUpu$$@zv2vVcq-", + "Y)VKbzp^teiuzy}R{LuvDjpuVb`79O+CBmg{Wx!", + "bvx$eu4zRE&PehMb=&G<9$>iZ|bFE)0=4I?KLFGBC0I(0_svgw0%FiMsT%koo*!nEYc6GY", + "@QnU}&4Isg;l=|khi(!VaiSE2=Ny`&&tpi~~;{$uMiozmmC;M)^ZwTGGtj|3E=aVrD5Bqa^;RV?wWs=hsohk2ql1XcqaOW|", + "E4urOCR0a_;Id)cJ-GU5w3iJ10Aox!FH|8SHoiD_{JMEEOV0O?MDsDaI;Y>v=$rgN_q~t`", + ";bL0p0cr+3oR<~L*q!A1N=YxYRoqaQo%ua#07hqE;U_X@B)L3Jd;2oN%}66Gz+0zO^<`*Jt_si5v;Qg-", + "3q})ae)#%Dl>20mc9;6%A4(VObs;0JpQAGD7ADLJ?Rqiv#V5ZljDomsklGi_^8gtLkmRF>EstlBz)cI_>MG*?Z%S", + "T;72Q8^Ku7t$MI_A1{5SEE>mII;1T8kfJf_FgrXNwx!AelhM`I@+>J+gg!uCyW&Vjnd0r~", + "xZpKPsHdS4@$h%w6Eq6>tdfnmQLWvk`|e2>DM-E4Qm9Nc-", + "(V_Gh@)x^Nj3H9p`fLm1IA_eaBVtRg`l1J@5pcFi$-", + "31XWMxJ!;}xqC^I};&9=Az*&VH*lfN0M|Gx-9!ypV67!-KSwt=VI-*jej4FC~WiMTU+-", + "L<2+d_ew|{n~!VJuGlSJ0d_=`@?_jC3h)r_?|J_;aJ|`U^>F6N?3pcY069b8yy#(^>pP8L", + "*@Vg?IIMosq$u-00HX=q!s`G%_Rg?vBYQl0ssI200dcD" ], "America/Santiago": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j;0fRZ<6QtM7KxBg84(fsEAUJ$J{f-TXlPEUec5Ee", - "n+hsD4lC(QYax=JdSpoyje8%VM`GW}{bJ8@y$A8O&*$pw{(f~Os#}2w", - "eX6^Rgi$IT%n^V^85L>$_c7{cB^#ogV=rHBJGiz-RQNFGK?gdPi|q)j`&8)}KJ{qo6dixa", - "9@yYyVg+%lo0nO+Tw0-w2hJ%mafyWL)|", - ")?W6Bi%FWuGPA1Dru$XR4SZANsAthU2EoKHF6oEtKq`rwP", - "(VNegnI_NI%;ma$)wj{k!@KFB30Yo)IOrl>)$)D|+(5h&+%2vuwGuy^@S8FT^s21V5};>VA9Iu;?8bHz#r<;JtfZDI1(FT@edh0#", - "MYW$A1qkMGIwTZqqdYNE3gl#zp&NbL9Mp=voqN|;?gqR&4$)1`znddtEyuKS*^nMMD=0^>", - "7^z6-C4P67UWOXuMBubP>j6i~03aR@jD^-Y`JSYu#Yp0P8dLLJ0QOPE8=BoiuRX59YW7xg", - "WiexjHX%&0?`ZQCdxCdL^qd1v@kOjQKaWo2Y1++~LcA%FTq?5o%}fX1-RIvlB)1#iTNomGnUL=nM!>Ix|AGtON7!F1O?53kqlC2o-`ZGw*+s", - "NM$^9znsIJMwlgscE`|O3|;BRgsQMYm~`uv+nvuv`nigRa}X=BX=A5Sw$)WEklF7&c>_~$", - "zJ(m--bqXgiN^w-U=BJH9C0Qro(x90zo@rK;&TJ$nI@&k$ORgOb2s%gWbc}ok_27)Eoku~Fq|B-Ps+4J_", - "HPJMLJ2^_)cOU$p&3kNAlrV!)%~6r$BJ>OOi~=-<6byle{?zd4J{NG}o8tw|+#ZNLcpNwk", - "TuPE~sbJB8_RZb2DopStO+Wwux~F#S59zm%00I98;S&G=b(j+6vBYQl0ssI200dcD" + "{Wp48S^xk9=GL@E0stWa761SMbT8$j;0e+L++6@F7KxBg84(fsEAUJ$9Yj;p>Mq3>*@-", + "8>razI(EFyOtYzTyCY`3kVX~k`hSJt^$bT@V;iGRbT`JI3V)lBnui#lA$wIsfE8sL=RFVi", + "Wi5>;Y=+h5(#B8hW33CVCYO92MtEmXQtd@", + "E+3y)$%o~XozOC|QgFl*-mp9+(`s0w4O4a$v!xt`G&ZI1uE4c`JE-t5WW%1*91J-", + "tr^_>U@@l^R_i@%gJ)q{kYX|w-", + "m{DbN=Z+Zey_(<=ZlU4e**~fkShDtX&9_W>qj>RuJZ-ko&-nY}Eq_?SFX8N<9wT-TH*xbF0XT;L+siI1gPQrnKc|85", + "UZaq6@7JAVeu%)Aa6I>6D;F*N)|f6jhs01q_UU%gc_Ek#>SbTrf6i;OsAQ>8&urTeX|Ier", + "uSV{o||MjbXV?)AHzh1+v~odHV<_+-", + "M0v=QR6~y%&K00{%grZ=+5)JNlFg!9Q}2rv{$OC*D{_yiUd$SL!S)f@K#pe<#CBb&}BH0p", + "%w(SzGJjGX`q+ybM!e4GEP>b&S_4lnbBR!*5>ZIxYP?QK2DIny}eL_od7Ll|WdneS(sbh~", + "!}|r_VlzIOB|lsf+rf*B~wqYWzu*", + "k-", + "19B1stj0gO@Kd^97k>cVnNvEEaMwZ6=ObszLNnyDGMW0?9>PhVq$r$BCx^ZdJ#fO^fC1JG", + "oW>FS5oC!pr7=y}O@ecL6T+R$E20#GvlwVfswl?qnCEe|@!hI*Ooyk8~vfN}h@~NGp9$00", + "H<1(-Qyy=a@C3vBYQl0ssI200dcD" ], "Asia/Tokyo": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j-~luMgIxeB7KxBg5R*;y?l4Rl4neXH3cv!OtfK@h", - "KZzauI)S!FSDREPhhBS6Fb$&Vv#7%;?Te|>pF^0HBr&z_Tk<%vMW_QqjevRZOp8XVFgP<8", - "TkT#`9H&0Ua;gT1#rZLV0HqbAKK;_z@nO;6t0LpF^0HBr&z_Tk<%vMW_QqjevRZOp8XVFgP<8TkT#`9H&0Ua;gT1#rZLV0HqbAKK;_z@", + "nO;6t0L}hOdk<>TdUa07R(LPI6@!GU$ty4=mwqHG-XVe*n(Yvgdlr+FqIU18!osi)48t~eWX8)&L", - "G)Ud^0zz@*AF+2r7E}Nf9Y72K~o-T%}D&z%}#7g2br?oH6ZiYH^%>J3D)TPKV(JY*bwjuw5=DsPB@~CrROZeN", - "x>A*H&CHrWt0`EP`m!F%waepl#|w#&`XgVc?~2M3uw$fGX~tf_Il!q#Aa<*8xlzQ2+7r6Z", - "^;Laa9F(WB_O&Dy2r>~@kSi16W{=6+i5GV=Uq~KX*~&HUN4oz7*O(gXIr}sDVcD`Ikgw#|", - "50ssal8s)Qy;?YGCf;*UKKKN!T4!Kqy_G;7PfQapugqvVBKy12v3TVH^L2", - "0?#5*VP~MOYfe$h`*L!7@tiW|_^X1N%<}`7YahiUYtMu5XwmOf3?dr+@zXHwW`z}ZDqZlT", - "<2Cs(<1%M!i6o&VK89BY0J7HPIo;O62s=|IbV^@y$N&#=>i^F00FcHoDl#3", - "Mdv&xvBYQl0ssI200dcD" + "{Wp48S^xk9=GL@E0stWa761SMbT8$j;0TQa5M2N&7KxBg5R*_t3)o}P`_Ull(nK1~U=~g{", + "!2#v7ta-VPM|>+w;XP~5#XzS!mmq>y(@${PQsHdkBYiJixTuCQ2N?55>HhxKTEufgeVl}_", + "Sq_FUIXFF$kI6!-", + "eKVzudw1Zyg8;a%MynCz&_3Cl@%Zs*_JRo#I#Ss92V)!~{AwVung!|wK?4JFyFv#=nfhNI", + "6Czr|3VjINV7V6#eFr=Gl1UDdL9MQRWZ`RiZET+fl#=kxZ_-", + "G@=#VCQEvCZVdj9;e?rY8ynpo&34DPa3", + "KI_Sc_0#?r^44F}Rzb_ChM7PPrq3@FkqqjWqgvOzPq+vkb;DT&2YMC|tC3lu6Ihz2prrFP", + "vOU@6I3$XU@68kFFWx8fx?jt@frXW`;AZso*plI73>*wENVoc+2cm`jgoe6(B`w`{BdxVOWD1rqVTCN+Y4kRvHLYXlr)vU4G7S$p~Ia_n|G>=3N5dDB8cS6IGd-ckfc7", + "8#^71HtN_BO2#F%&%Ll+IhR1DlEUG@+#_Yl8AKa1US?{&+yOwA=WA=!z-", + "B9t2>Tn9Wu2*8Ydrbage(I4dkD_vcP(|c-", + "LhGRkSn{W*nk?RJQN!j1RSZ}L6e<&UGMisk>nLH5JiLNgOSC7c&Mn1+Pit*Gz;s=M?_q!v", + "DZ@dJctlzl2>W(rvs{(CERM)RT0xuqDAl{)$*ztEhe=?|;3u&!6O1c88W}SFHDBBHh%rrh", + "U6=f6kjYt!N19xk*s_9IpbeS;(cPoTPX!vr00FE9ju8L=r}(KdvBYQl0ssI200dcD" ], "Europe/Dublin": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j;0>b$_+0=h7KxBg5R*;&J77#T_U2R5sleVWFDmK~", - "Kzj5oh@`QKHvW^6V{jU-w>qg1tSt0c^vh;?qAqA0%t?;#S~6U8Qi", - "v&f1s9IH#g$m1k1a#3+lylw4mwT4QnEUUQdwg+xnEcBlgu31bAVabn41OMZVLGz6NDwG%X", - "uQar!b>GI{qSahE`AG}$kRWbuI~JCt;38)Xwbb~Qggs55t+MAHIxgDxzTJ;2xXx99+qCy4", - "45kC#v_l8fx|G&jlVvaciR<-wwf22l%4(t@S6tnX39#_K(4S0fu$FUs$isud9IKzCXB78NkARYq@9Dc0TGkhz);NtM_SSzEffN", - "l{2^*CKGdp52h!52A)6q9fUSltXF{T*Ehc9Q7u8!W7pE(Fv$D$cKUAt6wY=DA1mGgxC*VX", - "q_If3G#FY6-Voj`fIKk`0}Cc72_SD{v>468LV{pyBI33^p0E?}RwDA6Pkq--C~0jF&Z@Pv", - "!dx_1SN_)jwz@P$(oK%P!Tk9?fRjK88yxhxlcFtTjjZ$DYssSsa#ufYrR+}}nKS+r384o~", - "!Uw$nwTbF~qgRsgr0N#d@KIinx%hQB(SJyjJtDtIy(%mDm}ZBGN}dV6K~om|=U", - "VGkbciQ=^$_14|gT21!YQ)@y*Rd0i_lS6gtPBE9+ah%WIJPwzUTjIr+J1XckkmA!6WE16%", - "CVAl{Dn&-)=G$Bjh?bh0$Xt1UDcgXJjXzzojuw0>paV~?Sa`VN3FysqFxTzfKVAu*ucq#+m=|KSSMvp_#@-lwd+q*ue", - "FQ^5<|<0R-u4qYMbRqzSn&", - "Q7jSuvc%b+EZc%>nI(+&0Tl1Y>a6v4`uNFD-7$QrhHgS7Wnv~rDgfH;rQw3+m`LJxoM4v#", - "gK@?|B{RHJ*VxZgk#!p<_&-sjxOda0YaiJ1UnG41VPv(Et%ElzKRMcO$AfgU+Xnwg5p2_+", - "NrnZ1WfEj^fmHd^sx@%JWKkh#zaK0ox%rdP)zUmGZZnqmZ_9L=%6R8ibJH0bOT$AGhDo6{", - "fJ?;_U;D|^>5by2ul@i4Zf()InfFN}00EQ=q#FPL>RM>svBYQl0ssI200dcD" + "{Wp48S^xk9=GL@E0stWa761SMbT8$j;0>b$_gw%g7KxBg5R*;&J77#T_U2R5sleVWFDmK~", + "Kzj5oh@`QKHvW^6V{jU-", + "w>qg1tSt0c^vh;?qAqA0%t?;#S~6U8Qiv&f1s9IH#g$m1k1a#3+lylw4mwT4QnEUUQdwg+", + "xnEcBlgu31bAVabn41OMZVLGz6NDwG%XuQar!b>GI{qSahE`AG}$kRWbuI~JCt;38)Xwbb", + "~Qggs55t+MAHIxgDxzTJ;2xXx99+qCy445kC#v_l8fx|G&jlVvaciR<-", + "wwf22l%4(t@S6tnX39#_K(4S0fu$FUs$isud9IKzCXB78NkARYq@9Dc0TGkhz);NtM_SSzEffNl{2^*CKGdp52h!52A)6q9fUSltXF{T", + "*Ehc9Q7u8!W7pE(Fv$D$cKUAt6wY=DA1mGgxC*VXq_If3G#FY6-", + "Voj`fIKk`0}Cc72_SD{v>468LV{pyBI33^p0E?}RwDA6Pkq--C~0jF&Z@Pv!dx_1SN_)jw", + "z@P$(oK%P!Tk9?fRjK88yxhxlcFtTjjZ$DYssSsa#ufYrR+}}nKS+r384o~!Uw$nwTbF~q", + "gRsgr0N#d@KIinx%hQB(SJyjJtDtIy(%mDm}ZBGN}dV6K~om|=UVGkbciQ=^$_", + "14|gT21!YQ)@y*Rd0i_lS6gtPBE9+ah%WIJPwzUTjIr+J1XckkmA!6WE16%CVAl{Dj@)nt", + "QW>5WCgG;uYjCg(j>qCs(*}h9IWV8w>LXsNq+C>vLWc", + ">tZt7asixk*XDd^+o!O=O52B7aPqt&HfgmRCd4-+ky?P-", + "XP?5Np6dxH29G;c3@torNWCs!ufT_DK<~j-", + "UgqAdf5G4ZdP`bECDkw8*?qvrtnMfoJT^Wq|8_~4;n!EAt=*dv)-", + "0yF8uKXAiZ~3d|7Z>ZO|t~YD2@;`6Qg{xlf8Q&;*xB-Ys_R2Cp{y((HBw7kN@@CtfA<<$B", + "fGc2BhK{XBpaQiJGWmO!j9XN7n0YhjD8vjw0{?{0zZm5js?lNS*8*{rU&d|`Rl_i(p2nHf}VB&&P+m6k^", + "y|9Wu}iApF2OdyoJC2VV0^9?>qd00ENOKUU4S;*h>v*ep0", - "xTi1cK2{aY*|2D*-~K<;-{_W+r@NvZ7-|NZv($ek_C%VfP0xjWeZP#CPXD`IKkakjh(kUd", - "&H)m;^Q(jGjIyiyrcUMtOP)u3A>sw6ux;Bmp3x$4QvQKMx5TrCx_!$srWQuXNs&`9=^IY1", - "yc&C31!sQh7P=Mk*#6x8Z@5^%ehR8UW$OWw0KMw}P1ycI^", - "4eh12oBUOV?S>n*d!+EM@>x#9PZD12iD=zaC;7`8dTfkU_6d}OZvSFSbGgXeKw}XyX@D=(", - ")D0!^DBGr8pXWBT$S-yhLP>Z3ys^VW3}RQ6{NGGVJG6vf*MH93vvNW6yLjie1;{4tVhg-KnSf|G`!", - "Z;j$7gJ1ows~RD=@n7I6aFd8rOR_7Y?E-$clI%1o5gA@O!KPa^(8^iFFeFykI-+z>E$mvp", - "E_h`vbHPjqkLs`Dn-0FV`R@z|h!S(Lb;M&|Exr!biY`%bfp$6`hK;GDhdP|^Q", - "*Ty*}1d41K>H2B{jrjE9aFK>yAQJBX9CD%-384S;0fw`PlprHGS`^b$oS-`I4VH7ji8ou-", - "g|060jfb1XcxiInT0oOoeR7#%e5Ug5#KW)nVSRvLHNe$SQHM@2)`S9L7>RL@Qx%fmm7?3u7P5TywFQ}C@S(pq}|", - "eLPT{C^{<0Q?uU&kSVd%!~8q3;Z0s3OqzF`$HRkePL5Ywgiwn{R(zi+jmOBFrVpW;)@UsU#%$8BcV#h@}m$#!Fglo&bwb78aYqOG_W7h{eb(+39&-mk4EIXq_", - "_`30=8sfA3=!3TO_TyS5X22~?6nKngZ|bq=grdq=9X)3xAkA42L!~rmS)n3w-~;lgz%Fhn", - "(?rXdp2ho~9?wmVs2JwVt~?@FVD%`tN69{(i3oQa;O0|FpV7KxBg5R*;+c_2(RlxFoAjepiN+t(&A", + "khpF;7sO(r>4o7M4zZVa$XY~v@-", + "@YI68ej+V4yBoGpi5ZYu;Zw>N;+Vkw)1TIVA4;Vn*JV=%f`o+fC9=H@gz8U6N-", + "M+jj4KAFBq5|dk<~RQE?jJV`tG;f@gAn7I{P&H39;;isJ!fMa`+wG", + "KkWXbi?P7&ivzm}BJ9guJ&D1=Ci_?iEC=T+}Ht)wPz7azBV$vs`Fg0TYba5j@iBgmJ}w{Wg", + "C;WaVQ5{ZjAIYY-lC8|yfnqplNF0_6r6Jo}h*-", + "^e6n7IHY9#^nyJM($bLr;XKyoo4e=k4E_rXAXU|8;BGkQ^kNAtK@OYtPw+AVo@wAk+F{Xd", + "YfNlG<<-FnlW4;LdIej=F0WFr~-c^-", + "M)7hP!$diHGAim;v4c$Ui^z<`A!+F8RhS5DXaZomO|PHR8B%eNWlI^Y;%XH23*BQ9Pv!0dNOS", + "JW;D6iM}OHVD9S;=_EGP=j^CP6mQ~WcEd%i!wnK!|`afKPHZ{nSFK{L!7$MM299!v3kGuq;oa;+;@@n1r@0Kc%yl18x$nR#Kzi@?+E(y", + "7o2rS3FClOOT`Amt}UyGfYZ7QWYqqCA(t;kD}FGa+vi>Zi)j}a2lrvx_};$<>-", + "h&pt_ePq>W5KHZPr_P0CVzjF(&G-", + "bL>Xi>@Jv$b)=hLcP>(ngUOdeI5{4_W6pSrkv%rnFAW~Xq0%BpP=^5An)E2@X9`)$o<{(F", + "VhGYMIW)@T&B7JZ06+RhK~>g?V;J{)+)M6xch^XnnI^Q0TC;zLSj(LMJ&sOV*Qj&~gGAP}", + "&ujCT8Fj?*_GQ!H)00D>!#~T0u=fLlPvBYQl0ssI200dcD" ], "Europe/London": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j;0`|pJ6!-O7KxBg5R*;$9DqzW!kQs3DZt(=0_!m1", - "4wvE`6N%Vj#u6PS_3S?~(2)&xn8}2}3Wr#kG8n2!x8>$E$lF&~Y#_H6bu6(BiwblJ>;-Fs", - "gA$Y$*?=X)n1pFkKn}F~`>=4)+LLQk?L*P!bhAm0;`N~z3QbUIyVrm%kOZ(n1JJsm0pyb8", - "!GV{d*C!9KXv;4vD4Q>-k#+x(!V5L@w5M>v2V5a`B>t(|B", - "|Fqr4^-{S*%Ep~ojUtx_CRbSQ(uFwu2=KH)Q@EBs@ZqRXn4mU;B!68;;IQs3Ub=n&UU%*m", - "k&zwD36&JSwsN(%k&x?H+tN^6)23c`I0=5^N_R0~1>tsFZ`^`3z~rXSXT&qcwa#n!%+Z#P", - "PG}(D^_CCILXnF|GKwabBh*xFS?4rwGo2vtJUwzrbv_$5PO+`?$l{H-jGB@X%S!OAhw;D4", - "XFycN3!XqQ&EorJOD3>~^U%Luw!jF<;6_q-f-S|6{cQDfZ2(4Xf1MMLr1=SA=MwVf2%Pp%VP;jn)|5Tf!-DbUGn%I-rkYaH7?$$O!t)wwClAisr3eUoeB^~T=U*_P~Y2*KdnO87>B!19sV=xZ5", - "yApq26RxgqA|*tmsvtL#OhcF(C<0EGWHP)BFl?h)_*7!{LoJiv%RsOs!q->n+DcV%9~B@RbC_1G_1g6`Yd~8|%-=2l~oGN!~TVv2Bnk>7wW8L@^?vX$f3AiT)(4nrCuTm9%(XC6Nai", - "E(;}7&=YZagjAN$O-cN;1u{dTkElmB0GT$|Wa)QMmKrx<|LCJ9qlUoFsUbD^H^6_8(w<0{", - "ftj&O1~p_%lh5z;zNV&sP$E$lF&~Y#_H6bu6(BiwblJ>;-", + "FsgA$Y$*?=X)n1pFkKn}F~`>=4)+LLQk?L*P!bhAm0;`N~z3QbUIyVrm%kOZ(n1JJsm0py", + "b8!GV{d*C!9KXv;4vD4Q>-", + "k#+x(!V5L@w5M>v2V5a`B>t(|B|Fqr4^-", + "{S*%Ep~ojUtx_CRbSQ(uFwu2=KH)Q@EBs@ZqRXn4mU;B!68;;IQs3Ub=n&UU%*mk&zwD36", + "&JSwsN(%k&x?H+tN^6)23c`I0=5^N_R0~1>tsFZ`^`3z~rXSXT&qcwa#n#k^5sFT7HKtyC", + "9A0oluNf^P4yk-d_|mUd;T0;~y@2Cu@Xd;IRT#++Y*Z6*0%M4`z`3a2vnHc-", + "B(#xp*94c8t_y=lV~#Q=Whn&p<+Qzs`pL<^`L`BrF9ohSDa^SnosMt{zpFXpUjqumClb$D", + "^}s!&5JM`)L?H!Gzj6q@G0mVG?P#xu;u1DMoWN$14T", + "b>^F1?&ymdJ4TS`!aAO1#Myz0fU6<#?jJoc&X-", + "z&$D#Zj!Dg3w**{JNc(J;D0DrI1K1-", + "iv3~i7vFT?5yqP3rSI@jsz*k!0bE*~Pkn+g>u6Z;Se-", + ")c$&;tI=8t;#10nr-)VFCx@^bf}Ak2a$g+MN&Pv7{W+wBYjvrBy)wwx-", + "|SlQynn=O3ULjr$jM*QQAezq5|DqO63Zf+jql$4rQ2m|lPqGyA<>cV6bIA", + "o~*{`bgCh=A>WU}#b$t&5MPj$~|esT>8v-", + "C$_n!^iqI5;Q?X=YtG#wS0iS@Z+K+>Pw@;#vN~2NVaNcNiR~iPI$HEp0CZblbg!9944qJf", + "e^U%kyd74NW@4bR+8mK^RfSa}|2+8EsMDCnOSZ@D)kcJx`Cx~hD", + "N7PV9xa~1y#{E$Hy#KX4zE=~k$7%Vm?00000LN&_Vg>>9w00Gqs&>R2&ZK8hovBYQl0ssI", + "200dcD" ], "Pacific/Kiritimati": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j-~jCaVO;+", - "NF2>iK{8KMUf+)<-)VxXbLxD(alL}N$AT-ogNbJSMMYeX+Z{jS)b8TK^PB=FxyBxzfmFto", - "eo0R`a(%NO?#aEH9|?Cv00000NIsFh6BW2800DjO0RR918Pu^`vBYQl0ssI200dcD" + "{Wp48S^xk9=GL@E0stWa761SMbT8$j-~itMU0nbw7KxBg5R*{Ky3@w34e-", + "emlEe%!1&HoVz@2)g91$Qvf%e=}%J+k5^yTOu{Q*OrV;`agAU{YYC1>Bq#Lo)Ct}OFqAaP", + "SYvN>0#bjna^XrQl~da<70IbZ?+00000VC(mK^UzXX00DX60RR91ZYU6cvBYQl0ssI200d", + "cD" ], "UTC": [ - "{Wp48S^xk9=GL@E0stWa761SMbT8$j-~e#|9bEt_7KxBg5R*|3h1|xhHLji!C57qW6L*|H", - "pEErm00000ygu;I+>V)?00B92fhY-(AGY&-0RR9100dcD" + "{Wp48S^xk9=GL@E0stWa761SMbT8$j-", + "~e#|9bEt_7KxBg5R*|3h1|xhHLji!C57qW6L*|HpEErm00000ygu;I+>V)?00B92fhY-", + "(AGY&-0RR9100dcD" ] }, "metadata": { - "version": "2020a" + "version": "2025b" } } \ No newline at end of file diff --git a/Lib/test/test_zoneinfo/test_zoneinfo.py b/Lib/test/test_zoneinfo/test_zoneinfo.py index 111b9d92283..8513268b0d5 100644 --- a/Lib/test/test_zoneinfo/test_zoneinfo.py +++ b/Lib/test/test_zoneinfo/test_zoneinfo.py @@ -12,6 +12,7 @@ import re import shutil import struct +import sys import tempfile import unittest from datetime import date, datetime, time, timedelta, timezone @@ -29,7 +30,7 @@ try: importlib.metadata.metadata("tzdata") - HAS_TZDATA_PKG = True + HAS_TZDATA_PKG = (importlib.metadata.version("tzdata") == "2025.3") except importlib.metadata.PackageNotFoundError: HAS_TZDATA_PKG = False @@ -316,6 +317,18 @@ def test_unambiguous(self): self.assertEqual(dt.utcoffset(), offset.utcoffset, dt) self.assertEqual(dt.dst(), offset.dst, dt) + def test_datetime_subclass_negative_components(self): + class MinusOneDateTime(datetime): + hour = minute = second = -1 + + zi = self.zone_from_key("UTC") + dt = MinusOneDateTime(2024, 1, 1, tzinfo=zi) + + self.assertEqual(dt.utcoffset(), ZERO) + self.assertEqual(dt.dst(), ZERO) + self.assertEqual(dt.tzname(), "UTC") + self.assertEqual(zi.fromutc(dt), datetime(2024, 1, 1, tzinfo=zi)) + def test_folds_and_gaps(self): test_cases = [] for key in self.zones(): @@ -630,6 +643,26 @@ def test_one_transition(self): dt_utc_actual = dt_local.astimezone(timezone.utc) self.assertEqual(dt_utc_actual, dt_utc) + def test_one_transition_fold(self): + GMT = ZoneOffset("-00", ZERO) + N03 = ZoneOffset("-03", -timedelta(hours=3)) + + transitions = [ + ZoneTransition(datetime(1976, 12, 1), GMT, N03), + ] + + after = "<-03>3" + + zf = self.construct_zone(transitions, after) + zi = self.klass.from_file(zf) + + dt_utc = datetime(1976, 12, 1, 1, tzinfo=timezone.utc) + dt_local = dt_utc.astimezone(zi) + + self.assertEqual(dt_local.fold, 1) + self.assertEqual(dt_local.utcoffset(), N03.utcoffset) + self.assertEqual(dt_local.astimezone(timezone.utc), dt_utc) + def test_one_zone_dst(self): DST = ZoneOffset("DST", ONE_H, ONE_H) transitions = [ @@ -1009,14 +1042,14 @@ def populate_tzstr_header(cls): cls._tzif_header = bytes(out) - def zone_from_tzstr(self, tzstr): + def zone_from_tzstr(self, tzstr, encoding="ascii"): """Creates a zoneinfo file following a POSIX rule.""" zonefile = io.BytesIO(self._tzif_header) zonefile.seek(0, 2) # Write the footer zonefile.write(b"\x0A") - zonefile.write(tzstr.encode("ascii")) + zonefile.write(tzstr.encode(encoding)) zonefile.write(b"\x0A") zonefile.seek(0) @@ -1111,6 +1144,9 @@ def test_extreme_tzstr(self): "AAA4BBB,J1/2,J1/14", "AAA4BBB,J20/2,J365/2", "AAA4BBB,J365/2,J365/14", + # Leading-zero day-of-year + "AAA4BBB,J001/2,J065/2", + "AAA4BBB,001/2,065/2", # Extreme transition hour "AAA4BBB,J60/167,J300/2", "AAA4BBB,J60/+167,J300/2", @@ -1142,9 +1178,21 @@ def test_extreme_tzstr(self): def test_invalid_tzstr(self): invalid_tzstrs = [ "PST8PDT", # DST but no transition specified + # gh-152212: the std offset is required (POSIX TZ grammar) + "AAA", + "A", + "AA", + "B", "+11", # Unquoted alphanumeric "GMT,M3.2.0/2,M11.1.0/3", # Transition rule but no DST "GMT0+11,M3.2.0/2,M11.1.0/3", # Unquoted alphanumeric in DST + # Unquoted abbreviation with embedded or leading whitespace + "AB C3", + " A B 3", + "AAA4BB B,J60/2,J300/2", # Embedded whitespace in DST + # Empty quoted abbreviation + "<>5", + "AAA4<>,M3.2.0/2,M11.1.0/3", "PST8PDT,M3.2.0/2", # Only one transition rule # Invalid offset hours "AAA168", @@ -1184,6 +1232,11 @@ def test_invalid_tzstr(self): # Invalid weekday "AAA4BBB,M1.1.7/2,M2.1.1/2", "AAA4BBB,M1.1.1/2,M2.1.7/2", + # Invalid Mm.w.d separator + "AAA4BBB,M3.2X0,M11.1.0", + "AAA4BBB,M3.2.0,M11.1X0", + "AAA4BBB,M3.2-0,M11.1.0/3", + "AAA4BBB,M3.2.0/2,M11.1:0", # Invalid numeric offset "AAA4BBB,-1/2,20/2", "AAA4BBB,1/2,-1/2", @@ -1192,6 +1245,15 @@ def test_invalid_tzstr(self): # Invalid julian offset "AAA4BBB,J0/2,J20/2", "AAA4BBB,J20/2,J366/2", + # gh-152847: non-digit day-of-year + "AAA4BBB,J1_0,J300/2", + "AAA4BBB,J60/2,J30_0/2", + "AAA4BBB,1_0,J300/2", + "AAA4BBB,J+1,J300/2", + "AAA4BBB,J 1,J300/2", + "AAA4BBB, 1,J300/2", + "AAA4BBB,J0001,J300/2", + "AAA4BBB,0001,J300/2", # Invalid transition time "AAA4BBB,J60/2/3,J300/2", "AAA4BBB,J60/2,J300/2/3", @@ -1222,6 +1284,24 @@ def test_invalid_tzstr(self): with self.assertRaisesRegex(ValueError, tzstr_regex): self.zone_from_tzstr(invalid_tzstr) + def test_invalid_tzstr_non_ascii_abbr(self): + tzstr = "ABÀC3" + if self.module is py_zoneinfo: + expected = re.escape(tzstr) + else: + expected = re.escape(repr(tzstr.encode("utf-8"))) + with self.assertRaisesRegex(ValueError, expected): + self.zone_from_tzstr(tzstr, encoding="utf-8") + + def test_invalid_tzstr_non_ascii_dst_date(self): + tzstr = "AAA4BBB,J١,J300/2" + if self.module is py_zoneinfo: + expected = re.escape(tzstr) + else: + expected = re.escape(repr(tzstr.encode("utf-8"))) + with self.assertRaisesRegex(ValueError, expected): + self.zone_from_tzstr(tzstr, encoding="utf-8") + @classmethod def _populate_test_cases(cls): # This method uses a somewhat unusual style in that it populates the @@ -1433,6 +1513,33 @@ def _add(): (datetime(2020, 12, 31, 23, 59, 59, 999999), AAA, NORMAL), ) + @call + def _add(): + # Julian days 58, 59 and 60 always mean February 27, February 28 + # and March 1, including in leap years. + AAA = ZoneOffset("AAA", ZERO) + BBB = ZoneOffset("BBB", ONE_H, ONE_H) + + for start, end, start_date, end_date in ( + (58, 59, (2, 27), (2, 28)), + (59, 60, (2, 28), (3, 1)), + ): + tzstr = f"AAA0BBB,J{start}/12,J{end}/12" + cases[tzstr] = [] + for year in (2019, 2020, 2000, 2100): + start_dt = datetime(year, *start_date, 12) + end_dt = datetime(year, *end_date, 12) + cases[tzstr].extend(( + (start_dt - timedelta(seconds=1), AAA, NORMAL), + (start_dt, AAA, GAP), + (start_dt.replace(fold=1), BBB, GAP), + (start_dt + ONE_H, BBB, NORMAL), + (end_dt - ONE_H - timedelta(seconds=1), BBB, NORMAL), + (end_dt - ONE_H, BBB, FOLD), + ((end_dt - ONE_H).replace(fold=1), AAA, FOLD), + (end_dt, AAA, NORMAL), + )) + @call def _add(): # Taken from America/Godthab, this rule has a transition on the @@ -2055,6 +2162,21 @@ def test_exclude_posixrules(self): actual = self.module.available_timezones() self.assertEqual(actual, expected) + def test_exclude_localtime(self): + expected = { + "America/New_York", + "Europe/London", + } + + tree = list(expected) + ["localtime"] + + with tempfile.TemporaryDirectory() as td: + for key in tree: + self.touch_zone(key, td) + + with self.tzpath_context([td]): + actual = self.module.available_timezones() + self.assertEqual(actual, expected) class CTestModule(TestModule): module = c_zoneinfo @@ -2080,6 +2202,8 @@ def test_pydatetime(self): PYTHONTZPATH=str(ZONEINFO_DATA.tzpath)) +@unittest.skipIf(sys.modules.get("_zoneinfo") is None, + "_zoneinfo C module not available") class ExtensionBuiltTest(unittest.TestCase): """Smoke test to ensure that the C and Python extensions are both tested. @@ -2296,8 +2420,8 @@ def _America_Los_Angeles(): ] def _America_Santiago(): - LMT = ZoneOffset("LMT", timedelta(seconds=-16966), ZERO) - SMT = ZoneOffset("SMT", timedelta(seconds=-16966), ZERO) + LMT = ZoneOffset("LMT", timedelta(seconds=-16965), ZERO) + SMT = ZoneOffset("SMT", timedelta(seconds=-16965), ZERO) N05 = ZoneOffset("-05", timedelta(seconds=-18000), ZERO) N04 = ZoneOffset("-04", timedelta(seconds=-14400), ZERO) N03 = ZoneOffset("-03", timedelta(seconds=-10800), ONE_H) @@ -2332,8 +2456,8 @@ def _Australia_Sydney(): return [ ZoneTransition(datetime(1895, 2, 1), LMT, AEST), - ZoneTransition(datetime(1917, 1, 1, 0, 1), AEST, AEDT), - ZoneTransition(datetime(1917, 3, 25, 2), AEDT, AEST), + ZoneTransition(datetime(1917, 1, 1, 2), AEST, AEDT), + ZoneTransition(datetime(1917, 3, 25, 3), AEDT, AEST), ZoneTransition(datetime(2012, 4, 1, 3), AEDT, AEST), ZoneTransition(datetime(2012, 10, 7, 2), AEST, AEDT), ZoneTransition(datetime(2040, 4, 1, 3), AEDT, AEST), @@ -2341,7 +2465,7 @@ def _Australia_Sydney(): ] def _Europe_Dublin(): - LMT = ZoneOffset("LMT", timedelta(seconds=-1500), ZERO) + LMT = ZoneOffset("LMT", timedelta(seconds=-1521), ZERO) DMT = ZoneOffset("DMT", timedelta(seconds=-1521), ZERO) IST_0 = ZoneOffset("IST", timedelta(seconds=2079), ONE_H) GMT_0 = ZoneOffset("GMT", ZERO, ZERO) diff --git a/Lib/test/test_zstd.py b/Lib/test/test_zstd.py index cf618534add..9225c42e0e7 100644 --- a/Lib/test/test_zstd.py +++ b/Lib/test/test_zstd.py @@ -12,7 +12,6 @@ from test.support.import_helper import import_module from test.support import threading_helper from test.support import _1M -from test.support import Py_GIL_DISABLED _zstd = import_module("_zstd") zstd = import_module("compression.zstd") @@ -2374,6 +2373,8 @@ def read(self, size): f.read(100) with self.assertRaises(io.UnsupportedOperation): f.seek(100) + with self.assertRaises(io.UnsupportedOperation): + next(iter(f)) self.assertEqual(f.closed, True) with self.assertRaises(ValueError): f.readable() diff --git a/Lib/test/testtar.tar b/Lib/test/testtar.tar deleted file mode 100644 index bb9345373e9..00000000000 Binary files a/Lib/test/testtar.tar and /dev/null differ diff --git a/Lib/test/tkinterdata/python.gif b/Lib/test/tkinterdata/python.gif new file mode 100644 index 00000000000..efa0be3861d Binary files /dev/null and b/Lib/test/tkinterdata/python.gif differ diff --git a/Lib/test/tkinterdata/python.pgm b/Lib/test/tkinterdata/python.pgm new file mode 100644 index 00000000000..8349f2a53a9 Binary files /dev/null and b/Lib/test/tkinterdata/python.pgm differ diff --git a/Lib/test/tkinterdata/python.png b/Lib/test/tkinterdata/python.png new file mode 100644 index 00000000000..1a987f79fcd Binary files /dev/null and b/Lib/test/tkinterdata/python.png differ diff --git a/Lib/test/tkinterdata/python.ppm b/Lib/test/tkinterdata/python.ppm new file mode 100644 index 00000000000..7d9cdb32158 Binary files /dev/null and b/Lib/test/tkinterdata/python.ppm differ diff --git a/Lib/test/tkinterdata/python.xbm b/Lib/test/tkinterdata/python.xbm new file mode 100644 index 00000000000..cfbee2e9806 --- /dev/null +++ b/Lib/test/tkinterdata/python.xbm @@ -0,0 +1,6 @@ +#define python_width 16 +#define python_height 16 +static char python_bits[] = { + 0xDF, 0xFE, 0x8F, 0xFD, 0x5F, 0xFB, 0xAB, 0xFE, 0xB5, 0x8D, 0xDA, 0x8F, + 0xA5, 0x86, 0xFA, 0x83, 0x1A, 0x80, 0x0D, 0x80, 0x0D, 0x80, 0x0F, 0xE0, + 0x0F, 0xF8, 0x0F, 0xF8, 0x0F, 0xFC, 0xFF, 0xFF, }; diff --git a/Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt b/Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt deleted file mode 100644 index 1b5335b64ed..00000000000 --- a/Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: latin1 -*- -# IMPORTANT: this file has the utf-8 BOM signature '\xef\xbb\xbf' -# at the start of it. Make sure this is preserved if any changes -# are made! Also note that the coding cookie above conflicts with -# the presence of a utf-8 BOM signature -- this is intended. - -# Arbitrary encoded utf-8 text (stolen from test_doctest2.py). -x = 'ЉЊЈЁЂ' -def y(): - """ - And again in a comment. ЉЊЈЁЂ - """ - pass diff --git a/Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt b/Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt deleted file mode 100644 index 23fd2168ae5..00000000000 --- a/Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt +++ /dev/null @@ -1,11 +0,0 @@ -# IMPORTANT: this file has the utf-8 BOM signature '\xef\xbb\xbf' -# at the start of it. Make sure this is preserved if any changes -# are made! - -# Arbitrary encoded utf-8 text (stolen from test_doctest2.py). -x = 'ЉЊЈЁЂ' -def y(): - """ - And again in a comment. ЉЊЈЁЂ - """ - pass diff --git a/Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt b/Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt deleted file mode 100644 index 04561e48472..00000000000 --- a/Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt +++ /dev/null @@ -1,13 +0,0 @@ -# -*- coding: utf-8 -*- -# IMPORTANT: unlike the other test_tokenize-*.txt files, this file -# does NOT have the utf-8 BOM signature '\xef\xbb\xbf' at the start -# of it. Make sure this is not added inadvertently by your editor -# if any changes are made to this file! - -# Arbitrary encoded utf-8 text (stolen from test_doctest2.py). -x = 'ЉЊЈЁЂ' -def y(): - """ - And again in a comment. ЉЊЈЁЂ - """ - pass diff --git a/Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt b/Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt deleted file mode 100644 index 4b20ff6ad6d..00000000000 --- a/Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# IMPORTANT: this file has the utf-8 BOM signature '\xef\xbb\xbf' -# at the start of it. Make sure this is preserved if any changes -# are made! - -# Arbitrary encoded utf-8 text (stolen from test_doctest2.py). -x = 'ЉЊЈЁЂ' -def y(): - """ - And again in a comment. ЉЊЈЁЂ - """ - pass diff --git a/Lib/test/tokenize_tests.txt b/Lib/test/tokenize_tests.txt deleted file mode 100644 index c4f5a58a946..00000000000 --- a/Lib/test/tokenize_tests.txt +++ /dev/null @@ -1,189 +0,0 @@ -# Tests for the 'tokenize' module. -# Large bits stolen from test_grammar.py. - -# Comments -"#" -#' -#" -#\ - # - # abc -'''# -#''' - -x = 1 # - -# Balancing continuation - -a = (3, 4, - 5, 6) -y = [3, 4, - 5] -z = {'a':5, - 'b':6} -x = (len(repr(y)) + 5*x - a[ - 3 ] - - x + len({ - } - ) - ) - -# Backslash means line continuation: -x = 1 \ -+ 1 - -# Backslash does not means continuation in comments :\ -x = 0 - -# Ordinary integers -0xff != 255 -0o377 != 255 -2147483647 != 0o17777777777 --2147483647-1 != 0o20000000000 -0o37777777777 != -1 -0xffffffff != -1; 0o37777777777 != -1; -0o1234567 == 0O001234567; 0b10101 == 0B00010101 - -# Long integers -x = 0 -x = 0 -x = 0xffffffffffffffff -x = 0xffffffffffffffff -x = 0o77777777777777777 -x = 0B11101010111111111 -x = 123456789012345678901234567890 -x = 123456789012345678901234567890 - -# Floating-point numbers -x = 3.14 -x = 314. -x = 0.314 -# XXX x = 000.314 -x = .314 -x = 3e14 -x = 3E14 -x = 3e-14 -x = 3e+14 -x = 3.e14 -x = .3e14 -x = 3.1e4 - -# String literals -x = ''; y = ""; -x = '\''; y = "'"; -x = '"'; y = "\""; -x = "doesn't \"shrink\" does it" -y = 'doesn\'t "shrink" does it' -x = "does \"shrink\" doesn't it" -y = 'does "shrink" doesn\'t it' -x = """ -The "quick" -brown fox -jumps over -the 'lazy' dog. -""" -y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' -y = ''' -The "quick" -brown fox -jumps over -the 'lazy' dog. -'''; -y = "\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the 'lazy' dog.\n\ -"; -y = '\n\ -The \"quick\"\n\ -brown fox\n\ -jumps over\n\ -the \'lazy\' dog.\n\ -'; -x = r'\\' + R'\\' -x = r'\'' + '' -y = r''' -foo bar \\ -baz''' + R''' -foo''' -y = r"""foo -bar \\ baz -""" + R'''spam -''' -x = b'abc' + B'ABC' -y = b"abc" + B"ABC" -x = br'abc' + Br'ABC' + bR'ABC' + BR'ABC' -y = br"abc" + Br"ABC" + bR"ABC" + BR"ABC" -x = rb'abc' + rB'ABC' + Rb'ABC' + RB'ABC' -y = rb"abc" + rB"ABC" + Rb"ABC" + RB"ABC" -x = br'\\' + BR'\\' -x = rb'\\' + RB'\\' -x = br'\'' + '' -x = rb'\'' + '' -y = br''' -foo bar \\ -baz''' + BR''' -foo''' -y = Br"""foo -bar \\ baz -""" + bR'''spam -''' -y = rB"""foo -bar \\ baz -""" + Rb'''spam -''' - -# Indentation -if 1: - x = 2 -if 1: - x = 2 -if 1: - while 0: - if 0: - x = 2 - x = 2 -if 0: - if 2: - while 0: - if 1: - x = 2 - -# Operators - -def d22(a, b, c=1, d=2): pass -def d01v(a=1, *restt, **restd): pass - -(x, y) != ({'a':1}, {'b':2}) - -# comparison -if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 != 1 in 1 not in 1 is 1 is not 1: pass - -# binary -x = 1 & 1 -x = 1 ^ 1 -x = 1 | 1 - -# shift -x = 1 << 1 >> 1 - -# additive -x = 1 - 1 + 1 - 1 + 1 - -# multiplicative -x = 1 / 1 * 1 % 1 - -# unary -x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 -x = -1*1/1 + 1*1 - ---1*1 - -# selector -import sys, time -x = sys.modules['time'].time() - -@staticmethod -def foo(): pass - -@staticmethod -def foo(x:1)->1: pass - diff --git a/Lib/test/translationdata/argparse/msgids.txt b/Lib/test/translationdata/argparse/msgids.txt index 97416aad520..ae89ac74726 100644 --- a/Lib/test/translationdata/argparse/msgids.txt +++ b/Lib/test/translationdata/argparse/msgids.txt @@ -2,29 +2,21 @@ %(heading)s: %(prog)s: error: %(message)s\n %(prog)s: warning: %(message)s\n -%r is not callable -'required' is an invalid argument for positionals -.__call__() not defined ambiguous option: %(option)s could match %(matches)s argument "-" with mode %r argument %(argument_name)s: %(message)s argument '%(argument_name)s' is deprecated can't open '%(filename)s': %(error)s -cannot have multiple subparser arguments -cannot merge actions - two groups are named %r command '%(parser_name)s' is deprecated -conflicting subparser alias: %s -conflicting subparser: %s -dest= is required for options like %r +conflicting option string: %s +expected %s argument expected at least one argument expected at most one argument expected one argument ignored explicit argument %r invalid %(type)s value: %(value)r invalid choice: %(value)r (choose from %(choices)s) -invalid conflict_resolution value: %r -invalid option string %(option)r: must start with a character %(prefix_chars)r -mutually exclusive arguments must be optional +invalid choice: %(value)r, maybe you meant %(closest)r? (choose from %(choices)s) not allowed with argument %s one of the arguments %s is required option '%(option)s' is deprecated diff --git a/Lib/test/translationdata/getopt/msgids.txt b/Lib/test/translationdata/getopt/msgids.txt index 1ffab1f31ab..5c0c02d452d 100644 --- a/Lib/test/translationdata/getopt/msgids.txt +++ b/Lib/test/translationdata/getopt/msgids.txt @@ -1,6 +1,6 @@ option -%s not recognized option -%s requires argument option --%s must not have an argument -option --%s not a unique prefix +option --%s not a unique prefix; possible options: %s option --%s not recognized option --%s requires argument \ No newline at end of file diff --git a/Lib/test/translationdata/optparse/msgids.txt b/Lib/test/translationdata/optparse/msgids.txt index ac5317c736a..8f405a2bf26 100644 --- a/Lib/test/translationdata/optparse/msgids.txt +++ b/Lib/test/translationdata/optparse/msgids.txt @@ -1,3 +1,4 @@ +%(option)s option requires %(number)d argument %prog [options] %s option does not take a value Options diff --git a/Lib/test/zip_cp437_header.zip b/Lib/test/zip_cp437_header.zip deleted file mode 100644 index f7c6cf17042..00000000000 Binary files a/Lib/test/zip_cp437_header.zip and /dev/null differ diff --git a/Lib/test/zipdir.zip b/Lib/test/zipdir.zip deleted file mode 100644 index ac21d7a1edd..00000000000 Binary files a/Lib/test/zipdir.zip and /dev/null differ diff --git a/Lib/test/ziptestdata/README.md b/Lib/test/ziptestdata/README.md deleted file mode 100644 index 6b9147db76e..00000000000 --- a/Lib/test/ziptestdata/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# Test data for `test_zipfile` - -The test executables in this directory are created manually from header.sh and -the `testdata_module_inside_zip.py` file. You must have infozip's zip utility -installed (`apt install zip` on Debian). - -## Purpose - -These are used to test executable files with an appended zipfile, in a scenario -where the executable is _not_ a Python interpreter itself so our automatic -zipimport machinery (that'd look for `__main__.py`) is not being used. - -## Updating the test executables - -If you update header.sh or the testdata_module_inside_zip.py file, rerun the -commands below. These are expected to be rarely changed, if ever. - -### Standard old format (2.0) zip file - -``` -zip -0 zip2.zip testdata_module_inside_zip.py -cat header.sh zip2.zip >exe_with_zip -rm zip2.zip -``` - -### Modern format (4.5) zip64 file - -Redirecting from stdin forces infozip's zip tool to create a zip64. - -``` -zip -0 zip64.zip -cat header.sh zip64.zip >exe_with_z64 -rm zip64.zip -``` - diff --git a/Lib/test/ziptestdata/exe_with_z64 b/Lib/test/ziptestdata/exe_with_z64 deleted file mode 100755 index 82b03cf39d9..00000000000 Binary files a/Lib/test/ziptestdata/exe_with_z64 and /dev/null differ diff --git a/Lib/test/ziptestdata/exe_with_zip b/Lib/test/ziptestdata/exe_with_zip deleted file mode 100755 index c833cdf9f93..00000000000 Binary files a/Lib/test/ziptestdata/exe_with_zip and /dev/null differ diff --git a/Lib/test/ziptestdata/header.sh b/Lib/test/ziptestdata/header.sh deleted file mode 100755 index 52dc91acf74..00000000000 --- a/Lib/test/ziptestdata/header.sh +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/bash -INTERPRETER_UNDER_TEST="$1" -if [[ ! -x "${INTERPRETER_UNDER_TEST}" ]]; then - echo "Interpreter must be the command line argument." - exit 4 -fi -EXECUTABLE="$0" exec "${INTERPRETER_UNDER_TEST}" -E - < 0: - gotit = waiter.acquire(True, timeout) - else: + if timeout <= 0: gotit = waiter.acquire(False) + else: + # A NaN timeout is rejected by acquire(). + gotit = waiter.acquire(True, timeout) return gotit finally: self._acquire_restore(saved_state) @@ -849,6 +844,148 @@ class BrokenBarrierError(RuntimeError): pass +## Synchronization tools for iterators ##################### + +class serialize_iterator: + """Wrap a non-concurrent iterator with a lock to enforce sequential access. + + Applies a non-reentrant lock around calls to __next__. If the + wrapped iterator also defines send(), throw(), or close(), those + calls are serialized as well. + + Allows iterator and generator instances to be shared by multiple consumer + threads. + + For example, itertools.count does not make thread-safe instances, + but that is easily fixed with: + + atomic_counter = serialize_iterator(itertools.count()) + + """ + + __slots__ = ('_iterator', '_lock') + + def __init__(self, iterable): + self._iterator = iter(iterable) + self._lock = Lock() + + def __iter__(self): + return self + + def __next__(self): + with self._lock: + return next(self._iterator) + + def send(self, value, /): + """Send a value to a generator. + + Raises AttributeError if not a generator. + """ + with self._lock: + return self._iterator.send(value) + + def throw(self, *args): + """Call throw() on a generator. + + Raises AttributeError if not a generator. + """ + with self._lock: + return self._iterator.throw(*args) + + def close(self): + """Call close() on a generator. + + Raises AttributeError if not a generator. + """ + with self._lock: + return self._iterator.close() + + +def synchronized_iterator(func): + """Wrap an iterator-returning callable to make its iterators thread-safe. + + Existing itertools and more-itertools can be wrapped so that their + iterator instances are serialized. + + For example, itertools.count does not make thread-safe instances, + but that is easily fixed with: + + atomic_counter = synchronized_iterator(itertools.count) + + Can also be used as a decorator for generator function definitions + so that the generator instances are serialized:: + + import time + + @synchronized_iterator + def enumerate_and_timestamp(iterable): + for count, value in enumerate(iterable): + yield count, time.time_ns(), value + + """ + + from functools import wraps + + @wraps(func) + def inner(*args, **kwargs): + iterator = func(*args, **kwargs) + return serialize_iterator(iterator) + + return inner + + +def concurrent_tee(iterable, n=2): + """Variant of itertools.tee() but with guaranteed threading semantics. + + Takes a non-threadsafe iterator as an input and creates concurrent + tee objects for other threads to have reliable independent copies of + the data stream. + + The new iterators are only thread-safe if consumed within a single thread. + To share just one of the new iterators across multiple threads, wrap it + with threading.serialize_iterator(). + """ + + if n < 0: + raise ValueError("n must be a non-negative integer") + if n == 0: + return () + iterator = _concurrent_tee(iterable) + result = [iterator] + for _ in range(n - 1): + result.append(_concurrent_tee(iterator)) + return tuple(result) + + +class _concurrent_tee: + __slots__ = ('iterator', 'link', 'lock') + + def __init__(self, iterable): + if isinstance(iterable, _concurrent_tee): + self.iterator = iterable.iterator + self.link = iterable.link + self.lock = iterable.lock + else: + self.iterator = iter(iterable) + self.link = [None, None] + self.lock = Lock() + + def __iter__(self): + return self + + def __next__(self): + link = self.link + if link[1] is None: + with self.lock: + if link[1] is None: + link[0] = next(self.iterator) + link[1] = [None, None] + value, self.link = link + return value + +############################################################ + + # Helper to generate new thread names _counter = _count(1).__next__ def _newname(name_template): @@ -1565,8 +1702,9 @@ def _shutdown(): # normally - that won't happen until the interpreter is nearly dead. So # mark it done here. if _main_thread._os_thread_handle.is_done() and _is_main_interpreter(): - # _shutdown() was already called - return + # _shutdown() was already called, but threads might have started + # in the meantime. + return _thread_shutdown() global _SHUTTING_DOWN _SHUTTING_DOWN = True diff --git a/Lib/timeit.py b/Lib/timeit.py index 0451f66bdf1..01bdfd901e3 100644 --- a/Lib/timeit.py +++ b/Lib/timeit.py @@ -6,35 +6,6 @@ Library usage: see the Timer class. -Command line usage: - python timeit.py [-n N] [-r N] [-s S] [-p] [-h] [--] [statement] - -Options: - -n/--number N: how many times to execute 'statement' (default: see below) - -r/--repeat N: how many times to repeat the timer (default 5) - -s/--setup S: statement to be executed once initially (default 'pass'). - Execution time of this setup statement is NOT timed. - -p/--process: use time.process_time() (default is time.perf_counter()) - -v/--verbose: print raw timing results; repeat for more digits precision - -u/--unit: set the output time unit (nsec, usec, msec, or sec) - -h/--help: print this usage message and exit - --: separate options from statement, use when statement starts with - - statement: statement to be timed (default 'pass') - -A multi-line statement may be given by specifying each line as a -separate argument; indented lines are possible by enclosing an -argument in quotes and using leading spaces. Multiple -s options are -treated similarly. - -If -n is not given, a suitable number of loops is calculated by trying -increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the -total time is at least 0.2 seconds. - -Note: there is a certain baseline overhead associated with executing a -pass statement. It differs between versions. The code here doesn't try -to hide it, but you should be aware of it. The baseline overhead can be -measured by invoking the program without arguments. - Classes: Timer @@ -57,6 +28,7 @@ default_number = 1000000 default_repeat = 5 default_timer = time.perf_counter +default_target_time = 0.2 _globals = globals @@ -133,7 +105,7 @@ def __init__(self, stmt="pass", setup="pass", timer=default_timer, exec(code, global_ns, local_ns) self.inner = local_ns["inner"] - def print_exc(self, file=None): + def print_exc(self, file=None, **kwargs): """Helper to print a traceback from the timed code. Typical use: @@ -149,6 +121,11 @@ def print_exc(self, file=None): The optional file argument directs where the traceback is sent; it defaults to sys.stderr. + + The optional colorize keyword argument controls whether the + traceback is colorized; it defaults to False for programmatic + usage. When used from the command line, this is automatically + set based on terminal capabilities. """ import linecache, traceback if self.src is not None: @@ -158,7 +135,8 @@ def print_exc(self, file=None): dummy_src_name) # else the source is already stored somewhere else - traceback.print_exc(file=file) + kwargs['colorize'] = kwargs.get('colorize', False) + traceback.print_exc(file=file, **kwargs) def timeit(self, number=default_number): """Time 'number' executions of the main statement. @@ -206,12 +184,13 @@ def repeat(self, repeat=default_repeat, number=default_number): r.append(t) return r - def autorange(self, callback=None): - """Return the number of loops and time taken so that total time >= 0.2. + def autorange(self, callback=None, target_time=default_target_time): + """Return the number of loops and time taken so that + total time >= target_time (default is 0.2 seconds). Calls the timeit method with increasing numbers from the sequence - 1, 2, 5, 10, 20, 50, ... until the time taken is at least 0.2 - second. Returns (number, time_taken). + 1, 2, 5, 10, 20, 50, ... until the target time is reached. + Returns (number, time_taken). If *callback* is given and is not None, it will be called after each trial with two arguments: ``callback(number, time_taken)``. @@ -223,7 +202,7 @@ def autorange(self, callback=None): time_taken = self.timeit(number) if callback: callback(number, time_taken) - if time_taken >= 0.2: + if time_taken >= target_time: return (number, time_taken) i *= 10 @@ -257,53 +236,114 @@ def main(args=None, *, _wrap_timer=None): is not None, it must be a callable that accepts a timer function and returns another timer function (used for unit testing). """ + import argparse if args is None: args = sys.argv[1:] - import getopt + import _colorize + colorize = _colorize.can_colorize() + theme = _colorize.get_theme(force_color=colorize).timeit + reset = theme.reset + + epilog = """\ +A multi-line statement may be given by specifying each line as a +separate argument; indented lines are possible by enclosing an +argument in quotes and using leading spaces. Multiple `-s` options are +treated similarly. + +If `-n` is not given, a suitable number of loops is calculated by trying +increasing numbers from the sequence 1, 2, 5, 10, 20, 50, ... until the +total time is at least `--target-time` seconds. + +Note: there is a certain baseline overhead associated with executing a +pass statement. It differs between versions. The code here doesn't try +to hide it, but you should be aware of it. The baseline overhead can be +measured by invoking the program without arguments.""" + + parser = argparse.ArgumentParser( + prog="python -m timeit", + description="""\ +Tool for measuring execution time of small code snippets. + +This module avoids a number of common traps for measuring execution +times. See also Tim Peters' introduction to the Algorithms chapter in +the Python Cookbook, published by O'Reilly. + +Library usage: see the `Timer` class.""", + epilog=epilog, + formatter_class=argparse.RawDescriptionHelpFormatter, + ) + parser.add_argument( + "-n", + "--number", + type=int, + default=0, + help="how many times to execute 'statement' (default: see below)", + ) + parser.add_argument( + "-r", + "--repeat", + type=int, + default=default_repeat, + help="how many times to repeat the timer (default %(default)s)", + ) + parser.add_argument( + "-s", + "--setup", + action="append", + default=[], + help="statement to be executed once initially. " + "Execution time of this setup statement is NOT timed. " + "(default 'pass')", + ) + parser.add_argument( + "-p", + "--process", + action="store_true", + help="use `time.process_time()` (default is `time.perf_counter()`)", + ) + parser.add_argument( + "-t", + "--target-time", + type=float, + default=default_target_time, + help="if `--number` is 0 the code will run until it takes " + "at least this many seconds (default %(default)s)", + ) + parser.add_argument( + "-v", + "--verbose", + action="count", + default=0, + help="print raw timing results; repeat for more digits precision", + ) + parser.add_argument( + "-u", + "--unit", + default=None, + choices=["nsec", "usec", "msec", "sec"], + help="set the output time unit", + ) + parser.add_argument( + "statement", + nargs="*", + default=["pass"], + help="statement to be timed (default 'pass')", + ) try: - opts, args = getopt.getopt(args, "n:u:s:r:pvh", - ["number=", "setup=", "repeat=", - "process", "verbose", "unit=", "help"]) - except getopt.error as err: - print(err) - print("use -h/--help for command line help") - return 2 - - timer = default_timer - stmt = "\n".join(args) or "pass" - number = 0 # auto-determine - setup = [] - repeat = default_repeat - verbose = 0 - time_unit = None + ns = parser.parse_args(args) + except SystemExit as e: + return e.code + + timer = time.process_time if ns.process else default_timer + stmt = "\n".join(ns.statement) or "pass" + number = ns.number + target_time = ns.target_time + setup = "\n".join(ns.setup) or "pass" + repeat = max(ns.repeat, 1) + verbose = ns.verbose + time_unit = ns.unit units = {"nsec": 1e-9, "usec": 1e-6, "msec": 1e-3, "sec": 1.0} - precision = 3 - for o, a in opts: - if o in ("-n", "--number"): - number = int(a) - if o in ("-s", "--setup"): - setup.append(a) - if o in ("-u", "--unit"): - if a in units: - time_unit = a - else: - print("Unrecognized unit. Please select nsec, usec, msec, or sec.", - file=sys.stderr) - return 2 - if o in ("-r", "--repeat"): - repeat = int(a) - if repeat <= 0: - repeat = 1 - if o in ("-p", "--process"): - timer = time.process_time - if o in ("-v", "--verbose"): - if verbose: - precision += 1 - verbose += 1 - if o in ("-h", "--help"): - print(__doc__, end="") - return 0 - setup = "\n".join(setup) or "pass" + precision = 3 + max(verbose - 1, 0) # Include the current directory, so that local imports work (sys.path # contains the directory of this script, rather than the current @@ -315,18 +355,21 @@ def main(args=None, *, _wrap_timer=None): t = Timer(stmt, setup, timer) if number == 0: - # determine number so that 0.2 <= total time < 2.0 + # determine number so that total time >= target_time callback = None if verbose: def callback(number, time_taken): - msg = "{num} loop{s} -> {secs:.{prec}g} sec" - plural = (number != 1) - print(msg.format(num=number, s='s' if plural else '', - secs=time_taken, prec=precision)) + s = "" if number == 1 else "s" + print( + f"{number} loop{s} " + f"{theme.punctuation}-> " + f"{theme.timing}{time_taken:.{precision}g} sec{reset}" + ) + try: - number, _ = t.autorange(callback) + number, _ = t.autorange(callback, target_time) except: - t.print_exc() + t.print_exc(colorize=colorize) return 1 if verbose: @@ -335,7 +378,7 @@ def callback(number, time_taken): try: raw_timings = t.repeat(repeat, number) except: - t.print_exc() + t.print_exc(colorize=colorize) return 1 def format_time(dt): @@ -353,24 +396,34 @@ def format_time(dt): return "%.*g %s" % (precision, dt / scale, unit) if verbose: - print("raw times: %s" % ", ".join(map(format_time, raw_timings))) + raw = f"{theme.punctuation}, ".join( + f"{theme.timing}{t}" for t in map(format_time, raw_timings) + ) + print(f"raw times: {raw}{reset}") print() timings = [dt / number for dt in raw_timings] - best = min(timings) - print("%d loop%s, best of %d: %s per loop" - % (number, 's' if number != 1 else '', - repeat, format_time(best))) - best = min(timings) worst = max(timings) + s = "" if number == 1 else "s" + print( + f"{number} loop{s}, best of {repeat}: " + f"{theme.best}{format_time(best)}{reset} " + f"{theme.per_loop}per loop{reset}" + ) + if worst >= best * 4: import warnings - warnings.warn_explicit("The test results are likely unreliable. " - "The worst time (%s) was more than four times " - "slower than the best time (%s)." - % (format_time(worst), format_time(best)), - UserWarning, '', 0) + + print(file=sys.stderr) + warnings.warn_explicit( + f"{theme.warning}The test results are likely unreliable. " + f"The {theme.warning_worst}worst time ({format_time(worst)})" + f"{theme.warning} was more than four times slower than the " + f"{theme.warning_best}best time ({format_time(best)})" + f"{theme.warning}.{reset}", + UserWarning, "", 0, + ) return None diff --git a/Lib/tkinter/__init__.py b/Lib/tkinter/__init__.py index 01ea2ab62cf..63b08b3e82d 100644 --- a/Lib/tkinter/__init__.py +++ b/Lib/tkinter/__init__.py @@ -3,7 +3,7 @@ Tkinter provides classes which allow the display, positioning and control of widgets. Toplevel widgets are Tk and Toplevel. Other widgets are Frame, Label, Entry, Text, Canvas, Button, Radiobutton, -Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox +Checkbutton, Scale, Listbox, Scrollbar, OptionMenu, Spinbox, LabelFrame and PanedWindow. Properties of the widgets are specified with keyword arguments. @@ -255,6 +255,10 @@ class Event: type - type of the event as a number widget - widget in which the event occurred delta - delta of wheel movement (MouseWheel) + detail - certain fixed strings (see Tcl/Tk documentation) + (Enter, Leave, FocusIn, FocusOut, ConfigureRequest) + user_data - data string which was passed to event_generate() or empty + string (VirtualEvent) """ def __repr__(self): @@ -501,12 +505,14 @@ def trace_variable(self, mode, callback): Return the name of the callback. This deprecated method wraps a deprecated Tcl method removed - in Tcl 9.0. Use trace_add() instead. + in Tcl 9.0 and will be removed in Python 3.17. Use trace_add() + instead. """ import warnings warnings.warn( - "trace_variable() is deprecated and not supported with Tcl 9; " - "use trace_add() instead.", + "trace_variable() is deprecated and will be removed in Python " + "3.17; use trace_add() instead. It is not supported with " + "Tcl 9.", DeprecationWarning, stacklevel=2) cbname = self._register(callback) self._tk.call("trace", "variable", self._name, mode, cbname) @@ -521,12 +527,14 @@ def trace_vdelete(self, mode, cbname): CBNAME is the name of the callback returned from trace_variable or trace. This deprecated method wraps a deprecated Tcl method removed - in Tcl 9.0. Use trace_remove() instead. + in Tcl 9.0 and will be removed in Python 3.17. Use trace_remove() + instead. """ import warnings warnings.warn( - "trace_vdelete() is deprecated and not supported with Tcl 9; " - "use trace_remove() instead.", + "trace_vdelete() is deprecated and will be removed in Python " + "3.17; use trace_remove() instead. It is not supported with " + "Tcl 9.", DeprecationWarning, stacklevel=2) self._tk.call("trace", "vdelete", self._name, mode, cbname) cbname = self._tk.splitlist(cbname)[0] @@ -544,12 +552,14 @@ def trace_vinfo(self): """Return all trace callback information. This deprecated method wraps a deprecated Tcl method removed - in Tcl 9.0. Use trace_info() instead. + in Tcl 9.0 and will be removed in Python 3.17. Use trace_info() + instead. """ import warnings warnings.warn( - "trace_vinfo() is deprecated and not supported with Tcl 9; " - "use trace_info() instead.", + "trace_vinfo() is deprecated and will be removed in Python " + "3.17; use trace_info() instead. It is not supported with " + "Tcl 9.", DeprecationWarning, stacklevel=2) return [self._tk.splitlist(x) for x in self._tk.splitlist( self._tk.call("trace", "vinfo", self._name))] @@ -817,7 +827,10 @@ def focus_get(self): the focus.""" name = self.tk.call('focus') if name == 'none' or not name: return None - return self._nametowidget(name) + try: + return self._nametowidget(name) + except KeyError: + return None def focus_displayof(self): """Return the widget which has currently the focus on the @@ -826,14 +839,20 @@ def focus_displayof(self): Return None if the application does not have the focus.""" name = self.tk.call('focus', '-displayof', self._w) if name == 'none' or not name: return None - return self._nametowidget(name) + try: + return self._nametowidget(name) + except KeyError: + return None def focus_lastfor(self): """Return the widget which would have the focus if top level for this widget gets the focus from the window manager.""" name = self.tk.call('focus', '-lastfor', self._w) if name == 'none' or not name: return None - return self._nametowidget(name) + try: + return self._nametowidget(name) + except KeyError: + return None def tk_focusFollowsMouse(self): """The widget under mouse will get automatically focus. Can not @@ -1236,7 +1255,10 @@ def winfo_containing(self, rootX, rootY, displayof=0): + self._displayof(displayof) + (rootX, rootY) name = self.tk.call(args) if not name: return None - return self._nametowidget(name) + try: + return self._nametowidget(name) + except KeyError: + return None def winfo_depth(self): """Return the number of bits per pixel.""" @@ -1499,13 +1521,26 @@ def bindtags(self, tagList=None): else: self.tk.call('bindtags', self._w, tagList) - def _bind(self, what, sequence, func, add, needcleanup=1): + def _delete_bind_commands(self, *what): + lines = self.tk.call(what).split('\n') + p = re.compile(r'if \{"\[([^ ]+) .*\]" == "break"\} break') + for line in lines: + m = p.fullmatch(line) + if m: + funcid = m[1] + try: + self.deletecommand(funcid) + except TclError: + pass + + def _bind(self, what, sequence, func, add): """Internal function.""" if isinstance(func, str): self.tk.call(what + (sequence, func)) elif func: - funcid = self._register(func, self._substitute, - needcleanup) + if not add: + self._delete_bind_commands(*what, sequence) + funcid = self._register(func, self._substitute, needcleanup=True) cmd = ('%sif {"[%s %s]" == "break"} break\n' % (add and '+' or '', @@ -1538,7 +1573,7 @@ def bind(self, sequence=None, func=None, add=None): for pressing A and the Alt key (KeyPress can be omitted). An event pattern can also be a virtual event of the form <> where AString can be arbitrary. This - event can be generated by event_generate. + event can be generated by event_generate(). If events are concatenated they must appear shortly after each other. @@ -1571,6 +1606,7 @@ def unbind(self, sequence, funcid=None): def _unbind(self, what, funcid=None): if funcid is None: + self._delete_bind_commands(*what) self.tk.call(*what, '') else: lines = self.tk.call(what).split('\n') @@ -1587,7 +1623,7 @@ def bind_all(self, sequence=None, func=None, add=None): An additional boolean parameter ADD specifies whether FUNC will be called additionally to the other bound function or whether it will replace the previous function. See bind for the return value.""" - return self._root()._bind(('bind', 'all'), sequence, func, add, True) + return self._root()._bind(('bind', 'all'), sequence, func, add) def unbind_all(self, sequence): """Unbind for all widgets for event SEQUENCE all functions.""" @@ -1601,7 +1637,7 @@ def bind_class(self, className, sequence=None, func=None, add=None): whether it will replace the previous function. See bind for the return value.""" - return self._root()._bind(('bind', className), sequence, func, add, True) + return self._root()._bind(('bind', className), sequence, func, add) def unbind_class(self, className, sequence): """Unbind for all widgets with bindtag CLASSNAME for event SEQUENCE @@ -1688,7 +1724,16 @@ def nametowidget(self, name): for n in name: if not n: break - w = w.children[n] + try: + w = w.children[n] + except KeyError: + # Menu clones (a menu used as a menubar or a cascade) get + # auto-generated names where each path component is the + # original name prefixed with one or more '#' clone markers. + # Map such a name back to the original widget. + if not n.startswith('#'): + raise + w = w.children[n.rsplit('#', 1)[-1]] return w @@ -1723,7 +1768,7 @@ def _root(self): w = self while w.master is not None: w = w.master return w - _subst_format = ('%#', '%b', '%f', '%h', '%k', + _subst_format = ('%#', '%b', '%d', '%f', '%h', '%k', '%s', '%t', '%w', '%x', '%y', '%A', '%E', '%K', '%N', '%W', '%T', '%X', '%Y', '%D') _subst_format_str = " ".join(_subst_format) @@ -1744,11 +1789,14 @@ def getint_event(s): if any(isinstance(s, tuple) for s in args): args = [s[0] if isinstance(s, tuple) and len(s) == 1 else s for s in args] - nsign, b, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args - # Missing: (a, c, d, m, o, v, B, R) + nsign, b, d, f, h, k, s, t, w, x, y, A, E, K, N, W, T, X, Y, D = args + # Missing: (a, c, m, o, v, B, R) e = Event() # serial field: valid for all events # number of button: ButtonPress and ButtonRelease events only + # detail: for Enter, Leave, FocusIn, FocusOut and ConfigureRequest + # events certain fixed strings (see Tcl/Tk documentation) + # user_data: data string from a virtual event or an empty string # height field: Configure, ConfigureRequest, Create, # ResizeRequest, and Expose events only # keycode field: KeyPress and KeyRelease events only @@ -1762,6 +1810,12 @@ def getint_event(s): # KeyRelease, and Motion events e.serial = getint(nsign) e.num = getint_event(b) + if T == EventType.VirtualEvent: + e.user_data = d + e.detail = '??' + else: + e.user_data = '??' + e.detail = d try: e.focus = getboolean(f) except TclError: pass e.height = getint_event(h) @@ -1848,6 +1902,7 @@ def cget(self, key): return self.tk.call(self._w, 'cget', '-' + key) __getitem__ = cget + __iter__ = None # prevent using __getitem__ for iteration def __setitem__(self, key, value): self.configure({key: value}) @@ -1884,9 +1939,21 @@ def pack_propagate(self, flag=_noarg_): propagate = pack_propagate - def pack_slaves(self): + def pack_content(self): """Returns a list of all of the content widgets in the packing order for this container.""" + try: + res = self.tk.call('pack', 'content', self._w) + except TclError: + if self.info_patchlevel() >= (8, 6): + raise + res = self.tk.call('pack', 'slaves', self._w) + return [self._nametowidget(x) for x in self.tk.splitlist(res)] + + content = pack_content + + def pack_slaves(self): + """Synonym for pack_content().""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call('pack', 'slaves', self._w))] @@ -1894,9 +1961,19 @@ def pack_slaves(self): slaves = pack_slaves # Place method that applies to the container widget - def place_slaves(self): + def place_content(self): """Returns a list of all the content widgets for which this widget is the container.""" + try: + res = self.tk.call('place', 'content', self._w) + except TclError: + if self.info_patchlevel() >= (8, 6): + raise + res = self.tk.call('place', 'slaves', self._w) + return [self._nametowidget(x) for x in self.tk.splitlist(res)] + + def place_slaves(self): + """Synonym for place_content().""" return [self._nametowidget(x) for x in self.tk.splitlist( self.tk.call( @@ -2017,7 +2094,7 @@ def grid_size(self): size = grid_size - def grid_slaves(self, row=None, column=None): + def grid_content(self, row=None, column=None): """Returns a list of the content widgets. If no arguments are supplied, a list of all of the content in this @@ -2026,6 +2103,21 @@ def grid_slaves(self, row=None, column=None): column is returned. """ args = () + if row is not None: + args = args + ('-row', row) + if column is not None: + args = args + ('-column', column) + try: + res = self.tk.call('grid', 'content', self._w, *args) + except TclError: + if self.info_patchlevel() >= (8, 6): + raise + res = self.tk.call('grid', 'slaves', self._w, *args) + return [self._nametowidget(x) for x in self.tk.splitlist(res)] + + def grid_slaves(self, row=None, column=None): + """Synonym for grid_content().""" + args = () if row is not None: args = args + ('-row', row) if column is not None: @@ -2344,7 +2436,7 @@ def wm_iconphoto(self, default=False, *args): # new in Tk 8.5 def wm_iconposition(self, x=None, y=None): """Set the position of the icon of this widget to X and Y. Return - a tuple of the current values of X and X if None is given.""" + a tuple of the current values of X and Y if None is given.""" return self._getints(self.tk.call( 'wm', 'iconposition', self._w, x, y)) @@ -2547,11 +2639,13 @@ def readprofile(self, baseName, className): if os.path.isfile(class_tcl): self.tk.call('source', class_tcl) if os.path.isfile(class_py): - exec(open(class_py).read(), dir) + with open(class_py, 'rb') as f: + exec(f.read(), dir) if os.path.isfile(base_tcl): self.tk.call('source', base_tcl) if os.path.isfile(base_py): - exec(open(base_py).read(), dir) + with open(base_py, 'rb') as f: + exec(f.read(), dir) def report_callback_exception(self, exc, val, tb): """Report callback exception on sys.stderr. @@ -2640,6 +2734,7 @@ def pack_info(self): info = pack_info propagate = pack_propagate = Misc.pack_propagate + content = pack_content = Misc.pack_content slaves = pack_slaves = Misc.pack_slaves @@ -2697,6 +2792,7 @@ def place_info(self): return d info = place_info + content = place_content = Misc.place_content slaves = place_slaves = Misc.place_slaves @@ -2752,6 +2848,7 @@ def grid_info(self): propagate = grid_propagate = Misc.grid_propagate rowconfigure = grid_rowconfigure = Misc.grid_rowconfigure size = grid_size = Misc.grid_size + content = grid_content = Misc.grid_content slaves = grid_slaves = Misc.grid_slaves @@ -2834,10 +2931,11 @@ class Toplevel(BaseWidget, Wm): def __init__(self, master=None, cnf={}, **kw): """Construct a toplevel widget with the parent MASTER. - Valid option names: background, bd, bg, borderwidth, class, - colormap, container, cursor, height, highlightbackground, - highlightcolor, highlightthickness, menu, relief, screen, takefocus, - use, visual, width.""" + Valid option names: background, backgroundimage (Tk 9.0+), bd, bg, + bgimg (Tk 9.0+), borderwidth, class, colormap, container, + cursor, height, highlightbackground, highlightcolor, + highlightthickness, menu, padx, pady, relief, screen, + takefocus, tile (Tk 9.0+), use, visual, width.""" if kw: cnf = _cnfmerge((cnf, kw)) extra = () @@ -2957,7 +3055,7 @@ def addtag_withtag(self, newtag, tagOrId): """Add tag NEWTAG to all items with TAGORID.""" self.addtag(newtag, 'withtag', tagOrId) - def bbox(self, *args): + def bbox(self, *args): # overrides Misc.bbox """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses all items with tags specified as arguments.""" return self._getints( @@ -3096,7 +3194,7 @@ def find_withtag(self, tagOrId): """Return all items with TAGORID.""" return self.find('withtag', tagOrId) - def focus(self, *args): + def focus(self, *args): # overrides Misc.focus """Set focus to the first item specified in ARGS.""" return self.tk.call((self._w, 'focus') + args) @@ -3142,7 +3240,7 @@ def tag_lower(self, *args): (optional below another item).""" self.tk.call((self._w, 'lower') + args) - lower = tag_lower + lower = tag_lower # overrides Misc.lower def move(self, *args): """Move an item TAGORID given in ARGS.""" @@ -3170,7 +3268,7 @@ def tag_raise(self, *args): (optional above another item).""" self.tk.call((self._w, 'raise') + args) - lift = tkraise = tag_raise + lift = tkraise = tag_raise # overrides Misc.tkraise def scale(self, *args): """Scale item TAGORID with XORIGIN, YORIGIN, XSCALE, YSCALE.""" @@ -3220,12 +3318,13 @@ def __init__(self, master=None, cnf={}, **kw): """Construct a checkbutton widget with the parent MASTER. Valid option names: activebackground, activeforeground, anchor, - background, bd, bg, bitmap, borderwidth, command, cursor, - disabledforeground, fg, font, foreground, height, - highlightbackground, highlightcolor, highlightthickness, image, - indicatoron, justify, offvalue, onvalue, padx, pady, relief, - selectcolor, selectimage, state, takefocus, text, textvariable, - underline, variable, width, wraplength.""" + background, bd, bg, bitmap, borderwidth, command, compound, + cursor, disabledforeground, fg, font, foreground, height, + highlightbackground, highlightcolor, highlightthickness, + image, indicatoron, justify, offrelief, offvalue, onvalue, + overrelief, padx, pady, relief, selectcolor, selectimage, + state, takefocus, text, textvariable, tristateimage, + tristatevalue, underline, variable, width, wraplength.""" Widget.__init__(self, master, 'checkbutton', cnf, kw) def _setup(self, master, cnf): @@ -3269,13 +3368,15 @@ def __init__(self, master=None, cnf={}, **kw): """Construct an entry widget with the parent MASTER. Valid option names: background, bd, bg, borderwidth, cursor, - exportselection, fg, font, foreground, highlightbackground, - highlightcolor, highlightthickness, insertbackground, - insertborderwidth, insertofftime, insertontime, insertwidth, - invalidcommand, invcmd, justify, relief, selectbackground, - selectborderwidth, selectforeground, show, state, takefocus, - textvariable, validate, validatecommand, vcmd, width, - xscrollcommand.""" + disabledbackground, disabledforeground, exportselection, fg, + font, foreground, highlightbackground, highlightcolor, + highlightthickness, insertbackground, insertborderwidth, + insertofftime, insertontime, insertwidth, invalidcommand, + invcmd, justify, locale (Tk 9.1+), placeholder (Tk 9.0+), + placeholderforeground (Tk 9.0+), readonlybackground, relief, + selectbackground, selectborderwidth, selectforeground, show, + state, takefocus, textvariable, validate, validatecommand, + vcmd, width, xscrollcommand.""" Widget.__init__(self, master, 'entry', cnf, kw) def delete(self, first, last=None): @@ -3315,7 +3416,7 @@ def selection_adjust(self, index): select_adjust = selection_adjust - def selection_clear(self): + def selection_clear(self): # overrides Misc.selection_clear """Clear the selection if it is in this widget.""" self.tk.call(self._w, 'selection', 'clear') @@ -3354,9 +3455,11 @@ class Frame(Widget): def __init__(self, master=None, cnf={}, **kw): """Construct a frame widget with the parent MASTER. - Valid option names: background, bd, bg, borderwidth, class, - colormap, container, cursor, height, highlightbackground, - highlightcolor, highlightthickness, relief, takefocus, visual, width.""" + Valid option names: background, backgroundimage (Tk 9.0+), bd, bg, + bgimg (Tk 9.0+), borderwidth, class, colormap, container, + cursor, height, highlightbackground, highlightcolor, + highlightthickness, padx, pady, relief, takefocus, tile (Tk + 9.0+), visual, width.""" cnf = _cnfmerge((cnf, kw)) extra = () if 'class_' in cnf: @@ -3386,7 +3489,8 @@ def __init__(self, master=None, cnf={}, **kw): WIDGET-SPECIFIC OPTIONS - height, state, width + compound, height, state, + textangle (Tk 9.1+), width """ Widget.__init__(self, master, 'label', cnf, kw) @@ -3398,18 +3502,21 @@ class Listbox(Widget, XView, YView): def __init__(self, master=None, cnf={}, **kw): """Construct a listbox widget with the parent MASTER. - Valid option names: background, bd, bg, borderwidth, cursor, - exportselection, fg, font, foreground, height, highlightbackground, - highlightcolor, highlightthickness, relief, selectbackground, - selectborderwidth, selectforeground, selectmode, setgrid, takefocus, - width, xscrollcommand, yscrollcommand, listvariable.""" + Valid option names: activestyle, background, bd, bg, borderwidth, + cursor, disabledforeground, exportselection, fg, font, + foreground, height, highlightbackground, highlightcolor, + highlightthickness, inactiveselectbackground (Tk 9.1+), + inactiveselectforeground (Tk 9.1+), justify, listvariable, + relief, selectbackground, selectborderwidth, selectforeground, + selectmode, setgrid, state, takefocus, width, xscrollcommand, + yscrollcommand.""" Widget.__init__(self, master, 'listbox', cnf, kw) def activate(self, index): """Activate item identified by INDEX.""" self.tk.call(self._w, 'activate', index) - def bbox(self, index): + def bbox(self, index): # overrides Misc.bbox """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the item identified by the given index.""" return self._getints(self.tk.call(self._w, 'bbox', index)) or None @@ -3465,7 +3572,7 @@ def selection_anchor(self, index): select_anchor = selection_anchor - def selection_clear(self, first, last=None): + def selection_clear(self, first, last=None): # overrides Misc.selection_clear """Clear the selection from FIRST to LAST (included).""" self.tk.call(self._w, 'selection', 'clear', first, last) @@ -3486,7 +3593,7 @@ def selection_set(self, first, last=None): select_set = selection_set - def size(self): + def size(self): # overrides Misc.size """Return the number of elements in the listbox.""" return self.tk.getint(self.tk.call(self._w, 'size')) @@ -3512,7 +3619,8 @@ def __init__(self, master=None, cnf={}, **kw): """Construct menu widget with the parent MASTER. Valid option names: activebackground, activeborderwidth, - activeforeground, background, bd, bg, borderwidth, cursor, + activeforeground, activerelief (Tk 9.0+), background, bd, bg, + borderwidth, cursor, disabledforeground, fg, font, foreground, postcommand, relief, selectcolor, takefocus, tearoff, tearoffcommand, title, type.""" Widget.__init__(self, master, 'menu', cnf, kw) @@ -3642,6 +3750,14 @@ class Menubutton(Widget): """Menubutton widget, obsolete since Tk8.0.""" def __init__(self, master=None, cnf={}, **kw): + """Construct a menubutton widget with the parent MASTER. + + Valid option names: activebackground, activeforeground, anchor, + background, bd, bg, bitmap, borderwidth, compound, cursor, + direction, disabledforeground, fg, font, foreground, height, + highlightbackground, highlightcolor, highlightthickness, + image, indicatoron, justify, menu, padx, pady, relief, state, + takefocus, text, textvariable, underline, width, wraplength.""" Widget.__init__(self, master, 'menubutton', cnf, kw) @@ -3649,6 +3765,12 @@ class Message(Widget): """Message widget to display multiline text. Obsolete since Label does it too.""" def __init__(self, master=None, cnf={}, **kw): + """Construct a message widget with the parent MASTER. + + Valid option names: anchor, aspect, background, bd, bg, borderwidth, + cursor, fg, font, foreground, highlightbackground, + highlightcolor, highlightthickness, justify, padx, pady, + relief, takefocus, text, textvariable, width.""" Widget.__init__(self, master, 'message', cnf, kw) @@ -3659,12 +3781,13 @@ def __init__(self, master=None, cnf={}, **kw): """Construct a radiobutton widget with the parent MASTER. Valid option names: activebackground, activeforeground, anchor, - background, bd, bg, bitmap, borderwidth, command, cursor, - disabledforeground, fg, font, foreground, height, - highlightbackground, highlightcolor, highlightthickness, image, - indicatoron, justify, padx, pady, relief, selectcolor, selectimage, - state, takefocus, text, textvariable, underline, value, variable, - width, wraplength.""" + background, bd, bg, bitmap, borderwidth, command, compound, + cursor, disabledforeground, fg, font, foreground, height, + highlightbackground, highlightcolor, highlightthickness, + image, indicatoron, justify, offrelief, overrelief, padx, + pady, relief, selectcolor, selectimage, state, takefocus, + text, textvariable, tristateimage, tristatevalue, underline, + value, variable, width, wraplength.""" Widget.__init__(self, master, 'radiobutton', cnf, kw) def deselect(self): @@ -3795,14 +3918,16 @@ def __init__(self, master=None, cnf={}, **kw): WIDGET-SPECIFIC OPTIONS - autoseparators, height, maxundo, - spacing1, spacing2, spacing3, - state, tabs, undo, width, wrap, + autoseparators, blockcursor, endline, + height, inactiveselectbackground, + insertunfocussed, locale (Tk 9.1+), maxundo, + spacing1, spacing2, spacing3, startline, + state, tabs, tabstyle, undo, width, wrap, """ Widget.__init__(self, master, 'text', cnf, kw) - def bbox(self, index): + def bbox(self, index): # overrides Misc.bbox """Return a tuple of (x,y,width,height) which gives the bounding box of the visible part of the character at the given index.""" return self._getints( @@ -3987,7 +4112,7 @@ def image_create(self, index, cnf={}, **kw): self._w, "image", "create", index, *self._options(cnf, kw)) - def image_names(self): + def image_names(self): # overrides Misc.image_names """Return all names of embedded images in this widget.""" return self.tk.call(self._w, "image", "names") @@ -4059,8 +4184,9 @@ def scan_dragto(self, x, y): self.tk.call(self._w, 'scan', 'dragto', x, y) def search(self, pattern, index, stopindex=None, - forwards=None, backwards=None, exact=None, - regexp=None, nocase=None, count=None, elide=None): + forwards=None, backwards=None, exact=None, + regexp=None, nocase=None, count=None, + elide=None, *, nolinestop=None, strictlimits=None): """Search PATTERN beginning from INDEX until STOPINDEX. Return the index of the first character of a match or an empty string.""" @@ -4072,12 +4198,39 @@ def search(self, pattern, index, stopindex=None, if nocase: args.append('-nocase') if elide: args.append('-elide') if count: args.append('-count'); args.append(count) + if nolinestop: args.append('-nolinestop') + if strictlimits: args.append('-strictlimits') if pattern and pattern[0] == '-': args.append('--') args.append(pattern) args.append(index) - if stopindex: args.append(stopindex) + if stopindex is not None: args.append(stopindex) return str(self.tk.call(tuple(args))) + def search_all(self, pattern, index, stopindex=None, *, + forwards=None, backwards=None, exact=None, + regexp=None, nocase=None, count=None, + elide=None, nolinestop=None, overlap=None, + strictlimits=None): + """Search all occurrences of PATTERN from INDEX to STOPINDEX. + Return a tuple of indices where matches begin.""" + args = [self._w, 'search', '-all'] + if forwards: args.append('-forwards') + if backwards: args.append('-backwards') + if exact: args.append('-exact') + if regexp: args.append('-regexp') + if nocase: args.append('-nocase') + if elide: args.append('-elide') + if count: args.append('-count'); args.append(count) + if nolinestop: args.append('-nolinestop') + if overlap: args.append('-overlap') + if strictlimits: args.append('-strictlimits') + if pattern and pattern[0] == '-': args.append('--') + args.append(pattern) + args.append(index) + if stopindex is not None: args.append(stopindex) + result = self.tk.call(tuple(args)) + return self.tk.splitlist(result) + def see(self, index): """Scroll such that the character at INDEX is visible.""" self.tk.call(self._w, 'see', index) @@ -4291,6 +4444,8 @@ def __setitem__(self, key, value): def __getitem__(self, key): return self.tk.call(self.name, 'configure', '-'+key) + __iter__ = None # prevent using __getitem__ for iteration + def configure(self, **kw): """Configure the image.""" res = () @@ -4625,14 +4780,17 @@ def __init__(self, master=None, cnf={}, **kw): buttondownrelief, buttonuprelief, command, disabledbackground, disabledforeground, format, from, - invalidcommand, increment, + invalidcommand, invcmd, increment, + locale (Tk 9.1+), + placeholder (Tk 9.0+), + placeholderforeground (Tk 9.0+), readonlybackground, state, to, - validate, validatecommand values, + validate, validatecommand, vcmd, values, width, wrap, """ Widget.__init__(self, master, 'spinbox', cnf, kw) - def bbox(self, index): + def bbox(self, index): # overrides Misc.bbox """Return a tuple of X1,Y1,X2,Y2 coordinates for a rectangle which encloses the character given by index. @@ -4741,7 +4899,7 @@ def selection_adjust(self, index): """ return self.selection("adjust", index) - def selection_clear(self): + def selection_clear(self): # overrides Misc.selection_clear """Clear the selection If the selection isn't in this widget then the @@ -4816,8 +4974,9 @@ def __init__(self, master=None, cnf={}, **kw): WIDGET-SPECIFIC OPTIONS handlepad, handlesize, opaqueresize, - sashcursor, sashpad, sashrelief, - sashwidth, showhandle, + proxybackground, proxyborderwidth, + proxyrelief, sashcursor, sashpad, + sashrelief, sashwidth, showhandle, """ Widget.__init__(self, master, 'panedwindow', cnf, kw) @@ -4838,7 +4997,7 @@ def remove(self, child): """ self.tk.call(self._w, 'forget', child) - forget = remove + forget = remove # overrides Pack.forget def identify(self, x, y): """Identify the panedwindow component at point x, y diff --git a/Lib/tkinter/colorchooser.py b/Lib/tkinter/colorchooser.py index e2fb69dba92..4085bde1637 100644 --- a/Lib/tkinter/colorchooser.py +++ b/Lib/tkinter/colorchooser.py @@ -1,3 +1,5 @@ +"""Interface to the native Tk color selection dialog.""" + # tk common color chooser dialogue # # this module provides an interface to the native color dialogue diff --git a/Lib/tkinter/commondialog.py b/Lib/tkinter/commondialog.py index 86f5387e001..408cedc345d 100644 --- a/Lib/tkinter/commondialog.py +++ b/Lib/tkinter/commondialog.py @@ -1,3 +1,5 @@ +"""Base class for the Tk common dialogs.""" + # base class for tk common dialogues # # this module provides a base class for accessing the common diff --git a/Lib/tkinter/dialog.py b/Lib/tkinter/dialog.py index 36ae6c277cb..ef005af0d5a 100644 --- a/Lib/tkinter/dialog.py +++ b/Lib/tkinter/dialog.py @@ -1,5 +1,7 @@ # dialog.py -- Tkinter interface to the tk_dialog script. +"""Classic Tk dialog box, wrapping the tk_dialog script.""" + from tkinter import _cnfmerge, Widget, TclError, Button, Pack __all__ = ["Dialog"] @@ -8,6 +10,8 @@ class Dialog(Widget): + """A modal dialog box built from the classic (non-themed) Tk widgets.""" + def __init__(self, master=None, cnf={}, **kw): cnf = _cnfmerge((cnf, kw)) self.widgetName = '__dialog__' @@ -21,7 +25,8 @@ def __init__(self, master=None, cnf={}, **kw): try: Widget.destroy(self) except TclError: pass - def destroy(self): pass + def destroy(self): + """Do nothing; the dialog window is already destroyed.""" def _test(): diff --git a/Lib/tkinter/font.py b/Lib/tkinter/font.py index 3e24e28ef58..6199a04feaa 100644 --- a/Lib/tkinter/font.py +++ b/Lib/tkinter/font.py @@ -1,3 +1,5 @@ +"""Utilities to help work with fonts in Tkinter.""" + # Tkinter font wrapper # # written by Fredrik Lundh, February 1998 @@ -6,7 +8,6 @@ import itertools import tkinter -__version__ = "0.9" __all__ = ["NORMAL", "ROMAN", "BOLD", "ITALIC", "nametofont", "Font", "families", "names"] @@ -72,8 +73,15 @@ def __init__(self, root=None, font=None, name=None, exists=False, root = tkinter._get_default_root('use font') tk = getattr(root, 'tk', root) if font: - # get actual settings corresponding to the given font - font = tk.splitlist(tk.call("font", "actual", font)) + # start from the settings of the given font + try: + # a named font: copy its options, preserving the size, + # which can be negative (specified in pixels) + font = tk.splitlist(tk.call("font", "configure", font)) + except tkinter.TclError: + # a font description: resolve it ("font configure" only + # accepts a font name); this loses a size in pixels + font = tk.splitlist(tk.call("font", "actual", font)) else: font = self._set(options) if not name: @@ -83,7 +91,8 @@ def __init__(self, root=None, font=None, name=None, exists=False, if exists: self.delete_font = False # confirm font exists - if self.name not in tk.splitlist(tk.call("font", "names")): + name = getattr(name, 'string', name) # can be a Tcl object + if name not in tk.splitlist(tk.call("font", "names")): raise tkinter._tkinter.TclError( "named font %s does not already exist" % (self.name,)) # if font config info supplied, apply it @@ -98,7 +107,7 @@ def __init__(self, root=None, font=None, name=None, exists=False, self._call = tk.call def __str__(self): - return self.name + return str(self.name) def __repr__(self): return f"<{self.__class__.__module__}.{self.__class__.__qualname__}" \ @@ -107,7 +116,13 @@ def __repr__(self): def __eq__(self, other): if not isinstance(other, Font): return NotImplemented - return self.name == other.name and self._tk == other._tk + name = self.name + other_name = other.name + if type(name) is not type(other_name): + # A Tcl object does not compare equal to a string. + name = getattr(name, 'string', name) + other_name = getattr(other_name, 'string', other_name) + return name == other_name and self._tk == other._tk def __getitem__(self, key): return self.cget(key) @@ -115,6 +130,8 @@ def __getitem__(self, key): def __setitem__(self, key, value): self.configure(**{key: value}) + __iter__ = None # prevent using __getitem__ for iteration + def __del__(self): try: if self.delete_font: @@ -124,7 +141,7 @@ def __del__(self): def copy(self): "Return a distinct copy of the current font" - return Font(self._tk, **self.actual()) + return Font(self._tk, self.name) def actual(self, option=None, displayof=None): "Return actual font attributes" @@ -198,6 +215,15 @@ def names(root=None): return root.tk.splitlist(root.tk.call("font", "names")) +def __getattr__(name): + if name == "__version__": + from warnings import _deprecated + + _deprecated("__version__", remove=(3, 20)) + return "0.9" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + # -------------------------------------------------------------------- # test stuff diff --git a/Lib/tkinter/messagebox.py b/Lib/tkinter/messagebox.py index 5f0343b660c..f6848142a9a 100644 --- a/Lib/tkinter/messagebox.py +++ b/Lib/tkinter/messagebox.py @@ -1,3 +1,5 @@ +"""Interface to the standard Tk message boxes.""" + # tk common message boxes # # this module provides an interface to the native message boxes @@ -99,24 +101,24 @@ def showerror(title=None, message=None, **options): def askquestion(title=None, message=None, **options): - "Ask a question" + "Ask a question; return the symbolic name of the selected button" return _show(title, message, QUESTION, YESNO, **options) def askokcancel(title=None, message=None, **options): - "Ask if operation should proceed; return true if the answer is ok" + "Ask if operation should proceed; return True if the answer is ok" s = _show(title, message, QUESTION, OKCANCEL, **options) return s == OK def askyesno(title=None, message=None, **options): - "Ask a question; return true if the answer is yes" + "Ask a question; return True if the answer is yes" s = _show(title, message, QUESTION, YESNO, **options) return s == YES def askyesnocancel(title=None, message=None, **options): - "Ask a question; return true if the answer is yes, None if cancelled." + "Ask a question; return True if the answer is yes, None if cancelled" s = _show(title, message, QUESTION, YESNOCANCEL, **options) # s might be a Tcl index object, so convert it to a string s = str(s) @@ -126,7 +128,7 @@ def askyesnocancel(title=None, message=None, **options): def askretrycancel(title=None, message=None, **options): - "Ask if operation should be retried; return true if the answer is yes" + "Ask if operation should be retried; return True if the answer is retry" s = _show(title, message, WARNING, RETRYCANCEL, **options) return s == RETRY diff --git a/Lib/tkinter/simpledialog.py b/Lib/tkinter/simpledialog.py index 6e5b025a9f9..5c49d6c00f3 100644 --- a/Lib/tkinter/simpledialog.py +++ b/Lib/tkinter/simpledialog.py @@ -8,7 +8,7 @@ # fredrik@pythonware.com # http://www.pythonware.com # -"""This modules handles dialog boxes. +"""This module handles dialog boxes. It contains the following public symbols: @@ -23,9 +23,12 @@ askstring -- get a string from the user """ -from tkinter import * +from tkinter import Button, Entry, Frame, Label, Message, Tk, Toplevel from tkinter import _get_temp_root, _destroy_temp_root from tkinter import messagebox +from tkinter.constants import ACTIVE, BOTH, END, LEFT, RIDGE, W, E + +__all__ = ["SimpleDialog", "Dialog", "askinteger", "askfloat", "askstring"] class SimpleDialog: @@ -259,8 +262,11 @@ def _place_window(w, parent=None): def _setup_dialog(w): if w._windowingsystem == "aqua": - w.tk.call("::tk::unsupported::MacWindowStyle", "style", - w, "moveableModal", "") + if w.info_patchlevel() >= (9, 1): + w.wm_attributes(stylemask='titled') + else: + w.tk.call('::tk::unsupported::MacWindowStyle', 'style', + w, 'moveableModal', '') elif w._windowingsystem == "x11": w.wm_attributes(type="dialog") diff --git a/Lib/tkinter/ttk.py b/Lib/tkinter/ttk.py index ef2b91dfbb6..4ca8d12dc28 100644 --- a/Lib/tkinter/ttk.py +++ b/Lib/tkinter/ttk.py @@ -12,8 +12,6 @@ of the widgets appearance lies at Themes. """ -__version__ = "0.3.1" - __author__ = "Guilherme Polo " __all__ = ["Button", "Checkbutton", "Combobox", "Entry", "Frame", "Label", @@ -581,8 +579,8 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, compound, cursor, image, state, style, takefocus, - text, textvariable, underline, width + class, compound, cursor, image, justify (Tk 9.0+), padding, + state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS @@ -604,8 +602,8 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, compound, cursor, image, state, style, takefocus, - text, textvariable, underline, width + class, compound, cursor, image, justify (Tk 9.0+), padding, + state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS @@ -638,8 +636,10 @@ def __init__(self, master=None, widget=None, **kw): WIDGET-SPECIFIC OPTIONS - exportselection, invalidcommand, justify, show, state, - textvariable, validate, validatecommand, width + background, exportselection, font, foreground, invalidcommand, + justify, locale (Tk 9.1+), placeholder (Tk 9.0+), + placeholderforeground (Tk 9.0+), show, state, textvariable, + validate, validatecommand, width VALIDATION MODES @@ -648,7 +648,7 @@ def __init__(self, master=None, widget=None, **kw): Widget.__init__(self, master, widget or "ttk::entry", kw) - def bbox(self, index): + def bbox(self, index): # overrides Misc.bbox """Return a tuple of (x, y, width, height) which describes the bounding box of the character given by index.""" return self._getints(self.tk.call(self._w, "bbox", index)) @@ -676,12 +676,14 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, cursor, style, takefocus + class, cursor, style, takefocus, xscrollcommand WIDGET-SPECIFIC OPTIONS - exportselection, justify, height, postcommand, state, - textvariable, values, width + background, exportselection, font, foreground, height, + invalidcommand, justify, locale (Tk 9.1+), placeholder (Tk 9.0+), + placeholderforeground (Tk 9.0+), postcommand, show, state, + textvariable, validate, validatecommand, values, width """ Entry.__init__(self, master, "ttk::combobox", **kw) @@ -730,13 +732,13 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, compound, cursor, image, style, takefocus, text, - textvariable, underline, width + class, compound, cursor, image, state, style, takefocus, + text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS - anchor, background, font, foreground, justify, padding, - relief, text, wraplength + anchor, background, borderwidth, font, foreground, justify, + padding, relief, text, textangle (Tk 9.1+), wraplength """ Widget.__init__(self, master, "ttk::label", kw) @@ -754,8 +756,9 @@ def __init__(self, master=None, **kw): class, cursor, style, takefocus WIDGET-SPECIFIC OPTIONS - labelanchor, text, underline, padding, labelwidget, width, - height + + borderwidth, height, labelanchor, labelwidget, padding, + relief, text, underline, width """ Widget.__init__(self, master, "ttk::labelframe", kw) @@ -771,8 +774,8 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, compound, cursor, image, state, style, takefocus, - text, textvariable, underline, width + class, compound, cursor, image, justify (Tk 9.0+), padding, + state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS @@ -826,7 +829,7 @@ def add(self, child, **kw): self.tk.call(self._w, "add", child, *(_format_optdict(kw))) - def forget(self, tab_id): + def forget(self, tab_id): # overrides Pack.forget """Removes the tab specified by tab_id, unmaps and unmanages the associated window.""" self.tk.call(self._w, "forget", tab_id) @@ -985,7 +988,9 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, cursor, style, takefocus + anchor (Tk 9.0+), class, cursor, font (Tk 9.0+), + foreground (Tk 9.0+), justify (Tk 9.0+), style, takefocus, + text (Tk 9.0+), wraplength (Tk 9.0+) WIDGET-SPECIFIC OPTIONS @@ -1024,8 +1029,8 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, compound, cursor, image, state, style, takefocus, - text, textvariable, underline, width + class, compound, cursor, image, justify (Tk 9.0+), padding, + state, style, takefocus, text, textvariable, underline, width WIDGET-SPECIFIC OPTIONS @@ -1052,7 +1057,7 @@ def __init__(self, master=None, **kw): STANDARD OPTIONS - class, cursor, style, takefocus + class, cursor, state, style, takefocus WIDGET-SPECIFIC OPTIONS @@ -1149,7 +1154,10 @@ def __init__(self, master=None, **kw): WIDGET-SPECIFIC OPTIONS - to, from_, increment, values, wrap, format, command + background, command, exportselection, font, foreground, + format, from_, increment, justify, locale (Tk 9.1+), + placeholder (Tk 9.0+), placeholderforeground (Tk 9.0+), show, + state, textvariable, to, values, width, wrap """ Entry.__init__(self, master, "ttk::spinbox", **kw) @@ -1176,7 +1184,10 @@ def __init__(self, master=None, **kw): WIDGET-SPECIFIC OPTIONS - columns, displaycolumns, height, padding, selectmode, show + columns, displaycolumns, headingheight (Tk 9.1+), height, + padding, rowheight (Tk 9.1+), selectmode, selecttype (Tk 9.0+), + show, striped (Tk 9.0+), titlecolumns (Tk 9.0+), + titleitems (Tk 9.0+) ITEM OPTIONS @@ -1189,7 +1200,7 @@ def __init__(self, master=None, **kw): Widget.__init__(self, master, "ttk::treeview", kw) - def bbox(self, item, column=None): + def bbox(self, item, column=None): # overrides Misc.bbox """Returns the bounding box (relative to the treeview widget's window) of the specified item in the form x y width height. @@ -1248,7 +1259,7 @@ def exists(self, item): return self.tk.getboolean(self.tk.call(self._w, "exists", item)) - def focus(self, item=None): + def focus(self, item=None): # overrides Misc.focus """If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or '' if there is none.""" return self.tk.call(self._w, "focus", item) @@ -1472,8 +1483,8 @@ def tag_configure(self, tagname, option=None, **kw): def tag_has(self, tagname, item=None): - """If item is specified, returns 1 or 0 depending on whether the - specified item has the given tagname. Otherwise, returns a list of + """If item is specified, returns True if the specified item has the + given tagname, False otherwise. Otherwise, returns a list of all items which have the specified tag. * Availability: Tk 8.6""" @@ -1648,3 +1659,12 @@ def destroy(self): except AttributeError: pass super().destroy() + + +def __getattr__(name): + if name == "__version__": + from warnings import _deprecated + + _deprecated("__version__", remove=(3, 20)) + return "0.3.1" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/Lib/tokenize.py b/Lib/tokenize.py index 1f31258ce36..3545d92c4f5 100644 --- a/Lib/tokenize.py +++ b/Lib/tokenize.py @@ -35,6 +35,7 @@ from token import * from token import EXACT_TOKEN_TYPES import _tokenize +lazy import _colorize cookie_re = re.compile(br'^[ \t\f]*#.*?coding[:=][ \t]*([-\w.]+)', re.ASCII) blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.ASCII) @@ -403,7 +404,7 @@ def find_cookie(line): return None encoding = _get_normal_name(match.group(1).decode()) try: - codec = lookup(encoding) + lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter if filename is None: @@ -505,6 +506,56 @@ def generate_tokens(readline): """ return _generate_tokens_from_c_tokenizer(readline, extra_tokens=True) + +def _get_token_colors(syntax, tokenize): + """Map token type numbers to theme colors.""" + return frozendict({ + COMMENT: syntax.comment, + DEDENT: tokenize.whitespace, + ENCODING: tokenize.whitespace, + ENDMARKER: tokenize.whitespace, + ERRORTOKEN: tokenize.error, + FSTRING_START: syntax.string, + FSTRING_MIDDLE: syntax.string, + FSTRING_END: syntax.string, + INDENT: tokenize.whitespace, + NAME: syntax.reset, + NEWLINE: tokenize.whitespace, + NL: tokenize.whitespace, + NUMBER: syntax.number, + OP: syntax.op, + SOFT_KEYWORD: syntax.soft_keyword, + STRING: syntax.string, + TSTRING_START: syntax.string, + TSTRING_MIDDLE: syntax.string, + TSTRING_END: syntax.string, + }) + + +def _format_tokens(tokens, *, color=False, exact=False): + theme = _colorize.get_theme(force_no_color=not color) + s = theme.syntax + t = theme.tokenize + token_colors = _get_token_colors(s, t) + for token in tokens: + token_range = ( + f"{t.position}{token.start[0]}" + f"{t.delimiter},{t.position}{token.start[1]}" + f"{t.delimiter}-" + f"{t.position}{token.end[0]}" + f"{t.delimiter},{t.position}{token.end[1]}" + f"{t.delimiter}:" + ) + token_color = token_colors.get(token.type, s.reset) + token_name = tok_name[token.exact_type if exact else token.type] + visible_range = f"{token.start[0]},{token.start[1]}-{token.end[0]},{token.end[1]}:" + yield ( + f"{token_range}{' ' * (20 - len(visible_range))}" + f"{token_color}{token_name:<15}" + f"{s.reset}{token.string!r:<15}" + ) + + def _main(args=None): import argparse @@ -524,10 +575,10 @@ def error(message, filename=None, location=None): sys.exit(1) # Parse the arguments and options - parser = argparse.ArgumentParser(color=True) + parser = argparse.ArgumentParser() parser.add_argument(dest='filename', nargs='?', metavar='filename.py', - help='the file to tokenize; defaults to stdin') + help='the file to tokenize; defaults to `stdin`') parser.add_argument('-e', '--exact', dest='exact', action='store_true', help='display token names using the exact type') args = parser.parse_args(args) @@ -545,13 +596,8 @@ def error(message, filename=None, location=None): # Output the tokenization - for token in tokens: - token_type = token.type - if args.exact: - token_type = token.exact_type - token_range = "%d,%d-%d,%d:" % (token.start + token.end) - print("%-20s%-15s%-15r" % - (token_range, tok_name[token_type], token.string)) + for line in _format_tokens(tokens, color=True, exact=args.exact): + print(line) except IndentationError as err: line, column = err.args[1][1:3] error(err.args[0], filename, (line, column)) diff --git a/Lib/tomllib/_parser.py b/Lib/tomllib/_parser.py index 84e70495dd0..b8993480800 100644 --- a/Lib/tomllib/_parser.py +++ b/Lib/tomllib/_parser.py @@ -4,8 +4,11 @@ from __future__ import annotations +# Defer loading regular expressions until we actually need them in +# parse_value(). +__lazy_modules__ = ["tomllib._re"] + import sys -from types import MappingProxyType from ._re import ( RE_DATETIME, @@ -16,6 +19,9 @@ match_to_number, ) +if sys.version_info < (3, 15): + from types import MappingProxyType as frozendict + TYPE_CHECKING = False if TYPE_CHECKING: from collections.abc import Iterable @@ -30,35 +36,36 @@ # and RecursionError. MAX_KEY_PARTS: Final = sys.getrecursionlimit() -ASCII_CTRL = frozenset(chr(i) for i in range(32)) | frozenset(chr(127)) +ASCII_CTRL: Final = frozenset(chr(i) for i in range(32)) | frozenset(chr(127)) # Neither of these sets include quotation mark or backslash. They are # currently handled as separate cases in the parser functions. -ILLEGAL_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t") -ILLEGAL_MULTILINE_BASIC_STR_CHARS = ASCII_CTRL - frozenset("\t\n") +ILLEGAL_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t") +ILLEGAL_MULTILINE_BASIC_STR_CHARS: Final = ASCII_CTRL - frozenset("\t\n") -ILLEGAL_LITERAL_STR_CHARS = ILLEGAL_BASIC_STR_CHARS -ILLEGAL_MULTILINE_LITERAL_STR_CHARS = ILLEGAL_MULTILINE_BASIC_STR_CHARS +ILLEGAL_LITERAL_STR_CHARS: Final = ILLEGAL_BASIC_STR_CHARS +ILLEGAL_MULTILINE_LITERAL_STR_CHARS: Final = ILLEGAL_MULTILINE_BASIC_STR_CHARS -ILLEGAL_COMMENT_CHARS = ILLEGAL_BASIC_STR_CHARS +ILLEGAL_COMMENT_CHARS: Final = ILLEGAL_BASIC_STR_CHARS -TOML_WS = frozenset(" \t") -TOML_WS_AND_NEWLINE = TOML_WS | frozenset("\n") -BARE_KEY_CHARS = frozenset( +TOML_WS: Final = frozenset(" \t") +TOML_WS_AND_NEWLINE: Final = TOML_WS | frozenset("\n") +BARE_KEY_CHARS: Final = frozenset( "abcdefghijklmnopqrstuvwxyz" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "0123456789" "-_" ) -KEY_INITIAL_CHARS = BARE_KEY_CHARS | frozenset("\"'") -HEXDIGIT_CHARS = frozenset("abcdef" "ABCDEF" "0123456789") +KEY_INITIAL_CHARS: Final = BARE_KEY_CHARS | frozenset("\"'") +HEXDIGIT_CHARS: Final = frozenset("abcdef" "ABCDEF" "0123456789") -BASIC_STR_ESCAPE_REPLACEMENTS = MappingProxyType( +BASIC_STR_ESCAPE_REPLACEMENTS: Final = frozendict( { "\\b": "\u0008", # backspace "\\t": "\u0009", # tab - "\\n": "\u000A", # linefeed - "\\f": "\u000C", # form feed - "\\r": "\u000D", # carriage return + "\\n": "\u000a", # linefeed + "\\f": "\u000c", # form feed + "\\r": "\u000d", # carriage return + "\\e": "\u001b", # escape '\\"': "\u0022", # quote - "\\\\": "\u005C", # backslash + "\\\\": "\u005c", # backslash } ) @@ -141,7 +148,7 @@ def load(fp: IO[bytes], /, *, parse_float: ParseFloat = float) -> dict[str, Any] return loads(s, parse_float=parse_float) -def loads(s: str, /, *, parse_float: ParseFloat = float) -> dict[str, Any]: # noqa: C901 +def loads(s: str, /, *, parse_float: ParseFloat = float) -> dict[str, Any]: """Parse TOML from a string.""" # The spec allows converting "\r\n" to "\n", even in string @@ -216,10 +223,10 @@ class Flags: """Flags that map to parsed keys/namespaces.""" # Marks an immutable namespace (inline array or inline table). - FROZEN = 0 + FROZEN: Final = 0 # Marks a nest that has been explicitly created and can no longer # be opened using the "[table]" syntax. - EXPLICIT_NEST = 1 + EXPLICIT_NEST: Final = 1 def __init__(self) -> None: self._flags: dict[str, dict[Any, Any]] = {} @@ -265,8 +272,8 @@ def is_(self, key: Key, flag: int) -> bool: cont = inner_cont["nested"] key_stem = key[-1] if key_stem in cont: - cont = cont[key_stem] - return flag in cont["flags"] or flag in cont["recursive_flags"] + inner_cont = cont[key_stem] + return flag in inner_cont["flags"] or flag in inner_cont["recursive_flags"] return False @@ -527,7 +534,7 @@ def parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos nested_dict = NestedDict() flags = Flags() - pos = skip_chars(src, pos, TOML_WS) + pos = skip_comments_and_array_ws(src, pos) if src.startswith("}", pos): return pos + 1, nested_dict.dict while True: @@ -542,16 +549,18 @@ def parse_inline_table(src: str, pos: Pos, parse_float: ParseFloat) -> tuple[Pos if key_stem in nest: raise TOMLDecodeError(f"Duplicate inline table key {key_stem!r}", src, pos) nest[key_stem] = value - pos = skip_chars(src, pos, TOML_WS) + pos = skip_comments_and_array_ws(src, pos) c = src[pos : pos + 1] if c == "}": return pos + 1, nested_dict.dict if c != ",": raise TOMLDecodeError("Unclosed inline table", src, pos) + pos += 1 + pos = skip_comments_and_array_ws(src, pos) + if src.startswith("}", pos): + return pos + 1, nested_dict.dict if isinstance(value, (dict, list)): flags.set(key, Flags.FROZEN, recursive=True) - pos += 1 - pos = skip_chars(src, pos, TOML_WS) def parse_basic_str_escape( @@ -573,6 +582,8 @@ def parse_basic_str_escape( pos += 1 pos = skip_chars(src, pos, TOML_WS_AND_NEWLINE) return pos, "" + if escape_id == "\\x": + return parse_hex_char(src, pos, 2) if escape_id == "\\u": return parse_hex_char(src, pos, 4) if escape_id == "\\U": @@ -672,7 +683,7 @@ def parse_basic_str(src: str, pos: Pos, *, multiline: bool) -> tuple[Pos, str]: pos += 1 -def parse_value( # noqa: C901 +def parse_value( src: str, pos: Pos, parse_float: ParseFloat ) -> tuple[Pos, Any]: try: diff --git a/Lib/tomllib/_re.py b/Lib/tomllib/_re.py index eb8beb19747..fc374ed63d3 100644 --- a/Lib/tomllib/_re.py +++ b/Lib/tomllib/_re.py @@ -10,16 +10,20 @@ TYPE_CHECKING = False if TYPE_CHECKING: - from typing import Any + from typing import Any, Final from ._types import ParseFloat -# E.g. -# - 00:32:00.999999 -# - 00:32:00 -_TIME_RE_STR = r"([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])(?:\.([0-9]{1,6})[0-9]*)?" +_TIME_RE_STR: Final = r""" +([01][0-9]|2[0-3]) # hours +:([0-5][0-9]) # minutes +(?: + :([0-5][0-9]) # optional seconds + (?:\.([0-9]{1,6})[0-9]*)? # optional fractions of a second +)? +""" -RE_NUMBER = re.compile( +RE_NUMBER: Final = re.compile( r""" 0 (?: @@ -38,8 +42,8 @@ """, flags=re.VERBOSE, ) -RE_LOCALTIME = re.compile(_TIME_RE_STR) -RE_DATETIME = re.compile( +RE_LOCALTIME: Final = re.compile(_TIME_RE_STR, flags=re.VERBOSE) +RE_DATETIME: Final = re.compile( rf""" ([0-9]{{4}})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01]) # date, e.g. 1988-10-27 (?: @@ -74,7 +78,8 @@ def match_to_datetime(match: re.Match[str]) -> datetime | date: year, month, day = int(year_str), int(month_str), int(day_str) if hour_str is None: return date(year, month, day) - hour, minute, sec = int(hour_str), int(minute_str), int(sec_str) + hour, minute = int(hour_str), int(minute_str) + sec = int(sec_str) if sec_str else 0 micros = int(micros_str.ljust(6, "0")) if micros_str else 0 if offset_sign_str: tz: tzinfo | None = cached_tz( @@ -103,8 +108,9 @@ def cached_tz(hour_str: str, minute_str: str, sign_str: str) -> timezone: def match_to_localtime(match: re.Match[str]) -> time: hour_str, minute_str, sec_str, micros_str = match.groups() + sec = int(sec_str) if sec_str else 0 micros = int(micros_str.ljust(6, "0")) if micros_str else 0 - return time(int(hour_str), int(minute_str), int(sec_str), micros) + return time(int(hour_str), int(minute_str), sec, micros) def match_to_number(match: re.Match[str], parse_float: ParseFloat) -> Any: diff --git a/Lib/trace.py b/Lib/trace.py index cf8817f4383..43ec201c469 100644 --- a/Lib/trace.py +++ b/Lib/trace.py @@ -604,7 +604,7 @@ def results(self): def main(): import argparse - parser = argparse.ArgumentParser(color=True) + parser = argparse.ArgumentParser() parser.add_argument('--version', action='version', version='trace 2.0') grp = parser.add_argument_group('Main options', @@ -612,27 +612,27 @@ def main(): grp.add_argument('-c', '--count', action='store_true', help='Count the number of times each line is executed and write ' - 'the counts to .cover for each module executed, in ' - 'the module\'s directory. See also --coverdir, --file, ' - '--no-report below.') + 'the counts to `.cover` for each module executed, in ' + 'the module\'s directory. See also `--coverdir`, `--file`, ' + '`--no-report` below.') grp.add_argument('-t', '--trace', action='store_true', - help='Print each line to sys.stdout before it is executed') + help='Print each line to `sys.stdout` before it is executed') grp.add_argument('-l', '--listfuncs', action='store_true', help='Keep track of which functions are executed at least once ' - 'and write the results to sys.stdout after the program exits. ' - 'Cannot be specified alongside --trace or --count.') + 'and write the results to `sys.stdout` after the program exits. ' + 'Cannot be specified alongside `--trace` or `--count`.') grp.add_argument('-T', '--trackcalls', action='store_true', help='Keep track of caller/called pairs and write the results to ' - 'sys.stdout after the program exits.') + '`sys.stdout` after the program exits.') grp = parser.add_argument_group('Modifiers') _grp = grp.add_mutually_exclusive_group() _grp.add_argument('-r', '--report', action='store_true', help='Generate a report from a counts file; does not execute any ' - 'code. --file must specify the results file to read, which ' - 'must have been created in a previous run with --count ' - '--file=FILE') + 'code. `--file` must specify the results file to read, which ' + 'must have been created in a previous run with `--count` ' + '`--file=FILE`') _grp.add_argument('-R', '--no-report', action='store_true', help='Do not generate the coverage report files. ' 'Useful if you want to accumulate over several runs.') @@ -641,14 +641,14 @@ def main(): help='File to accumulate counts over several runs') grp.add_argument('-C', '--coverdir', help='Directory where the report files go. The coverage report ' - 'for . will be written to file ' - '//.cover') + 'for `.` will be written to file ' + '`//.cover`') grp.add_argument('-m', '--missing', action='store_true', help='Annotate executable lines that were not executed with ' '">>>>>> "') grp.add_argument('-s', '--summary', action='store_true', - help='Write a brief summary for each file to sys.stdout. ' - 'Can only be used with --count or --report') + help='Write a brief summary for each file to `sys.stdout`. ' + 'Can only be used with `--count` or `--report`') grp.add_argument('-g', '--timing', action='store_true', help='Prefix each line with the time since the program started. ' 'Only used while tracing') @@ -661,7 +661,7 @@ def main(): 'module names.') grp.add_argument('--ignore-dir', action='append', default=[], help='Ignore files in the given directory ' - '(multiple directories can be joined by os.pathsep).') + '(multiple directories can be joined by `os.pathsep`).') parser.add_argument('--module', action='store_true', default=False, help='Trace a module. ') @@ -721,7 +721,6 @@ def parse_ignore_dir(s): '__package__': mod_spec.parent, '__loader__': mod_spec.loader, '__spec__': mod_spec, - '__cached__': None, } else: sys.argv = [opts.progname, *opts.arguments] @@ -734,7 +733,6 @@ def parse_ignore_dir(s): '__file__': opts.progname, '__name__': '__main__', '__package__': None, - '__cached__': None, } t.runctx(code, globs, globs) except OSError as err: diff --git a/Lib/traceback.py b/Lib/traceback.py index 227ca8efa17..8d24fb4c290 100644 --- a/Lib/traceback.py +++ b/Lib/traceback.py @@ -1,18 +1,29 @@ """Extract, format and print information about Python stack traces.""" import collections.abc +import functools import itertools import linecache +import os +import re import sys import textwrap +import types import warnings import codeop import keyword import tokenize import io -import _colorize +import importlib.util +import pathlib from contextlib import suppress +lazy import _colorize + +try: + from _missing_stdlib_info import _MISSING_STDLIB_MODULE_MESSAGES +except ImportError: + _MISSING_STDLIB_MODULE_MESSAGES = {} __all__ = ['extract_stack', 'extract_tb', 'format_exception', 'format_exception_only', 'format_list', 'format_stack', @@ -21,6 +32,36 @@ 'FrameSummary', 'StackSummary', 'TracebackException', 'walk_stack', 'walk_tb', 'print_list'] + +class _ShutdownTheme: + """Empty stand-in if `_colorize` cannot be imported during late shutdown.""" + def __getattr__(self, _): return self + def __getitem__(self, _): return "" + def __format__(self, _): return "" + def __str__(self): return "" + def __add__(self, other): return other + __radd__ = __add__ + + +_shutdown_theme = _ShutdownTheme() + + +def _safe_get_theme(*, force_color=False, force_no_color=False): + try: + return _colorize.get_theme( + force_color=force_color, force_no_color=force_no_color + ) + except ImportError: + return _shutdown_theme + + +def _safe_can_colorize(*, file=None): + try: + return _colorize.can_colorize(file=file) + except ImportError: + return False + + # # Formatting and printing lists of traceback lines. # @@ -137,9 +178,10 @@ def print_exception(exc, /, value=_sentinel, tb=_sentinel, limit=None, \ BUILTIN_EXCEPTION_LIMIT = object() -def _print_exception_bltin(exc, /): - file = sys.stderr if sys.stderr is not None else sys.__stderr__ - colorize = _colorize.can_colorize(file=file) +def _print_exception_bltin(exc, file=None, /): + if file is None: + file = sys.stderr if sys.stderr is not None else sys.__stderr__ + colorize = _safe_can_colorize(file=file) return print_exception(exc, limit=BUILTIN_EXCEPTION_LIMIT, file=file, colorize=colorize) @@ -187,9 +229,9 @@ def _format_final_exc_line(etype, value, *, insert_final_newline=True, colorize= valuestr = _safe_string(value, 'exception') end_char = "\n" if insert_final_newline else "" if colorize: - theme = _colorize.get_theme(force_color=True).traceback + theme = _safe_get_theme(force_color=True).traceback else: - theme = _colorize.get_theme(force_no_color=True).traceback + theme = _safe_get_theme(force_no_color=True).traceback if value is None or not valuestr: line = f"{theme.type}{etype}{theme.reset}{end_char}" else: @@ -205,9 +247,9 @@ def _safe_string(value, what, func=str): # -- -def print_exc(limit=None, file=None, chain=True): +def print_exc(limit=None, file=None, chain=True, **kwargs): """Shorthand for 'print_exception(sys.exception(), limit=limit, file=file, chain=chain)'.""" - print_exception(sys.exception(), limit=limit, file=file, chain=chain) + print_exception(sys.exception(), limit=limit, file=file, chain=chain, **kwargs) def format_exc(limit=None, chain=True): """Like print_exc() but return a string.""" @@ -286,6 +328,12 @@ class FrameSummary: of code that was running when the frame was captured. - :attr:`locals` Either None if locals were not supplied, or a dict mapping the name to the repr() of the variable. + - :attr:`end_lineno` The last line number of the source code for this frame. + By default, it is set to lineno and indexation starts from 1. + - :attr:`colno` The column number of the source code for this frame. + By default, it is None and indexation starts from 0. + - :attr:`end_colno` The last column number of the source code for this frame. + By default, it is None and indexation starts from 0. """ __slots__ = ('filename', 'lineno', 'end_lineno', 'colno', 'end_colno', @@ -536,9 +584,9 @@ def format_frame_summary(self, frame_summary, **kwargs): if frame_summary.filename.startswith("'): filename = "" if colorize: - theme = _colorize.get_theme(force_color=True).traceback + theme = _safe_get_theme(force_color=True).traceback else: - theme = _colorize.get_theme(force_no_color=True).traceback + theme = _safe_get_theme(force_no_color=True).traceback row.append( ' File {}"{}"{}, line {}{}{}, in {}{}{}\n'.format( theme.filename, @@ -667,12 +715,12 @@ def output_line(lineno): colorized_line_parts = [] colorized_carets_parts = [] - for color, group in itertools.groupby(itertools.zip_longest(line, carets, fillvalue=""), key=lambda x: x[1]): + for color, group in itertools.groupby(_zip_display_width(line, carets), key=lambda x: x[1]): caret_group = list(group) - if color == "^": + if "^" in color: colorized_line_parts.append(theme.error_highlight + "".join(char for char, _ in caret_group) + theme.reset) colorized_carets_parts.append(theme.error_highlight + "".join(caret for _, caret in caret_group) + theme.reset) - elif color == "~": + elif "~" in color: colorized_line_parts.append(theme.error_range + "".join(char for char, _ in caret_group) + theme.reset) colorized_carets_parts.append(theme.error_range + "".join(caret for _, caret in caret_group) + theme.reset) else: @@ -954,7 +1002,54 @@ def setup_positions(expr, force_valid=True): return None -_WIDE_CHAR_SPECIFIERS = "WF" + +def _zip_display_width(line, carets): + carets = iter(carets) + if line.isascii() and '\x1a' not in line: + for char in line: + yield char, next(carets, "") + return + + import unicodedata + for char in unicodedata.iter_graphemes(line): + char = str(char) + char_width = _display_width(char) + yield char, "".join(itertools.islice(carets, char_width)) + + +@functools.cache +def _str_width(c: str) -> int: + # copied from _pyrepl.utils to fix gh-130273 + + if ord(c) < 128: + return 1 + import unicodedata + # gh-139246 for zero-width joiner and combining characters + if unicodedata.combining(c): + return 0 + category = unicodedata.category(c) + if category == "Cf" and c != "\u00ad": + return 0 + w = unicodedata.east_asian_width(c) + if w in ("N", "Na", "H", "A"): + return 1 + return 2 + + +_ANSI_ESCAPE_SEQUENCE = re.compile(r"\x1b\[[ -@]*[A-~]") + + +def _wlen(s: str) -> int: + # copied from _pyrepl.utils to fix gh-130273 + + if len(s) == 1 and s != "\x1a": + return _str_width(s) + length = sum(_str_width(i) for i in s) + # remove lengths of any escape sequences + sequence = _ANSI_ESCAPE_SEQUENCE.findall(s) + ctrl_z_cnt = s.count("\x1a") + return length - sum(len(i) for i in sequence) + ctrl_z_cnt + def _display_width(line, offset=None): """Calculate the amount of width space the given source @@ -962,19 +1057,14 @@ def _display_width(line, offset=None): width output device. Supports wide unicode characters and emojis.""" if offset is None: - offset = len(line) + return _wlen(line) - # Fast track for ASCII-only strings - if line.isascii(): - return offset + return _wlen(line[:offset]) - import unicodedata - - return sum( - 2 if unicodedata.east_asian_width(char) in _WIDE_CHAR_SPECIFIERS else 1 - for char in line[:offset] - ) +def _format_note(note, indent, theme): + for l in note.split("\n"): + yield f"{indent}{theme.note}{l}{theme.reset}\n" class _ExceptionPrintContext: @@ -1098,20 +1188,62 @@ def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None, wrong_name = getattr(exc_value, "name_from", None) suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name) if suggestion: - self._str += f". Did you mean: '{suggestion}'?" - elif exc_type and issubclass(exc_type, (NameError, AttributeError)) and \ + if suggestion.isascii(): + self._str += f". Did you mean: '{suggestion}'?" + else: + self._str += f". Did you mean: '{suggestion}' ({suggestion!a})?" + elif exc_type and issubclass(exc_type, ModuleNotFoundError): + module_name = getattr(exc_value, "name", None) + if module_name in sys.stdlib_module_names: + message = _MISSING_STDLIB_MODULE_MESSAGES.get( + module_name, + f"Standard library module {module_name!r} was not found" + ) + self._str = message + elif sys.flags.no_site: + self._str += (". Site initialization is disabled, did you forget to " + + "add the site-packages directory to sys.path " + + "or to enable your virtual environment?") + elif abi_tag := _find_incompatible_extension_module(module_name): + self._str += ( + ". Although a module with this name was found for a " + f"different Python version ({abi_tag})." + ) + else: + suggestion = _compute_suggestion_error(exc_value, exc_traceback, module_name) + if suggestion: + self._str += f". Did you mean: '{suggestion}'?" + elif exc_type and issubclass(exc_type, AttributeError) and \ + getattr(exc_value, "name", None) is not None: + wrong_name = getattr(exc_value, "name", None) + # Check cross-language/wrong-type hints first (more specific), + # then fall back to Levenshtein distance suggestions. + hint = None + if hasattr(exc_value, 'obj'): + hint = _get_cross_language_hint(exc_value.obj, wrong_name) + if hint: + self._str += f". {hint}" + else: + suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name) + if suggestion: + if suggestion.isascii(): + self._str += f". Did you mean '.{suggestion}' instead of '.{wrong_name}'?" + else: + self._str += f". Did you mean '.{suggestion}' ({suggestion!a}) instead of '.{wrong_name}' ({wrong_name!a})?" + elif exc_type and issubclass(exc_type, NameError) and \ getattr(exc_value, "name", None) is not None: wrong_name = getattr(exc_value, "name", None) suggestion = _compute_suggestion_error(exc_value, exc_traceback, wrong_name) if suggestion: - self._str += f". Did you mean: '{suggestion}'?" - if issubclass(exc_type, NameError): - wrong_name = getattr(exc_value, "name", None) - if wrong_name is not None and wrong_name in sys.stdlib_module_names: - if suggestion: - self._str += f" Or did you forget to import '{wrong_name}'?" - else: - self._str += f". Did you forget to import '{wrong_name}'?" + if suggestion.isascii(): + self._str += f". Did you mean: '{suggestion}'?" + else: + self._str += f". Did you mean: '{suggestion}' ({suggestion!a})?" + if wrong_name is not None and wrong_name in sys.stdlib_module_names: + if suggestion: + self._str += f" Or did you forget to import '{wrong_name}'?" + else: + self._str += f". Did you forget to import '{wrong_name}'?" if lookup_lines: self._load_lines() self.__suppress_context__ = \ @@ -1240,6 +1372,10 @@ def format_exception_only(self, *, show_group=False, _depth=0, **kwargs): well, recursively, with indentation relative to their nesting depth. """ colorize = kwargs.get("colorize", False) + if colorize: + theme = _safe_get_theme(force_color=True).traceback + else: + theme = _safe_get_theme(force_no_color=True).traceback indent = 3 * _depth * ' ' if not self._have_exc_type: @@ -1268,9 +1404,10 @@ def format_exception_only(self, *, show_group=False, _depth=0, **kwargs): ): for note in self.__notes__: note = _safe_string(note, 'note') - yield from [indent + l + '\n' for l in note.split('\n')] + yield from _format_note(note, indent, theme) elif self.__notes__ is not None: - yield indent + "{}\n".format(_safe_string(self.__notes__, '__notes__', func=repr)) + note = _safe_string(self.__notes__, '__notes__', func=repr) + yield from _format_note(note, indent, theme) if self.exceptions and show_group: for ex in self.exceptions: @@ -1315,6 +1452,15 @@ def _find_keyword_typos(self): if len(error_code) > 1024: return + # If the original code doesn't raise SyntaxError, we can't validate + # that a keyword replacement actually fixes anything + try: + codeop.compile_command(error_code, symbol="exec", flags=codeop.PyCF_ONLY_AST) + except SyntaxError: + pass # Good - the original code has a syntax error we might fix + else: + return # Original code compiles or is incomplete - can't validate fixes + error_lines = error_code.splitlines() tokens = tokenize.generate_tokens(io.StringIO(error_code).readline) tokens_left_to_process = 10 @@ -1377,9 +1523,9 @@ def _format_syntax_error(self, stype, **kwargs): # Show exactly where the problem was found. colorize = kwargs.get("colorize", False) if colorize: - theme = _colorize.get_theme(force_color=True).traceback + theme = _safe_get_theme(force_color=True).traceback else: - theme = _colorize.get_theme(force_no_color=True).traceback + theme = _safe_get_theme(force_no_color=True).traceback filename_suffix = '' if self.lineno is not None: yield ' File {}"{}"{}, line {}{}{}\n'.format( @@ -1430,10 +1576,11 @@ def _format_syntax_error(self, stype, **kwargs): # Convert 1-based column offset to 0-based index into stripped text colno = offset - 1 - spaces end_colno = end_offset - 1 - spaces - caretspace = ' ' if colno >= 0: - # non-space whitespace (likes tabs) must be kept for alignment - caretspace = ((c if c.isspace() else ' ') for c in ltext[:colno]) + # Calculate display width to account for wide characters + dp_colno = _display_width(ltext, colno) + highlighted = ltext[colno:end_colno] + caret_count = _display_width(highlighted) if highlighted else (end_colno - colno) start_color = end_color = "" if colorize: # colorize from colno to end_colno @@ -1446,14 +1593,18 @@ def _format_syntax_error(self, stype, **kwargs): end_color = theme.reset yield ' {}\n'.format(ltext) yield ' {}{}{}{}\n'.format( - "".join(caretspace), + ' ' * dp_colno, start_color, - ('^' * (end_colno - colno)), + '^' * caret_count, end_color, ) else: yield ' {}\n'.format(ltext) - msg = self.msg or "" + try: + if not (msg := self.msg): + msg = "" + except TypeError: + pass yield "{}{}{}: {}{}{}{}\n".format( theme.type, stype, @@ -1579,6 +1730,62 @@ def print(self, *, file=None, chain=True, **kwargs): _MOVE_COST = 2 _CASE_COST = 1 +# Cross-language method suggestions for builtin types. +# Consulted as a fallback when Levenshtein-based suggestions find no match. +# +# Inclusion criteria: +# +# 1. Must have evidence of real cross-language confusion (Stack Overflow +# traffic, bug reports in production repos, developer survey data). +# 2. Must not be catchable by Levenshtein distance (too different from +# the correct Python method name). +# +# Each entry maps a wrong method name to a list of (type, suggestion, is_raw) +# tuples. The lookup checks isinstance() so subclasses are also matched. +# If is_raw is False, the suggestion is wrapped in "Did you mean '.X'?". +# If is_raw is True, the suggestion is rendered as-is. +# +# See https://github.com/python/cpython/issues/146406. +_CROSS_LANGUAGE_HINTS = frozendict({ + # list -- JavaScript/Ruby equivalents + "push": ((list, "append", False),), + "concat": ((list, "extend", False),), + # list -- Java/C# equivalents + "addAll": ((list, "extend", False),), + "contains": ((list, "Use 'x in list'.", True),), + # list -- wrong-type suggestion (user expected a set) + "add": ((list, "Did you mean to use a 'set' object?", True), + (frozenset, "Did you mean to use a 'set' object?", True)), + # str -- JavaScript equivalents + "toUpperCase": ((str, "upper", False),), + "toLowerCase": ((str, "lower", False),), + "trimStart": ((str, "lstrip", False),), + "trimEnd": ((str, "rstrip", False),), + # dict -- Java/JavaScript equivalents + "keySet": ((dict, "keys", False),), + "entrySet": ((dict, "items", False),), + "entries": ((dict, "items", False),), + "putAll": ((dict, "update", False),), + "put": ((dict, "Use d[k] = v.", True),), + # tuple -- mutable method on immutable type (user expected a list) + "append": ((tuple, "Did you mean to use a 'list' object?", True),), + "extend": ((tuple, "Did you mean to use a 'list' object?", True),), + "insert": ((tuple, "Did you mean to use a 'list' object?", True),), + "remove": ((tuple, "Did you mean to use a 'list' object?", True), + (frozenset, "Did you mean to use a 'set' object?", True)), + # frozenset -- mutable method on immutable type (user expected a set) + "discard": ((frozenset, "Did you mean to use a 'set' object?", True),), + # frozendict -- mutable method on immutable type (user expected a dict) + "update": ((frozenset, "Did you mean to use a 'set' object?", True), + (frozendict, "Did you mean to use a 'dict' object?", True)), + # float -- bitwise operators belong to int + "__or__": ((float, "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'.", True),), + "__and__": ((float, "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'.", True),), + "__xor__": ((float, "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'.", True),), + "__lshift__": ((float, "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'.", True),), + "__rshift__": ((float, "Did you mean to use an 'int' object? Bitwise operators are not supported by 'float'.", True),), +}) + def _substitution_cost(ch_a, ch_b): if ch_a == ch_b: @@ -1588,19 +1795,100 @@ def _substitution_cost(ch_a, ch_b): return _MOVE_COST +def _is_lazy_import(obj, attr_name): + """Check if attr_name in obj's __dict__ is a lazy import. + + Returns True if obj is a module and the attribute is a LazyImportType, + False otherwise. This avoids triggering module loading when computing + suggestions for AttributeError. + """ + if not isinstance(obj, types.ModuleType): + return False + obj_dict = getattr(obj, '__dict__', None) + if obj_dict is None: + return False + attr_value = obj_dict.get(attr_name) + return isinstance(attr_value, types.LazyImportType) + + +def _check_for_nested_attribute(obj, wrong_name, attrs): + """Check if any attribute of obj has the wrong_name as a nested attribute. + + Returns the first nested attribute suggestion found, or None. + Limited to checking 20 attributes. + Only considers non-descriptor outer attributes to avoid executing + arbitrary code. Checks nested attributes statically so descriptors such + as properties can still be suggested without invoking them. + Skips lazy imports to avoid triggering module loading. + """ + from inspect import getattr_static + + # Check for nested attributes (only one level deep) + attrs_to_check = [x for x in attrs if not x.startswith('_')][:20] # Limit number of attributes to check + for attr_name in attrs_to_check: + with suppress(Exception): + # Check if attr_name is a descriptor - if so, skip it + attr_from_class = getattr_static(type(obj), attr_name, _sentinel) + if attr_from_class is not _sentinel and hasattr(attr_from_class, '__get__'): + continue # Skip descriptors to avoid executing arbitrary code + + # Skip lazy imports to avoid triggering module loading + if _is_lazy_import(obj, attr_name): + continue + + # Safe to get the attribute since it's not a descriptor + attr_obj = getattr(obj, attr_name) + + if _is_lazy_import(attr_obj, wrong_name): + continue + + if getattr_static(attr_obj, wrong_name, _sentinel) is not _sentinel: + return f"{attr_name}.{wrong_name}" + + return None + + +def _get_cross_language_hint(obj, wrong_name): + """Check if wrong_name is a common method name from another language, + a mutable method on an immutable type, or a method tried on None. + + Uses isinstance() so subclasses of builtin types also get hints. + Returns a formatted hint string, or None. + """ + entries = _CROSS_LANGUAGE_HINTS.get(wrong_name) + if entries is None: + return None + for check_type, hint, is_raw in entries: + if isinstance(obj, check_type): + if is_raw: + return hint + return f"Did you mean '.{hint}'?" + return None + + def _get_safe___dir__(obj): # Use obj.__dir__() to avoid a TypeError when calling dir(obj). # See gh-131001 and gh-139933. + # Also filters out lazy imports to avoid triggering module loading. try: d = obj.__dir__() except TypeError: # when obj is a class d = type(obj).__dir__(obj) - return sorted(x for x in d if isinstance(x, str)) + return sorted( + x for x in d if isinstance(x, str) and not _is_lazy_import(obj, x) + ) def _compute_suggestion_error(exc_value, tb, wrong_name): if wrong_name is None or not isinstance(wrong_name, str): return None + not_normalized = False + if not wrong_name.isascii(): + from unicodedata import normalize + normalized_name = normalize('NFKC', wrong_name) + if normalized_name != wrong_name: + not_normalized = True + wrong_name = normalized_name if isinstance(exc_value, AttributeError): obj = exc_value.obj try: @@ -1616,6 +1904,18 @@ def _compute_suggestion_error(exc_value, tb, wrong_name): d = [x for x in d if x[:1] != '_'] except Exception: return None + elif isinstance(exc_value, ModuleNotFoundError): + try: + if parent_name := wrong_name.rpartition('.')[0]: + parent = importlib.util.find_spec(parent_name) + else: + parent = None + d = [] + for finder in sys.meta_path: + if discover := getattr(finder, 'discover', None): + d += [spec.name for spec in discover(parent)] + except Exception: + return None elif isinstance(exc_value, ImportError): try: mod = __import__(exc_value.name) @@ -1626,36 +1926,45 @@ def _compute_suggestion_error(exc_value, tb, wrong_name): return None else: assert isinstance(exc_value, NameError) - # find most recent frame - if tb is None: + try: + # find most recent frame + if tb is None: + return None + while tb.tb_next is not None: + tb = tb.tb_next + frame = tb.tb_frame + d = ( + list(frame.f_locals) + + list(frame.f_globals) + + list(frame.f_builtins) + ) + d = [x for x in d if isinstance(x, str)] + if not_normalized and wrong_name in d: + return wrong_name + + # Check first if we are in a method and the instance + # has the wrong name as attribute + if 'self' in frame.f_locals: + self = frame.f_locals['self'] + try: + has_wrong_name = hasattr(self, wrong_name) + except Exception: + has_wrong_name = False + if has_wrong_name: + return f"self.{wrong_name}" + except Exception: return None - while tb.tb_next is not None: - tb = tb.tb_next - frame = tb.tb_frame - d = ( - list(frame.f_locals) - + list(frame.f_globals) - + list(frame.f_builtins) - ) - d = [x for x in d if isinstance(x, str)] - - # Check first if we are in a method and the instance - # has the wrong name as attribute - if 'self' in frame.f_locals: - self = frame.f_locals['self'] - try: - has_wrong_name = hasattr(self, wrong_name) - except Exception: - has_wrong_name = False - if has_wrong_name: - return f"self.{wrong_name}" + if not_normalized and wrong_name in d: + return wrong_name try: import _suggestions except ImportError: pass else: - return _suggestions._generate_suggestions(d, wrong_name) + suggestion = _suggestions._generate_suggestions(d, wrong_name) + if suggestion: + return suggestion # Compute closest match @@ -1680,6 +1989,14 @@ def _compute_suggestion_error(exc_value, tb, wrong_name): if not suggestion or current_distance < best_distance: suggestion = possible_name best_distance = current_distance + + # If no direct attribute match found, check for nested attributes + if not suggestion and isinstance(exc_value, AttributeError): + with suppress(Exception): + nested_suggestion = _check_for_nested_attribute(exc_value.obj, wrong_name, d) + if nested_suggestion: + return nested_suggestion + return suggestion @@ -1742,3 +2059,32 @@ def _levenshtein_distance(a, b, max_cost): # Everything in this row is too big, so bail early. return max_cost + 1 return result + + +def _find_incompatible_extension_module(module_name): + import importlib.machinery + import importlib.resources.readers + + if not module_name or not importlib.machinery.EXTENSION_SUFFIXES: + return + + # We assume the last extension is untagged (eg. .so, .pyd)! + # tests.test_traceback.MiscTest.test_find_incompatible_extension_modules + # tests that assumption. + untagged_suffix = importlib.machinery.EXTENSION_SUFFIXES[-1] + # On Windows the debug tag is part of the module file stem, instead of the + # extension (eg. foo_d.pyd), so let's remove it and just look for .pyd. + if os.name == 'nt': + untagged_suffix = untagged_suffix.removeprefix('_d') + + parent, _, child = module_name.rpartition('.') + if parent: + traversable = importlib.resources.files(parent) + else: + traversable = importlib.resources.readers.MultiplexedPath( + *map(pathlib.Path, filter(os.path.isdir, sys.path)) + ) + + for entry in traversable.iterdir(): + if entry.name.startswith(child + '.') and entry.name.endswith(untagged_suffix): + return entry.name diff --git a/Lib/turtle.py b/Lib/turtle.py index e5ce2c0a03c..fb3a458624d 100644 --- a/Lib/turtle.py +++ b/Lib/turtle.py @@ -22,80 +22,17 @@ # 3. This notice may not be removed or altered from any source distribution. """ -Turtle graphics is a popular way for introducing programming to -kids. It was part of the original Logo programming language developed -by Wally Feurzig and Seymour Papert in 1966. - -Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it -the command turtle.forward(15), and it moves (on-screen!) 15 pixels in -the direction it is facing, drawing a line as it moves. Give it the -command turtle.right(25), and it rotates in-place 25 degrees clockwise. - -By combining together these and similar commands, intricate shapes and -pictures can easily be drawn. - ------ turtle.py - -This module is an extended reimplementation of turtle.py from the -Python standard distribution up to Python 2.5. (See: https://www.python.org) - -It tries to keep the merits of turtle.py and to be (nearly) 100% -compatible with it. This means in the first place to enable the -learning programmer to use all the commands, classes and methods -interactively when using the module from within IDLE run with -the -n switch. - -Roughly it has the following features added: - -- Better animation of the turtle movements, especially of turning the - turtle. So the turtles can more easily be used as a visual feedback - instrument by the (beginning) programmer. - -- Different turtle shapes, image files as turtle shapes, user defined - and user controllable turtle shapes, among them compound - (multicolored) shapes. Turtle shapes can be stretched and tilted, which - makes turtles very versatile geometrical objects. - -- Fine control over turtle movement and screen updates via delay(), - and enhanced tracer() and speed() methods. - -- Aliases for the most commonly used commands, like fd for forward etc., - following the early Logo traditions. This reduces the boring work of - typing long sequences of commands, which often occur in a natural way - when kids try to program fancy pictures on their first encounter with - turtle graphics. - -- Turtles now have an undo()-method with configurable undo-buffer. - -- Some simple commands/methods for creating event driven programs - (mouse-, key-, timer-events). Especially useful for programming games. - -- A scrollable Canvas class. The default scrollable Canvas can be - extended interactively as needed while playing around with the turtle(s). - -- A TurtleScreen class with methods controlling background color or - background image, window and canvas size and other properties of the - TurtleScreen. - -- There is a method, setworldcoordinates(), to install a user defined - coordinate-system for the TurtleScreen. - -- The implementation uses a 2-vector class named Vec2D, derived from tuple. - This class is public, so it can be imported by the application programmer, - which makes certain types of computations very natural and compact. - -- Appearance of the TurtleScreen and the Turtles at startup/import can be - configured by means of a turtle.cfg configuration file. - The default configuration mimics the appearance of the old turtle module. - -- If configured appropriately the module reads in docstrings from a docstring - dictionary in some different language, supplied separately and replaces - the English ones by those read in. There is a utility function - write_docstringdict() to write a dictionary with the original (English) - docstrings to disc, so it can serve as a template for translations. - -Behind the scenes there are some features included with possible -extensions in mind. These will be commented and documented elsewhere. +Imagine a robotic turtle starting at (0, 0) in the x-y plane. +After an `import turtle`, give it the command `turtle.forward(15)`, and it +moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as +it moves. Give it the command `turtle.right(25)`, and it rotates in-place 25 +degrees clockwise. + +Turtle graphics is an implementation of the drawing tools introduced in Logo +in 1967. It was created as an educational tool, and its instant, visible +feedback makes it an effective way for learners to encounter programming +concepts. It is also a convenient way to produce simple graphical output +without bringing in external libraries. """ import tkinter as TK @@ -166,7 +103,7 @@ } def config_dict(filename): - """Convert content of config-file into dictionary.""" + """Convert the content of a config file into a dict.""" with open(filename, "r") as f: cfglines = f.readlines() cfgdict = {} @@ -195,17 +132,17 @@ def config_dict(filename): return cfgdict def readconfig(cfgdict): - """Read config-files, change configuration-dict accordingly. + """Read config files and update the configuration dict accordingly. If there is a turtle.cfg file in the current working directory, - read it from there. If this contains an importconfig-value, - say 'myway', construct filename turtle_mayway.cfg else use - turtle.cfg and read it from the import-directory, where - turtle.py is located. - Update configuration dictionary first according to config-file, - in the import directory, then according to config-file in the - current working directory. - If no config-file is found, the default configuration is used. + read it. If it contains an importconfig value, say 'myway', + use the filename turtle_myway.cfg, otherwise turtle.cfg, and + read that file from the directory where turtle.py is located. + + The configuration dict is updated first from the config file in + the turtle.py directory, then from the one in the current working + directory. If no config file is found, the default configuration + is used. """ default_cfg = "turtle.cfg" cfgdict1 = {} @@ -231,46 +168,54 @@ def readconfig(cfgdict): class Vec2D(tuple): - """A 2 dimensional vector class, used as a helper class - for implementing turtle graphics. - May be useful for turtle graphics programs also. - Derived from tuple, so a vector is a tuple! + """A two-dimensional vector class, used as a helper class for + implementing turtle graphics. May be useful for turtle graphics + programs too. Derived from tuple, so a vector is a tuple! Provides (for a, b vectors, k number): - a+b vector addition - a-b vector subtraction - a*b inner product - k*a and a*k multiplication with scalar - |a| absolute value of a - a.rotate(angle) rotation + a + b: vector addition + a - b: vector subtraction + a * b: inner product + k * a and a * k: multiplication with scalar + abs(a): absolute value of a + a.rotate(angle): rotation """ + def __new__(cls, x, y): return tuple.__new__(cls, (x, y)) + def __add__(self, other): return Vec2D(self[0]+other[0], self[1]+other[1]) + def __mul__(self, other): if isinstance(other, Vec2D): return self[0]*other[0]+self[1]*other[1] return Vec2D(self[0]*other, self[1]*other) + def __rmul__(self, other): if isinstance(other, int) or isinstance(other, float): return Vec2D(self[0]*other, self[1]*other) return NotImplemented + def __sub__(self, other): return Vec2D(self[0]-other[0], self[1]-other[1]) + def __neg__(self): return Vec2D(-self[0], -self[1]) + def __abs__(self): return math.hypot(*self) + def rotate(self, angle): - """rotate self counterclockwise by angle - """ + """Rotate self counterclockwise by angle.""" perp = Vec2D(-self[1], self[0]) angle = math.radians(angle) c, s = math.cos(angle), math.sin(angle) return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s) + def __getnewargs__(self): return (self[0], self[1]) + def __repr__(self): return "(%.2f,%.2f)" % self @@ -284,7 +229,7 @@ def __repr__(self): ## to ScrolledCanvas class def __methodDict(cls, _dict): - """helper function for Scrolled Canvas""" + """Helper function for Scrolled Canvas.""" baseList = list(cls.__bases__) baseList.reverse() for _super in baseList: @@ -294,7 +239,7 @@ def __methodDict(cls, _dict): _dict[key] = value def __methods(cls): - """helper function for Scrolled Canvas""" + """Helper function for Scrolled Canvas.""" _dict = {} __methodDict(cls, _dict) return _dict.keys() @@ -356,7 +301,7 @@ def __init__(self, master, width=500, height=350, self._rootwindow.bind('', self.onResize) def reset(self, canvwidth=None, canvheight=None, bg = None): - """Adjust canvas and scrollbars according to given canvas size.""" + """Adjust canvas size, background color and scrollbars.""" if canvwidth: self.canvwidth = canvwidth if canvheight: @@ -374,8 +319,7 @@ def reset(self, canvwidth=None, canvheight=None, bg = None): def adjustScrolls(self): - """ Adjust scrollbars according to window- and canvas-size. - """ + """Adjust scrollbars according to window and canvas size.""" cwidth = self._canvas.winfo_width() cheight = self._canvas.winfo_height() self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth) @@ -453,7 +397,7 @@ def win_height(self): Canvas = TK.Canvas -class TurtleScreenBase(object): +class TurtleScreenBase: """Provide the basic graphics functionality. Interface between Tkinter and turtle.py. @@ -462,14 +406,13 @@ class TurtleScreenBase(object): """ def _blankimage(self): - """return a blank image object - """ + """Return a blank image object.""" img = TK.PhotoImage(width=1, height=1, master=self.cv) img.blank() return img def _image(self, filename): - """return an image object containing the + """Return an image object containing the imagedata from an image file named filename. """ return TK.PhotoImage(file=filename, master=self.cv) @@ -486,22 +429,24 @@ def __init__(self, cv): self.canvwidth = w self.canvheight = h self.xscale = self.yscale = 1.0 + self._updating = False def _createpoly(self): - """Create an invisible polygon item on canvas self.cv) - """ + """Create an invisible polygon item on canvas self.cv.""" return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="") def _drawpoly(self, polyitem, coordlist, fill=None, outline=None, width=None, top=False): - """Configure polygonitem polyitem according to provided - arguments: - coordlist is sequence of coordinates - fill is filling color - outline is outline color - top is a boolean value, which specifies if polyitem - will be put on top of the canvas' displaylist so it - will not be covered by other items. + """Configure polygon item polyitem according to the given arguments. + + Arguments: + coordlist -- a sequence of coordinates + fill -- the fill color + outline -- the outline color + width -- the outline width + top -- a boolean value, which specifies if polyitem will be + put on top of the canvas' display list so it will not + be covered by other items """ cl = [] for x, y in coordlist: @@ -518,20 +463,21 @@ def _drawpoly(self, polyitem, coordlist, fill=None, self.cv.tag_raise(polyitem) def _createline(self): - """Create an invisible line item on canvas self.cv) - """ + """Create an invisible line item on canvas self.cv.""" return self.cv.create_line(0, 0, 0, 0, fill="", width=2, capstyle = TK.ROUND) def _drawline(self, lineitem, coordlist=None, fill=None, width=None, top=False): - """Configure lineitem according to provided arguments: - coordlist is sequence of coordinates - fill is drawing color - width is width of drawn line. - top is a boolean value, which specifies if polyitem - will be put on top of the canvas' displaylist so it - will not be covered by other items. + """Configure line item lineitem according to the given arguments. + + Arguments: + coordlist -- a sequence of coordinates + fill -- the drawing color + width -- the width of the drawn line + top -- a boolean value, which specifies if lineitem will be + put on top of the canvas' display list so it will not + be covered by other items """ if coordlist is not None: cl = [] @@ -548,14 +494,23 @@ def _drawline(self, lineitem, coordlist=None, def _delete(self, item): """Delete graphics item from canvas. - If item is"all" delete all graphics items. + + If item is "all", delete all graphics items. """ self.cv.delete(item) def _update(self): - """Redraw graphics items on canvas - """ - self.cv.update() + """Redraw graphics items on canvas.""" + if self._updating: + # Reentrant call (e.g. a drag handler moving the turtle, + # gh-50966): flush drawing without reprocessing input. + self.cv.update_idletasks() + return + self._updating = True + try: + self.cv.update() + finally: + self._updating = False def _delay(self, delay): """Delay subsequent canvas actions for delay ms.""" @@ -565,7 +520,7 @@ def _iscolorstring(self, color): """Check if the string color is a legal Tkinter color string. """ try: - rgb = self.cv.winfo_rgb(color) + self.cv.winfo_rgb(color) ok = True except TK.TclError: ok = False @@ -581,10 +536,11 @@ def _bgcolor(self, color=None): return self.cv.cget("bg") def _write(self, pos, txt, align, font, pencolor): - """Write txt at pos in canvas with specified font - and color. - Return text item and x-coord of right bottom corner - of text's bounding box.""" + """Write txt at pos on the canvas with specified font and color. + + Return text item and x-coord of right bottom corner of text's + bounding box. + """ x, y = pos x = x * self.xscale y = y * self.yscale @@ -737,13 +693,13 @@ def _type(self, item): return self.cv.type(item) def _pointlist(self, item): - """returns list of coordinate-pairs of points of item - Example (for insiders): - >>> from turtle import * - >>> getscreen()._pointlist(getturtle().turtle._item) - [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982), - (9.9999999999999982, 0.0)] - >>> """ + """Return list of coordinate pairs of points of item. + + For example: + >>> getscreen()._pointlist(getturtle().turtle._item) + [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982), + (9.9999999999999982, 0.0)] + """ cl = self.cv.coords(item) pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)] return pl @@ -764,8 +720,9 @@ def _rescale(self, xscalefactor, yscalefactor): self.cv.coords(item, *newcoordlist) def _resize(self, canvwidth=None, canvheight=None, bg=None): - """Resize the canvas the turtles are drawing on. Does - not alter the drawing window. + """Resize the canvas the turtles are drawing on. + + Does not alter the drawing window. """ # needs amendment if not isinstance(self.cv, ScrolledCanvas): @@ -779,8 +736,7 @@ def _resize(self, canvwidth=None, canvheight=None, bg=None): self.cv.reset(canvwidth, canvheight, bg) def _window_size(self): - """ Return the width and height of the turtle window. - """ + """Return the width and height of the turtle window.""" width = self.cv.winfo_width() if width <= 1: # the window isn't managed by a geometry manager width = self.cv['width'] @@ -790,52 +746,51 @@ def _window_size(self): return width, height def mainloop(self): - """Starts event loop - calling Tkinter's mainloop function. - - No argument. - - Must be last statement in a turtle graphics program. - Must NOT be used if a script is run from within IDLE in -n mode - (No subprocess) - for interactive use of turtle graphics. - - Example (for a TurtleScreen instance named screen): - >>> screen.mainloop() + """Start the event loop by calling Tkinter's mainloop function. + Must be the last statement in a turtle graphics program. Must not + be used if a script is run from within IDLE in -n mode (no + subprocess). """ self.cv.tk.mainloop() def textinput(self, title, prompt): """Pop up a dialog window for input of a string. - Arguments: title is the title of the dialog window, - prompt is a text mostly describing what information to input. - - Return the string input + title is the title of the dialog window and prompt is a text + describing what information to input. Return the string entered. If the dialog is canceled, return None. - Example (for a TurtleScreen instance named screen): - >>> screen.textinput("NIM", "Name of first player:") + Arguments: + title -- a string + prompt -- a string + Example (for a TurtleScreen instance named screen): + >>> screen.textinput("NIM", "Name of first player:") """ return simpledialog.askstring(title, prompt, parent=self.cv) def numinput(self, title, prompt, default=None, minval=None, maxval=None): """Pop up a dialog window for input of a number. - Arguments: title is the title of the dialog window, - prompt is a text mostly describing what numerical information to input. - default: default value - minval: minimum value for input - maxval: maximum value for input + title is the title of the dialog window and prompt is a text + describing what numerical information to input. default is the + default value, minval and maxval are the minimum and maximum + values for input. If these are given, the number entered must be + between minval and maxval. If not, a hint is issued and the dialog + remains open for correction. Return the number entered. + If the dialog is canceled, return None. - The number input must be in the range minval .. maxval if these are - given. If not, a hint is issued and the dialog remains open for - correction. Return the number input. - If the dialog is canceled, return None. + Arguments: + title -- a string + prompt -- a string + default -- a number or None + minval -- a number or None + maxval -- a number or None Example (for a TurtleScreen instance named screen): - >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000) - + >>> screen.numinput("Poker", "Your stakes:", 1000, + ... minval=10, maxval=10000) """ return simpledialog.askfloat(title, prompt, initialvalue=default, minvalue=minval, maxvalue=maxval, @@ -847,7 +802,7 @@ def numinput(self, title, prompt, default=None, minval=None, maxval=None): ############################################################################## -class Terminator (Exception): +class Terminator(Exception): """Will be raised in TurtleScreen.update, if _RUNNING becomes False. This stops execution of a turtle graphics script. @@ -857,16 +812,17 @@ class Terminator (Exception): class TurtleGraphicsError(Exception): - """Some TurtleGraphics Error - """ + """Raised for invalid arguments or operations.""" -class Shape(object): +class Shape: """Data structure modeling shapes. - attribute _type is one of "polygon", "image", "compound" - attribute _data is - depending on _type a poygon-tuple, - an image or a list constructed using the addcomponent method. + type_ is one of the strings "polygon", "image" or "compound". What + data must be depends on type_: for "polygon" a tuple of pairs of + coordinates, for "image" an image (only used internally), and for + "compound" None, as a compound shape is built up using the + addcomponent method. """ def __init__(self, type_, data=None): self._type = type_ @@ -882,20 +838,22 @@ def __init__(self, type_, data=None): self._data = data def addcomponent(self, poly, fill, outline=None): - """Add component to a shape of type compound. + """Add a component to a shape of type "compound". - Arguments: poly is a polygon, i. e. a tuple of number pairs. - fill is the fillcolor of the component, - outline is the outline color of the component. + poly is a polygon, a tuple of pairs of numbers. fill is the color + the polygon is filled with and outline is the color of its + outline. If outline is not given, fill is used for it as well. - call (for a Shapeobject namend s): - -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue") + Arguments: + poly -- a tuple of pairs of numbers + fill -- a color + outline -- a color or None Example: - >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) - >>> s = Shape("compound") - >>> s.addcomponent(poly, "red", "blue") - >>> # .. add more components and then use register_shape() + >>> poly = ((0,0), (10,-5), (0,10), (-10,-5)) + >>> s = Shape("compound") + >>> s.addcomponent(poly, "red", "blue") + >>> # ... add more components and then use register_shape() """ if self._type != "compound": raise TurtleGraphicsError("Cannot add component to %s Shape" @@ -905,13 +863,15 @@ def addcomponent(self, poly, fill, outline=None): self._data.append([poly, fill, outline]) -class Tbuffer(object): - """Ring buffer used as undobuffer for RawTurtle objects.""" +class Tbuffer: + """Ring buffer used as undo buffer for RawTurtle objects.""" + def __init__(self, bufsize=10): self.bufsize = bufsize self.buffer = [[None]] * bufsize self.ptr = -1 self.cumulate = False + def reset(self, bufsize=None): if bufsize is None: for i in range(self.bufsize): @@ -920,6 +880,7 @@ def reset(self, bufsize=None): self.bufsize = bufsize self.buffer = [[None]] * bufsize self.ptr = -1 + def push(self, item): if self.bufsize > 0: if not self.cumulate: @@ -927,6 +888,7 @@ def push(self, item): self.buffer[self.ptr] = item else: self.buffer[self.ptr].append(item) + def pop(self): if self.bufsize > 0: item = self.buffer[self.ptr] @@ -936,8 +898,19 @@ def pop(self): self.buffer[self.ptr] = [None] self.ptr = (self.ptr - 1) % self.bufsize return (item) + + def remove(self, item): + if item not in self.buffer: + return + index = self.buffer.index(item) + self.buffer.remove(item) + if index <= self.ptr: + self.ptr = (self.ptr - 1) % self.bufsize + self.buffer.insert((self.ptr+1) % self.bufsize, [None]) + def nr_of_items(self): return self.bufsize - self.buffer.count([None]) + def __repr__(self): return str(self.buffer) + " " + str(self.ptr) @@ -946,9 +919,9 @@ def __repr__(self): class TurtleScreen(TurtleScreenBase): """Provides screen oriented methods like bgcolor etc. - Only relies upon the methods of TurtleScreenBase and NOT - upon components of the underlying graphics toolkit - - which is Tkinter in this case. + Only relies upon the methods of TurtleScreenBase and not upon + components of the underlying graphics toolkit, which is Tkinter + in this case. """ _RUNNING = True @@ -989,21 +962,25 @@ def __init__(self, cv, mode=_CFG["mode"], # the Turtle window will show behind the Terminal window when you # start the demo from the command line. rootwindow = cv.winfo_toplevel() - rootwindow.call('wm', 'attributes', '.', '-topmost', '1') - rootwindow.call('wm', 'attributes', '.', '-topmost', '0') + rootwindow.wm_attributes(topmost=True) + rootwindow.wm_attributes(topmost=False) + + # A new screen means that turtle graphics is running again. + TurtleScreen._RUNNING = True def clear(self): """Delete all drawings and all turtles from the TurtleScreen. - No argument. + Aliases: clear | clearscreen - Reset empty TurtleScreen to its initial state: white background, - no backgroundimage, no eventbindings and tracing on. + Reset the now empty TurtleScreen to its initial state: white + background, no background image, no event bindings and tracing on. + As a function, this method is only available under the name + clearscreen. The function clear is derived from the Turtle method + clear. Example (for a TurtleScreen instance named screen): - >>> screen.clear() - - Note: this method is not available as function. + >>> screen.clearscreen() """ self._delayvalue = _CFG["delay"] self._colormode = _CFG["colormode"] @@ -1023,26 +1000,29 @@ def clear(self): Turtle._pen = None def mode(self, mode=None): - """Set turtle-mode ('standard', 'logo' or 'world') and perform reset. + """Set the turtle mode and perform a reset. - Optional argument: - mode -- one of the strings 'standard', 'logo' or 'world' + mode is one of the strings "standard", "logo" or "world". If mode + is not given, return the current mode. - Mode 'standard' is compatible with turtle.py. - Mode 'logo' is compatible with most Logo-Turtle-Graphics. - Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in - this mode angles appear distorted if x/y unit-ratio doesn't equal 1. - If mode is not given, return the current mode. + Mode "standard" is compatible with the old turtle module. Mode + "logo" is compatible with most Logo turtle graphics. Mode "world" + uses user-defined world coordinates, see setworldcoordinates(). In + this mode, angles appear distorted if the x and y units are not of + equal length. Mode Initial turtle heading positive angles ------------|-------------------------|------------------- - 'standard' to the right (east) counterclockwise - 'logo' upward (north) clockwise + "standard" to the right (east) counterclockwise + "logo" upward (north) clockwise + + Argument: + mode -- a string or None - Examples: - >>> mode('logo') # resets turtle heading to north - >>> mode() - 'logo' + Example (for a TurtleScreen instance named screen): + >>> screen.mode("logo") # resets turtle heading to north + >>> screen.mode() + 'logo' """ if mode is None: return self._mode @@ -1057,26 +1037,29 @@ def mode(self, mode=None): self.reset() def setworldcoordinates(self, llx, lly, urx, ury): - """Set up a user defined coordinate-system. - - Arguments: - llx -- a number, x-coordinate of lower left corner of canvas - lly -- a number, y-coordinate of lower left corner of canvas - urx -- a number, x-coordinate of upper right corner of canvas - ury -- a number, y-coordinate of upper right corner of canvas + """Set up a user-defined coordinate system. - Set up user coodinat-system and switch to mode 'world' if necessary. - This performs a screen.reset. If mode 'world' is already active, - all drawings are redrawn according to the new coordinates. + llx and lly are the x and y coordinates of the lower left corner of + the canvas. urx and ury are the x and y coordinates of the upper + right corner. Switch to mode "world" if necessary, which performs a + reset. If mode "world" is already active, all drawings are redrawn + according to the new coordinates. In user-defined coordinate + systems, angles may appear distorted, see mode(). - But ATTENTION: in user-defined coordinatesystems angles may appear - distorted. (see Screen.mode()) + Arguments: + llx -- a number + lly -- a number + urx -- a number + ury -- a number Example (for a TurtleScreen instance named screen): - >>> screen.setworldcoordinates(-10,-0.5,50,1.5) - >>> for _ in range(36): - ... left(10) - ... forward(0.5) + >>> screen.reset() + >>> screen.setworldcoordinates(-50,-7.5,50,7.5) + >>> for _ in range(72): + ... left(10) + ... + >>> for _ in range(8): + ... left(45); fd(2) # a regular octagon """ if self.mode() != "world": self.mode("world") @@ -1096,31 +1079,35 @@ def setworldcoordinates(self, llx, lly, urx, ury): self.update() def register_shape(self, name, shape=None): - """Adds a turtle shape to TurtleScreen's shapelist. + """Add a turtle shape to the TurtleScreen's shape list. + + Aliases: register_shape | addshape + + It can be called in four different ways: + + (1) name is the name of an image file (PNG, GIF, PGM, and PPM) and + shape is None. Install the corresponding image shape. + (2) name is an arbitrary string and shape is the name of an image + file (PNG, GIF, PGM, and PPM). Install the corresponding image + shape. + (3) name is an arbitrary string and shape is a tuple of pairs of + coordinates. Install the corresponding polygon shape. + (4) name is an arbitrary string and shape is a (compound) Shape + object. Install the corresponding compound shape. + + Image shapes do not rotate when turning the turtle, so they do not + display the heading of the turtle. To use a registered shape, call + shape() with its name. Arguments: - (1) name is the name of an image file (PNG, GIF, PGM, and PPM) and shape is None. - Installs the corresponding image shape. - !! Image-shapes DO NOT rotate when turning the turtle, - !! so they do not display the heading of the turtle! - (2) name is an arbitrary string and shape is the name of an image file (PNG, GIF, PGM, and PPM). - Installs the corresponding image shape. - !! Image-shapes DO NOT rotate when turning the turtle, - !! so they do not display the heading of the turtle! - (3) name is an arbitrary string and shape is a tuple - of pairs of coordinates. Installs the corresponding - polygon shape - (4) name is an arbitrary string and shape is a - (compound) Shape object. Installs the corresponding - compound shape. - To use a shape, you have to issue the command shape(shapename). - - call: register_shape("turtle.gif") - --or: register_shape("tri", ((0,0), (10,10), (-10,10))) + name -- a string + shape -- a string, a tuple of pairs of numbers, a Shape object + or None Example (for a TurtleScreen instance named screen): - >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3))) - + >>> screen.register_shape("turtle.gif") + >>> screen.register_shape("turtle", "turtle.gif") + >>> screen.register_shape("triangle", ((5,-3), (0,5), (-5,-3))) """ if shape is None: shape = Shape("image", self._image(name)) @@ -1132,14 +1119,12 @@ def register_shape(self, name, shape=None): self._shapes[name] = shape def _colorstr(self, color): - """Return color string corresponding to args. + """Return the color string corresponding to color. - Argument may be a string or a tuple of three - numbers corresponding to actual colormode, - i.e. in the range 0<=n<=colormode. + color may be a string or a tuple of three numbers, each between 0 and + the current colormode. - If the argument doesn't represent a color, - an error is raised. + If color doesn't represent a color, an error is raised. """ if len(color) == 1: color = color[0] @@ -1172,16 +1157,24 @@ def _color(self, cstr): def colormode(self, cmode=None): """Return the colormode or set it to 1.0 or 255. - Optional argument: - cmode -- one of the values 1.0 or 255 + After setting it, the r, g and b values of color triples have to + be between 0 and cmode. - r, g, b values of colortriples have to be in range 0..cmode. + Argument: + cmode -- a number or None Example (for a TurtleScreen instance named screen): - >>> screen.colormode() - 1.0 - >>> screen.colormode(255) - >>> pencolor(240,160,80) + >>> screen.colormode(1) + >>> turtle.pencolor(240, 160, 80) + Traceback (most recent call last): + ... + TurtleGraphicsError: bad color sequence: (240, 160, 80) + >>> screen.colormode() + 1.0 + >>> screen.colormode(255) + >>> screen.colormode() + 255 + >>> turtle.pencolor(240,160,80) """ if cmode is None: return self._colormode @@ -1191,12 +1184,13 @@ def colormode(self, cmode=None): self._colormode = int(cmode) def reset(self): - """Reset all Turtles on the Screen to their initial state. + """Reset all turtles on the screen to their initial state. - No argument. + Aliases: reset | resetscreen - Example (for a TurtleScreen instance named screen): - >>> screen.reset() + As a function, this method is only available under the name + resetscreen. The function reset is derived from the Turtle method + reset(). """ for turtle in self._turtles: turtle._setmode(self._mode) @@ -1206,40 +1200,40 @@ def turtles(self): """Return the list of turtles on the screen. Example (for a TurtleScreen instance named screen): - >>> screen.turtles() - [] + >>> for turtle in screen.turtles(): + ... turtle.color("red") """ return self._turtles def bgcolor(self, *args): - """Set or return backgroundcolor of the TurtleScreen. + """Return or set the background color of the TurtleScreen. Four input formats are allowed: - bgcolor() - Return the current background color as color specification + Return the current background color as a color specification string or as a tuple (see example). May be used as input - to another color/pencolor/fillcolor/bgcolor call. + to another color(), pencolor(), fillcolor() or bgcolor() call. - bgcolor(colorstring) Set the background color to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c". - bgcolor((r, g, b)) Set the background color to the RGB color represented by - the tuple of r, g, and b. Each of r, g, and b must be in - the range 0..colormode, where colormode is either 1.0 or 255 + the tuple of r, g, and b. Each of r, g, and b must be + between 0 and colormode, where colormode is either 1.0 or 255 (see colormode()). - bgcolor(r, g, b) Set the background color to the RGB color represented by - r, g, and b. Each of r, g, and b must be in the range - 0..colormode. + r, g, and b. Each of r, g, and b must be between 0 and + colormode. Example (for a TurtleScreen instance named screen): - >>> screen.bgcolor("orange") - >>> screen.bgcolor() - 'orange' - >>> colormode(255) - >>> screen.bgcolor('#800080') - >>> screen.bgcolor() - (128.0, 0.0, 128.0) + >>> screen.bgcolor("orange") + >>> screen.bgcolor() + 'orange' + >>> screen.colormode(255) + >>> screen.bgcolor("#800080") + >>> screen.bgcolor() + (128.0, 0.0, 128.0) """ if args: color = self._colorstr(args) @@ -1251,23 +1245,26 @@ def bgcolor(self, *args): return color def tracer(self, n=None, delay=None): - """Turns turtle animation on/off and set delay for update drawings. + """Turn turtle animation on or off and set the drawing delay. - Optional arguments: - n -- nonnegative integer - delay -- nonnegative integer + If n is given, only every n-th regular screen update is performed, + which can be used to speed up the drawing of complex graphics. If + n is 0, animation is turned off and the screen is only updated by + calling update(). If delay is given, it sets the drawing delay, see + delay(). When called without arguments, return the current value + of n. - If n is given, only each n-th regular screen update is really performed. - (Can be used to accelerate the drawing of complex graphics.) - Second arguments sets delay value (see RawTurtle.delay()) + Arguments: + n -- a nonnegative integer or None + delay -- a nonnegative integer or None Example (for a TurtleScreen instance named screen): - >>> screen.tracer(8, 25) - >>> dist = 2 - >>> for i in range(200): - ... fd(dist) - ... rt(90) - ... dist += 2 + >>> screen.tracer(8, 25) + >>> dist = 2 + >>> for i in range(200): + ... fd(dist) + ... rt(90) + ... dist += 2 """ if n is None: return self._tracing @@ -1279,15 +1276,21 @@ def tracer(self, n=None, delay=None): self.update() def delay(self, delay=None): - """ Return or set the drawing delay in milliseconds. + """Return or set the drawing delay in milliseconds. - Optional argument: - delay -- positive integer + This is approximately the time interval between two consecutive + canvas updates. The longer the drawing delay, the slower the + animation. + + Argument: + delay -- a nonnegative integer or None Example (for a TurtleScreen instance named screen): - >>> screen.delay(15) - >>> screen.delay() - 15 + >>> screen.delay() + 10 + >>> screen.delay(5) + >>> screen.delay() + 5 """ if delay is None: return self._delayvalue @@ -1295,16 +1298,17 @@ def delay(self, delay=None): @contextmanager def no_animation(self): - """Temporarily turn off auto-updating the screen. + """Temporarily turn off turtle animation. - This is useful for drawing complex shapes where even the fastest setting - is too slow. Once this context manager is exited, the drawing will - be displayed. + The code inside the with block is not animated. Once the block is + exited, the drawing appears. This is useful for drawing complex + shapes where even the fastest speed setting is too slow. - Example (for a TurtleScreen instance named screen - and a Turtle instance named turtle): - >>> with screen.no_animation(): - ... turtle.circle(50) + Example (for a TurtleScreen instance named screen): + >>> with screen.no_animation(): + ... for dist in range(2, 400, 2): + ... fd(dist) + ... rt(90) """ tracer = self.tracer() try: @@ -1314,7 +1318,7 @@ def no_animation(self): self.tracer(tracer) def _incrementudc(self): - """Increment update counter.""" + """Increment the update counter.""" if not TurtleScreen._RUNNING: TurtleScreen._RUNNING = True raise Terminator @@ -1323,8 +1327,7 @@ def _incrementudc(self): self._updatecounter %= self._tracing def update(self): - """Perform a TurtleScreen update. - """ + """Perform a TurtleScreen update.""" tracing = self._tracing self._tracing = True for t in self.turtles(): @@ -1334,60 +1337,65 @@ def update(self): self._update() def window_width(self): - """ Return the width of the turtle window. + """Return the width of the turtle window. Example (for a TurtleScreen instance named screen): - >>> screen.window_width() - 640 + >>> screen.window_width() + 640 """ return self._window_size()[0] def window_height(self): - """ Return the height of the turtle window. + """Return the height of the turtle window. Example (for a TurtleScreen instance named screen): - >>> screen.window_height() - 480 + >>> screen.window_height() + 480 """ return self._window_size()[1] def getcanvas(self): """Return the Canvas of this TurtleScreen. - No argument. - Example (for a Screen instance named screen): - >>> cv = screen.getcanvas() - >>> cv - + >>> cv = screen.getcanvas() + >>> cv + """ return self.cv def getshapes(self): """Return a list of names of all currently available turtle shapes. - No argument. - Example (for a TurtleScreen instance named screen): - >>> screen.getshapes() - ['arrow', 'blank', 'circle', ... , 'turtle'] + >>> screen.getshapes() + ['arrow', 'blank', 'circle', ..., 'turtle'] """ return sorted(self._shapes.keys()) def onclick(self, fun, btn=1, add=None): - """Bind fun to mouse-click event on canvas. + """Bind fun to mouse-click events on this screen. - Arguments: - fun -- a function with two arguments, the coordinates of the - clicked point on the canvas. - btn -- the number of the mouse-button, defaults to 1 + Aliases: onclick | onscreenclick - Example (for a TurtleScreen instance named screen) + fun is called with the coordinates of the clicked point on the + canvas. If fun is None, existing bindings are removed. btn is the + number of the mouse button and defaults to 1, the left mouse + button. If add is True, a new binding is added, otherwise it + replaces a former binding. As a function, this method is only + available under the name onscreenclick. The function onclick is + derived from the Turtle method onclick. - >>> screen.onclick(goto) - >>> # Subsequently clicking into the TurtleScreen will - >>> # make the turtle move to the clicked point. - >>> screen.onclick(None) + Arguments: + fun -- a function with two arguments or None + btn -- an integer + add -- a boolean or None + + Example (for a TurtleScreen instance named screen): + >>> screen.onscreenclick(turtle.goto) + >>> # Subsequently clicking into the TurtleScreen will + >>> # make the turtle move to the clicked point. + >>> screen.onscreenclick(None) # remove event binding again """ self._onscreenclick(fun, btn, add) @@ -1568,14 +1576,16 @@ def save(self, filename, *, overwrite=False): addshape = register_shape onkeyrelease = onkey -class TNavigator(object): - """Navigation part of the RawTurtle. +class TNavigator: + """The navigation part of RawTurtle. + Implements methods for turtle movement. """ START_ORIENTATION = { "standard": Vec2D(1.0, 0.0), "world" : Vec2D(1.0, 0.0), - "logo" : Vec2D(0.0, 1.0) } + "logo" : Vec2D(0.0, 1.0), + } DEFAULT_MODE = "standard" DEFAULT_ANGLEOFFSET = 0 DEFAULT_ANGLEORIENT = 1 @@ -1591,16 +1601,15 @@ def __init__(self, mode=DEFAULT_MODE): TNavigator.reset(self) def reset(self): - """reset turtle to its initial values + """Reset the turtle to its initial values. - Will be overwritten by parent class + Will be overwritten by the child class. """ self._position = Vec2D(0.0, 0.0) self._orient = TNavigator.START_ORIENTATION[self._mode] def _setmode(self, mode=None): - """Set turtle-mode to 'standard', 'world' or 'logo'. - """ + """Set the turtle's mode to 'standard', 'world' or 'logo'.""" if mode is None: return self._mode if mode not in ["standard", "logo", "world"]: @@ -1614,7 +1623,7 @@ def _setmode(self, mode=None): self._angleOrient = -1 def _setDegreesPerAU(self, fullcircle): - """Helper function for degrees() and radians()""" + """Helper function for degrees() and radians().""" self._fullcircle = fullcircle self._degreesPerAU = 360/fullcircle if self._mode == "standard": @@ -1623,60 +1632,80 @@ def _setDegreesPerAU(self, fullcircle): self._angleOffset = fullcircle/4. def degrees(self, fullcircle=360.0): - """ Set angle measurement units to degrees. + """Set the angle measurement units to degrees. - Optional argument: - fullcircle - a number + The number of degrees in a full circle is set to fullcircle, which + defaults to 360. - Set angle measurement units, i. e. set number - of 'degrees' for a full circle. Default value is - 360 degrees. + Argument: + fullcircle -- a number Example (for a Turtle instance named turtle): - >>> turtle.left(90) - >>> turtle.heading() - 90 - - Change angle measurement unit to grad (also known as gon, - grade, or gradian and equals 1/100-th of the right angle.) - >>> turtle.degrees(400.0) - >>> turtle.heading() - 100 - + >>> turtle.home() + >>> turtle.left(90) + >>> turtle.heading() + 90.0 + + >>> # Change angle measurement unit to grad (also known as gon, + >>> # grade, or gradian and equals 1/100-th of the right angle.) + >>> turtle.degrees(400.0) + >>> turtle.heading() + 100.0 + >>> turtle.degrees(360) + >>> turtle.heading() + 90.0 """ self._setDegreesPerAU(fullcircle) def radians(self): - """ Set the angle measurement units to radians. + """Set the angle measurement units to radians. - No arguments. + Equivalent to degrees(2 * math.pi). Example (for a Turtle instance named turtle): - >>> turtle.heading() - 90 - >>> turtle.radians() - >>> turtle.heading() - 1.5707963267948966 + >>> turtle.home() + >>> turtle.left(90) + >>> turtle.heading() + 90.0 + >>> turtle.radians() + >>> turtle.heading() + 1.5707963267948966 """ self._setDegreesPerAU(math.tau) def _go(self, distance): - """move turtle forward by specified distance""" + """Move the turtle forward by the specified distance.""" ende = self._position + self._orient * distance self._goto(ende) def _rotate(self, angle): - """Turn turtle counterclockwise by specified angle if angle > 0.""" + """Turn the turtle counterclockwise by specified angle, if the angle > 0.""" angle *= self._degreesPerAU self._orient = self._orient.rotate(angle) def _goto(self, end): - """move turtle to position end.""" + """Move the turtle to the end position.""" self._position = end + @contextmanager + def _undo_sequence(self): + """Record the enclosed actions as a single undo step.""" + undobuffer = self.undobuffer + if not undobuffer or undobuffer.cumulate: + yield + return + undobuffer.push(["seq"]) + undobuffer.cumulate = True + try: + yield + finally: + undobuffer.cumulate = False + def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None: - """To be overwritten by child class RawTurtle. - Includes no TPen references.""" + """To be overwritten by the child class RawTurtle. + + Includes no TPen references. + """ new_x = x if x is not None else self._position[0] new_y = y if y is not None else self._position[1] self._position = Vec2D(new_x, new_y) @@ -1686,21 +1715,20 @@ def forward(self, distance): Aliases: forward | fd - Argument: - distance -- a number (integer or float) + The turtle moves in the direction it is headed. - Move the turtle forward by the specified distance, in the direction - the turtle is headed. + Argument: + distance -- a number Example (for a Turtle instance named turtle): - >>> turtle.position() - (0.00,0.00) - >>> turtle.forward(25) - >>> turtle.position() - (25.00,0.00) - >>> turtle.forward(-75) - >>> turtle.position() - (-50.00,0.00) + >>> turtle.position() + (0.00,0.00) + >>> turtle.forward(25) + >>> turtle.position() + (25.00,0.00) + >>> turtle.forward(-75) + >>> turtle.position() + (-50.00,0.00) """ self._go(distance) @@ -1709,134 +1737,125 @@ def back(self, distance): Aliases: back | backward | bk - Argument: - distance -- a number + The turtle moves opposite to the direction it is headed. + The turtle's heading does not change. - Move the turtle backward by distance, opposite to the direction the - turtle is headed. Do not change the turtle's heading. + Argument: + distance -- a number Example (for a Turtle instance named turtle): - >>> turtle.position() - (0.00,0.00) - >>> turtle.backward(30) - >>> turtle.position() - (-30.00,0.00) + >>> turtle.position() + (0.00,0.00) + >>> turtle.backward(30) + >>> turtle.position() + (-30.00,0.00) """ self._go(-distance) def right(self, angle): - """Turn turtle right by angle units. + """Turn the turtle right by the specified angle. Aliases: right | rt - Argument: - angle -- a number (integer or float) + The angle is measured in degrees by default; the unit can be + changed with degrees() or radians(). How the heading is measured + depends on the turtle mode, see mode(). - Turn turtle right by angle units. (Units are by default degrees, - but can be set via the degrees() and radians() functions.) - Angle orientation depends on mode. (See this.) + Argument: + angle -- a number Example (for a Turtle instance named turtle): - >>> turtle.heading() - 22.0 - >>> turtle.right(45) - >>> turtle.heading() - 337.0 + >>> turtle.heading() + 22.0 + >>> turtle.right(45) + >>> turtle.heading() + 337.0 """ self._rotate(-angle) def left(self, angle): - """Turn turtle left by angle units. + """Turn the turtle left by the specified angle. Aliases: left | lt - Argument: - angle -- a number (integer or float) + The angle is measured in degrees by default; the unit can be + changed with degrees() or radians(). How the heading is measured + depends on the turtle mode, see mode(). - Turn turtle left by angle units. (Units are by default degrees, - but can be set via the degrees() and radians() functions.) - Angle orientation depends on mode. (See this.) + Argument: + angle -- a number Example (for a Turtle instance named turtle): - >>> turtle.heading() - 22.0 - >>> turtle.left(45) - >>> turtle.heading() - 67.0 + >>> turtle.heading() + 22.0 + >>> turtle.left(45) + >>> turtle.heading() + 67.0 """ self._rotate(angle) def pos(self): - """Return the turtle's current location (x,y), as a Vec2D-vector. + """Return the turtle's current location (x,y) as a Vec2D vector. Aliases: pos | position - No arguments. - Example (for a Turtle instance named turtle): - >>> turtle.pos() - (0.00, 240.00) + >>> turtle.pos() + (0.00,240.00) """ return self._position def xcor(self): - """ Return the turtle's x coordinate. - - No arguments. + """Return the turtle's x coordinate. Example (for a Turtle instance named turtle): - >>> reset() - >>> turtle.left(60) - >>> turtle.forward(100) - >>> print(turtle.xcor()) - 50.0 + >>> turtle.home() + >>> turtle.left(50) + >>> turtle.forward(100) + >>> print(round(turtle.xcor(), 5)) + 64.27876 """ return self._position[0] def ycor(self): - """ Return the turtle's y coordinate - --- - No arguments. + """Return the turtle's y coordinate Example (for a Turtle instance named turtle): - >>> reset() - >>> turtle.left(60) - >>> turtle.forward(100) - >>> print(turtle.ycor()) - 86.6025403784 + >>> reset() + >>> turtle.left(60) + >>> turtle.forward(100) + >>> print(round(turtle.ycor(), 5)) + 86.60254 """ return self._position[1] def goto(self, x, y=None): - """Move turtle to an absolute position. - - Aliases: setpos | setposition | goto: + """Move the turtle to an absolute position. - Arguments: - x -- a number or a pair/vector of numbers - y -- a number None + Aliases: goto | setpos | setposition - call: goto(x, y) # two coordinates - --or: goto((x, y)) # a pair (tuple) of coordinates - --or: goto(vec) # e.g. as returned by pos() + If y is None, x must be a pair of coordinates or a Vec2D, for + example as returned by pos(). If the pen is down, a line is drawn. + The turtle's heading does not change. - Move turtle to an absolute position. If the pen is down, - a line will be drawn. The turtle's orientation does not change. + Arguments: + x -- a number or a pair/vector of numbers + y -- a number or None Example (for a Turtle instance named turtle): - >>> tp = turtle.pos() - >>> tp - (0.00,0.00) - >>> turtle.setpos(60,30) - >>> turtle.pos() - (60.00,30.00) - >>> turtle.setpos((20,80)) - >>> turtle.pos() - (20.00,80.00) - >>> turtle.setpos(tp) - >>> turtle.pos() - (0.00,0.00) + >>> tp = turtle.pos() + >>> tp + (0.00,0.00) + >>> turtle.goto(60,30) + >>> turtle.pos() + (60.00,30.00) + >>> turtle.goto((20,80)) + >>> turtle.pos() + (20.00,80.00) + >>> turtle.goto(tp) + >>> turtle.pos() + (0.00,0.00) """ if y is None: self._goto(Vec2D(*x)) @@ -1844,76 +1863,79 @@ def goto(self, x, y=None): self._goto(Vec2D(x, y)) def home(self): - """Move turtle to the origin - coordinates (0,0). + """Move the turtle to the origin, coordinates (0,0). - No arguments. - - Move turtle to the origin - coordinates (0,0) and set its - heading to its start-orientation (which depends on mode). + The turtle's heading is set to its start orientation, which + depends on the turtle mode, see mode(). Example (for a Turtle instance named turtle): - >>> turtle.home() + >>> turtle.heading() + 90.0 + >>> turtle.position() + (0.00,-10.00) + >>> turtle.home() + >>> turtle.position() + (0.00,0.00) + >>> turtle.heading() + 0.0 """ self.goto(0, 0) self.setheading(0) def setx(self, x): - """Set the turtle's first coordinate to x + """Set the turtle's x coordinate to x. - Argument: - x -- a number (integer or float) + The y coordinate is unchanged. - Set the turtle's first coordinate to x, leave second coordinate - unchanged. + Argument: + x -- a number Example (for a Turtle instance named turtle): - >>> turtle.position() - (0.00, 240.00) - >>> turtle.setx(10) - >>> turtle.position() - (10.00, 240.00) + >>> turtle.position() + (0.00,240.00) + >>> turtle.setx(10) + >>> turtle.position() + (10.00,240.00) """ self._goto(Vec2D(x, self._position[1])) def sety(self, y): - """Set the turtle's second coordinate to y + """Set the turtle's y coordinate to y. - Argument: - y -- a number (integer or float) + The x coordinate is unchanged. - Set the turtle's first coordinate to x, second coordinate remains - unchanged. + Argument: + y -- a number Example (for a Turtle instance named turtle): - >>> turtle.position() - (0.00, 40.00) - >>> turtle.sety(-10) - >>> turtle.position() - (0.00, -10.00) + >>> turtle.position() + (0.00,40.00) + >>> turtle.sety(-10) + >>> turtle.position() + (0.00,-10.00) """ self._goto(Vec2D(self._position[0], y)) def distance(self, x, y=None): """Return the distance from the turtle to (x,y) in turtle step units. - Arguments: - x -- a number or a pair/vector of numbers or a turtle instance - y -- a number None None + If y is None, x must be a pair of coordinates, a Vec2D, for example + as returned by pos(), or another turtle. - call: distance(x, y) # two coordinates - --or: distance((x, y)) # a pair (tuple) of coordinates - --or: distance(vec) # e.g. as returned by pos() - --or: distance(mypen) # where mypen is another turtle + Arguments: + x -- a number or a pair/vector of numbers or a turtle instance + y -- a number if x is a number, else None Example (for a Turtle instance named turtle): - >>> turtle.pos() - (0.00,0.00) - >>> turtle.distance(30,40) - 50.0 - >>> pen = Turtle() - >>> pen.forward(77) - >>> turtle.distance(pen) - 77.0 + >>> turtle.home() + >>> turtle.distance(30,40) + 50.0 + >>> turtle.distance((30,40)) + 50.0 + >>> joe = Turtle() + >>> joe.forward(77) + >>> turtle.distance(joe) + 77.0 """ if y is not None: pos = Vec2D(x, y) @@ -1926,26 +1948,21 @@ def distance(self, x, y=None): return abs(pos - self._position) def towards(self, x, y=None): - """Return the angle of the line from the turtle's position to (x, y). - - Arguments: - x -- a number or a pair/vector of numbers or a turtle instance - y -- a number None None + """Return the angle of the line from the turtle's position to (x,y). - call: distance(x, y) # two coordinates - --or: distance((x, y)) # a pair (tuple) of coordinates - --or: distance(vec) # e.g. as returned by pos() - --or: distance(mypen) # where mypen is another turtle + If y is None, x must be a pair of coordinates, a Vec2D, for example + as returned by pos(), or another turtle. The angle is measured from + the turtle's start orientation, which depends on the turtle mode, + see mode(). - Return the angle, between the line from turtle-position to position - specified by x, y and the turtle's start orientation. (Depends on - modes - "standard" or "logo") + Arguments: + x -- a number or a pair/vector of numbers or a turtle instance + y -- a number if x is a number, else None Example (for a Turtle instance named turtle): - >>> turtle.pos() - (10.00, 10.00) - >>> turtle.towards(0,0) - 225.0 + >>> turtle.goto(10, 10) + >>> turtle.towards(0,0) + 225.0 """ if y is not None: pos = Vec2D(x, y) @@ -1961,14 +1978,15 @@ def towards(self, x, y=None): return (self._angleOffset + self._angleOrient*result) % self._fullcircle def heading(self): - """ Return the turtle's current heading. + """Return the turtle's current heading. - No arguments. + The value depends on the turtle mode, see mode(). Example (for a Turtle instance named turtle): - >>> turtle.left(67) - >>> turtle.heading() - 67.0 + >>> turtle.home() + >>> turtle.left(67) + >>> turtle.heading() + 67.0 """ x, y = self._orient result = round(math.degrees(math.atan2(y, x)), 10) % 360.0 @@ -1976,72 +1994,63 @@ def heading(self): return (self._angleOffset + self._angleOrient*result) % self._fullcircle def setheading(self, to_angle): - """Set the orientation of the turtle to to_angle. + """Set the turtle's heading to to_angle. - Aliases: setheading | seth + Aliases: setheading | seth - Argument: - to_angle -- a number (integer or float) - - Set the orientation of the turtle to to_angle. Here are some common directions in degrees: - standard - mode: logo-mode: - -------------------|-------------------- - 0 - east 0 - north - 90 - north 90 - east - 180 - west 180 - south - 270 - south 270 - west + standard mode logo mode + -------------------|--------------- + 0 - east 0 - north + 90 - north 90 - east + 180 - west 180 - south + 270 - south 270 - west + + Argument: + to_angle -- a number Example (for a Turtle instance named turtle): - >>> turtle.setheading(90) - >>> turtle.heading() - 90 + >>> turtle.setheading(90) + >>> turtle.heading() + 90.0 """ - angle = (to_angle - self.heading())*self._angleOrient + angle = (to_angle - self.heading()) * self._angleOrient full = self._fullcircle angle = (angle+full/2.)%full - full/2. self._rotate(angle) def circle(self, radius, extent = None, steps = None): - """ Draw a circle with given radius. + """Draw a circle with the given radius. - Arguments: - radius -- a number - extent (optional) -- a number - steps (optional) -- an integer - - Draw a circle with given radius. The center is radius units left - of the turtle; extent - an angle - determines which part of the - circle is drawn. If extent is not given, draw the entire circle. - If extent is not a full circle, one endpoint of the arc is the - current pen position. Draw the arc in counterclockwise direction - if radius is positive, otherwise in clockwise direction. Finally - the direction of the turtle is changed by the amount of extent. + The center is radius units left of the turtle; extent, an angle, + determines which part of the circle is drawn. If extent is not + given, draw the entire circle. If extent is not a full circle, one + endpoint of the arc is the current pen position. Draw the arc in + the counterclockwise direction if radius is positive, otherwise in + the clockwise direction. Finally, the turtle's heading is changed by + extent. As the circle is approximated by an inscribed regular polygon, - steps determines the number of steps to use. If not given, - it will be calculated automatically. Maybe used to draw regular + steps determines the number of steps to use. If not given, it + will be calculated automatically. May be used to draw regular polygons. - call: circle(radius) # full circle - --or: circle(radius, extent) # arc - --or: circle(radius, extent, steps) - --or: circle(radius, steps=6) # 6-sided polygon + Arguments: + radius -- a number + extent -- a number or None + steps -- an integer or None Example (for a Turtle instance named turtle): - >>> turtle.circle(50) - >>> turtle.circle(120, 180) # semicircle + >>> turtle.circle(50) + >>> turtle.circle(120, 180) # draw a semicircle """ - if self.undobuffer: - self.undobuffer.push(["seq"]) - self.undobuffer.cumulate = True speed = self.speed() if extent is None: extent = self._fullcircle if steps is None: frac = abs(extent)/self._fullcircle - steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac) + steps = 1 + int(min(11 + abs(radius) / 6.0, 59.0) * frac) w = 1.0 * extent / steps w2 = 0.5 * w l = 2.0 * radius * math.sin(math.radians(w2)*self._degreesPerAU) @@ -2049,31 +2058,32 @@ def circle(self, radius, extent = None, steps = None): l, w, w2 = -l, -w, -w2 tr = self._tracer() dl = self._delay() - if speed == 0: - self._tracer(0, 0) - else: - self.speed(0) - self._rotate(w2) - for i in range(steps): + with self._undo_sequence(): + if speed == 0: + self._tracer(0, 0) + else: + self.speed(0) + self._rotate(w2) + for i in range(steps): + self.speed(speed) + self._go(l) + self.speed(0) + self._rotate(w) + self._rotate(-w2) + if speed == 0: + self._tracer(tr, dl) self.speed(speed) - self._go(l) - self.speed(0) - self._rotate(w) - self._rotate(-w2) - if speed == 0: - self._tracer(tr, dl) - self.speed(speed) - if self.undobuffer: - self.undobuffer.cumulate = False -## three dummy methods to be implemented by child class: + # Three dummy methods to be implemented by the child class: def speed(self, s=0): - """dummy method - to be overwritten by child class""" + """Dummy method - to be overwritten by the child class.""" def _tracer(self, a=None, b=None): - """dummy method - to be overwritten by child class""" + """Dummy method - to be overwritten by the child class.""" def _delay(self, n=None): - """dummy method - to be overwritten by child class""" + """Dummy method - to be overwritten by the child class.""" + + # Aliases for the commonly used commands: fd = forward bk = back @@ -2086,10 +2096,12 @@ def _delay(self, n=None): seth = setheading -class TPen(object): +class TPen: """Drawing part of the RawTurtle. + Implements drawing properties. """ + def __init__(self, resizemode=_CFG["resizemode"]): self._resizemode = resizemode # or "user" or "noresize" self.undobuffer = None @@ -2110,26 +2122,29 @@ def _reset(self, pencolor=_CFG["pencolor"], self._outlinewidth = 1 def resizemode(self, rmode=None): - """Set resizemode to one of the values: "auto", "user", "noresize". + """Set the resizemode to "auto", "user" or "noresize". - (Optional) Argument: - rmode -- one of the strings "auto", "user", "noresize" + If rmode is not given, return the current resizemode. The + different resizemodes have the following effects: - Different resizemodes have the following effects: - - "auto" adapts the appearance of the turtle - corresponding to the value of pensize. - - "user" adapts the appearance of the turtle according to the - values of stretchfactor and outlinewidth (outline), - which are set by shapesize() - - "noresize" no adaption of the turtle's appearance takes place. - If no argument is given, return current resizemode. - resizemode("user") is called by a call of shapesize with arguments. + - "auto": the turtle is resized according to the value of + pensize(). + - "user": the turtle is resized according to the stretch factors + and outline width, which are set by shapesize(). + - "noresize": the turtle is not resized. + resizemode("user") is called by shapesize() when used with + arguments. - Examples (for a Turtle instance named turtle): - >>> turtle.resizemode("noresize") - >>> turtle.resizemode() - 'noresize' + Argument: + rmode -- a string or None + + Example (for a Turtle instance named turtle): + >>> turtle.resizemode() + 'noresize' + >>> turtle.resizemode("auto") + >>> turtle.resizemode() + 'auto' """ if rmode is None: return self._resizemode @@ -2138,22 +2153,21 @@ def resizemode(self, rmode=None): self.pen(resizemode=rmode) def pensize(self, width=None): - """Set or return the line thickness. + """Return or set the line thickness. - Aliases: pensize | width + Aliases: pensize | width - Argument: - width -- positive number + If width is not given, return the current pensize. If resizemode + is set to "auto" and the turtle shape is a polygon, that polygon is + drawn with the same line thickness. - Set the line thickness to width or return it. If resizemode is set - to "auto" and turtleshape is a polygon, that polygon is drawn with - the same line thickness. If no argument is given, current pensize - is returned. + Argument: + width -- a positive number or None Example (for a Turtle instance named turtle): - >>> turtle.pensize() - 1 - >>> turtle.pensize(10) # from here on lines of width 10 are drawn + >>> turtle.pensize() + 1 + >>> turtle.pensize(10) # from here on lines of width 10 are drawn """ if width is None: return self._pensize @@ -2161,80 +2175,84 @@ def pensize(self, width=None): def penup(self): - """Pull the pen up -- no drawing when moving. + """Lift the pen. Aliases: penup | pu | up - No argument - - Example (for a Turtle instance named turtle): - >>> turtle.penup() + The turtle does not draw when it moves. """ if not self._drawing: return self.pen(pendown=False) def pendown(self): - """Pull the pen down -- drawing when moving. + """Lower the pen. Aliases: pendown | pd | down - No argument. - - Example (for a Turtle instance named turtle): - >>> turtle.pendown() + The turtle draws a line when it moves. """ if self._drawing: return self.pen(pendown=True) def isdown(self): - """Return True if pen is down, False if it's up. - - No argument. + """Return True if the pen is down, False if it's up. Example (for a Turtle instance named turtle): - >>> turtle.penup() - >>> turtle.isdown() - False - >>> turtle.pendown() - >>> turtle.isdown() - True + >>> turtle.penup() + >>> turtle.isdown() + False + >>> turtle.pendown() + >>> turtle.isdown() + True """ return self._drawing def speed(self, speed=None): - """ Return or set the turtle's speed. + """Return or set the turtle's speed. - Optional argument: - speed -- an integer in the range 0..10 or a speedstring (see below) - - Set the turtle's speed to an integer value in the range 0 .. 10. - If no argument is given: return current speed. - - If input is a number greater than 10 or smaller than 0.5, - speed is set to 0. - Speedstrings are mapped to speedvalues in the following way: - 'fastest' : 0 - 'fast' : 10 - 'normal' : 6 - 'slow' : 3 - 'slowest' : 1 - speeds from 1 to 10 enforce increasingly faster animation of - line drawing and turtle turning. - - Attention: - speed = 0 : *no* animation takes place. forward/back makes turtle jump - and likewise left/right make the turtle turn instantly. + If speed is not given, return the current speed. Otherwise set the + turtle's speed to an integer from 0 to 10. If speed is a number + greater than 10 or smaller than 0.5, the speed is set to 0. You + can also use these names instead of numbers: + + "fastest": 0 + "fast": 10 + "normal": 6 + "slow": 3 + "slowest": 1 + + Speeds from 1 to 10 give increasingly faster animation of line + drawing and turtle turning. A speed of 0 means that no animation + takes place: forward() and back() make the turtle jump, and + likewise left() and right() make the turtle turn instantly. + + Argument: + speed -- an integer, a string or None Example (for a Turtle instance named turtle): - >>> turtle.speed(3) - """ - speeds = {'fastest':0, 'fast':10, 'normal':6, 'slow':3, 'slowest':1 } + >>> turtle.speed() + 3 + >>> turtle.speed('normal') + >>> turtle.speed() + 6 + >>> turtle.speed(9) + >>> turtle.speed() + 9 + """ + speed_strings = { + 'fastest': 0, + 'fast': 10, + 'normal': 6, + 'slow': 3, + 'slowest': 1, + } + if speed is None: return self._speed - if speed in speeds: - speed = speeds[speed] + if speed in speed_strings: + speed = speed_strings[speed] elif 0.5 < speed < 10.5: speed = int(round(speed)) else: @@ -2244,32 +2262,30 @@ def speed(self, speed=None): def color(self, *args): """Return or set the pencolor and fillcolor. - Arguments: - Several input formats are allowed. - They use 0 to 3 arguments as follows: + Several input formats are allowed. They use 0 to 3 arguments as follows: - color() Return the current pencolor and the current fillcolor as a pair of color specification strings or tuples as returned by pencolor() and fillcolor(). - color(colorstring), color((r,g,b)), color(r,g,b) - Inputs as in pencolor(), set both, fillcolor and pencolor, - to the given value. + Inputs as in pencolor(). Set both the pencolor and the + fillcolor to the given value. - color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2)) Equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously if the other input format is used. - If turtleshape is a polygon, outline and interior of that polygon - is drawn with the newly set colors. - For more info see: pencolor, fillcolor + If the turtle shape is a polygon, the outline and interior of that + polygon are drawn with the newly set colors. For more information, + see pencolor() and fillcolor(). Example (for a Turtle instance named turtle): - >>> turtle.color('red', 'green') - >>> turtle.color() - ('red', 'green') - >>> colormode(255) - >>> color(('#285078', '#a0c8f0')) - >>> color() - ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0)) + >>> turtle.color("red", "green") + >>> turtle.color() + ('red', 'green') + >>> colormode(255) + >>> turtle.color("#285078", "#a0c8f0") + >>> turtle.color() + ((40.0, 80.0, 120.0), (160.0, 200.0, 240.0)) """ if args: l = len(args) @@ -2286,37 +2302,36 @@ def color(self, *args): return self._color(self._pencolor), self._color(self._fillcolor) def pencolor(self, *args): - """ Return or set the pencolor. + """Return or set the pencolor. - Arguments: Four input formats are allowed: - pencolor() Return the current pencolor as color specification string or as a tuple (see example). May be used as input to another - color/pencolor/fillcolor/bgcolor call. + color(), pencolor(), fillcolor() or bgcolor() call. - pencolor(colorstring) - Set pencolor to colorstring, which is a Tk color + Set the pencolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c". - pencolor((r, g, b)) - Set pencolor to the RGB color represented by the tuple of - r, g, and b. Each of r, g, and b must be in the range - 0..colormode, where colormode is either 1.0 or 255 (see + Set the pencolor to the RGB color represented by the tuple of + r, g, and b. Each of r, g, and b must be between 0 and + colormode, where colormode is either 1.0 or 255 (see colormode()). - pencolor(r, g, b) - Set pencolor to the RGB color represented by r, g, and b. - Each of r, g, and b must be in the range 0..colormode. + Set the pencolor to the RGB color represented by r, g, and b. + Each of r, g, and b must be between 0 and colormode. - If turtleshape is a polygon, the outline of that polygon is drawn - with the newly set pencolor. + If the turtle shape is a polygon, the outline of that polygon is + drawn with the newly set pencolor. Example (for a Turtle instance named turtle): - >>> turtle.pencolor('brown') - >>> turtle.pencolor() - 'brown' - >>> colormode(255) - >>> turtle.pencolor('#32c18f') - >>> turtle.pencolor() - (50.0, 193.0, 143.0) + >>> turtle.pencolor("brown") + >>> turtle.pencolor() + 'brown' + >>> colormode(255) + >>> turtle.pencolor("#32c18f") + >>> turtle.pencolor() + (50.0, 193.0, 143.0) """ if args: color = self._colorstr(args) @@ -2327,37 +2342,36 @@ def pencolor(self, *args): return self._color(self._pencolor) def fillcolor(self, *args): - """ Return or set the fillcolor. + """Return or set the fillcolor. - Arguments: Four input formats are allowed: - fillcolor() Return the current fillcolor as color specification string, possibly in tuple format (see example). May be used as - input to another color/pencolor/fillcolor/bgcolor call. + input to another color(), pencolor(), fillcolor() or bgcolor() call. - fillcolor(colorstring) - Set fillcolor to colorstring, which is a Tk color + Set the fillcolor to colorstring, which is a Tk color specification string, such as "red", "yellow", or "#33cc8c". - fillcolor((r, g, b)) - Set fillcolor to the RGB color represented by the tuple of - r, g, and b. Each of r, g, and b must be in the range - 0..colormode, where colormode is either 1.0 or 255 (see + Set the fillcolor to the RGB color represented by the tuple of + r, g, and b. Each of r, g, and b must be between 0 and + colormode, where colormode is either 1.0 or 255 (see colormode()). - fillcolor(r, g, b) - Set fillcolor to the RGB color represented by r, g, and b. - Each of r, g, and b must be in the range 0..colormode. + Set the fillcolor to the RGB color represented by r, g, and b. + Each of r, g, and b must be between 0 and colormode. - If turtleshape is a polygon, the interior of that polygon is drawn - with the newly set fillcolor. + If the turtle shape is a polygon, the interior of that polygon is + drawn with the newly set fillcolor. Example (for a Turtle instance named turtle): - >>> turtle.fillcolor('violet') - >>> turtle.fillcolor() - 'violet' - >>> colormode(255) - >>> turtle.fillcolor('#ffffff') - >>> turtle.fillcolor() - (255.0, 255.0, 255.0) + >>> turtle.fillcolor("violet") + >>> turtle.fillcolor() + 'violet' + >>> colormode(255) + >>> turtle.fillcolor("#ffffff") + >>> turtle.fillcolor() + (255.0, 255.0, 255.0) """ if args: color = self._colorstr(args) @@ -2368,7 +2382,8 @@ def fillcolor(self, *args): return self._color(self._fillcolor) def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None: - """To be overwritten by child class RawTurtle. + """To be overwritten by the child class RawTurtle. + Includes no TNavigator references. """ pendown = self.isdown() @@ -2377,43 +2392,31 @@ def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None: self.pen(pendown=pendown) def showturtle(self): - """Makes the turtle visible. + """Make the turtle visible. Aliases: showturtle | st - - No argument. - - Example (for a Turtle instance named turtle): - >>> turtle.hideturtle() - >>> turtle.showturtle() """ self.pen(shown=True) def hideturtle(self): - """Makes the turtle invisible. + """Make the turtle invisible. Aliases: hideturtle | ht - No argument. - - It's a good idea to do this while you're in the - middle of a complicated drawing, because hiding - the turtle speeds up the drawing observably. - - Example (for a Turtle instance named turtle): - >>> turtle.hideturtle() + If the pen is down, movement still draws. """ self.pen(shown=False) def isvisible(self): - """Return True if the Turtle is shown, False if it's hidden. - - No argument. + """Return True if the turtle is visible, False if it's hidden. Example (for a Turtle instance named turtle): - >>> turtle.hideturtle() - >>> print(turtle.isvisible()) - False + >>> turtle.hideturtle() + >>> turtle.isvisible() + False + >>> turtle.showturtle() + >>> turtle.isvisible() + True """ return self._shown @@ -2542,16 +2545,18 @@ def pen(self, pen=None, **pendict): -scx*sa, scy*(ca - shf*sa)) self._update() -## three dummy methods to be implemented by child class: + # Three dummy methods to be implemented by the child class: def _newLine(self, usePos = True): - """dummy method - to be overwritten by child class""" + """Dummy method - to be overwritten by the child class.""" def _update(self, count=True, forced=False): - """dummy method - to be overwritten by child class""" + """Dummy method - to be overwritten by the child class.""" def _color(self, args): - """dummy method - to be overwritten by child class""" + """Dummy method - to be overwritten by the child class.""" def _colorstr(self, args): - """dummy method - to be overwritten by child class""" + """Dummy method - to be overwritten by the child class.""" + + # Aliases for the commonly used commands: width = pensize up = penup @@ -2562,9 +2567,8 @@ def _colorstr(self, args): ht = hideturtle -class _TurtleImage(object): - """Helper class: Datatype to store Turtle attributes - """ +class _TurtleImage: + """Helper class holding the canvas items that display a turtle's shape.""" def __init__(self, screen, shapeIndex): self.screen = screen @@ -2594,9 +2598,10 @@ def _setshape(self, shapeIndex): class RawTurtle(TPen, TNavigator): - """Animation part of the RawTurtle. - Puts RawTurtle upon a TurtleScreen and provides tools for - its animation. + """A turtle that draws on the given canvas or TurtleScreen. + + Combines the navigation part (TNavigator) and the drawing part (TPen) + and adds the animation of the turtle on the screen. """ screens = [] @@ -2641,23 +2646,22 @@ def __init__(self, canvas=None, self._update() def reset(self): - """Delete the turtle's drawings and restore its default values. + """Delete the turtle's drawings and re-center the turtle. - No argument. - - Delete the turtle's drawings from the screen, re-center the turtle - and set variables to the default values. + The turtle's settings are restored to their default values. Example (for a Turtle instance named turtle): - >>> turtle.position() - (0.00,-22.00) - >>> turtle.heading() - 100.0 - >>> turtle.reset() - >>> turtle.position() - (0.00,0.00) - >>> turtle.heading() - 0.0 + >>> turtle.goto(0,-22) + >>> turtle.left(100) + >>> turtle.position() + (0.00,-22.00) + >>> turtle.heading() + 100.0 + >>> turtle.reset() + >>> turtle.position() + (0.00,0.00) + >>> turtle.heading() + 0.0 """ TNavigator.reset(self) TPen._reset(self) @@ -2666,18 +2670,17 @@ def reset(self): self._update() def setundobuffer(self, size): - """Set or disable undobuffer. + """Set or disable the undo buffer. - Argument: - size -- an integer or None + If size is an integer, an empty undo buffer of the given size is + installed. size is the maximum number of turtle actions that can + be undone by undo(). If size is None, the undo buffer is disabled. - If size is an integer an empty undobuffer of given size is installed. - Size gives the maximum number of turtle-actions that can be undone - by the undo() function. - If size is None, no undobuffer is present. + Argument: + size -- an integer or None Example (for a Turtle instance named turtle): - >>> turtle.setundobuffer(42) + >>> turtle.setundobuffer(42) """ if size is None or size <= 0: self.undobuffer = None @@ -2685,20 +2688,18 @@ def setundobuffer(self, size): self.undobuffer = Tbuffer(size) def undobufferentries(self): - """Return count of entries in the undobuffer. - - No argument. + """Return the number of entries in the undo buffer. Example (for a Turtle instance named turtle): - >>> while undobufferentries(): - ... undo() + >>> while undobufferentries(): + ... undo() """ if self.undobuffer is None: return 0 return self.undobuffer.nr_of_items() def _clear(self): - """Delete all of pen's drawings""" + """Delete all of the pen's drawings.""" self._fillitem = self._fillpath = None for item in self.items: self.screen._delete(item) @@ -2712,16 +2713,13 @@ def _clear(self): def clear(self): - """Delete the turtle's drawings from the screen. Do not move turtle. - - No arguments. + """Delete the turtle's drawings from the screen. - Delete the turtle's drawings from the screen. Do not move turtle. - State and position of the turtle as well as drawings of other - turtles are not affected. + The state and position of the turtle as well as the drawings of + other turtles are not affected. - Examples (for a Turtle instance named turtle): - >>> turtle.clear() + Example (for a Turtle instance named turtle): + >>> turtle.clear() """ self._clear() self._update() @@ -2735,8 +2733,7 @@ def _update_data(self): self._pencolor, self._pensize) def _update(self): - """Perform a Turtle-data update. - """ + """Perform a Turtle-data update.""" screen = self.screen if screen._tracing == 0: return @@ -2753,24 +2750,7 @@ def _update(self): screen._update() def _tracer(self, flag=None, delay=None): - """Turns turtle animation on/off and set delay for update drawings. - - Optional arguments: - n -- nonnegative integer - delay -- nonnegative integer - - If n is given, only each n-th regular screen update is really performed. - (Can be used to accelerate the drawing of complex graphics.) - Second arguments sets delay value (see RawTurtle.delay()) - - Example (for a Turtle instance named turtle): - >>> turtle.tracer(8, 25) - >>> dist = 2 - >>> for i in range(200): - ... turtle.fd(dist) - ... turtle.rt(90) - ... dist += 2 - """ + """Forward flag and delay to the screen's tracer() method.""" return self.screen.tracer(flag, delay) def _color(self, args): @@ -2780,8 +2760,7 @@ def _colorstr(self, args): return self.screen._colorstr(args) def _cc(self, args): - """Convert colortriples to hexstrings. - """ + """Convert colortriples to hexstrings.""" if isinstance(args, str): return args try: @@ -2795,64 +2774,60 @@ def _cc(self, args): return "#%02x%02x%02x" % (r, g, b) def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None: - """Instantly move turtle to an absolute position. + """Teleport, or instantly move, the turtle to an absolute position. + + Unlike goto(), no line is drawn. If x or y is not given, that + coordinate is kept as it is. The turtle's heading does not change. + + If the turtle is filling a shape, the shape drawn so far is + finished and filled before teleporting, and filling starts again + at the new position. Pass fill_gap=True to keep filling one shape + instead. The teleport then counts as an edge of the shape, as it + would with goto(). Arguments: - x -- a number or None - y -- a number None - fill_gap -- a boolean This argument must be specified by name. - - call: teleport(x, y) # two coordinates - --or: teleport(x) # teleport to x position, keeping y as is - --or: teleport(y=y) # teleport to y position, keeping x as is - --or: teleport(x, y, fill_gap=True) - # teleport but fill the gap in between - - Move turtle to an absolute position. Unlike goto(x, y), a line will not - be drawn. The turtle's orientation does not change. If currently - filling, the polygon(s) teleported from will be filled after leaving, - and filling will begin again after teleporting. This can be disabled - with fill_gap=True, which makes the imaginary line traveled during - teleporting act as a fill barrier like in goto(x, y). + x -- a number or None + y -- a number or None + fill_gap -- a boolean Example (for a Turtle instance named turtle): - >>> tp = turtle.pos() - >>> tp - (0.00,0.00) - >>> turtle.teleport(60) - >>> turtle.pos() - (60.00,0.00) - >>> turtle.teleport(y=10) - >>> turtle.pos() - (60.00,10.00) - >>> turtle.teleport(20, 30) - >>> turtle.pos() - (20.00,30.00) + >>> tp = turtle.pos() + >>> tp + (0.00,0.00) + >>> turtle.teleport(60) + >>> turtle.pos() + (60.00,0.00) + >>> turtle.teleport(y=10) + >>> turtle.pos() + (60.00,10.00) + >>> turtle.teleport(20, 30) + >>> turtle.pos() + (20.00,30.00) """ pendown = self.isdown() was_filling = self.filling() - if pendown: - self.pen(pendown=False) - if was_filling and not fill_gap: - self.end_fill() - new_x = x if x is not None else self._position[0] - new_y = y if y is not None else self._position[1] - self._position = Vec2D(new_x, new_y) - self.pen(pendown=pendown) - if was_filling and not fill_gap: - self.begin_fill() + with self._undo_sequence(): + if pendown: + self.pen(pendown=False) + if was_filling and not fill_gap: + self.end_fill() + new_x = x if x is not None else self._position[0] + new_y = y if y is not None else self._position[1] + if self.undobuffer: + self.undobuffer.push(("teleport", self._position)) + self._position = Vec2D(new_x, new_y) + self.pen(pendown=pendown) + if was_filling and not fill_gap: + self.begin_fill() def clone(self): """Create and return a clone of the turtle. - No argument. - - Create and return a clone of the turtle with same position, heading - and turtle properties. + The clone has the same position, heading and turtle properties. - Example (for a Turtle instance named mick): - mick = Turtle() - joe = mick.clone() + Example: + >>> leonel = Turtle() + >>> marco = leonel.clone() """ screen = self.screen self._newLine(self._drawing) @@ -2883,24 +2858,23 @@ def clone(self): return q def shape(self, name=None): - """Set turtle shape to shape with given name / return current shapename. + """Set the turtle shape to the named shape. - Optional argument: - name -- a string, which is a valid shapename + If name is not given, return the name of the current shape. The + shape must exist in the TurtleScreen's shape dictionary. Initially + there are the following shapes: "arrow", "turtle", "circle", + "square", "triangle" and "classic". To add shapes, see the Screen + method register_shape(). - Set turtle shape to shape with given name or, if name is not given, - return name of current shape. - Shape with name must exist in the TurtleScreen's shape dictionary. - Initially there are the following polygon shapes: - 'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'. - To learn about how to deal with shapes see Screen-method register_shape. + Argument: + name -- a string or None Example (for a Turtle instance named turtle): - >>> turtle.shape() - 'arrow' - >>> turtle.shape("turtle") - >>> turtle.shape() - 'turtle' + >>> turtle.shape() + 'classic' + >>> turtle.shape("turtle") + >>> turtle.shape() + 'turtle' """ if name is None: return self.turtle.shapeIndex @@ -2910,25 +2884,39 @@ def shape(self, name=None): self._update() def shapesize(self, stretch_wid=None, stretch_len=None, outline=None): - """Set/return turtle's stretchfactors/outline. Set resizemode to "user". + """Return or set the turtle's stretch factors and outline width. - Optional arguments: - stretch_wid : positive number - stretch_len : positive number - outline : positive number - - Return or set the pen's attributes x/y-stretchfactors and/or outline. - Set resizemode to "user". - If and only if resizemode is set to "user", the turtle will be displayed - stretched according to its stretchfactors: - stretch_wid is stretchfactor perpendicular to orientation - stretch_len is stretchfactor in direction of turtles orientation. - outline determines the width of the shapes's outline. + Aliases: shapesize | turtlesize - Examples (for a Turtle instance named turtle): - >>> turtle.resizemode("user") - >>> turtle.shapesize(5, 5, 12) - >>> turtle.shapesize(outline=8) + If no arguments are given, return the current values. Otherwise + set resizemode to "user", so that the turtle is displayed + stretched according to its stretch factors: + + - stretch_wid: the stretch factor perpendicular to the turtle's + heading + - stretch_len: the stretch factor in the direction of the + turtle's heading + - outline: the width of the shape's outline + + For example, shapesize(2, 1) makes the turtle twice as wide + without changing its length. If only stretch_wid is given, + stretch_len is set to the same value. + + Arguments: + stretch_wid -- a positive number or None + stretch_len -- a positive number or None + outline -- a positive number or None + + Example (for a Turtle instance named turtle): + >>> turtle.shapesize() + (1.0, 1.0, 1) + >>> turtle.resizemode("user") + >>> turtle.shapesize(5, 5, 12) + >>> turtle.shapesize() + (5, 5, 12) + >>> turtle.shapesize(outline=8) + >>> turtle.shapesize() + (5, 5, 8) """ if stretch_wid is stretch_len is outline is None: stretch_wid, stretch_len = self._stretchfactor @@ -3191,12 +3179,12 @@ def stamp(self): screen._drawpoly(item, poly, fill=self._cc(fc), outline=self._cc(oc), width=self._outlinewidth, top=True) self.stampItems.append(stitem) - self.undobuffer.push(("stamp", stitem)) + if self.undobuffer: + self.undobuffer.push(("stamp", stitem)) return stitem def _clearstamp(self, stampid): - """does the work for clearstamp() and clearstamps() - """ + """Does the work for clearstamp() and clearstamps().""" if stampid in self.stampItems: if isinstance(stampid, tuple): for subitem in stampid: @@ -3206,15 +3194,8 @@ def _clearstamp(self, stampid): self.stampItems.remove(stampid) # Delete stampitem from undobuffer if necessary # if clearstamp is called directly. - item = ("stamp", stampid) - buf = self.undobuffer - if item not in buf.buffer: - return - index = buf.buffer.index(item) - buf.buffer.remove(item) - if index <= buf.ptr: - buf.ptr = (buf.ptr - 1) % buf.bufsize - buf.buffer.insert((buf.ptr+1)%buf.bufsize, [None]) + if self.undobuffer: + self.undobuffer.remove(("stamp", stampid)) def clearstamp(self, stampid): """Delete stamp with given stampid @@ -3313,8 +3294,7 @@ def _goto(self, end): self._update() #count=True) def _undogoto(self, entry): - """Reverse a _goto. Used for undo() - """ + """Reverse a _goto(). Used for undo().""" old, new, go_modes, coodata = entry drawing, pc, ps, filling = go_modes cLI, cL, pl, items = coodata @@ -3378,8 +3358,7 @@ def _undogoto(self, entry): self._update() #count=True) def _rotate(self, angle): - """Turns pen clockwise by angle. - """ + """Turns pen clockwise by angle.""" if self.undobuffer: self.undobuffer.push(("rot", angle, self._degreesPerAU)) angle *= self._degreesPerAU @@ -3396,9 +3375,10 @@ def _rotate(self, angle): self._update() def _newLine(self, usePos=True): - """Closes current line item and starts a new one. - Remark: if current line became too long, animation - performance (via _drawline) slowed down considerably. + """Closes the current line item and starts a new one. + + If the current line becomes too long, animation performance (via _drawline) + can slow down considerably. """ if len(self.currentLine) > 1: self.screen._drawline(self.currentLineItem, self.currentLine, @@ -3412,16 +3392,14 @@ def _newLine(self, usePos=True): self.currentLine = [self._position] def filling(self): - """Return fillstate (True if filling, False else). - - No argument. + """Return True if the turtle is filling, False otherwise. Example (for a Turtle instance named turtle): - >>> turtle.begin_fill() - >>> if turtle.filling(): - ... turtle.pensize(5) - ... else: - ... turtle.pensize(3) + >>> turtle.begin_fill() + >>> if turtle.filling(): + ... turtle.pensize(5) + ... else: + ... turtle.pensize(3) """ return isinstance(self._fillpath, list) @@ -3484,18 +3462,19 @@ def end_fill(self): self._update() def dot(self, size=None, *color): - """Draw a dot with diameter size, using color. + """Draw a circular dot with diameter size, using color. - Optional arguments: - size -- an integer >= 1 (if given) - color -- a colorstring or a numeric color tuple + If size is not given, the larger of pensize + 4 and 2 * pensize is + used. If color is not given, the current pencolor is used. - Draw a circular dot with diameter size, using color. - If size is not given, the maximum of pensize+4 and 2*pensize is used. + Arguments: + size -- a positive integer or None + color -- a colorstring or a numeric color tuple Example (for a Turtle instance named turtle): - >>> turtle.dot() - >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) + >>> turtle.home() + >>> turtle.dot() + >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50) """ if not color: if isinstance(size, (str, tuple)): @@ -3511,20 +3490,16 @@ def dot(self, size=None, *color): color = self._colorstr(color) # If screen were to gain a dot function, see GH #104218. pen = self.pen() - if self.undobuffer: - self.undobuffer.push(["seq"]) - self.undobuffer.cumulate = True - try: - if self.resizemode() == 'auto': - self.ht() - self.pendown() - self.pensize(size) - self.pencolor(color) - self.forward(0) - finally: - self.pen(pen) - if self.undobuffer: - self.undobuffer.cumulate = False + with self._undo_sequence(): + try: + if self.resizemode() == 'auto': + self.ht() + self.pendown() + self.pensize(size) + self.pencolor(color) + self.forward(0) + finally: + self.pen(pen) def _write(self, txt, align, font): """Performs the writing for write() @@ -3556,15 +3531,11 @@ def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")): >>> turtle.write('Home = ', True, align="center") >>> turtle.write((0,0), True) """ - if self.undobuffer: - self.undobuffer.push(["seq"]) - self.undobuffer.cumulate = True - end = self._write(str(arg), align.lower(), font) - if move: - x, y = self.pos() - self.setpos(end, y) - if self.undobuffer: - self.undobuffer.cumulate = False + with self._undo_sequence(): + end = self._write(str(arg), align.lower(), font) + if move: + x, y = self.pos() + self.setpos(end, y) @contextmanager def poly(self): @@ -3590,13 +3561,7 @@ def poly(self): def begin_poly(self): """Start recording the vertices of a polygon. - No argument. - - Start recording the vertices of a polygon. Current turtle position - is first point of polygon. - - Example (for a Turtle instance named turtle): - >>> turtle.begin_poly() + The current turtle position is the first vertex of the polygon. """ self._poly = [self._position] self._creatingPoly = True @@ -3604,59 +3569,56 @@ def begin_poly(self): def end_poly(self): """Stop recording the vertices of a polygon. - No argument. - - Stop recording the vertices of a polygon. Current turtle position is - last point of polygon. This will be connected with the first point. - - Example (for a Turtle instance named turtle): - >>> turtle.end_poly() + The current turtle position is the last vertex of the polygon. + This will be connected with the first vertex. """ self._creatingPoly = False def get_poly(self): - """Return the lastly recorded polygon. - - No argument. + """Return the last recorded polygon. Example (for a Turtle instance named turtle): - >>> p = turtle.get_poly() - >>> turtle.register_shape("myFavouriteShape", p) - """ - ## check if there is any poly? + >>> turtle.home() + >>> turtle.begin_poly() + >>> turtle.fd(100) + >>> turtle.left(20) + >>> turtle.fd(30) + >>> turtle.left(60) + >>> turtle.fd(50) + >>> turtle.end_poly() + >>> p = turtle.get_poly() + >>> register_shape("myFavouriteShape", p) + """ + # Check if there are any poly? if self._poly is not None: return tuple(self._poly) def getscreen(self): - """Return the TurtleScreen object, the turtle is drawing on. - - No argument. + """Return the TurtleScreen object the turtle is drawing on. - Return the TurtleScreen object, the turtle is drawing on. So TurtleScreen-methods can be called for that object. Example (for a Turtle instance named turtle): - >>> ts = turtle.getscreen() - >>> ts - - >>> ts.bgcolor("pink") + >>> ts = turtle.getscreen() + >>> ts + + >>> ts.bgcolor("pink") """ return self.screen def getturtle(self): - """Return the Turtleobject itself. + """Return the Turtle object itself. - No argument. + Aliases: getturtle | getpen - Only reasonable use: as a function to return the 'anonymous turtle': + Call getturtle() to get the turtle used by functions such as + forward() and left(). Example: - >>> pet = getturtle() - >>> pet.fd(50) - >>> pet - - >>> turtles() - [] + >>> pet = getturtle() + >>> pet.fd(50) + >>> pet + """ return self @@ -3668,27 +3630,29 @@ def getturtle(self): ################################################################ def _delay(self, delay=None): - """Set delay value which determines speed of turtle animation. - """ + """Set the delay which determines the speed of turtle animation.""" return self.screen.delay(delay) def onclick(self, fun, btn=1, add=None): - """Bind fun to mouse-click event on this turtle on canvas. + """Bind fun to mouse-click events on this turtle. - Arguments: - fun -- a function with two arguments, to which will be assigned - the coordinates of the clicked point on the canvas. - btn -- number of the mouse-button defaults to 1 (left mouse button). - add -- True or False. If True, new binding will be added, otherwise - it will replace a former binding. + fun is called with the coordinates of the clicked point on the + canvas. If fun is None, existing bindings are removed. btn is the + number of the mouse button and defaults to 1, the left mouse + button. If add is True, a new binding is added, otherwise it + replaces a former binding. - Example for the anonymous turtle, i. e. the procedural way: + Arguments: + fun -- a function with two arguments or None + btn -- an integer + add -- a boolean or None - >>> def turn(x, y): - ... left(360) - ... - >>> onclick(turn) # Now clicking into the turtle will turn it. - >>> onclick(None) # event-binding will be removed + Example for the anonymous turtle, that is, the procedural way: + >>> def turn(x, y): + ... left(180) + ... + >>> onclick(turn) # Now clicking into the turtle will turn it. + >>> onclick(None) # event-binding will be removed """ self.screen._onclick(self.turtle._item, fun, btn, add) self._update() @@ -3740,19 +3704,21 @@ def ondrag(self, fun, btn=1, add=None): def _undo(self, action, data): - """Does the main part of the work for undo() - """ + """Does the main part of the work for undo().""" if self.undobuffer is None: return if action == "rot": angle, degPAU = data self._rotate(-angle*degPAU/self._degreesPerAU) - dummy = self.undobuffer.pop() + self.undobuffer.pop() elif action == "stamp": stitem = data[0] self.clearstamp(stitem) elif action == "go": self._undogoto(data) + elif action == "teleport": + self._position = data[0] + self._update() elif action in ["wri", "dot"]: item = data[0] self.screen._delete(item) @@ -3807,9 +3773,10 @@ def undo(self): ### Screen - Singleton ######################## def Screen(): - """Return the singleton screen object. - If none exists at the moment, create a new one and return it, - else return the existing one.""" + """Return the single screen object. + + If it does not exist yet, create it. Otherwise return the existing one. + """ if Turtle._screen is None: Turtle._screen = _Screen() return Turtle._screen @@ -3878,17 +3845,17 @@ def setup(self, width=_CFG["width"], height=_CFG["height"], self.update() def title(self, titlestring): - """Set title of turtle-window + """Set the title of the turtle window to titlestring. - Argument: - titlestring -- a string, to appear in the titlebar of the - turtle graphics window. + The title is shown in the title bar of the turtle graphics window. + This is a method of the Screen class. It is not available for + TurtleScreen objects. - This is a method of Screen-class. Not available for TurtleScreen- - objects. + Argument: + titlestring -- a string Example (for a Screen instance named screen): - >>> screen.title("Welcome to the turtle-zoo!") + >>> screen.title("Welcome to the turtle zoo!") """ if _Screen._root is not None: _Screen._root.title(titlestring) @@ -3905,11 +3872,7 @@ def _destroy(self): root.destroy() def bye(self): - """Shut the turtlegraphics window. - - Example (for a TurtleScreen instance named screen): - >>> screen.bye() - """ + """Close the turtle graphics window.""" self._destroy() def exitonclick(self): @@ -3999,7 +3962,7 @@ def write_docstringdict(filename="turtle_docstringdict"): f.close() def read_docstrings(lang): - """Read in docstrings from lang-specific docstring dictionary. + """Read in docstrings from a language-specific docstring dictionary. Transfer docstrings, translated to lang, from a dictionary-file to the methods of classes Screen and Turtle and - in revised form - @@ -4064,8 +4027,7 @@ def getmethparlist(ob): return str(func_sig), call_text def _turtle_docrevise(docstr): - """To reduce docstrings from RawTurtle class for functions - """ + """To reduce docstrings from the RawTurtle class for functions.""" import re if docstr is None: return None @@ -4076,8 +4038,7 @@ def _turtle_docrevise(docstr): return newdocstr def _screen_docrevise(docstr): - """To reduce docstrings from TurtleScreen class for functions - """ + """To reduce docstrings from the TurtleScreen class for functions.""" import re if docstr is None: return None diff --git a/Lib/turtledemo/__main__.py b/Lib/turtledemo/__main__.py index 7c2d753f4c3..cffc08f59b9 100644 --- a/Lib/turtledemo/__main__.py +++ b/Lib/turtledemo/__main__.py @@ -333,7 +333,7 @@ def loadfile(self, filename): modname = 'turtledemo.' + filename __import__(modname) self.module = sys.modules[modname] - with open(self.module.__file__, 'r') as f: + with open(self.module.__file__, encoding='utf-8') as f: chars = f.read() self.text.delete("1.0", "end") self.text.insert("1.0", chars) diff --git a/Lib/types.py b/Lib/types.py index 60a4b22c200..6c069591ab2 100644 --- a/Lib/types.py +++ b/Lib/types.py @@ -58,7 +58,10 @@ def _m(self): pass raise TypeError except TypeError as exc: TracebackType = type(exc.__traceback__) - FrameType = type(exc.__traceback__.tb_frame) + + _f = (lambda: sys._getframe())() + FrameType = type(_f) + FrameLocalsProxyType = type(_f.f_locals) GetSetDescriptorType = type(FunctionType.__code__) MemberDescriptorType = type(FunctionType.__globals__) @@ -73,6 +76,9 @@ def _m(self): pass # CapsuleType cannot be accessed from pure Python, # so there is no fallback definition. + # LazyImportType in pure Python cannot be guaranteed + # without overriding the filter, so there is no fallback. + del sys, _f, _g, _C, _c, _ag, _cell_factory # Not for export @@ -251,7 +257,6 @@ def deleter(self, fdel): class _GeneratorWrapper: - # TODO: Implement this in C. def __init__(self, gen): self.__wrapped = gen self.__isgen = gen.__class__ is GeneratorType @@ -278,6 +283,12 @@ def gi_yieldfrom(self): @property def gi_suspended(self): return self.__wrapped.gi_suspended + @property + def gi_state(self): + return self.__wrapped.gi_state + @property + def cr_state(self): + return self.__wrapped.gi_state.replace('GEN_', 'CORO_') cr_code = gi_code cr_frame = gi_frame cr_running = gi_running @@ -310,7 +321,6 @@ def coroutine(func): # Check if 'func' is a generator function. # (0x20 == CO_GENERATOR) if co_flags & 0x20: - # TODO: Implement this in C. co = func.__code__ # 0x100 == CO_ITERABLE_COROUTINE func.__code__ = co.replace(co_flags=co.co_flags | 0x100) diff --git a/Lib/typing.py b/Lib/typing.py index 2b4389b2967..5b764419d8a 100644 --- a/Lib/typing.py +++ b/Lib/typing.py @@ -28,6 +28,7 @@ import sys import types from types import GenericAlias +lazy import annotationlib from _typing import ( _idfunc, @@ -65,7 +66,6 @@ # ABCs (from collections.abc). 'AbstractSet', # collections.abc.Set. - 'ByteString', 'Container', 'ContextManager', 'Hashable', @@ -127,6 +127,7 @@ 'cast', 'clear_overloads', 'dataclass_transform', + 'disjoint_base', 'evaluate_forward_ref', 'final', 'get_args', @@ -140,8 +141,8 @@ 'Never', 'NewType', 'no_type_check', - 'no_type_check_decorator', 'NoDefault', + 'NoExtraItems', 'NoReturn', 'NotRequired', 'overload', @@ -156,21 +157,13 @@ 'Text', 'TYPE_CHECKING', 'TypeAlias', + 'TypeForm', 'TypeGuard', 'TypeIs', 'TypeAliasType', 'Unpack', ] -class _LazyAnnotationLib: - def __getattr__(self, attr): - global _lazy_annotationlib - import annotationlib - _lazy_annotationlib = annotationlib - return getattr(annotationlib, attr) - -_lazy_annotationlib = _LazyAnnotationLib() - def _type_convert(arg, module=None, *, allow_special_forms=False, owner=None): """For converting None to type(None), and strings to ForwardRef.""" @@ -254,19 +247,30 @@ def _type_repr(obj): if isinstance(obj, tuple): # Special case for `repr` of types with `ParamSpec`: return '[' + ', '.join(_type_repr(t) for t in obj) + ']' - return _lazy_annotationlib.type_repr(obj) + return annotationlib.type_repr(obj) -def _collect_type_parameters(args, *, enforce_default_ordering: bool = True): +def _collect_type_parameters( + args, + *, + enforce_default_ordering: bool = True, + validate_all: bool = False, +): """Collect all type parameters in args in order of first appearance (lexicographic order). + Having an explicit `Generic` or `Protocol` base class determines + the exact parameter order. + For example:: >>> P = ParamSpec('P') >>> T = TypeVar('T') >>> _collect_type_parameters((T, Callable[P, T])) (~T, ~P) + >>> _collect_type_parameters((list[T], Generic[P, T])) + (~P, ~T) + """ # required type parameter cannot appear after parameter with default default_encountered = False @@ -298,6 +302,17 @@ def _collect_type_parameters(args, *, enforce_default_ordering: bool = True): ' follows type parameter with a default') parameters.append(t) + elif ( + not validate_all + and isinstance(t, _GenericAlias) + and t.__origin__ in (Generic, Protocol) + ): + # If we see explicit `Generic[...]` or `Protocol[...]` base classes, + # we need to just copy them as-is. + # Unless `validate_all` is passed, in this case it means that + # we are doing a validation of `Generic` subclasses, + # then we collect all unique parameters to be able to inspect them. + parameters = t.__parameters__ else: if _is_unpacked_typevartuple(t): type_var_tuple_encountered = True @@ -408,6 +423,17 @@ def inner(*args, **kwds): return decorator +def _rebuild_generic_alias(alias: GenericAlias, args: tuple[object, ...]) -> GenericAlias: + is_unpacked = alias.__unpacked__ + if _should_unflatten_callable_args(alias, args): + t = alias.__origin__[(args[:-1], args[-1])] + else: + t = alias.__origin__[args] + if is_unpacked: + t = Unpack[t] + return t + + def _deprecation_warning_for_no_type_params_passed(funcname: str) -> None: import warnings @@ -421,16 +447,7 @@ def _deprecation_warning_for_no_type_params_passed(funcname: str) -> None: warnings.warn(depr_message, category=DeprecationWarning, stacklevel=3) -class _Sentinel: - __slots__ = () - def __repr__(self): - return '' - - -_sentinel = _Sentinel() - - -def _eval_type(t, globalns, localns, type_params=_sentinel, *, recursive_guard=frozenset(), +def _eval_type(t, globalns, localns, type_params, *, recursive_guard=frozenset(), format=None, owner=None, parent_fwdref=None, prefer_fwd_module=False): """Evaluate all forward references in the given type t. @@ -438,10 +455,7 @@ def _eval_type(t, globalns, localns, type_params=_sentinel, *, recursive_guard=f recursive_guard is used to prevent infinite recursion with a recursive ForwardRef. """ - if type_params is _sentinel: - _deprecation_warning_for_no_type_params_passed("typing._eval_type") - type_params = () - if isinstance(t, _lazy_annotationlib.ForwardRef): + if isinstance(t, annotationlib.ForwardRef): # If the forward_ref has __forward_module__ set, evaluate() infers the globals # from the module, and it will probably pick better than the globals we have here. # We do this only for calls from get_type_hints() (which opts in through the @@ -467,25 +481,20 @@ def _eval_type(t, globalns, localns, type_params=_sentinel, *, recursive_guard=f _make_forward_ref(arg, parent_fwdref=parent_fwdref) if isinstance(arg, str) else arg for arg in t.__args__ ) - is_unpacked = t.__unpacked__ - if _should_unflatten_callable_args(t, args): - t = t.__origin__[(args[:-1], args[-1])] - else: - t = t.__origin__[args] - if is_unpacked: - t = Unpack[t] + else: + args = t.__args__ ev_args = tuple( _eval_type( a, globalns, localns, type_params, recursive_guard=recursive_guard, format=format, owner=owner, prefer_fwd_module=prefer_fwd_module, ) - for a in t.__args__ + for a in args ) if ev_args == t.__args__: return t if isinstance(t, GenericAlias): - return GenericAlias(t.__origin__, ev_args) + return _rebuild_generic_alias(t, ev_args) if isinstance(t, Union): return functools.reduce(operator.or_, ev_args) else: @@ -573,6 +582,13 @@ def __getitem__(self, parameters): return self._getitem(self, *parameters) +class _TypeFormForm(_SpecialForm, _root=True): + # TypeForm(X) is equivalent to X but indicates to the type checker + # that the object is a TypeForm. + def __call__(self, obj, /): + return obj + + class _AnyMeta(type): def __instancecheck__(self, obj): if self is Any: @@ -883,6 +899,31 @@ def func1(val: list[object]): return _GenericAlias(self, (item,)) +@_TypeFormForm +def TypeForm(self, parameters): + """A special form representing the value that results from the evaluation + of a type expression. + + This value encodes the information supplied in the type expression, and it + represents the type described by that type expression. + + When used in a type expression, TypeForm describes a set of type form + objects. It accepts a single type argument, which must be a valid type + expression. ``TypeForm[T]`` describes the set of all type form objects that + represent the type T or types that are assignable to T. + + Usage:: + + def cast[T](typ: TypeForm[T], value: Any) -> T: ... + + reveal_type(cast(int, "x")) # int + + See PEP 747 for more information. + """ + item = _type_check(parameters, f'{self} accepts only single type.') + return _GenericAlias(self, (item,)) + + @_SpecialForm def TypeIs(self, parameters): """Special typing construct for marking user-defined type predicate functions. @@ -958,7 +999,7 @@ def _make_forward_ref(code, *, parent_fwdref=None, **kwargs): kwargs['module'] = parent_fwdref.__forward_module__ if parent_fwdref.__owner__ is not None: kwargs['owner'] = parent_fwdref.__owner__ - forward_ref = _lazy_annotationlib.ForwardRef(code, **kwargs) + forward_ref = annotationlib.ForwardRef(code, **kwargs) # For compatibility, eagerly compile the forwardref's code. forward_ref.__forward_code__ return forward_ref @@ -993,18 +1034,18 @@ def evaluate_forward_ref( VALUE. """ - if format == _lazy_annotationlib.Format.STRING: + if format == annotationlib.Format.STRING: return forward_ref.__resolved_str__ if forward_ref.__forward_arg__ in _recursive_guard: return forward_ref if format is None: - format = _lazy_annotationlib.Format.VALUE + format = annotationlib.Format.VALUE value = forward_ref.evaluate(globals=globals, locals=locals, type_params=type_params, owner=owner, format=format) - if (isinstance(value, _lazy_annotationlib.ForwardRef) - and format == _lazy_annotationlib.Format.FORWARDREF): + if (isinstance(value, annotationlib.ForwardRef) + and format == annotationlib.Format.FORWARDREF): return value if isinstance(value, str): @@ -1186,20 +1227,22 @@ def _generic_init_subclass(cls, *args, **kwargs): if error: raise TypeError("Cannot inherit from plain Generic") if '__orig_bases__' in cls.__dict__: - tvars = _collect_type_parameters(cls.__orig_bases__) + tvars = _collect_type_parameters(cls.__orig_bases__, validate_all=True) # Look for Generic[T1, ..., Tn]. # If found, tvars must be a subset of it. # If not found, tvars is it. # Also check for and reject plain Generic, # and reject multiple Generic[...]. gvars = None + basename = None for base in cls.__orig_bases__: if (isinstance(base, _GenericAlias) and - base.__origin__ is Generic): + base.__origin__ in (Generic, Protocol)): if gvars is not None: raise TypeError( "Cannot inherit from Generic[...] multiple times.") gvars = base.__parameters__ + basename = base.__origin__.__name__ if gvars is not None: tvarset = set(tvars) gvarset = set(gvars) @@ -1207,7 +1250,7 @@ def _generic_init_subclass(cls, *args, **kwargs): s_vars = ', '.join(str(t) for t in tvars if t not in gvarset) s_args = ', '.join(str(g) for g in gvars) raise TypeError(f"Some type variables ({s_vars}) are" - f" not listed in Generic[{s_args}]") + f" not listed in {basename}[{s_args}]") tvars = gvars cls.__parameters__ = tuple(tvars) @@ -1605,21 +1648,6 @@ def __ror__(self, left): return Union[left, self] -class _DeprecatedGenericAlias(_SpecialGenericAlias, _root=True): - def __init__( - self, origin, nparams, *, removal_version, inst=True, name=None - ): - super().__init__(origin, nparams, inst=inst, name=name) - self._removal_version = removal_version - - def __instancecheck__(self, inst): - import warnings - warnings._deprecated( - f"{self.__module__}.{self._name}", remove=self._removal_version - ) - return super().__instancecheck__(inst) - - class _CallableGenericAlias(_NotIterable, _GenericAlias, _root=True): def __repr__(self): assert self._name == 'Callable' @@ -1832,6 +1860,7 @@ class _TypingEllipsis: _TYPING_INTERNALS = frozenset({ '__parameters__', '__orig_bases__', '__orig_class__', '_is_protocol', '_is_runtime_protocol', '__protocol_attrs__', + '__typing_is_deprecated_inherited_runtime_protocol__', '__non_callable_proto_members__', '__type_params__', }) @@ -1861,8 +1890,8 @@ def _get_protocol_attrs(cls): annotations = base.__annotations__ except Exception: # Only go through annotationlib to handle deferred annotations if we need to - annotations = _lazy_annotationlib.get_annotations( - base, format=_lazy_annotationlib.Format.FORWARDREF + annotations = annotationlib.get_annotations( + base, format=annotationlib.Format.FORWARDREF ) for attr in (*base.__dict__, *annotations): if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES: @@ -1916,7 +1945,9 @@ def _allow_reckless_class_checks(depth=2): The abc and functools modules indiscriminately call isinstance() and issubclass() on the whole MRO of a user class, which may contain protocols. """ - return _caller(depth) in {'abc', 'functools', None} + # gh-136047: When `_abc` module is not available, `_py_abc` is required to + # allow `_py_abc.ABCMeta` fallback. + return _caller(depth) in {'abc', '_py_abc', 'functools', None} _PROTO_ALLOWLIST = { @@ -2019,6 +2050,16 @@ def __subclasscheck__(cls, other): "Instance and class checks can only be used with " "@runtime_checkable protocols" ) + if getattr(cls, '__typing_is_deprecated_inherited_runtime_protocol__', False): + # See GH-132604. + import warnings + depr_message = ( + f"{cls!r} isn't explicitly decorated with @runtime_checkable but " + "it is used in issubclass() or isinstance(). Instance and class " + "checks can only be used with @runtime_checkable protocols. " + "This will raise a TypeError in Python 3.20." + ) + warnings.warn(depr_message, category=DeprecationWarning, stacklevel=2) if ( # this attribute is set by @runtime_checkable: cls.__non_callable_proto_members__ @@ -2048,6 +2089,18 @@ def __instancecheck__(cls, instance): raise TypeError("Instance and class checks can only be used with" " @runtime_checkable protocols") + if getattr(cls, '__typing_is_deprecated_inherited_runtime_protocol__', False): + # See GH-132604. + import warnings + + depr_message = ( + f"{cls!r} isn't explicitly decorated with @runtime_checkable but " + "it is used in issubclass() or isinstance(). Instance and class " + "checks can only be used with @runtime_checkable protocols. " + "This will raise a TypeError in Python 3.20." + ) + warnings.warn(depr_message, category=DeprecationWarning, stacklevel=2) + if _abc_instancecheck(cls, instance): return True @@ -2086,8 +2139,8 @@ def _proto_hook(cls, other): try: annos = base.__annotations__ except Exception: - annos = _lazy_annotationlib.get_annotations( - base, format=_lazy_annotationlib.Format.FORWARDREF + annos = annotationlib.get_annotations( + base, format=annotationlib.Format.FORWARDREF ) if attr in annos: break @@ -2140,6 +2193,11 @@ def __init_subclass__(cls, *args, **kwargs): if not cls.__dict__.get('_is_protocol', False): cls._is_protocol = any(b is Protocol for b in cls.__bases__) + # Mark inherited runtime checkability (deprecated). See GH-132604. + if cls._is_protocol and getattr(cls, '_is_runtime_protocol', False): + # This flag is set to False by @runtime_checkable. + cls.__typing_is_deprecated_inherited_runtime_protocol__ = True + # Set (or override) the protocol subclass hook. if '__subclasshook__' not in cls.__dict__: cls.__subclasshook__ = _proto_hook @@ -2286,6 +2344,9 @@ def close(self): ... raise TypeError('@runtime_checkable can be only applied to protocol classes,' ' got %r' % cls) cls._is_runtime_protocol = True + # See GH-132604. + if hasattr(cls, '__typing_is_deprecated_inherited_runtime_protocol__'): + cls.__typing_is_deprecated_inherited_runtime_protocol__ = False # PEP 544 prohibits using issubclass() # with protocols that have non-method members. # See gh-113320 for why we compute this attribute here, @@ -2366,14 +2427,14 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False, """ if getattr(obj, '__no_type_check__', None): return {} - Format = _lazy_annotationlib.Format + Format = annotationlib.Format if format is None: format = Format.VALUE # Classes require a special treatment. if isinstance(obj, type): hints = {} for base in reversed(obj.__mro__): - ann = _lazy_annotationlib.get_annotations(base, format=format) + ann = annotationlib.get_annotations(base, format=format) if format == Format.STRING: hints.update(ann) continue @@ -2406,7 +2467,7 @@ def get_type_hints(obj, globalns=None, localns=None, include_extras=False, else: return {k: _strip_annotations(t) for k, t in hints.items()} - hints = _lazy_annotationlib.get_annotations(obj, format=format) + hints = annotationlib.get_annotations(obj, format=format) if ( not hints and not isinstance(obj, types.ModuleType) @@ -2482,7 +2543,7 @@ def _strip_annotations(t): stripped_args = tuple(_strip_annotations(a) for a in t.__args__) if stripped_args == t.__args__: return t - return GenericAlias(t.__origin__, stripped_args) + return _rebuild_generic_alias(t, stripped_args) if isinstance(t, Union): stripped_args = tuple(_strip_annotations(a) for a in t.__args__) if stripped_args == t.__args__: @@ -2630,23 +2691,6 @@ def no_type_check(arg): return arg -def no_type_check_decorator(decorator): - """Decorator to give another decorator the @no_type_check effect. - - This wraps the decorator with something that wraps the decorated - function in @no_type_check. - """ - import warnings - warnings._deprecated("typing.no_type_check_decorator", remove=(3, 15)) - @functools.wraps(decorator) - def wrapped_decorator(*args, **kwds): - func = decorator(*args, **kwds) - func = no_type_check(func) - return func - - return wrapped_decorator - - def _overload_dummy(*args, **kwds): """Helper for @overload to raise when called.""" raise NotImplementedError( @@ -2753,6 +2797,29 @@ class Other(Leaf): # Error reported by type checker return f +def disjoint_base(cls): + """This decorator marks a class as a disjoint base. + + Child classes of a disjoint base cannot inherit from other disjoint bases that are + not parent or child classes of the disjoint base. + + For example: + + @disjoint_base + class Disjoint1: pass + + @disjoint_base + class Disjoint2: pass + + class Disjoint3(Disjoint1, Disjoint2): pass # Type checker error + + Type checkers can use knowledge of disjoint bases to detect unreachable code + and determine when two types can overlap. + """ + cls.__disjoint_base__ = True + return cls + + # Some unconstrained type variables. These were initially used by the container types. # They were never meant for export and are now unused, but we keep them around to # avoid breaking compatibility with users who import them. @@ -2808,9 +2875,6 @@ class Other(Leaf): # Error reported by type checker MutableMapping = _alias(collections.abc.MutableMapping, 2) Sequence = _alias(collections.abc.Sequence, 1) MutableSequence = _alias(collections.abc.MutableSequence, 1) -ByteString = _DeprecatedGenericAlias( - collections.abc.ByteString, 0, removal_version=(3, 17) # Not generic. -) # Tuple accepts variable number of parameters. Tuple = _TupleType(tuple, -1, inst=False, name='Tuple') Tuple.__doc__ = \ @@ -2954,10 +3018,10 @@ def _make_eager_annotate(types): for key, val in types.items()} def annotate(format): match format: - case _lazy_annotationlib.Format.VALUE | _lazy_annotationlib.Format.FORWARDREF: + case annotationlib.Format.VALUE | annotationlib.Format.FORWARDREF: return checked_types - case _lazy_annotationlib.Format.STRING: - return _lazy_annotationlib.annotations_to_string(types) + case annotationlib.Format.STRING: + return annotationlib.annotations_to_string(types) case _: raise NotImplementedError(format) return annotate @@ -2987,9 +3051,9 @@ def __new__(cls, typename, bases, ns): types = ns["__annotations__"] field_names = list(types) annotate = _make_eager_annotate(types) - elif (original_annotate := _lazy_annotationlib.get_annotate_from_class_namespace(ns)) is not None: - types = _lazy_annotationlib.call_annotate_function( - original_annotate, _lazy_annotationlib.Format.FORWARDREF) + elif (original_annotate := annotationlib.get_annotate_from_class_namespace(ns)) is not None: + types = annotationlib.call_annotate_function( + original_annotate, annotationlib.Format.FORWARDREF) field_names = list(types) # For backward compatibility, type-check all the types at creation time @@ -2997,9 +3061,9 @@ def __new__(cls, typename, bases, ns): _type_check(typ, "field annotation must be a type") def annotate(format): - annos = _lazy_annotationlib.call_annotate_function( + annos = annotationlib.call_annotate_function( original_annotate, format) - if format != _lazy_annotationlib.Format.STRING: + if format != annotationlib.Format.STRING: return {key: _type_check(val, f"field {key} annotation must be a type") for key, val in annos.items()} return annos @@ -3049,7 +3113,7 @@ def annotate(format): return nm_tpl -def NamedTuple(typename, fields=_sentinel, /, **kwargs): +def NamedTuple(typename, fields, /): """Typed version of collections.namedtuple. Usage:: @@ -3069,49 +3133,9 @@ class Employee(NamedTuple): Employee = NamedTuple('Employee', [('name', str), ('id', int)]) """ - if fields is _sentinel: - if kwargs: - deprecated_thing = "Creating NamedTuple classes using keyword arguments" - deprecation_msg = ( - "{name} is deprecated and will be disallowed in Python {remove}. " - "Use the class-based or functional syntax instead." - ) - else: - deprecated_thing = "Failing to pass a value for the 'fields' parameter" - example = f"`{typename} = NamedTuple({typename!r}, [])`" - deprecation_msg = ( - "{name} is deprecated and will be disallowed in Python {remove}. " - "To create a NamedTuple class with 0 fields " - "using the functional syntax, " - "pass an empty list, e.g. " - ) + example + "." - elif fields is None: - if kwargs: - raise TypeError( - "Cannot pass `None` as the 'fields' parameter " - "and also specify fields using keyword arguments" - ) - else: - deprecated_thing = "Passing `None` as the 'fields' parameter" - example = f"`{typename} = NamedTuple({typename!r}, [])`" - deprecation_msg = ( - "{name} is deprecated and will be disallowed in Python {remove}. " - "To create a NamedTuple class with 0 fields " - "using the functional syntax, " - "pass an empty list, e.g. " - ) + example + "." - elif kwargs: - raise TypeError("Either list of fields or keywords" - " can be provided to NamedTuple, not both") - if fields is _sentinel or fields is None: - import warnings - warnings._deprecated(deprecated_thing, message=deprecation_msg, remove=(3, 15)) - fields = kwargs.items() types = {n: _type_check(t, f"field {n} annotation must be a type") for n, t in fields} - field_names = [n for n, _ in fields] - - nt = _make_nmtuple(typename, field_names, _make_eager_annotate(types), module=_caller()) + nt = _make_nmtuple(typename, types, _make_eager_annotate(types), module=_caller()) nt.__orig_bases__ = (NamedTuple,) return nt @@ -3124,6 +3148,9 @@ def _namedtuple_mro_entries(bases): NamedTuple.__mro_entries__ = _namedtuple_mro_entries +NoExtraItems = sentinel("NoExtraItems") + + def _get_typeddict_qualifiers(annotation_type): while True: annotation_origin = get_origin(annotation_type) @@ -3147,7 +3174,8 @@ def _get_typeddict_qualifiers(annotation_type): class _TypedDictMeta(type): - def __new__(cls, name, bases, ns, total=True): + def __new__(cls, name, bases, ns, total=True, closed=None, + extra_items=NoExtraItems): """Create a new typed dict class object. This method is called when TypedDict is subclassed, @@ -3159,6 +3187,8 @@ def __new__(cls, name, bases, ns, total=True): if type(base) is not _TypedDictMeta and base is not Generic: raise TypeError('cannot inherit from both a TypedDict type ' 'and a non-TypedDict base class') + if closed is not None and extra_items is not NoExtraItems: + raise TypeError(f"Cannot combine closed={closed!r} and extra_items") if any(issubclass(b, Generic) for b in bases): generic_base = (Generic,) @@ -3175,9 +3205,9 @@ def __new__(cls, name, bases, ns, total=True): if ns_annotations is not None: own_annotate = None own_annotations = ns_annotations - elif (own_annotate := _lazy_annotationlib.get_annotate_from_class_namespace(ns)) is not None: - own_annotations = _lazy_annotationlib.call_annotate_function( - own_annotate, _lazy_annotationlib.Format.FORWARDREF, owner=tp_dict + elif (own_annotate := annotationlib.get_annotate_from_class_namespace(ns)) is not None: + own_annotations = annotationlib.call_annotate_function( + own_annotate, annotationlib.Format.FORWARDREF, owner=tp_dict ) else: own_annotate = None @@ -3244,20 +3274,20 @@ def __annotate__(format): base_annotate = base.__annotate__ if base_annotate is None: continue - base_annos = _lazy_annotationlib.call_annotate_function( + base_annos = annotationlib.call_annotate_function( base_annotate, format, owner=base) annos.update(base_annos) if own_annotate is not None: - own = _lazy_annotationlib.call_annotate_function( + own = annotationlib.call_annotate_function( own_annotate, format, owner=tp_dict) - if format != _lazy_annotationlib.Format.STRING: + if format != annotationlib.Format.STRING: own = { n: _type_check(tp, msg, module=tp_dict.__module__) for n, tp in own.items() } - elif format == _lazy_annotationlib.Format.STRING: - own = _lazy_annotationlib.annotations_to_string(own_annotations) - elif format in (_lazy_annotationlib.Format.FORWARDREF, _lazy_annotationlib.Format.VALUE): + elif format == annotationlib.Format.STRING: + own = annotationlib.annotations_to_string(own_annotations) + elif format in (annotationlib.Format.FORWARDREF, annotationlib.Format.VALUE): own = own_checked_annotations else: raise NotImplementedError(format) @@ -3270,6 +3300,8 @@ def __annotate__(format): tp_dict.__readonly_keys__ = frozenset(readonly_keys) tp_dict.__mutable_keys__ = frozenset(mutable_keys) tp_dict.__total__ = total + tp_dict.__closed__ = closed + tp_dict.__extra_items__ = extra_items return tp_dict __call__ = dict # static method @@ -3281,7 +3313,8 @@ def __subclasscheck__(cls, other): __instancecheck__ = __subclasscheck__ -def TypedDict(typename, fields=_sentinel, /, *, total=True): +def TypedDict(typename, fields, /, *, total=True, closed=None, + extra_items=NoExtraItems): """A simple typed namespace. At runtime it is equivalent to a plain dict. TypedDict creates a dictionary type such that a type checker will expect all @@ -3335,33 +3368,41 @@ class DatabaseUser(TypedDict): id: ReadOnly[int] # the "id" key must not be modified username: str # the "username" key can be changed - See PEPs 589, 655, and 705 for more information. - """ - if fields is _sentinel or fields is None: - import warnings + The closed argument controls whether the TypedDict allows additional + non-required items during inheritance and assignability checks. + If closed=True, the TypedDict does not allow additional items:: - if fields is _sentinel: - deprecated_thing = "Failing to pass a value for the 'fields' parameter" - else: - deprecated_thing = "Passing `None` as the 'fields' parameter" - - example = f"`{typename} = TypedDict({typename!r}, {{{{}}}})`" - deprecation_msg = ( - "{name} is deprecated and will be disallowed in Python {remove}. " - "To create a TypedDict class with 0 fields " - "using the functional syntax, " - "pass an empty dictionary, e.g. " - ) + example + "." - warnings._deprecated(deprecated_thing, message=deprecation_msg, remove=(3, 15)) - fields = {} + Point2D = TypedDict('Point2D', {'x': int, 'y': int}, closed=True) + class Point3D(Point2D): + z: int # Type checker error + + Passing closed=False explicitly requests TypedDict's default open behavior. + If closed is not provided, the behavior is inherited from the superclass. + A type checker is only expected to support a literal False or True as the + value of the closed argument. + + The extra_items argument can instead be used to specify the assignable type + of unknown non-required keys:: + Point2D = TypedDict('Point2D', {'x': int, 'y': int}, extra_items=int) + class Point3D(Point2D): + z: int # OK + label: str # Type checker error + + The extra_items argument is also inherited through subclassing. It is unset + by default, and it may not be used with the closed argument at the same + time. + + See PEPs 589, 655, 705, and 728 for more information. + """ ns = {'__annotations__': dict(fields)} module = _caller() if module is not None: # Setting correct module is necessary to make typed dict classes pickleable. ns['__module__'] = module - td = _TypedDictMeta(typename, (), ns, total=total) + td = _TypedDictMeta(typename, (), ns, total=total, closed=closed, + extra_items=extra_items) td.__orig_bases__ = (TypedDict,) return td @@ -3549,7 +3590,7 @@ def isatty(self) -> bool: pass @abstractmethod - def read(self, n: int = -1) -> AnyStr: + def read(self, n: int = -1, /) -> AnyStr: pass @abstractmethod @@ -3557,15 +3598,15 @@ def readable(self) -> bool: pass @abstractmethod - def readline(self, limit: int = -1) -> AnyStr: + def readline(self, limit: int = -1, /) -> AnyStr: pass @abstractmethod - def readlines(self, hint: int = -1) -> list[AnyStr]: + def readlines(self, hint: int = -1, /) -> list[AnyStr]: pass @abstractmethod - def seek(self, offset: int, whence: int = 0) -> int: + def seek(self, offset: int, whence: int = 0, /) -> int: pass @abstractmethod @@ -3577,7 +3618,7 @@ def tell(self) -> int: pass @abstractmethod - def truncate(self, size: int | None = None) -> int: + def truncate(self, size: int | None = None, /) -> int: pass @abstractmethod @@ -3585,11 +3626,11 @@ def writable(self) -> bool: pass @abstractmethod - def write(self, s: AnyStr) -> int: + def write(self, s: AnyStr, /) -> int: pass @abstractmethod - def writelines(self, lines: list[AnyStr]) -> None: + def writelines(self, lines: list[AnyStr], /) -> None: pass @abstractmethod @@ -3597,7 +3638,7 @@ def __enter__(self) -> IO[AnyStr]: pass @abstractmethod - def __exit__(self, type, value, traceback) -> None: + def __exit__(self, type, value, traceback, /) -> None: pass @@ -3607,7 +3648,7 @@ class BinaryIO(IO[bytes]): __slots__ = () @abstractmethod - def write(self, s: bytes | bytearray) -> int: + def write(self, s: bytes | bytearray, /) -> int: pass @abstractmethod @@ -3843,7 +3884,7 @@ def __getattr__(attr): are only created on-demand here. """ if attr == "ForwardRef": - obj = _lazy_annotationlib.ForwardRef + obj = annotationlib.ForwardRef elif attr in {"Pattern", "Match"}: import re obj = _alias(getattr(re, attr), 1) @@ -3860,6 +3901,48 @@ def __getattr__(attr): ) warnings.warn(depr_message, category=DeprecationWarning, stacklevel=2) obj = _collect_type_parameters + elif attr == "ByteString": + import warnings + + warnings._deprecated( + "typing.ByteString", + message=( + "{name!r} and 'collections.abc.ByteString' are deprecated " + "and slated for removal in Python {remove}" + ), + remove=(3, 17) + ) + + class _DeprecatedGenericAlias(_SpecialGenericAlias, _root=True): + def __init__( + self, origin, nparams, *, removal_version, inst=True, name=None + ): + super().__init__(origin, nparams, inst=inst, name=name) + self._removal_version = removal_version + + def __instancecheck__(self, inst): + import warnings + warnings._deprecated( + f"{self.__module__}.{self._name}", remove=self._removal_version + ) + return super().__instancecheck__(inst) + + def __subclasscheck__(self, cls): + import warnings + warnings._deprecated( + f"{self.__module__}.{self._name}", remove=self._removal_version + ) + return super().__subclasscheck__(cls) + + with warnings.catch_warnings( + action="ignore", category=DeprecationWarning + ): + # Not generic + ByteString = globals()["ByteString"] = _DeprecatedGenericAlias( + collections.abc.ByteString, 0, removal_version=(3, 17) + ) + + return ByteString else: raise AttributeError(f"module {__name__!r} has no attribute {attr!r}") globals()[attr] = obj diff --git a/Lib/unittest/_log.py b/Lib/unittest/_log.py index 94868e5bb95..3d69385ea24 100644 --- a/Lib/unittest/_log.py +++ b/Lib/unittest/_log.py @@ -30,7 +30,7 @@ class _AssertLogsContext(_BaseTestCaseContext): LOGGING_FORMAT = "%(levelname)s:%(name)s:%(message)s" - def __init__(self, test_case, logger_name, level, no_logs): + def __init__(self, test_case, logger_name, level, no_logs, formatter=None): _BaseTestCaseContext.__init__(self, test_case) self.logger_name = logger_name if level: @@ -39,13 +39,14 @@ def __init__(self, test_case, logger_name, level, no_logs): self.level = logging.INFO self.msg = None self.no_logs = no_logs + self.formatter = formatter def __enter__(self): if isinstance(self.logger_name, logging.Logger): logger = self.logger = self.logger_name else: logger = self.logger = logging.getLogger(self.logger_name) - formatter = logging.Formatter(self.LOGGING_FORMAT) + formatter = self.formatter or logging.Formatter(self.LOGGING_FORMAT) handler = _CapturingHandler() handler.setLevel(self.level) handler.setFormatter(formatter) diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index 884fc1b21f6..a392238c85a 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -149,9 +149,7 @@ def doModuleCleanups(): except Exception as exc: exceptions.append(exc) if exceptions: - # Swallows all but first exception. If a multi-exception handler - # gets written we should use that here instead. - raise exceptions[0] + raise ExceptionGroup('module cleanup failed', exceptions) def skip(reason): @@ -303,7 +301,7 @@ def __enter__(self): v.__warningregistry__ = {} self.warnings_manager = warnings.catch_warnings(record=True) self.warnings = self.warnings_manager.__enter__() - warnings.simplefilter("always", self.expected) + warnings.simplefilter("always") return self def __exit__(self, exc_type, exc_value, tb): @@ -316,19 +314,44 @@ def __exit__(self, exc_type, exc_value, tb): except AttributeError: exc_name = str(self.expected) first_matching = None + matched = False + non_matching_warnings = [] for m in self.warnings: w = m.message if not isinstance(w, self.expected): + non_matching_warnings.append(m) continue if first_matching is None: first_matching = w if (self.expected_regex is not None and not self.expected_regex.search(str(w))): + non_matching_warnings.append(m) continue + if matched: + continue + matched = True # store warning for later retrieval self.warning = w self.filename = m.filename self.lineno = m.lineno + for m in non_matching_warnings: + module = m.module + module_globals = None + registry = None + if module is not None: + try: + module_globals = vars(sys.modules[module]) + except (KeyError, TypeError): + # module == "" or sys.modules[module] is None + pass + else: + registry = module_globals.setdefault("__warningregistry__", {}) + warnings.warn_explicit(m.message, m.category, m.filename, m.lineno, + module=module, + registry=registry, + module_globals=module_globals, + source=m.source) + if matched: return # Now we simply try to choose a helpful failure message if first_matching is not None: @@ -340,7 +363,6 @@ def __exit__(self, exc_type, exc_value, tb): else: self._raiseFailure("{} not triggered".format(exc_name)) - class _AssertNotWarnsContext(_AssertWarnsContext): def __exit__(self, exc_type, exc_value, tb): @@ -851,7 +873,7 @@ def _assertNotWarns(self, expected_warning, *args, **kwargs): context = _AssertNotWarnsContext(expected_warning, self) return context.handle('_assertNotWarns', args, kwargs) - def assertLogs(self, logger=None, level=None): + def assertLogs(self, logger=None, level=None, formatter=None): """Fail unless a log message of level *level* or higher is emitted on *logger_name* or its children. If omitted, *level* defaults to INFO and *logger* defaults to the root logger. @@ -863,6 +885,8 @@ def assertLogs(self, logger=None, level=None): `records` attribute will be a list of the corresponding LogRecord objects. + Optionally supply `formatter` to control how messages are formatted. + Example:: with self.assertLogs('foo', level='INFO') as cm: @@ -873,7 +897,7 @@ def assertLogs(self, logger=None, level=None): """ # Lazy import to avoid importing logging if it is not needed. from ._log import _AssertLogsContext - return _AssertLogsContext(self, logger, level, no_logs=False) + return _AssertLogsContext(self, logger, level, no_logs=False, formatter=formatter) def assertNoLogs(self, logger=None, level=None): """ Fail unless no log messages of level *level* or higher are emitted diff --git a/Lib/unittest/loader.py b/Lib/unittest/loader.py index a52950dad22..697520246f0 100644 --- a/Lib/unittest/loader.py +++ b/Lib/unittest/loader.py @@ -1,5 +1,6 @@ """Loading unittests.""" +import inspect import os import re import sys @@ -84,8 +85,10 @@ def loadTestsFromTestCase(self, testCaseClass): raise TypeError("Test cases should not be derived from " "TestSuite. Maybe you meant to derive from " "TestCase?") - if testCaseClass in (case.TestCase, case.FunctionTestCase): - # We don't load any tests from base types that should not be loaded. + if (testCaseClass in (case.TestCase, case.FunctionTestCase) or + inspect.isabstract(testCaseClass)): + # We don't load any tests from base types that should not be loaded, + # and abstract base classes that can't be instantiated testCaseNames = [] else: testCaseNames = self.getTestCaseNames(testCaseClass) @@ -103,6 +106,7 @@ def loadTestsFromModule(self, module, *, pattern=None): isinstance(obj, type) and issubclass(obj, case.TestCase) and obj not in (case.TestCase, case.FunctionTestCase) + and not inspect.isabstract(obj) ): tests.append(self.loadTestsFromTestCase(obj)) @@ -181,6 +185,9 @@ def loadTestsFromName(self, name, module=None): elif (isinstance(obj, types.FunctionType) and isinstance(parent, type) and issubclass(parent, case.TestCase)): + if inspect.isabstract(parent): + raise TypeError( + "Cannot instantiate abstract test case %s" % parent.__name__) name = parts[-1] inst = parent(name) # static methods follow a different path diff --git a/Lib/unittest/main.py b/Lib/unittest/main.py index be99d93c78c..6eeebf9657a 100644 --- a/Lib/unittest/main.py +++ b/Lib/unittest/main.py @@ -172,7 +172,7 @@ def _getParentArgParser(self): help='Show local variables in tracebacks') parser.add_argument('--durations', dest='durations', type=int, default=None, metavar="N", - help='Show the N slowest test cases (N=0 for all)') + help='Show the `N` slowest test cases (`N=0` for all)') if self.failfast is None: parser.add_argument('-f', '--failfast', dest='failfast', action='store_true', @@ -181,12 +181,12 @@ def _getParentArgParser(self): if self.catchbreak is None: parser.add_argument('-c', '--catch', dest='catchbreak', action='store_true', - help='Catch Ctrl-C and display results so far') + help='Catch `Ctrl-C` and display results so far') self.catchbreak = False if self.buffer is None: parser.add_argument('-b', '--buffer', dest='buffer', action='store_true', - help='Buffer stdout and stderr during tests') + help='Buffer `stdout` and `stderr` during tests') self.buffer = False if self.testNamePatterns is None: parser.add_argument('-k', dest='testNamePatterns', @@ -197,7 +197,7 @@ def _getParentArgParser(self): return parser def _getMainArgParser(self, parent): - parser = argparse.ArgumentParser(parents=[parent], color=True) + parser = argparse.ArgumentParser(parents=[parent]) parser.prog = self.progName parser.print_help = self._print_help @@ -208,16 +208,16 @@ def _getMainArgParser(self, parent): return parser def _getDiscoveryArgParser(self, parent): - parser = argparse.ArgumentParser(parents=[parent], color=True) + parser = argparse.ArgumentParser(parents=[parent]) parser.prog = '%s discover' % self.progName parser.epilog = ('For test discovery all test modules must be ' 'importable from the top level directory of the ' 'project.') parser.add_argument('-s', '--start-directory', dest='start', - help="Directory to start discovery ('.' default)") + help="Directory to start discovery (`.` default)") parser.add_argument('-p', '--pattern', dest='pattern', - help="Pattern to match tests ('test*.py' default)") + help="Pattern to match tests (`test*.py` default)") parser.add_argument('-t', '--top-level-directory', dest='top', help='Top level directory of project (defaults to ' 'start directory)') diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 5a8fccf59dc..6a103f8fd66 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -36,7 +36,7 @@ import threading from annotationlib import Format from dataclasses import fields, is_dataclass -from types import CodeType, ModuleType, MethodType +from types import CodeType, LazyImportType, ModuleType, MethodType from unittest.util import safe_repr from functools import wraps, partial from threading import RLock @@ -597,7 +597,7 @@ def __set_return_value(self, value): __return_value_doc = "The value to be returned when the mock is called." return_value = property(__get_return_value, __set_return_value, - __return_value_doc) + doc=__return_value_doc) @property @@ -701,7 +701,7 @@ def __getattr__(self, name): if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')) or name in _ATTRIB_DENY_LIST: raise AttributeError( f"{name!r} is not a valid assertion. Use a spec " - f"for the mock if {name!r} is meant to be an attribute.") + f"for the mock if {name!r} is meant to be an attribute") with NonCallableMock._lock: result = self._mock_children.get(name) @@ -937,7 +937,7 @@ def _call_matcher(self, _call): return _call def assert_not_called(self): - """assert that the mock was never called. + """Assert that the mock was never called. """ if self.call_count != 0: msg = ("Expected '%s' to not have been called. Called %s times.%s" @@ -947,7 +947,7 @@ def assert_not_called(self): raise AssertionError(msg) def assert_called(self): - """assert that the mock was called at least once + """Assert that the mock was called at least once. """ if self.call_count == 0: msg = ("Expected '%s' to have been called." % @@ -955,7 +955,7 @@ def assert_called(self): raise AssertionError(msg) def assert_called_once(self): - """assert that the mock was called only once. + """Assert that the mock was called only once. """ if not self.call_count == 1: msg = ("Expected '%s' to have been called once. Called %s times.%s" @@ -965,7 +965,7 @@ def assert_called_once(self): raise AssertionError(msg) def assert_called_with(self, /, *args, **kwargs): - """assert that the last call was made with the specified arguments. + """Assert that the last call was made with the specified arguments. Raises an AssertionError if the args and keyword args passed in are different to the last call to the mock.""" @@ -987,7 +987,7 @@ def _error_message(): def assert_called_once_with(self, /, *args, **kwargs): - """assert that the mock was called exactly once and that that call was + """Assert that the mock was called exactly once and that call was with the specified arguments.""" if not self.call_count == 1: msg = ("Expected '%s' to be called once. Called %s times.%s" @@ -999,7 +999,7 @@ def assert_called_once_with(self, /, *args, **kwargs): def assert_has_calls(self, calls, any_order=False): - """assert the mock has been called with the specified calls. + """Assert the mock has been called with the specified calls. The `mock_calls` list is checked for the calls. If `any_order` is False (the default) then the calls must be @@ -1044,7 +1044,7 @@ def assert_has_calls(self, calls, any_order=False): def assert_any_call(self, /, *args, **kwargs): - """assert the mock has been called with the specified arguments. + """Assert the mock has been called with the specified arguments. The assert passes if the mock has *ever* been called, unlike `assert_called_with` and `assert_called_once_with` that only pass if @@ -1509,6 +1509,10 @@ def __enter__(self): original, local = self.get_original() + if (isinstance(original, LazyImportType) + and (spec is True or spec_set is True or autospec is True)): + original = original.resolve() + if new is DEFAULT and autospec is None: inherit = False if spec is True: diff --git a/Lib/unittest/runner.py b/Lib/unittest/runner.py index 5f22d91aebd..893fcba968c 100644 --- a/Lib/unittest/runner.py +++ b/Lib/unittest/runner.py @@ -4,11 +4,10 @@ import time import warnings -from _colorize import get_theme - from . import result from .case import _SubTest from .signals import registerResult +lazy from _colorize import get_theme __unittest = True diff --git a/Lib/unittest/suite.py b/Lib/unittest/suite.py index 6f45b6fe5f6..ae9ca2d615d 100644 --- a/Lib/unittest/suite.py +++ b/Lib/unittest/suite.py @@ -223,6 +223,11 @@ def _handleModuleFixture(self, test, result): if result._moduleSetUpFailed: try: case.doModuleCleanups() + except ExceptionGroup as eg: + for e in eg.exceptions: + self._createClassOrModuleLevelException(result, e, + 'setUpModule', + currentModule) except Exception as e: self._createClassOrModuleLevelException(result, e, 'setUpModule', @@ -235,15 +240,15 @@ def _createClassOrModuleLevelException(self, result, exc, method_name, errorName = f'{method_name} ({parent})' self._addClassOrModuleLevelException(result, exc, errorName, info) - def _addClassOrModuleLevelException(self, result, exception, errorName, + def _addClassOrModuleLevelException(self, result, exc, errorName, info=None): error = _ErrorHolder(errorName) addSkip = getattr(result, 'addSkip', None) - if addSkip is not None and isinstance(exception, case.SkipTest): - addSkip(error, str(exception)) + if addSkip is not None and isinstance(exc, case.SkipTest): + addSkip(error, str(exc)) else: if not info: - result.addError(error, sys.exc_info()) + result.addError(error, (type(exc), exc, exc.__traceback__)) else: result.addError(error, info) @@ -273,6 +278,13 @@ def _handleModuleTearDown(self, result): previousModule) try: case.doModuleCleanups() + except ExceptionGroup as eg: + if isinstance(result, _DebugResult): + raise + for e in eg.exceptions: + self._createClassOrModuleLevelException(result, e, + 'tearDownModule', + previousModule) except Exception as e: if isinstance(result, _DebugResult): raise diff --git a/Lib/unittest/util.py b/Lib/unittest/util.py index 050eaed0b3f..0681163c979 100644 --- a/Lib/unittest/util.py +++ b/Lib/unittest/util.py @@ -1,7 +1,6 @@ """Various utility functions.""" from collections import namedtuple, Counter -from os.path import commonprefix __unittest = True @@ -21,13 +20,23 @@ def _shorten(s, prefixlen, suffixlen): s = '%s[%d chars]%s' % (s[:prefixlen], skip, s[len(s) - suffixlen:]) return s +def _common_prefix(m): + if not m: + return "" + s1 = min(m) + s2 = max(m) + for i, c in enumerate(s1): + if c != s2[i]: + return s1[:i] + return s1 + def _common_shorten_repr(*args): args = tuple(map(safe_repr, args)) maxlen = max(map(len, args)) if maxlen <= _MAX_LENGTH: return args - prefix = commonprefix(args) + prefix = _common_prefix(args) prefixlen = len(prefix) common_len = _MAX_LENGTH - \ @@ -54,6 +63,14 @@ def safe_repr(obj, short=False): def strclass(cls): return "%s.%s" % (cls.__module__, cls.__qualname__) +def _dedupe_sorted(lst): + """Remove consecutive duplicate elements from a sorted list.""" + result = [] + for item in lst: + if not result or result[-1] != item: + result.append(item) + return result + def sorted_list_difference(expected, actual): """Finds elements in only one or the other of two, sorted input lists. @@ -89,8 +106,8 @@ def sorted_list_difference(expected, actual): while actual[j] == a: j += 1 except IndexError: - missing.extend(expected[i:]) - unexpected.extend(actual[j:]) + missing.extend(_dedupe_sorted(expected[i:])) + unexpected.extend(_dedupe_sorted(actual[j:])) break return missing, unexpected diff --git a/Lib/urllib/error.py b/Lib/urllib/error.py index a9cd1ecadd6..beb32d0df48 100644 --- a/Lib/urllib/error.py +++ b/Lib/urllib/error.py @@ -18,7 +18,7 @@ class URLError(OSError): # URLError is a sub-type of OSError, but it doesn't share any of - # the implementation. need to override __init__ and __str__. + # the implementation. It overrides __init__ and __str__. # It sets self.args for compatibility with other OSError # subclasses, but args doesn't have the typical format with errno in # slot 0 and strerror in slot 1. This may be better than nothing. diff --git a/Lib/urllib/parse.py b/Lib/urllib/parse.py index c9f8a33e72c..4247b9a4b07 100644 --- a/Lib/urllib/parse.py +++ b/Lib/urllib/parse.py @@ -97,11 +97,9 @@ def clear_cache(): _byte_quoter_factory.cache_clear() # Helpers for bytes handling -# For 3.2, we deliberately require applications that -# handle improperly quoted URLs to do their own -# decoding and encoding. If valid use cases are -# presented, we may relax this by using latin-1 -# decoding internally for 3.3 +# We deliberately require applications that +# handle improperly quoted URLs to do their +# own decoding and encoding. _implicit_encoding = 'ascii' _implicit_errors = 'strict' @@ -114,7 +112,10 @@ def _encode_result(obj, encoding=_implicit_encoding, def _decode_args(args, encoding=_implicit_encoding, errors=_implicit_errors): - return tuple(x.decode(encoding, errors) if x else '' for x in args) + return tuple(x.decode(encoding, errors) if x + else '' if x is not None + else None + for x in args) def _coerce_args(*args): # Invokes decode if necessary to create str args @@ -122,13 +123,20 @@ def _coerce_args(*args): # an appropriate result coercion function # - noop for str inputs # - encoding function otherwise - str_input = isinstance(args[0], str) - for arg in args[1:]: - # We special-case the empty string to support the - # "scheme=''" default argument to some functions - if arg and isinstance(arg, str) != str_input: - raise TypeError("Cannot mix str and non-str arguments") - if str_input: + str_input = None + for arg in args: + if arg: + if str_input is None: + str_input = isinstance(arg, str) + else: + if isinstance(arg, str) != str_input: + raise TypeError("Cannot mix str and non-str arguments") + if str_input is None: + for arg in args: + if arg is not None: + str_input = isinstance(arg, str) + break + if str_input is not False: return args + (_noop,) return _decode_args(args) + (_encode_result,) @@ -138,7 +146,14 @@ class _ResultMixinStr(object): __slots__ = () def encode(self, encoding='ascii', errors='strict'): - return self._encoded_counterpart(*(x.encode(encoding, errors) for x in self)) + result = self._encoded_counterpart(*(x.encode(encoding, errors) + if x is not None else None + for x in self)) + try: + result._keep_empty = self._keep_empty + except AttributeError: + pass + return result class _ResultMixinBytes(object): @@ -146,7 +161,14 @@ class _ResultMixinBytes(object): __slots__ = () def decode(self, encoding='ascii', errors='strict'): - return self._decoded_counterpart(*(x.decode(encoding, errors) for x in self)) + result = self._decoded_counterpart(*(x.decode(encoding, errors) + if x is not None else None + for x in self)) + try: + result._keep_empty = self._keep_empty + except AttributeError: + pass + return result class _NetlocResultMixinBase(object): @@ -193,6 +215,8 @@ class _NetlocResultMixinStr(_NetlocResultMixinBase, _ResultMixinStr): @property def _userinfo(self): netloc = self.netloc + if netloc is None: + return None, None userinfo, have_info, hostinfo = netloc.rpartition('@') if have_info: username, have_password, password = userinfo.partition(':') @@ -205,6 +229,8 @@ def _userinfo(self): @property def _hostinfo(self): netloc = self.netloc + if netloc is None: + return None, None _, _, hostinfo = netloc.rpartition('@') _, have_open_br, bracketed = hostinfo.partition('[') if have_open_br: @@ -223,6 +249,8 @@ class _NetlocResultMixinBytes(_NetlocResultMixinBase, _ResultMixinBytes): @property def _userinfo(self): netloc = self.netloc + if netloc is None: + return None, None userinfo, have_info, hostinfo = netloc.rpartition(b'@') if have_info: username, have_password, password = userinfo.partition(b':') @@ -235,6 +263,8 @@ def _userinfo(self): @property def _hostinfo(self): netloc = self.netloc + if netloc is None: + return None, None _, _, hostinfo = netloc.rpartition(b'@') _, have_open_br, bracketed = hostinfo.partition(b'[') if have_open_br: @@ -247,11 +277,70 @@ def _hostinfo(self): return hostname, port -_DefragResultBase = namedtuple('_DefragResultBase', 'url fragment') -_SplitResultBase = namedtuple( - '_SplitResultBase', 'scheme netloc path query fragment') -_ParseResultBase = namedtuple( - '_ParseResultBase', 'scheme netloc path params query fragment') +_UNSPECIFIED = sentinel("_UNSPECIFIED", repr="") +_MISSING_AS_NONE_DEFAULT = False + +class _ResultBase: + __slots__ = () + + def __replace__(self, /, **kwargs): + result = super().__replace__(**kwargs) + try: + result._keep_empty = self._keep_empty + except AttributeError: + pass + return result + + def _replace(self, /, **kwargs): + result = super()._replace(**kwargs) + try: + result._keep_empty = self._keep_empty + except AttributeError: + pass + return result + + def __copy__(self): + return self + + def __deepcopy__(self, memo): + return self + + def __getstate__(self): + state = super().__getstate__() + try: + if state[1]['_keep_empty'] == _MISSING_AS_NONE_DEFAULT: + del state[1]['_keep_empty'] + if state == (None, {}): + state = None + except LookupError: + pass + return state + + +class _DefragResultBase(_ResultBase, namedtuple('_DefragResultBase', 'url fragment')): + __slots__ = ('_keep_empty',) + + def geturl(self): + if self.fragment or (self.fragment is not None and + getattr(self, '_keep_empty', _MISSING_AS_NONE_DEFAULT)): + return self.url + self._HASH + self.fragment + else: + return self.url + +class _SplitResultBase(_ResultBase, namedtuple( + '_SplitResultBase', 'scheme netloc path query fragment')): + __slots__ = ('_keep_empty',) + + def geturl(self): + return urlunsplit(self) + +class _ParseResultBase(_ResultBase, namedtuple( + '_ParseResultBase', 'scheme netloc path params query fragment')): + __slots__ = ('_keep_empty',) + + def geturl(self): + return urlunparse(self) + _DefragResultBase.__doc__ = """ DefragResult(url, fragment) @@ -322,40 +411,24 @@ def _hostinfo(self): # Structured result objects for string data class DefragResult(_DefragResultBase, _ResultMixinStr): __slots__ = () - def geturl(self): - if self.fragment: - return self.url + '#' + self.fragment - else: - return self.url + _HASH = '#' class SplitResult(_SplitResultBase, _NetlocResultMixinStr): __slots__ = () - def geturl(self): - return urlunsplit(self) class ParseResult(_ParseResultBase, _NetlocResultMixinStr): __slots__ = () - def geturl(self): - return urlunparse(self) # Structured result objects for bytes data class DefragResultBytes(_DefragResultBase, _ResultMixinBytes): __slots__ = () - def geturl(self): - if self.fragment: - return self.url + b'#' + self.fragment - else: - return self.url + _HASH = b'#' class SplitResultBytes(_SplitResultBase, _NetlocResultMixinBytes): __slots__ = () - def geturl(self): - return urlunsplit(self) class ParseResultBytes(_ParseResultBase, _NetlocResultMixinBytes): __slots__ = () - def geturl(self): - return urlunparse(self) # Set up the encode/decode result pairs def _fix_result_transcoding(): @@ -371,7 +444,7 @@ def _fix_result_transcoding(): _fix_result_transcoding() del _fix_result_transcoding -def urlparse(url, scheme='', allow_fragments=True): +def urlparse(url, scheme=None, allow_fragments=True, *, missing_as_none=_MISSING_AS_NONE_DEFAULT): """Parse a URL into 6 components: :///;?# @@ -394,23 +467,33 @@ def urlparse(url, scheme='', allow_fragments=True): urlsplit() should generally be used instead of urlparse(). """ url, scheme, _coerce_result = _coerce_args(url, scheme) + if url is None: + url = '' scheme, netloc, url, params, query, fragment = _urlparse(url, scheme, allow_fragments) - result = ParseResult(scheme or '', netloc or '', url, params or '', query or '', fragment or '') - return _coerce_result(result) + if not missing_as_none: + if scheme is None: scheme = '' + if netloc is None: netloc = '' + if params is None: params = '' + if query is None: query = '' + if fragment is None: fragment = '' + result = ParseResult(scheme, netloc, url, params, query, fragment) + result = _coerce_result(result) + result._keep_empty = missing_as_none + return result def _urlparse(url, scheme=None, allow_fragments=True): scheme, netloc, url, query, fragment = _urlsplit(url, scheme, allow_fragments) if (scheme or '') in uses_params and ';' in url: - url, params = _splitparams(url, allow_none=True) + url, params = _splitparams(url, missing_as_none=True) else: params = None return (scheme, netloc, url, params, query, fragment) -def _splitparams(url, allow_none=False): +def _splitparams(url, missing_as_none=False): if '/' in url: i = url.find(';', url.rfind('/')) if i < 0: - return url, None if allow_none else '' + return url, None if missing_as_none else '' else: i = url.find(';') return url[:i], url[i+1:] @@ -472,7 +555,7 @@ def _check_bracketed_host(hostname): # typed=True avoids BytesWarnings being emitted during cache key # comparison since this API supports both bytes and str input. @functools.lru_cache(typed=True) -def urlsplit(url, scheme='', allow_fragments=True): +def urlsplit(url, scheme=None, allow_fragments=True, *, missing_as_none=_MISSING_AS_NONE_DEFAULT): """Parse a URL into 5 components: :///?# @@ -494,9 +577,18 @@ def urlsplit(url, scheme='', allow_fragments=True): """ url, scheme, _coerce_result = _coerce_args(url, scheme) + if url is None: + url = '' scheme, netloc, url, query, fragment = _urlsplit(url, scheme, allow_fragments) - v = SplitResult(scheme or '', netloc or '', url, query or '', fragment or '') - return _coerce_result(v) + if not missing_as_none: + if scheme is None: scheme = '' + if netloc is None: netloc = '' + if query is None: query = '' + if fragment is None: fragment = '' + result = SplitResult(scheme, netloc, url, query, fragment) + result = _coerce_result(result) + result._keep_empty = missing_as_none + return result def _urlsplit(url, scheme=None, allow_fragments=True): # Only lstrip url as some applications rely on preserving trailing space. @@ -532,38 +624,61 @@ def _urlsplit(url, scheme=None, allow_fragments=True): _checknetloc(netloc) return (scheme, netloc, url, query, fragment) -def urlunparse(components): +def urlunparse(components, *, keep_empty=_UNSPECIFIED): """Put a parsed URL back together again. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had redundant delimiters, e.g. a ? with an empty query - (the draft states that these are equivalent).""" + (the draft states that these are equivalent) and keep_empty is false + or components is the result of the urlparse() call with + missing_as_none=False.""" scheme, netloc, url, params, query, fragment, _coerce_result = ( _coerce_args(*components)) - if not netloc: - if scheme and scheme in uses_netloc and (not url or url[:1] == '/'): - netloc = '' - else: - netloc = None - if params: + if keep_empty is _UNSPECIFIED: + keep_empty = getattr(components, '_keep_empty', _MISSING_AS_NONE_DEFAULT) + elif keep_empty and not getattr(components, '_keep_empty', True): + raise ValueError('Cannot distinguish between empty and not defined ' + 'URI components in the result of parsing URL with ' + 'missing_as_none=False') + if not keep_empty: + if not netloc: + if scheme and scheme in uses_netloc and (not url or url[:1] == '/'): + netloc = '' + else: + netloc = None + if not scheme: scheme = None + if not params: params = None + if not query: query = None + if not fragment: fragment = None + if params is not None: url = "%s;%s" % (url, params) - return _coerce_result(_urlunsplit(scheme or None, netloc, url, - query or None, fragment or None)) + return _coerce_result(_urlunsplit(scheme, netloc, url, query, fragment)) -def urlunsplit(components): +def urlunsplit(components, *, keep_empty=_UNSPECIFIED): """Combine the elements of a tuple as returned by urlsplit() into a complete URL as a string. The data argument can be any five-item iterable. This may result in a slightly different, but equivalent URL, if the URL that was parsed originally had unnecessary delimiters (for example, a ? with an - empty query; the RFC states that these are equivalent).""" + empty query; the RFC states that these are equivalent) and keep_empty + is false or components is the result of the urlsplit() call with + missing_as_none=False.""" scheme, netloc, url, query, fragment, _coerce_result = ( _coerce_args(*components)) - if not netloc: - if scheme and scheme in uses_netloc and (not url or url[:1] == '/'): - netloc = '' - else: - netloc = None - return _coerce_result(_urlunsplit(scheme or None, netloc, url, - query or None, fragment or None)) + if keep_empty is _UNSPECIFIED: + keep_empty = getattr(components, '_keep_empty', _MISSING_AS_NONE_DEFAULT) + elif keep_empty and not getattr(components, '_keep_empty', True): + raise ValueError('Cannot distinguish between empty and not defined ' + 'URI components in the result of parsing URL with ' + 'missing_as_none=False') + if not keep_empty: + if not netloc: + if scheme and scheme in uses_netloc and (not url or url[:1] == '/'): + netloc = '' + else: + netloc = None + if not scheme: scheme = None + if not query: query = None + if not fragment: fragment = None + return _coerce_result(_urlunsplit(scheme, netloc, url, query, fragment)) def _urlunsplit(scheme, netloc, url, query, fragment): if netloc is not None: @@ -651,21 +766,24 @@ def urljoin(base, url, allow_fragments=True): resolved_path) or '/', query, fragment)) -def urldefrag(url): +def urldefrag(url, *, missing_as_none=_MISSING_AS_NONE_DEFAULT): """Removes any existing fragment from URL. Returns a tuple of the defragmented URL and the fragment. If the URL contained no fragments, the second element is the - empty string. + empty string or None if missing_as_none is True. """ url, _coerce_result = _coerce_args(url) if '#' in url: s, n, p, q, frag = _urlsplit(url) defrag = _urlunsplit(s, n, p, q, None) else: - frag = '' + frag = None defrag = url - return _coerce_result(DefragResult(defrag, frag or '')) + if not missing_as_none and frag is None: frag = '' + result = _coerce_result(DefragResult(defrag, frag)) + result._keep_empty = missing_as_none + return result _hexdig = '0123456789ABCDEFabcdef' _hextobyte = None @@ -1066,7 +1184,7 @@ def urlencode(query, doseq=False, safe='', encoding=None, errors=None, else: try: # Is this a sufficient test for sequence-ness? - x = len(v) + len(v) except TypeError: # not a sequence v = quote_via(str(v), safe, encoding, errors) @@ -1117,7 +1235,7 @@ def unwrap(url): def splittype(url): warnings.warn("urllib.parse.splittype() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splittype(url) @@ -1138,7 +1256,7 @@ def _splittype(url): def splithost(url): warnings.warn("urllib.parse.splithost() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splithost(url) @@ -1161,7 +1279,7 @@ def _splithost(url): def splituser(host): warnings.warn("urllib.parse.splituser() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splituser(host) @@ -1174,7 +1292,7 @@ def _splituser(host): def splitpasswd(user): warnings.warn("urllib.parse.splitpasswd() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splitpasswd(user) @@ -1187,7 +1305,7 @@ def _splitpasswd(user): def splitport(host): warnings.warn("urllib.parse.splitport() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splitport(host) @@ -1210,7 +1328,7 @@ def _splitport(host): def splitnport(host, defport=-1): warnings.warn("urllib.parse.splitnport() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splitnport(host, defport) @@ -1234,7 +1352,7 @@ def _splitnport(host, defport=-1): def splitquery(url): warnings.warn("urllib.parse.splitquery() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splitquery(url) @@ -1249,7 +1367,7 @@ def _splitquery(url): def splittag(url): warnings.warn("urllib.parse.splittag() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splittag(url) @@ -1264,7 +1382,7 @@ def _splittag(url): def splitattr(url): warnings.warn("urllib.parse.splitattr() is deprecated as of 3.8, " - "use urllib.parse.urlparse() instead", + "use urllib.parse.urlsplit() instead", DeprecationWarning, stacklevel=2) return _splitattr(url) diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index a8f40100b7b..9fa92659a25 100644 --- a/Lib/urllib/request.py +++ b/Lib/urllib/request.py @@ -415,6 +415,8 @@ def add_handler(self, handler): continue i = meth.find("_") + if i < 1: + continue protocol = meth[:i] condition = meth[i+1:] @@ -813,16 +815,17 @@ def add_password(self, realm, uri, user, passwd): self.passwd[realm] = {} for default_port in True, False: reduced_uri = tuple( - self.reduce_uri(u, default_port) for u in uri) + self._reduce_uri_with_scheme(u, default_port) for u in uri) self.passwd[realm][reduced_uri] = (user, passwd) def find_user_password(self, realm, authuri): domains = self.passwd.get(realm, {}) for default_port in True, False: - reduced_authuri = self.reduce_uri(authuri, default_port) + reduced_authuri = self._reduce_uri_with_scheme( + authuri, default_port) for uris, authinfo in domains.items(): for uri in uris: - if self.is_suburi(uri, reduced_authuri): + if self._is_suburi_with_scheme(uri, reduced_authuri): return authinfo return None, None @@ -849,6 +852,17 @@ def reduce_uri(self, uri, default_port=True): authority = "%s:%d" % (host, dport) return authority, path + def _reduce_uri_with_scheme(self, uri, default_port=True): + parts = urlsplit(uri) + scheme = parts[0] if parts[1] else None + return (scheme or None, *self.reduce_uri(uri, default_port)) + + def _is_suburi_with_scheme(self, base, test): + if (base[0] is not None and test[0] is not None and + base[0] != test[0]): + return False + return self.is_suburi(base[1:], test[1:]) + def is_suburi(self, base, test): """Check if test is below base in a URI tree @@ -894,14 +908,15 @@ def update_authenticated(self, uri, is_authenticated=False): for default_port in True, False: for u in uri: - reduced_uri = self.reduce_uri(u, default_port) + reduced_uri = self._reduce_uri_with_scheme(u, default_port) self.authenticated[reduced_uri] = is_authenticated def is_authenticated(self, authuri): for default_port in True, False: - reduced_authuri = self.reduce_uri(authuri, default_port) + reduced_authuri = self._reduce_uri_with_scheme( + authuri, default_port) for uri in self.authenticated: - if self.is_suburi(uri, reduced_authuri): + if self._is_suburi_with_scheme(uri, reduced_authuri): return self.authenticated[uri] diff --git a/Lib/uuid.py b/Lib/uuid.py index 043ad7bcbde..3f10fed81c1 100644 --- a/Lib/uuid.py +++ b/Lib/uuid.py @@ -43,7 +43,7 @@ >>> x.bytes b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' - # make a UUID from a 16-byte string + # make a UUID from a 16-byte bytes object >>> uuid.UUID(bytes=x.bytes) UUID('00010203-0405-0607-0809-0a0b0c0d0e0f') @@ -118,19 +118,19 @@ class UUID: '12345678-1234-1234-1234-123456789abc'. The UUID constructor accepts five possible forms: a similar string of hexadecimal digits, or a tuple of six integer fields (with 32-bit, 16-bit, 16-bit, 8-bit, 8-bit, and - 48-bit values respectively) as an argument named 'fields', or a string - of 16 bytes (with all the integer fields in big-endian order) as an - argument named 'bytes', or a string of 16 bytes (with the first three - fields in little-endian order) as an argument named 'bytes_le', or a - single 128-bit integer as an argument named 'int'. + 48-bit values respectively) as an argument named 'fields', or a 16-byte + bytes object (with all the integer fields in big-endian order) as an + argument named 'bytes', or a 16-byte bytes object (with the first three + fields in little-endian order) as an argument named 'bytes_le', or a single + 128-bit integer as an argument named 'int'. UUIDs have these read-only attributes: - bytes the UUID as a 16-byte string (containing the six + bytes the UUID as a 16-byte bytes object (containing the six integer fields in big-endian byte order) - bytes_le the UUID as a 16-byte string (with time_low, time_mid, - and time_hi_version in little-endian byte order) + bytes_le the UUID as a 16-byte bytes object (with time_low, + time_mid, and time_hi_version in little-endian byte order) fields a tuple of the six integer fields of the UUID, which are also available as six individual attributes @@ -179,7 +179,7 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, int=None, version=None, *, is_safe=SafeUUID.unknown): r"""Create a UUID from either a string of 32 hexadecimal digits, - a string of 16 bytes as the 'bytes' argument, a string of 16 bytes + a 16-byte bytes object as the 'bytes' argument, a 16-byte bytes object in little-endian order as the 'bytes_le' argument, a tuple of six integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version, 8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as @@ -191,9 +191,9 @@ def __init__(self, hex=None, bytes=None, bytes_le=None, fields=None, UUID('{12345678-1234-5678-1234-567812345678}') UUID('12345678123456781234567812345678') UUID('urn:uuid:12345678-1234-5678-1234-567812345678') - UUID(bytes='\x12\x34\x56\x78'*4) - UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' + - '\x12\x34\x56\x78\x12\x34\x56\x78') + UUID(bytes=b'\x12\x34\x56\x78'*4) + UUID(bytes_le=b'\x78\x56\x34\x12\x34\x12\x78\x56' + + b'\x12\x34\x56\x78\x12\x34\x56\x78') UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678)) UUID(int=0x12345678123456781234567812345678) @@ -737,6 +737,7 @@ def uuid1(node=None, clock_seq=None): is_safe = SafeUUID(safely_generated) except ValueError: is_safe = SafeUUID.unknown + # The version field is assumed to be handled by _generate_time_safe(). return UUID(bytes=uuid_time, is_safe=is_safe) global _last_timestamp @@ -954,7 +955,6 @@ def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description="Generate a UUID using the selected UUID function.", - color=True, ) parser.add_argument("-u", "--uuid", choices=uuid_funcs.keys(), @@ -962,14 +962,14 @@ def main(): help="function to generate the UUID") parser.add_argument("-n", "--namespace", metavar=f"{{any UUID,{','.join(namespaces)}}}", - help="uuid3/uuid5 only: " + help="`uuid3`/`uuid5` only: " "a UUID, or a well-known predefined UUID addressed " "by namespace name") parser.add_argument("-N", "--name", - help="uuid3/uuid5 only: " + help="`uuid3`/`uuid5` only: " "name used as part of generating the UUID") parser.add_argument("-C", "--count", metavar="NUM", type=int, default=1, - help="generate NUM fresh UUIDs") + help="generate `NUM` fresh UUIDs") args = parser.parse_args() uuid_func = uuid_funcs[args.uuid] diff --git a/Lib/venv/__init__.py b/Lib/venv/__init__.py index 88f3340af41..0653a43a8b1 100644 --- a/Lib/venv/__init__.py +++ b/Lib/venv/__init__.py @@ -174,6 +174,7 @@ def create_if_needed(d): context.python_exe = exename binpath = self._venv_path(env_dir, 'scripts') libpath = self._venv_path(env_dir, 'purelib') + platlibpath = self._venv_path(env_dir, 'platlib') # PEP 405 says venvs should create a local include directory. # See https://peps.python.org/pep-0405/#include-files @@ -191,12 +192,8 @@ def create_if_needed(d): create_if_needed(incpath) context.lib_path = libpath create_if_needed(libpath) - # Issue 21197: create lib64 as a symlink to lib on 64-bit non-OS X POSIX - if ((sys.maxsize > 2**32) and (os.name == 'posix') and - (sys.platform != 'darwin')): - link_path = os.path.join(env_dir, 'lib64') - if not os.path.exists(link_path): # Issue #21643 - os.symlink('lib', link_path) + context.platlib_path = platlibpath + create_if_needed(platlibpath) context.bin_path = binpath context.bin_name = os.path.relpath(binpath, env_dir) context.env_exe = os.path.join(binpath, exename) @@ -309,15 +306,11 @@ def setup_python(self, context): binpath = context.bin_path path = context.env_exe copier = self.symlink_or_copy - dirname = context.python_dir copier(context.executable, path) if not os.path.islink(path): os.chmod(path, 0o755) - - suffixes = ['python', 'python3', f'python3.{sys.version_info[1]}'] - if sys.version_info[:2] == (3, 14) and sys.getfilesystemencoding() == 'utf-8': - suffixes.append('𝜋thon') - for suffix in suffixes: + for suffix in ('python', 'python3', + f'python3.{sys.version_info[1]}'): path = os.path.join(binpath, suffix) if not os.path.exists(path): # Issue 18807: make copies if @@ -365,6 +358,9 @@ def setup_python(self, context): exe_t = f'3.{sys.version_info[1]}t' python_exe = os.path.join(dirname, f'python{exe_t}{exe_d}.exe') pythonw_exe = os.path.join(dirname, f'pythonw{exe_t}{exe_d}.exe') + if not os.path.isfile(python_exe): + python_exe = os.path.join(dirname, f'python{exe_d}.exe') + pythonw_exe = os.path.join(dirname, f'pythonw{exe_d}.exe') link_sources = { 'python.exe': python_exe, f'python{exe_d}.exe': python_exe, @@ -625,7 +621,6 @@ def main(args=None): 'activate it, e.g. by ' 'sourcing an activate script ' 'in its bin directory.', - color=True, ) parser.add_argument('dirs', metavar='ENV_DIR', nargs='+', help='A directory to create the environment in.') diff --git a/Lib/venv/scripts/nt/activate.bat b/Lib/venv/scripts/nt/activate.bat index 9ac5c20b477..90c2ad06a89 100644 --- a/Lib/venv/scripts/nt/activate.bat +++ b/Lib/venv/scripts/nt/activate.bat @@ -1,34 +1,32 @@ -@echo off - -rem This file is UTF-8 encoded, so we need to update the current code page while executing it -for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do ( - set _OLD_CODEPAGE=%%a +@rem This file is UTF-8 encoded, so we need to update the current code page while executing it +@for /f "tokens=2 delims=:." %%a in ('"%SystemRoot%\System32\chcp.com"') do @( + @set _OLD_CODEPAGE=%%a ) -if defined _OLD_CODEPAGE ( - "%SystemRoot%\System32\chcp.com" 65001 > nul +@if defined _OLD_CODEPAGE ( + @"%SystemRoot%\System32\chcp.com" 65001 > nul ) -set "VIRTUAL_ENV=__VENV_DIR__" +@set "VIRTUAL_ENV=__VENV_DIR__" -if not defined PROMPT set PROMPT=$P$G +@if not defined PROMPT @set PROMPT=$P$G -if defined _OLD_VIRTUAL_PROMPT set PROMPT=%_OLD_VIRTUAL_PROMPT% -if defined _OLD_VIRTUAL_PYTHONHOME set PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME% +@if defined _OLD_VIRTUAL_PROMPT @set PROMPT=%_OLD_VIRTUAL_PROMPT% +@if defined _OLD_VIRTUAL_PYTHONHOME @set PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME% -set "_OLD_VIRTUAL_PROMPT=%PROMPT%" -set "PROMPT=(__VENV_PROMPT__) %PROMPT%" +@if not defined VIRTUAL_ENV_DISABLE_PROMPT @set "_OLD_VIRTUAL_PROMPT=%PROMPT%" +@if not defined VIRTUAL_ENV_DISABLE_PROMPT @set "PROMPT=(__VENV_PROMPT__) %PROMPT%" -if defined PYTHONHOME set _OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME% -set PYTHONHOME= +@if defined PYTHONHOME @set _OLD_VIRTUAL_PYTHONHOME=%PYTHONHOME% +@set PYTHONHOME= -if defined _OLD_VIRTUAL_PATH set PATH=%_OLD_VIRTUAL_PATH% -if not defined _OLD_VIRTUAL_PATH set _OLD_VIRTUAL_PATH=%PATH% +@if defined _OLD_VIRTUAL_PATH @set PATH=%_OLD_VIRTUAL_PATH% +@if not defined _OLD_VIRTUAL_PATH @set _OLD_VIRTUAL_PATH=%PATH% -set "PATH=%VIRTUAL_ENV%\__VENV_BIN_NAME__;%PATH%" -set "VIRTUAL_ENV_PROMPT=__VENV_PROMPT__" +@set "PATH=%VIRTUAL_ENV%\__VENV_BIN_NAME__;%PATH%" +@set "VIRTUAL_ENV_PROMPT=__VENV_PROMPT__" :END -if defined _OLD_CODEPAGE ( - "%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul - set _OLD_CODEPAGE= +@if defined _OLD_CODEPAGE ( + @"%SystemRoot%\System32\chcp.com" %_OLD_CODEPAGE% > nul + @set _OLD_CODEPAGE= ) diff --git a/Lib/venv/scripts/nt/deactivate.bat b/Lib/venv/scripts/nt/deactivate.bat index 44dae495370..8f1650b6bf7 100644 --- a/Lib/venv/scripts/nt/deactivate.bat +++ b/Lib/venv/scripts/nt/deactivate.bat @@ -1,22 +1,20 @@ -@echo off - -if defined _OLD_VIRTUAL_PROMPT ( - set "PROMPT=%_OLD_VIRTUAL_PROMPT%" +@if defined _OLD_VIRTUAL_PROMPT ( + @set "PROMPT=%_OLD_VIRTUAL_PROMPT%" ) -set _OLD_VIRTUAL_PROMPT= +@set _OLD_VIRTUAL_PROMPT= -if defined _OLD_VIRTUAL_PYTHONHOME ( - set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%" - set _OLD_VIRTUAL_PYTHONHOME= +@if defined _OLD_VIRTUAL_PYTHONHOME ( + @set "PYTHONHOME=%_OLD_VIRTUAL_PYTHONHOME%" + @set _OLD_VIRTUAL_PYTHONHOME= ) -if defined _OLD_VIRTUAL_PATH ( - set "PATH=%_OLD_VIRTUAL_PATH%" +@if defined _OLD_VIRTUAL_PATH ( + @set "PATH=%_OLD_VIRTUAL_PATH%" ) -set _OLD_VIRTUAL_PATH= +@set _OLD_VIRTUAL_PATH= -set VIRTUAL_ENV= -set VIRTUAL_ENV_PROMPT= +@set VIRTUAL_ENV= +@set VIRTUAL_ENV_PROMPT= :END diff --git a/Lib/venv/scripts/posix/activate.csh b/Lib/venv/scripts/posix/activate.csh index 2a3fa835476..7226034df0f 100644 --- a/Lib/venv/scripts/posix/activate.csh +++ b/Lib/venv/scripts/posix/activate.csh @@ -16,10 +16,12 @@ setenv PATH "$VIRTUAL_ENV/"__VENV_BIN_NAME__":$PATH" setenv VIRTUAL_ENV_PROMPT __VENV_PROMPT__ -set _OLD_VIRTUAL_PROMPT="$prompt" +if ($?prompt) then + set _OLD_VIRTUAL_PROMPT="$prompt" -if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then - set prompt = "("__VENV_PROMPT__") $prompt:q" + if (! "$?VIRTUAL_ENV_DISABLE_PROMPT") then + set prompt = "("__VENV_PROMPT__") $prompt:q" + endif endif alias pydoc python -m pydoc diff --git a/Lib/wave.py b/Lib/wave.py index b8476e26486..c4e1a493a7e 100644 --- a/Lib/wave.py +++ b/Lib/wave.py @@ -15,15 +15,13 @@ getsampwidth() -- returns sample width in bytes getframerate() -- returns sampling frequency getnframes() -- returns number of audio frames + getformat() -- returns frame encoding (WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT + or WAVE_FORMAT_EXTENSIBLE) getcomptype() -- returns compression type ('NONE' for linear samples) getcompname() -- returns human-readable version of compression type ('not compressed' linear samples) getparams() -- returns a namedtuple consisting of all of the above in the above order - getmarkers() -- returns None (for compatibility with the - old aifc module) - getmark(id) -- raises an error since the mark does not - exist (for compatibility with the old aifc module) readframes(n) -- returns at most n frames of audio rewind() -- rewind to the beginning of the audio stream setpos(pos) -- seek to the specified position @@ -46,6 +44,9 @@ setsampwidth(n) -- set the sample width setframerate(n) -- set the frame rate setnframes(n) -- set the number of frames + setformat(format) + -- set the frame format. Only WAVE_FORMAT_PCM and + WAVE_FORMAT_IEEE_FLOAT are supported. setcomptype(type, name) -- set the compression type and the human-readable compression type @@ -73,16 +74,26 @@ from collections import namedtuple import builtins +import os import struct import sys -__all__ = ["open", "Error", "Wave_read", "Wave_write"] +__all__ = [ + "open", + "Error", + "Wave_read", + "Wave_write", + "WAVE_FORMAT_PCM", + "WAVE_FORMAT_IEEE_FLOAT", + "WAVE_FORMAT_EXTENSIBLE", +] class Error(Exception): pass WAVE_FORMAT_PCM = 0x0001 +WAVE_FORMAT_IEEE_FLOAT = 0x0003 WAVE_FORMAT_EXTENSIBLE = 0xFFFE # Derived from uuid.UUID("00000001-0000-0010-8000-00aa00389b71").bytes_le KSDATAFORMAT_SUBTYPE_PCM = b'\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x008\x9bq' @@ -100,7 +111,7 @@ def _byteswap(data, width): for j in range(width): swapped_data[i + width - 1 - j] = data[i + j] - return bytes(swapped_data) + return swapped_data.take_bytes() class _Chunk: @@ -229,6 +240,10 @@ class Wave_read: available through the getsampwidth() method _framerate -- the sampling frequency available through the getframerate() method + _format -- frame format + One of WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT + or WAVE_FORMAT_EXTENSIBLE available through + getformat() method _comptype -- the AIFF-C compression type ('NONE' if AIFF) available through the getcomptype() method _compname -- the human-readable AIFF-C compression type @@ -278,7 +293,7 @@ def initfp(self, file): def __init__(self, f): self._i_opened_the_file = None - if isinstance(f, str): + if isinstance(f, (bytes, str, os.PathLike)): f = builtins.open(f, 'rb') self._i_opened_the_file = f # else, assume it is an open file object already @@ -330,6 +345,9 @@ def getsampwidth(self): def getframerate(self): return self._framerate + def getformat(self): + return self._format + def getcomptype(self): return self._comptype @@ -341,16 +359,6 @@ def getparams(self): self.getframerate(), self.getnframes(), self.getcomptype(), self.getcompname()) - def getmarkers(self): - import warnings - warnings._deprecated("Wave_read.getmarkers", remove=(3, 15)) - return None - - def getmark(self, id): - import warnings - warnings._deprecated("Wave_read.getmark", remove=(3, 15)) - raise Error('no marks') - def setpos(self, pos): if pos < 0 or pos > self._nframes: raise Error('position not in range') @@ -380,16 +388,16 @@ def readframes(self, nframes): def _read_fmt_chunk(self, chunk): try: - wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from(' 4: + if self._format == WAVE_FORMAT_IEEE_FLOAT: + if sampwidth not in (4, 8): + raise Error('unsupported sample width for IEEE float format') + elif sampwidth < 1 or sampwidth > 4: raise Error('bad sample width') self._sampwidth = sampwidth @@ -506,9 +521,10 @@ def getsampwidth(self): def setframerate(self, framerate): if self._datawritten: raise Error('cannot change parameters after starting to write') + framerate = int(round(framerate)) if framerate <= 0: raise Error('bad frame rate') - self._framerate = int(round(framerate)) + self._framerate = framerate def getframerate(self): if not self._framerate: @@ -531,6 +547,18 @@ def setcomptype(self, comptype, compname): self._comptype = comptype self._compname = compname + def setformat(self, format): + if self._datawritten: + raise Error('cannot change parameters after starting to write') + if format not in (WAVE_FORMAT_IEEE_FLOAT, WAVE_FORMAT_PCM): + raise Error('unsupported wave format') + if format == WAVE_FORMAT_IEEE_FLOAT and self._sampwidth and self._sampwidth not in (4, 8): + raise Error('unsupported sample width for IEEE float format') + self._format = format + + def getformat(self): + return self._format + def getcomptype(self): return self._comptype @@ -538,10 +566,15 @@ def getcompname(self): return self._compname def setparams(self, params): - nchannels, sampwidth, framerate, nframes, comptype, compname = params if self._datawritten: raise Error('cannot change parameters after starting to write') + if len(params) == 6: + nchannels, sampwidth, framerate, nframes, comptype, compname = params + format = WAVE_FORMAT_PCM + else: + nchannels, sampwidth, framerate, nframes, comptype, compname, format = params self.setnchannels(nchannels) + self.setformat(format) self.setsampwidth(sampwidth) self.setframerate(framerate) self.setnframes(nframes) @@ -553,21 +586,6 @@ def getparams(self): return _wave_params(self._nchannels, self._sampwidth, self._framerate, self._nframes, self._comptype, self._compname) - def setmark(self, id, pos, name): - import warnings - warnings._deprecated("Wave_write.setmark", remove=(3, 15)) - raise Error('setmark() not supported') - - def getmark(self, id): - import warnings - warnings._deprecated("Wave_write.getmark", remove=(3, 15)) - raise Error('no marks') - - def getmarkers(self): - import warnings - warnings._deprecated("Wave_write.getmarkers", remove=(3, 15)) - return None - def tell(self): return self._nframeswritten @@ -593,6 +611,8 @@ def close(self): try: if self._file: self._ensure_header_written(0) + if self._datawritten & 1: + self._file.write(b'\x00') if self._datalength != self._datawritten: self._patchheader() self._file.flush() @@ -617,6 +637,9 @@ def _ensure_header_written(self, datasize): raise Error('sampling rate not specified') self._write_header(datasize) + def _needs_fact_chunk(self): + return self._format == WAVE_FORMAT_IEEE_FLOAT + def _write_header(self, initlength): assert not self._headerwritten self._file.write(b'RIFF') @@ -627,12 +650,23 @@ def _write_header(self, initlength): self._form_length_pos = self._file.tell() except (AttributeError, OSError): self._form_length_pos = None - self._file.write(struct.pack(' is used so that the URL is always passed + to a browser application rather than dispatched by the OS file handler. + This prevents file injection attacks where a file:// URL pointing to an + executable bundle could otherwise be launched by the OS. + + Named browsers with known bundle IDs use -b; unknown names fall back + to -a. + """ + + _BUNDLE_IDS = { + 'google chrome': 'com.google.Chrome', + 'firefox': 'org.mozilla.firefox', + 'safari': 'com.apple.Safari', + 'chromium': 'org.chromium.Chromium', + 'opera': 'com.operasoftware.Opera', + 'microsoft edge': 'com.microsoft.edgemac', + 'brave browser': 'com.brave.Browser', + } + + def open(self, url, new=0, autoraise=True): + sys.audit("webbrowser.open", url) + self._check_url(url) + if self.name == 'default': + proto, sep, _ = url.partition(':') + if sep and proto.lower() in {'http', 'https'}: + cmd = ['/usr/bin/open', url] + else: + bundle_id = _macos_default_browser_bundle_id() + cmd = ['/usr/bin/open', '-b', bundle_id, url] + else: + bundle_id = self._BUNDLE_IDS.get(self.name.lower()) + if bundle_id: + cmd = ['/usr/bin/open', '-b', bundle_id, url] + else: + cmd = ['/usr/bin/open', '-a', self.name, url] + proc = subprocess.run(cmd, stderr=subprocess.DEVNULL) + return proc.returncode == 0 + class MacOSXOSAScript(BaseBrowser): def __init__(self, name='default'): + import warnings + warnings._deprecated("webbrowser.MacOSXOSAScript", remove=(3, 17)) super().__init__(name) def open(self, url, new=0, autoraise=True): @@ -734,7 +812,7 @@ def open(self, url, new=0, autoraise=True): def parse_args(arg_list: list[str] | None): import argparse parser = argparse.ArgumentParser( - description="Open URL in a web browser.", color=True, + description="Open URL in a web browser.", ) parser.add_argument("url", help="URL to open") diff --git a/Lib/wsgiref/handlers.py b/Lib/wsgiref/handlers.py index f8fe89f6e13..b82862deea7 100644 --- a/Lib/wsgiref/handlers.py +++ b/Lib/wsgiref/handlers.py @@ -69,7 +69,8 @@ def read_environ(): # Python 3's http.server.CGIHTTPRequestHandler decodes # using the urllib.unquote default of UTF-8, amongst other - # issues. + # issues. While the CGI handler is removed in 3.15, this + # is kept for legacy reasons. elif ( software.startswith('simplehttp/') and 'python/3' in software diff --git a/Lib/wsgiref/simple_server.py b/Lib/wsgiref/simple_server.py index a0f2397fcf0..31efd8c9bae 100644 --- a/Lib/wsgiref/simple_server.py +++ b/Lib/wsgiref/simple_server.py @@ -16,11 +16,10 @@ from wsgiref.handlers import SimpleHandler from platform import python_implementation -__version__ = "0.2" __all__ = ['WSGIServer', 'WSGIRequestHandler', 'demo_app', 'make_server'] -server_version = "WSGIServer/" + __version__ +server_version = "WSGIServer" sys_version = python_implementation() + "/" + sys.version.split()[0] software_version = server_version + ' ' + sys_version @@ -70,7 +69,7 @@ def set_app(self,application): class WSGIRequestHandler(BaseHTTPRequestHandler): - server_version = "WSGIServer/" + __version__ + server_version = "WSGIServer" def get_environ(self): env = self.server.base_environ.copy() @@ -152,6 +151,15 @@ def make_server( return server +def __getattr__(name): + if name == "__version__": + from warnings import _deprecated + + _deprecated("__version__", remove=(3, 20)) + return "0.2" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + if __name__ == '__main__': with make_server('', 8000, demo_app) as httpd: sa = httpd.socket.getsockname() diff --git a/Lib/xml/__init__.py b/Lib/xml/__init__.py index bf6d8ddfd04..ecfce1c6ae5 100644 --- a/Lib/xml/__init__.py +++ b/Lib/xml/__init__.py @@ -16,5 +16,6 @@ """ +from .utils import * -__all__ = ["dom", "parsers", "sax", "etree"] +__all__ = ["dom", "parsers", "sax", "etree", "is_valid_name", "is_valid_text"] diff --git a/Lib/xml/dom/expatbuilder.py b/Lib/xml/dom/expatbuilder.py index 7dd667bf3fb..346f83dd7db 100644 --- a/Lib/xml/dom/expatbuilder.py +++ b/Lib/xml/dom/expatbuilder.py @@ -30,7 +30,8 @@ from xml.dom import xmlbuilder, minidom, Node from xml.dom import EMPTY_NAMESPACE, EMPTY_PREFIX, XMLNS_NAMESPACE from xml.parsers import expat -from xml.dom.minidom import _append_child, _set_attribute_node +from xml.dom.minidom import (_append_child, _set_attribute_node, + _XML_WHITESPACE) from xml.dom.NodeFilter import NodeFilter TEXT_NODE = Node.TEXT_NODE @@ -412,7 +413,8 @@ def _handle_white_text_nodes(self, node, info): # whitespace. L = [] for child in node.childNodes: - if child.nodeType == TEXT_NODE and not child.data.strip(): + if (child.nodeType == TEXT_NODE + and not child.data.strip(_XML_WHITESPACE)): L.append(child) # Remove ignorable whitespace from the tree. diff --git a/Lib/xml/dom/minidom.py b/Lib/xml/dom/minidom.py index 16b33b90184..6762853e91a 100644 --- a/Lib/xml/dom/minidom.py +++ b/Lib/xml/dom/minidom.py @@ -30,6 +30,9 @@ _nodeTypes_with_children = (xml.dom.Node.ELEMENT_NODE, xml.dom.Node.ENTITY_REFERENCE_NODE) +# The white space characters of the XML specification (see XML 1.0, 2.3). +_XML_WHITESPACE = " \t\r\n" + class Node(xml.dom.Node): namespaceURI = None # this is non-null only for elements and attributes @@ -1174,7 +1177,7 @@ def replaceWholeText(self, content): return None def _get_isWhitespaceInElementContent(self): - if self.data.strip(): + if self.data.strip(_XML_WHITESPACE): return False elem = _get_containing_element(self) if elem is None: diff --git a/Lib/xml/dom/pulldom.py b/Lib/xml/dom/pulldom.py index 913141cd7ef..9d33d83458e 100644 --- a/Lib/xml/dom/pulldom.py +++ b/Lib/xml/dom/pulldom.py @@ -1,3 +1,5 @@ +"""Support for building partial DOM trees from SAX events.""" + import xml.sax import xml.sax.handler @@ -11,6 +13,10 @@ CHARACTERS = "CHARACTERS" class PullDOM(xml.sax.ContentHandler): + """Content handler which turns SAX events into pull parser events. + + The nodes are created, but they are not added to the tree.""" + _locator = None document = None @@ -202,6 +208,8 @@ def fatalError(self, exception): raise exception class DOMEventStream: + """Stream of the pull parser events.""" + def __init__(self, stream, parser, bufsize): self.stream = stream self.parser = parser @@ -211,6 +219,7 @@ def __init__(self, stream, parser, bufsize): self.reset() def reset(self): + """Discard unread events and prepare for parsing a new document.""" self.pulldom = PullDOM() # This content handler relies on namespace support self.parser.setFeature(xml.sax.handler.feature_namespaces, 1) @@ -226,6 +235,7 @@ def __iter__(self): return self def expandNode(self, node): + """Expand all children of the node into the node.""" event = self.getEvent() parents = [node] while event: @@ -241,6 +251,7 @@ def expandNode(self, node): event = self.getEvent() def getEvent(self): + """Return the next (event, node) tuple, or None at the end.""" # use IncrementalParser interface, so we get the desired # pull effect if not self.pulldom.firstEvent[1]: @@ -274,13 +285,14 @@ def _emit(self): return rc def clear(self): - """clear(): Explicitly release parsing objects""" + """Release the parser and the document.""" self.pulldom.clear() del self.pulldom self.parser = None self.stream = None class SAX2DOM(PullDOM): + """PullDOM which also adds every created node to the tree.""" def startElementNS(self, name, tagName , attrs): PullDOM.startElementNS(self, name, tagName, attrs) @@ -316,6 +328,7 @@ def characters(self, chars): default_bufsize = (2 ** 14) - 20 def parse(stream_or_string, parser=None, bufsize=None): + """Return a DOMEventStream for the given file name or file object.""" if bufsize is None: bufsize = default_bufsize if isinstance(stream_or_string, str): @@ -327,6 +340,7 @@ def parse(stream_or_string, parser=None, bufsize=None): return DOMEventStream(stream, parser, bufsize) def parseString(string, parser=None): + """Return a DOMEventStream for the given string.""" from io import StringIO bufsize = len(string) diff --git a/Lib/xml/etree/ElementPath.py b/Lib/xml/etree/ElementPath.py index dc6bd28c031..de1fd203ff6 100644 --- a/Lib/xml/etree/ElementPath.py +++ b/Lib/xml/etree/ElementPath.py @@ -324,15 +324,22 @@ def select_negated(context, result): index = -1 def select(context, result): parent_map = get_parent_map(context) + cache = {} for elem in result: try: parent = parent_map[elem] + except KeyError: + continue + key = (parent, elem.tag) + if key not in cache: # FIXME: what if the selector is "*" ? - elems = list(parent.findall(elem.tag)) - if elems[index] is elem: - yield elem - except (IndexError, KeyError): - pass + elems = parent.findall(elem.tag) + try: + cache[key] = elems[index] + except IndexError: + cache[key] = None + if cache[key] is elem: + yield elem return select raise SyntaxError("invalid predicate") diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py index 0a4203d372c..c5235feb2fa 100644 --- a/Lib/xml/etree/ElementTree.py +++ b/Lib/xml/etree/ElementTree.py @@ -83,15 +83,12 @@ "SubElement", "tostring", "tostringlist", "TreeBuilder", - "VERSION", "XML", "XMLID", "XMLParser", "XMLPullParser", "register_namespace", "canonicalize", "C14NWriterTarget", ] -VERSION = "1.3.0" - import sys import re import warnings @@ -104,6 +101,9 @@ from . import ElementPath +# The white space characters of the XML specification (see XML 1.0, 2.3). +_XML_WHITESPACE = " \t\r\n" + class ParseError(SyntaxError): """An error when parsing an XML document. @@ -132,9 +132,6 @@ class Element: want to check if an element is truly empty, you should check BOTH its length AND its text attribute. - The element tag, attribute names, and attribute values can be either - bytes or strings. - *tag* is the element name. *attrib* is an optional dictionary containing element attributes. *extra* are additional element attributes given as keyword arguments. @@ -167,9 +164,9 @@ class Element: """ - def __init__(self, tag, attrib={}, **extra): - if not isinstance(attrib, dict): - raise TypeError("attrib must be dict, not %s" % ( + def __init__(self, tag, /, attrib={}, **extra): + if not isinstance(attrib, (dict, frozendict)): + raise TypeError("attrib must be dict or frozendict, not %s" % ( attrib.__class__.__name__,)) self.tag = tag self.attrib = {**attrib, **extra} @@ -266,12 +263,15 @@ def remove(self, subelement): ValueError is raised if a matching element could not be found. """ - # assert iselement(element) try: self._children.remove(subelement) except ValueError: + # to align the error type with the C implementation + if isinstance(subelement, type) or not iselement(subelement): + raise TypeError('expected an Element, not %s' % + type(subelement).__name__) from None # to align the error message with the C implementation - raise ValueError("Element.remove(x): element not found") from None + raise ValueError(f"{subelement!r} not in {self!r}") from None def find(self, path, namespaces=None): """Find first matching element by tag name or path. @@ -359,21 +359,17 @@ def set(self, key, value): self.attrib[key] = value def keys(self): - """Get list of attribute names. + """Get attribute names. - Names are returned in an arbitrary order, just like an ordinary - Python dict. Equivalent to attrib.keys() + Equivalent to attrib.keys() """ return self.attrib.keys() def items(self): - """Get element attributes as a sequence. - - The attributes are returned in arbitrary order. Equivalent to - attrib.items(). + """Get element attributes as (name, value) pairs. - Return a list of (name, value) tuples. + Equivalent to attrib.items(). """ return self.attrib.items() @@ -420,7 +416,7 @@ def itertext(self): yield t -def SubElement(parent, tag, attrib={}, **extra): +def SubElement(parent, tag, /, attrib={}, **extra): """Subelement factory which creates an element instance, and appends it to an existing parent. @@ -928,9 +924,9 @@ def _serialize_html(write, elem, qnames, namespaces, **kwargs): tag = elem.tag text = elem.text if tag is Comment: - write("" % _escape_cdata(text)) + write("" % text) elif tag is ProcessingInstruction: - write("" % _escape_cdata(text)) + write("" % text) else: tag = qnames[tag] if tag is None: @@ -954,12 +950,15 @@ def _serialize_html(write, elem, qnames, namespaces, **kwargs): for k, v in items: if isinstance(k, QName): k = k.text - if isinstance(v, QName): - v = qnames[v.text] + k = qnames[k] + if v is None: + write(" %s" % k) # empty attr else: - v = _escape_attrib_html(v) - # FIXME: handle boolean attributes - write(" %s=\"%s\"" % (qnames[k], v)) + if isinstance(v, QName): + v = qnames[v.text] + else: + v = _escape_attrib_html(v) + write(" %s=\"%s\"" % (k, v)) write(">") ltag = tag.lower() if text: @@ -1194,17 +1193,17 @@ def _indent_children(elem, level): child_indentation = indentations[level] + space indentations.append(child_indentation) - if not elem.text or not elem.text.strip(): + if not elem.text or not elem.text.strip(_XML_WHITESPACE): elem.text = child_indentation for child in elem: if len(child): _indent_children(child, child_level) - if not child.tail or not child.tail.strip(): + if not child.tail or not child.tail.strip(_XML_WHITESPACE): child.tail = child_indentation # Dedent after the last child by overwriting the previous indentation. - if not child.tail.strip(): + if not child.tail.strip(_XML_WHITESPACE): child.tail = indentations[level] _indent_children(tree, 0) @@ -1275,16 +1274,20 @@ def iterator(source): gen = iterator(source) class IterParseIterator(collections.abc.Iterator): __next__ = gen.__next__ + def close(self): + nonlocal close_source if close_source: source.close() + close_source = False gen.close() - def __del__(self): - # TODO: Emit a ResourceWarning if it was not explicitly closed. - # (When the close() method will be supported in all maintained Python versions.) + def __del__(self, _warn=warnings.warn): if close_source: - source.close() + try: + _warn(f"unclosed iterparse iterator {source.name!r}", ResourceWarning, stacklevel=2) + finally: + source.close() it = IterParseIterator() it.root = None @@ -1576,10 +1579,10 @@ def __init__(self, *, target=None, encoding=None): parser.CommentHandler = target.comment if hasattr(target, 'pi'): parser.ProcessingInstructionHandler = target.pi + parser.StartDoctypeDeclHandler = self._start_doctype # Configure pyexpat: buffering, new-style attribute handling. parser.buffer_text = 1 parser.ordered_attributes = 1 - self._doctype = None self.entity = {} try: self.version = "Expat %d.%d.%d" % expat.version_info @@ -1698,38 +1701,15 @@ def _default(self, text): err.lineno = self.parser.ErrorLineNumber err.offset = self.parser.ErrorColumnNumber raise err - elif prefix == "<" and text[:9] == "": - self._doctype = None - return - text = text.strip() - if not text: - return - self._doctype.append(text) - n = len(self._doctype) - if n > 2: - type = self._doctype[1] - if type == "PUBLIC" and n == 4: - name, type, pubid, system = self._doctype - if pubid: - pubid = pubid[1:-1] - elif type == "SYSTEM" and n == 3: - name, type, system = self._doctype - pubid = None - else: - return - if hasattr(self.target, "doctype"): - self.target.doctype(name, pubid, system[1:-1]) - elif hasattr(self, "doctype"): - warnings.warn( - "The doctype() method of XMLParser is ignored. " - "Define doctype() method on the TreeBuilder target.", - RuntimeWarning) - self._doctype = None + def _start_doctype(self, name, system, pubid, has_internal_subset): + if hasattr(self.target, "doctype"): + self.target.doctype(name, pubid, system) + elif hasattr(self, "doctype"): + warnings.warn( + "The doctype() method of XMLParser is ignored. " + "Define doctype() method on the TreeBuilder target.", + RuntimeWarning) def feed(self, data): """Feed encoded data to parser.""" @@ -1921,7 +1901,7 @@ def _flush(self, _join_text=''.join): data = _join_text(self._data) del self._data[:] if self._strip_text and not self._preserve_space[-1]: - data = data.strip() + data = data.strip(_XML_WHITESPACE) if self._pending_start is not None: args, self._pending_start = self._pending_start, None qname_text = data if data and _looks_like_prefix_name(data) else None @@ -2118,3 +2098,14 @@ def _escape_attrib_c14n(text): pass else: _set_factories(Comment, ProcessingInstruction) + + +# -------------------------------------------------------------------- + +def __getattr__(name): + if name == "VERSION": + from warnings import _deprecated + + _deprecated("VERSION", remove=(3, 20)) + return "1.3.0" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/Lib/xml/sax/__init__.py b/Lib/xml/sax/__init__.py index fe4582c6f8b..45f69c6bc22 100644 --- a/Lib/xml/sax/__init__.py +++ b/Lib/xml/sax/__init__.py @@ -27,12 +27,21 @@ def parse(source, handler, errorHandler=ErrorHandler()): + """Parse an XML document with the default parser. + + source is a system identifier, a path-like object or a file object, + handler is a ContentHandler instance, and errorHandler is an + ErrorHandler instance. All work is done by the handler.""" parser = make_parser() parser.setContentHandler(handler) parser.setErrorHandler(errorHandler) parser.parse(source) def parseString(string, handler, errorHandler=ErrorHandler()): + """Parse an XML document from a string with the default parser. + + string is a str or a bytes-like object, the other arguments are the + same as for parse().""" import io if errorHandler is None: errorHandler = ErrorHandler() diff --git a/Lib/xml/sax/expatreader.py b/Lib/xml/sax/expatreader.py index ba3c1e98517..37b1add2848 100644 --- a/Lib/xml/sax/expatreader.py +++ b/Lib/xml/sax/expatreader.py @@ -3,8 +3,6 @@ pyexpat.__version__ == '2.22'. """ -version = "0.20" - from xml.sax._exceptions import * from xml.sax.handler import feature_validation, feature_namespaces from xml.sax.handler import feature_namespace_prefixes @@ -446,6 +444,16 @@ def create_parser(*args, **kwargs): # --- +def __getattr__(name): + if name == "version": + from warnings import _deprecated + + _deprecated("version", remove=(3, 20)) + return "0.20" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + +# --- + if __name__ == "__main__": import xml.sax.saxutils p = create_parser() diff --git a/Lib/xml/sax/handler.py b/Lib/xml/sax/handler.py index 3183c3fe96d..9c2e3af838a 100644 --- a/Lib/xml/sax/handler.py +++ b/Lib/xml/sax/handler.py @@ -9,8 +9,6 @@ $Id$ """ -version = '2.0beta' - #============================================================================ # # HANDLER INTERFACES @@ -385,3 +383,12 @@ def startCDATA(self): def endCDATA(self): """Reports the end of a CDATA marked section.""" + + +def __getattr__(name): + if name == "version": + from warnings import _deprecated + + _deprecated("version", remove=(3, 20)) + return "2.0beta" # Do not change + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/Lib/xml/sax/saxutils.py b/Lib/xml/sax/saxutils.py index c1612ea1ceb..920283c3f34 100644 --- a/Lib/xml/sax/saxutils.py +++ b/Lib/xml/sax/saxutils.py @@ -110,6 +110,7 @@ def __getattr__(self, name): write_through=True) class XMLGenerator(handler.ContentHandler): + """Content handler which writes the events back as an XML document.""" def __init__(self, out=None, encoding="iso-8859-1", short_empty_elements=False): handler.ContentHandler.__init__(self) @@ -186,9 +187,9 @@ def startElementNS(self, name, qname, attrs): for prefix, uri in self._undeclared_ns_maps: if prefix: - self._write(' xmlns:%s="%s"' % (prefix, uri)) + self._write(' xmlns:%s=%s' % (prefix, quoteattr(uri))) else: - self._write(' xmlns="%s"' % uri) + self._write(' xmlns=%s' % quoteattr(uri)) self._undeclared_ns_maps = [] for (name, value) in attrs.items(): diff --git a/Lib/xml/sax/xmlreader.py b/Lib/xml/sax/xmlreader.py index e906121d23b..98e93113fbb 100644 --- a/Lib/xml/sax/xmlreader.py +++ b/Lib/xml/sax/xmlreader.py @@ -89,7 +89,7 @@ def setProperty(self, name, value): raise SAXNotRecognizedException("Property '%s' not recognized" % name) class IncrementalParser(XMLReader): - """This interface adds three extra methods to the XMLReader + """This interface adds four extra methods to the XMLReader interface that allow XML parsers to support incremental parsing. Support for this interface is optional, since not all underlying XML parsers support this functionality. @@ -104,7 +104,7 @@ class IncrementalParser(XMLReader): is, after parse has been called and before it returns. By default, the class also implements the parse method of the XMLReader - interface using the feed, close and reset methods of the + interface using the prepareParser, feed and close methods of the IncrementalParser interface as a convenience to SAX 2.0 driver writers.""" @@ -274,6 +274,7 @@ def getCharacterStream(self): # ===== ATTRIBUTESIMPL ===== class AttributesImpl: + """Implementation of the Attributes interface.""" def __init__(self, attrs): """Non-NS-aware implementation. diff --git a/Lib/xml/utils.py b/Lib/xml/utils.py new file mode 100644 index 00000000000..532aa224dae --- /dev/null +++ b/Lib/xml/utils.py @@ -0,0 +1,37 @@ +lazy import re as _re + + +def is_valid_name(name): + """Test whether a string is a valid element or attribute name.""" + # https://www.w3.org/TR/xml/#NT-Name + return _re.fullmatch( + # NameStartChar + '[' + ':A-Z_a-z' + '\xC0-\xD6\xD8-\xF6\xF8-\u02FF\u0370-\u037D\u037F-\u1FFF' + '\u200C\u200D' + '\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF' + '\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF' + ']' + # NameChar + '[' + r'\-.0-9:A-Z_a-z' + '\xB7' + '\xC0-\xD6\xD8-\xF6\xF8-\u037D\u037F-\u1FFF' + '\u200C\u200D\u203F\u2040' + '\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF' + '\uF900-\uFDCF\uFDF0-\uFFFD\U00010000-\U000EFFFF' + ']*+', + name) is not None + +# https://www.w3.org/TR/xml/#charsets +_ILLEGAL_XML_CHAR = ( + '[' + '\x00-\x08\x0B\x0C\x0E-\x1F' # C0 controls except TAB, CR and LF + '\uD800-\uDFFF' # the surrogate blocks + '\uFFFE\uFFFF' # special Unicode characters + ']') + +def is_valid_text(data): + """Test whether a string is a sequence of legal XML 1.0 characters.""" + return _re.search(_ILLEGAL_XML_CHAR, data) is None diff --git a/Lib/zipapp.py b/Lib/zipapp.py index 7a4ef96ea0f..39e765d1ffd 100644 --- a/Lib/zipapp.py +++ b/Lib/zipapp.py @@ -69,7 +69,7 @@ def _copy_archive(archive, new_archive, interpreter=None): dst.write(first_2) shutil.copyfileobj(src, dst) - if interpreter and isinstance(new_archive, str): + if interpreter and isinstance(new_archive, (str, os.PathLike)): os.chmod(new_archive, os.stat(new_archive).st_mode | stat.S_IEXEC) @@ -187,16 +187,16 @@ def main(args=None): """ import argparse - parser = argparse.ArgumentParser(color=True) + parser = argparse.ArgumentParser() parser.add_argument('--output', '-o', default=None, help="The name of the output archive. " - "Required if SOURCE is an archive.") + "Required if `SOURCE` is an archive.") parser.add_argument('--python', '-p', default=None, help="The name of the Python interpreter to use " "(default: no shebang line).") parser.add_argument('--main', '-m', default=None, help="The main function of the application " - "(default: use an existing __main__.py).") + "(default: use an existing `__main__.py`).") parser.add_argument('--compress', '-c', action='store_true', help="Compress files with the deflate method. " "Files are stored uncompressed by default.") diff --git a/Lib/zipfile/__init__.py b/Lib/zipfile/__init__.py index 2b6e6163b96..7d9522013db 100644 --- a/Lib/zipfile/__init__.py +++ b/Lib/zipfile/__init__.py @@ -786,7 +786,16 @@ def __init__(self): self._unconsumed = b'' self.eof = False - def decompress(self, data): + @property + def needs_input(self): + # While the LZMA properties header is still being buffered, more input + # is required; afterwards defer to the wrapped decompressor so a bounded + # decompress() call can be drained across reads. + if self._decomp is None: + return True + return self._decomp.needs_input + + def decompress(self, data, max_length=-1): if self._decomp is None: self._unconsumed += data if len(self._unconsumed) <= 4: @@ -802,7 +811,7 @@ def decompress(self, data): data = self._unconsumed[4 + psize:] del self._unconsumed - result = self._decomp.decompress(data) + result = self._decomp.decompress(data, max_length) self.eof = self._decomp.eof return result @@ -1171,8 +1180,15 @@ def _read1(self, n): data = self._decompressor.unconsumed_tail if n > len(data): data += self._read2(n - len(data)) - else: + elif self._compress_type == ZIP_STORED: data = self._read2(n) + else: + # bzip2/lzma/zstd: a bounded decompress() call may leave input + # buffered inside the decompressor; drain that before reading more. + if getattr(self._decompressor, "needs_input", True): + data = self._read2(n) + else: + data = b'' if self._compress_type == ZIP_STORED: self._eof = self._compress_left <= 0 @@ -1185,8 +1201,17 @@ def _read1(self, n): if self._eof: data += self._decompressor.flush() else: - data = self._decompressor.decompress(data) - self._eof = self._decompressor.eof or self._compress_left <= 0 + # Bound the output of a single decompress() call (mirroring the + # DEFLATE path above) so that a small compressed member cannot + # expand into one unbounded read. + try: + data = self._decompressor.decompress(data, max(n, self.MIN_READ_SIZE)) + except TypeError: + # See MonkeypatchedDecompressorTests in test_core.py + data = self._decompressor.decompress(data) + self._eof = (self._decompressor.eof or + self._compress_left <= 0 and + getattr(self._decompressor, "needs_input", True)) data = data[:self._left] self._left -= len(data) @@ -2057,6 +2082,15 @@ def mkdir(self, zinfo_or_directory_name, mode=511): else: raise TypeError("Expected type str or ZipInfo") + if not self.fp: + raise ValueError( + "Attempt to write to ZIP archive that was already closed" + ) + if self._writing: + raise ValueError( + "Can't write to ZIP archive while an open writing handle exists." + ) + with self._lock: if self._seekable: self.fp.seek(self.start_dir) @@ -2242,10 +2276,10 @@ def writepy(self, pathname, basename="", filterfunc=None): basename = name if self.debug: print("Adding package in", pathname, "as", basename) - fname, arcname = self._get_codename(initname[0:-3], basename) + arcname, bytecode = self._get_code(initname[0:-3], basename) if self.debug: print("Adding", arcname) - self.write(fname, arcname) + self.writestr(arcname, bytecode) dirlist = sorted(os.listdir(pathname)) dirlist.remove("__init__.py") # Add all *.py files and package subdirectories @@ -2262,11 +2296,10 @@ def writepy(self, pathname, basename="", filterfunc=None): if self.debug: print('file %r skipped by filterfunc' % path) continue - fname, arcname = self._get_codename(path[0:-3], - basename) + arcname, bytecode = self._get_code(path[0:-3], basename) if self.debug: print("Adding", arcname) - self.write(fname, arcname) + self.writestr(arcname, bytecode) else: # This is NOT a package directory, add its files at top level if self.debug: @@ -2279,108 +2312,65 @@ def writepy(self, pathname, basename="", filterfunc=None): if self.debug: print('file %r skipped by filterfunc' % path) continue - fname, arcname = self._get_codename(path[0:-3], - basename) + arcname, bytecode = self._get_code(path[0:-3], basename) if self.debug: print("Adding", arcname) - self.write(fname, arcname) + self.writestr(arcname, bytecode) else: if pathname[-3:] != ".py": raise RuntimeError( 'Files added with writepy() must end with ".py"') - fname, arcname = self._get_codename(pathname[0:-3], basename) + arcname, bytecode = self._get_code(pathname[0:-3], basename) if self.debug: print("Adding file", arcname) - self.write(fname, arcname) + self.writestr(arcname, bytecode) - def _get_codename(self, pathname, basename): - """Return (filename, archivename) for the path. + def _get_code(self, pathname, basename): + """Return (arcname, bytecode) for the path. - Given a module name path, return the correct file path and - archive name, compiling if necessary. For example, given - /python/lib/string, return (/python/lib/string.pyc, string). + Given a module name path, return the bytecode and archive + name. For example, given /python/lib/string, return + ('string', b''). """ - def _compile(file, optimize=-1): - import py_compile - if self.debug: - print("Compiling", file) - try: - py_compile.compile(file, doraise=True, optimize=optimize) - except py_compile.PyCompileError as err: - print(err.msg) - return False - return True + import importlib._bootstrap_external + import importlib.machinery file_py = pathname + ".py" file_pyc = pathname + ".pyc" - pycache_opt0 = importlib.util.cache_from_source(file_py, optimization='') - pycache_opt1 = importlib.util.cache_from_source(file_py, optimization=1) - pycache_opt2 = importlib.util.cache_from_source(file_py, optimization=2) - if self._optimize == -1: - # legacy mode: use whatever file is present - if (os.path.isfile(file_pyc) and - os.stat(file_pyc).st_mtime >= os.stat(file_py).st_mtime): - # Use .pyc file. - arcname = fname = file_pyc - elif (os.path.isfile(pycache_opt0) and - os.stat(pycache_opt0).st_mtime >= os.stat(file_py).st_mtime): - # Use the __pycache__/*.pyc file, but write it to the legacy pyc - # file name in the archive. - fname = pycache_opt0 - arcname = file_pyc - elif (os.path.isfile(pycache_opt1) and - os.stat(pycache_opt1).st_mtime >= os.stat(file_py).st_mtime): - # Use the __pycache__/*.pyc file, but write it to the legacy pyc - # file name in the archive. - fname = pycache_opt1 - arcname = file_pyc - elif (os.path.isfile(pycache_opt2) and - os.stat(pycache_opt2).st_mtime >= os.stat(file_py).st_mtime): - # Use the __pycache__/*.pyc file, but write it to the legacy pyc - # file name in the archive. - fname = pycache_opt2 - arcname = file_pyc - else: - # Compile py into PEP 3147 pyc file. - if _compile(file_py): - if sys.flags.optimize == 0: - fname = pycache_opt0 - elif sys.flags.optimize == 1: - fname = pycache_opt1 - else: - fname = pycache_opt2 - arcname = file_pyc - else: - fname = arcname = file_py + archivename = os.path.split(file_pyc)[1] + + loader = importlib.machinery.SourceFileLoader('', file_py) + source_bytes = loader.get_data(file_py) + try: + if self.debug: + print("Compiling", file_py) + code = loader.source_to_code(source_bytes, archivename) + except Exception as err: + # Historically, this function prints messages here rather than raising + # (see test_zipfile.test_write_filtered_python_package) + from py_compile import PyCompileError + print(PyCompileError(type(err), err, file_py).msg) + + archivename = os.path.split(file_py)[1] + bytecode = source_bytes else: - # new mode: use given optimization level - if self._optimize == 0: - fname = pycache_opt0 - arcname = file_pyc - else: - arcname = file_pyc - if self._optimize == 1: - fname = pycache_opt1 - elif self._optimize == 2: - fname = pycache_opt2 - else: - msg = "invalid value for 'optimize': {!r}".format(self._optimize) - raise ValueError(msg) - if not (os.path.isfile(fname) and - os.stat(fname).st_mtime >= os.stat(file_py).st_mtime): - if not _compile(file_py, optimize=self._optimize): - fname = arcname = file_py - archivename = os.path.split(arcname)[1] + # Historically this function has used timestamp comparisons, so we + # keep using it until someone makes that specific improvement. + source_stats = loader.path_stats(file_py) + bytecode = importlib._bootstrap_external._code_to_timestamp_pyc( + code, source_stats['mtime'], source_stats['size']) + if basename: archivename = "%s/%s" % (basename, archivename) - return (fname, archivename) + + return archivename, bytecode def main(args=None): import argparse description = 'A simple command-line interface for zipfile module.' - parser = argparse.ArgumentParser(description=description, color=True) + parser = argparse.ArgumentParser(description=description) group = parser.add_mutually_exclusive_group(required=True) group.add_argument('-l', '--list', metavar='', help='Show listing of a zipfile') @@ -2393,7 +2383,7 @@ def main(args=None): group.add_argument('-t', '--test', metavar='', help='Test if a zipfile is valid') parser.add_argument('--metadata-encoding', metavar='', - help='Specify encoding of member names for -l, -e and -t') + help='Specify encoding of member names for `-l`, `-e` and `-t`') args = parser.parse_args(args) encoding = args.metadata_encoding diff --git a/Lib/zipfile/_path/__init__.py b/Lib/zipfile/_path/__init__.py index 80f5d607731..010eeed95d2 100644 --- a/Lib/zipfile/_path/__init__.py +++ b/Lib/zipfile/_path/__init__.py @@ -7,7 +7,7 @@ for more detail. """ -import contextlib +import functools import io import itertools import pathlib @@ -17,6 +17,7 @@ import sys import zipfile +from ._functools import none_as, save_method_args from .glob import Translator __all__ = ['Path'] @@ -85,13 +86,12 @@ class InitializedState: Mix-in to save the initialization state for pickling. """ + @save_method_args def __init__(self, *args, **kwargs): - self.__args = args - self.__kwargs = kwargs super().__init__(*args, **kwargs) def __getstate__(self): - return self.__args, self.__kwargs + return self._saved___init__.args, self._saved___init__.kwargs def __setstate__(self, state): args, kwargs = state @@ -180,16 +180,19 @@ class FastLookup(CompleteDirs): """ def namelist(self): - with contextlib.suppress(AttributeError): - return self.__names - self.__names = super().namelist() - return self.__names + return self._namelist + + @functools.cached_property + def _namelist(self): + return super().namelist() def _name_set(self): - with contextlib.suppress(AttributeError): - return self.__lookup - self.__lookup = super()._name_set() - return self.__lookup + return self._name_set_prop + + @functools.cached_property + def _name_set_prop(self): + return super()._name_set() + def _extract_text_encoding(encoding=None, *args, **kwargs): # compute stack level so that the caller of the caller sees any warning. @@ -273,7 +276,7 @@ class Path: resolve to the zipfile. >>> str(path) - 'mem/abcde.zip/' + 'mem/abcde.zip' >>> path.name 'abcde.zip' >>> path.filename == pathlib.Path('mem/abcde.zip') @@ -431,7 +434,8 @@ def relative_to(self, other, *extra): return posixpath.relpath(str(self), str(other.joinpath(*extra))) def __str__(self): - return posixpath.join(self.root.filename, self.at) + root = none_as(self.root.filename, ':zipfile:') + return posixpath.join(root, self.at) if self.at else root def __repr__(self): return self.__repr.format(self=self) diff --git a/Lib/zipfile/_path/_functools.py b/Lib/zipfile/_path/_functools.py new file mode 100644 index 00000000000..7d82636ac8d --- /dev/null +++ b/Lib/zipfile/_path/_functools.py @@ -0,0 +1,31 @@ +import collections +import functools + + +# from jaraco.functools 4.0.2 +def save_method_args(method): + """ + Wrap a method such that when it is called, the args and kwargs are + saved on the method. + """ + args_and_kwargs = collections.namedtuple('args_and_kwargs', 'args kwargs') # noqa: PYI024 + + @functools.wraps(method) + def wrapper(self, /, *args, **kwargs): + attr_name = '_saved_' + method.__name__ + attr = args_and_kwargs(args, kwargs) + setattr(self, attr_name, attr) + return method(self, *args, **kwargs) + + return wrapper + + +# from jaraco.functools 4.3 +def none_as(value, replacement=None): + """ + >>> none_as(None, 'foo') + 'foo' + >>> none_as('bar', 'foo') + 'bar' + """ + return replacement if value is None else value diff --git a/Lib/zipimport.py b/Lib/zipimport.py index 444c9dd11d8..09a85f6d7f5 100644 --- a/Lib/zipimport.py +++ b/Lib/zipimport.py @@ -10,15 +10,12 @@ to Zip archives. """ -#from importlib import _bootstrap_external -#from importlib import _bootstrap # for _verbose_message import _frozen_importlib_external as _bootstrap_external from _frozen_importlib_external import _unpack_uint16, _unpack_uint32, _unpack_uint64 import _frozen_importlib as _bootstrap # for _verbose_message import _imp # for check_hash_based_pycs import _io # for open import marshal # for loads -import sys # for modules import time # for mktime __all__ = ['ZipImportError', 'zipimporter'] @@ -34,8 +31,6 @@ class ZipImportError(ImportError): # _read_directory() cache _zip_directory_cache = {} -_module_type = type(sys) - END_CENTRAL_DIR_SIZE = 22 END_CENTRAL_DIR_SIZE_64 = 56 END_CENTRAL_DIR_LOCATOR_SIZE_64 = 20 @@ -164,11 +159,12 @@ def get_filename(self, fullname): """get_filename(fullname) -> filename string. Return the filename for the specified module or raise ZipImportError - if it couldn't be imported. + if it couldn't be found. """ # Deciding the filename requires working out where the code # would come from if the module was actually loaded - code, ispackage, modpath = _get_module_code(self, fullname) + _, _, modpath = _get_module_code( + self, fullname, compile_source=False) return modpath @@ -210,52 +206,6 @@ def is_package(self, fullname): return mi - # Load and return the module named by 'fullname'. - def load_module(self, fullname): - """load_module(fullname) -> module. - - Load the module specified by 'fullname'. 'fullname' must be the - fully qualified (dotted) module name. It returns the imported - module, or raises ZipImportError if it could not be imported. - - Deprecated since Python 3.10. Use exec_module() instead. - """ - import warnings - warnings._deprecated("zipimport.zipimporter.load_module", - f"{warnings._DEPRECATED_MSG}; " - "use zipimport.zipimporter.exec_module() instead", - remove=(3, 15)) - code, ispackage, modpath = _get_module_code(self, fullname) - mod = sys.modules.get(fullname) - if mod is None or not isinstance(mod, _module_type): - mod = _module_type(fullname) - sys.modules[fullname] = mod - mod.__loader__ = self - - try: - if ispackage: - # add __path__ to the module *before* the code gets - # executed - path = _get_module_path(self, fullname) - fullpath = _bootstrap_external._path_join(self.archive, path) - mod.__path__ = [fullpath] - - if not hasattr(mod, '__builtins__'): - mod.__builtins__ = __builtins__ - _bootstrap_external._fix_up_module(mod.__dict__, fullname, modpath) - exec(code, mod.__dict__) - except: - del sys.modules[fullname] - raise - - try: - mod = sys.modules[fullname] - except KeyError: - raise ImportError(f'Loaded module {fullname!r} not found in sys.modules') - _bootstrap._verbose_message('import {} # loaded from Zip {}', fullname, modpath) - return mod - - def get_resource_reader(self, fullname): """Return the ResourceReader for a module in a zip file.""" from importlib.readers import ZipReader @@ -478,7 +428,12 @@ def _read_directory(archive): if flags & 0x800: # UTF-8 file names extension - name = name.decode() + try: + name = name.decode() + except UnicodeDecodeError as exc: + raise ZipImportError( + f"can't decode file name in Zip file: {archive!r}", + path=archive) from exc else: # Historical ZIP filename encoding try: @@ -603,11 +558,16 @@ def _read_directory(archive): ) _importing_zlib = False +_zlib_decompress = None # Return the zlib.decompress function object, or NULL if zlib couldn't # be imported. The function is cached when found, so subsequent calls # don't import zlib again. -def _get_decompress_func(): +def _get_zlib_decompress_func(): + global _zlib_decompress + if _zlib_decompress: + return _zlib_decompress + global _importing_zlib if _importing_zlib: # Someone has a zlib.py[co] in their Zip file @@ -617,7 +577,7 @@ def _get_decompress_func(): _importing_zlib = True try: - from zlib import decompress + from zlib import decompress as _zlib_decompress except Exception: _bootstrap._verbose_message('zipimport: zlib UNAVAILABLE') raise ZipImportError("can't decompress data; zlib not available") @@ -625,7 +585,66 @@ def _get_decompress_func(): _importing_zlib = False _bootstrap._verbose_message('zipimport: zlib available') - return decompress + return _zlib_decompress + + +_importing_zstd = False +_zstd_decompressor_class = None +_zstd_get_frame_size = None + +# Return the _zstd.ZstdDecompressor function object, or NULL if _zstd couldn't +# be imported. The result is cached when found. +def _get_zstd_decompressor_class(): + global _zstd_decompressor_class, _zstd_get_frame_size + if _zstd_decompressor_class and _zstd_get_frame_size: + return _zstd_decompressor_class + + global _importing_zstd + if _importing_zstd: + # Someone has a _zstd.py[co] in their Zip file + # let's avoid a stack overflow. + _bootstrap._verbose_message("zipimport: zstd UNAVAILABLE") + raise ZipImportError("can't decompress data; zstd not available") + + _importing_zstd = True + try: + from _zstd import ( + ZstdDecompressor as _zstd_decompressor_class, + get_frame_size as _zstd_get_frame_size, + ) + except Exception: + _bootstrap._verbose_message("zipimport: zstd UNAVAILABLE") + raise ZipImportError("can't decompress data; zstd not available") + finally: + _importing_zstd = False + + _bootstrap._verbose_message("zipimport: zstd available") + return _zstd_decompressor_class + + +def _zstd_decompress(data): + # A simple version of compression.zstd.decompress() as we cannot import + # that here as the stdlib itself could be being zipimported. + decomp_class = _get_zstd_decompressor_class() + data = memoryview(data) + if not data: + raise ZipImportError("zipimport: zstd compressed data ended before " + "the end-of-stream marker") + results = [] + while data: + try: + frame_size = _zstd_get_frame_size(data) + except Exception: + raise ZipImportError("zipimport: zstd compressed data ended before " + "the end-of-stream marker") from None + decomp = decomp_class() + results.append(decomp.decompress(data[:frame_size])) + if not decomp.eof: + raise ZipImportError("zipimport: zstd compressed data ended before " + "the end-of-stream marker") + data = data[frame_size:] + return b"".join(results) + # Given a path to a Zip file and a toc_entry, return the (uncompressed) data. def _get_data(archive, toc_entry): @@ -659,16 +678,23 @@ def _get_data(archive, toc_entry): if len(raw_data) != data_size: raise OSError("zipimport: can't read data") - if compress == 0: - # data is not compressed - return raw_data - - # Decompress with zlib - try: - decompress = _get_decompress_func() - except Exception: - raise ZipImportError("can't decompress data; zlib not available") - return decompress(raw_data, -15) + match compress: + case 0: # stored + return raw_data + case 8: # deflate aka zlib + try: + decompress = _get_zlib_decompress_func() + except Exception: + raise ZipImportError("can't decompress data; zlib not available") + return decompress(raw_data, -15) + case 93: # zstd + try: + return _zstd_decompress(raw_data) + except Exception: + raise ZipImportError("could not decompress zstd data") + # bz2 and lzma could be added, but are largely obsolete. + case _: + raise ZipImportError(f"zipimport: unsupported compression {compress}") # Lenient date/time comparison function. The precision of the mtime @@ -734,9 +760,9 @@ def _normalize_line_endings(source): # Given a string buffer containing Python source code, compile it # and return a code object. -def _compile_source(pathname, source): +def _compile_source(pathname, source, module): source = _normalize_line_endings(source) - return compile(source, pathname, 'exec', dont_inherit=True) + return compile(source, pathname, 'exec', dont_inherit=True, module=module) # Convert the date/time values found in the Zip archive to a value # that's compatible with the time stamp stored in .pyc files. @@ -785,9 +811,9 @@ def _get_pyc_source(self, path): return _get_data(self.archive, toc_entry) -# Get the code object associated with the module specified by -# 'fullname'. -def _get_module_code(self, fullname): +# Get the code object associated with the module specified by 'fullname'. +# If compile_source is false, return None for source code without reading or compiling it. +def _get_module_code(self, fullname, *, compile_source=True): path = _get_module_path(self, fullname) import_error = None for suffix, isbytecode, ispackage in _zip_searchorder: @@ -799,6 +825,8 @@ def _get_module_code(self, fullname): pass else: modpath = toc_entry[0] + if not isbytecode and not compile_source: + return None, ispackage, modpath data = _get_data(self.archive, toc_entry) code = None if isbytecode: @@ -807,12 +835,11 @@ def _get_module_code(self, fullname): except ImportError as exc: import_error = exc else: - code = _compile_source(modpath, data) + code = _compile_source(modpath, data, fullname) if code is None: # bad magic number or non-matching mtime # in byte code, try next continue - modpath = toc_entry[0] return code, ispackage, modpath else: if import_error: diff --git a/Lib/zoneinfo/_tzpath.py b/Lib/zoneinfo/_tzpath.py index 177d32c35ef..3661c837daa 100644 --- a/Lib/zoneinfo/_tzpath.py +++ b/Lib/zoneinfo/_tzpath.py @@ -177,6 +177,10 @@ def valid_key(fpath): # posixrules is a special symlink-only time zone where it exists, it # should not be included in the output valid_zones.remove("posixrules") + if "localtime" in valid_zones: + # localtime is a special symlink-only time zone where it exists, it + # should not be included in the output + valid_zones.remove("localtime") return valid_zones diff --git a/Lib/zoneinfo/_zoneinfo.py b/Lib/zoneinfo/_zoneinfo.py index 7063eb6a902..7cdb4c22fa8 100644 --- a/Lib/zoneinfo/_zoneinfo.py +++ b/Lib/zoneinfo/_zoneinfo.py @@ -144,7 +144,7 @@ def fromutc(self, dt): if num_trans > 1 and timestamp >= self._trans_utc[1]: tti_prev, tti = self._ttinfos[idx - 2 : idx] elif timestamp > self._trans_utc[-1]: - tti_prev = self._ttinfos[-1] + tti_prev = self._tti_before tti = self._tz_after else: tti_prev = self._tti_before @@ -535,7 +535,7 @@ def year_to_epoch(self, year): days_before_year = _post_epoch_days_before_year(year) d = self.d - if self.julian and d >= 59 and calendar.isleap(year): + if self.julian and d >= 60 and calendar.isleap(year): d += 1 epoch = (days_before_year + d) * 86400 @@ -640,11 +640,11 @@ def _parse_tz_str(tz_str): parser_re = re.compile( r""" - (?P[^<0-9:.+-]+|<[a-zA-Z0-9+-]+>) + (?P[a-zA-Z]+|<[a-zA-Z0-9+-]+>) (?: (?P[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?) (?: - (?P[^0-9:.+-]+|<[a-zA-Z0-9+-]+>) + (?P[a-zA-Z]+|<[a-zA-Z0-9+-]+>) (?P[+-]?\d{1,3}(?::\d{2}(?::\d{2})?)?)? )? # dst )? # stdoff @@ -672,7 +672,8 @@ def _parse_tz_str(tz_str): except ValueError as e: raise ValueError(f"Invalid STD offset in {tz_str}") from e else: - std_offset = 0 + # The STD offset is required + raise ValueError(f"Invalid STD offset in {tz_str}") if dst_abbr is not None: if dst_offset := m.group("dstoff"): @@ -707,7 +708,7 @@ def _parse_dst_start_end(dststr): type = date[:1] if type == "M": n_is_julian = False - m = re.fullmatch(r"M(\d{1,2})\.(\d).(\d)", date, re.ASCII) + m = re.fullmatch(r"M(\d{1,2})\.(\d)\.(\d)", date, re.ASCII) if m is None: raise ValueError(f"Invalid dst start/end date: {dststr}") date_offset = tuple(map(int, m.groups())) @@ -719,6 +720,8 @@ def _parse_dst_start_end(dststr): else: n_is_julian = False + if re.fullmatch(r"\d{1,3}", date, re.ASCII) is None: + raise ValueError(f"Invalid dst start/end date: {dststr}") doy = int(date) offset = _DayOffset(doy, n_is_julian) diff --git a/README.md b/README.md index 1fc891b7901..c422a954320 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ # [RustPython](https://rustpython.github.io/) -A Python-3 (CPython >= 3.14.0) Interpreter written in Rust :snake: :scream: +A Python-3 (CPython >= 3.15.0) Interpreter written in Rust :snake: :scream: :metal:. [![Build Status](https://github.com/RustPython/RustPython/workflows/CI/badge.svg)](https://github.com/RustPython/RustPython/actions?query=workflow%3ACI) @@ -145,7 +145,7 @@ cargo build --release --target wasm32-wasip1 --features="freeze-stdlib" ### JIT (Just in time) compiler -RustPython has a **very** experimental JIT compiler that compile python functions into native code. +RustPython has a **very** experimental JIT compiler that compiles python functions into native code. #### Building @@ -202,7 +202,7 @@ make cool projects: - [pyckitup](https://github.com/pickitup247/pyckitup): a game engine written in rust. - [Robot Rumble](https://github.com/robot-rumble/logic/): an arena-based AI competition platform -- [Ruff](https://github.com/charliermarsh/ruff/): an extremely fast Python linter, written in Rust +- [Ruff](https://github.com/astral-sh/ruff/): an extremely fast Python linter, written in Rust ## Goals diff --git a/architecture/architecture.md b/architecture/architecture.md index 4b4110ee895..7b464cf3514 100644 --- a/architecture/architecture.md +++ b/architecture/architecture.md @@ -76,6 +76,20 @@ For each of the three components, the entry point is as follows: - Compiler: `compile`, located in [`crates/vm/src/vm/compile.rs`][11], this eventually forwards a call to [`compiler::compile`][12]. - VM: `run_code_obj`, located in [`crates/vm/src/vm/mod.rs`][13]. This creates a new frame in which the bytecode is executed. +## Embedded file I/O + +The `rustpython-vm` feature `host_io` enables `_io.FileIO` and file-descriptor +and path conversion without the `os`, signal, subprocess or ctypes modules. +`host_env` includes `host_io`. + +On native targets, FileIO uses the host's file descriptors and paths +directly, so `host_io` is not a sandbox. On `wasm32-unknown-unknown`, +`host_io` makes the guest import a subset of WASI preview1 +(`wasi_snapshot_preview1`: fd read/write/seek/close/sync/filestat_set_size/fdstat_get, +prestat, path_open). Paths resolve through host preopens and the host decides +access. `wasm32-wasip1` builds use the standard WASI libc path instead. This +does not provide stdio, `os`, or a `-m test` runner on wasm32-unknown. + ## Components Here we give a brief overview of each component and its function. For more details for the separate crates please take a look at their respective READMEs. diff --git a/benches/README.md b/benches/README.md index d31e1a0f271..998304b130c 100644 --- a/benches/README.md +++ b/benches/README.md @@ -5,7 +5,7 @@ These are some files to determine performance of rustpython. ## Usage Running `cargo bench` from the root of the repository will start the benchmarks. Once done there will be a graphical -report under `target/criterion/report/index.html` that you can use use to view the results. +report under `target/criterion/report/index.html` that you can use to view the results. `cargo bench` supports name matching to run a subset of the benchmarks. To run only the sorted microbenchmark, you can run: @@ -42,9 +42,9 @@ Two things differ when the benchmarks run under CodSpeed: - The CPython comparison benchmarks are skipped. They are useful to compare RustPython against CPython locally, but CodSpeed tracks the evolution of RustPython itself, and running them would double the duration of an already slow instrumented run. -- The microbenchmarks using `ITERATIONS` run with a single value instead of five. The criterion - benchmark id does not include the iteration count, so all five sizes are reported under the same - name. +- The microbenchmarks using `ITERATIONS` run with a single value of 1,000 instead of five sizes. + CodSpeed retains the existing benchmark names; local runs include the iteration count in each + benchmark id. ### Adding a benchmark @@ -54,6 +54,15 @@ in two ways: 1. The time to parse the file to AST 2. The time it takes to execute the file +Parsing stops at an AST in both implementations. The CPython reference uses +`compile(..., flags=ast.PyCF_ONLY_AST)` without compiling bytecode. + +Execution includes compilation and runs each iteration with a fresh namespace whose `__name__` +is `"__main__"`, so script entry points run in both RustPython and CPython. + +Both Rust harnesses load only `.py` files and run workloads in filename order. +Other entries, such as `__pycache__` directories, are ignored. + ### Adding a micro benchmark Micro benchmarks are small snippets of code added under the `microbenchmarks/` directory. A microbenchmark file has @@ -73,7 +82,7 @@ len(a_list) ``` Only `len(a_list)` will be timed. Setup or benchmarked code can optionally reference a variable called `ITERATIONS`. If -present then the benchmark code will be invoked 5 times with `ITERATIONS` set to a value between 100 and 1,000. For +present then the benchmark runs at five sizes: 100, 300, 500, 700 and 900 iterations locally. For example: ```python @@ -82,6 +91,23 @@ obj = [i for i in range(ITERATIONS)] `ITERATIONS` can appear in both the setup code and the benchmark code. +## Subprocess benchmarks with pytest + +The optional pytest driver measures whole interpreter processes, including startup. +Install `pytest` and `pytest-benchmark`, build RustPython with `cargo build --release`, +and run from the repository root: + +```shell +python -m pytest benches/test_benchmarks.py +``` + +It uses the release executable in `target/release` by default. Set `RUSTPYTHON` to +the executable path when using a different build directory. Relative `RUSTPYTHON` +paths are resolved from the directory where pytest is launched; absolute paths +can be used from any directory. Script paths are resolved relative to this +checkout, so pytest can also be launched from another directory. A failed +subprocess fails the benchmark instead of producing a timing. + ## MacOS setup On MacOS you will need to add the following to a `.cargo/config` file: diff --git a/benches/execution.rs b/benches/execution.rs index 56d4fc4fc19..5f862c7a45b 100644 --- a/benches/execution.rs +++ b/benches/execution.rs @@ -1,15 +1,15 @@ -#![allow(clippy::iter_over_hash_type)] - extern crate alloc; +use alloc::collections::BTreeMap; use core::hint::black_box; use criterion::{ Bencher, BenchmarkGroup, BenchmarkId, Criterion, Throughput, criterion_group, criterion_main, measurement::WallTime, }; +use pyo3::types::{PyCode, PyCodeMethods, PyDict, PyDictMethods, code::PyCodeInput}; use rustpython_compiler::Mode; use rustpython_vm::{Interpreter, PyResult, Settings}; -use std::{collections::HashMap, path::Path}; +use std::path::Path; /// `true` when the benchmarks are executed by the CodSpeed runner. /// @@ -25,9 +25,14 @@ fn bench_cpython_code(b: &mut Bencher<'_>, source: &str) { let c_str_source = c_str_source_head.as_c_str(); pyo3::Python::attach(|py| { b.iter(|| { - let module = pyo3::types::PyModule::from_code(py, c_str_source, c"", c"") + let code = PyCode::compile(py, c_str_source, c"", PyCodeInput::File) + .expect("Error compiling source"); + let globals = PyDict::new(py); + globals.set_item("__name__", "__main__").unwrap(); + let result = code + .run(Some(&globals), None) .expect("Error running source"); - black_box(module); + black_box(result); }) }) } @@ -35,9 +40,12 @@ fn bench_cpython_code(b: &mut Bencher<'_>, source: &str) { fn bench_rustpython_code(b: &mut Bencher<'_>, name: &str, source: &str) { // NOTE: Take long time. let mut settings = Settings::default(); - settings.path_list.push("Lib/".to_string()); + settings.path_list.push("Lib/".into()); settings.write_bytecode = false; settings.user_site_directory = false; + // Pin the str/bytes hash secret so dict/set probe sequences (and thus + // timings) are reproducible across benchmark runs. + settings.hash_seed = Some(0); let builder = Interpreter::builder(settings); let defs = rustpython_stdlib::stdlib_module_defs(&builder.ctx); builder.add_native_modules(&defs).build().enter(|vm| { @@ -46,6 +54,10 @@ fn bench_rustpython_code(b: &mut Bencher<'_>, name: &str, source: &str) { b.iter(|| { let code = vm.compile(source, Mode::Exec, name).unwrap(); let scope = vm.new_scope_with_builtins(); + scope + .globals + .set_item("__name__", vm.ctx.new_str("__main__").into(), vm) + .unwrap(); let res: PyResult = vm.run_code_obj(code, scope); vm.unwrap_pyresult(res); }) @@ -83,9 +95,14 @@ pub fn benchmark_file_parsing( let builtins = pyo3::types::PyModule::import(py, "builtins") .expect("Failed to import builtins"); let compile = builtins.getattr("compile").expect("no compile in builtins"); + let ast = pyo3::types::PyModule::import(py, "ast").expect("Failed to import ast"); + let only_ast: i32 = ast + .getattr("PyCF_ONLY_AST") + .and_then(|flag| flag.extract()) + .expect("no PyCF_ONLY_AST in ast"); b.iter(|| { let x = compile - .call1((contents, name, "exec")) + .call1((contents, name, "exec", only_ast)) .expect("Failed to parse code"); black_box(x); }) @@ -117,14 +134,15 @@ pub fn criterion_benchmark(c: &mut Criterion) { let mut benches = benchmark_dir .read_dir() .unwrap() - .map(|entry| { - let path = entry.unwrap().path(); + .map(|entry| entry.unwrap().path()) + .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "py")) + .map(|path| { ( path.file_name().unwrap().to_str().unwrap().to_owned(), std::fs::read_to_string(path).unwrap(), ) }) - .collect::>(); + .collect::>(); // Benchmark parsing let mut parse_group = c.benchmark_group("parse_to_ast"); diff --git a/benches/microbenchmarks.rs b/benches/microbenchmarks.rs index 4d48278e447..4a6e3596135 100644 --- a/benches/microbenchmarks.rs +++ b/benches/microbenchmarks.rs @@ -4,7 +4,7 @@ use criterion::{ }; use pyo3::types::PyAnyMethods; use rustpython_compiler::Mode; -use rustpython_vm::{AsObject, Interpreter, PyResult, Settings}; +use rustpython_vm::{AsObject, Interpreter, PyResult, Settings, scope::Scope}; use std::{fs, io, path::Path}; // List of microbenchmarks to skip. @@ -45,11 +45,8 @@ fn bench_cpython_code(group: &mut BenchmarkGroup<'_, WallTime>, bench: &MicroBen pyo3::types::PyModule::import(py, "builtins").expect("Failed to import builtins"); let exec = builtins.getattr("exec").expect("no exec in builtins"); - let bench_func = |(globals, locals): &mut ( - pyo3::Bound<'_, pyo3::types::PyDict>, - pyo3::Bound<'_, pyo3::types::PyDict>, - )| { - let res = exec.call((&code, &*globals, &*locals), None); + let bench_func = |globals: &mut pyo3::Bound<'_, pyo3::types::PyDict>| { + let res = exec.call((&code, &*globals), None); if let Err(e) = res { e.print(py); panic!("Error running microbenchmark") @@ -58,23 +55,24 @@ fn bench_cpython_code(group: &mut BenchmarkGroup<'_, WallTime>, bench: &MicroBen let bench_setup = |iterations| { let globals = pyo3::types::PyDict::new(py); - let locals = pyo3::types::PyDict::new(py); + globals.set_item("__name__", "__main__").unwrap(); if let Some(idx) = iterations { globals.set_item("ITERATIONS", idx).unwrap(); } - let res = exec.call((&setup_code, &globals, &locals), None); + let res = exec.call((&setup_code, &globals), None); if let Err(e) = res { e.print(py); panic!("Error running microbenchmark setup code") } - (globals, locals) + globals }; if bench.iterate { for idx in iteration_counts() { group.throughput(Throughput::Elements(idx as u64)); - group.bench_with_input(BenchmarkId::new("cpython", &bench.name), &idx, |b, idx| { + let id = BenchmarkId::new("cpython", format!("{}[{idx}]", bench.name)); + group.bench_with_input(id, &idx, |b, idx| { b.iter_batched_ref( || bench_setup(Some(*idx)), bench_func, @@ -106,9 +104,12 @@ fn cpy_compile_code<'a>( fn bench_rustpython_code(group: &mut BenchmarkGroup<'_, WallTime>, bench: &MicroBenchmark) { let mut settings = Settings::default(); - settings.path_list.push("Lib/".to_string()); + settings.path_list.push("Lib/".into()); settings.write_bytecode = false; settings.user_site_directory = false; + // Pin the str/bytes hash secret so dict/set probe sequences (and thus + // timings) are reproducible across benchmark runs. + settings.hash_seed = Some(0); let builder = Interpreter::builder(settings); let defs = rustpython_stdlib::stdlib_module_defs(&builder.ctx); @@ -121,13 +122,18 @@ fn bench_rustpython_code(group: &mut BenchmarkGroup<'_, WallTime>, bench: &Micro .compile(&bench.code, Mode::Exec, &bench.name) .expect("Error compiling bench code"); - let bench_func = |scope| { - let res: PyResult = vm.run_code_obj(bench_code.clone(), scope); + let bench_func = |scope: &mut Scope| { + // Keep setup objects alive until after timing, as in the CPython benchmark. + let res: PyResult = vm.run_code_obj(bench_code.clone(), scope.clone()); vm.unwrap_pyresult(res); }; let bench_setup = |iterations| { let scope = vm.new_scope_with_builtins(); + scope + .globals + .set_item("__name__", vm.ctx.new_str("__main__").into(), vm) + .unwrap(); if let Some(idx) = iterations { scope .locals @@ -145,21 +151,22 @@ fn bench_rustpython_code(group: &mut BenchmarkGroup<'_, WallTime>, bench: &Micro if bench.iterate { for idx in iteration_counts() { group.throughput(Throughput::Elements(idx as u64)); - group.bench_with_input( - BenchmarkId::new("rustpython", &bench.name), - &idx, - |b, idx| { - b.iter_batched( - || bench_setup(Some(*idx)), - bench_func, - BatchSize::LargeInput, - ); - }, - ); + let name = if is_codspeed() { + bench.name.clone() + } else { + format!("{}[{idx}]", bench.name) + }; + group.bench_with_input(BenchmarkId::new("rustpython", name), &idx, |b, idx| { + b.iter_batched_ref( + || bench_setup(Some(*idx)), + bench_func, + BatchSize::LargeInput, + ); + }); } } else { group.bench_function(BenchmarkId::new("rustpython", &bench.name), move |b| { - b.iter_batched(|| bench_setup(None), bench_func, BatchSize::LargeInput); + b.iter_batched_ref(|| bench_setup(None), bench_func, BatchSize::LargeInput); }); } }) @@ -200,16 +207,20 @@ pub fn run_micro_benchmark(c: &mut Criterion, benchmark: MicroBenchmark) { pub fn criterion_benchmark(c: &mut Criterion) { let benchmark_dir = Path::new("./benches/microbenchmarks/"); - let dirs: Vec = benchmark_dir + let mut paths: Vec<_> = benchmark_dir .read_dir() .unwrap() - .collect::>() - .unwrap(); + .collect::>>() + .unwrap() + .into_iter() + .map(|entry| entry.path()) + .filter(|path| path.is_file() && path.extension().is_some_and(|ext| ext == "py")) + .collect(); + paths.sort(); - let benchmarks: Vec = dirs + let benchmarks: Vec = paths .iter() - .map(|d| { - let p = d.path(); + .map(|p| { let name = p.file_name().unwrap().to_os_string(); let contents = fs::read_to_string(p).unwrap(); let iterate = contents.contains("ITERATIONS"); diff --git a/benches/test_benchmarks.py b/benches/test_benchmarks.py index 2626461aa79..24744b19a85 100644 --- a/benches/test_benchmarks.py +++ b/benches/test_benchmarks.py @@ -1,34 +1,36 @@ - import os -import time +import subprocess import sys +from pathlib import Path import pytest -import subprocess + +ROOT = Path(__file__).resolve().parent.parent +BENCHES = ROOT / "benches" # Interpreters: -rustpython_exe = '../target/release/rustpython' +default_rustpython = ( + ROOT + / "target" + / "release" + / ("rustpython.exe" if os.name == "nt" else "rustpython") +) +rustpython_exe = str(Path(os.environ.get("RUSTPYTHON", default_rustpython)).resolve()) cpython_exe = sys.executable -pythons = [ - cpython_exe, - rustpython_exe -] +pythons = [cpython_exe, rustpython_exe] # Benchmark scripts: benchmarks = [ - ['benchmarks/nbody.py'], - ['benchmarks/mandelbrot.py'], - ['benchmarks/strings.py'], + BENCHES / "benchmarks" / "nbody.py", + BENCHES / "benchmarks" / "mandelbrot.py", + BENCHES / "microbenchmarks" / "strings.py", ] -exe_ids = ['cpython', 'rustpython'] -benchmark_ids = [benchmark[0].split('/')[-1] for benchmark in benchmarks] - -@pytest.mark.parametrize('exe', pythons, ids=exe_ids) -@pytest.mark.parametrize('args', benchmarks, ids=benchmark_ids) -def test_bench(exe, args, benchmark): - def bench(): - subprocess.run([exe] + args) +exe_ids = ["cpython", "rustpython"] +benchmark_ids = [benchmark.name for benchmark in benchmarks] - benchmark(bench) +@pytest.mark.parametrize("exe", pythons, ids=exe_ids) +@pytest.mark.parametrize("script", benchmarks, ids=benchmark_ids) +def test_bench(exe, script, benchmark): + benchmark(subprocess.run, [exe, str(script)], cwd=ROOT, check=True) diff --git a/crates/capi/Cargo.toml b/crates/capi/Cargo.toml index 671c8d1640c..08c102b4a64 100644 --- a/crates/capi/Cargo.toml +++ b/crates/capi/Cargo.toml @@ -22,6 +22,7 @@ rustpython-stdlib = {workspace = true, features = ["threading"] } rustpython-pylib = { workspace = true } [dev-dependencies] +static_assertions = { workspace = true } pyo3 = { workspace = true, features = ["auto-initialize", "abi3t"] } [lints] diff --git a/crates/capi/src/abstract_.rs b/crates/capi/src/abstract_.rs index 33021e43f6f..c26c8d950c5 100644 --- a/crates/capi/src/abstract_.rs +++ b/crates/capi/src/abstract_.rs @@ -203,7 +203,7 @@ pub unsafe extern "C" fn PyVectorcall_Call( Some(kwnames.as_slice()) }; - callable.vectorcall(args, num_positional_args, kwnames, vm) + callable.vectorcall_call(args, num_positional_args, kwnames, vm) }) } diff --git a/crates/capi/src/abstract_/iter.rs b/crates/capi/src/abstract_/iter.rs index 75834b22657..03f9fb14b1d 100644 --- a/crates/capi/src/abstract_/iter.rs +++ b/crates/capi/src/abstract_/iter.rs @@ -106,7 +106,7 @@ pub unsafe extern "C" fn PyIter_Send( #[cfg(test)] mod tests { use pyo3::prelude::*; - use pyo3::types::{PyAnyMethods, PyIterator, PyList, PySendResult}; + use pyo3::types::{PyAnyMethods, PyIterator, PyList, iterator::PySendResult}; #[test] fn next_item() { diff --git a/crates/capi/src/bytesobject.rs b/crates/capi/src/bytesobject.rs index f9aa9eb8f2e..f1ffb7a903a 100644 --- a/crates/capi/src/bytesobject.rs +++ b/crates/capi/src/bytesobject.rs @@ -1,7 +1,7 @@ use crate::object::define_py_check; use crate::util::FfiPtrExt; use crate::{PyObject, pystate::with_vm}; -use core::ffi::{CStr, c_char, c_int}; +use core::ffi::{CStr, VaList, c_char, c_int, c_long, c_uint, c_ulong, c_void}; use rustpython_vm::builtins::PyBytes; define_py_check!(fn PyBytes_Check, types.bytes_type); @@ -38,6 +38,136 @@ pub unsafe extern "C" fn PyBytes_FromString(s: *const c_char) -> *mut PyObject { }) } +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyBytes_FromFormat(format: *const c_char, args: ...) -> *mut PyObject { + unsafe { PyBytes_FromFormatV(format, args) } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyBytes_FromFormatV( + format: *const c_char, + mut args: VaList<'_>, +) -> *mut PyObject { + with_vm(|vm| { + let format = unsafe { CStr::from_ptr(format) }.to_bytes(); + let mut result = Vec::with_capacity(format.len()); + let mut pos = 0; + while pos < format.len() { + if format[pos] != b'%' { + result.push(format[pos]); + pos += 1; + continue; + } + let start = pos; + pos += 1; + // The C API ignores field width and applies precision only to %s. + while format.get(pos).is_some_and(u8::is_ascii_digit) { + pos += 1; + } + let mut precision = 0usize; + if format.get(pos) == Some(&b'.') { + pos += 1; + while let Some(&digit) = format.get(pos).filter(|b| b.is_ascii_digit()) { + precision = precision + .saturating_mul(10) + .saturating_add((digit - b'0').into()); + pos += 1; + } + } + while format + .get(pos) + .is_some_and(|b| *b != b'%' && !b.is_ascii_alphabetic()) + { + pos += 1; + } + let modifier = if matches!(format.get(pos), Some(b'l' | b'z')) + && matches!(format.get(pos + 1), Some(b'd' | b'u')) + { + let modifier = format[pos]; + pos += 1; + Some(modifier) + } else { + None + }; + match format.get(pos) { + Some(b'c') => { + let value = unsafe { args.next_arg::() }; + let value = u8::try_from(value).map_err(|_| { + vm.new_overflow_error( + "PyBytes_FromFormatV(): %c format expects an integer in range [0; 255]", + ) + })?; + result.push(value); + } + Some(b'd') => { + let value = match modifier { + Some(b'l') => unsafe { args.next_arg::() }.to_string(), + Some(b'z') => unsafe { args.next_arg::() }.to_string(), + _ => unsafe { args.next_arg::() }.to_string(), + }; + result.extend_from_slice(value.as_bytes()); + } + Some(b'u') => { + let value = match modifier { + Some(b'l') => unsafe { args.next_arg::() }.to_string(), + Some(b'z') => unsafe { args.next_arg::() }.to_string(), + _ => unsafe { args.next_arg::() }.to_string(), + }; + result.extend_from_slice(value.as_bytes()); + } + Some(b'i') => result + .extend_from_slice(unsafe { args.next_arg::() }.to_string().as_bytes()), + Some(b'x') => result.extend_from_slice( + format!("{:x}", unsafe { args.next_arg::() } as c_uint).as_bytes(), + ), + Some(b's') => { + let string = unsafe { args.next_arg::<*const c_char>() }; + if precision == 0 { + result.extend_from_slice(unsafe { CStr::from_ptr(string) }.to_bytes()); + } else { + // A precision-limited string need not have a terminator + // beyond the specified readable region. + for offset in 0..precision { + let byte = unsafe { *string.add(offset) } as u8; + if byte == 0 { + break; + } + result.push(byte); + } + } + } + Some(b'p') => { + let pointer = unsafe { args.next_arg::<*const c_void>() }; + // Preserve the platform's %p spelling, including Windows + // uppercase digits, but always supply the C API's 0x prefix. + let mut buffer = [0 as c_char; 2 * size_of::() + 16]; + unsafe { + libc::snprintf(buffer.as_mut_ptr(), buffer.len(), c"%p".as_ptr(), pointer); + } + let pointer = unsafe { CStr::from_ptr(buffer.as_ptr()) }.to_bytes(); + result.extend_from_slice(b"0x"); + result.extend_from_slice( + if pointer.starts_with(b"0x") || pointer.starts_with(b"0X") { + &pointer[2..] + } else { + pointer + }, + ); + } + Some(b'%') => result.push(b'%'), + _ => { + // The first unrecognized format copies the remaining + // format verbatim, without consuming any more arguments. + result.extend_from_slice(&format[start..]); + break; + } + } + pos += 1; + } + Ok(vm.ctx.new_bytes(result)) + }) +} + #[unsafe(no_mangle)] pub unsafe extern "C" fn PyBytes_FromObject(obj: *mut PyObject) -> *mut PyObject { with_vm(|vm| { diff --git a/crates/capi/src/ceval.rs b/crates/capi/src/ceval.rs index 4064b289caf..64c2b567fe5 100644 --- a/crates/capi/src/ceval.rs +++ b/crates/capi/src/ceval.rs @@ -1,12 +1,12 @@ use crate::pyframe::PyFrameObject; use crate::pystate::with_vm; use crate::unicodeobject::decode_fsdefault_and_size; -use crate::util::FfiPtrExt; +use crate::util::{CStrExt, FfiPtrExt}; use core::ffi::{CStr, c_char, c_int}; -use rustpython_vm::builtins::{PyCode, PyDict}; +use rustpython_vm::builtins::{PyAnyDict, PyCode}; use rustpython_vm::function::ArgMapping; use rustpython_vm::scope::Scope; -use rustpython_vm::{AsObject, PyObject, TryFromObject}; +use rustpython_vm::{AsObject, PyObject, PyRef, TryFromObject}; use rustpython_vm::{PyObjectRef, version}; #[unsafe(no_mangle)] @@ -32,12 +32,17 @@ pub unsafe extern "C" fn PyEval_EvalCode( ) -> *mut PyObject { with_vm(|vm| { let code = unsafe { co.assume_borrowed_and_cast::(vm) }?; - let globals = unsafe { globals.assume_borrowed_and_cast::(vm) }?; + let globals = PyRef::::try_from_object( + vm, + unsafe { globals.assume_borrowed() }.to_owned(), + )?; let locals = unsafe { locals.assume_borrowed_or_opt() } .map(|obj| ArgMapping::try_from_object(vm, obj.to_owned())) .transpose()?; - let scope = Scope::with_builtins(locals, globals.to_owned(), vm); + let locals = locals.or_else(|| Some(ArgMapping::from_anydict_exact(globals.clone()))); + // Unlike Python's eval/exec, this API does not insert __builtins__. + let scope = Scope::new(locals, globals); vm.run_code_obj(code.to_owned(), scope) }) @@ -67,8 +72,7 @@ pub extern "C" fn PyEval_GetBuiltins() -> *mut PyObject { pub extern "C" fn PyEval_GetFrame() -> *mut PyFrameObject { with_vm(|vm| -> *mut PyObject { vm.current_frame() - .map(|frame| frame.as_object().as_raw().cast_mut()) - .unwrap_or_default() + .map_or_default(|frame| frame.as_object().as_raw().cast_mut()) }) .cast() } @@ -86,17 +90,15 @@ pub extern "C" fn PyEval_GetFrameBuiltins() -> *mut PyObject { #[unsafe(no_mangle)] pub extern "C" fn PyEval_GetFrameGlobals() -> *mut PyObject { with_vm(|vm| { - vm.current_frame() - .map(|frame| { - frame - .iframe() - .globals() - .as_object() - .to_owned() - .into_raw() - .as_ptr() - }) - .unwrap_or_default() + vm.current_frame().map_or_default(|frame| { + frame + .iframe() + .globals() + .as_object() + .to_owned() + .into_raw() + .as_ptr() + }) }) } @@ -115,8 +117,7 @@ pub extern "C" fn PyEval_GetFrameLocals() -> *mut PyObject { pub extern "C" fn PyEval_GetGlobals() -> *mut PyObject { with_vm(|vm| { vm.current_frame() - .map(|frame| frame.iframe().globals().as_object().as_raw()) - .unwrap_or_default() + .map_or_default(|frame| frame.iframe().globals().as_object().as_raw()) }) } @@ -157,10 +158,21 @@ pub unsafe extern "C" fn PyEval_GetFuncDesc(func: *mut PyObject) -> *const c_cha }) } +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Py_EnterRecursiveCall(where_: *const c_char) -> c_int { + with_vm(|vm| vm.enter_recursive_call(unsafe { where_.try_as_str(vm)? })) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn Py_LeaveRecursiveCall() { + with_vm(|vm| vm.leave_recursive_call()) +} + #[cfg(test)] mod tests { + use super::{Py_EnterRecursiveCall, Py_LeaveRecursiveCall}; use alloc::ffi::CString; - use pyo3::exceptions::PyException; + use pyo3::exceptions::{PyException, PyRecursionError}; use pyo3::prelude::*; #[pyfunction] @@ -268,4 +280,23 @@ assert not hidden_leaked .unwrap(); }) } + + #[test] + fn recursion_error() { + fn recurse(py: Python<'_>) -> PyResult<()> { + unsafe { + if Py_EnterRecursiveCall(c"".as_ptr().cast()) != 0 { + return Err(PyErr::fetch(py)); + }; + let result = recurse(py); + Py_LeaveRecursiveCall(); + result + } + } + + Python::attach(|py| { + let err = recurse(py).unwrap_err(); + assert!(err.is_instance_of::(py)); + }) + } } diff --git a/crates/capi/src/descrobject.rs b/crates/capi/src/descrobject.rs index 1e53b72e0ce..20eab9e27bf 100644 --- a/crates/capi/src/descrobject.rs +++ b/crates/capi/src/descrobject.rs @@ -1,5 +1,5 @@ use crate::PyObject; -use crate::methodobject::{PyMethodDef, build_method_def}; +use crate::methodobject::PyMethodDef; use crate::object::PyTypeObject; use crate::pystate::with_vm; use crate::util::{CStrExt, FfiPtrExt}; @@ -201,7 +201,7 @@ pub unsafe extern "C" fn PyDescr_NewMethod( method: *mut PyMethodDef, ) -> *mut PyObject { with_vm(|vm| { - let method = build_method_def(vm, unsafe { &*method }, true)?; + let method = unsafe { &*method }.build_method_def(vm)?; Ok(method.build_method(unsafe { typ.assume_borrowed() }, vm)) }) } @@ -212,8 +212,8 @@ pub unsafe extern "C" fn PyDescr_NewClassMethod( method: *mut PyMethodDef, ) -> *mut PyObject { with_vm(|vm| { - let method = build_method_def(vm, unsafe { &*method }, true)?; - Ok(method.build_method(unsafe { typ.assume_borrowed() }, vm)) + let method = unsafe { &*method }.build_method_def(vm)?; + Ok(method.build_classmethod(unsafe { typ.assume_borrowed() }, vm)) }) } diff --git a/crates/capi/src/dictobject.rs b/crates/capi/src/dictobject.rs index 2c3eedff3ba..1e6fab1b131 100644 --- a/crates/capi/src/dictobject.rs +++ b/crates/capi/src/dictobject.rs @@ -4,9 +4,8 @@ use crate::pystate::with_vm; use crate::util::{CStrExt, FfiPtrExt}; use core::ffi::{c_char, c_int}; use core::ptr::NonNull; -use rustpython_vm::AsObject; -use rustpython_vm::PyPayload; -use rustpython_vm::builtins::PyDict; +use rustpython_vm::builtins::{PyAnyDict, PyDict, PyFrozenDict}; +use rustpython_vm::{AsObject, Py, PyPayload, PyResult, VirtualMachine}; define_py_check!(fn PyDict_Check, types.dict_type); define_py_check!(exact fn PyDict_CheckExact, types.dict_type); @@ -14,6 +13,27 @@ define_py_check!(fn PyDictKeys_Check, types.dict_keys_type); define_py_check!(fn PyDictValues_Check, types.dict_values_type); define_py_check!(fn PyDictItems_Check, types.dict_items_type); +fn any_dict<'a>(dict: &'a PyObject, vm: &VirtualMachine) -> PyResult<&'a PyAnyDict> { + PyAnyDict::from_object(dict) + .ok_or_else(|| vm.new_system_error("bad argument to internal function")) +} + +fn writable_dict<'a>( + dict: &'a PyObject, + operation: &str, + vm: &VirtualMachine, +) -> PyResult<&'a Py> { + dict.downcast_ref::().ok_or_else(|| { + if dict.downcast_ref::().is_some() { + vm.new_type_error(format!( + "frozendict object does not support item {operation}" + )) + } else { + vm.new_system_error("bad argument to internal function") + } + }) +} + #[unsafe(no_mangle)] pub extern "C" fn PyDict_New() -> *mut PyObject { with_vm(|vm| vm.ctx.new_dict()) @@ -21,10 +41,10 @@ pub extern "C" fn PyDict_New() -> *mut PyObject { #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Clear(dict: *mut PyObject) { - with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; - dict.clear(); - Ok(()) + with_vm(|_vm| { + if let Some(dict) = unsafe { dict.assume_borrowed() }.downcast_ref::() { + dict.clear(); + } }) } @@ -35,7 +55,7 @@ pub unsafe extern "C" fn PyDict_SetItem( val: *mut PyObject, ) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = writable_dict(unsafe { dict.assume_borrowed() }, "assignment", vm)?; let key = unsafe { key.assume_borrowed() }; let value = unsafe { val.assume_borrowed() }.to_owned(); dict.inner_setitem(key, value, vm) @@ -49,8 +69,8 @@ pub unsafe extern "C" fn PyDict_SetItemString( val: *mut PyObject, ) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; let key = unsafe { key.try_as_str(vm) }?; + let dict = writable_dict(unsafe { dict.assume_borrowed() }, "assignment", vm)?; let value = unsafe { val.assume_borrowed() }.to_owned(); dict.inner_setitem(key, value, vm) }) @@ -59,12 +79,14 @@ pub unsafe extern "C" fn PyDict_SetItemString( #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_GetItem(dict: *mut PyObject, key: *mut PyObject) -> *mut PyObject { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let Some(dict) = PyAnyDict::from_object(unsafe { dict.assume_borrowed() }) else { + return core::ptr::null_mut(); + }; let key = unsafe { key.assume_borrowed() }; match dict.inner_getitem_opt(key, vm) { - Ok(Some(value)) => Ok(value.as_object().as_raw().cast_mut()), - Ok(None) | Err(_) => Ok(core::ptr::null_mut()), + Ok(Some(value)) => value.as_object().as_raw().cast_mut(), + Ok(None) | Err(_) => core::ptr::null_mut(), } }) } @@ -75,7 +97,7 @@ pub unsafe extern "C" fn PyDict_GetItemWithError( key: *mut PyObject, ) -> *mut PyObject { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = any_dict(unsafe { dict.assume_borrowed() }, vm)?; let key = unsafe { key.assume_borrowed() }; if let Some(value) = dict.inner_getitem_opt(key, vm)? { @@ -92,12 +114,16 @@ pub unsafe extern "C" fn PyDict_GetItemString( key: *const c_char, ) -> *mut PyObject { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; - let key = unsafe { key.try_as_str(vm) }?; + let Ok(key) = (unsafe { key.try_as_str(vm) }) else { + return core::ptr::null_mut(); + }; + let Some(dict) = PyAnyDict::from_object(unsafe { dict.assume_borrowed() }) else { + return core::ptr::null_mut(); + }; - match dict.inner_getitem_opt(key, vm)? { - Some(value) => Ok(value.as_object().as_raw().cast_mut()), - None => Ok(core::ptr::null_mut()), + match dict.inner_getitem_opt(key, vm) { + Ok(Some(value)) => value.as_object().as_raw().cast_mut(), + Ok(None) | Err(_) => core::ptr::null_mut(), } }) } @@ -112,8 +138,8 @@ pub unsafe extern "C" fn PyDict_GetItemStringRef( unsafe { *result = core::ptr::null_mut(); } - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; let key = unsafe { key.try_as_str(vm) }?; + let dict = any_dict(unsafe { dict.assume_borrowed() }, vm)?; if let Some(value) = dict.inner_getitem_opt(key, vm)? { unsafe { @@ -134,7 +160,7 @@ pub unsafe extern "C" fn PyDict_GetItemRef( ) -> c_int { with_vm(|vm| { unsafe { *result = core::ptr::null_mut() }; - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = any_dict(unsafe { dict.assume_borrowed() }, vm)?; let key = unsafe { key.assume_borrowed() }; if let Some(value) = dict.inner_getitem_opt(key, vm)? { @@ -165,7 +191,7 @@ pub unsafe extern "C" fn PyDict_SetDefaultRef( result.write(core::ptr::null_mut()); } } - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = writable_dict(unsafe { dict.assume_borrowed() }, "assignment", vm)?; let key = unsafe { key.assume_borrowed() }; if let Some(value) = dict.inner_getitem_opt(key, vm)? { @@ -191,7 +217,9 @@ pub unsafe extern "C" fn PyDict_SetDefaultRef( #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Size(dict: *mut PyObject) -> isize { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = unsafe { dict.assume_borrowed_or_opt() } + .ok_or_else(|| vm.new_system_error("bad argument to internal function"))?; + let dict = any_dict(dict, vm)?; Ok(dict.__len__()) }) } @@ -199,7 +227,7 @@ pub unsafe extern "C" fn PyDict_Size(dict: *mut PyObject) -> isize { #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Contains(dict: *mut PyObject, key: *mut PyObject) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = any_dict(unsafe { dict.assume_borrowed() }, vm)?; let key = unsafe { key.assume_borrowed() }; Ok(dict.inner_getitem_opt(key, vm)?.is_some()) }) @@ -208,7 +236,9 @@ pub unsafe extern "C" fn PyDict_Contains(dict: *mut PyObject, key: *mut PyObject #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Copy(dict: *mut PyObject) -> *mut PyObject { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = unsafe { dict.assume_borrowed_or_opt() } + .and_then(|dict| dict.downcast_ref::()) + .ok_or_else(|| vm.new_system_error("bad argument to internal function"))?; Ok(dict.copy().into_ref(&vm.ctx)) }) } @@ -216,8 +246,12 @@ pub unsafe extern "C" fn PyDict_Copy(dict: *mut PyObject) -> *mut PyObject { #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_DelItem(dict: *mut PyObject, key: *mut PyObject) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = unsafe { dict.assume_borrowed() }; let key = unsafe { key.assume_borrowed() }; + if dict.downcast_ref::().is_some() { + PyFrozenDict::key_hash(key, vm)?; + } + let dict = writable_dict(dict, "deletion", vm)?; dict.del_item(key, vm) }) } @@ -225,8 +259,8 @@ pub unsafe extern "C" fn PyDict_DelItem(dict: *mut PyObject, key: *mut PyObject) #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_DelItemString(dict: *mut PyObject, key: *const c_char) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; let key = unsafe { key.try_as_str(vm) }?; + let dict = writable_dict(unsafe { dict.assume_borrowed() }, "deletion", vm)?; dict.del_item(key, vm) }) } @@ -234,7 +268,9 @@ pub unsafe extern "C" fn PyDict_DelItemString(dict: *mut PyObject, key: *const c #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Items(dict: *mut PyObject) -> *mut PyObject { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = unsafe { dict.assume_borrowed_or_opt() } + .ok_or_else(|| vm.new_system_error("bad argument to internal function"))?; + let dict = any_dict(dict, vm)?; let items = dict .items_vec() .into_iter() @@ -247,7 +283,9 @@ pub unsafe extern "C" fn PyDict_Items(dict: *mut PyObject) -> *mut PyObject { #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Keys(dict: *mut PyObject) -> *mut PyObject { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = unsafe { dict.assume_borrowed_or_opt() } + .ok_or_else(|| vm.new_system_error("bad argument to internal function"))?; + let dict = any_dict(dict, vm)?; Ok(vm.ctx.new_list(dict.keys_vec())) }) } @@ -255,7 +293,9 @@ pub unsafe extern "C" fn PyDict_Keys(dict: *mut PyObject) -> *mut PyObject { #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Values(dict: *mut PyObject) -> *mut PyObject { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = unsafe { dict.assume_borrowed_or_opt() } + .ok_or_else(|| vm.new_system_error("bad argument to internal function"))?; + let dict = any_dict(dict, vm)?; Ok(vm.ctx.new_list(dict.values_vec())) }) } @@ -267,7 +307,7 @@ pub unsafe extern "C" fn PyDict_Merge( override_: c_int, ) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = writable_dict(unsafe { dict.assume_borrowed() }, "assignment", vm)?; let other = unsafe { other.assume_borrowed() }.to_owned(); if override_ != 0 { dict.merge_object(other, vm) @@ -280,7 +320,7 @@ pub unsafe extern "C" fn PyDict_Merge( #[unsafe(no_mangle)] pub unsafe extern "C" fn PyDict_Update(dict: *mut PyObject, other: *mut PyObject) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = writable_dict(unsafe { dict.assume_borrowed() }, "assignment", vm)?; let other = unsafe { other.assume_borrowed() }.to_owned(); dict.merge_object(other, vm) }) @@ -293,7 +333,7 @@ pub unsafe extern "C" fn PyDict_MergeFromSeq2( override_: c_int, ) -> c_int { with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + let dict = writable_dict(unsafe { dict.assume_borrowed() }, "assignment", vm)?; let seq2 = unsafe { seq2.assume_borrowed() }; dict.merge_from_seq2(seq2, override_ != 0, vm) }) @@ -306,8 +346,10 @@ pub unsafe extern "C" fn PyDict_Next( key: *mut *mut PyObject, value: *mut *mut PyObject, ) -> c_int { - with_vm(|vm| { - let dict = unsafe { dict.assume_borrowed_and_cast::(vm) }?; + with_vm(|_vm| { + let Some(dict) = PyAnyDict::from_object(unsafe { dict.assume_borrowed() }) else { + return false; + }; let index = unsafe { *pos } as usize; if let Some((next_pos, k, v)) = dict.next_entry(index) { @@ -320,9 +362,9 @@ pub unsafe extern "C" fn PyDict_Next( value.write(v.as_object().as_raw().cast_mut()); } } - Ok(true) + true } else { - Ok(false) + false } }) } diff --git a/crates/capi/src/fileobject.rs b/crates/capi/src/fileobject.rs new file mode 100644 index 00000000000..c45f9f06981 --- /dev/null +++ b/crates/capi/src/fileobject.rs @@ -0,0 +1,95 @@ +use crate::PyObject; +use crate::pystate::with_vm; +use crate::util::{CStrExt, FfiPtrExt}; +use core::ffi::{c_char, c_int}; +use rustpython_vm::stdlib::_io::{self, Fildes, OpenArgs}; +use rustpython_vm::{PyResult, TryFromObject}; + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyFile_FromFd( + fd: c_int, + _name: *const c_char, + mode: *const c_char, + buffering: c_int, + encoding: *const c_char, + errors: *const c_char, + newline: *const c_char, + closefd: c_int, +) -> *mut PyObject { + with_vm(|vm| { + let mode = unsafe { mode.try_as_str(vm) }?; + let encoding = unsafe { encoding.try_as_str_opt(vm) }?.map(|s| vm.ctx.new_utf8_str(s)); + let errors = unsafe { errors.try_as_str_opt(vm) }?.map(|s| vm.ctx.new_utf8_str(s)); + let newline = unsafe { newline.try_as_str_opt(vm) }?.map(|s| vm.ctx.new_utf8_str(s)); + _io::open( + vm.ctx.new_int(fd).into(), + Some(mode), + OpenArgs { + buffering: buffering as isize, + encoding, + errors, + newline, + closefd: closefd != 0, + ..Default::default() + }, + vm, + ) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyFile_GetLine(file: *mut PyObject, n: c_int) -> *mut PyObject { + with_vm(|vm| { + let file = unsafe { file.assume_borrowed() }; + let line = if n > 0 { + vm.call_method(file, "readline", (n,))? + } else { + vm.call_method(file, "readline", ())? + }; + if n < 0 && line.length(vm)? == 0 { + Err(vm.new_eof_error("EOF when reading a line")) + } else { + Ok(line) + } + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyFile_WriteObject( + obj: *mut PyObject, + file: *mut PyObject, + flags: c_int, +) -> c_int { + with_vm(|vm| -> PyResult<()> { + let file = unsafe { file.assume_borrowed() }; + let text = if let Some(obj) = unsafe { obj.assume_borrowed_or_opt() } { + if flags & 1 != 0 { + obj.str(vm)? + } else { + obj.repr(vm)? + } + } else { + vm.ctx.new_str("") + }; + vm.call_method(file, "write", (text,))?; + Ok(()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyFile_WriteString(s: *const c_char, file: *mut PyObject) -> c_int { + with_vm(|vm| -> PyResult<()> { + let s = unsafe { s.try_as_str(vm) }?; + let file = unsafe { file.assume_borrowed() }; + vm.call_method(file, "write", (s,))?; + Ok(()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyObject_AsFileDescriptor(obj: *mut PyObject) -> c_int { + with_vm(|vm| { + let obj = unsafe { obj.assume_borrowed() }.to_owned(); + Fildes::try_from_object(vm, obj).map(|fd| fd.0) + }) +} diff --git a/crates/capi/src/import.rs b/crates/capi/src/import.rs index ba15530a6c9..cd9095b66c1 100644 --- a/crates/capi/src/import.rs +++ b/crates/capi/src/import.rs @@ -1,18 +1,14 @@ use crate::util::{CStrExt, FfiPtrExt}; use crate::{PyObject, pystate::with_vm}; use core::ffi::c_char; -use rustpython_vm::builtins::{PyCode, PyDict, PyModule, PyStr}; -use rustpython_vm::import::import_code_obj; +use rustpython_vm::builtins::{PyCode, PyStr}; +use rustpython_vm::import::{add_module, import_code_obj}; #[unsafe(no_mangle)] pub unsafe extern "C" fn PyImport_Import(name: *mut PyObject) -> *mut PyObject { with_vm(|vm| { let name = unsafe { name.assume_borrowed_and_cast::(vm) }?; - let _ = vm.import(name, 0)?; - - vm.sys_module - .get_attr(rustpython_vm::identifier!(vm, modules), vm)? - .get_item(name, vm) + rustpython_vm::import::import_module(vm, name) }) } @@ -21,24 +17,7 @@ pub unsafe extern "C" fn PyImport_AddModuleRef(name: *const c_char) -> *mut PyOb with_vm(|vm| { let name = unsafe { name.try_as_str(vm) }?; - let sys_modules = vm - .sys_module - .get_attr(rustpython_vm::identifier!(vm, modules), vm)?; - - sys_modules - .try_downcast_ref::(vm)? - .get_item_opt(name, vm)? - .map_or_else( - || { - let module = vm.new_module(name, vm.ctx.new_dict(), None); - sys_modules.set_item(name, module.clone().into(), vm)?; - Ok(module) - }, - |module| { - let module = module.try_downcast_ref::(vm)?; - Ok(module.to_owned()) - }, - ) + add_module(vm, name) }) } diff --git a/crates/capi/src/lib.rs b/crates/capi/src/lib.rs index 90ef71da7a8..026788e61a3 100644 --- a/crates/capi/src/lib.rs +++ b/crates/capi/src/lib.rs @@ -4,7 +4,7 @@ use crate::pyerrors::init_exception_statics; use crate::pylifecycle::{MAIN_INTERP, MAIN_INTERP_PTR}; use core::sync::atomic::Ordering; pub use rustpython_vm::PyObject; -use rustpython_vm::{Context, Interpreter}; +use rustpython_vm::{Context, Interpreter, VirtualMachine}; use std::sync::MutexGuard; extern crate alloc; @@ -19,6 +19,7 @@ pub mod complexobject; pub mod critical_section; pub mod descrobject; pub mod dictobject; +pub mod fileobject; pub mod floatobject; pub mod genericaliasobject; pub mod import; @@ -32,6 +33,7 @@ pub mod moduleobject; pub mod object; pub mod objimpl; pub mod osmodule; +pub mod pybuffer; pub mod pycapsule; pub mod pyerrors; pub mod pyframe; @@ -43,6 +45,7 @@ pub mod refcount; pub mod setobject; pub mod sliceobject; pub mod slots; +pub mod sysmodule; pub mod traceback; pub mod tupleobject; pub mod unicodeobject; @@ -70,3 +73,32 @@ pub fn init_main_interpreter(interpreter: Interpreter) { Ordering::Release, ); } + +/// Py_RunMain for an interpreter that C API threads can attach to. +/// +/// `f` reports its own errors and returns the exit code. +pub fn run_main_interpreter( + mut interpreter: Interpreter, + f: impl FnOnce(&VirtualMachine) -> u32, +) -> u32 { + let main_thread = interpreter.take_main_thread(); + init_main_interpreter(interpreter); + + struct RegistrationGuard; + impl Drop for RegistrationGuard { + fn drop(&mut self) { + let mut registered = MAIN_INTERP + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + MAIN_INTERP_PTR.store(core::ptr::null_mut(), Ordering::Release); + let _interpreter = registered.take(); + drop(registered); + } + } + let _registration = RegistrationGuard; + + // The registered interpreter is an inactive worker-VM template. Running + // the original VM locally preserves main-thread state without keeping the + // global mutex locked across Python execution or finalization callbacks. + main_thread.run_main(f) +} diff --git a/crates/capi/src/longobject.rs b/crates/capi/src/longobject.rs index 89c0868a3d1..f68548d5b00 100644 --- a/crates/capi/src/longobject.rs +++ b/crates/capi/src/longobject.rs @@ -538,7 +538,7 @@ pub unsafe extern "C" fn PyLongWriter_Create( ndigits: isize, digits: *mut *mut c_void, ) -> *mut PyLongWriter { - with_vm::, _>(|vm| { + with_vm(|vm| { unsafe { *digits = core::ptr::null_mut(); } @@ -577,9 +577,8 @@ pub unsafe extern "C" fn PyLongWriter_Create( *digits = writer.digits.as_mut_ptr().cast(); } - Ok(Box::into_raw(writer).cast()) + Ok(Box::into_raw(writer)) }) - .cast() } #[unsafe(no_mangle)] diff --git a/crates/capi/src/methodobject.rs b/crates/capi/src/methodobject.rs index 9868db36cac..e2ff8759bdb 100644 --- a/crates/capi/src/methodobject.rs +++ b/crates/capi/src/methodobject.rs @@ -5,7 +5,8 @@ use crate::pystate::with_vm; use crate::util::{CStrExt, FfiPtrExt}; use core::ffi::{c_char, c_int}; use core::fmt::Debug; -use rustpython_vm::function::{FuncArgs, HeapMethodDef, ItemDoc, PosArgs, PyMethodFlags}; +use rustpython_vm::function::{Callee, FuncArgs, HeapMethodDef, ItemDoc, PosArgs, PyMethodFlags}; +use rustpython_vm::types::c_slots::{kwargs_ptr, split_args}; use rustpython_vm::{AsObject, PyObjectRef, PyRef, PyResult, VirtualMachine}; define_py_check!(fn PyCFunction_Check, types.builtin_function_or_method_type); @@ -32,29 +33,126 @@ impl PyMethodDef { } }) } + + pub(crate) fn build_method_def(&self, vm: &VirtualMachine) -> PyResult> { + let name = unsafe { self.ml_name.try_as_str(vm) }?; + + let doc = unsafe { self.ml_doc.try_as_str_opt(vm) }?; + let doc = doc + .filter(|doc| !doc.is_empty()) + .map_or(ItemDoc::NONE, |doc| { + let text: &'static str = Box::leak(doc.to_owned().into_boxed_str()); + ItemDoc::static_text(text) + }); + + let flags = PyMethodFlags::from_bits(self.ml_flags as u32) + .ok_or_else(|| vm.new_system_error("PyMethodDef contains unknown flags"))?; + + let method = self.ml_meth; + + if flags.contains(PyMethodFlags::METHOD) { + return Err(vm.new_system_error("METH_METHOD is not supported on abi3")); + } + + let call_flags = flags + & (PyMethodFlags::VARARGS + | PyMethodFlags::KEYWORDS + | PyMethodFlags::NOARGS + | PyMethodFlags::O + | PyMethodFlags::FASTCALL); + + bitflags::bitflags_match!(call_flags, { + PyMethodFlags::NOARGS => { + let callable = move |vm: &VirtualMachine, receiver: Option<&rustpython_vm::PyObject>, args: FuncArgs, callee: Callee| { + let receiver = receiver.filter(|_| !flags.contains(PyMethodFlags::STATIC)); + args.bind_for::<()>(vm, callee)?; + let slf_ptr = self_ptr(receiver); + unsafe { + (method.PyCFunction)(slf_ptr, core::ptr::null_mut()).assume_owned_or_err(vm) + } + }; + Ok(vm.ctx.new_raw_method_def(name, callable, flags, doc)) + }, + PyMethodFlags::VARARGS => { + let callable = move |vm: &VirtualMachine, receiver: Option<&rustpython_vm::PyObject>, args: FuncArgs, callee: Callee| { + let receiver = receiver.filter(|_| !flags.contains(PyMethodFlags::STATIC)); + let (args,) = args.bind_for::<(PosArgs,)>(vm, callee)?; + unsafe { call_function(vm, method, args.into(), receiver) } + }; + Ok(vm.ctx.new_raw_method_def(name, callable, flags, doc)) + }, + PyMethodFlags::VARARGS | PyMethodFlags::KEYWORDS => { + let callable = move |vm: &VirtualMachine, receiver: Option<&rustpython_vm::PyObject>, args: FuncArgs, _callee: Callee| unsafe { + let receiver = receiver.filter(|_| !flags.contains(PyMethodFlags::STATIC)); + call_function_with_keywords(vm, method, args, receiver) + }; + Ok(vm.ctx.new_raw_method_def(name, callable, flags, doc)) + }, + PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS => { + let callable = move |vm: &VirtualMachine, receiver: Option<&rustpython_vm::PyObject>, args: FuncArgs, _callee: Callee| unsafe { + let receiver = receiver.filter(|_| !flags.contains(PyMethodFlags::STATIC)); + call_fast_function_with_keywords(vm, method, args, receiver) + }; + Ok(vm.ctx.new_raw_method_def(name, callable, flags, doc)) + }, + PyMethodFlags::FASTCALL => { + let callable = move |vm: &VirtualMachine, receiver: Option<&rustpython_vm::PyObject>, args: FuncArgs, callee: Callee| { + let receiver = receiver.filter(|_| !flags.contains(PyMethodFlags::STATIC)); + let (args,) = args.bind_for::<(PosArgs,)>(vm, callee)?; + unsafe { call_fast_function(vm, method, args, receiver) } + }; + Ok(vm.ctx.new_raw_method_def(name, callable, flags, doc)) + }, + PyMethodFlags::O => { + let callable = move |vm: &VirtualMachine, receiver: Option<&rustpython_vm::PyObject>, args: FuncArgs, callee: Callee| { + let receiver = receiver.filter(|_| !flags.contains(PyMethodFlags::STATIC)); + let (arg,) = args.bind_for::<(PyObjectRef,)>(vm, callee)?; + let slf_ptr = self_ptr(receiver); + unsafe { + (method.PyCFunction)(slf_ptr, arg.as_raw().cast_mut()).assume_owned_or_err(vm) + } + }; + Ok(vm.ctx.new_raw_method_def(name, callable, flags, doc)) + }, + _ => { + Err(vm.new_system_error(format!( + "function {name} has unsupported or invalid calling-convention flags: {flags:?}" + ))) + }, + }) + } } +pub type PyCFunction = + unsafe extern "C" fn(slf: *mut PyObject, args: *mut PyObject) -> *mut PyObject; + +pub type PyCFunctionWithKeywords = unsafe extern "C" fn( + slf: *mut PyObject, + args: *mut PyObject, + kwargs: *mut PyObject, +) -> *mut PyObject; + +pub type PyCFunctionFast = unsafe extern "C" fn( + slf: *mut PyObject, + args: *const *mut PyObject, + nargs: isize, +) -> *mut PyObject; + +pub type PyCFunctionFastWithKeywords = unsafe extern "C" fn( + slf: *mut PyObject, + args: *const *mut PyObject, + nargs: isize, + kwnames: *mut PyObject, +) -> *mut PyObject; + #[repr(C)] #[derive(Copy, Clone)] #[allow(non_snake_case)] pub union PyMethodPointer { - pub PyCFunction: unsafe extern "C" fn(slf: *mut PyObject, args: *mut PyObject) -> *mut PyObject, - pub PyCFunctionWithKeywords: unsafe extern "C" fn( - slf: *mut PyObject, - args: *mut PyObject, - kwargs: *mut PyObject, - ) -> *mut PyObject, - pub PyCFunctionFast: unsafe extern "C" fn( - slf: *mut PyObject, - args: *const *mut PyObject, - nargs: isize, - ) -> *mut PyObject, - pub PyCFunctionFastWithKeywords: unsafe extern "C" fn( - slf: *mut PyObject, - args: *const *mut PyObject, - nargs: isize, - kwnames: *mut PyObject, - ) -> *mut PyObject, + pub PyCFunction: PyCFunction, + pub PyCFunctionWithKeywords: PyCFunctionWithKeywords, + pub PyCFunctionFast: PyCFunctionFast, + pub PyCFunctionFastWithKeywords: PyCFunctionFastWithKeywords, } impl Debug for PyMethodPointer { @@ -63,150 +161,32 @@ impl Debug for PyMethodPointer { } } -pub(crate) fn build_method_def( - vm: &VirtualMachine, - ml: &PyMethodDef, - has_self: bool, -) -> PyResult> { - let name = unsafe { ml.ml_name.try_as_str(vm) }?; - - let doc = unsafe { ml.ml_doc.try_as_str_opt(vm) }?; - let doc = doc - .filter(|doc| !doc.is_empty()) - .map_or(ItemDoc::NONE, |doc| { - let text: &'static str = Box::leak(doc.to_owned().into_boxed_str()); - ItemDoc::static_text(text) - }); - - let flags = PyMethodFlags::from_bits(ml.ml_flags as u32) - .ok_or_else(|| vm.new_system_error("PyMethodDef contains unknown flags"))?; - let has_self = has_self && !flags.contains(PyMethodFlags::STATIC); - - let method = ml.ml_meth; - - if flags.contains(PyMethodFlags::METHOD) { - return Err(vm.new_system_error("METH_METHOD is not supported on abi3")); - } - - let call_flags = flags - & (PyMethodFlags::VARARGS - | PyMethodFlags::KEYWORDS - | PyMethodFlags::NOARGS - | PyMethodFlags::O - | PyMethodFlags::FASTCALL); - - bitflags::bitflags_match!(call_flags, { - PyMethodFlags::NOARGS => { - if has_self { - let callable = move |zelf: PyObjectRef, vm: &VirtualMachine| unsafe { - let f = method.PyCFunction; - f(zelf.as_raw().cast_mut(), core::ptr::null_mut()).assume_owned_or_err(vm) - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - } else { - let callable = move |vm: &VirtualMachine| unsafe { - let f = method.PyCFunction; - f(core::ptr::null_mut(), core::ptr::null_mut()).assume_owned_or_err(vm) - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - } - }, - PyMethodFlags::VARARGS => { - let callable = move |args: PosArgs, vm: &VirtualMachine| unsafe { - call_function(vm, method, flags, Some(args)) - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - }, - PyMethodFlags::VARARGS | PyMethodFlags::KEYWORDS => { - let callable = move | args: FuncArgs, vm: &VirtualMachine| unsafe { - call_function_with_keywords(vm, method, flags, args) - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - }, - PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS => { - let callable = move |args: FuncArgs, vm: &VirtualMachine| unsafe { - call_fast_function_with_keywords(vm, method, flags, args) - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - }, - PyMethodFlags::FASTCALL => { - let callable = move |args: PosArgs, vm: &VirtualMachine| unsafe { - call_fast_function(vm, method, flags, args) - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - }, - PyMethodFlags::O => { - let f = unsafe { method.PyCFunction }; - if has_self { - let callable = move |zelf: PyObjectRef, arg: PyObjectRef, vm: &VirtualMachine| -> PyResult { - unsafe { f(zelf.as_raw().cast_mut(), arg.as_raw().cast_mut()).assume_owned_or_err(vm) } - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - } else { - let callable = move |arg: PyObjectRef, vm: &VirtualMachine| -> PyResult { - unsafe { f(core::ptr::null_mut(), arg.as_raw().cast_mut()).assume_owned_or_err(vm) } - }; - Ok(vm.ctx.new_method_def(name, callable, flags, doc)) - } - }, - _ => { - Err(vm.new_system_error(format!( - "function {name} has unsupported or invalid calling-convention flags: {flags:?}" - ))) - }, - }) -} - -unsafe fn call_function>( +unsafe fn call_function( vm: &VirtualMachine, method: PyMethodPointer, - flags: PyMethodFlags, - args: Option, + args: FuncArgs, + receiver: Option<&rustpython_vm::PyObject>, ) -> PyResult { let f = unsafe { method.PyCFunction }; - let (slf, arg_tuple) = if let Some(mut args) = args.map(Into::into) { - let slf = take_self_arg(&mut args, flags); - let arg_tuple = vm.ctx.new_tuple(args.args); - (slf, Some(arg_tuple)) - } else { - (None, None) - }; - - let slf_ptr = slf - .as_ref() - .map(|obj| obj.as_object().as_raw().cast_mut()) - .unwrap_or_default(); - - let arg_ptr = arg_tuple - .as_ref() - .map(|tuple| tuple.as_object().as_raw().cast_mut()) - .unwrap_or_default(); - - unsafe { f(slf_ptr, arg_ptr).assume_owned_or_err(vm) } + let arg_tuple = vm.ctx.new_tuple(args.args); + let slf_ptr = self_ptr(receiver); + unsafe { f(slf_ptr, arg_tuple.as_object().as_raw().cast_mut()).assume_owned_or_err(vm) } } unsafe fn call_function_with_keywords( vm: &VirtualMachine, method: PyMethodPointer, - flags: PyMethodFlags, - mut args: FuncArgs, + args: FuncArgs, + receiver: Option<&rustpython_vm::PyObject>, ) -> PyResult { let f = unsafe { method.PyCFunctionWithKeywords }; - let slf = take_self_arg(&mut args, flags); - let slf_ptr = slf - .as_ref() - .map(|obj| obj.as_object().as_raw().cast_mut()) - .unwrap_or_default(); - let arg_tuple = vm.ctx.new_tuple(args.args); - let kwargs = vm.ctx.new_dict(); - for (k, v) in args.kwargs { - kwargs.set_item(&*k, v, vm)?; - } + let slf_ptr = self_ptr(receiver); + let (arg_tuple, kwargs) = split_args(vm, args)?; unsafe { f( slf_ptr, arg_tuple.as_object().as_raw().cast_mut(), - kwargs.as_object().as_raw().cast_mut(), + kwargs_ptr(kwargs.as_ref()), ) .assume_owned_or_err(vm) } @@ -215,15 +195,11 @@ unsafe fn call_function_with_keywords( unsafe fn call_fast_function_with_keywords( vm: &VirtualMachine, method: PyMethodPointer, - flags: PyMethodFlags, - mut args: FuncArgs, + args: FuncArgs, + receiver: Option<&rustpython_vm::PyObject>, ) -> PyResult { let f = unsafe { method.PyCFunctionFastWithKeywords }; - let slf = take_self_arg(&mut args, flags); - let slf_ptr = slf - .as_ref() - .map(|obj| obj.as_object().as_raw().cast_mut()) - .unwrap_or_default(); + let slf_ptr = self_ptr(receiver); let nargs = args.args.len(); let mut fastcall_args = args.args; let kwnames_tuple = if !args.kwargs.is_empty() { @@ -238,8 +214,7 @@ unsafe fn call_fast_function_with_keywords( }; let kwnames_ptr = kwnames_tuple .as_ref() - .map(|tuple| tuple.as_object().as_raw().cast_mut()) - .unwrap_or_default(); + .map_or_default(|tuple| tuple.as_object().as_raw().cast_mut()); // SAFETY: PyObjectRef is repr(transparent) over a pointer to PyObject, so a // Vec has a layout-compatible contiguous backing buffer. The // vector is kept alive for the duration of the call. @@ -250,29 +225,21 @@ unsafe fn call_fast_function_with_keywords( unsafe fn call_fast_function( vm: &VirtualMachine, method: PyMethodPointer, - flags: PyMethodFlags, args: PosArgs, + receiver: Option<&rustpython_vm::PyObject>, ) -> PyResult { let f = unsafe { method.PyCFunctionFast }; - let mut args: FuncArgs = args.into(); - let slf = take_self_arg(&mut args, flags); - let slf_ptr = slf - .as_ref() - .map(|obj| obj.as_object().as_raw().cast_mut()) - .unwrap_or_default(); + let args: FuncArgs = args.into(); + let slf_ptr = self_ptr(receiver); // SAFETY: PyObjectRef is repr(transparent) over a pointer to PyObject, so a // Vec has a layout-compatible contiguous backing buffer. The // vector is kept alive for the duration of the call. - let fastcall_arg_ptrs = args.args.as_mut_ptr().cast::<*mut PyObject>(); + let fastcall_arg_ptrs = args.args.as_ptr().cast::<*mut PyObject>(); unsafe { f(slf_ptr, fastcall_arg_ptrs, args.args.len() as isize).assume_owned_or_err(vm) } } -fn take_self_arg(args: &mut FuncArgs, flags: PyMethodFlags) -> Option { - if flags.contains(PyMethodFlags::STATIC) { - None - } else { - args.take_positional() - } +fn self_ptr(slf: Option<&rustpython_vm::PyObject>) -> *mut PyObject { + slf.map_or(core::ptr::null_mut(), |obj| obj.as_raw().cast_mut()) } #[unsafe(no_mangle)] @@ -289,9 +256,7 @@ pub unsafe extern "C" fn PyCMethod_New( ); let ml = unsafe { &*ml }; let zelf = unsafe { slf.assume_borrowed_or_opt() }.map(ToOwned::to_owned); - Ok(build_method_def(vm, ml, zelf.is_some())? - .build_function(vm, zelf) - .into()) + Ok(ml.build_method_def(vm)?.build_function(vm, zelf).into()) }) } @@ -385,4 +350,360 @@ mod tests { func.call0().unwrap(); }); } + + #[test] + fn wrap_one_arg_function_with_no_module() { + #[pyfunction] + fn one_arg(value: i64) -> i64 { + value + } + + Python::attach(|py| { + let func = wrap_pyfunction!(one_arg, py).unwrap(); + func.call1((7,)).unwrap(); + }); + } + + #[test] + fn module_receiver_is_not_a_python_argument() { + #[pyfunction(pass_module)] + fn module_noargs(module: &Bound<'_, PyModule>) -> Py { + module.clone().unbind() + } + + #[pyfunction(pass_module, signature = (value, /))] + fn module_one(module: &Bound<'_, PyModule>, value: i64) -> (Py, i64) { + (module.clone().unbind(), value) + } + + #[pyfunction(pass_module, signature = (*args, **kwargs))] + fn module_variadic( + module: &Bound<'_, PyModule>, + args: &Bound<'_, pyo3::types::PyTuple>, + kwargs: Option<&Bound<'_, pyo3::types::PyDict>>, + ) -> (Py, usize, usize) { + ( + module.clone().unbind(), + args.len(), + kwargs.map_or(0, |kwargs| kwargs.len()), + ) + } + + Python::attach(|py| { + let module = PyModule::new(py, "receiver_module").unwrap(); + let noargs = wrap_pyfunction!(module_noargs, &module).unwrap(); + assert!(noargs.getattr("__self__").unwrap().is(&module)); + assert!(noargs.call0().unwrap().is(&module)); + assert!(noargs.call1((1,)).is_err()); + + let one = wrap_pyfunction!(module_one, &module).unwrap(); + let (receiver, value): (Py, i64) = + one.call1((7,)).unwrap().extract().unwrap(); + assert!(receiver.bind(py).is(&module)); + assert_eq!(value, 7); + assert!(one.call0().is_err()); + assert!(one.call1((7, 8)).is_err()); + + let variadic = wrap_pyfunction!(module_variadic, &module).unwrap(); + let kwargs = pyo3::types::PyDict::new(py); + kwargs.set_item("keyword", 3).unwrap(); + let (receiver, positional, keywords): (Py, usize, usize) = variadic + .call((1, 2), Some(&kwargs)) + .unwrap() + .extract() + .unwrap(); + assert!(receiver.bind(py).is(&module)); + assert_eq!((positional, keywords), (2, 1)); + }); + } + + #[test] + fn no_keywords_before_arity() { + Python::attach(|py| { + unsafe extern "C" fn c_fn(_self: *mut PyObject, _args: *mut PyObject) -> *mut PyObject { + unsafe { PyLong_FromLong(42) } + } + let f = PyCFunction::new(py, c_fn, c"no_keywords", c"", None).unwrap(); + let kwargs = pyo3::types::PyDict::new(py); + kwargs.set_item("unexpected", 1).unwrap(); + let err = f.call((1,), Some(&kwargs)).unwrap_err(); + assert_eq!( + err.value(py).str().unwrap().to_str().unwrap(), + "no_keywords() takes no keyword arguments" + ); + kwargs.clear(); + assert_eq!( + f.call((), Some(&kwargs)).unwrap().extract::().unwrap(), + 42 + ); + }); + } + #[test] + fn native_methods_receive_self_separately_from_user_arguments() { + use pyo3::ffi; + use pyo3::types::{PyDict, PyTuple}; + + unsafe extern "C" fn receiver(slf: *mut PyObject, _args: *mut PyObject) -> *mut PyObject { + unsafe { ffi::Py_NewRef(slf) } + } + unsafe extern "C" fn one(_slf: *mut PyObject, arg: *mut PyObject) -> *mut PyObject { + unsafe { ffi::Py_NewRef(arg) } + } + unsafe extern "C" fn variadic( + slf: *mut PyObject, + args: *mut PyObject, + kwargs: *mut PyObject, + ) -> *mut PyObject { + unsafe { + let result = ffi::PyTuple_New(3); + if result.is_null() { + return result; + } + let kwargs = if kwargs.is_null() { + ffi::Py_None() + } else { + kwargs + }; + ffi::PyTuple_SetItem(result, 0, ffi::Py_NewRef(slf)); + ffi::PyTuple_SetItem(result, 1, ffi::Py_NewRef(args)); + ffi::PyTuple_SetItem(result, 2, ffi::Py_NewRef(kwargs)); + result + } + } + unsafe extern "C" fn static_noargs( + _slf: *mut PyObject, + _args: *mut PyObject, + ) -> *mut PyObject { + unsafe { PyLong_FromLong(42) } + } + + Python::attach(|py| { + let method = |name: &'static core::ffi::CStr, function, flags| ffi::PyMethodDef { + ml_name: name.as_ptr(), + ml_meth: ffi::PyMethodDefPointer { + PyCFunction: function, + }, + ml_flags: flags, + ml_doc: c"".as_ptr(), + }; + let mut methods = [ + method(c"noargs", receiver as ffi::PyCFunction, ffi::METH_NOARGS), + method(c"one", one as ffi::PyCFunction, ffi::METH_O), + ffi::PyMethodDef { + ml_name: c"variadic".as_ptr(), + ml_meth: ffi::PyMethodDefPointer { + PyCFunctionWithKeywords: variadic, + }, + ml_flags: ffi::METH_VARARGS | ffi::METH_KEYWORDS, + ml_doc: c"".as_ptr(), + }, + method( + c"class_receiver", + receiver as ffi::PyCFunction, + ffi::METH_CLASS | ffi::METH_NOARGS, + ), + method( + c"static_noargs", + static_noargs as ffi::PyCFunction, + ffi::METH_STATIC | ffi::METH_NOARGS, + ), + method( + c"explicit_type_argument", + one as ffi::PyCFunction, + ffi::METH_STATIC | ffi::METH_O, + ), + ffi::PyMethodDef::zeroed(), + ]; + // This boundary does not need a Rust payload. Use a zero-sized C + // type spec instead of PyO3's currently unsupported payload layout. + let mut slots = [ + ffi::PyType_Slot { + slot: ffi::Py_tp_methods, + pfunc: methods.as_mut_ptr().cast(), + }, + ffi::PyType_Slot { + slot: 0, + pfunc: core::ptr::null_mut(), + }, + ]; + let mut spec = ffi::PyType_Spec { + name: c"test.Receiver".as_ptr(), + basicsize: 0, + itemsize: 0, + flags: ffi::Py_TPFLAGS_DEFAULT as _, + slots: slots.as_mut_ptr(), + }; + let class = unsafe { + Bound::::from_owned_ptr_or_err(py, ffi::PyType_FromSpec(&mut spec)) + } + .unwrap(); + let obj = class.call0().unwrap(); + let bound = obj.getattr("one").unwrap(); + assert!(bound.getattr("__self__").unwrap().is(&obj)); + assert_eq!(bound.call1((2,)).unwrap().extract::().unwrap(), 2); + assert_eq!( + class + .getattr("one") + .unwrap() + .call1((&obj, 2)) + .unwrap() + .extract::() + .unwrap(), + 2 + ); + assert!(bound.call0().is_err()); + assert!(bound.call1((1, 2)).is_err()); + assert!(class.getattr("one").unwrap().call0().is_err()); + assert!(class.getattr("one").unwrap().call1((1, 2)).is_err()); + assert!(obj.call_method0("noargs").unwrap().is(&obj)); + let kwargs = PyDict::new(py); + kwargs.set_item("named", 3).unwrap(); + let result = obj.call_method("variadic", (1, 2), Some(&kwargs)).unwrap(); + let result = result.cast::().unwrap(); + assert!(result.get_item(0).unwrap().is(&obj)); + assert_eq!( + result.get_item(1).unwrap().extract::<(i64, i64)>().unwrap(), + (1, 2) + ); + assert_eq!( + result + .get_item(2) + .unwrap() + .get_item("named") + .unwrap() + .extract::() + .unwrap(), + 3 + ); + let without_keywords = obj.call_method1("variadic", (1, 2)).unwrap(); + assert!( + without_keywords + .cast::() + .unwrap() + .get_item(2) + .unwrap() + .is_none() + ); + assert!(obj.call_method0("class_receiver").unwrap().is(&class)); + assert!(class.call_method0("class_receiver").unwrap().is(&class)); + let class_wrapper = class + .getattr("__dict__") + .unwrap() + .get_item("class_receiver") + .unwrap(); + assert_eq!( + class_wrapper.get_type().name().unwrap().to_str().unwrap(), + "classmethod_descriptor" + ); + assert_eq!( + class + .call_method0("static_noargs") + .unwrap() + .extract::() + .unwrap(), + 42 + ); + assert_eq!( + obj.call_method0("static_noargs") + .unwrap() + .extract::() + .unwrap(), + 42 + ); + let static_function = class.getattr("explicit_type_argument").unwrap(); + assert!(static_function.getattr("__self__").unwrap().is_none()); + let wrapper = class + .getattr("__dict__") + .unwrap() + .get_item("explicit_type_argument") + .unwrap(); + assert_eq!( + wrapper.get_type().name().unwrap().to_str().unwrap(), + "staticmethod" + ); + assert!(wrapper.getattr("__func__").unwrap().is(&static_function)); + let module = static_function.getattr("__module__").unwrap(); + class + .setattr("__module__", "changed_after_registration") + .unwrap(); + assert!(static_function.getattr("__module__").unwrap().is(&module)); + assert!(static_function.call1((&class,)).unwrap().is(&class)); + assert!(wrapper.call1((&class,)).unwrap().is(&class)); + assert!( + obj.call_method1("explicit_type_argument", (&class,)) + .unwrap() + .is(&class) + ); + assert!(obj.call_method0("explicit_type_argument").is_err()); + }); + } + #[test] + fn static_c_adapter_ignores_its_bound_class() { + unsafe extern "C" fn check_self( + slf: *mut crate::PyObject, + args: *mut crate::PyObject, + ) -> *mut crate::PyObject { + unsafe { PyLong_FromLong((slf.is_null() && args.is_null()).into()).cast() } + } + Python::attach(|py| { + let mut definition = super::PyMethodDef { + ml_name: c"static_noargs".as_ptr(), + ml_meth: super::PyMethodPointer { + PyCFunction: check_self, + }, + ml_flags: pyo3::ffi::METH_STATIC | pyo3::ffi::METH_NOARGS, + ml_doc: c"".as_ptr(), + }; + // The safe PyO3 wrapper owns the function; only construction crosses + // the C boundary so the callback can observe its actual self pointer. + let function = unsafe { + Bound::::from_owned_ptr_or_err( + py, + super::PyCFunction_New(&mut definition, py.get_type::().as_ptr().cast()) + .cast(), + ) + } + .unwrap(); + assert!(function.getattr("__self__").unwrap().is_none()); + assert_eq!(function.call0().unwrap().extract::().unwrap(), 1); + }); + } + + #[test] + fn descr_new_classmethod_binds_the_type_as_self() { + use pyo3::ffi; + + unsafe extern "C" fn receiver( + slf: *mut crate::PyObject, + _args: *mut crate::PyObject, + ) -> *mut crate::PyObject { + unsafe { ffi::Py_NewRef(slf.cast()).cast() } + } + + Python::attach(|py| { + let mut definition = super::PyMethodDef { + ml_name: c"class_receiver".as_ptr(), + ml_meth: super::PyMethodPointer { + PyCFunction: receiver, + }, + ml_flags: ffi::METH_CLASS | ffi::METH_NOARGS, + ml_doc: c"".as_ptr(), + }; + let ty = py.get_type::(); + let descr = unsafe { + Bound::::from_owned_ptr_or_err( + py, + crate::descrobject::PyDescr_NewClassMethod(ty.as_ptr().cast(), &mut definition) + .cast(), + ) + } + .unwrap(); + assert_eq!( + descr.get_type().name().unwrap().to_str().unwrap(), + "classmethod_descriptor" + ); + let bound = descr.call_method1("__get__", (py.None(), &ty)).unwrap(); + assert!(bound.call0().unwrap().is(&ty)); + }); + } } diff --git a/crates/capi/src/modsupport.rs b/crates/capi/src/modsupport.rs index 50903977714..e166826bb1f 100644 --- a/crates/capi/src/modsupport.rs +++ b/crates/capi/src/modsupport.rs @@ -1,4 +1,5 @@ use crate::PyObject; +use crate::methodobject::PyMethodDef; use crate::object::PyTypeObject; use crate::pystate::with_vm; use crate::util::{CStrExt, FfiPtrExt}; @@ -52,6 +53,28 @@ impl PyABIInfo { } } +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyModule_AddFunctions( + module: *mut PyObject, + functions: *mut PyMethodDef, +) -> c_int { + with_vm(|vm| { + let module = unsafe { module.assume_borrowed_and_cast::(vm) }?; + let module_name = module.as_object().get_attr("__name__", vm)?; + for def in PyMethodDef::iter(functions) { + let name = unsafe { def.ml_name.try_as_str(vm) }?; + let function = def + .build_method_def(vm)? + .build_function(vm, Some(module.to_owned().into())); + function + .as_object() + .set_attr("__module__", module_name.clone(), vm)?; + module.dict().set_item(name, function.into(), vm)?; + } + Ok(()) + }) +} + #[unsafe(no_mangle)] pub unsafe extern "C" fn PyModule_AddObjectRef( module: *mut PyObject, diff --git a/crates/capi/src/object.rs b/crates/capi/src/object.rs index bfce1a81711..69a2af4e22c 100644 --- a/crates/capi/src/object.rs +++ b/crates/capi/src/object.rs @@ -7,7 +7,7 @@ use rustpython_vm::builtins::{PyStr, object_generic_set_dict, object_get_dict}; use rustpython_vm::bytecode::ComparisonOperator; use rustpython_vm::function::PySetterValue; use rustpython_vm::types::{PyComparisonOp, hash_not_implemented}; -use rustpython_vm::{AsObject, PyPayload, PyResult, VirtualMachine}; +use rustpython_vm::{AsObject, PyResult, VirtualMachine}; mod pytype; @@ -355,9 +355,8 @@ pub unsafe extern "C" fn PyObject_ClearWeakRefs(obj: *mut PyObject) { #[unsafe(no_mangle)] pub unsafe extern "C" fn PyObject_Dir(obj: *mut PyObject) -> *mut PyObject { with_vm(|vm| { - unsafe { obj.assume_borrowed_or_opt() } - .map_or_else(|| vm.dir(None), |obj| obj.to_owned().dir(vm)) - .map(|list| list.into_ref(&vm.ctx)) + let obj = unsafe { obj.assume_borrowed_or_opt() }.map(ToOwned::to_owned); + vm.dir(obj) }) } @@ -381,7 +380,7 @@ pub unsafe extern "C" fn PyObject_Not(obj: *mut PyObject) -> c_int { pub unsafe extern "C" fn PyObject_Hash(obj: *mut PyObject) -> isize { with_vm(|vm| { let obj = unsafe { obj.assume_borrowed() }; - obj.hash(vm).map(|hash| hash as isize) + obj.hash(vm) }) } @@ -389,7 +388,7 @@ pub unsafe extern "C" fn PyObject_Hash(obj: *mut PyObject) -> isize { pub unsafe extern "C" fn PyObject_HashNotImplemented(obj: *mut PyObject) -> isize { with_vm(|vm| { let obj = unsafe { obj.assume_borrowed() }; - hash_not_implemented(obj, vm).map(|hash| hash as isize) + hash_not_implemented(obj, vm) }) } diff --git a/crates/capi/src/object/pytype.rs b/crates/capi/src/object/pytype.rs index 27254dc83cc..46d5f1340cd 100644 --- a/crates/capi/src/object/pytype.rs +++ b/crates/capi/src/object/pytype.rs @@ -1,15 +1,19 @@ use crate::descrobject::{PyGetSetDef, PyMemberDef}; -use crate::methodobject::{PyMethodDef, build_method_def}; +use crate::methodobject::PyMethodDef; use crate::object::define_py_check; use crate::pystate::with_vm; use crate::slots::{PySlot, PySlotKind, PySlotType}; use crate::util::CStrExt; use crate::util::FfiPtrExt; -use core::ffi::{c_char, c_int, c_ulong, c_void}; +use core::ffi::{c_char, c_int, c_uint, c_ulong, c_void}; +use core::ptr; use rustpython_vm::builtins::{PyStr, PyType}; use rustpython_vm::function::{ItemDoc, PyMethodFlags}; -use rustpython_vm::types::{AtomicPyTypeFlags, PyTypeFlags, PyTypeSlots, SlotAccessor}; -use rustpython_vm::{AsObject, Py, PyObject}; +use rustpython_vm::types::{ + AtomicPyTypeFlags, CNewFunc, CSlotId, CSlots, PyTypeFlags, PyTypeSlots, + SlotAccessor::{TpBase, TpDealloc, TpDoc, TpGetset, TpMembers, TpMethods, TpNew, TpTraverse}, +}; +use rustpython_vm::{AsObject, Py, PyObject, PyPayload, PyResult, VirtualMachine, identifier}; pub type PyTypeObject = Py; @@ -22,23 +26,13 @@ pub struct PyType_Slot { pub pfunc: *mut c_void, } -impl PyType_Slot { - pub(crate) fn iter<'a>(mut slots: *const Self) -> impl Iterator { - core::iter::from_fn(move || { - let slot = unsafe { &*slots }; - if slot.slot == 0 { - None - } else { - slots = unsafe { slots.add(1) }; - Some(slot) - } - }) - } - - fn as_slot_accessor(&self) -> Option { - let slot_id: u8 = self.slot.try_into().ok()?; - slot_id.try_into().ok() - } +#[repr(C)] +pub struct PyType_Spec { + pub name: *const c_char, + pub basicsize: c_int, + pub itemsize: c_int, + pub flags: c_uint, + pub slots: *mut PyType_Slot, } #[unsafe(no_mangle)] @@ -103,12 +97,7 @@ pub unsafe extern "C" fn PyType_GetFullyQualifiedName(ptr: *mut PyTypeObject) -> } #[unsafe(no_mangle)] -pub unsafe extern "C" fn PyType_GetSlot(_ty: *const PyTypeObject, _slot: c_int) -> *mut c_void { - core::ptr::null_mut() -} - -#[unsafe(no_mangle)] -pub extern "C" fn PyType_FromSlots(slots: *const PySlot) -> *mut PyObject { +pub unsafe extern "C" fn PyType_FromSlots(slots: *const PySlot) -> *mut PyObject { with_vm(|vm| { let mut name = None; let mut base = None; @@ -117,12 +106,16 @@ pub extern "C" fn PyType_FromSlots(slots: *const PySlot) -> *mut PyObject { let attrs = Default::default(); let mut getsets = Vec::new(); let mut members = Vec::new(); + let mut metaclass = vm.ctx.types.type_type.to_owned(); + let mut tp_new: Option = None; for slot in PySlot::iter(slots) { match slot.as_kind(vm)? { - kind @ PySlotKind::Type(type_slot) => { + PySlotKind::Type(type_slot) => { match type_slot { PySlotType::Name(value) => name = Some(value), + PySlotType::Metaclass(meta) => metaclass = meta.to_owned(), + PySlotType::Module(_) => {} PySlotType::Flags(value) => { let flags = PyTypeFlags::from_bits(value).ok_or_else(|| { vm.new_value_error(format!( @@ -131,75 +124,50 @@ pub extern "C" fn PyType_FromSlots(slots: *const PySlot) -> *mut PyObject { })?; type_slots.flags = AtomicPyTypeFlags::from_plain(flags); } - PySlotType::BasicSize(size) | PySlotType::ExtraBasicSize(size) => { + PySlotType::BasicSize(size) + | PySlotType::ExtraBasicSize(size) + | PySlotType::ItemSize(size) => { if size != 0 { return Err(vm.new_not_implemented_error( "PyType_FromSlots with non-zero size is not yet supported", )); } } - PySlotType::Slots { value, .. } => { - for slot in PyType_Slot::iter(value) { - let accessor = slot.as_slot_accessor().ok_or_else(|| { - vm.new_value_error(format!( - "Invalid slot id: {} for PyType_FromSlots", - slot.slot - )) - })?; - match accessor { - SlotAccessor::TpDoc => { - let doc = unsafe { - slot.pfunc.cast::().try_as_str_opt(vm)? - } - .map_or( - ItemDoc::NONE, - |doc| { - let text: &'static str = - Box::leak(doc.to_owned().into_boxed_str()); - ItemDoc::static_text(text) - }, - ); - type_slots.doc = doc; - } - SlotAccessor::TpNew => { - type_slots.new.store(Some(|ty, _args, vm| { - Err(vm.new_not_implemented_error(format!("tp_new is not yet implemented in PyType_FromSlots for {ty:?}"))) - })); - } - SlotAccessor::TpBase => { - base = unsafe { Some(&*slot.pfunc.cast::()) } - } - SlotAccessor::TpDealloc => { - //TODO - } - SlotAccessor::TpMethods => { - for def in PyMethodDef::iter(slot.pfunc.cast()) { - let name = unsafe { def.ml_name.try_as_str(vm)? }; - let is_static = - PyMethodFlags::from_bits_retain(def.ml_flags as _) - .contains(PyMethodFlags::STATIC); - let method = build_method_def(vm, def, !is_static)?; - methods.push((name, method)); - } - } - SlotAccessor::TpGetset => { - getsets.extend(PyGetSetDef::iter(slot.pfunc.cast())); - } - SlotAccessor::TpMembers => { - members.extend(PyMemberDef::iter(slot.pfunc.cast())); - } - slot => { - return Err(vm.new_not_implemented_error(format!( - "PyType_FromSlots with PyType_Slot {slot:?} not implemented yet" - ))); - } - } + PySlotType::TypeSlot(TpDoc, pfunc) => { + let doc = unsafe { pfunc.cast::().try_as_str_opt(vm)? }.map_or( + ItemDoc::NONE, + |doc| { + let text: &'static str = + Box::leak(doc.to_owned().into_boxed_str()); + ItemDoc::static_text(text) + }, + ); + type_slots.doc = doc; + } + PySlotType::TypeSlot(TpBase, pfunc) => { + base = unsafe { Some(&*pfunc.cast::()) } + } + PySlotType::TypeSlot(TpMembers, pfunc) => { + members.extend(PyMemberDef::iter(pfunc.cast())); + } + PySlotType::TypeSlot(TpGetset, pfunc) => { + getsets.extend(PyGetSetDef::iter(pfunc.cast())); + } + PySlotType::TypeSlot(TpMethods, pfunc) => { + for def in PyMethodDef::iter(pfunc.cast()) { + let name = unsafe { def.ml_name.try_as_str(vm)? }; + let flags = PyMethodFlags::from_bits_retain(def.ml_flags as _); + let method = def.build_method_def(vm)?; + methods.push((name, flags, method)); } } - _ => { - return Err(vm.new_not_implemented_error(format!( - "PyType_FromSlots with slot {kind:?} not implemented yet" - ))); + PySlotType::TypeSlot(TpNew, pfunc) => { + tp_new = Some(unsafe { + core::mem::transmute::<*mut c_void, CNewFunc>(pfunc) + }); + } + PySlotType::TypeSlot(TpDealloc | TpTraverse | _, _) => { + // TODO } } } @@ -222,18 +190,36 @@ pub extern "C" fn PyType_FromSlots(slots: *const PySlot) -> *mut PyObject { return Err(vm.new_system_error("PyType_FromSlots requires a name slot")); }; - let metaclass = vm.ctx.types.type_type.to_owned(); let class = PyType::new_heap(name, bases, attrs, type_slots, metaclass, &vm.ctx).map_err( |msg| vm.new_system_error(format!("Failed to create type from slots: {msg}")), )?; + if let Some(tp_new) = tp_new { + set_tp_new(vm, &class, tp_new)?; + } let attrs = &class.attributes; let class_static = unsafe { &*((&*class) as *const _) }; - for (name, method) in methods { - attrs.insert( - vm.ctx.intern_str(name), - method.build_method(class_static, vm).into(), - ); + for (name, flags, method) in methods { + let method = if flags.contains(PyMethodFlags::CLASS) { + if flags.contains(PyMethodFlags::STATIC) { + return Err(vm.new_value_error("method cannot be both class and static")); + } + method.build_classmethod(class_static, vm).into() + } else if flags.contains(PyMethodFlags::STATIC) { + // Static functions bind the defining class for metadata, not as + // a Python argument. They must not use a method descriptor, + // whose call protocol consumes its first argument as self. + let function = method.build_function(vm, Some(class.to_owned().into())); + if let Some(module) = attrs.get(identifier!(vm, __module__)) { + function.as_object().set_attr("__module__", module, vm)?; + } + rustpython_vm::builtins::PyStaticMethod::new(function.into()) + .into_ref(&vm.ctx) + .into() + } else { + method.build_method(class_static, vm).into() + }; + attrs.insert(vm.ctx.intern_str(name), method); } for getset in getsets { let name = unsafe { getset.name.try_as_str(vm)? }; @@ -254,6 +240,78 @@ pub extern "C" fn PyType_FromSlots(slots: *const PySlot) -> *mut PyObject { }) } +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyType_FromMetaclass( + metaclass: *mut PyTypeObject, + module: *mut PyObject, + spec: *mut PyType_Spec, + bases: *mut PyObject, +) -> *mut PyObject { + let &PyType_Spec { + name, + basicsize, + itemsize, + flags, + slots: type_slots, + } = unsafe { &*spec }; + let mut slots = [PySlot::SLOT_END; 9]; + let mut write_slot = { + let mut iter = slots.iter_mut(); + move |slot| { + debug_assert!( + iter.len() >= 2, + "PyType_FromMetaclass: last slot is reserved for SLOT_END" + ); + let entry = iter + .next() + .expect("Too many slots for PyType_FromMetaclass"); + *entry = slot; + } + }; + + write_slot(PySlot::new(95, name.cast_mut())); + write_slot(PySlot::new(96, basicsize as isize)); + write_slot(PySlot::new(98, itemsize as isize)); + write_slot(PySlot::new(99, flags as u64)); + write_slot(PySlot::new(93, type_slots)); + + if !bases.is_null() { + write_slot(PySlot::new(49, bases)); + } + + if !metaclass.is_null() { + write_slot(PySlot::new(107, metaclass)); + } + + if !module.is_null() { + write_slot(PySlot::new(108, module)); + } + + unsafe { PyType_FromSlots(slots.as_ptr()) } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyType_FromModuleAndSpec( + module: *mut PyObject, + spec: *mut PyType_Spec, + bases: *mut PyObject, +) -> *mut PyObject { + unsafe { PyType_FromMetaclass(ptr::null_mut(), module, spec, bases) } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyType_FromSpecWithBases( + spec: *mut PyType_Spec, + bases: *mut PyObject, +) -> *mut PyObject { + unsafe { PyType_FromMetaclass(ptr::null_mut(), ptr::null_mut(), spec, bases) } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyType_FromSpec(spec: *mut PyType_Spec) -> *mut PyObject { + unsafe { PyType_FromMetaclass(ptr::null_mut(), ptr::null_mut(), spec, ptr::null_mut()) } +} + #[unsafe(no_mangle)] pub unsafe extern "C" fn PyObject_GetTypeData( obj: *mut PyObject, @@ -283,9 +341,69 @@ pub extern "C" fn PyType_Freeze(_ty: *mut PyTypeObject) -> c_int { 0 } +// C level type slots. +// +// Slots cross the boundary in both directions. A `newfunc` from an extension +// goes into the type's `CSlots` table and `new` gets the trampoline that +// reads it; the table pointer is inherited alongside the trampoline. A slot +// implemented in Rust is paired with a static C function of that same +// implementation, and `PyType_GetSlot` returns it — for a subclass, the +// base's function — so the caller can run that body with its own subtype. +// +// `__new__` is the same wrapper a native type gets, so a call through it is +// checked by `PyType::__new__` before it reaches the slot. + +#[allow(non_camel_case_types)] +pub type newfunc = CNewFunc; + +#[allow(non_upper_case_globals)] +pub const Py_tp_new: c_int = CSlotId::TpNew as c_int; + +/// Install a C `newfunc` as the type's tp_new. +/// +/// Fails on a static type, on a type that already has C slots, and on a type +/// that defines `__new__` itself, since the C slot would then be shadowed. +pub fn set_tp_new(vm: &VirtualMachine, ty: &Py, tp_new: newfunc) -> PyResult<()> { + if ty.attributes.contains(identifier!(vm, __new__)) { + return Err(vm.new_type_error(format!("type '{}' already defines __new__", ty.name()))); + } + let c_slots = CSlots::new(); + c_slots.new.store(Some(tp_new)); + ty.set_c_slots(c_slots, vm)?; + + // The wrapper that reaches the slot the checked way, as a native type gets + // from `extend_class`. Stored without the attribute protocol so that + // `update_slot` does not read it back as a definition of `__new__`. + let def = vm.ctx.new_method_def( + "__new__", + rustpython_vm::function::ReceiverFunction(PyType::__new__), + PyMethodFlags::METHOD, + ItemDoc::NONE, + ); + let wrapper = def.build_function(vm, Some(ty.to_owned().into())); + ty.set_attr(identifier!(vm, __new__), wrapper.into()); + Ok(()) +} + +/// The C function installed in `slot`. +/// +/// `Py_tp_new` is reported for a function installed from C and for a Rust +/// `tp_new`, including one a subclass inherited. Any other id reads as empty. +#[unsafe(no_mangle)] +#[allow(non_upper_case_globals)] +pub unsafe extern "C" fn PyType_GetSlot(ty: *const PyTypeObject, slot: c_int) -> *mut c_void { + let ty = unsafe { &*ty }; + match CSlotId::from_raw(slot) { + Some(CSlotId::TpNew) => ty.c_tp_new().map_or(ptr::null_mut(), |f| f as *mut c_void), + None => ptr::null_mut(), + } +} + #[cfg(test)] mod tests { use pyo3::IntoPyObjectExt; + use pyo3::exceptions::PyValueError; + use pyo3::ffi; use pyo3::prelude::*; use pyo3::types::{PyDict, PyInt, PyList, PyString, PyType, PyTypeMethods}; @@ -384,7 +502,6 @@ mod tests { } #[test] - #[ignore] fn zero_sized_class() { #[pyclass(frozen)] struct MyEmptyClass {} @@ -442,8 +559,47 @@ mod tests { }); } + /// A `#[new]` with arguments runs through `Py_tp_new` from Python code: + /// the result has the pyclass type, its error is raised, and a Python + /// subclass of a final class is refused. + #[test] + fn pyclass_new_from_python() { + #[pyclass(frozen)] + struct Probe {} + + #[pymethods] + impl Probe { + #[new] + fn new(x: i32) -> PyResult { + if x < 0 { + return Err(PyValueError::new_err("negative")); + } + Ok(Self {}) + } + } + + Python::attach(|py| { + let globals = PyDict::new(py); + globals.set_item("Probe", py.get_type::()).unwrap(); + py.run( + c"obj = Probe(1)\nassert type(obj) is Probe", + Some(&globals), + None, + ) + .unwrap(); + + let err = py.run(c"Probe(-1)", Some(&globals), None).unwrap_err(); + assert!(err.is_instance_of::(py)); + assert_eq!(err.value(py).to_string(), "negative"); + + let err = py + .run(c"class Sub(Probe): pass", Some(&globals), None) + .unwrap_err(); + assert!(err.is_instance_of::(py)); + }); + } + #[test] - #[ignore] fn subclass_with_property() { #[pyclass(frozen, extends=PyList)] struct MyList {} @@ -475,4 +631,618 @@ mod tests { ); }); } + + #[test] + fn type_from_spec() { + Python::attach(|py| { + let mut slots = [ffi::PyType_Slot { + slot: 0, + pfunc: core::ptr::null_mut(), + }]; + let mut spec = ffi::PyType_Spec { + name: c"somemodule.MySpecClass".as_ptr(), + basicsize: 0, + itemsize: 0, + flags: ffi::Py_TPFLAGS_DEFAULT as _, + slots: slots.as_mut_ptr(), + }; + + let type_ptr = unsafe { ffi::PyType_FromSpec(&mut spec) }; + let type_obj = unsafe { + Bound::from_borrowed_ptr_or_err(py, type_ptr) + .unwrap() + .cast_into::() + .unwrap() + }; + + assert_eq!(type_obj.qualname().unwrap(), "somemodule.MySpecClass"); + }); + } + + #[test] + fn fast_subclass_check_using_flags() { + Python::attach(|py| { + assert!(unsafe { + ffi::PyType_HasFeature( + py.get_type::().as_type_ptr(), + ffi::Py_TPFLAGS_DICT_SUBCLASS, + ) != 0 + }); + assert!(unsafe { + ffi::PyType_HasFeature( + py.get_type::().as_type_ptr(), + ffi::Py_TPFLAGS_BASE_EXC_SUBCLASS, + ) != 0 + }); + }) + } +} + +#[cfg(test)] +mod c_slot_tests { + use super::*; + use crate::PyObject; + use core::ptr::NonNull; + use pyo3::Python; + use rustpython_vm::builtins::{PyInt, PyStrRef, PyTuple, PyTypeRef}; + use rustpython_vm::function::{FuncArgs, KwArgs}; + use rustpython_vm::vm::thread::{current_vm_is_set, with_current_vm}; + use rustpython_vm::{AsObject, PyObjectRef, PyRef}; + + fn load_tp_new(ty: &PyTypeObject) -> newfunc { + let slot = unsafe { PyType_GetSlot(ty, Py_tp_new) }; + assert!(!slot.is_null()); + unsafe { core::mem::transmute::<*mut c_void, newfunc>(slot) } + } + + fn call_tp_new(tp_new: newfunc, subtype: &PyTypeObject, args: PyRef) -> PyObjectRef { + let ptr = unsafe { + tp_new( + core::ptr::from_ref(subtype).cast_mut(), + args.as_object().as_raw().cast_mut(), + core::ptr::null_mut(), + ) + }; + let Some(ptr) = NonNull::new(ptr) else { + let msg = with_current_vm(|vm| { + vm.take_raised_exception() + .and_then(|exc| exc.as_object().str(vm).ok()) + .map_or_else(|| "no exception".to_owned(), |msg| msg.to_string()) + }); + panic!("tp_new returned NULL: {msg}"); + }; + unsafe { PyObjectRef::from_raw(ptr) } + } + + /// `PyType_GetSlot(base, Py_tp_new)(subtype, args, NULL)`. + /// + /// A missing slot sets TypeError ("base type without tp_new") and returns NULL. + /// The pointer from the base, including NULL, is returned unchanged. + fn call_base_tp_new( + vm: &VirtualMachine, + base: &PyTypeObject, + subtype: *mut PyTypeObject, + args: &PyRef, + ) -> *mut PyObject { + let slot = unsafe { PyType_GetSlot(base, Py_tp_new) }; + if slot.is_null() { + vm.set_raised_exception(Some(vm.new_type_error("base type without tp_new"))); + return core::ptr::null_mut(); + } + let tp_new = unsafe { core::mem::transmute::<*mut c_void, newfunc>(slot) }; + unsafe { + tp_new( + subtype, + args.as_object().as_raw().cast_mut(), + core::ptr::null_mut(), + ) + } + } + + /// Returns `(subtype.__name__, args, kwds is NULL)`. + unsafe extern "C" fn echo_new( + subtype: *mut PyTypeObject, + args: *mut PyObject, + kwds: *mut PyObject, + ) -> *mut PyObject { + assert!(current_vm_is_set()); + with_current_vm(|vm| { + let subtype = unsafe { &*subtype }; + let args = unsafe { &*args }.to_owned(); + let echo = vm.ctx.new_tuple(vec![ + vm.ctx.new_str(subtype.name().to_string()).into(), + args, + vm.ctx.new_bool(kwds.is_null()).into(), + ]); + PyObjectRef::from(echo).into_raw().as_ptr() + }) + } + + /// Returns an empty tuple, so it is told apart from `echo_new` by result. + unsafe extern "C" fn other_new( + _subtype: *mut PyTypeObject, + _args: *mut PyObject, + _kwds: *mut PyObject, + ) -> *mut PyObject { + with_current_vm(|vm| { + PyObjectRef::from(vm.ctx.new_tuple(vec![])) + .into_raw() + .as_ptr() + }) + } + + unsafe extern "C" fn new_with_object_base( + subtype: *mut PyTypeObject, + _args: *mut PyObject, + _kwds: *mut PyObject, + ) -> *mut PyObject { + with_current_vm(|vm| { + call_base_tp_new(vm, vm.ctx.types.object_type, subtype, &vm.ctx.empty_tuple) + }) + } + + unsafe extern "C" fn new_with_int_base( + subtype: *mut PyTypeObject, + _args: *mut PyObject, + _kwds: *mut PyObject, + ) -> *mut PyObject { + with_current_vm(|vm| { + call_base_tp_new(vm, vm.ctx.types.int_type, subtype, &vm.ctx.empty_tuple) + }) + } + + /// Same as [`new_with_int_base`], but the base receives `("nope",)`. + unsafe extern "C" fn new_with_int_base_nope( + subtype: *mut PyTypeObject, + _args: *mut PyObject, + _kwds: *mut PyObject, + ) -> *mut PyObject { + with_current_vm(|vm| { + let args = vm.ctx.new_tuple(vec![vm.ctx.new_str("nope").into()]); + call_base_tp_new(vm, vm.ctx.types.int_type, subtype, &args) + }) + } + + fn heap_type(name: &str, base: &Py, vm: &VirtualMachine) -> PyTypeRef { + PyType::new_simple_heap(name, base, &vm.ctx).unwrap() + } + + fn call(ty: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyRef { + ty.as_object() + .call(args, vm) + .unwrap() + .downcast::() + .unwrap() + } + + fn echoed_name(echo: &PyTuple) -> String { + let name: PyStrRef = echo[0].clone().downcast().unwrap(); + name.to_string() + } + + #[test] + fn c_tp_new_is_called() { + Python::attach(|_py| { + with_current_vm(|vm| { + let ty = heap_type("CType", vm.ctx.types.object_type, vm); + set_tp_new(vm, &ty, echo_new).unwrap(); + + let echo = call(&ty, FuncArgs::default(), vm); + assert_eq!(echoed_name(&echo), "CType"); + assert_eq!(echo[1].clone().downcast::().unwrap().len(), 0); + // No keywords were passed, so kwds must be NULL. + assert!(echo[2].clone().try_to_bool(vm).unwrap()); + + let echo = call(&ty, FuncArgs::from(vec![vm.ctx.new_int(1).into()]), vm); + assert_eq!(echo[1].clone().downcast::().unwrap().len(), 1); + + let kwargs: KwArgs = + core::iter::once(("k".to_owned(), vm.ctx.new_int(2).into())).collect(); + let echo = call(&ty, FuncArgs::new(vec![], kwargs), vm); + assert!(!echo[2].clone().try_to_bool(vm).unwrap()); + }) + }) + } + + /// `Py_tp_new` in a type spec lands in the type's table: the type + /// instantiates through it, `__new__` reaches it the checked way, and + /// `PyType_GetSlot` hands the same function back. + #[test] + fn spec_tp_new_is_installed() { + Python::attach(|_py| { + with_current_vm(|vm| { + let mut slots = [ + pyo3::ffi::PyType_Slot { + slot: pyo3::ffi::Py_tp_new, + pfunc: echo_new as *mut c_void, + }, + pyo3::ffi::PyType_Slot { + slot: 0, + pfunc: core::ptr::null_mut(), + }, + ]; + let mut spec = pyo3::ffi::PyType_Spec { + name: c"SpecNew".as_ptr(), + basicsize: 0, + itemsize: 0, + flags: pyo3::ffi::Py_TPFLAGS_DEFAULT as _, + slots: slots.as_mut_ptr(), + }; + let ptr = unsafe { pyo3::ffi::PyType_FromSpec(&mut spec) }; + let ptr = NonNull::new(ptr.cast::()).expect("PyType_FromSpec failed"); + let ty: PyTypeRef = unsafe { PyObjectRef::from_raw(ptr) }.downcast().unwrap(); + + assert_eq!(echoed_name(&call(&ty, FuncArgs::default(), vm)), "SpecNew"); + assert_eq!( + unsafe { PyType_GetSlot(&*ty, Py_tp_new) }, + echo_new as *mut c_void + ); + + let via_dunder = vm + .call_method( + ty.as_object(), + "__new__", + FuncArgs::from(vec![ty.clone().into()]), + ) + .unwrap() + .downcast::() + .unwrap(); + assert_eq!(echoed_name(&via_dunder), "SpecNew"); + }) + }) + } + + /// A subclass reaches the C slot through the inherited slot pair, and the + /// type it is instantiated with is the one handed to the slot. + #[test] + fn c_tp_new_is_inherited() { + Python::attach(|_py| { + with_current_vm(|vm| { + let base = heap_type("CBase", vm.ctx.types.object_type, vm); + set_tp_new(vm, &base, echo_new).unwrap(); + let sub = heap_type("CSub", &base, vm); + + assert!(sub.slots.c_slots().and_then(|c| c.new.load()).is_some()); + assert_eq!(echoed_name(&call(&sub, FuncArgs::default(), vm)), "CSub"); + }) + }) + } + + /// Every C type reaches its slot through one shared trampoline, so the + /// "is not safe" check has to compare the C functions behind it, not the + /// trampoline. Without that, `CBase.__new__(CSub)` would silently run + /// CSub's tp_new where the caller asked for CBase's. + #[test] + fn cross_type_dunder_new_call_is_rejected() { + Python::attach(|_py| { + with_current_vm(|vm| { + let base = heap_type("COuter", vm.ctx.types.object_type, vm); + set_tp_new(vm, &base, echo_new).unwrap(); + let sub = heap_type("CInner", &base, vm); + set_tp_new(vm, &sub, other_new).unwrap(); + + // Each type reaches its own C function. + assert_eq!(echoed_name(&call(&base, FuncArgs::default(), vm)), "COuter"); + assert!(call(&sub, FuncArgs::default(), vm).is_empty()); + + // But COuter.__new__(CInner) must not reach CInner's. + let dunder_new = base + .as_object() + .get_attr(identifier!(vm, __new__), vm) + .unwrap(); + let err = dunder_new.call((sub,), vm).unwrap_err(); + let msg = err.as_object().str(vm).unwrap().to_string(); + assert!( + msg.contains("is not safe"), + "expected an is-not-safe error, got {msg}" + ); + }) + }) + } + + /// `__new__` reaches the slot through `PyType::__new__`, so a direct call + /// is argument-checked instead of handing the raw pointer to the callee. + #[test] + fn direct_dunder_new_call_is_checked() { + Python::attach(|_py| { + with_current_vm(|vm| { + let ty = heap_type("CChecked", vm.ctx.types.object_type, vm); + set_tp_new(vm, &ty, echo_new).unwrap(); + let dunder_new = ty + .as_object() + .get_attr(identifier!(vm, __new__), vm) + .unwrap(); + + // No type argument at all. + assert!(dunder_new.call((), vm).is_err()); + // First argument is not a type. + assert!(dunder_new.call((vm.ctx.new_int(42),), vm).is_err()); + // First argument is a type, but not a subtype of this one. + assert!( + dunder_new + .call((vm.ctx.types.dict_type.to_owned(),), vm) + .is_err() + ); + + // The type itself and a subclass of it are accepted. + let echo = dunder_new + .call((ty.clone(),), vm) + .unwrap() + .downcast::() + .unwrap(); + assert_eq!(echoed_name(&echo), "CChecked"); + + let sub = heap_type("CCheckedSub", &ty, vm); + let echo = dunder_new + .call((sub,), vm) + .unwrap() + .downcast::() + .unwrap(); + assert_eq!(echoed_name(&echo), "CCheckedSub"); + }) + }) + } + + /// A Python-level `__new__` on a subclass replaces the inherited C slot. + #[test] + fn python_subclass_new_overrides_the_slot() { + Python::attach(|_py| { + with_current_vm(|vm| { + let base = heap_type("COverBase", vm.ctx.types.object_type, vm); + set_tp_new(vm, &base, echo_new).unwrap(); + let sub = heap_type("COverSub", &base, vm); + + let py_new = vm.ctx.new_method_def( + "__new__", + |_args: FuncArgs, vm: &VirtualMachine| -> PyResult { + Ok(vm.ctx.new_str("from python").into()) + }, + PyMethodFlags::STATIC, + ItemDoc::NONE, + ); + let py_new = py_new.build_function(vm, None); + sub.as_object() + .set_attr(identifier!(vm, __new__), py_new, vm) + .unwrap(); + + assert!(sub.slots.c_slots().is_none()); + let obj = sub.as_object().call((), vm).unwrap(); + let obj: PyStrRef = obj.downcast().unwrap(); + assert_eq!(obj.to_string(), "from python"); + }) + }) + } + + /// A type whose own dict defines `__new__` keeps it: installing a C + /// tp_new under it is refused instead of being silently shadowed. + #[test] + fn set_tp_new_rejects_a_type_defining_dunder_new() { + Python::attach(|_py| { + with_current_vm(|vm| { + let ty = heap_type("CHasNew", vm.ctx.types.object_type, vm); + let py_new = vm.ctx.new_method_def( + "__new__", + |_args: FuncArgs, vm: &VirtualMachine| -> PyResult { + Ok(vm.ctx.new_str("from python").into()) + }, + PyMethodFlags::STATIC, + ItemDoc::NONE, + ); + let py_new = py_new.build_function(vm, None); + ty.as_object() + .set_attr(identifier!(vm, __new__), py_new, vm) + .unwrap(); + + let err = set_tp_new(vm, &ty, echo_new).unwrap_err(); + assert!(err.fast_isinstance(vm.ctx.exceptions.type_error)); + assert!(ty.slots.c_slots().is_none()); + // The slot still routes to the Python `__new__`, not to C. + assert_ne!( + unsafe { PyType_GetSlot(&*ty, Py_tp_new) }, + echo_new as *mut c_void + ); + + let obj = ty.as_object().call((), vm).unwrap(); + let obj: PyStrRef = obj.downcast().unwrap(); + assert_eq!(obj.to_string(), "from python"); + + // Installing twice is refused as well. + let ty = heap_type("CTwice", vm.ctx.types.object_type, vm); + set_tp_new(vm, &ty, echo_new).unwrap(); + let err = set_tp_new(vm, &ty, other_new).unwrap_err(); + assert!(err.fast_isinstance(vm.ctx.exceptions.type_error)); + assert_eq!( + unsafe { PyType_GetSlot(&*ty, Py_tp_new) }, + echo_new as *mut c_void + ); + }) + }) + } + + #[test] + fn get_slot_round_trips() { + Python::attach(|_py| { + with_current_vm(|vm| { + let ty = heap_type("CGet", vm.ctx.types.object_type, vm); + // Inherits object's Rust tp_new until a C function is installed. + assert_eq!(unsafe { PyType_GetSlot(&*ty, Py_tp_new) }, unsafe { + PyType_GetSlot(vm.ctx.types.object_type, Py_tp_new) + },); + + set_tp_new(vm, &ty, echo_new).unwrap(); + assert_eq!( + unsafe { PyType_GetSlot(&*ty, Py_tp_new) }, + echo_new as *mut c_void + ); + + // Inherited by pointer, as tp_new is. + let sub = heap_type("CGetSub", &ty, vm); + assert_eq!( + unsafe { PyType_GetSlot(&*sub, Py_tp_new) }, + echo_new as *mut c_void + ); + }) + }) + } + + #[test] + fn rust_int_tp_new_builds_an_int_and_a_subclass() { + Python::attach(|_py| { + with_current_vm(|vm| { + let int_type = vm.ctx.types.int_type; + let tp_new = load_tp_new(int_type); + + let args = vm.ctx.new_tuple(vec![vm.ctx.new_str("42").into()]); + let value: PyRef = call_tp_new(tp_new, int_type, args).downcast().unwrap(); + assert_eq!(value.as_bigint().to_string(), "42"); + + let sub = heap_type("SubInt", int_type, vm); + let args = vm.ctx.new_tuple(vec![vm.ctx.new_str("42").into()]); + let obj = call_tp_new(tp_new, &sub, args); + assert!(obj.class().is(&sub)); + }) + }) + } + + #[test] + fn rust_object_tp_new_is_callable() { + Python::attach(|_py| { + with_current_vm(|vm| { + let object_type = vm.ctx.types.object_type; + let tp_new = load_tp_new(object_type); + let obj = call_tp_new(tp_new, object_type, vm.ctx.new_tuple(vec![])); + assert!(obj.class().is(object_type)); + }) + }) + } + + #[test] + fn inherited_int_tp_new_matches_int() { + Python::attach(|_py| { + with_current_vm(|vm| { + let int_type = vm.ctx.types.int_type; + let int_slot = unsafe { PyType_GetSlot(int_type, Py_tp_new) }; + let sub = heap_type("InheritedInt", int_type, vm); + assert!(!int_slot.is_null()); + assert_eq!(unsafe { PyType_GetSlot(&*sub, Py_tp_new) }, int_slot); + }) + }) + } + + #[test] + fn python_level_new_is_callable_from_c() { + Python::attach(|_py| { + with_current_vm(|vm| { + let sub = heap_type("PyNew", vm.ctx.types.object_type, vm); + let py_new = vm.ctx.new_method_def( + "__new__", + |_args: FuncArgs, vm: &VirtualMachine| -> PyResult { + Ok(vm.ctx.new_str("from python").into()) + }, + PyMethodFlags::STATIC, + ItemDoc::NONE, + ); + let py_new = py_new.build_function(vm, None); + sub.as_object() + .set_attr(identifier!(vm, __new__), py_new, vm) + .unwrap(); + + let tp_new = load_tp_new(&sub); + let obj = call_tp_new(tp_new, &sub, vm.ctx.new_tuple(vec![])); + let obj: PyStrRef = obj.downcast().unwrap(); + assert_eq!(obj.to_string(), "from python"); + }) + }) + } + + #[test] + fn rust_int_tp_new_sets_value_error() { + Python::attach(|_py| { + with_current_vm(|vm| { + let int_type = vm.ctx.types.int_type; + let tp_new = load_tp_new(int_type); + let args = vm + .ctx + .new_tuple(vec![vm.ctx.new_str("not a number").into()]); + let ptr = unsafe { + tp_new( + core::ptr::from_ref(int_type).cast_mut(), + args.as_object().as_raw().cast_mut(), + core::ptr::null_mut(), + ) + }; + assert!(ptr.is_null()); + let exc = vm.take_raised_exception().expect("exception pending"); + assert!(exc.fast_isinstance(vm.ctx.exceptions.value_error)); + }) + }) + } + + /// pyo3's `PyNativeTypeInitializer` calls the base `tp_new` with the subtype + /// it was given. + #[test] + fn extension_tp_new_reaches_object_tp_new_with_its_subtype() { + Python::attach(|_py| { + with_current_vm(|vm| { + let ext = heap_type("Ext", vm.ctx.types.object_type, vm); + set_tp_new(vm, &ext, new_with_object_base).unwrap(); + + let obj = ext.as_object().call((), vm).unwrap(); + assert!(obj.class().is(&ext)); + + let sub = heap_type("ExtSub", &ext, vm); + let sub_obj = sub.as_object().call((), vm).unwrap(); + assert!(sub_obj.class().is(&sub)); + }) + }) + } + + #[test] + fn extension_tp_new_reaches_int_tp_new_with_its_subtype() { + Python::attach(|_py| { + with_current_vm(|vm| { + let ext = heap_type("Ext", vm.ctx.types.int_type, vm); + set_tp_new(vm, &ext, new_with_int_base).unwrap(); + + let obj = ext.as_object().call((), vm).unwrap(); + assert!(obj.class().is(&ext)); + let value: PyRef = obj.downcast().unwrap(); + assert_eq!(value.as_bigint().to_string(), "0"); + + let sub = heap_type("ExtIntSub", &ext, vm); + let sub_obj = sub.as_object().call((), vm).unwrap(); + assert!(sub_obj.class().is(&sub)); + }) + }) + } + + #[test] + fn extension_type_reports_its_own_c_tp_new_not_the_base() { + Python::attach(|_py| { + with_current_vm(|vm| { + let object_type = vm.ctx.types.object_type; + let ext = heap_type("Ext", object_type, vm); + set_tp_new(vm, &ext, new_with_object_base).unwrap(); + + let ext_slot = unsafe { PyType_GetSlot(&*ext, Py_tp_new) }; + let base_slot = unsafe { PyType_GetSlot(object_type, Py_tp_new) }; + assert_eq!(ext_slot, new_with_object_base as *mut c_void); + assert_ne!(ext_slot, base_slot); + assert!(!base_slot.is_null()); + }) + }) + } + + #[test] + fn extension_tp_new_propagates_base_error() { + Python::attach(|_py| { + with_current_vm(|vm| { + let ext = heap_type("Ext", vm.ctx.types.int_type, vm); + set_tp_new(vm, &ext, new_with_int_base_nope).unwrap(); + + let err = ext.as_object().call((), vm).unwrap_err(); + assert!(err.fast_isinstance(vm.ctx.exceptions.value_error)); + }) + }) + } } diff --git a/crates/capi/src/pybuffer.rs b/crates/capi/src/pybuffer.rs new file mode 100644 index 00000000000..1eec20cd3a5 --- /dev/null +++ b/crates/capi/src/pybuffer.rs @@ -0,0 +1,335 @@ +use crate::PyObject; +use crate::pystate::with_vm; +use crate::util::FfiPtrExt; +use alloc::borrow::Cow; +use alloc::ffi::CString; +use core::ffi::{c_char, c_int, c_void}; +use core::ptr::{self, NonNull}; +use rustpython_vm::protocol::{BufferFlags, PyBuffer}; + +#[repr(C)] +#[derive(Default)] +pub struct Py_buffer { + pub buf: *mut c_void, + pub obj: *mut PyObject, + pub len: isize, + pub itemsize: isize, + pub readonly: c_int, + pub ndim: c_int, + pub format: *mut c_char, + pub shape: *mut isize, + pub strides: *mut isize, + pub suboffsets: *mut isize, + pub internal: *mut c_void, +} + +impl Py_buffer { + fn is_contiguous_for_order(&self, order: u8) -> bool { + let desc = unsafe { &(&*self.internal.cast::()).buffer.desc }; + if desc.len == 0 || desc.ndim() <= 1 { + return true; + } + + if desc.has_suboffsets() { + return false; + } + + match order { + b'C' => desc.is_contiguous(), + b'F' => desc.is_fortran_contiguous(), + b'A' => desc.is_contiguous() || desc.is_fortran_contiguous(), + _ => false, + } + } +} + +#[allow(dead_code)] +struct BufferInternal { + buffer: PyBuffer, + format: Option, +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyObject_GetBuffer( + obj: *mut PyObject, + view: *mut Py_buffer, + flags: c_int, +) -> c_int { + with_vm(|vm| { + let obj = unsafe { obj.assume_borrowed() }; + let flags = BufferFlags::from_bits_retain(flags as u32); + let buffer = PyBuffer::from_object(vm, obj, flags)?; + + if flags.contains(BufferFlags::WRITABLE) && buffer.desc.readonly { + return Err(vm.new_buffer_error("Object is not writable")); + } + + let format = flags + .contains(BufferFlags::FORMAT) + .then(|| { + CString::new(&*buffer.desc.format) + .map_err(|_| vm.new_system_error("buffer format contains NUL")) + }) + .transpose()?; + + let shape = if flags.contains(BufferFlags::ND) { + buffer.desc.shape().as_ptr().cast_mut() + } else { + ptr::null_mut() + }; + + let strides = if flags.contains(BufferFlags::STRIDES) { + buffer.desc.strides().as_ptr().cast_mut() + } else { + ptr::null_mut() + }; + + let suboffsets = if flags.contains(BufferFlags::INDIRECT) { + buffer.desc.suboffsets().as_ptr().cast_mut() + } else { + ptr::null_mut() + }; + + let mut buffer_view = Py_buffer { + len: buffer.desc.len as _, + itemsize: buffer.desc.itemsize as _, + readonly: buffer.desc.readonly.into(), + ndim: buffer.desc.ndim() as _, + format: format.as_ref().map_or_default(|s| s.as_ptr().cast_mut()), + shape, + strides, + suboffsets, + ..Default::default() + }; + + let c_contig = buffer.desc.is_contiguous(); + let f_contig = buffer.desc.is_fortran_contiguous(); + + if flags.contains(BufferFlags::C_CONTIGUOUS) && !c_contig { + return Err(vm.new_buffer_error("Object is not C-contiguous")); + } + if flags.contains(BufferFlags::F_CONTIGUOUS) && !f_contig { + return Err(vm.new_buffer_error("Object is not Fortran-contiguous")); + } + if flags.contains(BufferFlags::ANY_CONTIGUOUS) && !(c_contig || f_contig) { + return Err(vm.new_buffer_error("Object is not contiguous")); + } + + buffer_view.obj = obj.as_raw().cast_mut(); + buffer_view.buf = unsafe { + buffer + .obj_bytes() + .as_ptr() + .cast_mut() + .offset(buffer.desc.offset) + } + .cast(); + buffer_view.internal = Box::into_raw(Box::new(BufferInternal { buffer, format })).cast(); + + unsafe { + ptr::replace(view, buffer_view); + } + Ok(()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyBuffer_Release(view: *mut Py_buffer) { + let view = unsafe { &mut *view }; + let internal = unsafe { + NonNull::new(view.internal.cast::()).map(|ptr| Box::from_non_null(ptr)) + }; + drop(internal); + core::mem::take(view); +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyBuffer_IsContiguous(view: *const Py_buffer, fort: c_char) -> c_int { + unsafe { &*view } + .is_contiguous_for_order((fort as u8).to_ascii_uppercase()) + .into() +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyBuffer_GetPointer( + view: *const Py_buffer, + indices: *const isize, +) -> *mut c_void { + with_vm(|vm| { + let view = unsafe { &*view }; + + if view.strides.is_null() && view.shape.is_null() { + let i0 = unsafe { *indices }; + let delta = i0 + .checked_mul(view.itemsize) + .ok_or_else(|| vm.new_system_error("index * itemsize overflow"))?; + return unsafe { Ok(view.buf.cast::().offset(delta).cast()) }; + } + + let ndim: usize = view + .ndim + .try_into() + .map_err(|_| vm.new_system_error("view.ndim does not fit usize"))?; + + let idx = unsafe { core::slice::from_raw_parts(indices, ndim) }; + + let strides: Cow<'_, _> = unsafe { view.strides.as_ref() }.map_or_else( + || { + let shape = unsafe { core::slice::from_raw_parts(view.shape, ndim) }; + let mut strides = vec![0; shape.len()]; + let mut stride = view.itemsize; + for (ix, dim) in shape.iter().copied().enumerate().rev() { + strides[ix] = stride; + stride = stride + .checked_mul(dim) + .ok_or_else(|| vm.new_system_error("stride overflow"))?; + } + Ok(strides.into()) + }, + |strides| unsafe { Ok(core::slice::from_raw_parts(strides, ndim).into()) }, + )?; + + let suboffsets = unsafe { + view.suboffsets + .as_ref() + .map(|suboffsets| core::slice::from_raw_parts(suboffsets, ndim)) + }; + + let mut ptr_u8 = view.buf.cast::(); + for (dim, index) in idx.iter().enumerate() { + let delta = index + .checked_mul(strides[dim]) + .ok_or_else(|| vm.new_system_error("index * stride overflow"))?; + ptr_u8 = unsafe { ptr_u8.offset(delta) }; + if let Some(suboffsets) = suboffsets { + let suboffset = suboffsets[dim]; + if suboffset >= 0 { + let inner = unsafe { core::ptr::read_unaligned(ptr_u8.cast::<*mut u8>()) }; + ptr_u8 = unsafe { inner.offset(suboffset) }; + } + } + } + + Ok(ptr_u8.cast()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyBuffer_ToContiguous( + buf: *mut c_void, + view: *const Py_buffer, + len: isize, + order: c_char, +) -> c_int { + with_vm(|vm| { + let view = unsafe { &*view }; + + if !view.is_contiguous_for_order((order as u8).to_ascii_uppercase()) { + return Err(vm.new_buffer_error( + "PyBuffer_ToContiguous only supports contiguous exported buffers", + )); + } + + if len != view.len { + return Err(vm.new_buffer_error("len must match view->len")); + } + + let len: usize = len + .try_into() + .map_err(|_| vm.new_system_error("buffer len does not fit usize"))?; + + let src = unsafe { core::slice::from_raw_parts(view.buf.cast::(), len) }; + let dst = unsafe { core::slice::from_raw_parts_mut(buf.cast::(), len) }; + + dst.copy_from_slice(src); + Ok(()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyBuffer_FromContiguous( + view: *const Py_buffer, + buf: *const c_void, + len: isize, + order: c_char, +) -> c_int { + with_vm(|vm| { + let view = unsafe { &*view }; + + if view.readonly != 0 { + return Err(vm.new_buffer_error("cannot write into readonly buffer")); + } + + if !view.is_contiguous_for_order((order as u8).to_ascii_uppercase()) { + return Err(vm.new_buffer_error( + "PyBuffer_FromContiguous only supports contiguous exported buffers", + )); + } + + let len: usize = len + .min(view.len) + .try_into() + .map_err(|_| vm.new_system_error("len does not fit usize"))?; + + let src = unsafe { core::slice::from_raw_parts(buf.cast::(), len) }; + let dst = unsafe { core::slice::from_raw_parts_mut(view.buf.cast::(), len) }; + dst.copy_from_slice(src); + Ok(()) + }) +} + +#[cfg(test)] +mod tests { + use pyo3::buffer::PyBuffer; + use pyo3::prelude::*; + use pyo3::types::{PyByteArray, PyBytes}; + + #[test] + fn object_getbuffer_basic_and_release() { + Python::attach(|py| { + let bytes = PyBytes::new(py, b"hello"); + let buffer = PyBuffer::::get(&bytes).unwrap(); + assert_eq!(buffer.dimensions(), 1); + assert_eq!(buffer.item_count(), 5); + assert_eq!(buffer.to_vec(py).unwrap(), b"hello"); + }); + } + + #[test] + fn contiguous_copy_roundtrip() { + Python::attach(|py| { + let src = PyBytes::new(py, b"abcde"); + let buffer = PyBuffer::::get(&src).unwrap(); + let mut out = [0u8; 5]; + buffer.copy_to_slice(py, &mut out).unwrap(); + assert_eq!(&out, b"abcde"); + }); + } + + #[test] + fn is_contiguous_and_get_pointer() { + Python::attach(|py| { + let bytes = PyBytes::new(py, b"xyz"); + let buffer = PyBuffer::::get(&bytes).unwrap(); + assert!(buffer.is_c_contiguous()); + + let p = buffer.get_ptr(&[1]); + assert!(!p.is_null()); + unsafe { assert_eq!(*(p.cast::()), b'y') }; + }); + } + + #[test] + fn writable_bytearray() { + Python::attach(|py| { + let bytearray = PyByteArray::new(py, b"hello"); + let buffer = PyBuffer::::get(&bytearray).unwrap(); + assert_eq!(buffer.dimensions(), 1); + assert_eq!(buffer.item_count(), 5); + // SAFETY: There are no other references to the buffer. + unsafe { buffer.as_slice_ptr().unwrap().as_mut()[0] = b'H' }; + drop(buffer); + assert_eq!(bytearray.to_vec(), b"Hello"); + }); + } +} diff --git a/crates/capi/src/pycapsule.rs b/crates/capi/src/pycapsule.rs index c46e33c0301..0fcdd6b93a7 100644 --- a/crates/capi/src/pycapsule.rs +++ b/crates/capi/src/pycapsule.rs @@ -38,7 +38,7 @@ pub unsafe extern "C" fn PyCapsule_GetName(capsule: *mut PyObject) -> *const c_c let capsule = unsafe { capsule.assume_borrowed() } .downcast_ref_if_exact::(vm) .ok_or_else(|| vm.new_value_error("Invalid capsule"))?; - Ok(capsule.name().map(CStr::as_ptr).unwrap_or_default()) + Ok(capsule.name().map_or_default(CStr::as_ptr)) }) } @@ -135,7 +135,7 @@ fn checked_capsule<'a>( .downcast_ref_if_exact::(vm) .ok_or_else(|| vm.new_value_error("Invalid capsule"))?; - if !names_match(capsule.name().map(CStr::as_ptr).unwrap_or_default(), name) { + if !names_match(capsule.name().map_or_default(CStr::as_ptr), name) { return Err(vm.new_value_error("Capsule name does not match")); } diff --git a/crates/capi/src/pyerrors.rs b/crates/capi/src/pyerrors.rs index e43358ae348..9619030434b 100644 --- a/crates/capi/src/pyerrors.rs +++ b/crates/capi/src/pyerrors.rs @@ -2,10 +2,9 @@ use crate::object::define_py_check; use crate::util::{CStrExt, FfiPtrExt}; use crate::{PyObject, pystate::with_vm}; use core::convert::Infallible; -use core::ffi::{c_char, c_int}; +use core::ffi::{VaList, c_char, c_int}; use core::slice; use rustpython_vm::builtins::{PyBaseException, PyTraceback, PyTuple, PyType}; -use rustpython_vm::convert::IntoObject; use rustpython_vm::exceptions::ExceptionZoo; use rustpython_vm::{AsObject, PyResult}; @@ -102,9 +101,8 @@ define_py_check!(fn PyExceptionInstance_Check, exceptions.base_exception_type); #[unsafe(no_mangle)] pub extern "C" fn PyErr_Occurred() -> *mut PyObject { with_vm(|vm| { - vm.current_exception() - .map(|exc| exc.class().as_object().as_raw()) - .unwrap_or_default() + vm.raised_exception() + .map_or_default(|exc| exc.class().as_object().as_raw()) }) } @@ -112,8 +110,7 @@ pub extern "C" fn PyErr_Occurred() -> *mut PyObject { pub extern "C" fn PyErr_GetRaisedException() -> *mut PyObject { with_vm(|vm| { vm.take_raised_exception() - .map(|exc| exc.into_object().into_raw().as_ptr()) - .unwrap_or_default() + .map_or_default(|exc| exc.into_object().into_raw().as_ptr()) }) } @@ -122,7 +119,7 @@ pub unsafe extern "C" fn PyErr_SetRaisedException(exc: *mut PyObject) { with_vm(|vm| { let exception = unsafe { exc.assume_owned_or_opt() }.map(|exc| unsafe { exc.downcast_unchecked() }); - vm.set_exception(exception); + vm.set_raised_exception(exception); }) } @@ -132,6 +129,15 @@ pub unsafe extern "C" fn PyErr_SetObject(exception: *mut PyObject, value: *mut P let exc_type = unsafe { exception.assume_borrowed() }.to_owned(); let exc_val = unsafe { value.assume_borrowed() }.to_owned(); + if let Some(cls) = exc_type.downcast_ref::() + && cls.fast_issubclass(vm.ctx.exceptions.base_exception_type) + && !exc_val + .downcast_ref::() + .is_some_and(|exc| exc.fast_isinstance(cls)) + { + // Exception constructors must run without a pending C error. + vm.set_raised_exception(None); + } let normalized = vm.normalize_exception(exc_type, exc_val, vm.ctx.none())?; Err(normalized) }) @@ -143,6 +149,7 @@ pub unsafe extern "C" fn PyErr_SetString(exception: *mut PyObject, message: *con let exc_type = unsafe { exception.assume_borrowed_and_cast::(vm) }?; let message = unsafe { message.try_as_str(vm) }?; + vm.set_raised_exception(None); let exc = vm.invoke_exception(exc_type, vec![vm.ctx.new_str(message).into_object()])?; Err(exc) @@ -259,8 +266,7 @@ pub unsafe extern "C" fn PyException_GetTraceback(exc: *mut PyObject) -> *mut Py let exc = unsafe { exc.assume_borrowed_and_cast::(vm) }?; let tb = exc .traceback() - .map(|tb| tb.into_object().into_raw().as_ptr()) - .unwrap_or_default(); + .map_or_default(|tb| tb.into_object().into_raw().as_ptr()); Ok(tb) }) } @@ -271,8 +277,7 @@ pub unsafe extern "C" fn PyException_GetCause(exc: *mut PyObject) -> *mut PyObje let exc = unsafe { exc.assume_borrowed_and_cast::(vm) }?; let cause = exc .__cause__() - .map(|cause| cause.into_object().into_raw().as_ptr()) - .unwrap_or_default(); + .map_or_default(|cause| cause.into_object().into_raw().as_ptr()); Ok(cause) }) } @@ -283,8 +288,7 @@ pub unsafe extern "C" fn PyException_GetContext(exc: *mut PyObject) -> *mut PyOb let exc = unsafe { exc.assume_borrowed_and_cast::(vm) }?; let context = exc .__context__() - .map(|context| context.into_object().into_raw().as_ptr()) - .unwrap_or_default(); + .map_or_default(|context| context.into_object().into_raw().as_ptr()); Ok(context) }) } @@ -372,6 +376,45 @@ pub unsafe extern "C" fn PyException_SetTraceback(exc: *mut PyObject, tb: *mut P }) } +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyOS_snprintf( + str: *mut c_char, + size: usize, + format: *const c_char, + args: ... +) -> c_int { + unsafe { PyOS_vsnprintf(str, size, format, args) } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyOS_vsnprintf( + str: *mut c_char, + size: usize, + format: *const c_char, + args: VaList<'_>, +) -> c_int { + unsafe extern "C" { + fn vsnprintf( + str: *mut c_char, + size: usize, + format: *const c_char, + args: VaList<'_>, + ) -> c_int; + } + + let len = if size > (c_int::MAX as usize - 1) { + -666 + } else { + unsafe { vsnprintf(str, size, format, args) } + }; + + if size > 0 && !str.is_null() { + unsafe { *str.add(size - 1) = 0 }; + } + + len +} + #[cfg(test)] mod tests { use pyo3::PyTypeInfo; diff --git a/crates/capi/src/pyframe.rs b/crates/capi/src/pyframe.rs index 2214ee55820..c3e81c235b3 100644 --- a/crates/capi/src/pyframe.rs +++ b/crates/capi/src/pyframe.rs @@ -2,9 +2,9 @@ use crate::PyObject; use crate::pystate::with_vm; use crate::util::FfiPtrExt; use core::ffi::c_int; -use rustpython_vm::Py; use rustpython_vm::builtins::PyCode; use rustpython_vm::frame::FrameObject; +use rustpython_vm::{Py, PyObjectRef}; pub type PyFrameObject = Py; pub type PyCodeObject = Py; @@ -26,7 +26,7 @@ pub unsafe extern "C" fn PyFrame_GetLocals(frame: *mut PyFrameObject) -> *mut Py #[unsafe(no_mangle)] pub unsafe extern "C" fn PyFrame_GetGlobals(frame: *mut PyFrameObject) -> *mut PyObject { - with_vm(|_vm| Ok(unsafe { frame.assume_borrowed() }.f_globals())) + with_vm(|_vm| PyObjectRef::from(unsafe { frame.assume_borrowed() }.f_globals())) } #[unsafe(no_mangle)] diff --git a/crates/capi/src/pylifecycle.rs b/crates/capi/src/pylifecycle.rs index 7255a0e34a5..58f8ecd08c4 100644 --- a/crates/capi/src/pylifecycle.rs +++ b/crates/capi/src/pylifecycle.rs @@ -19,7 +19,7 @@ pub(crate) fn request_vm_from_interpreter() -> ThreadedVirtualMachine { get_main_interpreter() .as_ref() .expect("Interpreter not initialized") - .enter(|vm| vm.new_thread()) + .new_thread() } #[unsafe(no_mangle)] @@ -50,7 +50,11 @@ pub extern "C" fn Py_InitializeEx(_initsigs: c_int) { let path = rustpython_pylib::LIB_PATH.to_owned(); state.config.paths.stdlib_dir = Some(path.clone()); - state.config.paths.module_search_paths.insert(0, path); + state + .config + .paths + .module_search_paths + .insert(0, path.into()); }) .build() .into(); @@ -123,4 +127,27 @@ mod tests { assert!(unsafe { pyo3::ffi::Py_Version } >= 0x030d0000); } + + #[test] + fn requesting_thread_vm_does_not_attach() { + use rustpython_vm::vm::thread::{current_thread_slot, current_vm_is_set}; + + Python::attach(|py| { + let handle = std::thread::spawn(|| { + let before = (current_vm_is_set(), current_thread_slot().is_some()); + let worker_vm = super::request_vm_from_interpreter(); + let after = (current_vm_is_set(), current_thread_slot().is_some()); + (worker_vm, before, after) + }); + let (worker_vm, before, after) = py.detach(|| handle.join().unwrap()); + // Drop cloned Python references under the parent interpreter context. + drop(worker_vm); + assert_eq!(before, (false, false), "worker must start outside any VM"); + assert_eq!( + after, + (false, false), + "creating a worker VM must not attach under MAIN_INTERP" + ); + }); + } } diff --git a/crates/capi/src/slots.rs b/crates/capi/src/slots.rs index 79b11c7b450..590ffcf3bd8 100644 --- a/crates/capi/src/slots.rs +++ b/crates/capi/src/slots.rs @@ -3,12 +3,16 @@ use crate::methodobject::PyMethodDef; use crate::modsupport::PyABIInfo; use crate::object::PyType_Slot; use crate::util::CStrExt; +use alloc::borrow::Cow; use core::ffi::{c_char, c_int, c_void}; -use core::slice::from_ref; +use core::num::TryFromIntError; +use itertools::Either; use rustpython_vm::builtins::{PyModule, PyType}; +use rustpython_vm::types::SlotAccessor; use rustpython_vm::{Py, PyResult, VirtualMachine}; #[repr(C)] +#[derive(Clone)] pub struct PySlot { pub sl_id: u16, pub sl_flags: u16, @@ -16,19 +20,83 @@ pub struct PySlot { pub value: PySlotValue, } +impl TryFrom<&PyType_Slot> for PySlot { + type Error = TryFromIntError; + + fn try_from(slot: &PyType_Slot) -> Result { + Ok(Self { + sl_id: slot.slot.try_into()?, + sl_flags: 0, + _reserved: 0, + value: slot.pfunc.into(), + }) + } +} + impl PySlot { const SLOT_OPTIONAL: u16 = 0x0001; const SLOT_STATIC: u16 = 0x0002; const SLOT_INTPTR: u16 = 0x0004; + pub(crate) const SLOT_END: Self = unsafe { core::mem::zeroed() }; + + pub(crate) fn new(id: u16, value: impl Into) -> Self { + Self { + sl_id: id, + sl_flags: 0, + _reserved: 0, + value: value.into(), + } + } - pub(crate) fn iter<'a>(mut slots: *const Self) -> impl Iterator { + pub(crate) fn iter<'a>(slots: *const Self) -> impl Iterator> { + let mut stack: Vec> = vec![Either::Left(slots)]; core::iter::from_fn(move || { - let slot = unsafe { &*slots }; - if slot.sl_id == 0 { - None - } else { - slots = unsafe { slots.add(1) }; - Some(slot) + loop { + assert!( + stack.len() <= 10, + "Too many nested slots, possible infinite loop in slot iteration" + ); + return match stack.last_mut()? { + Either::Left(slot_ptr) => { + let slot = unsafe { &**slot_ptr }; + if slot.sl_id == 0 { + stack.pop(); + continue; + } + + *slot_ptr = unsafe { slot_ptr.add(1) }; + + if slot.sl_id == 92 { + let subslots = unsafe { slot.value.sl_ptr }.cast_const().cast::(); + if !subslots.is_null() { + stack.push(Either::Left(subslots)); + } + continue; + } + + if slot.sl_id == 93 { + let type_slots = unsafe { slot.value.sl_ptr } + .cast_const() + .cast::(); + if !type_slots.is_null() { + stack.push(Either::Right(type_slots)); + } + continue; + } + + Some(Cow::Borrowed(slot)) + } + Either::Right(slot_ptr) => { + let type_slot = unsafe { &**slot_ptr }; + if type_slot.slot == 0 { + stack.pop(); + continue; + } + + *slot_ptr = unsafe { slot_ptr.add(1) }; + Some(Cow::Owned(type_slot.try_into().expect("invalid slot"))) + } + }; } }) } @@ -48,12 +116,15 @@ impl PySlot { self.sl_flags & Self::SLOT_INTPTR != 0 } - pub(crate) fn as_kind(&self, vm: &VirtualMachine) -> PyResult> { + pub(crate) fn as_kind<'a>(&self, vm: &VirtualMachine) -> PyResult> { let value_ptr = unsafe { self.value.sl_ptr }; let is_static = self.is_static(); let kind = match self.sl_id { - 48 => PySlotKind::Type(PySlotType::Base(unsafe { &*value_ptr.cast() })), - 49 => PySlotKind::Type(PySlotType::Bases(unsafe { from_ref(&*value_ptr.cast()) })), + 1..82 => { + let slot_id: u8 = self.sl_id.try_into().unwrap(); + let accessor = slot_id.try_into().unwrap(); + PySlotKind::Type(PySlotType::TypeSlot(accessor, value_ptr)) + } 84 => { let create = unsafe { core::mem::transmute::< @@ -79,16 +150,15 @@ impl PySlot { 87 => PySlotKind::Module(PySlotModule::Gil { gil_used: !value_ptr.is_null(), }), - // 92 => Py_slot_subslots - 93 => PySlotKind::Type(PySlotType::Slots { - value: value_ptr.cast(), - is_static, - }), + 92 | 93 => { + unreachable!("Py_slot_subslots and Py_tp_slots should be handled in the iterator") + } 95 => PySlotKind::Type(PySlotType::Name(unsafe { value_ptr.cast::().try_as_str(vm)? })), 96 => PySlotKind::Type(PySlotType::BasicSize(unsafe { self.value.sl_size })), 97 => PySlotKind::Type(PySlotType::ExtraBasicSize(unsafe { self.value.sl_size })), + 98 => PySlotKind::Type(PySlotType::ItemSize(unsafe { self.value.sl_size })), 99 => PySlotKind::Type(PySlotType::Flags(unsafe { self.value.sl_uint64 })), 100 => PySlotKind::Module(PySlotModule::Name(unsafe { value_ptr.cast::().try_as_str(vm)? @@ -122,6 +192,7 @@ impl PySlot { } #[repr(C)] +#[derive(Copy, Clone)] pub union PySlotValue { pub sl_ptr: *mut c_void, pub sl_func: unsafe extern "C" fn(), @@ -130,6 +201,24 @@ pub union PySlotValue { pub sl_uint64: u64, } +impl From<*mut T> for PySlotValue { + fn from(ptr: *mut T) -> Self { + Self { sl_ptr: ptr.cast() } + } +} + +impl From for PySlotValue { + fn from(size: isize) -> Self { + Self { sl_size: size } + } +} + +impl From for PySlotValue { + fn from(value: u64) -> Self { + Self { sl_uint64: value } + } +} + #[allow(dead_code)] #[derive(Debug, Copy, Clone)] pub(crate) enum PySlotModule<'a> { @@ -146,16 +235,12 @@ pub(crate) enum PySlotModule<'a> { #[allow(dead_code)] #[derive(Debug, Copy, Clone)] pub(crate) enum PySlotType<'a> { - Base(&'a Py), - Bases(&'a [Py]), - Slots { - value: *mut PyType_Slot, - is_static: bool, - }, + TypeSlot(SlotAccessor, *mut c_void), Name(&'a str), Flags(u64), BasicSize(isize), ExtraBasicSize(isize), + ItemSize(isize), Metaclass(&'a Py), Module(&'a Py), } diff --git a/crates/capi/src/sysmodule.rs b/crates/capi/src/sysmodule.rs new file mode 100644 index 00000000000..eecbf91ad5a --- /dev/null +++ b/crates/capi/src/sysmodule.rs @@ -0,0 +1,93 @@ +use crate::PyObject; +use crate::pystate::with_vm; +use crate::util::{CStrExt, FfiPtrExt}; +use core::ffi::{c_char, c_int}; +use rustpython_vm::AsObject; +use rustpython_vm::builtins::{PyDict, PyStr}; + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PySys_GetAttr(name: *mut PyObject) -> *mut PyObject { + with_vm(|vm| { + let name = unsafe { name.assume_borrowed_and_cast::(vm) }?; + vm.sys_module.dict().get_item(name, vm) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PySys_GetAttrString(name: *const c_char) -> *mut PyObject { + with_vm(|vm| { + let name = unsafe { name.try_as_str(vm) }?; + vm.sys_module.dict().get_item(name, vm) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PySys_GetObject(name: *const c_char) -> *mut PyObject { + with_vm(|vm| { + let Ok(name) = (unsafe { name.try_as_str(vm) }) else { + return core::ptr::null(); + }; + vm.sys_module + .dict() + .get_item_opt(name, vm) + .ok() + .flatten() + .map_or_default(|value| value.as_object().as_raw()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PySys_GetOptionalAttr( + name: *mut PyObject, + result: *mut *mut PyObject, +) -> c_int { + with_vm(|vm| { + unsafe { *result = core::ptr::null_mut() }; + let name = unsafe { name.assume_borrowed_and_cast::(vm) }?; + if let Some(value) = vm.sys_module.dict().get_item_opt(name, vm)? { + unsafe { *result = value.into_raw().as_ptr() }; + Ok(true) + } else { + Ok(false) + } + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PySys_GetOptionalAttrString( + name: *const c_char, + result: *mut *mut PyObject, +) -> c_int { + with_vm(|vm| { + unsafe { *result = core::ptr::null_mut() }; + let name = unsafe { name.try_as_str(vm) }?; + if let Some(value) = vm.sys_module.dict().get_item_opt(name, vm)? { + unsafe { *result = value.into_raw().as_ptr() }; + Ok(true) + } else { + Ok(false) + } + }) +} + +#[unsafe(no_mangle)] +pub extern "C" fn PySys_GetXOptions() -> *mut PyObject { + with_vm(|vm| { + let options = vm.sys_module.dict().get_item("_xoptions", vm)?; + let options = options.try_downcast_ref::(vm)?; + Ok(options.as_object().as_raw()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PySys_SetObject(name: *const c_char, value: *mut PyObject) -> c_int { + with_vm(|vm| { + let name = unsafe { name.try_as_str(vm) }?; + let dict = vm.sys_module.dict(); + if let Some(value) = unsafe { value.assume_borrowed_or_opt() } { + dict.set_item(name, value.to_owned(), vm) + } else { + dict.del_item(name, vm) + } + }) +} diff --git a/crates/capi/src/tupleobject.rs b/crates/capi/src/tupleobject.rs index 2a3a2d4abbf..1c02f6ad130 100644 --- a/crates/capi/src/tupleobject.rs +++ b/crates/capi/src/tupleobject.rs @@ -3,8 +3,9 @@ use crate::object::define_py_check; use crate::pystate::with_vm; use crate::util::FfiPtrExt; use core::ffi::c_int; +use core::ptr; use core::slice; -use rustpython_vm::PyResult; +use rustpython_vm::AsObject; use rustpython_vm::builtins::PyTuple; use rustpython_vm::sliceable::SliceableSequenceOp; @@ -15,12 +16,13 @@ define_py_check!(exact fn PyTuple_CheckExact, types.tuple_type); pub extern "C" fn PyTuple_New(len: isize) -> *mut PyObject { with_vm(|vm| { if len == 0 { - return Ok(vm.ctx.empty_tuple.to_owned()); + Ok(vm.ctx.empty_tuple.to_owned()) + } else { + let len: usize = len + .try_into() + .map_err(|_| vm.new_system_error("Negative size passed to PyTuple_New"))?; + Ok(vm.new_tuple(vec![vm.ctx.none(); len])) } - - Err(vm.new_not_implemented_error( - "PyTuple_New for non zero sized tuples is not supported, use PyTuple_FromArray instead", - )) }) } @@ -61,14 +63,30 @@ pub unsafe extern "C" fn PyTuple_Pack(len: isize, mut args: ...) -> *mut PyObjec } #[unsafe(no_mangle)] -pub extern "C" fn PyTuple_SetItem( - _tuple: *mut PyObject, - _pos: isize, - _value: *mut PyObject, +pub unsafe extern "C" fn PyTuple_SetItem( + tuple: *mut PyObject, + pos: isize, + value: *mut PyObject, ) -> c_int { - with_vm::, _>( - |vm| Err(vm.new_not_implemented_error("Tuple objects are immutable")), - ) + with_vm(|vm| { + let tuple = unsafe { tuple.assume_borrowed_and_cast::(vm)? }; + let value = unsafe { value.assume_owned() }; + let index: usize = pos + .try_into() + .map_err(|_| vm.new_index_error("negative position"))?; + + if tuple.len() <= index { + Err(vm.new_index_error("tuple index out of range")) + } else if tuple.as_object().strong_count() > 1 { + Err(vm.new_system_error("Tuple objects are immutable when the reference count > 1")) + } else { + // SAFETY: We have exclusive access to the tuple payload (strong_count == 1), + // so mutating the selected element in place is valid. + let data_ptr = unsafe { tuple.as_ptr().add(index).cast_mut() }; + unsafe { ptr::replace(data_ptr, value) }; + Ok(()) + } + }) } #[unsafe(no_mangle)] @@ -111,6 +129,7 @@ pub unsafe extern "C" fn PyTuple_GetSlice( #[cfg(test)] mod tests { + use pyo3::ffi; use pyo3::prelude::*; use pyo3::types::PyTuple; @@ -138,4 +157,29 @@ mod tests { assert_eq!(slice.extract::<(u32,)>().unwrap(), (2,)); }) } + + #[test] + fn tuple_is_mutable_with_one_ref() { + Python::attach(|py| { + let value: Bound<'_, _> = 1.into_pyobject(py).unwrap(); + let tuple: Bound<'_, PyTuple> = + unsafe { Bound::from_owned_ptr(py, ffi::PyTuple_New(1)).cast_into_unchecked() }; + assert!(tuple.get_item(0).unwrap().is_none()); + unsafe { + assert_eq!( + ffi::PyTuple_SetItem(tuple.as_ptr(), 0, value.clone().into_ptr()), + 0 + ); + } + assert_eq!(tuple.get_item(0).unwrap().extract::().unwrap(), 1); + let _new_ref = tuple.clone(); + unsafe { + assert_eq!( + ffi::PyTuple_SetItem(tuple.as_ptr(), 0, value.clone().into_ptr()), + -1 + ); + } + assert!(PyErr::take(py).is_some()) + }) + } } diff --git a/crates/capi/src/unicodeobject.rs b/crates/capi/src/unicodeobject.rs index fd78fa20ba8..20ec5e7587f 100644 --- a/crates/capi/src/unicodeobject.rs +++ b/crates/capi/src/unicodeobject.rs @@ -8,6 +8,9 @@ use rustpython_vm::builtins::{PyBytesRef, PyStr, PyStrRef, PyUtf8StrRef}; use rustpython_vm::common::wtf8::{CodePoint, Wtf8Buf}; use rustpython_vm::convert::ToPyObject; use rustpython_vm::{AsObject, PyObjectRef, PyResult, VirtualMachine}; +pub use writer::*; + +mod writer; define_py_check!(fn PyUnicode_Check, types.str_type); define_py_check!(exact fn PyUnicode_CheckExact, types.str_type); diff --git a/crates/capi/src/unicodeobject/writer.rs b/crates/capi/src/unicodeobject/writer.rs new file mode 100644 index 00000000000..46c7eb8008d --- /dev/null +++ b/crates/capi/src/unicodeobject/writer.rs @@ -0,0 +1,145 @@ +use crate::pystate::with_vm; +use crate::util::CStrExt; +use core::ffi::{c_char, c_int}; +use core::ptr::NonNull; +use core::{slice, str}; +use rustpython_vm::common::wtf8::{CodePoint, Wtf8Buf}; +use rustpython_vm::{PyObject, PyResult, VirtualMachine}; + +pub struct PyUnicodeWriter { + buffer: Wtf8Buf, +} + +impl PyUnicodeWriter { + fn try_reserve(&mut self, vm: &VirtualMachine, additional: usize) -> PyResult<()> { + self.buffer + .try_reserve(additional) + .map_err(|_| vm.no_memory_error()) + } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyUnicodeWriter_Create(length: isize) -> *mut PyUnicodeWriter { + with_vm(|vm| { + let length = length + .try_into() + .map_err(|_| vm.new_value_error("invalid length"))?; + + let writer = Box::into_raw(Box::new(PyUnicodeWriter { + buffer: Wtf8Buf::with_capacity(length), + })); + + Ok(writer) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyUnicodeWriter_Finish(writer: *mut PyUnicodeWriter) -> *mut PyObject { + with_vm(|vm| { + let writer = unsafe { Box::from_raw(writer) }; + Ok(vm.ctx.new_str(writer.buffer)) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyUnicodeWriter_Discard(writer: *mut PyUnicodeWriter) { + if let Some(ptr) = NonNull::new(writer) { + let _ = unsafe { Box::from_non_null(ptr) }; + } +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyUnicodeWriter_WriteChar(writer: *mut PyUnicodeWriter, ch: u32) -> c_int { + with_vm(|vm| { + let writer = unsafe { &mut *writer }; + let codepoint = + CodePoint::from_u32(ch).ok_or_else(|| vm.new_value_error("invalid char"))?; + writer.try_reserve(vm, 4)?; + writer.buffer.push(codepoint); + Ok(()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyUnicodeWriter_WriteUTF8( + writer: *mut PyUnicodeWriter, + str: *const c_char, + size: isize, +) -> c_int { + with_vm(|vm| { + let writer = unsafe { &mut *writer }; + let str = if size == -1 { + unsafe { str.try_as_str(vm)? } + } else { + let length = size + .try_into() + .map_err(|_| vm.new_value_error("invalid size"))?; + let slice = unsafe { slice::from_raw_parts(str as *const u8, length) }; + str::from_utf8(slice).map_err(|_| vm.new_system_error("invalid UTF-8"))? + }; + writer.try_reserve(vm, str.len())?; + writer.buffer.push_str(str); + Ok(()) + }) +} + +#[unsafe(no_mangle)] +pub unsafe extern "C" fn PyUnicodeWriter_WriteASCII( + writer: *mut PyUnicodeWriter, + str: *const c_char, + size: isize, +) -> c_int { + unsafe { PyUnicodeWriter_WriteUTF8(writer, str, size) } +} + +#[cfg(test)] +mod tests { + use super::*; + use pyo3::prelude::*; + use pyo3::py_format; + use pyo3::types::PyString; + + #[test] + fn format_using_unicode_writer() { + Python::attach(|py| { + let name = String::from("world"); + let _string = py_format!(py, "Hello, {}!", name).unwrap(); + }); + } + + #[test] + fn unicode_writer_raw() { + Python::attach(|py| { + let writer_ptr = unsafe { PyUnicodeWriter_Create(0) }; + assert!(!writer_ptr.is_null()); + + let hello = "Hello, "; + let world = "world!"; + let _ = unsafe { + PyUnicodeWriter_WriteUTF8( + writer_ptr, + hello.as_ptr() as *const _, + hello.len() as isize, + ) + }; + let _ = unsafe { + PyUnicodeWriter_WriteUTF8( + writer_ptr, + world.as_ptr() as *const _, + world.len() as isize, + ) + }; + assert_eq!(unsafe { PyUnicodeWriter_WriteChar(writer_ptr, 0xD800) }, 0); + + let string_ptr = unsafe { PyUnicodeWriter_Finish(writer_ptr) }; + assert!(!string_ptr.is_null()); + + let string = unsafe { + Bound::from_owned_ptr(py, string_ptr.cast()) + .cast_into::() + .unwrap() + }; + assert_eq!(string.repr().unwrap(), "'Hello, world!\\ud800'"); + }); + } +} diff --git a/crates/capi/src/util.rs b/crates/capi/src/util.rs index 5d0e2c26f5a..b3fc2c39a04 100644 --- a/crates/capi/src/util.rs +++ b/crates/capi/src/util.rs @@ -1,7 +1,7 @@ use crate::PyObject; use core::any::type_name; use core::convert::Infallible; -use core::ffi::{CStr, c_char, c_double, c_int, c_long, c_ulong, c_void}; +use core::ffi::{CStr, c_char, c_double, c_int, c_long, c_ulong}; use core::ptr::NonNull; use rustpython_vm::{Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine}; @@ -40,27 +40,19 @@ where impl FfiResult<*mut Py> for PyRef where - Self: Into, + T: rustpython_vm::object::PyRefTarget>, { const ERR_VALUE: *mut Py = core::ptr::null_mut(); fn into_output(self, _vm: &VirtualMachine) -> *mut Py { - self.into().into_raw().as_ptr().cast() + PyObjectRef::from(self).into_raw().as_ptr().cast() } } -impl FfiResult<*mut PyObject> for PyObjectRef { - const ERR_VALUE: *mut PyObject = core::ptr::null_mut(); +impl FfiResult for *mut T { + const ERR_VALUE: *mut T = core::ptr::null_mut(); - fn into_output(self, _vm: &VirtualMachine) -> *mut PyObject { - self.into_raw().as_ptr() - } -} - -impl FfiResult for *mut PyObject { - const ERR_VALUE: *mut PyObject = core::ptr::null_mut(); - - fn into_output(self, _vm: &VirtualMachine) -> *mut PyObject { + fn into_output(self, _vm: &VirtualMachine) -> *mut T { self } } @@ -73,14 +65,6 @@ impl FfiResult<*mut PyObject> for *const PyObject { } } -impl FfiResult for *mut c_void { - const ERR_VALUE: *mut c_void = core::ptr::null_mut(); - - fn into_output(self, _vm: &VirtualMachine) -> *mut c_void { - self - } -} - impl FfiResult<*mut c_char> for *const u8 { const ERR_VALUE: *mut c_char = core::ptr::null_mut(); @@ -202,7 +186,7 @@ impl FfiResult<()> for PyResult { fn into_output(self, vm: &VirtualMachine) { match self { - Err(err) => vm.set_exception(Some(err)), + Err(err) => vm.set_raised_exception(Some(err)), } } } @@ -216,7 +200,7 @@ where fn into_output(self, vm: &VirtualMachine) -> Output { self.map_or_else( |err| { - vm.set_exception(Some(err)); + vm.set_raised_exception(Some(err)); T::ERR_VALUE }, |obj| obj.into_output(vm), @@ -324,7 +308,7 @@ impl FfiPtrExt for *mut Py { "Attempted to dereference NULL {}", type_name::() ); - unsafe { PyRef::from_raw(self.cast_const()) } + unsafe { PyRef::::from_raw(self.cast_const()) } } #[inline] @@ -384,6 +368,14 @@ mod tests { use core::ffi::{c_longlong, c_ulonglong}; use core::fmt::Debug; + #[test] + fn pyref_object_ffi_targets() { + use rustpython_vm::builtins::PyInt; + static_assertions::assert_impl_all!(PyObjectRef: FfiResult<*mut PyObject>); + static_assertions::assert_impl_all!(PyRef: FfiResult<*mut PyObject>, FfiResult<*mut Py>); + static_assertions::assert_not_impl_any!(PyObjectRef: FfiResult<*mut Py>); + } + #[test] fn ffi_result_err_value() { fn assert_error_value(value: Output) diff --git a/crates/codegen/src/compile.rs b/crates/codegen/src/compile.rs index c2b6446ee79..ae6492c0772 100644 --- a/crates/codegen/src/compile.rs +++ b/crates/codegen/src/compile.rs @@ -14,7 +14,9 @@ use crate::{ error::{CodegenError, CodegenErrorType, InternalError}, interpolated_string_literal_value, interpolation_debug_text, ir::{self, Block, BlockIdx, Blocks}, - preprocess, string_literal_part_value, string_literal_value, + preprocess, + source_location::{CompilerSourceSpan, node_location}, + string_literal_part_value, string_literal_value, symboltable::{self, CompilerScope, Symbol, SymbolFlags, SymbolScope, SymbolTable}, unparse::UnparseExpr, }; @@ -23,10 +25,11 @@ use core::{mem, slice}; use malachite_bigint::BigInt; use num_complex::Complex; use num_traits::{Num, ToPrimitive, Zero}; -use ruff_python_ast::{self as ast, name::Name}; +use ruff_python_ast::{self as ast, HasNodeIndex, name::Name}; use ruff_text_size::{Ranged, TextRange, TextSize, TextSlice}; use rustpython_compiler_core::{ - Mode, OneIndexed, PositionEncoding, SourceFile, SourceLocation, + AstLocations, Mode, OneIndexed, PositionEncoding, SourceFile, SourceLocation, + SourceLocationRange, bytecode::{ self, AnyInstruction, AnyOpcode, Arg as OpArgMarker, BinaryOperator, BuildSliceArgCount, CodeObject, ComparisonOperator, ConstantData, ConvertValueOparg, Instruction, @@ -68,6 +71,7 @@ const CO_MAXBLOCKS: usize = 21; pub enum FBlockType { WhileLoop, ForLoop, + AsyncForLoop, TryExcept, FinallyTry, FinallyEnd, @@ -107,6 +111,8 @@ enum SuperCallType<'a> { #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum BuiltinGeneratorCallKind { Tuple, + List, + Set, All, Any, } @@ -118,7 +124,7 @@ pub struct FBlockInfo { pub(crate) fb_block: ir::InstructionSequenceLabel, // CPython's optional type-specific exit or cleanup jump_target_label. pub(crate) fb_exit: ir::InstructionSequenceLabel, - pub fb_range: TextRange, + pub(crate) fb_span: CompilerSourceSpan, // additional data for fblock unwinding pub fb_datum: FBlockDatum, } @@ -148,36 +154,39 @@ fn checked_future_features( let source_code = source_file.to_source_code(); let location = source_code.source_location(err.range.start(), PositionEncoding::Utf8); let end_location = source_code.source_location(err.range.end(), PositionEncoding::Utf8); - let error = match err.kind { - preprocess::FutureFeatureErrorKind::InvalidFeature(feature) => { - CodegenErrorType::InvalidFutureFeature(feature) - } - preprocess::FutureFeatureErrorKind::InvalidBraces => { - CodegenErrorType::InvalidFutureBraces - } - }; CodegenError { location: Some(location), end_location: Some(end_location), - error, + error: future_feature_error_type(err.kind), source_path: source_file.name().to_owned(), } }) } +fn future_feature_error_type(kind: preprocess::FutureFeatureErrorKind) -> CodegenErrorType { + match kind { + preprocess::FutureFeatureErrorKind::InvalidFeature(feature) => { + CodegenErrorType::InvalidFutureFeature(feature) + } + preprocess::FutureFeatureErrorKind::InvalidBraces => CodegenErrorType::InvalidFutureBraces, + } +} + #[derive(PartialEq, Eq, Clone, Copy)] enum NameUsage { Load, Store, Delete, } + /// Main structure holding the state of compilation. struct Compiler<'a> { code_stack: Vec, symbol_table_stack: Vec, source_file: SourceFile, // current_source_location: SourceLocation, - current_source_range: TextRange, + current_source_span: CompilerSourceSpan, + ast_locations: Option, future_features: bytecode::CodeFlags, future_annotations: bool, ctx: CompileContext, @@ -186,10 +195,6 @@ struct Compiler<'a> { /// True when compiling in "single" (interactive) mode. /// Expression statements at module scope emit CALL_INTRINSIC_1(Print). interactive: bool, - /// Counter for dead-code elimination during constant folding. - /// When > 0, the compiler walks AST (consuming sub_tables) but emits no bytecode. - /// Mirrors CPython's `c_do_not_emit_bytecode`. - do_not_emit_bytecode: u32, /// Mirrors `c_disable_warning` while compiling FINALLY_END copies. disable_warning: u32, syntax_warning_handler: Option<&'a mut SyntaxWarningHandler<'a>>, @@ -311,6 +316,10 @@ pub struct CompileOpts { pub dont_imply_dedent: bool, /// Recursion limit used by compiler tree walks, matching Py_EnterRecursiveCall. pub recursion_limit: usize, + /// Emit `BUILD_LIST_FROM_ARG` for a list comprehension with one + /// generator and no `if`, sizing the result from the iterator's length + /// hint. Off by default: the opcode is not part of the CPython set. + pub build_list_from_arg: bool, } impl Default for CompileOpts { @@ -323,6 +332,7 @@ impl Default for CompileOpts { future_features: bytecode::CodeFlags::empty(), dont_imply_dedent: false, recursion_limit: 1000, + build_list_from_arg: false, } } } @@ -362,7 +372,7 @@ enum ComprehensionLoopControl { loop_block: BlockIdx, if_cleanup_block: BlockIdx, after_block: BlockIdx, - backedge_range: TextRange, + backedge_range: CompilerSourceSpan, is_async: bool, end_async_for_target: BlockIdx, }, @@ -395,13 +405,58 @@ pub fn compile_top( compile_top_with_syntax_warning_handler(ast, source_file, mode, opts, None) } +/// An AST and its optional explicitly supplied Python source coordinates. +/// Parser callers leave `locations` absent and retain source-based positions. +pub struct AstInput { + pub ast: ast::Mod, + pub source_file: SourceFile, + pub locations: Option, +} + pub fn compile_top_with_syntax_warning_handler<'a>( - mut ast: ruff_python_ast::Mod, + ast: ruff_python_ast::Mod, source_file: SourceFile, mode: Mode, + opts: CompileOpts, + syntax_warning_handler: Option<&'a mut SyntaxWarningHandler<'a>>, +) -> CompileResult { + compile_ast_with_syntax_warning_handler( + AstInput { + ast, + source_file, + locations: None, + }, + mode, + opts, + syntax_warning_handler, + ) +} + +pub fn compile_ast_with_syntax_warning_handler<'a>( + input: AstInput, + mode: Mode, + opts: CompileOpts, + syntax_warning_handler: Option<&'a mut SyntaxWarningHandler<'a>>, +) -> CompileResult { + let mut compiler = lower_ast(input, mode, opts, false, syntax_warning_handler)?; + Ok(compiler.exit_scope()) +} + +// Like CPython's compiler_setup followed by compiler_codegen, keep the +// preparation and lowering shared between normal compilation and the +// codegen test entry point. +fn lower_ast<'a>( + input: AstInput, + mode: Mode, mut opts: CompileOpts, + save_nested_seqs: bool, mut syntax_warning_handler: Option<&'a mut SyntaxWarningHandler<'a>>, -) -> CompileResult { +) -> CompileResult> { + let AstInput { + mut ast, + source_file, + mut locations, + } = input; opts.future_features |= checked_future_features(&ast, &source_file)?; let future_annotations = opts .future_features @@ -411,46 +466,67 @@ pub fn compile_top_with_syntax_warning_handler<'a>( warn_ast_preprocess_syntax(&source_file, handler, range, message) })?; } - if matches!(mode, Mode::Single) + let location_error = if matches!(mode, Mode::Single) && let ruff_python_ast::Mod::Module(module) = &mut ast { - preprocess::preprocess_statements( - &mut module.body, + if let Some(locations) = &mut locations { + preprocess::preprocess_statements_with_locations( + &mut module.body, + opts.optimize, + future_annotations, + false, + locations, + ) + } else { + preprocess::preprocess_statements( + &mut module.body, + opts.optimize, + future_annotations, + false, + ); + Ok(()) + } + } else if let Some(locations) = &mut locations { + preprocess::preprocess_mod_with_locations( + &mut ast, opts.optimize, future_annotations, false, - ); + locations, + ) } else { preprocess::preprocess_mod(&mut ast, opts.optimize, future_annotations, false); - } + Ok(()) + }; + location_error.map_err(|error| CodegenError { + error: CodegenErrorType::AstLocation(error), + location: None, + end_location: None, + source_path: source_file.name().to_owned(), + })?; + let mut compiler = Compiler::new_with_syntax_warning_handler( + opts, + source_file.clone(), + "", + syntax_warning_handler, + ); + compiler.ast_locations = locations; + compiler.save_nested_seqs = save_nested_seqs; match ast { - ruff_python_ast::Mod::Module(module) => match mode { - Mode::Exec | Mode::Eval => compile_program_with_syntax_warning_handler( - &module, - source_file, - opts, - syntax_warning_handler, - ), - Mode::Single => compile_program_single_with_syntax_warning_handler( - &module, - source_file, - opts, - syntax_warning_handler, - ), - Mode::BlockExpr => compile_block_expression_with_syntax_warning_handler( - &module, - source_file, - opts, - syntax_warning_handler, - ), - }, - ruff_python_ast::Mod::Expression(expr) => compile_expression_with_syntax_warning_handler( - &expr, - source_file, - opts, - syntax_warning_handler, - ), + ast::Mod::Module(module) => { + let symbols = scan_module_symbols(&module, &source_file, &compiler.opts)?; + match mode { + Mode::Exec | Mode::Eval => compiler.compile_program(&module, symbols)?, + Mode::Single => compiler.compile_program_single(&module.body, symbols)?, + Mode::BlockExpr => compiler.compile_block_expr(&module.body, symbols)?, + } + } + ast::Mod::Expression(expression) => { + let symbols = scan_expr_symbols(&expression, &source_file, &compiler.opts)?; + compiler.compile_eval(&expression, symbols)?; + } } + Ok(compiler) } /// Unoptimized instruction sequence and the metadata needed by optimize_cfg. @@ -473,61 +549,31 @@ pub fn compile_codegen( } fn compile_codegen_with_syntax_warning_handler<'a>( - mut ast: ruff_python_ast::Mod, + ast: ruff_python_ast::Mod, source_file: SourceFile, mode: Mode, - mut opts: CompileOpts, - mut syntax_warning_handler: Option<&'a mut SyntaxWarningHandler<'a>>, + opts: CompileOpts, + syntax_warning_handler: Option<&'a mut SyntaxWarningHandler<'a>>, ) -> CompileResult { - opts.future_features |= checked_future_features(&ast, &source_file)?; - let future_annotations = opts - .future_features - .contains(bytecode::CodeFlags::FUTURE_ANNOTATIONS); - if let Some(handler) = syntax_warning_handler.as_deref_mut() { - preprocess::warn_control_flow_in_finally(&ast, |range, message| { - warn_ast_preprocess_syntax(&source_file, handler, range, message) - })?; - } - if matches!(mode, Mode::Single) - && let ruff_python_ast::Mod::Module(module) = &mut ast - { - preprocess::preprocess_statements( - &mut module.body, - opts.optimize, - future_annotations, - false, - ); - } else { - preprocess::preprocess_mod(&mut ast, opts.optimize, future_annotations, false); - } - - let mut compiler = Compiler::new_with_syntax_warning_handler( + compile_codegen_ast( + AstInput { + ast, + source_file, + locations: None, + }, + mode, opts, - source_file.clone(), - "", syntax_warning_handler, - ); - compiler.save_nested_seqs = true; - match ast { - ruff_python_ast::Mod::Module(module) => match mode { - Mode::Exec | Mode::Eval => { - let symbol_table = scan_module_symbols(&module, &source_file, &compiler.opts)?; - compiler.compile_program(&module, symbol_table)?; - } - Mode::Single => { - let symbol_table = scan_module_symbols(&module, &source_file, &compiler.opts)?; - compiler.compile_program_single(&module.body, symbol_table)?; - } - Mode::BlockExpr => { - let symbol_table = scan_module_symbols(&module, &source_file, &compiler.opts)?; - compiler.compile_block_expr(&module.body, symbol_table)?; - } - }, - ruff_python_ast::Mod::Expression(expr) => { - let symbol_table = scan_expr_symbols(&expr, &source_file, &compiler.opts)?; - compiler.compile_eval(&expr, symbol_table)?; - } - } + ) +} + +pub fn compile_codegen_ast<'a>( + input: AstInput, + mode: Mode, + opts: CompileOpts, + syntax_warning_handler: Option<&'a mut SyntaxWarningHandler<'a>>, +) -> CompileResult { + let mut compiler = lower_ast(input, mode, opts, true, syntax_warning_handler)?; let mut unit = compiler .code_stack @@ -707,14 +753,14 @@ macro_rules! emit { } fn eprint_location(zelf: &Compiler<'_>) { - let start = zelf - .source_file - .to_source_code() - .source_location(zelf.current_source_range.start(), PositionEncoding::Utf8); + let start = zelf.source_file.to_source_code().source_location( + zelf.current_source_span.range.start(), + PositionEncoding::Utf8, + ); let end = zelf .source_file .to_source_code() - .source_location(zelf.current_source_range.end(), PositionEncoding::Utf8); + .source_location(zelf.current_source_span.range.end(), PositionEncoding::Utf8); eprintln!( "LOCATION: {} from {}:{} to {}:{}", zelf.source_file.name(), @@ -1200,7 +1246,8 @@ impl<'warnings> Compiler<'warnings> { symbol_table_stack: Vec::new(), source_file, // current_source_location: SourceLocation::default(), - current_source_range: TextRange::default(), + current_source_span: CompilerSourceSpan::parsed(TextRange::default()), + ast_locations: None, future_features: opts.future_features, future_annotations: false, ctx: CompileContext { @@ -1211,7 +1258,6 @@ impl<'warnings> Compiler<'warnings> { opts, in_annotation: false, interactive: false, - do_not_emit_bytecode: 0, disable_warning: 0, syntax_warning_handler, save_nested_seqs: false, @@ -1221,7 +1267,7 @@ impl<'warnings> Compiler<'warnings> { fn compile_module_annotation_setup_sequence( &mut self, body: &[ast::Stmt], - loc: TextRange, + loc: CompilerSourceSpan, ) -> CompileResult<()> { let ( saved_blocks, @@ -1271,7 +1317,7 @@ impl<'warnings> Compiler<'warnings> { if let Some(lower) = &s.lower { self.compile_expression(lower)?; } else { - self.set_source_range(s.range); + self.set_source_node(s.range, &s.node_index); self.emit_load_const(ConstantData::None); } @@ -1279,7 +1325,7 @@ impl<'warnings> Compiler<'warnings> { if let Some(upper) = &s.upper { self.compile_expression(upper)?; } else { - self.set_source_range(s.range); + self.set_source_node(s.range, &s.node_index); self.emit_load_const(ConstantData::None); } @@ -1294,7 +1340,8 @@ impl<'warnings> Compiler<'warnings> { ctx: ast::ExprContext, ) -> CompileResult<()> { // Save full subscript expression range (set by compile_expression before this call) - let subscript_range = self.current_source_range; + let subscript_range_span = self.current_source_span; + if matches!(ctx, ast::ExprContext::Load) { self.check_subscripter(value)?; self.check_index(value, slice)?; @@ -1319,7 +1366,7 @@ impl<'warnings> Compiler<'warnings> { } // Restore full subscript expression range before emitting - self.set_source_range(subscript_range); + self.restore_source_span(subscript_range_span); match (use_slice_opt, ctx) { (true, ast::ExprContext::Load) => emit!(self, Instruction::BinarySlice), @@ -1358,7 +1405,8 @@ impl<'warnings> Compiler<'warnings> { pushed: u32, collection_type: CollectionType, ) -> CompileResult<()> { - let collection_range = self.current_source_range; + let collection_range_span = self.current_source_span; + let n = elts.len().to_u32(); let seen_star = elts.iter().any(|e| matches!(e, ast::Expr::Starred(_))); @@ -1375,11 +1423,11 @@ impl<'warnings> Compiler<'warnings> { self.compile_expression(elt)?; } if let Some(injected_arg) = injected_arg { - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); self.load_name(injected_arg)?; } let total_size = n + injected_count + pushed; - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); match collection_type { CollectionType::List => { emit!(self, Instruction::BuildList { count: total_size }); @@ -1399,7 +1447,7 @@ impl<'warnings> Compiler<'warnings> { let mut i = 0u32; if big { - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); match collection_type { CollectionType::List => { emit!(self, Instruction::BuildList { count: pushed }); @@ -1420,7 +1468,7 @@ impl<'warnings> Compiler<'warnings> { if let ast::Expr::Starred(ast::ExprStarred { value, .. }) = elt { // When we hit first star, build sequence with elements so far if !sequence_built { - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); match collection_type { CollectionType::List => { emit!(self, Instruction::BuildList { count: i + pushed }); @@ -1437,7 +1485,7 @@ impl<'warnings> Compiler<'warnings> { // Compile the starred expression and extend self.compile_expression(value)?; - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); match collection_type { CollectionType::List => { emit!(self, Instruction::ListExtend { i: 1 }); @@ -1455,7 +1503,7 @@ impl<'warnings> Compiler<'warnings> { if sequence_built { // Sequence already exists, append to it - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); match collection_type { CollectionType::List => { emit!(self, Instruction::ListAppend { i: 1 }); @@ -1476,9 +1524,9 @@ impl<'warnings> Compiler<'warnings> { debug_assert!(sequence_built); if let Some(injected_arg) = injected_arg { - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); self.load_name(injected_arg)?; - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); match collection_type { CollectionType::List | CollectionType::Tuple => { emit!(self, Instruction::ListAppend { i: 1 }); @@ -1490,7 +1538,7 @@ impl<'warnings> Compiler<'warnings> { } if collection_type == CollectionType::Tuple { - self.set_source_range(collection_range); + self.restore_source_span(collection_range_span); emit!( self, Instruction::CallIntrinsic1 { @@ -1512,7 +1560,7 @@ impl<'warnings> Compiler<'warnings> { } fn error(&mut self, error: CodegenErrorType) -> CodegenError { - self.error_ranged(error, self.current_source_range) + self.error_ranged(error, self.current_source_span.range) } fn error_ranged(&mut self, error: CodegenErrorType, range: TextRange) -> CodegenError { @@ -1599,14 +1647,14 @@ impl<'warnings> Compiler<'warnings> { } /// Get the index of a global name. - fn get_global_name_index(&mut self, name: &str) -> u32 { + fn get_global_name_index(&mut self, name: &str) -> oparg::NameIdx { let info = self.code_stack.last_mut().unwrap(); let idx = info .metadata .names .get_index_of(name) .unwrap_or_else(|| info.metadata.names.insert_full(name.to_owned()).0); - idx.to_u32() + oparg::NameIdx::from_u32(idx.to_u32()) } /// Push the next symbol table on to the stack @@ -1859,11 +1907,11 @@ impl<'warnings> Compiler<'warnings> { fn load_args_for_super( &mut self, super_type: &SuperCallType<'_>, - super_name_range: TextRange, - super_call_range: TextRange, + super_name_range: CompilerSourceSpan, + super_call_range: CompilerSourceSpan, ) -> CompileResult<()> { // 1. Load global super - self.set_source_range(super_name_range); + self.restore_source_span(super_name_range); self.compile_name(&"super".into(), NameUsage::Load)?; match super_type { @@ -1878,7 +1926,7 @@ impl<'warnings> Compiler<'warnings> { SuperCallType::ZeroArg => { // 0-arg: load __class__ cell and first parameter // Load __class__ from cell/free variable - self.set_source_range(super_call_range); + self.restore_source_span(super_call_range); let scope = self .get_ref_type(&"__class__".into()) .map_err(|e| self.error(e))?; @@ -1905,7 +1953,7 @@ impl<'warnings> Compiler<'warnings> { "super(): no arguments and no first parameter".to_owned(), )) })?; - self.set_source_range(super_call_range); + self.restore_source_span(super_call_range); self.compile_name(&first_param.into(), NameUsage::Load)?; } } @@ -1949,6 +1997,8 @@ impl<'warnings> Compiler<'warnings> { } }; + let is_generator = ste.is_coroutine || ste.is_generator; + // Use varnames from symbol table (already collected in definition order) let varname_cache: IndexSet = ste.varnames.iter().cloned().collect(); let nparams = ste.varnames.len(); @@ -1989,18 +2039,15 @@ impl<'warnings> Compiler<'warnings> { // Build freevars using dictbytype (FREE scope, offset by cellvars size) let mut freevar_cache = IndexSet::default(); - let annotation_free_names: IndexSet = ste - .annotation_block - .as_ref() - .map(|annotation| { + let annotation_free_names: IndexSet = + ste.annotation_block.as_ref().map_or_default(|annotation| { annotation .symbols .iter() .filter(|(_, s)| s.scope == SymbolScope::Free) .map(|(name, _)| name.clone()) .collect() - }) - .unwrap_or_default(); + }); let mut free_names: Vec<_> = ste .symbols .iter() @@ -2150,16 +2197,37 @@ impl<'warnings> Compiler<'warnings> { self.set_qualname(); } - // Emit RESUME (handles async preamble and module lineno 0) - // CPython: LOCATION(lineno, lineno, 0, 0), then loc.lineno = 0 for module - self.emit_resume_for_scope(scope_type, lineno); + self.emit_scope_prefix(scope_type, lineno, is_generator); Ok(()) } - /// Emit RESUME instruction with proper handling for module lineno. - /// codegen_enter_scope equivalent for RESUME emission. - fn emit_resume_for_scope(&mut self, scope_type: CompilerScope, lineno: u32) { + /// Emit the generator prefix and RESUME, as the tail of + /// codegen_enter_scope does. `is_generator` is + /// `ste_coroutine || ste_generator`. + fn emit_scope_prefix(&mut self, scope_type: CompilerScope, lineno: u32, is_generator: bool) { + // Add the generator prefix instructions. + if is_generator { + // RETURN_GENERATOR + POP_TOP have a net stack effect of 0, because + // RETURN_GENERATOR pushes the generator before returning. + let location = SourceLocation { + line: OneIndexed::new(lineno as usize).unwrap_or(OneIndexed::MIN), + character_offset: OneIndexed::MIN, + }; + for instr in [Instruction::ReturnGenerator, Instruction::PopTop] { + self.cpython_cfg_builder_addop(ir::InstructionInfo { + instr: instr.into(), + arg: OpArg::NULL, + target: BlockIdx::NULL, + location, + end_location: location, + except_handler: None, + semantic_location: None, + lineno_override: Some(ir::LINE_ONLY_LOCATION_OVERRIDE), + }); + } + } + // CPython: LOCATION(lineno, lineno, 0, 0) // Module scope: loc.lineno = 0 (before the first line) let lineno_override = if scope_type == CompilerScope::Module { @@ -2186,6 +2254,7 @@ impl<'warnings> Compiler<'warnings> { location, end_location, except_handler, + semantic_location: None, lineno_override, }); } @@ -2291,7 +2360,7 @@ impl<'warnings> Compiler<'warnings> { fn enter_annotation_scope( &mut self, func_name: &str, - loc: TextRange, + loc: CompilerSourceSpan, ) -> CompileResult> { if !self.push_annotation_symbol_table() { return Ok(None); @@ -2305,7 +2374,7 @@ impl<'warnings> Compiler<'warnings> { in_async_scope: false, }; - self.set_source_range(loc); + self.restore_source_span(loc); let key = self.symbol_table_stack.len() - 1; let lineno = self.get_source_line_number().get(); self.enter_scope( @@ -2385,7 +2454,7 @@ impl<'warnings> Compiler<'warnings> { fb_exit: ir::InstructionSequenceLabel, fb_datum: FBlockDatum, ) -> CompileResult<()> { - let fb_range = self.current_source_range; + let fb_span = self.current_source_span; if self.current_code_info().fblock.len() >= CO_MAXBLOCKS { return Err(self.error(CodegenErrorType::SyntaxError( "too many statically nested blocks".to_owned(), @@ -2399,7 +2468,7 @@ impl<'warnings> Compiler<'warnings> { fb_type, fb_block, fb_exit, - fb_range, + fb_span, fb_datum, }); Ok(()) @@ -2434,33 +2503,33 @@ impl<'warnings> Compiler<'warnings> { fb_type, fb_block, fb_exit, - fb_range, + fb_span, fb_datum, } = fblock; let code = self.current_code_info(); if code.fblock.len() >= CO_MAXBLOCKS { return Err(self.error_ranged( CodegenErrorType::SyntaxError("too many statically nested blocks".to_owned()), - fb_range, + fb_span.range, )); } code.fblock.push(FBlockInfo { fb_type, fb_block, fb_exit, - fb_range, + fb_span, fb_datum, }); Ok(()) } - fn set_unwind_source_range(&mut self, loc: Option) { + fn set_unwind_source_range(&mut self, loc: Option) { if let Some(range) = loc { - self.set_source_range(range); + self.restore_source_span(range); } } - fn mark_unwind_no_location(&mut self, loc: Option) { + fn mark_unwind_no_location(&mut self, loc: Option) { if loc.is_none() { self.set_no_location(); } @@ -2472,7 +2541,7 @@ impl<'warnings> Compiler<'warnings> { &mut self, info: &FBlockInfo, preserve_tos: bool, - loc: &mut Option, + loc: &mut Option, ) -> CompileResult<()> { match info.fb_type { FBlockType::WhileLoop @@ -2483,17 +2552,27 @@ impl<'warnings> Compiler<'warnings> { // No cleanup needed } - FBlockType::ForLoop => { - // When returning from a for-loop, CPython swaps the preserved - // value with the iterator and uses POP_TOP for loop cleanup. + FBlockType::ForLoop | FBlockType::AsyncForLoop => { + let iterator_slots = if info.fb_type == FBlockType::ForLoop { + 2 + } else { + 1 + }; if preserve_tos { self.set_unwind_source_range(*loc); - emit!(self, Instruction::Swap { i: 2 }); + emit!( + self, + Instruction::Swap { + i: iterator_slots + 1 + } + ); + self.mark_unwind_no_location(*loc); + } + for _ in 0..iterator_slots { + self.set_unwind_source_range(*loc); + emit!(self, Instruction::PopTop); self.mark_unwind_no_location(*loc); } - self.set_unwind_source_range(*loc); - emit!(self, Instruction::PopTop); - self.mark_unwind_no_location(*loc); } FBlockType::TryExcept => { @@ -2577,7 +2656,7 @@ impl<'warnings> Compiler<'warnings> { // CPython codegen_unwind_fblock() assigns *ploc = info->fb_loc // for WITH/ASYNC_WITH cleanup and then makes following unwind // instructions artificial with *ploc = NO_LOCATION. - *loc = Some(info.fb_range); + *loc = Some(info.fb_span); self.set_unwind_source_range(*loc); emit!(self, PseudoInstruction::PopBlock); @@ -2598,6 +2677,8 @@ impl<'warnings> Compiler<'warnings> { self.set_unwind_source_range(*loc); emit!(self, Instruction::GetAwaitable { r#where: 2 }); self.set_unwind_source_range(*loc); + emit!(self, Instruction::PushNull); + self.set_unwind_source_range(*loc); self.emit_load_const(ConstantData::None); let _ = self.compile_yield_from_sequence(true); } @@ -2664,7 +2745,7 @@ impl<'warnings> Compiler<'warnings> { &mut self, preserve_tos: bool, stop_at_loop: bool, - ) -> CompileResult> { + ) -> CompileResult> { let (unwind_loc, _loop_fblock) = self.unwind_fblock_stack_with_loop(preserve_tos, stop_at_loop)?; Ok(unwind_loc) @@ -2677,8 +2758,8 @@ impl<'warnings> Compiler<'warnings> { &mut self, preserve_tos: bool, stop_at_loop: bool, - ) -> CompileResult<(Option, Option)> { - let mut unwind_loc = Some(self.current_source_range); + ) -> CompileResult<(Option, Option)> { + let mut unwind_loc = Some(self.current_source_span); let loop_fblock = self.unwind_fblock_stack_inner(preserve_tos, stop_at_loop, &mut unwind_loc)?; Ok((unwind_loc, loop_fblock)) @@ -2688,7 +2769,7 @@ impl<'warnings> Compiler<'warnings> { &mut self, preserve_tos: bool, stop_at_loop: bool, - unwind_loc: &mut Option, + unwind_loc: &mut Option, ) -> CompileResult> { let Some(top) = self.current_code_info().fblock.last().cloned() else { return Ok(None); @@ -2696,10 +2777,15 @@ impl<'warnings> Compiler<'warnings> { if matches!(top.fb_type, FBlockType::ExceptionGroupHandler) { return Err(self.error_optional_range( CodegenErrorType::BreakContinueReturnInExceptStar, - *unwind_loc, + unwind_loc.map(|span| span.range), )); } - if stop_at_loop && matches!(top.fb_type, FBlockType::WhileLoop | FBlockType::ForLoop) { + if stop_at_loop + && matches!( + top.fb_type, + FBlockType::WhileLoop | FBlockType::ForLoop | FBlockType::AsyncForLoop + ) + { return Ok(Some(top)); } @@ -2717,7 +2803,7 @@ impl<'warnings> Compiler<'warnings> { // could take impl Into>, but everything is borrowed from ast structs; we never // actually have a `String` to pass fn name(&mut self, name: &str) -> bytecode::NameIdx { - self._name_inner(name, |i| &mut i.metadata.names) + oparg::NameIdx::from_u32(self._name_inner(name, |i| &mut i.metadata.names)) } fn varname(&mut self, name: &str) -> oparg::VarNum { @@ -2770,79 +2856,48 @@ impl<'warnings> Compiler<'warnings> { return current_obj_name; } - // Check parent scope let mut parent_idx = stack_size - 2; let mut parent = &self.code_stack[parent_idx]; + let mut parent_table = &self.symbol_table_stack[parent.symbol_table_index]; - let mut parent_scope = self - .symbol_table_stack - .get(parent_idx) - .map(|table| table.typ); - - // CPython skips both generic-parameter scopes and annotation scopes - // when building qualnames for the contained function/class code object. + // CPython compiler units skip the annotation scope (including generic + // parameters). If that scope was directly under the module, the + // current unit keeps its bare name, even for a signature annotation. if matches!( - parent_scope, - Some( - CompilerScope::TypeParams - | CompilerScope::Annotation - | CompilerScope::TypeAlias - | CompilerScope::TypeVariable, - ) - ) || parent.metadata.name.starts_with(" qualname. - let mut force_global = false; + // CPython looks up a mangled definition name in the same enclosing + // unit used for qualification, not in the intervening annotation + // scope. A global function or class is bound in the module. let current_scope = self .code_stack .last() .map(|code| self.symbol_table_stack[code.symbol_table_index].typ); - if matches!( + let force_global = if matches!( current_scope, Some(CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Class) ) { - if stack_size > self.symbol_table_stack.len() { - // We might be in a situation where symbol table isn't pushed yet - // In this case, check the parent symbol table - if let Some(parent_table) = self.symbol_table_stack.last() - && let Some(symbol) = parent_table.lookup(¤t_obj_name.clone().into()) - && symbol.scope == SymbolScope::GlobalExplicit - { - force_global = true; - } - } else if let Some(_current_table) = self.symbol_table_stack.last() { - // Mangle the name if necessary (for private names in classes) - let target = ¤t_obj_name.clone().into(); - let mangled_name = self.mangle(target); - - // Look up in parent symbol table to check scope - if self.symbol_table_stack.len() >= 2 { - let parent_table = &self.symbol_table_stack[self.symbol_table_stack.len() - 2]; - if let Some(symbol) = parent_table.lookup(&mangled_name) - && symbol.scope == SymbolScope::GlobalExplicit - { - force_global = true; - } - } - } - } + let target = current_obj_name.as_str().into(); + let private = parent.private.as_deref().map(Name::from); + let mangled_name = symboltable::mangle_name(private.as_ref(), &target); + parent_table + .lookup(&mangled_name) + .is_some_and(|symbol| symbol.scope == SymbolScope::GlobalExplicit) + } else { + false + }; // Build the prefix the current name is qualified by, if any let base = if force_global { @@ -2854,10 +2909,8 @@ impl<'warnings> Compiler<'warnings> { // Determine if parent is a function-like scope let is_function_parent = matches!( - parent_scope, - Some( - CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda - ) + parent_table.typ, + CompilerScope::Function | CompilerScope::AsyncFunction | CompilerScope::Lambda ); // Use parent's qualname if available, otherwise use parent_obj_name @@ -2923,35 +2976,36 @@ impl<'warnings> Compiler<'warnings> { self.symbol_table_stack.push(symbol_table); - self.emit_resume_for_scope(CompilerScope::Module, 1); + let is_coroutine = self.current_symbol_table().is_coroutine; + self.emit_scope_prefix(CompilerScope::Module, 1, is_coroutine); emit!(self, PseudoInstruction::AnnotationsPlaceholder); + let doc_span = self.docstring_span(&body.body); let (doc, statements) = split_doc_with_range(&body.body, &self.opts); let module_start_loc = self.module_start_location(&body.body); let annotations_used = self.current_symbol_table().annotations_used; // Handle annotation bookkeeping before the docstring assignment, as // codegen_body() does after _PyCodegen_Module() inserts the prefix set. if Self::scope_needs_conditional_annotations_cell(self.current_symbol_table()) { - self.set_source_range(module_start_loc); + self.restore_source_span(module_start_loc); emit!(self, Instruction::BuildSet { count: 0 }); self.store_name(&"__conditional_annotations__".into())?; } if self.future_annotations && annotations_used { - self.set_source_range(module_start_loc); + self.restore_source_span(module_start_loc); emit!(self, Instruction::SetupAnnotations); } if let Some((value, range)) = doc { - let saved_range = self.current_source_range; - self.set_source_range(range); + let saved_range = self.current_source_span; + self.restore_source_span(doc_span.unwrap_or_else(|| CompilerSourceSpan::parsed(range))); self.emit_load_const(ConstantData::Str { value: value.into(), }); - let doc = self.name("__doc__"); - emit!(self, Instruction::StoreName { namei: doc }); + self.store_name(&"__doc__".into())?; self.set_no_location(); - self.set_source_range(saved_range); + self.restore_source_span(saved_range); } // Compile all statements @@ -3004,19 +3058,20 @@ impl<'warnings> Compiler<'warnings> { self.symbol_table_stack.push(symbol_table); let module_start_loc = self.module_start_location(body); - self.emit_resume_for_scope(CompilerScope::Module, 1); + let is_coroutine = self.current_symbol_table().is_coroutine; + self.emit_scope_prefix(CompilerScope::Module, 1, is_coroutine); emit!(self, PseudoInstruction::AnnotationsPlaceholder); let annotations_used = self.current_symbol_table().annotations_used; // Handle annotations based on future_annotations flag if self.current_symbol_table().has_conditional_annotations { - self.set_source_range(module_start_loc); + self.restore_source_span(module_start_loc); emit!(self, Instruction::BuildSet { count: 0 }); self.store_name(&"__conditional_annotations__".into())?; } if self.future_annotations && annotations_used { - self.set_source_range(module_start_loc); + self.restore_source_span(module_start_loc); // PEP 563: Initialize __annotations__ dict emit!(self, Instruction::SetupAnnotations); } @@ -3044,7 +3099,8 @@ impl<'warnings> Compiler<'warnings> { .insert(bytecode::CodeFlags::COROUTINE); } self.symbol_table_stack.push(symbol_table); - self.emit_resume_for_scope(CompilerScope::Module, 1); + let is_coroutine = self.current_symbol_table().is_coroutine; + self.emit_scope_prefix(CompilerScope::Module, 1, is_coroutine); if let Some((last_statement, statements)) = body.split_last() { self.compile_statements(statements)?; @@ -3118,7 +3174,8 @@ impl<'warnings> Compiler<'warnings> { .insert(bytecode::CodeFlags::COROUTINE); } self.symbol_table_stack.push(symbol_table); - self.emit_resume_for_scope(CompilerScope::Module, 1); + let is_coroutine = self.current_symbol_table().is_coroutine; + self.emit_scope_prefix(CompilerScope::Module, 1, is_coroutine); self.compile_expression(&expression.body)?; self.emit_return_value(); @@ -3507,10 +3564,38 @@ impl<'warnings> Compiler<'warnings> { Ok(()) } + /// `_PyCompile_InExceptionHandler` + fn in_exception_handler(&mut self) -> bool { + self.current_code_info().fblock.iter().any(|block| { + matches!( + block.fb_type, + FBlockType::TryExcept + | FBlockType::FinallyTry + | FBlockType::FinallyEnd + | FBlockType::ExceptionHandler + | FBlockType::ExceptionGroupHandler + | FBlockType::HandlerCleanup + ) + }) + } + + fn import_policy(&mut self, explicit: bool, star: bool) -> u32 { + if explicit { + 1 + } else if star + || self.current_symbol_table().typ != CompilerScope::Module + || self.in_exception_handler() + { + 2 + } else { + 0 + } + } + fn compile_statement(&mut self, statement: &ast::Stmt) -> CompileResult<()> { trace!("Compiling {statement:?}"); - let prev_source_range = self.current_source_range; - self.set_source_range(statement.range()); + let prev_source_range = self.current_source_span; + self.set_source_node(statement.range(), statement.node_index()); // `from __future__` still executes that `from` statement at runtime, so the // ImportFrom is compiled down below as well. @@ -3527,7 +3612,7 @@ impl<'warnings> Compiler<'warnings> { } match &statement { - ast::Stmt::Import(ast::StmtImport { names, .. }) => { + ast::Stmt::Import(ast::StmtImport { names, is_lazy, .. }) => { // import a, b, c as d for name in names { let name = &name; @@ -3535,7 +3620,10 @@ impl<'warnings> Compiler<'warnings> { value: num_traits::Zero::zero(), }); self.emit_load_const(ConstantData::None); - let namei = self.name(&name.name); + let namei = oparg::ImportName::new( + self.name(&name.name), + self.import_policy(*is_lazy, false), + ); emit!(self, Instruction::ImportName { namei }); if let Some(alias) = &name.asname { let parts: Vec<&str> = name.name.split('.').skip(1).collect(); @@ -3560,6 +3648,7 @@ impl<'warnings> Compiler<'warnings> { level, module, names, + is_lazy, .. }) => { let import_star = names.first().is_some_and(|n| &n.name == "*"); @@ -3580,7 +3669,10 @@ impl<'warnings> Compiler<'warnings> { }); let module_name = module.as_ref().map_or("", |s| s.as_str()); - let module_idx = self.name(module_name); + let module_idx = oparg::ImportName::new( + self.name(module_name), + self.import_policy(*is_lazy, import_star), + ); emit!(self, Instruction::ImportName { namei: module_idx }); if import_star { @@ -3622,13 +3714,14 @@ impl<'warnings> Compiler<'warnings> { if !dominated_by_interactive && value.is_constant() { emit!(self, Instruction::Nop); } else { - let statement_range = self.current_source_range; + let statement_range_span = self.current_source_span; + self.compile_expression(value)?; if dominated_by_interactive { // The printing belongs to the statement, not to whatever // the expression left behind. - self.set_source_range(statement_range); + self.restore_source_span(statement_range_span); emit!( self, Instruction::CallIntrinsic1 { @@ -3651,38 +3744,26 @@ impl<'warnings> Compiler<'warnings> { .. }) => { self.enter_conditional_block(); - self.compile_if(test, body, elif_else_clauses, statement.range())?; + self.compile_if(test, body, elif_else_clauses, self.node_span(statement))?; self.leave_conditional_block(); - self.set_source_range(statement.range()); + self.set_source_node(statement.range(), statement.node_index()); } ast::Stmt::While(ast::StmtWhile { - test, - body, - orelse, - range, - .. - }) => self.compile_while(test, body, orelse, *range)?, + test, body, orelse, .. + }) => self.compile_while(test, body, orelse, self.node_span(statement))?, ast::Stmt::With(ast::StmtWith { items, body, is_async, .. }) => self.compile_with(items, body, *is_async)?, - ast::Stmt::For(ast::StmtFor { - target, - iter, - body, - orelse, - is_async, - range, - .. - }) => self.compile_for(target, iter, body, orelse, *is_async, *range)?, + ast::Stmt::For(for_stmt) => { + self.compile_for_statement(for_stmt, self.node_span(statement))? + } ast::Stmt::Match(ast::StmtMatch { subject, cases, .. }) => { self.compile_match(subject, cases)? } - ast::Stmt::Raise(ast::StmtRaise { - exc, cause, range, .. - }) => { + ast::Stmt::Raise(ast::StmtRaise { exc, cause, .. }) => { let kind = match exc { Some(value) => { self.compile_expression(value)?; @@ -3696,7 +3777,7 @@ impl<'warnings> Compiler<'warnings> { } None => bytecode::RaiseKind::BareRaise, }; - self.set_source_range(*range); + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::RaiseVarargs { argc: kind }); } ast::Stmt::Try(ast::StmtTry { @@ -3754,15 +3835,18 @@ impl<'warnings> Compiler<'warnings> { false, )?, ast::Stmt::Assert(assert_stmt) => { - let ast::StmtAssert { - test, msg, range, .. - } = assert_stmt; + let ast::StmtAssert { test, msg, .. } = assert_stmt; self.check_assert(assert_stmt)?; // if some flag, ignore all assert statements! if self.opts.optimize == 0 { let after_block = self.new_block(); - self.compile_jump_if_inner(test, true, after_block, Some(*range))?; - self.set_source_range(*range); + self.compile_jump_if_inner( + test, + true, + after_block, + Some(self.node_span(statement)), + )?; + self.set_source_node(statement.range(), statement.node_index()); emit!( self, Instruction::LoadCommonConstant { @@ -3771,10 +3855,10 @@ impl<'warnings> Compiler<'warnings> { ); if let Some(e) = msg { self.compile_expression(e)?; - self.set_source_range(*range); + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::Call { argc: 0 }); } - self.set_source_range(test.range()); + self.set_source_node(test.range(), test.node_index()); emit!( self, Instruction::RaiseVarargs { @@ -3794,11 +3878,11 @@ impl<'warnings> Compiler<'warnings> { } ast::Stmt::Break(_) => { // Unwind fblock stack until we find a loop, emitting cleanup for each fblock - self.compile_break_continue(statement.range(), true)?; + self.compile_break_continue(self.node_span(statement), true)?; } ast::Stmt::Continue(_) => { // Unwind fblock stack until we find a loop, emitting cleanup for each fblock - self.compile_break_continue(statement.range(), false)?; + self.compile_break_continue(self.node_span(statement), false)?; } ast::Stmt::Return(ast::StmtReturn { value, .. }) => { if !self.ctx.in_func() { @@ -3807,7 +3891,7 @@ impl<'warnings> Compiler<'warnings> { ); } - let prev_source_range = self.current_source_range; + let prev_source_range = self.current_source_span; let stmt_range = statement.range(); match value { Some(v) => { @@ -3831,12 +3915,12 @@ impl<'warnings> Compiler<'warnings> { None }; let preserve_tos = folded_constant.is_none(); - let mut return_range = stmt_range; + let mut return_span = self.node_span(statement); if preserve_tos { self.compile_expression(v)?; } else { - return_range = v.range(); - self.set_source_range(v.range()); + return_span = self.node_span(v.as_ref()); + self.set_source_node(v.range(), v.node_index()); emit!(self, Instruction::Nop); } @@ -3844,14 +3928,14 @@ impl<'warnings> Compiler<'warnings> { if source.line_index(v.range().start()) != source.line_index(stmt_range.start()) { - return_range = stmt_range; - self.set_source_range(stmt_range); + return_span = self.node_span(statement); + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::Nop); } - self.set_source_range(return_range); + self.restore_source_span(return_span); let unwind_loc = self.unwind_fblock_stack(preserve_tos, false)?; if let Some(loc) = unwind_loc { - self.set_source_range(loc); + self.restore_source_span(loc); match folded_constant { Some(constant) => self.emit_return_const(constant), None => { @@ -3869,31 +3953,26 @@ impl<'warnings> Compiler<'warnings> { } } None => { - self.set_source_range(stmt_range); + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::Nop); // Unwind fblock stack with preserve_tos=false (no value to preserve) let unwind_loc = self.unwind_fblock_stack(false, false)?; if let Some(loc) = unwind_loc { - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_return_const(ConstantData::None); } else { self.emit_return_const_no_location(ConstantData::None); } } } - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); } - ast::Stmt::Assign(ast::StmtAssign { - targets, - value, - range, - .. - }) => { + ast::Stmt::Assign(ast::StmtAssign { targets, value, .. }) => { self.compile_expression(value)?; for (i, target) in targets.iter().enumerate() { if i + 1 != targets.len() { - self.set_source_range(*range); + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::Copy { i: 1 }); } self.compile_store(target)?; @@ -3907,7 +3986,6 @@ impl<'warnings> Compiler<'warnings> { annotation, value, simple, - range, .. }) => { self.compile_annotated_assign( @@ -3915,12 +3993,12 @@ impl<'warnings> Compiler<'warnings> { annotation, value.as_deref(), *simple, - *range, + self.node_span(statement), )?; // Bare annotations in function scope emit no code; restore // source range so subsequent instructions keep the correct line. if value.is_none() && self.ctx.in_func() { - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); } } ast::Stmt::Delete(ast::StmtDelete { targets, .. }) => { @@ -3935,7 +4013,6 @@ impl<'warnings> Compiler<'warnings> { name, type_params, value, - range, .. }) => { let Some(name) = name.as_name_expr() else { @@ -3945,8 +4022,8 @@ impl<'warnings> Compiler<'warnings> { }; let name_string = name.id(); + self.set_source_node(statement.range(), statement.node_index()); if let Some(type_params) = type_params { - self.set_source_range(*range); self.push_symbol_table()?; let key = self.symbol_table_stack.len() - 1; let lineno = self.get_source_line_number().get().to_u32(); @@ -3961,13 +4038,17 @@ impl<'warnings> Compiler<'warnings> { in_async_scope: false, }; - self.set_source_range(*range); + self.set_source_node(statement.range(), statement.node_index()); self.emit_load_const(ConstantData::Str { value: name_string.as_str().into(), }); self.compile_type_params(type_params)?; - self.compile_typealias_value_closure(name_string, value, *range)?; - self.set_source_range(*range); + self.compile_typealias_value_closure( + name_string, + value, + self.node_span(statement), + )?; + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::BuildTuple { count: 3 }); emit!( self, @@ -3979,19 +4060,22 @@ impl<'warnings> Compiler<'warnings> { let code = self.exit_scope(); self.ctx = prev_ctx; - self.set_source_range(*range); + self.set_source_node(statement.range(), statement.node_index()); self.make_closure(code, bytecode::MakeFunctionFlags::new())?; - self.set_source_range(*range); + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::PushNull); emit!(self, Instruction::Call { argc: 0 }); } else { - self.set_source_range(*range); self.emit_load_const(ConstantData::Str { value: name_string.as_str().into(), }); self.emit_load_const(ConstantData::None); - self.compile_typealias_value_closure(name_string, value, *range)?; - self.set_source_range(*range); + self.compile_typealias_value_closure( + name_string, + value, + self.node_span(statement), + )?; + self.set_source_node(statement.range(), statement.node_index()); emit!(self, Instruction::BuildTuple { count: 3 }); emit!( self, @@ -4001,7 +4085,7 @@ impl<'warnings> Compiler<'warnings> { ); } - self.set_source_range(*range); + self.set_source_node(statement.range(), statement.node_index()); self.store_name(name_string)?; } ast::Stmt::IpyEscapeCommand(stmt) => { @@ -4015,8 +4099,8 @@ impl<'warnings> Compiler<'warnings> { } fn compile_delete(&mut self, expression: &ast::Expr) -> CompileResult<()> { - let prev_source_range = self.current_source_range; - self.set_source_range(expression.range()); + let prev_source_range = self.current_source_span; + self.set_source_node(expression.range(), expression.node_index()); let result = (|| -> CompileResult<()> { match &expression { ast::Expr::Name(ast::ExprName { id, .. }) => { @@ -4025,11 +4109,11 @@ impl<'warnings> Compiler<'warnings> { ast::Expr::Attribute(ast::ExprAttribute { value, attr, .. }) => { self.compile_expression(value)?; let namei = self.name(attr.as_str()); - self.set_source_range(self.update_start_location_to_match_attr( - expression.range(), - expression.range(), + self.restore_source_span(self.update_start_span_to_match_attr( + self.node_span(expression), + self.node_span(expression), attr.as_str(), - )); + )?); emit!(self, Instruction::DeleteAttr { namei }); } ast::Expr::Subscript(ast::ExprSubscript { @@ -4050,7 +4134,7 @@ impl<'warnings> Compiler<'warnings> { } Ok(()) })(); - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); result } @@ -4097,7 +4181,10 @@ impl<'warnings> Compiler<'warnings> { /// Stack: [dec1, dec2, func] → CALL 0 → [dec1, dec2(func)] → CALL 0 → [dec1(dec2(func))] fn apply_decorators(&mut self, decorator_list: &[ast::Decorator]) { for decorator in decorator_list.iter().rev() { - self.set_source_range(decorator.expression.range()); + self.set_source_node( + decorator.expression.range(), + decorator.expression.node_index(), + ); emit!(self, Instruction::Call { argc: 0 }); } } @@ -4109,8 +4196,7 @@ impl<'warnings> Compiler<'warnings> { name: &str, allow_starred: bool, ) -> CompileResult<()> { - let expr_range = expr.range(); - self.set_source_range(expr_range); + self.set_source_node(expr.range(), expr.node_index()); self.emit_load_const(ConstantData::Tuple { elements: vec![ConstantData::Integer { value: 1.into() }], }); @@ -4141,7 +4227,7 @@ impl<'warnings> Compiler<'warnings> { if allow_starred && matches!(expr, ast::Expr::Starred(_)) { if let ast::Expr::Starred(starred) = expr { self.compile_expression(&starred.value)?; - self.set_source_range(expr_range); + self.set_source_node(expr.range(), expr.node_index()); emit!(self, Instruction::UnpackSequence { count: 1 }); } } else { @@ -4149,7 +4235,7 @@ impl<'warnings> Compiler<'warnings> { } // Return value - self.set_source_range(expr_range); + self.set_source_node(expr.range(), expr.node_index()); emit!(self, Instruction::ReturnValue); self.emit_return_const_no_location(ConstantData::None); @@ -4157,7 +4243,7 @@ impl<'warnings> Compiler<'warnings> { let code = self.exit_scope(); self.ctx = prev_ctx; - self.set_source_range(expr_range); + self.set_source_node(expr.range(), expr.node_index()); self.make_closure( code, bytecode::MakeFunctionFlags::from([bytecode::MakeFunctionFlag::Defaults]), @@ -4170,9 +4256,9 @@ impl<'warnings> Compiler<'warnings> { &mut self, alias_name: &str, value: &ast::Expr, - alias_range: TextRange, + alias_range: CompilerSourceSpan, ) -> CompileResult<()> { - self.set_source_range(alias_range); + self.restore_source_span(alias_range); self.emit_load_const(ConstantData::Tuple { elements: vec![ConstantData::Integer { value: 1.into() }], }); @@ -4192,12 +4278,12 @@ impl<'warnings> Compiler<'warnings> { }; self.compile_expression(value)?; - self.set_source_range(alias_range); + self.restore_source_span(alias_range); emit!(self, Instruction::ReturnValue); let code = self.exit_scope(); self.ctx = prev_ctx; - self.set_source_range(alias_range); + self.restore_source_span(alias_range); self.make_closure( code, bytecode::MakeFunctionFlags::from([bytecode::MakeFunctionFlag::Defaults]), @@ -4220,7 +4306,7 @@ impl<'warnings> Compiler<'warnings> { range, .. }) => { - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); self.emit_load_const(ConstantData::Str { value: name.as_str().into(), }); @@ -4228,7 +4314,7 @@ impl<'warnings> Compiler<'warnings> { if let Some(expr) = &bound { self.compile_type_param_bound_or_default(expr, name.as_str(), false)?; - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); let intrinsic = if expr.is_tuple_expr() { bytecode::IntrinsicFunction2::TypeVarWithConstraint } else { @@ -4251,7 +4337,7 @@ impl<'warnings> Compiler<'warnings> { name.as_str(), false, )?; - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); emit!( self, Instruction::CallIntrinsic2 { @@ -4267,7 +4353,7 @@ impl<'warnings> Compiler<'warnings> { )); } - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); emit!(self, Instruction::Copy { i: 1 }); self.store_name(name.id())?; } @@ -4277,7 +4363,7 @@ impl<'warnings> Compiler<'warnings> { range, .. }) => { - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); self.emit_load_const(ConstantData::Str { value: name.as_str().into(), }); @@ -4295,7 +4381,7 @@ impl<'warnings> Compiler<'warnings> { name.as_str(), false, )?; - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); emit!( self, Instruction::CallIntrinsic2 { @@ -4311,7 +4397,7 @@ impl<'warnings> Compiler<'warnings> { )); } - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); emit!(self, Instruction::Copy { i: 1 }); self.store_name(name.id())?; } @@ -4321,7 +4407,7 @@ impl<'warnings> Compiler<'warnings> { range, .. }) => { - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); self.emit_load_const(ConstantData::Str { value: name.as_str().into(), }); @@ -4339,7 +4425,7 @@ impl<'warnings> Compiler<'warnings> { name.as_str(), true, )?; - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); emit!( self, Instruction::CallIntrinsic2 { @@ -4356,14 +4442,14 @@ impl<'warnings> Compiler<'warnings> { )); } - self.set_source_range(*range); + self.set_source_node(type_param.range(), type_param.node_index()); emit!(self, Instruction::Copy { i: 1 }); self.store_name(name.id())?; } }; } if let Some(first) = type_params.type_params.first() { - self.set_source_range(first.range()); + self.set_source_node(first.range(), first.node_index()); } emit!( self, @@ -4527,10 +4613,9 @@ impl<'warnings> Compiler<'warnings> { type_, name, body, - range: handler_range, .. }) = handler; - self.set_source_range(*handler_range); + self.set_source_node(handler.range(), handler.node_index()); if type_.is_none() && i < handlers.len() - 1 { return Err(self.error(CodegenErrorType::SyntaxError( "default 'except:' must be last".to_owned(), @@ -4540,7 +4625,7 @@ impl<'warnings> Compiler<'warnings> { if let Some(exc_type) = type_ { self.compile_expression(exc_type)?; - self.set_source_range(*handler_range); + self.set_source_node(handler.range(), handler.node_index()); emit!(self, Instruction::CheckExcMatch); emit!( self, @@ -4587,7 +4672,6 @@ impl<'warnings> Compiler<'warnings> { self.use_cpython_label_block(cleanup_end); self.emit_no_location_exception_name_cleanup(alias.id())?; emit!(self, Instruction::Reraise { depth: 1 }); - self.set_no_location(); } else { let cleanup_body = self.new_block(); @@ -4612,8 +4696,8 @@ impl<'warnings> Compiler<'warnings> { self, PseudoInstruction::JumpNoInterrupt { delta: end_block } ); - self.set_no_location(); } + self.set_no_location(); self.use_cpython_label_block(next_handler); } @@ -4796,11 +4880,10 @@ impl<'warnings> Compiler<'warnings> { type_, name, body, - range: handler_range, .. }) = handler; let is_last_handler = i == n - 1; - self.set_source_range(*handler_range); + self.set_source_node(handler.range(), handler.node_index()); let next_handler_block = self.new_block(); let except_with_error_block = self.new_block(); @@ -4817,7 +4900,7 @@ impl<'warnings> Compiler<'warnings> { // NULL type here, so codegen only emits CHECK_EG_MATCH when present. if let Some(exc_type) = type_ { self.compile_expression(exc_type)?; - self.set_source_range(*handler_range); + self.set_source_node(handler.range(), handler.node_index()); } if type_.is_some() { @@ -4936,7 +5019,7 @@ impl<'warnings> Compiler<'warnings> { self.set_no_location(); self.use_cpython_label_block(no_match_block); - self.set_source_range(*handler_range); + self.set_source_node(handler.range(), handler.node_index()); emit!(self, Instruction::PopTop); // pop match (None) // Stack: [prev_exc, orig, list, new_rest] @@ -5051,7 +5134,7 @@ impl<'warnings> Compiler<'warnings> { fn compile_default_arguments( &mut self, parameters: &ast::Parameters, - loc: TextRange, + loc: CompilerSourceSpan, ) -> CompileResult { let mut funcflags = bytecode::MakeFunctionFlags::new(); @@ -5067,7 +5150,7 @@ impl<'warnings> Compiler<'warnings> { for default in &defaults { self.compile_expression(default)?; } - self.set_source_range(loc); + self.restore_source_span(loc); emit!( self, Instruction::BuildTuple { @@ -5088,13 +5171,13 @@ impl<'warnings> Compiler<'warnings> { if !kw_with_defaults.is_empty() { // Compile kwdefaults and build dict for (arg, default) in &kw_with_defaults { - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_load_const(ConstantData::Str { value: self.mangle(arg.name().id()).as_str().into(), }); self.compile_expression(default)?; } - self.set_source_range(loc); + self.restore_source_span(loc); emit!( self, Instruction::BuildMap { @@ -5116,7 +5199,7 @@ impl<'warnings> Compiler<'warnings> { body: &[ast::Stmt], is_async: bool, funcflags: bytecode::MakeFunctionFlags, - closure_range: TextRange, + closure_range: CompilerSourceSpan, ) -> CompileResult<()> { // Always enter function scope self.enter_function(name, parameters)?; @@ -5198,7 +5281,7 @@ impl<'warnings> Compiler<'warnings> { let code = self.exit_scope(); self.ctx = prev_ctx; - self.set_source_range(closure_range); + self.restore_source_span(closure_range); // Create function object with closure self.make_closure(code, funcflags)?; @@ -5217,7 +5300,7 @@ impl<'warnings> Compiler<'warnings> { func_name: &str, parameters: &ast::Parameters, returns: Option<&ast::Expr>, - func_range: TextRange, + func_range: CompilerSourceSpan, ) -> CompileResult { if !self.next_function_annotation_symbol_table_uses_annotations() { // CPython creates a hidden AnnotationBlock for every function @@ -5238,10 +5321,10 @@ impl<'warnings> Compiler<'warnings> { // Count annotations let parameters_iter = parameters - .args + .posonlyargs .iter() .map(|x| &x.parameter) - .chain(parameters.posonlyargs.iter().map(|x| &x.parameter)) + .chain(parameters.args.iter().map(|x| &x.parameter)) .chain(parameters.vararg.as_deref()) .chain(parameters.kwonlyargs.iter().map(|x| &x.parameter)) .chain(parameters.kwarg.as_deref()); @@ -5253,17 +5336,17 @@ impl<'warnings> Compiler<'warnings> { // Compile annotations inside the annotation scope let parameters_iter = parameters - .args + .posonlyargs .iter() .map(|x| &x.parameter) - .chain(parameters.posonlyargs.iter().map(|x| &x.parameter)) + .chain(parameters.args.iter().map(|x| &x.parameter)) .chain(parameters.vararg.as_deref()) .chain(parameters.kwonlyargs.iter().map(|x| &x.parameter)) .chain(parameters.kwarg.as_deref()); for param in parameters_iter { if let Some(annotation) = ¶m.annotation { - self.set_source_range(func_range); + self.restore_source_span(func_range); self.emit_load_const(ConstantData::Str { value: self.mangle(param.name.id()).as_str().into(), }); @@ -5273,7 +5356,7 @@ impl<'warnings> Compiler<'warnings> { // Handle return annotation if let Some(annotation) = returns { - self.set_source_range(func_range); + self.restore_source_span(func_range); self.emit_load_const(ConstantData::Str { value: "return".into(), }); @@ -5281,7 +5364,7 @@ impl<'warnings> Compiler<'warnings> { } // Build the map and return it - self.set_source_range(func_range); + self.restore_source_span(func_range); emit!( self, Instruction::BuildMap { @@ -5295,7 +5378,7 @@ impl<'warnings> Compiler<'warnings> { let annotate_code = self.exit_annotation_scope(saved_ctx); // Make a closure from the code object - self.set_source_range(func_range); + self.restore_source_span(func_range); self.make_closure(annotate_code, bytecode::MakeFunctionFlags::new())?; Ok(true) @@ -5386,9 +5469,9 @@ impl<'warnings> Compiler<'warnings> { fn compile_module_annotate( &mut self, body: &[ast::Stmt], - loc: Option, + loc: Option, ) -> CompileResult { - let loc = loc.unwrap_or(self.current_source_range); + let loc = loc.unwrap_or(self.current_source_span); // Get parent scope type BEFORE pushing annotation symbol table. let parent_scope_type = self.current_symbol_table().typ; let annotations = Self::collect_annotations(body, parent_scope_type); @@ -5418,7 +5501,7 @@ impl<'warnings> Compiler<'warnings> { }; // Enter annotation scope for code generation - self.set_source_range(loc); + self.restore_source_span(loc); let key = self.symbol_table_stack.len() - 1; let lineno = self.get_source_line_number().get(); self.enter_scope( @@ -5435,7 +5518,7 @@ impl<'warnings> Compiler<'warnings> { // Emit format validation: if format > VALUE_WITH_FAKE_GLOBALS: raise NotImplementedError self.emit_format_validation(); - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::BuildMap { count: 0 }); let mut conditional_idx = 0usize; @@ -5444,7 +5527,6 @@ impl<'warnings> Compiler<'warnings> { target, annotation, simple, - range, .. } = stmt; let simple_name = if *simple { @@ -5469,7 +5551,7 @@ impl<'warnings> Compiler<'warnings> { let name = simple_name.expect("missing simple annotation name"); if let Some(not_set_block) = not_set_block { - self.set_source_range(*range); + self.set_source_node(stmt.range, &stmt.node_index); self.emit_load_const(ConstantData::Integer { value: conditional_idx.into(), }); @@ -5496,12 +5578,12 @@ impl<'warnings> Compiler<'warnings> { } self.compile_annotation(annotation)?; - self.set_source_range(*range); + self.set_source_node(stmt.range, &stmt.node_index); emit!(self, Instruction::Copy { i: 2 }); self.emit_load_const(ConstantData::Str { value: self.mangle(name).as_str().into(), }); - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::StoreSubscr); if let Some(not_set_block) = not_set_block { @@ -5514,7 +5596,7 @@ impl<'warnings> Compiler<'warnings> { } } - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::ReturnValue); self.emit_return_const_no_location(ConstantData::None); @@ -5536,7 +5618,7 @@ impl<'warnings> Compiler<'warnings> { Self::expose_annotation_format_parameter(&mut annotate_code); // Make a closure from the code object - self.set_source_range(loc); + self.restore_source_span(loc); self.make_closure(annotate_code, bytecode::MakeFunctionFlags::new())?; // Store as __annotate_func__ for classes, __annotate__ for modules @@ -5546,7 +5628,7 @@ impl<'warnings> Compiler<'warnings> { "__annotate__" } .into(); - self.set_source_range(loc); + self.restore_source_span(loc); self.store_name(&name)?; Ok(true) @@ -5567,13 +5649,18 @@ impl<'warnings> Compiler<'warnings> { ) -> CompileResult<()> { // CPython's FunctionDef/AsyncFunctionDef LOC(s) starts at the // definition line even when decorators are present. - let stmt_source_range = self.current_source_range; + let statement_span = self.current_source_span; + let stmt_source_range = statement_span.range; let def_source_range = crate::decorated_definition_range( &self.source_file, stmt_source_range, decorator_list, if is_async { "async def " } else { "def " }, ); + let def_source_span = CompilerSourceSpan { + range: def_source_range, + ..statement_span + }; // The symtable visits defaults before decorators, but // codegen_function() emits decorators first. Keep the symbol table in @@ -5587,12 +5674,12 @@ impl<'warnings> Compiler<'warnings> { // The first decorator line is used for code objects created by // this definition, but LOC(s) for the surrounding instructions. - let firstlineno_range = decorator_list - .first() - .map_or(stmt_source_range, |decorator| decorator.expression.range()); + let firstlineno_span = decorator_list.first().map_or(statement_span, |decorator| { + self.node_span(&decorator.expression) + }); // compile defaults and return funcflags - let funcflags = self.compile_default_arguments(parameters, def_source_range)?; + let funcflags = self.compile_default_arguments(parameters, def_source_span)?; self.set_symbol_table_cursors(after_decorators_symbol_table_cursors); let is_generic = type_params.is_some(); @@ -5610,13 +5697,13 @@ impl<'warnings> Compiler<'warnings> { num_typeparam_args += 1; } if num_typeparam_args == 2 { - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); emit!(self, Instruction::Swap { i: 2 }); } // Enter type params scope let type_params_name = format!(""); - self.set_source_range(firstlineno_range); + self.restore_source_span(firstlineno_span); self.push_output( bytecode::CodeFlags::OPTIMIZED | bytecode::CodeFlags::NEWLOCALS, 0, @@ -5653,7 +5740,7 @@ impl<'warnings> Compiler<'warnings> { self.compile_type_params(type_params.unwrap())?; // Load defaults/kwdefaults with LOAD_FAST - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); for i in 0..num_typeparam_args { let var_num = oparg::VarNum::from(i); emit!(self, Instruction::LoadFast { var_num }); @@ -5662,13 +5749,13 @@ impl<'warnings> Compiler<'warnings> { // Compile annotations as closure (PEP 649) let mut annotations_flag = bytecode::MakeFunctionFlags::new(); - if self.compile_annotations_closure(name, parameters, returns, def_source_range)? { + if self.compile_annotations_closure(name, parameters, returns, def_source_span)? { annotations_flag.insert(bytecode::MakeFunctionFlag::Annotate); } // Compile function body. codegen_function() uses the first // decorator line for co_firstlineno, but LOC(s) for MAKE_FUNCTION. - self.set_source_range(firstlineno_range); + self.restore_source_span(firstlineno_span); let final_funcflags = funcflags | annotations_flag; self.compile_function_body( name, @@ -5676,18 +5763,18 @@ impl<'warnings> Compiler<'warnings> { body, is_async, final_funcflags, - def_source_range, + def_source_span, )?; // Handle type params if present if is_generic { // SWAP to get function on top // Stack: [type_params_tuple, function] -> [function, type_params_tuple] - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); emit!(self, Instruction::Swap { i: 2 }); // Call INTRINSIC_SET_FUNCTION_TYPE_PARAMS - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); emit!( self, Instruction::CallIntrinsic2 { @@ -5708,18 +5795,18 @@ impl<'warnings> Compiler<'warnings> { self.ctx = saved_ctx; // Make closure for type params code - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); self.make_closure(type_params_code, bytecode::MakeFunctionFlags::new())?; + self.restore_source_span(def_source_span); if num_typeparam_args > 0 { - self.set_source_range(def_source_range); emit!( self, Instruction::Swap { i: num_typeparam_args + 1 } ); - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); emit!( self, Instruction::Call { @@ -5728,10 +5815,9 @@ impl<'warnings> Compiler<'warnings> { ); } else { // Stack: [closure] - self.set_source_range(def_source_range); emit!(self, Instruction::PushNull); // Stack: [closure, NULL] - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); emit!(self, Instruction::Call { argc: 0 }); } } @@ -5740,7 +5826,7 @@ impl<'warnings> Compiler<'warnings> { self.apply_decorators(decorator_list); // Store the function - self.set_source_range(def_source_range); + self.restore_source_span(def_source_span); if preserve_value_before_store { emit!(self, Instruction::Copy { i: 1 }); } @@ -5843,7 +5929,12 @@ impl<'warnings> Compiler<'warnings> { } }; - emit!(self, PseudoInstruction::LoadClosure { i: idx.to_u32() }); + emit!( + self, + PseudoInstruction::LoadClosure { + i: oparg::VarNum::from_u32(idx.to_u32()) + } + ); } // Build tuple of closure variables @@ -5946,6 +6037,8 @@ impl<'warnings> Compiler<'warnings> { body: &[ast::Stmt], type_params: Option<&ast::TypeParams>, firstlineno: u32, + firstlineno_source_line: u32, + class_span: CompilerSourceSpan, ) -> CompileResult { // 1. Enter class scope let key = self.symbol_table_stack.len(); @@ -5959,9 +6052,20 @@ impl<'warnings> Compiler<'warnings> { self.code_stack.last_mut().unwrap().private = Some(name.to_owned()); // 2. Set up class namespace + let doc_span = self.docstring_span(body); let (doc_str, body) = split_doc_with_range(body, &self.opts); - let class_body_prefix_range = self.source_line_start_range(firstlineno); - self.set_source_range(class_body_prefix_range); + // The range indexes the source text; firstlineno may come from the location table. + let class_body_prefix_range = self.source_line_start_range(firstlineno_source_line); + let class_body_prefix_span = CompilerSourceSpan { + range: class_body_prefix_range, + location: class_span.location.map(|_| SourceLocationRange { + line: firstlineno.to_i32().expect("validated first line"), + end_line: firstlineno.to_i32().expect("validated first line"), + col: 0, + end_col: 0, + }), + }; + self.restore_source_span(class_body_prefix_span); // Load __name__ and store as __module__ self.load_name(&"__name__".into())?; @@ -6007,19 +6111,19 @@ impl<'warnings> Compiler<'warnings> { // Store __doc__ only if there's an explicit docstring. if let Some((doc, range)) = doc_str { - let saved_range = self.current_source_range; - self.set_source_range(range); + let saved_range = self.current_source_span; + self.restore_source_span(doc_span.unwrap_or_else(|| CompilerSourceSpan::parsed(range))); self.emit_load_const(ConstantData::Str { value: doc.into() }); self.store_name(&"__doc__".into())?; self.set_no_location(); - self.set_source_range(saved_range); + self.restore_source_span(saved_range); } // 3. Compile the class body self.compile_statements(body)?; if annotations_used && !self.future_annotations { - self.compile_module_annotate(body, Some(class_body_prefix_range))?; + self.compile_module_annotate(body, Some(class_body_prefix_span))?; } // 4. Handle __classcell__ if needed @@ -6040,8 +6144,7 @@ impl<'warnings> Compiler<'warnings> { .unwrap() .static_attributes .as_ref() - .map(|s| s.iter().cloned().collect()) - .unwrap_or_default(); + .map_or_default(|s| s.iter().cloned().collect()); attrs.sort(); self.emit_load_const(ConstantData::Tuple { elements: attrs @@ -6056,7 +6159,7 @@ impl<'warnings> Compiler<'warnings> { // Store __classdictcell__ if __classdict__ is a cell variable if self.current_symbol_table().needs_classdict { - let classdict_idx = u32::from(self.get_cell_var_index("__classdict__")); + let classdict_idx = self.get_cell_var_index("__classdict__"); emit!(self, PseudoInstruction::LoadClosure { i: classdict_idx }); self.set_no_location(); self.store_name(&"__classdictcell__".into())?; @@ -6067,19 +6170,19 @@ impl<'warnings> Compiler<'warnings> { emit!( self, PseudoInstruction::LoadClosure { - i: classcell_idx.to_u32() + i: oparg::VarNum::from_u32(classcell_idx.to_u32()) } ); self.set_no_location(); emit!(self, Instruction::Copy { i: 1 }); self.set_no_location(); self.store_name(&"__classcell__".into())?; - self.set_no_location(); } else { self.emit_load_const(ConstantData::None); - self.set_no_location(); } + self.set_no_location(); + // Return the class namespace self.emit_return_value(); self.set_no_location(); @@ -6100,30 +6203,40 @@ impl<'warnings> Compiler<'warnings> { ) -> CompileResult<()> { // CPython's ClassDef LOC(s) starts at the class line even when // decorators are present. - let stmt_source_range = self.current_source_range; + let statement_span = self.current_source_span; + let stmt_source_range = statement_span.range; let class_source_range = crate::decorated_definition_range( &self.source_file, stmt_source_range, decorator_list, "class ", ); + let class_source_span = CompilerSourceSpan { + range: class_source_range, + ..statement_span + }; self.prepare_decorators(decorator_list)?; let is_generic = type_params.is_some(); - let firstlineno_range = decorator_list - .first() - .map_or(stmt_source_range, |decorator| decorator.expression.range()); - #[expect(clippy::map_unwrap_or, reason = "Changing this will not compile")] - let firstlineno = decorator_list - .first() - .map(|decorator| { + let firstlineno_span = decorator_list.first().map_or(statement_span, |decorator| { + self.node_span(&decorator.expression) + }); + let firstlineno = firstlineno_span + .location + .and_then(|loc| u32::try_from(loc.line).ok()) + .unwrap_or_else(|| { self.source_file .to_source_code() - .line_index(decorator.expression.range().start()) + .line_index(firstlineno_span.range.start()) .get() .to_u32() - }) - .unwrap_or_else(|| self.get_source_line_number().get().to_u32()); + }); + let firstlineno_source_line = self + .source_file + .to_source_code() + .line_index(firstlineno_span.range.start()) + .get() + .to_u32(); // Save context before entering any scopes let saved_ctx = self.ctx; @@ -6131,7 +6244,7 @@ impl<'warnings> Compiler<'warnings> { // Step 1: If generic, enter type params scope and compile type params if is_generic { let type_params_name = format!(""); - self.set_source_range(firstlineno_range); + self.restore_source_span(firstlineno_span); self.push_output( bytecode::CodeFlags::OPTIMIZED | bytecode::CodeFlags::NEWLOCALS, 0, @@ -6153,7 +6266,7 @@ impl<'warnings> Compiler<'warnings> { // Compile type parameters and store them in the synthetic cell that // generic class bodies close over. self.compile_type_params(type_params.unwrap())?; - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); self.store_name(&".type_params".into())?; } @@ -6165,28 +6278,35 @@ impl<'warnings> Compiler<'warnings> { in_async_scope: false, }; let pre_class_body_symbol_table_cursors = self.current_symbol_table_cursors(); - let class_code = self.compile_class_body(name, body, type_params, firstlineno)?; + let class_code = self.compile_class_body( + name, + body, + type_params, + firstlineno, + firstlineno_source_line, + class_source_span, + )?; let post_class_body_symbol_table_cursors = self.current_symbol_table_cursors(); self.set_symbol_table_cursors(pre_class_body_symbol_table_cursors); self.ctx = prev_ctx; - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); // Step 3: Generate the rest of the code for the call - if is_generic { - // Generate class creation code - emit!(self, Instruction::LoadBuildClass); - emit!(self, Instruction::PushNull); + // Generate class creation code + emit!(self, Instruction::LoadBuildClass); + emit!(self, Instruction::PushNull); - // Create the class body function with the .type_params closure - // captured through the class code object's freevars. - self.make_closure(class_code, bytecode::MakeFunctionFlags::new())?; - self.emit_load_const(ConstantData::Str { - value: name.as_str().into(), - }); + // Create the class body function with closure. For generic classes the + // .type_params closure is captured through the class code object's freevars. + self.make_closure(class_code, bytecode::MakeFunctionFlags::new())?; + self.emit_load_const(ConstantData::Str { + value: name.as_str().into(), + }); + if is_generic { // Create .generic_base after the class function and name are on the // stack so the remaining call shape matches CPython's ordering. - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); self.load_name(&".type_params".into())?; emit!( self, @@ -6194,7 +6314,7 @@ impl<'warnings> Compiler<'warnings> { func: bytecode::IntrinsicFunction1::SubscriptGeneric } ); - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); self.store_name(&".generic_base".into())?; let (bases, keywords) = arguments.map_or((&[][..], &[][..]), |args| { @@ -6204,7 +6324,7 @@ impl<'warnings> Compiler<'warnings> { 2, bases, keywords, - class_source_range, + class_source_span, None, Some(&".generic_base".into()), )?; @@ -6218,27 +6338,18 @@ impl<'warnings> Compiler<'warnings> { self.ctx = saved_ctx; // Execute the type params function - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); self.make_closure(type_params_code, bytecode::MakeFunctionFlags::new())?; - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); emit!(self, Instruction::PushNull); - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); emit!(self, Instruction::Call { argc: 0 }); } else { // Non-generic class: standard path - emit!(self, Instruction::LoadBuildClass); - emit!(self, Instruction::PushNull); - - // Create class function with closure - self.make_closure(class_code, bytecode::MakeFunctionFlags::new())?; - self.emit_load_const(ConstantData::Str { - value: name.as_str().into(), - }); - if let Some(arguments) = arguments { - self.codegen_call_helper(2, arguments, class_source_range, None)?; + self.codegen_call_helper(2, arguments, class_source_span, None)?; } else { - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); emit!(self, Instruction::Call { argc: 2 }); } self.set_symbol_table_cursors(post_class_body_symbol_table_cursors); @@ -6246,7 +6357,7 @@ impl<'warnings> Compiler<'warnings> { // Step 4: Apply decorators and store (common to both paths) self.apply_decorators(decorator_list); - self.set_source_range(class_source_range); + self.restore_source_span(class_source_span); if preserve_value_before_store { emit!(self, Instruction::Copy { i: 1 }); } @@ -6260,7 +6371,7 @@ impl<'warnings> Compiler<'warnings> { test: &ast::Expr, body: &[ast::Stmt], elif_else_clauses: &[ast::ElifElseClause], - stmt_range: TextRange, + stmt_span: CompilerSourceSpan, ) -> CompileResult<()> { let end_block = self.new_block(); let next_block = if elif_else_clauses.is_empty() { @@ -6269,7 +6380,7 @@ impl<'warnings> Compiler<'warnings> { self.new_block() }; - self.compile_jump_if_inner(test, false, next_block, Some(stmt_range))?; + self.compile_jump_if_inner(test, false, next_block, Some(stmt_span))?; self.compile_statements(body)?; let Some((clause, rest)) = elif_else_clauses.split_first() else { @@ -6285,7 +6396,7 @@ impl<'warnings> Compiler<'warnings> { self.use_cpython_label_block(next_block); if let Some(test) = &clause.test { - self.compile_if(test, &clause.body, rest, clause.range)?; + self.compile_if(test, &clause.body, rest, self.node_span(clause))?; } else { debug_assert!(rest.is_empty()); self.compile_statements(&clause.body)?; @@ -6299,7 +6410,7 @@ impl<'warnings> Compiler<'warnings> { test: &ast::Expr, body: &[ast::Stmt], orelse: &[ast::Stmt], - while_range: TextRange, + while_span: CompilerSourceSpan, ) -> CompileResult<()> { self.enter_conditional_block(); @@ -6315,7 +6426,7 @@ impl<'warnings> Compiler<'warnings> { end_label, FBlockDatum::None, )?; - self.compile_jump_if_inner(test, false, anchor_block, Some(while_range))?; + self.compile_jump_if_inner(test, false, anchor_block, Some(while_span))?; self.compile_loop_body_statements(body)?; emit!(self, PseudoInstruction::Jump { delta: loop_block }); @@ -6378,7 +6489,7 @@ impl<'warnings> Compiler<'warnings> { let Some((item, items)) = items.split_first() else { return Err(self.error(CodegenErrorType::EmptyWithItems)); }; - let with_range = item.context_expr.range(); + let with_range = self.node_span(&item.context_expr); let body_block = self.new_block(); let exc_handler_block = self.new_block(); @@ -6387,7 +6498,7 @@ impl<'warnings> Compiler<'warnings> { // Compile context expression and load __enter__/__exit__ methods self.compile_expression(&item.context_expr)?; - self.set_source_range(with_range); + self.restore_source_span(with_range); // Stack: [cm] emit!(self, Instruction::Copy { i: 1 }); // [cm, cm] @@ -6415,6 +6526,7 @@ impl<'warnings> Compiler<'warnings> { ); // [aexit_func, self_ae, aenter_func, self_an] emit!(self, Instruction::Call { argc: 0 }); // [aexit_func, self_ae, awaitable] emit!(self, Instruction::GetAwaitable { r#where: 1 }); + emit!(self, Instruction::PushNull); self.emit_load_const(ConstantData::None); let _ = self.compile_yield_from_sequence(true); } else { @@ -6463,7 +6575,7 @@ impl<'warnings> Compiler<'warnings> { // Store or pop the enter result match &item.optional_vars { Some(var) => { - self.set_source_range(var.range()); + self.set_source_node(var.range(), var.node_index()); self.compile_store(var)?; } None => { @@ -6479,7 +6591,10 @@ impl<'warnings> Compiler<'warnings> { } self.compile_with_body_statements(body)?; } else { - self.set_source_range(items[0].context_expr.range()); + self.set_source_node( + items[0].context_expr.range(), + items[0].context_expr.node_index(), + ); self.compile_with_inner(items, body, is_async)?; } @@ -6487,18 +6602,19 @@ impl<'warnings> Compiler<'warnings> { // sync with emits the artificial POP_BLOCK before popping the fblock. if is_async { self.pop_fblock_label(fblock_type, body_label); - self.set_source_range(with_range); + self.restore_source_span(with_range); emit!(self, PseudoInstruction::PopBlock); } else { emit!(self, PseudoInstruction::PopBlock); self.set_no_location(); - self.set_source_range(with_range); + self.restore_source_span(with_range); self.pop_fblock_label(fblock_type, body_label); } self.compile_call_exit_with_nones(); if is_async { emit!(self, Instruction::GetAwaitable { r#where: 2 }); + emit!(self, Instruction::PushNull); self.emit_load_const(ConstantData::None); let _ = self.compile_yield_from_sequence(true); } @@ -6525,6 +6641,7 @@ impl<'warnings> Compiler<'warnings> { if is_async { emit!(self, Instruction::GetAwaitable { r#where: 2 }); + emit!(self, Instruction::PushNull); self.emit_load_const(ConstantData::None); let _ = self.compile_yield_from_sequence(true); } @@ -6536,149 +6653,163 @@ impl<'warnings> Compiler<'warnings> { Ok(()) } - fn compile_for( + fn compile_for_statement( &mut self, - target: &ast::Expr, - iter: &ast::Expr, - body: &[ast::Stmt], - orelse: &[ast::Stmt], - is_async: bool, - for_range: TextRange, + for_stmt: &ast::StmtFor, + for_span: CompilerSourceSpan, ) -> CompileResult<()> { self.enter_conditional_block(); - // Start loop - let for_block = self.new_block(); - let (body_label, send_block) = if is_async { - (None, self.new_block()) + let after_block = if for_stmt.is_async { + self.compile_async_for(for_stmt, for_span)? } else { - let body_label = self.current_code_info().new_instr_sequence_label(); - (Some(body_label), BlockIdx::NULL) + self.compile_for(for_stmt)? }; - let else_block = self.new_block(); + self.compile_statements(&for_stmt.orelse)?; + self.use_cpython_label_block(after_block); + + // Implicit return after for-loop should be attributed to the iterator. + self.set_source_node(for_stmt.iter.range(), for_stmt.iter.node_index()); + + self.leave_conditional_block(); + Ok(()) + } + + /// CPython `codegen_for()`: the loop fblock encloses iterable evaluation + /// and remains active through the iterator cleanup. + fn compile_for(&mut self, for_stmt: &ast::StmtFor) -> CompileResult { + let for_block = self.new_block(); + let body_label = self.current_code_info().new_instr_sequence_label(); + let cleanup_block = self.new_block(); let after_block = self.new_block(); let for_label = self.instr_sequence_label_for_block(for_block); let after_label = self.instr_sequence_label_for_block(after_block); - let mut end_async_for_target = BlockIdx::NULL; - - if !is_async { - // CPython codegen_for() pushes the loop fblock before compiling - // the iterable expression. - self.push_fblock_labels( - FBlockType::ForLoop, - for_label, - after_label, - FBlockDatum::None, - )?; - } - // The thing iterated: - self.compile_expression(iter)?; + self.push_fblock_labels( + FBlockType::ForLoop, + for_label, + after_label, + FBlockDatum::None, + )?; + self.compile_expression(&for_stmt.iter)?; + self.set_source_node(for_stmt.iter.range(), for_stmt.iter.node_index()); + emit!(self, Instruction::GetIter { mode: 0 }); - if is_async { - if self.ctx.func != FunctionContext::AsyncFunction - && !self.allows_top_level_await_in_current_context() - { - return Err(self.error(CodegenErrorType::InvalidAsyncFor)); + self.use_cpython_label_block(for_block); + emit!( + self, + Instruction::ForIter { + delta: cleanup_block } - self.set_source_range(iter.range()); - emit!(self, Instruction::GetAiter); - - self.use_cpython_label_block(for_block); - self.set_source_range(for_range); - - // codegen_async_for: push fblock BEFORE SETUP_FINALLY - self.push_fblock_labels( - FBlockType::ForLoop, - for_label, - after_label, - FBlockDatum::None, - )?; - - // SETUP_FINALLY to guard the __anext__ call - emit!(self, PseudoInstruction::SetupFinally { delta: else_block }); - emit!(self, Instruction::GetAnext); - self.emit_load_const(ConstantData::None); - self.use_cpython_label_block(send_block); - let _ = self.compile_yield_from_sequence(true); - end_async_for_target = send_block; - // POP_BLOCK for SETUP_FINALLY - only GetANext/yield_from are protected - emit!(self, PseudoInstruction::PopBlock); - emit!(self, Instruction::NotTaken); - - // Success block for __anext__ - self.compile_store(target)?; - } else { - // Retrieve Iterator - self.set_source_range(iter.range()); - emit!(self, Instruction::GetIter); + ); - self.use_cpython_label_block(for_block); + // Keep the raw sequence body label after the traceable target NOP. + let saved_range = self.current_source_span; + let target = &for_stmt.target; + self.set_source_node(target.range(), target.node_index()); + emit!(self, Instruction::Nop); + let result = self + .current_code_info() + .use_raw_instr_sequence_label(body_label); + unwrap_internal(self, result); + self.compile_store(target)?; + self.restore_source_span(saved_range); - emit!(self, Instruction::ForIter { delta: else_block }); + self.compile_for_body_and_backedge(&for_stmt.body, for_block)?; + self.use_cpython_label_block(cleanup_block); + // Keep END_FOR before POP_ITER for flowgraph line propagation and tracing. + emit!(self, Instruction::EndFor); + self.set_no_location(); + emit!(self, Instruction::PopIter); + self.set_no_location(); + self.pop_fblock_label(FBlockType::ForLoop, for_label); - let saved_range = self.current_source_range; - self.set_source_range(target.range()); - emit!(self, Instruction::Nop); - let result = self - .current_code_info() - .use_raw_instr_sequence_label(body_label.expect("sync for must have body label")); - unwrap_internal(self, result); - self.compile_store(target)?; - self.set_source_range(saved_range); - }; + Ok(after_block) + } - self.compile_loop_body_statements(body)?; - emit!(self, PseudoInstruction::Jump { delta: for_block }); - self.set_no_location(); + /// CPython `codegen_async_for()`: protect only __anext__ and its await, + /// and pop the loop fblock before handling exhaustion. + fn compile_async_for( + &mut self, + for_stmt: &ast::StmtFor, + for_span: CompilerSourceSpan, + ) -> CompileResult { + let for_block = self.new_block(); + let send_block = self.new_block(); + let except_block = self.new_block(); + let after_block = self.new_block(); + let for_label = self.instr_sequence_label_for_block(for_block); + let after_label = self.instr_sequence_label_for_block(after_block); - if is_async { - // codegen_async_for() pops the loop fblock before the - // END_ASYNC_FOR exception block. Sync codegen_for() keeps the - // fblock through END_FOR/POP_ITER and pops below. - self.pop_fblock_label(FBlockType::ForLoop, for_label); + let iter = &for_stmt.iter; + self.compile_expression(iter)?; + if self.ctx.func != FunctionContext::AsyncFunction + && !self.allows_top_level_await_in_current_context() + { + return Err(self.error(CodegenErrorType::InvalidAsyncFor)); } + self.set_source_node(iter.range(), iter.node_index()); + emit!(self, Instruction::GetAiter); - self.use_cpython_label_block(else_block); + self.use_cpython_label_block(for_block); + self.restore_source_span(for_span); + self.push_fblock_labels( + FBlockType::AsyncForLoop, + for_label, + after_label, + FBlockDatum::None, + )?; - // Except block for __anext__ / end of sync for - if is_async { - // codegen_async_for emits END_ASYNC_FOR at the iterator location, - // after the for-loop fblock has already been popped. - let saved_range = self.current_source_range; - self.set_source_range(iter.range()); - self.emit_end_async_for(end_async_for_target); - self.set_source_range(saved_range); - } else { - // codegen_for emits END_FOR/POP_ITER with NO_LOCATION. Line numbers - // are propagated later by flowgraph.c::resolve_line_numbers(). - emit!(self, Instruction::EndFor); - self.set_no_location(); - emit!(self, Instruction::PopIter); - self.set_no_location(); - self.pop_fblock_label(FBlockType::ForLoop, for_label); - } - self.compile_statements(orelse)?; + emit!( + self, + PseudoInstruction::SetupFinally { + delta: except_block + } + ); + emit!(self, Instruction::GetAnext); + emit!(self, Instruction::PushNull); + self.emit_load_const(ConstantData::None); + self.use_cpython_label_block(send_block); + let _ = self.compile_yield_from_sequence(true); + emit!(self, PseudoInstruction::PopBlock); + emit!(self, Instruction::NotTaken); - self.use_cpython_label_block(after_block); + self.compile_store(&for_stmt.target)?; + self.compile_for_body_and_backedge(&for_stmt.body, for_block)?; + self.pop_fblock_label(FBlockType::AsyncForLoop, for_label); - // Implicit return after for-loop should be attributed to the `for` line - self.set_source_range(iter.range()); + // END_ASYNC_FOR uses the iterator location but leaves the current + // source span unchanged for the common else suite. + self.use_cpython_label_block(except_block); + let saved_range = self.current_source_span; + self.set_source_node(iter.range(), iter.node_index()); + self.emit_end_async_for(send_block); + self.restore_source_span(saved_range); - self.leave_conditional_block(); + Ok(after_block) + } + + fn compile_for_body_and_backedge( + &mut self, + body: &[ast::Stmt], + for_block: BlockIdx, + ) -> CompileResult<()> { + self.compile_loop_body_statements(body)?; + emit!(self, PseudoInstruction::Jump { delta: for_block }); + self.set_no_location(); Ok(()) } fn compile_comprehension_iter(&mut self, generator: &ast::Comprehension) -> CompileResult<()> { - let saved_range = self.current_source_range; + let saved_range = self.current_source_span; self.compile_expression(&generator.iter)?; - self.set_source_range(generator.iter.range()); + self.set_source_node(generator.iter.range(), generator.iter.node_index()); if generator.is_async { emit!(self, Instruction::GetAiter); } else { - emit!(self, Instruction::GetIter); + emit!(self, Instruction::GetIter { mode: 0 }); } - self.set_source_range(saved_range); + self.restore_source_span(saved_range); Ok(()) } @@ -6736,7 +6867,7 @@ impl<'warnings> Compiler<'warnings> { /// Emits the necessary POP instructions for all failure targets in the pattern context, /// then resets the fail_pop vector. - fn emit_and_reset_fail_pop(&mut self, pc: &mut PatternContext, loc: TextRange) { + fn emit_and_reset_fail_pop(&mut self, pc: &mut PatternContext, loc: CompilerSourceSpan) { // If the fail_pop vector is empty, nothing needs to be done. if pc.fail_pop.is_empty() { debug_assert!(pc.fail_pop.is_empty()); @@ -6747,7 +6878,7 @@ impl<'warnings> Compiler<'warnings> { // CPython emit_and_reset_fail_pop() uses USE_LABEL here. self.use_cpython_label_block(label); // Emit the POP instruction. - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::PopTop); } // Finally, use the first label. @@ -6759,7 +6890,7 @@ impl<'warnings> Compiler<'warnings> { } /// Duplicate the effect of Python 3.10's ROT_* instructions using SWAPs. - fn pattern_helper_rotate(&mut self, loc: TextRange, mut count: usize) { + fn pattern_helper_rotate(&mut self, loc: CompilerSourceSpan, mut count: usize) { // Rotate TOS (top of stack) to position `count` down // This is done by a series of swaps // For count=1, no rotation needed (already at top) @@ -6767,7 +6898,7 @@ impl<'warnings> Compiler<'warnings> { // For count=3, swap TOS with item 2 positions down, then with item 1 position down while count > 1 { // Emit a SWAP instruction with the current count. - self.set_source_range(loc); + self.restore_source_span(loc); emit!( self, Instruction::Swap { @@ -6786,16 +6917,15 @@ impl<'warnings> Compiler<'warnings> { /// to the list of captured names. fn pattern_helper_store_name( &mut self, - loc: TextRange, + loc: CompilerSourceSpan, n: Option<&ast::Identifier>, pc: &mut PatternContext, ) -> CompileResult<()> { match n { // If no name is provided, simply pop the top of the stack. None => { - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::PopTop); - Ok(()) } Some(name) => { // Ensure we don't store the same name twice. @@ -6803,7 +6933,7 @@ impl<'warnings> Compiler<'warnings> { if pc.stores.contains(name.id()) { return Err(self.error_ranged( CodegenErrorType::DuplicateStore(name.as_str().to_string()), - loc, + loc.range, )); } @@ -6813,9 +6943,9 @@ impl<'warnings> Compiler<'warnings> { // Append the name to the captured stores. pc.stores.push(name.id().clone()); - Ok(()) } } + Ok(()) } fn pattern_wildcard_check(pattern: &ast::Pattern) -> bool { @@ -6834,7 +6964,7 @@ impl<'warnings> Compiler<'warnings> { fn pattern_unpack_helper( &mut self, - loc: TextRange, + loc: CompilerSourceSpan, elts: &[ast::Pattern], ) -> CompileResult<()> { let n = elts.len(); @@ -6844,25 +6974,25 @@ impl<'warnings> Compiler<'warnings> { if i >= (1 << 8) || (n - i - 1) >= ((i32::MAX as usize) >> 8) { return Err(self.error_ranged( CodegenErrorType::TooManyExpressionsInStarUnpackingSequencePattern, - loc, + loc.range, )); } let counts = UnpackExArgs { before: u8::try_from(i).unwrap(), after: u32::try_from(n - i - 1).unwrap(), }; - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::UnpackEx { counts }); seen_star = true; } else if elt.is_match_star() { return Err(self.error_ranged( CodegenErrorType::MultipleStarredExpressionsInSequencePattern, - loc, + loc.range, )); } } if !seen_star { - self.set_source_range(loc); + self.restore_source_span(loc); emit!( self, Instruction::UnpackSequence { @@ -6875,7 +7005,7 @@ impl<'warnings> Compiler<'warnings> { fn pattern_helper_sequence_unpack( &mut self, - loc: TextRange, + loc: CompilerSourceSpan, patterns: &[ast::Pattern], _star: Option, pc: &mut PatternContext, @@ -6896,7 +7026,7 @@ impl<'warnings> Compiler<'warnings> { fn pattern_helper_sequence_subscr( &mut self, - loc: TextRange, + loc: CompilerSourceSpan, patterns: &[ast::Pattern], star: usize, pc: &mut PatternContext, @@ -6913,23 +7043,22 @@ impl<'warnings> Compiler<'warnings> { continue; } // Duplicate the subject. - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::Copy { i: 1 }); + self.restore_source_span(loc); if i < star { // For indices before the star, use a nonnegative index equal to i. - self.set_source_range(loc); self.emit_load_const(ConstantData::Integer { value: i.into() }); } else { // For indices after the star, compute a nonnegative index: // index = len(subject) - (size - i) - self.set_source_range(loc); emit!(self, Instruction::GetLen); - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_load_const(ConstantData::Integer { value: (patterns.len() - i).into(), }); // Subtract to compute the correct index. - self.set_source_range(loc); + self.restore_source_span(loc); emit!( self, Instruction::BinaryOp { @@ -6938,7 +7067,7 @@ impl<'warnings> Compiler<'warnings> { ); } // Use BINARY_OP/NB_SUBSCR to extract the element. - self.set_source_range(loc); + self.restore_source_span(loc); emit!( self, Instruction::BinaryOp { @@ -6950,7 +7079,7 @@ impl<'warnings> Compiler<'warnings> { } // Pop the subject off the stack. pc.on_top -= 1; - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::PopTop); Ok(()) } @@ -6991,19 +7120,19 @@ impl<'warnings> Compiler<'warnings> { ); } // If irrefutable matches are allowed, store the name (if any). - return self.pattern_helper_store_name(p.range, p.name.as_ref(), pc); + return self.pattern_helper_store_name(self.node_span(p), p.name.as_ref(), pc); } // Otherwise, there is a sub-pattern. Duplicate the object on top of the stack. pc.on_top += 1; - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::Copy { i: 1 }); // Compile the sub-pattern. self.compile_pattern(p.pattern.as_ref().unwrap(), pc)?; // After success, decrement the on_top counter. pc.on_top -= 1; // Store the captured name (if any). - self.pattern_helper_store_name(p.range, p.name.as_ref(), pc)?; + self.pattern_helper_store_name(self.node_span(p), p.name.as_ref(), pc)?; Ok(()) } @@ -7012,7 +7141,7 @@ impl<'warnings> Compiler<'warnings> { p: &ast::PatternMatchStar, pc: &mut PatternContext, ) -> CompileResult<()> { - self.pattern_helper_store_name(p.range, p.name.as_ref(), pc)?; + self.pattern_helper_store_name(self.node_span(p), p.name.as_ref(), pc)?; Ok(()) } @@ -7090,7 +7219,7 @@ impl<'warnings> Compiler<'warnings> { // Compile the class expression. self.compile_expression(&match_class.cls)?; - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); // Create a new tuple of attribute names. let mut attr_names = vec![]; @@ -7127,7 +7256,7 @@ impl<'warnings> Compiler<'warnings> { // At this point the TOS is a tuple of (nargs + n_attrs) attributes (or None). pc.on_top += 1; - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); // Unpack the tuple into (nargs + n_attrs) items. @@ -7150,7 +7279,7 @@ impl<'warnings> Compiler<'warnings> { pc.on_top -= 1; if Self::pattern_wildcard_check(subpattern) { - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::PopTop); continue; // Don't compile wildcard patterns } @@ -7199,11 +7328,11 @@ impl<'warnings> Compiler<'warnings> { // Stack: [subject] pc.on_top += 1; - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::MatchMapping); // Stack: [subject, is_mapping] - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); // Stack: [subject] @@ -7218,19 +7347,19 @@ impl<'warnings> Compiler<'warnings> { // Length check for patterns with keys if size > 0 { // Check if the mapping has at least 'size' keys - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::GetLen); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.emit_load_const(ConstantData::Integer { value: size.into() }); // Stack: [subject, len, size] - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!( self, Instruction::CompareOp { opname: ComparisonOperator::GreaterOrEqual } ); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); // Stack: [subject] } @@ -7251,7 +7380,7 @@ impl<'warnings> Compiler<'warnings> { for key in keys { self.compile_pattern_mapping_key(&mut seen, p.range, key)?; } - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); // Stack: [subject, key1, key2, ..., key_n] // Build tuple of keys (empty tuple if size==0) @@ -7264,14 +7393,14 @@ impl<'warnings> Compiler<'warnings> { pc.on_top += 2; // subject and keys_tuple are underneath // Check if match succeeded - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::Copy { i: 1 }); // Stack: [subject, keys_tuple, values_tuple, values_tuple_copy] // Check if copy is None (consumes the copy like POP_JUMP_IF_NONE) - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.emit_load_const(ConstantData::None); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!( self, Instruction::IsOp { @@ -7280,7 +7409,7 @@ impl<'warnings> Compiler<'warnings> { ); // Stack: [subject, keys_tuple, values_tuple, bool] - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); // Stack: [subject, keys_tuple, values_tuple] @@ -7305,24 +7434,24 @@ impl<'warnings> Compiler<'warnings> { pc.on_top -= 2; // Step 4: Handle rest pattern or cleanup + self.set_source_node(p.range, &p.node_index); if let Some(rest_name) = star_target { // Build rest dict for **rest pattern // Stack: [subject, keys_tuple] // Build rest dict exactly - self.set_source_range(p.range); emit!(self, Instruction::BuildMap { count: 0 }); // Stack: [subject, keys_tuple, {}] - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::Swap { i: 3 }); // Stack: [{}, keys_tuple, subject] - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::DictUpdate { i: 2 }); // Stack after DICT_UPDATE: [rest_dict, keys_tuple] // DICT_UPDATE consumes source (subject) and leaves dict in place // Unpack keys and delete from rest_dict - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::UnpackSequence { count: size }); // Stack: [rest_dict, k1, k2, ..., kn] (if size==0, nothing pushed) @@ -7331,13 +7460,13 @@ impl<'warnings> Compiler<'warnings> { let mut remaining = size; while remaining > 0 { // Copy rest_dict which is at position (1 + remaining) from TOS - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::Copy { i: 1 + remaining }); // Stack: [rest_dict, k1, ..., kn, rest_dict] - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::Swap { i: 2 }); // Stack: [rest_dict, k1, ..., kn-1, rest_dict, kn] - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::DeleteSubscr); // Stack: [rest_dict, k1, ..., kn-1] (removed kn from rest_dict) remaining -= 1; @@ -7346,14 +7475,13 @@ impl<'warnings> Compiler<'warnings> { // pattern_helper_store_name will handle the rotation correctly // Store the rest dict - self.pattern_helper_store_name(p.range, Some(rest_name), pc)?; + self.pattern_helper_store_name(self.node_span(p), Some(rest_name), pc)?; } else { // Non-rest pattern: just clean up the stack // Pop them as we're not using them - self.set_source_range(p.range); emit!(self, Instruction::PopTop); // Pop keys_tuple - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::PopTop); // Pop subject } @@ -7586,7 +7714,7 @@ impl<'warnings> Compiler<'warnings> { pc.fail_pop.clear(); pc.on_top = 0; // Emit a COPY(1) instruction before compiling the alternative. - self.set_source_range(alt.range()); + self.set_source_node(alt.range(), alt.node_index()); emit!(self, Instruction::Copy { i: 1 }); self.compile_pattern(alt, pc)?; @@ -7628,19 +7756,19 @@ impl<'warnings> Compiler<'warnings> { pc.stores.insert(insert_pos + j, elem); } // Also perform the same rotation on the evaluation stack. - self.set_source_range(alt.range()); + self.set_source_node(alt.range(), alt.node_index()); for _ in 0..=i_stores { - self.pattern_helper_rotate(alt.range(), i_control + 1); + self.pattern_helper_rotate(self.node_span(alt), i_control + 1); } } } } } // Emit a jump to the common end label and reset any failure jump targets. - self.set_source_range(alt.range()); + self.set_source_node(alt.range(), alt.node_index()); emit!(self, PseudoInstruction::Jump { delta: end }); - self.set_source_range(alt.range()); - self.emit_and_reset_fail_pop(pc, alt.range()); + self.set_source_node(alt.range(), alt.node_index()); + self.emit_and_reset_fail_pop(pc, self.node_span(alt)); } // Restore the original pattern context. @@ -7651,7 +7779,7 @@ impl<'warnings> Compiler<'warnings> { // In Rust, old_pc is a local clone, so we need not worry about that. // No alternative matched: pop the subject and fail. - self.set_source_range(p.range()); + self.set_source_node(p.range(), p.node_index()); emit!(self, Instruction::PopTop); self.jump_to_fail_pop(pc, JumpOp::Jump); @@ -7664,8 +7792,8 @@ impl<'warnings> Compiler<'warnings> { let n_rots = n_stores + 1 + pc.on_top + pc.stores.len(); for i in 0..n_stores { // Rotate the capture to its proper place. - self.set_source_range(p.range()); - self.pattern_helper_rotate(p.range(), n_rots); + self.set_source_node(p.range(), p.node_index()); + self.pattern_helper_rotate(self.node_span(p), n_rots); let name = &control.as_ref().unwrap()[i]; // Check for duplicate binding. if pc.stores.contains(name) { @@ -7679,7 +7807,7 @@ impl<'warnings> Compiler<'warnings> { // Old context and control will be dropped automatically. // Finally, pop the copy of the subject. - self.set_source_range(p.range()); + self.set_source_node(p.range(), p.node_index()); emit!(self, Instruction::PopTop); Ok(()) } @@ -7717,42 +7845,42 @@ impl<'warnings> Compiler<'warnings> { // Keep the subject on top during the sequence and length checks. pc.on_top += 1; - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::MatchSequence); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); if star.is_none() { // No star: len(subject) == size - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::GetLen); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.emit_load_const(ConstantData::Integer { value: size.into() }); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!( self, Instruction::CompareOp { opname: ComparisonOperator::Equal } ); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); } else if size > 1 { // Star exists: len(subject) >= size - 1 - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::GetLen); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.emit_load_const(ConstantData::Integer { value: (size - 1).into(), }); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!( self, Instruction::CompareOp { opname: ComparisonOperator::GreaterOrEqual } ); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); } @@ -7760,12 +7888,12 @@ impl<'warnings> Compiler<'warnings> { pc.on_top -= 1; if only_wildcard { // ast::Patterns like: [] / [_] / [_, _] / [*_] / [_, *_] / [_, _, *_] / etc. - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::PopTop); } else if star_wildcard { - self.pattern_helper_sequence_subscr(p.range, patterns, star.unwrap(), pc)?; + self.pattern_helper_sequence_subscr(self.node_span(p), patterns, star.unwrap(), pc)?; } else { - self.pattern_helper_sequence_unpack(p.range, patterns, star, pc)?; + self.pattern_helper_sequence_unpack(self.node_span(p), patterns, star, pc)?; } Ok(()) } @@ -7779,7 +7907,7 @@ impl<'warnings> Compiler<'warnings> { // before the fail jump. Late IR folding will collapse COMPARE_OP+TO_BOOL // into COMPARE_OP bool(...) when applicable. if let Some(constant) = self.try_compile_match_value_constant(&p.value)? { - self.set_source_range(p.value.range()); + self.set_source_node(p.value.range(), p.value.node_index()); self.emit_load_const(constant); } else if matches!(*p.value, ast::Expr::Attribute(_)) { self.compile_expression(&p.value)?; @@ -7799,16 +7927,16 @@ impl<'warnings> Compiler<'warnings> { p.range, )); } - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!( self, Instruction::CompareOp { opname: bytecode::ComparisonOperator::Equal } ); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::ToBool); - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); Ok(()) } @@ -7819,17 +7947,17 @@ impl<'warnings> Compiler<'warnings> { pc: &mut PatternContext, ) { // Load the singleton constant value. - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.emit_load_const(match p.value { ast::Singleton::None => ConstantData::None, ast::Singleton::False => ConstantData::Boolean { value: false }, ast::Singleton::True => ConstantData::Boolean { value: true }, }); // Compare using the "Is" operator. - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); emit!(self, Instruction::IsOp { invert: Invert::No }); // Jump to the failure label if the comparison is false. - self.set_source_range(p.range); + self.set_source_node(p.range, &p.node_index); self.jump_to_fail_pop(pc, JumpOp::PopJumpIfFalse); } @@ -7838,8 +7966,8 @@ impl<'warnings> Compiler<'warnings> { pattern_type: &ast::Pattern, pattern_context: &mut PatternContext, ) -> CompileResult<()> { - let prev_source_range = self.current_source_range; - self.set_source_range(pattern_type.range()); + let prev_source_range = self.current_source_span; + self.set_source_node(pattern_type.range(), pattern_type.node_index()); let result = match &pattern_type { ast::Pattern::MatchValue(pattern_type) => { self.compile_pattern_value(pattern_type, pattern_context) @@ -7867,7 +7995,7 @@ impl<'warnings> Compiler<'warnings> { self.compile_pattern_or(pattern_type, pattern_context) } }; - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); result } @@ -7889,7 +8017,7 @@ impl<'warnings> Compiler<'warnings> { for (i, m) in cases.iter().enumerate().take(case_count) { // Only copy the subject if not on the last case if i != case_count - 1 { - self.set_source_range(m.pattern.range()); + self.set_source_node(m.pattern.range(), m.pattern.node_index()); emit!(self, Instruction::Copy { i: 1 }); } @@ -7902,7 +8030,7 @@ impl<'warnings> Compiler<'warnings> { assert_eq!(pattern_context.on_top, 0); for name in &pattern_context.stores { - self.set_source_range(m.pattern.range()); + self.set_source_node(m.pattern.range(), m.pattern.node_index()); self.compile_name(name, NameUsage::Store)?; } @@ -7912,13 +8040,13 @@ impl<'warnings> Compiler<'warnings> { guard, false, pattern_context.fail_pop[0], - Some(m.pattern.range()), + Some(self.node_span(&m.pattern)), )?; } if i != case_count - 1 { if let Some(first_stmt) = m.body.first() { - self.set_source_range(first_stmt.range()); + self.set_source_node(first_stmt.range(), first_stmt.node_index()); } emit!(self, Instruction::PopTop); // CPython emits NEXT_LOCATION here; resolve it after redundant @@ -7929,20 +8057,20 @@ impl<'warnings> Compiler<'warnings> { self.compile_statements(&m.body)?; emit!(self, PseudoInstruction::Jump { delta: end }); self.set_no_location(); - self.set_source_range(m.pattern.range()); - self.emit_and_reset_fail_pop(pattern_context, m.pattern.range()); + self.set_source_node(m.pattern.range(), m.pattern.node_index()); + self.emit_and_reset_fail_pop(pattern_context, self.node_span(&m.pattern)); } if has_default { let m = &cases[num_cases - 1]; - self.set_source_range(m.pattern.range()); + self.set_source_node(m.pattern.range(), m.pattern.node_index()); if num_cases == 1 { emit!(self, Instruction::PopTop); } else { emit!(self, Instruction::Nop); } if let Some(ref guard) = m.guard { - self.compile_jump_if_inner(guard, false, end, Some(m.pattern.range()))?; + self.compile_jump_if_inner(guard, false, end, Some(self.node_span(&m.pattern)))?; } self.compile_statements(&m.body)?; } @@ -8046,7 +8174,8 @@ impl<'warnings> Compiler<'warnings> { comparators: &[ast::Expr], ) -> CompileResult<()> { // Save the full Compare expression range for COMPARE_OP positions - let compare_range = self.current_source_range; + let compare_range_span = self.current_source_span; + let compare_range = compare_range_span.range; self.check_compare(compare_range, left, ops, comparators)?; let (last_op, mid_ops) = ops.split_last().unwrap(); let (last_comparator, mid_comparators) = comparators.split_last().unwrap(); @@ -8056,7 +8185,7 @@ impl<'warnings> Compiler<'warnings> { if mid_comparators.is_empty() { self.compile_expression(last_comparator)?; - self.set_source_range(compare_range); + self.restore_source_span(compare_range_span); self.compile_addcompare(*last_op); return Ok(()); @@ -8069,7 +8198,7 @@ impl<'warnings> Compiler<'warnings> { self.compile_expression(comparator)?; // store rhs for the next comparison in chain - self.set_source_range(compare_range); + self.restore_source_span(compare_range_span); emit!(self, Instruction::Swap { i: 2 }); emit!(self, Instruction::Copy { i: 2 }); @@ -8083,7 +8212,7 @@ impl<'warnings> Compiler<'warnings> { } self.compile_expression(last_comparator)?; - self.set_source_range(compare_range); + self.restore_source_span(compare_range_span); self.compile_addcompare(*last_op); let end = self.new_block(); @@ -8107,7 +8236,8 @@ impl<'warnings> Compiler<'warnings> { condition: bool, target_block: BlockIdx, ) -> CompileResult<()> { - let compare_range = self.current_source_range; + let compare_range_span = self.current_source_span; + let compare_range = compare_range_span.range; self.check_compare(compare_range, left, ops, comparators)?; let (last_op, mid_ops) = ops.split_last().unwrap(); let (last_comparator, mid_comparators) = comparators.split_last().unwrap(); @@ -8115,7 +8245,7 @@ impl<'warnings> Compiler<'warnings> { if mid_comparators.is_empty() { self.compile_expression(left)?; self.compile_expression(last_comparator)?; - self.set_source_range(compare_range); + self.restore_source_span(compare_range_span); self.compile_addcompare(*last_op); self.emit_pop_jump_by_condition(condition, target_block); return Ok(()); @@ -8126,7 +8256,7 @@ impl<'warnings> Compiler<'warnings> { for (op, comparator) in mid_ops.iter().zip(mid_comparators) { self.compile_expression(comparator)?; - self.set_source_range(compare_range); + self.restore_source_span(compare_range_span); emit!(self, Instruction::Swap { i: 2 }); emit!(self, Instruction::Copy { i: 2 }); self.compile_addcompare(*op); @@ -8135,7 +8265,7 @@ impl<'warnings> Compiler<'warnings> { } self.compile_expression(last_comparator)?; - self.set_source_range(compare_range); + self.restore_source_span(compare_range_span); self.compile_addcompare(*last_op); emit!(self, Instruction::ToBool); self.emit_pop_jump_by_condition(condition, target_block); @@ -8179,7 +8309,7 @@ impl<'warnings> Compiler<'warnings> { fn compile_annotation(&mut self, annotation: &ast::Expr) -> CompileResult<()> { if self.future_annotations { - self.set_source_range(annotation.range()); + self.set_source_node(annotation.range(), annotation.node_index()); self.emit_load_const(ConstantData::Str { value: UnparseExpr::new(annotation, &self.source_file) .to_string() @@ -8194,9 +8324,9 @@ impl<'warnings> Compiler<'warnings> { ast::Expr::Starred(ast::ExprStarred { value, .. }) => { // *args: *Ts (where Ts is a TypeVarTuple). // Do [annotation_value] = [*Ts]. - let saved_range = self.current_source_range; + let saved_range = self.current_source_span; self.compile_expression(value)?; - self.set_source_range(saved_range); + self.restore_source_span(saved_range); emit!(self, Instruction::UnpackSequence { count: 1 }); Ok(()) } @@ -8211,7 +8341,7 @@ impl<'warnings> Compiler<'warnings> { fn compile_check_annotation_expression(&mut self, expression: &ast::Expr) -> CompileResult<()> { self.compile_expression(expression)?; - self.set_source_range(expression.range()); + self.set_source_node(expression.range(), expression.node_index()); emit!(self, Instruction::PopTop); Ok(()) } @@ -8247,7 +8377,7 @@ impl<'warnings> Compiler<'warnings> { annotation: &ast::Expr, value: Option<&ast::Expr>, simple: bool, - loc: TextRange, + loc: CompilerSourceSpan, ) -> CompileResult<()> { // Perform the actual assignment first if let Some(value) = value { @@ -8264,7 +8394,7 @@ impl<'warnings> Compiler<'warnings> { // PEP 563: Store stringified annotation directly to __annotations__ // Compile annotation as string self.compile_annotation(annotation)?; - self.set_source_range(loc); + self.restore_source_span(loc); // Load __annotations__ let annotations_name = self.name("__annotations__"); emit!( @@ -8274,12 +8404,12 @@ impl<'warnings> Compiler<'warnings> { } ); // Load the variable name - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_load_const(ConstantData::Str { value: self.mangle(id).as_str().into(), }); // Store: __annotations__[name] = annotation - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::StoreSubscr); } else { // PEP 649: Handle conditional annotations @@ -8294,7 +8424,7 @@ impl<'warnings> Compiler<'warnings> { let annotation_index = code_info.next_conditional_annotation_index; code_info.next_conditional_annotation_index += 1; - self.set_source_range(loc); + self.restore_source_span(loc); if matches!(scope_type, CompilerScope::Class) { let i = self.get_cell_var_index("__conditional_annotations__"); emit!(self, Instruction::LoadDeref { i }); @@ -8329,8 +8459,8 @@ impl<'warnings> Compiler<'warnings> { } fn compile_store(&mut self, target: &ast::Expr) -> CompileResult<()> { - let prev_source_range = self.current_source_range; - self.set_source_range(target.range()); + let prev_source_range = self.current_source_span; + self.set_source_node(target.range(), target.node_index()); let result = (|| -> CompileResult<()> { match &target { ast::Expr::Name(ast::ExprName { id, .. }) => self.store_name(id)?, @@ -8342,11 +8472,11 @@ impl<'warnings> Compiler<'warnings> { ast::Expr::Attribute(ast::ExprAttribute { value, attr, .. }) => { self.maybe_add_static_attribute_to_class(value, attr.as_str()); self.compile_expression(value)?; - self.set_source_range(self.update_start_location_to_match_attr( - target.range(), - target.range(), + self.restore_source_span(self.update_start_span_to_match_attr( + self.node_span(target), + self.node_span(target), attr.as_str(), - )); + )?); let namei = self.name(attr.as_str()); emit!(self, Instruction::StoreAttr { namei }); } @@ -8409,7 +8539,7 @@ impl<'warnings> Compiler<'warnings> { Ok(()) })(); - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); result } @@ -8419,8 +8549,9 @@ impl<'warnings> Compiler<'warnings> { op: ast::Operator, value: &ast::Expr, ) -> CompileResult<()> { - let stmt_range = self.current_source_range; - let target_range = target.range(); + let stmt_range_span = self.current_source_span; + + let target_span = self.node_span(target); enum AugAssignKind<'a> { Name { id: &'a Name, @@ -8430,20 +8561,20 @@ impl<'warnings> Compiler<'warnings> { }, Attr { idx: bytecode::NameIdx, - attr_range: TextRange, + attr_range: CompilerSourceSpan, }, } let kind = match &target { ast::Expr::Name(ast::ExprName { id, .. }) => { - self.set_source_range(target_range); + self.restore_source_span(target_span); self.compile_name(id, NameUsage::Load)?; AugAssignKind::Name { id } } ast::Expr::Subscript(ast::ExprSubscript { value, slice, .. }) => { let use_slice_opt = self.should_apply_two_element_slice_optimization(slice); self.compile_expression(value)?; - self.set_source_range(target_range); + self.restore_source_span(target_span); if use_slice_opt { let ast::Expr::Slice(slice_expr) = slice.as_ref() else { unreachable!( @@ -8451,14 +8582,14 @@ impl<'warnings> Compiler<'warnings> { ); }; self.compile_slice_two_parts(slice_expr)?; - self.set_source_range(target_range); + self.restore_source_span(target_span); emit!(self, Instruction::Copy { i: 3 }); emit!(self, Instruction::Copy { i: 3 }); emit!(self, Instruction::Copy { i: 3 }); emit!(self, Instruction::BinarySlice); } else { self.compile_expression(slice)?; - self.set_source_range(target_range); + self.restore_source_span(target_span); emit!(self, Instruction::Copy { i: 2 }); emit!(self, Instruction::Copy { i: 2 }); emit!( @@ -8474,11 +8605,11 @@ impl<'warnings> Compiler<'warnings> { let attr = attr.as_str(); self.compile_expression(value)?; let attr_range = - self.update_start_location_to_match_attr(target_range, target_range, attr); - self.set_source_range(target_range); + self.update_start_span_to_match_attr(target_span, target_span, attr)?; + self.restore_source_span(target_span); emit!(self, Instruction::Copy { i: 1 }); let idx = self.name(attr); - self.set_source_range(attr_range); + self.restore_source_span(attr_range); self.emit_load_attr(idx); AugAssignKind::Attr { idx, attr_range } } @@ -8488,17 +8619,17 @@ impl<'warnings> Compiler<'warnings> { }; self.compile_expression(value)?; - self.set_source_range(stmt_range); + self.restore_source_span(stmt_range_span); self.compile_op(op, true); match kind { AugAssignKind::Name { id } => { // stack: RESULT - self.set_source_range(target_range); + self.restore_source_span(target_span); self.compile_name(id, NameUsage::Store)?; } AugAssignKind::Subscript { use_slice_opt } => { - self.set_source_range(target_range); + self.restore_source_span(target_span); if use_slice_opt { // stack: CONTAINER START STOP RESULT emit!(self, Instruction::Swap { i: 4 }); @@ -8514,7 +8645,7 @@ impl<'warnings> Compiler<'warnings> { } AugAssignKind::Attr { idx, attr_range } => { // stack: CONTAINER RESULT - self.set_source_range(attr_range); + self.restore_source_span(attr_range); emit!(self, Instruction::Swap { i: 2 }); emit!(self, Instruction::StoreAttr { namei: idx }); } @@ -8557,10 +8688,10 @@ impl<'warnings> Compiler<'warnings> { expression: &ast::Expr, condition: bool, target_block: BlockIdx, - source_range: Option, + source_range: Option, ) -> CompileResult<()> { - let prev_source_range = self.current_source_range; - self.set_source_range(source_range.unwrap_or_else(|| expression.range())); + let prev_source_range = self.current_source_span; + self.restore_source_span(source_range.unwrap_or_else(|| self.node_span(expression))); // Compile expression for test, and jump to label if false let result = match &expression { @@ -8604,19 +8735,20 @@ impl<'warnings> Compiler<'warnings> { self.use_cpython_label_block(end); Ok(()) } - ast::Expr::Compare(ast::ExprCompare { - left, - ops, - comparators, - .. - }) if ops.len() > 1 => { - self.set_source_range(expression.range()); - self.compile_jump_if_compare(left, ops, comparators, condition, target_block) + ast::Expr::Compare(compare) if compare.ops.len() > 1 => { + self.set_source_node(expression.range(), expression.node_index()); + self.compile_jump_if_compare( + compare.first_operand(), + &compare.ops, + compare.comparators(), + condition, + target_block, + ) } _ => { // Fall back case which always will work! self.compile_expression(expression)?; - self.set_source_range(expression.range()); + self.set_source_node(expression.range(), expression.node_index()); emit!(self, Instruction::ToBool); if condition { emit!( @@ -8637,7 +8769,7 @@ impl<'warnings> Compiler<'warnings> { } }; - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); result } @@ -8653,15 +8785,16 @@ impl<'warnings> Compiler<'warnings> { /// Compile a boolean operation as an expression. /// This means, that the last value remains on the stack. fn compile_bool_op(&mut self, op: ast::BoolOp, values: &[ast::Expr]) -> CompileResult<()> { - let boolop_range = self.current_source_range; + let boolop_range_span = self.current_source_span; + let after_block = self.new_block(); let (last_value, prefix_values) = values.split_last().unwrap(); for value in prefix_values { self.compile_expression(value)?; - self.set_source_range(boolop_range); + self.restore_source_span(boolop_range_span); self.emit_short_circuit_test(op, after_block); - self.set_source_range(boolop_range); + self.restore_source_span(boolop_range_span); emit!(self, Instruction::PopTop); } @@ -8688,30 +8821,34 @@ impl<'warnings> Compiler<'warnings> { items: &[ast::DictItem], begin: usize, end: usize, - range: TextRange, + span: CompilerSourceSpan, ) -> CompileResult<()> { let n = end - begin; let big = n * 2 > STACK_USE_GUIDELINE as usize; if big { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::BuildMap { count: 0 }); } for item in &items[begin..end] { self.compile_expression(item.key.as_ref().unwrap())?; self.compile_expression(&item.value)?; if big { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::MapAdd { i: 1 }); } } if !big { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::BuildMap { count: n.to_u32() }); } Ok(()) } - fn compile_dict(&mut self, items: &[ast::DictItem], range: TextRange) -> CompileResult<()> { + fn compile_dict( + &mut self, + items: &[ast::DictItem], + span: CompilerSourceSpan, + ) -> CompileResult<()> { let n = items.len(); let mut have_dict = false; let mut elements = 0usize; @@ -8719,26 +8856,26 @@ impl<'warnings> Compiler<'warnings> { for (i, item) in items.iter().enumerate() { if item.key.is_none() { if elements != 0 { - self.compile_subdict(items, i - elements, i, range)?; + self.compile_subdict(items, i - elements, i, span)?; if have_dict { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::DictUpdate { i: 1 }); } have_dict = true; elements = 0; } if !have_dict { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::BuildMap { count: 0 }); have_dict = true; } self.compile_expression(&item.value)?; - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::DictUpdate { i: 1 }); } else if elements * 2 > STACK_USE_GUIDELINE as usize { - self.compile_subdict(items, i - elements, i + 1, range)?; + self.compile_subdict(items, i - elements, i + 1, span)?; if have_dict { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::DictUpdate { i: 1 }); } have_dict = true; @@ -8749,15 +8886,15 @@ impl<'warnings> Compiler<'warnings> { } if elements != 0 { - self.compile_subdict(items, n - elements, n, range)?; + self.compile_subdict(items, n - elements, n, span)?; if have_dict { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::DictUpdate { i: 1 }); } have_dict = true; } if !have_dict { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::BuildMap { count: 0 }); } @@ -8817,8 +8954,8 @@ impl<'warnings> Compiler<'warnings> { ); // fail: CLEANUP_THROW - // Stack when exception: [receiver, yielded_value, exc] - // CLEANUP_THROW: [sub_iter, last_sent_val, exc] -> [None, value] + // Stack when exception: [receiver, NULL, yielded_value, exc] + // CLEANUP_THROW: [sub_iter, NULL, last_sent_val, exc] -> [None, NULL, value] // CPython lets this block fall through to END_SEND during codegen; // push_cold_blocks_to_end later inserts the no-interrupt jump after // moving the cold fail block behind the warm exit path. @@ -8826,8 +8963,8 @@ impl<'warnings> Compiler<'warnings> { emit!(self, Instruction::CleanupThrow); // exit: END_SEND - // Stack: [receiver, value] (from SEND) or [None, value] (from CLEANUP_THROW) - // END_SEND: [receiver/None, value] -> [value] + // Stack: [receiver, NULL, value] or [None, NULL, value] after CLEANUP_THROW. + // END_SEND: [receiver/None, NULL, value] -> [value] self.use_cpython_label_block(exit_block); emit!(self, Instruction::EndSend); @@ -8852,8 +8989,8 @@ impl<'warnings> Compiler<'warnings> { fn compile_expression(&mut self, expression: &ast::Expr) -> CompileResult<()> { trace!("Compiling {expression:?}"); - let range = expression.range(); - self.set_source_range(range); + let expression_span = self.node_span(expression); + self.restore_source_span(expression_span); if let Some(constant) = self.ast_constant_value(expression) { self.emit_load_const(constant); @@ -8874,7 +9011,7 @@ impl<'warnings> Compiler<'warnings> { self.compile_expression(right)?; // Restore full expression range before emitting the operation - self.set_source_range(range); + self.restore_source_span(expression_span); self.compile_op(*op, false); } ast::Expr::Subscript(ast::ExprSubscript { @@ -8886,7 +9023,7 @@ impl<'warnings> Compiler<'warnings> { self.compile_expression(operand)?; // Restore full expression range before emitting the operation - self.set_source_range(range); + self.restore_source_span(expression_span); match op { ast::UnaryOp::UAdd => emit!( self, @@ -8913,10 +9050,17 @@ impl<'warnings> Compiler<'warnings> { else { unreachable!("can_optimize_super_call only accepts calls"); }; - self.load_args_for_super(&super_type, super_func.range(), value.range())?; - let attr_access_range = - self.update_start_location_to_match_attr(range, range, attr.as_str()); - self.set_source_range(range); + self.load_args_for_super( + &super_type, + self.node_span(super_func.as_ref()), + self.node_span(value.as_ref()), + )?; + let attr_access_span = self.update_start_span_to_match_attr( + expression_span, + expression_span, + attr.as_str(), + )?; + self.restore_source_span(expression_span); let idx = self.name(attr.as_str()); match super_type { SuperCallType::TwoArg { .. } => { @@ -8926,72 +9070,63 @@ impl<'warnings> Compiler<'warnings> { self.emit_load_zero_super_attr(idx); } } - self.set_source_range(attr_access_range); + self.restore_source_span(attr_access_span); emit!(self, Instruction::Nop); } else { // Normal attribute access self.compile_expression(value)?; - self.set_source_range(self.update_start_location_to_match_attr( - range, - range, + self.restore_source_span(self.update_start_span_to_match_attr( + expression_span, + expression_span, attr.as_str(), - )); + )?); let idx = self.name(attr.as_str()); self.emit_load_attr(idx); } } - ast::Expr::Compare(ast::ExprCompare { - left, - ops, - comparators, - .. - }) => { - self.compile_compare(left, ops, comparators)?; + ast::Expr::Compare(compare) => { + self.compile_compare(compare.first_operand(), &compare.ops, compare.comparators())?; } ast::Expr::Constant(ast::ExprConstant { value, .. }) => { self.emit_load_const(ast_constant_value_to_constant_data(value.clone())); } - ast::Expr::List(ast::ExprList { elts, range, .. }) => { - self.set_source_range(*range); + ast::Expr::List(ast::ExprList { elts, .. }) => { + self.restore_source_span(expression_span); self.starunpack_helper(elts, 0, CollectionType::List)?; } - ast::Expr::Tuple(ast::ExprTuple { elts, range, .. }) => { - self.set_source_range(*range); + ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => { + self.restore_source_span(expression_span); self.starunpack_helper(elts, 0, CollectionType::Tuple)?; } - ast::Expr::Set(ast::ExprSet { elts, range, .. }) => { - self.set_source_range(*range); + ast::Expr::Set(ast::ExprSet { elts, .. }) => { + self.restore_source_span(expression_span); self.starunpack_helper(elts, 0, CollectionType::Set)?; } - ast::Expr::Dict(ast::ExprDict { items, range, .. }) => { - self.compile_dict(items, *range)?; + ast::Expr::Dict(ast::ExprDict { items, .. }) => { + self.compile_dict(items, expression_span)?; } ast::Expr::Slice(ast::ExprSlice { - lower, - upper, - step, - range, - .. + lower, upper, step, .. }) => { if let Some(folded_const) = self.try_fold_constant_slice( lower.as_deref(), upper.as_deref(), step.as_deref(), )? { - self.set_source_range(*range); + self.restore_source_span(expression_span); self.emit_load_const(folded_const); return Ok(()); } if let Some(lower) = lower { self.compile_expression(lower)?; } else { - self.set_source_range(*range); + self.restore_source_span(expression_span); self.emit_load_const(ConstantData::None); } if let Some(upper) = upper { self.compile_expression(upper)?; } else { - self.set_source_range(*range); + self.restore_source_span(expression_span); self.emit_load_const(ConstantData::None); } if let Some(step) = step { @@ -9001,7 +9136,7 @@ impl<'warnings> Compiler<'warnings> { Some(_) => BuildSliceArgCount::Three, None => BuildSliceArgCount::Two, }; - self.set_source_range(*range); + self.restore_source_span(expression_span); emit!(self, Instruction::BuildSlice { argc }); } ast::Expr::Yield(ast::ExprYield { value, .. }) => { @@ -9013,7 +9148,7 @@ impl<'warnings> Compiler<'warnings> { Some(expression) => self.compile_expression(expression)?, Option::None => self.emit_load_const(ConstantData::None), }; - self.set_source_range(range); + self.restore_source_span(expression_span); if self.ctx.func == FunctionContext::AsyncFunction { emit!( self, @@ -9038,8 +9173,9 @@ impl<'warnings> Compiler<'warnings> { return Err(self.error(CodegenErrorType::InvalidAwait)); } self.compile_expression(value)?; - self.set_source_range(range); + self.restore_source_span(expression_span); emit!(self, Instruction::GetAwaitable { r#where: 0 }); + emit!(self, Instruction::PushNull); self.emit_load_const(ConstantData::None); let _ = self.compile_yield_from_sequence(true); } @@ -9055,17 +9191,19 @@ impl<'warnings> Compiler<'warnings> { } self.mark_generator(); self.compile_expression(value)?; - self.set_source_range(range); - emit!(self, Instruction::GetYieldFromIter); + self.restore_source_span(expression_span); + emit!( + self, + Instruction::GetIter { + mode: oparg::GET_ITER_YIELD_FROM + } + ); self.emit_load_const(ConstantData::None); let _ = self.compile_yield_from_sequence(false); } ast::Expr::Name(ast::ExprName { id, .. }) => self.load_name(id)?, ast::Expr::Lambda(ast::ExprLambda { - parameters, - body, - range, - .. + parameters, body, .. }) => { let default_params = ast::Parameters::default(); let params = parameters.as_deref().unwrap_or(&default_params); @@ -9087,7 +9225,7 @@ impl<'warnings> Compiler<'warnings> { for element in &defaults { self.compile_expression(element)?; } - self.set_source_range(*range); + self.restore_source_span(expression_span); emit!(self, Instruction::BuildTuple { count: size }); } @@ -9103,13 +9241,13 @@ impl<'warnings> Compiler<'warnings> { if have_kwdefaults { let default_kw_count = kw_with_defaults.len(); for (arg, default) in &kw_with_defaults { - self.set_source_range(*range); + self.restore_source_span(expression_span); self.emit_load_const(ConstantData::Str { value: self.mangle(arg.name().id()).as_str().into(), }); self.compile_expression(default)?; } - self.set_source_range(*range); + self.restore_source_span(expression_span); emit!( self, Instruction::BuildMap { @@ -9149,23 +9287,20 @@ impl<'warnings> Compiler<'warnings> { emit!(self, Instruction::ReturnValue); self.set_no_location(); } else { - self.set_source_range(body.range()); + self.set_source_node(body.range(), body.node_index()); self.emit_return_value(); self.emit_return_const_no_location(ConstantData::None); } let code = self.exit_scope(); // Create lambda function with closure - self.set_source_range(*range); + self.restore_source_span(expression_span); self.make_closure(code, func_flags)?; self.ctx = prev_ctx; } ast::Expr::ListComp(ast::ExprListComp { - elt, - generators, - range, - .. + elt, generators, .. }) => { self.compile_comprehension( "", @@ -9177,28 +9312,25 @@ impl<'warnings> Compiler<'warnings> { ), generators, &|compiler, collection_add_i| { - compiler.compile_comprehension_element(elt)?; - compiler.set_source_range(elt.range()); - emit!( - compiler, - Instruction::ListAppend { - i: collection_add_i.to_u32(), - } - ); + let unpack = compiler.compile_comprehension_element(elt)?; + compiler.set_source_node(elt.range(), elt.node_index()); + let i = collection_add_i.to_u32(); + if unpack { + emit!(compiler, Instruction::ListExtend { i }); + } else { + emit!(compiler, Instruction::ListAppend { i }); + } Ok(()) }, ComprehensionType::List, Self::contains_await(elt) || Self::generators_contain_await(generators), - *range, - elt.range(), - elt.range(), + expression_span, + self.node_span(elt.as_ref()), + self.node_span(elt.as_ref()), )?; } ast::Expr::SetComp(ast::ExprSetComp { - elt, - generators, - range, - .. + elt, generators, .. }) => { self.compile_comprehension( "", @@ -9210,35 +9342,32 @@ impl<'warnings> Compiler<'warnings> { ), generators, &|compiler, collection_add_i| { - compiler.compile_comprehension_element(elt)?; - compiler.set_source_range(elt.range()); - emit!( - compiler, - Instruction::SetAdd { - i: collection_add_i.to_u32(), - } - ); + let unpack = compiler.compile_comprehension_element(elt)?; + compiler.set_source_node(elt.range(), elt.node_index()); + let i = collection_add_i.to_u32(); + if unpack { + emit!(compiler, Instruction::SetUpdate { i }); + } else { + emit!(compiler, Instruction::SetAdd { i }); + } Ok(()) }, ComprehensionType::Set, Self::contains_await(elt) || Self::generators_contain_await(generators), - *range, - elt.range(), - elt.range(), + expression_span, + self.node_span(elt.as_ref()), + self.node_span(elt.as_ref()), )?; } ast::Expr::DictComp(ast::ExprDictComp { key, value, generators, - range, .. }) => { - let Some(key) = key.as_deref() else { - self.set_source_range(*range); - return Err(self.error(CodegenErrorType::SyntaxError( - "dict unpacking cannot be used in dict comprehension".to_owned(), - ))); + let element_span = match key.as_deref() { + Some(key) => self.dict_comprehension_element_span(key, value)?, + None => self.node_span(value.as_ref()), }; self.compile_comprehension( "", @@ -9250,39 +9379,36 @@ impl<'warnings> Compiler<'warnings> { ), generators, &|compiler, collection_add_i| { - // changed evaluation order for Py38 named expression PEP 572 - compiler.compile_expression(key)?; + // Keys precede values; a missing Ruff key denotes **value. + if let Some(key) = key { + // Changed evaluation order for Py38 named expression PEP 572. + compiler.compile_expression(key)?; + } compiler.compile_expression(value)?; - compiler.set_source_range(TextRange::new( - key.range().start(), - value.range().end(), - )); - emit!( - compiler, - Instruction::MapAdd { - i: collection_add_i.to_u32(), - } - ); + compiler.restore_source_span(element_span); + let i = collection_add_i.to_u32(); + if key.is_some() { + emit!(compiler, Instruction::MapAdd { i }); + } else { + emit!(compiler, Instruction::DictUpdate { i }); + } Ok(()) }, ComprehensionType::Dict, - Self::contains_await(key) + key.as_deref().is_some_and(Self::contains_await) || Self::contains_await(value) || Self::generators_contain_await(generators), - *range, - TextRange::new(key.range().start(), value.range().end()), - key.range(), + expression_span, + element_span, + self.node_span(key.as_deref().unwrap_or(value)), )?; } ast::Expr::Generator(ast::ExprGenerator { - elt, - generators, - range, - .. + elt, generators, .. }) => { - self.compile_generator_expression(elt, generators, *range)?; + self.compile_generator_expression(elt, generators, expression_span)?; } ast::Expr::Starred(ast::ExprStarred { value, .. }) => { if self.in_annotation { @@ -9321,7 +9447,7 @@ impl<'warnings> Compiler<'warnings> { target, value, node_index: _, - range, + range: _, }) => { // Walrus targets in inlined comps should NOT be hidden from locals() if self.current_code_info().in_inlined_comp @@ -9335,10 +9461,10 @@ impl<'warnings> Compiler<'warnings> { .swap_remove(name.into_owned().as_str()); } self.compile_expression(value)?; - self.set_source_range(*range); + self.restore_source_span(expression_span); emit!(self, Instruction::Copy { i: 1 }); self.compile_store(target)?; - self.set_source_range(target.range()); + self.set_source_node(target.range(), target.node_index()); } ast::Expr::FString(fstring) => { if let Some(joined_str) = fstring.runtime_joined_str.as_ref() { @@ -9399,37 +9525,41 @@ impl<'warnings> Compiler<'warnings> { Ok(()) } - /// The called name of a `name(genexpr)` call, the shape - /// `maybe_optimize_function_call()` reserves a `skip_optimization` label - /// for. An `await` or an `async for` inside the generator does not - /// disqualify it: the inlined loop raises the same `TypeError` that - /// calling the builtin on an async generator would. + /// The called name of a synchronous `name(genexpr)` call, the shape + /// `maybe_optimize_function_call()` reserves a `skip_optimization` label for. fn cpython_genexpr_call_name<'a>( - &self, + &mut self, func: &'a ast::Expr, args: &ast::Arguments, - ) -> Option<&'a str> { + ) -> CompileResult> { let ast::Expr::Name(ast::ExprName { id, .. }) = func else { - return None; + return Ok(None); }; - let [ast::Expr::Generator(ast::ExprGenerator { .. })] = &args.args[..] else { - return None; + let [ast::Expr::Generator(ast::ExprGenerator { generators, .. })] = &args.args[..] else { + return Ok(None); }; if !args.keywords.is_empty() { - return None; + return Ok(None); } - let table = self.current_symbol_table(); - table.sub_tables.get(table.next_sub_table)?; - Some(id.as_str()) + let Some(outermost) = generators.first() else { + return Ok(None); + }; + let (comp_table, _) = self + .lookup_comprehension_symbol_table_after_skipped_nested_scopes_in_expr( + &outermost.iter, + ComprehensionType::Generator, + )?; + if comp_table.is_coroutine { + return Ok(None); + } + Ok(Some(id.as_str())) } - fn detect_builtin_generator_call( - &self, - func: &ast::Expr, - args: &ast::Arguments, - ) -> Option { - match self.cpython_genexpr_call_name(func, args)? { + fn detect_builtin_generator_call(&self, name: &str) -> Option { + match name { "tuple" => Some(BuiltinGeneratorCallKind::Tuple), + "list" => Some(BuiltinGeneratorCallKind::List), + "set" => Some(BuiltinGeneratorCallKind::Set), "all" => Some(BuiltinGeneratorCallKind::All), "any" => Some(BuiltinGeneratorCallKind::Any), _ => None, @@ -9445,11 +9575,13 @@ impl<'warnings> Compiler<'warnings> { &mut self, kind: BuiltinGeneratorCallKind, generator_expr: &ast::Expr, - loc: TextRange, + loc: CompilerSourceSpan, end: BlockIdx, ) -> CompileResult<()> { let common_constant = match kind { BuiltinGeneratorCallKind::Tuple => bytecode::CommonConstant::BuiltinTuple, + BuiltinGeneratorCallKind::List => bytecode::CommonConstant::BuiltinList, + BuiltinGeneratorCallKind::Set => bytecode::CommonConstant::BuiltinSet, BuiltinGeneratorCallKind::All => bytecode::CommonConstant::BuiltinAll, BuiltinGeneratorCallKind::Any => bytecode::CommonConstant::BuiltinAny, }; @@ -9457,7 +9589,7 @@ impl<'warnings> Compiler<'warnings> { let skip_optimization = self.new_block(); // Stack: [func] - copy function for identity check - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::Copy { i: 1 }); emit!( self, @@ -9474,48 +9606,63 @@ impl<'warnings> Compiler<'warnings> { ); emit!(self, Instruction::PopTop); - if matches!(kind, BuiltinGeneratorCallKind::Tuple) { - self.set_source_range(loc); - emit!(self, Instruction::BuildList { count: 0 }); + match kind { + BuiltinGeneratorCallKind::Tuple | BuiltinGeneratorCallKind::List => { + self.restore_source_span(loc); + emit!(self, Instruction::BuildList { count: 0 }); + } + BuiltinGeneratorCallKind::Set => { + self.restore_source_span(loc); + emit!(self, Instruction::BuildSet { count: 0 }); + } + BuiltinGeneratorCallKind::All | BuiltinGeneratorCallKind::Any => {} } let symbol_table_cursors = self.current_symbol_table_cursors(); self.compile_expression(generator_expr)?; self.set_symbol_table_cursors(symbol_table_cursors); + self.restore_source_span(loc); + emit!(self, Instruction::PushNull); let loop_block = self.new_block(); let cleanup = self.new_block(); self.use_cpython_label_block(loop_block); - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::ForIter { delta: cleanup }); match kind { - BuiltinGeneratorCallKind::Tuple => { - self.set_source_range(loc); - emit!(self, Instruction::ListAppend { i: 2 }); - self.set_source_range(loc); + BuiltinGeneratorCallKind::Tuple | BuiltinGeneratorCallKind::List => { + self.restore_source_span(loc); + emit!(self, Instruction::ListAppend { i: 3 }); + self.restore_source_span(loc); + emit!(self, PseudoInstruction::Jump { delta: loop_block }); + } + BuiltinGeneratorCallKind::Set => { + self.restore_source_span(loc); + emit!(self, Instruction::SetAdd { i: 3 }); + self.restore_source_span(loc); emit!(self, PseudoInstruction::Jump { delta: loop_block }); } BuiltinGeneratorCallKind::All => { - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::ToBool); emit!(self, Instruction::PopJumpIfTrue { delta: loop_block }); emit!(self, Instruction::PopIter); self.set_no_location(); - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_load_const(ConstantData::Boolean { value: false }); - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, PseudoInstruction::Jump { delta: end }); } BuiltinGeneratorCallKind::Any => { - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, Instruction::ToBool); emit!(self, Instruction::PopJumpIfFalse { delta: loop_block }); emit!(self, Instruction::PopIter); self.set_no_location(); - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_load_const(ConstantData::Boolean { value: true }); - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, PseudoInstruction::Jump { delta: end }); } } @@ -9527,7 +9674,7 @@ impl<'warnings> Compiler<'warnings> { self.set_no_location(); match kind { BuiltinGeneratorCallKind::Tuple => { - self.set_source_range(loc); + self.restore_source_span(loc); emit!( self, Instruction::CallIntrinsic1 { @@ -9535,16 +9682,17 @@ impl<'warnings> Compiler<'warnings> { } ); } + BuiltinGeneratorCallKind::List | BuiltinGeneratorCallKind::Set => {} BuiltinGeneratorCallKind::All => { - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_load_const(ConstantData::Boolean { value: true }); } BuiltinGeneratorCallKind::Any => { - self.set_source_range(loc); + self.restore_source_span(loc); self.emit_load_const(ConstantData::Boolean { value: false }); } } - self.set_source_range(loc); + self.restore_source_span(loc); emit!(self, PseudoInstruction::Jump { delta: end }); self.use_cpython_label_block(skip_optimization); @@ -9574,15 +9722,15 @@ impl<'warnings> Compiler<'warnings> { fn compile_method_call_arguments( &mut self, args: &ast::Arguments, - call_range: TextRange, - kw_names_range: TextRange, + call_range: CompilerSourceSpan, + kw_names_range: CompilerSourceSpan, ) -> CompileResult<()> { for arg in &args.args { self.compile_expression(arg)?; } if args.keywords.is_empty() { - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!( self, Instruction::Call { @@ -9599,11 +9747,11 @@ impl<'warnings> Compiler<'warnings> { }); self.compile_expression(&keyword.value)?; } - self.set_source_range(kw_names_range); + self.restore_source_span(kw_names_range); self.emit_load_const(ConstantData::Tuple { elements: kwarg_names, }); - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!( self, Instruction::CallKw { @@ -9616,9 +9764,14 @@ impl<'warnings> Compiler<'warnings> { fn compile_call(&mut self, func: &ast::Expr, args: &ast::Arguments) -> CompileResult<()> { // Save the call expression's source range so CALL instructions use the // call start line, not the last argument's line. - let call_range = self.current_source_range; + let call_range = self.current_source_span; self.validate_keywords(&args.keywords)?; let uses_ex_call = self.call_uses_ex_call(args); + let genexpr_call_name = if uses_ex_call { + None + } else { + self.cpython_genexpr_call_name(func, args)? + }; // Method call: obj → LOAD_ATTR_METHOD → [method, self_or_null] → args → CALL // Regular call: func → PUSH_NULL → args → CALL @@ -9626,7 +9779,7 @@ impl<'warnings> Compiler<'warnings> { if !self.can_use_cpython_method_call(value, args) { self.check_caller(func)?; self.compile_expression(func)?; - self.set_source_range(func.range()); + self.set_source_node(func.range(), func.node_index()); emit!(self, Instruction::PushNull); self.codegen_call_helper(0, args, call_range, None)?; return Ok(()); @@ -9642,18 +9795,17 @@ impl<'warnings> Compiler<'warnings> { else { unreachable!("can_optimize_super_call only accepts calls"); }; - self.load_args_for_super(&super_type, super_func.range(), value.range())?; - let attr_access_range = self.update_start_location_to_match_attr( - func.range(), - func.range(), - attr.as_str(), - ); - let method_call_range = self.update_start_location_to_match_attr( - call_range, - func.range(), + self.load_args_for_super( + &super_type, + self.node_span(super_func.as_ref()), + self.node_span(value.as_ref()), + )?; + let attr_access_range = self.update_start_span_to_match_attr( + self.node_span(func), + self.node_span(func), attr.as_str(), - ); - self.set_source_range(func.range()); + )?; + self.set_source_node(func.range(), func.node_index()); let idx = self.name(attr.as_str()); match super_type { SuperCallType::TwoArg { .. } => { @@ -9664,30 +9816,35 @@ impl<'warnings> Compiler<'warnings> { } } // NOP for line tracking at .method( line - self.set_source_range(attr_access_range); + self.restore_source_span(attr_access_range); emit!(self, Instruction::Nop); - // CALL at .method( line (not the full expression line) - self.compile_method_call_arguments(args, method_call_range, attr_access_range)?; } else { self.compile_expression(value)?; let idx = self.name(attr.as_str()); - let attr_access_range = self.update_start_location_to_match_attr( - func.range(), - func.range(), + let attr_access_range = self.update_start_span_to_match_attr( + self.node_span(func), + self.node_span(func), attr.as_str(), - ); - let method_call_range = self.update_start_location_to_match_attr( - call_range, - func.range(), - attr.as_str(), - ); - self.set_source_range(attr_access_range); + )?; + self.restore_source_span(attr_access_range); self.emit_load_attr_method(idx); - self.compile_method_call_arguments(args, method_call_range, attr_access_range)?; } - } else if let Some(kind) = (!uses_ex_call) - .then(|| self.detect_builtin_generator_call(func, args)) - .flatten() + // CALL at .method( line (not the full expression line) + self.compile_method_call_arguments( + args, + self.update_start_span_to_match_attr( + call_range, + self.node_span(func), + attr.as_str(), + )?, + self.update_start_span_to_match_attr( + self.node_span(func), + self.node_span(func), + attr.as_str(), + )?, + )?; + } else if let Some(kind) = + genexpr_call_name.and_then(|name| self.detect_builtin_generator_call(name)) { let skip_normal_call = self.new_block(); self.check_caller(func)?; @@ -9695,10 +9852,10 @@ impl<'warnings> Compiler<'warnings> { self.optimize_builtin_generator_call( kind, &args.args[0], - func.range(), + self.node_span(func), skip_normal_call, )?; - self.set_source_range(func.range()); + self.set_source_node(func.range(), func.node_index()); emit!(self, Instruction::PushNull); self.codegen_call_helper(0, args, call_range, None)?; self.use_cpython_label_block(skip_normal_call); @@ -9709,23 +9866,19 @@ impl<'warnings> Compiler<'warnings> { // `skip_normal_call`, even when `maybe_optimize_function_call()` // leaves it untargeted. let skip_normal_call = self.current_code_info().new_instr_sequence_label(); - let genexpr_call_name = (!uses_ex_call) - .then(|| self.cpython_genexpr_call_name(func, args)) - .flatten() - .is_some(); self.check_caller(func)?; self.compile_expression(func)?; - if genexpr_call_name { + if genexpr_call_name.is_some() { // CPython `maybe_optimize_function_call()` creates and uses // `skip_optimization` for every name(genexpr) shape after - // loading the function, even when the name is not all/any/tuple. + // loading the function, even when the name is not all/any/tuple/list/set. let skip_optimization = self.current_code_info().new_instr_sequence_label(); let result = self .current_code_info() .use_raw_instr_sequence_label(skip_optimization); unwrap_internal(self, result); } - self.set_source_range(func.range()); + self.set_source_node(func.range(), func.node_index()); emit!(self, Instruction::PushNull); self.codegen_call_helper(0, args, call_range, None)?; let result = self @@ -9775,7 +9928,7 @@ impl<'warnings> Compiler<'warnings> { keywords: &[ast::Keyword], begin: usize, end: usize, - call_range: TextRange, + call_range: CompilerSourceSpan, ) -> CompileResult<()> { let n = end - begin; assert!(n > 0); @@ -9790,7 +9943,7 @@ impl<'warnings> Compiler<'warnings> { for kw in &keywords[begin..end] { // Key first, then value - this is critical! - self.set_source_range(call_range); + self.restore_source_span(call_range); self.emit_load_const(ConstantData::Str { value: kw.arg.as_ref().unwrap().as_str().into(), }); @@ -9803,7 +9956,7 @@ impl<'warnings> Compiler<'warnings> { } if !big { - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!(self, Instruction::BuildMap { count: n.to_u32() }); } @@ -9817,8 +9970,8 @@ impl<'warnings> Compiler<'warnings> { &mut self, additional_positional: u32, arguments: &ast::Arguments, - call_range: TextRange, - kw_names_range: Option, + call_range: CompilerSourceSpan, + kw_names_range: Option, ) -> CompileResult<()> { self.codegen_call_helper_impl( additional_positional, @@ -9835,8 +9988,8 @@ impl<'warnings> Compiler<'warnings> { additional_positional: u32, args: &[ast::Expr], keywords: &[ast::Keyword], - call_range: TextRange, - kw_names_range: Option, + call_range: CompilerSourceSpan, + kw_names_range: Option, injected_arg: Option<&Name>, ) -> CompileResult<()> { self.validate_keywords(keywords)?; @@ -9859,7 +10012,7 @@ impl<'warnings> Compiler<'warnings> { self.compile_expression(arg)?; } let injected_count = if let Some(injected_arg) = injected_arg { - self.set_source_range(call_range); + self.restore_source_span(call_range); self.load_name(injected_arg)?; 1 } else { @@ -9877,17 +10030,17 @@ impl<'warnings> Compiler<'warnings> { } // Restore call expression range for kwnames and CALL_KW - self.set_source_range(kw_names_range.unwrap_or(call_range)); + self.restore_source_span(kw_names_range.unwrap_or(call_range)); self.emit_load_const(ConstantData::Tuple { elements: kwarg_names, }); - self.set_source_range(call_range); + self.restore_source_span(call_range); let argc = additional_positional + nelts.to_u32() + injected_count + nkwelts.to_u32(); emit!(self, Instruction::CallKw { argc }); } else { - self.set_source_range(call_range); + self.restore_source_span(call_range); let argc = additional_positional + nelts.to_u32() + injected_count; emit!(self, Instruction::Call { argc }); } @@ -9908,7 +10061,7 @@ impl<'warnings> Compiler<'warnings> { // `starunpack_helper_impl(..., BUILD_LIST, LIST_APPEND, // LIST_EXTEND, tuple=1)`, even when the only reason for the // ex-call path is too many non-starred positional arguments. - self.set_source_range(call_range); + self.restore_source_span(call_range); self.starunpack_helper_impl( args, injected_arg, @@ -9919,7 +10072,7 @@ impl<'warnings> Compiler<'warnings> { self.compile_call_function_ex_keywords(keywords, call_range)?; - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!(self, Instruction::CallFunctionEx); } @@ -9929,10 +10082,10 @@ impl<'warnings> Compiler<'warnings> { fn compile_call_function_ex_keywords( &mut self, keywords: &[ast::Keyword], - call_range: TextRange, + call_range: CompilerSourceSpan, ) -> CompileResult<()> { if keywords.is_empty() { - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!(self, Instruction::PushNull); return Ok(()); } @@ -9945,7 +10098,7 @@ impl<'warnings> Compiler<'warnings> { if nseen > 0 { self.codegen_subkwargs(keywords, i - nseen, i, call_range)?; if have_dict { - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!(self, Instruction::DictMerge { i: 1 }); } have_dict = true; @@ -9953,13 +10106,13 @@ impl<'warnings> Compiler<'warnings> { } if !have_dict { - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!(self, Instruction::BuildMap { count: 0 }); have_dict = true; } self.compile_expression(&keyword.value)?; - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!(self, Instruction::DictMerge { i: 1 }); } else { nseen += 1; @@ -9969,7 +10122,7 @@ impl<'warnings> Compiler<'warnings> { if nseen > 0 { self.codegen_subkwargs(keywords, keywords.len() - nseen, keywords.len(), call_range)?; if have_dict { - self.set_source_range(call_range); + self.restore_source_span(call_range); emit!(self, Instruction::DictMerge { i: 1 }); } have_dict = true; @@ -9979,23 +10132,20 @@ impl<'warnings> Compiler<'warnings> { Ok(()) } - fn compile_comprehension_element(&mut self, element: &ast::Expr) -> CompileResult<()> { - self.compile_expression(element).map_err(|e| { - if let CodegenErrorType::InvalidStarExpr = e.error { - self.error(CodegenErrorType::SyntaxError( - "iterable unpacking cannot be used in comprehension".to_owned(), - )) - } else { - e - } - }) + fn compile_comprehension_element(&mut self, element: &ast::Expr) -> CompileResult { + let (value, unpack) = match element { + ast::Expr::Starred(starred) => (&*starred.value, true), + _ => (element, false), + }; + self.compile_expression(value)?; + Ok(unpack) } fn compile_generator_expression( &mut self, elt: &ast::Expr, generators: &[ast::Comprehension], - range: TextRange, + range: CompilerSourceSpan, ) -> CompileResult<()> { // Check if element or generators contain async content // This makes the generator expression into an async generator @@ -10009,11 +10159,19 @@ impl<'warnings> Compiler<'warnings> { // Compile the element expression // Note: if element is an async comprehension, compile_expression // already handles awaiting it, so we don't need to await again here - compiler.compile_comprehension_element(elt)?; + let unpack = compiler.compile_comprehension_element(elt)?; + let unpack_loop = unpack.then(|| (compiler.new_block(), compiler.new_block())); + if let Some((start, end)) = unpack_loop { + // Unpacking forwards values, not send()/throw() as yield-from would. + compiler.set_source_node(elt.range(), elt.node_index()); + emit!(compiler, Instruction::GetIter { mode: 0 }); + compiler.use_cpython_label_block(start); + emit!(compiler, Instruction::ForIter { delta: end }); + } compiler.mark_generator(); if compiler.ctx.func == FunctionContext::AsyncFunction { - compiler.set_source_range(elt.range()); + compiler.set_source_node(elt.range(), elt.node_index()); emit!( compiler, Instruction::CallIntrinsic1 { @@ -10022,7 +10180,7 @@ impl<'warnings> Compiler<'warnings> { ); } // arg=0: direct yield (wrapped for async generators) - compiler.set_source_range(elt.range()); + compiler.set_source_node(elt.range(), elt.node_index()); emit!(compiler, Instruction::YieldValue { arg: 0 }); emit!( compiler, @@ -10031,14 +10189,20 @@ impl<'warnings> Compiler<'warnings> { } ); emit!(compiler, Instruction::PopTop); + if let Some((start, end)) = unpack_loop { + emit!(compiler, PseudoInstruction::Jump { delta: start }); + compiler.set_no_location(); + compiler.use_cpython_label_block(end); + compiler.emit_sync_comprehension_end_for(); + } Ok(()) }, ComprehensionType::Generator, element_contains_await, range, - elt.range(), - elt.range(), + self.node_span(elt), + self.node_span(elt), ) } @@ -10293,12 +10457,10 @@ impl<'warnings> Compiler<'warnings> { }) => { self.visit_parameter_defaults(parameters); self.visit_decorators(decorator_list); - if type_params.is_some() { - self.consume_scope(); - } else { + if type_params.is_none() { self.consume_function_annotation_scope_if_used(); - self.consume_scope(); } + self.consume_scope(); } ast::Stmt::ClassDef(ast::StmtClassDef { arguments, @@ -10606,6 +10768,48 @@ impl<'warnings> Compiler<'warnings> { Ok(()) } + /// ast.ListComp.build_container_and_load_iter: one generator, no ifs, + /// not an `async for`. The iterator is already on the stack; BUILD_LIST_FROM_ARG + /// sizes the list from its length hint. + fn listcomp_uses_build_list_from_arg( + &self, + init_collection: Option<&AnyInstruction>, + generators: &[ast::Comprehension], + ) -> bool { + self.opts.build_list_from_arg + && matches!( + init_collection, + Some(AnyInstruction::Real(Instruction::BuildList { .. })) + ) + && generators.len() == 1 + && generators[0].ifs.is_empty() + && !generators[0].is_async + } + + fn dict_comprehension_element_span( + &self, + key: &ast::Expr, + value: &ast::Expr, + ) -> CompileResult { + let key = self.node_span(key); + let value = self.node_span(value); + Ok(CompilerSourceSpan { + range: TextRange::new(key.range.start(), value.range.end().max(key.range.start())), + // codegen.c: LOCATION(elt->lineno, val->end_lineno, + // elt->col_offset, val->end_col_offset). + location: match (key.location, value.location) { + (Some(key), Some(value)) => Some(SourceLocationRange { + line: key.line, + end_line: value.end_line, + col: key.col, + end_col: value.end_col, + }), + (None, None) => None, + _ => return Err(self.mixed_location_provenance_error()), + }, + }) + } + #[expect(clippy::too_many_arguments, reason = "ignore warning for now")] fn compile_comprehension( &mut self, @@ -10615,9 +10819,9 @@ impl<'warnings> Compiler<'warnings> { compile_element: &dyn Fn(&mut Self, usize) -> CompileResult<()>, comprehension_type: ComprehensionType, element_contains_await: bool, - comprehension_range: TextRange, - element_range: TextRange, - outer_backedge_range: TextRange, + comprehension_range: CompilerSourceSpan, + element_range: CompilerSourceSpan, + outer_backedge_range: CompilerSourceSpan, ) -> CompileResult<()> { let prev_ctx = self.ctx; let has_an_async_gen = generators.iter().any(|g| g.is_async); @@ -10706,7 +10910,7 @@ impl<'warnings> Compiler<'warnings> { // Set qualname for comprehension self.set_qualname(); - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); let arg0 = self.varname(".0"); @@ -10718,13 +10922,37 @@ impl<'warnings> Compiler<'warnings> { let stop_iteration_block = if comprehension_type == ComprehensionType::Generator { let handler_block = self.new_block(); self.insert_cpython_stopiteration_setup_cleanup(handler_block); + let source = self.source_file.to_source_code(); + let iterator = ir::InstructionInfo { + instr: if outermost.is_async { + bytecode::Opcode::GetAiter.into() + } else { + bytecode::Opcode::GetIter.into() + }, + arg: OpArg::NULL, + target: BlockIdx::NULL, + location: source.source_location(outermost.iter.start(), PositionEncoding::Utf8), + end_location: source.source_location(outermost.iter.end(), PositionEncoding::Utf8), + except_handler: None, + semantic_location: self.node_span(&outermost.iter).location, + lineno_override: None, + }; + let result = self.current_code_info().insert_genexpr_prefix(iterator); + unwrap_internal(self, result); Some(handler_block) } else { None }; + // ast.ListComp.build_container_and_load_iter: one generator and no + // ifs loads the iterator first, then BUILD_LIST_FROM_ARG. + let use_build_list_from_arg = + self.listcomp_uses_build_list_from_arg(init_collection.as_ref(), generators); + // Create empty object of proper type: - if let Some(init_collection) = init_collection { + if let Some(init_collection) = init_collection + && !use_build_list_from_arg + { self._emit(init_collection, OpArg::new(0), BlockIdx::NULL) } @@ -10766,8 +10994,20 @@ impl<'warnings> Compiler<'warnings> { }; if gen_index == 0 { - // Load iterator onto stack (passed as first argument): - emit!(self, Instruction::LoadFast { var_num: arg0 }); + // Genexpr creation has already left the acquired iterator on the stack. + if comprehension_type != ComprehensionType::Generator { + emit!(self, Instruction::LoadFast { var_num: arg0 }); + // BUILD_LIST_FROM_ARG keeps the iterable on top, under which + // GET_ITER pushes the iterator and its index slot. + if use_build_list_from_arg { + emit!(self, Instruction::BuildListFromArg); + } + if generator.is_async { + emit!(self, Instruction::GetAiter); + } else { + emit!(self, Instruction::GetIter { mode: 0 }); + } + } } else { // Evaluate iterated item: self.compile_comprehension_iter(generator)?; @@ -10785,6 +11025,7 @@ impl<'warnings> Compiler<'warnings> { )?; emit!(self, PseudoInstruction::SetupFinally { delta: after_block }); emit!(self, Instruction::GetAnext); + emit!(self, Instruction::PushNull); self.emit_load_const(ConstantData::None); self.use_cpython_label_block(send_block); let _ = self.compile_yield_from_sequence(true); @@ -10792,15 +11033,14 @@ impl<'warnings> Compiler<'warnings> { // POP_BLOCK before store: only __anext__/yield_from are // protected by SetupFinally targeting END_ASYNC_FOR. emit!(self, PseudoInstruction::PopBlock); - self.compile_store(&generator.target)?; } else { - let saved_range = self.current_source_range; - self.set_source_range(generator.iter.range()); + let saved_range = self.current_source_span; + self.set_source_node(generator.iter.range(), generator.iter.node_index()); emit!(self, Instruction::ForIter { delta: after_block }); - self.set_source_range(saved_range); - self.compile_store(&generator.target)?; + self.restore_source_span(saved_range); } - real_loop_depth += 1; + self.compile_store(&generator.target)?; + real_loop_depth += if generator.is_async { 1 } else { 2 }; let backedge_range = if gen_index + 1 == generators.len() { element_range } else { @@ -10835,7 +11075,7 @@ impl<'warnings> Compiler<'warnings> { end_async_for_target, } => { self.use_cpython_label_block(if_cleanup_block); - self.set_source_range(backedge_range); + self.restore_source_span(backedge_range); emit!(self, PseudoInstruction::Jump { delta: loop_block }); if is_async { @@ -10845,7 +11085,7 @@ impl<'warnings> Compiler<'warnings> { self.use_cpython_label_block(after_block); if is_async { - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); // EndAsyncFor pops both the exception and the aiter // (handler depth is before GetANext, so aiter is at handler depth) self.emit_end_async_for(end_async_for_target); @@ -10862,7 +11102,7 @@ impl<'warnings> Compiler<'warnings> { if return_none { self.emit_return_const_no_location(ConstantData::None); } else { - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); self.emit_return_value(); } @@ -10886,21 +11126,22 @@ impl<'warnings> Compiler<'warnings> { self.ctx = prev_ctx; // Create comprehension function with closure - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); self.make_closure(code, bytecode::MakeFunctionFlags::new())?; - // Evaluate iterated item and get its iterator. - self.compile_comprehension_iter(outermost)?; + // The callee acquires the iterator; a genexpr does this eagerly before creation. + self.compile_expression(&outermost.iter)?; self.symbol_table_stack .last_mut() .expect("no current symbol table") .next_sub_table += 1; // Call just created function: - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); emit!(self, Instruction::Call { argc: 0 }); if is_async_list_set_dict_comprehension { emit!(self, Instruction::GetAwaitable { r#where: 0 }); + emit!(self, Instruction::PushNull); self.emit_load_const(ConstantData::None); let _ = self.compile_yield_from_sequence(true); } @@ -10916,7 +11157,7 @@ impl<'warnings> Compiler<'warnings> { init_collection: Option, generators: &[ast::Comprehension], compile_element: &dyn Fn(&mut Self, usize) -> CompileResult<()>, - ranges: (TextRange, TextRange, TextRange), + ranges: (CompilerSourceSpan, CompilerSourceSpan, CompilerSourceSpan), comp_source: ComprehensionSymbolSource, ) -> CompileResult<()> { let (comprehension_range, element_range, outer_backedge_range) = ranges; @@ -10924,7 +11165,7 @@ impl<'warnings> Compiler<'warnings> { // nested scopes (e.g. lambdas) whose sub_tables sit at the current // position in the parent's list. Those must be consumed before we // splice in the comprehension's own children. - self.compile_comprehension_iter(&generators[0])?; + self.compile_expression(&generators[0].iter)?; match comp_source { ComprehensionSymbolSource::Child => { self.symbol_table_stack @@ -10941,7 +11182,8 @@ impl<'warnings> Compiler<'warnings> { } let was_in_inlined_comp = self.current_code_info().in_inlined_comp; - let saved_source_range = self.current_source_range; + let saved_source_range_span = self.current_source_span; + let tweak_in_class_block = { let ct = self.current_symbol_table(); ct.typ == CompilerScope::Class && !was_in_inlined_comp @@ -11036,7 +11278,7 @@ impl<'warnings> Compiler<'warnings> { // For merged CELL variables, LoadFastAndClear saves the cell object from // the merged slot, and MAKE_CELL creates a new empty cell in-place. // MAKE_CELL has no stack effect (operates only on fastlocals). - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); let mut total_stack_items: usize = 0; for name in &pushed_locals { let var_num = self.varname(name); @@ -11086,8 +11328,14 @@ impl<'warnings> Compiler<'warnings> { None }; - // Step 4: Create the collection (list/set/dict) - if let Some(init_collection) = init_collection { + // Step 4: Create the collection (list/set/dict). + // BUILD_LIST_FROM_ARG pops the iterator, pushes the list, then + // the iterator: the same stack as BUILD_LIST 0; SWAP 2. + let use_build_list_from_arg = + self.listcomp_uses_build_list_from_arg(init_collection.as_ref(), generators); + if use_build_list_from_arg { + emit!(self, Instruction::BuildListFromArg); + } else if let Some(init_collection) = init_collection { self._emit(init_collection, OpArg::new(0), BlockIdx::NULL); // SWAP to get iterator on top emit!(self, Instruction::Swap { i: 2 }); @@ -11133,6 +11381,15 @@ impl<'warnings> Compiler<'warnings> { if i > 0 { self.compile_comprehension_iter(generator)?; + } else { + let saved_range = self.current_source_span; + self.set_source_node(generator.iter.range(), generator.iter.node_index()); + if generator.is_async { + emit!(self, Instruction::GetAiter); + } else { + emit!(self, Instruction::GetIter { mode: 0 }); + } + self.restore_source_span(saved_range); } self.use_cpython_label_block(loop_block); @@ -11148,21 +11405,21 @@ impl<'warnings> Compiler<'warnings> { )?; emit!(self, PseudoInstruction::SetupFinally { delta: after_block }); emit!(self, Instruction::GetAnext); + emit!(self, Instruction::PushNull); self.emit_load_const(ConstantData::None); self.use_cpython_label_block(send_block); let _ = self.compile_yield_from_sequence(true); end_async_for_target = send_block; emit!(self, PseudoInstruction::PopBlock); - self.compile_store(&generator.target)?; } else { - let saved_range = self.current_source_range; - self.set_source_range(generator.iter.range()); + let saved_range = self.current_source_span; + self.set_source_node(generator.iter.range(), generator.iter.node_index()); emit!(self, Instruction::ForIter { delta: after_block }); - self.set_source_range(saved_range); - self.compile_store(&generator.target)?; + self.restore_source_span(saved_range); } + self.compile_store(&generator.target)?; - real_loop_depth += 1; + real_loop_depth += if generator.is_async { 1 } else { 2 }; let backedge_range = if i + 1 == generators.len() { element_range } else { @@ -11199,7 +11456,7 @@ impl<'warnings> Compiler<'warnings> { end_async_for_target, } => { self.use_cpython_label_block(if_cleanup_block); - self.set_source_range(backedge_range); + self.restore_source_span(backedge_range); emit!(self, PseudoInstruction::Jump { delta: loop_block }); if is_async { @@ -11212,7 +11469,7 @@ impl<'warnings> Compiler<'warnings> { self.use_cpython_label_block(after_block); if is_async { - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); self.emit_end_async_for(end_async_for_target); } else { self.emit_sync_comprehension_end_for(); @@ -11225,7 +11482,7 @@ impl<'warnings> Compiler<'warnings> { } // Step 8: Clean up - restore saved locals (and cell values) - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); if let Some(cleanup_block) = cleanup_block { emit!(self, PseudoInstruction::PopBlock); self.set_no_location(); @@ -11250,7 +11507,7 @@ impl<'warnings> Compiler<'warnings> { self.set_no_location(); // Restore locals and cell values - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); emit!( self, Instruction::Swap { @@ -11258,7 +11515,7 @@ impl<'warnings> Compiler<'warnings> { } ); for name in pushed_locals.iter().rev() { - let var_num = self.varname(name).as_u32(); + let var_num = self.varname(name); emit!(self, PseudoInstruction::StoreFastMaybeNull { var_num }); } // Re-raise the exception @@ -11267,7 +11524,7 @@ impl<'warnings> Compiler<'warnings> { // Normal end path self.use_cpython_label_block(end_block); - self.set_source_range(comprehension_range); + self.restore_source_span(comprehension_range); } // SWAP result to TOS (above saved values) @@ -11282,10 +11539,10 @@ impl<'warnings> Compiler<'warnings> { // Restore saved locals (StoreFast restores the saved cell object for merged cells) for name in pushed_locals.iter().rev() { - let var_num = self.varname(name).as_u32(); + let var_num = self.varname(name); emit!(self, PseudoInstruction::StoreFastMaybeNull { var_num }); } - self.set_source_range(saved_source_range); + self.restore_source_span(saved_source_range_span); Ok(()) })(); @@ -11307,41 +11564,15 @@ impl<'warnings> Compiler<'warnings> { fn compile_future_features(&mut self, features: &[ast::Alias]) -> Result<(), CodegenError> { for feature in features { - let future_feature = feature.name.as_str().try_into().map_err(|name| { - self.error_ranged(CodegenErrorType::InvalidFutureFeature(name), feature.range) + let flags = preprocess::future_alias_flags(feature.name.as_str()).map_err(|kind| { + self.error_ranged(future_feature_error_type(kind), feature.range) })?; - - match future_feature { - FutureFeature::Braces => { - return Err( - self.error_ranged(CodegenErrorType::InvalidFutureBraces, feature.range) - ); - } - FutureFeature::Annotations => { - self.future_annotations = true; - self.future_features - .insert(bytecode::CodeFlags::FUTURE_ANNOTATIONS); - self.current_code_info() - .flags - .insert(bytecode::CodeFlags::FUTURE_ANNOTATIONS); - } - FutureFeature::BarryAsFLUFL => { - self.future_features - .insert(bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL); - self.current_code_info() - .flags - .insert(bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL); - } - FutureFeature::AbsoluteImport - | FutureFeature::Division - | FutureFeature::GeneratorStop - | FutureFeature::Generators - | FutureFeature::NestedScopes - | FutureFeature::PrintFunction - | FutureFeature::UnicodeLiterals - | FutureFeature::WithStatement => { - // Python 3 features. They are already implemented by default. - } + if flags.contains(bytecode::CodeFlags::FUTURE_ANNOTATIONS) { + self.future_annotations = true; + } + if !flags.is_empty() { + self.future_features |= flags; + self.current_code_info().flags |= flags; } } Ok(()) @@ -11390,9 +11621,6 @@ impl<'warnings> Compiler<'warnings> { } fn _emit>(&mut self, instr: I, arg: OpArg, target: BlockIdx) { - if self.do_not_emit_bytecode > 0 { - return; - } let instr = instr.into(); let opcode = AnyOpcode::from(instr); debug_assert!( @@ -11407,7 +11635,7 @@ impl<'warnings> Compiler<'warnings> { target == BlockIdx::NULL || instr.has_target(), "CPython codegen_addop_j only accepts HAS_TARGET opcodes" ); - let range = self.current_source_range; + let range = self.current_source_span.range; let source = self.source_file.to_source_code(); let location = source.source_location(range.start(), PositionEncoding::Utf8); let end_location = source.source_location(range.end(), PositionEncoding::Utf8); @@ -11419,6 +11647,7 @@ impl<'warnings> Compiler<'warnings> { location, end_location, except_handler, + semantic_location: self.current_source_span.location, lineno_override: None, }); } @@ -11430,9 +11659,6 @@ impl<'warnings> Compiler<'warnings> { instr: I, target_label: ir::InstructionSequenceLabel, ) { - if self.do_not_emit_bytecode > 0 { - return; - } let instr = instr.into(); debug_assert!( instr.has_target(), @@ -11442,22 +11668,20 @@ impl<'warnings> Compiler<'warnings> { !instr.is_assembler(), "CPython codegen_addop_j must not emit assembler-only opcodes" ); - let range = self.current_source_range; + let range = self.current_source_span.range; let source = self.source_file.to_source_code(); let location = source.source_location(range.start(), PositionEncoding::Utf8); let end_location = source.source_location(range.end(), PositionEncoding::Utf8); - let target = self - .current_code_info() - .block_for_instr_sequence_label(target_label); self.maybe_start_cpython_cfg_addop_block(); self.push_emitted_instruction_with_target_label( ir::InstructionInfo { instr, arg: OpArg::NULL, - target, + target: BlockIdx::NULL, location, end_location, except_handler: None, + semantic_location: self.current_source_span.location, lineno_override: None, }, target_label, @@ -11480,42 +11704,11 @@ impl<'warnings> Compiler<'warnings> { self.set_no_location(); } - /// CPython `codegen_wrap_in_stopiteration_handler()` inserts - /// `SETUP_CLEANUP` into the instruction sequence at index 0 with - /// `_PyInstructionSequence_InsertInstruction()`. Generator and cell/free - /// prefixes are inserted later by `flowgraph.c::insert_prefix_instructions()`. + /// The SETUP_CLEANUP part of `codegen_wrap_in_stopiteration_handler`. fn insert_cpython_stopiteration_setup_cleanup(&mut self, handler_block: BlockIdx) { - let code = self.current_code_info(); - let entry = code - .blocks - .first_mut() - .expect("code unit must have an entry block"); - debug_assert!( - entry - .used_instructions() - .first() - .is_some_and(|info| match info.instr.real() { - Some(Instruction::Resume { context }) => matches!( - context.get(info.arg).location(), - oparg::ResumeLocation::AtFuncStart - ), - _ => false, - }), - "scope entry must start with a function-start RESUME" - ); - debug_assert!( - !entry.used_instructions().iter().any(|info| matches!( - info.instr.real(), - Some( - Instruction::ReturnGenerator - | Instruction::MakeCell { .. } - | Instruction::CopyFreeVars { .. } - ) - )), - "CPython inserts StopIteration cleanup before CFG prefix instructions" - ); - - let result = code.insert_start_setup_cleanup(handler_block); + let result = self + .current_code_info() + .insert_start_setup_cleanup(handler_block); unwrap_internal(self, result); } @@ -11960,12 +12153,12 @@ impl<'warnings> Compiler<'warnings> { &mut self, expr: &ast::Expr, ) -> CompileResult> { - // CPython 3.14 ast_preprocess.c::fold_const_match_patterns() + // CPython ast_preprocess.c::fold_const_match_patterns() // folds only the constant forms needed by match patterns before // codegen_pattern_value()/codegen_pattern_mapping_key() visit them. Ok(match expr { ast::Expr::UnaryOp(ast::ExprUnaryOp { - op: ast::UnaryOp::USub, + op: op @ (ast::UnaryOp::UAdd | ast::UnaryOp::USub), operand, .. }) => { @@ -11973,7 +12166,11 @@ impl<'warnings> Compiler<'warnings> { else { return Ok(None); }; - Self::try_negate_match_pattern_constant(constant) + if *op == ast::UnaryOp::USub { + Self::try_negate_match_pattern_constant(constant) + } else { + Some(constant) + } } ast::Expr::BinOp(ast::ExprBinOp { left, op, right, .. @@ -11998,7 +12195,7 @@ impl<'warnings> Compiler<'warnings> { return Ok(Some(constant)); } let ast::Expr::UnaryOp(ast::ExprUnaryOp { - op: ast::UnaryOp::USub, + op: op @ (ast::UnaryOp::UAdd | ast::UnaryOp::USub), operand, .. }) = expr @@ -12008,7 +12205,11 @@ impl<'warnings> Compiler<'warnings> { let Some(constant) = self.try_compile_match_pattern_real_constant(operand)? else { return Ok(None); }; - Ok(Self::try_negate_match_pattern_constant(constant)) + Ok(if *op == ast::UnaryOp::USub { + Self::try_negate_match_pattern_constant(constant) + } else { + Some(constant) + }) } fn try_compile_match_pattern_real_constant( @@ -12057,7 +12258,7 @@ impl<'warnings> Compiler<'warnings> { fn compile_match_pattern_expr(&mut self, expr: &ast::Expr) -> CompileResult<()> { if let Some(constant) = self.try_fold_match_pattern_const_expr(expr)? { - self.set_source_range(expr.range()); + self.set_source_node(expr.range(), expr.node_index()); self.emit_load_const(constant); } else { self.compile_expression(expr)?; @@ -12135,49 +12336,49 @@ impl<'warnings> Compiler<'warnings> { /// Emit LOAD_ATTR for attribute access (method=false). /// Encodes: (name_idx << 1) | 0 - fn emit_load_attr(&mut self, name_idx: u32) { + fn emit_load_attr(&mut self, name_idx: oparg::NameIdx) { let encoded = LoadAttr::new(name_idx, false); self.emit_arg(encoded, |namei| Instruction::LoadAttr { namei }) } /// Emit LOAD_ATTR with method flag set (for method calls). /// Encodes: (name_idx << 1) | 1 - fn emit_load_attr_method(&mut self, name_idx: u32) { + fn emit_load_attr_method(&mut self, name_idx: oparg::NameIdx) { let encoded = LoadAttr::new(name_idx, true); self.emit_arg(encoded, |namei| Instruction::LoadAttr { namei }) } /// Emit LOAD_GLOBAL. /// Encodes: (name_idx << 1) | push_null_bit - fn emit_load_global(&mut self, name_idx: u32, push_null: bool) { - let encoded = (name_idx << 1) | u32::from(push_null); + fn emit_load_global(&mut self, name_idx: oparg::NameIdx, push_null: bool) { + let encoded = oparg::LoadGlobal::new(name_idx, push_null); self.emit_arg(encoded, |namei| Instruction::LoadGlobal { namei }); } /// Emit LOAD_SUPER_ATTR for 2-arg super().attr access. /// Encodes: (name_idx << 2) | 0b10 (method=0, class=1) - fn emit_load_super_attr(&mut self, name_idx: u32) { + fn emit_load_super_attr(&mut self, name_idx: oparg::NameIdx) { let encoded = LoadSuperAttr::new(name_idx, false, true); self.emit_arg(encoded, |namei| Instruction::LoadSuperAttr { namei }) } /// Emit LOAD_SUPER_ATTR for 2-arg super().method() call. /// Encodes: (name_idx << 2) | 0b11 (method=1, class=1) - fn emit_load_super_method(&mut self, name_idx: u32) { + fn emit_load_super_method(&mut self, name_idx: oparg::NameIdx) { let encoded = LoadSuperAttr::new(name_idx, true, true); self.emit_arg(encoded, |namei| Instruction::LoadSuperAttr { namei }) } /// Emit LOAD_SUPER_ATTR for 0-arg super().attr access. /// Encodes: (name_idx << 2) | 0b00 (method=0, class=0) - fn emit_load_zero_super_attr(&mut self, name_idx: u32) { + fn emit_load_zero_super_attr(&mut self, name_idx: oparg::NameIdx) { let encoded = LoadSuperAttr::new(name_idx, false, false); self.emit_arg(encoded, |namei| Instruction::LoadSuperAttr { namei }) } /// Emit LOAD_SUPER_ATTR for 0-arg super().method() call. /// Encodes: (name_idx << 2) | 0b01 (method=1, class=0) - fn emit_load_zero_super_method(&mut self, name_idx: u32) { + fn emit_load_zero_super_method(&mut self, name_idx: oparg::NameIdx) { let encoded = LoadSuperAttr::new(name_idx, true, false); self.emit_arg(encoded, |namei| Instruction::LoadSuperAttr { namei }) } @@ -12214,44 +12415,17 @@ impl<'warnings> Compiler<'warnings> { /// This handles unwinding through With blocks and exception handlers. fn compile_break_continue( &mut self, - range: ruff_text_size::TextRange, + span: CompilerSourceSpan, is_break: bool, ) -> CompileResult<()> { - if self.do_not_emit_bytecode > 0 { - // Still validate that we're inside a loop even in dead code - let code = self.current_code_info(); - let mut found_loop = false; - for i in (0..code.fblock.len()).rev() { - match code.fblock[i].fb_type { - FBlockType::WhileLoop | FBlockType::ForLoop => { - found_loop = true; - break; - } - FBlockType::ExceptionGroupHandler => { - return Err(self.error_ranged( - CodegenErrorType::BreakContinueReturnInExceptStar, - range, - )); - } - _ => {} - } - } - if !found_loop { - if is_break { - return Err(self.error_ranged(CodegenErrorType::InvalidBreak, range)); - } - return Err(self.error_ranged(CodegenErrorType::InvalidContinue, range)); - } - return Ok(()); - } - - let prev_source_range = self.current_source_range; - self.set_source_range(range); + let range = span.range; + let prev_source_range = self.current_source_span; + self.restore_source_span(span); emit!(self, Instruction::Nop); let (mut unwind_loc, loop_fblock) = self.unwind_fblock_stack_with_loop(false, true)?; let Some(loop_fblock) = loop_fblock else { - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); if is_break { return Err(self.error_ranged(CodegenErrorType::InvalidBreak, range)); } @@ -12274,7 +12448,7 @@ impl<'warnings> Compiler<'warnings> { loop_fblock.fb_block }; let jump_is_artificial = if let Some(loc) = unwind_loc { - self.set_source_range(loc); + self.restore_source_span(loc); false } else { true @@ -12288,7 +12462,7 @@ impl<'warnings> Compiler<'warnings> { if jump_is_artificial { self.set_no_location(); } - self.set_source_range(prev_source_range); + self.restore_source_span(prev_source_range); Ok(()) } @@ -12354,7 +12528,7 @@ impl<'warnings> Compiler<'warnings> { && code.blocks[block.idx()].next == BlockIdx::NULL; if !can_reuse_current { - let result = code.mark_cpython_cfg_label(block); + let result = code.instr_sequence_label_for_block(block); unwrap_internal(self, result); self.switch_to_block(block); return; @@ -12367,7 +12541,9 @@ impl<'warnings> Compiler<'warnings> { debug_assert_eq!(target.start_depth, ir::START_DEPTH_UNSET); debug_assert!(!target.cold); } - let result = code.mark_cpython_cfg_label(cur); + // Reserve the canonical block's sequence label before aliasing this + // target. The real CFG will get its labels from the sequence offsets. + let result = code.instr_sequence_label_for_block(cur); unwrap_internal(self, result); let result = self @@ -12441,8 +12617,76 @@ impl<'warnings> Compiler<'warnings> { code.current_block = block; } + fn node_span(&self, node: &(impl Ranged + HasNodeIndex)) -> CompilerSourceSpan { + CompilerSourceSpan { + range: node.range(), + location: self + .ast_locations + .as_ref() + .and_then(|locations| node_location(locations, node)), + } + } + + fn set_source_node(&mut self, range: TextRange, index: &ast::AtomicNodeIndex) { + self.current_source_span = CompilerSourceSpan { + range, + location: index + .load() + .as_u32() + .and_then(|id| self.ast_locations.as_ref()?.get(id)), + }; + } + + #[cfg(test)] const fn set_source_range(&mut self, range: TextRange) { - self.current_source_range = range; + self.current_source_span = CompilerSourceSpan::parsed(range); + } + + const fn restore_source_span(&mut self, span: CompilerSourceSpan) { + self.current_source_span = span; + } + + fn mixed_location_provenance_error(&self) -> CodegenError { + CodegenError { + error: CodegenErrorType::MixedAstLocationProvenance, + location: None, + end_location: None, + source_path: self.source_file.name().to_owned(), + } + } + + fn update_start_span_to_match_attr( + &self, + loc: CompilerSourceSpan, + attribute: CompilerSourceSpan, + name: &str, + ) -> CompileResult { + let range = self.update_start_location_to_match_attr(loc.range, attribute.range, name); + let location = match (loc.location, attribute.location) { + (Some(mut loc), Some(attribute)) => { + // CPython codegen.c update_start_location_to_match_attr. + if loc.line != attribute.end_line { + loc.line = attribute.end_line; + let length = + i32::try_from(name.chars().count()).expect("validated attribute name"); + if length <= attribute.end_col { + loc.col = attribute.end_col - length; + } else { + loc.col = -1; + loc.end_col = -1; + } + loc.end_line = loc.line.max(loc.end_line); + if loc.line == loc.end_line { + loc.end_col = loc.col.max(loc.end_col); + } + } + Some(loc) + } + // The parser-only path has no explicit semantic coordinates. + (None, None) => None, + _ => return Err(self.mixed_location_provenance_error()), + }; + Ok(CompilerSourceSpan { range, location }) } fn update_start_location_to_match_attr( @@ -12462,7 +12706,8 @@ impl<'warnings> Compiler<'warnings> { if attr_len > attr_range.len() { return TextRange::new(loc_range.start(), loc_range.end()); } - TextRange::new(attr_range.end() - attr_len, loc_range.end()) + let start = attr_range.end() - attr_len; + TextRange::new(start, loc_range.end().max(start)) } fn source_line_start_range(&self, lineno: u32) -> TextRange { @@ -12472,15 +12717,30 @@ impl<'warnings> Compiler<'warnings> { TextRange::new(start, start) } - fn module_start_location(&self, body: &[ast::Stmt]) -> TextRange { - body.first() - .map_or_else(|| self.source_line_start_range(1), Ranged::range) + fn module_start_location(&self, body: &[ast::Stmt]) -> CompilerSourceSpan { + body.first().map_or_else( + || CompilerSourceSpan::parsed(self.source_line_start_range(1)), + |node| self.node_span(node), + ) + } + + fn docstring_span(&self, body: &[ast::Stmt]) -> Option { + let ast::Stmt::Expr(statement) = body.first()? else { + return None; + }; + Some(self.node_span(statement.value.as_ref())) } fn get_source_line_number(&mut self) -> OneIndexed { + if let Some(location) = self.current_source_span.location + && let Ok(line) = usize::try_from(location.line) + && let Some(line) = OneIndexed::new(line) + { + return line; + } self.source_file .to_source_code() - .line_index(self.current_source_range.start()) + .line_index(self.current_source_span.range.start()) } fn mark_generator(&mut self) { @@ -12521,7 +12781,11 @@ impl<'warnings> Compiler<'warnings> { ast::Expr::Await(_) => self.found = true, ast::Expr::ListComp(ast::ExprListComp { generators, .. }) | ast::Expr::SetComp(ast::ExprSetComp { generators, .. }) - | ast::Expr::DictComp(ast::ExprDictComp { generators, .. }) + if generators.iter().any(|generator| generator.is_async) => + { + self.found = true + } + ast::Expr::DictComp(ast::ExprDictComp { generators, .. }) if generators.iter().any(|generator| generator.is_async) => { self.found = true @@ -12555,17 +12819,17 @@ impl<'warnings> Compiler<'warnings> { } fn compile_expr_fstring(&mut self, fstring: &ast::ExprFString) -> CompileResult<()> { - let fstring_range = fstring.range; - let fstring = fstring.value.as_slice(); - if self.count_fstring_parts(fstring) > STACK_USE_GUIDELINE { - return self.compile_fstring_parts_joined(fstring, fstring_range); + let fstring_range = self.node_span(fstring); + let value = &fstring.value; + if self.count_fstring_parts(value) > STACK_USE_GUIDELINE { + return self.compile_fstring_parts_joined(value, fstring_range); } let mut element_count = 0; let mut pending_literal = None; let mut pending_literal_range = None; let mut pending_literal_no_location = false; - for part in fstring { + for part in value { self.compile_fstring_part_into( part, &mut pending_literal, @@ -12590,13 +12854,13 @@ impl<'warnings> Compiler<'warnings> { fstring: &ast::ExprFString, values: &[ast::Expr], ) -> CompileResult<()> { - let range = fstring.range; + let span = self.node_span(fstring); let value_count: u32 = values .len() .try_into() .expect("JoinedStr value count overflowed"); if value_count > STACK_USE_GUIDELINE { - self.set_source_range(range); + self.restore_source_span(span); self.emit_load_const(ConstantData::Str { value: Wtf8Buf::new(), }); @@ -12605,20 +12869,20 @@ impl<'warnings> Compiler<'warnings> { emit!(self, Instruction::BuildList { count: 0 }); for value in values { self.compile_expression(value)?; - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::ListAppend { i: 1 }); } - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::Call { argc: 1 }); } else { for value in values { self.compile_expression(value)?; } if value_count > 1 { - self.set_source_range(range); + self.restore_source_span(span); emit!(self, Instruction::BuildString { count: value_count }); } else if value_count == 0 { - self.set_source_range(range); + self.restore_source_span(span); self.emit_load_const(ConstantData::Str { value: Wtf8Buf::new(), }); @@ -12629,10 +12893,10 @@ impl<'warnings> Compiler<'warnings> { fn compile_fstring_parts_joined( &mut self, - fstring: &[ast::FStringPart], - fstring_range: TextRange, + fstring: &ast::FStringValue, + fstring_range: CompilerSourceSpan, ) -> CompileResult<()> { - self.set_source_range(fstring_range); + self.restore_source_span(fstring_range); self.emit_load_const(ConstantData::Str { value: Wtf8Buf::new(), }); @@ -12666,28 +12930,32 @@ impl<'warnings> Compiler<'warnings> { fn compile_fstring_part_into( &mut self, - part: &ast::FStringPart, + part: ast::FStringPartRef<'_>, pending_literal: &mut Option, - pending_literal_range: &mut Option, + pending_literal_range: &mut Option, pending_literal_no_location: &mut bool, element_count: &mut u32, - join_append_range: Option, + join_append_range: Option, ) -> CompileResult<()> { match part { - ast::FStringPart::Literal(string) => { + ast::FStringPartRef::Literal(string) => { let value = string_literal_part_value(&self.source_file, string); if pending_literal.is_none() { - *pending_literal_range = Some(string.range); - *pending_literal_no_location = string.range == TextRange::default(); + *pending_literal_range = Some(self.node_span(string)); + *pending_literal_no_location = self.node_span(string).is_artificial(); *pending_literal = Some(value); } else if let Some(pending) = pending_literal.as_mut() { - Self::extend_pending_literal_range(pending_literal_range, string.range); - *pending_literal_no_location &= string.range == TextRange::default(); + Self::extend_pending_literal_span( + pending_literal_range, + self.node_span(string), + ) + .map_err(|error| self.error(error))?; + *pending_literal_no_location &= self.node_span(string).is_artificial(); pending.push_wtf8(value.as_ref()); } Ok(()) } - ast::FStringPart::FString(fstring) => self.compile_fstring_elements_into( + ast::FStringPartRef::FString(fstring) => self.compile_fstring_elements_into( fstring.flags, &fstring.elements, pending_literal, @@ -12701,10 +12969,10 @@ impl<'warnings> Compiler<'warnings> { fn finish_fstring( &mut self, mut pending_literal: Option, - mut pending_literal_range: Option, + mut pending_literal_range: Option, mut pending_literal_no_location: bool, mut element_count: u32, - fstring_range: Option, + fstring_range: Option, ) { self.emit_pending_fstring_literal( &mut pending_literal, @@ -12716,14 +12984,14 @@ impl<'warnings> Compiler<'warnings> { if element_count == 0 { if let Some(fstring_range) = fstring_range { - self.set_source_range(fstring_range); + self.restore_source_span(fstring_range); } self.emit_load_const(ConstantData::Str { value: Wtf8Buf::new(), }); } else if element_count > 1 { if let Some(fstring_range) = fstring_range { - self.set_source_range(fstring_range); + self.restore_source_span(fstring_range); } emit!( self, @@ -12737,10 +13005,10 @@ impl<'warnings> Compiler<'warnings> { fn finish_fstring_join( &mut self, mut pending_literal: Option, - mut pending_literal_range: Option, + mut pending_literal_range: Option, mut pending_literal_no_location: bool, mut element_count: u32, - fstring_range: TextRange, + fstring_range: CompilerSourceSpan, ) { self.emit_pending_fstring_literal( &mut pending_literal, @@ -12749,17 +13017,17 @@ impl<'warnings> Compiler<'warnings> { &mut element_count, Some(fstring_range), ); - self.set_source_range(fstring_range); + self.restore_source_span(fstring_range); emit!(self, Instruction::Call { argc: 1 }); } fn emit_pending_fstring_literal( &mut self, pending_literal: &mut Option, - pending_literal_range: &mut Option, + pending_literal_range: &mut Option, pending_literal_no_location: &mut bool, element_count: &mut u32, - join_append_range: Option, + join_append_range: Option, ) { let Some(value) = pending_literal.take() else { return; @@ -12776,7 +13044,7 @@ impl<'warnings> Compiler<'warnings> { } if let Some(range) = range { - self.set_source_range(range); + self.restore_source_span(range); } self.emit_load_const(ConstantData::Str { value }); if no_location { @@ -12784,24 +13052,40 @@ impl<'warnings> Compiler<'warnings> { } *element_count += 1; if let Some(join_append_range) = join_append_range { - self.set_source_range(join_append_range); + self.restore_source_span(join_append_range); emit!(self, Instruction::ListAppend { i: 1 }); } } - fn extend_pending_literal_range(pending: &mut Option, range: TextRange) { + fn extend_pending_literal_span( + pending: &mut Option, + span: CompilerSourceSpan, + ) -> Result<(), CodegenErrorType> { let Some(existing) = pending else { - *pending = Some(range); - return; + *pending = Some(span); + return Ok(()); }; - if *existing == TextRange::default() { - *existing = range; - } else if range != TextRange::default() { - *existing = TextRange::new(existing.start(), range.end()); + // Check before changing either range or artificial-location state. + // Valid VM AST inputs map every literal; parser inputs map none. + if existing.location.is_some() != span.location.is_some() { + return Err(CodegenErrorType::MixedAstLocationProvenance); + } + if existing.is_artificial() { + *existing = span; + } else if !span.is_artificial() { + existing.range = TextRange::new( + existing.range.start(), + span.range.end().max(existing.range.start()), + ); + if let (Some(first), Some(last)) = (&mut existing.location, span.location) { + first.end_line = last.end_line; + first.end_col = last.end_col; + } } + Ok(()) } - fn count_fstring_parts(&self, fstring: &[ast::FStringPart]) -> u32 { + fn count_fstring_parts(&self, fstring: &ast::FStringValue) -> u32 { let mut element_count = 0; let mut pending_literal = None; for part in fstring { @@ -12813,12 +13097,12 @@ impl<'warnings> Compiler<'warnings> { fn count_fstring_part_into( &self, - part: &ast::FStringPart, + part: ast::FStringPartRef<'_>, pending_literal: &mut Option, element_count: &mut u32, ) { match part { - ast::FStringPart::Literal(string) => { + ast::FStringPartRef::Literal(string) => { let value = string_literal_part_value(&self.source_file, string); if let Some(pending) = pending_literal.as_mut() { pending.push_wtf8(value.as_ref()); @@ -12826,7 +13110,7 @@ impl<'warnings> Compiler<'warnings> { *pending_literal = Some(value); } } - ast::FStringPart::FString(fstring) => self.count_fstring_elements_into( + ast::FStringPartRef::FString(fstring) => self.count_fstring_elements_into( fstring.flags, &fstring.elements, pending_literal, @@ -12854,16 +13138,16 @@ impl<'warnings> Compiler<'warnings> { &mut self, flags: ast::FStringFlags, fstring_elements: &ast::InterpolatedStringElements, - fstring_range: Option, + fstring_range: Option, ) -> CompileResult<()> { if self.count_fstring_elements(flags, fstring_elements) > STACK_USE_GUIDELINE { - let fstring_range = fstring_range.unwrap_or(self.current_source_range); + let fstring_range = fstring_range.unwrap_or(self.current_source_span); return self.compile_fstring_elements_joined(flags, fstring_elements, fstring_range); } let mut element_count = 0; let mut pending_literal: Option = None; - let mut pending_literal_range: Option = None; + let mut pending_literal_range: Option = None; let mut pending_literal_no_location = false; self.compile_fstring_elements_into( flags, @@ -12887,9 +13171,9 @@ impl<'warnings> Compiler<'warnings> { &mut self, flags: ast::FStringFlags, fstring_elements: &ast::InterpolatedStringElements, - fstring_range: TextRange, + fstring_range: CompilerSourceSpan, ) -> CompileResult<()> { - self.set_source_range(fstring_range); + self.restore_source_span(fstring_range); self.emit_load_const(ConstantData::Str { value: Wtf8Buf::new(), }); @@ -12899,7 +13183,7 @@ impl<'warnings> Compiler<'warnings> { let mut element_count = 0; let mut pending_literal: Option = None; - let mut pending_literal_range: Option = None; + let mut pending_literal_range: Option = None; let mut pending_literal_no_location = false; self.compile_fstring_elements_into( flags, @@ -12919,6 +13203,14 @@ impl<'warnings> Compiler<'warnings> { Ok(()) } + fn format_spec_span(&self, spec: &ast::InterpolatedStringFormatSpec) -> CompilerSourceSpan { + let mut span = self.node_span(spec); + if span.location.is_none() { + span.range = self.cpython_format_spec_range(spec.range); + } + span + } + fn cpython_format_spec_range(&self, range: TextRange) -> TextRange { let start = range.start().to_usize(); if start == 0 { @@ -12937,9 +13229,9 @@ impl<'warnings> Compiler<'warnings> { flags: ast::FStringFlags, fstring_elements: &ast::InterpolatedStringElements, pending_literal: &mut Option, - pending_literal_meta: (&mut Option, &mut bool), + pending_literal_meta: (&mut Option, &mut bool), element_count: &mut u32, - join_append_range: Option, + join_append_range: Option, ) -> CompileResult<()> { let (pending_literal_range, pending_literal_no_location) = pending_literal_meta; for element in fstring_elements { @@ -12948,12 +13240,16 @@ impl<'warnings> Compiler<'warnings> { let value = interpolated_string_literal_value(&self.source_file, string, flags.into()); if pending_literal.is_none() { - *pending_literal_range = Some(string.range); - *pending_literal_no_location = string.range == TextRange::default(); + *pending_literal_range = Some(self.node_span(string)); + *pending_literal_no_location = self.node_span(string).is_artificial(); *pending_literal = Some(value); } else if let Some(pending) = pending_literal.as_mut() { - Self::extend_pending_literal_range(pending_literal_range, string.range); - *pending_literal_no_location &= string.range == TextRange::default(); + Self::extend_pending_literal_span( + pending_literal_range, + self.node_span(string), + ) + .map_err(|error| self.error(error))?; + *pending_literal_no_location &= self.node_span(string).is_artificial(); pending.push_wtf8(value.as_ref()); } } @@ -12972,7 +13268,11 @@ impl<'warnings> Compiler<'warnings> { fstring_expr.expression.range(), ); let text: Wtf8Buf = text.into(); - Self::extend_pending_literal_range(pending_literal_range, debug_text_range); + Self::extend_pending_literal_span( + pending_literal_range, + CompilerSourceSpan::parsed(debug_text_range), + ) + .map_err(|error| self.error(error))?; *pending_literal_no_location = false; pending_literal .get_or_insert_with(Wtf8Buf::new) @@ -12998,13 +13298,13 @@ impl<'warnings> Compiler<'warnings> { self.compile_expression(&fstring_expr.expression)?; - let formatted_value_range = fstring_expr.range; + let formatted_value_span = self.node_span(fstring_expr); match conversion { ConvertValueOparg::None => {} ConvertValueOparg::Str | ConvertValueOparg::Repr | ConvertValueOparg::Ascii => { - self.set_source_range(formatted_value_range); + self.restore_source_span(formatted_value_span); emit!(self, Instruction::ConvertValue { oparg: conversion }) } } @@ -13014,24 +13314,23 @@ impl<'warnings> Compiler<'warnings> { { self.compile_expression(format_spec)?; - self.set_source_range(formatted_value_range); + self.restore_source_span(formatted_value_span); emit!(self, Instruction::FormatWithSpec); } else { match &fstring_expr.format_spec { Some(format_spec) => { - let format_spec_range = - self.cpython_format_spec_range(format_spec.range); + let format_spec_range = self.format_spec_span(format_spec); self.compile_fstring_elements( flags, &format_spec.elements, Some(format_spec_range), )?; - self.set_source_range(formatted_value_range); + self.restore_source_span(formatted_value_span); emit!(self, Instruction::FormatWithSpec); } None => { - self.set_source_range(formatted_value_range); + self.restore_source_span(formatted_value_span); emit!(self, Instruction::FormatSimple); } } @@ -13039,7 +13338,7 @@ impl<'warnings> Compiler<'warnings> { *element_count += 1; if let Some(join_append_range) = join_append_range { - self.set_source_range(join_append_range); + self.restore_source_span(join_append_range); emit!(self, Instruction::ListAppend { i: 1 }); } } @@ -13110,7 +13409,7 @@ impl<'warnings> Compiler<'warnings> { // strings tuple first, then evaluating interpolations left-to-right. let tstring_value = &expr_tstring.value; - let mut all_strings: Vec<(Wtf8Buf, TextRange)> = Vec::new(); + let mut all_strings: Vec<(Wtf8Buf, CompilerSourceSpan)> = Vec::new(); let mut current_string = Wtf8Buf::new(); let mut current_string_range = None; let mut interp_count: u32 = 0; @@ -13122,13 +13421,14 @@ impl<'warnings> Compiler<'warnings> { &mut current_string, &mut current_string_range, &mut interp_count, - expr_tstring.range, - ); + self.node_span(expr_tstring), + ) + .map_err(|error| self.error(error))?; } all_strings.push(( core::mem::take(&mut current_string), - current_string_range.unwrap_or(expr_tstring.range), + current_string_range.unwrap_or_else(|| self.node_span(expr_tstring)), )); let string_count: u32 = all_strings @@ -13136,10 +13436,10 @@ impl<'warnings> Compiler<'warnings> { .try_into() .expect("t-string string count overflowed"); for (s, range) in &all_strings { - self.set_source_range(*range); + self.restore_source_span(*range); self.emit_load_const(ConstantData::Str { value: s.clone() }); } - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); emit!( self, Instruction::BuildTuple { @@ -13151,14 +13451,14 @@ impl<'warnings> Compiler<'warnings> { self.compile_tstring_interpolations(tstring)?; } - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); emit!( self, Instruction::BuildTuple { count: interp_count } ); - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); emit!(self, Instruction::BuildTemplate); Ok(()) @@ -13174,7 +13474,7 @@ impl<'warnings> Compiler<'warnings> { for value in values { if self.runtime_template_value_interpolation(value).is_some() { if last_was_interpolation { - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); self.emit_load_const(ConstantData::Str { value: Wtf8Buf::new(), }); @@ -13188,13 +13488,13 @@ impl<'warnings> Compiler<'warnings> { } } if last_was_interpolation { - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); self.emit_load_const(ConstantData::Str { value: Wtf8Buf::new(), }); strings_len += 1; } - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); emit!(self, Instruction::BuildTuple { count: strings_len }); let mut interpolations_len = 0; @@ -13205,14 +13505,14 @@ impl<'warnings> Compiler<'warnings> { interpolations_len += 1; } } - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); emit!( self, Instruction::BuildTuple { count: interpolations_len } ); - self.set_source_range(expr_tstring.range); + self.set_source_node(expr_tstring.range, &expr_tstring.node_index); emit!(self, Instruction::BuildTemplate); Ok(()) } @@ -13252,7 +13552,7 @@ impl<'warnings> Compiler<'warnings> { ) -> CompileResult<()> { let (str, format_spec) = interpolation; self.compile_expression(&interp.expression)?; - self.set_source_range(interp.range); + self.set_source_node(interp.range, &interp.node_index); self.emit_load_const(ast_constant_value_to_constant_data(str.clone())); let conversion = match interp.conversion { @@ -13268,7 +13568,7 @@ impl<'warnings> Compiler<'warnings> { } let format = 2 | (conversion << 2) | u32::from(has_format_spec); - self.set_source_range(interp.range); + self.set_source_node(interp.range, &interp.node_index); emit!(self, Instruction::BuildInterpolation { format }); Ok(()) } @@ -13292,19 +13592,22 @@ impl<'warnings> Compiler<'warnings> { fn collect_tstring_strings( &self, tstring: &ast::TString, - strings: &mut Vec<(Wtf8Buf, TextRange)>, + strings: &mut Vec<(Wtf8Buf, CompilerSourceSpan)>, current_string: &mut Wtf8Buf, - current_string_range: &mut Option, + current_string_range: &mut Option, interp_count: &mut u32, - template_range: TextRange, - ) { + template_range: CompilerSourceSpan, + ) -> Result<(), CodegenErrorType> { for element in &tstring.elements { match element { ast::InterpolatedStringElement::Literal(lit) => { if current_string_range.is_none() { - *current_string_range = Some(lit.range); + *current_string_range = Some(self.node_span(lit)); } else { - Self::extend_pending_literal_range(current_string_range, lit.range); + Self::extend_pending_literal_span( + current_string_range, + self.node_span(lit), + )?; } current_string.push_wtf8(&interpolated_string_literal_value( &self.source_file, @@ -13320,28 +13623,25 @@ impl<'warnings> Compiler<'warnings> { interp.expression.range(), ); if current_string_range.is_none() { - *current_string_range = Some(debug_text_range); + *current_string_range = + Some(CompilerSourceSpan::parsed(debug_text_range)); } else { - Self::extend_pending_literal_range( + Self::extend_pending_literal_span( current_string_range, - debug_text_range, - ); + CompilerSourceSpan::parsed(debug_text_range), + )?; } current_string.push_str(&text); - strings.push(( - core::mem::take(current_string), - current_string_range.take().unwrap_or(template_range), - )); - } else { - strings.push(( - core::mem::take(current_string), - current_string_range.take().unwrap_or(template_range), - )); } + strings.push(( + core::mem::take(current_string), + current_string_range.take().unwrap_or(template_range), + )); *interp_count += 1; } } } + Ok(()) } fn compile_tstring_interpolations(&mut self, tstring: &ast::TString) -> CompileResult<()> { @@ -13361,19 +13661,14 @@ impl<'warnings> Compiler<'warnings> { self.compile_expression(&interp.expression)?; - let expr_range = interp.expression.range(); - let expr_source = if interp.range.start() < expr_range.start() - && interp.range.end() >= expr_range.end() - { - let after_brace = interp.range.start() + TextSize::new(1); - self.source_file - .source_text() - .slice(TextRange::new(after_brace, expr_range.end())) - } else { - self.source_file.source_text().slice(expr_range) - } - .to_string(); - self.set_source_range(interp.range); + let expr_source = crate::interpolation_expression_text(&self.source_file, interp) + .unwrap_or_else(|| { + self.source_file + .source_text() + .slice(interp.expression.range()) + .to_owned() + }); + self.set_source_node(interp.range, &interp.node_index); self.emit_load_const(ConstantData::Str { value: expr_source.into(), }); @@ -13391,7 +13686,7 @@ impl<'warnings> Compiler<'warnings> { let has_format_spec = interp.format_spec.is_some(); if let Some(format_spec) = &interp.format_spec { - let format_spec_range = self.cpython_format_spec_range(format_spec.range); + let format_spec_range = self.format_spec_span(format_spec); self.compile_fstring_elements( ast::FStringFlags::empty(), &format_spec.elements, @@ -13402,7 +13697,7 @@ impl<'warnings> Compiler<'warnings> { // CPython keeps bit 1 set in BUILD_INTERPOLATION's oparg and uses // bit 0 for the optional format spec. let format = 2 | (conversion << 2) | u32::from(has_format_spec); - self.set_source_range(interp.range); + self.set_source_node(interp.range, &interp.node_index); emit!(self, Instruction::BuildInterpolation { format }); } @@ -13972,7 +14267,7 @@ mod tests { arguments: ast::Arguments { node_index: ast::AtomicNodeIndex::NONE, range: TextRange::default(), - args: Box::default(), + args: Default::default(), keywords: Default::default(), runtime_args: None, runtime_bases: None, @@ -14120,7 +14415,7 @@ mod tests { arguments: ast::Arguments { node_index: ast::AtomicNodeIndex::NONE, range: TextRange::default(), - args: Box::default(), + args: Default::default(), keywords: Default::default(), runtime_args: None, runtime_bases: None, @@ -14196,12 +14491,14 @@ mod tests { let message = first_ast_constant_warning(ast::Expr::Compare(ast::ExprCompare { node_index: ast::AtomicNodeIndex::NONE, range: TextRange::default(), - left: Box::new(left), ops: Box::new([ast::CmpOp::Is]), - comparators: Box::new([ast::Expr::NoneLiteral(ast::ExprNoneLiteral { - node_index: ast::AtomicNodeIndex::NONE, - range: TextRange::default(), - })]), + operands: Box::new([ + left, + ast::Expr::NoneLiteral(ast::ExprNoneLiteral { + node_index: ast::AtomicNodeIndex::NONE, + range: TextRange::default(), + }), + ]), runtime_comparators: None, })); assert!( @@ -14618,66 +14915,6 @@ match x: ); } - #[test] - fn empty_module_implicit_return_inherits_resume_location_like_cpython() { - let code = compile_exec(""); - // codegen emits the implicit LOAD_CONST/RETURN_VALUE with - // NO_LOCATION, then flowgraph.c::propagate_line_numbers() propagates - // the module RESUME location, whose line is 0. - assert_eq!(code.linetable.as_ref(), &[0xf2, 0x03, 0x01, 0x01, 0x01]); - } - - #[test] - fn module_docstring_load_uses_doc_location_like_cpython() { - let code = compile_exec( - "\ -\"doc\" -x = 1 -", - ); - - // codegen_body() emits the docstring LOAD_CONST at the - // string expression location, then emits STORE_NAME __doc__ with - // NO_LOCATION. - assert_eq!( - code.linetable.as_ref(), - &[ - 0xf0, 0x03, 0x01, 0x01, 0x01, 0xd9, 0x00, 0x05, 0xd8, 0x04, 0x05, 0x82, 0x01, - ], - ); - } - - #[test] - fn redundant_nop_location_copies_full_location_like_cpython() { - let code = compile_exec( - "\ -def f(x, y, z): - while x: - if y: - pass - elif z: - if y < 0: - return y - if z: - y = y + 1 - elif y: - return 1 - return -1 -", - ); - let f = find_code(&code, "f").expect("missing function code"); - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdf, 0x0a, 0x0b, 0xdf, 0x0b, 0x0c, 0xd9, 0x0c, 0x10, 0xdf, 0x0d, 0x0e, - 0xd8, 0x0f, 0x10, 0x90, 0x31, 0x8c, 0x75, 0xd8, 0x17, 0x18, 0x90, 0x08, 0xdf, 0x0f, - 0x10, 0xd8, 0x14, 0x15, 0x98, 0x01, 0x95, 0x45, 0x92, 0x01, 0xf1, 0x03, 0x00, 0x10, - 0x11, 0xe7, 0x0d, 0x0e, 0x89, 0x51, 0xd9, 0x13, 0x14, 0xd8, 0x0b, 0x0d, 0x80, 0x49, - ], - "CPython basicblock_remove_redundant_nops() copies the full NOP location into a following no-location jump" - ); - } - fn scan_program_symbol_table(source: &str) -> SymbolTable { let source_file = SourceFileBuilder::new("source_path", source).finish(); let parsed = ruff_python_parser::parse( @@ -14899,11 +15136,12 @@ def f(support, func, value): .expect("missing CPython-style false jump for if/break"); assert!( matches!( - ops.get(cond..cond + 5), + ops.get(cond..cond + 6), Some([ Instruction::PopJumpIfFalse { .. }, Instruction::NotTaken, Instruction::PopTop, + Instruction::PopTop, Instruction::JumpForward { .. }, Instruction::JumpBackward { .. }, ]) @@ -14947,7 +15185,7 @@ def f(input): Instruction::CompareOp { .. }, Instruction::PopJumpIfFalse { .. }, Instruction::NotTaken, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue, Instruction::JumpBackward { .. }, ] @@ -15184,7 +15422,7 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "fail" + f.names[load_attr.name_idx()].as_str() == "fail" } _ => false, }) @@ -15576,8 +15814,7 @@ def f(self, os, tempfile, oldmode): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "assertEqual" + f.names[load_attr.name_idx()].as_str() == "assertEqual" } _ => false, }) @@ -15786,7 +16023,7 @@ def f(self): ) && matches!( window[1].op, Instruction::LoadAttr { namei } - if f.names[usize::try_from(namei.get(attr_arg).name_idx()).unwrap()] + if f.names[namei.get(attr_arg).name_idx()] == "assertFalse" ) && matches!( window[2].op, @@ -15844,7 +16081,7 @@ def f(self): ) && matches!( window[1].op, Instruction::LoadAttr { namei } - if f.names[usize::try_from(namei.get(attr_arg).name_idx()).unwrap()] + if f.names[namei.get(attr_arg).name_idx()] == "assertFalse" ) && matches!( window[2].op, @@ -15984,11 +16221,11 @@ def f(self): ) && matches!( window[1].op, Instruction::LoadAttr { namei } - if f.names[usize::try_from(namei.get(attr_arg).name_idx()).unwrap()] + if f.names[namei.get(attr_arg).name_idx()] == "close" ) && matches!(window[2].op, Instruction::Call { .. }) && matches!(window[3].op, Instruction::PopTop) - && matches!(window[4].op, Instruction::LoadConst { .. }) + && matches!(window[4].op, Instruction::LoadCommonConstant { .. }) && matches!(window[5].op, Instruction::ReturnValue) }) .unwrap_or_else(|| { @@ -16110,7 +16347,7 @@ def f(self, cm): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "close" + f.names[load_attr.name_idx()].as_str() == "close" } _ => false, }) @@ -16149,7 +16386,7 @@ def f(self, g): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "close" + f.names[load_attr.name_idx()].as_str() == "close" } _ => false, }) @@ -16236,7 +16473,7 @@ def f(self, x): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "use" + f.names[load_attr.name_idx()].as_str() == "use" } _ => false, }) @@ -16397,7 +16634,7 @@ def f(self, block=True): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == name + f.names[load_attr.name_idx()].as_str() == name } _ => false, }) @@ -16517,7 +16754,7 @@ def f(buffer, pos, last_char): Instruction::NotTaken, Instruction::JumpBackward { .. } | Instruction::JumpBackwardNoInterrupt { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreFast { .. }, ] ) @@ -16532,7 +16769,7 @@ def f(buffer, pos, last_char): Instruction::CompareOp { .. }, Instruction::PopJumpIfFalse { .. }, Instruction::NotTaken, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -16585,86 +16822,6 @@ def f(buffer, pos, last_char): }) } - #[test] - fn annotated_multiline_function_body_keeps_def_firstlineno_like_cpython() { - let code = compile_exec( - r#" -a = 1 -def f( - x: a, -): ... -"#, - ); - let f = find_code(&code, "f").expect("missing f code"); - // CPython 3.14 codegen_function() computes firstlineno from the - // FunctionDef before compiling annotations, then passes it to - // codegen_function_body(). - assert_eq!(f.linetable.as_ref(), &[0x80, 0x00, 0xe1, 0x03, 0x06]); - } - - #[test] - fn annotation_scope_return_uses_function_location_like_cpython() { - let code = compile_exec( - r#" -def g(): - def f(x: not (int is int), /): ... -"#, - ); - let g = find_code(&code, "g").expect("missing g code"); - let annotate = find_code(g, "__annotate__").expect("missing annotation code"); - // CPython 3.14 codegen_function_annotations() receives LOC(function) - // and uses it for the annotation closure's BUILD_MAP/RETURN_VALUE and - // for the parent MAKE_FUNCTION annotate sequence. - assert_eq!(g.linetable.as_ref(), &[0x80, 0x00, 0xdf, 0x04, 0x26]); - assert_eq!( - annotate.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd7, 0x04, 0x26, 0xd1, 0x04, 0x26, 0x94, 0x23, 0x9c, 0x13, 0xd0, 0x0d, - 0x1d, 0xd1, 0x04, 0x26, - ], - ); - } - - #[test] - fn starred_arg_annotation_unpack_uses_function_location_like_cpython() { - let code = compile_exec("def f(*args: *Ts): pass\n"); - let annotate = find_code(&code, "__annotate__").expect("missing annotation code"); - - // codegen_argannotation() visits `Ts` at the annotation - // expression location, then emits UNPACK_SEQUENCE at LOC(function). - assert_eq!( - annotate.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd7, 0x00, 0x17, 0xd1, 0x00, 0x17, 0x8c, 0x62, 0xd3, 0x00, 0x17 - ], - ); - } - - #[test] - fn module_deferred_annotations_use_start_location_like_cpython() { - let code = compile_exec( - "\ -import os -X: int -Y: str -", - ); - let annotate = find_code(&code, "__annotate__").expect("missing __annotate__ code"); - - // compile.c::start_location() passes the first module - // statement location into _PyCodegen_Module(), and - // codegen_process_deferred_annotations() uses that loc for annotation - // scope setup, BUILD_MAP, STORE_SUBSCR, and RETURN_VALUE. - assert_eq!( - annotate.linetable.as_ref(), - &[ - 0x80, 0x00, 0x87, 0x09, 0x81, 0x09, 0xdf, 0x00, 0x06, 0x82, 0x06, 0x84, 0x33, 0x81, - 0x06, 0xf1, 0x03, 0x00, 0x01, 0x0a, 0xe7, 0x00, 0x06, 0x82, 0x06, 0x84, 0x33, 0x81, - 0x06, 0xf2, 0x05, 0x00, 0x01, 0x0a, - ] - ); - } - #[test] fn super_method_call_kw_names_use_attribute_location_like_cpython() { let code = compile_exec( @@ -16915,83 +17072,6 @@ def continues(xs): } } - #[test] - fn not_compare_uses_unary_location_like_cpython() { - let code = compile_exec( - "\ -def f(self, other): - return not self == other -", - ); - let f = find_code(&code, "f").expect("missing f code"); - - // CPython 3.14 parses the Compare inside UnaryOp(Not) with the - // UnaryOp start location, so codegen_compare() emits COMPARE_OP at - // the full "not self == other" range before flowgraph folds TO_BOOL. - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x0f, 0x13, 0xd2, 0x0b, 0x1c, 0xd0, 0x04, 0x1c, - ] - ); - } - - #[test] - fn not_chained_compare_keeps_compare_location_like_cpython() { - let code = compile_exec( - "\ -def f(c): - return not (b\" \" <= c <= b\"~\") -", - ); - let f = find_code(&code, "f").expect("missing f code"); - - // CPython's single Compare under UnaryOp(Not) includes "not" in the - // Compare range, but chained comparisons keep their inner range for - // compare scaffolding and only use the UnaryOp range for TO_BOOL and - // UNARY_NOT. - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x10, 0x14, 0x98, 0x01, 0xd7, 0x10, 0x21, 0xd4, 0x10, 0x21, 0x98, - 0x54, 0xd1, 0x10, 0x21, 0xd4, 0x0b, 0x22, 0xd0, 0x04, 0x22, 0xd1, 0x10, 0x21, 0xd4, - 0x0b, 0x22, 0xd0, 0x04, 0x22, - ] - ); - } - - #[test] - fn type_param_scopes_use_cpython_locations() { - let code = compile_exec("type BoundGenericAlias[X: int] = set[X]\n"); - let type_params = find_code(&code, "") - .expect("missing generic parameters code"); - let bound = find_direct_child_code(type_params, "X").expect("missing X bound code"); - let alias = - find_direct_child_code(type_params, "BoundGenericAlias").expect("missing alias code"); - - // CPython 3.14 codegen_type_params() emits type-parameter ops at - // LOC(typeparam), bound/default evaluator ops at LOC(e), and type alias - // body plumbing at LOC(s). - assert_eq!( - type_params.linetable.as_ref(), - &[ - 0xf8, 0x80, 0x00, 0xd0, 0x00, 0x27, 0x90, 0x76, 0x9b, 0x23, 0x93, 0x76, 0xd7, 0x00, - 0x27, 0xd1, 0x00, 0x27, - ], - ); - assert_eq!( - bound.linetable.as_ref(), - &[0x80, 0x00, 0x9f, 0x23, 0x9e, 0x23] - ); - assert_eq!( - alias.linetable.as_ref(), - &[ - 0xf8, 0x80, 0x00, 0xd7, 0x00, 0x27, 0xd0, 0x00, 0x27, 0xa4, 0x13, 0xa0, 0x51, 0xa5, - 0x16, 0xd0, 0x00, 0x27, - ], - ); - } - #[test] fn typealias_value_scope_has_single_return_like_cpython() { let code = compile_exec("type Alias = int\n"); @@ -17008,23 +17088,6 @@ def f(c): ); } - #[test] - fn generic_typealias_wrapper_return_uses_alias_location_like_cpython() { - let code = compile_exec("type A[T] = T\n"); - let type_params = - find_code(&code, "").expect("missing type params code"); - - // codegen_typealias() assembles the generic-parameters - // wrapper with addNone=0 after codegen_typealias_body() leaves the type - // alias object on the stack. The final RETURN_VALUE keeps LOC(type alias). - assert_eq!( - type_params.linetable.as_ref(), - &[ - 0xf8, 0x80, 0x00, 0x80, 0x0d, 0x84, 0x71, 0x87, 0x0d, 0x81, 0x0d - ], - ); - } - #[test] fn type_param_bound_scope_has_single_return_like_cpython() { let code = compile_exec("type Alias[T: int] = T\n"); @@ -17060,22 +17123,78 @@ def f(c): } #[test] - fn generic_function_annotation_scope_uses_function_location_like_cpython() { - let code = compile_exec("def f[T](x: int): ...\n"); - let type_params = - find_code(&code, "").expect("missing type params code"); - let annotate = - find_direct_child_code(type_params, "__annotate__").expect("missing annotation code"); + fn class_body_with_table_lines_past_source_text() { + let source = "class C:\n pass\n"; + let source_file = SourceFileBuilder::new("source_path", source).finish(); + let parsed = ruff_python_parser::parse( + source_file.source_text(), + ruff_python_parser::Mode::Module.into(), + ) + .unwrap(); + let ast = parsed.into_syntax(); + let mut locations = AstLocations::default(); + { + let ast::Mod::Module(module) = &ast else { + panic!("expected module"); + }; + let ast::Stmt::ClassDef(class_def) = &module.body[0] else { + panic!("expected ClassDef"); + }; + let ast::Stmt::Pass(pass) = &class_def.body[0] else { + panic!("expected Pass"); + }; - // CPython 3.14 passes LOC(function) into codegen_function_annotations(), - // even when the annotation closure is emitted inside the generic - // parameters scope after codegen_type_params(). - assert_eq!( - annotate.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd7, 0x00, 0x15, 0xd1, 0x00, 0x15, 0x8c, 0x43, 0xd1, 0x00, 0x15, - ], - ); + let module_id = locations + .allocate(Some(SourceLocationRange { + line: 1000, + end_line: 1001, + col: 0, + end_col: 8, + })) + .unwrap(); + module.node_index.set(ast::NodeIndex::from(module_id)); + let class_id = locations + .allocate(Some(SourceLocationRange { + line: 1000, + end_line: 1001, + col: 0, + end_col: 8, + })) + .unwrap(); + class_def.node_index.set(ast::NodeIndex::from(class_id)); + let name_id = locations + .allocate(Some(SourceLocationRange { + line: 1000, + end_line: 1000, + col: 6, + end_col: 7, + })) + .unwrap(); + class_def.name.node_index.set(ast::NodeIndex::from(name_id)); + let pass_id = locations + .allocate(Some(SourceLocationRange { + line: 1001, + end_line: 1001, + col: 4, + end_col: 8, + })) + .unwrap(); + pass.node_index.set(ast::NodeIndex::from(pass_id)); + } + + let code = compile_ast_with_syntax_warning_handler( + AstInput { + ast, + source_file, + locations: Some(locations), + }, + Mode::Exec, + CompileOpts::default(), + None, + ) + .expect("class body with table lines past the source text should compile"); + let class_code = find_code(&code, "C").expect("missing class code"); + assert_eq!(class_code.first_line_number.unwrap().get(), 1000); } #[test] @@ -17095,27 +17214,6 @@ def f[T](): pass assert_eq!(type_params.first_line_number.unwrap().get(), 2); } - #[test] - fn generic_class_type_params_store_uses_class_location_like_cpython() { - let code = compile_exec( - "\ -def outer(): - class X[T]: ... -", - ); - let type_params = - find_code(&code, "").expect("missing type params code"); - - // CPython 3.14 codegen_class() calls codegen_type_params(), then stores - // the resulting .type_params cell with codegen_nameop(c, LOC(class), ...). - assert_eq!( - type_params.linetable.as_ref(), - &[ - 0xf8, 0x80, 0x00, 0x8c, 0x41, 0x87, 0x4f, 0x87, 0x4f, 0x80, 0x4f, - ] - ); - } - #[test] fn generic_class_wrapper_ops_use_class_location_like_cpython() { let code = compile_exec( @@ -17129,9 +17227,9 @@ def f(): let wrapper_positions: Vec<_> = f .instructions .iter() - .filter(|unit| !matches!(unit.op, Instruction::Resume { .. })) + .zip(&f.locations) + .filter(|(unit, _)| !matches!(unit.op, Instruction::Resume { .. } | Instruction::Cache)) .take(4) - .zip(f.locations.iter().filter(|_| true).skip(1)) .map(|(unit, (location, end_location))| { ( unit.op, @@ -17341,48 +17439,6 @@ class C[T]: pass } #[test] - fn class_deferred_annotations_use_class_body_location_like_cpython() { - let code = compile_exec( - r#" -class C: - "doc" - x: int -"#, - ); - let class_code = find_code(&code, "C").expect("missing class code"); - - // CPython 3.14 calls codegen_body(c, loc, ...) from codegen_class_body() - // with LOCATION(firstlineno, firstlineno, 0, 0). Deferred annotation - // closure setup and following artificial class tail inherit that class - // body location, not the annotation expression location. - assert_eq!( - class_code.linetable.as_ref(), - &[ - 0xf8, 0x87, 0x00, 0x80, 0x00, 0xd9, 0x04, 0x09, 0xf7, 0x03, 0x00, 0x01, 0x01, 0x83, - 0x00, - ], - ); - } - - #[test] - fn future_annotation_string_uses_annotation_location_like_cpython() { - let code = compile_exec("from __future__ import annotations\nclass Bar:\n foo: Foo\n"); - let class_code = find_code(&code, "Bar").expect("missing class code"); - - // CPython 3.14 codegen_annassign() calls codegen_visit_annexpr(), - // which emits the stringized annotation at LOC(annotation), then emits - // the __annotations__ store sequence at LOC(AnnAssign). - assert_eq!( - class_code.linetable.as_ref(), - &[0x87, 0x00, 0xd8, 0x09, 0x0c, 0x87, 0x48] - ); - } - - #[test] - #[expect( - clippy::literal_string_with_formatting_args, - reason = "the literal is the expected t-string annotation" - )] fn future_tstring_annotation_preserves_interpolation_source_like_cpython() { let code = compile_exec( "from __future__ import annotations\nx: t'{a + b}'\ny: t'{ a + b }'\nz: f'{a + b =}'\nu: t'{a + b =}'\nv: t'{a + b =:>10}'\np: t'{(a)}'\nq: t'{((a))!r}'\nr: t'{ ((a)) = !r:>10}'\ns: t'{(a)=}'\nt: t'{a == b = }'\na1: t'''{a= # x=y\n}'''\na2: t'''{a # x=y\n}'''\na3: t'''{(a # x=y\n)}'''\na4: t'''{a # x=y\n!r}'''\na5: t'''{a # x=y\n:>10}'''\na6: t'''{'#'}'''\na7: t'''{('#', a) # c=d\n}'''\n", @@ -17405,61 +17461,26 @@ class C: annotation_strings, [ "t'{a + b}'", - "t'{ a + b}'", + "t'{ a + b }'", "f'a + b ={a + b!r}'", - "t'a + b ={a + b!r}'", - "t'a + b ={a + b:>10}'", + "t'a + b ={a + b !r}'", + "t'a + b ={a + b :>10}'", "t'{(a)}'", "t'{((a))!r}'", - "t' ((a)) = { ((a))!r:>10}'", + "t' ((a)) = { ((a)) !r:>10}'", "t'(a)={(a)!r}'", - "t'a == b = {a == b!r}'", + "t'a == b = {a == b !r}'", "t'a= \\n{a!r}'", - "t'{a}'", + "t'{a \\n}'", "t'{(a \\n)}'", - "t'{a!r}'", - "t'{a:>10}'", + "t'{a \\n!r}'", + "t'{a \\n:>10}'", "t\"{'#'}\"", - "t\"{('#', a)}\"", + "t\"{('#', a) \\n}\"", ] ); } - #[test] - fn lambda_dict_literal_ops_use_dict_location_like_cpython() { - let code = compile_exec( - "\ -f = lambda data: {'x': data} -g = lambda i: {**i} -", - ); - let f = find_code(&code, "").expect("missing f lambda code"); - let g = code - .constants - .iter() - .filter_map(|constant| { - if let ConstantData::Code { code } = constant { - (code.obj_name == "").then_some(code.as_ref()) - } else { - None - } - }) - .nth(1) - .expect("missing g lambda code"); - - // CPython 3.14 codegen_dict()/codegen_subdict() uses LOC(dict) for - // BUILD_MAP, MAP_ADD, and DICT_UPDATE, so the lambda RETURN_VALUE - // inherits the full dict literal location after compiling its body. - assert_eq!( - f.linetable.as_ref(), - &[0x80, 0x00, 0x90, 0x23, 0x90, 0x74, 0x91, 0x1b] - ); - assert_eq!( - g.linetable.as_ref(), - &[0x80, 0x00, 0x88, 0x65, 0x90, 0x11, 0x89, 0x65] - ); - } - #[test] fn dict_unpacking_large_regular_run_uses_subdict_chunks_like_cpython() { let pairs = (0..17) @@ -17699,11 +17720,10 @@ def f(self, payload): function.constants.as_ref(), [ ConstantData::Str { value: doc }, - ConstantData::None, ConstantData::Str { value: message }, ] if doc.as_ref() == "doc" && message.as_ref() == "bad" ), - "CPython registers None from the pre-folded `is None` comparison before the else-body string" + "CPython 3.15 keeps the docstring and else-body string in co_consts; None uses the common-constant table" ); } @@ -17784,64 +17804,78 @@ def f(self): } #[test] - fn or_return_not_taken_before_jump_target_splits_exception_table_like_cpython() { - let code = compile_exec_with_options( - r#" -def f(self, maintype): - if maintype != "multipart" or not self.is_multipart(): - return - yield 1 -"#, - CompileOpts::default(), - ); - let f = find_code(&code, "f").expect("missing f"); - let not_taken_before_return = u32::try_from( - f.instructions - .windows(3) - .position(|window| { - matches!( - window, - [ - CodeUnit { - op: Instruction::NotTaken, - .. - }, - CodeUnit { - op: Instruction::LoadConst { .. }, - .. - }, - CodeUnit { - op: Instruction::ReturnValue, - .. - }, - ] - ) - }) - .expect("missing NOT_TAKEN before return"), - ) - .unwrap(); - let return_load = not_taken_before_return + 1; - let entries = bytecode::decode_exception_table(&f.exceptiontable); + fn listcomp_build_list_from_arg_option() { + let has = |source: &str, build_list_from_arg: bool| { + let code = compile_exec_with_options( + source, + CompileOpts { + build_list_from_arg, + ..CompileOpts::default() + }, + ); + let f = find_code(&code, "f").expect("missing f"); + ( + f.instructions + .iter() + .any(|unit| matches!(unit.op, Instruction::BuildListFromArg)), + f.instructions + .iter() + .any(|unit| matches!(unit.op, Instruction::BuildList { .. })), + ) + }; + let single = "def f(n):\n return [i for i in range(n)]\n"; + // (BUILD_LIST_FROM_ARG, BUILD_LIST) + assert_eq!(has(single, false), (false, true)); + assert_eq!(has(single, true), (true, false)); + for source in [ + "def f(xs):\n return [x for x in xs if x]\n", + "def f(xss):\n return [x for xs in xss for x in xs]\n", + "async def f(xs):\n return [x async for x in xs]\n", + ] { + assert_eq!(has(source, true), (false, true), "source={source:?}"); + } - assert!( - entries.iter().all(|entry| { - not_taken_before_return < entry.start || not_taken_before_return >= entry.end - }), - "CPython normalize_jumps() can leave a NOT_TAKEN before a separately labelled jump target outside the generator StopIteration range; entries={entries:?}, instructions={:?}", - f.instructions + // Non-inlined path: a type alias in a class body can see class scope, + // so the list comprehension is compiled as its own code object. + let code = compile_exec_with_options( + "\ +class C: + type A = [i for i in range(3)] +", + CompileOpts { + build_list_from_arg: true, + ..CompileOpts::default() + }, ); + let listcomp = find_code(&code, "").expect("missing non-inlined listcomp"); + let build_idx = listcomp + .instructions + .iter() + .position(|unit| matches!(unit.op, Instruction::BuildListFromArg)) + .expect("missing BUILD_LIST_FROM_ARG"); + let next = listcomp.instructions[build_idx + 1..] + .iter() + .find(|unit| !matches!(unit.op, Instruction::Cache)) + .expect("missing instruction after BUILD_LIST_FROM_ARG"); assert!( - entries - .iter() - .any(|entry| entry.start <= return_load && return_load < entry.end), - "the return block after that NOT_TAKEN is still protected by the StopIteration handler; entries={entries:?}, instructions={:?}", - f.instructions + matches!(next.op, Instruction::GetIter { .. }), + "BUILD_LIST_FROM_ARG must precede GET_ITER, got instructions={:?}", + listcomp.instructions ); } #[test] - fn loop_break_condition_splits_exception_table_like_cpython() { - let code = compile_exec_with_options( + fn generator_conditional_jumps_keep_stopiteration_handler() { + // CPython 3.15.2 keeps the generator's StopIteration handler around + // both branches of the normalized conditional, including NOT_TAKEN + // and any inserted JUMP_BACKWARD. + for source in [ + r#" +def f(self, maintype): + if maintype != "multipart" or not self.is_multipart(): + return + yield 1 +"#, r#" def f(start, items): if start: @@ -17850,120 +17884,12 @@ def f(start, items): break yield 1 "#, - CompileOpts::default(), - ); - let f = find_code(&code, "f").expect("missing f"); - let break_jump = u32::try_from( - f.instructions - .windows(3) - .position(|window| { - matches!( - window, - [ - CodeUnit { - op: Instruction::PopJumpIfTrue { .. }, - .. - }, - CodeUnit { - op: Instruction::Cache, - .. - }, - CodeUnit { - op: Instruction::NotTaken, - .. - }, - ] - ) || matches!( - window, - [ - CodeUnit { - op: Instruction::PopJumpIfTrue { .. }, - .. - }, - CodeUnit { - op: Instruction::NotTaken, - .. - }, - CodeUnit { - op: Instruction::JumpBackward { .. }, - .. - }, - ] - ) - }) - .expect("missing loop break conditional jump"), - ) - .unwrap(); - let entries = bytecode::decode_exception_table(&f.exceptiontable); - - assert!( - entries - .iter() - .all(|entry| break_jump < entry.start || break_jump >= entry.end), - "CPython normalize_jumps() leaves the loop-break conditional before the synthetic NOT_TAKEN/JUMP_BACKWARD block outside the StopIteration table; break_jump={break_jump}, entries={entries:?}, instructions={:?}", - f.instructions - ); - } - - #[test] - fn nested_ifexp_not_taken_splits_exception_table_like_cpython() { - let code = compile_exec_with_options( r#" def f(flag, subparts): if flag: candidate = subparts[0] if subparts else None yield 1 "#, - CompileOpts::default(), - ); - let f = find_code(&code, "f").expect("missing f"); - let conditional_expr_not_taken = u32::try_from( - f.instructions - .iter() - .enumerate() - .find_map(|(idx, unit)| { - if !matches!(unit.op, Instruction::NotTaken) { - return None; - } - let prev = f.instructions[..idx] - .iter() - .rev() - .find(|unit| !matches!(unit.op, Instruction::Cache))?; - let mut following = f.instructions[idx + 1..] - .iter() - .filter(|unit| !matches!(unit.op, Instruction::Cache)); - let next = following.next()?; - let after_next = following.next()?; - (matches!(prev.op, Instruction::PopJumpIfFalse { .. }) - && matches!(next.op, Instruction::LoadFastBorrow { .. }) - && matches!(after_next.op, Instruction::LoadSmallInt { .. })) - .then_some(idx) - }) - .expect("missing conditional expression NOT_TAKEN"), - ) - .unwrap(); - let body_start = conditional_expr_not_taken + 1; - let entries = bytecode::decode_exception_table(&f.exceptiontable); - - assert!( - entries.iter().all(|entry| { - conditional_expr_not_taken < entry.start || conditional_expr_not_taken >= entry.end - }), - "CPython codegen_ifexp() uses a separate orelse label inside conditional statements, leaving the normalize_jumps NOT_TAKEN outside the StopIteration table; not_taken={conditional_expr_not_taken}, entries={entries:?}, instructions={:?}", - f.instructions - ); - assert!( - entries - .iter() - .any(|entry| entry.start <= body_start && body_start < entry.end), - "the conditional-expression body after that NOT_TAKEN remains protected; body_start={body_start}, entries={entries:?}, instructions={:?}", - f.instructions - ); - } - - #[test] - fn bool_not_taken_after_conditional_yield_splits_like_cpython() { - let code = compile_exec_with_options( r#" def f(a, b, c): if a: @@ -17974,38 +17900,41 @@ def f(a, b, c): x = 3 yield 4 "#, - CompileOpts::default(), - ); - let f = find_code(&code, "f").expect("missing f"); - let split_not_taken = f - .instructions - .iter() - .enumerate() - .filter_map(|(idx, unit)| { - if !matches!(unit.op, Instruction::NotTaken) { - return None; + ] { + let code = compile_exec_with_options(source, CompileOpts::default()); + let f = find_code(&code, "f").expect("missing f"); + let entries = bytecode::decode_exception_table(&f.exceptiontable); + let [entry] = entries.as_slice() else { + panic!("expected a single StopIteration range, got {entries:?} for {source}"); + }; + assert!(entry.push_lasti); + assert_eq!(entry.depth, 0); + let target = &f.instructions[entry.target as usize]; + assert!(matches!( + target.op, + Instruction::CallIntrinsic1 { func } + if func.get(OpArg::new(u32::from(u8::from(target.arg)))) + == oparg::IntrinsicFunction1::StopIterationError + )); + let mut branches = 0; + for (offset, unit) in f.instructions.iter().enumerate() { + if matches!( + unit.op, + Instruction::PopJumpIfFalse { .. } + | Instruction::PopJumpIfTrue { .. } + | Instruction::NotTaken + | Instruction::JumpBackward { .. } + ) { + branches += 1; + let offset = u32::try_from(offset).unwrap(); + assert!( + entry.start <= offset && offset < entry.end, + "unprotected branch at {offset} in {source}; exception entry: {entry:?}" + ); } - let prev = f.instructions[..idx] - .iter() - .rev() - .find(|unit| !matches!(unit.op, Instruction::Cache))?; - matches!( - prev.op, - Instruction::PopJumpIfFalse { .. } | Instruction::PopJumpIfTrue { .. } - ) - .then(|| u32::try_from(idx).unwrap()) - }) - .nth(1) - .expect("missing second bool conditional NOT_TAKEN"); - let entries = bytecode::decode_exception_table(&f.exceptiontable); - - assert!( - entries - .iter() - .all(|entry| split_not_taken < entry.start || split_not_taken >= entry.end), - "CPython labels exception targets before normalize_jumps(), so the general bool-jump NOT_TAKEN after a conditional yield is outside the StopIteration table; not_taken={split_not_taken}, entries={entries:?}, instructions={:?}", - f.instructions - ); + } + assert!(branches > 0); + } } fn non_cache_instructions(code: &CodeObject) -> impl Iterator { @@ -18172,7 +18101,7 @@ def f(command): [ Instruction::PopTop, Instruction::Nop, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, ] )), "CPython NEXT_LOCATION keeps the pass NOP after match subject POP_TOP, got {ops:?}", @@ -18210,30 +18139,6 @@ def f(x): ); } - #[test] - fn match_or_alternative_copies_use_alternative_locations_like_cpython() { - let code = compile_exec( - "\ -def f(): - x = False - match 0: - case 0 | 1 | 2 | 3: - x = True - return x -", - ); - let f = find_code(&code, "f").expect("missing f code"); - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x08, 0x0d, 0x80, 0x41, 0xd8, 0x0a, 0x0b, 0xdf, 0x0d, 0x0e, 0x97, - 0x11, 0x97, 0x51, 0x9f, 0x11, 0x88, 0x5d, 0xe0, 0x0b, 0x0c, 0x80, 0x48, 0xf0, 0x05, - 0x00, 0x0e, 0x1b, 0xd8, 0x10, 0x14, 0x88, 0x41, 0xd8, 0x0b, 0x0c, 0x80, 0x48, - ], - "CPython codegen_pattern_or() emits each alternative COPY with LOC(alt)" - ); - } - #[test] fn match_or_conflicting_bind_error_uses_or_pattern_location_like_cpython() { let error = compile_exec_error( @@ -18276,31 +18181,6 @@ def f(value): ); } - #[test] - fn match_success_jump_uses_no_location_like_cpython() { - let code = compile_exec( - "\ -def f(self): - match 0: - case 0: - x = True - case 0: - x = False - self.assertIs(x, True) -", - ); - let f = find_code(&code, "f").expect("missing f code"); - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x0a, 0x0b, 0xde, 0x0d, 0x0e, 0xd9, 0x10, 0x14, 0x89, 0x41, 0xdd, - 0x0d, 0x0e, 0xd8, 0x10, 0x15, 0x88, 0x41, 0xd8, 0x04, 0x08, 0x87, 0x4d, 0x81, 0x4d, - 0x90, 0x21, 0x90, 0x54, 0xd6, 0x04, 0x1a, - ], - "CPython codegen_match_inner() emits the success jump with NO_LOCATION" - ); - } - #[test] fn match_default_simple_guard_jump_uses_guard_location_like_cpython() { let code = compile_exec( @@ -18350,32 +18230,6 @@ def f(x, y): ); } - #[test] - fn match_mapping_keys_scaffolding_uses_mapping_location_like_cpython() { - let code = compile_exec( - "\ -def f(self): - x = {} - y = None - match x: - case {0: 0}: - y = 0 - self.assertIs(y, None) -", - ); - let f = find_code(&code, "f").expect("missing f code"); - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x08, 0x0a, 0x80, 0x41, 0xd8, 0x08, 0x0c, 0x80, 0x41, 0xd8, 0x0a, - 0x0b, 0xdf, 0x0d, 0x13, 0x8f, 0x56, 0x8a, 0x56, 0x95, 0x11, 0x89, 0x56, 0xd8, 0x10, - 0x11, 0x89, 0x41, 0xf2, 0x03, 0x00, 0x0e, 0x14, 0xe0, 0x04, 0x08, 0x87, 0x4d, 0x81, - 0x4d, 0x90, 0x21, 0x90, 0x54, 0xd6, 0x04, 0x1a, - ], - "CPython codegen_pattern_mapping() returns to LOC(p) for BUILD_TUPLE/MATCH_KEYS scaffolding" - ); - } - #[test] fn match_mapping_rest_cleanup_uses_mapping_location_like_cpython() { let code = compile_exec( @@ -18427,29 +18281,6 @@ def f(x): } } - #[test] - fn match_class_scaffolding_uses_class_pattern_location_like_cpython() { - let code = compile_exec( - "\ -def f(x): - match x: - case bool(z): - y = 0 - return y, z -", - ); - let f = find_code(&code, "f").expect("missing f code"); - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x0a, 0x0b, 0xdc, 0x0d, 0x11, 0x8f, 0x57, 0x88, 0x57, 0xd8, 0x10, - 0x11, 0x88, 0x41, 0xd8, 0x0b, 0x0c, 0x88, 0x34, 0x80, 0x4b, 0xf0, 0x05, 0x00, 0x0e, - 0x15, 0xe0, 0x0b, 0x0c, 0x88, 0x61, 0x88, 0x34, 0x80, 0x4b, - ], - "CPython codegen_pattern_class() returns to LOC(p) after VISIT(cls)" - ); - } - #[test] fn match_class_wildcard_pop_uses_class_pattern_location_like_cpython() { let code = compile_exec( @@ -18547,7 +18378,7 @@ def f(waiters): [ Instruction::LoadFastBorrow { .. } | Instruction::LoadFast { .. }, Instruction::LoadAttr { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] )), @@ -18873,77 +18704,6 @@ x = 1 or 2 or 3 ); } - #[test] - fn taken_constant_boolop_load_const_uses_literal_location_like_cpython() { - let code = compile_exec( - "\ -def and_false(x): - return False and x - -def or_true(x): - return True or x -", - ); - let and_false = find_code(&code, "and_false").expect("missing and_false code"); - let or_true = find_code(&code, "or_true").expect("missing or_true code"); - - // CPython 3.14 codegen_boolop() VISITs the selected literal before the - // short-circuit jump is optimized away, so the surviving LOAD_CONST - // keeps the literal range rather than the whole BoolOp range. - assert_eq!( - and_false.linetable.as_ref(), - &[0x80, 0x00, 0xd8, 0x0b, 0x10, 0xd0, 0x04, 0x16] - ); - assert_eq!( - or_true.linetable.as_ref(), - &[0x80, 0x00, 0xd8, 0x0b, 0x0f, 0xd0, 0x04, 0x14] - ); - } - - #[test] - fn assert_false_message_call_uses_assert_location_like_cpython() { - let code = compile_exec( - "\ -def f(): - assert False, \"x\" -", - ); - let f = find_code(&code, "f").expect("missing f code"); - - // CPython 3.14 codegen_assert() emits LOAD_COMMON_CONSTANT and CALL - // at LOC(assert statement), then RAISE_VARARGS at LOC(test). - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x04, 0x15, 0x90, 0x23, 0xd3, 0x04, 0x15, 0x88, 0x35, - ] - ); - } - - #[test] - fn static_swap_implicit_return_keeps_preswap_store_location_like_cpython() { - let code = compile_exec( - "\ -def f(a, b): - a, b = a, b - b, a = a, b -", - ); - let f = find_code(&code, "f").expect("missing f code"); - - // CPython 3.14 flowgraph.c resolves line numbers before - // optimize_basic_block() turns BUILD_TUPLE/UNPACK_SEQUENCE into SWAP - // and apply_static_swaps() reorders the STORE_FAST pair. The - // synthetic return epilogue therefore keeps the pre-swap final store - // location. - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x0b, 0x0c, 0x80, 0x71, 0xd8, 0x0b, 0x0c, 0x82, 0x71, - ] - ); - } - #[test] fn unpack_store_pair_jump_uses_second_target_location_like_cpython() { let code = compile_exec( @@ -19055,169 +18815,6 @@ def f(flag, n, exp): assert_eq!(jump_position, (3, 12, 3, 13)); } - #[test] - fn genexpr_make_closure_and_call_use_genexpr_location_like_cpython() { - let code = compile_exec( - "\ -def f(parameters): - return ((p, type(p)) for p in parameters) -", - ); - let f = find_code(&code, "f").expect("missing f code"); - let genexpr = find_code(f, "").expect("missing genexpr code"); - - // CPython 3.14 codegen_comprehension() uses LOC(e) for - // codegen_make_closure(), the outer CALL, and the implicit .0 load - // in codegen_sync_comprehension_generator(). - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd9, 0x0b, 0x2d, 0xa1, 0x2a, 0xd3, 0x0b, 0x2d, 0xd0, 0x04, 0x2d, - ] - ); - assert_eq!( - genexpr.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x0b, 0x2d, 0xa1, 0x2a, 0x98, 0x51, 0x94, 0x04, 0x90, - 0x51, 0x93, 0x07, 0x8d, 0x4c, 0xa3, 0x2a, 0xf9, - ] - ); - } - - #[test] - fn implicit_call_genexpr_range_includes_call_parens_like_cpython() { - let code = compile_exec( - "\ -def implicit(): - return list(x for x in range(10)) - -def explicit(): - return list((x for x in range(10))) -", - ); - let implicit = find_code(&code, "implicit").expect("missing implicit code"); - let implicit_gen = find_code(implicit, "").expect("missing implicit genexpr code"); - let explicit = find_code(&code, "explicit").expect("missing explicit code"); - let explicit_gen = find_code(explicit, "").expect("missing explicit genexpr code"); - - // CPython's parser gives an unparenthesized sole GeneratorExp call - // argument the call-parenthesized range, and codegen_comprehension() - // uses LOC(e) for MAKE_FUNCTION, the outer CALL, and the implicit .0 - // LOAD_FAST. Explicitly parenthesized genexprs already carry their own - // parentheses and must not be widened again. - assert_eq!( - implicit.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdc, 0x0b, 0x0f, 0xd1, 0x0f, 0x25, 0x9c, 0x35, 0xa0, 0x12, 0x9c, 0x39, - 0xd3, 0x0f, 0x25, 0xd3, 0x0b, 0x25, 0xd0, 0x04, 0x25, - ] - ); - assert_eq!( - implicit_gen.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x0f, 0x25, 0x99, 0x39, 0x90, 0x61, 0x94, 0x01, 0x9b, - 0x39, 0xf9, - ] - ); - assert_eq!( - explicit_gen.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x10, 0x26, 0x99, 0x49, 0x90, 0x71, 0x94, 0x11, 0x9b, - 0x49, 0xf9, - ] - ); - } - - #[test] - fn implicit_call_genexpr_parenthesized_element_range_like_cpython() { - let code = compile_exec( - "\ -def bytes_binop(): - return bytes((x ^ 0x5C) for x in range(256)) - -def dict_tuple(d): - return dict((v, k) for (k, v) in d.items()) - -def plain_tuple_elt(xs): - return list((x, y) for x, y in xs) - -def explicit_gen(xs): - return list(((x, y) for x, y in xs)) -", - ); - let bytes_binop = find_code(&code, "bytes_binop").expect("missing bytes_binop code"); - let bytes_gen = find_code(bytes_binop, "").expect("missing bytes genexpr code"); - let dict_tuple = find_code(&code, "dict_tuple").expect("missing dict_tuple code"); - let dict_gen = find_code(dict_tuple, "").expect("missing dict genexpr code"); - let plain_tuple_elt = - find_code(&code, "plain_tuple_elt").expect("missing plain_tuple_elt code"); - let plain_gen = - find_code(plain_tuple_elt, "").expect("missing plain genexpr code"); - let explicit_gen = find_code(&code, "explicit_gen").expect("missing explicit_gen code"); - let explicit_inner = - find_code(explicit_gen, "").expect("missing explicit genexpr code"); - - // CPython 3.14's parser includes the call argument parentheses in - // LOC(GeneratorExp) for implicit sole-argument generator expressions, - // even when the element expression itself starts with parentheses. - assert_eq!( - bytes_binop.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdc, 0x0b, 0x10, 0xd1, 0x10, 0x30, 0xa4, 0x55, 0xa8, 0x33, 0xa4, 0x5a, - 0xd3, 0x10, 0x30, 0xd3, 0x0b, 0x30, 0xd0, 0x04, 0x30, - ] - ); - assert_eq!( - bytes_gen.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x10, 0x30, 0xa1, 0x5a, 0xa0, 0x01, 0x90, 0x64, 0x97, - 0x28, 0x92, 0x28, 0xa3, 0x5a, 0xf9, - ] - ); - assert_eq!( - dict_tuple.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdc, 0x0b, 0x0f, 0xd1, 0x0f, 0x2f, 0xa0, 0x51, 0xa7, 0x57, 0xa1, 0x57, - 0xa4, 0x59, 0xd3, 0x0f, 0x2f, 0xd3, 0x0b, 0x2f, 0xd0, 0x04, 0x2f, - ] - ); - assert_eq!( - dict_gen.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x0f, 0x2f, 0xa1, 0x59, 0x99, 0x36, 0x98, 0x41, 0x90, - 0x11, 0x95, 0x06, 0xa3, 0x59, 0xf9, - ] - ); - assert_eq!( - plain_tuple_elt.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdc, 0x0b, 0x0f, 0xd1, 0x0f, 0x26, 0xa1, 0x32, 0xd3, 0x0f, 0x26, 0xd3, - 0x0b, 0x26, 0xd0, 0x04, 0x26, - ] - ); - assert_eq!( - plain_gen.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x0f, 0x26, 0xa1, 0x32, 0x99, 0x34, 0x98, 0x31, 0x90, - 0x11, 0x95, 0x06, 0xa3, 0x32, 0xf9, - ] - ); - assert_eq!( - explicit_gen.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdc, 0x0b, 0x0f, 0xd1, 0x10, 0x27, 0xa1, 0x42, 0xd3, 0x10, 0x27, 0xd3, - 0x0b, 0x28, 0xd0, 0x04, 0x28, - ] - ); - assert_eq!( - explicit_inner.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x10, 0x27, 0xa1, 0x42, 0x99, 0x44, 0x98, 0x41, 0x90, - 0x21, 0x95, 0x16, 0xa3, 0x42, 0xf9, - ] - ); - } - #[test] fn implicit_call_genexpr_operator_element_range_like_cpython() { // The element opens with a parenthesized group that the rest of the @@ -19232,14 +18829,14 @@ def f(p, q): let f = find_code(&code, "f").expect("missing f code"); let genexpr = find_code(f, "").expect("missing genexpr code"); - // Columns are one-based here, so these are `dis`'s 14..56. + // MAKE_FUNCTION keeps the genexpr range; eager .0 acquisition uses the iterable range. assert_eq!( instruction_range(f, |op| matches!(op, Instruction::MakeFunction)), Some((2, 15, 2, 57)) ); assert_eq!( instruction_range(genexpr, |op| matches!(op, Instruction::LoadFast { .. })), - Some((2, 15, 2, 57)) + Some((2, 47, 2, 56)) ); } @@ -19261,7 +18858,12 @@ w = f'' 'a' f'' .instructions .iter() .zip(&code.locations) - .filter(|(unit, _)| matches!(unit.op, Instruction::LoadConst { .. })) + .filter(|(unit, _)| { + matches!(unit.op, Instruction::LoadConst { .. }) + || matches!(unit.op, Instruction::LoadCommonConstant { idx } + if idx.get(OpArg::new(u32::from(u8::from(unit.arg)))) + == bytecode::CommonConstant::EmptyStr) + }) .map(|(_, locations)| location_range(locations)) .take(4) .collect(); @@ -19273,71 +18875,6 @@ w = f'' 'a' f'' ); } - #[test] - fn genexpr_filter_cleanup_jumps_use_element_location_like_cpython() { - let code = compile_exec( - "\ -def simple(names): - return (x for x in names if not _ishidden(x)) - -def boolop(fields): - return (f for f in fields if f.init and not f.kw_only) -", - ); - let simple = find_code(&code, "simple").expect("missing simple code"); - let simple_gen = find_code(simple, "").expect("missing simple genexpr code"); - let boolop = find_code(&code, "boolop").expect("missing boolop code"); - let boolop_gen = find_code(boolop, "").expect("missing boolop genexpr code"); - - // codegen_sync_comprehension_generator() emits the - // comprehension guard jump to if_cleanup, then emits the if_cleanup - // backedge with elt_loc. flowgraph.c::jump_thread() copies that target - // jump location to the threaded POP_JUMP/NOT_TAKEN cleanup path. - assert_eq!( - simple_gen.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x0b, 0x31, 0x91, 0x75, 0x90, 0x21, 0xa4, 0x49, 0xa8, - 0x61, 0xa7, 0x4c, 0x8f, 0x41, 0x8a, 0x41, 0x93, 0x75, 0xf9, - ] - ); - assert_eq!( - boolop_gen.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd0, 0x0b, 0x3a, 0x91, 0x76, 0x90, 0x21, 0xa7, 0x16, 0xa5, - 0x16, 0x8c, 0x41, 0xb0, 0x01, 0xb7, 0x09, 0xb5, 0x09, 0x8f, 0x41, 0x8a, 0x41, 0x93, - 0x76, 0xf9, - ] - ); - } - - #[test] - fn try_finally_exception_scaffolding_uses_no_location_like_cpython() { - let code = compile_exec( - "\ -def f(self, node): - self.flag = True - try: - self.body(node) - finally: - self.flag = False -", - ); - let f = find_code(&code, "f").expect("missing f code"); - - // codegen_try_finally() emits the exception path - // SETUP_CLEANUP/PUSH_EXC_INFO and POP_EXCEPT_AND_RERAISE with - // NO_LOCATION; flowgraph line propagation then gives only the - // finalbody's direct RERAISE the finalbody location. - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x10, 0x14, 0x80, 0x44, 0x84, 0x49, 0xf0, 0x02, 0x03, 0x05, 0x1a, - 0xd8, 0x08, 0x0c, 0x8f, 0x09, 0x89, 0x09, 0x90, 0x24, 0x8c, 0x0f, 0xe0, 0x14, 0x19, - 0x88, 0x04, 0x8e, 0x09, 0xf8, 0x90, 0x45, 0x88, 0x04, 0x8d, 0x09, 0xfa, - ] - ); - } - #[test] fn return_debug_in_finally_uses_cpython_preprocessed_constant_order() { let code = compile_exec( @@ -19359,11 +18896,10 @@ def f(close): .instructions .iter() .position(|unit| { - let Instruction::LoadConst { consti } = unit.op else { + let Instruction::LoadCommonConstant { idx } = unit.op else { return false; }; - let constant = &f.constants[consti.get(OpArg::new(u32::from(u8::from(unit.arg))))]; - matches!(constant, ConstantData::Boolean { value: true }) + idx.get(OpArg::new(u32::from(u8::from(unit.arg)))) == bytecode::CommonConstant::True }) .expect("missing __debug__ constant load"); @@ -19464,76 +19000,6 @@ def f(close): ); } - #[test] - fn adjacent_no_location_entries_merge_like_cpython() { - let code = compile_exec( - "\ -def f(file): - if sys.platform == \"win32\": - try: - import nt - if not nt._supports_virtual_terminal(): - return False - except (ImportError, AttributeError): - return False - try: - return os.isatty(file.fileno()) - except OSError: - return hasattr(file, \"isatty\") and file.isatty() -", - ); - let f = find_code(&code, "f").expect("missing f code"); - - // CPython's NO_LOCATION is {-1, -1, -1, -1}, and - // assemble.c::assemble_location_info() merges adjacent instructions - // with the same NO_LOCATION into one linetable entry. - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdc, 0x07, 0x0a, 0x87, 0x7c, 0x81, 0x7c, 0x90, 0x77, 0xd4, 0x07, 0x1e, - 0xf0, 0x02, 0x05, 0x09, 0x19, 0xdb, 0x0c, 0x15, 0xd8, 0x13, 0x15, 0xd7, 0x13, 0x30, - 0xd1, 0x13, 0x30, 0xd7, 0x13, 0x32, 0xd2, 0x13, 0x32, 0xd9, 0x17, 0x1c, 0xf0, 0x03, - 0x00, 0x14, 0x33, 0xf0, 0x08, 0x03, 0x05, 0x39, 0xdc, 0x0f, 0x11, 0x8f, 0x79, 0x89, - 0x79, 0x98, 0x14, 0x9f, 0x1b, 0x99, 0x1b, 0x9b, 0x1d, 0xd3, 0x0f, 0x27, 0xd0, 0x08, - 0x27, 0xf8, 0xf4, 0x07, 0x00, 0x11, 0x1c, 0x9c, 0x5e, 0xd0, 0x0f, 0x2c, 0xf4, 0x00, - 0x01, 0x09, 0x19, 0xda, 0x13, 0x18, 0xf0, 0x03, 0x01, 0x09, 0x19, 0xfb, 0xf4, 0x08, - 0x00, 0x0c, 0x13, 0xf4, 0x00, 0x01, 0x05, 0x39, 0xdc, 0x0f, 0x16, 0x90, 0x74, 0x98, - 0x58, 0xd3, 0x0f, 0x26, 0xd7, 0x0f, 0x38, 0xd0, 0x0f, 0x38, 0xa8, 0x34, 0xaf, 0x3b, - 0xa9, 0x3b, 0xab, 0x3d, 0xd2, 0x08, 0x38, 0xf0, 0x03, 0x01, 0x05, 0x39, 0xfa, - ] - ); - } - - #[test] - fn fstring_format_ops_use_formatted_value_location_like_cpython() { - let code = compile_exec( - "\ -def simple(self): - return f'{self.value}' - -def spec(x): - return f'{x!r:>3}' -", - ); - let simple = find_code(&code, "simple").expect("missing simple code"); - let spec = find_code(&code, "spec").expect("missing spec code"); - - // CPython 3.14 codegen_formatted_value() VISITs the inner expression - // first, then emits CONVERT_VALUE / FORMAT_* at LOC(FormattedValue). - assert_eq!( - simple.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x0e, 0x12, 0x8f, 0x6a, 0x89, 0x6a, 0x88, 0x5c, 0xd0, 0x04, 0x1a, - ] - ); - assert_eq!( - spec.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x0e, 0x0f, 0x88, 0x58, 0x90, 0x22, 0x88, 0x58, 0xd0, 0x04, 0x16, - ] - ); - } - #[test] fn debug_fstring_literal_merging_and_location_like_cpython() { fn string_load_position(code: &CodeObject, expected: &str) -> (usize, usize, usize, usize) { @@ -19631,29 +19097,6 @@ def padded(digits, int_len): ); } - #[test] - fn joined_string_literals_extend_pending_literal_location_like_cpython() { - let code = compile_exec( - "\ -def f(a): - return ( - 'x' - f'y{a}z' - 'w' - ) -", - ); - let f = find_code(&code, "f").expect("missing f code"); - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xf0, 0x04, 0x01, 0x09, 0x0c, 0xd8, 0x0c, 0x0d, 0x88, 0x33, 0xf0, 0x00, - 0x01, 0x0f, 0x0c, 0xf0, 0x03, 0x02, 0x09, 0x0c, 0xf0, 0x03, 0x04, 0x05, 0x06, - ], - "CPython parser/codegen represents adjacent f-string literal fragments as Constant ranges spanning the merged fragments" - ); - } - #[test] fn starred_call_preserves_bool_op_short_circuit_shape() { let code = compile_exec( @@ -19726,60 +19169,6 @@ def outer(null): ); } - #[test] - fn decorated_definitions_use_cpython_locations() { - let code = compile_exec( - "\ -def dec(f): return f - -class C: - @dec - def f(self): - yield - -@dec -class D: - pass - -class E: - @dec - def g(self, flags: int, /) -> memoryview: - raise NotImplementedError -", - ); - let c = find_code(&code, "C").expect("missing C code"); - let d = find_code(&code, "D").expect("missing D code"); - let e = find_code(&code, "E").expect("missing E code"); - let annotate = find_code(e, "__annotate__").expect("missing annotation code"); - - // CPython 3.14 codegen_function()/codegen_class() evaluate - // decorators first, then use LOC(s) for codegen_make_closure() and - // codegen_nameop(); codegen_apply_decorators() emits CALL at each - // decorator expression's location. - assert_eq!( - c.linetable.as_ref(), - &[ - 0xf8, 0x87, 0x00, 0x80, 0x00, 0xd8, 0x05, 0x08, 0xf1, 0x02, 0x01, 0x05, 0x0e, 0xf3, - 0x03, 0x00, 0x06, 0x09, 0xf6, 0x02, 0x01, 0x05, 0x0e, - ] - ); - assert_eq!(d.linetable.as_ref(), &[0x86, 0x00, 0xe3, 0x04, 0x08]); - assert_eq!( - e.linetable.as_ref(), - &[ - 0xf8, 0x87, 0x00, 0x80, 0x00, 0xd8, 0x05, 0x08, 0xf7, 0x02, 0x01, 0x05, 0x22, 0xf3, - 0x03, 0x00, 0x06, 0x09, 0xf6, 0x02, 0x01, 0x05, 0x22, - ] - ); - assert_eq!( - annotate.linetable.as_ref(), - &[ - 0xf8, 0x80, 0x00, 0xf7, 0x00, 0x01, 0x05, 0x22, 0xf1, 0x00, 0x01, 0x05, 0x22, 0x91, - 0x73, 0xf0, 0x00, 0x01, 0x05, 0x22, 0xa1, 0x2a, 0xf1, 0x00, 0x01, 0x05, 0x22, - ] - ); - } - #[test] fn taken_constant_boolop_jump_disables_following_borrows() { for source in [ @@ -20134,7 +19523,7 @@ x = +0.0j Instruction::Resume { .. }, Instruction::LoadConst { .. }, Instruction::StoreName { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue ] ), @@ -20556,74 +19945,25 @@ def outer(log): } #[test] - fn builtin_any_genexpr_call_is_optimized() { - let code = compile_exec( - "\ -def f(xs): - return any(x for x in xs) -", - ); - let f = find_code(&code, "f").expect("missing function code"); - - assert!(has_common_constant(f, bytecode::CommonConstant::BuiltinAny)); - assert!( - f.instructions - .iter() - .any(|unit| matches!(unit.op, Instruction::PopJumpIfTrue { .. })) - ); - assert!( - f.instructions - .iter() - .any(|unit| matches!(unit.op, Instruction::NotTaken)) - ); - assert_eq!( - f.instructions - .iter() - .filter(|unit| matches!(unit.op, Instruction::PushNull)) - .count(), - 1, - "fallback call path should remain for shadowed any()" - ); - let genexpr_const_count = f - .constants - .iter() - .filter(|constant| { - matches!(constant, ConstantData::Code { code } if code.obj_name == "") - }) - .count(); - assert_eq!( - genexpr_const_count, 1, - "optimized and fallback any(genexpr) paths should share the same CPython-range code const" - ); - assert_eq!( - f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdf, 0x0b, 0x0e, 0x8b, 0x33, 0x89, 0x6f, 0x99, 0x22, 0x8b, 0x6f, 0x8f, - 0x33, 0x8c, 0x33, 0xd0, 0x04, 0x1d, 0x8a, 0x33, 0xd0, 0x04, 0x1d, 0x88, 0x33, 0x89, - 0x6f, 0x99, 0x22, 0x8b, 0x6f, 0xd3, 0x0b, 0x1d, 0xd0, 0x04, 0x1d, - ] - ); - } - - #[test] - fn builtin_any_async_genexpr_call_is_optimized_like_cpython() { + fn builtin_any_async_genexpr_call_is_not_optimized_like_cpython() { for source in [ "async def f(xs):\n return any(x async for x in xs)\n", "async def f(xs):\n return any(await x for x in xs)\n", + "async def f(xs):\n return any(x async for x in (lambda: xs)())\n", + "async def f(xs):\n return any(await x for x in (y for y in xs))\n", ] { let code = compile_exec(source); let f = find_code(&code, "f").expect("missing function code"); assert!( - has_common_constant(f, bytecode::CommonConstant::BuiltinAny), - "maybe_optimize_function_call() guards any(genexpr) whether or not the \ - generator is a coroutine: {source}" + !has_common_constant(f, bytecode::CommonConstant::BuiltinAny), + "coroutine generator expressions must use the ordinary call path: {source}" ); assert!( - f.instructions + !f.instructions .iter() .any(|unit| matches!(unit.op, Instruction::ForIter { .. })), - "the guarded path inlines the loop: {source}" + "the ordinary call path must not inline an async generator loop: {source}" ); assert!( f.instructions @@ -20650,72 +19990,6 @@ async def f(get_xs): ); } - #[test] - fn builtin_tuple_genexpr_call_is_optimized_but_list_set_are_not() { - let code = compile_exec( - "\ -def tuple_f(xs): - return tuple(x for x in xs) - -def list_f(xs): - return list(x for x in xs) - -def set_f(xs): - return set(x for x in xs) -", - ); - - let tuple_f = find_code(&code, "tuple_f").expect("missing tuple_f code"); - assert!(has_common_constant( - tuple_f, - bytecode::CommonConstant::BuiltinTuple - )); - assert!(has_intrinsic_1(tuple_f, IntrinsicFunction1::ListToTuple)); - let tuple_list_append = tuple_f - .instructions - .iter() - .find_map(|unit| match unit.op { - Instruction::ListAppend { .. } => Some(u32::from(u8::from(unit.arg))), - _ => None, - }) - .expect("tuple(genexpr) fast path should emit LIST_APPEND"); - assert_eq!(tuple_list_append, 2); - assert_eq!( - tuple_f.linetable.as_ref(), - &[ - 0x80, 0x00, 0xdf, 0x0b, 0x10, 0x8c, 0x35, 0x91, 0x0f, 0x99, 0x42, 0x93, 0x0f, 0x8f, - 0x35, 0xd0, 0x04, 0x1f, 0x88, 0x35, 0x91, 0x0f, 0x99, 0x42, 0x93, 0x0f, 0xd3, 0x0b, - 0x1f, 0xd0, 0x04, 0x1f, - ] - ); - - let list_f = find_code(&code, "list_f").expect("missing list_f code"); - assert!( - list_f - .instructions - .iter() - .any(|unit| matches!(unit.op, Instruction::Call { .. })), - "list(genexpr) should stay on the normal call path" - ); - assert!( - !has_common_constant(list_f, bytecode::CommonConstant::BuiltinList), - "CPython 3.14.5 does not optimize list(genexpr)" - ); - - let set_f = find_code(&code, "set_f").expect("missing set_f code"); - assert!( - set_f - .instructions - .iter() - .any(|unit| matches!(unit.op, Instruction::Call { .. })), - "set(genexpr) should stay on the normal call path" - ); - assert!( - !has_common_constant(set_f, bytecode::CommonConstant::BuiltinSet), - "CPython 3.14.5 does not optimize set(genexpr)" - ); - } - #[test] fn builtin_tuple_genexpr_try_assignment_uses_shared_tail() { let code = compile_exec( @@ -20829,8 +20103,7 @@ def f(template): continue; }; let load_attr = namei.get(OpArg::new(u32::from(u8::from(attr.arg)))); - if f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() != "interpolations" - { + if f.names[load_attr.name_idx()].as_str() != "interpolations" { continue; } saw_interpolations = true; @@ -20862,12 +20135,59 @@ class C: assert!(code.instructions.iter().any(|unit| match unit.op { Instruction::StoreGlobal { namei } => { let idx = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - code.names[usize::try_from(idx).unwrap()].as_str() == "_address_fmt_re" + code.names[idx].as_str() == "_address_fmt_re" } _ => false, })); } + fn find_module_doc_store(code: &CodeObject) -> Option<&Instruction> { + code.instructions.iter().find_map(|unit| match unit.op { + Instruction::StoreName { namei } | Instruction::StoreGlobal { namei } => { + let idx = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); + (code.names[idx].as_str() == "__doc__").then_some(&unit.op) + } + _ => None, + }) + } + + #[test] + fn module_docstring_store_uses_global_when_nested_scope_declares_global() { + let code = compile_exec( + "\ +\"module doc\" +def f(): + global __doc__ +", + ); + + let op = find_module_doc_store(&code).expect("missing module docstring store"); + assert!( + matches!(op, Instruction::StoreGlobal { .. }), + "module docstring store should resolve through name resolution to StoreGlobal \ + when a nested scope declares `global __doc__`, got instructions={:?}", + code.instructions + ); + } + + #[test] + fn module_docstring_store_stays_name_without_nested_global() { + let code = compile_exec( + "\ +\"module doc\" +x = 1 +", + ); + + let op = find_module_doc_store(&code).expect("missing module docstring store"); + assert!( + matches!(op, Instruction::StoreName { .. }), + "module docstring store should remain StoreName without a nested \ + `global __doc__` declaration, got instructions={:?}", + code.instructions + ); + } + #[test] fn conditional_return_epilogue_is_duplicated() { let code = compile_exec( @@ -20964,7 +20284,7 @@ def f(cache, lock, format): Instruction::LoadFastLoadFast { .. }, Instruction::LoadFast { .. }, Instruction::StoreSubscr, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -21106,27 +20426,6 @@ def aug(x, a, b, y): ); } - #[test] - fn augassign_constant_slice_copy_uses_subscript_location_like_cpython() { - let code = compile_exec( - "\ -def aug_const(x, y): - x[1:2] += y -", - ); - let aug_const = find_code(&code, "aug_const").expect("missing aug_const code"); - - // CPython 3.14 codegen_augassign() visits a constant slice, then emits - // COPY/COPY/BINARY_OP NB_SUBSCR at LOC(target), not at LOC(slice). - assert_eq!( - aug_const.linetable.as_ref(), - &[ - 0x80, 0x00, 0xd8, 0x04, 0x05, 0x80, 0x63, 0x87, 0x46, 0x88, 0x61, 0x85, 0x4b, 0x85, - 0x46, - ] - ); - } - #[test] fn augassign_attribute_copy_uses_target_location_like_cpython() { let code = compile_exec( @@ -21181,7 +20480,7 @@ def f(obj): .filter(|op| !matches!(op, Instruction::Cache)) .collect(); - let has_cpython_shape = ops.windows(7).any(|window| { + let has_cpython_shape = ops.windows(8).any(|window| { matches!( window, [ @@ -21191,6 +20490,7 @@ def f(obj): Instruction::LoadFastBorrow { .. } | Instruction::LoadFast { .. }, Instruction::Swap { .. }, Instruction::PopTop, + Instruction::PopTop, Instruction::ReturnValue, ] ) @@ -21565,7 +20865,7 @@ def f(self, exc_type, KeyboardInterrupt, TimeoutExpired): Instruction::LoadSmallInt { .. }, Instruction::LoadFastBorrow { .. }, Instruction::StoreAttr { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue, ] ) @@ -21705,7 +21005,7 @@ def f(locale, category, locales): Instruction::RaiseVarargs { .. }, Instruction::Nop, Instruction::Nop, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::YieldValue { .. }, ] ) @@ -21852,18 +21152,19 @@ def f(parts): ); let break_cleanup_idx = ops - .windows(3) + .windows(4) .position(|window| { matches!( window, [ Instruction::PopTop, - Instruction::LoadConst { .. }, + Instruction::PopTop, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue ] ) }) - .expect("missing POP_TOP/LOAD_CONST/RETURN_VALUE break cleanup"); + .expect("missing POP_TOP/POP_TOP/LOAD_COMMON_CONSTANT/RETURN_VALUE break cleanup"); let end_for_idx = ops .iter() .position(|op| matches!(op, Instruction::EndFor)) @@ -21903,7 +21204,7 @@ elif maxsize == 9223372036854775807: [ Instruction::EndFor, Instruction::PopIter, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue, ] ) @@ -21918,7 +21219,7 @@ elif maxsize == 9223372036854775807: Instruction::EndFor, Instruction::PopIter, Instruction::Nop, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -22485,8 +21786,10 @@ def f(one: int): let loads_global = |name: &str| { f.instructions.iter().any(|unit| match unit.op { Instruction::LoadGlobal { namei } => { - let namei = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) >> 1; - f.names[usize::try_from(namei).unwrap()].as_str() == name + let namei = namei + .get(OpArg::new(u32::from(u8::from(unit.arg)))) + .name_idx(); + f.names[namei].as_str() == name } _ => false, }) @@ -22569,7 +21872,7 @@ def f(self, file, backupfilename): ], [ Instruction::PopExcept, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::LoadFast { .. }, Instruction::StoreAttr { .. }, Instruction::Reraise { .. }, @@ -22608,8 +21911,10 @@ def f(): .collect(); let load_global_name = |unit: &&bytecode::CodeUnit| match unit.op { Instruction::LoadGlobal { namei } => { - let name = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) >> 1; - Some(f.names[usize::try_from(name).unwrap()].as_str()) + let name = namei + .get(OpArg::new(u32::from(u8::from(unit.arg)))) + .name_idx(); + Some(f.names[name].as_str()) } _ => None, }; @@ -23063,15 +22368,9 @@ def f(x): ) }) .expect("missing folded -0.0 match value"); - let none_index = f - .constants - .iter() - .position(|constant| matches!(constant, ConstantData::None)) - .expect("missing implicit None"); - assert!( - negative_zero_index < none_index, - "CPython ast_preprocess.c folds MatchValue constants before codegen registers the implicit None" - ); + assert_eq!(negative_zero_index, 0); + assert_eq!(f.constants.len(), 1); + assert!(has_common_constant(f, bytecode::CommonConstant::None)); } #[test] @@ -23158,7 +22457,7 @@ def f(x): } #[test] - fn match_mapping_attribute_key_keeps_plain_load_fast_without_block_disable() { + fn match_mapping_attribute_key_keeps_borrowed_load_fast_without_block_disable() { let code = compile_exec( "\ def f(self): @@ -23178,8 +22477,7 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "assertRaises" + f.names[load_attr.name_idx()].as_str() == "assertRaises" } _ => false, }) @@ -23199,15 +22497,15 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "KEY" + f.names[load_attr.name_idx()].as_str() == "KEY" } _ => false, }) .expect("missing Keys.KEY attribute load"); let prev = f.instructions[key_load_idx - 1].op; assert!( - matches!(prev, Instruction::LoadFast { .. }), - "CPython optimize_load_fast() records MATCH_KEYS' no-input pseudo-ref with the produced-value loop index, so this consumed Keys load stays strong; got ops={:?}", + matches!(prev, Instruction::LoadFastBorrow { .. }), + "CPython optimize_load_fast() records MATCH_KEYS' no-input pseudo-ref with the current instruction index, so this consumed Keys load is borrowed; got ops={:?}", f.instructions .iter() .map(|unit| unit.op) @@ -23237,7 +22535,7 @@ def f(self, groupby): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "b" + f.names[load_attr.name_idx()].as_str() == "b" } _ => false, }) @@ -23283,7 +22581,7 @@ def f(self, typ, dat): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "debug" + f.names[load_attr.name_idx()].as_str() == "debug" } _ => false, }) @@ -23299,7 +22597,7 @@ def f(self, typ, dat): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "_mesg" + f.names[load_attr.name_idx()].as_str() == "_mesg" } _ => false, }) @@ -23336,7 +22634,7 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "debug" + f.names[load_attr.name_idx()].as_str() == "debug" } _ => false, }) @@ -23391,9 +22689,9 @@ def f(i): matches!( window, [ - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, ] @@ -23590,9 +22888,9 @@ def f(cm): [ (Instruction::DeleteFast { .. }, 6), (Instruction::Nop, 6), - (Instruction::LoadConst { .. }, 2), - (Instruction::LoadConst { .. }, 2), - (Instruction::LoadConst { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), (Instruction::Call { .. }, 2), ] ) @@ -23630,9 +22928,9 @@ def f(cm, names, modname): Instruction::Call { .. }, Instruction::PopTop, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -23669,9 +22967,9 @@ def f(cm): [ Instruction::StoreFast { .. }, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -23711,9 +23009,9 @@ def f(cm, func, check): Instruction::Call { .. }, Instruction::PopTop, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -23758,9 +23056,9 @@ def f(meta_path, cm): (Instruction::Call { .. }, 9), (Instruction::StoreFast { .. }, 9), (Instruction::Nop, 9), - (Instruction::LoadConst { .. }, 3), - (Instruction::LoadConst { .. }, 3), - (Instruction::LoadConst { .. }, 3), + (Instruction::LoadCommonConstant { .. }, 3), + (Instruction::LoadCommonConstant { .. }, 3), + (Instruction::LoadCommonConstant { .. }, 3), ] ) }), @@ -23792,8 +23090,10 @@ def f(module, fromlist, import_, recursive=False): let is_load_global = |unit: &&rustpython_compiler_core::bytecode::CodeUnit, name: &str| match unit.op { Instruction::LoadGlobal { namei } => { - let namei = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) >> 1; - f.names[usize::try_from(namei).unwrap()].as_str() == name + let namei = namei + .get(OpArg::new(u32::from(u8::from(unit.arg)))) + .name_idx(); + f.names[namei].as_str() == name } _ => false, }; @@ -23845,9 +23145,9 @@ def f(cm): [ Instruction::StoreFast { .. }, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -23860,9 +23160,9 @@ def f(cm): window, [ Instruction::StoreFast { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -23899,9 +23199,9 @@ def f(cm, ValueError): window, [ (Instruction::Nop, 6), - (Instruction::LoadConst { .. }, 2), - (Instruction::LoadConst { .. }, 2), - (Instruction::LoadConst { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), (Instruction::Call { .. }, 2), ] ) @@ -23939,9 +23239,9 @@ def f(open, src, dst, copyfileobj): [ Instruction::Call { .. }, Instruction::PopTop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, ] @@ -23957,9 +23257,9 @@ def f(open, src, dst, copyfileobj): Instruction::Call { .. }, Instruction::PopTop, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, ] @@ -24599,7 +23899,7 @@ def f(tar1, x): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "close" + f.names[load_attr.name_idx()].as_str() == "close" } _ => false, }) @@ -24637,7 +23937,7 @@ def f(tar1, x): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "close" + f.names[load_attr.name_idx()].as_str() == "close" } _ => false, }) @@ -24722,9 +24022,9 @@ def f(selector, self): [ (Instruction::JumpBackward { .. }, 4), (Instruction::Nop, 3), - (Instruction::LoadConst { .. }, 2), - (Instruction::LoadConst { .. }, 2), - (Instruction::LoadConst { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), + (Instruction::LoadCommonConstant { .. }, 2), (Instruction::Call { .. }, 2), ] ) @@ -25619,7 +24919,7 @@ def f(value): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "defects" + f.names[load_attr.name_idx()].as_str() == "defects" } _ => false, }) @@ -25637,7 +24937,7 @@ def f(value): .rposition(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "format" + f.names[load_attr.name_idx()].as_str() == "format" } _ => false, }) @@ -25868,7 +25168,7 @@ def f(part, lines, maxlen, encoding): window, [ Instruction::LoadFastBorrow { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreSubscr, ] ) @@ -25993,7 +25293,7 @@ def f(part, lines, maxlen, encoding): window, [ Instruction::LoadFastBorrow { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreSubscr, ] ) @@ -26512,7 +25812,7 @@ def f(self, action): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "_dedent" + f.names[load_attr.name_idx()].as_str() == "_dedent" } _ => false, }) @@ -26606,7 +25906,7 @@ async def f(g, self, x): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "aclose" + f.names[load_attr.name_idx()].as_str() == "aclose" } _ => false, }) @@ -26925,11 +26225,23 @@ def f(fields): Instruction::LoadFastBorrow { .. }, Instruction::LoadAttr { .. }, Instruction::Call { .. }, - Instruction::GetIter, + Instruction::Call { .. }, ] ) }), - "expected plain attr-iter chain to keep borrowed receiver, got ops={ops:?}" + "expected plain attr-genexpr-call chain to keep borrowed receiver, got ops={ops:?}" + ); + assert!( + !f.instructions + .iter() + .any(|unit| matches!(unit.op, Instruction::GetIter { .. })) + ); + let genexpr = find_code(f, "").expect("missing genexpr"); + assert!( + genexpr + .instructions + .iter() + .any(|unit| matches!(unit.op, Instruction::GetIter { .. })) ); } @@ -26989,7 +26301,7 @@ class C: unit.op, Instruction::StoreName { namei } if class_code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__classdictcell__" ) @@ -27034,7 +26346,7 @@ class C: matches!( unit.op, Instruction::StoreName { namei } - if namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize + if namei.get(OpArg::new(u32::from(u8::from(unit.arg)))).as_usize() == class_name_index ) })); @@ -27079,7 +26391,7 @@ class C: unit.op, Instruction::StoreName { namei } if class_code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__static_attributes__" ) @@ -27112,7 +26424,7 @@ class C: unit.op, Instruction::StoreName { namei } if class_code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__classdictcell__" ) @@ -27226,7 +26538,7 @@ class C: unit.op, Instruction::StoreName { namei } if class_code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__firstlineno__" ) @@ -27296,7 +26608,7 @@ def f(): unit.op, Instruction::StoreName { namei } if class_code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__firstlineno__" ) @@ -27448,7 +26760,7 @@ class C: unit.op, Instruction::StoreName { namei } if code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__doc__" ) @@ -27474,7 +26786,7 @@ class C: unit.op, Instruction::StoreName { namei } if class_code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__doc__" ) @@ -27513,7 +26825,7 @@ class C: unit.op, Instruction::StoreName { namei } if code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__doc__" ) @@ -27537,7 +26849,7 @@ class C: unit.op, Instruction::StoreName { namei } if class_code.names - [namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) as usize] + [namei.get(OpArg::new(u32::from(u8::from(unit.arg))))] .as_str() == "__doc__" ) @@ -27651,6 +26963,62 @@ def outer(): ); } + #[test] + fn generic_definition_qualnames_use_the_enclosing_scope() { + let code = compile_exec( + "\ +def annotate[T](x: T): + pass + +def outer(): + global publish, Publish + async def publish[T](x: T): + pass + class Publish[T]: + pass + def private[T](x: T): + pass + +class Owner: + global _Owner__method + def __method[T](x: T): + pass +", + ); + let annotation = |generic: &str| { + let generic = find_code(&code, generic).unwrap(); + find_direct_child_code(generic, "__annotate__") + .unwrap() + .qualname + .as_str() + }; + for (name, expected) in [ + ("publish", "publish"), + ("Publish", "Publish"), + ("private", "outer..private"), + ("__method", "__method"), + ] { + assert_eq!(find_code(&code, name).unwrap().qualname, expected); + } + for (name, expected) in [ + ("", "__annotate__"), + ( + "", + "outer..publish.__annotate__", + ), + ( + "", + "outer..private.__annotate__", + ), + ( + "", + "Owner.__method.__annotate__", + ), + ] { + assert_eq!(annotation(name), expected); + } + } + #[test] fn relative_future_import_does_not_enable_annotations_like_cpython() { let code = compile_exec( @@ -28086,7 +27454,7 @@ def bug(): && entry.depth == 1 && entry.push_lasti }), - "CPython codegen_try_except() stores the exception alias before the inner SETUP_CLEANUP, so NOT_TAKEN and the alias store stay covered by the outer cleanup entry; entries={entries:?}, instructions={:?}", + "CPython 3.15.2 keeps the normalized branch and alias store covered by the outer cleanup entry; entries={entries:?}, instructions={:?}", bug.instructions ); } @@ -28447,7 +27815,7 @@ def f(self): window, [ Instruction::PopExcept, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreName { .. } | Instruction::StoreFast { .. }, Instruction::DeleteName { .. } | Instruction::DeleteFast { .. }, Instruction::JumpForward { .. }, @@ -28556,8 +27924,7 @@ def f(self, x): return None; }; let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - (f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "fail") - .then_some(idx) + (f.names[load_attr.name_idx()].as_str() == "fail").then_some(idx) }) .collect::>(); assert!( @@ -28898,7 +28265,13 @@ def f(cond, obj, xs, E): _ => None, }; - for name in ["xs", "obj", "x"] { + assert!(normal_tail.iter().any(|unit| { + matches!(unit.op, Instruction::LoadFast { .. }) && load_name(unit) == Some("xs") + })); + assert!(!normal_tail.iter().any(|unit| { + matches!(unit.op, Instruction::LoadFastBorrow { .. }) && load_name(unit) == Some("xs") + })); + for name in ["obj", "x"] { assert!( normal_tail .iter() @@ -29202,7 +28575,7 @@ def f(self, typ, dat): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "debug" + f.names[load_attr.name_idx()].as_str() == "debug" } _ => false, }) @@ -29212,7 +28585,7 @@ def f(self, typ, dat): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "_mesg" + f.names[load_attr.name_idx()].as_str() == "_mesg" } _ => false, }) @@ -29259,7 +28632,7 @@ def f(self, literal): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "send" + f.names[load_attr.name_idx()].as_str() == "send" } _ => false, }) @@ -29270,7 +28643,7 @@ def f(self, literal): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "send" + f.names[load_attr.name_idx()].as_str() == "send" } _ => false, }) @@ -29321,8 +28694,7 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "do_disassembly_test" + f.names[load_attr.name_idx()].as_str() == "do_disassembly_test" } _ => false, }) @@ -29405,9 +28777,9 @@ def f(obj): [ Instruction::Resume { .. }, Instruction::LoadFastBorrow { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::BuildSlice { .. }, Instruction::BinaryOp { .. }, Instruction::ReturnValue, @@ -29432,7 +28804,7 @@ def f(obj, step): .zip(&f.locations) .filter_map(|(unit, (location, end_location))| { let op = match unit.op { - Instruction::LoadConst { .. } => "LOAD_CONST", + Instruction::LoadCommonConstant { .. } => "LOAD_CONST", Instruction::BuildSlice { .. } => "BUILD_SLICE", _ => return None, }; @@ -29561,7 +28933,7 @@ def f(obj): Instruction::Resume { .. }, Instruction::LoadFastBorrow { .. }, Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::BinarySlice, Instruction::ReturnValue, ] @@ -29727,9 +29099,9 @@ def f(self, xs, ys, cm1, cm2): [ Instruction::EndFor, Instruction::PopIter, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, ] @@ -29745,9 +29117,9 @@ def f(self, xs, ys, cm1, cm2): Instruction::EndFor, Instruction::PopIter, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, ] @@ -29775,15 +29147,9 @@ def f(p, s): .filter(|unit| { matches!( unit.op, - Instruction::LoadConst { consti } - if matches!( - f.constants.get( - consti - .get(OpArg::new(u32::from(u8::from(unit.arg)))) - .as_usize() - ), - Some(ConstantData::Integer { value }) if value == &BigInt::from(-1) - ) + Instruction::LoadCommonConstant { idx } + if idx.get(OpArg::new(u32::from(u8::from(unit.arg)))) + == bytecode::CommonConstant::MinusOne ) }) .count(); @@ -29816,18 +29182,21 @@ def f(xs): .collect(); assert!( - units.windows(4).any(|window| { + units.windows(5).any(|window| { matches!( window[0].op, - Instruction::LoadConst { .. } | Instruction::LoadSmallInt { .. } + Instruction::LoadCommonConstant { idx } + if idx.get(OpArg::new(u32::from(u8::from(window[0].arg)))) + == bytecode::CommonConstant::MinusOne ) && matches!( window[1].op, Instruction::Swap { i } - if i.get(OpArg::new(u32::from(u8::from(window[1].arg)))) == 2 + if i.get(OpArg::new(u32::from(u8::from(window[1].arg)))) == 3 ) && matches!(window[2].op, Instruction::PopTop) - && matches!(window[3].op, Instruction::ReturnValue) + && matches!(window[3].op, Instruction::PopTop) + && matches!(window[4].op, Instruction::ReturnValue) }), - "expected CPython-style LOAD_CONST/SWAP/POP_TOP/RETURN_VALUE cleanup, got units={units:?}" + "expected CPython-style LOAD_COMMON_CONSTANT/SWAP 3/POP_TOP/POP_TOP/RETURN_VALUE cleanup, got units={units:?}" ); } @@ -29994,10 +29363,10 @@ def f(self): window, [ Instruction::PopExcept, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreFast { .. } | Instruction::StoreName { .. }, Instruction::DeleteFast { .. } | Instruction::DeleteName { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue, ] ) @@ -30038,10 +29407,10 @@ def f(onerror, err, OSError): window, [ Instruction::PopExcept, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreFast { .. } | Instruction::StoreName { .. }, Instruction::DeleteFast { .. } | Instruction::DeleteName { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue, ] ) @@ -30082,10 +29451,10 @@ def f(self, module_name, ModuleNotFoundError): window, [ Instruction::PopExcept, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreFast { .. } | Instruction::StoreName { .. }, Instruction::DeleteFast { .. } | Instruction::DeleteName { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue, ] ) @@ -30372,12 +29741,12 @@ def f(cm, registry, altkey): window, [ Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::ReturnValue, ] ) @@ -30419,9 +29788,9 @@ def f(a, b, path): Instruction::PopExcept, Instruction::Reraise { .. }, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -30625,7 +29994,7 @@ def f(self, logger): [ Instruction::PopTop, Instruction::PopExcept, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreFast { .. }, Instruction::DeleteFast { .. }, Instruction::JumpBackwardNoInterrupt { .. }, @@ -30825,9 +30194,7 @@ def f(x): .filter(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - load_attr.is_method() - && f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "join" + load_attr.is_method() && f.names[load_attr.name_idx()].as_str() == "join" } _ => false, }) @@ -31629,7 +30996,7 @@ class C: .filter_map(|unit| match unit.op { Instruction::LoadName { namei } => { let idx = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - Some(class_code.names[usize::try_from(idx).unwrap()].as_str()) + Some(class_code.names[idx].as_str()) } _ => None, }) @@ -32200,7 +31567,7 @@ def f(): } #[test] - fn constant_list_iterable_uses_tuple() { + fn constant_list_iterable_keeps_list_before_saved_locals() { let code = compile_exec( "\ def f(): @@ -32209,26 +31576,17 @@ def f(): ); let f = find_code(&code, "f").expect("missing function code"); - assert!( - !f.instructions - .iter() - .any(|unit| matches!(unit.op, Instruction::BuildList { .. })), - "constant list iterable should avoid BUILD_LIST before GET_ITER" - ); + assert!(f.instructions.iter().any(|unit| { + matches!(unit.op, Instruction::BuildList { count } + if count.get(OpArg::new(u32::from(u8::from(unit.arg)))) == 1) + })); assert!(f.constants.iter().any(|constant| matches!( constant, ConstantData::Tuple { elements } - if matches!( - elements.as_slice(), - [ConstantData::Tuple { elements: inner }] - if matches!( - inner.as_slice(), - [ - ConstantData::Integer { .. }, - ConstantData::Integer { .. } - ] - ) - ) + if matches!(elements.as_slice(), [ + ConstantData::Integer { value: first }, + ConstantData::Integer { value: second }, + ] if first == &BigInt::from(1) && second == &BigInt::from(2)) ))); } @@ -32248,9 +31606,9 @@ def f(): matches!(constants[0], ConstantData::Str { value } if value.to_string() == "a"), "CPython emits list elements as LOAD_CONST before flowgraph folds GET_ITER lists" ); - assert!(matches!(constants[1], ConstantData::None)); + assert_eq!(constants.len(), 2); assert!(matches!( - constants[2], + constants[1], ConstantData::Tuple { elements } if matches!( elements.as_slice(), @@ -32470,18 +31828,17 @@ def f(g, kwargs, ns): ); let f = find_code(&code, "f").expect("missing function code"); let constants = f.constants.iter().collect::>(); - assert_eq!(constants.len(), 3); + assert_eq!(constants.len(), 2); assert!( matches!(constants[0], ConstantData::Str { value } if value.to_string() == "T") - && matches!(constants[1], ConstantData::None) - && matches!(constants[2], ConstantData::Tuple { elements } if elements.is_empty()), + && matches!(constants[1], ConstantData::Tuple { elements } if elements.is_empty()), "CPython emits BUILD_TUPLE 0 for CALL_FUNCTION_EX args and folds it after earlier constants" ); } #[test] - fn large_constant_list_iterable_keeps_streaming_list_build() { + fn large_constant_list_iterable_folds_to_tuple_like_cpython() { let source = format!( "def f():\n for x in [{}]:\n pass\n", (0..=STACK_USE_GUIDELINE) @@ -32492,19 +31849,47 @@ def f(g, kwargs, ns): let code = compile_exec(&source); let f = find_code(&code, "f").expect("missing function code"); + // Final CPython folds the stack-limited BUILD_LIST/LIST_APPEND sequence + // before GET_ITER, preserving every constant in its original order. + let tuple_loads = f + .instructions + .iter() + .filter_map(|unit| match unit.op { + Instruction::LoadConst { consti } => { + match &f.constants[consti.get(OpArg::new(u32::from(u8::from(unit.arg))))] { + ConstantData::Tuple { elements } => Some(elements), + _ => None, + } + } + _ => None, + }) + .collect::>(); + assert_eq!(tuple_loads.len(), 1); + let elements = tuple_loads[0]; + assert_eq!( + elements.len(), + usize::try_from(STACK_USE_GUIDELINE + 1).unwrap() + ); + for (i, element) in elements.iter().enumerate() { + assert!(matches!( + element, + ConstantData::Str { value } if value.to_string() == format!("v{i}") + )); + } assert!( - f.instructions - .iter() - .any(|unit| matches!(unit.op, Instruction::BuildList { .. })), - "large list iterable should keep CPython streaming BUILD_LIST form, got instructions={:?}", + !f.instructions.iter().any(|unit| matches!( + unit.op, + Instruction::BuildList { .. } | Instruction::ListAppend { .. } + )), + "constant iterable should use the folded tuple, got instructions={:?}", f.instructions ); - assert!( + assert_eq!( f.instructions .iter() - .any(|unit| matches!(unit.op, Instruction::ListAppend { .. })), - "large list iterable should use LIST_APPEND streaming form, got instructions={:?}", - f.instructions + .filter(|unit| matches!(unit.op, Instruction::GetIter { .. })) + .count(), + 1 ); } @@ -32519,10 +31904,10 @@ def f(): let f = find_code(&code, "f").expect("missing function code"); assert!( - !f.instructions + f.instructions .iter() .any(|unit| matches!(unit.op, Instruction::BuildSet { .. })), - "constant set iterable should avoid BUILD_SET before GET_ITER" + "constant set iterable should build the set before saved locals and GET_ITER" ); assert!(f.constants.iter().any(|constant| matches!( constant, @@ -32702,13 +32087,13 @@ def f(a, b, c): assert!( f.instructions .iter() - .any(|unit| matches!(unit.op, Instruction::GetIter)), + .any(|unit| matches!(unit.op, Instruction::GetIter { .. })), "expected GET_ITER in for loop" ); } #[test] - fn comprehension_single_list_iterable_uses_tuple() { + fn comprehension_single_list_iterable_keeps_list_before_saved_locals() { let code = compile_exec( "\ def g(): @@ -32724,37 +32109,20 @@ def g(): .collect(); assert!( - ops.windows(2).any(|window| { + ops.windows(6).any(|window| { matches!( window, - [Instruction::BuildTuple { .. }, Instruction::GetIter] + [ + Instruction::BuildList { .. }, + Instruction::LoadFastAndClear { .. }, + Instruction::Swap { .. }, + Instruction::BuildList { .. }, + Instruction::Swap { .. }, + Instruction::GetIter { .. }, + ] ) }), - "expected BUILD_TUPLE before GET_ITER for single-item list iterable in comprehension, got ops={ops:?}" - ); - } - - #[test] - fn comprehension_list_iterable_build_uses_iter_location_like_cpython() { - let code = compile_exec( - "\ -async def f(i): - return i - -async def run_list(): - return [await c for c in [f(1), f(41)]] -", - ); - let run_list = find_code(&code, "run_list").expect("missing run_list code"); - assert_eq!( - run_list.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xdc, 0x1e, 0x1f, 0xa0, 0x01, 0x9b, 0x64, 0xa4, 0x41, 0xa0, - 0x62, 0xa3, 0x45, 0x99, 0x5d, 0xd3, 0x0b, 0x2b, 0x99, 0x5d, 0x98, 0x01, 0x8f, 0x47, - 0x8a, 0x47, 0x99, 0x5d, 0xd1, 0x0b, 0x2b, 0xd0, 0x04, 0x2b, 0x89, 0x47, 0xf9, 0xd2, - 0x0b, 0x2b, 0xf9, - ], - "CPython codegen_comprehension_iter() emits GET_ITER at LOC(comp->iter)" + "expected BUILD_LIST before saved locals, output collection, and GET_ITER for single-item list iterable in comprehension, got ops={ops:?}" ); } @@ -32767,12 +32135,13 @@ def f(self): ", ); let f = find_code(&code, "f").expect("missing f code"); - let get_iter_positions: Vec<_> = f + let genexpr = find_code(f, "").expect("missing genexpr code"); + let get_iter_positions: Vec<_> = genexpr .instructions .iter() - .zip(&f.locations) + .zip(&genexpr.locations) .filter_map(|(unit, (location, end_location))| { - matches!(unit.op, Instruction::GetIter).then_some(( + matches!(unit.op, Instruction::GetIter { .. }).then_some(( location.line.get(), location.character_offset.get(), end_location.line.get(), @@ -32787,30 +32156,6 @@ def f(self): ); } - #[test] - fn inlined_comprehension_backedges_use_element_location_like_cpython() { - let code = compile_exec( - "\ -async def f(i): - return i - -async def run_list(): - return [s for c in [f(''), f('abc')] for s in await c] -", - ); - let run_list = find_code(&code, "run_list").expect("missing run_list code"); - assert_eq!( - run_list.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xdc, 0x18, 0x19, 0x98, 0x22, 0x9b, 0x05, 0x9c, 0x71, 0xa0, - 0x15, 0x9b, 0x78, 0xd1, 0x17, 0x28, 0xd4, 0x0b, 0x3a, 0xd1, 0x17, 0x28, 0x90, 0x21, - 0xb7, 0x27, 0xb2, 0x27, 0xa8, 0x51, 0x8a, 0x41, 0xb1, 0x27, 0x89, 0x41, 0xd1, 0x17, - 0x28, 0xd2, 0x0b, 0x3a, 0xd0, 0x04, 0x3a, 0xb1, 0x27, 0xf9, 0xd3, 0x0b, 0x3a, 0xf9, - ], - "CPython codegen_sync_comprehension_generator() emits comprehension backedges at elt_loc" - ); - } - #[test] fn nested_dict_comprehension_outer_backedge_uses_key_location_like_cpython() { let code = compile_exec( @@ -32903,53 +32248,7 @@ def f(fields): } #[test] - fn inlined_async_comprehension_end_async_for_uses_comprehension_location_like_cpython() { - let code = compile_exec( - "\ -async def f(it): - for i in it: - yield i - -async def run_list(): - return [i + 1 async for i in f([10, 20])] -", - ); - let run_list = find_code(&code, "run_list").expect("missing run_list code"); - assert_eq!( - run_list.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xdc, 0x21, 0x22, 0xa0, 0x42, 0xa8, 0x02, 0xa0, 0x38, 0xa4, - 0x1b, 0xd7, 0x0b, 0x2d, 0xd3, 0x0b, 0x2d, 0x98, 0x41, 0x90, 0x01, 0x8f, 0x45, 0x88, - 0x45, 0xd4, 0x0b, 0x2d, 0xd0, 0x04, 0x2d, 0xf9, 0xd2, 0x0b, 0x2d, 0xf9, - ], - "CPython codegen_async_comprehension_generator() emits END_ASYNC_FOR at comprehension loc" - ); - } - - #[test] - fn async_for_anext_sequence_uses_statement_location_like_cpython() { - let code = compile_exec( - "\ -async def f(source, buffer): - async for i1, i2 in source(): - buffer.append(i1 + i2) -", - ); - let f = find_code(&code, "f").expect("missing f code"); - assert_eq!( - f.linetable.as_ref(), - &[ - 0xe9, 0x00, 0x80, 0x00, 0xd9, 0x18, 0x1e, 0x9c, 0x08, 0xf7, 0x00, 0x01, 0x05, 0x1f, - 0xf0, 0x00, 0x01, 0x05, 0x1f, 0x89, 0x66, 0x88, 0x62, 0xd8, 0x08, 0x0e, 0x8f, 0x0d, - 0x89, 0x0d, 0x90, 0x62, 0x95, 0x67, 0xd6, 0x08, 0x1e, 0xf1, 0x03, 0x01, 0x05, 0x1f, - 0x9a, 0x08, 0xf9, - ], - "CPython codegen_async_for() emits GET_ANEXT/yield-from scaffolding at LOC(s)" - ); - } - - #[test] - fn nested_comprehension_list_iterable_uses_tuple() { + fn nested_comprehension_list_iterable_keeps_list_before_saved_locals() { let code = compile_exec( "\ def f(): @@ -32965,13 +32264,20 @@ def f(): .collect(); assert!( - ops.windows(2).any(|window| { + ops.windows(6).any(|window| { matches!( window, - [Instruction::BuildTuple { .. }, Instruction::GetIter] + [ + Instruction::BuildList { .. }, + Instruction::LoadFastAndClear { .. }, + Instruction::Swap { .. }, + Instruction::BuildList { .. }, + Instruction::Swap { .. }, + Instruction::GetIter { .. }, + ] ) }), - "expected BUILD_TUPLE before GET_ITER for nested list iterable in comprehension, got ops={ops:?}" + "expected BUILD_LIST before saved locals, output collection, and GET_ITER for nested list iterable in comprehension, got ops={ops:?}" ); } @@ -32989,11 +32295,11 @@ def f(): .iter() .filter(|unit| matches!(unit.op, Instruction::ForIter { .. })) .count(); - let has_map_add_depth_2 = f.instructions.iter().any(|unit| { + let has_map_add_depth_3 = f.instructions.iter().any(|unit| { matches!( unit.op, Instruction::MapAdd { i } - if i.get(OpArg::new(u32::from(u8::from(unit.arg)))) == 2 + if i.get(OpArg::new(u32::from(u8::from(unit.arg)))) == 3 ) }); @@ -33003,8 +32309,8 @@ def f(): f.instructions ); assert!( - has_map_add_depth_2, - "assignment-idiom dictcomp should use MAP_ADD depth 2, got instructions={:?}", + has_map_add_depth_3, + "assignment-idiom dictcomp should use MAP_ADD depth 3, got instructions={:?}", f.instructions ); assert!( @@ -33322,9 +32628,9 @@ async def f(cm, source, tgt): [ Instruction::EndAsyncFor, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -33487,19 +32793,29 @@ _pathseps_with_colon = {f':{s}' for s in path_separators} .filter(|op| !matches!(op, Instruction::Cache)) .collect(); - let load_name_path = ops - .windows(2) - .any(|window| matches!(window, [Instruction::LoadName { .. }, Instruction::GetIter])); + let load_name_path = ops.windows(6).any(|window| { + matches!( + window, + [ + Instruction::LoadName { .. }, + Instruction::LoadFastAndClear { .. }, + Instruction::Swap { .. }, + Instruction::BuildSet { .. }, + Instruction::Swap { .. }, + Instruction::GetIter { .. } + ] + ) + }); assert!( load_name_path, - "expected outer iterable to stay a NAME lookup before GET_ITER, got ops={ops:?}" + "expected NAME lookup before locals are saved and iterator acquisition after collection construction, got ops={ops:?}" ); assert!( !ops.windows(2).any(|window| matches!( window, [ Instruction::LoadFast { .. } | Instruction::LoadFastCheck { .. }, - Instruction::GetIter + Instruction::GetIter { .. } ] )), "module local outer iterable should not become a fast local, got ops={ops:?}" @@ -33605,33 +32921,12 @@ def f(seq, value): assert!(f.instructions.iter().any(|unit| match unit.op { Instruction::StoreGlobal { namei } => { let idx = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(idx).unwrap()] == "G" + f.names[idx] == "G" } _ => false, })); } - #[test] - fn namedexpr_copy_uses_namedexpr_location_like_cpython() { - let code = compile_exec( - "\ -def outer(): - a = 10 - def spam(): - nonlocal a - (a := 20) -", - ); - let spam = find_code(&code, "spam").expect("missing spam code"); - - // CPython 3.14 NamedExpr_kind emits COPY at LOC(named expression), - // between visiting the value and visiting the target. - assert_eq!( - spam.linetable.as_ref(), - &[0xf8, 0x80, 0x00, 0xe0, 0x0e, 0x10, 0x88, 0x17, 0x8b, 0x11,] - ); - } - #[test] fn genexpr_namedexpr_target_is_cell_not_fast_local() { let code = compile_exec( @@ -33823,13 +33118,15 @@ values = ( "CPython codegen_stmt_expr() prints and pops interactive expressions; it does not preserve the final expression as the code object's return value, got ops={ops:?}" ); let Some(load_none) = ops.iter().rev().nth(1) else { - panic!("missing final LOAD_CONST None before RETURN_VALUE, got ops={ops:?}"); + panic!("missing final LOAD_COMMON_CONSTANT None before RETURN_VALUE, got ops={ops:?}"); }; - let Instruction::LoadConst { consti } = load_none.op else { - panic!("missing final LOAD_CONST None before RETURN_VALUE, got ops={ops:?}"); + let Instruction::LoadCommonConstant { idx } = load_none.op else { + panic!("missing final LOAD_COMMON_CONSTANT None before RETURN_VALUE, got ops={ops:?}"); }; - let constant = &code.constants[consti.get(OpArg::new(u32::from(u8::from(load_none.arg))))]; - assert!(matches!(constant, ConstantData::None)); + assert_eq!( + idx.get(OpArg::new(u32::from(u8::from(load_none.arg)))), + bytecode::CommonConstant::None + ); assert!(matches!( ops.last().map(|unit| unit.op), Some(Instruction::ReturnValue) @@ -35155,7 +34452,7 @@ def f(items): let get_iter_idx = ops .iter() - .rposition(|op| matches!(op, Instruction::GetIter)) + .rposition(|op| matches!(op, Instruction::GetIter { .. })) .expect("missing GET_ITER"); assert!( matches!(ops[get_iter_idx - 1], Instruction::LoadFast { .. }), @@ -35178,7 +34475,7 @@ def f(items): } #[test] - fn plain_pass_before_for_tail_keeps_borrows() { + fn plain_pass_before_for_tail_keeps_owned_iterator_input() { let code = compile_exec( "\ def f(xs): @@ -35198,11 +34495,11 @@ def f(xs): let get_iter_idx = ops .iter() - .position(|op| matches!(op, Instruction::GetIter)) + .position(|op| matches!(op, Instruction::GetIter { .. })) .expect("missing GET_ITER"); assert!( - matches!(ops[get_iter_idx - 1], Instruction::LoadFastBorrow { .. }), - "plain pass before for-tail should keep borrowed iterable load, got ops={ops:?}" + matches!(ops[get_iter_idx - 1], Instruction::LoadFast { .. }), + "plain pass before for-tail should keep an owned iterable load for GET_ITER, got ops={ops:?}" ); } @@ -35367,7 +34664,7 @@ def f(s, size, encodeSetO, encodeWhiteSpace): window, [ Instruction::PopTop, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreFast { .. }, Instruction::JumpBackward { .. } | Instruction::JumpBackwardNoInterrupt { .. }, @@ -35860,7 +35157,7 @@ def f(cls, _FIELDS, _PARAMS): Instruction::NotTaken, Instruction::JumpBackward { .. } | Instruction::JumpBackwardNoInterrupt { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::StoreFast { .. }, ] ) @@ -35896,9 +35193,9 @@ def f(it): Instruction::PopJumpIfFalse { .. }, Instruction::NotTaken, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, Instruction::JumpBackward { .. } @@ -35933,9 +35230,9 @@ async def foo(): matches!( window, [ - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::GetAwaitable { .. }, ] @@ -35949,9 +35246,9 @@ async def foo(): window, [ Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::GetAwaitable { .. }, ] @@ -35998,8 +35295,8 @@ async def foo(self): Instruction::PopExcept, Instruction::Reraise { .. }, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -36034,8 +35331,8 @@ def f(): Instruction::PopExcept, Instruction::Reraise { .. }, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -36736,7 +36033,7 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "waiter" + f.names[load_attr.name_idx()].as_str() == "waiter" } _ => false, }) @@ -36799,8 +36096,7 @@ def f(self, fut=None): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "add_done_callback" + f.names[load_attr.name_idx()].as_str() == "add_done_callback" } _ => false, }) @@ -36862,7 +36158,7 @@ def f(self, fut=None): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "recv" + f.names[load_attr.name_idx()].as_str() == "recv" } _ => false, }) @@ -36872,8 +36168,7 @@ def f(self, fut=None): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "add_done_callback" + f.names[load_attr.name_idx()].as_str() == "add_done_callback" } _ => false, }) @@ -36933,7 +36228,7 @@ def f(self, cm, p, platform): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == name + f.names[load_attr.name_idx()].as_str() == name } _ => false, }) @@ -37855,7 +37150,7 @@ async def wait_for(fut, timeout): matches!(window[0].op, Instruction::LoadFastBorrow { .. }) && loaded_names(window[0]).iter().any(|name| name == "fut") && matches!(window[1].op, Instruction::LoadAttr { namei } - if f.names[usize::try_from(namei.get(OpArg::new(u32::from(u8::from(window[1].arg)))).name_idx()).unwrap()] == "result") + if f.names[namei.get(OpArg::new(u32::from(u8::from(window[1].arg)))).name_idx()] == "result") && matches!(window[2].op, Instruction::Call { .. }) && matches!(window[3].op, Instruction::ReturnValue) }), @@ -38171,7 +37466,7 @@ def f(self, document): } #[test] - fn from_import_after_conditional_store_join_uses_strong_prefix_loads() { + fn from_import_after_conditional_store_join_uses_borrowed_prefix_loads() { let code = compile_exec( "\ def f(x): @@ -38197,15 +37492,18 @@ def f(x): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "rpartition" + f.names[load_attr.name_idx()].as_str() == "rpartition" } _ => false, }) .expect("missing rpartition LOAD_ATTR"); assert!( - matches!(ops[rpartition_idx - 1].op, Instruction::LoadFast { .. }), - "CPython optimize_load_fast() keeps the conditional-store join receiver strong before IMPORT_FROM, got ops={ops:?}" + matches!( + ops[rpartition_idx - 1].op, + Instruction::LoadFastBorrow { .. } + ), + "CPython optimize_load_fast() borrows the conditional-store join receiver before IMPORT_FROM, got ops={ops:?}" ); } @@ -38236,7 +37534,7 @@ def f(x): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "rpartition" + f.names[load_attr.name_idx()].as_str() == "rpartition" } _ => false, }) @@ -38275,7 +37573,7 @@ def f(): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "argv" + f.names[load_attr.name_idx()].as_str() == "argv" } _ => false, }) @@ -38340,9 +37638,25 @@ def f(output): warm_path .iter() .filter_map(load_fast_name) - .all(|name| name != "row" && name != "result"), - "terminal-except inlined comprehension warm path should keep CPython-style borrowed row/result loads, got warm_path={warm_path:?}" + .all(|name| name != "row"), + "terminal-except inlined comprehension warm path should keep CPython-style borrowed row loads, got warm_path={warm_path:?}" + ); + assert_eq!( + warm_path + .iter() + .filter_map(load_fast_name) + .filter(|name| *name == "result") + .count(), + 1 ); + let result_iterable = warm_path + .iter() + .position(|unit| load_fast_name(unit) == Some("result")) + .unwrap(); + assert!(matches!( + warm_path[result_iterable + 1].op, + Instruction::LoadFastAndClear { .. } + )); for name in ["row", "result"] { assert!( warm_path @@ -38537,7 +37851,7 @@ def f(self): .position(|unit| match unit.op { Instruction::StoreAttr { namei } => { let namei = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(namei).unwrap()].as_str() == "PROTOCOL_VERSION" + f.names[namei].as_str() == "PROTOCOL_VERSION" } _ => false, }) @@ -38637,7 +37951,7 @@ def f(flags, A, B, stop): Instruction::PopJumpIfTrue { .. }, Instruction::NotTaken, Instruction::JumpBackward { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -39624,7 +38938,7 @@ def f(self, rawdata, j, match): } #[test] - fn join_store_global_before_import_keeps_strong_load_fast() { + fn join_store_global_before_import_keeps_borrowed_load_fast() { let code = compile_exec( "\ def f(module=None): @@ -39648,12 +38962,12 @@ def f(module=None): matches!( window, [ - Instruction::LoadFast { .. }, + Instruction::LoadFastBorrow { .. }, Instruction::StoreGlobal { .. }, ] ) }), - "expected CPython-style strong LOAD_FAST before join STORE_GLOBAL followed by import, got ops={ops:?}" + "expected CPython-style LOAD_FAST_BORROW before join STORE_GLOBAL followed by import, got ops={ops:?}" ); } @@ -39687,7 +39001,7 @@ def f(p, errors, s, pos, look, final, escape_start, st): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "append" + f.names[load_attr.name_idx()].as_str() == "append" } _ => false, }) @@ -39834,7 +39148,7 @@ def f(args): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "_setoption" + f.names[load_attr.name_idx()].as_str() == "_setoption" } _ => false, }) @@ -39938,8 +39252,7 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "get_disassemble_as_string" + f.names[load_attr.name_idx()].as_str() == "get_disassemble_as_string" } _ => false, }) @@ -40034,7 +39347,7 @@ def f(self, cm, E): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "x" + f.names[load_attr.name_idx()].as_str() == "x" } _ => false, }) @@ -40101,7 +39414,7 @@ def f(self, b, BlockingIOError): .. }, CodeUnit { - op: Instruction::LoadConst { .. }, + op: Instruction::LoadCommonConstant { .. }, .. }, ] @@ -40148,9 +39461,9 @@ def f(self): window, [ Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, ] @@ -40187,9 +39500,9 @@ def f(cm, source): window, [ Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, Instruction::PopTop, ] @@ -40225,9 +39538,9 @@ def f(cm, xs, g): [ Instruction::EndFor, Instruction::PopIter, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -40242,9 +39555,9 @@ def f(cm, xs, g): Instruction::EndFor, Instruction::PopIter, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -40321,9 +39634,9 @@ def f(cm1, cm2, g, E): Instruction::Copy { .. }, Instruction::PopExcept, Instruction::Reraise { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -40338,9 +39651,9 @@ def f(cm1, cm2, g, E): Instruction::PopExcept, Instruction::Reraise { .. }, Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, ] ) }), @@ -40372,9 +39685,9 @@ def f(cm, dst): window, [ Instruction::Nop, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::Call { .. }, ] ) @@ -40423,7 +39736,7 @@ def f(self, fd, file, closefd, owned_fd, OSError, AttributeError, errno, os, sta Instruction::LoadAttr { namei } => { let arg = OpArg::new(u32::from(u8::from(unit.arg))); let load_attr = namei.get(arg); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == expected + f.names[load_attr.name_idx()].as_str() == expected } _ => false, }; @@ -40436,7 +39749,7 @@ def f(self, fd, file, closefd, owned_fd, OSError, AttributeError, errno, os, sta .position(|unit| match unit.op { Instruction::StoreAttr { namei } => { let arg = OpArg::new(u32::from(u8::from(unit.arg))); - f.names[usize::try_from(namei.get(arg)).unwrap()].as_str() == "_fd" + f.names[namei.get(arg)].as_str() == "_fd" } _ => false, }) @@ -40496,7 +39809,7 @@ def f(self, cm, E): .collect(); let get_iter = instructions .iter() - .position(|unit| matches!(unit.op, Instruction::GetIter)) + .position(|unit| matches!(unit.op, Instruction::GetIter { .. })) .expect("missing loop iterator"); let handler_start = instructions .iter() @@ -40546,7 +39859,7 @@ def f(resources, valid_zones, TZPATH, os): .collect(); let get_iter = instructions .iter() - .position(|unit| matches!(unit.op, Instruction::GetIter)) + .position(|unit| matches!(unit.op, Instruction::GetIter { .. })) .expect("missing post-try loop iterator"); let tail = &instructions[get_iter.saturating_sub(1)..]; let load_fast_name = |unit: &&bytecode::CodeUnit| match unit.op { @@ -40608,8 +39921,7 @@ def f(self, fobj, unlink, TESTFN, C): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "assertEqual" + f.names[load_attr.name_idx()].as_str() == "assertEqual" } _ => false, }) @@ -40678,7 +39990,7 @@ def f(self, os, alive_r, alive_w, address, pid): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "close" + f.names[load_attr.name_idx()].as_str() == "close" } _ => false, }) @@ -40732,7 +40044,7 @@ def f(resource, desired_fds, max_fds): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "getrlimit" + f.names[load_attr.name_idx()].as_str() == "getrlimit" } _ => false, }) @@ -40962,7 +40274,7 @@ def f(self, cm): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "y" + f.names[load_attr.name_idx()].as_str() == "y" } _ => false, }) @@ -41002,7 +40314,7 @@ def f(self, factory): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "join" + f.names[load_attr.name_idx()].as_str() == "join" } _ => false, }) @@ -41044,7 +40356,7 @@ def f(self, cm, E): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "shutdown" + f.names[load_attr.name_idx()].as_str() == "shutdown" } _ => false, }) @@ -41088,8 +40400,7 @@ def f(self, cm, E, obj): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "saved_details" + f.names[load_attr.name_idx()].as_str() == "saved_details" } _ => false, }) @@ -41138,8 +40449,7 @@ def f(self, cm): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "_exit_callbacks" + f.names[load_attr.name_idx()].as_str() == "_exit_callbacks" } _ => false, }) @@ -41185,8 +40495,7 @@ def f(self, arc, tmp_filename, new_mode): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "check_context" + f.names[load_attr.name_idx()].as_str() == "check_context" } _ => false, }) @@ -41244,7 +40553,7 @@ def f(self, fd, appending, errno): .position(|unit| match unit.op { Instruction::StoreAttr { namei } => { let arg = OpArg::new(u32::from(u8::from(unit.arg))); - f.names[usize::try_from(namei.get(arg)).unwrap()].as_str() == "_fd" + f.names[namei.get(arg)].as_str() == "_fd" } _ => false, }) @@ -41284,7 +40593,7 @@ def f(self, cm): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "x" + f.names[load_attr.name_idx()].as_str() == "x" } _ => false, }) @@ -41339,7 +40648,7 @@ def f(re, proc, unittest): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "search" + f.names[load_attr.name_idx()].as_str() == "search" } _ => false, }) @@ -41612,7 +40921,7 @@ def f(charset, failobj, E): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "lower" + f.names[load_attr.name_idx()].as_str() == "lower" } _ => false, }) @@ -41671,7 +40980,7 @@ def f(events, callback, args, self, sig, signal): .. }, bytecode::CodeUnit { - op: Instruction::LoadConst { .. }, + op: Instruction::LoadCommonConstant { .. }, .. }, bytecode::CodeUnit { @@ -41708,8 +41017,7 @@ def f(self, OSError): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let arg = OpArg::new(u32::from(u8::from(unit.arg))); - f.names[usize::try_from(namei.get(arg).name_idx()).unwrap()].as_str() - == "verify_request" + f.names[namei.get(arg).name_idx()].as_str() == "verify_request" } _ => false, }) @@ -42068,7 +41376,7 @@ def f(self, E, Event): .position(|unit| match unit.op { Instruction::StoreAttr { namei } => { let arg = OpArg::new(u32::from(u8::from(unit.arg))); - f.names[usize::try_from(namei.get(arg)).unwrap()].as_str() == "keymap" + f.names[namei.get(arg)].as_str() == "keymap" } _ => false, }) @@ -42078,7 +41386,7 @@ def f(self, E, Event): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "insert" + f.names[load_attr.name_idx()].as_str() == "insert" } _ => false, }) @@ -42194,7 +41502,7 @@ def f(items, chunk, out, packI, Error): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "append" + f.names[load_attr.name_idx()].as_str() == "append" } _ => false, }) @@ -42308,7 +41616,7 @@ def f(items, decoded, b32rev): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "to_bytes" + f.names[load_attr.name_idx()].as_str() == "to_bytes" } _ => false, }) @@ -42766,7 +42074,7 @@ def f(pattern, prefix, get_prefix): .collect(); assert!( - ops.windows(7).any(|window| { + ops.windows(8).any(|window| { matches!( window, [ @@ -42774,8 +42082,9 @@ def f(pattern, prefix, get_prefix): Instruction::PopJumpIfTrue { .. }, Instruction::NotTaken, Instruction::PopTop, + Instruction::PopTop, Instruction::LoadFastBorrow { .. } | Instruction::LoadFast { .. }, - Instruction::LoadConst { .. }, + Instruction::LoadCommonConstant { .. }, Instruction::BuildTuple { .. }, ] ) @@ -43151,7 +42460,7 @@ def f(formatstr, args, output, overflowok): .position(|unit| match unit.op { Instruction::LoadGlobal { namei } => { let load_global = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_global >> 1).unwrap()].as_str() == "AssertionError" + f.names[load_global.name_idx()].as_str() == "AssertionError" } _ => false, }) @@ -43296,8 +42605,7 @@ def f(self, data, length): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == "data_received" + f.names[load_attr.name_idx()].as_str() == "data_received" } _ => false, }) @@ -43425,7 +42733,7 @@ async def f(self, cm): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "fail" + f.names[load_attr.name_idx()].as_str() == "fail" } _ => false, }) @@ -43466,7 +42774,7 @@ def f(self, cm): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "x" + f.names[load_attr.name_idx()].as_str() == "x" } _ => false, }) @@ -43572,16 +42880,16 @@ def f(self, obj, expected, buf): .collect(); let get_iter = instructions .iter() - .position(|unit| matches!(unit.op, Instruction::GetIter)) + .position(|unit| matches!(unit.op, Instruction::GetIter { .. })) .expect("missing GET_ITER"); assert!( matches!( instructions .get(get_iter.saturating_sub(1)) .map(|unit| unit.op), - Some(Instruction::LoadFastBorrow { .. }) + Some(Instruction::LoadFast { .. }) ), - "finally-protected loop without except resume should keep borrowed iterable load, got instructions={instructions:?}" + "finally-protected loop without except resume should keep the owned iterable load for GET_ITER, got instructions={instructions:?}" ); for attr_name in ["close", "open"] { @@ -43590,8 +42898,7 @@ def f(self, obj, expected, buf): .rposition(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() - == attr_name + f.names[load_attr.name_idx()].as_str() == attr_name } _ => false, }) @@ -43683,8 +42990,8 @@ def f(self, cls, fns): let load_global_name = |unit: &&CodeUnit, name: &str| match unit.op { Instruction::LoadGlobal { namei } => { let arg = OpArg::new(u32::from(u8::from(unit.arg))); - let load_global = namei.get(arg) >> 1; - f.names[usize::try_from(load_global).unwrap()].as_str() == name + let load_global = namei.get(arg).name_idx(); + f.names[load_global].as_str() == name } _ => false, }; @@ -43816,7 +43123,7 @@ def f(s, size, errors, final): match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - let name = f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str(); + let name = f.names[load_attr.name_idx()].as_str(); if name == "warn" { after_warn_attr = true; } @@ -43880,7 +43187,7 @@ def f(self, exc_type, CRLF, OSError): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "_mesg" + f.names[load_attr.name_idx()].as_str() == "_mesg" } _ => false, }) @@ -43917,14 +43224,30 @@ async def name_4(): else { panic!("missing GET_AITER in name_4"); }; - let prev = &name_4.instructions[get_aiter_pos - 1]; + assert!(matches!( + name_4.instructions[get_aiter_pos - 4].op, + Instruction::LoadFastAndClear { .. } + )); + assert!(matches!( + name_4.instructions[get_aiter_pos - 3].op, + Instruction::Swap { .. } + )); + assert!(matches!( + name_4.instructions[get_aiter_pos - 2].op, + Instruction::BuildMap { .. } + )); + assert!(matches!( + name_4.instructions[get_aiter_pos - 1].op, + Instruction::Swap { .. } + )); + let prev = &name_4.instructions[get_aiter_pos - 5]; assert!( matches!( prev.op, Instruction::LoadFastBorrow { var_num } if name_4.varnames[usize::from(var_num.get(OpArg::new(u32::from(u8::from(prev.arg)))))] == "name_5" ), - "expected async comprehension iterator capture to borrow name_5 before GET_AITER, got {prev:?}" + "expected async comprehension iterator capture to borrow name_5 before saved locals, result collection, and GET_AITER, got {prev:?}" ); } @@ -43950,7 +43273,7 @@ def f(self): .position(|unit| match unit.op { Instruction::LoadAttr { namei } => { let load_attr = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))); - f.names[usize::try_from(load_attr.name_idx()).unwrap()].as_str() == "assertIs" + f.names[load_attr.name_idx()].as_str() == "assertIs" } _ => false, }) @@ -43988,8 +43311,10 @@ def f(w): .iter() .position(|unit| match unit.op { Instruction::LoadGlobal { namei } => { - let name = namei.get(OpArg::new(u32::from(u8::from(unit.arg)))) >> 1; - f.names[usize::try_from(name).unwrap()].as_str() == "locals" + let name = namei + .get(OpArg::new(u32::from(u8::from(unit.arg)))) + .name_idx(); + f.names[name].as_str() == "locals" } _ => false, }) diff --git a/crates/codegen/src/error.rs b/crates/codegen/src/error.rs index e6b57a2e43f..080b8fd619e 100644 --- a/crates/codegen/src/error.rs +++ b/crates/codegen/src/error.rs @@ -84,6 +84,9 @@ pub enum CodegenErrorType { InvalidFutureFeature(String), InvalidFutureBraces, RecursionError, + AstLocation(rustpython_compiler_core::AstLocationError), + /// A partial internal AST location map reached a span operation. + MixedAstLocationProvenance, TooManyStarUnpack, TooManyExpressionsInStarUnpackingSequencePattern, EmptyWithItems, @@ -103,6 +106,20 @@ impl core::error::Error for CodegenErrorType {} impl fmt::Display for CodegenErrorType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::MixedAstLocationProvenance => { + write!(f, "mixed AST location provenance") + } + Self::AstLocation(error) => match error { + rustpython_compiler_core::AstLocationError::ExhaustedNodeIdentities => { + write!(f, "too many AST location identities") + } + rustpython_compiler_core::AstLocationError::ConflictingLocation => { + write!(f, "conflicting AST location identity") + } + rustpython_compiler_core::AstLocationError::CoordinateOverflow => { + write!(f, "AST location coordinate overflow") + } + }, Self::Assign(target) => write!(f, "cannot assign to {target}"), Self::Delete(target) => write!(f, "cannot delete {target}"), Self::SyntaxError(err) => write!(f, "{}", err.as_str()), diff --git a/crates/codegen/src/ir.rs b/crates/codegen/src/ir.rs index 790846a4028..f176df9fd85 100644 --- a/crates/codegen/src/ir.rs +++ b/crates/codegen/src/ir.rs @@ -7,7 +7,7 @@ use num_traits::{ToPrimitive, Zero}; use rustpython_wtf8::Wtf8Buf; use rustpython_compiler_core::{ - OneIndexed, SourceLocation, + OneIndexed, SourceLocation, SourceLocationRange as LineTableLocation, bytecode::{ AnyInstruction, AnyOpcode, CO_FAST_ARG_KW, CO_FAST_ARG_POS, CO_FAST_ARG_VAR, CO_FAST_CELL, CO_FAST_FREE, CO_FAST_HIDDEN, CO_FAST_LOCAL, CodeFlags, CodeObject, CodeUnit, CodeUnits, @@ -17,17 +17,9 @@ use rustpython_compiler_core::{ varint::{write_signed_varint, write_varint}, }; -/// Location info for linetable generation (allows line 0 for RESUME) -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -struct LineTableLocation { - line: i32, - end_line: i32, - col: i32, - end_col: i32, -} - #[derive(Clone, Copy)] struct InstructionLocation { + semantic_location: Option, location: SourceLocation, end_location: SourceLocation, lineno_override: Option, @@ -326,6 +318,7 @@ pub struct InstructionInfo { pub location: SourceLocation, pub end_location: SourceLocation, pub except_handler: Option, + pub semantic_location: Option, /// Override line number for linetable (e.g., line 0 for module RESUME) pub lineno_override: Option, } @@ -352,6 +345,7 @@ impl InstructionInfo { end_location: SourceLocation, lineno_override: Option, ) { + self.semantic_location = None; self.location = location; self.end_location = end_location; self.lineno_override = lineno_override; @@ -359,6 +353,7 @@ impl InstructionInfo { fn instr_location(&self) -> InstructionLocation { InstructionLocation { + semantic_location: self.semantic_location, location: self.location, end_location: self.end_location, lineno_override: self.lineno_override, @@ -367,6 +362,7 @@ impl InstructionInfo { fn instr_set_location(&mut self, loc: InstructionLocation) { self.instr_set_loc(loc.location, loc.end_location, loc.lineno_override); + self.semantic_location = loc.semantic_location; } fn set_to_nop(&mut self) { @@ -391,6 +387,7 @@ impl InstructionInfo { location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: None, } } @@ -424,6 +421,12 @@ impl InstructionInfo { } fn instruction_linetable_location(&self) -> LineTableLocation { + let location = self.semantic_location.unwrap_or_else(|| LineTableLocation { + line: self.location.line.get() as i32, + end_line: self.end_location.line.get() as i32, + col: self.location.character_offset.to_zero_indexed() as i32, + end_col: self.end_location.character_offset.to_zero_indexed() as i32, + }); match self.lineno_override { Some(NO_LOCATION_OVERRIDE) => LineTableLocation { line: NO_LOCATION_OVERRIDE, @@ -432,30 +435,23 @@ impl InstructionInfo { end_col: NO_LOCATION_OVERRIDE, }, Some(LINE_ONLY_LOCATION_OVERRIDE) => LineTableLocation { - line: self.location.line.get() as i32, - end_line: self.end_location.line.get() as i32, col: -1, end_col: -1, + ..location }, Some(NEXT_LOCATION_OVERRIDE) => next_linetable_location(), - Some(lineno) => LineTableLocation { - line: lineno, - end_line: self.end_location.line.get() as i32, - col: self.location.character_offset.to_zero_indexed() as i32, - end_col: self.end_location.character_offset.to_zero_indexed() as i32, - }, - None => LineTableLocation { - line: self.location.line.get() as i32, - end_line: self.end_location.line.get() as i32, - col: self.location.character_offset.to_zero_indexed() as i32, - end_col: self.end_location.character_offset.to_zero_indexed() as i32, - }, + Some(line) => LineTableLocation { line, ..location }, + None => location, } } /// flowgraph.c loads_const const fn loads_const(&self) -> bool { - self.instr.has_const() || matches!(self.instr.real_opcode(), Some(Opcode::LoadSmallInt)) + self.instr.has_const() + || matches!( + self.instr.real_opcode(), + Some(Opcode::LoadSmallInt | Opcode::LoadCommonConstant) + ) } /// flowgraph.c STORES_TO @@ -478,6 +474,26 @@ impl InstructionInfo { false } + /// flowgraph.c maybe_instr_make_load_common_const + fn maybe_instr_make_load_common_const(&mut self, constant: &ConstantData) -> bool { + use oparg::CommonConstant; + let idx = match constant { + ConstantData::None => CommonConstant::None, + ConstantData::Boolean { value: true } => CommonConstant::True, + ConstantData::Boolean { value: false } => CommonConstant::False, + ConstantData::Str { value } if value.is_empty() => CommonConstant::EmptyStr, + ConstantData::Integer { value } if value.to_i32() == Some(-1) => { + CommonConstant::MinusOne + } + _ => return false, + }; + self.instr_set_op1( + Opcode::LoadCommonConstant.into(), + OpArg::new(u32::from(idx)), + ); + true + } + /// flowgraph.c make_super_instruction fn make_super_instruction(inst1: &mut Self, inst2: &mut Self, super_op: AnyInstruction) { let line1 = inst1.instruction_lineno(); @@ -496,7 +512,7 @@ impl InstructionInfo { fn instruction_lineno(&self) -> i32 { match self.lineno_override { - Some(LINE_ONLY_LOCATION_OVERRIDE) | None => self.location.line.get() as i32, + Some(LINE_ONLY_LOCATION_OVERRIDE) | None => self.instruction_linetable_location().line, Some(lineno) => lineno, } } @@ -527,6 +543,7 @@ pub struct ExceptHandlerInfo { fn no_instruction_location() -> InstructionLocation { InstructionLocation { + semantic_location: None, location: SourceLocation::default(), end_location: SourceLocation::default(), lineno_override: Some(NO_LOCATION_OVERRIDE), @@ -835,6 +852,12 @@ fn instruction_info_from_python( character_offset: end_col, }, except_handler: None, + semantic_location: Some(LineTableLocation { + line: lineno, + end_line: end_lineno, + col: col_offset, + end_col: end_col_offset, + }), lineno_override, } } @@ -865,6 +888,7 @@ fn instruction_sequence_next_inst(seq: &mut InstructionSequence) -> crate::Inter location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: None, }, ZERO_EXCEPTION_HANDLER_INFO, @@ -1084,7 +1108,7 @@ fn resolve_unconditional_jumps(instr_sequence: &mut InstructionSequence) { /// assemble.c resolve_jump_offsets fn resolve_jump_offsets(instr_sequence: &mut InstructionSequence) { // The offset (in code units) of END_SEND from SEND in the yield-from sequence. - const END_SEND_OFFSET: i32 = 5; + const END_SEND_OFFSET: i32 = 6; for i in 0..instr_sequence.instr_used { let instr = &mut instr_sequence.instrs[i]; let opcode = instr.info.instr.expect_real(); @@ -1239,11 +1263,9 @@ fn assemble_location_info( } else { debug_assert!(i < instr_sequence.instr_used - 1); let next = instr_sequence.instrs[i + 1].info; - instr_sequence.instrs[i].info.instr_set_loc( - next.location, - next.end_location, - next.lineno_override, - ); + instr_sequence.instrs[i] + .info + .instr_set_location(next.instr_location()); } } } @@ -1515,9 +1537,7 @@ impl Block { "CPython basicblock_addop requires 0 <= oparg < (1 << 30)" ); let off = self.basicblock_next_instr()?; - let except_handler = self.instructions[off].except_handler; info.target = BlockIdx::NULL; - info.except_handler = except_handler; self.instructions[off] = info; Ok(()) } @@ -2015,6 +2035,7 @@ impl Blocks { location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: None, }; nop.instr_set_op0(Instruction::Nop.into()); @@ -2163,10 +2184,12 @@ impl Blocks { } AnyInstruction::Real(Instruction::LoadGlobal { .. }) if matches!(nextop, Some(Instruction::PushNull)) - && (u32::from(inst.arg) & 1) == 0 => + && !oparg::LoadGlobal::from_u32(u32::from(inst.arg)).push_null() => { + let name_idx = oparg::LoadGlobal::from_u32(u32::from(inst.arg)).name_idx(); + let load_global = oparg::LoadGlobal::new(name_idx, true); self[block_idx].instructions[i] - .instr_set_op1(inst.instr, OpArg::new(u32::from(inst.arg) | 1)); + .instr_set_op1(inst.instr, OpArg::new(load_global.as_u32())); self[block_idx].instructions[i + 1].set_to_nop(); } AnyInstruction::Real(Instruction::CompareOp { .. }) @@ -2227,14 +2250,17 @@ impl Blocks { AnyInstruction::Real(Instruction::CallIntrinsic1 { func }) => { match func.get(inst.arg) { IntrinsicFunction1::ListToTuple => { - if matches!(nextop, Some(Instruction::GetIter)) { + fold_constant_sequence_into_load_const( + metadata, + &mut self[block_idx], + i, + )?; + if matches!( + self[block_idx].instructions[i].instr.real(), + Some(Instruction::CallIntrinsic1 { .. }) + ) && matches!(nextop, Some(Instruction::GetIter { .. })) + { self[block_idx].instructions[i].set_to_nop(); - } else { - fold_constant_intrinsic_list_to_tuple( - metadata, - &mut self[block_idx], - i, - )?; } } IntrinsicFunction1::UnaryPositive => { @@ -2243,6 +2269,16 @@ impl Blocks { _ => {} } } + AnyInstruction::Real( + Instruction::ListAppend { .. } | Instruction::SetAdd { .. }, + ) if u32::from(inst.arg) == 1 + && matches!( + nextop, + Some(Instruction::GetIter { .. } | Instruction::ContainsOp { .. }) + ) => + { + fold_constant_sequence_into_load_const(metadata, &mut self[block_idx], i)?; + } AnyInstruction::Real(Instruction::BinaryOp { .. }) => { fold_const_binop(metadata, &mut self[block_idx], i)?; } @@ -2410,7 +2446,7 @@ impl Blocks { Instruction::FormatSimple | Instruction::GetAnext | Instruction::GetLen - | Instruction::GetYieldFromIter + | Instruction::GetIter { .. } | Instruction::ImportFrom { .. } | Instruction::MatchKeys | Instruction::MatchMapping @@ -2420,10 +2456,8 @@ impl Blocks { let effect = instr.stack_effect_info(arg_u32); let net_pushed = effect.pushed() as isize - effect.popped() as isize; debug_assert!(net_pushed >= 0); - // CPython optimize_load_fast() shadows the outer - // instruction index in this produced-value loop. - for produced in 0..net_pushed { - push_ref(&mut refs, produced, NOT_LOCAL)?; + for _ in 0..net_pushed { + push_ref(&mut refs, i as isize, NOT_LOCAL)?; } } AnyInstruction::Real( @@ -2447,10 +2481,19 @@ impl Blocks { Instruction::EndSend | Instruction::SetFunctionAttribute { .. }, ) => { let effect = instr.stack_effect_info(arg_u32); - debug_assert_eq!(effect.popped(), 2); + debug_assert_eq!( + effect.popped(), + if matches!(instr.real(), Some(Instruction::EndSend)) { + 3 + } else { + 2 + } + ); debug_assert_eq!(effect.pushed(), 1); let tos = ref_stack_pop(&mut refs); - let _ = ref_stack_pop(&mut refs); + for _ in 1..effect.popped() { + let _ = ref_stack_pop(&mut refs); + } push_ref(&mut refs, tos.instr, tos.local)?; } AnyInstruction::Real(Instruction::CheckExcMatch) => { @@ -2634,8 +2677,14 @@ impl Blocks { let opcode = instr_info.instr.real_opcode(); let is_redundant_pair = matches!(opcode, Some(Opcode::PopTop)) - && (matches!(prev_opcode, Some(Opcode::LoadConst | Opcode::LoadSmallInt)) - || (prev_oparg == 1 && matches!(prev_opcode, Some(Opcode::Copy)))); + && (matches!( + prev_opcode, + Some( + Opcode::LoadConst + | Opcode::LoadSmallInt + | Opcode::LoadCommonConstant + ) + ) || (prev_oparg == 1 && matches!(prev_opcode, Some(Opcode::Copy)))); if is_redundant_pair { let (prev_block, prev_instr_idx) = @@ -3052,6 +3101,7 @@ impl Blocks { location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: Some(NO_LOCATION_OVERRIDE), })?; self[explicit_jump].cold = true; @@ -3177,7 +3227,8 @@ impl Blocks { target: BlockIdx::NULL, location: loc_source.location, end_location: loc_source.end_location, - except_handler: None, + except_handler: loc_source.except_handler, + semantic_location: loc_source.semantic_location, lineno_override: loc_source.lineno_override, })?; let last = block.basicblock_last_instr_mut().expect("missing jump"); @@ -3218,6 +3269,7 @@ impl Blocks { let location = instr.location; let end_location = instr.end_location; let except_handler = instr.except_handler; + let semantic_location = instr.semantic_location; let lineno_override = instr.lineno_override; let copy = InstructionInfo { instr: Opcode::Copy.into(), @@ -3226,6 +3278,7 @@ impl Blocks { location, end_location, except_handler, + semantic_location, lineno_override, }; block.basicblock_insert_instruction(i, copy)?; @@ -3238,6 +3291,7 @@ impl Blocks { location, end_location, except_handler, + semantic_location, lineno_override, }; block.basicblock_insert_instruction(i, to_bool)?; @@ -3271,7 +3325,8 @@ impl Blocks { target: BlockIdx::NULL, location: last_ins.location, end_location: last_ins.end_location, - except_handler: None, + except_handler: last_ins.except_handler, + semantic_location: last_ins.semantic_location, lineno_override: last_ins.lineno_override, }; @@ -3301,7 +3356,8 @@ impl Blocks { target: BlockIdx::NULL, location: loc, end_location: end_loc, - except_handler: None, + except_handler: last_ins.except_handler, + semantic_location: last_ins.semantic_location, lineno_override: last_ins.lineno_override, })?; self.basicblock_add_jump( @@ -3412,11 +3468,8 @@ impl Blocks { continue; } if next_lineno < 0 { - self[block_idx].instructions[src + 1].instr_set_loc( - instr.location, - instr.end_location, - instr.lineno_override, - ); + self[block_idx].instructions[src + 1] + .instr_set_location(instr.instr_location()); continue; } } else { @@ -3452,6 +3505,8 @@ impl Blocks { debug_assert!(dest <= instr_count); let num_removed = instr_count - dest; self[block_idx].instruction_used = dest; + // Later instructions reuse these slots and must not inherit a removed handler. + self[block_idx].instructions[dest..instr_count].fill(InstructionInfo::empty()); num_removed } @@ -3743,22 +3798,6 @@ fn instruction_sequence_label_map_resolve_label( }) } -fn instruction_sequence_label_map_resolve_label_to_block( - map: &InstructionSequenceLabelMap, - label: InstructionSequenceLabel, -) -> BlockIdx { - if !is_label(label) { - return BlockIdx::NULL; - } - instruction_sequence_label_map_block_for_label(map, label).unwrap_or_else(|| { - debug_assert!( - false, - "CPython instruction-sequence label must map to a codegen CFG block" - ); - BlockIdx::NULL - }) -} - fn instruction_sequence_label_oparg(label: InstructionSequenceLabel) -> OpArg { debug_assert!(is_label(label)); OpArg::new(label.idx() as u32) @@ -3936,27 +3975,10 @@ impl CodeInfo { instruction_sequence_use_label(&mut self.instr_sequence, label) } - pub(crate) fn mark_cpython_cfg_label(&mut self, block: BlockIdx) -> crate::InternalResult<()> { - let label = instruction_sequence_label_map_ensure_label_for_block( - &mut self.instr_sequence_label_map, - &mut self.instr_sequence, - block, - )?; - self.blocks[block].cpython_label = label; - Ok(()) - } - pub(crate) fn resolve_instr_sequence_label(&self, block: BlockIdx) -> BlockIdx { instruction_sequence_label_map_resolve_label(&self.instr_sequence_label_map, block) } - pub(crate) fn block_for_instr_sequence_label( - &self, - label: InstructionSequenceLabel, - ) -> BlockIdx { - instruction_sequence_label_map_resolve_label_to_block(&self.instr_sequence_label_map, label) - } - pub(crate) fn use_instr_sequence_label_at_block( &mut self, from: BlockIdx, @@ -3985,6 +4007,7 @@ impl CodeInfo { } } + /// Insert SETUP_CLEANUP just after the initial RETURN_GENERATOR; POP_TOP. pub(crate) fn insert_start_setup_cleanup( &mut self, handler_block: BlockIdx, @@ -3994,9 +4017,20 @@ impl CodeInfo { &mut self.instr_sequence, handler_block, )?; + let seq = &self.instr_sequence; + let opcode_at = |i: usize| seq.instrs[i].info.instr.real(); + let mut resume = 0; + while !matches!(opcode_at(resume), Some(Instruction::ReturnGenerator)) { + resume += 1; + debug_assert!(resume < seq.instr_used); + } + resume += 1; + debug_assert!(matches!(opcode_at(resume), Some(Instruction::PopTop))); + resume += 1; + debug_assert!(resume < seq.instr_used); instruction_sequence_insert_instruction( &mut self.instr_sequence, - 0, + resume, InstructionInfo { instr: PseudoOpcode::SetupCleanup.into(), arg: instruction_sequence_label_oparg(handler_label), @@ -4004,11 +4038,33 @@ impl CodeInfo { location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: Some(NO_LOCATION_OVERRIDE), }, ) } + /// Insert `RESUME`, `LOAD_FAST 0` and the outermost `GET_ITER` (or + /// `GET_AITER`) before RETURN_GENERATOR. + pub(crate) fn insert_genexpr_prefix( + &mut self, + mut iterator: InstructionInfo, + ) -> crate::InternalResult<()> { + let mut resume = InstructionInfo::empty(); + resume.instr_set_op1( + Opcode::Resume.into(), + OpArg::new(oparg::ResumeLocation::AtGenExprStart.into()), + ); + resume.lineno_override = Some(NO_LOCATION_OVERRIDE); + let mut load = iterator; + load.instr_set_op1(Opcode::LoadFast.into(), OpArg::new(0)); + iterator.arg = OpArg::new(0); + for (i, info) in [resume, load, iterator].into_iter().enumerate() { + instruction_sequence_insert_instruction(&mut self.instr_sequence, i, info)?; + } + Ok(()) + } + pub(crate) fn push_unmapped_instr_sequence_label(&mut self) -> crate::InternalResult<()> { instruction_sequence_label_map_push_unmapped_label( &mut self.instr_sequence_label_map, @@ -4114,7 +4170,7 @@ fn optimized_cfg_to_instruction_sequence( blocks.convert_pseudo_conditional_jumps()?; let max_stackdepth = blocks.calculate_stackdepth()?; debug_assert!(!is_generator(flags) || max_stackdepth != 0); - let nlocalsplus = prepare_localsplus(metadata, blocks, flags)?; + let nlocalsplus = prepare_localsplus(metadata, blocks)?; // Pseudo ops are lowered after stackdepth and // localsplus preparation, before normalize_jumps. convert_pseudo_ops(blocks)?; @@ -4172,8 +4228,29 @@ pub fn assemble_for_tests( blocks.mark_except_handlers(); label_exception_targets(&mut blocks)?; let flags = CodeFlags::empty(); - let (max_stackdepth, nlocalsplus, mut instr_sequence) = + let (max_stackdepth, nlocalsplus, instr_sequence) = optimized_cfg_to_instruction_sequence(&metadata, flags, &mut blocks)?; + assemble_code_object( + filename, + metadata, + flags, + max_stackdepth, + nlocalsplus, + instr_sequence, + debug_ranges, + ) +} + +/// assemble.c _PyAssemble_MakeCodeObject +fn assemble_code_object( + source_path: String, + metadata: CodeUnitMetadata, + flags: CodeFlags, + max_stackdepth: u32, + nlocalsplus: usize, + mut instr_sequence: InstructionSequence, + debug_ranges: bool, +) -> crate::InternalResult { let localsplusinfo = compute_localsplus_info(&metadata, nlocalsplus, flags)?; let CodeUnitMetadata { name: obj_name, @@ -4210,10 +4287,11 @@ pub fn assemble_for_tests( posonlyarg_count, arg_count: code_arg_count, kwonlyarg_count, - source_path: filename, + source_path, first_line_number: Some(first_line_number), obj_name: obj_name.clone(), qualname: qualname.unwrap_or(obj_name), + // Room for one value is always reserved, even where nothing is pushed. max_stackdepth: max_stackdepth.max(1), instructions: CodeUnits::from(assembled.instructions), locations, @@ -4227,7 +4305,6 @@ pub fn assemble_for_tests( exceptiontable: assembled.exceptiontable, }) } - impl CodeInfo { pub fn finalize_code( mut self, @@ -4243,85 +4320,17 @@ impl CodeInfo { nlocals, nparams, )?; - let (max_stackdepth, nlocalsplus, mut instr_sequence) = + let (max_stackdepth, nlocalsplus, instr_sequence) = optimized_cfg_to_instruction_sequence(&self.metadata, self.flags, &mut self.blocks)?; - let localsplusinfo = compute_localsplus_info(&self.metadata, nlocalsplus, self.flags)?; - - let Self { - flags, - source_path, - private: _, // private is only used during compilation - - blocks: _, - current_block: _, - instr_sequence: _, - instr_sequence_label_map: _, - annotations_instr_sequence: _, - metadata, - static_attributes: _, - in_inlined_comp: _, - fblock: _, - symbol_table_index: _, - nparams: _, - in_conditional_block: _, - next_conditional_annotation_index: _, - } = self; - - let CodeUnitMetadata { - name: obj_name, - qualname, - consts: constants, - names: name_cache, - varnames: varname_cache, - cellvars: _, - freevars: freevar_cache, - fast_hidden: _, - fast_hidden_final: _, - argcount: arg_count, - posonlyargcount: posonlyarg_count, - kwonlyargcount: kwonlyarg_count, - firstlineno: first_line_number, - } = metadata; - let code_arg_count = posonlyarg_count - .checked_add(arg_count) - .ok_or(InternalError::MalformedControlFlowGraph)?; - - resolve_unconditional_jumps(&mut instr_sequence); - resolve_jump_offsets(&mut instr_sequence); - let assembled = assemble_emit( - &mut instr_sequence, - first_line_number.get() as i32, + assemble_code_object( + self.source_path, + self.metadata, + self.flags, + max_stackdepth, + nlocalsplus, + instr_sequence, opts.debug_ranges, - )?; - let locations = rustpython_compiler_core::marshal::linetable_to_locations( - &assembled.linetable, - first_line_number.get() as i32, - assembled.instructions.len(), - ); - - Ok(CodeObject { - flags, - posonlyarg_count, - arg_count: code_arg_count, - kwonlyarg_count, - source_path, - first_line_number: Some(first_line_number), - obj_name: obj_name.clone(), - qualname: qualname.unwrap_or(obj_name), - - // Room for one value is always reserved, even where nothing is pushed. - max_stackdepth: max_stackdepth.max(1), - instructions: CodeUnits::from(assembled.instructions), - locations, - constants: constants.into_iter().collect(), - names: name_cache.into_iter().collect(), - varnames: varname_cache.into_iter().collect(), - cellvars: localsplusinfo.cellvars, - freevars: freevar_cache.into_iter().collect(), - localspluskinds: localsplusinfo.kinds, - linetable: assembled.linetable, - exceptiontable: assembled.exceptiontable, - }) + ) } } @@ -4336,7 +4345,6 @@ fn insert_prefix_instructions( blocks: &mut Blocks, cellfixedoffsets: &[i32], nfreevars: usize, - flags: CodeFlags, ) -> crate::InternalResult<()> { debug_assert!(!blocks.is_empty()); let entry = &mut blocks[0]; @@ -4344,37 +4352,6 @@ fn insert_prefix_instructions( let firstlineno = metadata.firstlineno; debug_assert!(firstlineno.get() > 0); - if is_generator(flags) { - let location = SourceLocation { - line: firstlineno, - character_offset: OneIndexed::MIN, - }; - entry.basicblock_insert_instruction( - 0, - InstructionInfo { - instr: Instruction::ReturnGenerator.into(), - arg: OpArg::new(0), - target: BlockIdx::NULL, - location, - end_location: location, - except_handler: None, - lineno_override: Some(LINE_ONLY_LOCATION_OVERRIDE), - }, - )?; - entry.basicblock_insert_instruction( - 1, - InstructionInfo { - instr: Instruction::PopTop.into(), - arg: OpArg::new(0), - target: BlockIdx::NULL, - location, - end_location: location, - except_handler: None, - lineno_override: Some(LINE_ONLY_LOCATION_OVERRIDE), - }, - )?; - } - if ncellvars > 0 { let nvars = metadata.varnames.len() + ncellvars; let mut sorted = Vec::new(); @@ -4400,6 +4377,7 @@ fn insert_prefix_instructions( location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: Some(NO_LOCATION_OVERRIDE), }, )?; @@ -4417,6 +4395,7 @@ fn insert_prefix_instructions( location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: Some(NO_LOCATION_OVERRIDE), }, )?; @@ -4428,7 +4407,6 @@ fn insert_prefix_instructions( fn prepare_localsplus( metadata: &CodeUnitMetadata, blocks: &mut Blocks, - flags: CodeFlags, ) -> crate::InternalResult { let nlocals = metadata.varnames.len(); let ncellvars = metadata.cellvars.len(); @@ -4443,7 +4421,7 @@ fn prepare_localsplus( let mut cellfixedoffsets = build_cellfixedoffsets(metadata)?; // This must be called before fix_cell_offsets(). - insert_prefix_instructions(metadata, blocks, &cellfixedoffsets, nfreevars, flags)?; + insert_prefix_instructions(metadata, blocks, &cellfixedoffsets, nfreevars)?; let numdropped = fix_cell_offsets(metadata, blocks, &mut cellfixedoffsets); nlocalsplus -= numdropped; @@ -4517,6 +4495,13 @@ fn load_const_truthiness( Some(constant.truthiness()) } Instruction::LoadSmallInt { i } => Some(i.get(arg) != 0), + Instruction::LoadCommonConstant { idx } => { + use oparg::CommonConstant; + Some(!matches!( + idx.get(arg), + CommonConstant::None | CommonConstant::False | CommonConstant::EmptyStr + )) + } _ => None, } } @@ -4534,7 +4519,9 @@ fn instr_make_load_const( instr: &mut InstructionInfo, constant: ConstantData, ) -> crate::InternalResult<()> { - if instr.maybe_instr_make_load_smallint(&constant) { + if instr.maybe_instr_make_load_smallint(&constant) + || instr.maybe_instr_make_load_common_const(&constant) + { return Ok(()); } @@ -4627,6 +4614,21 @@ fn fold_const_binop( /// flowgraph.c get_const_value fn get_const_value(metadata: &CodeUnitMetadata, info: &InstructionInfo) -> Option { match info.instr.real_opcode() { + Some(Opcode::LoadCommonConstant) => { + use oparg::CommonConstant; + match CommonConstant::try_from(u32::from(info.arg)).ok()? { + CommonConstant::None => Some(ConstantData::None), + CommonConstant::EmptyStr => Some(ConstantData::Str { + value: Wtf8Buf::new(), + }), + CommonConstant::True => Some(ConstantData::Boolean { value: true }), + CommonConstant::False => Some(ConstantData::Boolean { value: false }), + CommonConstant::MinusOne => Some(ConstantData::Integer { + value: BigInt::from(-1), + }), + _ => None, + } + } Some(Opcode::LoadSmallInt) => { let v = u32::from(info.arg) as i32; Some(ConstantData::Integer { @@ -4816,40 +4818,13 @@ fn const_folding_safe_mod(left: &ConstantData, right: &ConstantData) -> Option { - let (_, modulo) = float_div_mod(*l, *r)?; + let (_, modulo) = rustpython_literal::float::divmod(*l, *r)?; Some(ConstantData::Float { value: modulo }) } _ => None, } } -fn float_div_mod(left: f64, right: f64) -> Option<(f64, f64)> { - if right == 0.0 { - return None; - } - - let mut modulo = left % right; - let div = (left - modulo) / right; - let floordiv = if modulo != 0.0 { - let div = if (right < 0.0) != (modulo < 0.0) { - modulo += right; - div - 1.0 - } else { - div - }; - let mut floordiv = div.floor(); - if div - floordiv > 0.5 { - floordiv += 1.0; - } - floordiv - } else { - modulo = 0.0f64.copysign(right); - 0.0f64.copysign(left / right) - }; - - Some((floordiv, modulo)) -} - /// flowgraph.c eval_const_binop complex result construction fn eval_const_complex_const(value: Complex) -> Option { (value.re.is_finite() && value.im.is_finite()).then_some(ConstantData::Complex { value }) @@ -4865,28 +4840,16 @@ fn eval_const_complex_binop( let value = match op { BinOp::Add => left + right, - BinOp::Subtract => { - let re = left.re - right.re; - // Preserve signed-zero behavior for real-zero - // minus zero-complex expressions such as `0 - 0j`. - let im = if left.re == 0.0 - && left.im == 0.0 - && right.re == 0.0 - && right.im == 0.0 - && !right.im.is_sign_negative() - { - -0.0 - } else { - left.im - right.im - }; + BinOp::Subtract => left - right, + BinOp::Multiply => { + let (re, im) = + rustpython_literal::complex::multiply((left.re, left.im), (right.re, right.im)); Complex::new(re, im) } - BinOp::Multiply => left * right, BinOp::TrueDivide => { - if right == Complex::new(0.0, 0.0) { - return None; - } - left / right + let (re, im) = + rustpython_literal::complex::divide((left.re, left.im), (right.re, right.im))?; + Complex::new(re, im) } BinOp::Power => { if left == Complex::new(0.0, 0.0) { @@ -4913,7 +4876,48 @@ fn eval_const_complex_binop( } _ => return None, }; - eval_const_complex_const(value) + if matches!(op, BinOp::Power) { + eval_const_complex_const(value) + } else { + Some(ConstantData::Complex { value }) + } +} + +// Python keeps real/complex operands distinct; coercing the real operand to +// a zero-imaginary complex changes signed zeros and nonfinite multiplication. +fn eval_const_mixed_complex_binop( + real: f64, + value: Complex, + real_left: bool, + op: oparg::BinaryOperator, +) -> Option { + use oparg::BinaryOperator as BinOp; + let result = match op { + BinOp::Add if real_left => Complex::new(real + value.re, value.im), + BinOp::Add => Complex::new(value.re + real, value.im), + BinOp::Subtract if real_left => Complex::new(real - value.re, -value.im), + BinOp::Subtract => Complex::new(value.re - real, value.im), + BinOp::Multiply if real_left => Complex::new(real * value.re, real * value.im), + BinOp::Multiply => Complex::new(value.re * real, value.im * real), + BinOp::TrueDivide if real_left => { + let (re, im) = rustpython_literal::complex::real_divide(real, (value.re, value.im))?; + Complex::new(re, im) + } + BinOp::TrueDivide => { + if real == 0.0 { + return None; + } + Complex::new(value.re / real, value.im / real) + } + _ => { + return if real_left { + eval_const_complex_binop(Complex::new(real, 0.0), value, op) + } else { + eval_const_complex_binop(value, Complex::new(real, 0.0), op) + }; + } + }; + Some(ConstantData::Complex { value: result }) } /// flowgraph.c eval_const_binop subscript index conversion @@ -5155,9 +5159,13 @@ fn eval_const_binop( if r.is_zero() { return None; } - let l_f = l.to_f64()?; - let r_f = r.to_f64()?; - let result = l_f / r_f; + // Python divides first and rounds the quotient once. Converting + // large operands independently can change the rounded value. + let result = if l.bits().max(r.bits()) <= u64::from(f64::MANTISSA_DIGITS) { + l.to_f64()? / r.to_f64()? + } else { + rustpython_literal::float::true_div(l, r) + }; if !result.is_finite() { return None; } @@ -5201,7 +5209,7 @@ fn eval_const_binop( l / r } BinOp::FloorDivide => { - let (floordiv, _) = float_div_mod(*l, *r)?; + let (floordiv, _) = rustpython_literal::float::divmod(*l, *r)?; floordiv } BinOp::Remainder => return const_folding_safe_mod(left, right), @@ -5231,16 +5239,26 @@ fn eval_const_binop( ) } (ConstantData::Integer { value: l }, ConstantData::Complex { value: r }) => { - eval_const_complex_binop(Complex::new(l.to_f64()?, 0.0), *r, op) + eval_const_mixed_complex_binop( + l.to_f64().filter(|value| value.is_finite())?, + *r, + true, + op, + ) } (ConstantData::Complex { value: l }, ConstantData::Integer { value: r }) => { - eval_const_complex_binop(*l, Complex::new(r.to_f64()?, 0.0), op) + eval_const_mixed_complex_binop( + r.to_f64().filter(|value| value.is_finite())?, + *l, + false, + op, + ) } (ConstantData::Float { value: l }, ConstantData::Complex { value: r }) => { - eval_const_complex_binop(Complex::new(*l, 0.0), *r, op) + eval_const_mixed_complex_binop(*l, *r, true, op) } (ConstantData::Complex { value: l }, ConstantData::Float { value: r }) => { - eval_const_complex_binop(*l, Complex::new(*r, 0.0), op) + eval_const_mixed_complex_binop(*r, *l, false, op) } (ConstantData::Complex { value: l }, ConstantData::Complex { value: r }) => { eval_const_complex_binop(*l, *r, op) @@ -5358,20 +5376,28 @@ fn fold_tuple_of_constants( Ok(true) } -fn fold_constant_intrinsic_list_to_tuple( +fn fold_constant_sequence_into_load_const( metadata: &mut CodeUnitMetadata, block: &mut Block, i: usize, ) -> crate::InternalResult { - let Some(Instruction::CallIntrinsic1 { func }) = block.instructions[i].instr.real() else { - return Ok(false); + let (intrinsic, is_set) = match block.instructions[i].instr.real() { + Some(Instruction::CallIntrinsic1 { func }) + if func.get(block.instructions[i].arg) == IntrinsicFunction1::ListToTuple => + { + (true, false) + } + Some(Instruction::ListAppend { .. }) if u32::from(block.instructions[i].arg) == 1 => { + (false, false) + } + Some(Instruction::SetAdd { .. }) if u32::from(block.instructions[i].arg) == 1 => { + (false, true) + } + _ => return Ok(false), }; - if func.get(block.instructions[i].arg) != IntrinsicFunction1::ListToTuple { - return Ok(false); - } let mut consts_found = 0usize; - let mut expect_append = true; + let mut expect_append = intrinsic; let mut pos = i; while let Some(prev) = pos.checked_sub(1) { pos = prev; @@ -5380,9 +5406,12 @@ fn fold_constant_intrinsic_list_to_tuple( continue; } - if matches!(instr.instr.real(), Some(Instruction::BuildList { .. })) - && u32::from(instr.arg) == 0 - { + let is_start = if is_set { + matches!(instr.instr.real(), Some(Instruction::BuildSet { .. })) + } else { + matches!(instr.instr.real(), Some(Instruction::BuildList { .. })) + }; + if is_start && u32::from(instr.arg) == 0 { if !expect_append { return Ok(false); } @@ -5391,7 +5420,8 @@ fn fold_constant_intrinsic_list_to_tuple( elements .try_reserve_exact(consts_found) .map_err(|_| InternalError::MalformedControlFlowGraph)?; - for idx in (pos..i).rev() { + let end = if intrinsic { i } else { i + 1 }; + for idx in (pos..end).rev() { if matches!(block.instructions[idx].instr.real(), Some(Instruction::Nop)) { continue; } @@ -5401,22 +5431,35 @@ fn fold_constant_intrinsic_list_to_tuple( }; elements.push(value); } - block.instructions[idx].nop_out_no_location(); } debug_assert_eq!(elements.len(), consts_found); elements.reverse(); + // A valid common constant may have no ConstantData representation. + // Leave the sequence intact when collecting its values rejects it. + for instr in &mut block.instructions[pos..end] { + if !matches!(instr.instr.real(), Some(Instruction::Nop)) { + instr.nop_out_no_location(); + } + } instr_make_load_const( metadata, &mut block.instructions[i], - ConstantData::Tuple { elements }, + if is_set { + ConstantData::Frozenset { elements } + } else { + ConstantData::Tuple { elements } + }, )?; return Ok(true); } if expect_append { - if !matches!(instr.instr.real(), Some(Instruction::ListAppend { .. })) - || u32::from(instr.arg) != 1 - { + let is_append = if is_set { + matches!(instr.instr.real(), Some(Instruction::SetAdd { .. })) + } else { + matches!(instr.instr.real(), Some(Instruction::ListAppend { .. })) + }; + if !is_append || u32::from(instr.arg) != 1 { return Ok(false); } } else { @@ -5449,7 +5492,7 @@ fn optimize_lists_and_sets( let contains_or_iter = matches!( nextop, - Some(Instruction::GetIter | Instruction::ContainsOp { .. }) + Some(Instruction::GetIter { .. } | Instruction::ContainsOp { .. }) ); let seq_size = u32::from(block.instructions[i].arg) as usize; if seq_size > STACK_USE_GUIDELINE || (seq_size < MIN_CONST_SEQUENCE_SIZE && !contains_or_iter) { @@ -5539,84 +5582,88 @@ fn basicblock_optimize_load_const( metadata: &mut CodeUnitMetadata, block: &mut Block, ) -> crate::InternalResult<()> { - let mut i = 0; let mut effective_opcode = Instruction::Nop.into(); let mut effective_oparg = OpArg::new(0); - while i < block.instruction_used { - if matches!( - block.instructions[i].instr.real(), - Some(Instruction::LoadConst { .. }) - ) && let Some(constant) = get_const_value(metadata, &block.instructions[i]) - { - block.instructions[i].maybe_instr_make_load_smallint(&constant); - } + for i in 0..block.instruction_used { + 'instruction: { + if matches!( + block.instructions[i].instr.real(), + Some(Instruction::LoadConst { .. }) + ) && let Some(constant) = get_const_value(metadata, &block.instructions[i]) + { + block.instructions[i].maybe_instr_make_load_smallint(&constant); + } - let curr = block.instructions[i]; - let curr_arg = curr.arg; + let curr = block.instructions[i]; + let curr_arg = curr.arg; - let is_copy_of_load_const = matches!( - (effective_opcode, curr.instr.real()), - (AnyInstruction::Real(Instruction::LoadConst { .. }), Some(Instruction::Copy { i })) - if i.get(curr_arg) == 1 - ); - if !is_copy_of_load_const { - effective_opcode = curr.instr; - effective_oparg = curr_arg; - } - debug_assert!(!effective_opcode.is_assembler()); - let Some(const_instr @ (Instruction::LoadConst { .. } | Instruction::LoadSmallInt { .. })) = - effective_opcode.real() - else { - i += 1; - continue; - }; - let const_arg = effective_oparg; + let is_copy_of_load_const = matches!( + (effective_opcode, curr.instr.real()), + (AnyInstruction::Real(Instruction::LoadConst { .. }), Some(Instruction::Copy { i })) + if i.get(curr_arg) == 1 + ); + if !is_copy_of_load_const { + effective_opcode = curr.instr; + effective_oparg = curr_arg; + } + debug_assert!(!effective_opcode.is_assembler()); + let Some( + const_instr @ (Instruction::LoadConst { .. } + | Instruction::LoadSmallInt { .. } + | Instruction::LoadCommonConstant { .. }), + ) = effective_opcode.real() + else { + break 'instruction; + }; + let const_arg = effective_oparg; - if i + 1 >= block.instruction_used { - i += 1; - continue; - } + if i + 1 >= block.instruction_used { + break 'instruction; + } - let next = block.instructions[i + 1]; - let next_arg = next.arg; + let next = block.instructions[i + 1]; + let next_arg = next.arg; - if let Some(is_true) = load_const_truthiness(const_instr, const_arg, metadata) { - let const_jump = match (next.instr.real_opcode(), next.instr.pseudo_opcode()) { - (_, Some(PseudoOpcode::JumpIfTrue)) => Some((true, false)), - (_, Some(PseudoOpcode::JumpIfFalse)) => Some((false, false)), - (Some(Opcode::PopJumpIfTrue), _) => Some((true, true)), - (Some(Opcode::PopJumpIfFalse), _) => Some((false, true)), - _ => None, - }; - if let Some((jump_if_true, pops_condition)) = const_jump { - if pops_condition { - block.instructions[i].set_to_nop(); - } - if is_true == jump_if_true { - block.instructions[i + 1].instr = PseudoOpcode::Jump.into(); - } else { - block.instructions[i + 1].set_to_nop(); + if let Some(is_true) = load_const_truthiness(const_instr, const_arg, metadata) { + let const_jump = match (next.instr.real_opcode(), next.instr.pseudo_opcode()) { + (_, Some(PseudoOpcode::JumpIfTrue)) => Some((true, false)), + (_, Some(PseudoOpcode::JumpIfFalse)) => Some((false, false)), + (Some(Opcode::PopJumpIfTrue), _) => Some((true, true)), + (Some(Opcode::PopJumpIfFalse), _) => Some((false, true)), + _ => None, + }; + if let Some((jump_if_true, pops_condition)) = const_jump { + if pops_condition { + block.instructions[i].set_to_nop(); + } + if is_true == jump_if_true { + block.instructions[i + 1].instr = PseudoOpcode::Jump.into(); + } else { + block.instructions[i + 1].set_to_nop(); + } + break 'instruction; } - i += 1; - continue; } - } - // The remaining combinations require both instructions to be real. - let Some(next_instr) = next.instr.real() else { - i += 1; - continue; - }; + // The remaining combinations require both instructions to be real. + let Some(next_instr) = next.instr.real() else { + break 'instruction; + }; - if let Instruction::LoadConst { consti } = const_instr { - let constant = &metadata.consts[consti.get(const_arg).as_usize()]; - if matches!(constant, ConstantData::None) - && let Instruction::IsOp { invert } = next_instr - { + let is_none = match const_instr { + Instruction::LoadConst { consti } => matches!( + &metadata.consts[consti.get(const_arg).as_usize()], + ConstantData::None + ), + Instruction::LoadCommonConstant { idx } => { + idx.get(const_arg) == oparg::CommonConstant::None + } + _ => false, + }; + if is_none && let Instruction::IsOp { invert } = next_instr { let mut jump_idx = i + 2; if jump_idx >= block.instruction_used { - i += 1; - continue; + break 'instruction; } if matches!( @@ -5626,14 +5673,12 @@ fn basicblock_optimize_load_const( block.instructions[jump_idx].set_to_nop(); jump_idx += 1; if jump_idx >= block.instruction_used { - i += 1; - continue; + break 'instruction; } } let Some(jump_instr) = block.instructions[jump_idx].instr.real() else { - i += 1; - continue; + break 'instruction; }; let mut invert = matches!( @@ -5646,8 +5691,7 @@ fn basicblock_optimize_load_const( } Instruction::PopJumpIfTrue { .. } => {} _ => { - i += 1; - continue; + break 'instruction; } }; @@ -5659,27 +5703,32 @@ fn basicblock_optimize_load_const( Opcode::PopJumpIfNone } .into(); - i += 1; - continue; + break 'instruction; } - } + if matches!( + const_instr, + Instruction::LoadConst { .. } + | Instruction::LoadSmallInt { .. } + | Instruction::LoadCommonConstant { .. } + ) && matches!(next_instr, Instruction::ToBool) + && let Some(value) = load_const_truthiness(const_instr, const_arg, metadata) + { + let const_idx = add_const(metadata, ConstantData::Boolean { value })?; + block.instructions[i].set_to_nop(); + + block.instructions[i + 1] + .instr_set_op1(Opcode::LoadConst.into(), OpArg::new(const_idx as u32)); + break 'instruction; + } + } if matches!( - const_instr, - Instruction::LoadConst { .. } | Instruction::LoadSmallInt { .. } - ) && matches!(next_instr, Instruction::ToBool) - && let Some(value) = load_const_truthiness(const_instr, const_arg, metadata) + block.instructions[i].instr.real_opcode(), + Some(Opcode::LoadConst) + ) && let Some(constant) = get_const_value(metadata, &block.instructions[i]) { - let const_idx = add_const(metadata, ConstantData::Boolean { value })?; - block.instructions[i].set_to_nop(); - - block.instructions[i + 1] - .instr_set_op1(Opcode::LoadConst.into(), OpArg::new(const_idx as u32)); - i += 1; - continue; + block.instructions[i].maybe_instr_make_load_common_const(&constant); } - - i += 1; } Ok(()) } @@ -5837,7 +5886,7 @@ impl CodeInfo { )); let _max_stackdepth = self.blocks.calculate_stackdepth()?; - let _nlocalsplus = prepare_localsplus(&self.metadata, &mut self.blocks, self.flags)?; + let _nlocalsplus = prepare_localsplus(&self.metadata, &mut self.blocks)?; convert_pseudo_ops(&mut self.blocks)?; trace.push(( "after_convert_pseudo_ops".to_owned(), @@ -5867,8 +5916,8 @@ impl InstrDisplayContext for CodeInfo { &self.metadata.consts[consti.as_usize()] } - fn get_name(&self, i: usize) -> &str { - self.metadata.names[i].as_ref() + fn get_name(&self, namei: oparg::NameIdx) -> &str { + self.metadata.names[namei.as_usize()].as_ref() } fn get_varname(&self, var_num: oparg::VarNum) -> &str { @@ -6968,7 +7017,9 @@ pub(crate) fn label_exception_targets(blocks: &mut Blocks) -> crate::InternalRes } else if let Some(Instruction::Resume { context: _ }) = instr.real() { blocks[bi].instructions[i].except_handler = handler; let resume_arg = u32::from(arg); - if resume_arg != u32::from(oparg::ResumeLocation::AtFuncStart) { + if resume_arg != u32::from(oparg::ResumeLocation::AtFuncStart) + && resume_arg != u32::from(oparg::ResumeLocation::AtGenExprStart) + { debug_assert!(last_yield_except_depth >= 0); if last_yield_except_depth == 1 { blocks[bi].instructions[i].arg = @@ -7196,6 +7247,7 @@ mod tests { location: test_location(line), end_location: test_location(line), except_handler: None, + semantic_location: None, lineno_override: None, } } @@ -7263,6 +7315,217 @@ mod tests { } } + fn test_sequence_block(instructions: &[(Opcode, u32)]) -> Block { + let mut block = Block::default(); + for (i, &(op, arg)) in instructions.iter().enumerate() { + let mut instr = test_instr(op.into(), i as u32 + 1); + instr.arg = OpArg::new(arg); + test_block_push(&mut block, instr); + } + block + } + + #[test] + fn constant_append_sequences_fold_for_iteration_and_membership() { + for (build, append) in [ + (Opcode::BuildList, Opcode::ListAppend), + (Opcode::BuildSet, Opcode::SetAdd), + ] { + for consumer in [Opcode::GetIter, Opcode::ContainsOp] { + for intrinsic in [false, true] { + if intrinsic && build == Opcode::BuildSet { + continue; + } + let mut instructions = vec![(build, 0)]; + for value in [3, 1, 3] { + instructions.extend([(Opcode::LoadSmallInt, value), (append, 1)]); + } + if intrinsic { + instructions.push(( + Opcode::CallIntrinsic1, + IntrinsicFunction1::ListToTuple as u32, + )); + } + let folded_index = instructions.len() - 1; + instructions.push((consumer, 0)); + let mut info = test_code_info(test_sequence_block(&instructions)); + info.blocks + .optimize_basic_block(&mut info.metadata, BlockIdx::new(0)) + .unwrap(); + let block = &info.blocks[0]; + let expected = if build == Opcode::BuildSet { + ConstantData::Frozenset { + elements: vec![int_const(3), int_const(1)], + } + } else { + ConstantData::Tuple { + elements: vec![int_const(3), int_const(1), int_const(3)], + } + }; + assert_eq!( + get_const_value(&info.metadata, &block.instructions[folded_index]), + Some(expected) + ); + } + } + } + } + + #[test] + fn constant_append_sequences_require_unaliased_matching_constant_elements() { + for instructions in [ + vec![ + (Opcode::BuildList, 0), + (Opcode::LoadName, 0), + (Opcode::ListAppend, 1), + ], + vec![ + (Opcode::BuildList, 0), + (Opcode::LoadSmallInt, 1), + (Opcode::SetAdd, 1), + ], + vec![ + (Opcode::BuildSet, 0), + (Opcode::LoadSmallInt, 1), + (Opcode::ListAppend, 1), + ], + vec![ + (Opcode::BuildList, 0), + (Opcode::LoadSmallInt, 1), + (Opcode::ListAppend, 2), + ], + vec![ + (Opcode::BuildList, 0), + (Opcode::BuildList, 0), + (Opcode::ListAppend, 1), + ], + vec![ + (Opcode::BuildList, 0), + (Opcode::Copy, 1), + (Opcode::LoadSmallInt, 1), + (Opcode::ListAppend, 1), + ], + vec![ + (Opcode::BuildList, 0), + (Opcode::LoadConst, 0), + (Opcode::ListAppend, 1), + (Opcode::LoadSmallInt, 1), + (Opcode::ListAppend, 1), + ], + ] { + let mut block = test_sequence_block(&instructions); + let mut metadata = test_code_info(Block::default()).metadata; + assert!( + !fold_constant_sequence_into_load_const( + &mut metadata, + &mut block, + instructions.len() - 1, + ) + .unwrap() + ); + assert!(metadata.consts.is_empty()); + for (instr, (op, arg)) in block.instructions.iter().zip(instructions) { + assert_eq!(instr.instr.real_opcode(), Some(op)); + assert_eq!(u32::from(instr.arg), arg); + } + } + } + + #[test] + fn rejected_constant_append_fold_preserves_instructions() { + for (build, append, intrinsic) in [ + (Opcode::BuildList, Opcode::ListAppend, false), + (Opcode::BuildSet, Opcode::SetAdd, false), + (Opcode::BuildList, Opcode::ListAppend, true), + ] { + let mut block = Block::default(); + for (index, (opcode, arg)) in [ + (build, 0), + ( + Opcode::LoadCommonConstant, + oparg::CommonConstant::BuiltinAny as u32, + ), + (append, 1), + (Opcode::LoadSmallInt, 7), + (append, 1), + ] + .into_iter() + .enumerate() + { + let mut instr = test_instr(Instruction::Nop, index as u32 + 1); + instr.instr = opcode.into(); + instr.arg = OpArg::new(arg); + test_block_push(&mut block, instr); + } + let target = if intrinsic { + let mut instr = test_instr(Instruction::Nop, 6); + instr.instr = Opcode::CallIntrinsic1.into(); + instr.arg = OpArg::new(IntrinsicFunction1::ListToTuple as u32); + test_block_push(&mut block, instr); + 5 + } else { + 4 + }; + let before = block.instructions.clone(); + let mut metadata = test_code_info(Block::default()).metadata; + metadata.consts.insert_full(int_const(42)); + let consts_before = metadata.consts.clone().into_vec(); + + // BuiltinAny is a valid common constant but has no ConstantData + // representation. Reject the fold before changing any of its tail. + assert!( + !fold_constant_sequence_into_load_const(&mut metadata, &mut block, target).unwrap() + ); + assert_eq!(metadata.consts.clone().into_vec(), consts_before); + assert_eq!(block.instructions.len(), before.len()); + for (actual, expected) in block.instructions.iter().zip(&before) { + assert_eq!(actual.instr.real_opcode(), expected.instr.real_opcode()); + assert_eq!(u32::from(actual.arg), u32::from(expected.arg)); + assert_eq!(actual.target, expected.target); + assert_eq!(actual.location, expected.location); + assert_eq!(actual.end_location, expected.end_location); + assert_eq!(actual.except_handler, expected.except_handler); + assert_eq!(actual.semantic_location, expected.semantic_location); + assert_eq!(actual.lineno_override, expected.lineno_override); + } + } + } + + #[test] + fn float_divmod_folds_quotient_and_remainder_independently() { + use oparg::BinaryOperator::{FloorDivide, Remainder}; + + let float = |value| ConstantData::Float { value }; + let smallest = f64::from_bits(1); + for (left, right, quotient, remainder) in [ + (2.0, 2.0, 1.0, 0.0), + (2.0, -2.0, -1.0, -0.0), + (-2.0, -2.0, 1.0, -0.0), + (-2.0, -3.0, 0.0, -2.0), + (-0.0, 2.0, -0.0, 0.0), + (smallest, smallest, 1.0, 0.0), + (1.0, 0.1, 9.0, f64::from_bits(0x3fb9_9999_9999_9996)), + (2.0, f64::NEG_INFINITY, -1.0, f64::NEG_INFINITY), + (f64::INFINITY, 2.0, f64::NAN, f64::NAN), + (f64::NAN, -2.0, f64::NAN, f64::NAN), + ] { + for (op, expected) in [(FloorDivide, quotient), (Remainder, remainder)] { + let Some(ConstantData::Float { value: result }) = + eval_const_binop(&float(left), &float(right), op) + else { + panic!("expected float constant"); + }; + if expected.is_nan() { + assert!(result.is_nan()); + } else { + assert_eq!(result.to_bits(), expected.to_bits()); + } + } + } + assert!(eval_const_binop(&float(2.0), &float(-0.0), FloorDivide).is_none()); + assert!(eval_const_binop(&float(2.0), &float(0.0), Remainder).is_none()); + } + #[test] fn get_stack_effects_rejects_cpython_deopt_opcodes() { match get_stack_effects(Instruction::BinaryOpAddInt.into(), OpArg::new(0), 0) { @@ -7322,6 +7585,7 @@ mod tests { location: SourceLocation::default(), end_location: SourceLocation::default(), except_handler: None, + semantic_location: None, lineno_override: None, }; let handler = push_except_block(&mut stack, setup, &mut blocks).unwrap(); @@ -7465,26 +7729,66 @@ mod tests { } #[test] - fn basicblock_addop_reuses_cpython_spare_except_handler_slot() { + fn redundant_nop_compaction_clears_vacated_instruction_metadata() { let handler = ExceptHandlerInfo { - handler_block: BlockIdx::new(7), + handler_block: BlockIdx::new(2), preserve_lasti: true, }; let mut block = Block::default(); - let mut stale = test_instr(Instruction::Nop, 11); - stale.except_handler = Some(handler); - test_block_push(&mut block, stale); - block.basicblock_clear(); + for _ in 0..2 { + let mut nop = test_instr(Instruction::Nop, 10); + nop.lineno_override = Some(NO_LOCATION_OVERRIDE); + nop.target = BlockIdx::new(1); + nop.except_handler = Some(handler); + test_block_push(&mut block, nop); + } + let mut jump = test_instr(Opcode::PopJumpIfTrue.into(), 10); + jump.target = BlockIdx::new(1); + jump.except_handler = Some(handler); + test_block_push(&mut block, jump); + let mut blocks = Blocks::from([block, Block::default(), Block::default()]); - block - .basicblock_addop(test_instr(Instruction::PopTop, 12)) - .expect("basicblock_addop succeeds"); + assert_eq!(blocks.basicblock_remove_redundant_nops(BlockIdx::new(0)), 2); + assert_eq!(blocks[0].instructions[0].target, jump.target); + assert_eq!(blocks[0].instructions[0].except_handler, Some(handler)); + for slot in &blocks[0].instructions[1..3] { + assert_eq!(slot.target, BlockIdx::NULL); + assert_eq!(slot.except_handler, None); + } - // CPython `basicblock_addop()` writes opcode/oparg/target/location into - // the reused `b_instr[b_iused]` slot, but does not clear `i_except`. - assert_eq!(block.instruction_used, 1); - assert_eq!(block.instructions[0].except_handler, Some(handler)); - assert_eq!(block.instructions[0].target, BlockIdx::NULL); + blocks.normalize_jumps_in_block(BlockIdx::new(0)).unwrap(); + let not_taken = &blocks[0].instructions[1]; + assert_eq!(not_taken.instr.real_opcode(), Some(Opcode::NotTaken)); + assert_eq!(not_taken.except_handler, Some(handler)); + } + + #[test] + fn basicblock_addop_overwrites_spare_exception_handler() { + let stale = ExceptHandlerInfo { + handler_block: BlockIdx::new(7), + preserve_lasti: true, + }; + let replacement = ExceptHandlerInfo { + handler_block: BlockIdx::new(8), + preserve_lasti: false, + }; + for new_handler in [None, Some(replacement)] { + let mut block = Block::default(); + let mut old = test_instr(Instruction::Nop, 11); + old.except_handler = Some(stale); + test_block_push(&mut block, old); + block.basicblock_clear(); + + let mut new = test_instr(Instruction::PopTop, 12); + new.except_handler = new_handler; + block + .basicblock_addop(new) + .expect("basicblock_addop succeeds"); + + assert_eq!(block.instruction_used, 1); + assert_eq!(block.instructions[0].except_handler, new_handler); + assert_eq!(block.instructions[0].target, BlockIdx::NULL); + } } #[test] @@ -7529,64 +7833,6 @@ mod tests { assert_eq!(block.instructions[0].except_handler, None); } - #[test] - fn basicblock_clear_preserves_cpython_spare_slots() { - let handler = ExceptHandlerInfo { - handler_block: BlockIdx::new(3), - preserve_lasti: true, - }; - let mut block = Block::default(); - let mut stale = test_instr(Instruction::PopTop, 31); - stale.except_handler = Some(handler); - test_block_push(&mut block, stale); - - block.basicblock_clear(); - block - .basicblock_addop(test_instr(Instruction::Nop, 32)) - .expect("basicblock_addop succeeds"); - - // CPython `remove_unreachable()` sets `b_iused = 0` without clearing the - // backing `b_instr` slot. A later `basicblock_addop()` reuses that slot - // and does not overwrite `i_except`. - assert_eq!(block.instruction_used, 1); - assert_eq!(block.instructions[0].except_handler, Some(handler)); - } - - #[test] - fn basicblock_clear_reuses_cpython_spare_slots_in_offset_order() { - let mut block = Block::default(); - for i in 0..3 { - let mut stale = test_instr(Instruction::Nop, 35 + i); - stale.except_handler = Some(ExceptHandlerInfo { - handler_block: BlockIdx::new(i + 1), - preserve_lasti: false, - }); - test_block_push(&mut block, stale); - } - - block.basicblock_clear(); - for i in 0..3 { - block - .basicblock_addop(test_instr(Instruction::PopTop, 38 + i)) - .expect("basicblock_addop succeeds"); - } - - let handlers = block - .used_instructions() - .iter() - .map(|instr| { - instr - .except_handler - .expect("reused CPython slot") - .handler_block - }) - .collect::>(); - assert_eq!( - handlers, - [BlockIdx::new(1), BlockIdx::new(2), BlockIdx::new(3)] - ); - } - #[test] fn basicblock_append_instructions_overwrites_cpython_spare_slot() { let handler = ExceptHandlerInfo { @@ -7726,7 +7972,7 @@ mod tests { // CPython `basicblock_optimize_load_const()` keeps the previous // LOAD_CONST as the effective opcode for a following `COPY 1`, so the - // COPY is NOPed and TO_BOOL becomes LOAD_CONST True. + // COPY is NOPed and TO_BOOL becomes LOAD_COMMON_CONSTANT True. assert!(matches!( code.blocks[0].instructions[0].instr.real(), Some(Instruction::LoadConst { .. }) @@ -7738,11 +7984,11 @@ mod tests { let load_bool = &code.blocks[0].instructions[2]; assert!(matches!( load_bool.instr.real(), - Some(Instruction::LoadConst { .. }) + Some(Instruction::LoadCommonConstant { .. }) )); assert_eq!( - code.metadata.consts[u32::from(load_bool.arg) as usize], - ConstantData::Boolean { value: true } + u32::from(load_bool.arg), + u32::from(oparg::CommonConstant::True) ); } @@ -7793,7 +8039,7 @@ mod tests { } #[test] - fn optimize_load_fast_records_no_input_opcode_ref_at_cpython_produced_index() { + fn optimize_load_fast_records_no_input_opcode_ref_at_cpython_instruction_index() { let mut block = Block::default(); test_block_push(&mut block, test_instr(Opcode::LoadFast.into(), 10)); test_block_push(&mut block, test_instr(Instruction::GetLen, 10)); @@ -7807,78 +8053,53 @@ mod tests { .optimize_load_fast() .expect("optimize_load_fast succeeds"); - // CPython `optimize_load_fast()` shadows the outer instruction index in - // the produced-value loop for GET_LEN, so the produced ref is recorded - // with index 0 here. The original LOAD_FAST is therefore not considered - // the consumed producer. + // CPython records GET_LEN's result at instruction index 1. The + // SWAP/POP_TOP consumes the original local reference, so it can borrow. assert!(matches!( code.blocks[0].instructions[0].instr.real(), - Some(Instruction::LoadFast { .. }) + Some(Instruction::LoadFastBorrow { .. }) )); } #[test] - fn constant_sequence_loads_use_cpython_opcode_has_const_metadata() { - let mut metadata = CodeUnitMetadata { - name: "".to_owned(), - qualname: Some("".to_owned()), - consts: Default::default(), - names: IndexSet::default(), - varnames: IndexSet::default(), - cellvars: IndexSet::default(), - freevars: IndexSet::default(), - fast_hidden: IndexMap::default(), - fast_hidden_final: IndexSet::default(), - argcount: 0, - posonlyargcount: 0, - kwonlyargcount: 0, - firstlineno: OneIndexed::MIN, - }; - let (left, _) = metadata - .consts - .insert_full(ConstantData::Str { value: "a".into() }); - let (right, _) = metadata - .consts - .insert_full(ConstantData::Str { value: "b".into() }); - - let mut immortal = test_instr(Instruction::Nop, 90); - immortal.instr = Opcode::LoadConstImmortal.into(); - immortal.arg = OpArg::new(left as u32); - let mut mortal = test_instr(Instruction::Nop, 90); - mortal.instr = Opcode::LoadConstMortal.into(); - mortal.arg = OpArg::new(right as u32); - let mut build = test_instr(Opcode::BuildTuple.into(), 90); - build.arg = OpArg::new(2); - let mut block = Block::default(); - for info in [immortal, mortal, build] { - test_block_push(&mut block, info); - } - - assert!( - fold_tuple_of_constants(&mut metadata, &mut block, 2) - .expect("fold_tuple_of_constants succeeds") - ); + fn integer_true_division_folds_the_exact_quotient() { + use oparg::BinaryOperator::TrueDivide; - // CPython `loads_const()` accepts every `OPCODE_HAS_CONST` opcode, not - // just canonical LOAD_CONST, so LOAD_CONST_IMMORTAL/MORTAL participate - // in constant-sequence folding. - assert!(matches!( - block.instructions[0].instr.real(), - Some(Instruction::Nop) - )); - assert!(matches!( - block.instructions[1].instr.real(), - Some(Instruction::Nop) - )); - let folded = &block.instructions[2]; - assert!(matches!( - folded.instr.real(), - Some(Instruction::LoadConst { .. }) - )); - assert!(matches!( - &metadata.consts[u32::from(folded.arg) as usize], - ConstantData::Tuple { elements } if elements.len() == 2 - )); + let ten_to_310 = BigInt::from(10_u8).pow(310_u32); + let ten_to_400 = BigInt::from(10_u8).pow(400_u32); + let integer = |value| ConstantData::Integer { value }; + let cases = [ + ( + BigInt::from((1_u64 << 53) + 1), + BigInt::from(3), + Some(0x4325_5555_5555_5556), + ), + ( + BigInt::from(1), + ten_to_310.clone(), + Some(0x0000_1268_8b70_e62b), + ), + (ten_to_310.clone(), ten_to_310, Some(1.0_f64.to_bits())), + (BigInt::from(0), -&ten_to_400, Some((-0.0_f64).to_bits())), + ( + BigInt::from(-1), + ten_to_400.clone(), + Some((-0.0_f64).to_bits()), + ), + (ten_to_400, BigInt::from(2), None), + (BigInt::from(1), BigInt::from(0), None), + ]; + + for (numerator, denominator, expected) in cases { + let result = eval_const_binop(&integer(numerator), &integer(denominator), TrueDivide); + assert_eq!( + result.map(|result| match result { + ConstantData::Float { value } => value.to_bits(), + other => panic!("expected float, got {other:?}"), + }), + expected + ); + } } #[test] diff --git a/crates/codegen/src/lib.rs b/crates/codegen/src/lib.rs index 0bc16d72ded..089f7ab496c 100644 --- a/crates/codegen/src/lib.rs +++ b/crates/codegen/src/lib.rs @@ -8,7 +8,7 @@ extern crate log; extern crate alloc; -use alloc::{string::String, vec::Vec}; +use alloc::string::String; use rustpython_compiler_core::bytecode::ConstantData; type IndexMap = indexmap::IndexMap; @@ -18,6 +18,7 @@ pub mod compile; pub mod error; pub mod ir; pub mod preprocess; +pub mod source_location; mod string_parser; pub mod symboltable; mod unparse; @@ -188,12 +189,14 @@ pub fn interpolation_debug_text( ) -> (String, TextRange) { let leading = debug_text.leading(); let trailing = debug_text.trailing(); - let text = [ - strip_python_comments(leading).as_str(), - source_file.source_text().slice(expression_range), - strip_python_comments(trailing).as_str(), - ] - .concat(); + let text = strip_python_comments( + &[ + leading, + source_file.source_text().slice(expression_range), + trailing, + ] + .concat(), + ); let width = |len: usize| TextSize::new(u32::try_from(len).expect("debug interpolation text too long")); let range = TextRange::new( @@ -203,64 +206,109 @@ pub fn interpolation_debug_text( (text, range) } +/// The source text stored in a template interpolation, including whitespace +/// before its debug marker, conversion, format specifier, or closing brace. +/// Returns `None` for a synthetic node without a source interpolation range. +#[must_use] +pub fn interpolation_expression_text( + source_file: &SourceFile, + interpolation: &ast::InterpolatedElement, +) -> Option { + if let Some(debug_text) = &interpolation.debug_text { + let mut text = strip_python_comments(debug_text.as_str()); + let end = interpolation_suffix_end(&text); + if text[..end].ends_with('=') { + text.truncate(end - 1); + } + return Some(text); + } + + let expression_range = interpolation.expression.range(); + if interpolation.range.start() >= expression_range.start() + || interpolation.range.end() <= expression_range.end() + { + return None; + } + let start = interpolation.range.start() + TextSize::new(1); + let end = interpolation + .format_spec + .as_ref() + .map_or_else( + || interpolation.range.end(), + |format_spec| format_spec.range.start(), + ) + .checked_sub(TextSize::new(1))?; + if start > expression_range.start() || end < expression_range.end() { + return None; + } + let mut text = + strip_python_comments(source_file.source_text().slice(TextRange::new(start, end))); + if interpolation.conversion != ast::ConversionFlag::None { + let end = interpolation_suffix_end(&text); + let conversion_start = end.checked_sub(2)?; + if text.as_bytes().get(conversion_start) != Some(&b'!') { + return None; + } + text.truncate(conversion_start); + } + Some(text) +} + +fn interpolation_suffix_end(text: &str) -> usize { + let mut end = text.len(); + // Debug markers and conversions can be followed by whitespace and line + // continuations. Whitespace preceding either marker remains significant. + loop { + let trimmed = text[..end].trim_end(); + let has_newline = text[trimmed.len()..end].contains(['\n', '\r']); + end = trimmed.len(); + if has_newline && text[..end].ends_with('\\') { + end -= 1; + } else { + return end; + } + } +} + fn strip_python_comments(text: &str) -> String { - let chars = text.chars().collect::>(); + // Tokenizer metadata uses universal newlines even when source ranges refer + // to the original CRLF or CR input. + let normalized; + let text = if text.contains('\r') { + normalized = text.replace("\r\n", "\n").replace('\r', "\n"); + normalized.as_str() + } else { + text + }; + let mut chars = text.chars(); let mut result = String::with_capacity(text.len()); let mut quote = None; - let mut triple_quoted = false; - let mut escaped = false; - let mut in_comment = false; - let mut index = 0; - while index < chars.len() { - let ch = chars[index]; - if in_comment { - if matches!(ch, '\n' | '\r') { - in_comment = false; - result.push(ch); - } - index += 1; - continue; - } - - if let Some(delimiter) = quote { + while let Some(ch) = chars.next() { + // Match tokenizer metadata reconstruction, including escaped quotes + // outside literals and its per-quote handling of triple strings. + if ch == '\\' { result.push(ch); - if escaped { - escaped = false; - } else if ch == '\\' { - escaped = true; - } else if triple_quoted - && ch == delimiter - && chars.get(index + 1) == Some(&delimiter) - && chars.get(index + 2) == Some(&delimiter) - { - result.push(delimiter); - result.push(delimiter); - quote = None; - index += 2; - } else if !triple_quoted && ch == delimiter { - quote = None; + if let Some(escaped) = chars.next() { + result.push(escaped); } - index += 1; - continue; - } - - match ch { - '#' => in_comment = true, - '\'' | '"' => { + } else if matches!(ch, '\'' | '"') { + if quote.is_none() { quote = Some(ch); - triple_quoted = - chars.get(index + 1) == Some(&ch) && chars.get(index + 2) == Some(&ch); - result.push(ch); - if triple_quoted { - result.push(ch); - result.push(ch); - index += 2; + } else if quote == Some(ch) { + quote = None; + } + result.push(ch); + } else if ch == '#' && quote.is_none() { + for comment_ch in chars.by_ref() { + if comment_ch == '\n' { + result.push('\n'); + break; } } - _ => result.push(ch), + } else { + result.push(ch); } - index += 1; } result } diff --git a/crates/codegen/src/preprocess.rs b/crates/codegen/src/preprocess.rs index 466d8f35ebe..8bd16f106a8 100644 --- a/crates/codegen/src/preprocess.rs +++ b/crates/codegen/src/preprocess.rs @@ -1,4 +1,10 @@ -use alloc::{boxed::Box, string::String, vec::Vec}; +use alloc::{ + boxed::Box, + string::{String, ToString}, + vec::Vec, +}; +use malachite_bigint::BigInt; +use num_traits::ToPrimitive; use ruff_python_ast::{ self as ast, AtomicNodeIndex, ConversionFlag, Expr, ExprFString, FString, FStringFlags, @@ -9,8 +15,9 @@ use ruff_python_ast::{ }; use ruff_text_size::{Ranged, TextRange}; -use crate::compile::FutureFeature; -use rustpython_compiler_core::bytecode; +use crate::compile::{FutureFeature, ruff_int_to_bigint}; +use core::cell::{Cell, RefCell}; +use rustpython_compiler_core::{AstLocationError, AstLocations, SourceLocationRange, bytecode}; const MAXDIGITS: usize = 3; const F_LJUST: u8 = 1; @@ -206,6 +213,28 @@ pub enum FutureFeatureErrorKind { InvalidBraces, } +/// Classify one imported name like CPython's future_check_features. +pub(crate) fn future_alias_flags( + name: &str, +) -> Result { + let feature = name + .try_into() + .map_err(FutureFeatureErrorKind::InvalidFeature)?; + Ok(match feature { + FutureFeature::Braces => return Err(FutureFeatureErrorKind::InvalidBraces), + FutureFeature::Annotations => bytecode::CodeFlags::FUTURE_ANNOTATIONS, + FutureFeature::BarryAsFLUFL => bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL, + FutureFeature::AbsoluteImport + | FutureFeature::Division + | FutureFeature::GeneratorStop + | FutureFeature::Generators + | FutureFeature::NestedScopes + | FutureFeature::PrintFunction + | FutureFeature::UnicodeLiterals + | FutureFeature::WithStatement => bytecode::CodeFlags::empty(), + }) +} + pub fn checked_future_features( module: &ast::Mod, ) -> Result { @@ -234,42 +263,14 @@ pub fn checked_future_features_in_body( .. }) if *level == 0 && module.as_ref().map(|id| id.as_str()) == Some("__future__") => { for alias in names { - let future_feature = - alias - .name - .as_str() - .try_into() - .map_err(|name| FutureFeatureError { - features: future_features, - range: alias.range, - kind: FutureFeatureErrorKind::InvalidFeature(name), - })?; - - match future_feature { - FutureFeature::Braces => { - return Err(FutureFeatureError { - features: future_features, - range: alias.range, - kind: FutureFeatureErrorKind::InvalidBraces, - }); + let flags = future_alias_flags(alias.name.as_str()).map_err(|kind| { + FutureFeatureError { + features: future_features, + range: alias.range, + kind, } - FutureFeature::Annotations => { - future_features.insert(bytecode::CodeFlags::FUTURE_ANNOTATIONS) - } - FutureFeature::BarryAsFLUFL => { - future_features.insert(bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL) - } - FutureFeature::AbsoluteImport - | FutureFeature::Division - | FutureFeature::GeneratorStop - | FutureFeature::Generators - | FutureFeature::NestedScopes - | FutureFeature::PrintFunction - | FutureFeature::UnicodeLiterals - | FutureFeature::WithStatement => { - // Python 3 features. They are already implemented by default. - } - } + })?; + future_features |= flags; } } _ => return Ok(future_features), @@ -288,6 +289,8 @@ pub fn preprocess_statements( optimize, future_annotations, constant_folding: !syntax_check_only, + locations: None, + location_error: None, }; for stmt in body { preprocessor.visit_stmt(stmt); @@ -304,25 +307,147 @@ pub fn preprocess_mod( optimize, future_annotations, constant_folding: !syntax_check_only, + locations: None, + location_error: None, + }; + match module { + ast::Mod::Module(module) => preprocessor.visit_astfold_body(&mut module.body), + ast::Mod::Expression(expr) => preprocessor.visit_expr(&mut expr.body), + } +} + +/// Run preprocessing while retaining explicit Python AST location provenance. +/// The table is borrowed only inside native transformations, never across Python calls. +pub fn preprocess_mod_with_locations( + module: &mut ast::Mod, + optimize: u8, + future_annotations: bool, + syntax_check_only: bool, + locations: &mut AstLocations, +) -> Result<(), AstLocationError> { + let table = RefCell::new(core::mem::take(locations)); + let error = Cell::new(None); + let preprocessor = AstPreprocessor { + optimize, + future_annotations, + constant_folding: !syntax_check_only, + locations: Some(&table), + location_error: Some(&error), }; match module { ast::Mod::Module(module) => preprocessor.visit_astfold_body(&mut module.body), ast::Mod::Expression(expr) => preprocessor.visit_expr(&mut expr.body), } + *locations = table.into_inner(); + error.get().map_or(Ok(()), Err) +} + +pub fn preprocess_statements_with_locations( + body: &mut [ast::Stmt], + optimize: u8, + future_annotations: bool, + syntax_check_only: bool, + locations: &mut AstLocations, +) -> Result<(), AstLocationError> { + let table = RefCell::new(core::mem::take(locations)); + let error = Cell::new(None); + let preprocessor = AstPreprocessor { + optimize, + future_annotations, + constant_folding: !syntax_check_only, + locations: Some(&table), + location_error: Some(&error), + }; + for stmt in body { + preprocessor.visit_stmt(stmt); + } + *locations = table.into_inner(); + error.get().map_or(Ok(()), Err) } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -struct AstPreprocessor { +#[derive(Clone, Copy)] +struct AstPreprocessor<'a> { optimize: u8, future_annotations: bool, constant_folding: bool, + locations: Option<&'a RefCell>, + location_error: Option<&'a Cell>>, } -impl AstPreprocessor { +impl AstPreprocessor<'_> { + fn record_location_error(&self, error: AstLocationError) { + if let Some(slot) = self.location_error + && slot.get().is_none() + { + slot.set(Some(error)); + } + } + + fn location(&self, node: &impl HasNodeIndex) -> Option { + self.locations? + .borrow() + .get(node.node_index().load().as_u32()?) + } + + fn fresh_location(&self, location: SourceLocationRange) -> AtomicNodeIndex { + let index = AtomicNodeIndex::NONE; + if let Some(locations) = self.locations { + match locations.borrow_mut().allocate(Some(location)) { + Ok(id) => index.set(ast::NodeIndex::from(id)), + Err(error) => self.record_location_error(error), + } + } + index + } + + fn artificial_elements(&self, elements: &mut InterpolatedStringElements) { + if self.locations.is_none() { + return; + } + let artificial = SourceLocationRange { + line: -1, + end_line: -1, + col: -1, + end_col: -1, + }; + for element in elements.iter_mut() { + match element { + InterpolatedStringElement::Literal(literal) => { + if literal.node_index.load().as_u32().is_none() { + literal.node_index = self.fresh_location(artificial); + } + } + InterpolatedStringElement::Interpolation(value) => { + if let Some(spec) = &mut value.format_spec { + if spec.node_index.load().as_u32().is_none() { + spec.node_index = self.fresh_location(artificial); + } + self.artificial_elements(&mut spec.elements); + // This visitor only runs on the result of optimize_format. + // final ast_preprocess.c constructs a Constant format spec, + // not a JoinedStr. Preserve that explicit shape in the + // existing runtime AST field rather than inferring it + // from the artificial coordinates during serialization. + if let [InterpolatedStringElement::Literal(literal)] = &spec.elements[..] { + value.runtime_formatted_value_format_spec = + Some(Box::new(Expr::Constant(ast::ExprConstant { + node_index: spec.node_index.clone(), + range: spec.range, + value: ast::ConstantValue::Str(literal.value.clone()), + kind: None, + invalid_type: None, + }))); + } + } + } + } + } + } + fn visit_astfold_body(self, body: &mut ast::Suite) { let mut docstring = body_starts_with_docstring(body); if docstring && self.optimize >= 2 { - remove_docstring_from_body(body); + remove_docstring_from_body(body, &self); docstring = false; } @@ -331,12 +456,12 @@ impl AstPreprocessor { } if !docstring && body_starts_with_docstring(body) { - wrap_first_docstring_as_fstring(body); + wrap_first_docstring_as_fstring(body, self.locations.is_some()); } } } -impl Transformer for AstPreprocessor { +impl Transformer for AstPreprocessor<'_> { fn visit_stmt(&self, stmt: &mut ast::Stmt) { match stmt { ast::Stmt::FunctionDef(function) => { @@ -394,7 +519,14 @@ impl Transformer for AstPreprocessor { transformer::walk_expr(self, expr); widen_implicit_call_generator_range(expr); if self.constant_folding { - if let Some(optimized) = optimize_format(expr) { + if let Some(mut optimized) = optimize_format(expr) { + if let Expr::FString(fstring) = &mut optimized { + for part in &mut fstring.value { + if let ast::FStringPartMut::FString(part) = part { + self.artificial_elements(&mut part.elements); + } + } + } *expr = optimized; } else if let Some(optimized) = fold_debug_constant(expr, self.optimize) { *expr = optimized; @@ -632,15 +764,27 @@ fn generated_literal(value: String) -> InterpolatedStringLiteralElement { } } -fn remove_docstring_from_body(body: &mut ast::Suite) { +fn remove_docstring_from_body(body: &mut ast::Suite, preprocessor: &AstPreprocessor<'_>) { + let statement_location = body.first().and_then(|node| preprocessor.location(node)); if let Some(range) = take_docstring(body) { if !body.is_empty() { return; } let start = range.start(); let pass_range = TextRange::new(start, start + ruff_text_size::TextSize::from(4)); + let node_index = statement_location.map_or(AtomicNodeIndex::NONE, |location| { + let Some(end_col) = location.col.checked_add(4) else { + preprocessor.record_location_error(AstLocationError::CoordinateOverflow); + return AtomicNodeIndex::NONE; + }; + preprocessor.fresh_location(SourceLocationRange { + end_line: location.line, + end_col, + ..location + }) + }); body.push(ast::Stmt::Pass(ast::StmtPass { - node_index: Default::default(), + node_index, range: pass_range, })); } @@ -664,7 +808,7 @@ fn body_starts_with_docstring(body: &[ast::Stmt]) -> bool { string_literal_expr_value(&expr_stmt.value).is_some() } -fn wrap_first_docstring_as_fstring(body: &mut [ast::Stmt]) { +fn wrap_first_docstring_as_fstring(body: &mut [ast::Stmt], explicit_locations: bool) { let Some(ast::Stmt::Expr(expr_stmt)) = body.first_mut() else { return; }; @@ -672,16 +816,27 @@ fn wrap_first_docstring_as_fstring(body: &mut [ast::Stmt]) { return; }; let value = value.to_string(); + let literal_index = expr_stmt.value.node_index().clone(); + let wrapper_range = if explicit_locations { + expr_stmt.range + } else { + range + }; + let wrapper_index = if explicit_locations { + expr_stmt.node_index.clone() + } else { + AtomicNodeIndex::NONE + }; *expr_stmt.value = ast::Expr::FString(ast::ExprFString { - node_index: AtomicNodeIndex::NONE, - range, + node_index: wrapper_index.clone(), + range: wrapper_range, value: FStringValue::single(FString { - range, - node_index: AtomicNodeIndex::NONE, + range: wrapper_range, + node_index: wrapper_index, elements: InterpolatedStringElements::from(vec![InterpolatedStringElement::Literal( InterpolatedStringLiteralElement { range, - node_index: AtomicNodeIndex::NONE, + node_index: literal_index, value: value.into_boxed_str(), }, )]), @@ -703,99 +858,175 @@ fn string_literal_expr_value(expr: &Expr) -> Option<(&str, TextRange)> { } } -fn fold_match_value_constant_expr(expr: &mut ast::Expr) { - match expr { - ast::Expr::UnaryOp(unary) - if matches!(unary.op, ast::UnaryOp::USub) - && matches!(unary.operand.as_ref(), ast::Expr::NumberLiteral(_)) => - { - if let Some(number) = negate_match_number(&unary.operand) { - *expr = ast::Expr::NumberLiteral(ast::ExprNumberLiteral { - node_index: unary.node_index.clone(), - range: unary.range, - value: number, - }); - } +/// Numeric constants have two representations before preprocessing: Ruff's +/// unsigned literal token and the Constant value from Python AST input. +enum MatchNumber { + Int(BigInt), + Float(f64), + Complex { real: f64, imag: f64 }, +} + +impl MatchNumber { + fn from_expr(expr: &Expr) -> Option { + Some(match expr { + Expr::NumberLiteral(node) => match &node.value { + ast::Number::Int(value) => Self::Int(ruff_int_to_bigint(value).ok()?), + ast::Number::Float(value) => Self::Float(*value), + ast::Number::Complex { real, imag } => Self::Complex { + real: *real, + imag: *imag, + }, + }, + Expr::Constant(node) => match &node.value { + ast::ConstantValue::Integer(value) => Self::Int(value.parse().ok()?), + ast::ConstantValue::Float(value) => Self::Float(*value), + ast::ConstantValue::Complex { real, imag } => Self::Complex { + real: *real, + imag: *imag, + }, + _ => return None, + }, + _ => return None, + }) + } + + fn negated(self) -> Self { + match self { + Self::Int(value) => Self::Int(-value), + Self::Float(value) => Self::Float(-value), + Self::Complex { real, imag } => Self::Complex { + real: -real, + imag: -imag, + }, } - ast::Expr::BinOp(binop) if matches!(binop.op, ast::Operator::Add | ast::Operator::Sub) => { - fold_match_value_constant_expr(&mut binop.left); - if let Some(number) = fold_match_number_binop(&binop.left, binop.op, &binop.right) { - *expr = ast::Expr::NumberLiteral(ast::ExprNumberLiteral { - node_index: binop.node_index.clone(), - range: binop.range, - value: number, - }); - } + } + + fn into_constant(self) -> ast::ConstantValue { + match self { + Self::Int(value) => ast::ConstantValue::Integer(value.to_string().into_boxed_str()), + Self::Float(value) => ast::ConstantValue::Float(value), + Self::Complex { real, imag } => ast::ConstantValue::Complex { real, imag }, } - _ => {} } } -fn negate_match_number(expr: &ast::Expr) -> Option { - let ast::Expr::NumberLiteral(number) = expr else { - return None; - }; - Some(match &number.value { - ast::Number::Int(value) => { - if *value == ast::Int::ZERO { - ast::Number::Int(ast::Int::ZERO) - } else { - return None; - } +fn fold_match_value_constant_expr(expr: &mut Expr) { + let folded = match expr { + Expr::UnaryOp(unary) if matches!(unary.op, ast::UnaryOp::UAdd | ast::UnaryOp::USub) => { + MatchNumber::from_expr(&unary.operand).map(|value| { + if unary.op == ast::UnaryOp::USub { + value.negated() + } else { + value + } + }) } - ast::Number::Float(value) => ast::Number::Float(-value), - ast::Number::Complex { real, imag } => ast::Number::Complex { - real: -real, - imag: -imag, - }, - }) + Expr::BinOp(binop) if matches!(binop.op, Operator::Add | Operator::Sub) => { + fold_match_value_constant_expr(&mut binop.left); + fold_match_number_binop(&binop.left, binop.op, &binop.right) + } + _ => None, + }; + if let Some(value) = folded { + *expr = Expr::Constant(ast::ExprConstant { + node_index: expr.node_index().clone(), + range: expr.range(), + value: value.into_constant(), + kind: None, + invalid_type: None, + }); + } } -fn fold_match_number_binop( - left: &ast::Expr, - op: ast::Operator, - right: &ast::Expr, -) -> Option { - let ast::Expr::NumberLiteral(left) = left else { +fn fold_match_number_binop(left: &Expr, op: Operator, right: &Expr) -> Option { + let MatchNumber::Complex { real, imag } = MatchNumber::from_expr(right)? else { return None; }; - let ast::Expr::NumberLiteral(right) = right else { - return None; - }; - let right = match right.value { - ast::Number::Complex { real, imag } => (real, imag), - _ => return None, - }; - enum MatchNumberLeft { - Real(f64), - Complex { real: f64, imag: f64 }, - } - let left = match &left.value { - ast::Number::Int(value) => MatchNumberLeft::Real(value.as_i64()? as f64), - ast::Number::Float(value) => MatchNumberLeft::Real(*value), - ast::Number::Complex { real, imag } => MatchNumberLeft::Complex { - real: *real, - imag: *imag, - }, - }; - let (real, imag) = match (left, op) { - (MatchNumberLeft::Real(left), ast::Operator::Add) => (left + right.0, right.1), - (MatchNumberLeft::Real(left), ast::Operator::Sub) => (left - right.0, -right.1), - (MatchNumberLeft::Complex { real, imag }, ast::Operator::Add) => { - (real + right.0, imag + right.1) + let left = match MatchNumber::from_expr(left)? { + MatchNumber::Int(value) => { + // CPython refuses to convert an overflowing integer to float and + // leaves the binary expression unfolded in this optimization pass. + let value = value.to_f64()?; + if !value.is_finite() { + return None; + } + value } - (MatchNumberLeft::Complex { real, imag }, ast::Operator::Sub) => { - (real - right.0, imag - right.1) + MatchNumber::Float(value) => value, + MatchNumber::Complex { + real: left_real, + imag: left_imag, + } => { + return Some(match op { + Operator::Add => MatchNumber::Complex { + real: left_real + real, + imag: left_imag + imag, + }, + Operator::Sub => MatchNumber::Complex { + real: left_real - real, + imag: left_imag - imag, + }, + _ => return None, + }); } + }; + let (real, imag) = match op { + Operator::Add => (left + real, imag), + Operator::Sub => (left - real, -imag), _ => return None, }; - Some(ast::Number::Complex { real, imag }) + Some(MatchNumber::Complex { real, imag }) } #[cfg(test)] mod tests { use super::*; + #[test] + fn preprocessing_preserves_first_location_error() { + for first_error in [ + AstLocationError::ExhaustedNodeIdentities, + AstLocationError::CoordinateOverflow, + ] { + let ast::Mod::Module(mut module) = + ruff_python_parser::parse("\"doc\"", ruff_python_parser::Mode::Module.into()) + .unwrap() + .into_syntax() + else { + panic!("expected module"); + }; + let location = SourceLocationRange { + line: 1, + end_line: 1, + col: i32::MAX, + end_col: i32::MAX, + }; + let mut locations = AstLocations::default(); + // One entry exhausts the identity cursor without allocating a huge AST. + locations.insert(AstLocations::MAX_ID, location).unwrap(); + module.body[0] + .node_index() + .set(ast::NodeIndex::from(AstLocations::MAX_ID)); + let locations = RefCell::new(locations); + let error = Cell::new(None); + let preprocessor = AstPreprocessor { + optimize: 2, + future_annotations: false, + constant_folding: true, + locations: Some(&locations), + location_error: Some(&error), + }; + + if first_error == AstLocationError::ExhaustedNodeIdentities { + preprocessor.fresh_location(location); + } + remove_docstring_from_body(&mut module.body, &preprocessor); + assert_eq!(error.get(), Some(first_error)); + preprocessor.fresh_location(location); + assert_eq!(error.get(), Some(first_error)); + } + } + fn first_match_value(source: &str) -> ast::Expr { let parsed = ruff_python_parser::parse(source, ruff_python_parser::Mode::Module.into()) .unwrap() @@ -851,10 +1082,10 @@ match value: pass ", ); - let ast::Expr::NumberLiteral(number) = value else { - panic!("expected folded number literal, got {value:?}"); + let ast::Expr::Constant(number) = value else { + panic!("expected folded constant, got {value:?}"); }; - assert!(matches!(number.value, ast::Number::Float(value) if value == -1.5)); + assert!(matches!(number.value, ast::ConstantValue::Float(value) if value == -1.5)); } #[test] @@ -866,11 +1097,11 @@ match value: pass ", ); - let ast::Expr::NumberLiteral(number) = value else { - panic!("expected folded number literal, got {value:?}"); + let ast::Expr::Constant(number) = value else { + panic!("expected folded constant, got {value:?}"); }; assert!( - matches!(number.value, ast::Number::Complex { real, imag } if real == 1.0 && imag == 2.0) + matches!(number.value, ast::ConstantValue::Complex { real, imag } if real == 1.0 && imag == 2.0) ); } @@ -895,7 +1126,7 @@ match value: let number = fold_match_number_binop(&left, ast::Operator::Add, &right) .expect("CPython fold_const_match_patterns() uses PyNumber_Add"); assert!( - matches!(number, ast::Number::Complex { real, imag } if real == 0.0 && imag == 3.0) + matches!(number, MatchNumber::Complex { real, imag } if real == 0.0 && imag == 3.0) ); } @@ -908,11 +1139,13 @@ match value: pass ", ); - let ast::Expr::NumberLiteral(number) = value else { - panic!("expected folded number literal, got {value:?}"); + let ast::Expr::Constant(number) = value else { + panic!("expected folded constant, got {value:?}"); }; - assert!(matches!(number.value, ast::Number::Complex { real, imag } - if real == 0.0 && imag == 0.0 && imag.is_sign_negative())); + assert!( + matches!(number.value, ast::ConstantValue::Complex { real, imag } + if real == 0.0 && imag == 0.0 && imag.is_sign_negative()) + ); } #[test] diff --git a/crates/codegen/src/source_location.rs b/crates/codegen/src/source_location.rs new file mode 100644 index 00000000000..371d915be0f --- /dev/null +++ b/crates/codegen/src/source_location.rs @@ -0,0 +1,40 @@ +//! Explicit locations supplied by Python AST objects. +//! +//! Parser input continues to resolve its text ranges through the source file. +//! AST input needs node identity because absent columns and a real column zero +//! can produce the same normalized text range. + +use ruff_python_ast::HasNodeIndex; +use ruff_text_size::TextRange; +use rustpython_compiler_core::{AstLocations, SourceLocationRange}; + +/// NONE is a shared placeholder and can never identify semantic coordinates. +pub(crate) fn node_location( + locations: &AstLocations, + node: &impl HasNodeIndex, +) -> Option { + locations.get(node.node_index().load().as_u32()?) +} + +/// Navigation range and semantic coordinates must be saved/restored together. +#[derive(Clone, Copy, Debug)] +pub(crate) struct CompilerSourceSpan { + pub range: TextRange, + pub location: Option, +} + +impl CompilerSourceSpan { + pub(crate) fn is_artificial(self) -> bool { + self.location.map_or_else( + || self.range == TextRange::default(), + |location| location.line < 0, + ) + } + + pub(crate) const fn parsed(range: TextRange) -> Self { + Self { + range, + location: None, + } + } +} diff --git a/crates/codegen/src/symboltable.rs b/crates/codegen/src/symboltable.rs index bff326087e6..664a416f5a9 100644 --- a/crates/codegen/src/symboltable.rs +++ b/crates/codegen/src/symboltable.rs @@ -505,6 +505,14 @@ fn inline_comprehension( existing.flags.insert(sub_symbol.flags); existing.scope = scope; } + // Propagate references to enclosing bindings, not class locals or + // comprehension-local iteration variables. + if scope == SymbolScope::Free + && parent_type != CompilerScope::Class + && sub_symbol.flags.contains(SymbolFlags::USE) + { + existing.flags.insert(SymbolFlags::USE); + } // Name exists in parent if existing.is_bound() && parent_type != CompilerScope::Class { // Check if the name is free in any child of the comprehension @@ -526,6 +534,21 @@ fn inline_comprehension( symbol.scope = scope; parent_symbols.insert(name.clone(), symbol); } + + // An inlined comprehension contributes its symbols before + // update_symbols(), including forwarding-only FREE entries. Those + // entries have no flags of their own but are no longer placeholders + // introduced solely to forward a nested scope's free variable. + if parent_type == CompilerScope::Class + && scope == SymbolScope::Free + && comp_free.contains(name) + { + parent_symbols + .get_mut(name) + .unwrap() + .flags + .insert(SymbolFlags::DEF_FREE_CLASS); + } } removed_class_implicits } @@ -740,6 +763,9 @@ impl SymbolTableAnalyzer { // Analyze symbols in current scope let function_like_scope = SymbolTableBuilder::is_function_like_scope(symbol_table.typ); + // Class implicit cells satisfy child requests, not this scope's own + // closure. Keep its free names out of drop_class_free(). + let mut scope_free = IndexSet::default(); for symbol in symbol_table.symbols.values_mut() { self.analyze_symbol( symbol, @@ -760,7 +786,7 @@ impl SymbolTableAnalyzer { if symbol.scope == SymbolScope::Free || symbol.flags.contains(SymbolFlags::DEF_FREE_CLASS) { - newfree.insert(symbol.name.clone()); + scope_free.insert(symbol.name.clone()); } } @@ -791,12 +817,17 @@ impl SymbolTableAnalyzer { // generator expressions. if symbol_table.typ == CompilerScope::Class || symbol_table.can_see_class_scope { for name in &newfree { - if let Some(symbol) = symbol_table.symbols.get_mut(name) { + if let Some(symbol) = symbol_table.symbols.get_mut(name) + // Forwarding-only entries do not exist until update_symbols() + // inserts them as FREE; they do not get DEF_FREE_CLASS. + && !symbol.flags.is_empty() + { symbol.flags.insert(SymbolFlags::DEF_FREE_CLASS); } } } + newfree.extend(scope_free); Ok(newfree) } @@ -987,16 +1018,7 @@ impl SymbolTableAnalyzer { name == "__classdict__" || name == "__conditional_annotations__"; for (table, typ, _skip) in self.tables.iter_mut().rev().take(decl_depth) { - if let CompilerScope::Class = typ { - if let Some(free_class) = table.get_mut(name) { - free_class.flags.insert(SymbolFlags::DEF_FREE_CLASS) - } else { - let mut symbol = Symbol::new(name.clone()); - symbol.flags.insert(SymbolFlags::DEF_FREE_CLASS); - symbol.scope = SymbolScope::Free; - table.insert(name.to_owned(), symbol); - } - } else if is_class_implicit + if is_class_implicit && matches!( typ, CompilerScope::Function @@ -1063,6 +1085,22 @@ enum SymbolUsage { TypeParam, } +bitflags! { + // Statement traversal state, owned by the current lexical scope. + #[derive(Clone, Copy)] + struct ScanRegion: u8 { + const CONDITIONAL = 1 << 0; + const TRY = 1 << 1; + } +} + +/// A scope owns a statement visit region only while its visit is active. +#[derive(Clone, Copy)] +struct ActiveScanRegion { + owner: usize, + flags: ScanRegion, +} + struct SymbolTableBuilder { class_name: Option, // Scope stack. @@ -1070,17 +1108,12 @@ struct SymbolTableBuilder { future_annotations: bool, allow_top_level_await: bool, source_file: SourceFile, - // Current scope's varnames being collected (temporary storage) - current_varnames: Vec, - // Stack to preserve parent varnames when entering nested scopes - varnames_stack: Vec>, // Track if we're inside an iterable definition expression (for nested comprehensions) in_iter_def_exp: bool, // yield/yield from inside comprehension scopes is rejected with a // message that names the comprehension kind. comprehension_yield_context: Option<&'static str>, - // PEP 649: Track if we're inside a conditional block (if/for/while/etc.) - in_conditional_block: bool, + active_scan_region: Option, // Mirrors symtable ENTER_RECURSIVE guards during compilation. recursion_depth: usize, recursion_limit: usize, @@ -1117,11 +1150,9 @@ impl SymbolTableBuilder { future_annotations: false, allow_top_level_await: false, source_file, - current_varnames: Vec::new(), - varnames_stack: Vec::new(), in_iter_def_exp: false, comprehension_yield_context: None, - in_conditional_block: false, + active_scan_region: None, recursion_depth: 0, recursion_limit: DEFAULT_RECURSION_LIMIT, next_block_index: 0, @@ -1178,8 +1209,6 @@ impl SymbolTableBuilder { fn finish(mut self) -> Result { assert_eq!(self.tables.len(), 1); let mut symbol_table = self.tables.pop().unwrap(); - // Save varnames for the top-level module scope - symbol_table.varnames = self.current_varnames; // Propagate future_annotations to the symbol table symbol_table.future_annotations = self.future_annotations; analyze_symbol_table(&mut symbol_table)?; @@ -1213,9 +1242,6 @@ impl SymbolTableBuilder { table.future_annotations = self.future_annotations; table.mangled_names = inherited_mangled_names; self.tables.push(table); - // Save parent's varnames and start fresh for the new scope - self.varnames_stack - .push(core::mem::take(&mut self.current_varnames)); } fn enter_type_param_block( @@ -1273,20 +1299,13 @@ impl SymbolTableBuilder { /// Pop symbol table and add to sub table of parent table. fn leave_scope(&mut self) { - let mut table = self.tables.pop().unwrap(); - // Save the collected varnames to the symbol table - table.varnames = core::mem::take(&mut self.current_varnames); + let table = self.tables.pop().unwrap(); self.tables.last_mut().unwrap().sub_tables.push(table); - // Restore parent's varnames - self.current_varnames = self.varnames_stack.pop().unwrap_or_default(); } /// Pop symbol table without adding it to the parent children list. fn discard_scope(&mut self) -> SymbolTable { - let mut table = self.tables.pop().unwrap(); - table.varnames = core::mem::take(&mut self.current_varnames); - self.current_varnames = self.varnames_stack.pop().unwrap_or_default(); - table + self.tables.pop().unwrap() } fn resolve_future_annotation_names_as_globals(table: &mut SymbolTable) { @@ -1345,10 +1364,6 @@ impl SymbolTableBuilder { .take() .unwrap(); self.tables.push(*annotation_table); - // Save parent's varnames and seed with existing annotation varnames (e.g., "format") - self.varnames_stack - .push(core::mem::take(&mut self.current_varnames)); - self.current_varnames = self.tables.last().unwrap().varnames.clone(); if can_see_class_scope && (include_classdict_with_future || !self.future_annotations) { self.add_classdict_freevar(); @@ -1364,16 +1379,12 @@ impl SymbolTableBuilder { /// Stores the annotation block back to parent instead of sub_tables fn leave_annotation_scope(&mut self) { let mut table = self.tables.pop().unwrap(); - // Save the collected varnames to the symbol table - table.varnames = core::mem::take(&mut self.current_varnames); if self.future_annotations { Self::resolve_future_annotation_names_as_globals(&mut table); } // Store back to parent's annotation_block (not sub_tables) let parent = self.tables.last_mut().unwrap(); parent.annotation_block = Some(Box::new(table)); - // Restore parent's varnames - self.current_varnames = self.varnames_stack.pop().unwrap_or_default(); } fn add_classdict_freevar(&mut self) { @@ -1384,16 +1395,11 @@ impl SymbolTableBuilder { .entry(name.clone()) .or_insert_with(|| Symbol::new(name)); symbol.scope = SymbolScope::Free; - symbol - .flags - .insert(SymbolFlags::USE | SymbolFlags::DEF_FREE_CLASS); + symbol.flags.insert(SymbolFlags::USE); } fn add_format_parameter(&mut self) { self.tables.last_mut().unwrap().add_format_parameter(); - if !self.current_varnames.iter().any(|name| name == ".format") { - self.current_varnames.push(".format".into()); - } } /// Walk up the scope chain to determine if we're inside an async function. @@ -1448,19 +1454,22 @@ impl SymbolTableBuilder { } fn scan_parameter(&mut self, parameter: &ast::Parameter) -> SymbolTableResult { + // CPython reports the whole arg node, including any annotation. + // Ruff parameter ranges also include * or **, so start at the name. + let range = TextRange::new(parameter.name.start(), parameter.end()); // Check for duplicate parameter names let table = self.tables.last().unwrap(); if table.symbols.contains_key(parameter.name.as_str()) { return Err(self.error_ranged( format!( - "duplicate argument '{}' in function definition", + "duplicate parameter '{}' in function definition", parameter.name ), - parameter.name.range, + range, )); } - self.register_ident(¶meter.name, SymbolUsage::Parameter) + self.register_name(parameter.name.id(), SymbolUsage::Parameter, range) } /// Scan an annotation from an AnnAssign statement (can be conditional) @@ -1567,7 +1576,7 @@ impl SymbolTableBuilder { let needs_conditional_annotations = is_ann_assign && (matches!(current_scope, Some(CompilerScope::Module)) || (matches!(current_scope, Some(CompilerScope::Class)) - && self.in_conditional_block)); + && self.current_scan_region().contains(ScanRegion::CONDITIONAL))); let should_register_conditional_annotations = needs_conditional_annotations && !self.tables.last().unwrap().has_conditional_annotations; @@ -1630,6 +1639,63 @@ impl SymbolTableBuilder { Ok(()) } + fn validate_lazy_import(&self, statement: &ast::Stmt) -> SymbolTableResult { + let (kind, star) = match statement { + ast::Stmt::Import(node) if node.is_lazy => ("import", false), + ast::Stmt::ImportFrom(node) if node.is_lazy => ( + "from ... import", + node.names + .first() + .is_some_and(|name| name.name.as_str() == "*"), + ), + _ => return Ok(()), + }; + let scope = self.tables.last().unwrap(); + let reason = if self.current_scan_region().contains(ScanRegion::TRY) { + Some(format!("lazy {kind} not allowed inside try/except blocks")) + } else { + match scope.typ { + CompilerScope::Function | CompilerScope::AsyncFunction => { + Some(format!("lazy {kind} not allowed inside functions")) + } + CompilerScope::Class => Some(format!("lazy {kind} not allowed inside classes")), + _ if star => Some("lazy from ... import * is not allowed".to_owned()), + _ => None, + } + }; + if let Some(reason) = reason { + Err(self.error_ranged(reason, statement.range())) + } else { + Ok(()) + } + } + + fn current_scan_region(&self) -> ScanRegion { + let owner = self.tables.last().unwrap().block_index; + match self.active_scan_region { + Some(region) if region.owner == owner => region.flags, + _ => ScanRegion::empty(), + } + } + + /// CPython's conditional and try bits are local to an entry. Statement + /// visits nest in stack order, so only the latest region can belong to + /// the current entry; a newly entered scope sees no inherited flags. + fn with_scan_region( + &mut self, + flags: ScanRegion, + visit: impl FnOnce(&mut Self) -> SymbolTableResult, + ) -> SymbolTableResult { + let owner = self.tables.last().unwrap().block_index; + let flags = flags | self.current_scan_region(); + let previous = self + .active_scan_region + .replace(ActiveScanRegion { owner, flags }); + let result = visit(self); + self.active_scan_region = previous; + result + } + fn scan_statement(&mut self, statement: &ast::Stmt) -> SymbolTableResult { if self.recursion_depth >= self.recursion_limit { return Err(SymbolTableError { @@ -1641,6 +1707,7 @@ impl SymbolTableBuilder { self.recursion_depth += 1; let result = (|| { use ast::*; + self.validate_lazy_import(statement)?; self.track_future_statement(statement)?; match &statement { Stmt::Global(StmtGlobal { names, .. }) => { @@ -1768,9 +1835,6 @@ impl SymbolTableBuilder { CompilerScope::Class, self.line_index_start(def_range), ); - // Reset in_conditional_block for new class scope - let saved_in_conditional = self.in_conditional_block; - self.in_conditional_block = false; self.class_name = Some(name.id().clone()); if type_params.is_some() { self.register_name( @@ -1782,7 +1846,6 @@ impl SymbolTableBuilder { } self.scan_statements(body)?; self.leave_scope(); - self.in_conditional_block = saved_in_conditional; if type_params.is_some() { self.leave_scope(); } @@ -1799,17 +1862,16 @@ impl SymbolTableBuilder { .. }) => { self.scan_expression(test, ExpressionContext::Load)?; - // PEP 649: Track conditional block for annotations - let saved_in_conditional_block = self.in_conditional_block; - self.in_conditional_block = true; - self.scan_statements(body)?; - for elif in elif_else_clauses { - if let Some(test) = &elif.test { - self.scan_expression(test, ExpressionContext::Load)?; + self.with_scan_region(ScanRegion::CONDITIONAL, |builder| { + builder.scan_statements(body)?; + for elif in elif_else_clauses { + if let Some(test) = &elif.test { + builder.scan_expression(test, ExpressionContext::Load)?; + } + builder.scan_statements(&elif.body)?; } - self.scan_statements(&elif.body)?; - } - self.in_conditional_block = saved_in_conditional_block; + Ok(()) + })?; } Stmt::For(StmtFor { target, @@ -1830,23 +1892,19 @@ impl SymbolTableBuilder { } self.scan_expression(target, ExpressionContext::Store)?; self.scan_expression(iter, ExpressionContext::Load)?; - // PEP 649: Track conditional block for annotations - let saved_in_conditional_block = self.in_conditional_block; - self.in_conditional_block = true; - self.scan_statements(body)?; - self.scan_statements(orelse)?; - self.in_conditional_block = saved_in_conditional_block; + self.with_scan_region(ScanRegion::CONDITIONAL, |builder| { + builder.scan_statements(body)?; + builder.scan_statements(orelse) + })?; } Stmt::While(StmtWhile { test, body, orelse, .. }) => { self.scan_expression(test, ExpressionContext::Load)?; - // PEP 649: Track conditional block for annotations - let saved_in_conditional_block = self.in_conditional_block; - self.in_conditional_block = true; - self.scan_statements(body)?; - self.scan_statements(orelse)?; - self.in_conditional_block = saved_in_conditional_block; + self.with_scan_region(ScanRegion::CONDITIONAL, |builder| { + builder.scan_statements(body)?; + builder.scan_statements(orelse) + })?; } Stmt::Break(_) | Stmt::Continue(_) | Stmt::Pass(_) => { // No symbols here. @@ -1983,17 +2041,15 @@ impl SymbolTableBuilder { statement.range(), )); } - // PEP 649: Track conditional block for annotations - let saved_in_conditional_block = self.in_conditional_block; - self.in_conditional_block = true; - for item in items { - self.scan_expression(&item.context_expr, ExpressionContext::Load)?; - if let Some(expression) = &item.optional_vars { - self.scan_expression(expression, ExpressionContext::Store)?; + self.with_scan_region(ScanRegion::CONDITIONAL, |builder| { + for item in items { + builder.scan_expression(&item.context_expr, ExpressionContext::Load)?; + if let Some(expression) = &item.optional_vars { + builder.scan_expression(expression, ExpressionContext::Store)?; + } } - } - self.scan_statements(body)?; - self.in_conditional_block = saved_in_conditional_block; + builder.scan_statements(body) + })?; } Stmt::Try(StmtTry { body, @@ -2002,42 +2058,43 @@ impl SymbolTableBuilder { finalbody, .. }) => { - // PEP 649: Track conditional block for annotations - let saved_in_conditional_block = self.in_conditional_block; - self.in_conditional_block = true; - self.scan_statements(body)?; - for handler in handlers { - let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { - type_, - name, - body, - .. - }) = &handler; - if let Some(expression) = type_ { - self.scan_expression(expression, ExpressionContext::Load)?; - } - if let Some(name) = name { - self.register_name(name.id(), SymbolUsage::Assigned, handler.range())?; + self.with_scan_region(ScanRegion::CONDITIONAL | ScanRegion::TRY, |builder| { + builder.scan_statements(body)?; + for handler in handlers { + let ExceptHandler::ExceptHandler(ast::ExceptHandlerExceptHandler { + type_, + name, + body, + .. + }) = &handler; + if let Some(expression) = type_ { + builder.scan_expression(expression, ExpressionContext::Load)?; + } + if let Some(name) = name { + builder.register_name( + name.id(), + SymbolUsage::Assigned, + handler.range(), + )?; + } + builder.scan_statements(body)?; } - self.scan_statements(body)?; - } - self.scan_statements(orelse)?; - self.scan_statements(finalbody)?; - self.in_conditional_block = saved_in_conditional_block; + builder.scan_statements(orelse)?; + builder.scan_statements(finalbody) + })?; } Stmt::Match(StmtMatch { subject, cases, .. }) => { self.scan_expression(subject, ExpressionContext::Load)?; - // PEP 649: Track conditional block for annotations - let saved_in_conditional_block = self.in_conditional_block; - self.in_conditional_block = true; - for case in cases { - self.scan_pattern(&case.pattern)?; - if let Some(guard) = &case.guard { - self.scan_expression(guard, ExpressionContext::Load)?; + self.with_scan_region(ScanRegion::CONDITIONAL, |builder| { + for case in cases { + builder.scan_pattern(&case.pattern)?; + if let Some(guard) = &case.guard { + builder.scan_expression(guard, ExpressionContext::Load)?; + } + builder.scan_statements(&case.body)?; } - self.scan_statements(&case.body)?; - } - self.in_conditional_block = saved_in_conditional_block; + Ok(()) + })?; } Stmt::Raise(StmtRaise { exc, cause, .. }) => { if let Some(expression) = exc { @@ -2207,11 +2264,9 @@ impl SymbolTableBuilder { Expr::BoolOp(ExprBoolOp { values, .. }) => { self.scan_expressions(values, context)?; } - Expr::Compare(ExprCompare { - left, comparators, .. - }) => { - self.scan_expression(left, context)?; - self.scan_expressions(comparators, context)?; + Expr::Compare(compare) => { + self.scan_expression(compare.first_operand(), context)?; + self.scan_expressions(compare.comparators(), context)?; } Expr::Subscript(ExprSubscript { value, slice, .. }) => { self.scan_expression(value, ExpressionContext::Load)?; @@ -2386,16 +2441,14 @@ impl SymbolTableBuilder { self.in_iter_def_exp = true; } // Dict comprehension - is_generator = false (can be inlined) - let Some(key) = key.as_deref() else { - return Err(self.error_ranged( - "dict unpacking cannot be used in dict comprehension".to_owned(), - *range, - )); + let (element, value) = match key.as_deref() { + Some(key) => (key, Some(value.as_ref())), + None => (value.as_ref(), None), }; self.scan_comprehension( &"".into(), - key, - Some(value), + element, + value, generators, *range, false, @@ -2995,10 +3048,6 @@ impl SymbolTableBuilder { } } - fn register_ident(&mut self, ident: &ast::Identifier, role: SymbolUsage) -> SymbolTableResult { - self.register_name(ident.id(), role, ident.range) - } - fn check_name( &self, name: &Name, @@ -3171,7 +3220,7 @@ impl SymbolTableBuilder { if matches!(role, SymbolUsage::Parameter) && flags.contains(SymbolFlags::DEF_PARAM) { return Err(SymbolTableError { - error: format!("duplicate argument '{original_name}' in function definition"), + error: format!("duplicate parameter '{original_name}' in function definition"), location, end_location, }); @@ -3187,65 +3236,37 @@ impl SymbolTableBuilder { }); } match role { - SymbolUsage::Global if !symbol.is_global() => { - if flags.contains(SymbolFlags::DEF_PARAM) { - return Err(SymbolTableError { - error: format!("name '{name}' is parameter and global"), - location, - end_location, - }); - } - if flags.contains(SymbolFlags::USE) { - return Err(SymbolTableError { - error: format!("name '{name}' is used prior to global declaration"), - location, - end_location, - }); - } - if flags.contains(SymbolFlags::DEF_ANNOT) { - return Err(SymbolTableError { - error: format!("annotated name '{name}' can't be global"), - location, - end_location, - }); - } - if flags.contains(SymbolFlags::DEF_LOCAL) { - return Err(SymbolTableError { - error: format!( - "name '{name}' is assigned to before global declaration" - ), - location, - end_location, - }); - } - } - SymbolUsage::Nonlocal => { - if flags.contains(SymbolFlags::DEF_PARAM) { - return Err(SymbolTableError { - error: format!("name '{name}' is parameter and nonlocal"), - location, - end_location, - }); - } - if flags.contains(SymbolFlags::USE) { - return Err(SymbolTableError { - error: format!("name '{name}' is used prior to nonlocal declaration"), - location, - end_location, - }); - } - if flags.contains(SymbolFlags::DEF_ANNOT) { - return Err(SymbolTableError { - error: format!("annotated name '{name}' can't be nonlocal"), - location, - end_location, - }); - } - if flags.contains(SymbolFlags::DEF_LOCAL) { + SymbolUsage::Global | SymbolUsage::Nonlocal => { + // CPython checks the accumulated flags even on a repeated + // directive. Lookup uses the mangled name; diagnostics use + // the spelling from the current directive. + let directive = if matches!(role, SymbolUsage::Global) { + "global" + } else { + "nonlocal" + }; + let error = if flags.contains(SymbolFlags::DEF_PARAM) { + Some(format!( + "name '{original_name}' is parameter and {directive}" + )) + } else if flags.contains(SymbolFlags::USE) { + Some(format!( + "name '{original_name}' is used prior to {directive} declaration" + )) + } else if flags.contains(SymbolFlags::DEF_ANNOT) { + Some(format!( + "annotated name '{original_name}' can't be {directive}" + )) + } else if flags.contains(SymbolFlags::DEF_LOCAL) { + Some(format!( + "name '{original_name}' is assigned to before {directive} declaration" + )) + } else { + None + }; + if let Some(error) = error { return Err(SymbolTableError { - error: format!( - "name '{name}' is assigned to before nonlocal declaration" - ), + error, location, end_location, }); @@ -3315,8 +3336,8 @@ impl SymbolTableBuilder { flags.insert(SymbolFlags::DEF_PARAM); // Parameters are always added to varnames first let name_str = symbol.name.clone(); - if !self.current_varnames.contains(&name_str) { - self.current_varnames.push(name_str); + if !table.varnames.contains(&name_str) { + table.varnames.push(name_str); } } SymbolUsage::AnnotationAssigned => { @@ -3452,11 +3473,11 @@ mod tests { #[test] fn duplicate_parameter_check_uses_mangled_name_like_cpython() { let err = scan_source_result("class C:\n def f(__x, _C__x):\n pass\n") - .expect_err("expected duplicate argument after class-private mangling"); + .expect_err("expected duplicate parameter after class-private mangling"); assert_eq!( err.error, - "duplicate argument '_C__x' in function definition" + "duplicate parameter '_C__x' in function definition" ); } @@ -3498,6 +3519,47 @@ mod tests { ); } + #[test] + fn free_class_flag_distinguishes_forwarding_from_class_symbols() { + for (class_body, has_flag) in [ + ("", false), + (" x = 2\n", true), + (" item = x\n", true), + (" global x\n", true), + (" nonlocal x\n", true), + (" item = [lambda: x for _ in range(2)]\n", true), + ] { + let source = format!( + "def outer():\n x = 1\n class C:\n{class_body} def a(self): return x\n def b(self): return x\n" + ); + let top = scan_source(&source); + let outer = top.sub_tables.iter().find(|st| st.name == "outer").unwrap(); + let class = outer.sub_tables.iter().find(|st| st.name == "C").unwrap(); + let x = class.lookup(&"x".into()).unwrap(); + assert_eq!(x.flags.contains(SymbolFlags::DEF_FREE_CLASS), has_flag); + } + } + + #[test] + fn annotation_classdict_only_has_free_class_flag_when_needed_by_child() { + for (expression, has_flag) in [ + ("int", false), + ("(__classdict__, (lambda: __classdict__)())", true), + ] { + let source = format!("class C:\n item: {expression}\n"); + let top = scan_source(&source); + let class = top.sub_tables.iter().find(|st| st.name == "C").unwrap(); + let block = class.annotation_block.as_ref().unwrap(); + let classdict = block.lookup(&"__classdict__".into()).unwrap(); + assert_eq!(classdict.scope, super::SymbolScope::Free); + assert!(classdict.flags.contains(SymbolFlags::USE)); + assert_eq!( + classdict.flags.contains(SymbolFlags::DEF_FREE_CLASS), + has_flag + ); + } + } + #[test] fn inlined_comprehension_children_are_spliced_like_cpython() { let table = scan_source("result = [(lambda: i) for i in xs]\n"); @@ -3832,6 +3894,55 @@ def f(x=(lambda: 1)()): ); } + #[test] + fn repeated_global_rechecks_prior_uses_and_definitions() { + for (statement, reason) in [ + ("x", "is used prior to"), + ("x = 1", "is assigned to before"), + ("del x", "is assigned to before"), + ] { + let source = format!("def f():\n global x\n {statement}\n global x\n"); + let err = scan_source_result(&source).unwrap_err(); + assert_eq!(err.error, format!("name 'x' {reason} global declaration")); + let start = err.location.unwrap(); + let end = err.end_location.unwrap(); + assert_eq!((start.line.get(), start.character_offset.get()), (4, 5)); + assert_eq!((end.line.get(), end.character_offset.get()), (4, 13)); + } + // Repetition alone is legal. Imports do not carry any of the + // definition flags checked by a scope directive. + assert!(scan_source_result("global x\nglobal x\n").is_ok()); + assert!(scan_source_result("def f():\n global x\n import x\n global x\n").is_ok()); + } + + #[test] + fn private_scope_directive_conflicts_use_source_spelling() { + for (directive, statement, message) in [ + ( + "global", + "__x = 1", + "name '__x' is assigned to before global declaration", + ), + ( + "nonlocal", + "__x", + "name '__x' is used prior to nonlocal declaration", + ), + ( + "nonlocal", + "__x: int", + "annotated name '__x' can't be nonlocal", + ), + ] { + let source = + format!("class C:\n def f():\n {statement}\n {directive} __x\n"); + let err = scan_source_result(&source).unwrap_err(); + assert_eq!(err.error, message); + let start = err.location.unwrap(); + assert_eq!((start.line.get(), start.character_offset.get()), (4, 9)); + } + } + #[test] fn type_param_debug_name_is_checked_like_cpython_add_def_ctx() { let source = "class C[__debug__]:\n pass\n"; diff --git a/crates/codegen/src/unparse.rs b/crates/codegen/src/unparse.rs index 86744a6010b..06e8f27a604 100644 --- a/crates/codegen/src/unparse.rs +++ b/crates/codegen/src/unparse.rs @@ -1,8 +1,8 @@ -use crate::strip_python_comments; +use crate::{interpolation_debug_text, interpolation_expression_text}; use alloc::fmt; use core::fmt::Display as _; use ruff_python_ast as ast; -use ruff_text_size::{Ranged, TextSize, TextSlice}; +use ruff_text_size::Ranged; use rustpython_compiler_core::SourceFile; use rustpython_literal::escape::{AsciiEscape, UnicodeEscape}; @@ -380,18 +380,11 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { UnparseExpr::new(value, self.source) )?; } - ast::Expr::Compare(ast::ExprCompare { - left, - ops, - comparators, - node_index: _, - range: _range, - .. - }) => { + ast::Expr::Compare(compare) => { group_if!(precedence::CMP, { let new_lvl = precedence::CMP + 1; - self.unparse_expr(left, new_lvl)?; - for (op, cmp) in ops.iter().zip(comparators) { + self.unparse_expr(compare.first_operand(), new_lvl)?; + for (_, op, cmp) in compare.iter() { self.p(" ")?; self.p(op.as_str())?; self.p(" ")?; @@ -622,11 +615,8 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { fmt::from_fn(|f| Unparser::new(f, self.source).unparse_expr(val, precedence::TEST + 1)) .to_string(); if let Some(debug_text) = debug_text { - let leading = debug_text.leading(); - let trailing = debug_text.trailing(); - self.p(leading)?; - self.p(self.source.source_text().slice(val.range()))?; - self.p(trailing)?; + let (text, _) = interpolation_debug_text(self.source, debug_text, val.range()); + self.unparse_fstring_str(&text)?; if conversion == ast::ConversionFlag::None && spec.is_none() { conversion = ast::ConversionFlag::Repr; } @@ -635,19 +625,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { // put a space to avoid escaping the bracket "{ " } else { - // Preserve leading whitespace between '{' and the expression - let source_text = self.source.source_text(); - let start = val.range().start().to_usize(); - if start > 0 - && source_text - .as_bytes() - .get(start - 1) - .is_some_and(|b| b.is_ascii_whitespace()) - { - "{ " - } else { - "{" - } + "{" }; self.p(brace)?; self.p(&buffered)?; @@ -700,8 +678,8 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { self.p("f")?; let body = fmt::from_fn(|f| { value.iter().try_for_each(|part| match part { - ast::FStringPart::Literal(lit) => f.write_str(lit), - ast::FStringPart::FString(ast::FString { elements, .. }) => { + ast::FStringPartRef::Literal(lit) => f.write_str(lit), + ast::FStringPartRef::FString(ast::FString { elements, .. }) => { Unparser::new(f, self.source).unparse_fstring_body(elements) } }) @@ -744,23 +722,11 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { &mut self, interpolation: &ast::InterpolatedElement, ) -> fmt::Result { - let source_conversion = interpolation.conversion; - let mut conversion = source_conversion; - let debug_parts = interpolation.debug_text.as_ref().map(|debug_text| { - ( - strip_python_comments(debug_text.leading()), - strip_python_comments( - self.source - .source_text() - .slice(interpolation.expression.range()), - ), - strip_python_comments(debug_text.trailing()), - ) - }); - if let Some((leading, source, trailing)) = &debug_parts { - self.p(leading)?; - self.p(source)?; - self.p(trailing)?; + let mut conversion = interpolation.conversion; + if let Some(debug_text) = &interpolation.debug_text { + let (text, _) = + interpolation_debug_text(self.source, debug_text, interpolation.expression.range()); + self.unparse_fstring_str(&text)?; if conversion == ast::ConversionFlag::None && interpolation.format_spec.is_none() { conversion = ast::ConversionFlag::Repr; } @@ -768,42 +734,14 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { let expression = if let Some(ast::ConstantValue::Str(value)) = &interpolation.runtime_str { value.to_string() - } else if let Some((leading, source, trailing)) = &debug_parts { - let mut expression = leading.clone(); - expression.push_str(source); - let equal = trailing - .rfind('=') - .expect("debug interpolation must contain '='"); - expression.push_str(&trailing[..equal]); - expression.trim_end().to_owned() + } else if let Some(expression) = interpolation_expression_text(self.source, interpolation) { + expression } else { - let expression_range = interpolation.expression.range(); - let after_brace = interpolation.range.start() + TextSize::new(1); - let mut expression_end = interpolation.format_spec.as_ref().map_or_else( - || interpolation.range.end() - TextSize::new(1), - |format_spec| format_spec.range.start() - TextSize::new(1), - ); - if source_conversion != ast::ConversionFlag::None { - expression_end -= TextSize::new(2); - } - if interpolation.range.start() < expression_range.start() - && interpolation.range.end() >= expression_range.end() - && after_brace <= expression_end - { - strip_python_comments( - self.source - .source_text() - .slice(ruff_text_size::TextRange::new(after_brace, expression_end)), - ) - .trim_end() - .to_owned() - } else { - fmt::from_fn(|f| { - Unparser::new(f, self.source) - .unparse_expr(&interpolation.expression, precedence::TEST + 1) - }) - .to_string() - } + fmt::from_fn(|f| { + Unparser::new(f, self.source) + .unparse_expr(&interpolation.expression, precedence::TEST + 1) + }) + .to_string() }; self.p(if expression.starts_with('{') { @@ -821,7 +759,7 @@ impl<'a, 'b, 'c> Unparser<'a, 'b, 'c> { if let Some(format_spec) = &interpolation.format_spec { self.p(":")?; - self.unparse_tstring_body(&format_spec.elements)?; + self.unparse_fstring_body(&format_spec.elements)?; } self.p("}") diff --git a/crates/common/Cargo.toml b/crates/common/Cargo.toml index 25247e4d010..ea31322575e 100644 --- a/crates/common/Cargo.toml +++ b/crates/common/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true [features] default = ["std"] -binascii = ["dep:base64", "dep:crc32fast"] +binascii = ["dep:crc32fast"] bz2 = ["std", "dep:bzip2"] cjk-codecs = [] inet = ["std"] @@ -39,7 +39,6 @@ rustpython-unicode = { workspace = true } rustpython-wtf8 = { workspace = true } ascii = { workspace = true } -base64 = { workspace = true, optional = true } bitflags = { workspace = true } blake2b_simd = { workspace = true, optional = true } blake2s_simd = { workspace = true, optional = true } diff --git a/crates/common/src/binascii.rs b/crates/common/src/binascii.rs index 2a262d3a28b..4a389025d40 100644 --- a/crates/common/src/binascii.rs +++ b/crates/common/src/binascii.rs @@ -7,7 +7,6 @@ //! the caller's responsibility (see `mod.rs`). use alloc::{vec, vec::Vec}; -use base64::Engine; /// The base64 pad character `=`. pub const PAD: u8 = 61u8; @@ -31,13 +30,17 @@ pub enum Error { TooLong, /// `a2b_base64`: base64 decoding failed. Base64(Base64DecodeError), + /// The base64 output would exceed the maximum Python bytes length. + TooMuchBase64Data, + /// Reserving the transform output failed. + Memory, } /// Mirrors CPython's `binascii_a2b_base64_impl` (`Modules/binascii.c`) error /// paths one-for-one, so the caller can build the exact Python error message. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Base64DecodeError { - /// A `=` at `quad_pos == 0, i == 0`, strict mode. + /// Padding before any decoded output, in strict mode. LeadingPaddingNotAllowed, /// A `=` outside the padding-completion window, strict mode. ExcessPaddingNotAllowed, @@ -51,6 +54,10 @@ pub enum Base64DecodeError { InvalidLastSymbol { index: usize }, /// `quad_pos != 0` and the trailing padding does not complete the quad. IncorrectPadding, + /// Padding is forbidden when decoding unpadded input in strict mode. + PaddingNotAllowed, + /// The final symbol contains non-zero unused bits. + NonZeroPaddingBits, } const fn hex_nibble(n: u8) -> u8 { @@ -70,8 +77,8 @@ const fn unhex_nibble(c: u8) -> Option { } } -/// `b2a_hex` / `hexlify`. `sep` is the (already validated, length-1 ASCII) -/// separator byte, or `None` for no separator. +/// `b2a_hex` / `hexlify`. `sep` is the already validated separator byte, +/// or `None` for no separator. #[must_use] pub fn hexlify(bytes: &[u8], sep: Option, bytes_per_sep: isize) -> Vec { // If no separator or bytes_per_sep is 0, use simple hexlify @@ -230,45 +237,53 @@ pub fn crc_hqx(bytes: &[u8], init: u32) -> u32 { crc } -/// `a2b_base64`. A line-by-line port of `binascii_a2b_base64_impl` -/// (CPython `Modules/binascii.c`): padding characters within the completion -/// window (`quad_pos >= 2 && quad_pos + pads <= 4`) are always skipped — -/// even in strict mode — and non-strict mode additionally skips *every* -/// pad and every non-alphabet byte outside that window. Errors therefore -/// only fire in strict mode (mid-loop) or from the two post-loop length -/// checks, which apply unconditionally. -pub fn a2b_base64(b: &[u8], strict_mode: bool) -> Result, Error> { - // Converts between ASCII and base-64 characters. The index of a given number yields the - // number in ASCII while the value of said index yields the number in base-64. For example - // "=" is 61 in ASCII but 0 (since it's the pad character) in base-64, so BASE64_TABLE[61] == 0 - #[rustfmt::skip] - const BASE64_TABLE: [i8; 256] = [ - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63, - 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */ - -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14, - 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1, - -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40, - 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1, - - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, - ]; +/// RFC 4648's standard base64 alphabet. +pub const BASE64_ALPHABET: &[u8; 64] = + b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +/// Build the decoder table, with later duplicate symbols taking precedence. +#[must_use] +pub const fn base64_reverse_table(alphabet: &[u8; 64]) -> [u8; 256] { + let mut table = [u8::MAX; 256]; + let mut index = 0; + while index < 64 { + table[alphabet[index] as usize] = index as u8; + index += 1; + } + // Padding always takes precedence, even in a custom alphabet. + table[PAD as usize] = 64; + table +} - let mut decoded: Vec = Vec::with_capacity(b.len().div_ceil(4) * 3); +/// Options for CPython 3.15's base64 decoder. +pub struct Base64DecodeOptions<'a> { + pub strict_mode: bool, + pub padded: bool, + pub table: &'a [u8; 256], + pub ignored: &'a [bool; 256], + pub canonical: bool, +} - let mut quad_pos: u32 = 0; // position in the quad, 0..=3 - let mut pads: u32 = 0; +/// `a2b_base64`, following CPython 3.15's `Modules/binascii.c`. +pub fn a2b_base64(b: &[u8], options: Base64DecodeOptions<'_>) -> Result, Error> { + let Base64DecodeOptions { + strict_mode, + padded, + table, + ignored, + canonical, + } = options; + + let mut decoded: Vec = Vec::new(); + decoded + .try_reserve_exact(b.len().div_ceil(4) * 3) + .map_err(|_| Error::Memory)?; + + let mut quad_pos: usize = 0; // position in the quad, 0..=3 + let mut pads: usize = 0; let mut left_char: u8 = 0; - for (i, &el) in b.iter().enumerate() { - if el == PAD { + for &el in b { + if padded && el == PAD { pads += 1; if quad_pos >= 2 && quad_pos + pads <= 4 { continue; @@ -276,7 +291,7 @@ pub fn a2b_base64(b: &[u8], strict_mode: bool) -> Result, Error> { // RFC 4648 section-3.3: implementations MAY ignore a pad // character present before the end of the encoded data, and // MAY ignore excess pad characters. Non-strict mode does. - if !strict_mode { + if !strict_mode || ignored[PAD as usize] { continue; } if quad_pos == 1 { @@ -284,22 +299,26 @@ pub fn a2b_base64(b: &[u8], strict_mode: bool) -> Result, Error> { // `quad_pos == 1` check below. break; } - return Err(Error::Base64(if quad_pos == 0 && i == 0 { + return Err(Error::Base64(if quad_pos == 0 && decoded.is_empty() { Base64DecodeError::LeadingPaddingNotAllowed } else { Base64DecodeError::ExcessPaddingNotAllowed })); } - let binary_char = BASE64_TABLE[el as usize]; - if binary_char < 0 { - if strict_mode { - return Err(Error::Base64(Base64DecodeError::OnlyBase64DataAllowed)); + let binary_char = table[el as usize]; + if binary_char >= 64 { + if strict_mode && !ignored[el as usize] { + return Err(Error::Base64(if el == PAD { + Base64DecodeError::PaddingNotAllowed + } else { + Base64DecodeError::OnlyBase64DataAllowed + })); } continue; } - if pads > 0 && strict_mode { + if pads > 0 && strict_mode && !ignored[PAD as usize] { return Err(Error::Base64(if quad_pos + pads == 4 { Base64DecodeError::ExcessDataAfterPadding } else { @@ -312,21 +331,21 @@ pub fn a2b_base64(b: &[u8], strict_mode: bool) -> Result, Error> { match quad_pos { 0 => { quad_pos = 1; - left_char = binary_char as u8; + left_char = binary_char; } 1 => { quad_pos = 2; - decoded.push((left_char << 2) | (binary_char >> 4) as u8); - left_char = (binary_char & 0x0f) as u8; + decoded.push((left_char << 2) | (binary_char >> 4)); + left_char = binary_char & 0x0f; } 2 => { quad_pos = 3; - decoded.push((left_char << 4) | (binary_char >> 2) as u8); - left_char = (binary_char & 0x03) as u8; + decoded.push((left_char << 4) | (binary_char >> 2)); + left_char = binary_char & 0x03; } 3 => { quad_pos = 0; - decoded.push((left_char << 6) | binary_char as u8); + decoded.push((left_char << 6) | binary_char); left_char = 0; } _ => unsafe { @@ -344,24 +363,72 @@ pub fn a2b_base64(b: &[u8], strict_mode: bool) -> Result, Error> { })); } - if quad_pos != 0 && quad_pos + pads < 4 { + if padded && quad_pos != 0 && quad_pos + pads < 4 { return Err(Error::Base64(Base64DecodeError::IncorrectPadding)); } + if canonical && left_char != 0 { + return Err(Error::Base64(Base64DecodeError::NonZeroPaddingBits)); + } Ok(decoded) } -/// `b2a_base64`. -#[must_use] -pub fn b2a_base64(data: &[u8], newline: bool) -> Vec { - // https://stackoverflow.com/questions/63916821 - let mut encoded = base64::engine::general_purpose::STANDARD - .encode(data) - .into_bytes(); +/// `b2a_base64`, including CPython 3.15's wrapping and custom alphabets. +pub fn b2a_base64( + data: &[u8], + padded: bool, + wrapcol: usize, + newline: bool, + alphabet: &[u8; 64], +) -> Result, Error> { + let pads = (3 - data.len() % 3) % 3; + let mut size = data + .len() + .div_ceil(3) + .checked_mul(4) + .ok_or(Error::TooMuchBase64Data)?; + if !padded { + size -= pads; + } + let width = if wrapcol == 0 { + usize::MAX + } else { + wrapcol.max(4) / 4 * 4 + }; + let newlines = size.saturating_sub(1) / width; + size = size + .checked_add(newlines) + .and_then(|n| n.checked_add(usize::from(newline))) + .filter(|&n| isize::try_from(n).is_ok()) + .ok_or(Error::TooMuchBase64Data)?; + let mut encoded = Vec::new(); + encoded.try_reserve_exact(size).map_err(|_| Error::Memory)?; + let mut column = 0; + let mut emit = |symbol| { + if column == width { + encoded.push(b'\n'); + column = 0; + } + encoded.push(symbol); + column += 1; + }; + for chunk in data.chunks(3) { + let value = (u32::from(chunk[0]) << 16) + | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) + | u32::from(*chunk.get(2).unwrap_or(&0)); + for index in 0..=chunk.len() { + emit(alphabet[((value >> (18 - index * 6)) & 63) as usize]); + } + if padded { + for _ in chunk.len() + 1..4 { + emit(PAD); + } + } + } if newline { encoded.push(b'\n'); } - encoded + Ok(encoded) } #[inline] @@ -604,15 +671,14 @@ pub fn b2a_qp(buf: &[u8], quotetabs: bool, istext: bool, header: bool) -> Vec b'_', + b => b, + }; + out_data.push(ch); + out_idx += 1; + in_idx += 1; } } out_data diff --git a/crates/common/src/borrow.rs b/crates/common/src/borrow.rs index ebf69fde71d..0f9903b6d22 100644 --- a/crates/common/src/borrow.rs +++ b/crates/common/src/borrow.rs @@ -39,10 +39,9 @@ impl_from!('a, T, BorrowedValue<'a, T>, impl<'a, T: ?Sized> BorrowedValue<'a, T> { /// Whether reaching the value holds a lock that other threads wait on. /// - /// An immutable object hands out a plain reference and answers `false`; - /// one whose storage can change hands out a guard. A caller about to wait - /// for something unrelated -- a peer, a file, a signal -- can use this to - /// decide whether it may keep the borrow for the duration. + /// A plain reference answers `false`, including references to externally + /// managed memory. This does not guarantee that the storage is immutable + /// or safe to borrow while another thread runs. #[must_use] pub const fn is_locked(&self) -> bool { !matches!(self, Self::Ref(_)) diff --git a/crates/common/src/cformat.rs b/crates/common/src/cformat.rs index de437f2ce0d..263b4776a69 100644 --- a/crates/common/src/cformat.rs +++ b/crates/common/src/cformat.rs @@ -19,7 +19,7 @@ pub enum CFormatErrorType { UnmatchedKeyParentheses, MissingModuloSign, UnsupportedFormatChar(CodePoint), - IncompleteFormat, + StrayModulo, WidthTooBig, PrecisionTooBig, // Unimplemented, @@ -38,7 +38,7 @@ impl fmt::Display for CFormatError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.typ { CFormatErrorType::UnmatchedKeyParentheses => write!(f, "incomplete format key"), - CFormatErrorType::IncompleteFormat => write!(f, "incomplete format"), + CFormatErrorType::StrayModulo => write!(f, "stray % at position {}", self.index), CFormatErrorType::UnsupportedFormatChar(c) => write!( f, "unsupported format character '{}' ({:#x}) at index {}", @@ -590,7 +590,7 @@ impl CFormatSpec { } } -fn parse_spec_mapping_key(iter: &mut ParseIter) -> Result, ParsingError> +pub fn parse_spec_mapping_key(iter: &mut ParseIter) -> Result, ParsingError> where T: FormatBuf, I: Iterator, @@ -604,7 +604,7 @@ where Ok(None) } -fn parse_flags(iter: &mut ParseIter) -> CConversionFlags +pub fn parse_flags(iter: &mut ParseIter) -> CConversionFlags where C: FormatChar, I: Iterator, @@ -626,7 +626,7 @@ where flags } -fn consume_length(iter: &mut ParseIter) +pub fn consume_length(iter: &mut ParseIter) where C: FormatChar, I: Iterator, @@ -634,7 +634,7 @@ where iter.next_if(|(_, c)| matches!(c.to_char_lossy(), 'h' | 'l' | 'L')); } -fn parse_format_type( +pub fn parse_format_type( iter: &mut ParseIter, context: CFormatContext, ) -> Result @@ -644,7 +644,7 @@ where { let (index, c) = iter.next().ok_or_else(|| { ( - CFormatErrorType::IncompleteFormat, + CFormatErrorType::StrayModulo, iter.peek().map_or(0, |x| x.0), ) })?; @@ -674,7 +674,7 @@ where }) } -fn parse_quantity( +pub fn parse_quantity( iter: &mut ParseIter, max_value: usize, too_big: CFormatErrorType, @@ -709,7 +709,9 @@ where Ok(None) } -fn parse_precision(iter: &mut ParseIter) -> Result, ParsingError> +pub fn parse_precision( + iter: &mut ParseIter, +) -> Result, ParsingError> where C: FormatChar, I: Iterator, @@ -831,9 +833,14 @@ impl CFormatStrOrBytes { } let spec = - CFormatSpecKeyed::parse(iter, context).map_err(|err| CFormatError { - typ: err.0, - index: err.1, + CFormatSpecKeyed::parse(iter, context).map_err(|(typ, err_index)| { + // A stray % is reported at the position of the %. + let index = if typ == CFormatErrorType::StrayModulo { + index + } else { + err_index + }; + CFormatError { typ, index } })?; parts.push((index, CFormatPart::Spec(spec))); @@ -842,8 +849,8 @@ impl CFormatStrOrBytes { } } else { return Err(CFormatError { - typ: CFormatErrorType::IncompleteFormat, - index: index + 1, + typ: CFormatErrorType::StrayModulo, + index, }); } } else { @@ -991,8 +998,8 @@ mod tests { assert_eq!( "Hello %".parse::(), Err(CFormatError { - typ: CFormatErrorType::IncompleteFormat, - index: 7 + typ: CFormatErrorType::StrayModulo, + index: 6 }) ); } diff --git a/crates/common/src/compression/lzma.rs b/crates/common/src/compression/lzma.rs index 2e2b44fd984..7838b6bcd5e 100644 --- a/crates/common/src/compression/lzma.rs +++ b/crates/common/src/compression/lzma.rs @@ -14,7 +14,6 @@ use super::{CHUNKSIZE, Chunker}; pub const BUFSIZ: usize = 8192; const DEF_BUF_SIZE: usize = 16 * 1024; -const USE_AFTER_FINISH_ERR: &str = "Error -2: inconsistent stream state"; const LZMA_FILTERS_MAX: usize = 4; pub const CHECK_NONE: i32 = xz_sys::LZMA_CHECK_NONE as _; @@ -267,9 +266,7 @@ pub fn encode_filter_properties(spec: &FilterSpec) -> Result, Error> { FILTER_DELTA => { let dist = spec.dist.unwrap_or(1); if !(1..=256).contains(&dist) { - return Err(Error::Value( - "Invalid filter specifier for delta filter".to_owned(), - )); + return Err(Error::Lzma("Internal error".to_owned())); } Ok(vec![(dist - 1) as u8]) } @@ -350,14 +347,17 @@ impl LzmaStream { } } - fn process(&mut self, input: &[u8], output: &mut Vec) -> Result { + fn process(&mut self, input: &[u8], output: &mut [u8]) -> Result { + let previous_in = self.stream.total_in(); + let result = self.stream.process(input, output, Action::Run); + let consumed = (self.stream.total_in() - previous_in) as usize; if self.track_header && self.header_collected < 8 { - let count = (8 - usize::from(self.header_collected)).min(input.len()); + let count = (8 - usize::from(self.header_collected)).min(consumed); let start = usize::from(self.header_collected); self.header_buf[start..start + count].copy_from_slice(&input[..count]); self.header_collected += count as u8; } - match self.stream.process_vec(input, output, Action::Run) { + match result { Ok(Status::GetCheck) => { if self.header_collected >= 8 { self.check = i32::from(self.header_buf[7] & 0x0f); @@ -377,35 +377,39 @@ fn decompress_chunks( chunks: &mut Chunker<'_>, stream: &mut LzmaStream, max_length: Option, -) -> Result<(Vec, bool), XzError> { - // No input to feed the decoder: not a stream end, so `eof` stays false and - // the caller can still supply compressed data later. - if chunks.is_empty() { - return Ok((Vec::new(), false)); - } +) -> Result<(Vec, bool, bool), Error> { let max_length = max_length.unwrap_or(usize::MAX); let mut output = Vec::new(); - 'outer: loop { + let mut block = vec![0; BUFSIZ.min(max_length)]; + loop { let chunk = chunks.chunk(); - loop { - let additional = BUFSIZ.min(max_length - output.capacity()); - if additional == 0 { - return Ok((output, false)); - } - output.reserve_exact(additional); - let previous_in = stream.stream.total_in(); - let result = stream.process(chunk, &mut output); - let consumed = (stream.stream.total_in() - previous_in) as usize; - chunks.advance(consumed); - let status = result?; - if status == Status::StreamEnd || chunks.is_empty() { - output.shrink_to_fit(); - return Ok((output, status == Status::StreamEnd)); - } - if !chunk.is_empty() && consumed == 0 { - continue; + let available = block.len().min(max_length - output.len()); + let previous_in = stream.stream.total_in(); + let previous_out = stream.stream.total_out(); + let result = stream.process(chunk, &mut block[..available]); + let consumed = (stream.stream.total_in() - previous_in) as usize; + let produced = (stream.stream.total_out() - previous_out) as usize; + chunks.advance(consumed); + let status = result?; + output.extend_from_slice(&block[..produced]); + let filled = produced == available; + + // liblzma reports BUF_ERROR after consecutive calls without progress. + // Exhausted input with output space is just a request for more input. + if status == Status::MemNeeded && !(consumed == chunk.len() && !filled) { + return Err(Error::Lzma("Insufficient buffer space".to_owned())); + } + if status == Status::StreamEnd { + return Ok((output, true, false)); + } + // Check output before input: liblzma may have buffered output even + // after consuming the last supplied input byte. + if filled { + if output.len() == max_length { + return Ok((output, false, true)); } - continue 'outer; + } else if chunks.is_empty() { + return Ok((output, false, false)); } } } @@ -477,9 +481,9 @@ impl Decompressor { let mut chunks = Chunker::chain(input_buffer, data); let previous_len = chunks.len(); let result = decompress_chunks(&mut chunks, stream, max_length); - let stream_end = match &result { - Ok((_, stream_end)) => *stream_end, - Err(_) => false, + let (stream_end, capped) = match &result { + Ok((_, stream_end, capped)) => (*stream_end, *capped), + Err(_) => (false, false), }; let consumed = previous_len - chunks.len(); self.eof |= stream_end; @@ -490,7 +494,7 @@ impl Decompressor { } } else if chunks.is_empty() { input_buffer.clear(); - self.needs_input = true; + self.needs_input = !capped; } else { self.needs_input = false; if let Some(consumed_from_data) = consumed.checked_sub(input_buffer.len()) { @@ -501,7 +505,7 @@ impl Decompressor { input_buffer.extend_from_slice(data); } } - result.map(|(output, _)| output).map_err(Error::from) + result.map(|(output, _, _)| output) } #[must_use] @@ -540,8 +544,14 @@ impl Compressor { } let stream = match format { FORMAT_XZ => { - let check = int_to_check(check) - .ok_or_else(|| Error::Value("Invalid check value".to_owned()))?; + let check = int_to_check(check).ok_or_else(|| { + let message = if (0..=CHECK_ID_MAX).contains(&check) { + "Unsupported integrity check" + } else { + "Internal error" + }; + Error::Lzma(message.to_owned()) + })?; if let Some(specs) = filters { Stream::new_stream_encoder(&build_filters(&specs)?, check)? } else { @@ -582,7 +592,7 @@ impl Compressor { let stream = self .stream .as_mut() - .ok_or_else(|| Error::Lzma(USE_AFTER_FINISH_ERR.to_owned()))?; + .ok_or_else(|| Error::Value("Compressor has been flushed".to_owned()))?; let mut output = Vec::new(); for mut chunk in data.chunks(CHUNKSIZE) { while !chunk.is_empty() { @@ -601,7 +611,7 @@ impl Compressor { let stream = self .stream .as_mut() - .ok_or_else(|| Error::Lzma(USE_AFTER_FINISH_ERR.to_owned()))?; + .ok_or_else(|| Error::Value("Repeated call to flush()".to_owned()))?; let mut output = Vec::new(); let status = loop { if output.len() == output.capacity() { diff --git a/crates/common/src/compression/zlib.rs b/crates/common/src/compression/zlib.rs index 6c34d7cbe55..b2528cbfc9c 100644 --- a/crates/common/src/compression/zlib.rs +++ b/crates/common/src/compression/zlib.rs @@ -28,6 +28,34 @@ pub const MAX_WBITS: i32 = 15; pub const DEF_BUF_SIZE: usize = 16 * 1024; pub const DEF_MEM_LEVEL: u8 = 8; +// CPython uses a large-file off_t except on Windows (always 32-bit) and +// GNU/Hurd, where its configure script disables large-file support. +#[cfg(windows)] +pub type ChecksumLength = i32; +#[cfg(not(any(windows, target_os = "hurd")))] +pub type ChecksumLength = i64; +#[cfg(target_os = "hurd")] +pub type ChecksumLength = libc::off_t; + +#[must_use] +pub fn adler32_combine(adler1: u32, adler2: u32, len2: ChecksumLength) -> u32 { + z_checksum_to_u32(libz_rs_sys::adler32_combine64( + z_checksum_from_u32(adler1), + z_checksum_from_u32(adler2), + z_checksum_length(len2), + )) +} + +// As in zlib, CRC combination requires a nonnegative length. +#[must_use] +pub fn crc32_combine(crc1: u32, crc2: u32, len2: ChecksumLength) -> u32 { + z_checksum_to_u32(libz_rs_sys::crc32_combine64( + z_checksum_from_u32(crc1), + z_checksum_from_u32(crc2), + z_checksum_length(len2), + )) +} + const USE_AFTER_FINISH_ERR: &str = "Error -2: inconsistent stream state"; fn valid_level(level: i32) -> bool { @@ -58,6 +86,34 @@ const fn z_size_to_u64(value: core::ffi::c_ulong) -> u64 { } } +const fn z_checksum_length(value: ChecksumLength) -> libz_rs_sys::z_off64_t { + #[cfg(any( + all(windows, not(target_env = "gnu")), + all(target_os = "hurd", target_pointer_width = "32") + ))] + { + value as i64 + } + #[cfg(not(any( + all(windows, not(target_env = "gnu")), + all(target_os = "hurd", target_pointer_width = "32") + )))] + { + value + } +} + +const fn z_checksum_from_u32(value: u32) -> core::ffi::c_ulong { + #[cfg(all(target_pointer_width = "64", not(windows)))] + { + value as u64 + } + #[cfg(any(target_pointer_width = "32", windows))] + { + value + } +} + const fn z_checksum_to_u32(value: core::ffi::c_ulong) -> u32 { #[cfg(all(target_pointer_width = "64", not(windows)))] { @@ -350,9 +406,6 @@ fn decompress_chunks( max_length: Option, calc_flush: impl Fn(bool) -> InflateFlush, ) -> Result<(Vec, bool), String> { - if data.is_empty() { - return Ok((Vec::new(), false)); - } let max_length = max_length.unwrap_or(usize::MAX); let mut buf = Vec::new(); @@ -378,7 +431,9 @@ fn decompress_chunks( match res { Ok(status) => { let stream_end = status == Status::StreamEnd; - if stream_end || data.is_empty() { + // A full output buffer can leave output pending in inflate, + // even with no input left: only a partial buffer ends it. + if stream_end || (data.is_empty() && produced < additional) { buf.shrink_to_fit(); return Ok((buf, stream_end)); } else if !chunk.is_empty() && consumed == 0 { @@ -698,6 +753,9 @@ impl Decompressor { /// `Decompress.flush(length)`. pub fn flush(&mut self, length: usize) -> Result, String> { + if self.eof && self.decompress.is_none() { + return Ok(Vec::new()); + } let data = core::mem::take(&mut self.unconsumed_tail); let (ret, stream_end) = self.decompress_inner(&data, length, None, true)?; self.eof |= stream_end; @@ -1022,4 +1080,56 @@ mod tests { assert_eq!(d.unconsumed_tail(), b""); assert_eq!(d.unused_data(), b"NEXT"); } + + /// Decode raw deflate of `b"x" * 1168` in 100-byte steps until all + /// input is consumed. Inflate then still holds the last 68 bytes. + fn drained_raw_deflate() -> (Decompressor, Vec) { + let mut co = Compressor::new(6, 8, -MAX_WBITS, 8, 0, None).unwrap(); + let mut raw = co.compress(&[b'x'; 1168]).unwrap(); + raw.extend(co.flush(Z_FINISH).unwrap()); + let mut d = Decompressor::new(-MAX_WBITS, None).unwrap(); + let mut out = d.decompress(&raw, Some(100)).unwrap(); + while !d.unconsumed_tail().is_empty() { + let tail = d.unconsumed_tail().to_vec(); + out.extend(d.decompress(&tail, Some(100)).unwrap()); + } + assert_eq!(out.len(), 1100); + assert!(!d.eof()); + (d, out) + } + + #[test] + fn empty_input_returns_pending_output() { + let (mut d, mut out) = drained_raw_deflate(); + out.extend(d.decompress(b"", Some(100)).unwrap()); + assert_eq!(out, [b'x'; 1168]); + assert!(d.eof()); + } + + #[test] + fn flush_returns_pending_output() { + let (mut d, mut out) = drained_raw_deflate(); + out.extend(d.flush(DEF_BUF_SIZE).unwrap()); + assert_eq!(out, [b'x'; 1168]); + assert!(d.eof()); + } + + #[test] + fn small_bufsize_returns_pending_output() { + let data = [b'x'; 1168]; + let raw = compress(&data, 6, -MAX_WBITS).unwrap(); + for bufsize in [1, 100] { + assert_eq!(decompress(&raw, -MAX_WBITS, bufsize).unwrap(), data); + } + } + + #[test] + fn empty_flush_does_not_finish_a_stream() { + let encoded = compress(b"later input", -1, MAX_WBITS).unwrap(); + let mut d = Decompressor::new(MAX_WBITS, None).unwrap(); + assert_eq!(d.flush(DEF_BUF_SIZE).unwrap(), b""); + assert!(!d.eof()); + assert_eq!(d.decompress(&encoded, None).unwrap(), b"later input"); + assert!(d.eof()); + } } diff --git a/crates/common/src/encodings.rs b/crates/common/src/encodings.rs index 8f9b936651a..6cb9eb72995 100644 --- a/crates/common/src/encodings.rs +++ b/crates/common/src/encodings.rs @@ -72,6 +72,9 @@ pub trait DecodeContext: CodecContext { fn restart_from(&mut self, pos: usize) -> Result<(), Self::Error>; + /// Load the Unicode name database when a `\N` escape is reached. + fn load_unicode_names(&self) -> Result<(), Self::Error>; + fn error_decoding(&self, byte_range: Range, reason: Option<&str>) -> Self::Error; fn handle_error( @@ -252,7 +255,7 @@ where let replace = ctx.handle_error(errors, range.clone(), Some(err_reason))?; match replace { EncodeReplace::Str(s) => { - if s.is_compatible_with(target_kind) { + if s.is_compatible_with(StrKind::Ascii) { out.extend_from_slice(s.as_ref().as_bytes()); } else { return Err(ctx.error_encoding(range, Some(err_reason))); @@ -425,7 +428,7 @@ pub mod errors { let mut out = String::with_capacity(num_chars * 4); for c in err_str.code_points() { let c_u32 = c.to_u32(); - if let Some(c_name) = c.to_char().and_then(rustpython_unicode::character_name) { + if let Some(c_name) = rustpython_unicode::data::name_for_namereplace(c_u32) { write!(out, "\\N{{{c_name}}}").unwrap(); } else if c_u32 >= 0x10000 { write!(out, "\\U{c_u32:08x}").unwrap(); @@ -617,8 +620,8 @@ pub mod latin_1 { _errors: &E, ) -> Result<(Wtf8Buf, usize), Ctx::Error> { let out: String = ctx.remaining_data().iter().map(|c| *c as char).collect(); - let out_len = out.len(); - Ok((out.into(), out_len)) + let consumed = ctx.full_data().len(); + Ok((out.into(), consumed)) } } diff --git a/crates/common/src/encodings/cjk/hk.rs b/crates/common/src/encodings/cjk/hk.rs index fdee5d5aebd..32cb98e8990 100644 --- a/crates/common/src/encodings/cjk/hk.rs +++ b/crates/common/src/encodings/cjk/hk.rs @@ -79,7 +79,11 @@ pub(super) fn encode_big5hkscs(input: &[u32], final_input: bool) -> EncodeOne { if let Some(mut code) = try_map_encode(&BIG5HKSCS_BMP_ENCMAP, &BIG5HKSCS_BMP_ENCMAP_DATA, c) { if code == MULTIC { - if input.len() >= 2 && c & 0xffdf == 0x00ca && input[1] & 0xfff7 == 0x0304 { + if input.len() >= 2 + && input[1] <= 0xffff + && c & 0xffdf == 0x00ca + && input[1] & 0xfff7 == 0x0304 + { code = PAIR_ENCODE_TABLE[((c >> 4 | input[1] >> 3) & 3) as usize]; return encoded(code, 2); } diff --git a/crates/common/src/encodings/raw_unicode_escape.rs b/crates/common/src/encodings/raw_unicode_escape.rs index a2df01a2627..a61c9dae4c1 100644 --- a/crates/common/src/encodings/raw_unicode_escape.rs +++ b/crates/common/src/encodings/raw_unicode_escape.rs @@ -41,6 +41,7 @@ where E: DecodeErrorHandler, { let mut out = Wtf8Buf::new(); + let mut consumed = ctx.full_data().len(); loop { let rest = ctx.remaining_data(); if rest.is_empty() { @@ -62,6 +63,7 @@ where let escape_start = ctx.position(); let digits_start = 2; if !final_decode && rest.len() < digits_start + want { + consumed = ctx.position(); break; } let available = (digits_start + want).min(rest.len()); @@ -99,6 +101,7 @@ where continue; } if kind.is_none() && !final_decode { + consumed = ctx.position(); break; } out.push_char(b as char); @@ -108,5 +111,5 @@ where ctx.advance(1); } } - Ok((out, ctx.position())) + Ok((out, consumed)) } diff --git a/crates/common/src/encodings/unicode_escape.rs b/crates/common/src/encodings/unicode_escape.rs index cea7533c1bd..30eeb3f4d0e 100644 --- a/crates/common/src/encodings/unicode_escape.rs +++ b/crates/common/src/encodings/unicode_escape.rs @@ -68,6 +68,7 @@ where { let mut out = Wtf8Buf::new(); let mut warning = None; + let mut consumed = ctx.full_data().len(); loop { let rest = ctx.remaining_data(); if rest.is_empty() { @@ -84,6 +85,7 @@ where let escape_start = ctx.position(); if rest.len() == 1 { if !final_decode { + consumed = ctx.position(); break; } let end = ctx.full_data().len(); @@ -163,6 +165,7 @@ where _ => (8usize, "truncated \\UXXXXXXXX escape"), }; if !final_decode && rest.len() < 2 + digits { + consumed = ctx.position(); break; } ctx.advance(2); @@ -193,7 +196,9 @@ where out.push_wtf8(replace.as_ref()); } b'N' => { + ctx.load_unicode_names()?; if rest.len() == 2 && !final_decode { + consumed = ctx.position(); break; } if rest.len() >= 3 && rest[2] == b'{' { @@ -204,6 +209,7 @@ where } if look >= rest.len() { if !final_decode { + consumed = ctx.position(); break; } let start = escape_start; @@ -268,5 +274,5 @@ where } } } - Ok((out, ctx.position(), warning)) + Ok((out, consumed, warning)) } diff --git a/crates/common/src/encodings/wide.rs b/crates/common/src/encodings/wide.rs index 7d0220f6047..a8eda2d0b6f 100644 --- a/crates/common/src/encodings/wide.rs +++ b/crates/common/src/encodings/wide.rs @@ -131,12 +131,11 @@ where let replace = ctx.handle_error(errors, range.clone(), Some(reason))?; match replace { EncodeReplace::Str(s) => { + if !s.is_compatible_with(StrKind::Ascii) { + return Err(ctx.error_encoding(range, Some(reason))); + } for c in s.as_ref().code_points() { - let cp = c.to_u32(); - if is_surrogate(cp) { - return Err(ctx.error_encoding(range, Some(reason))); - } - emit(&mut out, cp, big_endian); + emit(&mut out, c.to_u32(), big_endian); } } EncodeReplace::Bytes(b) => { diff --git a/crates/common/src/float_ops.rs b/crates/common/src/float_ops.rs index f519cdaba64..6cfabecf973 100644 --- a/crates/common/src/float_ops.rs +++ b/crates/common/src/float_ops.rs @@ -90,37 +90,7 @@ pub fn floordiv(v1: f64, v2: f64) -> Option { divmod(v1, v2).map(|(d, _)| d) } -// Canonical (floordiv, mod) for floats matching CPython's _float_div_mod -// (Objects/floatobject.c). `mod_` and `floordiv` delegate here so that -// `divmod(a, b) == (a // b, a % b)` holds by construction. -#[must_use] -pub fn divmod(v1: f64, v2: f64) -> Option<(f64, f64)> { - if v2 == 0.0 { - return None; - } - let mut m = v1 % v2; - let mut d = (v1 - m) / v2; - if m != 0.0 { - // Non-zero remainder must have the sign of the divisor. - if v2.is_sign_negative() != m.is_sign_negative() { - m += v2; - d -= 1.0; - } - } else { - // Zero remainder: sign matches divisor (IEEE 754 / CPython contract). - m = (0.0_f64).copysign(v2); - } - let d = if d != 0.0 { - let f = d.floor(); - // Snap up if (v1 - m) / v2 undershot the true integer quotient by - // more than half an ULP (mirrors CPython's `if (div - *floordiv > 0.5)`). - if d - f > 0.5 { f + 1.0 } else { f } - } else { - // Zero quotient: take the sign of the true quotient v1 / v2. - (0.0_f64).copysign(v1 / v2) - }; - Some((d, m)) -} +pub use rustpython_literal::float::divmod; // nextafter algorithm based off of https://gitlab.com/bronsonbdevost/next_afterf #[allow(clippy::float_cmp)] @@ -781,52 +751,61 @@ mod tests { fn hash_float_smallest_subnormal() { // hash(5e-324) == 16777216 (CPython 3.14 ground truth). The pre-fix // bit-twiddling frexp returned 8404992 here. - assert_eq!(hash_float(f64::from_bits(1)), Some(16777216)); + assert_eq!( + hash_float(f64::from_bits(1)), + Some(if usize::BITS == 64 { 16777216 } else { 2048 }) + ); } /// Differential float-hash table captured from CPython 3.14.5, spanning /// subnormal boundaries, powers of two across the whole exponent range, and - /// a spread of normals. + /// a spread of normals. The 32-bit column uses the same rational values + /// reduced modulo 2**31 - 1 instead of 2**61 - 1. #[test] fn hash_float_matches_cpython() { - const HASH_CASES: &[(u64, i64)] = &[ - (0x0000000000000001, 16777216), // smallest subnormal 5e-324 - (0x0000000000000002, 33554432), // subnormal - (0x00000000deadbeef, 62678480394911744), // subnormal midrange - (0x0008000000000000, 16384), // subnormal high bit - (0x000fffffffffffff, 2305843009196949503), // largest subnormal - (0x0010000000000000, 32768), // DBL_MIN smallest normal - (0x8000000000000001, -16777216), // negative smallest subnormal - (0x0020000000000000, 65536), // 2**-1021 - (0x0170000000000000, 137438953472), // 2**-1000 - (0x39b0000000000000, 4194304), // 2**-100 - (0x3f50000000000000, 2251799813685248), // 2**-10 - (0x3fe0000000000000, 1152921504606846976), // 2**-1 - (0x3ff0000000000000, 1), // 2**0 - (0x4000000000000000, 2), // 2**1 - (0x4090000000000000, 1024), // 2**10 - (0x4630000000000000, 549755813888), // 2**100 - (0x7e70000000000000, 16777216), // 2**1000 - (0x7fe0000000000000, 140737488355328), // 2**1023 - (0xffe0000000000000, -140737488355328), // -2**1023 - (0x3ff8000000000000, 1152921504606846977), // 1.5 - (0x400921fb54442d18, 326490430436040707), // 3.141592653589793 - (0x7e37e43c8800759c, 1224995262755759164), // 1e+300 - (0x01a56e1fc2f8f359, 482449582752280463), // 1e-300 - (0x40c81cd6c8b43958, 1563361560246628409), // 12345.678 - (0x3fb999999999999a, 230584300921369408), // 0.1 - (0x4005666666666666, 1556444031219243010), // 2.675 - (0x4132d68700000000, 1234567), // 1234567.0 - (0x44dfe154f457ea13, 1428027733287631914), // 6.022e+23 - (0x3c07a42f549647fb, 851769299698974080), // 1.602e-19 - (0xbff0000000000000, -2), // -1.0 - (0xbfb999999999999a, -230584300921369408), // -0.1 + const HASH_CASES: &[(u64, i64, i32)] = &[ + (0x0000000000000001, 16777216, 2048), // smallest subnormal 5e-324 + (0x0000000000000002, 33554432, 4096), // subnormal + (0x00000000deadbeef, 62678480394911744, 1844938218), // subnormal midrange + (0x0008000000000000, 16384, 1), // subnormal high bit + (0x000fffffffffffff, 2305843009196949503, 2147481601), // largest subnormal + (0x0010000000000000, 32768, 2), // DBL_MIN smallest normal + (0x8000000000000001, -16777216, -2048), // negative smallest subnormal + (0x0020000000000000, 65536, 4), // 2**-1021 + (0x0170000000000000, 137438953472, 8388608), // 2**-1000 + (0x39b0000000000000, 4194304, 16777216), // 2**-100 + (0x3f50000000000000, 2251799813685248, 2097152), // 2**-10 + (0x3fe0000000000000, 1152921504606846976, 1073741824), // 2**-1 + (0x3ff0000000000000, 1, 1), // 2**0 + (0x4000000000000000, 2, 2), // 2**1 + (0x4090000000000000, 1024, 1024), // 2**10 + (0x4630000000000000, 549755813888, 128), // 2**100 + (0x7e70000000000000, 16777216, 256), // 2**1000 + (0x7fe0000000000000, 140737488355328, 1), // 2**1023 + (0xffe0000000000000, -140737488355328, -2), // -2**1023 + (0x3ff8000000000000, 1152921504606846977, 1073741825), // 1.5 + (0x400921fb54442d18, 326490430436040707, 864580935), // 3.141592653589793 + (0x7e37e43c8800759c, 1224995262755759164, 260391960), // 1e+300 + (0x01a56e1fc2f8f359, 482449582752280463, 1685713680), // 1e-300 + (0x40c81cd6c8b43958, 1563361560246628409, 46720115), // 12345.678 + (0x3fb999999999999a, 230584300921369408, 1932735308), // 0.1 + (0x4005666666666666, 1556444031219243010, 161060457), // 2.675 + (0x4132d68700000000, 1234567, 1234567), // 1234567.0 + (0x44dfe154f457ea13, 1428027733287631914, 1940176229), // 6.022e+23 + (0x3c07a42f549647fb, 851769299698974080, 186692435), // 1.602e-19 + (0xbff0000000000000, -2, -2), // -1.0 + (0xbfb999999999999a, -230584300921369408, -1932735308), // -0.1 ]; - for &(bits, expected) in HASH_CASES { + for &(bits, expected64, expected32) in HASH_CASES { + let expected = if usize::BITS == 64 { + expected64 + } else { + i64::from(expected32) + }; let v = f64::from_bits(bits); assert_eq!( hash_float(v), - Some(expected), + Some(expected as crate::hash::PyHash), "hash mismatch for {v:e} (bits {bits:#018x})" ); } diff --git a/crates/common/src/format.rs b/crates/common/src/format.rs index 28afac7358b..ef38774ffe7 100644 --- a/crates/common/src/format.rs +++ b/crates/common/src/format.rs @@ -1,7 +1,6 @@ // spell-checker:ignore ddfe DTSF use core::ops::Deref; use core::{cmp, str::FromStr}; -use itertools::{Itertools, PeekingNext}; use malachite_base::num::basic::floats::PrimitiveFloat; use malachite_bigint::{BigInt, Sign}; use num_complex::Complex64; @@ -10,6 +9,7 @@ use num_traits::{Signed, cast::ToPrimitive}; use rustpython_literal::float; use rustpython_literal::format::Case; +use crate::str::char_to_decimal; use crate::wtf8::{CodePoint, Wtf8, Wtf8Buf}; /// Locale information for 'n' format specifier. @@ -21,7 +21,8 @@ pub struct LocaleInfo { pub decimal_point: String, /// Grouping pattern from `lconv.grouping`. /// Each element is a group size. The last non-zero element repeats. - /// e.g. `[3, 0]` means groups of 3 repeating forever. + /// e.g. `[3, 0]` means groups of 3 repeating forever. A `CHAR_MAX` + /// element ends grouping, e.g. `[3, CHAR_MAX]` groups only the last 3 digits. pub grouping: Vec, } @@ -214,15 +215,6 @@ pub struct FormatSpec { format_type: Option, } -fn get_num_digits(text: &Wtf8) -> usize { - for (index, character) in text.code_point_indices() { - if !character.is_char_and(|c| c.is_ascii_digit()) { - return index; - } - } - text.len() -} - fn parse_fill_and_align(text: &Wtf8) -> (Option, Option, &Wtf8) { let char_indices: Vec<(usize, CodePoint)> = text.code_point_indices().take(3).collect(); if char_indices.is_empty() { @@ -242,16 +234,26 @@ fn parse_fill_and_align(text: &Wtf8) -> (Option, Option, } fn parse_number(text: &Wtf8) -> Result<(Option, &Wtf8), FormatSpecError> { - let num_digits: usize = get_num_digits(text); - if num_digits == 0 { - return Ok((None, text)); - } - if let Some(num) = parse_usize(&text[..num_digits]) { - Ok((Some(num), &text[num_digits..])) - } else { + let mut number = None; + let mut rest = text; + let mut chars = text.code_points(); + while let Some(digit) = chars.next().and_then(CodePoint::to_char).and_then(|c| { + if c.is_ascii() { + c.to_digit(10) + } else { + char_to_decimal(c).map(u32::from) + } + }) { // NOTE: this condition is different from CPython - Err(FormatSpecError::DecimalDigitsTooMany) - } + let value = number + .unwrap_or(0usize) + .checked_mul(10) + .and_then(|value| value.checked_add(digit as usize)) + .ok_or(FormatSpecError::DecimalDigitsTooMany)?; + number = Some(value); + rest = chars.as_wtf8(); + } + Ok((number, rest)) } fn parse_alternate_form(text: &Wtf8) -> (bool, &Wtf8) { @@ -618,10 +620,16 @@ impl FormatSpec { return int_part.to_string(); } + #[allow( + clippy::unnecessary_cast, + reason = "core::ffi::c_char is not u8 on all platforms" + )] + const CHAR_MAX: u8 = core::ffi::c_char::MAX as u8; + let mut group_idx = 0; let mut group_size = locale.grouping[0] as usize; - if group_size == 0 { + if group_size == 0 || locale.grouping[0] == CHAR_MAX { return int_part.to_string(); } @@ -641,9 +649,13 @@ impl FormatSpec { // Advance to next group size if group_idx + 1 < locale.grouping.len() { - let next = locale.grouping[group_idx + 1] as usize; + let next = locale.grouping[group_idx + 1]; + if next == CHAR_MAX { + groups.push(&int_part[..pos]); + break; + } if next != 0 { - group_size = next; + group_size = next as usize; group_idx += 1; } // 0 means repeat previous group size forever @@ -1354,9 +1366,12 @@ pub enum FormatParseError { MissingStartBracket, UnescapedStartBracketInLiteral, InvalidFormatSpecifier, - UnknownConversion, + MissingConversion, + MissingConversionColon, + UnexpectedStartBracket, EmptyAttribute, MissingRightBracket, + MissingRightSquareBracket, InvalidCharacterAfterRightBracket, TooManyDecimalDigits, } @@ -1375,43 +1390,56 @@ pub enum FieldNamePart { StringIndex(Wtf8Buf), } -impl FieldNamePart { - fn parse_part( - chars: &mut impl PeekingNext, - ) -> Result, FormatParseError> { - chars - .next() - .map(|ch| match ch.to_char_lossy() { - '.' => { - let mut attribute = Wtf8Buf::new(); - for ch in chars.peeking_take_while(|ch| *ch != '.' && *ch != '[') { - attribute.push(ch); - } - if attribute.is_empty() { - Err(FormatParseError::EmptyAttribute) - } else { - Ok(Self::Attribute(attribute)) +/// Lazily parse field suffixes so each lookup can happen before the next parse. +#[derive(Debug, PartialEq, Eq)] +pub struct FieldNameParts { + text: Wtf8Buf, + cursor: usize, +} + +impl Iterator for FieldNameParts { + type Item = Result; + + fn next(&mut self) -> Option { + let ch = self.text[self.cursor..].code_points().next()?; + self.cursor += ch.len_wtf8(); + let start = self.cursor; + Some(match ch.to_char_lossy() { + '.' => { + while let Some(ch) = self.text[self.cursor..].code_points().next() { + if ch == '.' || ch == '[' { + break; } + self.cursor += ch.len_wtf8(); } - '[' => { - let mut index = Wtf8Buf::new(); - for ch in chars { - if ch == ']' { - return if index.is_empty() { - Err(FormatParseError::EmptyAttribute) - } else if let Some(index) = parse_usize(&index) { - Ok(Self::Index(index)) - } else { - Ok(Self::StringIndex(index)) - }; - } - index.push(ch); + if self.cursor == start { + Err(FormatParseError::EmptyAttribute) + } else { + Ok(FieldNamePart::Attribute( + self.text[start..self.cursor].to_owned(), + )) + } + } + '[' => { + while let Some(ch) = self.text[self.cursor..].code_points().next() { + let end = self.cursor; + self.cursor += ch.len_wtf8(); + if ch == ']' { + let index = &self.text[start..end]; + return Some(if index.is_empty() { + Err(FormatParseError::EmptyAttribute) + } else { + parse_field_index(index).map(|number| match number { + Some(index) => FieldNamePart::Index(index), + None => FieldNamePart::StringIndex(index.to_owned()), + }) + }); } - Err(FormatParseError::MissingRightBracket) } - _ => Err(FormatParseError::InvalidCharacterAfterRightBracket), - }) - .transpose() + Err(FormatParseError::MissingRightSquareBracket) + } + _ => Err(FormatParseError::InvalidCharacterAfterRightBracket), + }) } } @@ -1432,38 +1460,51 @@ fn parse_usize(s: &Wtf8) -> Option { s.as_str().ok().and_then(|s| s.parse().ok()) } -impl FieldName { - pub fn parse(text: &Wtf8) -> Result { - let mut chars = text.code_points().peekable(); - let first: Wtf8Buf = chars - .peeking_take_while(|ch| *ch != '.' && *ch != '[') - .collect(); +fn parse_field_index(text: &Wtf8) -> Result, FormatParseError> { + if let Some(index) = parse_usize(text) { + if index > isize::MAX as usize { + return Err(FormatParseError::TooManyDecimalDigits); + } + Ok(Some(index)) + } else if text + .as_str() + .is_ok_and(|s| s.bytes().all(|b| b.is_ascii_digit())) + { + Err(FormatParseError::TooManyDecimalDigits) + } else { + Ok(None) + } +} +impl FieldName { + pub fn split(text: &Wtf8) -> Result<(FieldType, FieldNameParts), FormatParseError> { + let split = text + .code_point_indices() + .find(|(_, ch)| *ch == '.' || *ch == '[') + .map_or(text.len(), |(index, _)| index); + let first = &text[..split]; let field_type = if first.is_empty() { FieldType::Auto - } else if let Some(index) = parse_usize(&first) { - // Match CPython's get_integer: digits-only segment must fit in - // Py_ssize_t. Above that, raise ValueError at parse time. - if index > isize::MAX as usize { - return Err(FormatParseError::TooManyDecimalDigits); - } + } else if let Some(index) = parse_field_index(first)? { FieldType::Index(index) - } else if first - .as_str() - .is_ok_and(|s| s.bytes().all(|b| b.is_ascii_digit())) - { - // All-digit segment whose value overflows usize itself. - return Err(FormatParseError::TooManyDecimalDigits); } else { - FieldType::Keyword(first) + FieldType::Keyword(first.to_owned()) }; + Ok(( + field_type, + FieldNameParts { + text: text[split..].to_owned(), + cursor: 0, + }, + )) + } - let mut parts = Vec::new(); - while let Some(part) = FieldNamePart::parse_part(&mut chars)? { - parts.push(part) - } - - Ok(Self { field_type, parts }) + pub fn parse(text: &Wtf8) -> Result { + let (field_type, parts) = Self::split(text)?; + Ok(Self { + field_type, + parts: parts.collect::>()?, + }) } } @@ -1521,112 +1562,75 @@ impl FormatString { Ok((FormatPart::Literal(result_string), "".as_ref())) } - fn parse_part_in_brackets(text: &Wtf8) -> Result { - let mut chars = text.code_points().peekable(); - - let mut left = Wtf8Buf::new(); - let mut right = Wtf8Buf::new(); - - let mut split = false; - let mut selected = &mut left; - let mut inside_brackets = false; - - while let Some(char) = chars.next() { - if char == '[' { - inside_brackets = true; - - selected.push(char); - - while let Some(next_char) = chars.next() { - selected.push(next_char); + fn parse_spec(text: &Wtf8) -> Result<(FormatPart, &Wtf8), FormatParseError> { + let mut chars = text.code_point_indices(); + if chars.next().is_none_or(|(_, ch)| ch != '{') { + return Err(FormatParseError::MissingStartBracket); + } + if text.len() == 1 { + return Err(FormatParseError::UnescapedStartBracketInLiteral); + } - if next_char == ']' { - inside_brackets = false; - break; - } - if chars.peek().is_none() { + // Braces, colons and conversion markers inside an item key are data. + let (field_end, mut delimiter) = loop { + let Some((index, ch)) = chars.next() else { + return Err(FormatParseError::UnmatchedBracket); + }; + match ch.to_char_lossy() { + '[' => { + if !chars.any(|(_, ch)| ch == ']') { return Err(FormatParseError::MissingRightBracket); } } - } else if char == ':' && !split && !inside_brackets { - split = true; - selected = &mut right; - } else { - selected.push(char); + '{' => return Err(FormatParseError::UnexpectedStartBracket), + '!' | ':' | '}' => break (index, ch), + _ => {} + } + }; + let field_name = text[1..field_end].to_owned(); + let mut delimiter_index = field_end; + let mut conversion_spec = None; + if delimiter == '!' { + conversion_spec = Some(chars.next().ok_or(FormatParseError::MissingConversion)?.1); + let Some((index, ch)) = chars.next() else { + return Err(FormatParseError::InvalidFormatSpecifier); + }; + if ch != ':' && ch != '}' { + return Err(FormatParseError::MissingConversionColon); } + delimiter_index = index; + delimiter = ch; } - // before the comma is a keyword or arg index, after the comma is maybe a spec. - let arg_part: &Wtf8 = &left; - - let format_spec = if split { right } else { Wtf8Buf::new() }; - - // left can still be the conversion (!r, !s, !a) - let parts: Vec<&Wtf8> = arg_part.splitn(2, "!".as_ref()).collect(); - // before the bang is a keyword or arg index, after the comma is maybe a conversion spec. - let arg_part = parts[0]; - - let conversion_spec = parts - .get(1) - .map(|conversion| { - // conversions are only every one character - conversion - .code_points() - .exactly_one() - .map_err(|_| FormatParseError::UnknownConversion) - }) - .transpose()?; - - Ok(FormatPart::Field { - field_name: arg_part.to_owned(), - conversion_spec, - format_spec, - }) - } - - fn parse_spec(text: &Wtf8) -> Result<(FormatPart, &Wtf8), FormatParseError> { - let mut nested = false; - let mut end_bracket_pos = None; - let mut left = Wtf8Buf::new(); - - // There may be one layer nesting brackets in spec - for (idx, c) in text.code_point_indices() { - if idx == 0 { - if c != '{' { - return Err(FormatParseError::MissingStartBracket); - } - } else if c == '{' { - if nested { + let mut format_spec = Wtf8Buf::new(); + if delimiter == ':' { + let spec_start = delimiter_index + 1; + let mut depth = 1usize; + let spec_end = loop { + let Some((index, ch)) = chars.next() else { return Err(FormatParseError::InvalidFormatSpecifier); + }; + if ch == '{' { + depth += 1; + } else if ch == '}' { + depth -= 1; + if depth == 0 { + break index; + } } - nested = true; - left.push(c); - continue; - } else if c == '}' { - if nested { - nested = false; - left.push(c); - continue; - } - end_bracket_pos = Some(idx); - break; - } else { - left.push(c); - } - } - if let Some(pos) = end_bracket_pos { - let right = &text[pos..]; - let format_part = Self::parse_part_in_brackets(&left)?; - Ok((format_part, &right[1..])) - } else if text.len() == 1 { - // Nothing follows the brace, so it is a stray one rather than a field - // that was left open: CPython separates "{" and "a{" from "{0" and - // "a{b" the same way. `{` is one byte, so a length of one is the brace - // on its own. - Err(FormatParseError::UnescapedStartBracketInLiteral) - } else { - Err(FormatParseError::UnmatchedBracket) + }; + text[spec_start..spec_end].clone_into(&mut format_spec); + delimiter_index = spec_end; } + + Ok(( + FormatPart::Field { + field_name, + conversion_spec, + format_spec, + }, + &text[delimiter_index + 1..], + )) } } @@ -1906,6 +1910,33 @@ mod tests { ); } + #[test] + fn format_int_locale_stops_grouping_at_char_max() { + #[allow( + clippy::unnecessary_cast, + reason = "core::ffi::c_char is not u8 on all platforms" + )] + const CHAR_MAX: u8 = core::ffi::c_char::MAX as u8; + let locale = |grouping| LocaleInfo { + thousands_sep: ",".to_owned(), + decimal_point: ".".to_owned(), + grouping, + }; + let digits = "1".repeat(200); + assert_eq!( + FormatSpec::insert_locale_grouping(&digits, &locale(vec![CHAR_MAX])), + digits + ); + assert_eq!( + FormatSpec::insert_locale_grouping("1234567", &locale(vec![3, CHAR_MAX])), + "1234,567" + ); + assert_eq!( + FormatSpec::insert_locale_grouping("1234567", &locale(vec![3, 0])), + "1,234,567" + ); + } + #[test] fn format_complex_locale_rejects_zero_padding_before_after_sign_alignment() { let locale = LocaleInfo { @@ -2478,7 +2509,10 @@ mod tests { ); assert_eq!(parse("key.."), Err(FormatParseError::EmptyAttribute)); assert_eq!(parse("key[]"), Err(FormatParseError::EmptyAttribute)); - assert_eq!(parse("key["), Err(FormatParseError::MissingRightBracket)); + assert_eq!( + parse("key["), + Err(FormatParseError::MissingRightSquareBracket) + ); assert_eq!( parse("key[0]after"), Err(FormatParseError::InvalidCharacterAfterRightBracket) diff --git a/crates/common/src/hash.rs b/crates/common/src/hash.rs index 1c58abc20f7..3635442a85a 100644 --- a/crates/common/src/hash.rs +++ b/crates/common/src/hash.rs @@ -3,8 +3,8 @@ use malachite_bigint::BigInt; use num_traits::ToPrimitive; use siphasher::sip::SipHasher24; -pub type PyHash = i64; -pub type PyUHash = u64; +pub type PyHash = isize; +pub type PyUHash = usize; /// A PyHash value used to represent a missing hash value, e.g. means "not yet computed" for /// `str`'s hash cache @@ -13,13 +13,14 @@ pub const SENTINEL: PyHash = -1; /// Prime multiplier used in string and various other hashes. pub const MULTIPLIER: PyHash = 1_000_003; // 0xf4243 /// Numeric hashes are based on reduction modulo the prime 2**_BITS - 1 -pub const BITS: usize = 61; +pub const BITS: usize = if usize::BITS >= 64 { 61 } else { 31 }; pub const MODULUS: PyUHash = (1 << BITS) - 1; pub const INF: PyHash = 314_159; pub const NAN: PyHash = 0; pub const IMAG: PyHash = MULTIPLIER; pub const ALGO: &str = "siphash24"; -pub const HASH_BITS: usize = core::mem::size_of::() * 8; +// SipHash24 produces 64 bits before conversion to the platform hash width. +pub const HASH_BITS: usize = 64; // SipHasher24 takes 2 u64s as a seed pub const SEED_BITS: usize = core::mem::size_of::() * 2 * 8; @@ -43,7 +44,10 @@ impl HashSecret { #[must_use] pub fn new(seed: u32) -> Self { let mut buf = [0u8; 16]; - lcg_urandom(seed, &mut buf); + // CPython disables hash randomization with an all-zero secret. + if seed != 0 { + lcg_urandom(seed, &mut buf); + } let (left, right) = buf.split_at(8); let k0 = u64::from_le_bytes(left.try_into().unwrap()); let k1 = u64::from_le_bytes(right.try_into().unwrap()); @@ -72,7 +76,7 @@ impl HashSecret { let item_hash = hash_func(element)?; item_hash.hash(&mut hasher); } - Ok(fix_sentinel(mod_int(hasher.finish() as PyHash))) + Ok(fix_sentinel(mod_int(hasher.finish() as i64))) } #[must_use] @@ -80,13 +84,48 @@ impl HashSecret { if value.is_empty() { 0 } else { - self.hash_value(value) + let mut hasher = self.build_hasher(); + // Py_HashBuffer hashes the buffer directly, without Rust's slice + // length prefix or the modulus used for numeric hashes. + hasher.write(value); + fix_sentinel(hasher.finish() as PyHash) } } + #[inline] #[must_use] pub fn hash_str(&self, value: &str) -> PyHash { - self.hash_bytes(value.as_bytes()) + self.hash_wtf8(value.into()) + } + + /// Hash CPython's canonical native-endian Unicode storage, including surrogates. + #[inline] + #[must_use] + pub fn hash_wtf8(&self, value: &crate::wtf8::Wtf8) -> PyHash { + if value.as_bytes().is_ascii() { + return self.hash_bytes(value.as_bytes()); + } + self.hash_non_ascii(value) + } + + #[cold] + fn hash_non_ascii(&self, value: &crate::wtf8::Wtf8) -> PyHash { + let max = value.code_points().map(|cp| cp.to_u32()).max().unwrap_or(0); + let mut hasher = self.build_hasher(); + if max <= 0xff { + for cp in value.code_points() { + hasher.write_u8(cp.to_u32() as u8); + } + } else if max <= 0xffff { + for cp in value.code_points() { + hasher.write(&(cp.to_u32() as u16).to_ne_bytes()); + } + } else { + for cp in value.code_points() { + hasher.write(&cp.to_u32().to_ne_bytes()); + } + } + fix_sentinel(hasher.finish() as PyHash) } } @@ -149,8 +188,8 @@ pub fn hash_bigint(value: &BigInt) -> PyHash { mod_int(v) } else { // SAFETY: - // MODULUS < i64::MAX, so value % MODULUS is guaranteed to be in the range of i64 - unsafe { (value % MODULUS).to_i64().unwrap_unchecked() } + // MODULUS < isize::MAX, so the signed remainder fits in PyHash. + unsafe { (value % MODULUS).to_isize().unwrap_unchecked() } }; fix_sentinel(ret) @@ -159,7 +198,7 @@ pub fn hash_bigint(value: &BigInt) -> PyHash { #[inline] #[must_use] pub const fn hash_usize(data: usize) -> PyHash { - fix_sentinel(mod_int(data as i64)) + fix_sentinel((data % MODULUS) as PyHash) } #[inline(always)] @@ -171,7 +210,7 @@ pub const fn fix_sentinel(x: PyHash) -> PyHash { #[inline] #[must_use] pub const fn mod_int(value: i64) -> PyHash { - value % MODULUS as i64 + (value % MODULUS as i64) as PyHash } pub fn lcg_urandom(mut x: u32, buf: &mut [u8]) { @@ -214,29 +253,23 @@ pub fn keyed_hash(key: u64, buf: &[u8]) -> u64 { pub fn hash_tuple( element_hashes: impl IntoIterator>, ) -> Result { - const PRIME1: PyUHash = cfg_select! { - target_pointer_width = "64" => 11400714785074694791, - target_pointer_width = "32" => 2654435761, - _ => unreachable!(), - }; - - const PRIME2: PyUHash = cfg_select! { - target_pointer_width = "64" => 14029467366897019727, - target_pointer_width = "32" => 2246822519, - _ => unreachable!(), - }; - - const PRIME5: PyUHash = cfg_select! { - target_pointer_width = "64" => 2870177450012600261, - target_pointer_width = "32" => 374761393, - _ => unreachable!(), - }; - - const ROTATE: u32 = cfg_select! { - target_pointer_width = "64" => 31, - target_pointer_width = "32" => 13, - _ => unreachable!(), - }; + // CPython selects xxHash's constants and rotation by Py_hash_t width. + #[cfg(target_pointer_width = "64")] + const PRIME1: PyUHash = 11400714785074694791; + #[cfg(target_pointer_width = "64")] + const PRIME2: PyUHash = 14029467366897019727; + #[cfg(target_pointer_width = "64")] + const PRIME5: PyUHash = 2870177450012600261; + #[cfg(target_pointer_width = "64")] + const ROTATE: u32 = 31; + #[cfg(target_pointer_width = "32")] + const PRIME1: PyUHash = 2654435761; + #[cfg(target_pointer_width = "32")] + const PRIME2: PyUHash = 2246822519; + #[cfg(target_pointer_width = "32")] + const PRIME5: PyUHash = 374761393; + #[cfg(target_pointer_width = "32")] + const ROTATE: u32 = 13; let mut acc = PRIME5; let mut len: PyUHash = 0; @@ -266,7 +299,8 @@ pub fn hash_tuple( /// each element hash fallibly). The fold is commutative, so element order does /// not affect the result. pub struct FrozenSetHash { - hash: u64, + // collections.abc.Set._hash uses sys.maxsize to mask this algorithm. + hash: usize, } impl FrozenSetHash { @@ -274,7 +308,7 @@ impl FrozenSetHash { pub fn new(len: usize) -> Self { // Factor in the number of active entries Self { - hash: (len as u64 + 1).wrapping_mul(1927868237), + hash: len.wrapping_add(1).wrapping_mul(1927868237), } } @@ -283,12 +317,12 @@ impl FrozenSetHash { // This is important because some use cases have many combinations of a // small number of elements with nearby hashes so that many distinct // combinations collapse to only a handful of distinct hash values. - const fn shuffle_bits(h: u64) -> u64 { + const fn shuffle_bits(h: usize) -> usize { ((h ^ 89869747) ^ (h.wrapping_shl(16))).wrapping_mul(3644798167) } // Xor-in shuffled bits from every entry's hash field because xor is // commutative and a frozenset hash should be independent of order. - self.hash ^= shuffle_bits(element_hash as u64); + self.hash ^= shuffle_bits(element_hash as usize); } #[must_use] @@ -298,7 +332,7 @@ impl FrozenSetHash { hash ^= (hash >> 11) ^ (hash >> 25); hash = hash.wrapping_mul(69069).wrapping_add(907133923); // -1 is reserved as an error code - if hash == u64::MAX { + if hash == usize::MAX { hash = 590923713; } hash as PyHash @@ -309,11 +343,85 @@ impl FrozenSetHash { mod tests { use super::*; + #[test] + fn unicode_hash_uses_canonical_code_units() { + let secret = HashSecret::new(42); + for text in ["", "abc", "éÿ", "äú∑ℇ", "a𐀀b"] { + let max = text.chars().map(u32::from).max().unwrap_or(0); + let mut storage = alloc::vec::Vec::new(); + for ch in text.chars() { + if max <= 0xff { + storage.push(ch as u8); + } else if max <= 0xffff { + storage.extend_from_slice(&(ch as u16).to_ne_bytes()); + } else { + storage.extend_from_slice(&(ch as u32).to_ne_bytes()); + } + } + assert_eq!(secret.hash_str(text), secret.hash_bytes(&storage)); + } + let surrogate = crate::wtf8::Wtf8Buf::from_wide(&[0xd800]); + assert_eq!( + secret.hash_wtf8(&surrogate), + secret.hash_bytes(&0xd800u16.to_ne_bytes()) + ); + } + + #[test] + fn native_integer_key_hash_matches_bigint() { + for value in [0, 1, isize::MAX as usize, usize::MAX] { + assert_eq!(hash_usize(value), hash_bigint(&BigInt::from(value))); + } + } + + #[test] + fn frozenset_hash_matches_set_mixin_width() { + for elements in [ + &[][..], + &[0][..], + &[-1, 1][..], + &[1, 2, 3][..], + &[PyHash::MIN, PyHash::MAX][..], + ] { + let mut hasher = FrozenSetHash::new(elements.len()); + let mask = usize::MAX as u128; + let mut expected = (1927868237 * (elements.len() as u128 + 1)) & mask; + for &element in elements { + hasher.add(element); + let h = element as u64 as u128; + expected ^= (h ^ (h << 16) ^ 89869747) * 3644798167; + expected &= mask; + } + expected ^= (expected >> 11) ^ (expected >> 25); + expected = (expected * 69069 + 907133923) & mask; + let expected = expected as usize as PyHash; + let expected = if expected == -1 { 590923713 } else { expected }; + assert_eq!(hasher.finish(), expected); + } + } + + #[test] + fn tuple_hash_uses_the_declared_hash_width() { + for (elements, expected64, expected32) in [ + (&[][..], 5740354900026072187i64, 750394483), + (&[0][..], -8753497827991233192, 1214856301), + (&[0, 0][..], -8458139203682520985, -168982784), + ] { + let expected = if usize::BITS == 64 { + expected64 as PyHash + } else { + expected32 + }; + let actual = hash_tuple(elements.iter().copied().map(Ok::<_, ()>)).unwrap(); + assert_eq!(actual, expected); + } + } + #[test] fn from_keys_is_stable_and_seed_independent() { const K0: u64 = 0x0706_0504_0302_0100; const K1: u64 = 0x0f0e_0d0c_0b0a_0908; - const LOCKED_DIGEST: PyHash = -1862661396243998188; + const LOCKED_DIGEST: PyHash = 424532722944612153u64 as PyHash; // Two secrets built from the same explicit keys hash identically, and // the digest does not depend on the seed-derivation path. diff --git a/crates/common/src/int.rs b/crates/common/src/int.rs index f0e84d9b730..07bb97a65ff 100644 --- a/crates/common/src/int.rs +++ b/crates/common/src/int.rs @@ -1,19 +1,8 @@ -use malachite_base::{num::conversion::traits::RoundingInto, rounding_modes::RoundingMode}; use malachite_bigint::{BigInt, BigUint, Sign}; use malachite_q::Rational; use num_traits::{One, ToPrimitive, Zero}; -#[must_use] -pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 { - let rational = Rational::from_integers_ref(numerator.into(), denominator.into()); - match rational.rounding_into(RoundingMode::Nearest) { - // returned value is $t::MAX but still less than the original - (val, core::cmp::Ordering::Less) if val == f64::MAX => f64::INFINITY, - // returned value is $t::MIN but still greater than the original - (val, core::cmp::Ordering::Greater) if val == f64::MIN => f64::NEG_INFINITY, - (val, _) => val, - } -} +pub use rustpython_literal::float::true_div; #[must_use] pub fn float_to_ratio(value: f64) -> Option<(BigInt, BigInt)> { @@ -202,17 +191,40 @@ fn word_all_ascii_digits(word: u64) -> bool { (below | above) & 0x8080_8080_8080_8080 == 0 } -// num-bigint now returns Some(inf) for to_f64() in some cases, so just keep that the same for now +/// Convert an integer to a finite float, or return None when it overflows. #[inline(always)] #[must_use] pub fn bigint_to_finite_float(int: &BigInt) -> Option { - int.to_f64().filter(|f| f.is_finite()) + // malachite-bigint's ToPrimitive returns None when the input exceeds + // the largest finite magnitude, even when nearest rounding is finite. + let value = int + .to_f64() + .unwrap_or_else(|| true_div(int, &BigInt::one())); + value.is_finite().then_some(value) } #[cfg(test)] mod tests { use super::*; + #[test] + fn true_div_signed_zero() { + let denominator = BigInt::one() << 100usize; + assert_eq!( + true_div(&BigInt::zero(), &denominator).to_bits(), + 0.0f64.to_bits() + ); + assert_eq!( + true_div(&BigInt::zero(), &-denominator).to_bits(), + (-0.0f64).to_bits() + ); + let denominator = BigInt::one() << 2000usize; + assert_eq!( + true_div(&BigInt::from(-1), &denominator).to_bits(), + (-0.0f64).to_bits() + ); + } + const DIGIT_LIMIT: usize = 4300; // Default of Cpython #[test] diff --git a/crates/common/src/lock.rs b/crates/common/src/lock.rs index 134b7f2a4fa..56253b4ba36 100644 --- a/crates/common/src/lock.rs +++ b/crates/common/src/lock.rs @@ -8,14 +8,16 @@ use lock_api::{ cfg_select! { feature = "threading" => { + pub use core::cell::LazyCell; pub use detaching::{BlockingWaitHook, set_blocking_wait_hook, set_world_stopped}; pub use parking_lot::{RawMutex, RawRwLock, RawThreadId}; pub use std::sync::OnceLock as OnceCell; - pub use core::cell::LazyCell; } _ => { mod cell_lock; - pub use cell_lock::{RawCellMutex as RawMutex, RawCellRwLock as RawRwLock, SingleThreadId as RawThreadId}; + pub use cell_lock::{ + RawCellMutex as RawMutex, RawCellRwLock as RawRwLock, SingleThreadId as RawThreadId, + }; pub use core::cell::{LazyCell, OnceCell}; } @@ -37,13 +39,19 @@ cfg_select! { unsafe impl Sync for LazyLock {} impl T> LazyLock { - pub const fn new(f: F) -> Self { Self(core::cell::LazyCell::new(f)) } - pub fn force(this: &Self) -> &T { core::cell::LazyCell::force(&this.0) } + pub const fn new(f: F) -> Self { + Self(core::cell::LazyCell::new(f)) + } + pub fn force(this: &Self) -> &T { + core::cell::LazyCell::force(&this.0) + } } impl T> core::ops::Deref for LazyLock { type Target = T; - fn deref(&self) -> &T { &self.0 } + fn deref(&self) -> &T { + &self.0 + } } } } diff --git a/crates/common/src/lock/thread_mutex.rs b/crates/common/src/lock/thread_mutex.rs index c996ff80289..2be0b03bea3 100644 --- a/crates/common/src/lock/thread_mutex.rs +++ b/crates/common/src/lock/thread_mutex.rs @@ -8,7 +8,7 @@ use core::{ ptr::NonNull, sync::atomic::{AtomicUsize, Ordering}, }; -use lock_api::{GetThreadId, GuardNoSend, RawMutex}; +use lock_api::{GetThreadId, GuardNoSend, RawMutex, RawMutexTimed}; // based off ReentrantMutex from lock_api @@ -30,6 +30,10 @@ impl RawThreadMutex { get_thread_id: G::INIT, }; + fn is_owned_by_current_thread(&self) -> bool { + self.owner.load(Ordering::Relaxed) == self.get_thread_id.nonzero_thread_id().get() + } + #[inline] fn lock_internal bool>(&self, try_lock: F) -> Option { let id = self.get_thread_id.nonzero_thread_id().get(); @@ -53,18 +57,6 @@ impl RawThreadMutex { .is_some() } - /// Like `lock()` but wraps the blocking wait in `wrap_fn`. - /// The caller can use this to detach thread state while waiting. - pub fn lock_wrapped(&self, wrap_fn: F) -> bool { - let id = self.get_thread_id.nonzero_thread_id().get(); - if self.owner.load(Ordering::Relaxed) == id { - return false; - } - wrap_fn(&|| self.mutex.lock()); - self.owner.store(id, Ordering::Relaxed); - true - } - /// Returns `Some(true)` if able to successfully lock without blocking, `Some(false)` /// otherwise, and `None` when the mutex is already locked on the current thread. pub fn try_lock(&self) -> Option { @@ -149,18 +141,16 @@ impl ThreadMutex { /// Like `lock()` but wraps the blocking wait in `wrap_fn`. /// The caller can use this to detach thread state while waiting. - pub fn lock_wrapped( - &self, - wrap_fn: F, - ) -> Option> { - if self.raw.lock_wrapped(wrap_fn) { - Some(ThreadMutexGuard { - mu: self, - marker: PhantomData, - }) - } else { - None + pub fn lock_wrapped<'a, F>(&'a self, wrap_fn: F) -> Option> + where + F: FnOnce( + &dyn Fn() -> Option>, + ) -> Option>, + { + if self.raw.is_owned_by_current_thread() { + return None; } + wrap_fn(&|| self.lock()) } pub fn try_lock(&self) -> Result, TryLockThreadError> { @@ -175,6 +165,36 @@ impl ThreadMutex { } } +impl ThreadMutex { + /// Wait at most `timeout`, wrapping only the blocking acquisition. + pub fn try_lock_for_wrapped<'a, F>( + &'a self, + timeout: R::Duration, + wrap_fn: F, + ) -> Result, TryLockThreadError> + where + F: FnOnce( + &dyn Fn() -> Result, TryLockThreadError>, + ) -> Result, TryLockThreadError>, + R::Duration: Copy, + { + if self.raw.is_owned_by_current_thread() { + return Err(TryLockThreadError::Current); + } + wrap_fn(&|| match self + .raw + .lock_internal(|| self.raw.mutex.try_lock_for(timeout)) + { + Some(true) => Ok(ThreadMutexGuard { + mu: self, + marker: PhantomData, + }), + Some(false) => Err(TryLockThreadError::Other), + None => Err(TryLockThreadError::Current), + }) + } +} + #[derive(Clone, Copy)] pub enum TryLockThreadError { /// Failed to lock because mutex was already locked on another thread. @@ -353,3 +373,49 @@ impl fmt::Debug fmt::Debug::fmt(&**self, f) } } + +#[cfg(test)] +#[cfg(feature = "threading")] +mod tests { + use super::TryLockThreadError; + use crate::lock::PyThreadMutex; + use core::time::Duration; + + #[test] + fn timed_lock_preserves_ownership() { + let mutex = PyThreadMutex::new(0); + let guard = mutex.lock().unwrap(); + assert!(matches!( + mutex.try_lock_for_wrapped(Duration::ZERO, |_| panic!("reentrant wait")), + Err(TryLockThreadError::Current) + )); + std::thread::scope(|scope| { + scope.spawn(|| { + assert!(matches!( + mutex.try_lock_for_wrapped(Duration::from_millis(1), |wait| wait()), + Err(TryLockThreadError::Other) + )); + }); + }); + drop(guard); + let mut guard = mutex + .try_lock_for_wrapped(Duration::ZERO, |wait| wait()) + .unwrap_or_else(|_| panic!("unlocked mutex")); + *guard = 1; + drop(guard); + assert_eq!(*mutex.lock().unwrap(), 1); + } + + #[test] + fn wrapped_lock_releases_on_panic() { + let mutex = PyThreadMutex::new(0); + let result = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| { + mutex.lock_wrapped(|wait| { + let _g = wait(); + panic!() + }) + })); + assert!(result.is_err()); + assert!(mutex.try_lock().is_ok()); + } +} diff --git a/crates/common/src/str.rs b/crates/common/src/str.rs index be1086b6209..0da47e72582 100644 --- a/crates/common/src/str.rs +++ b/crates/common/src/str.rs @@ -743,24 +743,31 @@ pub mod levenshtein { /// Replace all tabs in a string with spaces, using the given tab size. #[must_use] pub fn expandtabs(input: &Wtf8, tab_size: usize) -> Wtf8Buf { + let capacity = if tab_size == 0 { 0 } else { input.len() }; + let mut expanded_str = Wtf8Buf::with_capacity(capacity); + expandtabs_into(input, tab_size, &mut expanded_str); + expanded_str +} + +/// Append tab-expanded input to a buffer whose capacity the caller may reserve. +pub fn expandtabs_into(input: &Wtf8, tab_stop: usize, expanded_str: &mut Wtf8Buf) { // A tab size of zero, which is also where a negative one lands, leaves no // column for a tab to advance to: the tabs come out and nothing else moves. // Going through the arithmetic anyway subtracts the current column from a // tab stop of zero and underflows on the first tab, so the width asked for - // next is `usize::MAX`. The bytes version of this already returns here. - if tab_size == 0 { - return input.code_points().filter(|ch| *ch != '\t').collect(); + // next is `usize::MAX`. + if tab_stop == 0 { + expanded_str.extend(input.code_points().filter(|ch| *ch != '\t')); + return; } - let tab_stop = tab_size; - let mut expanded_str = Wtf8Buf::with_capacity(input.len()); let mut tab_size = tab_stop; let mut col_count = 0usize; for ch in input.code_points() { if ch == '\t' { let num_spaces = tab_size - col_count; col_count += num_spaces; - expanded_str.push_str(&" ".repeat(num_spaces)); + expanded_str.extend(core::iter::repeat_n(CodePoint::from(' '), num_spaces)); } else { expanded_str.push(ch); if ch == '\r' || ch == '\n' { @@ -774,7 +781,6 @@ pub fn expandtabs(input: &Wtf8, tab_size: usize) -> Wtf8Buf { tab_size += tab_stop; } } - expanded_str } /// Creates an [`AsciiStr`][ascii::AsciiStr] from a string literal, throwing a compile error if the diff --git a/crates/compiler-core/src/bytecode.rs b/crates/compiler-core/src/bytecode.rs index f7d117cb76b..022c4e8cbb3 100644 --- a/crates/compiler-core/src/bytecode.rs +++ b/crates/compiler-core/src/bytecode.rs @@ -11,7 +11,7 @@ use bitflags::bitflags; use core::{ cell::UnsafeCell, hash, mem, - ops::{Deref, DerefMut, Index, IndexMut}, + ops::{Deref, Index, IndexMut}, sync::atomic::{AtomicU8, AtomicU16, AtomicUsize, Ordering}, }; use itertools::Itertools; @@ -27,9 +27,9 @@ pub use crate::bytecode::{ }, oparg::{ BinaryOperator, BuildSliceArgCount, CommonConstant, ComparisonOperator, ConvertValueOparg, - IntrinsicFunction1, IntrinsicFunction2, Invert, Label, LoadAttr, LoadSuperAttr, - MakeFunctionFlag, MakeFunctionFlags, NameIdx, OpArg, OpArgByte, OpArgState, OpArgType, - RaiseKind, SpecialMethod, UnpackExArgs, + ImportName, IntrinsicFunction1, IntrinsicFunction2, Invert, Label, LoadAttr, LoadGlobal, + LoadSuperAttr, MakeFunctionFlag, MakeFunctionFlags, NameIdx, OpArg, OpArgByte, OpArgState, + OpArgType, RaiseKind, SpecialMethod, UnpackExArgs, }, }; @@ -286,12 +286,16 @@ impl PyCodeLocationInfoKind { pub trait Constant: Sized + Clone { type Name: AsRef; + /// Storage of a code object's constants (`co_consts`). + type Tuple: Clone + Deref + FromIterator; + /// Transforms the given Constant to a BorrowedConstant fn borrow_constant(&self) -> BorrowedConstant<'_, Self>; } impl Constant for ConstantData { type Name = String; + type Tuple = Box<[Self]>; fn borrow_constant(&self) -> BorrowedConstant<'_, Self> { match self { @@ -373,19 +377,23 @@ impl ConstantBag for BasicBag { } #[derive(Clone)] -pub struct Constants(Box<[C]>); +pub struct Constants(C::Tuple); -impl Deref for Constants { - type Target = [C]; +impl Constants { + pub const fn new(tuple: C::Tuple) -> Self { + Self(tuple) + } - fn deref(&self) -> &Self::Target { + pub const fn as_tuple(&self) -> &C::Tuple { &self.0 } } -impl DerefMut for Constants { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 +impl Deref for Constants { + type Target = [C]; + + fn deref(&self) -> &Self::Target { + &self.0 } } @@ -397,18 +405,66 @@ impl Index for Constants { } } -impl IndexMut for Constants { - fn index_mut(&mut self, consti: oparg::ConstIdx) -> &mut Self::Output { - &mut self.0[consti.as_usize()] +impl FromIterator for Constants { + fn from_iter>(iter: T) -> Self { + Self(iter.into_iter().collect()) } } -impl FromIterator for Constants { - fn from_iter>(iter: T) -> Self { +/// Names referenced by a code object (`co_names`), indexed by [`oparg::NameIdx`]. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Names(Box<[N]>); + +impl Names { + #[must_use] + pub const fn as_slice(&self) -> &[N] { + &self.0 + } + + #[must_use] + pub const fn len(&self) -> usize { + self.0.len() + } + + #[must_use] + pub const fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn iter(&self) -> core::slice::Iter<'_, N> { + self.0.iter() + } +} + +impl Index for Names { + type Output = N; + + fn index(&self, namei: oparg::NameIdx) -> &Self::Output { + &self.0[namei.as_usize()] + } +} + +impl From> for Names { + fn from(names: Box<[N]>) -> Self { + Self(names) + } +} + +impl FromIterator for Names { + fn from_iter>(iter: T) -> Self { Self(iter.into_iter().collect()) } } +impl<'a, N> IntoIterator for &'a Names { + type Item = &'a N; + type IntoIter = core::slice::Iter<'a, N>; + + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + // TODO: Newtype "CodeObject.varnames". Make sure only `oparg:VarNum` can be used as index impl Index for [T] { type Output = T; @@ -479,7 +535,7 @@ pub struct CodeObject { /// Qualified name of the object (like CPython's co_qualname) pub qualname: C::Name, pub constants: Constants, - pub names: Box<[C::Name]>, + pub names: Names, pub varnames: Box<[C::Name]>, pub cellvars: Box<[C::Name]>, pub freevars: Box<[C::Name]>, @@ -734,6 +790,27 @@ impl Deref for CodeUnits { } impl CodeUnits { + /// `fixup_getiter` applied to every `GET_ITER` by `_PyCode_Quicken`. + /// + /// The compiler can't know if `types.coroutine()` will be called, so a + /// yield-from `GET_ITER` is resolved when the code object is created. + pub fn fixup_get_iter(&mut self, flags: CodeFlags) { + let mode = if flags.intersects(CodeFlags::COROUTINE | CodeFlags::ITERABLE_COROUTINE) { + oparg::GET_ITER_YIELD_FROM_NO_CHECK + } else { + oparg::GET_ITER_YIELD_FROM_CORO_CHECK + }; + let mut i = 0; + let units = self.units.get_mut(); + while i < units.len() { + let unit = &mut units[i]; + if matches!(unit.op, Instruction::GetIter { .. }) && u8::from(unit.arg) != 0 { + unit.arg = (mode as u8).into(); + } + i += 1 + unit.op.cache_entries(); + } + } + /// Disable adaptive specialization by setting all counters to unreachable. /// Used for CPython-compiled bytecode where specialization may not be safe. pub fn disable_specialization(&self) { @@ -937,26 +1014,46 @@ impl CodeUnits { /// (marshal) and `co_code`. Specialized opcodes are mapped back to their /// base variants via `deoptimize()` and all CACHE entries are zeroed. pub fn original_bytes(&self) -> Vec { - let len = self.len(); - let mut out = Vec::with_capacity(len * 2); - let mut i = 0; - while i < len { - let op = self.read_op(i).deoptimize(); - let arg = self.read_arg(i); - let caches = op.cache_entries(); - out.push(u8::from(op)); - out.push(u8::from(arg)); + self.original_bytes_with(|_, op| op) + } + + /// [`Self::original_bytes`], with `resolve` first replacing the opcode at + /// an index, e.g. an instrumentation placeholder by its original opcode. + pub fn original_bytes_with( + &self, + resolve: impl Fn(usize, Instruction) -> Instruction, + ) -> Vec { + let mut out = Vec::with_capacity(self.len() * 2); + for unit in self.original_instructions_with(resolve) { + out.push(u8::from(unit.op)); + out.push(u8::from(unit.arg)); // Zero-fill all CACHE entries (counter + cached data) - for _ in 0..caches { - i += 1; + for _ in 0..unit.op.cache_entries() { out.push(0); // op = Cache = 0 out.push(0); // arg = 0 } - i += 1; } out } + /// Iterate over deoptimized instructions, skipping inline cache data. + /// `resolve` restores instrumentation placeholders before resolving base opcodes. + pub fn original_instructions_with( + &self, + resolve: impl Fn(usize, Instruction) -> Instruction, + ) -> impl Iterator { + let mut i = 0; + core::iter::from_fn(move || { + if i >= self.len() { + return None; + } + let op = resolve(i, self.read_op(i)).deoptimize(); + let unit = CodeUnit::new(op, self.read_arg(i)); + i += 1 + op.cache_entries(); + Some(unit) + }) + } + /// Initialize adaptive warmup counters for all cacheable instructions. /// Called lazily at RESUME (first execution of a code object). /// Counters are stored out-of-line to preserve `op = Instruction::Cache`. @@ -1321,7 +1418,11 @@ impl CodeObject { .iter() .map(|x| bag.make_constant(x.borrow_constant())) .collect(), - names: map_names(self.names), + names: self + .names + .iter() + .map(|x| bag.make_name(x.as_ref())) + .collect(), varnames: map_names(self.varnames), cellvars: map_names(self.cellvars), freevars: map_names(self.freevars), @@ -1353,7 +1454,11 @@ impl CodeObject { .iter() .map(|x| bag.make_constant(x.borrow_constant())) .collect(), - names: map_names(&self.names), + names: self + .names + .iter() + .map(|x| bag.make_name(x.as_ref())) + .collect(), varnames: map_names(&self.varnames), cellvars: map_names(&self.cellvars), freevars: map_names(&self.freevars), @@ -1381,7 +1486,7 @@ pub trait InstrDisplayContext { fn get_constant(&self, consti: oparg::ConstIdx) -> &Self::Constant; - fn get_name(&self, i: usize) -> &str; + fn get_name(&self, namei: oparg::NameIdx) -> &str; fn get_varname(&self, var_num: oparg::VarNum) -> &str; @@ -1396,8 +1501,8 @@ impl InstrDisplayContext for CodeObject { &self.constants[consti] } - fn get_name(&self, i: usize) -> &str { - self.names[i].as_ref() + fn get_name(&self, namei: oparg::NameIdx) -> &str { + self.names[namei].as_ref() } fn get_varname(&self, var_num: oparg::VarNum) -> &str { diff --git a/crates/compiler-core/src/bytecode/instruction.rs b/crates/compiler-core/src/bytecode/instruction.rs index f403507f1aa..07c9317c467 100644 --- a/crates/compiler-core/src/bytecode/instruction.rs +++ b/crates/compiler-core/src/bytecode/instruction.rs @@ -333,261 +333,260 @@ define_opcodes!( FormatWithSpec = 13, GetAiter = 14, GetAnext = 15, - GetIter = 16, + GetLen = 16, Reserved = 17, - GetLen = 18, - GetYieldFromIter = 19, - InterpreterExit = 20, - LoadBuildClass = 21, - LoadLocals = 22, - MakeFunction = 23, - MatchKeys = 24, - MatchMapping = 25, - MatchSequence = 26, - Nop = 27, - NotTaken = 28, - PopExcept = 29, - PopIter = 30, - PopTop = 31, - PushExcInfo = 32, - PushNull = 33, - ReturnGenerator = 34, - ReturnValue = 35, - SetupAnnotations = 36, - StoreSlice = 37, - StoreSubscr = 38, - ToBool = 39, - UnaryInvert = 40, - UnaryNegative = 41, - UnaryNot = 42, - WithExceptStart = 43, + InterpreterExit = 18, + LoadBuildClass = 19, + LoadLocals = 20, + MakeFunction = 21, + MatchKeys = 22, + MatchMapping = 23, + MatchSequence = 24, + Nop = 25, + NotTaken = 26, + PopExcept = 27, + PopIter = 28, + PopTop = 29, + PushExcInfo = 30, + PushNull = 31, + ReturnGenerator = 32, + ReturnValue = 33, + SetupAnnotations = 34, + StoreSlice = 35, + StoreSubscr = 36, + ToBool = 37, + UnaryInvert = 38, + UnaryNegative = 39, + UnaryNot = 40, + WithExceptStart = 41, BinaryOp { op: Arg, - } = 44, + } = 42, BuildInterpolation { format: Arg, - } = 45, + } = 43, BuildList { count: Arg, - } = 46, + } = 44, BuildMap { count: Arg, - } = 47, + } = 45, BuildSet { count: Arg, - } = 48, + } = 46, BuildSlice { argc: Arg, - } = 49, + } = 47, BuildString { count: Arg, - } = 50, + } = 48, BuildTuple { count: Arg, - } = 51, + } = 49, Call { argc: Arg, - } = 52, + } = 50, CallIntrinsic1 { func: Arg, - } = 53, + } = 51, CallIntrinsic2 { func: Arg, - } = 54, + } = 52, CallKw { argc: Arg, - } = 55, + } = 53, CompareOp { opname: Arg, - } = 56, + } = 54, ContainsOp { invert: Arg, - } = 57, + } = 55, ConvertValue { oparg: Arg, - } = 58, + } = 56, Copy { i: Arg, - } = 59, + } = 57, CopyFreeVars { n: Arg, - } = 60, + } = 58, DeleteAttr { namei: Arg, - } = 61, + } = 59, DeleteDeref { i: Arg, - } = 62, + } = 60, DeleteFast { var_num: Arg, - } = 63, + } = 61, DeleteGlobal { namei: Arg, - } = 64, + } = 62, DeleteName { namei: Arg, - } = 65, + } = 63, DictMerge { i: Arg, - } = 66, + } = 64, DictUpdate { i: Arg, - } = 67, - EndAsyncFor = 68, - ExtendedArg = 69, + } = 65, + EndAsyncFor = 66, + ExtendedArg = 67, ForIter { delta: Arg, - } = 70, + } = 68, GetAwaitable { r#where: Arg, - } = 71, + } = 69, + GetIter { mode: Arg } = 70, ImportFrom { namei: Arg, - } = 72, + } = 71, ImportName { - namei: Arg, - } = 73, + namei: Arg, + } = 72, IsOp { invert: Arg, - } = 74, + } = 73, JumpBackward { delta: Arg, - } = 75, + } = 74, JumpBackwardNoInterrupt { delta: Arg, - } = 76, + } = 75, JumpForward { delta: Arg, - } = 77, + } = 76, ListAppend { i: Arg, - } = 78, + } = 77, ListExtend { i: Arg, - } = 79, + } = 78, LoadAttr { namei: Arg, - } = 80, + } = 79, LoadCommonConstant { idx: Arg, - } = 81, + } = 80, LoadConst { consti: Arg, - } = 82, + } = 81, LoadDeref { i: Arg, - } = 83, + } = 82, LoadFast { var_num: Arg, - } = 84, + } = 83, LoadFastAndClear { var_num: Arg, - } = 85, + } = 84, LoadFastBorrow { var_num: Arg, - } = 86, + } = 85, LoadFastBorrowLoadFastBorrow { var_nums: Arg, - } = 87, + } = 86, LoadFastCheck { var_num: Arg, - } = 88, + } = 87, LoadFastLoadFast { var_nums: Arg, - } = 89, + } = 88, LoadFromDictOrDeref { i: Arg, - } = 90, + } = 89, LoadFromDictOrGlobals { i: Arg, - } = 91, + } = 90, LoadGlobal { - namei: Arg, - } = 92, + namei: Arg, + } = 91, LoadName { namei: Arg, - } = 93, + } = 92, LoadSmallInt { i: Arg, - } = 94, + } = 93, LoadSpecial { method: Arg, - } = 95, + } = 94, LoadSuperAttr { namei: Arg, - } = 96, + } = 95, MakeCell { i: Arg, - } = 97, + } = 96, MapAdd { i: Arg, - } = 98, + } = 97, MatchClass { count: Arg, - } = 99, + } = 98, PopJumpIfFalse { delta: Arg, - } = 100, + } = 99, PopJumpIfNone { delta: Arg, - } = 101, + } = 100, PopJumpIfNotNone { delta: Arg, - } = 102, + } = 101, PopJumpIfTrue { delta: Arg, - } = 103, + } = 102, RaiseVarargs { argc: Arg, - } = 104, + } = 103, Reraise { depth: Arg, - } = 105, + } = 104, Send { delta: Arg, - } = 106, + } = 105, SetAdd { i: Arg, - } = 107, + } = 106, SetFunctionAttribute { flag: Arg, - } = 108, + } = 107, SetUpdate { i: Arg, - } = 109, + } = 108, StoreAttr { namei: Arg, - } = 110, + } = 109, StoreDeref { i: Arg, - } = 111, + } = 110, StoreFast { var_num: Arg, - } = 112, + } = 111, StoreFastLoadFast { var_nums: Arg, - } = 113, + } = 112, StoreFastStoreFast { var_nums: Arg, - } = 114, + } = 113, StoreGlobal { namei: Arg, - } = 115, + } = 114, StoreName { namei: Arg, - } = 116, + } = 115, Swap { i: Arg, - } = 117, + } = 116, UnpackEx { counts: Arg, - } = 118, + } = 117, UnpackSequence { count: Arg, - } = 119, + } = 118, YieldValue { arg: Arg, - } = 120, + } = 119, Resume { context: Arg, } = 128, @@ -603,99 +602,108 @@ define_opcodes!( BinaryOpSubscrListSlice = 138, BinaryOpSubscrStrInt = 139, BinaryOpSubscrTupleInt = 140, - BinaryOpSubtractFloat = 141, - BinaryOpSubtractInt = 142, - CallAllocAndEnterInit = 143, - CallBoundMethodExactArgs = 144, - CallBoundMethodGeneral = 145, - CallBuiltinClass = 146, - CallBuiltinFast = 147, - CallBuiltinFastWithKeywords = 148, - CallBuiltinO = 149, - CallIsinstance = 150, - CallKwBoundMethod = 151, - CallKwNonPy = 152, - CallKwPy = 153, - CallLen = 154, - CallListAppend = 155, - CallMethodDescriptorFast = 156, - CallMethodDescriptorFastWithKeywords = 157, - CallMethodDescriptorNoargs = 158, - CallMethodDescriptorO = 159, - CallNonPyGeneral = 160, - CallPyExactArgs = 161, - CallPyGeneral = 162, - CallStr1 = 163, - CallTuple1 = 164, - CallType1 = 165, - CompareOpFloat = 166, - CompareOpInt = 167, - CompareOpStr = 168, - ContainsOpDict = 169, - ContainsOpSet = 170, - ForIterGen = 171, - ForIterList = 172, - ForIterRange = 173, - ForIterTuple = 174, - JumpBackwardJit = 175, - JumpBackwardNoJit = 176, - LoadAttrClass = 177, - LoadAttrClassWithMetaclassCheck = 178, - LoadAttrGetattributeOverridden = 179, - LoadAttrInstanceValue = 180, - LoadAttrMethodLazyDict = 181, - LoadAttrMethodNoDict = 182, - LoadAttrMethodWithValues = 183, - LoadAttrModule = 184, - LoadAttrNondescriptorNoDict = 185, - LoadAttrNondescriptorWithValues = 186, - LoadAttrProperty = 187, - LoadAttrSlot = 188, - LoadAttrWithHint = 189, - LoadConstImmortal = 190, - LoadConstMortal = 191, - LoadGlobalBuiltin = 192, - LoadGlobalModule = 193, - LoadSuperAttrAttr = 194, - LoadSuperAttrMethod = 195, - ResumeCheck = 196, - SendGen = 197, - StoreAttrInstanceValue = 198, - StoreAttrSlot = 199, - StoreAttrWithHint = 200, - StoreSubscrDict = 201, - StoreSubscrListInt = 202, - ToBoolAlwaysTrue = 203, - ToBoolBool = 204, - ToBoolInt = 205, - ToBoolList = 206, - ToBoolNone = 207, - ToBoolStr = 208, - UnpackSequenceList = 209, - UnpackSequenceTuple = 210, - UnpackSequenceTwoTuple = 211, - InstrumentedEndFor = 234, - InstrumentedPopIter = 235, - InstrumentedEndSend = 236, - InstrumentedForIter = 237, - InstrumentedInstruction = 238, - InstrumentedJumpForward = 239, - InstrumentedNotTaken = 240, - InstrumentedPopJumpIfTrue = 241, - InstrumentedPopJumpIfFalse = 242, - InstrumentedPopJumpIfNone = 243, - InstrumentedPopJumpIfNotNone = 244, - InstrumentedResume = 245, - InstrumentedReturnValue = 246, - InstrumentedYieldValue = 247, - InstrumentedEndAsyncFor = 248, - InstrumentedLoadSuperAttr = 249, - InstrumentedCall = 250, - InstrumentedCallKw = 251, - InstrumentedCallFunctionEx = 252, - InstrumentedJumpBackward = 253, - InstrumentedLine = 254, - EnterExecutor = 255, + BinaryOpSubscrUstrInt = 141, + BinaryOpSubtractFloat = 142, + BinaryOpSubtractInt = 143, + CallAllocAndEnterInit = 144, + CallBoundMethodExactArgs = 145, + CallBoundMethodGeneral = 146, + CallBuiltinClass = 147, + CallBuiltinFast = 148, + CallBuiltinFastWithKeywords = 149, + CallBuiltinO = 150, + CallExNonPyGeneral = 151, + CallExPy = 152, + CallIsinstance = 153, + CallKwBoundMethod = 154, + CallKwNonPy = 155, + CallKwPy = 156, + CallLen = 157, + CallListAppend = 158, + CallMethodDescriptorFast = 159, + CallMethodDescriptorFastWithKeywords = 160, + CallMethodDescriptorNoargs = 161, + CallMethodDescriptorO = 162, + CallNonPyGeneral = 163, + CallPyExactArgs = 164, + CallPyGeneral = 165, + CallStr1 = 166, + CallTuple1 = 167, + CallType1 = 168, + CompareOpFloat = 169, + CompareOpInt = 170, + CompareOpStr = 171, + ContainsOpDict = 172, + ContainsOpSet = 173, + ForIterGen = 174, + ForIterList = 175, + ForIterRange = 176, + ForIterTuple = 177, + ForIterVirtual = 178, + GetIterSelf = 179, + GetIterVirtual = 180, + JumpBackwardJit = 181, + JumpBackwardNoJit = 182, + LoadAttrClass = 183, + LoadAttrClassWithMetaclassCheck = 184, + LoadAttrGetattributeOverridden = 185, + LoadAttrInstanceValue = 186, + LoadAttrMethodLazyDict = 187, + LoadAttrMethodNoDict = 188, + LoadAttrMethodWithValues = 189, + LoadAttrModule = 190, + LoadAttrNondescriptorNoDict = 191, + LoadAttrNondescriptorWithValues = 192, + LoadAttrProperty = 193, + LoadAttrSlot = 194, + LoadAttrWithHint = 195, + LoadGlobalBuiltin = 196, + LoadGlobalModule = 197, + LoadSuperAttrAttr = 198, + LoadSuperAttrMethod = 199, + ResumeCheck = 200, + ResumeCheckJit = 201, + SendAsyncGen = 202, + SendGen = 203, + SendVirtual = 204, + StoreAttrInstanceValue = 205, + StoreAttrSlot = 206, + StoreAttrWithHint = 207, + StoreSubscrDict = 208, + StoreSubscrListInt = 209, + ToBoolAlwaysTrue = 210, + ToBoolBool = 211, + ToBoolInt = 212, + ToBoolList = 213, + ToBoolNone = 214, + ToBoolStr = 215, + UnpackSequenceList = 216, + UnpackSequenceTuple = 217, + UnpackSequenceTwoTuple = 218, + BuildListFromArg = 219, + InstrumentedEndFor = 233, + InstrumentedPopIter = 234, + InstrumentedEndSend = 235, + InstrumentedForIter = 236, + InstrumentedInstruction = 237, + InstrumentedJumpForward = 238, + InstrumentedNotTaken = 239, + InstrumentedPopJumpIfTrue = 240, + InstrumentedPopJumpIfFalse = 241, + InstrumentedPopJumpIfNone = 242, + InstrumentedPopJumpIfNotNone = 243, + InstrumentedResume = 244, + InstrumentedReturnValue = 245, + InstrumentedYieldValue = 246, + InstrumentedEndAsyncFor = 247, + InstrumentedLoadSuperAttr = 248, + InstrumentedCall = 249, + InstrumentedCallKw = 250, + InstrumentedCallFunctionEx = 251, + InstrumentedJumpBackward = 252, + InstrumentedLine = 253, + EnterExecutor = 254, + TraceRecord = 255, } ); @@ -709,12 +717,12 @@ define_opcodes!( JumpIfFalse { delta: Arg } = 258, JumpIfTrue { delta: Arg } = 259, JumpNoInterrupt { delta: Arg } = 260, - LoadClosure { i: Arg } = 261, + LoadClosure { i: Arg } = 261, PopBlock = 262, SetupCleanup { delta: Arg } = 263, SetupFinally { delta: Arg } = 264, SetupWith { delta: Arg } = 265, - StoreFastMaybeNull { var_num: Arg } = 266, + StoreFastMaybeNull { var_num: Arg } = 266, } ); @@ -1427,8 +1435,6 @@ mod tests { #[test] fn const_flags_match_cpython_opcode_metadata() { assert!(Opcode::LoadConst.has_const()); - assert!(Opcode::LoadConstImmortal.has_const()); - assert!(Opcode::LoadConstMortal.has_const()); assert!(!Opcode::LoadSmallInt.has_const()); assert!(!Opcode::Nop.has_const()); @@ -1438,8 +1444,8 @@ mod tests { #[test] fn stack_effects_match_cpython_opcode_metadata() { - assert_eq!(Opcode::ForIter.stack_effect_info(0).popped(), 1); - assert_eq!(Opcode::ForIter.stack_effect_info(0).pushed(), 2); + assert_eq!(Opcode::ForIter.stack_effect_info(0).popped(), 2); + assert_eq!(Opcode::ForIter.stack_effect_info(0).pushed(), 3); assert_eq!(Opcode::ForIter.stack_effect(0), 1); assert_eq!(Opcode::ForIter.stack_effect_jump(0), 1); @@ -1482,8 +1488,7 @@ mod tests { pub(super) const fn deopt(op: Opcode) -> Option { Some(match op { - Opcode::ResumeCheck => Opcode::Resume, - Opcode::LoadConstMortal | Opcode::LoadConstImmortal => Opcode::LoadConst, + Opcode::ResumeCheck | Opcode::ResumeCheckJit => Opcode::Resume, Opcode::ToBoolAlwaysTrue | Opcode::ToBoolBool | Opcode::ToBoolInt @@ -1501,12 +1506,13 @@ mod tests { | Opcode::BinaryOpSubscrListSlice | Opcode::BinaryOpSubscrTupleInt | Opcode::BinaryOpSubscrStrInt + | Opcode::BinaryOpSubscrUstrInt | Opcode::BinaryOpSubscrDict | Opcode::BinaryOpSubscrGetitem | Opcode::BinaryOpExtend | Opcode::BinaryOpInplaceAddUnicode => Opcode::BinaryOp, Opcode::StoreSubscrDict | Opcode::StoreSubscrListInt => Opcode::StoreSubscr, - Opcode::SendGen => Opcode::Send, + Opcode::SendGen | Opcode::SendAsyncGen | Opcode::SendVirtual => Opcode::Send, Opcode::UnpackSequenceTwoTuple | Opcode::UnpackSequenceTuple | Opcode::UnpackSequenceList => Opcode::UnpackSequence, @@ -1536,7 +1542,9 @@ mod tests { Opcode::ForIterList | Opcode::ForIterTuple | Opcode::ForIterRange - | Opcode::ForIterGen => Opcode::ForIter, + | Opcode::ForIterGen + | Opcode::ForIterVirtual => Opcode::ForIter, + Opcode::GetIterSelf | Opcode::GetIterVirtual => Opcode::GetIter, Opcode::CallBoundMethodExactArgs | Opcode::CallPyExactArgs | Opcode::CallType1 @@ -1560,6 +1568,7 @@ mod tests { Opcode::CallKwBoundMethod | Opcode::CallKwPy | Opcode::CallKwNonPy => { Opcode::CallKw } + Opcode::CallExPy | Opcode::CallExNonPyGeneral => Opcode::CallFunctionEx, _ => return None, }) } @@ -1576,6 +1585,7 @@ mod tests { pub(super) const fn cache_entries(op: Opcode) -> usize { match deoptimize(op) { + Opcode::Resume | Opcode::GetIter | Opcode::CallFunctionEx => 1, Opcode::StoreSubscr => 1, Opcode::ToBool => 3, Opcode::BinaryOp => 5, diff --git a/crates/compiler-core/src/bytecode/oparg.rs b/crates/compiler-core/src/bytecode/oparg.rs index 8f706003091..b66a2e7f45e 100644 --- a/crates/compiler-core/src/bytecode/oparg.rs +++ b/crates/compiler-core/src/bytecode/oparg.rs @@ -342,7 +342,10 @@ oparg_enum!( } ); -pub type NameIdx = u32; +/// Values used in the oparg for `GET_ITER`. +pub const GET_ITER_YIELD_FROM: u32 = 1; +pub const GET_ITER_YIELD_FROM_NO_CHECK: u32 = 2; +pub const GET_ITER_YIELD_FROM_CORO_CHECK: u32 = 3; impl OpArgType for u32 {} @@ -756,6 +759,16 @@ oparg_enum!( BuiltinList = (5, "list"), /// Built-in `set` type BuiltinSet = (6, "set"), + /// The None singleton. + None = (7, "None"), + /// The empty string. + EmptyStr = (8, "empty string"), + /// The true singleton. + True = (9, "True"), + /// The false singleton. + False = (10, "False"), + /// Integer minus one. + MinusOne = (11, "-1"), } ); @@ -876,6 +889,12 @@ newtype_oparg!( pub struct VarNums(u32) ); +newtype_oparg!( + #[derive(Clone, Copy)] + #[repr(transparent)] + pub struct NameIdx(u32) +); + newtype_oparg!( #[derive(Clone, Copy)] #[repr(transparent)] @@ -888,6 +907,18 @@ newtype_oparg!( pub struct LoadSuperAttr(u32) ); +newtype_oparg!( + #[derive(Clone, Copy)] + #[repr(transparent)] + pub struct LoadGlobal(u32) +); + +newtype_oparg!( + #[derive(Clone, Copy)] + #[repr(transparent)] + pub struct ImportName(u32) +); + newtype_oparg!( #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, PartialOrd)] #[repr(transparent)] @@ -906,11 +937,11 @@ newtype_oparg!( ); impl ResumeContext { - /// [CPython `RESUME_OPARG_LOCATION_MASK`](https://github.com/python/cpython/blob/v3.14.3/Include/internal/pycore_opcode_utils.h#L84) - pub const LOCATION_MASK: u32 = 0x3; + /// [CPython `RESUME_OPARG_LOCATION_MASK`](https://github.com/python/cpython/blob/v3.15.0/Include/internal/pycore_opcode_utils.h#L92) + pub const LOCATION_MASK: u32 = 0x7; - /// [CPython `RESUME_OPARG_DEPTH1_MASK`](https://github.com/python/cpython/blob/v3.14.3/Include/internal/pycore_opcode_utils.h#L85) - pub const DEPTH1_MASK: u32 = 0x4; + /// [CPython `RESUME_OPARG_DEPTH1_MASK`](https://github.com/python/cpython/blob/v3.15.0/Include/internal/pycore_opcode_utils.h#L93) + pub const DEPTH1_MASK: u32 = 0x8; #[must_use] pub const fn new(location: ResumeLocation, is_exception_depth1: bool) -> Self { @@ -926,8 +957,8 @@ impl ResumeContext { /// Resume location is determined by [`Self::LOCATION_MASK`]. #[must_use] pub fn location(&self) -> ResumeLocation { - // SAFETY: The mask should return a value that is in range. - unsafe { ResumeLocation::try_from(self.as_u32() & Self::LOCATION_MASK).unwrap_unchecked() } + ResumeLocation::try_from(self.as_u32() & Self::LOCATION_MASK) + .expect("invalid RESUME location") } /// True if the bit at [`Self::DEPTH1_MASK`] is on. @@ -947,6 +978,9 @@ pub enum ResumeLocation { AfterYieldFrom, /// After an `await` expression. AfterAwait, + /// Start of a generator expression, before its outermost iterator is + /// acquired and the generator is created. + AtGenExprStart, } impl From for ResumeContext { @@ -964,6 +998,7 @@ impl TryFrom for ResumeLocation { 1 => Self::AfterYield, 2 => Self::AfterYieldFrom, 3 => Self::AfterAwait, + 4 => Self::AtGenExprStart, _ => return Err(Self::Error::InvalidBytecode), }) } @@ -977,6 +1012,7 @@ impl ResumeLocation { Self::AfterYield => 1, Self::AfterYieldFrom => 2, Self::AfterAwait => 3, + Self::AtGenExprStart => 4, } } @@ -1017,13 +1053,13 @@ impl VarNums { impl LoadAttr { #[must_use] - pub const fn new(name_idx: u32, is_method: bool) -> Self { - Self::from_u32((name_idx << 1) | (is_method as u32)) + pub const fn new(name_idx: NameIdx, is_method: bool) -> Self { + Self::from_u32((name_idx.as_u32() << 1) | (is_method as u32)) } #[must_use] - pub const fn name_idx(self) -> u32 { - self.0 >> 1 + pub const fn name_idx(self) -> NameIdx { + NameIdx::from_u32(self.0 >> 1) } #[must_use] @@ -1034,13 +1070,15 @@ impl LoadAttr { impl LoadSuperAttr { #[must_use] - pub const fn new(name_idx: u32, is_load_method: bool, has_class: bool) -> Self { - Self::from_u32((name_idx << 2) | (is_load_method as u32) | ((has_class as u32) << 1)) + pub const fn new(name_idx: NameIdx, is_load_method: bool, has_class: bool) -> Self { + Self::from_u32( + (name_idx.as_u32() << 2) | (is_load_method as u32) | ((has_class as u32) << 1), + ) } #[must_use] - pub const fn name_idx(self) -> u32 { - self.0 >> 2 + pub const fn name_idx(self) -> NameIdx { + NameIdx::from_u32(self.0 >> 2) } #[must_use] @@ -1053,3 +1091,37 @@ impl LoadSuperAttr { (self.0 & 2) == 2 } } + +impl LoadGlobal { + #[must_use] + pub const fn new(name_idx: NameIdx, push_null: bool) -> Self { + Self::from_u32((name_idx.as_u32() << 1) | (push_null as u32)) + } + + #[must_use] + pub const fn name_idx(self) -> NameIdx { + NameIdx::from_u32(self.0 >> 1) + } + + #[must_use] + pub const fn push_null(self) -> bool { + (self.0 & 1) == 1 + } +} + +impl ImportName { + #[must_use] + pub const fn new(name_idx: NameIdx, flags: u32) -> Self { + Self::from_u32((name_idx.as_u32() << 2) | flags) + } + + #[must_use] + pub const fn name_idx(self) -> NameIdx { + NameIdx::from_u32(self.0 >> 2) + } + + #[must_use] + pub const fn flags(self) -> u32 { + self.0 & 3 + } +} diff --git a/crates/compiler-core/src/bytecode/opcode_metadata.rs b/crates/compiler-core/src/bytecode/opcode_metadata.rs index ca23e3c9e02..b264639fda7 100644 --- a/crates/compiler-core/src/bytecode/opcode_metadata.rs +++ b/crates/compiler-core/src/bytecode/opcode_metadata.rs @@ -15,15 +15,15 @@ impl super::Opcode { #[inline] pub const fn cache_entries(self) -> usize { const CACHE_ENTRIES: [u8; 256] = [ - 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 1, 1, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, - 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, 3, - 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 4, 4, 1, 1, 0, 1, 4, 4, 4, 1, 1, - 3, 3, 3, 3, 3, 3, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 3, 3, 0, 1, 0, 0, + 0, 0, 0, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1, 3, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 3, 1, 1, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 9, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 4, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, + 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 3, + 3, 3, 3, 3, 3, 3, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 4, 1, 1, 1, 1, 1, + 1, 1, 4, 4, 4, 1, 1, 3, 3, 3, 3, 3, 3, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 3, 3, 1, 1, 0, 0, 0, ]; CACHE_ENTRIES[self.as_numeric() as usize] as usize @@ -176,6 +176,7 @@ impl super::Opcode { Some(super::Opcode::BinaryOp), Some(super::Opcode::BinaryOp), Some(super::Opcode::BinaryOp), + Some(super::Opcode::BinaryOp), Some(super::Opcode::Call), Some(super::Opcode::Call), Some(super::Opcode::Call), @@ -183,6 +184,8 @@ impl super::Opcode { Some(super::Opcode::Call), Some(super::Opcode::Call), Some(super::Opcode::Call), + Some(super::Opcode::CallFunctionEx), + Some(super::Opcode::CallFunctionEx), Some(super::Opcode::Call), Some(super::Opcode::CallKw), Some(super::Opcode::CallKw), @@ -208,6 +211,9 @@ impl super::Opcode { Some(super::Opcode::ForIter), Some(super::Opcode::ForIter), Some(super::Opcode::ForIter), + Some(super::Opcode::ForIter), + Some(super::Opcode::GetIter), + Some(super::Opcode::GetIter), Some(super::Opcode::JumpBackward), Some(super::Opcode::JumpBackward), Some(super::Opcode::LoadAttr), @@ -223,13 +229,14 @@ impl super::Opcode { Some(super::Opcode::LoadAttr), Some(super::Opcode::LoadAttr), Some(super::Opcode::LoadAttr), - Some(super::Opcode::LoadConst), - Some(super::Opcode::LoadConst), Some(super::Opcode::LoadGlobal), Some(super::Opcode::LoadGlobal), Some(super::Opcode::LoadSuperAttr), Some(super::Opcode::LoadSuperAttr), Some(super::Opcode::Resume), + Some(super::Opcode::Resume), + Some(super::Opcode::Send), + Some(super::Opcode::Send), Some(super::Opcode::Send), Some(super::Opcode::StoreAttr), Some(super::Opcode::StoreAttr), @@ -282,13 +289,6 @@ impl super::Opcode { None, None, None, - None, - None, - None, - None, - None, - None, - None, ]; DEOPT[self.as_numeric() as usize] @@ -327,6 +327,7 @@ impl super::Opcode { | Self::ExtendedArg | Self::ForIter | Self::GetAwaitable + | Self::GetIter | Self::ImportFrom | Self::ImportName | Self::IsOp @@ -384,7 +385,7 @@ impl super::Opcode { | Self::CallBuiltinFast | Self::CallBuiltinFastWithKeywords | Self::CallBuiltinO - | Self::CallIsinstance + | Self::CallExPy | Self::CallKwBoundMethod | Self::CallKwNonPy | Self::CallKwPy @@ -408,6 +409,7 @@ impl super::Opcode { | Self::ForIterList | Self::ForIterRange | Self::ForIterTuple + | Self::ForIterVirtual | Self::JumpBackwardJit | Self::JumpBackwardNoJit | Self::LoadAttrClass @@ -423,13 +425,14 @@ impl super::Opcode { | Self::LoadAttrProperty | Self::LoadAttrSlot | Self::LoadAttrWithHint - | Self::LoadConstImmortal - | Self::LoadConstMortal | Self::LoadGlobalBuiltin | Self::LoadGlobalModule | Self::LoadSuperAttrAttr | Self::LoadSuperAttrMethod + | Self::ResumeCheckJit + | Self::SendAsyncGen | Self::SendGen + | Self::SendVirtual | Self::StoreAttrWithHint | Self::UnpackSequenceList | Self::UnpackSequenceTuple @@ -448,16 +451,14 @@ impl super::Opcode { | Self::InstrumentedCallKw | Self::InstrumentedJumpBackward | Self::EnterExecutor + | Self::TraceRecord ) } /// Does this opcode have 'HAS_CONST_FLAG' set. #[must_use] pub const fn has_const(self) -> bool { - matches!( - self, - Self::LoadConst | Self::LoadConstImmortal | Self::LoadConstMortal - ) + matches!(self, Self::LoadConst) } /// Does this opcode have 'HAS_EVAL_BREAK_FLAG' set. @@ -473,6 +474,7 @@ impl super::Opcode { | Self::CallBuiltinFast | Self::CallBuiltinFastWithKeywords | Self::CallBuiltinO + | Self::CallExNonPyGeneral | Self::CallKwNonPy | Self::CallMethodDescriptorFast | Self::CallMethodDescriptorFastWithKeywords @@ -517,8 +519,11 @@ impl super::Opcode { | Self::ForIterList | Self::ForIterRange | Self::ForIterTuple + | Self::ForIterVirtual | Self::JumpBackwardJit | Self::JumpBackwardNoJit + | Self::SendAsyncGen + | Self::SendVirtual | Self::InstrumentedForIter | Self::InstrumentedEndAsyncFor ) @@ -609,23 +614,21 @@ impl super::Opcode { Self::Cache => (0, 0), Self::BinarySlice => (1, 3), Self::BuildTemplate => (1, 2), - Self::BinaryOpInplaceAddUnicode => (0, 2), + Self::BinaryOpInplaceAddUnicode => (1, 2), Self::CallFunctionEx => (1, 4), Self::CheckEgMatch => (2, 2), Self::CheckExcMatch => (2, 2), - Self::CleanupThrow => (2, 3), + Self::CleanupThrow => (3, 4), Self::DeleteSubscr => (0, 2), Self::EndFor => (0, 1), - Self::EndSend => (1, 2), + Self::EndSend => (1, 3), Self::ExitInitCheck => (0, 1), Self::FormatSimple => (1, 1), Self::FormatWithSpec => (1, 2), Self::GetAiter => (1, 1), Self::GetAnext => (2, 1), - Self::GetIter => (1, 1), - Self::Reserved => (0, 0), Self::GetLen => (2, 1), - Self::GetYieldFromIter => (1, 1), + Self::Reserved => (0, 0), Self::InterpreterExit => (0, 1), Self::LoadBuildClass => (1, 0), Self::LoadLocals => (1, 0), @@ -636,7 +639,7 @@ impl super::Opcode { Self::Nop => (0, 0), Self::NotTaken => (0, 0), Self::PopExcept => (0, 1), - Self::PopIter => (0, 1), + Self::PopIter => (0, 2), Self::PopTop => (0, 1), Self::PushExcInfo => (2, 1), Self::PushNull => (1, 0), @@ -676,8 +679,9 @@ impl super::Opcode { Self::DictUpdate => (1 + (oparg - 1), 2 + (oparg - 1)), Self::EndAsyncFor => (0, 2), Self::ExtendedArg => (0, 0), - Self::ForIter => (2, 1), + Self::ForIter => (3, 2), Self::GetAwaitable => (1, 1), + Self::GetIter => (2, 1), Self::ImportFrom => (2, 1), Self::ImportName => (1, 2), Self::IsOp => (1, 2), @@ -712,7 +716,7 @@ impl super::Opcode { Self::PopJumpIfTrue => (0, 1), Self::RaiseVarargs => (0, oparg), Self::Reraise => (oparg, 1 + oparg), - Self::Send => (2, 2), + Self::Send => (3, 3), Self::SetAdd => (1 + (oparg - 1), 2 + (oparg - 1)), Self::SetFunctionAttribute => (1, 2), Self::SetUpdate => (1 + (oparg - 1), 2 + (oparg - 1)), @@ -740,6 +744,7 @@ impl super::Opcode { Self::BinaryOpSubscrListSlice => (1, 2), Self::BinaryOpSubscrStrInt => (1, 2), Self::BinaryOpSubscrTupleInt => (1, 2), + Self::BinaryOpSubscrUstrInt => (1, 2), Self::BinaryOpSubtractFloat => (1, 2), Self::BinaryOpSubtractInt => (1, 2), Self::CallAllocAndEnterInit => (0, 2 + oparg), @@ -749,12 +754,14 @@ impl super::Opcode { Self::CallBuiltinFast => (1, 2 + oparg), Self::CallBuiltinFastWithKeywords => (1, 2 + oparg), Self::CallBuiltinO => (1, 2 + oparg), - Self::CallIsinstance => (1, 2 + oparg), + Self::CallExNonPyGeneral => (1, 4), + Self::CallExPy => (0, 4), + Self::CallIsinstance => (1, 4), Self::CallKwBoundMethod => (0, 3 + oparg), Self::CallKwNonPy => (1, 3 + oparg), Self::CallKwPy => (0, 3 + oparg), Self::CallLen => (1, 3), - Self::CallListAppend => (0, 3), + Self::CallListAppend => (1, 3), Self::CallMethodDescriptorFast => (1, 2 + oparg), Self::CallMethodDescriptorFastWithKeywords => (1, 2 + oparg), Self::CallMethodDescriptorNoargs => (1, 2 + oparg), @@ -770,15 +777,18 @@ impl super::Opcode { Self::CompareOpStr => (1, 2), Self::ContainsOpDict => (1, 2), Self::ContainsOpSet => (1, 2), - Self::ForIterGen => (1, 1), - Self::ForIterList => (2, 1), - Self::ForIterRange => (2, 1), - Self::ForIterTuple => (2, 1), + Self::ForIterGen => (2, 2), + Self::ForIterList => (3, 2), + Self::ForIterRange => (3, 2), + Self::ForIterTuple => (3, 2), + Self::ForIterVirtual => (3, 2), + Self::GetIterSelf => (2, 1), + Self::GetIterVirtual => (2, 1), Self::JumpBackwardJit => (0, 0), Self::JumpBackwardNoJit => (0, 0), Self::LoadAttrClass => (1 + (oparg & 1), 1), Self::LoadAttrClassWithMetaclassCheck => (1 + (oparg & 1), 1), - Self::LoadAttrGetattributeOverridden => (1, 1), + Self::LoadAttrGetattributeOverridden => (0, 1), Self::LoadAttrInstanceValue => (1 + (oparg & 1), 1), Self::LoadAttrMethodLazyDict => (2, 1), Self::LoadAttrMethodNoDict => (2, 1), @@ -789,14 +799,15 @@ impl super::Opcode { Self::LoadAttrProperty => (0, 1), Self::LoadAttrSlot => (1 + (oparg & 1), 1), Self::LoadAttrWithHint => (1 + (oparg & 1), 1), - Self::LoadConstImmortal => (1, 0), - Self::LoadConstMortal => (1, 0), Self::LoadGlobalBuiltin => (1 + (oparg & 1), 0), Self::LoadGlobalModule => (1 + (oparg & 1), 0), Self::LoadSuperAttrAttr => (1, 3), Self::LoadSuperAttrMethod => (2, 3), Self::ResumeCheck => (0, 0), - Self::SendGen => (1, 2), + Self::ResumeCheckJit => (0, 0), + Self::SendAsyncGen => (3, 3), + Self::SendGen => (2, 3), + Self::SendVirtual => (3, 3), Self::StoreAttrInstanceValue => (0, 2), Self::StoreAttrSlot => (0, 2), Self::StoreAttrWithHint => (0, 2), @@ -811,10 +822,14 @@ impl super::Opcode { Self::UnpackSequenceList => (oparg, 1), Self::UnpackSequenceTuple => (oparg, 1), Self::UnpackSequenceTwoTuple => (2, 1), - Self::InstrumentedEndFor => (1, 2), - Self::InstrumentedPopIter => (0, 1), - Self::InstrumentedEndSend => (1, 2), - Self::InstrumentedForIter => (2, 1), + Self::BuildListFromArg => ( + 2, // TODO: Differs from CPython `None` + 1, // TODO: Differs from CPython `None` + ), + Self::InstrumentedEndFor => (2, 3), + Self::InstrumentedPopIter => (0, 2), + Self::InstrumentedEndSend => (1, 3), + Self::InstrumentedForIter => (3, 2), Self::InstrumentedInstruction => (0, 0), Self::InstrumentedJumpForward => (0, 0), Self::InstrumentedNotTaken => (0, 0), @@ -833,6 +848,7 @@ impl super::Opcode { Self::InstrumentedJumpBackward => (0, 0), Self::InstrumentedLine => (0, 0), Self::EnterExecutor => (0, 0), + Self::TraceRecord => (0, 0), }; debug_assert!(u32::try_from(pushed).is_ok()); diff --git a/crates/compiler-core/src/lib.rs b/crates/compiler-core/src/lib.rs index 8fe1146e514..ab531e150ce 100644 --- a/crates/compiler-core/src/lib.rs +++ b/crates/compiler-core/src/lib.rs @@ -9,9 +9,13 @@ pub mod bytecode; pub mod frozen; pub mod marshal; mod mode; +mod source; +mod source_location; pub mod varint; pub use mode::Mode; +pub use source::normalize_newlines; +pub use source_location::{AstLocationError, AstLocations, SourceLocationRange}; pub use ruff_source_file::{ LineIndex, OneIndexed, PositionEncoding, SourceFile, SourceFileBuilder, SourceLocation, diff --git a/crates/compiler-core/src/marshal.rs b/crates/compiler-core/src/marshal.rs index 1615c1d6a78..3358af46b27 100644 --- a/crates/compiler-core/src/marshal.rs +++ b/crates/compiler-core/src/marshal.rs @@ -5,7 +5,7 @@ use malachite_bigint::{BigInt, Sign}; use num_complex::Complex64; use rustpython_wtf8::Wtf8; -pub const FORMAT_VERSION: u32 = 5; +pub const FORMAT_VERSION: u32 = 6; #[derive(Clone, Copy, Debug)] pub enum MarshalError { @@ -84,6 +84,7 @@ enum Type { SmallTuple = b')', List = b'[', Dict = b'{', + FrozenDict = b'}', Code = b'c', Unicode = b'u', Set = b'<', @@ -120,6 +121,7 @@ impl TryFrom for Type { b')' => Self::SmallTuple, b'[' => Self::List, b'{' => Self::Dict, + b'}' => Self::FrozenDict, b'c' => Self::Code, b'u' => Self::Unicode, b'<' => Self::Set, @@ -466,13 +468,9 @@ fn read_marshal_name_tuple( rdr: &mut R, bag: &Bag, refs: &mut Vec>, -) -> Result::Name]>> { +) -> Result::Name>> { let names = read_marshal_str_vec(rdr, bag, refs)?; - Ok(names - .iter() - .map(|s| bag.make_name(s)) - .collect::>() - .into_boxed_slice()) + Ok(names.iter().map(|s| bag.make_name(s)).collect()) } /// Read a marshal tuple of constants. Shares the ref table with the @@ -554,6 +552,17 @@ fn read_const_value( Ok(value) } +/// Object-valued code fields as read from the stream (`r_object` TYPE_CODE). +pub struct CodeFields { + pub consts: V, + pub qualname: V, + pub names: V, + pub localsplusnames: V, + pub localspluskinds: V, + pub linetable: V, + pub exceptiontable: V, +} + pub trait MarshalBag: Copy { type Value: Clone; type ConstantBag: ConstantBag; @@ -580,23 +589,14 @@ pub trait MarshalBag: Copy { fn make_tuple(&self, elements: impl Iterator) -> Self::Value; + /// Construct a code object. `fields` holds the objects read for the + /// object-valued fields that `code` was decoded from. fn make_code( &self, code: CodeObject<::Constant>, + fields: CodeFields, ) -> Result; - /// Construct a runtime code object while retaining the exact values read - /// from ``co_consts``. Compiler bags ignore this second channel; runtime - /// bags use it for marshalable values (lists, dicts, sets, recursive - /// containers) that their compiler constant representation cannot hold. - fn make_code_with_constants( - &self, - code: CodeObject<::Constant>, - _constants: Vec, - ) -> Result { - self.make_code(code) - } - /// Decode the public `co_code` byte string into the execution-oriented /// instruction storage. /// @@ -608,22 +608,6 @@ pub trait MarshalBag: Copy { CodeUnits::try_from(code_bytes) } - /// Construct a runtime code object while retaining both its exact public - /// `co_code` bytes and the exact values read from `co_consts`. - /// - /// The default ignores the redundant byte spelling because ordinary - /// compiler code is represented losslessly by `CodeUnits`. Runtime bags - /// that accepted otherwise unrepresentable opcode bytes in - /// [`MarshalBag::code_units_from_bytes`] can preserve them here. - fn make_code_with_constants_and_bytes( - &self, - code: CodeObject<::Constant>, - constants: Vec, - _code_bytes: Vec, - ) -> Result { - self.make_code_with_constants(code, constants) - } - fn make_stop_iter(&self) -> Result; fn make_list(&self, it: impl Iterator) -> Result; @@ -637,6 +621,10 @@ pub trait MarshalBag: Copy { it: impl Iterator, ) -> Result; + fn freeze_dict(&self, _dict: Self::Value) -> Result { + Err(MarshalError::BadType) + } + /// Install partially-built containers in the marshal reference table /// before reading their children, as CPython's `r_object()` does. /// Runtime bags can opt in; constant bags retain collect-then-construct. @@ -786,6 +774,7 @@ impl MarshalBag for Bag { fn make_code( &self, code: CodeObject<::Constant>, + _fields: CodeFields, ) -> Result { Ok(self.make_code(code)) } @@ -958,17 +947,20 @@ fn deserialize_code_value_inner( .into_iter() .collect(); - let read_strings = - |rdr: &mut R, refs: &mut Vec>| -> Result> { - let tuple = deserialize_value_depth(rdr, bag, child_depth, refs)?; - bag.tuple_elements_from_value(&tuple) - .ok_or(MarshalError::BadType)? - .iter() - .map(|value| bag.str_from_value(value).ok_or(MarshalError::BadType)) - .collect() - }; - let names_raw = read_strings(rdr, refs)?; - let localsplusnames = read_strings(rdr, refs)?; + let read_strings = |rdr: &mut R, + refs: &mut Vec>| + -> Result<(Bag::Value, Vec)> { + let tuple = deserialize_value_depth(rdr, bag, child_depth, refs)?; + let names = bag + .tuple_elements_from_value(&tuple) + .ok_or(MarshalError::BadType)? + .iter() + .map(|value| bag.str_from_value(value).ok_or(MarshalError::BadType)) + .collect::>>()?; + Ok((tuple, names)) + }; + let (names_value, names_raw) = read_strings(rdr, refs)?; + let (localsplusnames_value, localsplusnames) = read_strings(rdr, refs)?; let kinds_value = deserialize_value_depth(rdr, bag, child_depth, refs)?; let localspluskinds = bag @@ -982,7 +974,10 @@ fn deserialize_code_value_inner( }; let source_path_raw = read_string(rdr, refs)?; let obj_name_raw = read_string(rdr, refs)?; - let qualname_raw = read_string(rdr, refs)?; + let qualname_value = deserialize_value_depth(rdr, bag, child_depth, refs)?; + let qualname_raw = bag + .str_from_value(&qualname_value) + .ok_or(MarshalError::BadType)?; let first_line_raw = rdr.read_u32()? as i32; let first_line_number = if first_line_raw > 0 { @@ -1050,7 +1045,18 @@ fn deserialize_code_value_inner( linetable, exceptiontable, }; - bag.make_code_with_constants_and_bytes(code, constant_values, code_bytes) + bag.make_code( + code, + CodeFields { + consts: consts_value, + qualname: qualname_value, + names: names_value, + localsplusnames: localsplusnames_value, + localspluskinds: kinds_value, + linetable: linetable_value, + exceptiontable: exceptiontable_value, + }, + ) } fn deserialize_value_typed( @@ -1197,22 +1203,30 @@ fn deserialize_value_typed( let it = (0..len).map(|_| deserialize_value_depth(rdr, bag, d, refs)); itertools::process_results(it, |it| bag.make_frozenset(it))?? } - Type::Dict => { + Type::Dict | Type::FrozenDict => { let d = depth - 1; - if let Some(index) = slot + // Immutable mappings are published only after all entries are read. + let frozen = matches!(typ, Type::FrozenDict); + if (frozen || slot.is_some()) && let Some(dict) = bag.make_dict_placeholder() { - refs[index] = Some(dict.clone()); + if !frozen && let Some(index) = slot { + refs[index] = Some(dict.clone()); + } loop { let raw = read_object_type(rdr)?; if raw & !FLAG_REF == b'0' { break; } let key = deserialize_value_after_header(rdr, bag, d, refs, raw)?; - let value = deserialize_value_depth(rdr, bag, d, refs)?; + let raw = read_object_type(rdr)?; + if raw & !FLAG_REF == b'0' { + break; + } + let value = deserialize_value_after_header(rdr, bag, d, refs, raw)?; bag.insert_dict_item(&dict, key, value)?; } - dict + if frozen { bag.freeze_dict(dict)? } else { dict } } else { let mut pairs = Vec::new(); loop { @@ -1221,10 +1235,15 @@ fn deserialize_value_typed( break; } let key = deserialize_value_after_header(rdr, bag, d, refs, raw)?; - let value = deserialize_value_depth(rdr, bag, d, refs)?; + let raw = read_object_type(rdr)?; + if raw & !FLAG_REF == b'0' { + break; + } + let value = deserialize_value_after_header(rdr, bag, d, refs, raw)?; pairs.push((key, value)); } - bag.make_dict(pairs.into_iter())? + let dict = bag.make_dict(pairs.into_iter())?; + if frozen { bag.freeze_dict(dict)? } else { dict } } } Type::Bytes => { @@ -1268,6 +1287,7 @@ pub enum DumpableValue<'a, D: Dumpable> { Set(&'a [D]), Frozenset(&'a [D]), Dict(&'a [(D, D)]), + Frozendict(&'a [(D, D)]), Slice(&'a D, &'a D, &'a D), } @@ -1439,8 +1459,13 @@ pub fn serialize_value( val.with_dump(|val| serialize_value(buf, val))?? } } - DumpableValue::Dict(d) => { - buf.write_u8(Type::Dict as u8); + DumpableValue::Dict(d) | DumpableValue::Frozendict(d) => { + let typ = if matches!(constant, DumpableValue::Frozendict(_)) { + Type::FrozenDict + } else { + Type::Dict + }; + buf.write_u8(typ as u8); for (k, v) in d { k.with_dump(|val| serialize_value(buf, val))??; v.with_dump(|val| serialize_value(buf, val))??; @@ -1501,7 +1526,7 @@ pub fn serialize_code_with( } // 8: co_names (tuple of strings) - write_marshal_name_tuple(buf, &code.names); + write_marshal_name_tuple(buf, code.names.as_slice()); // 9: co_localsplusnames — varnames ++ cell_only ++ freevars let cell_only_names: Vec<&str> = code @@ -1918,7 +1943,7 @@ mod tests { assert_eq!(code.arg_count, 0); assert_eq!(code.max_stackdepth, 1); assert_eq!(code.names.len(), 1); - assert_eq!(code.names[0].as_str(), "x"); + assert_eq!(code.names.as_slice()[0].as_str(), "x"); assert_eq!(code.constants.len(), 2); // (1, None) let consts: &[ConstantData] = &code.constants; @@ -1943,8 +1968,8 @@ mod tests { let code = decode_code(hex); assert_eq!(code.obj_name.as_str(), ""); assert_eq!(code.names.len(), 2); - assert_eq!(code.names[0].as_str(), "add"); - assert_eq!(code.names[1].as_str(), "GREETING"); + assert_eq!(code.names.as_slice()[0].as_str(), "add"); + assert_eq!(code.names.as_slice()[1].as_str(), "GREETING"); assert_eq!(code.constants.len(), 3); // Inner code, "hello", None let consts: &[ConstantData] = &code.constants; @@ -1984,7 +2009,7 @@ mod tests { assert_eq!(code.qualname.as_str(), ""); assert_eq!(code.source_path.as_str(), ""); assert_eq!(code.names.len(), 1); - assert_eq!(code.names[0].as_str(), "x"); + assert_eq!(code.names.as_slice()[0].as_str(), "x"); assert_eq!(code.constants.len(), 2); } } diff --git a/crates/compiler-core/src/source.rs b/crates/compiler-core/src/source.rs new file mode 100644 index 00000000000..82476928c2f --- /dev/null +++ b/crates/compiler-core/src/source.rs @@ -0,0 +1,43 @@ +use alloc::{borrow::Cow, string::String}; + +/// Translate physical source line endings before tokenization, including those +/// inside literals, as CPython's `_PyTokenizer_translate_newlines` does. +#[must_use] +pub fn normalize_newlines(source: &str) -> Cow<'_, str> { + let Some(first_cr) = source.find('\r') else { + return Cow::Borrowed(source); + }; + let mut normalized = String::with_capacity(source.len()); + normalized.push_str(&source[..first_cr]); + let mut rest = &source[first_cr..]; + while let Some(cr) = rest.find('\r') { + normalized.push_str(&rest[..cr]); + normalized.push('\n'); + rest = &rest[cr + 1..]; + if let Some(after_lf) = rest.strip_prefix('\n') { + rest = after_lf; + } + } + normalized.push_str(rest); + Cow::Owned(normalized) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn borrow_lf_source() { + let source = "print('한글')\n"; + assert!(matches!(normalize_newlines(source), Cow::Borrowed(s) if s == source)); + } + + #[test] + fn physical_line_endings() { + assert_eq!( + normalize_newlines("a\r\nb\rc\n\rd\r\r\n"), + "a\nb\nc\n\nd\n\n" + ); + assert_eq!(normalize_newlines("'\\r'\r"), "'\\r'\n"); + } +} diff --git a/crates/compiler-core/src/source_location.rs b/crates/compiler-core/src/source_location.rs new file mode 100644 index 00000000000..ca7d301c695 --- /dev/null +++ b/crates/compiler-core/src/source_location.rs @@ -0,0 +1,78 @@ +/// A Python source range with signed line and column coordinates. +/// +/// Unlike a parser text range, this preserves absent coordinates (negative +/// values), as well as line zero used by synthetic RESUME instructions. +/// Columns are zero-based; positive line numbers are one-based. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SourceLocationRange { + pub line: i32, + pub end_line: i32, + pub col: i32, + pub end_col: i32, +} + +/// Location metadata shared by AST conversion and code generation. +/// +/// Numeric IDs occupy Ruff's top-level node identity range. Keeping the store +/// independent of Ruff allows AST-only VM builds without the codegen crate. +#[derive(Default, Debug)] +pub struct AstLocations { + locations: alloc::collections::BTreeMap, + next_index: u32, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AstLocationError { + ConflictingLocation, + ExhaustedNodeIdentities, + CoordinateOverflow, +} + +impl AstLocations { + // Ruff reserves the upper two bits for sub-AST levels and sentinel IDs. + pub const MAX_ID: u32 = (1 << 30) - 1; + + pub fn allocate( + &mut self, + location: Option, + ) -> Result { + if self.next_index > Self::MAX_ID { + return Err(AstLocationError::ExhaustedNodeIdentities); + } + let id = self.next_index; + self.next_index = self + .next_index + .checked_add(1) + .ok_or(AstLocationError::ExhaustedNodeIdentities)?; + if let Some(location) = location { + self.insert(id, location)?; + } + Ok(id) + } + + /// An inherited identity may be shared only with identical coordinates. + pub fn insert( + &mut self, + id: u32, + location: SourceLocationRange, + ) -> Result<(), AstLocationError> { + if id > Self::MAX_ID { + return Err(AstLocationError::ExhaustedNodeIdentities); + } + if let Some(previous) = self.locations.get(&id) { + return if *previous == location { + Ok(()) + } else { + Err(AstLocationError::ConflictingLocation) + }; + } + self.locations.insert(id, location); + self.next_index = self.next_index.max(id + 1); + Ok(()) + } + + #[must_use] + pub fn get(&self, id: u32) -> Option { + self.locations.get(&id).copied() + } +} diff --git a/crates/compiler/src/lib.rs b/crates/compiler/src/lib.rs index 534173d2c11..c0daadc9696 100644 --- a/crates/compiler/src/lib.rs +++ b/crates/compiler/src/lib.rs @@ -37,6 +37,76 @@ pub struct ParseError { pub is_unclosed_bracket: bool, /// Set when a string is still open at EOF and more input could close it. pub is_unclosed_string: bool, + /// Set when the parser failed on a token made up at the end of the input. + pub eof_token: Option>, +} + +/// The tokenizer state at the end of the input, where it makes up the +/// NEWLINE, DEDENT and ENDMARKER tokens that close it. Those tokens have no +/// column, so an error on one of them is placed where the tokenizer stopped. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EofToken { + /// `tok->lineno`: the number of lines read, 0 for empty input. + pub lineno: usize, + /// The last line read, which the tokenizer stopped at the end of. + pub line: String, + /// Where the error on the token is raised from. + pub raised_at: EofErrorLocation, +} + +/// Where an error on a token made up at the end of the input is placed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EofErrorLocation { + /// Where the tokenizer stopped, as `_PyPegen_raise_error` places an error + /// on a token without a column. + Tokenizer, + /// At the token itself, as the generic syntax error and a missing forced + /// token are, so its columns are 0. + Token, + /// From the token to where the tokenizer stopped, as + /// `RAISE_SYNTAX_ERROR_STARTING_FROM` places it. + StartingFromToken, +} + +impl EofToken { + fn new(source: &str, mode: Mode, raised_at: EofErrorLocation) -> Self { + let lineno = source.split_inclusive('\n').count(); + let mut line = source + .split_inclusive('\n') + .next_back() + .unwrap_or_default() + .to_owned(); + // translate_newlines: exec input that does not end with a newline + // gets one. + if matches!(mode, Mode::Exec | Mode::BlockExpr) && !line.is_empty() && !line.ends_with('\n') + { + line.push('\n'); + } + Self { + lineno, + line, + raised_at, + } + } + + /// `SyntaxError.offset` + #[must_use] + pub fn offset(&self) -> usize { + match self.raised_at { + EofErrorLocation::Tokenizer => self.line.chars().count(), + EofErrorLocation::Token | EofErrorLocation::StartingFromToken => 0, + } + } + + /// `SyntaxError.end_offset` + #[must_use] + pub fn end_offset(&self) -> isize { + match self.raised_at { + EofErrorLocation::Tokenizer => -1, + EofErrorLocation::Token => 0, + EofErrorLocation::StartingFromToken => self.line.chars().count() as isize, + } + } } impl ::core::fmt::Display for ParseError { @@ -61,11 +131,34 @@ impl CompileError { mode: Mode, ) -> Self { let raw_location = error.location; + let at_eof_token = fails_at_eof_token(&error, source_file.source_text(), mode); let diagnostic = match cpython_parse_diagnostic_override(&error, source_file, mode) { Some(diagnostic) => diagnostic, - None => default_parse_diagnostic(error, source_file), + None => { + let is_unclosed_bracket = matches!( + error.error, + parser::ParseErrorType::Lexical(parser::LexicalErrorType::UnclosedBracket { + incomplete: true, + .. + }) + ); + let is_unclosed_string = + unclosed_string_is_continuable(&error, source_file.source_text(), mode); + let mut diagnostic = default_parse_diagnostic(error, source_file); + diagnostic.is_unclosed_bracket = is_unclosed_bracket; + diagnostic.is_unclosed_string = is_unclosed_string; + diagnostic + } }; + let eof_token = at_eof_token.then(|| { + let source = source_file.source_text(); + Box::new(EofToken::new( + source, + mode, + eof_error_location(&diagnostic.error), + )) + }); Self::Parse(ParseError { error: diagnostic.error, raw_location, @@ -74,6 +167,7 @@ impl CompileError { source_path: source_file.name().to_owned(), is_unclosed_bracket: diagnostic.is_unclosed_bracket, is_unclosed_string: diagnostic.is_unclosed_string, + eof_token, }) } @@ -89,8 +183,9 @@ impl CompileError { location, end_location, source_path: source_file.name().to_owned(), - is_unclosed_bracket: diagnostic.is_unclosed_bracket, - is_unclosed_string: diagnostic.is_unclosed_string, + is_unclosed_bracket: false, + is_unclosed_string: false, + eof_token: None, }) } @@ -103,8 +198,14 @@ impl CompileError { } #[must_use] - pub const fn python_location(&self) -> (usize, usize) { - if let Some(location) = self.location() { + pub fn python_location(&self) -> (usize, usize) { + if let Self::Parse(ParseError { + eof_token: Some(eof_token), + .. + }) = self + { + (eof_token.lineno, eof_token.offset()) + } else if let Some(location) = self.location() { (location.line.get(), location.character_offset.get()) } else { (0, 0) @@ -182,22 +283,6 @@ impl NormalizedParseDiagnostic { } } - fn other(source_file: &SourceFile, diagnostic: CpythonDiagnostic) -> Self { - let (location, end_location) = source_locations( - source_file, - diagnostic.range.start(), - diagnostic.range.end(), - ); - let mut diagnostic_out = Self::new( - parser::ParseErrorType::OtherError(diagnostic.message), - location, - end_location, - ); - diagnostic_out.is_unclosed_string = diagnostic.is_unclosed_string; - diagnostic_out.is_unclosed_bracket = diagnostic.is_unclosed_bracket; - diagnostic_out - } - const fn with_unclosed_bracket(mut self, is_unclosed_bracket: bool) -> Self { self.is_unclosed_bracket = is_unclosed_bracket; self @@ -212,8 +297,6 @@ impl NormalizedParseDiagnostic { struct CpythonDiagnostic { message: String, range: ruff_text_size::TextRange, - is_unclosed_string: bool, - is_unclosed_bracket: bool, } impl CpythonDiagnostic { @@ -228,66 +311,8 @@ impl CpythonDiagnostic { TextSize::new(start as u32), TextSize::new(end as u32), ), - is_unclosed_string: false, - is_unclosed_bracket: false, } } - - const fn with_unclosed_string(mut self) -> Self { - self.is_unclosed_string = true; - self - } - - const fn with_unclosed_bracket(mut self) -> Self { - self.is_unclosed_bracket = true; - self - } -} - -/// Lexer-class failures outrank print hints. Decode and f-string diagnostics -/// compete with lexer failures by offset, and an unterminated quote is only -/// a fallback when no decode/f-string diagnostic exists. Print is considered -/// against the final winner: a later 0x still beats print, but an f-string -/// that replaced that 0x must not hide an earlier print. A decode diagnostic -/// also suppresses an EOF unclosed opener. -#[derive(Clone, Copy, PartialEq, Eq)] -enum OverrideClass { - Lexer, - Decode, - Print, -} - -struct RankedOverride { - diagnostic: CpythonDiagnostic, - unclosed_bracket: bool, - class: OverrideClass, -} - -fn consider_override( - best: &mut Option, - diagnostic: CpythonDiagnostic, - class: OverrideClass, -) { - let unclosed_bracket = diagnostic.is_unclosed_bracket; - consider_ranked(best, diagnostic, unclosed_bracket, class); -} - -fn consider_ranked( - best: &mut Option, - diagnostic: CpythonDiagnostic, - unclosed_bracket: bool, - class: OverrideClass, -) { - if best - .as_ref() - .is_none_or(|current| diagnostic.range.start() < current.diagnostic.range.start()) - { - *best = Some(RankedOverride { - diagnostic, - unclosed_bracket, - class, - }); - } } fn cpython_parse_diagnostic_override( @@ -297,109 +322,42 @@ fn cpython_parse_diagnostic_override( ) -> Option { let source_text = source_file.source_text(); - macro_rules! source_error { - ($expr:expr) => { - if let Some(error) = $expr { - return Some(NormalizedParseDiagnostic::other(source_file, error)); - } - }; - } - - let mut earliest: Option = None; - if let Some(diagnostic) = invalid_number_literal_error(source_text) { - consider_override(&mut earliest, diagnostic, OverrideClass::Lexer); - } - if let Some(diagnostic) = incompatible_string_prefix_error(source_text) { - consider_override(&mut earliest, diagnostic, OverrideClass::Lexer); - } - if let Some(diagnostic) = non_printable_character_error(source_text) { - consider_override(&mut earliest, diagnostic, OverrideClass::Lexer); - } - let bracket = bracket_syntax_error(source_text); - if let Some(bracket) = bracket.as_ref() { - // Unclosed openers are reported at the opener and only become errors - // at EOF. A later token-time diagnostic (invalid number, prefix, …) - // must keep winning. Mismatched closers stay in the lexer-class - // positional ranking. - if !bracket.unclosed { - consider_ranked( - &mut earliest, - bracket.diagnostic.clone(), - false, - OverrideClass::Lexer, - ); - } - } - let mut saw_decode = false; - if let Some(diagnostic) = malformed_unicode_n_escape_error(source_text) { - saw_decode = true; - consider_override(&mut earliest, diagnostic, OverrideClass::Decode); - } - if let Some(diagnostic) = invalid_interpolated_string_error(source_text) { - saw_decode = true; - consider_override(&mut earliest, diagnostic, OverrideClass::Decode); - } - if let Some(diagnostic) = mixed_tstring_literal_error(error, source_text) { - saw_decode = true; - consider_override(&mut earliest, diagnostic, OverrideClass::Decode); - } - // A later ordinary unterminated quote is only a fallback. Format-spec - // newlines and empty fields are decode diagnostics and must keep winning. - let line_continuation = matches!( + let tokenizer_error = matches!( &error.error, - parser::ParseErrorType::Lexical(parser::LexicalErrorType::LineContinuationError) + parser::ParseErrorType::Lexical(lexical) if lexical.is_tokenizer_error() ); - if !saw_decode - && !line_continuation - && let Some(diagnostic) = unterminated_string_error(source_text, mode) - { - consider_override(&mut earliest, diagnostic, OverrideClass::Lexer); - } - // Indentation errors outrank a print/exec missing-parentheses rewrite. - let indent_error = matches!( - &error.error, - parser::ParseErrorType::Lexical(parser::LexicalErrorType::IndentationError) - | parser::ParseErrorType::UnexpectedIndentation - ) || expected_indented_block_error(error, source_text).is_some(); - if !indent_error - && earliest - .as_ref() - .is_none_or(|current| current.class != OverrideClass::Lexer) - && let Some(diagnostic) = invalid_legacy_statement_error(source_text) - { - consider_override(&mut earliest, diagnostic, OverrideClass::Print); - } - if !saw_decode - && earliest - .as_ref() - .is_none_or(|current| current.class == OverrideClass::Print) - && let Some(bracket) = bracket.filter(|bracket| bracket.unclosed) - { - consider_ranked( - &mut earliest, - bracket.diagnostic, - true, - OverrideClass::Lexer, - ); - } - if let Some(override_diag) = earliest { - return Some( - NormalizedParseDiagnostic::other(source_file, override_diag.diagnostic) - .with_unclosed_bracket(override_diag.unclosed_bracket), - ); - } - - if matches!( + let line_continuation = matches!( &error.error, parser::ParseErrorType::Lexical(parser::LexicalErrorType::LineContinuationError) - ) { + ); + if line_continuation { // exec input gets an implicit trailing newline, so a final `\` is a // continuation that then hits EOF (`E_EOF`). single/eval see `\` at // EOF as `E_LINECONT` instead. - let terminal_backslash = source_text.len().checked_sub(1); - if matches!(mode, Mode::Exec) - && terminal_backslash == Some(error.location.start().to_usize()) - { + if matches!(mode, Mode::Exec) && error.location.start().to_usize() == source_text.len() { + let source_with_newline = format!("{source_text}\n"); + let parsed = parser::parse_unchecked( + &source_with_newline, + parser::ParseOptions::from(parser::Mode::Module), + ); + if let Some(unclosed) = parsed.errors().first().filter(|first| { + matches!( + first.error, + parser::ParseErrorType::Lexical( + parser::LexicalErrorType::UnclosedBracket { .. } + ) + ) + }) { + let mut diagnostic = default_parse_diagnostic(unclosed.clone(), source_file); + diagnostic.is_unclosed_bracket = matches!( + unclosed.error, + parser::ParseErrorType::Lexical(parser::LexicalErrorType::UnclosedBracket { + incomplete: true, + .. + }) + ); + return Some(diagnostic); + } let loc = source_line_end_location(source_file, error.location.start()); return Some(NormalizedParseDiagnostic::new( parser::ParseErrorType::OtherError("unexpected EOF while parsing".to_owned()), @@ -407,136 +365,36 @@ fn cpython_parse_diagnostic_override( loc, )); } - let loc = source_location(source_file, error.location.start() + TextSize::from(1)); - return Some(NormalizedParseDiagnostic::new( - parser::ParseErrorType::OtherError( - "unexpected character after line continuation character".to_owned(), - ), - loc, - loc, - )); + return None; } - source_error!(unterminated_string_error(source_text, mode)); - source_error!(expected_indented_block_error(error, source_text)); - if matches!( &error.error, parser::ParseErrorType::Lexical(parser::LexicalErrorType::Eof) ) { return Some(eof_parse_diagnostic(error, source_file)); } - - source_error!(invalid_type_param_error(source_text)); - source_error!(invalid_comprehension_error(source_text)); - source_error!(invalid_parameter_star_annotation_error(source_text)); - source_error!(invalid_parameter_list_error(source_text)); - source_error!(invalid_call_argument_error(source_text)); - - if is_missing_comma_between_literals(error) { - let (loc, end_loc) = adjusted_error_locations(source_file, error.location); - let msg = "invalid syntax. Perhaps you forgot a comma?".into(); - return Some(NormalizedParseDiagnostic::new( - parser::ParseErrorType::OtherError(msg), - loc, - end_loc, - )); - } - - source_error!(invalid_dict_error(source_text)); - if !matches!(mode, Mode::Eval) { - source_error!(invalid_collection_assignment_error(source_text)); - } - source_error!(invalid_group_error(source_text)); - source_error!(invalid_def_type_params_error(source_text)); - source_error!(invalid_expression_error(source_text)); - source_error!(invalid_named_expression_error(source_text)); - // Assignment and other statements are not expressions. Eval keeps the - // generic parse error rather than a statement-target rewrite. - if !matches!(mode, Mode::Eval) { - source_error!(invalid_plain_assignment_error(source_text)); - source_error!(expression_assignment_error(source_text)); - source_error!(invalid_annotation_target_error(source_text)); - source_error!(invalid_assignment_target_error(source_text)); - source_error!(invalid_condition_assignment_error( - source_text, - error.location.start().to_usize() - )); - source_error!(invalid_augassign_target_error(source_text)); - source_error!(invalid_for_target_error(source_text)); - source_error!(invalid_with_target_error(source_text)); - source_error!(invalid_delete_target_error(source_text)); - source_error!(invalid_standalone_except_error(source_text)); - source_error!(invalid_import_statement_error(source_text)); - source_error!(invalid_import_target_error(source_text)); - source_error!(invalid_except_as_target_error(source_text)); - source_error!(invalid_match_mapping_rest_wildcard_error(source_text)); - source_error!(invalid_match_as_target_error(source_text)); - source_error!(invalid_for_if_clause_error(source_text)); - source_error!(invalid_if_expression_statement_error(source_text)); - source_error!(invalid_else_elif_error(source_text)); - source_error!(mixed_except_handlers_error(source_text)); - } - - if matches!( - &error.error, - parser::ParseErrorType::Lexical(parser::LexicalErrorType::InvalidByteLiteral) - ) && let Some((start, end)) = - bytes_literal_span(source_text, error.location.start().to_usize()) + if tokenizer_error + || matches!( + &error.error, + parser::ParseErrorType::ExpectedIndentedBlock { .. } + ) { - let (loc, end_loc) = source_locations( - source_file, - TextSize::new(start as u32), - TextSize::new(end as u32), - ); - return Some(NormalizedParseDiagnostic::new( - error.error.clone(), - loc, - end_loc, - )); - } - - if matches!( - &error.error, - parser::ParseErrorType::Lexical(parser::LexicalErrorType::IndentationError) - ) { - let end_loc = source_line_end_location(source_file, error.location.start()); - return Some(NormalizedParseDiagnostic::new( - error.error.clone(), - end_loc, - end_loc, - )); - } - - if matches!( - &error.error, - parser::ParseErrorType::InvalidAssignmentTarget - ) { - return Some(invalid_assignment_target_diagnostic(error, source_file)); - } - - if matches!( - &error.error, - parser::ParseErrorType::InvalidNamedAssignmentTarget - ) { - let (loc, end_loc) = adjusted_error_locations(source_file, error.location); - let target = source_file.source_text().slice(error.location); - let msg = format!("cannot use assignment expressions with {target}"); - return Some(NormalizedParseDiagnostic::new( - parser::ParseErrorType::OtherError(msg), - loc, - end_loc, - )); + return None; } // CPython's PEG parser collapses a bare "expected an expression" failure // into the generic "invalid syntax" message. rustpython-vm's `vm_new.rs` // does this same collapse for its own callers; rustpython-compiler has no - // vm dependency, so mirror it here. + // vm dependency, so mirror it here. CPython also uses the generic + // diagnostic when an indented match suite does not begin with a case. if matches!( &error.error, parser::ParseErrorType::ExpectedExpression | parser::ParseErrorType::UnexpectedExpressionToken + ) || matches!( + &error.error, + parser::ParseErrorType::OtherError(message) if message == "expected `case` block" ) { let (loc, end_loc) = adjusted_error_locations(source_file, error.location); return Some(NormalizedParseDiagnostic::new( @@ -549,6 +407,71 @@ fn cpython_parse_diagnostic_override( None } +/// Whether the parser fails on a token made up at the end of the input. +fn fails_at_eof_token(error: &parser::ParseError, source: &str, mode: Mode) -> bool { + let start = error.location.start().to_usize(); + match &error.error { + parser::ParseErrorType::Lexical(_) => false, + // `NEWLINE !INDENT` fails on the token after the newline, and the + // error is reported at the newline when only blank lines and comments + // follow it. + parser::ParseErrorType::ExpectedIndentedBlock { .. } => { + let end = error.location.end().to_usize(); + source + .get(start..end) + .is_some_and(|text| text.chars().all(|c| c.is_ascii_whitespace())) + && source.get(end..).is_some_and(is_blank_python_source) + } + _ if start < source.len() => false, + // Exec input gets a newline appended, which is a real NEWLINE token, + // so the error is at the end only when it stays there once the + // newline is added. + _ if matches!(mode, Mode::Exec | Mode::BlockExpr) + && !source.is_empty() + && !source.ends_with('\n') => + { + let source = format!("{source}\n"); + let parsed = + parser::parse_unchecked(&source, parser::ParseOptions::from(parser::Mode::Module)); + parsed + .errors() + .first() + .is_none_or(|error| error.location.start().to_usize() >= source.len()) + } + _ => true, + } +} + +/// Where the error is placed when the parser fails on a token made up at the +/// end of the input. +fn eof_error_location(error: &parser::ParseErrorType) -> EofErrorLocation { + match error { + // A `:` that is not forced is reported missing before the newline by an + // `invalid_*` rule. + parser::ParseErrorType::ExpectedToken { + expected: TokenKind::Colon, + found: TokenKind::Newline, + } => EofErrorLocation::Tokenizer, + parser::ParseErrorType::ExpectedToken { .. } + | parser::ParseErrorType::ExpectedForcedToken { .. } + | parser::ParseErrorType::ExpectedExpression + | parser::ParseErrorType::ExpectedIdentifier + | parser::ParseErrorType::UnexpectedExpressionToken + | parser::ParseErrorType::UnexpectedTokenAfterAsync(_) + | parser::ParseErrorType::EmptyDeleteTargets + | parser::ParseErrorType::EmptyGlobalNames + | parser::ParseErrorType::EmptyNonlocalNames + | parser::ParseErrorType::SimpleStatementsOnSameLine + | parser::ParseErrorType::SimpleAndCompoundStatementOnSameLine + | parser::ParseErrorType::InvalidStarredExpressionUsage => EofErrorLocation::Token, + parser::ParseErrorType::EmptyImportNames => EofErrorLocation::StartingFromToken, + parser::ParseErrorType::OtherError(message) if message == "invalid syntax" => { + EofErrorLocation::Token + } + _ => EofErrorLocation::Tokenizer, + } +} + fn eof_parse_diagnostic( error: &parser::ParseError, source_file: &SourceFile, @@ -569,48 +492,73 @@ fn eof_parse_diagnostic( } } -fn invalid_assignment_target_diagnostic( - error: &parser::ParseError, - source_file: &SourceFile, -) -> NormalizedParseDiagnostic { - let (loc, end_loc) = adjusted_error_locations(source_file, error.location); - let expr_str = source_file.source_text().slice(error.location); +/// Returns whether more input could still terminate the string that `error` reports as +/// unterminated. +/// +/// A string that reached the end of the source can continue, except a single-quoted f/t-string, +/// a single-quoted string in exec input whose implicit final newline ends it, and a string after +/// an assignment in eval input. +fn unclosed_string_is_continuable(error: &parser::ParseError, source: &str, mode: Mode) -> bool { + use parser::{InterpolatedStringErrorType, LexicalErrorType}; - let msg = parser::parse_expression(expr_str).map_or_else( - |_| match expr_str { - "yield" => "assignment to yield expression not possible".into(), - _ => format!("cannot assign to {expr_str}"), - }, - |parsed| match *parsed.syntax().body { - ast::Expr::Call(_) => "cannot assign to function call".into(), - ast::Expr::BinOp(_) => "cannot assign to expression".into(), - ast::Expr::If(_) => "cannot assign to conditional expression".into(), - ast::Expr::Generator(_) => "cannot assign to generator expression".into(), - ast::Expr::Yield(_) | ast::Expr::YieldFrom(_) => { - "cannot assign to yield expression here. Maybe you meant '==' instead of '='?" - .into() - } - ast::Expr::FString(_) => "invalid syntax".into(), - ast::Expr::StringLiteral(_) - | ast::Expr::BytesLiteral(_) - | ast::Expr::NumberLiteral(_) => { - "cannot assign to literal here. Maybe you meant '==' instead of '='?".into() - } - ast::Expr::EllipsisLiteral(_) => { - "cannot assign to ellipsis here. Maybe you meant '==' instead of '='?".into() - } - _ => format!("cannot assign to {expr_str}"), - }, - ); + let parser::ParseErrorType::Lexical(lexical) = &error.error else { + return false; + }; + let start = error.location.start().to_usize(); + let at_eof = match lexical { + LexicalErrorType::UnclosedStringError { + triple_quoted: true, + .. + } + | LexicalErrorType::FStringError( + InterpolatedStringErrorType::UnterminatedTripleQuotedString { .. }, + ) + | LexicalErrorType::TStringError( + InterpolatedStringErrorType::UnterminatedTripleQuotedString { .. }, + ) => true, + LexicalErrorType::UnclosedStringError { .. } => { + // Exec mode appends a newline, which only a final `\` can escape. + let rest = &source[start..]; + !has_unescaped_newline(rest) && (!matches!(mode, Mode::Exec) || rest.ends_with('\\')) + } + _ => false, + }; + at_eof && !(matches!(mode, Mode::Eval) && eval_has_assignment_before(source.as_bytes(), start)) +} - NormalizedParseDiagnostic::new(parser::ParseErrorType::OtherError(msg), loc, end_loc) +fn has_unescaped_newline(text: &str) -> bool { + let mut chars = text.chars(); + while let Some(c) = chars.next() { + match c { + '\\' => { + chars.next(); + } + '\n' | '\r' => return true, + _ => {} + } + } + false } fn default_parse_diagnostic( error: parser::ParseError, source_file: &SourceFile, ) -> NormalizedParseDiagnostic { - let (loc, end_loc) = adjusted_error_locations(source_file, error.location); + if let parser::ParseErrorType::MissingCommaAfterConcatenatedLiteral { + diagnostic_start, .. + } = &error.error + { + // Concatenation hints can have empty or reversed CPython diagnostic ranges. + let (location, end_location) = + source_locations(source_file, *diagnostic_start, error.location.end()); + return NormalizedParseDiagnostic::new(error.error, location, end_location); + } + let (loc, end_loc) = if matches!(error.error, parser::ParseErrorType::EmptyImportNames) { + // RAISE_SYNTAX_ERROR_STARTING_FROM the newline ends where it starts. + source_locations(source_file, error.location.start(), error.location.end()) + } else { + adjusted_error_locations(source_file, error.location) + }; NormalizedParseDiagnostic::new(error.error, loc, end_loc) } @@ -646,14 +594,6 @@ fn source_line_end_location(source_file: &SourceFile, offset: TextSize) -> Sourc } } -fn is_missing_comma_between_literals(error: &parser::ParseError) -> bool { - matches!( - &error.error, - parser::ParseErrorType::ExpectedToken { expected, found } - if matches!((expected, found), (TokenKind::Comma, TokenKind::Int)) - ) -} - fn is_ascii_identifier_char(byte: u8) -> bool { byte == b'_' || byte.is_ascii_alphanumeric() } @@ -675,668 +615,384 @@ fn identifier_continue_before(bytes: &[u8], index: usize) -> bool { .is_some_and(|ch| ch == '_' || ch.is_alphanumeric()) } -fn numeric_keyword_suffix(rest: &[u8]) -> bool { - rest.starts_with(b"and") - || rest.starts_with(b"else") - || rest.starts_with(b"for") - || rest.starts_with(b"if") - || rest.starts_with(b"in") - || rest.starts_with(b"is") - || rest.starts_with(b"or") - || rest.starts_with(b"not") -} - -fn consume_decimal_digits(bytes: &[u8], mut index: usize) -> usize { - while index < bytes.len() { - match bytes[index] { - b'0'..=b'9' => index += 1, - b'_' if bytes - .get(index + 1) - .is_some_and(|byte| byte.is_ascii_digit()) => - { - index += 2; - } - _ => break, - } +fn quoted_string_is_closed(bytes: &[u8], start: usize) -> bool { + let quote = bytes[start]; + let triple = bytes.get(start + 1) == Some("e) && bytes.get(start + 2) == Some("e); + let end = skip_quoted_string(bytes, start); + if triple { + end >= start + 6 + && bytes[end - 3] == quote + && bytes[end - 2] == quote + && bytes[end - 1] == quote + } else { + end > start + 1 && bytes[end - 1] == quote } - index } -fn consume_radix_digits(bytes: &[u8], mut index: usize, is_digit: impl Fn(u8) -> bool) -> usize { +fn skip_quoted_string(bytes: &[u8], mut index: usize) -> usize { + let quote = bytes[index]; + let triple = bytes.get(index + 1) == Some("e) && bytes.get(index + 2) == Some("e); + let quote_len = if triple { 3 } else { 1 }; + index += quote_len; while index < bytes.len() { - if is_digit(bytes[index]) { - index += 1; - } else if bytes.get(index) == Some(&b'_') - && bytes.get(index + 1).is_some_and(|&byte| is_digit(byte)) + if bytes[index] == b'\\' { + index = (index + 2).min(bytes.len()); + } else if triple + && bytes.get(index) == Some("e) + && bytes.get(index + 1) == Some("e) + && bytes.get(index + 2) == Some("e) { - index += 2; + return index + 3; + } else if !triple && bytes[index] == quote { + return index + 1; } else { - break; - } - } - index -} - -fn invalid_radix_literal_error( - bytes: &[u8], - start: usize, - kind: &'static str, - is_digit: impl Fn(u8) -> bool, -) -> Option<(String, usize)> { - let mut index = start + 2; - let mut has_digit = false; - loop { - let Some(&byte) = bytes.get(index) else { - return if has_digit { - None - } else { - Some((format!("invalid {kind} literal"), start + 1)) - }; - }; - if byte == b'_' { - let Some(&next) = bytes.get(index + 1) else { - return Some((format!("invalid {kind} literal"), index)); - }; - if is_digit(next) { - has_digit = true; - index += 2; - continue; - } - if next.is_ascii_digit() && matches!(kind, "binary" | "octal") { - return Some(( - format!("invalid digit '{}' in {kind} literal", next as char), - index + 1, - )); - } - return Some((format!("invalid {kind} literal"), index)); - } - if is_digit(byte) { - has_digit = true; index += 1; - continue; - } - if byte.is_ascii_digit() && matches!(kind, "binary" | "octal") { - return Some(( - format!("invalid digit '{}' in {kind} literal", byte as char), - index, - )); - } - if has_digit { - return None; } - return Some((format!("invalid {kind} literal"), start + 1)); } + index } -fn decimal_tail_error(bytes: &[u8], mut index: usize) -> Option { - loop { - while bytes.get(index).is_some_and(|byte| byte.is_ascii_digit()) { - index += 1; - } - if bytes.get(index) != Some(&b'_') { - return None; - } - let underscore = index; - index += 1; - if !bytes.get(index).is_some_and(|byte| byte.is_ascii_digit()) { - return Some(underscore); - } - } +fn starts_identifier(bytes: &[u8], index: usize, word: &[u8]) -> bool { + bytes.get(index..index + word.len()) == Some(word) + && index + .checked_sub(1) + .and_then(|before| bytes.get(before)) + .is_none_or(|byte| !is_ascii_identifier_char(*byte)) + && bytes + .get(index + word.len()) + .is_none_or(|byte| !is_ascii_identifier_char(*byte)) } -fn decimal_tail_end(bytes: &[u8], mut index: usize) -> usize { - loop { - while bytes.get(index).is_some_and(|byte| byte.is_ascii_digit()) { - index += 1; - } - if bytes.get(index) == Some(&b'_') - && bytes - .get(index + 1) - .is_some_and(|byte| byte.is_ascii_digit()) - { - index += 2; - } else { - return index; - } - } -} - -fn invalid_decimal_literal_error(bytes: &[u8], start: usize) -> Option<(String, usize)> { - if bytes.get(start) == Some(&b'.') { - return None; - } - let message = "invalid decimal literal".to_owned(); - if let Some(offset) = decimal_tail_error(bytes, start) { - return Some((message, offset)); - } - - let mut index = decimal_tail_end(bytes, start); - if bytes.get(index) == Some(&b'.') { - if bytes.get(index + 1) == Some(&b'_') { - return Some((message, index)); - } - if let Some(offset) = decimal_tail_error(bytes, index + 1) { - return Some((message, offset)); - } - index = decimal_tail_end(bytes, index + 1); - } - if matches!(bytes.get(index), Some(b'e' | b'E')) { - let exponent = index; - index += 1; - let sign = if matches!(bytes.get(index), Some(b'+' | b'-')) { - let sign = index; - index += 1; - Some(sign) - } else { - None - }; - if !bytes.get(index).is_some_and(|byte| byte.is_ascii_digit()) { - // Without a sign the exponent letter is put back, so the position - // is the digit before it rather than the letter. - return Some((message, sign.unwrap_or_else(|| exponent.saturating_sub(1)))); - } - if let Some(offset) = decimal_tail_error(bytes, index) { - return Some((message, offset)); - } - } - None -} - -fn leading_zero_decimal_literal_error(bytes: &[u8], start: usize) -> Option { - if bytes.get(start) != Some(&b'0') { - return None; - } - let mut index = start; - loop { - match bytes.get(index) { - Some(b'0') => index += 1, - Some(b'_') - if bytes - .get(index + 1) - .is_some_and(|byte| byte.is_ascii_digit()) => - { +fn eval_has_assignment_before(bytes: &[u8], end: usize) -> bool { + let mut index = 0; + let mut level = 0usize; + let mut in_lambda_params = false; + while index < end { + match bytes[index] { + b'#' => { + while index < end && bytes[index] != b'\n' { + index += 1; + } + } + b'\'' | b'"' => index = skip_quoted_string(bytes, index), + b'(' | b'[' | b'{' => { + level += 1; index += 1; } - _ => break, - } - } - if bytes.get(index).is_some_and(|byte| byte.is_ascii_digit()) { - let after_digits = decimal_tail_end(bytes, index); - if !matches!( - bytes.get(after_digits), - Some(b'.' | b'e' | b'E' | b'j' | b'J') - ) { - return Some(CpythonDiagnostic::new( - "leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers" - .to_owned(), - start, - index, - )); + b')' | b']' | b'}' => { + level = level.saturating_sub(1); + index += 1; + } + b':' if level == 0 => { + in_lambda_params = false; + index += 1; + } + b'=' if level == 0 + && !in_lambda_params + && bytes.get(index + 1) != Some(&b'=') + && !matches!( + bytes.get(index.saturating_sub(1)), + Some(b':' | b'!' | b'<' | b'>') + ) => + { + return true; + } + _ if level == 0 && starts_identifier(bytes, index, b"lambda") => { + in_lambda_params = true; + index += b"lambda".len(); + } + _ => index += 1, } } - None + false } -fn invalid_numeric_literal_error(bytes: &[u8], start: usize) -> Option { - if bytes.get(start) == Some(&b'0') { - let radix = match bytes.get(start + 1) { - Some(b'x' | b'X') => invalid_radix_literal_error(bytes, start, "hexadecimal", |byte| { - byte.is_ascii_hexdigit() - }), - Some(b'o' | b'O') => invalid_radix_literal_error(bytes, start, "octal", |byte| { - matches!(byte, b'0'..=b'7') - }), - Some(b'b' | b'B') => invalid_radix_literal_error(bytes, start, "binary", |byte| { - matches!(byte, b'0' | b'1') - }), - _ => None, - }; - if let Some(radix) = radix { - return Some(point_span(radix)); - } - if let Some(err) = leading_zero_decimal_literal_error(bytes, start) { - return Some(err); +fn interpolated_string_prefix(bytes: &[u8], quote: usize) -> Option<&'static str> { + let prev = quote.checked_sub(1).and_then(|index| bytes.get(index))?; + let lower_prev = prev.to_ascii_lowercase(); + let (prefix_start, marker) = if matches!(lower_prev, b'f' | b't') { + if quote >= 2 && bytes[quote - 2].eq_ignore_ascii_case(&b'r') { + (quote - 2, lower_prev) + } else { + (quote - 1, lower_prev) } - } - invalid_decimal_literal_error(bytes, start).map(point_span) -} - -fn consume_exponent(bytes: &[u8], index: usize) -> usize { - if !matches!(bytes.get(index), Some(b'e' | b'E')) { - return index; - } - let mut cursor = index + 1; - if matches!(bytes.get(cursor), Some(b'+' | b'-')) { - cursor += 1; - } - if bytes.get(cursor).is_some_and(|byte| byte.is_ascii_digit()) { - consume_decimal_digits(bytes, cursor) + } else if lower_prev == b'r' + && quote >= 2 + && matches!(bytes[quote - 2].to_ascii_lowercase(), b'f' | b't') + { + (quote - 2, bytes[quote - 2].to_ascii_lowercase()) } else { - index - } -} - -fn number_literal_end(bytes: &[u8], start: usize) -> Option<(&'static str, usize)> { - if bytes.get(start) == Some(&b'.') { - if !bytes - .get(start + 1) - .is_some_and(|byte| byte.is_ascii_digit()) - { - return None; - } - let mut index = consume_decimal_digits(bytes, start + 1); - index = consume_exponent(bytes, index); - if matches!(bytes.get(index), Some(b'j' | b'J')) { - return Some(("imaginary", index + 1)); - } - return Some(("decimal", index)); - } - - if !bytes.get(start).is_some_and(|byte| byte.is_ascii_digit()) { return None; - } - - if bytes.get(start) == Some(&b'0') { - match bytes.get(start + 1) { - Some(b'x' | b'X') => { - let end = consume_radix_digits(bytes, start + 2, |byte| byte.is_ascii_hexdigit()); - return Some(("hexadecimal", end)); - } - Some(b'o' | b'O') => { - let end = - consume_radix_digits(bytes, start + 2, |byte| matches!(byte, b'0'..=b'7')); - return Some(("octal", end)); - } - Some(b'b' | b'B') => { - let end = - consume_radix_digits(bytes, start + 2, |byte| matches!(byte, b'0' | b'1')); - return Some(("binary", end)); - } - _ => {} - } - } + }; - let mut index = consume_decimal_digits(bytes, start); - if bytes.get(index) == Some(&b'.') { - index = consume_decimal_digits(bytes, index + 1); - } - index = consume_exponent(bytes, index); - if matches!(bytes.get(index), Some(b'j' | b'J')) { - return Some(("imaginary", index + 1)); + if prefix_start > 0 && identifier_continue_before(bytes, prefix_start) { + return None; } - Some(("decimal", index)) -} -fn quoted_string_is_closed(bytes: &[u8], start: usize) -> bool { - let quote = bytes[start]; - let triple = bytes.get(start + 1) == Some("e) && bytes.get(start + 2) == Some("e); - let end = skip_quoted_string(bytes, start); - if triple { - end >= start + 6 - && bytes[end - 3] == quote - && bytes[end - 2] == quote - && bytes[end - 1] == quote + Some(if marker == b'f' { + "f-string" } else { - end > start + 1 && bytes[end - 1] == quote - } + "t-string" + }) } -fn bytes_literal_span(source: &str, error_at: usize) -> Option<(usize, usize)> { - let bytes = source.as_bytes(); - if error_at > bytes.len() || bytes.is_empty() { - return None; - } - let mut quote_idx = error_at.min(bytes.len().saturating_sub(1)); - loop { - if matches!(bytes[quote_idx], b'\'' | b'"') { - break; - } - if quote_idx == 0 { - return None; - } - quote_idx -= 1; - } - let mut start = quote_idx; - while start > 0 && matches!(bytes[start - 1], b'b' | b'B' | b'r' | b'R') { - start -= 1; - } - if !matches!(bytes.get(start), Some(b'b' | b'B' | b'r' | b'R')) { - return None; - } - let end = skip_quoted_string(bytes, quote_idx); - Some((start, end)) -} +const MAXFSTRINGLEVEL: usize = 150; -fn skip_quoted_string(bytes: &[u8], mut index: usize) -> usize { - let quote = bytes[index]; - let triple = bytes.get(index + 1) == Some("e) && bytes.get(index + 2) == Some("e); - let quote_len = if triple { 3 } else { 1 }; - index += quote_len; - while index < bytes.len() { - if bytes[index] == b'\\' { - index = (index + 2).min(bytes.len()); - } else if triple - && bytes.get(index) == Some("e) - && bytes.get(index + 1) == Some("e) - && bytes.get(index + 2) == Some("e) - { - return index + 3; - } else if !triple && bytes[index] == quote { - return index + 1; - } else { - index += 1; - } +fn skip_string_token(bytes: &[u8], quote_index: usize) -> usize { + if interpolated_string_prefix(bytes, quote_index).is_some() { + interpolated_string_end(bytes, quote_index).unwrap_or(bytes.len()) + } else { + skip_quoted_string(bytes, quote_index) } - index -} - -// An error the tokenizer reports at a single position spans nothing. -fn point_span((message, offset): (String, usize)) -> CpythonDiagnostic { - CpythonDiagnostic::new(message, offset, offset) } -fn invalid_number_literal_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; +fn interpolated_string_end(bytes: &[u8], quote_index: usize) -> Option { + let quote = bytes[quote_index]; + let triple = + bytes.get(quote_index + 1) == Some("e) && bytes.get(quote_index + 2) == Some("e); + let quote_len = if triple { 3 } else { 1 }; + let mut index = quote_index + quote_len; + let mut brace_depth = 0usize; while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } + if brace_depth == 0 { + if bytes[index] == b'\\' { + index = (index + 2).min(bytes.len()); + continue; } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); + if triple + && bytes.get(index) == Some("e) + && bytes.get(index + 1) == Some("e) + && bytes.get(index + 2) == Some("e) + { + return Some(index + 3); } - byte if byte >= 0x80 || byte == b'_' || byte.is_ascii_alphabetic() => { - index += 1; - while index < bytes.len() - && (bytes[index] >= 0x80 || is_ascii_identifier_char(bytes[index])) - { + if !triple && bytes[index] == quote { + return Some(index + 1); + } + if bytes[index] == b'{' { + if bytes.get(index + 1) == Some(&b'{') { + index += 2; + } else { + brace_depth = 1; index += 1; } + } else if bytes[index] == b'}' && bytes.get(index + 1) == Some(&b'}') { + index += 2; + } else { + index += 1; } - b'.' | b'0'..=b'9' => { - if let Some(err) = invalid_numeric_literal_error(bytes, index) { - return Some(err); - } - let Some((kind, end)) = number_literal_end(bytes, index) else { - index += 1; - continue; - }; - if end > index { - if source[end..].starts_with('⁄') { - return Some(CpythonDiagnostic::new( - "invalid character '⁄' (U+2044)".to_owned(), - end, - end, - )); + } else { + match bytes[index] { + quote_ch @ (b'\'' | b'"') => { + if quoted_string_is_closed(bytes, index) { + index = skip_string_token(bytes, index).max(index + 1); + } else if !triple && quote_ch == quote { + return Some(index + 1); + } else { + index = skip_string_token(bytes, index).max(index + 1); } - if bytes - .get(end) - .is_some_and(|byte| *byte < 128 && is_ascii_identifier_char(*byte)) - && !numeric_keyword_suffix(&bytes[end..]) - { - let offset = end.saturating_sub(1); - return Some(CpythonDiagnostic::new( - format!("invalid {kind} literal"), - offset, - offset, - )); + } + b'#' => { + while index < bytes.len() && bytes[index] != b'\n' { + index += 1; } } - index = end.max(index + 1); + b'{' => { + brace_depth += 1; + index += 1; + } + b'}' => { + brace_depth -= 1; + index += 1; + } + b'\\' => index = (index + 2).min(bytes.len()), + _ => index += 1, } - _ => index += 1, } } None } -fn cpython_indented_block_clause(message: &str) -> Option<&'static str> { - let clause = message.strip_prefix("Expected an indented block after ")?; - Some(match clause { - "`if` statement" => "'if' statement", - "`elif` clause" => "'elif' statement", - "`else` clause" => "'else' statement", - "`for` statement" => "'for' statement", - "`with` statement" => "'with' statement", - "`while` statement" => "'while' statement", - "`try` statement" => "'try' statement", - "`except` clause" => "'except' statement", - "`finally` clause" => "'finally' statement", - "`match` statement" => "'match' statement", - "`case` block" => "'case' statement", - "`class` definition" => "class definition", - "function definition" => "function definition", - _ => return None, - }) +fn quote_len_at(bytes: &[u8], quote_index: usize) -> usize { + let quote = bytes[quote_index]; + if bytes.get(quote_index + 1) == Some("e) && bytes.get(quote_index + 2) == Some("e) { + 3 + } else { + 1 + } } -fn previous_non_empty_line_number(source: &str, offset: usize) -> Option { - let bytes = source.as_bytes(); - let mut index = offset.min(bytes.len()); - while index > 0 { - let line_end = index; - while index > 0 && bytes[index - 1] != b'\n' { - index -= 1; - } - let line_start = index; - let content_start = skip_horizontal_whitespace(bytes, line_start); - let mut content_end = line_end; - while content_end > content_start - && matches!( - bytes.get(content_end - 1), - Some(b' ' | b'\t' | b'\r' | b'\x0c') - ) - { - content_end -= 1; - } - if content_start < content_end { - return Some( - source[..line_start] - .bytes() - .filter(|byte| *byte == b'\n') - .count() - + 1, - ); - } - index = line_start.saturating_sub(1); - } - None +fn interpolated_string_content_range(bytes: &[u8], quote_index: usize) -> Option<(usize, usize)> { + let end = interpolated_string_end(bytes, quote_index)?; + let quote_len = quote_len_at(bytes, quote_index); + Some((quote_index + quote_len, end - quote_len)) } -fn expected_indented_block_error( - error: &parser::ParseError, - source: &str, -) -> Option { - let parser::ParseErrorType::OtherError(message) = &error.error else { +/// Return the syntax error for a decimal integer literal exceeding the configured limit. +/// +/// The parser has already distinguished integer literals from strings, comments, floats, and +/// complex numbers. Inspecting its tokens keeps the limit consistent for every source parsing +/// entry point without reimplementing Python's lexer here. +#[must_use] +pub fn long_decimal_integer_literal_error( + source_file: &SourceFile, + tokens: &Tokens, + max_str_digits: usize, +) -> Option { + if max_str_digits == 0 { return None; - }; - let mut clause = cpython_indented_block_clause(message)?; - let start = error.location.start().to_usize(); - let end = error.location.end().to_usize(); - let line = previous_non_empty_line_number(source, start)?; - if clause == "'except' statement" - && let Some(previous_line) = previous_non_empty_line(source, start) - && matches!( - previous_line.trim_start(), - line if line.starts_with("except*") || line.starts_with("except *") - ) - { - clause = "'except*' statement"; } - Some(CpythonDiagnostic::new( - format!("expected an indented block after {clause} on line {line}"), - start, - end, - )) -} - -fn previous_non_empty_line(source: &str, offset: usize) -> Option<&str> { - let bytes = source.as_bytes(); - let mut index = offset.min(bytes.len()); - while index > 0 { - let line_end = index; - while index > 0 && bytes[index - 1] != b'\n' { - index -= 1; - } - let line_start = index; - let mut content_start = line_start; - while content_start < line_end - && matches!(bytes[content_start], b' ' | b'\t' | b'\n' | b'\r' | b'\x0c') - { - content_start += 1; + tokens.iter().find_map(|token| { + if token.kind() != TokenKind::Int { + return None; } - let mut content_end = line_end; - while content_end > content_start - && matches!(bytes[content_end - 1], b' ' | b'\t' | b'\r' | b'\x0c') + let literal = source_file.source_text().slice(token.range()); + if literal + .as_bytes() + .get(..2) + .is_some_and(|prefix| matches!(prefix, b"0x" | b"0X" | b"0o" | b"0O" | b"0b" | b"0B")) { - content_end -= 1; - } - if content_start < content_end { - return source.get(line_start..line_end); + return None; } - index = line_start.saturating_sub(1); - } - None -} - -fn starts_identifier(bytes: &[u8], index: usize, word: &[u8]) -> bool { - bytes.get(index..index + word.len()) == Some(word) - && index - .checked_sub(1) - .and_then(|before| bytes.get(before)) - .is_none_or(|byte| !is_ascii_identifier_char(*byte)) - && bytes - .get(index + word.len()) - .is_none_or(|byte| !is_ascii_identifier_char(*byte)) + let digits = literal.bytes().filter(u8::is_ascii_digit).count(); + (digits > max_str_digits).then(|| { + let start = token.range().start().to_usize(); + CompileError::from_source_error(source_file, CpythonDiagnostic::new(format!( + "Exceeds the limit ({max_str_digits} digits) for integer string conversion: value has {digits} digits; use sys.set_int_max_str_digits() to increase the limit - Consider hexadecimal for huge integer literals to avoid decimal conversion limits." + ), start, start)) + }) + }) } -fn is_plain_assignment_operator(bytes: &[u8], index: usize) -> bool { - bytes.get(index) == Some(&b'=') - && bytes.get(index + 1) != Some(&b'=') - && !matches!( - index.checked_sub(1).and_then(|before| bytes.get(before)), - Some(b'=' | b'!' | b'<' | b'>' | b':') - ) +fn too_many_nested_interpolated_strings(source: &str) -> Option { + too_many_nested_interpolated_strings_in(source.as_bytes(), 0, source.len(), 0) } -fn is_simple_keyword_name(bytes: &[u8], mut start: usize, mut end: usize) -> bool { - while matches!( - bytes.get(start), - Some(b' ' | b'\t' | b'\n' | b'\r' | b'\x0c') - ) { - start += 1; - } - while end > start - && matches!( - bytes.get(end - 1), - Some(b' ' | b'\t' | b'\n' | b'\r' | b'\x0c') - ) - { - end -= 1; - } - let Some(&first) = bytes.get(start) else { - return false; - }; - if !(first == b'_' || first.is_ascii_alphabetic() || first >= 0x80) { - return false; - } - let mut index = start + 1; +fn too_many_nested_interpolated_strings_in( + bytes: &[u8], + mut index: usize, + end: usize, + depth: usize, +) -> Option { while index < end { - if bytes[index] < 0x80 && !is_ascii_identifier_char(bytes[index]) { - return false; - } - index += 1; - } - true -} - -fn is_function_parameter_list(bytes: &[u8], paren: usize) -> bool { - let mut cursor = paren; - while cursor > 0 && matches!(bytes.get(cursor - 1), Some(b' ' | b'\t' | b'\x0c')) { - cursor -= 1; - } - if cursor > 0 && bytes.get(cursor - 1) == Some(&b']') { - let mut bracket = cursor; - let mut level = 0usize; - while bracket > 0 { - bracket -= 1; - match bytes[bracket] { - b']' => level += 1, - b'[' => { - level = level.saturating_sub(1); - if level == 0 { - cursor = bracket; - break; + match bytes[index] { + b'#' => { + while index < end && bytes[index] != b'\n' { + index += 1; + } + } + b'\'' | b'"' => { + if interpolated_string_prefix(bytes, index).is_some() { + if depth + 1 >= MAXFSTRINGLEVEL { + return Some(CpythonDiagnostic::new( + "too many nested f-strings or t-strings".to_owned(), + index, + index + 1, + )); + } + if let Some((content_start, content_end)) = + interpolated_string_content_range(bytes, index) + && let Some(error) = too_many_nested_interpolated_strings_in( + bytes, + content_start, + content_end, + depth + 1, + ) + { + return Some(error); } } - _ => {} + index = skip_string_token(bytes, index).max(index + 1); } - } - while cursor > 0 && matches!(bytes.get(cursor - 1), Some(b' ' | b'\t' | b'\x0c')) { - cursor -= 1; + _ => index += 1, } } - while cursor > 0 - && bytes - .get(cursor - 1) - .is_some_and(|byte| *byte >= 0x80 || is_ascii_identifier_char(*byte)) - { - cursor -= 1; + None +} + +/// Horizontal and vertical space the tokenizer skips, not `str::trim()`. +const fn is_ascii_tokenizer_whitespace(c: char) -> bool { + matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c') +} + +/// True when every line is empty or a comment after tokenizer whitespace. +#[doc(hidden)] +#[must_use] +pub fn is_blank_python_source(source: &str) -> bool { + source.lines().all(|line| { + let trimmed = line.trim_matches(is_ascii_tokenizer_whitespace); + trimmed.is_empty() || trimmed.starts_with('#') + }) +} + +fn single_mode_blank_source_error(source_file: &SourceFile) -> Option { + let source = source_file.source_text(); + if !is_blank_python_source(source) { + return None; } - while cursor > 0 && matches!(bytes.get(cursor - 1), Some(b' ' | b'\t' | b'\x0c')) { - cursor -= 1; + let has_indent_only_line = source.lines().any(|line| { + line.trim_matches(is_ascii_tokenizer_whitespace).is_empty() + && line.chars().any(|c| matches!(c, ' ' | '\t')) + }); + if has_indent_only_line { + let (location, end_location) = + source_locations(source_file, TextSize::new(0), TextSize::new(0)); + return Some(CompileError::Parse(ParseError { + error: parser::ParseErrorType::UnexpectedIndentation, + raw_location: ruff_text_size::TextRange::new(TextSize::new(0), TextSize::new(0)), + location, + end_location, + source_path: source_file.name().to_owned(), + is_unclosed_bracket: false, + is_unclosed_string: false, + eof_token: None, + })); } - cursor >= 3 - && starts_identifier(bytes, cursor - 3, b"def") - && cursor - .checked_sub(4) - .and_then(|before| bytes.get(before)) - .is_none_or(|byte| !is_ascii_identifier_char(*byte)) + Some(CompileError::from_source_error( + source_file, + CpythonDiagnostic::new("invalid syntax".to_owned(), 0, 0), + )) } -#[derive(Clone, Copy)] -enum ParameterListKind { - Function, - Lambda, +/// The byte-order mark is only stripped while decoding source bytes, so one +/// that survives into the text is just a non-printable character. The tokenizer +/// rejects it everywhere except at the very start of the text, which is where +/// this covers. +#[doc(hidden)] +#[must_use] +pub fn leading_byte_order_mark_error(source_file: &SourceFile) -> Option { + source_file.source_text().starts_with('\u{feff}').then(|| { + CompileError::from_source_error( + source_file, + CpythonDiagnostic::new("invalid non-printable character U+FEFF".to_owned(), 0, 0), + ) + }) } -fn matching_delimiter(bytes: &[u8], open: usize, close: u8) -> Option { - let mut index = open; +fn too_many_nested_parentheses_error(source: &str) -> Option { + const MAXLEVEL: usize = 200; + + let bytes = source.as_bytes(); + let mut index = 0; let mut level = 0usize; while index < bytes.len() { match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - byte if byte == close => { - level = level.saturating_sub(1); - if level == 0 { - return Some(index); + b'#' => { + while index < bytes.len() && bytes[index] != b'\n' { + index += 1; } - index += 1; } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; + b'\'' | b'"' => { + index = skip_quoted_string(bytes, index); } - _ => index += 1, - } - } - None -} - -fn find_lambda_parameter_end(bytes: &[u8], mut index: usize) -> Option { - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' if level == 0 => return None, - b'\'' | b'"' => index = skip_quoted_string(bytes, index), b'(' | b'[' | b'{' => { + if level >= MAXLEVEL { + return Some(CpythonDiagnostic::new( + "too many nested parentheses".to_owned(), + index, + index, + )); + } level += 1; index += 1; } @@ -1344,5734 +1000,1054 @@ fn find_lambda_parameter_end(bytes: &[u8], mut index: usize) -> Option { level = level.saturating_sub(1); index += 1; } - b':' if level == 0 => return Some(index), _ => index += 1, } } None } -fn top_level_byte(bytes: &[u8], mut index: usize, end: usize, needle: u8) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - byte if level == 0 && byte == needle => return Some(index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ => index += 1, - } +/// Source-level errors raised before parsing, as CPython's tokenizer does. +/// +/// Checking after the parse would build the tree first, and one nested that +/// deep exhausts the native stack when it is dropped. +pub fn pre_parse_source_error(source_file: &SourceFile) -> Result<(), CompileError> { + match too_many_nested_parentheses_error(source_file.source_text()) { + Some(error) => Err(CompileError::from_source_error(source_file, error)), + None => Ok(()), } - None } -fn identifier_end(bytes: &[u8], mut index: usize, end: usize) -> usize { - if !bytes - .get(index) - .is_some_and(|byte| *byte >= 0x80 || *byte == b'_' || byte.is_ascii_alphabetic()) - { - return index; +fn post_parse_source_error( + source_file: &SourceFile, + tokens: &Tokens, + opts: &CompileOpts, +) -> Option { + if let Some(error) = leading_byte_order_mark_error(source_file) { + return Some(error); } - index += 1; - while index < end - && bytes - .get(index) - .is_some_and(|byte| *byte >= 0x80 || is_ascii_identifier_char(*byte)) - { - index += 1; + if let Some(error) = too_many_nested_interpolated_strings(source_file.source_text()) { + return Some(CompileError::from_source_error(source_file, error)); } - index + long_decimal_integer_literal_error(source_file, tokens, opts.int_max_str_digits) } -fn expression_slice_is_tuple(source: &str, start: usize, end: usize) -> bool { - let bytes = source.as_bytes(); - let (start, end) = trim_target_range(bytes, start, end); - if start >= end { - return false; - } - let Ok(parsed) = parser::parse(&source[start..end], parser::Mode::Expression.into()) else { - return false; - }; - matches!(parsed.into_syntax(), ast::Mod::Expression(expression) if matches!(*expression.body, ast::Expr::Tuple(_))) -} +fn is_compound_stmt(stmt: &ast::Stmt) -> bool { + matches!( + stmt, + ast::Stmt::FunctionDef(_) + | ast::Stmt::ClassDef(_) + | ast::Stmt::If(_) + | ast::Stmt::For(_) + | ast::Stmt::While(_) + | ast::Stmt::With(_) + | ast::Stmt::Try(_) + | ast::Stmt::Match(_) + ) +} -fn type_param_list_open(bytes: &[u8], open: usize) -> bool { - let mut cursor = open; - while cursor > 0 && matches!(bytes.get(cursor - 1), Some(b' ' | b'\t' | b'\x0c')) { - cursor -= 1; - } - while cursor > 0 - && bytes - .get(cursor - 1) - .is_some_and(|byte| *byte >= 0x80 || is_ascii_identifier_char(*byte)) - { - cursor -= 1; - } - while cursor > 0 && matches!(bytes.get(cursor - 1), Some(b' ' | b'\t' | b'\x0c')) { - cursor -= 1; +/// Rejects an AST nested deeper than `limit`. +/// +/// The parser grows its own stack, so it returns trees deeper than the passes +/// after it can walk, and each of those recurses without a limit of its own. +/// The symbol table applies the same limit, but `compile(..., PyCF_ONLY_AST)` +/// returns before reaching it. +pub fn too_deeply_nested_error( + ast: &ast::Mod, + source_file: &SourceFile, + limit: usize, +) -> Result<(), CompileError> { + use ast::visitor::Visitor; + + struct DepthChecker { + depth: usize, + limit: usize, + too_deep: Option, } - (cursor >= 3 && starts_identifier(bytes, cursor - 3, b"def")) - || (cursor >= 5 && starts_identifier(bytes, cursor - 5, b"class")) - || (cursor >= 4 && starts_identifier(bytes, cursor - 4, b"type")) -} -fn invalid_type_param_item_error( - source: &str, - start: usize, - end: usize, -) -> Option { - let bytes = source.as_bytes(); - let (start, end) = trim_target_range(bytes, start, end); - if start >= end || bytes.get(start) != Some(&b'*') { - return None; + impl DepthChecker { + fn descend(&mut self, range: ruff_text_size::TextRange, walk: impl FnOnce(&mut Self)) { + if self.too_deep.is_some() { + return; + } + if self.depth >= self.limit { + self.too_deep = Some(range); + return; + } + self.depth += 1; + walk(self); + self.depth -= 1; + } } - let is_param_spec = bytes.get(start + 1) == Some(&b'*'); - let name_start = start + if is_param_spec { 2 } else { 1 }; - let name_end = identifier_end(bytes, name_start, end); - if name_start == name_end { - return None; + + impl<'a> Visitor<'a> for DepthChecker { + fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { + self.descend(stmt.range(), |checker| { + ast::visitor::walk_stmt(checker, stmt); + }); + } + + fn visit_expr(&mut self, expr: &'a ast::Expr) { + self.descend(expr.range(), |checker| { + ast::visitor::walk_expr(checker, expr); + }); + } + + fn visit_pattern(&mut self, pattern: &'a ast::Pattern) { + self.descend(pattern.range(), |checker| { + ast::visitor::walk_pattern(checker, pattern); + }); + } } - let colon = next_non_horizontal_whitespace(bytes, name_end); - if colon >= end || bytes.get(colon) != Some(&b':') { - return None; + + let mut checker = DepthChecker { + depth: 0, + limit, + too_deep: None, + }; + match ast { + ast::Mod::Module(module) => checker.visit_body(&module.body), + ast::Mod::Expression(expression) => checker.visit_expr(&expression.body), } - let has_constraints = expression_slice_is_tuple(source, colon + 1, end); - let message = match (is_param_spec, has_constraints) { - (false, false) => "cannot use bound with TypeVarTuple", - (false, true) => "cannot use constraints with TypeVarTuple", - (true, false) => "cannot use bound with ParamSpec", - (true, true) => "cannot use constraints with ParamSpec", + + let Some(range) = checker.too_deep else { + return Ok(()); }; - Some(CpythonDiagnostic::new(message.to_owned(), colon, colon + 1)) + let (location, end_location) = source_locations(source_file, range.start(), range.end()); + Err(CompileError::Codegen(codegen::error::CodegenError { + location: Some(location), + end_location: Some(end_location), + error: codegen::error::CodegenErrorType::RecursionError, + source_path: source_file.name().to_owned(), + })) } -fn invalid_type_param_list_error( - source: &str, - open: usize, - close: usize, -) -> Option { - let bytes = source.as_bytes(); - let mut item_start = open + 1; - let mut index = item_start; - let mut level = 0usize; - while index <= close { - if index == close || (level == 0 && bytes.get(index) == Some(&b',')) { - if let Some(error) = invalid_type_param_item_error(source, item_start, index) { - return Some(error); +/// Syntax the reference grammar has no rule for, but that this parser accepts. +/// +/// A bare generator expression is one: `f(x for x in y)` is the `primary +/// genexp` alternative of a call, and a class header only takes `arguments`, +/// which has no such alternative. A format spec nested more than two deep is +/// the other; the tokenizer runs out of nesting levels for it. A lazy +/// `__future__` import is rejected by the `checked_from_import` action. +#[doc(hidden)] +#[must_use] +pub fn unsupported_grammar_error(ast: &ast::Mod, source_file: &SourceFile) -> Option { + use ast::visitor::Visitor; + + /// The deepest chain of format specs one string literal may hold. + const MAX_FORMAT_SPEC_DEPTH: usize = 2; + + struct Checker<'a> { + source_file: &'a SourceFile, + error: Option, + } + + impl Checker<'_> { + fn fail(&mut self, message: &str, range: ruff_text_size::TextRange) { + self.error = Some(CompileError::from_source_error( + self.source_file, + CpythonDiagnostic::new( + message.to_owned(), + range.start().to_usize(), + range.end().to_usize(), + ), + )); + } + + fn check_format_specs( + &mut self, + kind: &str, + elements: &ast::InterpolatedStringElements, + depth: usize, + ) { + for element in elements.interpolations() { + let Some(format_spec) = &element.format_spec else { + continue; + }; + if depth == MAX_FORMAT_SPEC_DEPTH { + self.fail( + &alloc::format!("{kind}: expressions nested too deeply"), + format_spec.range, + ); + return; + } + self.check_format_specs(kind, &format_spec.elements, depth + 1); + if self.error.is_some() { + return; + } } - item_start = index + 1; - index += 1; - continue; } - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; + } + + impl<'a> Visitor<'a> for Checker<'_> { + fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { + if self.error.is_some() { + return; } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; + if let ast::Stmt::ImportFrom(import) = stmt + && import.is_lazy + && import.level == 0 + && import + .module + .as_ref() + .is_some_and(|module| module.as_str() == "__future__") + { + let lazy = ruff_text_size::TextRange::at(import.range.start(), 4.into()); + self.fail("lazy from __future__ import is not allowed", lazy); + return; } - _ => index += 1, + if let ast::Stmt::ClassDef(class_def) = stmt + && let Some(arguments) = &class_def.arguments + && let [ast::Expr::Generator(generator)] = &arguments.args[..] + && !generator.parenthesized + { + let range = generator + .generators + .first() + .map_or(generator.range, |comprehension| comprehension.range); + self.fail("invalid syntax", range); + return; + } + ast::visitor::walk_stmt(self, stmt); } - } - None -} -fn invalid_type_param_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } + fn visit_expr(&mut self, expr: &'a ast::Expr) { + if self.error.is_some() { + return; } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'[' if type_param_list_open(bytes, index) => { - let Some(close) = matching_delimiter(bytes, index, b']') else { - index += 1; - continue; - }; - if let Some(error) = invalid_type_param_list_error(source, index, close) { - return Some(error); + // Each literal counts its own nesting: one written inside a format + // spec starts over. + match expr { + ast::Expr::FString(fstring) => { + for part in &fstring.value { + if let ast::FStringPartRef::FString(part) = part { + self.check_format_specs("f-string", &part.elements, 0); + } + } + } + ast::Expr::TString(tstring) => { + for part in &tstring.value { + self.check_format_specs("t-string", &part.elements, 0); + } } - index = close + 1; + _ => {} } - _ => index += 1, + if self.error.is_some() { + return; + } + ast::visitor::walk_expr(self, expr); } } - None -} -fn invalid_comprehension_in_slice( - bytes: &[u8], - open: usize, - close: usize, -) -> Option { - let for_index = find_keyword_at_level(bytes, open + 1, close, b"for")?; - let item_start = next_non_horizontal_whitespace(bytes, open + 1); - if item_start >= for_index { - return None; - } - if bytes.get(item_start..item_start + 2) == Some(b"**") && bytes.get(open) == Some(&b'{') { - return Some(CpythonDiagnostic::new( - "dict unpacking cannot be used in dict comprehension".to_owned(), - item_start, - item_start + 2, - )); - } - if bytes.get(item_start..item_start + 2) == Some(b"**") && bytes.get(open) == Some(&b'(') { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - for_index, - for_index + 3, - )); - } - if bytes.get(item_start) == Some(&b'*') { - return Some(CpythonDiagnostic::new( - "iterable unpacking cannot be used in comprehension".to_owned(), - item_start, - item_start + 1, - )); - } - if !matches!(bytes.get(open), Some(b'[' | b'{')) { - return None; + let mut checker = Checker { + source_file, + error: None, + }; + match ast { + ast::Mod::Module(module) => checker.visit_body(&module.body), + ast::Mod::Expression(expression) => checker.visit_expr(&expression.body), } - if top_level_colon(bytes, open + 1, for_index).is_none() - && let Some(comma) = top_level_byte(bytes, open + 1, for_index, b',') + checker.error +} + +fn single_mode_body_error(body: &[ast::Stmt], source_file: &SourceFile) -> Option { + let first = body.first()?; + let source_code = source_file.to_source_code(); + let first_start = source_code.source_location(first.range().start(), PositionEncoding::Utf8); + let first_end = source_code.source_location(first.range().end(), PositionEncoding::Utf8); + + if is_compound_stmt(first) + && first_start.line == first_end.line + && !ends_with_line_break(source_file.source_text()) { - let (start, _) = trim_target_range(bytes, open + 1, comma); - return Some(CpythonDiagnostic::new( - "did you forget parentheses around the comprehension target?".to_owned(), - start, - comma + 1, + return Some(CompileError::from_source_error( + source_file, + CpythonDiagnostic::new( + "invalid syntax".to_owned(), + first.range().start().to_usize(), + first.range().start().to_usize(), + ), )); } None } -fn invalid_comprehension_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - let close_byte = match bytes[index] { - b'(' => b')', - b'[' => b']', - _ => b'}', - }; - let Some(close) = matching_delimiter(bytes, index, close_byte) else { - index += 1; - continue; - }; - if let Some(error) = invalid_comprehension_in_slice(bytes, index, close) { - return Some(error); - } - index = close + 1; - } - _ => index += 1, - } +/// Converts the first parse error. A tokenizer error that follows an earlier syntax error is +/// only found by the pass over the rest of the source, so it never asks for more input. +/// Classify an initial INDENT after expression parsing has failed. +/// CPython reports this before later tokenizer errors in the same input. +#[doc(hidden)] +#[must_use] +pub fn expression_initial_indent_error( + tokens: &Tokens, + source_file: &SourceFile, +) -> Option { + let first = tokens.iter().find(|token| { + !matches!( + token.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline | TokenKind::Newline + ) + })?; + if first.kind() != TokenKind::Indent { + return None; } - None + // An indentation token can span explicitly continued physical lines. + // The parser points at the last indentation character on the final line. + let offset = first.end() - TextSize::new(1); + Some(CompileError::from_ruff_parse_error( + parser::ParseError { + error: ParseErrorType::UnexpectedIndentation, + location: ruff_text_size::TextRange::empty(offset), + }, + source_file, + Mode::Eval, + )) } -fn invalid_group_in_slice(bytes: &[u8], open: usize, close: usize) -> Option { - let (item_start, item_end) = trim_target_range(bytes, open + 1, close); - if item_start >= item_end - || top_level_byte(bytes, item_start, item_end, b',').is_some() - || top_level_colon(bytes, item_start, item_end).is_some() - || find_keyword_at_level(bytes, item_start, item_end, b"for").is_some() +fn first_parse_error( + parsed: parser::Parsed, + source_file: &SourceFile, + mode: Mode, + prepared_source: &str, + parser_options: &parser::ParseOptions, +) -> Result, CompileError> { + let Some((first, rest)) = parsed.errors().split_first() else { + return Ok(parsed); + }; + if matches!(mode, Mode::Eval) + && let Some(error) = expression_initial_indent_error(parsed.tokens(), source_file) { - return None; - } - if bytes.get(item_start..item_start + 2) == Some(b"**") { - return Some(CpythonDiagnostic::new( - "cannot use double starred expression here".to_owned(), - item_start, - item_start + 2, - )); + return Err(error); } - if bytes.get(item_start) == Some(&b'*') { - return Some(CpythonDiagnostic::new( - "cannot use starred expression here".to_owned(), - item_start, - item_start + 1, - )); + let after_syntax_error = rest.iter().any(|error| { + !matches!(error.error, ParseErrorType::Lexical(_)) + && error.location.start() < first.location.start() + }); + let normalized = unpacking_parse_diagnostic( + first, + rest, + parsed.tokens(), + parsed.syntax(), + parsed.unsupported_syntax_errors().is_empty(), + ) + .or_else(|| call_argument_unpacking_diagnostic(&parsed, prepared_source, parser_options)) + .or_else(|| unfinished_dict_comprehension_diagnostic(&parsed, parser_options)) + .map(|diagnostic| parser::ParseError { + error: ParseErrorType::OtherError(diagnostic.message), + location: diagnostic.range, + }) + .or_else(|| normalize_raise_parse_error(&parsed)) + .unwrap_or_else(|| first.clone()); + let mut error = CompileError::from_ruff_parse_error(normalized, source_file, mode); + if after_syntax_error && let CompileError::Parse(error) = &mut error { + error.is_unclosed_string = false; } - None + Err(error) } -fn invalid_group_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' => { - let Some(close) = matching_delimiter(bytes, index, b')') else { - index += 1; - continue; - }; - if let Some(error) = invalid_group_in_slice(bytes, index, close) { - return Some(error); - } - index = close + 1; - } - _ => index += 1, - } - } - None -} +/// Convert the sole parser error for an unparenthesized raise operand to +/// CPython's generic syntax error at the comma. Other tuple roles and recovery +/// involving more than one error retain the parser's original diagnostics. +pub fn normalize_raise_parse_error( + parsed: &parser::Parsed, +) -> Option { + use ast::visitor::Visitor; -fn invalid_parameter_star_annotation_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' => { - let Some(close) = matching_delimiter(bytes, index, b')') else { - index += 1; - continue; - }; - let mut param_start = index + 1; - while param_start < close { - let param_end = - find_byte_at_level(bytes, param_start, close, b',').unwrap_or(close); - if let Some(colon) = top_level_colon(bytes, param_start, param_end) { - let value_start = next_non_horizontal_whitespace(bytes, colon + 1); - if bytes.get(value_start) == Some(&b'*') { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - value_start, - value_start + 1, - )); - } - } - param_start = param_end.saturating_add(1); - } - index = close + 1; - } - _ => index += 1, - } + let [error] = parsed.errors() else { + return None; + }; + if !matches!(error.error, ParseErrorType::UnparenthesizedTupleExpression) + || !parsed.unsupported_syntax_errors().is_empty() + { + return None; } - None -} + let ast::Mod::Module(module) = parsed.syntax() else { + return None; + }; -fn invalid_def_type_params_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - _ if starts_identifier(bytes, index, b"def") => { - let name_start = skip_horizontal_whitespace(bytes, index + 3); - let name_end = identifier_end(bytes, name_start, bytes.len()); - let bracket = skip_horizontal_whitespace(bytes, name_end); - if bytes.get(bracket) == Some(&b'[') { - let Some(close) = matching_delimiter(bytes, bracket, b']') else { - index = bracket + 1; - continue; - }; - let after_close = skip_horizontal_whitespace(bytes, close + 1); - if bytes.get(after_close) == Some(&b'(') - && type_param_list_is_malformed(bytes, bracket + 1, close) - { - return Some(CpythonDiagnostic::new( - "expected '('".to_owned(), - bracket, - bracket + 1, - )); - } - } - index = name_end.max(index + 3); - } - _ => index += 1, - } + struct Statements<'a> { + range: ruff_text_size::TextRange, + pending: Vec<&'a ast::Stmt>, } - None -} -fn type_param_list_is_malformed(bytes: &[u8], start: usize, end: usize) -> bool { - let mut index = start; - let mut expect_item = true; - while index < end { - index = skip_horizontal_whitespace(bytes, index); - if index >= end { - break; - } - if bytes[index] == b',' { - if expect_item { - return true; - } - expect_item = true; - index += 1; - continue; - } - if !expect_item { - return true; - } - if bytes.get(index..index + 2) == Some(b"**") { - index += 2; - } else if bytes.get(index) == Some(&b'*') { - index += 1; - } - let item_start = skip_horizontal_whitespace(bytes, index); - let item_end = identifier_end(bytes, item_start, end); - if item_end == item_start { - return true; - } - index = item_end; - if bytes.get(skip_horizontal_whitespace(bytes, index)) == Some(&b':') { - index = skip_horizontal_whitespace(bytes, index) + 1; - while index < end && bytes[index] != b',' { - index = match bytes[index] { - b'\'' | b'"' => skip_quoted_string(bytes, index), - _ => index + 1, - }; + impl<'a> Visitor<'a> for Statements<'a> { + fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { + if stmt.range().contains_range(self.range) { + self.pending.push(stmt); } } - expect_item = false; - } - false -} -fn invalid_parameter_list_slice_error( - source: &str, - start: usize, - end: usize, - kind: ParameterListKind, -) -> Option { - let bytes = source.as_bytes(); - let mut index = start; - let mut level = 0usize; - let mut default_seen = false; - let mut keyword_only = false; - let mut slash_seen = false; - let mut var_keyword_seen = false; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - _ if level == 0 - && var_keyword_seen - && bytes.get(index).is_some_and(|byte| { - *byte >= 0x80 || *byte == b'_' || byte.is_ascii_alphabetic() - }) => - { - let name_end = identifier_end(bytes, index, end); - return Some(CpythonDiagnostic::new( - "arguments cannot follow var-keyword argument".to_owned(), - index, - name_end, - )); - } - _ if level == 0 - && !keyword_only - && bytes.get(index).is_some_and(|byte| { - *byte >= 0x80 || *byte == b'_' || byte.is_ascii_alphabetic() - }) => - { - let param_end = find_byte_at_level(bytes, index, end, b',') - .or_else(|| top_level_byte(bytes, index, end, b')')) - .or_else(|| { - matches!(kind, ParameterListKind::Lambda) - .then(|| top_level_byte(bytes, index, end, b':')) - .flatten() - }) - .unwrap_or(end); - let name_end = identifier_end(bytes, index, param_end); - if let Some(eq) = top_level_byte(bytes, index, param_end, b'=') { - let value_start = next_non_horizontal_whitespace(bytes, eq + 1); - if value_start >= param_end - || matches!(bytes.get(value_start), Some(b',' | b')' | b':')) - { - let message = if matches!(kind, ParameterListKind::Lambda) - && matches!(bytes.get(value_start), Some(b':')) - { - "invalid syntax" - } else { - "expected default value expression" - }; - return Some(CpythonDiagnostic::new(message.to_owned(), eq, eq + 1)); - } - default_seen = true; - } else if default_seen { - return Some(CpythonDiagnostic::new( - "parameter without a default follows parameter with a default".to_owned(), - index, - name_end, - )); - } - index = param_end; - } - b'(' if level == 0 => { - let close = matching_delimiter(bytes, index, b')') - .filter(|close| *close <= end) - .unwrap_or(index + 1); - let message = match kind { - ParameterListKind::Function => "Function parameters cannot be parenthesized", - ParameterListKind::Lambda => { - "Lambda expression parameters cannot be parenthesized" - } - }; - return Some(CpythonDiagnostic::new(message.to_owned(), index, close + 1)); - } - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b'/' if level == 0 => { - if var_keyword_seen { - return Some(CpythonDiagnostic::new( - "arguments cannot follow var-keyword argument".to_owned(), - index, - index + 1, - )); - } - if slash_seen { - return Some(CpythonDiagnostic::new( - "/ may appear only once".to_owned(), - index, - index + 1, - )); - } - slash_seen = true; - let next = next_non_horizontal_whitespace(bytes, index + 1); - if bytes.get(next) == Some(&b'*') { - return Some(CpythonDiagnostic::new( - "expected comma between / and *".to_owned(), - next, - next + 1, - )); - } - index += 1; - } - b'*' if level == 0 => { - if var_keyword_seen { - return Some(CpythonDiagnostic::new( - "arguments cannot follow var-keyword argument".to_owned(), - index, - index + 1, - )); - } - keyword_only = true; - let stars = usize::from(bytes.get(index + 1) == Some(&b'*')) + 1; - let name_start = next_non_horizontal_whitespace(bytes, index + stars); - for keyword in [b"True".as_slice(), b"False".as_slice(), b"None".as_slice()] { - if starts_identifier(bytes, name_start, keyword) { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - name_start, - name_start + keyword.len(), - )); - } - } - let param_end = find_byte_at_level(bytes, name_start, end, b',') - .or_else(|| top_level_byte(bytes, name_start, end, b')')) - .or_else(|| { - matches!(kind, ParameterListKind::Lambda) - .then(|| top_level_byte(bytes, name_start, end, b':')) - .flatten() - }) - .unwrap_or(end); - if stars == 1 && matches!(bytes.get(name_start), Some(b')' | b',' | b':')) { - return Some(CpythonDiagnostic::new( - "named arguments must follow bare *".to_owned(), - index, - index + 1, - )); - } - if stars == 1 && top_level_byte(bytes, name_start, param_end, b'=').is_some() { - return Some(CpythonDiagnostic::new( - "var-positional argument cannot have default value".to_owned(), - index, - index + 1, - )); - } - if stars == 2 && top_level_byte(bytes, name_start, param_end, b'=').is_some() { - return Some(CpythonDiagnostic::new( - "var-keyword argument cannot have default value".to_owned(), - index, - index + 2, - )); - } - if stars == 2 { - var_keyword_seen = true; - index = param_end; - continue; - } - index += stars; - } - b'=' if level == 0 => { - let value_start = next_non_horizontal_whitespace(bytes, index + 1); - if value_start >= end || matches!(bytes.get(value_start), Some(b',' | b')' | b':')) - { - if matches!(kind, ParameterListKind::Lambda) - && matches!(bytes.get(value_start), Some(b':')) - { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - index, - index + 1, - )); - } - return Some(CpythonDiagnostic::new( - "expected default value expression".to_owned(), - index, - index + 1, - )); - } - index += 1; - } - _ => index += 1, - } + fn visit_expr(&mut self, _: &'a ast::Expr) {} + + fn visit_pattern(&mut self, _: &'a ast::Pattern) {} } - None -} -fn invalid_parameter_list_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - _ if starts_identifier(bytes, index, b"def") => { - let Some(paren) = top_level_byte(bytes, index + 3, bytes.len(), b'(') else { - index += 3; - continue; - }; - let Some(close) = matching_delimiter(bytes, paren, b')') else { - index = paren + 1; - continue; - }; - if let Some(error) = invalid_parameter_list_slice_error( - source, - paren + 1, - close, - ParameterListKind::Function, - ) { - return Some(error); - } - index = close + 1; - } - _ if starts_identifier(bytes, index, b"lambda") => { - let params_start = index + 6; - let Some(params_end) = find_lambda_parameter_end(bytes, params_start) else { - index = params_start; - continue; - }; - if let Some(error) = invalid_parameter_list_slice_error( - source, - params_start, - params_end, - ParameterListKind::Lambda, - ) { - return Some(error); + // The recovered tree has not reached AST depth validation, so only collect + // immediate child statements per iteration and never recurse into operands. + let mut statements = Statements { + range: error.location, + pending: Vec::new(), + }; + statements.visit_body(&module.body); + while let Some(stmt) = statements.pending.pop() { + let ast::Stmt::Raise(raise) = stmt else { + ast::visitor::walk_stmt(&mut statements, stmt); + continue; + }; + let first_end = [raise.exc.as_deref(), raise.cause.as_deref()] + .into_iter() + .flatten() + .find_map(|expr| match expr { + ast::Expr::Tuple(tuple) + if !tuple.parenthesized && tuple.range() == error.location => + { + tuple.elts.first().map(Ranged::end) } - index = params_end + 1; - } - _ => index += 1, + _ => None, + }); + if let Some(first_end) = first_end { + let comma = parsed + .tokens() + .iter() + .take_while(|token| token.start() < error.location.end()) + .find(|token| token.start() >= first_end && token.kind() == TokenKind::Comma)?; + return Some(parser::ParseError { + error: ParseErrorType::OtherError("invalid syntax".to_owned()), + location: comma.range(), + }); } } None } -#[derive(Clone, Copy)] -struct CallArgFrame { - level: usize, - arg_start: Option, - in_call: bool, -} - -fn next_non_horizontal_whitespace(bytes: &[u8], mut index: usize) -> usize { - while matches!(bytes.get(index), Some(b' ' | b'\t' | b'\x0c')) { - index += 1; - } - index -} - -fn invalid_call_argument_assignment_error( - source: &str, - arg_start: usize, - equal: usize, +// A recovered call never parsed its comprehension clauses. For a narrowly owned +// whole-input argument list, ask the same parser to validate that exact slice once. +fn call_argument_unpacking_diagnostic( + parsed: &parser::Parsed, + prepared_source: &str, + options: &parser::ParseOptions, ) -> Option { - let bytes = source.as_bytes(); - let start = bytes[arg_start..equal] - .iter() - .rposition(|byte| *byte == b'\n') - .map_or(arg_start, |newline| arg_start + newline + 1); - let (target_start, target_end) = trim_target_range(bytes, start, equal); - if target_start >= target_end { + let first = parsed.errors().first()?; + if !matches!( + first.error, + ParseErrorType::ExpectedToken { + expected: TokenKind::Rpar, + found: TokenKind::For + } + ) || !parsed.unsupported_syntax_errors().is_empty() + || parsed + .errors() + .iter() + .any(|error| error.location.start() < first.location.start()) + { return None; } - let value_start = next_non_horizontal_whitespace(bytes, equal + 1); - if matches!(bytes.get(value_start), None | Some(b',' | b')')) { - return Some(CpythonDiagnostic::new( - "expected argument value expression".to_owned(), - target_start, - equal + 1, - )); - } - if bytes.get(target_start..target_start + 2) == Some(b"**") { - return Some(CpythonDiagnostic::new( - "cannot assign to keyword argument unpacking".to_owned(), - target_start, - value_start, - )); - } - if bytes.get(target_start) == Some(&b'*') { - return Some(CpythonDiagnostic::new( - "cannot assign to iterable argument unpacking".to_owned(), - target_start, - value_start, - )); + let ast::Mod::Module(module) = parsed.syntax() else { + return None; + }; + let ast::Stmt::Expr(statement) = module.body.first()? else { + return None; + }; + let ast::Expr::Call(call) = statement.value.as_ref() else { + return None; + }; + let [keyword] = call.arguments.keywords.as_slice() else { + return None; + }; + if !call.arguments.args.is_empty() + || keyword.arg.is_some() + || keyword.end() != call.arguments.end() + || call.end() != keyword.end() + { + return None; } - for keyword in [b"True".as_slice(), b"False".as_slice(), b"None".as_slice()] { - if bytes.get(target_start..target_end) == Some(keyword) { - let keyword = ::core::str::from_utf8(keyword).ok()?; - return Some(CpythonDiagnostic::new( - format!("cannot assign to {keyword}"), - target_start, - target_end, - )); - } + let tokens: Vec<_> = parsed + .tokens() + .iter() + .filter(|token| { + !matches!( + token.kind(), + TokenKind::Comment + | TokenKind::NonLogicalNewline + | TokenKind::Newline + | TokenKind::EndOfFile + ) + }) + .collect(); + if tokens.first()?.start() != call.start() { + return None; } - if is_simple_keyword_name(bytes, target_start, target_end) { - // NAME '=' expression for_if_clauses - if unparenthesized_comprehension(bytes, equal + 1) { - return Some(CpythonDiagnostic::new( - "invalid syntax. Maybe you meant '==' or ':=' instead of '='?".to_owned(), - target_start, - equal + 1, - )); - } + let opening_index = tokens + .iter() + .position(|token| token.start() == call.arguments.start())?; + let opening = tokens.get(opening_index)?; + let operator = tokens.get(opening_index.checked_add(1)?)?; + let closing = tokens.last()?; + let clause = tokens.iter().find(|token| token.start() >= keyword.end())?; + if opening.kind() != TokenKind::Lpar + || operator.kind() != TokenKind::DoubleStar + || operator.start() != keyword.start() + || closing.kind() != TokenKind::Rpar + || clause.range() != first.location + || clause.kind() != TokenKind::For + { return None; } - Some(CpythonDiagnostic::new( - "expression cannot contain assignment, perhaps you meant \"==\"?".to_owned(), - target_start, - equal, - )) -} - -fn unparenthesized_comprehension(bytes: &[u8], mut index: usize) -> bool { - index = next_non_horizontal_whitespace(bytes, index); - if index >= bytes.len() { - return false; + let slice = prepared_source.get(usize::from(opening.start())..usize::from(closing.end()))?; + let reparsed = parser::parse_unchecked( + slice, + parser::ParseOptions::from(parser::Mode::Expression) + .with_target_version(options.target_version()), + ); + let [error] = reparsed.errors() else { + return None; + }; + if !matches!(error.error, ParseErrorType::ExpectedExpression) + || !reparsed.unsupported_syntax_errors().is_empty() + || opening.start().checked_add(error.location.start())? != operator.start() + || opening.start().checked_add(error.location.end())? != operator.end() + { + return None; } - let start = index; - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - if level == 0 { - return false; - } - level -= 1; - index += 1; - } - b',' | b':' if level == 0 => return false, - _ if level == 0 && index > start && starts_identifier(bytes, index, b"for") => { - return true; - } - _ => index += 1, - } + let ast::Mod::Expression(expression) = reparsed.syntax() else { + return None; + }; + let ast::Expr::Generator(generator) = expression.body.as_ref() else { + return None; + }; + let ast::Expr::BinOp(binary) = generator.elt.as_ref() else { + return None; + }; + if !generator.parenthesized + || generator.start() != TextSize::new(0) + || usize::from(generator.end()) != slice.len() + || binary.end() != binary.right.end() + { + return None; } - false -} - -fn invalid_call_star_expression_error( - bytes: &[u8], - arg_start: usize, - index: usize, -) -> Option { - let start = next_non_horizontal_whitespace(bytes, arg_start); - if start != index || bytes.get(index) != Some(&b'*') { + // Both parses must retain the same unpacked operand, not just its operator. + if opening.start().checked_add(generator.elt.start())? != keyword.start() + || opening.start().checked_add(generator.elt.end())? != keyword.end() + || opening.start().checked_add(binary.right.start())? != keyword.value.start() + || opening.start().checked_add(binary.right.end())? != keyword.value.end() + { return None; } - let after_star = next_non_horizontal_whitespace(bytes, index + 1); - if matches!(bytes.get(after_star), None | Some(b',' | b')' | b':')) { - return Some(CpythonDiagnostic::new( - "Invalid star expression".to_owned(), - index, - (index + 1).min(bytes.len()), - )); + let diagnostic = owned_unpacking_diagnostic(error, reparsed.tokens(), reparsed.syntax())?; + if usize::from(diagnostic.range.end()) > slice.len() { + return None; } - None -} - -fn invalid_call_argument_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - let mut level = 0usize; - let mut frames: Vec = Vec::new(); - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - _ if starts_identifier(bytes, index, b"lambda") => { - let params_start = index + 6; - if let Some(params_end) = find_lambda_parameter_end(bytes, params_start) { - index = params_end + 1; - } else { - index = params_start; - } - } - b'(' => { - level += 1; - let in_call = opening_paren_is_call(bytes, index) - || frames.last().is_some_and(|frame| frame.in_call); - frames.push(CallArgFrame { - level, - arg_start: (in_call && !is_function_parameter_list(bytes, index)) - .then_some(index + 1), - in_call, - }); - index += 1; - } - b')' => { - if matches!(frames.last(), Some(frame) if frame.level == level) { - frames.pop(); - } - level = level.saturating_sub(1); - index += 1; - } - b'[' | b'{' => { - level += 1; - index += 1; - } - b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b',' => { - if let Some(frame) = frames.last_mut() - && frame.level == level - && frame.arg_start.is_some() - { - frame.arg_start = Some(index + 1); - } - index += 1; - } - b'*' => { - if let Some(CallArgFrame { - level: frame_level, - arg_start: Some(arg_start), - in_call: true, - }) = frames.last().copied() - && frame_level == level - && let Some(error) = invalid_call_star_expression_error(bytes, arg_start, index) - { - return Some(error); - } - index += 1; - } - b'=' if is_plain_assignment_operator(bytes, index) => { - if let Some(CallArgFrame { - level: frame_level, - arg_start: Some(arg_start), - in_call: true, - }) = frames.last().copied() - && frame_level == level - && let Some(error) = - invalid_call_argument_assignment_error(source, arg_start, index) - { - return Some(error); - } - index += 1; - } - _ => index += 1, + // Module recovery forgets the call's opening delimiter before reaching its + // closing token. Only the complete, balanced generator reparse above can + // justify treating this exact unmatched-closing error as a recovery shadow. + if parsed.errors().iter().any(|error| match &error.error { + ParseErrorType::Lexical(parser::LexicalErrorType::UnmatchedBracket { closing: ')' }) => { + !error.location.is_empty() || error.location.start() != closing.start() } + ParseErrorType::Lexical(_) => true, + _ => false, + }) { + return None; } - None + Some(CpythonDiagnostic { + message: diagnostic.message, + range: ruff_text_size::TextRange::new( + opening.start().checked_add(diagnostic.range.start())?, + opening.start().checked_add(diagnostic.range.end())?, + ), + }) } -fn top_level_colon(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b':' if level == 0 => return Some(index), - _ => index += 1, +// An unfinished unpacking comprehension can recover as an annotated assignment. +// Recognize only the complete, owned recovery cascade, not arbitrary later errors. +fn unfinished_dict_comprehension_diagnostic( + parsed: &parser::Parsed, + options: &parser::ParseOptions, +) -> Option { + let first = parsed.errors().first()?; + if !matches!( + first.error, + ParseErrorType::ExpectedToken { + expected: TokenKind::Rbrace, + found: TokenKind::Colon } + ) { + return None; } - None -} - -fn expression_slice_is_valid(source: &str, start: usize, end: usize) -> bool { - let bytes = source.as_bytes(); - let (start, end) = trim_target_range(bytes, start, end); - start < end - && parser::parse(&source[start..end], parser::Mode::Expression.into()) - .is_ok_and(|parsed| matches!(parsed.into_syntax(), ast::Mod::Expression(_))) -} - -fn invalid_dict_entry_error( - source: &str, - item_start: usize, - item_end: usize, - colon: Option, - saw_dict_item: bool, -) -> Option { - let bytes = source.as_bytes(); - let (item_start, item_end) = trim_target_range(bytes, item_start, item_end); - if item_start >= item_end { + let ast::Mod::Module(module) = parsed.syntax() else { + return None; + }; + let [ast::Stmt::AnnAssign(statement)] = module.body.as_slice() else { + return None; + }; + let ast::Expr::DictComp(dict) = statement.target.as_ref() else { + return None; + }; + if dict.key.is_some() + || dict.end() != dict.generators.last()?.end() + || statement.start() != dict.start() + || statement.value.is_some() + || statement.annotation.range().is_empty() + || statement.annotation.start() < first.location.end() + || statement.annotation.end() != statement.end() + { return None; } - if let Some(colon) = colon { - let value_start = next_non_horizontal_whitespace(bytes, colon + 1); - if value_start >= item_end { - return Some(CpythonDiagnostic::new( - "expression expected after dictionary key and ':'".to_owned(), - colon, - colon + 1, - )); - } - if bytes.get(value_start) == Some(&b'*') { - return Some(CpythonDiagnostic::new( - "cannot use a starred expression in a dictionary value".to_owned(), - value_start, - value_start + 1, - )); - } - if !expression_slice_is_valid(source, value_start, item_end) { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - value_start, - value_start, - )); - } - } else if saw_dict_item { - return Some(CpythonDiagnostic::new( - "':' expected after dictionary key".to_owned(), - item_end.saturating_sub(1), - item_end, - )); + let tokens: Vec<_> = parsed + .tokens() + .iter() + .filter(|token| { + !matches!( + token.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline | TokenKind::EndOfFile + ) + }) + .collect(); + let opening = tokens.first()?; + let operator = tokens.get(1)?; + if opening.kind() != TokenKind::Lbrace + || opening.start() != dict.start() + || operator.kind() != TokenKind::DoubleStar + || operator.end() > dict.value.start() + { + return None; } - None -} - -fn invalid_dict_literal_error( - source: &str, - open: usize, - close: usize, -) -> Option { - let bytes = source.as_bytes(); - let mut item_start = open + 1; - let mut index = item_start; - let mut level = 0usize; - let mut saw_dict_item = false; - let mut item_colon = None; - while index <= close { - if index == close || (level == 0 && bytes.get(index) == Some(&b',')) { - if let Some(error) = - invalid_dict_entry_error(source, item_start, index, item_colon, saw_dict_item) - { - return Some(error); - } - saw_dict_item |= item_colon.is_some(); - item_start = index + 1; - item_colon = None; - index += 1; - continue; - } - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b':' if level == 0 && item_colon.is_none() => { - item_colon = Some(index); - saw_dict_item = true; - index += 1; - } - _ => index += 1, - } + let colon = tokens.iter().find(|token| token.start() >= dict.end())?; + if colon.kind() != TokenKind::Colon || colon.range() != first.location { + return None; } - None -} - -fn invalid_dict_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'{' => { - let Some(close) = matching_delimiter(bytes, index, b'}') else { - index += 1; - continue; - }; - if top_level_colon(bytes, index + 1, close).is_some() - && let Some(error) = invalid_dict_literal_error(source, index, close) - { - return Some(error); - } - index = close + 1; - } - _ => index += 1, - } + let closing_index = tokens + .iter() + .position(|token| token.start() >= statement.end())?; + let closing = tokens.get(closing_index)?; + if closing.kind() != TokenKind::Rbrace { + return None; } - None -} - -fn collection_open_is_call(bytes: &[u8], open: usize) -> bool { - if bytes.get(open) != Some(&b'(') { - return false; + let newline = match tokens.get(closing_index.checked_add(1)?..)? { + [] => None, + [newline] if newline.kind() == TokenKind::Newline => Some(*newline), + _ => return None, + }; + let [unsupported] = parsed.unsupported_syntax_errors() else { + return None; + }; + // The payload enum is not exported. This exact DictComp/operator range owns + // the parser's DictInDict producer, excluding other comprehension features. + if !matches!( + unsupported.kind, + parser::UnsupportedSyntaxErrorKind::UnpackingInComprehension(_) + ) || unsupported.range != ruff_text_size::TextRange::new(operator.start(), dict.value.end()) + || unsupported.target_version != options.target_version() + { + return None; } - let mut cursor = open; - while cursor > 0 && matches!(bytes.get(cursor - 1), Some(b' ' | b'\t' | b'\x0c')) { - cursor -= 1; + let errors = parsed.errors(); + if errors.len() != 3 + usize::from(newline.is_some()) + || !matches!( + errors.get(1)?.error, + ParseErrorType::InvalidAnnotatedAssignmentTarget + ) + || errors.get(1)?.location != dict.range() + { + return None; } - matches!( - cursor.checked_sub(1).and_then(|before| bytes.get(before)), - Some(b')' | b']' | b'_' | b'a'..=b'z' | b'A'..=b'Z' | 0x80..=0xff) - ) -} - -fn invalid_collection_assignment_in_slice( - source: &str, - bytes: &[u8], - start: usize, - end: usize, -) -> Option { - let mut item_start = start; - let mut index = start; - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b',' if level == 0 => { - item_start = index + 1; - index += 1; - } - b'=' if level == 0 && is_plain_assignment_operator(bytes, index) => { - if top_level_colon(bytes, item_start, index).is_none() { - let start = next_non_horizontal_whitespace(bytes, item_start); - let target_end = trim_end_horizontal_whitespace(bytes, start, index); - if start < target_end - && let Some((expr_name, expr_start, expr_end, _)) = - expression_name_and_range(&source[start..target_end]) - { - if matches!(expr_name, "list" | "tuple") { - return None; - } - if matches!(expr_name, "expression" | "attribute" | "subscript") { - return Some(CpythonDiagnostic::new( - format!( - "cannot assign to {expr_name} here. Maybe you meant '==' instead of '='?" - ), - start + expr_start, - start + expr_end, - )); - } - } - return Some(CpythonDiagnostic::new( - "invalid syntax. Maybe you meant '==' or ':=' instead of '='?".to_owned(), - start, - index + 1, - )); - } - index += 1; - } - _ => index += 1, - } + let is_shadow = |error: &parser::ParseError, range| { + matches!(&error.error, ParseErrorType::OtherError(message) if message == "invalid syntax") + && error.location == range + }; + if !is_shadow(errors.get(2)?, closing.range()) + || newline.is_some_and(|newline| !is_shadow(&errors[3], newline.range())) + { + return None; } - None + Some(CpythonDiagnostic { + message: "cannot use dict unpacking here".to_owned(), + range: operator.range(), + }) } -fn invalid_collection_assignment_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - let close_byte = match bytes[index] { - b'(' => b')', - b'[' => b']', - _ => b'}', - }; - let Some(close) = matching_delimiter(bytes, index, close_byte) else { - index += 1; - continue; - }; - if !collection_open_is_call(bytes, index) - && let Some(error) = - invalid_collection_assignment_in_slice(source, bytes, index + 1, close) - { - return Some(error); - } - index = close + 1; - } - _ => index += 1, - } - } - None -} - -fn expression_assignment_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - let mut paren_arg_starts: Vec<(Option, bool)> = Vec::new(); - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - _ if starts_identifier(bytes, index, b"lambda") => { - let params_start = index + 6; - if let Some(params_end) = find_lambda_parameter_end(bytes, params_start) { - index = params_end + 1; - } else { - index = params_start; - } - } - b'(' => { - let in_call_context = opening_paren_is_call(bytes, index) - || paren_arg_starts.last().is_some_and(|(_, in_call)| *in_call); - paren_arg_starts.push(( - (!is_function_parameter_list(bytes, index)).then_some(index + 1), - in_call_context, - )); - index += 1; - } - b')' => { - paren_arg_starts.pop(); - index += 1; - } - b',' => { - if let Some((start, _)) = paren_arg_starts.last_mut() - && start.is_some() - { - *start = Some(index + 1); - } - index += 1; - } - b'=' if is_plain_assignment_operator(bytes, index) => { - if let Some((Some(start), true)) = paren_arg_starts.last().copied() - && !is_simple_keyword_name(bytes, start, index) - { - let mut expr_start = start; - while matches!(bytes.get(expr_start), Some(b' ' | b'\t' | b'\x0c')) { - expr_start += 1; - } - return Some(CpythonDiagnostic::new( - "expression cannot contain assignment, perhaps you meant \"==\"?" - .to_owned(), - expr_start, - index, - )); - } - index += 1; - } - _ => index += 1, - } - } - None -} - -fn invalid_named_expression_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index + 1 < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b':' if bytes.get(index + 1) == Some(&b'=') => { - let target_start = named_expression_target_start(bytes, index); - let target_end = trim_end_horizontal_whitespace(bytes, target_start, index); - if target_start < target_end - && let Some((expr_name, start, end, is_name)) = - expression_name_and_range(&source[target_start..target_end]) - && !is_name - { - return Some(CpythonDiagnostic::new( - format!("cannot use assignment expressions with {expr_name}"), - target_start + start, - target_start + end, - )); - } - index += 2; - } - _ => index += 1, - } - } - None -} - -#[derive(Clone, Copy)] -struct AssignmentContext { - start: usize, - call: bool, -} - -fn invalid_plain_assignment_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut stack: Vec = Vec::new(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - stack.push(AssignmentContext { - start: index + 1, - call: bytes[index] == b'(' && opening_paren_is_call(bytes, index), - }); - index += 1; - } - b')' | b']' | b'}' => { - stack.pop(); - index += 1; - } - b',' => { - if let Some(context) = stack.last_mut() - && !context.call - { - context.start = index + 1; - } - index += 1; - } - b'=' if is_plain_assignment_operator(bytes, index) => { - if let Some(context) = stack.last().copied() - && !context.call - { - let target_start = skip_horizontal_whitespace(bytes, context.start); - let target_end = trim_end_horizontal_whitespace(bytes, target_start, index); - if target_start < target_end - && let Some((expr_name, start, end, _)) = - expression_name_and_range(&source[target_start..target_end]) - && matches!(expr_name, "expression" | "attribute" | "subscript") - { - return Some(CpythonDiagnostic::new( - format!( - "cannot assign to {expr_name} here. Maybe you meant '==' instead of '='?" - ), - target_start + start, - target_start + end, - )); - } - } - index += 1; - } - _ => index += 1, - } - } - None -} - -fn opening_paren_is_call(bytes: &[u8], paren: usize) -> bool { - let mut cursor = paren; - while cursor > 0 && matches!(bytes[cursor - 1], b' ' | b'\t' | b'\x0c') { - cursor -= 1; - } - cursor > 0 - && (bytes[cursor - 1] >= 0x80 - || is_ascii_identifier_char(bytes[cursor - 1]) - || matches!(bytes[cursor - 1], b')' | b']')) -} - -fn named_expression_target_start(bytes: &[u8], walrus: usize) -> usize { - let mut index = walrus; - let mut level = 0usize; - while index > 0 { - index -= 1; - match bytes[index] { - b')' | b']' | b'}' => level += 1, - b'(' | b'[' | b'{' if level > 0 => level -= 1, - b'(' | b'[' | b'{' if level == 0 => return index + 1, - b',' | b'\n' | b';' if level == 0 => return index + 1, - _ => {} - } - } - 0 -} - -fn trim_end_horizontal_whitespace(bytes: &[u8], start: usize, mut end: usize) -> usize { - while end > start && matches!(bytes[end - 1], b' ' | b'\t' | b'\x0c') { - end -= 1; - } - end -} - -fn annotation_target_error_for_slice( - source: &str, - start: usize, - colon: usize, -) -> Option { - let bytes = source.as_bytes(); - let (target_start, target_end) = trim_target_range(bytes, start, colon); - if target_start >= target_end { - return None; - } - let target_text = &source[target_start..target_end]; - let Ok(parsed) = parser::parse(target_text, parser::Mode::Expression.into()) else { - return None; - }; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - return None; - }; - match expression.body.as_ref() { - ast::Expr::Name(_) | ast::Expr::Attribute(_) | ast::Expr::Subscript(_) => None, - ast::Expr::List(_) => Some(CpythonDiagnostic::new( - "only single target (not list) can be annotated".to_owned(), - target_start, - target_end, - )), - ast::Expr::Tuple(_) => Some(CpythonDiagnostic::new( - "only single target (not tuple) can be annotated".to_owned(), - target_start, - target_end, - )), - _ => Some(CpythonDiagnostic::new( - "illegal target for annotation".to_owned(), - target_start, - target_end, - )), - } -} - -fn invalid_annotation_line_start(bytes: &[u8], line_start: usize) -> bool { - let column = skip_horizontal_whitespace(bytes, line_start); - for keyword in [ - b"async".as_slice(), - b"case", - b"class", - b"def", - b"elif", - b"else", - b"except", - b"finally", - b"for", - b"if", - b"match", - b"try", - b"while", - b"with", - ] { - if starts_identifier(bytes, column, keyword) { - return false; - } - } - true -} - -fn invalid_annotation_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - if invalid_annotation_line_start(bytes, line_start) - && let Some(colon) = find_byte_at_level(bytes, line_start, line_end, b':') - && bytes.get(colon + 1) != Some(&b'=') - && colon.checked_sub(1).and_then(|before| bytes.get(before)) != Some(&b':') - && let Some(error) = annotation_target_error_for_slice(source, line_start, colon) - { - return Some(error); - } - line_start = line_end; - } - None -} - -fn statement_target_end(bytes: &[u8], mut index: usize) -> usize { - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' if level == 0 => return index, - b'\n' | b';' if level == 0 => return index, - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ => index += 1, - } - } - index -} - -fn invalid_assignment_target(expression: &ast::Expr) -> Option<&ast::Expr> { - match expression { - ast::Expr::List(ast::ExprList { elts, .. }) - | ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => { - elts.iter().find_map(invalid_assignment_target) - } - ast::Expr::Starred(ast::ExprStarred { value, .. }) => invalid_assignment_target(value), - ast::Expr::Name(_) | ast::Expr::Subscript(_) | ast::Expr::Attribute(_) => None, - _ => Some(expression), - } -} - -fn invalid_for_target(expression: &ast::Expr) -> Option<&ast::Expr> { - match expression { - ast::Expr::List(ast::ExprList { elts, .. }) - | ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => elts.iter().find_map(invalid_for_target), - ast::Expr::Starred(ast::ExprStarred { value, .. }) => invalid_for_target(value), - ast::Expr::Compare(ast::ExprCompare { left, ops, .. }) => { - if matches!(ops.first(), Some(ast::CmpOp::In)) { - invalid_for_target(left) - } else { - None - } - } - ast::Expr::Name(_) | ast::Expr::Subscript(_) | ast::Expr::Attribute(_) => None, - _ => Some(expression), - } -} - -fn invalid_delete_target(expression: &ast::Expr) -> Option<&ast::Expr> { - match expression { - ast::Expr::List(ast::ExprList { elts, .. }) - | ast::Expr::Tuple(ast::ExprTuple { elts, .. }) => { - elts.iter().find_map(invalid_delete_target) - } - ast::Expr::Name(_) | ast::Expr::Subscript(_) | ast::Expr::Attribute(_) => None, - ast::Expr::Starred(_) => Some(expression), - ast::Expr::Compare(_) => Some(expression), - _ => Some(expression), - } -} - -fn delete_target_expr_name(expression: &ast::Expr) -> &'static str { - match expression { - ast::Expr::Attribute(_) => "attribute", - ast::Expr::Subscript(_) => "subscript", - ast::Expr::Starred(_) => "starred", - ast::Expr::Name(_) => "name", - ast::Expr::List(_) => "list", - ast::Expr::Tuple(_) => "tuple", - ast::Expr::Lambda(_) => "lambda", - ast::Expr::Call(_) => "function call", - ast::Expr::BoolOp(_) | ast::Expr::BinOp(_) | ast::Expr::UnaryOp(_) => "expression", - ast::Expr::Generator(_) => "generator expression", - ast::Expr::Yield(_) | ast::Expr::YieldFrom(_) => "yield expression", - ast::Expr::Await(_) => "await expression", - ast::Expr::ListComp(_) => "list comprehension", - ast::Expr::SetComp(_) => "set comprehension", - ast::Expr::DictComp(_) => "dict comprehension", - ast::Expr::Dict(_) => "dict literal", - ast::Expr::Set(_) => "set display", - ast::Expr::FString(_) => "f-string expression", - ast::Expr::TString(_) => "t-string expression", - ast::Expr::NumberLiteral(_) | ast::Expr::StringLiteral(_) | ast::Expr::BytesLiteral(_) => { - "literal" - } - ast::Expr::Constant(expr) => match &expr.value { - ast::ConstantValue::None => "None", - ast::ConstantValue::Boolean(true) => "True", - ast::ConstantValue::Boolean(false) => "False", - ast::ConstantValue::Ellipsis => "ellipsis", - ast::ConstantValue::Tuple(_) => "tuple", - ast::ConstantValue::Frozenset(_) => "literal", - ast::ConstantValue::Str(_) - | ast::ConstantValue::Bytes(_) - | ast::ConstantValue::Integer(_) - | ast::ConstantValue::Float(_) - | ast::ConstantValue::Complex { .. } => "literal", - }, - ast::Expr::BooleanLiteral(boolean) => { - if boolean.value { - "True" - } else { - "False" - } - } - ast::Expr::NoneLiteral(_) => "None", - ast::Expr::EllipsisLiteral(_) => "ellipsis", - ast::Expr::Compare(_) => "comparison", - ast::Expr::If(_) => "conditional expression", - ast::Expr::Named(_) => "named expression", - ast::Expr::Slice(_) | ast::Expr::IpyEscapeCommand(_) => "expression", - } -} - -fn parenthesized_single_starred_delete_target(bytes: &[u8], start: usize, end: usize) -> bool { - let mut cursor = start; - while matches!(bytes.get(cursor), Some(b' ' | b'\t' | b'\x0c')) { - cursor += 1; - } - if bytes.get(cursor) != Some(&b'(') { - return false; - } - cursor += 1; - while matches!(bytes.get(cursor), Some(b' ' | b'\t' | b'\x0c')) { - cursor += 1; - } - if bytes.get(cursor) != Some(&b'*') { - return false; - } - let mut level = 1usize; - cursor += 1; - while cursor < end { - match bytes[cursor] { - b'\'' | b'"' => { - cursor = skip_quoted_string(bytes, cursor); - } - b'(' | b'[' | b'{' => { - level += 1; - cursor += 1; - } - b')' => { - level = level.saturating_sub(1); - if level == 0 { - cursor += 1; - while matches!(bytes.get(cursor), Some(b' ' | b'\t' | b'\x0c')) { - cursor += 1; - } - return cursor == end; - } - cursor += 1; - } - b',' if level == 1 => return false, - b']' | b'}' => { - level = level.saturating_sub(1); - cursor += 1; - } - _ => cursor += 1, - } - } - false -} - -fn assignment_target_expr_range(source: &str, start: usize, end: usize) -> Option<(usize, usize)> { - let bytes = source.as_bytes(); - let (target_start, target_end) = trim_target_range(bytes, start, end); - if target_start >= target_end { - return None; - } - if parser::parse( - &source[target_start..target_end], - parser::Mode::Expression.into(), - ) - .is_ok() - { - return Some((target_start, target_end)); - } - // `def f(): (yield bar)` — skip the suite header so the remaining - // text is the assignment target expression. Other colons (`x: int += 1`) - // are not suite headers for this diagnostic. Grouping parentheses may - // wrap the yield expression. - let colon = top_level_colon(bytes, target_start, target_end)?; - let after = skip_horizontal_whitespace(bytes, colon + 1); - let yield_at = skip_opening_parentheses(bytes, after, target_end); - if yield_at >= target_end || !starts_identifier(bytes, yield_at, b"yield") { - return None; - } - Some((after, target_end)) -} - -fn skip_opening_parentheses(bytes: &[u8], mut index: usize, end: usize) -> usize { - loop { - index = skip_horizontal_whitespace(bytes, index); - if index >= end || bytes[index] != b'(' { - return index; - } - index += 1; - } -} - -fn trim_target_range(bytes: &[u8], mut start: usize, mut end: usize) -> (usize, usize) { - while start < end - && matches!( - bytes.get(start), - Some(b' ' | b'\t' | b'\n' | b'\r' | b'\x0c') - ) - { - start += 1; - } - while end > start - && matches!( - bytes.get(end - 1), - Some(b' ' | b'\t' | b'\n' | b'\r' | b'\x0c') - ) - { - end -= 1; - } - (start, end) -} - -fn invalid_assignment_message(name: &'static str, top_level_bitwise: bool) -> String { - if top_level_bitwise { - format!("cannot assign to {name} here. Maybe you meant '==' instead of '='?") - } else { - format!("cannot assign to {name}") - } -} - -fn assignment_target_error_for_slice( - source: &str, - start: usize, - end: usize, -) -> Option { - let bytes = source.as_bytes(); - let (target_start, target_end) = assignment_target_expr_range(source, start, end)?; - if starts_identifier(bytes, target_start, b"yield") { - return Some(CpythonDiagnostic::new( - "assignment to yield expression not possible".to_owned(), - target_start, - target_start + 5, - )); - } - let target_text = &source[target_start..target_end]; - let Ok(parsed) = parser::parse(target_text, parser::Mode::Expression.into()) else { - return None; - }; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - return None; - }; - let invalid_target = invalid_assignment_target(&expression.body)?; - let invalid_start = target_start + invalid_target.range().start().to_usize(); - let invalid_end = target_start + invalid_target.range().end().to_usize(); - let name = delete_target_expr_name(invalid_target); - let top_level = invalid_target.range() == expression.body.range(); - let bitwise_like = matches!( - invalid_target, - ast::Expr::Call(_) - | ast::Expr::BoolOp(_) - | ast::Expr::BinOp(_) - | ast::Expr::UnaryOp(_) - | ast::Expr::NumberLiteral(_) - | ast::Expr::StringLiteral(_) - | ast::Expr::BytesLiteral(_) - | ast::Expr::EllipsisLiteral(_) - | ast::Expr::Yield(_) - | ast::Expr::YieldFrom(_) - | ast::Expr::Set(_) - | ast::Expr::Dict(_) - | ast::Expr::FString(_) - | ast::Expr::TString(_) - ); - Some(CpythonDiagnostic::new( - invalid_assignment_message(name, top_level && bitwise_like), - invalid_start, - invalid_end, - )) -} - -fn star_target_error_for_slice( - source: &str, - start: usize, - end: usize, -) -> Option { - invalid_target_error_for_slice(source, start, end, invalid_assignment_target) -} - -fn for_target_error_for_slice(source: &str, start: usize, end: usize) -> Option { - invalid_target_error_for_slice(source, start, end, invalid_for_target) -} - -fn invalid_target_error_for_slice( - source: &str, - start: usize, - end: usize, - invalid_target: for<'a> fn(&'a ast::Expr) -> Option<&'a ast::Expr>, -) -> Option { - let bytes = source.as_bytes(); - let (target_start, target_end) = trim_target_range(bytes, start, end); - if target_start >= target_end { - return None; - } - let target_text = &source[target_start..target_end]; - let Ok(parsed) = parser::parse(target_text, parser::Mode::Expression.into()) else { - return None; - }; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - return None; - }; - let invalid_target = invalid_target(&expression.body)?; - let name = delete_target_expr_name(invalid_target); - let invalid_start = target_start + invalid_target.range().start().to_usize(); - let invalid_end = target_start + invalid_target.range().end().to_usize(); - Some(CpythonDiagnostic::new( - format!("cannot assign to {name}"), - invalid_start, - invalid_end, - )) -} - -fn first_compare_operator_at_level(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b'<' | b'>' if level == 0 => return Some(index), - b'=' if level == 0 && bytes.get(index + 1) == Some(&b'=') => return Some(index), - b'!' if level == 0 && bytes.get(index + 1) == Some(&b'=') => return Some(index), - _ if level == 0 && starts_identifier(bytes, index, b"is") => return Some(index), - _ if level == 0 && starts_identifier(bytes, index, b"not") => return Some(index), - _ => index += 1, - } - } - None -} - -fn non_in_compare_for_target_error( - source: &str, - start: usize, - end: usize, -) -> Option { - let bytes = source.as_bytes(); - let (target_start, target_end) = trim_target_range(bytes, start, end); - if target_start >= target_end { - return None; - } - let target_text = &source[target_start..target_end]; - let Ok(parsed) = parser::parse(target_text, parser::Mode::Expression.into()) else { - return None; - }; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - return None; - }; - let ast::Expr::Compare(ast::ExprCompare { ops, .. }) = expression.body.as_ref() else { - return None; - }; - if matches!(ops.first(), Some(ast::CmpOp::In)) { - return None; - } - let operator = first_compare_operator_at_level(bytes, target_start, target_end)?; - Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - operator, - (operator + 1).min(target_end), - )) -} - -fn top_level_plain_assignment_offsets(bytes: &[u8]) -> Vec { - let mut offsets = Vec::new(); - let mut index = 0usize; - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' if level == 0 => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b'=' if level == 0 && is_plain_assignment_operator(bytes, index) => { - offsets.push(index); - index += 1; - } - _ => index += 1, - } - } - offsets -} - -fn invalid_condition_assignment_error( - source: &str, - parse_error_offset: usize, -) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - let mut line_start = 0usize; - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' if level == 0 => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\n' => { - line_start = index + 1; - index += 1; - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ if level == 0 - && index == skip_horizontal_whitespace(bytes, line_start) - && (starts_identifier(bytes, index, b"if") - || starts_identifier(bytes, index, b"elif") - || starts_identifier(bytes, index, b"while")) => - { - let keyword_len = if starts_identifier(bytes, index, b"while") { - 5 - } else if starts_identifier(bytes, index, b"elif") { - 4 - } else { - 2 - }; - let cond_start = skip_horizontal_whitespace(bytes, index + keyword_len); - let Some(colon) = top_level_colon(bytes, cond_start, bytes.len()) else { - index += keyword_len; - continue; - }; - if parse_error_offset < index || parse_error_offset > colon { - index += keyword_len; - continue; - } - let Some(equal) = condition_plain_assignment(bytes, cond_start, colon) else { - index += keyword_len; - continue; - }; - let (target_start, target_end) = trim_target_range(bytes, cond_start, equal); - if target_start >= target_end { - index += keyword_len; - continue; - } - if is_simple_keyword_name(bytes, target_start, target_end) { - return Some(CpythonDiagnostic::new( - "invalid syntax. Maybe you meant '==' or ':=' instead of '='?".to_owned(), - target_start, - equal + 1, - )); - } - if let Some((expr_name, start, end, _)) = - expression_name_and_range(&source[target_start..target_end]) - { - return Some(CpythonDiagnostic::new( - format!( - "cannot assign to {expr_name} here. Maybe you meant '==' instead of '='?" - ), - target_start + start, - target_start + end, - )); - } - return Some(CpythonDiagnostic::new( - "invalid syntax. Maybe you meant '==' or ':=' instead of '='?".to_owned(), - target_start, - equal + 1, - )); - } - _ => index += 1, - } - } - None -} - -fn condition_plain_assignment(bytes: &[u8], start: usize, end: usize) -> Option { - let mut index = start; - let mut nest = Vec::new(); - while index < end { - match bytes[index] { - b'#' => { - while index < end && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' => { - nest.push(if is_call_open(bytes, start, index) { - b'c' - } else { - b'g' - }); - index += 1; - } - b'[' => { - nest.push(b'['); - index += 1; - } - b'{' => { - nest.push(b'{'); - index += 1; - } - b')' | b']' | b'}' => { - nest.pop(); - index += 1; - } - b':' if nest.last() == Some(&b'l') => { - nest.pop(); - index += 1; - } - b'=' if is_plain_assignment_operator(bytes, index) - && !nest.contains(&b'c') - && !nest.contains(&b'l') => - { - return Some(index); - } - _ if starts_identifier(bytes, index, b"lambda") => { - nest.push(b'l'); - index += 6; - } - _ => index += 1, - } - } - None -} - -fn is_call_open(bytes: &[u8], start: usize, open: usize) -> bool { - let mut index = open; - while index > start { - index -= 1; - match bytes[index] { - b' ' | b'\t' | b'\n' | b'\r' | b'\x0c' => {} - b')' | b']' => return true, - byte if byte >= 0x80 || is_ascii_identifier_char(byte) => { - let mut ident_start = index; - while ident_start > start - && bytes - .get(ident_start - 1) - .is_some_and(|b| *b >= 0x80 || is_ascii_identifier_char(*b)) - { - ident_start -= 1; - } - return !is_condition_keyword(&bytes[ident_start..=index]); - } - _ => return false, - } - } - false -} - -fn is_condition_keyword(word: &[u8]) -> bool { - matches!( - word, - b"not" | b"and" | b"or" | b"in" | b"is" | b"if" | b"elif" | b"while" | b"await" | b"lambda" - ) -} - -fn invalid_assignment_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let offsets = top_level_plain_assignment_offsets(bytes); - if offsets.is_empty() { - return None; - } - let mut start = 0usize; - for offset in offsets { - if let Some(error) = assignment_target_error_for_slice(source, start, offset) { - return Some(error); - } - start = offset + 1; - } - None -} - -fn top_level_augassign_offset(bytes: &[u8]) -> Option<(usize, usize)> { - let mut index = 0usize; - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' if level == 0 => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b'+' | b'-' | b'*' | b'@' | b'/' | b'%' | b'&' | b'|' | b'^' - if level == 0 && bytes.get(index + 1) == Some(&b'=') => - { - return Some((index, 2)); - } - b'<' | b'>' - if level == 0 - && bytes.get(index + 1) == Some(&bytes[index]) - && bytes.get(index + 2) == Some(&b'=') => - { - return Some((index, 3)); - } - b'*' if level == 0 - && bytes.get(index + 1) == Some(&b'*') - && bytes.get(index + 2) == Some(&b'=') => - { - return Some((index, 3)); - } - b'/' if level == 0 - && bytes.get(index + 1) == Some(&b'/') - && bytes.get(index + 2) == Some(&b'=') => - { - return Some((index, 3)); - } - _ => index += 1, - } - } - None -} - -fn invalid_augassign_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let (operator, _) = top_level_augassign_offset(bytes)?; - let (target_start, target_end) = assignment_target_expr_range(source, 0, operator)?; - let target_text = &source[target_start..target_end]; - let Ok(parsed) = parser::parse(target_text, parser::Mode::Expression.into()) else { - return None; - }; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - return None; - }; - let name = delete_target_expr_name(&expression.body); - Some(CpythonDiagnostic::new( - format!("'{name}' is an illegal expression for augmented assignment"), - target_start, - target_end, - )) -} - -fn find_for_target_delimiter(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'#' if level == 0 => return None, - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ if level == 0 && starts_identifier(bytes, index, b"in") => return Some(index), - b':' if level == 0 => return Some(index), - _ => index += 1, - } - } - None -} - -fn invalid_for_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - _ if starts_identifier(bytes, index, b"for") => { - let target_start = skip_horizontal_whitespace(bytes, index + 3); - let line_end = source[index..] - .find('\n') - .map_or(bytes.len(), |newline| index + newline); - if let Some(target_end) = find_for_target_delimiter(bytes, target_start, line_end) { - if let Some(error) = - for_target_error_for_slice(source, target_start, target_end) - { - return Some(error); - } - if let Some(error) = - non_in_compare_for_target_error(source, target_start, target_end) - { - return Some(error); - } - } - index = target_start.max(index + 3); - } - _ => index += 1, - } - } - None -} - -fn find_with_target_delimiter(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'#' if level == 0 => return None, - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' if level == 0 => return Some(index), - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b',' | b':' if level == 0 => return Some(index), - _ => index += 1, - } - } - None -} - -fn invalid_with_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - let mut column = skip_horizontal_whitespace(bytes, line_start); - if starts_identifier(bytes, column, b"async") { - column = skip_horizontal_whitespace(bytes, column + 5); - } - if !starts_identifier(bytes, column, b"with") { - line_start = line_end; - continue; - } - let mut index = column + 4; - while let Some(as_index) = find_keyword_at_level(bytes, index, line_end, b"as") { - let target_start = skip_horizontal_whitespace(bytes, as_index + 2); - if let Some(target_end) = find_with_target_delimiter(bytes, target_start, line_end) { - if let Some(error) = star_target_error_for_slice(source, target_start, target_end) { - return Some(error); - } - index = target_end.saturating_add(1); - } else { - break; - } - } - line_start = line_end; - } - None -} - -fn find_missing_in_if_keyword(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'#' if level == 0 => return None, - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' if level == 0 => return None, - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ if level == 0 && starts_identifier(bytes, index, b"in") => return None, - _ if level == 0 && starts_identifier(bytes, index, b"if") => return Some(index), - _ => index += 1, - } - } - None -} - -fn invalid_for_if_clause_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0usize; - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' if level == 0 => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ if level > 0 && starts_identifier(bytes, index, b"for") => { - let target_start = skip_horizontal_whitespace(bytes, index + 3); - let line_end = source[index..] - .find('\n') - .map_or(bytes.len(), |newline| index + newline); - if let Some(if_index) = find_missing_in_if_keyword(bytes, target_start, line_end) { - return Some(CpythonDiagnostic::new( - "'in' expected after for-loop variables".to_owned(), - if_index, - (if_index + 2).min(line_end), - )); - } - index = target_start.max(index + 3); - } - _ => index += 1, - } - } - None -} - -fn invalid_delete_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'd' if starts_identifier(bytes, index, b"del") => { - let mut target_start = index + 3; - if !matches!(bytes.get(target_start), Some(b' ' | b'\t' | b'\x0c')) { - index += 3; - continue; - } - while matches!(bytes.get(target_start), Some(b' ' | b'\t' | b'\x0c')) { - target_start += 1; - } - let mut target_end = statement_target_end(bytes, target_start); - while target_end > target_start - && matches!(bytes.get(target_end - 1), Some(b' ' | b'\t' | b'\x0c')) - { - target_end -= 1; - } - if target_start >= target_end { - index = target_end.max(index + 3); - continue; - } - if parenthesized_single_starred_delete_target(bytes, target_start, target_end) { - return Some(CpythonDiagnostic::new( - "cannot use starred expression here".to_owned(), - target_start, - target_end, - )); - } - if bytes.get(target_start) == Some(&b'*') { - return Some(CpythonDiagnostic::new( - "cannot delete starred".to_owned(), - target_start, - (target_start + 1).min(target_end), - )); - } - let target_text = &source[target_start..target_end]; - let Ok(parsed) = parser::parse(target_text, parser::Mode::Expression.into()) else { - index = target_end; - continue; - }; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - index = target_end; - continue; - }; - let Some(invalid_target) = invalid_delete_target(&expression.body) else { - index = target_end; - continue; - }; - let start = target_start + invalid_target.range().start().to_usize(); - let end = target_start + invalid_target.range().end().to_usize(); - if matches!(invalid_target, ast::Expr::FString(_)) { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - start, - end, - )); - } - let name = delete_target_expr_name(invalid_target); - return Some(CpythonDiagnostic::new( - format!("cannot delete {name}"), - start, - end, - )); - } - _ => index += 1, - } - } - None -} - -fn skip_horizontal_whitespace(bytes: &[u8], mut index: usize) -> usize { - while matches!(bytes.get(index), Some(b' ' | b'\t' | b'\x0c')) { - index += 1; - } - index -} - -fn find_keyword_at_level( - bytes: &[u8], - mut index: usize, - end: usize, - keyword: &[u8], -) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'#' if level == 0 => return None, - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ if level == 0 && starts_identifier(bytes, index, keyword) => return Some(index), - _ => index += 1, - } - } - None -} - -fn find_byte_at_level(bytes: &[u8], mut index: usize, end: usize, needle: u8) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'#' if level == 0 => return None, - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - byte if level == 0 && byte == needle => return Some(index), - _ => index += 1, - } - } - None -} - -fn expression_name_and_range(source: &str) -> Option<(&'static str, usize, usize, bool)> { - let parsed = parser::parse(source, parser::Mode::Expression.into()).ok()?; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - return None; - }; - let is_name = matches!(expression.body.as_ref(), ast::Expr::Name(_)); - Some(( - delete_target_expr_name(&expression.body), - expression.body.range().start().to_usize(), - expression.body.range().end().to_usize(), - is_name, - )) -} - -fn invalid_standalone_except_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - let mut seen_try = false; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - let column = skip_horizontal_whitespace(bytes, line_start); - if column >= line_end { - line_start = line_end; - continue; - } - if starts_identifier(bytes, column, b"try") { - seen_try = true; - } else if (bytes.get(column..column + 7) == Some(b"except*") - || starts_identifier(bytes, column, b"except")) - && !seen_try - { - let end = if bytes.get(column..column + 7) == Some(b"except*") { - column + 7 - } else { - column + 6 - }; - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - column, - end, - )); - } - line_start = line_end; - } - None -} - -fn invalid_import_statement_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - let column = skip_horizontal_whitespace(bytes, line_start); - if column < line_end - && starts_identifier(bytes, column, b"import") - && find_keyword_at_level(bytes, column + 6, line_end, b"from").is_some() - { - return Some(CpythonDiagnostic::new( - "Did you mean to use 'from ... import ...' instead?".to_owned(), - column, - column + 6, - )); - } - line_start = line_end; - } - None -} - -fn import_as_target_end(bytes: &[u8], mut index: usize) -> usize { - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' if level == 0 => return index, - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' if level == 0 => return index, - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b',' | b';' | b'\n' if level == 0 => return index, - _ => index += 1, - } - } - index -} - -fn valid_import_alias_name(bytes: &[u8], mut start: usize, end: usize) -> bool { - start = skip_horizontal_whitespace(bytes, start); - let Some(&first) = bytes.get(start) else { - return false; - }; - if !(first == b'_' || first.is_ascii_alphabetic() || first >= 0x80) { - return false; - } - let mut index = start + 1; - while index < end { - match bytes[index] { - b' ' | b'\t' | b'\x0c' => break, - byte if byte >= 0x80 || is_ascii_identifier_char(byte) => index += 1, - _ => return false, - } - } - let index = skip_horizontal_whitespace(bytes, index); - matches!( - bytes.get(index), - None | Some(b',' | b')' | b';' | b'\n' | b'\r') - ) -} - -fn import_target_error_for_slice( - source: &str, - start: usize, - end: usize, -) -> Option { - let bytes = source.as_bytes(); - let (target_start, target_end) = trim_target_range(bytes, start, end); - if target_start >= target_end || valid_import_alias_name(bytes, target_start, target_end) { - return None; - } - let parsed = parser::parse( - &source[target_start..target_end], - parser::Mode::Expression.into(), - ) - .ok()?; - let ast::Mod::Expression(expression) = parsed.into_syntax() else { - return None; - }; - let name = delete_target_expr_name(&expression.body); - let start = target_start + expression.body.range().start().to_usize(); - let end = target_start + expression.body.range().end().to_usize(); - Some(CpythonDiagnostic::new( - format!("cannot use {name} as import target"), - start, - end, - )) -} - -fn statement_starts_import(bytes: &[u8], line_start: usize, line_end: usize) -> bool { - let column = skip_horizontal_whitespace(bytes, line_start); - if starts_identifier(bytes, column, b"import") { - return true; - } - starts_identifier(bytes, column, b"from") - && find_keyword_at_level(bytes, column + 4, line_end, b"import").is_some() -} - -fn invalid_import_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - let mut in_parenthesized_from_import = false; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - let starts_import = statement_starts_import(bytes, line_start, line_end); - if starts_import && bytes[line_start..line_end].contains(&b'(') { - in_parenthesized_from_import = true; - } - if starts_import || in_parenthesized_from_import { - let mut index = line_start; - while index < line_end { - if starts_identifier(bytes, index, b"as") { - let target_start = skip_horizontal_whitespace(bytes, index + 2); - let target_end = import_as_target_end(bytes, target_start); - if let Some(error) = - import_target_error_for_slice(source, target_start, target_end) - { - return Some(error); - } - index = target_end.max(index + 2); - } else { - index += 1; - } - } - } - if in_parenthesized_from_import && bytes[line_start..line_end].contains(&b')') { - in_parenthesized_from_import = false; - } - line_start = line_end; - } - None -} - -fn invalid_except_as_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - let mut seen_try = false; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - let mut column = skip_horizontal_whitespace(bytes, line_start); - if column >= line_end { - line_start = line_end; - continue; - } - if starts_identifier(bytes, column, b"try") { - seen_try = true; - line_start = line_end; - continue; - } - let (keyword_len, starred) = if bytes.get(column..column + 7) == Some(b"except*") { - (7, true) - } else if starts_identifier(bytes, column, b"except") { - (6, false) - } else { - line_start = line_end; - continue; - }; - if !seen_try { - line_start = line_end; - continue; - } - column += keyword_len; - let Some(as_index) = find_keyword_at_level(bytes, column, line_end, b"as") else { - line_start = line_end; - continue; - }; - let target_start = skip_horizontal_whitespace(bytes, as_index + 2); - let Some(delimiter) = find_byte_at_level(bytes, target_start, line_end, b':') - .into_iter() - .chain(find_byte_at_level(bytes, target_start, line_end, b',')) - .min() - else { - line_start = line_end; - continue; - }; - let mut target_end = delimiter; - while target_end > target_start - && matches!(bytes.get(target_end - 1), Some(b' ' | b'\t' | b'\x0c')) - { - target_end -= 1; - } - let Some((expr_name, start, end, is_name)) = - expression_name_and_range(&source[target_start..target_end]) - else { - line_start = line_end; - continue; - }; - if !is_name { - let statement = if starred { "except*" } else { "except" }; - return Some(CpythonDiagnostic::new( - format!("cannot use {statement} statement with {expr_name}"), - target_start + start, - target_start + end, - )); - } - line_start = line_end; - } - None -} - -fn invalid_match_as_target_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let quoted_ranges = quoted_string_ranges(bytes); - let mut quoted_range = 0usize; - let mut line_start = 0usize; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - let mut column = skip_horizontal_whitespace(bytes, line_start); - if column >= line_end - || offset_in_ranges("ed_ranges, &mut quoted_range, column) - || !starts_identifier(bytes, column, b"case") - { - line_start = line_end; - continue; - } - column += 4; - let Some(as_index) = find_keyword_at_level(bytes, column, line_end, b"as") else { - line_start = line_end; - continue; - }; - let target_start = skip_horizontal_whitespace(bytes, as_index + 2); - let Some(delimiter) = find_byte_at_level(bytes, target_start, line_end, b':') - .into_iter() - .chain(find_byte_at_level(bytes, target_start, line_end, b',')) - .min() - else { - line_start = line_end; - continue; - }; - let mut target_end = delimiter; - while target_end > target_start - && matches!(bytes.get(target_end - 1), Some(b' ' | b'\t' | b'\x0c')) - { - target_end -= 1; - } - if source[target_start..target_end].trim() == "_" { - return Some(CpythonDiagnostic::new( - "cannot use '_' as a target".to_owned(), - target_start, - target_end, - )); - } - let Some((expr_name, start, end, is_name)) = - expression_name_and_range(&source[target_start..target_end]) - else { - line_start = line_end; - continue; - }; - if !is_name { - if matches!(expr_name, "expression" | "subscript") { - line_start = line_end; - continue; - } - return Some(CpythonDiagnostic::new( - format!("cannot use {expr_name} as pattern target"), - target_start + start, - target_start + end, - )); - } - line_start = line_end; - } - None -} - -fn quoted_string_ranges(bytes: &[u8]) -> Vec<(usize, usize)> { - let mut ranges = Vec::new(); - let mut index = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - let end = skip_quoted_string(bytes, index); - ranges.push((index, end)); - index = end; - } - _ => index += 1, - } - } - ranges -} - -fn offset_in_ranges(ranges: &[(usize, usize)], range_index: &mut usize, offset: usize) -> bool { - while ranges - .get(*range_index) - .is_some_and(|(_, end)| *end <= offset) - { - *range_index += 1; - } - ranges - .get(*range_index) - .is_some_and(|(start, end)| *start <= offset && offset < *end) -} - -fn invalid_match_mapping_rest_wildcard_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let next_line_end = |line_start: usize| { - line_start - + bytes[line_start..] - .iter() - .position(|byte| *byte == b'\n') - .unwrap_or(bytes.len() - line_start) - }; - let mut index = 0usize; - let mut line_start = 0usize; - let mut line_end = next_line_end(line_start); - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'\n' => { - index += 1; - line_start = index; - line_end = next_line_end(line_start); - } - _ => { - let column = skip_horizontal_whitespace(bytes, line_start); - if index != column - || column >= line_end - || !starts_identifier(bytes, column, b"case") - { - index += 1; - continue; - } - let mut cursor = column + 4; - while cursor < line_end { - match bytes[cursor] { - b'#' => break, - b'\'' | b'"' => cursor = skip_quoted_string(bytes, cursor), - b'{' => { - let rest = next_non_horizontal_whitespace(bytes, cursor + 1); - if bytes.get(rest..rest + 2) == Some(b"**") { - let name_start = next_non_horizontal_whitespace(bytes, rest + 2); - let name_end = identifier_end(bytes, name_start, line_end); - if source.get(name_start..name_end) == Some("_") { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - name_start, - name_end, - )); - } - } - cursor += 1; - } - _ => cursor += 1, - } - } - index = line_end; - } - } - } - None -} - -fn invalid_if_expression_statement_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - if let Some(if_index) = find_keyword_at_level(bytes, line_start, line_end, b"if") - && let Some((start, end)) = statement_before_if_expression(bytes, line_start, if_index) - && find_keyword_at_level(bytes, if_index + 2, line_end, b"else").is_some() - { - return Some(CpythonDiagnostic::new( - "expected expression before 'if', but statement is given".to_owned(), - start, - end, - )); - } - if let Some(else_index) = find_keyword_at_level(bytes, line_start, line_end, b"else") - && find_keyword_at_level(bytes, line_start, else_index, b"if").is_some() - && let Some((start, end)) = - statement_after_else_expression(bytes, else_index + 4, line_end) - { - return Some(CpythonDiagnostic::new( - "expected expression after 'else', but statement is given".to_owned(), - start, - end, - )); - } - line_start = line_end; - } - None -} - -fn statement_before_if_expression( - bytes: &[u8], - line_start: usize, - if_index: usize, -) -> Option<(usize, usize)> { - let mut start = if_index; - while start > line_start && matches!(bytes.get(start - 1), Some(b' ' | b'\t' | b'\x0c')) { - start -= 1; - } - while start > line_start - && !matches!( - bytes.get(start - 1), - Some(b'=' | b':' | b',' | b'(' | b'[' | b'{') - ) - { - start -= 1; - } - start = skip_horizontal_whitespace(bytes, start); - for keyword in [b"pass".as_slice(), b"break", b"continue"] { - if starts_identifier(bytes, start, keyword) { - return Some((start, start + keyword.len())); - } - } - None -} - -fn statement_after_else_expression( - bytes: &[u8], - else_end: usize, - line_end: usize, -) -> Option<(usize, usize)> { - let start = skip_horizontal_whitespace(bytes, else_end); - for keyword in [ - b"pass".as_slice(), - b"return", - b"raise", - b"del", - b"yield", - b"assert", - b"break", - b"continue", - b"import", - b"from", - ] { - if starts_identifier(bytes, start, keyword) { - let end = statement_target_end(bytes, start).min(line_end); - return Some((start, end.max(start + keyword.len()))); - } - } - None -} - -fn invalid_else_elif_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut line_start = 0usize; - let mut else_indents: Vec = Vec::new(); - for line in source.split_inclusive('\n') { - let line_end = line_start + line.len(); - let column = skip_horizontal_whitespace(bytes, line_start); - let line_column = column.saturating_sub(line_start); - if column >= line_end { - line_start = line_end; - continue; - } - while else_indents - .last() - .is_some_and(|indent| line_column < *indent) - { - else_indents.pop(); - } - if starts_identifier(bytes, column, b"else") - && find_byte_at_level(bytes, column + 4, line_end, b':').is_some() - { - else_indents.push(line_column); - } else if starts_identifier(bytes, column, b"elif") && else_indents.contains(&line_column) { - return Some(CpythonDiagnostic::new( - "'elif' block follows an 'else' block".to_owned(), - column, - column + 4, - )); - } - line_start = line_end; - } - None -} - -fn mixed_except_handlers_error(source: &str) -> Option { - let message = "cannot have both 'except' and 'except*' on the same 'try'".to_owned(); - let mut seen_except = false; - let mut seen_except_star = false; - let mut line_start = 0usize; - for line in source.split_inclusive('\n') { - let bytes = line.as_bytes(); - let mut column = 0usize; - while matches!(bytes.get(column), Some(b' ' | b'\t' | b'\x0c')) { - column += 1; - } - let token_start = line_start + column; - if bytes.get(column..column + 7) == Some(b"except*") { - if seen_except { - return Some(CpythonDiagnostic::new( - message, - token_start, - token_start + 7, - )); - } - seen_except_star = true; - } else if starts_identifier(bytes, column, b"except") { - if seen_except_star { - return Some(CpythonDiagnostic::new( - message, - token_start, - token_start + 6, - )); - } - seen_except = true; - } - line_start += line.len(); - } - None -} - -fn non_printable_character_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - byte if byte.is_ascii_control() && !matches!(byte, b'\t' | b'\n' | b'\r' | b'\x0c') => { - return Some(CpythonDiagnostic::new( - format!("invalid non-printable character U+{byte:04X}"), - index, - index + 1, - )); - } - byte if byte >= 0x80 => { - let ch = source[index..].chars().next()?; - if ch.is_control() { - return Some(CpythonDiagnostic::new( - format!("invalid non-printable character U+{:04X}", ch as u32), - index, - index + ch.len_utf8(), - )); - } - index += ch.len_utf8(); - } - _ => index += 1, - } - } - None -} - -fn unterminated_string_error(source: &str, mode: Mode) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - let mut line = 1usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\n' => { - line += 1; - index += 1; - } - quote @ (b'\'' | b'"') => { - let start = index; - let start_line = line; - let quote_size = if bytes.get(index + 1) == Some("e) - && bytes.get(index + 2) == Some("e) - { - 3 - } else { - 1 - }; - index += quote_size; - let mut has_escaped_quote = false; - let mut ended_with_escape = false; - let mut closed = false; - while index < bytes.len() { - let c = bytes[index]; - if c == b'\n' { - if quote_size == 1 { - // A single-quoted literal cannot span a line, so this is the same - // "the literal never ended" case as running out of source; CPython - // spells the two as one condition in lexer.c too. - break; - } - line += 1; - index += 1; - } else if c == quote { - if quote_size == 3 { - if bytes.get(index + 1) == Some("e) - && bytes.get(index + 2) == Some("e) - { - index += 3; - closed = true; - break; - } - index += 1; - } else { - index += 1; - closed = true; - break; - } - } else if c == b'\\' { - if bytes.get(index + 1) == Some("e) { - has_escaped_quote = true; - } - ended_with_escape = index + 1 >= bytes.len(); - index = (index + 2).min(bytes.len()); - } else { - index += 1; - } - } - if !closed { - if let Some(error) = - unclosed_replacement_field_error(bytes, start, start + quote_size, index) - { - return Some(error); - } - let detected_line = if quote_size == 3 { line } else { start_line }; - let interpolated = interpolated_string_prefix(bytes, start); - let diagnostic = CpythonDiagnostic::new( - unterminated_string_message( - detected_line, - quote_size == 3, - has_escaped_quote, - interpolated, - ), - start, - start, - ); - // E_EOLS is only for a plain single-quoted string at EOF. - // Single-quoted f/t-strings never set it. exec input appends a - // newline, so a single-quoted literal becomes the newline case - // unless a final `\` consumes that newline. - let exec_implicit_newline = - matches!(mode, Mode::Exec) && quote_size == 1 && !ended_with_escape; - let eval_assignment = - matches!(mode, Mode::Eval) && eval_has_assignment_before(bytes, start); - let continuable = index >= bytes.len() - && !(interpolated.is_some() && quote_size == 1) - && !exec_implicit_newline - && !eval_assignment; - return Some(if continuable { - diagnostic.with_unclosed_string() - } else { - diagnostic - }); - } - } - _ => index += 1, - } - } - None -} - -fn eval_has_assignment_before(bytes: &[u8], end: usize) -> bool { - let mut index = 0; - let mut level = 0usize; - let mut in_lambda_params = false; - while index < end { - match bytes[index] { - b'#' => { - while index < end && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - b':' if level == 0 => { - in_lambda_params = false; - index += 1; - } - b'=' if level == 0 - && !in_lambda_params - && bytes.get(index + 1) != Some(&b'=') - && !matches!( - bytes.get(index.saturating_sub(1)), - Some(b':' | b'!' | b'<' | b'>') - ) => - { - return true; - } - _ if level == 0 && starts_identifier(bytes, index, b"lambda") => { - in_lambda_params = true; - index += b"lambda".len(); - } - _ => index += 1, - } - } - false -} - -fn invalid_interpolated_string_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - quote @ (b'\'' | b'"') => { - let Some(prefix) = interpolated_string_prefix(bytes, index) else { - index = skip_quoted_string(bytes, index); - continue; - }; - if let Some(error) = - single_quoted_format_spec_newline_error(bytes, index, quote, prefix) - { - return Some(error); - } - let Some((content_start, content_end)) = - quoted_string_content_range(bytes, index, quote) - else { - index = skip_quoted_string(bytes, index); - continue; - }; - if let Some(error) = - invalid_replacement_field_error(bytes, content_start, content_end, prefix) - { - return Some(error); - } - index = skip_quoted_string(bytes, index); - } - _ => index += 1, - } - } - None -} - -/// Whether the literal opened at `quote` carries a `b` in its prefix. -fn is_bytes_literal(bytes: &[u8], quote: usize) -> bool { - let mut start = quote; - while quote - start < 2 - && start > 0 - && matches!( - bytes[start - 1].to_ascii_lowercase(), - b'r' | b'b' | b'u' | b'f' | b't' - ) - { - start -= 1; - } - if start > 0 && is_ascii_identifier_char(bytes[start - 1]) { - return false; - } - bytes[start..quote] - .iter() - .any(|byte| byte.eq_ignore_ascii_case(&b'b')) -} - -/// Which of CPython's two messages a mixed literal concatenation gets. Ruff reports only the -/// bytes/non-bytes mix, so `t"x" b"y"` arrives here as a bytes error where CPython names the -/// t-string, and this scanner owns the choice between them. -/// -/// CPython's `invalid_string_tstring_concat` is an `invalid_` rule, reached only on the error -/// pass, and the `strings` rule tries `(fstring|string)+` first. That alternative consumes the -/// concatenation's leading run of non-t-string literals, so a bytes/non-bytes mix among *those* -/// raises from `_PyPegen_concatenate_strings` on the first pass and the t-string rule never runs. -/// The bytes message therefore keeps precedence for `"a" b"b" t"c"` but not for `t"x" b"y"`. -fn mixed_tstring_literal_error( - error: &parser::ParseError, - source: &str, -) -> Option { - let parser::ParseErrorType::OtherError(message) = &error.error else { - return None; - }; - if !message.eq_ignore_ascii_case("bytes literal cannot be mixed with non-bytes literals") { - return None; - } - - let start = error.location.start().to_usize(); - let end = error.location.end().to_usize(); - let bytes = source.as_bytes(); - if end > bytes.len() { - return None; - } - - let mut index = start; - let (mut bytes_seen, mut nonbytes_seen) = (false, false); - while index < end { - match bytes[index] { - b'\'' | b'"' => { - if interpolated_string_prefix(bytes, index) == Some("t-string") { - let message = if bytes_seen && nonbytes_seen { - // Reported here rather than left to ruff's error so that the scanners - // further down the chain cannot claim the concatenation instead. - "cannot mix bytes and nonbytes literals" - } else { - "cannot mix t-string literals with string or bytes literals" - }; - return Some(CpythonDiagnostic::new(message.to_owned(), start, end)); - } - if is_bytes_literal(bytes, index) { - bytes_seen = true; - } else { - nonbytes_seen = true; - } - index = skip_quoted_string(bytes, index); - } - _ => index += 1, - } - } - None -} - -fn single_quoted_format_spec_newline_error( - bytes: &[u8], - quote_index: usize, - quote: u8, - prefix: &str, -) -> Option { - if bytes.get(quote_index + 1) == Some("e) && bytes.get(quote_index + 2) == Some("e) { - return None; - } - - let (content_start, content_end) = quoted_string_content_range(bytes, quote_index, quote)?; - let mut index = content_start; - while index < content_end { - match bytes[index] { - b'{' if bytes.get(index + 1) == Some(&b'{') => index += 2, - b'}' if bytes.get(index + 1) == Some(&b'}') => index += 2, - b'{' => { - let expr_start = skip_ascii_whitespace(bytes, index + 1, content_end); - if let Some(separator) = replacement_field_separator(bytes, expr_start, content_end) - && bytes[separator] == b':' - { - let format_end = - replacement_field_closing_brace(bytes, separator + 1, content_end) - .unwrap_or(content_end); - if bytes[separator + 1..format_end].contains(&b'\n') { - return Some(CpythonDiagnostic::new( - format!( - "{prefix}: newlines are not allowed in format specifiers for single quoted {prefix}s" - ), - quote_index, - quote_index + 1, - )); - } - } - index += 1; - } - _ => index += 1, - } - } - None -} - -fn interpolated_string_prefix(bytes: &[u8], quote: usize) -> Option<&'static str> { - let prev = quote.checked_sub(1).and_then(|index| bytes.get(index))?; - let lower_prev = prev.to_ascii_lowercase(); - let (prefix_start, marker) = if matches!(lower_prev, b'f' | b't') { - if quote >= 2 && bytes[quote - 2].eq_ignore_ascii_case(&b'r') { - (quote - 2, lower_prev) - } else { - (quote - 1, lower_prev) - } - } else if lower_prev == b'r' - && quote >= 2 - && matches!(bytes[quote - 2].to_ascii_lowercase(), b'f' | b't') - { - (quote - 2, bytes[quote - 2].to_ascii_lowercase()) - } else { - return None; - }; - - if prefix_start > 0 && identifier_continue_before(bytes, prefix_start) { - return None; - } - - Some(if marker == b'f' { - "f-string" - } else { - "t-string" - }) -} - -const MAXFSTRINGLEVEL: usize = 150; - -fn skip_string_token(bytes: &[u8], quote_index: usize) -> usize { - if interpolated_string_prefix(bytes, quote_index).is_some() { - interpolated_string_end(bytes, quote_index).unwrap_or(bytes.len()) - } else { - skip_quoted_string(bytes, quote_index) - } -} - -fn interpolated_string_end(bytes: &[u8], quote_index: usize) -> Option { - let quote = bytes[quote_index]; - let triple = - bytes.get(quote_index + 1) == Some("e) && bytes.get(quote_index + 2) == Some("e); - let quote_len = if triple { 3 } else { 1 }; - let mut index = quote_index + quote_len; - let mut brace_depth = 0usize; - while index < bytes.len() { - if brace_depth == 0 { - if bytes[index] == b'\\' { - index = (index + 2).min(bytes.len()); - continue; - } - if triple - && bytes.get(index) == Some("e) - && bytes.get(index + 1) == Some("e) - && bytes.get(index + 2) == Some("e) - { - return Some(index + 3); - } - if !triple && bytes[index] == quote { - return Some(index + 1); - } - if bytes[index] == b'{' { - if bytes.get(index + 1) == Some(&b'{') { - index += 2; - } else { - brace_depth = 1; - index += 1; - } - } else if bytes[index] == b'}' && bytes.get(index + 1) == Some(&b'}') { - index += 2; - } else { - index += 1; - } - } else { - match bytes[index] { - quote_ch @ (b'\'' | b'"') => { - if quoted_string_is_closed(bytes, index) { - index = skip_string_token(bytes, index).max(index + 1); - } else if !triple && quote_ch == quote { - return Some(index + 1); - } else { - index = skip_string_token(bytes, index).max(index + 1); - } - } - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'{' => { - brace_depth += 1; - index += 1; - } - b'}' => { - brace_depth -= 1; - index += 1; - } - b'\\' => index = (index + 2).min(bytes.len()), - _ => index += 1, - } - } - } - None -} - -fn quote_len_at(bytes: &[u8], quote_index: usize) -> usize { - let quote = bytes[quote_index]; - if bytes.get(quote_index + 1) == Some("e) && bytes.get(quote_index + 2) == Some("e) { - 3 - } else { - 1 - } -} - -fn interpolated_string_content_range(bytes: &[u8], quote_index: usize) -> Option<(usize, usize)> { - let end = interpolated_string_end(bytes, quote_index)?; - let quote_len = quote_len_at(bytes, quote_index); - Some((quote_index + quote_len, end - quote_len)) -} - -fn quoted_string_content_range( - bytes: &[u8], - quote_index: usize, - quote: u8, -) -> Option<(usize, usize)> { - let triple = - bytes.get(quote_index + 1) == Some("e) && bytes.get(quote_index + 2) == Some("e); - let quote_len = if triple { 3 } else { 1 }; - let content_start = quote_index + quote_len; - let mut index = content_start; - while index < bytes.len() { - if bytes[index] == b'\\' { - index = (index + 2).min(bytes.len()); - } else if (triple - && bytes.get(index) == Some("e) - && bytes.get(index + 1) == Some("e) - && bytes.get(index + 2) == Some("e)) - || (!triple && bytes[index] == quote) - { - return Some((content_start, index)); - } else { - index += 1; - } - } - None -} - -fn invalid_replacement_field_error( - bytes: &[u8], - start: usize, - end: usize, - prefix: &str, -) -> Option { - let mut index = start; - while index < end { - match bytes[index] { - b'{' if bytes.get(index + 1) == Some(&b'{') => index += 2, - b'}' if bytes.get(index + 1) == Some(&b'}') => index += 2, - b'{' => { - if let Some(error) = replacement_field_error(bytes, index, end, prefix, 0) { - return Some(error); - } - // Resume in the literal text. Inside the field a `#` starts a comment and a `{` - // opens no new field, so walking on byte by byte would misread both. - index = replacement_field_end(bytes, index, end).unwrap_or(end); - } - _ => index += 1, - } - } - None -} - -/// Position just past a replacement field's closing brace. The expression part is code, where a -/// comment runs to the end of the line; past the separator only nested fields nest. -fn replacement_field_end(bytes: &[u8], open: usize, end: usize) -> Option { - let expr_start = skip_replacement_field_trivia(bytes, open + 1, end); - let separator = replacement_field_separator(bytes, expr_start, end)?; - if bytes[separator] == b'}' { - return Some(separator + 1); - } - replacement_field_closing_brace(bytes, separator + 1, end).map(|brace| brace + 1) -} - -/// The one-based line holding `offset`. Counted on demand: these scanners only run once the -/// source has failed to parse, and tracking a line through the spans they skip would have to -/// re-scan them anyway. -fn line_of_offset(bytes: &[u8], offset: usize) -> usize { - 1 + bytes[..offset] - .iter() - .filter(|byte| **byte == b'\n') - .count() -} - -/// Brackets opened in a replacement field's expression must close before the field does. CPython -/// words these exactly as it does for brackets anywhere else, except that a closer with nothing -/// open is attributed to the literal. `start..end` must cover only the expression: a format spec -/// is plain text, so a bracket there opens nothing. -fn replacement_field_bracket_error( - bytes: &[u8], - start: usize, - end: usize, - prefix: &str, -) -> Option { - // Each entry carries where its bracket opened, so a mismatch can name that line. - let mut stack: Vec<(u8, usize)> = Vec::new(); - let mut index = start; - while index < end { - let byte = bytes[index]; - match byte { - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - continue; - } - b'#' => { - index = skip_replacement_field_comment(bytes, index, end); - continue; - } - b'(' | b'[' | b'{' => stack.push((byte, index)), - b')' | b']' | b'}' => { - let expected = expected_opening_bracket(byte as char) as u8; - match stack.last() { - // The field's own closing brace: everything inside it balanced. - None if byte == b'}' => return None, - None => { - return Some(CpythonDiagnostic::new( - format!("{prefix}: unmatched '{}'", byte as char), - index, - index + 1, - )); - } - Some(&(opening, _)) if opening == expected => { - stack.pop(); - } - Some(&(opening, opened_at)) => { - // CPython names the opening line only when it is not the closing one, - // comparing `parenlinenostack[level]` against the current `lineno`. - let opening_line = line_of_offset(bytes, opened_at); - let suffix = if opening_line == line_of_offset(bytes, index) { - String::new() - } else { - format!(" on line {opening_line}") - }; - return Some(CpythonDiagnostic::new( - format!( - "closing parenthesis '{}' does not match opening parenthesis '{}'{suffix}", - byte as char, opening as char - ), - index, - index + 1, - )); - } - } - } - _ => {} - } - index += 1; - } - None -} - -/// A `#` in a replacement field's expression starts a comment. When no newline follows it before -/// the end of the literal, the comment swallows the closing brace and the field can never close. -/// `start..end` must cover only the expression: `#` is an ordinary character in a format spec, -/// where it selects the alternate form. -fn replacement_field_comment_error( - bytes: &[u8], - open: usize, - start: usize, - end: usize, - literal_end: usize, -) -> Option { - let mut index = start; - while index < end { - match bytes[index] { - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - continue; - } - b'#' => { - if !bytes[index..literal_end].contains(&b'\n') { - return Some( - CpythonDiagnostic::new("'{' was never closed".to_owned(), open, open + 1) - .with_unclosed_bracket(), - ); - } - index = skip_replacement_field_comment(bytes, index, end); - continue; - } - _ => index += 1, - } - } - None -} - -/// Advances past a comment, stopping on the newline that ends it. -fn skip_replacement_field_comment(bytes: &[u8], mut index: usize, end: usize) -> usize { - while index < end && bytes[index] != b'\n' { - index += 1; - } - index -} - -/// Whitespace and comments may both precede a replacement field's expression. -fn skip_replacement_field_trivia(bytes: &[u8], mut index: usize, end: usize) -> usize { - loop { - index = skip_ascii_whitespace(bytes, index, end); - if index < end && bytes[index] == b'#' { - index = skip_replacement_field_comment(bytes, index, end); - continue; - } - return index; - } -} - -/// Bounds the mutual recursion between a replacement field and the format spec it contains, -/// so that pathologically nested input cannot exhaust the stack. -const MAX_REPLACEMENT_FIELD_DEPTH: usize = 32; - -fn replacement_field_error( - bytes: &[u8], - open: usize, - end: usize, - prefix: &str, - depth: usize, -) -> Option { - let expr_start = skip_replacement_field_trivia(bytes, open + 1, end); - - // The expression runs up to the field's first top-level `=`, `!`, `:` or `}`. Everything past - // it is a conversion or a format spec, which are text rather than code, so the checks that - // treat the field as code have to stop here. - let separator = replacement_field_separator(bytes, expr_start, end); - let expr_end = separator.unwrap_or(end); - - if let Some(backslash) = replacement_field_line_continuation(bytes, expr_start, expr_end) { - return Some(CpythonDiagnostic::new( - "unexpected character after line continuation character".to_owned(), - backslash + 1, - (backslash + 2).min(end), - )); - } - if let Some(quote) = unterminated_string_in_replacement_field(bytes, expr_start, expr_end) { - return Some(CpythonDiagnostic::new( - unterminated_string_message(1, false, false, None), - quote, - quote + 1, - )); - } - // Brackets are reported ahead of everything else in the field, and a comment that swallows - // the closing brace ahead of the expression itself. The comment scan starts at the brace - // because a comment may also sit between it and the expression. - if let Some(error) = replacement_field_bracket_error(bytes, expr_start, expr_end, prefix) { - return Some(error); - } - if let Some(error) = replacement_field_comment_error(bytes, open, open + 1, expr_end, end) { - return Some(error); - } - - // Nothing follows `{` at all, so the field simply never closed. CPython asks for the - // brace here; an expression that merely fails to start is reported further down. - if expr_start >= end { - return Some(CpythonDiagnostic::new( - format!("{prefix}: expecting '}}'"), - open, - open + 1, - )); - } - - if let marker @ (b'=' | b'!' | b':' | b'}') = bytes[expr_start] - && is_replacement_field_marker(bytes, expr_start) - { - return Some(CpythonDiagnostic::new( - format!( - "{prefix}: valid expression required before '{}'", - marker as char - ), - expr_start, - expr_start + 1, - )); - } - - // A `{` display is a valid expression, but only if something can follow it. CPython - // reports the inner brace when it cannot, as in `f'{3:{{>10}'`. - if bytes[expr_start] == b'{' { - let inner = skip_ascii_whitespace(bytes, expr_start + 1, end); - if inner < end - && bytes[inner] != b'}' - && invalid_replacement_expression_start(bytes, inner, end) - { - return Some(CpythonDiagnostic::new( - format!("{prefix}: expecting a valid expression after '{{'"), - expr_start, - expr_start + 1, - )); - } - } - - if starts_identifier(bytes, expr_start, b"lambda") { - return Some(CpythonDiagnostic::new( - format!("{prefix}: lambda expressions are not allowed without parentheses"), - expr_start, - expr_start + b"lambda".len(), - )); - } - - if invalid_replacement_expression_start(bytes, expr_start, end) { - return Some(CpythonDiagnostic::new( - format!("{prefix}: expecting a valid expression after '{{'"), - open, - open + 1, - )); - } - - // Adjacent atoms in a replacement field are a missing comma, not an - // f-string "expecting '}'" at the opening brace. Prefix `yield`/`await`/ - // `not` and continuation keywords (`and`, `for`, ...) are not a second atom. - if !starts_identifier(bytes, expr_start, b"yield") - && !starts_identifier(bytes, expr_start, b"await") - && !starts_identifier(bytes, expr_start, b"not") - && let Some(atom_end) = adjacent_atom_end(bytes, expr_start) - { - let next = skip_ascii_whitespace(bytes, atom_end, expr_end); - if next > atom_end - && expression_atom_start(bytes, next) - && !expression_continuation_keyword(bytes, next) - { - let second_end = adjacent_atom_end(bytes, next).unwrap_or(next + 1); - return Some(CpythonDiagnostic::new( - "invalid syntax. Perhaps you forgot a comma?".to_owned(), - expr_start, - second_end, - )); - } - } - - // The expression started fine but ran into a character that cannot continue it. CPython - // points at that character and lists the separators it wanted instead. - if let Some(stray) = replacement_expression_stray_character(bytes, expr_start, expr_end) { - return Some(CpythonDiagnostic::new( - format!("{prefix}: expecting '=', or '!', or ':', or '}}'"), - stray, - stray + 1, - )); - } - - let Some(separator) = separator else { - return Some(CpythonDiagnostic::new( - format!("{prefix}: expecting '}}'"), - open, - open + 1, - )); - }; - - // Only now that the field is known to close. A stray character above is a finished token - // the parser rejects on lookahead, but a dangling operator makes it ask for one more, and - // producing that token runs into the literal's closing quote: lexer.c then answers from - // `INSIDE_FSTRING(tok)` with "%c-string: expecting '}'" before any `invalid_` rule is tried. - if let Some(operator) = dangling_operator(bytes, expr_start, expr_end) { - return Some(CpythonDiagnostic::new( - format!("{prefix}: expecting '=', or '!', or ':', or '}}'"), - operator, - operator + 1, - )); - } - - if let Some(lambda_at) = top_level_lambda(bytes, expr_start, expr_end) - && lambda_allowed_at_expression_position(bytes, expr_start, lambda_at) - { - return Some(CpythonDiagnostic::new( - format!("{prefix}: lambda expressions are not allowed without parentheses"), - lambda_at, - lambda_at + b"lambda".len(), - )); - } - - if bytes[separator] == b':' - && replacement_expression_has_parse_error(bytes, expr_start, separator) - { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - expr_start, - separator, - )); - } - - match bytes[separator] { - b'=' => invalid_debug_expression_error(bytes, separator, end, prefix, depth), - b'!' => invalid_conversion_error(bytes, separator, end, prefix, depth), - b':' => invalid_format_spec_error(bytes, separator, end, prefix, depth), - b'}' => None, - _ => unreachable!(), - } -} - -fn replacement_field_line_continuation( - bytes: &[u8], - mut index: usize, - end: usize, -) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'#' => index = skip_replacement_field_comment(bytes, index, end), - b'\\' => return Some(index), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' if level > 0 => { - level -= 1; - index += 1; - } - b'=' | b'!' | b':' | b'}' - if level == 0 && is_replacement_field_marker(bytes, index) => - { - return None; - } - _ => index += 1, - } - } - None -} - -fn unterminated_string_in_replacement_field( - bytes: &[u8], - mut index: usize, - end: usize, -) -> Option { - while index < end { - match bytes[index] { - quote @ (b'\'' | b'"') => { - let string_end = skip_quoted_string(bytes, index); - if string_end >= end && !bytes[index + 1..end].contains("e) { - return Some(index); - } - index = string_end; - } - b'#' => index = skip_replacement_field_comment(bytes, index, end), - _ => index += 1, - } - } - None -} - -fn top_level_lambda(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'#' => index = skip_replacement_field_comment(bytes, index, end), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' if level > 0 => { - level -= 1; - index += 1; - } - _ if level == 0 && starts_identifier(bytes, index, b"lambda") => { - return Some(index); - } - _ => index += 1, - } - } - None -} - -/// Unparenthesized `lambda` is allowed in the same places a `lambdef` can appear: -/// at the start of the field or after a top-level comma. -fn lambda_allowed_at_expression_position(bytes: &[u8], mut index: usize, lambda_at: usize) -> bool { - let mut after_comma = true; - let mut level = 0usize; - while index < lambda_at { - match bytes[index] { - b'\'' | b'"' => { - after_comma = false; - index = skip_quoted_string(bytes, index); - } - b'#' => index = skip_replacement_field_comment(bytes, index, lambda_at), - b'(' | b'[' | b'{' => { - level += 1; - after_comma = false; - index += 1; - } - b')' | b']' | b'}' if level > 0 => { - level -= 1; - after_comma = false; - index += 1; - } - b',' if level == 0 => { - after_comma = true; - index += 1; - } - b' ' | b'\t' | b'\n' | b'\r' | b'\x0c' => index += 1, - _ => { - after_comma = false; - index += 1; - } - } - } - after_comma -} - -fn replacement_expression_has_parse_error(bytes: &[u8], start: usize, end: usize) -> bool { - let Ok(expression) = ::core::str::from_utf8(&bytes[start..end]) else { - return false; - }; - parser::parse_expression(expression).is_err() -} - -fn invalid_replacement_expression_start(bytes: &[u8], index: usize, end: usize) -> bool { - if index >= end { - return true; - } - - // A leading `.` is Ellipsis or a float without an integer part, both of which start a - // perfectly good expression. - if bytes[index] == b'.' - && (bytes[index..end].starts_with(b"...") - || bytes - .get(index + 1) - .is_some_and(|byte| byte.is_ascii_digit())) - { - return false; - } - - if matches!( - bytes[index], - b'.' | b',' | b'*' | b'/' | b'%' | b'&' | b'|' | b'^' | b'<' | b'>' | b'@' | b'=' | b'!' - ) || is_stray_in_replacement_expression(bytes[index]) - { - return true; - } - - if matches!(bytes[index], b'+' | b'-' | b'~') { - let operand = skip_ascii_whitespace(bytes, index + 1, end); - if starts_identifier(bytes, operand, b"lambda") { - return true; - } - return !bytes.get(operand).is_some_and(|byte| { - *byte >= 0x80 - || *byte == b'_' - || byte.is_ascii_alphabetic() - || byte.is_ascii_digit() - || matches!(*byte, b'\'' | b'"' | b'(' | b'[' | b'{') - // `-.5` is a signed float. - || (*byte == b'.' - && bytes - .get(operand + 1) - .is_some_and(|next| next.is_ascii_digit())) - }); - } - - [ - b"and".as_slice(), - b"as".as_slice(), - b"else".as_slice(), - b"for".as_slice(), - b"if".as_slice(), - b"in".as_slice(), - b"is".as_slice(), - b"or".as_slice(), - ] - .iter() - .any(|keyword| starts_identifier(bytes, index, keyword)) -} - -/// A top-level `=` or `!` marks a debug specifier or a conversion only when it is not part of a -/// longer operator. CPython's tokenizer consumes `==`, `!=`, `<=`, `+=` and the rest as single -/// tokens before it ever considers the debug marker, so those must not end the expression here. -fn is_replacement_field_marker(bytes: &[u8], index: usize) -> bool { - match bytes[index] { - b'=' => { - if bytes.get(index + 1) == Some(&b'=') { - return false; - } - !index - .checked_sub(1) - .and_then(|previous| bytes.get(previous).copied()) - .is_some_and(precedes_equals_in_one_operator) - } - b'!' => bytes.get(index + 1) != Some(&b'='), - _ => true, - } -} - -fn replacement_field_separator(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'#' => index = skip_replacement_field_comment(bytes, index, end), - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' if level > 0 => { - level -= 1; - index += 1; - } - b'=' | b'!' | b':' | b'}' - if level == 0 && is_replacement_field_marker(bytes, index) => - { - return Some(index); - } - _ => index += 1, - } - } - None -} - -/// Characters that can neither start nor continue a replacement field expression. CPython's -/// interpolated-string tokenizer stops at them and asks for a separator instead. -const fn is_stray_in_replacement_expression(byte: u8) -> bool { - matches!(byte, b';' | b'$' | b'?' | b'`') -} - -fn replacement_expression_stray_character( - bytes: &[u8], - mut index: usize, - end: usize, -) -> Option { - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'#' => index = skip_replacement_field_comment(bytes, index, end), - byte if is_stray_in_replacement_expression(byte) => return Some(index), - _ => index += 1, - } - } - None -} - -/// A byte that pairs with a following `=` to make one operator token, so that the `=` belongs -/// to it rather than opening a debug specifier: `==`, `!=`, `<=`, `>=`, the augmented -/// assignments, and the `:=` walrus. Against `is_dangling_operator_byte` below, this has `:` -/// and lacks `.` and `~`, because neither `.=` nor `~=` is a Python operator. -const fn precedes_equals_in_one_operator(byte: u8) -> bool { - matches!( - byte, - b'!' | b'%' - | b'&' - | b'*' - | b'+' - | b'-' - | b'/' - | b':' - | b'<' - | b'=' - | b'>' - | b'@' - | b'^' - | b'|' - ) -} - -/// Characters that make up an operator which cannot end an expression. Against -/// `precedes_equals_in_one_operator` above, this has `.` and `~` for `a.b.` and `~a`, and lacks -/// `:`, which separates a replacement field's parts rather than operating on anything. -const fn is_dangling_operator_byte(byte: u8) -> bool { - matches!( - byte, - b'!' | b'%' - | b'&' - | b'*' - | b'+' - | b'-' - | b'.' - | b'/' - | b'<' - | b'=' - | b'>' - | b'@' - | b'^' - | b'|' - | b'~' - ) -} - -/// The identifier that ends just before `word`, skipping the whitespace between them. -fn preceding_keyword(bytes: &[u8], start: usize, word: usize) -> Option<(usize, &[u8])> { - let mut cursor = word; - while cursor > start && matches!(bytes[cursor - 1], b' ' | b'\t' | b'\r' | b'\n' | 0x0c) { - cursor -= 1; - } - let stop = cursor; - while cursor > start && is_ascii_identifier_char(bytes[cursor - 1]) { - cursor -= 1; - } - (cursor < stop).then(|| (cursor, &bytes[cursor..stop])) -} - -/// A replacement field expression cannot end on an operator that still wants an operand. -/// CPython's tokenizer then reaches the field brace with the expression unfinished and asks for -/// a separator, pointing at the operator that left it that way. Returns that operator's start. -fn dangling_operator(bytes: &[u8], start: usize, end: usize) -> Option { - // The region cannot be read backwards: the newline that ends a comment is whitespace, so - // trimming from `end` would step into the comment body. Walk forward instead and keep the - // position just past the last byte that is really part of the expression. - let mut index = start; - let mut tail = start; - while index < end { - match bytes[index] { - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index).min(end); - tail = index; - } - b'#' => index = skip_replacement_field_comment(bytes, index, end), - b' ' | b'\t' | b'\r' | b'\n' | 0x0c => index += 1, - _ => { - index += 1; - tail = index; - } - } - } - if tail == start { - return None; - } - - // A trailing keyword operator reads back as an identifier. - if is_ascii_identifier_char(bytes[tail - 1]) { - let mut word = tail; - while word > start && is_ascii_identifier_char(bytes[word - 1]) { - word -= 1; - } - if ![ - b"and".as_slice(), - b"or".as_slice(), - b"not".as_slice(), - b"in".as_slice(), - b"is".as_slice(), - b"if".as_slice(), - b"for".as_slice(), - ] - .iter() - .any(|keyword| &bytes[word..tail] == *keyword) - { - return None; - } - // `is not` and `not in` are single operators, and CPython points at their first word. - let previous = preceding_keyword(bytes, start, word); - return Some(match (previous, &bytes[word..tail]) { - (Some((at, b"is")), b"not") | (Some((at, b"not")), b"in") => at, - _ => word, - }); - } - - if !is_dangling_operator_byte(bytes[tail - 1]) { - return None; - } - let mut token = tail; - while token > start && is_dangling_operator_byte(bytes[token - 1]) { - token -= 1; - } - - // `1.` is a float: that dot finishes the literal rather than dangling. - if bytes[token..tail] == *b"." && token > start && bytes[token - 1].is_ascii_digit() { - return None; - } - // `...` is Ellipsis, so consume whole triples: a leftover dot is what dangles. - if bytes[token..tail].iter().all(|byte| *byte == b'.') { - let leftover = (tail - token) % 3; - return (leftover != 0).then(|| tail - leftover); - } - Some(token) -} - -fn invalid_debug_expression_error( - bytes: &[u8], - equals: usize, - end: usize, - prefix: &str, - depth: usize, -) -> Option { - let next = equals + 1; - if next >= end { - return None; - } - // A conversion or format spec may follow `=`, and is validated exactly as it would be - // when following the expression directly. - match bytes[next] { - b'!' => return invalid_conversion_error(bytes, next, end, prefix, depth), - b':' => return invalid_format_spec_error(bytes, next, end, prefix, depth), - b'}' => return None, - _ => {} - } - Some(CpythonDiagnostic::new( - format!("{prefix}: expecting '!', or ':', or '}}'"), - next, - next.saturating_add(1).min(end), - )) -} - -fn invalid_conversion_error( - bytes: &[u8], - bang: usize, - end: usize, - prefix: &str, - depth: usize, -) -> Option { - let next = bang + 1; - if next >= end { - return Some(CpythonDiagnostic::new( - format!("{prefix}: expecting '}}'"), - bang, - bang + 1, - )); - } - - if bytes[next].is_ascii_whitespace() { - let following = skip_ascii_whitespace(bytes, next, end); - let message = if bytes - .get(following) - .is_some_and(|byte| byte.is_ascii_alphabetic() || *byte == b'_') - { - "conversion type must come right after the exclamation mark" - } else { - "missing conversion character" - }; - return Some(CpythonDiagnostic::new( - format!("{prefix}: {message}"), - next, - next + 1, - )); - } - - if matches!(bytes[next], b':' | b'}') { - return Some(CpythonDiagnostic::new( - format!("{prefix}: missing conversion character"), - next, - next + 1, - )); - } - - // A non-ASCII character is still a conversion character as far as CPython is concerned, - // so it gets named in the message like any other invalid one. - if bytes[next] >= 0x80 - && let Some(character) = ::core::str::from_utf8(&bytes[next..end]) - .ok() - .and_then(|text| text.chars().next()) - { - return Some(CpythonDiagnostic::new( - format!( - "{prefix}: invalid conversion character '{character}': expected 's', 'r', or 'a'" - ), - next, - next + character.len_utf8(), - )); - } - - if !bytes[next].is_ascii_alphabetic() && bytes[next] != b'_' { - return Some(CpythonDiagnostic::new( - format!("{prefix}: invalid conversion character"), - next, - next + 1, - )); - } - - let conversion_end = identifier_end(bytes, next, end); - let conversion = &bytes[next..conversion_end]; - if !matches!(conversion, b"s" | b"r" | b"a") { - let conversion = ::core::str::from_utf8(conversion).unwrap_or(""); - return Some(CpythonDiagnostic::new( - format!( - "{prefix}: invalid conversion character '{conversion}': expected 's', 'r', or 'a'" - ), - next, - conversion_end, - )); - } - - if conversion_end >= end { - return None; - } - - match bytes[conversion_end] { - b':' => return invalid_format_spec_error(bytes, conversion_end, end, prefix, depth), - b'}' => return None, - _ => {} - } - - Some(CpythonDiagnostic::new( - format!("{prefix}: expecting ':' or '}}'"), - conversion_end, - conversion_end + 1, - )) -} - -fn invalid_format_spec_error( - bytes: &[u8], - colon: usize, - end: usize, - prefix: &str, - depth: usize, -) -> Option { - // Unlike literal text, a format spec has no `{{` escape: every `{` opens a nested - // replacement field, so the outer scanner cannot validate these for us. - let mut index = colon + 1; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'{' => { - if depth < MAX_REPLACEMENT_FIELD_DEPTH - && let Some(error) = - replacement_field_error(bytes, index, end, prefix, depth + 1) - { - return Some(error); - } - // Resume after the nested field. Walking into it again from every enclosing - // spec would re-scan the same bytes once per level, which costs O(2^depth). - let Some(after) = replacement_field_end(bytes, index, end) else { - break; - }; - index = after; - } - b'}' => return None, - _ => index += 1, - } - } - Some(CpythonDiagnostic::new( - format!("{prefix}: expecting '}}', or format specs"), - colon, - colon + 1, - )) -} - -fn replacement_field_closing_brace(bytes: &[u8], mut index: usize, end: usize) -> Option { - let mut level = 0usize; - while index < end { - match bytes[index] { - b'\'' | b'"' => index = skip_quoted_string(bytes, index), - b'{' => { - level += 1; - index += 1; - } - b'}' if level > 0 => { - level -= 1; - index += 1; - } - b'}' => return Some(index), - _ => index += 1, - } - } - None -} - -fn skip_ascii_whitespace(bytes: &[u8], mut index: usize, end: usize) -> usize { - while index < end && matches!(bytes[index], b' ' | b'\t' | b'\r' | b'\n' | 0x0c) { - index += 1; - } - index -} - -fn string_literal_end_at(bytes: &[u8], index: usize) -> Option { - match bytes.get(index).copied()? { - b'\'' | b'"' => Some(skip_quoted_string(bytes, index)), - first if first.is_ascii_alphabetic() => { - if matches!(bytes.get(index + 1), Some(b'\'' | b'"')) { - return string_literal_prefix(bytes, index, index + 1) - .then(|| skip_quoted_string(bytes, index + 1)); - } - if matches!(bytes.get(index + 2), Some(b'\'' | b'"')) { - return string_literal_prefix(bytes, index, index + 2) - .then(|| skip_quoted_string(bytes, index + 2)); - } - None - } - _ => None, - } -} - -fn string_literal_prefix(bytes: &[u8], start: usize, quote: usize) -> bool { - let prefix = &bytes[start..quote]; - let valid = matches!( - prefix, - b"b" | b"B" - | b"r" - | b"R" - | b"u" - | b"U" - | b"f" - | b"F" - | b"t" - | b"T" - | b"br" - | b"bR" - | b"Br" - | b"BR" - | b"rb" - | b"rB" - | b"Rb" - | b"RB" - | b"fr" - | b"fR" - | b"Fr" - | b"FR" - | b"rf" - | b"rF" - | b"Rf" - | b"RF" - | b"tr" - | b"tR" - | b"Tr" - | b"TR" - | b"rt" - | b"rT" - | b"Rt" - | b"RT" - ); - valid && (start == 0 || !is_ascii_identifier_char(bytes[start - 1])) -} - -fn invalid_expression_error(source: &str) -> Option { - invalid_string_expression_error(source).or_else(|| missing_comma_expression_error(source)) -} - -fn invalid_string_expression_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - if let Some(first_string_end) = string_literal_end_at(bytes, index) { - let expr_start = skip_ascii_whitespace(bytes, first_string_end, bytes.len()); - if expression_atom_start(bytes, expr_start) - && let Some(expr_end) = adjacent_atom_end(bytes, expr_start) - { - let next = skip_ascii_whitespace(bytes, expr_end, bytes.len()); - if string_literal_end_at(bytes, next).is_some() { - return Some(CpythonDiagnostic::new( - "invalid syntax. Is this intended to be part of the string?".to_owned(), - expr_start, - expr_end, - )); - } - } - index = first_string_end; - } else { - index += 1; - } - } - None -} - -fn missing_comma_expression_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut stack: Vec = Vec::new(); - let mut index = 0; - while index < bytes.len() { - if bytes[index] == b'#' { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } else if let Some(string_end) = string_literal_end_at(bytes, index) { - index = string_end; - } else { - match bytes[index] { - b'(' | b'[' | b'{' => { - if bytes[index] == b'[' && opening_bracket_is_class_type_params(bytes, index) { - let Some(close) = matching_delimiter(bytes, index, b']') else { - index += 1; - continue; - }; - index = close + 1; - continue; - } - stack.push(bytes[index]); - index += 1; - } - b')' | b']' | b'}' => { - stack.pop(); - index += 1; - } - _ if !stack.is_empty() && expression_continuation_keyword(bytes, index) => { - index = identifier_end(bytes, index, bytes.len()); - } - byte if !stack.is_empty() && expression_atom_start_byte(byte) => { - // `yield x` / `await x` are prefix expressions, not two - // adjacent atoms missing a comma. - if starts_identifier(bytes, index, b"yield") { - index = identifier_end(bytes, index, bytes.len()); - let after_yield = skip_ascii_whitespace(bytes, index, bytes.len()); - if starts_identifier(bytes, after_yield, b"from") { - index = identifier_end(bytes, after_yield, bytes.len()); - } - continue; - } - if starts_identifier(bytes, index, b"await") { - index = identifier_end(bytes, index, bytes.len()); - continue; - } - let atom_end = adjacent_atom_end(bytes, index).unwrap_or(index + 1); - let next = skip_ascii_whitespace(bytes, atom_end, bytes.len()); - if next > atom_end - && expression_atom_start(bytes, next) - && !expression_continuation_keyword(bytes, next) - { - // The diagnostic covers both atoms, so it ends past - // the whole second one. `next + 1` ended past its - // first byte instead, which is only the same thing - // when that atom is one ASCII character. - let second_end = adjacent_atom_end(bytes, next).unwrap_or(next + 1); - return Some(CpythonDiagnostic::new( - "invalid syntax. Perhaps you forgot a comma?".to_owned(), - index, - second_end, - )); - } - index = atom_end; - } - _ => index += 1, - } - } - } - None -} - -fn opening_bracket_is_class_type_params(bytes: &[u8], bracket: usize) -> bool { - let mut cursor = bracket; - while cursor > 0 && matches!(bytes[cursor - 1], b' ' | b'\t' | b'\x0c') { - cursor -= 1; - } - while cursor > 0 - && bytes - .get(cursor - 1) - .is_some_and(|byte| *byte >= 0x80 || is_ascii_identifier_char(*byte)) - { - cursor -= 1; - } - while cursor > 0 && matches!(bytes[cursor - 1], b' ' | b'\t' | b'\x0c') { - cursor -= 1; - } - cursor >= 5 && starts_identifier(bytes, cursor - 5, b"class") -} - -fn expression_continuation_keyword(bytes: &[u8], index: usize) -> bool { - [ - b"and".as_slice(), - b"else".as_slice(), - b"for".as_slice(), - b"if".as_slice(), - b"in".as_slice(), - b"is".as_slice(), - b"not".as_slice(), - b"or".as_slice(), - ] - .iter() - .any(|keyword| starts_identifier(bytes, index, keyword)) -} - -fn expression_atom_start(bytes: &[u8], index: usize) -> bool { - bytes - .get(index) - .is_some_and(|byte| expression_atom_start_byte(*byte)) - || string_literal_end_at(bytes, index).is_some() -} - -fn expression_atom_start_byte(byte: u8) -> bool { - byte >= 0x80 - || byte == b'_' - || byte.is_ascii_alphabetic() - || byte.is_ascii_digit() - || matches!(byte, b'\'' | b'"' | b'(' | b'[' | b'{') -} - -fn adjacent_atom_end(bytes: &[u8], index: usize) -> Option { - if let Some(string_end) = string_literal_end_at(bytes, index) { - return Some(string_end); - } - match bytes.get(index).copied()? { - byte if byte >= 0x80 || byte == b'_' || byte.is_ascii_alphabetic() => { - Some(identifier_end(bytes, index, bytes.len())) - } - byte if byte.is_ascii_digit() => { - let mut end = index + 1; - while end < bytes.len() && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'_') { - end += 1; - } - Some(end) - } - b'(' | b'[' | b'{' => Some(index + 1), - _ => None, - } -} - -struct OpenDelimiter { - position: usize, - opener: u8, - in_format_spec: bool, -} - -/// An f-string or t-string that runs off the end with a replacement field still open reports -/// the brace rather than the missing quote, matching CPython — but only while the tokenizer is -/// still reading the field's *expression*. Past the field's own `:` it is emitting FSTRING_MIDDLE -/// again, so running out of input there is an unterminated literal like any other, and -/// `f'{a:>5` gets the quote message where `f'{a` gets the brace. -fn unclosed_replacement_field_error( - bytes: &[u8], - quote_start: usize, - content_start: usize, - content_end: usize, -) -> Option { - interpolated_string_prefix(bytes, quote_start)?; - - // Brackets and quotes are delimiters only once a field is open; in the literal's text they - // are ordinary characters. And past a field's own format spec the tokenizer emits literal - // text again, so a field still open at end of input is an unclosed brace only before that. - let mut open: Vec = Vec::new(); - let mut index = content_start; - while index < content_end { - let inside_expression = matches!( - open.last(), - Some(OpenDelimiter { - opener: b'{', - in_format_spec: false, - .. - }) - ); - match bytes[index] { - // `{{` and `}}` escape only in literal text, which is where a brace at depth zero is. - b'{' if open.is_empty() && bytes.get(index + 1) == Some(&b'{') => index += 2, - b'}' if open.is_empty() && bytes.get(index + 1) == Some(&b'}') => index += 2, - b'{' => { - open.push(OpenDelimiter { - position: index, - opener: b'{', - in_format_spec: false, - }); - index += 1; - } - b'}' => { - open.pop(); - index += 1; - } - byte @ (b'(' | b'[') if !open.is_empty() => { - open.push(OpenDelimiter { - position: index, - opener: byte, - in_format_spec: false, - }); - index += 1; - } - b')' | b']' if !open.is_empty() => { - open.pop(); - index += 1; - } - // Only the field's own `:` opens a format spec — one in a slice, a display or a - // lambda belongs to whatever bracket encloses it. - b':' if inside_expression => { - open.last_mut().expect("a brace is open").in_format_spec = true; - index += 1; - } - b'\'' | b'"' if !open.is_empty() => { - index = skip_quoted_string(bytes, index).min(content_end); - } - b'#' if inside_expression => { - index = skip_replacement_field_comment(bytes, index, content_end); - } - _ => index += 1, - } - } - - // CPython names the innermost unclosed delimiter, so a bracket opened inside the expression - // takes the message from the field that encloses it. - let &OpenDelimiter { - position, - opener, - in_format_spec, - } = open.last()?; - (!in_format_spec).then(|| { - CpythonDiagnostic::new( - format!("'{}' was never closed", opener as char), - position, - position + 1, - ) - .with_unclosed_bracket() - }) -} - -fn unterminated_string_message( - detected_line: usize, - triple: bool, - has_escaped_quote: bool, - prefix: Option<&str>, -) -> String { - // CPython names the literal kind, e.g. "unterminated f-string literal". - let kind = prefix.unwrap_or("string"); - if triple { - format!("unterminated triple-quoted {kind} literal (detected at line {detected_line})") - // The escaped-quote hint belongs to the plain-string branch of CPython's tokenizer alone. - // Its interpolated branch has only the two forms above and below, so pairing the hint with - // a prefix would invent a message CPython never emits. - } else if has_escaped_quote && prefix.is_none() { - format!( - "unterminated {kind} literal (detected at line {detected_line}); perhaps you escaped the end quote?" - ) - } else { - format!("unterminated {kind} literal (detected at line {detected_line})") - } -} - -fn expected_opening_bracket(closing: char) -> char { - match closing { - ')' => '(', - ']' => '[', - '}' => '{', - _ => unreachable!(), - } -} - -/// A bracket diagnostic, and whether it is an opener that was never closed. The caller needs -/// that apart from the message because ruff reports the unclosed case as an EOF error. -#[derive(Clone)] -struct BracketError { - diagnostic: CpythonDiagnostic, - unclosed: bool, -} - -fn bracket_syntax_error(source: &str) -> Option { - let mut stack: Vec<(char, usize, usize)> = Vec::new(); - let mut in_string = false; - let mut string_quote = '\0'; - let mut triple_quote = false; - let mut escape_next = false; - let mut is_raw_string = false; - let mut line = 1usize; - - let chars: Vec<(usize, char)> = source.char_indices().collect(); - let mut index = 0; - while index < chars.len() { - let (byte_offset, ch) = chars[index]; - - if ch == '\n' { - line += 1; - } - - if escape_next { - escape_next = false; - index += 1; - continue; - } - - if in_string { - if ch == '\\' && !is_raw_string { - escape_next = true; - } else if triple_quote { - if ch == string_quote - && index + 2 < chars.len() - && chars[index + 1].1 == string_quote - && chars[index + 2].1 == string_quote - { - in_string = false; - index += 3; - continue; - } - } else if ch == string_quote { - in_string = false; - } - index += 1; - continue; - } - - if ch == '#' { - while index < chars.len() && chars[index].1 != '\n' { - index += 1; - } - continue; - } - - if ch == '\\' { - match chars.get(index + 1).map(|(_, next)| *next) { - Some('\n' | '\r') => { - escape_next = true; - index += 1; - continue; - } - Some(_) => { - index += 2; - continue; - } - None => { - index += 1; - continue; - } - } - } - - if ch == '\'' || ch == '"' { - is_raw_string = false; - for look_back in 1..=2.min(index) { - let prev = chars[index - look_back].1; - if matches!(prev, 'r' | 'R') { - is_raw_string = true; - break; - } - if !matches!(prev, 'b' | 'B' | 'f' | 'F' | 'u' | 'U') { - break; - } - } - string_quote = ch; - if index + 2 < chars.len() && chars[index + 1].1 == ch && chars[index + 2].1 == ch { - triple_quote = true; - in_string = true; - index += 3; - continue; - } - triple_quote = false; - in_string = true; - index += 1; - continue; - } - - match ch { - '(' | '[' | '{' => stack.push((ch, byte_offset, line)), - ')' | ']' | '}' => { - let expected = expected_opening_bracket(ch); - let Some(&(opening, _, opening_line)) = stack.last() else { - return Some(BracketError { - diagnostic: CpythonDiagnostic::new( - format!("unmatched '{ch}'"), - byte_offset, - byte_offset, - ), - unclosed: false, - }); - }; - if opening == expected { - stack.pop(); - } else { - let suffix = if opening_line != line { - format!(" on line {opening_line}") - } else { - String::new() - }; - return Some(BracketError { - diagnostic: CpythonDiagnostic::new( - format!( - "closing parenthesis '{ch}' does not match opening parenthesis '{opening}'{suffix}" - ), - byte_offset, - byte_offset, - ), - unclosed: false, - }); - } - } - _ => {} - } - - index += 1; - } - - stack.last().map(|(opening, byte_offset, _)| BracketError { - diagnostic: CpythonDiagnostic::new( - format!("'{opening}' was never closed"), - *byte_offset, - *byte_offset, - ), - unclosed: true, - }) -} - -fn is_legacy_statement_expression_start(byte: u8) -> bool { - byte >= 0x80 - || byte == b'_' - || byte.is_ascii_alphabetic() - || byte.is_ascii_digit() - || matches!(byte, b'\'' | b'"' | b'{' | b'[') -} - -fn legacy_statement_container_has_invalid_attribute(bytes: &[u8], start: usize) -> bool { - let Some(&opening) = bytes.get(start) else { - return false; - }; - if !matches!(opening, b'{' | b'[') { - return false; - } - - let mut index = start; - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\n' | b';' if level == 0 => return false, - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'(' | b'[' | b'{' => { - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - if level == 0 { - return false; - } - } - b'.' => { - let mut cursor = index + 1; - while matches!(bytes.get(cursor), Some(b' ' | b'\t' | b'\x0c')) { - cursor += 1; - } - if matches!(bytes.get(cursor), Some(b')' | b']' | b'}')) { - return true; - } - index += 1; - } - _ => index += 1, - } - } - false -} - -fn invalid_legacy_statement_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'p' | b'e' => { - let keyword = if starts_identifier(bytes, index, b"print") { - Some("print") - } else if starts_identifier(bytes, index, b"exec") { - Some("exec") - } else { - None - }; - let Some(keyword) = keyword else { - index += 1; - continue; - }; - let after_keyword = index + keyword.len(); - if !matches!(bytes.get(after_keyword), Some(b' ' | b'\t' | b'\x0c')) { - index = after_keyword; - continue; - } - let mut cursor = after_keyword; - while matches!(bytes.get(cursor), Some(b' ' | b'\t' | b'\x0c')) { - cursor += 1; - } - if legacy_statement_container_has_invalid_attribute(bytes, cursor) { - index = after_keyword; - continue; - } - if bytes.get(cursor).is_some_and(|byte| { - *byte != b'(' && is_legacy_statement_expression_start(*byte) - }) { - return Some(CpythonDiagnostic::new( - format!( - "Missing parentheses in call to '{keyword}'. Did you mean {keyword}(...)?" - ), - index, - after_keyword, - )); - } - index = after_keyword; - } - _ => index += 1, - } - } - None -} - -/// Return the syntax error for a decimal integer literal exceeding the configured limit. -/// -/// The parser has already distinguished integer literals from strings, comments, floats, and -/// complex numbers. Inspecting its tokens keeps the limit consistent for every source parsing -/// entry point without reimplementing Python's lexer here. -#[must_use] -pub fn long_decimal_integer_literal_error( - source_file: &SourceFile, - tokens: &Tokens, - max_str_digits: usize, -) -> Option { - if max_str_digits == 0 { - return None; - } - tokens.iter().find_map(|token| { - if token.kind() != TokenKind::Int { - return None; - } - let literal = source_file.source_text().slice(token.range()); - if literal - .as_bytes() - .get(..2) - .is_some_and(|prefix| matches!(prefix, b"0x" | b"0X" | b"0o" | b"0O" | b"0b" | b"0B")) - { - return None; - } - let digits = literal.bytes().filter(u8::is_ascii_digit).count(); - (digits > max_str_digits).then(|| { - let start = token.range().start().to_usize(); - CompileError::from_source_error(source_file, CpythonDiagnostic::new(format!( - "Exceeds the limit ({max_str_digits} digits) for integer string conversion: value has {digits} digits; use sys.set_int_max_str_digits() to increase the limit - Consider hexadecimal for huge integer literals to avoid decimal conversion limits." - ), start, start)) - }) - }) -} - -fn invalid_parenthesized_import_star_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'f' if starts_identifier(bytes, index, b"from") => { - let mut cursor = index + 4; - while cursor < bytes.len() && !matches!(bytes[cursor], b'\n' | b';') { - if starts_identifier(bytes, cursor, b"import") { - cursor += 6; - while matches!(bytes.get(cursor), Some(b' ' | b'\t' | b'\r')) { - cursor += 1; - } - if bytes.get(cursor) == Some(&b'(') { - cursor += 1; - while cursor < bytes.len() - && !matches!(bytes[cursor], b')' | b'\n' | b';') - { - if bytes[cursor] == b'*' { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - cursor, - cursor + 1, - )); - } - cursor += 1; - } - } - break; - } - cursor += 1; - } - index = cursor; - } - _ => index += 1, - } - } - None -} - -fn prefix_letters_before_quote(bytes: &[u8], quote_index: usize) -> Option<(usize, Vec)> { - let mut letters = Vec::new(); - let mut index = quote_index; - while index > 0 { - let byte = bytes[index - 1]; - if !matches!( - byte, - b'r' | b'R' | b'b' | b'B' | b'u' | b'U' | b'f' | b'F' | b't' | b'T' - ) { - break; - } - letters.push(byte.to_ascii_lowercase()); - index -= 1; - } - if letters.is_empty() { - return None; - } - if index > 0 && (bytes[index - 1] == b'_' || bytes[index - 1].is_ascii_alphabetic()) { - return None; - } - letters.reverse(); - Some((index, letters)) -} - -fn incompatible_string_prefix_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - if let Some((start, letters)) = prefix_letters_before_quote(bytes, index) - && let Some(message) = incompatible_prefix_message(&letters) - { - return Some(CpythonDiagnostic::new(message, start, start + 1)); - } - index = skip_string_token(bytes, index); - } - _ => index += 1, - } - } - None -} - -fn incompatible_prefix_message(letters: &[u8]) -> Option { - if letters.len() < 2 { - return None; - } - let mut seen_r = false; - let mut seen_b = false; - let mut seen_u = false; - let mut seen_f = false; - let mut seen_t = false; - for &letter in letters { - match letter { - b'r' if seen_r => return None, - b'b' if seen_b => return None, - b'u' if seen_u => return None, - b'f' if seen_f => return None, - b't' if seen_t => return None, - b'r' => seen_r = true, - b'b' => seen_b = true, - b'u' => seen_u = true, - b'f' => seen_f = true, - b't' => seen_t = true, - _ => {} - } - } - let pair = if seen_u && seen_b { - ("u", "b") - } else if seen_u && seen_r { - ("u", "r") - } else if seen_u && seen_f { - ("u", "f") - } else if seen_u && seen_t { - ("u", "t") - } else if seen_b && seen_f { - ("b", "f") - } else if seen_b && seen_t { - ("b", "t") - } else if seen_f && seen_t { - ("f", "t") - } else { - return None; - }; - Some(format!( - "'{}' and '{}' prefixes are incompatible", - pair.0, pair.1 - )) -} - -fn malformed_unicode_n_escape_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - let quote_index = index; - let interpolated = interpolated_string_prefix(bytes, quote_index).is_some(); - let Some((content_start, content_end)) = - quoted_string_content_range(bytes, quote_index, bytes[quote_index]) - else { - index = skip_quoted_string(bytes, quote_index); - continue; - }; - if let Some(error) = malformed_unicode_n_in_content( - bytes, - content_start, - content_end, - quote_index, - interpolated, - ) { - return Some(error); - } - index = skip_string_token(bytes, quote_index); - } - _ => index += 1, - } - } - None -} - -fn malformed_unicode_n_in_content( - bytes: &[u8], - start: usize, - end: usize, - quote_index: usize, - interpolated: bool, -) -> Option { - let mut index = start; - let mut brace_depth = 0usize; - while index + 1 < end { - if interpolated && brace_depth == 0 && bytes[index] == b'{' { - if bytes.get(index + 1) == Some(&b'{') { - index += 2; - continue; - } - brace_depth = 1; - index += 1; - continue; - } - if interpolated && brace_depth > 0 { - match bytes[index] { - b'\'' | b'"' => index = skip_string_token(bytes, index).max(index + 1), - b'{' => { - brace_depth += 1; - index += 1; - } - b'}' => { - brace_depth -= 1; - index += 1; - } - _ => index += 1, - } - continue; - } - if bytes[index] == b'\\' && bytes[index + 1] == b'N' { - let escape_start = index; - if bytes.get(index + 2) == Some(&b'{') { - let mut look = index + 3; - while look < end && bytes[look] != b'}' { - look += 1; - } - if look >= end { - return Some(unicode_n_diagnostic(escape_start, end, start, quote_index)); - } - index = look + 1; - continue; - } - return Some(unicode_n_diagnostic( - escape_start, - escape_start + 2, - start, - quote_index, - )); - } - if interpolated && bytes[index] == b'}' && bytes.get(index + 1) == Some(&b'}') { - index += 2; - continue; - } - index += 1; - } - None -} - -fn unicode_n_diagnostic( - escape_start: usize, - escape_end: usize, - content_start: usize, - quote_index: usize, -) -> CpythonDiagnostic { - let start = escape_start - content_start; - let end = escape_end.saturating_sub(content_start).saturating_sub(1); - CpythonDiagnostic::new( - format!( - "(unicode error) 'unicodeescape' codec can't decode bytes in position {start}-{end}: malformed \\N character escape" - ), - quote_index, - quote_index + 1, - ) -} - -fn too_many_nested_interpolated_strings(source: &str) -> Option { - too_many_nested_interpolated_strings_in(source.as_bytes(), 0, source.len(), 0) -} - -fn too_many_nested_interpolated_strings_in( - bytes: &[u8], - mut index: usize, - end: usize, - depth: usize, -) -> Option { - while index < end { - match bytes[index] { - b'#' => { - while index < end && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - if interpolated_string_prefix(bytes, index).is_some() { - if depth + 1 >= MAXFSTRINGLEVEL { - return Some(CpythonDiagnostic::new( - "too many nested f-strings or t-strings".to_owned(), - index, - index + 1, - )); - } - if let Some((content_start, content_end)) = - interpolated_string_content_range(bytes, index) - && let Some(error) = too_many_nested_interpolated_strings_in( - bytes, - content_start, - content_end, - depth + 1, - ) - { - return Some(error); - } - } - index = skip_string_token(bytes, index).max(index + 1); - } - _ => index += 1, - } - } - None -} - -fn too_many_nested_parentheses_error(source: &str) -> Option { - const MAXLEVEL: usize = 200; - - let bytes = source.as_bytes(); - let mut index = 0; - let mut level = 0usize; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b'(' | b'[' | b'{' => { - if level >= MAXLEVEL { - return Some(CpythonDiagnostic::new( - "too many nested parentheses".to_owned(), - index, - index + 1, - )); - } - level += 1; - index += 1; - } - b')' | b']' | b'}' => { - level = level.saturating_sub(1); - index += 1; - } - _ => index += 1, - } - } - None -} - -fn invalid_unparenthesized_yield_after_comma_error(source: &str) -> Option { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => { - index = skip_quoted_string(bytes, index); - } - b',' => { - let mut cursor = index + 1; - while matches!(bytes.get(cursor), Some(b' ' | b'\t' | b'\x0c')) { - cursor += 1; - } - if starts_identifier(bytes, cursor, b"yield") { - return Some(CpythonDiagnostic::new( - "invalid syntax".to_owned(), - cursor, - cursor + 5, - )); - } - index += 1; - } - _ => index += 1, - } - } - None -} - -/// Horizontal and vertical space the tokenizer skips, not `str::trim()`. -const fn is_ascii_tokenizer_whitespace(c: char) -> bool { - matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c') -} - -/// True when every line is empty or a comment after tokenizer whitespace. -#[doc(hidden)] -#[must_use] -pub fn is_blank_python_source(source: &str) -> bool { - source.lines().all(|line| { - let trimmed = line.trim_matches(is_ascii_tokenizer_whitespace); - trimmed.is_empty() || trimmed.starts_with('#') - }) -} - -fn single_mode_blank_source_error(source_file: &SourceFile) -> Option { - let source = source_file.source_text(); - if !is_blank_python_source(source) { - return None; - } - let has_indent_only_line = source.lines().any(|line| { - line.trim_matches(is_ascii_tokenizer_whitespace).is_empty() - && line.chars().any(|c| matches!(c, ' ' | '\t')) - }); - if has_indent_only_line { - let (location, end_location) = - source_locations(source_file, TextSize::new(0), TextSize::new(0)); - return Some(CompileError::Parse(ParseError { - error: parser::ParseErrorType::UnexpectedIndentation, - raw_location: ruff_text_size::TextRange::new(TextSize::new(0), TextSize::new(0)), - location, - end_location, - source_path: source_file.name().to_owned(), - is_unclosed_bracket: false, - is_unclosed_string: false, - })); - } - Some(CompileError::from_source_error( - source_file, - CpythonDiagnostic::new("invalid syntax".to_owned(), 0, 0), - )) -} - -/// The byte-order mark is only stripped while decoding source bytes, so one -/// that survives into the text is just a non-printable character. The tokenizer -/// rejects it everywhere except at the very start of the text, which is where -/// this covers. -#[doc(hidden)] -#[must_use] -pub fn leading_byte_order_mark_error(source_file: &SourceFile) -> Option { - source_file.source_text().starts_with('\u{feff}').then(|| { - CompileError::from_source_error( - source_file, - CpythonDiagnostic::new("invalid non-printable character U+FEFF".to_owned(), 0, 0), - ) - }) -} - -/// Source-level errors raised before parsing, as CPython's tokenizer does. -/// -/// Checking after the parse would build the tree first, and one nested that -/// deep exhausts the native stack when it is dropped. -pub fn pre_parse_source_error(source_file: &SourceFile) -> Result<(), CompileError> { - match too_many_nested_parentheses_error(source_file.source_text()) { - Some(error) => Err(CompileError::from_source_error(source_file, error)), - None => Ok(()), - } -} - -fn post_parse_source_error( - source_file: &SourceFile, +/// Refine unpacking errors whose grammar context and operand range the parser already +/// identified. Tokens only distinguish the unpacking operator; they do not reparse the input. +fn unpacking_parse_diagnostic( + error: &parser::ParseError, + following_errors: &[parser::ParseError], tokens: &Tokens, - opts: &CompileOpts, -) -> Option { - if let Some(error) = leading_byte_order_mark_error(source_file) { - return Some(error); - } - if let Some(error) = too_many_nested_interpolated_strings(source_file.source_text()) { - return Some(CompileError::from_source_error(source_file, error)); - } - if let Some(error) = - long_decimal_integer_literal_error(source_file, tokens, opts.int_max_str_digits) + syntax: &ast::Mod, + no_unsupported_errors: bool, +) -> Option { + if matches!( + error.error, + ParseErrorType::InvalidStarredExpressionUsage | ParseErrorType::ExpectedExpression + ) && following_errors.is_empty() + && no_unsupported_errors { - return Some(error); - } - invalid_call_argument_error(source_file.source_text()) - .or_else(|| invalid_match_mapping_rest_wildcard_error(source_file.source_text())) - .or_else(|| invalid_match_as_target_error(source_file.source_text())) - .or_else(|| invalid_unparenthesized_yield_after_comma_error(source_file.source_text())) - .or_else(|| invalid_parenthesized_import_star_error(source_file.source_text())) - .map(|error| CompileError::from_source_error(source_file, error)) -} - -fn is_compound_stmt(stmt: &ast::Stmt) -> bool { - matches!( - stmt, - ast::Stmt::FunctionDef(_) - | ast::Stmt::ClassDef(_) - | ast::Stmt::If(_) - | ast::Stmt::For(_) - | ast::Stmt::While(_) - | ast::Stmt::With(_) - | ast::Stmt::Try(_) - | ast::Stmt::Match(_) - ) -} - -/// Rejects an AST nested deeper than `limit`. -/// -/// The parser grows its own stack, so it returns trees deeper than the passes -/// after it can walk, and each of those recurses without a limit of its own. -/// The symbol table applies the same limit, but `compile(..., PyCF_ONLY_AST)` -/// returns before reaching it. -pub fn too_deeply_nested_error( - ast: &ast::Mod, - source_file: &SourceFile, - limit: usize, -) -> Result<(), CompileError> { - use ast::visitor::Visitor; - - struct DepthChecker { - depth: usize, - limit: usize, - too_deep: Option, - } - - impl DepthChecker { - fn descend(&mut self, range: ruff_text_size::TextRange, walk: impl FnOnce(&mut Self)) { - if self.too_deep.is_some() { - return; - } - if self.depth >= self.limit { - self.too_deep = Some(range); - return; - } - self.depth += 1; - walk(self); - self.depth -= 1; - } - } - - impl<'a> Visitor<'a> for DepthChecker { - fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { - self.descend(stmt.range(), |checker| { - ast::visitor::walk_stmt(checker, stmt); + return owned_unpacking_diagnostic(error, tokens, syntax); + } + let ParseErrorType::OtherError(message) = &error.error else { + return None; + }; + let mut range = error.location; + let message = match message.as_str() { + "cannot use double starred expression here" if following_errors.is_empty() => { + let mut operand = tokens.iter().filter(|token| { + token.start() >= range.end() + && !matches!( + token.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline + ) }); + // The parser consumed a complete parenthesized operand. Lambda and + // `not` do not start the bitwise-or prefix required by CPython. + if matches!(operand.next()?.kind(), TokenKind::Lambda | TokenKind::Not) { + return None; + } + "cannot use dict unpacking here".to_owned() } - - fn visit_expr(&mut self, expr: &'a ast::Expr) { - self.descend(expr.range(), |checker| { - ast::visitor::walk_expr(checker, expr); + "pattern cannot follow a double star pattern" => { + // A later recovery error can change which invalid production CPython + // selects. Leave those inputs to the existing diagnostic conversion. + if !following_errors.is_empty() { + return None; + } + let mut preceding = tokens.iter().rev().filter(|token| { + token.end() <= range.start() + && !matches!( + token.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline + ) }); + // The parser has already recognized a mapping entry after its rest + // capture. CPython points at that capture, not the following entry. + if preceding.next()?.kind() != TokenKind::Comma { + return None; + } + let capture = preceding.next()?; + if capture.kind() != TokenKind::Identifier + || preceding.next()?.kind() != TokenKind::DoubleStar + { + return None; + } + range = capture.range(); + "double star pattern must be the last (right-most) subpattern in the mapping pattern" + .to_owned() } - - fn visit_pattern(&mut self, pattern: &'a ast::Pattern) { - self.descend(pattern.range(), |checker| { - ast::visitor::walk_pattern(checker, pattern); + "conditional expression cannot be used here" => { + let mut preceding = tokens.iter().rev().filter(|token| { + token.end() <= range.start() + && !matches!( + token.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline + ) }); + let operator = preceding.next()?; + let kind = match operator.kind() { + TokenKind::Star => "starred", + // Only the first dictionary spread uses this invalid production. + // Dictionary values and later spreads have different error priority. + TokenKind::DoubleStar + if preceding + .next() + .is_some_and(|token| token.kind() == TokenKind::Lbrace) => + { + "double starred" + } + _ => return None, + }; + range = ruff_text_size::TextRange::new(operator.start(), range.end()); + // Do not replace the operand error when the parser also rejected the + // enclosing unpacking operation, for example in a dictionary value. + if following_errors.iter().any(|error| { + error.location == range + && (matches!(error.error, ParseErrorType::InvalidStarredExpressionUsage) + || matches!(&error.error, ParseErrorType::OtherError(message) + if message == "cannot use a starred expression in a dictionary value")) + }) { + return None; + } + format!( + "invalid {kind} expression. Did you forget to wrap the conditional expression in parentheses?" + ) } - } - - let mut checker = DepthChecker { - depth: 0, - limit, - too_deep: None, - }; - match ast { - ast::Mod::Module(module) => checker.visit_body(&module.body), - ast::Mod::Expression(expression) => checker.visit_expr(&expression.body), - } - - let Some(range) = checker.too_deep else { - return Ok(()); + "expected expression after 'else', but statement is given" => { + let operator = tokens.iter().find(|token| token.range() == range)?; + match operator.kind() { + TokenKind::Star => "cannot unpack only part of a conditional expression", + TokenKind::DoubleStar => { + "cannot use dict unpacking on only part of a conditional expression" + } + _ => return None, + } + .to_owned() + } + _ => return None, }; - let (location, end_location) = source_locations(source_file, range.start(), range.end()); - Err(CompileError::Codegen(codegen::error::CodegenError { - location: Some(location), - end_location: Some(end_location), - error: codegen::error::CodegenErrorType::RecursionError, - source_path: source_file.name().to_owned(), - })) + Some(CpythonDiagnostic { message, range }) } -/// Syntax the reference grammar has no rule for, but that this parser accepts. -/// -/// A bare generator expression is one: `f(x for x in y)` is the `primary -/// genexp` alternative of a call, and a class header only takes `arguments`, -/// which has no such alternative. A format spec nested more than two deep is -/// the other; the tokenizer runs out of nesting levels for it. -#[doc(hidden)] -#[must_use] -pub fn unsupported_grammar_error(ast: &ast::Mod, source_file: &SourceFile) -> Option { +fn owned_unpacking_diagnostic( + error: &parser::ParseError, + tokens: &Tokens, + syntax: &ast::Mod, +) -> Option { use ast::visitor::Visitor; - /// The deepest chain of format specs one string literal may hold. - const MAX_FORMAT_SPEC_DEPTH: usize = 2; - struct Checker<'a> { - source_file: &'a SourceFile, - error: Option, + range: ruff_text_size::TextRange, + tokens: &'a Tokens, + comprehension: bool, + message: Option<&'static str>, } impl Checker<'_> { - fn fail(&mut self, message: &str, range: ruff_text_size::TextRange) { - self.error = Some(CompileError::from_source_error( - self.source_file, - CpythonDiagnostic::new( - message.to_owned(), - range.start().to_usize(), - range.end().to_usize(), - ), - )); + fn is_double_starred_operand(&self, operand: &ast::Expr) -> bool { + self.tokens + .iter() + .rev() + .find(|token| { + token.end() <= operand.start() + && !matches!( + token.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline + ) + }) + .is_some_and(|token| { + token.kind() == TokenKind::DoubleStar && token.start() == self.range.start() + }) } - fn check_format_specs( + fn check_comprehension( &mut self, - kind: &str, - elements: &ast::InterpolatedStringElements, - depth: usize, + element: &ast::Expr, + generators: &[ast::Comprehension], + delimiter: TokenKind, + container_start: TextSize, + message: &'static str, ) { - for element in elements.interpolations() { - let Some(format_spec) = &element.format_spec else { - continue; - }; - if depth == MAX_FORMAT_SPEC_DEPTH { - self.fail( - &alloc::format!("{kind}: expressions nested too deeply"), - format_spec.range, - ); - return; - } - self.check_format_specs(kind, &format_spec.elements, depth + 1); - if self.error.is_some() { - return; - } + let ast::Expr::BinOp(binary) = element else { + return; + }; + let ast::Expr::Name(missing) = binary.left.as_ref() else { + return; + }; + if binary.op != ast::Operator::Pow + || !missing.id.is_empty() + || missing.ctx != ast::ExprContext::Invalid + || !missing.range.is_empty() + || element.start() != self.range.start() + || generators.is_empty() + { + return; + } + let Some(operator) = self.tokens.iter().find(|token| token.range() == self.range) + else { + return; + }; + let preceding = self.tokens.iter().rev().find(|token| { + token.end() <= operator.start() + && !matches!( + token.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline + ) + }); + if operator.kind() == TokenKind::DoubleStar + && preceding.is_some_and(|token| { + token.kind() == delimiter && token.start() == container_start + }) + { + self.range = ruff_text_size::TextRange::new(operator.start(), element.end()); + self.message = Some(message); } } - } - impl<'a> Visitor<'a> for Checker<'_> { - fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { - if self.error.is_some() { + fn check_item(&mut self, key: Option<&ast::Expr>, value: &ast::Expr) { + let Some(key) = key else { return }; + // The parser reports InvalidStarredExpressionUsage at just the first + // byte of the operator. Recover the operand end from its retained role. + if self.range.len() != TextSize::new(1) { return; } - if let ast::Stmt::ClassDef(class_def) = stmt - && let Some(arguments) = &class_def.arguments - && let [ast::Expr::Generator(generator)] = &arguments.args[..] - && !generator.parenthesized + let (message, end) = if matches!(key, ast::Expr::Starred(_)) + && key.start() == self.range.start() + && self + .tokens + .iter() + .any(|token| token.kind() == TokenKind::Star && token.range() == self.range) { - let range = generator - .generators - .first() - .map_or(generator.range, |comprehension| comprehension.range); - self.fail("invalid syntax", range); + ( + "cannot use a starred expression in a dictionary key", + key.end(), + ) + } else if self.is_double_starred_operand(key) { + ("cannot use dict unpacking in a dictionary key", key.end()) + } else if self.is_double_starred_operand(value) { + ( + "cannot use dict unpacking in a dictionary value", + value.end(), + ) + } else { return; - } - ast::visitor::walk_stmt(self, stmt); + }; + self.range = ruff_text_size::TextRange::new(self.range.start(), end); + self.message = Some(message); } + } + impl<'a> Visitor<'a> for Checker<'_> { fn visit_expr(&mut self, expr: &'a ast::Expr) { - if self.error.is_some() { + if self.message.is_some() || !expr.range().contains_range(self.range) { return; } - // Each literal counts its own nesting: one written inside a format - // spec starts over. + // Retained nodes establish the operand role; the parser reported + // no other errors. Dictionary errors here only have first-item producers. match expr { - ast::Expr::FString(fstring) => { - for part in &fstring.value { - if let ast::FStringPart::FString(part) = part { - self.check_format_specs("f-string", &part.elements, 0); - } + ast::Expr::ListComp(comp) if self.comprehension => self.check_comprehension( + &comp.elt, + &comp.generators, + TokenKind::Lsqb, + comp.start(), + "cannot use dict unpacking in list comprehension", + ), + ast::Expr::Generator(comp) if self.comprehension && comp.parenthesized => self + .check_comprehension( + &comp.elt, + &comp.generators, + TokenKind::Lpar, + comp.start(), + "cannot use dict unpacking in generator expression", + ), + ast::Expr::Dict(dict) if !self.comprehension => { + if let Some(item) = dict.items.first() { + self.check_item(item.key.as_ref(), &item.value); } } - ast::Expr::TString(tstring) => { - for part in &tstring.value { - self.check_format_specs("t-string", &part.elements, 0); - } + ast::Expr::DictComp(dict) if !self.comprehension => { + self.check_item(dict.key.as_deref(), &dict.value) } _ => {} } - if self.error.is_some() { - return; + if self.message.is_none() { + ast::visitor::walk_expr(self, expr); } - ast::visitor::walk_expr(self, expr); } } let mut checker = Checker { - source_file, - error: None, + range: error.location, + tokens, + comprehension: matches!(error.error, ParseErrorType::ExpectedExpression), + message: None, }; - match ast { + match syntax { ast::Mod::Module(module) => checker.visit_body(&module.body), ast::Mod::Expression(expression) => checker.visit_expr(&expression.body), } - checker.error + checker.message.map(|message| CpythonDiagnostic { + message: message.to_owned(), + range: checker.range, + }) } -fn single_mode_body_error(body: &[ast::Stmt], source_file: &SourceFile) -> Option { - let first = body.first()?; - let source_code = source_file.to_source_code(); - let first_start = source_code.source_location(first.range().start(), PositionEncoding::Utf8); - let first_end = source_code.source_location(first.range().end(), PositionEncoding::Utf8); +/// The first logical input accepted by the single-input grammar. +#[derive(Clone, Copy)] +pub enum SingleModeStatementBoundary { + Simple { newline_index: usize, end: TextSize }, + Compound { end: TextSize }, +} - if body.iter().skip(1).any(|stmt| { - source_code - .source_location(stmt.range().start(), PositionEncoding::Utf8) - .line - > first_start.line - }) { - return Some(CompileError::from_source_error( - source_file, - CpythonDiagnostic::new( - "multiple statements found while compiling a single statement".to_owned(), - first.range().end().to_usize(), - first.range().end().to_usize(), - ), - )); +/// Classify a logical input without changing parser diagnostics or recovery. +#[must_use] +pub fn single_mode_statement_boundary( + parsed: &parser::Parsed, +) -> Option { + let ast::Mod::Module(module) = parsed.syntax() else { + return None; + }; + let first = module.body.first()?; + if is_compound_stmt(first) { + return Some(SingleModeStatementBoundary::Compound { end: first.end() }); } + let newline_index = parsed + .tokens() + .iter() + .position(|token| token.kind() == TokenKind::Newline)?; + Some(SingleModeStatementBoundary::Simple { + newline_index, + end: parsed.tokens()[newline_index].end(), + }) +} - if is_compound_stmt(first) - && first_start.line == first_end.line - && !ends_with_line_break(source_file.source_text()) - { +/// Single mode reads only the first statement when it is a simple statement, so any code after +/// its line is reported as multiple statements, ahead of errors the rest of the source has. +#[must_use] +pub fn single_mode_multiple_statements_error( + source_file: &SourceFile, + parsed: &parser::Parsed, +) -> Option { + let ast::Mod::Module(module) = parsed.syntax() else { + return None; + }; + let boundary = single_mode_statement_boundary(parsed)?; + if matches!(boundary, SingleModeStatementBoundary::Compound { .. }) { + // The interactive grammar ends a compound statement with a NEWLINE, + // so the first token of a following statement is invalid syntax. + let next = module.body.get(1)?; + if parsed + .errors() + .iter() + .any(|error| error.location.start() <= next.start()) + { + return None; + } + let token = parsed + .tokens() + .iter() + .find(|token| token.start() >= next.start() && !token.range().is_empty())?; return Some(CompileError::from_source_error( source_file, CpythonDiagnostic::new( "invalid syntax".to_owned(), - first.range().start().to_usize(), - first.range().start().to_usize(), + token.start().to_usize(), + token.end().to_usize(), ), )); } - None + let tokens = parsed.tokens(); + let SingleModeStatementBoundary::Simple { newline_index, .. } = boundary else { + unreachable!() + }; + let newline = &tokens[newline_index]; + if parsed + .errors() + .iter() + .any(|error| error.location.start() < newline.end()) + { + return None; + } + let mut rest = &source_file.source_text()[newline.end().to_usize()..]; + loop { + rest = rest.trim_start_matches([' ', '\t', '\n', '\r', '\x0c']); + match rest.strip_prefix('#') { + Some(comment) => rest = comment.find('\n').map_or("", |end| &comment[end..]), + None if rest.is_empty() => return None, + None => break, + } + } + // The error is at the newline token, which starts at a trailing comment. + let position = match newline_index.checked_sub(1).map(|index| &tokens[index]) { + Some(comment) if comment.kind() == TokenKind::Comment => comment.start(), + _ => newline.start(), + }; + // Include the comment and one logical newline character. Using the token's + // full end would count both bytes of CRLF; position + 1 truncates comments. + Some(CompileError::from_ruff_parse_error( + parser::ParseError { + error: parser::ParseErrorType::OtherError( + "multiple statements found while compiling a single statement".to_owned(), + ), + location: ruff_text_size::TextRange::new(position, newline.start() + TextSize::new(1)), + }, + source_file, + Mode::Single, + )) } fn single_mode_source_error(ast: &ast::Mod, source_file: &SourceFile) -> Option { @@ -7222,13 +2198,7 @@ pub fn compile( source_path: &str, opts: CompileOpts, ) -> Result { - // TODO: do this less hacky; ruff's parser should translate a CRLF line - // break in a multiline string into just an LF in the parsed value - #[cfg(windows)] - let source = source.replace("\r\n", "\n"); - #[cfg(windows)] - let source = source.as_str(); - + let source = core::normalize_newlines(source); let source_file = SourceFileBuilder::new(source_path, source).finish(); _compile(source_file, mode, opts) // let index = LineIndex::from_source_text(source); @@ -7277,12 +2247,22 @@ fn _compile_with_syntax_warning_handler<'a>( .contains(core::bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL), ); pre_parse_source_error(&source_file)?; - let parsed = parser::parse(barry_source.source(), parser_options); - if let Some(error) = barry_source.diagnostic(parsed.as_ref().err(), &source_file) { + let parsed = parser::parse_unchecked(barry_source.source(), parser_options.clone()); + if matches!(mode, Mode::Single) + && let Some(error) = single_mode_multiple_statements_error(&source_file, &parsed) + { + return Err(error); + } + if let Some(error) = barry_source.diagnostic(parsed.errors().first(), &source_file) { return Err(error); } - let parsed = - parsed.map_err(|err| CompileError::from_ruff_parse_error(err, &source_file, mode))?; + let parsed = first_parse_error( + parsed, + &source_file, + mode, + barry_source.source(), + &parser_options, + )?; if matches!(mode, Mode::Single) && let Some(error) = single_mode_blank_source_error(&source_file) { @@ -7355,11 +2335,9 @@ impl BarrySource<'_> { }) } - /// The obsolete `<>` operator the parse error points at, if any. In Barry - /// mode the operator was rewritten to `!=`, so the error lands on its - /// start; outside Barry mode ruff lexes `<` and then an unexpected `>`, so - /// the error lands one character in. Either way the whole operator is one - /// token to the tokenizer, so report it as one. + /// The `<>` operator the parse error points at, if any. In Barry mode the + /// operator was rewritten to `!=`, so the error lands on its start, and the + /// whole operator is one token to the tokenizer, so report it as one. #[must_use] pub fn invalid_legacy_operator( &self, @@ -7380,16 +2358,36 @@ impl BarrySource<'_> { .is_none_or(|(_, offset)| range.start() <= TextSize::new(offset as u32)) } - /// The diagnostic for this source, if any: an obsolete `<>` the parse - /// error points at, or -- in Barry mode only -- the first `!=`. A `<>` - /// takes precedence over a `!=` reported later in the source. + /// The Barry mode diagnostic for this source, if any: a `<>` the parse + /// error points at, or the first `!=`. A `<>` takes precedence over a `!=` + /// reported later in the source. #[must_use] pub fn diagnostic( &self, parse_error: Option<&parser::ParseError>, source_file: &SourceFile, ) -> Option { - if let Some(range) = parse_error.and_then(|error| self.invalid_legacy_operator(error)) { + if let Some(error) = parse_error + && let Some(range) = self.invalid_legacy_operator(error) + { + if error.location.start() > range.start() { + return Some(CompileError::from_source_error( + source_file, + CpythonDiagnostic::new( + "invalid syntax. Maybe you meant '!=' instead of '<>'?".to_owned(), + range.start().to_usize(), + range.end().to_usize(), + ), + )); + } + // At expression start, '<' is already invalid: the comparison + // production (and its obsolete-operator hint) was never entered. + // Barry mode instead lexed the rewritten '!=' as one token. + let range = if self.source.as_bytes()[range.start().to_usize()] == b'<' { + ruff_text_size::TextRange::at(range.start(), TextSize::new(1)) + } else { + range + }; return Some(barry_as_flufl_invalid_legacy_operator_error( source_file, range, @@ -7432,21 +2430,6 @@ pub fn barry_as_flufl_invalid_legacy_operator_error( ) } -/// Every `<>` in `source`, located by plain text search. Only used where the -/// operator is not rewritten, so an occurrence inside a string or a comment -/// costs nothing: it can never coincide with the location of a parse error. -fn textual_legacy_not_equal(source: &str) -> Vec { - source - .match_indices("<>") - .map(|(offset, matched)| { - ruff_text_size::TextRange::at( - TextSize::new(offset as u32), - TextSize::new(matched.len() as u32), - ) - }) - .collect() -} - #[doc(hidden)] pub fn prepare_barry_as_flufl_source( source: &str, @@ -7464,7 +2447,7 @@ pub fn prepare_barry_as_flufl_source( return BarrySource { source: Cow::Borrowed(source), not_equal: None, - legacy_not_equal: textual_legacy_not_equal(source), + legacy_not_equal: Vec::new(), }; }; @@ -7503,6 +2486,62 @@ pub fn prepare_barry_as_flufl_source( } } +/// Parse-only state for a native interactive record. This never runs codegen, +/// emits Python warnings, or changes the caller's future flags. +pub struct InteractiveInput { + pub future_features: core::bytecode::CodeFlags, + pub empty: bool, +} + +/// The native interactive grammar terminates compound statements with an empty +/// physical line (or EOF), unlike the module grammar used by the Ruff parser. +/// Use the parsed statement shape rather than a second ad-hoc source lexer. +pub fn interactive_input( + source: &str, + source_path: &str, + future_features: core::bytecode::CodeFlags, + terminated: bool, +) -> Result, CompileError> { + let source_file = SourceFileBuilder::new(source_path, source).finish(); + pre_parse_source_error(&source_file)?; + let options = parser::ParseOptions::from(parser::Mode::Module); + let prepared = prepare_barry_as_flufl_source( + source, + options.clone(), + future_features.contains(core::bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL), + ); + let parsed = parser::parse_unchecked(prepared.source(), options.clone()); + if let Some(error) = single_mode_multiple_statements_error(&source_file, &parsed) { + return Err(error); + } + if let Some(error) = prepared.diagnostic(parsed.errors().first(), &source_file) { + return Err(error); + } + let parsed = first_parse_error( + parsed, + &source_file, + Mode::Single, + prepared.source(), + &options, + )?; + let ast::Mod::Module(module) = parsed.syntax() else { + unreachable!() + }; + // A compound statement ends with an empty line or EOF. + if !terminated && module.body.first().is_some_and(is_compound_stmt) { + return Ok(None); + } + if let Some(error) = unsupported_grammar_error(parsed.syntax(), &source_file) { + return Err(error); + } + let future_features = codegen::preprocess::checked_future_features_in_body(&module.body) + .map_err(|error| future_feature_error(error, &source_file))?; + Ok(Some(InteractiveInput { + future_features, + empty: module.body.is_empty(), + })) +} + pub fn compile_with_syntax_warning_handler<'a>( source: &str, mode: Mode, @@ -7510,9 +2549,7 @@ pub fn compile_with_syntax_warning_handler<'a>( opts: CompileOpts, syntax_warning_handler: &'a mut compile::SyntaxWarningHandler<'a>, ) -> Result { - let source = source.replace("\r\n", "\n"); - #[cfg(windows)] - let source = source.as_str(); + let source = core::normalize_newlines(source); let source_file = SourceFileBuilder::new(source_path, source).finish(); _compile_with_syntax_warning_handler(source_file, mode, opts, Some(syntax_warning_handler)) @@ -7523,6 +2560,7 @@ pub fn compile_symtable( mode: Mode, source_path: &str, ) -> Result { + let source = core::normalize_newlines(source); let source_file = SourceFileBuilder::new(source_path, source).finish(); _compile_symtable(source_file, mode) } @@ -7580,12 +2618,23 @@ pub fn _compile_symtable( let res = match mode { Mode::Exec | Mode::Single | Mode::BlockExpr => { pre_parse_source_error(&source_file)?; - let parsed = ruff_python_parser::parse(barry_source.source(), parser_options); - if let Some(error) = barry_source.diagnostic(parsed.as_ref().err(), &source_file) { + let parsed = + ruff_python_parser::parse_unchecked(barry_source.source(), parser_options.clone()); + if matches!(mode, Mode::Single) + && let Some(error) = single_mode_multiple_statements_error(&source_file, &parsed) + { + return Err(error); + } + if let Some(error) = barry_source.diagnostic(parsed.errors().first(), &source_file) { return Err(error); } - let ast = - parsed.map_err(|e| CompileError::from_ruff_parse_error(e, &source_file, mode))?; + let ast = first_parse_error( + parsed, + &source_file, + mode, + barry_source.source(), + &parser_options, + )?; if let Some(error) = post_parse_source_error(&source_file, ast.tokens(), &CompileOpts::default()) { @@ -7608,12 +2657,18 @@ pub fn _compile_symtable( } Mode::Eval => { pre_parse_source_error(&source_file)?; - let parsed = ruff_python_parser::parse(barry_source.source(), parser_options); - if let Some(error) = barry_source.diagnostic(parsed.as_ref().err(), &source_file) { + let parsed = + ruff_python_parser::parse_unchecked(barry_source.source(), parser_options.clone()); + if let Some(error) = barry_source.diagnostic(parsed.errors().first(), &source_file) { return Err(error); } - let ast = - parsed.map_err(|e| CompileError::from_ruff_parse_error(e, &source_file, mode))?; + let ast = first_parse_error( + parsed, + &source_file, + mode, + barry_source.source(), + &parser_options, + )?; if let Some(error) = post_parse_source_error(&source_file, ast.tokens(), &CompileOpts::default()) { @@ -7732,11 +2787,11 @@ mod tests { ), ( "t\"x\" b\"y\"", - "Cannot mix t-string literals with string or bytes literals", + "cannot mix t-string literals with string or bytes literals", ), ( "b\"x\" t\"y\"", - "Cannot mix t-string literals with string or bytes literals", + "cannot mix t-string literals with string or bytes literals", ), // The literals ahead of the first t-string already mix, so CPython's first pass // raises from `_PyPegen_concatenate_strings` before the t-string rule is reached. @@ -7819,7 +2874,6 @@ mod tests { "(print x; '\\N'", "Missing parentheses in call to 'print'. Did you mean print(...)?", ), - ("f'{x'; '", "f-string: expecting '}'"), ("f'{x'; 0x", "f-string: expecting '}'"), ( "print x; f'{x'; 0x", @@ -7835,7 +2889,10 @@ mod tests { "f-string: valid expression required before '}'", ), ("{\\'a\\'}", "unexpected character after line continuation"), - ("\"\\\n\"(1 for c in I,\\\n\\", "'(' was never closed"), + ( + "\"\\\n\"(1 for c in I,\\\n\\", + "unexpected character after line continuation character", + ), ( r"'\N'", "(unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: malformed \\N character escape", @@ -8320,7 +3377,10 @@ mod tests { fn obsolete_not_equal_diagnostic_spans_the_whole_operator() { let err = compile("2 <> 3\n", Mode::Exec, "", CompileOpts::default()) .expect_err("'<>' outside Barry mode is a syntax error"); - assert_eq!(err.to_string(), "invalid syntax"); + assert_eq!( + err.to_string(), + "invalid syntax. Maybe you meant '!=' instead of '<>'?" + ); assert_eq!(err.python_location(), (1, 3)); assert_eq!(err.python_end_location(), Some((1, 5))); @@ -8332,13 +3392,25 @@ mod tests { assert_eq!(err.python_location(), (1, 4)); assert_eq!(err.python_end_location(), Some((1, 5))); - // A `<>` that starts a statement is reported at the `<` too, where the - // parser stops instead of one character in. + // A `<>` that starts a statement is not a comparison, so only the `<` + // is reported. let err = compile("<>\n", Mode::Exec, "", CompileOpts::default()) .expect_err("a bare '<>' is a syntax error"); assert_eq!(err.to_string(), "invalid syntax"); assert_eq!(err.python_location(), (1, 1)); - assert_eq!(err.python_end_location(), Some((1, 3))); + assert_eq!(err.python_end_location(), Some((1, 2))); + + // `<<>` is a left shift followed by `>`. + let err = compile( + "2 <<> 3\n", + Mode::Exec, + "", + CompileOpts::default(), + ) + .expect_err("'<<>' is a syntax error"); + assert_eq!(err.to_string(), "invalid syntax"); + assert_eq!(err.python_location(), (1, 5)); + assert_eq!(err.python_end_location(), Some((1, 6))); // A bracket left open earlier in the source outranks the operator. let err = compile( diff --git a/crates/derive-impl/Cargo.toml b/crates/derive-impl/Cargo.toml index 1c2b5704785..9106d8697b4 100644 --- a/crates/derive-impl/Cargo.toml +++ b/crates/derive-impl/Cargo.toml @@ -18,7 +18,6 @@ syn = { workspace = true, features = ["full", "extra-traits", "visit", "visit-mu proc-macro2 = { workspace = true } quote = { workspace = true } -syn-ext = { workspace = true, features = ["full"] } textwrap = { workspace = true, default-features = false } [lints] diff --git a/crates/derive-impl/src/compile_bytecode.rs b/crates/derive-impl/src/compile_bytecode.rs index d28a7db3b17..e08c230e27d 100644 --- a/crates/derive-impl/src/compile_bytecode.rs +++ b/crates/derive-impl/src/compile_bytecode.rs @@ -145,10 +145,16 @@ impl CompilationSource { let mut code_map = HashMap::new(); let paths = fs::read_dir(path) .or_else(|e| { + // Without symlink support git checks a symlink out as a text file + // holding its target, which is relative to the file's own directory. if cfg!(windows) - && let Ok(real_path) = fs::read_to_string(path.canonicalize().unwrap()) + && let Ok(target) = fs::read_to_string(path) { - return fs::read_dir(real_path.trim()); + let target_dir = path + .parent() + .unwrap_or_else(|| Path::new("")) + .join(target.trim()); + return fs::read_dir(target_dir); } Err(e) }) @@ -171,6 +177,10 @@ impl CompilationSource { }; code_map.extend(self.compile_dir(base, &path, &nparent, mode, compiler)?); } else if file_name.ends_with(".py") { + // These fixtures must be parsed at import time to exercise syntax errors. + if parent == "test.test_lazy_import.data.badsyntax" { + continue; + } let stem = path.file_stem().unwrap().to_str().unwrap(); let is_init = stem == "__init__"; let module_name = if is_init { diff --git a/crates/derive-impl/src/from_args.rs b/crates/derive-impl/src/from_args.rs index cb53dfa6e6f..8971a25a68f 100644 --- a/crates/derive-impl/src/from_args.rs +++ b/crates/derive-impl/src/from_args.rs @@ -1,11 +1,14 @@ use proc_macro2::TokenStream; -use quote::{ToTokens, quote}; +use quote::{ToTokens, format_ident, quote}; use syn::ext::IdentExt; use syn::meta::ParseNestedMeta; use syn::{ Attribute, Data, DeriveInput, Expr, Field, Ident, Lit, Result, Token, Type, parse_quote, }; +#[cfg(test)] +mod integer_alias_tests; + /// The kind of the python parameter, this corresponds to the value of Parameter.kind /// (https://docs.python.org/3/library/inspect.html#inspect.Parameter.kind) #[derive(Clone, Copy, Default, Eq, PartialEq)] @@ -156,7 +159,102 @@ impl TryFrom<&Field> for ArgAttribute { } } -fn generate_field((i, field): (usize, &Field)) -> Result { +#[derive(Clone, Copy)] +enum FieldMode { + Clinic, + Legacy, +} + +fn try_from_object_expr(attr: &ArgAttribute, pyname: &str) -> TokenStream { + if let Some(error_msg) = &attr.error_msg { + return quote! { + ::rustpython_vm::convert::TryFromObject::try_from_object(vm, x) + .map_err(|_| vm.new_type_error(#error_msg)) + }; + } + match attr.kind { + ParameterKind::PositionalOnly => quote! { + ::rustpython_vm::convert::TryFromObject::try_from_argument(vm, x) + }, + _ => quote! { + ::rustpython_vm::convert::TryFromObject::try_from_argument(vm, x) + .map_err(|err| err.with_argument_name(#pyname)) + }, + } +} + +fn default_ending_tokens(field: &Field, default: DefaultValue) -> Result { + let ty = &field.ty; + let literal_obj = match &default { + Some(expr) if !keeps_direct_literal(ty) && !is_wrapped_arg_ty(ty) => { + literal_object_expr(expr) + } + _ => None, + }; + if let Some(obj) = literal_obj { + Ok(quote! { + .map(<#ty as ::rustpython_vm::function::FromArgOptional>::from_inner) + .map(::core::result::Result::Ok) + .unwrap_or_else(|| { + <#ty as ::rustpython_vm::convert::TryFromObject>::try_from_object( + vm, + ::rustpython_vm::convert::ToPyObject::to_pyobject(#obj, vm), + ) + .map_err(::rustpython_vm::function::ArgumentError::from) + })? + }) + } else { + let default = match default { + Some(expr) => match absolute_const_ident(&expr)? { + Some(name) => parse_quote!(::core::convert::Into::into(#name)), + None => expr, + }, + None => parse_quote!(::std::default::Default::default()), + }; + Ok(quote! { + .map(<#ty as ::rustpython_vm::function::FromArgOptional>::from_inner) + .unwrap_or_else(|| #default) + }) + } +} + +fn missing_ending_tokens(kind: ParameterKind, pyname: &str, i: usize) -> TokenStream { + // Flatten returns before this is called. A named-or-positional missing + // argument is named back; a positional-only one is only counted. + let err = if kind == ParameterKind::PositionalOnly { + quote! { + ::rustpython_vm::function::ArgumentError::TooFewArgs + } + } else { + let pos = i + 1; + quote! { + ::rustpython_vm::function::ArgumentError::MissingRequiredArgument { + name: #pyname.to_owned(), + pos: #pos, + } + } + }; + quote! { + .ok_or_else(|| #err)? + } +} + +fn take_option_tokens(kind: ParameterKind, pyname: &str) -> TokenStream { + if kind == ParameterKind::PositionalOnly { + quote!(args.take_positional()) + } else if kind == ParameterKind::KeywordOnly { + quote!(args.take_keyword(#pyname)) + } else { + quote!(args.take_positional_keyword(#pyname)) + } +} + +#[cfg(test)] +fn generate_field(item: (usize, &Field)) -> Result { + generate_field_with(item, FieldMode::Clinic) +} + +fn generate_field_with((i, field): (usize, &Field), mode: FieldMode) -> Result { let attr = ArgAttribute::try_from(field)?; let name = field.ident.as_ref(); let name_string = name.map(|ident| ident.unraw().to_string()); @@ -179,90 +277,36 @@ fn generate_field((i, field): (usize, &Field)) -> Result { let pyname = attr .name + .clone() .or(name_string) .ok_or_else(|| err_span!(field, "field in tuple struct must have name attribute"))?; + let convert = try_from_object_expr(&attr, &pyname); - let middle = if let Some(error_msg) = &attr.error_msg { - quote! { - .map(|x| ::rustpython_vm::convert::TryFromObject::try_from_object(vm, x) - .map_err(|_| vm.new_type_error(#error_msg))).transpose()? - } - } else { - quote! { - .map(|x| ::rustpython_vm::convert::TryFromObject::try_from_object(vm, x)).transpose()? - } - }; + if let FieldMode::Legacy = mode + && attr.default.is_none() + { + return Ok(quote! { + #field_name: { + let x = slots.required(vm)?; + #convert? + }, + }); + } + let middle = quote! { .map(|x| #convert).transpose()? }; + let taken = match mode { + FieldMode::Clinic => take_option_tokens(attr.kind, &pyname), + FieldMode::Legacy => quote!(slots.optional(vm)?), + }; let ending = if let Some(default) = attr.default { - let ty = &field.ty; - let literal_obj = match &default { - Some(expr) if !keeps_direct_literal(ty) && !is_wrapped_arg_ty(ty) => { - literal_object_expr(expr) - } - _ => None, - }; - if let Some(obj) = literal_obj { - quote! { - .map(<#ty as ::rustpython_vm::function::FromArgOptional>::from_inner) - .map(::core::result::Result::Ok) - .unwrap_or_else(|| { - <#ty as ::rustpython_vm::convert::TryFromObject>::try_from_object( - vm, - ::rustpython_vm::convert::ToPyObject::to_pyobject(#obj, vm), - ) - .map_err(::rustpython_vm::function::ArgumentError::from) - })? - } - } else { - let default = match default { - Some(expr) => match absolute_const_ident(&expr)? { - Some(name) => parse_quote!(::core::convert::Into::into(#name)), - None => expr, - }, - None => parse_quote!(::std::default::Default::default()), - }; - quote! { - .map(<#ty as ::rustpython_vm::function::FromArgOptional>::from_inner) - .unwrap_or_else(|| #default) - } - } + default_ending_tokens(field, default)? } else { - // A parameter a call may name is named back when it is missing; one - // that can only be passed by position is only ever counted. - let err = match attr.kind { - ParameterKind::PositionalOnly => quote! { - ::rustpython_vm::function::ArgumentError::TooFewArgs - }, - ParameterKind::PositionalOrKeyword | ParameterKind::KeywordOnly => { - let pos = i + 1; - quote! { - ::rustpython_vm::function::ArgumentError::MissingRequiredArgument { - name: #pyname.to_owned(), - pos: #pos, - } - } - } - ParameterKind::Flatten => unreachable!(), - }; - quote! { - .ok_or_else(|| #err)? - } + missing_ending_tokens(attr.kind, &pyname, i) }; - let file_output = match attr.kind { - ParameterKind::PositionalOnly => quote! { - #field_name: args.take_positional()#middle #ending, - }, - ParameterKind::PositionalOrKeyword => quote! { - #field_name: args.take_positional_keyword(#pyname)#middle #ending, - }, - ParameterKind::KeywordOnly => quote! { - #field_name: args.take_keyword(#pyname)#middle #ending, - }, - ParameterKind::Flatten => unreachable!(), - }; - - Ok(file_output) + Ok(quote! { + #field_name: #taken #middle #ending, + }) } fn is_phantom(field: &Field) -> bool { @@ -293,6 +337,7 @@ fn is_primitive_int(ty: &Type) -> bool { | "i64" | "i128" | "isize" + | "PySsize" | "u8" | "u16" | "u32" @@ -523,7 +568,7 @@ fn signature_default(field: &Field, attr: &ArgAttribute) -> Result } else if is_float_ty(ty) { quote!(#repr::Raw("0.0")) } else { - quote!(#repr::Unrepresentable) + quote!(#repr::Unknown) }; return Ok(quote!(Some(#value))); } @@ -531,11 +576,19 @@ fn signature_default(field: &Field, attr: &ArgAttribute) -> Result } fn param_token(field: &Field, attr: &ArgAttribute) -> Result { + param_token_with(field, attr, &format_ident!("PARAMS")) +} + +fn param_token_with( + field: &Field, + attr: &ArgAttribute, + metadata: &syn::Ident, +) -> Result { if let ParameterKind::Flatten = attr.kind { let ty = &field.ty; return Ok(quote! { ::rustpython_vm::function::Param::flatten( - <#ty as ::rustpython_vm::function::FromArgs>::PARAMS + <#ty as ::rustpython_vm::function::FromArgs>::#metadata ) }); } @@ -566,6 +619,170 @@ fn param_token(field: &Field, attr: &ArgAttribute) -> Result { }) } +struct LegacyFromArgs { + fname: String, +} + +enum FromArgsMode { + Owned, + Legacy(LegacyFromArgs), + Borrowed, +} + +fn parse_from_args_attr( + attrs: &[Attribute], +) -> Result<(FromArgsMode, Option)> { + let mut found = None; + for attr in attrs { + if !attr.path().is_ident("from_args") { + continue; + } + if found.is_some() { + bail_span!(attr, "multiple #[from_args] attributes"); + } + found = Some(attr); + } + let Some(attr) = found else { + return Ok((FromArgsMode::Owned, None)); + }; + + let mut text_signature = None; + let mut borrowed = false; + let mut legacy = false; + let mut fname = None; + attr.parse_nested_meta(|meta| { + if meta.path.is_ident("text_signature") { + if text_signature.is_some() { return Err(meta.error("duplicate `text_signature`")); } + let value = meta.value()?.parse::()?; + let signature = crate::text_signature::TextSignature::parse(value.value(), value.span())?; + signature.validate_receiver(None, value.span())?; + text_signature = Some(signature); + Ok(()) + } else if meta.path.is_ident("borrowed") { + if borrowed { + return Err(meta.error("duplicate `borrowed`")); + } + borrowed = true; + Ok(()) + } else if meta.path.is_ident("legacy") { + if legacy { + return Err(meta.error("duplicate `legacy`")); + } + legacy = true; + Ok(()) + } else if meta.path.is_ident("fname") { + if fname.is_some() { + return Err(meta.error("duplicate `fname`")); + } + let val = meta.value()?.parse::()?; + fname = Some(val.value()); + Ok(()) + } else { + Err(meta.error( + "unknown #[from_args] key; expected `text_signature`, `borrowed`, `legacy`, or `fname = \"...\"`", + )) + } + })?; + + let mode = match (borrowed, legacy, fname) { + (true, false, None) => Ok(FromArgsMode::Borrowed), + (false, true, Some(fname)) => Ok(FromArgsMode::Legacy(LegacyFromArgs { fname })), + (true, _, _) => Err(err_span!( + attr, + "borrowed FromArgs uses Clinic binding; legacy parsing requires owned arguments" + )), + (false, true, None) => Err(err_span!( + attr, + "#[from_args(legacy)] requires fname = \"...\"" + )), + (false, false, Some(_)) => Err(err_span!( + attr, + "#[from_args(fname = \"...\")] requires `legacy`" + )), + (false, false, None) if text_signature.is_some() => Ok(FromArgsMode::Owned), + (false, false, None) => Err(err_span!( + attr, + "#[from_args] requires `legacy` and fname = \"...\"" + )), + }?; + Ok((mode, text_signature)) +} + +fn field_pyname(field: &Field, attr: &ArgAttribute) -> Result { + let name = field.ident.as_ref().map(|ident| ident.unraw().to_string()); + attr.name + .clone() + .or(name) + .ok_or_else(|| err_span!(field, "field in tuple struct must have name attribute")) +} + +fn validate_legacy_fields<'a>(fields: impl IntoIterator) -> Result<()> { + let mut seen_optional = false; + let mut seen_keyword_only = false; + for field in fields { + if is_phantom(field) { + continue; + } + let attr = ArgAttribute::try_from(field)?; + match attr.kind { + ParameterKind::PositionalOnly => { + bail_span!( + field, + "#[from_args(legacy)] does not support positional-only fields" + ); + } + ParameterKind::Flatten => { + bail_span!( + field, + "#[from_args(legacy)] does not support flatten fields" + ); + } + ParameterKind::KeywordOnly => { + seen_keyword_only = true; + } + ParameterKind::PositionalOrKeyword => { + if seen_keyword_only { + bail_span!( + field, + "#[from_args(legacy)] does not allow a non-keyword-only field after a keyword-only field" + ); + } + } + } + if attr.default.is_some() { + seen_optional = true; + } else if seen_optional { + bail_span!( + field, + "#[from_args(legacy)] does not allow a required field after an optional one" + ); + } + } + Ok(()) +} + +fn legacy_spec_parts<'a>( + fields: impl IntoIterator, +) -> Result<(Vec, usize, usize)> { + let mut keywords = Vec::new(); + let mut required = 0; + let mut max_positional = 0; + for field in fields { + if is_phantom(field) { + continue; + } + let attr = ArgAttribute::try_from(field)?; + keywords.push(field_pyname(field, &attr)?); + if attr.default.is_none() { + required += 1; + } + if attr.kind != ParameterKind::KeywordOnly { + max_positional += 1; + } + } + Ok((keywords, required, max_positional)) +} + fn compute_arity_bounds(field_attrs: &[ArgAttribute]) -> (usize, usize) { let positional_fields = field_attrs.iter().filter(|attr| { matches!( @@ -583,7 +800,152 @@ fn compute_arity_bounds(field_attrs: &[ArgAttribute]) -> (usize, usize) { (min_arity, max_arity) } +fn impl_borrowed_from_args( + input: &DeriveInput, + fields: &syn::Fields, + text_signature: TokenStream, +) -> Result { + let lifetimes = input.generics.lifetimes().collect::>(); + if lifetimes.len() != 1 || input.generics.params.len() != 1 { + bail_span!( + input.generics, + "borrowed FromArgs requires exactly one lifetime and no type or const parameters" + ); + } + let lifetime = &lifetimes[0].lifetime; + let name = &input.ident; + let mut params = Vec::new(); + let mut values = Vec::new(); + let attrs = fields + .iter() + .filter(|field| !is_phantom(field)) + .map(ArgAttribute::try_from) + .collect::>>()?; + let (min, max) = compute_arity_bounds(&attrs); + let mut slot = 0usize; + for (i, field) in fields.iter().enumerate() { + let attr = ArgAttribute::try_from(field)?; + if is_phantom(field) { + let member = &field.ident; + values.push(quote!(#member: ::core::marker::PhantomData,)); + continue; + } + if attr.kind == ParameterKind::Flatten { + bail_span!(field, "borrowed FromArgs does not support flattened fields"); + } + if attr.py_default.is_some() && attr.default.is_none() { + bail_span!( + field, + "a borrowed py_default requires optional or default omission handling" + ); + } + params.push(param_token(field, &attr)?); + let member = field.ident.as_ref().map_or_else( + || syn::Index::from(i).into_token_stream(), + ToTokens::to_token_stream, + ); + let pyname = attr + .name + .clone() + .or_else(|| field.ident.as_ref().map(|name| name.unraw().to_string())) + .ok_or_else(|| err_span!(field, "field in tuple struct must have name attribute"))?; + let mut convert = quote! { + ::rustpython_vm::convert::TryFromBorrowedObject::try_from_borrowed_argument(vm, x) + }; + if let Some(message) = &attr.error_msg { + convert = quote! { + #convert.map_err(|_| ::rustpython_vm::function::ArgumentError::from(vm.new_type_error(#message))) + }; + } else if attr.kind != ParameterKind::PositionalOnly { + convert = quote! { #convert.map_err(|err| err.with_argument_name(#pyname)) }; + } + let ending = if let Some(default) = attr.default { + let ty = &field.ty; + if let Some(expr) = &default + && !keeps_direct_literal(ty) + && !is_wrapped_arg_ty(ty) + && literal_object_expr(expr).is_some() + { + bail_span!( + field, + "a borrowed default cannot allocate an owned Python object; use OptionalArg with py_default or a Rust converter constant" + ); + } + let default = match default { + Some(expr) => match absolute_const_ident(&expr)? { + Some(name) => quote!(::core::convert::Into::into(#name)), + None => quote!(#expr), + }, + None => quote!(::core::default::Default::default()), + }; + quote! { + .map(<#ty as ::rustpython_vm::function::FromBorrowedArgOptional<#lifetime>>::from_inner) + .unwrap_or_else(|| #default) + } + } else { + quote! { .expect("Clinic checked the required argument") } + }; + let i = slot; + slot += 1; + let pos = i + 1; + values.push(quote! { + #member: slots[#i].map(|x| #convert) + .transpose() + .map_err(|error| error.into_exception(&(#min..=#max), args.args.len(), #pos, callee, vm))? + #ending, + }); + } + let n = slot; + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + Ok(quote! { + impl #impl_generics ::rustpython_vm::function::ArgsMetadata for #name #ty_generics #where_clause { + #text_signature + const DISPLAY_PARAMS: ::core::option::Option<&'static [::rustpython_vm::function::Param]> = + Some(&[#(#params),*]); + } + + impl ::rustpython_vm::function::BorrowedArgs for #name<'static> { + type Bound<#lifetime> = #name<#lifetime>; + + #[inline] + fn bind<#lifetime>( + args: &#lifetime ::rustpython_vm::function::FuncArgs, + vm: &::rustpython_vm::VirtualMachine, + callee: ::rustpython_vm::function::Callee, + ) -> ::rustpython_vm::PyResult> { + let slots = args.bind_borrowed::<#n, Self>(vm, callee)?; + Ok(#name { #(#values)* }) + } + } + }) +} + pub(crate) fn impl_from_args(input: DeriveInput) -> Result { + let (mode, signature) = parse_from_args_attr(&input.attrs)?; + let text_signature = signature.map_or_else(TokenStream::new, |signature| { + let text = signature.text.clone(); + let params = signature.params_tokens(); + let validator = signature.validator(); + quote! { + const TEXT_SIGNATURE: Option<&'static str> = { + #validator( + &[::rustpython_vm::function::SigArg::from_arg::("")], + &[#(#params),*], + ); + Some(#text) + }; + } + }); + let legacy = match mode { + FromArgsMode::Borrowed => { + let Data::Struct(data) = &input.data else { + bail_span!(input, "FromArgs input must be a struct"); + }; + return impl_borrowed_from_args(&input, &data.fields, text_signature); + } + FromArgsMode::Legacy(legacy) => Some(legacy), + FromArgsMode::Owned => None, + }; let Data::Struct(syn::DataStruct { fields: struct_fields, .. @@ -591,17 +953,39 @@ pub(crate) fn impl_from_args(input: DeriveInput) -> Result { else { bail_span!(input, "FromArgs input must be a struct") }; + if legacy.is_some() { + validate_legacy_fields(&struct_fields)?; + } + let mode = if legacy.is_some() { + FieldMode::Legacy + } else { + FieldMode::Clinic + }; let fields = struct_fields .iter() .enumerate() - .map(generate_field) + .map(|item| generate_field_with(item, mode)) .collect::>()?; let field_attrs = struct_fields .iter() .map(ArgAttribute::try_from) .collect::>>()?; - let (min_arity, max_arity) = compute_arity_bounds(&field_attrs); + // Phantom fields are absent from both argument extraction and signatures. + let visible_attrs = struct_fields + .iter() + .filter(|field| !is_phantom(field)) + .map(ArgAttribute::try_from) + .collect::>>()?; + let (min_arity, max_arity) = compute_arity_bounds(&visible_attrs); + // Flattened types contribute both bounds. Saturate each sum, including + // custom required bounds and an unbounded `PosArgs` upper bound. + let flattened = struct_fields + .iter() + .zip(&field_attrs) + .filter(|(field, attr)| !is_phantom(field) && attr.kind == ParameterKind::Flatten) + .map(|(field, _)| &field.ty) + .collect::>(); let mut params = Vec::new(); for field in &struct_fields { @@ -613,22 +997,412 @@ pub(crate) fn impl_from_args(input: DeriveInput) -> Result { let name = input.ident; let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); - let output = quote! { + let binding_params = if legacy.is_some() { + quote! { + const BINDING_PARAMS: Option<&'static [::rustpython_vm::function::Param]> = None; + } + } else if flattened.is_empty() { + quote! {} + } else { + let params = struct_fields + .iter() + .filter(|field| !is_phantom(field)) + .map(|field| { + param_token_with( + field, + &ArgAttribute::try_from(field)?, + &format_ident!("BINDING_PARAMS"), + ) + }) + .collect::>>()?; + quote! { + const BINDING_PARAMS: Option<&'static [::rustpython_vm::function::Param]> = + Some(&[#(#params),*]); + } + }; + let check_before_convert = if legacy.is_some() { + quote! { + fn check_before_convert( + _: &::rustpython_vm::function::FuncArgs, + _: &::std::ops::RangeInclusive, + _: usize, + _: ::rustpython_vm::function::Callee, + _: &::rustpython_vm::VirtualMachine, + ) -> ::core::option::Option<::rustpython_vm::builtins::PyBaseExceptionRef> { + None + } + } + } else { + quote! {} + }; + let from_args_body = if let Some(LegacyFromArgs { fname }) = legacy { + let (keywords, required, max_positional) = legacy_spec_parts(&struct_fields)?; + quote! { + const SPEC: ::rustpython_vm::function::ArgSpec<'static> = + ::rustpython_vm::function::ArgSpec { + fname: #fname, + keywords: &[#(#keywords),*], + required: #required, + max_positional: #max_positional, + }; + let bound = SPEC.bind(args, vm, |slots| -> ::core::result::Result< + Self, + ::rustpython_vm::function::ArgumentError, + > { Ok(Self { #fields }) })?; + *args = ::core::default::Default::default(); + Ok(bound) + } + } else { + quote! { + Ok(Self { #fields }) + } + }; + Ok(quote! { impl #impl_generics ::rustpython_vm::function::FromArgs for #name #ty_generics #where_clause { + #text_signature const PARAMS: Option<&'static [::rustpython_vm::function::Param]> = Some(&[#(#params),*]); + #binding_params + + const FORCE_UNPACK_KEYWORDS: bool = false #( + || <#flattened as ::rustpython_vm::function::FromArgs>::FORCE_UNPACK_KEYWORDS + )*; + fn arity() -> ::std::ops::RangeInclusive { - #min_arity..=#max_arity + let min = #min_arity; + let max = #max_arity; + #( + let (start, end) = <#flattened as ::rustpython_vm::function::FromArgs>::arity().into_inner(); + let min = min.saturating_add(start); + let max = max.saturating_add(end); + )* + min..=max } + #check_before_convert + fn from_args( vm: &::rustpython_vm::VirtualMachine, args: &mut ::rustpython_vm::function::FuncArgs ) -> ::core::result::Result { - Ok(Self { #fields }) + #from_args_body } } - }; - Ok(output) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn shared_text_signature_is_checked_on_the_argument_spec() { + let input = parse_quote! { + #[from_args(text_signature = "(value[, end], /)")] + struct Args { + #[pyarg(positional)] value: u32, + #[pyarg(positional, default)] end: Option, + } + }; + let tokens = impl_from_args(input).unwrap().to_string(); + assert!(tokens.contains("const TEXT_SIGNATURE")); + assert!(tokens.contains("validate_text_signature")); + assert!(tokens.contains("SigArg :: from_arg :: < Self >")); + assert!(tokens.contains("(value[, end], /)")); + for input in [ + parse_quote! { #[from_args(text_signature = "($self, value, /)")] struct Args { value: u32 } }, + parse_quote! { #[from_args(text_signature = "(value, /)", text_signature = "(value, /)")] struct Args { value: u32 } }, + ] { + assert!(impl_from_args(input).is_err()); + } + } + + #[test] + fn unspecified_rust_default_is_not_a_declared_omission() { + let default = impl_from_args(parse_quote! { + struct Args { #[pyarg(any, default)] value: CustomDefault } + }) + .unwrap() + .to_string(); + assert!(default.contains("DefaultRepr :: Unknown")); + let optional = impl_from_args(parse_quote! { + struct Args { #[pyarg(any, optional)] value: OptionalArg } + }) + .unwrap() + .to_string(); + assert!(optional.contains("OptionalArgDefault")); + assert!(!optional.contains("DefaultRepr :: Unknown")); + } + + #[test] + fn borrowed_codegen_uses_one_binding_and_no_owners() { + let input = parse_quote! { + #[from_args(borrowed)] + struct Args<'a> { + #[pyarg(any)] + value: &'a PyObject, + #[pyarg(named, optional, py_default = "None")] + optional: OptionalArg<&'a Py>, + } + }; + let tokens = impl_from_args(input).unwrap().to_string(); + assert_eq!(tokens.matches("bind_borrowed").count(), 1); + assert_eq!(tokens.matches("try_from_borrowed_argument").count(), 2); + for forbidden in [ + "clone", + "Vec", + "ArgSpec", + "take_keyword", + "take_positional", + "check_before_convert", + ] { + assert!(!tokens.contains(forbidden), "{forbidden}: {tokens}"); + } + assert!(tokens.contains("BorrowedArgs")); + assert!(tokens.contains("ArgsMetadata")); + } + + #[test] + fn a_lifetime_alone_does_not_change_owned_binding() { + let input = parse_quote! { + struct Args<'a> { + #[pyarg(flatten)] + value: ExistingOwnedArgs<'a>, + } + }; + let tokens = impl_from_args(input).unwrap().to_string(); + assert!(tokens.contains("FromArgs for Args")); + assert!(!tokens.contains("BorrowedArgs")); + } + + #[test] + fn borrowed_binding_rejects_unsupported_layouts_and_defaults() { + for input in [ + parse_quote! { #[from_args(borrowed)] struct Args { value: PyObjectRef } }, + parse_quote! { #[from_args(borrowed)] struct Args<'a> { #[pyarg(any, py_default = "None")] value: &'a PyObject } }, + parse_quote! { #[from_args(borrowed)] struct Args<'a, T> { value: &'a T } }, + parse_quote! { #[from_args(borrowed)] struct Args<'a> { #[pyarg(flatten)] value: &'a PyObject } }, + parse_quote! { #[from_args(borrowed)] struct Args<'a> { #[pyarg(any, default = "x")] value: &'a Py } }, + parse_quote! { #[from_args(borrowed)] #[from_args(legacy, fname = "f")] struct Args<'a> { value: &'a PyObject } }, + parse_quote! { #[from_args(borrowed, legacy)] struct Args<'a> { value: &'a PyObject } }, + ] { + assert!(impl_from_args(input).is_err()); + } + } + + #[test] + fn option_none_default_keeps_rust_value_and_metadata() { + let types: [Type; 2] = [ + parse_quote!(Option), + parse_quote!(Option), + ]; + for ty in types { + let field: Field = parse_quote! { + #[pyarg(any, default = None)] + value: #ty + }; + let tokens = generate_field((0, &field)).unwrap().to_string(); + assert!(tokens.contains("e!(unwrap_or_else(|| None)).to_string())); + assert!(!tokens.contains("vm . ctx . none")); + let attr = ArgAttribute::try_from(&field).unwrap(); + let repr = repr_path(); + assert_eq!( + signature_default(&field, &attr).unwrap().to_string(), + quote!(Some(#repr::None)).to_string() + ); + } + } + + #[test] + fn none_default_keeps_wrapped_argument_paths() { + let types: [Type; 3] = [ + parse_quote!(Option), + parse_quote!(OptionalArg), + parse_quote!(OptionalOption), + ]; + for ty in types { + let field: Field = parse_quote! { + #[pyarg(any, default = None)] + value: #ty + }; + let tokens = generate_field((0, &field)).unwrap().to_string(); + assert!(!tokens.contains("vm . ctx . none")); + assert!(tokens.contains("e!(unwrap_or_else(|| None)).to_string())); + } + } + + #[test] + fn none_is_not_a_python_object_literal() { + for expr in [parse_quote!(None), parse_quote!((None))] { + assert!(literal_object_expr(&expr).is_none()); + } + for expr in [ + parse_quote!("text"), + parse_quote!(b"bytes"), + parse_quote!(true), + ] { + assert_eq!( + literal_object_expr(&expr).unwrap().to_string(), + quote!(#expr).to_string() + ); + } + let field: Field = parse_quote! { + #[pyarg(any, default = "text")] + value: PyStrRef + }; + let tokens = generate_field((0, &field)).unwrap().to_string(); + assert!(tokens.contains("< PyStrRef as :: rustpython_vm :: convert :: TryFromObject >")); + assert!(!tokens.contains("vm . ctx . none")); + } + + fn tokens_of(input: DeriveInput) -> String { + match impl_from_args(input) { + Ok(tokens) => tokens.to_string(), + Err(err) => panic!("{err}"), + } + } + + fn error_of(input: DeriveInput) -> String { + match impl_from_args(input) { + Ok(_) => panic!("expected a compile error"), + Err(err) => err.to_string(), + } + } + + #[test] + fn without_from_args_attribute_does_not_use_arg_spec() { + let input: DeriveInput = parse_quote! { + struct ExampleArgs { + #[pyarg(any)] + first: i32, + } + }; + let tokens = tokens_of(input); + assert!(!tokens.contains("ArgSpec")); + assert!(!tokens.contains("check_before_convert")); + assert!(tokens.contains("take_positional_keyword")); + } + + #[test] + fn legacy_from_args_binds_with_arg_spec() { + let input: DeriveInput = parse_quote! { + #[from_args(legacy, fname = "example")] + struct ExampleArgs { + #[pyarg(any)] + first: i32, + #[pyarg(any, default)] + second: i32, + #[pyarg(named, default)] + third: i32, + } + }; + let tokens = tokens_of(input); + assert!(tokens.contains("ArgSpec")); + assert!(tokens.contains("example")); + assert!(tokens.contains("check_before_convert")); + assert!(tokens.contains("slots . required")); + assert!(tokens.contains("optional")); + assert!(tokens.contains("first")); + assert!(tokens.contains("second")); + assert!(tokens.contains("third")); + } + + #[test] + fn legacy_without_fname_is_an_error() { + let input: DeriveInput = parse_quote! { + #[from_args(legacy)] + struct ExampleArgs { + #[pyarg(any)] + first: i32, + } + }; + let err = error_of(input); + assert!(err.contains("fname"), "{err}"); + } + + #[test] + fn fname_without_legacy_is_an_error() { + let input: DeriveInput = parse_quote! { + #[from_args(fname = "example")] + struct ExampleArgs { + #[pyarg(any)] + first: i32, + } + }; + let err = error_of(input); + assert!(err.contains("legacy"), "{err}"); + } + + #[test] + fn unknown_from_args_key_is_an_error() { + let input: DeriveInput = parse_quote! { + #[from_args(legacy, fname = "example", extra)] + struct ExampleArgs { + #[pyarg(any)] + first: i32, + } + }; + let err = error_of(input); + assert!(err.contains("unknown"), "{err}"); + } + + #[test] + fn legacy_rejects_positional_fields() { + let input: DeriveInput = parse_quote! { + #[from_args(legacy, fname = "example")] + struct ExampleArgs { + #[pyarg(positional)] + first: i32, + } + }; + let err = error_of(input); + assert!(err.contains("positional-only"), "{err}"); + } + + #[test] + fn legacy_rejects_flatten_fields() { + let input: DeriveInput = parse_quote! { + #[from_args(legacy, fname = "example")] + struct ExampleArgs { + #[pyarg(flatten)] + first: i32, + } + }; + let err = error_of(input); + assert!(err.contains("flatten"), "{err}"); + } + + #[test] + fn legacy_rejects_required_after_optional() { + let input: DeriveInput = parse_quote! { + #[from_args(legacy, fname = "example")] + struct ExampleArgs { + #[pyarg(any, default)] + first: i32, + #[pyarg(any)] + second: i32, + } + }; + let err = error_of(input); + assert!(err.contains("required field after an optional"), "{err}"); + } + + #[test] + fn legacy_rejects_non_keyword_only_after_named() { + let input: DeriveInput = parse_quote! { + #[from_args(legacy, fname = "example")] + struct ExampleArgs { + #[pyarg(named, default)] + first: i32, + #[pyarg(any, default)] + second: i32, + } + }; + let err = error_of(input); + assert!( + err.contains("non-keyword-only field after a keyword-only"), + "{err}" + ); + } } diff --git a/crates/derive-impl/src/from_args/integer_alias_tests.rs b/crates/derive-impl/src/from_args/integer_alias_tests.rs new file mode 100644 index 00000000000..a5acfcb6a0e --- /dev/null +++ b/crates/derive-impl/src/from_args/integer_alias_tests.rs @@ -0,0 +1,105 @@ +use super::*; + +#[test] +fn integer_alias_literal_defaults_stay_native() { + let types: [Type; 4] = [ + parse_quote!(PySsize), + parse_quote!(rustpython_vm::function::PySsize), + parse_quote!(::rustpython_vm::function::PySsize), + parse_quote!(crate::vm::function::PySsize), + ]; + let defaults: [(Expr, i128); 3] = [ + (parse_quote!(0), 0), + (parse_quote!(-1), -1), + (parse_quote!((-1)), -1), + ]; + for ty in types { + assert!(is_primitive_int(&ty)); + for (default, value) in &defaults { + let field: Field = parse_quote! { + #[pyarg(any, default = #default)] + max_length: #ty + }; + let tokens = generate_field((0, &field)).unwrap().to_string(); + assert!(tokens.contains("e!(unwrap_or_else(|| #default)).to_string())); + assert!(!tokens.contains("ToPyObject")); + assert!( + tokens.contains( + "e!(::rustpython_vm::convert::TryFromObject::try_from_argument( + vm, x + )) + .to_string() + ) + ); + let attr = ArgAttribute::try_from(&field).unwrap(); + let repr = repr_path(); + assert_eq!( + signature_default(&field, &attr).unwrap().to_string(), + quote!(Some(#repr::Int(#value))).to_string() + ); + } + } +} + +#[test] +fn integer_alias_defaults_have_integer_metadata() { + let repr = repr_path(); + let field: Field = parse_quote! { + #[pyarg(any, default)] + max_length: PySsize + }; + let attr = ArgAttribute::try_from(&field).unwrap(); + assert_eq!( + signature_default(&field, &attr).unwrap().to_string(), + quote!(Some(#repr::Int(0))).to_string() + ); + + let field: Field = parse_quote! { + #[pyarg(any, default = MAX_LENGTH)] + max_length: PySsize + }; + let attr = ArgAttribute::try_from(&field).unwrap(); + assert_eq!( + signature_default(&field, &attr).unwrap().to_string(), + quote!(Some(#repr::Int((MAX_LENGTH) as i128))).to_string() + ); +} + +#[test] +fn integer_alias_recognition_does_not_include_wrappers_or_unknown_aliases() { + let types: [Type; 5] = [ + parse_quote!(OptionalArg), + parse_quote!(Option), + parse_quote!(OtherSize), + parse_quote!(PySsize), + parse_quote!(::PySsize), + ]; + for ty in types { + assert!(!is_primitive_int(&ty)); + } + let field: Field = parse_quote! { + #[pyarg(any, optional)] + max_length: OptionalArg + }; + let tokens = generate_field((0, &field)).unwrap().to_string(); + assert!( + tokens.contains("e!(unwrap_or_else(|| ::std::default::Default::default())).to_string()) + ); + assert!(!tokens.contains("ToPyObject")); + let attr = ArgAttribute::try_from(&field).unwrap(); + assert_eq!( + signature_default(&field, &attr).unwrap().to_string(), + quote!(Some( + as ::rustpython_vm::function::OptionalArgDefault>::PY_DEFAULT + )) + .to_string() + ); + + let field: Field = parse_quote! { + #[pyarg(any, default = -1)] + max_length: OtherSize + }; + let tokens = generate_field((0, &field)).unwrap().to_string(); + assert!(tokens.contains("ToPyObject")); + assert!(tokens.contains("< OtherSize as :: rustpython_vm :: convert :: TryFromObject >")); +} diff --git a/crates/derive-impl/src/item.rs b/crates/derive-impl/src/item.rs new file mode 100644 index 00000000000..5929246ae69 --- /dev/null +++ b/crates/derive-impl/src/item.rs @@ -0,0 +1,141 @@ +//! The item information shared by module, impl, and trait macro expansion. + +use proc_macro2::Span; +use quote::ToTokens; +use syn::{Attribute, Ident, Result, Signature, spanned::Spanned}; + +pub(crate) struct Function<'a> { + signature: &'a Signature, + span: Span, +} + +impl<'a> Function<'a> { + pub(crate) fn sig(&self) -> &'a Signature { + self.signature + } + + pub(crate) fn span(&self) -> Span { + self.span + } +} + +pub(crate) struct Constant<'a> { + ident: &'a Ident, + span: Span, +} + +impl<'a> Constant<'a> { + pub(crate) fn ident(&self) -> &'a Ident { + self.ident + } + + pub(crate) fn span(&self) -> Span { + self.span + } +} + +pub(crate) trait ItemLike: ToTokens { + fn attrs_mut(&mut self) -> Result<&mut Vec>; + fn function_or_method(&self) -> Result>; + fn constant(&self) -> Result>; + + // Only functions and constants can supply values to #[pyattr]. + fn get_ident(&self) -> Option<&Ident> { + if let Ok(function) = self.function_or_method() { + Some(&function.sig().ident) + } else { + self.constant().ok().map(|constant| constant.ident()) + } + } + + fn try_split_attr_mut( + &mut self, + expand: impl FnOnce(&mut Vec, &mut Self) -> Result, + ) -> Result + where + Self: Sized, + { + let mut attrs = core::mem::take(self.attrs_mut()?); + let result = expand(&mut attrs, self); + // Restore attributes even when expansion reports a diagnostic. + let item_attrs = self.attrs_mut()?; + assert!( + item_attrs.is_empty(), + "attrs changed during replacement. this behavior must be a bug." + ); + *item_attrs = attrs; + result + } +} + +macro_rules! impl_item { + ($item:ident, $attrs_error:literal, $($variant:ident),+ $(,)?) => { + impl ItemLike for syn::$item { + fn attrs_mut(&mut self) -> Result<&mut Vec> { + match self { + $(Self::$variant(item) => Ok(&mut item.attrs),)+ + other => Err(syn::Error::new_spanned(other, $attrs_error)), + } + } + + fn function_or_method(&self) -> Result> { + match self { + Self::Fn(item) => Ok(Function { + signature: &item.sig, + span: item.span(), + }), + other => Err(syn::Error::new_spanned( + other, + "this item is not a function or method", + )), + } + } + + fn constant(&self) -> Result> { + match self { + Self::Const(item) => Ok(Constant { + ident: &item.ident, + span: item.span(), + }), + other => Err(syn::Error::new_spanned(other, "this item is not a const")), + } + } + } + }; +} + +impl_item!( + Item, + "this kind of item doesn't have attrs", + Const, + Enum, + ExternCrate, + Fn, + ForeignMod, + Impl, + Macro, + Mod, + Static, + Struct, + Trait, + TraitAlias, + Type, + Union, + Use, +); +impl_item!( + ImplItem, + "this kind of item doesn't have attrs", + Const, + Fn, + Type, + Macro, +); +impl_item!( + TraitItem, + "this kind of impl item doesn't have attrs", + Const, + Fn, + Type, + Macro, +); diff --git a/crates/derive-impl/src/lib.rs b/crates/derive-impl/src/lib.rs index af261517012..0191171bb9d 100644 --- a/crates/derive-impl/src/lib.rs +++ b/crates/derive-impl/src/lib.rs @@ -13,17 +13,20 @@ mod util; mod class_docs; mod compile_bytecode; mod from_args; +mod item; +mod metadata; mod pyclass; mod pymodule; mod pypayload; mod pystructseq; mod pytraverse; +mod text_signature; use error::Diagnostic; +use metadata::PunctuatedNestedMeta; use proc_macro2::TokenStream; use quote::ToTokens; use syn::{DeriveInput, Item}; -use syn_ext::types::PunctuatedNestedMeta; pub use pymodule::PyModuleArgs; diff --git a/crates/derive-impl/src/metadata.rs b/crates/derive-impl/src/metadata.rs new file mode 100644 index 00000000000..c34b92f5b98 --- /dev/null +++ b/crates/derive-impl/src/metadata.rs @@ -0,0 +1,191 @@ +//! Parsing for Python macro arguments. Rust keywords such as `impl` are valid +//! option names, and literal arguments are retained for contextual diagnostics. +use proc_macro2::TokenStream; +use quote::ToTokens; +use syn::{ + Attribute, Expr, Ident, Lit, MacroDelimiter, Meta, Path, Result, Token, + ext::IdentExt, + parse::{Parse, ParseStream}, + punctuated::Punctuated, +}; + +#[derive(Clone)] +pub enum NestedMeta { + Meta(Meta), + Lit(Lit), +} + +pub(crate) type PunctuatedNestedMeta = Punctuated; + +impl Parse for NestedMeta { + fn parse(input: ParseStream<'_>) -> Result { + if input.peek(Lit) && !(input.peek(syn::LitBool) && input.peek2(Token![=])) { + return input.parse().map(Self::Lit); + } + if !input.peek(Ident::peek_any) && !input.peek(Token![::]) { + return Err(input.error("expected identifier or literal")); + } + let leading_colon = input.parse()?; + let segments = Punctuated::parse_separated_nonempty_with(input, |input| { + Ident::parse_any(input).map(syn::PathSegment::from) + })?; + let path = Path { + leading_colon, + segments, + }; + let meta = if input.peek(syn::token::Paren) { + let content; + let paren = syn::parenthesized!(content in input); + let nested = content.parse_terminated(Self::parse, Token![,])?; + Meta::List(syn::MetaList { + path, + delimiter: MacroDelimiter::Paren(paren), + tokens: nested.into_token_stream(), + }) + } else if input.peek(Token![=]) { + let eq_token = input.parse()?; + let mut value = input.parse()?; + while let Expr::Group(group) = value { + value = *group.expr; + } + Meta::NameValue(syn::MetaNameValue { + path, + eq_token, + value, + }) + } else { + Meta::Path(path) + }; + Ok(Self::Meta(meta)) + } +} + +impl ToTokens for NestedMeta { + fn to_tokens(&self, tokens: &mut TokenStream) { + match self { + Self::Meta(meta) => meta.to_tokens(tokens), + Self::Lit(lit) => lit.to_tokens(tokens), + } + } +} + +impl NestedMeta { + pub(crate) fn get_ident(&self) -> Option<&Ident> { + match self { + Self::Meta(meta) => meta.path().get_ident(), + Self::Lit(_) => None, + } + } +} + +pub(crate) fn nested_meta(list: &syn::MetaList) -> Result { + if !matches!(list.delimiter, MacroDelimiter::Paren(_)) { + return Err(syn::Error::new( + list.delimiter.span().open(), + "expected paren", + )); + } + list.parse_args_with(PunctuatedNestedMeta::parse_terminated) +} + +pub(crate) trait AttributeDoc { + fn doc(self) -> Option; +} + +impl<'a, I: IntoIterator> AttributeDoc for I { + fn doc(self) -> Option { + let docs: Vec<_> = self + .into_iter() + .filter_map(|attr| { + let Meta::NameValue(meta) = &attr.meta else { + return None; + }; + if !meta.path.is_ident("doc") { + return None; + } + let Expr::Lit(expr) = &meta.value else { + return None; + }; + let Lit::Str(lit) = &expr.lit else { + return None; + }; + Some(lit.value().trim().to_owned()) + }) + .collect(); + (!docs.is_empty()).then(|| docs.join("\n")) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use quote::quote; + use syn::{parse::Parser, parse_quote}; + + #[test] + fn keyword_keys_and_nested_literals_round_trip() { + let tokens = quote!( + impl, + module = false, + with(::some::Trait), + options("value", 7, true), + ); + let args = PunctuatedNestedMeta::parse_terminated + .parse2(tokens.clone()) + .unwrap(); + assert_eq!(args.to_token_stream().to_string(), tokens.to_string()); + assert_eq!(args.first().unwrap().get_ident().unwrap(), "impl"); + let NestedMeta::Meta(Meta::List(list)) = &args[3] else { + panic!("expected list") + }; + let nested = nested_meta(list).unwrap(); + assert_eq!(nested.len(), 3); + assert!(nested.iter().all(|arg| matches!(arg, NestedMeta::Lit(_)))); + } + + #[test] + fn boolean_name_value_is_not_a_literal() { + let arg: NestedMeta = syn::parse_str("true = false").unwrap(); + assert!(matches!(arg, NestedMeta::Meta(Meta::NameValue(_)))); + } + + #[test] + fn malformed_nested_arguments_are_rejected() { + for source in ["with(a b)", "with(a,,)", "with(a::)", "name =", "with[a]"] { + assert!(syn::parse_str::(source).is_err(), "{source}"); + } + let list: syn::MetaList = parse_quote!(with[a]); + assert_eq!( + nested_meta(&list).err().unwrap().to_string(), + "expected paren" + ); + } + + #[test] + fn docs_trim_each_line_and_ignore_non_strings() { + let attrs: Vec = vec![ + parse_quote!(#[doc = " first "]), + parse_quote!(#[cfg(test)]), + parse_quote!(#[doc = 7]), + parse_quote!(#[doc = " second "]), + ]; + assert_eq!(attrs.doc().as_deref(), Some("first\nsecond")); + let blank: Vec = vec![parse_quote!(#[doc = " "])]; + assert_eq!(blank.doc().as_deref(), Some("")); + assert_eq!(Vec::::new().doc(), None); + } + + #[test] + fn name_value_ungroups_macro_substitutions() { + let mut tokens = quote!(name =); + tokens.extend([proc_macro2::TokenTree::Group(proc_macro2::Group::new( + proc_macro2::Delimiter::None, + quote!("value"), + ))]); + let arg: NestedMeta = syn::parse2(tokens).unwrap(); + let NestedMeta::Meta(Meta::NameValue(value)) = arg else { + panic!("expected name-value") + }; + assert!(matches!(value.value, Expr::Lit(_))); + } +} diff --git a/crates/derive-impl/src/pyclass.rs b/crates/derive-impl/src/pyclass.rs index be59d7a339d..be643ad2498 100644 --- a/crates/derive-impl/src/pyclass.rs +++ b/crates/derive-impl/src/pyclass.rs @@ -1,16 +1,17 @@ use super::Diagnostic; +use crate::item::ItemLike; +use crate::metadata::{AttributeDoc, NestedMeta, PunctuatedNestedMeta, nested_meta}; use crate::util::{ ALL_ALLOWED_NAMES, ClassItemMeta, ContentItem, ContentItemInner, ErrorVec, ExceptionItemMeta, - ItemMeta, ItemMetaInner, ItemNursery, SimpleItemMeta, infer_native_call_flags, - internal_doc_tokens, pyclass_ident_and_attrs, pyexception_ident_and_attrs, + ItemMeta, ItemMetaInner, ItemNursery, SimpleItemMeta, internal_doc_tokens, + pyclass_ident_and_attrs, pyexception_ident_and_attrs, }; use core::str::FromStr; use proc_macro2::{Delimiter, Group, Span, TokenStream, TokenTree}; use quote::{ToTokens, quote, quote_spanned}; use std::collections::{HashMap, HashSet}; +use syn::Meta; use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned}; -use syn_ext::ext::*; -use syn_ext::types::*; #[derive(Copy, Clone, Debug, Eq, PartialEq)] enum AttrName { @@ -81,7 +82,7 @@ fn extract_items_into_context<'a, Item>( context: &mut ImplContext, items: impl Iterator, ) where - Item: ItemLike + ToTokens + GetIdent + syn_ext::ext::ItemAttrExt + 'a, + Item: ItemLike + ToTokens + 'a, { for item in items { let r = item.try_split_attr_mut(|attrs, item| { @@ -254,8 +255,28 @@ pub(crate) fn impl_pyclass_impl(attr: PunctuatedNestedMeta, item: Item) -> Resul sig_constructor, sig_structseq, ); + // The table names `Self`, so it has to be an associated const on the + // payload, not a `static` item inside `extend_slots`. + let static_c_slots_impl = if sig_constructor { + quote! { + impl ::rustpython_vm::types::HasStaticCSlots for #payload_ty { + const TABLE: ::rustpython_vm::types::StaticCSlots = + ::rustpython_vm::types::StaticCSlots { + new: Some(::rustpython_vm::types::CSlotPair { + rust: <#payload_ty as ::rustpython_vm::types::Constructor>::slot_new as _, + c: ::rustpython_vm::types::c_new_for::< + ::rustpython_vm::types::ViaConstructor<#payload_ty>, + > as _, + }), + }; + } + } + } else { + quote! {} + }; quote! { #imp + #static_c_slots_impl impl ::rustpython_vm::class::PyClassImpl for #payload_ty { const TP_FLAGS: ::rustpython_vm::types::PyTypeFlags = #flags; @@ -579,8 +600,10 @@ fn generate_class_def( }; let is_pystruct = attrs.iter().any(|attr| { attr.path().is_ident("derive") - && if let Ok(Meta::List(l)) = attr.parse_meta() { - l.nested + && if let Meta::List(l) = &attr.meta + && let Ok(nested) = nested_meta(l) + { + nested .into_iter() .any(|n| n.get_ident().is_some_and(|p| p == "PyStructSequence")) } else { @@ -591,8 +614,10 @@ fn generate_class_def( // generate PySubclass impl (requires same memory layout as base type) let is_repr_transparent = attrs.iter().any(|attr| { attr.path().is_ident("repr") - && if let Ok(Meta::List(l)) = attr.parse_meta() { - l.nested + && if let Meta::List(l) = &attr.meta + && let Ok(nested) = nested_meta(l) + { + nested .into_iter() .any(|n| n.get_ident().is_some_and(|p| p == "transparent")) } else { @@ -649,7 +674,9 @@ fn generate_class_def( let subclass_impl = if !is_pystruct && is_repr_transparent { base.as_ref().map(|typ| { quote! { - impl ::rustpython_vm::class::PySubclass for #ident { + // SAFETY: the transparent base field has the same layout as Self; + // pyclass also checks the object payload offsets and alignment. + unsafe impl ::rustpython_vm::class::PySubclass for #ident { type Base = #typ; #[inline] @@ -976,9 +1003,59 @@ pub(crate) fn impl_pyexception(attr: PunctuatedNestedMeta, item: &Item) -> Resul // Forward a `traverse` option to the generated `#[pyclass]` so exception // payloads with a manual `Traverse` impl are GC-tracked and traversed. - let traverse_attr = match class_meta.inner()._optional_str("traverse").ok().flatten() { - Some(value) => quote! { , traverse = #value }, - None => quote! {}, + // Owned one-field wrappers must expose the base's references when allocated + // with their own vtable, rather than through the base's allocation slot. + let is_wrapper = matches!(item, Item::Struct(item) if matches!(&item.fields, + syn::Fields::Unnamed(fields) if fields.unnamed.len() == 1)); + // One-field wrappers implement owned construction. Other shapes keep the + // trait default, which leaves allocation on slot_new. + let owned_constructor_impl = if is_wrapper { + quote! { + impl ::rustpython_vm::exceptions::PyExceptionOwnedConstructor for #ident { + /// Wraps the owned payload returned by the base constructor. + fn __pyexception_new( + new_base: F, + ) -> ::rustpython_vm::PyResult + where + F: ::core::ops::FnOnce() -> ::rustpython_vm::PyResult< + ::Base, + >, + { + Ok(Self(new_base()?)) + } + } + } + } else { + quote! { + impl ::rustpython_vm::exceptions::PyExceptionOwnedConstructor for #ident {} + } + }; + let (traverse_attr, traverse_impl) = match class_meta + .inner() + ._optional_str("traverse") + .ok() + .flatten() + { + Some(value) => (quote! { , traverse = #value }, quote! {}), + None if is_wrapper => ( + quote! { , traverse = "manual" }, + quote! { + // SAFETY: The sole field owns all payload references. Forward + // to its traversal once without cloning any references. + unsafe impl ::rustpython_vm::object::Traverse for #ident { + /// Visits the sole field's Python references without cloning them. + fn traverse(&self, tracer_fn: &mut ::rustpython_vm::object::TraverseFn<'_>) { + ::rustpython_vm::object::MaybeTraverse::try_traverse(&self.0, tracer_fn); + } + + /// Forwards cycle breaking to the sole field's clear implementation. + fn clear(&mut self, out: &mut ::std::vec::Vec<::rustpython_vm::PyObjectRef>) { + ::rustpython_vm::object::MaybeTraverse::try_clear(&mut self.0, out); + } + } + }, + ), + None => (quote! {}, quote! {}), }; let payload_attr = match class_meta.inner()._optional_str("payload")? { @@ -994,11 +1071,17 @@ pub(crate) fn impl_pyexception(attr: PunctuatedNestedMeta, item: &Item) -> Resul let ret = quote! { #[pyclass(#module_attr name = #class_name, base = #base_class_name #traverse_attr #payload_attr)] #item + #owned_constructor_impl + #traverse_impl #impl_pyclass }; Ok(ret) } +/// Expands exception methods while preserving custom constructors and base allocation slots. +/// +/// Unless `with(Constructor)` supplies a custom implementation, owned construction +/// uses the struct-generated helper and Python allocation delegates to the base. pub(crate) fn impl_pyexception_impl(attr: PunctuatedNestedMeta, item: Item) -> TokenStream { let Item::Impl(imp) = item else { return item.into_token_stream(); @@ -1008,7 +1091,12 @@ pub(crate) fn impl_pyexception_impl(attr: PunctuatedNestedMeta, item: Item) -> T let mut extra_attrs = Vec::new(); let mut with_items = vec![]; for nested in &attr { - if let NestedMeta::Meta(Meta::List(MetaList { path, nested, .. })) = nested { + if let NestedMeta::Meta(Meta::List(list)) = nested { + let path = &list.path; + let nested = match nested_meta(list) { + Ok(nested) => nested, + Err(error) => return error.into_compile_error(), + }; // If we already found the constructor trait, no need to keep looking for it if path.is_ident("with") { for meta in nested { @@ -1016,11 +1104,7 @@ pub(crate) fn impl_pyexception_impl(attr: PunctuatedNestedMeta, item: Item) -> T } continue; } - extra_attrs.push(NestedMeta::Meta(Meta::List(MetaList { - path: path.clone(), - paren_token: Default::default(), - nested: nested.clone(), - }))); + extra_attrs.push(NestedMeta::Meta(Meta::List(list.clone()))); } } @@ -1051,12 +1135,15 @@ pub(crate) fn impl_pyexception_impl(attr: PunctuatedNestedMeta, item: Item) -> T ) -> ::rustpython_vm::PyResult { ::Base::slot_new(cls, args, vm) } + /// Constructs an owned wrapper through its base payload constructor. fn py_new( - _cls: &::rustpython_vm::Py<::rustpython_vm::builtins::PyType>, - _args: Self::Args, - _vm: &::rustpython_vm::VirtualMachine + cls: &::rustpython_vm::Py<::rustpython_vm::builtins::PyType>, + args: Self::Args, + vm: &::rustpython_vm::VirtualMachine ) -> ::rustpython_vm::PyResult { - unreachable!("slot_new is defined") + ::__pyexception_new(|| { + <::Base as ::rustpython_vm::types::Constructor>::py_new(cls, args, vm) + }) } } } @@ -1158,14 +1245,14 @@ struct ImplItemArgs<'a, Item: ItemLike> { trait ImplItem: ContentItem where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()>; } impl ImplItem for MethodItem where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> { let func = args @@ -1307,9 +1394,6 @@ where _ => None, } }; - let drop_first_typed = usize::from(implicit_self.is_some()); - let call_flags = infer_native_call_flags(func.sig(), drop_first_typed); - // Add #[allow(non_snake_case)] for setter methods like set___name__ let method_name = ident.to_string(); if method_name.starts_with("set_") && method_name.contains("__") { @@ -1329,6 +1413,13 @@ where ), args.context.self_ty_subst.as_ref(), None, + item_meta + .text_signature(match self.inner.attr_name { + AttrName::Method => Some("$self"), + AttrName::ClassMethod => Some("$type"), + _ => None, + })? + .as_ref(), ); let doc_body_pending = doc_body_pending_expr(args.context.self_ty_subst.as_ref(), &py_name, rust_doc); @@ -1341,7 +1432,6 @@ where raw, coexist, attr_name: self.inner.attr_name, - call_flags, }); Ok(()) } @@ -1349,7 +1439,7 @@ where impl ImplItem for GetSetItem where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> { let func = args @@ -1384,7 +1474,7 @@ where impl ImplItem for SlotItem where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> { let (ident, span) = if let Ok(c) = args.item.constant() { @@ -1416,6 +1506,11 @@ where slots.#slot_ident.store(Some(Self::#ident as _)); slots.has_release_buffer.store(Self::RELEASE_BUFFER); } + } else if slot_name == "vectorcall" { + quote_spanned! { span => + slots.#slot_ident.store(Some(Self::#ident as _)); + slots.flags.insert(::rustpython_vm::types::PyTypeFlags::HAVE_VECTORCALL); + } } else if POINTER_SLOTS.contains(&slot_name.as_str()) { quote_spanned! { span => slots.#slot_ident.store(Some(PointerSlot::from(Self::#ident()))); @@ -1446,7 +1541,7 @@ where impl ImplItem for AttributeItem where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> { let cfgs = args.cfgs.to_vec(); @@ -1492,7 +1587,7 @@ where impl ImplItem for ExtendClassItem where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> { args.attrs.remove(self.index()); @@ -1514,7 +1609,7 @@ where impl ImplItem for MemberItem where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { fn gen_impl_item(&self, args: ImplItemArgs<'_, Item>) -> Result<()> { Err(self.new_syn_error( @@ -1538,7 +1633,6 @@ struct MethodNurseryItem { doc: TokenStream, doc_body_pending: TokenStream, attr_name: AttrName, - call_flags: TokenStream, } impl MethodNursery { @@ -1578,7 +1672,6 @@ impl ToTokens for MethodNursery { } _ => unreachable!(), }; - let call_flags = &item.call_flags; let coexist_flags = if item.coexist { quote! { | rustpython_vm::function::PyMethodFlags::COEXIST.bits() } } else { @@ -1586,7 +1679,7 @@ impl ToTokens for MethodNursery { }; let flags = quote! { rustpython_vm::function::PyMethodFlags::from_bits_retain( - (#binding_flags).bits() | (#call_flags).bits() #coexist_flags + (#binding_flags).bits() #coexist_flags ) }; // TODO: intern @@ -1601,12 +1694,17 @@ impl ToTokens for MethodNursery { } else { quote!(new_const) }; + let function = if !item.raw && !matches!(item.attr_name, AttrName::StaticMethod) { + quote!(rustpython_vm::function::ReceiverFunction(Self::#ident)) + } else { + quote!(Self::#ident) + }; inner_tokens.extend(quote! [ #(#cfgs)* { let mut def = rustpython_vm::function::PyMethodDef::#method_new( #py_name, - Self::#ident, + #function, #flags, #doc, ); @@ -1737,7 +1835,7 @@ impl ToTokens for GetSetNursery { struct MethodItemMeta(ItemMetaInner); impl ItemMeta for MethodItemMeta { - const ALLOWED_NAMES: &'static [&'static str] = &["name", "raw", "coexist"]; + const ALLOWED_NAMES: &'static [&'static str] = &["name", "raw", "coexist", "text_signature"]; fn from_inner(inner: ItemMetaInner) -> Self { Self(inner) @@ -2507,7 +2605,9 @@ fn extract_impl_attrs(attr: PunctuatedNestedMeta, item: &Ident) -> Result { + NestedMeta::Meta(Meta::List(list)) => { + let nested = nested_meta(&list)?; + let path = &list.path; if path.is_ident("with") { for meta in nested { let NestedMeta::Meta(Meta::Path(path)) = &meta else { @@ -2558,6 +2658,9 @@ fn extract_impl_attrs(attr: PunctuatedNestedMeta, item: &Ident) -> Result slots.new.store(Some(::slot_new as _)); + slots.static_c_slots.store(Some( + &::TABLE, + )); } } else { quote_spanned! { item_span => @@ -2635,76 +2738,59 @@ fn class_internal_doc( has_constructor: bool, has_structseq: bool, ) -> TokenStream { - let init_params = quote!(<<#payload as ::rustpython_vm::types::Initializer>::Args as ::rustpython_vm::function::FromArgs>::PARAMS); - let ctor_params = quote!(<<#payload as ::rustpython_vm::types::Constructor>::Args as ::rustpython_vm::function::FromArgs>::PARAMS); - let chosen = match (has_initializer, has_constructor) { - (true, true) => quote! { - ::rustpython_vm::function::choose_class_params(#init_params, #ctor_params) - }, - (true, false) => quote! { - ::rustpython_vm::function::real_signature(#init_params) - }, - (false, true) => quote! { - ::rustpython_vm::function::real_signature(#ctor_params) - }, - (false, false) => quote!(None), - }; - let chosen = if has_structseq { + let metadata = |trait_name: TokenStream| { quote! { - match #chosen { - Some(params) => Some(params), - None => ::rustpython_vm::types::STRUCT_SEQUENCE_PARAMS, - } + ( + ::rustpython_vm::function::real_signature( + <<#payload as ::rustpython_vm::types::#trait_name>::Args as ::rustpython_vm::function::FromArgs>::PARAMS, + ), + <<#payload as ::rustpython_vm::types::#trait_name>::Args as ::rustpython_vm::function::FromArgs>::TEXT_SIGNATURE, + ) } + }; + let init = if has_initializer { + metadata(quote!(Initializer)) } else { - chosen + quote!((None, None)) }; - quote! { - { - const CHOSEN: Option<&'static [::rustpython_vm::function::Param]> = #chosen; - if CHOSEN.is_none() { + let ctor = if has_constructor { + metadata(quote!(Constructor)) + } else { + quote!((None, None)) + }; + let fallback = if has_structseq { + quote!(::rustpython_vm::types::STRUCT_SEQUENCE_PARAMS) + } else { + quote!(None) + }; + crate::util::doc_from_signature_args( + "e!(NAME), + quote! { + if CHOSEN.is_none() && OVERRIDE.is_none() { ::rustpython_vm::function::ItemDoc::NONE } else { - const ARGS: &[::rustpython_vm::function::SigArg] = &[ - ::rustpython_vm::function::SigArg { - name: "", - params: CHOSEN, - }, - ]; - const BASE: ::rustpython_vm::function::ItemDoc = - <#payload as ::rustpython_vm::class::PyClassDef>::DOC; - const NAME: &str = <#payload as ::rustpython_vm::class::PyClassDef>::NAME; - if BASE.len != 0 { - const N: usize = ::rustpython_vm::function::signature_prefix_len(NAME, ARGS); - const B: [u8; N] = - ::rustpython_vm::function::signature_prefix_bytes::(NAME, ARGS); - const PREFIX: &str = match ::core::str::from_utf8(&B) { - Ok(s) => s, - Err(_) => panic!(), - }; - ::rustpython_vm::function::ItemDoc { - text: Some(PREFIX), - offset: BASE.offset, - len: BASE.len, - } - } else { - const BODY: &str = match BASE.text { - Some(text) => text, - None => "", - }; - const N: usize = - ::rustpython_vm::function::internal_doc_len(NAME, ARGS, BODY); - const B: [u8; N] = - ::rustpython_vm::function::internal_doc_bytes::(NAME, ARGS, BODY); - const FULL: &str = match ::core::str::from_utf8(&B) { - Ok(s) => s, - Err(_) => panic!(), - }; - ::rustpython_vm::function::ItemDoc::static_text(FULL) - } + <#payload as ::rustpython_vm::class::PyClassDef>::DOC } - } - } + }, + quote! { + const NAME: &str = <#payload as ::rustpython_vm::class::PyClassDef>::NAME; + const INIT: (Option<&[::rustpython_vm::function::Param]>, Option<&str>) = #init; + const CTOR: (Option<&[::rustpython_vm::function::Param]>, Option<&str>) = #ctor; + const SELECTED: (Option<&[::rustpython_vm::function::Param]>, Option<&str>) = + if INIT.0.is_some() || INIT.1.is_some() { INIT } else { CTOR }; + const CHOSEN: Option<&[::rustpython_vm::function::Param]> = match SELECTED.0 { + Some(params) => Some(params), None => #fallback, + }; + const ARGS: &[::rustpython_vm::function::SigArg] = &[ + ::rustpython_vm::function::SigArg { + name: "", params: CHOSEN, binding_params: CHOSEN, force_unpack_keywords: false, + }, + ]; + const OVERRIDE: Option<(&str, Option<&str>)> = match SELECTED.1 { + Some(text) => Some((text, None)), None => None, + }; + }, + ) } fn impl_item_new( @@ -2712,7 +2798,7 @@ fn impl_item_new( attr_name: AttrName, ) -> Box> where - Item: ItemLike + ToTokens + GetIdent, + Item: ItemLike + ToTokens, { match attr_name { attr_name @ (AttrName::Method | AttrName::ClassMethod | AttrName::StaticMethod) => { @@ -2752,7 +2838,7 @@ where while let Some((_, attr)) = iter.peek() { // take all cfgs but no py items let attr = *attr; - let attr_name = if let Some(ident) = attr.get_ident() { + let attr_name = if let Some(ident) = attr.path().get_ident() { ident.to_string() } else { continue; @@ -2767,7 +2853,7 @@ where for (i, attr) in iter { // take py items but no cfgs - let attr_name = if let Some(ident) = attr.get_ident() { + let attr_name = if let Some(ident) = attr.path().get_ident() { ident.to_string() } else { continue; @@ -2810,3 +2896,20 @@ fn parse_vec_ident( })? .to_string()) } + +#[cfg(test)] +mod text_signature_tests { + use super::*; + + #[test] + fn class_doc_reuses_argument_overrides_and_central_docs() { + for (init, ctor) in [(true, false), (false, true), (true, true)] { + let tokens = class_internal_doc(&parse_quote!(Example), init, ctor, false).to_string(); + assert!(tokens.contains("FromArgs > :: TEXT_SIGNATURE")); + assert!(tokens.contains("PyClassDef > :: DOC")); + assert!(tokens.contains("offset : BASE . offset")); + assert!(tokens.contains("text_signature_doc_bytes")); + assert!(!tokens.contains("SigArg :: implicit")); + } + } +} diff --git a/crates/derive-impl/src/pymodule.rs b/crates/derive-impl/src/pymodule.rs index 14ad5ea3cfb..a239361baa0 100644 --- a/crates/derive-impl/src/pymodule.rs +++ b/crates/derive-impl/src/pymodule.rs @@ -1,9 +1,11 @@ use crate::error::Diagnostic; +use crate::item::ItemLike; +use crate::metadata::{AttributeDoc, NestedMeta}; use crate::pystructseq::PyStructSequenceMeta; use crate::util::{ ALL_ALLOWED_NAMES, AttrItemMeta, AttributeExt, ClassItemMeta, ContentItem, ContentItemInner, - ErrorVec, ItemMeta, ItemNursery, ModuleItemMeta, SimpleItemMeta, infer_native_call_flags, - internal_doc_tokens, iter_use_idents, pyclass_ident_and_attrs, + ErrorVec, FunctionItemMeta, ItemMeta, ItemNursery, ModuleItemMeta, SimpleItemMeta, + flags_signature_doc_tokens, internal_doc_tokens, iter_use_idents, pyclass_ident_and_attrs, }; use core::str::FromStr; use proc_macro2::{Delimiter, Group, TokenStream, TokenTree}; @@ -11,8 +13,6 @@ use quote::{ToTokens, format_ident, quote, quote_spanned}; use std::collections::HashSet; use syn::{Attribute, Ident, Item, Result, parse_quote, spanned::Spanned}; -use syn_ext::ext::*; -use syn_ext::types::NestedMeta; /// A `with(...)` item that may be gated by `#[cfg(...)]` attributes. pub struct WithItem { @@ -171,9 +171,13 @@ pub(crate) fn impl_pymodule(args: PyModuleArgs, module_item: Item) -> Result Result, - ) { - ::rustpython_vm::builtins::PyModule::__init_dict_from_def(vm, module); + ) -> ::rustpython_vm::PyResult<()> { + ::rustpython_vm::builtins::PyModule::__init_dict_from_def(vm, module) } }, ]); @@ -449,7 +453,7 @@ where while let Some((_, attr)) = iter.peek() { // take all cfgs but no py items let attr = *attr; - if let Some(ident) = attr.get_ident() { + if let Some(ident) = attr.path().get_ident() { let attr_name = ident.to_string(); if attr_name == "cfg" { cfgs.push(attr.clone()); @@ -464,7 +468,7 @@ where let mut py_attrs = Vec::new(); for (i, attr) in iter { // take py items but no cfgs - let attr_name = if let Some(ident) = attr.get_ident() { + let attr_name = if let Some(ident) = attr.path().get_ident() { ident.to_string() } else { continue; @@ -536,7 +540,7 @@ struct FunctionNurseryItem { ident: Ident, /// One internal doc per [`py_names`](Self::py_names) entry. docs: Vec, - call_flags: TokenStream, + binds_module: bool, } impl FunctionNursery { @@ -566,14 +570,18 @@ impl ToTokens for ValidatedFunctionNursery { let ident = &item.ident; let cfgs = &item.cfgs; let cfgs = quote!(#(#cfgs)*); - let flags = &item.call_flags; + let function = if item.binds_module { + quote!(rustpython_vm::function::ReceiverFunction(#ident)) + } else { + quote!(#ident) + }; for (py_name, doc) in item.py_names.iter().zip(&item.docs) { inner_tokens.extend(quote![ #cfgs rustpython_vm::function::PyMethodDef::new_const( #py_name, - #ident, - #flags, + #function, + rustpython_vm::function::PyMethodFlags::empty(), #doc, ), ]); @@ -672,14 +680,17 @@ impl ModuleItem for FunctionItem { let ident = &func.sig().ident; let item_attr = args.attrs.remove(self.index()); - let item_meta = SimpleItemMeta::from_attr(ident.clone(), &item_attr)?; + let item_meta = FunctionItemMeta::from_attr(ident.clone(), &item_attr)?; let py_name = item_meta.simple_name()?; + let mut flags_signatures = vec![item_meta.signature_from_flags()?]; + let binds_module = crate::util::has_module_receiver(func.sig())?; + let mut text_signatures = vec![item_meta.text_signature(Some("$module"))?]; let mut py_names = vec![py_name]; for attr_index in self.py_attrs.iter().rev() { let mut loop_unit = || { let attr_attr = args.attrs.remove(*attr_index); - let item_meta = SimpleItemMeta::from_attr(ident.clone(), &attr_attr)?; + let item_meta = FunctionItemMeta::from_attr(ident.clone(), &attr_attr)?; let py_name = item_meta.simple_name()?; if py_names.iter().any(|name| name == &py_name) { @@ -688,6 +699,8 @@ impl ModuleItem for FunctionItem { &format!("`{py_name}` is duplicated name for multiple py* attribute"), )); } + flags_signatures.push(item_meta.signature_from_flags()?); + text_signatures.push(item_meta.text_signature(Some("$module"))?); py_names.push(py_name); Ok(()) }; @@ -695,11 +708,27 @@ impl ModuleItem for FunctionItem { args.context.errors.ok_or_push(r); } + let mut doc_signature = func.sig().clone(); + if binds_module { + doc_signature.inputs = doc_signature.inputs.into_iter().skip(1).collect(); + } + if flags_signatures + .iter() + .zip(&text_signatures) + .any(|(flags, text)| *flags && text.is_some()) + { + return Err(self.new_syn_error( + ident.span(), + "text_signature and signature_from_flags are mutually exclusive", + )); + } let module = args.doc_module(); let rust_doc = args.attrs.doc().filter(|doc| !doc.is_empty()); let docs = py_names .iter() - .map(|py_name| { + .zip(flags_signatures) + .zip(text_signatures) + .map(|((py_name, from_flags), text_signature)| { let db_doc = if rust_doc.is_some() { None } else { @@ -708,17 +737,28 @@ impl ModuleItem for FunctionItem { }) }; let doc = crate::class_docs::item_doc_tokens(db_doc, rust_doc.clone()); - internal_doc_tokens(func.sig(), py_name, None, doc, None, Some("$module")) + if from_flags { + flags_signature_doc_tokens(&doc_signature, py_name, doc) + } else { + internal_doc_tokens( + &doc_signature, + py_name, + None, + doc, + None, + Some("$module"), + text_signature.as_ref(), + ) + } }) .collect(); - let call_flags = infer_native_call_flags(func.sig(), 0); args.context.function_items.add_item(FunctionNurseryItem { ident: ident.to_owned(), py_names, cfgs: args.cfgs.to_vec(), docs, - call_flags, + binds_module, }); Ok(()) } diff --git a/crates/derive-impl/src/pystructseq.rs b/crates/derive-impl/src/pystructseq.rs index aa89b3717bb..e2857901cec 100644 --- a/crates/derive-impl/src/pystructseq.rs +++ b/crates/derive-impl/src/pystructseq.rs @@ -1,9 +1,9 @@ +use crate::metadata::{AttributeDoc, PunctuatedNestedMeta, nested_meta}; use crate::util::{ItemMeta, ItemMetaInner}; use proc_macro2::TokenStream; use quote::{format_ident, quote}; +use syn::Meta; use syn::{DeriveInput, Ident, Item, Result}; -use syn_ext::ext::{AttributeExt, AttributeIteratorExt, GetIdent}; -use syn_ext::types::{Meta, PunctuatedNestedMeta}; // #[pystruct_sequence_data] - For Data structs @@ -94,16 +94,12 @@ fn parse_fields(input: &mut DeriveInput) -> Result { continue; } - let Ok(meta) = attr.parse_meta() else { - continue; - }; - - let Meta::List(l) = meta else { + let Meta::List(l) = &attr.meta else { bail_span!(input, "Only #[pystruct_sequence(...)] form is allowed"); }; - let idents = l - .nested + let Ok(nested) = nested_meta(l) else { continue }; + let idents = nested .iter() .filter_map(|n| n.get_ident()) .cloned() @@ -602,7 +598,8 @@ pub(crate) fn impl_pystruct_sequence( } // PySubclass for proper inheritance - impl ::rustpython_vm::class::PySubclass for #pytype_ident { + // SAFETY: the generated payload is a transparent wrapper around PyTuple. + unsafe impl ::rustpython_vm::class::PySubclass for #pytype_ident { type Base = ::rustpython_vm::builtins::PyTuple; #[inline] diff --git a/crates/derive-impl/src/text_signature.rs b/crates/derive-impl/src/text_signature.rs new file mode 100644 index 00000000000..947a61d4893 --- /dev/null +++ b/crates/derive-impl/src/text_signature.rs @@ -0,0 +1,419 @@ +//! Explicit checked text signatures. This deliberately accepts a small grammar: +//! positional parameters, a `/`, literal defaults, `**kwargs`, and trailing +//! nested optional positional groups. It is not a Python expression parser. +use proc_macro2::{Span, TokenStream}; +use quote::quote; +use syn::{Error, Result}; + +pub(crate) struct TextSignature { + pub(crate) text: String, + params: Vec, + pub(crate) omitted_slash: bool, +} + +struct Parameter { + name: String, + positional: bool, + optional: bool, + keywords: bool, +} + +fn identifier(name: &str) -> bool { + let name = name.strip_prefix('$').unwrap_or(name); + if matches!( + name, + "False" + | "None" + | "True" + | "and" + | "as" + | "assert" + | "async" + | "await" + | "break" + | "class" + | "continue" + | "def" + | "del" + | "elif" + | "else" + | "except" + | "finally" + | "for" + | "from" + | "global" + | "if" + | "import" + | "in" + | "is" + | "lambda" + | "nonlocal" + | "not" + | "or" + | "pass" + | "raise" + | "return" + | "try" + | "while" + | "with" + | "yield" + ) { + return false; + } + let mut bytes = name.bytes(); + matches!(bytes.next(), Some(b'a'..=b'z' | b'A'..=b'Z' | b'_')) + && bytes.all(|b| b.is_ascii_alphanumeric() || b == b'_') +} + +impl TextSignature { + pub(crate) fn parse(text: String, span: Span) -> Result { + let invalid = || Error::new(span, "invalid or unsupported text_signature override"); + let body = text + .strip_prefix('(') + .and_then(|s| s.strip_suffix(')')) + .ok_or_else(invalid)?; + if body.contains('\0') { + return Err(invalid()); + } + let mut params = Vec::new(); + let mut quote = None; + let has_group = body.chars().any(|ch| { + if matches!(ch, '\'' | '"') { + quote = if quote == Some(ch) { None } else { Some(ch) }; + } + ch == '[' && quote.is_none() + }); + let omitted_slash = has_group && !body.ends_with(", /"); + if omitted_slash { + // CPython's explicit deque bracket signatures omit '/' notation. + // Brackets describe omission only; parameter kinds come from the binder. + let mut groups = Vec::new(); + let mut token = String::new(); + let mut closed = false; + let mut require_comma = false; + let mut last_comma = false; + for ch in body.chars().chain(['\0']) { + if matches!(ch, '[' | ']' | ',' | '\0') { + let name = token.trim(); + let had_name = !name.is_empty(); + if closed && !matches!(ch, ']' | '\0') { + return Err(invalid()); + } + if ch == ',' && !had_name && !require_comma { + return Err(invalid()); + } + if had_name { + if closed { + return Err(invalid()); + } + params.push(Parameter { + name: name.into(), + positional: false, + optional: !groups.is_empty(), + keywords: false, + }); + token.clear(); + last_comma = false; + } + match ch { + '[' => { + if closed || require_comma { + return Err(invalid()); + } + groups.push(params.len()); + require_comma = had_name; + last_comma = false; + } + ']' => { + if last_comma { + return Err(invalid()); + } + let start = groups.pop().ok_or_else(invalid)?; + if params.len() == start { + return Err(invalid()); + } + closed = true; + } + ',' => { + require_comma = false; + last_comma = true; + } + _ => { + if last_comma || require_comma { + return Err(invalid()); + } + } + } + } else { + if require_comma && !ch.is_whitespace() { + return Err(invalid()); + } + token.push(ch); + } + } + if !groups.is_empty() || params.is_empty() { + return Err(invalid()); + } + } else if body.contains("[,") { + let mut parts = body.split("[,").collect::>(); + let optional_count = parts.len() - 1; + let ending = format!("{}, /", "]".repeat(optional_count)); + let last = parts + .pop() + .unwrap() + .strip_suffix(&ending) + .ok_or_else(invalid)?; + let required = parts.remove(0); + for name in required.split(',').map(str::trim) { + params.push(Parameter { + name: name.into(), + positional: true, + optional: false, + keywords: false, + }); + } + for name in parts.into_iter().chain([last]).map(str::trim) { + params.push(Parameter { + name: name.into(), + positional: true, + optional: true, + keywords: false, + }); + } + } else { + let mut slash = false; + let mut optional = false; + let mut keywords = false; + for part in body.split(',').map(str::trim) { + if keywords { + return Err(invalid()); + } + if part == "/" { + if slash || params.is_empty() { + return Err(invalid()); + } + slash = true; + for param in &mut params { + param.positional = true; + } + continue; + } + let (name, default) = match part.split_once('=') { + Some((name, default)) => { + let default = default.trim(); + let quoted = (default.starts_with('\'') && default.ends_with('\'')) + || (default.starts_with('"') && default.ends_with('"')); + let literal = if quoted && default.len() >= 2 { + !default[1..default.len() - 1].contains(['\'', '"', '\\', '\n', '\r']) + } else { + matches!(default, "None" | "True" | "False") + || default + .parse::() + .is_ok_and(|value| value.to_string() == default) + }; + if !literal { + return Err(invalid()); + } + (name.trim(), true) + } + None => (part, false), + }; + let name = if let Some(name) = name.strip_prefix("**") { + if default { + return Err(invalid()); + } + keywords = true; + name + } else { + name + }; + if optional && !default && !keywords { + return Err(invalid()); + } + optional |= default; + params.push(Parameter { + name: name.into(), + positional: false, + optional: default, + keywords, + }); + } + } + for (index, param) in params.iter().enumerate() { + if !identifier(¶m.name) + || params[..index].iter().any(|other| other.name == param.name) + || (param.name.starts_with('$') + && (index != 0 + || (!param.positional && !omitted_slash) + || param.optional + || !matches!(param.name.as_str(), "$self" | "$type" | "$cls" | "$module"))) + { + return Err(invalid()); + } + } + Ok(Self { + text, + params, + omitted_slash, + }) + } + + pub(crate) fn validate_receiver(&self, expected: Option<&str>, span: Span) -> Result<()> { + let receiver = self + .params + .first() + .map(|p| p.name.as_str()) + .filter(|name| name.starts_with('$')); + if receiver != expected && !matches!((receiver, expected), (Some("$cls"), Some("$type"))) { + return Err(Error::new( + span, + format!("text_signature receiver must match the item kind (expected {expected:?})"), + )); + } + Ok(()) + } + + pub(crate) fn validator(&self) -> TokenStream { + if self.omitted_slash { + quote!(::rustpython_vm::function::validate_text_signature_without_slash) + } else { + quote!(::rustpython_vm::function::validate_text_signature) + } + } + + pub(crate) fn params_tokens(&self) -> Vec { + self.params.iter().filter(|param| !param.name.starts_with('$')).map(|param| { + let name = ¶m.name; + let kind = if param.keywords { quote!(VarKeyword) } else if param.positional { quote!(PositionalOnly) } else { quote!(PositionalOrKeyword) }; + let default = if param.optional { quote!(Some(::rustpython_vm::function::DefaultRepr::Unrepresentable)) } else { quote!(None) }; + quote! { ::rustpython_vm::function::Param { name: #name, kind: ::rustpython_vm::function::ParamKind::#kind, default: #default } } + }).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn explicit_class_and_handwritten_signatures() { + for text in [ + "([iterable[, maxlen]])", + "($self, value, [start, [stop]])", + "(name='[', other=None)", + "($cls, name, bases, /, **kwds)", + ] { + assert!( + TextSignature::parse(text.into(), Span::call_site()).is_ok(), + "{text}" + ); + } + for text in [ + "([a]", + "([])", + "([a], b)", + "(a, [b], c)", + "(a, [b]])", + "(a[b])", + "([, a])", + "([a,,b])", + "([a],,,)", + "([a,])", + ] { + assert!( + TextSignature::parse(text.into(), Span::call_site()).is_err(), + "{text}" + ); + } + } + + #[test] + fn supported_overrides() { + for name in ["sub", "prefix", "suffix"] { + let sig = TextSignature::parse( + format!("($self, {name}[, start[, end]], /)"), + Span::call_site(), + ) + .unwrap(); + assert_eq!(sig.params.len(), 4); + assert!(sig.params[2..].iter().all(|p| p.positional && p.optional)); + assert!(!sig.params[1].optional); + } + for name in ["iterable", "fileobj", "name"] { + let sig = TextSignature::parse( + format!("($module, {name}, /, dialect='excel', **fmtparams)"), + Span::call_site(), + ) + .unwrap(); + assert_eq!(sig.params.len(), 4); + assert!(sig.params[1].positional); + assert!(!sig.params[2].positional); + assert!(sig.params[2].optional); + assert!(sig.params[3].keywords); + } + } + + #[test] + fn receivers_are_checked_against_the_item_kind() { + for (text, expected) in [ + ("($self, value, /)", Some("$self")), + ("($module, value, /)", Some("$module")), + ("($type, value, /)", Some("$type")), + ("($cls, value, /)", Some("$type")), + ("(value, /)", None), + ] { + let signature = TextSignature::parse(text.into(), Span::call_site()).unwrap(); + signature + .validate_receiver(expected, Span::call_site()) + .unwrap(); + assert_eq!(signature.params_tokens().len(), 1); + for wrong in [Some("$self"), Some("$module"), Some("$type"), None] { + if wrong != expected { + assert!( + signature + .validate_receiver(wrong, Span::call_site()) + .is_err(), + "{text} {wrong:?}" + ); + } + } + } + } + + #[test] + fn malformed_overrides() { + for text in [ + "()", + "(a[[b]])", + "(a[ [b]])", + "(class, /)", + "(value=01, /)", + "($self, sub[, ], /)", + "($self, sub[, start[, ]], /)", + "($self, sub[, start[, end], /)", + "($self, $self, /)", + "($module, name, /, **name)", + "($module, name, /, **kwargs, **kwargs)", + "($self, sub[, start[, end]]], /)", + "($self, sub[, start], end, /)", + "($self, sub[, start=0], /)", + "($self, sub[, start], /, **kwargs)", + "($self, sub[, start, end], /)", + "($module, name, /, dialect=call(), **fmtparams)", + "($module, name, /, dialect='excel', **fmtparams, extra)", + "($module, name, /, /)", + "($module, name, /, name=None)", + "($module, name)", + "(name, $self, /)", + "($unknown, name, /)", + "($module, name, /, dialect='excel', required)", + "($module, name, /, **kwargs=None)", + "($module, name, /, dialect='excel'junk')", + ] { + assert!( + TextSignature::parse(text.into(), Span::call_site()).is_err(), + "{text}" + ); + } + } +} diff --git a/crates/derive-impl/src/util.rs b/crates/derive-impl/src/util.rs index 985a8312301..1d43f8d984e 100644 --- a/crates/derive-impl/src/util.rs +++ b/crates/derive-impl/src/util.rs @@ -1,16 +1,14 @@ +use crate::metadata::{NestedMeta, PunctuatedNestedMeta, nested_meta}; use itertools::Itertools; use proc_macro2::{Span, TokenStream}; use quote::{ToTokens, quote}; use std::collections::{HashMap, HashSet}; +use syn::Meta; use syn::visit::Visit; use syn::visit_mut::VisitMut; use syn::{ Attribute, FnArg, Ident, Result, Signature, Type, UseTree, ext::IdentExt, spanned::Spanned, }; -use syn_ext::{ - ext::{AttributeExt as SynAttributeExt, *}, - types::*, -}; pub(crate) const ALL_ALLOWED_NAMES: &[&str] = &[ "pymethod", @@ -133,24 +131,32 @@ impl ItemMetaInner { where I: core::iter::Iterator, { - let (meta_map, lits) = nested.into_unique_map_and_lits(|path| { - if let Some(ident) = path.get_ident() { - let name = ident.to_string(); - if allowed_names.contains(&name.as_str()) { - Ok(Some(name)) - } else { - Err(err_span!( - ident, - "#[{meta_ident}({name})] is not one of allowed attributes [{}]", - allowed_names.iter().format(", ") - )) - } - } else { - Ok(None) + let mut meta_map = HashMap::new(); + let mut has_literal = false; + for (index, nested) in nested.enumerate() { + let NestedMeta::Meta(meta) = nested else { + has_literal = true; + continue; + }; + let Some(ident) = meta.path().get_ident() else { + continue; + }; + let name = ident.to_string(); + if !allowed_names.contains(&name.as_str()) { + bail_span!( + ident, + "#[{meta_ident}({name})] is not one of allowed attributes [{}]", + allowed_names.iter().format(", ") + ); } - })?; - - if !lits.is_empty() { + if let Some((_, previous)) = meta_map.insert(name, (index, meta)) { + return Err(syn::Error::new_spanned( + previous, + "this attribute path must be unique in the attribute", + )); + } + } + if has_literal { bail_span!(meta_ident, "#[{meta_ident}(..)] cannot contain literal") } @@ -247,22 +253,16 @@ impl ItemMetaInner { Ok(value) } - pub(crate) fn _optional_list( - &self, - key: &str, - ) -> Result>> { - let value = if let Some((_, meta)) = self.meta_map.get(key) { - let Meta::List(MetaList { - path: _, nested, .. - }) = meta - else { - bail_span!(meta, "#[{}({}(...))] must be a list", self.meta_name(), key) - }; - Some(nested.into_iter()) - } else { - None - }; - Ok(value) + pub(crate) fn _optional_list(&self, key: &str) -> Result> { + self.meta_map + .get(key) + .map(|(_, meta)| { + let Meta::List(list) = meta else { + bail_span!(meta, "#[{}({}(...))] must be a list", self.meta_name(), key) + }; + nested_meta(list) + }) + .transpose() } } @@ -289,6 +289,21 @@ pub(crate) trait ItemMeta: Sized { fn from_inner(inner: ItemMetaInner) -> Self; fn inner(&self) -> &ItemMetaInner; + fn text_signature( + &self, + receiver: Option<&str>, + ) -> Result> { + self.inner() + ._optional_str("text_signature")? + .map(|text| { + let span = self.inner().item_ident.span(); + let signature = crate::text_signature::TextSignature::parse(text, span)?; + signature.validate_receiver(receiver, span)?; + Ok(signature) + }) + .transpose() + } + fn simple_name(&self) -> Result { let inner = self.inner(); Ok(inner @@ -319,6 +334,27 @@ impl ItemMeta for SimpleItemMeta { } } +/// Module function metadata; flag-derived signatures deliberately opt out of Clinic text. +pub(crate) struct FunctionItemMeta(pub ItemMetaInner); + +impl ItemMeta for FunctionItemMeta { + const ALLOWED_NAMES: &'static [&'static str] = + &["name", "signature_from_flags", "text_signature"]; + + fn from_inner(inner: ItemMetaInner) -> Self { + Self(inner) + } + fn inner(&self) -> &ItemMetaInner { + &self.0 + } +} + +impl FunctionItemMeta { + pub(crate) fn signature_from_flags(&self) -> Result { + self.inner()._bool("signature_from_flags") + } +} + pub(crate) struct ModuleItemMeta(pub ItemMetaInner); impl ItemMeta for ModuleItemMeta { @@ -553,7 +589,7 @@ impl core::ops::Deref for ExceptionItemMeta { } } -pub(crate) trait AttributeExt: SynAttributeExt { +pub(crate) trait AttributeExt { fn promoted_nested(&self) -> Result; fn ident_and_promoted_nested(&self) -> Result<(&Ident, PunctuatedNestedMeta)>; @@ -567,70 +603,85 @@ pub(crate) trait AttributeExt: SynAttributeExt { impl AttributeExt for Attribute { fn promoted_nested(&self) -> Result { - let list = self.promoted_list().map_err(|mut e| { - let name = self.get_ident().unwrap().to_string(); - e.combine(err_span!( - self, - r##"#[{name} = "..."] cannot be a name/value, you probably meant \ - #[{name}(name = "...")]"##, - )); - e - })?; - Ok(list.nested) + match &self.meta { + Meta::Path(_) => Ok(PunctuatedNestedMeta::new()), + Meta::List(list) => nested_meta(list), + meta => { + let mut error = syn::Error::new_spanned( + meta, + "Only Path can be promoted and List is accepted as non-promoted", + ); + let name = self.path().get_ident().unwrap(); + error.combine(err_span!( + self, + r##"#[{name} = "..."] cannot be a name/value, you probably meant \ + #[{name}(name = "...")]"## + )); + Err(error) + } + } } fn ident_and_promoted_nested(&self) -> Result<(&Ident, PunctuatedNestedMeta)> { - Ok((self.get_ident().unwrap(), self.promoted_nested()?)) + Ok((self.path().get_ident().unwrap(), self.promoted_nested()?)) } fn try_remove_name(&mut self, item_name: &str) -> Result> { - self.try_meta_mut(|meta| { - let nested = match meta { - Meta::List(MetaList { nested, .. }) => Ok(nested), - other => Err(syn::Error::new( - other.span(), - format!( - "#[{name}(...)] doesn't contain '{item}' to remove", - name = other.get_ident().unwrap(), - item = item_name - ), - )), - }?; - - let mut found = None; - for (i, item) in nested.iter().enumerate() { - if item.get_ident().is_none_or(|ident| ident != item_name) { - continue; - } - - if found.is_some() { - return Err(syn::Error::new( - item.span(), - format!("#[py..({item_name}...)] must be unique but found multiple times"), - )); + let Meta::List(list) = &mut self.meta else { + bail_span!( + self.meta, + "#[{name}(...)] doesn't contain '{item}' to remove", + name = self.path().get_ident().unwrap(), + item = item_name + ); + }; + let nested = nested_meta(list)?; + let mut retained = PunctuatedNestedMeta::new(); + let mut removed = None; + for pair in nested.into_pairs() { + if pair + .value() + .get_ident() + .is_some_and(|ident| ident == item_name) + { + if removed.is_some() { + bail_span!( + pair.value(), + "#[py..({item_name}...)] must be unique but found multiple times" + ); } - found = Some(i); + removed = Some(pair.into_value()); + } else { + retained.extend([pair]); } - - Ok(found.map(|idx| nested.remove(idx).into_value())) - }) + } + list.tokens = retained.into_token_stream(); + Ok(removed) } fn fill_nested_meta(&mut self, name: &str, new_item: F) -> Result<()> where F: Fn() -> NestedMeta, { - self.try_meta_mut(|meta| { - let list = meta.promote_to_list(Default::default())?; - let has_name = list - .nested - .iter() - .any(|nested_meta| nested_meta.get_path().is_some_and(|p| p.is_ident(name))); - if !has_name { - list.nested.push(new_item()) + let mut nested = self.promoted_nested()?; + if !nested.iter().any(|item| { + matches!(item, + NestedMeta::Meta(meta) if meta.path().is_ident(name)) + }) { + nested.push(new_item()); + } + match &mut self.meta { + Meta::List(list) => list.tokens = nested.into_token_stream(), + Meta::Path(path) => { + self.meta = Meta::List(syn::MetaList { + path: path.clone(), + delimiter: syn::MacroDelimiter::Paren(Default::default()), + tokens: nested.into_token_stream(), + }) } - Ok(()) - }) + Meta::NameValue(_) => unreachable!("promoted_nested rejects name-value attributes"), + } + Ok(()) } } @@ -759,9 +810,60 @@ enum SigPiece { Implicit(Type), } +/// A leading `&Py` is injected by the module function adapter. +/// A leading `PyRef` is rejected; later positions remain ordinary +/// Python arguments. This is syntax-based: Rust aliases cannot be resolved by +/// a procedural macro. +pub(crate) fn has_module_receiver(sig: &Signature) -> Result { + let Some(FnArg::Typed(arg)) = sig.inputs.first() else { + return Ok(false); + }; + let (ty, wrapper, mutable) = match &*arg.ty { + Type::Reference(reference) => (&*reference.elem, "Py", reference.mutability.is_some()), + ty => (ty, "PyRef", false), + }; + let Type::Path(path) = ty else { + return Ok(false); + }; + let Some(segment) = path.path.segments.last() else { + return Ok(false); + }; + if segment.ident != wrapper { + return Ok(false); + } + let syn::PathArguments::AngleBracketed(arguments) = &segment.arguments else { + return Ok(false); + }; + let Some(syn::GenericArgument::Type(Type::Path(payload))) = arguments.args.first() else { + return Ok(false); + }; + let is_module = arguments.args.len() == 1 + && payload + .path + .segments + .last() + .is_some_and(|segment| segment.ident == "PyModule"); + if is_module && (mutable || wrapper == "PyRef") { + return Err(syn::Error::new_spanned( + &arg.ty, + "the module receiver must be &Py", + )); + } + Ok(is_module) +} + fn is_vm_or_callee(ty: &Type) -> bool { + if let Type::Path(path) = ty + && path + .path + .segments + .last() + .is_some_and(|segment| segment.ident == "Callee") + { + return true; + } let ty = quote!(#ty).to_string().replace(' ', ""); - (ty.starts_with('&') && ty.ends_with("VirtualMachine")) || ty.ends_with("Callee") + ty.starts_with('&') && ty.ends_with("VirtualMachine") } fn arg_name(pat: &syn::Pat) -> String { @@ -885,13 +987,115 @@ pub(crate) fn internal_doc_tokens( doc: TokenStream, self_ty: Option<&Type>, leading_marker: Option<&str>, + text_signature: Option<&crate::text_signature::TextSignature>, +) -> TokenStream { + let pieces = sig_pieces(sig, implicit_self, self_ty, leading_marker); + let args = args_const(&pieces); + let user_pieces = pieces + .iter() + .filter(|piece| match piece { + SigPiece::Implicit(_) => false, + SigPiece::Marker(name) => !name.starts_with('$'), + _ => true, + }) + .collect::>(); + let binding = user_pieces.iter().map(|piece| sig_arg_tokens(piece)); + let shared = user_pieces.iter().map(|piece| match piece { + SigPiece::Arg { ty, .. } => { + quote!(<#ty as ::rustpython_vm::function::ArgsMetadata>::TEXT_SIGNATURE) + } + _ => quote!(None), + }); + let receiver = leading_marker.or(implicit_self).or_else(|| { + sig.inputs + .iter() + .any(|arg| matches!(arg, FnArg::Receiver(_))) + .then_some("$self") + }); + let receiver = match receiver { + Some(marker) => quote!(Some(#marker)), + None => quote!(None), + }; + let selection = if let Some(signature) = text_signature { + let text = &signature.text; + let params = signature.params_tokens(); + let validator = signature.validator(); + quote! { + const BINDING_ARGS: &[::rustpython_vm::function::SigArg] = &[#(#binding),*]; + const _: () = { + assert!(SHARED.is_none(), "text_signature is already declared on the argument spec"); + #validator(BINDING_ARGS, &[#(#params),*]); + }; + const OVERRIDE: Option<(&str, Option<&str>)> = Some((#text, None)); + } + } else { + quote! { const OVERRIDE: Option<(&str, Option<&str>)> = match SHARED { + Some(text) => Some((text, #receiver)), None => None, + }; } + }; + let args = quote! { + #args + const SHARED: Option<&str> = ::rustpython_vm::function::argument_text_signature(&[#(#shared),*]); + #selection + }; + doc_from_signature_args(py_name, doc, args) +} + +/// CPython's flags-based fallback, evaluated entirely during compilation. +pub(crate) fn flags_signature_doc_tokens( + sig: &Signature, + py_name: &str, + doc: TokenStream, ) -> TokenStream { - let args_const = args_const(&sig_pieces(sig, implicit_self, self_ty, leading_marker)); + let pieces = sig_pieces(sig, None, None, None); + let original = args_const(&pieces); + let shared = pieces.iter().map(|piece| match piece { + SigPiece::Arg { ty, .. } => { + quote!(<#ty as ::rustpython_vm::function::ArgsMetadata>::TEXT_SIGNATURE) + } + _ => quote!(None), + }); + let args = quote! { + const ARGS: &[::rustpython_vm::function::SigArg] = { + #original + assert!(::rustpython_vm::function::argument_text_signature(&[#(#shared),*]).is_none(), + "text_signature and signature_from_flags are mutually exclusive"); + ::rustpython_vm::function::signature_from_flags(ARGS) + }; + }; + doc_from_signature_args( + py_name, + doc, + quote!(#args const OVERRIDE: Option<(&str, Option<&str>)> = None;), + ) +} + +pub(crate) fn doc_from_signature_args( + py_name: &(impl ToTokens + ?Sized), + doc: TokenStream, + args_const: TokenStream, +) -> TokenStream { + let prefix_len = quote! { match OVERRIDE { + Some((text, receiver)) => #py_name.len() + ::rustpython_vm::function::text_signature_len(text, receiver) + 5, + None => ::rustpython_vm::function::signature_prefix_len(#py_name, ARGS), + } }; + let prefix_bytes = quote! { match OVERRIDE { + Some((text, receiver)) => ::rustpython_vm::function::text_signature_doc_bytes::(#py_name, text, receiver, ""), + None => ::rustpython_vm::function::signature_prefix_bytes::(#py_name, ARGS), + } }; + let full_len = quote! { match OVERRIDE { + Some((text, receiver)) => #py_name.len() + ::rustpython_vm::function::text_signature_len(text, receiver) + 5 + BODY.len(), + None => ::rustpython_vm::function::internal_doc_len(#py_name, ARGS, BODY), + } }; + let full_bytes = quote! { match OVERRIDE { + Some((text, receiver)) => ::rustpython_vm::function::text_signature_doc_bytes::(#py_name, text, receiver, BODY), + None => ::rustpython_vm::function::internal_doc_bytes::(#py_name, ARGS, BODY), + } }; quote! { { #args_const const BASE: ::rustpython_vm::function::ItemDoc = #doc; - if !::rustpython_vm::function::has_signature(ARGS) { + if OVERRIDE.is_none() && !::rustpython_vm::function::has_signature(ARGS) { if BASE.len == 0 { match BASE.text { Some(text) if !text.is_empty() => { @@ -903,9 +1107,9 @@ pub(crate) fn internal_doc_tokens( BASE } } else if BASE.len != 0 { - const N: usize = ::rustpython_vm::function::signature_prefix_len(#py_name, ARGS); + const N: usize = #prefix_len; const B: [u8; N] = - ::rustpython_vm::function::signature_prefix_bytes::(#py_name, ARGS); + #prefix_bytes; const PREFIX: &str = match ::core::str::from_utf8(&B) { Ok(s) => s, Err(_) => panic!(), @@ -924,9 +1128,9 @@ pub(crate) fn internal_doc_tokens( Some(text) => text, None => "", }; - const N: usize = ::rustpython_vm::function::internal_doc_len(#py_name, ARGS, BODY); + const N: usize = #full_len; const B: [u8; N] = - ::rustpython_vm::function::internal_doc_bytes::(#py_name, ARGS, BODY); + #full_bytes; const FULL: &str = match ::core::str::from_utf8(&B) { Ok(s) => s, Err(_) => panic!(), @@ -937,74 +1141,224 @@ pub(crate) fn internal_doc_tokens( } } -pub(crate) fn infer_native_call_flags(sig: &Signature, drop_first_typed: usize) -> TokenStream { - // Best-effort mapping of Rust function signatures to CPython-style - // METH_* calling convention flags used by CALL specialization. - let mut typed_args = Vec::new(); - for arg in &sig.inputs { - let FnArg::Typed(typed) = arg else { - continue; - }; - let ty_tokens = &typed.ty; - let ty = quote!(#ty_tokens).to_string().replace(' ', ""); - // The interpreter supplies `vm` and `callee`; a Python call never - // passes them. - if (ty.starts_with('&') && ty.ends_with("VirtualMachine")) || ty.ends_with("Callee") { - continue; +#[cfg(test)] +mod metadata_tests { + use super::*; + use syn::{parse::Parser, parse_quote}; + + #[test] + fn module_receiver_has_no_opt_in() { + let attr = parse_quote!(#[pyfunction(with_module)]); + assert!(FunctionItemMeta::from_attr(parse_quote!(f), &attr).is_err()); + } + + #[test] + fn module_receiver_rejects_owned_ref_and_mutable_borrow() { + for signature in [ + parse_quote!(fn f(module: &mut Py)), + parse_quote!(fn f(module: PyRef, value: u8)), + parse_quote!(fn f(module: crate::PyRef)), + ] { + assert!(has_module_receiver(&signature).is_err()); } - typed_args.push(ty); } - let mut user_args = typed_args.into_iter(); - for _ in 0..drop_first_typed { - if user_args.next().is_none() { - break; + #[test] + fn module_receiver_is_a_leading_module_payload() { + for signature in [ + parse_quote!(fn f(module: &Py, value: u8)), + parse_quote!(fn f(module: &crate::Py)), + ] { + assert!(has_module_receiver(&signature).unwrap()); + } + for signature in [ + parse_quote!(fn f(value: PyRef)), + parse_quote!(fn f(value: PyObjectRef)), + parse_quote!(fn f(value: u8, module: PyRef)), + parse_quote!(fn f()), + ] { + assert!(!has_module_receiver(&signature).unwrap()); } } - let mut has_keywords = false; - let mut variable_arity = false; - let mut fixed_positional = 0usize; + fn parse_options(source: &str) -> Result { + let args = PunctuatedNestedMeta::parse_terminated.parse_str(source)?; + ItemMetaInner::from_nested( + parse_quote!(Example), + parse_quote!(pyclass), + args.into_iter(), + &["name", "impl"], + ) + } - for ty in user_args { - let is_named = |name: &str| { - ty == name - || ty.starts_with(&format!("{name}<")) - || ty.contains(&format!("::{name}<")) - || ty.ends_with(&format!("::{name}")) - }; + #[test] + fn signature_from_flags_is_a_module_function_only_opt_in() { + let attr = parse_quote!(#[pyfunction(name = "alias", signature_from_flags)]); + let meta = FunctionItemMeta::from_attr(parse_quote!(function), &attr).unwrap(); + assert_eq!(meta.simple_name().unwrap(), "alias"); + assert!(meta.signature_from_flags().unwrap()); + let ordinary = parse_quote!(#[pyfunction]); + assert!( + !FunctionItemMeta::from_attr(parse_quote!(function), &ordinary) + .unwrap() + .signature_from_flags() + .unwrap() + ); + assert!(SimpleItemMeta::from_attr(parse_quote!(function), &attr).is_err()); + let invalid = parse_quote!(#[pyfunction(signature_from_flags = "arbitrary text")]); + let result = FunctionItemMeta::from_attr(parse_quote!(function), &invalid); + assert!(result.and_then(|meta| meta.signature_from_flags()).is_err()); + } - if is_named("FuncArgs") { - has_keywords = true; - variable_arity = true; - continue; - } - if is_named("KwArgs") { - has_keywords = true; - variable_arity = true; - continue; - } - if is_named("PosArgs") || is_named("OptionalArg") || is_named("OptionalOption") { - variable_arity = true; - continue; - } - fixed_positional += 1; + #[test] + fn signature_receiver_validation_precedes_codegen() { + let module: Attribute = parse_quote!(#[pyfunction(text_signature = "($self, value, /)")]); + let meta = FunctionItemMeta::from_attr(parse_quote!(sample), &module).unwrap(); + assert!(meta.text_signature(Some("$module")).is_err()); + assert!(meta.text_signature(None).is_err()); + assert!(meta.text_signature(Some("$self")).is_ok()); } - if has_keywords { - quote! { - rustpython_vm::function::PyMethodFlags::from_bits_retain( - rustpython_vm::function::PyMethodFlags::FASTCALL.bits() - | rustpython_vm::function::PyMethodFlags::KEYWORDS.bits() + #[test] + fn shared_signature_uses_only_python_argument_specs() { + let signature: Signature = + parse_quote!(fn method(zelf: PyRef, args: SearchArgs, vm: &VirtualMachine)); + let tokens = internal_doc_tokens( + &signature, + "method", + Some("$self"), + quote!(Doc), + None, + None, + None, + ) + .to_string(); + let binding = tokens + .split("const SHARED") + .nth(1) + .unwrap() + .split("const OVERRIDE") + .next() + .unwrap(); + assert!(binding.contains("SearchArgs")); + assert!(!binding.contains("PyRef")); + assert!(!binding.contains("$self")); + assert!(tokens.contains("ArgsMetadata > :: TEXT_SIGNATURE")); + let signature: Signature = parse_quote!(fn ordinary(value: PyRef)); + let tokens = + internal_doc_tokens(&signature, "ordinary", None, quote!(Doc), None, None, None) + .to_string(); + let binding = tokens + .split("const SHARED") + .nth(1) + .unwrap() + .split("const OVERRIDE") + .next() + .unwrap(); + assert!(binding.contains("PyRef")); + } + + #[test] + fn explicit_signature_is_checked_even_without_generated_display_or_docs() { + let sig: Signature = parse_quote!(fn sample((a, b): ValueArgs)); + let signature = crate::text_signature::TextSignature::parse( + "($module, value, /)".into(), + Span::call_site(), + ) + .unwrap(); + for doc in [ + quote!(::rustpython_vm::function::ItemDoc::NONE), + quote!(::rustpython_vm::function::ItemDoc::static_text("Body")), + quote!(::rustpython_vm::function::ItemDoc { + text: None, + offset: 1, + len: 4 + }), + ] { + let tokens = internal_doc_tokens( + &sig, + "sample", + None, + doc, + None, + Some("$module"), + Some(&signature), ) + .to_string(); + assert!(tokens.contains("validate_text_signature (BINDING_ARGS")); + assert!(tokens.contains("if OVERRIDE . is_none () && !")); + assert!(tokens.contains("text_signature_doc_bytes")); + assert!(tokens.contains("ValueArgs")); + assert!(tokens.contains("offset : BASE . offset")); + assert!(tokens.contains("len : BASE . len")); } - } else if variable_arity { - quote! { rustpython_vm::function::PyMethodFlags::FASTCALL } - } else { - match fixed_positional { - 0 => quote! { rustpython_vm::function::PyMethodFlags::NOARGS }, - 1 => quote! { rustpython_vm::function::PyMethodFlags::O }, - _ => quote! { rustpython_vm::function::PyMethodFlags::FASTCALL }, - } + } + + #[test] + fn signature_from_flags_codegen_preserves_original_argument_metadata() { + let sig: Signature = parse_quote!(fn sample(value: ValueArgs, vm: &VirtualMachine)); + let doc = quote!(::rustpython_vm::function::ItemDoc::NONE); + let from_flags = flags_signature_doc_tokens(&sig, "sample", doc.clone()).to_string(); + assert!(from_flags.contains("signature_from_flags")); + assert!(from_flags.contains("ValueArgs")); + assert!(from_flags.contains("TEXT_SIGNATURE")); + assert!(from_flags.contains("mutually exclusive")); + let ordinary = + internal_doc_tokens(&sig, "sample", None, doc, None, Some("$module"), None).to_string(); + assert!(!ordinary.contains("signature_from_flags")); + assert!(ordinary.contains("$module")); + } + + #[test] + fn option_validation_keeps_contextual_diagnostics() { + assert_eq!( + parse_options("name, name").err().unwrap().to_string(), + "this attribute path must be unique in the attribute" + ); + assert_eq!( + parse_options("7").err().unwrap().to_string(), + "#[pyclass(..)] cannot contain literal" + ); + assert_eq!( + parse_options("unknown").err().unwrap().to_string(), + "#[pyclass(unknown)] is not one of allowed attributes [name, impl]" + ); + let options = parse_options("impl, name = \"Example\"").unwrap(); + assert!(options._bool("impl").unwrap()); + assert_eq!( + options._optional_str("name").unwrap().as_deref(), + Some("Example") + ); + } + + #[test] + fn attribute_edits_preserve_other_options_and_delimiters() { + let mut attr: Attribute = parse_quote!(#[pyclass(name, no_attr, module = false,)]); + assert!(attr.try_remove_name("no_attr").unwrap().is_some()); + attr.fill_nested_meta("module", || parse_quote!(module = "replacement")) + .unwrap(); + assert_eq!( + quote!(#attr).to_string(), + quote!(#[pyclass(name, module = false,)]).to_string() + ); + assert!(attr.try_remove_name("missing").unwrap().is_none()); + let mut bare: Attribute = parse_quote!(#[pyclass]); + bare.fill_nested_meta("name", || parse_quote!(name = "Example")) + .unwrap(); + assert_eq!( + quote!(#bare).to_string(), + quote!(#[pyclass(name = "Example")]).to_string() + ); + } + + #[test] + fn failed_duplicate_removal_does_not_mutate_attribute() { + let mut attr: Attribute = parse_quote!(#[pyclass(no_attr, no_attr)]); + let original = quote!(#attr).to_string(); + assert_eq!( + attr.try_remove_name("no_attr").err().unwrap().to_string(), + "#[py..(no_attr...)] must be unique but found multiple times" + ); + assert_eq!(quote!(#attr).to_string(), original); } } diff --git a/crates/derive/src/lib.rs b/crates/derive/src/lib.rs index d6cd7bc2ba3..f460bb93252 100644 --- a/crates/derive/src/lib.rs +++ b/crates/derive/src/lib.rs @@ -26,6 +26,10 @@ use syn::punctuated::Punctuated; /// `OptionalArg` is converted only when the argument is missing: /// `::try_from_object(vm, ToPyObject::to_pyobject(LIT, vm))?`. /// A byte-string literal becomes a Python `bytes` object. +/// `default = None` on `Option`, including `Option`, stores +/// Rust `None` and displays `None` in the signature without `py_default`. +/// It does not construct Python's None object for an unwrapped field or +/// mean `OptionalArg::Missing`. /// - `default = ::NAME`: `NAME` is one identifier. The signature copies that /// name, and the missing argument stores `Into::into(NAME)` (the leading /// `::` is not Rust syntax for a local constant). A longer `::` path is a @@ -40,6 +44,14 @@ use syn::punctuated::Punctuated; /// when a missing argument is a distinct state, or give the default's type a /// real `py_default()`. /// - `error_msg = "..."`: type-error text when conversion fails. +/// +/// A complete shared argument spec can use +/// `#[from_args(text_signature = "(sub[, start[, end]], /)")]`. +/// This checked display-only override is inherited by functions sharing the +/// type, like a Clinic clone. It has no receiver; the item macro supplies one. +/// It must be the function's only Python argument spec. It does not change +/// binding, defaults, conversions, or the stored docstring body. +/// /// # Signature default /// An explicit `py_default` is used as written. Otherwise: /// - a literal, a negative literal, or the path `None` becomes a typed default @@ -80,6 +92,47 @@ use syn::punctuated::Punctuated; /// | `Option` | `None` or a value. A missing argument and an explicit `None` are the same | `= None` | `None` | /// | `OptionalOption` (`OptionalArg>`) | missing, `None`, and a value are all distinct | `= NULL`, and `None` is accepted | `` | /// +/// # Borrowed arguments +/// `#[from_args(borrowed)]` selects borrowing with the same strict Clinic rules: +/// +/// ```rust,ignore +/// #[derive(FromArgs)] +/// #[from_args(borrowed)] +/// struct CallArgs<'a> { +/// #[pyarg(any)] +/// object: &'a PyObject, +/// #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] +/// flag: ArgIntoBool, +/// } +/// +/// #[pyfunction] +/// fn call(args: CallArgs<'_>, vm: &VirtualMachine) -> PyResult { /* ... */ } +/// ``` +/// +/// Binding uses stack slots and `TryFromBorrowedObject`, leaving the native +/// call's original owners alive through the implementation and return conversion. +/// It adds no owning copies or heap allocation. All Clinic binding errors are +/// checked before converting fields in declaration order. `OptionalArg<&Py>` +/// distinguishes omission from an explicitly supplied value without constructing +/// a default Python object. Rust converter constants can supply scalar defaults. +/// A borrowed `py_default` requires `optional` or `default` omission handling. +/// +/// Borrowed structs currently support fixed fields, one lifetime, and no other +/// generic parameters. Flattened and legacy bindings remain owned. A borrowed +/// struct is passed as the sole arguments struct followed by `&VirtualMachine`. +/// +/// # `#[from_args(legacy, fname = "...")]` +/// Bind arguments the way `PyArg_ParseTupleAndKeywords` does: convert each +/// supplied value in parameter order, then report a missing argument, a leftover +/// keyword, or a name given both by position and by keyword. `fname` is the name +/// those messages use. `PARAMS` and `arity()` are still generated, so +/// `__text_signature__` and docs keep working. +/// +/// Both `legacy` and `fname` are required. An unknown key is rejected. +/// A `legacy` struct may not contain `positional` or `flatten` fields, a +/// required field after an optional one, or a non-keyword-only field after a +/// keyword-only (`named`) field. +/// /// Keep `py_default` when the expression needs `vm` (so it is not const), or /// when an `OptionalArg` is missing in the body and the shown default is a /// concrete value the Rust type cannot store. @@ -101,7 +154,7 @@ use syn::punctuated::Punctuated; /// file: Option, /// } /// ``` -#[proc_macro_derive(FromArgs, attributes(pyarg))] +#[proc_macro_derive(FromArgs, attributes(pyarg, from_args))] pub fn derive_from_args(input: TokenStream) -> TokenStream { let input = parse_macro_input!(input); derive_impl::derive_from_args(input).into() @@ -145,6 +198,9 @@ pub fn derive_from_args(input: TokenStream) -> TokenStream { /// ... /// } /// ``` +/// A constructor or initializer argument spec can use `#[from_args(text_signature = "(...)")]` +/// for an explicit class display signature. The receiverless override is checked +/// against that spec and composed with the existing class documentation. /// ## Docstrings /// A `///` doc comment on the struct, or on a `#[pymethod]` / `#[pyclassmethod]` / /// `#[pystaticmethod]` / `#[pygetset]` / `#[pymember]` item, is the Python @@ -169,6 +225,14 @@ pub fn derive_from_args(input: TokenStream) -> TokenStream { /// - `name`: the name of the method in Python, /// by default it is the same as the Rust method, or surrounded by double underscores if magic is present. /// This overrides `magic` and the default name and cannot be used with `magic` to prevent ambiguity. +/// - `text_signature = "(...)"`: an explicit checked display signature, checked +/// at compile time against binding metadata. Supports positional parameters, +/// `/`, literal defaults, `**kwargs`, and nested trailing optional groups +/// such as `($self, sub[, start[, end]], /)`. Display-only aliases for +/// positional parameters and literal defaults do not change argument parsing. +/// Optional positional parameters may be documented as keyword-capable when +/// a legacy wrapper accepts and forwards arbitrary keywords; the name must +/// match the binding metadata. Unknown binders are rejected. /// ### pygetset /// This is used to mark a getter/setter pair. /// #### Arguments @@ -346,8 +410,27 @@ pub fn pyexception(attr: TokenStream, item: TokenStream) -> TokenStream { /// } /// ``` /// ### pyfunction +/// +/// `#[pyfunction(text_signature = "(...)")]` supports the same checked explicit +/// display overrides as `pymethod`. It cannot be combined with +/// `signature_from_flags`. +/// +/// `#[pyfunction(signature_from_flags)]` displays CPython's non-Clinic +/// `METH_NOARGS` / `METH_O` signature (`$self`, and `object` for one argument). +/// Compilation rejects anything other than zero or one required positional-only +/// argument. It changes only the generated text, not module ownership or calls. +/// Use this only where CPython derives the signature from its method flags; +/// ordinary functions retain their generated Clinic-style signature. +/// /// This is used to create a python function. /// #### Function signature +/// A leading `&Py` receives the defining module, outside the Python +/// argument list. No attribute option is needed. Qualified paths are supported, +/// but type aliases are not resolved; a leading `PyRef` is rejected. +/// Use the canonical form for module receivers. To +/// accept a Python-visible module as the first argument, declare the +/// defining-module receiver first and the target module second. +/// /// The last argument can optionally be of the type `&VirtualMachine` to access the VM. /// Refer to the `pymethod` documentation (located in the `pyclass` macro documentation) /// for more information on what regular argument types are permitted. diff --git a/crates/doc/generate.py b/crates/doc/generate.py index 4b64ce5e236..bb81cb9295e 100644 --- a/crates/doc/generate.py +++ b/crates/doc/generate.py @@ -6,7 +6,6 @@ import os import pathlib import platform -import pydoc import re import sys import types @@ -14,6 +13,11 @@ import warnings from importlib.machinery import EXTENSION_SUFFIXES, ExtensionFileLoader +try: + from inspect import _getowndoc +except ImportError: # Python 3.14 and earlier + from pydoc import _getowndoc + if typing.TYPE_CHECKING: from collections.abc import Iterable @@ -146,7 +150,7 @@ def traverse( parts += (obj.__name__,) if any(f(obj) for f in (inspect.ismodule, inspect.isclass, inspect.isbuiltin)): - yield DocEntry(parts, pydoc._getowndoc(obj)) + yield DocEntry(parts, _getowndoc(obj)) if inspect.isclass(obj): # getmembers() shows the class's own metadata for these names (e.g. @@ -159,7 +163,7 @@ def traverse( if isinstance( attr, (types.GetSetDescriptorType, types.MemberDescriptorType) ): - yield DocEntry(parts + (name,), pydoc._getowndoc(attr)) + yield DocEntry(parts + (name,), _getowndoc(attr)) for name, attr in inspect.getmembers(obj): if name in IGNORED_ATTRS: @@ -211,7 +215,7 @@ def traverse( ) if is_callable or is_func: - yield DocEntry(new_parts, pydoc._getowndoc(attr)) + yield DocEntry(new_parts, _getowndoc(attr)) # A native type the module exposes only through an instance # (e.g. the type of sys.flags). if ( @@ -283,7 +287,7 @@ def iter_native_on_python_modules( if inspect.isclass(attr): yield from traverse(attr, module, parts) else: - yield DocEntry(parts, pydoc._getowndoc(attr)) + yield DocEntry(parts, _getowndoc(attr)) def find_doc_entries() -> "Iterable[DocEntry]": @@ -322,7 +326,7 @@ def find_doc_entries() -> "Iterable[DocEntry]": module_names.append(typ.__module__) for module_name in module_names: parts = (module_name, typ.__name__) - yield DocEntry(parts, pydoc._getowndoc(typ)) + yield DocEntry(parts, _getowndoc(typ)) yield from traverse(typ, __builtins__, parts) diff --git a/crates/doc/src/data.inc.rs b/crates/doc/src/data.inc.rs index 0d10b224d20..94ae7093cdd 100644 --- a/crates/doc/src/data.inc.rs +++ b/crates/doc/src/data.inc.rs @@ -685,7 +685,7 @@ pub const DB: &[(&str, &str)] = &[ ("_ast.Dict.__str__", "Return str(self)."), ("_ast.Dict.__subclasshook__", "Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n"), ("_ast.Dict.__weakref__", "list of weak references to the object"), - ("_ast.DictComp", "DictComp(expr key, expr value, comprehension* generators)"), + ("_ast.DictComp", "DictComp(expr key, expr? value, comprehension* generators)"), ("_ast.DictComp.__class__", "the object's class"), ("_ast.DictComp.__delattr__", "Implement delattr(self, name)."), ("_ast.DictComp.__dir__", "Default dir() implementation."), @@ -2886,7 +2886,7 @@ pub const DB: &[(&str, &str)] = &[ ("_ast.excepthandler.__str__", "Return str(self)."), ("_ast.excepthandler.__subclasshook__", "Abstract classes can override this to customize issubclass().\n\nThis is invoked early on by abc.ABCMeta.__subclasscheck__().\nIt should return True, False or NotImplemented. If it returns\nNotImplemented, the normal algorithm is used. Otherwise, it\noverrides the normal algorithm (and the outcome is cached).\n"), ("_ast.excepthandler.__weakref__", "list of weak references to the object"), - ("_ast.expr", "expr = BoolOp(boolop op, expr* values)\n | NamedExpr(expr target, expr value)\n | BinOp(expr left, operator op, expr right)\n | UnaryOp(unaryop op, expr operand)\n | Lambda(arguments args, expr body)\n | IfExp(expr test, expr body, expr orelse)\n | Dict(expr?* keys, expr* values)\n | Set(expr* elts)\n | ListComp(expr elt, comprehension* generators)\n | SetComp(expr elt, comprehension* generators)\n | DictComp(expr key, expr value, comprehension* generators)\n | GeneratorExp(expr elt, comprehension* generators)\n | Await(expr value)\n | Yield(expr? value)\n | YieldFrom(expr value)\n | Compare(expr left, cmpop* ops, expr* comparators)\n | Call(expr func, expr* args, keyword* keywords)\n | FormattedValue(expr value, int conversion, expr? format_spec)\n | Interpolation(expr value, constant str, int conversion, expr? format_spec)\n | JoinedStr(expr* values)\n | TemplateStr(expr* values)\n | Constant(constant value, string? kind)\n | Attribute(expr value, identifier attr, expr_context ctx)\n | Subscript(expr value, expr slice, expr_context ctx)\n | Starred(expr value, expr_context ctx)\n | Name(identifier id, expr_context ctx)\n | List(expr* elts, expr_context ctx)\n | Tuple(expr* elts, expr_context ctx)\n | Slice(expr? lower, expr? upper, expr? step)"), + ("_ast.expr", "expr = BoolOp(boolop op, expr* values)\n | NamedExpr(expr target, expr value)\n | BinOp(expr left, operator op, expr right)\n | UnaryOp(unaryop op, expr operand)\n | Lambda(arguments args, expr body)\n | IfExp(expr test, expr body, expr orelse)\n | Dict(expr?* keys, expr* values)\n | Set(expr* elts)\n | ListComp(expr elt, comprehension* generators)\n | SetComp(expr elt, comprehension* generators)\n | DictComp(expr key, expr? value, comprehension* generators)\n | GeneratorExp(expr elt, comprehension* generators)\n | Await(expr value)\n | Yield(expr? value)\n | YieldFrom(expr value)\n | Compare(expr left, cmpop* ops, expr* comparators)\n | Call(expr func, expr* args, keyword* keywords)\n | FormattedValue(expr value, int conversion, expr? format_spec)\n | Interpolation(expr value, constant str, int conversion, expr? format_spec)\n | JoinedStr(expr* values)\n | TemplateStr(expr* values)\n | Constant(constant value, string? kind)\n | Attribute(expr value, identifier attr, expr_context ctx)\n | Subscript(expr value, expr slice, expr_context ctx)\n | Starred(expr value, expr_context ctx)\n | Name(identifier id, expr_context ctx)\n | List(expr* elts, expr_context ctx)\n | Tuple(expr* elts, expr_context ctx)\n | Slice(expr? lower, expr? upper, expr? step)"), ("_ast.expr.__class__", "the object's class"), ("_ast.expr.__delattr__", "Implement delattr(self, name)."), ("_ast.expr.__dir__", "Default dir() implementation."), @@ -11221,7 +11221,9 @@ pub const DB: &[(&str, &str)] = &[ ("binascii.Incomplete.__weakref__", "list of weak references to the object"), ("binascii.Incomplete.add_note", "Add a note to the exception"), ("binascii.Incomplete.with_traceback", "Set self.__traceback__ to tb and return self."), - ("binascii.a2b_base64", "Decode a line of base64 data.\n\n strict_mode\n When set to True, bytes that are not part of the base64 standard are not allowed.\n The same applies to excess data after padding (= / ==)."), + ("binascii.a2b_base32", "Decode a line of base32 data.\n\n padded\n When set to false, padding in input is not required.\n ignorechars\n A byte string containing characters to ignore from the input.\n canonical\n When set to true, reject non-zero padding bits per RFC 4648 section 3.5."), + ("binascii.a2b_base64", "Decode a line of base64 data.\n\n strict_mode\n When set to true, bytes that are not part of the base64 standard are\n not allowed. The same applies to excess data after padding (= / ==).\n Set to True by default if ignorechars is specified, False otherwise.\n padded\n When set to false, padding in input is not required.\n ignorechars\n A byte string containing characters to ignore from the input when\n strict_mode is true.\n canonical\n When set to true, reject non-zero padding bits per RFC 4648 section 3.5."), + ("binascii.a2b_base85", "Decode a line of Base85 data.\n\n ignorechars\n A byte string containing characters to ignore from the input.\n canonical\n When set to true, reject non-canonical encodings."), ("binascii.a2b_hex", "Binary data of hexadecimal representation.\n\nhexstr must contain an even number of hex digits (upper or lower case).\nThis function is also available as \"unhexlify()\"."), ("binascii.a2b_qp", "Decode a string of qp-encoded data."), ("binascii.a2b_uu", "Decode a line of uuencoded data."), diff --git a/crates/host_env/Cargo.toml b/crates/host_env/Cargo.toml index 029c2860f33..2cc3efc913e 100644 --- a/crates/host_env/Cargo.toml +++ b/crates/host_env/Cargo.toml @@ -9,6 +9,9 @@ repository.workspace = true license.workspace = true [features] +# On wasm32-unknown-unknown this makes the io/crt_fd backends import the WASI +# preview1 subset; on other targets it has no effect. +host_io = [] # `ctypes` module: libffi (linked against the system library) and libloading. ctypes = ["dep:libffi", "dep:libloading"] native-certs = ["dep:rustls-native-certs"] @@ -37,7 +40,6 @@ getrandom = { workspace = true } libc = { workspace = true } num-traits = { workspace = true } parking_lot = { workspace = true } -paste = { workspace = true } pkcs8 = { workspace = true, features = ["encryption", "pkcs5", "pem"], optional = true } rustls = { workspace = true, default-features = false, features = ["std", "tls12"], optional = true } rustls-pemfile = { workspace = true, optional = true } @@ -77,10 +79,14 @@ libloading = { workspace = true, optional = true } libffi = { workspace = true, features = ["system"], optional = true } [target.'cfg(target_os = "macos")'.dependencies] +mach2 = { workspace = true } system-configuration = { workspace = true } +[target.'cfg(any(all(target_os = "linux", not(target_env = "uclibc")), target_os = "macos", windows))'.dependencies] +object = { workspace = true } + [target.'cfg(windows)'.dependencies] -memchr.workspace = true +paste = { workspace = true } junction = { workspace = true } schannel = { workspace = true } windows-sys = { workspace = true, features = [ @@ -97,7 +103,9 @@ windows-sys = { workspace = true, features = [ "Win32_System_Com", "Win32_System_Console", "Win32_System_Diagnostics_Debug", + "Win32_System_Diagnostics_ToolHelp", "Win32_System_Environment", + "Win32_System_EventLog", "Win32_System_Ole", "Win32_System_IO", "Win32_System_Ioctl", diff --git a/crates/host_env/src/cert_store.rs b/crates/host_env/src/cert_store.rs index f95716faa99..ab5b92672a8 100644 --- a/crates/host_env/src/cert_store.rs +++ b/crates/host_env/src/cert_store.rs @@ -1,11 +1,15 @@ +use core::ffi::CStr; use std::io; use schannel::{RawPointer, cert_context::ValidUses, cert_store::CertStore}; use windows_sys::Win32::{ Foundation::{CRYPT_E_NOT_FOUND, GetLastError}, Security::Cryptography::{ - CERT_CONTEXT, CRL_CONTEXT, CertCloseStore, CertEnumCRLsInStore, CertOpenSystemStoreW, - PKCS_7_ASN_ENCODING, X509_ASN_ENCODING, + CERT_CONTEXT, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG, + CERT_STORE_PROV_SYSTEM_A, CERT_STORE_READONLY_FLAG, CERT_SYSTEM_STORE_LOCAL_MACHINE, + CRL_CONTEXT, CTL_USAGE, CertCloseStore, CertEnumCRLsInStore, CertEnumCertificatesInStore, + CertFreeCertificateContext, CertGetEnhancedKeyUsage, CertOpenStore, CertOpenSystemStoreW, + HCERTSTORE, PKCS_7_ASN_ENCODING, X509_ASN_ENCODING, }, }; @@ -51,6 +55,158 @@ fn encoding_type(raw: u32) -> EncodingType { } } +fn encoding_type_exact(raw: u32) -> EncodingType { + match raw { + X509_ASN_ENCODING => EncodingType::X509Asn, + PKCS_7_ASN_ENCODING => EncodingType::Pkcs7Asn, + other => EncodingType::Other(other), + } +} + +fn open_local_machine(store_name: &CStr) -> io::Result { + let store = unsafe { + CertOpenStore( + CERT_STORE_PROV_SYSTEM_A, + 0, + 0, + CERT_SYSTEM_STORE_LOCAL_MACHINE | CERT_STORE_READONLY_FLAG, + store_name.as_ptr().cast(), + ) + }; + if store.is_null() { + Err(io::Error::last_os_error()) + } else { + Ok(store) + } +} + +unsafe fn certificate_uses_for_flags( + cert: *const CERT_CONTEXT, + flags: u32, +) -> io::Result> { + let mut size = 0; + if unsafe { CertGetEnhancedKeyUsage(cert, flags, core::ptr::null_mut(), &mut size) } == 0 { + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(CRYPT_E_NOT_FOUND) { + return Ok(None); + } + return Err(error); + } + + let words = (size as usize) + .max(core::mem::size_of::()) + .div_ceil(core::mem::size_of::()); + let mut buffer = vec![0usize; words]; + let usage = buffer.as_mut_ptr().cast::(); + if unsafe { CertGetEnhancedKeyUsage(cert, flags, usage, &mut size) } == 0 { + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(CRYPT_E_NOT_FOUND) { + return Ok(None); + } + return Err(error); + } + + let usage = unsafe { &*usage }; + let mut oids = Vec::with_capacity(usage.cUsageIdentifier as usize); + for index in 0..usage.cUsageIdentifier as usize { + let oid = unsafe { *usage.rgpszUsageIdentifier.add(index) }; + if !oid.is_null() { + oids.push( + unsafe { CStr::from_ptr(oid.cast()) } + .to_string_lossy() + .into_owned(), + ); + } + } + Ok(Some(CertificateUses::Oids(oids))) +} + +unsafe fn certificate_uses(cert: *const CERT_CONTEXT) -> io::Result { + if let Some(uses) = + unsafe { certificate_uses_for_flags(cert, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG) }? + { + return Ok(uses); + } + Ok( + unsafe { certificate_uses_for_flags(cert, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG) }? + .unwrap_or(CertificateUses::All), + ) +} + +/// Enumerate one read-only local-machine system store, matching the store +/// selected by CPython's Windows SSL helpers. Opening and closing the store +/// are both fallible; a close failure takes precedence over an enumeration +/// failure because it happens last. +pub fn enum_certificates_local_machine(store_name: &CStr) -> io::Result> { + let store = open_local_machine(store_name)?; + let result = (|| { + let mut entries = Vec::new(); + let mut context: *const CERT_CONTEXT = core::ptr::null(); + loop { + context = unsafe { CertEnumCertificatesInStore(store, context) }; + if context.is_null() { + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(CRYPT_E_NOT_FOUND) { + break; + } + return Err(error); + } + let cert = unsafe { &*context }; + let valid_uses = unsafe { certificate_uses(context) }; + if let Err(error) = valid_uses { + unsafe { CertFreeCertificateContext(context) }; + return Err(error); + } + entries.push(CertificateEntry { + der: unsafe { + core::slice::from_raw_parts(cert.pbCertEncoded, cert.cbCertEncoded as usize) + } + .to_vec(), + encoding: encoding_type_exact(cert.dwCertEncodingType), + valid_uses, + }); + } + Ok(entries) + })(); + if unsafe { CertCloseStore(store, 0) } == 0 { + return Err(io::Error::last_os_error()); + } + result +} + +/// Enumerate certificate-revocation lists from one read-only local-machine +/// system store. +pub fn enum_crls_local_machine(store_name: &CStr) -> io::Result> { + let store = open_local_machine(store_name)?; + let result = (|| { + let mut entries = Vec::new(); + let mut context: *const CRL_CONTEXT = core::ptr::null(); + loop { + context = unsafe { CertEnumCRLsInStore(store, context) }; + if context.is_null() { + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(CRYPT_E_NOT_FOUND) { + break; + } + return Err(error); + } + let crl = unsafe { &*context }; + entries.push(CrlEntry { + der: unsafe { + core::slice::from_raw_parts(crl.pbCrlEncoded, crl.cbCrlEncoded as usize) + } + .to_vec(), + encoding: encoding_type_exact(crl.dwCertEncodingType), + }); + } + Ok(entries) + })(); + if unsafe { CertCloseStore(store, 0) } == 0 { + return Err(io::Error::last_os_error()); + } + result +} + pub fn enum_certificates(store_name: &str) -> CertificateEntries { let open_fns = [CertStore::open_current_user, CertStore::open_local_machine]; let mut had_open_store = false; diff --git a/crates/host_env/src/crt_fd.rs b/crates/host_env/src/crt_fd.rs index f06c5aad984..12c335eb3a3 100644 --- a/crates/host_env/src/crt_fd.rs +++ b/crates/host_env/src/crt_fd.rs @@ -21,6 +21,8 @@ mod c { unsafe extern "C" { #[link_name = "_chsize_s"] pub(super) fn ftruncate(fd: i32, len: i64) -> i32; + pub(super) fn _get_doserrno(value: *mut c_ulong) -> c_int; + pub(super) fn _set_doserrno(value: c_ulong) -> c_int; } } @@ -317,7 +319,10 @@ impl AsRawFd for Borrowed<'_> { #[inline] fn ebadf() -> io::Error { - io::Error::from_raw_os_error(c::EBADF) + cfg_select! { + windows => crate::os::io_error_from_errno(c::EBADF), + _ => io::Error::from_raw_os_error(c::EBADF), + } } pub fn open(path: &ffi::CStr, flags: i32, mode: i32) -> io::Result { @@ -331,7 +336,13 @@ pub fn wopen(path: &widestring::WideCStr, flags: i32, mode: i32) -> io::Result, path: &ffi::CStr, flags: i32, mode: i32) -> io::Result { - cvt_fd(unsafe { c::openat(dir.as_raw(), path.as_ptr(), flags, mode) }) + openat_raw(dir.as_raw(), path, flags, mode) +} + +#[cfg(all(any(unix, target_os = "wasi"), not(target_os = "redox")))] +// Accept a descriptor number without asserting it stays open across calls. +pub fn openat_raw(dir: Raw, path: &ffi::CStr, flags: i32, mode: i32) -> io::Result { + cvt_fd(unsafe { c::openat(dir, path.as_ptr(), flags, mode) }) } pub fn fsync(fd: Borrowed<'_>) -> io::Result<()> { @@ -348,8 +359,53 @@ pub fn close(fd: Owned) -> io::Result<()> { _close(fd.into_raw()) } +#[cfg(not(any(target_os = "freebsd", target_os = "linux")))] +pub fn closerange(fd_low: Raw, fd_high: Raw) { + close_range_slow(fd_low, fd_high); +} + +// _Py_closerange +#[cfg(any(target_os = "freebsd", target_os = "linux"))] +pub fn closerange(fd_low: Raw, fd_high: Raw) { + // CPython clamps low to 0. + let fd_low = fd_low.max(0); + // close_range(2) is [low, high] whereas CPython's is [low, high). + if fd_high <= fd_low { + return; + } + let high = fd_high - 1; + + if close_range(fd_low as _, high as _) == -1 + && io::Error::last_os_error().raw_os_error() == Some(libc::ENOSYS) + { + close_range_slow(fd_low, fd_high); + } +} + +#[cfg(target_os = "freebsd")] +fn close_range(low: ffi::c_uint, high: ffi::c_uint) -> ffi::c_int { + unsafe { libc::close_range(low, high, 0) as ffi::c_int } +} + +#[cfg(target_os = "linux")] +fn close_range(low: ffi::c_uint, high: ffi::c_uint) -> ffi::c_int { + unsafe { libc::syscall(libc::SYS_close_range, low, high, 0) as ffi::c_int } +} + +fn close_range_slow(low: Raw, high: Raw) { + for fd in low..high { + // The range can contain closed descriptors, so it cannot use Owned. + let _ = _close(fd); + } +} + pub fn ftruncate(fd: Borrowed<'_>, len: Offset) -> io::Result<()> { - let ret = unsafe { suppress_iph!(c::ftruncate(fd.as_raw(), len)) }; + ftruncate_raw(fd.as_raw(), len) +} + +/// Truncate a caller-supplied descriptor, letting the CRT validate its value. +pub fn ftruncate_raw(fd: Raw, len: Offset) -> io::Result<()> { + let ret = unsafe { suppress_iph!(c::ftruncate(fd, len)) }; // On Windows, _chsize_s returns 0 on success, or a positive error code (errno value) on failure. // On other platforms, ftruncate returns 0 on success, or -1 on failure with errno set. cfg_select! { @@ -381,14 +437,82 @@ pub fn as_handle(fd: Borrowed<'_>) -> io::Result> { fn _write(fd: Raw, buf: &[u8]) -> io::Result { let count = cmp::min(buf.len(), MAX_RW); - let n = cvt(unsafe { suppress_iph!(c::write(fd, buf.as_ptr() as _, count as _)) })?; - Ok(n as usize) + write_errno(fd, &buf[..count]).map_err(|errno| { + cfg_select! { + windows => crate::os::io_error_from_errno(errno), + _ => io::Error::from_raw_os_error(errno), + } + }) +} + +/// `_Py_write_noraise`: retry on EINTR and return the errno on failure +/// without allocating, so the OS signal handler can use it. +pub fn write_noraise(fd: Raw, buf: &[u8]) -> Result { + let count = cmp::min(buf.len(), MAX_RW); + loop { + match write_errno(fd, &buf[..count]) { + Err(libc::EINTR) => continue, + result => return result, + } + } +} + +fn write_errno(fd: Raw, buf: &[u8]) -> Result { + #[cfg(windows)] + { + let mut count = buf.len(); + loop { + unsafe { c::_set_doserrno(0) }; + let n = unsafe { suppress_iph!(c::write(fd, buf.as_ptr() as _, count as _)) }; + if n >= 0 { + return Ok(n as usize); + } + let errno = crate::os::get_errno(); + // The CRT reports a successful zero-byte WriteFile as ENOSPC. + // A nonblocking pipe may still accept a smaller prefix. + if errno != libc::ENOSPC || dos_error() != 0 { + return Err(errno); + } + count /= 2; + if count == 0 { + return Err(libc::EAGAIN); + } + } + } + #[cfg(not(windows))] + { + let n = unsafe { suppress_iph!(c::write(fd, buf.as_ptr() as _, buf.len() as _)) }; + if n < 0 { + Err(crate::os::get_errno()) + } else { + Ok(n as usize) + } + } } fn _read(fd: Raw, buf: &mut [u8]) -> io::Result { let count = cmp::min(buf.len(), MAX_RW); - let n = cvt(unsafe { suppress_iph!(libc::read(fd, buf.as_mut_ptr() as _, count as _)) })?; - Ok(n as usize) + #[cfg(windows)] + unsafe { + c::_set_doserrno(0); + } + let n = unsafe { suppress_iph!(libc::read(fd, buf.as_mut_ptr() as _, count as _)) }; + #[cfg(windows)] + if n < 0 + && crate::os::get_errno() == libc::EINVAL + && dos_error() == windows_sys::Win32::Foundation::ERROR_NO_DATA + { + return Err(crate::os::io_error_from_errno(libc::EAGAIN)); + } + cvt(n).map(|n| n as usize) +} + +#[cfg(windows)] +fn dos_error() -> u32 { + let mut error = 0; + // SAFETY: the CRT writes to a valid unsigned long on the current thread. + unsafe { c::_get_doserrno(&mut error) }; + error } pub fn write(fd: Borrowed<'_>, buf: &[u8]) -> io::Result { diff --git a/crates/host_env/src/crt_fd_unsupported.rs b/crates/host_env/src/crt_fd_unsupported.rs index 7fb8a406e32..109ce0fa38f 100644 --- a/crates/host_env/src/crt_fd_unsupported.rs +++ b/crates/host_env/src/crt_fd_unsupported.rs @@ -1,3 +1,4 @@ +use crate::errno::errors::EBADF; use alloc::fmt; use core::marker::PhantomData; use std::{ffi, io}; @@ -5,8 +6,6 @@ use std::{ffi, io}; pub type Offset = i64; pub type Raw = i32; -const EBADF: i32 = 9; - #[repr(transparent)] pub struct Owned { fd: Raw, @@ -153,6 +152,8 @@ pub fn close(_fd: Owned) -> io::Result<()> { Err(ebadf()) } +pub fn closerange(_fd_low: Raw, _fd_high: Raw) {} + pub fn ftruncate(_fd: Borrowed<'_>, _len: Offset) -> io::Result<()> { Err(ebadf()) } diff --git a/crates/host_env/src/crt_fd_wasm.rs b/crates/host_env/src/crt_fd_wasm.rs new file mode 100644 index 00000000000..b4173d0749f --- /dev/null +++ b/crates/host_env/src/crt_fd_wasm.rs @@ -0,0 +1,195 @@ +use alloc::fmt; +use core::marker::PhantomData; +use std::{ffi, io}; + +pub type Offset = i64; +pub type Raw = i32; + +use crate::errno::errors::{EBADF, EINVAL, ENOENT}; +use crate::wasi_p1; + +#[repr(transparent)] +pub struct Owned { + fd: Raw, +} + +impl fmt::Debug for Owned { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("crt_fd::Owned") + .field(&self.as_raw()) + .finish() + } +} + +#[derive(Copy, Clone)] +#[repr(transparent)] +pub struct Borrowed<'fd> { + fd: Raw, + _marker: PhantomData<&'fd Owned>, +} + +impl PartialEq for Borrowed<'_> { + fn eq(&self, other: &Self) -> bool { + self.as_raw() == other.as_raw() + } +} + +impl Eq for Borrowed<'_> {} + +impl fmt::Debug for Borrowed<'_> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("crt_fd::Borrowed") + .field(&self.as_raw()) + .finish() + } +} + +impl Owned { + /// Create a `crt_fd::Owned` from a raw file descriptor. + /// + /// # Safety + /// + /// `fd` must be a valid file descriptor for the embedding host. + #[inline] + pub const unsafe fn from_raw(fd: Raw) -> Self { + Self { fd } + } + + /// Create a `crt_fd::Owned` from a raw file descriptor. + /// + /// Returns an error if `fd` is negative. + /// + /// # Safety + /// + /// `fd` must be a valid file descriptor for the embedding host. + #[inline] + pub unsafe fn try_from_raw(fd: Raw) -> io::Result { + if fd < 0 { + Err(ebadf()) + } else { + Ok(unsafe { Self::from_raw(fd) }) + } + } + + #[inline] + pub const fn borrow(&self) -> Borrowed<'_> { + unsafe { Borrowed::borrow_raw(self.as_raw()) } + } + + #[inline] + pub const fn as_raw(&self) -> Raw { + self.fd + } + + #[inline] + pub fn into_raw(self) -> Raw { + let fd = self.fd; + core::mem::forget(self); + fd + } + + pub fn leak<'fd>(self) -> Borrowed<'fd> { + unsafe { Borrowed::borrow_raw(self.into_raw()) } + } +} + +impl Drop for Owned { + fn drop(&mut self) { + // Close consumes the descriptor even when the import reports an error. + let _ = wasi_p1::close(self.fd); + } +} + +impl Borrowed<'_> { + /// Create a `crt_fd::Borrowed` from a raw file descriptor. + /// + /// # Safety + /// + /// `fd` must be a valid file descriptor for the embedding host. + #[inline] + pub const unsafe fn borrow_raw(fd: Raw) -> Self { + Self { + fd, + _marker: PhantomData, + } + } + + /// Create a `crt_fd::Borrowed` from a raw file descriptor. + /// + /// Returns an error if `fd` is negative. + /// + /// # Safety + /// + /// `fd` must be a valid file descriptor for the embedding host. + #[inline] + pub unsafe fn try_borrow_raw(fd: Raw) -> io::Result { + if fd < 0 { + Err(ebadf()) + } else { + Ok(unsafe { Self::borrow_raw(fd) }) + } + } + + #[inline] + pub const fn as_raw(self) -> Raw { + self.fd + } +} + +#[inline] +fn ebadf() -> io::Error { + io::Error::from_raw_os_error(EBADF) +} + +pub fn open(path: &ffi::CStr, flags: i32, _mode: i32) -> io::Result { + let path = path.to_bytes(); + if path.is_empty() { + return Err(io::Error::from_raw_os_error(ENOENT)); + } + let raw = wasi_p1::path_open_preopen(path, flags)?; + // SAFETY: path_open transferred a newly owned descriptor. + Ok(unsafe { Owned::from_raw(raw) }) +} + +pub fn openat(_dir: Borrowed<'_>, _path: &ffi::CStr, _flags: i32, _mode: i32) -> io::Result { + Err(io::Error::new( + io::ErrorKind::Unsupported, + "host path opening is unsupported by this embedding ABI", + )) +} + +pub fn fsync(fd: Borrowed<'_>) -> io::Result<()> { + wasi_p1::sync(fd.as_raw()) +} + +pub fn close(fd: Owned) -> io::Result<()> { + // Suppress Drop before invoking close: the descriptor is consumed even on error. + wasi_p1::close(fd.into_raw()) +} + +pub fn closerange(fd_low: Raw, fd_high: Raw) { + for fd in fd_low.max(0)..fd_high { + let _ = wasi_p1::close(fd); + } +} + +pub fn ftruncate(fd: Borrowed<'_>, len: Offset) -> io::Result<()> { + if len < 0 { + return Err(io::Error::from_raw_os_error(EINVAL)); + } + wasi_p1::set_size(fd.as_raw(), len) +} + +pub fn write(fd: Borrowed<'_>, buf: &[u8]) -> io::Result { + wasi_p1::write(fd.as_raw(), buf) +} + +pub fn read(fd: Borrowed<'_>, buf: &mut [u8]) -> io::Result { + wasi_p1::read(fd.as_raw(), buf) +} + +impl io::Read for Borrowed<'_> { + fn read(&mut self, buf: &mut [u8]) -> io::Result { + read(*self, buf) + } +} diff --git a/crates/host_env/src/ctypes.rs b/crates/host_env/src/ctypes.rs index b0d15679b1f..51a7a311058 100644 --- a/crates/host_env/src/ctypes.rs +++ b/crates/host_env/src/ctypes.rs @@ -221,6 +221,36 @@ const LONG_DOUBLE_SIZE: usize = core::mem::size_of::(); )))] const LONG_DOUBLE_SIZE: usize = core::mem::size_of::(); +/// Return the loader's current shared-object names, including its empty main entry. +#[cfg(any(target_os = "linux", target_os = "android"))] +pub fn dllist() -> Vec { + use std::os::unix::ffi::OsStringExt; + + unsafe extern "C" fn collect( + info: *mut libc::dl_phdr_info, + _size: libc::size_t, + data: *mut c_void, + ) -> c_int { + // dl_iterate_phdr supplies a valid record and calls synchronously while + // the loader keeps the object and its NUL-terminated name alive. + let name = unsafe { (*info).dlpi_name }; + let names = unsafe { &mut *data.cast::>() }; + if !name.is_null() { + let bytes = unsafe { CStr::from_ptr(name) }.to_bytes().to_vec(); + names.push(std::ffi::OsString::from_vec(bytes)); + } + 0 + } + + let mut names = Vec::new(); + // The callback only copies loader-owned bytes into this live, exclusive + // vector. It never invokes Python or mutates the loader's object list. + unsafe { + libc::dl_iterate_phdr(Some(collect), core::ptr::from_mut(&mut names).cast()); + } + names +} + pub fn simple_type_size(ty: &str) -> Option { match ty { "c" | "b" => Some(core::mem::size_of::()), @@ -578,6 +608,65 @@ pub enum SimpleStorageValue { Zero, } +// An allocation is owned only until published into ctypes storage. Like CPython, +// committed BSTRs are freed by replacement, not by CData destruction: callers +// can transfer them to COM or copy their pointers into other ctypes objects. +#[cfg(windows)] +pub struct BStr { + bytes: [u8; core::mem::size_of::()], + committed: bool, +} + +#[cfg(windows)] +impl BStr { + pub fn new(units: Option<&[u16]>) -> Option { + let address = match units { + Some(units) => crate::windows::sys_alloc_string_len(units)? as usize, + None => 0, + }; + Some(Self { + bytes: address.to_ne_bytes(), + committed: false, + }) + } + + pub fn bytes(&self) -> &[u8] { + &self.bytes + } + + pub fn commit(&mut self) { + self.committed = true; + } + + /// # Safety + /// The old slot must contain NULL or a valid, live COM BSTR. + pub unsafe fn replace(&mut self, previous: &[u8]) { + let address = read_pointer_from_buffer(previous); + crate::windows::sys_free_string(address as *const u16); + self.commit(); + } +} + +#[cfg(windows)] +impl Drop for BStr { + fn drop(&mut self) { + if !self.committed { + crate::windows::sys_free_string(read_pointer_from_buffer(&self.bytes) as *const u16); + } + } +} + +#[cfg(windows)] +unsafe fn decode_bstr(address: usize) -> DecodedValue { + if address == 0 { + return DecodedValue::None; + } + let pointer = address as *const u16; + let len = crate::windows::sys_string_len(pointer); + let units = unsafe { core::slice::from_raw_parts(pointer, len) }; + DecodedValue::WideString(Wtf8Buf::from_wide(units)) +} + pub enum DecodedValue { Bytes(Vec), Signed(i64), @@ -586,6 +675,8 @@ pub enum DecodedValue { Bool(bool), Pointer(usize), String(String), + #[cfg(windows)] + WideString(Wtf8Buf), None, } @@ -783,8 +874,7 @@ pub fn read_array_element( Some("u") => { let value = wchar_from_bytes(rest) .and_then(char::from_u32) - .map(|c| c.to_string()) - .unwrap_or_default(); + .map_or_default(|c| c.to_string()); DecodedValue::String(value) } Some("z") => { @@ -813,6 +903,8 @@ pub fn read_array_element( } } } + #[cfg(windows)] + Some("X") => unsafe { decode_bstr(read_pointer_from_buffer(rest)) }, Some("f") => DecodedValue::Float( rest.first_chunk::<4>() .copied() @@ -1083,7 +1175,7 @@ pub fn simple_storage_value_to_bytes_endian( } _ => vec![0; 2], }, - "P" | "z" | "Z" => match value { + "P" | "z" | "Z" | "X" => match value { SimpleStorageValue::Pointer(value) => { uint_to_sized_bytes_endian(value as u64, pointer_size(), swapped) } @@ -1246,6 +1338,8 @@ pub fn decode_type_code(type_code: &str, bytes: &[u8]) -> DecodedValue { None => DecodedValue::None, } }, + #[cfg(windows)] + "X" => unsafe { decode_bstr(read_pointer_from_buffer(bytes)) }, "P" => DecodedValue::Pointer(read_pointer_from_buffer(bytes)), "u" => { let val = if bytes.len() >= core::mem::size_of::() { @@ -1270,6 +1364,8 @@ pub fn decode_type_code(type_code: &str, bytes: &[u8]) -> DecodedValue { /// `type_code`. pub unsafe fn callback_arg_value(type_code: Option<&str>, ptr: *const c_void) -> DecodedValue { match type_code { + #[cfg(windows)] + Some("X") => unsafe { decode_bstr(core::ptr::read_unaligned(ptr.cast::())) }, Some("b") => DecodedValue::Signed(unsafe { *(ptr as *const i8) as i64 }), Some("B") => DecodedValue::Unsigned(unsafe { *(ptr as *const u8) as u64 }), Some("c") => DecodedValue::Bytes(vec![unsafe { *(ptr as *const u8) }]), @@ -1368,7 +1464,7 @@ pub unsafe fn write_callback_result( (Some("Q"), CallbackResultValue::Unsigned(v)) => unsafe { *(result as *mut u64) = v }, (Some("f"), CallbackResultValue::Float(v)) => unsafe { *(result as *mut f32) = v as f32 }, (Some("d"), CallbackResultValue::Float(v)) => unsafe { *(result as *mut f64) = v }, - (Some("P" | "z" | "Z"), CallbackResultValue::Pointer(v)) => unsafe { + (Some("P" | "z" | "Z" | "X"), CallbackResultValue::Pointer(v)) => unsafe { *(result as *mut usize) = v }, (Some("?"), CallbackResultValue::Bool(v)) => unsafe { *(result as *mut u8) = u8::from(v) }, @@ -1419,7 +1515,7 @@ pub fn ffi_value_from_type_code(type_code: &str, buffer: &[u8]) -> FfiValue { .copied() .map_or(0.0, f64::from_ne_bytes), ), - "z" | "Z" | "P" | "O" => FfiValue::Pointer(read_pointer_from_buffer(buffer)), + "z" | "Z" | "P" | "X" | "O" => FfiValue::Pointer(read_pointer_from_buffer(buffer)), "?" => FfiValue::U8(u8::from(buffer.first().is_some_and(|&b| b != 0))), "u" => FfiValue::U32(buffer.first_chunk().copied().map_or(0, u32::from_ne_bytes)), _ => FfiValue::Pointer(0), @@ -1738,7 +1834,11 @@ pub const HRESULT_S_OK: i32 = crate::windows::HRESULT_S_OK; #[cfg(windows)] pub fn format_error_message(code: Option) -> Option { - crate::windows::format_error_message(code) + let code = code + .filter(|&code| code != 0) + .unwrap_or_else(crate::windows::get_last_error); + crate::windows::format_error_message_with_language(code, 1 << 10) + .map(|message| message.trim_end().to_owned()) } #[cfg(windows)] @@ -1830,6 +1930,12 @@ impl CallbackThunk { } } + /// Borrow the userdata owned by this callback closure. + pub fn userdata(&self) -> &U { + // SAFETY: new stores Box::into_raw here; Drop owns its only reclamation. + unsafe { &*self.userdata_ptr } + } + pub fn code_ptr(&self) -> CodePtr { self.code_ptr } @@ -2011,7 +2117,7 @@ pub enum CallRet<'a> { Aggregate(&'a CTypeLayout), } -/// Per-call error-swapping options. +/// Per-call ABI and error-swapping options. #[cfg(all( any( target_os = "linux", @@ -2023,6 +2129,10 @@ pub enum CallRet<'a> { ))] #[derive(Debug, Clone, Copy, Default)] pub struct CallOptions { + /// Declared argument count for a variadic call. Values must already have + /// their promoted C types; libffi rejects explicit narrow ctypes values. + /// `None` uses a fixed-arity CIF. + pub fixed_arg_count: Option, /// Swap the ctypes-local errno around the raw call (unix; ignored on windows). pub use_errno: bool, /// Swap the ctypes-local last error around the raw call (windows; ignored @@ -2066,6 +2176,9 @@ pub enum CallValue { #[derive(Debug, Clone, PartialEq, Eq)] pub enum CallError { NullFunctionPointer, + InvalidCallInterface { + variadic: bool, + }, UnknownTypeCode(String), /// An aggregate argument's buffer was shorter than its layout size. BufferTooSmall { @@ -2156,7 +2269,13 @@ pub fn call( }) .collect(); - let cif = Cif::new(ffi_arg_types, ffi_return_type); + let cif = match options.fixed_arg_count { + Some(fixed) => Cif::try_new_variadic(ffi_arg_types, fixed, ffi_return_type), + None => Cif::try_new(ffi_arg_types, ffi_return_type), + } + .map_err(|_| CallError::InvalidCallInterface { + variadic: options.fixed_arg_count.is_some(), + })?; // Allocate the aggregate return buffer outside the error-swap window so no // allocation runs between the raw call and the errno/last-error capture. @@ -2480,7 +2599,7 @@ pub unsafe fn read_value_at_address( Some("d" | "g") => { AddressValue::Float(unsafe { core::ptr::read_unaligned(ptr as *const f64) }) } - Some("P" | "z" | "Z") => { + Some("P" | "z" | "Z" | "X") => { AddressValue::Pointer(unsafe { core::ptr::read_unaligned(ptr as *const usize) }) } _ => AddressValue::Bytes(unsafe { bytes_at(ptr, size) }), @@ -2718,7 +2837,6 @@ impl ExternalLibs { let new_lib = SharedLibrary::new(library_path)?; let key = new_lib.get_pointer(); if self.libraries.contains_key(&key) { - drop(new_lib); return Ok(key); } self.libraries.insert(key, new_lib); @@ -2734,7 +2852,6 @@ impl ExternalLibs { let new_lib = SharedLibrary::new_with_mode(library_path, mode)?; let key = new_lib.get_pointer(); if self.libraries.contains_key(&key) { - drop(new_lib); return Ok(key); } self.libraries.insert(key, new_lib); @@ -2809,29 +2926,7 @@ pub fn free_library(module: windows_sys::Win32::Foundation::HMODULE) -> std::io: } #[cfg(windows)] -#[allow(clippy::not_unsafe_ptr_arg_deref)] -pub fn sys_string_len(bstr: *const u16) -> usize { - unsafe { windows_sys::Win32::Foundation::SysStringLen(bstr) as usize } -} - -#[cfg(windows)] -#[allow(clippy::not_unsafe_ptr_arg_deref)] -pub fn sys_free_string(bstr: *const u16) { - unsafe { windows_sys::Win32::Foundation::SysFreeString(bstr) }; -} - -#[cfg(windows)] -pub fn sys_alloc_string_len(units: &[u16]) -> Option<*mut u16> { - let len = u32::try_from(units.len()).ok()?; - let bstr = unsafe { windows_sys::Win32::Foundation::SysAllocStringLen(units.as_ptr(), len) }; - (!bstr.is_null()).then_some(bstr as *mut u16) -} - -#[cfg(windows)] -#[allow(clippy::not_unsafe_ptr_arg_deref)] -pub fn co_task_mem_free(ptr: *mut core::ffi::c_void) { - unsafe { windows_sys::Win32::System::Com::CoTaskMemFree(ptr) }; -} +pub use crate::windows::{co_task_mem_free, sys_alloc_string_len, sys_free_string, sys_string_len}; /// `GetErrorInfo(0)`. `None` when the thread has no error object (`S_FALSE`). #[cfg(windows)] @@ -3016,6 +3111,73 @@ pub fn dlsym_checked(_handle: usize, symbol_name: &CStr) -> Result<*mut c_void, mod tests { use super::*; + #[cfg(all( + any( + target_os = "linux", + target_os = "macos", + target_os = "windows", + target_os = "android" + ), + not(any(target_env = "musl", target_env = "sgx")) + ))] + #[test] + fn bstr_foreign_argument_preserves_pointer() { + let address = usize::MAX; + assert!(matches!( + ffi_value_from_type_code("X", &address.to_ne_bytes()), + FfiValue::Pointer(value) if value == address + )); + } + + #[cfg(windows)] + #[test] + fn bstr_roundtrip_and_replacement() { + // Embedded NUL, a surrogate pair, and an unpaired surrogate must survive. + let units = [0x61, 0, 0xd83d, 0xde00, 0xd800]; + let mut slot = 0usize.to_ne_bytes(); + let mut value = BStr::new(Some(&units)).expect("SysAllocStringLen"); + unsafe { + value.replace(&slot); + } + slot.copy_from_slice(value.bytes()); + drop(value); + match decode_type_code("X", &slot) { + DecodedValue::WideString(value) => { + assert_eq!(value.encode_wide().collect::>(), units) + } + _ => panic!("expected BSTR string"), + } + let mut empty = BStr::new(Some(&[])).expect("empty BSTR"); + unsafe { + empty.replace(&slot); + } + slot.copy_from_slice(empty.bytes()); + drop(empty); + assert!( + matches!(decode_type_code("X", &slot), DecodedValue::WideString(value) if value.is_empty()) + ); + let mut null = BStr::new(None).unwrap(); + unsafe { + null.replace(&slot); + } + slot.copy_from_slice(null.bytes()); + assert!(matches!(decode_type_code("X", &slot), DecodedValue::None)); + } + + #[test] + fn bstr_storage_preserves_pointer_width() { + for address in [0, usize::MAX] { + assert_eq!( + simple_storage_value_to_bytes_endian( + "X", + SimpleStorageValue::Pointer(address), + false, + ), + address.to_ne_bytes(), + ); + } + } + #[test] fn simple_type_is_pointer_classifies_codes() { assert!(simple_type_is_pointer("z")); @@ -3681,6 +3843,7 @@ mod tests { CallOptions { use_errno: true, use_last_error: false, + ..CallOptions::default() }, ) .unwrap(); @@ -3698,3 +3861,157 @@ mod tests { } } } + +/// Owned UTF-16 fields returned by COM's error-information interfaces. +#[cfg(windows)] +#[derive(Default)] +pub struct ComErrorDetails { + pub description: Option>, + pub source: Option>, + pub helpfile: Option>, + pub help_context: u32, + pub progid: Option>, +} + +/// Format a COM error like ctypes' FormatError (retain trailing punctuation). +#[cfg(windows)] +pub fn format_com_error_message(status: i32) -> Option { + crate::windows::format_error_message_with_language(status as u32, 1 << 10) + .map(|message| message.trim_end().to_owned()) +} + +/// Obtain the error information associated with a failed COM method call. +/// +/// The caller must detach its interpreter while this runs: COM methods can +/// call back into Python. No borrowed Python buffers may be held here. +/// +/// # Safety +/// `com_ptr` must identify a live IUnknown-compatible COM interface for the +/// duration of this call. `iid` is the native byte representation of its GUID. +#[cfg(windows)] +pub unsafe fn com_error_details(com_ptr: usize, iid: &[u8; 16]) -> ComErrorDetails { + use windows_sys::core::GUID; + + type QueryInterface = + unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> i32; + type Release = unsafe extern "system" fn(*mut c_void) -> u32; + type SupportsErrorInfo = unsafe extern "system" fn(*mut c_void, *const GUID) -> i32; + type GetGuid = unsafe extern "system" fn(*mut c_void, *mut GUID) -> i32; + type GetString = unsafe extern "system" fn(*mut c_void, *mut *mut u16) -> i32; + type GetContext = unsafe extern "system" fn(*mut c_void, *mut u32) -> i32; + + struct ComRef(*mut c_void); + impl Drop for ComRef { + fn drop(&mut self) { + // SAFETY: ComRef owns one reference on an IUnknown-compatible + // interface, whose third vtable entry is Release. + unsafe { + let release: Release = core::mem::transmute(method(self.0, 2)); + release(self.0); + } + } + } + + unsafe fn method(interface: *mut c_void, index: usize) -> usize { + // SAFETY: the caller provides a live interface and a valid slot for + // that interface's documented COM ABI. + unsafe { *(*(interface as *const *const usize)).add(index) } + } + + unsafe fn string_field(interface: *mut c_void, index: usize) -> Option> { + let mut value = core::ptr::null_mut(); + // SAFETY: IErrorInfo slots 4–6 all return an owned BSTR through an + // initialized output pointer. Free even if the method reports failure. + unsafe { + let get: GetString = core::mem::transmute(method(interface, index)); + get(interface, &mut value); + if value.is_null() { + return None; + } + let units = core::slice::from_raw_parts(value, sys_string_len(value)); + // CPython builds these fields from NUL-terminated wide strings. + let end = units + .iter() + .position(|&unit| unit == 0) + .unwrap_or(units.len()); + let result = units[..end].to_vec(); + sys_free_string(value); + Some(result) + } + } + + let mut details = ComErrorDetails::default(); + if com_ptr == 0 { + return details; + } + // IID_ISupportErrorInfo = {DF0B3D60-548F-101B-8E65-08002B2BD119}. + let support_iid = GUID { + data1: 0xdf0b3d60, + data2: 0x548f, + data3: 0x101b, + data4: [0x8e, 0x65, 0x08, 0x00, 0x2b, 0x2b, 0xd1, 0x19], + }; + // SAFETY: GUID is a 16-byte POD value; the input need not be aligned. + let iid = unsafe { core::ptr::read_unaligned(iid.as_ptr().cast::()) }; + let interface = com_ptr as *mut c_void; + let mut support = core::ptr::null_mut(); + // SAFETY: the live input interface implements IUnknown. A successful + // QueryInterface returns one owned ISupportErrorInfo reference. + let status = unsafe { + let query: QueryInterface = core::mem::transmute(method(interface, 0)); + query(interface, &support_iid, &mut support) + }; + if status < 0 || support.is_null() { + return details; + } + let support = ComRef(support); + // SAFETY: ISupportErrorInfo's fourth slot accepts the requested IID. + let status = unsafe { + let supports: SupportsErrorInfo = core::mem::transmute(method(support.0, 3)); + supports(support.0, &iid) + }; + drop(support); + if status < 0 { + return details; + } + let Some(error_info) = get_error_info() else { + return details; + }; + if error_info.is_null() { + return details; + } + let error_info = ComRef(error_info); + let mut guid = GUID { + data1: 0, + data2: 0, + data3: 0, + data4: [0; 8], + }; + // SAFETY: GetErrorInfo supplied a live IErrorInfo. Its slots have the + // documented signatures, and all output storage is initialized. + let guid_status = unsafe { + details.description = string_field(error_info.0, 5); + let get_guid: GetGuid = core::mem::transmute(method(error_info.0, 3)); + let status = get_guid(error_info.0, &mut guid); + let get_context: GetContext = core::mem::transmute(method(error_info.0, 7)); + get_context(error_info.0, &mut details.help_context); + details.helpfile = string_field(error_info.0, 6); + details.source = string_field(error_info.0, 4); + status + }; + drop(error_info); + if guid_status >= 0 { + // SAFETY: GUID is POD; copy the initialized native representation. + let guid_bytes = + unsafe { core::ptr::read_unaligned((&guid as *const GUID).cast::<[u8; 16]>()) }; + if let Some(progid) = prog_id_from_clsid(&guid_bytes) { + // SAFETY: ProgIDFromCLSID returns a NUL-terminated allocation + // owned by this call and released with CoTaskMemFree. + unsafe { + details.progid = Some(WideCStr::from_ptr_str(progid).as_slice().to_vec()); + co_task_mem_free(progid.cast()); + } + } + } + details +} diff --git a/crates/host_env/src/errno.rs b/crates/host_env/src/errno.rs index e816a04a55f..c0a122ddbcc 100644 --- a/crates/host_env/src/errno.rs +++ b/crates/host_env/src/errno.rs @@ -2,7 +2,7 @@ /// Return the platform `strerror(errno)` message as an owned `String`. /// Returns `None` when the runtime gives no description for `errno`. -#[cfg(any(unix, windows))] +#[cfg(any(unix, windows, target_os = "wasi"))] #[must_use] pub fn strerror_string(errno: i32) -> Option { let ptr = unsafe { libc::strerror(errno) }; diff --git a/crates/host_env/src/errno_wasm.rs b/crates/host_env/src/errno_wasm.rs index a5103ef047c..1bf266cd1b8 100644 --- a/crates/host_env/src/errno_wasm.rs +++ b/crates/host_env/src/errno_wasm.rs @@ -1,7 +1,7 @@ //! Errno numbers for `wasm32-unknown-unknown`. //! -//! There is no libc errno table. The values are the Darwin/BSD numbers the -//! guest `O_*` flags and `OSError` subclasses match against. +//! Use WASI preview1 errno values, matching `wasm32-wasip1`. Native host +//! builds continue to use their platform libc errno table. #[must_use] pub fn strerror_string(errno: i32) -> Option { @@ -9,46 +9,57 @@ pub fn strerror_string(errno: i32) -> Option { } pub mod errors { - pub const EPERM: i32 = 1; - pub const ENOENT: i32 = 2; - pub const ESRCH: i32 = 3; - pub const EINTR: i32 = 4; - pub const EIO: i32 = 5; - pub const EBADF: i32 = 9; - pub const ECHILD: i32 = 10; - pub const EAGAIN: i32 = 35; - pub const EWOULDBLOCK: i32 = 35; - pub const EINPROGRESS: i32 = 36; - pub const EALREADY: i32 = 37; - pub const EPIPE: i32 = 32; - pub const ENOTDIR: i32 = 20; - pub const EISDIR: i32 = 21; - pub const EINVAL: i32 = 22; - pub const EMFILE: i32 = 24; - pub const ESPIPE: i32 = 29; - pub const EROFS: i32 = 30; - pub const EACCES: i32 = 13; - pub const EEXIST: i32 = 17; - pub const ENOTSUP: i32 = 45; - pub const EAFNOSUPPORT: i32 = 47; - pub const ECONNABORTED: i32 = 53; - pub const ECONNRESET: i32 = 54; - pub const ESHUTDOWN: i32 = 58; - pub const ETIMEDOUT: i32 = 60; - pub const ECONNREFUSED: i32 = 61; + pub const EPERM: i32 = 63; + pub const ENOENT: i32 = 44; + pub const ESRCH: i32 = 71; + pub const EINTR: i32 = 27; + pub const EIO: i32 = 29; + pub const EBADF: i32 = 8; + pub const ECHILD: i32 = 12; + pub const EACCES: i32 = 2; + pub const EEXIST: i32 = 20; + pub const ENOTDIR: i32 = 54; + pub const EISDIR: i32 = 31; + pub const EINVAL: i32 = 28; + pub const EMFILE: i32 = 33; + pub const EFBIG: i32 = 22; + pub const ENOSPC: i32 = 51; + pub const ESPIPE: i32 = 70; + pub const EROFS: i32 = 69; + pub const EPIPE: i32 = 64; + pub const EAGAIN: i32 = 6; + pub const EWOULDBLOCK: i32 = 6; + pub const EINPROGRESS: i32 = 26; + pub const EALREADY: i32 = 7; + pub const ENOTSUP: i32 = 58; + pub const EAFNOSUPPORT: i32 = 5; + pub const ECONNABORTED: i32 = 13; + pub const ECONNRESET: i32 = 15; + pub const ETIMEDOUT: i32 = 73; + pub const ECONNREFUSED: i32 = 14; + pub const ENAMETOOLONG: i32 = 37; + pub const EOVERFLOW: i32 = 61; + pub const ENOTCAPABLE: i32 = 76; pub fn strerror(errno: i32) -> Option<&'static str> { Some(match errno { EPERM => "Operation not permitted", ENOENT => "No such file or directory", ESRCH => "No such process", - EIO => "Input/output error", EINTR => "Interrupted system call", + EIO => "Input/output error", + EBADF => "Bad file descriptor", ECHILD => "No child processes", EACCES => "Permission denied", EEXIST => "File exists", ENOTDIR => "Not a directory", EISDIR => "Is a directory", + EINVAL => "Invalid argument", + EMFILE => "Too many open files", + EFBIG => "File too large", + ENOSPC => "No space left on device", + ESPIPE => "Illegal seek", + EROFS => "Read-only file system", EPIPE => "Broken pipe", EAGAIN => "Resource temporarily unavailable", EINPROGRESS => "Operation now in progress", @@ -59,12 +70,9 @@ pub mod errors { ECONNRESET => "Connection reset by peer", ETIMEDOUT => "Operation timed out", ECONNREFUSED => "Connection refused", - EBADF => "Bad file descriptor", - EINVAL => "Invalid argument", - EMFILE => "Too many open files", - ESPIPE => "Illegal seek", - EROFS => "Read-only file system", - ESHUTDOWN => "Can't send after socket shutdown", + ENAMETOOLONG => "File name too long", + EOVERFLOW => "Value too large to be stored in data type", + ENOTCAPABLE => "Capabilities insufficient", _ => return None, }) } @@ -75,9 +83,9 @@ mod tests { use super::errors; #[test] - fn eagain_is_darwin() { - assert_eq!(errors::EAGAIN, 35); - assert_eq!(errors::EWOULDBLOCK, 35); + fn eagain_is_wasi() { + assert_eq!(errors::EAGAIN, 6); + assert_eq!(errors::EWOULDBLOCK, 6); assert_eq!( errors::strerror(errors::EAGAIN), Some("Resource temporarily unavailable") diff --git a/crates/host_env/src/faulthandler.rs b/crates/host_env/src/faulthandler.rs index 80c5838522d..99ff12853f9 100644 --- a/crates/host_env/src/faulthandler.rs +++ b/crates/host_env/src/faulthandler.rs @@ -8,6 +8,9 @@ )] #![allow(static_mut_refs)] +mod c_stack; +pub use c_stack::dump_c_stack; + #[cfg(unix)] use alloc::vec::Vec; #[cfg(unix)] @@ -127,6 +130,92 @@ impl Default for RegisteredUserSignal { #[cfg(unix)] static USER_SIGNALS: Mutex>> = Mutex::new(None); +// Signal handlers cannot take USER_SIGNALS: delivery may interrupt a thread +// holding that mutex. Publish only the copyable dump configuration separately. +// Keep the original descriptor number (not a dup), including its dup2 behavior. +// Previous dispositions and chaining remain in the existing bookkeeping path; +// this does not make concurrent chain/unregister signal-safe. +#[cfg(all(unix, target_has_atomic = "64"))] +mod user_signal_config { + use super::{USER_SIGNAL_CAPACITY, UserSignal}; + use core::sync::atomic::{AtomicU64, Ordering}; + + const ENABLED: u64 = 1 << 32; + const ALL_THREADS: u64 = 1 << 33; + const CHAIN: u64 = 1 << 34; + static SLOTS: [AtomicU64; USER_SIGNAL_CAPACITY] = + [const { AtomicU64::new(0) }; USER_SIGNAL_CAPACITY]; + + fn encode(signal: UserSignal) -> u64 { + u64::from(signal.fd as u32) + | ENABLED + | if signal.all_threads { ALL_THREADS } else { 0 } + | if signal.chain { CHAIN } else { 0 } + } + + fn decode(value: u64) -> Option { + (value & ENABLED != 0).then_some(UserSignal { + fd: value as u32 as i32, + all_threads: value & ALL_THREADS != 0, + chain: value & CHAIN != 0, + }) + } + + pub(super) fn store(signum: usize, signal: Option) { + SLOTS[signum].store(signal.map_or(0, encode), Ordering::SeqCst); + } + + pub(super) fn load(signum: usize) -> Option { + decode(SLOTS.get(signum)?.load(Ordering::SeqCst)) + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn configuration_preserves_descriptor_bits_and_flags() { + for fd in [0, 1, i32::MAX, i32::MIN, -1] { + for all_threads in [false, true] { + for chain in [false, true] { + let actual = decode(encode(UserSignal { + fd, + all_threads, + chain, + })) + .unwrap(); + assert_eq!(actual.fd, fd); + assert_eq!(actual.all_threads, all_threads); + assert_eq!(actual.chain, chain); + } + } + } + assert!(decode(0).is_none()); + } + + #[test] + fn reading_configuration_does_not_lock_registration_bookkeeping() { + // Slot zero is never a valid registration. Model a signal interrupting + // the writer, without installing a process-global test disposition. + let _writer = super::super::USER_SIGNALS.lock(); + store( + 0, + Some(UserSignal { + fd: 17, + all_threads: true, + chain: false, + }), + ); + let actual = super::super::get_user_signal(0).unwrap(); + store(0, None); + assert_eq!(actual.fd, 17); + assert!(actual.all_threads); + assert!(!actual.chain); + assert!(super::super::get_user_signal(USER_SIGNAL_CAPACITY).is_none()); + } + } +} + pub fn write_fd(fd: i32, buf: &[u8]) { let _ = unsafe { libc::write(fd, buf.as_ptr() as *const libc::c_void, buf.len() as _) }; } @@ -259,7 +348,14 @@ pub fn exit_immediately(code: libc::c_int) -> ! { unsafe { libc::_exit(code) } } -#[cfg(unix)] +#[cfg(all(unix, target_has_atomic = "64"))] +pub fn get_user_signal(signum: usize) -> Option { + user_signal_config::load(signum) +} + +// Preserve the existing implementation on targets without lock-free 64-bit +// atomics. Its signal-context mutex limitation is not fixed by this change. +#[cfg(all(unix, not(target_has_atomic = "64")))] pub fn get_user_signal(signum: usize) -> Option { let guard = USER_SIGNALS.lock(); guard @@ -316,6 +412,15 @@ pub fn register_user_signal( entry.fd = fd; entry.all_threads = all_threads; entry.chain = chain; + #[cfg(target_has_atomic = "64")] + user_signal_config::store( + signum, + Some(UserSignal { + fd, + all_threads, + chain, + }), + ); Ok(()) } @@ -337,6 +442,8 @@ pub fn unregister_user_signal(signum: libc::c_int) -> bool { } let previous = entry.previous; + #[cfg(target_has_atomic = "64")] + user_signal_config::store(signum, None); *entry = RegisteredUserSignal::default(); restore_sigaction(signum as libc::c_int, &previous); true diff --git a/crates/host_env/src/faulthandler/c_stack.rs b/crates/host_env/src/faulthandler/c_stack.rs new file mode 100644 index 00000000000..16d40cefe41 --- /dev/null +++ b/crates/host_env/src/faulthandler/c_stack.rs @@ -0,0 +1,195 @@ +use core::fmt::{self, Write}; + +struct Output(i32); + +impl Output { + fn bytes(&mut self, bytes: &[u8]) { + // Like CPython's diagnostic writes, output errors are best effort. + let _ = crate::crt_fd::write_noraise(self.0, bytes); + } +} + +impl Write for Output { + fn write_str(&mut self, text: &str) -> fmt::Result { + self.bytes(text.as_bytes()); + Ok(()) + } +} + +/// Dump the calling thread's native stack to a borrowed file descriptor. +/// +/// This is only for normal execution, never a signal or exception handler: +/// unwinding and loader lookup may allocate or acquire internal locks. The +/// descriptor remains owned by the caller and must stay open during this call. +pub fn dump_c_stack(fd: i32) { + let mut output = Output(fd); + output.bytes(b"Current thread's C stack trace (most recent call first):\n"); + #[cfg(all(target_os = "linux", target_env = "gnu"))] + native::dump(&mut output); + #[cfg(not(all(target_os = "linux", target_env = "gnu")))] + output.bytes(b" \n"); +} + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +mod native { + use super::Output; + use alloc::vec::Vec; + use core::{ffi::CStr, fmt::Write, ptr}; + use std::{os::unix::ffi::OsStrExt, path::PathBuf}; + + const BACKTRACE_SIZE: usize = 32; + + #[derive(Default)] + struct Frame { + bias: Option, + filename: Vec, + copy_failed: bool, + } + + struct Frames { + addresses: [*mut libc::c_void; BACKTRACE_SIZE], + details: [Frame; BACKTRACE_SIZE], + executable: Option, + count: usize, + } + + // ELF addresses have the target's pointer width. Use a wider intermediate + // and checked conversion so malformed or overflowing ranges are ignored. + fn load_range( + bias: impl Into, + address: impl Into, + size: impl Into, + ) -> Option<(usize, usize)> { + let start = bias.into().checked_add(address.into())?; + let end = start.checked_add(size.into())?; + Some((usize::try_from(start).ok()?, usize::try_from(end).ok()?)) + } + + unsafe extern "C" fn collect_frames( + info: *mut libc::dl_phdr_info, + _size: libc::size_t, + data: *mut libc::c_void, + ) -> libc::c_int { + // dl_iterate_phdr invokes this synchronously while the GNU loader keeps + // these records, headers, and names alive. data is the caller's exclusive + // live Frames. Only owned filename bytes escape this callback. + let info = unsafe { &*info }; + let frames = unsafe { &mut *data.cast::() }; + if info.dlpi_phdr.is_null() { + return 0; + } + let filename = if info.dlpi_name.is_null() { + &[][..] + } else { + unsafe { CStr::from_ptr(info.dlpi_name) }.to_bytes() + }; + // The main executable has an empty loader name. Resolve its actual path + // before taking the loader lock, rather than doing filesystem I/O here. + let filename = if filename.is_empty() { + frames + .executable + .as_ref() + .map_or(&[][..], |path| path.as_os_str().as_bytes()) + } else { + filename + }; + // libc selects Elf32_Addr or Elf64_Addr to match the pointer width. + let bias = info.dlpi_addr as usize; + // The loader supplies exactly dlpi_phnum initialized program headers. + let headers = + unsafe { core::slice::from_raw_parts(info.dlpi_phdr, usize::from(info.dlpi_phnum)) }; + for header in headers { + if header.p_type != libc::PT_LOAD { + continue; + } + let Some((start, end)) = load_range(info.dlpi_addr, header.p_vaddr, header.p_memsz) + else { + continue; + }; + for (address, frame) in frames + .addresses + .iter() + .zip(frames.details.iter_mut()) + .take(frames.count) + { + let address = *address as usize; + if frame.bias.is_some() || address < start || address >= end { + continue; + } + frame.bias = Some(bias); + // Allocation failure is recorded, not unwound through the C + // callback. After reservation, copying bytes cannot allocate. + if frame.filename.try_reserve_exact(filename.len()).is_err() { + frame.copy_failed = true; + } else { + frame.filename.extend_from_slice(filename); + } + } + } + 0 + } + + fn write_frame(output: &mut Output, address: usize, frame: &Frame) { + if frame.copy_failed { + let _ = writeln!(output, " [{address:#x}]"); + return; + } + if frame.filename.is_empty() { + let _ = writeln!(output, " Binary file '' [{address:#x}]"); + return; + } + output.bytes(b" Binary file \""); + output.bytes(&frame.filename); + output.bytes(b"\""); + // A zero ELF load bias (e.g. non-PIE executable) uses CPython's + // filename/address-only form. Do not substitute a mapping address. + if let Some(base) = frame.bias.filter(|&bias| bias != 0) { + let (sign, offset) = if address >= base { + ('+', address - base) + } else { + ('-', base - address) + }; + let _ = write!(output, ", at {sign}{offset:#x}"); + } + let _ = writeln!(output, " [{address:#x}]"); + } + + pub(super) fn dump(output: &mut Output) { + let mut frames = Frames { + addresses: [ptr::null_mut(); BACKTRACE_SIZE], + details: core::array::from_fn(|_| Frame::default()), + executable: std::env::current_exe().ok(), + count: 0, + }; + // The buffer has room for the exact number of pointers passed to libc. + let count = unsafe { + libc::backtrace(frames.addresses.as_mut_ptr(), BACKTRACE_SIZE as libc::c_int) + }; + frames.count = count.clamp(0, BACKTRACE_SIZE as libc::c_int) as usize; + if frames.count == 0 { + output.bytes(b" \n"); + return; + } + // Callback state lives until this synchronous traversal returns. The + // callback performs only checked collection and fallible byte copies, + // never output or Python calls while the loader lock is held. + // Do not call dladdr here: its returned strings can be invalidated by + // dlclose after it returns, and nesting it inside dl_iterate_phdr would + // invert glibc's dl_load_lock/dl_load_write_lock order. Report genuine + // object-relative offsets without optional symbol names instead. + unsafe { + libc::dl_iterate_phdr(Some(collect_frames), ptr::from_mut(&mut frames).cast()); + } + for (address, frame) in frames + .addresses + .iter() + .zip(frames.details.iter()) + .take(frames.count) + { + write_frame(output, *address as usize, frame); + } + if frames.count == BACKTRACE_SIZE { + output.bytes(b" \n"); + } + } +} diff --git a/crates/host_env/src/fcntl.rs b/crates/host_env/src/fcntl.rs index 1839d344d08..7c5b58930f4 100644 --- a/crates/host_env/src/fcntl.rs +++ b/crates/host_env/src/fcntl.rs @@ -3,6 +3,9 @@ use std::io; #[cfg(unix)] use std::os::fd::BorrowedFd; +#[cfg(not(target_os = "wasi"))] +use rustix::fs::{self, FlockOperation}; + use crate::os::CheckLibcResult; pub use libc::{F_GETFD, F_GETFL, F_SETFD, F_SETFL, FD_CLOEXEC}; @@ -19,10 +22,13 @@ pub use libc::{F_GETFD, F_GETFL, F_SETFD, F_SETFL, FD_CLOEXEC}; pub use libc::{F_LOCK, F_TEST, F_TLOCK, F_ULOCK}; #[cfg(not(target_os = "wasi"))] -pub use libc::{F_DUPFD, F_DUPFD_CLOEXEC, F_GETLK, F_SETLK, F_SETLKW}; +pub use libc::{ + F_DUPFD, F_DUPFD_CLOEXEC, F_GETLK, F_RDLCK, F_SETLK, F_SETLKW, F_UNLCK, F_WRLCK, LOCK_EX, + LOCK_NB, LOCK_SH, LOCK_UN, +}; #[cfg(not(any(target_os = "wasi", target_os = "redox")))] -pub use libc::{F_GETOWN, F_RDLCK, F_SETOWN, F_UNLCK, F_WRLCK, LOCK_EX, LOCK_NB, LOCK_SH, LOCK_UN}; +pub use libc::{F_GETOWN, F_SETOWN}; #[cfg(target_vendor = "apple")] pub use libc::{F_FULLFSYNC, F_NOCACHE}; @@ -61,9 +67,8 @@ pub use libc::{ #[cfg(any(target_os = "dragonfly", target_os = "netbsd", target_vendor = "apple"))] pub use libc::F_GETPATH; -pub fn normalize_ioctl_request(request: i64) -> libc::c_ulong { - (request as u32) as libc::c_ulong -} +#[cfg(target_os = "linux")] +pub use libc::{FICLONE, FICLONERANGE}; pub fn fcntl_int(fd: i32, cmd: i32, arg: i32) -> io::Result { unsafe { libc::fcntl(fd, cmd, arg) }.check_libc_neg() @@ -128,19 +133,46 @@ pub fn ioctl_int(fd: i32, request: libc::c_ulong, arg: i32) -> io::Result { unsafe { libc::ioctl(fd, request as _, arg) }.check_libc_neg() } -#[cfg(not(any(target_os = "wasi", target_os = "redox")))] -pub fn flock(fd: i32, operation: i32) -> io::Result { - unsafe { libc::flock(fd, operation) }.check_libc_neg() +#[cfg(not(target_os = "wasi"))] +pub fn flock(fd: &BorrowedFd<'_>, operation: i32) -> io::Result<()> { + let operation = match operation { + libc::LOCK_SH => FlockOperation::LockShared, + libc::LOCK_EX => FlockOperation::LockExclusive, + libc::LOCK_UN => FlockOperation::Unlock, + f if f == (libc::LOCK_SH | libc::LOCK_NB) => FlockOperation::NonBlockingLockShared, + f if f == (libc::LOCK_EX | libc::LOCK_NB) => FlockOperation::NonBlockingLockExclusive, + f if f == (libc::LOCK_UN | libc::LOCK_NB) => FlockOperation::NonBlockingUnlock, + _ => return Err(std::io::Error::from_raw_os_error(libc::EINVAL)), + }; + + fs::flock(fd, operation).map_err(Into::into) } -#[cfg(not(any(target_os = "wasi", target_os = "redox")))] +#[cfg(not(target_os = "wasi"))] pub enum LockfError { InvalidCmd, Overflow(String), Io(io::Error), } -#[cfg(not(any(target_os = "wasi", target_os = "redox")))] +#[cfg(not(target_os = "wasi"))] +pub fn lockf_type(cmd: i32) -> Result { + let l_type = if cmd == libc::LOCK_UN { + libc::F_UNLCK + } else if (cmd & libc::LOCK_SH) != 0 { + libc::F_RDLCK + } else if (cmd & libc::LOCK_EX) != 0 { + libc::F_WRLCK + } else { + return Err(LockfError::InvalidCmd); + }; + + // Lock constants are c_short on BSD-family targets and c_int on Linux. + #[allow(clippy::unnecessary_cast)] + Ok(l_type as libc::c_int) +} + +#[cfg(not(target_os = "wasi"))] pub fn lockf(fd: i32, cmd: i32, len: i64, start: i64, whence: i32) -> Result { fn convert_field(value: T) -> Result where @@ -152,19 +184,11 @@ pub fn lockf(fd: i32, cmd: i32, len: i64, start: i64, whence: i32) -> Result String { + match self { + Self::Invalid => format!("invalid mode: {mode_str}"), + Self::BadRwa => { + "Must have exactly one of create/read/write/append mode and at most one plus" + .to_owned() + } + } + } +} + +#[derive(Clone, Copy, Debug)] +pub struct ParsedFileMode { + pub mode: FileMode, + pub flags: i32, +} + +impl FileMode { + pub const fn raw_mode(self) -> &'static str { + if self.contains(&FileModeFlag::Created) { + if self.contains(&FileModeFlag::Readable) { + "xb+" + } else { + "xb" + } + } else if self.contains(&FileModeFlag::Appending) { + if self.contains(&FileModeFlag::Readable) { + "ab+" + } else { + "ab" + } + } else if self.contains(&FileModeFlag::Readable) { + if self.contains(&FileModeFlag::Writable) { + if self.contains(&FileModeFlag::Truncating) { + "wb+" + } else { + "rb+" + } + } else { + "rb" + } + } else { + "wb" + } + } +} + +pub fn parse_fileio_mode( + mode_str: &str, + mut mode: FileMode, +) -> Result { + let mut flags = 0; + let mut plus = false; + let mut rwa = false; + for c in mode_str.bytes() { + match c { + b'x' => { + if rwa { + return Err(FileModeError::BadRwa); + } + rwa = true; + mode |= FileMode::WRITABLE | FileMode::CREATED; + flags |= crate::os::O_EXCL | crate::os::O_CREAT; + } + b'r' => { + if rwa { + return Err(FileModeError::BadRwa); + } + rwa = true; + mode |= FileMode::READABLE; + } + b'w' => { + if rwa { + return Err(FileModeError::BadRwa); + } + rwa = true; + mode |= FileMode::WRITABLE | FileMode::TRUNCATING; + flags |= crate::os::O_CREAT | crate::os::O_TRUNC; + } + b'a' => { + if rwa { + return Err(FileModeError::BadRwa); + } + rwa = true; + mode |= FileMode::WRITABLE | FileMode::APPENDING; + flags |= crate::os::O_APPEND | crate::os::O_CREAT; + } + b'+' => { + if plus { + return Err(FileModeError::BadRwa); + } + plus = true; + mode |= FileMode::READABLE | FileMode::WRITABLE; + } + b'b' => {} + _ => return Err(FileModeError::Invalid), + } + } + + if !rwa { + return Err(FileModeError::BadRwa); + } + + if mode.is_superset(&(FileMode::READABLE | FileMode::WRITABLE)) { + flags |= crate::os::O_RDWR; + } else if mode.contains(&FileModeFlag::Readable) { + flags |= crate::os::O_RDONLY; + } else { + flags |= crate::os::O_WRONLY; + } + + #[cfg(windows)] + { + flags |= crate::os::O_BINARY | crate::os::O_NOINHERIT; + } + #[cfg(unix)] + { + flags |= crate::os::O_CLOEXEC; + } + + Ok(ParsedFileMode { mode, flags }) +} diff --git a/crates/host_env/src/fileutils.rs b/crates/host_env/src/fileutils.rs index 8db9af89501..a2341aae620 100644 --- a/crates/host_env/src/fileutils.rs +++ b/crates/host_env/src/fileutils.rs @@ -3,6 +3,32 @@ use alloc::ffi::CString; +/// Check a raw descriptor without borrowing it or taking ownership. +/// This is only a point-in-time check: another thread can close it afterwards. +pub fn is_valid_fd(fd: i32) -> bool { + if fd < 0 { + return false; + } + cfg_select! { + any(target_os = "linux", target_os = "android", target_vendor = "apple") => { + crate::fcntl::validate_fd(fd).is_ok() + } + windows => { + use windows_sys::Win32::Foundation::INVALID_HANDLE_VALUE; + use windows_sys::Win32::Storage::FileSystem::{FILE_TYPE_UNKNOWN, GetFileType}; + + let handle = crate::nt::handle_from_fd(fd); + handle != INVALID_HANDLE_VALUE + && unsafe { GetFileType(handle) } != FILE_TYPE_UNKNOWN + } + _ => { + let mut stat = core::mem::MaybeUninit::::uninit(); + // fstat validates the raw descriptor; no Rust fd lifetime is claimed. + unsafe { libc::fstat(fd, stat.as_mut_ptr()) == 0 } + } + } +} + #[cfg(not(windows))] pub use rustix::fs::Stat as StatStruct; @@ -11,6 +37,10 @@ pub use windows::{StatStruct, fstat}; #[cfg(not(windows))] pub fn fstat(fd: crate::crt_fd::Borrowed<'_>) -> std::io::Result { + // Unlike a directory fd, fstat accepts no negative descriptor sentinels. + if fd.as_raw() < 0 { + return Err(std::io::Error::from_raw_os_error(libc::EBADF)); + } rustix::fs::fstat(fd).map_err(Into::into) } @@ -20,7 +50,6 @@ pub mod windows { use libc::{S_IFCHR, S_IFDIR, S_IFMT}; use std::ffi::OsStr; use std::os::windows::io::AsRawHandle; - use std::path::Path; use std::sync::OnceLock; use windows_sys::Win32::Foundation::{ ERROR_INVALID_HANDLE, ERROR_NOT_SUPPORTED, FILETIME, FreeLibrary, SetLastError, @@ -51,13 +80,13 @@ pub mod windows { pub st_gid: i32, pub st_rdev: libc::c_ulong, pub st_size: u64, - pub st_atime: libc::time_t, + pub st_atime: crate::time::TimeT, pub st_atime_nsec: i32, - pub st_mtime: libc::time_t, + pub st_mtime: crate::time::TimeT, pub st_mtime_nsec: i32, - pub st_ctime: libc::time_t, + pub st_ctime: crate::time::TimeT, pub st_ctime_nsec: i32, - pub st_birthtime: libc::time_t, + pub st_birthtime: crate::time::TimeT, pub st_birthtime_nsec: i32, pub st_file_attributes: libc::c_ulong, pub st_reparse_tag: u32, @@ -67,13 +96,21 @@ pub mod windows { impl StatStruct { // update_st_mode_from_path in cpython pub fn update_st_mode_from_path(&mut self, path: &OsStr, attr: u32) { - if attr & FILE_ATTRIBUTE_DIRECTORY == 0 - && let Some(file_extension) = - Path::new(path).extension().and_then(|ext| ext.to_str()) - && (file_extension.eq_ignore_ascii_case("exe") - || file_extension.eq_ignore_ascii_case("bat") - || file_extension.eq_ignore_ascii_case("cmd") - || file_extension.eq_ignore_ascii_case("com")) + if attr & FILE_ATTRIBUTE_DIRECTORY != 0 { + return; + } + // The prefix and suffix are ASCII, so inspecting the encoded bytes also + // supports paths containing unpaired surrogates without allocation. + let mut path = path.as_encoded_bytes(); + if !path.starts_with(br"\\?\") { + while matches!(path.last(), Some(b'.' | b' ')) { + path = &path[..path.len() - 1]; + } + } + if let Some(extension) = path.get(path.len().saturating_sub(4)..) + && [b".exe", b".bat", b".cmd", b".com"] + .iter() + .any(|suffix| extension.eq_ignore_ascii_case(*suffix)) { self.st_mode |= 0o111; } @@ -151,13 +188,13 @@ pub mod windows { )) } - fn large_integer_to_time_t_nsec(input: i64) -> (libc::time_t, libc::c_int) { + fn large_integer_to_time_t_nsec(input: i64) -> (crate::time::TimeT, libc::c_int) { let nsec_out = (input % 10_000_000) * 100; // FILETIME is in units of 100 nsec. - let time_out = ((input / 10_000_000) - SECS_BETWEEN_EPOCHS) as libc::time_t; + let time_out = (input / 10_000_000) - SECS_BETWEEN_EPOCHS; (time_out, nsec_out as _) } - fn file_time_to_time_t_nsec(in_ptr: FILETIME) -> (libc::time_t, libc::c_int) { + fn file_time_to_time_t_nsec(in_ptr: FILETIME) -> (crate::time::TimeT, libc::c_int) { let in_val: i64 = unsafe { core::mem::transmute_copy(&in_ptr) }; let nsec_out = (in_val % 10_000_000) * 100; // FILETIME is in units of 100 nsec. let time_out = (in_val / 10_000_000) - SECS_BETWEEN_EPOCHS; diff --git a/crates/host_env/src/fs.rs b/crates/host_env/src/fs.rs index d6516c76374..498ffbf6896 100644 --- a/crates/host_env/src/fs.rs +++ b/crates/host_env/src/fs.rs @@ -11,6 +11,10 @@ pub fn open(path: impl AsRef) -> io::Result { File::open(path) } +pub fn create(path: impl AsRef) -> io::Result { + File::create(path) +} + pub fn read(path: impl AsRef) -> io::Result> { fs::read(path) } diff --git a/crates/host_env/src/io.rs b/crates/host_env/src/io.rs index 134e99df14d..618bc5e90f8 100644 --- a/crates/host_env/src/io.rs +++ b/crates/host_env/src/io.rs @@ -9,152 +9,9 @@ use rustix::{fs::FileType, io::Errno}; use crate::fileutils; use crate::{crt_fd, os}; -bitflagset::bitflag! { - #[derive(Copy, Clone, Debug, PartialEq, Eq)] - #[repr(u8)] - pub enum FileModeFlag { - Created = 0, - Readable = 1, - Writable = 2, - Appending = 3, - } -} - -bitflagset::bitflagset! { - #[derive(Copy, Clone, PartialEq, Eq)] - pub struct FileMode(u8): FileModeFlag -} - -impl FileMode { - pub const CREATED: Self = Self::from_element(FileModeFlag::Created); - pub const READABLE: Self = Self::from_element(FileModeFlag::Readable); - pub const WRITABLE: Self = Self::from_element(FileModeFlag::Writable); - pub const APPENDING: Self = Self::from_element(FileModeFlag::Appending); -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum FileModeError { - Invalid, - BadRwa, -} - -impl FileModeError { - pub fn error_msg(self, mode_str: &str) -> String { - match self { - Self::Invalid => format!("invalid mode: {mode_str}"), - Self::BadRwa => { - "Must have exactly one of create/read/write/append mode and at most one plus" - .to_owned() - } - } - } -} - -#[derive(Clone, Copy, Debug)] -pub struct ParsedFileMode { - pub mode: FileMode, - pub flags: i32, -} - -impl FileMode { - pub const fn raw_mode(self) -> &'static str { - if self.contains(&FileModeFlag::Created) { - if self.contains(&FileModeFlag::Readable) { - "xb+" - } else { - "xb" - } - } else if self.contains(&FileModeFlag::Appending) { - if self.contains(&FileModeFlag::Readable) { - "ab+" - } else { - "ab" - } - } else if self.contains(&FileModeFlag::Readable) { - if self.contains(&FileModeFlag::Writable) { - "rb+" - } else { - "rb" - } - } else { - "wb" - } - } -} - -pub fn parse_fileio_mode(mode_str: &str) -> Result { - let mut flags = 0; - let mut plus = false; - let mut rwa = false; - let mut mode = FileMode::empty(); - for c in mode_str.bytes() { - match c { - b'x' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::WRITABLE | FileMode::CREATED; - flags |= os::O_EXCL | os::O_CREAT; - } - b'r' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::READABLE; - } - b'w' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::WRITABLE; - flags |= os::O_CREAT | os::O_TRUNC; - } - b'a' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::WRITABLE | FileMode::APPENDING; - flags |= os::O_APPEND | os::O_CREAT; - } - b'+' => { - if plus { - return Err(FileModeError::BadRwa); - } - plus = true; - mode |= FileMode::READABLE | FileMode::WRITABLE; - } - b'b' => {} - _ => return Err(FileModeError::Invalid), - } - } - - if !rwa { - return Err(FileModeError::BadRwa); - } - - if mode.is_superset(&(FileMode::READABLE | FileMode::WRITABLE)) { - flags |= os::O_RDWR; - } else if mode.contains(&FileModeFlag::Readable) { - flags |= os::O_RDONLY; - } else { - flags |= os::O_WRONLY; - } - - #[cfg(windows)] - { - flags |= os::O_BINARY | os::O_NOINHERIT; - } - #[cfg(unix)] - { - flags |= os::O_CLOEXEC; - } - - Ok(ParsedFileMode { mode, flags }) -} +pub use crate::file_mode::{ + FileMode, FileModeError, FileModeFlag, ParsedFileMode, parse_fileio_mode, +}; #[derive(Clone, Copy, Debug)] pub struct FileTargetInfo { diff --git a/crates/host_env/src/io_unsupported.rs b/crates/host_env/src/io_unsupported.rs index a779d6f19d1..dde3279dbe3 100644 --- a/crates/host_env/src/io_unsupported.rs +++ b/crates/host_env/src/io_unsupported.rs @@ -3,151 +3,10 @@ use std::io; use crate::crt_fd; use crate::errno::errors::{EAGAIN, EBADF, EINTR, EISDIR}; -use crate::os::{O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY}; -bitflagset::bitflag! { - #[derive(Copy, Clone, Debug, PartialEq, Eq)] - #[repr(u8)] - pub enum FileModeFlag { - Created = 0, - Readable = 1, - Writable = 2, - Appending = 3, - } -} - -bitflagset::bitflagset! { - #[derive(Copy, Clone, PartialEq, Eq)] - pub struct FileMode(u8): FileModeFlag -} - -impl FileMode { - pub const CREATED: Self = Self::from_element(FileModeFlag::Created); - pub const READABLE: Self = Self::from_element(FileModeFlag::Readable); - pub const WRITABLE: Self = Self::from_element(FileModeFlag::Writable); - pub const APPENDING: Self = Self::from_element(FileModeFlag::Appending); -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum FileModeError { - Invalid, - BadRwa, -} - -impl FileModeError { - pub fn error_msg(self, mode_str: &str) -> String { - match self { - Self::Invalid => format!("invalid mode: {mode_str}"), - Self::BadRwa => { - "Must have exactly one of create/read/write/append mode and at most one plus" - .to_owned() - } - } - } -} - -#[derive(Clone, Copy, Debug)] -pub struct ParsedFileMode { - pub mode: FileMode, - pub flags: i32, -} - -impl FileMode { - pub const fn raw_mode(self) -> &'static str { - if self.contains(&FileModeFlag::Created) { - if self.contains(&FileModeFlag::Readable) { - "xb+" - } else { - "xb" - } - } else if self.contains(&FileModeFlag::Appending) { - if self.contains(&FileModeFlag::Readable) { - "ab+" - } else { - "ab" - } - } else if self.contains(&FileModeFlag::Readable) { - if self.contains(&FileModeFlag::Writable) { - "rb+" - } else { - "rb" - } - } else { - "wb" - } - } -} - -pub fn parse_fileio_mode(mode_str: &str) -> Result { - let mut flags = 0; - let mut plus = false; - let mut binary = false; - let mut rwa = false; - let mut mode = FileMode::empty(); - for c in mode_str.bytes() { - match c { - b'x' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::WRITABLE | FileMode::CREATED; - flags |= O_EXCL | O_CREAT; - } - b'r' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::READABLE; - } - b'w' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::WRITABLE; - flags |= O_CREAT | O_TRUNC; - } - b'a' => { - if rwa { - return Err(FileModeError::BadRwa); - } - rwa = true; - mode |= FileMode::WRITABLE | FileMode::APPENDING; - flags |= O_APPEND | O_CREAT; - } - b'+' => { - if plus { - return Err(FileModeError::BadRwa); - } - plus = true; - mode |= FileMode::READABLE | FileMode::WRITABLE; - } - b'b' => { - if binary { - return Err(FileModeError::Invalid); - } - binary = true; - } - _ => return Err(FileModeError::Invalid), - } - } - - if !rwa { - return Err(FileModeError::BadRwa); - } - - if mode.is_superset(&(FileMode::READABLE | FileMode::WRITABLE)) { - flags |= O_RDWR; - } else if mode.contains(&FileModeFlag::Readable) { - flags |= O_RDONLY; - } else { - flags |= O_WRONLY; - } - - Ok(ParsedFileMode { mode, flags }) -} +pub use crate::file_mode::{ + FileMode, FileModeError, FileModeFlag, ParsedFileMode, parse_fileio_mode, +}; #[derive(Clone, Copy, Debug)] pub struct FileTargetInfo { diff --git a/crates/host_env/src/io_wasm.rs b/crates/host_env/src/io_wasm.rs new file mode 100644 index 00000000000..a228867691a --- /dev/null +++ b/crates/host_env/src/io_wasm.rs @@ -0,0 +1,101 @@ +use core::ffi::CStr; +use std::io; + +use crate::errno::errors::{EAGAIN, EBADF, EINTR, EINVAL, EISDIR}; +pub use crate::file_mode::{ + FileMode, FileModeError, FileModeFlag, ParsedFileMode, parse_fileio_mode, +}; +use crate::{crt_fd, wasi_p1}; + +#[derive(Clone, Copy, Debug)] +pub struct FileTargetInfo { + pub blksize: Option, +} + +pub fn inspect_file_target(fd: crt_fd::Borrowed<'_>) -> io::Result { + let stat = wasi_p1::fdstat(fd.as_raw())?; + if stat.fs_filetype == wasi_p1::FILETYPE_DIRECTORY { + return Err(io::Error::from_raw_os_error(EISDIR)); + } + Ok(FileTargetInfo { blksize: None }) +} + +pub fn open_path(path: &CStr, flags: i32, mode: i32) -> io::Result { + crt_fd::open(path, flags, mode) +} + +pub fn should_forget_fd_after_inspect_error(err: &io::Error, fd_is_own: bool) -> bool { + let errno = err.raw_os_error(); + (errno == Some(EISDIR) || errno == Some(EBADF)) && (!fd_is_own || errno == Some(EBADF)) +} + +pub fn seek_to_end(fd: crt_fd::Borrowed<'_>) -> io::Result { + seek(fd, 0, 2) +} + +pub fn is_seekable(fd: crt_fd::Borrowed<'_>) -> bool { + tell(fd).is_ok() +} + +pub fn reads_without_waiting(fd: crt_fd::Borrowed<'_>) -> bool { + is_seekable(fd) +} + +pub fn validate_whence(whence: i32) -> bool { + (0..=2).contains(&whence) +} + +pub fn is_interrupted_errno(errno: i32) -> bool { + errno == EINTR +} + +pub fn is_interrupted_error(err: &io::Error) -> bool { + err.raw_os_error() == Some(EINTR) +} + +pub fn is_would_block_error(err: &io::Error) -> bool { + err.raw_os_error() == Some(EAGAIN) +} + +pub fn seek( + fd: crt_fd::Borrowed<'_>, + offset: crt_fd::Offset, + how: i32, +) -> io::Result { + if !validate_whence(how) { + return Err(io::Error::from_raw_os_error(EINVAL)); + } + wasi_p1::seek(fd.as_raw(), offset, how) +} + +pub fn tell(fd: crt_fd::Borrowed<'_>) -> io::Result { + seek(fd, 0, 1) +} + +pub fn isatty(fd: i32) -> bool { + wasi_p1::is_tty(fd) +} + +pub fn read_once(fd: crt_fd::Borrowed<'_>, buf: &mut [u8]) -> io::Result { + crt_fd::read(fd, buf) +} + +pub fn read_all(fd: crt_fd::Borrowed<'_>, out: &mut Vec) -> io::Result<()> { + let mut buffer = [0; 8192]; + loop { + match read_once(fd, &mut buffer) { + Ok(0) => return Ok(()), + Ok(n) => out.extend_from_slice(&buffer[..n]), + Err(err) if is_interrupted_error(&err) => continue, + Err(err) => return Err(err), + } + } +} + +pub fn write_once(fd: crt_fd::Borrowed<'_>, buf: &[u8]) -> io::Result { + crt_fd::write(fd, buf) +} + +pub fn close_owned_fd(fd: crt_fd::Owned) -> io::Result<()> { + crt_fd::close(fd) +} diff --git a/crates/host_env/src/lib.rs b/crates/host_env/src/lib.rs index ee9c5238e5d..ba6276bbc0a 100644 --- a/crates/host_env/src/lib.rs +++ b/crates/host_env/src/lib.rs @@ -13,20 +13,35 @@ pub mod errno; #[cfg(all(target_arch = "wasm32", target_os = "unknown"))] #[path = "errno_wasm.rs"] pub mod errno; +mod file_mode; #[cfg(any(unix, windows, target_os = "wasi"))] pub mod io; -#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] +#[cfg(all( + target_arch = "wasm32", + not(target_os = "wasi"), + not(all(target_os = "unknown", feature = "host_io")) +))] #[path = "io_unsupported.rs"] pub mod io; +#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "host_io"))] +#[path = "io_wasm.rs"] +pub mod io; pub mod os; #[cfg(any(unix, windows))] pub mod thread; #[cfg(any(unix, windows, target_os = "wasi"))] pub mod crt_fd; -#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] +#[cfg(all( + target_arch = "wasm32", + not(target_os = "wasi"), + not(all(target_os = "unknown", feature = "host_io")) +))] #[path = "crt_fd_unsupported.rs"] pub mod crt_fd; +#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "host_io"))] +#[path = "crt_fd_wasm.rs"] +pub mod crt_fd; #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] pub mod fileutils; @@ -36,6 +51,7 @@ pub mod locale; #[cfg(feature = "native-certs")] pub mod native_certs; pub mod readline; +pub mod remote_debugging; #[cfg(feature = "ssl")] pub mod ssl; @@ -72,9 +88,9 @@ pub mod posix_unix_like; pub mod pwd; #[cfg(unix)] pub mod resource; -#[cfg(all(unix, not(target_os = "redox"), not(target_os = "android")))] +#[cfg(all(unix, not(target_os = "android")))] pub mod shm; -#[cfg(any(unix, windows))] +#[cfg(any(unix, windows, target_os = "wasi"))] pub mod signal; pub mod time; @@ -108,3 +124,6 @@ pub mod winreg; pub mod winsound; #[cfg(windows)] pub mod wmi; + +#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "host_io"))] +mod wasi_p1; diff --git a/crates/host_env/src/locale.rs b/crates/host_env/src/locale.rs index e9df052c208..3c194a72dbe 100644 --- a/crates/host_env/src/locale.rs +++ b/crates/host_env/src/locale.rs @@ -3,6 +3,53 @@ use core::{ffi::CStr, ptr}; pub use libc::{LC_ALL, LC_COLLATE, LC_CTYPE, LC_MONETARY, LC_NUMERIC, LC_TIME}; +// CPython uses the wide-character APIs after btowc() on Apple platforms. +// Darwin's wint_t is int; libc does not expose these declarations. +#[cfg(target_vendor = "apple")] +unsafe extern "C" { + fn btowc(ch: libc::c_int) -> libc::c_int; + fn iswalnum(ch: libc::c_int) -> libc::c_int; + fn towlower(ch: libc::c_int) -> libc::c_int; + fn towupper(ch: libc::c_int) -> libc::c_int; +} + +/// Classify a byte using the current LC_CTYPE locale. +pub fn byte_isalnum(ch: u8) -> bool { + // ctype functions require EOF or an unsigned-char value, never a signed byte. + #[cfg(not(target_vendor = "apple"))] + unsafe { + libc::isalnum(ch.into()) != 0 + } + #[cfg(target_vendor = "apple")] + unsafe { + iswalnum(btowc(ch.into())) != 0 + } +} + +/// Lowercase a byte using the current LC_CTYPE locale. +pub fn byte_tolower(ch: u8) -> u32 { + #[cfg(not(target_vendor = "apple"))] + unsafe { + libc::tolower(ch.into()) as u32 + } + #[cfg(target_vendor = "apple")] + unsafe { + towlower(btowc(ch.into())) as u32 + } +} + +/// Uppercase a byte using the current LC_CTYPE locale. +pub fn byte_toupper(ch: u8) -> u32 { + #[cfg(not(target_vendor = "apple"))] + unsafe { + libc::toupper(ch.into()) as u32 + } + #[cfg(target_vendor = "apple")] + unsafe { + towupper(btowc(ch.into())) as u32 + } +} + #[cfg(all(unix, not(any(target_os = "ios", target_os = "redox"))))] pub use libc::LC_MESSAGES; @@ -86,8 +133,12 @@ fn copy_grouping(ptr: *const libc::c_char) -> Vec { let mut out = Vec::new(); let mut cur = ptr; unsafe { - while ![0, libc::c_char::MAX].contains(&*cur) { - out.push(*cur); + while *cur != 0 { + let value = *cur; + out.push(value); + if value == libc::c_char::MAX { + break; + } cur = cur.add(1); } } @@ -175,6 +226,103 @@ pub fn strxfrm(string: &CStr, _initial_len: usize) -> Vec { buff } +#[cfg(target_os = "linux")] +pub use wide_collation::{CollationString, CollationTransformError}; + +#[cfg(target_os = "linux")] +mod wide_collation { + use rustpython_wtf8::{CodePoint, Wtf8, Wtf8Buf}; + use std::io; + + unsafe extern "C" { + fn wcscoll(first: *const libc::wchar_t, second: *const libc::wchar_t) -> libc::c_int; + fn wcsxfrm( + destination: *mut libc::wchar_t, + source: *const libc::wchar_t, + capacity: usize, + ) -> usize; + } + + /// A NUL-terminated wide string for the locale collation APIs. + pub struct CollationString(Vec); + + pub enum CollationTransformError { + Memory, + Os(io::Error), + } + + impl CollationString { + /// Preserve Python's lone surrogates and reject embedded NULs. + pub fn new(string: &Wtf8) -> Option { + let mut wide = Vec::with_capacity(string.len() + 1); + for point in string.code_points() { + let value = point.to_u32(); + if value == 0 { + return None; + } + wide.push(value as libc::wchar_t); + } + wide.push(0); + Some(Self(wide)) + } + + pub fn compare(&self, other: &Self) -> libc::c_int { + // Both buffers retain their terminator and cannot contain interior NULs. + unsafe { wcscoll(self.0.as_ptr(), other.0.as_ptr()) } + } + + pub fn transform(&self) -> Result { + let mut dummy = [0]; + crate::os::clear_errno(); + let needed = unsafe { wcsxfrm(dummy.as_mut_ptr(), self.0.as_ptr(), 1) }; + let errno = crate::os::get_errno(); + if errno != 0 && errno != libc::ERANGE { + return Err(CollationTransformError::Os(io::Error::from_raw_os_error( + errno, + ))); + } + let capacity = needed + .checked_add(1) + .ok_or(CollationTransformError::Memory)?; + let mut wide = Vec::new(); + wide.try_reserve_exact(capacity) + .map_err(|_| CollationTransformError::Memory)?; + wide.resize(capacity, 0); + crate::os::clear_errno(); + let written = unsafe { wcsxfrm(wide.as_mut_ptr(), self.0.as_ptr(), wide.len()) }; + let errno = crate::os::get_errno(); + if errno != 0 { + return Err(CollationTransformError::Os(io::Error::from_raw_os_error( + errno, + ))); + } + // A concurrent locale change can invalidate the size query. Never + // interpret a truncated or unterminated result as a collation key. + if written >= wide.len() { + return Err(CollationTransformError::Os(io::Error::from_raw_os_error( + libc::ERANGE, + ))); + } + wide.truncate(written); + + // wcsxfrm emits integer weights, not necessarily Unicode. CPython + // 3.15 splits weights above 0x10000 into two ordered code points. + // Keep individual surrogates rather than decoding as UTF-16. + let mut key = Wtf8Buf::new(); + for weight in wide { + let value = weight as u32; + if value > 0x10000 { + key.push(CodePoint::from_u32((value >> 16) | 0x10000).unwrap()); + key.push(CodePoint::from_u32(value & 0xffff).unwrap()); + } else { + key.push(CodePoint::from_u32(value).unwrap()); + } + } + Ok(key) + } + } +} + pub fn setlocale(category: i32, locale: Option<&CStr>) -> Option> { let result = unsafe { match locale { @@ -278,3 +426,299 @@ pub fn nl_langinfo_codeset() -> Option> { let codeset = unsafe { libc::nl_langinfo(libc::CODESET) }; (!codeset.is_null()).then(|| unsafe { CStr::from_ptr(codeset) }.to_bytes().to_vec()) } + +/// Initialize the command-line interpreter's locale from its environment. +/// +/// Ordinary startup changes only LC_CTYPE. PEP 538 coercion additionally +/// updates LC_CTYPE in the environment and refreshes the other categories, +/// just as CPython's _coerce_default_locale_settings does. Embedders should +/// preserve their application's locale and use a snapshot instead. +/// +/// # Safety +/// +/// Call only during single-threaded process startup, before other threads or +/// libraries can read the environment or use the process-global locale. +#[cfg(any(target_os = "linux", target_os = "macos"))] +pub unsafe fn initialize_ctype(ignore_environment: bool) { + use std::io::Write; + + // An invalid environment locale is not a fatal initialization error. + let _ = setlocale(LC_CTYPE, Some(c"")); + let control = (!ignore_environment) + .then(|| std::env::var_os("PYTHONCOERCECLOCALE")) + .flatten(); + let warn = control.as_deref() == Some(std::ffi::OsStr::new("warn")); + let coerce = control.as_deref() != Some(std::ffi::OsStr::new("0")); + let legacy = |locale: &[u8]| locale == b"C" || locale == b"POSIX"; + let Some(original) = setlocale(LC_CTYPE, None) else { + return; + }; + if !legacy(&original) { + return; + } + + let overridden = std::env::var_os("LC_ALL").is_some_and(|value| !value.is_empty()); + if coerce && !overridden { + for candidate in [c"C.UTF-8", c"C.utf8", c"UTF-8"] { + if setlocale(LC_CTYPE, Some(candidate)).is_none() { + continue; + } + if nl_langinfo_codeset().is_none_or(|value| value.is_empty()) { + let _ = setlocale(LC_CTYPE, Some(c"")); + continue; + } + let _ = setlocale(LC_ALL, Some(c"")); + // SAFETY: the caller guarantees exclusive access to environment + // and global locale state for the entire initialization operation. + if unsafe { libc::setenv(c"LC_CTYPE".as_ptr(), candidate.as_ptr(), 1) } != 0 { + let _ = writeln!( + std::io::stderr(), + "Error setting LC_CTYPE, skipping C locale coercion" + ); + break; + } + if warn { + let _ = writeln!( + std::io::stderr(), + "Python detected LC_CTYPE=C: LC_CTYPE coerced to {} (set another locale or PYTHONCOERCECLOCALE=0 to disable this locale coercion behavior).", + candidate.to_string_lossy() + ); + } + let _ = setlocale(LC_ALL, Some(c"")); + return; + } + // setlocale's returned string contains no NUL bytes. + if let Ok(original) = alloc::ffi::CString::new(original) { + let _ = setlocale(LC_CTYPE, Some(&original)); + } + } + if warn { + let _ = writeln!( + std::io::stderr(), + "Python runtime initialized with LC_CTYPE=C (a locale with default ASCII encoding), which may cause Unicode compatibility problems. Using C.UTF-8, C.utf8, or UTF-8 (if available) as alternative Unicode-compatible locales is recommended." + ); + } +} + +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub use snapshot::{LocaleEncodeError, LocaleSnapshot}; + +// libc exposes mbstate_t on GNU Linux. Do not guess an opaque C conversion- +// state layout on platforms where the crate does not expose this type. +#[cfg(all(target_os = "linux", target_env = "gnu"))] +mod snapshot { + use core::{ffi::CStr, marker::PhantomData, ptr}; + use rustpython_wtf8::{CodePoint, Wtf8, Wtf8Buf}; + use std::io; + + unsafe extern "C" { + fn mbrtowc( + out: *mut libc::wchar_t, + input: *const libc::c_char, + count: usize, + state: *mut libc::mbstate_t, + ) -> usize; + fn wcrtomb( + out: *mut libc::c_char, + input: libc::wchar_t, + state: *mut libc::mbstate_t, + ) -> usize; + fn __ctype_get_mb_cur_max() -> usize; + } + + /// A conversion failure with enough information for UnicodeEncodeError. + #[derive(Debug)] + pub enum LocaleEncodeError { + Native(io::Error), + Character { index: usize, reason: &'static str }, + } + + impl From for LocaleEncodeError { + fn from(error: io::Error) -> Self { + Self::Native(error) + } + } + + /// An owned copy of the startup thread's locale for filesystem bootstrap. + /// Later process-global setlocale calls cannot change this conversion state. + pub struct LocaleSnapshot { + locale: libc::locale_t, + encoding: String, + } + + // The owned locale is never modified after duplocale. uselocale installs + // it only in the calling thread; every conversion has its own mbstate_t. + // A borrowed guard keeps the locale alive until that thread restores its + // previous locale, so sharing an immutable snapshot is safe. + unsafe impl Send for LocaleSnapshot {} + unsafe impl Sync for LocaleSnapshot {} + + impl Drop for LocaleSnapshot { + fn drop(&mut self) { + // SAFETY: capture owns a non-null duplicate, never LC_GLOBAL_LOCALE. + unsafe { libc::freelocale(self.locale) }; + } + } + + struct ThreadLocale<'a> { + previous: libc::locale_t, + _snapshot: &'a LocaleSnapshot, + // The guard must be restored on the same thread that installed it. + _not_send: PhantomData<*mut ()>, + } + + impl Drop for ThreadLocale<'_> { + fn drop(&mut self) { + // SAFETY: previous is the valid locale returned by uselocale, and + // the non-Send guard cannot migrate to a different thread. + unsafe { libc::uselocale(self.previous) }; + } + } + + impl LocaleSnapshot { + pub fn capture() -> io::Result { + // A null argument queries the caller's locale without changing it. + let current = unsafe { libc::uselocale(ptr::null_mut()) }; + if current.is_null() { + return Err(io::Error::last_os_error()); + } + // duplocale also accepts the LC_GLOBAL_LOCALE sentinel. + let locale = unsafe { libc::duplocale(current) }; + if locale.is_null() { + return Err(io::Error::last_os_error()); + } + let mut snapshot = Self { + locale, + encoding: String::new(), + }; + let codeset = unsafe { libc::nl_langinfo_l(libc::CODESET, locale) }; + if codeset.is_null() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "missing locale encoding", + )); + } + let encoding = unsafe { CStr::from_ptr(codeset) } + .to_str() + .map_err(|error| io::Error::new(io::ErrorKind::InvalidData, error))?; + if encoding.is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "empty locale encoding", + )); + } + encoding.clone_into(&mut snapshot.encoding); + Ok(snapshot) + } + + pub fn encoding(&self) -> &str { + &self.encoding + } + + fn enter(&self) -> io::Result> { + let previous = unsafe { libc::uselocale(self.locale) }; + if previous.is_null() { + return Err(io::Error::last_os_error()); + } + Ok(ThreadLocale { + previous, + _snapshot: self, + _not_send: PhantomData, + }) + } + + /// Decode with CPython's locale bootstrap surrogateescape behavior. + pub fn decode(&self, input: &[u8]) -> io::Result { + let _locale = self.enter()?; + let mut output = Wtf8Buf::with_capacity(input.len()); + let mut input = input; + // C specifies an all-zero mbstate_t as the initial conversion state. + let mut state: libc::mbstate_t = unsafe { core::mem::zeroed() }; + while !input.is_empty() { + let mut value: libc::wchar_t = 0; + let count = + unsafe { mbrtowc(&mut value, input.as_ptr().cast(), input.len(), &mut state) }; + let point = u32::try_from(value).ok().and_then(char::from_u32); + if count >= usize::MAX - 1 || point.is_none() { + // Invalid, incomplete, surrogate, and out-of-Unicode-range + // results all escape one byte and restart the shift state. + output.push(CodePoint::from(0xdc00u16 + u16::from(input[0]))); + input = &input[1..]; + state = unsafe { core::mem::zeroed() }; + } else { + if let Some(point) = point { + output.push_char(point); + } + // mbrtowc returns zero for an embedded NUL, consuming one + // byte. Our slice API retains NULs for later path validation. + input = &input[count.max(1)..]; + } + } + Ok(output) + } + + /// Encode with the locale captured at startup, preserving escaped bytes. + pub fn encode(&self, input: &Wtf8) -> Result, LocaleEncodeError> { + let _locale = self.enter()?; + let max_bytes = unsafe { __ctype_get_mb_cur_max() }; + if max_bytes == 0 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid locale character size", + ) + .into()); + } + let mut buffer = vec![0u8; max_bytes]; + let mut output = Vec::with_capacity(input.len()); + for (index, point) in input.code_points().enumerate() { + let value = point.to_u32(); + if (0xdc80..=0xdcff).contains(&value) { + output.push((value - 0xdc00) as u8); + continue; + } + if char::from_u32(value).is_none() { + return Err(LocaleEncodeError::Character { + index, + reason: "surrogates not allowed", + }); + } + // CPython's bootstrap encoder converts each character from the + // initial shift state (wcstombs on a one-character string). + let mut state: libc::mbstate_t = unsafe { core::mem::zeroed() }; + let count = unsafe { + wcrtomb( + buffer.as_mut_ptr().cast(), + value as libc::wchar_t, + &mut state, + ) + }; + if count == usize::MAX { + return Err(LocaleEncodeError::Character { + index, + reason: "encoding error", + }); + } + output.extend_from_slice(&buffer[..count]); + // Preserve a stateful codec's shift-back bytes, excluding the + // terminator that wcstombs would not count in its result. + let count = unsafe { wcrtomb(buffer.as_mut_ptr().cast(), 0, &mut state) }; + if count == usize::MAX { + return Err(io::Error::last_os_error().into()); + } + output.extend_from_slice(&buffer[..count.saturating_sub(1)]); + } + Ok(output) + } + } +} + +#[cfg(test)] +mod tests { + use super::copy_grouping; + + #[test] + fn grouping_keeps_char_max_terminator() { + let grouping = [3, libc::c_char::MAX, 2, 0]; + assert_eq!(copy_grouping(grouping.as_ptr()), [3, libc::c_char::MAX]); + } +} diff --git a/crates/host_env/src/macros.rs b/crates/host_env/src/macros.rs index 08d00e592d9..a975997ceda 100644 --- a/crates/host_env/src/macros.rs +++ b/crates/host_env/src/macros.rs @@ -12,9 +12,9 @@ macro_rules! suppress_iph { #[cfg(all(windows, target_env = "msvc"))] macro_rules! __suppress_iph_impl { ($e:expr) => {{ - let old = $crate::__macro_private::_set_thread_local_invalid_parameter_handler( + let old = $crate::__macro_private::_set_thread_local_invalid_parameter_handler(Some( $crate::__macro_private::silent_iph_handler, - ); + )); let ret = $e; $crate::__macro_private::_set_thread_local_invalid_parameter_handler(old); ret @@ -43,8 +43,8 @@ pub mod __macro_private { #[cfg(target_env = "msvc")] unsafe extern "C" { pub fn _set_thread_local_invalid_parameter_handler( - pNew: InvalidParamHandler, - ) -> InvalidParamHandler; + pNew: Option, + ) -> Option; } #[cfg(target_env = "msvc")] diff --git a/crates/host_env/src/mmap.rs b/crates/host_env/src/mmap.rs index 976d78e2c38..6b502062e23 100644 --- a/crates/host_env/src/mmap.rs +++ b/crates/host_env/src/mmap.rs @@ -7,8 +7,8 @@ use std::io; #[cfg(unix)] pub use libc::{ - MADV_DONTNEED, MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL, MADV_WILLNEED, PROT_EXEC, PROT_READ, - PROT_WRITE, + MADV_DONTNEED, MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL, MADV_WILLNEED, MS_ASYNC, + MS_INVALIDATE, MS_SYNC, PROT_EXEC, PROT_READ, PROT_WRITE, }; #[cfg(unix)] @@ -139,15 +139,15 @@ use std::os::windows::io::{AsRawHandle, IntoRawHandle}; #[cfg(windows)] use windows_sys::Win32::{ Foundation::{ - CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, GetLastError, HANDLE, - INVALID_HANDLE_VALUE, + CloseHandle, DUPLICATE_SAME_ACCESS, DuplicateHandle, ERROR_ALREADY_EXISTS, + ERROR_USER_MAPPED_FILE, GetLastError, HANDLE, INVALID_HANDLE_VALUE, }, Storage::FileSystem::{FILE_BEGIN, GetFileSize, SetEndOfFile, SetFilePointerEx}, System::{ Memory::{ CreateFileMappingW, FILE_MAP_COPY, FILE_MAP_READ, FILE_MAP_WRITE, FlushViewOfFile, - MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, PAGE_READONLY, PAGE_READWRITE, - PAGE_WRITECOPY, UnmapViewOfFile, + MEMORY_MAPPED_VIEW_ADDRESS, MapViewOfFile, OpenFileMappingW, PAGE_READONLY, + PAGE_READWRITE, PAGE_WRITECOPY, UnmapViewOfFile, }, Threading::GetCurrentProcess, }, @@ -168,8 +168,9 @@ pub enum AccessMode { #[cfg(windows)] #[derive(Debug)] -pub struct NamedMmap { +pub struct WindowsMmap { map_handle: Handle, + tag: Option>, view_ptr: *mut u8, len: usize, } @@ -202,10 +203,43 @@ impl MappedFile { } } - pub fn flush_range(&self, offset: usize, size: usize) -> io::Result<()> { + pub fn flush_range(&self, offset: usize, size: usize, flags: i32) -> io::Result<()> { + #[cfg(unix)] + { + if offset > self.as_slice().len() || size > self.as_slice().len() - offset { + return Err(io::Error::from_raw_os_error(libc::EINVAL)); + } + let ptr = unsafe { self.as_ptr().add(offset) }; + let flags = if flags == 0 { MS_SYNC } else { flags }; + if unsafe { libc::msync(ptr.cast_mut().cast(), size, flags) } == -1 { + return Err(io::Error::last_os_error()); + } + Ok(()) + } + #[cfg(not(unix))] + { + let _ = flags; + match self { + Self::Read(_) => Ok(()), + Self::Write(mmap) => mmap.flush_range(offset, size), + } + } + } + + /// # Safety + /// The backing file must cover the mapping offset plus `new_size`, and no + /// exported pointers may remain live while the mapping is moved or shrunk. + #[cfg(target_os = "linux")] + pub unsafe fn remap(&mut self, new_size: usize) -> io::Result<()> { + // memmap2 permits a zero-length mapping, whereas mmap.resize(0) must + // preserve mremap's EINVAL result. + if new_size == 0 { + return Err(io::Error::from_raw_os_error(libc::EINVAL)); + } + let options = memmap2::RemapOptions::new().may_move(true); match self { - Self::Read(_) => Ok(()), - Self::Write(mmap) => mmap.flush_range(offset, size), + Self::Read(mmap) => unsafe { mmap.remap(new_size, options) }, + Self::Write(mmap) => unsafe { mmap.remap(new_size, options) }, } } @@ -216,13 +250,130 @@ impl MappedFile { } } +#[cfg(target_os = "linux")] +pub fn set_mapping_name(address: usize, size: usize, name: &core::ffi::CStr) -> io::Result<()> { + if unsafe { + libc::prctl( + libc::PR_SET_VMA, + libc::PR_SET_VMA_ANON_NAME, + address, + size, + name.as_ptr(), + ) + } == -1 + { + return Err(io::Error::last_os_error()); + } + Ok(()) +} + #[cfg(windows)] -unsafe impl Send for NamedMmap {} +unsafe impl Send for WindowsMmap {} #[cfg(windows)] -unsafe impl Sync for NamedMmap {} +unsafe impl Sync for WindowsMmap {} #[cfg(windows)] -impl NamedMmap { +impl WindowsMmap { + pub fn is_valid(&self) -> bool { + !self.map_handle.is_null() && !self.view_ptr.is_null() + } + + pub fn size(&self) -> usize { + self.len + } + + /// Resize like CPython's Windows mmap: retain the old anonymous view until + /// its contents have been copied, but release file views before truncation. + /// + /// # Safety + /// No exported pointers may remain live, and the caller must discard an + /// invalid mapping after an error before exposing its contents again. + pub unsafe fn resize(&mut self, file: Handle, offset: i64, new_size: usize) -> io::Result<()> { + let old_data = self.view_ptr; + let mut new_size = new_size; + let mut max_size = offset as u64 + new_size as u64; + let mut file_resize_error = None; + unsafe { CloseHandle(self.map_handle) }; + self.map_handle = core::ptr::null_mut(); + if let Some(tag) = &self.tag { + self.map_handle = unsafe { OpenFileMappingW(FILE_MAP_WRITE, 0, tag.as_ptr()) }; + if !self.map_handle.is_null() { + return Err(io::Error::from_raw_os_error(ERROR_USER_MAPPED_FILE as i32)); + } + } + if file != INVALID_HANDLE { + unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: self.view_ptr.cast(), + }) + } + .check_win32_bool()?; + self.view_ptr = core::ptr::null_mut(); + if let Err(err) = extend_file(file, max_size as i64) { + file_resize_error = Some(err); + max_size = self.len as u64; + new_size = self.len; + } + } + self.map_handle = unsafe { + CreateFileMappingW( + file, + core::ptr::null(), + PAGE_READWRITE, + (max_size >> 32) as u32, + max_size as u32, + self.tag + .as_ref() + .map_or(core::ptr::null(), |tag| tag.as_ptr()), + ) + }; + let error = unsafe { GetLastError() }; + // A different mapping may have taken this name between close and create. + if error == ERROR_ALREADY_EXISTS { + unsafe { CloseHandle(self.map_handle) }; + self.map_handle = core::ptr::null_mut(); + return Err(io::Error::from_raw_os_error(error as i32)); + } + if self.map_handle.is_null() { + return Err(io::Error::from_raw_os_error(error as i32)); + } + let view = unsafe { + MapViewOfFile( + self.map_handle, + FILE_MAP_WRITE, + (offset as u64 >> 32) as u32, + offset as u32, + new_size, + ) + }; + if view.Value.is_null() { + let err = io::Error::last_os_error(); + unsafe { CloseHandle(self.map_handle) }; + self.map_handle = core::ptr::null_mut(); + return Err(err); + } + self.view_ptr = view.Value.cast(); + if file == INVALID_HANDLE { + unsafe { + core::ptr::copy_nonoverlapping(old_data, self.view_ptr, self.len.min(new_size)) + }; + let result = unsafe { + UnmapViewOfFile(MEMORY_MAPPED_VIEW_ADDRESS { + Value: old_data.cast(), + }) + } + .check_win32_bool(); + self.len = new_size; + result?; + } else { + self.len = new_size; + } + if let Some(err) = file_resize_error { + return Err(err); + } + Ok(()) + } + pub fn as_slice(&self) -> &[u8] { unsafe { core::slice::from_raw_parts(self.view_ptr, self.len) } } @@ -241,7 +392,7 @@ impl NamedMmap { } #[cfg(windows)] -impl Drop for NamedMmap { +impl Drop for WindowsMmap { fn drop(&mut self) { unsafe { if !self.view_ptr.is_null() { @@ -293,16 +444,47 @@ pub fn file_len(fd: crt_fd::Borrowed<'_>) -> io::Result { Ok(fileutils::fstat(fd)?.st_size.into()) } +/// Inspect Python's raw descriptor without assuming that it is a valid Rust fd. +/// CPython ignores failed fstat calls and only bounds regular-file mappings. #[cfg(unix)] -pub fn prepare_file_mapping(fd: crt_fd::Borrowed<'_>) { - #[cfg(target_os = "macos")] - { - let _ = posix::full_fsync(fd.into()); +pub fn regular_file_len(fd: i32) -> Option { + // Use the same target selection as memmap2's mmap64/off64_t aliases. + #[cfg(not(any( + target_os = "android", + all(target_os = "linux", not(target_env = "musl")) + )))] + use libc::{fstat, stat as Stat}; + #[cfg(any( + target_os = "android", + all(target_os = "linux", not(target_env = "musl")) + ))] + use libc::{fstat64 as fstat, stat64 as Stat}; + + let mut status = core::mem::MaybeUninit::::uninit(); + // SAFETY: fstat accepts an arbitrary integer and initializes status only + // on success. No borrowed/owned descriptor is constructed from that input. + if unsafe { fstat(fd, status.as_mut_ptr()) } != 0 { + return None; } - #[cfg(not(target_os = "macos"))] - { - let _ = fd; + let status = unsafe { status.assume_init() }; + if status.st_mode & libc::S_IFMT != libc::S_IFREG { + return None; } + #[allow(clippy::useless_conversion, reason = "needed for 32-bit platforms")] + i64::try_from(status.st_size).ok() +} + +#[cfg(target_os = "macos")] +pub fn prepare_file_mapping(fd: i32) { + // CPython intentionally ignores F_FULLFSYNC errors, including invalid fds. + let _ = unsafe { libc::fcntl(fd, libc::F_FULLFSYNC) }; +} + +#[cfg(windows)] +pub fn prepare_file_mapping(fd: i32) { + // Match CPython's historical Windows constructor side effect. Seek errors + // are intentionally ignored; CreateFileMapping reports unusable handles. + let _ = unsafe { crate::suppress_iph!(libc::lseek(fd, 0, libc::SEEK_SET)) }; } #[cfg(windows)] @@ -340,13 +522,13 @@ pub fn last_error() -> u32 { } #[cfg(windows)] -pub fn create_named_mapping( +pub fn create_mapping( file_handle: Handle, - tag: &str, + tag: Option<&str>, access: AccessMode, offset: i64, map_size: usize, -) -> io::Result { +) -> io::Result { let (fl_protect, desired_access) = match access { AccessMode::Default | AccessMode::Write => (PAGE_READWRITE, FILE_MAP_WRITE), AccessMode::Read => (PAGE_READONLY, FILE_MAP_READ), @@ -358,7 +540,8 @@ pub fn create_named_mapping( .ok_or_else(|| io::Error::from_raw_os_error(libc::EOVERFLOW))?; let size_hi = (total_size >> 32) as u32; let size_lo = total_size as u32; - let tag_wide: Vec = tag.encode_utf16().chain(core::iter::once(0)).collect(); + let tag_wide: Option> = + tag.map(|tag| tag.encode_utf16().chain(core::iter::once(0)).collect()); let map_handle = unsafe { CreateFileMappingW( @@ -367,7 +550,9 @@ pub fn create_named_mapping( fl_protect, size_hi, size_lo, - tag_wide.as_ptr(), + tag_wide + .as_ref() + .map_or(core::ptr::null(), |tag| tag.as_ptr()), ) } .into_owned() @@ -389,8 +574,9 @@ pub fn create_named_mapping( return Err(io::Error::last_os_error()); } - Ok(NamedMmap { + Ok(WindowsMmap { map_handle: map_handle.into_raw_handle() as Handle, + tag: tag_wide, view_ptr: view.Value as *mut u8, len: map_size, }) @@ -409,25 +595,44 @@ pub fn map_anon(size: usize) -> io::Result { } #[cfg(unix)] -pub fn map_file( - fd: crt_fd::Borrowed<'_>, - offset: i64, - size: usize, - access: AccessMode, -) -> io::Result<(crt_fd::Owned, MappedFile)> { - let new_fd: crt_fd::Owned = posix::dup_noninheritable(fd.into())?.into(); +pub fn duplicate_descriptor(fd: i32) -> io::Result { + // Python supplies an arbitrary integer, so validate it through fcntl before + // constructing a Rust descriptor. Only the successful duplicate is owned. + let new_fd = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 0) }; + if new_fd != -1 { + return Ok(unsafe { crt_fd::Owned::from_raw(new_fd) }); + } + let err = io::Error::last_os_error(); + if err.raw_os_error() != Some(libc::EINVAL) { + return Err(err); + } + // Older kernels may not support F_DUPFD_CLOEXEC. + let new_fd = unsafe { libc::dup(fd) }; + if new_fd == -1 { + return Err(io::Error::last_os_error()); + } + let new_fd = unsafe { crt_fd::Owned::from_raw(new_fd) }; + posix::set_inheritable(new_fd.borrow().into(), false)?; + Ok(new_fd) +} + +#[cfg(unix)] +pub fn map_file(fd: i32, offset: i64, size: usize, access: AccessMode) -> io::Result { let mut mmap_opt = MmapOptions::new(); let mmap_opt = mmap_opt.offset(offset as u64).len(size); + // len is always explicit, so memmap2 never wraps this raw fd in File to + // query metadata. Its mmap syscall rejects invalid descriptors directly. + // The caller retains any owned tracking descriptor through this call. let mapped = match access { AccessMode::Default | AccessMode::Write => { - unsafe { mmap_opt.map_mut(&new_fd) }.map(MappedFile::Write)? + unsafe { mmap_opt.map_mut(fd) }.map(MappedFile::Write)? } - AccessMode::Read => unsafe { mmap_opt.map(&new_fd) }.map(MappedFile::Read)?, - AccessMode::Copy => unsafe { mmap_opt.map_copy(&new_fd) }.map(MappedFile::Write)?, + AccessMode::Read => unsafe { mmap_opt.map(fd) }.map(MappedFile::Read)?, + AccessMode::Copy => unsafe { mmap_opt.map_copy(fd) }.map(MappedFile::Write)?, }; - Ok((new_fd, mapped)) + Ok(mapped) } #[cfg(all(unix, not(target_os = "redox")))] diff --git a/crates/host_env/src/nt.rs b/crates/host_env/src/nt.rs index 9f1c1c23de4..4a17f81f188 100644 --- a/crates/host_env/src/nt.rs +++ b/crates/host_env/src/nt.rs @@ -7,7 +7,10 @@ use std::{ ffi::OsString, io, - os::windows::{ffi::OsStringExt, io::AsRawHandle}, + os::windows::{ + ffi::{OsStrExt, OsStringExt}, + io::AsRawHandle, + }, path::Path, }; @@ -22,7 +25,8 @@ use crate::{ windows::{CheckWin32Bool, CheckWin32Handle, CheckWin32Sentinel, HandleToOwned}, }; use libc::intptr_t; -use widestring::WideCString; + +use widestring::{WideCStr, WideCString}; use windows_sys::{ Win32::{ Foundation::{ @@ -75,6 +79,25 @@ pub use windows_sys::Win32::Storage::FileSystem::{ FILE_ATTRIBUTE_TEMPORARY, FILE_ATTRIBUTE_VIRTUAL, }; +pub fn get_blocking(fd: crt_fd::Borrowed<'_>) -> io::Result { + let handle = crt_fd::as_handle(fd)?; + let mode = crate::winapi::get_named_pipe_handle_state(handle.as_raw_handle())?; + Ok(mode & windows_sys::Win32::System::Pipes::PIPE_NOWAIT == 0) +} + +pub fn set_blocking(fd: crt_fd::Borrowed<'_>, blocking: bool) -> io::Result<()> { + use windows_sys::Win32::System::Pipes::PIPE_NOWAIT; + + let handle = crt_fd::as_handle(fd)?; + let mode = crate::winapi::get_named_pipe_handle_state(handle.as_raw_handle())?; + let mode = if blocking { + mode & !PIPE_NOWAIT + } else { + mode | PIPE_NOWAIT + }; + crate::winapi::set_named_pipe_handle_state(handle.as_raw_handle(), Some(mode), None, None) +} + pub type Handle = HANDLE; pub const MAX_PATH_USIZE: usize = MAX_PATH as usize; pub const ERROR_INVALID_HANDLE_I32: i32 = ERROR_INVALID_HANDLE as i32; @@ -129,16 +152,16 @@ struct FileAttributeTagInfo { reparse_tag: u32, } -const fn win32_large_integer_to_time(li: i64) -> (libc::time_t, i32) { +const fn win32_large_integer_to_time(li: i64) -> (crate::time::TimeT, i32) { let nsec = ((li % 10_000_000) * 100) as i32; - let sec = (li / 10_000_000 - crate::fileutils::windows::SECS_BETWEEN_EPOCHS) as libc::time_t; + let sec = li / 10_000_000 - crate::fileutils::windows::SECS_BETWEEN_EPOCHS; (sec, nsec) } -const fn win32_filetime_to_time(ft_low: u32, ft_high: u32) -> (libc::time_t, i32) { +const fn win32_filetime_to_time(ft_low: u32, ft_high: u32) -> (crate::time::TimeT, i32) { let ticks = ((ft_high as i64) << 32) | (ft_low as i64); let nsec = ((ticks % 10_000_000) * 100) as i32; - let sec = (ticks / 10_000_000 - crate::fileutils::windows::SECS_BETWEEN_EPOCHS) as libc::time_t; + let sec = ticks / 10_000_000 - crate::fileutils::windows::SECS_BETWEEN_EPOCHS; (sec, nsec) } @@ -228,8 +251,8 @@ fn win32_attribute_data_to_stat( } } -pub fn visible_env_vars() -> impl Iterator { - crate::os::vars().filter(|(key, _)| !key.starts_with('=')) +pub fn visible_env_vars() -> impl Iterator { + crate::os::vars_os().filter(|(key, _)| key.encode_wide().next() != Some(u16::from(b'='))) } #[derive(Debug)] @@ -245,11 +268,8 @@ pub enum ReadConsoleError { BufferTooSmall { available: usize, required: usize }, } -pub fn access(path: &Path, mode: u8) -> bool { - let Ok(wide) = WideCString::from_os_str(path.as_os_str()) else { - return false; - }; - let attr = unsafe { GetFileAttributesW(wide.as_ptr()) }; +pub fn access(path: &WideCStr, mode: u8) -> bool { + let attr = unsafe { GetFileAttributesW(path.as_ptr()) }; attr != INVALID_FILE_ATTRIBUTES && (mode & 2 == 0 || attr & FILE_ATTRIBUTE_READONLY == 0 @@ -326,7 +346,6 @@ pub fn symlink( if src.len() >= max_path { return false; } - resolved.extend_from_slice(src); } else { let separator_len = usize::from(!parent.is_empty()); if parent.len() + separator_len + src.len() >= max_path { @@ -336,8 +355,8 @@ pub fn symlink( if !parent.is_empty() { resolved.push(b'\\' as u16); } - resolved.extend_from_slice(src); } + resolved.extend_from_slice(src); resolved.push(0); let mut info: WIN32_FILE_ATTRIBUTE_DATA = unsafe { core::mem::zeroed() }; @@ -591,10 +610,10 @@ impl ScandirEntry { if reparse_tag == IO_REPARSE_TAG_SYMLINK { mode = (mode & !libc::S_IFMT) | S_IFLNK; } - let to_time = |ticks: u64| -> (libc::time_t, i32) { + let to_time = |ticks: u64| -> (crate::time::TimeT, i32) { let ticks = ticks as i64; ( - (ticks / 10_000_000 - SECS_BETWEEN_EPOCHS) as libc::time_t, + ticks / 10_000_000 - SECS_BETWEEN_EPOCHS, ((ticks % 10_000_000) * 100) as i32, ) }; @@ -645,7 +664,20 @@ impl core::fmt::Debug for Scandir { /// `rposix_scandir.opendir`: join `*.*` onto the directory and open the walk. pub fn scandir(path: &widestring::WideCStr) -> io::Result { let dir = path.as_slice().to_vec(); - let mut mask = join_path_filename(&dir, &[b'*' as u16, b'.' as u16, b'*' as u16]); + // Normalize before appending the wildcard, as CPython does. Otherwise a + // trailing space becomes an interior path component and is not stripped. + // Extended paths deliberately retain their literal spelling. + let normalized; + let search_dir = if !dir.is_empty() + && !dir.starts_with(&[b'\\' as u16, b'\\' as u16, b'?' as u16, b'\\' as u16]) + { + use std::os::windows::ffi::OsStrExt; + normalized = getfullpathname(path)?.encode_wide().collect::>(); + &normalized + } else { + &dir + }; + let mut mask = join_path_filename(search_dir, &[b'*' as u16, b'.' as u16, b'*' as u16]); mask.push(0); let mut data: WIN32_FIND_DATAW = unsafe { core::mem::zeroed() }; let handle = unsafe { FindFirstFileW(mask.as_ptr(), &mut data) }; @@ -2479,6 +2511,24 @@ pub fn execve( } } +#[cfg(test)] +mod scandir_tests { + use super::*; + + #[test] + fn trailing_space_is_normalized_except_in_extended_paths() { + let mut path = getfullpathname(widestring::widecstr!(".")).unwrap(); + path.push(" "); + let wide = WideCString::from_os_str(&path).unwrap(); + assert!(scandir(&wide).is_ok()); + + let mut extended = OsString::from("\\\\?\\"); + extended.push(path); + let wide = WideCString::from_os_str(&extended).unwrap(); + assert!(scandir(&wide).is_err()); + } +} + #[cfg(test)] mod find_last_utf8_boundary_tests { use super::find_last_utf8_boundary; diff --git a/crates/host_env/src/os.rs b/crates/host_env/src/os.rs index 6eda6030c83..32ef2f39f8e 100644 --- a/crates/host_env/src/os.rs +++ b/crates/host_env/src/os.rs @@ -74,7 +74,7 @@ pub const AT_EACCESS: i32 = 0x200; pub use libc::{ST_NOSUID, ST_RDONLY}; /// `open(2)` flags. libc on hosts that bind them; Darwin/BSD numbers on -/// `wasm32-unknown-unknown`, matching the guest errno table. +/// `wasm32-unknown-unknown`. These flags are independent of errno values. #[cfg(any(unix, windows, target_os = "wasi"))] pub use libc::{O_APPEND, O_CREAT, O_EXCL, O_RDONLY, O_RDWR, O_TRUNC, O_WRONLY}; @@ -487,14 +487,34 @@ pub fn device_encoding(_fd: i32) -> Option { #[cfg(windows)] { - use windows_sys::Win32::System::Console; - let cp = match _fd { - 0 => unsafe { Console::GetConsoleCP() }, - 1 | 2 => unsafe { Console::GetConsoleOutputCP() }, - _ => 0, + use windows_sys::Win32::{ + Foundation::{ERROR_ACCESS_DENIED, GetLastError, INVALID_HANDLE_VALUE}, + Storage::FileSystem::{FILE_TYPE_CHAR, GetFileType}, + System::Console, }; - - Some(format!("cp{cp}")) + let handle = crate::nt::handle_from_fd(_fd); + if handle == INVALID_HANDLE_VALUE || unsafe { GetFileType(handle) } != FILE_TYPE_CHAR { + return None; + } + let mut mode = 0; + let cp = unsafe { + if Console::GetConsoleMode(handle, &mut mode) == 0 { + // Like CPython, an access-denied console handle is assumed to be output. + if GetLastError() != ERROR_ACCESS_DENIED { + return None; + } + Console::GetConsoleOutputCP() + } else if Console::GetNumberOfConsoleInputEvents(handle, &mut mode) != 0 { + Console::GetConsoleCP() + } else { + Console::GetConsoleOutputCP() + } + }; + match cp { + 0 => None, + 65001 => Some("utf-8".to_owned()), + _ => Some(format!("cp{cp}")), + } } #[cfg(not(any( @@ -519,8 +539,28 @@ pub fn device_encoding(_fd: i32) -> Option { } } +/// Terminate the process through the C `exit()`, which runs the C atexit +/// handlers and flushes C stdio. pub fn exit(code: i32) -> ! { - std::process::exit(code) + cfg_select! { + // std::process::exit ends in ExitProcess here, which skips the CRT + // atexit handlers and the stdio flush. + windows => { + use std::io::Write; + let _ = std::io::stdout().flush(); + unsafe { libc::exit(code) } + } + _ => std::process::exit(code), + } +} + +/// Terminate the process through `_exit()`, without running the C atexit +/// handlers or flushing C stdio. +pub fn exit_immediately(code: i32) -> ! { + cfg_select! { + any(unix, windows, target_os = "wasi") => unsafe { libc::_exit(code) }, + _ => std::process::exit(code), + } } /// Wrapper around the C `abort()` call: terminates the process abnormally. @@ -601,6 +641,20 @@ pub fn seek_fd( unsafe { suppress_iph!(libc::lseek(fd.as_raw(), position, how)) }.check_libc_neg() } +#[cfg(windows)] +pub type FileTimeSeconds = libc::time64_t; +#[cfg(any(unix, target_os = "wasi"))] +#[cfg_attr(target_env = "musl", allow(deprecated))] +pub type FileTimeSeconds = libc::time_t; + +/// Seconds and nanoseconds passed to filesystem timestamp operations. +#[cfg(any(unix, windows, target_os = "wasi"))] +#[derive(Clone, Copy)] +pub struct FileTime { + pub seconds: FileTimeSeconds, + pub nanoseconds: libc::c_long, +} + #[cfg(windows)] fn filetime_from_duration(duration: Duration) -> FILETIME { let intervals = ((duration.as_secs() as i64 + 11644473600) * 10_000_000) @@ -680,13 +734,17 @@ impl core::error::Error for CrtErrno {} /// Build an [`io::Error`] that preserves a raw C runtime `errno`. /// -/// The [`io::ErrorKind`] is derived from the closest Win32 mapping so callers -/// matching on `kind()` keep working, while the exact `errno` is preserved for +/// The [`io::ErrorKind`] preserves would-block semantics and otherwise uses the +/// closest Win32 mapping. The exact `errno` is preserved for /// [`ErrorExt::posix_errno`]. #[cfg(windows)] #[must_use] pub fn io_error_from_errno(errno: i32) -> io::Error { - let kind = io::Error::from_raw_os_error(errno_to_winerror(errno)).kind(); + let kind = if errno == libc::EAGAIN { + io::ErrorKind::WouldBlock + } else { + io::Error::from_raw_os_error(errno_to_winerror(errno)).kind() + }; io::Error::new(kind, CrtErrno(errno)) } @@ -808,7 +866,17 @@ pub fn bytes_as_os_str(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> { Ok(std::ffi::OsStr::from_bytes(b)) } -#[cfg(not(any(unix, all(target_os = "wasi", not(target_env = "p2")))))] +#[cfg(all(target_arch = "wasm32", target_os = "unknown"))] +pub fn bytes_as_os_str(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> { + // SAFETY: this target stores OsStr as an unvalidated byte string. + Ok(unsafe { std::ffi::OsStr::from_encoded_bytes_unchecked(b) }) +} + +#[cfg(not(any( + unix, + all(target_os = "wasi", not(target_env = "p2")), + all(target_arch = "wasm32", target_os = "unknown"), +)))] pub fn bytes_as_os_str(b: &[u8]) -> Result<&std::ffi::OsStr, Utf8Error> { Ok(core::str::from_utf8(b)?.as_ref()) } @@ -902,7 +970,7 @@ pub fn errno_to_winerror(errno: i32) -> i32 { // errno: https://learn.microsoft.com/cpp/c-runtime-library/errno-constants?view=msvc-170 #[cfg(windows)] #[must_use] -pub fn winerror_to_errno(winerror: i32) -> i32 { +pub fn winerror_to_errno(mut winerror: i32) -> i32 { use libc::*; use windows_sys::Win32::{ Foundation::*, @@ -912,9 +980,9 @@ pub fn winerror_to_errno(winerror: i32) -> i32 { }, }; // Unwrap FACILITY_WIN32 HRESULT errors. - // if ((winerror & 0xFFFF0000) == 0x80070000) { - // winerror &= 0x0000FFFF; - // } + if winerror as u32 & 0xffff_0000 == 0x8007_0000 { + winerror &= 0xffff; + } // Winsock error codes (10000-11999) are errno values. if (10000..12000).contains(&winerror) { diff --git a/crates/host_env/src/posix.rs b/crates/host_env/src/posix.rs index a6ae039fd24..79d58188c9f 100644 --- a/crates/host_env/src/posix.rs +++ b/crates/host_env/src/posix.rs @@ -6,14 +6,37 @@ use core::ffi::CStr; #[cfg(all(unix, not(target_os = "redox")))] use core::ptr::NonNull; use std::ffi::{OsStr, OsString}; -#[cfg(target_os = "linux")] use std::os::fd::FromRawFd; use std::os::fd::{AsFd, AsRawFd, BorrowedFd, IntoRawFd, OwnedFd}; use std::path::Path; pub use super::posix_unix_like::*; +pub use crate::os::{AccessMode, F_OK, R_OK, W_OK, X_OK}; pub use libc::{c_char, pid_t}; +#[cfg(target_os = "linux")] +pub mod xattr; + +// CPython caps subprocess extra_groups using NGROUPS_MAX from the target +// headers, not sysconf(_SC_NGROUPS_MAX). These are the verified header values; +// leave other targets uncapped until their compile-time limit is available. +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub const SUBPROCESS_MAX_GROUPS: Option = Some(65_536); +#[cfg(target_os = "macos")] +pub const SUBPROCESS_MAX_GROUPS: Option = Some(16); +#[cfg(any(target_os = "freebsd", target_os = "netbsd"))] +pub const SUBPROCESS_MAX_GROUPS: Option = Some(libc::NGROUPS_MAX as usize); +#[cfg(not(any( + all(target_os = "linux", target_env = "gnu"), + target_os = "macos", + target_os = "freebsd", + target_os = "netbsd", +)))] +pub const SUBPROCESS_MAX_GROUPS: Option = None; + +/// `` on glibc defines NODEV as `(dev_t)-1`. +#[cfg(all(target_os = "linux", target_env = "gnu"))] +pub const NODEV: i32 = -1; /// ``. The `libc` crate does not bind these. pub const EX_OK: i32 = 0; @@ -407,15 +430,20 @@ pub struct PosixSpawnConfig<'a> { } pub fn set_inheritable(fd: BorrowedFd<'_>, inheritable: bool) -> std::io::Result<()> { + set_inheritable_raw(fd.as_raw_fd(), inheritable) +} + +/// Set inheritance for an integer descriptor without asserting that it is open. +pub fn set_inheritable_raw(fd: i32, inheritable: bool) -> std::io::Result<()> { use nix::fcntl; - let flags = fcntl::FdFlag::from_bits_truncate( - fcntl::fcntl(fd, fcntl::FcntlArg::F_GETFD).map_err(std::io::Error::from)?, - ); + let flags = fcntl::FdFlag::from_bits_truncate(nix::errno::Errno::result(unsafe { + libc::fcntl(fd, libc::F_GETFD) + })?); let mut new_flags = flags; new_flags.set(fcntl::FdFlag::FD_CLOEXEC, !inheritable); if flags != new_flags { - fcntl::fcntl(fd, fcntl::FcntlArg::F_SETFD(new_flags)).map_err(std::io::Error::from)?; + nix::errno::Errno::result(unsafe { libc::fcntl(fd, libc::F_SETFD, new_flags.bits()) })?; } Ok(()) } @@ -569,6 +597,67 @@ pub fn statvfs_fd(fd: i32) -> std::io::Result { } } +#[cfg(not(target_os = "redox"))] +pub fn mkfifo(path: &CStr, mode: libc::mode_t) -> std::io::Result<()> { + let ret = unsafe { libc::mkfifo(path.as_ptr(), mode) }; + if ret == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(target_vendor = "apple")] +type MkfifoAt = unsafe extern "C" fn(libc::c_int, *const libc::c_char, libc::mode_t) -> libc::c_int; + +#[cfg(target_vendor = "apple")] +fn mkfifoat_symbol() -> Option { + static MKFIFOAT: std::sync::OnceLock> = std::sync::OnceLock::new(); + *MKFIFOAT.get_or_init(|| { + // mkfifoat was added in macOS 13 / iOS 16. Resolve it at runtime so + // ordinary mkfifo remains usable on older Apple systems. + let symbol = unsafe { libc::dlsym(libc::RTLD_DEFAULT, c"mkfifoat".as_ptr()) }; + if symbol.is_null() { + None + } else { + // SAFETY: the system symbol has the MkfifoAt signature and stays + // loaded for the lifetime of the process. + Some(unsafe { core::mem::transmute::<*mut libc::c_void, MkfifoAt>(symbol) }) + } + }) +} + +#[cfg(not(target_os = "redox"))] +pub fn has_mkfifoat() -> bool { + #[cfg(target_vendor = "apple")] + { + mkfifoat_symbol().is_some() + } + #[cfg(not(target_vendor = "apple"))] + { + !cfg!(target_os = "android") + } +} + +#[cfg(not(any(target_os = "redox", target_os = "android")))] +pub fn mkfifoat(dir_fd: i32, path: &CStr, mode: libc::mode_t) -> std::io::Result<()> { + #[cfg(target_vendor = "apple")] + let mkfifoat = mkfifoat_symbol().ok_or_else(|| { + std::io::Error::new( + std::io::ErrorKind::Unsupported, + "mkfifoat unavailable on this platform", + ) + })?; + #[cfg(not(target_vendor = "apple"))] + let mkfifoat = libc::mkfifoat; + let ret = unsafe { mkfifoat(dir_fd, path.as_ptr(), mode) }; + if ret == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + #[cfg(not(target_os = "redox"))] pub fn mknod(path: &CStr, mode: libc::mode_t, device: libc::dev_t) -> std::io::Result<()> { let ret = unsafe { libc::mknod(path.as_ptr(), mode, device) }; @@ -632,7 +721,15 @@ pub fn fork() -> std::io::Result { } pub fn write_fd(fd: BorrowedFd<'_>, buf: &[u8]) -> std::io::Result { - nix::unistd::write(fd, buf).map_err(std::io::Error::from) + write_fd_raw(fd.as_raw_fd(), buf) +} + +/// Write through an integer descriptor, reporting invalid descriptors as OS errors. +pub fn write_fd_raw(fd: i32, buf: &[u8]) -> std::io::Result { + let ret = unsafe { libc::write(fd, buf.as_ptr().cast(), buf.len()) }; + nix::errno::Errno::result(ret) + .map(|n| n as usize) + .map_err(std::io::Error::from) } pub fn pread(fd: i32, buf: &mut [u8], offset: libc::off_t) -> std::io::Result { @@ -762,12 +859,12 @@ pub fn fchmod(fd: BorrowedFd<'_>, mode: u32) -> std::io::Result<()> { #[cfg(target_os = "redox")] pub fn utimes( path: &Path, - acc: core::time::Duration, - modif: core::time::Duration, + acc: crate::os::FileTime, + modif: crate::os::FileTime, ) -> std::io::Result<()> { - let tv = |d: core::time::Duration| libc::timeval { - tv_sec: d.as_secs() as _, - tv_usec: d.subsec_micros() as _, + let tv = |time: crate::os::FileTime| libc::timeval { + tv_sec: time.seconds, + tv_usec: (time.nanoseconds / 1_000) as _, }; nix::sys::stat::utimes(path, &tv(acc).into(), &tv(modif).into()).map_err(std::io::Error::from) } @@ -776,13 +873,13 @@ pub fn utimes( pub fn set_file_times_at( dir_fd: i32, path: &CStr, - access: core::time::Duration, - modified: core::time::Duration, + access: crate::os::FileTime, + modified: crate::os::FileTime, follow_symlinks: bool, ) -> std::io::Result<()> { - let ts = |d: core::time::Duration| libc::timespec { - tv_sec: d.as_secs() as _, - tv_nsec: d.subsec_nanos() as _, + let ts = |time: crate::os::FileTime| libc::timespec { + tv_sec: time.seconds, + tv_nsec: time.nanoseconds as _, }; let times = [ts(access), ts(modified)]; let ret = unsafe { @@ -882,6 +979,7 @@ pub fn get_number_of_os_threads() -> isize { 0 } +#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita",))] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct Permissions { pub is_readable: bool, @@ -889,21 +987,8 @@ pub struct Permissions { pub is_executable: bool, } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum AccessError { - InvalidMode, - Os(i32), -} - -impl From for AccessError { - fn from(value: std::io::Error) -> Self { - Self::Os(value.raw_os_error().unwrap_or(0)) - } -} - -pub use crate::os::{AccessMode, F_OK, R_OK, W_OK, X_OK}; - -fn get_permissions(mode: u32) -> Permissions { +#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita",))] +const fn get_permissions(mode: u32) -> Permissions { Permissions { is_readable: mode & 4 != 0, is_writable: mode & 2 != 0, @@ -911,6 +996,7 @@ fn get_permissions(mode: u32) -> Permissions { } } +#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita",))] pub fn get_right_permission( mode: u32, file_owner: u32, @@ -966,32 +1052,50 @@ pub fn getgroups() -> std::io::Result> { Err(std::io::Error::from_raw_os_error(libc::EOPNOTSUPP)) } -pub fn check_access(path: &Path, mode: u8) -> Result { +#[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita",))] +pub fn check_access( + dir_fd: Option>, + path: &Path, + mode: u8, + effective_ids: bool, + follow_symlinks: bool, +) -> bool { use std::os::unix::fs::MetadataExt; let Some(mode) = AccessMode::from_bits(mode) else { - return Err(AccessError::InvalidMode); + return false; }; - let metadata = match crate::fs::metadata(path) { - Ok(m) => m, - Err(_) => return Ok(false), + let Ok(metadata) = crate::fs::metadata(path) else { + return false; }; if mode.is_empty() { - return Ok(true); + return true; } - let perm = get_right_permission(metadata.mode(), metadata.uid(), metadata.gid())?; + let Ok(perm) = get_right_permission(metadata.mode(), metadata.uid(), metadata.gid()) else { + return false; + }; let r_ok = !mode.contains(&crate::os::AccessFlag::R) || perm.is_readable; let w_ok = !mode.contains(&crate::os::AccessFlag::W) || perm.is_writable; let x_ok = !mode.contains(&crate::os::AccessFlag::X) || perm.is_executable; - Ok(r_ok && w_ok && x_ok) + r_ok && w_ok && x_ok } pub fn close_fds(above: i32, keep: &[BorrowedFd<'_>]) { + close_fds_impl(above, keep) +} + +/// Close child descriptors using a sorted list of integer descriptors to keep. +/// No validity or ownership is inferred from the integers. +pub fn close_fds_raw(above: i32, keep: &[i32]) { + close_fds_impl(above, keep) +} + +fn close_fds_impl(above: i32, keep: &[Fd]) { #[cfg(not(target_os = "redox"))] if close_dir_fds(above, keep).is_ok() { return; @@ -1015,9 +1119,60 @@ pub fn setup_child_fds( errwrite: i32, errpipe_read: i32, ) -> std::io::Result<()> { - for &fd in fds_to_keep { - if fd.as_raw_fd() != errpipe_write.as_raw_fd() { - set_inheritable(fd, true)?; + setup_child_fds_impl( + fds_to_keep, + errpipe_write.as_raw_fd(), + p2cread, + p2cwrite, + c2pread, + c2pwrite, + errread, + errwrite, + errpipe_read, + ) +} + +/// Prepare child descriptors without borrowing user-supplied descriptor integers. +#[allow(clippy::too_many_arguments)] +pub fn setup_child_fds_raw( + fds_to_keep: &[i32], + errpipe_write: i32, + p2cread: i32, + p2cwrite: i32, + c2pread: i32, + c2pwrite: i32, + errread: i32, + errwrite: i32, + errpipe_read: i32, +) -> std::io::Result<()> { + setup_child_fds_impl( + fds_to_keep, + errpipe_write, + p2cread, + p2cwrite, + c2pread, + c2pwrite, + errread, + errwrite, + errpipe_read, + ) +} + +#[allow(clippy::too_many_arguments)] +fn setup_child_fds_impl( + fds_to_keep: &[Fd], + errpipe_write: i32, + p2cread: i32, + p2cwrite: i32, + c2pread: i32, + c2pwrite: i32, + errread: i32, + errwrite: i32, + errpipe_read: i32, +) -> std::io::Result<()> { + for fd in fds_to_keep { + if fd.as_raw_fd() != errpipe_write { + set_inheritable_raw(fd.as_raw_fd(), true)?; } } @@ -1029,8 +1184,7 @@ pub fn setup_child_fds( nix::unistd::close(errpipe_read).map_err(std::io::Error::from)?; let c2pwrite = if c2pwrite == 0 { - let fd = unsafe { BorrowedFd::borrow_raw(c2pwrite) }; - let dup = nix::unistd::dup(fd).map_err(std::io::Error::from)?; + let dup = dup_raw(c2pwrite)?; set_inheritable(dup.as_fd(), true)?; dup.into_raw_fd() } else { @@ -1039,8 +1193,7 @@ pub fn setup_child_fds( let mut errwrite = errwrite; while errwrite == 0 || errwrite == 1 { - let fd = unsafe { BorrowedFd::borrow_raw(errwrite) }; - let dup = nix::unistd::dup(fd).map_err(std::io::Error::from)?; + let dup = dup_raw(errwrite)?; set_inheritable(dup.as_fd(), true)?; errwrite = dup.into_raw_fd(); } @@ -1051,20 +1204,23 @@ pub fn setup_child_fds( Ok(()) } +fn dup_raw(fd: i32) -> std::io::Result { + let duplicate = nix::errno::Errno::result(unsafe { libc::dup(fd) })?; + // SAFETY: a successful dup returns a new, owned descriptor. + Ok(unsafe { OwnedFd::from_raw_fd(duplicate) }) +} + fn dup_into_stdio(fd: i32, io_fd: i32) -> std::io::Result<()> { if fd < 0 { return Ok(()); } - let fd = unsafe { BorrowedFd::borrow_raw(fd) }; - if fd.as_raw_fd() == io_fd { - set_inheritable(fd, true) + if fd == io_fd { + set_inheritable_raw(fd, true) } else { - match io_fd { - 0 => nix::unistd::dup2_stdin(fd).map_err(std::io::Error::from), - 1 => nix::unistd::dup2_stdout(fd).map_err(std::io::Error::from), - 2 => nix::unistd::dup2_stderr(fd).map_err(std::io::Error::from), - _ => unreachable!(), - } + debug_assert!((0..=2).contains(&io_fd)); + nix::errno::Errno::result(unsafe { libc::dup2(fd, io_fd) }) + .map(drop) + .map_err(std::io::Error::from) } } @@ -1087,13 +1243,22 @@ pub fn sync() { unsafe { libc::sync() }; } -pub fn getlogin() -> Option { +pub fn getlogin() -> std::io::Result { + let old_errno = crate::os::get_errno(); + crate::os::clear_errno(); let ptr = unsafe { libc::getlogin() }; - if ptr.is_null() { - None + let result = if ptr.is_null() { + let errno = crate::os::get_errno(); + Err(if errno == 0 { + std::io::Error::other("unable to determine login name") + } else { + std::io::Error::from_raw_os_error(errno) + }) } else { - Some(unsafe { CStr::from_ptr(ptr) }.to_owned()) - } + Ok(unsafe { CStr::from_ptr(ptr) }.to_owned()) + }; + crate::os::set_errno(old_errno); + result } pub fn restore_signals() { @@ -1884,26 +2049,81 @@ pub fn posix_spawn(config: PosixSpawnConfig<'_>) -> std::io::Result #[cfg(target_os = "linux")] pub fn sendfile( + out_fd: i32, + in_fd: i32, + offset: Option<&mut crate::crt_fd::Offset>, + count: usize, +) -> std::io::Result { + let offset = offset.map_or(core::ptr::null_mut(), |offset| offset as *mut _); + // The syscall validates raw descriptor numbers; no Rust fd lifetime is claimed. + let result = unsafe { libc::sendfile(out_fd, in_fd, offset, count) }; + if result < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(result as usize) + } +} + +#[cfg(target_os = "linux")] +/// Send from the input descriptor's current position and update that position. +pub fn sendfile_no_offset( out_fd: BorrowedFd<'_>, in_fd: BorrowedFd<'_>, - offset: &mut crate::crt_fd::Offset, count: usize, ) -> std::io::Result { - nix::sys::sendfile::sendfile(out_fd, in_fd, Some(offset), count).map_err(std::io::Error::from) + nix::sys::sendfile::sendfile(out_fd, in_fd, None, count).map_err(std::io::Error::from) } #[cfg(target_os = "macos")] pub fn sendfile( - in_fd: BorrowedFd<'_>, - out_fd: BorrowedFd<'_>, + in_fd: i32, + out_fd: i32, offset: crate::crt_fd::Offset, - count: i64, + written: &mut i64, headers: Option<&[&[u8]]>, trailers: Option<&[&[u8]]>, -) -> (std::io::Result<()>, i64) { - let (res, written) = - nix::sys::sendfile::sendfile(in_fd, out_fd, offset, Some(count), headers, trailers); - (res.map_err(std::io::Error::from), written) + flags: i32, +) -> std::io::Result<()> { + let header_count = headers.map_or(0, |buffers| buffers.len()); + let trailer_count = trailers.map_or(0, |buffers| buffers.len()); + let (Ok(header_count), Ok(trailer_count)) = + (i32::try_from(header_count), i32::try_from(trailer_count)) + else { + return Err(std::io::Error::from(std::io::ErrorKind::InvalidInput)); + }; + let iovecs = |buffers: Option<&[&[u8]]>| { + buffers + .unwrap_or_default() + .iter() + .map(|buffer| libc::iovec { + iov_base: buffer.as_ptr().cast_mut().cast(), + iov_len: buffer.len(), + }) + .collect::>() + }; + let mut headers = iovecs(headers); + let mut trailers = iovecs(trailers); + let mut hdtr = libc::sf_hdtr { + headers: if headers.is_empty() { + core::ptr::null_mut() + } else { + headers.as_mut_ptr() + }, + hdr_cnt: header_count, + trailers: if trailers.is_empty() { + core::ptr::null_mut() + } else { + trailers.as_mut_ptr() + }, + trl_cnt: trailer_count, + }; + // The slices and both iovec arrays remain live for this synchronous call. + let result = unsafe { libc::sendfile(in_fd, out_fd, offset, written, &mut hdtr, flags) }; + if result < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(()) + } } #[cfg(any( @@ -1999,15 +2219,12 @@ pub fn exec_replace>( first_err.unwrap_or_else(nix::errno::Errno::last) } -fn should_keep(above: i32, keep: &[BorrowedFd<'_>], fd: i32) -> bool { - fd > above - && keep - .binary_search_by_key(&fd, BorrowedFd::as_raw_fd) - .is_err() +fn should_keep(above: i32, keep: &[Fd], fd: i32) -> bool { + fd > above && keep.binary_search_by_key(&fd, AsRawFd::as_raw_fd).is_err() } #[cfg(not(target_os = "redox"))] -fn close_dir_fds(above: i32, keep: &[BorrowedFd<'_>]) -> nix::Result<()> { +fn close_dir_fds(above: i32, keep: &[Fd]) -> nix::Result<()> { use nix::{dir::Dir, fcntl::OFlag}; use std::os::fd::AsRawFd; @@ -2046,7 +2263,7 @@ fn close_dir_fds(above: i32, keep: &[BorrowedFd<'_>]) -> nix::Result<()> { } #[cfg(target_os = "redox")] -fn close_filetable_fds(above: i32, keep: &[BorrowedFd<'_>]) -> nix::Result<()> { +fn close_filetable_fds(above: i32, keep: &[Fd]) -> nix::Result<()> { use nix::fcntl; use std::os::fd::AsRawFd; @@ -2083,7 +2300,7 @@ fn close_filetable_fds(above: i32, keep: &[BorrowedFd<'_>]) -> nix::Result<()> { Ok(()) } -fn close_fds_brute_force(above: i32, keep: &[BorrowedFd<'_>]) { +fn close_fds_brute_force(above: i32, keep: &[Fd]) { debug_assert!( keep.windows(2) .all(|fds| fds[0].as_raw_fd() <= fds[1].as_raw_fd()), @@ -2098,7 +2315,7 @@ fn close_fds_brute_force(above: i32, keep: &[BorrowedFd<'_>]) { let mut prev = above; for fd in keep .iter() - .map(BorrowedFd::as_raw_fd) + .map(AsRawFd::as_raw_fd) .chain(core::iter::once(max_fd)) { for candidate in prev + 1..fd { @@ -2123,3 +2340,82 @@ impl IntParser { Ok(()) } } + +#[cfg(test)] +mod subprocess_raw_fd_tests { + use super::*; + + fn pipe_above_stdio() -> (OwnedFd, OwnedFd) { + let duplicate = |fd: OwnedFd, minimum| { + let raw = + nix::fcntl::fcntl(&fd, nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(minimum)).unwrap(); + // SAFETY: F_DUPFD_CLOEXEC returned a fresh descriptor owned by this test. + unsafe { OwnedFd::from_raw_fd(raw) } + }; + let (reader, writer) = nix::unistd::pipe().unwrap(); + // pipe() orders endpoints by direction, not descriptor number. Allocate + // the fixture above stderr and in the order required by the keep list. + let reader = duplicate(reader, 3); + let writer = duplicate(writer, reader.as_raw_fd() + 1); + (reader, writer) + } + + #[test] + fn invalid_raw_descriptors_return_ebadf() { + for err in [ + set_inheritable_raw(-1, true).unwrap_err(), + write_fd_raw(-1, b"x").unwrap_err(), + dup_raw(-1).unwrap_err(), + ] { + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + } + } + + #[test] + fn invalid_kept_descriptor_stops_before_child_setup() { + // The first operation fails, before any close or stdio redirection. + let err = setup_child_fds_raw(&[-1], -2, -1, -1, -1, -1, -1, -1, -1).unwrap_err(); + assert_eq!(err.raw_os_error(), Some(libc::EBADF)); + } + + #[test] + fn raw_and_borrowed_keep_lists_select_the_same_descriptors() { + let (reader, writer) = pipe_above_stdio(); + let raw = [reader.as_raw_fd(), writer.as_raw_fd()]; + assert!(raw[0] > 2 && raw[1] > raw[0]); + let borrowed = [reader.as_fd(), writer.as_fd()]; + for candidate in [2, raw[0], raw[1], raw[1] + 1] { + assert_eq!( + should_keep(2, &raw, candidate), + should_keep(2, &borrowed, candidate) + ); + } + assert!(!should_keep(2, &raw, raw[0])); + assert!(should_keep(2, &raw, raw[1] + 1)); + } + + #[test] + fn raw_helpers_preserve_pipe_ownership_and_flags() { + let (reader, writer) = pipe_above_stdio(); + assert!(reader.as_raw_fd() > 2 && writer.as_raw_fd() > 2); + let high = nix::fcntl::fcntl(&writer, nix::fcntl::FcntlArg::F_DUPFD_CLOEXEC(64)).unwrap(); + // SAFETY: F_DUPFD_CLOEXEC returned a fresh descriptor owned by this test. + let high = unsafe { OwnedFd::from_raw_fd(high) }; + let fd = high.as_raw_fd(); + assert!(fd >= 64); + let flags = || nix::fcntl::fcntl(&high, nix::fcntl::FcntlArg::F_GETFD).unwrap(); + assert_ne!(flags() & libc::FD_CLOEXEC, 0); + set_inheritable_raw(fd, true).unwrap(); + assert_eq!(flags() & libc::FD_CLOEXEC, 0); + set_inheritable(high.as_fd(), false).unwrap(); + assert_ne!(flags() & libc::FD_CLOEXEC, 0); + assert_eq!(write_fd_raw(fd, b"x").unwrap(), 1); + let mut buf = [0]; + assert_eq!(nix::unistd::read(&reader, &mut buf).unwrap(), 1); + assert_eq!(buf, *b"x"); + let duplicate = dup_raw(fd).unwrap(); + assert_eq!(write_fd(duplicate.as_fd(), b"y").unwrap(), 1); + assert_eq!(nix::unistd::read(&reader, &mut buf).unwrap(), 1); + assert_eq!(buf, *b"y"); + } +} diff --git a/crates/host_env/src/posix/xattr.rs b/crates/host_env/src/posix/xattr.rs new file mode 100644 index 00000000000..f0653d3e7ef --- /dev/null +++ b/crates/host_env/src/posix/xattr.rs @@ -0,0 +1,106 @@ +// spell-checker:disable + +use core::ffi::CStr; +use std::io; + +// Linux limits from . +pub const XATTR_SIZE_MAX: usize = 65_536; +const XATTR_LIST_MAX: usize = 65_536; + +/// Paths use a C string; a Python descriptor is deliberately an unchecked +/// integer so EBADF is reported by the OS without inventing a BorrowedFd. +pub enum Target<'path> { + Follow(&'path CStr), + NoFollow(&'path CStr), + Fd(i32), +} + +impl Target<'_> { + pub fn get(&self, name: &CStr) -> io::Result> { + read::<128, XATTR_SIZE_MAX>(|buf| { + let ptr = buf.as_mut_ptr().cast(); + let len = buf.len(); + // SAFETY: paths and name are NUL-terminated; buf is valid for len writes. + unsafe { + match self { + Self::Follow(path) => libc::getxattr(path.as_ptr(), name.as_ptr(), ptr, len), + Self::NoFollow(path) => libc::lgetxattr(path.as_ptr(), name.as_ptr(), ptr, len), + Self::Fd(fd) => libc::fgetxattr(*fd, name.as_ptr(), ptr, len), + } + } + }) + } + + pub fn list(&self) -> io::Result> { + read::<256, XATTR_LIST_MAX>(|buf| { + let ptr = buf.as_mut_ptr().cast(); + let len = buf.len(); + // SAFETY: paths are NUL-terminated; buf is valid for len writes. + unsafe { + match self { + Self::Follow(path) => libc::listxattr(path.as_ptr(), ptr, len), + Self::NoFollow(path) => libc::llistxattr(path.as_ptr(), ptr, len), + Self::Fd(fd) => libc::flistxattr(*fd, ptr, len), + } + } + }) + } + + pub fn set(&self, name: &CStr, value: &[u8], flags: i32) -> io::Result<()> { + let ptr = value.as_ptr().cast(); + let len = value.len(); + // SAFETY: paths and name are NUL-terminated; value is valid for len reads. + let result = unsafe { + match self { + Self::Follow(path) => libc::setxattr(path.as_ptr(), name.as_ptr(), ptr, len, flags), + Self::NoFollow(path) => { + libc::lsetxattr(path.as_ptr(), name.as_ptr(), ptr, len, flags) + } + Self::Fd(fd) => libc::fsetxattr(*fd, name.as_ptr(), ptr, len, flags), + } + }; + cvt(result as isize).map(drop) + } + + pub fn remove(&self, name: &CStr) -> io::Result<()> { + // SAFETY: paths and name are NUL-terminated; descriptors remain integers. + let result = unsafe { + match self { + Self::Follow(path) => libc::removexattr(path.as_ptr(), name.as_ptr()), + Self::NoFollow(path) => libc::lremovexattr(path.as_ptr(), name.as_ptr()), + Self::Fd(fd) => libc::fremovexattr(*fd, name.as_ptr()), + } + }; + cvt(result as isize).map(drop) + } +} + +fn cvt(result: isize) -> io::Result { + usize::try_from(result).map_err(|_| io::Error::last_os_error()) +} + +// Match CPython's bounded two attempts, without a size-query race. +fn read( + mut call: impl FnMut(&mut [u8]) -> isize, +) -> io::Result> { + let mut small = [0; SMALL]; + match cvt(call(&mut small)) { + Ok(size) => { + let mut out = Vec::new(); + out.try_reserve_exact(size) + .map_err(|_| io::ErrorKind::OutOfMemory)?; + out.extend_from_slice(&small[..size]); + Ok(out) + } + Err(err) if err.raw_os_error() == Some(libc::ERANGE) => { + let mut out = Vec::new(); + out.try_reserve_exact(MAX) + .map_err(|_| io::ErrorKind::OutOfMemory)?; + out.resize(MAX, 0); + let size = cvt(call(&mut out))?; + out.truncate(size); + Ok(out) + } + Err(err) => Err(err), + } +} diff --git a/crates/host_env/src/posix_unix_like.rs b/crates/host_env/src/posix_unix_like.rs index e318fdbac43..3a7095300f8 100644 --- a/crates/host_env/src/posix_unix_like.rs +++ b/crates/host_env/src/posix_unix_like.rs @@ -4,13 +4,55 @@ use std::{io, path::Path}; use rustix::{ fd::AsFd, - fs::{self, AtFlags}, + fs::{self, Access, AtFlags}, }; pub use rustix::fs::RawMode; use crate::{crt_fd, fileutils::StatStruct}; +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum AccessError { + InvalidMode, + Os(i32), +} + +impl From for AccessError { + fn from(value: io::Error) -> Self { + Self::Os(value.raw_os_error().unwrap_or(0)) + } +} + +/// https://www.man7.org/linux/man-pages/man2/faccessat.2.html +#[cfg(not(any(target_os = "espidf", target_os = "horizon", target_os = "vita")))] +pub fn check_access( + dir_fd: Option>, + path: impl AsRef, + access: u8, + #[cfg_attr(target_os = "android", expect(unused))] effective_ids: bool, + follow_symlinks: bool, +) -> bool { + let dir_fd = dir_fd.as_ref().map_or(fs::CWD, AsFd::as_fd); + let access = Access::from_bits_retain(access as _); + + #[cfg(not(target_os = "android"))] + let flags = if effective_ids { + AtFlags::EACCESS + } else { + AtFlags::empty() + }; + #[cfg(target_os = "android")] + let flags = AtFlags::empty(); + let flags = flags.union(if !follow_symlinks { + AtFlags::SYMLINK_NOFOLLOW + } else { + AtFlags::empty() + }); + + // CPython returns false for all error codes. + fs::accessat(dir_fd, path.as_ref(), access, flags).is_ok() +} + /// https://pubs.opengroup.org/onlinepubs/9799919799/functions/mkdir.html pub fn make_dir( dir_fd: Option>, diff --git a/crates/host_env/src/posix_wasi.rs b/crates/host_env/src/posix_wasi.rs index df09c08bc09..7c055f08426 100644 --- a/crates/host_env/src/posix_wasi.rs +++ b/crates/host_env/src/posix_wasi.rs @@ -1,5 +1,5 @@ use alloc::ffi::CString; -use core::{ffi::CStr, time::Duration}; +use core::ffi::CStr; use rustix::fd::AsFd; use std::{ffi::OsStr, io, path::Path}; @@ -14,13 +14,13 @@ pub fn stat_fd(fd: crate::crt_fd::Borrowed<'_>) -> io::Result io::Result<()> { - let ts = |d: Duration| libc::timespec { - tv_sec: d.as_secs() as _, - tv_nsec: d.subsec_nanos() as _, + let ts = |time: crate::os::FileTime| libc::timespec { + tv_sec: time.seconds, + tv_nsec: time.nanoseconds as _, }; let times = [ts(access), ts(modified)]; unsafe { diff --git a/crates/host_env/src/readline.rs b/crates/host_env/src/readline.rs index f3f468cba56..7f5d09c8f98 100644 --- a/crates/host_env/src/readline.rs +++ b/crates/host_env/src/readline.rs @@ -196,3 +196,217 @@ impl Readline { self.0.readline(prompt) } } + +/// A nested readline must fail rather than consume the outer call's input. +#[derive(Debug)] +pub struct ReentrantReadline; + +#[derive(PartialEq, Eq)] +struct TerminalIdentity { + streams: StreamIdentity, +} + +#[cfg(unix)] +type StreamIdentity = (libc::dev_t, libc::ino_t, libc::dev_t); +#[cfg(windows)] +type StreamIdentity = [usize; 2]; +#[cfg(not(any(unix, windows)))] +type StreamIdentity = (); + +impl TerminalIdentity { + fn current() -> io::Result { + #[cfg(unix)] + let streams = { + let mut stat = core::mem::MaybeUninit::::uninit(); + // Only an input change invalidates read-ahead. Unix rustyline uses + // fd 1 directly, so an output-only change needs no new editor. + if unsafe { libc::fstat(0, stat.as_mut_ptr()) } != 0 { + return Err(io::Error::last_os_error()); + } + let stat = unsafe { stat.assume_init() }; + (stat.st_dev, stat.st_ino, stat.st_rdev) + }; + #[cfg(windows)] + let streams = { + use windows_sys::Win32::System::Console::{STD_INPUT_HANDLE, STD_OUTPUT_HANDLE}; + // Windows rustyline caches both handles, but has no read-ahead + // buffer (ConsoleRawReader::unbuffer returns None). + [ + crate::winapi::get_std_handle(STD_INPUT_HANDLE)?.unwrap_or_default() as usize, + crate::winapi::get_std_handle(STD_OUTPUT_HANDLE)?.unwrap_or_default() as usize, + ] + }; + #[cfg(not(any(unix, windows)))] + let streams = (); + Ok(Self { streams }) + } +} + +struct InputReader { + identity: TerminalIdentity, + reader: Readline<()>, +} + +// stdin is process-wide, not thread-local. Retain read-ahead when the next +// input() runs on another thread, and serialize the terminal's raw-mode guards. +// A reentrant mutex plus a fallible borrow rejects same-thread recursion without +// deadlocking. The reader contains no Python references or interpreter helper. +static INPUT_READER: parking_lot::ReentrantMutex>> = + parking_lot::ReentrantMutex::new(core::cell::RefCell::new(None)); + +/// Read an interactive input line with the process's retained terminal reader. +/// The VM must detach while waiting for both the lock and terminal input. +pub fn input_readline(prompt: &str) -> Result { + let guard = INPUT_READER.lock(); + let mut slot = guard.try_borrow_mut().map_err(|_| ReentrantReadline)?; + let identity = match TerminalIdentity::current() { + Ok(identity) => identity, + Err(error) => return Ok(ReadlineResult::Io(error)), + }; + if slot + .as_ref() + .is_none_or(|reader| reader.identity != identity) + { + *slot = Some(InputReader { + identity, + reader: Readline::new(()), + }); + } + Ok(slot.as_mut().unwrap().reader.readline(prompt)) +} + +/// Borrow the shared buffered stdin for one physical read. The caller retains +/// partial bytes across EINTR and checks signals after this lock is released. +pub fn stdio_readline_bytes(prompt: &str, line: &mut Vec) -> io::Result { + use std::io::Write; + let mut stderr = io::stderr().lock(); + stderr.write_all(prompt.as_bytes())?; + stderr.flush()?; + drop(stderr); + read_line_bytes(&mut io::stdin().lock(), line) +} + +fn read_line_bytes(reader: &mut impl io::BufRead, line: &mut Vec) -> io::Result { + let mut read = 0; + loop { + // Unlike read_until, return Interrupted to the VM before retrying. + let available = reader.fill_buf()?; + if available.is_empty() { + return Ok(read); + } + let newline = available.iter().position(|&byte| byte == b'\n'); + let used = newline.map_or(available.len(), |index| index + 1); + line.extend_from_slice(&available[..used]); + reader.consume(used); + read += used; + if newline.is_some() { + return Ok(read); + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn nested_input_is_rejected_before_touching_the_terminal() { + let guard = super::INPUT_READER.lock(); + let _active_reader = guard.borrow_mut(); + assert!(matches!( + super::input_readline(""), + Err(super::ReentrantReadline) + )); + } + + use super::read_line_bytes; + use std::io::{self, BufRead, Read}; + + struct ScriptedReader { + chunks: alloc::collections::VecDeque>>, + consumed: usize, + } + + impl ScriptedReader { + fn new(chunks: impl IntoIterator>>) -> Self { + Self { + chunks: chunks.into_iter().collect(), + consumed: 0, + } + } + } + + impl Read for ScriptedReader { + fn read(&mut self, _: &mut [u8]) -> io::Result { + unreachable!("the transport uses BufRead directly") + } + } + + impl BufRead for ScriptedReader { + fn fill_buf(&mut self) -> io::Result<&[u8]> { + if self.chunks.front().is_some_and(Result::is_err) { + return Err(self.chunks.pop_front().unwrap().unwrap_err()); + } + Ok(self + .chunks + .front() + .map_or(&[], |chunk| &chunk.as_ref().unwrap()[self.consumed..])) + } + + fn consume(&mut self, amount: usize) { + self.consumed += amount; + if self.consumed == self.chunks.front().unwrap().as_ref().unwrap().len() { + self.chunks.pop_front(); + self.consumed = 0; + } + } + } + + #[test] + fn physical_lines_preserve_buffered_remainder_and_count_only_new_bytes() { + let mut reader = ScriptedReader::new([Ok(b"one\ntwo\ntail".to_vec())]); + let mut line = b"prefix".to_vec(); + assert_eq!(read_line_bytes(&mut reader, &mut line).unwrap(), 4); + assert_eq!(line, b"prefixone\n"); + line.clear(); + assert_eq!(read_line_bytes(&mut reader, &mut line).unwrap(), 4); + assert_eq!(line, b"two\n"); + line.clear(); + assert_eq!(read_line_bytes(&mut reader, &mut line).unwrap(), 4); + assert_eq!(line, b"tail"); + assert_eq!(read_line_bytes(&mut reader, &mut line).unwrap(), 0); + assert_eq!(line, b"tail"); + } + + #[test] + fn errors_return_immediately_and_leave_partial_bytes_for_the_caller() { + for kind in [io::ErrorKind::Interrupted, io::ErrorKind::Other] { + let mut reader = ScriptedReader::new([ + Ok(b"part".to_vec()), + Err(io::Error::from(kind)), + Ok(b"ial\nnext".to_vec()), + ]); + let mut line = Vec::new(); + assert_eq!( + read_line_bytes(&mut reader, &mut line).unwrap_err().kind(), + kind + ); + assert_eq!(line, b"part"); + assert_eq!(read_line_bytes(&mut reader, &mut line).unwrap(), 4); + assert_eq!(line, b"partial\n"); + } + } + + #[test] + fn eof_after_interruption_keeps_partial_bytes() { + let mut reader = ScriptedReader::new([ + Ok(b"partial".to_vec()), + Err(io::Error::from(io::ErrorKind::Interrupted)), + ]); + let mut line = Vec::new(); + assert_eq!( + read_line_bytes(&mut reader, &mut line).unwrap_err().kind(), + io::ErrorKind::Interrupted + ); + assert_eq!(read_line_bytes(&mut reader, &mut line).unwrap(), 0); + assert_eq!(line, b"partial"); + } +} diff --git a/crates/host_env/src/remote_debugging/children.rs b/crates/host_env/src/remote_debugging/children.rs new file mode 100644 index 00000000000..fc3983e7df7 --- /dev/null +++ b/crates/host_env/src/remote_debugging/children.rs @@ -0,0 +1,246 @@ +//! Process-tree snapshots, independent of remote stack-unwinding support. +use std::io; + +#[derive(Debug)] +pub enum Error { + Os(io::Error), + Proc { + error: io::Error, + operation: Option<&'static str>, + }, + Memory, + Unsupported, + Message(&'static str), +} + +impl From for Error { + fn from(error: io::Error) -> Self { + Self::Os(error) + } +} + +fn push(items: &mut Vec, item: T) -> Result<(), Error> { + items.try_reserve(1).map_err(|_| Error::Memory)?; + items.push(item); + Ok(()) +} + +pub(super) fn enumerate(pid: i32, recursive: bool) -> Result, Error> { + let processes = snapshot()?; + let mut result = Vec::new(); + let mut pending = Vec::new(); + push(&mut pending, pid)?; + let mut next = 0; + while let Some(&parent) = pending.get(next) { + next += 1; + // Preserve the platform snapshot order, like CPython's BFS. + for &(child, ppid) in &processes { + if ppid == parent && !result.contains(&child) { + push(&mut result, child)?; + if recursive { + push(&mut pending, child)?; + } + } + } + if !recursive { + break; + } + } + Ok(result) +} + +#[cfg(any(target_os = "linux", target_os = "android"))] +fn snapshot() -> Result, Error> { + use core::{ffi::CStr, ptr::NonNull}; + use std::{fs::File, io::Read}; + + struct Directory(Option>); + impl Directory { + fn close(&mut self) -> io::Result<()> { + if let Some(directory) = self.0.take() { + // SAFETY: this uniquely owned handle came from opendir and is + // taken before closing, including on a failed close. + if unsafe { libc::closedir(directory.as_ptr()) } != 0 { + return Err(io::Error::last_os_error()); + } + } + Ok(()) + } + } + impl Drop for Directory { + fn drop(&mut self) { + let _ = self.close(); + } + } + + fn parent(pid: i32) -> Option { + let mut file = File::open(format!("/proc/{pid}/stat")).ok()?; + // CPython reads at most 2047 bytes of stat, once. + let mut bytes = [0_u8; 2047]; + let count = file.read(&mut bytes).ok()?; + let bytes = &bytes[..count]; + let end = bytes.iter().rposition(|&byte| byte == b')')?; + let tail = bytes.get(end + 2..)?; + let mut fields = tail + .split(|byte| byte.is_ascii_whitespace()) + .filter(|s| !s.is_empty()); + fields.next()?; // process state + let ppid = core::str::from_utf8(fields.next()?).ok()?.parse().ok()?; + (ppid >= 0).then_some(ppid) + } + + // SAFETY: the path is a static NUL-terminated string. + let pointer = + NonNull::new(unsafe { libc::opendir(c"/proc".as_ptr()) }).ok_or_else(|| Error::Proc { + error: io::Error::last_os_error(), + operation: None, + })?; + let mut directory = Directory(Some(pointer)); + let mut processes = Vec::new(); + loop { + crate::os::clear_errno(); + // SAFETY: pointer remains open for this loop; the entry is consumed + // before the next readdir call, with no concurrent access to the DIR. + let entry = unsafe { libc::readdir(pointer.as_ptr()) }; + if entry.is_null() { + let errno = crate::os::get_errno(); + if errno != 0 { + return Err(Error::Proc { + error: io::Error::from_raw_os_error(errno), + operation: Some("read"), + }); + } + break; + } + // SAFETY: readdir supplies a NUL-terminated d_name valid until its next call. + let name = unsafe { CStr::from_ptr((*entry).d_name.as_ptr()) }.to_bytes(); + if !matches!(name.first(), Some(b'1'..=b'9')) || !name.iter().all(u8::is_ascii_digit) { + continue; + } + let Some(pid) = core::str::from_utf8(name) + .ok() + .and_then(|name| name.parse::().ok()) + else { + continue; + }; + if let Some(ppid) = parent(pid) { + push(&mut processes, (pid, ppid))?; + } + } + directory.close().map_err(|error| Error::Proc { + error, + operation: Some("close"), + })?; + Ok(processes) +} + +#[cfg(target_os = "macos")] +fn snapshot() -> Result, Error> { + use core::{mem::size_of, ptr}; + + // Apple's ; libc exposes the functions but not this constant. + const PROC_ALL_PIDS: u32 = 1; + // SAFETY: a null buffer and zero size query the required byte count. + let count = unsafe { libc::proc_listpids(PROC_ALL_PIDS, 0, ptr::null_mut(), 0) }; + if count <= 0 { + return Err(Error::Message("Failed to get process count")); + } + let capacity = (count as usize / size_of::()) + .checked_add(64) + .ok_or(Error::Memory)?; + let bytes = capacity + .checked_mul(size_of::()) + .and_then(|size| i32::try_from(size).ok()) + .ok_or(Error::Memory)?; + let mut pids = Vec::::new(); + pids.try_reserve_exact(capacity) + .map_err(|_| Error::Memory)?; + pids.resize(capacity, 0); + // SAFETY: the initialized Vec provides exactly the passed writable byte size. + let actual = unsafe { libc::proc_listpids(PROC_ALL_PIDS, 0, pids.as_mut_ptr().cast(), bytes) }; + if actual <= 0 { + return Err(Error::Message("Failed to list PIDs")); + } + if actual > bytes { + return Err(Error::Message("process list exceeds buffer")); + } + let mut processes = Vec::new(); + for &pid in &pids[..actual as usize / size_of::()] { + // SAFETY: proc_bsdinfo is a C structure of integer and byte-array fields. + let mut info: libc::proc_bsdinfo = unsafe { core::mem::zeroed() }; + // SAFETY: info is a live, aligned buffer of the supplied size. + let got = unsafe { + libc::proc_pidinfo( + pid, + libc::PROC_PIDTBSDINFO, + 0, + (&mut info as *mut libc::proc_bsdinfo).cast(), + size_of::() as i32, + ) + }; + if got == size_of::() as i32 { + push(&mut processes, (pid, info.pbi_ppid as i32))?; + } + } + Ok(processes) +} + +#[cfg(windows)] +fn snapshot() -> Result, Error> { + use windows_sys::Win32::{ + Foundation::{ + CloseHandle, ERROR_NO_MORE_FILES, GetLastError, HANDLE, INVALID_HANDLE_VALUE, + }, + System::Diagnostics::ToolHelp::{ + CreateToolhelp32Snapshot, PROCESSENTRY32W, Process32FirstW, Process32NextW, + TH32CS_SNAPPROCESS, + }, + }; + struct Snapshot(HANDLE); + impl Drop for Snapshot { + fn drop(&mut self) { + // SAFETY: only a valid uniquely owned snapshot is stored here. + unsafe { CloseHandle(self.0) }; + } + } + // SAFETY: snapshot enumeration needs no pointer arguments or process mutation. + let handle = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; + if handle == INVALID_HANDLE_VALUE { + return Err(io::Error::last_os_error().into()); + } + let snapshot = Snapshot(handle); + // SAFETY: PROCESSENTRY32W is a C structure of integer and character-array fields. + let mut entry: PROCESSENTRY32W = unsafe { core::mem::zeroed() }; + entry.dwSize = core::mem::size_of::() as u32; + // SAFETY: the handle is valid and entry is an initialized full-sized buffer. + if unsafe { Process32FirstW(snapshot.0, &mut entry) } == 0 { + return Err(io::Error::last_os_error().into()); + } + let mut processes = Vec::new(); + loop { + push( + &mut processes, + (entry.th32ProcessID as i32, entry.th32ParentProcessID as i32), + )?; + // SAFETY: the same owned snapshot and live buffer remain valid. + if unsafe { Process32NextW(snapshot.0, &mut entry) } == 0 { + // Read the error before Drop closes the snapshot. + let error = unsafe { GetLastError() }; + if error != ERROR_NO_MORE_FILES { + return Err(io::Error::from_raw_os_error(error as i32).into()); + } + break; + } + } + Ok(processes) +} + +#[cfg(not(any( + target_os = "linux", + target_os = "android", + target_os = "macos", + windows +)))] +fn snapshot() -> Result, Error> { + Err(Error::Unsupported) +} diff --git a/crates/host_env/src/remote_debugging/common.rs b/crates/host_env/src/remote_debugging/common.rs new file mode 100644 index 00000000000..a3f9be6982d --- /dev/null +++ b/crates/host_env/src/remote_debugging/common.rs @@ -0,0 +1,62 @@ +use std::io; + +pub(super) const COOKIE: &[u8; 8] = b"xdebugpy"; + +pub(super) trait RemoteRead { + fn read_exact(&mut self, address: u64, destination: &mut [u8]) -> io::Result<()>; +} + +pub(super) fn has_cookie(reader: &mut impl RemoteRead, address: u64) -> io::Result { + if address == 0 { + return Ok(false); + } + let mut bytes = [0; COOKIE.len()]; + match reader.read_exact(address, &mut bytes) { + Ok(()) => Ok(&bytes == COOKIE), + Err(error) if stops_probe(&error) => Err(error), + Err(_) => Ok(false), + } +} + +pub(super) fn stops_probe(error: &io::Error) -> bool { + matches!( + error.kind(), + io::ErrorKind::PermissionDenied | io::ErrorKind::OutOfMemory + ) +} + +pub(super) fn invalid_data(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} + +// These are resource limits, not claims about an unwinder's capabilities. +// Exhaustion is a failed probe, just like inaccessible or missing metadata. +pub(super) struct ReadBudget { + bytes: usize, + calls: usize, +} + +impl ReadBudget { + pub(super) fn new() -> Self { + Self { + bytes: 256 * 1024 * 1024, + calls: 65_536, + } + } + + pub(super) fn consume(&mut self, bytes: usize) -> io::Result<()> { + self.bytes = self.bytes.checked_sub(bytes).ok_or_else(|| { + io::Error::new( + io::ErrorKind::OutOfMemory, + "runtime probe byte budget exhausted", + ) + })?; + self.calls = self.calls.checked_sub(1).ok_or_else(|| { + io::Error::new( + io::ErrorKind::OutOfMemory, + "runtime probe read budget exhausted", + ) + })?; + Ok(()) + } +} diff --git a/crates/host_env/src/remote_debugging/linux.rs b/crates/host_env/src/remote_debugging/linux.rs new file mode 100644 index 00000000000..a237ac47c3a --- /dev/null +++ b/crates/host_env/src/remote_debugging/linux.rs @@ -0,0 +1,190 @@ +use super::{COOKIE, ReadBudget, RemoteRead, has_cookie, invalid_data, object_file, stops_probe}; +use std::{ + ffi::OsStr, + fs::{File, OpenOptions}, + io::{self, Read}, + os::unix::{ffi::OsStrExt, fs::FileExt}, + path::Path, +}; + +const MAX_MAPS_BYTES: u64 = 8 * 1024 * 1024; +const SCAN_CHUNK: usize = 1024 * 1024; + +struct Process { + pid: i32, + memory: Option, + budget: ReadBudget, +} + +impl RemoteRead for Process { + fn read_exact(&mut self, address: u64, destination: &mut [u8]) -> io::Result<()> { + let address = usize::try_from(address) + .map_err(|_| invalid_data("remote address exceeds native pointer width"))?; + address + .checked_add(destination.len()) + .ok_or_else(|| invalid_data("remote read address overflow"))?; + let mut completed = 0; + while completed < destination.len() { + let remaining = &mut destination[completed..]; + self.budget.consume(remaining.len())?; + let current = address + completed; + let count = if let Some(memory) = &self.memory { + memory.read_at(remaining, current as u64)? + } else { + let local = libc::iovec { + iov_base: remaining.as_mut_ptr().cast(), + iov_len: remaining.len(), + }; + let remote = libc::iovec { + iov_base: current as *mut libc::c_void, + iov_len: remaining.len(), + }; + // SAFETY: local names the writable destination slice. The + // remote pointer is only an address for the kernel, never a + // pointer dereferenced by this process. + let result = unsafe { libc::process_vm_readv(self.pid, &local, 1, &remote, 1, 0) }; + if result < 0 { + let error = io::Error::last_os_error(); + if error.raw_os_error() == Some(libc::ENOSYS) { + // Match CPython's fallback only for a missing syscall. + // Permission denials must not select another route. + self.memory = Some( + OpenOptions::new() + .read(true) + .write(true) + .open(format!("/proc/{}/mem", self.pid))?, + ); + continue; + } + return Err(error); + } + result as usize + }; + if count == 0 || count > remaining.len() { + return Err(io::ErrorKind::UnexpectedEof.into()); + } + completed += count; + } + Ok(()) + } +} + +struct Mapping<'a> { + start: u64, + end: u64, + writable: bool, + path: &'a [u8], +} + +fn token<'a>(remaining: &mut &'a [u8]) -> Option<&'a [u8]> { + let source = (*remaining).trim_ascii_start(); + if source.is_empty() { + return None; + } + let end = source + .iter() + .position(u8::is_ascii_whitespace) + .unwrap_or(source.len()); + let (value, rest) = source.split_at(end); + *remaining = rest; + Some(value) +} + +fn mapping(line: &[u8]) -> Option> { + let mut fields = line; + let range = token(&mut fields)?; + let permissions = token(&mut fields)?; + for _ in 0..3 { + token(&mut fields)?; + } + let path = fields.trim_ascii_start(); + if path.is_empty() || (path.starts_with(b"[") && path.ends_with(b"]")) { + return None; + } + let dash = range.iter().position(|byte| *byte == b'-')?; + let parse = |bytes| u64::from_str_radix(core::str::from_utf8(bytes).ok()?, 16).ok(); + let start = parse(&range[..dash])?; + let end = parse(&range[dash + 1..])?; + if start == 0 || end <= start { + return None; + } + Some(Mapping { + start, + end, + writable: permissions.starts_with(b"rw"), + path, + }) +} + +fn scan_deleted(process: &mut Process, mapping: &Mapping<'_>) -> io::Result> { + let mut buffer = vec![0; SCAN_CHUNK]; + let mut address = mapping.start; + while address < mapping.end { + let wanted = usize::try_from((mapping.end - address).min(SCAN_CHUNK as u64)) + .map_err(|_| invalid_data("mapping scan size overflow"))?; + match process.read_exact(address, &mut buffer[..wanted]) { + Ok(()) => { + if let Some(offset) = buffer[..wanted] + .windows(COOKIE.len()) + .position(|bytes| bytes == COOKIE) + { + return Ok(Some(address + offset as u64)); + } + } + Err(error) if stops_probe(&error) => return Err(error), + Err(_) => {} + } + let overlap = COOKIE.len() - 1; + if wanted <= overlap { + break; + } + address = address + .checked_add((wanted - overlap) as u64) + .ok_or_else(|| invalid_data("mapping scan address overflow"))?; + } + Ok(None) +} + +pub(super) fn probe(pid: i32) -> io::Result { + let mut maps = Vec::new(); + File::open(format!("/proc/{pid}/maps"))? + .take(MAX_MAPS_BYTES + 1) + .read_to_end(&mut maps)?; + if maps.len() as u64 > MAX_MAPS_BYTES { + return Err(invalid_data("process map exceeds its size bound")); + } + let mut process = Process { + pid, + memory: None, + budget: ReadBudget::new(), + }; + for line in maps.split(|byte| *byte == b'\n') { + process.budget.consume(0)?; + let Some(mapping) = mapping(line) else { + continue; + }; + let path = Path::new(OsStr::from_bytes(mapping.path)); + let Some(name) = path.file_name() else { + continue; + }; + if !name.as_bytes().windows(6).any(|bytes| bytes == b"python") { + continue; + } + let candidate = if mapping.path.ends_with(b" (deleted)") { + if !mapping.writable { + continue; + } + scan_deleted(&mut process, &mapping) + } else { + object_file::read(path, &mut process.budget).and_then(|bytes| { + object_file::section_address(&bytes, mapping.start, object::BinaryFormat::Elf) + }) + }; + match candidate { + Ok(Some(address)) if has_cookie(&mut process, address)? => return Ok(true), + Err(error) if stops_probe(&error) => return Err(error), + _ => {} + } + } + Ok(false) +} diff --git a/crates/host_env/src/remote_debugging/macos.rs b/crates/host_env/src/remote_debugging/macos.rs new file mode 100644 index 00000000000..c43916628c1 --- /dev/null +++ b/crates/host_env/src/remote_debugging/macos.rs @@ -0,0 +1,281 @@ +use super::{ReadBudget, RemoteRead, has_cookie, invalid_data, object_file, stops_probe}; +use core::mem::size_of; +use mach2::{ + kern_return::{ + KERN_INVALID_ADDRESS, KERN_NO_ACCESS, KERN_PROTECTION_FAILURE, KERN_RESOURCE_SHORTAGE, + KERN_SUCCESS, kern_return_t, + }, + mach_port::mach_port_deallocate, + port::{MACH_PORT_DEAD, MACH_PORT_NULL, mach_port_t}, + traps::{mach_task_self, task_for_pid}, + vm::{mach_vm_read_overwrite, mach_vm_region}, + vm_prot::{VM_PROT_EXECUTE, VM_PROT_READ}, + vm_region::{VM_REGION_BASIC_INFO_64, vm_region_basic_info_64}, +}; +use object::BinaryFormat; +use std::{ffi::OsStr, io, os::unix::ffi::OsStrExt, path::Path}; + +const MAX_FAT_ARCHES: usize = 64; + +struct OwnedPort(mach_port_t); + +impl Drop for OwnedPort { + fn drop(&mut self) { + if self.0 != MACH_PORT_NULL && self.0 != MACH_PORT_DEAD { + // task_for_pid and mach_vm_region each return an owned send right. + // mach_task_self is borrowed and must not itself be deallocated. + unsafe { mach_port_deallocate(mach_task_self(), self.0) }; + } + } +} + +struct Process { + task: OwnedPort, + budget: ReadBudget, +} + +fn mach_error(code: kern_return_t) -> io::Error { + // Mach error codes carry the detailed code in their low fourteen bits. + let kind = match code & 0x3fff { + KERN_PROTECTION_FAILURE | KERN_NO_ACCESS => io::ErrorKind::PermissionDenied, + KERN_RESOURCE_SHORTAGE => io::ErrorKind::OutOfMemory, + KERN_INVALID_ADDRESS => io::ErrorKind::UnexpectedEof, + _ => io::ErrorKind::Other, + }; + io::Error::new(kind, format!("Mach runtime probe failed: {code}")) +} + +impl RemoteRead for Process { + fn read_exact(&mut self, address: u64, destination: &mut [u8]) -> io::Result<()> { + if destination.is_empty() { + return Ok(()); + } + address + .checked_add(destination.len() as u64 - 1) + .ok_or_else(|| invalid_data("remote read address overflow"))?; + self.budget.consume(destination.len())?; + let mut count = 0; + // Only the local destination is a dereferenceable pointer. The remote + // address remains an integer interpreted by the kernel. + let result = unsafe { + mach_vm_read_overwrite( + self.task.0, + address, + destination.len() as u64, + destination.as_mut_ptr() as usize as u64, + &mut count, + ) + }; + if result != KERN_SUCCESS { + return Err(mach_error(result)); + } + if count != destination.len() as u64 { + return Err(io::ErrorKind::UnexpectedEof.into()); + } + Ok(()) + } +} + +fn word(bytes: &[u8], offset: usize) -> io::Result<[u8; N]> { + let end = offset + .checked_add(N) + .ok_or_else(|| invalid_data("Mach-O field offset overflow"))?; + bytes + .get(offset..end) + .and_then(|value| value.try_into().ok()) + .ok_or_else(|| invalid_data("truncated Mach-O field")) +} + +fn read_u32(bytes: &[u8], offset: usize, little: bool) -> io::Result { + let value = word(bytes, offset)?; + Ok(if little { + u32::from_le_bytes(value) + } else { + u32::from_be_bytes(value) + }) +} + +fn sysctl_int(name: &core::ffi::CStr) -> io::Result { + let mut value = 0i32; + let mut length = size_of::(); + let result = unsafe { + libc::sysctlbyname( + name.as_ptr(), + (&mut value as *mut i32).cast(), + &mut length, + core::ptr::null_mut(), + 0, + ) + }; + if result != 0 { + return Err(io::Error::last_os_error()); + } + if length != size_of::() { + return Err(invalid_data("invalid CPU sysctl size")); + } + Ok(value) +} + +fn mach_slice(bytes: &[u8]) -> io::Result> { + let magic = u32::from_be_bytes(word(bytes, 0)?); + let little = match magic { + object::macho::FAT_MAGIC => false, + object::macho::FAT_CIGAM => true, + _ => return Ok(Some(bytes)), + }; + let count = usize::try_from(read_u32(bytes, 4, little)?) + .map_err(|_| invalid_data("Mach-O architecture count overflow"))?; + if count > MAX_FAT_ARCHES { + return Err(invalid_data("Mach-O architecture count exceeds its bound")); + } + let entry_size = 20; + let table_end = count + .checked_mul(entry_size) + .and_then(|size| size.checked_add(8)) + .ok_or_else(|| invalid_data("Mach-O architecture table overflow"))?; + if table_end > bytes.len() { + return Err(invalid_data("truncated Mach-O architecture table")); + } + // Match the pinned CPython locator's host-CPU selection, rather than guessing + // from the inspector's build target (which may itself run under translation). + let cpu = sysctl_int(c"hw.cputype")? as u32; + let capable = sysctl_int(c"hw.cpu64bit_capable")?; + let cpu = cpu + | if capable != 0 { + object::macho::CPU_ARCH_ABI64 + } else { + 0 + }; + for index in 0..count { + // The bounded, validated architecture table makes these offsets safe. + let entry = 8 + index * entry_size; + if read_u32(bytes, entry, little)? != cpu { + continue; + } + let offset = u64::from(read_u32(bytes, entry + 8, little)?); + let length = u64::from(read_u32(bytes, entry + 12, little)?); + let end = offset + .checked_add(length) + .ok_or_else(|| invalid_data("Mach-O architecture range overflow"))?; + let offset = usize::try_from(offset) + .map_err(|_| invalid_data("Mach-O architecture offset overflow"))?; + let end = + usize::try_from(end).map_err(|_| invalid_data("Mach-O architecture end overflow"))?; + if offset < table_end || length == 0 { + return Err(invalid_data("invalid Mach-O architecture range")); + } + return bytes + .get(offset..end) + .map(Some) + .ok_or_else(|| invalid_data("truncated Mach-O architecture")); + } + Ok(None) +} + +fn candidate(process: &mut Process, path: &Path, base: u64) -> io::Result { + let bytes = object_file::read(path, &mut process.budget)?; + let Some(bytes) = mach_slice(&bytes)? else { + return Ok(false); + }; + let Some(address) = object_file::section_address(bytes, base, BinaryFormat::MachO)? else { + return Ok(false); + }; + has_cookie(process, address) +} + +fn search(process: &mut Process, pid: i32, prefix: &[u8]) -> io::Result { + let mut address = 0; + loop { + process.budget.consume(0)?; + let requested = address; + let mut size = 0; + let mut info = vm_region_basic_info_64::default(); + let mut count = vm_region_basic_info_64::count(); + let mut object = MACH_PORT_NULL; + let result = unsafe { + mach_vm_region( + process.task.0, + &mut address, + &mut size, + VM_REGION_BASIC_INFO_64, + (&mut info as *mut vm_region_basic_info_64).cast(), + &mut count, + &mut object, + ) + }; + // Even irrelevant regions may return an owned memory-object port. + let _object = OwnedPort(object); + if result == KERN_INVALID_ADDRESS { + return Ok(false); + } + if result != KERN_SUCCESS { + return Err(mach_error(result)); + } + if count < vm_region_basic_info_64::count() || address < requested || size == 0 { + return Err(invalid_data("invalid Mach memory region")); + } + let next = address + .checked_add(size) + .ok_or_else(|| invalid_data("Mach memory region address overflow"))?; + if info.protection & (VM_PROT_READ | VM_PROT_EXECUTE) == (VM_PROT_READ | VM_PROT_EXECUTE) { + let mut path = [0u8; libc::MAXPATHLEN as usize + 1]; + process.budget.consume(0)?; + let length = unsafe { + // A zero return can describe an anonymous mapping; clear errno + // first so an older failure cannot be mistaken for a denial. + *libc::__error() = 0; + libc::proc_regionfilename( + pid, + address, + path.as_mut_ptr().cast(), + libc::MAXPATHLEN as u32, + ) + }; + if length <= 0 { + let error = io::Error::last_os_error(); + if stops_probe(&error) { + return Err(error); + } + } else if (length as usize) < path.len() + && let Some(end) = path.iter().position(|&byte| byte == 0) + && end < libc::MAXPATHLEN as usize + { + let path = &path[..end]; + let name = path.rsplit(|&byte| byte == b'/').next().unwrap_or(path); + if name.starts_with(prefix) { + match candidate(process, Path::new(OsStr::from_bytes(path)), address) { + Ok(true) => return Ok(true), + Err(error) if stops_probe(&error) => return Err(error), + Ok(false) | Err(_) => {} + } + } + } + } + address = next; + } +} + +pub(super) fn probe(pid: i32) -> io::Result { + let mut task = MACH_PORT_NULL; + let result = unsafe { task_for_pid(mach_task_self(), pid, &mut task) }; + let task = OwnedPort(task); + if result != KERN_SUCCESS || task.0 == MACH_PORT_NULL || task.0 == MACH_PORT_DEAD { + // CPython classifies every task_for_pid failure as a permission failure. + return Err(io::Error::new( + io::ErrorKind::PermissionDenied, + format!("cannot acquire task port for PID {pid}: {result}"), + )); + } + let mut process = Process { + task, + budget: ReadBudget::new(), + }; + for prefix in [b"libpython".as_slice(), b"python", b"Python"] { + match search(&mut process, pid, prefix) { + Ok(true) => return Ok(true), + Err(error) if stops_probe(&error) => return Err(error), + Ok(false) | Err(_) => {} + } + } + Ok(false) +} diff --git a/crates/host_env/src/remote_debugging/mod.rs b/crates/host_env/src/remote_debugging/mod.rs new file mode 100644 index 00000000000..0e3ee4735f8 --- /dev/null +++ b/crates/host_env/src/remote_debugging/mod.rs @@ -0,0 +1,63 @@ +//! Read-only discovery of CPython's exported runtime metadata. +//! +//! A successful cookie probe identifies a runtime; it does not validate its +//! debug offsets or promise that stack unwinding is supported. + +mod children; +pub use children::Error as ChildPidsError; + +pub fn get_child_pids(pid: i32, recursive: bool) -> Result, ChildPidsError> { + children::enumerate(pid, recursive) +} + +#[cfg(all(target_os = "linux", not(target_env = "uclibc")))] +mod linux; +#[cfg(target_os = "macos")] +mod macos; +#[cfg(windows)] +mod windows; + +#[cfg(any( + all(target_os = "linux", not(target_env = "uclibc")), + target_os = "macos", + windows +))] +mod object_file; + +#[cfg(any( + all(target_os = "linux", not(target_env = "uclibc")), + target_os = "macos", + windows +))] +mod common; + +#[cfg(all(target_os = "linux", not(target_env = "uclibc")))] +use common::COOKIE; +#[cfg(any( + all(target_os = "linux", not(target_env = "uclibc")), + target_os = "macos", + windows +))] +use common::{ReadBudget, RemoteRead, has_cookie, invalid_data, stops_probe}; + +pub const PROCESS_VM_READV_SUPPORTED: u8 = + cfg!(all(target_os = "linux", not(target_env = "uclibc"))) as u8; + +pub fn is_python_process(pid: i32) -> bool { + #[cfg(all(target_os = "linux", not(target_env = "uclibc")))] + let result = linux::probe(pid); + #[cfg(target_os = "macos")] + let result = macos::probe(pid); + #[cfg(windows)] + let result = windows::probe(pid); + #[cfg(not(any( + all(target_os = "linux", not(target_env = "uclibc")), + target_os = "macos", + windows + )))] + let result: Result = { + let _ = pid; + Err(std::io::ErrorKind::Unsupported.into()) + }; + result.unwrap_or(false) +} diff --git a/crates/host_env/src/remote_debugging/object_file.rs b/crates/host_env/src/remote_debugging/object_file.rs new file mode 100644 index 00000000000..37678b93a9c --- /dev/null +++ b/crates/host_env/src/remote_debugging/object_file.rs @@ -0,0 +1,94 @@ +use super::{ReadBudget, invalid_data}; +use object::{BinaryFormat, Object, ObjectSection, ObjectSegment}; +use std::{fs::OpenOptions, io, io::Read, path::Path}; + +const MAX_OBJECT_BYTES: u64 = 256 * 1024 * 1024; + +pub(super) fn read(path: &Path, budget: &mut ReadBudget) -> io::Result> { + budget.consume(0)?; + let mut options = OpenOptions::new(); + options.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + // A mapped pathname can be replaced with a FIFO while being inspected. + options.custom_flags(libc::O_NONBLOCK); + } + let file = options.open(path)?; + let metadata = file.metadata()?; + if !metadata.is_file() || metadata.len() > MAX_OBJECT_BYTES { + return Err(invalid_data( + "runtime candidate is not a bounded regular file", + )); + } + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(metadata.len() as usize) + .map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?; + let result = file.take(MAX_OBJECT_BYTES + 1).read_to_end(&mut bytes); + // A failed read may already have appended bytes. Account for them before + // propagating the error, as well as before rejecting a grown file. + budget.consume(bytes.len())?; + result?; + if bytes.len() as u64 > MAX_OBJECT_BYTES { + return Err(invalid_data("runtime candidate grew beyond its size bound")); + } + Ok(bytes) +} + +pub(super) fn section_address( + bytes: &[u8], + mapping_base: u64, + format: BinaryFormat, +) -> io::Result> { + let file = object::File::parse(bytes).map_err(|_| invalid_data("invalid object file"))?; + if file.format() != format { + return Ok(None); + } + let name = match format { + BinaryFormat::Elf => b".PyRuntime".as_slice(), + BinaryFormat::MachO => b"PyRuntime".as_slice(), + BinaryFormat::Pe => b"PyRuntim".as_slice(), + _ => return Ok(None), + }; + let section = if format == BinaryFormat::MachO { + file.sections().find(|section| { + section.name_bytes().ok() == Some(name) + && section.segment_name_bytes().ok() == Some(Some(b"__DATA".as_slice())) + }) + } else { + file.section_by_name_bytes(name) + }; + let Some(section) = section else { + return Ok(None); + }; + let image_base = match format { + BinaryFormat::Elf => { + // The ELF reader's segment iterator contains only PT_LOAD entries. + let first = file + .segments() + .next() + .ok_or_else(|| invalid_data("ELF image has no load segment"))?; + let alignment = first.align(); + if alignment == 0 || !alignment.is_power_of_two() { + return Err(invalid_data("invalid ELF load alignment")); + } + first.address() - first.address() % alignment + } + BinaryFormat::MachO => file + .segments() + .find(|segment| segment.name_bytes().ok() == Some(Some(b"__TEXT".as_slice()))) + .ok_or_else(|| invalid_data("Mach-O image has no text segment"))? + .address(), + BinaryFormat::Pe => file.relative_address_base(), + _ => unreachable!(), + }; + let relative = section + .address() + .checked_sub(image_base) + .ok_or_else(|| invalid_data("runtime section precedes its image base"))?; + let address = mapping_base + .checked_add(relative) + .ok_or_else(|| invalid_data("runtime section address overflow"))?; + Ok((address != 0).then_some(address)) +} diff --git a/crates/host_env/src/remote_debugging/windows.rs b/crates/host_env/src/remote_debugging/windows.rs new file mode 100644 index 00000000000..77a55fc0a5c --- /dev/null +++ b/crates/host_env/src/remote_debugging/windows.rs @@ -0,0 +1,178 @@ +use super::{ReadBudget, RemoteRead, has_cookie, invalid_data, object_file, stops_probe}; +use core::mem::size_of; +use object::BinaryFormat; +use std::{ffi::OsString, io, os::windows::ffi::OsStringExt, path::PathBuf}; +use windows_sys::Win32::{ + Foundation::{ + CloseHandle, ERROR_BAD_LENGTH, ERROR_NO_MORE_FILES, GetLastError, HANDLE, + INVALID_HANDLE_VALUE, + }, + System::{ + Diagnostics::{ + Debug::ReadProcessMemory, + ToolHelp::{ + CreateToolhelp32Snapshot, MODULEENTRY32W, Module32FirstW, Module32NextW, + TH32CS_SNAPMODULE, + }, + }, + Threading::{ + OpenProcess, PROCESS_QUERY_INFORMATION, PROCESS_SUSPEND_RESUME, PROCESS_VM_OPERATION, + PROCESS_VM_READ, PROCESS_VM_WRITE, + }, + }, +}; + +const MAX_SNAPSHOT_ATTEMPTS: usize = 16; +const MAX_MODULES: usize = 16_384; + +struct OwnedHandle(HANDLE); + +impl Drop for OwnedHandle { + fn drop(&mut self) { + // Only successfully acquired process and snapshot handles are owned here. + unsafe { CloseHandle(self.0) }; + } +} + +struct Process { + handle: OwnedHandle, + budget: ReadBudget, +} + +impl RemoteRead for Process { + fn read_exact(&mut self, address: u64, mut destination: &mut [u8]) -> io::Result<()> { + if destination.is_empty() { + return Ok(()); + } + let end = address + .checked_add(destination.len() as u64 - 1) + .ok_or_else(|| invalid_data("remote read address overflow"))?; + usize::try_from(end).map_err(|_| invalid_data("remote address exceeds pointer width"))?; + let mut address = usize::try_from(address) + .map_err(|_| invalid_data("remote address exceeds pointer width"))?; + while !destination.is_empty() { + self.budget.consume(destination.len())?; + let mut count = 0; + // The address is passed to the OS, never dereferenced in this process. + let success = unsafe { + ReadProcessMemory( + self.handle.0, + address as *const _, + destination.as_mut_ptr().cast(), + destination.len(), + &mut count, + ) + }; + if success == 0 { + // In particular, an ERROR_PARTIAL_COPY failure is not a successful + // short read. CPython only continues after successful reads. + return Err(io::Error::last_os_error()); + } + if count == 0 { + return Err(io::ErrorKind::UnexpectedEof.into()); + } + if count > destination.len() { + return Err(invalid_data("remote read exceeded its destination")); + } + destination = &mut destination[count..]; + if !destination.is_empty() { + address = address + .checked_add(count) + .ok_or_else(|| invalid_data("remote read address overflow"))?; + } + } + Ok(()) + } +} + +fn snapshot(pid: u32, budget: &mut ReadBudget) -> io::Result { + for _ in 0..MAX_SNAPSHOT_ATTEMPTS { + budget.consume(0)?; + // Keep CPython's module selection flags, including its cross-bitness limits. + let handle = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid) }; + if handle != INVALID_HANDLE_VALUE { + return Ok(OwnedHandle(handle)); + } + let error = unsafe { GetLastError() }; + if error != ERROR_BAD_LENGTH { + return Err(io::Error::from_raw_os_error(error as i32)); + } + } + Err(io::Error::from_raw_os_error(ERROR_BAD_LENGTH as i32)) +} + +fn terminated(value: &[u16]) -> io::Result<&[u16]> { + let end = value + .iter() + .position(|&unit| unit == 0) + .ok_or_else(|| invalid_data("unterminated module name or path"))?; + Ok(&value[..end]) +} + +fn candidate(process: &mut Process, module: &MODULEENTRY32W) -> io::Result { + const PYTHON: &[u16] = &[112, 121, 116, 104, 111, 110]; + let name = terminated(&module.szModule)?; + if !name.windows(PYTHON.len()).any(|part| part == PYTHON) { + return Ok(false); + } + let path = PathBuf::from(OsString::from_wide(terminated(&module.szExePath)?)); + let bytes = object_file::read(&path, &mut process.budget)?; + let base = module.modBaseAddr as usize as u64; + let Some(address) = object_file::section_address(&bytes, base, BinaryFormat::Pe)? else { + return Ok(false); + }; + has_cookie(process, address) +} + +pub(super) fn probe(pid: i32) -> io::Result { + // CPython requests these rights even for this read-only operation. Reducing + // them could make detection succeed where CPython's handle initialization fails. + // The DWORD conversion also preserves the Windows API's signed-PID behavior. + let handle = unsafe { + OpenProcess( + PROCESS_VM_READ + | PROCESS_VM_WRITE + | PROCESS_VM_OPERATION + | PROCESS_QUERY_INFORMATION + | PROCESS_SUSPEND_RESUME, + 0, + pid as u32, + ) + }; + if handle.is_null() { + return Err(io::Error::last_os_error()); + } + let mut process = Process { + handle: OwnedHandle(handle), + budget: ReadBudget::new(), + }; + let snapshot = snapshot(pid as u32, &mut process.budget)?; + let mut module = MODULEENTRY32W { + dwSize: size_of::() as u32, + ..Default::default() + }; + process.budget.consume(0)?; + let mut success = unsafe { Module32FirstW(snapshot.0, &mut module) }; + for _ in 0..MAX_MODULES { + if success == 0 { + let error = unsafe { GetLastError() }; + return if error == ERROR_NO_MORE_FILES { + Ok(false) + } else { + Err(io::Error::from_raw_os_error(error as i32)) + }; + } + match candidate(&mut process, &module) { + Ok(true) => return Ok(true), + Err(error) if stops_probe(&error) => return Err(error), + Ok(false) | Err(_) => {} + } + process.budget.consume(0)?; + module.dwSize = size_of::() as u32; + success = unsafe { Module32NextW(snapshot.0, &mut module) }; + } + Err(io::Error::new( + io::ErrorKind::OutOfMemory, + "runtime probe module budget exhausted", + )) +} diff --git a/crates/host_env/src/resource.rs b/crates/host_env/src/resource.rs index 530b7e9e0a1..074aab32115 100644 --- a/crates/host_env/src/resource.rs +++ b/crates/host_env/src/resource.rs @@ -7,6 +7,19 @@ pub use libc::{ RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_RSS, RLIMIT_STACK, c_long, rlim_t, rlimit, timeval, }; +#[cfg(any( + target_os = "linux", + target_os = "l4re", + target_os = "emscripten", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "aix", + target_os = "fuchsia", + target_os = "cygwin" +))] +pub use libc::{RLIM_SAVED_CUR, RLIM_SAVED_MAX}; + #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))] pub use libc::{RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_SIGPENDING}; diff --git a/crates/host_env/src/select.rs b/crates/host_env/src/select.rs index 287f64b56bf..cd202091bab 100644 --- a/crates/host_env/src/select.rs +++ b/crates/host_env/src/select.rs @@ -36,10 +36,62 @@ pub mod platform { #[allow(non_snake_case)] #[cfg(windows)] pub mod platform { - pub use WinSock::{FD_SET as fd_set, FD_SETSIZE, SOCKET as RawFd, TIMEVAL as timeval, select}; + pub use WinSock::{SOCKET as RawFd, TIMEVAL as timeval}; use std::io; use windows_sys::Win32::Networking::WinSock; + // Match CPython's Windows capacity. WinSock uses fd_count to determine + // the array length; the windows-sys declaration has the SDK default of 64. + pub const FD_SETSIZE: u32 = 512; + + #[allow(non_camel_case_types)] + #[repr(C)] + pub struct fd_set { + fd_count: u32, + fd_array: [RawFd; FD_SETSIZE as usize], + } + + const _: () = { + assert!(core::mem::align_of::() == core::mem::align_of::()); + assert!( + core::mem::offset_of!(fd_set, fd_count) + == core::mem::offset_of!(WinSock::FD_SET, fd_count) + ); + assert!( + core::mem::offset_of!(fd_set, fd_array) + == core::mem::offset_of!(WinSock::FD_SET, fd_array) + ); + assert!( + core::mem::size_of::() + == core::mem::offset_of!(fd_set, fd_array) + + FD_SETSIZE as usize * core::mem::size_of::() + ); + }; + + /// # Safety + /// + /// Every non-null set must point to an initialized fd_set, and timeout + /// must be null or point to an initialized timeval. + pub unsafe fn select( + nfds: i32, + readfds: *mut fd_set, + writefds: *mut fd_set, + errorfds: *mut fd_set, + timeout: *const timeval, + ) -> i32 { + // fd_set is a count followed by a caller-sized SOCKET array. Both + // layouts have the same alignment and offset of the array. + unsafe { + WinSock::select( + nfds, + readfds.cast(), + writefds.cast(), + errorfds.cast(), + timeout, + ) + } + } + /// # Safety /// /// `set` must be a valid mutable pointer to an initialized WinSock fd_set. @@ -71,8 +123,8 @@ pub mod platform { /// /// `set` must be a valid mutable pointer to an initialized WinSock fd_set. pub unsafe fn FD_ISSET(fd: RawFd, set: *mut fd_set) -> bool { - use WinSock::__WSAFDIsSet; - unsafe { __WSAFDIsSet(fd as _, set) != 0 } + let set = unsafe { &*set }; + set.fd_array[..set.fd_count as usize].contains(&fd) } #[must_use] @@ -239,6 +291,19 @@ pub fn duration_to_timeval(d: Duration) -> timeval { tv } +pub fn duration_to_timeval_ceiling(duration: Duration) -> Option { + let micros = i64::try_from(duration.as_nanos().div_ceil(1000)).ok()?; + timeval_from_microseconds(micros) +} + +#[allow(clippy::useless_conversion, reason = "timeval fields can be 32-bit")] +pub fn timeval_from_microseconds(micros: i64) -> Option { + Some(timeval { + tv_sec: micros.div_euclid(1_000_000).try_into().ok()?, + tv_usec: micros.rem_euclid(1_000_000).try_into().ok()?, + }) +} + fn saturate_secs(secs: u64, _sample: T) -> T where T: TryFrom + TryFrom, @@ -430,12 +495,125 @@ pub fn poll_fds(fds: &mut [PollFd], timeout: i32) -> std::io::Result { } } +// ppoll preserves Python's nanosecond timeout on platforms with a supported +// binding. Other poll backends continue to use rounded signed milliseconds. +#[cfg(unix)] +pub struct PollTimeout { + #[cfg(any(target_os = "linux", target_os = "android"))] + timespec: Option, + #[cfg(not(any(target_os = "linux", target_os = "android")))] + milliseconds: i32, +} + +#[cfg(unix)] +impl PollTimeout { + #[allow(clippy::useless_conversion, reason = "time_t can be 32-bit")] + pub fn from_nanoseconds(timeout: Option) -> Option { + #[cfg(any(target_os = "linux", target_os = "android"))] + if let Some(nanoseconds) = timeout { + // CPython validates timespec even for negative (infinite) waits. + // Floor division matches the normalized signed timespec seconds. + libc::time_t::try_from(nanoseconds.div_euclid(1_000_000_000)).ok()?; + } + Self::from_duration( + timeout + .filter(|&ns| ns >= 0) + .map(|ns| Duration::from_nanos(ns as u64)), + ) + } + + pub fn from_duration(timeout: Option) -> Option { + #[cfg(any(target_os = "linux", target_os = "android"))] + { + let timespec = match timeout { + Some(duration) => Some(libc::timespec { + tv_sec: duration.as_secs().try_into().ok()?, + tv_nsec: duration.subsec_nanos() as _, + }), + None => None, + }; + Some(Self { timespec }) + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + { + let milliseconds = match timeout { + Some(duration) => duration_as_millis_ceiling(duration)?, + None => -1, + }; + Some(Self { milliseconds }) + } + } +} + +#[cfg(unix)] +pub fn poll_fds_with_timeout(fds: &mut [PollFd], timeout: &PollTimeout) -> io::Result { + #[cfg(any(target_os = "linux", target_os = "android"))] + { + let timespec = timeout.timespec.as_ref().map_or(core::ptr::null(), |ts| ts); + // A null mask preserves the calling thread's signal mask. libc owns + // any platform-specific copying needed by the ppoll syscall. + let result = unsafe { + libc::ppoll( + fds.as_mut_ptr(), + fds.len() as _, + timespec, + core::ptr::null(), + ) + }; + if result < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(result) + } + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + { + poll_fds(fds, timeout.milliseconds) + } +} + #[cfg(any(target_os = "linux", target_os = "android", target_os = "redox"))] pub mod epoll { - use std::os::fd::{AsFd, IntoRawFd, OwnedFd}; + use std::os::fd::{IntoRawFd, RawFd}; + + // Keep the native event layout inside host_env while allowing the syscall + // to initialize a Vec of these transparent wrappers directly. + #[repr(transparent)] + pub struct Event(libc::epoll_event); - pub use rustix::event::Timespec; - pub use rustix::event::epoll::{Event, EventData, EventFlags}; + impl Event { + pub fn data(&self) -> u64 { + self.0.u64 + } + + pub fn flags(&self) -> u32 { + self.0.events + } + } + pub use rustix::event::epoll::EventFlags; + + // Python exposes descriptor integers and permits aliases via fromfd(). The + // descriptor may therefore already be closed when this wrapper is dropped. + #[derive(Debug)] + pub struct EpollFd(RawFd); + + impl EpollFd { + pub fn from_raw(fd: RawFd) -> Self { + Self(fd) + } + + pub fn as_raw(&self) -> RawFd { + self.0 + } + } + + impl Drop for EpollFd { + fn drop(&mut self) { + if self.0 != -1 { + let _ = nix::unistd::close(self.0); + } + } + } #[derive(Debug)] pub enum WaitError { @@ -443,52 +621,74 @@ pub mod epoll { Io(std::io::Error), } - pub fn create() -> std::io::Result { - rustix::event::epoll::create(rustix::event::epoll::CreateFlags::CLOEXEC).map_err(Into::into) + pub fn create() -> std::io::Result { + rustix::event::epoll::create(rustix::event::epoll::CreateFlags::CLOEXEC) + .map(|fd| EpollFd(fd.into_raw_fd())) + .map_err(Into::into) } - pub fn close(fd: OwnedFd) -> nix::Result<()> { - nix::unistd::close(fd.into_raw_fd()) + pub fn close(mut fd: EpollFd) -> nix::Result<()> { + let raw = core::mem::replace(&mut fd.0, -1); + nix::unistd::close(raw) } - pub fn add(epoll: &OwnedFd, fd: F, data: u64, events: u32) -> std::io::Result<()> { - rustix::event::epoll::add( - epoll, - fd, - EventData::new_u64(data), - EventFlags::from_bits_retain(events), - ) - .map_err(Into::into) + fn control(epoll: &EpollFd, op: i32, fd: RawFd, data: u64, events: u32) -> std::io::Result<()> { + let mut event = libc::epoll_event { + events, + u64: data, + #[cfg(target_os = "redox")] + _pad: 0, + }; + // Both descriptors come from Python and may be invalid. The syscall + // reports that as an error without asserting Rust descriptor ownership. + let result = unsafe { libc::epoll_ctl(epoll.0, op, fd, &mut event) }; + if result < 0 { + Err(std::io::Error::last_os_error()) + } else { + Ok(()) + } } - pub fn modify(epoll: &OwnedFd, fd: F, data: u64, events: u32) -> std::io::Result<()> { - rustix::event::epoll::modify( - epoll, - fd, - EventData::new_u64(data), - EventFlags::from_bits_retain(events), - ) - .map_err(Into::into) + pub fn add(epoll: &EpollFd, fd: RawFd, data: u64, events: u32) -> std::io::Result<()> { + control(epoll, libc::EPOLL_CTL_ADD, fd, data, events) } - pub fn delete(epoll: &OwnedFd, fd: F) -> std::io::Result<()> { - rustix::event::epoll::delete(epoll, fd).map_err(Into::into) + pub fn modify(epoll: &EpollFd, fd: RawFd, data: u64, events: u32) -> std::io::Result<()> { + control(epoll, libc::EPOLL_CTL_MOD, fd, data, events) + } + + pub fn delete(epoll: &EpollFd, fd: RawFd) -> std::io::Result<()> { + control(epoll, libc::EPOLL_CTL_DEL, fd, 0, 0) } pub fn wait( - epoll: &OwnedFd, + epoll: &EpollFd, events: &mut Vec, - timeout: Option<&Timespec>, + timeout: i32, ) -> Result { events.clear(); - match rustix::event::epoll::wait(epoll, rustix::buffer::spare_capacity(events), timeout) { - Ok(n) => { - unsafe { events.set_len(n) }; - Ok(n) - } - Err(rustix::io::Errno::INTR) => Err(WaitError::Interrupted), - Err(err) => Err(WaitError::Io(err.into())), + // Event is transparent over libc's native event layout, and capacity + // is bounded by Python's i32 maxevents. epoll_wait initializes each + // returned element, so the cast and subsequent set_len are valid. + let result = unsafe { + libc::epoll_wait( + epoll.0, + events.as_mut_ptr().cast::(), + events.capacity().min(i32::MAX as usize) as i32, + timeout, + ) + }; + if result < 0 { + let error = std::io::Error::last_os_error(); + return if error.kind() == std::io::ErrorKind::Interrupted { + Err(WaitError::Interrupted) + } else { + Err(WaitError::Io(error)) + }; } + let count = result as usize; + unsafe { events.set_len(count) }; + Ok(count) } } diff --git a/crates/host_env/src/shm.rs b/crates/host_env/src/shm.rs index b50e460b79a..cf4a7f34bfd 100644 --- a/crates/host_env/src/shm.rs +++ b/crates/host_env/src/shm.rs @@ -1,18 +1,29 @@ use core::ffi::CStr; use std::io; -use crate::os::CheckLibcResult; +use rustix::{ + fd::{IntoRawFd, OwnedFd}, + fs, shm, +}; pub use libc::mode_t; -pub fn shm_open(name: &CStr, flags: libc::c_int, mode: libc::c_uint) -> io::Result { - #[cfg(target_os = "freebsd")] - let mode = mode.try_into().unwrap(); +pub fn shm_open(name: &CStr, flags: libc::c_int, mode: libc::mode_t) -> io::Result { + // FreeBSD implements shared memory differently from Linux so NO_FOLLOW isn't set or needed. + #[cfg(not(target_os = "linux"))] + let flags = shm::OFlags::from_bits_retain(flags as _); - unsafe { libc::shm_open(name.as_ptr(), flags, mode) }.check_libc_neg() + // Glibc and musl both set NOFOLLOW. + #[cfg(target_os = "linux")] + let flags = shm::OFlags::from_bits_retain(flags as u32 | fs::OFlags::NOFOLLOW.bits()); + + let mode = fs::Mode::from_bits_retain(mode); + + shm::open(name, flags, mode) + .map(OwnedFd::into_raw_fd) + .map_err(Into::into) } pub fn shm_unlink(name: &CStr) -> io::Result<()> { - unsafe { libc::shm_unlink(name.as_ptr()) }.check_libc_neg()?; - Ok(()) + shm::unlink(name).map_err(Into::into) } diff --git a/crates/host_env/src/signal.rs b/crates/host_env/src/signal.rs index 090269123fc..ffe47dc41fa 100644 --- a/crates/host_env/src/signal.rs +++ b/crates/host_env/src/signal.rs @@ -1,3 +1,4 @@ +#[cfg(any(unix, windows))] use std::io; #[cfg(windows)] use std::sync::Once; @@ -13,13 +14,109 @@ pub use libc::sighandler_t; #[cfg(unix)] pub use libc::{SIG_DFL, SIG_ERR, SIG_IGN}; -#[cfg(not(unix))] +#[cfg(not(any(unix, target_os = "wasi")))] pub const SIG_DFL: libc::sighandler_t = 0; -#[cfg(not(unix))] +#[cfg(not(any(unix, target_os = "wasi")))] pub const SIG_IGN: libc::sighandler_t = 1; -#[cfg(not(unix))] +#[cfg(not(any(unix, target_os = "wasi")))] pub const SIG_ERR: libc::sighandler_t = -1 as _; +/// wasi-libc's userspace emulation of `signal()`/`raise()`, linked from +/// `libwasi-emulated-signal` (see `crates/host_env/vendor/wasm32-wasip1`). +/// WebAssembly has no asynchronous signal delivery, so this is a +/// synchronous, in-process handler table: a handler only runs when this +/// process's own code calls `raise()`, never from an outside interrupt. +/// Numbering matches wasi-libc's `bits/signal.h`, the same values CPython's +/// WASI build gets by linking the same library. +#[cfg(target_os = "wasi")] +mod wasm { + use std::io; + + #[allow(non_camel_case_types)] + pub type sighandler_t = usize; + + pub const SIG_DFL: sighandler_t = 0; + pub const SIG_IGN: sighandler_t = 1; + pub const SIG_ERR: sighandler_t = -1isize as usize; + + pub const SIGINT: i32 = 2; + pub const SIGILL: i32 = 4; + pub const SIGABRT: i32 = 6; + pub const SIGFPE: i32 = 8; + pub const SIGSEGV: i32 = 11; + pub const SIGTERM: i32 = 15; + + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum Handler { + Default, + Ignore, + Custom(sighandler_t), + } + + unsafe extern "C" { + #[link_name = "signal"] + fn c_signal(signum: i32, handler: sighandler_t) -> sighandler_t; + #[link_name = "__SIG_IGN"] + fn c_sig_ign(signum: i32); + #[link_name = "__SIG_ERR"] + fn c_sig_err(signum: i32); + fn raise(signum: i32) -> i32; + } + + impl Handler { + fn as_raw(self) -> sighandler_t { + match self { + Self::Default => 0, + Self::Ignore => c_sig_ign as *const () as sighandler_t, + Self::Custom(handler) => handler, + } + } + + fn from_raw(handler: sighandler_t) -> io::Result { + // wasi-libc uses function pointers for SIG_IGN and SIG_ERR because + // table index 1 is also a valid custom Wasm function pointer. + if handler == c_sig_err as *const () as sighandler_t { + Err(io::Error::last_os_error()) + } else if handler == 0 { + Ok(Self::Default) + } else if handler == c_sig_ign as *const () as sighandler_t { + Ok(Self::Ignore) + } else { + Ok(Self::Custom(handler)) + } + } + } + + /// # Safety + /// + /// The caller must ensure `signalnum` is a valid platform signal number. + pub unsafe fn probe_handler(signalnum: i32) -> Option { + let handler = unsafe { install_handler(signalnum, Handler::Ignore) }.ok()?; + unsafe { install_handler(signalnum, handler) }.ok()?; + Some(handler) + } + + /// # Safety + /// + /// The caller must ensure `signalnum` is a valid platform signal number and + /// a custom `handler` is accepted by the platform signal ABI. + pub unsafe fn install_handler(signalnum: i32, handler: Handler) -> io::Result { + let old = unsafe { c_signal(signalnum, handler.as_raw()) }; + Handler::from_raw(old) + } + + pub fn raise_signal(signalnum: i32) -> io::Result<()> { + if unsafe { raise(signalnum) } == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } + } +} + +#[cfg(target_os = "wasi")] +pub use wasm::*; + #[cfg(unix)] pub use libc::{SIG_BLOCK, SIG_SETMASK, SIG_UNBLOCK}; @@ -104,12 +201,26 @@ mod ffi { /// The caller must ensure `signalnum` is a valid platform signal number. #[cfg(any(unix, windows))] pub unsafe fn probe_handler(signalnum: i32) -> Option { - let handler = unsafe { libc::signal(signalnum, libc::SIG_IGN) }; - if handler == libc::SIG_ERR as sighandler_t { - None - } else { - unsafe { libc::signal(signalnum, handler) }; - Some(handler) + #[cfg(unix)] + { + // Query without changing disposition: even temporarily ignoring SIGCHLD + // can discard a child's exit status, and signal() also replaces masks. + let mut action = core::mem::MaybeUninit::::uninit(); + if unsafe { libc::sigaction(signalnum, core::ptr::null(), action.as_mut_ptr()) } == 0 { + Some(unsafe { action.assume_init() }.sa_sigaction) + } else { + None + } + } + #[cfg(windows)] + { + let handler = unsafe { libc::signal(signalnum, libc::SIG_IGN) }; + if handler == libc::SIG_ERR as sighandler_t { + None + } else { + unsafe { libc::signal(signalnum, handler) }; + Some(handler) + } } } @@ -284,13 +395,43 @@ pub fn wakeup_fd_is_socket(fd: libc::SOCKET) -> io::Result { Ok(false) } +#[cfg(any(unix, windows))] +pub enum WakeupError { + Write(i32), + #[cfg(windows)] + Send(i32), +} + +#[cfg(any(unix, windows))] +impl WakeupError { + pub fn is_would_block(&self) -> bool { + match *self { + Self::Write(errno) => errno == libc::EAGAIN || errno == libc::EWOULDBLOCK, + #[cfg(windows)] + Self::Send(error) => error == windows_sys::Win32::Networking::WinSock::WSAEWOULDBLOCK, + } + } + + // Only convert to an allocating error outside the OS signal handler. + pub fn into_io_error(self) -> io::Error { + match self { + #[cfg(unix)] + Self::Write(errno) => io::Error::from_raw_os_error(errno), + #[cfg(windows)] + Self::Write(errno) => crate::os::io_error_from_errno(errno), + #[cfg(windows)] + Self::Send(error) => io::Error::from_raw_os_error(error), + } + } +} + #[cfg(windows)] pub fn notify_signal( signum: i32, wakeup_fd: libc::SOCKET, wakeup_is_socket: bool, sigint_event: Option, -) { +) -> Option { if signum == libc::SIGINT && let Some(handle) = sigint_event { @@ -300,27 +441,44 @@ pub fn notify_signal( } if wakeup_fd == INVALID_SOCKET { - return; + return None; } let sigbyte = signum as u8; if wakeup_is_socket { - unsafe { - let _ = windows_sys::Win32::Networking::WinSock::send( + let result = unsafe { + windows_sys::Win32::Networking::WinSock::send( wakeup_fd, &sigbyte as *const u8 as *const _, 1, 0, - ); + ) + }; + if result < 0 { + Some(WakeupError::Send(unsafe { + windows_sys::Win32::Networking::WinSock::WSAGetLastError() + })) + } else { + None } } else { - unsafe { - let _ = libc::write(wakeup_fd as _, &sigbyte as *const u8 as *const _, 1); - } + crate::crt_fd::write_noraise(wakeup_fd as _, &[sigbyte]) + .err() + .map(WakeupError::Write) } } #[cfg(unix)] +pub fn notify_signal(signum: i32, wakeup_fd: i32) -> Option { + if wakeup_fd == -1 { + return None; + } + crate::crt_fd::write_noraise(wakeup_fd, &[signum as u8]) + .err() + .map(WakeupError::Write) +} + +#[cfg(target_os = "wasi")] pub fn notify_signal(signum: i32, wakeup_fd: i32) { if wakeup_fd == -1 { return; @@ -379,3 +537,49 @@ pub fn sigset_contains(mask: libc::sigset_t, signum: i32) -> bool { pub fn valid_signals(_max_signum: usize) -> io::Result> { Ok(VALID_SIGNALS.to_vec()) } + +#[cfg(test)] +#[cfg(unix)] +mod tests { + #[test] + fn probing_preserves_signal_flags_and_mask() { + unsafe extern "C" fn handler(_: libc::c_int) {} + + struct Restore(libc::sigaction); + impl Drop for Restore { + fn drop(&mut self) { + unsafe { libc::sigaction(libc::SIGUSR2, &self.0, core::ptr::null_mut()) }; + } + } + + // No other host_env test uses SIGUSR2; retain the host disposition even + // when an assertion fails. Do not deliver any signal to the process. + unsafe { + let mut action: libc::sigaction = core::mem::zeroed(); + action.sa_sigaction = handler as *const () as libc::sighandler_t; + action.sa_flags = libc::SA_NODEFER; + assert_eq!(libc::sigemptyset(&mut action.sa_mask), 0); + assert_eq!(libc::sigaddset(&mut action.sa_mask, libc::SIGUSR1), 0); + let mut original = core::mem::MaybeUninit::uninit(); + assert_eq!( + libc::sigaction(libc::SIGUSR2, &action, original.as_mut_ptr()), + 0 + ); + let _restore = Restore(original.assume_init()); + + assert_eq!( + super::probe_handler(libc::SIGUSR2), + Some(action.sa_sigaction) + ); + let mut observed = core::mem::MaybeUninit::::uninit(); + assert_eq!( + libc::sigaction(libc::SIGUSR2, core::ptr::null(), observed.as_mut_ptr()), + 0 + ); + let observed = observed.assume_init(); + assert_eq!(observed.sa_sigaction, action.sa_sigaction); + assert_ne!(observed.sa_flags & libc::SA_NODEFER, 0); + assert_eq!(libc::sigismember(&observed.sa_mask, libc::SIGUSR1), 1); + } + } +} diff --git a/crates/host_env/src/socket.rs b/crates/host_env/src/socket.rs index c70f4a16068..f5603a1dbec 100644 --- a/crates/host_env/src/socket.rs +++ b/crates/host_env/src/socket.rs @@ -18,6 +18,9 @@ pub use ::dns_lookup as dns; #[cfg(not(target_arch = "wasm32"))] pub use ::socket2 as raw; +#[cfg(target_os = "linux")] +pub mod bluetooth; + #[cfg(not(any( target_os = "ios", target_os = "android", @@ -801,11 +804,30 @@ pub fn setsockopt_none(fd: libc::c_int, level: i32, name: i32, optlen: u32) -> i target_os = "openbsd", ))] pub fn if_nameindex() -> io::Result> { + Ok(if_nameindex_bytes()? + .into_iter() + .map(|(index, name)| (index, String::from_utf8_lossy(&name).into_owned())) + .collect()) +} + +#[cfg(any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "fuchsia", + target_os = "ios", + target_os = "linux", + target_os = "macos", + target_os = "netbsd", + target_os = "openbsd", +))] +/// Return interface names as their original platform bytes without applying +/// a lossy text conversion. +pub fn if_nameindex_bytes() -> io::Result)>> { let list = nix::net::if_::if_nameindex().map_err(io::Error::from)?; Ok(list .to_slice() .iter() - .map(|iface| (iface.index(), iface.name().to_string_lossy().into_owned())) + .map(|iface| (iface.index(), iface.name().to_bytes().to_vec())) .collect()) } @@ -821,6 +843,12 @@ pub fn if_nametoindex_checked(name: &CStr) -> io::Result { #[cfg(unix)] pub fn if_indextoname_checked(index: u32) -> io::Result { + if_indextoname_bytes(index).map(|name| String::from_utf8_lossy(&name).into_owned()) +} + +#[cfg(unix)] +/// Return an interface name as its original platform bytes. +pub fn if_indextoname_bytes(index: u32) -> io::Result> { let mut buf = [0u8; libc::IF_NAMESIZE]; let ret = unsafe { libc::if_indextoname(index as libc::c_uint, buf.as_mut_ptr() as *mut libc::c_char) @@ -829,7 +857,7 @@ pub fn if_indextoname_checked(index: u32) -> io::Result { Err(io::Error::last_os_error()) } else { let buf = unsafe { CStr::from_ptr(buf.as_ptr() as *const libc::c_char) }; - Ok(buf.to_string_lossy().into_owned()) + Ok(buf.to_bytes().to_vec()) } } @@ -855,6 +883,17 @@ pub struct AncillaryMessage { pub data: Vec, } +#[cfg(all(unix, not(target_os = "redox")))] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum AncillaryDataStatus { + /// Every control message in `ancdata` is complete. + Complete, + /// The last message in `ancdata` holds only the part of its payload that fit. + Truncated, + /// Parsing stopped at a header that is not included in `ancdata`. + Malformed, +} + #[cfg(all(unix, not(target_os = "redox")))] pub type SocketAddressBytes = [u8; core::mem::size_of::()]; @@ -870,26 +909,102 @@ pub struct RawSocketAddress { pub struct RecvMsgResult { pub data: Vec, pub ancdata: Vec, + pub ancdata_status: AncillaryDataStatus, pub msg_flags: i32, pub address: Option, } +#[cfg(all(unix, not(target_os = "redox")))] +#[derive(Debug)] +pub struct RecvMsgIntoResult { + pub bytes_read: usize, + pub ancdata: Vec, + pub ancdata_status: AncillaryDataStatus, + pub msg_flags: i32, + pub address: Option, +} + +// Owned, zero-initialized msg_control storage aligned to 16 bytes. +#[cfg(all(unix, not(target_os = "redox")))] +#[repr(C, align(16))] +#[derive(Clone, Copy)] +struct ControlBufferUnit([u8; 16]); + +#[cfg(all(unix, not(target_os = "redox")))] +pub struct ControlBuffer { + storage: Vec, + len: usize, +} + +#[cfg(all(unix, not(target_os = "redox")))] +impl ControlBuffer { + pub fn new(len: usize) -> Option { + const UNIT: usize = 16; + let n_units = len.div_ceil(UNIT); + let alloc_size = n_units.checked_mul(UNIT)?; + if isize::try_from(alloc_size).is_err() { + return None; + } + Some(Self { + storage: vec![ControlBufferUnit([0; UNIT]); n_units], + len, + }) + } + + pub fn len(&self) -> usize { + self.len + } + + pub fn is_empty(&self) -> bool { + self.len == 0 + } + + pub fn as_mut_ptr(&mut self) -> *mut u8 { + self.storage.as_mut_ptr().cast() + } +} + +#[cfg(all(unix, not(target_os = "redox")))] +impl core::ops::Deref for ControlBuffer { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + // SAFETY: `storage` is zero-initialized and contains at least `len` bytes. + unsafe { core::slice::from_raw_parts(self.storage.as_ptr().cast(), self.len) } + } +} + #[cfg(all(unix, not(target_os = "redox")))] #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum AncillaryPackError { ItemTooLarge, TooMuchData, - UnexpectedNullHeader, + UnexpectedNullFirstHeader, + UnexpectedNullNextHeader, + ItemSizeOutOfRange, + DoesNotFit, +} + +#[cfg(target_os = "linux")] +#[derive(Debug)] +pub enum AfAlgControlError { + UnexpectedNullFirstHeader, + UnexpectedNullNextHeaderIv, + UnexpectedNullNextHeaderAssoc, + NoMemory, } +#[cfg(all(unix, not(target_os = "redox")))] +pub const SOCKLEN_T_LIMIT: usize = i32::MAX as usize; + #[cfg(all(unix, not(target_os = "redox")))] pub fn checked_cmsg_len(len: usize) -> Option { let cmsg_len = |length| unsafe { libc::CMSG_LEN(length) }; - if len as u64 > (i32::MAX as u64 - cmsg_len(0) as u64) { + if len as u64 > (SOCKLEN_T_LIMIT as u64 - cmsg_len(0) as u64) { return None; } let res = cmsg_len(len as _) as usize; - if res > i32::MAX as usize || res < len { + if res > SOCKLEN_T_LIMIT || res < len { return None; } Some(res) @@ -898,88 +1013,422 @@ pub fn checked_cmsg_len(len: usize) -> Option { #[cfg(all(unix, not(target_os = "redox")))] pub fn checked_cmsg_space(len: usize) -> Option { let cmsg_space = |length| unsafe { libc::CMSG_SPACE(length) }; - if len as u64 > (i32::MAX as u64 - cmsg_space(1) as u64) { + if len as u64 > (SOCKLEN_T_LIMIT as u64 - cmsg_space(1) as u64) { return None; } let res = cmsg_space(len as _) as usize; - if res > i32::MAX as usize || res < len { + if res > SOCKLEN_T_LIMIT || res < len { return None; } Some(res) } #[cfg(all(unix, not(target_os = "redox")))] -pub fn pack_ancillary_messages(cmsgs: &[(i32, i32, &[u8])]) -> Result, AncillaryPackError> { - use core::{mem, ptr}; +fn cmsg_min_space(msg: &libc::msghdr, cmsgh: *mut libc::cmsghdr, mut space: usize) -> bool { + if cmsgh.is_null() || msg.msg_control.is_null() { + return false; + } + #[allow( + clippy::useless_conversion, + reason = "msg_controllen is not usize on all platforms" + )] + let Some(controllen) = usize::try_from(msg.msg_controllen).ok() else { + return false; + }; + // SAFETY: `cmsghdr` contains only integer fields; zero is a valid bit pattern. + let dummy: libc::cmsghdr = unsafe { core::mem::zeroed() }; + let cmsg_len_end = + core::mem::offset_of!(libc::cmsghdr, cmsg_len) + core::mem::size_of_val(&dummy.cmsg_len); + if space < cmsg_len_end { + space = cmsg_len_end; + } + let cmsg_offset = cmsgh.addr().wrapping_sub(msg.msg_control.addr()); + cmsg_offset <= usize::MAX - space && cmsg_offset + space <= controllen +} + +#[cfg(all(unix, not(target_os = "redox")))] +fn get_cmsg_data_space(msg: &libc::msghdr, cmsgh: *mut libc::cmsghdr, space: &mut usize) -> bool { + // SAFETY: `cmsgh` is a control header associated with `msg`. + let data_ptr = unsafe { libc::CMSG_DATA(cmsgh) }; + if data_ptr.is_null() { + return false; + } + let data_offset = data_ptr.addr().wrapping_sub(msg.msg_control.addr()); + #[allow( + clippy::useless_conversion, + reason = "msg_controllen is not usize on all platforms" + )] + let Some(controllen) = usize::try_from(msg.msg_controllen).ok() else { + return false; + }; + if data_offset > controllen { + return false; + } + *space = controllen - data_offset; + true +} + +/// Returns -1 if `cmsgh` is invalid, 0 if its payload is fully contained, and 1 +/// if only part of the payload is in the buffer. `data_len` is the contained +/// payload length when the result is 0 or 1. +#[cfg(all(unix, not(target_os = "redox")))] +fn get_cmsg_data_len(msg: &libc::msghdr, cmsgh: *mut libc::cmsghdr, data_len: &mut usize) -> i32 { + // SAFETY: `CMSG_LEN` is a length macro over integer fields. + let cmsg_len_0 = unsafe { libc::CMSG_LEN(0) }; + if !cmsg_min_space(msg, cmsgh, cmsg_len_0 as usize) { + return -1; + } + // SAFETY: `cmsg_min_space` with `CMSG_LEN(0)` confirmed the `cmsg_len` + // field lies in the control buffer. + let cmsg_len = unsafe { (*cmsgh).cmsg_len }; + if (cmsg_len as u64) < (cmsg_len_0 as u64) { + return -1; + } + let cmsg_data_len = (cmsg_len as u64 - cmsg_len_0 as u64) as usize; + let mut space = 0usize; + if !get_cmsg_data_space(msg, cmsgh, &mut space) { + return -1; + } + if space >= cmsg_data_len { + *data_len = cmsg_data_len; + 0 + } else { + *data_len = space; + 1 + } +} - if cmsgs.is_empty() { - return Ok(vec![]); +/// Walk `CMSG_FIRSTHDR` / `CMSG_NXTHDR` on the `msghdr` returned by recvmsg. +#[cfg(all(unix, not(target_os = "redox")))] +fn parse_ancillary_from_msg(msg: &libc::msghdr) -> (Vec, AncillaryDataStatus) { + let mut result = Vec::new(); + // POSIX allows a signed `msg_controllen`; skip `CMSG_FIRSTHDR` when empty. + #[allow( + clippy::useless_conversion, + reason = "msg_controllen is not usize on all platforms" + )] + let has_control = usize::try_from(msg.msg_controllen).is_ok_and(|n| n > 0); + let mut cmsgh = if has_control { + // SAFETY: `msg.msg_control` is the aligned control buffer of + // `msg.msg_controllen` bytes filled by recvmsg or a pack helper. + unsafe { libc::CMSG_FIRSTHDR(msg) } + } else { + core::ptr::null_mut() + }; + while !cmsgh.is_null() { + let mut cmsgdatalen = 0usize; + let cmsg_status = get_cmsg_data_len(msg, cmsgh, &mut cmsgdatalen); + if cmsg_status < 0 { + return (result, AncillaryDataStatus::Malformed); + } + // SAFETY: status 0 or 1 means `CMSG_DATA` and `cmsgdatalen` bytes lie + // in the control buffer, and the header fields are readable. + let (level, kind, data) = unsafe { + let src = libc::CMSG_DATA(cmsgh); + ( + (*cmsgh).cmsg_level, + (*cmsgh).cmsg_type, + core::slice::from_raw_parts(src, cmsgdatalen).to_vec(), + ) + }; + result.push(AncillaryMessage { level, kind, data }); + if cmsg_status != 0 { + return (result, AncillaryDataStatus::Truncated); + } + // SAFETY: `cmsgh` came from `CMSG_FIRSTHDR`/`CMSG_NXTHDR` on `msg`. + cmsgh = unsafe { libc::CMSG_NXTHDR(msg, cmsgh) }; } + (result, AncillaryDataStatus::Complete) +} + +#[cfg(all(unix, not(target_os = "redox")))] +pub fn pack_ancillary_messages( + cmsgs: &[(i32, i32, &[u8])], +) -> Result { + use core::{mem, ptr}; - let capacity = cmsgs + let controllen = cmsgs .iter() .map(|(_, _, buf)| buf.len()) .try_fold(0usize, |sum, len| { let space = checked_cmsg_space(len).ok_or(AncillaryPackError::ItemTooLarge)?; - usize::checked_add(sum, space).ok_or(AncillaryPackError::TooMuchData) + match usize::checked_add(sum, space) { + Some(next) if next <= SOCKLEN_T_LIMIT => Ok(next), + _ => Err(AncillaryPackError::TooMuchData), + } })?; - let mut cmsg_buffer = vec![0u8; capacity]; - let mut mhdr = unsafe { mem::zeroed::() }; - mhdr.msg_control = cmsg_buffer.as_mut_ptr().cast(); - mhdr.msg_controllen = capacity as _; + let mut control_buf = ControlBuffer::new(controllen).ok_or(AncillaryPackError::TooMuchData)?; - let mut pmhdr: *mut libc::cmsghdr = unsafe { libc::CMSG_FIRSTHDR(&mhdr) }; - for (lvl, typ, data) in cmsgs { - if pmhdr.is_null() { - return Err(AncillaryPackError::UnexpectedNullHeader); + // SAFETY: `msghdr` is a POD of pointers and integers; zero is a valid bit pattern. + let mut msg = unsafe { mem::zeroed::() }; + msg.msg_control = control_buf.as_mut_ptr().cast(); + msg.msg_controllen = controllen as _; + + let mut cmsgh: *mut libc::cmsghdr = ptr::null_mut(); + for (i, (lvl, typ, data)) in cmsgs.iter().enumerate() { + // SAFETY: `msg.msg_control` points at `control_buf`'s aligned, zeroed + // storage of `msg.msg_controllen` bytes. After the first header, + // `cmsgh` is a previous CMSG_* result in that buffer; remaining + // bytes stay zero so CMSG_NXTHDR can inspect the next header. + cmsgh = unsafe { + if i == 0 { + libc::CMSG_FIRSTHDR(&msg) + } else { + libc::CMSG_NXTHDR(&msg, cmsgh) + } + }; + if cmsgh.is_null() { + return Err(if i == 0 { + AncillaryPackError::UnexpectedNullFirstHeader + } else { + AncillaryPackError::UnexpectedNullNextHeader + }); + } + let msg_len = checked_cmsg_len(data.len()).ok_or(AncillaryPackError::ItemSizeOutOfRange)?; + let enough_space = if cmsg_min_space(&msg, cmsgh, msg_len) { + // SAFETY: `cmsg_min_space` confirmed `cmsgh` lies in the control + // buffer with room for the `cmsg_len` field. + unsafe { + #[allow( + clippy::unnecessary_cast, + reason = "cmsg_len is not usize on all platforms" + )] + { + (*cmsgh).cmsg_len = msg_len as _; + } + } + let mut space = 0usize; + get_cmsg_data_space(&msg, cmsgh, &mut space) && space >= data.len() + } else { + false + }; + if !enough_space { + return Err(AncillaryPackError::DoesNotFit); } - let cmsg_len = checked_cmsg_len(data.len()).ok_or(AncillaryPackError::ItemTooLarge)?; + // SAFETY: `enough_space` means the header and `data.len()` payload + // bytes fit in the control buffer. `CMSG_DATA` yields the payload + // pointer for this header. unsafe { - (*pmhdr).cmsg_level = *lvl; - (*pmhdr).cmsg_type = *typ; - (*pmhdr).cmsg_len = cmsg_len as _; - ptr::copy_nonoverlapping(data.as_ptr(), libc::CMSG_DATA(pmhdr), data.len()); - pmhdr = libc::CMSG_NXTHDR(&mhdr, pmhdr); + (*cmsgh).cmsg_level = *lvl; + (*cmsgh).cmsg_type = *typ; + ptr::copy_nonoverlapping(data.as_ptr(), libc::CMSG_DATA(cmsgh), data.len()); } } - Ok(cmsg_buffer) + Ok(control_buf) } +#[cfg(test)] #[cfg(all(unix, not(target_os = "redox")))] -pub fn parse_ancillary_messages(control: &[u8]) -> Vec { - use core::mem; +mod ancillary_parse_tests { + use super::{ + AncillaryDataStatus, ControlBuffer, checked_cmsg_len, pack_ancillary_messages, + parse_ancillary_from_msg, recvmsg, + }; + use std::os::fd::{AsFd, AsRawFd, FromRawFd, OwnedFd}; + + fn msghdr_for_control(control: &ControlBuffer) -> libc::msghdr { + // SAFETY: `msghdr` is a POD of pointers and integers. + let mut msg = unsafe { core::mem::zeroed::() }; + msg.msg_control = control.as_ptr() as *mut _; + msg.msg_controllen = control.len() as _; + msg + } - if control.is_empty() { - return Vec::new(); + #[test] + fn parses_packed_messages_from_msghdr() { + let packed = pack_ancillary_messages(&[ + (1, 2, b"".as_slice()), + (7, 8, b"abc".as_slice()), + (9, 10, b"z".as_slice()), + ]) + .unwrap(); + let msg = msghdr_for_control(&packed); + let (messages, status) = parse_ancillary_from_msg(&msg); + assert_eq!(status, AncillaryDataStatus::Complete); + assert_eq!(messages.len(), 3); + assert_eq!((messages[0].level, messages[0].kind), (1, 2)); + assert!(messages[0].data.is_empty()); + assert_eq!((messages[1].level, messages[1].kind), (7, 8)); + assert_eq!(messages[1].data.as_slice(), b"abc"); + assert_eq!((messages[2].level, messages[2].kind), (9, 10)); + assert_eq!(messages[2].data.as_slice(), b"z"); } - let mut msg = unsafe { mem::zeroed::() }; - msg.msg_control = control.as_ptr() as *mut _; - msg.msg_controllen = control.len() as _; + #[test] + fn truncated_payload_returns_truncated() { + let packed = pack_ancillary_messages(&[(1, 2, b"abcdef".as_slice())]).unwrap(); + let data_offset = checked_cmsg_len(0).unwrap(); + let mut msg = msghdr_for_control(&packed); + msg.msg_controllen = (data_offset + 2) as _; + let (messages, status) = parse_ancillary_from_msg(&msg); + assert_eq!(status, AncillaryDataStatus::Truncated); + assert_eq!(messages.len(), 1); + assert_eq!(messages[0].data.as_slice(), b"ab"); + } - let ctrl_buf = msg.msg_control as *const u8; - let ctrl_end = unsafe { ctrl_buf.add(msg.msg_controllen as _) }; + #[test] + fn undersized_cmsg_len_returns_malformed() { + let mut packed = pack_ancillary_messages(&[(1, 2, b"x".as_slice())]).unwrap(); + // SAFETY: `msghdr` is a POD of pointers and integers. + let mut msg = unsafe { core::mem::zeroed::() }; + msg.msg_control = packed.as_mut_ptr().cast(); + msg.msg_controllen = packed.len() as _; + // SAFETY: `CMSG_FIRSTHDR` returns the packed header in `packed`. + let cmsgh = unsafe { libc::CMSG_FIRSTHDR(&msg) }; + assert!(!cmsgh.is_null()); + // SAFETY: `cmsgh` is the aligned first header in `packed`. + unsafe { + (*cmsgh).cmsg_len = 1; + } + let (messages, status) = parse_ancillary_from_msg(&msg); + assert_eq!(status, AncillaryDataStatus::Malformed); + assert!(messages.is_empty()); + } - let mut result = Vec::new(); - let mut cmsg: *mut libc::cmsghdr = unsafe { libc::CMSG_FIRSTHDR(&msg) }; - while !cmsg.is_null() { - let cmsg_ref = unsafe { &*cmsg }; - let data_ptr = unsafe { libc::CMSG_DATA(cmsg) }; - let data_len_from_cmsg = cmsg_ref.cmsg_len as usize - (data_ptr as usize - cmsg as usize); - let available = ctrl_end as usize - data_ptr as usize; - let data_len = data_len_from_cmsg.min(available); - let data = unsafe { core::slice::from_raw_parts(data_ptr, data_len) }; - result.push(AncillaryMessage { - level: cmsg_ref.cmsg_level, - kind: cmsg_ref.cmsg_type, - data: data.to_vec(), - }); - cmsg = unsafe { libc::CMSG_NXTHDR(&msg, cmsg) }; + #[test] + fn recvmsg_round_trips_scm_rights() { + let mut pair = [0i32; 2]; + // SAFETY: `pair` has room for two descriptors. + let rc = + unsafe { libc::socketpair(libc::AF_UNIX, libc::SOCK_STREAM, 0, pair.as_mut_ptr()) }; + assert_eq!(rc, 0); + // SAFETY: `socketpair` filled both slots with owned descriptors. + let send = unsafe { OwnedFd::from_raw_fd(pair[0]) }; + let recv = unsafe { OwnedFd::from_raw_fd(pair[1]) }; + + let mut payload = [0i32; 2]; + // SAFETY: `payload` has room for the read and write ends. + let rc = unsafe { libc::pipe(payload.as_mut_ptr()) }; + assert_eq!(rc, 0); + // SAFETY: `pipe` filled both slots with owned descriptors. + let pipe_r = unsafe { OwnedFd::from_raw_fd(payload[0]) }; + let pipe_w = unsafe { OwnedFd::from_raw_fd(payload[1]) }; + + let fd_bytes = pipe_r.as_raw_fd().to_ne_bytes(); + let packed = + pack_ancillary_messages(&[(libc::SOL_SOCKET, libc::SCM_RIGHTS, fd_bytes.as_slice())]) + .unwrap(); + + let mut iov_buf = *b"x"; + let mut iov = [libc::iovec { + iov_base: iov_buf.as_mut_ptr().cast(), + iov_len: 1, + }]; + // SAFETY: `msghdr` is a POD of pointers and integers. + let mut msg = unsafe { core::mem::zeroed::() }; + msg.msg_iov = iov.as_mut_ptr(); + msg.msg_iovlen = 1; + msg.msg_control = packed.as_ptr() as *mut _; + msg.msg_controllen = packed.len() as _; + // SAFETY: `iov` and `packed` live until `sendmsg` returns. + let n = unsafe { libc::sendmsg(send.as_raw_fd(), &msg, 0) }; + assert!(n >= 0); + + let result = recvmsg(recv.as_fd(), 16, packed.len() + 64, 0).unwrap(); + assert_eq!(result.data.as_slice(), b"x"); + assert_eq!(result.ancdata_status, AncillaryDataStatus::Complete); + assert_eq!(result.ancdata.len(), 1); + assert_eq!(result.ancdata[0].level, libc::SOL_SOCKET); + assert_eq!(result.ancdata[0].kind, libc::SCM_RIGHTS); + let received = i32::from_ne_bytes(result.ancdata[0].data[..4].try_into().unwrap()); + assert!(received >= 0); + // SAFETY: recvmsg transferred this descriptor. + drop(unsafe { OwnedFd::from_raw_fd(received) }); + drop(pipe_w); + } +} + +#[cfg(test)] +#[cfg(all(unix, not(target_os = "redox")))] +mod ancillary_pack_tests { + use super::{ + AncillaryDataStatus, ControlBuffer, pack_ancillary_messages, parse_ancillary_from_msg, + }; + + #[test] + fn packs_messages_aligned_and_round_trips() { + let packed = pack_ancillary_messages(&[ + (1, 2, b"".as_slice()), + (7, 8, b"abc".as_slice()), + (9, 10, b"z".as_slice()), + ]) + .unwrap(); + assert!((packed.as_ptr() as usize).is_multiple_of(16)); + // SAFETY: `msghdr` is a POD of pointers and integers. + let mut msg = unsafe { core::mem::zeroed::() }; + msg.msg_control = packed.as_ptr() as *mut _; + msg.msg_controllen = packed.len() as _; + let (messages, status) = parse_ancillary_from_msg(&msg); + assert_eq!(status, AncillaryDataStatus::Complete); + assert_eq!(messages.len(), 3); + assert_eq!((messages[0].level, messages[0].kind), (1, 2)); + assert!(messages[0].data.is_empty()); + assert_eq!((messages[1].level, messages[1].kind), (7, 8)); + assert_eq!(messages[1].data.as_slice(), b"abc"); + assert_eq!((messages[2].level, messages[2].kind), (9, 10)); + assert_eq!(messages[2].data.as_slice(), b"z"); + } + + #[test] + fn pack_empty_input_is_empty() { + let packed = pack_ancillary_messages(&[]).unwrap(); + assert!(packed.is_empty()); } - result + #[test] + fn control_buffer_rejects_overflow_len() { + assert!(ControlBuffer::new(usize::MAX).is_none()); + } +} + +#[cfg(test)] +#[cfg(target_os = "linux")] +mod sendmsg_afalg_tests { + use super::pack_sendmsg_afalg; + + #[test] + fn packs_op_iv_and_assoc_headers() { + let iv = b"iviv"; + let mut packed = pack_sendmsg_afalg(1, Some(iv.as_slice()), Some(4)).unwrap(); + // SAFETY: `msghdr` is a POD of pointers and integers. + let mut msg = unsafe { core::mem::zeroed::() }; + msg.msg_control = packed.as_mut_ptr().cast(); + msg.msg_controllen = packed.len() as _; + // SAFETY: `packed` is an aligned, zeroed control buffer. + let first = unsafe { libc::CMSG_FIRSTHDR(&msg) }; + assert!(!first.is_null()); + // SAFETY: `first` is the OP header in `packed`. + unsafe { + assert_eq!((*first).cmsg_level, libc::SOL_ALG); + assert_eq!((*first).cmsg_type, libc::ALG_SET_OP); + assert_eq!((*first).cmsg_len, libc::CMSG_LEN(4) as _); + assert_eq!(libc::CMSG_DATA(first).cast::().read(), 1); + } + // SAFETY: `first` is a CMSG header in `packed`. + let iv_hdr = unsafe { libc::CMSG_NXTHDR(&msg, first) }; + assert!(!iv_hdr.is_null()); + let iv_payload = core::mem::size_of::() + iv.len(); + // SAFETY: `iv_hdr` is the IV header in `packed`. + unsafe { + assert_eq!((*iv_hdr).cmsg_type, libc::ALG_SET_IV); + assert_eq!((*iv_hdr).cmsg_len, libc::CMSG_SPACE(iv_payload as _) as _); + assert_eq!( + libc::CMSG_DATA(iv_hdr).cast::().read(), + iv.len() as u32 + ); + } + // SAFETY: `iv_hdr` is a CMSG header in `packed`. + let assoc = unsafe { libc::CMSG_NXTHDR(&msg, iv_hdr) }; + assert!(!assoc.is_null()); + // SAFETY: `assoc` is the assoclen header in `packed`. + unsafe { + assert_eq!((*assoc).cmsg_type, libc::ALG_SET_AEAD_ASSOCLEN); + assert_eq!((*assoc).cmsg_len, libc::CMSG_LEN(4) as _); + assert_eq!(libc::CMSG_DATA(assoc).cast::().read(), 4); + } + } } #[cfg(all(unix, not(target_os = "redox")))] @@ -991,35 +1440,80 @@ pub fn recvmsg( ) -> io::Result { use core::mem::MaybeUninit; - let mut data_buf: Vec> = vec![MaybeUninit::uninit(); bufsize]; - let mut anc_buf: Vec> = vec![MaybeUninit::uninit(); ancbufsize]; - let mut addr_storage: libc::sockaddr_storage = unsafe { core::mem::zeroed() }; + // MSG_TRUNC on Linux TCP can report consumed bytes without writing data. + let initial = if flags & libc::MSG_TRUNC != 0 { + MaybeUninit::new(0) + } else { + MaybeUninit::uninit() + }; + let mut data_buf = vec![initial; bufsize]; + let result = recvmsg_into(fd, &mut [&mut data_buf], ancbufsize, flags)?; + let data = unsafe { + // Datagram MSG_TRUNC may report more bytes than the supplied storage. + data_buf.set_len(result.bytes_read.min(bufsize)); + core::mem::transmute::>, Vec>(data_buf) + }; + Ok(RecvMsgResult { + data, + ancdata: result.ancdata, + ancdata_status: result.ancdata_status, + msg_flags: result.msg_flags, + address: result.address, + }) +} - let mut iov = [libc::iovec { - iov_base: data_buf.as_mut_ptr().cast(), - iov_len: bufsize, - }]; +#[cfg(all(unix, not(target_os = "redox")))] +pub fn recvmsg_into( + fd: BorrowedFd<'_>, + buffers: &mut [&mut [core::mem::MaybeUninit]], + ancbufsize: usize, + flags: i32, +) -> io::Result { + use core::mem::MaybeUninit; + let as_iovec = |buf: &mut [MaybeUninit]| libc::iovec { + iov_base: buf.as_mut_ptr().cast(), + iov_len: buf.len(), + }; + let mut single; + let mut multiple; + let iov: &mut [libc::iovec] = if let [buf] = buffers { + single = [as_iovec(buf)]; + &mut single + } else { + multiple = buffers + .iter_mut() + .map(|buf| as_iovec(buf)) + .collect::>(); + &mut multiple + }; + let mut anc_buf = ControlBuffer::new(ancbufsize) + .ok_or_else(|| io::Error::from(io::ErrorKind::OutOfMemory))?; + let mut addr_storage: libc::sockaddr_storage = unsafe { core::mem::zeroed() }; let mut msg: libc::msghdr = unsafe { core::mem::zeroed() }; msg.msg_name = (&mut addr_storage as *mut libc::sockaddr_storage).cast(); msg.msg_namelen = core::mem::size_of::() as libc::socklen_t; msg.msg_iov = iov.as_mut_ptr(); - msg.msg_iovlen = 1; + // These msghdr fields are narrower on some Unix targets. + #[allow(clippy::useless_conversion)] + let iovlen = iov + .len() + .try_into() + .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + msg.msg_iovlen = iovlen; if ancbufsize > 0 { msg.msg_control = anc_buf.as_mut_ptr().cast(); - msg.msg_controllen = ancbufsize as _; + #[allow(clippy::useless_conversion)] + let controllen = ancbufsize + .try_into() + .map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + msg.msg_controllen = controllen; } + // SAFETY: all iovecs refer to disjoint writable slices; the control and address + // buffers are aligned and live until the syscall returns. let ret = unsafe { libc::recvmsg(fd.as_raw_fd(), &mut msg, flags) }.check_libc_neg()?; - - let data = unsafe { - data_buf.set_len(ret as usize); - core::mem::transmute::>, Vec>(data_buf) - }; - let control = unsafe { - core::slice::from_raw_parts(anc_buf.as_ptr().cast::(), msg.msg_controllen as usize) - }; - let ancdata = parse_ancillary_messages(control); + let (ancdata, ancdata_status) = parse_ancillary_from_msg(&msg); let address = if msg.msg_namelen > 0 { let storage = unsafe { core::mem::transmute::(addr_storage) @@ -1031,94 +1525,100 @@ pub fn recvmsg( } else { None }; - - Ok(RecvMsgResult { - data, + Ok(RecvMsgIntoResult { + bytes_read: ret as usize, ancdata, + ancdata_status, msg_flags: msg.msg_flags, address, }) } +/// Build the AF_ALG control buffer: OP, then optional IV, then optional assoclen. #[cfg(target_os = "linux")] -pub fn sendmsg_afalg( - fd: BorrowedFd<'_>, - buffers: &[io::IoSlice<'_>], +pub fn pack_sendmsg_afalg( op: u32, iv: Option<&[u8]>, assoclen: Option, - flags: i32, -) -> io::Result { - let mut control_buf = Vec::new(); - - { - let op_bytes = op.to_ne_bytes(); - let space = unsafe { libc::CMSG_SPACE(core::mem::size_of::() as u32) } as usize; - let old_len = control_buf.len(); - control_buf.resize(old_len + space, 0u8); +) -> Result { + use core::mem; - let cmsg = control_buf[old_len..].as_mut_ptr() as *mut libc::cmsghdr; - unsafe { - (*cmsg).cmsg_len = libc::CMSG_LEN(core::mem::size_of::() as u32) as _; - (*cmsg).cmsg_level = libc::SOL_ALG; - (*cmsg).cmsg_type = libc::ALG_SET_OP; - let data = libc::CMSG_DATA(cmsg); - core::ptr::copy_nonoverlapping(op_bytes.as_ptr(), data, op_bytes.len()); - } + // SAFETY: `CMSG_SPACE` is a length macro over integer fields. + let word_space = unsafe { libc::CMSG_SPACE(4) } as usize; + let mut controllen = word_space; + if let Some(iv) = iv { + let iv_payload = mem::size_of::() + .checked_add(iv.len()) + .ok_or(AfAlgControlError::NoMemory)?; + // SAFETY: `CMSG_SPACE` is a length macro over integer fields. + let iv_space = unsafe { libc::CMSG_SPACE(iv_payload as _) } as usize; + controllen = controllen + .checked_add(iv_space) + .ok_or(AfAlgControlError::NoMemory)?; + } + if assoclen.is_some() { + controllen = controllen + .checked_add(word_space) + .ok_or(AfAlgControlError::NoMemory)?; } - if let Some(iv_bytes) = iv { - let iv_struct_size = 4 + iv_bytes.len(); - let space = unsafe { libc::CMSG_SPACE(iv_struct_size as u32) } as usize; - let old_len = control_buf.len(); - control_buf.resize(old_len + space, 0u8); + let mut control_buf = ControlBuffer::new(controllen).ok_or(AfAlgControlError::NoMemory)?; - let cmsg = control_buf[old_len..].as_mut_ptr() as *mut libc::cmsghdr; - unsafe { - (*cmsg).cmsg_len = libc::CMSG_LEN(iv_struct_size as u32) as _; - (*cmsg).cmsg_level = libc::SOL_ALG; - (*cmsg).cmsg_type = libc::ALG_SET_IV; - let data = libc::CMSG_DATA(cmsg); - let ivlen = (iv_bytes.len() as u32).to_ne_bytes(); - core::ptr::copy_nonoverlapping(ivlen.as_ptr(), data, 4); - core::ptr::copy_nonoverlapping(iv_bytes.as_ptr(), data.add(4), iv_bytes.len()); - } + // SAFETY: `msghdr` is a POD of pointers and integers; zero is a valid bit pattern. + let mut msg = unsafe { mem::zeroed::() }; + msg.msg_control = control_buf.as_mut_ptr().cast(); + msg.msg_controllen = controllen as _; + + // SAFETY: `msg.msg_control` points at `control_buf`'s aligned, zeroed + // storage of `msg.msg_controllen` bytes. + let mut header = unsafe { libc::CMSG_FIRSTHDR(&msg) }; + if header.is_null() { + return Err(AfAlgControlError::UnexpectedNullFirstHeader); + } + // SAFETY: `CMSG_FIRSTHDR` returned a header in the zeroed control buffer. + unsafe { + (*header).cmsg_level = libc::SOL_ALG; + (*header).cmsg_type = libc::ALG_SET_OP; + (*header).cmsg_len = libc::CMSG_LEN(4) as _; + libc::CMSG_DATA(header).cast::().write(op); } - if let Some(assoclen_val) = assoclen { - let assoclen_bytes = assoclen_val.to_ne_bytes(); - let space = unsafe { libc::CMSG_SPACE(core::mem::size_of::() as u32) } as usize; - let old_len = control_buf.len(); - control_buf.resize(old_len + space, 0u8); - - let cmsg = control_buf[old_len..].as_mut_ptr() as *mut libc::cmsghdr; + if let Some(iv) = iv { + // SAFETY: `header` is a previous CMSG_* result in the zeroed buffer. + header = unsafe { libc::CMSG_NXTHDR(&msg, header) }; + if header.is_null() { + return Err(AfAlgControlError::UnexpectedNullNextHeaderIv); + } + let iv_payload = mem::size_of::() + .checked_add(iv.len()) + .ok_or(AfAlgControlError::NoMemory)?; + // SAFETY: `CMSG_NXTHDR` returned the IV header in the control buffer. unsafe { - (*cmsg).cmsg_len = libc::CMSG_LEN(core::mem::size_of::() as u32) as _; - (*cmsg).cmsg_level = libc::SOL_ALG; - (*cmsg).cmsg_type = libc::ALG_SET_AEAD_ASSOCLEN; - let data = libc::CMSG_DATA(cmsg); - core::ptr::copy_nonoverlapping(assoclen_bytes.as_ptr(), data, assoclen_bytes.len()); + (*header).cmsg_level = libc::SOL_ALG; + (*header).cmsg_type = libc::ALG_SET_IV; + (*header).cmsg_len = libc::CMSG_SPACE(iv_payload as _) as _; + let data = libc::CMSG_DATA(header); + data.cast::().write(iv.len() as u32); + core::ptr::copy_nonoverlapping(iv.as_ptr(), data.add(mem::size_of::()), iv.len()); } } - let iovecs: Vec = buffers - .iter() - .map(|buf| libc::iovec { - iov_base: buf.as_ptr() as *mut _, - iov_len: buf.len(), - }) - .collect(); - - let mut msghdr: libc::msghdr = unsafe { core::mem::zeroed() }; - msghdr.msg_iov = iovecs.as_ptr() as *mut _; - msghdr.msg_iovlen = iovecs.len() as _; - if !control_buf.is_empty() { - msghdr.msg_control = control_buf.as_mut_ptr() as *mut _; - msghdr.msg_controllen = control_buf.len() as _; + if let Some(assoclen) = assoclen { + // SAFETY: `header` is a previous CMSG_* result in the zeroed buffer. + header = unsafe { libc::CMSG_NXTHDR(&msg, header) }; + if header.is_null() { + return Err(AfAlgControlError::UnexpectedNullNextHeaderAssoc); + } + // SAFETY: `CMSG_NXTHDR` returned the assoclen header in the control buffer. + unsafe { + (*header).cmsg_level = libc::SOL_ALG; + (*header).cmsg_type = libc::ALG_SET_AEAD_ASSOCLEN; + (*header).cmsg_len = libc::CMSG_LEN(4) as _; + libc::CMSG_DATA(header).cast::().write(assoclen); + } } - let ret = unsafe { libc::sendmsg(fd.as_raw_fd(), &msghdr, flags) }.check_libc_neg()?; - Ok(ret as usize) + Ok(control_buf) } #[cfg(windows)] diff --git a/crates/host_env/src/socket/bluetooth.rs b/crates/host_env/src/socket/bluetooth.rs new file mode 100644 index 00000000000..0b803282a72 --- /dev/null +++ b/crates/host_env/src/socket/bluetooth.rs @@ -0,0 +1,185 @@ +//! Linux Bluetooth socket address layouts from the BlueZ headers. + +use super::raw::{SockAddr, SockAddrStorage}; + +pub const L2CAP: i32 = 0; +pub const HCI: i32 = 1; +pub const SCO: i32 = 2; +pub const RFCOMM: i32 = 3; + +#[repr(C)] +struct SockaddrL2 { + family: libc::sa_family_t, + psm: u16, + bdaddr: [u8; 6], + cid: u16, + addr_type: u8, +} + +#[repr(C)] +struct SockaddrRc { + family: libc::sa_family_t, + bdaddr: [u8; 6], + channel: u8, +} + +#[repr(C)] +struct SockaddrHci { + family: libc::sa_family_t, + dev: u16, + channel: u16, +} + +#[repr(C)] +struct SockaddrSco { + family: libc::sa_family_t, + bdaddr: [u8; 6], +} + +#[derive(Debug, PartialEq, Eq)] +pub enum Address { + L2cap { + bdaddr: [u8; 6], + psm: u16, + cid: u16, + addr_type: u8, + }, + Rfcomm { + bdaddr: [u8; 6], + channel: u8, + }, + Hci { + dev: u16, + channel: u16, + }, + Sco { + bdaddr: [u8; 6], + }, +} + +impl Address { + pub fn to_sockaddr(&self) -> SockAddr { + let mut storage = SockAddrStorage::zeroed(); + // SAFETY: these repr(C) layouts match the Linux sockaddr_* definitions. + // SockAddrStorage provides their size/alignment and is zero-initialized. + // Write fields in place so padding remains initialized. + let len = unsafe { + match *self { + Self::L2cap { + bdaddr, + psm, + cid, + addr_type, + } => { + let addr = storage.view_as::(); + addr.family = libc::AF_BLUETOOTH as _; + addr.psm = psm; + addr.bdaddr = bdaddr; + addr.cid = cid; + addr.addr_type = addr_type; + size_of::() + } + Self::Rfcomm { bdaddr, channel } => { + let addr = storage.view_as::(); + addr.family = libc::AF_BLUETOOTH as _; + addr.bdaddr = bdaddr; + addr.channel = channel; + size_of::() + } + Self::Hci { dev, channel } => { + let addr = storage.view_as::(); + addr.family = libc::AF_BLUETOOTH as _; + addr.dev = dev; + addr.channel = channel; + size_of::() + } + Self::Sco { bdaddr } => { + let addr = storage.view_as::(); + addr.family = libc::AF_BLUETOOTH as _; + addr.bdaddr = bdaddr; + size_of::() + } + } + }; + // SAFETY: storage contains a complete address of the stated length. + unsafe { SockAddr::new(storage, len as _) } + } + + pub fn from_sockaddr(addr: &SockAddr, protocol: i32) -> Option { + if addr.family() != libc::AF_BLUETOOTH as _ { + return None; + } + // SAFETY: SockAddr owns aligned storage; each cast checks the returned + // length. All bit patterns are valid for these integer-only layouts. + unsafe { + match protocol { + L2CAP if addr.len() as usize >= size_of::() => { + let addr = &*addr.as_ptr().cast::(); + Some(Self::L2cap { + bdaddr: addr.bdaddr, + psm: addr.psm, + cid: addr.cid, + addr_type: addr.addr_type, + }) + } + RFCOMM if addr.len() as usize >= size_of::() => { + let addr = &*addr.as_ptr().cast::(); + Some(Self::Rfcomm { + bdaddr: addr.bdaddr, + channel: addr.channel, + }) + } + HCI if addr.len() as usize >= size_of::() => { + let addr = &*addr.as_ptr().cast::(); + Some(Self::Hci { + dev: addr.dev, + channel: addr.channel, + }) + } + SCO if addr.len() as usize >= size_of::() => { + let addr = &*addr.as_ptr().cast::(); + Some(Self::Sco { + bdaddr: addr.bdaddr, + }) + } + _ => None, + } + } + } +} + +pub fn parse_bdaddr(name: &[u8]) -> Option<[u8; 6]> { + let mut parts = name.split(|&b| b == b':'); + let mut bdaddr = [0; 6]; + for byte in bdaddr.iter_mut().rev() { + // CPython's %X parser permits leading whitespace, a sign and 0x. + let part = parts.next()?.trim_ascii_start(); + let (part, negative) = match part.first() { + Some(b'+') => (&part[1..], false), + Some(b'-') => (&part[1..], true), + _ => (part, false), + }; + if part.is_empty() { + return None; + } + let part = part + .strip_prefix(b"0x") + .or_else(|| part.strip_prefix(b"0X")) + .unwrap_or(part); + let mut value = 0u8; + for &digit in part { + let digit = (digit as char).to_digit(16)? as u8; + value = value.checked_mul(16)?.checked_add(digit)?; + } + if negative && value != 0 { + return None; + } + *byte = value; + } + parts.next().is_none().then_some(bdaddr) +} + +pub fn format_bdaddr(bdaddr: [u8; 6]) -> String { + let [f, e, d, c, b, a] = bdaddr; + alloc::format!("{a:02X}:{b:02X}:{c:02X}:{d:02X}:{e:02X}:{f:02X}") +} diff --git a/crates/host_env/src/ssl/cipher.rs b/crates/host_env/src/ssl/cipher.rs index 34c50f15de1..6038cd32336 100644 --- a/crates/host_env/src/ssl/cipher.rs +++ b/crates/host_env/src/ssl/cipher.rs @@ -444,9 +444,9 @@ pub fn kx_group_by_openssl_name(name: &str) -> Option<&'static dyn SupportedKxGr fn kx_group_openssl_names(name: rustls::NamedGroup) -> &'static [&'static str] { match name { - rustls::NamedGroup::secp256r1 => &["prime256v1", "secp256r1"], - rustls::NamedGroup::secp384r1 => &["secp384r1", "prime384v1"], - rustls::NamedGroup::secp521r1 => &["secp521r1", "prime521v1"], + rustls::NamedGroup::secp256r1 => &["prime256v1", "secp256r1", "P-256"], + rustls::NamedGroup::secp384r1 => &["secp384r1", "prime384v1", "P-384"], + rustls::NamedGroup::secp521r1 => &["secp521r1", "prime521v1", "P-521"], rustls::NamedGroup::X25519 => &["X25519", "x25519"], rustls::NamedGroup::X448 => &["X448", "x448"], rustls::NamedGroup::MLKEM768 => &["MLKEM768"], diff --git a/crates/host_env/src/ssl/config.rs b/crates/host_env/src/ssl/config.rs index f19e53e189d..81fb37eda30 100644 --- a/crates/host_env/src/ssl/config.rs +++ b/crates/host_env/src/ssl/config.rs @@ -22,6 +22,7 @@ pub struct ProtocolSettings { pub versions: &'static [&'static rustls::SupportedProtocolVersion], pub kx_groups: Option>, pub cipher_suites: Option>, + pub server_sigalgs: Option>, pub alpn_protocols: Vec>, } @@ -176,12 +177,27 @@ pub fn create_server_config(options: ServerConfigOptions) -> Result + } else { + resolver + }; builder.with_cert_resolver(resolver) } else { // Use single certificate - builder - .with_single_cert(options.cert_chain, options.private_key) - .map_err(|e| format!("Failed to set server certificate: {e}"))? + let key = CertifiedKey::from_der( + options.cert_chain, + options.private_key, + CryptoExt::get_provider(), + ) + .map_err(|e| format!("Failed to set server certificate: {e}"))?; + builder.with_cert_resolver(Arc::new(MultiCertResolver::new( + vec![Arc::new(key)], + options.protocol_settings.server_sigalgs.as_deref(), + ))) }; // Set ALPN protocols with fallback @@ -432,6 +448,15 @@ pub fn create_client_config(options: ClientConfigOptions) -> Result + } else { + verifier + }; + // Step 2: Create ClientConfig builder once with the selected verifier let builder = ClientConfig::builder_with_provider(custom_provider) .with_protocol_versions(options.protocol_settings.versions) @@ -481,7 +506,15 @@ pub struct MultiCertResolver { impl MultiCertResolver { /// Create a new multi-certificate resolver - pub fn new(cert_keys: Vec>) -> Self { + pub fn new( + mut cert_keys: Vec>, + schemes: Option<&[rustls::SignatureScheme]>, + ) -> Self { + if let Some(schemes) = schemes { + for key in &mut cert_keys { + *key = super::sigalg::restrict_key(key, schemes); + } + } Self { cert_keys } } } diff --git a/crates/host_env/src/ssl/error.rs b/crates/host_env/src/ssl/error.rs index cec73e49ff7..a7ddcf613fa 100644 --- a/crates/host_env/src/ssl/error.rs +++ b/crates/host_env/src/ssl/error.rs @@ -43,6 +43,9 @@ impl TlsError { use rustls::PeerIncompatible; match peer_err { PeerIncompatible::NoCipherSuitesInCommon => Self::NoCipherSuites, + PeerIncompatible::NoSignatureSchemesInCommon => { + Self::Ssl("no signature schemes in common".to_owned()) + } _ => Self::Eof, } } @@ -66,3 +69,38 @@ impl From for TlsError { Self::Io(err) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn signature_incompatibility_is_not_transport_eof() { + let error = TlsError::from_rustls(rustls::Error::PeerIncompatible( + rustls::PeerIncompatible::NoSignatureSchemesInCommon, + )); + assert!(!error.is_eof()); + assert!(matches!(error, TlsError::Ssl(_))); + } + + #[test] + fn unrelated_negotiation_and_transport_errors_keep_their_classification() { + assert!(matches!( + TlsError::from_rustls(rustls::Error::PeerIncompatible( + rustls::PeerIncompatible::NoCipherSuitesInCommon, + )), + TlsError::NoCipherSuites + )); + assert!(matches!( + TlsError::from_rustls(rustls::Error::PeerIncompatible( + rustls::PeerIncompatible::Tls12NotOffered, + )), + TlsError::Eof + )); + let os_error = std::io::Error::from_raw_os_error(10053); + match TlsError::from(os_error) { + TlsError::Io(error) => assert_eq!(error.raw_os_error(), Some(10053)), + error => panic!("OS error was reclassified: {error:?}"), + } + } +} diff --git a/crates/host_env/src/ssl/handshake.rs b/crates/host_env/src/ssl/handshake.rs index 6df5d070ced..f70f53370e1 100644 --- a/crates/host_env/src/ssl/handshake.rs +++ b/crates/host_env/src/ssl/handshake.rs @@ -47,6 +47,34 @@ pub fn sni_alert(description: u8) -> Vec { vec![21, 3, 3, 0, 2, 2, description] } +/// Serialize a failed initial `Accepted::into_connection` attempt. +/// +/// No server bytes have been sent at this boundary. Rustls may have queued +/// ServerHello before finding that a full handshake has no usable signature, +/// or may return a signing-key error without queuing any alert (TLS 1.2). +/// Send only a plaintext fatal alert, so the peer cannot start its next flight +/// while the server is closing. Keep certificate/session selection in rustls: +/// resumed sessions do not need a new certificate signature. +pub fn initial_handshake_alert( + error: &rustls::Error, + mut alert: rustls::server::AcceptedAlert, +) -> std::io::Result> { + // TLS 1.2's emit_server_kx reports the exact General message below when + // SigningKey::choose_scheme fails; TLS 1.3 uses PeerIncompatible. + let signature_mismatch = matches!( + error, + rustls::Error::PeerIncompatible(rustls::PeerIncompatible::NoSignatureSchemesInCommon) + ) || matches!(error, rustls::Error::General(message) if message == "incompatible signing key"); + if signature_mismatch { + return Ok(sni_alert(u8::from( + rustls::AlertDescription::HandshakeFailure, + ))); + } + let mut bytes = Vec::new(); + alert.write_all(&mut bytes)?; + Ok(bytes) +} + pub fn feed_acceptor(acceptor: &mut Acceptor, bytes: &[u8]) -> std::io::Result<()> { let mut reader = std::io::Cursor::new(bytes); while reader.position() < bytes.len() as u64 { @@ -107,3 +135,322 @@ mod tests { assert_eq!(sni_alert(80), [21, 3, 3, 0, 2, 2, 80]); } } + +#[cfg(test)] +mod signature_tests { + use super::super::config::MultiCertResolver; + use super::*; + use alloc::sync::Arc; + use rustls::{ + ClientConnection, SignatureScheme, client::WebPkiServerVerifier, server::Acceptor, + }; + use rustls::{RootCertStore, SupportedCipherSuite, crypto::CryptoProvider, sign::CertifiedKey}; + use rustls::{client::ClientConfig, server::ServerConfig}; + + fn certificate_key(mut pem: &[u8], provider: &CryptoProvider) -> Arc { + let mut private_key_pem = pem; + let certificates = rustls_pemfile::certs(&mut pem) + .collect::, _>>() + .unwrap(); + let key = rustls_pemfile::private_key(&mut private_key_pem) + .unwrap() + .unwrap(); + Arc::new(CertifiedKey::from_der(certificates, key, provider).unwrap()) + } + + fn client_config( + version: &'static rustls::SupportedProtocolVersion, + scheme: SignatureScheme, + cipher_suite: Option, + ) -> Arc { + let mut provider = rustls::crypto::aws_lc_rs::default_provider(); + if let Some(suite) = cipher_suite { + provider.cipher_suites = vec![suite]; + } + let provider = Arc::new(provider); + let mut roots = RootCertStore::empty(); + let ca = include_bytes!("../../../../Lib/test/certdata/pycacert.pem"); + for cert in rustls_pemfile::certs(&mut &ca[..]) { + roots.add(cert.unwrap()).unwrap(); + } + let verifier = + WebPkiServerVerifier::builder_with_provider(Arc::new(roots), provider.clone()) + .build() + .unwrap(); + let config = ClientConfig::builder_with_provider(provider) + .with_protocol_versions(&[version]) + .unwrap() + .dangerous() + .with_custom_certificate_verifier(Arc::new(super::super::sigalg::ServerVerifier { + inner: verifier, + schemes: vec![scheme], + })) + .with_no_client_auth(); + Arc::new(config) + } + + fn client_hello(config: Arc) -> (ClientConnection, rustls::server::Accepted) { + let mut client = ClientConnection::new(config, "localhost".try_into().unwrap()).unwrap(); + let mut hello = Vec::new(); + client.write_tls(&mut hello).unwrap(); + let mut acceptor = Acceptor::default(); + super::super::handshake::feed_acceptor(&mut acceptor, &hello).unwrap(); + (client, acceptor.accept().unwrap().unwrap()) + } + + fn server_config( + version: &'static rustls::SupportedProtocolVersion, + include_incompatible_first_key: bool, + cipher_suite: Option, + scheme: SignatureScheme, + ) -> Arc { + let mut provider = rustls::crypto::aws_lc_rs::default_provider(); + if let Some(suite) = cipher_suite { + provider.cipher_suites = vec![suite]; + } + let provider = Arc::new(provider); + let mut keys = Vec::new(); + if include_incompatible_first_key { + keys.push(certificate_key( + include_bytes!("../../../../Lib/test/certdata/keycertecc.pem"), + &provider, + )); + } + keys.push(certificate_key( + include_bytes!("../../../../Lib/test/certdata/keycert3.pem"), + &provider, + )); + Arc::new( + ServerConfig::builder_with_provider(provider) + .with_protocol_versions(&[version]) + .unwrap() + .with_no_client_auth() + .with_cert_resolver(Arc::new(MultiCertResolver::new(keys, Some(&[scheme])))), + ) + } + + fn assert_signature_mismatch_sends_only_a_fatal_alert( + version: &'static rustls::SupportedProtocolVersion, + ) { + let (mut client, accepted) = client_hello(client_config( + version, + SignatureScheme::RSA_PSS_SHA256, + None, + )); + let (error, alert) = accepted + .into_connection(server_config( + version, + false, + None, + SignatureScheme::RSA_PSS_SHA384, + )) + .unwrap_err(); + let bytes = initial_handshake_alert(&error, alert).unwrap(); + assert!(matches!( + super::super::error::TlsError::from_rustls(error), + super::super::error::TlsError::Ssl(_) + )); + assert_eq!(bytes.len(), 7, "only a plaintext alert may precede failure"); + assert_eq!(bytes[0], 21, "no ServerHello or CCS may precede the alert"); + assert_eq!(&bytes[3..6], &[0, 2, 2]); + client.read_tls(&mut &bytes[..]).unwrap(); + assert!(matches!( + client.process_new_packets(), + Err(rustls::Error::AlertReceived(_)) + )); + assert!( + !client.wants_write(), + "a rejected client must not queue CCS" + ); + } + + #[test] + fn tls12_signature_mismatch_sends_only_a_fatal_alert() { + assert_signature_mismatch_sends_only_a_fatal_alert(&rustls::version::TLS12); + } + + #[test] + fn tls13_signature_mismatch_sends_only_a_fatal_alert() { + assert_signature_mismatch_sends_only_a_fatal_alert(&rustls::version::TLS13); + } + + #[test] + fn unrelated_initial_alert_and_similar_error_text_are_preserved() { + for override_error in [ + None, + Some(rustls::Error::General( + "incompatible signing key detail".into(), + )), + ] { + let (mut client, accepted) = client_hello(client_config( + &rustls::version::TLS12, + SignatureScheme::RSA_PSS_SHA384, + None, + )); + let (error, alert) = accepted + .into_connection(server_config( + &rustls::version::TLS13, + false, + None, + SignatureScheme::RSA_PSS_SHA384, + )) + .unwrap_err(); + let bytes = initial_handshake_alert(&override_error.unwrap_or(error), alert).unwrap(); + assert_eq!(bytes, sni_alert(70)); + client.read_tls(&mut &bytes[..]).unwrap(); + assert!(matches!( + client.process_new_packets(), + Err(rustls::Error::AlertReceived( + rustls::AlertDescription::ProtocolVersion + )) + )); + } + } + + #[test] + fn disjoint_cipher_suites_keep_the_no_shared_cipher_error() { + use rustls::crypto::aws_lc_rs::cipher_suite::{ + TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, + }; + let version = &rustls::version::TLS12; + let (_, accepted) = client_hello(client_config( + version, + SignatureScheme::RSA_PSS_SHA384, + Some(TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256), + )); + let (error, _) = accepted + .into_connection(server_config( + version, + false, + Some(TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384), + SignatureScheme::RSA_PSS_SHA384, + )) + .unwrap_err(); + assert!(matches!( + super::super::error::TlsError::from_rustls(error), + super::super::error::TlsError::NoCipherSuites + )); + } + + #[test] + fn incompatible_certificate_algorithm_keeps_the_no_shared_cipher_error() { + use rustls::crypto::aws_lc_rs::cipher_suite::TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; + let version = &rustls::version::TLS12; + let (_, accepted) = client_hello(client_config( + version, + SignatureScheme::ECDSA_NISTP256_SHA256, + Some(TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256), + )); + let (error, _) = accepted + .into_connection(server_config( + version, + false, + None, + SignatureScheme::RSA_PSS_SHA384, + )) + .unwrap_err(); + assert!(matches!( + super::super::error::TlsError::from_rustls(error), + super::super::error::TlsError::NoCipherSuites + )); + } + + fn finish_handshake(client: &mut ClientConnection, server: &mut rustls::ServerConnection) { + for _ in 0..16 { + let mut bytes = Vec::new(); + server.write_tls(&mut bytes).unwrap(); + if !bytes.is_empty() { + client.read_tls(&mut &bytes[..]).unwrap(); + client.process_new_packets().unwrap(); + } + bytes.clear(); + client.write_tls(&mut bytes).unwrap(); + if !bytes.is_empty() { + server.read_tls(&mut &bytes[..]).unwrap(); + server.process_new_packets().unwrap(); + } + if !client.is_handshaking() + && !server.is_handshaking() + && !client.wants_write() + && !server.wants_write() + { + return; + } + } + panic!("in-memory handshake did not finish within 16 exchanges"); + } + + #[test] + fn signature_match_selects_a_later_compatible_key() { + for version in [&rustls::version::TLS12, &rustls::version::TLS13] { + let client_config = client_config(version, SignatureScheme::RSA_PSS_SHA384, None); + let server_config = server_config(version, true, None, SignatureScheme::RSA_PSS_SHA384); + for expected_kind in [rustls::HandshakeKind::Full, rustls::HandshakeKind::Resumed] { + let (mut client, accepted) = client_hello(client_config.clone()); + let mut server = accepted.into_connection(server_config.clone()).unwrap(); + finish_handshake(&mut client, &mut server); + assert_eq!(client.handshake_kind(), Some(expected_kind)); + assert_eq!(server.handshake_kind(), Some(expected_kind)); + } + } + } + + fn assert_resumption_survives_signature_policy_change( + version: &'static rustls::SupportedProtocolVersion, + ) { + let client_config = client_config(version, SignatureScheme::RSA_PSS_SHA256, None); + let initial_config = server_config(version, false, None, SignatureScheme::RSA_PSS_SHA256); + let (mut client, accepted) = client_hello(client_config.clone()); + let mut server = accepted.into_connection(initial_config.clone()).unwrap(); + finish_handshake(&mut client, &mut server); + assert_eq!(client.handshake_kind(), Some(rustls::HandshakeKind::Full)); + + // SSLContext retains its server session cache/ticketer when a policy + // change rebuilds the configuration. Change only the signing policy. + let mut changed_config = (*initial_config).clone(); + changed_config.cert_resolver = + server_config(version, false, None, SignatureScheme::RSA_PSS_SHA384) + .cert_resolver + .clone(); + let changed_config = Arc::new(changed_config); + let (mut client, accepted) = client_hello(client_config); + let mut server = accepted.into_connection(changed_config.clone()).unwrap(); + finish_handshake(&mut client, &mut server); + assert_eq!( + client.handshake_kind(), + Some(rustls::HandshakeKind::Resumed) + ); + assert_eq!( + server.handshake_kind(), + Some(rustls::HandshakeKind::Resumed) + ); + + // The same changed policy must still reject a fresh client's PSS256 + // offer; accepting a resumed session must not relax a full handshake. + let (mut client, accepted) = client_hello(self::client_config( + version, + SignatureScheme::RSA_PSS_SHA256, + None, + )); + let (error, alert) = accepted.into_connection(changed_config).unwrap_err(); + let bytes = initial_handshake_alert(&error, alert).unwrap(); + assert_eq!(bytes, sni_alert(40)); + client.read_tls(&mut &bytes[..]).unwrap(); + assert!(matches!( + client.process_new_packets(), + Err(rustls::Error::AlertReceived( + rustls::AlertDescription::HandshakeFailure, + )) + )); + } + + #[test] + fn tls12_resumption_survives_signature_policy_change() { + assert_resumption_survives_signature_policy_change(&rustls::version::TLS12); + } + + #[test] + fn tls13_resumption_survives_signature_policy_change() { + assert_resumption_survives_signature_policy_change(&rustls::version::TLS13); + } +} diff --git a/crates/host_env/src/ssl/mod.rs b/crates/host_env/src/ssl/mod.rs index a2d8f32e563..7befb9ec244 100644 --- a/crates/host_env/src/ssl/mod.rs +++ b/crates/host_env/src/ssl/mod.rs @@ -33,6 +33,8 @@ pub mod providers; #[cfg(feature = "rustls")] pub mod session; #[cfg(feature = "rustls")] +pub mod sigalg; +#[cfg(feature = "rustls")] pub mod verify; #[cfg(feature = "rustls")] pub mod x509; diff --git a/crates/host_env/src/ssl/sigalg.rs b/crates/host_env/src/ssl/sigalg.rs new file mode 100644 index 00000000000..ee23d8d0a85 --- /dev/null +++ b/crates/host_env/src/ssl/sigalg.rs @@ -0,0 +1,190 @@ +// cspell: ignore sigalgs rsae mldsa + +//! Per-context TLS server signature algorithm selection. + +use alloc::sync::Arc; +use rustls::{ + DigitallySignedStruct, DistinguishedName, Error, SignatureAlgorithm, SignatureScheme, + client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}, + pki_types::{CertificateDer, ServerName, SubjectPublicKeyInfoDer, UnixTime}, + server::{ClientHello, ResolvesServerCert}, + sign::{CertifiedKey, Signer, SigningKey}, +}; + +use super::providers::CryptoExt; + +pub fn scheme_name(scheme: SignatureScheme) -> Option<&'static str> { + use SignatureScheme::{ + ECDSA_NISTP256_SHA256, ECDSA_NISTP384_SHA384, ECDSA_NISTP521_SHA512, ECDSA_SHA1_Legacy, + ED448, ED25519, ML_DSA_44, ML_DSA_65, ML_DSA_87, RSA_PKCS1_SHA1, RSA_PKCS1_SHA256, + RSA_PKCS1_SHA384, RSA_PKCS1_SHA512, RSA_PSS_SHA256, RSA_PSS_SHA384, RSA_PSS_SHA512, + }; + Some(match scheme { + RSA_PKCS1_SHA1 => "rsa_pkcs1_sha1", + ECDSA_SHA1_Legacy => "ecdsa_sha1", + RSA_PKCS1_SHA256 => "rsa_pkcs1_sha256", + RSA_PKCS1_SHA384 => "rsa_pkcs1_sha384", + RSA_PKCS1_SHA512 => "rsa_pkcs1_sha512", + ECDSA_NISTP256_SHA256 => "ecdsa_secp256r1_sha256", + ECDSA_NISTP384_SHA384 => "ecdsa_secp384r1_sha384", + ECDSA_NISTP521_SHA512 => "ecdsa_secp521r1_sha512", + RSA_PSS_SHA256 => "rsa_pss_rsae_sha256", + RSA_PSS_SHA384 => "rsa_pss_rsae_sha384", + RSA_PSS_SHA512 => "rsa_pss_rsae_sha512", + ED25519 => "ed25519", + ED448 => "ed448", + ML_DSA_44 => "mldsa44", + ML_DSA_65 => "mldsa65", + ML_DSA_87 => "mldsa87", + _ => return None, + }) +} + +pub fn parse_list(list: &str) -> Result, &'static str> { + let supported = CryptoExt::get_provider() + .signature_verification_algorithms + .supported_schemes(); + let mut selected = Vec::new(); + for name in list.split(':') { + let (name, optional) = name.strip_prefix('?').map_or((name, false), |n| (n, true)); + let name = match name { + "RSA+SHA256" => "rsa_pkcs1_sha256", + "RSA+SHA384" => "rsa_pkcs1_sha384", + "RSA+SHA512" => "rsa_pkcs1_sha512", + "ECDSA+SHA256" => "ecdsa_secp256r1_sha256", + "ECDSA+SHA384" => "ecdsa_secp384r1_sha384", + "ECDSA+SHA512" => "ecdsa_secp521r1_sha512", + other => other, + }; + match supported.iter().find(|s| scheme_name(**s) == Some(name)) { + Some(scheme) if !selected.contains(scheme) => selected.push(*scheme), + Some(_) => {} + None if optional => {} + None => return Err("unrecognized signature algorithm"), + } + } + if selected.is_empty() { + return Err("unrecognized signature algorithm"); + } + Ok(selected) +} + +/// Restrict advertisement and handshake signatures, retaining the complete +/// certificate verifier (including trust, hostname and revocation checks). +#[derive(Debug)] +pub struct ServerVerifier { + pub inner: Arc, + pub schemes: Vec, +} + +impl ServerVerifier { + fn check_scheme(&self, dss: &DigitallySignedStruct) -> Result<(), Error> { + if self.schemes.contains(&dss.scheme) { + Ok(()) + } else { + Err(Error::General( + "server signature algorithm is not enabled".into(), + )) + } + } +} + +impl ServerCertVerifier for ServerVerifier { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + intermediates: &[CertificateDer<'_>], + server_name: &ServerName<'_>, + ocsp_response: &[u8], + now: UnixTime, + ) -> Result { + self.inner + .verify_server_cert(end_entity, intermediates, server_name, ocsp_response, now) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + self.check_scheme(dss)?; + self.inner.verify_tls12_signature(message, cert, dss) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + self.check_scheme(dss)?; + self.inner.verify_tls13_signature(message, cert, dss) + } + + fn supported_verify_schemes(&self) -> Vec { + let supported = self.inner.supported_verify_schemes(); + self.schemes + .iter() + .filter(|s| supported.contains(s)) + .copied() + .collect() + } + + fn requires_raw_public_keys(&self) -> bool { + self.inner.requires_raw_public_keys() + } + + fn root_hint_subjects(&self) -> Option<&[DistinguishedName]> { + self.inner.root_hint_subjects() + } +} + +#[derive(Debug)] +struct RestrictedSigningKey { + inner: Arc, + schemes: Vec, +} + +impl SigningKey for RestrictedSigningKey { + fn choose_scheme(&self, offered: &[SignatureScheme]) -> Option> { + self.schemes + .iter() + .filter(|s| offered.contains(s)) + .find_map(|s| self.inner.choose_scheme(&[*s])) + } + + fn public_key(&self) -> Option> { + self.inner.public_key() + } + + fn algorithm(&self) -> SignatureAlgorithm { + self.inner.algorithm() + } +} + +#[derive(Debug)] +pub struct ServerResolver { + pub inner: Arc, + pub schemes: Vec, +} + +pub fn restrict_key(key: &CertifiedKey, schemes: &[SignatureScheme]) -> Arc { + let mut key = key.clone(); + key.key = Arc::new(RestrictedSigningKey { + inner: key.key, + schemes: schemes.to_vec(), + }); + Arc::new(key) +} + +impl ResolvesServerCert for ServerResolver { + fn resolve(&self, hello: ClientHello<'_>) -> Option> { + let key = self.inner.resolve(hello)?; + Some(restrict_key(&key, &self.schemes)) + } + + fn only_raw_public_keys(&self) -> bool { + self.inner.only_raw_public_keys() + } +} diff --git a/crates/host_env/src/ssl/verify.rs b/crates/host_env/src/ssl/verify.rs index a88b6cbf4b5..ba2132efee2 100644 --- a/crates/host_env/src/ssl/verify.rs +++ b/crates/host_env/src/ssl/verify.rs @@ -747,6 +747,25 @@ impl ClientCertVerifier for DeferredClientCertVerifier { // Public Utility Functions +/// Preserve which filesystem operation failed, independently of PEM errors. +#[derive(Debug)] +pub struct CertFileError { + pub error: std::io::Error, + pub key_file: bool, +} + +impl core::fmt::Display for CertFileError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::Display::fmt(&self.error, f) + } +} + +impl core::error::Error for CertFileError { + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + Some(&self.error) + } +} + /// Load certificate chain and private key from files /// /// This function loads a certificate chain from `cert_path` and a private key @@ -771,7 +790,10 @@ pub fn load_cert_chain_from_file( password: Option<&str>, ) -> Result<(Vec>, PrivateKeyDer<'static>), Box> { // Load certificate file - preserve io::Error for errno - let cert_contents = crate::fs::read(cert_path)?; + let cert_contents = crate::fs::read(cert_path).map_err(|error| CertFileError { + error, + key_file: false, + })?; // Parse certificates (PEM format) let mut cert_cursor = std::io::Cursor::new(&cert_contents); @@ -784,7 +806,10 @@ pub fn load_cert_chain_from_file( } // Load private key file - preserve io::Error for errno - let key_contents = crate::fs::read(key_path)?; + let key_contents = crate::fs::read(key_path).map_err(|error| CertFileError { + error, + key_file: true, + })?; // Parse private key (supports PKCS8, RSA, EC formats) let private_key = if let Some(pwd) = password { diff --git a/crates/host_env/src/ssl/x509.rs b/crates/host_env/src/ssl/x509.rs index 03b34cc18d5..e8aa44ada08 100644 --- a/crates/host_env/src/ssl/x509.rs +++ b/crates/host_env/src/ssl/x509.rs @@ -7,6 +7,7 @@ pub const X509_V_ERR_CERT_HAS_EXPIRED: i32 = 10; pub const X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY: i32 = 20; pub const X509_V_ERR_CERT_REVOKED: i32 = 23; pub const X509_V_ERR_INVALID_PURPOSE: i32 = 26; +pub const X509_V_ERR_CERT_REJECTED: i32 = 28; pub const X509_V_ERR_HOSTNAME_MISMATCH: i32 = 62; pub const X509_V_ERR_IP_ADDRESS_MISMATCH: i32 = 64; @@ -36,6 +37,16 @@ pub fn rustls_cert_error_to_verify_info( X509_V_ERR_INVALID_PURPOSE, "unsupported certificate purpose", ), + // rustls preserves WebPKI errors without a dedicated CertificateError variant. + // Only translate an actual distrust decision; do not inspect or re-verify the chain. + CertificateError::Other(other_err) + if matches!( + other_err.0.downcast_ref::(), + Some(webpki::Error::CertDistrusted) + ) => + { + (X509_V_ERR_CERT_REJECTED, "certificate rejected") + } CertificateError::Other(other_err) => { let err_msg = format!("{other_err:?}"); if err_msg.contains("Hostname mismatch") || err_msg.contains("not valid for") { @@ -55,3 +66,29 @@ pub fn rustls_cert_error_to_verify_info( _ => (X509_V_ERR_UNSPECIFIED, "certificate verification failed"), } } + +#[cfg(test)] +mod tests { + use super::*; + use alloc::sync::Arc; + + #[test] + fn maps_only_typed_webpki_distrust_to_rejected() { + let distrust = rustls::CertificateError::Other(rustls::OtherError(Arc::new( + webpki::Error::CertDistrusted, + ))); + assert_eq!( + rustls_cert_error_to_verify_info(&distrust), + (X509_V_ERR_CERT_REJECTED, "certificate rejected") + ); + for other in [ + rustls::OtherError(Arc::new(webpki::Error::BadDer)), + rustls::OtherError(Arc::new(std::io::Error::other("CertDistrusted"))), + ] { + assert_eq!( + rustls_cert_error_to_verify_info(&rustls::CertificateError::Other(other)), + (X509_V_ERR_UNSPECIFIED, "certificate verification failed") + ); + } + } +} diff --git a/crates/host_env/src/syslog.rs b/crates/host_env/src/syslog.rs index b6e3c0cb415..b0308bac25f 100644 --- a/crates/host_env/src/syslog.rs +++ b/crates/host_env/src/syslog.rs @@ -67,6 +67,9 @@ pub fn closelog() { #[must_use] pub fn setlogmask(maskpri: i32) -> i32 { + // libc setlogmask() is not thread-safe. + static SETLOGMASK: parking_lot::Mutex<()> = parking_lot::Mutex::new(()); + let _guard = SETLOGMASK.lock(); unsafe { libc::setlogmask(maskpri) } } diff --git a/crates/host_env/src/termios.rs b/crates/host_env/src/termios.rs index 0ee7a124b5e..16f309c8453 100644 --- a/crates/host_env/src/termios.rs +++ b/crates/host_env/src/termios.rs @@ -181,17 +181,25 @@ pub fn tcgetwinsize(fd: i32) -> std::io::Result<(u16, u16)> { Ok((size.ws_row, size.ws_col)) } -pub fn tcsetwinsize(fd: i32, row: u16, col: u16) -> std::io::Result<()> { +pub enum SetWinSizeError { + Io(std::io::Error), + OutOfRange, +} + +pub fn tcsetwinsize(fd: i32, row: libc::c_long, col: libc::c_long) -> Result<(), SetWinSizeError> { let mut size: libc::winsize = unsafe { core::mem::zeroed() }; let ret = unsafe { libc::ioctl(fd, TIOCGWINSZ as _, &mut size) }; if ret < 0 { - return Err(std::io::Error::last_os_error()); + return Err(SetWinSizeError::Io(std::io::Error::last_os_error())); + } + size.ws_row = row as _; + size.ws_col = col as _; + if libc::c_long::from(size.ws_row) != row || libc::c_long::from(size.ws_col) != col { + return Err(SetWinSizeError::OutOfRange); } - size.ws_row = row; - size.ws_col = col; let ret = unsafe { libc::ioctl(fd, TIOCSWINSZ as _, &size) }; if ret < 0 { - return Err(std::io::Error::last_os_error()); + return Err(SetWinSizeError::Io(std::io::Error::last_os_error())); } Ok(()) } diff --git a/crates/host_env/src/testconsole.rs b/crates/host_env/src/testconsole.rs index 02b82f4bf4d..b693ff457ca 100644 --- a/crates/host_env/src/testconsole.rs +++ b/crates/host_env/src/testconsole.rs @@ -4,12 +4,17 @@ use windows_sys::Win32::{ System::Console::{INPUT_RECORD, KEY_EVENT, WriteConsoleInputW}, }; -use crate::windows::{CheckWin32Bool, CheckWin32Handle}; +use crate::windows::CheckWin32Bool; -pub fn write_console_input(fd: i32, data: &[u16]) -> io::Result<()> { - let handle = (unsafe { libc::get_osfhandle(fd) } as HANDLE).check_valid()?; +fn console_handle(fd: i32) -> io::Result { + let raw_handle = unsafe { crate::suppress_iph!(libc::get_osfhandle(fd)) }; + if raw_handle == -1 { + return Err(crate::os::errno_io_error()); + } + Ok(raw_handle as HANDLE) +} - let size = data.len() as u32; +fn input_records(data: &[u16]) -> Vec { let mut records: Vec = Vec::with_capacity(data.len()); for &wc in data { let mut rec: INPUT_RECORD = unsafe { core::mem::zeroed() }; @@ -19,7 +24,11 @@ pub fn write_console_input(fd: i32, data: &[u16]) -> io::Result<()> { rec.Event.KeyEvent.uChar.UnicodeChar = wc; records.push(rec); } + records +} +fn write_records(handle: HANDLE, records: &[INPUT_RECORD]) -> io::Result<()> { + let size = records.len() as u32; let mut total: u32 = 0; while total < size { let mut wrote: u32 = 0; @@ -40,6 +49,19 @@ pub fn write_console_input(fd: i32, data: &[u16]) -> io::Result<()> { } total += wrote; } - Ok(()) } + +pub fn write_console_input(fd: i32, data: &[u16]) -> io::Result<()> { + let handle = console_handle(fd)?; + let records = input_records(data); + write_records(handle, &records) +} + +/// Resolve the descriptor after preparing the input records. +#[doc(hidden)] +pub fn write_console_input_with_fd(data: &[u16], get_fd: impl FnOnce() -> i32) -> io::Result<()> { + let records = input_records(data); + let handle = console_handle(get_fd())?; + write_records(handle, &records) +} diff --git a/crates/host_env/src/time.rs b/crates/host_env/src/time.rs index 14d77fe7a51..a009bbc739c 100644 --- a/crates/host_env/src/time.rs +++ b/crates/host_env/src/time.rs @@ -91,7 +91,7 @@ pub fn duration_since_system_now() -> Result { pub type TimeT = libc::time_t; #[cfg(windows)] -pub type TimeT = libc::time_t; +pub type TimeT = libc::time64_t; #[cfg(unix)] #[derive(Clone, Copy, Debug)] @@ -132,32 +132,101 @@ pub fn mktime(tm: &mut libc::tm) -> TimeT { #[cfg(windows)] unsafe extern "C" { - fn _gmtime64_s(tm: *mut libc::tm, time: *const libc::time_t) -> libc::c_int; - fn _localtime64_s(tm: *mut libc::tm, time: *const libc::time_t) -> libc::c_int; + fn _gmtime64_s(tm: *mut libc::tm, time: *const TimeT) -> libc::c_int; + fn _localtime64_s(tm: *mut libc::tm, time: *const TimeT) -> libc::c_int; #[link_name = "_mktime64"] - fn c_mktime(tm: *mut libc::tm) -> libc::time_t; + fn c_mktime(tm: *mut libc::tm) -> TimeT; + #[link_name = "_time64"] + fn c_time(time: *mut TimeT) -> TimeT; } #[cfg(windows)] #[cfg_attr(target_env = "musl", allow(deprecated))] pub fn current_time_t() -> TimeT { - unsafe { libc::time(core::ptr::null_mut()) } + unsafe { c_time(core::ptr::null_mut()) } } #[cfg(windows)] -#[cfg_attr(target_env = "musl", allow(deprecated))] -pub fn gmtime_from_timestamp(when: TimeT) -> Option { +#[derive(Debug)] +pub enum TimestampError { + FiletimeOutOfRange, + Os(std::io::Error), +} + +#[cfg(windows)] +fn windows_filetime(when: TimeT, local: bool) -> Result { + use windows_sys::Win32::{ + Foundation::{FILETIME, SYSTEMTIME}, + System::Time::{FileTimeToSystemTime, SystemTimeToTzSpecificLocalTime}, + }; + + const SECS_BETWEEN_EPOCHS: i64 = 11_644_473_600; + if when < -SECS_BETWEEN_EPOCHS { + return Err(TimestampError::FiletimeOutOfRange); + } + // Only negative timestamps reach this fallback, so the FILETIME cannot overflow. + debug_assert!(when < 0); + let ticks = ((when + SECS_BETWEEN_EPOCHS) as u64) * 10_000_000; + let filetime = FILETIME { + dwLowDateTime: ticks as u32, + dwHighDateTime: (ticks >> 32) as u32, + }; + let mut utc = SYSTEMTIME::default(); + if unsafe { FileTimeToSystemTime(&filetime, &mut utc) } == 0 { + return Err(TimestampError::Os(std::io::Error::last_os_error())); + } + let time = if local { + let mut result = SYSTEMTIME::default(); + // Unlike FileTimeToLocalFileTime, this applies DST rules for the timestamp. + if unsafe { SystemTimeToTzSpecificLocalTime(core::ptr::null(), &utc, &mut result) } == 0 { + return Err(TimestampError::Os(std::io::Error::last_os_error())); + } + result + } else { + utc + }; + const DAYS_BEFORE_MONTH: [i32; 12] = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; + let year = i32::from(time.wYear); + let leap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); + let yday = DAYS_BEFORE_MONTH[usize::from(time.wMonth - 1)] + i32::from(time.wDay) - 1 + + i32::from(time.wMonth > 2 && leap); + Ok(libc::tm { + tm_year: year - 1900, + tm_mon: i32::from(time.wMonth) - 1, + tm_mday: i32::from(time.wDay), + tm_hour: i32::from(time.wHour), + tm_min: i32::from(time.wMinute), + tm_sec: i32::from(time.wSecond), + tm_wday: i32::from(time.wDayOfWeek), + tm_yday: yday, + tm_isdst: if local { -1 } else { 0 }, + }) +} + +#[cfg(windows)] +pub fn gmtime_from_timestamp(when: TimeT) -> Result { + if when < 0 { + return windows_filetime(when, false); + } let mut out = core::mem::MaybeUninit::::uninit(); let err = unsafe { _gmtime64_s(out.as_mut_ptr(), &when) }; - (err == 0).then(|| unsafe { out.assume_init() }) + if err != 0 { + return Err(TimestampError::Os(crate::os::io_error_from_errno(err))); + } + Ok(unsafe { out.assume_init() }) } #[cfg(windows)] -#[cfg_attr(target_env = "musl", allow(deprecated))] -pub fn localtime_from_timestamp(when: TimeT) -> Option { +pub fn localtime_from_timestamp(when: TimeT) -> Result { + if when < 0 { + return windows_filetime(when, true); + } let mut out = core::mem::MaybeUninit::::uninit(); let err = unsafe { _localtime64_s(out.as_mut_ptr(), &when) }; - (err == 0).then(|| unsafe { out.assume_init() }) + if err != 0 { + return Err(TimestampError::Os(crate::os::io_error_from_errno(err))); + } + Ok(unsafe { out.assume_init() }) } #[cfg(windows)] @@ -594,7 +663,7 @@ pub enum CheckedTmError { } #[cfg(any(unix, windows))] -pub fn checked_tm_from_parts(parts: CheckedTmParts) -> Result { +pub fn tm_from_parts(parts: CheckedTmParts) -> Result { if parts.year < i64::from(i32::MIN) + 1900 || parts.year > i64::from(i32::MAX) { return Err(CheckedTmError::YearOutOfRange); } @@ -610,6 +679,34 @@ pub fn checked_tm_from_parts(parts: CheckedTmParts) -> Result Result<(), CheckedTmError> { if tm.tm_mon == -1 { tm.tm_mon = 0; } else if !(0..=11).contains(&tm.tm_mon) { @@ -638,45 +735,37 @@ pub fn checked_tm_from_parts(parts: CheckedTmParts) -> Result Some(CString::new(zone).map_err(|_| CheckedTmError::EmbeddedNul)?), - None => None, - }; - if let Some(zone) = &zone { - tm.tm_zone = zone.as_ptr().cast_mut(); - } - if let Some(gmtoff) = parts.gmtoff { - tm.tm_gmtoff = gmtoff as _; - } - Ok(CheckedTm { tm, zone }) - } - #[cfg(windows)] - { - Ok(CheckedTm { tm }) - } + Ok(()) +} + +#[cfg(any(unix, windows))] +pub fn checked_tm_from_parts(parts: CheckedTmParts) -> Result { + let mut checked = tm_from_parts(parts)?; + check_tm(&mut checked.tm)?; + Ok(checked) } #[cfg(any(unix, windows))] pub fn mktime_tm_from_parts(parts: MktimeTmParts) -> Result { - if parts.year < i32::MIN + 1900 { - return Err(CheckedTmError::YearOutOfRange); - } - let mut tm: libc::tm = unsafe { core::mem::zeroed() }; - tm.tm_sec = parts.tm_sec; - tm.tm_min = parts.tm_min; - tm.tm_hour = parts.tm_hour; - tm.tm_mday = parts.tm_mday; - tm.tm_mon = parts.tm_mon - 1; - tm.tm_year = parts.year - 1900; - tm.tm_wday = -1; - tm.tm_yday = parts.tm_yday - 1; - tm.tm_isdst = parts.tm_isdst; - Ok(tm) + tm_from_parts(CheckedTmParts { + year: parts.year.into(), + tm_mon: parts.tm_mon.wrapping_sub(1), + tm_mday: parts.tm_mday, + tm_hour: parts.tm_hour, + tm_min: parts.tm_min, + tm_sec: parts.tm_sec, + tm_wday: -1, + tm_yday: parts.tm_yday.wrapping_sub(1), + tm_isdst: parts.tm_isdst, + #[cfg(unix)] + zone: None, + #[cfg(unix)] + gmtoff: None, + }) + .map(|checked| checked.tm) } -#[cfg(unix)] +#[cfg(all(unix, not(any(target_os = "linux", target_os = "macos"))))] pub fn strftime_ascii(fmt: &str, tm: &libc::tm) -> Result { let fmt_c = CString::new(fmt).map_err(|_| CheckedTmError::EmbeddedNul)?; let mut size = 1024usize; @@ -698,7 +787,42 @@ pub fn strftime_ascii(fmt: &str, tm: &libc::tm) -> Result Result { + if fmt.contains('\0') { + return Err(CheckedTmError::EmbeddedNul); + } + let fmt_wide: Vec = fmt + .chars() + .map(|ch| ch as libc::wchar_t) + .chain([0]) + .collect(); + let mut size = 1024usize; + let max_scale = 256usize.saturating_mul(fmt.len().max(1)); + loop { + let mut out = vec![0 as libc::wchar_t; size]; + let written = unsafe { + wcsftime( + out.as_mut_ptr(), + out.len(), + fmt_wide.as_ptr(), + tm as *const libc::tm, + ) + }; + if written > 0 || size >= max_scale { + return Ok(out[..written] + .iter() + .map(|ch| char::from_u32(*ch as u32).unwrap_or(char::REPLACEMENT_CHARACTER)) + .collect()); + } + size = size.saturating_mul(2); + } +} + +#[cfg(any(windows, target_os = "linux", target_os = "macos"))] unsafe extern "C" { fn wcsftime( s: *mut libc::wchar_t, diff --git a/crates/host_env/src/uuid.rs b/crates/host_env/src/uuid.rs index 137a7a6f1ef..c90be70feca 100644 --- a/crates/host_env/src/uuid.rs +++ b/crates/host_env/src/uuid.rs @@ -33,3 +33,20 @@ pub fn create_sequential() -> SequentialUuid { pub fn has_stable_node() -> bool { create_sequential().status == STATUS_OK } + +/// Format an RPC status like CPython's PyErr_SetFromWindowsErr, without +/// replacing the explicit status with the thread's last-error value. +#[must_use] +pub fn format_error_message(status: i32) -> String { + const LANG_NEUTRAL_SUBLANG_DEFAULT: u32 = 1 << 10; + let code = status as u32; + crate::windows::format_error_message_with_language(code, LANG_NEUTRAL_SUBLANG_DEFAULT) + .map_or_else( + || format!("Windows Error 0x{code:x}"), + |message| { + message + .trim_end_matches(|ch: char| ch <= ' ' || ch == '.') + .to_owned() + }, + ) +} diff --git a/crates/host_env/src/wasi_p1.rs b/crates/host_env/src/wasi_p1.rs new file mode 100644 index 00000000000..96264e42bc9 --- /dev/null +++ b/crates/host_env/src/wasi_p1.rs @@ -0,0 +1,368 @@ +//! Subset of WASI preview1 used by the `wasm32-unknown-unknown` `host_io` guest. +//! +//! The guest imports `wasi_snapshot_preview1` functions and opens paths only +//! through preopened directories. The host decides which rights each open is +//! granted; this guest does not reject open flags on its own. + +use std::io; +use std::sync::OnceLock; + +use crate::errno::errors::{ENOENT, EOVERFLOW}; +use crate::os::{ + O_ACCMODE, O_APPEND, O_CREAT, O_DIRECTORY, O_EXCL, O_NOFOLLOW, O_RDONLY, O_TRUNC, O_WRONLY, +}; + +const ERRNO_SUCCESS: i32 = 0; +const ERRNO_BADF: i32 = 8; + +const FILETYPE_CHARACTER_DEVICE: u8 = 2; +pub(crate) const FILETYPE_DIRECTORY: u8 = 3; + +const PRESTAT_DIR: u8 = 0; + +const LOOKUP_SYMLINK_FOLLOW: i32 = 1; + +const OFLAGS_CREAT: i32 = 1; +const OFLAGS_DIRECTORY: i32 = 2; +const OFLAGS_EXCL: i32 = 4; +const OFLAGS_TRUNC: i32 = 8; + +const FDFLAGS_APPEND: i32 = 1; + +const RIGHTS_FD_DATASYNC: u64 = 1 << 0; +const RIGHTS_FD_READ: u64 = 1 << 1; +const RIGHTS_FD_SEEK: u64 = 1 << 2; +const RIGHTS_FD_FDSTAT_SET_FLAGS: u64 = 1 << 3; +const RIGHTS_FD_SYNC: u64 = 1 << 4; +const RIGHTS_FD_TELL: u64 = 1 << 5; +const RIGHTS_FD_WRITE: u64 = 1 << 6; +const RIGHTS_FD_ADVISE: u64 = 1 << 7; +const RIGHTS_FD_ALLOCATE: u64 = 1 << 8; +const RIGHTS_FD_READDIR: u64 = 1 << 14; +const RIGHTS_FD_FILESTAT_GET: u64 = 1 << 21; +const RIGHTS_FD_FILESTAT_SET_SIZE: u64 = 1 << 22; +const RIGHTS_FD_FILESTAT_SET_TIMES: u64 = 1 << 23; +const RIGHTS_POLL_FD_READWRITE: u64 = 1 << 27; + +const RIGHTS_ALL: u64 = (1 << 30) - 1; + +const RIGHTS_BASE_ALWAYS: u64 = RIGHTS_FD_SEEK + | RIGHTS_FD_TELL + | RIGHTS_FD_SYNC + | RIGHTS_FD_DATASYNC + | RIGHTS_FD_FDSTAT_SET_FLAGS + | RIGHTS_FD_ADVISE + | RIGHTS_FD_FILESTAT_GET + | RIGHTS_FD_FILESTAT_SET_TIMES + | RIGHTS_FD_READDIR + | RIGHTS_POLL_FD_READWRITE; + +#[repr(C)] +struct IoVec { + buf: u32, + buf_len: u32, +} + +const _: () = assert!(core::mem::size_of::() == 8); +const _: () = assert!(core::mem::align_of::() == 4); + +#[repr(C)] +#[derive(Clone, Copy, Default)] +pub(crate) struct FdStat { + pub fs_filetype: u8, + _pad0: u8, + _fs_flags: u16, + _pad1: u32, + pub fs_rights_base: u64, + _fs_rights_inheriting: u64, +} + +const _: () = assert!(core::mem::size_of::() == 24); +const _: () = assert!(core::mem::align_of::() == 8); + +#[repr(C)] +#[derive(Default)] +struct Prestat { + tag: u8, + _pad: [u8; 3], + pr_name_len: u32, +} + +const _: () = assert!(core::mem::size_of::() == 8); +const _: () = assert!(core::mem::align_of::() == 4); + +#[link(wasm_import_module = "wasi_snapshot_preview1")] +unsafe extern "C" { + fn fd_read(fd: i32, iovs: i32, iovs_len: i32, nread: i32) -> i32; + fn fd_write(fd: i32, iovs: i32, iovs_len: i32, nwritten: i32) -> i32; + fn fd_seek(fd: i32, offset: i64, whence: i32, newoffset: i32) -> i32; + fn fd_close(fd: i32) -> i32; + fn fd_sync(fd: i32) -> i32; + fn fd_filestat_set_size(fd: i32, size: i64) -> i32; + fn fd_fdstat_get(fd: i32, buf: i32) -> i32; + fn fd_prestat_get(fd: i32, buf: i32) -> i32; + fn fd_prestat_dir_name(fd: i32, path: i32, path_len: i32) -> i32; + fn path_open( + dirfd: i32, + dirflags: i32, + path: i32, + path_len: i32, + oflags: i32, + fs_rights_base: i64, + fs_rights_inheriting: i64, + fdflags: i32, + fd: i32, + ) -> i32; +} + +fn guest_ptr(ptr: *const T) -> i32 { + ptr as *const u8 as usize as i32 +} + +fn check(errno: i32) -> io::Result<()> { + if errno == ERRNO_SUCCESS { + Ok(()) + } else { + Err(io::Error::from_raw_os_error(errno)) + } +} + +fn checked_count(count: u32, len: usize) -> io::Result { + let n = count as usize; + if n <= len { + Ok(n) + } else { + Err(io::Error::new( + io::ErrorKind::InvalidData, + "WASI I/O count exceeds buffer length", + )) + } +} + +fn io_once(fd: i32, buf: *const u8, len: usize, write: bool) -> io::Result { + let iov = IoVec { + buf: buf as u32, + buf_len: len as u32, + }; + let mut n: u32 = 0; + let import = if write { fd_write } else { fd_read }; + // SAFETY: `iov` describes `buf`/`len` in this guest's linear memory, and `n` + // is a valid out-pointer for the duration of the import. + let errno = unsafe { + import( + fd, + guest_ptr(&iov), + 1, + guest_ptr(core::ptr::addr_of_mut!(n)), + ) + }; + check(errno)?; + checked_count(n, len) +} + +pub(crate) fn read(fd: i32, buf: &mut [u8]) -> io::Result { + io_once(fd, buf.as_mut_ptr(), buf.len(), false) +} + +pub(crate) fn write(fd: i32, buf: &[u8]) -> io::Result { + io_once(fd, buf.as_ptr(), buf.len(), true) +} + +pub(crate) fn close(fd: i32) -> io::Result<()> { + // SAFETY: `fd` is a host descriptor; close consumes it even when the import fails. + check(unsafe { fd_close(fd) }) +} + +pub(crate) fn sync(fd: i32) -> io::Result<()> { + // SAFETY: `fd` is a borrowed host descriptor for the duration of the import. + check(unsafe { fd_sync(fd) }) +} + +pub(crate) fn set_size(fd: i32, size: i64) -> io::Result<()> { + // SAFETY: `fd` is a borrowed host descriptor for the duration of the import. + check(unsafe { fd_filestat_set_size(fd, size) }) +} + +pub(crate) fn seek(fd: i32, offset: i64, whence: i32) -> io::Result { + let mut newoffset: u64 = 0; + // SAFETY: `newoffset` is a valid out-pointer in this guest's linear memory. + check(unsafe { + fd_seek( + fd, + offset, + whence, + guest_ptr(core::ptr::addr_of_mut!(newoffset)), + ) + })?; + i64::try_from(newoffset).map_err(|_| io::Error::from_raw_os_error(EOVERFLOW)) +} + +pub(crate) fn fdstat(fd: i32) -> io::Result { + let mut buf = FdStat::default(); + // SAFETY: `buf` is a valid fdstat out-buffer in this guest's linear memory. + check(unsafe { fd_fdstat_get(fd, guest_ptr(core::ptr::addr_of_mut!(buf))) })?; + Ok(buf) +} + +pub(crate) fn is_tty(fd: i32) -> bool { + let Ok(stat) = fdstat(fd) else { + return false; + }; + stat.fs_filetype == FILETYPE_CHARACTER_DEVICE + && stat.fs_rights_base & (RIGHTS_FD_SEEK | RIGHTS_FD_TELL) == 0 +} + +fn normalize_preopen_name(name: &[u8]) -> Vec { + let mut end = name.len(); + while end > 0 && name[end - 1] == b'/' { + end -= 1; + } + let name = &name[..end]; + if name.is_empty() || name == b"." { + b"/".to_vec() + } else { + name.to_vec() + } +} + +fn make_absolute(path: &[u8]) -> Vec { + if path.starts_with(b"/") { + path.to_vec() + } else { + let mut abs = Vec::with_capacity(path.len() + 1); + abs.push(b'/'); + abs.extend_from_slice(path); + abs + } +} + +fn is_component_prefix(prefix: &[u8], path: &[u8]) -> bool { + if prefix == b"/" { + return path.starts_with(b"/"); + } + path.starts_with(prefix) + && (path.len() == prefix.len() || path.get(prefix.len()) == Some(&b'/')) +} + +fn relative_from_prefix(path: &[u8], prefix: &[u8]) -> Vec { + let rest = if prefix == b"/" { + &path[1..] + } else if path.len() == prefix.len() { + &[] + } else { + &path[prefix.len() + 1..] + }; + if rest.is_empty() { + b".".to_vec() + } else { + rest.to_vec() + } +} + +fn enumerate_preopens() -> Vec<(i32, Vec)> { + let mut preopens = Vec::new(); + let mut fd = 3i32; + loop { + let mut prestat = Prestat::default(); + // SAFETY: `prestat` is a valid out-buffer in this guest's linear memory. + let errno = unsafe { fd_prestat_get(fd, guest_ptr(core::ptr::addr_of_mut!(prestat))) }; + if errno == ERRNO_BADF { + break; + } + if errno == ERRNO_SUCCESS && prestat.tag == PRESTAT_DIR { + let mut name = vec![0u8; prestat.pr_name_len as usize]; + // SAFETY: `name` is `pr_name_len` bytes of guest linear memory. + let errno = + unsafe { fd_prestat_dir_name(fd, guest_ptr(name.as_mut_ptr()), name.len() as i32) }; + if errno == ERRNO_SUCCESS { + preopens.push((fd, normalize_preopen_name(&name))); + } + } + let Some(next) = fd.checked_add(1) else { + break; + }; + fd = next; + } + preopens +} + +fn preopens() -> &'static [(i32, Vec)] { + static PREOPENS: OnceLock)>> = OnceLock::new(); + PREOPENS.get_or_init(enumerate_preopens) +} + +fn resolve_preopen(path: &[u8]) -> io::Result<(i32, Vec)> { + let abs = make_absolute(path); + let mut best: Option<(usize, i32)> = None; + for &(fd, ref name) in preopens() { + if is_component_prefix(name, &abs) && best.is_none_or(|(len, _)| name.len() > len) { + best = Some((name.len(), fd)); + } + } + let Some((prefix_len, fd)) = best else { + return Err(io::Error::from_raw_os_error(ENOENT)); + }; + let prefix = &abs[..prefix_len]; + Ok((fd, relative_from_prefix(&abs, prefix))) +} + +fn oflags_from_open_flags(flags: i32) -> i32 { + let mut oflags = 0; + if flags & O_CREAT != 0 { + oflags |= OFLAGS_CREAT; + } + if flags & O_DIRECTORY != 0 { + oflags |= OFLAGS_DIRECTORY; + } + if flags & O_EXCL != 0 { + oflags |= OFLAGS_EXCL; + } + if flags & O_TRUNC != 0 { + oflags |= OFLAGS_TRUNC; + } + oflags +} + +fn rights_base_from_open_flags(flags: i32) -> u64 { + let accmode = flags & O_ACCMODE; + let mut rights = RIGHTS_BASE_ALWAYS; + if accmode != O_WRONLY { + rights |= RIGHTS_FD_READ; + } + if accmode != O_RDONLY { + rights |= RIGHTS_FD_WRITE | RIGHTS_FD_ALLOCATE | RIGHTS_FD_FILESTAT_SET_SIZE; + } + rights +} + +pub(crate) fn path_open_preopen(path: &[u8], flags: i32) -> io::Result { + let (dirfd, rel) = resolve_preopen(path)?; + let dirflags = if flags & O_NOFOLLOW == 0 { + LOOKUP_SYMLINK_FOLLOW + } else { + 0 + }; + let oflags = oflags_from_open_flags(flags); + let fdflags = if flags & O_APPEND != 0 { + FDFLAGS_APPEND + } else { + 0 + }; + let rights_base = rights_base_from_open_flags(flags); + let mut opened: i32 = 0; + // SAFETY: `rel` and `opened` are valid guest buffers for the duration of the import. + check(unsafe { + path_open( + dirfd, + dirflags, + guest_ptr(rel.as_ptr()), + rel.len() as i32, + oflags, + rights_base as i64, + RIGHTS_ALL as i64, + fdflags, + guest_ptr(core::ptr::addr_of_mut!(opened)), + ) + })?; + Ok(opened) +} diff --git a/crates/host_env/src/winapi.rs b/crates/host_env/src/winapi.rs index bf62cfaafa0..fb59b70582b 100644 --- a/crates/host_env/src/winapi.rs +++ b/crates/host_env/src/winapi.rs @@ -8,7 +8,6 @@ use std::{io, path::Path}; use crate::windows::{CheckWin32Bool, CheckWin32Handle}; -use memchr::memchr; pub use windows_sys::Win32::{ Foundation::{ DUPLICATE_CLOSE_SOURCE, DUPLICATE_SAME_ACCESS, ERROR_ACCESS_DENIED, ERROR_ALREADY_EXISTS, @@ -39,6 +38,10 @@ pub use windows_sys::Win32::{ }, System::{ Console::{STD_ERROR_HANDLE, STD_INPUT_HANDLE, STD_OUTPUT_HANDLE}, + EventLog::{ + EVENTLOG_AUDIT_FAILURE, EVENTLOG_AUDIT_SUCCESS, EVENTLOG_ERROR_TYPE, + EVENTLOG_INFORMATION_TYPE, EVENTLOG_SUCCESS, EVENTLOG_WARNING_TYPE, + }, Memory::{ FILE_MAP_ALL_ACCESS, FILE_MAP_COPY, FILE_MAP_EXECUTE, FILE_MAP_READ, FILE_MAP_WRITE, MEM_COMMIT, MEM_FREE, MEM_IMAGE, MEM_MAPPED, MEM_PRIVATE, MEM_RESERVE, PAGE_EXECUTE, @@ -86,6 +89,44 @@ pub const LCMAP_HASH_FLAG: u32 = windows_sys::Win32::Globalization::LCMAP_HASH; pub const LCMAP_SORTHANDLE_FLAG: u32 = windows_sys::Win32::Globalization::LCMAP_SORTHANDLE; pub const LCMAP_SORTKEY_FLAG: u32 = windows_sys::Win32::Globalization::LCMAP_SORTKEY; +pub fn register_event_source_w( + server: Option<&widestring::WideCStr>, + source: &widestring::WideCStr, +) -> io::Result { + let server = server.map_or(core::ptr::null(), |name| name.as_ptr()); + unsafe { windows_sys::Win32::System::EventLog::RegisterEventSourceW(server, source.as_ptr()) } + .check_nonnull() +} + +pub fn deregister_event_source(handle: HANDLE) -> io::Result<()> { + unsafe { windows_sys::Win32::System::EventLog::DeregisterEventSource(handle) } + .check_win32_bool() +} + +pub fn report_event_w( + handle: HANDLE, + event_type: u16, + category: u16, + event_id: u32, + message: &widestring::WideCStr, +) -> io::Result<()> { + let message = message.as_ptr(); + unsafe { + windows_sys::Win32::System::EventLog::ReportEventW( + handle, + event_type, + category, + event_id, + core::ptr::null_mut(), + 1, + 0, + &message, + core::ptr::null(), + ) + } + .check_win32_bool() +} + pub struct PeekNamedPipeResult { pub data: Option>, pub available: u32, @@ -114,6 +155,7 @@ pub enum BatchedWaitError { } pub enum BuildEnvironmentBlockError { + Os(io::Error), ContainsNul, IllegalName, } @@ -296,34 +338,47 @@ pub fn create_junction(src: &Path, dst: &Path) -> io::Result<()> { } pub fn build_environment_block( - entries: Vec<(String, String)>, + entries: Vec<(Vec, Vec)>, ) -> Result, BuildEnvironmentBlockError> { - use std::collections::HashMap; - - let mut last_entry: HashMap> = HashMap::new(); + let invariant = widestring::WideCStr::from_slice(&[0]).unwrap(); + let mut normalized = Vec::with_capacity(entries.len()); for (key, value) in entries { - if memchr(b'\0', key.as_bytes()).is_some() || memchr(b'\0', value.as_bytes()).is_some() { + let uppercase = lc_map_string_ex(invariant, LCMAP_UPPERCASE, &key) + .map_err(BuildEnvironmentBlockError::Os)?; + // CPython sorts the mapped Python strings by code point, preserving + // lone surrogates rather than replacing them or requiring UTF-8. + let sort_key: Vec = char::decode_utf16(uppercase) + .map(|c| c.map_or_else(|e| u32::from(e.unpaired_surrogate()), u32::from)) + .collect(); + normalized.push((sort_key, key, value)); + } + normalized.sort_by(|a, b| a.0.cmp(&b.0)); + + let mut out = Vec::new(); + for (index, (_, key, value)) in normalized.iter().enumerate() { + if let Some((_, next_key, _)) = normalized.get(index + 1) { + let comparison = compare_string_ordinal(key, next_key, true); + if comparison == 0 { + return Err(BuildEnvironmentBlockError::Os(io::Error::last_os_error())); + } + if comparison == CSTR_EQUAL { + // Stable sorting retains insertion order: keep the last key. + continue; + } + } + // CPython normalizes and deduplicates before validating retained entries. + if key.contains(&0) || value.contains(&0) { cold_path(); return Err(BuildEnvironmentBlockError::ContainsNul); } - if key.is_empty() || key[1..].contains('=') { + // Windows permits a leading '=' for hidden drive variables. + if key.is_empty() || key[1..].contains(&(b'=' as u16)) { return Err(BuildEnvironmentBlockError::IllegalName); } - - let key_upper = key.to_uppercase(); - let mut entry: Vec = key.encode_utf16().collect(); - entry.push(b'=' as u16); - entry.extend(value.encode_utf16()); - entry.push(0); - last_entry.insert(key_upper, entry); - } - - let mut entries: Vec<(String, Vec)> = last_entry.into_iter().collect(); - entries.sort_by(|a, b| a.0.cmp(&b.0)); - - let mut out = Vec::new(); - for (_, entry) in entries { - out.extend(entry); + out.extend_from_slice(key); + out.push(b'=' as u16); + out.extend_from_slice(value); + out.push(0); } if out.is_empty() { out.push(0); diff --git a/crates/host_env/src/windows.rs b/crates/host_env/src/windows.rs index 4cba8e3579e..6a5dee64891 100644 --- a/crates/host_env/src/windows.rs +++ b/crates/host_env/src/windows.rs @@ -16,7 +16,11 @@ use windows_sys::{ FORMAT_MESSAGE_ALLOCATE_BUFFER, FORMAT_MESSAGE_FROM_SYSTEM, FORMAT_MESSAGE_IGNORE_INSERTS, FormatMessageW, }, - LibraryLoader::{GetModuleFileNameW, GetModuleHandleW}, + LibraryLoader::{ + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, + GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, GetModuleFileNameW, + GetModuleHandleExW, GetModuleHandleW, + }, SystemInformation::{GetVersionExW, OSVERSIONINFOEXW, OSVERSIONINFOW}, Threading::{GetCurrentThreadStackLimits, SetThreadStackGuarantee}, }, @@ -49,6 +53,23 @@ pub fn init_winsock() { }) } +/// Handle of the already-loaded image containing this RustPython runtime. +/// The handle is borrowed and must not be passed to `FreeLibrary`. +pub fn runtime_module_handle() -> io::Result { + let mut module = core::ptr::null_mut(); + // FROM_ADDRESS treats this pointer as an address inside the image, not a + // string. UNCHANGED_REFCOUNT avoids loading a second copy or owning a ref. + unsafe { + GetModuleHandleExW( + GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, + runtime_module_handle as *const () as *const u16, + &mut module, + ) + } + .check_win32_bool()?; + Ok(module as usize) +} + /// Win32 BOOL convention: 0 = failure, nonzero = success. /// Reads error via `GetLastError()` through [`io::Error::last_os_error`]. pub trait CheckWin32Bool { @@ -258,7 +279,14 @@ pub fn get_last_error() -> u32 { pub fn format_error_message(code: Option) -> Option { let error_code = code.unwrap_or_else(get_last_error); + format_error_message_with_language(error_code, 0).map(|message| message.trim_end().to_owned()) +} + +/// Return the system message without applying a caller's trimming policy. +pub(crate) fn format_error_message_with_language(error_code: u32, language: u32) -> Option { let mut buffer: *mut u16 = core::ptr::null_mut(); + // SAFETY: ALLOCATE_BUFFER makes FormatMessageW write an allocated buffer + // pointer into `buffer`. No message arguments are read with IGNORE_INSERTS. let len = unsafe { FormatMessageW( FORMAT_MESSAGE_ALLOCATE_BUFFER @@ -266,7 +294,7 @@ pub fn format_error_message(code: Option) -> Option { | FORMAT_MESSAGE_IGNORE_INSERTS, core::ptr::null(), error_code, - 0, + language, &mut buffer as *mut *mut u16 as *mut u16, 0, core::ptr::null(), @@ -274,12 +302,19 @@ pub fn format_error_message(code: Option) -> Option { }; if len == 0 || buffer.is_null() { + if !buffer.is_null() { + // SAFETY: Any buffer supplied by FormatMessageW with + // ALLOCATE_BUFFER is owned by this call and released with LocalFree. + unsafe { windows_sys::Win32::Foundation::LocalFree(buffer as *mut _) }; + } return None; } + // SAFETY: On success, FormatMessageW returns the initialized UTF-16 length + // (excluding the terminator). Copy it before releasing the owned buffer. let message = unsafe { let slice = core::slice::from_raw_parts(buffer, len as usize); - let msg = String::from_utf16_lossy(slice).trim_end().to_string(); + let msg = String::from_utf16_lossy(slice); windows_sys::Win32::Foundation::LocalFree(buffer as *mut _); msg }; @@ -426,3 +461,24 @@ impl ToWideString for Wtf8 { WideCString::from_vec(buf).map_err(|_| io::Error::other(NUL_ERROR)) } } + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn sys_string_len(bstr: *const u16) -> usize { + unsafe { windows_sys::Win32::Foundation::SysStringLen(bstr) as usize } +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn sys_free_string(bstr: *const u16) { + unsafe { windows_sys::Win32::Foundation::SysFreeString(bstr) }; +} + +pub fn sys_alloc_string_len(units: &[u16]) -> Option<*mut u16> { + let len = u32::try_from(units.len()).ok()?; + let bstr = unsafe { windows_sys::Win32::Foundation::SysAllocStringLen(units.as_ptr(), len) }; + (!bstr.is_null()).then_some(bstr as *mut u16) +} + +#[allow(clippy::not_unsafe_ptr_arg_deref)] +pub fn co_task_mem_free(ptr: *mut core::ffi::c_void) { + unsafe { windows_sys::Win32::System::Com::CoTaskMemFree(ptr) }; +} diff --git a/crates/host_env/src/winreg.rs b/crates/host_env/src/winreg.rs index 6678b7b6808..d01f7a8f542 100644 --- a/crates/host_env/src/winreg.rs +++ b/crates/host_env/src/winreg.rs @@ -13,7 +13,8 @@ extern crate alloc; -use alloc::string::FromUtf16Error; +use alloc::{borrow::Cow, string::FromUtf16Error}; +use rustpython_wtf8::Wtf8Buf; use windows_sys::Win32::{ Foundation, @@ -96,6 +97,26 @@ pub fn bytes_as_wide_slice(bytes: &[u8]) -> &[u16] { u16_slice } +pub fn registry_wide_units(bytes: &[u8]) -> Cow<'_, [u16]> { + // Windows strings use complete native-endian UTF-16 code units; CPython + // ignores a trailing incomplete byte. + let bytes = &bytes[..bytes.len() & !1]; + // SAFETY: Every u16 bit pattern is valid and align_to checks alignment. + let (prefix, u16_slice, _) = unsafe { bytes.align_to::() }; + if prefix.is_empty() { + Cow::Borrowed(u16_slice) + } else { + Cow::Owned( + bytes + .as_chunks::<2>() + .0 + .iter() + .map(|&pair| u16::from_ne_bytes(pair)) + .collect(), + ) + } +} + pub fn close_key(hkey: Registry::HKEY) -> u32 { unsafe { Registry::RegCloseKey(hkey) } } @@ -111,15 +132,21 @@ pub unsafe fn connect_registry( pub unsafe fn create_key( key: Registry::HKEY, - sub_key: &widestring::WideCStr, + sub_key: Option<&widestring::WideCStr>, out_key: *mut Registry::HKEY, ) -> u32 { - unsafe { Registry::RegCreateKeyW(key, sub_key.as_ptr(), out_key) } + unsafe { + Registry::RegCreateKeyW( + key, + sub_key.map_or(core::ptr::null(), |key| key.as_ptr()), + out_key, + ) + } } pub unsafe fn create_key_ex( key: Registry::HKEY, - sub_key: &widestring::WideCStr, + sub_key: Option<&widestring::WideCStr>, reserved: u32, class: *mut u16, options: u32, @@ -131,7 +158,7 @@ pub unsafe fn create_key_ex( unsafe { Registry::RegCreateKeyExW( key, - sub_key.as_ptr(), + sub_key.map_or(core::ptr::null(), |key| key.as_ptr()), reserved, class, options, @@ -161,6 +188,11 @@ pub unsafe fn delete_value(key: Registry::HKEY, value_name: Option<&widestring:: unsafe { Registry::RegDeleteValueW(key, name_ptr) } } +pub unsafe fn delete_tree(key: Registry::HKEY, sub_key: Option<&widestring::WideCStr>) -> u32 { + let name_ptr = sub_key.map_or(core::ptr::null(), |n| n.as_ptr()); + unsafe { Registry::RegDeleteTreeW(key, name_ptr) } +} + pub unsafe fn enum_key_ex( key: Registry::HKEY, index: u32, @@ -280,12 +312,13 @@ pub unsafe fn load_key( pub unsafe fn open_key_ex( key: Registry::HKEY, - sub_key: &widestring::WideCStr, + sub_key: Option<&widestring::WideCStr>, options: u32, sam: u32, out_key: *mut Registry::HKEY, ) -> u32 { - unsafe { Registry::RegOpenKeyExW(key, sub_key.as_ptr(), options, sam, out_key) } + let name_ptr = sub_key.map_or(core::ptr::null(), |n| n.as_ptr()); + unsafe { Registry::RegOpenKeyExW(key, name_ptr, options, sam, out_key) } } pub unsafe fn query_value_ex( @@ -349,9 +382,34 @@ pub fn query_default_value( hkey: Registry::HKEY, sub_key: Option<&widestring::WideCStr>, ) -> Result { + query_default_value_with(hkey, sub_key, |value| { + String::from_utf16(value).map_err(QueryStringError::Utf16) + }) +} + +pub fn query_default_value_wtf8( + hkey: Registry::HKEY, + sub_key: Option<&widestring::WideCStr>, +) -> Result { + query_default_value_with(hkey, sub_key, |value| Ok(Wtf8Buf::from_wide(value))) +} + +fn query_default_value_with( + hkey: Registry::HKEY, + sub_key: Option<&widestring::WideCStr>, + decode: impl Fn(&[u16]) -> Result, +) -> Result { let child_key = if let Some(sub_key) = sub_key.filter(|s| !s.is_empty()) { let mut out_key = core::ptr::null_mut(); - let res = unsafe { open_key_ex(hkey, sub_key, 0, Registry::KEY_QUERY_VALUE, &mut out_key) }; + let res = unsafe { + open_key_ex( + hkey, + Some(sub_key), + 0, + Registry::KEY_QUERY_VALUE, + &mut out_key, + ) + }; if res != 0 { return Err(QueryStringError::Code(res)); } @@ -382,7 +440,7 @@ pub fn query_default_value( continue; } if res == Foundation::ERROR_FILE_NOT_FOUND { - break Ok(String::new()); + break decode(&[]); } if res != 0 { break Err(QueryStringError::Code(res)); @@ -391,12 +449,12 @@ pub fn query_default_value( break Err(QueryStringError::Code(Foundation::ERROR_INVALID_DATA)); } - let u16_slice = bytes_as_wide_slice(&buffer[..size as usize]); + let u16_slice = registry_wide_units(&buffer[..size as usize]); let len = u16_slice .iter() .position(|&c| c == 0) .unwrap_or(u16_slice.len()); - break String::from_utf16(&u16_slice[..len]).map_err(QueryStringError::Utf16); + break decode(&u16_slice[..len]); }; if let Some(ck) = child_key { @@ -408,22 +466,25 @@ pub fn query_default_value( pub fn query_value_bytes( hkey: Registry::HKEY, - wide_name: &widestring::WideCStr, + wide_name: Option<&widestring::WideCStr>, ) -> Result<(Vec, u32), u32> { let mut buf_size: u32 = 0; let res = unsafe { query_value_ex( hkey, - Some(wide_name), + wide_name, core::ptr::null_mut(), core::ptr::null_mut(), &mut buf_size, ) }; - if res == Foundation::ERROR_MORE_DATA || buf_size == 0 { + if res == Foundation::ERROR_MORE_DATA { buf_size = 256; } else if res != 0 { return Err(res); + } else if buf_size == 0 { + // Keep a nonzero buffer so a value that grows between calls can retry. + buf_size = 256; } let mut ret_buf = vec![0u8; buf_size as usize]; @@ -434,7 +495,7 @@ pub fn query_value_bytes( let res = unsafe { query_value_ex( hkey, - Some(wide_name), + wide_name, &mut typ, ret_buf.as_mut_ptr(), &mut ret_size, @@ -463,7 +524,7 @@ pub fn set_default_value( let res = unsafe { create_key_ex( hkey, - sub_key, + Some(sub_key), 0, core::ptr::null_mut(), 0, diff --git a/crates/host_env/src/winsound.rs b/crates/host_env/src/winsound.rs index b91a7a62490..a68759b4893 100644 --- a/crates/host_env/src/winsound.rs +++ b/crates/host_env/src/winsound.rs @@ -40,13 +40,20 @@ pub fn play_sound(source: PlaySoundSource<'_>, flags: u32) -> Result<(), PlaySou if matches!(source, PlaySoundSource::Memory(_)) && flags & SND_ASYNC != 0 { return Err(PlaySoundError::MemoryAsyncRejected); } - // `SND_MEMORY` requires a `Memory(_)` source; an empty pointer would - // dereference garbage. - if !matches!(source, PlaySoundSource::Memory(_)) && flags & SND_MEMORY != 0 { + // `SND_MEMORY` with a name would reinterpret the name's UTF-16 allocation + // as a RIFF buffer. A null source is still the documented stop operation, + // for which the remaining flags are ignored. + if matches!(source, PlaySoundSource::Name(_)) && flags & SND_MEMORY != 0 { return Err(PlaySoundError::MemoryFlagWithoutBuffer); } + // An empty slice's pointer is a dangling sentinel. Give WinMM zeroed + // storage instead; zero bytes do not start a RIFF header. + static EMPTY_IMAGE: [u8; 64] = [0; 64]; + // SND_MEMORY makes the `LPCWSTR` parameter point at a byte-oriented RIFF + // image. The pointer is only passed through, so it needs no `u16` alignment. let ptr: *const u16 = match source { PlaySoundSource::Stop => core::ptr::null(), + PlaySoundSource::Memory([]) => EMPTY_IMAGE.as_ptr().cast(), PlaySoundSource::Memory(buf) => buf.as_ptr().cast(), PlaySoundSource::Name(s) => s.as_ptr(), }; @@ -64,7 +71,7 @@ pub enum PlaySoundError { CallFailed, /// `Memory(_)` source cannot be combined with `SND_ASYNC` in the safe API. MemoryAsyncRejected, - /// `SND_MEMORY` set in `flags` but no `Memory(_)` buffer supplied. + /// `SND_MEMORY` set in `flags` for a named source. MemoryFlagWithoutBuffer, } diff --git a/crates/host_env/src/wmi.rs b/crates/host_env/src/wmi.rs index ceccf4d79fb..100588640b8 100644 --- a/crates/host_env/src/wmi.rs +++ b/crates/host_env/src/wmi.rs @@ -7,7 +7,7 @@ use core::ffi::c_void; use core::ptr::{NonNull, null, null_mut}; -use widestring::WideCString; +use widestring::{WideCStr, WideCString}; use windows_sys::Win32::Foundation::{ CloseHandle, ERROR_BROKEN_PIPE, ERROR_INVALID_NAME, ERROR_MORE_DATA, ERROR_NOT_ENOUGH_MEMORY, GetLastError, HANDLE, WAIT_OBJECT_0, WAIT_TIMEOUT, @@ -19,7 +19,7 @@ use windows_sys::Win32::System::Threading::{ }; use windows_sys::w; -use crate::ctypes::wcslen; +use crate::windows::{sys_alloc_string_len, sys_free_string}; pub const BUFFER_SIZE: usize = 8192; @@ -122,21 +122,20 @@ fn alloc_bstr(wide: &[u16]) -> *mut u16 { .iter() .position(|&unit| unit == 0) .unwrap_or(wide.len()); - crate::ctypes::sys_alloc_string_len(&wide[..len]).unwrap_or(null_mut()) + sys_alloc_string_len(&wide[..len]).unwrap_or(null_mut()) } fn alloc_bstr_ptr(ptr: *const u16) -> *mut u16 { let Some(ptr) = NonNull::new(ptr.cast_mut()) else { return null_mut(); }; - let len = unsafe { crate::ctypes::wcslen(ptr) }; - crate::ctypes::sys_alloc_string_len(unsafe { core::slice::from_raw_parts(ptr.as_ptr(), len) }) - .unwrap_or(null_mut()) + let wide = unsafe { WideCStr::from_ptr_str(ptr.as_ptr()) }; + sys_alloc_string_len(wide.as_slice()).unwrap_or(null_mut()) } fn free_bstr(bstr: *mut u16) { if !bstr.is_null() { - crate::ctypes::sys_free_string(bstr); + sys_free_string(bstr); } } @@ -478,9 +477,9 @@ unsafe fn query_thread_impl(param: *mut c_void) -> u32 { } if succeeded(hr) && (flavor & WBEM_FLAVOR_MASK_ORIGIN) != WBEM_FLAVOR_ORIGIN_SYSTEM { - let Some(cb_str1) = NonNull::new(prop_name) - .map(|prop_name| (unsafe { wcslen(prop_name) } * 2) as u32) - else { + let Some(cb_str1) = NonNull::new(prop_name).map(|prop_name| { + (unsafe { WideCStr::from_ptr_str(prop_name.as_ptr()) }.len() * 2) as u32 + }) else { free_bstr(prop_name); break; }; @@ -490,7 +489,9 @@ unsafe fn query_thread_impl(param: *mut c_void) -> u32 { VariantToString(&prop_value, prop_str.as_mut_ptr(), BUFFER_SIZE as u32) }; let cb_str2 = NonNull::new(prop_str.as_ptr().cast_mut()) - .map(|prop_str| (unsafe { wcslen(prop_str) } * 2) as u32) + .map(|prop_str| { + (unsafe { WideCStr::from_ptr_str(prop_str.as_ptr()) }.len() * 2) as u32 + }) .expect("prop_str is never null"); if succeeded(hr) @@ -565,10 +566,10 @@ unsafe fn query_thread_impl(param: *mut c_void) -> u32 { hr as u32 } -pub fn exec_query(query_str: &str) -> Result { - let query = WideCString::from_str(query_str) - .map(WideCString::into_vec_with_nul) - .map_err(|_| ExecQueryError::Code(ERROR_INVALID_NAME))?; +/// Execute a WMI query without translating unpaired UTF-16 surrogates in the +/// query or result. +pub fn exec_query_wide(query: &widestring::WideCStr) -> Result, ExecQueryError> { + let query = query.as_slice_with_nul().to_vec(); let mut h_thread: HANDLE = null_mut(); let mut err: u32 = 0; @@ -681,9 +682,15 @@ pub fn exec_query(query_str: &str) -> Result { return Err(ExecQueryError::Code(err)); } if offset == 0 { - return Ok(String::new()); + return Ok(Vec::new()); } let char_count = (offset as usize) / 2 - 1; - Ok(String::from_utf16_lossy(&buffer[..char_count])) + Ok(buffer[..char_count].to_vec()) +} + +pub fn exec_query(query_str: &str) -> Result { + let query = + WideCString::from_str(query_str).map_err(|_| ExecQueryError::Code(ERROR_INVALID_NAME))?; + exec_query_wide(&query).map(|result| String::from_utf16_lossy(&result)) } diff --git a/crates/host_env/vendor/wasm32-wasip1/README.md b/crates/host_env/vendor/wasm32-wasip1/README.md new file mode 100644 index 00000000000..b8d201c915e --- /dev/null +++ b/crates/host_env/vendor/wasm32-wasip1/README.md @@ -0,0 +1,16 @@ +# Vendored wasi-libc emulation library + +`libwasi-emulated-signal.a` is a prebuilt static library from +[wasi-sdk](https://github.com/WebAssembly/wasi-sdk), providing wasi-libc's +userspace emulation of `signal()`/`raise()` for `wasm32-wasip1` (WebAssembly +has no asynchronous signal delivery, so this is a synchronous, in-process +handler table, not a real OS signal mechanism). + +CPython's own WASI build links the same library +(`configure.ac`'s `_WASI_EMULATED_SIGNAL` case). + +- Source: https://github.com/WebAssembly/wasi-sdk/releases/download/wasi-sdk-34/wasi-sysroot-34.0.tar.gz + (path: `lib/wasm32-wasip1/libwasi-emulated-signal.a`) +- License: Apache-2.0 WITH LLVM-exception (same as wasi-libc) +- sha256: see below +becc35b856608fb9282d94c70166796e4d7b21e4e1057e625725306e765eb035 crates/host_env/vendor/wasm32-wasip1/libwasi-emulated-signal.a diff --git a/crates/host_env/vendor/wasm32-wasip1/libwasi-emulated-signal.a b/crates/host_env/vendor/wasm32-wasip1/libwasi-emulated-signal.a new file mode 100644 index 00000000000..25ba3e0515c Binary files /dev/null and b/crates/host_env/vendor/wasm32-wasip1/libwasi-emulated-signal.a differ diff --git a/crates/jit/src/instructions.rs b/crates/jit/src/instructions.rs index 499d7c8baa4..15abc4206cd 100644 --- a/crates/jit/src/instructions.rs +++ b/crates/jit/src/instructions.rs @@ -663,6 +663,21 @@ impl<'a, 'b> FunctionCompiler<'a, 'b> { self.stack.push(val); Ok(()) } + Instruction::LoadCommonConstant { idx } => { + let val = match idx.get(arg) { + oparg::CommonConstant::None => JitValue::None, + oparg::CommonConstant::True | oparg::CommonConstant::False => { + let value = i64::from(idx.get(arg) == oparg::CommonConstant::True); + JitValue::Bool(self.builder.ins().iconst(types::I8, value)) + } + oparg::CommonConstant::MinusOne => { + JitValue::Int(self.builder.ins().iconst(types::I64, -1)) + } + _ => return Err(JitCompileError::NotSupported), + }; + self.stack.push(val); + Ok(()) + } Instruction::LoadSmallInt { i } => { let small_int = i.get(arg) as i64; let val = self.builder.ins().iconst(types::I64, small_int); @@ -701,13 +716,13 @@ impl<'a, 'b> FunctionCompiler<'a, 'b> { } Instruction::LoadGlobal { namei } => { let oparg = namei.get(arg); - let name = &bytecode.names[(oparg >> 1) as usize]; + let name = &bytecode.names[oparg.name_idx()]; if name.as_ref() != bytecode.obj_name.as_ref() { Err(JitCompileError::NotSupported) } else { self.stack.push(JitValue::FuncRef(func_ref)); - if (oparg & 1) != 0 { + if oparg.push_null() { self.stack.push(JitValue::Null); } Ok(()) diff --git a/crates/jit/tests/common.rs b/crates/jit/tests/common.rs index fe0e4bd33d4..dfc2ea12b94 100644 --- a/crates/jit/tests/common.rs +++ b/crates/jit/tests/common.rs @@ -1,6 +1,6 @@ use core::ops::ControlFlow; use rustpython_compiler_core::bytecode::{ - CodeObject, ConstantData, Constants, Instruction, OpArg, OpArgState, + CodeObject, CommonConstant, ConstantData, Constants, Instruction, Names, OpArg, OpArgState, }; use rustpython_jit::{CompiledCode, JitType}; use rustpython_wtf8::{Wtf8, Wtf8Buf}; @@ -90,10 +90,10 @@ fn extract_annotations_from_annotate_code(code: &CodeObject) -> HashMap { - stack.push((false, namei.get(arg) as usize)); + stack.push((false, namei.get(arg).as_usize())); } Instruction::LoadGlobal { namei } => { - stack.push((false, (namei.get(arg) >> 1) as usize)); + stack.push((false, namei.get(arg).name_idx().as_usize())); } Instruction::BuildMap { count } => { let count = count.get(arg) as usize; @@ -133,7 +133,7 @@ fn extract_annotations_from_annotate_code(code: &CodeObject) -> HashMap name.clone(), None => panic!( "Annotation name idx out of bounds for '{:?}': {} (len={})", @@ -198,7 +198,7 @@ impl StackMachine { instruction: Instruction, arg: OpArg, constants: &Constants, - names: &[String], + names: &Names, ) -> ControlFlow<()> { match instruction { Instruction::Resume { .. } | Instruction::Cache | Instruction::NotTaken => { @@ -207,13 +207,22 @@ impl StackMachine { Instruction::LoadConst { consti } => { self.stack.push(constants[consti.get(arg)].clone().into()) } + Instruction::LoadCommonConstant { idx } => { + self.stack.push(match idx.get(arg) { + CommonConstant::None => StackValue::None, + CommonConstant::EmptyStr => StackValue::String(String::new()), + constant => unimplemented!( + "common constant {constant:?} isn't yet supported in py_function!" + ), + }); + } Instruction::LoadName { namei } => self .stack - .push(StackValue::String(names[namei.get(arg) as usize].clone())), + .push(StackValue::String(names[namei.get(arg)].clone())), Instruction::StoreName { namei } => { let idx = namei.get(arg); self.locals - .insert(names[idx as usize].clone(), self.stack.pop().unwrap()); + .insert(names[idx].clone(), self.stack.pop().unwrap()); } Instruction::StoreAttr { .. } => { // Do nothing except throw away the stack values diff --git a/crates/literal/Cargo.toml b/crates/literal/Cargo.toml index 2a80fc6338e..e42dfd14af4 100644 --- a/crates/literal/Cargo.toml +++ b/crates/literal/Cargo.toml @@ -18,6 +18,9 @@ rustpython-wtf8 = { workspace = true } hexf-parse = { workspace = true } is-macro.workspace = true lexical-parse-float = { workspace = true, features = ["format"] } +malachite-base = { workspace = true } +malachite-bigint = { workspace = true } +malachite-q = { workspace = true } num-traits = { workspace = true } [dev-dependencies] diff --git a/crates/literal/src/complex.rs b/crates/literal/src/complex.rs index 78f3fc0237a..24bbdf17164 100644 --- a/crates/literal/src/complex.rs +++ b/crates/literal/src/complex.rs @@ -105,6 +105,161 @@ pub fn parse_str(s: &str) -> Option<(f64, f64)> { Some(value) } +type ComplexParts = (f64, f64); + +const fn parts(re: f64, im: f64) -> ComplexParts { + (re, im) +} + +/// Only the magnitude of an infinite part matters once a product has gone to +/// nan, so it stands in as a signed one; a nan beside it stands in as a +/// signed zero. +fn signed_unit(part: f64) -> f64 { + if part.is_infinite() { 1.0 } else { 0.0f64 }.copysign(part) +} + +fn tamed(value: ComplexParts) -> ComplexParts { + parts(signed_unit(value.0), signed_unit(value.1)) +} + +fn nans_to_zero(value: ComplexParts) -> ComplexParts { + let zeroed = |part: f64| { + if part.is_nan() { + 0.0f64.copysign(part) + } else { + part + } + }; + parts(zeroed(value.0), zeroed(value.1)) +} + +/// Multiply, recovering the infinities that the plain formula turns into nan, +/// the way C11 Annex G.5.1 does. +#[inline] +#[must_use] +pub fn multiply(a: ComplexParts, b: ComplexParts) -> ComplexParts { + let r = parts(a.0 * b.0 - a.1 * b.1, a.0 * b.1 + a.1 * b.0); + if !(r.0.is_nan() && r.1.is_nan()) { + return r; + } + + // "Box" an infinite operand into a signed one and turn the other's nans + // into signed zeros, so that the infinity survives a second pass. + let (mut a, mut b) = (a, b); + let a_infinite = a.0.is_infinite() || a.1.is_infinite(); + if a_infinite { + a = tamed(a); + b = nans_to_zero(b); + } + let b_infinite = b.0.is_infinite() || b.1.is_infinite(); + if b_infinite { + b = tamed(b); + a = nans_to_zero(a); + } + // An infinity that overflow lost, rather than one an operand carried. + let overflowed = !a_infinite + && !b_infinite + && ((a.0 * b.0).is_infinite() + || (a.1 * b.1).is_infinite() + || (a.0 * b.1).is_infinite() + || (a.1 * b.0).is_infinite()); + if overflowed { + a = nans_to_zero(a); + b = nans_to_zero(b); + } + + if !(a_infinite || b_infinite || overflowed) { + return r; + } + parts( + f64::INFINITY * (a.0 * b.0 - a.1 * b.1), + f64::INFINITY * (a.0 * b.1 + a.1 * b.0), + ) +} + +/// Divide a real by a complex. Written out rather than routed through `quot` +/// with a zero imaginary part, which would lose the sign of a zero. +#[inline] +#[must_use] +pub fn real_divide(a: f64, b: ComplexParts) -> Option { + let abs_re = b.0.abs(); + let abs_im = b.1.abs(); + + let r = if abs_re >= abs_im { + if abs_re == 0.0 { + return None; + } + let ratio = b.1 / b.0; + let denom = b.0 + b.1 * ratio; + parts(a / denom, -a * ratio / denom) + } else if abs_im >= abs_re { + let ratio = b.0 / b.1; + let denom = b.0 * ratio + b.1; + parts(a * ratio / denom, -a / denom) + } else { + // One part of the divisor is a nan, so neither comparison held. + parts(f64::NAN, f64::NAN) + }; + + // A quotient that came out as nan recovers the way `recovered_quot` does, + // except that a real numerator has no imaginary term to carry a sign. + if r.0.is_nan() && r.1.is_nan() && (b.0.is_infinite() || b.1.is_infinite()) && a.is_finite() { + let (x, y) = tamed(b); + return Some(parts(0.0 * (a * x), 0.0 * -(a * y))); + } + + Some(r) +} + +/// Divide by whichever part of the divisor is larger, so that the ratio the +/// other part is scaled by cannot overflow. `None` stands for a divisor of +/// zero. +#[inline] +#[must_use] +pub fn divide(a: ComplexParts, b: ComplexParts) -> Option { + let abs_re = b.0.abs(); + let abs_im = b.1.abs(); + + let r = if abs_re >= abs_im { + if abs_re == 0.0 { + return None; + } + let ratio = b.1 / b.0; + let denom = b.0 + b.1 * ratio; + parts((a.0 + a.1 * ratio) / denom, (a.1 - a.0 * ratio) / denom) + } else if abs_im >= abs_re { + let ratio = b.0 / b.1; + let denom = b.0 * ratio + b.1; + parts((a.0 * ratio + a.1) / denom, (a.1 * ratio - a.0) / denom) + } else { + // One part of the divisor is a nan, so neither comparison held. + parts(f64::NAN, f64::NAN) + }; + + Some(recovered_quot(r, a, b)) +} + +/// Recover the infinities and zeros a quotient came out of as nan, the way +/// C11 Annex G.5.2 does. +fn recovered_quot(r: ComplexParts, a: ComplexParts, b: ComplexParts) -> ComplexParts { + if !(r.0.is_nan() && r.1.is_nan()) { + return r; + } + + if (a.0.is_infinite() || a.1.is_infinite()) && b.0.is_finite() && b.1.is_finite() { + let (x, y) = tamed(a); + parts( + f64::INFINITY * (x * b.0 + y * b.1), + f64::INFINITY * (y * b.0 - x * b.1), + ) + } else if (b.0.is_infinite() || b.1.is_infinite()) && a.0.is_finite() && a.1.is_finite() { + let (x, y) = tamed(b); + parts(0.0 * (a.0 * x + a.1 * y), 0.0 * (a.1 * x - a.0 * y)) + } else { + r + } +} + #[cfg(test)] mod tests { use super::*; @@ -140,3 +295,5 @@ mod tests { assert_eq!(parse_str("abc"), None); } } + +// Shared runtime/compiler arithmetic, with no Python object ownership. diff --git a/crates/literal/src/float.rs b/crates/literal/src/float.rs index 8a0a18fc96b..2e8ed658c46 100644 --- a/crates/literal/src/float.rs +++ b/crates/literal/src/float.rs @@ -2,8 +2,28 @@ use crate::format::Case; use alloc::borrow::ToOwned; use alloc::format; use alloc::string::{String, ToString}; +use malachite_base::{num::conversion::traits::RoundingInto, rounding_modes::RoundingMode}; +use malachite_bigint::{BigInt, Sign}; +use malachite_q::Rational; use num_traits::Zero; +/// Round the exact quotient of two integers to a Python float. +/// +/// The denominator must be nonzero. +#[must_use] +pub fn true_div(numerator: &BigInt, denominator: &BigInt) -> f64 { + // Rational has no signed zero. Preserve the division sign before + // converting a zero numerator, as CPython's long_true_divide does. + if numerator.is_zero() && denominator.sign() == Sign::Minus { + return -0.0; + } + let rational = Rational::from_integers_ref(numerator.into(), denominator.into()); + // Nearest rounding can return the largest finite value for a quotient + // slightly beyond it; overflow starts at the halfway rounding boundary. + let (rounded, _) = rational.rounding_into(RoundingMode::Nearest); + rounded +} + #[must_use] pub fn parse_str(literal: &str) -> Option { parse_inner(literal.trim().as_bytes()) @@ -418,6 +438,38 @@ pub fn to_hex(value: f64) -> String { } } +// Canonical (floordiv, mod) for floats matching CPython's _float_div_mod +// (Objects/floatobject.c). `mod_` and `floordiv` delegate here so that +// `divmod(a, b) == (a // b, a % b)` holds by construction. +#[must_use] +pub fn divmod(v1: f64, v2: f64) -> Option<(f64, f64)> { + if v2 == 0.0 { + return None; + } + let mut m = v1 % v2; + let mut d = (v1 - m) / v2; + if m != 0.0 { + // Non-zero remainder must have the sign of the divisor. + if v2.is_sign_negative() != m.is_sign_negative() { + m += v2; + d -= 1.0; + } + } else { + // Zero remainder: sign matches divisor (IEEE 754 / CPython contract). + m = (0.0_f64).copysign(v2); + } + let d = if d != 0.0 { + let f = num_traits::float::FloatCore::floor(d); + // Snap up if (v1 - m) / v2 undershot the true integer quotient by + // more than half an ULP (mirrors CPython's `if (div - *floordiv > 0.5)`). + if d - f > 0.5 { f + 1.0 } else { f } + } else { + // Zero quotient: take the sign of the true quotient v1 / v2. + (0.0_f64).copysign(v1 / v2) + }; + Some((d, m)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/pylib/Cargo.toml b/crates/pylib/Cargo.toml index 0a9326640c1..b1962409af4 100644 --- a/crates/pylib/Cargo.toml +++ b/crates/pylib/Cargo.toml @@ -2,7 +2,7 @@ name = "rustpython-pylib" description = "A subset of the Python standard library for use with RustPython" license-file = "Lib/PSF-LICENSE" -include = ["Cargo.toml", "build.rs", "src/**/*.rs", "Lib/", "!Lib/**/test/", "!Lib/**/*.pyc"] +include = ["Cargo.toml", "build.rs", "src/**/*.rs", "LICENSE-profiling", "Lib/", "!Lib/**/test/", "!Lib/**/*.pyc"] authors = ["CPython Developers"] version.workspace = true edition.workspace = true @@ -10,7 +10,7 @@ rust-version.workspace = true repository.workspace = true [features] -freeze-stdlib = ["dep:rustpython-compiler-core", "dep:rustpython-derive"] +freeze-stdlib = ["dep:rustpython-compiler-core", "dep:rustpython-derive", "dep:sha2"] [dependencies] rustpython-compiler-core = { workspace = true, optional = true } @@ -18,6 +18,7 @@ rustpython-derive = { workspace = true, optional = true } [build-dependencies] glob = { workspace = true } +sha2 = { workspace = true, optional = true } [lints] workspace = true \ No newline at end of file diff --git a/crates/pylib/LICENSE-profiling b/crates/pylib/LICENSE-profiling new file mode 100644 index 00000000000..5dd1460ed18 --- /dev/null +++ b/crates/pylib/LICENSE-profiling @@ -0,0 +1,225 @@ +Vendored profiling output assets +=============================== + +License notices and terms copied from CPython commit +d220409a13b77de7a6c30abe16ea90db01528edc, with the section reference adapted +for this standalone notice. +Source notices: Doc/license.rst, "Profiling module" and the Apache License +text referenced there (reproduced below from the "OpenSSL" section). +https://github.com/python/cpython/blob/d220409a13b77de7a6c30abe16ea90db01528edc/Doc/license.rst + +Asset mapping under Lib/profiling/sampling/_vendor/: +- d3/7.8.5/d3.min.js: d3.js notice below. +- d3-flame-graph/4.1.3/d3-flamegraph.css: Apache License 2.0. +- d3-flame-graph/4.1.3/d3-flamegraph.min.js: Apache License 2.0. +- d3-flame-graph/4.1.3/d3-flamegraph-tooltip.min.js: Apache License 2.0. + +Canonical profiling notices +--------------------------- + +The :mod:`!profiling` module includes vendored third-party libraries in +:file:`Lib/profiling/sampling/_vendor/` with the following licenses: + +**d3-flamegraph** + +The d3-flamegraph library is distributed under the Apache License, Version 2.0. +See "Referenced Apache License text" below for the full text of the Apache License Version 2.0. + +**d3.js** + +The d3.js library contains the following notice:: + + Copyright 2010-2021 Mike Bostock + + Permission to use, copy, modify, and/or distribute this software for any purpose + with or without fee is hereby granted, provided that the above copyright notice + and this permission notice appear in all copies. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND + FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF + THIS SOFTWARE. + + +Referenced Apache License text +------------------------------ + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/crates/pylib/build.rs b/crates/pylib/build.rs index f96ef9b477c..55f82d255bd 100644 --- a/crates/pylib/build.rs +++ b/crates/pylib/build.rs @@ -1,6 +1,8 @@ const CRATE_ROOT: &str = "../.."; fn main() { + #[cfg(feature = "freeze-stdlib")] + embed_profiling_resources(); process_python_libs(format!("{CRATE_ROOT}/vm/Lib/python_builtins/*").as_str()); process_python_libs(format!("{CRATE_ROOT}/vm/Lib/core_modules/*").as_str()); @@ -50,3 +52,132 @@ fn process_python_libs(pattern: &str) { println!("cargo:rerun-if-changed={display}"); } } + +// spell-checker: ignore pyfile +// Only these canonical CPython 3.15.0 assets are bundled. This is deliberately +// not a recursive embedding of Lib data or tests. Keep the notices in +// crates/pylib/LICENSE-profiling with every distribution of these bytes. +#[cfg(feature = "freeze-stdlib")] +const PROFILING_RESOURCES: &[(&str, &str)] = &[ + ( + "profiling/sampling/_assets/tachyon-logo.png", + "b72b0e28079ee7c033458f279e1c721d4d689db43f6e616848504d09ebe9c85d", + ), + ( + "profiling/sampling/_flamegraph_assets/flamegraph.css", + "a57f0512fe7071ca7915ac063e45df2173d7cea3b1fdded36fbb481cc14dafbb", + ), + ( + "profiling/sampling/_flamegraph_assets/flamegraph.js", + "9b39e61bfeadb6e4f9132c6dedb3b6f62f421821dc98261079ca6942f7649995", + ), + ( + "profiling/sampling/_flamegraph_assets/flamegraph_template.html", + "6469b5f46e27eaccf9b212e2d30d30807bca15873ea106a66726cbafc0babf39", + ), + ( + "profiling/sampling/_heatmap_assets/heatmap.css", + "17dd5a24ea930b2c8e3e51cd16dda20b68434273b9400ef3f965159e31213608", + ), + ( + "profiling/sampling/_heatmap_assets/heatmap.js", + "335f02d7b8baa94f0294afc0a71a3a4cbc5799187524524ce2a62ee18d16023f", + ), + ( + "profiling/sampling/_heatmap_assets/heatmap_index.js", + "d75ff0fe6781bba58b3a2ce3af63a329da39a7002f3eabf1adcc3cdc14c4d3fd", + ), + ( + "profiling/sampling/_heatmap_assets/heatmap_index_template.html", + "152b8b80c6cd318403c8e4a7a6d3b9256ae2dc3459698c606398bb58e199cffe", + ), + ( + "profiling/sampling/_heatmap_assets/heatmap_pyfile_template.html", + "ed68e3905f19b4535d561628359464ef7d575332a126a827fdc7b70ca4c17099", + ), + ( + "profiling/sampling/_heatmap_assets/heatmap_shared.js", + "15e4ba8b7830fb5e33f9aec95c42acf62b950df11210884aee62eddd580a68ab", + ), + ( + "profiling/sampling/_shared_assets/base.css", + "f09f2a549ce69a31e6a3fc29979a32204781320b377bd6488f00f71c3811af23", + ), + ( + "profiling/sampling/_shared_assets/base.js", + "b6f0d0a0720a7f3b20b14be710b7db257a89098178f3ab785d77da76eb019b18", + ), + ( + "profiling/sampling/_vendor/d3/7.8.5/d3.min.js", + "d6b03aefc9f6c44c7bc78713679c78c295028fa914319119e5cc4b4954855b1c", + ), + ( + "profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph-tooltip.min.js", + "105738fc5fe7ca67327cf9a91a63fbd54e5fd3d2becd0e07650ca919b5678ac9", + ), + ( + "profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph.css", + "7d75d68cb662819a37401248863100dd9db351f4bebf3310845d9196fbab7e2a", + ), + ( + "profiling/sampling/_vendor/d3-flame-graph/4.1.3/d3-flamegraph.min.js", + "1846f1e636ed1bd2c32fc87d1e24d63aff7e4f18629b4bbd819351f09ea22353", + ), +]; + +#[cfg(feature = "freeze-stdlib")] +fn embed_profiling_resources() { + use core::fmt::Write; + use sha2::{Digest, Sha256}; + use std::path::PathBuf; + + // Match LIB_PATH's Windows checkout-link handling without relying on Git's + // ability to create a symlink. Canonicalize the root before containment checks. + let lib = if cfg!(windows) { + std::fs::read_to_string("Lib") + .map_or_else(|_| PathBuf::from("Lib"), |link| PathBuf::from(link.trim())) + } else { + PathBuf::from("Lib") + }; + let lib = lib + .canonicalize() + .expect("resolve canonical Lib resource root"); + let out = PathBuf::from(std::env::var_os("OUT_DIR").expect("Cargo OUT_DIR")); + let mut source = String::from( + "pub const FROZEN_STDLIB_RESOURCES: &[FrozenResourceBundle] = &[(\"profiling\", &[\n", + ); + println!("cargo:rerun-if-changed=Lib"); + for (index, &(relative, expected)) in PROFILING_RESOURCES.iter().enumerate() { + let path = lib.join(relative); + println!("cargo:rerun-if-changed={}", path.display()); + let canonical = path.canonicalize().expect("resolve profiling resource"); + assert!( + canonical.starts_with(&lib), + "profiling resource escapes Lib: {relative}" + ); + assert!( + canonical.is_file(), + "profiling resource is not a file: {relative}" + ); + let bytes = std::fs::read(&canonical).expect("read profiling resource"); + let mut actual = String::with_capacity(64); + for byte in Sha256::digest(&bytes) { + write!(actual, "{byte:02x}").expect("write digest hex"); + } + assert_eq!( + actual, expected, + "profiling resource differs from pinned CPython: {relative}" + ); + // Snapshot exactly the bytes we hashed, rather than asking include_bytes! + // to reread a mutable source file after this build script has returned. + let snapshot = out.join(format!("profiling-resource-{index}.bin")); + std::fs::write(&snapshot, bytes).expect("write owned resource snapshot"); + let logical = relative + .strip_prefix("profiling/") + .expect("profiling resource path"); + writeln!(source, "({logical:?}, include_bytes!({snapshot:?})),") + .expect("write resource source"); + } + source.push_str("])];\n"); + std::fs::write(out.join("frozen_resources.rs"), source).expect("write resource sidecar"); +} diff --git a/crates/pylib/src/lib.rs b/crates/pylib/src/lib.rs index db957f633fc..a116242e395 100644 --- a/crates/pylib/src/lib.rs +++ b/crates/pylib/src/lib.rs @@ -14,3 +14,12 @@ pub const LIB_PATH: &str = match option_env!("win_lib_path") { #[cfg(feature = "freeze-stdlib")] pub const FROZEN_STDLIB: &rustpython_compiler_core::frozen::FrozenLib = rustpython_derive::py_freeze!(dir = "../Lib", crate_name = "rustpython_compiler_core"); + +#[cfg(feature = "freeze-stdlib")] +type FrozenResource = (&'static str, &'static [u8]); +#[cfg(feature = "freeze-stdlib")] +type FrozenResourceBundle = (&'static str, &'static [FrozenResource]); + +// Resource bytes are registered alongside the exact frozen module batch. +#[cfg(feature = "freeze-stdlib")] +include!(concat!(env!("OUT_DIR"), "/frozen_resources.rs")); diff --git a/crates/sre_engine/src/engine.rs b/crates/sre_engine/src/engine.rs index c2a6ac81975..a113e7cc501 100644 --- a/crates/sre_engine/src/engine.rs +++ b/crates/sre_engine/src/engine.rs @@ -1,11 +1,11 @@ // good luck to those that follow; here be dragons use crate::string::{ - is_digit, is_linebreak, is_loc_word, is_space, is_uni_digit, is_uni_linebreak, is_uni_space, - is_uni_word, is_word, lower_ascii, lower_locate, lower_unicode, upper_locate, upper_unicode, + is_digit, is_linebreak, is_space, is_uni_digit, is_uni_linebreak, is_uni_space, is_uni_word, + is_word, lower_ascii, lower_unicode, upper_unicode, }; -use super::{MAXREPEAT, SreAtCode, SreCatCode, SreInfo, SreOpcode, StrDrive, StringCursor}; +use super::{Locale, MAXREPEAT, SreAtCode, SreCatCode, SreInfo, SreOpcode, StrDrive, StringCursor}; use alloc::{vec, vec::Vec}; use core::{convert::TryFrom, ptr::null}; use optional::Optioned; @@ -18,6 +18,7 @@ pub struct Request<'a, S> { pub pattern_codes: &'a [u32], pub match_all: bool, pub must_advance: bool, + pub locale: Locale, } impl<'a, S: StrDrive> Request<'a, S> { @@ -38,6 +39,7 @@ impl<'a, S: StrDrive> Request<'a, S> { pattern_codes, match_all, must_advance: false, + locale: Locale::default(), } } } @@ -101,9 +103,9 @@ impl Marks { } fn pop_keep(&mut self) { - let (marks, last_index) = self.marks_stack.last().unwrap().clone(); - self.marks = marks; - self.last_index = last_index; + let (marks, last_index) = self.marks_stack.last().unwrap(); + self.marks.clone_from(marks); + self.last_index = *last_index; } fn pop_discard(&mut self) { @@ -288,6 +290,7 @@ enum Jump { MaxUntil2, MaxUntil3, MinUntil1, + MinUntil2, RepeatOne1, RepeatOne2, MinRepeatOne1, @@ -321,6 +324,7 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo } Jump::AssertNot1 => { if popped_result { + state.marks.pop_discard(); break 'result false; } state.marks.pop(); @@ -340,6 +344,7 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo } Jump::Branch2 => { if popped_result { + state.marks.pop_discard(); break 'result true; } state.marks.pop_keep(); @@ -385,6 +390,7 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo } Jump::MinUntil1 => { if popped_result { + state.marks.pop_discard(); break 'result true; } ctx.repeat_ctx_id = ctx.count as usize; @@ -402,10 +408,19 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo } /* zero-width match protection */ + ctx.count = repeat_ctx.last_position as isize; repeat_ctx.last_position = state.cursor.position; - break 'context ctx - .next_at(repeat_ctx.code_position + 4, Jump::UntilBacktrace); + break 'context ctx.next_at(repeat_ctx.code_position + 4, Jump::MinUntil2); + } + Jump::MinUntil2 => { + let repeat_ctx = &mut state.repeat_stack[ctx.repeat_ctx_id]; + repeat_ctx.last_position = ctx.count as usize; + if !popped_result { + repeat_ctx.count -= 1; + state.cursor = ctx.cursor; + } + break 'result popped_result; } Jump::RepeatOne1 => { let min_count = ctx.peek_code(req, 2) as isize; @@ -430,6 +445,7 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo } Jump::RepeatOne2 => { if popped_result { + state.marks.pop_discard(); break 'result true; } @@ -457,6 +473,7 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo } Jump::MinRepeatOne2 => { if popped_result { + state.marks.pop_discard(); break 'result true; } @@ -674,20 +691,24 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo } SreOpcode::CATEGORY => { let cat_code = SreCatCode::try_from(ctx.peek_code(req, 1)).unwrap(); - if ctx.at_end(req) || !category(cat_code, ctx.peek_char::()) { + if ctx.at_end(req) + || !category(cat_code, ctx.peek_char::(), req.locale) + { break 'result false; } ctx.skip_code(2); ctx.advance_char::(); } - SreOpcode::IN => general_op_in!(charset), + SreOpcode::IN => general_op_in!(|set, c| charset(set, c, req.locale)), SreOpcode::IN_IGNORE => { - general_op_in!(|set, c| charset(set, lower_ascii(c))) + general_op_in!(|set, c| charset(set, lower_ascii(c), req.locale)) } SreOpcode::IN_UNI_IGNORE => { - general_op_in!(|set, c| charset(set, lower_unicode(c))) + general_op_in!(|set, c| charset(set, lower_unicode(c), req.locale)) + } + SreOpcode::IN_LOC_IGNORE => { + general_op_in!(|set, c| charset_loc_ignore(set, c, req.locale)) } - SreOpcode::IN_LOC_IGNORE => general_op_in!(charset_loc_ignore), SreOpcode::MARK => { state .marks @@ -739,12 +760,13 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo /* cannot match more repeated items here. make sure the tail matches */ + repeat_ctx.count -= 1; let mut next_ctx = ctx.next_offset(1, Jump::MaxUntil3); next_ctx.repeat_ctx_id = repeat_ctx.prev_id; break 'context next_ctx; } SreOpcode::MIN_UNTIL => { - let repeat_ctx = state.repeat_stack.last_mut().unwrap(); + let repeat_ctx = &mut state.repeat_stack[ctx.repeat_ctx_id]; state.cursor = ctx.cursor; repeat_ctx.count += 1; @@ -837,13 +859,17 @@ fn _match(req: &Request<'_, S>, state: &mut State, mut ctx: MatchCo SreOpcode::NOT_LITERAL_UNI_IGNORE => { general_op_literal!(|code, c| code != lower_unicode(c)) } - SreOpcode::LITERAL_LOC_IGNORE => general_op_literal!(char_loc_ignore), + SreOpcode::LITERAL_LOC_IGNORE => { + general_op_literal!(|code, c| char_loc_ignore(code, c, req.locale)) + } SreOpcode::NOT_LITERAL_LOC_IGNORE => { - general_op_literal!(|code, c| !char_loc_ignore(code, c)) + general_op_literal!(|code, c| !char_loc_ignore(code, c, req.locale)) } SreOpcode::GROUPREF => general_op_groupref!(|x| x), SreOpcode::GROUPREF_IGNORE => general_op_groupref!(lower_ascii), - SreOpcode::GROUPREF_LOC_IGNORE => general_op_groupref!(lower_locate), + SreOpcode::GROUPREF_LOC_IGNORE => { + general_op_groupref!(|c| req.locale.lower(c)) + } SreOpcode::GROUPREF_UNI_IGNORE => general_op_groupref!(lower_unicode), SreOpcode::GROUPREF_EXISTS => { let (group_start, group_end) = @@ -1042,7 +1068,7 @@ fn search_info_charset( req.must_advance = false; loop { - while !ctx.at_end(req) && !charset(set, ctx.peek_char::()) { + while !ctx.at_end(req) && !charset(set, ctx.peek_char::(), req.locale) { ctx.advance_char::(); } if ctx.at_end(req) { @@ -1226,27 +1252,76 @@ fn at(req: &Request<'_, S>, ctx: &MatchContext, at_code: SreAtCode) } SreAtCode::END_LINE => ctx.at_linebreak(req) || ctx.at_end(req), SreAtCode::END_STRING => ctx.at_end(req), - SreAtCode::LOC_BOUNDARY => ctx.at_boundary(req, is_loc_word), - SreAtCode::LOC_NON_BOUNDARY => ctx.at_non_boundary(req, is_loc_word), + SreAtCode::LOC_BOUNDARY => ctx.at_boundary(req, |ch| req.locale.is_word(ch)), + SreAtCode::LOC_NON_BOUNDARY => ctx.at_non_boundary(req, |ch| req.locale.is_word(ch)), SreAtCode::UNI_BOUNDARY => ctx.at_boundary(req, is_uni_word), SreAtCode::UNI_NON_BOUNDARY => ctx.at_non_boundary(req, is_uni_word), } } -fn char_loc_ignore(code: u32, c: u32) -> bool { - code == c || code == lower_locate(c) || code == upper_locate(c) +fn char_loc_ignore(code: u32, c: u32, locale: Locale) -> bool { + code == c || code == locale.lower(c) || code == locale.upper(c) } -fn charset_loc_ignore(set: &[u32], c: u32) -> bool { - let lo = lower_locate(c); - if charset(set, c) { - return true; +fn charset_loc_ignore(set: &[u32], c: u32, locale: Locale) -> bool { + let lo = locale.lower(c); + let up = locale.upper(c); + if lo == up { + return charset(set, lo, locale); } - let up = upper_locate(c); - up != lo && charset(set, up) + + // Test both cases before applying NEGATE. OR-ing two complete charset + // matches would incorrectly accept a character excluded by either case. + let mut ok = true; + let mut i = 0; + while i < set.len() { + let Ok(opcode) = SreOpcode::try_from(set[i]) else { + break; + }; + match opcode { + SreOpcode::FAILURE => return !ok, + SreOpcode::LITERAL => { + if lo == set[i + 1] || up == set[i + 1] { + return ok; + } + i += 2; + } + SreOpcode::CATEGORY => { + let Ok(cat_code) = SreCatCode::try_from(set[i + 1]) else { + break; + }; + if category(cat_code, lo, locale) || category(cat_code, up, locale) { + return ok; + } + i += 2; + } + SreOpcode::CHARSET => { + let bitmap = &set[i + 1..]; + if (lo < 256 && bitmap[(lo >> 5) as usize] & (1u32 << (lo & 31)) != 0) + || (up < 256 && bitmap[(up >> 5) as usize] & (1u32 << (up & 31)) != 0) + { + return ok; + } + i += 9; + } + SreOpcode::RANGE => { + if (set[i + 1] <= lo && lo <= set[i + 2]) || (set[i + 1] <= up && up <= set[i + 2]) + { + return ok; + } + i += 3; + } + SreOpcode::NEGATE => { + ok = !ok; + i += 1; + } + _ => break, + } + } + false } -fn category(cat_code: SreCatCode, c: u32) -> bool { +fn category(cat_code: SreCatCode, c: u32, locale: Locale) -> bool { match cat_code { SreCatCode::DIGIT => is_digit(c), SreCatCode::NOT_DIGIT => !is_digit(c), @@ -1256,8 +1331,8 @@ fn category(cat_code: SreCatCode, c: u32) -> bool { SreCatCode::NOT_WORD => !is_word(c), SreCatCode::LINEBREAK => is_linebreak(c), SreCatCode::NOT_LINEBREAK => !is_linebreak(c), - SreCatCode::LOC_WORD => is_loc_word(c), - SreCatCode::LOC_NOT_WORD => !is_loc_word(c), + SreCatCode::LOC_WORD => locale.is_word(c), + SreCatCode::LOC_NOT_WORD => !locale.is_word(c), SreCatCode::UNI_DIGIT => is_uni_digit(c), SreCatCode::UNI_NOT_DIGIT => !is_uni_digit(c), SreCatCode::UNI_SPACE => is_uni_space(c), @@ -1269,7 +1344,7 @@ fn category(cat_code: SreCatCode, c: u32) -> bool { } } -fn charset(set: &[u32], ch: u32) -> bool { +fn charset(set: &[u32], ch: u32, locale: Locale) -> bool { /* check if character is a member of the given set */ let mut ok = true; let mut i = 0; @@ -1292,7 +1367,7 @@ fn charset(set: &[u32], ch: u32) -> bool { break; } }; - if category(cat_code, ch) { + if category(cat_code, ch, locale) { return ok; } i += 2; @@ -1382,7 +1457,8 @@ fn _count( ctx.skip_char::(max_count); } SreOpcode::IN => { - while ctx.cursor.position < end && charset(&ctx.pattern(req)[2..], ctx.peek_char::()) + while ctx.cursor.position < end + && charset(&ctx.pattern(req)[2..], ctx.peek_char::(), req.locale) { ctx.advance_char::(); } @@ -1400,10 +1476,14 @@ fn _count( general_count_literal(req, ctx, end, |code, c| code != lower_ascii(c)); } SreOpcode::LITERAL_LOC_IGNORE => { - general_count_literal(req, ctx, end, char_loc_ignore); + general_count_literal(req, ctx, end, |code, c| { + char_loc_ignore(code, c, req.locale) + }); } SreOpcode::NOT_LITERAL_LOC_IGNORE => { - general_count_literal(req, ctx, end, |code, c| !char_loc_ignore(code, c)); + general_count_literal(req, ctx, end, |code, c| { + !char_loc_ignore(code, c, req.locale) + }); } SreOpcode::LITERAL_UNI_IGNORE => { general_count_literal(req, ctx, end, |code, c| code == lower_unicode(c)); diff --git a/crates/sre_engine/src/lib.rs b/crates/sre_engine/src/lib.rs index df598974ba9..7c31a6bae9d 100644 --- a/crates/sre_engine/src/lib.rs +++ b/crates/sre_engine/src/lib.rs @@ -8,7 +8,7 @@ pub mod string; pub use constants::{SRE_MAGIC, SreAtCode, SreCatCode, SreFlag, SreInfo, SreOpcode}; pub use engine::{Request, SearchIter, State}; -pub use string::{StrDrive, StringCursor}; +pub use string::{Locale, StrDrive, StringCursor}; pub const CODESIZE: usize = 4; diff --git a/crates/sre_engine/src/string.rs b/crates/sre_engine/src/string.rs index d16a3ee88af..52b427a9414 100644 --- a/crates/sre_engine/src/string.rs +++ b/crates/sre_engine/src/string.rs @@ -391,15 +391,44 @@ pub(crate) fn is_digit(ch: u32) -> bool { u8::try_from(ch).is_ok_and(|x| x.is_ascii_digit()) } -#[inline] -pub(crate) fn is_loc_alnum(ch: u32) -> bool { - // FIXME: Ignore the locales - u8::try_from(ch).is_ok_and(|x| x.is_ascii_alphanumeric()) +/// Byte classification and case conversion in the current locale. +/// +/// Callbacks keep host APIs outside this `no_std` engine. They are called while +/// matching, rather than cached in a compiled pattern, so a locale change also +/// affects existing patterns and scanners. Without host callbacks, matching uses +/// the ASCII rules of the C locale. +#[derive(Debug, Clone, Copy)] +pub struct Locale { + pub is_alnum: fn(u8) -> bool, + pub to_lower: fn(u8) -> u32, + pub to_upper: fn(u8) -> u32, } -#[inline] -pub(crate) fn is_loc_word(ch: u32) -> bool { - ch == UNDERSCORE || is_loc_alnum(ch) +impl Default for Locale { + fn default() -> Self { + Self { + is_alnum: |ch| ch.is_ascii_alphanumeric(), + to_lower: |ch| ch.to_ascii_lowercase() as u32, + to_upper: |ch| ch.to_ascii_uppercase() as u32, + } + } +} + +impl Locale { + #[inline] + pub(crate) fn is_word(self, ch: u32) -> bool { + ch == UNDERSCORE || u8::try_from(ch).is_ok_and(self.is_alnum) + } + + #[inline] + pub(crate) fn lower(self, ch: u32) -> u32 { + u8::try_from(ch).map_or(ch, self.to_lower) + } + + #[inline] + pub(crate) fn upper(self, ch: u32) -> u32 { + u8::try_from(ch).map_or(ch, self.to_upper) + } } #[inline] @@ -413,18 +442,6 @@ pub fn lower_ascii(ch: u32) -> u32 { u8::try_from(ch).map_or(ch, |x| x.to_ascii_lowercase() as u32) } -#[inline] -pub(crate) fn lower_locate(ch: u32) -> u32 { - // FIXME: Ignore the locales - lower_ascii(ch) -} - -#[inline] -pub(crate) fn upper_locate(ch: u32) -> u32 { - // FIXME: Ignore the locales - u8::try_from(ch).map_or(ch, |x| x.to_ascii_uppercase() as u32) -} - #[inline] pub(crate) fn is_uni_digit(ch: u32) -> bool { // SRE_UNI_IS_DIGIT matches Unicode decimal digits (Py_UNICODE_ISDECIMAL), diff --git a/crates/stdlib/Cargo.toml b/crates/stdlib/Cargo.toml index 64e926fb610..38cfe24b60c 100644 --- a/crates/stdlib/Cargo.toml +++ b/crates/stdlib/Cargo.toml @@ -11,7 +11,8 @@ license.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [features] -default = ["compiler", "host_env", "doc"] +default = ["compiler", "host_env", "doc", "ucd_3_2_0"] +ucd_3_2_0 = ["rustpython-unicode/ucd_3_2_0"] doc = ["rustpython-vm/doc"] host_env = ["rustpython-vm/host_env"] compiler = ["rustpython-vm/compiler"] @@ -41,6 +42,7 @@ ruff_text_size = { workspace = true } ruff_source_file = { workspace = true } ascii = { workspace = true } +half = { workspace = true } crossbeam-utils = { workspace = true } flame = { workspace = true, optional = true } hex = { workspace = true } diff --git a/crates/stdlib/build.rs b/crates/stdlib/build.rs index d9d1ca4a677..7f6248783a8 100644 --- a/crates/stdlib/build.rs +++ b/crates/stdlib/build.rs @@ -20,6 +20,8 @@ fn main() { (0x3_01_00_00_0, "ossl310"), (0x3_02_00_00_0, "ossl320"), (0x3_03_00_00_0, "ossl330"), + (0x3_04_00_00_0, "ossl340"), + (0x3_05_00_00_0, "ossl350"), ]; for (_, cfg) in ossl_vers { diff --git a/crates/stdlib/src/_asyncio.rs b/crates/stdlib/src/_asyncio.rs index f56943c19d7..91c6210d386 100644 --- a/crates/stdlib/src/_asyncio.rs +++ b/crates/stdlib/src/_asyncio.rs @@ -14,7 +14,7 @@ pub(crate) mod _asyncio { AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{ PyBaseException, PyBaseExceptionRef, PyDict, PyGenericAlias, PyList, PyListRef, - PyModule, PySet, PyTraceback, PyTuple, PyType, PyTypeRef, + PyModule, PySet, PyTraceback, PyTuple, PyType, PyTypeRef, alloc_default, }, extend_module, function::{FuncArgs, KwArgs, OptionalArg, PySetterValue}, @@ -62,10 +62,11 @@ pub(crate) mod _asyncio { #[derive(FromArgs)] struct AddDoneCallbackArgs { - #[pyarg(positional, name = "fn")] - func: PyObjectRef, + #[pyarg(positional)] + r#fn: PyObjectRef, + // Omission copies the context now; explicit None is forwarded to call_soon. #[pyarg(named, optional)] - context: Option, + context: OptionalArg, } #[derive(FromArgs)] @@ -74,10 +75,20 @@ pub(crate) mod _asyncio { msg: Option, } + fn cancel_message_delete_error(zelf: &PyObject, vm: &VirtualMachine) -> PyBaseExceptionRef { + let class = zelf.class(); + let name = class.slot_name(); + let end = name.floor_char_boundary(name.len().min(100)); + vm.new_attribute_error(format!( + "attribute '_cancel_message' of '{}' objects cannot be deleted", + &name[..end] + )) + } + #[derive(FromArgs)] struct LoopArg { - #[pyarg(any, name = "loop", optional)] - loop_: Option, + #[pyarg(any, optional)] + r#loop: Option, } #[derive(FromArgs)] @@ -146,15 +157,15 @@ pub(crate) mod _asyncio { #[derive(FromArgs)] struct FutureInitArgs { - #[pyarg(named, name = "loop", optional)] - loop_: Option, + #[pyarg(named, optional)] + r#loop: Option, } impl Initializer for PyFuture { type Args = FutureInitArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - Self::py_init(zelf, args.loop_, vm) + Self::py_init(zelf, args.r#loop, vm) } } @@ -188,6 +199,13 @@ pub(crate) mod _asyncio { loop_: Option, vm: &VirtualMachine, ) -> PyResult<()> { + if zelf.fut_loop.read().is_some() { + return Err(vm.new_runtime_error(wtf8_concat!( + zelf.class().fully_qualified_name(vm)?, + " object is already initialized" + ))); + } + // Get the event loop let loop_obj = match loop_ { Some(l) if !vm.is_none(&l) => l, @@ -293,8 +311,14 @@ pub(crate) mod _asyncio { } // Normalize the exception - let exc = if exception.fast_isinstance(vm.ctx.types.type_type) { - exception.call((), vm)? + let exc = if let Some(cls) = exception.downcast_ref::() + && cls.fast_issubclass(vm.ctx.exceptions.base_exception_type) + { + let exc = exception.call((), vm)?; + if zelf.fut_state.load() != FutureState::Pending { + return Err(new_invalid_state_error(vm, "invalid state")); + } + exc } else { exception }; @@ -327,8 +351,8 @@ pub(crate) mod _asyncio { *zelf.fut_exception.write() = Some(exc); zelf.fut_state.store(FutureState::Finished); - zelf.fut_log_tb.store(true, Ordering::Relaxed); Self::schedule_callbacks(&zelf, vm)?; + zelf.fut_log_tb.store(true, Ordering::Relaxed); Ok(()) } @@ -338,27 +362,44 @@ pub(crate) mod _asyncio { args: AddDoneCallbackArgs, vm: &VirtualMachine, ) -> PyResult<()> { - if zelf.fut_loop.read().is_none() { + zelf.add_done_callback_impl(zelf.as_object(), args, vm) + } + + fn add_done_callback_impl( + &self, + owner: &PyObject, + args: AddDoneCallbackArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + if self.fut_loop.read().is_none() { return Err(vm.new_runtime_error("Future object is not initialized.")); } let ctx = match args.context { - Some(c) => c, - None => get_copy_context(vm)?, + OptionalArg::Present(c) => c, + OptionalArg::Missing => get_copy_context(vm)?, }; - if zelf.fut_state.load() != FutureState::Pending { - Self::call_soon_with_context(&zelf, args.func, Some(ctx), vm)?; - } else if zelf.fut_callback0.read().is_none() { - *zelf.fut_callback0.write() = Some(args.func); - *zelf.fut_context0.write() = Some(ctx); + if self.fut_state.load() != FutureState::Pending { + self.call_soon_with_context(owner, args.r#fn, Some(ctx), vm)?; } else { - let tuple = vm.ctx.new_tuple(vec![args.func, ctx]); - let mut callbacks = zelf.fut_callbacks.write(); - if callbacks.is_none() { - *callbacks = Some(vm.ctx.new_list(vec![tuple.into()]).into()); + let callbacks = self.fut_callbacks.read().clone(); + // Once a list exists, append to it even if callback0 was removed. + // Refilling callback0 would move the new callback ahead of the list. + if callbacks.is_none() && self.fut_callback0.read().is_none() { + *self.fut_callback0.write() = Some(args.r#fn); + *self.fut_context0.write() = Some(ctx); } else { - let list = callbacks.as_ref().unwrap(); - vm.call_method(list, "append", (tuple,))?; + let tuple = vm.ctx.new_tuple(vec![args.r#fn, ctx]); + if let Some(callbacks) = callbacks { + callbacks + .downcast_ref::() + .unwrap() + .borrow_vec_mut() + .push(tuple.into()); + } else { + *self.fut_callbacks.write() = + Some(vm.ctx.new_list(vec![tuple.into()]).into()); + } } } Ok(()) @@ -367,102 +408,106 @@ pub(crate) mod _asyncio { #[pymethod] fn remove_done_callback( zelf: &Py, - RemoveDoneCallbackArgs { func }: RemoveDoneCallbackArgs, + RemoveDoneCallbackArgs { r#fn: func }: RemoveDoneCallbackArgs, vm: &VirtualMachine, - ) -> PyResult { - if zelf.fut_loop.read().is_none() { + ) -> PyResult { + zelf.remove_done_callback_impl(&func, vm) + } + + fn remove_done_callback_impl( + &self, + func: &PyObject, + vm: &VirtualMachine, + ) -> PyResult { + if self.fut_loop.read().is_none() { return Err(vm.new_runtime_error("Future object is not initialized.")); } - let mut cleared_callback0 = 0usize; - - // Check fut_callback0 first - // Clone to release lock before comparison (which may run Python code) - let cb0 = zelf.fut_callback0.read().clone(); + let mut cleared_callback0 = 0; + let cb0 = self.fut_callback0.read().clone(); if let Some(cb0) = cb0 { - let cmp = vm.identical_or_equal(&cb0, &func)?; - if cmp { - *zelf.fut_callback0.write() = None; - *zelf.fut_context0.write() = None; + let cmp = vm.identical_or_equal(&cb0, func); + drop(cb0); + if cmp? { + // Dropping callbacks or contexts may run finalizers. Release + // each field lock before dropping the previous reference. + let callback = self.fut_callback0.write().take(); + drop(callback); + let _context = self.fut_context0.write().take(); cleared_callback0 = 1; } } - // Check if fut_callbacks exists - let callbacks = zelf.fut_callbacks.read().clone(); - let callbacks = match callbacks { - Some(c) => c, - None => return Ok(cleared_callback0), + let len = { + let callbacks = self.fut_callbacks.read().clone(); + let Some(callbacks) = callbacks else { + return Ok(cleared_callback0); + }; + callbacks + .downcast_ref::() + .unwrap() + .borrow_vec() + .len() }; - - let list: PyListRef = callbacks.downcast().unwrap(); - let len = list.borrow_vec().len(); - if len == 0 { - *zelf.fut_callbacks.write() = None; + let _callbacks = self.fut_callbacks.write().take(); return Ok(cleared_callback0); } - - // Special case for single callback if len == 1 { - let item = list.borrow_vec().first().cloned(); - if let Some(item) = item { - let tuple: &Py = item.downcast_ref().unwrap(); - let cb = tuple.as_slice().first().unwrap().clone(); - let cmp = vm.identical_or_equal(&cb, &func)?; - if cmp { - *zelf.fut_callbacks.write() = None; - return Ok(1 + cleared_callback0); - } + let item = { + let callbacks = self.fut_callbacks.read().clone().unwrap(); + callbacks.downcast_ref::().unwrap().borrow_vec()[0].clone() + }; + let tuple = item.downcast_ref::().unwrap(); + let cmp = vm.identical_or_equal(&tuple.as_slice()[0], func); + drop(item); + if cmp? { + let _callbacks = self.fut_callbacks.write().take(); + return Ok(1 + cleared_callback0); } return Ok(cleared_callback0); } - // Multiple callbacks - iterate with index, checking validity each time - // to handle evil comparisons let mut new_callbacks = Vec::with_capacity(len); - let mut i = 0usize; - let mut removed = 0usize; - + let mut i = 0; loop { - // Re-check fut_callbacks on each iteration (evil code may have cleared it) - let callbacks = zelf.fut_callbacks.read().clone(); - let callbacks = match callbacks { - Some(c) => c, - None => break, - }; - let list: PyListRef = callbacks.downcast().unwrap(); - let current_len = list.borrow_vec().len(); - if i >= current_len { - break; - } - - // Get item and release lock before comparison - let item = list.borrow_vec().get(i).cloned(); - let item = match item { - Some(item) => item, - None => break, + // Comparisons can remove, append, or schedule the callbacks. + let item = { + let callbacks = self.fut_callbacks.read().clone(); + let Some(callbacks) = callbacks else { break }; + callbacks + .downcast_ref::() + .unwrap() + .borrow_vec() + .get(i) + .cloned() }; - - let tuple: &Py = item.downcast_ref().unwrap(); - let cb = tuple.as_slice().first().unwrap().clone(); - let cmp = vm.identical_or_equal(&cb, &func)?; - - if !cmp { + let Some(item) = item else { break }; + let tuple = item.downcast_ref::().unwrap(); + if !vm.identical_or_equal(&tuple.as_slice()[0], func)? { new_callbacks.push(item); - } else { - removed += 1; } i += 1; } - // Update fut_callbacks with filtered list - if new_callbacks.is_empty() { - *zelf.fut_callbacks.write() = None; - } else { - *zelf.fut_callbacks.write() = Some(vm.ctx.new_list(new_callbacks).into()); + let callbacks = self.fut_callbacks.read().clone(); + if new_callbacks.is_empty() || callbacks.is_none() { + let _callbacks = self.fut_callbacks.write().take(); + return Ok(len as isize + cleared_callback0); } - - Ok(removed + cleared_callback0) + let callbacks = callbacks.unwrap(); + let list = callbacks.downcast_ref::().unwrap(); + let current_len = list.borrow_vec().len(); + let remaining = new_callbacks.len(); + if remaining != current_len { + // Keep the filtered snapshot alive while removed callbacks run + // finalizers: they can recursively remove the surviving callbacks. + let previous = + core::mem::replace(&mut *list.borrow_vec_mut(), new_callbacks.clone()); + for _item in previous.into_iter().rev() {} + } + drop(callbacks); + for _item in new_callbacks.into_iter().rev() {} + Ok(current_len as isize - remaining as isize + cleared_callback0) } #[pymethod] @@ -523,53 +568,50 @@ pub(crate) mod _asyncio { } fn schedule_callbacks(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { - // Collect all callbacks first to avoid holding locks during callback execution - // This prevents deadlock when callbacks access the future's properties - let mut callbacks_to_call: Vec<(PyObjectRef, Option)> = Vec::new(); - - // Take callback0 - release lock before collecting from list - let cb0 = zelf.fut_callback0.write().take(); - let ctx0 = zelf.fut_context0.write().take(); - if let Some(cb) = cb0 { - callbacks_to_call.push((cb, ctx0)); - } - - // Take callbacks list and collect items - let callbacks_list = zelf.fut_callbacks.write().take(); - if let Some(callbacks) = callbacks_list - && let Ok(list) = callbacks.downcast::() - { - // Clone the items while holding the list lock, then release - let items: Vec<_> = list.borrow_vec().iter().cloned().collect(); - for item in items { - if let Some(tuple) = item.downcast_ref::() - && let (Some(cb), Some(ctx)) = - (tuple.as_slice().first(), tuple.as_slice().get(1)) - { - callbacks_to_call.push((cb.clone(), Some(ctx.clone()))); - } + zelf.schedule_callbacks_impl(zelf.as_object(), vm) + } + + fn schedule_callbacks_impl(&self, owner: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + let callback = self.fut_callback0.write().take(); + let context = self.fut_context0.write().take(); + if let Some(callback) = callback { + // Keep the list visible until the first call_soon returns: it + // may remove callbacks, and may also fail while scheduling. + if let Err(err) = self.call_soon_with_context(owner, callback, context, vm) { + let _callbacks = self.fut_callbacks.write().take(); + return Err(err); } } - // Now call all callbacks without holding any locks - for (cb, ctx) in callbacks_to_call { - Self::call_soon_with_context(zelf, cb, ctx, vm)?; + let callbacks = self.fut_callbacks.write().take(); + if let Some(callbacks) = callbacks { + let list = callbacks.downcast_ref::().unwrap(); + let items = list.borrow_vec().to_vec(); + for item in &items { + let tuple = item.downcast_ref::().unwrap(); + self.call_soon_with_context( + owner, + tuple.as_slice()[0].clone(), + Some(tuple.as_slice()[1].clone()), + vm, + )?; + } } - Ok(()) } fn call_soon_with_context( - zelf: &Py, + &self, + owner: &PyObject, callback: PyObjectRef, context: Option, vm: &VirtualMachine, ) -> PyResult<()> { - let loop_obj = zelf.fut_loop.read().clone(); + let loop_obj = self.fut_loop.read().clone(); if let Some(loop_obj) = loop_obj { // call_soon(callback, *args, context=context) // callback receives the future as its argument - let future_arg: PyObjectRef = zelf.to_owned().into(); + let future_arg: PyObjectRef = owner.to_owned(); let args = if let Some(ctx) = context { FuncArgs::new( vec![callback, future_arg], @@ -703,11 +745,16 @@ pub(crate) mod _asyncio { } #[pygetset(setter)] - fn set__cancel_message(zelf: &Py, value: PySetterValue) { - match value { - PySetterValue::Assign(v) => *zelf.fut_cancel_msg.write() = Some(v), - PySetterValue::Delete => *zelf.fut_cancel_msg.write() = None, - } + fn set__cancel_message( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let PySetterValue::Assign(value) = value else { + return Err(cancel_message_delete_error(zelf.as_object(), vm)); + }; + *zelf.fut_cancel_msg.write() = Some(value); + Ok(()) } #[pygetset] @@ -953,13 +1000,18 @@ pub(crate) mod _asyncio { #[pyattr] #[pyclass(name = "FutureIter", module = "_asyncio", traverse)] - #[derive(Debug, PyPayload)] + #[derive(Debug, Default, PyPayload)] struct PyFutureIter { future: PyRwLock>, } - #[pyclass(with(IterNext, Iterable))] + #[pyclass(with(IterNext, Iterable), flags(HEAPTYPE))] impl PyFutureIter { + #[pyslot] + fn slot_alloc(cls: PyTypeRef, nitems: usize, vm: &VirtualMachine) -> PyResult { + alloc_default::(cls, nitems, vm) + } + #[pymethod] fn send(zelf: &Py, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult { let future = zelf.future.read().clone(); @@ -1139,8 +1191,8 @@ pub(crate) mod _asyncio { struct TaskInitArgs { #[pyarg(any)] coro: PyObjectRef, - #[pyarg(named, name = "loop", optional)] - loop_: Option, + #[pyarg(named, optional)] + r#loop: Option, #[pyarg(named, optional)] name: Option, #[pyarg(named, optional)] @@ -1183,6 +1235,13 @@ pub(crate) mod _asyncio { )] impl PyTask { fn py_init(zelf: &Py, args: TaskInitArgs, vm: &VirtualMachine) -> PyResult<()> { + if zelf.base.fut_loop.read().is_some() { + return Err(vm.new_runtime_error(wtf8_concat!( + zelf.class().fully_qualified_name(vm)?, + " object is already initialized" + ))); + } + // Validate coroutine if !is_coroutine(args.coro.clone(), vm)? { return Err(vm.new_type_error(format!( @@ -1192,7 +1251,7 @@ pub(crate) mod _asyncio { } // Get the event loop - let loop_obj = match args.loop_ { + let loop_obj = match args.r#loop { Some(l) => l, None => get_running_loop(vm) .map_err(|_| vm.new_runtime_error("no current event loop"))?, @@ -1217,8 +1276,18 @@ pub(crate) mod _asyncio { // Get or create context let context = match args.context { - Some(c) => c, - None => get_copy_context(vm)?, + Some(c) if !vm.is_none(&c) => { + if !c.class().is(PyContext::class(&vm.ctx)) { + zelf.task_log_destroy_pending + .store(false, Ordering::Relaxed); + return Err(vm.new_type_error(wtf8_concat!( + "a contextvars.Context was expected, got ", + c.class().fully_qualified_name(vm)? + ))); + } + c + } + _ => get_copy_context(vm)?, }; *zelf.task_context.write() = Some(context); @@ -1360,192 +1429,20 @@ pub(crate) mod _asyncio { args: AddDoneCallbackArgs, vm: &VirtualMachine, ) -> PyResult<()> { - if zelf.base.fut_loop.read().is_none() { - return Err(vm.new_runtime_error("Future object is not initialized.")); - } - let ctx = match args.context { - Some(c) => c, - None => get_copy_context(vm)?, - }; - - if zelf.base.fut_state.load() != FutureState::Pending { - Self::call_soon_with_context(&zelf, args.func, Some(ctx), vm)?; - } else if zelf.base.fut_callback0.read().is_none() { - *zelf.base.fut_callback0.write() = Some(args.func); - *zelf.base.fut_context0.write() = Some(ctx); - } else { - let tuple = vm.ctx.new_tuple(vec![args.func, ctx]); - let mut callbacks = zelf.base.fut_callbacks.write(); - if callbacks.is_none() { - *callbacks = Some(vm.ctx.new_list(vec![tuple.into()]).into()); - } else { - let list = callbacks.as_ref().unwrap(); - vm.call_method(list, "append", (tuple,))?; - } - } - Ok(()) + zelf.base.add_done_callback_impl(zelf.as_object(), args, vm) } #[pymethod] fn remove_done_callback( zelf: &Py, - RemoveDoneCallbackArgs { func }: RemoveDoneCallbackArgs, + RemoveDoneCallbackArgs { r#fn: func }: RemoveDoneCallbackArgs, vm: &VirtualMachine, - ) -> PyResult { - if zelf.base.fut_loop.read().is_none() { - return Err(vm.new_runtime_error("Future object is not initialized.")); - } - let mut cleared_callback0 = 0usize; - - // Check fut_callback0 first - // Clone to release lock before comparison (which may run Python code) - let cb0 = zelf.base.fut_callback0.read().clone(); - if let Some(cb0) = cb0 { - let cmp = vm.identical_or_equal(&cb0, &func)?; - if cmp { - *zelf.base.fut_callback0.write() = None; - *zelf.base.fut_context0.write() = None; - cleared_callback0 = 1; - } - } - - // Check if fut_callbacks exists - let callbacks = zelf.base.fut_callbacks.read().clone(); - let callbacks = match callbacks { - Some(c) => c, - None => return Ok(cleared_callback0), - }; - - let list: PyListRef = callbacks.downcast().unwrap(); - let len = list.borrow_vec().len(); - - if len == 0 { - *zelf.base.fut_callbacks.write() = None; - return Ok(cleared_callback0); - } - - // Special case for single callback - if len == 1 { - let item = list.borrow_vec().first().cloned(); - if let Some(item) = item { - let tuple: &Py = item.downcast_ref().unwrap(); - let cb = tuple.as_slice().first().unwrap().clone(); - let cmp = vm.identical_or_equal(&cb, &func)?; - if cmp { - *zelf.base.fut_callbacks.write() = None; - return Ok(1 + cleared_callback0); - } - } - return Ok(cleared_callback0); - } - - // Multiple callbacks - iterate with index, checking validity each time - // to handle evil comparisons - let mut new_callbacks = Vec::with_capacity(len); - let mut i = 0usize; - let mut removed = 0usize; - - loop { - // Re-check fut_callbacks on each iteration (evil code may have cleared it) - let callbacks = zelf.base.fut_callbacks.read().clone(); - let callbacks = match callbacks { - Some(c) => c, - None => break, - }; - let list: PyListRef = callbacks.downcast().unwrap(); - let current_len = list.borrow_vec().len(); - if i >= current_len { - break; - } - - // Get item and release lock before comparison - let item = list.borrow_vec().get(i).cloned(); - let item = match item { - Some(item) => item, - None => break, - }; - - let tuple: &Py = item.downcast_ref().unwrap(); - let cb = tuple.as_slice().first().unwrap().clone(); - let cmp = vm.identical_or_equal(&cb, &func)?; - - if !cmp { - new_callbacks.push(item); - } else { - removed += 1; - } - i += 1; - } - - // Update fut_callbacks with filtered list - if new_callbacks.is_empty() { - *zelf.base.fut_callbacks.write() = None; - } else { - *zelf.base.fut_callbacks.write() = Some(vm.ctx.new_list(new_callbacks).into()); - } - - Ok(removed + cleared_callback0) + ) -> PyResult { + zelf.base.remove_done_callback_impl(&func, vm) } fn schedule_callbacks(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { - // Collect all callbacks first to avoid holding locks during callback execution - // This prevents deadlock when callbacks access the future's properties - let mut callbacks_to_call: Vec<(PyObjectRef, Option)> = Vec::new(); - - // Take callback0 - release lock before collecting from list - let cb0 = zelf.base.fut_callback0.write().take(); - let ctx0 = zelf.base.fut_context0.write().take(); - if let Some(cb) = cb0 { - callbacks_to_call.push((cb, ctx0)); - } - - // Take callbacks list and collect items - let callbacks_list = zelf.base.fut_callbacks.write().take(); - if let Some(callbacks) = callbacks_list - && let Ok(list) = callbacks.downcast::() - { - // Clone the items while holding the list lock, then release - let items: Vec<_> = list.borrow_vec().iter().cloned().collect(); - for item in items { - if let Some(tuple) = item.downcast_ref::() - && let (Some(cb), Some(ctx)) = - (tuple.as_slice().first(), tuple.as_slice().get(1)) - { - callbacks_to_call.push((cb.clone(), Some(ctx.clone()))); - } - } - } - - // Now call all callbacks without holding any locks - for (cb, ctx) in callbacks_to_call { - Self::call_soon_with_context(zelf, cb, ctx, vm)?; - } - - Ok(()) - } - - fn call_soon_with_context( - zelf: &Py, - callback: PyObjectRef, - context: Option, - vm: &VirtualMachine, - ) -> PyResult<()> { - let loop_obj = zelf.base.fut_loop.read().clone(); - if let Some(loop_obj) = loop_obj { - // call_soon(callback, *args, context=context) - // callback receives the task as its argument - let task_arg: PyObjectRef = zelf.to_owned().into(); - let args = if let Some(ctx) = context { - FuncArgs::new( - vec![callback, task_arg], - KwArgs::new(core::iter::once((Wtf8Buf::from("context"), ctx)).collect()), - ) - } else { - FuncArgs::new(vec![callback, task_arg], KwArgs::default()) - }; - vm.call_method(&loop_obj, "call_soon", args)?; - } - Ok(()) + zelf.base.schedule_callbacks_impl(zelf.as_object(), vm) } #[pymethod] @@ -1830,11 +1727,16 @@ pub(crate) mod _asyncio { } #[pygetset(setter)] - fn set__cancel_message(zelf: &Py, value: PySetterValue) { - match value { - PySetterValue::Assign(v) => *zelf.base.fut_cancel_msg.write() = Some(v), - PySetterValue::Delete => *zelf.base.fut_cancel_msg.write() = None, - } + fn set__cancel_message( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let PySetterValue::Assign(value) = value else { + return Err(cancel_message_delete_error(zelf.as_object(), vm)); + }; + *zelf.base.fut_cancel_msg.write() = Some(value); + Ok(()) } #[pygetset] @@ -2019,7 +1921,7 @@ pub(crate) mod _asyncio { // Swap current task - save previous task let prev_task = _swap_current_task( LoopTaskArgs { - loop_: loop_obj.clone(), + r#loop: loop_obj.clone(), task: task_obj.clone(), }, vm, @@ -2043,7 +1945,25 @@ pub(crate) mod _asyncio { match ctx.downcast::() { Ok(ctx) => { // Only exit a context that was actually entered. - PyContext::enter(&ctx, vm)?; + if let Err(error) = PyContext::enter(&ctx, vm) { + zelf.task_log_destroy_pending + .store(false, Ordering::Relaxed); + let _ = _swap_current_task( + LoopTaskArgs { + r#loop: loop_obj, + task: prev_task, + }, + vm, + ); + let _ = _unregister_eager_task( + TaskArg { + task: task_obj.clone(), + }, + vm, + ); + let _ = _unregister_task(TaskArg { task: task_obj }, vm); + return Err(error); + } let result = vm.call_method(&c, "send", (vm.ctx.none(),)); PyContext::exit(&ctx, vm)?; result @@ -2062,7 +1982,7 @@ pub(crate) mod _asyncio { None => { let _ = _swap_current_task( LoopTaskArgs { - loop_: loop_obj, + r#loop: loop_obj, task: prev_task, }, vm, @@ -2075,7 +1995,7 @@ pub(crate) mod _asyncio { // Restore previous task let _ = _swap_current_task( LoopTaskArgs { - loop_: loop_obj, + r#loop: loop_obj, task: prev_task, }, vm, @@ -2144,7 +2064,7 @@ pub(crate) mod _asyncio { // Enter task - register as current task _enter_task( LoopTaskArgs { - loop_: loop_obj.clone(), + r#loop: loop_obj.clone(), task: task.to_owned(), }, vm, @@ -2189,7 +2109,7 @@ pub(crate) mod _asyncio { // Leave task - unregister as current task (must happen even on error) let _ = _leave_task( LoopTaskArgs { - loop_: loop_obj, + r#loop: loop_obj, task: task.to_owned(), }, vm, @@ -2355,23 +2275,9 @@ pub(crate) mod _asyncio { task.base.fut_state.store(FutureState::Finished); *task.base.fut_result.write() = Some(result); } - PyTask::schedule_callbacks(task, vm)?; - _unregister_task( - TaskArg { - task: task.to_owned().into(), - }, - vm, - )?; } else if is_cancelled_error(&exc, vm) { task.base.fut_state.store(FutureState::Cancelled); *task.base.fut_cancelled_exc.write() = Some(exc.clone().into()); - PyTask::schedule_callbacks(task, vm)?; - _unregister_task( - TaskArg { - task: task.to_owned().into(), - }, - vm, - )?; } else { task.base.fut_state.store(FutureState::Finished); // Save the original traceback for later restoration @@ -2379,14 +2285,14 @@ pub(crate) mod _asyncio { *task.base.fut_exception_tb.write() = tb; *task.base.fut_exception.write() = Some(exc.clone().into()); task.base.fut_log_tb.store(true, Ordering::Relaxed); - PyTask::schedule_callbacks(task, vm)?; - _unregister_task( - TaskArg { - task: task.to_owned().into(), - }, - vm, - )?; } + PyTask::schedule_callbacks(task, vm)?; + _unregister_task( + TaskArg { + task: task.to_owned().into(), + }, + vm, + )?; // Re-raise KeyboardInterrupt and SystemExit after storing in task if should_reraise { @@ -2565,13 +2471,13 @@ pub(crate) mod _asyncio { #[derive(FromArgs)] struct SetRunningLoopArgs { - #[pyarg(positional, name = "loop")] - loop_: Option, + #[pyarg(positional)] + r#loop: Option, } #[pyfunction] fn _set_running_loop(args: SetRunningLoopArgs, vm: &VirtualMachine) { - *vm.asyncio_running_loop.borrow_mut() = args.loop_; + *vm.asyncio_running_loop.borrow_mut() = args.r#loop; } #[pyfunction] @@ -2601,7 +2507,7 @@ pub(crate) mod _asyncio { #[pyfunction] fn current_task(args: LoopArg, vm: &VirtualMachine) -> PyResult { - let loop_obj = match args.loop_ { + let loop_obj = match args.r#loop { Some(l) if !vm.is_none(&l) => l, _ => { // When loop is None or not provided, use the running loop @@ -2644,7 +2550,7 @@ pub(crate) mod _asyncio { #[pyfunction] fn all_tasks(args: LoopArg, vm: &VirtualMachine) -> PyResult { - let loop_obj = match args.loop_ { + let loop_obj = match args.r#loop { Some(l) if !vm.is_none(&l) => l, _ => get_running_loop(vm)?, }; @@ -2685,8 +2591,8 @@ pub(crate) mod _asyncio { #[derive(FromArgs)] struct RemoveDoneCallbackArgs { - #[pyarg(positional, name = "fn")] - func: PyObjectRef, + #[pyarg(positional)] + r#fn: PyObjectRef, } #[derive(FromArgs)] @@ -2697,8 +2603,8 @@ pub(crate) mod _asyncio { #[derive(FromArgs)] struct LoopTaskArgs { - #[pyarg(any, name = "loop")] - loop_: PyObjectRef, + #[pyarg(any)] + r#loop: PyObjectRef, #[pyarg(any)] task: PyObjectRef, } @@ -2735,7 +2641,10 @@ pub(crate) mod _asyncio { #[pyfunction] fn _enter_task( - LoopTaskArgs { loop_, task }: LoopTaskArgs, + LoopTaskArgs { + r#loop: loop_, + task, + }: LoopTaskArgs, vm: &VirtualMachine, ) -> PyResult<()> { // Per-thread check, matching CPython's ts->asyncio_running_task @@ -2763,7 +2672,10 @@ pub(crate) mod _asyncio { #[pyfunction] fn _leave_task( - LoopTaskArgs { loop_, task }: LoopTaskArgs, + LoopTaskArgs { + r#loop: loop_, + task, + }: LoopTaskArgs, vm: &VirtualMachine, ) -> PyResult<()> { // Per-thread check, matching CPython's ts->asyncio_running_task @@ -2791,7 +2703,10 @@ pub(crate) mod _asyncio { #[pyfunction] fn _swap_current_task( - LoopTaskArgs { loop_, task }: LoopTaskArgs, + LoopTaskArgs { + r#loop: loop_, + task, + }: LoopTaskArgs, vm: &VirtualMachine, ) -> PyObjectRef { // Per-thread swap, matching CPython's swap_current_task @@ -2839,8 +2754,12 @@ pub(crate) mod _asyncio { waiter: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - // Only operate on native Future/Task objects (including subclasses). + // Both arguments must be native Future/Task objects (including subclasses). // Non-native objects are silently ignored. + if waiter.downcast_ref::().is_none() && waiter.downcast_ref::().is_none() + { + return Ok(()); + } if let Some(task) = fut.downcast_ref::() { return task.base.awaited_by_add(waiter, vm); } @@ -2856,8 +2775,12 @@ pub(crate) mod _asyncio { waiter: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - // Only operate on native Future/Task objects (including subclasses). + // Both arguments must be native Future/Task objects (including subclasses). // Non-native objects are silently ignored. + if waiter.downcast_ref::().is_none() && waiter.downcast_ref::().is_none() + { + return Ok(()); + } if let Some(task) = fut.downcast_ref::() { return task.base.awaited_by_discard(&waiter, vm); } @@ -2871,13 +2794,18 @@ pub(crate) mod _asyncio { #[pyattr] #[pyclass(name, traverse)] - #[derive(Debug, PyPayload)] + #[derive(Debug, Default, PyPayload)] struct TaskStepMethWrapper { task: PyRwLock>, } - #[pyclass(with(Callable, Representable))] + #[pyclass(with(Callable, Representable), flags(HEAPTYPE))] impl TaskStepMethWrapper { + #[pyslot] + fn slot_alloc(cls: PyTypeRef, nitems: usize, vm: &VirtualMachine) -> PyResult { + alloc_default::(cls, nitems, vm) + } + fn new(task: PyObjectRef) -> Self { Self { task: PyRwLock::new(Some(task)), diff --git a/crates/stdlib/src/_datetime.rs b/crates/stdlib/src/_datetime.rs index e424d903b1d..6b989a7a20a 100644 --- a/crates/stdlib/src/_datetime.rs +++ b/crates/stdlib/src/_datetime.rs @@ -9,6 +9,8 @@ pub(crate) use _datetime::{PyTzInfo, datetime_type, module_def, timedelta_from_s #[pymodule] mod _datetime { + #[cfg(windows)] + use crate::vm::convert::ToPyException; use crate::vm::{ AsObject, Py, PyObject, PyObjectCell, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, @@ -18,7 +20,9 @@ mod _datetime { hash::PyHash, wtf8::{CodePoint, Wtf8Buf}, }, - function::{ArgumentError, FromArgs, FuncArgs, OptionalArg, Param, PyComparisonValue}, + function::{ + ArgCInt, ArgumentError, FromArgs, FuncArgs, OptionalArg, Param, PyComparisonValue, + }, protocol::{PyNumber, PyNumberMethods}, types::{AsNumber, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; @@ -562,19 +566,19 @@ mod _datetime { #[derive(FromArgs)] pub(super) struct DeltaArgs { - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "0")] days: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "0")] seconds: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "0")] microseconds: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "0")] milliseconds: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "0")] minutes: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "0")] hours: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "0")] weeks: OptionalArg, } @@ -1129,9 +1133,7 @@ mod _datetime { arg: &PyObject, vm: &VirtualMachine, ) -> PyResult { - Ok(call_utcoffset(tzinfo, arg, vm)? - .map(|offset| format_offset(&offset, sep)) - .unwrap_or_default()) + Ok(call_utcoffset(tzinfo, arg, vm)?.map_or_default(|offset| format_offset(&offset, sep))) } fn append_keyword_tzinfo( @@ -1525,7 +1527,8 @@ mod _datetime { vals: &mut [i32; 4], tzoffset: &mut i32, tzmicrosecond: &mut i32, - ) -> i32 { + vm: &VirtualMachine, + ) -> PyResult { let p_end = start + len; let mut tzinfo_pos = start; loop { @@ -1540,18 +1543,18 @@ mod _datetime { } let rv = parse_hh_mm_ss_ff(s, start, tzinfo_pos, vals); if rv < 0 { - return rv; + return Ok(rv); } else if tzinfo_pos == p_end { - return if rv == 1 { -5 } else { 0 }; + return Ok(if rv == 1 { -5 } else { 0 }); } if byte_at(s, tzinfo_pos) == b'Z' { *tzoffset = 0; *tzmicrosecond = 0; - return if byte_at(s, tzinfo_pos + 1) != 0 { + return Ok(if byte_at(s, tzinfo_pos + 1) != 0 { -5 } else { 1 - }; + }); } let tzsign = if byte_at(s, tzinfo_pos) == b'-' { -1 @@ -1560,9 +1563,10 @@ mod _datetime { }; let mut tz = [0; 4]; let rv = parse_hh_mm_ss_ff(s, tzinfo_pos + 1, p_end, &mut tz); + check_time_args(tz[0], tz[1], tz[2], tz[3], 0, vm)?; *tzoffset = tzsign * (tz[0] * 3600 + tz[1] * 60 + tz[2]); *tzmicrosecond = tzsign * tz[3]; - if rv != 0 { -5 } else { 1 } + Ok(if rv != 0 { -5 } else { 1 }) } fn tzinfo_from_isoformat_results( @@ -1720,25 +1724,36 @@ mod _datetime { } #[derive(FromArgs)] - struct DateArgs { + pub(super) struct DateArgs { #[pyarg(any)] - year: i32, + year: ArgCInt, #[pyarg(any)] - month: i32, + month: ArgCInt, #[pyarg(any)] - day: i32, + day: ArgCInt, } impl Constructor for PyDate { - type Args = FuncArgs; + type Args = DateArgs; - fn py_new(_cls: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if args.args.len() == 1 && let Some(state) = pickle_state(&args.args[0], 4, 2, month_is_sane, "date", vm)? { - return Ok(Self::from_state(&state)); + let payload = Self::from_state(&state); + drop(args); + return payload.into_ref_with_type(vm, cls).map(Into::into); } - let DateArgs { year, month, day } = args.bind(vm)?; + let args = args.bind_for(vm, "date")?; + Self::py_new(&cls, args, vm)? + .into_ref_with_type(vm, cls) + .map(Into::into) + } + + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + let year = args.year.into_primitive(); + let month = args.month.into_primitive(); + let day = args.day.into_primitive(); check_date_args(year, month, day, vm)?; Ok(Self::new(year, month, day)) } @@ -1746,18 +1761,15 @@ mod _datetime { /// `_PyTime_ObjectToTime_t` with floor rounding. fn object_to_time_t(obj: &PyObject, vm: &VirtualMachine) -> PyResult { - if let Some(float) = obj.downcast_ref::() { - let d = float.to_f64(); - if d.is_nan() { - return Err(vm.new_value_error("Invalid value NaN (not a number)")); - } - let d = d.floor(); - if !(-9.223_372_036_854_776e18..9.223_372_036_854_776e18).contains(&d) { - return Err(time_t_overflow(vm)); - } - return Ok(d as i64); + if obj.number().is_index() { + return long_to_time_t(obj, vm); } - long_to_time_t(obj, vm) + let d = timestamp_as_double(obj, vm)?; + let d = d.floor(); + if !(-9.223_372_036_854_776e18..9.223_372_036_854_776e18).contains(&d) { + return Err(time_t_overflow(vm)); + } + Ok(d as i64) } fn time_t_overflow(vm: &VirtualMachine) -> crate::vm::builtins::PyBaseExceptionRef { @@ -1770,29 +1782,37 @@ mod _datetime { int.as_bigint().to_i64().ok_or_else(|| time_t_overflow(vm)) } + fn timestamp_as_double(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + let d = match obj.downcast_ref::() { + Some(float) => float.to_f64(), + None => obj.try_float(vm)?.to_f64(), + }; + if d.is_nan() { + return Err(vm.new_value_error("Invalid value NaN (not a number)")); + } + Ok(d) + } + /// `_PyTime_ObjectToTimeval` with half-even rounding: whole seconds and microseconds. fn object_to_timeval(obj: &PyObject, vm: &VirtualMachine) -> PyResult<(i64, i32)> { - if let Some(float) = obj.downcast_ref::() { - let d = float.to_f64(); - if d.is_nan() { - return Err(vm.new_value_error("Invalid value NaN (not a number)")); - } - let mut intpart = d.trunc(); - let mut floatpart = (d - intpart) * 1e6; - floatpart = round_half_even(floatpart); - if floatpart >= 1e6 { - floatpart -= 1e6; - intpart += 1.0; - } else if floatpart < 0.0 { - floatpart += 1e6; - intpart -= 1.0; - } - if !(-9.223_372_036_854_776e18..9.223_372_036_854_776e18).contains(&intpart) { - return Err(time_t_overflow(vm)); - } - return Ok((intpart as i64, floatpart as i32)); + if obj.number().is_index() { + return Ok((long_to_time_t(obj, vm)?, 0)); + } + let d = timestamp_as_double(obj, vm)?; + let mut intpart = d.trunc(); + let mut floatpart = (d - intpart) * 1e6; + floatpart = round_half_even(floatpart); + if floatpart >= 1e6 { + floatpart -= 1e6; + intpart += 1.0; + } else if floatpart < 0.0 { + floatpart += 1e6; + intpart -= 1.0; + } + if !(-9.223_372_036_854_776e18..9.223_372_036_854_776e18).contains(&intpart) { + return Err(time_t_overflow(vm)); } - Ok((long_to_time_t(obj, vm)?, 0)) + Ok((intpart as i64, floatpart as i32)) } fn round_half_even(x: f64) -> f64 { @@ -1819,12 +1839,16 @@ mod _datetime { fn platform_time(t: i64, local: bool, vm: &VirtualMachine) -> PyResult { #[cfg(any(unix, windows))] { - let t_c = libc::time_t::try_from(t).map_err(|_| time_t_overflow(vm))?; + let t_c = + rustpython_host_env::time::TimeT::try_from(t).map_err(|_| time_t_overflow(vm))?; let tm = if local { rustpython_host_env::time::localtime_from_timestamp(t_c) } else { rustpython_host_env::time::gmtime_from_timestamp(t_c) }; + #[cfg(windows)] + let tm = tm.map_err(|error| error.to_pyexception(vm))?; + #[cfg(unix)] let Some(tm) = tm else { return Err(vm.new_last_errno_error()); }; @@ -1947,7 +1971,8 @@ mod _datetime { } #[pyclassmethod] - fn fromordinal(cls: PyTypeRef, ordinal: i32, vm: &VirtualMachine) -> PyResult { + fn fromordinal(cls: PyTypeRef, ordinal: ArgCInt, vm: &VirtualMachine) -> PyResult { + let ordinal = ordinal.into_primitive(); if ordinal < 1 { return Err(vm.new_value_error("ordinal must be >= 1")); } @@ -1956,8 +1981,8 @@ mod _datetime { } #[pyclassmethod] - fn fromisoformat(cls: PyTypeRef, object: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let dtstr = object; + fn fromisoformat(cls: PyTypeRef, string: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let dtstr = string; let Some(s) = dtstr.downcast_ref::() else { return Err(vm.new_type_error("fromisoformat: argument must be str")); }; @@ -1979,16 +2004,9 @@ mod _datetime { #[pyclassmethod] fn fromisocalendar(cls: PyTypeRef, args: IsoCalendarArgs, vm: &VirtualMachine) -> PyResult { - let to_i32 = |obj: PyObjectRef| -> PyResult { - obj.try_into_value::(vm).map_err(|err| { - if err.fast_isinstance(vm.ctx.exceptions.overflow_error) { - vm.new_value_error("ISO calendar component out of range") - } else { - err - } - }) - }; - let (year, week, day) = (to_i32(args.year)?, to_i32(args.week)?, to_i32(args.day)?); + let year = args.year.into_primitive(); + let week = args.week.into_primitive(); + let day = args.day.into_primitive(); match iso_to_ymd(year, week, day) { Ok((y, m, d)) => new_date_subclass(y, m, d, &cls, vm), Err(-4) => Err( @@ -2024,8 +2042,8 @@ mod _datetime { } #[pymethod] - fn __format__(zelf: PyObjectRef, spec: PyObjectRef, vm: &VirtualMachine) -> PyResult { - object_format(&zelf, spec, vm) + fn __format__(zelf: PyObjectRef, format: PyObjectRef, vm: &VirtualMachine) -> PyResult { + object_format(&zelf, format, vm) } #[pymethod] @@ -2080,9 +2098,9 @@ mod _datetime { #[pymethod] fn replace(zelf: &Py, args: DateReplaceArgs, vm: &VirtualMachine) -> PyResult { new_date_subclass( - args.year.unwrap_or_else(|| zelf.y()), - args.month.unwrap_or_else(|| zelf.m()), - args.day.unwrap_or_else(|| zelf.d()), + replacement_int(args.year, zelf.y()), + replacement_int(args.month, zelf.m()), + replacement_int(args.day, zelf.d()), zelf.class(), vm, ) @@ -2127,11 +2145,11 @@ mod _datetime { #[derive(FromArgs)] struct IsoCalendarArgs { #[pyarg(any)] - year: PyObjectRef, + year: ArgCInt, #[pyarg(any)] - week: PyObjectRef, + week: ArgCInt, #[pyarg(any)] - day: PyObjectRef, + day: ArgCInt, } /// `**changes` in the text signature. Binding still accepts the same @@ -2141,6 +2159,9 @@ mod _datetime { } impl FromArgs for ReplaceChanges { + // Forward every argument to replace(), which owns validation and diagnostics. + const BINDING_PARAMS: Option<&'static [Param]> = FuncArgs::BINDING_PARAMS; + const PARAMS: Option<&'static [Param]> = Some(&[Param::var_keyword("changes")]); fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result { @@ -2150,14 +2171,18 @@ mod _datetime { } } + fn replacement_int(arg: OptionalArg, old: i32) -> i32 { + arg.into_option().map_or(old, ArgCInt::into_primitive) + } + #[derive(FromArgs)] struct DateReplaceArgs { #[pyarg(any, optional, py_default = "unchanged")] - year: OptionalArg, + year: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - month: OptionalArg, + month: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - day: OptionalArg, + day: OptionalArg, } impl PyDate { @@ -2557,7 +2582,10 @@ mod _datetime { } } - #[pyclass(with(Constructor, Comparable, Hashable, Representable))] + #[pyclass( + with(Constructor, Comparable, Hashable, Representable), + flags(IMMUTABLETYPE) + )] impl PyTimeZone { #[pymethod] fn tzname(zelf: &Py, object: PyObjectRef, vm: &VirtualMachine) -> PyResult { @@ -2769,19 +2797,19 @@ mod _datetime { } #[derive(FromArgs)] - struct TimeArgs { + pub(super) struct TimeArgs { #[pyarg(any, default = 0)] - hour: i32, + hour: ArgCInt, #[pyarg(any, default = 0)] - minute: i32, + minute: ArgCInt, #[pyarg(any, default = 0)] - second: i32, + second: ArgCInt, #[pyarg(any, default = 0)] - microsecond: i32, - #[pyarg(any, optional)] - tzinfo: OptionalArg, + microsecond: ArgCInt, + #[pyarg(any, default = None)] + tzinfo: Option, #[pyarg(named, default = 0)] - fold: i32, + fold: ArgCInt, } fn pickle_tzinfo( @@ -2800,9 +2828,9 @@ mod _datetime { } impl Constructor for PyTime { - type Args = FuncArgs; + type Args = TimeArgs; - fn py_new(_cls: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if (1..=2).contains(&args.args.len()) && let Some(state) = pickle_state(&args.args[0], 6, 0, |hour| (hour & 0x7f) < 24, "time", vm)? @@ -2810,51 +2838,57 @@ mod _datetime { let tzinfo = pickle_tzinfo(args.args.get(1), vm)?; let fold = (state[0] & 0x80) != 0; let us = i32::from(state[3]) << 16 | i32::from(state[4]) << 8 | i32::from(state[5]); - return Ok(Self::new( + let payload = Self::new( i32::from(state[0] & 0x7f), i32::from(state[1]), i32::from(state[2]), us, tzinfo, i32::from(fold), - )); + ); + drop(args); + return payload.into_ref_with_type(vm, cls).map(Into::into); } - let a: TimeArgs = args.bind(vm)?; - let tzinfo = a.tzinfo.into_option().and_then(|tz| tzinfo_arg(tz, vm)); - check_time_args(a.hour, a.minute, a.second, a.microsecond, a.fold, vm)?; + let args = args.bind(vm)?; + Self::py_new(&cls, args, vm)? + .into_ref_with_type(vm, cls) + .map(Into::into) + } + + fn py_new(_cls: &Py, a: Self::Args, vm: &VirtualMachine) -> PyResult { + let tzinfo = a.tzinfo.and_then(|tz| tzinfo_arg(tz, vm)); + let hour = a.hour.into_primitive(); + let minute = a.minute.into_primitive(); + let second = a.second.into_primitive(); + let microsecond = a.microsecond.into_primitive(); + let fold = a.fold.into_primitive(); + check_time_args(hour, minute, second, microsecond, fold, vm)?; if let Some(tz) = &tzinfo { check_tzinfo_subclass(tz, vm)?; } - Ok(Self::new( - a.hour, - a.minute, - a.second, - a.microsecond, - tzinfo, - a.fold, - )) + Ok(Self::new(hour, minute, second, microsecond, tzinfo, fold)) } } #[derive(FromArgs)] struct TimeReplaceArgs { #[pyarg(any, optional, py_default = "unchanged")] - hour: OptionalArg, + hour: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - minute: OptionalArg, + minute: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - second: OptionalArg, + second: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - microsecond: OptionalArg, + microsecond: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] tzinfo: OptionalArg, #[pyarg(named, optional, py_default = "unchanged")] - fold: OptionalArg, + fold: OptionalArg, } #[derive(FromArgs)] struct TimeIsoformatArgs { - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "'auto'")] timespec: OptionalArg, } @@ -2955,8 +2989,8 @@ mod _datetime { } #[pymethod] - fn __format__(zelf: PyObjectRef, spec: PyObjectRef, vm: &VirtualMachine) -> PyResult { - object_format(&zelf, spec, vm) + fn __format__(zelf: PyObjectRef, format: PyObjectRef, vm: &VirtualMachine) -> PyResult { + object_format(&zelf, format, vm) } #[pymethod] @@ -2988,12 +3022,12 @@ mod _datetime { OptionalArg::Missing => zelf.tzinfo.clone(), }; new_time_subclass( - args.hour.unwrap_or_else(|| i32::from(zelf.hour)), - args.minute.unwrap_or_else(|| i32::from(zelf.minute)), - args.second.unwrap_or_else(|| i32::from(zelf.second)), - args.microsecond.unwrap_or(zelf.microsecond as i32), + replacement_int(args.hour, i32::from(zelf.hour)), + replacement_int(args.minute, i32::from(zelf.minute)), + replacement_int(args.second, i32::from(zelf.second)), + replacement_int(args.microsecond, zelf.microsecond as i32), tzinfo, - args.fold.unwrap_or_else(|| i32::from(zelf.fold)), + replacement_int(args.fold, i32::from(zelf.fold)), zelf.class(), vm, ) @@ -3005,8 +3039,8 @@ mod _datetime { } #[pyclassmethod] - fn fromisoformat(cls: PyTypeRef, object: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let tstr = object; + fn fromisoformat(cls: PyTypeRef, string: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let tstr = string; let Some(s) = tstr.downcast_ref::() else { return Err(vm.new_type_error("fromisoformat: argument must be str")); }; @@ -3018,7 +3052,8 @@ mod _datetime { let len = bytes.len() - start; let mut vals = [0; 4]; let (mut tzoffset, mut tzusec) = (0, 0); - let rv = parse_isoformat_time(bytes, start, len, &mut vals, &mut tzoffset, &mut tzusec); + let rv = + parse_isoformat_time(bytes, start, len, &mut vals, &mut tzoffset, &mut tzusec, vm)?; if rv < 0 { return Err(invalid_isoformat(&tstr, vm)?); } @@ -3486,8 +3521,7 @@ mod _datetime { let tm = platform_time(timet, local_tm, vm)?; let second = tm.second.min(59); let mut fold = 0; - let skip_probe = cfg!(windows) && timet - MAX_FOLD_SECONDS <= 0; - if tzinfo.is_none() && local_tm && !skip_probe { + if tzinfo.is_none() && local_tm { let result_seconds = utc_to_seconds(tm.year, tm.month, tm.day, tm.hour, tm.minute, second, vm)?; let probe_seconds = local(EPOCH_SECONDS + timet - MAX_FOLD_SECONDS, vm)?; @@ -3549,31 +3583,31 @@ mod _datetime { } #[derive(FromArgs)] - struct DateTimeArgs { + pub(super) struct DateTimeArgs { #[pyarg(any)] - year: i32, + year: ArgCInt, #[pyarg(any)] - month: i32, + month: ArgCInt, #[pyarg(any)] - day: i32, + day: ArgCInt, #[pyarg(any, default = 0)] - hour: i32, + hour: ArgCInt, #[pyarg(any, default = 0)] - minute: i32, + minute: ArgCInt, #[pyarg(any, default = 0)] - second: i32, + second: ArgCInt, #[pyarg(any, default = 0)] - microsecond: i32, - #[pyarg(any, optional)] - tzinfo: OptionalArg, + microsecond: ArgCInt, + #[pyarg(any, default = None)] + tzinfo: Option, #[pyarg(named, default = 0)] - fold: i32, + fold: ArgCInt, } impl Constructor for PyDateTime { - type Args = FuncArgs; + type Args = DateTimeArgs; - fn py_new(_cls: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if (1..=2).contains(&args.args.len()) && let Some(state) = pickle_state( &args.args[0], @@ -3588,7 +3622,7 @@ mod _datetime { let fold = (state[2] & 0x80) != 0; let date = PyDate::from_state(&[state[0], state[1], state[2] & 0x7f, state[3]]); let us = i32::from(state[7]) << 16 | i32::from(state[8]) << 8 | i32::from(state[9]); - return Ok(Self::new( + let payload = Self::new( date.y(), date.m(), date.d(), @@ -3598,41 +3632,57 @@ mod _datetime { us, tzinfo, i32::from(fold), - )); + ); + drop(args); + return payload.into_ref_with_type(vm, cls).map(Into::into); } - let a: DateTimeArgs = args.bind(vm)?; - let tzinfo = a.tzinfo.into_option().and_then(|tz| tzinfo_arg(tz, vm)); - check_date_args(a.year, a.month, a.day, vm)?; - check_time_args(a.hour, a.minute, a.second, a.microsecond, a.fold, vm)?; + let args = args.bind_for(vm, "datetime")?; + Self::py_new(&cls, args, vm)? + .into_ref_with_type(vm, cls) + .map(Into::into) + } + + fn py_new(_cls: &Py, a: Self::Args, vm: &VirtualMachine) -> PyResult { + let tzinfo = a.tzinfo.and_then(|tz| tzinfo_arg(tz, vm)); + let year = a.year.into_primitive(); + let month = a.month.into_primitive(); + let day = a.day.into_primitive(); + let hour = a.hour.into_primitive(); + let minute = a.minute.into_primitive(); + let second = a.second.into_primitive(); + let microsecond = a.microsecond.into_primitive(); + let fold = a.fold.into_primitive(); + check_date_args(year, month, day, vm)?; + check_time_args(hour, minute, second, microsecond, fold, vm)?; if let Some(tz) = &tzinfo { check_tzinfo_subclass(tz, vm)?; } Ok(Self::new( - a.year, - a.month, - a.day, - a.hour, - a.minute, - a.second, - a.microsecond, + year, + month, + day, + hour, + minute, + second, + microsecond, tzinfo, - a.fold, + fold, )) } } #[derive(FromArgs)] struct NowArgs { - #[pyarg(any, optional, py_default = "None")] - tz: OptionalArg, + #[pyarg(any, default = None)] + tz: Option, } #[derive(FromArgs)] struct FromTimestampArgs { #[pyarg(any)] timestamp: PyObjectRef, - #[pyarg(any, optional)] - tz: OptionalArg, + #[pyarg(any, default = None)] + tz: Option, } #[derive(FromArgs)] @@ -3647,38 +3697,38 @@ mod _datetime { #[derive(FromArgs)] struct DateTimeIsoformatArgs { - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "'T'")] sep: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "'auto'")] timespec: OptionalArg, } #[derive(FromArgs)] struct DateTimeReplaceArgs { #[pyarg(any, optional, py_default = "unchanged")] - year: OptionalArg, + year: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - month: OptionalArg, + month: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - day: OptionalArg, + day: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - hour: OptionalArg, + hour: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - minute: OptionalArg, + minute: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - second: OptionalArg, + second: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] - microsecond: OptionalArg, + microsecond: OptionalArg, #[pyarg(any, optional, py_default = "unchanged")] tzinfo: OptionalArg, #[pyarg(named, optional, py_default = "unchanged")] - fold: OptionalArg, + fold: OptionalArg, } #[derive(FromArgs)] struct AstimezoneArgs { - #[pyarg(any, optional)] - tz: OptionalArg, + #[pyarg(any, default = None)] + tz: Option, } /// `_find_isoformat_datetime_separator` @@ -3727,7 +3777,7 @@ mod _datetime { impl PyDateTime { #[pyclassmethod] fn now(cls: PyTypeRef, args: NowArgs, vm: &VirtualMachine) -> PyResult { - let tz = args.tz.unwrap_or_none(vm); + let tz = args.tz.unwrap_or_else(|| vm.ctx.none()); check_tzinfo_subclass(&tz, vm)?; let tzinfo = tzinfo_arg(tz, vm); let result = datetime_best_possible(&cls, tzinfo.is_none(), tzinfo.clone(), vm)?; @@ -3757,7 +3807,7 @@ mod _datetime { #[pyclassmethod] fn fromtimestamp(cls: PyTypeRef, args: FromTimestampArgs, vm: &VirtualMachine) -> PyResult { - let tz = args.tz.unwrap_or_none(vm); + let tz = args.tz.unwrap_or_else(|| vm.ctx.none()); check_tzinfo_subclass(&tz, vm)?; let tzinfo = tzinfo_arg(tz, vm); let (timet, us) = object_to_timeval(&args.timestamp, vm)?; @@ -3835,8 +3885,8 @@ mod _datetime { } #[pyclassmethod] - fn fromisoformat(cls: PyTypeRef, object: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let dtstr = object; + fn fromisoformat(cls: PyTypeRef, string: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let dtstr = string; let Some(s) = dtstr.downcast_ref::() else { return Err(vm.new_type_error("fromisoformat: argument must be str")); }; @@ -3890,7 +3940,8 @@ mod _datetime { } }; len = len.saturating_sub(p); - rv = parse_isoformat_time(bytes, p, len, &mut vals, &mut tzoffset, &mut tzusec); + rv = + parse_isoformat_time(bytes, p, len, &mut vals, &mut tzoffset, &mut tzusec, vm)?; } if rv < 0 { return Err(invalid_isoformat(&dtstr, vm)?); @@ -4108,15 +4159,15 @@ mod _datetime { }; let (y, mo, d, h, mi, s, us) = zelf.fields(); new_datetime_subclass( - args.year.unwrap_or(y), - args.month.unwrap_or(mo), - args.day.unwrap_or(d), - args.hour.unwrap_or(h), - args.minute.unwrap_or(mi), - args.second.unwrap_or(s), - args.microsecond.unwrap_or(us), + replacement_int(args.year, y), + replacement_int(args.month, mo), + replacement_int(args.day, d), + replacement_int(args.hour, h), + replacement_int(args.minute, mi), + replacement_int(args.second, s), + replacement_int(args.microsecond, us), tzinfo, - args.fold.unwrap_or_else(|| i32::from(zelf.fold)), + replacement_int(args.fold, i32::from(zelf.fold)), zelf.class(), vm, ) @@ -4129,7 +4180,7 @@ mod _datetime { #[pymethod] fn astimezone(zelf: &Py, args: AstimezoneArgs, vm: &VirtualMachine) -> PyResult { - let tz = args.tz.unwrap_or_none(vm); + let tz = args.tz.unwrap_or_else(|| vm.ctx.none()); check_tzinfo_subclass(&tz, vm)?; let target = tzinfo_arg(tz, vm); let local_zone = |vm: &VirtualMachine| -> PyResult { diff --git a/crates/stdlib/src/_heapq.rs b/crates/stdlib/src/_heapq.rs index f1066e97608..8869c206754 100644 --- a/crates/stdlib/src/_heapq.rs +++ b/crates/stdlib/src/_heapq.rs @@ -19,32 +19,40 @@ mod _heapq { ) -> PyResult<()> { let size = heap.__len__(); - let newitem = match heap.borrow_vec().get(pos) { - Some(v) => v.clone(), - None => return Err(vm.new_index_error("index out of range")), - }; + if pos >= size { + return Err(vm.new_index_error("index out of range")); + } - // Follow the path to the root, moving parents down until finding - // a place newitem fits. + // Re-read both entries after each comparison: user code can replace + // elements without changing the list's size. while pos > startpos { let parentpos = (pos - 1) >> 1; - let parent = { + let (newitem, parent) = { let vec = heap.borrow_vec(); - vec[parentpos].clone() + if vec.len() != size { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } + (vec[pos].clone(), vec[parentpos].clone()) }; - let cmp = newitem.rich_compare_bool(&parent, PyComparisonOp::Lt, vm)?; - - if size != heap.__len__() { - return Err(vm.new_runtime_error("list changed size during iteration")); - } + let cmp = newitem.rich_compare_bool(&parent, PyComparisonOp::Lt, vm); + drop(parent); + drop(newitem); + let cmp = cmp?; if !cmp { + if heap.__len__() != size { + return Err(vm.new_runtime_error("list changed size during iteration")); + } break; } - { let mut vec = heap.borrow_vec_mut(); + if vec.len() != size { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } vec.swap(pos, parentpos); } @@ -73,23 +81,28 @@ mod _heapq { if childpos + 1 < endpos { let (a, b) = { let vec = heap.borrow_vec(); + if vec.len() != endpos { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } (vec[childpos].clone(), vec[childpos + 1].clone()) }; - let cmp = a.rich_compare_bool(&b, PyComparisonOp::Lt, vm)?; - - if endpos != heap.__len__() { - return Err(vm.new_runtime_error("list changed size during iteration")); - } - + let cmp = a.rich_compare_bool(&b, PyComparisonOp::Lt, vm); + drop(a); + let cmp = cmp?; if !cmp { childpos += 1; } } { - // Move the smaller child up + // Move the smaller child up. let mut vec = heap.borrow_vec_mut(); + if vec.len() != endpos { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } vec.swap(pos, childpos); } @@ -114,14 +127,15 @@ mod _heapq { where F: Fn(&Py, usize, usize, &VirtualMachine) -> PyResult<()>, { - { + let pos = { let mut vec = heap.borrow_vec_mut(); - vec.push(item); - } - - let size = heap.__len__(); + vec.push(item.clone()); + vec.len() - 1 + }; - siftdown_func(heap, 0, size - 1, vm) + let result = siftdown_func(heap, 0, pos, vm); + drop(item); + result } #[pyfunction] @@ -138,22 +152,23 @@ mod _heapq { where F: Fn(&Py, usize, &VirtualMachine) -> PyResult<()>, { - let Some(lastelt) = heap.borrow_vec_mut().pop() else { - return Err(vm.new_index_error("index out of range")); - }; - - if heap.borrow_vec().is_empty() { - return Ok(lastelt); - }; - - let returnitem = { + let popped = { let mut vec = heap.borrow_vec_mut(); - let root = vec[0].clone(); - vec[0] = lastelt; - root + vec.pop().map(|lastelt| { + if vec.is_empty() { + (lastelt, false) + } else { + (core::mem::replace(&mut vec[0], lastelt), true) + } + }) + }; + let Some((returnitem, needs_sift)) = popped else { + return Err(vm.new_index_error("index out of range")); }; - siftup_func(heap, 0, vm)?; + if needs_sift { + siftup_func(heap, 0, vm)?; + } Ok(returnitem) } @@ -176,14 +191,18 @@ mod _heapq { let mut vec = heap.borrow_vec_mut(); let root = match vec.first() { Some(v) => v.clone(), - None => return Err(vm.new_index_error("index out of range")), + None => { + drop(vec); + return Err(vm.new_index_error("index out of range")); + } }; - vec[0] = item; + vec[0] = item.clone(); root }; siftup_func(heap, 0, vm)?; + drop(item); Ok(returnitem) } @@ -210,7 +229,9 @@ mod _heapq { } }; - let cmp = top.rich_compare_bool(&item, PyComparisonOp::Lt, vm)?; + let cmp = top.rich_compare_bool(&item, PyComparisonOp::Lt, vm); + drop(top); + let cmp = cmp?; if !cmp { return Ok(item); } @@ -219,14 +240,18 @@ mod _heapq { let mut vec = heap.borrow_vec_mut(); let root = match vec.first() { Some(v) => v.clone(), - None => return Err(vm.new_index_error("index out of range")), + None => { + drop(vec); + return Err(vm.new_index_error("index out of range")); + } }; - vec[0] = item; + vec[0] = item.clone(); root }; siftup(&heap, 0, vm)?; + drop(item); Ok(returnitem) } @@ -318,32 +343,40 @@ mod _heapq { ) -> PyResult<()> { let size = heap.__len__(); - let newitem = match heap.borrow_vec().get(pos) { - Some(v) => v.clone(), - None => return Err(vm.new_index_error("index out of range")), - }; + if pos >= size { + return Err(vm.new_index_error("index out of range")); + } - // Follow the path to the root, moving parents down until finding - // a place newitem fits. + // Re-read both entries after each comparison: user code can replace + // elements without changing the list's size. while pos > startpos { let parentpos = (pos - 1) >> 1; - let parent = { + let (newitem, parent) = { let vec = heap.borrow_vec(); - vec[parentpos].clone() + if vec.len() != size { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } + (vec[pos].clone(), vec[parentpos].clone()) }; - let cmp = parent.rich_compare_bool(&newitem, PyComparisonOp::Lt, vm)?; - - if size != heap.__len__() { - return Err(vm.new_runtime_error("list changed size during iteration")); - } + let cmp = parent.rich_compare_bool(&newitem, PyComparisonOp::Lt, vm); + drop(parent); + drop(newitem); + let cmp = cmp?; if !cmp { + if heap.__len__() != size { + return Err(vm.new_runtime_error("list changed size during iteration")); + } break; } - { let mut vec = heap.borrow_vec_mut(); + if vec.len() != size { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } vec.swap(pos, parentpos); } @@ -372,23 +405,28 @@ mod _heapq { if childpos + 1 < endpos { let (a, b) = { let vec = heap.borrow_vec(); + if vec.len() != endpos { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } (vec[childpos + 1].clone(), vec[childpos].clone()) }; - let cmp = a.rich_compare_bool(&b, PyComparisonOp::Lt, vm)?; - - if endpos != heap.__len__() { - return Err(vm.new_runtime_error("list changed size during iteration")); - } - + let cmp = a.rich_compare_bool(&b, PyComparisonOp::Lt, vm); + drop(a); + let cmp = cmp?; if !cmp { childpos += 1; } } { - // Move the larger child up + // Move the larger child up. let mut vec = heap.borrow_vec_mut(); + if vec.len() != endpos { + drop(vec); + return Err(vm.new_runtime_error("list changed size during iteration")); + } vec.swap(pos, childpos); } @@ -437,7 +475,9 @@ mod _heapq { } }; - let cmp = item.rich_compare_bool(&top, PyComparisonOp::Lt, vm)?; + let cmp = item.rich_compare_bool(&top, PyComparisonOp::Lt, vm); + drop(top); + let cmp = cmp?; if !cmp { return Ok(item); } @@ -446,14 +486,18 @@ mod _heapq { let mut vec = heap.borrow_vec_mut(); let root = match vec.first() { Some(v) => v.clone(), - None => return Err(vm.new_index_error("index out of range")), + None => { + drop(vec); + return Err(vm.new_index_error("index out of range")); + } }; - vec[0] = item; + vec[0] = item.clone(); root }; siftup_max(&heap, 0, vm)?; + drop(item); Ok(returnitem) } } diff --git a/crates/stdlib/src/_opcode.rs b/crates/stdlib/src/_opcode.rs index 6a3c500c537..2b7a8e5d651 100644 --- a/crates/stdlib/src/_opcode.rs +++ b/crates/stdlib/src/_opcode.rs @@ -4,7 +4,6 @@ pub(crate) use _opcode::module_def; mod _opcode { use crate::vm::{ AsObject, PyObjectRef, PyResult, VirtualMachine, - builtins::{PyInt, PyIntRef}, bytecode::{AnyOpcode, oparg}, }; @@ -25,7 +24,7 @@ mod _opcode { #[derive(FromArgs)] struct StackEffectArgs { #[pyarg(positional)] - opcode: PyIntRef, + opcode: i32, #[pyarg(positional, optional)] oparg: Option, #[pyarg(named, optional)] @@ -33,58 +32,33 @@ mod _opcode { } #[pyfunction] + #[allow(clippy::unnecessary_cast)] // `c_long` is `i32` or `i64` fn stack_effect(args: StackEffectArgs, vm: &VirtualMachine) -> PyResult { - let oparg = args.oparg.map_or(Ok(0), |v| { - if !v.fast_isinstance(vm.ctx.types.int_type) { - return Err(vm.new_type_error(format!( - "'{}' object cannot be interpreted as an integer", - v.class().name() - ))); - } - v.downcast_ref::() - .ok_or_else(|| { - vm.new_type_error(format!( - "'{}' object cannot be interpreted as an integer", - v.class().name() - )) - })? - .try_to_primitive::(vm) - })?; - - let jump: Option = match args.jump { - Some(v) => { - if vm.is_none(&v) { - None - } else { - Some(v.try_to_bool(vm).map_err(|_| { - vm.new_value_error("stack_effect: jump must be False, True or None") - })?) - } - } + let oparg = match args.oparg { + // (int)PyLong_AsLong(oparg) + Some(v) if !vm.is_none(&v) => v.try_into_value::(vm)? as i32, + _ => 0, + }; + let jump = match args.jump { None => None, + Some(v) if vm.is_none(&v) => None, + Some(v) if v.is(&vm.ctx.true_value) => Some(true), + Some(v) if v.is(&vm.ctx.false_value) => Some(false), + Some(_) => { + return Err(vm.new_value_error("stack_effect: jump must be False, True or None")); + } }; - - let instr = args - .opcode - .try_to_primitive::(vm) - .and_then(|v| { - AnyOpcode::try_from(v) - .map_err(|_| vm.new_exception_empty(vm.ctx.exceptions.value_error.to_owned())) - }) - .map_err(|_| vm.new_value_error("invalid opcode or oparg"))?; - - // Raise ValueError if specialized. + let invalid = || vm.new_value_error("invalid opcode or oparg"); + let instr = try_from_i32(args.opcode).map_err(|_| invalid())?; + // Specialized instructions are not supported. if instr.real().is_some_and(|op| op.deopt().is_some()) { - return Err(vm.new_value_error("invalid opcode or oparg")); + return Err(invalid()); } - - let effect = match jump { - Some(true) => instr.stack_effect_jump(oparg), - Some(false) => instr.stack_effect(oparg), - // jump=None: max of both paths (CPython convention) - None => instr - .stack_effect(oparg) - .max(instr.stack_effect_jump(oparg)), + let oparg = u32::try_from(oparg).map_err(|_| invalid())?; + let effect = if jump == Some(false) { + instr.stack_effect(oparg) + } else { + instr.stack_effect_jump(oparg) }; Ok(effect) } @@ -197,16 +171,20 @@ mod tests { macro_rules! assert_dis_snapshot { ($value:expr) => { - insta::assert_snapshot!(dis($value)) + insta::assert_snapshot!(dis($value, false)) + }; + (positions: $value:expr) => { + insta::assert_snapshot!(dis($value, true)) }; } - /// Returns the [`dis.dis`](https://docs.python.org/3/library/dis.html#dis.dis) output. + /// Returns the [`dis.dis`](https://docs.python.org/3/library/dis.html#dis.dis) output, + /// with the source positions of the instructions if `show_positions` is true. /// /// # Notes /// /// Memory addresses in the output are replaced with `0xdeadbeef` for consistency. - fn dis(source: &str) -> String { + fn dis(source: &str, show_positions: bool) -> String { const FNAME: &str = ""; let builder = vm::Interpreter::builder(Default::default()); @@ -223,6 +201,10 @@ mod tests { .map_err(|err| err.into_pyexception(vm, Some(source))) .unwrap(); scope.globals.set_item("code", code_obj.into(), vm).unwrap(); + scope + .globals + .set_item("show_positions", vm.new_pyobj(show_positions), vm) + .unwrap(); let py_source = r#" import dis @@ -232,13 +214,13 @@ import sys old_stdout = sys.stdout sys.stdout = buf = io.StringIO() -dis.dis(code) +dis.dis(code, show_positions=show_positions) sys.stdout = old_stdout tmp_output = buf.getvalue() # constant mem address -output = re.sub(r'(0xdeadbeef', tmp_output) +output = re.sub(r'(0xdeadbeef', tmp_output) "#; let py_code_obj = vm @@ -246,7 +228,12 @@ output = re.sub(r'(0xdeadbeef', tmp .map_err(|err| err.into_pyexception(vm, Some(py_source))) .unwrap(); - vm.run_code_obj(py_code_obj, scope.clone()).unwrap(); + vm.run_code_obj(py_code_obj, scope.clone()) + .unwrap_or_else(|err| { + let mut traceback = String::new(); + let _ = vm.write_exception(&mut traceback, &err); + panic!("Python disassembly failed: {err:?}\n{traceback}"); + }); let py_output = scope.globals.get_item("output", vm).unwrap(); py_output.str(vm).unwrap().to_string() }) @@ -338,6 +325,707 @@ def f(one: int): my_lst = [1] my_lst[one]: int return my_lst +"# + ) + } + + #[test] + fn empty_module_implicit_return_location() { + // The implicit return is emitted with NO_LOCATION; propagate_line_numbers() + // gives it the module RESUME location, whose line is 0. + assert_dis_snapshot!(positions: "") + } + + #[test] + fn module_docstring_location() { + // codegen_body() loads the docstring at its expression location and stores + // __doc__ with NO_LOCATION. + assert_dis_snapshot!( + positions: r#" +"doc" +x = 1 +"# + ) + } + + #[test] + fn redundant_nop_location() { + // basicblock_remove_redundant_nops() copies the full NOP location into a + // following no-location jump. + assert_dis_snapshot!( + positions: r#" +def f(x, y, z): + while x: + if y: + pass + elif z: + if y < 0: + return y + if z: + y = y + 1 + elif y: + return 1 + return -1 +"# + ) + } + + #[test] + fn annotated_multiline_function_firstlineno() { + // codegen_function() computes firstlineno from the FunctionDef before + // compiling annotations. + assert_dis_snapshot!( + positions: r#" + +a = 1 +def f( + x: a, +): ... +"# + ) + } + + #[test] + fn annotation_scope_function_location() { + // codegen_function_annotations() receives LOC(function) and uses it for the + // annotation closure's BUILD_MAP/RETURN_VALUE and the MAKE_FUNCTION annotate + // sequence. + assert_dis_snapshot!( + positions: r#" + +def g(): + def f(x: not (int is int), /): ... +"# + ) + } + + #[test] + fn starred_arg_annotation_unpack_location() { + // codegen_argannotation() visits `Ts` at the annotation location, then emits + // UNPACK_SEQUENCE at LOC(function). + assert_dis_snapshot!( + positions: r#" +def f(*args: *Ts): pass +"# + ) + } + + #[test] + fn module_deferred_annotations_location() { + // codegen_process_deferred_annotations() uses the first module statement + // location from start_location(). + assert_dis_snapshot!( + positions: r#" +import os +X: int +Y: str +"# + ) + } + + #[test] + fn not_compare_location() { + // A Compare inside UnaryOp(Not) is parsed with the UnaryOp start location. + assert_dis_snapshot!( + positions: r#" +def f(self, other): + return not self == other +"# + ) + } + + #[test] + fn not_chained_compare_location() { + // A chained comparison keeps its inner range for the comparison scaffolding + // and uses the UnaryOp range only for TO_BOOL and UNARY_NOT. + assert_dis_snapshot!( + positions: r#" +def f(c): + return not (b" " <= c <= b"~") +"# + ) + } + + #[test] + fn type_param_scope_locations() { + // codegen_type_params() emits type parameter ops at LOC(typeparam), + // bound/default evaluators at LOC(e), and type alias plumbing at LOC(s). + assert_dis_snapshot!( + positions: r#" +type BoundGenericAlias[X: int] = set[X] +"# + ) + } + + #[test] + fn generic_typealias_wrapper_return_location() { + // The generic parameters wrapper of a type alias returns at LOC(type alias). + assert_dis_snapshot!( + positions: r#" +type A[T] = T +"# + ) + } + + #[test] + fn generic_function_annotation_scope_location() { + // codegen_function_annotations() gets LOC(function) inside the generic + // parameters scope too. + assert_dis_snapshot!( + positions: r#" +def f[T](x: int): ... +"# + ) + } + + #[test] + fn generic_class_type_params_store_location() { + // codegen_class() stores the .type_params cell at LOC(class). + assert_dis_snapshot!( + positions: r#" +def outer(): + class X[T]: ... +"# + ) + } + + #[test] + fn class_deferred_annotations_location() { + // Deferred annotation setup and the class tail inherit the class body + // location LOCATION(firstlineno, firstlineno, 0, 0). + assert_dis_snapshot!( + positions: r#" + +class C: + "doc" + x: int +"# + ) + } + + #[test] + fn future_annotation_string_location() { + // The stringized annotation is loaded at LOC(annotation) and stored at + // LOC(AnnAssign). + assert_dis_snapshot!( + positions: r#" +from __future__ import annotations +class Bar: + foo: Foo +"# + ) + } + + #[test] + fn lambda_dict_literal_location() { + // codegen_dict() and codegen_subdict() use LOC(dict) for BUILD_MAP, MAP_ADD + // and DICT_UPDATE. + assert_dis_snapshot!( + positions: r#" +f = lambda data: {'x': data} +g = lambda i: {**i} +"# + ) + } + + #[test] + fn match_or_alternative_locations() { + // codegen_pattern_or() emits the COPY of each alternative at LOC(alt). + assert_dis_snapshot!( + positions: r#" +def f(): + x = False + match 0: + case 0 | 1 | 2 | 3: + x = True + return x +"# + ) + } + + #[test] + fn match_success_jump_location() { + // codegen_match_inner() emits the success jump with NO_LOCATION. + assert_dis_snapshot!( + positions: r#" +def f(self): + match 0: + case 0: + x = True + case 0: + x = False + self.assertIs(x, True) +"# + ) + } + + #[test] + fn match_mapping_keys_location() { + // codegen_pattern_mapping() returns to LOC(p) for the BUILD_TUPLE/MATCH_KEYS + // scaffolding. + assert_dis_snapshot!( + positions: r#" +def f(self): + x = {} + y = None + match x: + case {0: 0}: + y = 0 + self.assertIs(y, None) +"# + ) + } + + #[test] + fn match_class_scaffolding_location() { + // codegen_pattern_class() returns to LOC(p) after visiting the class. + assert_dis_snapshot!( + positions: r#" +def f(x): + match x: + case bool(z): + y = 0 + return y, z +"# + ) + } + + #[test] + fn taken_constant_boolop_location() { + // The surviving load of a short-circuited BoolOp keeps the literal range. + assert_dis_snapshot!( + positions: r#" +def and_false(x): + return False and x + +def or_true(x): + return True or x +"# + ) + } + + #[test] + fn assert_false_message_location() { + // codegen_assert() emits LOAD_COMMON_CONSTANT and CALL at LOC(assert) and + // RAISE_VARARGS at LOC(test). + assert_dis_snapshot!( + positions: r#" +def f(): + assert False, "x" +"# + ) + } + + #[test] + fn static_swap_implicit_return_location() { + // Line numbers are resolved before apply_static_swaps() reorders the stores, + // so the return epilogue keeps the location of the last store before the swap. + assert_dis_snapshot!( + positions: r#" +def f(a, b): + a, b = a, b + b, a = a, b +"# + ) + } + + #[test] + fn genexpr_closure_and_call_location() { + // codegen_comprehension() uses LOC(e) for the closure, the outer CALL and the + // implicit .0 load. + assert_dis_snapshot!( + positions: r#" +def f(parameters): + return ((p, type(p)) for p in parameters) +"# + ) + } + + #[test] + fn implicit_call_genexpr_range() { + // A sole unparenthesized generator expression argument spans the call + // parentheses. + assert_dis_snapshot!( + positions: r#" +def implicit(): + return list(x for x in range(10)) + +def explicit(): + return list((x for x in range(10))) +"# + ) + } + + #[test] + fn implicit_call_genexpr_parenthesized_element_range() { + // The call parentheses are part of the generator expression range even when + // its element starts with a parenthesis. + assert_dis_snapshot!( + positions: r#" +def bytes_binop(): + return bytes((x ^ 0x5C) for x in range(256)) + +def dict_tuple(d): + return dict((v, k) for (k, v) in d.items()) + +def plain_tuple_elt(xs): + return list((x, y) for x, y in xs) + +def explicit_gen(xs): + return list(((x, y) for x, y in xs)) +"# + ) + } + + #[test] + fn genexpr_filter_cleanup_location() { + // jump_thread() copies the if_cleanup backedge location, elt_loc, to the + // threaded cleanup path. + assert_dis_snapshot!( + positions: r#" +def simple(names): + return (x for x in names if not _ishidden(x)) + +def boolop(fields): + return (f for f in fields if f.init and not f.kw_only) +"# + ) + } + + #[test] + fn try_finally_exception_scaffolding_location() { + // codegen_try_finally() emits the exception path scaffolding with NO_LOCATION. + assert_dis_snapshot!( + positions: r#" +def f(self, node): + self.flag = True + try: + self.body(node) + finally: + self.flag = False +"# + ) + } + + #[test] + fn adjacent_no_location_entries() { + // assemble_location_info() merges adjacent NO_LOCATION instructions into one + // linetable entry. + assert_dis_snapshot!( + positions: r#" +def f(file): + if sys.platform == "win32": + try: + import nt + if not nt._supports_virtual_terminal(): + return False + except (ImportError, AttributeError): + return False + try: + return os.isatty(file.fileno()) + except OSError: + return hasattr(file, "isatty") and file.isatty() +"# + ) + } + + #[test] + fn fstring_format_location() { + // codegen_formatted_value() emits CONVERT_VALUE and FORMAT_* at + // LOC(FormattedValue). + assert_dis_snapshot!( + positions: r#" +def simple(self): + return f'{self.value}' + +def spec(x): + return f'{x!r:>3}' +"# + ) + } + + #[test] + fn joined_string_literals_location() { + // Adjacent f-string literal fragments are one Constant spanning all of them. + assert_dis_snapshot!( + positions: r#" +def f(a): + return ( + 'x' + f'y{a}z' + 'w' + ) +"# + ) + } + + #[test] + fn decorated_definition_locations() { + // Decorators are evaluated first, the closure and the store use LOC(s), and + // each decorator CALL uses the decorator location. + assert_dis_snapshot!( + positions: r#" +def dec(f): return f + +class C: + @dec + def f(self): + yield + +@dec +class D: + pass + +class E: + @dec + def g(self, flags: int, /) -> memoryview: + raise NotImplementedError +"# + ) + } + + #[test] + fn builtin_any_genexpr_call() { + // any(genexpr) is inlined behind a builtin identity check that falls back to + // the ordinary call. + assert_dis_snapshot!( + positions: r#" +def f(xs): + return any(x for x in xs) +"# + ) + } + + #[test] + fn builtin_tuple_list_set_genexpr_calls() { + // tuple(), list() and set() of a generator expression are inlined behind a + // builtin identity check that falls back to the ordinary call. + assert_dis_snapshot!( + positions: r#" +def tuple_f(xs): + return tuple(x for x in xs) + +def list_f(xs): + return list(x for x in xs) + +def set_f(xs): + return set(x for x in xs) +"# + ) + } + + #[test] + fn augassign_constant_slice_location() { + // codegen_augassign() emits the COPY/COPY/BINARY_OP NB_SUBSCR at LOC(target). + assert_dis_snapshot!( + positions: r#" +def aug_const(x, y): + x[1:2] += y +"# + ) + } + + #[test] + fn comprehension_list_iterable_location() { + // codegen_comprehension_iter() emits GET_ITER at LOC(comp->iter). + assert_dis_snapshot!( + positions: r#" +async def f(i): + return i + +async def run_list(): + return [await c for c in [f(1), f(41)]] +"# + ) + } + + #[test] + fn inlined_comprehension_backedge_location() { + // codegen_sync_comprehension_generator() emits the backedges at elt_loc. + assert_dis_snapshot!( + positions: r#" +async def f(i): + return i + +async def run_list(): + return [s for c in [f(''), f('abc')] for s in await c] +"# + ) + } + + #[test] + fn inlined_async_comprehension_end_async_for_location() { + // codegen_async_comprehension_generator() emits END_ASYNC_FOR at the + // comprehension location. + assert_dis_snapshot!( + positions: r#" +async def f(it): + for i in it: + yield i + +async def run_list(): + return [i + 1 async for i in f([10, 20])] +"# + ) + } + + #[test] + fn async_for_anext_location() { + // codegen_async_for() emits the GET_ANEXT/yield-from scaffolding at LOC(s). + assert_dis_snapshot!( + positions: r#" +async def f(source, buffer): + async for i1, i2 in source(): + buffer.append(i1 + i2) +"# + ) + } + + #[test] + fn namedexpr_copy_location() { + // The COPY of a named expression is at its location, between the value and + // the target. + assert_dis_snapshot!( + positions: r#" +def outer(): + a = 10 + def spam(): + nonlocal a + (a := 20) +"# + ) + } + + #[test] + fn with_cleanup_covers_not_taken() { + // The synthetic NOT_TAKEN shares the conditional jump's cleanup handler. + assert_dis_snapshot!( + positions: r#" +def f(c): + with c: + x = 1 + y = 2 +"# + ) + } + + #[test] + fn async_for_end_async_for() { + // END_ASYNC_FOR jumps back to the END_SEND of its awaitable loop. + assert_dis_snapshot!( + positions: r#" +async def f(xs): + async for x in xs: + pass +"# + ) + } + + #[test] + fn genexpr_prefix() { + // The outermost iterator is acquired before RETURN_GENERATOR, outside the + // StopIteration handler. + assert_dis_snapshot!( + positions: r#" +def f(xs): + return (x for x in xs) + +async def g(xs): + return (x async for x in xs) +"# + ) + } + + #[test] + fn yield_from_and_await() { + // GET_ITER and GET_AWAITABLE leave the iterator pair that SEND uses. + assert_dis_snapshot!( + positions: r#" +def f(xs): + yield from xs + +async def g(xs): + return await xs +"# + ) + } + + #[test] + fn comprehension_collection_depth() { + // The collection depth counts the slots of every nested iterator. + assert_dis_snapshot!( + positions: r#" +def f(xs, ys): + return [x for x in xs for y in ys] + +async def g(xs, ys): + return [x async for x in xs for y in ys] +"# + ) + } + + #[test] + fn import_flags() { + // The IMPORT_NAME oparg flags depend on the scope and the enclosing handlers. + assert_dis_snapshot!( + positions: r#" +import sample +from sample import member +from sample import * + +def f(): + import sample + +class C: + from sample import member + +try: + import sample +except Exception: + pass + +try: + operation() +except Exception: + import sample + +try: + operation() +finally: + import sample + +with manager: + import sample +"# + ) + } + + #[test] + fn loop_return_cleanup() { + // A return pops two slots for a for loop and one for an async for loop. + assert_dis_snapshot!( + positions: r#" +def f(xs): + for x in xs: + return x + +async def g(xs): + async for x in xs: + return x +"# + ) + } + + #[test] + fn list_set_async_genexpr_calls() { + // list() and set() of an async generator expression stay ordinary calls. + assert_dis_snapshot!( + positions: r#" +async def f(xs): + return list(x async for x in xs) + +async def g(xs): + return set(x async for x in xs) "# ) } diff --git a/crates/stdlib/src/_queue.rs b/crates/stdlib/src/_queue.rs index 27155b7c3f3..0e47f1f13ff 100644 --- a/crates/stdlib/src/_queue.rs +++ b/crates/stdlib/src/_queue.rs @@ -9,8 +9,9 @@ mod _queue { use crate::vm::{ AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{PyBaseExceptionRef, PyException, PyGenericAlias, PyStr, PyType, PyTypeRef}, - function::TimeoutSeconds, + function::OptionalArg, protocol::PyNumberMethods, + stdlib::time::pytime, types::{AsNumber, Constructor, Representable}, }; @@ -21,7 +22,7 @@ mod _queue { use parking_lot::{Condvar, Mutex, MutexGuard}; type Buf = Mutex; - }, + } _ => { use crate::common::lock::PyMutex; @@ -85,15 +86,6 @@ mod _queue { vm.allow_threads(|| self.mutex.lock()) } - fn release(&self, vm: &VirtualMachine) { - { - let mut count = self.lock_count(vm); - *count += 1; - } // lock dropped. now we can notify a waiting thread - - self.cond.notify_one(); - } - /// `Ok(true)` if acquired, `Ok(false)` on timeout, `Err` if a signal /// handler raised (e.g. `KeyboardInterrupt`) while we were waiting. fn acquire( @@ -167,10 +159,21 @@ mod _queue { expect(unused_variables, reason = "only the semaphore needs the vm") )] fn push(&self, item: PyObjectRef, vm: &VirtualMachine) { - self.buf.lock().push_back(item); - #[cfg(feature = "threading")] - self.sem.release(vm); + { + // Publish the permit before unlocking the buffer, so another + // thread cannot observe an item that no getter can claim. + let mut count = self.sem.lock_count(vm); + { + let mut buf = self.buf.lock(); + buf.push_back(item); + *count += 1; + } + drop(count); + self.sem.cond.notify_one(); + } + #[cfg(not(feature = "threading"))] + self.buf.lock().push_back(item); } /// Returns a strong reference from the head of the buffer. @@ -204,26 +207,25 @@ mod _queue { struct PutArgs { #[pyarg(any)] item: PyObjectRef, - #[expect( - dead_code, - reason = "Intentional. Provide compatibility with the Queue class" - )] - #[pyarg(any, default = true)] - block: bool, - #[expect( - dead_code, - reason = "Intentional. Provide compatibility with the Queue class" - )] + #[pyarg(any, optional, py_default = "True")] + block: OptionalArg, #[pyarg(any, optional)] timeout: Option, } #[derive(FromArgs)] struct GetArgs { - #[pyarg(any, default = true)] - block: bool, + #[pyarg(any, optional, py_default = "True")] + block: OptionalArg, #[pyarg(any, optional)] - timeout: Option, + timeout: Option, + } + + fn is_blocking(block: &OptionalArg, vm: &VirtualMachine) -> PyResult { + match block { + OptionalArg::Present(value) => value.try_to_bool(vm), + OptionalArg::Missing => Ok(true), + } } #[pyclass( @@ -231,6 +233,12 @@ mod _queue { flags(BASETYPE, HAS_WEAKREF, IMMUTABLETYPE) )] impl PySimpleQueue { + #[pymethod] + fn __sizeof__(zelf: &Py) -> usize { + core::mem::size_of::() + + zelf.buf.lock().capacity() * core::mem::size_of::() + } + #[pymethod] fn empty(zelf: &Py) -> bool { zelf.buf.lock().is_empty() @@ -242,9 +250,15 @@ mod _queue { } #[pymethod] - fn put(zelf: &Py, args: PutArgs, vm: &VirtualMachine) { - let PutArgs { item, .. } = args; + fn put(zelf: &Py, args: PutArgs, vm: &VirtualMachine) -> PyResult<()> { + let PutArgs { + item, + block, + timeout: _timeout, + } = args; + is_blocking(&block, vm)?; zelf.push(item, vm); + Ok(()) } #[pymethod] @@ -255,10 +269,11 @@ mod _queue { #[pymethod] fn get(zelf: &Py, args: GetArgs, vm: &VirtualMachine) -> PyResult { let GetArgs { block, timeout } = args; + let blocking = is_blocking(&block, vm)?; // Non-blocking: just try once - if !block { - return Self::get_inner(&mut zelf.buf.lock()).ok_or_else(|| empty_error(vm)); + if !blocking { + return Self::get_nowait(zelf, vm); } #[cfg_attr( @@ -268,22 +283,37 @@ mod _queue { reason = "We are still validating the 'timeout' arg even if we don't have threading" ) )] - let deadline = match timeout.map(|v| v.to_secs_f64()) { - Some(v) if v < 0.0 => { - return Err(vm.new_value_error("'timeout' must be a non-negative number")); + let deadline = match timeout.as_ref() { + Some(value) => { + let overflow = + || vm.new_overflow_error("timestamp out of range for C PyTime_t"); + // SimpleQueue uses ceiling, unlike the away-from-zero + // rounding used by thread locks and select timeouts. + let nanos = pytime::from_seconds_object(value, pytime::Round::Ceiling, vm)?; + if nanos < 0 { + return Err(vm.new_value_error("'timeout' must be a non-negative number")); + } + Some( + Instant::now() + .checked_add(Duration::from_nanos(nanos as u64)) + .ok_or_else(overflow)?, + ) } - Some(v) => Some(Instant::now() + Duration::from_secs_f64(v)), None => None, }; #[cfg(feature = "threading")] { - if !zelf.sem.acquire(block, deadline, vm)? { + if !zelf.sem.acquire(blocking, deadline, vm)? { return Err(empty_error(vm)); } } - Self::get_inner(&mut zelf.buf.lock()).ok_or_else(|| empty_error(vm)) + let item = { + let mut buf = zelf.buf.lock(); + Self::get_inner(&mut buf) + }; + item.ok_or_else(|| empty_error(vm)) } #[pymethod] @@ -295,7 +325,11 @@ mod _queue { } } - Self::get_inner(&mut zelf.buf.lock()).ok_or_else(|| empty_error(vm)) + let item = { + let mut buf = zelf.buf.lock(); + Self::get_inner(&mut buf) + }; + item.ok_or_else(|| empty_error(vm)) } #[pyclassmethod] diff --git a/crates/stdlib/src/_remote_debugging.rs b/crates/stdlib/src/_remote_debugging.rs index 618ea9fe0a8..fd31f1fdd0a 100644 --- a/crates/stdlib/src/_remote_debugging.rs +++ b/crates/stdlib/src/_remote_debugging.rs @@ -1,19 +1,47 @@ +mod binary; + pub(crate) use _remote_debugging::module_def; #[pymodule] mod _remote_debugging { + use super::binary; use crate::vm::{ - Py, PyObjectRef, PyResult, VirtualMachine, - builtins::PyType, - function::FuncArgs, - types::{Constructor, PyStructSequence}, + AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, VirtualMachine, + builtins::{PyBaseExceptionRef, PyDictRef, PyFloat, PyList, PyListRef, PyTuple, PyType}, + common::{lock::PyMutex, rc::PyRc}, + convert::{IntoPyException, ToPyObject}, + function::{FsPath, FuncArgs, OptionalArg}, + types::{Constructor, DefaultConstructor, Initializer, PyStructSequence}, }; + use alloc::sync::Arc; + use core::sync::atomic::{AtomicBool, Ordering}; + use num_traits::ToPrimitive; + + #[pystruct_sequence_data] + struct LocationInfoData { + lineno: PyObjectRef, + end_lineno: PyObjectRef, + col_offset: PyObjectRef, + end_col_offset: PyObjectRef, + } + + #[pyattr] + #[pystruct_sequence( + name = "LocationInfo", + module = "_remote_debugging", + data = "LocationInfoData" + )] + struct LocationInfo; + + #[pyclass(with(PyStructSequence))] + impl LocationInfo {} #[pystruct_sequence_data] struct FrameInfoData { - filename: String, - lineno: i64, - funcname: String, + filename: PyObjectRef, + location: PyObjectRef, + funcname: PyObjectRef, + opcode: PyObjectRef, } #[pyattr] @@ -58,6 +86,7 @@ mod _remote_debugging { #[pystruct_sequence_data] struct ThreadInfoData { thread_id: PyObjectRef, + status: PyObjectRef, frame_info: PyObjectRef, } @@ -72,6 +101,130 @@ mod _remote_debugging { #[pyclass(with(PyStructSequence))] impl ThreadInfo {} + #[pystruct_sequence_data] + struct InterpreterInfoData { + interpreter_id: PyObjectRef, + threads: PyObjectRef, + } + + #[pyattr] + #[pystruct_sequence( + name = "InterpreterInfo", + module = "_remote_debugging", + data = "InterpreterInfoData" + )] + struct InterpreterInfo; + + #[pyclass(with(PyStructSequence))] + impl InterpreterInfo {} + + #[pyattr] + const PROCESS_VM_READV_SUPPORTED: u8 = + rustpython_host_env::remote_debugging::PROCESS_VM_READV_SUPPORTED; + + #[pyattr] + const THREAD_STATUS_HAS_GIL: u8 = 1; + #[pyattr] + const THREAD_STATUS_ON_CPU: u8 = 2; + #[pyattr] + const THREAD_STATUS_UNKNOWN: u8 = 4; + #[pyattr] + const THREAD_STATUS_GIL_REQUESTED: u8 = 8; + #[pyattr] + const THREAD_STATUS_HAS_EXCEPTION: u8 = 16; + #[pyattr] + const THREAD_STATUS_MAIN_THREAD: u8 = 32; + + #[derive(FromArgs)] + struct IsPythonProcessArgs { + #[pyarg(any)] + pid: PyObjectRef, + } + + /// Check if a process is a Python process. + #[pyfunction] + fn is_python_process(args: IsPythonProcessArgs, vm: &VirtualMachine) -> PyResult { + // Finish argument binding before invoking a user-defined __index__. + let pid: i32 = args.pid.try_into_value(vm)?; + Ok(rustpython_host_env::remote_debugging::is_python_process( + pid, + )) + } + + #[derive(FromArgs)] + struct GetChildPidsArgs { + #[pyarg(any)] + pid: PyObjectRef, + #[pyarg(named, optional, py_default = "True")] + recursive: OptionalArg, + } + + /// Return a snapshot of a process's children, optionally including descendants. + #[pyfunction] + fn get_child_pids(args: GetChildPidsArgs, vm: &VirtualMachine) -> PyResult { + // Complete argument binding first, then preserve CPython's conversion order. + let pid = args + .pid + .try_index(vm)? + .as_bigint() + .to_i32() + .ok_or_else(|| vm.new_overflow_error("Python int too large to convert to C int"))?; + let recursive = args + .recursive + .into_option() + .map(|value| value.try_to_bool(vm)) + .transpose()? + .unwrap_or(true); + let pids = rustpython_host_env::remote_debugging::get_child_pids(pid, recursive).map_err( + |error| { + use rustpython_host_env::remote_debugging::ChildPidsError; + match error { + ChildPidsError::Unsupported => vm.new_not_implemented_error( + "Subprocess enumeration not supported on this platform", + ), + ChildPidsError::Memory => { + vm.new_exception_empty(vm.ctx.exceptions.memory_error.to_owned()) + } + ChildPidsError::Message(message) => vm.new_os_error(message), + ChildPidsError::Os(error) => error.into_pyexception(vm), + ChildPidsError::Proc { error, operation } => { + // Preserve errno/subtype and filename. CPython wraps read/close + // errors with context, but never hides PermissionError. + let description = error + .raw_os_error() + .and_then(rustpython_host_env::errno::strerror_string) + .unwrap_or_else(|| error.to_string()); + let cause = error.into_pyexception(vm); + let _ = cause + .as_object() + .set_attr("filename", vm.ctx.new_str("/proc"), vm); + match operation { + Some(operation) + if !cause.fast_isinstance(vm.ctx.exceptions.permission_error) => + { + let outer = vm.new_os_error(format!( + "Failed to {operation} process directory '/proc': {description}" + )); + outer.set_context(Some(cause.clone())); + outer.set_cause(Some(cause)); + outer + } + _ => cause, + } + } + } + }, + )?; + Ok(vm + .ctx + .new_list(pids.into_iter().map(|pid| pid.to_pyobject(vm)).collect())) + } + + #[pyfunction] + fn zstd_available() -> bool { + false + } + #[pystruct_sequence_data] struct AwaitedInfoData { thread_id: PyObjectRef, @@ -89,6 +242,748 @@ mod _remote_debugging { #[pyclass(with(PyStructSequence))] impl AwaitedInfo {} + fn codec_error(error: binary::Error, vm: &VirtualMachine) -> PyBaseExceptionRef { + match error { + binary::Error::Io(error) => error.into_pyexception(vm), + binary::Error::Value(message) => vm.new_value_error(message), + binary::Error::Overflow(message) | binary::Error::Limit(message) => { + vm.new_overflow_error(message) + } + binary::Error::Memory => vm.new_memory_error("unable to allocate profiling data"), + binary::Error::Runtime(message) => vm.new_runtime_error(message), + } + } + + fn codec_path_error( + error: binary::Error, + path: PyObjectRef, + vm: &VirtualMachine, + ) -> PyBaseExceptionRef { + let is_io = matches!(error, binary::Error::Io(_)); + let exception = codec_error(error, vm); + if is_io { + let _ = exception.as_object().set_attr("filename", path, vm); + } + exception + } + + fn list_items(value: &PyObject, name: &str, vm: &VirtualMachine) -> PyResult> { + value + .downcast_ref::() + .map(|list| list.borrow_vec().to_vec()) + .ok_or_else(|| vm.new_type_error(format!("{name} must be a list"))) + } + + fn record_fields<'a>( + value: &'a PyObject, + count: usize, + name: &str, + vm: &VirtualMachine, + ) -> PyResult<&'a [PyObjectRef]> { + value + .downcast_ref::() + .map(|tuple| tuple.as_slice()) + .filter(|fields| fields.len() >= count) + .ok_or_else(|| { + vm.new_type_error(format!( + "{name} must be a tuple with at least {count} fields" + )) + }) + } + + fn normalize_frame(value: &PyObject, vm: &VirtualMachine) -> PyResult { + let fields = record_fields(value, 4, "frame", vm)?; + let mut location = [-1; 4]; + if !vm.is_none(&fields[1]) { + let values = record_fields(&fields[1], 4, "location", vm)?; + for (target, value) in location.iter_mut().zip(values) { + // Match CPython: C long is 32-bit on Windows, 64-bit on LP64. + #[allow(clippy::unnecessary_cast)] + let normalized = value.try_to_value::(vm).unwrap_or(-1) as i32; + *target = normalized; + } + } + let opcode = fields[3] + .try_to_value::(vm) + .ok() + .filter(|value| (0..=254).contains(value)) + .map_or(255, |value| value as u8); + Ok(binary::Frame { + filename: fields[0].try_to_value::(vm)?, + funcname: fields[2].try_to_value::(vm)?, + location, + opcode, + }) + } + + #[derive(FromArgs)] + struct BinaryWriterArgs { + #[pyarg(any)] + filename: PyObjectRef, + #[pyarg(any)] + sample_interval_us: u64, + #[pyarg(any)] + start_time_us: u64, + #[pyarg(named, default = 0)] + compression: i32, + #[pyarg(named, default = -1)] + mode: i32, + #[pyarg(named, default = -1)] + capture_features: i32, + } + + #[derive(Debug, Default, PartialEq, Eq)] + enum WriterStatus { + #[default] + Open, + LimitReached, + Broken, + } + + #[derive(Debug, Default)] + struct WriterState { + writer: Option, + cached_total_samples: u64, + status: WriterStatus, + generation: u64, + } + + #[pyattr] + #[pyclass(name = "BinaryWriter", module = "_remote_debugging")] + #[derive(Debug, PyPayload, Default)] + struct BinaryWriter { + state: PyMutex, + } + + impl DefaultConstructor for BinaryWriter {} + + impl Initializer for BinaryWriter { + type Args = BinaryWriterArgs; + fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { + if !(-1..=4).contains(&args.mode) { + return Err(vm.new_value_error("invalid profiling mode")); + } + if !(-1..=31).contains(&args.capture_features) { + return Err(vm.new_value_error("invalid capture features")); + } + let old = { + let mut state = zelf.state.lock(); + state.cached_total_samples = 0; + state.status = WriterStatus::Open; + state.generation = state.generation.wrapping_add(1); + state.writer.take() + }; + drop(old); + if args.compression == 1 { + return Err(vm.new_runtime_error( + "zstd compression requested but not available (HAVE_ZSTD not defined)", + )); + } + vm.audit("open", || (args.filename.clone(), "wb", 0))?; + let path = + FsPath::try_from_path_like(args.filename.clone(), true, vm)?.to_path_buf(vm)?; + let writer = binary::Writer::create( + &path, + args.sample_interval_us, + args.start_time_us, + args.compression, + args.mode, + args.capture_features, + [ + crate::vm::version::MAJOR as u8, + crate::vm::version::MINOR as u8, + crate::vm::version::MICRO as u8, + ], + ) + .map_err(|error| codec_path_error(error, args.filename, vm))?; + zelf.state.lock().writer = Some(writer); + Ok(()) + } + } + + #[derive(FromArgs)] + struct BinaryExitArgs { + #[pyarg(any, optional, name = "exc_type")] + _exc_type: Option, + #[pyarg(any, optional, name = "exc_val")] + _exc_value: Option, + #[pyarg(any, optional, name = "exc_tb")] + _exc_tb: Option, + } + + #[derive(FromArgs)] + struct SampleArgs { + #[pyarg(any)] + stack_frames: PyObjectRef, + #[pyarg(any)] + timestamp_us: PyObjectRef, + } + + fn profile_float(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + // PyFloat_AsDouble reads float subclasses without calling __float__. + Ok(match obj.downcast_ref::() { + Some(value) => value.to_f64(), + None => obj.try_float(vm)?.to_f64(), + }) + } + + #[derive(FromArgs)] + struct SetStatsArgs { + #[pyarg(any)] + duration_sec: PyObjectRef, + #[pyarg(any)] + sample_rate: PyObjectRef, + #[pyarg(any, optional)] + error_rate: Option, + #[pyarg(any, optional)] + missed_samples: Option, + } + + fn optional_float(value: Option, vm: &VirtualMachine) -> PyResult> { + value + .filter(|value| !vm.is_none(value)) + .map(|value| profile_float(&value, vm)) + .transpose() + } + + #[pyclass(with(Constructor, Initializer))] + impl BinaryWriter { + #[pymethod] + fn write_sample(zelf: &Py, args: SampleArgs, vm: &VirtualMachine) -> PyResult<()> { + let SampleArgs { + stack_frames, + timestamp_us, + } = args; + let timestamp_us = timestamp_us.try_into_value::(vm)?; + let (generation, error) = { + let mut state = zelf.state.lock(); + let error = if state.writer.is_none() { + Some("Writer is closed") + } else if state.status == WriterStatus::Broken { + Some("Writer is broken") + } else { + state.status = WriterStatus::Open; + None + }; + (state.generation, error) + }; + if let Some(error) = error { + return Err(vm.new_value_error(error)); + } + let result = + Self::write_sample_inner(zelf, &stack_frames, timestamp_us, generation, vm); + if result.is_err() { + let mut state = zelf.state.lock(); + if state.generation == generation + && state.writer.is_some() + && state.status != WriterStatus::LimitReached + { + state.status = WriterStatus::Broken; + } + } + result + } + + fn write_sample_inner( + zelf: &Py, + stack_frames: &PyObject, + timestamp_us: u64, + generation: u64, + vm: &VirtualMachine, + ) -> PyResult<()> { + for interpreter in list_items(stack_frames, "stack_frames", vm)? { + let fields = record_fields(&interpreter, 2, "interpreter", vm)?; + let interpreter_id = fields[0].try_to_value::(vm)?; + let interpreter_id = u32::try_from(interpreter_id).map_err(|_| { + { + let mut state = zelf.state.lock(); + if state.generation == generation && state.writer.is_some() { + state.status = WriterStatus::LimitReached; + } + } + vm.new_overflow_error(format!( + "interpreter_id {interpreter_id} exceeds maximum value {}", + u32::MAX + )) + })?; + for thread in list_items(&fields[1], "threads", vm)? { + let fields = record_fields(&thread, 3, "thread", vm)?; + let thread_id = fields[0].try_to_value::(vm)?; + let status = fields[1].try_to_value::(vm)? as u8; + let frame_objects = { + let list = fields[2] + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("frame_info must be a list"))?; + list.borrow_vec() + .iter() + .take(256) + .cloned() + .collect::>() + }; + let frames = frame_objects + .into_iter() + .map(|frame| normalize_frame(&frame, vm)) + .collect::>>()?; + let sample = binary::Sample { + interpreter_id, + thread_id, + status, + frames, + timestamp_us, + }; + // All Python conversions above have finished before borrowing file state. + let result = { + let mut state = zelf.state.lock(); + if state.generation == generation { + state + .writer + .as_mut() + .map(|writer| writer.write_sample(&sample)) + } else { + None + } + }; + result + .ok_or_else(|| vm.new_value_error("Writer is closed"))? + .map_err(|error| { + if matches!(error, binary::Error::Limit(_)) { + let mut state = zelf.state.lock(); + if state.generation == generation && state.writer.is_some() { + state.status = WriterStatus::LimitReached; + } + } + codec_error(error, vm) + })?; + } + } + Ok(()) + } + + #[pymethod] + fn set_stats(zelf: &Py, args: SetStatsArgs, vm: &VirtualMachine) -> PyResult<()> { + let duration_sec = profile_float(&args.duration_sec, vm)?; + let sample_rate = profile_float(&args.sample_rate, vm)?; + let is_open = zelf.state.lock().writer.is_some(); + if !is_open { + return Err(vm.new_value_error("Writer is closed")); + } + let profile = binary::ProfileStats { + duration_sec, + sample_rate, + error_rate: optional_float(args.error_rate, vm)?, + missed_samples: optional_float(args.missed_samples, vm)?, + }; + let result = { + let mut state = zelf.state.lock(); + state + .writer + .as_mut() + .map(|writer| writer.set_stats(profile)) + }; + result + .ok_or_else(|| vm.new_value_error("Writer is closed"))? + .map_err(|error| codec_error(error, vm)) + } + + #[pymethod] + fn finalize(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + let result = { + let mut state = zelf.state.lock(); + if state.writer.is_some() && state.status == WriterStatus::Broken { + Err(Some(binary::Error::Value("Writer is broken".to_owned()))) + } else if let Some(writer) = state.writer.as_mut() { + match writer.finalize() { + Ok(()) => { + state.cached_total_samples = writer.total_samples(); + state.generation = state.generation.wrapping_add(1); + Ok(state.writer.take()) + } + Err(error) => { + state.status = WriterStatus::Broken; + Err(Some(error)) + } + } + } else { + Err(None) + } + }; + match result { + Ok(_writer) => Ok(()), + Err(Some(error)) => Err(codec_error(error, vm)), + Err(None) => Err(vm.new_value_error("Writer is already closed")), + } + } + + #[pymethod] + fn close(zelf: &Py) { + let _writer = { + let mut state = zelf.state.lock(); + state.generation = state.generation.wrapping_add(1); + state.writer.take() + }; + } + + #[pygetset] + fn limit_reached(zelf: &Py) -> bool { + let state = zelf.state.lock(); + state.writer.is_some() && state.status == WriterStatus::LimitReached + } + + #[pygetset] + fn total_samples(zelf: &Py) -> u64 { + let state = zelf.state.lock(); + state + .writer + .as_ref() + .map_or(state.cached_total_samples, binary::Writer::total_samples) + } + + #[pymethod] + fn get_stats(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let stats = zelf + .state + .lock() + .writer + .as_ref() + .map(|writer| *writer.stats()); + let stats = stats.ok_or_else(|| vm.new_value_error("Writer is closed"))?; + let dict = vm.ctx.new_dict(); + for (key, value) in [ + ("repeat_records", stats.repeat_records), + ("repeat_samples", stats.repeat_samples), + ("full_records", stats.full_records), + ("suffix_records", stats.suffix_records), + ("pop_push_records", stats.pop_push_records), + ("total_records", stats.total_records()), + ("total_samples", stats.total_samples), + ("total_frames_written", stats.total_frames_written), + ("frames_saved", stats.frames_saved), + ("bytes_written", stats.bytes_written), + ] { + dict.set_item(key, value.to_pyobject(vm), vm)?; + } + dict.set_item( + "frame_compression_pct", + stats.frame_compression_pct().to_pyobject(vm), + vm, + )?; + Ok(dict) + } + + #[pymethod] + fn __enter__(zelf: PyRef) -> PyRef { + zelf + } + + #[pymethod] + fn __exit__(zelf: &Py, _args: BinaryExitArgs, vm: &VirtualMachine) -> PyResult { + let (is_open, broken) = { + let state = zelf.state.lock(); + (state.writer.is_some(), state.status == WriterStatus::Broken) + }; + if broken { + Self::close(zelf); + } else if is_open && let Err(error) = Self::finalize(zelf, vm) { + Self::close(zelf); + return Err(error); + } + Ok(false) + } + } + + #[derive(Debug)] + struct ReaderOpen { + reader: Arc, + stats: PyMutex, + replaying: AtomicBool, + } + + struct ReplayLease(PyRc); + impl Drop for ReplayLease { + fn drop(&mut self) { + self.0.replaying.store(false, Ordering::Release); + } + } + + #[pyattr] + #[pyclass(name = "BinaryReader", module = "_remote_debugging")] + #[derive(Debug, PyPayload, Default)] + struct BinaryReader { + state: PyMutex>>, + } + + impl DefaultConstructor for BinaryReader {} + + #[derive(FromArgs)] + struct BinaryReaderArgs { + #[pyarg(any)] + filename: PyObjectRef, + } + + impl Initializer for BinaryReader { + type Args = BinaryReaderArgs; + fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { + let old = zelf.state.lock().take(); + drop(old); + vm.audit("open", || (args.filename.clone(), "rb", 0))?; + let path = + FsPath::try_from_path_like(args.filename.clone(), true, vm)?.to_path_buf(vm)?; + let reader = binary::Reader::open(&path) + .map_err(|error| codec_path_error(error, args.filename, vm))?; + *zelf.state.lock() = Some(PyRc::new(ReaderOpen { + reader: Arc::new(reader), + stats: PyMutex::new(binary::ReaderStats::default()), + replaying: AtomicBool::new(false), + })); + Ok(()) + } + } + + fn replay_records(sample: &binary::Sample, vm: &VirtualMachine) -> PyObjectRef { + let frames = sample + .frames + .iter() + .map(|frame| { + let location = if frame.location[0] == -1 { + vm.ctx.none() + } else { + vm.ctx + .new_tuple( + frame + .location + .iter() + .map(|value| value.to_pyobject(vm)) + .collect(), + ) + .into() + }; + FrameInfo::from_data( + FrameInfoData { + filename: frame.filename.clone().to_pyobject(vm), + location, + funcname: frame.funcname.clone().to_pyobject(vm), + opcode: if frame.opcode == 255 { + vm.ctx.none() + } else { + frame.opcode.to_pyobject(vm) + }, + }, + vm, + ) + .into() + }) + .collect(); + let thread = ThreadInfo::from_data( + ThreadInfoData { + thread_id: sample.thread_id.to_pyobject(vm), + status: sample.status.to_pyobject(vm), + frame_info: vm.ctx.new_list(frames).into(), + }, + vm, + ); + let interpreter = InterpreterInfo::from_data( + InterpreterInfoData { + interpreter_id: sample.interpreter_id.to_pyobject(vm), + threads: vm.ctx.new_list(vec![thread.into()]).into(), + }, + vm, + ); + vm.ctx.new_list(vec![interpreter.into()]).into() + } + + #[derive(FromArgs)] + struct ReplayArgs { + #[pyarg(any)] + collector: PyObjectRef, + #[pyarg(any, optional)] + progress_callback: Option, + } + + #[pyclass(with(Constructor, Initializer))] + impl BinaryReader { + fn opened(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + let open = zelf.state.lock().clone(); + open.ok_or_else(|| vm.new_value_error("Reader is closed")) + } + + #[pymethod] + fn close(zelf: &Py) { + let _old = zelf.state.lock().take(); + } + + #[pygetset] + fn sample_count(zelf: &Py) -> u64 { + zelf.state + .lock() + .as_ref() + .map_or(0, |open| open.reader.metadata().sample_count) + } + + #[pygetset] + fn sample_interval_us(zelf: &Py) -> u64 { + zelf.state + .lock() + .as_ref() + .map_or(0, |open| open.reader.metadata().sample_interval_us) + } + + #[pymethod] + fn get_info(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let open = Self::opened(zelf, vm)?; + let info = open.reader.metadata(); + let dict = vm.ctx.new_dict(); + dict.set_item("version", info.version.to_pyobject(vm), vm)?; + dict.set_item( + "python_version", + vm.ctx + .new_tuple( + info.python_version + .iter() + .map(|value| value.to_pyobject(vm)) + .collect(), + ) + .into(), + vm, + )?; + for (key, value) in [ + ("start_time_us", info.start_time_us), + ("sample_interval_us", info.sample_interval_us), + ("sample_count", info.sample_count), + ("thread_count", u64::from(info.thread_count)), + ("string_count", u64::from(info.string_count)), + ("frame_count", u64::from(info.frame_count)), + ] { + dict.set_item(key, value.to_pyobject(vm), vm)?; + } + dict.set_item( + "compression_type", + (info.compression_type as i32).to_pyobject(vm), + vm, + )?; + dict.set_item("mode", info.mode.to_pyobject(vm), vm)?; + dict.set_item( + "capture_features", + info.capture_features.to_pyobject(vm), + vm, + )?; + let profile = info.profile_stats.as_ref(); + for (key, value) in [ + ("duration_sec", profile.map(|value| value.duration_sec)), + ("sample_rate", profile.map(|value| value.sample_rate)), + ("error_rate", profile.and_then(|value| value.error_rate)), + ( + "missed_samples", + profile.and_then(|value| value.missed_samples), + ), + ] { + dict.set_item(key, value.to_pyobject(vm), vm)?; + } + Ok(dict) + } + + #[pymethod] + fn get_stats(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let open = Self::opened(zelf, vm)?; + let stats = *open.stats.lock(); + let dict = vm.ctx.new_dict(); + for (key, value) in [ + ("repeat_records", stats.repeat_records), + ("repeat_samples", stats.repeat_samples), + ("full_records", stats.full_records), + ("suffix_records", stats.suffix_records), + ("pop_push_records", stats.pop_push_records), + ("total_records", stats.total_records()), + ("total_samples", stats.total_samples), + ("stack_reconstructions", stats.stack_reconstructions), + ] { + dict.set_item(key, value.to_pyobject(vm), vm)?; + } + Ok(dict) + } + + #[pymethod] + fn replay(zelf: &Py, args: ReplayArgs, vm: &VirtualMachine) -> PyResult { + let open = Self::opened(zelf, vm)?; + if open + .replaying + .compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed) + .is_err() + { + return Err(vm.new_runtime_error("A replay is already active on this reader")); + } + let _lease = ReplayLease(open.clone()); + // The per-open snapshot survives close/reinitialization, but cannot + // publish counters into a replacement reader. No lock crosses Python. + let initial_collect = args.collector.get_attr("collect", vm).map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.attribute_error) { + vm.new_type_error("Collector must have a collect() method") + } else { + error + } + })?; + drop(initial_collect); + let progress = args.progress_callback.filter(|value| !vm.is_none(value)); + let total = open.reader.metadata().sample_count; + if let Some(callback) = &progress { + callback.call((0_u64, total), vm)?; + } + let mut replay = open.reader.replay(); + let mut committed_samples = 0; + loop { + let batch = replay.next_batch(); + let mut stats = *replay.stats(); + stats.total_samples = committed_samples; + *open.stats.lock() = stats; + let Some(batch) = batch.map_err(|error| codec_error(error, vm))? else { + break; + }; + let records = replay_records(&batch.sample, vm); + let timestamps: PyObjectRef = vm + .ctx + .new_list( + batch + .timestamps + .iter() + .map(|value| value.to_pyobject(vm)) + .collect(), + ) + .into(); + args.collector + .get_attr("collect", vm)? + .call((records, timestamps), vm)?; + if batch.record_complete { + committed_samples = replay.replayed(); + *open.stats.lock() = *replay.stats(); + if let Some(callback) = &progress { + if batch.is_repeat + && committed_samples % 1000 < u64::from(batch.record_samples) + { + callback.call((committed_samples, total), vm)?; + } + if committed_samples % 1000 == 0 { + callback.call((committed_samples, total), vm)?; + } + } + } + } + if let Some(callback) = &progress { + callback.call((replay.replayed(), total), vm)?; + } + Ok(replay.replayed()) + } + + #[pymethod] + fn __enter__(zelf: PyRef) -> PyRef { + zelf + } + + #[pymethod] + fn __exit__(zelf: &Py, _args: BinaryExitArgs) -> bool { + Self::close(zelf); + false + } + } + #[pyattr] #[pyclass(name = "RemoteUnwinder", module = "_remote_debugging")] #[derive(Debug, PyPayload)] diff --git a/crates/stdlib/src/_remote_debugging/binary.rs b/crates/stdlib/src/_remote_debugging/binary.rs new file mode 100644 index 00000000000..6c984d895f3 --- /dev/null +++ b/crates/stdlib/src/_remote_debugging/binary.rs @@ -0,0 +1,1390 @@ +//! Offline sampling files, compatible with CPython's version-one TACH format. +//! +//! Only the sample stream is compressible. This implementation writes raw +//! samples and explicitly rejects zstd instead of misidentifying raw data. + +use alloc::sync::Arc; +use std::{ + collections::HashMap, + fs::File, + io::{self, BufWriter, Read, Seek, SeekFrom, Write}, + path::Path, +}; + +pub(crate) const FORMAT_VERSION: u32 = 1; +const MAGIC: u32 = 0x5441_4348; +const HEADER_SIZE: usize = 64; +const FOOTER_SIZE: usize = 32; +const STATS_SIZE: usize = 56; +const STACK_LIMIT: usize = 256; +const WRITE_BUFFER_SIZE: usize = 512 * 1024; +const REPEAT_BUFFER_SIZE: usize = 16 * 1024; +const FULL: u8 = 1; +const SUFFIX: u8 = 2; +const POP_PUSH: u8 = 3; +const REPEAT: u8 = 0; + +#[derive(Debug)] +pub(crate) enum Error { + Io(io::Error), + Value(String), + Overflow(&'static str), + Limit(&'static str), + Memory, + Runtime(&'static str), +} + +pub(crate) type Result = core::result::Result; + +impl From for Error { + fn from(error: io::Error) -> Self { + Self::Io(error) + } +} + +fn format_table_limit(error: Error) -> Error { + match error { + Error::Overflow(message) => Error::Limit(message), + error => error, + } +} + +fn invalid(message: impl Into) -> Error { + Error::Value(message.into()) +} + +fn reserve(values: &mut Vec, additional: usize) -> Result<()> { + let capacity = values + .len() + .checked_add(additional) + .ok_or(Error::Overflow("Array capacity overflow"))?; + let allocation = capacity + .checked_mul(core::mem::size_of::()) + .ok_or(Error::Overflow("Array allocation size overflow"))?; + if allocation > isize::MAX as usize { + return Err(Error::Overflow("Array allocation size overflow")); + } + values.try_reserve(additional).map_err(|_| Error::Memory) +} + +fn copy_string(value: &str) -> Result { + let mut result = String::new(); + result.try_reserve(value.len()).map_err(|_| Error::Memory)?; + result.push_str(value); + Ok(result) +} + +fn push_varint(bytes: &mut Vec, mut value: u64) -> Result<()> { + reserve(bytes, 10)?; + while value >= 0x80 { + bytes.push((value as u8 & 0x7f) | 0x80); + value >>= 7; + } + bytes.push(value as u8); + Ok(()) +} + +fn push_signed(bytes: &mut Vec, value: i32) -> Result<()> { + push_varint( + bytes, + (((value as u32) << 1) ^ ((value >> 31) as u32)).into(), + ) +} + +fn add(counter: &mut u64, value: u64) -> Result<()> { + *counter = counter + .checked_add(value) + .ok_or(Error::Overflow("Sample statistics overflow"))?; + Ok(()) +} + +#[derive(Debug)] +pub(crate) struct Frame { + pub(crate) filename: String, + pub(crate) funcname: String, + pub(crate) location: [i32; 4], + pub(crate) opcode: u8, +} + +#[derive(Debug)] +pub(crate) struct Sample { + pub(crate) interpreter_id: u32, + pub(crate) thread_id: u64, + pub(crate) status: u8, + pub(crate) frames: Vec, + pub(crate) timestamp_us: u64, +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct ProfileStats { + pub(crate) duration_sec: f64, + pub(crate) sample_rate: f64, + pub(crate) error_rate: Option, + pub(crate) missed_samples: Option, +} + +impl ProfileStats { + fn validate(&self) -> Result<()> { + if !self.duration_sec.is_finite() || self.duration_sec < 0.0 { + return Err(invalid("duration must be a finite non-negative value")); + } + if !self.sample_rate.is_finite() || self.sample_rate < 0.0 { + return Err(invalid("sample rate must be a finite non-negative value")); + } + if self + .error_rate + .is_some_and(|value| !value.is_finite() || value < 0.0) + { + return Err(invalid("error rate must be a finite non-negative value")); + } + if self.missed_samples.is_some_and(|value| !value.is_finite()) { + return Err(invalid("missed samples must be a finite value")); + } + Ok(()) + } +} + +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct WriterStats { + pub(crate) repeat_records: u64, + pub(crate) repeat_samples: u64, + pub(crate) full_records: u64, + pub(crate) suffix_records: u64, + pub(crate) pop_push_records: u64, + pub(crate) total_samples: u64, + pub(crate) total_frames_written: u64, + pub(crate) frames_saved: u64, + pub(crate) bytes_written: u64, +} + +impl WriterStats { + pub(crate) fn total_records(&self) -> u64 { + self.repeat_records + self.full_records + self.suffix_records + self.pop_push_records + } + + pub(crate) fn frame_compression_pct(&self) -> f64 { + let potential = self.total_frames_written as f64 + self.frames_saved as f64; + if potential == 0.0 { + 0.0 + } else { + self.frames_saved as f64 / potential * 100.0 + } + } +} + +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct ReaderStats { + pub(crate) repeat_records: u64, + pub(crate) repeat_samples: u64, + pub(crate) full_records: u64, + pub(crate) suffix_records: u64, + pub(crate) pop_push_records: u64, + pub(crate) total_samples: u64, + pub(crate) stack_reconstructions: u64, +} + +impl ReaderStats { + pub(crate) fn total_records(&self) -> u64 { + self.repeat_records + self.full_records + self.suffix_records + self.pop_push_records + } +} + +#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] +struct FrameEntry { + filename: u32, + funcname: u32, + location: [i32; 4], + opcode: u8, +} + +#[derive(Debug)] +struct WriterThread { + thread_id: u64, + interpreter_id: u32, + timestamp: u64, + stack: [u32; STACK_LIMIT], + depth: usize, + pending: Vec, + pending_count: u32, +} + +#[derive(Debug)] +pub(crate) struct Writer { + file: Option>, + buffer: Vec, + strings: Vec, + string_indices: HashMap, + frames: Vec, + frame_indices: HashMap, + threads: Vec, + thread_indices: HashMap<(u64, u32), usize>, + interval: u64, + start: u64, + compression: i32, + mode: i32, + features: i32, + python_version: [u8; 3], + profile: Option, + stats: WriterStats, +} + +impl Writer { + #[allow(clippy::too_many_arguments)] + pub(crate) fn create( + path: &Path, + interval: u64, + start: u64, + compression: i32, + mode: i32, + features: i32, + python_version: [u8; 3], + ) -> Result { + if !(-1..=4).contains(&mode) { + return Err(invalid("invalid profiling mode")); + } + if !(-1..=31).contains(&features) { + return Err(invalid("invalid capture features")); + } + let mut buffer = Vec::new(); + reserve(&mut buffer, WRITE_BUFFER_SIZE)?; + let mut file = BufWriter::new(rustpython_host_env::fs::create(path)?); + file.write_all(&[0; HEADER_SIZE])?; + Ok(Self { + file: Some(file), + buffer, + strings: Vec::new(), + string_indices: HashMap::new(), + frames: Vec::new(), + frame_indices: HashMap::new(), + threads: Vec::new(), + thread_indices: HashMap::new(), + interval, + start, + compression, + mode, + features, + python_version, + profile: None, + stats: WriterStats::default(), + }) + } + + fn file(&mut self) -> Result<&mut BufWriter> { + self.file + .as_mut() + .ok_or_else(|| invalid("Writer is closed")) + } + + fn flush_buffer(&mut self) -> Result<()> { + if !self.buffer.is_empty() { + self.file + .as_mut() + .ok_or_else(|| invalid("Writer is closed"))? + .write_all(&self.buffer)?; + self.buffer.clear(); + } + Ok(()) + } + + fn write_bytes(&mut self, mut bytes: &[u8]) -> Result<()> { + let length = bytes.len() as u64; + while !bytes.is_empty() { + let count = bytes.len().min(WRITE_BUFFER_SIZE - self.buffer.len()); + self.buffer.extend_from_slice(&bytes[..count]); + bytes = &bytes[count..]; + if self.buffer.len() == WRITE_BUFFER_SIZE { + self.flush_buffer()?; + } + } + add(&mut self.stats.bytes_written, length) + } + + fn intern_string(&mut self, value: &str) -> Result { + if let Some(index) = self.string_indices.get(value) { + return Ok(*index); + } + if self.strings.len() >= u32::MAX as usize { + return Err(Error::Limit("too many strings for binary format")); + } + if value.len() > u32::MAX as usize { + return Err(Error::Limit("string length exceeds binary format maximum")); + } + reserve(&mut self.strings, 1).map_err(format_table_limit)?; + self.string_indices + .try_reserve(1) + .map_err(|_| Error::Memory)?; + let stored = copy_string(value)?; + let key = copy_string(value)?; + let index = self.strings.len() as u32; + self.strings.push(stored); + self.string_indices.insert(key, index); + Ok(index) + } + + fn intern_frame(&mut self, frame: &Frame) -> Result { + let entry = FrameEntry { + filename: self.intern_string(&frame.filename)?, + funcname: self.intern_string(&frame.funcname)?, + location: frame.location, + opcode: frame.opcode, + }; + if let Some(index) = self.frame_indices.get(&entry) { + return Ok(*index); + } + if self.frames.len() >= u32::MAX as usize { + return Err(Error::Limit("too many frames for binary format")); + } + // Reject unrepresentable deltas before adding a frame to the table. + location_delta(entry.location[0], entry.location[1])?; + location_delta(entry.location[2], entry.location[3])?; + reserve(&mut self.frames, 1).map_err(format_table_limit)?; + self.frame_indices + .try_reserve(1) + .map_err(|_| Error::Memory)?; + let index = self.frames.len() as u32; + self.frames.push(entry); + self.frame_indices.insert(entry, index); + Ok(index) + } + + fn thread(&mut self, thread_id: u64, interpreter_id: u32) -> Result { + let key = (thread_id, interpreter_id); + if let Some(index) = self.thread_indices.get(&key) { + return Ok(*index); + } + if self.threads.len() >= u32::MAX as usize { + return Err(Error::Limit("too many threads for binary format")); + } + reserve(&mut self.threads, 1).map_err(format_table_limit)?; + self.thread_indices + .try_reserve(1) + .map_err(|_| Error::Memory)?; + let index = self.threads.len(); + self.threads.push(WriterThread { + thread_id, + interpreter_id, + timestamp: self.start, + stack: [0; STACK_LIMIT], + depth: 0, + pending: Vec::new(), + pending_count: 0, + }); + self.thread_indices.insert(key, index); + Ok(index) + } + + fn flush_repeat(&mut self, index: usize) -> Result<()> { + let thread = &self.threads[index]; + if thread.pending_count == 0 { + return Ok(()); + } + let count = thread.pending_count; + let saved = u64::from(count) * thread.depth as u64; + let mut header = record_header(thread.thread_id, thread.interpreter_id, REPEAT)?; + push_varint(&mut header, count.into())?; + self.write_bytes(&header)?; + let mut pending = core::mem::take(&mut self.threads[index].pending); + let result = self.write_bytes(&pending); + if result.is_ok() { + pending.clear(); + self.threads[index].pending_count = 0; + } + self.threads[index].pending = pending; + result?; + add(&mut self.stats.repeat_records, 1)?; + add(&mut self.stats.repeat_samples, count.into())?; + add(&mut self.stats.frames_saved, saved) + } + + pub(crate) fn write_sample(&mut self, sample: &Sample) -> Result<()> { + self.file()?; + if self.stats.total_samples == u64::MAX { + return Err(Error::Limit("too many samples for binary format")); + } + let mut stack = [0; STACK_LIMIT]; + let depth = sample.frames.len().min(STACK_LIMIT); + for (slot, frame) in stack.iter_mut().zip(sample.frames.iter()).take(depth) { + *slot = self.intern_frame(frame)?; + } + let index = self.thread(sample.thread_id, sample.interpreter_id)?; + let thread = &self.threads[index]; + let delta = sample.timestamp_us.wrapping_sub(thread.timestamp); + let previous = &thread.stack[..thread.depth]; + let current = &stack[..depth]; + if previous == current { + if thread.pending.len() + 11 > REPEAT_BUFFER_SIZE { + self.flush_repeat(index)?; + } + let thread = &mut self.threads[index]; + reserve(&mut thread.pending, 11)?; + push_varint(&mut thread.pending, delta)?; + thread.pending.push(sample.status); + thread.pending_count += 1; + } else { + let shared = previous + .iter() + .rev() + .zip(current.iter().rev()) + .take_while(|(left, right)| left == right) + .count(); + let pop = previous.len() - shared; + let push = depth - shared; + let encoding = if shared == 0 { + FULL + } else if pop == 0 && push > 0 { + SUFFIX + } else if shared < depth / 2 { + FULL + } else { + POP_PUSH + }; + self.flush_repeat(index)?; + let mut record = record_header(sample.thread_id, sample.interpreter_id, encoding)?; + push_varint(&mut record, delta)?; + reserve(&mut record, 1)?; + record.push(sample.status); + let written = match encoding { + FULL => { + push_varint(&mut record, depth as u64)?; + depth + } + SUFFIX => { + push_varint(&mut record, shared as u64)?; + push_varint(&mut record, push as u64)?; + push + } + _ => { + push_varint(&mut record, pop as u64)?; + push_varint(&mut record, push as u64)?; + push + } + }; + for &frame in &stack[..written] { + push_varint(&mut record, frame.into())?; + } + self.write_bytes(&record)?; + match encoding { + FULL => add(&mut self.stats.full_records, 1)?, + SUFFIX => add(&mut self.stats.suffix_records, 1)?, + _ => add(&mut self.stats.pop_push_records, 1)?, + } + add(&mut self.stats.total_frames_written, written as u64)?; + if encoding != FULL { + add(&mut self.stats.frames_saved, shared as u64)?; + } + self.threads[index].stack = stack; + self.threads[index].depth = depth; + } + self.threads[index].timestamp = sample.timestamp_us; + add(&mut self.stats.total_samples, 1) + } + + pub(crate) fn set_stats(&mut self, stats: ProfileStats) -> Result<()> { + self.file()?; + stats.validate()?; + self.profile = Some(stats); + Ok(()) + } + + pub(crate) fn stats(&self) -> &WriterStats { + &self.stats + } + + pub(crate) fn total_samples(&self) -> u64 { + self.stats.total_samples + } + + pub(crate) fn finalize(&mut self) -> Result<()> { + if self.file.is_none() { + return Err(invalid("Writer is already closed")); + } + for index in 0..self.threads.len() { + self.flush_repeat(index)?; + } + self.flush_buffer()?; + let string_offset = self.file()?.stream_position()?; + let mut scratch = Vec::new(); + reserve(&mut scratch, 64)?; + let file = self + .file + .as_mut() + .ok_or_else(|| invalid("Writer is closed"))?; + for string in &self.strings { + scratch.clear(); + push_varint(&mut scratch, string.len() as u64)?; + file.write_all(&scratch)?; + file.write_all(string.as_bytes())?; + } + let frame_offset = file.stream_position()?; + for frame in &self.frames { + scratch.clear(); + push_varint(&mut scratch, frame.filename.into())?; + push_varint(&mut scratch, frame.funcname.into())?; + push_signed(&mut scratch, frame.location[0])?; + push_signed( + &mut scratch, + location_delta(frame.location[0], frame.location[1])?, + )?; + push_signed(&mut scratch, frame.location[2])?; + push_signed( + &mut scratch, + location_delta(frame.location[2], frame.location[3])?, + )?; + reserve(&mut scratch, 1)?; + scratch.push(frame.opcode); + file.write_all(&scratch)?; + } + if let Some(stats) = self.profile { + let mut bytes = [0; STATS_SIZE]; + bytes[0..8].copy_from_slice(&stats.duration_sec.to_ne_bytes()); + bytes[8..16].copy_from_slice(&stats.sample_rate.to_ne_bytes()); + bytes[16..24].copy_from_slice(&stats.error_rate.unwrap_or(0.0).to_ne_bytes()); + bytes[24..32].copy_from_slice(&stats.missed_samples.unwrap_or(0.0).to_ne_bytes()); + let present = u32::from(stats.error_rate.is_some()) + | (u32::from(stats.missed_samples.is_some()) << 1); + bytes[32..36].copy_from_slice(&present.to_ne_bytes()); + bytes[40..48].copy_from_slice(b"TACHSTAT"); + bytes[48..52].copy_from_slice(&1_u32.to_ne_bytes()); + bytes[52..56].copy_from_slice(&(STATS_SIZE as u32).to_ne_bytes()); + file.write_all(&bytes)?; + } + let file_size = file + .stream_position()? + .checked_add(FOOTER_SIZE as u64) + .ok_or(Error::Overflow("File size exceeds binary format maximum"))?; + let mut footer = [0; FOOTER_SIZE]; + footer[0..4].copy_from_slice(&(self.strings.len() as u32).to_ne_bytes()); + footer[4..8].copy_from_slice(&(self.frames.len() as u32).to_ne_bytes()); + footer[8..16].copy_from_slice(&file_size.to_ne_bytes()); + file.write_all(&footer)?; + let mut header = [0; HEADER_SIZE]; + header[0..4].copy_from_slice(&MAGIC.to_ne_bytes()); + header[4..8].copy_from_slice(&FORMAT_VERSION.to_ne_bytes()); + header[8..11].copy_from_slice(&self.python_version); + header[12..20].copy_from_slice(&self.start.to_ne_bytes()); + header[20..28].copy_from_slice(&self.interval.to_ne_bytes()); + header[28..36].copy_from_slice(&self.stats.total_samples.to_ne_bytes()); + header[36..40].copy_from_slice(&(self.threads.len() as u32).to_ne_bytes()); + header[40..48].copy_from_slice(&string_offset.to_ne_bytes()); + header[48..56].copy_from_slice(&frame_offset.to_ne_bytes()); + header[56..60].copy_from_slice(&(self.compression as u32).to_ne_bytes()); + let mut config = (self.mode + 1) as u32; + if self.features >= 0 { + config |= 8 | ((self.features as u32) << 4); + } + header[60..64].copy_from_slice(&config.to_ne_bytes()); + file.seek(SeekFrom::Start(0))?; + file.write_all(&header)?; + file.flush()?; + self.file.take(); + Ok(()) + } +} + +fn location_delta(start: i32, end: i32) -> Result { + if start == -1 || end == -1 { + Ok(0) + } else { + end.checked_sub(start) + .ok_or(Error::Overflow("Source location delta exceeds i32 range")) + } +} + +fn record_header(thread: u64, interpreter: u32, encoding: u8) -> Result> { + let mut bytes = Vec::new(); + reserve(&mut bytes, 32)?; + bytes.extend_from_slice(&thread.to_ne_bytes()); + bytes.extend_from_slice(&interpreter.to_ne_bytes()); + bytes.push(encoding); + Ok(bytes) +} + +#[derive(Clone, Copy, Debug)] +enum Endian { + Little, + Big, +} + +impl Endian { + fn u32(self, bytes: [u8; 4]) -> u32 { + match self { + Self::Little => u32::from_le_bytes(bytes), + Self::Big => u32::from_be_bytes(bytes), + } + } + + fn u64(self, bytes: [u8; 8]) -> u64 { + match self { + Self::Little => u64::from_le_bytes(bytes), + Self::Big => u64::from_be_bytes(bytes), + } + } +} + +struct Cursor<'a> { + data: &'a [u8], + offset: usize, +} + +impl<'a> Cursor<'a> { + fn new(data: &'a [u8]) -> Self { + Self { data, offset: 0 } + } + + fn remaining(&self) -> usize { + self.data.len() - self.offset + } + + fn bytes(&mut self, count: usize) -> Result<&'a [u8]> { + let end = self + .offset + .checked_add(count) + .ok_or_else(|| invalid("Unexpected end of binary data"))?; + let result = self + .data + .get(self.offset..end) + .ok_or_else(|| invalid("Unexpected end of binary data"))?; + self.offset = end; + Ok(result) + } + + fn fixed(&mut self) -> Result<[u8; N]> { + self.bytes(N)? + .try_into() + .map_err(|_| invalid("Unexpected end of binary data")) + } + + fn byte(&mut self) -> Result { + Ok(self.fixed::<1>()?[0]) + } + + fn varint(&mut self) -> Result { + let mut pos = self.offset; + let mut value = 0_u64; + for shift in (0..=63).step_by(7) { + let byte = *self + .data + .get(pos) + .ok_or_else(|| invalid("Invalid or incomplete varint in binary data"))?; + pos += 1; + if shift == 63 && byte & 0xfe != 0 { + return Err(invalid("Invalid or incomplete varint in binary data")); + } + value |= u64::from(byte & 0x7f) << shift; + if byte & 0x80 == 0 { + self.offset = pos; + return Ok(value); + } + } + Err(invalid("Invalid or incomplete varint in binary data")) + } + + fn var_u32(&mut self) -> Result { + let previous = self.offset; + let value = self.varint()?; + match u32::try_from(value) { + Ok(value) => Ok(value), + Err(_) => { + self.offset = previous; + Err(invalid("Invalid or incomplete varint in binary data")) + } + } + } + + fn signed(&mut self) -> Result { + let value = self.var_u32()?; + Ok(((value >> 1) as i32) ^ -((value & 1) as i32)) + } +} + +#[derive(Clone, Copy, Debug)] +pub(crate) struct Metadata { + pub(crate) version: u32, + pub(crate) python_version: [u8; 3], + pub(crate) start_time_us: u64, + pub(crate) sample_interval_us: u64, + pub(crate) sample_count: u64, + pub(crate) thread_count: u32, + pub(crate) string_count: u32, + pub(crate) frame_count: u32, + pub(crate) compression_type: u32, + pub(crate) mode: Option, + pub(crate) capture_features: Option, + pub(crate) profile_stats: Option, +} + +/// The snapshot and parsed tables use memory proportional to actual file bytes, +/// not header sample counts. Repeat timestamps are expanded only one batch at a +/// time, and every batch is bounded by encoded bytes remaining in the snapshot. +#[derive(Debug)] +pub(crate) struct Reader { + data: Vec, + sample_end: usize, + endian: Endian, + strings: Vec, + frames: Vec, + metadata: Metadata, +} + +impl Reader { + pub(crate) fn open(path: &Path) -> Result { + let mut file = rustpython_host_env::fs::open(path)?; + let mut data = Vec::new(); + let mut chunk = [0; 64 * 1024]; + loop { + let count = match file.read(&mut chunk) { + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + result => result?, + }; + if count == 0 { + break; + } + reserve(&mut data, count)?; + data.extend_from_slice(&chunk[..count]); + } + Self::parse(data) + } + + fn parse(data: Vec) -> Result { + if data.len() < HEADER_SIZE { + return Err(invalid("File too small for header")); + } + if data.len() < HEADER_SIZE + FOOTER_SIZE { + return Err(invalid("File too small for footer")); + } + let mut header = Cursor::new(&data[..HEADER_SIZE]); + let magic = header.fixed::<4>()?; + let endian = if u32::from_le_bytes(magic) == MAGIC { + Endian::Little + } else if u32::from_be_bytes(magic) == MAGIC { + Endian::Big + } else { + return Err(invalid(format!( + "Invalid magic number: 0x{:08x}", + u32::from_ne_bytes(magic) + ))); + }; + let version = endian.u32(header.fixed()?); + let python_version = header.fixed::<3>()?; + header.byte()?; + if version != FORMAT_VERSION { + return Err(invalid(if version > FORMAT_VERSION { + format!( + "Binary file was created with Python {}.{}.{} (format version {}), \ + but this reader supports format version {}", + python_version[0], + python_version[1], + python_version[2], + version, + FORMAT_VERSION + ) + } else { + format!( + "Unsupported format version {version} (this reader supports version {FORMAT_VERSION})" + ) + })); + } + let start_time_us = endian.u64(header.fixed()?); + let sample_interval_us = endian.u64(header.fixed()?); + let sample_count = endian.u64(header.fixed()?); + let thread_count = endian.u32(header.fixed()?); + let string_offset = endian.u64(header.fixed()?); + let frame_offset = endian.u64(header.fixed()?); + let compression_type = endian.u32(header.fixed()?); + let config = endian.u32(header.fixed()?); + let mode = config & 7; + if mode > 5 { + return Err(invalid(format!("Invalid profiling mode in header: {mode}"))); + } + let footer_start = data.len() - FOOTER_SIZE; + let mut footer = Cursor::new(&data[footer_start..]); + let string_count = endian.u32(footer.fixed()?); + let frame_count = endian.u32(footer.fixed()?); + let (profile_stats, _) = parse_profile_stats(&data, endian, footer_start)?; + for (name, offset) in [("string", string_offset), ("frame", frame_offset)] { + if offset > data.len() as u64 { + return Err(invalid(format!( + "Invalid {name} table offset: {offset} exceeds file size {}", + data.len() + ))); + } + if offset < HEADER_SIZE as u64 { + return Err(invalid(format!( + "Invalid {name} table offset: {offset} is before data section" + ))); + } + } + if string_offset > frame_offset { + return Err(invalid(format!( + "Invalid table offsets: string table ({string_offset}) is after frame table ({frame_offset})" + ))); + } + let string_offset = usize::try_from(string_offset) + .map_err(|_| Error::Overflow("File is too large to read"))?; + let frame_offset = usize::try_from(frame_offset) + .map_err(|_| Error::Overflow("File is too large to read"))?; + if compression_type == 1 { + return Err(Error::Runtime( + "File uses zstd compression but zstd support not compiled in", + )); + } + // CPython bounds table entries by the remaining file bytes, including + // subsequent sections. Keep the count and cursor checks anchored to EOF. + let mut string_data = Cursor::new(&data[string_offset..]); + validate_count("string", string_count, string_data.remaining(), 1)?; + let mut strings = Vec::new(); + reserve(&mut strings, string_count as usize)?; + for _ in 0..string_count { + let length = string_data + .var_u32() + .map_err(|_| invalid("Malformed varint in string table"))?; + let bytes = string_data + .bytes(length as usize) + .map_err(|_| invalid("String table overflow"))?; + strings.push(decode_utf8_replacing(bytes)?); + } + let mut frame_data = Cursor::new(&data[frame_offset..]); + validate_count("frame", frame_count, frame_data.remaining(), 7)?; + let mut frames = Vec::new(); + reserve(&mut frames, frame_count as usize)?; + for _ in 0..frame_count { + let filename = frame_data + .var_u32() + .map_err(|_| invalid("Malformed varint in frame table (filename)"))?; + let funcname = frame_data + .var_u32() + .map_err(|_| invalid("Malformed varint in frame table (funcname)"))?; + let line = frame_data + .signed() + .map_err(|_| invalid("Malformed varint in frame table (lineno)"))?; + let line_delta = frame_data + .signed() + .map_err(|_| invalid("Malformed varint in frame table (end_lineno_delta)"))?; + let column = frame_data + .signed() + .map_err(|_| invalid("Malformed varint in frame table (column)"))?; + let column_delta = frame_data + .signed() + .map_err(|_| invalid("Malformed varint in frame table (end_column_delta)"))?; + let opcode = frame_data + .byte() + .map_err(|_| invalid("Unexpected end of frame table (opcode)"))?; + frames.push(FrameEntry { + filename, + funcname, + location: [ + line, + reconstruct_location(line, line_delta)?, + column, + reconstruct_location(column, column_delta)?, + ], + opcode, + }); + } + Ok(Self { + data, + sample_end: string_offset, + endian, + strings, + frames, + metadata: Metadata { + version, + python_version, + start_time_us, + sample_interval_us, + sample_count, + thread_count, + string_count, + frame_count, + compression_type, + mode: (mode != 0).then_some(mode as i32 - 1), + capture_features: (config & 8 != 0).then_some(((config >> 4) & 31) as i32), + profile_stats, + }, + }) + } + + pub(crate) fn metadata(&self) -> &Metadata { + &self.metadata + } + + pub(crate) fn replay(self: &Arc) -> Replay { + Replay { + reader: Arc::clone(self), + offset: HEADER_SIZE, + threads: Vec::new(), + thread_indices: HashMap::new(), + repeat: None, + stats: ReaderStats::default(), + finished: false, + } + } + + fn build_sample(&self, thread: &ReaderThread, status: u8, timestamp_us: u64) -> Result { + let mut frames = Vec::new(); + reserve(&mut frames, thread.depth)?; + for &index in &thread.stack[..thread.depth] { + let frame = self + .frames + .get(index as usize) + .ok_or_else(|| invalid(format!("Invalid frame index: {index}")))?; + let filename = self + .strings + .get(frame.filename as usize) + .ok_or_else(|| invalid("Invalid string index in frame"))?; + let funcname = self + .strings + .get(frame.funcname as usize) + .ok_or_else(|| invalid("Invalid string index in frame"))?; + frames.push(Frame { + filename: copy_string(filename)?, + funcname: copy_string(funcname)?, + location: frame.location, + opcode: frame.opcode, + }); + } + Ok(Sample { + interpreter_id: thread.interpreter_id, + thread_id: thread.thread_id, + status, + frames, + timestamp_us, + }) + } +} + +fn reconstruct_location(start: i32, delta: i32) -> Result { + if start == -1 { + Ok(-1) + } else { + start + .checked_add(delta) + .ok_or_else(|| invalid("Source location exceeds i32 range")) + } +} + +fn validate_count(name: &str, count: u32, available: usize, minimum: usize) -> Result<()> { + let maximum = available / minimum; + if count as u64 > maximum as u64 { + return Err(invalid(format!( + "Invalid {name} count {count} exceeds maximum possible {maximum}" + ))); + } + Ok(()) +} + +fn decode_utf8_replacing(mut bytes: &[u8]) -> Result { + let mut result = String::new(); + while !bytes.is_empty() { + match core::str::from_utf8(bytes) { + Ok(valid) => { + result.try_reserve(valid.len()).map_err(|_| Error::Memory)?; + result.push_str(valid); + break; + } + Err(error) => { + let count = error.valid_up_to(); + let valid = core::str::from_utf8(&bytes[..count]) + .map_err(|_| invalid("Invalid UTF-8 string boundary"))?; + let additional = count.checked_add(3).ok_or(Error::Memory)?; + result.try_reserve(additional).map_err(|_| Error::Memory)?; + result.push_str(valid); + result.push('\u{fffd}'); + let skip = error.error_len().unwrap_or(bytes.len() - count); + bytes = &bytes[count + skip..]; + } + } + } + Ok(result) +} + +fn parse_profile_stats( + data: &[u8], + endian: Endian, + footer_start: usize, +) -> Result<(Option, usize)> { + if footer_start < 32 || &data[footer_start - 16..footer_start - 8] != b"TACHSTAT" { + return Ok((None, footer_start)); + } + let mut tail = Cursor::new(&data[footer_start - 8..footer_start]); + let version = endian.u32(tail.fixed()?); + let size = endian.u32(tail.fixed()?) as usize; + if size < 32 || size > footer_start { + return Err(invalid("Invalid profiling statistics size")); + } + let start = footer_start - size; + if start < HEADER_SIZE { + return Err(invalid("Invalid profiling statistics size")); + } + if version != 1 { + return Ok((None, start)); + } + let mut cursor = Cursor::new(&data[start..footer_start]); + let duration_sec = f64::from_bits(endian.u64(cursor.fixed()?)); + let sample_rate = f64::from_bits(endian.u64(cursor.fixed()?)); + let (error_rate, missed_samples) = if size >= STATS_SIZE { + let error_rate = f64::from_bits(endian.u64(cursor.fixed()?)); + let missed_samples = f64::from_bits(endian.u64(cursor.fixed()?)); + let present = endian.u32(cursor.fixed()?); + ( + (present & 1 != 0).then_some(error_rate), + (present & 2 != 0).then_some(missed_samples), + ) + } else { + (None, None) + }; + let stats = ProfileStats { + duration_sec, + sample_rate, + error_rate, + missed_samples, + }; + stats + .validate() + .map_err(|_| invalid("Invalid profiling statistics values"))?; + Ok((Some(stats), start)) +} + +#[derive(Debug)] +struct ReaderThread { + thread_id: u64, + interpreter_id: u32, + timestamp: u64, + stack: [u32; STACK_LIMIT], + depth: usize, +} + +#[derive(Clone, Copy, Debug)] +struct RepeatState { + thread: usize, + remaining: u32, + total: u32, +} + +#[derive(Debug)] +pub(crate) struct Batch { + pub(crate) sample: Sample, + pub(crate) timestamps: Vec, + pub(crate) is_repeat: bool, + pub(crate) record_complete: bool, + pub(crate) record_samples: u32, +} + +/// Independent replay state keeps close and Python callbacks from invalidating +/// any borrowed file data. No sample-count-sized allocation is performed. +#[derive(Debug)] +pub(crate) struct Replay { + reader: Arc, + offset: usize, + threads: Vec, + thread_indices: HashMap<(u64, u32), usize>, + repeat: Option, + stats: ReaderStats, + finished: bool, +} + +impl Replay { + pub(crate) fn stats(&self) -> &ReaderStats { + &self.stats + } + + pub(crate) fn replayed(&self) -> u64 { + self.stats.total_samples + } + + fn thread(&mut self, thread_id: u64, interpreter_id: u32) -> Result { + let key = (thread_id, interpreter_id); + if let Some(index) = self.thread_indices.get(&key) { + return Ok(*index); + } + if self.threads.len() as u64 >= u64::from(self.reader.metadata.thread_count) { + return Err(invalid(format!( + "Invalid thread count: sample data contains more unique threads than declared in header \ + (declared {}, found at least {})", + self.reader.metadata.thread_count, + self.threads.len() + 1 + ))); + } + reserve(&mut self.threads, 1)?; + self.thread_indices + .try_reserve(1) + .map_err(|_| Error::Memory)?; + let index = self.threads.len(); + self.threads.push(ReaderThread { + thread_id, + interpreter_id, + timestamp: self.reader.metadata.start_time_us, + stack: [0; STACK_LIMIT], + depth: 0, + }); + self.thread_indices.insert(key, index); + Ok(index) + } + + pub(crate) fn next_batch(&mut self) -> Result> { + if self.finished { + return Ok(None); + } + let result = self.next_batch_inner(); + if result.is_err() { + self.finished = true; + } + result + } + + fn next_batch_inner(&mut self) -> Result> { + loop { + if let Some(repeat) = self.repeat { + return self.repeat_batch(repeat).map(Some); + } + if self.offset == self.reader.sample_end { + if self.stats.total_samples != self.reader.metadata.sample_count { + return Err(invalid(format!( + "Sample count mismatch: header declares {} samples but replay decoded {}", + self.reader.metadata.sample_count, self.stats.total_samples + ))); + } + self.finished = true; + return Ok(None); + } + let remaining = self.reader.sample_end - self.offset; + if remaining < 13 { + return Err(invalid(format!( + "Truncated sample data: {remaining} trailing bytes" + ))); + } + let mut cursor = Cursor::new(&self.reader.data[self.offset..self.reader.sample_end]); + let thread_id = self.reader.endian.u64(cursor.fixed()?); + let interpreter_id = self.reader.endian.u32(cursor.fixed()?); + let encoding = cursor.byte()?; + self.offset += cursor.offset; + let index = self.thread(thread_id, interpreter_id)?; + let mut cursor = Cursor::new(&self.reader.data[self.offset..self.reader.sample_end]); + if encoding == REPEAT { + let count = cursor + .var_u32() + .map_err(|_| invalid("Malformed varint for RLE count"))?; + validate_count("RLE", count, cursor.remaining(), 2)?; + validate_sample_count(self.stats.total_samples, u64::from(count))?; + self.offset += cursor.offset; + add(&mut self.stats.repeat_records, 1)?; + add(&mut self.stats.repeat_samples, count.into())?; + if count != 0 { + self.repeat = Some(RepeatState { + thread: index, + remaining: count, + total: count, + }); + } + continue; + } + if ![FULL, SUFFIX, POP_PUSH].contains(&encoding) { + return Err(invalid(format!("Unknown stack encoding: {encoding}"))); + } + let delta = cursor + .varint() + .map_err(|_| invalid("Malformed varint in sample data"))?; + let status = cursor + .byte() + .map_err(|_| invalid("Unexpected end of sample data"))?; + let thread = &mut self.threads[index]; + decode_stack(thread, encoding, &mut cursor)?; + thread.timestamp = thread.timestamp.wrapping_add(delta); + self.offset += cursor.offset; + match encoding { + FULL => add(&mut self.stats.full_records, 1)?, + SUFFIX => add(&mut self.stats.suffix_records, 1)?, + _ => add(&mut self.stats.pop_push_records, 1)?, + } + add(&mut self.stats.stack_reconstructions, 1)?; + validate_sample_count(self.stats.total_samples, 1)?; + let sample = self.reader.build_sample(thread, status, thread.timestamp)?; + let mut timestamps = Vec::new(); + reserve(&mut timestamps, 1)?; + timestamps.push(thread.timestamp); + add(&mut self.stats.total_samples, 1)?; + return Ok(Some(Batch { + sample, + timestamps, + is_repeat: false, + record_complete: true, + record_samples: 1, + })); + } + } + + fn repeat_batch(&mut self, mut repeat: RepeatState) -> Result { + let mut cursor = Cursor::new(&self.reader.data[self.offset..self.reader.sample_end]); + let thread = &mut self.threads[repeat.thread]; + let mut timestamps = Vec::new(); + let mut batch_status = None; + while repeat.remaining > 0 && timestamps.len() < 8192 { + let previous = cursor.offset; + let delta = cursor + .varint() + .map_err(|_| invalid("Malformed varint in RLE sample data"))?; + let status = cursor + .byte() + .map_err(|_| invalid("Unexpected end of sample data in RLE"))?; + if batch_status.is_some_and(|previous| previous != status) { + cursor.offset = previous; + break; + } + reserve(&mut timestamps, 1)?; + batch_status = Some(status); + thread.timestamp = thread.timestamp.wrapping_add(delta); + timestamps.push(thread.timestamp); + repeat.remaining -= 1; + } + let status = batch_status.ok_or_else(|| invalid("Empty RLE batch"))?; + let timestamp = *timestamps + .first() + .ok_or_else(|| invalid("Empty RLE batch"))?; + let sample = self.reader.build_sample(thread, status, timestamp)?; + self.offset += cursor.offset; + add(&mut self.stats.total_samples, timestamps.len() as u64)?; + let record_complete = repeat.remaining == 0; + self.repeat = (!record_complete).then_some(repeat); + Ok(Batch { + sample, + timestamps, + is_repeat: true, + record_complete, + record_samples: repeat.total, + }) + } +} + +fn validate_sample_count(previous: u64, additional: u64) -> Result<()> { + if additional > (isize::MAX as u64).saturating_sub(previous) { + Err(Error::Overflow("Sample count exceeds Py_ssize_t maximum")) + } else { + Ok(()) + } +} + +fn decode_stack(thread: &mut ReaderThread, encoding: u8, cursor: &mut Cursor<'_>) -> Result<()> { + let (keep, added, source) = match encoding { + FULL => { + let depth = cursor.var_u32()?; + if depth > STACK_LIMIT as u32 { + return Err(invalid(format!( + "Stack depth {depth} exceeds capacity {STACK_LIMIT}" + ))); + } + (0, depth as usize, 0) + } + SUFFIX => { + let shared = cursor.var_u32()?; + let new = cursor.var_u32()?; + if shared as u64 > thread.depth as u64 { + return Err(invalid(format!( + "Shared count {shared} exceeds current stack depth {}", + thread.depth + ))); + } + let depth = u64::from(shared) + u64::from(new); + validate_depth(depth)?; + ( + shared as usize, + new as usize, + thread.depth - shared as usize, + ) + } + _ => { + let pop = cursor.var_u32()?; + let push = cursor.var_u32()?; + let keep = (thread.depth as u64).saturating_sub(u64::from(pop)); + validate_depth(keep + u64::from(push))?; + (keep as usize, push as usize, pop as usize) + } + }; + if keep != 0 { + thread.stack.copy_within(source..source + keep, added); + } + for slot in &mut thread.stack[..added] { + *slot = cursor.var_u32()?; + } + thread.depth = keep + added; + Ok(()) +} + +fn validate_depth(depth: u64) -> Result<()> { + if depth > STACK_LIMIT as u64 { + Err(invalid(format!( + "Final stack depth {depth} exceeds capacity {STACK_LIMIT}" + ))) + } else { + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn file(samples: &[u8], count: u64) -> Vec { + let mut bytes = vec![0; HEADER_SIZE]; + bytes[..4].copy_from_slice(&0x54414348u32.to_le_bytes()); + bytes[4..8].copy_from_slice(&1u32.to_le_bytes()); + bytes[28..36].copy_from_slice(&count.to_le_bytes()); + bytes[36..40].copy_from_slice(&1u32.to_le_bytes()); + let table = (HEADER_SIZE + samples.len()) as u64; + bytes[40..48].copy_from_slice(&table.to_le_bytes()); + bytes[48..56].copy_from_slice(&table.to_le_bytes()); + bytes.extend_from_slice(samples); + bytes.extend_from_slice(&[0; FOOTER_SIZE]); + bytes + } + + fn sample_header(encoding: u8) -> Vec { + let mut bytes = vec![0; 13]; + bytes[12] = encoding; + bytes + } + + #[test] + fn varint_rejects_overflow_and_truncation() { + let mut encoded = Vec::new(); + push_varint(&mut encoded, u64::MAX).unwrap(); + let mut cursor = Cursor::new(&encoded); + assert_eq!(cursor.varint().unwrap(), u64::MAX); + encoded[9] = 2; + let mut cursor = Cursor::new(&encoded); + assert!(cursor.varint().is_err()); + let mut cursor = Cursor::new(&[128]); + assert!(cursor.varint().is_err()); + } + + #[test] + fn full_stack_depth_is_bounded_before_allocation() { + let mut bytes = sample_header(1); + bytes.extend_from_slice(&[0, 0]); + push_varint(&mut bytes, 257).unwrap(); + let reader = Arc::new(Reader::parse(file(&bytes, 1)).unwrap()); + assert!( + matches!(reader.replay().next_batch(), Err(Error::Value(message)) if message == "Stack depth 257 exceeds capacity 256") + ); + } + + #[test] + fn repeat_count_is_bounded_by_remaining_bytes() { + let mut bytes = sample_header(0); + push_varint(&mut bytes, u32::MAX as u64).unwrap(); + let reader = Arc::new(Reader::parse(file(&bytes, 1)).unwrap()); + assert!( + matches!(reader.replay().next_batch(), Err(Error::Value(message)) if message == "Invalid RLE count 4294967295 exceeds maximum possible 0") + ); + } + + #[test] + fn empty_repeat_records_do_not_recurse() { + let mut bytes = sample_header(0); + bytes.push(0); + let reader = Arc::new(Reader::parse(file(&bytes.repeat(10_000), 0)).unwrap()); + let mut replay = reader.replay(); + assert!(replay.next_batch().unwrap().is_none()); + assert_eq!(replay.stats.repeat_records, 10_000); + assert_eq!(replay.stats.total_samples, 0); + } +} diff --git a/crates/stdlib/src/_sqlite3.rs b/crates/stdlib/src/_sqlite3.rs index 75c228fa3e6..6cc63b51b87 100644 --- a/crates/stdlib/src/_sqlite3.rs +++ b/crates/stdlib/src/_sqlite3.rs @@ -15,26 +15,28 @@ mod _sqlite3 { use core::{ ffi::{CStr, c_int, c_longlong, c_uint, c_void}, fmt::Debug, - ops::Deref, + ops::{Deref, DerefMut}, ptr::{NonNull, null, null_mut}, }; use libsqlite3_sys::{ SQLITE_BLOB, SQLITE_DETERMINISTIC, SQLITE_FLOAT, SQLITE_INTEGER, SQLITE_NULL, - SQLITE_OPEN_CREATE, SQLITE_OPEN_READWRITE, SQLITE_OPEN_URI, SQLITE_TEXT, SQLITE_TRACE_STMT, - SQLITE_TRANSIENT, SQLITE_UTF8, sqlite3, sqlite3_aggregate_context, sqlite3_backup_finish, - sqlite3_backup_init, sqlite3_backup_pagecount, sqlite3_backup_remaining, - sqlite3_backup_step, sqlite3_bind_blob, sqlite3_bind_double, sqlite3_bind_int64, - sqlite3_bind_null, sqlite3_bind_parameter_count, sqlite3_bind_parameter_name, - sqlite3_bind_text, sqlite3_blob, sqlite3_blob_bytes, sqlite3_blob_close, sqlite3_blob_open, - sqlite3_blob_read, sqlite3_blob_write, sqlite3_busy_timeout, sqlite3_changes, - sqlite3_column_blob, sqlite3_column_bytes, sqlite3_column_count, sqlite3_column_decltype, - sqlite3_column_double, sqlite3_column_int64, sqlite3_column_name, sqlite3_column_text, - sqlite3_column_type, sqlite3_complete, sqlite3_context, sqlite3_context_db_handle, - sqlite3_create_collation_v2, sqlite3_create_function_v2, sqlite3_create_window_function, - sqlite3_data_count, sqlite3_db_config, sqlite3_db_handle, sqlite3_errcode, sqlite3_errmsg, + SQLITE_OPEN_CREATE, SQLITE_OPEN_FULLMUTEX, SQLITE_OPEN_READWRITE, SQLITE_OPEN_URI, + SQLITE_TEXT, SQLITE_TRACE_STMT, SQLITE_TRANSIENT, SQLITE_UTF8, sqlite3, + sqlite3_aggregate_context, sqlite3_backup_finish, sqlite3_backup_init, + sqlite3_backup_pagecount, sqlite3_backup_remaining, sqlite3_backup_step, sqlite3_bind_blob, + sqlite3_bind_double, sqlite3_bind_int64, sqlite3_bind_null, sqlite3_bind_parameter_count, + sqlite3_bind_parameter_name, sqlite3_bind_text, sqlite3_blob, sqlite3_blob_bytes, + sqlite3_blob_close, sqlite3_blob_open, sqlite3_blob_read, sqlite3_blob_write, + sqlite3_busy_timeout, sqlite3_changes, sqlite3_clear_bindings, sqlite3_column_blob, + sqlite3_column_bytes, sqlite3_column_count, sqlite3_column_decltype, sqlite3_column_double, + sqlite3_column_int64, sqlite3_column_name, sqlite3_column_text, sqlite3_column_type, + sqlite3_complete, sqlite3_context, sqlite3_context_db_handle, sqlite3_create_collation_v2, + sqlite3_create_function_v2, sqlite3_create_window_function, sqlite3_data_count, + sqlite3_db_config, sqlite3_db_handle, sqlite3_db_mutex, sqlite3_errcode, sqlite3_errmsg, sqlite3_exec, sqlite3_expanded_sql, sqlite3_extended_errcode, sqlite3_finalize, - sqlite3_get_autocommit, sqlite3_interrupt, sqlite3_last_insert_rowid, sqlite3_libversion, - sqlite3_limit, sqlite3_open_v2, sqlite3_prepare_v2, sqlite3_progress_handler, + sqlite3_free, sqlite3_get_autocommit, sqlite3_interrupt, sqlite3_last_insert_rowid, + sqlite3_libversion, sqlite3_limit, sqlite3_mutex_enter, sqlite3_mutex_leave, + sqlite3_mutex_try, sqlite3_open_v2, sqlite3_prepare_v2, sqlite3_progress_handler, sqlite3_reset, sqlite3_result_blob, sqlite3_result_double, sqlite3_result_error, sqlite3_result_error_nomem, sqlite3_result_error_toobig, sqlite3_result_int64, sqlite3_result_null, sqlite3_result_text, sqlite3_set_authorizer, sqlite3_sleep, @@ -49,6 +51,8 @@ mod _sqlite3 { atomic::{Ordering, PyAtomic, Radium}, hash::PyHash, lock::{PyMappedMutexGuard, PyMutex, PyMutexGuard}, + rc::PyRc, + refcount::{try_defer_drop, with_deferred_drops}, static_cell, }; use rustpython_vm::{ @@ -60,10 +64,10 @@ mod _sqlite3 { PyInt, PyIntRef, PyModule, PySlice, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, PyUtf8Str, PyUtf8StrRef, }, - convert::IntoObject, function::{ - ArgCallable, ArgIterable, FsPath, FuncArgs, KwArgs, OptionalArg, PyComparisonValue, - PySetterValue, TimeoutSeconds, + ArgCallable, ArgIntoBool, ArgIntoFloat, ArgIterable, ArgStrOrBytesLike, ArgStrictInt, + ArgumentError, FromArgs, FsPath, FuncArgs, KwArgs, OptionalArg, Param, + PyComparisonValue, PySetterValue, UnpackKeywords, }, object::{Traverse, TraverseFn}, protocol::{ @@ -72,8 +76,8 @@ mod _sqlite3 { }, sliceable::{SaturatedSliceIter, SliceableSequenceOp}, types::{ - AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Hashable, - Initializer, IterNext, Iterable, PyComparisonOp, SelfIter, + AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Destructor, + Hashable, Initializer, IterNext, Iterable, PyComparisonOp, SelfIter, }, utils::ToCString, }; @@ -323,23 +327,48 @@ mod _sqlite3 { Ok(Self::Enabled) } else if obj.is(&vm.ctx.false_value) { Ok(Self::Disabled) - } else if let Ok(val) = obj.try_to_value::(vm) { - if val == LEGACY_TRANSACTION_CONTROL { - Ok(Self::Legacy) - } else { - Err(vm.new_value_error(format!( - "autocommit must be True, False, or sqlite3.LEGACY_TRANSACTION_CONTROL, not {val}" - ))) - } + } else if obj + .downcast_ref::() + .is_some_and(|value| value.as_bigint() == &LEGACY_TRANSACTION_CONTROL.into()) + { + Ok(Self::Legacy) } else { - Err(vm.new_value_error(format!( - "autocommit must be True, False, or sqlite3.LEGACY_TRANSACTION_CONTROL, not {}", - obj.class().name() - ))) + Err(vm.new_value_error( + "autocommit must be True, False, or sqlite3.LEGACY_TRANSACTION_CONTROL", + )) } } } + // Validate Clinic's str arguments while binding, before later conversions. + // Retain the original str so subclasses cannot finalize during conversion. + struct SqliteStringArg { + value: alloc::ffi::CString, + owner: PyUtf8StrRef, + } + + impl TryFromObject for SqliteStringArg { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let owner = PyUtf8StrRef::try_from_object(vm, obj)?; + let value = owner.to_cstring(vm)?; + Ok(Self { value, owner }) + } + } + + impl Deref for SqliteStringArg { + type Target = CStr; + + fn deref(&self) -> &CStr { + &self.value + } + } + + unsafe impl Traverse for SqliteStringArg { + fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { + self.owner.traverse(tracer_fn); + } + } + struct IsolationLevelArg(Option); impl TryFromObject for IsolationLevelArg { @@ -350,10 +379,14 @@ mod _sqlite3 { obj.downcast::() .map_err(|_| vm.new_type_error("isolation_level must be str or None".to_owned())) .and_then(|s| { + s.try_as_utf8(vm)?; if s.contains_nuls() { Err(vm.new_value_error("isolation_level contains interior NULs".to_owned())) } else { - Ok(Self(Some(s))) + begin_statement_ptr_from_isolation_level(&s, vm)?; + Ok(Self(Some( + vm.ctx.new_str(s.expect_str().to_ascii_uppercase()), + ))) } }) } @@ -362,29 +395,28 @@ mod _sqlite3 { #[derive(FromArgs)] struct ConnectArgs { #[pyarg(any)] - database: FsPath, - #[pyarg(any, default = TimeoutSeconds::new(5.0))] - timeout: TimeoutSeconds, - #[pyarg(any, default = 0)] + database: PyObjectRef, + #[pyarg(named, default = 5.0)] + timeout: ArgIntoFloat, + #[pyarg(named, default = 0)] detect_types: c_int, - #[pyarg(any, default = "")] + #[pyarg(named, default = "")] isolation_level: IsolationLevelArg, - #[pyarg(any, default = true)] - check_same_thread: bool, - #[pyarg(any, default = Connection::class(&vm.ctx).to_owned(), py_default = "ConnectionType")] - factory: PyTypeRef, - // TODO: cache statements - #[allow(dead_code)] - #[pyarg(any, default = 0)] + #[pyarg(named, default = ArgIntoBool::TRUE)] + check_same_thread: ArgIntoBool, + #[pyarg(named, default = Connection::class(&vm.ctx).to_owned().into_object(), py_default = "ConnectionType")] + factory: PyObjectRef, + #[pyarg(named, default = 128)] cached_statements: c_int, - #[pyarg(any, default = false)] - uri: bool, - #[pyarg(any, default)] + #[pyarg(named, default = ArgIntoBool::FALSE)] + uri: ArgIntoBool, + #[pyarg(named, default, py_default = "sqlite3.LEGACY_TRANSACTION_CONTROL")] autocommit: AutocommitMode, } unsafe impl Traverse for ConnectArgs { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { + self.database.traverse(tracer_fn); self.isolation_level.0.traverse(tracer_fn); self.factory.traverse(tracer_fn); } @@ -397,11 +429,11 @@ mod _sqlite3 { #[pyarg(named, default = -1)] pages: c_int, #[pyarg(named, optional)] - progress: Option, - #[pyarg(named, optional)] - name: Option, - #[pyarg(named, default = 0.250)] - sleep: f64, + progress: Option, + #[pyarg(named, default = "main")] + name: SqliteStringArg, + #[pyarg(named, default = 0.25)] + sleep: ArgIntoFloat, } unsafe impl Traverse for BackupArgs { @@ -418,39 +450,101 @@ mod _sqlite3 { } #[derive(FromArgs)] - struct CreateFunctionArgs { - #[pyarg(any)] + struct DatabaseNameArgs { + #[pyarg(named, default = "main")] + name: SqliteStringArg, + } + + #[derive(FromArgs)] + struct DeserializeArgs { + #[pyarg(positional)] + data: ArgStrOrBytesLike, + #[pyarg(named, default = "main")] name: PyStrRef, - #[pyarg(any)] + } + + #[derive(FromArgs)] + struct CreateFunctionArgs { + #[pyarg(positional)] + name: SqliteStringArg, + #[pyarg(positional)] narg: c_int, - #[pyarg(any)] + #[pyarg(positional)] func: PyObjectRef, - #[pyarg(named, default)] - deterministic: bool, + #[pyarg(named, default = ArgIntoBool::FALSE)] + deterministic: ArgIntoBool, } #[derive(FromArgs)] struct CreateAggregateArgs { - #[pyarg(any)] - name: PyStrRef, #[pyarg(positional)] - narg: c_int, + name: SqliteStringArg, + #[pyarg(positional)] + n_arg: c_int, + #[pyarg(positional)] + aggregate_class: PyObjectRef, + } + + #[derive(FromArgs)] + struct CreateCollationArgs { + #[pyarg(positional)] + name: SqliteStringArg, + #[pyarg(positional)] + callback: PyObjectRef, + } + + #[derive(FromArgs)] + struct CreateWindowFunctionArgs { + #[pyarg(positional)] + name: SqliteStringArg, + #[pyarg(positional)] + num_params: c_int, #[pyarg(positional)] aggregate_class: PyObjectRef, } + #[derive(FromArgs)] + struct CompleteStatementArgs { + #[pyarg(any)] + statement: SqliteStringArg, + } + + #[derive(FromArgs)] + struct ExecuteArgs { + #[pyarg(positional)] + sql: PyUtf8StrRef, + #[pyarg(positional, optional, py_default = "()")] + parameters: OptionalArg, + } + + #[derive(FromArgs)] + struct SetProgressHandlerArgs { + #[pyarg(positional)] + progress_handler: PyObjectRef, + #[pyarg(any)] + n: c_int, + } + + #[derive(FromArgs)] + struct SetConfigArgs { + #[pyarg(positional)] + op: c_int, + #[pyarg(positional, default = ArgIntoBool::TRUE)] + enable: ArgIntoBool, + } + #[derive(FromArgs)] struct BlobOpenArgs { #[pyarg(positional)] - table: PyStrRef, + table: SqliteStringArg, #[pyarg(positional)] - column: PyStrRef, + column: SqliteStringArg, #[pyarg(positional)] - rowid: i64, - #[pyarg(named, default)] - readonly: bool, + rowid: ArgStrictInt, + #[pyarg(named, default = ArgIntoBool::FALSE)] + readonly: ArgIntoBool, #[pyarg(named, default = "main")] - name: PyStrRef, + name: SqliteStringArg, } #[derive(FromArgs)] @@ -461,19 +555,61 @@ mod _sqlite3 { struct CallbackData { obj: NonNull, - vm: *const VirtualMachine, } impl CallbackData { fn new(obj: PyObjectRef, vm: &VirtualMachine) -> Option { (!vm.is_none(&obj)).then_some(Self { obj: obj.into_raw(), - vm, }) } - fn retrieve(&self) -> (&PyObject, &VirtualMachine) { - unsafe { (self.obj.as_ref(), &*self.vm) } + fn with_vm(&self, f: impl Fn(&PyObject, &VirtualMachine) -> R) -> Option { + let obj = unsafe { self.obj.as_ref() }; + // A shared connection may invoke this callback on a different thread + // after the registering thread's VM has already been destroyed. + rustpython_vm::vm::thread::with_vm(obj, |vm| f(obj, vm)) + } + + fn report_exception(callable: &PyObject, exc: PyBaseExceptionRef) { + if !enable_traceback().load(Ordering::Relaxed) { + return; + } + let callable = callable.to_owned(); + // Both repr() and sys.unraisablehook can re-enter SQLite. The + // surrounding operation releases its cursor/statement locks first. + try_defer_drop(move || { + rustpython_vm::vm::thread::with_vm(&callable, |vm| { + let message = callable.repr(vm).ok().map(|repr| { + format!( + "Exception ignored on sqlite3 callback {}", + repr.to_string_lossy() + ) + }); + vm.run_unraisable(exc.clone(), message, vm.ctx.none()); + }); + }); + } + + // The SQLite mutex keeps the registration alive until this reference is acquired. + unsafe fn registered(data: *mut c_void) -> PyRc { + let data = data.cast::(); + unsafe { + PyRc::increment_strong_count(data); + PyRc::from_raw(data) + } + } + + fn with_context(&self, context: SqliteContext, f: impl Fn(&PyObject, &VirtualMachine)) { + if self.with_vm(f).is_none() { + unsafe { + sqlite3_result_error( + context.ctx, + c"SQLite callback has no active interpreter".as_ptr(), + -1, + ) + }; + } } unsafe extern "C" fn destructor(data: *mut c_void) { @@ -486,25 +622,27 @@ mod _sqlite3 { argv: *mut *mut sqlite3_value, ) { let context = SqliteContext::from(context); - let (func, vm) = unsafe { (*context.user_data::()).retrieve() }; - let args = unsafe { core::slice::from_raw_parts(argv, argc as usize) }; + let data = unsafe { &*context.user_data::() }; + data.with_context(context, |func, vm| { + let args = unsafe { core::slice::from_raw_parts(argv, argc as usize) }; - let f = || -> PyResult<()> { - let db = context.db_handle(); - let args = args - .iter() - .copied() - .map(|val| value_to_object(val, db, vm)) - .collect::>>()?; + let f = || -> PyResult<()> { + let db = context.db_handle(); + let args = args + .iter() + .copied() + .map(|val| value_to_object(val, db, vm)) + .collect::>>()?; - let val = func.call(args, vm)?; + let val = func.call(args, vm)?; - context.result_from_object(&val, vm) - }; + context.result_from_object(&val, vm) + }; - if let Err(exc) = f() { - context.result_exception(vm, exc, c"user-defined function raised exception") - } + if let Err(exc) = f() { + context.result_exception(vm, exc, c"user-defined function raised exception") + } + }); } unsafe extern "C" fn step_callback( @@ -513,35 +651,53 @@ mod _sqlite3 { argv: *mut *mut sqlite3_value, ) { let context = SqliteContext::from(context); - let (cls, vm) = unsafe { (*context.user_data::()).retrieve() }; - let args = unsafe { core::slice::from_raw_parts(argv, argc as usize) }; - let instance = context.aggregate_context::<*const PyObject>(); - if unsafe { (*instance).is_null() } { - match cls.call((), vm) { - Ok(obj) => unsafe { *instance = obj.into_raw().as_ptr() }, - Err(exc) => { - return context.result_exception( - vm, - exc, - c"user-defined aggregate's '__init__' method raised error", - ); + let data = unsafe { &*context.user_data::() }; + data.with_context(context, |cls, vm| { + let args = unsafe { core::slice::from_raw_parts(argv, argc as usize) }; + let instance = context.aggregate_context(true); + if instance.is_null() { + unsafe { sqlite3_result_error_nomem(context.ctx) }; + return; + } + if unsafe { (*instance).is_null() } { + match cls.call((), vm) { + Ok(obj) => unsafe { *instance = obj.into_raw().as_ptr() }, + Err(exc) => { + return context.result_exception( + vm, + exc, + c"user-defined aggregate's '__init__' method raised error", + ); + } } } - } - let instance = unsafe { &**instance }; + let instance = unsafe { &**instance }; - Self::call_method_with_args(context, instance, "step", args, vm); + Self::call_method_with_args(context, instance, "step", args, vm); + }); } unsafe extern "C" fn finalize_callback(context: *mut sqlite3_context) { let context = SqliteContext::from(context); - let (_, vm) = unsafe { (*context.user_data::()).retrieve() }; - let instance = context.aggregate_context::<*const PyObject>(); - let Some(instance) = (unsafe { (*instance).as_ref() }) else { + let data = unsafe { &*context.user_data::() }; + let instance = context.aggregate_context(false); + if instance.is_null() { + return; + } + // xFinal releases the reference acquired by xStep, even if the + // query or finalize() fails. Clear the slot before calling Python. + let object = unsafe { instance.replace(core::ptr::null()) }; + let Some(object) = NonNull::new(object.cast_mut()) else { return; }; + let instance = unsafe { PyObjectRef::from_raw(object) }; - Self::callback_result_from_method(context, instance, "finalize", vm); + data.with_context(context, |_, vm| { + Self::callback_result_from_method(context, &instance, "finalize", vm); + }); + // __del__ and weakref callbacks must run after the caller releases + // its cursor, statement and connection locks. + try_defer_drop(move || drop(instance)); } unsafe extern "C" fn collation_callback( @@ -551,38 +707,45 @@ mod _sqlite3 { b_len: c_int, b_ptr: *const c_void, ) -> c_int { - let (callable, vm) = unsafe { (*data.cast::()).retrieve() }; - - let f = || -> PyResult { - let text1 = ptr_to_string(a_ptr.cast(), a_len, null_mut(), vm)?; - let text1 = vm.ctx.new_str(text1); - let text2 = ptr_to_string(b_ptr.cast(), b_len, null_mut(), vm)?; - let text2 = vm.ctx.new_str(text2); + let data = unsafe { &*data.cast::() }; + data.with_vm(|callable, vm| { + let f = || -> PyResult { + let text1 = ptr_to_string(a_ptr.cast(), a_len, null_mut(), vm)?; + let text1 = vm.ctx.new_str(text1); + let text2 = ptr_to_string(b_ptr.cast(), b_len, null_mut(), vm)?; + let text2 = vm.ctx.new_str(text2); + + let val = callable.call((text1, text2), vm)?; + let Some(val) = val.number().index(vm) else { + return Ok(0); + }; - let val = callable.call((text1, text2), vm)?; - let Some(val) = val.number().index(vm) else { - return Ok(0); - }; + let val = match val?.as_bigint().sign() { + Sign::Plus => 1, + Sign::Minus => -1, + Sign::NoSign => 0, + }; - let val = match val?.as_bigint().sign() { - Sign::Plus => 1, - Sign::Minus => -1, - Sign::NoSign => 0, + Ok(val) }; - Ok(val) - }; - - f().unwrap_or(0) + f().unwrap_or(0) + }) + .unwrap_or(0) } unsafe extern "C" fn value_callback(context: *mut sqlite3_context) { let context = SqliteContext::from(context); - let (_, vm) = unsafe { (*context.user_data::()).retrieve() }; - let instance = context.aggregate_context::<*const PyObject>(); - let instance = unsafe { &**instance }; + let data = unsafe { &*context.user_data::() }; + data.with_context(context, |_, vm| { + let instance = context.aggregate_context(false); + let Some(instance) = (unsafe { instance.as_ref().and_then(|obj| obj.as_ref()) }) + else { + return; + }; - Self::callback_result_from_method(context, instance, "value", vm); + Self::callback_result_from_method(context, instance, "value", vm); + }); } unsafe extern "C" fn inverse_callback( @@ -591,12 +754,17 @@ mod _sqlite3 { argv: *mut *mut sqlite3_value, ) { let context = SqliteContext::from(context); - let (_, vm) = unsafe { (*context.user_data::()).retrieve() }; - let args = unsafe { core::slice::from_raw_parts(argv, argc as usize) }; - let instance = context.aggregate_context::<*const PyObject>(); - let instance = unsafe { &**instance }; + let data = unsafe { &*context.user_data::() }; + data.with_context(context, |_, vm| { + let args = unsafe { core::slice::from_raw_parts(argv, argc as usize) }; + let instance = context.aggregate_context(false); + let Some(instance) = (unsafe { instance.as_ref().and_then(|obj| obj.as_ref()) }) + else { + return; + }; - Self::call_method_with_args(context, instance, "inverse", args, vm); + Self::call_method_with_args(context, instance, "inverse", args, vm); + }); } unsafe extern "C" fn authorizer_callback( @@ -607,21 +775,27 @@ mod _sqlite3 { db_name: *const libc::c_char, access: *const libc::c_char, ) -> c_int { - let (callable, vm) = unsafe { (*data.cast::()).retrieve() }; - let f = || -> PyResult { - let arg1 = ptr_to_str_or_none(arg1, vm)?; - let arg2 = ptr_to_str_or_none(arg2, vm)?; - let db_name = ptr_to_str_or_none(db_name, vm)?; - let access = ptr_to_str_or_none(access, vm)?; - - let val = callable.call((action, arg1, arg2, db_name, access), vm)?; - let Some(val) = val.downcast_ref::() else { - return Ok(SQLITE_DENY); + let data = unsafe { Self::registered(data) }; + data.with_vm(|callable, vm| { + let f = || -> PyResult { + let arg1 = ptr_to_str_or_none(arg1, vm)?; + let arg2 = ptr_to_str_or_none(arg2, vm)?; + let db_name = ptr_to_str_or_none(db_name, vm)?; + let access = ptr_to_str_or_none(access, vm)?; + + let val = callable.call((action, arg1, arg2, db_name, access), vm)?; + let Some(val) = val.downcast_ref::() else { + return Ok(SQLITE_DENY); + }; + val.try_to_primitive::(vm) }; - val.try_to_primitive::(vm) - }; - f().unwrap_or(SQLITE_DENY) + f().unwrap_or_else(|exc| { + Self::report_exception(callable, exc); + SQLITE_DENY + }) + }) + .unwrap_or(SQLITE_DENY) } unsafe extern "C" fn trace_callback( @@ -630,25 +804,55 @@ mod _sqlite3 { stmt: *mut c_void, sql: *mut c_void, ) -> c_int { - let (callable, vm) = unsafe { (*data.cast::()).retrieve() }; - let expanded = unsafe { sqlite3_expanded_sql(stmt.cast()) }; - let f = || -> PyResult<()> { - let stmt = ptr_to_str(expanded, vm).or_else(|_| ptr_to_str(sql.cast(), vm))?; - callable.call((stmt,), vm)?; - Ok(()) - }; - let _ = f(); - 0 + let data = unsafe { Self::registered(data) }; + data.with_vm(|callable, vm| { + let f = || -> PyResult<()> { + let stmt = { + let expanded = scopeguard::guard( + unsafe { sqlite3_expanded_sql(stmt.cast()) }, + |sql| unsafe { sqlite3_free(sql.cast()) }, + ); + let text = if expanded.is_null() { + let db = unsafe { sqlite3_db_handle(stmt.cast()) }; + if unsafe { sqlite3_errcode(db) } == SQLITE_NOMEM { + return Err(vm.new_memory_error("")); + } + Self::report_exception( + callable, + vm.new_exception_msg( + data_error_type().to_owned(), + "Expanded SQL string exceeds the maximum string length".into(), + ), + ); + ptr_to_str(sql.cast(), vm)? + } else { + ptr_to_str(*expanded, vm)? + }; + vm.ctx.new_str(text) + }; + callable.call((stmt,), vm)?; + Ok(()) + }; + if let Err(exc) = f() { + Self::report_exception(callable, exc); + } + 0 + }) + .unwrap_or(0) } unsafe extern "C" fn progress_callback(data: *mut c_void) -> c_int { - let (callable, vm) = unsafe { (*data.cast::()).retrieve() }; - if let Ok(val) = callable.call((), vm) - && let Ok(val) = val.is_true(vm) - { - return val as c_int; - } - -1 + let data = unsafe { Self::registered(data) }; + data.with_vm(|callable, vm| { + match callable.call((), vm).and_then(|val| val.is_true(vm)) { + Ok(val) => val as c_int, + Err(exc) => { + Self::report_exception(callable, exc); + -1 + } + } + }) + .unwrap_or(-1) } fn callback_result_from_method( @@ -732,42 +936,69 @@ mod _sqlite3 { impl Drop for CallbackData { fn drop(&mut self) { - unsafe { - let _ = PyObjectRef::from_raw(self.obj); - }; + let obj = unsafe { PyObjectRef::from_raw(self.obj) }; + // The last active callback may outlive its registration. Release the + // Python reference after the outer operation's native/Rust locks. + try_defer_drop(move || drop(obj)); + } + } + + // CPython displays the Connection parameters but forwards the original call + // to a custom factory without validating or converting those parameters. + struct ConnectForwardArgs(FuncArgs); + + impl FromArgs for ConnectForwardArgs { + const PARAMS: Option<&'static [Param]> = ConnectArgs::PARAMS; + const BINDING_PARAMS: Option<&'static [Param]> = FuncArgs::BINDING_PARAMS; + + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + FuncArgs::from_args(vm, args).map(Self) } } #[pyfunction] - fn connect(args: ConnectArgs, vm: &VirtualMachine) -> PyResult { - let factory = args.factory.clone(); - let conn = Connection::py_new(&factory, args, vm)?; - conn.into_ref_with_type(vm, factory).map(Into::into) + fn connect(ConnectForwardArgs(args): ConnectForwardArgs, vm: &VirtualMachine) -> PyResult { + if args.args.len() > 1 { + return Err(vm.new_type_error(format!( + "connect() takes at most 1 positional arguments ({} given)", + args.args.len() + ))); + } + let factory = args + .kwargs + .get("factory") + .cloned() + .unwrap_or_else(|| Connection::class(&vm.ctx).to_owned().into()); + factory.call(args, vm) } #[pyfunction] - fn complete_statement(statement: PyStrRef, vm: &VirtualMachine) -> PyResult { - let s = statement.to_cstring(vm)?; + fn complete_statement(args: CompleteStatementArgs) -> bool { + let s = args.statement; let ret = unsafe { sqlite3_complete(s.as_ptr()) }; - Ok(ret == 1) + ret == 1 } #[pyfunction] - fn enable_callback_tracebacks(flag: bool) { - enable_traceback().store(flag, Ordering::Relaxed); + fn enable_callback_tracebacks(enable: c_int) { + enable_traceback().store(enable != 0, Ordering::Relaxed); } #[pyfunction] - fn register_adapter(typ: PyTypeRef, adapter: ArgCallable, vm: &VirtualMachine) -> PyResult<()> { - if typ.is(PyInt::class(&vm.ctx)) - || typ.is(PyFloat::class(&vm.ctx)) - || typ.is(PyStr::class(&vm.ctx)) - || typ.is(PyByteArray::class(&vm.ctx)) + fn register_adapter( + r#type: PyTypeRef, + adapter: ArgCallable, + vm: &VirtualMachine, + ) -> PyResult<()> { + if r#type.is(PyInt::class(&vm.ctx)) + || r#type.is(PyFloat::class(&vm.ctx)) + || r#type.is(PyStr::class(&vm.ctx)) + || r#type.is(PyByteArray::class(&vm.ctx)) { let _ = BASE_TYPE_ADAPTED.set(()); } let protocol = PrepareProtocol::class(&vm.ctx).to_owned(); - let key = vm.ctx.new_tuple(vec![typ.into(), protocol.into()]); + let key = vm.ctx.new_tuple(vec![r#type.into(), protocol.into()]); adapters().set_item(key.as_object(), adapter.into(), vm) } @@ -825,13 +1056,18 @@ mod _sqlite3 { alt(obj) } - #[pyfunction] - fn adapt( + #[derive(FromArgs)] + struct AdaptArgs { + #[pyarg(positional)] obj: PyObjectRef, + #[pyarg(positional, default, py_default = "PrepareProtocolType")] proto: OptionalArg>, + #[pyarg(positional, optional)] alt: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult { + } + + #[pyfunction] + fn adapt(AdaptArgs { obj, proto, alt }: AdaptArgs, vm: &VirtualMachine) -> PyResult { if matches!(proto, OptionalArg::Present(None)) { return if let OptionalArg::Present(alt) = alt { Ok(alt) @@ -924,7 +1160,8 @@ mod _sqlite3 { #[pyclass(name)] #[derive(PyPayload)] struct Connection { - db: PyMutex>, + db: PyMutex>>, + statement_cache: PyMutex, initialized: PyAtomic, detect_types: PyAtomic, isolation_level: PyAtomicRef>, @@ -942,35 +1179,21 @@ mod _sqlite3 { } impl Constructor for Connection { - type Args = ConnectArgs; + type Args = FuncArgs; - fn py_new(cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + fn py_new(_cls: &Py, _args: Self::Args, vm: &VirtualMachine) -> PyResult { let text_factory = PyStr::class(&vm.ctx).to_owned().into_object(); - - // For non-subclassed Connection, initialize in __new__ - // For subclassed Connection, leave db as None and require __init__ to be called - let is_base_class = cls.is(Self::class(&vm.ctx)); - - let db = if is_base_class { - // Initialize immediately for base class - Some(Self::initialize_db(&args, vm)?) - } else { - // For subclasses, require __init__ to be called - None - }; - - let initialized = db.is_some(); - Ok(Self { - db: PyMutex::new(db), - initialized: Radium::new(initialized), - detect_types: Radium::new(args.detect_types), - isolation_level: PyAtomicRef::from(args.isolation_level.0), - check_same_thread: Radium::new(args.check_same_thread), + db: PyMutex::new(None), + statement_cache: PyMutex::new(StatementCache::new(0)), + initialized: Radium::new(false), + detect_types: Radium::new(0), + isolation_level: PyAtomicRef::from(None), + check_same_thread: Radium::new(false), thread_ident: PyMutex::new(std::thread::current().id()), row_factory: PyAtomicRef::from(None), text_factory: PyAtomicRef::from(text_factory), - autocommit: PyMutex::new(args.autocommit), + autocommit: PyMutex::new(AutocommitMode::default()), }) } } @@ -979,6 +1202,12 @@ mod _sqlite3 { type Args = FuncArgs; fn call(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + with_deferred_drops(|| Self::call_inner(zelf, args, vm)) + } + } + + impl Connection { + fn call_inner(zelf: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let _ = zelf.db_lock(vm)?; let (sql,): (PyUtf8StrRef,) = args.bind(vm)?; @@ -995,57 +1224,222 @@ mod _sqlite3 { type Args = ConnectArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - let was_initialized = Radium::swap(&zelf.initialized, false, Ordering::AcqRel); - - // Reset factories to their defaults, matching CPython's behavior. - zelf.reset_factories(vm); + vm.audit("sqlite3.connect", || (args.database.clone(),))?; + // Finish filesystem conversion before invalidating an existing connection. + let database = FsPath::try_from_object(vm, args.database.clone())?; + let path = database.to_cstring(vm)?; + // FSConverter releases Unicode after encoding, but retains bytes + // through opening the database. Either owner can have a finalizer. + let database = match database { + FsPath::Str(_owner) => None, + FsPath::Bytes(owner) => Some(owner), + }; + loop { + with_deferred_drops(|| { + Radium::store(&zelf.initialized, false, Ordering::Release); - if was_initialized { - zelf.drop_db(vm)?; + // Reset factories to their defaults, matching CPython's behavior. + zelf.reset_factories(vm); + zelf.drop_db(vm) + })?; + // A finalizer may itself reinitialize the connection. Dispose of + // that database too before publishing the requested replacement. + if zelf.db.lock().is_none() { + break; + } } + // Dispose of the old callbacks before publishing the replacement. + // Nested native calls still defer their drops to the outer operation. // Attempt to open the new database before mutating other state so failures leave // the connection uninitialized (and subsequent operations raise ProgrammingError). - let db = Self::initialize_db(&args, vm)?; + let db = Self::initialize_db(&args, &path, vm)?; + // A path-like result may finalize and reenter initialization. + // Release it before the publication loop rechecks the connection. + drop(database); let ConnectArgs { detect_types, isolation_level, check_same_thread, autocommit, + cached_statements, .. } = args; - zelf.detect_types.store(detect_types, Ordering::Relaxed); - zelf.check_same_thread - .store(check_same_thread, Ordering::Relaxed); - *zelf.autocommit.lock() = autocommit; - *zelf.thread_ident.lock() = std::thread::current().id(); - let _ = unsafe { zelf.isolation_level.swap(isolation_level.0) }; + let default_text_factory = PyStr::class(&vm.ctx).to_owned().into_object(); + loop { + let mut current = zelf.db.lock(); + if current.is_none() { + let previous = unsafe { zelf.isolation_level.swap(isolation_level.0.clone()) }; + let row_factory = unsafe { zelf.row_factory.swap(None) }; + let text_factory = + unsafe { zelf.text_factory.swap(default_text_factory.clone()) }; + if previous.as_ref().is_some_and(|previous| { + !isolation_level + .0 + .as_ref() + .is_some_and(|requested| previous.is(requested)) + }) || row_factory.is_some() + || !text_factory.is(&default_text_factory) + { + // Factories and str subclasses can finalize too. Retire + // them before publication, then recheck any reentrant changes. + drop(current); + with_deferred_drops(|| drop((previous, row_factory, text_factory))); + continue; + } - let mut guard = zelf.db.lock(); - *guard = Some(db); + // No destructor-capable owner remains to release here. + // Publish the settings and database under the same lock. + zelf.statement_cache.lock().capacity = cached_statements.max(0) as usize; + zelf.detect_types.store(detect_types, Ordering::Relaxed); + zelf.check_same_thread + .store(check_same_thread.into_bool(), Ordering::Relaxed); + *zelf.autocommit.lock() = autocommit; + *zelf.thread_ident.lock() = std::thread::current().id(); + *current = Some(db); + break; + } + drop(current); + + // A concurrent initializer or finalizer installed another database. + // Finish its teardown outside the lock before trying to publish. + with_deferred_drops(|| { + Radium::store(&zelf.initialized, false, Ordering::Release); + zelf.reset_factories(vm); + zelf.drop_db(vm) + })?; + } + vm.audit("sqlite3.connect/handle", || (zelf.to_owned(),))?; Radium::store(&zelf.initialized, true, Ordering::Release); + if autocommit == AutocommitMode::Disabled { + zelf._db_lock(vm)?._exec(c"BEGIN", vm)?; + } Ok(()) } } - #[pyclass(with(Constructor, Callable, Initializer), flags(BASETYPE, HAS_WEAKREF))] + impl Destructor for Connection { + fn del(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + let teardown = vm.state.finalizing.load(Ordering::Acquire); + if teardown { + let db = zelf.db.lock().clone(); + if let Some(db) = db { + db.disable_callbacks(); + } + } + if !zelf.is_closed() { + let warning = zelf.as_object().repr(vm).and_then(|repr| { + rustpython_vm::warn::warn( + vm.ctx + .new_str(format!("unclosed database in {}", repr.as_wtf8())) + .into(), + Some(vm.ctx.exceptions.resource_warning.to_owned()), + 1, + Some(zelf.as_object().to_owned()), + vm, + ) + }); + if let Err(exc) = warning + && exc.fast_isinstance(vm.ctx.exceptions.warning) + { + let message = zelf.as_object().repr(vm).ok().map(|repr| { + format!( + "Exception ignored while finalizing database connection {}", + repr.as_wtf8() + ) + }); + vm.run_unraisable(exc, message, vm.ctx.none()); + } + } + // A warning promoted to an exception must not prevent cleanup. + // Unlike close(), finalization is allowed on a different thread. + if let Err(exc) = zelf.drop_db(vm) + && !teardown + { + let message = zelf.as_object().repr(vm).ok().map(|repr| { + format!( + "Exception ignored while closing database {}", + repr.as_wtf8() + ) + }); + vm.run_unraisable(exc, message, vm.ctx.none()); + } + Ok(()) + } + } + + #[pyclass( + with(Constructor, Callable, Initializer, Destructor), + flags(BASETYPE, HAS_WEAKREF) + )] impl Connection { - fn drop_db(&self, vm: &VirtualMachine) -> PyResult<()> { - let mut guard = self.db.lock(); - let rollback_result = if let Some(db) = guard.as_ref() - && *self.autocommit.lock() == AutocommitMode::Disabled - && !db.is_autocommit() + fn cached_statement( + &self, + sql: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult> { + let (cached, generation) = { + let mut cache = self.statement_cache.lock(); + let statement = cache.entries.get_index_of(sql.as_str()).map(|index| { + let last = cache.entries.len() - 1; + cache.entries.move_index(index, last); + cache.entries.get_index(last).unwrap().1.clone() + }); + (statement, cache.generation) + }; + if let Some(statement) = &cached + && let Some(lease) = StatementLease::acquire(statement.clone()) { - db._exec(c"ROLLBACK", vm) - } else { - Ok(()) + return Ok(Some(lease)); + } + + // Preparing may invoke an authorizer. Never hold the cache lock + // across callbacks, or wait for a statement owned by another cursor. + let Some(statement) = Statement::new(self, sql.clone(), vm)? else { + return Ok(None); }; - let db = guard.take(); - drop(guard); - drop(db); - rollback_result + let statement = statement.into_ref(&vm.ctx); + let lease = StatementLease::acquire(statement.clone()).unwrap(); + let _evicted = { + let mut cache = self.statement_cache.lock(); + if cached.is_none() + && cache.generation == generation + && cache.capacity > 0 + && !cache.entries.contains_key(sql.as_str()) + { + let evicted = if cache.entries.len() == cache.capacity { + cache.entries.shift_remove_index(0) + } else { + None + }; + cache.entries.insert(sql.as_str().into(), statement); + evicted + } else { + None + } + }; + Ok(Some(lease)) + } + + fn drop_db(&self, vm: &VirtualMachine) -> PyResult<()> { + with_deferred_drops(|| Self::drop_db_inner(self, vm)) + } + + fn drop_db_inner(&self, vm: &VirtualMachine) -> PyResult<()> { + let db = self.db.lock().take(); + let statements = { + let mut cache = self.statement_cache.lock(); + cache.generation = cache.generation.wrapping_add(1); + core::mem::take(&mut cache.entries) + }; + drop(statements); + let rollback = *self.autocommit.lock() == AutocommitMode::Disabled; + if let Some(db) = db { + db.close_callbacks(rollback, vm)?; + } + Ok(()) } fn reset_factories(&self, vm: &VirtualMachine) { @@ -1054,44 +1448,55 @@ mod _sqlite3 { let _ = unsafe { self.text_factory.swap(default_text_factory) }; } - fn initialize_db(args: &ConnectArgs, vm: &VirtualMachine) -> PyResult { - let path = args.database.to_cstring(vm)?; - let db = Sqlite::from(SqliteRaw::open(path.as_ptr(), args.uri, vm)?); - let timeout = (args.timeout.to_secs_f64() * 1000.0) as c_int; + fn initialize_db( + args: &ConnectArgs, + path: &CStr, + vm: &VirtualMachine, + ) -> PyResult> { + let db = PyRc::new(Sqlite::from(SqliteRaw::open( + path.as_ptr(), + args.uri.into_bool(), + vm, + )?)); + #[cfg(feature = "threading")] + if unsafe { sqlite3_db_mutex(db.db) }.is_null() { + return Err(vm.new_runtime_error("SQLite connection mutexes are disabled")); + } + let timeout = (args.timeout.into_float() * 1000.0) as c_int; db.busy_timeout(timeout); if let Some(isolation_level) = &args.isolation_level.0 { begin_statement_ptr_from_isolation_level(isolation_level, vm)?; } - if args.autocommit == AutocommitMode::Disabled { - db._exec(c"BEGIN", vm)?; - } Ok(db) } - fn db_lock(&self, vm: &VirtualMachine) -> PyResult> { + fn db_lock(&self, vm: &VirtualMachine) -> PyResult { self.check_thread(vm)?; self._db_lock(vm) } - fn _db_lock(&self, vm: &VirtualMachine) -> PyResult> { - let guard = self.db.lock(); - if guard.is_some() { - Ok(PyMutexGuard::map(guard, |x| unsafe { - x.as_mut().unwrap_unchecked() - })) - } else if self.initialized.load(Ordering::Acquire) { - Err(new_programming_error( + fn _db_lock(&self, vm: &VirtualMachine) -> PyResult { + if !self.initialized.load(Ordering::Acquire) { + return Err(new_programming_error( vm, - "Cannot operate on a closed database.".to_owned(), - )) + "Base Connection.__init__ not called.".to_owned(), + )); + } + let guard = self.db.lock(); + if let Some(db) = guard.as_ref() { + Ok(SqliteOperation(db.clone())) } else { Err(new_programming_error( vm, - "Base Connection.__init__ not called.".to_owned(), + "Cannot operate on a closed database.".to_owned(), )) } } + fn check_open(&self, vm: &VirtualMachine) -> PyResult<()> { + self.db_lock(vm).map(drop) + } + #[pymethod] fn cursor( zelf: PyRef, @@ -1129,31 +1534,41 @@ mod _sqlite3 { args: BlobOpenArgs, vm: &VirtualMachine, ) -> PyResult> { - let table = args.table.to_cstring(vm)?; - let column = args.column.to_cstring(vm)?; - let name = args.name.to_cstring(vm)?; + with_deferred_drops(|| Self::blobopen_inner(zelf, args, vm)) + } + + fn blobopen_inner( + zelf: PyRef, + args: BlobOpenArgs, + vm: &VirtualMachine, + ) -> PyResult> { + let table = args.table; + let column = args.column; + let name = args.name; let db = zelf.db_lock(vm)?; let mut blob = null_mut(); - let ret = unsafe { + let ret = db.call(|| unsafe { sqlite3_blob_open( db.db, name.as_ptr(), table.as_ptr(), column.as_ptr(), - args.rowid, - (!args.readonly) as c_int, + args.rowid.into_primitive(), + (!args.readonly.into_bool()) as c_int, &mut blob, ) - }; + }); db.check(ret, vm)?; - drop(db); - let blob = SqliteBlob { blob }; let blob = Blob { connection: zelf, - inner: PyMutex::new(Some(BlobInner { blob, offset: 0 })), + inner: PyMutex::new(Some(BlobInner { + blob, + offset: 0, + db: db.0.clone(), + })), }; Ok(blob.into_ref(&vm.ctx)) } @@ -1161,6 +1576,12 @@ mod _sqlite3 { #[pymethod] fn close(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { zelf.check_thread(vm)?; + if !zelf.initialized.load(Ordering::Acquire) { + return Err(new_programming_error( + vm, + "Base Connection.__init__ not called.".to_owned(), + )); + } zelf.drop_db(vm) } @@ -1170,78 +1591,101 @@ mod _sqlite3 { #[pymethod] fn commit(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { - let db = zelf.db_lock(vm)?; - let mode = *zelf.autocommit.lock(); - match mode { - AutocommitMode::Legacy => db.implicit_commit(vm), - AutocommitMode::Enabled => Ok(()), - AutocommitMode::Disabled => { - db._exec(c"COMMIT", vm)?; - db._exec(c"BEGIN", vm) - } - } + with_deferred_drops(|| Self::commit_inner(zelf, vm)) + } + + fn commit_inner(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + zelf.end_transaction(c"COMMIT", vm) } #[pymethod] fn rollback(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { - let db = zelf.db_lock(vm)?; - let mode = *zelf.autocommit.lock(); - match mode { - AutocommitMode::Legacy => { - if db.is_autocommit() { - Ok(()) - } else { - db._exec(c"ROLLBACK", vm) - } + with_deferred_drops(|| Self::rollback_inner(zelf, vm)) + } + + fn rollback_inner(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + zelf.end_transaction(c"ROLLBACK", vm) + } + + fn end_transaction(&self, sql: &CStr, vm: &VirtualMachine) -> PyResult<()> { + let db = self.db_lock(vm)?; + let result = { + let _guard = db.lock(); + let mode = *self.autocommit.lock(); + db.end_transaction(sql, mode) + }; + result.map_err(|err| err.into_exception(vm)) + } + + fn begin_transaction(&self, db: SqliteRaw, vm: &VirtualMachine) -> PyResult<()> { + let result = { + let _guard = db.lock(); + let mode = *self.autocommit.lock(); + if mode == AutocommitMode::Legacy && db.is_autocommit() { + db.begin_transaction(self.isolation_level.deref().map(|x| x.to_owned())) + } else { + Ok(()) } - AutocommitMode::Enabled => Ok(()), - AutocommitMode::Disabled => { - db._exec(c"ROLLBACK", vm)?; - db._exec(c"BEGIN", vm) + }; + result.map_err(|err| err.into_exception(vm)) + } + + fn commit_before_script(&self, db: SqliteRaw, vm: &VirtualMachine) -> PyResult<()> { + let result = { + let _guard = db.lock(); + let mode = *self.autocommit.lock(); + if mode == AutocommitMode::Legacy { + db.end_transaction(c"COMMIT", mode) + } else { + Ok(()) } - } + }; + result.map_err(|err| err.into_exception(vm)) } #[pymethod] fn execute( zelf: PyRef, - sql: PyUtf8StrRef, - parameters: OptionalArg, + args: ExecuteArgs, vm: &VirtualMachine, ) -> PyResult> { let row_factory = zelf.row_factory.load_owned(); let cursor = Cursor::new(zelf, row_factory, vm).into_ref(&vm.ctx); - Cursor::execute(cursor, sql, parameters, vm) + Cursor::execute(cursor, args, vm) } #[pymethod] fn executemany( zelf: PyRef, sql: PyUtf8StrRef, - seq_of_params: ArgIterable, + parameters: ArgIterable, vm: &VirtualMachine, ) -> PyResult> { let row_factory = zelf.row_factory.load_owned(); let cursor = Cursor::new(zelf, row_factory, vm).into_ref(&vm.ctx); - Cursor::executemany(cursor, sql, seq_of_params, vm) + Cursor::executemany(cursor, sql, parameters, vm) } #[pymethod] fn executescript( zelf: PyRef, - script: PyUtf8StrRef, + sql_script: PyUtf8StrRef, vm: &VirtualMachine, ) -> PyResult> { let row_factory = zelf.row_factory.load_owned(); Cursor::executescript( Cursor::new(zelf, row_factory, vm).into_ref(&vm.ctx), - script, + sql_script, vm, ) } #[pymethod] fn backup(zelf: &Py, args: BackupArgs, vm: &VirtualMachine) -> PyResult<()> { + with_deferred_drops(|| Self::backup_inner(zelf, args, vm)) + } + + fn backup_inner(zelf: &Py, args: BackupArgs, vm: &VirtualMachine) -> PyResult<()> { let BackupArgs { target, pages, @@ -1253,30 +1697,35 @@ mod _sqlite3 { return Err(vm.new_value_error("target cannot be the same connection instance")); } + if let Some(progress) = &progress + && !progress.is_callable() + { + return Err(vm.new_type_error("progress argument must be a callable")); + } + let pages = if pages == 0 { -1 } else { pages }; - let name_cstring; - let name_ptr = if let Some(name) = &name { - name_cstring = name.to_cstring(vm)?; - name_cstring.as_ptr() - } else { - c"main".as_ptr() - }; + let name_ptr = name.as_ptr(); - let sleep_ms = (sleep * 1000.0) as c_int; + let sleep_ms = (sleep.into_float() * 1000.0) as c_int; let db = zelf.db_lock(vm)?; let target_db = target.db_lock(vm)?; - let handle = - unsafe { sqlite3_backup_init(target_db.db, c"main".as_ptr(), db.db, name_ptr) }; - - if handle.is_null() { - return Err(target_db.error_extended(vm)); + let handle = { + // Match SQLite's source-before-destination lock order, and retain + // the destination error before another operation can replace it. + let _source_guard = db.lock(); + let _target_guard = target_db.lock(); + let handle = + unsafe { sqlite3_backup_init(target_db.db, c"main".as_ptr(), db.db, name_ptr) }; + if handle.is_null() { + Err(target_db.error_snapshot()) + } else { + Ok(handle) + } } - - drop(db); - drop(target_db); + .map_err(|err| err.into_exception(vm))?; loop { let ret = unsafe { sqlite3_backup_step(handle, pages) }; @@ -1284,7 +1733,7 @@ mod _sqlite3 { if let Some(progress) = &progress { let remaining = unsafe { sqlite3_backup_remaining(handle) }; let pagecount = unsafe { sqlite3_backup_pagecount(handle) }; - if let Err(err) = progress.invoke((ret, remaining, pagecount), vm) { + if let Err(err) = progress.call((ret, remaining, pagecount), vm) { unsafe { sqlite3_backup_finish(handle) }; return Err(err); } @@ -1297,12 +1746,11 @@ mod _sqlite3 { } } - let ret = unsafe { sqlite3_backup_finish(handle) }; - if ret == SQLITE_OK { - Ok(()) - } else { - Err(target.db_lock(vm)?.error_extended(vm)) - } + let result = { + let _source_guard = db.lock(); + target_db.call(|| unsafe { sqlite3_backup_finish(handle) }) + }; + target_db.check(result, vm) } #[pymethod] @@ -1311,8 +1759,16 @@ mod _sqlite3 { args: CreateFunctionArgs, vm: &VirtualMachine, ) -> PyResult<()> { - let name = args.name.to_cstring(vm)?; - let flags = if args.deterministic { + with_deferred_drops(|| Self::create_function_inner(zelf, args, vm)) + } + + fn create_function_inner( + zelf: &Py, + args: CreateFunctionArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + let name = args.name; + let flags = if args.deterministic.into_bool() { SQLITE_UTF8 | SQLITE_DETERMINISTIC } else { SQLITE_UTF8 @@ -1348,17 +1804,25 @@ mod _sqlite3 { #[pymethod] fn create_aggregate( + zelf: &Py, + UnpackKeywords(args): UnpackKeywords, + vm: &VirtualMachine, + ) -> PyResult<()> { + with_deferred_drops(|| Self::create_aggregate_inner(zelf, args, vm)) + } + + fn create_aggregate_inner( zelf: &Py, args: CreateAggregateArgs, vm: &VirtualMachine, ) -> PyResult<()> { - let name = args.name.to_cstring(vm)?; + let name = args.name; let db = zelf.db_lock(vm)?; - check_num_params(&db, args.narg, "n_arg", vm)?; + check_num_params(&db, args.n_arg, "n_arg", vm)?; let Some(data) = CallbackData::new(args.aggregate_class, vm) else { return db.create_function( &name, - args.narg, + args.n_arg, SQLITE_UTF8, null_mut(), None, @@ -1371,7 +1835,7 @@ mod _sqlite3 { db.create_function( &name, - args.narg, + args.n_arg, SQLITE_UTF8, Box::into_raw(Box::new(data)).cast(), None, @@ -1385,11 +1849,18 @@ mod _sqlite3 { #[pymethod] fn create_collation( zelf: &Py, - name: PyUtf8StrRef, + UnpackKeywords(args): UnpackKeywords, + vm: &VirtualMachine, + ) -> PyResult<()> { + with_deferred_drops(|| Self::create_collation_inner(zelf, args.name, args.callback, vm)) + } + + fn create_collation_inner( + zelf: &Py, + name: SqliteStringArg, callable: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - let name = name.to_cstring(vm)?; let db = zelf.db_lock(vm)?; let Some(data) = CallbackData::new(callable.clone(), vm) else { unsafe { @@ -1410,7 +1881,7 @@ mod _sqlite3 { return Err(vm.new_type_error("parameter must be callable")); } - let ret = unsafe { + let ret = db.call(|| unsafe { sqlite3_create_collation_v2( db.db, name.as_ptr(), @@ -1419,7 +1890,7 @@ mod _sqlite3 { Some(CallbackData::collation_callback), Some(CallbackData::destructor), ) - }; + }); db.check(ret, vm).inspect_err(|_| { // create_collation do not call destructor if error occur @@ -1427,15 +1898,30 @@ mod _sqlite3 { }) } - #[pymethod] - fn create_window_function( + #[pymethod] + fn create_window_function( + zelf: &Py, + UnpackKeywords(args): UnpackKeywords, + vm: &VirtualMachine, + ) -> PyResult<()> { + with_deferred_drops(|| { + Self::create_window_function_inner( + zelf, + args.name, + args.num_params, + args.aggregate_class, + vm, + ) + }) + } + + fn create_window_function_inner( zelf: &Py, - name: PyStrRef, + name: SqliteStringArg, narg: c_int, aggregate_class: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - let name = name.to_cstring(vm)?; let db = zelf.db_lock(vm)?; check_num_params(&db, narg, "num_params", vm)?; let Some(data) = CallbackData::new(aggregate_class, vm) else { @@ -1456,7 +1942,7 @@ mod _sqlite3 { return Ok(()); }; - let ret = unsafe { + let ret = db.call(|| unsafe { sqlite3_create_window_function( db.db, name.as_ptr(), @@ -1469,7 +1955,7 @@ mod _sqlite3 { Some(CallbackData::inverse_callback), Some(CallbackData::destructor), ) - }; + }); db.check(ret, vm) .map_err(|_| new_programming_error(vm, "Error creating window function".to_owned())) } @@ -1477,74 +1963,74 @@ mod _sqlite3 { #[pymethod] fn set_authorizer( zelf: &Py, - callable: PyObjectRef, + UnpackKeywords(authorizer_callback): UnpackKeywords, vm: &VirtualMachine, ) -> PyResult<()> { - let db = zelf.db_lock(vm)?; - let Some(data) = CallbackData::new(callable, vm) else { - unsafe { sqlite3_set_authorizer(db.db, None, null_mut()) }; - return Ok(()); - }; - - let ret = unsafe { - sqlite3_set_authorizer( - db.db, - Some(CallbackData::authorizer_callback), - Box::into_raw(Box::new(data)).cast(), - ) - }; - db.check(ret, vm).map_err(|_| { - new_operational_error(vm, "Error setting authorizer callback".to_owned()) - }) + zelf.set_callback(authorizer_callback, CallbackKind::Authorizer, vm) } #[pymethod] fn set_trace_callback( zelf: &Py, - callable: PyObjectRef, + UnpackKeywords(trace_callback): UnpackKeywords, vm: &VirtualMachine, ) -> PyResult<()> { - let db = zelf.db_lock(vm)?; - let Some(data) = CallbackData::new(callable, vm) else { - unsafe { sqlite3_trace_v2(db.db, SQLITE_TRACE_STMT, None, null_mut()) }; - return Ok(()); - }; - - let ret = unsafe { - sqlite3_trace_v2( - db.db, - SQLITE_TRACE_STMT, - Some(CallbackData::trace_callback), - Box::into_raw(Box::new(data)).cast(), - ) - }; - - db.check(ret, vm) + zelf.set_callback(trace_callback, CallbackKind::Trace, vm) } #[pymethod] fn set_progress_handler( zelf: &Py, - callable: PyObjectRef, - n: c_int, + args: SetProgressHandlerArgs, vm: &VirtualMachine, ) -> PyResult<()> { - let db = zelf.db_lock(vm)?; - let Some(data) = CallbackData::new(callable, vm) else { - unsafe { sqlite3_progress_handler(db.db, n, None, null_mut()) }; - return Ok(()); - }; - - unsafe { - sqlite3_progress_handler( - db.db, - n, - Some(CallbackData::progress_callback), - Box::into_raw(Box::new(data)).cast(), - ) - }; + zelf.set_callback(args.progress_handler, CallbackKind::Progress(args.n), vm) + } - Ok(()) + fn set_callback( + &self, + callable: PyObjectRef, + kind: CallbackKind, + vm: &VirtualMachine, + ) -> PyResult<()> { + with_deferred_drops(|| { + let db = self.db_lock(vm)?; + let mut data = CallbackData::new(callable, vm).map(PyRc::new); + let pointer = data + .as_ref() + .map_or(null_mut(), |data| PyRc::as_ptr(data).cast_mut()); + let (closed, result, previous) = { + let _guard = db.lock(); + let mut callbacks = db.callbacks.lock(); + if callbacks.closed { + (true, Ok(SQLITE_OK), None) + } else { + let result = db.call(|| kind.register(db.raw, pointer)); + let previous = if result.is_ok() { + core::mem::replace(kind.slot(&mut callbacks), data.take()) + } else { + None + }; + (false, result, previous) + } + }; + // Both the native mutex and the slots mutex must be released + // before a displaced callable can run __del__ or weakref callbacks. + drop((previous, data)); + if closed { + return Err(new_programming_error( + vm, + "Cannot operate on a closed database.".to_owned(), + )); + } + db.check(result, vm).map_err(|error| { + if matches!(kind, CallbackKind::Authorizer) { + new_operational_error(vm, "Error setting authorizer callback".to_owned()) + } else { + error + } + }) + }) } #[pymethod] @@ -1559,6 +2045,108 @@ mod _sqlite3 { func.call(FuncArgs::new(vec![zelf.into()], kwargs), vm) } + #[pymethod] + fn serialize( + zelf: &Py, + args: DatabaseNameArgs, + vm: &VirtualMachine, + ) -> PyResult> { + use libsqlite3_sys::{SQLITE_SERIALIZE_NOCOPY, sqlite3_serialize}; + + with_deferred_drops(|| { + let name = args.name; + let db = zelf.db_lock(vm)?; + let bytes = { + // A no-copy SQLite view is only valid while no other operation + // can modify the database. Copy it before releasing the mutex. + let _guard = db.raw.lock(); + let mut size = 0; + let mut flags = SQLITE_SERIALIZE_NOCOPY; + let mut ptr = + unsafe { sqlite3_serialize(db.db, name.as_ptr(), &mut size, flags) }; + if ptr.is_null() { + flags = 0; + ptr = unsafe { sqlite3_serialize(db.db, name.as_ptr(), &mut size, flags) }; + } + let allocation = scopeguard::guard(ptr, |ptr| { + if flags == 0 { + unsafe { sqlite3_free(ptr.cast()) }; + } + }); + if allocation.is_null() { + return Err(new_operational_error( + vm, + format!("unable to serialize '{}'", name.owner.as_str()), + )); + } + let size = usize::try_from(size) + .ok() + .filter(|&n| isize::try_from(n).is_ok()) + .ok_or_else(|| vm.new_overflow_error("serialized database is too large"))?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(size) + .map_err(|_| vm.no_memory_error())?; + bytes.extend_from_slice(unsafe { + core::slice::from_raw_parts(*allocation, size) + }); + bytes + }; + Ok(vm.ctx.new_bytes(bytes)) + }) + } + + #[pymethod] + fn deserialize( + zelf: &Py, + args: DeserializeArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + use libsqlite3_sys::{ + SQLITE_DESERIALIZE_FREEONCLOSE, SQLITE_DESERIALIZE_RESIZEABLE, sqlite3_deserialize, + sqlite3_malloc64, + }; + + if let ArgStrOrBytesLike::Str(text) = &args.data { + text.try_as_utf8(vm)?; + } + with_deferred_drops(|| { + let name = args.name.to_cstring(vm)?; + let db = zelf.db_lock(vm)?; + let (allocation, size) = { + let bytes = args.data.borrow_bytes(); + let size = i64::try_from(bytes.len()) + .map_err(|_| vm.new_overflow_error("'data' is too large"))?; + let ptr = unsafe { sqlite3_malloc64(size as u64) }.cast::(); + if ptr.is_null() { + return Err(vm.no_memory_error()); + } + let allocation = + scopeguard::guard(ptr, |ptr| unsafe { sqlite3_free(ptr.cast()) }); + unsafe { + core::ptr::copy_nonoverlapping(bytes.as_ptr(), *allocation, bytes.len()) + }; + (allocation, size) + }; + // SQLite owns this allocation on both success and failure when + // FREEONCLOSE is set. No source-buffer borrow spans the call. + let ptr = scopeguard::ScopeGuard::into_inner(allocation); + db.checked( + || unsafe { + sqlite3_deserialize( + db.db, + name.as_ptr(), + ptr, + size, + size, + SQLITE_DESERIALIZE_FREEONCLOSE | SQLITE_DESERIALIZE_RESIZEABLE, + ) + }, + vm, + ) + }) + } + #[pymethod] fn interrupt(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { // DO NOT check thread safety @@ -1581,19 +2169,15 @@ mod _sqlite3 { } #[pymethod] - fn setconfig( - zelf: &Py, - op: c_int, - enable: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult<()> { + fn setconfig(zelf: &Py, args: SetConfigArgs, vm: &VirtualMachine) -> PyResult<()> { + let SetConfigArgs { op, enable } = args; let db = zelf.db_lock(vm)?; if !is_int_dbconfig(op) { return Err(vm.new_value_error(format!("unknown config 'op': {op}"))); } - let enable = enable.unwrap_or(true) as c_int; + let enable = enable.into_bool() as c_int; let mut actual: c_int = 0; - let rc = unsafe { sqlite3_db_config(db.db, op, enable, &mut actual) }; + let rc = db.call(|| unsafe { sqlite3_db_config(db.db, op, enable, &mut actual) }); db.check(rc, vm)?; if enable != actual { return Err(new_operational_error(vm, "Unable to set config".to_owned())); @@ -1608,7 +2192,7 @@ mod _sqlite3 { return Err(vm.new_value_error(format!("unknown config 'op': {op}"))); } let mut current: c_int = 0; - let rc = unsafe { sqlite3_db_config(db.db, op, -1, &mut current) }; + let rc = db.call(|| unsafe { sqlite3_db_config(db.db, op, -1, &mut current) }); db.check(rc, vm)?; Ok(current != 0) } @@ -1621,21 +2205,33 @@ mod _sqlite3 { #[pymethod] fn __exit__( zelf: &Py, - cls: PyObjectRef, - exc: PyObjectRef, - tb: PyObjectRef, + r#type: PyObjectRef, + value: PyObjectRef, + traceback: PyObjectRef, vm: &VirtualMachine, - ) -> PyResult<()> { - if vm.is_none(&cls) && vm.is_none(&exc) && vm.is_none(&tb) { - Self::commit(zelf, vm) + ) -> PyResult { + if vm.is_none(&r#type) && vm.is_none(&value) && vm.is_none(&traceback) { + if let Err(commit_error) = Self::commit(zelf, vm) { + // Release the failed transaction's locks, retaining the + // commit error if rollback succeeds or as the context if it fails. + return match Self::rollback(zelf, vm) { + Ok(()) => Err(commit_error), + Err(rollback_error) => { + rollback_error.set_context(Some(commit_error)); + Err(rollback_error) + } + }; + } } else { - Self::rollback(zelf, vm) + Self::rollback(zelf, vm)?; } + Ok(false) } #[pygetset] - fn isolation_level(zelf: &Py) -> Option { - zelf.isolation_level.deref().map(|x| x.to_owned()) + fn isolation_level(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + zelf._db_lock(vm)?; + Ok(zelf.isolation_level.deref().map(|x| x.to_owned())) } #[pygetset(setter)] fn set_isolation_level( @@ -1656,46 +2252,66 @@ mod _sqlite3 { let _ = unsafe { zelf.isolation_level.swap(value) }; Ok(()) } - PySetterValue::Delete => { - Err(vm.new_attribute_error("'isolation_level' attribute cannot be deleted")) - } + PySetterValue::Delete => Err(vm.new_attribute_error("cannot delete attribute")), } } #[pygetset] - fn autocommit(zelf: &Py, vm: &VirtualMachine) -> PyObjectRef { + fn autocommit(zelf: &Py, vm: &VirtualMachine) -> PyResult { + zelf.check_open(vm)?; let mode = *zelf.autocommit.lock(); - match mode { + Ok(match mode { AutocommitMode::Enabled => vm.ctx.true_value.clone().into(), AutocommitMode::Disabled => vm.ctx.false_value.clone().into(), AutocommitMode::Legacy => vm.ctx.new_int(LEGACY_TRANSACTION_CONTROL).into(), - } + }) } #[pygetset(setter)] - fn set_autocommit(zelf: &Py, val: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let mode = AutocommitMode::try_from_borrowed_object(vm, &val)?; - let db = zelf.db_lock(vm)?; - *zelf.autocommit.lock() = mode; + fn set_autocommit( + zelf: &Py, + val: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let PySetterValue::Assign(val) = val else { + return Err(vm.new_attribute_error("cannot delete autocommit attribute")); + }; + with_deferred_drops(|| Self::set_autocommit_inner(zelf, val, vm)) + } - // Handle transaction state based on mode change - match mode { - AutocommitMode::Enabled => { - // If there's a pending transaction, commit it - if !db.is_autocommit() { - db._exec(c"COMMIT", vm)?; + fn set_autocommit_inner( + zelf: &Py, + val: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let db = zelf.db_lock(vm)?; + let mode = AutocommitMode::try_from_borrowed_object(vm, &val)?; + let result = { + // Publish the Python mode and change SQLite's transaction state + // under the same mutex used by statement execution. + let _guard = db.lock(); + *zelf.autocommit.lock() = mode; + + // Handle transaction state based on mode change + match mode { + AutocommitMode::Enabled => { + // If there's a pending transaction, commit it + db.end_transaction(c"COMMIT", AutocommitMode::Legacy) } - } - AutocommitMode::Disabled => { - // If not in a transaction, begin one - if db.is_autocommit() { - db._exec(c"BEGIN", vm)?; + AutocommitMode::Disabled => { + // If not in a transaction, begin one + if db.is_autocommit() { + db.exec(c"BEGIN") + } else { + Ok(()) + } + } + AutocommitMode::Legacy => { + // Legacy mode doesn't change transaction state + Ok(()) } } - AutocommitMode::Legacy => { - // Legacy mode doesn't change transaction state - } - } - Ok(()) + }; + result.map_err(|err| err.into_exception(vm)) } #[pygetset] @@ -1756,12 +2372,16 @@ mod _sqlite3 { #[pygetset] fn in_transaction(zelf: &Py, vm: &VirtualMachine) -> PyResult { - zelf._db_lock(vm).map(|x| !x.is_autocommit()) + let db = zelf._db_lock(vm)?; + let _guard = db.lock(); + Ok(!db.is_autocommit()) } #[pygetset] fn total_changes(zelf: &Py, vm: &VirtualMachine) -> PyResult { - zelf._db_lock(vm).map(|x| x.total_changes()) + let db = zelf._db_lock(vm)?; + let _guard = db.lock(); + Ok(db.total_changes()) } #[pygetset(name = "Warning")] @@ -1812,7 +2432,7 @@ mod _sqlite3 { struct Cursor { connection: PyRef, #[pytraverse(skip)] - arraysize: PyAtomic, + arraysize: PyAtomic, #[pytraverse(skip)] row_factory: PyAtomicRef>, inner: PyMutex>, @@ -1826,15 +2446,25 @@ mod _sqlite3 { lastrowid: i64, #[pytraverse(skip)] rowcount: i64, - statement: Option>, + statement: Option, #[pytraverse(skip)] closed: bool, } #[derive(FromArgs)] struct FetchManyArgs { - #[pyarg(any, name = "size", optional)] - size: Option, + // Like Clinic, display the initial arraysize but read the current value + // when omitted. Explicit None must still fail integer conversion. + #[pyarg(any, optional, py_default = "1")] + size: OptionalArg, + } + + #[derive(FromArgs)] + struct SetOutputSizeArgs { + #[pyarg(positional)] + size: PyObjectRef, + #[pyarg(positional, optional)] + column: Option, } #[pyclass( @@ -1902,40 +2532,39 @@ mod _sqlite3 { #[pymethod] fn execute( + zelf: PyRef, + args: ExecuteArgs, + vm: &VirtualMachine, + ) -> PyResult> { + with_deferred_drops(|| Self::execute_inner(zelf, args.sql, args.parameters, vm)) + } + + fn execute_inner( zelf: PyRef, sql: PyUtf8StrRef, parameters: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { let mut inner = zelf.inner(vm)?; + zelf.connection.check_open(vm)?; if let Some(stmt) = inner.statement.take() { stmt.lock().reset(); } - let Some(stmt) = Statement::new(&zelf.connection, sql, vm)? else { + let Some(stmt) = zelf.connection.cached_statement(sql, vm)? else { drop(inner); return Ok(zelf); }; - let stmt = stmt.into_ref(&vm.ctx); inner.rowcount = if stmt.is_dml { 0 } else { -1 }; - let db = zelf.connection.db_lock(vm)?; + zelf.connection.check_open(vm)?; + let db = stmt.database(); // Only legacy transaction control starts implicit DML transactions. - if stmt.is_dml - && db.is_autocommit() - && zelf.connection.isolation_level.deref().is_some() - && *zelf.connection.autocommit.lock() == AutocommitMode::Legacy - { - db.begin_transaction( - zelf.connection - .isolation_level - .deref() - .map(|x| x.to_owned()), - vm, - )?; + if stmt.is_dml { + zelf.connection.begin_transaction(db.raw, vm)?; } let st = stmt.lock(); @@ -1950,57 +2579,66 @@ mod _sqlite3 { return Err(new_programming_error(vm, msg)); } + zelf.connection.check_open(vm)?; let ret = st.step(); - - if ret != SQLITE_DONE && ret != SQLITE_ROW { - if let Some(exc) = unsafe { user_function_exception().swap(None) } { - return Err(exc); - } - return Err(db.error_extended(vm)); - } + zelf.connection.check_open(vm)?; + let ret = ret.map_err(|error| { + unsafe { user_function_exception().swap(None) } + .unwrap_or_else(|| error.into_exception(vm)) + })?; inner.row_cast_map = zelf.build_row_cast_map(&st, vm)?; let detect_types = zelf.connection.detect_types.load(Ordering::Relaxed); inner.description = st.columns_description(detect_types, vm)?; - if ret == SQLITE_ROW { + if ret.has_row { drop(st); inner.statement = Some(stmt); } else { st.reset(); drop(st); if stmt.is_dml { - inner.rowcount += db.changes() as i64; + inner.rowcount += ret.changes as i64; } } - inner.lastrowid = db.lastrowid(); + inner.lastrowid = ret.lastrowid; drop(inner); - drop(db); Ok(zelf) } #[pymethod] fn executemany( + zelf: PyRef, + sql: PyUtf8StrRef, + seq_of_parameters: ArgIterable, + vm: &VirtualMachine, + ) -> PyResult> { + with_deferred_drops(|| Self::executemany_inner(zelf, sql, seq_of_parameters, vm)) + } + + fn executemany_inner( zelf: PyRef, sql: PyUtf8StrRef, seq_of_params: ArgIterable, vm: &VirtualMachine, ) -> PyResult> { let mut inner = zelf.inner(vm)?; + zelf.connection.check_open(vm)?; if let Some(stmt) = inner.statement.take() { stmt.lock().reset(); } - let Some(stmt) = Statement::new(&zelf.connection, sql, vm)? else { + let Some(stmt) = zelf.connection.cached_statement(sql, vm)? else { drop(inner); return Ok(zelf); }; - let stmt = stmt.into_ref(&vm.ctx); + zelf.connection.check_open(vm)?; + let db = stmt.database(); let st = stmt.lock(); if st.readonly() { @@ -2015,31 +2653,24 @@ mod _sqlite3 { inner.rowcount = if stmt.is_dml { 0 } else { -1 }; - let db = zelf.connection.db_lock(vm)?; - // Only legacy transaction control starts implicit DML transactions. - if stmt.is_dml - && db.is_autocommit() - && zelf.connection.isolation_level.deref().is_some() - && *zelf.connection.autocommit.lock() == AutocommitMode::Legacy - { - db.begin_transaction( - zelf.connection - .isolation_level - .deref() - .map(|x| x.to_owned()), - vm, - )?; + if stmt.is_dml { + zelf.connection.begin_transaction(db.raw, vm)?; } let iter = seq_of_params.iter(vm)?; for params in iter { let params = params?; + zelf.connection.check_open(vm)?; st.bind_parameters(¶ms, vm)?; + zelf.connection.check_open(vm)?; - if !st.step_row_else_done(vm)? { + let ret = st.step_checked(vm); + zelf.connection.check_open(vm)?; + let ret = ret?; + if !ret.has_row { if stmt.is_dml { - inner.rowcount += db.changes() as i64; + inner.rowcount += ret.changes as i64; } st.reset(); } @@ -2049,18 +2680,26 @@ mod _sqlite3 { // } } + zelf.connection.check_open(vm)?; if st.busy() { drop(st); inner.statement = Some(stmt); } drop(inner); - drop(db); Ok(zelf) } #[pymethod] fn executescript( + zelf: PyRef, + sql_script: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult> { + with_deferred_drops(|| Self::executescript_inner(zelf, sql_script, vm)) + } + + fn executescript_inner( zelf: PyRef, script: PyUtf8StrRef, vm: &VirtualMachine, @@ -2071,16 +2710,27 @@ mod _sqlite3 { db.sql_limit(script.byte_len(), vm)?; - if *zelf.connection.autocommit.lock() == AutocommitMode::Legacy { - db.implicit_commit(vm)?; - } + let result = zelf.connection.commit_before_script(db.raw, vm); + zelf.connection.check_open(vm)?; + result?; let script = script.to_cstring(vm)?; let mut sql = script.as_c_str(); let mut tail = null(); - while let Some(st) = db.prepare(sql, &mut tail, vm)? { - while st.step_row_else_done(vm)? {} + loop { + let statement = db.prepare(sql, &mut tail, vm); + zelf.connection.check_open(vm)?; + let Some(st) = statement? else { + break; + }; + loop { + let result = st.step_checked(vm); + zelf.connection.check_open(vm)?; + if !result?.has_row { + break; + } + } // SAFETY: SQLite advances the pointer w.r.t. `sql`, and `sql` is a valid CStr // without any interior NULs. sql = unsafe { CStr::from_ptr(tail) }; @@ -2104,16 +2754,9 @@ mod _sqlite3 { args: FetchManyArgs, vm: &VirtualMachine, ) -> PyResult> { - let max_rows = match args.size { - Some(size) => { - if size < 0 { - return Err(vm.new_value_error("fetchmany may not be negative")); - } - - size - } - None => zelf.arraysize.load(Ordering::Relaxed), - }; + let max_rows = args + .size + .unwrap_or_else(|| zelf.arraysize.load(Ordering::Relaxed)); let mut list = vec![]; let mut remaining = max_rows; @@ -2140,6 +2783,10 @@ mod _sqlite3 { #[pymethod] fn close(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + with_deferred_drops(|| Self::close_inner(zelf, vm)) + } + + fn close_inner(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { // Check if __init__ was called let mut guard = zelf.inner.lock(); @@ -2150,9 +2797,8 @@ mod _sqlite3 { )); }; - if let Some(stmt) = &inner.statement { - stmt.lock().reset(); - } + zelf.connection.check_open(vm)?; + drop(inner.statement.take()); inner.closed = true; Ok(()) @@ -2162,7 +2808,9 @@ mod _sqlite3 { fn setinputsizes(_zelf: &Py, _sizes: PyObjectRef) {} #[pymethod] - fn setoutputsize(_zelf: &Py, _size: PyObjectRef, _column: OptionalArg) {} + fn setoutputsize(_zelf: &Py, args: SetOutputSizeArgs) { + let _ = (args.size, args.column); + } #[pygetset] fn connection(zelf: &Py) -> PyRef { @@ -2185,18 +2833,35 @@ mod _sqlite3 { } #[pygetset] - fn arraysize(zelf: &Py) -> c_int { + fn arraysize(zelf: &Py) -> u32 { zelf.arraysize.load(Ordering::Relaxed) } #[pygetset(setter)] - fn set_arraysize(zelf: &Py, val: c_int, vm: &VirtualMachine) -> PyResult<()> { - if val < 0 { - return Err(vm.new_value_error("arraysize may not be negative")); - } - + fn set_arraysize( + zelf: &Py, + val: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let PySetterValue::Assign(val) = val else { + let message = { + let class = zelf.class(); + let slot_name = class.slot_name(); + // CPython's built-in Cursor uses the public module in tp_name. + let name = if class.is(Self::class(&vm.ctx)) { + "sqlite3.Cursor" + } else { + &slot_name + }; + let end = name.floor_char_boundary(name.len().min(100)); + format!( + "attribute 'arraysize' of '{}' objects cannot be deleted", + &name[..end] + ) + }; + return Err(vm.new_attribute_error(message)); + }; zelf.arraysize.store(val, Ordering::Relaxed); - Ok(()) } @@ -2206,8 +2871,16 @@ mod _sqlite3 { } #[pygetset(setter)] - fn set_row_factory(zelf: &Py, val: Option) { + fn set_row_factory( + zelf: &Py, + val: PySetterValue>, + vm: &VirtualMachine, + ) -> PyResult<()> { + let PySetterValue::Assign(val) = val else { + return Err(vm.new_attribute_error("cannot delete row_factory attribute")); + }; let _ = unsafe { zelf.row_factory.swap(val) }; + Ok(()) } fn build_row_cast_map( @@ -2227,22 +2900,31 @@ mod _sqlite3 { if detect_types & PARSE_COLNAMES != 0 { let col_name = st.column_name(i); let col_name = ptr_to_str(col_name, vm)?; - let col_name = col_name - .chars() - .skip_while(|&x| x != '[') - .skip(1) - .take_while(|&x| x != ']') - .flat_map(|x| x.to_uppercase()) - .collect::>(); - if let Some(converter) = converters().get_item_opt(&*col_name, vm)? { + let mut start = None; + let type_name = col_name.char_indices().find_map(|(index, ch)| match ch { + '[' => { + start = Some(index + 1); + None + } + ']' => start.map(|start| &col_name[start..index]), + _ => None, + }); + if let Some(type_name) = type_name + && let Some(converter) = + converters().get_item_opt(&type_name.to_uppercase(), vm)? + { cast_map.push(Some(converter)); continue; } } if detect_types & PARSE_DECLTYPES != 0 { let decltype = st.column_decltype(i); - let decltype = ptr_to_str(decltype, vm)?; - if let Some(decltype) = decltype.split_terminator(&[' ', '(']).next() { + // Expressions and columns without a declared type return NULL. + if !decltype.is_null() + && let Some(decltype) = ptr_to_str(decltype, vm)? + .split_terminator(&[' ', '(']) + .next() + { let decltype = decltype.to_uppercase(); if let Some(converter) = converters().get_item_opt(&decltype, vm)? { cast_map.push(Some(converter)); @@ -2293,24 +2975,29 @@ mod _sqlite3 { impl SelfIter for Cursor {} impl IterNext for Cursor { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - // Check if connection is closed first, and if so, clear statement to release file lock - if zelf.connection.is_closed() { - let mut guard = zelf.inner.lock(); - if let Some(stmt) = guard.as_mut().and_then(|inner| inner.statement.take()) { + with_deferred_drops(|| Self::next_inner(zelf, vm)) + } + } + + impl Cursor { + fn next_inner(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let mut inner = zelf.inner(vm)?; + zelf.connection.check_thread(vm)?; + if let Err(exc) = zelf.connection._db_lock(vm) { + // Preserve closed-database cleanup, but only after checking the + // cursor state and thread in CPython's order. + if zelf.connection.is_closed() + && let Some(stmt) = inner.statement.take() + { stmt.lock().reset(); } - return Err(new_programming_error( - vm, - "Cannot operate on a closed database.".to_owned(), - )); + return Err(exc); } - - let mut inner = zelf.inner(vm)?; let Some(stmt) = &inner.statement else { return Ok(PyIterReturn::StopIteration(None)); }; + let db = stmt.database(); let st = stmt.lock(); - let db = zelf.connection.db_lock(vm)?; // fetch_one_row let num_cols = st.data_count(); @@ -2330,7 +3017,9 @@ mod _sqlite3 { core::slice::from_raw_parts(blob.cast::(), nbytes as usize) }; let blob = vm.ctx.new_bytes(blob.to_vec()); - converter.call((blob,), vm)? + let value = converter.call((blob,), vm)?; + zelf.connection.check_open(vm)?; + value } } else { let col_type = st.column_type(i); @@ -2362,7 +3051,9 @@ mod _sqlite3 { PyByteArray::from(text).into_ref(&vm.ctx).into() } else { let bytes = vm.ctx.new_bytes(text); - text_factory.call((bytes,), vm)? + let value = text_factory.call((bytes,), vm)?; + zelf.connection.check_open(vm)?; + value } } SQLITE_BLOB => { @@ -2386,11 +3077,14 @@ mod _sqlite3 { row.push(val); } - if !st.step_row_else_done(vm)? { + let ret = st.step_checked(vm); + zelf.connection.check_open(vm)?; + let ret = ret?; + if !ret.has_row { st.reset(); drop(st); if stmt.is_dml { - inner.rowcount = db.changes() as i64; + inner.rowcount = ret.changes as i64; } inner.statement = None; } else { @@ -2553,32 +3247,177 @@ mod _sqlite3 { } } - #[pyattr] - #[pyclass(module = "sqlite3", name = "Blob", traverse)] - #[derive(Debug, PyPayload)] - struct Blob { - connection: PyRef, - #[pytraverse(skip)] - inner: PyMutex>, + #[pyattr] + #[pyclass(module = "sqlite3", name = "Blob", traverse)] + #[derive(Debug, PyPayload)] + struct Blob { + connection: PyRef, + #[pytraverse(skip)] + inner: PyMutex>, + } + + struct BlobInner { + blob: SqliteBlob, + offset: c_int, + db: PyRc, + } + + impl Debug for BlobInner { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("BlobInner") + .field("blob", &self.blob) + .field("offset", &self.offset) + .finish_non_exhaustive() + } + } + + impl BlobInner { + fn check(&self, ret: c_int, vm: &VirtualMachine) -> PyResult<()> { + if ret == SQLITE_OK { + Ok(()) + } else { + Err(self.db.error_extended(vm)) + } + } + } + + impl Drop for BlobInner { + fn drop(&mut self) { + self.db.pending.lock().blobs.push(self.blob); + self.db.flush_cleanup(); + } + } + + struct BlobGuard<'a> { + inner: Option>, + _db: SqliteOperation, + } + + impl<'a> BlobGuard<'a> { + fn new(inner: PyMappedMutexGuard<'a, BlobInner>) -> Self { + let db = SqliteOperation(inner.db.clone()); + Self { + inner: Some(inner), + _db: db, + } + } + } + + impl Deref for BlobGuard<'_> { + type Target = BlobInner; + + fn deref(&self) -> &Self::Target { + self.inner.as_deref().unwrap() + } + } + + impl DerefMut for BlobGuard<'_> { + fn deref_mut(&mut self) -> &mut Self::Target { + self.inner.as_deref_mut().unwrap() + } + } + + impl Drop for BlobGuard<'_> { + fn drop(&mut self) { + // The operation drains pending cleanup after releasing the blob lock. + self.inner.take(); + } + } + + #[cfg(test)] + #[cfg(feature = "threading")] + mod tests { + use super::*; + use core::time::Duration; + use std::sync::mpsc; + + #[test] + fn blob_operation_drains_contended_cleanup() { + let mut raw = null_mut(); + assert_eq!( + unsafe { + sqlite3_open_v2( + c":memory:".as_ptr(), + &mut raw, + SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, + null(), + ) + }, + SQLITE_OK + ); + let db = PyRc::new(Sqlite::from(SqliteRaw { db: raw })); + assert!( + db.exec(c"CREATE TABLE t(b); INSERT INTO t VALUES (zeroblob(1))") + .is_ok() + ); + let open_blob = || { + let mut blob = null_mut(); + assert_eq!( + unsafe { + sqlite3_blob_open( + db.db, + c"main".as_ptr(), + c"t".as_ptr(), + c"b".as_ptr(), + 1, + 0, + &mut blob, + ) + }, + SQLITE_OK + ); + BlobInner { + blob: SqliteBlob { blob }, + offset: 0, + db: db.clone(), + } + }; + let inner = PyMutex::new(Some(open_blob())); + let retired = open_blob(); + let guard = BlobGuard::new(PyMutexGuard::map(inner.lock(), |x| x.as_mut().unwrap())); + let (locked_tx, locked_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + let other = db.clone(); + let worker = std::thread::spawn(move || { + let _lock = other.raw.lock(); + locked_tx.send(()).unwrap(); + release_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + }); + locked_rx.recv_timeout(Duration::from_secs(5)).unwrap(); + // Reproduce close() losing both nonblocking cleanup attempts. + db.pending.lock().clear_callbacks = true; + db.flush_cleanup(); + drop(retired); + assert_eq!(db.pending.lock().blobs.len(), 1); + release_tx.send(()).unwrap(); + worker.join().unwrap(); + assert!(db.pending.lock().clear_callbacks); + drop(guard); + assert!(db.pending.lock().is_empty()); + } } - #[derive(Debug)] - struct BlobInner { - blob: SqliteBlob, - offset: c_int, + #[derive(FromArgs)] + struct BlobReadArgs { + #[pyarg(positional, default = -1)] + length: c_int, } - impl Drop for BlobInner { - fn drop(&mut self) { - unsafe { sqlite3_blob_close(self.blob.blob) }; - } + #[derive(FromArgs)] + struct BlobSeekArgs { + #[pyarg(positional)] + offset: c_int, + #[pyarg(positional, default = 0)] + origin: c_int, } #[pyclass(flags(DISALLOW_INSTANTIATION), with(AsMapping, AsNumber, AsSequence))] impl Blob { #[pymethod] fn close(zelf: &Py) { - zelf.inner.lock().take(); + with_deferred_drops(|| { + let _inner = zelf.inner.lock().take(); + }); } fn ensure_connection_open(&self, vm: &VirtualMachine) -> PyResult<()> { @@ -2595,12 +3434,12 @@ mod _sqlite3 { #[pymethod] fn read( zelf: &Py, - length: OptionalArg, + args: BlobReadArgs, vm: &VirtualMachine, ) -> PyResult> { zelf.ensure_connection_open(vm)?; - let mut length = length.unwrap_or(-1); + let mut length = args.length; let mut inner = zelf.inner(vm)?; let blob_len = inner.blob.bytes(); let max_read = blob_len - inner.offset; @@ -2616,7 +3455,7 @@ mod _sqlite3 { let ret = inner .blob .read(buf.as_mut_ptr().cast(), length, inner.offset); - zelf.check(ret, vm)?; + inner.check(ret, vm)?; unsafe { buf.set_len(length as usize) }; inner.offset += length; Ok(vm.ctx.new_bytes(buf)) @@ -2634,7 +3473,7 @@ mod _sqlite3 { inner.blob.write(buf.as_ptr().cast(), length, inner.offset) }); - zelf.check(ret, vm)?; + inner.check(ret, vm)?; inner.offset += length; Ok(()) } @@ -2646,14 +3485,9 @@ mod _sqlite3 { } #[pymethod] - fn seek( - zelf: &Py, - mut offset: c_int, - origin: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult<()> { + fn seek(zelf: &Py, args: BlobSeekArgs, vm: &VirtualMachine) -> PyResult<()> { zelf.ensure_connection_open(vm)?; - let origin = origin.unwrap_or(libc::SEEK_SET); + let BlobSeekArgs { mut offset, origin } = args; let mut inner = zelf.inner(vm)?; let blob_len = inner.blob.bytes(); @@ -2688,19 +3522,25 @@ mod _sqlite3 { } #[pymethod] - fn __exit__(zelf: &Py, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + fn __exit__( + zelf: &Py, + _type: PyObjectRef, + _val: PyObjectRef, + _tb: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { zelf.ensure_connection_open(vm)?; let _ = zelf.inner(vm)?; Self::close(zelf); - Ok(()) + Ok(false) } - fn inner(&self, vm: &VirtualMachine) -> PyResult> { + fn inner(&self, vm: &VirtualMachine) -> PyResult> { let guard = self.inner.lock(); if guard.is_some() { - Ok(PyMutexGuard::map(guard, |x| unsafe { - x.as_mut().unwrap_unchecked() - })) + Ok(BlobGuard::new(PyMutexGuard::map(guard, |x| { + x.as_mut().unwrap() + }))) } else { Err(new_programming_error( vm, @@ -2709,15 +3549,31 @@ mod _sqlite3 { } } - fn wrapped_index(index: PyIntRef, length: c_int, vm: &VirtualMachine) -> PyResult { - let mut index = index.try_to_primitive::(vm)?; + fn wrapped_index( + index: PyIntRef, + object: &PyObject, + length: c_int, + vm: &VirtualMachine, + ) -> PyResult { + let mut index = index.try_to_primitive::(vm).map_err(|_| { + let class = object.class(); + let type_name = class.slot_name(); + let mut end = type_name.len().min(200); + while !type_name.is_char_boundary(end) { + end -= 1; + } + vm.new_index_error(format!( + "cannot fit '{}' into an index-sized integer", + &type_name[..end] + )) + })?; if index < 0 { - index += length; + index += length as isize; } - if index < 0 || index >= length { + if index < 0 || index >= length as isize { Err(vm.new_index_error("Blob index out of range")) } else { - Ok(index) + Ok(index as c_int) } } @@ -2736,18 +3592,29 @@ mod _sqlite3 { } fn subscript(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + with_deferred_drops(|| Self::subscript_inner(self, needle, vm)) + } + + fn subscript_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { self.ensure_connection_open(vm)?; let inner = self.inner(vm)?; if let Some(index) = needle.try_index_opt(vm) { let blob_len = inner.blob.bytes(); - let index = Self::wrapped_index(index?, blob_len, vm)?; + let index = Self::wrapped_index(index?, needle, blob_len, vm)?; let mut byte: u8 = 0; let ret = inner.blob.read_single(&mut byte, index); - self.check(ret, vm).map(|_| vm.ctx.new_int(byte).into()) + inner.check(ret, vm).map(|_| vm.ctx.new_int(byte).into()) } else if let Some(slice) = needle.downcast_ref::() { - let blob_len = inner.blob.bytes(); let slice = slice.to_saturated(vm)?; - let (range, step, length) = slice.adjust_indices(blob_len as usize); + let (range, step, length) = slice.adjust_indices(inner.blob.bytes() as usize); + if length == 0 { + return Ok(vm.ctx.empty_bytes.clone().into()); + } + if step < 0 { + return Err( + vm.new_value_error("Blob doesn't support slices with a negative step") + ); + } let mut buf = Vec::::with_capacity(length); if step == 1 { @@ -2756,14 +3623,14 @@ mod _sqlite3 { length as c_int, range.start as c_int, ); - self.check(ret, vm)?; + inner.check(ret, vm)?; unsafe { buf.set_len(length) }; } else { let iter = SaturatedSliceIter::from_adjust_indices(range, step, length); let mut byte: u8 = 0; for index in iter { let ret = inner.blob.read_single(&mut byte, index as c_int); - self.check(ret, vm)?; + inner.check(ret, vm)?; buf.push(byte); } } @@ -2778,6 +3645,15 @@ mod _sqlite3 { needle: &PyObject, value: Option, vm: &VirtualMachine, + ) -> PyResult<()> { + with_deferred_drops(|| Self::ass_subscript_inner(self, needle, value, vm)) + } + + fn ass_subscript_inner( + &self, + needle: &PyObject, + value: Option, + vm: &VirtualMachine, ) -> PyResult<()> { self.ensure_connection_open(vm)?; let inner = self.inner(vm)?; @@ -2794,7 +3670,7 @@ mod _sqlite3 { ))); }; let blob_len = inner.blob.bytes(); - let index = Self::wrapped_index(index?, blob_len, vm)?; + let index = Self::wrapped_index(index?, needle, blob_len, vm)?; // Mirror CPython ass_subscript_index: use PyLong_AsLong, treat any // overflow (e.g. 2**65) as -1, then validate the [0, 255] range. let val = int_val.as_bigint().to_i64().unwrap_or(-1); @@ -2802,26 +3678,20 @@ mod _sqlite3 { return Err(vm.new_value_error("byte must be in range(0, 256)")); } let ret = inner.blob.write_single(val as u8, index); - self.check(ret, vm) + inner.check(ret, vm) } else if let Some(slice) = needle.downcast_ref::() { // Handle slice assignment: blob[a:b:c] = b"..." let Some(value) = value else { return Err(vm.new_type_error("Blob doesn't support slice deletion")); }; - let value_buf = PyBuffer::try_from_borrowed_object(vm, &value)?; + let slice = slice.to_saturated(vm)?; + let (range, step, slice_len) = slice.adjust_indices(inner.blob.bytes() as usize); + let value_buf = PyBuffer::try_from_borrowed_object(vm, &value)?; let buf = value_buf .as_contiguous() .ok_or_else(|| vm.new_buffer_error("underlying buffer is not C-contiguous"))?; - let blob_len = inner.blob.bytes(); - let slice = slice.to_saturated(vm)?; - let (range, step, slice_len) = slice.adjust_indices(blob_len as usize); - - if step == 0 { - return Err(vm.new_value_error("slice step cannot be zero")); - } - if buf.len() != slice_len { return Err(vm.new_index_error("Blob slice assignment is wrong size")); } @@ -2829,6 +3699,11 @@ mod _sqlite3 { if slice_len == 0 { return Ok(()); } + if step < 0 { + return Err( + vm.new_value_error("Blob doesn't support slices with a negative step") + ); + } if step == 1 { let ret = inner.blob.write( @@ -2836,7 +3711,7 @@ mod _sqlite3 { buf.len() as c_int, range.start as c_int, ); - self.check(ret, vm) + inner.check(ret, vm) } else { let span_len = range.end - range.start; let range_start = range.start; @@ -2847,7 +3722,7 @@ mod _sqlite3 { span_len as c_int, range_start as c_int, ); - self.check(ret, vm)?; + inner.check(ret, vm)?; let iter = SaturatedSliceIter::from_adjust_indices(range, step, slice_len); for (i_in_src, abs_idx) in iter.enumerate() { @@ -2859,20 +3734,12 @@ mod _sqlite3 { span_len as c_int, range_start as c_int, ); - self.check(ret, vm) + inner.check(ret, vm) } } else { Err(vm.new_type_error("Blob indices must be integers")) } } - - fn check(&self, ret: c_int, vm: &VirtualMachine) -> PyResult<()> { - if ret == SQLITE_OK { - Ok(()) - } else { - Err(self.connection.db_lock(vm)?.error_extended(vm)) - } - } } impl AsMapping for Blob { @@ -2950,6 +3817,7 @@ mod _sqlite3 { struct Statement { st: PyMutex, pub is_dml: bool, + in_use: PyAtomic, } impl Debug for Statement { @@ -2973,16 +3841,13 @@ mod _sqlite3 { new_programming_error(vm, "statement contains a null character.".to_owned()) })?; - let raw = { - let db = connection.db_lock(vm)?; - db.sql_limit(sql.byte_len(), vm)?; - **db - }; - + let db = connection.db_lock(vm)?; + db.sql_limit(sql.byte_len(), vm)?; let mut tail = null(); - let st = raw.prepare(&sql_cstr, &mut tail, vm)?; + let st = db.prepare(&sql_cstr, &mut tail, vm); + connection.check_open(vm)?; - let Some(st) = st else { + let Some(st) = st? else { return Ok(None); }; @@ -3008,6 +3873,7 @@ mod _sqlite3 { Ok(Some(Self { st: PyMutex::from(st), is_dml, + in_use: Radium::new(false), })) } @@ -3016,13 +3882,322 @@ mod _sqlite3 { } } + struct StatementCache { + capacity: usize, + generation: u64, + entries: indexmap::IndexMap, PyRef>, + } + + impl StatementCache { + fn new(capacity: c_int) -> Self { + Self { + capacity: capacity.max(0) as usize, + generation: 0, + entries: indexmap::IndexMap::new(), + } + } + } + + #[derive(Debug)] + struct StatementLease(PyRef); + + impl StatementLease { + fn acquire(statement: PyRef) -> Option { + statement + .in_use + .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) + .ok() + .map(|_| Self(statement)) + } + + fn database(&self) -> SqliteOperation { + // The statement owns a live connection, not just memory retained by + // sqlite3_close_v2. Reinitialization may replace Connection.db while + // existing cursors continue reading this original database. + SqliteOperation(self.lock().db.clone()) + } + } + + impl Deref for StatementLease { + type Target = Statement; + + fn deref(&self) -> &Statement { + &self.0 + } + } + + // SAFETY: the lease owns exactly one reference to its statement. + unsafe impl Traverse for StatementLease { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.0.traverse(tracer); + } + } + + impl Drop for StatementLease { + fn drop(&mut self) { + with_deferred_drops(|| { + let statement = self.0.lock(); + // Reset can delay cleanup queued by another thread's BLOB close. + let _db = SqliteOperation(statement.db.clone()); + statement.reset(); + // Cached statements must not retain previous parameter buffers. + unsafe { sqlite3_clear_bindings(statement.st) }; + drop(statement); + self.0.in_use.store(false, Ordering::Release); + }); + } + } + struct Sqlite { raw: SqliteRaw, + pending: PyMutex, + callbacks: PyMutex, + } + + #[derive(Default)] + struct CallbackSlots { + trace: Option>, + progress: Option>, + authorizer: Option>, + closed: bool, + } + + #[derive(Clone, Copy)] + enum CallbackKind { + Trace, + Progress(c_int), + Authorizer, + } + + impl CallbackKind { + fn slot(self, slots: &mut CallbackSlots) -> &mut Option> { + match self { + Self::Trace => &mut slots.trace, + Self::Progress(_) => &mut slots.progress, + Self::Authorizer => &mut slots.authorizer, + } + } + + // The caller holds the native mutex and retains data until unregistration. + fn register(self, db: SqliteRaw, data: *mut CallbackData) -> c_int { + unsafe { + match self { + Self::Trace => sqlite3_trace_v2( + db.db, + SQLITE_TRACE_STMT, + (!data.is_null()).then_some(CallbackData::trace_callback), + data.cast(), + ), + Self::Progress(n) => { + sqlite3_progress_handler( + db.db, + n, + (!data.is_null()).then_some(CallbackData::progress_callback), + data.cast(), + ); + SQLITE_OK + } + Self::Authorizer => sqlite3_set_authorizer( + db.db, + (!data.is_null()).then_some(CallbackData::authorizer_callback), + data.cast(), + ), + } + } + } + } + + #[derive(Default)] + struct SqliteCleanup { + statements: Vec, + blobs: Vec, + rollback: bool, + clear_callbacks: bool, + disable_callbacks: bool, + } + + impl SqliteCleanup { + fn is_empty(&self) -> bool { + self.statements.is_empty() + && self.blobs.is_empty() + && !self.rollback + && !self.clear_callbacks + && !self.disable_callbacks + } } impl From for Sqlite { fn from(raw: SqliteRaw) -> Self { - Self { raw } + Self { + raw, + pending: PyMutex::new(SqliteCleanup::default()), + callbacks: PyMutex::new(CallbackSlots::default()), + } + } + } + + impl Sqlite { + fn disable_callbacks(&self) { + self.pending.lock().disable_callbacks = true; + self.flush_cleanup(); + } + + fn flush_cleanup(&self) { + self.drain_cleanup(false); + } + + fn drain_cleanup(&self, wait: bool) { + if self.pending.lock().is_empty() { + return; + } + with_deferred_drops(|| { + loop { + let guard = if wait { + Some(self.raw.lock()) + } else { + self.raw.try_lock() + }; + let Some(guard) = guard else { + return; + }; + // Never keep a Rust mutex while SQLite can invoke Python. + let pending = core::mem::take(&mut *self.pending.lock()); + if pending.disable_callbacks { + self.remove_callbacks(); + } + if pending.rollback && !self.is_autocommit() { + // close() has already returned; like sqlite3_close_v2, + // deferred rollback cannot report an error to its caller. + unsafe { + sqlite3_exec( + self.db, + c"ROLLBACK".as_ptr(), + None, + null_mut(), + null_mut(), + ) + }; + } + for statement in pending.statements { + unsafe { sqlite3_finalize(statement.st) }; + } + for blob in pending.blobs { + unsafe { sqlite3_blob_close(blob.blob) }; + } + let callbacks = pending.clear_callbacks.then(|| self.clear_callbacks()); + drop(guard); + drop(callbacks); + // An enqueue after this check can acquire the native mutex and + // drain itself; one made while it was locked must be retried. + if self.pending.lock().is_empty() { + return; + } + } + }); + } + + fn close_callbacks(&self, rollback: bool, vm: &VirtualMachine) -> PyResult<()> { + self.callbacks.lock().closed = true; + if let Some(guard) = self.raw.try_lock() { + let disable_callbacks = core::mem::take(&mut self.pending.lock().disable_callbacks); + if disable_callbacks { + self.remove_callbacks(); + } + let result = if rollback && !self.is_autocommit() { + self._exec(c"ROLLBACK", vm) + } else { + Ok(()) + }; + self.pending.lock().clear_callbacks = true; + drop(guard); + self.flush_cleanup(); + result + } else { + { + let mut pending = self.pending.lock(); + pending.rollback |= rollback; + pending.clear_callbacks = true; + } + // Retry after enqueueing, in case the active call just ended. + self.flush_cleanup(); + Ok(()) + } + } + + // The native mutex is held. SQLite must stop using the pointers first. + fn remove_callbacks(&self) { + for kind in [ + CallbackKind::Trace, + CallbackKind::Progress(0), + CallbackKind::Authorizer, + ] { + kind.register(self.raw, null_mut()); + } + } + + fn clear_callbacks(&self) -> [Option>; 3] { + self.remove_callbacks(); + let mut slots = self.callbacks.lock(); + [ + slots.trace.take(), + slots.progress.take(), + slots.authorizer.take(), + ] + } + } + + // An operation retains its database and drains work deferred by a close + // callback after SQLite has released its native connection mutex. + struct SqliteOperation(PyRc); + + impl Deref for SqliteOperation { + type Target = Sqlite; + + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + impl Drop for SqliteOperation { + fn drop(&mut self) { + self.flush_cleanup(); + } + } + + impl SqliteOperation { + fn prepare( + &self, + sql: &CStr, + tail: &mut *const libc::c_char, + vm: &VirtualMachine, + ) -> PyResult> { + self.raw.prepare(sql, tail, vm).map(|statement| { + statement.map(|raw| SqliteStatement { + raw, + db: self.0.clone(), + }) + }) + } + } + + struct SqliteMutex(*mut libsqlite3_sys::sqlite3_mutex); + + impl Drop for SqliteMutex { + fn drop(&mut self) { + unsafe { sqlite3_mutex_leave(self.0) }; + } + } + + struct SqliteError { + code: c_int, + extended: c_int, + message: String, + } + + impl SqliteError { + fn into_exception(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + let typ = exception_type_from_errcode(self.code, vm); + raise_exception(typ.to_owned(), self.extended, self.message, vm) } } @@ -3035,8 +4210,18 @@ mod _sqlite3 { impl Drop for Sqlite { fn drop(&mut self) { + // No operation or statement owner remains. Drain native handles + // queued by their destructors before closing the database. + self.drain_cleanup(true); // Use sqlite3_close_v2 for safe closing even with active statements - unsafe { sqlite3_close_v2(self.raw.db) }; + with_deferred_drops(|| { + let callbacks = { + let _guard = self.raw.lock(); + self.clear_callbacks() + }; + drop(callbacks); + unsafe { sqlite3_close_v2(self.raw.db) }; + }); } } @@ -3058,7 +4243,9 @@ mod _sqlite3 { unsafe impl Send for SqliteStatement {} // unsafe impl Sync for SqliteStatement {} unsafe impl Send for Sqlite {} - // unsafe impl Sync for Sqlite {} + // SAFETY: connections use FULLMUTEX and require a native mutex. + // Owned references delay closing until active operations finish. + unsafe impl Sync for Sqlite {} unsafe impl Send for SqliteBlob {} } _ => {} @@ -3075,23 +4262,58 @@ mod _sqlite3 { } impl SqliteRaw { - fn check(self, ret: c_int, vm: &VirtualMachine) -> PyResult<()> { - if ret == SQLITE_OK { - Ok(()) + fn lock(self) -> SqliteMutex { + let mutex = unsafe { sqlite3_db_mutex(self.db) }; + unsafe { sqlite3_mutex_enter(mutex) }; + SqliteMutex(mutex) + } + + fn try_lock(self) -> Option { + let mutex = unsafe { sqlite3_db_mutex(self.db) }; + if unsafe { sqlite3_mutex_try(mutex) } == SQLITE_OK { + Some(SqliteMutex(mutex)) } else { - Err(self.error_extended(vm)) + None } } - fn error_extended(self, vm: &VirtualMachine) -> PyBaseExceptionRef { - let errcode = unsafe { sqlite3_errcode(self.db) }; - let typ = exception_type_from_errcode(errcode, vm); - let extended_errcode = unsafe { sqlite3_extended_errcode(self.db) }; - let errmsg = unsafe { sqlite3_errmsg(self.db) }; - let errmsg = unsafe { CStr::from_ptr(errmsg) }; - let errmsg = errmsg.to_str().unwrap().to_owned(); + fn call(self, call: impl FnOnce() -> c_int) -> Result { + let _guard = self.lock(); + let ret = call(); + if matches!(ret, SQLITE_OK | SQLITE_ROW | SQLITE_DONE) { + Ok(ret) + } else { + Err(self.error_snapshot()) + } + } + + fn check(self, result: Result, vm: &VirtualMachine) -> PyResult<()> { + result.map(drop).map_err(|err| err.into_exception(vm)) + } - raise_exception(typ.to_owned(), extended_errcode, errmsg, vm) + fn checked(self, call: impl FnOnce() -> c_int, vm: &VirtualMachine) -> PyResult<()> { + self.check(self.call(call), vm) + } + + // The caller holds the connection mutex from before the failed call. + fn error_snapshot(self) -> SqliteError { + unsafe { + SqliteError { + code: sqlite3_errcode(self.db), + extended: sqlite3_extended_errcode(self.db), + message: CStr::from_ptr(sqlite3_errmsg(self.db)) + .to_string_lossy() + .into_owned(), + } + } + } + + fn error_extended(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + let error = { + let _guard = self.lock(); + self.error_snapshot() + }; + error.into_exception(vm) } fn open(path: *const libc::c_char, uri: bool, vm: &VirtualMachine) -> PyResult { @@ -3102,17 +4324,28 @@ mod _sqlite3 { &raw mut db, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE + | SQLITE_OPEN_FULLMUTEX | if uri { SQLITE_OPEN_URI } else { 0 }, null(), ) }; let zelf = Self { db }; - zelf.check(ret, vm).map(|_| zelf) + if ret == SQLITE_OK { + Ok(zelf) + } else { + Err(zelf.error_extended(vm)) + } } fn _exec(self, sql: &CStr, vm: &VirtualMachine) -> PyResult<()> { - let ret = unsafe { sqlite3_exec(self.db, sql.as_ptr(), None, null_mut(), null_mut()) }; - self.check(ret, vm) + self.exec(sql).map_err(|err| err.into_exception(vm)) + } + + fn exec(self, sql: &CStr) -> Result<(), SqliteError> { + self.call(|| unsafe { + sqlite3_exec(self.db, sql.as_ptr(), None, null_mut(), null_mut()) + }) + .map(drop) } fn prepare( @@ -3120,14 +4353,16 @@ mod _sqlite3 { sql: &CStr, tail: &mut *const libc::c_char, vm: &VirtualMachine, - ) -> PyResult> { + ) -> PyResult> { let mut st = null_mut(); - let ret = unsafe { sqlite3_prepare_v2(self.db, sql.as_ptr(), -1, &mut st, tail) }; - self.check(ret, vm)?; + self.checked( + || unsafe { sqlite3_prepare_v2(self.db, sql.as_ptr(), -1, &mut st, tail) }, + vm, + )?; if st.is_null() { Ok(None) } else { - Ok(Some(SqliteStatement::from(SqliteStatementRaw::from(st)))) + Ok(Some(SqliteStatementRaw::from(st))) } } @@ -3167,19 +4402,20 @@ mod _sqlite3 { unsafe { sqlite3_last_insert_rowid(self.db) } } - fn implicit_commit(self, vm: &VirtualMachine) -> PyResult<()> { - if self.is_autocommit() { - Ok(()) - } else { - self._exec(c"COMMIT", vm) + // The caller holds the native mutex across checking the mode and the + // complete transition, including reopening a PEP 249 transaction. + fn end_transaction(self, sql: &CStr, mode: AutocommitMode) -> Result<(), SqliteError> { + match mode { + AutocommitMode::Legacy if !self.is_autocommit() => self.exec(sql), + AutocommitMode::Disabled => { + self.exec(sql)?; + self.exec(c"BEGIN") + } + _ => Ok(()), } } - fn begin_transaction( - self, - isolation_level: Option, - vm: &VirtualMachine, - ) -> PyResult<()> { + fn begin_transaction(self, isolation_level: Option) -> Result<(), SqliteError> { let Some(isolation_level) = isolation_level else { return Ok(()); }; @@ -3189,7 +4425,7 @@ mod _sqlite3 { s.push(b'\0'); // SAFETY: isolation_level is checked for interior NULs on construction let cs = unsafe { CStr::from_bytes_with_nul_unchecked(&s) }; - self._exec(cs, vm) + self.exec(cs) } fn interrupt(self) { @@ -3225,7 +4461,7 @@ mod _sqlite3 { destroy: Option, vm: &VirtualMachine, ) -> PyResult<()> { - let ret = unsafe { + let ret = self.call(|| unsafe { sqlite3_create_function_v2( self.db, name.as_ptr(), @@ -3237,7 +4473,7 @@ mod _sqlite3 { finalize, destroy, ) - }; + }); self.check(ret, vm) .map_err(|_| new_operational_error(vm, "Error creating function".to_owned())) } @@ -3245,19 +4481,17 @@ mod _sqlite3 { struct SqliteStatement { raw: SqliteStatementRaw, - } - - impl From for SqliteStatement { - fn from(raw: SqliteStatementRaw) -> Self { - Self { raw } - } + // Keep the original database usable for cursors surviving __init__. + db: PyRc, } impl Drop for SqliteStatement { fn drop(&mut self) { - unsafe { - sqlite3_finalize(self.raw.st); - } + // Finalization may wait for a callback running on another thread. + // Queue only the raw handle, so pending cleanup cannot form an + // ownership cycle with the database. + self.db.pending.lock().statements.push(self.raw); + self.db.flush_cleanup(); } } @@ -3274,6 +4508,12 @@ mod _sqlite3 { st: *mut sqlite3_stmt, } + struct SqliteStep { + has_row: bool, + changes: c_int, + lastrowid: i64, + } + impl From<*mut sqlite3_stmt> for SqliteStatementRaw { fn from(st: *mut sqlite3_stmt) -> Self { Self { st } @@ -3281,21 +4521,26 @@ mod _sqlite3 { } impl SqliteStatementRaw { - fn step(self) -> c_int { - unsafe { sqlite3_step(self.st) } + fn step(self) -> Result { + let db = SqliteRaw::from(self); + let _guard = db.lock(); + let ret = db.call(|| unsafe { sqlite3_step(self.st) })?; + // These values belong to the connection, not the statement. Another + // cursor must not overwrite them between step and the snapshot. + Ok(SqliteStep { + has_row: ret == SQLITE_ROW, + changes: db.changes(), + lastrowid: db.lastrowid(), + }) } - fn step_row_else_done(self, vm: &VirtualMachine) -> PyResult { + fn step_checked(self, vm: &VirtualMachine) -> PyResult { let ret = self.step(); if let Some(exc) = unsafe { user_function_exception().swap(None) } { Err(exc) - } else if ret == SQLITE_ROW { - Ok(true) - } else if ret == SQLITE_DONE { - Ok(false) } else { - Err(SqliteRaw::from(self).error_extended(vm)) + ret.map_err(|err| err.into_exception(vm)) } } @@ -3326,23 +4571,24 @@ mod _sqlite3 { parameter }; + let db = SqliteRaw::from(self); let ret = if vm.is_none(obj) { - unsafe { sqlite3_bind_null(self.st, pos) } + db.call(|| unsafe { sqlite3_bind_null(self.st, pos) }) } else if let Some(val) = obj.downcast_ref::() { let val = val.try_to_primitive::(vm).map_err(|_| { vm.new_overflow_error("Python int too large to convert to SQLite INTEGER") })?; - unsafe { sqlite3_bind_int64(self.st, pos, val) } + db.call(|| unsafe { sqlite3_bind_int64(self.st, pos, val) }) } else if let Some(val) = obj.downcast_ref::() { let val = val.to_f64(); - unsafe { sqlite3_bind_double(self.st, pos, val) } + db.call(|| unsafe { sqlite3_bind_double(self.st, pos, val) }) } else if let Some(val) = obj.downcast_ref::() { let val = val.try_as_utf8(vm)?; let (ptr, len) = str_to_ptr_len(val, vm)?; - unsafe { sqlite3_bind_text(self.st, pos, ptr, len, SQLITE_TRANSIENT()) } + db.call(|| unsafe { sqlite3_bind_text(self.st, pos, ptr, len, SQLITE_TRANSIENT()) }) } else if let Ok(buffer) = PyBuffer::try_from_borrowed_object(vm, obj) { let (ptr, len) = buffer_to_ptr_len(&buffer, vm)?; - unsafe { sqlite3_bind_blob(self.st, pos, ptr, len, SQLITE_TRANSIENT()) } + db.call(|| unsafe { sqlite3_bind_blob(self.st, pos, ptr, len, SQLITE_TRANSIENT()) }) } else { return Err(new_programming_error( vm, @@ -3354,12 +4600,7 @@ mod _sqlite3 { )); }; - if ret == SQLITE_OK { - Ok(()) - } else { - let db = SqliteRaw::from(self); - db.check(ret, vm) - } + db.check(ret, vm) } fn bind_parameters(self, parameters: &PyObject, vm: &VirtualMachine) -> PyResult<()> { @@ -3585,10 +4826,13 @@ mod _sqlite3 { unsafe { sqlite3_user_data(self.ctx).cast() } } - fn aggregate_context(self) -> *mut T { - unsafe { - sqlite3_aggregate_context(self.ctx, core::mem::size_of::() as c_int).cast() - } + fn aggregate_context(self, create: bool) -> *mut *const PyObject { + let size = if create { + core::mem::size_of::<*const PyObject>() as c_int + } else { + 0 + }; + unsafe { sqlite3_aggregate_context(self.ctx, size).cast() } } fn result_exception(self, vm: &VirtualMachine, exc: PyBaseExceptionRef, msg: &CStr) { @@ -3599,9 +4843,8 @@ mod _sqlite3 { } else { unsafe { sqlite3_result_error(self.ctx, msg.as_ptr(), -1) } } - if enable_traceback().load(Ordering::Relaxed) { - vm.print_exception(&exc); - } + let callable = unsafe { (*self.user_data::()).obj.as_ref() }; + CallbackData::report_exception(callable, exc); } fn db_handle(self) -> *mut sqlite3 { diff --git a/crates/stdlib/src/_testconsole.rs b/crates/stdlib/src/_testconsole.rs index 3b7aad17178..670fdb79108 100644 --- a/crates/stdlib/src/_testconsole.rs +++ b/crates/stdlib/src/_testconsole.rs @@ -3,32 +3,58 @@ pub(crate) use _testconsole::module_def; #[pymodule] mod _testconsole { use crate::vm::{ - PyObjectRef, PyResult, VirtualMachine, convert::IntoPyException, function::ArgBytesLike, + AsObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::PyTypeRef, + convert::IntoPyException, function::ArgBytesLike, }; use rustpython_host_env::testconsole as host_testconsole; - #[pyfunction] - fn write_input(file: PyObjectRef, s: ArgBytesLike, vm: &VirtualMachine) -> PyResult<()> { - // Get the fd from the file object via fileno() - let fd_obj = vm.call_method(&file, "fileno", ())?; - let fd: i32 = fd_obj.try_into_value(vm)?; - - let data = s.borrow_buf(); - let data = &*data; + #[derive(FromArgs)] + struct WriteInputArgs { + #[pyarg(any)] + file: PyObjectRef, + #[pyarg(any)] + s: ArgBytesLike, + } - // Interpret as UTF-16-LE pairs - let (chunks, []) = data.as_chunks::<2>() else { - return Err(vm.new_value_error("buffer must contain UTF-16-LE data (even length)")); + #[pyfunction] + fn write_input(args: WriteInputArgs, vm: &VirtualMachine) -> PyResult<()> { + let s = args.s; + let console_type = { + let io = vm.import("_io", 0)?; + PyTypeRef::try_from_object(vm, io.get_attr("_WindowsConsoleIO", vm)?)? }; - let wchars: Vec = chunks - .iter() - .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])) - .collect(); - host_testconsole::write_console_input(fd, &wchars).map_err(|e| e.into_pyexception(vm)) + let is_console = args.file.fast_isinstance(&console_type); + drop(console_type); + if !is_console || crate::vm::stdlib::_io::raw_windows_console_fd(&args.file).is_none() { + return Err(vm.new_type_error("expected raw console object")); + } + // CPython interprets complete UTF-16-LE pairs and ignores a final byte. + // Release the buffer borrow before the OS call and error conversion. + let wchars: Vec = { + let data = s.borrow_buf(); + let (chunks, _) = data.as_chunks::<2>(); + // CPython's Windows implementation casts the byte length to DWORD first. + let count = (data.len() as u32 / 2) as usize; + chunks[..count] + .iter() + .map(|chunk| u16::from_le_bytes(*chunk)) + .collect() + }; + host_testconsole::write_console_input_with_fd(&wchars, || { + crate::vm::stdlib::_io::raw_windows_console_fd(&args.file).unwrap_or(-1) + }) + .map_err(|e| e.into_pyexception(vm)) + } + + #[derive(FromArgs)] + struct ReadOutputArgs { + #[pyarg(any)] + file: PyObjectRef, } #[pyfunction] - fn read_output(_file: PyObjectRef) -> Option<()> { + fn read_output(args: ReadOutputArgs) -> Option<()> { + let _file = args.file; // Stub, same as CPython None } diff --git a/crates/stdlib/src/_tokenize.rs b/crates/stdlib/src/_tokenize.rs index b439ddb6e0b..05c9854b24d 100644 --- a/crates/stdlib/src/_tokenize.rs +++ b/crates/stdlib/src/_tokenize.rs @@ -11,8 +11,10 @@ mod _tokenize { function::ArgCallable, protocol::PyIterReturn, types::{Constructor, IterNext, Iterable, SelfIter}, + vm::thread::PyOperation, }, }; + use alloc::sync::Arc; use core::fmt; use ruff_python_ast::PySourceType; use ruff_python_ast::token::{Token, TokenKind}; @@ -35,6 +37,7 @@ mod _tokenize { readline: ArgCallable, extra_tokens: bool, encoding: Option, + operation: PyOperation, state: PyRwLock, } @@ -82,7 +85,7 @@ mod _tokenize { impl Constructor for PyTokenizerIter { type Args = PyTokenizerIterArgs; - fn py_new(_cls: &Py, args: Self::Args, _vm: &VirtualMachine) -> PyResult { + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { let Self::Args { readline, extra_tokens, @@ -93,6 +96,7 @@ mod _tokenize { readline, extra_tokens, encoding: encoding.map(|s| s.to_string()), + operation: PyOperation::new(vm), state: PyRwLock::new(TokenizerState { phase: TokenizerPhase::Reading { source: String::new(), @@ -106,43 +110,66 @@ mod _tokenize { impl IterNext for PyTokenizerIter { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let mut state = zelf.state.read().clone(); - - loop { - match &mut state.phase { - TokenizerPhase::Reading { source } => { + zelf.operation.with(vm, || { + loop { + // No payload borrow survives readline, codec callbacks, or Python + // object construction. The operation can suspend or be reentered. + let reading = matches!(zelf.state.read().phase, TokenizerPhase::Reading { .. }); + if reading { let line = zelf.readline(vm)?; - if line.is_empty() { - let accumulated = core::mem::take(source); - let parsed = parse_unchecked_source(&accumulated, PySourceType::Python); - let tokens: Vec = parsed.tokens().iter().copied().collect(); - let errors: Vec = parsed.errors().to_vec(); - let line_index = LineIndex::from_source_text(&accumulated); - let implicit_nl = !accumulated.ends_with('\n'); - state.phase = TokenizerPhase::Yielding { - source: accumulated, - tokens, - errors, - index: 0, - line_index, - need_implicit_nl: implicit_nl, - pending_fstring_parts: Vec::new(), - pending_empty_fstring_middle: None, - }; - } else { - source.push_str(&line); + let mut state = zelf.state.write(); + // Another next() may have completed input while readline ran. + // Keep its frozen token snapshot and cursor; EOF is sticky. + // This remains an eager tokenizer, not CPython's streaming + // buffer/line-metadata model for reentrant callbacks. + if let TokenizerPhase::Reading { source } = &mut state.phase { + if line.is_empty() { + let accumulated = core::mem::take(source); + let parsed = + parse_unchecked_source(&accumulated, PySourceType::Python); + let tokens = parsed.tokens().iter().copied().collect(); + let errors = parsed.errors().to_vec(); + let line_index = LineIndex::from_source_text(&accumulated); + let implicit_nl = !accumulated.ends_with('\n'); + state.phase = TokenizerPhase::Yielding { + data: Arc::new(TokenizedSource { + source: accumulated, + tokens, + errors, + line_index, + }), + index: 0, + need_implicit_nl: implicit_nl, + pending_fstring_parts: None, + pending_empty_fstring_middle: None, + }; + } else { + source.push_str(&line); + } } + continue; } - TokenizerPhase::Yielding { .. } => { - let result = emit_next_token(&mut state, zelf.extra_tokens, vm)?; - *zelf.state.write() = state; - return Ok(result); - } - TokenizerPhase::Done => { - return Ok(PyIterReturn::StopIteration(None)); - } + let result = { + let mut shared = zelf.state.write(); + match shared.phase { + TokenizerPhase::Reading { .. } => continue, + TokenizerPhase::Done => return Ok(PyIterReturn::StopIteration(None)), + TokenizerPhase::Yielding { .. } => {} + } + // This native-only transaction never crosses a callback. + // Preserve the existing cursor on lexical errors. + let mut next = shared.clone(); + let result = emit_next_token(&mut next, zelf.extra_tokens); + if result.is_ok() { + *shared = next; + } + result + }; + return result + .map(|token| PyIterReturn::Return(token.into_object(vm))) + .map_err(|error| error.into_exception(vm)); } - } + }) } } @@ -150,14 +177,10 @@ mod _tokenize { fn emit_next_token( state: &mut TokenizerState, extra_tokens: bool, - vm: &VirtualMachine, - ) -> PyResult { + ) -> Result { let TokenizerPhase::Yielding { - source, - tokens, - errors, + data, index, - line_index, need_implicit_nl, pending_fstring_parts, pending_empty_fstring_middle, @@ -165,13 +188,18 @@ mod _tokenize { else { unreachable!() }; + let TokenizedSource { + source, + tokens, + errors, + line_index, + } = data.as_ref(); // Emit pending empty FSTRING_MIDDLE (for format spec nesting) if let Some((mid_type, mid_line, mid_col, mid_line_str)) = pending_empty_fstring_middle.take() { - return Ok(PyIterReturn::Return(make_token_tuple( - vm, + return Ok(TokenData::new( mid_type, "", mid_line, @@ -179,53 +207,147 @@ mod _tokenize { mid_line, mid_col as isize, &mid_line_str, - ))); + )); } // Emit any pending fstring sub-tokens first - if let Some((tok_type, tok_str, sl, sc, el, ec)) = pending_fstring_parts.pop() { - let offset: usize = source - .lines() - .take(sl.saturating_sub(1)) - .map(|l| l.len() + 1) - .sum(); - let full_line = source.full_line_str(TextSize::from(offset.min(source.len()) as u32)); - return Ok(PyIterReturn::Return(make_token_tuple( - vm, - tok_type, - &tok_str, - sl, - sc as isize, - el, - ec as isize, + if let Some(pending) = pending_fstring_parts { + let (tok_type, tok_str, sl, sc, el, ec) = &pending.parts[pending.index]; + let full_line = source.full_line_str(line_index.line_starts()[sl - 1]); + let token = TokenData::new( + *tok_type, + tok_str, + *sl, + *sc as isize, + *el, + *ec as isize, full_line, - ))); + ); + pending.index += 1; + if pending.index == pending.parts.len() { + *pending_fstring_parts = None; + } + return Ok(token); } let source_len = TextSize::from(source.len() as u32); + // Ruff has no NL token for a final indentation-only line without a LF. + if extra_tokens + && *need_implicit_nl + && !source.is_empty() + && errors.is_empty() + && tokens[*index..] + .iter() + .all(|t| matches!(t.kind(), TokenKind::Dedent | TokenKind::EndOfFile)) + { + let final_line = last_physical_line(source); + if !final_line.is_empty() + && final_line + .bytes() + .all(|b| matches!(b, b' ' | b'\t' | b'\x0c')) + { + *need_implicit_nl = false; + let end_lc = line_index.line_column(source_len, source); + let line = end_lc.line.get(); + let column = end_lc.column.to_zero_indexed() as isize; + return Ok(TokenData::new( + TOKEN_NL, + "", + line, + column, + line, + column + 1, + final_line, + )); + } + } + + // A comment's implicit NL precedes the terminal DEDENT sequence. + if extra_tokens + && *need_implicit_nl + && tokens + .get(*index) + .is_some_and(|t| t.kind() == TokenKind::Dedent) + && tokens[*index..] + .iter() + .all(|t| matches!(t.kind(), TokenKind::Dedent | TokenKind::EndOfFile)) + && let Some(comment) = + last_non_dedent_token(tokens).filter(|t| t.kind() == TokenKind::Comment) + { + *need_implicit_nl = false; + return Ok(implicit_comment_newline(comment, source, line_index)); + } + while *index < tokens.len() { let token = tokens[*index]; *index += 1; let kind = token.kind(); let range = token.range(); - // Check for lexical indentation errors. - // Skip when source has tabs — ruff and CPython handle tab - // indentation differently (CPython uses tabsize=8), so ruff may - // report false IndentationErrors for valid mixed-tab code. - if !source.contains('\t') { - for err in errors.iter() { - if !matches!( - err.error, - ParseErrorType::Lexical(LexicalErrorType::IndentationError) - ) { - continue; - } - if err.location.start() <= range.start() && range.start() < err.location.end() { - return Err(raise_indentation_error(vm, err, source, line_index)); - } + // An indentation error replaces the token the lexer raised it for. + if kind == TokenKind::Unknown + && let Some(err) = errors.iter().find(|err| { + line_index.line_index(err.location.start()) + == line_index.line_index(range.start()) + && matches!( + err.error, + ParseErrorType::Lexical( + LexicalErrorType::IndentationError + | LexicalErrorType::TabError + | LexicalErrorType::TooDeepIndentation + ) + ) + }) + { + return Err(TokenError::Indentation { + error: err.clone(), + data: Arc::clone(data), + }); + } + + // Ruff emits an empty Unknown and a synthetic tail when recovering + // from an open bracket at EOF. They are not source tokens. + if kind == TokenKind::Unknown + && range.is_empty() + && range.start() == source_len + && has_unclosed_brackets(tokens, source) + && errors.iter().any(|err| { + let ParseErrorType::Lexical(LexicalErrorType::UnclosedBracket { + opening, + incomplete: true, + }) = &err.error + else { + return false; + }; + tokens.iter().any(|opener| { + !opener.range().is_empty() + && opener.range().start() == err.location.start() + && matches!( + (*opening, opener.kind()), + ('(', TokenKind::Lpar) + | ('[', TokenKind::Lsqb) + | ('{', TokenKind::Lbrace) + ) + }) + }) + { + *index = tokens.len(); + if extra_tokens && core::mem::take(need_implicit_nl) { + let end = line_index.line_column(source_len, source); + let line = end.line.get(); + let column = end.column.to_zero_indexed() as isize; + return Ok(TokenData::new( + TOKEN_NL, + "", + line, + column, + line, + column + 1, + last_physical_line(source), + )); } + break; } if kind == TokenKind::EndOfFile { @@ -237,7 +359,21 @@ mod _tokenize { } let raw_type = token_kind_value(kind); - let token_type = if extra_tokens + let leading_zero_number = extra_tokens + && kind == TokenKind::Unknown + && errors.iter().any(|err| { + matches!( + err.error, + ParseErrorType::Lexical(LexicalErrorType::LeadingZerosInDecimalInteger) + ) && err.location.start() == range.start() + && err.location.end() > range.start() + && err.location.end() < range.end() + }); + // Ruff diagnoses the zero prefix but retains the complete numeric token. + // CPython accepts that token as NUMBER only in extra-token mode. + let token_type = if leading_zero_number { + token_kind_value(TokenKind::Int) + } else if extra_tokens && (kind == TokenKind::Unknown || (raw_type > TOKEN_DEDENT && raw_type < TOKEN_OP)) { TOKEN_OP @@ -246,15 +382,30 @@ mod _tokenize { }; let (token_str, start_line, start_col, end_line, end_col, line_str) = - if kind == TokenKind::Dedent { + if !extra_tokens && kind == TokenKind::Indent { + // Explicit continuations can span the indentation range. + // CPython reports the line reached after consuming it. + let line = line_index.line_column(range.end(), source).line.get(); + ("", line, 0, line, 0, source.full_line_str(range.end())) + } else if kind == TokenKind::Dedent { let last_line = source.lines().count(); let default_pos = if extra_tokens { (last_line + 1, 0) } else { (last_line, 0) }; - let (pos, dedent_line) = - next_non_dedent_info(tokens, *index, source, line_index, default_pos); + let default_line = if extra_tokens { + "" + } else { + non_extra_eof_line(tokens, source, line_index) + }; + let (pos, dedent_line) = next_non_dedent_info( + tokens, + *index, + source, + line_index, + (default_pos, default_line), + ); ("", pos.0, pos.1, pos.0, pos.1, dedent_line) } else { let start_lc = line_index.line_column(range.start(), source); @@ -280,13 +431,23 @@ mod _tokenize { } } else if kind == TokenKind::NonLogicalNewline { let s = if in_source { &source[range] } else { "" }; - (s, start_line, start_col + s.len()) + if range.end() == source_len && s == "\r" && *need_implicit_nl { + // CPython appends LF to a readline chunk ending in bare CR. + *need_implicit_nl = false; + ("", start_line, start_col + 2) + } else { + (s, start_line, start_col + s.len()) + } } else { let end_lc = line_index.line_column(range.end(), source); let s = if in_source { &source[range] } else { "" }; (s, end_lc.line.get(), end_lc.column.to_zero_indexed()) }; - let line_str = source.full_line_str(range.start()); + let line_str = if kind == TokenKind::String && in_source { + source.full_lines_str(range) + } else { + source.full_line_str(range.start()) + }; (s, start_line, start_col, el, ec, line_str) }; @@ -298,11 +459,11 @@ mod _tokenize { split_fstring_middle(token_str, token_type, start_line, start_col).into_iter(); let (tt, ts, sl, sc, el, ec) = parts.next().unwrap(); let rest: Vec<_> = parts.collect(); - for p in rest.into_iter().rev() { - pending_fstring_parts.push(p); - } - return Ok(PyIterReturn::Return(make_token_tuple( - vm, + *pending_fstring_parts = (!rest.is_empty()).then(|| PendingFStringParts { + parts: rest.into(), + index: 0, + }); + return Ok(TokenData::new( tt, &ts, sl, @@ -310,7 +471,7 @@ mod _tokenize { el, ec as isize, line_str, - ))); + )); } // After emitting a Rbrace inside an fstring, check if the @@ -326,16 +487,17 @@ mod _tokenize { Some((mid_type, end_line, end_col, line_str.to_string())); } - return Ok(PyIterReturn::Return(make_token_tuple( - vm, - token_type, - token_str, - start_line, - start_col as isize, - end_line, - end_col as isize, - line_str, - ))); + // The non-extra tokenizer leaves INDENT/DEDENT token pointers unset. + let (token_str, start_col, end_col) = + if !extra_tokens && matches!(kind, TokenKind::Indent | TokenKind::Dedent) { + ("", -1, -1) + } else { + (token_str, start_col as isize, end_col as isize) + }; + + return Ok(TokenData::new( + token_type, token_str, start_line, start_col, end_line, end_col, line_str, + )); } // Emit implicit NL before ENDMARKER if source @@ -346,48 +508,16 @@ mod _tokenize { .rev() .find(|t| t.kind() != TokenKind::EndOfFile); if let Some(last) = last_tok.filter(|t| t.kind() == TokenKind::Comment) { - let end_lc = line_index.line_column(last.range().end(), source); - let nl_line = end_lc.line.get(); - let nl_col = end_lc.column.to_zero_indexed(); - return Ok(PyIterReturn::Return(make_token_tuple( - vm, - TOKEN_NL, - "", - nl_line, - nl_col as isize, - nl_line, - nl_col as isize + 1, - source.full_line_str(last.range().start()), - ))); + return Ok(implicit_comment_newline(last, source, line_index)); } } // Check for unclosed brackets before ENDMARKER — CPython's tokenizer - // raises SyntaxError("EOF in multi-line statement") in this case. + // raises SyntaxError("unexpected EOF in multi-line statement") in this case. { - let bracket_count: i32 = tokens - .iter() - .map(|t| match t.kind() { - TokenKind::Lpar | TokenKind::Lsqb | TokenKind::Lbrace => 1, - TokenKind::Rpar | TokenKind::Rsqb | TokenKind::Rbrace => -1, - // `$` inside an f-string interpolation is Unknown, and the - // matching `}` is then also Unknown rather than Rbrace. - TokenKind::Unknown => match &source[t.range()] { - "(" | "[" | "{" => 1, - ")" | "]" | "}" => -1, - _ => 0, - }, - _ => 0, - }) - .sum(); - if bracket_count > 0 { + if has_unclosed_brackets(tokens, source) { let last_line = source.lines().count(); - return Err(raise_syntax_error( - vm, - "EOF in multi-line statement", - last_line + 1, - 0, - )); + return Err(TokenError::UnclosedBrackets { line: last_line }); } } @@ -396,13 +526,14 @@ mod _tokenize { let (em_line, em_col, em_line_str): (usize, isize, &str) = if extra_tokens { (last_line + 1, 0, "") } else { - let last_line_text = - source.full_line_str(TextSize::from(source.len().saturating_sub(1) as u32)); - (last_line, -1, last_line_text) + ( + last_line, + -1, + non_extra_eof_line(tokens, source, line_index), + ) }; - let result = make_token_tuple( - vm, + let result = TokenData::new( TOKEN_ENDMARKER, "", em_line, @@ -412,7 +543,26 @@ mod _tokenize { em_line_str, ); state.phase = TokenizerPhase::Done; - Ok(PyIterReturn::Return(result)) + Ok(result) + } + + fn has_unclosed_brackets(tokens: &[Token], source: &str) -> bool { + let bracket_count: i32 = tokens + .iter() + .map(|t| match t.kind() { + TokenKind::Lpar | TokenKind::Lsqb | TokenKind::Lbrace => 1, + TokenKind::Rpar | TokenKind::Rsqb | TokenKind::Rbrace => -1, + // `$` inside an f-string interpolation is Unknown, and the + // matching `}` is then also Unknown rather than Rbrace. + TokenKind::Unknown => match &source[t.range()] { + "(" | "[" | "{" => 1, + ")" | "]" | "}" => -1, + _ => 0, + }, + _ => 0, + }) + .sum(); + bracket_count > 0 } /// Determine whether to emit FSTRING_MIDDLE (60) or TSTRING_MIDDLE (63) @@ -440,6 +590,62 @@ mod _tokenize { 60 // default to FSTRING_MIDDLE } + fn last_physical_line(source: &str) -> &str { + source.char_indices().next_back().map_or("", |(offset, _)| { + source.full_line_str(TextSize::from(offset as u32)) + }) + } + + fn last_non_dedent_token(tokens: &[Token]) -> Option<&Token> { + tokens + .iter() + .rev() + .find(|t| !matches!(t.kind(), TokenKind::Dedent | TokenKind::EndOfFile)) + } + + fn non_extra_eof_line<'a>( + tokens: &[Token], + source: &'a str, + line_index: &LineIndex, + ) -> &'a str { + let Some(last) = last_non_dedent_token(tokens) else { + return ""; + }; + if matches!( + last.kind(), + TokenKind::Comment | TokenKind::NonLogicalNewline + ) || line_index + .line_column(last.range().start(), source) + .line + .get() + != source.lines().count() + { + // Ignored trailing lines never populated the non-extra line cache. + "" + } else { + last_physical_line(source) + } + } + + fn implicit_comment_newline( + comment: &Token, + source: &str, + line_index: &LineIndex, + ) -> TokenData { + let end_lc = line_index.line_column(comment.range().end(), source); + let line = end_lc.line.get(); + let column = end_lc.column.to_zero_indexed() as isize; + TokenData::new( + TOKEN_NL, + "", + line, + column, + line, + column + 1, + source.full_line_str(comment.range().start()), + ) + } + /// Find the next non-DEDENT token's position and source line. /// Returns ((line, col), line_str). fn next_non_dedent_info<'a>( @@ -447,12 +653,12 @@ mod _tokenize { index: usize, source: &'a str, line_index: &LineIndex, - default_pos: (usize, usize), + default_info: ((usize, usize), &'a str), ) -> ((usize, usize), &'a str) { for future in &tokens[index..] { match future.kind() { TokenKind::Dedent => continue, - TokenKind::EndOfFile => return (default_pos, ""), + TokenKind::EndOfFile => return default_info, _ => { let flc = line_index.line_column(future.range().start(), source); let pos = (flc.line.get(), flc.column.to_zero_indexed()); @@ -460,7 +666,7 @@ mod _tokenize { } } } - (default_pos, "") + default_info } /// Raise a SyntaxError with the given message and position. @@ -480,7 +686,7 @@ mod _tokenize { exc } - /// Raise an IndentationError from a parse error. + /// Raise an IndentationError or TabError from a parse error. fn raise_indentation_error( vm: &VirtualMachine, err: &ParseError, @@ -491,10 +697,15 @@ mod _tokenize { let err_line_text = source.full_line_str(err.location.start()); let err_text = err_line_text.trim_end_matches('\n').trim_end_matches('\r'); let msg = format!("{}", err.error); - let exc = vm.new_exception_msg( - vm.ctx.exceptions.indentation_error.to_owned(), - msg.clone().into(), - ); + let exc_type = if matches!( + err.error, + ParseErrorType::Lexical(LexicalErrorType::TabError) + ) { + vm.ctx.exceptions.tab_error + } else { + vm.ctx.exceptions.indentation_error + }; + let exc = vm.new_exception_msg(exc_type.to_owned(), msg.clone().into()); let obj = exc.as_object(); let _ = obj.set_attr("lineno", vm.ctx.new_int(err_lc.line.get()), vm); let _ = obj.set_attr("offset", vm.ctx.new_int(err_text.len() as i64 + 1), vm); @@ -512,7 +723,7 @@ mod _tokenize { token_type: u8, start_line: usize, start_col: usize, - ) -> Vec<(u8, String, usize, usize, usize, usize)> { + ) -> Vec { let mut parts = Vec::new(); let mut current = String::new(); // Track source position (line, col) — these correspond to the @@ -524,99 +735,126 @@ mod _tokenize { let mut part_start_col = cur_col; let mut chars = raw.chars().peekable(); - // Compute end position of the current accumulated text - let end_pos = |current: &str, start_line: usize, start_col: usize| -> (usize, usize) { - let mut el = start_line; - let mut ec = start_col; - for ch in current.chars() { - if ch == '\n' { - el += 1; - ec = 0; - } else { - ec += ch.len_utf8(); - } - } - (el, ec) - }; - while let Some(ch) = chars.next() { - if ch == '{' && chars.peek() == Some(&'{') { - chars.next(); - current.push('{'); - cur_col += 2; // skip both {{ in source - } else if ch == '}' && chars.peek() == Some(&'}') { + current.push(ch); + if ch == '\n' { + cur_line += 1; + cur_col = 0; + } else { + cur_col += 1; + } + if matches!(ch, '{' | '}') && chars.peek() == Some(&ch) { chars.next(); - // Flush accumulated text before }} - if !current.is_empty() { - let (el, ec) = end_pos(¤t, part_start_line, part_start_col); - parts.push(( - token_type, - core::mem::take(&mut current), - part_start_line, - part_start_col, - el, - ec, - )); - } - // Emit unescaped '}' at source position of }} + // CPython ends each middle token at the first escaped brace. parts.push(( token_type, - "}".to_string(), + core::mem::take(&mut current), + part_start_line, + part_start_col, cur_line, cur_col, - cur_line, - cur_col + 1, )); - cur_col += 2; // skip both }} in source + cur_col += 1; part_start_line = cur_line; part_start_col = cur_col; - } else { - if current.is_empty() { - part_start_line = cur_line; - part_start_col = cur_col; - } - current.push(ch); - if ch == '\n' { - cur_line += 1; - cur_col = 0; - } else { - cur_col += ch.len_utf8(); - } } } if !current.is_empty() { - let (el, ec) = end_pos(¤t, part_start_line, part_start_col); - parts.push((token_type, current, part_start_line, part_start_col, el, ec)); + parts.push(( + token_type, + current, + part_start_line, + part_start_col, + cur_line, + cur_col, + )); } parts } - #[allow(clippy::too_many_arguments)] - fn make_token_tuple( - vm: &VirtualMachine, + struct TokenData { token_type: u8, - string: &str, - start_line: usize, - start_col: isize, - end_line: usize, - end_col: isize, - line: &str, - ) -> PyObjectRef { - vm.ctx - .new_tuple(vec![ - token_type.to_pyobject(vm), - vm.ctx.new_str(string).into(), - vm.ctx - .new_tuple(vec![start_line.to_pyobject(vm), start_col.to_pyobject(vm)]) - .into(), - vm.ctx - .new_tuple(vec![end_line.to_pyobject(vm), end_col.to_pyobject(vm)]) - .into(), - vm.ctx.new_str(line).into(), - ]) - .into() + string: String, + start: (usize, isize), + end: (usize, isize), + line: String, + } + + impl TokenData { + #[allow(clippy::too_many_arguments)] + fn new( + token_type: u8, + string: &str, + start_line: usize, + start_col: isize, + end_line: usize, + end_col: isize, + line: &str, + ) -> Self { + Self { + token_type, + string: string.to_owned(), + start: (start_line, start_col), + end: (end_line, end_col), + line: line.to_owned(), + } + } + + fn into_object(self, vm: &VirtualMachine) -> PyObjectRef { + vm.ctx + .new_tuple(vec![ + self.token_type.to_pyobject(vm), + vm.ctx.new_str(self.string).into(), + vm.ctx + .new_tuple(vec![ + self.start.0.to_pyobject(vm), + self.start.1.to_pyobject(vm), + ]) + .into(), + vm.ctx + .new_tuple(vec![self.end.0.to_pyobject(vm), self.end.1.to_pyobject(vm)]) + .into(), + vm.ctx.new_str(self.line).into(), + ]) + .into() + } + } + + enum TokenError { + Indentation { + error: ParseError, + data: Arc, + }, + UnclosedBrackets { + line: usize, + }, + } + + impl TokenError { + fn into_exception( + self, + vm: &VirtualMachine, + ) -> rustpython_vm::builtins::PyBaseExceptionRef { + match self { + Self::Indentation { error, data } => { + raise_indentation_error(vm, &error, &data.source, &data.line_index) + } + Self::UnclosedBrackets { line } => { + let exc = + raise_syntax_error(vm, "unexpected EOF in multi-line statement", line, 0); + // PyErr_SyntaxLocationObject sets the end line to the current line. + if let Err(error) = + exc.as_object() + .set_attr("end_lineno", vm.ctx.new_int(line), vm) + { + return error; + } + exc + } + } + } } #[derive(FromArgs)] @@ -634,20 +872,33 @@ mod _tokenize { phase: TokenizerPhase, } + type FStringPart = (u8, String, usize, usize, usize, usize); + + #[derive(Clone, Debug)] + struct PendingFStringParts { + parts: Arc<[FStringPart]>, + index: usize, + } + + #[derive(Debug)] + struct TokenizedSource { + source: String, + tokens: Vec, + errors: Vec, + line_index: LineIndex, + } + #[derive(Clone, Debug)] enum TokenizerPhase { Reading { source: String, }, Yielding { - source: String, - tokens: Vec, - errors: Vec, + data: Arc, index: usize, - line_index: LineIndex, need_implicit_nl: bool, /// Pending sub-tokens from FSTRING_MIDDLE splitting - pending_fstring_parts: Vec<(u8, String, usize, usize, usize, usize)>, + pending_fstring_parts: Option, /// Pending empty FSTRING_MIDDLE for format spec nesting: /// (type, line, col, line_str) pending_empty_fstring_middle: Option<(u8, usize, usize, String)>, @@ -658,7 +909,8 @@ mod _tokenize { const fn token_kind_value(kind: TokenKind) -> u8 { match kind { TokenKind::EndOfFile => 0, - TokenKind::Name + TokenKind::Identifier + | TokenKind::Lazy | TokenKind::For | TokenKind::In | TokenKind::Pass @@ -759,7 +1011,6 @@ mod _tokenize { TokenKind::TStringMiddle => 63, TokenKind::TStringEnd => 64, TokenKind::IpyEscapeCommand | TokenKind::Question | TokenKind::Unknown => 67, // ERRORTOKEN - TokenKind::Lazy => u8::MAX, // Placeholder: RustPython Doesn't support `lazy imports` yet } } } diff --git a/crates/stdlib/src/_zoneinfo.rs b/crates/stdlib/src/_zoneinfo.rs index 9ab94cbefcd..bc561004cb8 100644 --- a/crates/stdlib/src/_zoneinfo.rs +++ b/crates/stdlib/src/_zoneinfo.rs @@ -10,6 +10,7 @@ pub(crate) use _zoneinfo::module_def; #[pymodule] mod _zoneinfo { use alloc::collections::VecDeque; + use rustpython_common::wtf8::{Wtf8, Wtf8Buf, wtf8_concat}; use std::collections::HashMap; use crate::_datetime::{PyTzInfo, datetime_type, timedelta_from_seconds}; @@ -21,7 +22,7 @@ mod _zoneinfo { PyBaseExceptionRef, PyBytes, PyModule, PyStr, PyStrRef, PyTuple, PyType, PyTypeRef, }, class::StaticType, - function::{FuncArgs, IntoFuncArgs, KwArgs}, + function::{ArgIndex, FuncArgs, IntoFuncArgs, KwArgs}, object::{Traverse, TraverseFn}, protocol::{PyIter, PyIterReturn}, types::{Constructor, Representable}, @@ -264,12 +265,14 @@ mod _zoneinfo { if !is_base(cls) { return Ok(()); } - with_cache(vm, |cache| { + let _evicted = with_cache(vm, |cache| { cache.strong.push_front((key, zone)); - while cache.strong.len() > STRONG_CACHE_MAX { - cache.strong.pop_back(); - } - }) + cache + .strong + .split_off(STRONG_CACHE_MAX.min(cache.strong.len())) + })?; + // Dropping a zone or its key can reenter the cache through Python. + Ok(()) } fn strong_cache_eject(cls: &Py, key: &PyObject, vm: &VirtualMachine) -> PyResult<()> { @@ -278,11 +281,12 @@ mod _zoneinfo { } for (cached_key, zone) in strong_entries(vm)? { if vm.bool_eq(key, &cached_key)? { - with_cache(vm, |cache| { - if let Some(pos) = cache.strong.iter().position(|(_, cached)| cached.is(&zone)) - { - cache.strong.remove(pos); - } + let _removed = with_cache(vm, |cache| { + cache + .strong + .iter() + .position(|(_, cached)| cached.is(&zone)) + .and_then(|pos| cache.strong.remove(pos)) })?; return Ok(()); } @@ -294,7 +298,8 @@ mod _zoneinfo { if !is_base(cls) { return Ok(()); } - with_cache(vm, |cache| cache.strong.clear()) + let _removed = with_cache(vm, |cache| core::mem::take(&mut cache.strong))?; + Ok(()) } fn cached_delta(seconds: i64, vm: &VirtualMachine) -> PyResult { @@ -333,7 +338,7 @@ mod _zoneinfo { return existing.clone(); } cache.weak = Some(weak.clone()); - weak + weak.clone() }) } @@ -418,7 +423,7 @@ mod _zoneinfo { ) -> i64 { let days_before_year = i64::from(ymd_to_ord(year, 1, 1)) - EPOCHORDINAL - 1; let mut day = i64::from(day); - if julian && day >= 59 && is_leap_year(year) { + if julian && day >= 60 && is_leap_year(year) { day += 1; } (days_before_year + day) * 86_400 @@ -552,6 +557,9 @@ mod _zoneinfo { parser.bump(); } let end = parser.i; + if end == start { + return None; + } parser.bump(); return Some(String::from_utf8_lossy(&parser.bytes[start..end]).into_owned()); } @@ -999,10 +1007,14 @@ mod _zoneinfo { vm: &VirtualMachine, ) -> PyResult { let qual = instance.class().fully_qualified_name(vm)?; - let key_repr = key.repr(vm)?.to_string_lossy().into_owned(); - Err(vm.new_runtime_error(format!( - "Unexpected instance of {qual} in {} weak cache for key {key_repr}", - cls.name() + let key_repr = key.repr(vm)?.as_wtf8().to_owned(); + Err(vm.new_runtime_error(wtf8_concat!( + "Unexpected instance of ", + qual, + " in ", + &*cls.name(), + " weak cache for key ", + key_repr ))) } @@ -1193,8 +1205,7 @@ mod _zoneinfo { base: PyTzInfo, #[pymember(type = "object_ex")] key: PyObjectRef, - #[pytraverse(skip)] - file_repr: Option, + file_repr: Option, #[pytraverse(skip)] source: u8, data: ZoneDataBox, @@ -1214,14 +1225,17 @@ mod _zoneinfo { } impl Representable for ZoneInfo { - fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { let name = zelf.class().fully_qualified_name(vm)?; if vm.is_none(&zelf.key) { - let file = zelf.file_repr.as_deref().unwrap_or(""); - return Ok(format!("{name}.from_file({file})")); + let file = zelf + .file_repr + .as_ref() + .map_or_else(|| Wtf8::new(""), |file| file.as_wtf8()); + return Ok(wtf8_concat!(name, ".from_file(", file, ")")); } - let key = zelf.key.repr(vm)?.to_string_lossy().into_owned(); - Ok(format!("{name}(key={key})")) + let key = zelf.key.repr(vm)?.as_wtf8().to_owned(); + Ok(wtf8_concat!(name, "(key=", key, ")")) } } @@ -1268,7 +1282,7 @@ mod _zoneinfo { args: FromFileArgs, vm: &VirtualMachine, ) -> PyResult> { - let file_repr = args.file_obj.repr(vm)?.to_string_lossy().into_owned(); + let file_repr = args.file_obj.repr(vm)?; let key = args.key.unwrap_or_else(|| vm.ctx.none()); let data = load_data(&args.file_obj, vm)?; Self { @@ -1369,7 +1383,7 @@ mod _zoneinfo { Ok(vm .new_tuple(( constructor, - vm.new_tuple((zelf.key.clone(), vm.ctx.new_bool(from_cache))), + vm.new_tuple((zelf.key.clone(), vm.ctx.new_int(u8::from(from_cache)))), )) .into()) } @@ -1381,12 +1395,17 @@ mod _zoneinfo { from_cache: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - let from_cache = (from_cache.try_index(vm)?.as_u64_mask() as u8) != 0; - if from_cache { - cls.as_object().call((key,), vm) + let use_cache = { + let index = ArgIndex::try_from_object(vm, from_cache.clone())?; + index.as_unsigned_bitfield::<8>(vm)? != 0 + }; + let result = if use_cache { + cached_new(cls, key, vm) } else { Ok(new_instance(cls, key, SOURCE_NOCACHE, vm)?.into()) - } + }; + drop(from_cache); + result } #[pyclassmethod] @@ -1411,7 +1430,7 @@ mod _zoneinfo { zelf.key.class().slot_name() ))); } - Ok(vm.ctx.new_str(Self::repr_str(zelf, vm)?)) + Self::repr(zelf, vm) } } diff --git a/crates/stdlib/src/array.rs b/crates/stdlib/src/array.rs index cb6e40d0d54..b694c03fff9 100644 --- a/crates/stdlib/src/array.rs +++ b/crates/stdlib/src/array.rs @@ -17,15 +17,15 @@ pub mod array { AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, builtins::{ - PositionIterInternal, PyByteArray, PyBytes, PyBytesRef, PyDictRef, PyFloat, - PyGenericAlias, PyInt, PyList, PyListRef, PyStr, PyStrRef, PyTupleRef, PyType, - PyTypeRef, PyUtf8Str, PyUtf8StrRef, builtins_iter, locked_next, + PositionIterInternal, PyByteArray, PyBytes, PyDictRef, PyFloat, PyGenericAlias, + PyInt, PyListRef, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, PyUtf8StrRef, + builtins_iter, locked_next, }, class_or_notimplemented, - convert::{ToPyObject, ToPyResult, TryFromBorrowedObject, TryFromObject}, + convert::{ToPyObject, ToPyResult, TryFromObject}, function::{ - ArgBytesLike, ArgIndex, ArgIntoFloat, ArgIterable, KwArgs, OptionalArg, - PyComparisonValue, + ArgBytesLike, ArgCInt, ArgIndex, ArgIntoComplex, ArgIntoFloat, ArgIterable, + ArgNulFreeStr, KwArgs, OptionalArg, PyComparisonValue, }, protocol::{ BufferDescriptor, BufferFlags, BufferMethods, BufferResizeGuard, PyBuffer, @@ -33,7 +33,7 @@ pub mod array { }, sequence::{SequenceExt, SequenceMutExt}, sliceable::{ - SaturatedSlice, SequenceIndex, SequenceIndexOp, SliceableSequenceMutOp, + NameArray, SaturatedSlice, SequenceIndex, SequenceIndexOp, SliceableSequenceMutOp, SliceableSequenceOp, }, stdlib::_warnings, @@ -45,12 +45,14 @@ pub mod array { }; use alloc::fmt; use core::cmp::Ordering; + use half::f16; use itertools::Itertools; - use num_traits::{Signed, ToPrimitive}; + use num_complex::{Complex32, Complex64}; + use num_traits::Signed; use rustpython_common::wtf8::{CodePoint, Wtf8, Wtf8Buf}; use std::os::raw; macro_rules! def_array_enum { - ($(($n:ident, $t:ty, $c:literal, $scode:literal)),*$(,)?) => { + ($(($n:ident, $t:ty, $c:literal)),*$(,)?) => { #[derive(Debug, Clone)] pub enum ArrayContentType { $($n(Vec<$t>),)* @@ -62,28 +64,26 @@ pub mod array { } impl ArrayContentType { - fn from_char(c: char) -> Result { + fn typecodes(vm: &VirtualMachine) -> PyTupleRef { + vm.ctx.new_tuple(vec![$(vm.ctx.new_str($c).into(),)*]) + } + + fn from_typecode(c: &str) -> Result { match c { $($c => Ok(ArrayContentType::$n(Vec::new())),)* _ => Err( - "bad typecode (must be b, B, u, w, h, H, i, I, l, L, q, Q, f or d)".into() + "bad typecode (must be b, B, u, w, h, H, i, I, l, L, q, Q, e, f, d, Zf or Zd)".into() ), } } - const fn typecode(&self) -> char { + const fn typecode(&self) -> &'static str { match self { $(ArrayContentType::$n(_) => $c,)* } } - const fn typecode_str(&self) -> &'static str { - match self { - $(ArrayContentType::$n(_) => $scode,)* - } - } - - const fn itemsize_of_typecode(c: char) -> Option { + fn itemsize_of_typecode(c: &str) -> Option { match c { $($c => Some(core::mem::size_of::<$t>()),)* _ => None, @@ -152,7 +152,7 @@ pub mod array { } fn search_item( - typecode: char, + typecode: &str, needle: &PyObject, vm: &VirtualMachine, ) -> Option> { @@ -203,52 +203,44 @@ pub mod array { } fn frombytes_move(&mut self, b: Vec) { - match self { - $(ArrayContentType::$n(v) => { - if v.is_empty() { - // safe because every configuration of bytes for the types we - // support are valid - let b = core::mem::ManuallyDrop::new(b); - let ptr = b.as_ptr() as *mut $t; - let len = b.len() / core::mem::size_of::<$t>(); - let capacity = b.capacity() / core::mem::size_of::<$t>(); - *v = unsafe { Vec::from_raw_parts(ptr, len, capacity) }; - } else { - self.frombytes(&b); - } - })* - } + self.frombytes(&b); } fn frombytes(&mut self, b: &[u8]) { match self { $(ArrayContentType::$n(v) => { - // safe because every configuration of bytes for the types we - // support are valid - if b.len() > 0 { - let ptr = b.as_ptr() as *const $t; - let ptr_len = b.len() / core::mem::size_of::<$t>(); - let slice = unsafe { core::slice::from_raw_parts(ptr, ptr_len) }; - v.extend_from_slice(slice); + for chunk in b.chunks_exact(core::mem::size_of::<$t>()) { + // All bit patterns are valid elements. Byte buffers need + // not have the alignment of the array's element type. + v.push(unsafe { chunk.as_ptr().cast::<$t>().read_unaligned() }); } })* } } - fn fromlist(&mut self, list: &Py, vm: &VirtualMachine) -> PyResult<()> { + // The caller must rule out conversion callbacks before taking locks. + fn extend_builtin_list(&mut self, list: &[PyObjectRef], vm: &VirtualMachine) -> PyResult<()> { match self { $(ArrayContentType::$n(v) => { // convert list before modify self - let mut list: Vec<$t> = list - .borrow_vec() - .iter() - .cloned() + let mut items: Vec<$t> = list.iter().cloned() .map(|value| <$t>::try_into_from_object(vm, value)) .try_collect()?; - v.append(&mut list); - Ok(()) + v.append(&mut items); + })* + } + Ok(()) + } + + fn resize(&mut self, len: usize, vm: &VirtualMachine) -> PyResult<()> { + match self { + $(ArrayContentType::$n(v) => { + v.try_reserve(len.saturating_sub(v.len())) + .map_err(|_| vm.no_memory_error())?; + v.resize(len, <$t>::default()); })* } + Ok(()) } fn get_bytes(&self) -> &[u8] { @@ -314,7 +306,7 @@ pub mod array { /// which can reach the array, so it takes the typecode by /// value and holds no lock on it. fn item_from_object( - typecode: char, + typecode: &str, value: PyObjectRef, vm: &VirtualMachine ) -> PyResult { @@ -345,7 +337,11 @@ pub mod array { ) -> PyResult<()> { match self { $(Self::$n(elements) => if let ArrayContentType::$n(items) = items { - elements.setitem_by_slice(vm, slice, items) + if items.is_empty() { + elements.delitem_by_slice(vm, slice) + } else { + elements.setitem_by_slice(vm, slice, items) + } } else { Err(vm.new_type_error( "bad argument type for built-in operation".to_owned() @@ -359,14 +355,18 @@ pub mod array { slice: SaturatedSlice, items: &ArrayContentType, vm: &VirtualMachine - ) -> PyResult<()> { + ) -> Option> { match self { $(Self::$n(elements) => if let ArrayContentType::$n(items) = items { - elements.setitem_by_slice_no_resize(vm, slice, items) + if items.is_empty() { + None + } else { + Some(elements.setitem_by_slice_no_resize(vm, slice, items)) + } } else { - Err(vm.new_type_error( + Some(Err(vm.new_type_error( "bad argument type for built-in operation".to_owned() - )) + ))) },)* } } @@ -452,7 +452,7 @@ pub mod array { if v.is_empty() { format!("{}('{}')", class_name, $c) } else { - format!("{}('{}', [{}])", class_name, $c, v.iter().format(", ")) + format!("{}('{}', [{}])", class_name, $c, v.iter().map(|x| x.repr_item()).format(", ")) } })* }; @@ -470,7 +470,7 @@ pub mod array { match self { $(ArrayContentType::$n(v) => { if let ArrayContentType::$n(other) = other { - Ok(PartialOrd::partial_cmp(v, other)) + <$t>::compare_slice(v, other) } else { Err(()) } @@ -489,36 +489,55 @@ pub mod array { }; } + #[pyattr] + fn typecodes(vm: &VirtualMachine) -> PyTupleRef { + ArrayContentType::typecodes(vm) + } + def_array_enum!( - (SignedByte, i8, 'b', "b"), - (UnsignedByte, u8, 'B', "B"), - (PyUnicode, WideChar, 'u', "u"), - (PyUcs4, Ucs4Char, 'w', "w"), - (SignedShort, raw::c_short, 'h', "h"), - (UnsignedShort, raw::c_ushort, 'H', "H"), - (SignedInt, raw::c_int, 'i', "i"), - (UnsignedInt, raw::c_uint, 'I', "I"), - (SignedLong, raw::c_long, 'l', "l"), - (UnsignedLong, raw::c_ulong, 'L', "L"), - (SignedLongLong, raw::c_longlong, 'q', "q"), - (UnsignedLongLong, raw::c_ulonglong, 'Q', "Q"), - (Float, f32, 'f', "f"), - (Double, f64, 'd', "d"), + (SignedByte, i8, "b"), + (UnsignedByte, u8, "B"), + (PyUnicode, WideChar, "u"), + (PyUcs4, Ucs4Char, "w"), + (SignedShort, raw::c_short, "h"), + (UnsignedShort, raw::c_ushort, "H"), + (SignedInt, raw::c_int, "i"), + (UnsignedInt, raw::c_uint, "I"), + (SignedLong, raw::c_long, "l"), + (UnsignedLong, raw::c_ulong, "L"), + (SignedLongLong, raw::c_longlong, "q"), + (UnsignedLongLong, raw::c_ulonglong, "Q"), + (Half, HalfFloat, "e"), + (Float, f32, "f"), + (Double, f64, "d"), + (FloatComplex, ComplexFloat, "Zf"), + (DoubleComplex, ComplexDouble, "Zd"), ); - #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] + #[derive(Copy, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Debug)] pub struct WideChar(wchar_t); /// Element type for the 'w' typecode: always a 4-byte unicode code point /// (Py_UCS4), unlike 'u' which is platform-dependent `wchar_t`. - #[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Debug)] + #[derive(Copy, Clone, Default, Ord, PartialOrd, Eq, PartialEq, Debug)] pub struct Ucs4Char(u32); - trait ArrayElement: Sized { + trait ArrayElement: Sized + PartialOrd { + fn compare_slice(a: &[Self], b: &[Self]) -> Result, ()> { + Ok(a.partial_cmp(b)) + } + fn try_into_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult; fn byteswap(self) -> Self; fn to_object(self, vm: &VirtualMachine) -> PyObjectRef; + fn repr_item(&self) -> String + where + Self: fmt::Display, + { + self.to_string() + } + fn validate_slice(_items: &[Self], _vm: &VirtualMachine) -> PyResult<()> { Ok(()) } @@ -530,6 +549,103 @@ pub mod array { } } + #[repr(transparent)] + #[derive(Debug, Copy, Clone, Default, PartialEq, PartialOrd)] + pub struct HalfFloat(f16); + + impl ArrayElement for HalfFloat { + fn try_into_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + // array's setter parses a C float before packing it as binary16, + // unlike struct's direct binary64-to-binary16 conversion. + let value = f32_try_into_from_object(vm, obj)?; + let half = f16::from_f64_const(value as f64); + if half.is_infinite() && value.is_finite() { + return Err(vm.new_overflow_error("float too large to pack with e format")); + } + Ok(Self(half)) + } + + fn byteswap(self) -> Self { + Self(f16::from_bits(self.0.to_bits().swap_bytes())) + } + + fn to_object(self, vm: &VirtualMachine) -> PyObjectRef { + self.0.to_f64().to_pyobject(vm) + } + + fn repr_item(&self) -> String { + crate::vm::literal::float::to_string(self.0.to_f64()) + } + } + + impl ToPyResult for HalfFloat { + fn to_pyresult(self, vm: &VirtualMachine) -> PyResult { + Ok(self.to_object(vm)) + } + } + + impl fmt::Display for HalfFloat { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + self.0.to_f64().fmt(f) + } + } + + macro_rules! impl_complex_element { + ($name:ident, $complex:ty, $float:ty, $swap:ident) => { + #[repr(transparent)] + #[derive(Debug, Copy, Clone, Default, PartialEq)] + pub struct $name($complex); + + impl PartialOrd for $name { + fn partial_cmp(&self, other: &Self) -> Option { + (self == other).then_some(Ordering::Equal) + } + } + + impl ArrayElement for $name { + fn compare_slice(_a: &[Self], _b: &[Self]) -> Result, ()> { + // Python sequence comparison checks equality before ordering + // unequal complex elements (which must raise TypeError). + Err(()) + } + + fn try_into_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let value = ArgIntoComplex::try_from_object(vm, obj)?.into_complex(); + Ok(Self(<$complex>::new( + value.re as $float, + value.im as $float, + ))) + } + + fn byteswap(self) -> Self { + Self(<$complex>::new($swap(self.0.re), $swap(self.0.im))) + } + + fn to_object(self, vm: &VirtualMachine) -> PyObjectRef { + Complex64::new(self.0.re as f64, self.0.im as f64).to_pyobject(vm) + } + } + + impl ToPyResult for $name { + fn to_pyresult(self, vm: &VirtualMachine) -> PyResult { + Ok(self.to_object(vm)) + } + } + + impl fmt::Display for $name { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&crate::vm::literal::complex::to_string( + self.0.re as f64, + self.0.im as f64, + )) + } + } + }; + } + + impl_complex_element!(ComplexFloat, Complex32, f32, f32_swap_bytes); + impl_complex_element!(ComplexDouble, Complex64, f64, f64_swap_bytes); + macro_rules! impl_int_element { ($($t:ty,)*) => {$( impl ArrayElement for $t { @@ -570,6 +686,9 @@ pub mod array { fn to_object(self, vm: &VirtualMachine) -> PyObjectRef { $f_to(self).into_pyobject(vm) } + fn repr_item(&self) -> String { + crate::vm::literal::float::to_string(*self as f64) + } } )*}; } @@ -747,6 +866,9 @@ pub mod array { pub struct PyArray { array: PyRwLock, exports: AtomicUsize, + // Published before an export is retained, for bounds checks that must + // not reacquire the payload lock while a buffer is active. + export_len: AtomicUsize, } pub type PyArrayRef = PyRef; @@ -756,6 +878,7 @@ pub mod array { Self { array: PyRwLock::new(array), exports: AtomicUsize::new(0), + export_len: AtomicUsize::new(0), } } } @@ -776,15 +899,13 @@ pub mod array { (ArrayNewArgs { spec, init }, kwargs): Self::Args, vm: &VirtualMachine, ) -> PyResult { - let spec = spec.as_str().chars().exactly_one().map_err(|_| { - vm.new_type_error("array() argument 1 must be a unicode character, not str") - })?; + let spec = spec.as_str(); if cls.is(Self::class(&vm.ctx)) && !kwargs.is_empty() { return Err(vm.new_type_error("array.array() takes no keyword arguments")); } - if spec == 'u' { + if spec == "u" { _warnings::warn( vm.ctx.exceptions.deprecation_warning, "The 'u' type code is deprecated and will be removed in Python 3.16".to_owned(), @@ -794,14 +915,14 @@ pub mod array { } let mut array = - ArrayContentType::from_char(spec).map_err(|err| vm.new_value_error(err))?; + ArrayContentType::from_typecode(spec).map_err(|err| vm.new_value_error(err))?; if let OptionalArg::Present(init) = init { if let Some(init) = init.downcast_ref::() { let value = init.read().typecode(); match (spec, value) { (spec, ch) if spec == ch => array.frombytes(&init.get_bytes()), - (spec, 'u' | 'w') if !matches!(spec, 'u' | 'w') => { + (spec, "u" | "w") if !matches!(spec, "u" | "w") => { return Err(vm.new_type_error(format!( "cannot use a unicode array to initialize an array with typecode '{spec}'" ))) @@ -813,7 +934,7 @@ pub mod array { } } } else if let Some(wtf8) = init.downcast_ref::() { - if matches!(spec, 'u' | 'w') { + if matches!(spec, "u" | "w") { let bytes = Self::_unicode_to_wchar_bytes(wtf8.as_wtf8(), array.itemsize()); array.frombytes_move(bytes); } else { @@ -846,7 +967,7 @@ pub mod array { struct ArrayIndexArgs { #[pyarg(positional, optional, py_default = "0")] start: OptionalArg, - #[pyarg(positional, optional, py_default = "9223372036854775807")] + #[pyarg(positional, optional, py_default = "sys.maxsize")] stop: OptionalArg, } @@ -961,6 +1082,9 @@ pub mod array { #[pymethod] fn extend(zelf: &Py, bb: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if zelf.is(&bb) { + if zelf.empty_with_export() { + return Ok(()); + } zelf.try_resizable(vm)?.imul(2, vm) } else if let Some(array) = bb.downcast_ref::() { zelf.try_resizable(vm)?.iadd(&array.read(), vm) @@ -1023,7 +1147,7 @@ pub mod array { ustr.class().name() )) })?; - if !matches!(zelf.read().typecode(), 'u' | 'w') { + if !matches!(zelf.read().typecode(), "u" | "w") { return Err(vm.new_value_error( "fromunicode() may only be called on unicode type arrays ('u' or 'w')", )); @@ -1037,7 +1161,7 @@ pub mod array { #[pymethod] fn tounicode(zelf: &Py, vm: &VirtualMachine) -> PyResult { let array = zelf.array.read(); - if !matches!(array.typecode(), 'u' | 'w') { + if !matches!(array.typecode(), "u" | "w") { return Err(vm.new_value_error( "tounicode() may only be called on unicode type arrays ('u' or 'w')", )); @@ -1186,7 +1310,55 @@ pub mod array { #[pymethod] fn fromlist(zelf: &Py, list: PyListRef, vm: &VirtualMachine) -> PyResult<()> { - zelf.try_resizable(vm)?.fromlist(&list, vm) + let n = list.borrow_vec().len(); + if n == 0 { + return Ok(()); + } + { + let items = list.borrow_vec(); + if items.iter().all(|item| { + let class = item.class(); + class.is(vm.ctx.types.int_type) + || class.is(vm.ctx.types.float_type) + || class.is(vm.ctx.types.bool_type) + || class.is(vm.ctx.types.str_type) + }) { + return zelf.try_resizable(vm)?.extend_builtin_list(&items, vm); + } + } + let (old_size, typecode) = { + let mut array = zelf.try_resizable(vm)?; + let old_size = array.len(); + let new_size = old_size + .checked_add(n) + .ok_or_else(|| vm.no_memory_error())?; + // Callbacks can observe the new size, so initialize the new elements. + array.resize(new_size, vm)?; + (old_size, array.typecode()) + }; + let result = (|| { + for i in 0..n { + let value = list.borrow_vec().get(i).cloned().ok_or_else(|| { + vm.new_runtime_error("list changed size during iteration") + })?; + let index = zelf.read().len() as isize - n as isize + i as isize; + let item = ArrayContentType::item_from_object(typecode, value, vm)?; + // Conversion can resize the array. Check the saved index afterwards; + // a negative index is the conversion-only sentinel used by CPython. + if index >= 0 { + zelf.write().setitem_by_item(index, item, vm)?; + } + if list.borrow_vec().len() != n { + return Err(vm.new_runtime_error("list changed size during iteration")); + } + } + Ok(()) + })(); + if result.is_err() && zelf.read().len() != old_size { + // A callback may have exported a buffer, preventing even the rollback. + zelf.try_resizable(vm)?.resize(old_size, vm)?; + } + result } #[pymethod] @@ -1205,7 +1377,7 @@ pub mod array { } fn getitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - match SequenceIndex::try_from_borrowed_object(vm, needle, "array")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => self.read().getitem_by_index(i, vm), SequenceIndex::Slice(slice) => self.read().getitem_by_slice(slice, vm), } @@ -1215,43 +1387,68 @@ pub mod array { self.getitem_inner(needle, vm) } + fn assign_item( + zelf: &Py, + i: isize, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let (index, typecode) = { + let array = zelf.read(); + (i.wrapped_at(array.len()), array.typecode()) + }; + let index = + index.ok_or_else(|| vm.new_index_error("array assignment index out of range"))?; + let item = ArrayContentType::item_from_object(typecode, value.clone(), vm)?; + let mut array = zelf.write(); + if index >= array.len() { + drop(array); + return Err(vm.new_index_error("array assignment index out of range")); + } + let result = array.setitem_by_item(index as isize, item, vm); + drop(array); + drop(value); + result + } + fn setitem_inner( zelf: &Py, needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - match SequenceIndex::try_from_borrowed_object(vm, needle, "array")? { - SequenceIndex::Int(i) => { - let typecode = zelf.read().typecode(); - let item = ArrayContentType::item_from_object(typecode, value, vm)?; - zelf.write().setitem_by_item(i, item, vm) - } + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { + SequenceIndex::Int(i) => Self::assign_item(zelf, i, value, vm), SequenceIndex::Slice(slice) => { - let cloned; - let guard; - let items = if zelf.is(&value) { - cloned = zelf.read().clone(); - &cloned - } else { - match value.downcast_ref::() { - Some(array) => { - guard = array.read(); - &*guard - } - None => { - return Err(vm.new_type_error(format!( - "can only assign array (not \"{}\") to array slice", - value.class() - ))); + let outcome = { + let cloned; + let guard; + let items = if zelf.is(&value) { + cloned = zelf.read().clone(); + &cloned + } else { + match value.downcast_ref::() { + Some(array) => { + guard = array.read(); + &*guard + } + None => { + return Err(vm.new_type_error(format!( + "can only assign array (not \"{}\") to array slice", + value.class() + ))); + } } + }; + if let Some(mut w) = zelf.try_resizable_opt() { + Some(w.setitem_by_slice(slice, items, vm)) + } else { + zelf.write().setitem_by_slice_no_resize(slice, items, vm) } }; - if let Ok(mut w) = zelf.try_resizable(vm) { - w.setitem_by_slice(slice, items, vm) - } else { - zelf.write().setitem_by_slice_no_resize(slice, items, vm) - } + outcome.unwrap_or_else(|| { + Err(vm.new_buffer_error("cannot resize an array that is exporting buffers")) + }) } } } @@ -1265,9 +1462,20 @@ pub mod array { Self::setitem_inner(zelf, needle, value, vm) } + fn delitem_index(&self, i: isize, vm: &VirtualMachine) -> PyResult<()> { + if self.exports.load(atomic::Ordering::SeqCst) != 0 { + let len = self.export_len.load(atomic::Ordering::SeqCst); + if i.wrapped_at(len).is_none() { + return Err(vm.new_index_error("assignment index out of range")); + } + return Err(vm.new_buffer_error("cannot resize an array that is exporting buffers")); + } + self.try_resizable(vm)?.delitem_by_index(i, vm) + } + fn delitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - match SequenceIndex::try_from_borrowed_object(vm, needle, "array")? { - SequenceIndex::Int(i) => self.try_resizable(vm)?.delitem_by_index(i, vm), + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { + SequenceIndex::Int(i) => self.delitem_index(i, vm), SequenceIndex::Slice(slice) => self.try_resizable(vm)?.delitem_by_slice(slice, vm), } } @@ -1278,9 +1486,15 @@ pub mod array { fn __add__(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { if let Some(other) = other.downcast_ref::() { - self.read() - .add(&other.read(), vm) - .map(|array| Self::from(array).into_ref(&vm.ctx)) + let result = { + let array = self.read(); + if core::ptr::eq(self, &**other) { + array.add(&array, vm) + } else { + array.add(&other.read(), vm) + } + }?; + Ok(Self::from(result).into_ref(&vm.ctx)) } else { Err(vm.new_type_error(format!( "can only append array (not \"{}\") to array", @@ -1295,7 +1509,9 @@ pub mod array { vm: &VirtualMachine, ) -> PyResult> { if zelf.is(other) { - zelf.try_resizable(vm)?.imul(2, vm)?; + if !zelf.empty_with_export() { + zelf.try_resizable(vm)?.imul(2, vm)?; + } } else if let Some(other) = other.downcast_ref::() { zelf.try_resizable(vm)?.iadd(&other.read(), vm)?; } else { @@ -1314,36 +1530,71 @@ pub mod array { } fn __imul__(zelf: PyRef, value: isize, vm: &VirtualMachine) -> PyResult> { - zelf.try_resizable(vm)?.imul(value, vm)?; + if value != 1 && !zelf.empty_with_export() { + zelf.try_resizable(vm)?.imul(value, vm)?; + } Ok(zelf) } + fn empty_with_export(&self) -> bool { + self.exports.load(atomic::Ordering::SeqCst) != 0 + && self.export_len.load(atomic::Ordering::SeqCst) == 0 + } + pub(crate) fn __len__(&self) -> usize { self.read().len() } + fn equal_contents( + left: &ArrayContentType, + right: &ArrayContentType, + vm: &VirtualMachine, + ) -> PyResult { + if let Ok(ord) = left.cmp(right) { + return Ok(ord == Some(Ordering::Equal)); + } + for (a, b) in Iterator::zip(left.iter(vm), right.iter(vm)) { + if !vm.bool_eq(&*a?, &*b?)? { + return Ok(false); + } + } + Ok(true) + } + fn array_eq(&self, other: &Self, vm: &VirtualMachine) -> PyResult { - // we cannot use zelf.is(other) for shortcut because if we contenting a - // float value NaN we always return False even they are the same object. + // Reuse one guard for the same array, but still compare its contents: + // floating-point NaNs must not compare equal to themselves. + if core::ptr::eq(self, other) { + let array = self.read(); + return Self::equal_contents(&array, &array, vm); + } if self.__len__() != other.__len__() { return Ok(false); } let array_a = self.read(); let array_b = other.read(); + Self::equal_contents(&array_a, &array_b, vm) + } - // fast path for same ArrayContentType type - if let Ok(ord) = array_a.cmp(&array_b) { - return Ok(ord == Some(Ordering::Equal)); - } - - let iter = Iterator::zip(array_a.iter(vm), array_b.iter(vm)); - - for (a, b) in iter { - if !vm.bool_eq(&*a?, &*b?)? { - return Ok(false); + fn order_contents( + left: &ArrayContentType, + right: &ArrayContentType, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult { + match left.cmp(right) { + Ok(partial_ord) => Ok(partial_ord.is_some_and(|ord| op.eval_ord(ord))), + Err(()) => { + for (a, b) in Iterator::zip(left.iter(vm), right.iter(vm)) { + let (a, b) = (a?, b?); + if vm.bool_eq(&a, &b)? { + continue; + } + return a.rich_compare_bool(&b, op, vm); + } + Ok(op.eval_ord(left.len().cmp(&right.len()))) } } - Ok(true) } #[pymethod] @@ -1357,7 +1608,7 @@ pub mod array { } let array = zelf.read(); let cls = zelf.class().to_owned(); - let typecode = vm.ctx.new_str(array.typecode_str()); + let typecode = vm.ctx.new_str(array.typecode()); let bytes = vm.ctx.new_bytes(array.get_bytes().to_vec()); let code = MachineFormatCode::from_typecode(array.typecode()).unwrap(); let code = PyInt::from(u8::from(code)).into_pyobject(vm); @@ -1377,8 +1628,8 @@ pub mod array { ) -> PyResult<(PyObjectRef, PyTupleRef, Option)> { let array = zelf.read(); let cls = zelf.class().to_owned(); - let typecode = vm.ctx.new_str(array.typecode_str()); - let values = if matches!(array.typecode(), 'u' | 'w') { + let typecode = vm.ctx.new_str(array.typecode()); + let values = if matches!(array.typecode(), "u" | "w") { let s = Self::_wchar_bytes_to_string(array.get_bytes(), array.itemsize(), vm)?; s.code_points().map(|x| x.to_pyobject(vm)).collect() } else { @@ -1426,47 +1677,24 @@ pub mod array { return Ok(x.into()); } + if core::ptr::eq(zelf, other) { + let array = zelf.read(); + return Self::order_contents(&array, &array, op, vm).map(Into::into); + } + let array_a = zelf.read(); let array_b = other.read(); - - let res = match array_a.cmp(&array_b) { - // fast path for same ArrayContentType type - Ok(partial_ord) => partial_ord.is_some_and(|ord| op.eval_ord(ord)), - Err(()) => { - let iter = Iterator::zip(array_a.iter(vm), array_b.iter(vm)); - - for (a, b) in iter { - let ret = match op { - PyComparisonOp::Lt | PyComparisonOp::Le => { - vm.bool_seq_lt(&*a?, &*b?)? - } - PyComparisonOp::Gt | PyComparisonOp::Ge => { - vm.bool_seq_gt(&*a?, &*b?)? - } - _ => unreachable!(), - }; - if let Some(v) = ret { - return Ok(PyComparisonValue::Implemented(v)); - } - } - - // fallback: - op.eval_ord(array_a.len().cmp(&array_b.len())) - } - }; - - Ok(res.into()) + Self::order_contents(&array_a, &array_b, op, vm).map(Into::into) } } impl PyArray { - fn buffer_desc(&self) -> BufferDescriptor { - let array = self.read(); + fn buffer_desc(array: &ArrayContentType) -> BufferDescriptor { BufferDescriptor::format( array.len() * array.itemsize(), false, array.itemsize(), - array.typecode_str().into(), + array.typecode().into(), ) } } @@ -1484,17 +1712,20 @@ pub mod array { let zelf = zelf .downcast_ref::() .ok_or_else(|| vm.new_type_error("unexpected payload for as_buffer"))?; - let desc = zelf.buffer_desc().projected(flags); - flags.check_writable(desc.readonly, "Object is not writable.", vm)?; - Ok(PyBuffer::new(zelf.to_owned().into(), desc, &BUFFER_METHODS)) + flags.check_writable(false, "Object is not writable.", vm)?; + let array = zelf.read(); + let desc = Self::buffer_desc(&array).projected(flags); + zelf.export_len.store(array.len(), atomic::Ordering::SeqCst); + let buffer = PyBuffer::new(zelf.to_owned().into(), desc, &BUFFER_METHODS); + Ok(buffer) } fn as_buffer(zelf: &Py, _vm: &VirtualMachine) -> PyResult { - Ok(PyBuffer::new( - zelf.to_owned().into(), - zelf.buffer_desc(), - &BUFFER_METHODS, - )) + let array = zelf.read(); + let desc = Self::buffer_desc(&array); + zelf.export_len.store(array.len(), atomic::Ordering::SeqCst); + let buffer = PyBuffer::new(zelf.to_owned().into(), desc, &BUFFER_METHODS); + Ok(buffer) } } @@ -1504,7 +1735,7 @@ pub mod array { let class = zelf.class(); let class_name = class.name(); let typecode = zelf.read().typecode(); - if matches!(typecode, 'u' | 'w') { + if matches!(typecode, "u" | "w") { if zelf.__len__() == 0 { return Ok(format!("{class_name}('{typecode}')")); } @@ -1576,11 +1807,9 @@ pub mod array { ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyArray::sequence_downcast(seq); if let Some(value) = value { - let typecode = zelf.read().typecode(); - let item = ArrayContentType::item_from_object(typecode, value, vm)?; - zelf.write().setitem_by_item(i, item, vm) + PyArray::assign_item(zelf, i, value, vm) } else { - zelf.write().delitem_by_index(i, vm) + zelf.delitem_index(i, vm) } }), contains: atomic_func!(|seq, target, vm| { @@ -1615,7 +1844,15 @@ pub mod array { fn try_resizable_opt(&self) -> Option> { // An export is a borrow someone else still holds, so it is // answered before the lock rather than by waiting on it. - (self.exports.load(atomic::Ordering::SeqCst) == 0).then(|| self.write()) + if self.exports.load(atomic::Ordering::SeqCst) != 0 { + return None; + } + let array = self.write(); + if self.exports.load(atomic::Ordering::SeqCst) == 0 { + Some(array) + } else { + None + } } fn try_resizable(&self, vm: &VirtualMachine) -> PyResult> { @@ -1670,27 +1907,32 @@ pub mod array { #[derive(FromArgs)] struct ReconstructorArgs { + // Clinic converts only the typecode and machine format before + // entering the implementation; the object checks happen there. #[pyarg(positional)] - arraytype: PyTypeRef, + arraytype: PyObjectRef, #[pyarg(positional)] - typecode: PyUtf8StrRef, + typecode: ArgNulFreeStr, #[pyarg(positional)] - mformat_code: MachineFormatCode, + mformat_code: ArgCInt, #[pyarg(positional)] - items: PyBytesRef, + items: PyObjectRef, } #[derive(Debug, Copy, Clone, Eq, PartialEq)] #[repr(u8)] enum MachineFormatCode { - Int8 { signed: bool }, // 0, 1 - Int16 { signed: bool, big_endian: bool }, // 2, 3, 4, 5 - Int32 { signed: bool, big_endian: bool }, // 6, 7, 8, 9 - Int64 { signed: bool, big_endian: bool }, // 10, 11, 12, 13 - Ieee754Float { big_endian: bool }, // 14, 15 - Ieee754Double { big_endian: bool }, // 16, 17 - Utf16 { big_endian: bool }, // 18, 19 - Utf32 { big_endian: bool }, // 20, 21 + Int8 { signed: bool }, // 0, 1 + Int16 { signed: bool, big_endian: bool }, // 2, 3, 4, 5 + Int32 { signed: bool, big_endian: bool }, // 6, 7, 8, 9 + Int64 { signed: bool, big_endian: bool }, // 10, 11, 12, 13 + Ieee754Float { big_endian: bool }, // 14, 15 + Ieee754Double { big_endian: bool }, // 16, 17 + Utf16 { big_endian: bool }, // 18, 19 + Utf32 { big_endian: bool }, // 20, 21 + Ieee754FloatComplex { big_endian: bool }, // 22, 23 + Ieee754DoubleComplex { big_endian: bool }, // 24, 25 + Ieee754Half { big_endian: bool }, // 26, 27 } impl From for u8 { @@ -1710,6 +1952,9 @@ pub mod array { MachineFormatCode::Ieee754Double { big_endian } => 16 + big_endian as Self, MachineFormatCode::Utf16 { big_endian } => 18 + big_endian as Self, MachineFormatCode::Utf32 { big_endian } => 20 + big_endian as Self, + MachineFormatCode::Ieee754FloatComplex { big_endian } => 22 + big_endian as Self, + MachineFormatCode::Ieee754DoubleComplex { big_endian } => 24 + big_endian as Self, + MachineFormatCode::Ieee754Half { big_endian } => 26 + big_endian as Self, } } } @@ -1733,46 +1978,33 @@ pub mod array { 16..=17 => Ok(Self::Ieee754Double { big_endian }), 18..=19 => Ok(Self::Utf16 { big_endian }), 20..=21 => Ok(Self::Utf32 { big_endian }), + 22..=23 => Ok(Self::Ieee754FloatComplex { big_endian }), + 24..=25 => Ok(Self::Ieee754DoubleComplex { big_endian }), + 26..=27 => Ok(Self::Ieee754Half { big_endian }), _ => Err(code), } } } - impl<'a> TryFromBorrowedObject<'a> for MachineFormatCode { - fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { - obj.try_to_ref::(vm) - .map_err(|_| { - vm.new_type_error(format!( - "an integer is required (got type {})", - obj.class().name() - )) - })? - .try_to_primitive::(vm)? - .to_u8() - .unwrap_or(u8::MAX) - .try_into() - .map_err(|_| { - vm.new_value_error("third argument must be a valid machine format code.") - }) - } - } - impl MachineFormatCode { - fn from_typecode(code: char) -> Option { + fn from_typecode(code: &str) -> Option { use core::mem::size_of; - let signed = code.is_ascii_uppercase(); + let signed = matches!(code, "b" | "h" | "i" | "l" | "q"); let big_endian = cfg!(target_endian = "big"); let int_size = match code { - 'b' | 'B' => return Some(Self::Int8 { signed }), - 'u' => { + "b" | "B" => return Some(Self::Int8 { signed }), + "u" => { return match size_of::() { 2 => Some(Self::Utf16 { big_endian }), 4 => Some(Self::Utf32 { big_endian }), _ => None, }; } - 'w' => return Some(Self::Utf32 { big_endian }), - 'f' => { + "w" => return Some(Self::Utf32 { big_endian }), + "e" => return Some(Self::Ieee754Half { big_endian }), + "Zf" => return Some(Self::Ieee754FloatComplex { big_endian }), + "Zd" => return Some(Self::Ieee754DoubleComplex { big_endian }), + "f" => { // Copied from CPython const Y: f32 = 16711938.0; return match &Y.to_ne_bytes() { @@ -1781,7 +2013,7 @@ pub mod array { _ => None, }; } - 'd' => { + "d" => { // Copied from CPython const Y: f64 = 9006104071832581.0; return match &Y.to_ne_bytes() { @@ -1803,12 +2035,36 @@ pub mod array { _ => None, } } + fn compatible_integer_typecode(self) -> Option<&'static str> { + let signed = match self { + Self::Int8 { signed } + | Self::Int16 { signed, .. } + | Self::Int32 { signed, .. } + | Self::Int64 { signed, .. } => signed, + _ => return None, + }; + let size = self.item_size(); + // CPython uses the last matching integer descriptor, not + // necessarily the original type code on an ABI mismatch. + let codes = if signed { + ["q", "l", "i", "h", "b"] + } else { + ["Q", "L", "I", "H", "B"] + }; + codes + .into_iter() + .find(|code| ArrayContentType::itemsize_of_typecode(code) == Some(size)) + } + const fn item_size(self) -> usize { match self { Self::Int8 { .. } => 1, - Self::Int16 { .. } | Self::Utf16 { .. } => 2, + Self::Int16 { .. } | Self::Utf16 { .. } | Self::Ieee754Half { .. } => 2, Self::Int32 { .. } | Self::Utf32 { .. } | Self::Ieee754Float { .. } => 4, - Self::Int64 { .. } | Self::Ieee754Double { .. } => 8, + Self::Int64 { .. } + | Self::Ieee754Double { .. } + | Self::Ieee754FloatComplex { .. } => 8, + Self::Ieee754DoubleComplex { .. } => 16, } } } @@ -1822,13 +2078,8 @@ pub mod array { Ok(typ) } - fn check_type_code(spec: &Py, vm: &VirtualMachine) -> PyResult { - let spec = spec.as_str().chars().exactly_one().map_err(|_| { - vm.new_type_error( - "_array_reconstructor() argument 2 must be a unicode character, not str", - ) - })?; - ArrayContentType::from_char(spec) + fn check_type_code(spec: &str, vm: &VirtualMachine) -> PyResult { + ArrayContentType::from_typecode(spec) .map_err(|_| vm.new_value_error("second argument must be a valid type code")) } @@ -1857,10 +2108,27 @@ pub mod array { #[pyfunction] fn _array_reconstructor(args: ReconstructorArgs, vm: &VirtualMachine) -> PyResult { - let cls = check_array_type(args.arraytype, vm)?; - let mut array = check_type_code(&args.typecode, vm)?; - let format = args.mformat_code; - let bytes = args.items.as_bytes(); + let cls = args.arraytype.downcast::().map_err(|obj| { + vm.new_type_error(format!( + "first argument must be a type object, not {}", + obj.class().slot_name() + )) + })?; + let cls = check_array_type(cls, vm)?; + let mut array = check_type_code(args.typecode.as_str(), vm)?; + let format = u8::try_from(args.mformat_code.into_primitive()) + .ok() + .and_then(|code| MachineFormatCode::try_from(code).ok()) + .ok_or_else(|| { + vm.new_value_error("third argument must be a valid machine format code.") + })?; + let items = args.items.downcast::().map_err(|obj| { + vm.new_type_error(format!( + "fourth argument should be bytes, not {}", + obj.class().slot_name() + )) + })?; + let bytes = items.as_bytes(); if !bytes.len().is_multiple_of(format.item_size()) { return Err(vm.new_value_error("bytes length not a multiple of item size")); } @@ -1868,6 +2136,9 @@ pub mod array { array.frombytes(bytes); return PyArray::from(array).into_ref_with_type(vm, cls); } + if let Some(typecode) = format.compatible_integer_typecode() { + array = check_type_code(typecode, vm)?; + } if !matches!( format, MachineFormatCode::Utf16 { .. } | MachineFormatCode::Utf32 { .. } @@ -1876,6 +2147,26 @@ pub mod array { } let mut chunks = bytes.chunks(format.item_size()); match format { + MachineFormatCode::Ieee754Half { big_endian } => chunks.try_for_each(|b| { + let value = f16::from_bits(chunk_to_obj!(b, u16, big_endian)).to_f64(); + array.push(value.to_pyobject(vm), vm) + })?, + MachineFormatCode::Ieee754FloatComplex { big_endian } => chunks.try_for_each(|b| { + let (re, im) = b.split_at(4); + let value = Complex64::new( + chunk_to_obj!(re, f32, big_endian) as f64, + chunk_to_obj!(im, f32, big_endian) as f64, + ); + array.push(value.to_pyobject(vm), vm) + })?, + MachineFormatCode::Ieee754DoubleComplex { big_endian } => chunks.try_for_each(|b| { + let (re, im) = b.split_at(8); + let value = Complex64::new( + chunk_to_obj!(re, f64, big_endian), + chunk_to_obj!(im, f64, big_endian), + ); + array.push(value.to_pyobject(vm), vm) + })?, MachineFormatCode::Ieee754Float { big_endian } => { chunks.try_for_each(|b| array.push(chunk_to_obj!(vm, b, f32, big_endian), vm))? } @@ -1900,7 +2191,7 @@ pub mod array { vm.new_unicode_decode_error( vm.ctx .new_str(if big_endian { "utf-16-be" } else { "utf-16-le" }), - args.items.clone(), + items.clone(), index * 2, index * 2 + 2, vm.ctx.new_str(reason), diff --git a/crates/stdlib/src/binascii.rs b/crates/stdlib/src/binascii.rs index 73c20506dd7..150c2845915 100644 --- a/crates/stdlib/src/binascii.rs +++ b/crates/stdlib/src/binascii.rs @@ -1,6 +1,8 @@ -// spell-checker:ignore hexlify unhexlify uuencodes rlecode rledecode +// spell-checker:ignore hexlify unhexlify uuencodes rlecode rledecode ABCDEFGHIJKLMNPQRSTUVXYZ abcdefhijklmpqr -pub(super) use decl::crc32; +mod base_n; + +pub(super) use decl::crc32_impl; pub(crate) use decl::module_def; use rustpython_common::binascii::{Base64DecodeError, Error}; @@ -8,14 +10,101 @@ use rustpython_vm::{VirtualMachine, builtins::PyBaseExceptionRef}; #[pymodule(name = "binascii")] mod decl { - use super::new_binascii_error; + use super::{base_n, new_binascii_error}; use crate::vm::{ - PyResult, VirtualMachine, - builtins::PyTypeRef, - function::{ArgAsciiBuffer, ArgBytesLike, ArgIndex, OptionalArg}, + AsObject, Py, PyObjectRef, PyResult, VirtualMachine, + builtins::{PyBytes, PyBytesRef, PyDict, PyModule, PyStr, PyTypeRef}, + function::{ArgAsciiBuffer, ArgBytesLike, ArgIndex, ArgIntoBool, OptionalArg}, }; use rustpython_common::binascii; + #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] + pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { + __module_exec(vm, module); + module.set_native_state(vm.ctx.new_dict().into()); + Ok(()) + } + + fn reverse_table( + module: &Py, + alphabet: &PyBytesRef, + size: usize, + padchar: Option, + vm: &VirtualMachine, + ) -> PyResult<[u8; 256]> { + let bytes = alphabet.as_bytes(); + if bytes.len() != size { + return Err(vm.new_value_error(format!("alphabet must have length {size}"))); + } + let cache = module + .native_state() + .ok_or_else(|| vm.new_runtime_error("Missing binascii state"))? + .downcast::() + .map_err(|_| vm.new_runtime_error("Broken binascii cache"))?; + // The actual bytes object is the key: subclass hash/equality callbacks + // are part of CPython's cache lookup and insertion semantics. + if let Some(value) = cache.get_item_opt(alphabet.as_object(), vm)? { + return value + .downcast_ref::() + .and_then(|value| value.as_bytes().try_into().ok()) + .ok_or_else(|| vm.new_runtime_error("Broken binascii cache")); + } + let table = base_n::reverse_table(bytes, padchar); + cache.set_item( + alphabet.as_object(), + vm.ctx.new_bytes(table.to_vec()).into(), + vm, + )?; + Ok(table) + } + + #[pyattr(name = "CRYPT_ALPHABET")] + fn crypt_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx + .new_bytes(b"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".to_vec()) + } + + #[pyattr(name = "UU_ALPHABET")] + fn uu_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx.new_bytes( + b" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_".to_vec(), + ) + } + + #[pyattr(name = "BINHEX_ALPHABET")] + fn binhex_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx.new_bytes( + b"!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr".to_vec(), + ) + } + + #[pyattr(name = "BASE85_ALPHABET")] + fn base85_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx.new_bytes(b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~".to_vec()) + } + + #[pyattr(name = "ASCII85_ALPHABET")] + fn ascii85_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx.new_bytes(b"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu".to_vec()) + } + + #[pyattr(name = "Z85_ALPHABET")] + fn z85_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx.new_bytes(b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-:+=^!/*?&<>()[]{}@%$#".to_vec()) + } + + #[pyattr(name = "BASE32_ALPHABET")] + fn base32_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx + .new_bytes(b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".to_vec()) + } + + #[pyattr(name = "BASE32HEX_ALPHABET")] + fn base32hex_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx + .new_bytes(b"0123456789ABCDEFGHIJKLMNOPQRSTUV".to_vec()) + } + #[pyattr(name = "Error", once)] pub(super) fn error_type(vm: &VirtualMachine) -> PyTypeRef { vm.ctx.new_exception_type( @@ -30,36 +119,71 @@ mod decl { vm.ctx.new_exception_type("binascii", "Incomplete", None) } - #[pyfunction(name = "b2a_hex")] - #[pyfunction] - fn hexlify( + #[derive(FromArgs)] + struct HexlifyArgs { + #[pyarg(any)] data: ArgBytesLike, - sep: OptionalArg, + #[pyarg(any, optional)] + sep: OptionalArg, + #[pyarg(any, optional, py_default = "1")] bytes_per_sep: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult> { - let sep = match sep { - OptionalArg::Present(sep) => sep.with_ref(|sep| { - let [sep] = sep else { + } + + #[pyfunction(name = "b2a_hex")] + #[pyfunction] + fn hexlify(args: HexlifyArgs, vm: &VirtualMachine) -> PyResult> { + let HexlifyArgs { + data, + sep, + bytes_per_sep, + } = args; + let sep_byte = match &sep { + OptionalArg::Present(sep) => { + if sep.length(vm)? != 1 { return Err(vm.new_value_error("sep must be length 1.")); - }; - if !sep.is_ascii() { - return Err(vm.new_value_error("sep must be ASCII.")); } - Ok(Some(*sep)) - })?, + let byte = if let Some(string) = sep.downcast_ref::() { + if string.kind().is_ascii() { + string.as_bytes().first().copied().unwrap_or_default() + } else { + let mut chars = string.as_wtf8().code_points(); + let first = chars.next().map_or(0, |ch| ch.to_u32()); + if first > u8::MAX as u32 || chars.any(|ch| ch.to_u32() > u8::MAX as u32) { + return Err(vm.new_value_error("sep must be ASCII.")); + } + first as u8 + } + } else if let Some(bytes) = sep.downcast_ref::() { + bytes.as_bytes().first().copied().unwrap_or_default() + } else { + return Err(vm.new_type_error("sep must be str or bytes.")); + }; + Some(byte) + } OptionalArg::Missing => None, }; let bytes_per_sep = bytes_per_sep.unwrap_or(1); - Ok(data.with_ref(|bytes| binascii::hexlify(bytes, sep, bytes_per_sep))) + Ok(data.with_ref(|bytes| binascii::hexlify(bytes, sep_byte, bytes_per_sep))) + } + + #[derive(FromArgs)] + struct UnhexlifyArgs { + #[pyarg(positional)] + hexstr: ArgAsciiBuffer, + #[pyarg(named, optional, py_default = "b''")] + ignorechars: OptionalArg, } #[pyfunction(name = "a2b_hex")] #[pyfunction] - fn unhexlify(hexstr: ArgAsciiBuffer, vm: &VirtualMachine) -> PyResult> { - hexstr - .with_ref(binascii::unhexlify) - .map_err(|e| new_binascii_error(e, vm)) + fn unhexlify(args: UnhexlifyArgs, vm: &VirtualMachine) -> PyResult> { + let ignorechars = ignored_argument(&args.ignorechars); + let result = args + .hexstr + .with_ref(|data| base_n::decode_hex(data, &ignorechars)); + drop(args.hexstr); + drop(args.ignorechars); + base_n_result(result, vm) } #[derive(FromArgs)] @@ -70,15 +194,15 @@ mod decl { crc: ArgIndex, } - pub(crate) fn crc32(data: ArgBytesLike, crc: ArgIndex) -> u32 { + pub(crate) fn crc32_impl(data: ArgBytesLike, crc: ArgIndex) -> u32 { let crc = crc.into_int_ref().as_u32_mask(); data.with_ref(|bytes| binascii::crc32(bytes, crc)) } - #[pyfunction(name = "crc32")] - fn crc32_py(args: Crc32Args) -> u32 { + #[pyfunction] + fn crc32(args: Crc32Args) -> u32 { let Crc32Args { data, crc } = args; - crc32(data, crc) + crc32_impl(data, crc) } #[pyfunction] @@ -86,56 +210,445 @@ mod decl { data.with_ref(|bytes| binascii::crc_hqx(bytes, crc.into_int_ref().as_u32_mask())) } - #[derive(FromArgs)] - struct NewlineArg { - #[pyarg(named, default = true)] - newline: bool, + #[pyattr(name = "BASE64_ALPHABET")] + fn base64_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx.new_bytes(binascii::BASE64_ALPHABET.to_vec()) + } + + #[pyattr(name = "URLSAFE_BASE64_ALPHABET")] + fn urlsafe_base64_alphabet(vm: &VirtualMachine) -> PyBytesRef { + vm.ctx + .new_bytes(b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".to_vec()) } #[derive(FromArgs)] struct A2bBase64Args { #[pyarg(positional)] data: ArgAsciiBuffer, - #[pyarg(named, default)] - strict_mode: bool, + #[pyarg(named, optional)] + strict_mode: OptionalArg, + #[pyarg(named, default = ArgIntoBool::TRUE)] + padded: ArgIntoBool, + #[pyarg(named, optional, py_default = "BASE64_ALPHABET")] + alphabet: OptionalArg, + #[pyarg(named, optional)] + ignorechars: OptionalArg, + #[pyarg(named, optional, py_default = "False")] + canonical: OptionalArg, } #[pyfunction] - fn a2b_base64(args: A2bBase64Args, vm: &VirtualMachine) -> PyResult> { - let A2bBase64Args { data, strict_mode } = args; - data.with_ref(|b| binascii::a2b_base64(b, strict_mode)) + fn a2b_base64( + module: &Py, + args: A2bBase64Args, + vm: &VirtualMachine, + ) -> PyResult> { + let A2bBase64Args { + data, + strict_mode, + padded, + alphabet, + ignorechars, + canonical, + } = args; + let strict_mode = match strict_mode { + OptionalArg::Present(value) => value.into_bool(), + OptionalArg::Missing => matches!(&ignorechars, OptionalArg::Present(_)), + }; + let result = (|| { + // Convert the last Clinic argument while both acquired buffers are alive. + let canonical = match canonical { + OptionalArg::Present(value) => value.try_to_bool(vm)?, + OptionalArg::Missing => false, + }; + const DEFAULT_TABLE: [u8; 256] = + binascii::base64_reverse_table(binascii::BASE64_ALPHABET); + let table = match &alphabet { + OptionalArg::Present(value) => reverse_table(module, value, 64, Some(b'='), vm)?, + OptionalArg::Missing => DEFAULT_TABLE, + }; + let mut ignored = [false; 256]; + if strict_mode && let OptionalArg::Present(value) = &ignorechars { + value.with_ref(|bytes| { + for &symbol in bytes { + ignored[symbol as usize] = true; + } + }); + } + data.with_ref(|bytes| { + binascii::a2b_base64( + bytes, + binascii::Base64DecodeOptions { + strict_mode, + padded: padded.into_bool(), + table: &table, + ignored: &ignored, + canonical, + }, + ) + }) .map_err(|e| new_binascii_error(e, vm)) + })(); + // Match Argument Clinic cleanup order, including failures in __bool__. + drop(data); + result + } + + #[derive(FromArgs)] + struct B2aBase64Args { + #[pyarg(positional)] + data: ArgBytesLike, + #[pyarg(named, default = ArgIntoBool::TRUE)] + padded: ArgIntoBool, + #[pyarg(named, default = 0)] + wrapcol: usize, + #[pyarg(named, default = ArgIntoBool::TRUE)] + newline: ArgIntoBool, + #[pyarg(named, optional, py_default = "BASE64_ALPHABET")] + alphabet: OptionalArg, + } + + #[pyfunction] + fn b2a_base64(args: B2aBase64Args, vm: &VirtualMachine) -> PyResult> { + let B2aBase64Args { + data, + padded, + wrapcol, + newline, + alphabet, + } = args; + let copy_alphabet = |bytes: &[u8]| -> PyResult<[u8; 64]> { + bytes + .try_into() + .map_err(|_| vm.new_value_error("alphabet must have length 64")) + }; + let alphabet_bytes = match &alphabet { + OptionalArg::Present(value) => value.with_ref(copy_alphabet), + OptionalArg::Missing => Ok(*binascii::BASE64_ALPHABET), + }; + let result = alphabet_bytes.and_then(|alphabet_bytes| { + data.with_ref(|bytes| { + binascii::b2a_base64( + bytes, + padded.into_bool(), + wrapcol, + newline.into_bool(), + &alphabet_bytes, + ) + }) + .map_err(|e| new_binascii_error(e, vm)) + }); + drop(data); + result + } + + fn base_n_result( + result: Result, base_n::Error>, + vm: &VirtualMachine, + ) -> PyResult> { + result.map_err(|error| match error { + base_n::Error::InvalidAlphabet(size) => { + vm.new_value_error(format!("alphabet must have length {size}")) + } + base_n::Error::Codec(message) => vm.new_exception_msg(error_type(vm), message.into()), + base_n::Error::Memory => vm.no_memory_error(), + }) + } + + fn encoder_alphabet( + argument: &OptionalArg, + default: &[u8], + ) -> Result, base_n::Error> { + match argument { + OptionalArg::Present(value) => { + value.with_ref(|bytes| base_n::copy_alphabet(bytes, default.len())) + } + OptionalArg::Missing => base_n::copy_alphabet(default, default.len()), + } + } + + fn ignored_argument(argument: &OptionalArg) -> [bool; 256] { + match argument { + OptionalArg::Present(value) => value.with_ref(base_n::ignored), + OptionalArg::Missing => [false; 256], + } + } + + fn canonical_argument( + argument: &OptionalArg, + vm: &VirtualMachine, + ) -> PyResult { + match argument { + OptionalArg::Present(value) => value.try_to_bool(vm), + OptionalArg::Missing => Ok(false), + } + } + + #[derive(FromArgs)] + struct B2aBase32Args { + #[pyarg(positional)] + data: ArgBytesLike, + #[pyarg(named, default = ArgIntoBool::TRUE)] + padded: ArgIntoBool, + #[pyarg(named, default = 0)] + wrapcol: usize, + #[pyarg(named, optional, py_default = "BASE32_ALPHABET")] + alphabet: OptionalArg, + } + + #[derive(FromArgs)] + struct A2bBase32Args { + #[pyarg(positional)] + data: ArgAsciiBuffer, + #[pyarg(named, default = ArgIntoBool::TRUE)] + padded: ArgIntoBool, + #[pyarg(named, optional, py_default = "BASE32_ALPHABET")] + alphabet: OptionalArg, + #[pyarg(named, optional, py_default = "b''")] + ignorechars: OptionalArg, + #[pyarg(named, optional, py_default = "False")] + canonical: OptionalArg, + } + + #[pyfunction] + fn a2b_base32( + module: &Py, + args: A2bBase32Args, + vm: &VirtualMachine, + ) -> PyResult> { + let A2bBase32Args { + data, + padded, + alphabet, + ignorechars, + canonical, + } = args; + let result = (|| { + // This is the last Clinic conversion. Keep acquired exports alive + // and reach ordered cleanup even when __bool__ raises. + let canonical = canonical_argument(&canonical, vm)?; + let table = match &alphabet { + OptionalArg::Present(value) => reverse_table(module, value, 32, Some(b'='), vm)?, + OptionalArg::Missing => base_n::reverse_table(base_n::BASE32, Some(b'=')), + }; + let ignore = ignored_argument(&ignorechars); + let result = data.with_ref(|data| { + base_n::decode32(data, &table, &ignore, padded.into_bool(), canonical) + }); + base_n_result(result, vm) + })(); + // Match Argument Clinic cleanup: release data before auxiliary exports. + drop(data); + drop(ignorechars); + result } #[pyfunction] - fn b2a_base64(data: ArgBytesLike, NewlineArg { newline }: NewlineArg) -> Vec { - data.with_ref(|bytes| binascii::b2a_base64(bytes, newline)) + fn b2a_base32(args: B2aBase32Args, vm: &VirtualMachine) -> PyResult> { + let B2aBase32Args { + data, + padded, + wrapcol, + alphabet, + } = args; + let result = encoder_alphabet(&alphabet, base_n::BASE32).and_then(|alphabet_bytes| { + data.with_ref(|data| { + base_n::encode32(data, padded.into_bool(), wrapcol, &alphabet_bytes) + }) + }); + drop(data); + drop(alphabet); + base_n_result(result, vm) + } + + #[derive(FromArgs)] + struct B2aBase85Args { + #[pyarg(positional)] + data: ArgBytesLike, + #[pyarg(named, default = ArgIntoBool::FALSE)] + pad: ArgIntoBool, + #[pyarg(named, default = 0)] + wrapcol: usize, + #[pyarg(named, optional, py_default = "BASE85_ALPHABET")] + alphabet: OptionalArg, + } + + #[derive(FromArgs)] + struct A2bBase85Args { + #[pyarg(positional)] + data: ArgAsciiBuffer, + #[pyarg(named, optional, py_default = "BASE85_ALPHABET")] + alphabet: OptionalArg, + #[pyarg(named, optional, py_default = "b''")] + ignorechars: OptionalArg, + #[pyarg(named, optional, py_default = "False")] + canonical: OptionalArg, + } + + #[pyfunction] + fn a2b_base85( + module: &Py, + args: A2bBase85Args, + vm: &VirtualMachine, + ) -> PyResult> { + let A2bBase85Args { + data, + alphabet, + ignorechars, + canonical, + } = args; + let result = (|| { + // This is the last Clinic conversion. Keep acquired exports alive + // and reach ordered cleanup even when __bool__ raises. + let canonical = canonical_argument(&canonical, vm)?; + let table = match &alphabet { + OptionalArg::Present(value) => reverse_table(module, value, 85, None, vm)?, + OptionalArg::Missing => base_n::reverse_table(base_n::BASE85, None), + }; + let ignore = ignored_argument(&ignorechars); + let result = data.with_ref(|data| { + base_n::decode85(data, &table, &ignore, canonical, false, false, false) + }); + base_n_result(result, vm) + })(); + drop(data); + drop(ignorechars); + result + } + + #[pyfunction] + fn b2a_base85(args: B2aBase85Args, vm: &VirtualMachine) -> PyResult> { + let B2aBase85Args { + data, + pad, + wrapcol, + alphabet, + } = args; + let result = encoder_alphabet(&alphabet, base_n::BASE85).and_then(|alphabet_bytes| { + data.with_ref(|data| { + base_n::encode85( + data, + pad.into_bool(), + wrapcol, + &alphabet_bytes, + false, + false, + false, + ) + }) + }); + drop(data); + drop(alphabet); + base_n_result(result, vm) + } + + #[derive(FromArgs)] + struct B2aAscii85Args { + #[pyarg(positional)] + data: ArgBytesLike, + #[pyarg(named, default = ArgIntoBool::FALSE)] + foldspaces: ArgIntoBool, + #[pyarg(named, default = 0)] + wrapcol: usize, + #[pyarg(named, default = ArgIntoBool::FALSE)] + pad: ArgIntoBool, + #[pyarg(named, default = ArgIntoBool::FALSE)] + adobe: ArgIntoBool, + } + + #[derive(FromArgs)] + struct A2bAscii85Args { + #[pyarg(positional)] + data: ArgAsciiBuffer, + #[pyarg(named, default = ArgIntoBool::FALSE)] + foldspaces: ArgIntoBool, + #[pyarg(named, default = ArgIntoBool::FALSE)] + adobe: ArgIntoBool, + #[pyarg(named, optional, py_default = "b''")] + ignorechars: OptionalArg, + #[pyarg(named, optional, py_default = "False")] + canonical: OptionalArg, + } + + #[pyfunction] + fn a2b_ascii85(args: A2bAscii85Args, vm: &VirtualMachine) -> PyResult> { + let A2bAscii85Args { + data, + foldspaces, + adobe, + ignorechars, + canonical, + } = args; + let result = (|| { + // This is the last Clinic conversion. Keep acquired exports alive + // and reach ordered cleanup even when __bool__ raises. + let canonical = canonical_argument(&canonical, vm)?; + let ignore = ignored_argument(&ignorechars); + let result = data.with_ref(|data| { + base_n::decode85( + data, + &base_n::reverse_table(base_n::ASCII85, None), + &ignore, + canonical, + true, + foldspaces.into_bool(), + adobe.into_bool(), + ) + }); + base_n_result(result, vm) + })(); + drop(data); + drop(ignorechars); + result + } + + #[pyfunction] + fn b2a_ascii85(args: B2aAscii85Args, vm: &VirtualMachine) -> PyResult> { + let B2aAscii85Args { + data, + foldspaces, + wrapcol, + pad, + adobe, + } = args; + let result = data.with_ref(|data| { + base_n::encode85( + data, + pad.into_bool(), + wrapcol, + base_n::ASCII85, + true, + foldspaces.into_bool(), + adobe.into_bool(), + ) + }); + base_n_result(result, vm) } #[derive(FromArgs)] struct A2bQpArgs { #[pyarg(any)] data: ArgAsciiBuffer, - #[pyarg(any, default)] - header: bool, + #[pyarg(any, default = ArgIntoBool::FALSE)] + header: ArgIntoBool, } #[pyfunction] fn a2b_qp(args: A2bQpArgs) -> Vec { let A2bQpArgs { data, header } = args; - data.with_ref(|buffer| binascii::a2b_qp(buffer, header)) + data.with_ref(|buffer| binascii::a2b_qp(buffer, header.into_bool())) } #[derive(FromArgs)] struct B2aQpArgs { #[pyarg(any)] data: ArgBytesLike, - #[pyarg(any, default)] - quotetabs: bool, - #[pyarg(any, default = true)] - istext: bool, - #[pyarg(any, default)] - header: bool, + #[pyarg(any, default = ArgIntoBool::FALSE)] + quotetabs: ArgIntoBool, + #[pyarg(any, default = ArgIntoBool::TRUE)] + istext: ArgIntoBool, + #[pyarg(any, default = ArgIntoBool::FALSE)] + header: ArgIntoBool, } #[pyfunction] @@ -146,7 +659,14 @@ mod decl { istext, header, } = args; - data.with_ref(|buf| binascii::b2a_qp(buf, quotetabs, istext, header)) + data.with_ref(|buf| { + binascii::b2a_qp( + buf, + quotetabs.into_bool(), + istext.into_bool(), + header.into_bool(), + ) + }) } #[pyfunction] @@ -157,8 +677,8 @@ mod decl { #[derive(FromArgs)] struct BacktickArg { - #[pyarg(named, default)] - backtick: bool, + #[pyarg(named, default = ArgIntoBool::FALSE)] + backtick: ArgIntoBool, } #[pyfunction] @@ -167,7 +687,7 @@ mod decl { BacktickArg { backtick }: BacktickArg, vm: &VirtualMachine, ) -> PyResult> { - data.with_ref(|b| binascii::b2a_uu(b, backtick)) + data.with_ref(|b| binascii::b2a_uu(b, backtick.into_bool())) .map_err(|e| new_binascii_error(e, vm)) } } @@ -182,6 +702,8 @@ fn new_binascii_error(error: Error, vm: &VirtualMachine) -> PyBaseExceptionRef { Error::TrailingGarbage => "Trailing garbage".to_owned(), Error::TooLong => "At most 45 bytes at once".to_owned(), Error::Base64(e) => base64_message(e), + Error::TooMuchBase64Data => "Too much data for base64".to_owned(), + Error::Memory => return vm.no_memory_error(), }; vm.new_exception_msg(decl::error_type(vm), message.into()) } @@ -199,5 +721,7 @@ fn base64_message(error: Base64DecodeError) -> String { "Invalid base64-encoded string: number of data characters ({index}) cannot be 1 more than a multiple of 4" ), Base64DecodeError::IncorrectPadding => "Incorrect padding".to_owned(), + Base64DecodeError::PaddingNotAllowed => "Padding not allowed".to_owned(), + Base64DecodeError::NonZeroPaddingBits => "Non-zero padding bits".to_owned(), } } diff --git a/crates/stdlib/src/binascii/base_n.rs b/crates/stdlib/src/binascii/base_n.rs new file mode 100644 index 00000000000..fb966a9c3d4 --- /dev/null +++ b/crates/stdlib/src/binascii/base_n.rs @@ -0,0 +1,431 @@ +// Scalar native equivalents of CPython 3.15 Modules/binascii.c base-N codecs. + +pub(super) const BASE32: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; +pub(super) const BASE85: &[u8] = + b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~"; +pub(super) const ASCII85: &[u8] = + b"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstu"; + +#[derive(Debug)] +pub(super) enum Error { + InvalidAlphabet(usize), + Codec(String), + Memory, +} + +type Result = core::result::Result; + +fn codec(message: impl Into) -> Error { + Error::Codec(message.into()) +} + +fn buffer(size: usize, too_large: &str) -> Result> { + if size > isize::MAX as usize { + return Err(codec(too_large)); + } + let mut result = Vec::new(); + result.try_reserve_exact(size).map_err(|_| Error::Memory)?; + Ok(result) +} + +fn checked_alphabet(alphabet: &[u8], size: usize) -> Result<&[u8]> { + if alphabet.len() != size { + return Err(Error::InvalidAlphabet(size)); + } + Ok(alphabet) +} + +pub(super) fn copy_alphabet(alphabet: &[u8], size: usize) -> Result> { + checked_alphabet(alphabet, size)?; + let mut out = buffer(size, "Too large alphabet")?; + out.extend_from_slice(alphabet); + Ok(out) +} + +pub(super) fn reverse_table(alphabet: &[u8], padchar: Option) -> [u8; 256] { + let mut table = [u8::MAX; 256]; + for (digit, &ch) in alphabet.iter().enumerate() { + // Duplicate characters are allowed; their last occurrence wins. + table[usize::from(ch)] = digit as u8; + } + if let Some(padchar) = padchar { + table[usize::from(padchar)] = alphabet.len() as u8; + } + table +} + +pub(super) fn ignored(ignorechars: &[u8]) -> [bool; 256] { + let mut table = [false; 256]; + for &ch in ignorechars { + table[usize::from(ch)] = true; + } + table +} + +fn rounded_width(width: usize, quantum: usize) -> usize { + if width == 0 { + 0 + } else { + width.max(quantum) / quantum * quantum + } +} + +fn wrapped_size(size: usize, width: usize, newline: bool, too_large: &str) -> Result { + let breaks = if width == 0 || size == 0 { + 0 + } else { + (size - 1) / width + }; + size.checked_add(breaks) + .and_then(|n| n.checked_add(usize::from(newline))) + .filter(|n| isize::try_from(*n).is_ok()) + .ok_or_else(|| codec(too_large)) +} + +fn wrap(mut input: Vec, width: usize, newline: bool, too_large: &str) -> Result> { + let size = wrapped_size(input.len(), width, newline, too_large)?; + if width != 0 && input.len() > width { + let mut out = buffer(size, too_large)?; + for (index, chunk) in input.chunks(width).enumerate() { + if index != 0 { + out.push(b'\n'); + } + out.extend_from_slice(chunk); + } + input = out; + } + if newline { + input.try_reserve(1).map_err(|_| Error::Memory)?; + input.push(b'\n'); + } + Ok(input) +} + +pub(super) fn encode32( + data: &[u8], + padded: bool, + width: usize, + alphabet: &[u8], +) -> Result> { + let (size, in_group, out_group, too_large) = (32, 5, 8, "Too much data for base32"); + let bits = 5; + checked_alphabet(alphabet, size)?; + let full_size = data + .len() + .div_ceil(in_group) + .checked_mul(out_group) + .ok_or_else(|| codec(too_large))?; + let pads = (in_group - data.len() % in_group) % in_group * out_group / in_group; + let encoded_size = full_size - if padded { 0 } else { pads }; + let width = rounded_width(width, out_group); + wrapped_size(encoded_size, width, false, too_large)?; + let mut out = buffer(encoded_size, too_large)?; + let mut value = 0u32; + let mut available = 0u32; + let mask = (1u32 << bits) - 1; + for &byte in data { + value = (value << 8) | u32::from(byte); + available += 8; + while available >= bits { + available -= bits; + out.push(alphabet[((value >> available) & mask) as usize]); + } + value &= (1u32 << available) - 1; + } + if available != 0 { + out.push(alphabet[((value << (bits - available)) & mask) as usize]); + } + if padded { + out.resize(encoded_size, b'='); + } + wrap(out, width, false, too_large) +} + +pub(super) fn decode32( + data: &[u8], + table: &[u8; 256], + ignorechars: &[bool; 256], + padded: bool, + canonical: bool, +) -> Result> { + let (size, group, decoded_group, name) = (32, 8, 5, "base32"); + let bits = 5; + let ignore = ignorechars; + let capacity = data + .len() + .div_ceil(group) + .checked_mul(decoded_group) + .ok_or_else(|| codec(format!("Too much {name} data")))?; + let mut out = buffer(capacity, &format!("Too much {name} data"))?; + let mut pos = 0usize; + let mut pads = 0usize; + let mut value = 0u32; + let mut available = 0u32; + for &ch in data { + if padded && ch == b'=' { + pads += 1; + let allowed_pos = matches!(pos, 2 | 4 | 5 | 7); + if allowed_pos && pos + pads <= group { + continue; + } + if ignore[usize::from(b'=')] { + continue; + } + if matches!(pos, 1 | 3 | 6) { + break; + } + return Err(codec(if pos == 0 && out.is_empty() { + "Leading padding not allowed" + } else { + "Excess padding not allowed" + })); + } + let digit = table[usize::from(ch)]; + if usize::from(digit) >= size { + if !ignore[usize::from(ch)] { + return Err(codec(if ch == b'=' { + "Padding not allowed".to_owned() + } else { + format!("Only {name} data is allowed") + })); + } + continue; + } + if pads != 0 && !ignore[usize::from(b'=')] { + return Err(codec(if pos + pads == group { + "Excess data after padding" + } else { + "Discontinuous padding not allowed" + })); + } + value = (value << bits) | u32::from(digit); + available += bits; + if available >= 8 { + available -= 8; + out.push((value >> available) as u8); + value &= (1u32 << available) - 1; + } + pos += 1; + if pos == group { + pos = 0; + pads = 0; + } + } + if matches!(pos, 1 | 3 | 6) { + let count = out.len() / decoded_group * group + pos; + return Err(codec(format!( + "Invalid base32-encoded string: number of data characters ({count}) cannot be 1, 3, or 6 more than a multiple of 8" + ))); + } + if padded && pos != 0 && pos + pads < group { + return Err(codec("Incorrect padding")); + } + if canonical && value != 0 { + return Err(codec("Non-zero padding bits")); + } + Ok(out) +} + +fn digits85(mut value: u32, alphabet: &[u8]) -> [u8; 5] { + let mut out = [0; 5]; + for slot in out.iter_mut().rev() { + *slot = alphabet[(value % 85) as usize]; + value /= 85; + } + out +} + +pub(super) fn encode85( + data: &[u8], + pad: bool, + width: usize, + alphabet: &[u8], + ascii85: bool, + foldspaces: bool, + adobe: bool, +) -> Result> { + checked_alphabet(alphabet, 85)?; + let too_large = if ascii85 { + "Too much data for Ascii85" + } else { + "Too much data for Base85" + }; + let full_size = data + .len() + .div_ceil(4) + .checked_mul(5) + .and_then(|n| n.checked_add(if adobe { 4 } else { 0 })) + .ok_or_else(|| codec(too_large))?; + let size = full_size + - if !pad && !data.len().is_multiple_of(4) { + 4 - data.len() % 4 + } else { + 0 + }; + let width = if ascii85 { + if adobe && width == 1 { 2 } else { width } + } else { + rounded_width(width, 5) + }; + wrapped_size(size, width, false, too_large)?; + let mut out = buffer(size, too_large)?; + if adobe { + out.extend_from_slice(b"<~"); + } + for chunk in data.chunks(4) { + let mut block = [0; 4]; + block[..chunk.len()].copy_from_slice(chunk); + let value = u32::from_be_bytes(block); + if ascii85 && value == 0 && (pad || chunk.len() == 4) { + out.push(b'z'); + } else if ascii85 && foldspaces && value == 0x20202020 && chunk.len() == 4 { + out.push(b'y'); + } else { + let digits = digits85(value, alphabet); + let count = if pad || chunk.len() == 4 { + 5 + } else { + chunk.len() + 1 + }; + out.extend_from_slice(&digits[..count]); + } + } + if adobe { + out.extend_from_slice(b"~>"); + } + let mut out = wrap(out, width, false, too_large)?; + if adobe && out.len() >= 3 && out[out.len() - 2] == b'\n' { + let len = out.len(); + out[len - 3] = b'\n'; + out[len - 2] = b'~'; + } + Ok(out) +} + +pub(super) fn decode85( + mut data: &[u8], + table: &[u8; 256], + ignorechars: &[bool; 256], + canonical: bool, + ascii85: bool, + foldspaces: bool, + adobe: bool, +) -> Result> { + if adobe { + if !data.ends_with(b"~>") { + return Err(codec("Ascii85 encoded byte sequences must end with b'~>'")); + } + data = &data[..data.len() - 2]; + if data.starts_with(b"<~") { + data = &data[2..]; + } + } + let ignore = ignorechars; + let shortcuts = if ascii85 { + data.iter().filter(|ch| matches!(ch, b'y' | b'z')).count() + } else { + 0 + }; + let size = (data.len() - shortcuts) + .div_ceil(5) + .checked_mul(4) + .and_then(|n| shortcuts.checked_mul(4).and_then(|m| n.checked_add(m))) + .ok_or_else(|| codec("Too much Ascii85 data"))?; + let mut out = buffer(size, "Too much Ascii85 data")?; + let mut value = 0u32; + let mut pos = 0usize; + let mut from_z = false; + let mut index = 0usize; + let mut tail_len = 4usize; + while index < data.len() || pos != 0 { + let (ch, digit) = if index < data.len() { + let ch = data[index]; + (ch, table[usize::from(ch)]) + } else { + tail_len -= 1; + (0, 84) + }; + if digit < 85 { + value = value + .checked_mul(85) + .and_then(|n| n.checked_add(u32::from(digit))) + .ok_or_else(|| { + codec(if ascii85 { + "Ascii85 overflow".to_owned() + } else { + format!("Base85 overflow in hunk starting at byte {}", index / 5 * 5) + }) + })?; + pos += 1; + } else if ascii85 && (ch == b'z' || (ch == b'y' && foldspaces)) { + if pos != 0 { + return Err(codec(format!( + "'{}' inside Ascii85 5-tuple", + char::from(ch) + ))); + } + value = if ch == b'y' { 0x20202020 } else { 0 }; + from_z = ch == b'z'; + pos = 5; + } else if !ignore[usize::from(ch)] { + return Err(codec(if ascii85 { + format!("Non-Ascii85 digit found: {}", char::from(ch)) + } else { + format!("bad Base85 character at position {index}") + })); + } + index += 1; + if pos != 5 { + continue; + } + if tail_len == 0 { + return Err(codec(if ascii85 { + "Incomplete Ascii85 group" + } else { + "Incomplete Base85 group" + })); + } + out.extend_from_slice(&value.to_be_bytes()[..tail_len]); + if canonical { + if ascii85 && tail_len == 4 && value == 0 && !from_z { + return Err(codec("Non-canonical encoding, use 'z' for all-zero groups")); + } + if tail_len < 4 { + let pads = 4 - tail_len; + let top = value >> (pads * 8) << (pads * 8); + let divisor = 85u32.pow(pads as u32); + if top / divisor != value / divisor { + return Err(codec("Non-zero padding bits")); + } + } + } + pos = 0; + value = 0; + from_z = false; + } + Ok(out) +} + +pub(super) fn decode_hex(data: &[u8], ignorechars: &[bool; 256]) -> Result> { + let ignore = ignorechars; + let mut out = buffer(data.len() / 2, "Too much hexadecimal data")?; + let mut high = None; + for &ch in data { + let digit = match ch { + b'0'..=b'9' => ch - b'0', + b'a'..=b'f' => ch - b'a' + 10, + b'A'..=b'F' => ch - b'A' + 10, + _ if ignore[usize::from(ch)] => continue, + _ => return Err(codec("Non-hexadecimal digit found")), + }; + if let Some(hi) = high.take() { + out.push((hi << 4) | digit); + } else { + high = Some(digit); + } + } + if high.is_some() { + return Err(codec("Odd number of hexadecimal digits")); + } + Ok(out) +} diff --git a/crates/stdlib/src/bisect.rs b/crates/stdlib/src/bisect.rs index 8efdd7d4187..0848abfa5ab 100644 --- a/crates/stdlib/src/bisect.rs +++ b/crates/stdlib/src/bisect.rs @@ -3,144 +3,249 @@ pub(crate) use _bisect::module_def; #[pymodule] mod _bisect { use crate::vm::{ - PyObjectRef, PyResult, VirtualMachine, function::ArgIndex, types::PyComparisonOp, + AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, + function::{ArgIndex, Either, OptionalArg, PyComparisonValue}, + protocol::PySequence, + types::PyComparisonOp, }; #[derive(FromArgs)] struct BisectArgs { a: PyObjectRef, x: PyObjectRef, - #[pyarg(any, default = 0)] - lo: ArgIndex, + #[pyarg(any, optional, py_default = "0")] + lo: OptionalArg, // None means the sequence length. #[pyarg(any, optional)] - hi: Option, + hi: Option, #[pyarg(named, optional)] key: Option, } - // Handles objects that implement __index__ and makes sure index fits in needed isize. - #[inline] - fn handle_default(arg: ArgIndex, vm: &VirtualMachine) -> PyResult { - arg.into_int_ref().try_to_primitive(vm) - } - - // Handles defaults for lo, hi. - // - // - lo must be >= 0 with a default of 0. - // - hi, while it could be negative, defaults to `0` and the same effect is achieved - // (while loop isn't entered); this way we keep it a usize (and, if my understanding - // is correct, issue 13496 is handled). Its default value is set to the length of the - // input sequence. - #[inline] - fn as_usize( - lo: ArgIndex, - hi: Option, - seq_len: usize, + // Bind all arguments before calling __index__, then convert in the same + // order as the CPython wrapper. Keep the original argument objects alive. + fn parse_bounds( + lo: &OptionalArg, + hi: Option<&PyObjectRef>, vm: &VirtualMachine, - ) -> PyResult<(usize, usize)> { - // We only deal with positives for lo, try_from can't fail. - let lo = usize::try_from(handle_default(lo, vm)?) - .map_err(|_| vm.new_value_error("lo must be non-negative"))?; + ) -> PyResult<(usize, isize)> { + let lo = match lo { + OptionalArg::Missing => 0, + OptionalArg::Present(obj) => { + let index = ArgIndex::try_from_borrowed_object(vm, obj)?; + isize::try_from(index.as_ref().as_bigint()).map_err(|_| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") + })? + } + }; + let lo = usize::try_from(lo).map_err(|_| vm.new_value_error("lo cannot be negative"))?; let hi = match hi { - Some(value) => { - let value: isize = value.into_int_ref().try_to_primitive(vm)?; - usize::try_from(value).unwrap_or(0) + Some(obj) => { + if !obj.number().is_index() { + let name = obj.class().slot_name(); + let end = name.floor_char_boundary(name.len().min(200)); + return Err(vm.new_type_error(format!( + "argument should be integer or None, not '{}'", + &name[..end] + ))); + } + let index = ArgIndex::try_from_borrowed_object(vm, obj)?; + isize::try_from(index.as_ref().as_bigint()).map_err(|_| { + let name = obj.class().slot_name(); + let end = name.floor_char_boundary(name.len().min(200)); + vm.new_overflow_error(format!( + "cannot fit '{}' into an index-sized integer", + &name[..end] + )) + })? } - None => seq_len, + None => -1, }; Ok((lo, hi)) } + // The -1 sentinel is shared by an omitted/None hi and an explicit -1. + // Other negative upper bounds have the same result as zero because lo is + // nonnegative. Only the sentinel requires asking the sequence for length. #[inline] - #[pyfunction] - fn bisect_left( - BisectArgs { a, x, lo, hi, key }: BisectArgs, + fn resolve_hi(hi: isize, sequence: PySequence<'_>, vm: &VirtualMachine) -> PyResult { + if hi == -1 { + sequence.length(vm) + } else { + Ok(usize::try_from(hi).unwrap_or(0)) + } + } + + type SequenceItem = for<'a> fn(PySequence<'a>, isize, &VirtualMachine) -> PyResult; + + // Snapshot the item slot even when the search range is empty, as CPython does. + fn sequence_item(sequence: PySequence<'_>, vm: &VirtualMachine) -> PyResult { + sequence.slots().item.load().ok_or_else(|| { + let msg = { + let name = sequence.obj.class().slot_name(); + let end = name.floor_char_boundary(name.len().min(200)); + let name = &name[..end]; + if sequence.obj.mapping_unchecked().check() { + format!("{name} is not a sequence") + } else { + format!("'{name}' object does not support indexing") + } + }; + vm.new_type_error(msg) + }) + } + + #[inline] + fn bisect_impl( + a: &PyObject, + x: &PyObject, + mut lo: usize, + hi: isize, + key: Option<&PyObjectRef>, vm: &VirtualMachine, ) -> PyResult { - let (mut lo, mut hi) = as_usize(lo, hi, a.length(vm)?, vm)?; + let sequence = a.sequence_unchecked(); + let mut hi = resolve_hi(hi, sequence, vm)?; + let get_item = sequence_item(sequence, vm)?; + // On failure, leave the recursion section before releasing the current + // item. This owner must be declared before the guard for drop ordering. + let mut error_item = None; + let recursion_context = if LEFT { + " in _bisect.bisect_left" + } else { + " in _bisect.bisect_right" + }; + vm.enter_recursive_call(recursion_context)?; + let recursion_guard = scopeguard::guard((), |()| vm.leave_recursive_call()); + // Snapshot identity and slot without keeping the original class alive: + // a callback can change x.__class__ and collect the old heap type. + let (needle_type_id, mut compare) = { + let class = x.class(); + (class.get_id(), class.slots().richcompare.load()) + }; - while lo < hi { + let result = loop { + if lo >= hi { + break Ok(lo); + } // Handles issue 13496. let mid = (lo + hi) / 2; - let a_mid = a.get_item(&mid, vm)?; - let comp = if let Some(ref key) = key { - key.call((a_mid,), vm)? + let a_mid = get_item(sequence, mid as isize, vm)?; + let comp = if let Some(key) = key { + // The callback may delete its argument. Release our reference + // only after it returns, including when it raises an exception. + let result = match key.call((&*a_mid,), vm) { + Ok(result) => result, + Err(err) => { + error_item = Some(a_mid); + break Err(err); + } + }; + drop(a_mid); + result } else { a_mid }; - if comp.rich_compare_bool(&x, PyComparisonOp::Lt, vm)? { + let (left, right) = if LEFT { (&*comp, x) } else { (x, &*comp) }; + let less = (|| { + if let Some(compare_fn) = + compare.filter(|_| comp.class().get_id() == needle_type_id) + { + match compare_fn(left, right, PyComparisonOp::Lt, vm)? { + Either::A(obj) if obj.is(&vm.ctx.not_implemented) => {} + Either::A(obj) => return obj.try_to_bool(vm), + Either::B(PyComparisonValue::Implemented(value)) => return Ok(value), + Either::B(PyComparisonValue::NotImplemented) => {} + } + // NotImplemented disables the shortcut for this search. + // Generic dispatch retries __lt__ before reflected __gt__. + compare = None; + } + // A different type does not disable the same-type shortcut + // for subsequent midpoint objects. + left.rich_compare_bool(right, PyComparisonOp::Lt, vm) + })(); + let less = match less { + Ok(value) => value, + Err(err) => { + error_item = Some(comp); + break Err(err); + } + }; + // Comparison results have already been released after conversion + // to bool. Dispose of the midpoint before starting another probe. + if less == LEFT { lo = mid + 1; } else { hi = mid; } - } - Ok(lo) + }; + drop(recursion_guard); + drop(error_item); + result } #[inline] #[pyfunction] - fn bisect_right( + fn bisect_left( BisectArgs { a, x, lo, hi, key }: BisectArgs, vm: &VirtualMachine, ) -> PyResult { - let (mut lo, mut hi) = as_usize(lo, hi, a.length(vm)?, vm)?; + let (low, high) = parse_bounds(&lo, hi.as_ref(), vm)?; + bisect_impl::(&a, &x, low, high, key.as_ref(), vm) + } - while lo < hi { - // Handles issue 13496. - let mid = (lo + hi) / 2; - let a_mid = a.get_item(&mid, vm)?; - let comp = if let Some(ref key) = key { - key.call((a_mid,), vm)? - } else { - a_mid - }; - if x.rich_compare_bool(&comp, PyComparisonOp::Lt, vm)? { - hi = mid; - } else { - lo = mid + 1; - } - } - Ok(lo) + #[inline] + #[pyfunction] + fn bisect_right( + BisectArgs { a, x, lo, hi, key }: BisectArgs, + vm: &VirtualMachine, + ) -> PyResult { + let (low, high) = parse_bounds(&lo, hi.as_ref(), vm)?; + bisect_impl::(&a, &x, low, high, key.as_ref(), vm) } #[pyfunction] fn insort_left(BisectArgs { a, x, lo, hi, key }: BisectArgs, vm: &VirtualMachine) -> PyResult { + let (low, high) = parse_bounds(&lo, hi.as_ref(), vm)?; // The search runs on the key, the insert has to put back the item itself. - let needle = match key { - Some(ref key) => key.call((x.clone(),), vm)?, - None => x.clone(), + let needle = match &key { + Some(key) => Some(key.call((&*x,), vm)?), + None => None, }; - let index = bisect_left( - BisectArgs { - a: a.clone(), - x: needle, - lo, - hi, - key, - }, + let index = bisect_impl::( + &a, + needle.as_deref().unwrap_or(&x), + low, + high, + key.as_ref(), vm, - )?; - vm.call_method(&a, "insert", (index, x)) + ); + drop(needle); + let index = index?; + let _result = vm.call_method(&a, "insert", (index, &*x))?; + Ok(vm.ctx.none()) } #[pyfunction] fn insort_right(BisectArgs { a, x, lo, hi, key }: BisectArgs, vm: &VirtualMachine) -> PyResult { + let (low, high) = parse_bounds(&lo, hi.as_ref(), vm)?; // The search runs on the key, the insert has to put back the item itself. - let needle = match key { - Some(ref key) => key.call((x.clone(),), vm)?, - None => x.clone(), + let needle = match &key { + Some(key) => Some(key.call((&*x,), vm)?), + None => None, }; - let index = bisect_right( - BisectArgs { - a: a.clone(), - x: needle, - lo, - hi, - key, - }, + let index = bisect_impl::( + &a, + needle.as_deref().unwrap_or(&x), + low, + high, + key.as_ref(), vm, - )?; - vm.call_method(&a, "insert", (index, x)) + ); + drop(needle); + let index = index?; + let _result = vm.call_method(&a, "insert", (index, &*x))?; + Ok(vm.ctx.none()) } } diff --git a/crates/stdlib/src/blake2.rs b/crates/stdlib/src/blake2.rs index a7dad88d099..7eda4b02b7a 100644 --- a/crates/stdlib/src/blake2.rs +++ b/crates/stdlib/src/blake2.rs @@ -4,90 +4,16 @@ pub(crate) use _blake2::module_def; #[pymodule] mod _blake2 { - use crate::hashlib::_hashlib::{Blake2Hash, BlakeHashArgs, local_blake2b, local_blake2s}; + use crate::hashlib::_hashlib::{ + Blake2Hash, Blake2bArgs, Blake2sArgs, local_blake2b, local_blake2s, + }; use crate::vm::{ Context, Py, PyPayload, PyResult, VirtualMachine, - builtins::{PyBytes, PyIntRef, PyModule, PyType, PyTypeRef}, - function::{ArgBytesLike, FuncArgs}, + builtins::{PyBytes, PyIntRef, PyModule, PyType}, + function::ArgBytesLike, types::Constructor, }; - macro_rules! blake_sig { - ($name:ident, $digest:literal) => { - #[derive(FromArgs)] - struct $name { - #[pyarg(any, default = b"")] - data: ArgBytesLike, - #[pyarg(named, default = $digest)] - digest_size: i64, - #[pyarg(named, default = b"")] - key: ArgBytesLike, - #[pyarg(named, default = b"")] - salt: ArgBytesLike, - #[pyarg(named, default = b"")] - person: ArgBytesLike, - #[pyarg(named, default = 1)] - fanout: i64, - #[pyarg(named, default = 1)] - depth: i64, - #[pyarg(named, default)] - leaf_size: i64, - #[pyarg(named, default)] - node_offset: i64, - #[pyarg(named, default)] - node_depth: i64, - #[pyarg(named, default)] - inner_size: i64, - #[pyarg(named, default)] - last_node: bool, - #[pyarg(named, default = true)] - usedforsecurity: bool, - #[pyarg(named, optional)] - string: Option, - } - - impl $name { - fn touch(self) { - let Self { - data, - digest_size, - key, - salt, - person, - fanout, - depth, - leaf_size, - node_offset, - node_depth, - inner_size, - last_node, - usedforsecurity, - string, - } = self; - let _ = ( - data, - digest_size, - key, - salt, - person, - fanout, - depth, - leaf_size, - node_offset, - node_depth, - inner_size, - last_node, - usedforsecurity, - string, - ); - } - } - }; - } - - blake_sig!(Blake2bSig, 64); - blake_sig!(Blake2sSig, 32); - #[pyattr(name = "_GIL_MINSIZE")] const GIL_MINSIZE: u16 = 2048; @@ -147,15 +73,6 @@ mod _blake2 { ctx.new_int(BLAKE2B_MAX_DIGEST_SIZE) } - #[pyslot] - fn slot_new(_cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let args: BlakeHashArgs = args.bind(vm)?; - Ok(Self { - inner: local_blake2b(args, vm)?, - } - .into_pyobject(vm)) - } - #[pygetset] fn name(zelf: &Py) -> &'static str { zelf.inner.name() @@ -202,20 +119,22 @@ mod _blake2 { } impl Constructor for PyBlake2b { - type Args = Blake2bSig; + type Args = Blake2bArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - args.touch(); - Err(vm.new_type_error("use slot_new")) + Ok(Self { + inner: local_blake2b(args, vm)?, + }) } } impl Constructor for PyBlake2s { - type Args = Blake2sSig; + type Args = Blake2sArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - args.touch(); - Err(vm.new_type_error("use slot_new")) + Ok(Self { + inner: local_blake2s(args, vm)?, + }) } } @@ -244,15 +163,6 @@ mod _blake2 { ctx.new_int(BLAKE2S_MAX_DIGEST_SIZE) } - #[pyslot] - fn slot_new(_cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let args: BlakeHashArgs = args.bind(vm)?; - Ok(Self { - inner: local_blake2s(args, vm)?, - } - .into_pyobject(vm)) - } - #[pygetset] fn name(zelf: &Py) -> &'static str { zelf.inner.name() diff --git a/crates/stdlib/src/bz2.rs b/crates/stdlib/src/bz2.rs index 9c3eae59407..67c66fd303d 100644 --- a/crates/stdlib/src/bz2.rs +++ b/crates/stdlib/src/bz2.rs @@ -9,7 +9,7 @@ mod _bz2 { Py, PyObject, VirtualMachine, builtins::{PyBaseExceptionRef, PyBytes, PyType}, common::lock::PyMutex, - function::ArgBytesLike, + function::{ArgBytesLike, ArgCInt}, object::{PyAtomicRef, PyResult}, types::Constructor, }; @@ -105,8 +105,8 @@ mod _bz2 { result.map_err(|error| map_bz2_error(error, vm)) } - #[pymethod(name = "__reduce__")] - fn reduce(_zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __reduce__(_zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { Err(vm.new_type_error("cannot pickle '_bz2.BZ2Decompressor' object")) } } @@ -127,7 +127,7 @@ mod _bz2 { #[derive(FromArgs)] struct BZ2CompressorArgs { #[pyarg(positional, default = 9)] - compresslevel: i32, + compresslevel: ArgCInt, } impl Constructor for BZ2Compressor { @@ -138,7 +138,7 @@ mod _bz2 { BZ2CompressorArgs { compresslevel }: Self::Args, vm: &VirtualMachine, ) -> PyResult { - let compressor = backend::Compressor::new(i64::from(compresslevel)) + let compressor = backend::Compressor::new(i64::from(compresslevel.into_primitive())) .ok_or_else(|| vm.new_value_error("compresslevel must be between 1 and 9"))?; Ok(Self { state: PyMutex::new(compressor), @@ -167,8 +167,8 @@ mod _bz2 { compressor.flush().map_err(|error| map_bz2_error(error, vm)) } - #[pymethod(name = "__reduce__")] - fn reduce(_zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn __reduce__(_zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { Err(vm.new_type_error("cannot pickle '_bz2.BZ2Compressor' object")) } } diff --git a/crates/stdlib/src/cjkcodecs.rs b/crates/stdlib/src/cjkcodecs.rs index 3edabe7faae..9ce837bd604 100644 --- a/crates/stdlib/src/cjkcodecs.rs +++ b/crates/stdlib/src/cjkcodecs.rs @@ -17,7 +17,7 @@ macro_rules! codecs_module { const CODECS: &[&'static str] = &[$($name),+]; - #[pyfunction] + #[pyfunction(signature_from_flags)] fn getcodec(object: PyObjectRef, vm: &VirtualMachine) -> PyResult { multibytecodec::get_codec(CODECS, &object, vm) } diff --git a/crates/stdlib/src/cjkcodecs/multibytecodec.rs b/crates/stdlib/src/cjkcodecs/multibytecodec.rs index ca1f85b0103..313f1335cf2 100644 --- a/crates/stdlib/src/cjkcodecs/multibytecodec.rs +++ b/crates/stdlib/src/cjkcodecs/multibytecodec.rs @@ -617,8 +617,8 @@ mod _multibytecodec { // `__create_codec`, which turns the capsule `getcodec` hands it into a // codec object. Nothing here carries a codec in a capsule, so the argument // check rejects everything a caller can pass. - #[pyfunction(name = "__create_codec")] - fn create_codec(_arg: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pyfunction] + fn __create_codec(_arg: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_value_error("argument type invalid")) } @@ -679,8 +679,8 @@ mod _multibytecodec { #[pyarg(any)] input: PyObjectRef, // Any object is accepted by truthiness. - #[pyarg(any, name = "final", default = false)] - final_input: PyObjectRef, + #[pyarg(any, default = false)] + r#final: PyObjectRef, } #[derive(FromArgs)] @@ -688,8 +688,8 @@ mod _multibytecodec { #[pyarg(any)] input: ArgBytesLike, // Any object is accepted by truthiness. - #[pyarg(any, name = "final", default = false)] - final_input: PyObjectRef, + #[pyarg(any, default = false)] + r#final: PyObjectRef, } /// The `bool(accept={int})` conversion the `final` arguments share, which @@ -753,7 +753,7 @@ mod _multibytecodec { args: IncrementalEncodeArgs, vm: &VirtualMachine, ) -> PyResult { - let final_input = final_arg(args.final_input, vm)?; + let final_input = final_arg(args.r#final, vm)?; // Driven on a detached copy: an error handler can re-enter this object. let mut local = zelf.inner.lock().clone(); let result = zelf @@ -884,7 +884,7 @@ mod _multibytecodec { args: IncrementalDecodeArgs, vm: &VirtualMachine, ) -> PyResult { - let final_input = final_arg(args.final_input, vm)?; + let final_input = final_arg(args.r#final, vm)?; // Driven on a detached copy: an error handler can re-enter this object. let mut local = zelf.inner.lock().clone(); let original_pending = core::mem::take(&mut local.pending); diff --git a/crates/stdlib/src/compression.rs b/crates/stdlib/src/compression.rs index d8f6d3001f1..59369fe4f32 100644 --- a/crates/stdlib/src/compression.rs +++ b/crates/stdlib/src/compression.rs @@ -1,22 +1,22 @@ //! internal shared module for compression libraries -use crate::vm::function::{ArgBytesLike, OptionalArg, PySsize}; +use crate::vm::function::{ArgBytesLike, PySsize}; #[derive(FromArgs)] pub(crate) struct DecompressArgs { #[pyarg(positional)] data: ArgBytesLike, // Omitted max_length is 0, which means unlimited for this call. - #[pyarg(any, optional, py_default = "0")] - max_length: OptionalArg, + #[pyarg(any, default = 0)] + max_length: PySsize, } impl DecompressArgs { pub(crate) fn data(&self) -> crate::common::borrow::BorrowedValue<'_, [u8]> { self.data.borrow_buf() } - pub(crate) fn raw_max_length(&self) -> Option { - self.max_length.into_option() + pub(crate) fn raw_max_length(&self) -> PySsize { + self.max_length } } @@ -25,8 +25,8 @@ pub(crate) struct DecompressorArgs { #[pyarg(any)] data: ArgBytesLike, // Missing max_length is unlimited, shown as -1. - #[pyarg(any, optional, py_default = "-1")] - max_length: OptionalArg, + #[pyarg(any, default = -1)] + max_length: PySsize, } impl DecompressorArgs { @@ -35,8 +35,6 @@ impl DecompressorArgs { } pub(crate) fn max_length(&self) -> Option { - self.max_length - .into_option() - .and_then(|value| usize::try_from(value).ok()) + usize::try_from(self.max_length).ok() } } diff --git a/crates/stdlib/src/contextvars.rs b/crates/stdlib/src/contextvars.rs index 3c8cf9fa169..59d5d14f251 100644 --- a/crates/stdlib/src/contextvars.rs +++ b/crates/stdlib/src/contextvars.rs @@ -7,7 +7,7 @@ mod _contextvars { AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, builtins::{PyGenericAlias, PyList, PyStr, PyStrRef, PyType, PyTypeRef}, - class::StaticType, + class::{PyClassImpl, StaticType}, class_or_notimplemented, common::{ hash::PyHash, @@ -21,7 +21,7 @@ mod _contextvars { Representable, }, }; - use core::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; + use core::sync::atomic::{AtomicBool, AtomicIsize, AtomicUsize, Ordering}; use indexmap::IndexMap; // TODO: Real hamt implementation @@ -44,8 +44,19 @@ mod _contextvars { } } + // Unlike an object address, a cache identity must not be reused after a + // context is destroyed. Zero disables cache hits if the counter is exhausted. + static CONTEXT_CACHE_ID: AtomicUsize = AtomicUsize::new(0); + + fn next_context_cache_id() -> usize { + CONTEXT_CACHE_ID + .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) + .map_or(0, |id| id + 1) + } + #[derive(Debug)] struct ContextInner { + cache_id: usize, idx: AtomicUsize, vars: PyRef, // PyObject *ctx_weakreflist; @@ -72,6 +83,7 @@ mod _contextvars { fn empty(vm: &VirtualMachine) -> Self { Self { inner: ContextInner { + cache_id: next_context_cache_id(), idx: AtomicUsize::new(usize::MAX), vars: HamtObject::default().into_ref(&vm.ctx), entered: AtomicBool::new(false), @@ -166,7 +178,10 @@ mod _contextvars { } } - #[pyclass(with(Constructor, AsMapping, AsSequence, Iterable, Comparable))] + #[pyclass( + with(Constructor, AsMapping, AsSequence, Iterable, Comparable), + flags(IMMUTABLETYPE) + )] impl PyContext { #[pymethod] fn run(zelf: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { @@ -192,6 +207,7 @@ mod _contextvars { }; Self { inner: ContextInner { + cache_id: next_context_cache_id(), idx: AtomicUsize::new(usize::MAX), vars: vars_copy.into_ref(&vm.ctx), entered: AtomicBool::new(false), @@ -356,9 +372,9 @@ mod _contextvars { #[pytraverse(skip)] cached: PyMutex>, #[pytraverse(skip)] - cached_id: AtomicUsize, // cached_tsid in CPython + cached_id: AtomicUsize, // non-reused Context cache identity #[pytraverse(skip)] - hash: AtomicI64, + hash: AtomicIsize, } impl core::fmt::Debug for ContextVar { @@ -413,10 +429,9 @@ mod _contextvars { idx: ctx.inner.idx.load(Ordering::Relaxed), }; let mut cached = zelf.cached.lock(); - zelf.cached_id.store(ctx.get_id(), Ordering::SeqCst); - let replaced = cached.replace(cache); + zelf.cached_id.store(ctx.inner.cache_id, Ordering::SeqCst); + let _replaced = cached.replace(cache); drop(cached); - drop(replaced); } fn generate_hash(zelf: &Py, name_hash: PyHash) -> PyHash { @@ -426,7 +441,7 @@ mod _contextvars { } } - #[pyclass(with(Constructor, Hashable, Representable))] + #[pyclass(with(Constructor, Hashable, Representable), flags(IMMUTABLETYPE))] impl ContextVar { #[pymethod] fn get( @@ -444,7 +459,8 @@ mod _contextvars { let ctx = ctx_obj.downcast_ref::().unwrap(); let mut cached = zelf.cached.lock(); if let Some(cached) = &*cached - && zelf.cached_id.load(Ordering::SeqCst) == ctx.get_id() + && ctx.inner.cache_id != 0 + && zelf.cached_id.load(Ordering::SeqCst) == ctx.inner.cache_id && cached.idx + 1 == ctxs.len() { return (Some(cached.object.clone()), None); @@ -452,7 +468,7 @@ mod _contextvars { let Some(obj) = ctx.borrow_vars().get(zelf).map(|obj| obj.to_owned()) else { return (None, None); }; - zelf.cached_id.store(ctx.get_id(), Ordering::SeqCst); + zelf.cached_id.store(ctx.inner.cache_id, Ordering::SeqCst); let replaced = cached.replace(ContextVarCache { object: obj.clone(), @@ -566,7 +582,7 @@ mod _contextvars { default, cached_id: 0.into(), cached: PyMutex::new(None), - hash: AtomicI64::new(0), + hash: AtomicIsize::new(0), }; let py_var = var.into_ref_with_type(vm, cls)?; let hash = Self::generate_hash(&py_var, name_hash); @@ -619,8 +635,13 @@ mod _contextvars { used: AtomicBool, } - #[pyclass(with(Constructor, Representable))] + #[pyclass(with(Constructor, Representable), flags(IMMUTABLETYPE))] impl ContextToken { + #[pyattr(name = "MISSING")] + fn missing(_ctx: &crate::vm::Context) -> PyObjectRef { + ContextTokenMissing::make_static_type().into() + } + #[pygetset] fn var(zelf: &Py, _vm: &VirtualMachine) -> PyRef { zelf.var.clone() @@ -706,17 +727,4 @@ mod _contextvars { fn copy_context(vm: &VirtualMachine) -> PyContext { PyContext::copy(&PyContext::current(vm), vm) } - - // Set Token.MISSING attribute - pub(crate) fn module_exec( - vm: &VirtualMachine, - module: &Py, - ) -> PyResult<()> { - __module_exec(vm, module); - - let token_type = module.get_attr("Token", vm)?; - token_type.set_attr("MISSING", ContextTokenMissing::static_type().to_owned(), vm)?; - - Ok(()) - } } diff --git a/crates/stdlib/src/csv.rs b/crates/stdlib/src/csv.rs index a0f75300eda..774f038bd92 100644 --- a/crates/stdlib/src/csv.rs +++ b/crates/stdlib/src/csv.rs @@ -6,16 +6,16 @@ mod _csv { use crate::vm::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyBaseExceptionRef, PyInt, PyNone, PyStr, PyType, PyTypeRef, PyUtf8StrRef}, - function::{ArgIterable, ArgumentError, FromArgs, FuncArgs, OptionalArg, Param}, + builtins::{PyBaseExceptionRef, PyInt, PyStr, PyStrRef, PyType, PyTypeRef}, + function::{ArgIterable, FuncArgs, KwArgs, OptionalArg}, protocol::{PyIter, PyIterReturn, PyNumber}, - types::{Callable, Constructor, IterNext, Iterable, SelfIter}, + types::{Constructor, IterNext, Iterable, SelfIter}, + vm::thread::PyOperation, }; use alloc::fmt; use itertools::Itertools; use parking_lot::Mutex; use rustpython_common::{lock::LazyLock, wtf8::Wtf8Buf}; - use rustpython_vm::match_class; use std::collections::HashMap; #[pyattr] @@ -48,7 +48,7 @@ mod _csv { ) } - static GLOBAL_HASHMAP: LazyLock>> = LazyLock::new(|| { + static GLOBAL_HASHMAP: LazyLock>> = LazyLock::new(|| { let m = HashMap::new(); Mutex::new(m) }); @@ -73,13 +73,17 @@ mod _csv { ) } + fn utf8_data<'a>(s: &'a PyStr, vm: &VirtualMachine) -> PyResult<&'a str> { + core::str::from_utf8(s.as_bytes()).map_err(|e| new_not_utf8_error(vm, s.as_bytes(), e)) + } + #[pyattr] #[pyclass(module = "_csv", name = "Dialect")] #[derive(Debug, PyPayload, Clone)] struct PyDialect { - delimiter: u8, - quotechar: Option, - escapechar: Option, + delimiter: char, + quotechar: Option, + escapechar: Option, doublequote: bool, skipinitialspace: bool, lineterminator: String, @@ -88,12 +92,10 @@ mod _csv { } impl Constructor for PyDialect { - type Args = PyObjectRef; + type Args = FormatOptions; - fn py_new(_cls: &Py, obj: Self::Args, vm: &VirtualMachine) -> PyResult { - let dialect = Self::try_from_object(vm, obj)?; - validate_dialect(vm, &dialect)?; - Ok(dialect) + fn py_new(_cls: &Py, opts: Self::Args, vm: &VirtualMachine) -> PyResult { + opts.result(vm) } } @@ -101,12 +103,12 @@ mod _csv { impl PyDialect { #[pygetset] fn delimiter(zelf: &Py, vm: &VirtualMachine) -> PyRef { - vm.ctx.new_str(format!("{}", zelf.delimiter as char)) + vm.ctx.new_str(zelf.delimiter) } #[pygetset] fn quotechar(zelf: &Py, vm: &VirtualMachine) -> Option> { - Some(vm.ctx.new_str(format!("{}", zelf.quotechar? as char))) + Some(vm.ctx.new_str(zelf.quotechar?)) } #[pygetset] @@ -131,105 +133,41 @@ mod _csv { #[pygetset] fn escapechar(zelf: &Py, vm: &VirtualMachine) -> Option> { - Some(vm.ctx.new_str(format!("{}", zelf.escapechar? as char))) + Some(vm.ctx.new_str(zelf.escapechar?)) } - #[pygetset(name = "strict")] - fn get_strict(zelf: &Py) -> bool { + #[pygetset] + fn strict(zelf: &Py) -> bool { zelf.strict } } - /// Parses the delimiter from a Python object and returns its ASCII value. - /// - /// This function attempts to extract the 'delimiter' attribute from the given Python object and ensures that the attribute is a single-character string. If successful, it returns the ASCII value of the character. If the attribute is not a single-character string, an error is returned. - /// - /// # Arguments - /// - /// * `vm` - A reference to the VirtualMachine, used for executing Python code and manipulating Python objects. - /// * `obj` - A reference to the PyObjectRef from which the 'delimiter' attribute is to be parsed. - /// - /// # Returns - /// - /// If successful, returns a `PyResult` representing the ASCII value of the 'delimiter' attribute. If unsuccessful, returns a `PyResult` containing an error message. - /// - /// # Errors - /// - /// This function can return the following errors: - /// - /// * If the 'delimiter' attribute is not a single-character string, a type error is returned. - /// * If the 'obj' is not of string type and does not have a 'delimiter' attribute, a type error is returned. - fn parse_delimiter_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult { - if let Ok(attr) = obj.get_attr("delimiter", vm) { - parse_delimiter_from_obj(vm, &attr) - } else { - match_class!(match obj.to_owned() { - s @ PyStr => { - parse_single_char(&s, |len| { - vm.new_type_error(format!( - r#""delimiter" must be a unicode character, not a string of length {len}"# - )) - }) - } - attr => { - Err(vm.new_type_error(format!( - r#""delimiter" must be a unicode character, not {}"#, - attr.class().name() - ))) - } - }) + fn parse_char( + vm: &VirtualMachine, + obj: &PyObject, + name: &str, + allow_none: bool, + ) -> PyResult> { + if allow_none && vm.is_none(obj) { + return Ok(None); } - } - - fn parse_quotechar_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult> { - match_class!(match obj.get_attr("quotechar", vm)? { - s @ PyStr => { - Ok(Some(parse_single_char(&s, |len| { - new_csv_error( - vm, - format!( - r#""quotechar" must be a unicode character or None, not a string of length {len}"# - ), - ) - })?)) - } - _n @ PyNone => { - Ok(None) - } - attr => { - Err(new_csv_error( - vm, - format!( - r#""quotechar" must be a unicode character or None, not {}"#, - attr.class().name() - ), - )) - } - }) - } - - fn parse_escapechar_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult> { - match_class!(match obj.get_attr("escapechar", vm)? { - s @ PyStr => { - Ok(Some(parse_single_char(&s, |len| { - new_csv_error( - vm, - format!( - r#""escapechar" must be a unicode character or None, not a string of length {len}"# - ), - ) - })?)) - } - _n @ PyNone => { - Ok(None) - } - attr => { - Err(vm.new_type_error(format!( - r#""escapechar" must be a unicode character or None, not {}"#, - attr.class().name() - ))) - } + let expected = if allow_none { + "a unicode character or None" + } else { + "a unicode character" + }; + let value = obj.downcast_ref::().ok_or_else(|| { + vm.new_type_error(format!( + r#""{name}" must be {expected}, not {}"#, + obj.class().name() + )) + })?; + parse_single_char(value, |len| { + vm.new_type_error(format!( + r#""{name}" must be {expected}, not a string of length {len}"# + )) }) + .map(Some) } fn parse_lineterminator<'a>(vm: &VirtualMachine, s: &'a Py) -> PyResult<&'a str> { @@ -237,80 +175,16 @@ mod _csv { .ok_or_else(|| new_csv_error(vm, r#""lineterminator" must be a string"#)) } - fn prase_lineterminator_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult { - match_class!(match obj.get_attr("lineterminator", vm)? { - s @ PyStr => { - // Store the full line terminator string. CPython accepts an - // arbitrary-length terminator; the manual writer paths emit it - // verbatim and the csv-core writer path appends it after a - // sentinel terminator (see `writerow`). - let value = parse_lineterminator(vm, &s)?; - Ok(value.to_owned()) - } - attr => { - Err(vm.new_type_error(format!( - r#""lineterminator" must be a string, not {}"#, - attr.class().name() - ))) - } - }) - } - fn parse_single_char( s: &Py, error: impl Fn(usize) -> PyBaseExceptionRef, - ) -> PyResult { + ) -> PyResult { let ch = s .as_wtf8() .code_points() .exactly_one() .map_err(|_| error(s.char_len()))?; - u8::try_from(ch.to_u32()).map_err(|_| error(s.char_len())) - } - - fn prase_quoting_from_obj(vm: &VirtualMachine, obj: &PyObject) -> PyResult { - match_class!(match obj.get_attr("quoting", vm)? { - i @ PyInt => { - Ok(i.try_to_primitive::(vm)? - .try_into() - .map_err(|_| vm.new_type_error(r#"bad "quoting" value"#))?) - } - attr => { - Err(vm.new_type_error(format!( - r#""quoting" must be string or None, not {}"#, - attr.class().name() - ))) - } - }) - } - - impl TryFromObject for PyDialect { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - let delimiter = parse_delimiter_from_obj(vm, &obj)?; - let quotechar = parse_quotechar_from_obj(vm, &obj)?; - let escapechar = parse_escapechar_from_obj(vm, &obj)?; - let doublequote = obj.get_attr("doublequote", vm)?.try_to_bool(vm)?; - let skipinitialspace = obj.get_attr("skipinitialspace", vm)?.try_to_bool(vm)?; - let lineterminator = prase_lineterminator_from_obj(vm, &obj)?; - let quoting = prase_quoting_from_obj(vm, &obj)?; - - let strict = if let Ok(t) = obj.get_attr("strict", vm) { - t.try_to_bool(vm).unwrap_or(false) - } else { - false - }; - - Ok(Self { - delimiter, - quotechar, - escapechar, - doublequote, - skipinitialspace, - lineterminator, - quoting, - strict, - }) - } + ch.to_char().ok_or_else(|| error(s.char_len())) } #[derive(FromArgs)] @@ -319,59 +193,46 @@ mod _csv { name: PyObjectRef, } - #[pyfunction] - fn register_dialect( - name: PyObjectRef, - opts: FormatOptions, - vm: &VirtualMachine, - ) -> PyResult<()> { + #[pyfunction(text_signature = "($module, name, /, dialect='excel', **fmtparams)")] + fn register_dialect(name: PyObjectRef, opts: DialectArg, vm: &VirtualMachine) -> PyResult<()> { let name = name .downcast::() - .map_err(|_| vm.new_type_error("argument 0 must be a string"))?; - - let name: PyUtf8StrRef = name.try_into_utf8(vm)?; + .map_err(|_| vm.new_type_error("dialect name must be a string"))?; let dialect = opts.result(vm)?; validate_dialect(vm, &dialect)?; + name.as_object().hash(vm)?; GLOBAL_HASHMAP .lock() - .insert(name.as_str().to_owned(), dialect); + .insert(name.as_wtf8().to_owned(), dialect); Ok(()) } + // Hash the name as the dict lookup would; only str names are registered. + fn registry_key(name: PyObjectRef, vm: &VirtualMachine) -> PyResult { + name.hash(vm)?; + name.downcast::() + .map_err(|_| new_csv_error(vm, "unknown dialect")) + } + #[pyfunction] fn get_dialect(DialectName { name }: DialectName, vm: &VirtualMachine) -> PyResult { - let name = name.downcast::().map_err(|obj| { - new_csv_error( - vm, - format!("argument 0 must be a string, not '{}'", obj.class().name()), - ) - })?; - - let name: PyUtf8StrRef = name.try_into_utf8(vm)?; - let g = GLOBAL_HASHMAP.lock(); - - if let Some(dialect) = g.get(name.as_str()) { - return Ok(dialect.clone()); - } - - Err(new_csv_error(vm, "unknown dialect")) + let name = registry_key(name, vm)?; + let dialect = GLOBAL_HASHMAP.lock().get(name.as_wtf8()).cloned(); + dialect.ok_or_else(|| new_csv_error(vm, "unknown dialect")) } #[pyfunction] fn unregister_dialect(DialectName { name }: DialectName, vm: &VirtualMachine) -> PyResult<()> { - let name = name.downcast::().map_err(|obj| { - new_csv_error( - vm, - format!("argument 0 must be a string, not '{}'", obj.class().name()), - ) - })?; - - let name: PyUtf8StrRef = name.try_into_utf8(vm)?; - let mut g = GLOBAL_HASHMAP.lock(); + // PyDict_Pop misses on an empty dict without hashing the key. + if GLOBAL_HASHMAP.lock().is_empty() { + return Err(new_csv_error(vm, "unknown dialect")); + } + let name = registry_key(name, vm)?; + let removed = GLOBAL_HASHMAP.lock().remove(name.as_wtf8()); - if let Some(_removed) = g.remove(name.as_str()) { + if removed.is_some() { return Ok(()); } @@ -380,10 +241,9 @@ mod _csv { #[pyfunction] fn list_dialects(vm: &VirtualMachine) -> rustpython_vm::builtins::PyListRef { - let g = GLOBAL_HASHMAP.lock(); - let t = g - .keys() - .cloned() + let names = GLOBAL_HASHMAP.lock().keys().cloned().collect_vec(); + let t = names + .into_iter() .map(|x| vm.ctx.new_str(x).into()) .collect_vec(); // .iter().map(|x| vm.ctx.new_str(x.clone()).into_pyobject(vm)).collect_vec(); @@ -398,39 +258,39 @@ mod _csv { #[pyfunction] fn field_size_limit(args: FieldSizeLimitArgs, vm: &VirtualMachine) -> PyResult { - let old_size = GLOBAL_FIELD_LIMIT.lock().to_owned(); if let OptionalArg::Present(limit) = args.new_limit { - let Ok(new_size) = limit.try_int(vm) else { - return Err(vm.new_type_error("limit must be an integer")); - }; - *GLOBAL_FIELD_LIMIT.lock() = new_size.try_to_primitive::(vm)?; + let new_size = limit + .downcast_ref_if_exact::(vm) + .ok_or_else(|| vm.new_type_error("limit must be an integer"))? + .try_to_primitive::(vm)?; + Ok(core::mem::replace( + &mut *GLOBAL_FIELD_LIMIT.lock(), + new_size, + )) + } else { + Ok(*GLOBAL_FIELD_LIMIT.lock()) } - Ok(old_size) } - #[pyfunction] - fn reader(iterable: PyIter, options: FormatOptions, vm: &VirtualMachine) -> PyResult { + #[pyfunction(text_signature = "($module, iterable, /, dialect='excel', **fmtparams)")] + fn reader(iterable: PyIter, options: DialectArg, vm: &VirtualMachine) -> PyResult { let dialect = options.result(vm)?; Ok(Reader { iter: iterable, + operation: PyOperation::new(vm), state: PyMutex::new(ReadState { line_num: 0, - generation: 0, + parser: CsvParser::new(*GLOBAL_FIELD_LIMIT.lock()), }), dialect, }) } - #[pyfunction] - fn writer( - fileobj: PyObjectRef, - options: FormatOptions, - vm: &VirtualMachine, - ) -> PyResult { + #[pyfunction(text_signature = "($module, fileobj, /, dialect='excel', **fmtparams)")] + fn writer(fileobj: PyObjectRef, options: DialectArg, vm: &VirtualMachine) -> PyResult { let write = match vm.get_attribute_opt(&fileobj, "write")? { - Some(write_meth) => write_meth, - None if fileobj.is_callable() => fileobj, - None => { + Some(write) if write.is_callable() => write, + _ => { return Err(vm.new_type_error(r#"argument 1 must have a "write" method"#)); } }; @@ -438,7 +298,7 @@ mod _csv { Ok(Writer { write, - state: PyMutex::new(()), + operation: PyOperation::new(vm), dialect, }) } @@ -492,316 +352,194 @@ mod _csv { } } - #[derive(Default)] - enum DialectItem { - Str(String), - Obj(PyDialect), - #[default] - None, + #[derive(FromArgs)] + struct DialectArg { + #[pyarg(positional, optional)] + dialect: OptionalArg, + #[pyarg(flatten)] + fmtparams: KwArgs, } - #[derive(Default)] - struct FormatOptions { - dialect: DialectItem, - delimiter: Option, - quotechar: Option>, - escapechar: Option>, - doublequote: Option, - skipinitialspace: Option, - lineterminator: Option, - quoting: Option, - strict: Option, + impl DialectArg { + fn result(self, vm: &VirtualMachine) -> PyResult { + // Reader, writer and registration accept only one positional dialect. + // Its format parameters are bound by Dialect after their own inputs. + FuncArgs::new( + self.dialect.into_option().into_iter().collect::>(), + self.fmtparams, + ) + .bind::(vm)? + .result(vm) + } } - /// prase a dialect item from a Python argument and returns a `DialectItem` or an `ArgumentError`. - /// - /// This function takes a reference to the VirtualMachine and a PyObjectRef as input and attempts to parse a dialect item from the provided Python argument. It returns a `DialectItem` if successful, or an `ArgumentError` if unsuccessful. - /// - /// # Arguments - /// - /// * `vm` - A reference to the VirtualMachine, used for executing Python code and manipulating Python objects. - /// * `obj` - The PyObjectRef from which the dialect item is to be parsed. - /// - /// # Returns - /// - /// If successful, returns a `Result` representing the parsed dialect item. If unsuccessful, returns an `ArgumentError`. - /// - /// # Errors - /// - /// This function can return the following errors: - /// - /// * If the provided object is a PyStr, it returns a `DialectItem::Str` containing the string value. - /// * If the provided object is PyNone, it returns an `ArgumentError` with the message "InvalidKeywordArgument('dialect')". - /// * If the provided object is a PyType, it attempts to create a PyDialect from the object and returns a `DialectItem::Obj` containing the PyDialect if successful. If unsuccessful, it returns an `ArgumentError` with the message "InvalidKeywordArgument('dialect')". - /// * If the provided object is none of the above types, it attempts to create a PyDialect from the object and returns a `DialectItem::Obj` containing the PyDialect if successful. If unsuccessful, it returns an `ArgumentError` with the message "InvalidKeywordArgument('dialect')". - fn prase_dialect_item_from_arg( - vm: &VirtualMachine, - obj: PyObjectRef, - ) -> Result { - match_class!(match obj { - s @ PyStr => { - let s = s.try_into_utf8(vm).map_err(ArgumentError::Exception)?; - Ok(DialectItem::Str(s.as_str().to_owned())) - } - PyNone => { - Err(ArgumentError::InvalidKeywordArgument("dialect".to_string())) - } - t @ PyType => { - let temp = t - .as_object() - .call(vec![], vm) - .map_err(|_e| ArgumentError::InvalidKeywordArgument("dialect".to_string()))?; - Ok(DialectItem::Obj( - PyDialect::try_from_object(vm, temp).map_err(|_| { - ArgumentError::InvalidKeywordArgument("dialect".to_string()) - })?, - )) - } - obj => { - if let Ok(cur_dialect_item) = PyDialect::try_from_object(vm, obj) { - Ok(DialectItem::Obj(cur_dialect_item)) - } else { - Err(ArgumentError::InvalidKeywordArgument("dialect".to_string())) - } - } - }) + #[derive(FromArgs)] + struct FormatOptions { + #[pyarg(any, optional)] + dialect: OptionalArg, + #[pyarg(any, optional)] + delimiter: OptionalArg, + #[pyarg(any, optional)] + doublequote: OptionalArg, + #[pyarg(any, optional)] + escapechar: OptionalArg, + #[pyarg(any, optional)] + lineterminator: OptionalArg, + #[pyarg(any, optional)] + quotechar: OptionalArg, + #[pyarg(any, optional)] + quoting: OptionalArg, + #[pyarg(any, optional)] + skipinitialspace: OptionalArg, + #[pyarg(any, optional)] + strict: OptionalArg, } - impl FromArgs for FormatOptions { - const PARAMS: Option<&'static [Param]> = Some(&[ - Param { - name: "dialect", - kind: rustpython_vm::function::ParamKind::PositionalOrKeyword, - default: Some(rustpython_vm::function::DefaultRepr::Str("excel")), - }, - Param::var_keyword("fmtparams"), - ]); - - fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { - let dialect = if let Some(dialect) = args.take_positional_keyword("dialect") { - prase_dialect_item_from_arg(vm, dialect)? - } else { - DialectItem::None - }; - - let mut res = Self { - dialect, - ..Default::default() - }; - - if let Some(delimiter) = args.kwargs.swap_remove("delimiter") { - res.delimiter = Some(parse_delimiter_from_obj(vm, &delimiter)?); - } - - if let Some(escapechar) = args.kwargs.swap_remove("escapechar") { - res.escapechar = match_class!(match escapechar { - s @ PyStr => Some(Some(parse_single_char(&s, |_| { - vm.new_type_error(r#""escapechar" must be a 1-character string"#) - })?)), - PyNone => Some(None), - _ => { - return Err(ArgumentError::Exception( - vm.new_type_error(r#""escapechar" must be a 1-character string"#), - )); - } - }) - }; - - if let Some(lineterminator) = args.kwargs.swap_remove("lineterminator") { - let s = lineterminator.downcast_ref::().ok_or_else(|| { - vm.new_type_error(format!( - r#""lineterminator" must be a string, not {}"#, - lineterminator.class().name() - )) - })?; - let value = parse_lineterminator(vm, s)?; - res.lineterminator = Some(value.to_owned()); - }; - - if let Some(doublequote) = args.kwargs.swap_remove("doublequote") { - res.doublequote = Some( - doublequote - .try_to_bool(vm) - .map_err(|_| vm.new_type_error(r#""doublequote" must be a bool"#))?, - ) - }; - - if let Some(skipinitialspace) = args.kwargs.swap_remove("skipinitialspace") { - res.skipinitialspace = Some( - skipinitialspace - .try_to_bool(vm) - .map_err(|_| vm.new_type_error(r#""skipinitialspace" must be a bool"#))?, - ) - }; - - if let Some(quoting) = args.kwargs.swap_remove("quoting") { - res.quoting = match_class!(match quoting { - i @ PyInt => - Some(i.try_to_primitive::(vm)?.try_into().map_err(|_e| { - ArgumentError::InvalidKeywordArgument("quoting".to_string()) - })?), - _ => { - // let msg = r#""quoting" must be a int enum"#; - return Err(ArgumentError::InvalidKeywordArgument("quoting".to_string())); - } - }); - }; - - if let Some(quotechar) = args.kwargs.swap_remove("quotechar") { - res.quotechar = match_class!(match quotechar { - s @ PyStr => Some(Some(parse_single_char(&s, |_| { - vm.new_type_error(r#""quotechar" must be a 1-character string"#) - })?)), - PyNone => { - if res - .quoting - .is_some_and(|quoting| quoting != QuoteStyle::None) - { - return Err(ArgumentError::Exception( - vm.new_type_error("quotechar must be set if quoting enabled"), - )); - } - Some(None) - } - _o => { - return Err( - rustpython_vm::function::ArgumentError::InvalidKeywordArgument( - "quotechar".to_string(), - ), - ); - } - }) - }; - - if let Some(strict) = args.kwargs.swap_remove("strict") { - res.strict = Some( - strict - .try_to_bool(vm) - .map_err(|_| vm.new_type_error(r#""strict" must be a int enum"#))?, - ) + fn validate_dialect(vm: &VirtualMachine, dialect: &PyDialect) -> PyResult<()> { + let check_char = |name: &str, value: Option, allow_space: bool| { + let Some(value) = value else { + return Ok(()); }; - - if let Some(last_arg) = args.kwargs.pop() { - // The dialect is parsed by a parser of its own, which has no - // name to give the message. - return Err(ArgumentError::Exception( - vm.new_unexpected_keyword_type_error(None, &last_arg.0.to_string()), - )); + if matches!(value, '\r' | '\n') || (value == ' ' && !allow_space) { + return Err(vm.new_value_error(format!("bad {name} value"))); } - - Ok(res) - } - } - - fn validate_dialect(vm: &VirtualMachine, dialect: &PyDialect) -> PyResult<()> { - let special = |name: &str, value: u8| { - if matches!(value, b'\r' | b'\n') { - Err(vm.new_value_error(format!( - "{name} must be a single character, not a line break" - ))) - } else { - Ok(()) + if dialect.lineterminator.contains(value) { + return Err(vm.new_value_error(format!("bad {name} or lineterminator value"))); } + Ok(()) }; - special("delimiter", dialect.delimiter)?; - if let Some(quotechar) = dialect.quotechar { - special("quotechar", quotechar)?; - } - if let Some(escapechar) = dialect.escapechar { - special("escapechar", escapechar)?; - } + check_char("delimiter", Some(dialect.delimiter), true)?; + check_char("escapechar", dialect.escapechar, !dialect.skipinitialspace)?; + check_char("quotechar", dialect.quotechar, !dialect.skipinitialspace)?; - if dialect.skipinitialspace - && (matches!(dialect.escapechar, Some(b' ')) || matches!(dialect.quotechar, Some(b' '))) - { - return Err(vm.new_value_error( - "escapechar or quotechar cannot be a space when skipinitialspace is enabled", - )); - } - - let values: [(&str, Option); 3] = [ + let values = [ ("delimiter", Some(dialect.delimiter)), - ("quotechar", dialect.quotechar), ("escapechar", dialect.escapechar), + ("quotechar", dialect.quotechar), ]; for (index, (left_name, left)) in values.iter().enumerate() { for (right_name, right) in values.iter().skip(index + 1) { if left.is_some() && left == right { - return Err(vm.new_value_error(format!( - "{left_name} and {right_name} cannot be the same" - ))); + return Err( + vm.new_value_error(format!("bad {left_name} or {right_name} value")) + ); } } - if left.is_some_and(|value| { - dialect - .lineterminator - .chars() - .any(|character| character == value as char) - }) { - return Err(vm.new_value_error(format!( - "{left_name} and lineterminator cannot be the same" - ))); - } } Ok(()) } impl FormatOptions { - fn update_py_dialect(&self, mut res: PyDialect) -> PyDialect { - macro_rules! check_and_fill { - ($res:ident, $e:ident) => {{ - if let Some(t) = self.$e { - $res.$e = t; - } - }}; + fn result(mut self, vm: &VirtualMachine) -> PyResult { + if let OptionalArg::Present(obj) = + core::mem::replace(&mut self.dialect, OptionalArg::Missing) + { + let obj = if obj.downcast_ref::().is_some() { + get_dialect(DialectName { name: obj }, vm)? + .into_ref(&vm.ctx) + .into() + } else { + obj + }; + // Read all non-overridden attributes before converting their values. + macro_rules! fill_from_dialect { + ($($name:ident),* $(,)?) => { + $(if self.$name.is_missing() { + self.$name = vm.get_attribute_opt(&obj, stringify!($name))? + .map_or(OptionalArg::Missing, OptionalArg::Present); + })* + }; + } + fill_from_dialect!( + delimiter, + doublequote, + escapechar, + lineterminator, + quotechar, + quoting, + skipinitialspace, + strict, + ); + self.dialect = OptionalArg::Present(obj); } - check_and_fill!(res, delimiter); - // check_and_fill!(res, quotechar); - check_and_fill!(res, delimiter); - check_and_fill!(res, doublequote); - check_and_fill!(res, skipinitialspace); - - if let Some(t) = self.escapechar { - res.escapechar = t; + let delimiter = match &self.delimiter { + OptionalArg::Present(obj) => parse_char(vm, obj, "delimiter", false)?.unwrap(), + OptionalArg::Missing => ',', }; - - if let Some(t) = self.quotechar { - res.quotechar = t; + let doublequote = match &self.doublequote { + OptionalArg::Present(obj) => obj.try_to_bool(vm)?, + OptionalArg::Missing => true, }; - - check_and_fill!(res, quoting); - if let Some(t) = &self.lineterminator { - res.lineterminator.clone_from(t); + let escapechar = match &self.escapechar { + OptionalArg::Present(obj) => parse_char(vm, obj, "escapechar", true)?, + OptionalArg::Missing => None, }; - check_and_fill!(res, strict); - res - } - - fn result(&self, vm: &VirtualMachine) -> PyResult { - let dialect = match &self.dialect { - DialectItem::Str(name) => { - let g = GLOBAL_HASHMAP.lock(); - if let Some(dialect) = g.get(name) { - Ok(self.update_py_dialect(dialect.clone())) - } else { - Err(new_csv_error(vm, format!("{name} is not registered."))) + let lineterminator = match &self.lineterminator { + OptionalArg::Present(obj) => { + let value = obj.downcast_ref::().ok_or_else(|| { + vm.new_type_error(format!( + r#""lineterminator" must be a string, not {}"#, + obj.class().name() + )) + })?; + // Store the full line terminator string. CPython accepts an + // arbitrary-length terminator; the manual writer paths emit it + // verbatim and the csv-core writer path appends it after a + // sentinel terminator (see `writerow`). + parse_lineterminator(vm, value)?.to_owned() + } + OptionalArg::Missing => "\r\n".to_owned(), + }; + let quotechar = match &self.quotechar { + OptionalArg::Present(obj) => parse_char(vm, obj, "quotechar", true)?, + OptionalArg::Missing => Some('"'), + }; + let quoting = match &self.quoting { + OptionalArg::Present(obj) => { + if !obj.class().is(vm.ctx.types.int_type) { + return Err(vm.new_type_error(format!( + r#""quoting" must be an integer, not {}"#, + obj.class().name() + ))); } - // TODO: Maybe need to update the obj from HashMap + obj.downcast_ref::() + .unwrap() + .try_to_primitive::(vm)? } - DialectItem::Obj(o) => Ok(self.update_py_dialect(o.clone())), - DialectItem::None => Ok(self.update_py_dialect(PyDialect { - delimiter: b',', - quotechar: Some(b'"'), - escapechar: None, - doublequote: true, - skipinitialspace: false, - lineterminator: "\r\n".to_owned(), - quoting: QuoteStyle::Minimal, - strict: false, - })), - }?; + OptionalArg::Missing => QuoteStyle::Minimal as i32, + }; + let skipinitialspace = match &self.skipinitialspace { + OptionalArg::Present(obj) => obj.try_to_bool(vm)?, + OptionalArg::Missing => false, + }; + let strict = match &self.strict { + OptionalArg::Present(obj) => obj.try_to_bool(vm)?, + OptionalArg::Missing => false, + }; + + // Validate the quoting value only after all field conversions. + let quoting = QuoteStyle::try_from(quoting as isize) + .map_err(|_| vm.new_type_error(r#"bad "quoting" value"#))?; + let quoting = if quotechar.is_none() && self.quoting.is_missing() { + QuoteStyle::None + } else { + quoting + }; + if quotechar.is_none() && quoting != QuoteStyle::None { + return Err(vm.new_type_error("quotechar must be set if quoting enabled")); + } + let dialect = PyDialect { + delimiter, + quotechar, + escapechar, + doublequote, + skipinitialspace, + lineterminator, + quoting, + strict, + }; validate_dialect(vm, &dialect)?; Ok(dialect) } @@ -809,7 +547,7 @@ mod _csv { struct ReadState { line_num: u64, - generation: u64, + parser: CsvParser, } #[pyclass(no_attr, module = "_csv", name = "reader", traverse)] @@ -817,6 +555,9 @@ mod _csv { pub(super) struct Reader { iter: PyIter, #[pytraverse(skip)] + operation: PyOperation, + // The shared parser owns only native data, never Python references. + #[pytraverse(skip)] state: PyMutex, #[pytraverse(skip)] dialect: PyDialect, @@ -858,16 +599,66 @@ mod _csv { #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum ParserInput { - Byte(u8), + Char(char), Eol, } const EOL: ParserInput = ParserInput::Eol; + enum ParsedField { + String(String), + Float(f64), + None, + } + + impl ParsedField { + fn into_object(self, vm: &VirtualMachine) -> PyObjectRef { + match self { + Self::String(value) => vm.ctx.new_str(value).into(), + Self::Float(value) => vm.ctx.new_float(value).into(), + Self::None => vm.ctx.none(), + } + } + } + + enum ReadError { + Csv(String), + Float(String), + Utf8(Vec, core::str::Utf8Error), + } + + impl ReadError { + fn advanced() -> Self { + Self::Csv("iterator has already advanced the reader".to_owned()) + } + + // Exception construction can allocate or invoke Python: never call + // this while borrowing the shared parser. + fn into_exception(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + match self { + Self::Csv(message) => new_csv_error(vm, message), + Self::Float(field) => { + let field = vm.ctx.new_str(field); + crate::vm::builtins::invalid_float_literal_error(field.as_object(), vm) + } + Self::Utf8(bytes, error) => new_not_utf8_error(vm, &bytes, error), + } + } + } + + fn row_result(fields: Vec, vm: &VirtualMachine) -> PyIterReturn { + let fields = fields + .into_iter() + .map(|field| field.into_object(vm)) + .collect(); + PyIterReturn::Return(vm.ctx.new_list(fields).into()) + } + struct CsvParser { state: ParserState, - fields: Vec, - field: Vec, + fields: Option>, + field: String, + field_len: usize, unquoted_field: bool, field_limit: isize, } @@ -876,49 +667,50 @@ mod _csv { fn new(field_limit: isize) -> Self { Self { state: ParserState::StartRecord, - fields: Vec::new(), - field: Vec::new(), + fields: Some(Vec::new()), + field: String::new(), + field_len: 0, unquoted_field: false, field_limit, } } - fn into_result(self, vm: &VirtualMachine) -> PyIterReturn { - PyIterReturn::Return(vm.ctx.new_list(self.fields).into()) - } - - fn add_byte(&mut self, byte: u8, vm: &VirtualMachine) -> PyResult<()> { - if self.field_limit < 0 || self.field.len() >= self.field_limit as usize { - return Err(new_csv_error( - vm, - format!("field larger than field limit ({})", self.field_limit), - )); + fn add_char(&mut self, ch: char) -> Result<(), ReadError> { + if self.field_limit < 0 || self.field_len >= self.field_limit as usize { + return Err(ReadError::Csv(format!( + "field larger than field limit ({})", + self.field_limit + ))); } - self.field.push(byte); + self.field.push(ch); + self.field_len += 1; Ok(()) } - fn save_field(&mut self, quoting: QuoteStyle, vm: &VirtualMachine) -> PyResult<()> { + fn save_field(&mut self, quoting: QuoteStyle) -> Result<(), ReadError> { let field = if self.unquoted_field && self.field.is_empty() && matches!(quoting, QuoteStyle::Notnull | QuoteStyle::Strings) { - vm.ctx.none() + ParsedField::None + } else if self.unquoted_field + && !self.field.is_empty() + && matches!(quoting, QuoteStyle::Nonnumeric | QuoteStyle::Strings) + { + let normalized = + crate::common::str::transform_decimal_and_space_to_ascii(self.field.trim()); + let value = crate::vm::literal::float::parse_bytes(normalized.as_bytes()) + .ok_or_else(|| ReadError::Float(self.field.clone()))?; + ParsedField::Float(value) } else { - let value = core::str::from_utf8(&self.field) - .map_err(|e| new_not_utf8_error(vm, &self.field, e))?; - let field: PyObjectRef = vm.ctx.new_str(value).into(); - if self.unquoted_field - && !self.field.is_empty() - && matches!(quoting, QuoteStyle::Nonnumeric | QuoteStyle::Strings) - { - PyType::call(vm.ctx.types.float_type, vec![field].into(), vm)? - } else { - field - } + ParsedField::String(self.field.clone()) }; - self.fields.push(field); + self.fields + .as_mut() + .ok_or_else(ReadError::advanced)? + .push(field); self.field.clear(); + self.field_len = 0; Ok(()) } @@ -926,86 +718,84 @@ mod _csv { &mut self, input: ParserInput, dialect: &PyDialect, - vm: &VirtualMachine, - ) -> PyResult<()> { + ) -> Result<(), ReadError> { match self.state { ParserState::StartRecord => match input { ParserInput::Eol => {} - ParserInput::Byte(b'\r' | b'\n') => self.state = ParserState::EatCrnl, + ParserInput::Char('\r' | '\n') => self.state = ParserState::EatCrnl, _ => { self.state = ParserState::StartField; - return self.process_parser_input(input, dialect, vm); + return self.process_parser_input(input, dialect); } }, ParserState::StartField => { self.unquoted_field = true; match input { - ParserInput::Eol | ParserInput::Byte(b'\r' | b'\n') => { - self.save_field(dialect.quoting, vm)?; + ParserInput::Eol | ParserInput::Char('\r' | '\n') => { + self.save_field(dialect.quoting)?; self.state = state_after_record_end(input); } - ParserInput::Byte(byte) + ParserInput::Char(ch) if dialect.quoting != QuoteStyle::None - && dialect.quotechar == Some(byte) => + && dialect.quotechar == Some(ch) => { self.unquoted_field = false; self.state = ParserState::InQuotedField; } - ParserInput::Byte(byte) if dialect.escapechar == Some(byte) => { + ParserInput::Char(ch) if dialect.escapechar == Some(ch) => { self.state = ParserState::EscapedChar; } - ParserInput::Byte(b' ') if dialect.skipinitialspace => {} - ParserInput::Byte(byte) if byte == dialect.delimiter => { - self.save_field(dialect.quoting, vm)?; + ParserInput::Char(' ') if dialect.skipinitialspace => {} + ParserInput::Char(ch) if ch == dialect.delimiter => { + self.save_field(dialect.quoting)?; } - ParserInput::Byte(byte) => { - self.add_byte(byte, vm)?; + ParserInput::Char(ch) => { + self.add_char(ch)?; self.state = ParserState::InField; } } } ParserState::EscapedChar => match input { - ParserInput::Byte(byte @ (b'\r' | b'\n')) => { - self.add_byte(byte, vm)?; + ParserInput::Char(ch @ ('\r' | '\n')) => { + self.add_char(ch)?; self.state = ParserState::AfterEscapedCrnl; } ParserInput::Eol => { - self.add_byte(b'\n', vm)?; + self.add_char('\n')?; self.state = ParserState::InField; } - ParserInput::Byte(byte) => { - self.add_byte(byte, vm)?; + ParserInput::Char(ch) => { + self.add_char(ch)?; self.state = ParserState::InField; } }, ParserState::AfterEscapedCrnl => { if input != ParserInput::Eol { self.state = ParserState::InField; - return self.process_parser_input(input, dialect, vm); + return self.process_parser_input(input, dialect); } } ParserState::InField => match input { - ParserInput::Eol | ParserInput::Byte(b'\r' | b'\n') => { - self.save_field(dialect.quoting, vm)?; + ParserInput::Eol | ParserInput::Char('\r' | '\n') => { + self.save_field(dialect.quoting)?; self.state = state_after_record_end(input); } - ParserInput::Byte(byte) if dialect.escapechar == Some(byte) => { + ParserInput::Char(ch) if dialect.escapechar == Some(ch) => { self.state = ParserState::EscapedChar; } - ParserInput::Byte(byte) if byte == dialect.delimiter => { - self.save_field(dialect.quoting, vm)?; + ParserInput::Char(ch) if ch == dialect.delimiter => { + self.save_field(dialect.quoting)?; self.state = ParserState::StartField; } - ParserInput::Byte(byte) => self.add_byte(byte, vm)?, + ParserInput::Char(ch) => self.add_char(ch)?, }, ParserState::InQuotedField => match input { ParserInput::Eol => {} - ParserInput::Byte(byte) if dialect.escapechar == Some(byte) => { + ParserInput::Char(ch) if dialect.escapechar == Some(ch) => { self.state = ParserState::EscapeInQuotedField; } - ParserInput::Byte(byte) - if dialect.quoting != QuoteStyle::None - && dialect.quotechar == Some(byte) => + ParserInput::Char(ch) + if dialect.quoting != QuoteStyle::None && dialect.quotechar == Some(ch) => { self.state = if dialect.doublequote { ParserState::QuoteInQuotedField @@ -1013,57 +803,53 @@ mod _csv { ParserState::InField }; } - ParserInput::Byte(byte) => self.add_byte(byte, vm)?, + ParserInput::Char(ch) => self.add_char(ch)?, }, ParserState::EscapeInQuotedField => { - let byte = match input { - ParserInput::Eol => b'\n', - ParserInput::Byte(byte) => byte, + let ch = match input { + ParserInput::Eol => '\n', + ParserInput::Char(ch) => ch, }; - self.add_byte(byte, vm)?; + self.add_char(ch)?; self.state = ParserState::InQuotedField; } ParserState::QuoteInQuotedField => match input { - ParserInput::Byte(byte) - if dialect.quoting != QuoteStyle::None - && dialect.quotechar == Some(byte) => + ParserInput::Char(ch) + if dialect.quoting != QuoteStyle::None && dialect.quotechar == Some(ch) => { - self.add_byte(byte, vm)?; + self.add_char(ch)?; self.state = ParserState::InQuotedField; } - ParserInput::Byte(byte) if byte == dialect.delimiter => { - self.save_field(dialect.quoting, vm)?; + ParserInput::Char(ch) if ch == dialect.delimiter => { + self.save_field(dialect.quoting)?; self.state = ParserState::StartField; } - ParserInput::Eol | ParserInput::Byte(b'\r' | b'\n') => { - self.save_field(dialect.quoting, vm)?; + ParserInput::Eol | ParserInput::Char('\r' | '\n') => { + self.save_field(dialect.quoting)?; self.state = state_after_record_end(input); } - ParserInput::Byte(byte) if !dialect.strict => { - self.add_byte(byte, vm)?; + ParserInput::Char(ch) if !dialect.strict => { + self.add_char(ch)?; self.state = ParserState::InField; } - ParserInput::Byte(_) => { - return Err(new_csv_error( - vm, - format!( - "'{}' expected after '{}'", - dialect.delimiter as char, - dialect.quotechar.unwrap_or_default() as char, - ), - )); + ParserInput::Char(_) => { + return Err(ReadError::Csv(format!( + "'{}' expected after '{}'", + dialect.delimiter, + dialect.quotechar.unwrap_or_default(), + ))); } }, ParserState::EatCrnl => match input { - ParserInput::Byte(b'\r' | b'\n') => {} + ParserInput::Char('\r' | '\n') => {} ParserInput::Eol => self.state = ParserState::StartRecord, - ParserInput::Byte(_) => { - return Err(new_csv_error( - vm, + ParserInput::Char(_) => { + return Err(ReadError::Csv( concat!( "new-line character seen in unquoted field - ", "do you need to open the file with newline=''?" - ), + ) + .to_owned(), )); } }, @@ -1080,81 +866,110 @@ mod _csv { } } - fn next_input_item(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let generation = zelf.state.lock().generation; - // Advancing user code may re-enter this reader, so do not hold its lock here. - let result = zelf.iter.next(vm)?; - let mut state = zelf.state.lock(); - if state.generation != generation { - return Err(new_csv_error( - vm, - "iterator has already advanced the reader", - )); - } - if matches!(result, PyIterReturn::Return(_)) { - state.generation += 1; - } - Ok(result) - } - fn finish_at_true_eof( - mut parser: CsvParser, + parser: &mut CsvParser, dialect: &PyDialect, - vm: &VirtualMachine, - ) -> PyResult { + ) -> Result>, ReadError> { + // A reentrant call may already have returned the pending row. + if parser.fields.is_none() { + return Ok(None); + } let has_unfinished_record = !parser.field.is_empty() || parser.state == ParserState::InQuotedField; if !has_unfinished_record { - return Ok(PyIterReturn::StopIteration(None)); + return Ok(None); } if dialect.strict { - return Err(new_csv_error(vm, "unexpected end of data")); + return Err(ReadError::Csv("unexpected end of data".to_owned())); } - parser.save_field(dialect.quoting, vm)?; - Ok(parser.into_result(vm)) + parser.save_field(dialect.quoting)?; + Ok(parser.fields.take()) } impl IterNext for Reader { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let mut parser = CsvParser::new(*GLOBAL_FIELD_LIMIT.lock()); - - loop { - match next_input_item(zelf, vm)? { - PyIterReturn::Return(obj) => { - let string = obj.downcast::().map_err(|obj| { - new_csv_error( - vm, - format!( - concat!( - "iterator should return strings, not {} ", - "(the file should be opened in text mode)" + zelf.operation.with(vm, || { + let field_limit = *GLOBAL_FIELD_LIMIT.lock(); + zelf.state.lock().parser = CsvParser::new(field_limit); + + loop { + // Input callbacks may reenter this reader. No parser borrow + // or payload guard survives the call. + match zelf.iter.next(vm)? { + PyIterReturn::Return(obj) => { + let string = obj.downcast::().map_err(|obj| { + new_csv_error( + vm, + format!( + concat!( + "iterator should return strings, not {} ", + "(the file should be opened in text mode)" + ), + obj.class().name() ), - obj.class().name() - ), - ) - })?; - - zelf.state.lock().line_num += 1; - parser.field_limit = *GLOBAL_FIELD_LIMIT.lock(); - for &byte in string.as_bytes() { - parser.process_parser_input( - ParserInput::Byte(byte), - &zelf.dialect, - vm, - )?; + ) + })?; + + let field_limit = *GLOBAL_FIELD_LIMIT.lock(); + let parsed = (|| { + let mut state = zelf.state.lock(); + if state.parser.fields.is_none() { + return Err(ReadError::advanced()); + } + state.line_num += 1; + state.parser.field_limit = field_limit; + let text = + core::str::from_utf8(string.as_bytes()).map_err(|error| { + ReadError::Utf8(string.as_bytes().to_vec(), error) + })?; + for ch in text.chars() { + state.parser.process_parser_input( + ParserInput::Char(ch), + &zelf.dialect, + )?; + } + Ok(()) + })(); + // A str subclass can execute Python on destruction. + // CPython drops the input before processing EOL. + drop(string); + parsed.map_err(|error| error.into_exception(vm))?; + + let field_limit = *GLOBAL_FIELD_LIMIT.lock(); + let completed = (|| { + let mut state = zelf.state.lock(); + let parser = &mut state.parser; + if parser.fields.is_none() { + return Err(ReadError::advanced()); + } + parser.field_limit = field_limit; + parser.process_parser_input(EOL, &zelf.dialect)?; + Ok(if parser.state == ParserState::StartRecord { + parser.fields.take() + } else { + None + }) + })() + .map_err(|error| error.into_exception(vm))?; + if let Some(fields) = completed { + return Ok(row_result(fields, vm)); + } } - - // Virtual EOL marks an iterator-item boundary, not true EOF. - parser.process_parser_input(EOL, &zelf.dialect, vm)?; - if parser.state == ParserState::StartRecord { - return Ok(parser.into_result(vm)); + PyIterReturn::StopIteration(value) => { + drop(value); + let finished = { + let mut state = zelf.state.lock(); + finish_at_true_eof(&mut state.parser, &zelf.dialect) + } + .map_err(|error| error.into_exception(vm))?; + return Ok(finished + .map_or(PyIterReturn::StopIteration(None), |fields| { + row_result(fields, vm) + })); } } - PyIterReturn::StopIteration(_) => { - return finish_at_true_eof(parser, &zelf.dialect, vm); - } } - } + }) } } @@ -1163,7 +978,7 @@ mod _csv { pub(super) struct Writer { write: PyObjectRef, #[pytraverse(skip)] - state: PyMutex<()>, + operation: PyOperation, #[pytraverse(skip)] dialect: PyDialect, } @@ -1175,8 +990,8 @@ mod _csv { } fn write_quoted_field( - output: &mut Vec, - data: &[u8], + output: &mut String, + data: &str, dialect: &PyDialect, vm: &VirtualMachine, ) -> PyResult<()> { @@ -1184,22 +999,22 @@ mod _csv { .quotechar .ok_or_else(|| vm.new_type_error("quotechar must be set if quoting enabled"))?; output.push(quotechar); - for &byte in data { - if byte == quotechar { + for ch in data.chars() { + if ch == quotechar { if dialect.doublequote { output.push(quotechar); output.push(quotechar); } else if let Some(escapechar) = dialect.escapechar { output.push(escapechar); - output.push(byte); + output.push(ch); } else { return Err(new_csv_error(vm, "need to escape, but no escapechar set")); } } else { - if dialect.escapechar == Some(byte) { - output.push(byte); + if dialect.escapechar == Some(ch) { + output.push(ch); } - output.push(byte); + output.push(ch); } } output.push(quotechar); @@ -1207,159 +1022,134 @@ mod _csv { } fn write_unquoted_field( - output: &mut Vec, - data: &[u8], + output: &mut String, + data: &str, dialect: &PyDialect, vm: &VirtualMachine, ) -> PyResult<()> { - let mut data = data; - while let Some((&byte, rest)) = data.split_first() { - if field_needs_escape(data, dialect) { + for ch in data.chars() { + if char_needs_escape(ch, dialect) { let escapechar = dialect .escapechar .ok_or_else(|| new_csv_error(vm, "need to escape, but no escapechar set"))?; output.push(escapechar); } - output.push(byte); - data = rest; + output.push(ch); } Ok(()) } - fn data_contains_lineterminator_char(data: &[u8], dialect: &PyDialect) -> bool { - dialect.lineterminator.chars().any(|character| { - let mut encoded = [0; 4]; - let character = character.encode_utf8(&mut encoded).as_bytes(); - data.windows(character.len()) - .any(|window| window == character) + fn field_needs_quotes(data: &str, dialect: &PyDialect) -> bool { + data.chars().any(|ch| { + ch == dialect.delimiter + || (dialect.doublequote && dialect.quotechar == Some(ch)) + || matches!(ch, '\r' | '\n') + || dialect.lineterminator.contains(ch) }) } - fn data_starts_with_lineterminator_char(data: &[u8], dialect: &PyDialect) -> bool { - dialect.lineterminator.chars().any(|character| { - let mut encoded = [0; 4]; - let character = character.encode_utf8(&mut encoded).as_bytes(); - data.starts_with(character) - }) - } - - fn field_needs_quotes(data: &[u8], dialect: &PyDialect) -> bool { - data.iter().any(|&byte| { - byte == dialect.delimiter - || dialect.quotechar == Some(byte) - || matches!(byte, b'\r' | b'\n') - }) || data_contains_lineterminator_char(data, dialect) - } - - fn field_needs_escape(data: &[u8], dialect: &PyDialect) -> bool { - let byte = data[0]; - byte == dialect.delimiter - || dialect.quotechar == Some(byte) - || dialect.escapechar == Some(byte) - || matches!(byte, b'\r' | b'\n') - || data_starts_with_lineterminator_char(data, dialect) - } - - fn write_lineterminator(output: &mut Vec, terminator: &str) { - output.extend_from_slice(terminator.as_bytes()); + fn char_needs_escape(ch: char, dialect: &PyDialect) -> bool { + ch == dialect.delimiter + || dialect.quotechar == Some(ch) + || dialect.escapechar == Some(ch) + || matches!(ch, '\r' | '\n') + || dialect.lineterminator.contains(ch) } #[pyclass(flags(DISALLOW_INSTANTIATION))] impl Writer { - #[pygetset(name = "dialect")] - fn get_dialect(zelf: &Py, _vm: &VirtualMachine) -> PyDialect { + #[pygetset] + fn dialect(zelf: &Py, _vm: &VirtualMachine) -> PyDialect { zelf.dialect.clone() } #[pymethod] fn writerow(zelf: &Py, row: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let _state = zelf.state.lock(); - let row: ArgIterable = - ArgIterable::try_from_object(vm, row.to_owned()).map_err(|_e| { - new_csv_error( - vm, - format!("'{}' object is not iterable", row.class().name()), - ) - })?; - let fields = row.iter(vm)?.collect::>>()?; - let single_field = fields.len() == 1; - let mut output = Vec::new(); - - for (index, field) in fields.into_iter().enumerate() { - if index > 0 { - output.push(zelf.dialect.delimiter); - } + zelf.operation + .with(vm, || Self::writerow_impl(zelf, &row, vm)) + } - let stringified; - let (data, is_str, is_none): (&[u8], bool, bool) = match_class!(match field { - ref s @ PyStr => (s.as_bytes(), true, false), - crate::builtins::PyNone => (b"", false, true), - ref obj => { - stringified = obj.str(vm)?; - (stringified.as_bytes(), false, false) - } - }); - - if single_field - && data.is_empty() - && (zelf.dialect.quoting == QuoteStyle::None - || (is_none - && matches!( - zelf.dialect.quoting, - QuoteStyle::Strings | QuoteStyle::Notnull - ))) - { - return Err(new_csv_error( - vm, - "single empty field record must be quoted", - )); + fn writerow_impl(zelf: &Py, row: &PyObjectRef, vm: &VirtualMachine) -> PyResult { + let iter = row.get_iter(vm).map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + let message = { + let name = row.class().slot_name(); + let end = name.floor_char_boundary(name.len().min(200)); + format!("iterable expected, not {}", &name[..end]) + }; + new_csv_error(vm, message) + } else { + error } + })?; + let dialect = &zelf.dialect; + let mut output = String::new(); + let mut has_fields = false; + let mut empty_must_be_unquoted = false; + + for field in iter.into_iter::(vm) { + let field = field?; + if has_fields { + output.push(dialect.delimiter); + } + has_fields = true; + + // Numeric classification precedes __str__, which may alter the type. + let quote_nonnumeric = + dialect.quoting == QuoteStyle::Nonnumeric && !PyNumber::check(&field); + let (text, is_none, is_str) = match field.downcast::() { + Ok(text) => (Some(text), false, true), + Err(field) if vm.is_none(&field) => (None, true, false), + Err(field) => (Some(field.str(vm)?), false, false), + }; + let data = match &text { + Some(text) => utf8_data(text, vm)?, + None => "", + }; - if data.is_empty() - && zelf.dialect.delimiter == b' ' - && zelf.dialect.skipinitialspace - && (zelf.dialect.quoting == QuoteStyle::None - || (is_none - && matches!( - zelf.dialect.quoting, - QuoteStyle::Strings | QuoteStyle::Notnull - ))) - { + empty_must_be_unquoted = dialect.quoting == QuoteStyle::None + || (is_none + && matches!(dialect.quoting, QuoteStyle::Strings | QuoteStyle::Notnull)); + let space_requires_quote = + data.is_empty() && dialect.delimiter == ' ' && dialect.skipinitialspace; + if space_requires_quote && empty_must_be_unquoted { return Err(new_csv_error( vm, "empty field must be quoted if delimiter is a space and skipinitialspace is true", )); } - let mut should_quote = match zelf.dialect.quoting { + let should_quote = match dialect.quoting { QuoteStyle::All => true, - QuoteStyle::Nonnumeric => !PyNumber::check(&field), + QuoteStyle::Nonnumeric => quote_nonnumeric, QuoteStyle::Strings => is_str, QuoteStyle::Notnull => !is_none, QuoteStyle::Minimal | QuoteStyle::None => false, }; - if zelf.dialect.quoting != QuoteStyle::None - && ((data.is_empty() - && zelf.dialect.delimiter == b' ' - && zelf.dialect.skipinitialspace) - || (single_field && data.is_empty()) - || (!should_quote && field_needs_quotes(data, &zelf.dialect))) + if dialect.quoting != QuoteStyle::None + && (should_quote || space_requires_quote || field_needs_quotes(data, dialect)) { - should_quote = true; + write_quoted_field(&mut output, data, dialect, vm)?; + } else { + write_unquoted_field(&mut output, data, dialect, vm)?; } + } - if should_quote { - write_quoted_field(&mut output, data, &zelf.dialect, vm)?; - } else { - write_unquoted_field(&mut output, data, &zelf.dialect, vm)?; + // With no separator or field text, the record has exactly one empty field. + // Do this after iterating so a late iterator error still wins. + if has_fields && output.is_empty() { + if empty_must_be_unquoted { + return Err(new_csv_error( + vm, + "single empty field record must be quoted", + )); } + write_quoted_field(&mut output, "", dialect, vm)?; } - write_lineterminator(&mut output, &zelf.dialect.lineterminator); - let s = - core::str::from_utf8(&output).map_err(|e| new_not_utf8_error(vm, &output, e))?; - zelf.write.call((s,), vm) + output.push_str(&dialect.lineterminator); + zelf.write.call((output,), vm) } #[pymethod] diff --git a/crates/stdlib/src/elementtree.rs b/crates/stdlib/src/elementtree.rs index 57c793d5494..1dc8dc82a4d 100644 --- a/crates/stdlib/src/elementtree.rs +++ b/crates/stdlib/src/elementtree.rs @@ -26,16 +26,16 @@ pub(crate) mod _elementtree { use crate::vm::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, atomic_func, - builtins::{PyDict, PyDictRef, PyList, PyModule, PyStr, PyType, PyTypeRef}, - function::{FuncArgs, PySetterValue}, + builtins::{PyAnyDict, PyDict, PyDictRef, PyList, PyModule, PyStr, PyType, PyTypeRef}, + function::{ArgBytesOrStr, FuncArgs, PySetterValue}, protocol::{PyMappingMethods, PyNumberMethods, PySequenceMethods}, - sliceable::{SequenceIndex, SliceableSequenceOp}, + sliceable::{NameElement, SequenceIndex, SliceableSequenceOp}, types::{ AsMapping, AsNumber, AsSequence, Constructor, DefaultConstructor, Initializer, IterNext, Iterable, Representable, SelfIter, }, }; - use rustpython_common::lock::PyRwLock; + use rustpython_common::{lock::PyRwLock, wtf8::Wtf8Buf}; // The per-module bookkeeping `_elementtree.c` keeps in its // `elementtreestate`: the `Comment`/`ProcessingInstruction` factories @@ -174,7 +174,7 @@ pub(crate) mod _elementtree { tail: Joined, /// `None` until an attribute is actually needed, mirroring the C /// implementation's lazily allocated `extra->attrib`. - attrib: Option, + attrib: Option>, children: Vec, } @@ -222,8 +222,9 @@ pub(crate) mod _elementtree { } impl PyElement { - fn new(tag: PyObjectRef, attrib: Option, vm: &VirtualMachine) -> Self { - let attrib = attrib.filter(|d| !d.is_empty()); + fn new(tag: PyObjectRef, attrib: Option>, vm: &VirtualMachine) -> Self { + // CPython elides only empty exact dicts, preserving frozen/subclass identity. + let attrib = attrib.filter(|d| !d.class().is(vm.ctx.types.dict_type) || !d.is_empty()); Self { inner: PyRwLock::new(ElementInner { tag, @@ -287,15 +288,15 @@ pub(crate) mod _elementtree { Ok(joined) } - fn attrib_or_new(&self, vm: &VirtualMachine) -> PyDictRef { + fn attrib_or_new(&self, vm: &VirtualMachine) -> PyRef { let mut inner = self.inner.write(); inner .attrib - .get_or_insert_with(|| vm.ctx.new_dict()) + .get_or_insert_with(|| vm.ctx.new_dict().into()) .clone() } - fn attrib_opt(&self) -> Option { + fn attrib_opt(&self) -> Option> { self.inner.read().attrib.clone() } } @@ -310,13 +311,17 @@ pub(crate) mod _elementtree { if obj.downcastable::() { Ok(()) } else { - Err(vm.new_type_error(format!( - "expected an Element, not \"{}\"", - obj.class().name() - ))) + reject_element(obj, vm) } } + fn reject_element(obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + Err(vm.new_type_error(format!( + "expected an Element, not \"{}\"", + obj.class().name() + ))) + } + fn as_element<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> PyResult<&'a Py> { obj.downcast_ref::().ok_or_else(|| { vm.new_type_error(format!( @@ -356,14 +361,21 @@ pub(crate) mod _elementtree { let positional_attrib = args.args.get(extra_positional + 1).cloned(); let attrib = match positional_attrib { Some(obj) => { - let dict = obj.downcast::().map_err(|obj| { - vm.new_type_error(format!( - "{func_name}() argument {} must be dict, not {}", - extra_positional + 2, - obj.class().name() - )) - })?; - let copied = dict.copy().into_ref(&vm.ctx); + let expected = if extra_positional == 0 { + "dict or frozendict" + } else { + "dict" + }; + let dict = PyAnyDict::from_object(&obj) + .filter(|_| extra_positional == 0 || obj.downcastable::()) + .ok_or_else(|| { + vm.new_type_error(format!( + "{func_name}() argument {} must be {expected}, not {}", + extra_positional + 2, + obj.class().name() + )) + })?; + let copied = dict.copy_as_dict(vm)?.into_ref(&vm.ctx); for (key, value) in args.kwargs.drain(..) { copied.set_item(&key, value, vm)?; } @@ -373,13 +385,13 @@ pub(crate) mod _elementtree { let popped = args.kwargs.shift_remove("attrib"); let copied = match popped { Some(obj) => { - let dict = obj.downcast::().map_err(|obj| { + let dict = PyAnyDict::from_object(&obj).ok_or_else(|| { vm.new_type_error(format!( - "attrib must be dict, not {}", + "attrib must be dict or frozendict, not {}", obj.class().name() )) })?; - dict.copy().into_ref(&vm.ctx) + dict.copy_as_dict(vm)?.into_ref(&vm.ctx) } None => vm.ctx.new_dict(), }; @@ -454,19 +466,23 @@ pub(crate) mod _elementtree { fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { let (tag, attrib) = parse_attrib_args(args, "Element", 0, vm)?; - let attrib = attrib.filter(|d| !d.is_empty()); + let attrib = attrib.filter(|d| !d.is_empty()).map(Into::into); let _recycle = { let mut inner = zelf.inner.write(); - let old_attrib = if attrib.is_some() { - core::mem::replace(&mut inner.attrib, attrib) + let (old_attrib, old_children) = if let Some(attrib) = attrib { + ( + inner.attrib.replace(attrib), + core::mem::take(&mut inner.children), + ) } else { - None + (None, Vec::new()) }; ( core::mem::replace(&mut inner.tag, tag), core::mem::replace(&mut inner.text, Joined::plain(vm.ctx.none())), core::mem::replace(&mut inner.tail, Joined::plain(vm.ctx.none())), old_attrib, + old_children, ) }; Ok(()) @@ -525,16 +541,21 @@ pub(crate) mod _elementtree { } #[pygetset] - fn attrib(zelf: &Py, vm: &VirtualMachine) -> PyDictRef { + fn attrib(zelf: &Py, vm: &VirtualMachine) -> PyRef { zelf.attrib_or_new(vm) } #[pygetset(setter)] fn set_attrib(zelf: &Py, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let value = setter_value(value, vm)?; - let dict = value.downcast::().map_err(|obj| { - vm.new_type_error(format!("attrib must be dict, not {}", obj.class().name())) - })?; + let dict = PyAnyDict::from_object(&value) + .ok_or_else(|| { + vm.new_type_error(format!( + "attrib must be dict or frozendict, not {}", + value.class().name() + )) + })? + .to_owned(); let _recycle = zelf.inner.write().attrib.replace(dict); Ok(()) } @@ -549,10 +570,20 @@ pub(crate) mod _elementtree { #[pymethod] fn extend(zelf: &Py, elements: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let items: Vec = elements.try_to_value(vm)?; - for element in &items { - check_element(element, vm)?; + // Keep the bulk path while committing valid items before an error. + let valid_prefix = items + .iter() + .position(|element| !element.downcastable::()) + .unwrap_or(items.len()); + let mut items = items.into_iter(); + zelf.inner + .write() + .children + .extend(items.by_ref().take(valid_prefix)); + for element in items { + check_element(&element, vm)?; + zelf.inner.write().children.push(element); } - zelf.inner.write().children.extend(items); Ok(()) } @@ -578,7 +609,21 @@ pub(crate) mod _elementtree { #[pymethod] fn remove(zelf: &Py, subelement: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - check_element(&subelement, vm)?; + if !subelement.downcastable::() { + let name = if vm.is_none(&subelement) { + "None".into() + } else { + subelement.class().slot_name() + }; + let mut end = name.len().min(50); + while !name.is_char_boundary(end) { + end -= 1; + } + return Err(vm.new_type_error(format!( + "remove() argument must be xml.etree.ElementTree.Element, not {}", + &name[..end] + ))); + } // Identity first, then equality, the way `element_remove` does; // the equality test can run arbitrary code, so the lock is // dropped for it and the list re-read afterwards. @@ -603,7 +648,10 @@ pub(crate) mod _elementtree { i += 1; } let Some(i) = found else { - return Err(vm.new_value_error("Element.remove(x): element not found")); + let mut message = subelement.repr(vm)?.as_wtf8().to_owned(); + message.push_str(" not in "); + message.push_wtf8(zelf.as_object().repr(vm)?.as_wtf8()); + return Err(vm.new_value_error(message)); }; let _recycle = { let mut inner = zelf.inner.write(); @@ -631,7 +679,7 @@ pub(crate) mod _elementtree { let Some(attrib) = zelf.attrib_opt() else { return Ok(default); }; - Ok(attrib.get_item_opt(&*args.key, vm)?.unwrap_or(default)) + Ok(attrib.inner_getitem_opt(&*args.key, vm)?.unwrap_or(default)) } #[pymethod] @@ -650,7 +698,7 @@ pub(crate) mod _elementtree { let Some(attrib) = zelf.attrib_opt() else { return vec![]; }; - attrib.into_iter().map(|(k, _)| k).collect() + attrib.keys_vec() } #[pymethod] @@ -659,6 +707,7 @@ pub(crate) mod _elementtree { return vec![]; }; attrib + .items_vec() .into_iter() .map(|(k, v)| vm.ctx.new_tuple(vec![k, v]).into()) .collect() @@ -666,7 +715,7 @@ pub(crate) mod _elementtree { #[pymethod] fn makeelement( - zelf: &Py, + _zelf: &Py, tag: PyObjectRef, attrib: PyObjectRef, vm: &VirtualMachine, @@ -678,7 +727,7 @@ pub(crate) mod _elementtree { )) })?; let attrib = attrib.copy().into_ref(&vm.ctx); - create_element(zelf.class().to_owned(), tag, Some(attrib), vm) + Ok(create_element(tag, Some(attrib.into()), vm)) } #[pymethod] @@ -776,10 +825,9 @@ pub(crate) mod _elementtree { #[pymethod] fn iter(zelf: PyRef, args: IterArgs, vm: &VirtualMachine) -> PyElementIter { let tag = args.tag.unwrap_or_else(|| vm.ctx.none()); - let tag = match tag.downcast_ref::() { - Some(s) if s.as_wtf8() == "*" => vm.ctx.none(), - _ => tag, - }; + let wildcard = + ArgBytesOrStr::with_object_ref(&tag, |bytes| bytes == b"*").unwrap_or(false); + let tag = if wildcard { vm.ctx.none() } else { tag }; PyElementIter::new(zelf, tag, false) } @@ -806,14 +854,13 @@ pub(crate) mod _elementtree { inner.children.clone(), ) }; - let new = create_element(zelf.class().to_owned(), tag, attrib, vm)?; + let new = create_element(tag, attrib, vm); { let elem = as_element(&new, vm)?; let mut inner = elem.inner.write(); inner.text = text; inner.tail = tail; inner.children = children; - drop(inner); } Ok(new) } @@ -833,7 +880,10 @@ pub(crate) mod _elementtree { fn __getstate__(zelf: &Py, vm: &VirtualMachine) -> PyResult { let inner = zelf.inner.read(); let children = vm.ctx.new_list(inner.children.clone()); - let attrib = inner.attrib.clone().unwrap_or_else(|| vm.ctx.new_dict()); + let attrib = inner + .attrib + .clone() + .unwrap_or_else(|| vm.ctx.new_dict().into()); let text = inner.text.obj.clone(); let tail = inner.tail.obj.clone(); let tag = inner.tag.clone(); @@ -849,12 +899,21 @@ pub(crate) mod _elementtree { #[pymethod] fn __setstate__(zelf: &Py, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let dict = state.downcast_ref::().ok_or_else(|| { - vm.new_type_error(format!( - "Don't know how to unpickle \"{}\" as an Element", - state.repr(vm).map(|s| s.to_string()).unwrap_or_default() - )) - })?; + let Some(dict) = state + .downcast_ref::() + .filter(|_| state.class().is(vm.ctx.types.dict_type)) + else { + let repr = state.repr(vm)?; + let end = repr + .as_wtf8() + .code_point_indices() + .nth(200) + .map_or_else(|| repr.byte_len(), |(offset, _)| offset); + let mut message = Wtf8Buf::from("Don't know how to unpickle \""); + message.push_wtf8(&repr.as_wtf8()[..end]); + message.push_str("\" as an Element"); + return Err(vm.new_type_error(message)); + }; let tag = dict.get_item_opt("tag", vm)?; let attrib = dict.get_item_opt("attrib", vm)?; let text = dict.get_item_opt("text", vm)?; @@ -877,26 +936,28 @@ pub(crate) mod _elementtree { None => None, }; let attrib = match attrib { - Some(attrib) if !vm.is_none(&attrib) => { - Some(attrib.downcast::().map_err(|obj| { - vm.new_type_error(format!( - "attrib must be dict, not {}", - obj.class().name() - )) - })?) - } + Some(attrib) if !vm.is_none(&attrib) => Some( + PyAnyDict::from_object(&attrib) + .ok_or_else(|| { + vm.new_type_error(format!( + "attrib must be dict or frozendict, not {}", + attrib.class().name() + )) + })? + .to_owned(), + ), _ => None, }; let new_text = match text { Some(text) => { - let pending = text.downcastable::(); + let pending = text.class().is(vm.ctx.types.list_type); Joined { obj: text, pending } } None => Joined::plain(vm.ctx.none()), }; let new_tail = match tail { Some(tail) => { - let pending = tail.downcastable::(); + let pending = tail.class().is(vm.ctx.types.list_type); Joined { obj: tail, pending } } None => Joined::plain(vm.ctx.none()), @@ -948,40 +1009,48 @@ pub(crate) mod _elementtree { let mut recycle: Vec = Vec::new(); match sequence_index(vm, needle)? { SequenceIndex::Int(i) => { - check_element(&value, vm)?; let mut inner = self.inner.write(); - let pos = inner - .children - .wrap_index(i) - .ok_or_else(|| vm.new_index_error("child assignment index out of range"))?; + let Some(pos) = inner.children.wrap_index(i) else { + drop(inner); + return Err(vm.new_index_error("child assignment index out of range")); + }; + if !value.downcastable::() { + drop(inner); + return reject_element(&value, vm); + } recycle.push(core::mem::replace(&mut inner.children[pos], value)); Ok(()) } SequenceIndex::Slice(slice) => { let items: Vec = value.try_to_value(vm)?; - for item in &items { - check_element(item, vm)?; - } + // This check cannot call Python. Delay reporting it until + // after the extended-slice length check. + let invalid = items.iter().find(|item| !item.downcastable::()); let mut inner = self.inner.write(); let (range, step, slice_len) = slice.adjust_indices(inner.children.len()); + if step != 1 && slice_len != items.len() { + let new_len = items.len(); + drop(inner); + drop(items); + return Err(vm.new_value_error(format!( + "attempt to assign sequence of size {new_len} to extended slice of size {slice_len}" + ))); + } + if let Some(item) = invalid { + drop(inner); + return reject_element(item, vm); + } if step == 1 { recycle.extend(inner.children.splice(range, items)); - Ok(()) - } else if slice_len == items.len() { + } else { let iter = crate::vm::sliceable::SaturatedSliceIter::from_adjust_indices( range, step, slice_len, ); for (pos, item) in iter.zip(items) { recycle.push(core::mem::replace(&mut inner.children[pos], item)); } - Ok(()) - } else { - Err(vm.new_value_error(format!( - "attempt to assign sequence of size {} to extended slice of size {}", - items.len(), - slice_len - ))) } + Ok(()) } } } @@ -1028,20 +1097,18 @@ pub(crate) mod _elementtree { } fn sequence_index(vm: &VirtualMachine, needle: &PyObject) -> PyResult { - SequenceIndex::try_from_borrowed_object(vm, needle, "element") + SequenceIndex::try_from_borrowed_object::(vm, needle) .map_err(|_| vm.new_type_error("element indices must be integers")) } - /// Instantiate `cls` (which may be an `Element` subclass) directly, - /// bypassing `__init__`, the way `create_new_element` does. + /// Create a base Element directly, bypassing `__init__`, like CPython's + /// `create_new_element`. fn create_element( - cls: PyTypeRef, tag: PyObjectRef, - attrib: Option, + attrib: Option>, vm: &VirtualMachine, - ) -> PyResult { - let element = PyElement::new(tag, attrib, vm); - Ok(element.into_ref_with_type(vm, cls)?.into()) + ) -> PyObjectRef { + PyElement::new(tag, attrib, vm).into_ref(&vm.ctx).into() } fn deepcopy_obj(obj: &PyObject, memo: &Py, vm: &VirtualMachine) -> PyResult { @@ -1087,14 +1154,17 @@ pub(crate) mod _elementtree { }; let tag = deepcopy_obj(&tag, memo, vm)?; let attrib = match attrib { - Some(attrib) => Some( - deepcopy_obj(attrib.as_object(), memo, vm)? - .downcast::() - .map_err(|_| vm.new_type_error("attrib must be dict"))?, - ), + Some(attrib) => { + let copied = deepcopy_obj(attrib.as_object(), memo, vm)?; + Some( + PyAnyDict::from_object(&copied) + .ok_or_else(|| vm.new_type_error("attrib must be dict or frozendict"))? + .to_owned(), + ) + } None => None, }; - let new = create_element(zelf.class().to_owned(), tag, attrib, vm)?; + let new = create_element(tag, attrib, vm); let elem = as_element(&new, vm)?; let text = deepcopy_obj(&text, memo, vm)?; let tail = deepcopy_obj(&tail, memo, vm)?; @@ -1133,30 +1203,26 @@ pub(crate) mod _elementtree { /// plain tag, in which case `find`/`findall` must go through /// `ElementPath`? fn check_path(tag: &PyObject) -> bool { - let bytes = if let Some(s) = tag.downcast_ref::() { - s.as_bytes() - } else if let Some(b) = tag.downcast_ref::() { - b.as_bytes() - } else { - // Unknown type; might be a path expression. - return true; - }; - if bytes.len() >= 3 - && bytes[0] == b'{' - && (bytes[1] == b'}' || (bytes[1] == b'*' && bytes[2] == b'}')) - { - return true; - } - let mut check = true; - for &ch in bytes { - match ch { - b'{' => check = false, - b'}' => check = true, - b'/' | b'*' | b'[' | b'@' | b'.' if check => return true, - _ => {} + ArgBytesOrStr::with_object_ref(tag, |bytes| { + if bytes.len() >= 3 + && bytes[0] == b'{' + && (bytes[1] == b'}' || (bytes[1] == b'*' && bytes[2] == b'}')) + { + return true; } - } - false + let mut check = true; + for &ch in bytes { + match ch { + b'{' => check = false, + b'}' => check = true, + b'/' | b'*' | b'[' | b'@' | b'.' if check => return true, + _ => {} + } + } + false + }) + // Unknown type; might be a path expression. + .unwrap_or(true) } impl AsMapping for PyElement { @@ -1193,21 +1259,22 @@ pub(crate) mod _elementtree { }), ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyElement::sequence_downcast(seq); - let recycle = if let Some(value) = value { - check_element(&value, vm)?; - let mut inner = zelf.inner.write(); - let pos = inner.children.wrap_index(i).ok_or_else(|| { - vm.new_index_error("child assignment index out of range") - })?; - core::mem::replace(&mut inner.children[pos], value) - } else { + let _recycle = { let mut inner = zelf.inner.write(); - let pos = inner.children.wrap_index(i).ok_or_else(|| { - vm.new_index_error("child assignment index out of range") - })?; - inner.children.remove(pos) + let Some(pos) = inner.children.wrap_index(i) else { + drop(inner); + return Err(vm.new_index_error("child assignment index out of range")); + }; + if let Some(value) = value { + if !value.downcastable::() { + drop(inner); + return reject_element(&value, vm); + } + core::mem::replace(&mut inner.children[pos], value) + } else { + inner.children.remove(pos) + } }; - drop(recycle); Ok(()) }), ..PySequenceMethods::NOT_IMPLEMENTED @@ -1265,7 +1332,7 @@ pub(crate) mod _elementtree { )) })?; let (tag, attrib) = parse_attrib_args(args, "SubElement", 1, vm)?; - let element = create_element(parent.class().to_owned(), tag, attrib, vm)?; + let element = create_element(tag, attrib.map(Into::into), vm); parent.push(element.clone()); Ok(element) } @@ -1430,11 +1497,10 @@ pub(crate) mod _elementtree { if element.class().is(PyElement::class(&vm.ctx)) { check_element(&child, vm)?; element.downcast_ref::().unwrap().push(child); - Ok(()) } else { vm.call_method(element, "append", (child,))?; - Ok(()) } + Ok(()) } /// Attach the buffered character data to `element` as its text or tail. @@ -1541,7 +1607,9 @@ pub(crate) mod _elementtree { let factory = self.state.read().element_factory.clone(); let node = match factory { // CPython adopts the caller's dict rather than copying it. - None => PyElement::new(tag, attrib, vm).into_ref(&vm.ctx).into(), + None => PyElement::new(tag, attrib.map(Into::into), vm) + .into_ref(&vm.ctx) + .into(), Some(factory) => { let attrib = attrib.unwrap_or_else(|| vm.ctx.new_dict()); factory.call((tag, attrib), vm)? @@ -1731,28 +1799,25 @@ pub(crate) mod _elementtree { .try_to_value(vm) .map_err(|_| vm.new_type_error("events must be a sequence"))?; for event in events { - let name = if let Some(s) = event.downcast_ref::() { - s.as_bytes().to_vec() - } else if let Some(b) = event.downcast_ref::() { - b.as_bytes().to_vec() - } else { + let mut st = self.state.write(); + let slot = ArgBytesOrStr::with_object_ref(&event, |name| match name { + b"start" => Some(&mut st.start_event), + b"end" => Some(&mut st.end_event), + b"start-ns" => Some(&mut st.start_ns_event), + b"end-ns" => Some(&mut st.end_ns_event), + b"comment" => Some(&mut st.comment_event), + b"pi" => Some(&mut st.pi_event), + _ => None, + }); + let Some(slot) = slot else { + drop(st); return Err(vm.new_value_error("invalid events sequence")); }; - let mut st = self.state.write(); - match name.as_slice() { - b"start" => st.start_event = Some(event), - b"end" => st.end_event = Some(event), - b"start-ns" => st.start_ns_event = Some(event), - b"end-ns" => st.end_ns_event = Some(event), - b"comment" => st.comment_event = Some(event), - b"pi" => st.pi_event = Some(event), - _ => { - drop(st); - return Err( - vm.new_value_error(format!("unknown event {}", event.repr(vm)?)) - ); - } - } + let Some(slot) = slot else { + drop(st); + return Err(vm.new_value_error(format!("unknown event {}", event.repr(vm)?))); + }; + *slot = Some(event); } Ok(()) } @@ -2018,6 +2083,11 @@ pub(crate) mod _elementtree { vm, )?; parser.set_attr("EndElementHandler", this.get_attr("_expat_end", vm)?, vm)?; + parser.set_attr( + "StartDoctypeDeclHandler", + this.get_attr("_expat_doctype", vm)?, + vm, + )?; parser.set_attr( "CharacterDataHandler", this.get_attr("_expat_data", vm)?, @@ -2151,8 +2221,7 @@ pub(crate) mod _elementtree { let info: Vec = expat.get_attr("version_info", vm)?.try_to_value(vm)?; let part = |i: usize| -> String { info.get(i) - .map(|o| o.str(vm).map(|s| s.to_string()).unwrap_or_default()) - .unwrap_or_default() + .map_or_default(|o| o.str(vm).map_or_default(|s| s.to_string())) }; Ok(format!("Expat {}.{}.{}", part(0), part(1), part(2))) } @@ -2190,15 +2259,8 @@ pub(crate) mod _elementtree { let read = file.get_attr("read", vm)?; loop { let buffer = read.call((64 * 1024,), vm)?; - if let Some(s) = buffer.downcast_ref::() { - if s.is_empty() { - break; - } - } else if let Some(b) = buffer.downcast_ref::() { - if b.as_bytes().is_empty() { - break; - } - } else { + if ArgBytesOrStr::with_object_ref(&buffer, |bytes| bytes.is_empty()).unwrap_or(true) + { break; } zelf.expat_parse(buffer, false, vm)?; @@ -2241,6 +2303,38 @@ pub(crate) mod _elementtree { Ok(()) } + #[pymethod] + fn _expat_doctype( + zelf: &Py, + name: PyObjectRef, + system: PyObjectRef, + public: PyObjectRef, + _has_internal_subset: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let name = zelf.make_universal(name, vm)?; + let system = zelf.make_universal(system, vm)?; + let public = zelf.make_universal(public, vm)?; + let handler = zelf.state.read().handle_doctype.clone(); + if let Some(handler) = handler { + handler.call((name, public, system), vm)?; + } else if optional_handler(zelf.as_object(), "doctype", vm)?.is_some() { + crate::vm::warn::warn( + vm.ctx + .new_str( + "The doctype() method of XMLParser is ignored. \ + Define doctype() method on the TreeBuilder target.", + ) + .into(), + Some(vm.ctx.exceptions.runtime_warning.to_owned()), + 1, + None, + vm, + )?; + } + Ok(()) + } + #[pymethod] fn _expat_start( zelf: &Py, @@ -2251,8 +2345,7 @@ pub(crate) mod _elementtree { let tag = zelf.make_universal(tag, vm)?; let items = attr_list .downcast_ref::() - .map(|l| l.borrow_vec().to_vec()) - .unwrap_or_default(); + .map_or_default(|l| l.borrow_vec().to_vec()); let attrib = if items.is_empty() { None } else { @@ -2325,6 +2418,18 @@ pub(crate) mod _elementtree { uri: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { + // Expat uses null for the default prefix and undeclared URI; + // ElementTree exposes both as empty strings rather than None. + let prefix = if vm.is_none(&prefix) { + vm.ctx.empty_str.to_owned().into() + } else { + prefix + }; + let uri = if vm.is_none(&uri) { + vm.ctx.empty_str.to_owned().into() + } else { + uri + }; if let Some(builder) = zelf.native_target(vm) { // The standard tree builder has no start_ns() of its own; it // only forwards the event when one was asked for. @@ -2348,6 +2453,11 @@ pub(crate) mod _elementtree { } let handler = zelf.state.read().handle_end_ns.clone(); if let Some(handler) = handler { + let prefix = if vm.is_none(&prefix) { + vm.ctx.empty_str.to_owned().into() + } else { + prefix + }; handler.call((prefix,), vm)?; } Ok(()) diff --git a/crates/stdlib/src/faulthandler.rs b/crates/stdlib/src/faulthandler.rs index 267326933c2..57c2d09d7b9 100644 --- a/crates/stdlib/src/faulthandler.rs +++ b/crates/stdlib/src/faulthandler.rs @@ -4,12 +4,15 @@ pub(crate) use decl::module_def; #[pymodule(name = "faulthandler")] mod decl { use crate::vm::{ - PyObjectRef, PyResult, VirtualMachine, - function::{ArgIntoFloat, OptionalArg}, + AsObject, PyObjectRef, PyResult, VirtualMachine, + builtins::PyInt, + function::{ArgIntoBool, OptionalArg}, + stdlib::time::pytime, }; use alloc::sync::Arc; use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use core::time::Duration; + use num_traits::ToPrimitive; use parking_lot::{Condvar, Mutex}; #[cfg(any(unix, windows))] use rustpython_host_env::faulthandler as host_faulthandler; @@ -38,6 +41,7 @@ mod decl { cancel: bool, fd: i32, timeout_us: u64, + max_threads: isize, repeat: bool, exit: bool, header: String, @@ -64,17 +68,19 @@ mod decl { // _Py_DumpHexadecimal (traceback.c) #[cfg(any(unix, windows))] fn dump_hexadecimal(fd: i32, value: u64, width: usize) { - const HEX_CHARS: &[u8; 16] = b"0123456789abcdef"; - let mut buf = [0u8; 18]; // "0x" + 16 hex digits - buf[0] = b'0'; - buf[1] = b'x'; + puts(fd, "0x"); + dump_hex_digits(fd, value, width); + } - for i in 0..width { + #[cfg(any(unix, windows))] + fn dump_hex_digits(fd: i32, value: u64, width: usize) { + const HEX_CHARS: &[u8; 16] = b"0123456789abcdef"; + let mut buf = [0u8; 16]; + for (i, byte) in buf.iter_mut().take(width).enumerate() { let digit = ((value >> (4 * (width - 1 - i))) & 0xf) as usize; - buf[2 + i] = HEX_CHARS[digit]; + *byte = HEX_CHARS[digit]; } - - puts_bytes(fd, &buf[..2 + width]); + puts_bytes(fd, &buf[..width]); } // _Py_DumpDecimal (traceback.c) @@ -145,8 +151,8 @@ mod decl { #[cfg(any(unix, windows))] fn dump_iframe(fd: i32, iframe: &rustpython_vm::frame::InterpreterFrame) { let code = iframe.code(); - let filename = code.source_path().as_str(); - let funcname = code.obj_name.as_str(); + let filename = code.source_path().as_wtf8(); + let funcname = code.obj_name.as_wtf8(); let lasti = iframe.get_lasti(); let lineno = if lasti == 0 { code.first_line_number.map_or(1, |n| n.get()) as u32 @@ -193,47 +199,58 @@ mod decl { #[cfg(any(unix, windows))] const MAX_STRING_LENGTH: usize = 500; - /// Truncate a UTF-8 string to at most `max_bytes` without splitting a - /// multi-byte codepoint. Signal-safe (no allocation, no panic). + /// `_Py_DumpASCII`: escape non-printable code points and truncate by + /// character count, without allocation or Python calls in a signal handler. #[cfg(any(unix, windows))] - fn safe_truncate(s: &str, max_bytes: usize) -> (&str, bool) { - if s.len() <= max_bytes { - return (s, false); + fn dump_ascii(fd: i32, s: &rustpython_common::wtf8::Wtf8) { + let prefix = &s.as_bytes()[..s.len().min(MAX_STRING_LENGTH)]; + if prefix.iter().all(|byte| (0x20..=0x7e).contains(byte)) { + puts_bytes(fd, prefix); + if s.len() > MAX_STRING_LENGTH { + puts(fd, "..."); + } + return; } - let mut end = max_bytes; - while end > 0 && !s.is_char_boundary(end) { - end -= 1; + let mut points = s.code_points(); + for point in points.by_ref().take(MAX_STRING_LENGTH) { + let value = point.to_u32(); + if (0x20..=0x7e).contains(&value) { + puts_bytes(fd, &[value as u8]); + } else { + let (prefix, width) = if value <= 0xff { + ("\\x", 2) + } else if value <= 0xffff { + ("\\u", 4) + } else { + ("\\U", 8) + }; + puts(fd, prefix); + dump_hex_digits(fd, u64::from(value), width); + } } - (&s[..end], true) - } - - /// Write a string to fd, truncating with "..." if it exceeds MAX_STRING_LENGTH. - /// Mirrors `_Py_DumpASCII` truncation behavior. - #[cfg(any(unix, windows))] - fn dump_ascii(fd: i32, s: &str) { - let (truncated_s, was_truncated) = safe_truncate(s, MAX_STRING_LENGTH); - puts(fd, truncated_s); - if was_truncated { + if points.next().is_some() { puts(fd, "..."); } } #[derive(FromArgs)] struct DumpTracebackArgs { - #[pyarg(any, default)] + #[pyarg(any, default, py_default = "sys.stderr")] file: OptionalArg, - #[pyarg(any, default = true)] - all_threads: bool, + #[pyarg(any, default = ArgIntoBool::TRUE)] + all_threads: ArgIntoBool, + #[pyarg(named, default = 100)] + max_threads: isize, } #[pyfunction] fn dump_traceback(args: DumpTracebackArgs, vm: &VirtualMachine) -> PyResult<()> { - let fd = get_fd_from_file_opt(args.file, vm)?; + let (fd, _file) = get_fd_from_file_opt(args.file, vm)?; #[cfg(any(unix, windows))] { - if args.all_threads { - dump_all_threads(fd, vm); + if args.all_threads.into_bool() { + dump_all_threads(fd, args.max_threads, vm); } else { puts(fd, "Stack (most recent call first):\n"); dump_live_frames(fd); @@ -242,20 +259,52 @@ mod decl { #[cfg(not(any(unix, windows)))] { - let _ = (fd, args.all_threads); + let _ = (fd, args.all_threads, args.max_threads); } Ok(()) } + #[cfg(any(unix, windows))] + #[derive(FromArgs)] + struct DumpCStackArgs { + #[pyarg(any, default, py_default = "sys.stderr")] + file: OptionalArg, + } + + /// Dump the C stack of the current thread. + #[cfg(any(unix, windows))] + #[pyfunction] + fn dump_c_stack(args: DumpCStackArgs, vm: &VirtualMachine) -> PyResult<()> { + let (fd, file) = get_fd_from_file_opt(args.file, vm)?; + // Native unwinding and loader lookup run in ordinary execution only, + // never in one of this module's asynchronous signal callbacks. + host_faulthandler::dump_c_stack(fd); + drop(file); + vm.check_signals() + } + /// Dump tracebacks of all threads. #[cfg(any(unix, windows))] - fn dump_all_threads(fd: i32, vm: &VirtualMachine) { + fn dump_all_threads(fd: i32, max_threads: isize, vm: &VirtualMachine) { + let max_threads = if max_threads == 0 { 100 } else { max_threads }; + let mut nthreads = 0; + let mut begin_thread_dump = || { + if nthreads != 0 { + puts(fd, "\n"); + } + if nthreads >= max_threads { + puts(fd, "...\n"); + return false; + } + nthreads += 1; + true + }; // Get all threads' frame stacks from the shared registry - // unix: stop-the-world so every other thread is parked at a safepoint + // Stop the world so every other thread is parked at a safepoint // and its frame chain is quiescent and alive while we walk it (matches // faulthandler.dump_traceback running with the GIL held). - #[cfg(all(unix, feature = "threading"))] + #[cfg(feature = "threading")] { use core::sync::atomic::Ordering; let current_tid = rustpython_vm::stdlib::_thread::get_ident(); @@ -271,6 +320,9 @@ mod decl { if tid == current_tid { continue; } + if !begin_thread_dump() { + return; + } // Under STW, all other threads are suspended so their // stack-allocated iframes are stable. Walk via top_iframe // which covers both FrameObject and stack-allocated paths. @@ -292,55 +344,14 @@ mod decl { puts(fd, " ...\n"); } } - puts(fd, "\n"); } } // Now dump current thread from its live frame chain // (includes stack-allocated iframes without FrameObject). - write_thread_id(fd, current_tid, true); - dump_live_frames(fd); - } - - #[cfg(all(not(unix), feature = "threading"))] - { - let current_tid = rustpython_vm::stdlib::_thread::get_ident(); - let registry = vm.state.thread_frames.lock(); - - // Dump non-current threads using top_iframe, which includes - // both FrameObject and stack-allocated frames. - #[expect( - clippy::iter_over_hash_type, - reason = "Iteration order doesn't matter here" - )] - for (&tid, slot) in registry.iter() { - if tid == current_tid { - continue; - } - - let iframe_ptr = slot.top_iframe.load(core::sync::atomic::Ordering::Relaxed) - as *const rustpython_vm::frame::InterpreterFrame; - write_thread_id(fd, tid, false); - if iframe_ptr.is_null() { - puts(fd, " \n"); - } else { - let mut cur = iframe_ptr; - let mut depth = 0; - while !cur.is_null() && depth < 100 { - let iframe = unsafe { &*cur }; - dump_iframe(fd, iframe); - depth += 1; - cur = iframe.previous(); - } - if depth >= 100 && !cur.is_null() { - puts(fd, " ...\n"); - } - } - puts(fd, "\n"); + if !begin_thread_dump() { + return; } - - // Now dump current thread from its live frame chain - // (includes stack-allocated iframes without FrameObject). write_thread_id(fd, current_tid, true); dump_live_frames(fd); } @@ -348,6 +359,9 @@ mod decl { #[cfg(not(feature = "threading"))] { let _ = vm; + if !begin_thread_dump() { + return; + } write_thread_id(fd, current_thread_id(), true); dump_live_frames(fd); } @@ -356,23 +370,23 @@ mod decl { #[derive(FromArgs)] #[allow(unused)] struct EnableArgs { - #[pyarg(any, default)] + #[pyarg(any, default, py_default = "sys.stderr")] file: OptionalArg, - #[pyarg(any, default = true)] - all_threads: bool, + #[pyarg(any, default = ArgIntoBool::TRUE)] + all_threads: ArgIntoBool, } // faulthandler_py_enable #[pyfunction] fn enable(args: EnableArgs, vm: &VirtualMachine) -> PyResult<()> { // Get file descriptor - let fd = get_fd_from_file_opt(args.file, vm)?; + let (fd, _file) = get_fd_from_file_opt(args.file, vm)?; // Store fd and all_threads in global state FATAL_ERROR.fd.store(fd, Ordering::Relaxed); FATAL_ERROR .all_threads - .store(args.all_threads, Ordering::Relaxed); + .store(args.all_threads.into_bool(), Ordering::Relaxed); // Install signal handlers if !faulthandler_enable_internal() { @@ -399,12 +413,11 @@ mod decl { host_faulthandler::disable_fatal_signal(signum); puts(fd, "Fatal Python error: "); puts(fd, name); - puts(fd, "\n\n"); } else { puts(fd, "Fatal Python error from unexpected signum: "); dump_decimal(fd, signum as usize); - puts(fd, "\n\n"); } + puts(fd, "\n\n"); let all_threads = FATAL_ERROR.all_threads.load(Ordering::Relaxed); faulthandler_dump_traceback(fd, all_threads); @@ -436,12 +449,11 @@ mod decl { host_faulthandler::disable_fatal_signal(signum); puts(fd, "Fatal Python error: "); puts(fd, name); - puts(fd, "\n\n"); } else { puts(fd, "Fatal Python error from unexpected signum: "); dump_decimal(fd, signum as usize); - puts(fd, "\n\n"); } + puts(fd, "\n\n"); let all_threads = FATAL_ERROR.all_threads.load(Ordering::Relaxed); faulthandler_dump_traceback(fd, all_threads); @@ -451,7 +463,7 @@ mod decl { host_faulthandler::signal_default_and_raise(signum); // Fallback - rustpython_host_env::os::exit(1); + rustpython_host_env::os::exit_immediately(1); } // Windows vectored exception handler (faulthandler.c:417-480) @@ -597,25 +609,31 @@ mod decl { } } - fn get_fd_from_file_opt(file: OptionalArg, vm: &VirtualMachine) -> PyResult { - match file { - OptionalArg::Present(f) if !vm.is_none(&f) => { + fn get_fd_from_file_opt( + file: OptionalArg, + vm: &VirtualMachine, + ) -> PyResult<(i32, PyObjectRef)> { + let file = match file { + OptionalArg::Present(file) if !vm.is_none(&file) => { // Check if it's an integer (file descriptor) - if let Ok(fd) = f.try_to_value::(vm) { + if let Some(int) = file.downcast_ref::() { + if file.class().is(vm.ctx.types.bool_type) { + rustpython_vm::stdlib::_warnings::warn( + vm.ctx.exceptions.runtime_warning, + "bool is used as a file descriptor".to_owned(), + 1, + vm, + )?; + } + let fd = int.try_to_primitive(vm).map_err(|_| { + vm.new_overflow_error("Python int too large to convert to C int") + })?; if fd < 0 { return Err(vm.new_value_error("file is not a valid file descriptor")); } - return Ok(fd); + return Ok((fd, file)); } - // Try to get fileno() from file object - let fileno = vm.call_method(&f, "fileno", ())?; - let fd: i32 = fileno.try_to_value(vm)?; - if fd < 0 { - return Err(vm.new_value_error("file is not a valid file descriptor")); - } - // Try to flush the file - let _ = vm.call_method(&f, "flush", ()); - Ok(fd) + file } _ => { // file=None or file not passed: fall back to sys.stderr @@ -623,12 +641,25 @@ mod decl { if vm.is_none(&stderr) { return Err(vm.new_runtime_error("sys.stderr is None")); } - let fileno = vm.call_method(&stderr, "fileno", ())?; - let fd: i32 = fileno.try_to_value(vm)?; - let _ = vm.call_method(&stderr, "flush", ()); - Ok(fd) + stderr } - } + }; + + // fileno() must return an actual int, not an object with __index__. + // Unlike an integer passed directly, its upper bound excludes INT_MAX. + // Try to get fileno() from file object + let fileno = vm.call_method(&file, "fileno", ())?; + let fd = fileno + .downcast_ref::() + .and_then(|value| value.as_bigint().to_i32()) + .filter(|&fd| (0..i32::MAX).contains(&fd)); + drop(fileno); + let fd = + fd.ok_or_else(|| vm.new_runtime_error("file.fileno() is not a valid file descriptor"))?; + // Try to flush the file + let _ = vm.call_method(&file, "flush", ()); + // Keep the selected file alive until the caller has used its descriptor. + Ok((fd, file)) } fn watchdog_thread(state: WatchdogHandle) { @@ -641,7 +672,8 @@ mod decl { return; } let timeout = Duration::from_micros(guard.timeout_us); - cvar.wait_for(&mut guard, timeout); + // A notification or spurious wake does not mean the deadline passed. + cvar.wait_while_for(&mut guard, |state| !state.cancel, timeout); // Check if cancelled after wait if guard.cancel { @@ -652,6 +684,7 @@ mod decl { let repeat = guard.repeat; let exit = guard.exit; let fd = guard.fd; + let max_threads = guard.max_threads; let header = guard.header.clone(); #[cfg(feature = "threading")] let thread_frame_slots = guard.thread_frame_slots.clone(); @@ -660,10 +693,22 @@ mod decl { // Timeout occurred, dump traceback cfg_select! { target_arch = "wasm32" => { - let _ = (exit, fd, &header); + let _ = (exit, fd, max_threads, &header); } _ => { puts_bytes(fd, header.as_bytes()); + let mut nthreads = 0; + let mut begin_thread_dump = || { + if nthreads != 0 { + puts(fd, "\n"); + } + if nthreads >= max_threads { + puts(fd, "...\n"); + return false; + } + nthreads += 1; + true + }; // Use thread frame slots when threading is enabled (includes all threads). // Fall back to live frame walking for non-threaded builds. @@ -679,10 +724,12 @@ mod decl { // frames are still alive because the target thread // is executing (inside a blocking call). for (tid, slot) in &thread_frame_slots { - let iframe_ptr = slot - .top_iframe - .load(core::sync::atomic::Ordering::Relaxed) - as *const rustpython_vm::frame::InterpreterFrame; + if !begin_thread_dump() { + break; + } + let iframe_ptr = + slot.top_iframe.load(core::sync::atomic::Ordering::Relaxed) + as *const rustpython_vm::frame::InterpreterFrame; write_thread_id(fd, *tid, false); if iframe_ptr.is_null() { puts(fd, " \n"); @@ -703,10 +750,12 @@ mod decl { } all(not(unix), feature = "threading") => { for (tid, slot) in &thread_frame_slots { - let iframe_ptr = slot - .top_iframe - .load(core::sync::atomic::Ordering::Relaxed) - as *const rustpython_vm::frame::InterpreterFrame; + if !begin_thread_dump() { + break; + } + let iframe_ptr = + slot.top_iframe.load(core::sync::atomic::Ordering::Relaxed) + as *const rustpython_vm::frame::InterpreterFrame; write_thread_id(fd, *tid, false); if iframe_ptr.is_null() { puts(fd, " \n"); @@ -726,13 +775,15 @@ mod decl { } } _ => { - write_thread_id(fd, current_thread_id(), false); - dump_live_frames(fd); + if begin_thread_dump() { + write_thread_id(fd, current_thread_id(), false); + dump_live_frames(fd); + } } } if exit { - rustpython_host_env::os::exit(1); + rustpython_host_env::os::exit_immediately(1); } } } @@ -746,32 +797,36 @@ mod decl { #[derive(FromArgs)] #[allow(unused)] struct DumpTracebackLaterArgs { - #[pyarg(positional, error_msg = "timeout must be a number (int or float)")] - timeout: ArgIntoFloat, - #[pyarg(any, default)] - repeat: bool, - #[pyarg(any, default)] + // Clinic converts repeat/exit before interpreting the timeout object. + #[pyarg(any)] + timeout: PyObjectRef, + #[pyarg(any, default = ArgIntoBool::FALSE)] + repeat: ArgIntoBool, + #[pyarg(any, default, py_default = "sys.stderr")] file: OptionalArg, - #[pyarg(any, default)] - exit: bool, + #[pyarg(any, default = ArgIntoBool::FALSE)] + exit: ArgIntoBool, + #[pyarg(named, default = 100)] + max_threads: isize, } #[pyfunction] fn dump_traceback_later(args: DumpTracebackLaterArgs, vm: &VirtualMachine) -> PyResult<()> { - let timeout: f64 = args.timeout.into_float(); - - if timeout <= 0.0 { + let timeout = pytime::from_seconds_object(&args.timeout, pytime::Round::Up, vm)?; + let timeout_us = pytime::Round::Up.divide(timeout, 1_000); + if timeout_us <= 0 { return Err(vm.new_value_error("timeout must be greater than 0")); } - - let fd = get_fd_from_file_opt(args.file, vm)?; - - // Convert timeout to microseconds - let timeout_us = (timeout * 1_000_000.0) as u64; - if timeout_us == 0 { - return Err(vm.new_value_error("timeout must be greater than 0")); + pytime::check_thread_timeout(timeout, vm)?; + // CPython also bounds the seconds passed to format_timeout by LONG_MAX. + #[allow(clippy::unnecessary_cast)] // c_long is i32 or i64. + let max_seconds = core::ffi::c_long::MAX as i64; + if timeout_us / 1_000_000 > max_seconds { + return Err(vm.new_overflow_error("timeout value is too large")); } + let timeout_us = timeout_us as u64; + let (fd, _file) = get_fd_from_file_opt(args.file, vm)?; let header = format_timeout(timeout_us); // Snapshot thread frame slots so watchdog can dump tracebacks @@ -793,8 +848,13 @@ mod decl { cancel: false, fd, timeout_us, - repeat: args.repeat, - exit: args.exit, + max_threads: if args.max_threads == 0 { + 100 + } else { + args.max_threads + }, + repeat: args.repeat.into_bool(), + exit: args.exit.into_bool(), header, #[cfg(feature = "threading")] thread_frame_slots, @@ -839,7 +899,10 @@ mod decl { let user = match host_faulthandler::get_user_signal(signum as usize) { Some(u) => u, - _ => return, + _ => { + set_errno(save_errno); + return; + } }; faulthandler_dump_traceback(user.fd, user.all_threads); @@ -848,6 +911,7 @@ mod decl { set_errno(save_errno); let _ = host_faulthandler::reraise_user_signal(signum, faulthandler_user_signal); } + set_errno(save_errno); } #[cfg(unix)] @@ -871,14 +935,14 @@ mod decl { #[derive(FromArgs)] #[allow(unused)] struct RegisterArgs { - #[pyarg(positional)] + #[pyarg(any)] signum: i32, - #[pyarg(any, default)] + #[pyarg(any, default, py_default = "sys.stderr")] file: OptionalArg, - #[pyarg(any, default = true)] - all_threads: bool, - #[pyarg(any, default)] - chain: bool, + #[pyarg(any, default = ArgIntoBool::TRUE)] + all_threads: ArgIntoBool, + #[pyarg(any, default = ArgIntoBool::FALSE)] + chain: ArgIntoBool, } #[cfg(unix)] @@ -886,13 +950,13 @@ mod decl { fn register(args: RegisterArgs, vm: &VirtualMachine) -> PyResult<()> { check_signum(args.signum, vm)?; - let fd = get_fd_from_file_opt(args.file, vm)?; + let (fd, _file) = get_fd_from_file_opt(args.file, vm)?; host_faulthandler::register_user_signal( args.signum, fd, - args.all_threads, - args.chain, + args.all_threads.into_bool(), + args.chain.into_bool(), faulthandler_user_signal, ) .map_err(|_| { @@ -930,8 +994,8 @@ mod decl { #[derive(FromArgs)] #[allow(dead_code)] struct SigsegvArgs { - #[pyarg(positional, default)] - release_gil: bool, + #[pyarg(positional, default = ArgIntoBool::FALSE)] + release_gil: ArgIntoBool, } #[pyfunction] @@ -1037,4 +1101,57 @@ mod decl { suppress_crash_report(); host_faulthandler::raise_exception(args.code, args.flags); } + + #[cfg(test)] + #[cfg(any(unix, windows))] + mod tests { + use super::*; + use std::sync::mpsc; + use std::time::Instant; + + #[test] + fn watchdog_notification_does_not_expire_timeout() { + let state = Arc::new(( + Mutex::new(WatchdogState { + cancel: false, + fd: 2, + timeout_us: 60_000_000, + max_threads: 100, + repeat: false, + exit: false, + header: String::new(), + #[cfg(feature = "threading")] + thread_frame_slots: Vec::new(), + }), + Condvar::new(), + )); + let worker_state = Arc::clone(&state); + let (done_tx, done_rx) = mpsc::channel(); + let worker = thread::spawn(move || { + watchdog_thread(worker_state); + done_tx.send(()).unwrap(); + }); + + // Wait for a real waiter so the notification cannot be lost before + // the watchdog starts. No Python frames are exposed to this worker. + let deadline = Instant::now() + Duration::from_secs(5); + let notified = loop { + if state.1.notify_one() { + break true; + } + if Instant::now() >= deadline { + break false; + } + thread::sleep(Duration::from_millis(1)); + }; + let completed = done_rx.recv_timeout(Duration::from_millis(100)); + + // Always stop and join before asserting, including failure paths. + state.0.lock().cancel = true; + state.1.notify_all(); + worker.join().unwrap(); + assert!(notified, "watchdog did not start waiting"); + assert!(matches!(completed, Err(mpsc::RecvTimeoutError::Timeout))); + } + } } diff --git a/crates/stdlib/src/fcntl.rs b/crates/stdlib/src/fcntl.rs index a6dfdeb63b1..c3a8c82e6e6 100644 --- a/crates/stdlib/src/fcntl.rs +++ b/crates/stdlib/src/fcntl.rs @@ -7,14 +7,18 @@ mod fcntl { use rustpython_host_env::fcntl as host_fcntl; use crate::vm::{ - PyResult, VirtualMachine, - builtins::PyIntRef, + AsObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyBytes, PyStr}, convert::ToPyException, - function::{ArgMemoryBuffer, ArgStrOrBytesLike, Either, OptionalArg}, + function::ArgStrOrBytesLike, + protocol::{BufferFlags, PyBuffer}, stdlib::_io, }; use rustpython_host_env::io::is_interrupted_error; + #[cfg(not(target_os = "wasi"))] + use std::os::fd::BorrowedFd; + fn retry_on_eintr( vm: &VirtualMachine, mut call: impl FnMut() -> Result, @@ -44,13 +48,14 @@ mod fcntl { #[cfg(not(target_os = "wasi"))] #[pyattr] - use host_fcntl::{F_DUPFD, F_DUPFD_CLOEXEC, F_GETLK, F_SETLK, F_SETLKW}; + use host_fcntl::{ + F_DUPFD, F_DUPFD_CLOEXEC, F_GETLK, F_RDLCK, F_SETLK, F_SETLKW, F_UNLCK, F_WRLCK, LOCK_EX, + LOCK_NB, LOCK_SH, LOCK_UN, + }; #[cfg(not(any(target_os = "wasi", target_os = "redox")))] #[pyattr] - use host_fcntl::{ - F_GETOWN, F_RDLCK, F_SETOWN, F_UNLCK, F_WRLCK, LOCK_EX, LOCK_NB, LOCK_SH, LOCK_UN, - }; + use host_fcntl::{F_GETOWN, F_SETOWN}; #[cfg(target_vendor = "apple")] #[pyattr] @@ -83,10 +88,110 @@ mod fcntl { #[pyattr] use host_fcntl::F_GETPATH; + #[cfg(target_os = "linux")] + #[pyattr] + use host_fcntl::{FICLONE, FICLONERANGE}; + + const BUFFER_SIZE: usize = 1024; + const BUFFER_GUARD: [u8; 8] = [0, 0xfa, 0x69, 0xc4, 0x67, 0xa3, 0x6c, 0x58]; + + struct SyscallBuffer { + stack: [u8; BUFFER_SIZE + BUFFER_GUARD.len()], + heap: Option>, + len: usize, + } + + impl SyscallBuffer { + fn new(bytes: &[u8], vm: &VirtualMachine) -> PyResult { + let len = bytes.len(); + let mut buffer = Self { + stack: [0; BUFFER_SIZE + BUFFER_GUARD.len()], + heap: None, + len, + }; + if len > BUFFER_SIZE { + let size = len.checked_add(1).ok_or_else(|| vm.no_memory_error())?; + let mut heap = vm.new_zeroed_bytes(size)?; + heap[..len].copy_from_slice(bytes); + buffer.heap = Some(heap); + } else { + buffer.stack[..len].copy_from_slice(bytes); + buffer.stack[len..len + BUFFER_GUARD.len()].copy_from_slice(&BUFFER_GUARD); + } + Ok(buffer) + } + + fn as_mut_slice(&mut self) -> &mut [u8] { + self.heap.as_deref_mut().unwrap_or(&mut self.stack) + } + + fn check_guard( + &self, + operation: &str, + writable: bool, + vm: &VirtualMachine, + ) -> PyResult<()> { + // Like CPython, detect writes into the trailing guard. This cannot + // make a buffer safe for an operation requiring an arbitrary size. + let valid = match &self.heap { + Some(heap) => heap[self.len] == 0, + None => self.stack[self.len..self.len + BUFFER_GUARD.len()] == BUFFER_GUARD, + }; + if !valid { + let corruption = if self.heap.is_some() { + "Memory corruption" + } else { + "Possible stack corruption" + }; + let argument = if writable { + "a writable buffer argument" + } else { + "an argument" + }; + return Err(vm.new_system_error(format!( + "{corruption} in {operation}() due to buffer overflow. \ + Provide {argument} of sufficient size as determined by the operation." + ))); + } + Ok(()) + } + + fn into_bytes(self, operation: &str, vm: &VirtualMachine) -> PyResult> { + self.check_guard(operation, false, vm)?; + match self.heap { + Some(mut heap) => { + heap.truncate(self.len); + Ok(heap) + } + None => Ok(self.stack[..self.len].to_vec()), + } + } + } + + fn unsigned_mask(arg: &PyObjectRef, bits: u32, vm: &VirtualMachine) -> PyResult { + use num_traits::ToPrimitive; + + let value = arg.try_index(vm)?; + let valid_range = -(1i128 << (bits - 1))..=(1i128 << bits) - 1; + if !value + .as_bigint() + .to_i128() + .is_some_and(|value| valid_range.contains(&value)) + { + crate::vm::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "integer value out of range".to_owned(), + 1, + vm, + )?; + } + Ok(value.as_u64_mask()) + } + #[derive(FromArgs)] struct FcntlArg { #[pyarg(positional, default = 0)] - arg: Either, + arg: PyObjectRef, } #[pyfunction] @@ -96,26 +201,28 @@ mod fcntl { FcntlArg { arg }: FcntlArg, vm: &VirtualMachine, ) -> PyResult { - let int = match arg { - Either::A(arg) => { - let mut buf = [0u8; 1024]; - let arg_len; - { - let s = arg.borrow_bytes(); - arg_len = s.len(); - buf.get_mut(..arg_len) - .ok_or_else(|| vm.new_value_error("fcntl string arg too long"))? - .copy_from_slice(&s) - } - retry_on_eintr( - vm, - || host_fcntl::fcntl_with_bytes(fd, cmd, &mut buf[..arg_len]), - is_interrupted_error, - )?; - return Ok(vm.ctx.new_bytes(buf[..arg_len].to_vec()).into()); + if !arg.number().is_index() { + if !arg.check_buffer() && !arg.fast_isinstance(vm.ctx.types.str_type) { + return Err(vm.new_type_error(format!( + "fcntl() argument 3 must be an integer, a bytes-like object, or a string, not {}", + arg.class().name() + ))); } - Either::B(i) => i.as_u32_mask(), - }; + #[expect( + clippy::redundant_clone, + reason = "keep the original argument alive after releasing its buffer export" + )] + let buffer_arg = ArgStrOrBytesLike::try_from_object(vm, arg.clone())?; + let mut buf = SyscallBuffer::new(&buffer_arg.borrow_bytes(), vm)?; + drop(buffer_arg); + retry_on_eintr( + vm, + || host_fcntl::fcntl_with_bytes(fd, cmd, buf.as_mut_slice()), + is_interrupted_error, + )?; + return Ok(vm.ctx.new_bytes(buf.into_bytes("fcntl", vm)?).into()); + } + let int = unsigned_mask(&arg, u32::BITS, vm)? as u32; let ret = retry_on_eintr( vm, || host_fcntl::fcntl_int(fd, cmd, int as i32), @@ -127,112 +234,141 @@ mod fcntl { #[derive(FromArgs)] struct IoctlArgs { #[pyarg(positional, default = 0)] - arg: Either, i32>, + arg: PyObjectRef, #[pyarg(positional, default = true)] - mutate_flag: bool, + mutate_flag: PyObjectRef, } #[pyfunction] fn ioctl( _io::Fildes(fd): _io::Fildes, - request: i64, + request: PyObjectRef, IoctlArgs { arg, mutate_flag }: IoctlArgs, vm: &VirtualMachine, ) -> PyResult { - let mutate_flag = OptionalArg::Present(mutate_flag); - let request = host_fcntl::normalize_ioctl_request(request); - match arg { - Either::A(buf_kind) => { - const BUF_SIZE: usize = 1024; - let mut buf = [0u8; BUF_SIZE + 1]; // nul byte - let mut fill_buf = |b: &[u8]| { - if b.len() > BUF_SIZE { - return Err(vm.new_value_error("fcntl string arg too long")); - } - buf[..b.len()].copy_from_slice(b); - Ok(b.len()) - }; - let buf_len = match buf_kind { - Either::A(rw_arg) => { - let mutate_flag = mutate_flag.unwrap_or(true); - if mutate_flag { - // A terminal or a socket answers an ioctl when it is - // ready to, so the call runs detached, and the target's - // bytes go in and come back through a buffer of our own - // rather than stay locked meanwhile -- `fcntl_ioctl_impl` - // copies through one the same way. - let mut scratch = vm.new_zeroed_bytes(rw_arg.len())?; - scratch.copy_from_slice(&rw_arg.borrow_buf_mut()); - let ret = retry_on_eintr( - vm, - || unsafe { - host_fcntl::ioctl_ptr(fd, request, scratch.as_mut_ptr().cast()) - }, - is_interrupted_error, - )?; - rw_arg.borrow_buf_mut().copy_from_slice(&scratch); - return Ok(vm.ctx.new_int(ret).into()); - } - // treat like an immutable buffer - fill_buf(&rw_arg.borrow_buf_mut())? + let request = unsigned_mask(&request, libc::c_ulong::BITS, vm)? as libc::c_ulong; + // Clinic converts mutate_flag before the implementation examines arg. + let mutate_flag = mutate_flag.try_to_bool(vm)?; + if arg.number().is_index() { + let arg = arg.try_index(vm)?.try_to_primitive::(vm)?; + let ret = retry_on_eintr( + vm, + || host_fcntl::ioctl_int(fd, request, arg), + is_interrupted_error, + )?; + return Ok(vm.ctx.new_int(ret).into()); + } + if !arg.check_buffer() && !arg.fast_isinstance(vm.ctx.types.str_type) { + return Err(vm.new_type_error(format!( + "ioctl() argument 3 must be an integer, a bytes-like object, or a string, not {}", + arg.class().name() + ))); + } + + if mutate_flag && !arg.downcastable::() && !arg.downcastable::() { + match PyBuffer::from_object(vm, &arg, BufferFlags::WRITABLE) { + Ok(buffer) => { + let mut scratch = { + let bytes = buffer.as_contiguous_mut().ok_or_else(|| { + vm.new_buffer_error("underlying buffer is not C-contiguous") + })?; + SyscallBuffer::new(&bytes, vm)? + }; + // Keep the export alive, but not its lock, while detached. + // Small writable buffers need the same overflow guard as + // immutable buffers, rather than an exact-size allocation. + let ret = retry_on_eintr( + vm, + || unsafe { + host_fcntl::ioctl_ptr( + fd, + request, + scratch.as_mut_slice().as_mut_ptr().cast(), + ) + }, + is_interrupted_error, + )?; + { + let mut bytes = buffer.as_contiguous_mut().ok_or_else(|| { + vm.new_buffer_error("underlying buffer is not C-contiguous") + })?; + let len = bytes.len(); + bytes.copy_from_slice(&scratch.as_mut_slice()[..len]); } - Either::B(ro_buf) => fill_buf(&ro_buf.borrow_bytes())?, - }; - retry_on_eintr( - vm, - || unsafe { host_fcntl::ioctl_ptr(fd, request, buf.as_mut_ptr().cast()) }, - is_interrupted_error, - )?; - Ok(vm.ctx.new_bytes(buf[..buf_len].to_vec()).into()) - } - Either::B(i) => { - let ret = retry_on_eintr( - vm, - || host_fcntl::ioctl_int(fd, request, i), - is_interrupted_error, - )?; - Ok(vm.ctx.new_int(ret).into()) + drop(buffer); + scratch.check_guard("ioctl", true, vm)?; + return Ok(vm.ctx.new_int(ret).into()); + } + Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.buffer_error) => {} + Err(exc) => return Err(exc), } } + #[expect( + clippy::redundant_clone, + reason = "keep the original argument alive after releasing its buffer export" + )] + let buffer_arg = ArgStrOrBytesLike::try_from_object(vm, arg.clone())?; + let mut buf = SyscallBuffer::new(&buffer_arg.borrow_bytes(), vm)?; + drop(buffer_arg); + retry_on_eintr( + vm, + || unsafe { + host_fcntl::ioctl_ptr(fd, request, buf.as_mut_slice().as_mut_ptr().cast()) + }, + is_interrupted_error, + )?; + Ok(vm.ctx.new_bytes(buf.into_bytes("ioctl", vm)?).into()) } - // XXX: at the time of writing, wasi and redox don't have the necessary constants/function - #[cfg(not(any(target_os = "wasi", target_os = "redox")))] + // XXX: at the time of writing, wasi doesn't have the necessary constants/function + #[cfg(not(target_os = "wasi"))] #[pyfunction] - fn flock(_io::Fildes(fd): _io::Fildes, operation: i32, vm: &VirtualMachine) -> PyResult { + fn flock(_io::Fildes(fd): _io::Fildes, operation: i32, vm: &VirtualMachine) -> PyResult<()> { + // SAFETY: fd's owner isn't dropped before flock ends. + let fd = unsafe { BorrowedFd::borrow_raw(fd) }; // LOCK_EX without LOCK_NB waits for whoever holds the lock, which may // be for good. - let ret = retry_on_eintr( + retry_on_eintr( vm, - || host_fcntl::flock(fd, operation), + || host_fcntl::flock(&fd, operation), is_interrupted_error, )?; - Ok(vm.ctx.new_int(ret).into()) + Ok(()) } #[derive(FromArgs)] struct LockfArgs { #[pyarg(positional, default = 0)] - len: PyIntRef, + len: PyObjectRef, #[pyarg(positional, default = 0)] - start: PyIntRef, + start: PyObjectRef, #[pyarg(positional, default)] whence: i32, } - // XXX: at the time of writing, wasi and redox don't have the necessary constants - #[cfg(not(any(target_os = "wasi", target_os = "redox")))] + // XXX: at the time of writing, wasi doesn't have the necessary constants + #[cfg(not(target_os = "wasi"))] #[pyfunction] fn lockf( _io::Fildes(fd): _io::Fildes, cmd: i32, LockfArgs { len, start, whence }: LockfArgs, vm: &VirtualMachine, - ) -> PyResult { - let start = start.try_to_primitive(vm)?; - let len = len.try_to_primitive(vm)?; + ) -> PyResult<()> { + host_fcntl::lockf_type(cmd).map_err(|e| e.to_pyexception(vm))?; + // Clinic converts whence first. The implementation then validates cmd + // and converts start before len, using C long for index-only objects. + let offset = |obj: &PyObjectRef| -> PyResult { + let value = obj.try_index(vm)?; + if !obj.downcastable::() { + value.try_to_primitive::(vm)?; + } + value.try_to_primitive(vm) + }; + let start = offset(&start)?; + let len = offset(&len)?; // F_LOCK and F_TLOCK differ in exactly this: the first one waits. - let ret = retry_on_eintr( + retry_on_eintr( vm, || host_fcntl::lockf(fd, cmd, len, start, whence), |err| match err { @@ -240,6 +376,6 @@ mod fcntl { _ => false, }, )?; - Ok(vm.ctx.new_int(ret).into()) + Ok(()) } } diff --git a/crates/stdlib/src/grp.rs b/crates/stdlib/src/grp.rs index 5e73f5648d4..2dd08748c68 100644 --- a/crates/stdlib/src/grp.rs +++ b/crates/stdlib/src/grp.rs @@ -5,9 +5,10 @@ pub(crate) use grp::module_def; mod grp { use crate::vm::{ PyObjectRef, PyResult, VirtualMachine, - builtins::{PyIntRef, PyListRef, PyUtf8StrRef}, - convert::{IntoPyException, ToPyObject}, + builtins::{PyListRef, PyUtf8StrRef}, + convert::{ToPyObject, TryFromObject}, exceptions, + stdlib::posix::module::RawGid, types::PyStructSequence, }; use core::hint::cold_path; @@ -44,23 +45,19 @@ mod grp { #[derive(FromArgs)] struct GetGrGidArgs { #[pyarg(any)] - id: PyIntRef, + id: PyObjectRef, } #[pyfunction] fn getgrgid(id: GetGrGidArgs, vm: &VirtualMachine) -> PyResult { - let gid = id.id; - let gr_gid = gid.as_bigint(); - let gid = host_grp::gid_t::try_from(gr_gid).ok(); - let group = gid - .map(host_grp::getgrgid) - .transpose() - .map_err(|err| err.into_pyexception(vm))? - .flatten(); - let group = group.ok_or_else(|| { + let gid = RawGid::try_from_object(vm, id.id)?.0; + let group = host_grp::getgrgid(gid).ok().flatten().ok_or_else(|| { vm.new_key_error( vm.ctx - .new_str(format!("getgrgid: group id {gr_gid} not found")) + .new_str(format!( + "getgrgid(): gid not found: {}", + if gid == u32::MAX { -1 } else { i64::from(gid) } + )) .into(), ) })?; @@ -81,8 +78,7 @@ mod grp { return Err(exceptions::nul_char_error(vm)); } let gr_name = name.as_str(); - let group = host_grp::getgrnam(gr_name).map_err(|err| err.into_pyexception(vm))?; - let group = group.ok_or_else(|| { + let group = host_grp::getgrnam(gr_name).ok().flatten().ok_or_else(|| { vm.new_key_error( vm.ctx .new_str(format!("getgrnam: group name {gr_name} not found")) diff --git a/crates/stdlib/src/hashlib.rs b/crates/stdlib/src/hashlib.rs index f28f27b1055..2eddb1aedcd 100644 --- a/crates/stdlib/src/hashlib.rs +++ b/crates/stdlib/src/hashlib.rs @@ -8,13 +8,13 @@ pub(crate) use _hashlib::module_def; #[pymodule] pub(crate) mod _hashlib { use crate::vm::{ - Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, + Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, builtins::{ PyBaseExceptionRef, PyBytes, PyFrozenSet, PyStr, PyType, PyTypeRef, PyUtf8StrRef, PyValueError, }, class::StaticType, - function::{ArgBytesLike, ArgStrOrBytesLike, FuncArgs, OptionalArg}, + function::{ArgBytesLike, ArgCInt, ArgIntoBool, ArgStrOrBytesLike, FuncArgs, OptionalArg}, types::{Constructor, Representable}, }; use core::mem::MaybeUninit; @@ -67,52 +67,195 @@ pub(crate) mod _hashlib { dict.into() } + #[derive(Debug)] + struct HashName(PyUtf8StrRef); + + impl TryFromObject for HashName { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + if !obj.downcastable::() { + let name = if vm.is_none(&obj) { + "None".into() + } else { + obj.class().slot_name() + }; + let mut end = name.len().min(50); + while !name.is_char_boundary(end) { + end -= 1; + } + return Err(vm.new_type_error(format!( + "new() argument 'name' must be str, not {}", + &name[..end] + ))); + } + let name = PyUtf8StrRef::try_from_object(vm, obj)?; + if name.as_str().contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + Ok(Self(name)) + } + } + #[derive(FromArgs, Debug)] #[allow(unused)] struct NewHashArgs { #[pyarg(any)] - name: PyUtf8StrRef, + name: PyObjectRef, // Missing still allows the string keyword; b'' does not. #[pyarg(any, optional, py_default = "b''")] - data: OptionalArg, - #[pyarg(named, default = true)] - usedforsecurity: bool, - // None means no string data. - #[pyarg(named, optional)] - string: Option, + data: OptionalArg, + #[pyarg(named, optional, py_default = "True")] + usedforsecurity: OptionalArg, + // Preserve explicit None as a supplied argument. + #[pyarg(named, optional, py_default = "None")] + string: OptionalArg, + } + + // Bind raw objects first: Clinic rejects unknown keywords before conversion. + // The two constructors share options, but have different digest defaults. + macro_rules! blake_args { + ($name:ident, $digest:literal, $signature:literal) => { + #[derive(FromArgs)] + pub(crate) struct $name { + #[pyarg(any, optional, py_default = "b''")] + data: OptionalArg, + #[pyarg(named, optional, py_default = $signature)] + digest_size: OptionalArg, + #[pyarg(flatten)] + options: BlakeOptions, + } + + impl $name { + fn convert(&self, vm: &VirtualMachine) -> PyResult { + let digest_size = match &self.digest_size { + OptionalArg::Present(value) => { + ArgCInt::try_from_object(vm, value.clone())?.value + } + OptionalArg::Missing => $digest, + }; + self.options.convert(&self.data, digest_size, vm) + } + } + }; } + blake_args!(Blake2bArgs, 64, "_blake2.blake2b.MAX_DIGEST_SIZE"); + blake_args!(Blake2sArgs, 32, "_blake2.blake2s.MAX_DIGEST_SIZE"); + #[derive(FromArgs)] - #[allow(unused)] - pub(crate) struct BlakeHashArgs { - #[pyarg(any, optional)] - pub data: OptionalArg, - #[pyarg(named, optional)] - digest_size: OptionalArg, - #[pyarg(named, optional)] + struct BlakeOptions { + #[pyarg(named, optional, py_default = "b''")] + key: OptionalArg, + #[pyarg(named, optional, py_default = "b''")] + salt: OptionalArg, + #[pyarg(named, optional, py_default = "b''")] + person: OptionalArg, + #[pyarg(named, optional, py_default = "1")] + fanout: OptionalArg, + #[pyarg(named, optional, py_default = "1")] + depth: OptionalArg, + #[pyarg(named, optional, py_default = "0")] + leaf_size: OptionalArg, + #[pyarg(named, optional, py_default = "0")] + node_offset: OptionalArg, + #[pyarg(named, optional, py_default = "0")] + node_depth: OptionalArg, + #[pyarg(named, optional, py_default = "0")] + inner_size: OptionalArg, + #[pyarg(named, optional, py_default = "False")] + last_node: OptionalArg, + #[pyarg(named, optional, py_default = "True")] + usedforsecurity: OptionalArg, + #[pyarg(named, optional, py_default = "None")] + string: OptionalArg, + } + + struct BlakeHashArgs { + data: OptionalArg, + digest_size: i32, key: OptionalArg, - #[pyarg(named, optional)] salt: OptionalArg, - #[pyarg(named, optional)] person: OptionalArg, - #[pyarg(named, optional)] - fanout: OptionalArg, - #[pyarg(named, optional)] - depth: OptionalArg, - #[pyarg(named, optional)] - leaf_size: OptionalArg, - #[pyarg(named, optional)] - node_offset: OptionalArg, - #[pyarg(named, optional)] - node_depth: OptionalArg, - #[pyarg(named, optional)] - inner_size: OptionalArg, - #[pyarg(named, default)] + fanout: i32, + depth: i32, + leaf_size: u64, + node_offset: u64, + node_depth: i32, + inner_size: i32, last_node: bool, - #[pyarg(named, default = true)] - usedforsecurity: bool, - #[pyarg(named, optional)] - pub string: Option, + } + + fn optional_conversion( + value: &OptionalArg, + vm: &VirtualMachine, + ) -> PyResult> { + value + .as_ref() + .into_option() + .map(|value| T::try_from_object(vm, value.clone())) + .transpose() + .map(OptionalArg::from_option) + } + + fn blake_int( + value: &OptionalArg, + default: i32, + vm: &VirtualMachine, + ) -> PyResult { + Ok(optional_conversion::(value, vm)? + .into_option() + .map_or(default, |value| value.value)) + } + + fn hash_bool( + value: &OptionalArg, + default: bool, + vm: &VirtualMachine, + ) -> PyResult { + Ok(optional_conversion::(value, vm)? + .into_option() + .map_or(default, ArgIntoBool::into_bool)) + } + + impl BlakeOptions { + fn convert( + &self, + data: &OptionalArg, + digest_size: i32, + vm: &VirtualMachine, + ) -> PyResult { + let key = optional_conversion(&self.key, vm)?; + let salt = optional_conversion(&self.salt, vm)?; + let person = optional_conversion(&self.person, vm)?; + let fanout = blake_int(&self.fanout, 1, vm)?; + let depth = blake_int(&self.depth, 1, vm)?; + let leaf_size = blake_unsigned( + &self.leaf_size, + u64::MAX >> (u64::BITS - core::ffi::c_ulong::BITS), + "unsigned long", + vm, + )?; + let node_offset = + blake_unsigned(&self.node_offset, u64::MAX, "unsigned long long", vm)?; + let node_depth = blake_int(&self.node_depth, 0, vm)?; + let inner_size = blake_int(&self.inner_size, 0, vm)?; + let last_node = hash_bool(&self.last_node, false, vm)?; + hash_bool(&self.usedforsecurity, true, vm)?; + let data = resolve_data(data, &self.string, vm)?; + Ok(BlakeHashArgs { + data, + digest_size, + key, + salt, + person, + fanout, + depth, + leaf_size, + node_offset, + node_depth, + inner_size, + last_node, + }) + } } #[derive(FromArgs, Debug)] @@ -120,21 +263,17 @@ pub(crate) mod _hashlib { pub(crate) struct HashArgs { // Missing still allows the string keyword; b'' does not. #[pyarg(any, optional, py_default = "b''")] - pub data: OptionalArg, - #[pyarg(named, default = true)] - usedforsecurity: bool, - // Missing string is None. - #[pyarg(named, optional)] - pub string: Option, + pub data: OptionalArg, + #[pyarg(named, optional, py_default = "True")] + usedforsecurity: OptionalArg, + // Missing and explicit None are distinct for the deprecated alias. + #[pyarg(named, optional, py_default = "None")] + pub string: OptionalArg, } - impl From for HashArgs { - fn from(args: NewHashArgs) -> Self { - Self { - data: args.data, - usedforsecurity: args.usedforsecurity, - string: args.string, - } + impl HashArgs { + fn convert(&self, vm: &VirtualMachine) -> PyResult> { + convert_hash_data(&self.data, &self.usedforsecurity, &self.string, vm) } } @@ -213,14 +352,35 @@ pub(crate) mod _hashlib { dklen: Option, } - fn resolve_data( - data: OptionalArg, - string: Option, + fn convert_hash_data( + data: &OptionalArg, + usedforsecurity: &OptionalArg, + string: &OptionalArg, vm: &VirtualMachine, ) -> PyResult> { - match (data.into_option(), string) { - (Some(d), None) => Ok(OptionalArg::Present(d)), - (None, Some(s)) => Ok(OptionalArg::Present(s)), + hash_bool(usedforsecurity, true, vm)?; + optional_conversion(&resolve_data(data, string, vm)?, vm) + } + + fn resolve_data( + data: &OptionalArg, + string: &OptionalArg, + vm: &VirtualMachine, + ) -> PyResult> { + match (data.as_ref().into_option(), string.as_ref().into_option()) { + (Some(d), None) => Ok(OptionalArg::Present(d.clone())), + (None, Some(s)) => { + crate::vm::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "the 'string' keyword parameter is deprecated since Python 3.15 \ + and slated for removal in Python 3.19; use the 'data' keyword \ + parameter or pass the data to hash as a positional argument instead" + .to_owned(), + 1, + vm, + )?; + Ok(OptionalArg::Present(s.clone())) + } (None, None) => Ok(OptionalArg::Missing), (Some(_), Some(_)) => Err(vm.new_type_error( "'data' and 'string' are mutually exclusive \ @@ -734,8 +894,8 @@ pub(crate) mod _hashlib { } #[pymethod] - fn update(zelf: &Py, data: ArgBytesLike) { - data.with_ref(|bytes| zelf.ctx.update(bytes)); + fn update(zelf: &Py, obj: ArgBytesLike) { + obj.with_ref(|bytes| zelf.ctx.update(bytes)); } #[pymethod] @@ -782,10 +942,11 @@ pub(crate) mod _hashlib { ) } - #[pyfunction(name = "new")] - fn hashlib_new(args: NewHashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; - match args.name.as_str().to_lowercase().as_str() { + #[pyfunction] + fn new(args: NewHashArgs, vm: &VirtualMachine) -> PyResult { + let name = HashName::try_from_object(vm, args.name.clone())?; + let data = convert_hash_data(&args.data, &args.usedforsecurity, &args.string, vm)?; + match name.0.as_str().to_lowercase().as_str() { "md5" => Ok(new_fixed_hasher("md5", data).into_pyobject(vm)), "sha1" => Ok(new_fixed_hasher("sha1", data).into_pyobject(vm)), "sha224" => Ok(new_fixed_hasher("sha224", data).into_pyobject(vm)), @@ -804,90 +965,101 @@ pub(crate) mod _hashlib { } } - #[pyfunction(name = "openssl_md5")] - pub(crate) fn local_md5(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_md5(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("md5", data)) } - #[pyfunction(name = "openssl_sha1")] - pub(crate) fn local_sha1(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha1(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha1", data)) } - #[pyfunction(name = "openssl_sha224")] - pub(crate) fn local_sha224(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha224(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha224", data)) } - #[pyfunction(name = "openssl_sha256")] - pub(crate) fn local_sha256(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha256(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha256", data)) } - #[pyfunction(name = "openssl_sha384")] - pub(crate) fn local_sha384(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha384(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha384", data)) } - #[pyfunction(name = "openssl_sha512")] - pub(crate) fn local_sha512(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha512(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha512", data)) } - #[pyfunction(name = "openssl_sha3_224")] - pub(crate) fn local_sha3_224(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha3_224(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha3_224", data)) } - #[pyfunction(name = "openssl_sha3_256")] - pub(crate) fn local_sha3_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha3_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha3_256", data)) } - #[pyfunction(name = "openssl_sha3_384")] - pub(crate) fn local_sha3_384(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha3_384(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha3_384", data)) } - #[pyfunction(name = "openssl_sha3_512")] - pub(crate) fn local_sha3_512(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_sha3_512(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_fixed_hasher("sha3_512", data)) } - #[pyfunction(name = "openssl_shake_128")] - pub(crate) fn local_shake_128(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_shake_128(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_xof_hasher("shake_128", data)) } - #[pyfunction(name = "openssl_shake_256")] - pub(crate) fn local_shake_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { - let data = resolve_data(args.data, args.string, vm)?; + #[pyfunction] + pub(crate) fn openssl_shake_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { + let data = args.convert(vm)?; Ok(new_xof_hasher("shake_256", data)) } - fn parse_unsigned_int(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + fn blake_unsigned( + obj: &OptionalArg, + max: u64, + c_type: &str, + vm: &VirtualMachine, + ) -> PyResult { + let Some(obj) = obj.as_ref().into_option() else { + return Ok(0); + }; let value = obj.try_index(vm)?; if value.as_bigint().sign() == malachite_bigint::Sign::Minus { return Err(vm.new_value_error("Cannot convert negative int")); } - value.try_to_primitive(vm) + let overflow = || vm.new_overflow_error(format!("Python int too large for C {c_type}")); + let value = value.try_to_primitive::(vm).map_err(|_| overflow())?; + if value > max { + return Err(overflow()); + } + Ok(value) } struct Blake2Limits { name: &'static str, - display: &'static str, - default_digest_size: i64, max_digest_size: usize, max_key_size: usize, max_salt_size: usize, @@ -946,105 +1118,89 @@ pub(crate) mod _hashlib { ) -> PyResult { let Blake2Limits { name, - display, - default_digest_size, max_digest_size, max_key_size, max_salt_size, max_person_size, max_node_offset, } = limits; - let data = resolve_data(args.data, args.string, vm)?; - let digest_size = args.digest_size.unwrap_or(default_digest_size); + let data = args.data; + let digest_size = args.digest_size; if digest_size < 1 || digest_size as u64 > max_digest_size as u64 { return Err(vm.new_value_error(format!( - "digest_size for {display} must be between 1 and {max_digest_size} bytes, here it is {digest_size}" + "digest_size for {name} must be between 1 and {max_digest_size} bytes, got {digest_size}" ))); } let digest_size = digest_size as usize; - let empty: &[u8] = &[]; - let key_buf; - let salt_buf; - let person_buf; - let key = match args.key { - OptionalArg::Present(ref buf) => { - key_buf = buf.borrow_buf(); - &*key_buf - } - OptionalArg::Missing => empty, - }; - let salt = match args.salt { - OptionalArg::Present(ref buf) => { - salt_buf = buf.borrow_buf(); - &*salt_buf - } - OptionalArg::Missing => empty, - }; - let person = match args.person { - OptionalArg::Present(ref buf) => { - person_buf = buf.borrow_buf(); - &*person_buf + for (name, buffer, max) in [ + ("key", &args.key, max_key_size), + ("salt", &args.salt, max_salt_size), + ("person", &args.person, max_person_size), + ] { + let len = buffer + .as_ref() + .into_option() + .map_or(0, |buffer| buffer.len()); + if len > max { + return Err( + vm.new_value_error(format!("maximum {name} length is {max} bytes, got {len}")) + ); } - OptionalArg::Missing => empty, - }; - - if salt.len() > max_salt_size { - return Err(vm.new_value_error(format!("maximum salt length is {max_salt_size} bytes"))); - } - if person.len() > max_person_size { - return Err( - vm.new_value_error(format!("maximum person length is {max_person_size} bytes")) - ); } - let fanout = args.fanout.unwrap_or(1); + let fanout = args.fanout; if !(0..=255).contains(&fanout) { - return Err(vm.new_value_error("fanout must be between 0 and 255")); + return Err(vm.new_value_error("'fanout' must be between 0 and 255")); } - let depth = args.depth.unwrap_or(1); + let depth = args.depth; if !(1..=255).contains(&depth) { - return Err(vm.new_value_error("depth must be between 1 and 255")); + return Err(vm.new_value_error("'depth' must be between 1 and 255")); } - let leaf_size = match args.leaf_size.into_option() { - Some(obj) => { - let value = parse_unsigned_int(&obj, vm)?; - u32::try_from(value).map_err(|_| vm.new_overflow_error("leaf_size is too large"))? - } - None => 0, - }; - let node_offset = match args.node_offset.into_option() { - Some(obj) => { - let value = parse_unsigned_int(&obj, vm)?; - if value > max_node_offset { - return Err(vm.new_overflow_error("node_offset is too large")); - } - value - } - None => 0, - }; - - let node_depth = args.node_depth.unwrap_or(0); + let node_depth = args.node_depth; if !(0..=255).contains(&node_depth) { - return Err(vm.new_value_error("node_depth must be between 0 and 255")); + return Err(vm.new_value_error("'node_depth' must be between 0 and 255")); } - let inner_size = args.inner_size.unwrap_or(0); + let inner_size = args.inner_size; if inner_size < 0 || inner_size as u64 > max_digest_size as u64 { return Err(vm.new_value_error(format!( - "inner_size must be between 0 and is {max_digest_size}" + "'inner_size' must be between 0 and {max_digest_size}" ))); } - if key.len() > max_key_size { - return Err(vm.new_value_error(format!("maximum key length is {max_key_size} bytes"))); + let leaf_size = u32::try_from(args.leaf_size) + .map_err(|_| vm.new_overflow_error("'leaf_size' is too large"))?; + let node_offset = args.node_offset; + if node_offset > max_node_offset { + return Err(vm.new_overflow_error("'node_offset' is too large")); } + // Snapshot mutable options one at a time, without nested exporter locks. + // Keep their exports alive while acquiring the initial data buffer. + let key = args + .key + .as_ref() + .into_option() + .map(|buf| buf.borrow_buf_unlocked(vm)) + .transpose()?; + let salt = args + .salt + .as_ref() + .into_option() + .map(|buf| buf.borrow_buf_unlocked(vm)) + .transpose()?; + let person = args + .person + .as_ref() + .into_option() + .map(|buf| buf.borrow_buf_unlocked(vm)) + .transpose()?; let ctx = HashCtx::new_blake2( name, digest_size, - key, - salt, - person, + key.as_deref().unwrap_or(&[]), + salt.as_deref().unwrap_or(&[]), + person.as_deref().unwrap_or(&[]), fanout as u8, depth as u8, leaf_size, @@ -1055,7 +1211,7 @@ pub(crate) mod _hashlib { ) .ok_or_else(|| vm.new_value_error(format!("failed to initialize {name}")))?; if let OptionalArg::Present(d) = data { - d.with_ref(|bytes| ctx.update(bytes)); + ArgBytesLike::try_from_object(vm, d)?.with_ref(|bytes| ctx.update(bytes)); } Ok(Blake2Hash { name, @@ -1064,47 +1220,43 @@ pub(crate) mod _hashlib { }) } - pub(crate) fn local_blake2b(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_blake2b(args: Blake2bArgs, vm: &VirtualMachine) -> PyResult { blake2_hasher( Blake2Limits { name: "blake2b", - display: "Blake2b", - default_digest_size: 64, max_digest_size: 64, max_key_size: 64, max_salt_size: 16, max_person_size: 16, max_node_offset: u64::MAX, }, - args, + args.convert(vm)?, vm, ) } - pub(crate) fn local_blake2s(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { + pub(crate) fn local_blake2s(args: Blake2sArgs, vm: &VirtualMachine) -> PyResult { blake2_hasher( Blake2Limits { name: "blake2s", - display: "Blake2s", - default_digest_size: 32, max_digest_size: 32, max_key_size: 32, max_salt_size: 8, max_person_size: 8, max_node_offset: (1 << 48) - 1, }, - args, + args.convert(vm)?, vm, ) } - #[pyfunction(name = "openssl_blake2b")] - fn openssl_blake2b(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { + #[pyfunction] + fn openssl_blake2b(args: Blake2bArgs, vm: &VirtualMachine) -> PyResult { Ok(local_blake2b(args, vm)?.into_hasher()) } - #[pyfunction(name = "openssl_blake2s")] - fn openssl_blake2s(args: BlakeHashArgs, vm: &VirtualMachine) -> PyResult { + #[pyfunction] + fn openssl_blake2s(args: Blake2sArgs, vm: &VirtualMachine) -> PyResult { Ok(local_blake2s(args, vm)?.into_hasher()) } diff --git a/crates/stdlib/src/json.rs b/crates/stdlib/src/json.rs index 8b9da96cc8e..280f7011333 100644 --- a/crates/stdlib/src/json.rs +++ b/crates/stdlib/src/json.rs @@ -5,12 +5,13 @@ mod _json { use crate::vm::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, builtins::{ - PyBaseExceptionRef, PyDict, PyFloat, PyInt, PyList, PyStr, PyStrRef, PyTuple, PyType, + PyAnyDict, PyBaseExceptionRef, PyDict, PyDictRef, PyFloat, PyInt, PyList, PyListRef, + PyStr, PyStrRef, PyTuple, PyType, }, convert::ToPyResult, - function::{IntoFuncArgs, OptionalArg}, + function::{ArgIntoBool, IntoFuncArgs}, protocol::PyIterReturn, - types::{Callable, Constructor, PyComparisonOp}, + types::{Callable, Constructor}, }; use core::cell::RefCell; use core::str::FromStr; @@ -19,7 +20,7 @@ mod _json { json, wtf8::{Wtf8, Wtf8Buf}, }; - use std::collections::{HashMap, HashSet}; + use std::collections::HashMap; /// Skip JSON whitespace characters (space, tab, newline, carriage return). /// Works with a byte slice and returns the number of bytes skipped. @@ -51,6 +52,7 @@ mod _json { strict: bool, object_hook: Option, object_pairs_hook: Option, + array_hook: Option, parse_float: Option, parse_int: Option, parse_constant: PyObjectRef, @@ -64,6 +66,7 @@ mod _json { let strict = ctx.get_attr("strict", vm)?.try_to_bool(vm)?; let object_hook = vm.option_if_none(ctx.get_attr("object_hook", vm)?); let object_pairs_hook = vm.option_if_none(ctx.get_attr("object_pairs_hook", vm)?); + let array_hook = vm.option_if_none(ctx.get_attr("array_hook", vm)?); let parse_float = ctx.get_attr("parse_float", vm)?; let parse_float = if vm.is_none(&parse_float) || parse_float.is(vm.ctx.types.float_type) { @@ -83,6 +86,7 @@ mod _json { strict, object_hook, object_pairs_hook, + array_hook, parse_float, parse_int, parse_constant, @@ -93,6 +97,11 @@ mod _json { #[pyclass(with(Callable, Constructor))] impl JsonScanner { + #[pygetset] + fn array_hook(zelf: &Py) -> Option { + zelf.array_hook.clone() + } + fn parse( &self, pystr: PyStrRef, @@ -437,7 +446,7 @@ mod _json { // Check for empty array if bytes.get(byte_idx) == Some(&b']') { - return Ok((vm.ctx.new_list(vec![]).into(), char_idx + 1, byte_idx + 1)); + return self.finalize_array(vec![], char_idx + 1, byte_idx + 1, vm); } let mut values: Vec = Vec::new(); @@ -493,7 +502,23 @@ mod _json { } } - Ok((vm.ctx.new_list(values).into(), char_idx, byte_idx)) + self.finalize_array(values, char_idx, byte_idx, vm) + } + + fn finalize_array( + &self, + values: Vec, + end_char_idx: usize, + end_byte_idx: usize, + vm: &VirtualMachine, + ) -> PyResult<(PyObjectRef, usize, usize)> { + let values = vm.ctx.new_list(values); + let result = if let Some(ref hook) = self.array_hook { + hook.call((values,), vm)? + } else { + values.into() + }; + Ok((result, end_char_idx, end_byte_idx)) } /// Finalize object construction with hooks. @@ -546,7 +571,7 @@ mod _json { // `'[' * 50000 + ']' * 50000` overflows the native Rust stack and // crashes the process with SIGSEGV. Matches CPython's // _Py_EnterRecursiveCall in Modules/_json.c. - vm.with_recursion("while decoding a JSON object from a string", || { + vm.with_recursion(" while decoding a JSON object from a string", || { let bytes = pystr.as_bytes(); let wtf8 = pystr.as_wtf8(); @@ -694,13 +719,13 @@ mod _json { } #[pyfunction] - fn encode_basestring(object: PyStrRef) -> Wtf8Buf { - json::encode_string(object.as_wtf8(), false) + fn encode_basestring(pystr: PyStrRef) -> Wtf8Buf { + json::encode_string(pystr.as_wtf8(), false) } #[pyfunction] - fn encode_basestring_ascii(object: PyStrRef) -> Wtf8Buf { - json::encode_string(object.as_wtf8(), true) + fn encode_basestring_ascii(pystr: PyStrRef) -> Wtf8Buf { + json::encode_string(pystr.as_wtf8(), true) } /// Which Rust-native string escaper (if any) the `encoder` callable is @@ -764,8 +789,7 @@ mod _json { #[pyclass(name = "Encoder", traverse)] #[derive(Debug, PyPayload)] struct JsonEncoder { - #[pytraverse(skip)] - check_circular: bool, + markers: Option, default: PyObjectRef, encoder: PyObjectRef, #[pytraverse(skip)] @@ -780,44 +804,53 @@ mod _json { skipkeys: bool, #[pytraverse(skip)] allow_nan: bool, - #[pytraverse(skip)] - markers: crate::vm::common::lock::PyMutex>, + } + + #[derive(FromArgs)] + #[from_args(legacy, fname = "make_encoder")] + struct EncoderArgs { + #[pyarg(any)] + markers: PyObjectRef, + #[pyarg(any)] + default: PyObjectRef, + #[pyarg(any)] + encoder: PyObjectRef, + #[pyarg(any)] + indent: PyObjectRef, + #[pyarg(any)] + key_separator: PyStrRef, + #[pyarg(any)] + item_separator: PyStrRef, + #[pyarg(any)] + sort_keys: ArgIntoBool, + #[pyarg(any)] + skipkeys: ArgIntoBool, + #[pyarg(any)] + allow_nan: ArgIntoBool, } impl Constructor for JsonEncoder { - // markers, default, encoder, indent, key_separator, item_separator, - // sort_keys, skipkeys, allow_nan -- exactly as `encoder.py` calls - // `c_make_encoder`. - // Nested tuple: `FromArgs` is only implemented up to 8-tuples, and - // nested tuples count as a single top-level slot while still - // consuming their own positional arguments in order. - type Args = ( - PyObjectRef, - PyObjectRef, - PyObjectRef, - PyObjectRef, - PyStrRef, - PyStrRef, - (PyObjectRef, PyObjectRef, PyObjectRef), - ); + type Args = EncoderArgs; fn py_new( _cls: &Py, - ( + EncoderArgs { markers, default, encoder, indent, key_separator, item_separator, - (sort_keys, skipkeys, allow_nan), - ): Self::Args, + sort_keys, + skipkeys, + allow_nan, + }: Self::Args, vm: &VirtualMachine, ) -> PyResult { - let check_circular = if vm.is_none(&markers) { - false - } else if markers.downcast_ref::().is_some() { - true + let markers = if vm.is_none(&markers) { + None + } else if let Ok(markers) = markers.clone().downcast::() { + Some(markers) } else { return Err(vm.new_type_error(format!( "make_encoder() argument 1 must be dict or None, not {}", @@ -836,9 +869,9 @@ mod _json { ))); }; - let sort_keys = sort_keys.try_to_bool(vm)?; - let skipkeys = skipkeys.try_to_bool(vm)?; - let allow_nan = allow_nan.try_to_bool(vm)?; + let sort_keys = sort_keys.into_bool(); + let skipkeys = skipkeys.into_bool(); + let allow_nan = allow_nan.into_bool(); // Detect (by identity) whether `encoder` is one of our own // builtin string escapers, so the hot string-encoding path can @@ -859,7 +892,7 @@ mod _json { }; Ok(Self { - check_circular, + markers, default, encoder, encoder_kind, @@ -869,7 +902,6 @@ mod _json { sort_keys, skipkeys, allow_nan, - markers: crate::vm::common::lock::PyMutex::new(HashSet::new()), }) } } @@ -879,35 +911,39 @@ mod _json { /// being serialized when an error occurred), then return it unchanged so /// it can be re-raised. fn add_note(exc: PyBaseExceptionRef, note: Wtf8Buf, vm: &VirtualMachine) -> PyBaseExceptionRef { - // `PyBaseException::add_note` is `pub`, so call it directly instead + // `PyBaseException::add_note_str` is `pub`, so call it directly instead // of going through the generic attribute-lookup + call machinery. - let _ = exc.add_note(vm.ctx.new_str(note), vm); + let _ = exc.add_note_str(vm.ctx.new_str(note), vm); exc } #[pyclass(with(Callable, Constructor))] impl JsonEncoder { - /// Push `obj`'s id onto the recursion-detection set (a stand-in for - /// CPython's `markers` dict -- nothing outside this call ever reads - /// that dict back, so we don't need to actually mutate a real - /// Python dict object). Returns the id to later pass to - /// `pop_marker`, or `None` if circular-reference checking is - /// disabled. - fn push_marker(&self, obj: &PyObject, vm: &VirtualMachine) -> PyResult> { - if !self.check_circular { - return Ok(None); - } - let id = obj.get_id(); - if !self.markers.lock().insert(id) { - return Err(vm.new_value_error("Circular reference detected")); + #[pygetset] + fn markers(zelf: &Py) -> Option { + zelf.markers.clone() + } + + // The caller owns this dict and callbacks can inspect or mutate it. + // Use native dict operations even for subclasses, as PyDict_* does. + fn push_marker(&self, obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + if let Some(markers) = &self.markers { + let id = vm.ctx.new_int(obj.get_id()); + if markers.inner_getitem_opt(id.as_object(), vm)?.is_some() { + return Err(vm.new_value_error("Circular reference detected")); + } + markers.inner_setitem(id.as_object(), obj.to_owned(), vm)?; } - Ok(Some(id)) + Ok(()) } - fn pop_marker(&self, marker: Option) { - if let Some(id) = marker { - self.markers.lock().remove(&id); + // CPython removes markers only after successful encoding. Keeping them + // on errors also keeps the referenced objects alive for the caller. + fn pop_marker(&self, obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + if let Some(markers) = &self.markers { + markers.inner_delitem(vm.ctx.new_int(obj.get_id()).as_object(), vm)?; } + Ok(()) } /// `floatstr`: format a float per JSON rules, honouring `allow_nan`. @@ -1049,35 +1085,11 @@ mod _json { ))) } - /// `sorted(dct.items())`: sort dict items by key. Since dict keys - /// are unique, comparing keys alone reproduces tuple-comparison - /// semantics (the first differing element always decides). - fn sort_items( - &self, - mut items: Vec<(PyObjectRef, PyObjectRef)>, - vm: &VirtualMachine, - ) -> PyResult> { - // Use the VM's fallible timsort (the same one backing - // `list.sort`/`sorted`) instead of `Vec::sort_by`: a Python-level - // key comparison (`__lt__`) can raise partway through (e.g. - // comparing `str` and `int` keys), and `Vec::sort_by`'s - // comparator is infallible -- swallowing the error and reporting - // `Ordering::Equal` instead corrupts the sort's invariants and - // makes Rust's sort implementation panic with "comparison - // function does not correctly implement a total order", - // aborting the whole interpreter instead of propagating a - // catchable Python `TypeError` like CPython does. - crate::vm::sorting::timsort(&mut items, &mut |a, b| { - a.0.rich_compare_bool(&b.0, PyComparisonOp::Lt, vm) - })?; - Ok(items) - } - /// Encode a `list` or `tuple`. `len`/`get` re-read the live /// collection on every step (rather than working off a /// pre-collected snapshot) so that a `default()`/nested-encoder /// callback that shrinks the list mid-encode is observed the same - /// way CPython's `PySequence_Fast`-free direct indexing observes it + /// way CPython's live sequence iteration observes it /// (see `test_encode_mutated`: deleting the last element on every /// callback call causes encoding to stop early once the shrinking /// list's length catches up with the read cursor). @@ -1088,13 +1100,13 @@ mod _json { out: &mut Wtf8Buf, vm: &VirtualMachine, len: impl Fn() -> usize, - get: impl Fn(usize) -> PyObjectRef, + get: impl Fn(usize) -> Option, ) -> PyResult<()> { if len() == 0 { out.push_str("[]"); return Ok(()); } - let marker = self.push_marker(obj, vm)?; + self.push_marker(obj, vm)?; out.push_char('['); let new_level = if self.indent.is_some() { level + 1 @@ -1103,15 +1115,14 @@ mod _json { }; let mut i = 0; while i < len() { - let value = get(i); - if i == 0 { - self.push_newline_indent(out, new_level); - } else { + let Some(value) = get(i) else { + break; + }; + if i != 0 { out.push_wtf8(self.item_separator.as_wtf8()); - self.push_newline_indent(out, new_level); } + self.push_newline_indent(out, new_level); if let Err(e) = self.encode_value(&value, new_level, out, vm) { - self.pop_marker(marker); return Err(add_note( e, Wtf8Buf::from(format!("when serializing {} item {i}", obj.class().name())), @@ -1120,61 +1131,84 @@ mod _json { } i += 1; } + self.pop_marker(obj, vm)?; self.push_newline_indent(out, level); out.push_char(']'); - self.pop_marker(marker); Ok(()) } - /// Fetch `dct.items()` for encoding. For an exact `dict` this reads - /// the native table directly (matching CPython's fast path); for a - /// `dict` subclass (e.g. `collections.OrderedDict`) it calls the - /// real (possibly overridden) `.items()` method instead, so a - /// subclass's custom ordering/behavior is respected. + // Keep an exact items list alive rather than eagerly validating or + // copying its pairs: callbacks may change the next item or its length. fn dict_items( &self, obj: &PyObject, - dict: &Py, + dict: &PyAnyDict, vm: &VirtualMachine, - ) -> PyResult> { - if obj.class().is(vm.ctx.types.dict_type) { - return Ok(dict.items_vec()); + ) -> PyResult { + let items = if obj.class().is(vm.ctx.types.dict_type) + || obj.class().is(vm.ctx.types.frozendict_type) + { + vm.ctx.new_list( + dict.items_vec() + .into_iter() + .map(|(key, value)| vm.new_tuple((key, value)).into()) + .collect(), + ) + } else { + obj.try_mapping(vm)?.items(vm)?.try_into_value(vm)? + }; + if self.sort_keys { + // The mapping helper returns an exact list, so this uses the + // shared list sort including tuple comparison and mutation checks. + vm.call_method(items.as_object(), "sort", ())?; } - let items_obj = obj.get_attr("items", vm)?.call((), vm)?; - vm.extract_elements_with(&items_obj, |item| { - use crate::vm::builtins::PyTupleRef; - let tuple: PyTupleRef = item.try_into_value(vm)?; - if tuple.as_slice().len() != 2 { - return Err(vm.new_value_error("items() must return 2-tuples")); + Ok(items) + } + + fn encode_dict_item( + &self, + obj: &PyObject, + (key, value): (&PyObject, &PyObject), + first: &mut bool, + level: isize, + out: &mut Wtf8Buf, + vm: &VirtualMachine, + ) -> PyResult<()> { + let mut key_out = Wtf8Buf::new(); + if !self.write_dict_key(key, &mut key_out, vm)? { + return Ok(()); + } + if *first { + *first = false; + } else { + out.push_wtf8(self.item_separator.as_wtf8()); + } + self.push_newline_indent(out, level); + out.push_wtf8(&key_out); + out.push_wtf8(self.key_separator.as_wtf8()); + self.encode_value(value, level, out, vm).map_err(|e| { + let mut note = + Wtf8Buf::from(format!("when serializing {} item ", obj.class().name())); + if let Ok(r) = key.repr(vm) { + note.push_wtf8(r.as_wtf8()); } - let slice = tuple.as_slice(); - Ok((slice[0].clone(), slice[1].clone())) + add_note(e, note, vm) }) } fn encode_dict( &self, obj: &PyObject, - dict: &Py, + dict: &PyAnyDict, level: isize, out: &mut Wtf8Buf, vm: &VirtualMachine, ) -> PyResult<()> { - let mut items = self.dict_items(obj, dict, vm)?; - if items.is_empty() { + if dict.is_empty() { out.push_str("{}"); return Ok(()); } - let marker = self.push_marker(obj, vm)?; - if self.sort_keys { - items = match self.sort_items(items, vm) { - Ok(items) => items, - Err(e) => { - self.pop_marker(marker); - return Err(e); - } - }; - } + self.push_marker(obj, vm)?; out.push_char('{'); let new_level = if self.indent.is_some() { level + 1 @@ -1182,42 +1216,51 @@ mod _json { level }; let mut first = true; - for (key, value) in &items { - let mut key_out = Wtf8Buf::new(); - let wrote = match self.write_dict_key(key, &mut key_out, vm) { - Ok(wrote) => wrote, - Err(e) => { - self.pop_marker(marker); - return Err(e); - } - }; - if !wrote { - continue; - } - if first { - first = false; - self.push_newline_indent(out, new_level); - } else { - out.push_wtf8(self.item_separator.as_wtf8()); - self.push_newline_indent(out, new_level); + if self.sort_keys + || !(obj.class().is(vm.ctx.types.dict_type) + || obj.class().is(vm.ctx.types.frozendict_type)) + { + let items = self.dict_items(obj, dict, vm)?; + let mut index = 0; + loop { + // Release the list guard before any user code. Owning the + // tuple keeps its key/value alive even if the list shrinks. + let item = items.borrow_vec().get(index).cloned(); + let Some(item) = item else { break }; + let pair = item + .downcast_ref::() + .filter(|pair| pair.as_slice().len() == 2) + .ok_or_else(|| vm.new_value_error("items must return 2-tuples"))?; + self.encode_dict_item( + obj, + (&pair.as_slice()[0], &pair.as_slice()[1]), + &mut first, + new_level, + out, + vm, + )?; + index += 1; } - out.push_wtf8(&key_out); - out.push_wtf8(self.key_separator.as_wtf8()); - if let Err(e) = self.encode_value(value, new_level, out, vm) { - self.pop_marker(marker); - let mut note = - Wtf8Buf::from(format!("when serializing {} item ", obj.class().name())); - if let Ok(r) = key.repr(vm) { - note.push_wtf8(r.as_wtf8()); - } - return Err(add_note(e, note, vm)); + } else { + let mut position = 0; + // next_entry clones both references and releases the table + // lock before callbacks. Do not snapshot: later values and + // entries must reflect mutations made while encoding. + while let Some((next, key, value)) = dict.next_entry(position) { + position = next; + let result = + self.encode_dict_item(obj, (&key, &value), &mut first, new_level, out, vm); + // Match PyDict_Next's owned-reference release order even + // when callbacks remove these objects from the dictionary. + drop(key); + result?; } } + self.pop_marker(obj, vm)?; if !first { self.push_newline_indent(out, level); } out.push_char('}'); - self.pop_marker(marker); Ok(()) } @@ -1228,23 +1271,18 @@ mod _json { out: &mut Wtf8Buf, vm: &VirtualMachine, ) -> PyResult<()> { - let marker = self.push_marker(obj, vm)?; - let new_obj = match self.default.call((obj.to_owned(),), vm) { - Ok(v) => v, - Err(e) => { - self.pop_marker(marker); - return Err(e); - } - }; + self.push_marker(obj, vm)?; + let new_obj = self.default.call((obj.to_owned(),), vm)?; let result = self.encode_value(&new_obj, level, out, vm); - self.pop_marker(marker); + drop(new_obj); result.map_err(|e| { add_note( e, Wtf8Buf::from(format!("when serializing {} object", obj.class().name())), vm, ) - }) + })?; + self.pop_marker(obj, vm) } fn encode_value( @@ -1254,7 +1292,7 @@ mod _json { out: &mut Wtf8Buf, vm: &VirtualMachine, ) -> PyResult<()> { - vm.with_recursion("while encoding a JSON object", || { + vm.with_recursion(" while encoding a JSON object", || { if let Some(s) = obj.downcast_ref::() { self.write_str_obj(obj, s, out, vm) } else if vm.is_none(obj) { @@ -1280,12 +1318,19 @@ mod _json { out, vm, || list.borrow_vec().len(), - |i| list.borrow_vec()[i].clone(), + |i| list.borrow_vec().get(i).cloned(), ) } else if let Some(tuple) = obj.downcast_ref::() { let slice = tuple.as_slice(); - self.encode_list(obj, level, out, vm, || slice.len(), |i| slice[i].clone()) - } else if let Some(dict) = obj.downcast_ref::() { + self.encode_list( + obj, + level, + out, + vm, + || slice.len(), + |i| slice.get(i).cloned(), + ) + } else if let Some(dict) = PyAnyDict::from_object(obj) { self.encode_dict(obj, dict, level, out, vm) } else { self.encode_default(obj, level, out, vm) @@ -1294,11 +1339,29 @@ mod _json { } } - impl Callable for JsonEncoder { - type Args = (PyObjectRef, PyObjectRef); + #[derive(FromArgs)] + struct EncoderCallArgs { + #[pyarg(any)] + obj: PyObjectRef, + #[pyarg(any)] + _current_indent_level: PyObjectRef, + } - fn call(zelf: &Py, (obj, indent_level): Self::Args, vm: &VirtualMachine) -> PyResult { - let level: isize = indent_level.try_index(vm)?.try_to_primitive(vm)?; + impl Callable for JsonEncoder { + type Args = EncoderCallArgs; + + fn call( + zelf: &Py, + EncoderCallArgs { + obj, + _current_indent_level, + }: Self::Args, + vm: &VirtualMachine, + ) -> PyResult { + let level: isize = _current_indent_level.try_index(vm)?.try_to_primitive(vm)?; + // CPython starts its indent cache with indent * initial_level; + // negative string repetition produces the same prefix as zero. + let level = level.max(0); let mut out = Wtf8Buf::new(); zelf.encode_value(&obj, level, &mut out, vm)?; Ok(vm.new_tuple((out,)).into()) @@ -1320,37 +1383,42 @@ mod _json { } } + #[derive(FromArgs)] + struct ScanStringArgs { + #[pyarg(positional)] + pystr: PyStrRef, + #[pyarg(positional)] + end: isize, + #[pyarg(positional, default = ArgIntoBool::TRUE)] + strict: ArgIntoBool, + } + #[pyfunction] - fn scanstring( - s: PyStrRef, - end: usize, - strict: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult<(Wtf8Buf, usize)> { + fn scanstring(args: ScanStringArgs, vm: &VirtualMachine) -> PyResult<(Wtf8Buf, usize)> { + let ScanStringArgs { + pystr: s, + end, + strict, + } = args; flame_guard!("_json::scanstring"); let wtf8 = s.as_wtf8(); + if end < 0 || end as usize > s.char_len() { + return Err(vm.new_value_error("end is out of bounds")); + } + let end = end as usize; + // Convert char index `end` to byte index let byte_idx = if end == 0 { 0 } else { wtf8.code_point_indices() .nth(end) - .map(|(i, _)| i) - .ok_or_else(|| { - py_decode_error( - json::DecodeError { - msg: "Unterminated string starting at".to_owned(), - pos: end - 1, - }, - s.clone(), - vm, - ) - })? + .map_or(wtf8.len(), |(i, _)| i) }; let (result, end_char_idx, _bytes_consumed) = - json::scan_string(&wtf8[byte_idx..], end, strict.unwrap_or(true)) + json::scan_string(&wtf8[byte_idx..], end, strict.into_bool()) .map_err(|e| py_decode_error(e, s, vm))?; Ok((result, end_char_idx)) diff --git a/crates/stdlib/src/lib.rs b/crates/stdlib/src/lib.rs index bc3350231c3..ab307326a82 100644 --- a/crates/stdlib/src/lib.rs +++ b/crates/stdlib/src/lib.rs @@ -91,12 +91,7 @@ mod fcntl; #[cfg(all(feature = "host_env", not(target_arch = "wasm32")))] mod multiprocessing; -#[cfg(all( - feature = "host_env", - unix, - not(target_os = "redox"), - not(target_os = "android") -))] +#[cfg(all(feature = "host_env", unix, not(target_os = "android")))] mod posixshmem; #[cfg(all(feature = "host_env", unix))] @@ -174,7 +169,6 @@ mod termios; not(any( target_os = "android", target_os = "ios", - target_os = "windows", target_arch = "wasm32", target_os = "redox", )) @@ -232,6 +226,7 @@ pub fn stdlib_module_defs(ctx: &Context) -> Vec<&'static builtins::PyModuleDef> locale::module_def(ctx), lzma::module_def(ctx), math::module_def(ctx), + math::integer_module_def(ctx), md5::module_def(ctx), #[cfg(all(feature = "host_env", any(unix, windows)))] mmap::module_def(ctx), @@ -249,12 +244,7 @@ pub fn stdlib_module_defs(ctx: &Context) -> Vec<&'static builtins::PyModuleDef> overlapped::module_def(ctx), #[cfg(all(feature = "host_env", unix))] posixsubprocess::module_def(ctx), - #[cfg(all( - feature = "host_env", - unix, - not(target_os = "redox"), - not(target_os = "android") - ))] + #[cfg(all(feature = "host_env", unix, not(target_os = "android")))] posixshmem::module_def(ctx), pickle::module_def(ctx), pyexpat::module_def(ctx), @@ -317,7 +307,6 @@ pub fn stdlib_module_defs(ctx: &Context) -> Vec<&'static builtins::PyModuleDef> not(any( target_os = "android", target_os = "ios", - target_os = "windows", target_arch = "wasm32", target_os = "redox" )) diff --git a/crates/stdlib/src/locale.rs b/crates/stdlib/src/locale.rs index aba3b22433f..0333f20ffa9 100644 --- a/crates/stdlib/src/locale.rs +++ b/crates/stdlib/src/locale.rs @@ -6,6 +6,8 @@ pub(crate) use _locale::module_def; mod _locale { use alloc::ffi::CString; use rustpython_host_env::locale as host_locale; + #[cfg(target_os = "linux")] + use rustpython_vm::builtins::{PyStr, PyStrRef}; use rustpython_vm::{ PyObjectRef, PyResult, VirtualMachine, builtins::{PyDictRef, PyIntRef, PyListRef, PyTypeRef, PyUtf8StrRef}, @@ -47,7 +49,7 @@ mod _locale { group_vec.push(val.into()); } // https://github.com/python/cpython/blob/677320348728ce058fa3579017e985af74a236d4/Modules/_localemodule.c#L80 - if !group_vec.is_empty() { + if group.last().is_some_and(|&c| c != core::ffi::c_char::MAX) { group_vec.push(vm.ctx.new_int(0).into()); } vm.ctx.new_list(group_vec) @@ -90,7 +92,25 @@ mod _locale { Ok(vm.new_pyobj(host_locale::wcscoll(&w1, &w2))) } - #[cfg(not(windows))] + #[cfg(target_os = "linux")] + fn collation_string( + string: &PyStr, + vm: &VirtualMachine, + ) -> PyResult { + host_locale::CollationString::new(string.as_wtf8()) + .ok_or_else(|| vm.new_value_error("embedded null character")) + } + + #[cfg(target_os = "linux")] + #[pyfunction] + fn strcoll(os1: PyStrRef, os2: PyStrRef, vm: &VirtualMachine) -> PyResult { + // Bind both strings before checking for NULs, as Argument Clinic does. + let first = collation_string(&os1, vm)?; + let second = collation_string(&os2, vm)?; + Ok(vm.new_pyobj(first.compare(&second))) + } + + #[cfg(not(any(windows, target_os = "linux")))] #[pyfunction] fn strcoll(os1: PyUtf8StrRef, os2: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult { let cstr1 = CString::new(os1.as_str()).map_err(|e| e.to_pyexception(vm))?; @@ -109,7 +129,18 @@ mod _locale { Ok(vm.new_pyobj(String::from_utf16_lossy(&transformed))) } - #[cfg(not(windows))] + #[cfg(target_os = "linux")] + #[pyfunction] + fn strxfrm(string: PyStrRef, vm: &VirtualMachine) -> PyResult { + let string = collation_string(&string, vm)?; + let key = string.transform().map_err(|err| match err { + host_locale::CollationTransformError::Memory => vm.new_memory_error(""), + host_locale::CollationTransformError::Os(err) => err.to_pyexception(vm), + })?; + Ok(vm.ctx.new_str(key).into()) + } + + #[cfg(not(any(windows, target_os = "linux")))] #[pyfunction] fn strxfrm(string: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult { // https://github.com/python/cpython/blob/eaae563b6878aa050b4ad406b67728b6b066220e/Modules/_localemodule.c#L390-L442 @@ -194,9 +225,7 @@ mod _locale { fn check_locale_name(locale: &str) -> bool { if let Some(dot_pos) = locale.find('.') { let encoding_part = &locale[dot_pos + 1..]; - // Find the end of encoding (could be followed by '@' modifier) - let encoding_len = encoding_part.find('@').unwrap_or(encoding_part.len()); - encoding_len <= MAX_CP_LEN + encoding_part.len() <= MAX_CP_LEN } else { true } diff --git a/crates/stdlib/src/lzma.rs b/crates/stdlib/src/lzma.rs index 1e539c821d5..fbe0bfb4c6b 100644 --- a/crates/stdlib/src/lzma.rs +++ b/crates/stdlib/src/lzma.rs @@ -8,7 +8,7 @@ mod _lzma { use alloc::fmt; use core::sync::atomic::{AtomicBool, AtomicI32, Ordering}; use rustpython_common::{compression::lzma as backend, lock::PyMutex}; - use rustpython_vm::builtins::{PyBaseExceptionRef, PyBytes, PyDict, PyType, PyTypeRef}; + use rustpython_vm::builtins::{PyBaseExceptionRef, PyBytes, PyDict, PyStr, PyType, PyTypeRef}; use rustpython_vm::function::{ArgBytesLike, ItemDoc}; use rustpython_vm::object::PyAtomicRef; use rustpython_vm::types::Constructor; @@ -129,6 +129,30 @@ mod _lzma { }) } + /// A key the filter does not take makes the whole specifier invalid, as + /// the spec dict is read as keyword arguments. + fn check_filter_spec_keys( + spec: &PyObject, + allowed: &[&str], + error: &str, + vm: &VirtualMachine, + ) -> PyResult<()> { + let dict = spec.downcast_ref::().ok_or_else(|| { + vm.new_type_error("Filter specifier must be a dict or dict-like object") + })?; + for key in dict.keys_vec() { + let ok = key.downcast_ref::().is_some_and(|k| { + allowed + .iter() + .any(|a| k.as_wtf8().as_bytes() == a.as_bytes()) + }); + if !ok { + return Err(vm.new_value_error(error.to_owned())); + } + } + Ok(()) + } + fn parse_filter_chain_item( spec: &PyObject, vm: &VirtualMachine, @@ -136,6 +160,23 @@ mod _lzma { let mut parsed = filter_spec_with_id(spec, vm)?; match parsed.id { FILTER_LZMA1 | FILTER_LZMA2 => { + check_filter_spec_keys( + spec, + &[ + "id", + "preset", + "dict_size", + "lc", + "lp", + "pb", + "mode", + "nice_len", + "mf", + "depth", + ], + "Invalid filter specifier for LZMA filter", + vm, + )?; parsed.preset = get_dict_opt_u32(spec, "preset", vm)?; parsed.dict_size = get_dict_opt_u32(spec, "dict_size", vm)?; parsed.lc = get_dict_opt_u32(spec, "lc", vm)?; @@ -146,9 +187,23 @@ mod _lzma { parsed.mf = get_dict_opt_u32(spec, "mf", vm)?; parsed.depth = get_dict_opt_u32(spec, "depth", vm)?; } - FILTER_DELTA => parsed.dist = get_dict_opt_u32(spec, "dist", vm)?, + FILTER_DELTA => { + check_filter_spec_keys( + spec, + &["id", "dist"], + "Invalid filter specifier for delta filter", + vm, + )?; + parsed.dist = get_dict_opt_u32(spec, "dist", vm)?; + } FILTER_X86 | FILTER_POWERPC | FILTER_IA64 | FILTER_ARM | FILTER_ARMTHUMB | FILTER_SPARC => { + check_filter_spec_keys( + spec, + &["id", "start_offset"], + "Invalid filter specifier for BCJ filter", + vm, + )?; parsed.start_offset = get_dict_opt_u32(spec, "start_offset", vm)?; } _ => {} @@ -160,25 +215,109 @@ mod _lzma { spec: &PyObject, vm: &VirtualMachine, ) -> PyResult { - let mut parsed = filter_spec_with_id(spec, vm)?; - match parsed.id { - FILTER_LZMA1 => { - parsed.preset = get_dict_opt_u32(spec, "preset", vm)?; - parsed.lc = get_dict_opt_u32(spec, "lc", vm)?; - parsed.lp = get_dict_opt_u32(spec, "lp", vm)?; - parsed.pb = get_dict_opt_u32(spec, "pb", vm)?; - parsed.dict_size = get_dict_opt_u32(spec, "dict_size", vm)?; + fn take_keyword( + dict: &PyDict, + key: &str, + remaining: &mut usize, + error: &str, + vm: &VirtualMachine, + ) -> PyResult> { + if *remaining == 0 { + return Ok(None); } - FILTER_LZMA2 => { + let value = dict + .inner_getitem_opt(key, vm) + .map_err(|_| vm.new_value_error(error))?; + if value.is_some() { + *remaining -= 1; + } + Ok(value) + } + + fn field( + dict: &PyDict, + key: &str, + remaining: &mut usize, + error: &str, + vm: &VirtualMachine, + ) -> PyResult> { + take_keyword(dict, key, remaining, error, vm)? + .map(|value| { + value + .try_into_value::(vm) + .map_err(|_| vm.new_value_error(error)) + }) + .transpose() + } + + let mut parsed = filter_spec_with_id(spec, vm)?; + let dict = spec + .downcast_ref::() + .expect("filter ID was read from a dict"); + let (max, error) = match parsed.id { + FILTER_LZMA1 | FILTER_LZMA2 => { parsed.preset = get_dict_opt_u32(spec, "preset", vm)?; - parsed.dict_size = get_dict_opt_u32(spec, "dict_size", vm)?; + if let Some(preset) = parsed.preset + && preset & !PRESET_EXTREME > 9 + { + return Err(new_lzma_error( + format!("Invalid compression preset: {preset}"), + vm, + )); + } + (10, "Invalid filter specifier for LZMA filter") } - FILTER_DELTA => parsed.dist = get_dict_opt_u32(spec, "dist", vm)?, + FILTER_DELTA => (2, "Invalid filter specifier for delta filter"), FILTER_X86 | FILTER_POWERPC | FILTER_IA64 | FILTER_ARM | FILTER_ARMTHUMB - | FILTER_SPARC => { - parsed.start_offset = get_dict_opt_u32(spec, "start_offset", vm)?; + | FILTER_SPARC => (2, "Invalid filter specifier for BCJ filter"), + _ => return Ok(parsed), + }; + // PyArg_ParseTupleAndKeywords snapshots the keyword count and stops + // looking up optional fields when all of those keywords are consumed. + let mut remaining = dict.__len__(); + if remaining > max { + return Err(vm.new_value_error(error)); + } + let _ = take_keyword(dict, "id", &mut remaining, error, vm)?; + if matches!(parsed.id, FILTER_LZMA1 | FILTER_LZMA2) { + let _ = take_keyword(dict, "preset", &mut remaining, error, vm)?; + parsed.dict_size = field(dict, "dict_size", &mut remaining, error, vm)?; + parsed.lc = field(dict, "lc", &mut remaining, error, vm)?; + parsed.lp = field(dict, "lp", &mut remaining, error, vm)?; + parsed.pb = field(dict, "pb", &mut remaining, error, vm)?; + parsed.mode = field(dict, "mode", &mut remaining, error, vm)?; + parsed.nice_len = field(dict, "nice_len", &mut remaining, error, vm)?; + parsed.mf = field(dict, "mf", &mut remaining, error, vm)?; + parsed.depth = field(dict, "depth", &mut remaining, error, vm)?; + if remaining > 0 { + check_filter_spec_keys( + spec, + &[ + "id", + "preset", + "dict_size", + "lc", + "lp", + "pb", + "mode", + "nice_len", + "mf", + "depth", + ], + error, + vm, + )?; + } + } else if parsed.id == FILTER_DELTA { + parsed.dist = field(dict, "dist", &mut remaining, error, vm)?; + if remaining > 0 { + check_filter_spec_keys(spec, &["id", "dist"], error, vm)?; + } + } else { + parsed.start_offset = field(dict, "start_offset", &mut remaining, error, vm)?; + if remaining > 0 { + check_filter_spec_keys(spec, &["id", "start_offset"], error, vm)?; } - _ => {} } Ok(parsed) } @@ -389,16 +528,10 @@ mod _lzma { fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { if args.format != FORMAT_XZ && args.check != -1 && args.check != CHECK_NONE { - return Err(new_lzma_error( - "Integrity checks are only supported by FORMAT_XZ", - vm, - )); + return Err(vm.new_value_error("Integrity checks are only supported by FORMAT_XZ")); } if args.preset.is_some() && args.filters.is_some() { - return Err(new_lzma_error( - "Cannot specify both preset and filter chain", - vm, - )); + return Err(vm.new_value_error("Cannot specify both preset and filter chain")); } let preset = match args.preset { Some(preset) => preset.try_into_value::(vm)?, diff --git a/crates/stdlib/src/math.rs b/crates/stdlib/src/math.rs index 4b23b7b7b4a..c09dcb40e35 100644 --- a/crates/stdlib/src/math.rs +++ b/crates/stdlib/src/math.rs @@ -1,3 +1,4 @@ +pub(crate) use _math_integer::module_def as integer_module_def; pub(crate) use math::module_def; use crate::vm::{VirtualMachine, builtins::PyBaseExceptionRef}; @@ -5,19 +6,32 @@ use crate::vm::{VirtualMachine, builtins::PyBaseExceptionRef}; #[pymodule] mod math { use crate::vm::{ - AsObject, PyObject, PyObjectRef, PyRef, PyResult, VirtualMachine, - builtins::{PyFloat, PyInt, PyIntRef, PyStrInterned, try_bigint_to_f64, try_f64_to_bigint}, - function::{ - ArgIndex, ArgIntoFloat, ArgIterable, Either, NameCoordinates, NameIntegers, - OptionalArg, PosArgs, + AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine, + builtins::{ + PyFloat, PyInt, PyIntRef, PyModule, PyStrInterned, PyTuple, try_bigint_to_f64, + try_f64_to_bigint, }, + function::{ArgIndex, ArgIntoFloat, ArgIterable, NameCoordinates, OptionalArg, PosArgs}, identifier, }; + use itertools::Itertools; use malachite_bigint::BigInt; use num_traits::{Signed, ToPrimitive}; use super::{float_repr, pymath_exception}; + pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { + __module_exec(vm, module); + let integer = vm.import("_math_integer", 0)?; + for name in super::INTEGER_FUNCTIONS { + module.set_attr(name, integer.get_attr(name, vm)?, vm)?; + } + vm.sys_module + .get_attr("modules", vm)? + .set_item("math.integer", integer.clone(), vm)?; + module.set_attr("integer", integer, vm) + } + // Constants #[pyattr] use core::f64::consts::{E as e, PI as pi, TAU as tau}; @@ -48,6 +62,36 @@ mod math { pymath::math::isnan(x.into_float()) } + /// Return True if x is normal, and False otherwise. + #[pyfunction] + fn isnormal(x: ArgIntoFloat) -> bool { + pymath::math::isnormal(x.into_float()) + } + + /// Return True if x is subnormal, and False otherwise. + #[pyfunction] + fn issubnormal(x: ArgIntoFloat) -> bool { + pymath::math::issubnormal(x.into_float()) + } + + /// Return True if the sign of x is negative and False otherwise. + #[pyfunction] + fn signbit(x: ArgIntoFloat) -> bool { + pymath::math::signbit(x.into_float()) + } + + /// Return the larger of two floating-point arguments. + #[pyfunction] + fn fmax(x: ArgIntoFloat, y: ArgIntoFloat) -> f64 { + pymath::math::fmax(x.into_float(), y.into_float()) + } + + /// Return the smaller of two floating-point arguments. + #[pyfunction] + fn fmin(x: ArgIntoFloat, y: ArgIntoFloat) -> f64 { + pymath::math::fmin(x.into_float(), y.into_float()) + } + #[derive(FromArgs)] struct IsCloseArgs { #[pyarg(any)] @@ -93,30 +137,34 @@ mod math { pymath::math::expm1(x.into_float()).map_err(|err| pymath_exception(err, vm)) } - #[pyfunction] - fn log(x: PyObjectRef, base: OptionalArg, vm: &VirtualMachine) -> PyResult { - let base = base.into_option().map(|v| v.into_float()); - // Check base first for proper error messages - if let Some(b) = base { - if b <= 0.0 { - return Err(vm.new_value_error(format!( - "expected a positive input, got {}", - super::float_repr(b) - ))); - } - if b == 1.0 { - return Err(vm.new_value_error("math domain error")); - } - } - // Handle BigInt specially for large values (only for actual int type, not float) - if let Some(i) = x.downcast_ref::() { - return pymath::math::log_bigint(i.as_bigint(), base).map_err(|err| match err { + fn logarithm( + x: &PyObject, + float_log: impl Fn(f64) -> Result, + int_log: impl Fn(&BigInt) -> Result, + vm: &VirtualMachine, + ) -> PyResult { + let integer_log = |i: &PyInt| { + int_log(i.as_bigint()).map_err(|err| match err { pymath::Error::EDOM => vm.new_value_error("expected a positive input"), _ => pymath_exception(err, vm), - }); + }) + }; + if let Some(i) = x.downcast_ref::() { + return integer_log(i); } - let val = x.try_float(vm)?.to_f64(); - pymath::math::log(val, base).map_err(|err| match err { + let val = match x.to_owned().try_into_value::(vm) { + Ok(value) => value.into_float(), + Err(error) => { + if error.fast_isinstance(vm.ctx.exceptions.overflow_error) + && let Some(index) = x.try_index_opt(vm) + { + let index = index?; + return integer_log(&index); + } + return Err(error); + } + }; + float_log(val).map_err(|err| match err { pymath::Error::EDOM => vm.new_value_error(format!( "expected a positive input, got {}", super::float_repr(val) @@ -125,6 +173,30 @@ mod math { }) } + #[pyfunction] + fn log(x: PyObjectRef, base: OptionalArg, vm: &VirtualMachine) -> PyResult { + let natural_log = |x: &PyObject| { + logarithm( + x, + |value| pymath::math::log(value, None), + |value| pymath::math::log_bigint(value, None), + vm, + ) + }; + let numerator = natural_log(&x)?; + match base { + OptionalArg::Missing => Ok(numerator), + OptionalArg::Present(base) => { + let denominator = natural_log(&base)?; + if denominator == 0.0 { + Err(vm.new_zero_division_error("division by zero")) + } else { + Ok(numerator / denominator) + } + } + } + } + #[pyfunction] fn log1p(x: ArgIntoFloat, vm: &VirtualMachine) -> PyResult { pymath::math::log1p(x.into_float()).map_err(|err| pymath_exception(err, vm)) @@ -132,40 +204,12 @@ mod math { #[pyfunction] fn log2(x: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // Handle BigInt specially for large values (only for actual int type, not float) - if let Some(i) = x.downcast_ref::() { - return pymath::math::log2_bigint(i.as_bigint()).map_err(|err| match err { - pymath::Error::EDOM => vm.new_value_error("expected a positive input"), - _ => pymath_exception(err, vm), - }); - } - let val = x.try_float(vm)?.to_f64(); - pymath::math::log2(val).map_err(|err| match err { - pymath::Error::EDOM => vm.new_value_error(format!( - "expected a positive input, got {}", - super::float_repr(val) - )), - _ => pymath_exception(err, vm), - }) + logarithm(&x, pymath::math::log2, pymath::math::log2_bigint, vm) } #[pyfunction] fn log10(x: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // Handle BigInt specially for large values (only for actual int type, not float) - if let Some(i) = x.downcast_ref::() { - return pymath::math::log10_bigint(i.as_bigint()).map_err(|err| match err { - pymath::Error::EDOM => vm.new_value_error("expected a positive input"), - _ => pymath_exception(err, vm), - }); - } - let val = x.try_float(vm)?.to_f64(); - pymath::math::log10(val).map_err(|err| match err { - pymath::Error::EDOM => vm.new_value_error(format!( - "expected a positive input, got {}", - super::float_repr(val) - )), - _ => pymath_exception(err, vm), - }) + logarithm(&x, pymath::math::log10, pymath::math::log10_bigint, vm) } #[pyfunction] @@ -238,13 +282,27 @@ mod math { } #[pyfunction] - fn dist(p: Vec, q: Vec, vm: &VirtualMachine) -> PyResult { - let p = ArgIntoFloat::vec_into_f64(p); - let q = ArgIntoFloat::vec_into_f64(q); + fn dist(p: PyObjectRef, q: PyObjectRef, vm: &VirtualMachine) -> PyResult { + // Snapshot both points before checking dimensions or converting coordinates. + // Tuple subclasses use their stored elements, just like PyTuple_Check. + let p = match p.downcast_ref::() { + Some(tuple) => tuple.to_owned(), + None => p.sequence_unchecked().tuple(vm)?, + }; + let q = match q.downcast_ref::() { + Some(tuple) => tuple.to_owned(), + None => q.sequence_unchecked().tuple(vm)?, + }; if p.len() != q.len() { return Err(vm.new_value_error("both points must have the same number of dimensions")); } - Ok(pymath::math::dist(&p, &q)) + let mut differences = Vec::with_capacity(p.len()); + for (p, q) in p.as_slice().iter().zip(q.as_slice()) { + let p: ArgIntoFloat = p.clone().try_into_value(vm)?; + let q: ArgIntoFloat = q.clone().try_into_value(vm)?; + differences.push(p.into_float() - q.into_float()); + } + Ok(pymath::math::hypot(&differences)) } #[pyfunction] @@ -346,64 +404,47 @@ mod math { pymath::math::lgamma(x.into_float()).map_err(|err| pymath_exception(err, vm)) } - fn try_magic_method( - func_name: &'static PyStrInterned, + fn round_to_int( + x: &PyObject, + method: &'static PyStrInterned, + round: fn(f64) -> f64, vm: &VirtualMachine, - value: &PyObject, ) -> PyResult { - let method = vm.get_method_or_type_error(value.to_owned(), func_name, || { - format!( - "type '{}' doesn't define '{}' method", - value.class().name(), - func_name.as_str(), - ) - })?; - method.call((), vm) + // Exact floats skip special-method lookup. Other types may provide a + // result of any type, or fall back to the native float conversion. + let value = if let Some(float) = x.downcast_ref_if_exact::(vm) { + float.to_f64() + } else { + if let Some(result) = vm.call_special_method_opt(x, method, ())? { + return Ok(result); + } + x.to_owned() + .try_into_value::(vm)? + .into_float() + }; + let value = try_f64_to_bigint(round(value), vm)?; + Ok(vm.ctx.new_int(value).into()) } #[pyfunction] fn trunc(x: PyObjectRef, vm: &VirtualMachine) -> PyResult { - try_magic_method(identifier!(vm, __trunc__), vm, &x) + vm.call_special_method_opt(&x, identifier!(vm, __trunc__), ())? + .ok_or_else(|| { + let class = x.class(); + let name = class.slot_name(); + let name = &name[..name.floor_char_boundary(100)]; + vm.new_type_error(format!("type {name} doesn't define __trunc__ method")) + }) } #[pyfunction] fn ceil(x: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // `math_ceil`: an exact float skips the `__ceil__` lookup. - if let Some(f) = x.downcast_ref_if_exact::(vm) { - let v = try_f64_to_bigint(f.to_f64().ceil(), vm)?; - return Ok(vm.ctx.new_int(v).into()); - } - // Only call __ceil__ if the class defines it - if it exists but is not callable, - // the error should be propagated (not fall back to float conversion) - if x.class().has_attr(identifier!(vm, __ceil__)) { - return try_magic_method(identifier!(vm, __ceil__), vm, &x); - } - // __ceil__ not defined - fall back to float conversion - if let Some(v) = x.try_float_opt(vm) { - let v = try_f64_to_bigint(v?.to_f64().ceil(), vm)?; - return Ok(vm.ctx.new_int(v).into()); - } - Err(vm.new_type_error(format!("must be real number, not {}", x.class().name()))) + round_to_int(&x, identifier!(vm, __ceil__), f64::ceil, vm) } #[pyfunction] fn floor(x: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // `math_floor`: an exact float skips the `__floor__` lookup. - if let Some(f) = x.downcast_ref_if_exact::(vm) { - let v = try_f64_to_bigint(f.to_f64().floor(), vm)?; - return Ok(vm.ctx.new_int(v).into()); - } - // Only call __floor__ if the class defines it - if it exists but is not callable, - // the error should be propagated (not fall back to float conversion) - if x.class().has_attr(identifier!(vm, __floor__)) { - return try_magic_method(identifier!(vm, __floor__), vm, &x); - } - // __floor__ not defined - fall back to float conversion - if let Some(v) = x.try_float_opt(vm) { - let v = try_f64_to_bigint(v?.to_f64().floor(), vm)?; - return Ok(vm.ctx.new_int(v).into()); - } - Err(vm.new_type_error(format!("must be real number, not {}", x.class().name()))) + round_to_int(&x, identifier!(vm, __floor__), f64::floor, vm) } #[pyfunction] @@ -414,7 +455,7 @@ mod math { #[derive(FromArgs)] struct LdexpArgs { #[pyarg(positional)] - x: Either, PyIntRef>, + x: ArgIntoFloat, // Refuses anything that is not an `int`, including objects with `__index__`. #[pyarg(positional, error_msg = "Expected an int as second argument to ldexp.")] i: PyIntRef, @@ -423,11 +464,8 @@ mod math { #[pyfunction] fn ldexp(args: LdexpArgs, vm: &VirtualMachine) -> PyResult { let LdexpArgs { x, i } = args; - let value = match x { - Either::A(f) => f.to_f64(), - Either::B(z) => try_bigint_to_f64(z.as_bigint(), vm)?, - }; - pymath::math::ldexp_bigint(value, i.as_bigint()).map_err(|err| pymath_exception(err, vm)) + pymath::math::ldexp_bigint(x.into_float(), i.as_bigint()) + .map_err(|err| pymath_exception(err, vm)) } #[pyfunction] @@ -436,10 +474,20 @@ mod math { } #[pyfunction] - fn fsum(seq: ArgIterable, vm: &VirtualMachine) -> PyResult { - let values: Result, _> = - seq.iter(vm)?.map(|r| r.map(|v| v.into_float())).collect(); - pymath::math::fsum(values?).map_err(|err| pymath_exception(err, vm)) + fn fsum(seq: ArgIterable, vm: &VirtualMachine) -> PyResult { + // Stream conversions so an intermediate overflow does not advance the + // Python iterator or invoke __float__ on any later summands. + let mut values = seq + .iter(vm)? + .map(|value| value.map(ArgIntoFloat::into_float)); + values + .by_ref() + .process_results(|values| pymath::math::fsum(values))? + .map(|value| vm.ctx.new_float(value).into()) + .map_err(|err| match err { + pymath::Error::ERANGE => vm.new_overflow_error("intermediate overflow in fsum"), + pymath::Error::EDOM => vm.new_value_error("-inf + inf in fsum"), + }) } #[pyfunction] @@ -465,11 +513,13 @@ mod math { let steps = match arg.steps { Some(steps) => { - let steps: i64 = steps.into_int_ref().try_to_primitive(vm)?; - if steps < 0 { + let steps = steps.as_ref().as_bigint(); + if steps.is_negative() { return Err(vm.new_value_error("steps must be a non-negative integer")); } - Some(steps as u64) + // Every finite IEEE-754 path fits in u64 steps. Larger indices + // reach the destination, just like CPython's saturated count. + Some(steps.to_u64().unwrap_or(u64::MAX)) } None => None, }; @@ -481,8 +531,8 @@ mod math { pymath::math::ulp(x.into_float()) } - #[pyfunction(name = "fmod")] - fn py_fmod(x: ArgIntoFloat, y: ArgIntoFloat, vm: &VirtualMachine) -> PyResult { + #[pyfunction] + fn fmod(x: ArgIntoFloat, y: ArgIntoFloat, vm: &VirtualMachine) -> PyResult { pymath::math::fmod(x.into_float(), y.into_float()).map_err(|err| pymath_exception(err, vm)) } @@ -503,131 +553,83 @@ mod math { #[pyfunction] fn prod(args: ProdArgs, vm: &VirtualMachine) -> PyResult { - use crate::vm::builtins::PyInt; - - let iter = args.iterable; - let start = args.start; - - // Check if start is provided and what type it is (exact types only, not subclasses) - let (mut obj_result, start_is_int, start_is_float) = match &start { - OptionalArg::Present(s) => { - let is_int = s.class().is(vm.ctx.types.int_type); - let is_float = s.class().is(vm.ctx.types.float_type); - (Some(s.clone()), is_int, is_float) - } - OptionalArg::Missing => (None, true, false), // Default is int 1 + let mut items = args.iterable.iter(vm)?; + let mut result = match &args.start { + OptionalArg::Present(start) => start.clone(), + OptionalArg::Missing => vm.ctx.new_int(1).into(), }; - let mut item_iter = iter.iter(vm)?; - - // Integer fast path - if start_is_int && !start_is_float { - let mut int_result: i64 = match &start { - OptionalArg::Present(s) => { - if let Some(i) = s.downcast_ref::() { - match i.as_bigint().try_into() { - Ok(v) => v, - Err(_) => { - // Start overflows i64, fall through to generic path - obj_result = Some(s.clone()); - i64::MAX // Will be ignored - } - } - } else { - 1 - } + // Only exact builtins may bypass Python's multiplication methods. + if result.class().is(vm.ctx.types.int_type) + && let Some(integer) = result.downcast_ref::() + && let Ok(mut total) = integer.as_bigint().try_into() as Result + { + loop { + let Some(item) = items.next() else { + return Ok(vm.ctx.new_int(total).into()); + }; + let item = item?; + if item.class().is(vm.ctx.types.int_type) + && let Some(integer) = item.downcast_ref::() + && let Ok(value) = integer.as_bigint().try_into() as Result + && let Some(product) = total.checked_mul(value) + { + total = product; + continue; } - OptionalArg::Missing => 1, - }; - - if obj_result.is_none() { - loop { - let item = match item_iter.next() { - Some(r) => r?, - None => return Ok(vm.ctx.new_int(int_result).into()), - }; - - // Only use fast path for exact int type (not subclasses) - if item.class().is(vm.ctx.types.int_type) - && let Some(int_item) = item.downcast_ref::() - && let Ok(b) = int_item.as_bigint().try_into() as Result - && let Some(product) = int_result.checked_mul(b) - { - int_result = product; - continue; - } - // Overflow or non-int: restore to PyObject and continue - obj_result = Some(vm.ctx.new_int(int_result).into()); - let temp = vm._mul(obj_result.as_ref().unwrap(), &item)?; - obj_result = Some(temp); - break; - } + result = vm.ctx.new_int(total).into(); + result = vm._mul(&result, &item)?; + break; } } - // Float fast path - let obj_float = obj_result - .as_ref() - .and_then(|obj| obj.clone().downcast::().ok()); - if obj_float.is_some() || start_is_float { - let mut flt_result: f64 = if let Some(ref f) = obj_float { - f.to_f64() - } else if start_is_float && let OptionalArg::Present(s) = &start { - s.downcast_ref::().map_or(1.0, |f| f.to_f64()) - } else { - 1.0 - }; - + // The integer fallback can return a float subclass. Do not enter this + // path on a payload downcast: its __mul__ must still be called. + if result.class().is(vm.ctx.types.float_type) + && let Some(float) = result.downcast_ref::() + { + let mut total = float.to_f64(); loop { - let item = match item_iter.next() { - Some(r) => r?, - None => return Ok(vm.ctx.new_float(flt_result).into()), + let Some(item) = items.next() else { + return Ok(vm.ctx.new_float(total).into()); }; - - // Only use fast path for exact float/int types (not subclasses) + let item = item?; if item.class().is(vm.ctx.types.float_type) - && let Some(f) = item.downcast_ref::() + && let Some(float) = item.downcast_ref::() { - flt_result *= f.to_f64(); + total *= float.to_f64(); continue; } if item.class().is(vm.ctx.types.int_type) - && let Some(i) = item.downcast_ref::() - && let Ok(v) = i.as_bigint().try_into() as Result + && let Some(integer) = item.downcast_ref::() + && let Ok(value) = integer.as_bigint().try_into() as Result { - flt_result *= v as f64; + total *= value as f64; continue; } - // Non-exact-float/int: restore and continue with generic path - obj_result = Some(vm.ctx.new_float(flt_result).into()); - let temp = vm._mul(obj_result.as_ref().unwrap(), &item)?; - obj_result = Some(temp); + result = vm.ctx.new_float(total).into(); + result = vm._mul(&result, &item)?; break; } } - // Generic path for remaining items - let mut result = obj_result.unwrap_or_else(|| vm.ctx.new_int(1).into()); - for item in item_iter { + // Once the specialized paths end, every remaining product uses the + // normal numeric protocol, even if a later result is a builtin again. + for item in items { let item = item?; result = vm._mul(&result, &item)?; } - Ok(result) } #[pyfunction] - fn sumprod( - p: ArgIterable, - q: ArgIterable, - vm: &VirtualMachine, - ) -> PyResult { + fn sumprod(p: PyObjectRef, q: PyObjectRef, vm: &VirtualMachine) -> PyResult { use crate::vm::builtins::PyInt; - let mut p_iter = p.iter(vm)?; - let mut q_iter = q.iter(vm)?; + let mut p_iter = p.get_iter(vm)?.into_iter::(vm); + let mut q_iter = q.get_iter(vm)?.into_iter::(vm); // Fast path state let mut int_path_enabled = true; @@ -640,11 +642,13 @@ mod math { let mut obj_total: Option = None; loop { - let m_p = p_iter.next(); - let m_q = q_iter.next(); + // An exception from p must escape before q is advanced. Likewise, + // an exception from q takes precedence over a length mismatch. + let m_p = p_iter.next().transpose()?; + let m_q = q_iter.next().transpose()?; let (p_i, q_i, finished) = match (m_p, m_q) { - (Some(r_p), Some(r_q)) => (Some(r_p?), Some(r_q?), false), + (Some(p_i), Some(q_i)) => (Some(p_i), Some(q_i), false), (None, None) => (None, None, true), _ => return Err(vm.new_value_error("Inputs are not the same length")), }; @@ -690,8 +694,12 @@ mod math { let p_is_exact_float = p_i.class().is(vm.ctx.types.float_type); let q_is_exact_float = q_i.class().is(vm.ctx.types.float_type); - let p_is_exact_int = p_i.class().is(vm.ctx.types.int_type); - let q_is_exact_int = q_i.class().is(vm.ctx.types.int_type); + // Boolean weights participate in the compensated float + // path, but arbitrary integer subclasses must not. + let p_is_exact_int = p_i.class().is(vm.ctx.types.int_type) + || p_i.class().is(vm.ctx.types.bool_type); + let q_is_exact_int = q_i.class().is(vm.ctx.types.int_type) + || q_i.class().is(vm.ctx.types.bool_type); let p_is_exact_numeric = p_is_exact_float || p_is_exact_int; let q_is_exact_numeric = q_is_exact_float || q_is_exact_int; let has_exact_float = p_is_exact_float || q_is_exact_float; @@ -773,7 +781,18 @@ mod math { pymath::Error::ERANGE => vm.new_overflow_error("overflow in fma"), }) } +} + +const INTEGER_FUNCTIONS: [&str; 6] = ["comb", "factorial", "gcd", "isqrt", "lcm", "perm"]; +#[pymodule(sub, name = "math")] +mod integer_functions { + use crate::vm::{ + PyResult, VirtualMachine, + function::{ArgIndex, NameIntegers, PosArgs}, + }; + use malachite_bigint::BigInt; + use num_traits::{Signed, ToPrimitive}; // Integer functions: #[pyfunction] @@ -960,3 +979,21 @@ fn float_repr(value: f64) -> String { } } } + +/// This module provides access to integer related mathematical functions. +#[pymodule(with(integer_functions))] +mod _math_integer { + use crate::vm::{Py, PyResult, VirtualMachine, builtins::PyModule}; + + pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { + __module_exec(vm, module); + let name = vm.ctx.new_str("math.integer"); + module.set_attr("__name__", name.clone(), vm)?; + for function_name in super::INTEGER_FUNCTIONS { + module + .get_attr(function_name, vm)? + .set_attr("__module__", name.clone(), vm)?; + } + Ok(()) + } +} diff --git a/crates/stdlib/src/md5.rs b/crates/stdlib/src/md5.rs index 0339bf8ace7..01783968291 100644 --- a/crates/stdlib/src/md5.rs +++ b/crates/stdlib/src/md5.rs @@ -2,12 +2,12 @@ pub(crate) use _md5::module_def; #[pymodule] mod _md5 { - use crate::hashlib::_hashlib::{HashArgs, local_md5}; + use crate::hashlib::_hashlib::{HashArgs, openssl_md5}; use crate::vm::{Py, PyPayload, PyResult, VirtualMachine, builtins::PyModule}; #[pyfunction] fn md5(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_md5(args, vm)?.into_pyobject(vm)) + Ok(openssl_md5(args, vm)?.into_pyobject(vm)) } #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] diff --git a/crates/stdlib/src/mmap.rs b/crates/stdlib/src/mmap.rs index 2a3ee0bc460..a96e1be50a2 100644 --- a/crates/stdlib/src/mmap.rs +++ b/crates/stdlib/src/mmap.rs @@ -11,22 +11,22 @@ mod mmap { use crate::vm::{ AsObject, FromArgs, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, VirtualMachine, atomic_func, - builtins::{PyBytes, PyBytesRef, PyInt, PyIntRef, PyType, PyTypeRef}, + builtins::{PyBytes, PyBytesRef, PyInt, PyIntRef, PyType, PyTypeRef, PyUtf8StrRef}, byte::{bytes_from_object, value_from_object}, convert::ToPyException, - function::ArgBytesLike, + function::{ArgBytesLike, ArgIndex, ArgIntoBool}, protocol::{ BufferDescriptor, BufferMethods, PyBuffer, PyMappingMethods, PySequenceMethods, }, - sliceable::{SaturatedSlice, SequenceIndex, SequenceIndexOp}, + sliceable::{NameMmap, SaturatedSlice, SequenceIndex, SequenceIndexOp}, types::{AsBuffer, AsMapping, AsSequence, Constructor, Representable}, }; use core::ops::{Deref, DerefMut}; use crossbeam_utils::atomic::AtomicCell; - use num_traits::Signed; + use num_traits::{Signed, ToPrimitive}; use std::io::Write; #[cfg(windows)] - use {core::hint::cold_path, memchr::memchr, rustpython_vm::exceptions, std::io}; + use {core::hint::cold_path, memchr::memchr, rustpython_vm::exceptions}; #[cfg(unix)] use rustpython_host_env::crt_fd; @@ -45,23 +45,42 @@ mod mmap { Copy = 3, } - impl AccessMode { + #[derive(Copy, Clone)] + struct AccessArg(i32); + + impl AccessArg { + const DEFAULT: Self = Self(0); + #[must_use] pub(crate) const fn py_default(self) -> crate::vm::function::DefaultRepr { - crate::vm::function::DefaultRepr::Int(self as i128) + crate::vm::function::DefaultRepr::Int(self.0 as i128) + } + + fn into_mode(self, vm: &VirtualMachine) -> PyResult { + Ok(match self.0 { + 0 => AccessMode::Default, + 1 => AccessMode::Read, + 2 => AccessMode::Write, + 3 => AccessMode::Copy, + _ => return Err(vm.new_value_error("mmap invalid access parameter.")), + }) } } - impl<'a> TryFromBorrowedObject<'a> for AccessMode { + impl<'a> TryFromBorrowedObject<'a> for AccessArg { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { - let i = u32::try_from_borrowed_object(vm, obj)?; - Ok(match i { - 0 => Self::Default, - 1 => Self::Read, - 2 => Self::Write, - 3 => Self::Copy, - _ => return Err(vm.new_value_error("Not a valid AccessMode value")), - }) + let index = obj.try_index(vm)?; + // getargs.c's 'i' converts through C long before checking C int bounds. + let value = core::ffi::c_long::try_from(index.as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))?; + let value = value.to_i32().ok_or_else(|| { + vm.new_overflow_error(if value > 0 { + "signed integer is greater than maximum" + } else { + "signed integer is less than minimum" + }) + })?; + Ok(Self(value)) } } @@ -69,7 +88,8 @@ mod mmap { #[pyattr] use host_mmap::{ MADV_DONTNEED, MADV_NORMAL, MADV_RANDOM, MADV_SEQUENTIAL, MADV_WILLNEED, MAP_ANON, - MAP_ANONYMOUS, MAP_PRIVATE, MAP_SHARED, PROT_EXEC, PROT_READ, PROT_WRITE, + MAP_ANONYMOUS, MAP_PRIVATE, MAP_SHARED, MS_ASYNC, MS_INVALIDATE, MS_SYNC, PROT_EXEC, + PROT_READ, PROT_WRITE, }; #[cfg(target_os = "macos")] @@ -165,17 +185,19 @@ mod mmap { #[derive(Debug)] enum MmapObj { + #[cfg(unix)] Mapped(host_mmap::MappedFile), #[cfg(windows)] - Named(host_mmap::NamedMmap), + Windows(host_mmap::WindowsMmap), } impl MmapObj { fn as_slice(&self) -> &[u8] { match self { + #[cfg(unix)] Self::Mapped(mmap) => mmap.as_slice(), #[cfg(windows)] - Self::Named(named) => named.as_slice(), + Self::Windows(named) => named.as_slice(), } } } @@ -195,8 +217,11 @@ mod mmap { pos: AtomicCell, // relative to offset exports: AtomicCell, access: AccessMode, - #[cfg(unix)] trackfd: bool, + #[cfg(target_os = "linux")] + anonymous: bool, + #[cfg(target_os = "linux")] + private: bool, } impl PyMmap { @@ -225,6 +250,7 @@ mod mmap { #[cfg(unix)] #[derive(FromArgs)] + #[from_args(legacy, fname = "mmap")] struct MmapNewArgs { #[pyarg(any)] fileno: i32, @@ -234,16 +260,17 @@ mod mmap { flags: core::ffi::c_int, #[pyarg(any, default = host_mmap::PROT_WRITE | host_mmap::PROT_READ)] prot: core::ffi::c_int, - #[pyarg(any, default = AccessMode::Default)] - access: AccessMode, + #[pyarg(any, default = AccessArg::DEFAULT)] + access: AccessArg, #[pyarg(any, default)] offset: i64, - #[pyarg(named, default = true)] - trackfd: bool, + #[pyarg(named, default = ArgIntoBool::TRUE)] + trackfd: ArgIntoBool, } #[cfg(windows)] #[derive(FromArgs)] + #[from_args(legacy, fname = "mmap")] struct MmapNewArgs { #[pyarg(any)] fileno: i32, @@ -251,10 +278,12 @@ mod mmap { length: isize, #[pyarg(any, default)] tagname: Option, - #[pyarg(any, default = AccessMode::Default)] - access: AccessMode, + #[pyarg(any, default = AccessArg::DEFAULT)] + access: AccessArg, #[pyarg(any, default)] offset: i64, + #[pyarg(named, default = ArgIntoBool::TRUE)] + trackfd: ArgIntoBool, } impl MmapNewArgs { @@ -288,8 +317,10 @@ mod mmap { pub(super) struct FlushOptions { #[pyarg(positional, default)] offset: isize, - #[pyarg(positional, optional)] - size: Option, + #[pyarg(positional, default = -1)] + size: isize, + #[pyarg(named, default)] + flags: core::ffi::c_int, } impl FlushOptions { @@ -298,14 +329,15 @@ mod mmap { return None; } let offset = self.offset as usize; + let remaining = len.checked_sub(offset)?; let size = match self.size { - Some(s) if s < 0 => return None, - Some(s) => s as usize, - None => len, + -1 => remaining, + s if s < 0 => return None, + s => s as usize, }; - if len.checked_sub(offset)? < size { + if remaining < size { return None; } @@ -313,14 +345,14 @@ mod mmap { } } - #[derive(FromArgs, Clone)] + #[derive(FromArgs)] pub(super) struct FindOptions { #[pyarg(positional)] - view: Vec, + view: PyObjectRef, #[pyarg(positional, optional)] - start: Option, + start: Option, #[pyarg(positional, optional)] - end: Option, + end: Option, } #[cfg(all(unix, not(target_os = "redox")))] @@ -330,9 +362,9 @@ mod mmap { option: core::ffi::c_int, // None means 0. #[pyarg(positional, default, py_default = "0")] - start: Option, + start: Option, #[pyarg(positional, optional)] - length: Option, + length: Option, } #[cfg(all(unix, not(target_os = "redox")))] @@ -345,7 +377,8 @@ mod mmap { let start = self .start .map(|s| { - s.try_to_primitive::(vm) + s.as_ref() + .try_to_primitive::(vm) .ok() .filter(|s| *s < len) .ok_or_else(|| vm.new_value_error("madvise start out of bounds")) @@ -355,7 +388,8 @@ mod mmap { let length = self .length .map(|s| { - s.try_to_primitive::(vm) + s.as_ref() + .try_to_primitive::(vm) .map_err(|_| vm.new_value_error("madvise length invalid")) }) .transpose()? @@ -393,14 +427,17 @@ mod mmap { .. } = args; - if (access != AccessMode::Default) + let trackfd = trackfd.into_bool(); + if (access.0 != AccessMode::Default as i32) && ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))) { return Err(vm.new_value_error("mmap can't specify both access and flags, prot.")); } + let access = access.into_mode(vm)?; // TODO: memmap2 doesn't support mapping with prot and flags right now - let (_flags, _prot, access) = match access { + #[cfg_attr(not(target_os = "linux"), allow(unused_variables))] + let (flags, _prot, access) = match access { AccessMode::Read => (MAP_SHARED, PROT_READ, access), AccessMode::Write => (MAP_SHARED, PROT_READ | PROT_WRITE, access), AccessMode::Copy => (MAP_PRIVATE, PROT_READ | PROT_WRITE, access), @@ -416,24 +453,24 @@ mod mmap { } }; - let fd = unsafe { crt_fd::Borrowed::try_borrow_raw(fd) }; + vm.audit("mmap.__new__", || (fd, args.length, access as i32, offset))?; + let anonymous = fd == -1 || flags & host_mmap::MAP_ANONYMOUS != 0; - // macOS: Issue #11277: fsync(2) is not enough on OS X - a special, OS X specific - // fcntl(2) is necessary to force DISKSYNC and get around mmap(2) bug + // Inspect the supplied descriptor before acquiring ownership, as + // CPython does. Invalid and non-regular fds do not impose file bounds. #[cfg(target_os = "macos")] - if let Ok(fd) = fd { + if fd != -1 { host_mmap::prepare_file_mapping(fd); } - - if let Ok(fd) = fd { - let file_len = host_mmap::file_len(fd).map_err(|err| err.to_pyexception(vm))?; - + if fd != -1 + && let Some(file_len) = host_mmap::regular_file_len(fd) + { if map_size == 0 { if file_len == 0 { return Err(vm.new_value_error("cannot mmap an empty file")); } - if offset > file_len { + if offset >= file_len { return Err(vm.new_value_error("mmap offset is greater than file size")); } @@ -445,35 +482,40 @@ mod mmap { } } - let (fd, mmap) = || -> std::io::Result<_> { - if let Ok(fd) = fd { - let (new_fd, mmap) = host_mmap::map_file( - fd, - offset, - map_size, - match access { - AccessMode::Default => host_mmap::AccessMode::Default, - AccessMode::Read => host_mmap::AccessMode::Read, - AccessMode::Write => host_mmap::AccessMode::Write, - AccessMode::Copy => host_mmap::AccessMode::Copy, - }, - )?; - Ok((Some(new_fd), mmap)) - } else { - let mmap = host_mmap::map_anon(map_size)?; - Ok((None, mmap)) - } - }() + let retained_fd = if fd != -1 && trackfd { + Some(host_mmap::duplicate_descriptor(fd).map_err(|err| err.to_pyexception(vm))?) + } else { + None + }; + let mmap = if anonymous { + host_mmap::map_anon(map_size) + } else { + // Keep an owned tracking fd alive through mmap when requested. + // Otherwise use the raw integer directly, without fabricating a + // BorrowedFd or creating a transient duplicate that can hit EMFILE. + let mapping_fd = retained_fd.as_ref().map_or(fd, |owned| owned.as_raw()); + host_mmap::map_file( + mapping_fd, + offset, + map_size, + match access { + AccessMode::Default => host_mmap::AccessMode::Default, + AccessMode::Read => host_mmap::AccessMode::Read, + AccessMode::Write => host_mmap::AccessMode::Write, + AccessMode::Copy => host_mmap::AccessMode::Copy, + }, + ) + } .map_err(|e| e.to_pyexception(vm))?; Ok(Self { closed: AtomicCell::new(false), mmap: PyMutex::new(Some(MmapObj::Mapped(mmap))), - fd: AtomicCell::new(if trackfd { - fd.map_or(-1, |owned| owned.into_raw()) - } else { - -1 - }), + #[cfg(target_os = "linux")] + anonymous, + #[cfg(target_os = "linux")] + private: flags & MAP_PRIVATE != 0, + fd: AtomicCell::new(retained_fd.map_or(-1, |owned| owned.into_raw())), offset, size: AtomicCell::new(map_size), pos: AtomicCell::new(0), @@ -485,157 +527,101 @@ mod mmap { #[cfg(windows)] fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + vm.audit("mmap.__new__", || { + (args.fileno, args.length, args.access.0, args.offset) + })?; + let access = args.access.into_mode(vm)?; let mut map_size = args.validate_new_args(vm)?; let MmapNewArgs { fileno, tagname, - access, + access: _, offset, + trackfd, .. } = args; + let trackfd = trackfd.into_bool(); - // Parse tagname: None or a string - let tag_str: Option = match tagname { - Some(ref obj) if !vm.is_none(obj) => { - let s = obj - .try_to_value::(vm) - .map_err(|_| vm.new_type_error("tagname must be a string or None"))?; - if memchr(b'\0', s.as_bytes()).is_some() { - cold_path(); - return Err(exceptions::nul_char_error(vm)); - } - Some(s) - } - _ => None, - }; - - // Get file handle from fileno. fileno -1 means anonymous mapping. - let fh: Option = if fileno != -1 { - // Convert CRT file descriptor to a Windows file mapping handle. - // Use suppress_iph! to avoid crashes when the fd is invalid. - // This is critical because socket fds wrapped via _open_osfhandle - // may cause crashes in _get_osfhandle on Windows. - // See Python bug https://bugs.python.org/issue30114 + // CPython historically accepts both -1 and 0 for anonymous maps. + let fh = if fileno != -1 && fileno != 0 { let handle = host_nt::handle_from_fd(fileno); - // Check for invalid handle value (-1 on Windows) if host_mmap::is_invalid_handle_value(handle as isize) { return Err(vm.new_os_error(format!("Invalid file descriptor: {fileno}"))); } - Some(handle as host_mmap::Handle) + host_mmap::prepare_file_mapping(fileno); + handle as host_mmap::Handle } else { - None + host_mmap::INVALID_HANDLE }; - - // Get file size if we have a file handle and map_size is 0 - let mut duplicated_handle: host_mmap::Handle = host_mmap::INVALID_HANDLE; - if let Some(fh) = fh { - // Duplicate handle so Python code can close the original - duplicated_handle = - host_mmap::duplicate_handle(fh).map_err(|e| e.to_pyexception(vm))?; - - // Get file size - let file_len = match host_mmap::get_file_len(fh) { - Ok(len) => len, - Err(err) => { - host_mmap::close_handle(duplicated_handle); - return Err(err.to_pyexception(vm)); - } - }; - - if map_size == 0 { - if file_len == 0 { - host_mmap::close_handle(duplicated_handle); - return Err(vm.new_value_error("cannot mmap an empty file")); - } - if offset >= file_len { - host_mmap::close_handle(duplicated_handle); - return Err(vm.new_value_error("mmap offset is greater than file size")); - } - if file_len - offset > isize::MAX as i64 { - host_mmap::close_handle(duplicated_handle); - return Err(vm.new_value_error("mmap length is too large")); - } - map_size = (file_len - offset) as usize; - } else { - // If map_size > file_len, extend the file (Windows behavior) - let required_size = offset.checked_add(map_size as i64).ok_or_else(|| { - host_mmap::close_handle(duplicated_handle); - vm.new_overflow_error("mmap size would cause file size overflow") - })?; - if required_size > file_len - && let Err(err) = host_mmap::extend_file(duplicated_handle, required_size) - { - host_mmap::close_handle(duplicated_handle); - return Err(err.to_pyexception(vm)); - } - } - } - - // When tagname is provided, use raw Win32 APIs for named shared memory - if let Some(ref tag) = tag_str { - let fh = if let Some(fh) = fh { - // Close the duplicated handle - we'll use the original - // file handle for CreateFileMappingW - if duplicated_handle != host_mmap::INVALID_HANDLE { - host_mmap::close_handle(duplicated_handle); - } - fh - } else { - host_mmap::INVALID_HANDLE - }; - - let named = host_mmap::create_named_mapping( - fh, - tag, - match access { - AccessMode::Default => host_mmap::AccessMode::Default, - AccessMode::Read => host_mmap::AccessMode::Read, - AccessMode::Write => host_mmap::AccessMode::Write, - AccessMode::Copy => host_mmap::AccessMode::Copy, - }, - offset, - map_size, - ) - .map_err(|err| { - if err.raw_os_error() == Some(host_mmap::EOVERFLOW) { - vm.new_overflow_error("mmap offset plus size would overflow") - } else { - err.to_pyexception(vm) - } - })?; - - return Ok(Self { - closed: AtomicCell::new(false), - mmap: PyMutex::new(Some(MmapObj::Named(named))), - handle: AtomicCell::new(host_mmap::INVALID_HANDLE as isize), - offset, - size: AtomicCell::new(map_size), - pos: AtomicCell::new(0), - exports: AtomicCell::new(0), - access, - }); - } - - let (handle, mmap) = if duplicated_handle != host_mmap::INVALID_HANDLE { - let mmap = Self::create_mmap_windows(duplicated_handle, offset, map_size, &access) - .map_err(|e| e.to_pyexception(vm))?; - (duplicated_handle as isize, mmap) + let retained_handle = if fh != host_mmap::INVALID_HANDLE && trackfd { + host_mmap::duplicate_handle(fh).map_err(|err| err.to_pyexception(vm))? } else { - // Anonymous mapping - let mmap = host_mmap::map_anon(map_size).map_err(|e| e.to_pyexception(vm))?; - (host_mmap::INVALID_HANDLE as isize, MmapObj::Mapped(mmap)) + host_mmap::INVALID_HANDLE }; - - Ok(Self { + let fh = if retained_handle != host_mmap::INVALID_HANDLE { + retained_handle + } else { + fh + }; + // From here on Self owns the retained handle, including error paths. + let result = Self { closed: AtomicCell::new(false), - mmap: PyMutex::new(Some(mmap)), - handle: AtomicCell::new(handle), + mmap: PyMutex::new(None), + handle: AtomicCell::new(retained_handle as isize), offset, size: AtomicCell::new(map_size), pos: AtomicCell::new(0), exports: AtomicCell::new(0), access, - }) + trackfd, + }; + if fh != host_mmap::INVALID_HANDLE && map_size == 0 { + let file_len = host_mmap::get_file_len(fh).map_err(|err| err.to_pyexception(vm))?; + if file_len == 0 { + return Err(vm.new_value_error("cannot mmap an empty file")); + } + if offset >= file_len { + return Err(vm.new_value_error("mmap offset is greater than file size")); + } + if file_len - offset > isize::MAX as i64 { + return Err(vm.new_value_error("mmap length is too large")); + } + map_size = (file_len - offset) as usize; + result.size.store(map_size); + } + let tag_str: Option = match tagname { + Some(ref obj) if !vm.is_none(obj) => { + let s = obj.try_to_value::(vm).map_err(|_| { + vm.new_type_error(format!( + "expected str or None for 'tagname', not {}", + obj.class().slot_name() + )) + })?; + if memchr(b'\0', s.as_bytes()).is_some() { + cold_path(); + return Err(exceptions::nul_char_error(vm)); + } + Some(s) + } + _ => None, + }; + // Let CreateFileMapping extend files, enforcing the requested access + // itself. Named and anonymous maps share exactly the same Win32 path. + let mapping = host_mmap::create_mapping( + fh, + tag_str.as_deref(), + match access { + AccessMode::Default => host_mmap::AccessMode::Default, + AccessMode::Read => host_mmap::AccessMode::Read, + AccessMode::Write => host_mmap::AccessMode::Write, + AccessMode::Copy => host_mmap::AccessMode::Copy, + }, + offset, + map_size, + ) + .map_err(|err| err.to_pyexception(vm))?; + *result.mmap.lock() = Some(MmapObj::Windows(mapping)); + Ok(result) } } @@ -653,7 +639,9 @@ mod mmap { impl AsBuffer for PyMmap { const RELEASE_BUFFER: bool = true; - fn as_buffer(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + fn as_buffer(zelf: &Py, vm: &VirtualMachine) -> PyResult { + // Publish the export while close/resize cannot invalidate the mapping. + let _mmap = zelf.check_valid(vm)?; let readonly = matches!(zelf.access, AccessMode::Read); let buf = PyBuffer::new( zelf.to_owned().into(), @@ -695,7 +683,13 @@ mod mmap { length: atomic_func!(|seq, _vm| Ok(PyMmap::sequence_downcast(seq).__len__())), item: atomic_func!(|seq, i, vm| { let zelf = PyMmap::sequence_downcast(seq); - zelf.getitem_by_index(i, vm) + let mmap = zelf.check_valid(vm)?; + let byte = usize::try_from(i) + .ok() + .and_then(|i| mmap.as_ref().unwrap().as_slice().get(i)) + .copied() + .ok_or_else(|| vm.new_index_error("mmap index out of range"))?; + Ok(PyBytes::from(vec![byte]).into_ref(&vm.ctx).into()) }), ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyMmap::sequence_downcast(seq); @@ -720,9 +714,10 @@ mod mmap { fn as_bytes_mut(&self) -> BorrowedValueMut<'_, [u8]> { PyMutexGuard::map(self.mmap.lock(), |m| { match m.as_mut().expect("mmap closed or invalid") { + #[cfg(unix)] MmapObj::Mapped(mmap) => mmap.as_mut_slice(), #[cfg(windows)] - MmapObj::Named(named) => named.as_mut_slice(), + MmapObj::Windows(named) => named.as_mut_slice(), } }) .into() @@ -760,9 +755,10 @@ mod mmap { } match self.check_valid(vm)?.deref_mut().as_mut().unwrap() { + #[cfg(unix)] MmapObj::Mapped(mmap) => Ok(f(mmap.as_mut_slice())), #[cfg(windows)] - MmapObj::Named(named) => Ok(f(named.as_mut_slice())), + MmapObj::Windows(named) => Ok(f(named.as_mut_slice())), } } @@ -770,28 +766,38 @@ mod mmap { let m = self.mmap.lock(); if m.is_none() { + drop(m); return Err(vm.new_value_error("mmap closed or invalid")); } Ok(m) } - /// TODO: impl resize - #[allow(dead_code)] - fn check_resizeable(&self, vm: &VirtualMachine) -> PyResult<()> { + #[cfg(any(target_os = "linux", windows, all(test, feature = "threading")))] + fn check_resizeable( + &self, + vm: &VirtualMachine, + ) -> PyResult>> { + // Borrowed buffers can hold the data lock across blocking I/O. if self.exports.load() > 0 { return Err(vm.new_buffer_error("mmap can't resize with extant buffers exported.")); } + let mmap = self.check_valid(vm)?; + if self.exports.load() > 0 { + drop(mmap); + return Err(vm.new_buffer_error("mmap can't resize with extant buffers exported.")); + } - #[cfg(unix)] if !self.trackfd { + drop(mmap); return Err(vm.new_value_error("mmap can't resize with trackfd=False.")); } if self.access == AccessMode::Write || self.access == AccessMode::Default { - return Ok(()); + return Ok(mmap); } + drop(mmap); Err(vm.new_type_error("mmap can't resize a readonly or copy-on-write memory map.")) } @@ -802,15 +808,16 @@ mod mmap { #[pymethod] fn close(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { - if Self::closed(zelf) { - return Ok(()); + // Reject an existing export without waiting for its borrowed-data guard. + if zelf.exports.load() > 0 { + return Err(vm.new_buffer_error("cannot close exported pointers exist.")); } - + let mut mmap = zelf.mmap.lock(); if zelf.exports.load() > 0 { + drop(mmap); return Err(vm.new_buffer_error("cannot close exported pointers exist.")); } - let mut mmap = zelf.mmap.lock(); zelf.closed.store(true); *mmap = None; @@ -819,12 +826,25 @@ mod mmap { Ok(()) } - fn get_find_range(&self, options: &FindOptions) -> (usize, usize) { + fn get_find_range( + &self, + initial_pos: usize, + initial_size: usize, + start: Option, + end: Option, + ) -> (usize, usize) { let size = self.__len__(); - let start = options - .start - .map_or_else(|| self.pos(), |start| start.saturated_at(size)); - let end = options.end.map_or(size, |end| end.saturated_at(size)); + let start = start.map_or_else( + || initial_pos, + |start| { + if start < 0 { + start.saturated_at(size) + } else { + start as usize + } + }, + ); + let end = end.map_or_else(|| initial_size.min(size), |end| end.saturated_at(size)); (start, end) } @@ -834,15 +854,44 @@ mod mmap { reverse: bool, vm: &VirtualMachine, ) -> PyResult { + // Bind the positional arguments before acquiring the buffer, as + // Clinic does. The buffer can call Python and close the mapping. + let view = ArgBytesLike::try_from_borrowed_object(vm, &options.view)?; + let mmap = self.check_valid(vm)?; + let initial_pos = self.pos(); + let initial_size = self.__len__(); + drop(mmap); + + let start = options + .start + .as_ref() + .map(|value| isize::try_from_borrowed_object(vm, value)) + .transpose()?; + let end = if start.is_some() { + options + .end + .as_ref() + .map(|value| isize::try_from_borrowed_object(vm, value)) + .transpose()? + } else { + None + }; + // Index conversion may have closed the mapping. Do not borrow + // search bytes from an exporter before reporting that closure. + if self.closed.load() { + return Err(vm.new_value_error("mmap closed or invalid")); + } + // A search view may itself be this mmap (or a view of it). Take + // an unlocked snapshot before locking the mapping for the scan. + let sub = view.borrow_buf_unlocked(vm)?; let mmap = self.check_valid(vm)?; - let (start, end) = self.get_find_range(&options); + let (start, end) = self.get_find_range(initial_pos, initial_size, start, end); // A reversed range contains nothing, not even the empty subsequence. if start > end { return Ok(PyInt::from(-1isize)); } - let sub = &options.view; // The empty subsequence matches at the edge the scan begins from: // the start of the range going forward, the end going backward. if sub.is_empty() { @@ -853,9 +902,9 @@ mod mmap { let buf = &mmap.as_ref().unwrap().as_slice()[start..end]; let mut windows = buf.windows(sub.len()); let pos = if reverse { - windows.rposition(|window| window == sub) + windows.rposition(|window| window == &*sub) } else { - windows.position(|window| window == sub) + windows.position(|window| window == &*sub) }; Ok(pos.map_or_else(|| PyInt::from(-1isize), |i| PyInt::from(start + i))) @@ -873,6 +922,8 @@ mod mmap { #[pymethod] fn flush(zelf: &Py, options: FlushOptions, vm: &VirtualMachine) -> PyResult<()> { + let mmap = zelf.check_valid(vm)?; + let flags = options.flags; let (offset, size) = options .values(zelf.__len__()) .ok_or_else(|| vm.new_value_error("flush values out of range"))?; @@ -881,13 +932,15 @@ mod mmap { return Ok(()); } - match zelf.check_valid(vm)?.deref().as_ref().unwrap() { + match mmap.deref().as_ref().unwrap() { + #[cfg(unix)] MmapObj::Mapped(mmap) => { - mmap.flush_range(offset, size) + mmap.flush_range(offset, size, flags) .map_err(|e| e.to_pyexception(vm))?; } #[cfg(windows)] - MmapObj::Named(named) => { + MmapObj::Windows(named) => { + let _ = flags; named .flush_range(offset, size) .map_err(|e| e.to_pyexception(vm))?; @@ -897,20 +950,59 @@ mod mmap { Ok(()) } + #[pymethod] + fn set_name(zelf: &Py, name: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<()> { + let name = + alloc::ffi::CString::new(name.as_str()).map_err(|err| err.to_pyexception(vm))?; + #[cfg(target_os = "linux")] + { + const PREFIX: &str = "cpython:mmap:"; + if name.as_bytes().len() > 79 - PREFIX.len() { + return Err(vm.new_value_error("name is too long")); + } + if !zelf.anonymous { + return Err( + vm.new_value_error("Cannot set annotation on non-anonymous mappings") + ); + } + // As in CPython's release build, kernel annotations are enabled + // only in development mode. + if vm.state.config.settings.dev_mode { + let annotation = + alloc::ffi::CString::new([PREFIX.as_bytes(), name.as_bytes()].concat()) + .expect("the name was checked for embedded NUL characters"); + let mmap = zelf.mmap.lock(); + let address = mmap + .as_ref() + .map_or(0, |mapping| mapping.as_slice().as_ptr() as usize); + host_mmap::set_mapping_name(address, zelf.__len__(), &annotation) + .map_err(|err| err.to_pyexception(vm))?; + } + Ok(()) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (zelf, name); + Err(vm.new_not_implemented_error( + "Annotation of mmap is not supported on this platform", + )) + } + } + #[cfg(all(unix, not(target_os = "redox")))] #[pymethod] fn madvise(zelf: &Py, options: AdviseOptions, vm: &VirtualMachine) -> PyResult<()> { + let guard = zelf.check_valid(vm)?; let (option, start, length) = options.values(zelf.__len__(), vm)?; if !host_mmap::validate_advice(option) { return Err(vm.new_value_error("Not a valid Advice value")); } - let guard = zelf.check_valid(vm)?; let mmap = guard.deref().as_ref().unwrap(); match mmap { MmapObj::Mapped(m) => m.madvise_range(start, length, option), #[cfg(windows)] - MmapObj::Named(_) => unreachable!("unix-only method"), + MmapObj::Windows(_) => unreachable!("unix-only method"), } .map_err(|e| e.to_pyexception(vm))?; @@ -920,9 +1012,9 @@ mod mmap { #[pymethod(name = "move")] fn move_( zelf: &Py, - dest: PyIntRef, - src: PyIntRef, - count: PyIntRef, + dest: ArgIndex, + src: ArgIndex, + count: ArgIndex, vm: &VirtualMachine, ) -> PyResult<()> { fn args( @@ -947,14 +1039,13 @@ mod mmap { Some((dest, src, cnt)) } - let size = zelf.__len__(); - let (dest, src, cnt) = args(&dest, &src, &count, size, vm) - .ok_or_else(|| vm.new_value_error("source, destination, or count out of range"))?; - - let dest_end = dest + cnt; - let src_end = src + cnt; - zelf.try_writable(vm, |mmap| { + let (dest, src, cnt) = + args(dest.as_ref(), src.as_ref(), count.as_ref(), mmap.len(), vm).ok_or_else( + || vm.new_value_error("source, destination, or count out of range"), + )?; + let dest_end = dest + cnt; + let src_end = src + cnt; let src_buf = mmap[src..src_end].to_vec(); (&mut mmap[dest..dest_end]) .write(&src_buf) @@ -965,19 +1056,20 @@ mod mmap { #[pymethod] fn read(zelf: &Py, args: ReadArgs, vm: &VirtualMachine) -> PyResult { - let num_bytes = args - .n - .map(|obj| { - let class = obj.class().to_owned(); - obj.try_into_value::>(vm).map_err(|_| { + let num_bytes = match args.n { + Some(obj) if !vm.is_none(&obj) => { + let index = obj.try_index_opt(vm).ok_or_else(|| { + let class = obj.class(); + let name = class.slot_name(); + let name = &name[..name.floor_char_boundary(200)]; vm.new_type_error(format!( - "read argument must be int or None, not {}", - class.name() + "argument should be integer or None, not '{name}'" )) - }) - }) - .transpose()? - .flatten(); + })??; + Some(index.try_to_primitive::(vm)?) + } + _ => None, + }; let mmap = zelf.check_valid(vm)?; let pos = zelf.pos(); let remaining = zelf.__len__().saturating_sub(pos); @@ -985,6 +1077,9 @@ mod mmap { .filter(|&n| n >= 0 && (n as usize) <= remaining) .map_or(remaining, |n| n as usize); + if num_bytes == 0 { + return Ok(PyBytes::from(vec![]).into_ref(&vm.ctx)); + } let end_pos = pos + num_bytes; let bytes = mmap.deref().as_ref().unwrap().as_slice()[pos..end_pos].to_vec(); @@ -997,12 +1092,13 @@ mod mmap { #[pymethod] fn read_byte(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let mmap = zelf.check_valid(vm)?; let pos = zelf.pos(); if pos >= zelf.__len__() { return Err(vm.new_value_error("read byte out of range")); } - let b = zelf.check_valid(vm)?.deref().as_ref().unwrap().as_slice()[pos]; + let b = mmap.deref().as_ref().unwrap().as_slice()[pos]; zelf.advance_pos(1); @@ -1011,8 +1107,8 @@ mod mmap { #[pymethod] fn readline(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let pos = zelf.pos(); let mmap = zelf.check_valid(vm)?; + let pos = zelf.pos(); let remaining = zelf.__len__().saturating_sub(pos); if remaining == 0 { @@ -1037,104 +1133,74 @@ mod mmap { Ok(result) } - #[cfg(unix)] + #[cfg(target_os = "linux")] #[pymethod] - fn resize(zelf: &Py, _newsize: PyIntRef, vm: &VirtualMachine) -> PyResult<()> { - zelf.check_resizeable(vm)?; - // TODO: implement using mremap on Linux - Err(vm.new_system_error("mmap: resizing not available--no mremap()")) + fn resize(zelf: &Py, newsize: ArgIndex, vm: &VirtualMachine) -> PyResult<()> { + let newsize: isize = newsize.as_ref().try_to_primitive(vm).map_err(|_| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") + })?; + // Reject exports before taking the data lock, and retain the guard + // through truncation and remapping so a new export cannot race us. + let mut mmap = zelf.check_resizeable(vm)?; + let file_size = i128::from(zelf.offset) + newsize as i128; + if newsize < 0 || file_size > isize::MAX as i128 { + return Err(vm.new_value_error("new size out of range")); + } + let newsize = newsize as usize; + if zelf.anonymous && !zelf.private && newsize > zelf.__len__() { + return Err(vm.new_value_error("mmap: can't expand a shared anonymous mapping")); + } + let fd = zelf.fd.load(); + if fd != -1 { + let fd = unsafe { crt_fd::Borrowed::try_borrow_raw(fd) } + .map_err(|err| err.to_pyexception(vm))?; + let file_size = file_size + .try_into() + .map_err(|_| vm.new_value_error("new size out of range"))?; + crt_fd::ftruncate(fd, file_size).map_err(|err| err.to_pyexception(vm))?; + } + let MmapObj::Mapped(mapping) = mmap.as_mut().unwrap(); + // The mapping is locked, exported buffers are prohibited, and its + // backing file has already been resized to cover the new mapping. + unsafe { mapping.remap(newsize) }.map_err(|err| err.to_pyexception(vm))?; + zelf.size.store(newsize); + Ok(()) } #[cfg(windows)] #[pymethod] - fn resize(zelf: &Py, newsize: PyIntRef, vm: &VirtualMachine) -> PyResult<()> { - zelf.check_resizeable(vm)?; - - let newsize: usize = newsize - .try_to_primitive(vm) - .map_err(|_| vm.new_value_error("new size out of range"))?; - - if newsize == 0 { - return Err(vm.new_value_error("new size must be positive")); - } - - let handle = zelf.handle.load(); - - // Get the lock on mmap - let mut mmap_guard = zelf.mmap.lock(); - - // Check if this is a Named mmap - these cannot be resized - if let Some(MmapObj::Named(_)) = mmap_guard.as_ref() { - return Err(vm.new_os_error("mmap: cannot resize a named memory mapping")); + fn resize(zelf: &Py, newsize: ArgIndex, vm: &VirtualMachine) -> PyResult<()> { + let newsize: isize = newsize.as_ref().try_to_primitive(vm).map_err(|_| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") + })?; + let mut mmap = zelf.check_resizeable(vm)?; + let file_size = i128::from(zelf.offset) + newsize as i128; + if newsize < 0 || file_size > isize::MAX as i128 { + return Err(vm.new_value_error("new size out of range")); } - - let is_anonymous = host_mmap::is_invalid_handle_value(handle); - - if is_anonymous { - // For anonymous mmap, we need to: - // 1. Create a new anonymous mmap with the new size - // 2. Copy data from old mmap to new mmap - // 3. Replace the old mmap - - let old_size = zelf.size.load(); - let copy_size = core::cmp::min(old_size, newsize); - - // Create new anonymous mmap - let mut new_mmap = - host_mmap::map_anon(newsize).map_err(|e| e.to_pyexception(vm))?; - - // Copy data from old mmap to new mmap - if let Some(old_mmap) = mmap_guard.as_ref() { - let src = &old_mmap.as_slice()[..copy_size]; - new_mmap.as_mut_slice()[..copy_size].copy_from_slice(src); - } - - *mmap_guard = Some(MmapObj::Mapped(new_mmap)); - zelf.size.store(newsize); - } else { - // File-backed mmap resize - - // Drop the current mmap to release the file mapping - *mmap_guard = None; - - let required_size = zelf.offset + newsize as i64; - if let Err(err) = host_mmap::extend_file(handle as host_mmap::Handle, required_size) - { - // Restore original mmap on error - zelf.try_restore_mmap( - &mut mmap_guard, - handle as host_mmap::Handle, - zelf.size.load(), - ); - return Err(err.to_pyexception(vm)); - } - - // Create new mmap with the new size - let new_mmap = Self::create_mmap_windows( - handle as host_mmap::Handle, + let MmapObj::Windows(mapping) = mmap.as_mut().unwrap(); + // The lock and export check keep all pointers private during remapping. + let result = unsafe { + mapping.resize( + zelf.handle.load() as host_mmap::Handle, zelf.offset, - newsize, - &zelf.access, + newsize as usize, ) - .map_err(|e| e.to_pyexception(vm))?; - - *mmap_guard = Some(new_mmap); - zelf.size.store(newsize); - } - - // Adjust position if it's beyond the new size - let pos = zelf.pos.load(); - if pos > newsize { - zelf.pos.store(newsize); + }; + if mapping.is_valid() { + zelf.size.store(mapping.size()); + } else { + *mmap = None; + zelf.closed.store(true); } - - Ok(()) + result.map_err(|err| err.to_pyexception(vm)) } #[pymethod] fn seek(zelf: &Py, args: SeekArgs, vm: &VirtualMachine) -> PyResult { let dist = args.pos; let how = args.whence; + let _mmap = zelf.check_valid(vm)?; let size = zelf.__len__(); let new_pos = match how { @@ -1168,15 +1234,28 @@ mod mmap { #[cfg(unix)] #[pymethod] - fn size(zelf: &Py, vm: &VirtualMachine) -> std::io::Result { - let fd = unsafe { crt_fd::Borrowed::try_borrow_raw(zelf.fd.load())? }; - let file_len = host_mmap::file_len(fd)?; + fn size(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let _mmap = zelf.check_valid(vm)?; + if !zelf.trackfd { + return Err(vm.new_value_error("can't get size with trackfd=False")); + } + let fd = zelf.fd.load(); + if fd == -1 { + return Ok(PyInt::from(zelf.__len__()).into_ref(&vm.ctx)); + } + let fd = unsafe { crt_fd::Borrowed::try_borrow_raw(fd) } + .map_err(|err| err.to_pyexception(vm))?; + let file_len = host_mmap::file_len(fd).map_err(|err| err.to_pyexception(vm))?; Ok(PyInt::from(file_len).into_ref(&vm.ctx)) } #[cfg(windows)] #[pymethod] fn size(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let _mmap = zelf.check_valid(vm)?; + if !zelf.trackfd { + return Err(vm.new_value_error("can't get size with trackfd=False")); + } let handle = zelf.handle.load(); if host_mmap::is_invalid_handle_value(handle) { // Anonymous mapping, return the mmap size @@ -1201,8 +1280,6 @@ mod mmap { #[pymethod] fn write(zelf: &Py, bytes: ArgBytesLike, vm: &VirtualMachine) -> PyResult { let self_ = &**zelf; - let pos = self_.pos(); - let size = self_.__len__(); // Writing locks the map, and reading a source that views this same // map locks it too, so such a source is copied out first. @@ -1216,19 +1293,18 @@ mod mmap { &borrowed }; - if pos > size || size - pos < data.len() { - return Err(vm.new_value_error("data out of range")); - } - let len = self_.try_writable(vm, |mmap| { + let pos = self_.pos(); + if pos > mmap.len() || mmap.len() - pos < data.len() { + return Err(vm.new_value_error("data out of range")); + } (&mut mmap[pos..(pos + data.len())]) .write(data) .map_err(|err| err.to_pyexception(vm))?; + self_.advance_pos(data.len()); Ok(data.len()) })??; - self_.advance_pos(len); - Ok(PyInt::from(len).into_ref(&vm.ctx)) } @@ -1236,18 +1312,15 @@ mod mmap { fn write_byte(zelf: &Py, byte: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let b = value_from_object(vm, &byte)?; - let pos = zelf.pos(); - let size = zelf.__len__(); - - if pos >= size { - return Err(vm.new_value_error("write byte out of range")); - } - zelf.try_writable(vm, |mmap| { + let pos = zelf.pos(); + if pos >= mmap.len() { + return Err(vm.new_value_error("write byte out of range")); + } mmap[pos] = b; - })?; - - zelf.advance_pos(1); + zelf.advance_pos(1); + Ok(()) + })??; Ok(()) } @@ -1290,49 +1363,13 @@ mod mmap { } impl PyMmap { - #[cfg(windows)] - fn create_mmap_windows( - handle: host_mmap::Handle, - offset: i64, - size: usize, - access: &AccessMode, - ) -> io::Result { - host_mmap::map_handle( - handle, - offset, - size, - match access { - AccessMode::Default => host_mmap::AccessMode::Default, - AccessMode::Read => host_mmap::AccessMode::Read, - AccessMode::Write => host_mmap::AccessMode::Write, - AccessMode::Copy => host_mmap::AccessMode::Copy, - }, - ) - .map(MmapObj::Mapped) - } - - /// Try to restore mmap after a failed resize operation. - /// Returns true if restoration succeeded, false otherwise. - /// If restoration fails, marks the mmap as closed. - #[cfg(windows)] - fn try_restore_mmap( - &self, - mmap_guard: &mut Option, - handle: host_mmap::Handle, - size: usize, - ) { - match Self::create_mmap_windows(handle, self.offset, size, &self.access) { - Ok(mmap) => *mmap_guard = Some(mmap), - Err(_) => self.closed.store(true), - } - } - fn getitem_by_index(&self, i: isize, vm: &VirtualMachine) -> PyResult { + let mmap = self.check_valid(vm)?; let i = i .wrapped_at(self.__len__()) .ok_or_else(|| vm.new_index_error("mmap index out of range"))?; - let b = self.check_valid(vm)?.deref().as_ref().unwrap().as_slice()[i]; + let b = mmap.deref().as_ref().unwrap().as_slice()[i]; Ok(PyInt::from(b).into_ref(&vm.ctx).into()) } @@ -1342,9 +1379,8 @@ mod mmap { slice: &SaturatedSlice, vm: &VirtualMachine, ) -> PyResult { - let (range, step, slice_len) = slice.adjust_indices(self.__len__()); - let mmap = self.check_valid(vm)?; + let (range, step, slice_len) = slice.adjust_indices(self.__len__()); let slice_data = mmap.deref().as_ref().unwrap().as_slice(); if slice_len == 0 { @@ -1369,7 +1405,7 @@ mod mmap { } fn getitem_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - match SequenceIndex::try_from_borrowed_object(vm, needle, "mmap")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => self.getitem_by_index(i, vm), SequenceIndex::Slice(slice) => self.getitem_by_slice(&slice, vm), } @@ -1381,7 +1417,7 @@ mod mmap { value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { - match SequenceIndex::try_from_borrowed_object(vm, needle, "mmap")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => Self::setitem_by_index(zelf, i, value, vm), SequenceIndex::Slice(slice) => Self::setitem_by_slice(zelf, &slice, value, vm), } @@ -1393,17 +1429,15 @@ mod mmap { value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { - let i: usize = i - .wrapped_at(self.__len__()) - .ok_or_else(|| vm.new_index_error("mmap index out of range"))?; - let b = value_from_object(vm, value)?; self.try_writable(vm, |mmap| { + let i = i + .wrapped_at(mmap.len()) + .ok_or_else(|| vm.new_index_error("mmap index out of range"))?; mmap[i] = b; - })?; - - Ok(()) + Ok(()) + })? } fn setitem_by_slice( @@ -1412,43 +1446,133 @@ mod mmap { value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { - let (range, step, slice_len) = slice.adjust_indices(self.__len__()); - let bytes = bytes_from_object(vm, value)?; - if bytes.len() != slice_len { - return Err(vm.new_index_error("mmap slice assignment is wrong size")); - } + self.try_writable(vm, |mmap| { + let (range, step, slice_len) = slice.adjust_indices(mmap.len()); - if slice_len == 0 { - // do nothing - Ok(()) - } else if step == 1 { - self.try_writable(vm, |mmap| { + if bytes.len() != slice_len { + return Err(vm.new_index_error("mmap slice assignment is wrong size")); + } + + if slice_len == 0 { + // do nothing + } else if step == 1 { (&mut mmap[range]) .write(&bytes) .map_err(|err| err.to_pyexception(vm))?; - Ok(()) - })? - } else { - let mut bi = 0; // bytes index - if step.is_negative() { - for i in range.rev().step_by(step.unsigned_abs()) { - self.try_writable(vm, |mmap| { - mmap[i] = bytes[bi]; - })?; - bi += 1; - } } else { - for i in range.step_by(step.unsigned_abs()) { - self.try_writable(vm, |mmap| { + let mut bi = 0; // bytes index + if step.is_negative() { + for i in range.rev().step_by(step.unsigned_abs()) { mmap[i] = bytes[bi]; - })?; - bi += 1; + bi += 1; + } + } else { + for i in range.step_by(step.unsigned_abs()) { + mmap[i] = bytes[bi]; + bi += 1; + } } } Ok(()) - } + })? + } + } + + #[cfg(test)] + #[cfg(feature = "threading")] + mod tests { + use super::*; + use core::time::Duration; + use std::{sync::mpsc, thread}; + + fn rejects_borrowed_buffer(resize: bool) { + let builder = crate::vm::Interpreter::builder(Default::default()); + let defs = crate::stdlib_module_defs(&builder.ctx); + let interp = builder + .add_native_modules(&defs) + .add_frozen_modules(rustpython_pylib::FROZEN_STDLIB) + .build(); + interp.enter(|vm| { + let module = vm.import("mmap", 0).unwrap(); + let mapped = module + .get_attr("mmap", vm) + .unwrap() + .call((-1, 1), vm) + .unwrap() + .downcast::() + .unwrap(); + let buffer = PyMmap::as_buffer(&mapped, vm).unwrap(); + thread::scope(|scope| { + let (ready_tx, ready_rx) = mpsc::channel(); + let (done_tx, done_rx) = mpsc::channel(); + let buffer = &buffer; + let borrower = scope.spawn(move || { + // A native I/O operation can keep this guard while detached. + let bytes = buffer.as_contiguous().unwrap(); + assert!(bytes.is_locked()); + ready_tx.send(()).unwrap(); + // Release even on a regression, so the test fails rather than hangs. + let rejected_before_release = + done_rx.recv_timeout(Duration::from_secs(5)).is_ok(); + drop(bytes); + rejected_before_release + }); + ready_rx.recv().unwrap(); + let result = if resize { + mapped.check_resizeable(vm).map(drop) + } else { + PyMmap::close(&mapped, vm) + }; + let _ = done_tx.send(()); + assert!( + borrower.join().unwrap(), + "export rejection waited for the borrowed buffer" + ); + assert!( + result + .unwrap_err() + .class() + .is(vm.ctx.exceptions.buffer_error) + ); + }); + drop(buffer); + PyMmap::close(&mapped, vm).unwrap(); + }); + } + + #[test] + fn close_rejects_borrowed_buffer() { + rejects_borrowed_buffer(false); + } + + #[cfg(windows)] + #[test] + fn untracked_mapping_cannot_resize() { + crate::vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let mapped = PyMmap::py_new( + vm.ctx.types.type_type, + MmapNewArgs { + fileno: -1, + length: 64, + tagname: None, + access: AccessArg::DEFAULT, + offset: 0, + trackfd: ArgIntoBool::FALSE, + }, + vm, + ) + .unwrap(); + assert_eq!(mapped.__len__(), 64); + assert!(!mapped.trackfd); + assert!(mapped.check_resizeable(vm).is_err()); + }); + } + + #[test] + fn resize_rejects_borrowed_buffer() { + rejects_borrowed_buffer(true); } } diff --git a/crates/stdlib/src/multiprocessing.rs b/crates/stdlib/src/multiprocessing.rs index 5c335649509..3ec29bd3516 100644 --- a/crates/stdlib/src/multiprocessing.rs +++ b/crates/stdlib/src/multiprocessing.rs @@ -115,15 +115,15 @@ mod _multiprocessing { #[derive(FromArgs)] struct SemLockNewArgs { - #[pyarg(positional)] + #[pyarg(any)] kind: i32, - #[pyarg(positional)] + #[pyarg(any)] value: i32, - #[pyarg(positional)] + #[pyarg(any)] maxvalue: i32, - #[pyarg(positional)] + #[pyarg(any)] name: String, - #[pyarg(positional)] + #[pyarg(any)] unlink: bool, } @@ -266,8 +266,8 @@ mod _multiprocessing { Ok(()) } - #[pymethod(name = "__enter__")] - fn enter(zelf: &Py, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __enter__(zelf: &Py, vm: &VirtualMachine) -> PyResult { Self::acquire( zelf, AcquireArgs { @@ -283,8 +283,8 @@ mod _multiprocessing { Self::release(zelf, vm) } - #[pyclassmethod(name = "_rebuild")] - fn rebuild( + #[pyclassmethod] + fn _rebuild( cls: PyTypeRef, handle: isize, kind: i32, @@ -401,23 +401,29 @@ mod _multiprocessing { } #[pyfunction] - fn closesocket(socket: usize, vm: &VirtualMachine) -> PyResult<()> { - host_multiprocessing::close_socket(socket as host_multiprocessing::RawSocket) + fn closesocket(handle: usize, vm: &VirtualMachine) -> PyResult<()> { + host_multiprocessing::close_socket(handle as host_multiprocessing::RawSocket) .map_err(|_| vm.new_last_os_error()) } #[pyfunction] - fn recv(socket: usize, size: usize, vm: &VirtualMachine) -> PyResult> { - host_multiprocessing::recv_socket(socket as host_multiprocessing::RawSocket, size) - .map_err(|_| vm.new_last_os_error()) + fn recv(handle: usize, size: usize, vm: &VirtualMachine) -> PyResult> { + let mut buf = vm + .allow_threads(|| { + host_multiprocessing::recv_socket(handle as host_multiprocessing::RawSocket, size) + }) + .map_err(|error| error.to_pyexception(vm))?; + buf.shrink_to_fit(); + Ok(buf) } #[pyfunction] - fn send(socket: usize, buf: ArgBytesLike, vm: &VirtualMachine) -> PyResult { - buf.with_ref(|b| { - host_multiprocessing::send_socket(socket as host_multiprocessing::RawSocket, b) + fn send(handle: usize, buf: ArgBytesLike, vm: &VirtualMachine) -> PyResult { + let buf = buf.borrow_buf_unlocked(vm)?; + vm.allow_threads(|| { + host_multiprocessing::send_socket(handle as host_multiprocessing::RawSocket, &buf) }) - .map_err(|_| vm.new_last_os_error()) + .map_err(|error| error.to_pyexception(vm)) } } @@ -509,15 +515,15 @@ mod _multiprocessing { #[derive(FromArgs)] struct SemLockNewArgs { - #[pyarg(positional)] + #[pyarg(any)] kind: i32, - #[pyarg(positional)] + #[pyarg(any)] value: i32, - #[pyarg(positional)] + #[pyarg(any)] maxvalue: i32, - #[pyarg(positional)] + #[pyarg(any)] name: String, - #[pyarg(positional)] + #[pyarg(any)] unlink: bool, } @@ -719,8 +725,8 @@ mod _multiprocessing { } // _multiprocessing_SemLock___enter___impl - #[pymethod(name = "__enter__")] - fn enter(zelf: &Py, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __enter__(zelf: &Py, vm: &VirtualMachine) -> PyResult { // return _multiprocessing_SemLock_acquire_impl(self, 1, Py_None); Self::acquire( zelf, @@ -740,8 +746,8 @@ mod _multiprocessing { // Rebuild a SemLock from pickled state. // _multiprocessing_SemLock__rebuild_impl - #[pyclassmethod(name = "_rebuild")] - fn rebuild( + #[pyclassmethod] + fn _rebuild( cls: PyTypeRef, _handle: isize, kind: i32, diff --git a/crates/stdlib/src/openssl.rs b/crates/stdlib/src/openssl.rs index 5470f788462..c60f3918ddf 100644 --- a/crates/stdlib/src/openssl.rs +++ b/crates/stdlib/src/openssl.rs @@ -1,6 +1,11 @@ +mod distrusted; // spell-checker:disable mod cert; +#[cfg(all(unix, not(target_os = "aix")))] +mod driver; +#[cfg(all(unix, not(target_os = "aix")))] +mod waiter; // SSL exception types (shared with rustls backend) #[allow( @@ -39,9 +44,21 @@ pub(crate) use _ssl::module_def; #[cfg(ossl111)] ossl111, #[cfg(windows)] windows))] mod _ssl { + use crate::vm::function::PySetterValue; use core::hint::cold_path; use super::bio; + #[cfg(all(unix, not(target_os = "aix")))] + use super::{ + driver::{Driver, Needs, Permit, WriteOwner}, + waiter::{ProgressRegistry, ProgressWaiter}, + }; + #[cfg(not(all(unix, not(target_os = "aix"))))] + use crate::socket::{SockWaitKind, sock_wait}; + #[cfg(all(unix, not(target_os = "aix")))] + use alloc::sync::Arc; + #[cfg(all(unix, not(target_os = "aix")))] + use std::os::fd::AsRawFd; // Import error types and helpers used in this module (others are exposed via pymodule(with(...))) use super::ssl_error::{ @@ -53,20 +70,21 @@ mod _ssl { LazyLock, PyDetachingRwLock, PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard, }, - socket::{self, PySocket, SockWaitKind, sock_wait}, + socket::{self, PySocket}, vm::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{ PyBaseException, PyBaseExceptionRef, PyBytesRef, PyListRef, PyModule, PyStrRef, - PyType, PyWeak, + PyType, PyUtf8StrRef, PyWeak, }, class_or_notimplemented, convert::ToPyException, exceptions, function::{ - ArgBytesLike, ArgMemoryBuffer, ArgStrOrBytesLike, Either, FsPath, OptionalArg, - PyComparisonValue, + ArgBytesLike, ArgIndex, ArgIntoBool, ArgIntoFloat, ArgMemoryBuffer, + ArgStrOrBytesLike, Either, FsPath, OptionalArg, PyComparisonValue, }, + object::{Traverse, TraverseFn}, stdlib::_warnings, types::{Comparable, Constructor, PyComparisonOp}, utils::ToCString, @@ -74,7 +92,6 @@ mod _ssl { }; use crossbeam_utils::atomic::AtomicCell; use foreign_types_shared::{ForeignType, ForeignTypeRef}; - use memchr::memchr; use openssl::{ asn1::{Asn1Object, Asn1ObjectRef}, error::ErrorStack, @@ -231,7 +248,9 @@ mod _ssl { #[pyattr] const HAS_TLSv1_3: bool = cfg!(ossl111); #[pyattr] - const HAS_PSK: bool = true; + const HAS_PSK: bool = false; // External PSK callbacks are not implemented. + #[pyattr] + const HAS_PSK_TLS13: bool = false; #[pyattr] const HAS_PHA: bool = cfg!(ossl111); @@ -249,7 +268,7 @@ mod _ssl { // SSL_VERIFY constants for post-handshake authentication #[cfg(ossl111)] - const SSL_VERIFY_POST_HANDSHAKE: core::ffi::c_int = 0x20; + use sys::SSL_VERIFY_POST_HANDSHAKE; // the openssl version from the API headers @@ -433,8 +452,8 @@ mod _ssl { ) -> PyResult<(&'static str, PyObjectRef, &'static str, PyObjectRef)> { let (cert_file_env, cert_dir_env) = &*CERT_ENV_NAMES; let (cert_file, cert_dir) = get_cert_file_dir(); - let cert_file = OsPath::new_str(cert_file.as_path()).filename(vm); - let cert_dir = OsPath::new_str(cert_dir.as_path()).filename(vm); + let cert_file = OsPath::new_str(cert_file.as_path()).filename(vm)?; + let cert_dir = OsPath::new_str(cert_dir.as_path()).filename(vm)?; Ok(( cert_file_env.as_str(), cert_file, @@ -449,7 +468,8 @@ mod _ssl { } #[pyfunction(name = "RAND_add")] - fn rand_add(string: ArgStrOrBytesLike, entropy: f64) { + fn rand_add(string: ArgStrOrBytesLike, entropy: ArgIntoFloat) { + let entropy = entropy.into_float(); let f = |b: &[u8]| { for buf in b.chunks(core::ffi::c_int::MAX as usize) { unsafe { sys::RAND_add(buf.as_ptr() as *const _, buf.len() as _, entropy) } @@ -468,13 +488,7 @@ mod _ssl { Ok(buf) } - // Callback data stored in SSL ex_data for SNI/msg callbacks - struct SniCallbackData { - ssl_context: PyRef, - // Use weak reference to avoid reference cycle: - // PySslSocket -> SslStream -> SSL -> ex_data -> SniCallbackData -> PySslSocket - ssl_socket_weak: PyRef, - } + type ActiveSslConnection = (*const PyDetachingRwLock, *mut sys::SSL); // Thread-local storage for VirtualMachine pointer during handshake // SNI callback is only called during handshake which is synchronous @@ -483,148 +497,106 @@ mod _ssl { // SSL pointer during handshake - needed because connection lock is held during handshake // and callbacks may need to access SSL without acquiring the lock static HANDSHAKE_SSL_PTR: core::cell::Cell> = const { core::cell::Cell::new(None) }; + #[cfg(all(unix, not(target_os = "aix")))] + static SSL_IO_CALLS: core::cell::RefCell> = const { core::cell::RefCell::new(Vec::new()) }; + static HANDSHAKE_CONNECTIONS: core::cell::RefCell> = const { core::cell::RefCell::new(Vec::new()) }; } // RAII guard to set/clear thread-local handshake context struct HandshakeVmGuard { - _ssl_ptr: *mut sys::SSL, + previous_vm: Option<*const VirtualMachine>, + previous_ssl: Option<*mut sys::SSL>, } impl HandshakeVmGuard { - fn new(vm: &VirtualMachine, ssl_ptr: *mut sys::SSL) -> Self { - HANDSHAKE_VM.with(|cell| cell.set(Some(vm as *const _))); - HANDSHAKE_SSL_PTR.with(|cell| cell.set(Some(ssl_ptr))); - HandshakeVmGuard { _ssl_ptr: ssl_ptr } + fn new( + vm: &VirtualMachine, + connection: &PyDetachingRwLock, + ssl_ptr: *mut sys::SSL, + ) -> Self { + HANDSHAKE_CONNECTIONS.with(|connections| { + connections + .borrow_mut() + .push((connection as *const _, ssl_ptr)); + }); + Self { + previous_vm: HANDSHAKE_VM.with(|cell| cell.replace(Some(vm as *const _))), + previous_ssl: HANDSHAKE_SSL_PTR.with(|cell| cell.replace(Some(ssl_ptr))), + } } } impl Drop for HandshakeVmGuard { fn drop(&mut self) { - HANDSHAKE_VM.with(|cell| cell.set(None)); - HANDSHAKE_SSL_PTR.with(|cell| cell.set(None)); + HANDSHAKE_VM.with(|cell| cell.set(self.previous_vm)); + HANDSHAKE_SSL_PTR.with(|cell| cell.set(self.previous_ssl)); + HANDSHAKE_CONNECTIONS.with(|connections| { + connections.borrow_mut().pop(); + }); } } - // Get SSL pointer - either from thread-local (during handshake) or from connection - fn get_ssl_ptr_for_context_change( - connection: &PyDetachingRwLock, - ) -> *mut sys::SSL { - // First check if we're in a handshake callback (lock already held) - if let Some(ptr) = HANDSHAKE_SSL_PTR.with(|cell| cell.get()) { - return ptr; - } - // Otherwise, acquire the lock normally - connection.read().ssl().as_ptr() + fn active_ssl_pointer(connection: &PyDetachingRwLock) -> Option<*mut sys::SSL> { + HANDSHAKE_CONNECTIONS.with(|connections| { + connections + .borrow() + .iter() + .rev() + .find_map(|&(owner, pointer)| core::ptr::eq(owner, connection).then_some(pointer)) + }) } - // Get or create an ex_data index for SNI callback data - fn get_sni_ex_data_index() -> core::ffi::c_int { - use rustpython_common::lock::LazyLock; - static SNI_EX_DATA_IDX: LazyLock = LazyLock::new(|| unsafe { - sys::SSL_get_ex_new_index( - 0, - core::ptr::null_mut(), - None, - None, - Some(sni_callback_data_free), - ) - }); - *SNI_EX_DATA_IDX - } - - // Free function for callback data - // NOTE: We don't free the data here because it's managed manually in do_handshake - // to avoid use-after-free when the SSL object is dropped after timeout - unsafe extern "C" fn sni_callback_data_free( - _parent: *mut core::ffi::c_void, - _ptr: *mut core::ffi::c_void, - _ad: *mut sys::CRYPTO_EX_DATA, - _idx: core::ffi::c_int, - _argl: core::ffi::c_long, - _argp: *mut core::ffi::c_void, - ) { - // Intentionally empty - data is freed in cleanup_sni_ex_data() + fn with_ssl_pointer( + connection: &PyDetachingRwLock, + operation: impl FnOnce(*mut sys::SSL) -> T, + ) -> T { + if let Some(pointer) = active_ssl_pointer(connection) { + // This thread already holds this connection's write guard. + return operation(pointer); + } + let guard = connection.read(); + operation(guard.ssl().as_ptr()) } - // Clean up SNI callback data from SSL ex_data - // Called after handshake to free the data and release references - unsafe fn cleanup_sni_ex_data(ssl_ptr: *mut sys::SSL) { - unsafe { - let idx = get_sni_ex_data_index(); - let data_ptr = sys::SSL_get_ex_data(ssl_ptr, idx); - if !data_ptr.is_null() { - // Free the Box - this releases references to context and socket - let _ = Box::from_raw(data_ptr as *mut SniCallbackData); - // Clear the ex_data to prevent double-free - sys::SSL_set_ex_data(ssl_ptr, idx, core::ptr::null_mut()); - } + fn with_ssl_pointer_mut( + connection: &PyDetachingRwLock, + operation: impl FnOnce(*mut sys::SSL) -> T, + ) -> T { + if let Some(pointer) = active_ssl_pointer(connection) { + return operation(pointer); } + let guard = connection.write(); + operation(guard.ssl().as_ptr()) } - // Get or create an ex_data index for msg_callback data - fn get_msg_callback_ex_data_index() -> core::ffi::c_int { - use rustpython_common::lock::LazyLock; - static MSG_CB_EX_DATA_IDX: LazyLock = LazyLock::new(|| unsafe { - sys::SSL_get_ex_new_index( - 0, - core::ptr::null_mut(), - None, - None, - Some(msg_callback_data_free), - ) + // The owning _SSLSocket outlives its SSL connection. Borrow its stable + // address, as CPython's SSL app_data does, without creating a hidden cycle. + fn get_socket_ex_data_index() -> core::ffi::c_int { + static SOCKET_EX_DATA_IDX: LazyLock = LazyLock::new(|| unsafe { + sys::SSL_get_ex_new_index(0, core::ptr::null_mut(), None, None, None) }); - *MSG_CB_EX_DATA_IDX - } - - // Free function for msg_callback data - called by OpenSSL when SSL is freed - unsafe extern "C" fn msg_callback_data_free( - _parent: *mut core::ffi::c_void, - ptr: *mut core::ffi::c_void, - _ad: *mut sys::CRYPTO_EX_DATA, - _idx: core::ffi::c_int, - _argl: core::ffi::c_long, - _argp: *mut core::ffi::c_void, - ) { - if !ptr.is_null() { - unsafe { - // Reconstruct PyObjectRef and drop to decrement reference count - let raw = core::ptr::NonNull::new_unchecked(ptr as *mut PyObject); - let _ = PyObjectRef::from_raw(raw); - } - } + *SOCKET_EX_DATA_IDX } // SNI callback function called by OpenSSL unsafe extern "C" fn _servername_callback( ssl_ptr: *mut sys::SSL, al: *mut core::ffi::c_int, - arg: *mut core::ffi::c_void, + _arg: *mut core::ffi::c_void, ) -> core::ffi::c_int { const SSL_TLSEXT_ERR_OK: core::ffi::c_int = 0; const SSL_TLSEXT_ERR_ALERT_FATAL: core::ffi::c_int = 2; const SSL_AD_INTERNAL_ERROR: core::ffi::c_int = 80; + const SSL_AD_HANDSHAKE_FAILURE: core::ffi::c_int = 40; const TLSEXT_NAMETYPE_host_name: core::ffi::c_int = 0; - if arg.is_null() { - return SSL_TLSEXT_ERR_OK; - } - unsafe { - let ctx = &*(arg as *const PySslContext); - - // Nothing to call: leave without reaching the interpreter at all. - if ctx.sni_callback.lock().is_none() { - return SSL_TLSEXT_ERR_OK; - } - - // Get callback data from SSL ex_data - let idx = get_sni_ex_data_index(); - let data_ptr = sys::SSL_get_ex_data(ssl_ptr, idx); - if data_ptr.is_null() { + let socket_ptr = sys::SSL_get_ex_data(ssl_ptr, get_socket_ex_data_index()); + if socket_ptr.is_null() { + *al = SSL_AD_INTERNAL_ERROR; return SSL_TLSEXT_ERR_ALERT_FATAL; } - - let callback_data = &*(data_ptr as *const SniCallbackData); + let ssl_socket = &*(socket_ptr as *const Py); // Get VM from thread-local storage (set by HandshakeVmGuard in do_handshake) let Some(vm_ptr) = HANDSHAKE_VM.with(|cell| cell.get()) else { @@ -638,7 +610,9 @@ mod _ssl { // everything below rejoins it first — taking a reference to the // callback already counts — and gives the thread back after. vm.attach_for_callback(|| { - // Get the callback + // The callback may replace the socket's context and release its + // last outside reference. Keep both context and callback alive. + let ctx = ssl_socket.ctx.read().clone(); let callback_opt = ctx.sni_callback.lock().clone(); let Some(callback) = callback_opt else { return SSL_TLSEXT_ERR_OK; @@ -656,21 +630,15 @@ mod _ssl { } }; - // Get SSL socket from callback data via weak reference - let ssl_socket_obj = callback_data - .ssl_socket_weak - .upgrade() - .unwrap_or_else(|| vm.ctx.none()); + let ssl_socket_obj = match PySslSocket::callback_owner(ssl_socket) { + Some(owner) => owner, + None => { + *al = SSL_AD_INTERNAL_ERROR; + return SSL_TLSEXT_ERR_ALERT_FATAL; + } + }; - // Call the Python callback - match callback.call( - ( - ssl_socket_obj, - server_name_arg, - callback_data.ssl_context.to_owned(), - ), - vm, - ) { + match callback.call((ssl_socket_obj, server_name_arg, ctx), vm) { Ok(result) => { // Check return value type (must be None or integer) if vm.is_none(&result) { @@ -700,7 +668,7 @@ mod _ssl { Err(exc) => { // Log the exception but don't propagate it vm.run_unraisable(exc, None, vm.ctx.none()); - *al = SSL_AD_INTERNAL_ERROR; + *al = SSL_AD_HANDSHAKE_FAILURE; SSL_TLSEXT_ERR_ALERT_FATAL } } @@ -735,20 +703,15 @@ mod _ssl { unsafe { // Get SSL socket from ex_data using the dedicated index - let idx = get_msg_callback_ex_data_index(); + let idx = get_socket_ex_data_index(); let ssl_socket_ptr = sys::SSL_get_ex_data(ssl_ptr, idx); if ssl_socket_ptr.is_null() { return; } - // ssl_socket_ptr is a pointer to Box>, set in _wrap_socket/_wrap_bio + // Borrowed stable address, installed by _wrap_socket/_wrap_bio. let ssl_socket: &Py = &*(ssl_socket_ptr as *const Py); - // Nothing to call: leave without reaching the interpreter at all. - if ssl_socket.ctx.read().msg_callback.lock().is_none() { - return; - } - // Get VM from thread-local storage (set by HandshakeVmGuard in do_handshake) let Some(vm_ptr) = HANDSHAKE_VM.with(|cell| cell.get()) else { // VM not available - this shouldn't happen during handshake @@ -766,13 +729,9 @@ mod _ssl { return; }; - // Get SSL socket owner object - let ssl_socket_obj = ssl_socket - .owner - .read() - .as_ref() - .and_then(|weak| weak.upgrade()) - .unwrap_or_else(|| vm.ctx.none()); + let Some(ssl_socket_obj) = PySslSocket::callback_owner(ssl_socket) else { + return; + }; // Create the message bytes let buf_slice = core::slice::from_raw_parts(buf as *const u8, len); @@ -819,8 +778,13 @@ mod _ssl { ) { Ok(_) => {} Err(exc) => { - // Log the exception but don't propagate it - vm.run_unraisable(exc, None, vm.ctx.none()); + // SSL message callbacks cannot signal failure to the C + // library. Propagate it when the enclosing operation + // rejoins the interpreter, chaining earlier callbacks. + let previous = ssl_socket.callback_error.lock().replace(exc.clone()); + if let Some(previous) = previous { + exc.set_context(Some(previous)); + } } } }) @@ -841,18 +805,19 @@ mod _ssl { } #[pyattr] - #[pyclass(module = "_ssl", name = "_SSLContext")] + #[pyclass(module = "_ssl", name = "_SSLContext", traverse)] #[derive(PyPayload)] struct PySslContext { + #[pytraverse(skip)] ctx: PyRwLock, + #[pytraverse(skip)] check_hostname: AtomicCell, + #[pytraverse(skip)] protocol: SslVersion, + #[pytraverse(skip)] post_handshake_auth: PyMutex, sni_callback: PyMutex>, msg_callback: PyMutex>, - psk_client_callback: PyMutex>, - psk_server_callback: PyMutex>, - psk_identity_hint: PyMutex>, } impl fmt::Debug for PySslContext { @@ -861,6 +826,19 @@ mod _ssl { } } + impl Drop for PySslContext { + fn drop(&mut self) { + // SSL retains its original session context across context switches. + // It must not call back through a released Python context on HRR. + unsafe { + sys::SSL_CTX_set_tlsext_servername_callback__fixed_rust( + self.ctx.get_mut().as_ptr(), + None, + ); + } + } + } + fn builder_as_ctx(x: &SslContextBuilder) -> &ssl::SslContextRef { unsafe { ssl::SslContextRef::from_ptr(x.as_ptr()) } } @@ -900,11 +878,14 @@ mod _ssl { android::load_client_ca_list(vm, &mut builder)?; let check_hostname = proto == SslVersion::TlsClient; - builder.set_verify(if check_hostname { - SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT - } else { - SslVerifyMode::NONE - }); + builder.set_verify_callback( + if check_hostname { + SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT + } else { + SslVerifyMode::NONE + }, + super::distrusted::verify, + ); // Start with OP_ALL but remove options that CPython doesn't include by default let mut options = SslOptions::ALL & !SslOptions::DONT_INSERT_EMPTY_FRAGMENTS; @@ -972,9 +953,6 @@ mod _ssl { post_handshake_auth: PyMutex::new(false), sni_callback: PyMutex::new(None), msg_callback: PyMutex::new(None), - psk_client_callback: PyMutex::new(None), - psk_server_callback: PyMutex::new(None), - psk_identity_hint: PyMutex::new(None), }) } } @@ -1013,11 +991,13 @@ mod _ssl { #[pygetset(setter)] fn set_post_handshake_auth( zelf: &Py, - value: Option, + value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { - let value = value.ok_or_else(|| vm.new_attribute_error("cannot delete attribute"))?; - *zelf.post_handshake_auth.lock() = value.is_true(vm)?; + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'post_handshake_auth' cannot be deleted") + })?; + *zelf.post_handshake_auth.lock() = value.into_bool(); Ok(()) } @@ -1039,6 +1019,147 @@ mod _ssl { .map_err(|_| new_ssl_error(vm, "No cipher can be selected.")) } + #[pymethod] + fn set_ciphersuites( + zelf: &Py, + ciphersuites: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let list = ciphersuites.as_str().to_cstring(vm)?; + #[cfg(ossl111)] + { + let result = unsafe { + sys::SSL_CTX_set_ciphersuites(zelf.builder().as_ptr(), list.as_ptr()) + }; + if result != 1 { + let _ = ErrorStack::get(); + return Err(new_ssl_error(vm, "No cipher suite can be selected.")); + } + Ok(()) + } + #[cfg(not(ossl111))] + { + let _ = (zelf, list); + Err(vm.new_not_implemented_error("TLS 1.3 requires OpenSSL 1.1.1 or later.")) + } + } + + fn set_algorithm_list( + &self, + list: PyUtf8StrRef, + command: core::ffi::c_int, + message: &str, + vm: &VirtualMachine, + ) -> PyResult<()> { + let list = list.as_str().to_cstring(vm)?; + let result = unsafe { + sys::SSL_CTX_ctrl( + self.builder().as_ptr(), + command, + 0, + list.as_ptr().cast_mut().cast(), + ) + }; + if result != 1 { + let _ = ErrorStack::get(); + return Err(new_ssl_error(vm, message)); + } + Ok(()) + } + + #[pymethod] + fn set_groups( + zelf: &Py, + grouplist: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + // SSL_CTX_set1_groups_list is a macro around SSL_CTX_ctrl. + const SSL_CTRL_SET_GROUPS_LIST: core::ffi::c_int = 92; + zelf.set_algorithm_list( + grouplist, + SSL_CTRL_SET_GROUPS_LIST, + "unrecognized group", + vm, + ) + } + + #[pymethod] + fn set_server_sigalgs( + zelf: &Py, + sigalgslist: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + const SSL_CTRL_SET_SIGALGS_LIST: core::ffi::c_int = 98; + zelf.set_algorithm_list( + sigalgslist, + SSL_CTRL_SET_SIGALGS_LIST, + "unrecognized signature algorithm", + vm, + ) + } + + #[pymethod] + fn set_client_sigalgs( + zelf: &Py, + sigalgslist: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + const SSL_CTRL_SET_CLIENT_SIGALGS_LIST: core::ffi::c_int = 102; + zelf.set_algorithm_list( + sigalgslist, + SSL_CTRL_SET_CLIENT_SIGALGS_LIST, + "unrecognized signature algorithm", + vm, + ) + } + + #[pymethod] + fn get_groups( + zelf: &Py, + args: GetGroupsArgs, + vm: &VirtualMachine, + ) -> PyResult { + let include_aliases = args.include_aliases.into_bool(); + #[cfg(ossl350)] + unsafe { + const SSL_CTRL_GET0_IMPLEMENTED_GROUPS: core::ffi::c_int = 139; + let groups = sys::OPENSSL_sk_new_null(); + if groups.is_null() { + return Err(vm.new_memory_error("failed to allocate group list")); + } + let result = sys::SSL_CTX_ctrl( + zelf.ctx().as_ptr(), + SSL_CTRL_GET0_IMPLEMENTED_GROUPS, + core::ffi::c_long::from(include_aliases), + groups.cast(), + ); + if result == 0 { + sys::OPENSSL_sk_free(groups); + return Err(convert_openssl_error(vm, ErrorStack::get())); + } + // The stack owns its storage, but OpenSSL owns each name. + let names = (0..sys::OPENSSL_sk_num(groups)) + .map(|index| { + CStr::from_ptr(sys::OPENSSL_sk_value(groups, index).cast()) + .to_string_lossy() + .into_owned() + }) + .collect::>(); + sys::OPENSSL_sk_free(groups); + Ok(vm.ctx.new_list( + names + .into_iter() + .map(|name| vm.ctx.new_str(name).into()) + .collect(), + )) + } + #[cfg(not(ossl350))] + { + let _ = (zelf, include_aliases); + Err(vm.new_not_implemented_error("Getting groups requires OpenSSL 3.5 or later.")) + } + } + #[pymethod] fn get_ciphers(zelf: &Py, vm: &VirtualMachine) -> PyResult { let ctx = zelf.ctx(); @@ -1115,7 +1236,13 @@ mod _ssl { zelf.ctx.read().options().bits() as _ } #[pygetset(setter)] - fn set_options(zelf: &Py, new_opts: i64, vm: &VirtualMachine) -> PyResult<()> { + fn set_options( + zelf: &Py, + new_opts: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let new_opts = new_opts + .ok_or_else(|| vm.new_attribute_error("attribute 'options' cannot be deleted"))?; if new_opts < 0 { return Err(vm.new_value_error("invalid options value")); } @@ -1177,7 +1304,14 @@ mod _ssl { } } #[pygetset(setter)] - fn set_verify_mode(zelf: &Py, cert: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_verify_mode( + zelf: &Py, + cert: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let cert = cert.ok_or_else(|| { + vm.new_attribute_error("attribute 'verify_mode' cannot be deleted") + })?; let mut ctx = zelf.builder(); let cert_req = CertRequirements::try_from(cert) .map_err(|_| vm.new_value_error("invalid value for verify_mode"))?; @@ -1193,7 +1327,7 @@ mod _ssl { SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT } }; - ctx.set_verify(mode); + ctx.set_verify_callback(mode, super::distrusted::verify); Ok(()) } #[pygetset] @@ -1207,9 +1341,12 @@ mod _ssl { #[pygetset(setter)] fn set_verify_flags( zelf: &Py, - new_flags: core::ffi::c_ulong, + new_flags: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { + let new_flags = new_flags.ok_or_else(|| { + vm.new_attribute_error("attribute 'verify_flags' cannot be deleted") + })?; unsafe { let ctx_ptr = zelf.ctx().as_ptr(); let param = sys::SSL_CTX_get0_param(ctx_ptr); @@ -1230,18 +1367,59 @@ mod _ssl { fn check_hostname(zelf: &Py) -> bool { zelf.check_hostname.load() } + + #[pygetset] + fn _host_flags(zelf: &Py) -> u32 { + unsafe { X509_VERIFY_PARAM_get_hostflags(sys::SSL_CTX_get0_param(zelf.ctx().as_ptr())) } + } + + #[pygetset(setter)] + fn set__host_flags( + zelf: &Py, + flags: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let flags = flags.ok_or_else(|| { + vm.new_attribute_error("attribute '_host_flags' cannot be deleted") + })?; + let flags = flags.as_unsigned_bitfield::<32>(vm)? as u32; + let ctx = zelf.builder(); + unsafe { + sys::X509_VERIFY_PARAM_set_hostflags(sys::SSL_CTX_get0_param(ctx.as_ptr()), flags); + } + Ok(()) + } + #[pygetset(setter)] - fn set_check_hostname(zelf: &Py, ch: bool) { + fn set_check_hostname( + zelf: &Py, + ch: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let ch = ch.ok_or_else(|| { + vm.new_attribute_error("attribute 'check_hostname' cannot be deleted") + })?; + let ch = ch.into_bool(); let mut ctx = zelf.builder(); if ch && builder_as_ctx(&ctx).verify_mode() == SslVerifyMode::NONE { - ctx.set_verify(SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT); + ctx.set_verify_callback( + SslVerifyMode::PEER | SslVerifyMode::FAIL_IF_NO_PEER_CERT, + super::distrusted::verify, + ); } zelf.check_hostname.store(ch); + Ok(()) } // PY_PROTO_MINIMUM_SUPPORTED = -2, PY_PROTO_MAXIMUM_SUPPORTED = -1 #[pygetset] fn minimum_version(zelf: &Py) -> i32 { + if !matches!( + zelf.protocol, + SslVersion::Tls | SslVersion::TlsClient | SslVersion::TlsServer + ) { + return -2; + } let ctx = zelf.ctx(); let version = unsafe { sys::SSL_CTX_get_min_proto_version(ctx.as_ptr()) }; if version == 0 { @@ -1251,14 +1429,31 @@ mod _ssl { } } #[pygetset(setter)] - fn set_minimum_version(zelf: &Py, value: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_minimum_version( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'minimum_version' cannot be deleted") + })?; + if !matches!( + zelf.protocol, + SslVersion::Tls | SslVersion::TlsClient | SslVersion::TlsServer + ) { + return Err(vm.new_value_error( + "The context's protocol doesn't support modification of highest and lowest version.", + )); + } + ProtoVersion::try_from(value) + .map_err(|_| vm.new_value_error("invalid protocol version"))?; Self::warn_deprecated_tls_version(value, vm)?; // Handle special values let proto_version = match value { -2 => { - // PY_PROTO_MINIMUM_SUPPORTED -> use minimum available (TLS 1.2) - sys::TLS1_2_VERSION + // Zero removes the explicit minimum protocol limit. + 0 } -1 => { // PY_PROTO_MAXIMUM_SUPPORTED -> use maximum available @@ -1278,6 +1473,12 @@ mod _ssl { #[pygetset] fn maximum_version(zelf: &Py) -> i32 { + if !matches!( + zelf.protocol, + SslVersion::Tls | SslVersion::TlsClient | SslVersion::TlsServer + ) { + return -1; + } let ctx = zelf.ctx(); let version = unsafe { sys::SSL_CTX_get_max_proto_version(ctx.as_ptr()) }; if version == 0 { @@ -1287,7 +1488,24 @@ mod _ssl { } } #[pygetset(setter)] - fn set_maximum_version(zelf: &Py, value: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_maximum_version( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'maximum_version' cannot be deleted") + })?; + if !matches!( + zelf.protocol, + SslVersion::Tls | SslVersion::TlsClient | SslVersion::TlsServer + ) { + return Err(vm.new_value_error( + "The context's protocol doesn't support modification of highest and lowest version.", + )); + } + ProtoVersion::try_from(value) + .map_err(|_| vm.new_value_error("invalid protocol version"))?; Self::warn_deprecated_tls_version(value, vm)?; // Handle special values @@ -1296,10 +1514,8 @@ mod _ssl { // PY_PROTO_MAXIMUM_SUPPORTED -> use 0 for OpenSSL (means no limit) 0 } - -2 => { - // PY_PROTO_MINIMUM_SUPPORTED -> use minimum available (TLS 1.2) - sys::TLS1_2_VERSION - } + // This backend advertises TLSv1 as its lowest supported version. + -2 => sys::TLS1_VERSION, _ => value, }; @@ -1324,7 +1540,14 @@ mod _ssl { } } #[pygetset(setter)] - fn set_num_tickets(zelf: &Py, value: isize, vm: &VirtualMachine) -> PyResult<()> { + fn set_num_tickets( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'num_tickets' cannot be deleted") + })?; // Check for negative values if value < 0 { return Err(vm.new_value_error("num_tickets must be a non-negative integer")); @@ -1338,7 +1561,8 @@ mod _ssl { cfg_select! { ossl110 => { let ctx = zelf.builder(); - let result = unsafe { sys::SSL_CTX_set_num_tickets(ctx.as_ptr(), value as usize) }; + let result = + unsafe { sys::SSL_CTX_set_num_tickets(ctx.as_ptr(), value as usize) }; if result != 1 { return Err(vm.new_value_error("failed to set num tickets.")); } @@ -1360,11 +1584,10 @@ mod _ssl { .load_verify_locations(Some(cert_file.as_path()), Some(cert_dir.as_path())) .map_err(|e| convert_openssl_error(vm, e)) } - _ => { - zelf.builder() - .set_default_verify_paths() - .map_err(|e| convert_openssl_error(vm, e)) - } + _ => zelf + .builder() + .set_default_verify_paths() + .map_err(|e| convert_openssl_error(vm, e)), } } @@ -1407,74 +1630,25 @@ mod _ssl { #[pymethod] fn set_psk_client_callback( - zelf: &Py, - callback: PyObjectRef, + _zelf: &Py, + _callback: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - // Cannot add PSK client callback to a server context - if zelf.protocol == SslVersion::TlsServer { - return Err(vm - .new_os_subtype_error( - PySSLError::class(&vm.ctx).to_owned(), - None, - "Cannot add PSK client callback to a PROTOCOL_TLS_SERVER context" - .to_owned(), - ) - .upcast()); - } - - if vm.is_none(&callback) { - *zelf.psk_client_callback.lock() = None; - unsafe { - sys::SSL_CTX_set_psk_client_callback(zelf.builder().as_ptr(), None); - } - } else { - if !callback.is_callable() { - return Err(vm.new_type_error("callback must be callable")); - } - *zelf.psk_client_callback.lock() = Some(callback); - // Note: The actual callback will be invoked via SSL app_data mechanism - // when do_handshake is called - } - Ok(()) + Err(vm.new_not_implemented_error( + "TLS-PSK callbacks are not implemented by this backend.", + )) } #[pymethod] fn set_psk_server_callback( - zelf: &Py, - callback: PyObjectRef, - identity_hint: OptionalArg, + _zelf: &Py, + _callback: PyObjectRef, + _identity_hint: OptionalArg, vm: &VirtualMachine, ) -> PyResult<()> { - // Cannot add PSK server callback to a client context - if zelf.protocol == SslVersion::TlsClient { - return Err(vm - .new_os_subtype_error( - PySSLError::class(&vm.ctx).to_owned(), - None, - "Cannot add PSK server callback to a PROTOCOL_TLS_CLIENT context" - .to_owned(), - ) - .upcast()); - } - - if vm.is_none(&callback) { - *zelf.psk_server_callback.lock() = None; - *zelf.psk_identity_hint.lock() = None; - unsafe { - sys::SSL_CTX_set_psk_server_callback(zelf.builder().as_ptr(), None); - } - } else { - if !callback.is_callable() { - return Err(vm.new_type_error("callback must be callable")); - } - *zelf.psk_server_callback.lock() = Some(callback); - if let OptionalArg::Present(hint) = identity_hint { - *zelf.psk_identity_hint.lock() = Some(hint.to_string()); - } - // Note: The actual callback will be invoked via SSL app_data mechanism - } - Ok(()) + Err(vm.new_not_implemented_error( + "TLS-PSK callbacks are not implemented by this backend.", + )) } #[pymethod] @@ -1571,7 +1745,7 @@ mod _ssl { args: GetCertArgs, vm: &VirtualMachine, ) -> PyResult> { - let binary_form = args.binary_form.unwrap_or(false); + let binary_form = args.binary_form.map_or(false, ArgIntoBool::into_bool); let ctx = zelf.ctx(); let certs = cfg_select! { ossl300 => ctx.cert_store().all_certificates(), @@ -1675,8 +1849,13 @@ mod _ssl { } #[pymethod] - fn load_dh_params(zelf: &Py, filepath: FsPath, vm: &VirtualMachine) -> PyResult<()> { - let path = filepath.to_path_buf(vm)?; + fn load_dh_params( + zelf: &Py, + filepath: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + vm.audit("open", || (filepath.clone(), "rb", 0))?; + let path = FsPath::try_from_path_like(filepath, true, vm)?.to_path_buf(vm)?; // Open the file using fopen (cross-platform) let fp = @@ -1732,9 +1911,12 @@ mod _ssl { #[pygetset(setter)] fn set_sni_callback( zelf: &Py, - value: Option, + value: PySetterValue>, vm: &VirtualMachine, ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'sni_callback' cannot be deleted") + })?; // Check if this is a server context if zelf.protocol == SslVersion::TlsClient { return Err(vm.new_value_error("sni_callback cannot be set on TLS_CLIENT context")); @@ -1758,10 +1940,6 @@ mod _ssl { zelf.ctx().as_ptr(), Some(_servername_callback), ); - sys::SSL_CTX_set_tlsext_servername_arg( - zelf.ctx().as_ptr(), - zelf as *const _ as *mut _, - ); } } else { // Clear callback @@ -1793,20 +1971,23 @@ mod _ssl { callback: Option, vm: &VirtualMachine, ) -> PyResult<()> { - Self::set_sni_callback(zelf, callback, vm) + Self::set_sni_callback(zelf, PySetterValue::Assign(callback), vm) } - #[pygetset(name = "_msg_callback")] - fn msg_callback(zelf: &Py) -> Option { + #[pygetset] + fn _msg_callback(zelf: &Py) -> Option { zelf.msg_callback.lock().clone() } - #[pygetset(setter, name = "_msg_callback")] - fn set_msg_callback( + #[pygetset(setter)] + fn set__msg_callback( zelf: &Py, - value: Option, + value: PySetterValue>, vm: &VirtualMachine, ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute '_msg_callback' cannot be deleted") + })?; let mut callback_guard = zelf.msg_callback.lock(); if let Some(callback_obj) = value { @@ -1857,29 +2038,31 @@ mod _ssl { } = args; let mut ctx = zelf.builder(); - let key_path = keyfile.map(|path| path.to_path_buf(vm)).transpose()?; + let key_path = keyfile + .as_ref() + .map(|path| path.to_path_buf(vm)) + .transpose()?; let cert_path = certfile.to_path_buf(vm)?; - // Check file existence before calling OpenSSL to get proper errno - if !rustpython_host_env::fs::exists(&cert_path) { - return Err(vm - .new_os_subtype_error( - vm.ctx.exceptions.file_not_found_error.to_owned(), - Some(rustpython_host_env::errno::errors::ENOENT), - format!("No such file or directory: '{}'", cert_path.display()), - ) - .upcast()); - } - if let Some(ref kp) = key_path - && !rustpython_host_env::fs::exists(kp) - { - return Err(vm - .new_os_subtype_error( - vm.ctx.exceptions.file_not_found_error.to_owned(), - Some(rustpython_host_env::errno::errors::ENOENT), - format!("No such file or directory: '{}'", kp.display()), - ) - .upcast()); + let file_error = |error: std::io::Error, path: &FsPath| { + let exception = error.to_pyexception(vm); + let filename: PyObjectRef = match path { + FsPath::Str(path) => path.clone().into(), + FsPath::Bytes(path) => path.clone().into(), + }; + exception + .as_object() + .set_attr("filename", filename, vm) + .expect("OSError.filename is writable"); + exception + }; + // Keep OS errors and their original str/bytes filenames rather + // than replacing them with OpenSSL's generic file error. + rustpython_host_env::fs::metadata(&cert_path) + .map_err(|error| file_error(error, &certfile))?; + if let Some(ref path) = key_path { + rustpython_host_env::fs::metadata(path) + .map_err(|error| file_error(error, keyfile.as_ref().unwrap()))?; } // Load certificate chain @@ -1894,7 +2077,7 @@ mod _ssl { // Read key file data let key_data = rustpython_host_env::fs::read(key_file_path) - .map_err(|e| crate::vm::convert::ToPyException::to_pyexception(&e, vm))?; + .map_err(|error| file_error(error, keyfile.as_ref().unwrap_or(&certfile)))?; let pkey = if let Some(ref pw_obj) = password { if pw_obj.is_callable() { @@ -2086,10 +2269,9 @@ mod _ssl { // Only in combination with SSL_VERIFY_PEER let mode = sys::SSL_get_verify_mode(ssl.as_ptr()); if (mode & sys::SSL_VERIFY_PEER as core::ffi::c_int) != 0 { - sys::SSL_set_verify( - ssl.as_ptr(), - mode | SSL_VERIFY_POST_HANDSHAKE, - None, + ssl.set_verify_callback( + SslVerifyMode::from_bits_retain(mode | SSL_VERIFY_POST_HANDSHAKE), + super::distrusted::verify, ); } } else { @@ -2116,57 +2298,63 @@ mod _ssl { vm: &VirtualMachine, ) -> PyResult { // Use common helper function - let (ssl, socket_type, server_hostname) = - Self::new_py_ssl_socket(zelf.clone(), args.server_side, args.server_hostname, vm)?; + let (ssl, socket_type, server_hostname) = Self::new_py_ssl_socket( + zelf.clone(), + args.server_side.into_bool(), + args.server_hostname, + vm, + )?; // Create SslStream with socket - let stream = ssl::SslStream::new(ssl, SocketStream(args.sock.clone())) - .map_err(|e| convert_openssl_error(vm, e))?; + let stream = ssl::SslStream::new( + ssl, + SocketStream::new(args.sock.clone()).map_err(|e| e.to_pyexception(vm))?, + ) + .map_err(|e| convert_openssl_error(vm, e))?; let py_ssl_socket = PySslSocket { ctx: PyRwLock::new(zelf.clone()), - connection: PyDetachingRwLock::new(SslConnection::Socket(stream)), + connection: SslConnectionLock(PyDetachingRwLock::new(SslConnection::new( + SslTransport::Socket(stream), + ))), socket_type, server_hostname, - owner: PyRwLock::new(args.owner.map(|o| o.downgrade(None, vm)).transpose()?), + got_eof_error: AtomicCell::new(false), + shutdown_seen_zero: AtomicCell::new(false), + callback_error: PyMutex::new(None), + #[cfg(all(unix, not(target_os = "aix")))] + info_progress: AtomicCell::new(0), + #[cfg(all(unix, not(target_os = "aix")))] + previous_info_callback: AtomicCell::new(None), + owner: PyRwLock::new(Some( + args.owner + .unwrap_or_else(|| args.sock.clone().into()) + .downgrade(None, vm)?, + )), }; // Convert to PyRef (heap allocation) to avoid use-after-free let py_ref = py_ssl_socket.into_ref_with_type(vm, PySslSocket::class(&vm.ctx).to_owned())?; - // Check if SNI callback is configured (minimize lock time) - let has_sni_callback = zelf.sni_callback.lock().is_some(); - - // Set up ex_data for callbacks + // The connection is owned by py_ref, so this borrowed address + // remains valid through every SSL operation, including retries. unsafe { - let ssl_ptr = py_ref.connection.read().ssl().as_ptr(); - - // Clone and store via into_raw() - increments refcount and returns stable pointer - // The refcount will be decremented by msg_callback_data_free when SSL is freed - let cloned: PyObjectRef = py_ref.clone().into(); - let raw_ptr = cloned.into_raw(); - let msg_cb_idx = get_msg_callback_ex_data_index(); - sys::SSL_set_ex_data(ssl_ptr, msg_cb_idx, raw_ptr.as_ptr() as *mut _); - - // Set SNI callback data if needed - if has_sni_callback { - let ssl_socket_weak = py_ref.as_object().downgrade(None, vm)?; - // Store callback data in SSL ex_data - use weak reference to avoid cycle - let callback_data = Box::new(SniCallbackData { - ssl_context: zelf.clone(), - ssl_socket_weak, - }); - let sni_idx = get_sni_ex_data_index(); - sys::SSL_set_ex_data(ssl_ptr, sni_idx, Box::into_raw(callback_data) as *mut _); - } + sys::SSL_set_ex_data( + py_ref.connection.read().ssl().as_ptr(), + get_socket_ex_data_index(), + &*py_ref as *const Py as *mut _, + ); } + #[cfg(all(unix, not(target_os = "aix")))] + py_ref.install_progress_callback(); + // Set session if provided if let Some(session) = args.session && !vm.is_none(&session) { - PySslSocket::set_session(&py_ref, session, vm)?; + PySslSocket::set_session(&py_ref, PySetterValue::Assign(session), vm)?; } Ok(py_ref.into()) @@ -2179,13 +2367,19 @@ mod _ssl { vm: &VirtualMachine, ) -> PyResult { // Use common helper function - let (ssl, socket_type, server_hostname) = - Self::new_py_ssl_socket(zelf.clone(), args.server_side, args.server_hostname, vm)?; + let (ssl, socket_type, server_hostname) = Self::new_py_ssl_socket( + zelf.clone(), + args.server_side.into_bool(), + args.server_hostname, + vm, + )?; // Create BioStream wrapper let bio_stream = BioStream { inbio: args.incoming, outbio: args.outgoing, + #[cfg(all(unix, not(target_os = "aix")))] + progress: 0, }; // Create SslStream with BioStream @@ -2194,9 +2388,18 @@ mod _ssl { let py_ssl_socket = PySslSocket { ctx: PyRwLock::new(zelf.clone()), - connection: PyDetachingRwLock::new(SslConnection::Bio(stream)), + connection: SslConnectionLock(PyDetachingRwLock::new(SslConnection::new( + SslTransport::Bio(stream), + ))), socket_type, server_hostname, + got_eof_error: AtomicCell::new(false), + shutdown_seen_zero: AtomicCell::new(false), + callback_error: PyMutex::new(None), + #[cfg(all(unix, not(target_os = "aix")))] + info_progress: AtomicCell::new(0), + #[cfg(all(unix, not(target_os = "aix")))] + previous_info_callback: AtomicCell::new(None), owner: PyRwLock::new(args.owner.map(|o| o.downgrade(None, vm)).transpose()?), }; @@ -2204,38 +2407,24 @@ mod _ssl { let py_ref = py_ssl_socket.into_ref_with_type(vm, PySslSocket::class(&vm.ctx).to_owned())?; - // Check if SNI callback is configured (minimize lock time) - let has_sni_callback = zelf.sni_callback.lock().is_some(); - - // Set up ex_data for callbacks + // The connection is owned by py_ref, so this borrowed address + // remains valid through every SSL operation, including retries. unsafe { - let ssl_ptr = py_ref.connection.read().ssl().as_ptr(); - - // Clone and store via into_raw() - increments refcount and returns stable pointer - // The refcount will be decremented by msg_callback_data_free when SSL is freed - let cloned: PyObjectRef = py_ref.clone().into(); - let raw_ptr = cloned.into_raw(); - let msg_cb_idx = get_msg_callback_ex_data_index(); - sys::SSL_set_ex_data(ssl_ptr, msg_cb_idx, raw_ptr.as_ptr() as *mut _); - - // Set SNI callback data if needed - if has_sni_callback { - let ssl_socket_weak = py_ref.as_object().downgrade(None, vm)?; - // Store callback data in SSL ex_data - use weak reference to avoid cycle - let callback_data = Box::new(SniCallbackData { - ssl_context: zelf.clone(), - ssl_socket_weak, - }); - let sni_idx = get_sni_ex_data_index(); - sys::SSL_set_ex_data(ssl_ptr, sni_idx, Box::into_raw(callback_data) as *mut _); - } + sys::SSL_set_ex_data( + py_ref.connection.read().ssl().as_ptr(), + get_socket_ex_data_index(), + &*py_ref as *const Py as *mut _, + ); } + #[cfg(all(unix, not(target_os = "aix")))] + py_ref.install_progress_callback(); + // Set session if provided if let Some(session) = args.session && !vm.is_none(&session) { - PySslSocket::set_session(&py_ref, session, vm)?; + PySslSocket::set_session(&py_ref, PySetterValue::Assign(session), vm)?; } Ok(py_ref.into()) @@ -2247,7 +2436,7 @@ mod _ssl { struct WrapBioArgs { incoming: PyRef, outgoing: PyRef, - server_side: bool, + server_side: ArgIntoBool, #[pyarg(any, default)] server_hostname: Option, #[pyarg(named, default)] @@ -2259,7 +2448,7 @@ mod _ssl { #[derive(FromArgs)] struct WrapSocketArgs { sock: PyRef, - server_side: bool, + server_side: ArgIntoBool, #[pyarg(any, default)] server_hostname: Option, #[pyarg(named, default)] @@ -2290,12 +2479,19 @@ mod _ssl { #[derive(FromArgs)] struct GetCertArgs { #[pyarg(any, optional)] - binary_form: OptionalArg, + binary_form: OptionalArg, + } + + #[derive(FromArgs)] + struct GetGroupsArgs { + #[pyarg(named, default = ArgIntoBool::FALSE)] + include_aliases: ArgIntoBool, } // Err is true if the socket is blocking type SocketDeadline = Result; + #[cfg(not(all(unix, not(target_os = "aix"))))] enum SelectRet { Nonblocking, TimedOut, @@ -2303,26 +2499,47 @@ mod _ssl { Ok, } + #[cfg(not(all(unix, not(target_os = "aix"))))] #[derive(Clone, Copy)] enum SslNeeds { Read, Write, } - struct SocketStream(PyRef); + struct SocketStream { + socket: PyRef, + #[cfg(all(unix, not(target_os = "aix")))] + identity: Arc, + #[cfg(all(unix, not(target_os = "aix")))] + progress: u64, + #[cfg(all(unix, not(target_os = "aix")))] + interrupted: bool, + } impl SocketStream { + fn new(socket: PyRef) -> std::io::Result { + Ok(Self { + #[cfg(all(unix, not(target_os = "aix")))] + identity: socket.ssl_identity()?, + socket, + #[cfg(all(unix, not(target_os = "aix")))] + progress: 0, + #[cfg(all(unix, not(target_os = "aix")))] + interrupted: false, + }) + } fn timeout_deadline(&self) -> SocketDeadline { - self.0.get_timeout().map(|d| Instant::now() + d) + self.socket.get_timeout().map(|d| Instant::now() + d) } + #[cfg(not(all(unix, not(target_os = "aix"))))] fn select( &self, needs: SslNeeds, deadline: &SocketDeadline, vm: &VirtualMachine, ) -> PyResult { - let Some(sock) = self.0.sock_opt() else { + let Some(sock) = self.socket.sock_opt() else { return Ok(SelectRet::Closed); }; // For blocking sockets without timeout, call sock_select with None timeout @@ -2348,6 +2565,7 @@ mod _ssl { }) } + #[cfg(not(all(unix, not(target_os = "aix"))))] fn socket_needs( &self, err: &ssl::Error, @@ -2373,6 +2591,8 @@ mod _ssl { struct BioStream { inbio: PyRef, outbio: PyRef, + #[cfg(all(unix, not(target_os = "aix")))] + progress: u64, } impl Read for BioStream { @@ -2392,6 +2612,10 @@ mod _ssl { "BIO has no data available", )) } else { + #[cfg(all(unix, not(target_os = "aix")))] + { + self.progress = self.progress.wrapping_add(nbytes as u64); + } Ok(nbytes as usize) } } @@ -2410,6 +2634,10 @@ mod _ssl { if nbytes < 0 { return Err(std::io::Error::other("BIO write failed")); } + #[cfg(all(unix, not(target_os = "aix")))] + { + self.progress = self.progress.wrapping_add(nbytes as u64); + } Ok(nbytes as usize) } } @@ -2421,70 +2649,174 @@ mod _ssl { } // Enum to represent different SSL connection modes - enum SslConnection { + enum SslTransport { Socket(ssl::SslStream), Bio(ssl::SslStream), } - impl SslConnection { + impl Drop for SslTransport { + fn drop(&mut self) { + // Match CPython: freeing a socket without unwrap() must not invalidate + // a session retained by Python. This marks state without doing I/O. + let state = self.get_shutdown() | ssl::ShutdownState::SENT; + match self { + Self::Socket(stream) => stream.set_shutdown(state), + Self::Bio(stream) => stream.set_shutdown(state), + } + } + } + + impl SslTransport { // Get a reference to the SSL object fn ssl(&self) -> &ssl::SslRef { match self { - SslConnection::Socket(stream) => stream.ssl(), - SslConnection::Bio(stream) => stream.ssl(), + SslTransport::Socket(stream) => stream.ssl(), + SslTransport::Bio(stream) => stream.ssl(), } } // Get underlying socket stream reference (only for socket mode) fn get_ref(&self) -> Option<&SocketStream> { match self { - SslConnection::Socket(stream) => Some(stream.get_ref()), - SslConnection::Bio(_) => None, + SslTransport::Socket(stream) => Some(stream.get_ref()), + SslTransport::Bio(_) => None, } } - // Check if this is in BIO mode + // Check if this is in BIO mode (legacy blocking transport). + #[cfg(not(all(unix, not(target_os = "aix"))))] fn is_bio(&self) -> bool { - matches!(self, SslConnection::Bio(_)) + matches!(self, SslTransport::Bio(_)) } // Perform SSL handshake fn do_handshake(&mut self) -> Result<(), ssl::Error> { + // SSL_get_error requires an empty queue before this native attempt. + unsafe { sys::ERR_clear_error() }; match self { - SslConnection::Socket(stream) => stream.do_handshake(), - SslConnection::Bio(stream) => stream.do_handshake(), + SslTransport::Socket(stream) => stream.do_handshake(), + SslTransport::Bio(stream) => stream.do_handshake(), } } // Write data to SSL connection fn ssl_write(&mut self, buf: &[u8]) -> Result { + unsafe { sys::ERR_clear_error() }; match self { - SslConnection::Socket(stream) => stream.ssl_write(buf), - SslConnection::Bio(stream) => stream.ssl_write(buf), + SslTransport::Socket(stream) => stream.ssl_write(buf), + SslTransport::Bio(stream) => stream.ssl_write(buf), } } // Read data from SSL connection fn ssl_read(&mut self, buf: &mut [u8]) -> Result { + unsafe { sys::ERR_clear_error() }; match self { - SslConnection::Socket(stream) => stream.ssl_read(buf), - SslConnection::Bio(stream) => stream.ssl_read(buf), + SslTransport::Socket(stream) => stream.ssl_read(buf), + SslTransport::Bio(stream) => stream.ssl_read(buf), + } + } + + fn shutdown(&mut self) -> Result { + unsafe { sys::ERR_clear_error() }; + match self { + SslTransport::Socket(stream) => stream.shutdown(), + SslTransport::Bio(stream) => stream.shutdown(), } } // Get SSL shutdown state fn get_shutdown(&mut self) -> ssl::ShutdownState { match self { - SslConnection::Socket(stream) => stream.get_shutdown(), - SslConnection::Bio(stream) => stream.get_shutdown(), + SslTransport::Socket(stream) => stream.get_shutdown(), + SslTransport::Bio(stream) => stream.get_shutdown(), } } // Check if incoming BIO has EOF (for BIO mode only) fn is_bio_eof(&self) -> bool { match self { - SslConnection::Socket(_) => false, - SslConnection::Bio(stream) => stream.get_ref().inbio.eof_written.load(), + SslTransport::Socket(_) => false, + SslTransport::Bio(stream) => stream.get_ref().inbio.eof_written.load(), + } + } + } + + struct SslConnection { + transport: SslTransport, + #[cfg(all(unix, not(target_os = "aix")))] + driver: Driver, + #[cfg(all(unix, not(target_os = "aix")))] + progress: Arc, + } + + impl SslConnection { + fn new(transport: SslTransport) -> Self { + Self { + transport, + #[cfg(all(unix, not(target_os = "aix")))] + driver: Driver::default(), + #[cfg(all(unix, not(target_os = "aix")))] + progress: Arc::new(ProgressRegistry::default()), + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + fn notify_progress(&self) { + self.progress.notify(); + } + + #[cfg(all(unix, not(target_os = "aix")))] + fn io_progress(&self) -> u64 { + match &self.transport { + SslTransport::Socket(stream) => stream.get_ref().progress, + SslTransport::Bio(stream) => stream.get_ref().progress, + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + fn take_interrupted(&mut self) -> bool { + match &mut self.transport { + SslTransport::Socket(stream) => core::mem::take(&mut stream.get_mut().interrupted), + SslTransport::Bio(_) => false, + } + } + } + + impl core::ops::Deref for SslConnection { + type Target = SslTransport; + fn deref(&self) -> &Self::Target { + &self.transport + } + } + + impl core::ops::DerefMut for SslConnection { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.transport + } + } + + struct SslConnectionLock(PyDetachingRwLock); + + impl core::ops::Deref for SslConnectionLock { + type Target = PyDetachingRwLock; + fn deref(&self) -> &Self::Target { + &self.0 + } + } + + // Like Traverse for PyRwLock, conservatively retain a connection if a + // detached SSL operation holds its write guard when GC stops the world. + unsafe impl Traverse for SslConnectionLock { + fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { + if let Some(connection) = self.try_read() { + match &connection.transport { + SslTransport::Socket(stream) => stream.get_ref().socket.traverse(traverse_fn), + SslTransport::Bio(stream) => { + stream.get_ref().inbio.traverse(traverse_fn); + stream.get_ref().outbio.traverse(traverse_fn); + } + } } } } @@ -2494,12 +2826,22 @@ mod _ssl { #[derive(PyPayload)] struct PySslSocket { ctx: PyRwLock>, - #[pytraverse(skip)] - connection: PyDetachingRwLock, + connection: SslConnectionLock, #[pytraverse(skip)] socket_type: SslServerOrClient, server_hostname: Option, owner: PyRwLock>>, + #[pytraverse(skip)] + got_eof_error: AtomicCell, + #[pytraverse(skip)] + shutdown_seen_zero: AtomicCell, + callback_error: PyMutex>, + #[cfg(all(unix, not(target_os = "aix")))] + #[pytraverse(skip)] + info_progress: AtomicCell, + #[cfg(all(unix, not(target_os = "aix")))] + #[pytraverse(skip)] + previous_info_callback: AtomicCell, } impl fmt::Debug for PySslSocket { @@ -2508,14 +2850,777 @@ mod _ssl { } } + #[cfg(all(unix, not(target_os = "aix")))] + struct IoScope(*const PySslSocket); + + #[cfg(all(unix, not(target_os = "aix")))] + impl IoScope { + fn enter(socket: &PySslSocket, vm: &VirtualMachine) -> PyResult { + let pointer = socket as *const _; + let entered = SSL_IO_CALLS.with(|calls| { + let mut calls = calls.borrow_mut(); + if calls.contains(&pointer) { + false + } else { + calls.push(pointer); + true + } + }); + // Exception allocation can run Python finalizers. Do not retain a + // RefCell borrow while they may attempt another SSL invocation. + if entered { + Ok(Self(pointer)) + } else { + Err(vm.new_runtime_error("Reentrant I/O on the same SSL connection")) + } + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + impl Drop for IoScope { + fn drop(&mut self) { + SSL_IO_CALLS.with(|calls| { + let pointer = calls.borrow_mut().pop(); + debug_assert_eq!(pointer, Some(self.0)); + }); + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + enum IoOperation<'a> { + Handshake, + Read(&'a mut [u8]), + Write(Option>), + Shutdown, + #[cfg(ossl111)] + PostHandshake, + } + + #[cfg(all(unix, not(target_os = "aix")))] + impl IoOperation<'_> { + fn timeout_message(&self, needs: Option) -> &'static str { + match self { + Self::Handshake => "The handshake operation timed out", + Self::Read(_) => "The read operation timed out", + Self::Write(_) => "The write operation timed out", + Self::Shutdown if needs == Some(Needs::Read) => "The read operation timed out", + Self::Shutdown => "The write operation timed out", + #[cfg(ossl111)] + Self::PostHandshake => "The handshake operation timed out", + } + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + enum IoOutput { + Done, + Count(usize), + Shutdown(ssl::ShutdownResult), + Unwrapped(Option>), + } + + #[cfg(all(unix, not(target_os = "aix")))] + enum IoStep { + Done(IoOutput), + // Preserve the pre-existing clean-read-EOF/PHA signal boundary. + Immediate(IoOutput), + Again, + Wait(Option, Needs), + } + + // Owned failures leave the native guard before exception allocation or + // attribute writes, either of which can execute Python (including GC). + #[cfg(all(unix, not(target_os = "aix")))] + enum IoError { + Eof, + Closed, + Timeout(&'static str), + WantWrite, + Message(&'static str), + Io(std::io::Error), + Callback(PyBaseExceptionRef), + Native(SslErrorSnapshot, Option), + #[cfg(ossl111)] + Stack(ErrorStack, Option), + } + + #[cfg(all(unix, not(target_os = "aix")))] + impl IoError { + fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + match self { + Self::Eof => create_ssl_eof_error(vm).upcast(), + Self::Closed => socket_closed_error(vm), + Self::Timeout(message) => { + socket::timeout_error_msg(vm, message.to_owned()).upcast() + } + Self::WantWrite => create_ssl_want_write_error(vm).upcast(), + Self::Message(message) => new_ssl_error(vm, message), + Self::Io(error) => error.to_pyexception(vm), + Self::Callback(error) => error, + Self::Native(error, callback) => { + let error = error.into_pyexception(vm); + if let Some(callback) = callback { + error.set_context(Some(callback)); + } + error + } + #[cfg(ossl111)] + Self::Stack(error, callback) => { + let error = convert_openssl_error(vm, error); + if let Some(callback) = callback { + error.set_context(Some(callback)); + } + error + } + } + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + struct IoCall<'a> { + _ssl: &'a PySslSocket, + owner: Option, + owns_pending: bool, + last_needs: Option, + progress: Arc, + socket: Option<(PyRef, Arc, SocketDeadline)>, + waiter: Option>, + // Keep this installed through waits and signal callbacks, but never + // expose a stale native SSL pointer while its guard is released. + _scope: IoScope, + } + + #[cfg(all(unix, not(target_os = "aix")))] + impl<'a> IoCall<'a> { + fn new(ssl: &'a PySslSocket, writing: bool, vm: &VirtualMachine) -> PyResult { + let scope = IoScope::enter(ssl, vm)?; + let connection = ssl.connection.read(); + let progress = connection.progress.clone(); + let socket = connection.get_ref().map(|stream| { + ( + stream.socket.clone(), + stream.identity.clone(), + stream.timeout_deadline(), + ) + }); + Ok(Self { + _ssl: ssl, + owner: writing.then(WriteOwner::new), + owns_pending: false, + last_needs: None, + progress, + socket, + waiter: None, + _scope: scope, + }) + } + + fn prepare_wait( + &mut self, + observed: u64, + needs: Option, + error: IoError, + timeout_message: &'static str, + ) -> Result { + let Some((socket, identity, deadline)) = &self.socket else { + return Err(error); + }; + match deadline { + Err(false) => return Err(error), + Ok(deadline) if *deadline <= Instant::now() => { + return Err(IoError::Timeout(timeout_message)); + } + _ => {} + } + if self.waiter.is_none() { + self.waiter = Some(Arc::new(ProgressWaiter::new().map_err(IoError::Io)?)); + } + let waiter = self.waiter.as_ref().expect("waiter initialized"); + // Close does not need the SSL lock. Drain BEFORE checking identity + // and subscribing, or a concurrent close notification could be lost. + match waiter.drain() { + Ok(()) => {} + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => { + return Ok(IoStep::Again); + } + Err(error) => return Err(IoError::Io(error)), + } + let fd = socket + .sock_for_ssl_identity(identity) + .map_err(|_| IoError::Closed)? + .as_raw_fd(); + if !identity.subscribe(waiter.clone()) { + return Err(IoError::Closed); + } + self.progress.register(waiter, observed); + // Exclusive-writer contenders must not poll socket writability: it + // can remain ready while they are forbidden to execute native I/O. + Ok(IoStep::Wait( + needs.map(|_| fd), + needs.unwrap_or(Needs::Write), + )) + } + + fn wait( + &self, + fd: Option, + needs: Needs, + timeout_message: &'static str, + vm: &VirtualMachine, + ) -> Result<(), IoError> { + let waiter = self.waiter.as_ref().expect("registered waiter"); + let deadline = self + .socket + .as_ref() + .and_then(|(_, _, deadline)| deadline.as_ref().ok().copied()); + loop { + let result = vm.allow_threads(|| waiter.wait(fd, needs == Needs::Write, deadline)); + // No connection or socket lock is held while Python signals run. + vm.check_signals().map_err(IoError::Callback)?; + match result { + Ok(false) => return Ok(()), + Ok(true) => { + return Err(IoError::Timeout(timeout_message)); + } + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {} + Err(error) => { + if self + .socket + .as_ref() + .is_some_and(|(_, identity, _)| identity.is_closed()) + { + return Err(IoError::Closed); + } + return Err(IoError::Io(error)); + } + } + } + } + + fn abandon_pending(&mut self) { + if self.owns_pending { + self.owner.as_ref().expect("pending write owner").release(); + self.owns_pending = false; + self.progress.notify(); + } + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + impl Drop for IoCall<'_> { + fn drop(&mut self) { + // Cleanup must never acquire the SSL lock: a callback on another + // thread may be waiting for this invocation to finish. Publish an + // orphan before waking generation-checked registrations instead. + self.abandon_pending(); + if let Some(waiter) = &self.waiter { + self.progress.unregister(waiter); + if let Some((_, identity, _)) = &self.socket { + identity.unsubscribe(waiter.clone()); + } + } + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + impl PySslSocket { + fn install_progress_callback(&self) { + let connection = self.connection.write(); + let pointer = connection.ssl().as_ptr(); + unsafe { + self.previous_info_callback + .store(SSL_get_info_callback(pointer)); + SSL_set_info_callback(pointer, Some(ssl_info_progress)); + } + } + + fn drive(&self, mut operation: IoOperation<'_>, vm: &VirtualMachine) -> PyResult { + self.check_eof(vm)?; + let mut call = IoCall::new(self, matches!(operation, IoOperation::Write(_)), vm)?; + let mut queued = false; + let mut shutdown_zeros = 0; + let mut attempted = false; + let mut waited_for_ownership = false; + loop { + let step = (|| { + let mut connection = self.connection.write(); + if self.got_eof_error.load() { + return Err(IoError::Eof); + } + if connection.driver.terminal { + return Err(IoError::Message( + "TLS connection is unusable after a fatal error", + )); + } + if call + .socket + .as_ref() + .is_some_and(|(_, identity, _)| identity.is_closed()) + { + return Err(IoError::Closed); + } + // Buffered TLS data can satisfy even a very short positive + // timeout. Attempt native I/O once before timing retries. + if (attempted || waited_for_ownership) + && call.socket.as_ref().is_some_and(|(_, _, deadline)| { + deadline + .as_ref() + .is_ok_and(|deadline| *deadline <= Instant::now()) + }) + { + return Err(IoError::Timeout(operation.timeout_message(call.last_needs))); + } + // Abandonment is deliberately independent of the SSL lock. + // Observe its generation before checking the predicate. + let observed = call.progress.generation(); + let permit = match &mut operation { + IoOperation::Write(bytes) => connection.driver.write( + call.owner.as_ref().unwrap(), + bytes, + &mut queued, + ), + _ => connection.driver.other_io(), + }; + match permit { + Permit::RetryOriginalWrite => Err(IoError::WantWrite), + Permit::InvalidRetry => Err(IoError::Message( + "The pending SSL write must be retried with the same data in a new call", + )), + Permit::Wait => { + waited_for_ownership = true; + call.prepare_wait( + observed, + None, + IoError::WantWrite, + operation.timeout_message(call.last_needs), + ) + } + Permit::Ready => { + attempted = true; + call.owns_pending = call.owner.is_some(); + let before = ( + connection.io_progress(), + self.info_progress.load(), + connection.get_shutdown(), + ); + let permission_before = connection.driver.other_io(); + let pointer = connection.ssl().as_ptr(); + let result = { + let _native_scope = + HandshakeVmGuard::new(vm, &self.connection, pointer); + match &mut operation { + IoOperation::Handshake => vm + .allow_threads(|| connection.do_handshake()) + .map(|()| IoOutput::Done), + IoOperation::Read(buffer) => vm + .allow_threads(|| connection.ssl_read(buffer)) + .map(IoOutput::Count), + IoOperation::Write(_) => { + let SslConnection { + transport, driver, .. + } = &mut *connection; + vm.allow_threads(|| { + transport.ssl_write( + driver.bytes(call.owner.as_ref().unwrap()), + ) + }) + .map(IoOutput::Count) + } + IoOperation::Shutdown => { + if self.shutdown_seen_zero.load() { + // Leave plaintext after close_notify for unwrap(). + unsafe { + sys::SSL_ctrl( + pointer, + sys::SSL_CTRL_SET_READ_AHEAD, + 0, + core::ptr::null_mut(), + ); + } + } + vm.allow_threads(|| connection.shutdown()) + .map(IoOutput::Shutdown) + } + #[cfg(ossl111)] + IoOperation::PostHandshake => { + unsafe { sys::ERR_clear_error() }; + let result = vm.allow_threads(|| unsafe { + SSL_verify_client_post_handshake(pointer) + }); + let error = (result == 0).then(ErrorStack::get); + let callback = self.callback_error.lock().take(); + connection.notify_progress(); + return match (error, callback) { + (Some(error), callback) => { + Err(IoError::Stack(error, callback)) + } + (None, Some(callback)) => { + Err(IoError::Callback(callback)) + } + (None, None) => Ok(IoStep::Immediate(IoOutput::Done)), + }; + } + } + }; + let needs = + result.as_ref().err().and_then(|error| match error.code() { + ssl::ErrorCode::WANT_READ => Some(Needs::Read), + ssl::ErrorCode::WANT_WRITE => Some(Needs::Write), + _ => None, + }); + call.last_needs = needs; + let terminal = result.as_ref().err().is_some_and(|error| { + matches!( + error.code(), + ssl::ErrorCode::SSL | ssl::ErrorCode::SYSCALL + ) + }); + // Settle native ownership BEFORE a callback/signal can + // return an exception. Success must never be replayed. + if let Some(owner) = &call.owner { + call.owns_pending = connection.driver.settle_write(owner, needs); + } + if terminal { + connection.driver.fail(); + } + if result.as_ref().err().is_some_and(is_unexpected_eof) { + self.got_eof_error.store(true); + } + let after = ( + connection.io_progress(), + self.info_progress.load(), + connection.get_shutdown(), + ); + if before != after + || result.is_ok() + || terminal + || permission_before != connection.driver.other_io() + { + connection.notify_progress(); + } + let interrupted = connection.take_interrupted(); + // Snapshot exactly once, while this operation still + // owns native state. No unlocked helper drains it. + let callback = self.callback_error.lock().take(); + if let Some(callback) = callback { + // A fully blocking socket could not expose this + // intermediate WANT before the nonblocking driver. + // Timeout/nonblocking sockets and MemoryBIO retain + // native-error-first exception chaining. + if needs.is_some() + && call.socket.as_ref().is_some_and(|(_, _, deadline)| { + matches!(deadline, Err(true)) + }) + { + return Err(IoError::Callback(callback)); + } + return Err(match result { + Ok(_) => IoError::Callback(callback), + Err(error) => IoError::Native( + SslErrorSnapshot::capture(error, pointer), + Some(callback), + ), + }); + } + match result { + Ok(IoOutput::Shutdown(ssl::ShutdownResult::Sent)) => { + shutdown_zeros += 1; + self.shutdown_seen_zero.store(true); + if shutdown_zeros > 1 { + Ok(IoStep::Done(IoOutput::Unwrapped( + call.socket + .as_ref() + .map(|(socket, _, _)| socket.clone()), + ))) + } else { + Ok(IoStep::Again) + } + } + Ok(IoOutput::Shutdown(ssl::ShutdownResult::Received)) => { + Ok(IoStep::Done(IoOutput::Unwrapped( + call.socket.as_ref().map(|(socket, _, _)| socket.clone()), + ))) + } + Ok(output) => Ok(IoStep::Done(output)), + Err(error) => { + // Callback errors take precedence over these + // successful/EOF read reinterpretations above. + if matches!(operation, IoOperation::Read(_)) { + if error.code() == ssl::ErrorCode::ZERO_RETURN { + return Ok(IoStep::Immediate(IoOutput::Count(0))); + } + if error.code() == ssl::ErrorCode::WANT_READ + && connection.is_bio_eof() + { + self.got_eof_error.store(true); + connection.driver.fail(); + connection.notify_progress(); + return Err(IoError::Eof); + } + } + let error = IoError::Native( + SslErrorSnapshot::capture(error, pointer), + None, + ); + if let Some(needs) = needs { + if interrupted { + Ok(IoStep::Again) + } else { + call.prepare_wait( + observed, + Some(needs), + error, + operation.timeout_message(call.last_needs), + ) + } + } else { + Err(error) + } + } + } + } + } + })(); + // Allocation/attribute writes may run arbitrary Python. The + // SSL guard and callback pointer are gone, and a known-exiting + // write no longer blocks contenders as an active owner. + let step = match step { + Ok(IoStep::Immediate(output)) => return Ok(output), + Ok(step) => step, + Err(error) => { + call.abandon_pending(); + return Err(error.into_pyexception(vm)); + } + }; + if let Err(error) = vm.check_signals() { + call.abandon_pending(); + return Err(error); + } + match step { + IoStep::Immediate(_) => unreachable!("immediate result already returned"), + IoStep::Done(output) => return Ok(output), + IoStep::Again => {} + IoStep::Wait(fd, needs) => { + if let Err(error) = + call.wait(fd, needs, operation.timeout_message(call.last_needs), vm) + { + call.abandon_pending(); + return Err(error.into_pyexception(vm)); + } + } + } + } + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + type SslInfoCallback = + Option; + + #[cfg(all(unix, not(target_os = "aix")))] + unsafe extern "C" { + fn SSL_get_info_callback(ssl: *const sys::SSL) -> SslInfoCallback; + fn SSL_set_info_callback(ssl: *mut sys::SSL, callback: SslInfoCallback); + fn SSL_CTX_get_info_callback(ctx: *const sys::SSL_CTX) -> SslInfoCallback; + } + + #[cfg(all(unix, not(target_os = "aix")))] + unsafe extern "C" fn ssl_info_progress( + ssl: *const sys::SSL, + where_: core::ffi::c_int, + value: core::ffi::c_int, + ) { + // These public callback bits are present in OpenSSL 1.1.1 as well as 3.x. + const SSL_CB_LOOP: core::ffi::c_int = 0x01; + const SSL_CB_HANDSHAKE_DONE: core::ffi::c_int = 0x20; + const SSL_CB_ALERT: core::ffi::c_int = 0x4000; + unsafe { + let socket = + sys::SSL_get_ex_data(ssl, get_socket_ex_data_index()) as *const Py; + if socket.is_null() { + return; + } + let socket = &*socket; + if where_ & (SSL_CB_LOOP | SSL_CB_HANDSHAKE_DONE | SSL_CB_ALERT) != 0 { + socket + .info_progress + .store(socket.info_progress.load().wrapping_add(1)); + } + // A NULL per-SSL callback delegates to the CURRENT context, including + // a context installed by SNI. Preserve that fallback dynamically. + let callback = socket + .previous_info_callback + .load() + .or_else(|| SSL_CTX_get_info_callback(sys::SSL_get_SSL_CTX(ssl))); + if let Some(callback) = callback { + callback(ssl, where_, value); + } + } + } + #[pyclass(flags(IMMUTABLETYPE))] impl PySslSocket { + #[cfg(all(unix, not(target_os = "aix")))] + #[pymethod] + fn do_handshake(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + zelf.drive(IoOperation::Handshake, vm).map(|_| ()) + } + + #[cfg(all(unix, not(target_os = "aix")))] + #[pymethod] + fn shutdown(zelf: &Py, vm: &VirtualMachine) -> PyResult>> { + // Do not reacquire the connection after completion: another native + // callback may already be waiting for this Python call to return. + match zelf.drive(IoOperation::Shutdown, vm)? { + IoOutput::Unwrapped(socket) => Ok(socket), + _ => unreachable!("shutdown returns its underlying socket"), + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + #[pymethod] + fn verify_client_post_handshake(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + cfg_select! { + ossl111 => zelf.drive(IoOperation::PostHandshake, vm).map(|_| ()), + _ => Err(vm.new_not_implemented_error("Post-handshake auth is not supported by your OpenSSL version.")), + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + #[pymethod] + fn write(zelf: &Py, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult { + zelf.check_eof(vm)?; + // OpenSSL retains the write across WANT, including after this + // Python invocation returns. Own the bytes, not an exporter lock. + let bytes = { + let source = data.borrow_buf(); + let mut owned = Vec::new(); + owned + .try_reserve_exact(source.len()) + .map_err(|_| vm.no_memory_error())?; + owned.extend_from_slice(&source); + owned.into_boxed_slice() + }; + match zelf.drive(IoOperation::Write(Some(bytes)), vm)? { + IoOutput::Count(count) => Ok(count), + _ => unreachable!("write returns a byte count"), + } + } + + #[cfg(all(unix, not(target_os = "aix")))] + #[pymethod] + fn read( + zelf: &Py, + n: isize, + buffer: OptionalArg, + vm: &VirtualMachine, + ) -> PyResult { + let read_len = match &buffer { + OptionalArg::Present(buffer) => { + let len = buffer.borrow_buf_mut().len(); + if n <= 0 || n as usize > len { + len + } else { + n as usize + } + } + OptionalArg::Missing => { + if n < 0 { + return Err(vm.new_value_error("size should not be negative")); + } + n as usize + } + }; + zelf.check_eof(vm)?; + // As in CPython, a zero-length read need not enter native SSL. + if read_len == 0 { + return Ok(if buffer.is_present() { + vm.ctx.new_int(0).into() + } else { + vm.ctx.new_bytes(vec![]).into() + }); + } + // Do not keep the caller's buffer locked while waiting for a peer. + let mut scratch = vm.new_zeroed_bytes(read_len)?; + let count = match zelf.drive(IoOperation::Read(&mut scratch), vm)? { + IoOutput::Count(count) => count, + _ => unreachable!("read returns a byte count"), + }; + Ok(match &buffer { + OptionalArg::Present(buffer) => { + buffer.borrow_buf_mut()[..count].copy_from_slice(&scratch[..count]); + vm.ctx.new_int(count).into() + } + OptionalArg::Missing => { + scratch.truncate(count); + scratch.shrink_to_fit(); + vm.ctx.new_bytes(scratch).into() + } + }) + } + + fn callback_owner(zelf: &Py) -> Option { + if let Some(owner) = zelf.owner.read().as_ref() { + return owner.upgrade(); + } + // A MemoryBIO wrapper may have no Python owner. + Some(zelf.as_object().to_owned()) + } + + fn check_eof(&self, vm: &VirtualMachine) -> PyResult<()> { + if self.got_eof_error.load() { + Err(create_ssl_eof_error(vm).upcast()) + } else { + Ok(()) + } + } + + #[cfg(not(all(unix, not(target_os = "aix"))))] + fn ssl_error( + &self, + error: ssl::Error, + ssl_ptr: *const sys::SSL, + vm: &VirtualMachine, + ) -> PyBaseExceptionRef { + if is_unexpected_eof(&error) { + self.got_eof_error.store(true); + } + SslErrorSnapshot::capture(error, ssl_ptr).into_pyexception(vm) + } + + #[cfg(not(all(unix, not(target_os = "aix"))))] + fn finish_ssl_operation( + &self, + result: Result, + ssl_ptr: *const sys::SSL, + vm: &VirtualMachine, + ) -> PyResult> { + let callback_error = self.callback_error.lock().take(); + if let Some(callback_error) = callback_error { + return Err(match result { + Ok(_) => callback_error, + Err(error) => { + let error = self.ssl_error(error, ssl_ptr, vm); + error.set_context(Some(callback_error)); + error + } + }); + } + Ok(result) + } + #[pygetset] fn owner(zelf: &Py) -> Option { zelf.owner.read().as_ref().and_then(|weak| weak.upgrade()) } #[pygetset(setter)] - fn set_owner(zelf: &Py, owner: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn set_owner( + zelf: &Py, + owner: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let owner = owner + .ok_or_else(|| vm.new_attribute_error("attribute 'owner' cannot be deleted"))?; let mut lock = zelf.owner.write(); lock.take(); *lock = Some(owner.downgrade(None, vm)?); @@ -2532,24 +3637,21 @@ mod _ssl { #[pygetset(setter)] fn set_context( zelf: &Py, - value: PyRef, + value: PySetterValue>, vm: &VirtualMachine, ) -> PyResult<()> { - // Get SSL pointer - use thread-local during handshake to avoid deadlock - // (connection lock is already held during handshake) - let ssl_ptr = get_ssl_ptr_for_context_change(&zelf.connection); - - // Set the new SSL_CTX on the SSL object - unsafe { - let result = SSL_set_SSL_CTX(ssl_ptr, value.ctx().as_ptr()); - if result.is_null() { - return Err(vm.new_runtime_error("Failed to set SSL context")); + let value = value + .ok_or_else(|| vm.new_attribute_error("attribute 'context' cannot be deleted"))?; + with_ssl_pointer_mut(&zelf.connection, |ssl_ptr| { + unsafe { + let result = SSL_set_SSL_CTX(ssl_ptr, value.ctx().as_ptr()); + if result.is_null() { + return Err(vm.new_runtime_error("Failed to set SSL context")); + } } - } - - // Update self.ctx to the new context - *zelf.ctx.write() = value; - Ok(()) + *zelf.ctx.write() = value; + Ok(()) + }) } #[pygetset] fn server_hostname(zelf: &Py) -> Option { @@ -2562,183 +3664,280 @@ mod _ssl { args: GetCertArgs, vm: &VirtualMachine, ) -> PyResult> { - let binary = args.binary_form.unwrap_or(false); - let stream = zelf.connection.read(); - if !stream.ssl().is_init_finished() { - return Err(vm.new_value_error("handshake not done yet")); - } + let binary = args.binary_form.map_or(false, ArgIntoBool::into_bool); + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + let ssl = unsafe { ssl::SslRef::from_ptr(ssl_ptr) }; + if !ssl.is_init_finished() { + return Err(vm.new_value_error("handshake not done yet")); + } - let peer_cert = stream.ssl().peer_certificate(); - let Some(cert) = peer_cert else { - return Ok(None); - }; + let peer_cert = ssl.peer_certificate(); + let Some(cert) = peer_cert else { + return Ok(None); + }; - if binary { - // Return DER-encoded certificate - cert_to_py(vm, &cert, true).map(Some) - } else { - // Check verify_mode + if binary { + // Return DER-encoded certificate + cert_to_py(vm, &cert, true).map(Some) + } else { + // Check verify_mode + unsafe { + let ssl_ctx = sys::SSL_get_SSL_CTX(ssl_ptr); + let verify_mode = sys::SSL_CTX_get_verify_mode(ssl_ctx); + if (verify_mode & sys::SSL_VERIFY_PEER as core::ffi::c_int) == 0 { + // Return empty dict when SSL_VERIFY_PEER is not set + Ok(Some(vm.ctx.new_dict().into())) + } else { + // Return decoded certificate + cert_to_py(vm, &cert, false).map(Some) + } + } + } + }) + } + + #[pymethod] + fn get_unverified_chain( + zelf: &Py, + vm: &VirtualMachine, + ) -> PyResult> { + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + let ssl = unsafe { ssl::SslRef::from_ptr(ssl_ptr) }; + let chain = ssl.peer_cert_chain(); + // Resumed server sessions retain the peer certificate, not its chain. + let peer = if matches!(zelf.socket_type, SslServerOrClient::Server) { + let Some(peer) = ssl.peer_certificate() else { + return Ok(None); + }; + Some(peer) + } else { + if chain.is_none() { + return Ok(None); + } + None + }; + + // Return Certificate objects + let mut certs: Vec = chain + .into_iter() + .flat_map(|chain| chain.iter()) + .map(|cert| unsafe { + sys::X509_up_ref(cert.as_ptr()); + let owned = X509::from_ptr(cert.as_ptr()); + cert_to_certificate(vm, owned) + }) + .collect::>()?; + + // SSL_get_peer_cert_chain does not include peer cert for server-side sockets + // Add it manually at the beginning + if let Some(peer_cert) = peer { + let peer_obj = cert_to_certificate(vm, peer_cert)?; + certs.insert(0, peer_obj); + } + + Ok(Some(vm.ctx.new_list(certs))) + }) + } + + #[pymethod] + fn get_verified_chain(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + with_ssl_pointer(&zelf.connection, |ssl_ptr| { unsafe { - let ssl_ctx = sys::SSL_get_SSL_CTX(stream.ssl().as_ptr()); - let verify_mode = sys::SSL_CTX_get_verify_mode(ssl_ctx); - if (verify_mode & sys::SSL_VERIFY_PEER as core::ffi::c_int) == 0 { - // Return empty dict when SSL_VERIFY_PEER is not set - Ok(Some(vm.ctx.new_dict().into())) - } else { - // Return decoded certificate - cert_to_py(vm, &cert, false).map(Some) + let chain = sys::SSL_get0_verified_chain(ssl_ptr); + if chain.is_null() { + return Ok(None); + } + + let num_certs = sys::OPENSSL_sk_num(chain as *const _); + + let mut certs = Vec::with_capacity(num_certs as usize); + // Return Certificate objects + for i in 0..num_certs { + let cert_ptr = + sys::OPENSSL_sk_value(chain as *const _, i) as *mut sys::X509; + if cert_ptr.is_null() { + continue; + } + // Clone the X509 certificate to create an owned copy + sys::X509_up_ref(cert_ptr); + let owned_cert = X509::from_ptr(cert_ptr); + let cert_obj = cert_to_certificate(vm, owned_cert)?; + certs.push(cert_obj); } + + Ok(if certs.is_empty() { + None + } else { + Some(vm.ctx.new_list(certs)) + }) + } + }) + } + + #[pymethod] + fn version(zelf: &Py) -> Option<&'static str> { + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + // Return None if handshake is not complete (CPython behavior). + if unsafe { sys::SSL_is_init_finished(ssl_ptr) } == 0 { + return None; } + let version = unsafe { ssl::SslRef::from_ptr(ssl_ptr).version_str() }; + if version == "unknown" { + None + } else { + Some(version) + } + }) + } + #[pymethod] + fn cipher(zelf: &Py) -> Option { + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + unsafe { ssl::SslRef::from_ptr(ssl_ptr).current_cipher() }.map(cipher_to_tuple) + }) + } + #[pymethod] + fn group(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + #[cfg(ossl320)] + { + let _ = vm; + Ok(with_ssl_pointer(&zelf.connection, |ssl_ptr| { + // OpenSSL can dereference a missing session in SSL_get0_group_name. + if unsafe { sys::SSL_get_session(ssl_ptr) }.is_null() { + return None; + } + let name = unsafe { SSL_get0_group_name(ssl_ptr) }; + (!name.is_null()) + .then(|| unsafe { CStr::from_ptr(name).to_string_lossy().into_owned() }) + })) + } + #[cfg(not(ossl320))] + { + let _ = zelf; + Err(vm.new_not_implemented_error( + "Getting selected group requires OpenSSL 3.2 or later.", + )) } } - #[pymethod] - fn get_unverified_chain( - zelf: &Py, + fn signature_name( + &self, + side: SslServerOrClient, vm: &VirtualMachine, - ) -> PyResult> { - let stream = zelf.connection.read(); - let ssl = stream.ssl(); - let Some(chain) = ssl.peer_cert_chain() else { - return Ok(None); - }; - - // Return Certificate objects - let mut certs: Vec = chain - .iter() - .map(|cert| unsafe { - sys::X509_up_ref(cert.as_ptr()); - let owned = X509::from_ptr(cert.as_ptr()); - cert_to_certificate(vm, owned) - }) - .collect::>()?; - - // SSL_get_peer_cert_chain does not include peer cert for server-side sockets - // Add it manually at the beginning - if matches!(zelf.socket_type, SslServerOrClient::Server) - && let Some(peer_cert) = ssl.peer_certificate() + ) -> PyResult> { + #[cfg(ossl350)] { - let peer_obj = cert_to_certificate(vm, peer_cert)?; - certs.insert(0, peer_obj); + let _ = vm; + const SSL_CTRL_GET_SIGNATURE_NAME: core::ffi::c_int = 140; + const SSL_CTRL_GET_PEER_SIGNATURE_NAME: core::ffi::c_int = 141; + let command = if self.socket_type == side { + SSL_CTRL_GET_SIGNATURE_NAME + } else { + SSL_CTRL_GET_PEER_SIGNATURE_NAME + }; + Ok(with_ssl_pointer(&self.connection, |ssl_ptr| { + let mut name: *const core::ffi::c_char = core::ptr::null(); + let result = unsafe { + sys::SSL_ctrl(ssl_ptr, command, 0, core::ptr::addr_of_mut!(name).cast()) + }; + (result != 0 && !name.is_null()) + .then(|| unsafe { CStr::from_ptr(name).to_string_lossy().into_owned() }) + })) + } + #[cfg(not(ossl350))] + { + let _ = side; + Err(vm.new_not_implemented_error( + "Getting sig algorithms requires OpenSSL 3.5 or later.", + )) } - - Ok(Some(vm.ctx.new_list(certs))) } #[pymethod] - fn get_verified_chain(zelf: &Py, vm: &VirtualMachine) -> PyResult> { - let stream = zelf.connection.read(); - unsafe { - let chain = sys::SSL_get0_verified_chain(stream.ssl().as_ptr()); - if chain.is_null() { - return Ok(None); - } - - let num_certs = sys::OPENSSL_sk_num(chain as *const _); - - let mut certs = Vec::with_capacity(num_certs as usize); - // Return Certificate objects - for i in 0..num_certs { - let cert_ptr = sys::OPENSSL_sk_value(chain as *const _, i) as *mut sys::X509; - if cert_ptr.is_null() { - continue; - } - // Clone the X509 certificate to create an owned copy - sys::X509_up_ref(cert_ptr); - let owned_cert = X509::from_ptr(cert_ptr); - let cert_obj = cert_to_certificate(vm, owned_cert)?; - certs.push(cert_obj); - } + fn client_sigalg(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + zelf.signature_name(SslServerOrClient::Client, vm) + } - Ok(if certs.is_empty() { - None - } else { - Some(vm.ctx.new_list(certs)) - }) - } + #[pymethod] + fn server_sigalg(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + zelf.signature_name(SslServerOrClient::Server, vm) } #[pymethod] - fn version(zelf: &Py) -> Option<&'static str> { - // Use thread-local SSL pointer during handshake to avoid deadlock - let ssl_ptr = get_ssl_ptr_for_context_change(&zelf.connection); - // Return None if handshake is not complete (CPython behavior) - if unsafe { sys::SSL_is_init_finished(ssl_ptr) } == 0 { - return None; - } - let v = unsafe { ssl::SslRef::from_ptr(ssl_ptr).version_str() }; - if v == "unknown" { None } else { Some(v) } + fn uses_ktls_for_send(_zelf: &Py) -> bool { + // SslStream uses a custom Rust BIO, never OpenSSL's kernel TLS socket BIO. + false } #[pymethod] - fn cipher(zelf: &Py) -> Option { - // Use thread-local SSL pointer during handshake to avoid deadlock - let ssl_ptr = get_ssl_ptr_for_context_change(&zelf.connection); - unsafe { ssl::SslRef::from_ptr(ssl_ptr).current_cipher() }.map(cipher_to_tuple) + fn uses_ktls_for_recv(_zelf: &Py) -> bool { + false } #[pymethod] fn pending(zelf: &Py) -> i32 { - let stream = zelf.connection.read(); - unsafe { sys::SSL_pending(stream.ssl().as_ptr()) } + with_ssl_pointer(&zelf.connection, |ssl_ptr| unsafe { + sys::SSL_pending(ssl_ptr) + }) } #[pymethod] fn shared_ciphers(zelf: &Py, vm: &VirtualMachine) -> Option { #[cfg(ossl110)] { - // Use thread-local SSL pointer during handshake to avoid deadlock - let ssl_ptr = get_ssl_ptr_for_context_change(&zelf.connection); - unsafe { - let server_ciphers = SSL_get_ciphers(ssl_ptr); - if server_ciphers.is_null() { - return None; - } - - let client_ciphers = SSL_get_client_ciphers(ssl_ptr); - if client_ciphers.is_null() { - return None; - } + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + unsafe { + let server_ciphers = SSL_get_ciphers(ssl_ptr); + if server_ciphers.is_null() { + return None; + } - let mut result = Vec::new(); - let num_server = sys::OPENSSL_sk_num(server_ciphers as *const _); - let num_client = sys::OPENSSL_sk_num(client_ciphers as *const _); + let client_ciphers = SSL_get_client_ciphers(ssl_ptr); + if client_ciphers.is_null() { + return None; + } - for i in 0..num_server { - let server_cipher_ptr = sys::OPENSSL_sk_value(server_ciphers as *const _, i) - as *const sys::SSL_CIPHER; + let mut result = Vec::new(); + let num_server = sys::OPENSSL_sk_num(server_ciphers as *const _); + let num_client = sys::OPENSSL_sk_num(client_ciphers as *const _); - // Check if client supports this cipher by comparing pointers - let mut found = false; - for j in 0..num_client { - let client_cipher_ptr = - sys::OPENSSL_sk_value(client_ciphers as *const _, j) + for i in 0..num_server { + let server_cipher_ptr = + sys::OPENSSL_sk_value(server_ciphers as *const _, i) as *const sys::SSL_CIPHER; - if server_cipher_ptr == client_cipher_ptr { - found = true; - break; + // Check if client supports this cipher by comparing pointers + let mut found = false; + for j in 0..num_client { + let client_cipher_ptr = + sys::OPENSSL_sk_value(client_ciphers as *const _, j) + as *const sys::SSL_CIPHER; + + if server_cipher_ptr == client_cipher_ptr { + found = true; + break; + } } - } - if found { - let cipher = ssl::SslCipherRef::from_ptr(server_cipher_ptr as *mut _); - let (name, version, bits) = cipher_to_tuple(cipher); - let tuple = vm.new_tuple(( - vm.ctx.new_str(name), - vm.ctx.new_str(version), - vm.ctx.new_int(bits), - )); - result.push(tuple.into()); + if found { + let cipher = + ssl::SslCipherRef::from_ptr(server_cipher_ptr as *mut _); + let (name, version, bits) = cipher_to_tuple(cipher); + let tuple = vm.new_tuple(( + vm.ctx.new_str(name), + vm.ctx.new_str(version), + vm.ctx.new_int(bits), + )); + result.push(tuple.into()); + } } - } - if result.is_empty() { - None - } else { - Some(vm.ctx.new_list(result)) + if result.is_empty() { + None + } else { + Some(vm.ctx.new_list(result)) + } } - } + }) } #[cfg(not(ossl110))] { @@ -2751,9 +3950,7 @@ mod _ssl { fn selected_alpn_protocol(zelf: &Py) -> Option { #[cfg(ossl102)] { - // Use thread-local SSL pointer during handshake to avoid deadlock - let ssl_ptr = get_ssl_ptr_for_context_change(&zelf.connection); - unsafe { + with_ssl_pointer(&zelf.connection, |ssl_ptr| unsafe { let mut out: *const core::ffi::c_uchar = core::ptr::null(); let mut outlen: core::ffi::c_uint = 0; @@ -2765,7 +3962,7 @@ mod _ssl { let slice = core::slice::from_raw_parts(out, outlen as usize); Some(String::from_utf8_lossy(slice).into_owned()) } - } + }) } #[cfg(not(ossl102))] { @@ -2790,172 +3987,112 @@ mod _ssl { ))); } - let stream = zelf.connection.read(); - let ssl_ptr = stream.ssl().as_ptr(); - - unsafe { - let session_reused = sys::SSL_session_reused(ssl_ptr) != 0; - let is_client = matches!(zelf.socket_type, SslServerOrClient::Client); + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + unsafe { + let session_reused = sys::SSL_session_reused(ssl_ptr) != 0; + let is_client = matches!(zelf.socket_type, SslServerOrClient::Client); - // Use XOR logic from CPython - let use_finished = session_reused ^ is_client; + // Use XOR logic from CPython + let use_finished = session_reused ^ is_client; - let mut buf = vec![0u8; CB_MAXLEN]; - let len = if use_finished { - sys::SSL_get_finished(ssl_ptr, buf.as_mut_ptr() as *mut _, CB_MAXLEN) - } else { - sys::SSL_get_peer_finished(ssl_ptr, buf.as_mut_ptr() as *mut _, CB_MAXLEN) - }; + let mut buf = vec![0u8; CB_MAXLEN]; + let len = if use_finished { + sys::SSL_get_finished(ssl_ptr, buf.as_mut_ptr() as *mut _, CB_MAXLEN) + } else { + sys::SSL_get_peer_finished(ssl_ptr, buf.as_mut_ptr() as *mut _, CB_MAXLEN) + }; - if len == 0 { - Ok(None) - } else { - buf.truncate(len); - Ok(Some(vm.ctx.new_bytes(buf))) + if len == 0 { + Ok(None) + } else { + buf.truncate(len); + Ok(Some(vm.ctx.new_bytes(buf))) + } } - } + }) } + #[cfg(not(all(unix, not(target_os = "aix"))))] #[pymethod] fn verify_client_post_handshake(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { cfg_select! { ossl111 => { - let stream = zelf.connection.read(); - let result = unsafe { SSL_verify_client_post_handshake(stream.ssl().as_ptr()) }; - if result == 0 { - Err(convert_openssl_error(vm, openssl::error::ErrorStack::get())) - } else { - Ok(()) - } - } - _ => { - Err(vm.new_not_implemented_error( - "Post-handshake auth is not supported by your OpenSSL version.", - )) + with_ssl_pointer_mut(&zelf.connection, |ssl_ptr| { + let result = unsafe { SSL_verify_client_post_handshake(ssl_ptr) }; + if result == 0 { + Err(convert_openssl_error(vm, openssl::error::ErrorStack::get())) + } else { + Ok(()) + } + }) } + _ => Err(vm.new_not_implemented_error( + "Post-handshake auth is not supported by your OpenSSL version.", + )), } } + #[cfg(not(all(unix, not(target_os = "aix"))))] #[pymethod] fn shutdown(zelf: &Py, vm: &VirtualMachine) -> PyResult>> { - let stream = zelf.connection.read(); + let mut stream = zelf.connection.write(); let ssl_ptr = stream.ssl().as_ptr(); - - // BIO mode: just try shutdown once and raise SSLWantReadError if needed - if stream.is_bio() { - let ret = vm.allow_threads(|| unsafe { sys::SSL_shutdown(ssl_ptr) }); - if ret < 0 { - let err = unsafe { sys::SSL_get_error(ssl_ptr, ret) }; - if err == sys::SSL_ERROR_WANT_READ { - return Err(create_ssl_want_read_error(vm).upcast()); - } else if err == sys::SSL_ERROR_WANT_WRITE { - return Err(create_ssl_want_write_error(vm).upcast()); - } else { - return Err(new_ssl_error( - vm, - format!("SSL shutdown failed: error code {}", err), - )); - } - } else if ret == 0 { - // Sent close-notify, waiting for peer's - raise SSLWantReadError - return Err(create_ssl_want_read_error(vm).upcast()); - } - return Ok(None); - } - - // Socket mode: loop with select to wait for peer's close-notify - let socket_stream = stream.get_ref().expect("get_ref() failed for socket mode"); - let deadline = socket_stream.timeout_deadline(); - - // Track how many times we've seen ret == 0 (max 2 tries) + let _vm_guard = HandshakeVmGuard::new(vm, &zelf.connection, ssl_ptr); + let deadline = stream.get_ref().map(SocketStream::timeout_deadline); let mut zeros = 0; - loop { - // Shutting down sends close-notify and waits for the peer's, - // which a peer that has gone away never sends. `SSL_shutdown` - // is released around for the same reason. - let ret = vm.allow_threads(|| unsafe { sys::SSL_shutdown(ssl_ptr) }); - - // ret > 0: complete shutdown - if ret > 0 { - break; - } - - // ret == 0: sent our close-notify, need to receive peer's - if ret == 0 { - zeros += 1; - if zeros > 1 { - // Already tried twice, break out (legacy behavior) - break; + if zelf.shutdown_seen_zero.load() { + // Do not consume plaintext following the TLS close_notify. + unsafe { + sys::SSL_ctrl( + ssl_ptr, + sys::SSL_CTRL_SET_READ_AHEAD, + 0, + core::ptr::null_mut(), + ); } - // Wait briefly for peer's close_notify before retrying - match socket_stream.select(SslNeeds::Read, &deadline, vm)? { - SelectRet::TimedOut => { - return Err(socket::timeout_error_msg( - vm, - "The read operation timed out".to_string(), - ) - .upcast()); - } - SelectRet::Closed => { - return Err(socket_closed_error(vm)); - } - SelectRet::Nonblocking => { - // Non-blocking socket: return SSLWantReadError - return Err(create_ssl_want_read_error(vm).upcast()); - } - SelectRet::Ok => { - // Data available, continue to retry + } + let error = match zelf.finish_ssl_operation( + vm.allow_threads(|| stream.shutdown()), + ssl_ptr, + vm, + )? { + Ok(ssl::ShutdownResult::Received) => break, + Ok(ssl::ShutdownResult::Sent) => { + zeros += 1; + if zeros > 1 { + break; } + zelf.shutdown_seen_zero.store(true); + // Retry immediately: the peer's notification may already + // be buffered, even when the transport is not readable. + continue; } - continue; - } - - // ret < 0: error or would-block - let err = unsafe { sys::SSL_get_error(ssl_ptr, ret) }; - - let needs = if err == sys::SSL_ERROR_WANT_READ { - SslNeeds::Read - } else if err == sys::SSL_ERROR_WANT_WRITE { - SslNeeds::Write - } else { - // Real error - return Err(new_ssl_error( - vm, - format!("SSL shutdown failed: error code {}", err), - )); + Err(error) => error, }; - - // Wait on the socket - match socket_stream.select(needs, &deadline, vm)? { - SelectRet::TimedOut => { - let msg = if err == sys::SSL_ERROR_WANT_READ { - "The read operation timed out" - } else { - "The write operation timed out" - }; - return Err(socket::timeout_error_msg(vm, msg.to_string()).upcast()); - } - SelectRet::Closed => { - return Err(socket_closed_error(vm)); - } - SelectRet::Nonblocking => { - // Non-blocking socket, raise SSLWantReadError/SSLWantWriteError - if err == sys::SSL_ERROR_WANT_READ { - return Err(create_ssl_want_read_error(vm).upcast()); - } else { - return Err(create_ssl_want_write_error(vm).upcast()); + if let Some(socket) = stream.get_ref() { + let (needs, state) = socket.socket_needs( + &error, + deadline.as_ref().expect("socket deadline"), + vm, + )?; + match state { + SelectRet::TimedOut => { + let message = if error.code() == ssl::ErrorCode::WANT_READ { + "The read operation timed out" + } else { + "The write operation timed out" + }; + return Err(socket::timeout_error_msg(vm, message.to_owned()).upcast()); } - } - SelectRet::Ok => { - // Socket is ready, retry shutdown - continue; + SelectRet::Closed => return Err(socket_closed_error(vm)), + SelectRet::Ok if needs.is_some() => continue, + _ => {} } } + return Err(zelf.ssl_error(error, ssl_ptr, vm)); } - - // Return the underlying socket - Ok(Some(socket_stream.0.clone())) + Ok(stream.get_ref().map(|socket| socket.socket.clone())) } #[cfg(osslconf = "OPENSSL_NO_COMP")] @@ -2966,42 +4103,36 @@ mod _ssl { #[cfg(not(osslconf = "OPENSSL_NO_COMP"))] #[pymethod] fn compression(zelf: &Py) -> Option<&'static str> { - // Use thread-local SSL pointer during handshake to avoid deadlock - let ssl_ptr = get_ssl_ptr_for_context_change(&zelf.connection); - let comp_method = unsafe { sys::SSL_get_current_compression(ssl_ptr) }; - if comp_method.is_null() { - return None; - } - let typ = unsafe { sys::COMP_get_type(comp_method) }; - let nid = Nid::from_raw(typ); - if nid == Nid::UNDEF { - return None; - } - nid.short_name().ok() + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + let comp_method = unsafe { sys::SSL_get_current_compression(ssl_ptr) }; + if comp_method.is_null() { + return None; + } + let typ = unsafe { sys::COMP_get_type(comp_method) }; + let nid = Nid::from_raw(typ); + if nid == Nid::UNDEF { + return None; + } + nid.short_name().ok() + }) } + #[cfg(not(all(unix, not(target_os = "aix"))))] #[pymethod] fn do_handshake(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + zelf.check_eof(vm)?; let mut stream = zelf.connection.write(); let ssl_ptr = stream.ssl().as_ptr(); // Set up thread-local VM and SSL pointer for callbacks // This allows callbacks to access SSL without acquiring the connection lock - let _vm_guard = HandshakeVmGuard::new(vm, ssl_ptr); + let _vm_guard = HandshakeVmGuard::new(vm, &zelf.connection, ssl_ptr); // BIO mode: no timeout/select logic, just do handshake if stream.is_bio() { - let result = vm.allow_threads(|| stream.do_handshake()).map_err(|e| { - let exc = convert_ssl_error(vm, e); - // If it's a cert verification error, set verify info - if exc.class().is(PySSLCertVerificationError::class(&vm.ctx)) { - set_verify_error_info(&exc, ssl_ptr, vm); - } - exc - }); - // Clean up SNI ex_data after handshake (success or failure) - // SAFETY: ssl_ptr is valid for the lifetime of stream - unsafe { cleanup_sni_ex_data(ssl_ptr) }; + let result = zelf + .finish_ssl_operation(vm.allow_threads(|| stream.do_handshake()), ssl_ptr, vm)? + .map_err(|e| zelf.ssl_error(e, ssl_ptr, vm)); return result; } @@ -3017,11 +4148,12 @@ mod _ssl { // same reason. The connection lock stays held across it, which // is why it is a detaching lock: a thread reaching the same // socket gives up its interpreter rather than wait attached. - let err = match vm.allow_threads(|| stream.do_handshake()) { + let err = match zelf.finish_ssl_operation( + vm.allow_threads(|| stream.do_handshake()), + ssl_ptr, + vm, + )? { Ok(()) => { - // Clean up SNI ex_data after successful handshake - // SAFETY: ssl_ptr is valid for the lifetime of stream - unsafe { cleanup_sni_ex_data(ssl_ptr) }; return Ok(()); } Err(e) => e, @@ -3032,9 +4164,6 @@ mod _ssl { .socket_needs(&err, &timeout, vm)?; match state { SelectRet::TimedOut => { - // Clean up SNI ex_data before returning error - // SAFETY: ssl_ptr is valid for the lifetime of stream - unsafe { cleanup_sni_ex_data(ssl_ptr) }; return Err(socket::timeout_error_msg( vm, "The handshake operation timed out".to_owned(), @@ -3042,8 +4171,6 @@ mod _ssl { .upcast()); } SelectRet::Closed => { - // SAFETY: ssl_ptr is valid for the lifetime of stream - unsafe { cleanup_sni_ex_data(ssl_ptr) }; return Err(socket_closed_error(vm)); } SelectRet::Nonblocking => {} @@ -3055,29 +4182,25 @@ mod _ssl { } } } - let exc = convert_ssl_error(vm, err); - // If it's a cert verification error, set verify info - if exc.class().is(PySSLCertVerificationError::class(&vm.ctx)) { - set_verify_error_info(&exc, ssl_ptr, vm); - } - // Clean up SNI ex_data before returning error - // SAFETY: ssl_ptr is valid for the lifetime of stream - unsafe { cleanup_sni_ex_data(ssl_ptr) }; - return Err(exc); + return Err(zelf.ssl_error(err, ssl_ptr, vm)); } } + #[cfg(not(all(unix, not(target_os = "aix"))))] #[pymethod] fn write(zelf: &Py, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult { + zelf.check_eof(vm)?; let mut stream = zelf.connection.write(); + let ssl_ptr = stream.ssl().as_ptr(); + let _vm_guard = HandshakeVmGuard::new(vm, &zelf.connection, ssl_ptr); let data = data.borrow_buf(); let data = &*data; // BIO mode: no timeout/select logic if stream.is_bio() { - return vm - .allow_threads(|| stream.ssl_write(data)) - .map_err(|e| convert_ssl_error(vm, e)); + return zelf + .finish_ssl_operation(vm.allow_threads(|| stream.ssl_write(data)), ssl_ptr, vm)? + .map_err(|e| zelf.ssl_error(e, ssl_ptr, vm)); } // Socket mode: handle timeout and blocking @@ -3101,7 +4224,11 @@ mod _ssl { // Sending waits for the peer to make room, which it need not // ever do; `SSL_write_ex` is released around for the same // reason. - let err = match vm.allow_threads(|| stream.ssl_write(data)) { + let err = match zelf.finish_ssl_operation( + vm.allow_threads(|| stream.ssl_write(data)), + ssl_ptr, + vm, + )? { Ok(len) => return Ok(len), Err(e) => e, }; @@ -3127,29 +4254,36 @@ mod _ssl { } } } - return Err(convert_ssl_error(vm, err)); + return Err(zelf.ssl_error(err, ssl_ptr, vm)); } } #[pygetset] fn session(zelf: &Py, _vm: &VirtualMachine) -> PyResult> { - let stream = zelf.connection.read(); - unsafe { - // Use SSL_get1_session which returns an owned reference (ref count already incremented) - let session_ptr = SSL_get1_session(stream.ssl().as_ptr()); - if session_ptr.is_null() { - Ok(None) - } else { - Ok(Some(PySslSession { - session: session_ptr, - ctx: zelf.ctx.read().clone(), - })) + with_ssl_pointer(&zelf.connection, |ssl_ptr| { + unsafe { + // Use SSL_get1_session which returns an owned reference (ref count already incremented) + let session_ptr = SSL_get1_session(ssl_ptr); + if session_ptr.is_null() { + Ok(None) + } else { + Ok(Some(PySslSession { + session: session_ptr, + ctx: zelf.ctx.read().clone(), + })) + } } - } + }) } #[pygetset(setter)] - fn set_session(zelf: &Py, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn set_session( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value + .ok_or_else(|| vm.new_attribute_error("attribute 'session' cannot be deleted"))?; // Check if value is SSLSession type let session = value .downcast_ref::() @@ -3168,29 +4302,26 @@ mod _ssl { return Err(vm.new_value_error("Cannot set session for server-side SSLSocket.")); } - // Check if handshake is not finished - let stream = zelf.connection.read(); - unsafe { - if sys::SSL_is_init_finished(stream.ssl().as_ptr()) != 0 { - return Err(vm.new_value_error("Cannot set session after handshake.")); - } - - let ret = sys::SSL_set_session(stream.ssl().as_ptr(), session.session); - if ret == 0 { - return Err(convert_openssl_error(vm, ErrorStack::get())); + with_ssl_pointer_mut(&zelf.connection, |ssl_ptr| { + unsafe { + if sys::SSL_is_init_finished(ssl_ptr) != 0 { + return Err(vm.new_value_error("Cannot set session after handshake.")); + } + if sys::SSL_set_session(ssl_ptr, session.session) == 0 { + return Err(convert_openssl_error(vm, ErrorStack::get())); + } } - } - - Ok(()) + Ok(()) + }) } #[pygetset] fn session_reused(zelf: &Py) -> bool { - // Use thread-local SSL pointer during handshake to avoid deadlock - let ssl_ptr = get_ssl_ptr_for_context_change(&zelf.connection); - unsafe { sys::SSL_session_reused(ssl_ptr) != 0 } + with_ssl_pointer(&zelf.connection, |ssl_ptr| unsafe { + sys::SSL_session_reused(ssl_ptr) != 0 + }) } - + #[cfg(not(all(unix, not(target_os = "aix"))))] #[pymethod] fn read( zelf: &Py, @@ -3219,6 +4350,8 @@ mod _ssl { } }; + zelf.check_eof(vm)?; + // Special case: reading 0 bytes should return empty bytes immediately if read_len == 0 { return if buffer.is_present() { @@ -3229,6 +4362,8 @@ mod _ssl { } let mut stream = zelf.connection.write(); + let ssl_ptr = stream.ssl().as_ptr(); + let _vm_guard = HandshakeVmGuard::new(vm, &zelf.connection, ssl_ptr); // The read below answers when the peer writes, which may be never, // and reaching the caller's buffer takes a lock that every other // thread touching the same object waits on. Read aside and take @@ -3238,19 +4373,28 @@ mod _ssl { // BIO mode: no timeout/select logic let count = if stream.is_bio() { - match vm.allow_threads(|| stream.ssl_read(buf)) { + match zelf.finish_ssl_operation( + vm.allow_threads(|| stream.ssl_read(buf)), + ssl_ptr, + vm, + )? { Ok(count) => count, Err(e) => { - // Handle ZERO_RETURN (EOF) - raise SSLEOFError + // close_notify is an orderly TLS EOF. if e.code() == ssl::ErrorCode::ZERO_RETURN { - return Err(create_ssl_eof_error(vm).upcast()); + return if buffer.is_present() { + Ok(vm.ctx.new_int(0).into()) + } else { + Ok(vm.ctx.new_bytes(vec![]).into()) + }; } // If WANT_READ and the incoming BIO has EOF written, // this is an unexpected EOF (transport closed without TLS close_notify) if e.code() == ssl::ErrorCode::WANT_READ && stream.is_bio_eof() { + zelf.got_eof_error.store(true); return Err(create_ssl_eof_error(vm).upcast()); } - return Err(convert_ssl_error(vm, e)); + return Err(zelf.ssl_error(e, ssl_ptr, vm)); } } } else { @@ -3263,7 +4407,11 @@ mod _ssl { // This is the wait the whole method is shaped around: it // ends when the peer writes. `SSL_read_ex` is released // around for the same reason. - let err = match vm.allow_threads(|| stream.ssl_read(buf)) { + let err = match zelf.finish_ssl_operation( + vm.allow_threads(|| stream.ssl_read(buf)), + ssl_ptr, + vm, + )? { Ok(count) => break count, Err(e) => e, }; @@ -3294,7 +4442,7 @@ mod _ssl { } } } - return Err(convert_ssl_error(vm, err)); + return Err(zelf.ssl_error(err, ssl_ptr, vm)); } }; let ret = match &buffer { @@ -3399,11 +4547,49 @@ mod _ssl { unsafe impl Send for PySslMemoryBio {} unsafe impl Sync for PySslMemoryBio {} + #[pyfunction] + fn get_sigalgs(vm: &VirtualMachine) -> PyResult { + #[cfg(ossl340)] + unsafe { + let names = SSL_get1_builtin_sigalgs(core::ptr::null_mut()); + if names.is_null() { + return Err(vm.new_memory_error("failed to get signature algorithms")); + } + let names_text = CStr::from_ptr(names).to_string_lossy().into_owned(); + sys::CRYPTO_free(names.cast(), core::ptr::null(), 0); + Ok(vm.ctx.new_list( + names_text + .split(':') + .map(|name| vm.ctx.new_str(name).into()) + .collect(), + )) + } + #[cfg(not(ossl340))] + { + Err(vm.new_not_implemented_error( + "Getting signature algorithms requires OpenSSL 3.4 or later.", + )) + } + } + // OpenSSL functions not in openssl-sys + #[cfg(ossl320)] + unsafe extern "C" { + fn SSL_get0_group_name(ssl: *mut sys::SSL) -> *const core::ffi::c_char; + } + + #[cfg(ossl340)] + unsafe extern "C" { + fn SSL_get1_builtin_sigalgs(ctx: *mut core::ffi::c_void) -> *mut core::ffi::c_char; + } + unsafe extern "C" { // X509_check_ca returns 1 for CA certificates, 0 otherwise fn X509_check_ca(x: *const sys::X509) -> core::ffi::c_int; + fn X509_VERIFY_PARAM_get_hostflags( + param: *const sys::X509_VERIFY_PARAM, + ) -> core::ffi::c_uint; } unsafe extern "C" { @@ -3706,6 +4892,7 @@ mod _ssl { } buf.truncate(nbytes as usize); + buf.shrink_to_fit(); Ok(buf) } } @@ -3794,10 +4981,29 @@ mod _ssl { .upcast() } + fn system_error_errno(code: core::ffi::c_ulong) -> core::ffi::c_int { + // OpenSSL 3 stores errno below ERR_SYSTEM_FLAG, as specified by + // https://github.com/openssl/openssl/blob/openssl-3.5.7/include/openssl/err.h.in + // openssl-sys 0.9.117's ERR_GET_REASON returns ERR_LIB_SYS instead. + cfg_select! { + ossl300 => (code & sys::ERR_SYSTEM_MASK) as core::ffi::c_int, + _ => sys::ERR_GET_REASON(code), + } + } + #[track_caller] pub(crate) fn convert_openssl_error( vm: &VirtualMachine, err: ErrorStack, + ) -> PyBaseExceptionRef { + convert_openssl_error_with_errno(vm, err, None) + } + + #[track_caller] + fn convert_openssl_error_with_errno( + vm: &VirtualMachine, + err: ErrorStack, + operation_errno: Option, ) -> PyBaseExceptionRef { match err.errors().last() { Some(e) => { @@ -3806,7 +5012,9 @@ mod _ssl { if lib == sys::ERR_LIB_SYS { // A system error is being reported; reason is set to errno - let reason = sys::ERR_GET_REASON(e.code()); + let reason = system_error_errno(e.code()); + let message = rustpython_host_env::errno::strerror_string(reason) + .unwrap_or_else(|| format!("System error {reason}")); // errno 2 = ENOENT = FileNotFoundError let exc_type = if reason == 2 { @@ -3814,7 +5022,9 @@ mod _ssl { } else { vm.ctx.exceptions.os_error.to_owned() }; - return vm.new_os_subtype_error(exc_type, Some(reason), "").upcast(); + return vm + .new_os_subtype_error(exc_type, Some(reason), message) + .upcast(); } let caller = std::panic::Location::caller(); @@ -3855,16 +5065,17 @@ mod _ssl { PySSLError::class(&vm.ctx).to_owned() }; - // Build message + let description = e.reason().unwrap_or("unknown error"); let msg = if let Some(lib_str) = lib_name { - format!("[{lib_str}] {errstr} ({file}:{line})") + format!("[{lib_str}: {errstr}] {description} ({file}:{line})") } else { - format!("{errstr} ({file}:{line})") + format!("{description} ({file}:{line})") }; // Create exception instance let reason = sys::ERR_GET_REASON(e.code()); - let exc = vm.new_os_subtype_error(cls, Some(reason), msg); + let exc = + vm.new_os_subtype_error(cls, Some(operation_errno.unwrap_or(reason)), msg); let exc_obj: PyObjectRef = exc.upcast::().into(); // Set reason attribute (always set, even if just the error string) @@ -3900,37 +5111,85 @@ mod _ssl { } } - // Helper function to set verify_code and verify_message on SSLCertVerificationError - fn set_verify_error_info( - exc: &Py, - ssl_ptr: *const sys::SSL, - vm: &VirtualMachine, - ) { - // Get verify result - let verify_code = unsafe { sys::SSL_get_verify_result(ssl_ptr) }; - let verify_code_obj = vm.ctx.new_int(verify_code); - - // Get verify message - let verify_message = unsafe { - let verify_str = sys::X509_verify_cert_error_string(verify_code); - if verify_str.is_null() { - vm.ctx.none() - } else { - let c_str = core::ffi::CStr::from_ptr(verify_str); - vm.ctx.new_str(c_str.to_string_lossy()).into() + struct VerifyErrorInfo { + code: core::ffi::c_long, + message: Option, + } + + // Only owned metadata may outlive the native SSL guard. In particular, + // exception normalization must never consult a later operation's SSL state. + struct SslErrorSnapshot { + error: ssl::Error, + verify: Option, + } + + impl SslErrorSnapshot { + fn capture(error: ssl::Error, ssl_ptr: *const sys::SSL) -> Self { + let is_cert_verify = + matches!(error.code(), ssl::ErrorCode::SSL | ssl::ErrorCode::SYSCALL) + && error.ssl_error().is_some_and(|stack| { + stack.errors().last().is_some_and(|error| { + sys::ERR_GET_LIB(error.code()) == 20 + && sys::ERR_GET_REASON(error.code()) == 134 + }) + }); + let verify = is_cert_verify.then(|| { + // The caller holds this connection's native guard throughout + // capture. Neither the pointer nor borrowed C data is retained. + let code = unsafe { sys::SSL_get_verify_result(ssl_ptr) }; + let message = unsafe { + let pointer = sys::X509_verify_cert_error_string(code); + (!pointer.is_null()).then(|| { + core::ffi::CStr::from_ptr(pointer) + .to_string_lossy() + .into_owned() + }) + }; + VerifyErrorInfo { code, message } + }); + Self { error, verify } + } + + fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + let exception = convert_ssl_error(vm, self.error); + if let Some(verify) = self.verify { + let _ = + exception + .as_object() + .set_attr("verify_code", vm.ctx.new_int(verify.code), vm); + let message = verify + .message + .map_or_else(|| vm.ctx.none(), |message| vm.ctx.new_str(message).into()); + let _ = exception + .as_object() + .set_attr("verify_message", message, vm); } - }; + exception + } + } - let exc_obj = exc.as_object(); - let _ = exc_obj.set_attr("verify_code", verify_code_obj, vm); - let _ = exc_obj.set_attr("verify_message", verify_message, vm); + fn is_unexpected_eof(error: &ssl::Error) -> bool { + (error.code() == ssl::ErrorCode::SYSCALL + && error.io_error().is_none() + && error.ssl_error().is_none()) + || error.ssl_error().is_some_and(|stack| { + stack.errors().last().is_some_and(|error| { + error.library_code() == ERR_LIB_SSL + && error.reason_code() == SSL_R_UNEXPECTED_EOF_WHILE_READING + }) + }) } + #[track_caller] fn convert_ssl_error( vm: &VirtualMachine, e: impl std::borrow::Borrow, ) -> PyBaseExceptionRef { let e = e.borrow(); + if is_unexpected_eof(e) { + return create_ssl_eof_error(vm).upcast(); + } + let (cls, msg) = match e.code() { ssl::ErrorCode::WANT_READ => { return create_ssl_want_read_error(vm).upcast(); @@ -3940,26 +5199,24 @@ mod _ssl { } ssl::ErrorCode::SYSCALL => match e.io_error() { Some(io_err) => return io_err.to_pyexception(vm), - // When no I/O error and OpenSSL error queue is empty, - // this is an EOF in violation of protocol -> SSLEOFError None => { + if let Some(stack) = e.ssl_error() { + return convert_openssl_error_with_errno( + vm, + stack.clone(), + Some(sys::SSL_ERROR_SYSCALL), + ); + } return create_ssl_eof_error(vm).upcast(); } }, ssl::ErrorCode::SSL => { - // Check for OpenSSL 3.0 SSL_R_UNEXPECTED_EOF_WHILE_READING if let Some(ssl_err) = e.ssl_error() { - // In OpenSSL 3.0+, unexpected EOF is reported as SSL_ERROR_SSL - // with this specific reason code instead of SSL_ERROR_SYSCALL - unsafe { - let err_code = sys::ERR_peek_last_error(); - let reason = sys::ERR_GET_REASON(err_code); - let lib = sys::ERR_GET_LIB(err_code); - if lib == ERR_LIB_SSL && reason == SSL_R_UNEXPECTED_EOF_WHILE_READING { - return create_ssl_eof_error(vm).upcast(); - } - } - return convert_openssl_error(vm, ssl_err.clone()); + return convert_openssl_error_with_errno( + vm, + ssl_err.clone(), + Some(sys::SSL_ERROR_SSL), + ); } ( PySSLError::class(&vm.ctx).to_owned(), @@ -4037,21 +5294,70 @@ mod _ssl { } } + #[cfg(all(unix, not(target_os = "aix")))] + impl SocketStream { + fn finish_transport(&mut self, result: std::io::Result) -> std::io::Result { + match result { + Ok(count) => { + self.progress = self.progress.wrapping_add(count as u64); + Ok(count) + } + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => { + // openssl's custom BIO treats only WouldBlock/NotConnected + // as retryable. Passing EINTR through would become a fatal + // SSL_ERROR_SYSCALL. Check Python signals after settlement. + self.interrupted = true; + Err(std::io::Error::from(std::io::ErrorKind::WouldBlock)) + } + Err(error) => Err(error), + } + } + } + impl Read for SocketStream { fn read(&mut self, buf: &mut [u8]) -> std::io::Result { - let mut socket: &PySocket = &self.0; - socket.read(buf) + #[cfg(all(unix, not(target_os = "aix")))] + { + let result = { + let socket = self.socket.sock_for_ssl_identity(&self.identity)?; + // recv initializes only the reported prefix; this caller's + // buffer was already initialized and is valid throughout. + let buffer = unsafe { + core::slice::from_raw_parts_mut( + buf.as_mut_ptr().cast::>(), + buf.len(), + ) + }; + socket.recv_with_flags(buffer, libc::MSG_DONTWAIT) + }; + self.finish_transport(result) + } + #[cfg(not(all(unix, not(target_os = "aix"))))] + { + let mut socket: &PySocket = &self.socket; + socket.read(buf) + } } } impl Write for SocketStream { fn write(&mut self, buf: &[u8]) -> std::io::Result { - let mut socket: &PySocket = &self.0; - socket.write(buf) + #[cfg(all(unix, not(target_os = "aix")))] + { + let result = { + let socket = self.socket.sock_for_ssl_identity(&self.identity)?; + socket.send_with_flags(buf, libc::MSG_DONTWAIT) + }; + self.finish_transport(result) + } + #[cfg(not(all(unix, not(target_os = "aix"))))] + { + let mut socket: &PySocket = &self.socket; + socket.write(buf) + } } fn flush(&mut self) -> std::io::Result<()> { - let mut socket: &PySocket = &self.0; - socket.flush() + Ok(()) } } @@ -4116,6 +5422,21 @@ mod _ssl { Ok(()) } } + #[cfg(test)] + mod error_tests { + use super::{sys, system_error_errno}; + + #[test] + fn system_errors_preserve_errno() { + for errno in [libc::ENOENT, libc::EPIPE, libc::ECONNRESET] { + let code = cfg_select! { + ossl300 => sys::ERR_SYSTEM_FLAG | errno as core::ffi::c_ulong, + _ => sys::ERR_PACK(sys::ERR_LIB_SYS, 0, errno), + }; + assert_eq!(system_error_errno(code), errno); + } + } + } } #[allow(non_upper_case_globals)] diff --git a/crates/stdlib/src/openssl/cert.rs b/crates/stdlib/src/openssl/cert.rs index 55fb9dff973..5ab8e2a8eef 100644 --- a/crates/stdlib/src/openssl/cert.rs +++ b/crates/stdlib/src/openssl/cert.rs @@ -10,7 +10,7 @@ pub(crate) mod ssl_cert { Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, class_or_notimplemented, convert::{ToPyException, ToPyObject}, - function::{FsPath, OptionalArg, PyComparisonValue}, + function::{FsPath, PyComparisonValue}, types::{Comparable, Hashable, PyComparisonOp, Representable}, }, }; @@ -67,6 +67,12 @@ pub(crate) mod ssl_cert { } } + #[derive(FromArgs)] + struct CertificatePublicBytesArgs { + #[pyarg(any, default = ENCODING_PEM, py_default = "Encoding.PEM")] + format: i32, + } + #[pyclass( flags(IMMUTABLETYPE, DISALLOW_INSTANTIATION), with(Comparable, Hashable, Representable) @@ -75,12 +81,10 @@ pub(crate) mod ssl_cert { #[pymethod] fn public_bytes( zelf: &Py, - format: OptionalArg, + args: CertificatePublicBytesArgs, vm: &VirtualMachine, ) -> PyResult { - let format = format.unwrap_or(ENCODING_PEM); - - match format { + match args.format { ENCODING_DER => { // DER encoding let der = zelf diff --git a/crates/stdlib/src/openssl/distrusted.rs b/crates/stdlib/src/openssl/distrusted.rs new file mode 100644 index 00000000000..f40aaabbb47 --- /dev/null +++ b/crates/stdlib/src/openssl/distrusted.rs @@ -0,0 +1,102 @@ +// cspell:ignore SPKIS +//! CPython 3.15.2 Modules/_ssl/distrusted_spki.h, gh-160040. +//! Match compromised keys, including cross-signed certificates, only on the +//! chain selected by OpenSSL. Do not override an existing verification failure. + +use foreign_types_shared::ForeignTypeRef; +use openssl::x509::{X509StoreContextRef, X509VerifyResult}; + +const DISTRUSTED_SPKIS: [[u8; 32]; 8] = [ + [ + 0x43, 0xbf, 0xfa, 0x19, 0xd6, 0xef, 0x65, 0x14, 0x51, 0xf6, 0x84, 0x1e, 0x01, 0x99, 0x31, + 0xe9, 0x6f, 0x6f, 0x2e, 0xae, 0xff, 0x28, 0xab, 0x4b, 0x6f, 0x1c, 0xe4, 0x57, 0x6d, 0xe2, + 0x71, 0x7b, + ], + [ + 0x49, 0xdd, 0x35, 0x3d, 0xc2, 0xb9, 0x19, 0xa3, 0x77, 0x06, 0x45, 0x11, 0x7d, 0x0e, 0x60, + 0xc1, 0x61, 0x15, 0xe7, 0xd1, 0xbc, 0x25, 0x9e, 0xef, 0xe7, 0x34, 0xb0, 0x0e, 0xa4, 0x34, + 0xfe, 0x5f, + ], + [ + 0x5c, 0x06, 0x60, 0xa2, 0xb1, 0x64, 0x91, 0x0d, 0x8f, 0xf5, 0x89, 0xc1, 0x8e, 0x14, 0x55, + 0x2e, 0x9e, 0x0e, 0xc2, 0x37, 0xdc, 0xef, 0xe2, 0xcb, 0x73, 0x6d, 0x41, 0xa4, 0x81, 0x1f, + 0x81, 0xa0, + ], + [ + 0x63, 0xec, 0xef, 0xee, 0x43, 0x1d, 0x49, 0x52, 0x3b, 0xc1, 0x13, 0x6c, 0x4e, 0x72, 0xd0, + 0x20, 0x6a, 0x47, 0x70, 0x86, 0xca, 0xf6, 0x06, 0xcd, 0x5c, 0xf0, 0x25, 0x68, 0x6c, 0x10, + 0x9c, 0xf8, + ], + [ + 0x92, 0xc0, 0x63, 0xd6, 0x7e, 0x8f, 0x14, 0xdb, 0x71, 0xd2, 0x88, 0xe1, 0x12, 0x66, 0xff, + 0xda, 0xf6, 0x9c, 0xbf, 0x11, 0x5f, 0x7b, 0xab, 0x14, 0xf3, 0xbc, 0x2f, 0x68, 0xd2, 0x5e, + 0x0e, 0x30, + ], + [ + 0xe0, 0x25, 0x4c, 0x7f, 0xcd, 0xc2, 0x65, 0xe2, 0xf0, 0xf8, 0xa4, 0x28, 0xda, 0xbb, 0x75, + 0xab, 0x4a, 0xe0, 0x39, 0xb4, 0x87, 0x2d, 0x62, 0xf5, 0xee, 0x57, 0xf0, 0x87, 0x7d, 0x5a, + 0x8a, 0x41, + ], + [ + 0xeb, 0xed, 0x64, 0x75, 0xc2, 0xc2, 0xd8, 0x0f, 0xcb, 0x19, 0x9f, 0x3f, 0xe8, 0xdd, 0x6e, + 0x6b, 0x3c, 0xe6, 0x0b, 0x77, 0xeb, 0x15, 0xd4, 0xe4, 0x2c, 0x3d, 0xec, 0x0c, 0x6f, 0x5b, + 0x51, 0x05, + ], + [ + 0xec, 0x4f, 0xfa, 0x1a, 0xd0, 0xac, 0x88, 0x08, 0x13, 0x14, 0xb7, 0xaa, 0xff, 0xef, 0x6a, + 0x91, 0xf9, 0x7c, 0xd5, 0x72, 0x91, 0xbb, 0x5b, 0xa6, 0x86, 0xc5, 0x41, 0x5f, 0x5e, 0xb4, + 0xf6, 0xb6, + ], +]; + +pub(super) fn verify(preverified: bool, context: &mut X509StoreContextRef) -> bool { + if !preverified { + return false; + } + let Some(cert) = context.current_cert() else { + return true; + }; + let result = subject_public_key_info(cert).and_then(|spki| { + openssl::hash::hash(openssl::hash::MessageDigest::sha256(), &spki) + .ok() + .filter(|digest| digest.len() == 32) + }); + let error = match result { + Some(digest) + if DISTRUSTED_SPKIS + .iter() + .any(|key| key.as_slice() == digest.as_ref()) => + { + openssl_sys::X509_V_ERR_CERT_REJECTED + } + Some(_) => return true, + None => openssl_sys::X509_V_ERR_UNSPECIFIED, + }; + // Both values are public X509 verification result constants. + context.set_error(unsafe { X509VerifyResult::from_raw(error) }); + false +} + +// Preserve the certificate's exact SPKI encoding. Re-encoding an EVP_PKEY can +// normalize its algorithm parameters and therefore change the fingerprint. +fn subject_public_key_info(cert: &openssl::x509::X509Ref) -> Option> { + unsafe { + let spki = X509_get_X509_PUBKEY(cert.as_ptr()); + if spki.is_null() { + return None; + } + let length = i2d_X509_PUBKEY(spki, core::ptr::null_mut()); + if length <= 0 { + return None; + } + let mut encoded = vec![0; length as usize]; + let mut output = encoded.as_mut_ptr(); + let written = i2d_X509_PUBKEY(spki, &mut output); + (written == length).then_some(encoded) + } +} + +unsafe extern "C" { + fn X509_get_X509_PUBKEY(cert: *const openssl_sys::X509) -> *mut core::ffi::c_void; + fn i2d_X509_PUBKEY(key: *const core::ffi::c_void, output: *mut *mut u8) -> core::ffi::c_int; +} diff --git a/crates/stdlib/src/openssl/driver.rs b/crates/stdlib/src/openssl/driver.rs new file mode 100644 index 00000000000..b1ff3a4f757 --- /dev/null +++ b/crates/stdlib/src/openssl/driver.rs @@ -0,0 +1,264 @@ +//! Ownership rules for nonblocking OpenSSL retries. +//! +//! In particular, SSL_write returning WANT_WRITE forbids *any* other I/O on +//! that SSL until the same write is retried. Its buffer must survive Python +//! timeout, signal and nonblocking returns as well as ordinary OS waits. +use alloc::sync::Arc; +use core::sync::atomic::{AtomicBool, Ordering}; + +#[derive(Clone, Debug)] +pub(super) struct WriteOwner(Arc); + +impl WriteOwner { + pub(super) fn new() -> Self { + Self(Arc::new(AtomicBool::new(true))) + } + + pub(super) fn release(&self) { + self.0.store(false, Ordering::Release); + } + + fn is_active(&self) -> bool { + self.0.load(Ordering::Acquire) + } + + fn is(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Needs { + Read, + Write, +} + +#[derive(Debug)] +struct PendingWrite { + bytes: Box<[u8]>, + owner: WriteOwner, + needs: Option, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum Permit { + Ready, + Wait, + RetryOriginalWrite, + InvalidRetry, +} + +#[derive(Default, Debug)] +pub(super) struct Driver { + pending: Option, + pub(super) terminal: bool, +} + +impl Driver { + pub(super) fn other_io(&self) -> Permit { + match &self.pending { + Some(pending) if pending.needs == Some(Needs::Write) => { + if pending.owner.is_active() { + Permit::Wait + } else { + Permit::RetryOriginalWrite + } + } + _ => Permit::Ready, + } + } + + pub(super) fn write( + &mut self, + owner: &WriteOwner, + bytes: &mut Option>, + queued: &mut bool, + ) -> Permit { + // An invocation can fail before entering native SSL. There is no + // continuation in that case, so its abandoned buffer is disposable. + if self + .pending + .as_ref() + .is_some_and(|pending| pending.needs.is_none() && !pending.owner.is_active()) + { + self.pending = None; + } + if let Some(pending) = &mut self.pending { + if pending.owner.is_active() { + if pending.owner.is(owner) { + return Permit::Ready; + } + *queued = true; + return Permit::Wait; + } + // A write already queued behind another call is a distinct write, + // even when its contents happen to match the abandoned operation. + if *queued || bytes.as_deref() != Some(pending.bytes.as_ref()) { + return Permit::InvalidRetry; + } + pending.owner = owner.clone(); + // Retain the original allocation, not the new invocation's copy. + *bytes = None; + return Permit::Ready; + } + self.pending = Some(PendingWrite { + bytes: bytes.take().expect("new write owns its buffer"), + owner: owner.clone(), + needs: None, + }); + Permit::Ready + } + + pub(super) fn bytes(&self, owner: &WriteOwner) -> &[u8] { + let pending = self.pending.as_ref().expect("active write"); + assert!(pending.owner.is(owner) && pending.owner.is_active()); + &pending.bytes + } + + pub(super) fn settle_write(&mut self, owner: &WriteOwner, needs: Option) -> bool { + let pending = self.pending.as_mut().expect("active write"); + assert!(pending.owner.is(owner) && pending.owner.is_active()); + if let Some(needs) = needs { + pending.needs = Some(needs); + } else { + self.pending = None; + } + needs.is_some() + } + + pub(super) fn fail(&mut self) { + self.terminal = true; + self.pending = None; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn payload() -> Box<[u8]> { + Box::from(&b"stable bytes"[..]) + } + + #[test] + fn want_write_is_exclusive_and_keeps_original_allocation() { + let mut driver = Driver::default(); + let owner = WriteOwner::new(); + let mut bytes = Some(payload()); + let ptr = bytes.as_ref().unwrap().as_ptr(); + assert_eq!(driver.write(&owner, &mut bytes, &mut false), Permit::Ready); + driver.settle_write(&owner, Some(Needs::Write)); + assert_eq!(driver.other_io(), Permit::Wait); + assert_eq!(driver.bytes(&owner).as_ptr(), ptr); + owner.release(); + assert_eq!(driver.other_io(), Permit::RetryOriginalWrite); + let next = WriteOwner::new(); + assert_eq!( + driver.write(&next, &mut Some(payload()), &mut false), + Permit::Ready + ); + assert_eq!(driver.bytes(&next).as_ptr(), ptr); + assert!( + !driver.settle_write(&next, None), + "completion disarms cleanup" + ); + assert_eq!(driver.other_io(), Permit::Ready); + } + + #[test] + fn want_read_allows_progress_but_not_a_different_write() { + let mut driver = Driver::default(); + let owner = WriteOwner::new(); + driver.write(&owner, &mut Some(payload()), &mut false); + driver.settle_write(&owner, Some(Needs::Read)); + assert_eq!(driver.other_io(), Permit::Ready); + owner.release(); + assert_eq!(driver.other_io(), Permit::Ready); + let other = WriteOwner::new(); + let mut different = Some(Box::from(&b"different"[..])); + assert_eq!( + driver.write(&other, &mut different, &mut false), + Permit::InvalidRetry + ); + assert_eq!( + driver.write(&other, &mut Some(payload()), &mut false), + Permit::Ready + ); + assert_eq!(driver.bytes(&other), b"stable bytes"); + } + + #[test] + fn concurrent_equal_writes_are_distinct() { + let mut driver = Driver::default(); + let first = WriteOwner::new(); + let second = WriteOwner::new(); + driver.write(&first, &mut Some(payload()), &mut false); + driver.settle_write(&first, Some(Needs::Write)); + let mut bytes = Some(payload()); + let ptr = bytes.as_ref().unwrap().as_ptr(); + let mut queued = false; + assert_eq!(driver.write(&second, &mut bytes, &mut queued), Permit::Wait); + driver.settle_write(&first, None); + assert_eq!( + driver.write(&second, &mut bytes, &mut queued), + Permit::Ready + ); + assert_eq!(driver.bytes(&second).as_ptr(), ptr); + } + + #[test] + fn queued_writer_cannot_acknowledge_an_abandoned_write() { + let mut driver = Driver::default(); + let first = WriteOwner::new(); + let second = WriteOwner::new(); + driver.write(&first, &mut Some(payload()), &mut false); + driver.settle_write(&first, Some(Needs::Read)); + let mut bytes = Some(payload()); + let mut queued = false; + assert_eq!(driver.write(&second, &mut bytes, &mut queued), Permit::Wait); + first.release(); + assert_eq!( + driver.write(&second, &mut bytes, &mut queued), + Permit::InvalidRetry + ); + assert!(driver.pending.is_some()); + } + + #[test] + fn stale_release_cannot_orphan_an_adopted_writer() { + let mut driver = Driver::default(); + let first = WriteOwner::new(); + driver.write(&first, &mut Some(payload()), &mut false); + assert!(driver.settle_write(&first, Some(Needs::Write))); + first.release(); + let next = WriteOwner::new(); + assert_eq!( + driver.write(&next, &mut Some(payload()), &mut false), + Permit::Ready + ); + first.release(); + assert_eq!(driver.other_io(), Permit::Wait); + assert_eq!(driver.bytes(&next), b"stable bytes"); + assert!(!driver.settle_write(&next, None)); + } + + #[test] + fn release_before_attempt_and_terminal_error_leave_no_retry() { + let mut driver = Driver::default(); + let owner = WriteOwner::new(); + driver.write(&owner, &mut Some(payload()), &mut false); + owner.release(); + let owner = WriteOwner::new(); + let mut different = Some(Box::from(&b"new operation"[..])); + assert_eq!( + driver.write(&owner, &mut different, &mut false), + Permit::Ready + ); + assert_eq!(driver.bytes(&owner), b"new operation"); + driver.settle_write(&owner, Some(Needs::Write)); + driver.fail(); + assert!(driver.terminal); + owner.release(); + assert!(driver.pending.is_none()); + } +} diff --git a/crates/stdlib/src/openssl/waiter.rs b/crates/stdlib/src/openssl/waiter.rs new file mode 100644 index 00000000000..fa58e33e2bf --- /dev/null +++ b/crates/stdlib/src/openssl/waiter.rs @@ -0,0 +1,285 @@ +use alloc::sync::{Arc, Weak}; +use rustpython_host_env::{ + io as host_io, + select::{self, POLLIN, POLLNVAL, POLLOUT, PollFd}, +}; +use std::{ + io, + os::fd::{AsFd, AsRawFd, OwnedFd, RawFd}, + time::Instant, +}; + +/// A persistent, native-only notification for one blocked SSL operation. +#[derive(Debug)] +pub(super) struct ProgressWaiter { + read_fd: OwnedFd, + write_fd: OwnedFd, +} + +impl ProgressWaiter { + pub(super) fn new() -> io::Result { + let (read_fd, write_fd) = wake_pipe()?; + Ok(Self { read_fd, write_fd }) + } + + pub(super) fn notify(&self) { + loop { + match host_io::write_once(self.write_fd.as_fd().into(), &[1]) { + Ok(_) => return, + Err(error) if error.kind() == io::ErrorKind::Interrupted => continue, + // A full pipe already carries a persistent notification. + Err(error) if error.kind() == io::ErrorKind::WouldBlock => return, + // Both endpoints stay owned for this entire call, so neither + // EBADF nor EPIPE is possible without external fd corruption. + Err(_) => return, + } + } + } + + /// Re-arm under the connection guard, before the final identity check and + /// close-observer subscription. Draining after subscribing can lose close. + pub(super) fn drain(&self) -> io::Result<()> { + let mut buffer = [0; 256]; + loop { + match host_io::read_once(self.read_fd.as_fd().into(), &mut buffer) { + Ok(0) => { + return Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "SSL progress notification pipe closed", + )); + } + Ok(_) => {} + Err(error) if error.kind() == io::ErrorKind::WouldBlock => return Ok(()), + // In particular, return EINTR so the caller can check signals. + Err(error) => return Err(error), + } + } + } + + /// Wait without a connection or socket guard. A missing socket means that + /// write ownership permits only progress notifications to resume this call. + /// Returns true on timeout; readiness never drains the notification pipe. + pub(super) fn wait( + &self, + socket_fd: Option, + write: bool, + deadline: Option, + ) -> io::Result { + if socket_fd.is_some_and(|fd| fd < 0) { + return Err(io::Error::from_raw_os_error(libc::EBADF)); + } + let mut fds = [ + PollFd { + fd: self.read_fd.as_raw_fd(), + events: POLLIN, + revents: 0, + }, + PollFd { + // poll ignores a negative fd when only progress is allowed. + fd: socket_fd.unwrap_or(-1), + // TLS consumes normal stream data, never MSG_OOB. Watching + // POLLPRI could spin on urgent data that this BIO cannot read. + events: if write { POLLOUT } else { POLLIN }, + revents: 0, + }, + ]; + loop { + let (timeout, capped) = match deadline { + None => (-1, false), + Some(deadline) => { + let remaining = deadline.saturating_duration_since(Instant::now()); + match select::duration_as_millis_ceiling(remaining) { + Some(timeout) => (timeout, false), + None => (i32::MAX, true), + } + } + }; + // Even an expired deadline gets a zero-time poll, as in wait_fd. + // EINTR is deliberately propagated for Python signal checking. + match select::poll_fds(&mut fds, timeout)? { + 0 if capped => {} + 0 => return Ok(true), + _ if fds.iter().any(|fd| fd.revents & POLLNVAL != 0) => { + return Err(io::Error::from_raw_os_error(libc::EBADF)); + } + _ => return Ok(false), + } + } + } +} + +impl crate::socket::SocketCloseObserver for ProgressWaiter { + fn socket_closed(&self) { + self.notify(); + } +} + +fn wake_pipe() -> io::Result<(OwnedFd, OwnedFd)> { + cfg_select! { + any( + target_os = "dragonfly", + target_os = "freebsd", + target_os = "linux", + target_os = "android", + target_os = "netbsd", + target_os = "openbsd" + ) => { + rustpython_host_env::posix::pipe2(libc::O_CLOEXEC | libc::O_NONBLOCK) + } + target_os = "redox" => { + use std::os::fd::FromRawFd; + + // Redox provides pipe2, but the host helper excludes this target. + let mut fds = [-1; 2]; + // SAFETY: fds has storage for the two descriptors pipe2 writes. + if unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC | libc::O_NONBLOCK) } < 0 { + return Err(io::Error::last_os_error()); + } + // SAFETY: successful pipe2 transfers ownership of two new fds. + Ok(unsafe { (OwnedFd::from_raw_fd(fds[0]), OwnedFd::from_raw_fd(fds[1])) }) + } + _ => { + // The host helper sets CLOEXEC and owns both fds immediately, so + // any subsequent fcntl failure also closes both endpoints. + let (read_fd, write_fd) = rustpython_host_env::posix::pipe()?; + rustpython_host_env::fcntl::set_blocking(read_fd.as_fd(), false)?; + rustpython_host_env::fcntl::set_blocking(write_fd.as_fd(), false)?; + Ok((read_fd, write_fd)) + } + } +} + +/// Implementations are native-only and must not reenter the registry. +/// Production uses only ProgressWaiter's nonblocking pipe notification. +pub(super) trait ProgressNotify { + fn notify(&self); +} + +impl ProgressNotify for ProgressWaiter { + fn notify(&self) { + self.notify(); + } +} + +struct Registrations { + generation: u64, + waiters: Vec>, +} + +/// Ownership can be abandoned without acquiring the native SSL lock. Compare +/// generations when registering so that abandonment between predicate-check +/// and registration cannot strand a waiter. +pub(super) struct ProgressRegistry { + state: std::sync::Mutex>, +} + +impl Default for ProgressRegistry { + fn default() -> Self { + Self { + state: std::sync::Mutex::new(Registrations { + generation: 0, + waiters: Vec::new(), + }), + } + } +} + +impl ProgressRegistry { + pub(super) fn generation(&self) -> u64 { + self.state.lock().unwrap().generation + } + + pub(super) fn register(&self, waiter: &Arc, observed: u64) { + let mut state = self.state.lock().unwrap(); + let weak = Arc::downgrade(waiter); + state.waiters.retain(|waiter| waiter.strong_count() != 0); + if !state + .waiters + .iter() + .any(|registered| registered.ptr_eq(&weak)) + { + state.waiters.push(weak); + } + // Comparison and queuing share the notify mutex. A concurrent release + // either changed this generation or will find this registered waiter. + if state.generation != observed { + waiter.notify(); + } + } + + pub(super) fn unregister(&self, waiter: &Arc) { + let weak = Arc::downgrade(waiter); + self.state + .lock() + .unwrap() + .waiters + .retain(|registered| !registered.ptr_eq(&weak)); + } + + pub(super) fn notify(&self) { + let mut state = self.state.lock().unwrap(); + state.generation = state.generation.wrapping_add(1); + state.waiters.retain(|waiter| { + if let Some(waiter) = waiter.upgrade() { + waiter.notify(); + true + } else { + false + } + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use core::sync::atomic::{AtomicUsize, Ordering}; + + #[derive(Default)] + struct Counter(AtomicUsize); + + impl ProgressNotify for Counter { + fn notify(&self) { + self.0.fetch_add(1, Ordering::Relaxed); + } + } + + #[test] + fn release_before_registration_is_not_lost() { + let registry = ProgressRegistry::default(); + let observed = registry.generation(); + let waiter = Arc::new(Counter::default()); + registry.notify(); + registry.register(&waiter, observed); + assert_eq!(waiter.0.load(Ordering::Relaxed), 1); + } + + #[test] + fn release_after_registration_notifies_and_unregister_removes_it() { + let registry = ProgressRegistry::default(); + let waiter = Arc::new(Counter::default()); + registry.register(&waiter, registry.generation()); + assert_eq!(waiter.0.load(Ordering::Relaxed), 0); + registry.notify(); + assert_eq!(waiter.0.load(Ordering::Relaxed), 1); + registry.unregister(&waiter); + registry.notify(); + assert_eq!(waiter.0.load(Ordering::Relaxed), 1); + } + + #[test] + fn unchanged_retry_does_not_self_wake_or_duplicate_registration() { + let registry = ProgressRegistry::default(); + let waiter = Arc::new(Counter::default()); + for _ in 0..10 { + registry.register(&waiter, registry.generation()); + } + assert_eq!(waiter.0.load(Ordering::Relaxed), 0); + assert_eq!(registry.state.lock().unwrap().waiters.len(), 1); + registry.notify(); + assert_eq!(waiter.0.load(Ordering::Relaxed), 1); + let fresh = registry.generation(); + registry.register(&waiter, fresh); + assert_eq!(waiter.0.load(Ordering::Relaxed), 1); + } +} diff --git a/crates/stdlib/src/overlapped.rs b/crates/stdlib/src/overlapped.rs index fad4271ed48..11413a37693 100644 --- a/crates/stdlib/src/overlapped.rs +++ b/crates/stdlib/src/overlapped.rs @@ -10,7 +10,7 @@ mod _overlapped { use crate::vm::{ AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, builtins::{ - PyBaseExceptionRef, PyBytesRef, PyModule, PyStrRef, PyTuple, PyTupleRef, PyType, + PyBaseExceptionRef, PyBytesRef, PyInt, PyModule, PyStrRef, PyTuple, PyTupleRef, PyType, }, common::lock::PyMutex, convert::{ToPyException, ToPyObject}, @@ -24,6 +24,30 @@ mod _overlapped { windows::ToWideString, }; + #[derive(FromArgs)] + struct ReceiveFlags { + #[pyarg(positional, default)] + flags: u32, + } + + #[derive(FromArgs)] + struct RegisterWaitArgs { + #[pyarg(positional, name = "Object")] + object: isize, + #[pyarg(positional, name = "CompletionPort")] + completion_port: isize, + #[pyarg(positional, name = "Overlapped")] + overlapped: usize, + #[pyarg(positional, name = "Timeout")] + timeout: u32, + } + + #[derive(FromArgs)] + struct ResultWait { + #[pyarg(positional, default)] + wait: bool, + } + pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { let _ = vm.import("_socket", 0)?; host_overlapped::initialize_winsock_extensions() @@ -54,7 +78,7 @@ mod _overlapped { const INFINITE: u32 = host_winapi::INFINITE_TIMEOUT; #[pyattr] - const INVALID_HANDLE_VALUE: isize = host_overlapped::INVALID_HANDLE_VALUE_ISIZE; + const INVALID_HANDLE_VALUE: usize = usize::MAX; #[pyattr] const NULL: isize = 0; @@ -191,6 +215,19 @@ mod _overlapped { } } + // Match PyLong_AsVoidPtr: accept signed negatives and unsigned positive + // pointer-width integers, without invoking arbitrary __index__ methods. + fn pointer_value(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult { + let int = obj + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("an integer is required"))?; + if int.as_bigint().sign() == malachite_bigint::Sign::Minus { + int.try_to_primitive_in_range::(vm) + } else { + Ok(int.try_to_primitive_in_range::(vm)? as isize) + } + } + fn set_from_windows_err(err: u32, vm: &VirtualMachine) -> PyBaseExceptionRef { let err = if err == 0 { host_winapi::get_last_error() @@ -259,6 +296,12 @@ mod _overlapped { } } + #[derive(FromArgs)] + struct RecvFromIntoFlags { + #[pyarg(positional, default)] + flags: u32, + } + #[pyclass(with(Constructor, Destructor))] impl Overlapped { #[pygetset] @@ -304,11 +347,14 @@ mod _overlapped { } #[pymethod] - fn getresult(zelf: &Py, wait: OptionalArg, vm: &VirtualMachine) -> PyResult { + fn getresult( + zelf: &Py, + ResultWait { wait }: ResultWait, + vm: &VirtualMachine, + ) -> PyResult { use host_winapi::{ERROR_BROKEN_PIPE, ERROR_MORE_DATA, ERROR_SUCCESS}; let mut inner = zelf.inner.lock(); - let wait = wait.unwrap_or(false); // Check operation state if matches!(inner.data, OverlappedData::None) { @@ -492,7 +538,7 @@ mod _overlapped { zelf: &Py, handle: isize, size: u32, - flags: OptionalArg, + ReceiveFlags { flags }: ReceiveFlags, vm: &VirtualMachine, ) -> PyResult { use host_winapi::{ @@ -504,7 +550,7 @@ mod _overlapped { return Err(vm.new_value_error("operation already attempted")); } - let mut flags = flags.unwrap_or(0); + let mut flags = flags; #[cfg(target_pointer_width = "32")] let size = core::cmp::min(size, isize::MAX as u32); @@ -691,8 +737,8 @@ mod _overlapped { #[pymethod] fn AcceptEx( zelf: &Py, - listen_socket: isize, - accept_socket: isize, + listen_handle: isize, + accept_handle: isize, vm: &VirtualMachine, ) -> PyResult { use host_winapi::{ERROR_IO_PENDING, ERROR_SUCCESS}; @@ -707,12 +753,12 @@ mod _overlapped { let buf = vec![0u8; size * 2]; let buf = vm.ctx.new_bytes(buf); - inner.handle = listen_socket as host_overlapped::Handle; + inner.handle = listen_handle as host_overlapped::Handle; inner.data = OverlappedData::Accept(buf.clone()); let err = host_overlapped::start_accept_ex( - listen_socket as usize, - accept_socket as usize, + listen_handle as usize, + accept_handle as usize, buf.as_bytes().as_ptr() as *mut u8, size as u32, &mut inner.overlapped, @@ -732,8 +778,8 @@ mod _overlapped { #[pymethod] fn ConnectEx( zelf: &Py, - socket: isize, - address: PyTupleRef, + client_handle: isize, + address_as_bytes: PyTupleRef, vm: &VirtualMachine, ) -> PyResult { use host_winapi::{ERROR_IO_PENDING, ERROR_SUCCESS}; @@ -743,9 +789,9 @@ mod _overlapped { return Err(vm.new_value_error("operation already attempted")); } - let (addr_bytes, addr_len) = parse_address(&address, vm)?; + let (addr_bytes, addr_len) = parse_address(&address_as_bytes, vm)?; - inner.handle = socket as host_overlapped::Handle; + inner.handle = client_handle as host_overlapped::Handle; // Store addr_bytes in OverlappedData to keep it alive during async operation inner.data = OverlappedData::Connect(addr_bytes); @@ -756,7 +802,7 @@ mod _overlapped { }; let err = host_overlapped::start_connect_ex( - socket as usize, + client_handle as usize, addr_ptr as *const host_overlapped::SocketAddrRaw, addr_len, &mut inner.overlapped, @@ -776,7 +822,7 @@ mod _overlapped { #[pymethod] fn DisconnectEx( zelf: &Py, - socket: isize, + handle: isize, flags: u32, vm: &VirtualMachine, ) -> PyResult { @@ -787,11 +833,11 @@ mod _overlapped { return Err(vm.new_value_error("operation already attempted")); } - inner.handle = socket as host_overlapped::Handle; + inner.handle = handle as host_overlapped::Handle; inner.data = OverlappedData::Disconnect; let err = - host_overlapped::start_disconnect_ex(socket as usize, flags, &mut inner.overlapped); + host_overlapped::start_disconnect_ex(handle as usize, flags, &mut inner.overlapped); inner.error = err; match err { @@ -852,7 +898,7 @@ mod _overlapped { // ConnectNamedPipe #[pymethod] - fn ConnectNamedPipe(zelf: &Py, pipe: isize, vm: &VirtualMachine) -> PyResult { + fn ConnectNamedPipe(zelf: &Py, handle: isize, vm: &VirtualMachine) -> PyResult { use host_winapi::{ERROR_IO_PENDING, ERROR_PIPE_CONNECTED, ERROR_SUCCESS}; let mut inner = zelf.inner.lock(); @@ -860,11 +906,11 @@ mod _overlapped { return Err(vm.new_value_error("operation already attempted")); } - inner.handle = pipe as host_overlapped::Handle; + inner.handle = handle as host_overlapped::Handle; inner.data = OverlappedData::ConnectNamedPipe; let err = host_overlapped::start_connect_named_pipe( - pipe as host_overlapped::Handle, + handle as host_overlapped::Handle, &mut inner.overlapped, ); inner.error = err; @@ -890,7 +936,7 @@ mod _overlapped { // y*, as _overlapped.Overlapped.WSASendTo takes buf: ArgBytesLike, flags: u32, - address: PyTupleRef, + address_as_bytes: PyTupleRef, vm: &VirtualMachine, ) -> PyResult { use host_winapi::{ERROR_IO_PENDING, ERROR_SUCCESS}; @@ -901,7 +947,7 @@ mod _overlapped { return Err(vm.new_value_error("operation already attempted")); } - let (addr_bytes, addr_len) = parse_address(&address, vm)?; + let (addr_bytes, addr_len) = parse_address(&address_as_bytes, vm)?; inner.handle = handle as host_overlapped::Handle; let buf_len = buf.desc.len; @@ -951,7 +997,7 @@ mod _overlapped { zelf: &Py, handle: isize, size: u32, - flags: OptionalArg, + ReceiveFlags { flags }: ReceiveFlags, vm: &VirtualMachine, ) -> PyResult { use host_winapi::{ @@ -963,7 +1009,7 @@ mod _overlapped { return Err(vm.new_value_error("operation already attempted")); } - let mut flags = flags.unwrap_or(0); + let mut flags = flags; #[cfg(target_pointer_width = "32")] let size = core::cmp::min(size, isize::MAX as u32); @@ -1015,8 +1061,20 @@ mod _overlapped { } } - // WSARecvFromInto - #[pymethod] + // Preserve the Rust entry point used by existing tests while exposing + // the native default to Python's signature machinery. + #[pymethod(name = "WSARecvFromInto")] + fn recvfrom_into( + zelf: &Py, + handle: isize, + buf: ArgMemoryBuffer, + size: u32, + RecvFromIntoFlags { flags }: RecvFromIntoFlags, + vm: &VirtualMachine, + ) -> PyResult { + Self::WSARecvFromInto(zelf, handle, buf, size, OptionalArg::Present(flags), vm) + } + fn WSARecvFromInto( zelf: &Py, handle: isize, @@ -1048,6 +1106,10 @@ mod _overlapped { return Err(vm.new_value_error("buffer too large")); } + if size as usize > buf_len { + return Err(vm.new_value_error("nbytes is greater than the length of the buffer")); + } + let address: host_overlapped::SocketAddrV6 = unsafe { core::mem::zeroed() }; let address_length = core::mem::size_of::() as i32; @@ -1092,13 +1154,24 @@ mod _overlapped { } } - impl Constructor for Overlapped { - type Args = (OptionalArg,); + #[derive(FromArgs)] + struct OverlappedArgs { + #[pyarg(any, optional, py_default = "_overlapped.INVALID_HANDLE_VALUE")] + event: OptionalArg, + } - fn py_new(_cls: &Py, (event,): Self::Args, vm: &VirtualMachine) -> PyResult { - let mut event = event.unwrap_or(INVALID_HANDLE_VALUE); + impl Constructor for Overlapped { + type Args = OverlappedArgs; + + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + // PyLong_AsVoidPtr accepts actual integers, not arbitrary __index__ objects. + // Borrow the integer payload to avoid boxing int subclasses. + let mut event = match &args.event { + OptionalArg::Missing => host_overlapped::INVALID_HANDLE_VALUE_ISIZE, + OptionalArg::Present(event) => pointer_value(event, vm)?, + }; - if event == INVALID_HANDLE_VALUE { + if event == host_overlapped::INVALID_HANDLE_VALUE_ISIZE { event = host_winapi::create_event_w(true, false, None) .map(|handle| handle as isize) .map_err(|err| { @@ -1130,32 +1203,39 @@ mod _overlapped { let olderr = host_winapi::get_last_error(); // Cancel pending I/O and wait for completion - if !host_overlapped::has_overlapped_io_completed(&inner.overlapped) + let pending_error = if !host_overlapped::has_overlapped_io_completed(&inner.overlapped) && !matches!(inner.data, OverlappedData::NotStarted) { - match host_overlapped::cancel_overlapped_for_drop(inner.handle, &inner.overlapped) - .error - { - ERROR_SUCCESS | ERROR_NOT_FOUND | ERROR_OPERATION_ABORTED => {} - _ => { - let msg = format!( - "{zelf:?} still has pending operation at deallocation, the process may crash" - ); - let exc = vm.new_runtime_error(msg); - let err_msg = Some(format!( - "Exception ignored while deallocating overlapped operation {zelf:?}" - )); - let obj: PyObjectRef = zelf.to_owned().into(); - vm.run_unraisable(exc, err_msg, obj); - } - } - } + !matches!( + vm.allow_threads(|| host_overlapped::cancel_overlapped_for_drop( + inner.handle, + &inner.overlapped + )) + .error, + ERROR_SUCCESS | ERROR_NOT_FOUND | ERROR_OPERATION_ABORTED + ) + } else { + false + }; // Close the event handle if !inner.overlapped.hEvent.is_null() { let _ = host_winapi::close_handle(inner.overlapped.hEvent); inner.overlapped.hEvent = core::ptr::null_mut(); } + // Debug formatting takes inner again; the unraisable hook can also + // re-enter this object. Complete native cleanup before either runs. + drop(inner); + if pending_error { + let msg = format!( + "{zelf:?} still has pending operation at deallocation, the process may crash" + ); + let exc = vm.new_runtime_error(msg); + let err_msg = Some(format!( + "Exception ignored while deallocating overlapped operation {zelf:?}" + )); + vm.run_unraisable(exc, err_msg, vm.ctx.none()); + } // Restore last error host_windows::set_last_error(olderr); @@ -1165,21 +1245,31 @@ mod _overlapped { } #[pyfunction] - fn ConnectPipe(address: String, vm: &VirtualMachine) -> PyResult { - host_overlapped::connect_pipe(&address) + fn ConnectPipe(addr: String, vm: &VirtualMachine) -> PyResult { + host_overlapped::connect_pipe(&addr) .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } #[pyfunction] fn CreateIoCompletionPort( - handle: isize, - port: isize, - key: usize, - concurrency: u32, + handle: PyObjectRef, + port: PyObjectRef, + key: PyObjectRef, + concurrency: PyObjectRef, vm: &VirtualMachine, - ) -> PyResult { - host_overlapped::create_io_completion_port(handle, port, key, concurrency) - .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) + ) -> PyResult { + let handle_value = pointer_value(&handle, vm)?; + let port_value = pointer_value(&port, vm)?; + let key_value = pointer_value(&key, vm)? as usize; + let concurrency_value: u32 = concurrency.try_to_value(vm)?; + host_overlapped::create_io_completion_port( + handle_value, + port_value, + key_value, + concurrency_value, + ) + .map(|port| port as usize) + .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } #[pyfunction] @@ -1215,10 +1305,12 @@ mod _overlapped { #[pyfunction] fn RegisterWaitWithQueue( - object: isize, - completion_port: isize, - overlapped: usize, - timeout: u32, + RegisterWaitArgs { + object, + completion_port, + overlapped, + timeout, + }: RegisterWaitArgs, vm: &VirtualMachine, ) -> PyResult { host_overlapped::register_wait_with_queue(object, completion_port, overlapped, timeout) @@ -1226,23 +1318,23 @@ mod _overlapped { } #[pyfunction] - fn UnregisterWait(wait_handle: isize, vm: &VirtualMachine) -> PyResult<()> { - host_overlapped::unregister_wait(wait_handle) + fn UnregisterWait(WaitHandle: isize, vm: &VirtualMachine) -> PyResult<()> { + host_overlapped::unregister_wait(WaitHandle) .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } #[pyfunction] - fn UnregisterWaitEx(wait_handle: isize, event: isize, vm: &VirtualMachine) -> PyResult<()> { - host_overlapped::unregister_wait_ex(wait_handle, event) + fn UnregisterWaitEx(WaitHandle: isize, Event: isize, vm: &VirtualMachine) -> PyResult<()> { + host_overlapped::unregister_wait_ex(WaitHandle, Event) .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } #[pyfunction] - fn BindLocal(socket: isize, family: i32, vm: &VirtualMachine) -> PyResult<()> { + fn BindLocal(handle: isize, family: i32, vm: &VirtualMachine) -> PyResult<()> { if family != host_overlapped::AF_INET_FAMILY && family != host_overlapped::AF_INET6_FAMILY { return Err(vm.new_value_error("expected tuple of length 2 or 4")); } - host_overlapped::bind_local(socket, family) + host_overlapped::bind_local(handle, family) .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } @@ -1252,10 +1344,14 @@ mod _overlapped { } #[pyfunction] - fn WSAConnect(socket: isize, address: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { - let (addr_bytes, addr_len) = parse_address(&address, vm)?; + fn WSAConnect( + client_handle: isize, + address_as_bytes: PyTupleRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let (addr_bytes, addr_len) = parse_address(&address_as_bytes, vm)?; host_overlapped::wsa_connect( - socket, + client_handle, addr_bytes.as_ptr() as *const host_overlapped::SocketAddrRaw, addr_len, ) @@ -1264,33 +1360,69 @@ mod _overlapped { #[pyfunction] fn CreateEvent( - event_attributes: PyObjectRef, - manual_reset: bool, - initial_state: bool, - name: Option, + EventAttributes: PyObjectRef, + ManualReset: bool, + InitialState: bool, + Name: Option, vm: &VirtualMachine, ) -> PyResult { - if !vm.is_none(&event_attributes) { + if !vm.is_none(&EventAttributes) { return Err(vm.new_value_error("EventAttributes must be None")); } - let name_wide: Option = name + let name_wide: Option = Name .map(|n| widestring::WideCString::from_str(&n).map_err(|err| err.to_pyexception(vm))) .transpose()?; - host_winapi::create_event_w(manual_reset, initial_state, name_wide.as_deref()) + host_winapi::create_event_w(ManualReset, InitialState, name_wide.as_deref()) .map(|h| h as isize) .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } #[pyfunction] - fn SetEvent(handle: isize, vm: &VirtualMachine) -> PyResult<()> { - host_winapi::set_event(handle as host_winapi::Handle) + fn SetEvent(Handle: isize, vm: &VirtualMachine) -> PyResult<()> { + host_winapi::set_event(Handle as host_winapi::Handle) .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } #[pyfunction] - fn ResetEvent(handle: isize, vm: &VirtualMachine) -> PyResult<()> { - host_winapi::reset_event(handle as host_winapi::Handle) + fn ResetEvent(Handle: isize, vm: &VirtualMachine) -> PyResult<()> { + host_winapi::reset_event(Handle as host_winapi::Handle) .map_err(|err| set_from_windows_err(err.raw_os_error().unwrap_or(0) as u32, vm)) } + + #[cfg(test)] + mod tests { + use super::*; + use crate::vm::{TryFromObject, builtins::PyByteArray}; + + #[test] + fn recvfrom_into_rejects_oversized_request_before_starting_io() { + let builder = crate::vm::Interpreter::builder(Default::default()); + let defs = crate::stdlib_module_defs(&builder.ctx); + let interp = builder.add_native_modules(&defs).build(); + interp.enter(|vm| { + let module = vm.import("_overlapped", 0).unwrap(); + let overlapped = module + .get_attr("Overlapped", vm) + .unwrap() + .call((0,), vm) + .unwrap() + .downcast::() + .unwrap(); + let buffer = PyByteArray::from(vec![0; 8]).into_ref(&vm.ctx); + let buffer = ArgMemoryBuffer::try_from_object(vm, buffer.into()).unwrap(); + let err = Overlapped::WSARecvFromInto( + &overlapped, + 0, + buffer, + 9, + OptionalArg::Missing, + vm, + ) + .unwrap_err(); + assert!(err.fast_isinstance(vm.ctx.exceptions.value_error)); + assert!(matches!(overlapped.inner.lock().data, OverlappedData::None)); + }); + } + } } diff --git a/crates/stdlib/src/pickle.rs b/crates/stdlib/src/pickle.rs index 417a5721165..9b92d6ac4e2 100644 --- a/crates/stdlib/src/pickle.rs +++ b/crates/stdlib/src/pickle.rs @@ -5,19 +5,22 @@ pub(crate) use _pickle::module_def; mod _pickle { use crate::common::{ lock::{PyMutex, PyRwLock}, - wtf8::Wtf8Buf, + wtf8::{Wtf8Buf, wtf8_concat}, }; use crate::vm::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{ PyBaseExceptionRef, PyByteArray, PyBytes, PyDict, PyDictRef, PyFloat, PyFrozenSet, - PyInt, PyList, PySet, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef, + PyInt, PyList, PySet, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef, PyUtf8StrRef, }, - function::{FuncArgs, OptionalArg, PySetterValue}, + function::{ArgIntoBool, FuncArgs, OptionalArg, PySetterValue}, + object::{Traverse, TraverseFn}, protocol::{PyBuffer, PyIter, PyIterReturn}, types::{AsBuffer, Constructor, Initializer, Representable}, + utils::ToCString, }; + use alloc::collections::TryReserveError; use core::sync::atomic::{AtomicI32, Ordering}; use malachite_bigint::BigInt; use num_traits::{ToPrimitive, Zero}; @@ -68,7 +71,7 @@ mod _pickle { // PickleBuffer #[pyattr] - #[pyclass(module = "pickle", name = "PickleBuffer")] + #[pyclass(module = "pickle", name = "PickleBuffer", traverse)] #[derive(Debug, PyPayload)] pub(super) struct PyPickleBuffer { buffer: PyRwLock>, @@ -113,7 +116,9 @@ mod _pickle { #[pymethod] fn release(zelf: &Py) { - *zelf.buffer.write() = None; + // Releasing the last share can invoke Python's __release_buffer__. + // Publish the released state and drop the lock before that callback. + let _buffer = zelf.buffer.write().take(); } } @@ -227,12 +232,16 @@ mod _pickle { /// Amount of data `peek()` grabs at a time from a file-like input. const PREFETCH: usize = 8192; + // Grow reads geometrically from this bound, rather than trusting a length + // advertised by a potentially truncated pickle. + const MIN_READ_BUF_SIZE: usize = 1 << 20; // input handling #[derive(Debug, Default)] pub(super) struct ReadState { read: Option, + readinto: Option, readline: Option, peek: Option, /// Bytes currently available to the opcode loop. @@ -246,14 +255,30 @@ mod _pickle { frame_end: Option, } + // SAFETY: these are all the Python references owned by the input state. + unsafe impl Traverse for ReadState { + fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { + self.read.traverse(traverse_fn); + self.readinto.traverse(traverse_fn); + self.readline.traverse(traverse_fn); + self.peek.traverse(traverse_fn); + } + } + fn to_byte_vec(obj: &PyObject, what: &str, vm: &VirtualMachine) -> PyResult> { - obj.downcast_ref::() - .map(|b| b.as_bytes().to_vec()) + let bytes = obj + .downcast_ref::() .ok_or_else(|| { vm.new_type_error(format!( "{what}() from the underlying stream did not return bytes" )) - }) + })? + .as_bytes(); + let mut data = Vec::new(); + data.try_reserve_exact(bytes.len()) + .map_err(|_| vm.no_memory_error())?; + data.extend_from_slice(bytes); + Ok(data) } fn truncated(vm: &VirtualMachine) -> PyBaseExceptionRef { @@ -261,6 +286,17 @@ mod _pickle { } impl ReadState { + fn set_file(&mut self, file: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + self.peek = vm.get_attribute_opt(file, "peek")?; + self.readinto = vm.get_attribute_opt(file, "readinto")?; + self.read = vm.get_attribute_opt(file, "read")?; + self.readline = vm.get_attribute_opt(file, "readline")?; + if self.read.is_none() || self.readline.is_none() { + return Err(vm.new_type_error("file must have 'read' and 'readline' attributes")); + } + Ok(()) + } + fn set_input(&mut self, data: Vec, consumed: bool) { self.prefetched = if consumed { data.len() } else { 0 }; self.buf = data; @@ -303,8 +339,19 @@ mod _pickle { } } let read = self.read.clone().expect("file input"); - let data = read.call((n,), vm)?; - let data = to_byte_vec(&data, "read", vm)?; + let mut chunk_size = n.min(MIN_READ_BUF_SIZE); + let data = read.call((chunk_size,), vm)?; + let mut data = to_byte_vec(&data, "read", vm)?; + let mut received = data.len(); + while received == chunk_size && data.len() < n { + chunk_size = data.len().min(n - data.len()); + let chunk = read.call((chunk_size,), vm)?; + let chunk = to_byte_vec(&chunk, "read", vm)?; + received = chunk.len(); + data.try_reserve(received) + .map_err(|_| vm.no_memory_error())?; + data.extend_from_slice(&chunk); + } let len = data.len(); self.set_input(data, true); Ok(len) @@ -315,7 +362,7 @@ mod _pickle { if let Some(end) = self.frame_end { if self.pos >= end { self.frame_end = None; - } else if self.pos + n > end { + } else if n > end - self.pos { return Err(new_unpickling_error( vm, "pickle exhausted before end of frame", @@ -397,7 +444,7 @@ mod _pickle { // memo proxies #[pyattr] - #[pyclass(module = "_pickle", name = "UnpicklerMemoProxy")] + #[pyclass(module = "_pickle", name = "UnpicklerMemoProxy", traverse)] #[derive(Debug, PyPayload)] struct UnpicklerMemoProxy { unpickler: PyRef, @@ -407,17 +454,25 @@ mod _pickle { impl UnpicklerMemoProxy { #[pymethod] fn clear(zelf: &Py) { - zelf.unpickler.memo.write().clear(); + let _old_memo = core::mem::take(&mut *zelf.unpickler.memo.write()); } #[pymethod] fn copy(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let mut snapshot = Vec::new(); + let copied = { + let memo = zelf.unpickler.memo.read(); + snapshot.try_reserve_exact(memo.len()).map(|()| { + snapshot.extend(memo.iter().map(|(&index, obj)| (index, obj.clone()))); + }) + }; + copied.map_err(|_| vm.no_memory_error())?; + // CPython inserts present memo indices in ascending order. + snapshot.sort_unstable_by_key(|(index, _)| *index); let dict = vm.ctx.new_dict(); - for (i, entry) in zelf.unpickler.memo.read().iter().enumerate() { - if let Some(obj) = entry { - let key: PyObjectRef = vm.ctx.new_int(i).into(); - dict.set_item(&*key, obj.clone(), vm)?; - } + for (i, obj) in snapshot { + let key: PyObjectRef = vm.ctx.new_int(i).into(); + dict.set_item(&*key, obj, vm)?; } Ok(dict.into()) } @@ -440,6 +495,10 @@ mod _pickle { // Unpickler + // PUT indices need not be contiguous. A sparse table also keeps MEMOIZE's + // index equal to the number of entries rather than the largest index. + type UnpicklerMemo = HashMap; + #[derive(Debug)] pub(super) struct UnpicklerConfig { initialized: bool, @@ -450,6 +509,13 @@ mod _pickle { buffers: Option, } + // SAFETY: buffers is the only Python reference owned by the configuration. + unsafe impl Traverse for UnpicklerConfig { + fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { + self.buffers.traverse(traverse_fn); + } + } + impl Default for UnpicklerConfig { fn default() -> Self { Self { @@ -464,24 +530,58 @@ mod _pickle { } #[pyattr] - #[pyclass(module = "_pickle", name = "Unpickler")] + #[pyclass(module = "_pickle", name = "Unpickler", traverse = "manual")] #[derive(Debug, PyPayload)] pub(super) struct PyUnpickler { read_state: PyMutex, - memo: PyRwLock>>, + memo: PyRwLock, config: PyRwLock, } + // SAFETY: visit each owned reference once, including sparse memo entries. + unsafe impl Traverse for PyUnpickler { + fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { + self.read_state.traverse(traverse_fn); + self.config.traverse(traverse_fn); + if let Some(memo) = self.memo.try_read_recursive() { + #[expect( + clippy::iter_over_hash_type, + reason = "GC tracing visits every memo reference regardless of index order" + )] + for value in memo.values() { + value.traverse(traverse_fn); + } + } + } + + fn clear(&mut self, out: &mut Vec) { + let state = self.read_state.get_mut(); + out.extend(state.read.take()); + out.extend(state.readinto.take()); + out.extend(state.readline.take()); + out.extend(state.peek.take()); + out.extend(self.memo.get_mut().drain().map(|(_, value)| value)); + let config = self.config.get_mut(); + out.extend(config.buffers.take()); + config.initialized = false; + } + } + + fn pickle_string(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = PyUtf8StrRef::try_from_object(vm, obj.clone())?; + value.to_cstring(vm)?; + Ok(value.as_str().to_owned()) + } + + // Bind the whole call before converting options: Clinic rejects unknown + // keywords before invoking __bool__. Raw arguments also keep subclasses + // alive until all stream and buffer callbacks have finished. #[derive(FromArgs)] - pub(super) struct UnpicklerNewArgs { - #[pyarg(any)] - file: PyObjectRef, + struct UnpicklerOptions { #[pyarg(named, default = true)] - fix_imports: bool, - // None means ASCII. + fix_imports: PyObjectRef, #[pyarg(named, default = "ASCII")] encoding: PyObjectRef, - // None means strict. #[pyarg(named, default = "strict")] errors: PyObjectRef, // Missing or None means no buffers. @@ -489,13 +589,46 @@ mod _pickle { buffers: OptionalArg, } + impl UnpicklerOptions { + fn config(&self, vm: &VirtualMachine) -> PyResult { + Ok(UnpicklerConfig { + initialized: true, + proto: 0, + fix_imports: ArgIntoBool::try_from_object(vm, self.fix_imports.clone())? + .into_bool(), + encoding: pickle_string(&self.encoding, vm)?, + errors: pickle_string(&self.errors, vm)?, + buffers: None, + }) + } + + // Unlike the Clinic converters above, iter(buffers) belongs after + // file/data setup and inside an initializer's recursion guard. + fn buffers(&self, vm: &VirtualMachine) -> PyResult> { + match &self.buffers { + OptionalArg::Present(obj) if !vm.is_none(obj) => { + Ok(Some(PyIter::try_from_object(vm, obj.clone())?.into())) + } + _ => Ok(None), + } + } + } + + #[derive(FromArgs)] + pub(super) struct UnpicklerNewArgs { + #[pyarg(any)] + file: PyObjectRef, + #[pyarg(flatten)] + options: UnpicklerOptions, + } + impl Constructor for PyUnpickler { type Args = FuncArgs; fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { Ok(Self { read_state: PyMutex::new(ReadState::default()), - memo: PyRwLock::new(Vec::new()), + memo: PyRwLock::new(UnpicklerMemo::new()), config: PyRwLock::new(UnpicklerConfig::default()), }) } @@ -505,58 +638,20 @@ mod _pickle { type Args = UnpicklerNewArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { + let mut config = args.options.config(vm)?; + // On setup failure, the guard must go before staged references: + // dropping a file method or iterator can run a Python finalizer. + let mut new_state = ReadState::default(); let Some(mut state) = zelf.read_state.try_lock() else { return Err(vm.new_runtime_error("Unpickler.__init__() called recursively")); }; - let encoding = if vm.is_none(&args.encoding) { - "ASCII".to_owned() - } else { - args.encoding - .downcast_ref::() - .and_then(|s| s.to_str()) - .ok_or_else(|| vm.new_type_error("encoding must be a string"))? - .to_owned() - }; - let errors = if vm.is_none(&args.errors) { - "strict".to_owned() - } else { - args.errors - .downcast_ref::() - .and_then(|s| s.to_str()) - .ok_or_else(|| vm.new_type_error("errors must be a string"))? - .to_owned() - }; - let buffers = match args.buffers { - OptionalArg::Present(o) if !vm.is_none(&o) => { - Some(PyIter::try_from_object(vm, o)?.into()) - } - _ => None, - }; - - let file = args.file; - let peek = vm.get_attribute_opt(&file, "peek")?; - let _readinto = vm.get_attribute_opt(&file, "readinto")?; - let read = vm.get_attribute_opt(&file, "read")?; - let readline = vm.get_attribute_opt(&file, "readline")?; - if read.is_none() || readline.is_none() { - return Err(vm.new_type_error("file must have 'read' and 'readline' attributes")); - } - - *state = ReadState { - read, - readline, - peek, - ..ReadState::default() - }; - zelf.memo.write().clear(); - *zelf.config.write() = UnpicklerConfig { - initialized: true, - proto: 0, - fix_imports: args.fix_imports, - encoding, - errors, - buffers, - }; + new_state.set_file(&args.file, vm)?; + config.buffers = args.options.buffers(vm)?; + let old_state = core::mem::replace(&mut *state, new_state); + let old_memo = core::mem::take(&mut *zelf.memo.write()); + let old_config = core::mem::replace(&mut *zelf.config.write(), config); + drop(state); + drop((old_state, old_memo, old_config)); Ok(()) } } @@ -605,21 +700,21 @@ mod _pickle { } }; let new_memo = if let Some(proxy) = value.downcast_ref::() { - proxy.unpickler.memo.read().clone() + let snapshot = copy_memo(&proxy.unpickler.memo.read()); + snapshot.map_err(|_| vm.no_memory_error())? } else if let Some(dict) = value.downcast_ref::() { - let mut memo: Vec> = Vec::new(); + let mut memo = UnpicklerMemo::new(); + memo.try_reserve(dict.__len__()) + .map_err(|_| vm.no_memory_error())?; for (key, val) in dict { let idx = key .downcast_ref::() .ok_or_else(|| vm.new_type_error("memo key must be integers"))?; - let idx = idx - .as_bigint() - .to_usize() - .ok_or_else(|| vm.new_value_error("memo key must be positive integers."))?; - if memo.len() <= idx { - memo.resize(idx + 1, None); + let idx = idx.try_to_primitive::(vm)?; + if idx < 0 { + return Err(vm.new_value_error("memo key must be positive integers.")); } - memo[idx] = Some(val); + memo_insert(&mut memo, idx as usize, &val).map_err(|_| vm.no_memory_error())?; } memo } else { @@ -628,7 +723,7 @@ mod _pickle { value.class().name() ))); }; - *zelf.memo.write() = new_memo; + let _old_memo = core::mem::replace(&mut *zelf.memo.write(), new_memo); Ok(()) } } @@ -648,18 +743,6 @@ mod _pickle { } } - fn getattribute_path( - obj: PyObjectRef, - path: &str, - vm: &VirtualMachine, - ) -> PyResult { - let mut obj = obj; - for part in path.split('.') { - obj = obj.get_attr(&vm.ctx.new_str(part), vm)?; - } - Ok(obj) - } - fn find_class_impl( zelf: &Py, module: PyObjectRef, @@ -717,11 +800,8 @@ mod _pickle { let sys_modules = vm.sys_module.get_attr("modules", vm)?; let module_obj = sys_modules.get_item(&*module, vm)?; - if proto >= 4 - && name.as_bytes().contains(&b'.') - && let Some(name_str) = name.to_str() - { - getattribute_path(module_obj, name_str, vm).map_err(|e| { + if proto >= 4 && name.as_bytes().contains(&b'.') { + getattr_path(&module_obj, &split_dotted(&name, vm), vm).map_err(|e| { let name_repr = name .as_object() .repr(vm) @@ -801,13 +881,18 @@ mod _pickle { .ok() .filter(|n| isize::try_from(*n).is_ok()) .ok_or_else(|| { - new_unpickling_error( - vm, + let message = if what == "FRAME" { + format!( + "FRAME length exceeds system's maximum of {} bytes", + isize::MAX + ) + } else { format!( "{what} exceeds system's maximum size of {} bytes", isize::MAX - ), - ) + ) + }; + vm.new_overflow_error(message) }) } @@ -1073,7 +1158,7 @@ mod _pickle { } Some(BINBYTES8) => { let arr: [u8; 8] = st.read_n(8, vm)?.try_into().unwrap(); - let n = read_size(&arr, vm, "BINBYTES8")?; + let n = read_size(&arr, vm, "BINBYTES")?; let data = st.read_n(n, vm)?.to_vec(); stack.push(vm.ctx.new_bytes(data).into()); } @@ -1112,7 +1197,7 @@ mod _pickle { } Some(BINUNICODE8) => { let arr: [u8; 8] = st.read_n(8, vm)?.try_into().unwrap(); - let n = read_size(&arr, vm, "BINUNICODE8")?; + let n = read_size(&arr, vm, "BINUNICODE")?; let data = st.read_n(n, vm)?.to_vec(); stack.push(utf8_surrogatepass(&data, vm)?); } @@ -1253,13 +1338,16 @@ mod _pickle { Some(BINPUT) => { let i = st.read_n(1, vm)?[0] as usize; let value = top!(); - memo_put(zelf, i, value); + memo_put(zelf, Some(i), value, vm)?; } Some(LONG_BINPUT) => { let arr: [u8; 4] = st.read_n(4, vm)?.try_into().unwrap(); let i = u32::from_le_bytes(arr) as usize; let value = top!(); - memo_put(zelf, i, value); + if i > isize::MAX as usize { + return Err(vm.new_value_error("negative LONG_BINPUT argument")); + } + memo_put(zelf, Some(i), value, vm)?; } Some(PUT) => { let line = st.read_line(vm)?; @@ -1269,12 +1357,11 @@ mod _pickle { let body = &line[..line.len() - 1]; let idx = parse_memo_index(body, vm)?; let value = top!(); - memo_put(zelf, idx, value); + memo_put(zelf, Some(idx), value, vm)?; } Some(MEMOIZE) => { let value = top!(); - let idx = zelf.memo.read().len(); - memo_put(zelf, idx, value); + memo_put(zelf, None, value, vm)?; } Some(PERSID) => { let line = st.read_line(vm)?; @@ -1503,19 +1590,43 @@ mod _pickle { } fn memo_get(zelf: &Py, idx: usize, vm: &VirtualMachine) -> PyResult { - zelf.memo - .read() - .get(idx) - .and_then(|o| o.clone()) + let value = zelf.memo.read().get(&idx).cloned(); + value .ok_or_else(|| new_unpickling_error(vm, format!("Memo value not found at index {idx}"))) } - fn memo_put(zelf: &Py, idx: usize, value: PyObjectRef) { - let mut memo = zelf.memo.write(); - if memo.len() <= idx { - memo.resize(idx + 1, None); + fn copy_memo(memo: &UnpicklerMemo) -> Result { + let mut copy = UnpicklerMemo::new(); + copy.try_reserve(memo.len())?; + copy.extend(memo.iter().map(|(&idx, obj)| (idx, obj.clone()))); + Ok(copy) + } + + fn memo_insert( + memo: &mut UnpicklerMemo, + idx: usize, + value: &PyObjectRef, + ) -> Result, TryReserveError> { + if !memo.contains_key(&idx) { + memo.try_reserve(1)?; } - memo[idx] = Some(value); + Ok(memo.insert(idx, value.clone())) + } + + fn memo_put( + zelf: &Py, + idx: Option, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let old_value = { + let mut memo = zelf.memo.write(); + let idx = idx.unwrap_or_else(|| memo.len()); + memo_insert(&mut memo, idx, &value) + }; + // Releasing an entry can call a finalizer that accesses the memo. + drop(old_value.map_err(|_| vm.no_memory_error())?); + Ok(()) } fn instantiate( @@ -1619,62 +1730,13 @@ mod _pickle { pub(super) struct LoadsArgs { #[pyarg(positional)] data: PyObjectRef, - #[pyarg(named, default = true)] - fix_imports: bool, - // None means ASCII. - #[pyarg(named, default = "ASCII")] - encoding: PyObjectRef, - // None means strict. - #[pyarg(named, default = "strict")] - errors: PyObjectRef, - // Missing or None means no buffers. - #[pyarg(named, optional, py_default = "()")] - buffers: OptionalArg, - } - - fn unpickler_config( - fix_imports: bool, - encoding: PyObjectRef, - errors: PyObjectRef, - buffers: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult { - let encoding = if vm.is_none(&encoding) { - "ASCII".to_owned() - } else { - encoding - .downcast_ref::() - .and_then(|s| s.to_str()) - .ok_or_else(|| vm.new_type_error("encoding must be a string"))? - .to_owned() - }; - let errors = if vm.is_none(&errors) { - "strict".to_owned() - } else { - errors - .downcast_ref::() - .and_then(|s| s.to_str()) - .ok_or_else(|| vm.new_type_error("errors must be a string"))? - .to_owned() - }; - let buffers = match buffers { - OptionalArg::Present(o) if !vm.is_none(&o) => { - Some(PyIter::try_from_object(vm, o)?.into()) - } - _ => None, - }; - Ok(UnpicklerConfig { - initialized: true, - proto: 0, - fix_imports, - encoding, - errors, - buffers, - }) + #[pyarg(flatten)] + options: UnpicklerOptions, } #[pyfunction] fn loads(args: LoadsArgs, vm: &VirtualMachine) -> PyResult { + let mut config = args.options.config(vm)?; if args.data.downcastable::() { return Err(vm.new_type_error("Can't load pickle from unicode string")); } @@ -1687,19 +1749,13 @@ mod _pickle { )); } }; - let config = unpickler_config( - args.fix_imports, - args.encoding, - args.errors, - args.buffers, - vm, - )?; + config.buffers = args.options.buffers(vm)?; let unpickler = PyUnpickler { read_state: PyMutex::new(ReadState { buf: data, ..ReadState::default() }), - memo: PyRwLock::new(Vec::new()), + memo: PyRwLock::new(UnpicklerMemo::new()), config: PyRwLock::new(config), } .into_ref(&vm.ctx); @@ -1710,42 +1766,19 @@ mod _pickle { pub(super) struct LoadArgs { #[pyarg(any)] file: PyObjectRef, - #[pyarg(named, default = true)] - fix_imports: bool, - // None means ASCII. - #[pyarg(named, default = "ASCII")] - encoding: PyObjectRef, - // None means strict. - #[pyarg(named, default = "strict")] - errors: PyObjectRef, - // Missing or None means no buffers. - #[pyarg(named, optional, py_default = "()")] - buffers: OptionalArg, + #[pyarg(flatten)] + options: UnpicklerOptions, } #[pyfunction] fn load(args: LoadArgs, vm: &VirtualMachine) -> PyResult { - let peek = vm.get_attribute_opt(&args.file, "peek")?; - let read = vm.get_attribute_opt(&args.file, "read")?; - let readline = vm.get_attribute_opt(&args.file, "readline")?; - if read.is_none() || readline.is_none() { - return Err(vm.new_type_error("file must have 'read' and 'readline' attributes")); - } - let config = unpickler_config( - args.fix_imports, - args.encoding, - args.errors, - args.buffers, - vm, - )?; + let mut config = args.options.config(vm)?; + let mut state = ReadState::default(); + state.set_file(&args.file, vm)?; + config.buffers = args.options.buffers(vm)?; let unpickler = PyUnpickler { - read_state: PyMutex::new(ReadState { - read, - readline, - peek, - ..ReadState::default() - }), - memo: PyRwLock::new(Vec::new()), + read_state: PyMutex::new(state), + memo: PyRwLock::new(UnpicklerMemo::new()), config: PyRwLock::new(config), } .into_ref(&vm.ctx); @@ -1960,24 +1993,20 @@ mod _pickle { #[pyarg(any, optional)] protocol: Option, #[pyarg(any, default = true)] - fix_imports: bool, + fix_imports: PyObjectRef, #[pyarg(any, optional)] buffer_callback: Option, } - fn resolve_protocol(protocol: Option, vm: &VirtualMachine) -> PyResult { + fn resolve_protocol(protocol: Option<&PyObjectRef>, vm: &VirtualMachine) -> PyResult { let value = match protocol { - Some(o) => o - .try_index(vm)? - .as_bigint() - .to_i64() - .unwrap_or_else(|| i64::from(i32::MAX)), - None => i64::from(DEFAULT_PROTOCOL), + Some(obj) => core::ffi::c_long::try_from_object(vm, obj.clone())?, + None => core::ffi::c_long::from(DEFAULT_PROTOCOL), }; if value < 0 { return Ok(HIGHEST_PROTOCOL); } - if value > i64::from(HIGHEST_PROTOCOL) { + if value > core::ffi::c_long::from(HIGHEST_PROTOCOL) { return Err( vm.new_value_error(format!("pickle protocol must be <= {HIGHEST_PROTOCOL}")) ); @@ -1985,20 +2014,32 @@ mod _pickle { Ok(value as u8) } - fn pickler_config(args: &PicklerNewArgs, vm: &VirtualMachine) -> PyResult { - let proto = resolve_protocol(args.protocol.clone(), vm)?; - let buffer_callback = match &args.buffer_callback { - Some(o) if !vm.is_none(o) => Some(o.clone()), - _ => None, - }; + fn pickler_config( + protocol: Option<&PyObjectRef>, + fix_imports: bool, + buffer_callback: Option<&PyObjectRef>, + file: Option<&PyObject>, + output: &mut Output, + vm: &VirtualMachine, + ) -> PyResult { + let proto = resolve_protocol(protocol, vm)?; + // File setup precedes callback validation for Pickler and dump. dumps + // has no stream, so it goes straight from protocol to callback. + if let Some(file) = file { + output.write = vm.get_attribute_opt(file, "write")?; + if output.write.is_none() { + return Err(vm.new_type_error("file must have a 'write' attribute")); + } + } + let buffer_callback = buffer_callback.filter(|obj| !vm.is_none(obj)); if buffer_callback.is_some() && proto < 5 { return Err(vm.new_value_error("buffer_callback needs protocol >= 5")); } Ok(PicklerConfig { initialized: true, proto, - fix_imports: args.fix_imports && proto < 3, - buffer_callback, + fix_imports: fix_imports && proto < 3, + buffer_callback: buffer_callback.cloned(), }) } @@ -2020,26 +2061,28 @@ mod _pickle { type Args = PicklerNewArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { + let fix_imports = + ArgIntoBool::try_from_object(vm, args.fix_imports.clone())?.into_bool(); + let mut new_output = Output::default(); let Some(mut out) = zelf.out.try_lock() else { return Err(vm.new_runtime_error("Pickler.__init__() called recursively")); }; - let config = pickler_config(&args, vm)?; - let write = args.file.get_attr("write", vm).map_err(|e| { - if e.fast_isinstance(vm.ctx.exceptions.attribute_error) { - vm.new_type_error("file must have a 'write' attribute") - } else { - e - } - })?; - *out = Output { - write: Some(write), - ..Output::default() - }; - zelf.memo.write().clear(); + let config = pickler_config( + args.protocol.as_ref(), + fix_imports, + args.buffer_callback.as_ref(), + Some(&args.file), + &mut new_output, + vm, + )?; + let old_output = core::mem::replace(&mut *out, new_output); + let old_memo = core::mem::take(&mut *zelf.memo.write()); zelf.bin .store(i32::from(config.proto >= 1), Ordering::Relaxed); zelf.fast.store(0, Ordering::Relaxed); - *zelf.config.write() = config; + let old_config = core::mem::replace(&mut *zelf.config.write(), config); + drop(out); + drop((old_output, old_memo, old_config)); Ok(()) } } @@ -2111,7 +2154,7 @@ mod _pickle { // saving fn add_note(err: PyBaseExceptionRef, note: String, vm: &VirtualMachine) -> PyBaseExceptionRef { - let _ = err.add_note(vm.ctx.new_str(note), vm); + let _ = err.add_note_str(vm.ctx.new_str(note), vm); err } @@ -2532,17 +2575,24 @@ mod _pickle { } self.memoize(obj); let list = obj.downcast_ref::().expect("list"); - self.batch_appends_list(list, obj, vm) + if self.proto > 0 { + self.batch_appends_list(list, obj, vm) + } else { + let iter = obj.to_owned().get_iter(vm)?; + self.batch_appends_iter(&iter, Some(obj), vm) + } } fn save_item( &mut self, - item: &PyObject, + item: PyObjectRef, index: usize, obj: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { - self.save(item, false, vm).map_err(|e| { + let result = self.save(&item, false, vm); + drop(item); + result.map_err(|e| { add_note( e, format!("when serializing {} item {index}", obj_type_name(obj, vm)), @@ -2558,34 +2608,31 @@ mod _pickle { vm: &VirtualMachine, ) -> PyResult<()> { let initial_len = list.borrow_vec().len(); - let mut start = 0usize; - loop { - let batch: Vec = { - let items = list.borrow_vec(); - if start >= items.len() { - break; - } - items[start..items.len().min(start + BATCH_SIZE)].to_vec() - }; - if batch.is_empty() { - break; - } - if !self.bin { - for (k, item) in batch.iter().enumerate() { - self.save_item(item, start + k, obj, vm)?; - self.write(&[APPEND as u8]); - } - } else if batch.len() != 1 { - self.write(&[MARK as u8]); - for (k, item) in batch.iter().enumerate() { - self.save_item(item, start + k, obj, vm)?; - } - self.write(&[APPENDS as u8]); - } else { - self.save_item(&batch[0], start, obj, vm)?; + let mut index = 0usize; + while index < initial_len { + if initial_len - index == 1 { + let item = list.borrow_vec().get(index).cloned(); + let item = item.ok_or_else(|| { + add_note( + vm.new_index_error("list index out of range"), + format!("when serializing {} item {index}", obj_type_name(obj, vm)), + vm, + ) + })?; + self.save_item(item, index, obj, vm)?; self.write(&[APPEND as u8]); + return Ok(()); } - start += batch.len(); + + self.write(&[MARK as u8]); + for _ in 0..BATCH_SIZE { + // Saving an item may replace or remove later list entries. + let item = list.borrow_vec().get(index).cloned(); + let Some(item) = item else { break }; + self.save_item(item, index, obj, vm)?; + index += 1; + } + self.write(&[APPENDS as u8]); if list.borrow_vec().len() != initial_len { return Err(vm.new_runtime_error("list changed size during iteration")); } @@ -2600,50 +2647,78 @@ mod _pickle { vm: &VirtualMachine, ) -> PyResult<()> { let name = |vm: &VirtualMachine| obj.map_or_else(String::new, |o| obj_type_name(o, vm)); - let iter = items.to_owned().get_iter(vm)?; - let mut index = 0usize; - let mut pending: Vec = Vec::new(); - let mut exhausted = false; - while !exhausted { - pending.clear(); - while pending.len() < BATCH_SIZE { - match iter.next(vm)? { - PyIterReturn::Return(o) => pending.push(o), - PyIterReturn::StopIteration(_) => { - exhausted = true; - break; - } + self.batch_iter( + items, + Ok, + |ctx, item: PyObjectRef, index| { + let result = ctx.save(&item, false, vm); + if ctx.proto == 0 { + drop(item); } + result.map_err(|e| { + add_note(e, format!("when serializing {} item {index}", name(vm)), vm) + }) + }, + (APPEND as u8, APPENDS as u8), + vm, + ) + } + + fn batch_iter( + &mut self, + items: &PyObject, + validate: impl Fn(PyObjectRef) -> PyResult, + mut save: impl FnMut(&mut Self, T, usize) -> PyResult<()>, + (single, multiple): (u8, u8), + vm: &VirtualMachine, + ) -> PyResult<()> { + // Reduction items are already iterators; do not call __iter__ again. + let iter = PyIter::new(items); + let mut index = 0usize; + if self.proto == 0 { + while let Ok(item) = iter.next(vm)?.into_result() { + let item = validate(item)?; + save(self, item, index)?; + self.write(&[single]); + index += 1; } - if pending.is_empty() { - break; - } - if !self.bin { - for item in &pending { - self.save(item, false, vm).map_err(|e| { - add_note(e, format!("when serializing {} item {index}", name(vm)), vm) - })?; - self.write(&[APPEND as u8]); - index += 1; + return Ok(()); + } + + loop { + let Some(first) = iter.next(vm)?.into_result().ok() else { + return Ok(()); + }; + let first = validate(first)?; + let Some(mut item) = iter.next(vm)?.into_result().ok() else { + save(self, first, index)?; + self.write(&[single]); + return Ok(()); + }; + + self.write(&[MARK as u8]); + save(self, first, index)?; + index += 1; + let mut count = 1; + loop { + // Validate the second pair only after saving the first one. + let current = validate(item)?; + save(self, current, index)?; + index += 1; + count += 1; + if count == BATCH_SIZE { + break; } - } else if pending.len() != 1 { - self.write(&[MARK as u8]); - for item in &pending { - self.save(item, false, vm).map_err(|e| { - add_note(e, format!("when serializing {} item {index}", name(vm)), vm) - })?; - index += 1; + match iter.next(vm)?.into_result().ok() { + Some(next) => item = next, + None => break, } - self.write(&[APPENDS as u8]); - } else { - self.save(&pending[0], false, vm).map_err(|e| { - add_note(e, format!("when serializing {} item {index}", name(vm)), vm) - })?; - self.write(&[APPEND as u8]); - index += 1; + } + self.write(&[multiple]); + if count < BATCH_SIZE { + return Ok(()); } } - Ok(()) } fn save_dict(&mut self, obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { @@ -2655,34 +2730,49 @@ mod _pickle { self.memoize(obj); let dict = obj.downcast_ref::().expect("dict"); let initial_len = dict.__len__(); - let entries: Vec<(PyObjectRef, PyObjectRef)> = dict.into_iter().collect(); - let mut start = 0usize; - while start < entries.len() { - let end = entries.len().min(start + BATCH_SIZE); - let batch = &entries[start..end]; - if !self.bin { - for (k, v) in batch { - self.save(k, false, vm)?; - self.save_value(v, k, obj, vm)?; - self.write(&[SETITEM as u8]); - } - } else if batch.len() != 1 { - self.write(&[MARK as u8]); - for (k, v) in batch { - self.save(k, false, vm)?; - self.save_value(v, k, obj, vm)?; - } - self.write(&[SETITEMS as u8]); - } else { - let (k, v) = &batch[0]; - self.save(k, false, vm)?; - self.save_value(v, k, obj, vm)?; + if initial_len == 0 { + return Ok(()); + } + if self.proto == 0 { + let items = vm.call_method(obj, "items", ())?; + let iter = items.get_iter(vm)?; + return self.batch_setitems_iter(&iter, Some(obj), vm); + } + + let mut position = 0; + let mut total = 0; + while total < initial_len { + if initial_len - total == 1 { + let (_, key, value) = dict.next_entry(position).ok_or_else(|| { + vm.new_runtime_error("dictionary changed size during iteration") + })?; + let result = self.save_dict_item(&key, &value, Some(obj), vm); + drop((key, value)); + result?; self.write(&[SETITEM as u8]); + return Ok(()); + } + + self.write(&[MARK as u8]); + let mut exhausted = false; + for _ in 0..BATCH_SIZE { + let Some((next, key, value)) = dict.next_entry(position) else { + exhausted = true; + break; + }; + position = next; + let result = self.save_dict_item(&key, &value, Some(obj), vm); + drop((key, value)); + result?; + total += 1; } - start = end; + self.write(&[SETITEMS as u8]); if dict.__len__() != initial_len { return Err(vm.new_runtime_error("dictionary changed size during iteration")); } + if exhausted { + break; + } } Ok(()) } @@ -2713,52 +2803,38 @@ mod _pickle { obj: Option<&PyObject>, vm: &VirtualMachine, ) -> PyResult<()> { - let iter = items.to_owned().get_iter(vm)?; - let mut pending: Vec<(PyObjectRef, PyObjectRef)> = Vec::new(); - let mut exhausted = false; - while !exhausted { - pending.clear(); - while pending.len() < BATCH_SIZE { - match iter.next(vm)? { - PyIterReturn::Return(o) => { - let pair: PyTupleRef = o.downcast().map_err(|_| { - vm.new_type_error("dict items iterator must return 2-tuples") - })?; - if pair.as_slice().len() != 2 { - return Err( - vm.new_type_error("dict items iterator must return 2-tuples") - ); - } - pending.push((pair.as_slice()[0].clone(), pair.as_slice()[1].clone())); - } - PyIterReturn::StopIteration(_) => { - exhausted = true; - break; - } - } - } - if pending.is_empty() { - break; - } - let single = pending.len() == 1; - if self.bin && !single { - self.write(&[MARK as u8]); - } - for (k, v) in &pending { - self.save(k, false, vm)?; - match obj { - Some(o) => self.save_value(v, k, o, vm)?, - None => self.save(v, false, vm)?, - } - if !self.bin || single { - self.write(&[SETITEM as u8]); + self.batch_iter( + items, + |item| { + let pair: PyTupleRef = item.downcast().map_err(|_| { + vm.new_type_error("dict items iterator must return 2-tuples") + })?; + if pair.as_slice().len() != 2 { + return Err(vm.new_type_error("dict items iterator must return 2-tuples")); } - } - if self.bin && !single { - self.write(&[SETITEMS as u8]); - } + Ok(pair) + }, + |ctx, pair, _| { + let pair = pair.as_slice(); + ctx.save_dict_item(&pair[0], &pair[1], obj, vm) + }, + (SETITEM as u8, SETITEMS as u8), + vm, + ) + } + + fn save_dict_item( + &mut self, + key: &PyObject, + value: &PyObject, + obj: Option<&PyObject>, + vm: &VirtualMachine, + ) -> PyResult<()> { + self.save(key, false, vm)?; + match obj { + Some(obj) => self.save_value(value, key, obj, vm), + None => self.save(value, false, vm), } - Ok(()) } fn save_set(&mut self, obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { @@ -2779,19 +2855,36 @@ mod _pickle { } self.write(&[EMPTY_SET as u8]); self.memoize(obj); - let elements = set.elements(); - for batch in elements.chunks(BATCH_SIZE) { + let initial_len = obj.length(vm)?; + let mut position = 0; + let mut total = 0; + while total < initial_len { self.write(&[MARK as u8]); - for item in batch { - self.save(item, false, vm).map_err(|e| { + let mut exhausted = false; + for _ in 0..BATCH_SIZE { + let Some((next, item)) = set.next_entry(position) else { + exhausted = true; + break; + }; + position = next; + let result = self.save(&item, false, vm); + drop(item); + result.map_err(|e| { add_note( e, format!("when serializing {} element", obj_type_name(obj, vm)), vm, ) })?; + total += 1; } self.write(&[ADDITEMS as u8]); + if obj.length(vm)? != initial_len { + return Err(vm.new_runtime_error("set changed size during iteration")); + } + if exhausted { + break; + } } Ok(()) } @@ -2856,7 +2949,7 @@ mod _pickle { impl SaveCtx<'_> { fn save(&mut self, obj: &PyObject, pers_save: bool, vm: &VirtualMachine) -> PyResult<()> { - vm.with_recursion("while pickling an object", || { + vm.with_recursion(" while pickling an object", || { self.save_inner(obj, pers_save, vm) }) } @@ -3387,6 +3480,7 @@ mod _pickle { .map_err(|_| new_pickling_error(vm, "the global name must be a string"))? } }; + let name = mangle_global_name(name, vm); let module_name = whichmodule(obj, &name, vm)?; if self.proto >= 2 { @@ -3561,6 +3655,38 @@ mod _pickle { .collect() } + fn mangle_global_name(name: PyRef, vm: &VirtualMachine) -> PyRef { + if !name.as_bytes().windows(3).any(|part| part == b".__") { + return name; + } + let mut parts = split_dotted(&name, vm); + let mut changed = false; + // Work backwards so each parent still has its original class name. + for i in (1..parts.len()).rev() { + let part = &parts[i]; + if part.as_bytes().starts_with(b"__") && !part.as_bytes().ends_with(b"__") { + let parent = parts[i - 1] + .as_wtf8() + .trim_start_matches(|ch| ch.to_u32() == u32::from(b'_')); + if !parent.is_empty() { + parts[i] = vm.ctx.new_str(wtf8_concat!("_", parent, part.as_wtf8())); + changed = true; + } + } + } + if !changed { + return name; + } + let mut mangled = Wtf8Buf::new(); + for (i, part) in parts.iter().enumerate() { + if i != 0 { + mangled.push_char('.'); + } + mangled.push_wtf8(part.as_wtf8()); + } + vm.ctx.new_str(mangled) + } + fn whichmodule( obj: &PyObject, name: &Py, @@ -3751,32 +3877,25 @@ mod _pickle { #[pyarg(any, optional)] protocol: Option, #[pyarg(named, default = true)] - fix_imports: bool, + fix_imports: PyObjectRef, #[pyarg(named, optional)] buffer_callback: Option, } #[pyfunction] fn dump(args: DumpArgs, vm: &VirtualMachine) -> PyResult<()> { - let new_args = PicklerNewArgs { - file: args.file, - protocol: args.protocol, - fix_imports: args.fix_imports, - buffer_callback: args.buffer_callback, - }; - let config = pickler_config(&new_args, vm)?; - let write = new_args.file.get_attr("write", vm).map_err(|e| { - if e.fast_isinstance(vm.ctx.exceptions.attribute_error) { - vm.new_type_error("file must have a 'write' attribute") - } else { - e - } - })?; + let fix_imports = ArgIntoBool::try_from_object(vm, args.fix_imports.clone())?.into_bool(); + let mut output = Output::default(); + let config = pickler_config( + args.protocol.as_ref(), + fix_imports, + args.buffer_callback.as_ref(), + Some(&args.file), + &mut output, + vm, + )?; let pickler = PyPickler { - out: PyMutex::new(Output { - write: Some(write), - ..Output::default() - }), + out: PyMutex::new(output), memo: PyRwLock::new(MemoTable::default()), bin: AtomicI32::new(i32::from(config.proto >= 1)), fast: AtomicI32::new(0), @@ -3793,22 +3912,25 @@ mod _pickle { #[pyarg(any, optional)] protocol: Option, #[pyarg(named, default = true)] - fix_imports: bool, + fix_imports: PyObjectRef, #[pyarg(named, optional)] buffer_callback: Option, } #[pyfunction] fn dumps(args: DumpsArgs, vm: &VirtualMachine) -> PyResult { - let new_args = PicklerNewArgs { - file: vm.ctx.none(), - protocol: args.protocol, - fix_imports: args.fix_imports, - buffer_callback: args.buffer_callback, - }; - let config = pickler_config(&new_args, vm)?; + let fix_imports = ArgIntoBool::try_from_object(vm, args.fix_imports.clone())?.into_bool(); + let mut output = Output::default(); + let config = pickler_config( + args.protocol.as_ref(), + fix_imports, + args.buffer_callback.as_ref(), + None, + &mut output, + vm, + )?; let pickler = PyPickler { - out: PyMutex::new(Output::default()), + out: PyMutex::new(output), memo: PyRwLock::new(MemoTable::default()), bin: AtomicI32::new(i32::from(config.proto >= 1)), fast: AtomicI32::new(0), diff --git a/crates/stdlib/src/posixshmem.rs b/crates/stdlib/src/posixshmem.rs index dd21cd055ce..ac1fae572f1 100644 --- a/crates/stdlib/src/posixshmem.rs +++ b/crates/stdlib/src/posixshmem.rs @@ -1,7 +1,7 @@ -#[cfg(all(unix, not(target_os = "redox"), not(target_os = "android")))] +#[cfg(all(unix, not(target_os = "android")))] pub(crate) use _posixshmem::module_def; -#[cfg(all(unix, not(target_os = "redox"), not(target_os = "android")))] +#[cfg(all(unix, not(target_os = "android")))] #[pymodule] mod _posixshmem { use alloc::ffi::CString; @@ -12,6 +12,7 @@ mod _posixshmem { use rustpython_host_env::shm; #[derive(FromArgs)] + #[from_args(legacy, fname = "shm_open")] struct ShmOpenArgs { #[pyarg(any)] path: PyUtf8StrRef, @@ -23,14 +24,13 @@ mod _posixshmem { #[pyfunction] fn shm_open(args: ShmOpenArgs, vm: &VirtualMachine) -> PyResult { - let name = CString::new(args.path.as_str()).map_err(|e| e.into_pyexception(vm))?; - let mode: core::ffi::c_uint = args.mode as _; - shm::shm_open(name.as_c_str(), args.flags, mode).map_err(|e| e.into_pyexception(vm)) + let path = CString::new(args.path.as_str()).map_err(|e| e.into_pyexception(vm))?; + shm::shm_open(&path, args.flags, args.mode).map_err(|e| e.into_pyexception(vm)) } #[pyfunction] fn shm_unlink(path: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<()> { - let name = CString::new(path.as_str()).map_err(|e| e.into_pyexception(vm))?; - shm::shm_unlink(name.as_c_str()).map_err(|e| e.into_pyexception(vm)) + let path = CString::new(path.as_str()).map_err(|e| e.into_pyexception(vm))?; + shm::shm_unlink(&path).map_err(|e| e.into_pyexception(vm)) } } diff --git a/crates/stdlib/src/posixsubprocess.rs b/crates/stdlib/src/posixsubprocess.rs index f2ee7bbc2fe..7417b75e927 100644 --- a/crates/stdlib/src/posixsubprocess.rs +++ b/crates/stdlib/src/posixsubprocess.rs @@ -1,59 +1,71 @@ // spell-checker:disable use crate::vm::{ - builtins::PyListRef, - function::ArgSequence, - ospath::OsPath, - {PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine}, + AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyBytes, PyBytesRef, PyInt, PyList, PyTuple, PyTupleRef}, + function::{ArgIntoBool, FsPath}, + stdlib::posix::module::{RawGid, RawUid}, }; use rustpython_host_env::posix as host_posix; -use std::{ - io::prelude::*, - os::fd::{AsFd, AsRawFd, BorrowedFd, IntoRawFd, OwnedFd, RawFd}, -}; +use std::io::prelude::*; use alloc::ffi::CString; - use core::{convert::Infallible as Never, ffi::CStr, marker::PhantomData, ops::Deref}; pub(crate) use _posixsubprocess::module_def; #[pymodule] mod _posixsubprocess { - use rustpython_vm::{AsObject, TryFromBorrowedObject}; - use super::*; - use crate::vm::{PyResult, VirtualMachine, convert::IntoPyException}; + use crate::vm::convert::IntoPyException; #[pyfunction] - fn fork_exec(args: ForkExecArgs<'_>, vm: &VirtualMachine) -> PyResult { - // Check for interpreter shutdown when preexec_fn is used - if args.preexec_fn.is_some() - && vm + fn fork_exec(args: ForkExecArgs, vm: &VirtualMachine) -> PyResult { + // Clinic converts scalar controls before entering parent-side preparation. + let close_fds = args.close_fds == ArgIntoBool::TRUE; + let restore_signals = args.restore_signals == ArgIntoBool::TRUE; + let call_setsid = args.call_setsid == ArgIntoBool::TRUE; + let controls = ChildControls { + close_fds, + restore_signals, + call_setsid, + }; + if args.preexec_fn.is_some() { + if vm .state .finalizing .load(core::sync::atomic::Ordering::Acquire) - { - return Err(vm.new_python_finalization_error( - "preexec_fn not supported at interpreter shutdown".to_owned(), - )); + { + return Err(vm.new_python_finalization_error( + "preexec_fn not supported at interpreter shutdown".to_owned(), + )); + } + if !vm.state.is_main_interpreter() { + return Err(vm.new_runtime_error("preexec_fn not supported within subinterpreters")); + } } + if close_fds && args.errpipe_write < 3 { + return Err(vm.new_value_error("errpipe_write must be >= 3")); + } + check_pass_fds(&args.pass_fds, vm)?; - let extra_groups = args - .extra_groups - .as_ref() - .map(|l| Vec::::try_from_borrowed_object(vm, l.as_object())) - .map(|res| res.map(|groups| groups.into_iter().map(|gid| gid.0).collect::>())) - .transpose()?; - let argv = args.args.iter().collect::>(); - let envp = args.env.as_ref().map(CharPtrVec::from_iter); + let prepared = PreparedArgs::new(&args, vm)?; + let argv = prepared.argv.as_ref().map(CharPtrVec::from_iter); + let envp = prepared.env.as_ref().map(CharPtrVec::from_iter); let procargs = ProcArgs { - argv: &argv, + argv: argv.as_deref(), envp: envp.as_deref(), - extra_groups: extra_groups.as_deref(), }; + // The hook observes the original objects, after all native data is ready. + vm.audit("_posixsubprocess.fork_exec", || { + ( + args.executable_list.clone(), + args.args.clone(), + args.env.clone(), + ) + })?; match host_posix::fork().map_err(|err| err.into_pyexception(vm))? { - 0 => exec(&args, procargs, vm), + 0 => exec(&args, &prepared, controls, procargs, vm), child => Ok(child), } } @@ -62,25 +74,249 @@ mod _posixsubprocess { macro_rules! gen_args { ($($field:ident: $t:ty),*$(,)?) => { #[derive(FromArgs)] - struct ForkExecArgs<'fd> { + struct ForkExecArgs { $(#[pyarg(positional)] $field: $t,)* } }; } -struct CStrPathLike { - s: CString, +gen_args! { + args: PyObjectRef, + executable_list: PyObjectRef, + close_fds: ArgIntoBool, + pass_fds: PyTupleRef, + cwd: Option, + env: Option, + p2cread: i32, + p2cwrite: i32, + c2pread: i32, + c2pwrite: i32, + errread: i32, + errwrite: i32, + errpipe_read: i32, + errpipe_write: i32, + restore_signals: ArgIntoBool, + call_setsid: ArgIntoBool, + pgid_to_set: host_posix::pid_t, + gid: Option, + extra_groups: Option, + uid: Option, + child_umask: i32, + preexec_fn: Option, +} + +struct ChildControls { + close_fds: bool, + restore_signals: bool, + call_setsid: bool, +} + +// Everything that can call Python or allocate belongs to the parent, not exec(). +struct PreparedArgs { + executable_list: Vec, + argv: Option>, + env: Option>, + cwd: Option, + // FSConverter may return a bytes subclass whose destructor must wait. + _cwd_bytes: Option, + extra_groups: Option>, + gid: Option, + uid: Option, + pass_fds: Vec, +} + +impl PreparedArgs { + fn new(args: &ForkExecArgs, vm: &VirtualMachine) -> PyResult { + let executable_list = bytes_sequence(&args.executable_list, vm)?; + let argv = if vm.is_none(&args.args) { + None + } else { + Some(prepare_argv(&args.args, vm)?) + }; + let env = args + .env + .as_ref() + .map(|env| bytes_sequence(env, vm)) + .transpose()?; + let cwd_bytes = args + .cwd + .as_ref() + .map(|cwd| filesystem_bytes(cwd, vm)) + .transpose()?; + let cwd = cwd_bytes + .as_ref() + .map(|bytes| CString::new(bytes.as_bytes()).expect("FSConverter checked for NUL")); + let extra_groups = args + .extra_groups + .as_ref() + .map(|groups| prepare_groups(groups, vm)) + .transpose()?; + let gid = args + .gid + .clone() + .map(|gid| RawGid::try_from_object(vm, gid)) + .transpose()?; + let uid = args + .uid + .clone() + .map(|uid| RawUid::try_from_object(vm, uid)) + .transpose()?; + // Repeat conversion here, after all Python callbacks, as CPython does. + let pass_fds = args + .pass_fds + .as_slice() + .iter() + .map(|fd| fd.try_to_ref::(vm)?.try_to_primitive::(vm)) + .collect::>>()?; + Ok(Self { + executable_list, + argv, + env, + cwd, + _cwd_bytes: cwd_bytes, + extra_groups, + gid, + uid, + pass_fds, + }) + } +} + +fn check_pass_fds(pass_fds: &PyTuple, vm: &VirtualMachine) -> PyResult<()> { + let mut previous = -1; + // Tuple subclasses and int subclasses use their stored values, not overrides. + for fd in pass_fds.as_slice() { + let value = fd + .downcast_ref::() + .and_then(|fd| i32::try_from(fd.as_bigint()).ok()); + let Some(value) = value.filter(|value| *value >= 0 && *value > previous) else { + return Err(vm.new_value_error("bad value(s) in fds_to_keep")); + }; + previous = value; + } + Ok(()) +} + +fn bytes_sequence(obj: &PyObject, vm: &VirtualMachine) -> PyResult> { + let sequence = obj.sequence_unchecked(); + let count = sequence.length(vm)?; + let mut strings = Vec::new(); + strings + .try_reserve_exact(count) + .map_err(|_| vm.no_memory_error())?; + for i in 0..count { + let item = sequence.get_item(i as isize, vm)?; + let bytes = item.downcast_ref::().ok_or_else(|| { + vm.new_type_error(format!("expected bytes, {} found", item.class().name())) + })?; + strings.push( + CString::new(bytes.as_bytes()).map_err(|_| vm.new_value_error("embedded null byte"))?, + ); + } + Ok(strings) +} + +// PyUnicode_FSConverter applies PyOS_FSPath, filesystem encoding, then the +// bytes NUL check. PathConverter has different argument and NUL diagnostics. +fn filesystem_bytes(obj: &PyObjectRef, vm: &VirtualMachine) -> PyResult { + let bytes = match FsPath::try_from_path_like(obj.clone(), false, vm)? { + FsPath::Bytes(bytes) => bytes, + FsPath::Str(value) => vm + .ctx + .new_bytes(vm.fsencode(&value)?.as_encoded_bytes().to_vec()), + }; + if bytes.as_bytes().contains(&0) { + return Err(vm.new_value_error("embedded null byte")); + } + Ok(bytes) +} + +// CPython clears temporary tuples/lists from the last element to the first. +// These references can own subclasses with Python destructors; the order is +// observable on both successful preparation and error unwinding. +#[derive(Default)] +struct ReverseReferences(Vec); + +impl Drop for ReverseReferences { + fn drop(&mut self) { + while let Some(_item) = self.0.pop() {} + } } -impl TryFromObject for CStrPathLike { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - let s = OsPath::try_from_object(vm, obj)?.into_cstring(vm)?; - Ok(Self { s }) + +fn prepare_argv(args: &PyObjectRef, vm: &VirtualMachine) -> PyResult> { + // Keep exact lists live across __fspath__ calls. A snapshot would conceal a + // size change or use stale elements after an earlier element replaces them. + let list = args.downcast_ref_if_exact::(vm); + let items; + let slice: &[PyObjectRef] = if let Some(tuple) = args.downcast_ref_if_exact::(vm) { + tuple.as_slice() + } else if list.is_some() { + &[] + } else { + let iter = args.clone().get_iter(vm).map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + vm.new_type_error("argv must be a tuple") + } else { + error + } + })?; + items = ReverseReferences(vm.extract_elements_sized(iter.as_object(), &|| 0, Ok)?); + &items.0 + }; + let count = list.map_or_else(|| slice.len(), |list| list.borrow_vec().len()); + let mut converted = ReverseReferences(Vec::new()); + converted + .0 + .try_reserve_exact(count) + .map_err(|_| vm.no_memory_error())?; + for i in 0..count { + let item = if let Some(list) = list { + let elements = list.borrow_vec(); + if elements.len() != count { + return Err(vm.new_runtime_error("args changed during iteration")); + } + // Retain the item, then release the lock before calling __fspath__. + elements[i].clone() + } else { + slice[i].clone() + }; + converted.0.push(filesystem_bytes(&item, vm)?); } + // CPython retains all converted bytes until native argv is copied. In + // particular, bytes-subclass destructors must not run between conversions. + let mut strings = Vec::new(); + strings + .try_reserve_exact(count) + .map_err(|_| vm.no_memory_error())?; + for bytes in &converted.0 { + strings.push(CString::new(bytes.as_bytes()).expect("FSConverter checked for NUL")); + } + Ok(strings) } -impl AsRef for CStrPathLike { - fn as_ref(&self) -> &CStr { - &self.s + +fn prepare_groups(groups: &PyObject, vm: &VirtualMachine) -> PyResult> { + if groups.downcast_ref::().is_none() { + return Err(vm.new_type_error("setgroups argument must be a list")); } + let sequence = groups.sequence_unchecked(); + let count = sequence.length(vm)?; + if host_posix::SUBPROCESS_MAX_GROUPS.is_some_and(|limit| count > limit) { + return Err(vm.new_value_error("too many extra_groups")); + } + let mut values = Vec::new(); + values + .try_reserve_exact(count) + .map_err(|_| vm.new_memory_error("failed to allocate memory for group list"))?; + for i in 0..count { + let item = sequence.get_item(i as isize, vm)?; + if item.downcast_ref::().is_none() { + return Err(vm.new_type_error("extra_groups must be integers")); + } + let gid = RawGid::try_from_object(vm, item) + .map_err(|_| vm.new_value_error("invalid group id"))?; + values.push(gid.0); + } + Ok(values) } #[derive(Default)] @@ -124,21 +360,11 @@ impl CharPtrSlice<'_> { } } -#[derive(Copy, Clone)] -struct Fd(BorrowedFd<'static>); - -impl TryFromObject for Fd { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - match MaybeFd::try_from_object(vm, obj)? { - MaybeFd::Valid(fd) => Ok(fd), - MaybeFd::Invalid => Err(vm.new_value_error("invalid fd")), - } - } -} +struct Fd(i32); impl Write for Fd { fn write(&mut self, buf: &[u8]) -> std::io::Result { - host_posix::write_fd(self.as_fd(), buf) + host_posix::write_fd_raw(self.0, buf) } fn flush(&mut self) -> std::io::Result<()> { @@ -146,135 +372,24 @@ impl Write for Fd { } } -impl AsRawFd for Fd { - fn as_raw_fd(&self) -> RawFd { - self.0.as_raw_fd() - } -} - -impl IntoRawFd for Fd { - fn into_raw_fd(self) -> RawFd { - self.0.as_raw_fd() - } -} - -impl AsFd for Fd { - fn as_fd(&self) -> BorrowedFd<'_> { - self.0.as_fd() - } -} - -impl From for Fd { - fn from(fd: OwnedFd) -> Self { - Self(unsafe { BorrowedFd::borrow_raw(fd.into_raw_fd()) }) - } -} - -#[derive(Copy, Clone)] -enum MaybeFd { - Valid(Fd), - Invalid, -} - -impl TryFromObject for MaybeFd { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - let fd = i32::try_from_object(vm, obj)?; - Ok(if fd == -1 { - Self::Invalid - } else { - Self::Valid(Fd(unsafe { BorrowedFd::borrow_raw(fd) })) - }) - } -} - -impl AsRawFd for MaybeFd { - fn as_raw_fd(&self) -> RawFd { - match self { - Self::Valid(fd) => fd.as_raw_fd(), - Self::Invalid => -1, - } - } -} - -#[derive(Copy, Clone)] -struct RawUid(u32); - -#[derive(Copy, Clone)] -struct RawGid(u32); - -fn try_from_id(vm: &VirtualMachine, obj: &PyObject, typ_name: &str) -> PyResult { - use core::cmp::Ordering; - let i = obj - .try_to_ref::(vm) - .map_err(|_| { - vm.new_type_error(format!( - "an integer is required (got type {})", - obj.class().name() - )) - })? - .try_to_primitive::(vm)?; - - match i.cmp(&-1) { - Ordering::Greater => Ok(i - .try_into() - .map_err(|_| vm.new_overflow_error(format!("{typ_name} is larger than maximum")))?), - Ordering::Less => Err(vm.new_overflow_error(format!("{typ_name} is less than minimum"))), - Ordering::Equal => Ok(-1i32 as u32), - } -} - -impl TryFromObject for RawUid { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, &obj, "uid").map(Self) - } -} - -impl TryFromObject for RawGid { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, &obj, "gid").map(Self) - } -} - -// impl - -gen_args! { - args: ArgSequence /* list */, - executable_list: ArgSequence /* list */, - close_fds: bool, - pass_fds: ArgSequence>, - cwd: Option, - env: Option>, - p2cread: MaybeFd, - p2cwrite: MaybeFd, - c2pread: MaybeFd, - c2pwrite: MaybeFd, - errread: MaybeFd, - errwrite: MaybeFd, - errpipe_read: Fd, - errpipe_write: Fd, - restore_signals: bool, - call_setsid: bool, - pgid_to_set: host_posix::pid_t, - gid: Option, - extra_groups: Option, - uid: Option, - child_umask: i32, - preexec_fn: Option, -} - // can't reallocate inside of exec(), so we reallocate prior to fork() and pass this along struct ProcArgs<'a> { - argv: &'a CharPtrSlice<'a>, + argv: Option<&'a CharPtrSlice<'a>>, envp: Option<&'a CharPtrSlice<'a>>, - extra_groups: Option<&'a [u32]>, } -fn exec(args: &ForkExecArgs<'_>, procargs: ProcArgs<'_>, vm: &VirtualMachine) -> ! { +fn exec( + args: &ForkExecArgs, + prepared: &PreparedArgs, + controls: ChildControls, + procargs: ProcArgs<'_>, + vm: &VirtualMachine, +) -> ! { let mut ctx = ExecErrorContext::NoExec; - match exec_inner(args, procargs, &mut ctx, vm) { + match exec_inner(args, prepared, controls, procargs, &mut ctx, vm) { Ok(x) => match x {}, Err(e) => { - let mut pipe = args.errpipe_write; + let mut pipe = Fd(args.errpipe_write); if matches!(ctx, ExecErrorContext::PreExec) { // For preexec_fn errors, use SubprocessError format (errno=0) let _ = write!(pipe, "SubprocessError:0:{}", ctx.as_msg()); @@ -283,7 +398,7 @@ fn exec(args: &ForkExecArgs<'_>, procargs: ProcArgs<'_>, vm: &VirtualMachine) -> let errno = e.raw_os_error().unwrap_or(0); let _ = write!(pipe, "OSError:{errno:x}:{}", ctx.as_msg()); } - rustpython_host_env::os::exit(255) + rustpython_host_env::os::exit_immediately(255) } } } @@ -307,38 +422,40 @@ impl ExecErrorContext { } fn exec_inner( - args: &ForkExecArgs<'_>, + args: &ForkExecArgs, + prepared: &PreparedArgs, + controls: ChildControls, procargs: ProcArgs<'_>, ctx: &mut ExecErrorContext, vm: &VirtualMachine, ) -> std::io::Result { - host_posix::setup_child_fds( - args.pass_fds.as_slice(), - args.errpipe_write.as_fd(), - args.p2cread.as_raw_fd(), - args.p2cwrite.as_raw_fd(), - args.c2pread.as_raw_fd(), - args.c2pwrite.as_raw_fd(), - args.errread.as_raw_fd(), - args.errwrite.as_raw_fd(), - args.errpipe_read.as_raw_fd(), + host_posix::setup_child_fds_raw( + prepared.pass_fds.as_slice(), + args.errpipe_write, + args.p2cread, + args.p2cwrite, + args.c2pread, + args.c2pwrite, + args.errread, + args.errwrite, + args.errpipe_read, )?; - if let Some(ref cwd) = args.cwd { - host_posix::chdir(cwd.s.as_c_str()).inspect_err(|_| *ctx = ExecErrorContext::ChDir)? + if let Some(ref cwd) = prepared.cwd { + host_posix::chdir(cwd.as_c_str()).inspect_err(|_| *ctx = ExecErrorContext::ChDir)? } host_posix::set_umask(args.child_umask); - if args.restore_signals { + if controls.restore_signals { host_posix::restore_signals(); } - host_posix::setsid_if_needed(args.call_setsid)?; + host_posix::setsid_if_needed(controls.call_setsid)?; host_posix::setpgid_if_needed(args.pgid_to_set)?; - host_posix::setgroups_if_needed(procargs.extra_groups)?; - host_posix::setregid_if_needed(args.gid.map(|gid| gid.0))?; - host_posix::setreuid_if_needed(args.uid.map(|uid| uid.0))?; + host_posix::setgroups_if_needed(prepared.extra_groups.as_deref())?; + host_posix::setregid_if_needed(prepared.gid.map(|gid| gid.0))?; + host_posix::setreuid_if_needed(prepared.uid.map(|uid| uid.0))?; // Call preexec_fn after all process setup but before closing FDs if let Some(ref preexec_fn) = args.preexec_fn { @@ -354,13 +471,15 @@ fn exec_inner( *ctx = ExecErrorContext::Exec; - if args.close_fds { - host_posix::close_fds(2, args.pass_fds.as_slice()); + if controls.close_fds { + host_posix::close_fds_raw(2, prepared.pass_fds.as_slice()); } let err = host_posix::exec_replace( - args.executable_list.as_slice(), - procargs.argv.as_ptr(), + prepared.executable_list.as_slice(), + procargs + .argv + .map_or(core::ptr::null(), CharPtrSlice::as_ptr), procargs.envp.map(CharPtrSlice::as_ptr), ); Err(std::io::Error::from_raw_os_error(err as i32)) diff --git a/crates/stdlib/src/pyexpat.rs b/crates/stdlib/src/pyexpat.rs index 5a516dd7821..04c1fb03586 100644 --- a/crates/stdlib/src/pyexpat.rs +++ b/crates/stdlib/src/pyexpat.rs @@ -47,11 +47,9 @@ //! consumed everything fed so far and it is safe to return control to //! Python; `ParserMsg::Finished`/`Error` mean the thread has exited. //! - If a handler raises, `pump` stops dispatching and propagates the error -//! immediately, but leaves the parser thread and channel alone (any -//! already-produced events stay queued) so the *next* `Parse()` call -//! resumes exactly where dispatch left off, mirroring libexpat (a callback -//! exception aborts that `XML_Parse()` call without corrupting the -//! parser's internal state). +//! immediately, clears registered handlers, and stops the backend. Like +//! libexpat's non-resumable callback abort, later `Parse()` calls report +//! that parsing has finished. //! - Calling `Parse()`/`ParseFile()` reentrantly (e.g. from within a //! handler) would deadlock waiting on a channel that same call is meant to //! drain, so it is rejected with a `RuntimeError` via a `busy` flag @@ -168,15 +166,19 @@ mod _pyexpat { use crate::vm::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyBytesRef, PyException, PyModule, PyStr, PyStrRef, PyType, PyUtf8StrRef}, + builtins::{PyException, PyInt, PyModule, PyStr, PyStrRef, PyType, PyUtf8StrRef}, extend_module, - function::{ArgBytesLike, Either, IntoFuncArgs, OptionalArg, OptionalOption}, + function::{ + ArgBytesLike, ArgIndex, ArgStrOrBytesLike, IntoFuncArgs, OptionalArg, OptionalOption, + PySetterValue, + }, types::Constructor, }; + use alloc::borrow::Cow; use alloc::collections::VecDeque; use alloc::rc::Rc; use core::cell::RefCell; - use core::sync::atomic::{AtomicBool, Ordering}; + use core::sync::atomic::{AtomicBool, AtomicI32, AtomicUsize, Ordering}; use rustpython_common::lock::PyRwLock; use std::io::Read; use xml::common::Position; @@ -187,7 +189,14 @@ mod _pyexpat { // Add submodules let model = super::_model::module_def(&vm.ctx).create_module(vm)?; - let errors = super::_errors::module_def(&vm.ctx).create_module(vm)?; + let errors_def = super::_errors::module_def(&vm.ctx); + let errors = errors_def.create_module(vm)?; + errors_def.exec_module(vm, &errors)?; + vm.sys_module.get_attr("modules", vm)?.set_item( + "pyexpat.errors", + errors.clone().into(), + vm, + )?; extend_module!(vm, module, { "model" => model, @@ -197,8 +206,121 @@ mod _pyexpat { Ok(()) } + #[pyfunction(name = "ErrorString")] + fn error_string(code: ArgIndex, vm: &VirtualMachine) -> PyResult> { + let code = code + .into_int_ref() + .try_to_primitive::(vm)?; + // CPython converts a C long to int before calling XML_ErrorString. + let index = (code as core::ffi::c_int).wrapping_sub(1) as usize; + Ok(super::_errors::ERRORS + .get(index) + .map(|(_, message)| *message)) + } + type MutableObject = PyRwLock; + // Do not use Encoding::from_str here: xml-rs also accepts name prefixes. + fn native_encoding(name: &str) -> Option { + match name.to_ascii_uppercase().as_str() { + "UTF-8" => Some(xml::Encoding::Utf8), + "UTF-16" => Some(xml::Encoding::Utf16), + "UTF-16LE" => Some(xml::Encoding::Utf16Le), + "UTF-16BE" => Some(xml::Encoding::Utf16Be), + "ISO-8859-1" => Some(xml::Encoding::Latin1), + "US-ASCII" => Some(xml::Encoding::Ascii), + _ => None, + } + } + + /// xml-rs emits StartDocument even without a declaration and fills in + /// omitted values. Retain only the initial declaration to recover that + /// information; the backend still validates it before any callback. + #[derive(Debug, Default)] + struct DeclarationPrefix { + bytes: Vec, + complete: bool, + } + + impl DeclarationPrefix { + fn text(&self) -> String { + let bytes = &self.bytes; + let (little, offset) = if bytes.starts_with(&[0xff, 0xfe]) { + (true, 2) + } else if bytes.starts_with(&[0xfe, 0xff]) { + (false, 2) + } else if bytes.starts_with(&[b'<', 0]) { + (true, 0) + } else if bytes.starts_with(&[0, b'<']) { + (false, 0) + } else { + return String::from_utf8_lossy( + bytes.strip_prefix(&[0xef, 0xbb, 0xbf]).unwrap_or(bytes), + ) + .into_owned(); + }; + let units = bytes[offset..].as_chunks::<2>().0.iter().map(|&pair| { + if little { + u16::from_le_bytes(pair) + } else { + u16::from_be_bytes(pair) + } + }); + char::decode_utf16(units) + .map(|c| c.unwrap_or(char::REPLACEMENT_CHARACTER)) + .collect() + } + + fn record(&mut self, chunk: &[u8]) { + if self.complete { + return; + } + for &byte in chunk { + self.bytes.push(byte); + if self.bytes.len() >= 2 + && self.bytes.len() <= 16 + && ![0xef, 0xbb, 0xbf].starts_with(&self.bytes) + { + let text = self.text(); + if (!"") + || (self.bytes.len().is_multiple_of(2) + && (self.bytes.ends_with(&[b'?', 0, b'>', 0]) + || self.bytes.ends_with(&[0, b'?', 0, b'>']))) + { + self.complete = true; + break; + } + } + } + + fn take(&mut self) -> Option { + let text = self.text(); + self.bytes.clear(); + self.complete = true; + text.strip_prefix("(text: &'a str, name: &str) -> Option<&'a str> { + let (_, value) = text.split_once(name)?; + let value = value.trim_start().strip_prefix('=')?.trim_start(); + let quote = value.chars().next()?; + value.get(1..)?.split(quote).next() + } + #[pyattr(name = "version_info")] pub(super) const VERSION_INFO: (u32, u32, u32) = (2, 7, 1); @@ -217,6 +339,14 @@ mod _pyexpat { #[pytraverse(skip)] namespace_separator: Option, #[pytraverse(skip)] + encoding: Option, + #[pytraverse(skip)] + declaration: PyRwLock, + #[pytraverse(skip)] + initial_bytes: PyRwLock>, + #[pytraverse(skip)] + input_unicode: PyRwLock>, + #[pytraverse(skip)] base: PyRwLock>, // Position of the last event produced, exposed as CurrentLineNumber / // CurrentColumnNumber / CurrentByteIndex (mirrors libexpat's @@ -243,15 +373,40 @@ mod _pyexpat { // drain. #[pytraverse(skip)] busy: AtomicBool, - // Set once EndDocument has been observed, so further Parse() calls - // become harmless no-ops instead of starting a new document. + // Prevent creating another backend after finalization or fork failure. #[pytraverse(skip)] finished: AtomicBool, + // Zero while active; otherwise the error returned on another Parse call. + // Successful completion and callback aborts use XML_ERROR_FINISHED. + #[pytraverse(skip)] + terminal_error_code: AtomicI32, + #[pytraverse(skip)] + namespace_stack: PyRwLock)>>, + #[pytraverse(skip)] + element_depth: AtomicUsize, + #[pytraverse(skip)] + document_element_closed: AtomicBool, + #[pytraverse(skip)] + reparse_deferral_enabled: AtomicBool, + #[pytraverse(skip)] + parameter_entity_parsing: AtomicI32, + #[pytraverse(skip)] + use_foreign_dtd: AtomicBool, + #[pytraverse(skip)] + standalone: AtomicBool, + #[pytraverse(skip)] + external_subset_handled: AtomicBool, + #[pytraverse(skip)] + started: AtomicBool, + #[pytraverse(skip)] + external_entity: Option, + parent: Option, start_element: MutableObject, end_element: MutableObject, character_data: MutableObject, entity_decl: MutableObject, - buffer_text: MutableObject, + #[pytraverse(skip)] + character_buffer: PyRwLock, namespace_prefixes: MutableObject, ordered_attributes: MutableObject, specified_attributes: MutableObject, @@ -277,6 +432,19 @@ mod _pyexpat { attlist_decl: MutableObject, skipped_entity: MutableObject, } + #[derive(Debug)] + struct CharacterBuffer { + size: usize, + data: Option, + } + + fn new_character_buffer(size: usize, vm: &VirtualMachine) -> PyResult { + let mut data = String::new(); + data.try_reserve_exact(size) + .map_err(|_| vm.new_memory_error(""))?; + Ok(data) + } + type PyExpatLikeXmlParserRef = PyRef; #[inline] @@ -296,6 +464,58 @@ mod _pyexpat { Ok(()) } + #[derive(Debug)] + struct ExternalEntity { + context: Option, + encoding: Option, + } + + struct Doctype { + name: String, + system_id: Option, + public_id: Option, + has_internal_subset: bool, + } + + impl Doctype { + fn from_reader(parser: &xml::EventReader, event: &XmlEvent) -> Option { + let XmlEvent::Doctype { syntax } = event else { + return None; + }; + let ids = parser.doctype_ids()?; + let mut quote = None; + let has_internal_subset = syntax.chars().any(|character| { + if let Some(delimiter) = quote { + if character == delimiter { + quote = None; + } + } else if matches!(character, '\'' | '"') { + quote = Some(character); + } else if character == '[' { + return true; + } + false + }); + Some(Self { + name: ids.name().to_owned(), + system_id: ids.system_id().map(str::to_owned), + public_id: ids.public_id().map(str::to_owned), + has_internal_subset, + }) + } + } + + fn is_incomplete(error: &xml::reader::Error) -> bool { + match error.kind() { + xml::reader::ErrorKind::UnexpectedEof => true, + xml::reader::ErrorKind::Syntax(message) => { + message.starts_with("Unexpected end of stream") + || message.starts_with("Unclosed false, + } + } + /// Tracks byte offsets of line starts as bytes are handed to the parser /// thread, so that `TextPosition` (row/column, in characters) can be /// translated into an approximation of libexpat's `CurrentByteIndex` @@ -531,6 +751,7 @@ mod _pyexpat { #[cfg(not(target_arch = "wasm32"))] struct PreparedEvent { event: XmlEvent, + doctype: Option, line: i64, column: i64, byte_index: i64, @@ -547,10 +768,8 @@ mod _pyexpat { Event(PreparedEvent), /// `EndDocument` was reached; the parser thread has exited. Finished, - /// xml-rs reported a parse error. Mirrors the previous - /// whole-buffer implementation, which silently stopped dispatching - /// on the first parse error rather than raising `ExpatError`. - Error, + /// xml-rs reported a parse error, to be raised on the calling thread. + Error(xml::reader::Error), } /// Set, once and permanently, by a `pthread_atfork` child hook the @@ -714,6 +933,7 @@ mod _pyexpat { let pos = parser.position(); let byte_index = tracker.borrow_mut().byte_index_for(pos); let msg = ParserMsg::Event(PreparedEvent { + doctype: Doctype::from_reader(&parser, &event), event, line: pos.row() as i64 + 1, column: pos.column() as i64, @@ -723,8 +943,8 @@ mod _pyexpat { break; } } - Err(_) => { - let _ = tx.send(ParserMsg::Error); + Err(error) => { + let _ = tx.send(ParserMsg::Error(error)); break; } } @@ -805,8 +1025,11 @@ mod _pyexpat { #[pyclass] impl PyExpatLikeXmlParser { fn new( + encoding: Option, namespace_separator: Option, intern: OptionalOption, + parent: Option, + external_entity: Option, vm: &VirtualMachine, ) -> PyExpatLikeXmlParserRef { let intern_dict = match intern { @@ -815,6 +1038,10 @@ mod _pyexpat { OptionalArg::Present(None) => vm.ctx.none(), }; Self { + encoding, + declaration: PyRwLock::new(DeclarationPrefix::default()), + initial_bytes: PyRwLock::new(Vec::new()), + input_unicode: PyRwLock::new(None), namespace_separator, base: PyRwLock::new(None), current_line: PyRwLock::new(1), @@ -823,11 +1050,26 @@ mod _pyexpat { backend: PyRwLock::new(None), busy: AtomicBool::new(false), finished: AtomicBool::new(false), + terminal_error_code: AtomicI32::new(0), + namespace_stack: PyRwLock::new(Vec::new()), + element_depth: AtomicUsize::new(0), + document_element_closed: AtomicBool::new(false), + reparse_deferral_enabled: AtomicBool::new(true), + parameter_entity_parsing: AtomicI32::new(XML_PARAM_ENTITY_PARSING_NEVER), + use_foreign_dtd: AtomicBool::new(false), + standalone: AtomicBool::new(false), + external_subset_handled: AtomicBool::new(false), + started: AtomicBool::new(false), + external_entity, + parent, start_element: MutableObject::new(vm.ctx.none()), end_element: MutableObject::new(vm.ctx.none()), character_data: MutableObject::new(vm.ctx.none()), entity_decl: MutableObject::new(vm.ctx.none()), - buffer_text: MutableObject::new(vm.ctx.new_bool(false).into()), + character_buffer: PyRwLock::new(CharacterBuffer { + size: 8192, + data: None, + }), namespace_prefixes: MutableObject::new(vm.ctx.new_bool(false).into()), ordered_attributes: MutableObject::new(vm.ctx.new_bool(false).into()), specified_attributes: MutableObject::new(vm.ctx.new_bool(false).into()), @@ -861,15 +1103,21 @@ mod _pyexpat { create_property!(ctx, attributes, "StartElementHandler", class, start_element); create_property!(ctx, attributes, "EndElementHandler", class, end_element); - create_property!( - ctx, - attributes, + let attr = ctx.new_static_getset( "CharacterDataHandler", class, - character_data + |this: &Py| this.character_data.read().clone(), + |this: &Py, value: PySetterValue, vm: &VirtualMachine| { + let PySetterValue::Assign(value) = value else { + return Err(vm.new_runtime_error("Cannot delete attribute")); + }; + this.flush_character_buffer(vm)?; + let _old_handler = core::mem::replace(&mut *this.character_data.write(), value); + Ok(()) + }, ); + attributes.insert(ctx.intern_str("CharacterDataHandler"), attr.into()); create_property!(ctx, attributes, "EntityDeclHandler", class, entity_decl); - create_bool_property!(ctx, attributes, "buffer_text", class, buffer_text); create_bool_property!( ctx, attributes, @@ -891,27 +1139,15 @@ mod _pyexpat { class, specified_attributes ); - create_readonly_int_property!( - ctx, - attributes, - "CurrentLineNumber", - class, - current_line - ); - create_readonly_int_property!( - ctx, - attributes, - "CurrentColumnNumber", - class, - current_column - ); - create_readonly_int_property!( - ctx, - attributes, - "CurrentByteIndex", - class, - current_byte_index - ); + for name in ["CurrentLineNumber", "ErrorLineNumber"] { + create_readonly_int_property!(ctx, attributes, name, class, current_line); + } + for name in ["CurrentColumnNumber", "ErrorColumnNumber"] { + create_readonly_int_property!(ctx, attributes, name, class, current_column); + } + for name in ["CurrentByteIndex", "ErrorByteIndex"] { + create_readonly_int_property!(ctx, attributes, name, class, current_byte_index); + } // Additional handlers (stubs for compatibility) create_property!( ctx, @@ -1005,38 +1241,156 @@ mod _pyexpat { ); } - fn create_config(&self) -> xml::ParserConfig { + fn create_config( + &self, + unicode_input: bool, + sniffed: Option, + ) -> xml::ParserConfig { + let encoding = if unicode_input { + Some(xml::Encoding::Utf8) + } else { + self.encoding + .as_deref() + .and_then(native_encoding) + .or(sniffed) + }; xml::ParserConfig::new() + .override_encoding(encoding) + .ignore_invalid_encoding_declarations( + unicode_input || self.encoding.as_deref().and_then(native_encoding).is_some(), + ) + .allow_multiple_root_elements(false) .cdata_to_characters(false) .coalesce_characters(false) .ignore_comments(false) .whitespace_to_characters(true) } + #[pymethod(name = "GetReparseDeferralEnabled")] + fn get_reparse_deferral_enabled(zelf: &Py) -> bool { + zelf.reparse_deferral_enabled.load(Ordering::Relaxed) + } + + #[pymethod(name = "SetReparseDeferralEnabled")] + fn set_reparse_deferral_enabled(zelf: &Py, enabled: bool) { + // The streaming backend resumes a suspended parser rather than + // reparsing an unfinished token, so it needs no deferral to avoid + // quadratic work. Preserve the setting used by callers that + // temporarily disable it to flush already supplied input. + zelf.reparse_deferral_enabled + .store(enabled, Ordering::Relaxed); + } + #[pymethod(name = "SetParamEntityParsing")] - fn set_param_entity_parsing(_zelf: &Py, _flag: i32) -> i32 { - // Compatibility shim: xml.sax requires this setup API, but xml-rs - // does not expose Expat parameter entity parsing configuration. + fn set_param_entity_parsing(zelf: &Py, flag: i32) -> i32 { + if zelf.started.load(Ordering::Relaxed) && !zelf.finished.load(Ordering::Relaxed) { + return 0; + } + zelf.parameter_entity_parsing.store(flag, Ordering::Relaxed); 1 } #[pymethod(name = "UseForeignDTD")] - fn use_foreign_dtd(_zelf: &Py, _flag: OptionalArg) { - // Compatibility shim: CPython's implementation forwards the flag to - // libexpat's XML_UseForeignDTD, which lets a DTD handler splice in an - // external subset for documents that only declare one (e.g. via - // NotStandaloneHandler). The xml-rs backend used here has no such hook - // and always parses documents standalone, so the flag is accepted and - // ignored purely so callers that toggle this setting (e.g. genshi) don't - // fail with AttributeError. + fn use_foreign_dtd( + zelf: &Py, + flag: OptionalArg, + vm: &VirtualMachine, + ) -> PyResult<()> { + if zelf.started.load(Ordering::Relaxed) && !zelf.finished.load(Ordering::Relaxed) { + return Err(zelf.handler_error( + vm, + 26, + "cannot change setting once parsing has begun", + )?); + } + zelf.use_foreign_dtd + .store(flag.unwrap_or(true), Ordering::Relaxed); + Ok(()) + } + + #[pymethod(name = "ExternalEntityParserCreate")] + fn external_entity_parser_create( + zelf: PyRef, + context: Option, + encoding: OptionalArg, + vm: &VirtualMachine, + ) -> PyResult { + let context = context.map(|s| s.as_str().to_owned()); + let encoding = encoding.into_option().map(|s| s.as_str().to_owned()); + if context.as_ref().is_some_and(|s| s.contains('\0')) + || encoding.as_ref().is_some_and(|s| s.contains('\0')) + { + return Err(vm.new_value_error("embedded null character")); + } + let child = Self::new( + encoding.clone(), + zelf.namespace_separator.clone(), + OptionalArg::Present(Some(zelf.intern.clone())), + Some(zelf.clone()), + Some(ExternalEntity { context, encoding }), + vm, + ); + child.reparse_deferral_enabled.store( + zelf.reparse_deferral_enabled.load(Ordering::Relaxed), + Ordering::Relaxed, + ); + child.parameter_entity_parsing.store( + zelf.parameter_entity_parsing.load(Ordering::Relaxed), + Ordering::Relaxed, + ); + { + let parent = zelf.character_buffer.read(); + *child.character_buffer.write() = CharacterBuffer { + size: parent.size, + data: parent + .data + .as_ref() + .map(|_| new_character_buffer(parent.size, vm)) + .transpose()?, + }; + } + for (source, target) in [ + (&zelf.namespace_prefixes, &child.namespace_prefixes), + (&zelf.ordered_attributes, &child.ordered_attributes), + (&zelf.specified_attributes, &child.specified_attributes), + (&zelf.start_element, &child.start_element), + (&zelf.end_element, &child.end_element), + (&zelf.character_data, &child.character_data), + (&zelf.entity_decl, &child.entity_decl), + (&zelf.processing_instruction, &child.processing_instruction), + (&zelf.unparsed_entity_decl, &child.unparsed_entity_decl), + (&zelf.notation_decl, &child.notation_decl), + (&zelf.start_namespace_decl, &child.start_namespace_decl), + (&zelf.end_namespace_decl, &child.end_namespace_decl), + (&zelf.comment, &child.comment), + (&zelf.start_cdata_section, &child.start_cdata_section), + (&zelf.end_cdata_section, &child.end_cdata_section), + (&zelf.default, &child.default), + (&zelf.default_expand, &child.default_expand), + (&zelf.not_standalone, &child.not_standalone), + (&zelf.external_entity_ref, &child.external_entity_ref), + (&zelf.start_doctype_decl, &child.start_doctype_decl), + (&zelf.end_doctype_decl, &child.end_doctype_decl), + (&zelf.xml_decl, &child.xml_decl), + (&zelf.element_decl, &child.element_decl), + (&zelf.attlist_decl, &child.attlist_decl), + (&zelf.skipped_entity, &child.skipped_entity), + ] { + *target.write() = source.read().clone(); + } + Ok(child) } #[pymethod(name = "SetBase")] - fn set_base(zelf: &Py, base: PyStrRef) { + fn set_base(zelf: &Py, base: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult<()> { + if base.as_str().contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } // Store-only compatibility state for xml.sax locator APIs. The // xml-rs backend still does not perform Expat-style base URI // resolution for external entities. - *zelf.base.write() = Some(AsRef::::as_ref(&base).to_owned()); + *zelf.base.write() = Some(base.as_str().to_owned()); + Ok(()) } #[pymethod(name = "GetBase")] @@ -1047,10 +1401,239 @@ mod _pyexpat { ) } + #[pygetset] + fn buffer_text(zelf: &Py) -> bool { + zelf.character_buffer.read().data.is_some() + } + + #[pygetset(setter)] + fn set_buffer_text( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let PySetterValue::Assign(value) = value else { + return Err(vm.new_runtime_error("Cannot delete attribute")); + }; + if value.is_true(vm)? { + let mut buffer = zelf.character_buffer.write(); + if buffer.data.is_none() { + buffer.data = Some(new_character_buffer(buffer.size, vm)?); + } + } else if zelf.character_buffer.read().data.is_some() { + zelf.flush_character_buffer(vm)?; + zelf.character_buffer.write().data = None; + } + Ok(()) + } + + #[pygetset] + fn buffer_size(zelf: &Py) -> usize { + zelf.character_buffer.read().size + } + + #[pygetset(setter)] + fn set_buffer_size( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let PySetterValue::Assign(value) = value else { + return Err(vm.new_runtime_error("Cannot delete attribute")); + }; + if !value.fast_isinstance(PyInt::class(&vm.ctx)) { + return Err(vm.new_type_error("buffer_size must be an integer")); + } + let size = core::ffi::c_long::try_from_object(vm, value)?; + if size <= 0 { + return Err(vm.new_value_error("buffer_size must be greater than zero")); + } + if size as usize == zelf.character_buffer.read().size { + return Ok(()); + } + if size > i32::MAX as core::ffi::c_long { + return Err(vm.new_value_error(format!( + "buffer_size must not be greater than {}", + i32::MAX + ))); + } + zelf.flush_character_buffer(vm)?; + { + // Match CPython's release-before-allocation ordering: failure + // disables buffering while retaining the previous size. + let _old_data = zelf.character_buffer.write().data.take(); + } + let data = new_character_buffer(size as usize, vm)?; + *zelf.character_buffer.write() = CharacterBuffer { + size: size as usize, + data: Some(data), + }; + Ok(()) + } + + #[pygetset] + fn buffer_used(zelf: &Py) -> usize { + zelf.character_buffer + .read() + .data + .as_ref() + .map_or(0, String::len) + } + + fn after_callback(&self, result: PyResult, vm: &VirtualMachine) -> PyResult { + if result.is_err() { + // CPython call_with_frame/flag_error stops Expat without + // allowing resumption and clears every handler, not just the one + // which raised. Do not retain queued callbacks after failure. + self.terminal_error_code.store(36, Ordering::SeqCst); + self.finished.store(true, Ordering::SeqCst); + self.teardown_backend(); + for handler in [ + &self.start_element, + &self.end_element, + &self.character_data, + &self.entity_decl, + &self.processing_instruction, + &self.unparsed_entity_decl, + &self.notation_decl, + &self.start_namespace_decl, + &self.end_namespace_decl, + &self.comment, + &self.start_cdata_section, + &self.end_cdata_section, + &self.default, + &self.default_expand, + &self.not_standalone, + &self.external_entity_ref, + &self.start_doctype_decl, + &self.end_doctype_decl, + &self.xml_decl, + &self.element_decl, + &self.attlist_decl, + &self.skipped_entity, + ] { + // Releasing a callable may execute Python; the table lock + // must be gone before that callable is released. + let _old_handler = core::mem::replace(&mut *handler.write(), vm.ctx.none()); + } + } + result + } + + fn flush_character_buffer(&self, vm: &VirtualMachine) -> PyResult<()> { + let text = { + let mut buffer = self.character_buffer.write(); + let Some(data) = buffer.data.as_mut().filter(|data| !data.is_empty()) else { + return Ok(()); + }; + let text = data.clone(); + data.clear(); + text + }; + // Clear used data before invoking Python: the callback can resize, + // disable buffering, or replace itself without flushing recursively. + self.after_callback( + invoke_handler(vm, &self.character_data, (vm.ctx.new_str(text),)), + vm, + ) + } + + fn character_data(&self, vm: &VirtualMachine, text: String) -> PyResult<()> { + if vm.is_none(&self.character_data.read()) { + return Ok(()); + } + let needs_flush = { + let buffer = self.character_buffer.read(); + buffer + .data + .as_ref() + .is_some_and(|data| text.len() > buffer.size - data.len()) + }; + if needs_flush { + self.flush_character_buffer(vm)?; + if vm.is_none(&self.character_data.read()) { + return Ok(()); + } + } + { + let mut buffer = self.character_buffer.write(); + let size = buffer.size; + if let Some(data) = buffer.data.as_mut() + && text.len() <= size - data.len() + { + data.push_str(&text); + return Ok(()); + } + } + // An oversized backend event is delivered whole, not split into + // artificial chunks to imitate Expat's internal input conversion. + self.after_callback( + invoke_handler(vm, &self.character_data, (vm.ctx.new_str(text),)), + vm, + ) + } + + fn invoke_buffered_handler( + &self, + vm: &VirtualMachine, + handler: &MutableObject, + args: T, + ) -> PyResult<()> { + if !vm.is_none(&handler.read()) { + self.flush_character_buffer(vm)?; + } + self.after_callback(invoke_handler(vm, handler, args), vm) + } + + fn invoke_buffered_int_handler( + &self, + vm: &VirtualMachine, + handler: &MutableObject, + name: &str, + args: T, + ) -> PyResult> { + if !vm.is_none(&handler.read()) { + self.flush_character_buffer(vm)?; + } + let handler = handler.read().clone(); + if vm.is_none(&handler) { + return Ok(None); + } + let result = self.after_callback(handler.call(args, vm), vm)?; + core::ffi::c_long::try_from_object(vm, result) + .map(|value| { + // Expat callbacks convert C long to int. These types have the + // same width on Windows, but differ on 64-bit Unix targets. + #[allow(clippy::unnecessary_cast)] + let value = value as i32; + Some(value) + }) + .inspect_err(|error| { + let _ = error.add_note_str( + vm.ctx + .new_str(format!("invalid '{name}' event handler return value")), + vm, + ); + }) + } + /// Construct element name with namespace if separator is set - fn make_name(&self, name: &xml::name::OwnedName) -> String { + fn make_name(&self, name: &xml::name::OwnedName, vm: &VirtualMachine) -> String { match (&self.namespace_separator, &name.namespace) { - (Some(sep), Some(ns)) => format!("{}{}{}", ns, sep, name.local_name), + (Some(sep), Some(ns)) if !ns.is_empty() => { + let mut expanded = format!("{}{}{}", ns, sep, name.local_name); + if self.namespace_prefixes.read().is(&vm.ctx.true_value) + && let Some(prefix) = &name.prefix + { + expanded.push_str(sep); + expanded.push_str(prefix); + } + expanded + } + (None, _) => match &name.prefix { + Some(prefix) => format!("{prefix}:{}", name.local_name), + None => name.local_name.clone(), + }, _ => name.local_name.clone(), } } @@ -1083,17 +1666,131 @@ mod _pyexpat { /// Dispatch a single parser event to the registered handlers. Runs on /// the calling thread only -- see the module doc comment. - fn dispatch(&self, vm: &VirtualMachine, event: XmlEvent) -> PyResult<()> { + fn dispatch( + &self, + vm: &VirtualMachine, + event: XmlEvent, + doctype: Option, + ) -> PyResult<()> { match event { + XmlEvent::StartDocument { standalone, .. } => { + self.standalone + .store(standalone == Some(true), Ordering::Relaxed); + let declaration = self.declaration.write().take(); + if let Some(declaration) = declaration { + self.invoke_buffered_handler( + vm, + &self.xml_decl, + ( + declaration_value(&declaration, "version"), + declaration_value(&declaration, "encoding"), + standalone.map_or(-1, i32::from), + ), + )?; + } + Ok(()) + } + XmlEvent::Doctype { .. } => { + if let Some(doctype) = doctype { + self.external_subset_handled.store(true, Ordering::Relaxed); + let parse_entities = self.parse_parameter_entities(); + if doctype.system_id.is_some() + && !parse_entities + && !self.standalone.load(Ordering::Relaxed) + && self.invoke_buffered_int_handler( + vm, + &self.not_standalone, + "NotStandalone", + (), + )? == Some(0) + { + return Err(self.handler_error( + vm, + 22, + "document is not standalone", + )?); + } + let name = self.intern_name(vm, doctype.name); + let system_id = doctype.system_id.map(|s| vm.ctx.new_str(s)); + let public_id = doctype.public_id.map(|s| vm.ctx.new_str(s)); + self.invoke_buffered_handler( + vm, + &self.start_doctype_decl, + ( + name, + system_id.clone(), + public_id.clone(), + i32::from(doctype.has_internal_subset), + ), + )?; + if parse_entities + && (system_id.is_some() || self.use_foreign_dtd.load(Ordering::Relaxed)) + { + self.handle_external_subset(vm, system_id, public_id)?; + } + self.invoke_buffered_handler(vm, &self.end_doctype_decl, ())?; + } + Ok(()) + } XmlEvent::StartElement { - name, attributes, .. + name, + attributes, + namespace, } => { + self.element_depth.fetch_add(1, Ordering::Relaxed); + if !self.external_subset_handled.swap(true, Ordering::Relaxed) + && self.parent.is_none() + && self.use_foreign_dtd.load(Ordering::Relaxed) + && self.parse_parameter_entities() + { + self.handle_external_subset(vm, None, None)?; + } + if self.namespace_separator.is_some() { + let declarations = { + let mut stack = self.namespace_stack.write(); + let previous = stack.last().map(|(namespace, _)| namespace); + let declarations: Vec<_> = namespace + .iter() + .filter(|(prefix, uri)| { + previous.map_or_else( + || { + !matches!( + (*prefix, *uri), + ("", "") + | ("xml", xml::namespace::NS_XML_URI) + | ("xmlns", xml::namespace::NS_XMLNS_URI) + ) + }, + |previous| previous.get(prefix) != Some(*uri), + ) + }) + .map(|(prefix, uri)| (prefix.to_owned(), uri.to_owned())) + .collect(); + stack.push(( + namespace, + declarations + .iter() + .map(|(prefix, _)| prefix.clone()) + .collect(), + )); + declarations + }; + for (prefix, uri) in declarations { + let prefix = (!prefix.is_empty()).then(|| vm.ctx.new_str(prefix)); + let uri = (!uri.is_empty()).then(|| vm.ctx.new_str(uri)); + self.invoke_buffered_handler( + vm, + &self.start_namespace_decl, + (prefix, uri), + )?; + } + } let ordered = self.ordered_attributes.read().is(&vm.ctx.true_value); // Build the container. let attrs: PyObjectRef = if ordered { let mut items = Vec::with_capacity(attributes.len() * 2); for attribute in attributes { - let key = self.intern_name(vm, self.make_name(&attribute.name)); + let key = self.intern_name(vm, self.make_name(&attribute.name, vm)); items.push(key.into()); items.push(vm.ctx.new_str(attribute.value).into()); } @@ -1101,7 +1798,7 @@ mod _pyexpat { } else { let dict = vm.ctx.new_dict(); for attribute in attributes { - let key = self.intern_name(vm, self.make_name(&attribute.name)); + let key = self.intern_name(vm, self.make_name(&attribute.name, vm)); dict.set_item( AsRef::::as_ref(&key), vm.ctx.new_str(attribute.value).into(), @@ -1112,31 +1809,41 @@ mod _pyexpat { dict.into() }; - let name_str = self.intern_name(vm, self.make_name(&name)); - invoke_handler(vm, &self.start_element, (name_str, attrs)) + let name_str = self.intern_name(vm, self.make_name(&name, vm)); + self.invoke_buffered_handler(vm, &self.start_element, (name_str, attrs)) } XmlEvent::EndElement { name, .. } => { - let name_str = self.intern_name(vm, self.make_name(&name)); - invoke_handler(vm, &self.end_element, (name_str,)) - } - XmlEvent::Characters(chars) => { - let str = PyStr::from(chars).into_ref(&vm.ctx); - invoke_handler(vm, &self.character_data, (str,)) + if self.element_depth.fetch_sub(1, Ordering::Relaxed) == 1 { + self.document_element_closed.store(true, Ordering::Relaxed); + } + let name_str = self.intern_name(vm, self.make_name(&name, vm)); + self.invoke_buffered_handler(vm, &self.end_element, (name_str,))?; + let declarations = self.namespace_stack.write().pop(); + if let Some((_, prefixes)) = declarations { + for prefix in prefixes.into_iter().rev() { + let prefix = (!prefix.is_empty()).then(|| vm.ctx.new_str(prefix)); + self.invoke_buffered_handler(vm, &self.end_namespace_decl, (prefix,))?; + } + } + Ok(()) } + XmlEvent::Characters(chars) => self.character_data(vm, chars), XmlEvent::ProcessingInstruction { name, data } => { let name = PyStr::from(name).into_ref(&vm.ctx); - let data = PyStr::from(data.unwrap_or_default()).into_ref(&vm.ctx); - invoke_handler(vm, &self.processing_instruction, (name, data)) + let data = data.unwrap_or_default(); + // Expat skips XML S between the target and data, not trailing whitespace. + let data = PyStr::from(data.trim_start_matches([' ', '\t', '\r', '\n'])) + .into_ref(&vm.ctx); + self.invoke_buffered_handler(vm, &self.processing_instruction, (name, data)) } XmlEvent::Comment(comment) => { let comment = PyStr::from(comment).into_ref(&vm.ctx); - invoke_handler(vm, &self.comment, (comment,)) + self.invoke_buffered_handler(vm, &self.comment, (comment,)) } XmlEvent::CData(chars) => { - invoke_handler(vm, &self.start_cdata_section, ())?; - let str = PyStr::from(chars).into_ref(&vm.ctx); - invoke_handler(vm, &self.character_data, (str,))?; - invoke_handler(vm, &self.end_cdata_section, ()) + self.invoke_buffered_handler(vm, &self.start_cdata_section, ())?; + self.character_data(vm, chars)?; + self.invoke_buffered_handler(vm, &self.end_cdata_section, ()) } _ => Ok(()), } @@ -1152,17 +1859,145 @@ mod _pyexpat { *guard = None; } + fn parse_parameter_entities(&self) -> bool { + let mode = self.parameter_entity_parsing.load(Ordering::Relaxed); + mode == XML_PARAM_ENTITY_PARSING_ALWAYS + || (mode == XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE + && !self.standalone.load(Ordering::Relaxed)) + } + + fn handle_external_subset( + &self, + vm: &VirtualMachine, + system_id: Option, + public_id: Option, + ) -> PyResult<()> { + let base = self.base.read().as_ref().map(|s| vm.ctx.new_str(s.clone())); + let result = self.invoke_buffered_int_handler( + vm, + &self.external_entity_ref, + "ExternalEntityRef", + (vm.ctx.none(), base, system_id, public_id), + )?; + if result == Some(0) { + return Err(self.handler_error( + vm, + 21, + "error in processing external entity reference", + )?); + } + Ok(()) + } + + fn handler_error( + &self, + vm: &VirtualMachine, + code: i32, + description: &str, + ) -> PyResult { + let line = *self.current_line.read(); + let column = *self.current_column.read(); + let error = vm.new_exception_msg( + PyExpatError::class(&vm.ctx).to_owned(), + format!("{description}: line {line}, column {column}").into(), + ); + error + .as_object() + .set_attr("code", vm.ctx.new_int(code), vm)?; + error + .as_object() + .set_attr("lineno", vm.ctx.new_int(line), vm)?; + error + .as_object() + .set_attr("offset", vm.ctx.new_int(column), vm)?; + Ok(error) + } + + fn parse_error( + &self, + vm: &VirtualMachine, + error: xml::reader::Error, + ) -> PyResult { + let position = error.position(); + let line = position.row() as i64 + 1; + let column = position.column() as i64; + *self.current_line.write() = line; + *self.current_column.write() = column; + let (code, description) = match error.kind() { + xml::reader::ErrorKind::UnexpectedEof => (5, "unclosed token"), + xml::reader::ErrorKind::Syntax(message) => { + if let Some(encoding) = message.strip_prefix("Unsupported encoding: ") { + // CPython's PyUnknownEncodingHandler probes all bytes using + // the text codec with replacement before libexpat validates + // the resulting single-byte map. Preserve codec exceptions + // instead of flattening them into an XML syntax error. + self.terminal_error_code.store(18, Ordering::SeqCst); + let template: Vec = (0..=u8::MAX).collect(); + let decoded = match vm.state.codec_registry.decode_text( + vm.ctx.new_bytes(template).into(), + encoding, + Some(vm.ctx.new_utf8_str("replace")), + vm, + ) { + Ok(decoded) => decoded, + Err(error) => return Ok(error), + }; + if decoded.as_wtf8().code_points().count() != 256 { + return Ok(vm.new_value_error("multi-byte encodings are not supported")); + } + // xml-rs still cannot consume custom single-byte maps. + (18, "unknown encoding") + } else if self.document_element_closed.load(Ordering::Relaxed) + && (message.starts_with("Unexpected characters outside the root element:") + || message.as_ref() == "Unexpected token: <") + { + (9, "junk after document element") + } else if message.starts_with("Unexpected end of stream:") { + (3, "no element found") + } else if message.starts_with("Unexpected end of stream") { + (5, "unclosed token") + } else if message.starts_with("Unexpected closing tag:") { + (7, "mismatched tag") + } else if message.starts_with("Attribute ") + && message.ends_with(" is redefined") + { + (8, "duplicate attribute") + } else if message.starts_with("Undefined entity:") { + (11, "undefined entity") + } else if message.starts_with("Unclosed (4, "not well-formed (invalid token)"), + _ => (2, "syntax error"), + }; + self.terminal_error_code.store(code, Ordering::SeqCst); + let message = format!("{description}: line {line}, column {column}"); + let error = + vm.new_exception_msg(PyExpatError::class(&vm.ctx).to_owned(), message.into()); + error + .as_object() + .set_attr("code", vm.ctx.new_int(code), vm)?; + error + .as_object() + .set_attr("lineno", vm.ctx.new_int(line), vm)?; + error + .as_object() + .set_attr("offset", vm.ctx.new_int(column), vm)?; + Ok(error) + } + /// Drain events already produced by the parser thread (and any /// produced while draining), dispatching each to its handler, until /// the parser thread reports it is blocked waiting for more input /// (`NeedMore`), has finished (`Finished`), or hit a parse error - /// (`Error`, silently swallowed for compatibility -- see - /// `ParserMsg::Error`). If a handler raises, dispatching stops and - /// the error propagates, but the parser thread and any events it - /// already produced are kept around so a later `Parse()` call - /// resumes exactly where dispatch left off, mirroring libexpat - /// (a callback exception aborts that `XML_Parse()` call without - /// corrupting the parser's internal state). Only used by + /// (`Error`, raised as `ExpatError`). If a handler raises, dispatching stops and + /// the error propagates after clearing handlers and stopping the + /// backend, matching libexpat's non-resumable callback abort. Only used by /// `Backend::Threaded`. #[cfg(not(target_arch = "wasm32"))] fn pump(&self, vm: &VirtualMachine, min_pushes: u64) -> PyResult<()> { @@ -1197,19 +2032,20 @@ mod _pyexpat { continue; } ParserMsg::Finished => { + self.terminal_error_code.store(36, Ordering::SeqCst); self.finished.store(true, Ordering::SeqCst); self.teardown_backend(); return Ok(()); } - ParserMsg::Error => { + ParserMsg::Error(error) => { self.teardown_backend(); - return Ok(()); + return Err(self.parse_error(vm, error)?); } ParserMsg::Event(ev) => { *self.current_line.write() = ev.line; *self.current_column.write() = ev.column; *self.current_byte_index.write() = ev.byte_index; - self.dispatch(vm, ev.event)?; + self.dispatch(vm, ev.event, ev.doctype)?; } } } @@ -1286,7 +2122,8 @@ mod _pyexpat { if this_index < skip { continue; } - if let Err(e) = self.dispatch(vm, event) { + let doctype = Doctype::from_reader(&parser, &event); + if let Err(e) = self.dispatch(vm, event, doctype) { // The handler for `this_index` was invoked (it // raised, but it ran), so don't replay it next // call -- mirrors `Backend::Threaded`, where an @@ -1296,13 +2133,11 @@ mod _pyexpat { break Err(e); } } - // xml-rs is stricter than libexpat about a document - // prefix that is only well-formed once more bytes - // arrive (or never, if this chunk really is malformed); - // mirrors `ParserMsg::Error`, which is silently - // swallowed for compatibility rather than raising - // `ExpatError`. - Err(_) => break Ok(()), + // A non-final buffer can end in the middle of a token; + // defer only that incomplete-input error until more data + // arrives. Malformed complete input must still fail. + Err(error) if !isfinal && is_incomplete(&error) => break Ok(()), + Err(error) => break Err(self.parse_error(vm, error)?), } }; @@ -1313,16 +2148,27 @@ mod _pyexpat { } } if isfinal { - // The caller has declared there is no more data coming, so - // (whether or not this re-parse actually reached - // `EndDocument`) further Parse()/ParseFile() calls become - // no-ops, matching libexpat/`Backend::Threaded`. + // Remember successful completion separately from errors; + // both close this backend, but only success means the parser + // should report XML_ERROR_FINISHED on a later call. + if result.is_ok() { + self.terminal_error_code.store(36, Ordering::SeqCst); + } self.finished.store(true, Ordering::SeqCst); self.teardown_backend(); } result } + fn check_parse_state(&self, vm: &VirtualMachine) -> PyResult<()> { + let code = self.terminal_error_code.load(Ordering::SeqCst); + if code != 0 { + let (_, description) = super::_errors::ERRORS[code as usize - 1]; + return Err(self.handler_error(vm, code, description)?); + } + Ok(()) + } + /// Feed another chunk of the document to the (possibly newly /// created) backend and dispatch whatever events that unblocks. /// `Parse()` and `ParseFile()` may each be called several times @@ -1330,7 +2176,13 @@ mod _pyexpat { /// `xml.etree.ElementTree` reads and feeds a file 64KB at a time); /// see the module doc comment for how each backend stays consistent /// across those calls. - fn feed(&self, vm: &VirtualMachine, chunk: &[u8], isfinal: bool) -> PyResult<()> { + fn feed( + &self, + vm: &VirtualMachine, + chunk: &[u8], + isfinal: bool, + unicode_input: bool, + ) -> PyResult<()> { if self.busy.swap(true, Ordering::SeqCst) { // Reentrant call, e.g. a handler calling Parse() on the same // parser. Draining our own channel (Threaded) or re-entering @@ -1338,23 +2190,71 @@ mod _pyexpat { // corrupt state, so reject it instead, mirroring CPython. return Err(vm.new_runtime_error("Parse() called before Parse() returned")); } - let result = self.feed_inner(vm, chunk, isfinal); + let result = self + .feed_inner(vm, chunk, isfinal, unicode_input) + .and_then(|()| self.flush_character_buffer(vm)); self.busy.store(false, Ordering::SeqCst); result } - fn feed_inner(&self, vm: &VirtualMachine, chunk: &[u8], isfinal: bool) -> PyResult<()> { + fn feed_inner( + &self, + vm: &VirtualMachine, + chunk: &[u8], + isfinal: bool, + unicode_input: bool, + ) -> PyResult<()> { + if let Some(entity) = &self.external_entity { + // xml-rs only parses complete documents. In particular, an + // external DTD is not a document, and a general external + // entity can contain multiple top-level nodes and uses the + // namespace/entity context supplied by the parent. Keep + // construction and inherited configuration available, but + // never silently treat those inputs as ordinary documents. + let kind = if entity.context.is_none() { + "external DTD" + } else { + "external entity fragment" + }; + let encoding = if entity.encoding.is_some() { + " with an explicit encoding" + } else { + "" + }; + return Err(vm.new_not_implemented_error(format!( + "{kind} parsing{encoding} is not supported by the xml-rs backend" + ))); + } + self.started.store(true, Ordering::Relaxed); + self.check_parse_state(vm)?; + self.declaration.write().record(chunk); if self.finished.load(Ordering::SeqCst) { - // The document already ended; further data is ignored, same - // as libexpat happily no-oping once XML_Parse has seen EOF. return Ok(()); } - { - let mut guard = self.backend.write(); - if guard.is_none() { - *guard = Some(Backend::new(self.create_config())); + let mut input = Cow::Borrowed(chunk); + if self.backend.read().is_none() { + let unicode_input = *self.input_unicode.write().get_or_insert(unicode_input); + // xml-rs detects a UTF-16 BOM, but unlike Expat does not + // recognize UTF-16 XML without one. Two initial bytes suffice + // to distinguish the endian form; retain only a split prefix. + let mut initial = self.initial_bytes.write(); + if !initial.is_empty() { + initial.extend_from_slice(chunk); + input = Cow::Owned(core::mem::take(&mut *initial)); + } + if !unicode_input && self.encoding.is_none() && input.len() < 2 && !isfinal { + initial.extend_from_slice(&input); + return Ok(()); } + let sniffed = match input.as_ref() { + [0, _, ..] => Some(xml::Encoding::Utf16Be), + [_, 0, ..] => Some(xml::Encoding::Utf16Le), + _ => None, + }; + *self.backend.write() = + Some(Backend::new(self.create_config(unicode_input, sniffed))); } + let chunk = input.as_ref(); #[cfg(not(target_arch = "wasm32"))] { let is_threaded = matches!(*self.backend.read(), Some(Backend::Threaded(_))); @@ -1399,26 +2299,32 @@ mod _pyexpat { #[pymethod(name = "Parse")] fn parse( zelf: &Py, - data: Either, + data: ArgStrOrBytesLike, isfinal: OptionalArg, vm: &VirtualMachine, ) -> PyResult { - let bytes = match data { - Either::A(s) => s.as_bytes().to_vec(), - Either::B(b) => b.as_bytes().to_vec(), - }; - zelf.feed(vm, &bytes, isfinal.unwrap_or(false))?; + let bytes = data.borrow_bytes().to_vec(); + zelf.feed( + vm, + &bytes, + isfinal.unwrap_or(false), + matches!(data, ArgStrOrBytesLike::Str(_)), + )?; Ok(1) } #[pymethod(name = "ParseFile")] fn parse_file(zelf: &Py, file: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let read_res = vm.call_method(&file, "read", ())?; + let read = vm + .get_attribute_opt(&file, "read")? + .ok_or_else(|| vm.new_type_error("argument must have 'read' attribute"))?; + zelf.check_parse_state(vm)?; + let read_res = read.call((), vm)?; let bytes_like = ArgBytesLike::try_from_object(vm, read_res)?; let buf = bytes_like.borrow_buf().to_vec(); // `file.read()` with no argument reads to EOF, so this chunk is // always the last one. - zelf.feed(vm, &buf, true)?; + zelf.feed(vm, &buf, true, false)?; Ok(1) } } @@ -1426,35 +2332,71 @@ mod _pyexpat { #[derive(FromArgs)] struct ParserCreateArgs { #[pyarg(any, optional)] - encoding: Option, + encoding: Option, #[pyarg(any, optional)] - namespace_separator: Option, + namespace_separator: Option, #[pyarg(any, optional)] intern: OptionalOption, } + fn parser_create_string_arg( + value: Option, + name: &str, + vm: &VirtualMachine, + ) -> PyResult> { + let Some(value) = value else { + return Ok(None); + }; + let text = value.downcast::().map_err(|value| { + let actual = { + let actual = value.class().slot_name(); + let mut end = actual.len().min(50); + while !actual.is_char_boundary(end) { + end -= 1; + } + actual[..end].to_owned() + }; + vm.new_type_error(format!( + "ParserCreate() argument '{name}' must be str or None, not {actual}" + )) + })?; + let text = text.try_into_utf8(vm)?; + if text.as_str().contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + Ok(Some(text)) + } + #[pyfunction(name = "ParserCreate")] fn parser_create( args: ParserCreateArgs, vm: &VirtualMachine, ) -> PyResult { - // Validate namespace_separator: must be at most one character - let ns_sep = match args.namespace_separator { - Some(ref s) => { - if s.as_str().chars().count() > 1 { - return Err(vm.new_value_error( - "namespace_separator must be at most one character, omitted, or None", - )); - } - Some(s.as_str().to_owned()) - } - None => None, - }; - - // encoding parameter is currently not used (xml-rs handles encoding from XML declaration) - let _ = args.encoding; + // Clinic converts both strings before the implementation validates + // the separator and the intern dictionary. + let encoding = parser_create_string_arg(args.encoding, "encoding", vm)?; + let ns_sep = parser_create_string_arg(args.namespace_separator, "namespace_separator", vm)?; + if ns_sep.as_ref().is_some_and(|sep| sep.as_str().len() > 1) { + return Err(vm.new_value_error( + "namespace_separator must be at most one character, omitted, or None", + )); + } + if let OptionalArg::Present(Some(ref intern)) = args.intern + && intern + .downcast_ref::() + .is_none() + { + return Err(vm.new_type_error("intern must be a dictionary")); + } - Ok(PyExpatLikeXmlParser::new(ns_sep, args.intern, vm)) + Ok(PyExpatLikeXmlParser::new( + encoding.map(|encoding| encoding.as_str().to_owned()), + ns_sep.map(|sep| sep.as_str().to_owned()), + args.intern, + None, + None, + vm, + )) } // TODO: Tie this exception to the module's state. @@ -1472,5 +2414,130 @@ mod _pyexpat { #[pymodule(name = "model")] mod _model {} -#[pymodule(name = "errors")] -mod _errors {} +#[pymodule(name = "pyexpat.errors")] +mod _errors { + use crate::vm::{Py, PyResult, VirtualMachine, builtins::PyModule, extend_module}; + + // CPython 3.15 Modules/pyexpat.c error_info_of; code zero has no message. + pub(super) const ERRORS: &[(&str, &str)] = &[ + ("XML_ERROR_NO_MEMORY", "out of memory"), + ("XML_ERROR_SYNTAX", "syntax error"), + ("XML_ERROR_NO_ELEMENTS", "no element found"), + ("XML_ERROR_INVALID_TOKEN", "not well-formed (invalid token)"), + ("XML_ERROR_UNCLOSED_TOKEN", "unclosed token"), + ("XML_ERROR_PARTIAL_CHAR", "partial character"), + ("XML_ERROR_TAG_MISMATCH", "mismatched tag"), + ("XML_ERROR_DUPLICATE_ATTRIBUTE", "duplicate attribute"), + ( + "XML_ERROR_JUNK_AFTER_DOC_ELEMENT", + "junk after document element", + ), + ( + "XML_ERROR_PARAM_ENTITY_REF", + "illegal parameter entity reference", + ), + ("XML_ERROR_UNDEFINED_ENTITY", "undefined entity"), + ( + "XML_ERROR_RECURSIVE_ENTITY_REF", + "recursive entity reference", + ), + ("XML_ERROR_ASYNC_ENTITY", "asynchronous entity"), + ( + "XML_ERROR_BAD_CHAR_REF", + "reference to invalid character number", + ), + ("XML_ERROR_BINARY_ENTITY_REF", "reference to binary entity"), + ( + "XML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF", + "reference to external entity in attribute", + ), + ( + "XML_ERROR_MISPLACED_XML_PI", + "XML or text declaration not at start of entity", + ), + ("XML_ERROR_UNKNOWN_ENCODING", "unknown encoding"), + ( + "XML_ERROR_INCORRECT_ENCODING", + "encoding specified in XML declaration is incorrect", + ), + ("XML_ERROR_UNCLOSED_CDATA_SECTION", "unclosed CDATA section"), + ( + "XML_ERROR_EXTERNAL_ENTITY_HANDLING", + "error in processing external entity reference", + ), + ("XML_ERROR_NOT_STANDALONE", "document is not standalone"), + ( + "XML_ERROR_UNEXPECTED_STATE", + "unexpected parser state - please send a bug report", + ), + ( + "XML_ERROR_ENTITY_DECLARED_IN_PE", + "entity declared in parameter entity", + ), + ( + "XML_ERROR_FEATURE_REQUIRES_XML_DTD", + "requested feature requires XML_DTD support in Expat", + ), + ( + "XML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING", + "cannot change setting once parsing has begun", + ), + ("XML_ERROR_UNBOUND_PREFIX", "unbound prefix"), + ("XML_ERROR_UNDECLARING_PREFIX", "must not undeclare prefix"), + ( + "XML_ERROR_INCOMPLETE_PE", + "incomplete markup in parameter entity", + ), + ("XML_ERROR_XML_DECL", "XML declaration not well-formed"), + ("XML_ERROR_TEXT_DECL", "text declaration not well-formed"), + ("XML_ERROR_PUBLICID", "illegal character(s) in public id"), + ("XML_ERROR_SUSPENDED", "parser suspended"), + ("XML_ERROR_NOT_SUSPENDED", "parser not suspended"), + ("XML_ERROR_ABORTED", "parsing aborted"), + ("XML_ERROR_FINISHED", "parsing finished"), + ( + "XML_ERROR_SUSPEND_PE", + "cannot suspend in external parameter entity", + ), + ( + "XML_ERROR_RESERVED_PREFIX_XML", + "reserved prefix (xml) must not be undeclared or bound to another namespace name", + ), + ( + "XML_ERROR_RESERVED_PREFIX_XMLNS", + "reserved prefix (xmlns) must not be declared or undeclared", + ), + ( + "XML_ERROR_RESERVED_NAMESPACE_URI", + "prefix must not be bound to one of the reserved namespace names", + ), + ("XML_ERROR_INVALID_ARGUMENT", "invalid argument"), + ( + "XML_ERROR_NO_BUFFER", + "a successful prior call to function XML_GetBuffer is required", + ), + ( + "XML_ERROR_AMPLIFICATION_LIMIT_BREACH", + "limit on input amplification factor (from DTD and entities) breached", + ), + ("XML_ERROR_NOT_STARTED", "parser not started"), + ]; + + pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { + __module_exec(vm, module); + let codes = vm.ctx.new_dict(); + let messages = vm.ctx.new_dict(); + for (index, &(name, message)) in ERRORS.iter().enumerate() { + let code = vm.ctx.new_int(index + 1); + module.set_attr(name, vm.ctx.new_str(message), vm)?; + codes.set_item(message, code.into(), vm)?; + messages.set_item(&(index + 1), vm.ctx.new_str(message).into(), vm)?; + } + extend_module!(vm, module, { + "__doc__" => vm.ctx.new_str("Constants used to describe error conditions."), + "codes" => codes, + "messages" => messages, + }); + Ok(()) + } +} diff --git a/crates/stdlib/src/pystruct.rs b/crates/stdlib/src/pystruct.rs index 2a3c0dfe341..8a8ac906315 100644 --- a/crates/stdlib/src/pystruct.rs +++ b/crates/stdlib/src/pystruct.rs @@ -10,16 +10,15 @@ pub(crate) use _struct::module_def; #[pymodule] pub(crate) mod _struct { use crate::vm::{ - AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, + AsObject, FromArgs, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, + VirtualMachine, buffer::{FormatSpec, new_struct_error, struct_error_type}, builtins::{PyBytes, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef}, - common::{ - lock::{PyMappedRwLockReadGuard, PyRwLock, PyRwLockReadGuard}, - rc::PyRc, - }, - function::{ArgBytesLike, ArgMemoryBuffer, FuncArgs, PosArgs}, + common::{lock::PyRwLock, rc::PyRc}, + function::{ArgBytesLike, ArgBytesOrStr, ArgMemoryBuffer, FuncArgs, NameValues, PosArgs}, match_class, protocol::PyIterReturn, + stdlib::_warnings, types::{Constructor, Initializer, IterNext, Iterable, Representable, SelfIter}, }; use crossbeam_utils::atomic::AtomicCell; @@ -30,33 +29,22 @@ pub(crate) mod _struct { impl TryFromObject for IntoStructFormatBytes { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - // CPython turns str to bytes (via str.encode('ascii')) but we keep str. - // The error reporting for non-ASCII input still matches CPython: - // - str input with non-ASCII char: UnicodeEncodeError, the same exception - // str.encode('ascii') would produce. - // - bytes input with non-ASCII byte: struct.error("bad char in struct format"), - // matching CPython where bytes are passed through to the format parser. + // CPython decodes bytes with ASCII and surrogateescape, then rejects + // every non-ASCII format before parsing, for both str and bytes. let fmt = match_class!(match obj { s @ PyStr => { if !s.isascii() { - let start = s - .as_wtf8() - .code_points() - .position(|cp| !cp.to_char().is_some_and(|c| c.is_ascii())) - .unwrap_or(0); - return Err(vm.new_unicode_encode_error( - vm.ctx.new_str("ascii"), - s, - start, - start + 1, - vm.ctx.new_str("ordinal not in range(128)"), - )); + return Err(vm.new_value_error("non-ASCII character in struct format")); + } + if s.class().is(vm.ctx.types.str_type) { + s + } else { + vm.ctx.new_str(s.as_wtf8()) } - s } b @ PyBytes => { let ascii_str = ascii::AsciiStr::from_ascii(&b) - .map_err(|_| new_struct_error(vm, "bad char in struct format"))?; + .map_err(|_| vm.new_value_error("non-ASCII character in struct format"))?; vm.ctx.new_str(ascii_str) } other => @@ -89,13 +77,13 @@ pub(crate) mod _struct { vm: &VirtualMachine, ) -> PyResult { let offset_from_start = if offset < 0 { - if (-offset) as usize > buffer_len { + if offset.unsigned_abs() > buffer_len { return Err(new_struct_error( vm, format!("offset {offset} out of range for {buffer_len}-byte buffer"), )); } - buffer_len - (-offset as usize) + buffer_len - offset.unsigned_abs() } else { let offset = offset as usize; let (op, op_action) = if is_pack { @@ -103,13 +91,13 @@ pub(crate) mod _struct { } else { ("unpack_from", "unpacking") }; - if offset + needed > buffer_len { + if offset > buffer_len || needed > buffer_len - offset { let msg = format!( "{op} requires a buffer of at least {required} bytes for {op_action} {needed} \ bytes at offset {offset} (actual buffer size is {buffer_len})", op = op, op_action = op_action, - required = needed + offset, + required = (needed as u128) + (offset as u128), needed = needed, offset = offset, buffer_len = buffer_len @@ -134,21 +122,25 @@ pub(crate) mod _struct { } #[pyfunction] - fn pack(fmt: IntoStructFormatBytes, args: PosArgs, vm: &VirtualMachine) -> PyResult> { - fmt.cached_format_spec(vm)?.pack(args.into_vec(), vm) + fn pack( + format: IntoStructFormatBytes, + values: PosArgs, + vm: &VirtualMachine, + ) -> PyResult> { + format.cached_format_spec(vm)?.pack(values.into_vec(), vm) } #[pyfunction] fn pack_into( - fmt: IntoStructFormatBytes, + format: IntoStructFormatBytes, buffer: ArgMemoryBuffer, offset: isize, - args: PosArgs, + values: PosArgs, vm: &VirtualMachine, ) -> PyResult<()> { - let format_spec = fmt.cached_format_spec(vm)?; + let format_spec = format.cached_format_spec(vm)?; let offset = get_buffer_offset(buffer.len(), offset, format_spec.size, true, vm)?; - buffer.with_ref(|data| format_spec.pack_into(&mut data[offset..], args.into_vec(), vm)) + format_spec.pack_into_buffer(&buffer, offset, values.into_vec(), vm) } #[pyfunction] @@ -262,60 +254,188 @@ pub(crate) mod _struct { } /// What a `Struct` is once a format has been read into it. Held apart - /// from the object because `__new__` hands out a `Struct` that `__init__` - /// has not filled in yet, and `__init__` may be called again on one that - /// already holds a format. - #[derive(Debug)] + /// because `__new__` can still hand out an uninitialized `Struct`, and + /// `__init__` may be called again on one that already holds a format. + #[derive(Clone, Debug)] struct StructSpec { spec: PyRc, format: PyStrRef, } + #[derive(FromArgs)] + struct StructArgs { + #[pyarg(any)] + format: PyObjectRef, + } + + impl StructArgs { + fn bind(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let nargs = args.args.len() + args.kwargs.len(); + if nargs > 1 { + let keyword = if args.args.is_empty() { "keyword " } else { "" }; + return Err(vm.new_type_error(format!( + "Struct() takes at most 1 {keyword}argument ({nargs} given)" + ))); + } + args.bind_for(vm, "Struct") + } + } + #[pyattr] #[pyclass(name = "Struct", traverse)] #[derive(Debug, PyPayload)] struct PyStruct { #[pytraverse(skip)] inner: PyRwLock>, + #[pytraverse(skip)] + init_called: AtomicCell, + } + + impl PyStruct { + fn uses_struct_init(cls: &Py, vm: &VirtualMachine) -> bool { + cls.slots() + .init + .load() + .zip(Self::class(&vm.ctx).slots().init.load()) + .is_some_and(|(init, struct_init)| core::ptr::fn_addr_eq(init, struct_init)) + } + + fn parse_format(format: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let format = IntoStructFormatBytes::try_from_object(vm, format)?; + Ok(StructSpec { + spec: PyRc::new(format.format_spec(vm)?), + format: format.0, + }) + } + + fn same_format(format: &PyStr, candidate: &PyObject) -> bool { + ArgBytesOrStr::with_object_ref(candidate, |bytes| bytes == format.as_bytes()) + .unwrap_or(false) + } } impl Constructor for PyStruct { type Args = FuncArgs; + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let uses_struct_new = cls + .slots() + .new + .load() + .zip(Self::class(&vm.ctx).slots().new.load()) + .is_some_and(|(new, struct_new)| core::ptr::fn_addr_eq(new, struct_new)); + let uses_struct_init = Self::uses_struct_init(&cls, vm); + let format = if !uses_struct_new { + // A subclass explicitly called Struct.__new__ from its own __new__. + let args = StructArgs::bind(args, vm)?; + Some(args.format) + } else { + let format = match args.args.as_slice() { + [format] if args.kwargs.is_empty() => Some(format.clone()), + [] if args.kwargs.len() == 1 => args.kwargs.get("format").cloned(), + _ => None, + }; + if format.is_none() && !uses_struct_init { + let nargs = args.args.len() + args.kwargs.len(); + let message = if nargs > 1 { + format!("Struct() takes at most 1 argument ({nargs} given)") + } else { + "Struct() missing required argument 'format' (pos 1)".to_owned() + }; + _warnings::warn(vm.ctx.exceptions.deprecation_warning, message, 1, vm)?; + } + format + }; + // Allocate before parsing so a failing subclass constructor still + // finalizes its half-initialized instance. + let zelf = Self::py_new(&cls, FuncArgs::default(), vm)?.into_ref_with_type(vm, cls)?; + if let Some(format) = format { + match Self::parse_format(format, vm) { + Ok(inner) => { + let _old = zelf.inner.write().replace(inner); + } + Err(err) if uses_struct_new && !uses_struct_init => { + _warnings::warn( + vm.ctx.exceptions.deprecation_warning, + format!( + "Invalid 'format' argument for Struct.__new__(): {}", + err.as_object().str(vm)? + ), + 1, + vm, + )?; + } + Err(err) => return Err(err), + } + } + Ok(zelf.into()) + } + fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { Ok(Self { inner: PyRwLock::new(None), + init_called: AtomicCell::new(false), }) } } impl Initializer for PyStruct { - type Args = IntoStructFormatBytes; - - fn init(zelf: &Py, fmt: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - // The format is read before anything is replaced, so a format that - // cannot be read leaves the object as it was. - let spec = fmt.format_spec(vm)?; - *zelf.inner.write() = Some(StructSpec { - spec: PyRc::new(spec), - format: fmt.0, - }); + type Args = StructArgs; + + fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + let zelf = zelf.try_to_ref::(vm)?; + if !zelf.init_called.load() + && Self::uses_struct_init(zelf.class(), vm) + && zelf.inner.read().is_some() + { + // The implicit __init__ must not reinterpret a custom __new__'s arguments. + zelf.init_called.store(true); + return Ok(()); + } + let args = StructArgs::bind(args, vm)?; + Self::init(zelf, args, vm) + } + + fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { + let format = zelf.inner.read().as_ref().map(|inner| inner.format.clone()); + if let Some(format) = format { + if Self::same_format(&format, &args.format) { + zelf.init_called.store(true); + return Ok(()); + } + let message = if zelf.init_called.load() { + "Re-initialization of Struct by calling the __init__() method \ + will not work in future Python versions" + } else { + "Different format arguments for __new__() and __init__() \ + methods of Struct" + }; + _warnings::warn(vm.ctx.exceptions.future_warning, message.to_owned(), 1, vm)?; + } + // Warn and parse before replacing the format. Warning hooks may reenter, + // and either a warning or a conversion error must preserve the old state. + let inner = Self::parse_format(args.format, vm)?; + let old = zelf.inner.write().replace(inner); + drop(old); + zelf.init_called.store(true); Ok(()) } } #[pyclass(with(Constructor, Initializer, Representable), flags(BASETYPE))] impl PyStruct { - /// The format this was initialized with, or an error if `__init__` - /// never ran. - fn ready(&self, vm: &VirtualMachine) -> PyResult> { - PyRwLockReadGuard::try_map(self.inner.read(), Option::as_ref) - .map_err(|_| vm.new_runtime_error("Struct object is not initialized")) + // Hold an owned snapshot while conversions and warning hooks can reenter. + fn ready(&self, vm: &VirtualMachine) -> PyResult { + let inner = self.inner.read().clone(); + inner.ok_or_else(|| vm.new_runtime_error("Struct object is not initialized")) } #[pygetset] fn format(zelf: &Py, vm: &VirtualMachine) -> PyResult { - Ok(zelf.ready(vm)?.format.clone()) + let format = zelf.inner.read().as_ref().map(|inner| inner.format.clone()); + format.ok_or_else(|| { + vm.new_no_attribute_error(zelf.as_object().to_owned(), vm.ctx.new_str("format")) + }) } // The size an uninitialized `Struct` reports, which no format has @@ -329,8 +449,12 @@ pub(crate) mod _struct { } #[pymethod] - fn pack(zelf: &Py, args: PosArgs, vm: &VirtualMachine) -> PyResult> { - zelf.ready(vm)?.spec.pack(args.into_vec(), vm) + fn pack( + zelf: &Py, + values: PosArgs, + vm: &VirtualMachine, + ) -> PyResult> { + zelf.ready(vm)?.spec.pack(values.into_vec(), vm) } #[pymethod] @@ -338,16 +462,14 @@ pub(crate) mod _struct { zelf: &Py, buffer: ArgMemoryBuffer, offset: isize, - args: PosArgs, + values: PosArgs, vm: &VirtualMachine, ) -> PyResult<()> { let inner = zelf.ready(vm)?; let offset = get_buffer_offset(buffer.len(), offset, inner.spec.size, true, vm)?; - buffer.with_ref(|data| { - inner - .spec - .pack_into(&mut data[offset..], args.into_vec(), vm) - }) + inner + .spec + .pack_into_buffer(&buffer, offset, values.into_vec(), vm) } #[pymethod] @@ -379,7 +501,7 @@ pub(crate) mod _struct { buffer: ArgBytesLike, vm: &VirtualMachine, ) -> PyResult { - let spec = zelf.ready(vm)?.spec.clone(); + let spec = zelf.ready(vm)?.spec; UnpackIterator::with_buffer(vm, spec, buffer) } diff --git a/crates/stdlib/src/random.rs b/crates/stdlib/src/random.rs index a5955b50aee..746ec6d6cb8 100644 --- a/crates/stdlib/src/random.rs +++ b/crates/stdlib/src/random.rs @@ -7,7 +7,7 @@ mod _random { use crate::common::lock::PyMutex; use crate::vm::{ Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, - builtins::{PyInt, PyTupleRef}, + builtins::{PyInt, PyTuple, PyTupleRef}, types::{Constructor, Initializer}, }; use itertools::Itertools; @@ -52,15 +52,14 @@ mod _random { fn seed(zelf: &Py, args: SeedArgs, vm: &VirtualMachine) -> PyResult<()> { *zelf.rng.lock() = match args.n { Some(n) => { - // Fallback to using hash if object isn't Int-like. - let (_, mut key) = match n.downcast::() { + // CPython uses the absolute value for integers, but casts + // hashes of other objects to the unsigned pointer width. + let value = match n.downcast::() { Ok(n) => n.as_bigint().abs(), - Err(obj) => BigInt::from(obj.hash(vm)?).abs(), - } - .to_u32_digits(); - if cfg!(target_endian = "big") { - key.reverse(); - } + Err(obj) => BigInt::from(obj.hash(vm)? as usize), + }; + // Digits are already least-significant first on every target. + let (_, key) = value.to_u32_digits(); let key = if key.is_empty() { &[0] } else { key.as_slice() }; MT19937::new_with_slice_seed(key) } @@ -76,26 +75,28 @@ mod _random { if k_bigint.is_negative() { return Err(vm.new_value_error("number of bits must be non-negative")); } - let k: isize = k_int + let k: u64 = k_int .try_to_primitive(vm) .map_err(|_| vm.new_overflow_error("getrandbits: number of bits too large"))?; match k { 0 => Ok(BigInt::zero()), + 1..=32 => Ok(BigInt::from(zelf.rng.lock().next_u32() >> (32 - k))), mut k => { + let words = word_count(k).ok_or_else(|| vm.no_memory_error())?; + let mut word_array = Vec::new(); + word_array + .try_reserve_exact(words) + .map_err(|_| vm.no_memory_error())?; let mut rng = zelf.rng.lock(); let mut gen_u32 = |k| { let r = rng.next_u32(); if k < 32 { r >> (32 - k) } else { r } }; - let words = (k - 1) / 32 + 1; - let word_array = (0..words) - .map(|_| { - let word = gen_u32(k); - k = k.wrapping_sub(32); - word - }) - .collect::>(); + for _ in 0..words { + word_array.push(gen_u32(k)); + k = k.wrapping_sub(32); + } let uint = BigUint::new(word_array); // very unlikely but might as well check @@ -123,25 +124,77 @@ mod _random { } #[pymethod] - fn setstate(zelf: &Py, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { + fn setstate(zelf: &Py, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + let state = state + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("state vector must be a tuple"))?; let state: &[_; mt19937::N + 1] = state .as_slice() .try_into() .map_err(|_| vm.new_value_error("state vector is the wrong size"))?; let (index, state) = state.split_last().unwrap(); - let index: usize = index.try_to_value(vm)?; - if index > mt19937::N { - return Err(vm.new_value_error("invalid state")); - } let state: [u32; mt19937::N] = state .iter() - .map(|i| i.try_to_value(vm)) + .map(|item| { + let value = item + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("an integer is required"))?; + if value.as_bigint().is_negative() { + return Err( + vm.new_overflow_error("can't convert negative value to unsigned int") + ); + } + let value = core::ffi::c_ulong::try_from(value.as_bigint()).map_err(|_| { + vm.new_overflow_error("Python int too large to convert to C unsigned long") + })?; + #[allow(clippy::unnecessary_cast)] // c_ulong is u32 on some platforms. + let value = value as u32; + Ok(value) + }) .process_results(|it| it.collect_array())? .unwrap(); + let index = index.try_index(vm)?; + let index = core::ffi::c_long::try_from(index.as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))?; + if index < 0 || index > mt19937::N as core::ffi::c_long { + return Err(vm.new_value_error("invalid state")); + } let mut rng = zelf.rng.lock(); rng.set_state(&state); - rng.set_index(index); + rng.set_index(index as usize); Ok(()) } } + + fn word_count(bits: u64) -> Option { + let words = usize::try_from(bits.div_ceil(32)).ok()?; + (words <= isize::MAX as usize / size_of::()).then_some(words) + } + + #[cfg(test)] + mod tests { + use super::word_count; + + #[test] + fn getrandbits_word_counts() { + for (bits, words) in [ + (0, 0), + (1, 1), + (32, 1), + (33, 2), + (1 << 31, 1 << 26), + (1 << 32, 1 << 27), + ] { + assert_eq!(word_count(bits), Some(words)); + } + if usize::BITS == 32 { + let max_words = isize::MAX as usize / size_of::(); + assert_eq!(word_count(max_words as u64 * 32), Some(max_words)); + assert_eq!(word_count(max_words as u64 * 32 + 1), None); + assert_eq!(word_count(u64::MAX), None); + } else { + assert_eq!(word_count(u64::MAX), usize::try_from(1_u64 << 59).ok()); + } + } + } } diff --git a/crates/stdlib/src/resource.rs b/crates/stdlib/src/resource.rs index 0e2a777e6e2..0dfc718d4d8 100644 --- a/crates/stdlib/src/resource.rs +++ b/crates/stdlib/src/resource.rs @@ -5,20 +5,18 @@ pub(crate) use resource::module_def; #[pymodule] mod resource { use crate::vm::{ - Py, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, - builtins::{PyInt, PyIntRef}, + PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, convert::{ToPyException, ToPyObject}, + stdlib::_warnings, types::PyStructSequence, }; - use num_traits::Signed; + use num_traits::{Signed, ToPrimitive}; use rustpython_host_env::resource as host_resource; use std::io; #[cfg_attr(target_os = "android", expect(deprecated))] const RLIM_NLIMITS: i32 = cfg_select! { - target_os = "android" => { - host_resource::RLIM_NLIMITS - } + target_os = "android" => host_resource::RLIM_NLIMITS, _ => { // This constant isn't abi-stable across os versions, so we just // pick a high number so we don't get false positive ValueErrors and just bubble up the @@ -34,6 +32,20 @@ mod resource { RLIMIT_MEMLOCK, RLIMIT_NOFILE, RLIMIT_NPROC, RLIMIT_RSS, RLIMIT_STACK, }; + #[cfg(any( + target_os = "linux", + target_os = "l4re", + target_os = "emscripten", + target_os = "freebsd", + target_os = "netbsd", + target_os = "openbsd", + target_os = "aix", + target_os = "fuchsia", + target_os = "cygwin" + ))] + #[pyattr] + use host_resource::{RLIM_SAVED_CUR, RLIM_SAVED_MAX}; + #[cfg(any(target_os = "linux", target_os = "android", target_os = "emscripten"))] #[pyattr] use host_resource::{RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_SIGPENDING}; @@ -118,7 +130,7 @@ mod resource { // The exception the module reports its failures through, which is the one // every other call raises. - #[pyattr(name = "error", once)] + #[pyattr(once)] fn error(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.exceptions.os_error.to_owned().into() } @@ -161,20 +173,23 @@ mod resource { } } - fn py2rlim(obj: &Py, vm: &VirtualMachine) -> PyResult { - let value = obj.try_to_primitive::(vm)?; - - if value.is_negative() { - return Err(vm.new_value_error("Cannot convert negative int")); - } - - host_resource::rlim_t::try_from(value) - .map_err(|_| vm.new_overflow_error("Python int too large to convert to C rlim_t")) - } - fn py2rlim_limit(obj: &PyObject, vm: &VirtualMachine) -> PyResult { let int = obj.try_index(vm)?; if int.as_bigint().is_negative() { + // Only accept the legacy signed representation of RLIM_INFINITY, + // not arbitrary negative values truncated to the native width. + if let Some(value) = int.as_bigint().to_i128() + && value >= -(1_i128 << (host_resource::rlim_t::BITS - 1)) + && value as host_resource::rlim_t == RLIM_INFINITY + { + _warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "Use RLIM_INFINITY instead of negative limit value.".to_owned(), + 1, + vm, + )?; + return Ok(RLIM_INFINITY); + } return Err(vm.new_value_error("Cannot convert negative int")); } let value = int @@ -185,26 +200,25 @@ mod resource { } #[pyfunction] - fn getrlimit(resource: PyIntRef, vm: &VirtualMachine) -> PyResult { - let resource = py2rlim(&resource, vm)?; - - if resource >= RLIM_NLIMITS as host_resource::rlim_t { + fn getrlimit(resource: i32, vm: &VirtualMachine) -> PyResult { + if !(0..RLIM_NLIMITS).contains(&resource) { return Err(vm.new_value_error("invalid resource specified")); } - let rlimit = host_resource::getrlimit(resource).map_err(|_| vm.new_last_errno_error())?; + let rlimit = host_resource::getrlimit(resource as host_resource::rlim_t) + .map_err(|e| e.to_pyexception(vm))?; Ok(Limits(rlimit)) } #[pyfunction] - fn setrlimit(resource: PyIntRef, limits: Limits, vm: &VirtualMachine) -> PyResult<()> { - let resource = py2rlim(&resource, vm)?; - - if resource >= RLIM_NLIMITS as host_resource::rlim_t { + fn setrlimit(resource: i32, limits: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + if !(0..RLIM_NLIMITS).contains(&resource) { return Err(vm.new_value_error("invalid resource specified")); } - let res = host_resource::setrlimit(resource, limits.0); + vm.audit("resource.setrlimit", || (resource, limits.clone()))?; + let limits = Limits::try_from_borrowed_object(vm, &limits)?; + let res = host_resource::setrlimit(resource as host_resource::rlim_t, limits.0); res.map_err(|e| match e.kind() { io::ErrorKind::InvalidInput => { diff --git a/crates/stdlib/src/select.rs b/crates/stdlib/src/select.rs index 06cabef301f..d49a074d4fc 100644 --- a/crates/stdlib/src/select.rs +++ b/crates/stdlib/src/select.rs @@ -4,6 +4,7 @@ pub(crate) use decl::module_def; use crate::vm::{ PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::PyListRef, + stdlib::_io::Fildes, }; use rustpython_host_env::select::{self as host_select, FdSet, RawFd, platform::FD_SETSIZE}; use std::io; @@ -17,14 +18,8 @@ struct Selectable { impl TryFromObject for Selectable { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - let fno = obj.try_to_value(vm).or_else(|_| { - let meth = vm.get_method_or_type_error( - obj.clone(), - vm.ctx.interned_str("fileno").unwrap(), - || "select arg must be an int or object with a fileno() method".to_owned(), - )?; - meth.call((), vm)?.try_into_value(vm) - })?; + let Fildes(fd) = Fildes::try_from_object(vm, obj.clone())?; + let fno = fd as RawFd; Ok(Self { obj, fno }) } } @@ -33,13 +28,61 @@ impl TryFromObject for Selectable { mod decl { use super::*; use crate::vm::{ - Py, PyObjectRef, PyResult, VirtualMachine, + AsObject, Py, PyObjectRef, PyResult, VirtualMachine, builtins::{PyModule, PyTypeRef}, convert::ToPyException, - function::Either, - stdlib::time, + stdlib::time::pytime::{self, Round}, }; + use core::time::Duration; + use std::time::Instant; + + // Keep the signed result until each API has applied its negative-timeout + // policy. In particular, overflow must not become an infinite wait. + fn timeout_nanoseconds( + object: Option<&PyObject>, + milliseconds: bool, + vm: &VirtualMachine, + ) -> PyResult> { + let Some(object) = object.filter(|object| !vm.is_none(object)) else { + return Ok(None); + }; + let convert = if milliseconds { + pytime::from_milliseconds_object + } else { + pytime::from_seconds_object + }; + convert(object, Round::Up, vm).map(Some).map_err(|err| { + if err.fast_isinstance(vm.ctx.exceptions.type_error) { + vm.new_type_error(format!( + "timeout must be a real number or None, not {}", + object.class().name() + )) + } else { + err + } + }) + } + + fn timeout_duration(timeout: Option) -> Option { + timeout + .filter(|&ns| ns >= 0) + .map(|ns| Duration::from_nanos(ns as u64)) + } + + fn timeout_deadline( + timeout: Option, + vm: &VirtualMachine, + ) -> PyResult> { + timeout + .map(|duration| { + Instant::now() + .checked_add(duration) + .ok_or_else(|| vm.new_overflow_error("timeout is too large")) + }) + .transpose() + } + #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { #[cfg(windows)] @@ -69,7 +112,7 @@ mod decl { #[pyarg(positional)] xlist: PyObjectRef, #[pyarg(positional, optional)] - timeout: Option>, + timeout: Option, } #[pyfunction] @@ -83,23 +126,27 @@ mod decl { xlist, timeout, } = args; - let mut timeout = timeout.map(|e| match e { - Either::A(f) => f, - Either::B(i) => i as f64, - }); - if let Some(timeout) = timeout - && timeout < 0.0 - { - return Err(vm.new_value_error("timeout must be positive")); + let timeout = timeout_nanoseconds(timeout.as_deref(), false, vm)?; + if let Some(ns) = timeout { + host_select::timeval_from_microseconds(Round::Up.divide(ns, 1000)).ok_or_else( + || vm.new_overflow_error("timestamp out of range for platform time_t"), + )?; + if ns < 0 { + return Err(vm.new_value_error("timeout must be non-negative")); + } } - let deadline = timeout.map(|s| time::time(vm).unwrap() + s); + let mut timeout = timeout_duration(timeout); + let timeval = |duration| { + host_select::duration_to_timeval_ceiling(duration) + .ok_or_else(|| vm.new_overflow_error("timestamp out of range for platform time_t")) + }; let max_fds: usize = cfg_select! { windows => FD_SETSIZE as usize, _ => FD_SETSIZE, }; - let seq2set = |list: &PyObject| -> PyResult<(Vec, FdSet)> { + let seq2set = |list: &PyObject| -> PyResult> { // The limit is answered while the sequence is walked rather than // from the length of the result. fileno() runs Python and can // append to the very list being walked, and a walk that re-reads @@ -108,6 +155,10 @@ mod decl { let seen = core::cell::Cell::new(0usize); let v: Vec = vm.extract_elements_with(list, |obj| { let selectable = Selectable::try_from_object(vm, obj)?; + #[cfg(unix)] + if selectable.fno as usize >= FD_SETSIZE { + return Err(vm.new_value_error("filedescriptor out of range in select()")); + } seen.set(seen.get() + 1); if seen.get() > max_fds { return Err(vm.new_value_error("too many file descriptors in select()")); @@ -115,21 +166,12 @@ mod decl { Ok(selectable) })?; - let mut fds = FdSet::new(); - for fd in &v { - #[cfg(unix)] - if fd.fno as usize >= FD_SETSIZE { - return Err(vm.new_value_error("file descriptor out of range in select()")); - } - - fds.insert(fd.fno); - } - Ok((v, fds)) + Ok(v) }; - let (rlist, _) = seq2set(&rlist)?; - let (wlist, _) = seq2set(&wlist)?; - let (xlist, _) = seq2set(&xlist)?; + let rlist = seq2set(&rlist)?; + let wlist = seq2set(&wlist)?; + let xlist = seq2set(&xlist)?; let nfds = cfg_select! { windows => 0, // value is ignored on windows @@ -160,6 +202,7 @@ mod decl { ) }; + let deadline = timeout_deadline(timeout, vm)?; loop { // `select(2)` updates the fd sets in place. Rebuild them on every // attempt, including EINTR retries; otherwise an interrupted call @@ -168,7 +211,7 @@ mod decl { let mut w = fill(&wlist); let mut x = fill(&xlist); - let mut tv = timeout.map(host_select::sec_to_timeval); + let mut tv = timeout.map(timeval).transpose()?; let res = vm.allow_threads(|| host_select::select(nfds, &mut r, &mut w, &mut x, tv.as_mut())); @@ -182,9 +225,9 @@ mod decl { vm.check_signals()?; - if let Some(ref mut timeout) = timeout { - *timeout = deadline.unwrap() - time::time(vm).unwrap(); - if *timeout < 0.0 { + if let Some(deadline) = deadline { + timeout = deadline.checked_duration_since(Instant::now()); + if timeout.is_none() { return Ok(( vm.ctx.new_list(Vec::new()), vm.ctx.new_list(Vec::new()), @@ -212,67 +255,15 @@ mod decl { pub(super) mod poll { use super::*; use crate::vm::{ - AsObject, PyPayload, - builtins::PyFloat, + PyPayload, common::lock::PyMutex, convert::{IntoPyException, ToPyObject}, function::OptionalArg, stdlib::_io::Fildes, }; - use core::{ - convert::TryFrom, - sync::atomic::{AtomicBool, Ordering}, - time::Duration, - }; - use num_traits::{Signed, ToPrimitive}; + use core::sync::atomic::{AtomicBool, Ordering}; use std::time::Instant; - #[derive(Default)] - pub(super) struct TimeoutArg(pub Option); - - impl TryFromObject for TimeoutArg { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - let timeout = if vm.is_none(&obj) { - None - } else if let Some(float) = obj.downcast_ref::() { - let float = float.to_f64(); - if float.is_nan() { - return Err(vm.new_value_error("Invalid value NaN (not a number)")); - } - if float.is_sign_negative() { - None - } else { - // MILLIS: the Python timeout is in milliseconds. - let secs = if MILLIS { float / 1e3 } else { float }; - Some( - Duration::try_from_secs_f64(secs) - .map_err(|_| vm.new_overflow_error("timeout is too large"))?, - ) - } - } else if let Some(int) = obj.try_index_opt(vm).transpose()? { - if int.as_bigint().is_negative() { - None - } else { - let n = int - .as_bigint() - .to_u64() - .ok_or_else(|| vm.new_overflow_error("value out of range"))?; - Some(if MILLIS { - Duration::from_millis(n) - } else { - Duration::from_secs(n) - }) - } - } else { - return Err(vm.new_type_error(format!( - "expected an int or float for duration, got {}", - obj.class() - ))); - }; - Ok(Self(timeout)) - } - } - #[pyclass(module = "select", name = "poll")] #[derive(Default, Debug, PyPayload)] pub(crate) struct PyPoll { @@ -281,27 +272,20 @@ mod decl { poll_running: AtomicBool, } - // new EventMask type - #[derive(Copy, Clone)] - #[repr(transparent)] - pub(crate) struct EventMask(pub i16); - - impl TryFromObject for EventMask { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - // Event masks go through the integer converter, so `__index__` counts. - let int = obj.try_index(vm)?; - - let val = int.as_bigint(); - if val.is_negative() { - return Err(vm.new_value_error("negative event mask")); - } - - // Try converting to i16, should raise OverflowError if too large - let mask = i16::try_from(val) - .map_err(|_| vm.new_overflow_error("event mask value out of range"))?; + #[derive(FromArgs)] + struct PollRegisterArgs { + #[pyarg(positional)] + fd: PyObjectRef, + #[pyarg(positional, optional)] + eventmask: OptionalArg, + } - Ok(Self(mask)) - } + #[derive(FromArgs)] + struct PollModifyArgs { + #[pyarg(positional)] + fd: PyObjectRef, + #[pyarg(positional)] + eventmask: PyObjectRef, } const DEFAULT_EVENTS: i16 = @@ -310,26 +294,34 @@ mod decl { #[pyclass(flags(DISALLOW_INSTANTIATION))] impl PyPoll { #[pymethod] - fn register(zelf: &Py, Fildes(fd): Fildes, eventmask: OptionalArg) { - let mask = match eventmask { - OptionalArg::Present(event_mask) => event_mask.0, + fn register( + zelf: &Py, + args: PollRegisterArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + let Fildes(fd) = Fildes::try_from_object(vm, args.fd.clone())?; + let mask = match args.eventmask.as_ref() { + OptionalArg::Present(mask) => u16::try_from_object(vm, mask.clone())? as i16, OptionalArg::Missing => DEFAULT_EVENTS, }; host_select::insert_poll_fd(&mut zelf.fds.lock(), fd, mask); + Ok(()) } #[pymethod] - fn modify( - zelf: &Py, - Fildes(fd): Fildes, - eventmask: EventMask, - vm: &VirtualMachine, - ) -> PyResult<()> { + fn modify(zelf: &Py, args: PollModifyArgs, vm: &VirtualMachine) -> PyResult<()> { + let Fildes(fd) = Fildes::try_from_object(vm, args.fd.clone())?; + #[expect( + clippy::redundant_clone, + reason = "Keep raw argument alive through conversion" + )] + let eventmask = u16::try_from_object(vm, args.eventmask.clone())? as i16; let mut fds = zelf.fds.lock(); - // CPython raises KeyError if fd is not registered, match that behavior - let pfd = host_select::get_poll_fd_mut(&mut fds, fd) - .ok_or_else(|| vm.new_key_error(vm.ctx.new_int(fd).into()))?; - pfd.events = eventmask.0; + // Unlike unregister(), modify() reports an unregistered fd as ENOENT. + let pfd = host_select::get_poll_fd_mut(&mut fds, fd).ok_or_else(|| { + io::Error::from_raw_os_error(libc::ENOENT).into_pyexception(vm) + })?; + pfd.events = eventmask; Ok(()) } @@ -348,9 +340,27 @@ mod decl { #[pymethod] fn poll( zelf: &Py, - timeout: OptionalArg>, + timeout: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { + let timeout = timeout_nanoseconds( + timeout.as_ref().into_option().map(|obj| &**obj), + true, + vm, + )?; + #[cfg(not(any(target_os = "linux", target_os = "android")))] + if let Some(ns) = timeout { + i32::try_from(Round::Up.divide(ns, 1_000_000)) + .map_err(|_| vm.new_overflow_error("timeout is too large"))?; + } + let mut poll_timeout = host_select::PollTimeout::from_nanoseconds(timeout) + .ok_or_else(|| vm.new_overflow_error("timeout is too large"))?; + let timeout = timeout_duration(timeout); + let native_timeout = |timeout| { + host_select::PollTimeout::from_duration(timeout) + .ok_or_else(|| vm.new_overflow_error("timeout is too large")) + }; + let deadline = timeout_deadline(timeout, vm)?; if zelf.poll_running.swap(true, Ordering::SeqCst) { return Err(vm.new_runtime_error("concurrent poll() invocation")); } @@ -366,22 +376,10 @@ mod decl { // signal handlers, which can register or unregister on the same // object, and a held lock would deadlock them. let mut fds = zelf.fds.lock().clone(); - let TimeoutArg(timeout) = timeout.unwrap_or_default(); - let timeout_ms = match timeout { - Some(d) => host_select::duration_as_millis_ceiling(d) - .ok_or_else(|| vm.new_overflow_error("value out of range"))?, - None => -1i32, - }; - let deadline = timeout - .map(|d| { - Instant::now() - .checked_add(d) - .ok_or_else(|| vm.new_overflow_error("timeout is too large")) - }) - .transpose()?; - let mut poll_timeout = timeout_ms; loop { - match vm.allow_threads(|| host_select::poll_fds(&mut fds, poll_timeout)) { + match vm.allow_threads(|| { + host_select::poll_fds_with_timeout(&mut fds, &poll_timeout) + }) { Ok(_) => break, Err(err) if err.raw_os_error() == Some(host_select::EINTR) => { vm.check_signals()? @@ -390,24 +388,23 @@ mod decl { } if let Some(d) = deadline { if let Some(remaining) = d.checked_duration_since(Instant::now()) { - poll_timeout = host_select::duration_as_millis_ceiling(remaining) - .ok_or_else(|| vm.new_overflow_error("value out of range"))?; + poll_timeout = native_timeout(Some(remaining))?; } else { - break; + return Ok(Vec::new()); } } } Ok(fds .iter() .filter(|pfd| pfd.revents != 0) - .map(|pfd| (pfd.fd, pfd.revents & 0xfff).to_pyobject(vm)) + .map(|pfd| (pfd.fd, pfd.revents as u16).to_pyobject(vm)) .collect()) } } } #[cfg(any(target_os = "linux", target_os = "android", target_os = "redox"))] - #[pyattr(name = "epoll", once)] + #[pyattr(once)] fn epoll(_vm: &VirtualMachine) -> PyTypeRef { use crate::vm::class::PyClassImpl; epoll::PyEpoll::make_static_type() @@ -437,13 +434,14 @@ mod decl { types::Constructor, }; use core::ops::Deref; - use std::os::fd::{AsRawFd, OwnedFd}; + use host_select::epoll::EpollFd; + use std::os::fd::AsRawFd; use std::time::Instant; #[pyclass(module = "select", name = "epoll")] #[derive(Debug, rustpython_vm::PyPayload)] pub(crate) struct PyEpoll { - epoll_fd: PyRwLock>, + epoll_fd: PyRwLock>, } #[derive(FromArgs)] @@ -468,12 +466,58 @@ mod decl { } } + #[derive(FromArgs)] + struct EpollUnregisterArgs { + #[pyarg(any)] + fd: PyObjectRef, + } + + #[derive(FromArgs)] + struct EpollRegisterArgs { + #[pyarg(any)] + fd: PyObjectRef, + #[pyarg( + any, + optional, + py_default = "select.EPOLLIN | select.EPOLLPRI | select.EPOLLOUT" + )] + eventmask: OptionalArg, + } + + #[derive(FromArgs)] + struct EpollModifyArgs { + #[pyarg(any)] + fd: PyObjectRef, + #[pyarg(any)] + eventmask: PyObjectRef, + } + + fn epoll_eventmask(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + use crate::vm::function::ArgIndex; + + (|| { + let value = ArgIndex::try_from_object(vm, obj.clone())?; + Ok(value.as_unsigned_bitfield::<32>(vm)? as u32) + })() + } + #[derive(FromArgs)] struct EpollPollArgs { - #[pyarg(any, default)] - timeout: poll::TimeoutArg, - #[pyarg(any, default = -1)] - maxevents: i32, + #[pyarg(any, default, py_default = "None")] + timeout: Option, + #[pyarg(any, default, py_default = "-1")] + maxevents: OptionalArg, + } + + #[derive(FromArgs)] + #[allow(dead_code)] + struct EpollExitArgs { + #[pyarg(positional, default = None)] + exc_type: Option, + #[pyarg(positional, default = None)] + exc_value: Option, + #[pyarg(positional, default = None)] + exc_tb: Option, } #[pyclass(with(Constructor))] @@ -501,57 +545,78 @@ mod decl { fn get_epoll( &self, vm: &VirtualMachine, - ) -> PyResult + '_> { + ) -> PyResult + '_> { PyRwLockReadGuard::try_map(self.epoll_fd.read(), |x| x.as_ref()) .map_err(|_| vm.new_value_error("I/O operation on closed epoll object")) } #[pymethod] fn fileno(zelf: &Py, vm: &VirtualMachine) -> PyResult { - zelf.get_epoll(vm).map(|epoll_fd| epoll_fd.as_raw_fd()) + zelf.get_epoll(vm).map(|epoll_fd| epoll_fd.as_raw()) } #[pyclassmethod] - fn fromfd(cls: PyTypeRef, fd: OwnedFd, vm: &VirtualMachine) -> PyResult> { - let epoll_fd = Some(fd).into(); + fn fromfd(cls: PyTypeRef, fd: i32, vm: &VirtualMachine) -> PyResult> { + if fd == -1 { + return Err(std::io::Error::from_raw_os_error(libc::EBADF).into_pyexception(vm)); + } + let epoll_fd = Some(EpollFd::from_raw(fd)).into(); Self { epoll_fd }.into_ref_with_type(vm, cls) } #[pymethod] fn register( zelf: &Py, - fd: Fildes, - eventmask: OptionalArg, + args: EpollRegisterArgs, vm: &VirtualMachine, ) -> PyResult<()> { - let events = match eventmask { - OptionalArg::Present(mask) => mask, + let fd = Fildes::try_from_object(vm, args.fd.clone())?; + let events = match args.eventmask.as_ref() { + OptionalArg::Present(mask) => epoll_eventmask(mask.clone(), vm)?, OptionalArg::Missing => (host_select::epoll::EventFlags::IN | host_select::epoll::EventFlags::PRI | host_select::epoll::EventFlags::OUT) .bits(), }; let epoll_fd = &*zelf.get_epoll(vm)?; - host_select::epoll::add(epoll_fd, fd, fd.as_raw_fd() as u64, events) + host_select::epoll::add(epoll_fd, fd.as_raw_fd(), fd.as_raw_fd() as u64, events) .map_err(|e| e.into_pyexception(vm)) } #[pymethod] - fn modify( - zelf: &Py, - fd: Fildes, - eventmask: u32, - vm: &VirtualMachine, - ) -> PyResult<()> { + fn modify(zelf: &Py, args: EpollModifyArgs, vm: &VirtualMachine) -> PyResult<()> { + // Bind the full call before fileno(), __index__(), or warning hooks run. + let fd = Fildes::try_from_object(vm, args.fd.clone())?; + #[expect( + clippy::redundant_clone, + reason = "Keep raw argument alive through conversion and syscall" + )] + let eventmask = epoll_eventmask(args.eventmask.clone(), vm)?; let epoll_fd = &*zelf.get_epoll(vm)?; - host_select::epoll::modify(epoll_fd, fd, fd.as_raw_fd() as u64, eventmask) - .map_err(|e| e.into_pyexception(vm)) + host_select::epoll::modify( + epoll_fd, + fd.as_raw_fd(), + fd.as_raw_fd() as u64, + eventmask, + ) + .map_err(|e| e.into_pyexception(vm)) } #[pymethod] - fn unregister(zelf: &Py, fd: Fildes, vm: &VirtualMachine) -> PyResult<()> { + fn unregister( + zelf: &Py, + args: EpollUnregisterArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + // Validate the argument shape before fileno() can run Python code. + #[expect( + clippy::redundant_clone, + reason = "Keep descriptor object alive through the syscall" + )] + let fd = Fildes::try_from_object(vm, args.fd.clone())?; let epoll_fd = &*zelf.get_epoll(vm)?; - host_select::epoll::delete(epoll_fd, fd).map_err(|e| e.into_pyexception(vm)) + host_select::epoll::delete(epoll_fd, fd.as_raw_fd()) + .map_err(|e| e.into_pyexception(vm)) } #[pymethod] @@ -560,23 +625,38 @@ mod decl { args: EpollPollArgs, vm: &VirtualMachine, ) -> PyResult { - let poll::TimeoutArg(timeout) = args.timeout; - let maxevents = args.maxevents; - - let mut poll_timeout = timeout - .map(host_select::epoll::Timespec::try_from) - .transpose() - .map_err(|_| vm.new_overflow_error("timeout is too large"))?; - - let deadline = timeout - .map(|d| { - Instant::now() - .checked_add(d) - .ok_or_else(|| vm.new_overflow_error("timeout is too large")) - }) - .transpose()?; + let maxevents = match args.maxevents.as_ref() { + OptionalArg::Present(value) => i32::try_from_object(vm, value.clone())?, + OptionalArg::Missing => -1, + }; + // The closed check precedes timeout callbacks, but the read lock + // must not be held while a callback can close this object. + drop(zelf.get_epoll(vm)?); + let nanoseconds = timeout_nanoseconds(args.timeout.as_deref(), false, vm)?; + if let Some(ns) = nanoseconds { + i32::try_from(Round::Ceiling.divide(ns, 1_000_000)) + .map_err(|_| vm.new_overflow_error("timeout is too large"))?; + } + // Negative sub-millisecond values round to zero for epoll_wait. + let timeout = timeout_duration(nanoseconds.map(|ns| { + if ns < 0 && Round::Ceiling.divide(ns, 1_000_000) == 0 { + 0 + } else { + ns + } + })); + + // epoll_wait takes signed milliseconds; round upward and reject + // overflow, matching CPython's epoll.poll conversion. + let to_millis = |timeout| { + host_select::duration_as_millis_ceiling(timeout) + .ok_or_else(|| vm.new_overflow_error("timeout is too large")) + }; + let mut poll_timeout = timeout.map(to_millis).transpose()?.unwrap_or(-1); + + let deadline = timeout_deadline(timeout_duration(nanoseconds), vm)?; let maxevents = match maxevents { - ..-1 => { + ..=-2 | 0 => { return Err(vm.new_value_error(format!( "maxevents must be greater than 0, got {maxevents}" ))); @@ -591,7 +671,7 @@ mod decl { loop { match vm.allow_threads(|| { - host_select::epoll::wait(epoll, &mut events, poll_timeout.as_ref()) + host_select::epoll::wait(epoll, &mut events, poll_timeout) }) { Ok(_) => break, Err(host_select::epoll::WaitError::Interrupted) => vm.check_signals()?, @@ -601,11 +681,7 @@ mod decl { } if let Some(deadline) = deadline { if let Some(new_timeout) = deadline.checked_duration_since(Instant::now()) { - poll_timeout = Some( - new_timeout - .try_into() - .map_err(|_| vm.new_overflow_error("timeout is too large"))?, - ); + poll_timeout = to_millis(new_timeout)?; } else { break; } @@ -614,7 +690,7 @@ mod decl { let ret = events .iter() - .map(|ev| (ev.data.u64() as i32, { ev.flags }.bits()).to_pyobject(vm)) + .map(|ev| (ev.data() as i32, ev.flags()).to_pyobject(vm)) .collect(); Ok(vm.ctx.new_list(ret)) @@ -627,12 +703,7 @@ mod decl { } #[pymethod] - fn __exit__( - zelf: &Py, - _exc_type: OptionalArg, - _exc_value: OptionalArg, - _exc_tb: OptionalArg, - ) -> std::io::Result<()> { + fn __exit__(zelf: &Py, _args: EpollExitArgs) -> std::io::Result<()> { Self::close(zelf) } } @@ -703,7 +774,7 @@ mod decl { use super::*; use crate::vm::{ Py, PyObject, PyPayload, PyRef, - builtins::{PyFloat, PyType}, + builtins::PyType, class_or_notimplemented, common::lock::PyRwLock, convert::{IntoPyException, ToPyObject}, @@ -714,7 +785,6 @@ mod decl { use core::sync::atomic::{ AtomicI16, AtomicI32, AtomicI64, AtomicU16, AtomicU32, AtomicU64, Ordering, }; - use num_traits::ToPrimitive; use std::time::Instant; #[pyclass(module = "select", name = "kevent")] @@ -880,36 +950,14 @@ mod decl { } fn timespec_from_timeout( - timeout: Option, + timeout: Option<&PyObject>, vm: &VirtualMachine, ) -> PyResult> { - let Some(obj) = timeout else { - return Ok(None); - }; - if vm.is_none(&obj) { - return Ok(None); - } - let secs = if let Some(float) = obj.downcast_ref::() { - float.to_f64() - } else if let Some(int) = obj.try_index_opt(vm).transpose()? { - int.as_bigint() - .to_f64() - .ok_or_else(|| vm.new_overflow_error("timeout is too large"))? - } else { - return Err(vm.new_type_error(format!( - "timeout argument must be a number or None, got {}", - obj.class() - ))); - }; - if secs.is_nan() { - return Err(vm.new_value_error("Invalid value NaN (not a number)")); - } - if secs < 0.0 { + let timeout = timeout_nanoseconds(timeout, false, vm)?; + if timeout.is_some_and(|ns| ns < 0) { return Err(vm.new_value_error("timeout must be positive or None")); } - host_select::kqueue::Timespec::from_secs(secs) - .ok_or_else(|| vm.new_overflow_error("timeout is too large")) - .map(Some) + Ok(timeout_duration(timeout).map(host_select::kqueue::Timespec::from_duration)) } #[pyclass(with(Constructor, Destructor))] @@ -964,6 +1012,7 @@ mod decl { args: KqueueControlArgs, vm: &VirtualMachine, ) -> PyResult { + Self::fd_or_closed(zelf.kqfd.read().as_ref(), vm)?; if args.maxevents < 0 { return Err(vm.new_value_error(format!( "Length of eventlist must be 0 or positive, got {}", @@ -971,18 +1020,7 @@ mod decl { ))); } - let mut timeout = timespec_from_timeout(args.timeout, vm)?; - let deadline = timeout - .map(|ts| { - let duration = ts - .to_duration() - .ok_or_else(|| vm.new_overflow_error("timeout is too large"))?; - Instant::now() - .checked_add(duration) - .ok_or_else(|| vm.new_overflow_error("timeout is too large")) - }) - .transpose()?; - + let mut timeout = timespec_from_timeout(args.timeout.as_deref(), vm)?; let changelist = if vm.is_none(&args.changelist) { Vec::new() } else { @@ -1003,6 +1041,7 @@ mod decl { let mut eventlist = vec![host_select::kqueue::Event::default(); args.maxevents as usize]; + let deadline = timeout_deadline(timeout.and_then(|ts| ts.to_duration()), vm)?; let n = loop { let result = { let guard = zelf.kqfd.read(); diff --git a/crates/stdlib/src/sha1.rs b/crates/stdlib/src/sha1.rs index 71495435e56..0770f2fd59c 100644 --- a/crates/stdlib/src/sha1.rs +++ b/crates/stdlib/src/sha1.rs @@ -2,12 +2,12 @@ pub(crate) use _sha1::module_def; #[pymodule] mod _sha1 { - use crate::hashlib::_hashlib::{HashArgs, local_sha1}; + use crate::hashlib::_hashlib::{HashArgs, openssl_sha1}; use crate::vm::{Py, PyPayload, PyResult, VirtualMachine, builtins::PyModule}; #[pyfunction] fn sha1(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha1(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha1(args, vm)?.into_pyobject(vm)) } #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] diff --git a/crates/stdlib/src/sha256.rs b/crates/stdlib/src/sha256.rs index 6cc2e2ccb29..deed061cc49 100644 --- a/crates/stdlib/src/sha256.rs +++ b/crates/stdlib/src/sha256.rs @@ -1,16 +1,16 @@ #[pymodule] mod _sha256 { - use crate::hashlib::_hashlib::{HashArgs, local_sha224, local_sha256}; + use crate::hashlib::_hashlib::{HashArgs, openssl_sha224, openssl_sha256}; use crate::vm::{Py, PyPayload, PyResult, VirtualMachine, builtins::PyModule}; #[pyfunction] fn sha224(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha224(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha224(args, vm)?.into_pyobject(vm)) } #[pyfunction] fn sha256(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha256(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha256(args, vm)?.into_pyobject(vm)) } #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] diff --git a/crates/stdlib/src/sha3.rs b/crates/stdlib/src/sha3.rs index 642ed838a4d..a65d06f201d 100644 --- a/crates/stdlib/src/sha3.rs +++ b/crates/stdlib/src/sha3.rs @@ -3,39 +3,39 @@ pub(crate) use _sha3::module_def; #[pymodule] mod _sha3 { use crate::hashlib::_hashlib::{ - HashArgs, local_sha3_224, local_sha3_256, local_sha3_384, local_sha3_512, local_shake_128, - local_shake_256, + HashArgs, openssl_sha3_224, openssl_sha3_256, openssl_sha3_384, openssl_sha3_512, + openssl_shake_128, openssl_shake_256, }; use crate::vm::{Py, PyPayload, PyResult, VirtualMachine, builtins::PyModule}; #[pyfunction] fn sha3_224(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha3_224(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha3_224(args, vm)?.into_pyobject(vm)) } #[pyfunction] fn sha3_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha3_256(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha3_256(args, vm)?.into_pyobject(vm)) } #[pyfunction] fn sha3_384(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha3_384(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha3_384(args, vm)?.into_pyobject(vm)) } #[pyfunction] fn sha3_512(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha3_512(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha3_512(args, vm)?.into_pyobject(vm)) } #[pyfunction] fn shake_128(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_shake_128(args, vm)?.into_pyobject(vm)) + Ok(openssl_shake_128(args, vm)?.into_pyobject(vm)) } #[pyfunction] fn shake_256(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_shake_256(args, vm)?.into_pyobject(vm)) + Ok(openssl_shake_256(args, vm)?.into_pyobject(vm)) } #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] diff --git a/crates/stdlib/src/sha512.rs b/crates/stdlib/src/sha512.rs index e34f06577ab..5a32b3957ca 100644 --- a/crates/stdlib/src/sha512.rs +++ b/crates/stdlib/src/sha512.rs @@ -1,16 +1,16 @@ #[pymodule] mod _sha512 { - use crate::hashlib::_hashlib::{HashArgs, local_sha384, local_sha512}; + use crate::hashlib::_hashlib::{HashArgs, openssl_sha384, openssl_sha512}; use crate::vm::{Py, PyPayload, PyResult, VirtualMachine, builtins::PyModule}; #[pyfunction] fn sha384(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha384(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha384(args, vm)?.into_pyobject(vm)) } #[pyfunction] fn sha512(args: HashArgs, vm: &VirtualMachine) -> PyResult { - Ok(local_sha512(args, vm)?.into_pyobject(vm)) + Ok(openssl_sha512(args, vm)?.into_pyobject(vm)) } #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__adjacent_no_location_entries.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__adjacent_no_location_entries.snap new file mode 100644 index 00000000000..a595fb16a81 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__adjacent_no_location_entries.snap @@ -0,0 +1,106 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(file):\n if sys.platform == \"win32\":\n try:\n import nt\n if not nt._supports_virtual_terminal():\n return False\n except (ImportError, AttributeError):\n return False\n try:\n return os.isatty(file.fileno())\n except OSError:\n return hasattr(file, \"isatty\") and file.isatty()\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-12:56 LOAD_CONST 0 (", line 1>) +1:0-12:56 MAKE_FUNCTION +1:0-12:56 STORE_NAME 0 (f) +1:0-12:56 LOAD_COMMON_CONSTANT 7 (None) +1:0-12:56 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:7-2:10 LOAD_GLOBAL 0 (sys) +2:7-2:19 LOAD_ATTR 2 (platform) +2:23-2:30 LOAD_CONST 0 ('win32') +2:7-2:30 COMPARE_OP 88 (bool(==)) +2:7-2:30 POP_JUMP_IF_FALSE 31 (to L4) +2:7-2:30 NOT_TAKEN + +3:8-8:24 NOP + +4:12-4:21 L1: LOAD_SMALL_INT 0 +4:12-4:21 LOAD_COMMON_CONSTANT 7 (None) +4:12-4:21 IMPORT_NAME 10 (nt + eager) +4:12-4:21 STORE_FAST 1 (nt) + +5:19-5:21 LOAD_FAST_BORROW 1 (nt) +5:19-5:48 LOAD_ATTR 7 (_supports_virtual_terminal + NULL|self) +5:19-5:50 CALL 0 +5:19-5:50 TO_BOOL +5:19-5:50 POP_JUMP_IF_TRUE 3 (to L3) +5:19-5:50 NOT_TAKEN + +6:23-6:28 L2: LOAD_COMMON_CONSTANT 10 (False) +6:23-6:28 RETURN_VALUE + +5:19-5:50 L3: NOP + +9:4-12:56 L4: NOP + +10:15-10:17 L5: LOAD_GLOBAL 12 (os) +10:15-10:24 LOAD_ATTR 15 (isatty + NULL|self) +10:25-10:29 LOAD_FAST_BORROW 0 (file) +10:25-10:36 LOAD_ATTR 17 (fileno + NULL|self) +10:25-10:38 CALL 0 +10:15-10:39 CALL 1 +10:8-10:39 L6: RETURN_VALUE + + -- L7: PUSH_EXC_INFO + +7:16-7:27 LOAD_GLOBAL 8 (ImportError) +7:29-7:43 LOAD_GLOBAL 10 (AttributeError) +7:15-7:44 BUILD_TUPLE 2 +7:8-8:24 CHECK_EXC_MATCH +7:8-8:24 POP_JUMP_IF_FALSE 5 (to L9) +7:8-8:24 NOT_TAKEN +7:8-8:24 POP_TOP + +8:19-8:24 L8: POP_EXCEPT +8:19-8:24 LOAD_COMMON_CONSTANT 10 (False) +8:19-8:24 RETURN_VALUE + +7:8-8:24 L9: RERAISE 0 + + -- L10: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 + -- L11: PUSH_EXC_INFO + +11:11-11:18 LOAD_GLOBAL 18 (OSError) +11:4-12:56 CHECK_EXC_MATCH +11:4-12:56 POP_JUMP_IF_FALSE 40 (to L14) +11:4-12:56 NOT_TAKEN +11:4-12:56 POP_TOP + +12:15-12:22 LOAD_GLOBAL 21 (hasattr + NULL) +12:23-12:27 LOAD_FAST 0 (file) +12:29-12:37 LOAD_CONST 1 ('isatty') +12:15-12:38 CALL 2 +12:15-12:56 COPY 1 +12:15-12:56 TO_BOOL +12:15-12:56 POP_JUMP_IF_FALSE 17 (to L12) +12:15-12:56 NOT_TAKEN +12:15-12:56 POP_TOP +12:43-12:47 LOAD_FAST 0 (file) +12:43-12:54 LOAD_ATTR 15 (isatty + NULL|self) +12:43-12:56 CALL 0 +12:8-12:56 L12: SWAP 2 +12:8-12:56 L13: POP_EXCEPT +12:8-12:56 RETURN_VALUE + +11:4-12:56 L14: RERAISE 0 + + -- L15: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L7 [0] + L5 to L6 -> L11 [0] + L7 to L8 -> L10 [1] lasti + L9 to L10 -> L10 [1] lasti + L11 to L13 -> L15 [1] lasti + L14 to L15 -> L15 [1] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__annotated_multiline_function_firstlineno.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__annotated_multiline_function_firstlineno.snap new file mode 100644 index 00000000000..98bf8123a15 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__annotated_multiline_function_firstlineno.snap @@ -0,0 +1,39 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\n\na = 1\ndef f(\n x: a,\n): ...\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:4-1:5 LOAD_SMALL_INT 1 +1:0-1:1 STORE_NAME 0 (a) + +2:0-4:6 LOAD_CONST 1 (", line 2>) +2:0-4:6 MAKE_FUNCTION +2:0-4:6 LOAD_CONST 2 (", line 2>) +2:0-4:6 MAKE_FUNCTION +2:0-4:6 SET_FUNCTION_ATTRIBUTE 16 (annotate) +2:0-4:6 STORE_NAME 1 (f) +2:0-4:6 LOAD_COMMON_CONSTANT 7 (None) +2:0-4:6 RETURN_VALUE + +Disassembly of ", line 2>: +2:0-2:0 RESUME 0 +2:0-4:6 LOAD_FAST_BORROW 0 (format) +2:0-4:6 LOAD_SMALL_INT 2 +2:0-4:6 COMPARE_OP 132 (>) +2:0-4:6 POP_JUMP_IF_FALSE 3 (to L1) +2:0-4:6 NOT_TAKEN +2:0-4:6 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +2:0-4:6 RAISE_VARARGS 1 +2:0-4:6 L1: LOAD_CONST 1 ('x') + +3:7-3:8 LOAD_GLOBAL 0 (a) + +2:0-4:6 BUILD_MAP 1 +2:0-4:6 RETURN_VALUE + +Disassembly of ", line 2>: +2:0-2:0 RESUME 0 + +4:3-4:6 LOAD_COMMON_CONSTANT 7 (None) +4:3-4:6 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__annotation_scope_function_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__annotation_scope_function_location.snap new file mode 100644 index 00000000000..e8dec1373fc --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__annotation_scope_function_location.snap @@ -0,0 +1,44 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\n\ndef g():\n def f(x: not (int is int), /): ...\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-2:38 LOAD_CONST 0 (", line 1>) +1:0-2:38 MAKE_FUNCTION +1:0-2:38 STORE_NAME 0 (g) +1:0-2:38 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:38 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:4-2:38 LOAD_CONST 0 (", line 2>) +2:4-2:38 MAKE_FUNCTION +2:4-2:38 LOAD_CONST 1 (", line 2>) +2:4-2:38 MAKE_FUNCTION +2:4-2:38 SET_FUNCTION_ATTRIBUTE 16 (annotate) +2:4-2:38 STORE_FAST 0 (f) +2:4-2:38 LOAD_COMMON_CONSTANT 7 (None) +2:4-2:38 RETURN_VALUE + +Disassembly of ", line 2>: +2:0-2:0 RESUME 0 +2:4-2:38 LOAD_FAST_BORROW 0 (format) +2:4-2:38 LOAD_SMALL_INT 2 +2:4-2:38 COMPARE_OP 132 (>) +2:4-2:38 POP_JUMP_IF_FALSE 3 (to L1) +2:4-2:38 NOT_TAKEN +2:4-2:38 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +2:4-2:38 RAISE_VARARGS 1 +2:4-2:38 L1: LOAD_CONST 1 ('x') +2:18-2:21 LOAD_GLOBAL 0 (int) +2:25-2:28 LOAD_GLOBAL 0 (int) +2:13-2:29 IS_OP 1 (is not) +2:4-2:38 BUILD_MAP 1 +2:4-2:38 RETURN_VALUE + +Disassembly of ", line 2>: +2:0-2:0 RESUME 0 +2:35-2:38 LOAD_COMMON_CONSTANT 7 (None) +2:35-2:38 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__assert_false_message_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__assert_false_message_location.snap new file mode 100644 index 00000000000..e0c9da9f252 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__assert_false_message_location.snap @@ -0,0 +1,19 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f():\n assert False, \"x\"\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-2:21 LOAD_CONST 0 (", line 1>) +1:0-2:21 MAKE_FUNCTION +1:0-2:21 STORE_NAME 0 (f) +1:0-2:21 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:21 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:4-2:21 LOAD_COMMON_CONSTANT 0 (AssertionError) +2:18-2:21 LOAD_CONST 1 ('x') +2:4-2:21 CALL 0 +2:11-2:16 RAISE_VARARGS 1 diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__async_for_anext_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__async_for_anext_location.snap new file mode 100644 index 00000000000..57a303b673e --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__async_for_anext_location.snap @@ -0,0 +1,57 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nasync def f(source, buffer):\n async for i1, i2 in source():\n buffer.append(i1 + i2)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-3:30 LOAD_CONST 0 (", line 1>) +1:0-3:30 MAKE_FUNCTION +1:0-3:30 STORE_NAME 0 (f) +1:0-3:30 LOAD_COMMON_CONSTANT 7 (None) +1:0-3:30 RETURN_VALUE + +Disassembly of ", line 1>: +1:?-1:? RETURN_GENERATOR +1:?-1:? POP_TOP +1:0-1:0 L1: RESUME 0 + +2:24-2:30 LOAD_FAST_BORROW 0 (source) +2:24-2:30 PUSH_NULL +2:24-2:32 CALL 0 +2:24-2:32 GET_AITER +2:4-3:30 L2: GET_ANEXT +2:4-3:30 PUSH_NULL +2:4-3:30 LOAD_COMMON_CONSTANT 7 (None) +2:4-3:30 L3: SEND 4 (to L6) +2:4-3:30 L4: YIELD_VALUE 1 +2:4-3:30 L5: RESUME 3 +2:4-3:30 JUMP_BACKWARD_NO_INTERRUPT 6 (to L3) +2:4-3:30 L6: END_SEND +2:4-3:30 L7: NOT_TAKEN +2:14-2:20 UNPACK_SEQUENCE 2 +2:14-2:16 STORE_FAST_STORE_FAST 35 (i1, i2) + +3:8-3:14 LOAD_FAST_BORROW 1 (buffer) +3:8-3:21 LOAD_ATTR 1 (append + NULL|self) +3:22-3:24 LOAD_FAST_BORROW_LOAD_FAST_BORROW 35 (i1, i2) +3:22-3:29 BINARY_OP 0 (+) +3:8-3:30 CALL 1 +3:8-3:30 POP_TOP +3:8-3:30 JUMP_BACKWARD 39 (to L2) + +2:4-3:30 L8: CLEANUP_THROW +2:4-3:30 L9: JUMP_BACKWARD_NO_INTERRUPT 32 (to L6) +2:24-2:32 L10: END_ASYNC_FOR 33 (from L6) +2:24-2:32 LOAD_COMMON_CONSTANT 7 (None) +2:24-2:32 RETURN_VALUE + + -- L11: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L11 [0] lasti + L2 to L4 -> L10 [1] + L4 to L5 -> L8 [4] + L5 to L7 -> L10 [1] + L7 to L8 -> L11 [0] lasti + L8 to L9 -> L10 [1] + L10 to L11 -> L11 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__async_for_end_async_for.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__async_for_end_async_for.snap new file mode 100644 index 00000000000..5583383e472 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__async_for_end_async_for.snap @@ -0,0 +1,48 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nasync def f(xs):\n async for x in xs:\n pass\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-3:12 LOAD_CONST 0 (", line 1>) +1:0-3:12 MAKE_FUNCTION +1:0-3:12 STORE_NAME 0 (f) +1:0-3:12 LOAD_COMMON_CONSTANT 7 (None) +1:0-3:12 RETURN_VALUE + +Disassembly of ", line 1>: +1:?-1:? RETURN_GENERATOR +1:?-1:? POP_TOP +1:0-1:0 L1: RESUME 0 + +2:19-2:21 LOAD_FAST_BORROW 0 (xs) +2:19-2:21 GET_AITER +2:4-3:12 L2: GET_ANEXT +2:4-3:12 PUSH_NULL +2:4-3:12 LOAD_COMMON_CONSTANT 7 (None) +2:4-3:12 L3: SEND 4 (to L6) +2:4-3:12 L4: YIELD_VALUE 1 +2:4-3:12 L5: RESUME 3 +2:4-3:12 JUMP_BACKWARD_NO_INTERRUPT 6 (to L3) +2:4-3:12 L6: END_SEND +2:4-3:12 L7: NOT_TAKEN +2:14-2:15 STORE_FAST 1 (x) + +3:8-3:12 JUMP_BACKWARD 14 (to L2) + +2:4-3:12 L8: CLEANUP_THROW +2:4-3:12 L9: JUMP_BACKWARD_NO_INTERRUPT 7 (to L6) +2:19-2:21 L10: END_ASYNC_FOR 8 (from L6) +2:19-2:21 LOAD_COMMON_CONSTANT 7 (None) +2:19-2:21 RETURN_VALUE + + -- L11: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L11 [0] lasti + L2 to L4 -> L10 [1] + L4 to L5 -> L8 [4] + L5 to L7 -> L10 [1] + L7 to L8 -> L11 [0] lasti + L8 to L9 -> L10 [1] + L10 to L11 -> L11 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__augassign_constant_slice_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__augassign_constant_slice_location.snap new file mode 100644 index 00000000000..8c44eba81d9 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__augassign_constant_slice_location.snap @@ -0,0 +1,27 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef aug_const(x, y):\n x[1:2] += y\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-2:15 LOAD_CONST 0 (", line 1>) +1:0-2:15 MAKE_FUNCTION +1:0-2:15 STORE_NAME 0 (aug_const) +1:0-2:15 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:15 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:4-2:5 LOAD_FAST_BORROW 0 (x) +2:6-2:9 LOAD_CONST 0 (slice(1, 2, None)) +2:4-2:10 COPY 2 +2:4-2:10 COPY 2 +2:4-2:10 BINARY_OP 26 ([]) +2:14-2:15 LOAD_FAST_BORROW 1 (y) +2:4-2:15 BINARY_OP 13 (+=) +2:4-2:10 SWAP 3 +2:4-2:10 SWAP 2 +2:4-2:10 STORE_SUBSCR +2:4-2:10 LOAD_COMMON_CONSTANT 7 (None) +2:4-2:10 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__bare_function_annotations_check_attribute_and_subscript_expressions.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__bare_function_annotations_check_attribute_and_subscript_expressions.snap index c0cac3bbb98..76a7e0d8871 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__bare_function_annotations_check_attribute_and_subscript_expressions.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__bare_function_annotations_check_attribute_and_subscript_expressions.snap @@ -11,7 +11,7 @@ expression: "dis(r#\"\ndef f(one: int):\n int.new_attr: int\n [list][0].ne MAKE_FUNCTION SET_FUNCTION_ATTRIBUTE 16 (annotate) STORE_NAME 0 (f) - LOAD_CONST 2 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE Disassembly of ", line 1>: diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__builtin_any_genexpr_call.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__builtin_any_genexpr_call.snap new file mode 100644 index 00000000000..674ca418cfe --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__builtin_any_genexpr_call.snap @@ -0,0 +1,70 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(xs):\n return any(x for x in xs)\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-2:29 LOAD_CONST 0 (", line 1>) +1:0-2:29 MAKE_FUNCTION +1:0-2:29 STORE_NAME 0 (f) +1:0-2:29 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:29 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:14 LOAD_GLOBAL 0 (any) +2:11-2:14 COPY 1 +2:11-2:14 LOAD_COMMON_CONSTANT 4 () +2:11-2:14 IS_OP 0 (is) +2:11-2:14 POP_JUMP_IF_FALSE 28 (to L4) +2:11-2:14 NOT_TAKEN +2:11-2:14 POP_TOP +2:14-2:29 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:14-2:29 MAKE_FUNCTION +2:26-2:28 LOAD_FAST_BORROW 0 (xs) +2:14-2:29 CALL 0 +2:11-2:14 PUSH_NULL +2:11-2:14 L1: FOR_ITER 12 (to L3) +2:11-2:14 TO_BOOL +2:11-2:14 POP_JUMP_IF_TRUE 3 (to L2) +2:11-2:14 NOT_TAKEN +2:11-2:14 JUMP_BACKWARD 11 (to L1) +2:11-2:14 L2: POP_ITER +2:11-2:14 LOAD_COMMON_CONSTANT 9 (True) +2:4-2:29 RETURN_VALUE +2:11-2:14 L3: END_FOR +2:11-2:14 POP_ITER +2:11-2:14 LOAD_COMMON_CONSTANT 10 (False) +2:4-2:29 RETURN_VALUE +2:11-2:14 L4: PUSH_NULL +2:14-2:29 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:14-2:29 MAKE_FUNCTION +2:26-2:28 LOAD_FAST_BORROW 0 (xs) +2:14-2:29 CALL 0 +2:11-2:29 CALL 1 +2:4-2:29 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:26-2:28 LOAD_FAST 0 (.0) +2:26-2:28 GET_ITER 0 +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:26-2:28 L2: FOR_ITER 7 (to L3) +2:21-2:22 STORE_FAST_LOAD_FAST 17 (x, x) +2:15-2:16 YIELD_VALUE 0 +2:15-2:16 RESUME 9 +2:15-2:16 POP_TOP +2:15-2:16 JUMP_BACKWARD 9 (to L2) +2:26-2:28 L3: END_FOR +2:26-2:28 POP_ITER +2:26-2:28 LOAD_COMMON_CONSTANT 7 (None) +2:26-2:28 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__builtin_tuple_list_set_genexpr_calls.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__builtin_tuple_list_set_genexpr_calls.snap new file mode 100644 index 00000000000..a5e81ffaf1d --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__builtin_tuple_list_set_genexpr_calls.snap @@ -0,0 +1,182 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef tuple_f(xs):\n return tuple(x for x in xs)\n\ndef list_f(xs):\n return list(x for x in xs)\n\ndef set_f(xs):\n return set(x for x in xs)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:31 LOAD_CONST 0 (", line 1>) +1:0-2:31 MAKE_FUNCTION +1:0-2:31 STORE_NAME 0 (tuple_f) + +4:0-5:30 LOAD_CONST 1 (", line 4>) +4:0-5:30 MAKE_FUNCTION +4:0-5:30 STORE_NAME 1 (list_f) + +7:0-8:29 LOAD_CONST 2 (", line 7>) +7:0-8:29 MAKE_FUNCTION +7:0-8:29 STORE_NAME 2 (set_f) +7:0-8:29 LOAD_COMMON_CONSTANT 7 (None) +7:0-8:29 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:16 LOAD_GLOBAL 0 (tuple) +2:11-2:16 COPY 1 +2:11-2:16 LOAD_COMMON_CONSTANT 2 (tuple) +2:11-2:16 IS_OP 0 (is) +2:11-2:16 POP_JUMP_IF_FALSE 20 (to L3) +2:11-2:16 NOT_TAKEN +2:11-2:16 POP_TOP +2:11-2:16 BUILD_LIST 0 +2:16-2:31 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:16-2:31 MAKE_FUNCTION +2:28-2:30 LOAD_FAST_BORROW 0 (xs) +2:16-2:31 CALL 0 +2:11-2:16 PUSH_NULL +2:11-2:16 L1: FOR_ITER 3 (to L2) +2:11-2:16 LIST_APPEND 3 +2:11-2:16 JUMP_BACKWARD 5 (to L1) +2:11-2:16 L2: END_FOR +2:11-2:16 POP_ITER +2:11-2:16 CALL_INTRINSIC_1 6 (INTRINSIC_LIST_TO_TUPLE) +2:4-2:31 RETURN_VALUE +2:11-2:16 L3: PUSH_NULL +2:16-2:31 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:16-2:31 MAKE_FUNCTION +2:28-2:30 LOAD_FAST_BORROW 0 (xs) +2:16-2:31 CALL 0 +2:11-2:31 CALL 1 +2:4-2:31 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:28-2:30 LOAD_FAST 0 (.0) +2:28-2:30 GET_ITER 0 +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:28-2:30 L2: FOR_ITER 7 (to L3) +2:23-2:24 STORE_FAST_LOAD_FAST 17 (x, x) +2:17-2:18 YIELD_VALUE 0 +2:17-2:18 RESUME 9 +2:17-2:18 POP_TOP +2:17-2:18 JUMP_BACKWARD 9 (to L2) +2:28-2:30 L3: END_FOR +2:28-2:30 POP_ITER +2:28-2:30 LOAD_COMMON_CONSTANT 7 (None) +2:28-2:30 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti + +Disassembly of ", line 4>: +4:0-4:0 RESUME 0 + +5:11-5:15 LOAD_GLOBAL 0 (list) +5:11-5:15 COPY 1 +5:11-5:15 LOAD_COMMON_CONSTANT 5 (list) +5:11-5:15 IS_OP 0 (is) +5:11-5:15 POP_JUMP_IF_FALSE 19 (to L3) +5:11-5:15 NOT_TAKEN +5:11-5:15 POP_TOP +5:11-5:15 BUILD_LIST 0 +5:15-5:30 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:15-5:30 MAKE_FUNCTION +5:27-5:29 LOAD_FAST_BORROW 0 (xs) +5:15-5:30 CALL 0 +5:11-5:15 PUSH_NULL +5:11-5:15 L1: FOR_ITER 3 (to L2) +5:11-5:15 LIST_APPEND 3 +5:11-5:15 JUMP_BACKWARD 5 (to L1) +5:11-5:15 L2: END_FOR +5:11-5:15 POP_ITER +5:4-5:30 RETURN_VALUE +5:11-5:15 L3: PUSH_NULL +5:15-5:30 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:15-5:30 MAKE_FUNCTION +5:27-5:29 LOAD_FAST_BORROW 0 (xs) +5:15-5:30 CALL 0 +5:11-5:30 CALL 1 +5:4-5:30 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 5>: + -- RESUME 4 + +5:27-5:29 LOAD_FAST 0 (.0) +5:27-5:29 GET_ITER 0 +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 +5:27-5:29 L2: FOR_ITER 7 (to L3) +5:22-5:23 STORE_FAST_LOAD_FAST 17 (x, x) +5:16-5:17 YIELD_VALUE 0 +5:16-5:17 RESUME 9 +5:16-5:17 POP_TOP +5:16-5:17 JUMP_BACKWARD 9 (to L2) +5:27-5:29 L3: END_FOR +5:27-5:29 POP_ITER +5:27-5:29 LOAD_COMMON_CONSTANT 7 (None) +5:27-5:29 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti + +Disassembly of ", line 7>: +7:0-7:0 RESUME 0 + +8:11-8:14 LOAD_GLOBAL 0 (set) +8:11-8:14 COPY 1 +8:11-8:14 LOAD_COMMON_CONSTANT 6 (set) +8:11-8:14 IS_OP 0 (is) +8:11-8:14 POP_JUMP_IF_FALSE 19 (to L3) +8:11-8:14 NOT_TAKEN +8:11-8:14 POP_TOP +8:11-8:14 BUILD_SET 0 +8:14-8:29 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 8>) +8:14-8:29 MAKE_FUNCTION +8:26-8:28 LOAD_FAST_BORROW 0 (xs) +8:14-8:29 CALL 0 +8:11-8:14 PUSH_NULL +8:11-8:14 L1: FOR_ITER 3 (to L2) +8:11-8:14 SET_ADD 3 +8:11-8:14 JUMP_BACKWARD 5 (to L1) +8:11-8:14 L2: END_FOR +8:11-8:14 POP_ITER +8:4-8:29 RETURN_VALUE +8:11-8:14 L3: PUSH_NULL +8:14-8:29 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 8>) +8:14-8:29 MAKE_FUNCTION +8:26-8:28 LOAD_FAST_BORROW 0 (xs) +8:14-8:29 CALL 0 +8:11-8:29 CALL 1 +8:4-8:29 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 8>: + -- RESUME 4 + +8:26-8:28 LOAD_FAST 0 (.0) +8:26-8:28 GET_ITER 0 +8:?-8:? RETURN_GENERATOR +8:?-8:? POP_TOP +8:0-8:0 L1: RESUME 0 +8:26-8:28 L2: FOR_ITER 7 (to L3) +8:21-8:22 STORE_FAST_LOAD_FAST 17 (x, x) +8:15-8:16 YIELD_VALUE 0 +8:15-8:16 RESUME 9 +8:15-8:16 POP_TOP +8:15-8:16 JUMP_BACKWARD 9 (to L2) +8:26-8:28 L3: END_FOR +8:26-8:28 POP_ITER +8:26-8:28 LOAD_COMMON_CONSTANT 7 (None) +8:26-8:28 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__class_deferred_annotations_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__class_deferred_annotations_location.snap new file mode 100644 index 00000000000..c9d12f9fe74 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__class_deferred_annotations_location.snap @@ -0,0 +1,65 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\n\nclass C:\n \"doc\"\n x: int\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-3:10 LOAD_BUILD_CLASS +1:0-3:10 PUSH_NULL +1:0-3:10 LOAD_CONST 0 (", line 1>) +1:0-3:10 MAKE_FUNCTION +1:0-3:10 LOAD_CONST 1 ('C') +1:0-3:10 CALL 2 +1:0-3:10 STORE_NAME 0 (C) +1:0-3:10 LOAD_COMMON_CONSTANT 7 (None) +1:0-3:10 RETURN_VALUE + +Disassembly of ", line 1>: + -- MAKE_CELL 0 (__classdict__) + +1:0-1:0 RESUME 0 +1:0-1:0 LOAD_NAME 0 (__name__) +1:0-1:0 STORE_NAME 1 (__module__) +1:0-1:0 LOAD_CONST 0 ('C') +1:0-1:0 STORE_NAME 2 (__qualname__) +1:0-1:0 LOAD_SMALL_INT 1 +1:0-1:0 STORE_NAME 3 (__firstlineno__) +1:0-1:0 LOAD_LOCALS +1:0-1:0 STORE_DEREF 0 (__classdict__) + +2:4-2:9 LOAD_CONST 1 ('doc') +2:4-2:9 STORE_NAME 4 (__doc__) + +1:0-1:0 LOAD_FAST_BORROW 0 (__classdict__) +1:0-1:0 BUILD_TUPLE 1 +1:0-1:0 LOAD_CONST 2 (", line 1>) +1:0-1:0 MAKE_FUNCTION +1:0-1:0 SET_FUNCTION_ATTRIBUTE 8 (closure) +1:0-1:0 STORE_NAME 5 (__annotate_func__) +1:0-1:0 LOAD_CONST 3 (()) +1:0-1:0 STORE_NAME 6 (__static_attributes__) +1:0-1:0 LOAD_FAST_BORROW 0 (__classdict__) +1:0-1:0 STORE_NAME 7 (__classdictcell__) +1:0-1:0 LOAD_COMMON_CONSTANT 7 (None) +1:0-1:0 RETURN_VALUE + +Disassembly of ", line 1>: + -- COPY_FREE_VARS 1 + +1:0-1:0 RESUME 0 +1:0-1:0 LOAD_FAST_BORROW 0 (format) +1:0-1:0 LOAD_SMALL_INT 2 +1:0-1:0 COMPARE_OP 132 (>) +1:0-1:0 POP_JUMP_IF_FALSE 3 (to L1) +1:0-1:0 NOT_TAKEN +1:0-1:0 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +1:0-1:0 RAISE_VARARGS 1 +1:0-1:0 L1: BUILD_MAP 0 + +3:7-3:10 LOAD_DEREF 1 (__classdict__) +3:7-3:10 LOAD_FROM_DICT_OR_GLOBALS 0 (int) +3:4-3:10 COPY 2 +3:4-3:10 LOAD_CONST 1 ('x') + +1:0-1:0 STORE_SUBSCR +1:0-1:0 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__comprehension_collection_depth.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__comprehension_collection_depth.snap new file mode 100644 index 00000000000..5db02a260b7 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__comprehension_collection_depth.snap @@ -0,0 +1,110 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(xs, ys):\n return [x for x in xs for y in ys]\n\nasync def g(xs, ys):\n return [x async for x in xs for y in ys]\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:38 LOAD_CONST 0 (", line 1>) +1:0-2:38 MAKE_FUNCTION +1:0-2:38 STORE_NAME 0 (f) + +4:0-5:44 LOAD_CONST 1 (", line 4>) +4:0-5:44 MAKE_FUNCTION +4:0-5:44 STORE_NAME 1 (g) +4:0-5:44 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:44 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:23-2:25 LOAD_FAST 0 (xs) +2:11-2:38 LOAD_FAST_AND_CLEAR 2 (x) +2:11-2:38 LOAD_FAST_AND_CLEAR 3 (y) +2:11-2:38 SWAP 3 +2:11-2:38 L1: BUILD_LIST 0 +2:11-2:38 SWAP 2 +2:23-2:25 GET_ITER 0 +2:23-2:25 L2: FOR_ITER 13 (to L5) +2:18-2:19 STORE_FAST_LOAD_FAST 33 (x, ys) +2:35-2:37 GET_ITER 0 +2:35-2:37 L3: FOR_ITER 4 (to L4) +2:30-2:31 STORE_FAST_LOAD_FAST 50 (y, x) +2:12-2:13 LIST_APPEND 5 +2:12-2:13 JUMP_BACKWARD 6 (to L3) +2:35-2:37 L4: END_FOR +2:35-2:37 POP_ITER +2:12-2:13 JUMP_BACKWARD 15 (to L2) +2:23-2:25 L5: END_FOR +2:23-2:25 POP_ITER +2:11-2:38 L6: SWAP 3 +2:11-2:38 STORE_FAST 3 (y) +2:11-2:38 STORE_FAST 2 (x) +2:4-2:38 RETURN_VALUE + + -- L7: SWAP 2 + -- POP_TOP + +2:11-2:38 SWAP 3 +2:11-2:38 STORE_FAST 3 (y) +2:11-2:38 STORE_FAST 2 (x) +2:11-2:38 RERAISE 0 +ExceptionTable: + L1 to L6 -> L7 [3] + +Disassembly of ", line 4>: +4:?-4:? RETURN_GENERATOR +4:?-4:? POP_TOP +4:0-4:0 L1: RESUME 0 + +5:29-5:31 LOAD_FAST_BORROW 0 (xs) +5:11-5:44 LOAD_FAST_AND_CLEAR 2 (x) +5:11-5:44 LOAD_FAST_AND_CLEAR 3 (y) +5:11-5:44 SWAP 3 +5:11-5:44 L2: BUILD_LIST 0 +5:11-5:44 SWAP 2 +5:29-5:31 GET_AITER +5:11-5:44 L3: GET_ANEXT +5:11-5:44 PUSH_NULL +5:11-5:44 LOAD_COMMON_CONSTANT 7 (None) +5:11-5:44 L4: SEND 4 (to L7) +5:11-5:44 L5: YIELD_VALUE 1 +5:11-5:44 L6: RESUME 3 +5:11-5:44 JUMP_BACKWARD_NO_INTERRUPT 6 (to L4) +5:11-5:44 L7: END_SEND +5:24-5:25 L8: STORE_FAST_LOAD_FAST 33 (x, ys) +5:41-5:43 GET_ITER 0 +5:41-5:43 L9: FOR_ITER 4 (to L10) +5:36-5:37 STORE_FAST_LOAD_FAST 50 (y, x) +5:12-5:13 LIST_APPEND 4 +5:12-5:13 JUMP_BACKWARD 6 (to L9) +5:41-5:43 L10: END_FOR +5:41-5:43 POP_ITER +5:12-5:13 JUMP_BACKWARD 23 (to L3) +5:11-5:44 L11: CLEANUP_THROW +5:11-5:44 L12: JUMP_BACKWARD_NO_INTERRUPT 16 (to L7) +5:11-5:44 L13: END_ASYNC_FOR 17 (from L7) +5:11-5:44 L14: SWAP 3 +5:11-5:44 STORE_FAST 3 (y) +5:11-5:44 STORE_FAST 2 (x) +5:4-5:44 RETURN_VALUE + + -- L15: SWAP 2 + -- POP_TOP + +5:11-5:44 SWAP 3 +5:11-5:44 STORE_FAST 3 (y) +5:11-5:44 STORE_FAST 2 (x) +5:11-5:44 RERAISE 0 + + -- L16: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L16 [0] lasti + L2 to L3 -> L15 [3] + L3 to L5 -> L13 [4] + L5 to L6 -> L11 [7] + L6 to L8 -> L13 [4] + L8 to L11 -> L15 [3] + L11 to L12 -> L13 [4] + L13 to L14 -> L15 [3] + L14 to L16 -> L16 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__comprehension_list_iterable_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__comprehension_list_iterable_location.snap new file mode 100644 index 00000000000..c7bca48e842 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__comprehension_list_iterable_location.snap @@ -0,0 +1,83 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nasync def f(i):\n return i\n\nasync def run_list():\n return [await c for c in [f(1), f(41)]]\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:12 LOAD_CONST 0 (", line 1>) +1:0-2:12 MAKE_FUNCTION +1:0-2:12 STORE_NAME 0 (f) + +4:0-5:43 LOAD_CONST 1 (", line 4>) +4:0-5:43 MAKE_FUNCTION +4:0-5:43 STORE_NAME 1 (run_list) +4:0-5:43 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:43 RETURN_VALUE + +Disassembly of ", line 1>: +1:?-1:? RETURN_GENERATOR +1:?-1:? POP_TOP +1:0-1:0 L1: RESUME 0 + +2:11-2:12 LOAD_FAST_BORROW 0 (i) +2:4-2:12 RETURN_VALUE + + -- L2: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L2 [0] lasti + +Disassembly of ", line 4>: +4:?-4:? RETURN_GENERATOR +4:?-4:? POP_TOP +4:0-4:0 L1: RESUME 0 + +5:30-5:31 LOAD_GLOBAL 1 (f + NULL) +5:32-5:33 LOAD_SMALL_INT 1 +5:30-5:34 CALL 1 +5:36-5:37 LOAD_GLOBAL 1 (f + NULL) +5:38-5:40 LOAD_SMALL_INT 41 +5:36-5:41 CALL 1 +5:29-5:42 BUILD_LIST 2 +5:11-5:43 LOAD_FAST_AND_CLEAR 0 (c) +5:11-5:43 SWAP 2 +5:11-5:43 L2: BUILD_LIST 0 +5:11-5:43 SWAP 2 +5:29-5:42 GET_ITER 0 +5:29-5:42 L3: FOR_ITER 14 (to L8) +5:24-5:25 STORE_FAST_LOAD_FAST 0 (c, c) +5:12-5:19 GET_AWAITABLE 0 +5:12-5:19 PUSH_NULL +5:12-5:19 LOAD_COMMON_CONSTANT 7 (None) +5:12-5:19 L4: SEND 4 (to L7) +5:12-5:19 L5: YIELD_VALUE 1 +5:12-5:19 L6: RESUME 3 +5:12-5:19 JUMP_BACKWARD_NO_INTERRUPT 6 (to L4) +5:12-5:19 L7: END_SEND +5:12-5:19 LIST_APPEND 3 +5:12-5:19 JUMP_BACKWARD 16 (to L3) +5:29-5:42 L8: END_FOR +5:29-5:42 POP_ITER +5:11-5:43 L9: SWAP 2 +5:11-5:43 STORE_FAST 0 (c) +5:4-5:43 RETURN_VALUE +5:12-5:19 L10: CLEANUP_THROW +5:12-5:19 L11: JUMP_BACKWARD_NO_INTERRUPT 11 (to L7) + + -- L12: SWAP 2 + -- POP_TOP + +5:11-5:43 SWAP 2 +5:11-5:43 STORE_FAST 0 (c) +5:11-5:43 RERAISE 0 + + -- L13: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L13 [0] lasti + L2 to L5 -> L12 [2] + L5 to L6 -> L10 [7] + L6 to L9 -> L12 [2] + L9 to L10 -> L13 [0] lasti + L10 to L11 -> L12 [2] + L12 to L13 -> L13 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__const_no_op.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__const_no_op.snap index dc97f6b79c1..5713fb761d2 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__const_no_op.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__const_no_op.snap @@ -5,7 +5,7 @@ expression: "dis(r#\"\nx = not True\n\"#)" --- 0 RESUME 0 - 1 LOAD_CONST 2 (False) + 1 LOAD_COMMON_CONSTANT 10 (False) STORE_NAME 0 (x) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__constant_true_if_pass_keeps_line_anchor_nop.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__constant_true_if_pass_keeps_line_anchor_nop.snap index 3de37ce2009..5cbdc2104d3 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__constant_true_if_pass_keeps_line_anchor_nop.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__constant_true_if_pass_keeps_line_anchor_nop.snap @@ -7,5 +7,5 @@ expression: "dis(r#\"\nif 1:\n pass\n\"#)" 1 NOP - 2 LOAD_CONST 1 (None) + 2 LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__decorated_definition_locations.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__decorated_definition_locations.snap new file mode 100644 index 00000000000..91c9b7c85df --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__decorated_definition_locations.snap @@ -0,0 +1,164 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef dec(f): return f\n\nclass C:\n @dec\n def f(self):\n yield\n\n@dec\nclass D:\n pass\n\nclass E:\n @dec\n def g(self, flags: int, /) -> memoryview:\n raise NotImplementedError\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-1:20 LOAD_CONST 0 (", line 1>) +1:0-1:20 MAKE_FUNCTION +1:0-1:20 STORE_NAME 0 (dec) + +3:0-6:13 LOAD_BUILD_CLASS +3:0-6:13 PUSH_NULL +3:0-6:13 LOAD_CONST 1 (", line 3>) +3:0-6:13 MAKE_FUNCTION +3:0-6:13 LOAD_CONST 2 ('C') +3:0-6:13 CALL 2 +3:0-6:13 STORE_NAME 1 (C) + +8:1-8:4 LOAD_NAME 0 (dec) + +9:0-10:8 LOAD_BUILD_CLASS +9:0-10:8 PUSH_NULL +9:0-10:8 LOAD_CONST 3 (", line 8>) +9:0-10:8 MAKE_FUNCTION +9:0-10:8 LOAD_CONST 4 ('D') +9:0-10:8 CALL 2 + +8:1-8:4 CALL 0 + +9:0-10:8 STORE_NAME 2 (D) + +12:0-15:33 LOAD_BUILD_CLASS +12:0-15:33 PUSH_NULL +12:0-15:33 LOAD_CONST 5 (", line 12>) +12:0-15:33 MAKE_FUNCTION +12:0-15:33 LOAD_CONST 6 ('E') +12:0-15:33 CALL 2 +12:0-15:33 STORE_NAME 3 (E) +12:0-15:33 LOAD_COMMON_CONSTANT 7 (None) +12:0-15:33 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 +1:19-1:20 LOAD_FAST_BORROW 0 (f) +1:12-1:20 RETURN_VALUE + +Disassembly of ", line 3>: + -- MAKE_CELL 0 (__classdict__) + +3:0-3:0 RESUME 0 +3:0-3:0 LOAD_NAME 0 (__name__) +3:0-3:0 STORE_NAME 1 (__module__) +3:0-3:0 LOAD_CONST 0 ('C') +3:0-3:0 STORE_NAME 2 (__qualname__) +3:0-3:0 LOAD_SMALL_INT 3 +3:0-3:0 STORE_NAME 3 (__firstlineno__) +3:0-3:0 LOAD_LOCALS +3:0-3:0 STORE_DEREF 0 (__classdict__) + +4:5-4:8 LOAD_NAME 4 (dec) + +5:4-6:13 LOAD_CONST 1 (", line 4>) +5:4-6:13 MAKE_FUNCTION + +4:5-4:8 CALL 0 + +5:4-6:13 STORE_NAME 5 (f) +5:4-6:13 LOAD_CONST 2 (()) +5:4-6:13 STORE_NAME 6 (__static_attributes__) +5:4-6:13 LOAD_FAST_BORROW 0 (__classdict__) +5:4-6:13 STORE_NAME 7 (__classdictcell__) +5:4-6:13 LOAD_COMMON_CONSTANT 7 (None) +5:4-6:13 RETURN_VALUE + +Disassembly of ", line 4>: +4:?-4:? RETURN_GENERATOR +4:?-4:? POP_TOP +4:0-4:0 L1: RESUME 0 + +6:8-6:13 LOAD_COMMON_CONSTANT 7 (None) +6:8-6:13 YIELD_VALUE 0 +6:8-6:13 RESUME 9 +6:8-6:13 POP_TOP +6:8-6:13 LOAD_COMMON_CONSTANT 7 (None) +6:8-6:13 RETURN_VALUE + + -- L2: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L2 [0] lasti + +Disassembly of ", line 8>: +8:0-8:0 RESUME 0 +8:0-8:0 LOAD_NAME 0 (__name__) +8:0-8:0 STORE_NAME 1 (__module__) +8:0-8:0 LOAD_CONST 0 ('D') +8:0-8:0 STORE_NAME 2 (__qualname__) +8:0-8:0 LOAD_SMALL_INT 8 +8:0-8:0 STORE_NAME 3 (__firstlineno__) + +10:4-10:8 LOAD_CONST 1 (()) +10:4-10:8 STORE_NAME 4 (__static_attributes__) +10:4-10:8 LOAD_COMMON_CONSTANT 7 (None) +10:4-10:8 RETURN_VALUE + +Disassembly of ", line 12>: + -- MAKE_CELL 0 (__classdict__) + +12:0-12:0 RESUME 0 +12:0-12:0 LOAD_NAME 0 (__name__) +12:0-12:0 STORE_NAME 1 (__module__) +12:0-12:0 LOAD_CONST 0 ('E') +12:0-12:0 STORE_NAME 2 (__qualname__) +12:0-12:0 LOAD_SMALL_INT 12 +12:0-12:0 STORE_NAME 3 (__firstlineno__) +12:0-12:0 LOAD_LOCALS +12:0-12:0 STORE_DEREF 0 (__classdict__) + +13:5-13:8 LOAD_NAME 4 (dec) + +14:4-15:33 LOAD_FAST_BORROW 0 (__classdict__) +14:4-15:33 BUILD_TUPLE 1 +14:4-15:33 LOAD_CONST 1 (", line 14>) +14:4-15:33 MAKE_FUNCTION +14:4-15:33 SET_FUNCTION_ATTRIBUTE 8 (closure) +14:4-15:33 LOAD_CONST 2 (", line 13>) +14:4-15:33 MAKE_FUNCTION +14:4-15:33 SET_FUNCTION_ATTRIBUTE 16 (annotate) + +13:5-13:8 CALL 0 + +14:4-15:33 STORE_NAME 5 (g) +14:4-15:33 LOAD_CONST 3 (()) +14:4-15:33 STORE_NAME 6 (__static_attributes__) +14:4-15:33 LOAD_FAST_BORROW 0 (__classdict__) +14:4-15:33 STORE_NAME 7 (__classdictcell__) +14:4-15:33 LOAD_COMMON_CONSTANT 7 (None) +14:4-15:33 RETURN_VALUE + +Disassembly of ", line 14>: + -- COPY_FREE_VARS 1 + +14:0-14:0 RESUME 0 +14:4-15:33 LOAD_FAST_BORROW 0 (format) +14:4-15:33 LOAD_SMALL_INT 2 +14:4-15:33 COMPARE_OP 132 (>) +14:4-15:33 POP_JUMP_IF_FALSE 3 (to L1) +14:4-15:33 NOT_TAKEN +14:4-15:33 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +14:4-15:33 RAISE_VARARGS 1 +14:4-15:33 L1: LOAD_CONST 1 ('flags') +14:23-14:26 LOAD_DEREF 1 (__classdict__) +14:23-14:26 LOAD_FROM_DICT_OR_GLOBALS 0 (int) +14:4-15:33 LOAD_CONST 2 ('return') +14:34-14:44 LOAD_DEREF 1 (__classdict__) +14:34-14:44 LOAD_FROM_DICT_OR_GLOBALS 1 (memoryview) +14:4-15:33 BUILD_MAP 2 +14:4-15:33 RETURN_VALUE + +Disassembly of ", line 13>: +13:0-13:0 RESUME 0 + +15:14-15:33 LOAD_GLOBAL 0 (NotImplementedError) +15:8-15:33 RAISE_VARARGS 1 diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__empty_module_implicit_return_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__empty_module_implicit_return_location.snap new file mode 100644 index 00000000000..75795d00b10 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__empty_module_implicit_return_location.snap @@ -0,0 +1,7 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(\"\", true)" +--- +0:0-1:0 RESUME 0 +0:0-1:0 LOAD_COMMON_CONSTANT 7 (None) +0:0-1:0 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__fstring_format_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__fstring_format_location.snap new file mode 100644 index 00000000000..904cde2d209 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__fstring_format_location.snap @@ -0,0 +1,32 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef simple(self):\n return f'{self.value}'\n\ndef spec(x):\n return f'{x!r:>3}'\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:26 LOAD_CONST 0 (", line 1>) +1:0-2:26 MAKE_FUNCTION +1:0-2:26 STORE_NAME 0 (simple) + +4:0-5:22 LOAD_CONST 1 (", line 4>) +4:0-5:22 MAKE_FUNCTION +4:0-5:22 STORE_NAME 1 (spec) +4:0-5:22 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:22 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:14-2:18 LOAD_FAST_BORROW 0 (self) +2:14-2:24 LOAD_ATTR 0 (value) +2:13-2:25 FORMAT_SIMPLE +2:4-2:26 RETURN_VALUE + +Disassembly of ", line 4>: +4:0-4:0 RESUME 0 + +5:14-5:15 LOAD_FAST_BORROW 0 (x) +5:13-5:21 CONVERT_VALUE 2 (repr) +5:18-5:20 LOAD_CONST 0 ('>3') +5:13-5:21 FORMAT_WITH_SPEC +5:4-5:22 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__future_annotation_string_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__future_annotation_string_location.snap new file mode 100644 index 00000000000..82a554f86af --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__future_annotation_string_location.snap @@ -0,0 +1,41 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nfrom __future__ import annotations\nclass Bar:\n foo: Foo\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-1:34 LOAD_SMALL_INT 0 +1:0-1:34 LOAD_CONST 1 (('annotations',)) +1:0-1:34 IMPORT_NAME 0 (__future__) +1:0-1:34 IMPORT_FROM 1 (annotations) +1:0-1:34 STORE_NAME 1 (annotations) +1:0-1:34 POP_TOP + +2:0-3:12 LOAD_BUILD_CLASS +2:0-3:12 PUSH_NULL +2:0-3:12 LOAD_CONST 2 (", line 2>) +2:0-3:12 MAKE_FUNCTION +2:0-3:12 LOAD_CONST 3 ('Bar') +2:0-3:12 CALL 2 +2:0-3:12 STORE_NAME 2 (Bar) +2:0-3:12 LOAD_COMMON_CONSTANT 7 (None) +2:0-3:12 RETURN_VALUE + +Disassembly of ", line 2>: +2:0-2:0 RESUME 0 +2:0-2:0 LOAD_NAME 0 (__name__) +2:0-2:0 STORE_NAME 1 (__module__) +2:0-2:0 LOAD_CONST 0 ('Bar') +2:0-2:0 STORE_NAME 2 (__qualname__) +2:0-2:0 LOAD_SMALL_INT 2 +2:0-2:0 STORE_NAME 3 (__firstlineno__) +2:0-2:0 SETUP_ANNOTATIONS + +3:9-3:12 LOAD_CONST 1 ('Foo') +3:4-3:12 LOAD_NAME 4 (__annotations__) +3:4-3:12 LOAD_CONST 2 ('foo') +3:4-3:12 STORE_SUBSCR +3:4-3:12 LOAD_CONST 3 (()) +3:4-3:12 STORE_NAME 5 (__static_attributes__) +3:4-3:12 LOAD_COMMON_CONSTANT 7 (None) +3:4-3:12 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_class_type_params_store_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_class_type_params_store_location.snap new file mode 100644 index 00000000000..f0d8113a6a1 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_class_type_params_store_location.snap @@ -0,0 +1,64 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef outer():\n class X[T]: ...\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-2:19 LOAD_CONST 0 (", line 1>) +1:0-2:19 MAKE_FUNCTION +1:0-2:19 STORE_NAME 0 (outer) +1:0-2:19 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:19 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:4-2:19 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:4-2:19 MAKE_FUNCTION +2:4-2:19 PUSH_NULL +2:4-2:19 CALL 0 +2:4-2:19 STORE_FAST 0 (X) +2:4-2:19 LOAD_COMMON_CONSTANT 7 (None) +2:4-2:19 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- MAKE_CELL 2 (.type_params) + +2:0-2:0 RESUME 0 +2:12-2:13 LOAD_CONST 0 ('T') +2:12-2:13 CALL_INTRINSIC_1 7 (INTRINSIC_TYPEVAR) +2:12-2:13 COPY 1 +2:12-2:13 STORE_FAST 0 (T) +2:12-2:13 BUILD_TUPLE 1 +2:4-2:19 STORE_DEREF 2 (.type_params) +2:4-2:19 LOAD_BUILD_CLASS +2:4-2:19 PUSH_NULL +2:4-2:19 LOAD_FAST_BORROW 2 (.type_params) +2:4-2:19 BUILD_TUPLE 1 +2:4-2:19 LOAD_CONST 1 (", line 2>) +2:4-2:19 MAKE_FUNCTION +2:4-2:19 SET_FUNCTION_ATTRIBUTE 8 (closure) +2:4-2:19 LOAD_CONST 2 ('X') +2:4-2:19 LOAD_DEREF 2 (.type_params) +2:4-2:19 CALL_INTRINSIC_1 10 (INTRINSIC_SUBSCRIPT_GENERIC) +2:4-2:19 STORE_FAST_LOAD_FAST 17 (.generic_base, .generic_base) +2:4-2:19 CALL 3 +2:4-2:19 RETURN_VALUE + +Disassembly of ", line 2>: + -- COPY_FREE_VARS 1 + +2:0-2:0 RESUME 0 +2:0-2:0 LOAD_NAME 0 (__name__) +2:0-2:0 STORE_NAME 1 (__module__) +2:0-2:0 LOAD_CONST 0 ('outer..X') +2:0-2:0 STORE_NAME 2 (__qualname__) +2:0-2:0 LOAD_SMALL_INT 2 +2:0-2:0 STORE_NAME 3 (__firstlineno__) +2:0-2:0 LOAD_LOCALS +2:0-2:0 LOAD_FROM_DICT_OR_DEREF 0 (.type_params) +2:0-2:0 STORE_NAME 4 (__type_params__) +2:16-2:19 LOAD_CONST 1 (()) +2:16-2:19 STORE_NAME 5 (__static_attributes__) +2:16-2:19 LOAD_COMMON_CONSTANT 7 (None) +2:16-2:19 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_function_annotation_scope_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_function_annotation_scope_location.snap new file mode 100644 index 00000000000..0b9fa6890ee --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_function_annotation_scope_location.snap @@ -0,0 +1,48 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f[T](x: int): ...\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-1:21 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 1>) +1:0-1:21 MAKE_FUNCTION +1:0-1:21 PUSH_NULL +1:0-1:21 CALL 0 +1:0-1:21 STORE_NAME 0 (f) +1:0-1:21 LOAD_COMMON_CONSTANT 7 (None) +1:0-1:21 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 1>: +1:0-1:0 RESUME 0 +1:6-1:7 LOAD_CONST 0 ('T') +1:6-1:7 CALL_INTRINSIC_1 7 (INTRINSIC_TYPEVAR) +1:6-1:7 COPY 1 +1:6-1:7 STORE_FAST 1 (T) +1:6-1:7 BUILD_TUPLE 1 +1:0-1:21 LOAD_CONST 1 (", line 1>) +1:0-1:21 MAKE_FUNCTION +1:0-1:21 LOAD_CONST 2 (", line 1>) +1:0-1:21 MAKE_FUNCTION +1:0-1:21 SET_FUNCTION_ATTRIBUTE 16 (annotate) +1:0-1:21 SWAP 2 +1:0-1:21 CALL_INTRINSIC_2 4 (INTRINSIC_SET_FUNCTION_TYPE_PARAMS) +1:0-1:21 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 +1:0-1:21 LOAD_FAST_BORROW 0 (format) +1:0-1:21 LOAD_SMALL_INT 2 +1:0-1:21 COMPARE_OP 132 (>) +1:0-1:21 POP_JUMP_IF_FALSE 3 (to L1) +1:0-1:21 NOT_TAKEN +1:0-1:21 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +1:0-1:21 RAISE_VARARGS 1 +1:0-1:21 L1: LOAD_CONST 1 ('x') +1:12-1:15 LOAD_GLOBAL 0 (int) +1:0-1:21 BUILD_MAP 1 +1:0-1:21 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 +1:18-1:21 LOAD_COMMON_CONSTANT 7 (None) +1:18-1:21 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_typealias_wrapper_return_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_typealias_wrapper_return_location.snap new file mode 100644 index 00000000000..dd85d9a57e1 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__generic_typealias_wrapper_return_location.snap @@ -0,0 +1,48 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ntype A[T] = T\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-1:13 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 1>) +1:0-1:13 MAKE_FUNCTION +1:0-1:13 PUSH_NULL +1:0-1:13 CALL 0 +1:0-1:13 STORE_NAME 0 (A) +1:0-1:13 LOAD_COMMON_CONSTANT 7 (None) +1:0-1:13 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 1>: + -- MAKE_CELL 0 (T) + +1:0-1:0 RESUME 0 +1:0-1:13 LOAD_CONST 0 ('A') +1:7-1:8 LOAD_CONST 1 ('T') +1:7-1:8 CALL_INTRINSIC_1 7 (INTRINSIC_TYPEVAR) +1:7-1:8 COPY 1 +1:7-1:8 STORE_DEREF 0 (T) +1:7-1:8 BUILD_TUPLE 1 +1:0-1:13 LOAD_CONST 2 ((1,)) +1:0-1:13 LOAD_FAST_BORROW 0 (T) +1:0-1:13 BUILD_TUPLE 1 +1:0-1:13 LOAD_CONST 3 (", line 1>) +1:0-1:13 MAKE_FUNCTION +1:0-1:13 SET_FUNCTION_ATTRIBUTE 8 (closure) +1:0-1:13 SET_FUNCTION_ATTRIBUTE 1 (defaults) +1:0-1:13 BUILD_TUPLE 3 +1:0-1:13 CALL_INTRINSIC_1 11 (INTRINSIC_TYPEALIAS) +1:0-1:13 RETURN_VALUE + +Disassembly of ", line 1>: + -- COPY_FREE_VARS 1 + +1:0-1:0 RESUME 0 +1:0-1:13 LOAD_FAST_BORROW 0 (.format) +1:0-1:13 LOAD_SMALL_INT 2 +1:0-1:13 COMPARE_OP 132 (>) +1:0-1:13 POP_JUMP_IF_FALSE 3 (to L1) +1:0-1:13 NOT_TAKEN +1:0-1:13 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +1:0-1:13 RAISE_VARARGS 1 +1:12-1:13 L1: LOAD_DEREF 1 (T) +1:0-1:13 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_closure_and_call_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_closure_and_call_location.snap new file mode 100644 index 00000000000..266fe98e0be --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_closure_and_call_location.snap @@ -0,0 +1,48 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(parameters):\n return ((p, type(p)) for p in parameters)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:45 LOAD_CONST 0 (", line 1>) +1:0-2:45 MAKE_FUNCTION +1:0-2:45 STORE_NAME 0 (f) +1:0-2:45 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:45 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:45 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:11-2:45 MAKE_FUNCTION +2:34-2:44 LOAD_FAST_BORROW 0 (parameters) +2:11-2:45 CALL 0 +2:4-2:45 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:34-2:44 LOAD_FAST 0 (.0) +2:34-2:44 GET_ITER 0 +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:34-2:44 L2: FOR_ITER 18 (to L3) +2:29-2:30 STORE_FAST_LOAD_FAST 17 (p, p) +2:16-2:20 LOAD_GLOBAL 1 (type + NULL) +2:21-2:22 LOAD_FAST_BORROW 1 (p) +2:16-2:23 CALL 1 +2:12-2:24 BUILD_TUPLE 2 +2:12-2:24 YIELD_VALUE 0 +2:12-2:24 RESUME 9 +2:12-2:24 POP_TOP +2:12-2:24 JUMP_BACKWARD 20 (to L2) +2:34-2:44 L3: END_FOR +2:34-2:44 POP_ITER +2:34-2:44 LOAD_COMMON_CONSTANT 7 (None) +2:34-2:44 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_filter_cleanup_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_filter_cleanup_location.snap new file mode 100644 index 00000000000..5d5a5b287fc --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_filter_cleanup_location.snap @@ -0,0 +1,101 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef simple(names):\n return (x for x in names if not _ishidden(x))\n\ndef boolop(fields):\n return (f for f in fields if f.init and not f.kw_only)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:49 LOAD_CONST 0 (", line 1>) +1:0-2:49 MAKE_FUNCTION +1:0-2:49 STORE_NAME 0 (simple) + +4:0-5:58 LOAD_CONST 1 (", line 4>) +4:0-5:58 MAKE_FUNCTION +4:0-5:58 STORE_NAME 1 (boolop) +4:0-5:58 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:58 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:49 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:11-2:49 MAKE_FUNCTION +2:23-2:28 LOAD_FAST_BORROW 0 (names) +2:11-2:49 CALL 0 +2:4-2:49 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:23-2:28 LOAD_FAST 0 (.0) +2:23-2:28 GET_ITER 0 +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:23-2:28 L2: FOR_ITER 27 (to L4) +2:18-2:19 STORE_FAST 1 (x) +2:36-2:45 LOAD_GLOBAL 1 (_ishidden + NULL) +2:46-2:47 LOAD_FAST_BORROW 1 (x) +2:36-2:48 CALL 1 +2:36-2:48 TO_BOOL +2:12-2:13 POP_JUMP_IF_FALSE 3 (to L3) +2:12-2:13 NOT_TAKEN +2:12-2:13 JUMP_BACKWARD 22 (to L2) +2:12-2:13 L3: LOAD_FAST_BORROW 1 (x) +2:12-2:13 YIELD_VALUE 0 +2:12-2:13 RESUME 9 +2:12-2:13 POP_TOP +2:12-2:13 JUMP_BACKWARD 29 (to L2) +2:23-2:28 L4: END_FOR +2:23-2:28 POP_ITER +2:23-2:28 LOAD_COMMON_CONSTANT 7 (None) +2:23-2:28 RETURN_VALUE + + -- L5: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L5 -> L5 [2] lasti + +Disassembly of ", line 4>: +4:0-4:0 RESUME 0 + +5:11-5:58 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:11-5:58 MAKE_FUNCTION +5:23-5:29 LOAD_FAST_BORROW 0 (fields) +5:11-5:58 CALL 0 +5:4-5:58 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 5>: + -- RESUME 4 + +5:23-5:29 LOAD_FAST 0 (.0) +5:23-5:29 GET_ITER 0 +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 +5:23-5:29 L2: FOR_ITER 47 (to L5) +5:18-5:19 STORE_FAST_LOAD_FAST 17 (f, f) +5:33-5:39 LOAD_ATTR 0 (init) +5:33-5:39 TO_BOOL +5:12-5:13 POP_JUMP_IF_TRUE 3 (to L3) +5:12-5:13 NOT_TAKEN +5:12-5:13 JUMP_BACKWARD 22 (to L2) +5:48-5:49 L3: LOAD_FAST_BORROW 1 (f) +5:48-5:57 LOAD_ATTR 2 (kw_only) +5:48-5:57 TO_BOOL +5:12-5:13 POP_JUMP_IF_FALSE 3 (to L4) +5:12-5:13 NOT_TAKEN +5:12-5:13 JUMP_BACKWARD 42 (to L2) +5:12-5:13 L4: LOAD_FAST_BORROW 1 (f) +5:12-5:13 YIELD_VALUE 0 +5:12-5:13 RESUME 9 +5:12-5:13 POP_TOP +5:12-5:13 JUMP_BACKWARD 49 (to L2) +5:23-5:29 L5: END_FOR +5:23-5:29 POP_ITER +5:23-5:29 LOAD_COMMON_CONSTANT 7 (None) +5:23-5:29 RETURN_VALUE + + -- L6: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L6 -> L6 [2] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_prefix.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_prefix.snap new file mode 100644 index 00000000000..aff0ded464d --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__genexpr_prefix.snap @@ -0,0 +1,103 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(xs):\n return (x for x in xs)\n\nasync def g(xs):\n return (x async for x in xs)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:26 LOAD_CONST 0 (", line 1>) +1:0-2:26 MAKE_FUNCTION +1:0-2:26 STORE_NAME 0 (f) + +4:0-5:32 LOAD_CONST 1 (", line 4>) +4:0-5:32 MAKE_FUNCTION +4:0-5:32 STORE_NAME 1 (g) +4:0-5:32 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:32 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:26 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:11-2:26 MAKE_FUNCTION +2:23-2:25 LOAD_FAST_BORROW 0 (xs) +2:11-2:26 CALL 0 +2:4-2:26 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:23-2:25 LOAD_FAST 0 (.0) +2:23-2:25 GET_ITER 0 +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:23-2:25 L2: FOR_ITER 7 (to L3) +2:18-2:19 STORE_FAST_LOAD_FAST 17 (x, x) +2:12-2:13 YIELD_VALUE 0 +2:12-2:13 RESUME 9 +2:12-2:13 POP_TOP +2:12-2:13 JUMP_BACKWARD 9 (to L2) +2:23-2:25 L3: END_FOR +2:23-2:25 POP_ITER +2:23-2:25 LOAD_COMMON_CONSTANT 7 (None) +2:23-2:25 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti + +Disassembly of ", line 4>: +4:?-4:? RETURN_GENERATOR +4:?-4:? POP_TOP +4:0-4:0 L1: RESUME 0 + +5:11-5:32 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:11-5:32 MAKE_FUNCTION +5:29-5:31 LOAD_FAST_BORROW 0 (xs) +5:11-5:32 CALL 0 +5:4-5:32 RETURN_VALUE + + -- L2: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L2 [0] lasti + +Disassembly of at 0xdeadbeef, file "", line 5>: + -- RESUME 4 + +5:29-5:31 LOAD_FAST_BORROW 0 (.0) +5:29-5:31 GET_AITER +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 +5:11-5:32 L2: GET_ANEXT +5:11-5:32 PUSH_NULL +5:11-5:32 LOAD_COMMON_CONSTANT 7 (None) +5:11-5:32 L3: SEND 4 (to L6) +5:11-5:32 L4: YIELD_VALUE 1 +5:11-5:32 L5: RESUME 3 +5:11-5:32 JUMP_BACKWARD_NO_INTERRUPT 6 (to L3) +5:11-5:32 L6: END_SEND +5:24-5:25 L7: STORE_FAST_LOAD_FAST 17 (x, x) +5:12-5:13 CALL_INTRINSIC_1 4 (INTRINSIC_ASYNC_GEN_WRAP) +5:12-5:13 YIELD_VALUE 0 +5:12-5:13 RESUME 9 +5:12-5:13 POP_TOP +5:12-5:13 JUMP_BACKWARD 18 (to L2) +5:11-5:32 L8: CLEANUP_THROW +5:11-5:32 L9: JUMP_BACKWARD_NO_INTERRUPT 11 (to L6) +5:11-5:32 L10: END_ASYNC_FOR 12 (from L6) +5:11-5:32 LOAD_COMMON_CONSTANT 7 (None) +5:11-5:32 RETURN_VALUE + + -- L11: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L11 [1] lasti + L2 to L4 -> L10 [1] + L4 to L5 -> L8 [4] + L5 to L7 -> L10 [1] + L7 to L8 -> L11 [1] lasti + L8 to L9 -> L10 [1] + L10 to L11 -> L11 [1] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ands.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ands.snap index 5c58a2b6b85..0f3b62b3cdb 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ands.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ands.snap @@ -5,5 +5,5 @@ expression: "dis(r#\"\nif True and False and False:\n pass\n\"#)" --- 0 RESUME 0 - 1 LOAD_CONST 1 (None) + 1 LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_mixed.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_mixed.snap index 6bef04ee143..7da2fc67637 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_mixed.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_mixed.snap @@ -5,5 +5,5 @@ expression: "dis(r#\"\nif (True and False) or (False and True):\n pass\n\"#)" --- 0 RESUME 0 - 1 LOAD_CONST 1 (None) + 1 LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ors.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ors.snap index 065d893732e..d89e0a8d01d 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ors.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__if_ors.snap @@ -7,5 +7,5 @@ expression: "dis(r#\"\nif True or False or False:\n pass\n\"#)" 1 NOP - 2 LOAD_CONST 1 (None) + 2 LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__implicit_call_genexpr_parenthesized_element_range.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__implicit_call_genexpr_parenthesized_element_range.snap new file mode 100644 index 00000000000..7d1cdd914c2 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__implicit_call_genexpr_parenthesized_element_range.snap @@ -0,0 +1,216 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef bytes_binop():\n return bytes((x ^ 0x5C) for x in range(256))\n\ndef dict_tuple(d):\n return dict((v, k) for (k, v) in d.items())\n\ndef plain_tuple_elt(xs):\n return list((x, y) for x, y in xs)\n\ndef explicit_gen(xs):\n return list(((x, y) for x, y in xs))\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:48 LOAD_CONST 0 (", line 1>) +1:0-2:48 MAKE_FUNCTION +1:0-2:48 STORE_NAME 0 (bytes_binop) + +4:0-5:47 LOAD_CONST 1 (", line 4>) +4:0-5:47 MAKE_FUNCTION +4:0-5:47 STORE_NAME 1 (dict_tuple) + +7:0-8:38 LOAD_CONST 2 (", line 7>) +7:0-8:38 MAKE_FUNCTION +7:0-8:38 STORE_NAME 2 (plain_tuple_elt) + +10:0-11:40 LOAD_CONST 3 (", line 10>) +10:0-11:40 MAKE_FUNCTION +10:0-11:40 STORE_NAME 3 (explicit_gen) +10:0-11:40 LOAD_COMMON_CONSTANT 7 (None) +10:0-11:40 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:16 LOAD_GLOBAL 1 (bytes + NULL) +2:16-2:48 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:16-2:48 MAKE_FUNCTION +2:37-2:42 LOAD_GLOBAL 3 (range + NULL) +2:43-2:46 LOAD_CONST 1 (256) +2:37-2:47 CALL 1 +2:16-2:48 CALL 0 +2:11-2:48 CALL 1 +2:4-2:48 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:37-2:47 LOAD_FAST 0 (.0) +2:37-2:47 GET_ITER 0 +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:37-2:47 L2: FOR_ITER 14 (to L3) +2:32-2:33 STORE_FAST_LOAD_FAST 17 (x, x) +2:22-2:26 LOAD_SMALL_INT 92 +2:18-2:26 BINARY_OP 12 (^) +2:18-2:26 YIELD_VALUE 0 +2:18-2:26 RESUME 9 +2:18-2:26 POP_TOP +2:18-2:26 JUMP_BACKWARD 16 (to L2) +2:37-2:47 L3: END_FOR +2:37-2:47 POP_ITER +2:37-2:47 LOAD_COMMON_CONSTANT 7 (None) +2:37-2:47 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti + +Disassembly of ", line 4>: +4:0-4:0 RESUME 0 + +5:11-5:15 LOAD_GLOBAL 1 (dict + NULL) +5:15-5:47 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:15-5:47 MAKE_FUNCTION +5:37-5:38 LOAD_FAST_BORROW 0 (d) +5:37-5:44 LOAD_ATTR 3 (items + NULL|self) +5:37-5:46 CALL 0 +5:15-5:47 CALL 0 +5:11-5:47 CALL 1 +5:4-5:47 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 5>: + -- RESUME 4 + +5:37-5:46 LOAD_FAST 0 (.0) +5:37-5:46 GET_ITER 0 +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 +5:37-5:46 L2: FOR_ITER 11 (to L3) +5:27-5:33 UNPACK_SEQUENCE 2 +5:28-5:29 STORE_FAST_STORE_FAST 18 (k, v) +5:17-5:18 LOAD_FAST_BORROW_LOAD_FAST_BORROW 33 (v, k) +5:16-5:22 BUILD_TUPLE 2 +5:16-5:22 YIELD_VALUE 0 +5:16-5:22 RESUME 9 +5:16-5:22 POP_TOP +5:16-5:22 JUMP_BACKWARD 13 (to L2) +5:37-5:46 L3: END_FOR +5:37-5:46 POP_ITER +5:37-5:46 LOAD_COMMON_CONSTANT 7 (None) +5:37-5:46 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti + +Disassembly of ", line 7>: +7:0-7:0 RESUME 0 + +8:11-8:15 LOAD_GLOBAL 0 (list) +8:11-8:15 COPY 1 +8:11-8:15 LOAD_COMMON_CONSTANT 5 (list) +8:11-8:15 IS_OP 0 (is) +8:11-8:15 POP_JUMP_IF_FALSE 19 (to L3) +8:11-8:15 NOT_TAKEN +8:11-8:15 POP_TOP +8:11-8:15 BUILD_LIST 0 +8:15-8:38 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 8>) +8:15-8:38 MAKE_FUNCTION +8:35-8:37 LOAD_FAST_BORROW 0 (xs) +8:15-8:38 CALL 0 +8:11-8:15 PUSH_NULL +8:11-8:15 L1: FOR_ITER 3 (to L2) +8:11-8:15 LIST_APPEND 3 +8:11-8:15 JUMP_BACKWARD 5 (to L1) +8:11-8:15 L2: END_FOR +8:11-8:15 POP_ITER +8:4-8:38 RETURN_VALUE +8:11-8:15 L3: PUSH_NULL +8:15-8:38 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 8>) +8:15-8:38 MAKE_FUNCTION +8:35-8:37 LOAD_FAST_BORROW 0 (xs) +8:15-8:38 CALL 0 +8:11-8:38 CALL 1 +8:4-8:38 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 8>: + -- RESUME 4 + +8:35-8:37 LOAD_FAST 0 (.0) +8:35-8:37 GET_ITER 0 +8:?-8:? RETURN_GENERATOR +8:?-8:? POP_TOP +8:0-8:0 L1: RESUME 0 +8:35-8:37 L2: FOR_ITER 11 (to L3) +8:27-8:31 UNPACK_SEQUENCE 2 +8:27-8:28 STORE_FAST_STORE_FAST 18 (x, y) +8:17-8:18 LOAD_FAST_BORROW_LOAD_FAST_BORROW 18 (x, y) +8:16-8:22 BUILD_TUPLE 2 +8:16-8:22 YIELD_VALUE 0 +8:16-8:22 RESUME 9 +8:16-8:22 POP_TOP +8:16-8:22 JUMP_BACKWARD 13 (to L2) +8:35-8:37 L3: END_FOR +8:35-8:37 POP_ITER +8:35-8:37 LOAD_COMMON_CONSTANT 7 (None) +8:35-8:37 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti + +Disassembly of ", line 10>: +10:0-10:0 RESUME 0 + +11:11-11:15 LOAD_GLOBAL 0 (list) +11:11-11:15 COPY 1 +11:11-11:15 LOAD_COMMON_CONSTANT 5 (list) +11:11-11:15 IS_OP 0 (is) +11:11-11:15 POP_JUMP_IF_FALSE 19 (to L3) +11:11-11:15 NOT_TAKEN +11:11-11:15 POP_TOP +11:11-11:15 BUILD_LIST 0 +11:16-11:39 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 11>) +11:16-11:39 MAKE_FUNCTION +11:36-11:38 LOAD_FAST_BORROW 0 (xs) +11:16-11:39 CALL 0 +11:11-11:15 PUSH_NULL +11:11-11:15 L1: FOR_ITER 3 (to L2) +11:11-11:15 LIST_APPEND 3 +11:11-11:15 JUMP_BACKWARD 5 (to L1) +11:11-11:15 L2: END_FOR +11:11-11:15 POP_ITER +11:4-11:40 RETURN_VALUE +11:11-11:15 L3: PUSH_NULL +11:16-11:39 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 11>) +11:16-11:39 MAKE_FUNCTION +11:36-11:38 LOAD_FAST_BORROW 0 (xs) +11:16-11:39 CALL 0 +11:11-11:40 CALL 1 +11:4-11:40 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 11>: + -- RESUME 4 + +11:36-11:38 LOAD_FAST 0 (.0) +11:36-11:38 GET_ITER 0 +11:?-11:? RETURN_GENERATOR +11:?-11:? POP_TOP +11:0-11:0 L1: RESUME 0 +11:36-11:38 L2: FOR_ITER 11 (to L3) +11:28-11:32 UNPACK_SEQUENCE 2 +11:28-11:29 STORE_FAST_STORE_FAST 18 (x, y) +11:18-11:19 LOAD_FAST_BORROW_LOAD_FAST_BORROW 18 (x, y) +11:17-11:23 BUILD_TUPLE 2 +11:17-11:23 YIELD_VALUE 0 +11:17-11:23 RESUME 9 +11:17-11:23 POP_TOP +11:17-11:23 JUMP_BACKWARD 13 (to L2) +11:36-11:38 L3: END_FOR +11:36-11:38 POP_ITER +11:36-11:38 LOAD_COMMON_CONSTANT 7 (None) +11:36-11:38 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__implicit_call_genexpr_range.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__implicit_call_genexpr_range.snap new file mode 100644 index 00000000000..bc11da5dc0a --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__implicit_call_genexpr_range.snap @@ -0,0 +1,131 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef implicit():\n return list(x for x in range(10))\n\ndef explicit():\n return list((x for x in range(10)))\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:37 LOAD_CONST 0 (", line 1>) +1:0-2:37 MAKE_FUNCTION +1:0-2:37 STORE_NAME 0 (implicit) + +4:0-5:39 LOAD_CONST 1 (", line 4>) +4:0-5:39 MAKE_FUNCTION +4:0-5:39 STORE_NAME 1 (explicit) +4:0-5:39 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:39 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:15 LOAD_GLOBAL 0 (list) +2:11-2:15 COPY 1 +2:11-2:15 LOAD_COMMON_CONSTANT 5 (list) +2:11-2:15 IS_OP 0 (is) +2:11-2:15 POP_JUMP_IF_FALSE 28 (to L3) +2:11-2:15 NOT_TAKEN +2:11-2:15 POP_TOP +2:11-2:15 BUILD_LIST 0 +2:15-2:37 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:15-2:37 MAKE_FUNCTION +2:27-2:32 LOAD_GLOBAL 3 (range + NULL) +2:33-2:35 LOAD_SMALL_INT 10 +2:27-2:36 CALL 1 +2:15-2:37 CALL 0 +2:11-2:15 PUSH_NULL +2:11-2:15 L1: FOR_ITER 3 (to L2) +2:11-2:15 LIST_APPEND 3 +2:11-2:15 JUMP_BACKWARD 5 (to L1) +2:11-2:15 L2: END_FOR +2:11-2:15 POP_ITER +2:4-2:37 RETURN_VALUE +2:11-2:15 L3: PUSH_NULL +2:15-2:37 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:15-2:37 MAKE_FUNCTION +2:27-2:32 LOAD_GLOBAL 3 (range + NULL) +2:33-2:35 LOAD_SMALL_INT 10 +2:27-2:36 CALL 1 +2:15-2:37 CALL 0 +2:11-2:37 CALL 1 +2:4-2:37 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:27-2:36 LOAD_FAST 0 (.0) +2:27-2:36 GET_ITER 0 +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:27-2:36 L2: FOR_ITER 7 (to L3) +2:22-2:23 STORE_FAST_LOAD_FAST 17 (x, x) +2:16-2:17 YIELD_VALUE 0 +2:16-2:17 RESUME 9 +2:16-2:17 POP_TOP +2:16-2:17 JUMP_BACKWARD 9 (to L2) +2:27-2:36 L3: END_FOR +2:27-2:36 POP_ITER +2:27-2:36 LOAD_COMMON_CONSTANT 7 (None) +2:27-2:36 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti + +Disassembly of ", line 4>: +4:0-4:0 RESUME 0 + +5:11-5:15 LOAD_GLOBAL 0 (list) +5:11-5:15 COPY 1 +5:11-5:15 LOAD_COMMON_CONSTANT 5 (list) +5:11-5:15 IS_OP 0 (is) +5:11-5:15 POP_JUMP_IF_FALSE 28 (to L3) +5:11-5:15 NOT_TAKEN +5:11-5:15 POP_TOP +5:11-5:15 BUILD_LIST 0 +5:16-5:38 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:16-5:38 MAKE_FUNCTION +5:28-5:33 LOAD_GLOBAL 3 (range + NULL) +5:34-5:36 LOAD_SMALL_INT 10 +5:28-5:37 CALL 1 +5:16-5:38 CALL 0 +5:11-5:15 PUSH_NULL +5:11-5:15 L1: FOR_ITER 3 (to L2) +5:11-5:15 LIST_APPEND 3 +5:11-5:15 JUMP_BACKWARD 5 (to L1) +5:11-5:15 L2: END_FOR +5:11-5:15 POP_ITER +5:4-5:39 RETURN_VALUE +5:11-5:15 L3: PUSH_NULL +5:16-5:38 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:16-5:38 MAKE_FUNCTION +5:28-5:33 LOAD_GLOBAL 3 (range + NULL) +5:34-5:36 LOAD_SMALL_INT 10 +5:28-5:37 CALL 1 +5:16-5:38 CALL 0 +5:11-5:39 CALL 1 +5:4-5:39 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 5>: + -- RESUME 4 + +5:28-5:37 LOAD_FAST 0 (.0) +5:28-5:37 GET_ITER 0 +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 +5:28-5:37 L2: FOR_ITER 7 (to L3) +5:23-5:24 STORE_FAST_LOAD_FAST 17 (x, x) +5:17-5:18 YIELD_VALUE 0 +5:17-5:18 RESUME 9 +5:17-5:18 POP_TOP +5:17-5:18 JUMP_BACKWARD 9 (to L2) +5:28-5:37 L3: END_FOR +5:28-5:37 POP_ITER +5:28-5:37 LOAD_COMMON_CONSTANT 7 (None) +5:28-5:37 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [2] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__import_flags.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__import_flags.snap new file mode 100644 index 00000000000..64802b5c719 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__import_flags.snap @@ -0,0 +1,190 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nimport sample\nfrom sample import member\nfrom sample import *\n\ndef f():\n import sample\n\nclass C:\n from sample import member\n\ntry:\n import sample\nexcept Exception:\n pass\n\ntry:\n operation()\nexcept Exception:\n import sample\n\ntry:\n operation()\nfinally:\n import sample\n\nwith manager:\n import sample\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-1:13 LOAD_SMALL_INT 0 +1:0-1:13 LOAD_COMMON_CONSTANT 7 (None) +1:0-1:13 IMPORT_NAME 0 (sample) +1:0-1:13 STORE_NAME 0 (sample) + +2:0-2:25 LOAD_SMALL_INT 0 +2:0-2:25 LOAD_CONST 1 (('member',)) +2:0-2:25 IMPORT_NAME 0 (sample) +2:0-2:25 IMPORT_FROM 1 (member) +2:0-2:25 STORE_NAME 1 (member) +2:0-2:25 POP_TOP + +3:0-3:20 LOAD_SMALL_INT 0 +3:0-3:20 LOAD_CONST 2 (('*',)) +3:0-3:20 IMPORT_NAME 2 (sample + eager) +3:0-3:20 CALL_INTRINSIC_1 2 (INTRINSIC_IMPORT_STAR) +3:0-3:20 POP_TOP + +5:0-6:17 LOAD_CONST 3 (", line 5>) +5:0-6:17 MAKE_FUNCTION +5:0-6:17 STORE_NAME 2 (f) + +8:0-9:29 LOAD_BUILD_CLASS +8:0-9:29 PUSH_NULL +8:0-9:29 LOAD_CONST 4 (", line 8>) +8:0-9:29 MAKE_FUNCTION +8:0-9:29 LOAD_CONST 5 ('C') +8:0-9:29 CALL 2 +8:0-9:29 STORE_NAME 3 (C) + +11:0-14:8 NOP + +12:4-12:17 L1: LOAD_SMALL_INT 0 +12:4-12:17 LOAD_COMMON_CONSTANT 7 (None) +12:4-12:17 IMPORT_NAME 2 (sample + eager) +12:4-12:17 STORE_NAME 0 (sample) + +16:0-19:17 L2: NOP + +17:4-17:13 L3: LOAD_NAME 5 (operation) +17:4-17:13 PUSH_NULL +17:4-17:15 CALL 0 +17:4-17:15 POP_TOP + +21:0-24:17 L4: NOP + +22:4-22:13 L5: LOAD_NAME 5 (operation) +22:4-22:13 PUSH_NULL +22:4-22:15 CALL 0 +22:4-22:15 POP_TOP + +24:4-24:17 L6: LOAD_SMALL_INT 0 +24:4-24:17 LOAD_COMMON_CONSTANT 7 (None) +24:4-24:17 IMPORT_NAME 0 (sample) +24:4-24:17 STORE_NAME 0 (sample) + +26:5-26:12 LOAD_NAME 6 (manager) +26:5-26:12 COPY 1 +26:5-26:12 LOAD_SPECIAL 1 (__exit__) +26:5-26:12 SWAP 2 +26:5-26:12 SWAP 3 +26:5-26:12 LOAD_SPECIAL 0 (__enter__) +26:5-26:12 CALL 0 +26:5-26:12 L7: POP_TOP + +27:4-27:17 LOAD_SMALL_INT 0 +27:4-27:17 LOAD_COMMON_CONSTANT 7 (None) +27:4-27:17 IMPORT_NAME 0 (sample) +27:4-27:17 STORE_NAME 0 (sample) + +26:5-26:12 L8: LOAD_COMMON_CONSTANT 7 (None) +26:5-26:12 LOAD_COMMON_CONSTANT 7 (None) +26:5-26:12 LOAD_COMMON_CONSTANT 7 (None) +26:5-26:12 CALL 3 +26:5-26:12 POP_TOP +26:5-26:12 LOAD_COMMON_CONSTANT 7 (None) +26:5-26:12 RETURN_VALUE + + -- L9: PUSH_EXC_INFO + +13:7-13:16 LOAD_NAME 4 (Exception) +13:0-14:8 CHECK_EXC_MATCH +13:0-14:8 POP_JUMP_IF_FALSE 4 (to L11) +13:0-14:8 NOT_TAKEN +13:0-14:8 POP_TOP + +14:4-14:8 L10: POP_EXCEPT +14:4-14:8 JUMP_BACKWARD_NO_INTERRUPT 54 (to L2) + +13:0-14:8 L11: RERAISE 0 + + -- L12: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 + -- L13: PUSH_EXC_INFO + +18:7-18:16 LOAD_NAME 4 (Exception) +18:0-19:17 CHECK_EXC_MATCH +18:0-19:17 POP_JUMP_IF_FALSE 8 (to L15) +18:0-19:17 NOT_TAKEN +18:0-19:17 POP_TOP + +19:4-19:17 LOAD_SMALL_INT 0 +19:4-19:17 LOAD_COMMON_CONSTANT 7 (None) +19:4-19:17 IMPORT_NAME 2 (sample + eager) +19:4-19:17 STORE_NAME 0 (sample) +19:4-19:17 L14: POP_EXCEPT +19:4-19:17 JUMP_BACKWARD_NO_INTERRUPT 63 (to L4) + +18:0-19:17 L15: RERAISE 0 + + -- L16: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 + -- L17: PUSH_EXC_INFO + +24:4-24:17 LOAD_SMALL_INT 0 +24:4-24:17 LOAD_COMMON_CONSTANT 7 (None) +24:4-24:17 IMPORT_NAME 2 (sample + eager) +24:4-24:17 STORE_NAME 0 (sample) +24:4-24:17 RERAISE 0 + + -- L18: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 + +26:5-26:12 L19: PUSH_EXC_INFO +26:5-26:12 WITH_EXCEPT_START +26:5-26:12 TO_BOOL +26:5-26:12 POP_JUMP_IF_TRUE 2 (to L20) +26:5-26:12 NOT_TAKEN +26:5-26:12 RERAISE 2 +26:5-26:12 L20: POP_TOP +26:5-26:12 L21: POP_EXCEPT +26:5-26:12 POP_TOP +26:5-26:12 POP_TOP +26:5-26:12 POP_TOP +26:5-26:12 LOAD_COMMON_CONSTANT 7 (None) +26:5-26:12 RETURN_VALUE + + -- L22: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L9 [0] + L3 to L4 -> L13 [0] + L5 to L6 -> L17 [0] + L7 to L8 -> L19 [2] lasti + L9 to L10 -> L12 [1] lasti + L11 to L12 -> L12 [1] lasti + L13 to L14 -> L16 [1] lasti + L15 to L16 -> L16 [1] lasti + L17 to L18 -> L18 [1] lasti + L19 to L21 -> L22 [4] lasti + +Disassembly of ", line 5>: +5:0-5:0 RESUME 0 + +6:4-6:17 LOAD_SMALL_INT 0 +6:4-6:17 LOAD_COMMON_CONSTANT 7 (None) +6:4-6:17 IMPORT_NAME 2 (sample + eager) +6:4-6:17 STORE_FAST 0 (sample) +6:4-6:17 LOAD_COMMON_CONSTANT 7 (None) +6:4-6:17 RETURN_VALUE + +Disassembly of ", line 8>: +8:0-8:0 RESUME 0 +8:0-8:0 LOAD_NAME 0 (__name__) +8:0-8:0 STORE_NAME 1 (__module__) +8:0-8:0 LOAD_CONST 0 ('C') +8:0-8:0 STORE_NAME 2 (__qualname__) +8:0-8:0 LOAD_SMALL_INT 8 +8:0-8:0 STORE_NAME 3 (__firstlineno__) + +9:4-9:29 LOAD_SMALL_INT 0 +9:4-9:29 LOAD_CONST 1 (('member',)) +9:4-9:29 IMPORT_NAME 18 (sample + eager) +9:4-9:29 IMPORT_FROM 5 (member) +9:4-9:29 STORE_NAME 5 (member) +9:4-9:29 POP_TOP +9:4-9:29 LOAD_CONST 2 (()) +9:4-9:29 STORE_NAME 6 (__static_attributes__) +9:4-9:29 LOAD_COMMON_CONSTANT 7 (None) +9:4-9:29 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__inlined_async_comprehension_end_async_for_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__inlined_async_comprehension_end_async_for_location.snap new file mode 100644 index 00000000000..0e996da0912 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__inlined_async_comprehension_end_async_for_location.snap @@ -0,0 +1,97 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nasync def f(it):\n for i in it:\n yield i\n\nasync def run_list():\n return [i + 1 async for i in f([10, 20])]\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-3:15 LOAD_CONST 0 (", line 1>) +1:0-3:15 MAKE_FUNCTION +1:0-3:15 STORE_NAME 0 (f) + +5:0-6:45 LOAD_CONST 1 (", line 5>) +5:0-6:45 MAKE_FUNCTION +5:0-6:45 STORE_NAME 1 (run_list) +5:0-6:45 LOAD_COMMON_CONSTANT 7 (None) +5:0-6:45 RETURN_VALUE + +Disassembly of ", line 1>: +1:?-1:? RETURN_GENERATOR +1:?-1:? POP_TOP +1:0-1:0 L1: RESUME 0 + +2:13-2:15 LOAD_FAST 0 (it) +2:13-2:15 GET_ITER 0 +2:13-2:15 L2: FOR_ITER 9 (to L3) +2:8-2:9 STORE_FAST 1 (i) + +3:14-3:15 LOAD_FAST_BORROW 1 (i) +3:8-3:15 CALL_INTRINSIC_1 4 (INTRINSIC_ASYNC_GEN_WRAP) +3:8-3:15 YIELD_VALUE 0 +3:8-3:15 RESUME 9 +3:8-3:15 POP_TOP +3:8-3:15 JUMP_BACKWARD 11 (to L2) + +2:13-2:15 L3: END_FOR +2:13-2:15 POP_ITER +2:13-2:15 LOAD_COMMON_CONSTANT 7 (None) +2:13-2:15 RETURN_VALUE + + -- L4: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L4 -> L4 [0] lasti + +Disassembly of ", line 5>: +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 + +6:33-6:34 LOAD_GLOBAL 1 (f + NULL) +6:36-6:38 LOAD_SMALL_INT 10 +6:40-6:42 LOAD_SMALL_INT 20 +6:35-6:43 BUILD_LIST 2 +6:33-6:44 CALL 1 +6:11-6:45 LOAD_FAST_AND_CLEAR 0 (i) +6:11-6:45 SWAP 2 +6:11-6:45 L2: BUILD_LIST 0 +6:11-6:45 SWAP 2 +6:33-6:44 GET_AITER +6:11-6:45 L3: GET_ANEXT +6:11-6:45 PUSH_NULL +6:11-6:45 LOAD_COMMON_CONSTANT 7 (None) +6:11-6:45 L4: SEND 4 (to L7) +6:11-6:45 L5: YIELD_VALUE 1 +6:11-6:45 L6: RESUME 3 +6:11-6:45 JUMP_BACKWARD_NO_INTERRUPT 6 (to L4) +6:11-6:45 L7: END_SEND +6:28-6:29 L8: STORE_FAST_LOAD_FAST 0 (i, i) +6:16-6:17 LOAD_SMALL_INT 1 +6:12-6:17 BINARY_OP 0 (+) +6:12-6:17 LIST_APPEND 2 +6:12-6:17 JUMP_BACKWARD 21 (to L3) +6:11-6:45 L9: CLEANUP_THROW +6:11-6:45 L10: JUMP_BACKWARD_NO_INTERRUPT 14 (to L7) +6:11-6:45 L11: END_ASYNC_FOR 15 (from L7) +6:11-6:45 L12: SWAP 2 +6:11-6:45 STORE_FAST 0 (i) +6:4-6:45 RETURN_VALUE + + -- L13: SWAP 2 + -- POP_TOP + +6:11-6:45 SWAP 2 +6:11-6:45 STORE_FAST 0 (i) +6:11-6:45 RERAISE 0 + + -- L14: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L14 [0] lasti + L2 to L3 -> L13 [2] + L3 to L5 -> L11 [3] + L5 to L6 -> L9 [6] + L6 to L8 -> L11 [3] + L8 to L9 -> L13 [2] + L9 to L10 -> L11 [3] + L11 to L12 -> L13 [2] + L12 to L14 -> L14 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__inlined_comprehension_backedge_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__inlined_comprehension_backedge_location.snap new file mode 100644 index 00000000000..9ab39805cc9 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__inlined_comprehension_backedge_location.snap @@ -0,0 +1,92 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nasync def f(i):\n return i\n\nasync def run_list():\n return [s for c in [f(''), f('abc')] for s in await c]\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:12 LOAD_CONST 0 (", line 1>) +1:0-2:12 MAKE_FUNCTION +1:0-2:12 STORE_NAME 0 (f) + +4:0-5:58 LOAD_CONST 1 (", line 4>) +4:0-5:58 MAKE_FUNCTION +4:0-5:58 STORE_NAME 1 (run_list) +4:0-5:58 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:58 RETURN_VALUE + +Disassembly of ", line 1>: +1:?-1:? RETURN_GENERATOR +1:?-1:? POP_TOP +1:0-1:0 L1: RESUME 0 + +2:11-2:12 LOAD_FAST_BORROW 0 (i) +2:4-2:12 RETURN_VALUE + + -- L2: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L2 [0] lasti + +Disassembly of ", line 4>: +4:?-4:? RETURN_GENERATOR +4:?-4:? POP_TOP +4:0-4:0 L1: RESUME 0 + +5:24-5:25 LOAD_GLOBAL 1 (f + NULL) +5:26-5:28 LOAD_COMMON_CONSTANT 8 ('') +5:24-5:29 CALL 1 +5:31-5:32 LOAD_GLOBAL 1 (f + NULL) +5:33-5:38 LOAD_CONST 1 ('abc') +5:31-5:39 CALL 1 +5:23-5:40 BUILD_LIST 2 +5:11-5:58 LOAD_FAST_AND_CLEAR 0 (c) +5:11-5:58 LOAD_FAST_AND_CLEAR 1 (s) +5:11-5:58 SWAP 3 +5:11-5:58 L2: BUILD_LIST 0 +5:11-5:58 SWAP 2 +5:23-5:40 GET_ITER 0 +5:23-5:40 L3: FOR_ITER 23 (to L10) +5:18-5:19 STORE_FAST_LOAD_FAST 0 (c, c) +5:50-5:57 GET_AWAITABLE 0 +5:50-5:57 PUSH_NULL +5:50-5:57 LOAD_COMMON_CONSTANT 7 (None) +5:50-5:57 L4: SEND 4 (to L7) +5:50-5:57 L5: YIELD_VALUE 1 +5:50-5:57 L6: RESUME 3 +5:50-5:57 JUMP_BACKWARD_NO_INTERRUPT 6 (to L4) +5:50-5:57 L7: END_SEND +5:50-5:57 GET_ITER 0 +5:50-5:57 L8: FOR_ITER 4 (to L9) +5:45-5:46 STORE_FAST_LOAD_FAST 17 (s, s) +5:12-5:13 LIST_APPEND 5 +5:12-5:13 JUMP_BACKWARD 6 (to L8) +5:50-5:57 L9: END_FOR +5:50-5:57 POP_ITER +5:12-5:13 JUMP_BACKWARD 25 (to L3) +5:23-5:40 L10: END_FOR +5:23-5:40 POP_ITER +5:11-5:58 L11: SWAP 3 +5:11-5:58 STORE_FAST 1 (s) +5:11-5:58 STORE_FAST 0 (c) +5:4-5:58 RETURN_VALUE +5:50-5:57 L12: CLEANUP_THROW +5:50-5:57 L13: JUMP_BACKWARD_NO_INTERRUPT 21 (to L7) + + -- L14: SWAP 2 + -- POP_TOP + +5:11-5:58 SWAP 3 +5:11-5:58 STORE_FAST 1 (s) +5:11-5:58 STORE_FAST 0 (c) +5:11-5:58 RERAISE 0 + + -- L15: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L15 [0] lasti + L2 to L5 -> L14 [3] + L5 to L6 -> L12 [8] + L6 to L11 -> L14 [3] + L11 to L12 -> L15 [0] lasti + L12 to L13 -> L14 [3] + L14 to L15 -> L15 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__joined_string_literals_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__joined_string_literals_location.snap new file mode 100644 index 00000000000..69582f4f61f --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__joined_string_literals_location.snap @@ -0,0 +1,24 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(a):\n return (\n 'x'\n f'y{a}z'\n 'w'\n )\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-6:5 LOAD_CONST 0 (", line 1>) +1:0-6:5 MAKE_FUNCTION +1:0-6:5 STORE_NAME 0 (f) +1:0-6:5 LOAD_COMMON_CONSTANT 7 (None) +1:0-6:5 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +3:8-4:11 LOAD_CONST 0 ('xy') + +4:12-4:13 LOAD_FAST_BORROW 0 (a) +4:11-4:14 FORMAT_SIMPLE +4:14-5:11 LOAD_CONST 1 ('zw') + +3:8-5:11 BUILD_STRING 3 + +2:4-6:5 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__lambda_dict_literal_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__lambda_dict_literal_location.snap new file mode 100644 index 00000000000..11e587c10b0 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__lambda_dict_literal_location.snap @@ -0,0 +1,29 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nf = lambda data: {'x': data}\ng = lambda i: {**i}\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:4-1:28 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 1>) +1:4-1:28 MAKE_FUNCTION +1:0-1:1 STORE_NAME 0 (f) + +2:4-2:19 LOAD_CONST 1 ( at 0xdeadbeef, file "", line 2>) +2:4-2:19 MAKE_FUNCTION +2:0-2:1 STORE_NAME 1 (g) +2:0-2:1 LOAD_COMMON_CONSTANT 7 (None) +2:0-2:1 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 1>: +1:0-1:0 RESUME 0 +1:18-1:21 LOAD_CONST 0 ('x') +1:23-1:27 LOAD_FAST_BORROW 0 (data) +1:17-1:28 BUILD_MAP 1 +1:17-1:28 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 2>: +2:0-2:0 RESUME 0 +2:14-2:19 BUILD_MAP 0 +2:17-2:18 LOAD_FAST_BORROW 0 (i) +2:14-2:19 DICT_UPDATE 1 +2:14-2:19 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__list_set_async_genexpr_calls.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__list_set_async_genexpr_calls.snap new file mode 100644 index 00000000000..68e944983c8 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__list_set_async_genexpr_calls.snap @@ -0,0 +1,129 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nasync def f(xs):\n return list(x async for x in xs)\n\nasync def g(xs):\n return set(x async for x in xs)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:36 LOAD_CONST 0 (", line 1>) +1:0-2:36 MAKE_FUNCTION +1:0-2:36 STORE_NAME 0 (f) + +4:0-5:35 LOAD_CONST 1 (", line 4>) +4:0-5:35 MAKE_FUNCTION +4:0-5:35 STORE_NAME 1 (g) +4:0-5:35 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:35 RETURN_VALUE + +Disassembly of ", line 1>: +1:?-1:? RETURN_GENERATOR +1:?-1:? POP_TOP +1:0-1:0 L1: RESUME 0 + +2:11-2:15 LOAD_GLOBAL 1 (list + NULL) +2:15-2:36 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 2>) +2:15-2:36 MAKE_FUNCTION +2:33-2:35 LOAD_FAST_BORROW 0 (xs) +2:15-2:36 CALL 0 +2:11-2:36 CALL 1 +2:4-2:36 RETURN_VALUE + + -- L2: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L2 [0] lasti + +Disassembly of at 0xdeadbeef, file "", line 2>: + -- RESUME 4 + +2:33-2:35 LOAD_FAST_BORROW 0 (.0) +2:33-2:35 GET_AITER +2:?-2:? RETURN_GENERATOR +2:?-2:? POP_TOP +2:0-2:0 L1: RESUME 0 +2:15-2:36 L2: GET_ANEXT +2:15-2:36 PUSH_NULL +2:15-2:36 LOAD_COMMON_CONSTANT 7 (None) +2:15-2:36 L3: SEND 4 (to L6) +2:15-2:36 L4: YIELD_VALUE 1 +2:15-2:36 L5: RESUME 3 +2:15-2:36 JUMP_BACKWARD_NO_INTERRUPT 6 (to L3) +2:15-2:36 L6: END_SEND +2:28-2:29 L7: STORE_FAST_LOAD_FAST 17 (x, x) +2:16-2:17 CALL_INTRINSIC_1 4 (INTRINSIC_ASYNC_GEN_WRAP) +2:16-2:17 YIELD_VALUE 0 +2:16-2:17 RESUME 9 +2:16-2:17 POP_TOP +2:16-2:17 JUMP_BACKWARD 18 (to L2) +2:15-2:36 L8: CLEANUP_THROW +2:15-2:36 L9: JUMP_BACKWARD_NO_INTERRUPT 11 (to L6) +2:15-2:36 L10: END_ASYNC_FOR 12 (from L6) +2:15-2:36 LOAD_COMMON_CONSTANT 7 (None) +2:15-2:36 RETURN_VALUE + + -- L11: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L11 [1] lasti + L2 to L4 -> L10 [1] + L4 to L5 -> L8 [4] + L5 to L7 -> L10 [1] + L7 to L8 -> L11 [1] lasti + L8 to L9 -> L10 [1] + L10 to L11 -> L11 [1] lasti + +Disassembly of ", line 4>: +4:?-4:? RETURN_GENERATOR +4:?-4:? POP_TOP +4:0-4:0 L1: RESUME 0 + +5:11-5:14 LOAD_GLOBAL 1 (set + NULL) +5:14-5:35 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 5>) +5:14-5:35 MAKE_FUNCTION +5:32-5:34 LOAD_FAST_BORROW 0 (xs) +5:14-5:35 CALL 0 +5:11-5:35 CALL 1 +5:4-5:35 RETURN_VALUE + + -- L2: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L2 [0] lasti + +Disassembly of at 0xdeadbeef, file "", line 5>: + -- RESUME 4 + +5:32-5:34 LOAD_FAST_BORROW 0 (.0) +5:32-5:34 GET_AITER +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 +5:14-5:35 L2: GET_ANEXT +5:14-5:35 PUSH_NULL +5:14-5:35 LOAD_COMMON_CONSTANT 7 (None) +5:14-5:35 L3: SEND 4 (to L6) +5:14-5:35 L4: YIELD_VALUE 1 +5:14-5:35 L5: RESUME 3 +5:14-5:35 JUMP_BACKWARD_NO_INTERRUPT 6 (to L3) +5:14-5:35 L6: END_SEND +5:27-5:28 L7: STORE_FAST_LOAD_FAST 17 (x, x) +5:15-5:16 CALL_INTRINSIC_1 4 (INTRINSIC_ASYNC_GEN_WRAP) +5:15-5:16 YIELD_VALUE 0 +5:15-5:16 RESUME 9 +5:15-5:16 POP_TOP +5:15-5:16 JUMP_BACKWARD 18 (to L2) +5:14-5:35 L8: CLEANUP_THROW +5:14-5:35 L9: JUMP_BACKWARD_NO_INTERRUPT 11 (to L6) +5:14-5:35 L10: END_ASYNC_FOR 12 (from L6) +5:14-5:35 LOAD_COMMON_CONSTANT 7 (None) +5:14-5:35 RETURN_VALUE + + -- L11: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L11 [1] lasti + L2 to L4 -> L10 [1] + L4 to L5 -> L8 [4] + L5 to L7 -> L10 [1] + L7 to L8 -> L11 [1] lasti + L8 to L9 -> L10 [1] + L10 to L11 -> L11 [1] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__loop_return_cleanup.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__loop_return_cleanup.snap new file mode 100644 index 00000000000..098a84a976b --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__loop_return_cleanup.snap @@ -0,0 +1,74 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(xs):\n for x in xs:\n return x\n\nasync def g(xs):\n async for x in xs:\n return x\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-3:16 LOAD_CONST 0 (", line 1>) +1:0-3:16 MAKE_FUNCTION +1:0-3:16 STORE_NAME 0 (f) + +5:0-7:16 LOAD_CONST 1 (", line 5>) +5:0-7:16 MAKE_FUNCTION +5:0-7:16 STORE_NAME 1 (g) +5:0-7:16 LOAD_COMMON_CONSTANT 7 (None) +5:0-7:16 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:13-2:15 LOAD_FAST 0 (xs) +2:13-2:15 GET_ITER 0 +2:13-2:15 FOR_ITER 6 (to L1) +2:8-2:9 STORE_FAST 1 (x) + +3:15-3:16 LOAD_FAST_BORROW 1 (x) +3:8-3:16 SWAP 3 +3:8-3:16 POP_TOP +3:8-3:16 POP_TOP +3:8-3:16 RETURN_VALUE + +2:13-2:15 L1: END_FOR +2:13-2:15 POP_ITER +2:13-2:15 LOAD_COMMON_CONSTANT 7 (None) +2:13-2:15 RETURN_VALUE + +Disassembly of ", line 5>: +5:?-5:? RETURN_GENERATOR +5:?-5:? POP_TOP +5:0-5:0 L1: RESUME 0 + +6:19-6:21 LOAD_FAST_BORROW 0 (xs) +6:19-6:21 GET_AITER +6:4-7:16 L2: GET_ANEXT +6:4-7:16 PUSH_NULL +6:4-7:16 LOAD_COMMON_CONSTANT 7 (None) +6:4-7:16 L3: SEND 4 (to L6) +6:4-7:16 L4: YIELD_VALUE 1 +6:4-7:16 L5: RESUME 3 +6:4-7:16 JUMP_BACKWARD_NO_INTERRUPT 6 (to L3) +6:4-7:16 L6: END_SEND +6:4-7:16 L7: NOT_TAKEN +6:14-6:15 STORE_FAST 1 (x) + +7:15-7:16 LOAD_FAST_BORROW 1 (x) +7:8-7:16 SWAP 2 +7:8-7:16 POP_TOP +7:8-7:16 RETURN_VALUE + +6:4-7:16 L8: CLEANUP_THROW +6:4-7:16 L9: JUMP_BACKWARD_NO_INTERRUPT 9 (to L6) +6:19-6:21 L10: END_ASYNC_FOR 10 (from L6) +6:19-6:21 LOAD_COMMON_CONSTANT 7 (None) +6:19-6:21 RETURN_VALUE + + -- L11: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L11 [0] lasti + L2 to L4 -> L10 [1] + L4 to L5 -> L8 [4] + L5 to L7 -> L10 [1] + L7 to L8 -> L11 [0] lasti + L8 to L9 -> L10 [1] + L10 to L11 -> L11 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_class_scaffolding_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_class_scaffolding_location.snap new file mode 100644 index 00000000000..ba6e6a937c3 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_class_scaffolding_location.snap @@ -0,0 +1,39 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(x):\n match x:\n case bool(z):\n y = 0\n return y, z\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-5:15 LOAD_CONST 0 (", line 1>) +1:0-5:15 MAKE_FUNCTION +1:0-5:15 STORE_NAME 0 (f) +1:0-5:15 LOAD_COMMON_CONSTANT 7 (None) +1:0-5:15 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:10-2:11 LOAD_FAST_BORROW 0 (x) + +3:13-3:17 LOAD_GLOBAL 0 (bool) +3:13-3:20 LOAD_CONST 0 (()) +3:13-3:20 MATCH_CLASS 1 +3:13-3:20 COPY 1 +3:13-3:20 POP_JUMP_IF_NONE 9 (to L1) +3:13-3:20 NOT_TAKEN +3:13-3:20 UNPACK_SEQUENCE 1 +3:13-3:20 STORE_FAST 1 (z) + +4:16-4:17 LOAD_SMALL_INT 0 +4:12-4:13 STORE_FAST 2 (y) + +5:11-5:12 LOAD_FAST_BORROW_LOAD_FAST_BORROW 33 (y, z) +5:11-5:15 BUILD_TUPLE 2 +5:4-5:15 RETURN_VALUE + +3:13-3:20 L1: POP_TOP + +5:11-5:12 LOAD_FAST_CHECK 2 (y) +5:14-5:15 LOAD_FAST_CHECK 1 (z) +5:11-5:15 BUILD_TUPLE 2 +5:4-5:15 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_mapping_keys_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_mapping_keys_location.snap new file mode 100644 index 00000000000..cd45a759947 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_mapping_keys_location.snap @@ -0,0 +1,60 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(self):\n x = {}\n y = None\n match x:\n case {0: 0}:\n y = 0\n self.assertIs(y, None)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-7:26 LOAD_CONST 0 (", line 1>) +1:0-7:26 MAKE_FUNCTION +1:0-7:26 STORE_NAME 0 (f) +1:0-7:26 LOAD_COMMON_CONSTANT 7 (None) +1:0-7:26 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:8-2:10 BUILD_MAP 0 +2:4-2:5 STORE_FAST 1 (x) + +3:8-3:12 LOAD_COMMON_CONSTANT 7 (None) +3:4-3:5 STORE_FAST 2 (y) + +4:10-4:11 LOAD_FAST 1 (x) + +5:13-5:19 MATCH_MAPPING +5:13-5:19 POP_JUMP_IF_FALSE 29 (to L3) +5:13-5:19 NOT_TAKEN +5:13-5:19 GET_LEN +5:13-5:19 LOAD_SMALL_INT 1 +5:13-5:19 COMPARE_OP 172 (>=) +5:13-5:19 POP_JUMP_IF_FALSE 22 (to L3) +5:13-5:19 NOT_TAKEN +5:13-5:19 LOAD_CONST 1 ((0,)) +5:13-5:19 MATCH_KEYS +5:13-5:19 COPY 1 +5:13-5:19 POP_JUMP_IF_NONE 14 (to L1) +5:13-5:19 NOT_TAKEN +5:13-5:19 UNPACK_SEQUENCE 1 +5:17-5:18 LOAD_SMALL_INT 0 +5:17-5:18 COMPARE_OP 88 (bool(==)) +5:17-5:18 POP_JUMP_IF_FALSE 7 (to L2) +5:17-5:18 NOT_TAKEN +5:13-5:19 POP_TOP +5:13-5:19 POP_TOP + +6:16-6:17 LOAD_SMALL_INT 0 +6:12-6:13 STORE_FAST 2 (y) +6:12-6:13 JUMP_FORWARD 3 (to L4) + +5:13-5:19 L1: POP_TOP +5:13-5:19 L2: POP_TOP +5:13-5:19 L3: POP_TOP + +7:4-7:8 L4: LOAD_FAST_BORROW 0 (self) +7:4-7:17 LOAD_ATTR 1 (assertIs + NULL|self) +7:18-7:19 LOAD_FAST_BORROW 2 (y) +7:21-7:25 LOAD_COMMON_CONSTANT 7 (None) +7:4-7:26 CALL 2 +7:4-7:26 POP_TOP +7:4-7:26 LOAD_COMMON_CONSTANT 7 (None) +7:4-7:26 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_or_alternative_locations.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_or_alternative_locations.snap new file mode 100644 index 00000000000..e0b03b2a2dd --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_or_alternative_locations.snap @@ -0,0 +1,56 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f():\n x = False\n match 0:\n case 0 | 1 | 2 | 3:\n x = True\n return x\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-6:12 LOAD_CONST 0 (", line 1>) +1:0-6:12 MAKE_FUNCTION +1:0-6:12 STORE_NAME 0 (f) +1:0-6:12 LOAD_COMMON_CONSTANT 7 (None) +1:0-6:12 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:8-2:13 LOAD_COMMON_CONSTANT 10 (False) +2:4-2:5 STORE_FAST 0 (x) + +3:10-3:11 LOAD_SMALL_INT 0 + +4:13-4:14 COPY 1 +4:13-4:14 LOAD_SMALL_INT 0 +4:13-4:14 COMPARE_OP 88 (bool(==)) +4:13-4:14 POP_JUMP_IF_FALSE 2 (to L1) +4:13-4:14 NOT_TAKEN +4:13-4:14 JUMP_FORWARD 27 (to L5) +4:17-4:18 L1: COPY 1 +4:17-4:18 LOAD_SMALL_INT 1 +4:17-4:18 COMPARE_OP 88 (bool(==)) +4:17-4:18 POP_JUMP_IF_FALSE 2 (to L2) +4:17-4:18 NOT_TAKEN +4:17-4:18 JUMP_FORWARD 19 (to L5) +4:21-4:22 L2: COPY 1 +4:21-4:22 LOAD_SMALL_INT 2 +4:21-4:22 COMPARE_OP 88 (bool(==)) +4:21-4:22 POP_JUMP_IF_FALSE 2 (to L3) +4:21-4:22 NOT_TAKEN +4:21-4:22 JUMP_FORWARD 11 (to L5) +4:25-4:26 L3: COPY 1 +4:25-4:26 LOAD_SMALL_INT 3 +4:25-4:26 COMPARE_OP 88 (bool(==)) +4:25-4:26 POP_JUMP_IF_FALSE 2 (to L4) +4:25-4:26 NOT_TAKEN +4:25-4:26 JUMP_FORWARD 3 (to L5) +4:13-4:26 L4: POP_TOP + +6:11-6:12 LOAD_FAST_BORROW 0 (x) +6:4-6:12 RETURN_VALUE + +4:13-4:26 L5: POP_TOP + +5:16-5:20 LOAD_COMMON_CONSTANT 9 (True) +5:12-5:13 STORE_FAST 0 (x) + +6:11-6:12 LOAD_FAST_BORROW 0 (x) +6:4-6:12 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_success_jump_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_success_jump_location.snap new file mode 100644 index 00000000000..b76ff06acd8 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__match_success_jump_location.snap @@ -0,0 +1,44 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(self):\n match 0:\n case 0:\n x = True\n case 0:\n x = False\n self.assertIs(x, True)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-7:26 LOAD_CONST 0 (", line 1>) +1:0-7:26 MAKE_FUNCTION +1:0-7:26 STORE_NAME 0 (f) +1:0-7:26 LOAD_COMMON_CONSTANT 7 (None) +1:0-7:26 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:10-2:11 LOAD_SMALL_INT 0 + +3:13-3:14 COPY 1 +3:13-3:14 LOAD_SMALL_INT 0 +3:13-3:14 COMPARE_OP 88 (bool(==)) +3:13-3:14 POP_JUMP_IF_FALSE 5 (to L1) +3:13-3:14 NOT_TAKEN + +4:16-4:20 POP_TOP +4:16-4:20 LOAD_COMMON_CONSTANT 9 (True) +4:12-4:13 STORE_FAST 1 (x) +4:12-4:13 JUMP_FORWARD 8 (to L2) + +5:13-5:14 L1: LOAD_SMALL_INT 0 +5:13-5:14 COMPARE_OP 88 (bool(==)) +5:13-5:14 POP_JUMP_IF_FALSE 3 (to L2) +5:13-5:14 NOT_TAKEN + +6:16-6:21 LOAD_COMMON_CONSTANT 10 (False) +6:12-6:13 STORE_FAST 1 (x) + +7:4-7:8 L2: LOAD_FAST_BORROW 0 (self) +7:4-7:17 LOAD_ATTR 1 (assertIs + NULL|self) +7:18-7:19 LOAD_FAST_CHECK 1 (x) +7:21-7:25 LOAD_COMMON_CONSTANT 9 (True) +7:4-7:26 CALL 2 +7:4-7:26 POP_TOP +7:4-7:26 LOAD_COMMON_CONSTANT 7 (None) +7:4-7:26 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__module_deferred_annotations_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__module_deferred_annotations_location.snap new file mode 100644 index 00000000000..c266a49f7ad --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__module_deferred_annotations_location.snap @@ -0,0 +1,63 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\nimport os\nX: int\nY: str\n\"#, true)" +--- + -- MAKE_CELL 0 (__conditional_annotations__) + +0:0-1:0 RESUME 0 + +1:0-1:9 LOAD_CONST 1 (", line 1>) +1:0-1:9 MAKE_FUNCTION +1:0-1:9 STORE_NAME 2 (__annotate__) +1:0-1:9 BUILD_SET 0 +1:0-1:9 STORE_NAME 0 (__conditional_annotations__) +1:0-1:9 LOAD_SMALL_INT 0 +1:0-1:9 LOAD_COMMON_CONSTANT 7 (None) +1:0-1:9 IMPORT_NAME 4 (os) +1:0-1:9 STORE_NAME 1 (os) + +2:0-2:6 LOAD_NAME 0 (__conditional_annotations__) +2:0-2:6 LOAD_SMALL_INT 0 +2:0-2:6 SET_ADD 1 +2:0-2:6 POP_TOP + +3:0-3:6 LOAD_NAME 0 (__conditional_annotations__) +3:0-3:6 LOAD_SMALL_INT 1 +3:0-3:6 SET_ADD 1 +3:0-3:6 POP_TOP +3:0-3:6 LOAD_COMMON_CONSTANT 7 (None) +3:0-3:6 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 +1:0-1:9 LOAD_FAST_BORROW 0 (format) +1:0-1:9 LOAD_SMALL_INT 2 +1:0-1:9 COMPARE_OP 132 (>) +1:0-1:9 POP_JUMP_IF_FALSE 3 (to L1) +1:0-1:9 NOT_TAKEN +1:0-1:9 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +1:0-1:9 RAISE_VARARGS 1 +1:0-1:9 L1: BUILD_MAP 0 + +2:0-2:6 LOAD_SMALL_INT 0 +2:0-2:6 LOAD_GLOBAL 0 (__conditional_annotations__) +2:0-2:6 CONTAINS_OP 0 (in) +2:0-2:6 POP_JUMP_IF_FALSE 10 (to L2) +2:0-2:6 NOT_TAKEN +2:3-2:6 LOAD_GLOBAL 2 (int) +2:0-2:6 COPY 2 +2:0-2:6 LOAD_CONST 1 ('X') + +1:0-1:9 STORE_SUBSCR + +3:0-3:6 L2: LOAD_SMALL_INT 1 +3:0-3:6 LOAD_GLOBAL 0 (__conditional_annotations__) +3:0-3:6 CONTAINS_OP 0 (in) +3:0-3:6 POP_JUMP_IF_FALSE 10 (to L3) +3:0-3:6 NOT_TAKEN +3:3-3:6 LOAD_GLOBAL 4 (str) +3:0-3:6 COPY 2 +3:0-3:6 LOAD_CONST 2 ('Y') + +1:0-1:9 STORE_SUBSCR +1:0-1:9 L3: RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__module_docstring_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__module_docstring_location.snap new file mode 100644 index 00000000000..20daf83cdee --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__module_docstring_location.snap @@ -0,0 +1,13 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\n\"doc\"\nx = 1\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-1:5 LOAD_CONST 0 ('doc') +1:0-1:5 STORE_NAME 0 (__doc__) + +2:4-2:5 LOAD_SMALL_INT 1 +2:0-2:1 STORE_NAME 1 (x) +2:0-2:1 LOAD_COMMON_CONSTANT 7 (None) +2:0-2:1 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__namedexpr_copy_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__namedexpr_copy_location.snap new file mode 100644 index 00000000000..7ea7e2d942a --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__namedexpr_copy_location.snap @@ -0,0 +1,40 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef outer():\n a = 10\n def spam():\n nonlocal a\n (a := 20)\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-5:17 LOAD_CONST 0 (", line 1>) +1:0-5:17 MAKE_FUNCTION +1:0-5:17 STORE_NAME 0 (outer) +1:0-5:17 LOAD_COMMON_CONSTANT 7 (None) +1:0-5:17 RETURN_VALUE + +Disassembly of ", line 1>: + -- MAKE_CELL 1 (a) + +1:0-1:0 RESUME 0 + +2:8-2:10 LOAD_SMALL_INT 10 +2:4-2:5 STORE_DEREF 1 (a) + +3:4-5:17 LOAD_FAST_BORROW 1 (a) +3:4-5:17 BUILD_TUPLE 1 +3:4-5:17 LOAD_CONST 1 (", line 3>) +3:4-5:17 MAKE_FUNCTION +3:4-5:17 SET_FUNCTION_ATTRIBUTE 8 (closure) +3:4-5:17 STORE_FAST 0 (spam) +3:4-5:17 LOAD_COMMON_CONSTANT 7 (None) +3:4-5:17 RETURN_VALUE + +Disassembly of ", line 3>: + -- COPY_FREE_VARS 1 + +3:0-3:0 RESUME 0 + +5:14-5:16 LOAD_SMALL_INT 20 +5:9-5:16 COPY 1 +5:9-5:10 STORE_DEREF 0 (a) +5:9-5:10 POP_TOP +5:9-5:10 LOAD_COMMON_CONSTANT 7 (None) +5:9-5:10 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_bool_op.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_bool_op.snap index 00eeb277455..3278d9a7bad 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_bool_op.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_bool_op.snap @@ -13,13 +13,13 @@ expression: "dis(r#\"\nx = Test() and False or False\n\"#)" POP_JUMP_IF_FALSE 11 (to L1) NOT_TAKEN POP_TOP - LOAD_CONST 0 (False) + LOAD_COMMON_CONSTANT 10 (False) COPY 1 TO_BOOL POP_JUMP_IF_TRUE 3 (to L2) NOT_TAKEN L1: POP_TOP - LOAD_CONST 0 (False) + LOAD_COMMON_CONSTANT 10 (False) L2: STORE_NAME 1 (x) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_double_async_with.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_double_async_with.snap index 1c4b2ca9469..084e8f8d4cf 100644 --- a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_double_async_with.snap +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__nested_double_async_with.snap @@ -8,7 +8,7 @@ expression: "dis(r#\"\nasync def test():\n for stop_exc in (StopIteration('sp 1 LOAD_CONST 0 (", line 1>) MAKE_FUNCTION STORE_NAME 0 (test) - LOAD_CONST 1 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE Disassembly of ", line 1>: @@ -23,8 +23,8 @@ Disassembly of ", line 1>: LOAD_CONST 1 ('ham') CALL 1 BUILD_TUPLE 2 - GET_ITER - L2: FOR_ITER 71 (to L11) + GET_ITER 0 + L2: FOR_ITER 73 (to L11) STORE_FAST 0 (stop_exc) 3 LOAD_GLOBAL 4 (self) @@ -53,11 +53,12 @@ Disassembly of ", line 1>: LOAD_SPECIAL 2 (__aenter__) CALL 0 GET_AWAITABLE 1 - LOAD_CONST 3 (None) - L6: SEND 3 (to L9) + PUSH_NULL + LOAD_COMMON_CONSTANT 7 (None) + L6: SEND 4 (to L9) L7: YIELD_VALUE 1 L8: RESUME 3 - JUMP_BACKWARD_NO_INTERRUPT 5 (to L6) + JUMP_BACKWARD_NO_INTERRUPT 6 (to L6) L9: END_SEND L10: POP_TOP @@ -66,7 +67,7 @@ Disassembly of ", line 1>: 2 L11: END_FOR POP_ITER - LOAD_CONST 3 (None) + LOAD_COMMON_CONSTANT 7 (None) RETURN_VALUE 5 L12: CLEANUP_THROW @@ -74,114 +75,114 @@ Disassembly of ", line 1>: L14: PUSH_EXC_INFO WITH_EXCEPT_START GET_AWAITABLE 2 - LOAD_CONST 3 (None) - L15: SEND 4 (to L19) + PUSH_NULL + LOAD_COMMON_CONSTANT 7 (None) + L15: SEND 5 (to L19) L16: YIELD_VALUE 1 L17: RESUME 3 - JUMP_BACKWARD_NO_INTERRUPT 5 (to L15) + JUMP_BACKWARD_NO_INTERRUPT 6 (to L15) L18: CLEANUP_THROW L19: END_SEND TO_BOOL - POP_JUMP_IF_TRUE 2 (to L22) - L20: NOT_TAKEN - L21: RERAISE 2 - L22: POP_TOP - L23: POP_EXCEPT + POP_JUMP_IF_TRUE 2 (to L20) + NOT_TAKEN + RERAISE 2 + L20: POP_TOP + L21: POP_EXCEPT POP_TOP POP_TOP POP_TOP - JUMP_FORWARD 3 (to L25) + JUMP_FORWARD 3 (to L23) - -- L24: COPY 3 + -- L22: COPY 3 POP_EXCEPT RERAISE 1 - 5 L25: NOP + 5 L23: NOP - 10 L26: LOAD_GLOBAL 4 (self) + 10 L24: LOAD_GLOBAL 4 (self) LOAD_ATTR 13 (fail + NULL|self) LOAD_FAST 0 (stop_exc) FORMAT_SIMPLE - LOAD_CONST 4 (' was suppressed') + LOAD_CONST 3 (' was suppressed') BUILD_STRING 2 CALL 1 POP_TOP - JUMP_FORWARD 45 (to L33) + JUMP_FORWARD 45 (to L31) - -- L27: PUSH_EXC_INFO + -- L25: PUSH_EXC_INFO 7 LOAD_GLOBAL 14 (Exception) CHECK_EXC_MATCH - POP_JUMP_IF_FALSE 32 (to L31) + POP_JUMP_IF_FALSE 32 (to L29) NOT_TAKEN STORE_FAST 1 (ex) - 8 L28: LOAD_GLOBAL 4 (self) + 8 L26: LOAD_GLOBAL 4 (self) LOAD_ATTR 17 (assertIs + NULL|self) LOAD_FAST_LOAD_FAST 16 (ex, stop_exc) CALL 2 POP_TOP - L29: POP_EXCEPT - LOAD_CONST 3 (None) + L27: POP_EXCEPT + LOAD_COMMON_CONSTANT 7 (None) STORE_FAST 1 (ex) DELETE_FAST 1 (ex) - JUMP_FORWARD 8 (to L33) + JUMP_FORWARD 8 (to L31) - -- L30: LOAD_CONST 3 (None) + -- L28: LOAD_COMMON_CONSTANT 7 (None) STORE_FAST 1 (ex) DELETE_FAST 1 (ex) RERAISE 1 - 7 L31: RERAISE 0 + 7 L29: RERAISE 0 - -- L32: COPY 3 + -- L30: COPY 3 POP_EXCEPT RERAISE 1 - 3 L33: LOAD_CONST 3 (None) - LOAD_CONST 3 (None) - LOAD_CONST 3 (None) + 3 L31: LOAD_COMMON_CONSTANT 7 (None) + LOAD_COMMON_CONSTANT 7 (None) + LOAD_COMMON_CONSTANT 7 (None) CALL 3 POP_TOP - JUMP_BACKWARD 188 (to L2) - L34: PUSH_EXC_INFO + JUMP_BACKWARD 192 (to L2) + L32: PUSH_EXC_INFO WITH_EXCEPT_START TO_BOOL - POP_JUMP_IF_TRUE 2 (to L35) + POP_JUMP_IF_TRUE 2 (to L33) NOT_TAKEN RERAISE 2 - L35: POP_TOP - L36: POP_EXCEPT + L33: POP_TOP + L34: POP_EXCEPT POP_TOP POP_TOP POP_TOP - JUMP_BACKWARD 205 (to L2) + JUMP_BACKWARD 209 (to L2) - -- L37: COPY 3 + -- L35: COPY 3 POP_EXCEPT RERAISE 1 - L38: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + L36: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) RERAISE 1 ExceptionTable: - L1 to L3 -> L38 [0] lasti - L3 to L4 -> L34 [3] lasti - L5 to L7 -> L27 [3] - L7 to L8 -> L12 [7] - L8 to L10 -> L27 [3] - L10 to L11 -> L14 [5] lasti - L11 to L12 -> L38 [0] lasti - L12 to L13 -> L27 [3] - L14 to L16 -> L24 [7] lasti - L16 to L17 -> L18 [10] - L17 to L20 -> L24 [7] lasti - L21 to L23 -> L24 [7] lasti - L23 to L25 -> L27 [3] - L26 to L27 -> L34 [3] lasti + L1 to L3 -> L36 [0] lasti + L3 to L4 -> L32 [4] lasti + L5 to L7 -> L25 [4] + L7 to L8 -> L12 [9] + L8 to L10 -> L25 [4] + L10 to L11 -> L14 [6] lasti + L11 to L12 -> L36 [0] lasti + L12 to L13 -> L25 [4] + L14 to L16 -> L22 [8] lasti + L16 to L17 -> L18 [12] + L17 to L21 -> L22 [8] lasti + L21 to L23 -> L25 [4] + L24 to L25 -> L32 [4] lasti + L25 to L26 -> L30 [5] lasti + L26 to L27 -> L28 [5] lasti L27 to L28 -> L32 [4] lasti - L28 to L29 -> L30 [4] lasti - L29 to L30 -> L34 [3] lasti - L30 to L32 -> L32 [4] lasti - L32 to L33 -> L34 [3] lasti - L33 to L34 -> L38 [0] lasti - L34 to L36 -> L37 [5] lasti - L36 to L38 -> L38 [0] lasti + L28 to L30 -> L30 [5] lasti + L30 to L31 -> L32 [4] lasti + L31 to L32 -> L36 [0] lasti + L32 to L34 -> L35 [6] lasti + L34 to L36 -> L36 [0] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__not_chained_compare_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__not_chained_compare_location.snap new file mode 100644 index 00000000000..32292e60cef --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__not_chained_compare_location.snap @@ -0,0 +1,35 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(c):\n return not (b\" \" <= c <= b\"~\")\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-2:34 LOAD_CONST 0 (", line 1>) +1:0-2:34 MAKE_FUNCTION +1:0-2:34 STORE_NAME 0 (f) +1:0-2:34 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:34 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:16-2:20 LOAD_CONST 0 (b' ') +2:24-2:25 LOAD_FAST 0 (c) +2:16-2:33 SWAP 2 +2:16-2:33 COPY 2 +2:16-2:33 COMPARE_OP 42 (<=) +2:16-2:33 COPY 1 +2:16-2:33 TO_BOOL +2:16-2:33 POP_JUMP_IF_FALSE 11 (to L1) +2:16-2:33 NOT_TAKEN +2:16-2:33 POP_TOP +2:29-2:33 LOAD_CONST 1 (b'~') +2:16-2:33 COMPARE_OP 42 (<=) +2:11-2:34 TO_BOOL +2:11-2:34 UNARY_NOT +2:4-2:34 RETURN_VALUE +2:16-2:33 L1: SWAP 2 +2:16-2:33 POP_TOP +2:11-2:34 TO_BOOL +2:11-2:34 UNARY_NOT +2:4-2:34 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__not_compare_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__not_compare_location.snap new file mode 100644 index 00000000000..5b24334db26 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__not_compare_location.snap @@ -0,0 +1,19 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(self, other):\n return not self == other\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-2:28 LOAD_CONST 0 (", line 1>) +1:0-2:28 MAKE_FUNCTION +1:0-2:28 STORE_NAME 0 (f) +1:0-2:28 LOAD_COMMON_CONSTANT 7 (None) +1:0-2:28 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:15-2:19 LOAD_FAST_BORROW_LOAD_FAST_BORROW 1 (self, other) +2:11-2:28 COMPARE_OP 88 (bool(==)) +2:11-2:28 UNARY_NOT +2:4-2:28 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__redundant_nop_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__redundant_nop_location.snap new file mode 100644 index 00000000000..43fbde70607 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__redundant_nop_location.snap @@ -0,0 +1,65 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(x, y, z):\n while x:\n if y:\n pass\n elif z:\n if y < 0:\n return y\n if z:\n y = y + 1\n elif y:\n return 1\n return -1\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-12:13 LOAD_CONST 0 (", line 1>) +1:0-12:13 MAKE_FUNCTION +1:0-12:13 STORE_NAME 0 (f) +1:0-12:13 LOAD_COMMON_CONSTANT 7 (None) +1:0-12:13 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:10-2:11 L1: LOAD_FAST_BORROW 0 (x) +2:10-2:11 TO_BOOL +2:10-2:11 POP_JUMP_IF_FALSE 61 (to L7) +2:10-2:11 NOT_TAKEN + +3:11-3:12 LOAD_FAST_BORROW 1 (y) +3:11-3:12 TO_BOOL +3:11-3:12 POP_JUMP_IF_FALSE 3 (to L2) +3:11-3:12 NOT_TAKEN + +4:12-4:16 JUMP_BACKWARD 18 (to L1) + +5:13-5:14 L2: LOAD_FAST_BORROW 2 (z) +5:13-5:14 TO_BOOL +5:13-5:14 POP_JUMP_IF_FALSE 31 (to L5) +5:13-5:14 NOT_TAKEN + +6:15-6:16 LOAD_FAST_BORROW 1 (y) +6:19-6:20 LOAD_SMALL_INT 0 +6:15-6:20 COMPARE_OP 18 (bool(<)) +6:15-6:20 POP_JUMP_IF_FALSE 3 (to L3) +6:15-6:20 NOT_TAKEN + +7:23-7:24 LOAD_FAST_BORROW 1 (y) +7:16-7:24 RETURN_VALUE + +8:15-8:16 L3: LOAD_FAST_BORROW 2 (z) +8:15-8:16 TO_BOOL +8:15-8:16 POP_JUMP_IF_FALSE 12 (to L4) +8:15-8:16 NOT_TAKEN + +9:20-9:21 LOAD_FAST_BORROW 1 (y) +9:24-9:25 LOAD_SMALL_INT 1 +9:20-9:25 BINARY_OP 0 (+) +9:16-9:17 STORE_FAST 1 (y) +9:16-9:17 JUMP_BACKWARD 54 (to L1) + +8:15-8:16 L4: JUMP_BACKWARD 56 (to L1) + +10:13-10:14 L5: LOAD_FAST_BORROW 1 (y) +10:13-10:14 TO_BOOL +10:13-10:14 POP_JUMP_IF_TRUE 3 (to L6) +10:13-10:14 NOT_TAKEN +10:13-10:14 JUMP_BACKWARD 66 (to L1) + +11:19-11:20 L6: LOAD_SMALL_INT 1 +11:19-11:20 RETURN_VALUE + +12:11-12:13 L7: LOAD_COMMON_CONSTANT 11 (-1) +12:4-12:13 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__starred_arg_annotation_unpack_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__starred_arg_annotation_unpack_location.snap new file mode 100644 index 00000000000..4f82d8e7a10 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__starred_arg_annotation_unpack_location.snap @@ -0,0 +1,34 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(*args: *Ts): pass\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-1:23 LOAD_CONST 0 (", line 1>) +1:0-1:23 MAKE_FUNCTION +1:0-1:23 LOAD_CONST 1 (", line 1>) +1:0-1:23 MAKE_FUNCTION +1:0-1:23 SET_FUNCTION_ATTRIBUTE 16 (annotate) +1:0-1:23 STORE_NAME 0 (f) +1:0-1:23 LOAD_COMMON_CONSTANT 7 (None) +1:0-1:23 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 +1:0-1:23 LOAD_FAST_BORROW 0 (format) +1:0-1:23 LOAD_SMALL_INT 2 +1:0-1:23 COMPARE_OP 132 (>) +1:0-1:23 POP_JUMP_IF_FALSE 3 (to L1) +1:0-1:23 NOT_TAKEN +1:0-1:23 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +1:0-1:23 RAISE_VARARGS 1 +1:0-1:23 L1: LOAD_CONST 1 ('args') +1:14-1:16 LOAD_GLOBAL 0 (Ts) +1:0-1:23 UNPACK_SEQUENCE 1 +1:0-1:23 BUILD_MAP 1 +1:0-1:23 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 +1:19-1:23 LOAD_COMMON_CONSTANT 7 (None) +1:19-1:23 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__static_swap_implicit_return_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__static_swap_implicit_return_location.snap new file mode 100644 index 00000000000..33c4cade544 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__static_swap_implicit_return_location.snap @@ -0,0 +1,22 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(a, b):\n a, b = a, b\n b, a = a, b\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-3:15 LOAD_CONST 0 (", line 1>) +1:0-3:15 MAKE_FUNCTION +1:0-3:15 STORE_NAME 0 (f) +1:0-3:15 LOAD_COMMON_CONSTANT 7 (None) +1:0-3:15 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:12 LOAD_FAST_LOAD_FAST 1 (a, b) +2:7-2:8 STORE_FAST_STORE_FAST 16 (b, a) + +3:11-3:12 LOAD_FAST_LOAD_FAST 1 (a, b) +3:7-3:8 STORE_FAST_STORE_FAST 1 (a, b) +3:7-3:8 LOAD_COMMON_CONSTANT 7 (None) +3:7-3:8 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__taken_constant_boolop_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__taken_constant_boolop_location.snap new file mode 100644 index 00000000000..57ce5871085 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__taken_constant_boolop_location.snap @@ -0,0 +1,27 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef and_false(x):\n return False and x\n\ndef or_true(x):\n return True or x\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:22 LOAD_CONST 0 (", line 1>) +1:0-2:22 MAKE_FUNCTION +1:0-2:22 STORE_NAME 0 (and_false) + +4:0-5:20 LOAD_CONST 1 (", line 4>) +4:0-5:20 MAKE_FUNCTION +4:0-5:20 STORE_NAME 1 (or_true) +4:0-5:20 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:20 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:11-2:16 LOAD_COMMON_CONSTANT 10 (False) +2:4-2:22 RETURN_VALUE + +Disassembly of ", line 4>: +4:0-4:0 RESUME 0 + +5:11-5:15 LOAD_COMMON_CONSTANT 9 (True) +5:4-5:20 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__try_finally_exception_scaffolding_location.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__try_finally_exception_scaffolding_location.snap new file mode 100644 index 00000000000..68303704059 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__try_finally_exception_scaffolding_location.snap @@ -0,0 +1,46 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(self, node):\n self.flag = True\n try:\n self.body(node)\n finally:\n self.flag = False\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-6:25 LOAD_CONST 0 (", line 1>) +1:0-6:25 MAKE_FUNCTION +1:0-6:25 STORE_NAME 0 (f) +1:0-6:25 LOAD_COMMON_CONSTANT 7 (None) +1:0-6:25 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:16-2:20 LOAD_COMMON_CONSTANT 9 (True) +2:4-2:8 LOAD_FAST_BORROW 0 (self) +2:4-2:13 STORE_ATTR 0 (flag) + +3:4-6:25 NOP + +4:8-4:12 L1: LOAD_FAST_BORROW 0 (self) +4:8-4:17 LOAD_ATTR 3 (body + NULL|self) +4:18-4:22 LOAD_FAST_BORROW 1 (node) +4:8-4:23 CALL 1 +4:8-4:23 POP_TOP + +6:20-6:25 L2: LOAD_COMMON_CONSTANT 10 (False) +6:8-6:12 LOAD_FAST_BORROW 0 (self) +6:8-6:17 STORE_ATTR 0 (flag) +6:8-6:17 LOAD_COMMON_CONSTANT 7 (None) +6:8-6:17 RETURN_VALUE + + -- L3: PUSH_EXC_INFO + +6:20-6:25 LOAD_COMMON_CONSTANT 10 (False) +6:8-6:12 LOAD_FAST 0 (self) +6:8-6:17 STORE_ATTR 0 (flag) +6:8-6:17 RERAISE 0 + + -- L4: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L3 [0] + L3 to L4 -> L4 [1] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__type_param_scope_locations.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__type_param_scope_locations.snap new file mode 100644 index 00000000000..9f5ae9dee3e --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__type_param_scope_locations.snap @@ -0,0 +1,66 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ntype BoundGenericAlias[X: int] = set[X]\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-1:39 LOAD_CONST 0 ( at 0xdeadbeef, file "", line 1>) +1:0-1:39 MAKE_FUNCTION +1:0-1:39 PUSH_NULL +1:0-1:39 CALL 0 +1:0-1:39 STORE_NAME 0 (BoundGenericAlias) +1:0-1:39 LOAD_COMMON_CONSTANT 7 (None) +1:0-1:39 RETURN_VALUE + +Disassembly of at 0xdeadbeef, file "", line 1>: + -- MAKE_CELL 0 (X) + +1:0-1:0 RESUME 0 +1:0-1:39 LOAD_CONST 0 ('BoundGenericAlias') +1:23-1:29 LOAD_CONST 1 ('X') +1:26-1:29 LOAD_CONST 2 ((1,)) +1:26-1:29 LOAD_CONST 3 (", line 1>) +1:26-1:29 MAKE_FUNCTION +1:26-1:29 SET_FUNCTION_ATTRIBUTE 1 (defaults) +1:23-1:29 CALL_INTRINSIC_2 2 (INTRINSIC_TYPEVAR_WITH_BOUND) +1:23-1:29 COPY 1 +1:23-1:29 STORE_DEREF 0 (X) +1:23-1:29 BUILD_TUPLE 1 +1:0-1:39 LOAD_CONST 2 ((1,)) +1:0-1:39 LOAD_FAST_BORROW 0 (X) +1:0-1:39 BUILD_TUPLE 1 +1:0-1:39 LOAD_CONST 4 (", line 1>) +1:0-1:39 MAKE_FUNCTION +1:0-1:39 SET_FUNCTION_ATTRIBUTE 8 (closure) +1:0-1:39 SET_FUNCTION_ATTRIBUTE 1 (defaults) +1:0-1:39 BUILD_TUPLE 3 +1:0-1:39 CALL_INTRINSIC_1 11 (INTRINSIC_TYPEALIAS) +1:0-1:39 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 +1:26-1:29 LOAD_FAST_BORROW 0 (.format) +1:26-1:29 LOAD_SMALL_INT 2 +1:26-1:29 COMPARE_OP 132 (>) +1:26-1:29 POP_JUMP_IF_FALSE 3 (to L1) +1:26-1:29 NOT_TAKEN +1:26-1:29 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +1:26-1:29 RAISE_VARARGS 1 +1:26-1:29 L1: LOAD_GLOBAL 0 (int) +1:26-1:29 RETURN_VALUE + +Disassembly of ", line 1>: + -- COPY_FREE_VARS 1 + +1:0-1:0 RESUME 0 +1:0-1:39 LOAD_FAST_BORROW 0 (.format) +1:0-1:39 LOAD_SMALL_INT 2 +1:0-1:39 COMPARE_OP 132 (>) +1:0-1:39 POP_JUMP_IF_FALSE 3 (to L1) +1:0-1:39 NOT_TAKEN +1:0-1:39 LOAD_COMMON_CONSTANT 1 (NotImplementedError) +1:0-1:39 RAISE_VARARGS 1 +1:33-1:36 L1: LOAD_GLOBAL 0 (set) +1:37-1:38 LOAD_DEREF 1 (X) +1:33-1:39 BINARY_OP 26 ([]) +1:0-1:39 RETURN_VALUE diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__with_cleanup_covers_not_taken.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__with_cleanup_covers_not_taken.snap new file mode 100644 index 00000000000..140b01b9bf4 --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__with_cleanup_covers_not_taken.snap @@ -0,0 +1,61 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(c):\n with c:\n x = 1\n y = 2\n\"#, true)" +--- +0:0-1:0 RESUME 0 + +1:0-4:9 LOAD_CONST 0 (", line 1>) +1:0-4:9 MAKE_FUNCTION +1:0-4:9 STORE_NAME 0 (f) +1:0-4:9 LOAD_COMMON_CONSTANT 7 (None) +1:0-4:9 RETURN_VALUE + +Disassembly of ", line 1>: +1:0-1:0 RESUME 0 + +2:9-2:10 LOAD_FAST_BORROW 0 (c) +2:9-2:10 COPY 1 +2:9-2:10 LOAD_SPECIAL 1 (__exit__) +2:9-2:10 SWAP 2 +2:9-2:10 SWAP 3 +2:9-2:10 LOAD_SPECIAL 0 (__enter__) +2:9-2:10 CALL 0 +2:9-2:10 L1: POP_TOP + +3:12-3:13 LOAD_SMALL_INT 1 +3:8-3:9 STORE_FAST 1 (x) + +2:9-2:10 L2: LOAD_COMMON_CONSTANT 7 (None) +2:9-2:10 LOAD_COMMON_CONSTANT 7 (None) +2:9-2:10 LOAD_COMMON_CONSTANT 7 (None) +2:9-2:10 CALL 3 +2:9-2:10 POP_TOP + +4:8-4:9 LOAD_SMALL_INT 2 +4:4-4:5 STORE_FAST 2 (y) +4:4-4:5 LOAD_COMMON_CONSTANT 7 (None) +4:4-4:5 RETURN_VALUE + +2:9-2:10 L3: PUSH_EXC_INFO +2:9-2:10 WITH_EXCEPT_START +2:9-2:10 TO_BOOL +2:9-2:10 POP_JUMP_IF_TRUE 2 (to L4) +2:9-2:10 NOT_TAKEN +2:9-2:10 RERAISE 2 +2:9-2:10 L4: POP_TOP +2:9-2:10 L5: POP_EXCEPT +2:9-2:10 POP_TOP +2:9-2:10 POP_TOP +2:9-2:10 POP_TOP + +4:8-4:9 LOAD_SMALL_INT 2 +4:4-4:5 STORE_FAST 2 (y) +4:4-4:5 LOAD_COMMON_CONSTANT 7 (None) +4:4-4:5 RETURN_VALUE + + -- L6: COPY 3 + -- POP_EXCEPT + -- RERAISE 1 +ExceptionTable: + L1 to L2 -> L3 [2] lasti + L3 to L5 -> L6 [4] lasti diff --git a/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__yield_from_and_await.snap b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__yield_from_and_await.snap new file mode 100644 index 00000000000..9805d8e97df --- /dev/null +++ b/crates/stdlib/src/snapshots/rustpython_stdlib___opcode__tests__yield_from_and_await.snap @@ -0,0 +1,66 @@ +--- +source: crates/stdlib/src/_opcode.rs +expression: "dis(r#\"\ndef f(xs):\n yield from xs\n\nasync def g(xs):\n return await xs\n\"#,\ntrue)" +--- +0:0-1:0 RESUME 0 + +1:0-2:17 LOAD_CONST 0 (", line 1>) +1:0-2:17 MAKE_FUNCTION +1:0-2:17 STORE_NAME 0 (f) + +4:0-5:19 LOAD_CONST 1 (", line 4>) +4:0-5:19 MAKE_FUNCTION +4:0-5:19 STORE_NAME 1 (g) +4:0-5:19 LOAD_COMMON_CONSTANT 7 (None) +4:0-5:19 RETURN_VALUE + +Disassembly of ", line 1>: +1:?-1:? RETURN_GENERATOR +1:?-1:? POP_TOP +1:0-1:0 L1: RESUME 0 + +2:15-2:17 LOAD_FAST 0 (xs) +2:4-2:17 GET_ITER 3 +2:4-2:17 LOAD_COMMON_CONSTANT 7 (None) +2:4-2:17 L2: SEND 4 (to L5) +2:4-2:17 L3: YIELD_VALUE 1 +2:4-2:17 L4: RESUME 2 +2:4-2:17 JUMP_BACKWARD_NO_INTERRUPT 6 (to L2) +2:4-2:17 L5: END_SEND +2:4-2:17 POP_TOP +2:4-2:17 LOAD_COMMON_CONSTANT 7 (None) +2:4-2:17 RETURN_VALUE +2:4-2:17 L6: CLEANUP_THROW +2:4-2:17 L7: JUMP_BACKWARD_NO_INTERRUPT 6 (to L5) + + -- L8: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L3 -> L8 [0] lasti + L3 to L4 -> L6 [3] + L4 to L7 -> L8 [0] lasti + +Disassembly of ", line 4>: +4:?-4:? RETURN_GENERATOR +4:?-4:? POP_TOP +4:0-4:0 L1: RESUME 0 + +5:17-5:19 LOAD_FAST_BORROW 0 (xs) +5:11-5:19 GET_AWAITABLE 0 +5:11-5:19 PUSH_NULL +5:11-5:19 LOAD_COMMON_CONSTANT 7 (None) +5:11-5:19 L2: SEND 4 (to L5) +5:11-5:19 L3: YIELD_VALUE 1 +5:11-5:19 L4: RESUME 3 +5:11-5:19 JUMP_BACKWARD_NO_INTERRUPT 6 (to L2) +5:11-5:19 L5: END_SEND +5:4-5:19 RETURN_VALUE +5:11-5:19 L6: CLEANUP_THROW +5:11-5:19 L7: JUMP_BACKWARD_NO_INTERRUPT 4 (to L5) + + -- L8: CALL_INTRINSIC_1 3 (INTRINSIC_STOPITERATION_ERROR) + -- RERAISE 1 +ExceptionTable: + L1 to L3 -> L8 [0] lasti + L3 to L4 -> L6 [3] + L4 to L7 -> L8 [0] lasti diff --git a/crates/stdlib/src/socket.rs b/crates/stdlib/src/socket.rs index db22e6a1069..8ddfd9cf4d5 100644 --- a/crates/stdlib/src/socket.rs +++ b/crates/stdlib/src/socket.rs @@ -3,7 +3,14 @@ pub(crate) use _socket::module_def; #[cfg(feature = "ssl")] -pub(super) use _socket::{PySocket, SockWaitKind, sock_wait, timeout_error_msg}; +pub(super) use _socket::{PySocket, timeout_error_msg}; +#[cfg(any( + feature = "__ssl-rustls", + all(feature = "ssl-openssl", not(all(unix, not(target_os = "aix")))) +))] +pub(super) use _socket::{SockWaitKind, sock_wait}; +#[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] +pub(crate) use _socket::{SocketCloseObserver, SocketIdentity}; #[pymodule] mod _socket { @@ -21,12 +28,13 @@ mod _socket { }, convert::{IntoPyException, ToPyObject, TryFromBorrowedObject, TryFromObject}, function::{ - ArgBytesLike, ArgIntoFloat, ArgMemoryBuffer, ArgStrOrBytesLike, Either, FsPath, - FuncArgs, OptionalArg, + ArgBytesLike, ArgIndex, ArgIntoFloat, ArgMemoryBuffer, ArgSpec, ArgStrOrBytesLike, + FsPath, FuncArgs, OptionalArg, }, types::{Constructor, DefaultConstructor, Destructor, Initializer, Representable}, utils::ToCString, }; + use rustpython_common::wtf8::wtf8_concat; use rustpython_host_env::os::ErrorExt; #[cfg(any(unix, windows))] use rustpython_host_env::socket as host_socket; @@ -44,6 +52,10 @@ mod _socket { Ok(()) } + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + use alloc::sync::{Arc, Weak}; + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + use core::sync::atomic::AtomicBool; use core::sync::atomic::{AtomicI32, Ordering}; use core::{ mem::ManuallyDrop, @@ -53,6 +65,8 @@ mod _socket { use crossbeam_utils::atomic::AtomicCell; use host_socket::raw::Socket; use num_traits::ToPrimitive; + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + use std::sync::Mutex; use std::{ ffi, io::{self, Read, Write}, @@ -1048,16 +1062,84 @@ mod _socket { struct SendmsgAfalgArgs { #[pyarg(any, default)] msg: Vec, - #[pyarg(named)] - op: u32, + #[pyarg(named, default)] + op: OptionalArg, #[pyarg(named, default)] iv: Option, #[pyarg(named, default)] - assoclen: OptionalArg, + assoclen: OptionalArg, #[pyarg(named, default)] flags: i32, } + /// A native-only wakeup. Implementations must not execute Python. + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + pub(crate) trait SocketCloseObserver: Send + Sync { + fn socket_closed(&self); + } + + /// Identifies one initialization, even when a later socket reuses its fd. + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + #[derive(Debug, Default)] + pub(crate) struct SocketIdentity { + closed: AtomicBool, + observers: Mutex>>, + } + + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + impl SocketIdentity { + pub(crate) fn is_closed(&self) -> bool { + self.closed.load(Ordering::Acquire) + } + + /// Register atomically with the closed check, so close-before-wait + /// cannot lose a wakeup. The caller retains the strong observer. + pub(crate) fn subscribe(&self, observer: Arc) -> bool { + let mut observers = self.observers.lock().unwrap(); + if self.is_closed() { + return false; + } + observers.retain(|observer| observer.strong_count() != 0); + let observer = Arc::downgrade(&observer); + if !observers.iter().any(|current| current.ptr_eq(&observer)) { + observers.push(observer); + } + true + } + + pub(crate) fn unsubscribe(&self, observer: Arc) { + let observer = Arc::downgrade(&observer); + self.observers + .lock() + .unwrap() + .retain(|current| !current.ptr_eq(&observer)); + } + + // The socket write lock is held by the caller. Return weak observers + // rather than invoking them while either lock is held. + fn invalidate(&self) -> Vec> { + let mut observers = self.observers.lock().unwrap(); + self.closed.store(true, Ordering::Release); + core::mem::take(&mut *observers) + } + + fn notify_closed(observers: Vec>) { + for observer in observers { + if let Some(observer) = observer.upgrade() { + observer.socket_closed(); + } + } + } + } + + #[derive(FromArgs)] + struct SendArgs { + #[pyarg(positional)] + data: ArgBytesLike, + #[pyarg(positional, default)] + flags: i32, + } + #[pyattr(name = "socket")] #[pyattr(name = "SocketType")] #[pyclass(name = "socket")] @@ -1071,6 +1153,10 @@ mod _socket { proto: AtomicI32, pub(crate) timeout: AtomicCell, sock: PyRwLock>, + // Shared access takes `sock` first, in socket -> identity-slot order. + // Ordinary sockets never allocate an identity or observer list. + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + ssl_identity: Mutex>>, } const _: () = assert!(core::mem::size_of::>() == core::mem::size_of::()); @@ -1083,6 +1169,19 @@ mod _socket { proto: AtomicI32::new(0), timeout: AtomicCell::new(-1.0), sock: PyRwLock::new(None), + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + ssl_identity: Mutex::new(None), + } + } + } + + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + impl Drop for PySocket { + fn drop(&mut self) { + // Rust destruction must also notify when Python __del__ did not run. + // Keep ordinary socket destruction free of additional locking. + if self.ssl_identity.get_mut().unwrap().is_some() { + drop(self.take_sock()); } } } @@ -1119,6 +1218,64 @@ mod _socket { .ok_or_else(|| io::Error::from_raw_os_error(CLOSED_ERR)) } + /// Capture the current initialization under the socket read lock. + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + pub(crate) fn ssl_identity(&self) -> io::Result> { + let _sock = self.sock()?; + let mut identity = self.ssl_identity.lock().unwrap(); + Ok(identity + .get_or_insert_with(|| Arc::new(SocketIdentity::default())) + .clone()) + } + + /// Hold this guard only around a truly nonblocking transport syscall, + /// never around SSL processing, Python callbacks, or readiness waits. + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + pub(crate) fn sock_for_ssl_identity( + &self, + identity: &Arc, + ) -> io::Result> { + let sock = self.sock()?; + let current = self.ssl_identity.lock().unwrap(); + if !current + .as_ref() + .is_some_and(|current| Arc::ptr_eq(current, identity) && !identity.is_closed()) + { + return Err(io::Error::from_raw_os_error(CLOSED_ERR)); + } + Ok(sock) + } + + // Caller holds the socket write lock. Notifications must be delivered + // only after releasing that lock, including on initialization failure. + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + fn invalidate_ssl_identity_locked(&self) -> Vec> { + self.ssl_identity + .lock() + .unwrap() + .take() + .map_or_else(Vec::new, |identity| identity.invalidate()) + } + + fn take_sock(&self) -> Option { + let mut guard = self.sock.write(); + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + let observers = self.invalidate_ssl_identity_locked(); + let sock = guard.take(); + drop(guard); + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + SocketIdentity::notify_closed(observers); + sock + } + + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + fn invalidate_failed_ssl_init(&self) { + let guard = self.sock.write(); + let observers = self.invalidate_ssl_identity_locked(); + drop(guard); + SocketIdentity::notify_closed(observers); + } + /// Snapshot the inner socket without holding `self.sock` across a syscall. /// /// Blocking accept/recv/send must not keep the RwLock: `close()` needs @@ -1171,7 +1328,18 @@ mod _socket { self.kind.store(masked_kind, Ordering::Relaxed); self.proto.store(proto, Ordering::Relaxed); let mut s = self.sock.write(); - let sock = s.insert(sock); + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + let observers = self.invalidate_ssl_identity_locked(); + let old_socket = s.replace(sock); + // Closing a lingering socket may block. Unlock and wake old SSL + // operations first, including if initialization unwinds. + let mut s = scopeguard::guard(s, move |s| { + drop(s); + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + SocketIdentity::notify_closed(observers); + drop(old_socket); + }); + let sock = s.as_mut().unwrap(); // If SOCK_NONBLOCK is set, use timeout 0 (non-blocking) #[cfg(any( target_os = "android", @@ -1203,9 +1371,10 @@ mod _socket { let timeout = DEFAULT_TIMEOUT.load(); self.timeout.store(timeout); if timeout >= 0.0 { - sock.set_nonblocking(true)?; + sock.set_nonblocking(true) + } else { + Ok(()) } - Ok(()) } /// returns Err(blocking) @@ -1444,6 +1613,14 @@ mod _socket { }) } #[cfg(target_os = "linux")] + c::AF_BLUETOOTH => Ok(extract_bluetooth_address( + addr, + self.proto.load(Ordering::Relaxed), + caller, + vm, + )? + .to_sockaddr()), + #[cfg(target_os = "linux")] c::AF_CAN => { let tuple: PyTupleRef = addr.downcast().map_err(|obj| { vm.new_type_error(format!( @@ -1554,6 +1731,36 @@ mod _socket { ) }) } + #[cfg(any(target_os = "linux", target_os = "android"))] + c::AF_NETLINK => { + let tuple: PyTupleRef = addr.downcast().map_err(|obj| { + vm.new_type_error(format!( + "{caller}(): AF_NETLINK address must be tuple, not {}", + obj.class().name() + )) + })?; + let [pid, groups] = tuple.as_slice() else { + return Err(vm + .new_type_error("AF_NETLINK address must be a pair (pid, groups)") + .into()); + }; + let pid = pid.clone().try_index(vm)?.as_u32_mask(); + let groups = groups.clone().try_index(vm)?.as_u32_mask(); + let mut storage = host_socket::raw::SockAddrStorage::zeroed(); + // SAFETY: SockAddrStorage has sufficient size and alignment for + // sockaddr_nl; all its fields and padding start initialized to zero. + let netlink_addr = unsafe { storage.view_as::() }; + netlink_addr.nl_family = c::AF_NETLINK as c::sa_family_t; + netlink_addr.nl_pid = pid; + netlink_addr.nl_groups = groups; + // SAFETY: The family, address fields, and length describe sockaddr_nl. + Ok(unsafe { + host_socket::raw::SockAddr::new( + storage, + core::mem::size_of::() as c::socklen_t, + ) + }) + } #[cfg(target_os = "linux")] c::AF_ALG => { let tuple: PyTupleRef = addr.downcast().map_err(|obj| { @@ -1682,16 +1889,70 @@ mod _socket { #[cfg(all(unix, not(target_os = "redox")))] #[derive(FromArgs)] - struct SendmsgAddr { + struct SendmsgArgs { + #[pyarg(positional)] + buffers: PyObjectRef, + #[pyarg(positional, default, py_default = "()")] + ancdata: OptionalArg, + #[pyarg(positional, default = 0)] + flags: i32, #[pyarg(positional, optional)] - addr: Option, + address: Option, + } + + struct ReceiveIntoArgs { + buffer: ArgMemoryBuffer, + nbytes: usize, + flags: i32, + } + + impl ReceiveIntoArgs { + fn parse( + args: &FuncArgs, + name: &'static str, + too_small: &'static str, + vm: &VirtualMachine, + ) -> PyResult { + let (buffer, nbytes, flags) = ArgSpec { + fname: name, + keywords: &["buffer", "nbytes", "flags"], + required: 1, + max_positional: 3, + } + .bind(args, vm, |slots| -> PyResult<_> { + let buffer = slots.required_as::(vm)?; + let nbytes = slots.optional_as::(vm)?.unwrap_or(0); + let flags = slots.optional_as::(vm)?.unwrap_or(0); + Ok((buffer, nbytes, flags)) + })?; + let nbytes = usize::try_from(nbytes) + .map_err(|_| vm.new_value_error(format!("negative buffersize in {name}")))?; + let nbytes = if nbytes == 0 { buffer.len() } else { nbytes }; + if nbytes > buffer.len() { + return Err(vm.new_value_error(too_small)); + } + // Keep only the export alive during conversions and I/O, not a + // payload lock: index callbacks may write to this same buffer. + Ok(Self { + buffer, + nbytes, + flags, + }) + } } impl Initializer for PySocket { type Args = SocketInitArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - Self::_init(zelf, args, vm).map_err(|e| e.into_pyexception(vm)) + let result = Self::_init(zelf, args, vm); + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + if result.is_err() { + // _init can fail before reaching init_inner, leaving an older + // raw socket in place but invalidating its SSL initialization. + zelf.invalidate_failed_ssl_init(); + } + result.map_err(|e| e.into_pyexception(vm)) } } @@ -1902,65 +2163,98 @@ mod _socket { zelf: &Py, vm: &VirtualMachine, ) -> Result<(RawSocket, PyObjectRef), IoOrPyException> { + #[cfg(target_os = "linux")] + if zelf.family.load(Ordering::Relaxed) == c::AF_ALG { + // AF_ALG rejects accept when a peer address is requested. + let sock = zelf.sock_op(vm, SockWaitKind::Read, || { + let listener = zelf.sock_snapshot()?; + // SAFETY: The listener is a socket descriptor. Null pointers + // request no peer address, and a successful call returns a + // new descriptor owned by the caller. + let fd = unsafe { + c::accept4( + sock_fileno(&listener), + core::ptr::null_mut(), + core::ptr::null_mut(), + c::SOCK_CLOEXEC, + ) + }; + if fd < 0 { + Err(io::Error::last_os_error()) + } else { + // SAFETY: accept4 returned a new, valid descriptor. + Ok(unsafe { sock_from_raw_unchecked(fd) }) + } + })?; + return Ok((into_sock_fileno(sock), vm.ctx.none())); + } + // Use accept_raw() instead of accept() to avoid socket2's set_common_flags() // which tries to set SO_NOSIGPIPE and fails with EINVAL on Unix domain sockets on macOS let (sock, addr) = zelf.sock_op(vm, SockWaitKind::Read, || { zelf.sock_snapshot()?.accept_raw() })?; + let address = get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm)?; let fd = into_sock_fileno(sock); - Ok(( - fd, - get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm), - )) + Ok((fd, address)) } #[pymethod] fn recv( zelf: &Py, - bufsize: usize, + bufsize: isize, flags: OptionalArg, vm: &VirtualMachine, ) -> Result, IoOrPyException> { let flags = flags.unwrap_or(0); - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(bufsize) - .map_err(|_| vm.no_memory_error())?; + let bufsize = bufsize + .to_usize() + .ok_or_else(|| vm.new_value_error("negative buffersize in recv"))?; + if bufsize == 0 { + return Ok(Vec::new()); + } + let mut buffer = alloc_recv_scratch(bufsize, flags, vm)?; let n = zelf.sock_op(vm, SockWaitKind::Read, || { zelf.sock_snapshot()? - .recv_with_flags(buffer.spare_capacity_mut(), flags) + .recv_with_flags(&mut buffer.spare_capacity_mut()[..bufsize], flags) })?; - unsafe { buffer.set_len(n) }; + // MSG_TRUNC may report the full datagram length, beyond the buffer. + unsafe { buffer.set_len(n.min(bufsize)) }; + buffer.shrink_to_fit(); Ok(buffer) } #[pymethod] fn recv_into( zelf: &Py, - buf: ArgMemoryBuffer, - nbytes: OptionalArg, - flags: OptionalArg, + args: FuncArgs, vm: &VirtualMachine, ) -> Result { - let flags = flags.unwrap_or(0); - - // Handle nbytes parameter - let read_len = if let OptionalArg::Present(nbytes) = nbytes { - let nbytes = nbytes - .to_usize() - .ok_or_else(|| vm.new_value_error("negative buffersize in recv_into"))?; - nbytes.min(buf.len()) - } else { - buf.len() - }; + let ReceiveIntoArgs { + buffer: buf, + nbytes: read_len, + flags, + } = ReceiveIntoArgs::parse( + &args, + "recv_into", + "buffer too small for requested bytes", + vm, + )?; + // Like recv(), an empty receive does not enter the socket wait. + if read_len == 0 { + return Ok(0); + } - let mut scratch = alloc_recv_scratch(read_len, vm)?; + let mut scratch = alloc_recv_scratch(read_len, flags, vm)?; let n = zelf.sock_op(vm, SockWaitKind::Read, || { zelf.sock_snapshot()? .recv_with_flags(&mut scratch.spare_capacity_mut()[..read_len], flags) })?; - unsafe { scratch.set_len(n) }; - buf.borrow_buf_mut()[..n].copy_from_slice(&scratch); + let written = n.min(read_len); + unsafe { scratch.set_len(written) }; + if !zelf.recv_discards_data(flags) { + buf.borrow_buf_mut()[..written].copy_from_slice(&scratch); + } Ok(n) } @@ -1975,65 +2269,57 @@ mod _socket { let bufsize = bufsize .to_usize() .ok_or_else(|| vm.new_value_error("negative buffersize in recvfrom"))?; - let mut buffer = Vec::new(); - buffer - .try_reserve_exact(bufsize) - .map_err(|_| vm.no_memory_error())?; + let mut buffer = alloc_recv_scratch(bufsize, flags, vm)?; let (n, addr) = zelf.sock_op(vm, SockWaitKind::Read, || { zelf.sock_snapshot()? - .recv_from_with_flags(buffer.spare_capacity_mut(), flags) + .recv_from_with_flags(&mut buffer.spare_capacity_mut()[..bufsize], flags) })?; - unsafe { buffer.set_len(n) }; + unsafe { buffer.set_len(n.min(bufsize)) }; + buffer.shrink_to_fit(); Ok(( buffer, - get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm), + get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm)?, )) } #[pymethod] fn recvfrom_into( zelf: &Py, - buf: ArgMemoryBuffer, - nbytes: OptionalArg, - flags: OptionalArg, + args: FuncArgs, vm: &VirtualMachine, ) -> Result<(usize, PyObjectRef), IoOrPyException> { - let read_len = match nbytes { - OptionalArg::Present(i) => { - let i = i.to_usize().ok_or_else(|| { - vm.new_value_error("negative buffersize in recvfrom_into") - })?; - if i > buf.len() { - return Err(vm - .new_value_error("nbytes is greater than the length of the buffer") - .into()); - } - i - } - OptionalArg::Missing => buf.len(), - }; - let flags = flags.unwrap_or(0); - let mut scratch = alloc_recv_scratch(read_len, vm)?; + let ReceiveIntoArgs { + buffer: buf, + nbytes: read_len, + flags, + } = ReceiveIntoArgs::parse( + &args, + "recvfrom_into", + "nbytes is greater than the length of the buffer", + vm, + )?; + let mut scratch = alloc_recv_scratch(read_len, flags, vm)?; let (n, addr) = zelf.sock_op(vm, SockWaitKind::Read, || { zelf.sock_snapshot()? .recv_from_with_flags(&mut scratch.spare_capacity_mut()[..read_len], flags) })?; - unsafe { scratch.set_len(n) }; - buf.borrow_buf_mut()[..n].copy_from_slice(&scratch); + let written = n.min(read_len); + unsafe { scratch.set_len(written) }; + if !zelf.recv_discards_data(flags) { + buf.borrow_buf_mut()[..written].copy_from_slice(&scratch); + } Ok(( n, - get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm), + get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm)?, )) } #[pymethod] fn send( zelf: &Py, - bytes: ArgBytesLike, - flags: OptionalArg, + SendArgs { data: bytes, flags }: SendArgs, vm: &VirtualMachine, ) -> Result { - let flags = flags.unwrap_or(0); let buf = bytes.borrow_buf_unlocked(vm)?; let buf = &*buf; zelf.sock_op(vm, SockWaitKind::Write, || { @@ -2044,12 +2330,9 @@ mod _socket { #[pymethod] fn sendall( zelf: &Py, - bytes: ArgBytesLike, - flags: OptionalArg, + SendArgs { data: bytes, flags }: SendArgs, vm: &VirtualMachine, ) -> Result<(), IoOrPyException> { - let flags = flags.unwrap_or(0); - let timeout = zelf.get_timeout().ok(); let mut deadline = None; @@ -2079,20 +2362,34 @@ mod _socket { .new_type_error("sendto() takes no keyword arguments") .into()); } - let n = args.args.len(); - let (bytes, flags, address) = match n { - 2 => (args.args[0].clone(), 0, args.args[1].clone()), - 3 => { - let flags = args.args[1].try_index(vm)?.try_to_primitive::(vm)?; - (args.args[0].clone(), flags, args.args[2].clone()) - } - _ => { - return Err(vm - .new_type_error(format!("sendto() takes 2 or 3 arguments ({n} given)")) - .into()); - } + // This overload's diagnostic cannot be expressed by the binder's + // ordinary minimum/maximum arity messages. + let nargs = args.args.len(); + if !(2..=3).contains(&nargs) { + return Err(vm + .new_type_error(format!("sendto() takes 2 or 3 arguments ({nargs} given)")) + .into()); + } + #[expect( + clippy::redundant_clone, + reason = "Keep original arguments alive through callbacks and the socket operation" + )] + let (bytes, flags_or_address, address): ( + ArgBytesLike, + PyObjectRef, + OptionalArg, + ) = args.clone().bind_for(vm, "sendto")?; + // Export before converting flags, but defer borrowing its data + // until all Python callbacks, including address conversion, finish. + let (flags, address) = match address { + OptionalArg::Missing => (0, flags_or_address), + OptionalArg::Present(address) => ( + flags_or_address + .try_index(vm)? + .try_to_primitive::(vm)?, + address, + ), }; - let bytes = ArgBytesLike::try_from_object(vm, bytes)?; let addr = zelf.extract_address(address, "sendto", vm)?; let buf = bytes.borrow_buf_unlocked(vm)?; let buf = &*buf; @@ -2103,38 +2400,29 @@ mod _socket { #[cfg(all(unix, not(target_os = "redox")))] #[pymethod] - fn sendmsg( - zelf: &Py, - buffers: PyObjectRef, - ancdata: OptionalArg, - flags: OptionalArg, - addr: SendmsgAddr, - vm: &VirtualMachine, - ) -> PyResult { - let flags = flags.unwrap_or(0); + fn sendmsg(zelf: &Py, args: SendmsgArgs, vm: &VirtualMachine) -> PyResult { + let SendmsgArgs { + buffers, + ancdata, + flags, + address, + } = args; let mut msg = host_socket::raw::MsgHdr::new(); let sockaddr; - if let Some(addr) = addr.addr { + if let Some(addr) = address { sockaddr = zelf .extract_address(addr, "sendmsg", vm) .map_err(|e| e.into_pyexception(vm))?; msg = msg.with_addr(&sockaddr); } - let collect_iterable = - |obj: &PyObject, msg: &'static str| -> PyResult> { - match vm.extract_elements_with(obj, Ok) { - Ok(items) => Ok(items), - Err(e) if e.fast_isinstance(vm.ctx.exceptions.type_error) => { - Err(vm.new_type_error(msg)) - } - Err(e) => Err(e), - } - }; - - let buffer_items = - collect_iterable(&buffers, "sendmsg() argument 1 must be an iterable")?; + let buffer_items = Self::collect_socket_iterable( + &buffers, + "sendmsg() argument 1 must be an iterable", + Some("sendmsg() argument 1 is too long"), + vm, + )?; let buffers = buffer_items .into_iter() .map(|obj| ArgBytesLike::try_from_object(vm, obj)) @@ -2151,21 +2439,15 @@ mod _socket { let control_buf; if let OptionalArg::Present(ancdata) = ancdata { - let cmsg_fast = - collect_iterable(&ancdata, "sendmsg() argument 2 must be an iterable")?; + let cmsg_fast = Self::collect_socket_iterable( + &ancdata, + "sendmsg() argument 2 must be an iterable", + None, + vm, + )?; let cmsgs = cmsg_fast .into_iter() - .map(|item| -> PyResult<(i32, i32, ArgBytesLike)> { - let seq: Vec = item.try_into_value(vm)?; - let [lvl, typ, data]: [PyObjectRef; 3] = seq - .try_into() - .map_err(|_| vm.new_type_error("[sendmsg() ancillary data items]"))?; - Ok(( - lvl.try_index(vm)?.try_to_primitive::(vm)?, - typ.try_index(vm)?.try_to_primitive::(vm)?, - ArgBytesLike::try_from_object(vm, data)?, - )) - }) + .map(|item| Self::parse_sendmsg_cmsg_item(item, vm)) .collect::>>()?; control_buf = Self::pack_cmsgs_to_send(&cmsgs, vm)?; if !control_buf.is_empty() { @@ -2187,33 +2469,57 @@ mod _socket { args: SendmsgAfalgArgs, vm: &VirtualMachine, ) -> PyResult { - use std::os::fd::BorrowedFd; + if zelf.family.load(Ordering::Relaxed) != c::AF_ALG { + return Err(vm.new_os_error("algset is only supported for AF_ALG")); + } - let msg = args.msg; - let op = args.op; - let iv = args.iv; - let flags = args.flags; + let op = match args.op { + OptionalArg::Present(obj) => match obj + .try_index(vm) + .and_then(|i| i.try_to_primitive::(vm)) + { + Ok(op) if op >= 0 => op as u32, + _ => return Err(vm.new_type_error("Invalid or missing argument 'op'")), + }, + OptionalArg::Missing => { + return Err(vm.new_type_error("Invalid or missing argument 'op'")); + } + }; - // Validate assoclen - must be non-negative if provided - let assoclen: Option = match args.assoclen { - OptionalArg::Present(val) if val < 0 => { - return Err(vm.new_type_error("assoclen must be non-negative")); + let assoclen = match args.assoclen { + OptionalArg::Present(obj) => { + let val = obj.try_index(vm)?.try_to_primitive::(vm)?; + if val < 0 { + return Err(vm.new_type_error("assoclen must be positive")); + } + Some(val as u32) } - OptionalArg::Present(val) => Some(val as u32), OptionalArg::Missing => None, }; - let buffers = msg.iter().map(|buf| buf.borrow_buf()).collect::>(); + let flags = args.flags; + let buffers = args + .msg + .iter() + .map(|buf| buf.borrow_buf_unlocked(vm)) + .collect::>>()?; let buffers = buffers .iter() .map(|buf| io::IoSlice::new(buf)) .collect::>(); - let iv = iv.map(|iv| iv.borrow_buf().to_vec()); + let iv = args.iv.map(|iv| iv.borrow_buf().to_vec()); + let control_buf = host_socket::pack_sendmsg_afalg(op, iv.as_deref(), assoclen) + .map_err(|err| err.to_pyexception(vm))?; + + let mut msg = host_socket::raw::MsgHdr::new(); + msg = msg.with_buffers(&buffers); + if !control_buf.is_empty() { + msg = msg.with_control(&control_buf); + } zelf.sock_op(vm, SockWaitKind::Write, || { let sock = zelf.sock_snapshot()?; - let fd = unsafe { BorrowedFd::borrow_raw(sock_fileno(&sock)) }; - host_socket::sendmsg_afalg(fd, &buffers, op, iv.as_deref(), assoclen, flags) + sock.sendmsg(&msg, flags) }) .map_err(|e| e.into_pyexception(vm)) } @@ -2228,18 +2534,14 @@ mod _socket { vm: &VirtualMachine, ) -> PyResult { if bufsize < 0 { - return Err(vm.new_value_error("negative buffer size in recvmsg")); + return Err(vm.new_value_error("negative buffer size in recvmsg()")); } let bufsize = bufsize as usize; - let ancbufsize = ancbufsize.unwrap_or(0); - if ancbufsize < 0 { - return Err(vm.new_value_error("negative ancillary buffer size in recvmsg")); - } - let ancbufsize = ancbufsize as usize; + let ancbufsize = Self::check_ancbufsize(ancbufsize.unwrap_or(0), vm)?; let flags = flags.unwrap_or(0); - let msg = zelf + let mut msg = zelf .sock_op(vm, SockWaitKind::Read, || { let sock = zelf.sock_snapshot()?; let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(sock_fileno(&sock)) }; @@ -2247,19 +2549,15 @@ mod _socket { }) .map_err(|e| e.into_pyexception(vm))?; - // Build ancdata list - let ancdata = Self::parse_ancillary_data(&msg.ancdata, vm); - - // Build address tuple - let address = if let Some(address) = msg.address { - let storage: host_socket::raw::SockAddrStorage = - unsafe { core::mem::transmute(address.storage) }; - let addr = unsafe { host_socket::raw::SockAddr::new(storage, address.len as _) }; - get_addr_tuple(&addr, zelf.proto.load(Ordering::Relaxed), vm) - } else { - vm.ctx.none() - }; + msg.data.shrink_to_fit(); + let (ancdata, address) = Self::recvmsg_ancillary_and_address( + msg.ancdata, + msg.ancdata_status, + msg.address, + zelf.proto.load(Ordering::Relaxed), + vm, + )?; Ok(vm.ctx.new_tuple(vec![ vm.ctx.new_bytes(msg.data).into(), ancdata, @@ -2268,14 +2566,218 @@ mod _socket { ])) } + #[cfg(all(unix, not(target_os = "redox")))] + #[pymethod] + fn recvmsg_into( + zelf: &Py, + buffers: PyObjectRef, + ancbufsize: OptionalArg, + flags: OptionalArg, + vm: &VirtualMachine, + ) -> PyResult { + let buffer_items = Self::collect_socket_iterable( + &buffers, + "recvmsg_into() argument 1 must be an iterable", + Some("recvmsg_into() argument 1 is too long"), + vm, + )?; + let buffers = buffer_items + .iter() + .map(|obj| ArgMemoryBuffer::try_from_object(vm, obj.clone())) + .collect::>>()?; + let ancbufsize = Self::check_ancbufsize(ancbufsize.unwrap_or(0), vm)?; + let flags = flags.unwrap_or(0); + let total = buffers + .iter() + .try_fold(0usize, |sum, buf| sum.checked_add(buf.len())) + .filter(|&total| isize::try_from(total).is_ok()) + .ok_or_else(|| vm.new_overflow_error("recvmsg_into buffers are too large"))?; + let mut scratch = alloc_recv_scratch(total, flags, vm)?; + let msg = zelf + .sock_op(vm, SockWaitKind::Read, || { + let mut remaining = &mut scratch.spare_capacity_mut()[..total]; + let mut slices: Vec<_> = buffers + .iter() + .map(|buf| { + let (part, rest) = + core::mem::take(&mut remaining).split_at_mut(buf.len()); + remaining = rest; + part + }) + .collect(); + let sock = zelf.sock_snapshot()?; + let fd = unsafe { std::os::fd::BorrowedFd::borrow_raw(sock_fileno(&sock)) }; + host_socket::recvmsg_into(fd, &mut slices, ancbufsize, flags) + }) + .map_err(|e| e.into_pyexception(vm))?; + // MSG_TRUNC can report a larger datagram or consume TCP data without + // writing. alloc_recv_scratch initializes that case before the syscall. + unsafe { scratch.set_len(msg.bytes_read.min(total)) }; + if !zelf.recv_discards_data(flags) { + let mut remaining = scratch.as_slice(); + for buffer in &buffers { + let written = remaining.len().min(buffer.len()); + if written == 0 { + continue; + } + buffer.borrow_buf_mut()[..written].copy_from_slice(&remaining[..written]); + remaining = &remaining[written..]; + } + } + let (ancdata, address) = Self::recvmsg_ancillary_and_address( + msg.ancdata, + msg.ancdata_status, + msg.address, + zelf.proto.load(Ordering::Relaxed), + vm, + )?; + Ok(vm.ctx.new_tuple(vec![ + vm.ctx.new_int(msg.bytes_read).into(), + ancdata, + vm.ctx.new_int(msg.msg_flags).into(), + address, + ])) + } + + #[cfg(all(unix, not(target_os = "redox")))] + fn check_ancbufsize(ancbufsize: isize, vm: &VirtualMachine) -> PyResult { + if ancbufsize < 0 || ancbufsize as usize > host_socket::SOCKLEN_T_LIMIT { + Err(vm.new_value_error("invalid ancillary data buffer length")) + } else { + Ok(ancbufsize as usize) + } + } + + #[cfg(all(unix, not(target_os = "redox")))] + fn collect_socket_iterable( + obj: &PyObject, + not_iterable: &'static str, + too_long: Option<&'static str>, + vm: &VirtualMachine, + ) -> PyResult> { + let items = match vm.extract_elements_with(obj, Ok) { + Ok(items) => items, + Err(_) => return Err(vm.new_type_error(not_iterable)), + }; + if let Some(too_long) = too_long + && items.len() > i32::MAX as usize + { + return Err(vm.new_os_error(too_long)); + } + Ok(items) + } + + #[cfg(all(unix, not(target_os = "redox")))] + fn parse_sendmsg_cmsg_item( + item: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<(i32, i32, ArgBytesLike)> { + use crate::vm::builtins::{PyByteArray, PyBytes, PyStr, PyTuple}; + + const FNAME: &str = "[sendmsg() ancillary data items]"; + let type_name = if vm.is_none(&item) { + "None".to_owned() + } else { + item.class().name().to_string() + }; + let bad_type = || { + vm.new_type_error(format!( + "{FNAME}() argument 1 must be 3-item tuple, not {type_name}" + )) + }; + + let (lvl, typ, data) = if let Some(tuple) = item.downcast_ref::() { + if tuple.len() != 3 { + return Err(vm.new_type_error(format!( + "{FNAME}() argument 1 must be tuple of length 3, not {}", + tuple.len() + ))); + } + let slice = tuple.as_slice(); + (slice[0].clone(), slice[1].clone(), slice[2].clone()) + } else if item.downcast_ref::().is_some() + || item.downcast_ref::().is_some() + || item.downcast_ref::().is_some() + { + return Err(bad_type()); + } else { + let seq = vm + .extract_elements_with(&item, Ok) + .map_err(|_| bad_type())?; + if seq.len() != 3 { + return Err(vm.new_type_error(format!( + "{FNAME}() argument 1 must be sequence of length 3, not {}", + seq.len() + ))); + } + (seq[0].clone(), seq[1].clone(), seq[2].clone()) + }; + + Ok(( + lvl.try_index(vm)?.try_to_primitive::(vm)?, + typ.try_index(vm)?.try_to_primitive::(vm)?, + ArgBytesLike::try_from_object(vm, data)?, + )) + } + + #[cfg(all(unix, not(target_os = "redox")))] + fn recvmsg_ancillary_and_address( + ancdata: Vec, + ancdata_status: host_socket::AncillaryDataStatus, + address: Option, + proto: i32, + vm: &VirtualMachine, + ) -> PyResult<(PyObjectRef, PyObjectRef)> { + let list = match Self::parse_ancillary_data(&ancdata, ancdata_status, vm) { + Ok(list) => list, + Err(e) => { + Self::close_ancillary_fds(&ancdata); + return Err(e); + } + }; + let address = if let Some(address) = address { + // SAFETY: `SocketAddressBytes` and `SockAddrStorage` share the + // sockaddr_storage layout filled by recvmsg. + let storage: host_socket::raw::SockAddrStorage = + unsafe { core::mem::transmute(address.storage) }; + // SAFETY: `storage` holds `address.len` bytes of a socket address. + let addr = unsafe { host_socket::raw::SockAddr::new(storage, address.len as _) }; + match get_addr_tuple(&addr, proto, vm) { + Ok(address) => address, + Err(e) => { + Self::close_ancillary_fds(&ancdata); + return Err(e); + } + } + } else { + vm.ctx.none() + }; + Ok((list, address)) + } + /// Parse ancillary data from a received message header #[cfg(all(unix, not(target_os = "redox")))] fn parse_ancillary_data( control: &[host_socket::AncillaryMessage], + status: host_socket::AncillaryDataStatus, vm: &VirtualMachine, - ) -> PyObjectRef { + ) -> PyResult { + let warn_malformed = || { + crate::vm::stdlib::_warnings::warn( + vm.ctx.exceptions.runtime_warning, + "received malformed or improperly-truncated ancillary data", + 1, + vm, + ) + }; let mut result = Vec::new(); - for cmsg in control { + for (i, cmsg) in control.iter().enumerate() { + if status == host_socket::AncillaryDataStatus::Truncated && i + 1 == control.len() { + warn_malformed()?; + } + if cmsg.data.len() > isize::MAX as usize { + return Err(vm.new_os_error("control message too long")); + } let tuple = vm.ctx.new_tuple(vec![ vm.ctx.new_int(cmsg.level).into(), vm.ctx.new_int(cmsg.kind).into(), @@ -2283,8 +2785,32 @@ mod _socket { ]); result.push(tuple.into()); } + if status == host_socket::AncillaryDataStatus::Malformed { + warn_malformed()?; + } + + Ok(vm.ctx.new_list(result).into()) + } - vm.ctx.new_list(result).into() + #[cfg(all(unix, not(target_os = "redox")))] + fn close_ancillary_fds(control: &[host_socket::AncillaryMessage]) { + use std::os::fd::{FromRawFd, OwnedFd}; + for message in control { + if message.level == c::SOL_SOCKET && message.kind == c::SCM_RIGHTS { + for bytes in message + .data + .as_chunks::<{ core::mem::size_of::() }>() + .0 + { + let fd = i32::from_ne_bytes(*bytes); + if fd >= 0 { + // SAFETY: recvmsg transferred these descriptors to + // us, and the failed return has not exposed them. + drop(unsafe { OwnedFd::from_raw_fd(fd) }); + } + } + } + } } // based on nix's implementation @@ -2292,10 +2818,7 @@ mod _socket { fn pack_cmsgs_to_send( cmsgs: &[(i32, i32, ArgBytesLike)], vm: &VirtualMachine, - ) -> PyResult> { - if cmsgs.is_empty() { - return Ok(vec![]); - } + ) -> PyResult { let data = cmsgs .iter() .map(|(lvl, typ, buf)| { @@ -2313,7 +2836,7 @@ mod _socket { #[pymethod] fn close(zelf: &Py) -> io::Result<()> { - let sock = zelf.sock.write().take(); + let sock = zelf.take_sock(); if let Some(sock) = sock { close_inner(into_sock_fileno(sock))?; } @@ -2323,8 +2846,8 @@ mod _socket { #[pymethod] #[inline] fn detach(zelf: &Py) -> i64 { - let sock = zelf.sock.write().take(); - sock.map_or(INVALID_SOCKET as i64, |s| into_sock_fileno(s) as i64) + let sock = zelf.take_sock(); + sock.map_or(-1, |s| into_sock_fileno(s) as i64) } #[pymethod] @@ -2332,29 +2855,35 @@ mod _socket { zelf.sock .read() .as_ref() - .map_or(INVALID_SOCKET as i64, |s| sock_fileno(s) as i64) + .map_or(-1, |s| sock_fileno(s) as i64) } #[pymethod] - fn getsockname(zelf: &Py, vm: &VirtualMachine) -> std::io::Result { + fn getsockname( + zelf: &Py, + vm: &VirtualMachine, + ) -> Result { let addr = zelf.sock()?.local_addr()?; Ok(get_addr_tuple( &addr, zelf.proto.load(Ordering::Relaxed), vm, - )) + )?) } #[pymethod] - fn getpeername(zelf: &Py, vm: &VirtualMachine) -> std::io::Result { + fn getpeername( + zelf: &Py, + vm: &VirtualMachine, + ) -> Result { let addr = zelf.sock()?.peer_addr()?; Ok(get_addr_tuple( &addr, zelf.proto.load(Ordering::Relaxed), vm, - )) + )?) } #[pymethod] @@ -2363,6 +2892,11 @@ mod _socket { if timeout >= 0.0 { Some(timeout) } else { None } } + #[pygetset] + fn timeout(zelf: &Py) -> Option { + Self::gettimeout(zelf) + } + #[pymethod] fn setblocking(zelf: &Py, object: bool) -> io::Result<()> { zelf.timeout.store(if object { -1.0 } else { 0.0 }); @@ -2428,29 +2962,97 @@ mod _socket { #[pymethod] fn setsockopt( zelf: &Py, - level: i32, - name: i32, - value: Option>, - optlen: OptionalArg, + args: FuncArgs, vm: &VirtualMachine, ) -> Result<(), IoOrPyException> { - let sock = zelf.sock()?; - let fd = sock_fileno(&sock); - match (value, optlen) { - (Some(Either::A(b)), OptionalArg::Missing) => { - b.with_ref(|b| host_socket::setsockopt_bytes(fd as _, level, name, b))? + if !args.kwargs.is_empty() { + return Err(vm + .new_type_error("setsockopt() takes no keyword arguments") + .into()); + } + let argc = args.args.len(); + if !(3..=4).contains(&argc) { + let (bound, limit) = if argc < 3 { ("least", 3) } else { ("most", 4) }; + return Err(vm + .new_type_error(format!( + "setsockopt() takes at {bound} {limit} arguments ({argc} given)" + )) + .into()); + } + #[expect( + clippy::redundant_clone, + reason = "Keep original arguments alive through callbacks and the socket operation" + )] + let (level, name, value, optlen): ( + i32, + i32, + Option, + OptionalArg, + ) = args.clone().bind_for(vm, "setsockopt")?; + let optlen = match optlen { + OptionalArg::Present(index) => { + OptionalArg::Present(index.as_unsigned_bitfield::<32>(vm)? as u32) } - (Some(Either::B(val)), OptionalArg::Missing) => { - host_socket::setsockopt_int(fd as _, level, name, val)? + OptionalArg::Missing => OptionalArg::Missing, + }; + enum Value { + Int(i32), + Buffer(ArgBytesLike), + Null(u32), + } + let value = match (value, optlen) { + (Some(value), OptionalArg::Missing) => { + if let Some(index) = value.try_index_opt(vm) { + Value::Int(index?.try_to_primitive::(vm)?) + } else if value.check_buffer() { + let buffer = ArgBytesLike::try_from_object(vm, value)?; + #[cfg(windows)] + if buffer.len() > i32::MAX as usize { + return Err(vm + .new_overflow_error(format!( + "socket option is larger than {} bytes", + i32::MAX + )) + .into()); + } + Value::Buffer(buffer) + } else { + return Err(vm + .new_type_error(wtf8_concat!( + "socket option should be int, bytes-like object or None (got ", + value.class().fully_qualified_name(vm)?, + ")" + )) + .into()); + } } - (None, OptionalArg::Present(optlen)) => { - host_socket::setsockopt_none(fd as _, level, name, optlen)? + (None, OptionalArg::Present(optlen)) => Value::Null(optlen), + (None, OptionalArg::Missing) => { + return Err(vm + .new_type_error( + "setsockopt() requires 4 arguments when the third argument is None", + ) + .into()); } - _ => { + (Some(value), OptionalArg::Present(_)) => { return Err(vm - .new_type_error("expected the value arg xor the optlen arg") + .new_type_error(wtf8_concat!("setsockopt() only takes 4 arguments when the third argument is None (got ", value.class().fully_qualified_name(vm)?, ")")) .into()); } + }; + // Convert Python values before locking the socket; callbacks may close it. + let sock = zelf.sock()?; + let fd = sock_fileno(&sock); + match &value { + Value::Int(value) => { + host_socket::setsockopt_int(fd as _, level, name, *value)?; + } + Value::Buffer(buffer) => { + buffer.with_ref(|b| host_socket::setsockopt_bytes(fd as _, level, name, b))?; + } + Value::Null(optlen) => { + host_socket::setsockopt_none(fd as _, level, name, *optlen)?; + } } Ok(()) } @@ -2627,30 +3229,173 @@ mod _socket { } } + #[cfg(target_os = "linux")] + fn extract_bluetooth_address( + addr: PyObjectRef, + protocol: i32, + caller: &str, + vm: &VirtualMachine, + ) -> PyResult { + use crate::vm::builtins::PyBytes; + use host_socket::bluetooth::{self, Address}; + + let wrong_format = || vm.new_os_error(format!("{caller}(): wrong format")); + let parse_name = |name: &[u8]| { + bluetooth::parse_bdaddr(name).ok_or_else(|| vm.new_os_error("bad bluetooth address")) + }; + if protocol == bluetooth::SCO { + let (name, nul_error) = if let Some(bytes) = addr.downcast_ref::() { + (bytes.as_bytes().to_vec(), "embedded null byte") + } else { + let name: PyStrRef = addr.downcast().map_err(|_| wrong_format())?; + ( + name.try_into_utf8(vm)?.as_str().as_bytes().to_vec(), + "embedded null character", + ) + }; + if name.contains(&0) { + return Err(vm.new_value_error(nul_error)); + } + return Ok(Address::Sco { + bdaddr: parse_name(&name)?, + }); + } + if protocol == bluetooth::HCI + && let Some(index) = addr.try_index_opt(vm) + { + return Ok(Address::Hci { + dev: index?.as_u32_mask() as u16, + channel: 0, + }); + } + let (min, max) = match protocol { + bluetooth::L2CAP => (2, 4), + bluetooth::RFCOMM => (2, 2), + bluetooth::HCI => (1, 2), + _ => return Err(vm.new_os_error(format!("{caller}(): unknown Bluetooth protocol"))), + }; + let tuple: PyTupleRef = addr.downcast().map_err(|_| wrong_format())?; + let fields = tuple.as_slice(); + if !(min..=max).contains(&fields.len()) { + return Err(wrong_format()); + } + // PyArg_ParseTuple's H/B formats mask unsigned values rather than + // rejecting overflow, including values returned by __index__. + let number = |i: usize| -> PyResult { + fields.get(i).map_or(Ok(0), |value| { + value + .try_index(vm) + .map(|n| n.as_u32_mask()) + .map_err(|_| wrong_format()) + }) + }; + if protocol == bluetooth::HCI { + return Ok(Address::Hci { + dev: number(0)? as u16, + channel: number(1)? as u16, + }); + } + let name: PyStrRef = fields[0].clone().downcast().map_err(|_| wrong_format())?; + let name = name.try_into_utf8(vm).map_err(|_| wrong_format())?; + if name.as_str().contains('\0') { + return Err(wrong_format()); + } + let port = number(1)?; + let cid = number(2)? as u16; + let addr_type = number(3)? as u8; + let bdaddr = parse_name(name.as_str().as_bytes())?; + Ok(if protocol == bluetooth::L2CAP { + Address::L2cap { + bdaddr, + psm: port as u16, + cid, + addr_type, + } + } else { + Address::Rfcomm { + bdaddr, + channel: port as u8, + } + }) + } + + #[cfg_attr( + not(unix), + expect( + clippy::unnecessary_wraps, + reason = "Unix filesystem decoding is fallible; keep one return type for shared socket callers" + ) + )] fn get_addr_tuple( addr: &host_socket::raw::SockAddr, - #[cfg_attr(not(target_os = "linux"), allow(unused_variables))] proto: i32, + proto: i32, vm: &VirtualMachine, - ) -> PyObjectRef { - if let Some(addr) = addr.as_socket() { - return get_ip_addr_tuple(&addr, vm); - } + ) -> PyResult { #[cfg(unix)] if addr.is_unix() { use std::os::unix::ffi::OsStrExt; if let Some(abstractpath) = addr.as_abstract_namespace() { - return vm.ctx.new_bytes([b"\0", abstractpath].concat()).into(); + return Ok(vm.ctx.new_bytes([b"\0", abstractpath].concat()).into()); } // necessary on macos let path = ffi::OsStr::as_bytes(addr.as_pathname().unwrap_or_else(|| "".as_ref()).as_ref()); let nul_pos = memchr::memchr(b'\0', path).unwrap_or(path.len()); let path = ffi::OsStr::from_bytes(&path[..nul_pos]); - return vm.fsdecode(path).into(); + return vm.fsdecode(path).map(Into::into); + } + Ok(get_addr_tuple_non_unix(addr, proto, vm)) + } + + fn get_addr_tuple_non_unix( + addr: &host_socket::raw::SockAddr, + #[cfg_attr(not(target_os = "linux"), allow(unused_variables))] proto: i32, + vm: &VirtualMachine, + ) -> PyObjectRef { + if let Some(addr) = addr.as_socket() { + return get_ip_addr_tuple(&addr, vm); + } + #[cfg(any(target_os = "linux", target_os = "android"))] + if addr.family() == c::AF_NETLINK as c::sa_family_t { + // SAFETY: Socket addresses supplied by the OS use sockaddr_nl for AF_NETLINK; + // SockAddr owns storage with the required size and alignment. + let netlink_addr = unsafe { &*addr.as_ptr().cast::() }; + return (netlink_addr.nl_pid, netlink_addr.nl_groups).to_pyobject(vm); } #[cfg(target_os = "linux")] { let family = addr.family(); + if let Some(addr) = host_socket::bluetooth::Address::from_sockaddr(addr, proto) { + use host_socket::bluetooth::{Address, format_bdaddr}; + return match addr { + Address::L2cap { + bdaddr, + psm, + cid, + addr_type, + } => { + let name = format_bdaddr(bdaddr); + if addr_type != 0 { + (name, psm, cid, addr_type).to_pyobject(vm) + } else if cid != 0 { + (name, psm, cid).to_pyobject(vm) + } else { + (name, psm).to_pyobject(vm) + } + } + Address::Rfcomm { bdaddr, channel } => { + (format_bdaddr(bdaddr), channel).to_pyobject(vm) + } + Address::Hci { dev, channel } => { + if channel == 0 { + dev.to_pyobject(vm) + } else { + (dev, channel).to_pyobject(vm) + } + } + Address::Sco { bdaddr } => format_bdaddr(bdaddr).to_pyobject(vm), + }; + } if family == c::AF_CAN as c::sa_family_t { let can_addr = unsafe { &*(addr.as_ptr() as *const c::sockaddr_can) }; let ifindex = can_addr.can_ifindex; @@ -2736,7 +3481,7 @@ mod _socket { (String::new(), 0).to_pyobject(vm) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn gethostname(vm: &VirtualMachine) -> PyResult { vm.audit("socket.gethostname", || ())?; @@ -2822,14 +3567,42 @@ mod _socket { /// on a lock never reaches a safepoint — holding it across the wait stops /// the world from being stopped at all. The bytes are copied over once /// they have arrived. - fn alloc_recv_scratch(len: usize, vm: &VirtualMachine) -> PyResult> { + fn alloc_recv_scratch(len: usize, flags: i32, vm: &VirtualMachine) -> PyResult> { let mut scratch = Vec::new(); scratch .try_reserve_exact(len) .map_err(|_| vm.no_memory_error())?; + if i64::from(flags) & i64::from(MSG_TRUNC) != 0 { + // Linux TCP can consume bytes without writing them with MSG_TRUNC. + // Keep the initialized storage available to the receive syscall. + scratch.resize(len, 0); + scratch.clear(); + } Ok(scratch) } + impl PySocket { + fn recv_discards_data(&self, flags: i32) -> bool { + // Linux TCP treats MSG_TRUNC as a request to discard data. Do not + // overwrite the caller's buffer, including changes during the wait. + #[cfg(any(target_os = "linux", target_os = "android"))] + { + let family = self.family.load(Ordering::Relaxed); + let proto = self.proto.load(Ordering::Relaxed); + flags & MSG_TRUNC != 0 + && flags & c::MSG_ERRQUEUE == 0 + && self.kind.load(Ordering::Relaxed) == SOCK_STREAM + && (family == AF_INET || family == AF_INET6) + && (proto == 0 || proto == IPPROTO_TCP || proto == c::IPPROTO_MPTCP) + } + #[cfg(not(any(target_os = "linux", target_os = "android")))] + { + let _ = flags; + false + } + } + } + enum IoOrPyException { Timeout, Py(PyBaseExceptionRef), @@ -2878,7 +3651,10 @@ mod _socket { } /// returns Ok(true) on timeout - #[cfg(feature = "ssl")] + #[cfg(any( + feature = "__ssl-rustls", + all(feature = "ssl-openssl", not(all(unix, not(target_os = "aix")))) + ))] pub(crate) fn sock_wait( sock: &Socket, wait_kind: SockWaitKind, @@ -2921,12 +3697,12 @@ mod _socket { #[pyarg(any)] host: Option, #[pyarg(any)] - port: Option>, + port: Option, #[pyarg(any, default = c::AF_UNSPEC)] family: i32, - #[pyarg(any, name = "type", default)] - ty: i32, + #[pyarg(any, default)] + r#type: i32, #[pyarg(any, default)] proto: i32, #[pyarg(any, default)] @@ -2939,23 +3715,15 @@ mod _socket { vm: &VirtualMachine, ) -> Result, IoOrPyException> { let hints = host_socket::dns::AddrInfoHints { - socktype: opts.ty, + socktype: opts.r#type, protocol: opts.proto, address: opts.family, flags: opts.flags, }; - // Encode host: str uses IDNA encoding, bytes must be valid UTF-8 + // Encode non-ASCII hosts with IDNA; bytes must be valid UTF-8. let host_encoded: Option = match opts.host.as_ref() { - Some(ArgStrOrBytesLike::Str(s)) => { - let encoded = - vm.state - .codec_registry - .encode_text(s.to_owned(), "idna", None, vm)?; - let host_str = core::str::from_utf8(encoded.as_bytes()) - .map_err(|_| vm.new_runtime_error("idna output is not utf8"))?; - Some(host_str.to_owned()) - } + Some(ArgStrOrBytesLike::Str(s)) => Some(encode_hostname(s.as_wtf8(), vm)?), Some(ArgStrOrBytesLike::Buf(b)) => { let bytes = b.borrow_buf(); let host_str = core::str::from_utf8(&bytes).map_err(|e| { @@ -2973,10 +3741,23 @@ mod _socket { }; let host = host_encoded.as_deref(); - // Encode port: str/bytes as service name, int as port number - let port_encoded: Option = match opts.port.as_ref() { - Some(Either::A(sb)) => { - let port_str = match sb { + // Check the index protocol before string/bytes conversion, including for + // subclasses, and preserve any exception raised by __index__. + let port_index = opts + .port + .as_ref() + .and_then(|port| port.try_index_opt(vm)) + .transpose()?; + let port_encoded: Option = match (port_index, opts.port.as_ref()) { + (Some(index), _) => Some(crate::vm::builtins::PyInt::repr_str(&index, vm)?), + (None, Some(port)) => { + if !port.fast_isinstance(vm.ctx.types.str_type) + && !port.fast_isinstance(vm.ctx.types.bytes_type) + { + return Err(vm.new_os_error("Int or String expected").into()); + } + let sb = ArgStrOrBytesLike::try_from_object(vm, port.clone())?; + let port_str = match &sb { ArgStrOrBytesLike::Str(s) => { // For str, check for surrogates and raise UnicodeEncodeError if found s.to_str() @@ -3014,8 +3795,7 @@ mod _socket { }; Some(port_str) } - Some(Either::B(i)) => Some(i.to_string()), - None => None, + (None, None) => None, }; let port = port_encoded.as_deref(); @@ -3029,7 +3809,7 @@ mod _socket { ai.address, ai.socktype, ai.protocol, - ai.canonname, + ai.canonname.unwrap_or_default(), get_ip_addr_tuple(&ai.sockaddr, vm), )) .into() @@ -3218,10 +3998,12 @@ mod _socket { #[cfg(not(target_os = "redox"))] #[pyfunction] - fn if_indextoname(if_index: IfIndex, vm: &VirtualMachine) -> PyResult { + fn if_indextoname(if_index: IfIndex, vm: &VirtualMachine) -> PyResult { #[cfg(windows)] { - host_socket::if_indextoname_checked(if_index).map_err(|_| vm.new_last_errno_error()) + host_socket::if_indextoname_checked(if_index) + .map(|name| vm.ctx.new_str(name)) + .map_err(|_| vm.new_last_errno_error()) } #[cfg(not(windows))] { @@ -3232,8 +4014,9 @@ mod _socket { if ret.is_null() { Err(vm.new_last_errno_error()) } else { + use std::os::unix::ffi::OsStrExt; let buf = unsafe { ffi::CStr::from_ptr(buf.as_ptr() as _) }; - Ok(buf.to_string_lossy().into_owned()) + vm.fsdecode(std::ffi::OsStr::from_bytes(buf.to_bytes())) } } } @@ -3249,17 +4032,19 @@ mod _socket { target_os = "netbsd", target_os = "openbsd", ))] - #[pyfunction] + #[pyfunction(signature_from_flags)] fn if_nameindex(vm: &VirtualMachine) -> PyResult> { #[cfg(not(windows))] { - let list = host_socket::if_nameindex() + use std::os::unix::ffi::OsStringExt; + host_socket::if_nameindex_bytes() .map_err(|err| err.into_pyexception(vm))? .into_iter() - .map(|tup| tup.to_pyobject(vm)) - .collect(); - - Ok(list) + .map(|(index, name)| { + let name = vm.fsdecode(std::ffi::OsString::from_vec(name))?; + Ok((index, name).to_pyobject(vm)) + }) + .collect() } #[cfg(windows)] { @@ -3312,7 +4097,7 @@ mod _socket { { return Ok(SocketAddr::V4(net::SocketAddrV4::new(addr, 0))); } - if matches!(af, c::AF_INET | c::AF_UNSPEC) + if matches!(af, c::AF_INET6 | c::AF_UNSPEC) && !name.contains('%') && let Ok(addr) = name.parse::() { @@ -3322,17 +4107,30 @@ mod _socket { address: af, ..Default::default() }; - let name = vm - .state - .codec_registry - .encode_text(pyname.into_wtf8(), "idna", None, vm)?; - let name = core::str::from_utf8(name.as_bytes()) - .map_err(|_| vm.new_runtime_error("idna output is not utf8"))?; - let mut res = host_socket::dns::getaddrinfo(Some(name), None, Some(hints)) + let name = encode_hostname(pyname.as_wtf8(), vm)?; + let mut res = host_socket::dns::getaddrinfo(Some(&name), None, Some(hints)) .map_err(|e| convert_socket_error(vm, e, SocketError::GaiError))?; Ok(res.next().unwrap().map(|ainfo| ainfo.sockaddr)?) } + fn encode_hostname(name: &crate::common::wtf8::Wtf8, vm: &VirtualMachine) -> PyResult { + // Like CPython's idna_converter, ASCII hostnames need no codec lookup. + if let Ok(name) = name.as_str() + && name.is_ascii() + { + return Ok(name.to_owned()); + } + let encoded = vm.state.codec_registry.encode_text( + vm.ctx.new_str(name.to_owned()), + "idna", + None, + vm, + )?; + core::str::from_utf8(encoded.as_bytes()) + .map(str::to_owned) + .map_err(|_| vm.new_runtime_error("idna output is not utf8")) + } + fn sock_from_raw(fileno: RawSocket, vm: &VirtualMachine) -> PyResult { let invalid = cfg_select! { windows => fileno == INVALID_SOCKET, @@ -3381,16 +4179,8 @@ mod _socket { } } - pub(super) const INVALID_SOCKET: RawSocket = { - #[cfg(unix)] - { - -1 - } - #[cfg(windows)] - { - host_socket::INVALID_RAW_SOCKET as RawSocket - } - }; + #[cfg(windows)] + pub(super) const INVALID_SOCKET: RawSocket = host_socket::INVALID_RAW_SOCKET as RawSocket; fn convert_socket_error( vm: &VirtualMachine, @@ -3446,13 +4236,13 @@ mod _socket { static DEFAULT_TIMEOUT: AtomicCell = AtomicCell::new(-1.0); - #[pyfunction] + #[pyfunction(signature_from_flags)] fn getdefaulttimeout() -> Option { let timeout = DEFAULT_TIMEOUT.load(); if timeout >= 0.0 { Some(timeout) } else { None } } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn setdefaulttimeout(object: Option, vm: &VirtualMachine) -> PyResult<()> { let val = match object { Some(t) => { @@ -3471,7 +4261,7 @@ mod _socket { Ok(()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn dup(object: PyObjectRef, vm: &VirtualMachine) -> Result { let sock = get_raw_sock(&object, vm)?; let sock = core::mem::ManuallyDrop::new(sock_from_raw(sock, vm)?); @@ -3482,7 +4272,7 @@ mod _socket { Ok(fd) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn close(object: PyObjectRef, vm: &VirtualMachine) -> Result<(), IoOrPyException> { Ok(close_inner(get_raw_sock(&object, vm)?)?) } @@ -3511,4 +4301,154 @@ mod _socket { host_socket::checked_cmsg_space(length) .ok_or_else(|| vm.new_overflow_error("CMSG_SPACE() argument out of range")) } + + #[cfg(test)] + mod socket_tests { + use super::*; + + #[test] + fn closed_socket_descriptors_are_negative_one() { + let builder = crate::vm::Interpreter::builder(Default::default()); + let defs = crate::stdlib_module_defs(&builder.ctx); + let interp = builder.add_native_modules(&defs).build(); + interp.enter(|vm| { + vm.import("_socket", 0).unwrap(); + let socket = PySocket::default().into_ref(&vm.ctx); + for _ in 0..2 { + assert_eq!(PySocket::fileno(&socket), -1); + assert_eq!(PySocket::detach(&socket), -1); + } + assert_eq!( + PySocket::repr_str(&socket, vm).unwrap(), + "", + ); + }); + } + } + + #[cfg(test)] + mod address_tests { + use super::*; + + #[test] + fn ascii_hosts_do_not_require_idna() { + crate::vm::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for host in ["localhost", "127.0.0.1", "::1", "fe80::1%1"] { + assert_eq!(encode_hostname(host.into(), vm).unwrap(), host); + } + let addr = get_addr(vm, vm.ctx.new_utf8_str("::1"), c::AF_INET6) + .map_err(|err| err.into_pyexception(vm)) + .unwrap(); + assert_eq!(addr.ip(), net::IpAddr::V6(Ipv6Addr::LOCALHOST)); + }); + } + } + + #[cfg(test)] + #[cfg(all(feature = "ssl-openssl", unix, not(target_os = "aix")))] + mod ssl_identity_tests { + use super::{PySocket, SocketCloseObserver, SocketIdentity}; + use alloc::sync::{Arc, Weak}; + use core::sync::atomic::{AtomicUsize, Ordering}; + + struct Observer { + identity: Weak, + notifications: AtomicUsize, + } + + impl Observer { + fn new(identity: &Arc) -> Arc { + Arc::new(Self { + identity: Arc::downgrade(identity), + notifications: AtomicUsize::new(0), + }) + } + } + + impl SocketCloseObserver for Observer { + fn socket_closed(&self) { + if let Some(identity) = self.identity.upgrade() { + assert!(identity.is_closed()); + assert!(identity.observers.try_lock().is_ok()); + } + self.notifications.fetch_add(1, Ordering::Relaxed); + } + } + + #[test] + fn subscribe_before_close_notifies_after_invalidation() { + let identity = Arc::new(SocketIdentity::default()); + let observer = Observer::new(&identity); + assert!(identity.subscribe(observer.clone())); + assert!(identity.subscribe(observer.clone())); + let notifications = identity.invalidate(); + assert!(identity.is_closed()); + assert_eq!(observer.notifications.load(Ordering::Relaxed), 0); + assert_eq!(notifications.len(), 1); + SocketIdentity::notify_closed(notifications); + assert_eq!(observer.notifications.load(Ordering::Relaxed), 1); + assert!(identity.invalidate().is_empty()); + } + + #[test] + fn close_before_subscribe_rejects_registration() { + let identity = Arc::new(SocketIdentity::default()); + SocketIdentity::notify_closed(identity.invalidate()); + let observer = Observer::new(&identity); + assert!(!identity.subscribe(observer.clone())); + assert_eq!(observer.notifications.load(Ordering::Relaxed), 0); + } + + #[test] + fn registrations_do_not_keep_observers_alive() { + let identity = Arc::new(SocketIdentity::default()); + let observer = Observer::new(&identity); + let weak = Arc::downgrade(&observer); + assert!(identity.subscribe(observer.clone())); + drop(observer); + assert!(weak.upgrade().is_none()); + let next = Observer::new(&identity); + assert!(identity.subscribe(next.clone())); + let notifications = identity.invalidate(); + assert_eq!(notifications.len(), 1); + SocketIdentity::notify_closed(notifications); + assert_eq!(next.notifications.load(Ordering::Relaxed), 1); + } + + #[test] + fn uninitialized_socket_keeps_identity_unallocated() { + let socket = PySocket::default(); + assert!(socket.ssl_identity.lock().unwrap().is_none()); + assert!(socket.ssl_identity().is_err()); + assert!(socket.ssl_identity.lock().unwrap().is_none()); + } + + #[test] + fn failed_initialization_and_rust_drop_invalidate_identity() { + // Exercise lifecycle bookkeeping without creating an OS socket. + let socket = PySocket::default(); + let old = Arc::new(SocketIdentity::default()); + let old_observer = Observer::new(&old); + assert!(old.subscribe(old_observer.clone())); + { + let _socket = socket.sock.write(); + *socket.ssl_identity.lock().unwrap() = Some(old.clone()); + } + socket.invalidate_failed_ssl_init(); + assert!(old.is_closed()); + assert_eq!(old_observer.notifications.load(Ordering::Relaxed), 1); + + let new = Arc::new(SocketIdentity::default()); + let new_observer = Observer::new(&new); + assert!(new.subscribe(new_observer.clone())); + { + let _socket = socket.sock.write(); + *socket.ssl_identity.lock().unwrap() = Some(new.clone()); + } + assert!(!new.is_closed()); + drop(socket); + assert!(new.is_closed()); + assert_eq!(new_observer.notifications.load(Ordering::Relaxed), 1); + } + } } diff --git a/crates/stdlib/src/socket_wasm.rs b/crates/stdlib/src/socket_wasm.rs index 1c0d2b1d499..5ac0dc0fde6 100644 --- a/crates/stdlib/src/socket_wasm.rs +++ b/crates/stdlib/src/socket_wasm.rs @@ -143,15 +143,15 @@ mod _socket { } } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn getdefaulttimeout() -> Option { let timeout = f64::from_bits(DEFAULT_TIMEOUT.load(Ordering::Relaxed)); (timeout >= 0.0).then_some(timeout) } - #[pyfunction] - fn setdefaulttimeout(timeout: Option, vm: &VirtualMachine) -> PyResult<()> { - match timeout { + #[pyfunction(signature_from_flags)] + fn setdefaulttimeout(object: Option, vm: &VirtualMachine) -> PyResult<()> { + match object { None => DEFAULT_TIMEOUT.store((-1.0f64).to_bits(), Ordering::Relaxed), Some(value) => { let value = value.into_float(); @@ -167,7 +167,7 @@ mod _socket { Ok(()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn gethostname(vm: &VirtualMachine) -> PyResult { Err(unsupported(vm, "gethostname").into()) } diff --git a/crates/stdlib/src/ssl.rs b/crates/stdlib/src/ssl.rs index 74750cced43..5ccfda5cfa5 100644 --- a/crates/stdlib/src/ssl.rs +++ b/crates/stdlib/src/ssl.rs @@ -1,4 +1,4 @@ -// spell-checker: ignore ssleof aesccm aesgcm capath getblocking setblocking ENDTLS TLSEXT +// spell-checker: ignore ssleof aesccm aesgcm capath getblocking setblocking ENDTLS TLSEXT ktls sigalgs rsae mldsa //! Pure Rust SSL/TLS implementation using rustls //! @@ -64,8 +64,9 @@ mod _ssl { }, convert::IntoPyException, function::{ - ArgBytesLike, ArgMemoryBuffer, Either, FsPath, FuncArgs, OptionalArg, - PyComparisonValue, PySetterValue, + ArgBytesLike, ArgIndex, ArgIntoBool, ArgIntoFloat, ArgMemoryBuffer, + ArgStrOrBytesLike, Either, FsPath, FuncArgs, OptionalArg, PyComparisonValue, + PySetterValue, }, stdlib::_warnings, types::{Comparable, Constructor, Hashable, PyComparisonOp, Representable}, @@ -79,14 +80,14 @@ mod _ssl { // Import error types used in this module (others are exposed via pymodule(with(...))) use super::error::{ - PySSLError, PySSLWantReadError, PySSLWantWriteError, create_ssl_eof_error, + PySSLEOFError, PySSLError, PySSLWantReadError, PySSLWantWriteError, create_ssl_eof_error, create_ssl_want_read_error, create_ssl_want_write_error, create_ssl_zero_return_error, }; use alloc::sync::Arc; use core::{ hash::{Hash, Hasher}, hint::cold_path, - sync::atomic::{AtomicUsize, Ordering}, + sync::atomic::{AtomicBool, AtomicUsize, Ordering}, time::Duration, }; use rustpython_vm::exceptions; @@ -110,8 +111,8 @@ mod _ssl { TlsConnection, }; - /// Caps unsent TLS so BIO writes stay inside asyncio's 64 KiB - /// socket-transport high-water mark when SO_SNDBUF is small. + // Bound rustls' internal staging and nonblocking socket writes. MemoryBIO + // writes drain these chunks into the caller-owned outgoing BIO. const TLS_IO_BUFFER_LIMIT: Option = Some(4 * 1024); // Import certificate operations module @@ -281,6 +282,8 @@ mod _ssl { #[pyattr] const HAS_PSK: bool = false; // PSK not supported in rustls #[pyattr] + const HAS_PSK_TLS13: bool = false; // External PSK callbacks are not supported. + #[pyattr] const HAS_SSLv2: bool = false; #[pyattr] const HAS_SSLv3: bool = false; @@ -325,6 +328,8 @@ mod _ssl { #[pytraverse(skip)] context_identity: Arc<()>, #[pytraverse(skip)] + policy_identity: PyRwLock>, + #[pytraverse(skip)] protocol: i32, #[pytraverse(skip)] check_hostname: PyRwLock, @@ -336,7 +341,7 @@ mod _ssl { verify_flags: PyRwLock, // Rustls configuration (built lazily) #[pytraverse(skip)] - server_config: PyRwLock>, + server_config: PyRwLock, chain::ServerConfig)>>, // Certificate store #[pytraverse(skip)] root_certs: PyRwLock, @@ -380,9 +385,11 @@ mod _ssl { keylog_filename: PyRwLock>, #[pytraverse(skip)] key_log: Arc, - // ECDH curve name for key exchange + // Explicit key exchange groups, shared by set_groups and set_ecdh_curve. #[pytraverse(skip)] - ecdh_curve: PyRwLock>, + kx_groups: PyRwLock>>, + #[pytraverse(skip)] + server_sigalgs: PyRwLock>>, // Certificate statistics for cert_store_stats() #[pytraverse(skip)] ca_cert_count: PyRwLock, // Number of CA certificates @@ -414,7 +421,7 @@ mod _ssl { #[derive(FromArgs)] struct WrapSocketArgs { sock: PyObjectRef, - server_side: bool, + server_side: ArgIntoBool, #[pyarg(any, optional)] server_hostname: Option, #[pyarg(named, optional)] @@ -427,7 +434,7 @@ mod _ssl { struct WrapBioArgs { incoming: PyRef, outgoing: PyRef, - server_side: bool, + server_side: ArgIntoBool, #[pyarg(any, optional)] server_hostname: Option, #[pyarg(named, optional)] @@ -458,18 +465,26 @@ mod _ssl { #[derive(FromArgs)] struct GetCertArgs { - #[pyarg(positional, default)] - der: bool, + #[pyarg(positional, default = ArgIntoBool::FALSE)] + der: ArgIntoBool, } #[derive(FromArgs)] struct GetCaCertsArgs { - #[pyarg(any, default)] - binary_form: bool, + #[pyarg(any, default = ArgIntoBool::FALSE)] + binary_form: ArgIntoBool, } #[pyclass(with(Constructor, Representable), flags(BASETYPE))] impl PySSLContext { + fn invalidate_policy(&self) { + // Old SSLSession configurations must never override later policy. + // Replace the identity after mutation so concurrent snapshots also + // become ineligible for resumption once that mutation completes. + *self.policy_identity.write() = Arc::new(()); + *self.server_config.write() = None; + } + fn warn_deprecated_tls_version(version: i32, vm: &VirtualMachine) -> PyResult<()> { let version_name = match version { PROTO_SSLv3 => Some("SSLv3"), @@ -505,7 +520,7 @@ mod _ssl { capath_state.directories.push(directory); capath_state.cache = None; drop(capath_state); - *self.server_config.write() = None; + self.invalidate_policy(); } fn capath_certificates(&self) -> Arc>> { @@ -562,7 +577,15 @@ mod _ssl { } #[pygetset(setter)] - fn set_check_hostname(zelf: &Py, value: bool) { + fn set_check_hostname( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'check_hostname' cannot be deleted") + })?; + let value = value.into_bool(); *zelf.check_hostname.write() = value; // When check_hostname is enabled, ensure verify_mode is at least CERT_REQUIRED if value { @@ -571,16 +594,28 @@ mod _ssl { *zelf.verify_mode.write() = CERT_REQUIRED; } } + zelf.invalidate_policy(); + Ok(()) } #[pygetset] - fn _host_flags(zelf: &Py) -> i32 { - *zelf.host_flags.read() + fn _host_flags(zelf: &Py) -> u32 { + *zelf.host_flags.read() as u32 } #[pygetset(setter)] - fn set__host_flags(zelf: &Py, value: i32) { + fn set__host_flags( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute '_host_flags' cannot be deleted") + })?; + let value = value.as_unsigned_bitfield::<32>(vm)? as i32; *zelf.host_flags.write() = value; + zelf.invalidate_policy(); + Ok(()) } #[pygetset] @@ -589,7 +624,14 @@ mod _ssl { } #[pygetset(setter)] - fn set_verify_mode(zelf: &Py, mode: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_verify_mode( + zelf: &Py, + mode: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let mode = mode.ok_or_else(|| { + vm.new_attribute_error("attribute 'verify_mode' cannot be deleted") + })?; if !(CERT_NONE..=CERT_REQUIRED).contains(&mode) { return Err(vm.new_value_error("invalid verify mode")); } @@ -600,6 +642,7 @@ mod _ssl { )); } *zelf.verify_mode.write() = mode; + zelf.invalidate_policy(); Ok(()) } @@ -614,8 +657,17 @@ mod _ssl { } #[pygetset(setter)] - fn set_verify_flags(zelf: &Py, value: i32) { + fn set_verify_flags( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'verify_flags' cannot be deleted") + })?; *zelf.verify_flags.write() = value; + zelf.invalidate_policy(); + Ok(()) } #[pygetset] @@ -624,8 +676,18 @@ mod _ssl { } #[pygetset(setter)] - fn set_post_handshake_auth(zelf: &Py, value: bool) { + fn set_post_handshake_auth( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'post_handshake_auth' cannot be deleted") + })?; + let value = value.into_bool(); *zelf.post_handshake_auth.write() = value; + zelf.invalidate_policy(); + Ok(()) } #[pygetset] @@ -634,7 +696,14 @@ mod _ssl { } #[pygetset(setter)] - fn set_num_tickets(zelf: &Py, value: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_num_tickets( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'num_tickets' cannot be deleted") + })?; if value < 0 { return Err(vm.new_value_error("num_tickets must be a non-negative integer")); } @@ -644,6 +713,7 @@ mod _ssl { ); } *zelf.num_tickets.write() = value; + zelf.invalidate_policy(); Ok(()) } @@ -653,7 +723,13 @@ mod _ssl { } #[pygetset(setter)] - fn set_options(zelf: &Py, value: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_options( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value + .ok_or_else(|| vm.new_attribute_error("attribute 'options' cannot be deleted"))?; // Validate that the value is non-negative if value < 0 { return Err(vm.new_value_error("options must be non-negative")); @@ -682,6 +758,7 @@ mod _ssl { } *zelf.options.write() = value; + zelf.invalidate_policy(); Ok(()) } @@ -693,7 +770,14 @@ mod _ssl { } #[pygetset(setter)] - fn set_minimum_version(zelf: &Py, value: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_minimum_version( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'minimum_version' cannot be deleted") + })?; // Validate that the value is a valid TLS version constant // Valid values: 0 (default), -2 (MINIMUM_SUPPORTED), -1 (MAXIMUM_SUPPORTED), // or 0x0300-0x0304 (SSLv3-TLSv1.3) @@ -715,6 +799,7 @@ mod _ssl { _ => value, }; *zelf.minimum_version.write() = normalized_value; + zelf.invalidate_policy(); Ok(()) } @@ -726,7 +811,14 @@ mod _ssl { } #[pygetset(setter)] - fn set_maximum_version(zelf: &Py, value: i32, vm: &VirtualMachine) -> PyResult<()> { + fn set_maximum_version( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'maximum_version' cannot be deleted") + })?; // Validate that the value is a valid TLS version constant // Valid values: 0 (default), -2 (MINIMUM_SUPPORTED), -1 (MAXIMUM_SUPPORTED), // or 0x0300-0x0304 (SSLv3-TLSv1.3) @@ -748,6 +840,7 @@ mod _ssl { _ => value, }; *zelf.maximum_version.write() = normalized_value; + zelf.invalidate_policy(); Ok(()) } @@ -788,7 +881,9 @@ mod _ssl { // If failed and callable exists, invoke it and retry // This implements lazy evaluation: callable only invoked if password is actually needed - if result.is_err() + if result + .as_ref() + .is_err_and(|error| !error.is::()) && let Some(callable) = password_callable { // Invoke callable - exceptions propagate naturally @@ -826,6 +921,25 @@ mod _ssl { // Process result let (certs, key) = result.map_err(|e| { + let e = match e.downcast::() { + Ok(error) => { + let filename = if error.key_file { + args.keyfile.as_ref().unwrap_or(&args.certfile) + } else { + &args.certfile + }; + let filename: PyObjectRef = match filename { + Either::A(s) => s.clone().into(), + Either::B(b) => vm.ctx.new_bytes(b.borrow_buf().to_vec()).into(), + }; + let exc = error.error.into_pyexception(vm); + exc.as_object() + .set_attr("filename", filename, vm) + .expect("OSError.filename is writable"); + return exc; + } + Err(error) => error, + }; // Try to downcast to io::Error to preserve errno information if let Ok(io_err) = e.downcast::() { match io_err.kind() { @@ -932,6 +1046,7 @@ mod _ssl { // Add new cert/key pair as tuple cert_keys.push((Arc::new(certified_key), key)); + zelf.invalidate_policy(); Ok(()) } @@ -981,6 +1096,8 @@ mod _ssl { (None, false) }; + // Loaders may partially update trust before returning an error. + let _policy_change = ContextPolicyChange(zelf); // If it's a CRL, just add it (separate lock, no conflict with root_store) if let Some(crl) = crl_opt { zelf.crls.write().push(crl); @@ -1017,7 +1134,7 @@ mod _ssl { if let Some(dir_path) = capath_dir { zelf.add_verify_dir(dir_path); } - *zelf.server_config.write() = None; + zelf.invalidate_policy(); Ok(()) } @@ -1142,6 +1259,7 @@ mod _ssl { _purpose: OptionalArg, vm: &VirtualMachine, ) -> PyResult<()> { + let _policy_change = ContextPolicyChange(zelf); let mut store = zelf.root_certs.write(); #[cfg(windows)] @@ -1179,7 +1297,7 @@ mod _ssl { } drop(store); - *zelf.server_config.write() = None; + zelf.invalidate_policy(); Ok(()) } @@ -1195,6 +1313,7 @@ mod _ssl { alpn_list.push(bytes.borrow_buf().to_vec()); } *zelf.alpn_protocols.write() = alpn_list; + zelf.invalidate_policy(); Ok(()) } @@ -1207,6 +1326,7 @@ mod _ssl { let bytes = protos.borrow_buf(); let alpn_list = parse_length_prefixed_alpn(&bytes, vm)?; *zelf.alpn_protocols.write() = alpn_list; + zelf.invalidate_policy(); Ok(()) } @@ -1234,21 +1354,128 @@ mod _ssl { .upcast() })?; - // TLS 1.3 has a separate OpenSSL setter. Discard whatever this - // cipher string happened to match there, then restore exactly the - // provider defaults in their preference order. + // TLS 1.3 has a separate setter. Preserve its current selection. + let current = zelf.selected_ciphers.read(); selected_ciphers = cipher::restore_default_tls13( selected_ciphers, - CryptoExt::get_ext().default_ciphers_or_provider(), + current + .as_deref() + .unwrap_or_else(|| CryptoExt::get_ext().default_ciphers_or_provider()), ); + drop(current); *zelf.selected_ciphers.write() = Some(selected_ciphers); *zelf.suite_b_kx_groups.write() = suite_b_kx_groups; - *zelf.server_config.write() = None; + zelf.invalidate_policy(); Ok(()) } + #[pymethod] + fn set_ciphersuites( + zelf: &Py, + ciphersuites: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let list = ciphersuites.as_str(); + if list.contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + let mut selected = Vec::new(); + for name in list.split(':') { + if let Some(suite) = CryptoExt::get_ext() + .all_ciphers_or_default() + .iter() + .find(|suite| suite.tls13().is_some() && cipher::describe(suite).name == name) + && !selected.contains(suite) + { + selected.push(*suite); + } + } + if selected.is_empty() && !list.is_empty() { + return Err(vm + .new_os_subtype_error( + PySSLError::class(&vm.ctx).to_owned(), + None, + "No cipher suite can be selected.".to_owned(), + ) + .upcast()); + } + let mut current = zelf.selected_ciphers.write(); + selected.extend( + current + .as_deref() + .unwrap_or_else(|| CryptoExt::get_ext().default_ciphers_or_provider()) + .iter() + .filter(|suite| suite.tls13().is_none()) + .copied(), + ); + *current = Some(selected); + zelf.invalidate_policy(); + Ok(()) + } + + #[pymethod] + fn set_groups( + zelf: &Py, + grouplist: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let list = grouplist.as_str(); + if list.contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + let mut groups: Vec<&'static dyn SupportedKxGroup> = Vec::new(); + if !list.is_empty() { + for name in list.split(':') { + let (name, optional) = + name.strip_prefix('?').map_or((name, false), |n| (n, true)); + match cipher::kx_group_by_openssl_name(name) { + Some(group) if !groups.iter().any(|g| g.name() == group.name()) => { + groups.push(group) + } + Some(_) => {} + None if optional => {} + None => { + return Err(vm + .new_os_subtype_error( + PySSLError::class(&vm.ctx).to_owned(), + None, + "unrecognized group".to_owned(), + ) + .upcast()); + } + } + } + } + *zelf.kx_groups.write() = Some(groups); + zelf.invalidate_policy(); + Ok(()) + } + + #[pymethod] + fn set_server_sigalgs( + zelf: &Py, + sigalgslist: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let list = sigalgslist.as_str(); + if list.contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + let schemes = rustpython_host_env::ssl::sigalg::parse_list(list).map_err(|error| { + vm.new_os_subtype_error( + PySSLError::class(&vm.ctx).to_owned(), + None, + error.to_owned(), + ) + .upcast() + })?; + *zelf.server_sigalgs.write() = Some(schemes); + zelf.invalidate_policy(); + Ok(()) + } + #[pymethod] fn get_ciphers(zelf: &Py, vm: &VirtualMachine) -> PyListRef { // What the last `set_ciphers` selected, or the provider defaults @@ -1340,9 +1567,12 @@ mod _ssl { #[pygetset(setter)] fn set_sni_callback( zelf: &Py, - callback: Option, + callback: PySetterValue>, vm: &VirtualMachine, ) -> PyResult<()> { + let callback = callback.ok_or_else(|| { + vm.new_attribute_error("attribute 'sni_callback' cannot be deleted") + })?; // Validate callback is callable or None if let Some(ref cb) = callback && !cb.is(vm.ctx.types.none_type) @@ -1361,7 +1591,7 @@ mod _ssl { vm: &VirtualMachine, ) -> PyResult<()> { // Alias for set_sni_callback - Self::set_sni_callback(zelf, callback, vm) + Self::set_sni_callback(zelf, PySetterValue::Assign(callback), vm) } #[pygetset] @@ -1411,17 +1641,19 @@ mod _ssl { let _ = exc.as_object().set_attr("filename", value.clone(), vm); exc })?; - let old_filename = zelf.keylog_filename.write().replace(value); - drop(old_filename); + let _old_filename = zelf.keylog_filename.write().replace(value); Ok(()) } #[pygetset(setter)] fn set__msg_callback( zelf: &Py, - callback: Option, + callback: PySetterValue>, vm: &VirtualMachine, ) -> PyResult<()> { + let callback = callback.ok_or_else(|| { + vm.new_attribute_error("attribute '_msg_callback' cannot be deleted") + })?; // Validate callback is callable or None if let Some(ref cb) = callback && !cb.is(vm.ctx.types.none_type) @@ -1439,7 +1671,7 @@ mod _ssl { args: GetCaCertsArgs, vm: &VirtualMachine, ) -> PyResult { - let binary_form = args.binary_form; + let binary_form = args.binary_form.into_bool(); let ca_certs_der = zelf.ca_certs_der.read(); let mut certs = Vec::new(); @@ -1484,6 +1716,8 @@ mod _ssl { path: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { + // Py_fopen audits before filesystem conversion or opening. + vm.audit("open", || (path.clone(), "rb", 0))?; // Validate filepath is not None if vm.is_none(&path) { return Err(vm.new_type_error("DH params filepath cannot be None")); @@ -1556,11 +1790,10 @@ mod _ssl { return Err(vm.new_type_error("ECDH curve name must be str or bytes")); }; - curve_name_to_kx_group(&curve_name).map_err(|error| vm.new_value_error(error))?; - - // Store the curve name to be used during handshake - // This will limit the key exchange groups offered/accepted - *zelf.ecdh_curve.write() = Some(curve_name); + let groups = + curve_name_to_kx_group(&curve_name).map_err(|error| vm.new_value_error(error))?; + *zelf.kx_groups.write() = Some(groups); + zelf.invalidate_policy(); Ok(()) } @@ -1570,6 +1803,7 @@ mod _ssl { args: WrapSocketArgs, vm: &VirtualMachine, ) -> PyResult> { + let server_side = args.server_side.into_bool(); let socket_mod = vm.import("socket", 0)?; let socket_class = socket_mod.get_attr("socket", vm)?; @@ -1585,7 +1819,7 @@ mod _ssl { }; // Validate socket type and context protocol - if args.server_side && zelf.protocol == PROTOCOL_TLS_CLIENT { + if server_side && zelf.protocol == PROTOCOL_TLS_CLIENT { return Err(vm .new_os_subtype_error( PySSLError::class(&vm.ctx).to_owned(), @@ -1594,7 +1828,7 @@ mod _ssl { ) .upcast()); } - if !args.server_side && zelf.protocol == PROTOCOL_TLS_SERVER { + if !server_side && zelf.protocol == PROTOCOL_TLS_SERVER { return Err(vm .new_os_subtype_error( PySSLError::class(&vm.ctx).to_owned(), @@ -1614,10 +1848,11 @@ mod _ssl { record_cursor: PyMutex::new(RecordCursor::default()), key_log: Arc::new(super::keylog::ConnectionKeyLog::new(zelf.key_log.clone())), context: PyRwLock::new(zelf), - server_side: args.server_side, + server_side, server_hostname: PyRwLock::new(hostname), connection: PyMutex::new(None), - state: PyMutex::new(TlsState::new(args.server_side)), + state: PyMutex::new(TlsState::new(server_side)), + got_eof_error: AtomicBool::new(false), session_was_reused: PyMutex::new(false), owner: PyRwLock::new(args.owner.map(|o| o.downgrade(None, vm)).transpose()?), session: PyRwLock::new(None), @@ -1639,7 +1874,7 @@ mod _ssl { if let Some(session) = args.session && !vm.is_none(&session) { - PySSLSocket::set_session(&ssl_socket_ref, session, vm)?; + PySSLSocket::set_session(&ssl_socket_ref, PySetterValue::Assign(session), vm)?; } Ok(ssl_socket_ref) @@ -1662,7 +1897,7 @@ mod _ssl { None => None, }; - let server_side = args.server_side; + let server_side = args.server_side.into_bool(); // Validate socket type and context protocol if server_side && zelf.protocol == PROTOCOL_TLS_CLIENT { @@ -1698,6 +1933,7 @@ mod _ssl { server_hostname: PyRwLock::new(hostname), connection: PyMutex::new(None), state: PyMutex::new(TlsState::new(server_side)), + got_eof_error: AtomicBool::new(false), session_was_reused: PyMutex::new(false), owner: PyRwLock::new(args.owner.map(|o| o.downgrade(None, vm)).transpose()?), session: PyRwLock::new(None), @@ -1718,7 +1954,7 @@ mod _ssl { if let Some(session) = args.session && !vm.is_none(&session) { - PySSLSocket::set_session(&ssl_socket_ref, session, vm)?; + PySSLSocket::set_session(&ssl_socket_ref, PySetterValue::Assign(session), vm)?; } Ok(ssl_socket_ref) @@ -1983,6 +2219,7 @@ mod _ssl { let shared_session_cache = Arc::new(ParkingRwLock::new(HashMap::new())); Ok(Self { context_identity: Arc::new(()), + policy_identity: PyRwLock::new(Arc::new(())), protocol, check_hostname: PyRwLock::new(protocol == PROTOCOL_TLS_CLIENT), host_flags: PyRwLock::new(0), @@ -2004,7 +2241,8 @@ mod _ssl { msg_callback: PyRwLock::new(None), keylog_filename: PyRwLock::new(None), key_log: Arc::new(super::keylog::KeyLog::default()), - ecdh_curve: PyRwLock::new(None), + kx_groups: PyRwLock::new(None), + server_sigalgs: PyRwLock::new(None), ca_cert_count: PyRwLock::new(0), x509_cert_count: PyRwLock::new(0), // Use the shared cache created above @@ -2084,6 +2322,23 @@ mod _ssl { } } + // Trust loaders can mutate before a later input fails, so invalidate on + // both successful and exceptional exits, after their write locks drop. + struct ContextPolicyChange<'a>(&'a PySSLContext); + + impl Drop for ContextPolicyChange<'_> { + fn drop(&mut self) { + self.0.invalidate_policy(); + } + } + + #[derive(Debug)] + struct ClientConfigSnapshot { + config: Arc, + context_identity: Arc<()>, + policy_identity: Arc<()>, + } + // SSLSocket - represents a TLS-wrapped socket #[pyattr] #[pyclass(name = "_SSLSocket", module = "_ssl", traverse)] @@ -2107,6 +2362,8 @@ mod _ssl { connection: PyMutex>, // Includes the saved exception while a rejected handshake sends its alert. state: PyMutex, + #[pytraverse(skip)] + got_eof_error: AtomicBool, // Session was reused (for session resumption tracking) #[pytraverse(skip)] session_was_reused: PyMutex, @@ -2117,7 +2374,7 @@ mod _ssl { // Client configuration used by this connection. Retained so the resulting // SSLSession can reuse the same verifier and client credentials. #[pytraverse(skip)] - client_config: PyRwLock>>, + client_config: PyRwLock>, #[pytraverse(skip)] chain_builder: PyRwLock>>, #[pytraverse(skip)] @@ -2144,6 +2401,19 @@ mod _ssl { #[pyclass(with(Constructor, Representable), flags(BASETYPE))] impl PySSLSocket { + // Call only for transport/protocol failures. User message callbacks + // may raise SSLEOFError without closing the connection. + fn remember_eof( + &self, + error: PyBaseExceptionRef, + vm: &VirtualMachine, + ) -> PyBaseExceptionRef { + if error.fast_isinstance(PySSLEOFError::class(&vm.ctx)) { + self.got_eof_error.store(true, Ordering::Relaxed); + } + error + } + // Check if this is BIO mode pub(crate) fn is_bio_mode(&self) -> bool { matches!(self.io, SocketOrBio::Bio { .. }) @@ -2164,6 +2434,24 @@ mod _ssl { &self.connection } + pub(crate) fn check_write_state(&self, vm: &VirtualMachine) -> PyResult<()> { + // Application data cannot follow our close_notify. + if matches!( + *self.state.lock(), + TlsState::ShuttingDown | TlsState::ShutDown + ) { + return Err(vm + .new_os_subtype_error( + PySSLError::class(&vm.ctx).to_owned(), + None, + "cannot write after shutdown", + ) + .upcast()); + } + + Ok(()) + } + pub(crate) fn write_buffered_len(&self) -> usize { self.connection .lock() @@ -2275,13 +2563,7 @@ mod _ssl { // Try to get session data from context's session cache // IMPORTANT: Acquire and release locks quickly to avoid deadlock - let (context_identity, session_cache_arc) = { - let context = self.context.read(); - ( - context.context_identity.clone(), - context.client_session_cache.clone(), - ) - }; + let session_cache_arc = self.context.read().client_session_cache.clone(); let cached_session_data = if let Some(ref name) = server_name { let key = name.as_bytes().to_vec(); @@ -2327,7 +2609,7 @@ mod _ssl { _ => return, }; - let Some(client_config) = self.client_config.write().take() else { + let Some(config_snapshot) = self.client_config.write().take() else { return; }; let Some(session_store) = self.client_session_store.write().take() else { @@ -2335,8 +2617,9 @@ mod _ssl { }; let session = PySSLSession { - context_identity, - client_config, + context_identity: config_snapshot.context_identity, + policy_identity: config_snapshot.policy_identity, + client_config: config_snapshot.config, chain_builder: self .chain_builder .read() @@ -2594,15 +2877,21 @@ mod _ssl { Ok(()) })(); *self.state.lock() = TlsState::WaitingForClientHello(acceptor); - read?; + read.map_err(|error| self.remember_eof(error, vm))?; } TlsState::SendingAlert { error } => { - let result = self.flush_pending_tls_output(vm, None); - *self.state.lock() = TlsState::SendingAlert { - error: error.clone(), - }; - result?; - return Err(error); + if let Err(output_error) = self.flush_pending_tls_output(vm, None) { + *self.state.lock() = TlsState::SendingAlert { error }; + return Err(output_error); + } + // Once the alert is sent, do not retain the exception: + // its traceback can point back to this SSL object. + *self.state.lock() = TlsState::Failed; + return Err(self.remember_eof(error, vm)); + } + TlsState::Failed => { + *self.state.lock() = TlsState::Failed; + return Err(self.remember_eof(create_ssl_eof_error(vm).upcast(), vm)); } state @ (TlsState::Handshaking | TlsState::Connected @@ -2784,41 +3073,36 @@ mod _ssl { } /// Helper: Prepare KX groups (ECDH curve) from context settings - fn prepare_kx_groups( - &self, - vm: &VirtualMachine, - ) -> PyResult>> { + fn prepare_kx_groups(&self) -> Option> { let ctx = self.context.read(); - let ecdh_curve = ctx.ecdh_curve.read().clone(); + let kx_groups = ctx.kx_groups.read().clone(); let suite_b_kx_groups = ctx.suite_b_kx_groups.read().clone(); drop(ctx); - if let Some(ref curve_name) = ecdh_curve { - match curve_name_to_kx_group(curve_name) { - Ok(groups) => Ok(Some(groups)), - Err(e) => Err(vm.new_value_error(format!("Failed to set ECDH curve: {e}"))), - } + if kx_groups.is_some() { + kx_groups } else { // A SUITEB* cipher string pins its own groups, and nothing // else asked for a curve. - Ok(suite_b_kx_groups) + suite_b_kx_groups } } /// Helper: Prepare all common protocol settings (versions, KX groups, ciphers, ALPN) - fn prepare_protocol_settings(&self, vm: &VirtualMachine) -> PyResult { + fn prepare_protocol_settings(&self) -> ProtocolSettings { let ctx = self.context.read(); let versions = self.prepare_tls_versions(); - let kx_groups = self.prepare_kx_groups(vm)?; + let kx_groups = self.prepare_kx_groups(); let cipher_suites = ctx.selected_ciphers.read().clone(); let alpn_protocols = ctx.alpn_protocols.read().clone(); - Ok(ProtocolSettings { + ProtocolSettings { versions, kx_groups, cipher_suites, + server_sigalgs: ctx.server_sigalgs.read().clone(), alpn_protocols, - }) + } } /// Initialize server-side TLS connection with configuration @@ -2838,6 +3122,7 @@ mod _ssl { vm: &VirtualMachine, ) -> PyResult<()> { let ctx = self.context.read(); + let policy_identity = ctx.policy_identity.read().clone(); let cert_keys = ctx.cert_keys.read(); if cert_keys.is_empty() { @@ -2855,7 +3140,7 @@ mod _ssl { drop(cert_keys); // Prepare common protocol settings (TLS versions, ECDH curve, cipher suites, ALPN) - let protocol_settings = self.prepare_protocol_settings(vm)?; + let protocol_settings = self.prepare_protocol_settings(); let min_ver = *ctx.minimum_version.read(); // Check if client certificate verification is required @@ -2888,8 +3173,9 @@ mod _ssl { // Certificate selection uses the actual ClientHello after SNI has // selected the context, including multi-certificate configurations. let cert_keys_only = cert_keys_clone.iter().map(|(ck, _)| ck.clone()).collect(); - let cert_resolver: Option> = - Some(Arc::new(MultiCertResolver::new(cert_keys_only))); + let cert_resolver: Option> = Some(Arc::new( + MultiCertResolver::new(cert_keys_only, protocol_settings.server_sigalgs.as_deref()), + )); // Extract cert_chain and private_key from first cert_key // @@ -2935,7 +3221,11 @@ mod _ssl { let cache_server_config = !use_deferred_validation && ctx.capath_state.read().directories.is_empty(); let cached_config_arc = if cache_server_config { - ctx.server_config.read().clone() + ctx.server_config + .read() + .as_ref() + .filter(|(policy, _)| Arc::ptr_eq(policy, &policy_identity)) + .map(|(_, config)| config.clone()) } else { None }; @@ -2944,12 +3234,14 @@ mod _ssl { let (mut config_arc, chain_builder) = if let Some(cached) = cached_config_arc { cached } else { - let config = - create_server_config(config_options).map_err(|e| vm.new_value_error(e))?; + let config = create_server_config(config_options).map_err(|e| { + vm.new_os_subtype_error(PySSLError::class(&vm.ctx).to_owned(), None, e) + .upcast() + })?; if cache_server_config { let ctx = self.context.read(); - *ctx.server_config.write() = Some(config.clone()); + *ctx.server_config.write() = Some((policy_identity, config.clone())); } config @@ -2965,11 +3257,10 @@ mod _ssl { *conn_guard = Some(TlsConnection::new(Connection::Server(conn))); *self.state.lock() = TlsState::Handshaking; } - Err((error, mut alert)) => { - let mut bytes = Vec::new(); - alert - .write_all(&mut bytes) - .map_err(|e| e.into_pyexception(vm))?; + Err((error, alert)) => { + let bytes = + rustpython_host_env::ssl::handshake::initial_handshake_alert(&error, alert) + .map_err(|e| e.into_pyexception(vm))?; self.reject_connection(SslError::from_rustls(error).into_py_err(vm), bytes, vm); self.accept_client_hello(vm)?; } @@ -2980,6 +3271,9 @@ mod _ssl { #[pymethod] fn do_handshake(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + if zelf.got_eof_error.load(Ordering::Relaxed) { + return Err(create_ssl_eof_error(vm).upcast()); + } // Check if handshake already done if zelf.handshake_completed() { return Ok(()); @@ -2998,18 +3292,24 @@ mod _ssl { vm, ) { drop(conn_guard); - if matches!(*zelf.state.lock(), TlsState::SendingAlert { .. }) { + if matches!( + *zelf.state.lock(), + TlsState::SendingAlert { .. } | TlsState::Failed + ) { return Err(error); } zelf.reject_connection(error, super::handshake::sni_alert(40), vm); return zelf.accept_client_hello(vm).map(|_| ()); } } else { - // Client-side connection + // Client-side connection. Capture policy before reading any + // settings; mutations during construction invalidate this snapshot. let ctx = zelf.context.read(); + let policy_identity = ctx.policy_identity.read().clone(); + let has_capath = !ctx.capath_state.read().directories.is_empty(); // Prepare common protocol settings (TLS versions, ECDH curve, cipher suites, ALPN) - let protocol_settings = zelf.prepare_protocol_settings(vm)?; + let protocol_settings = zelf.prepare_protocol_settings(); // Clone values we need before building config let verify_mode = *ctx.verify_mode.read(); @@ -3060,23 +3360,32 @@ mod _ssl { }; let explicit_session = zelf.session.read().clone(); + let explicit_session = explicit_session + .as_ref() + .map(|session| { + let session = session + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("Value is not a SSLSession."))?; + if !Arc::ptr_eq(&session.context_identity, &context_identity) { + return Err( + vm.new_value_error("Session refers to a different SSLContext.") + ); + } + Ok(session) + }) + .transpose()?; + let reusable_session = explicit_session.filter(|session| { + !has_capath + && Arc::ptr_eq(&session.policy_identity, &policy_identity) + && session.server_name.as_ref() == Some(&server_name) + }); let session_store = Arc::new(CapturingClientSessionStore::new(session_cache)); - let (mut config, chain_builder) = if let Some(session) = explicit_session { - let session = session - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("Value is not a SSLSession."))?; - if !Arc::ptr_eq(&session.context_identity, &context_identity) { - return Err( - vm.new_value_error("Session refers to a different SSLContext.") - ); - } - if session.server_name.as_ref() == Some(&server_name) { - session.session_store.transfer_session( - &session_store, - &server_name, - session.kind, - ); - } + let (mut config, chain_builder) = if let Some(session) = reusable_session { + session.session_store.transfer_session( + &session_store, + &server_name, + session.kind, + ); let mut config = (*session.client_config).clone(); config.resumption = rustls::client::Resumption::store(session_store.clone()); @@ -3099,12 +3408,19 @@ mod _ssl { session_store: Some(session_store.clone()), crls: crls_clone, }; - create_client_config(config_options).map_err(|e| vm.new_value_error(e))? + create_client_config(config_options).map_err(|e| { + vm.new_os_subtype_error(PySSLError::class(&vm.ctx).to_owned(), None, e) + .upcast() + })? }; Arc::make_mut(&mut config).key_log = zelf.key_log.clone(); *zelf.chain_builder.write() = Some(chain_builder); - *zelf.client_config.write() = Some(config.clone()); + *zelf.client_config.write() = Some(ClientConfigSnapshot { + config: config.clone(), + context_identity, + policy_identity, + }); *zelf.client_session_store.write() = Some(session_store); let mut conn = ClientConnection::new(config, server_name).map_err(|e| { @@ -3131,7 +3447,7 @@ mod _ssl { zelf.reject_connection(error.into_py_err(vm), bytes, vm); return zelf.accept_client_hello(vm).map(|_| ()); } - handshake_result.map_err(|e| e.into_py_err(vm))?; + handshake_result.map_err(|e| zelf.remember_eof(e.into_py_err(vm), vm))?; if let Some(exc) = zelf.take_msg_exc() { return Err(exc); } @@ -3171,6 +3487,10 @@ mod _ssl { } } + if zelf.got_eof_error.load(Ordering::Relaxed) { + return Err(create_ssl_eof_error(vm).upcast()); + } + // return empty bytes immediately for len=0 if len == 0 { return match buffer { @@ -3198,7 +3518,7 @@ mod _ssl { } // Helper function to handle return value based on buffer presence - let return_data = |data: Vec, + let return_data = |mut data: Vec, buffer_arg: &OptionalArg, vm: &VirtualMachine| -> PyResult { @@ -3216,6 +3536,7 @@ mod _ssl { } OptionalArg::Missing => { // Return bytes object + data.shrink_to_fit(); Ok(vm.ctx.new_bytes(data).into()) } } @@ -3242,7 +3563,11 @@ mod _ssl { let mut conn_guard = zelf.connection.lock(); let conn = match conn_guard.as_mut() { Some(conn) => conn, - None => return Err(create_ssl_eof_error(vm).upcast()), + None => { + return Err( + zelf.remember_eof(create_ssl_eof_error(vm).upcast(), vm) + ); + } }; conn.pending_plaintext() }; @@ -3255,7 +3580,7 @@ mod _ssl { } } // EOF occurred in violation of protocol (unexpected closure) - Err(create_ssl_eof_error(vm).upcast()) + Err(zelf.remember_eof(create_ssl_eof_error(vm).upcast(), vm)) } Err(error) if error.is_zero_return() => { // If plaintext is still buffered, return it before clean EOF. @@ -3301,12 +3626,12 @@ mod _ssl { Err(timeout_error_msg(vm, msg).upcast()) } Err(crate::ssl::compat::SslError::Py(e)) => { - // Python exception - pass through - Err(e) + // Exception from a transport operation. + Err(zelf.remember_eof(e, vm)) } Err(e) => { // Other SSL errors - Err(e.into_py_err(vm)) + Err(zelf.remember_eof(e.into_py_err(vm), vm)) } } } @@ -3325,6 +3650,9 @@ mod _ssl { #[pymethod] fn write(zelf: &Py, b: ArgBytesLike, vm: &VirtualMachine) -> PyResult { + if zelf.got_eof_error.load(Ordering::Relaxed) { + return Err(create_ssl_eof_error(vm).upcast()); + } let data_bytes = b.borrow_buf(); let data_len = data_bytes.len(); @@ -3337,19 +3665,7 @@ mod _ssl { Self::do_handshake(zelf, vm)?; } - // Application data cannot follow our close_notify. - if matches!( - *zelf.state.lock(), - TlsState::ShuttingDown | TlsState::ShutDown - ) { - return Err(vm - .new_os_subtype_error( - PySSLError::class(&vm.ctx).to_owned(), - None, - "cannot write after shutdown", - ) - .upcast()); - } + zelf.check_write_state(vm)?; // Call ssl_write (matches CPython's SSL_write_ex loop) let result = crate::ssl::compat::ssl_write(zelf, data_bytes.as_ref(), vm); @@ -3371,7 +3687,7 @@ mod _ssl { Err(crate::ssl::compat::SslError::Timeout(msg)) => { Err(timeout_error_msg(vm, msg).upcast()) } - Err(e) => Err(e.into_py_err(vm)), + Err(e) => Err(zelf.remember_eof(e.into_py_err(vm), vm)), } } @@ -3381,7 +3697,7 @@ mod _ssl { args: GetCertArgs, vm: &VirtualMachine, ) -> PyResult> { - let binary = args.der; + let binary = args.der.into_bool(); // Check if handshake is complete if !zelf.handshake_completed() { @@ -3440,6 +3756,55 @@ mod _ssl { )) } + #[pymethod] + fn group(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + let group = { + let conn_guard = zelf.connection.lock(); + let Some(conn) = conn_guard.as_ref() else { + return Ok(None); + }; + let Some(group) = conn.inner().negotiated_key_exchange_group() else { + return Ok(None); + }; + group.name() + }; + group + .as_str() + .map(|name| Some(name.to_owned())) + .ok_or_else(|| { + vm.new_not_implemented_error(format!( + "The TLS provider has no name for negotiated group {:#06x}", + u16::from(group) + )) + }) + } + + #[pymethod] + fn client_sigalg(_zelf: &Py, vm: &VirtualMachine) -> PyResult> { + Err(vm.new_not_implemented_error( + "Rustls does not expose the selected client authentication signature algorithm", + )) + } + + #[pymethod] + fn server_sigalg(_zelf: &Py, vm: &VirtualMachine) -> PyResult> { + Err(vm.new_not_implemented_error( + "Rustls does not expose the selected server handshake signature algorithm", + )) + } + + #[pymethod] + fn uses_ktls_for_send(_zelf: &Py) -> bool { + // This transport encrypts records in rustls; it never enables kernel TLS. + false + } + + #[pymethod] + fn uses_ktls_for_recv(_zelf: &Py) -> bool { + // This transport decrypts records in rustls; it never enables kernel TLS. + false + } + #[pymethod] fn version(zelf: &Py) -> Option { // Extract cipher suite, releasing lock quickly @@ -3489,7 +3854,13 @@ mod _ssl { } #[pygetset(setter)] - fn set_owner(zelf: &Py, owner: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn set_owner( + zelf: &Py, + owner: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let owner = owner + .ok_or_else(|| vm.new_attribute_error("attribute 'owner' cannot be deleted"))?; *zelf.owner.write() = Some(owner.downgrade(None, vm)?); Ok(()) } @@ -3505,12 +3876,19 @@ mod _ssl { } #[pygetset(setter)] - fn set_context(zelf: &Py, value: PyRef, _vm: &VirtualMachine) { + fn set_context( + zelf: &Py, + value: PySetterValue>, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value + .ok_or_else(|| vm.new_attribute_error("attribute 'context' cannot be deleted"))?; zelf.key_log.set_sink(value.key_log.clone()); // Update context reference immediately // SSL_set_SSL_CTX allows context changes at any time, // even after handshake completion *zelf.context.write() = value; + Ok(()) } #[pygetset] @@ -3521,9 +3899,12 @@ mod _ssl { #[pygetset(setter)] fn set_server_hostname( zelf: &Py, - value: Option, + value: PySetterValue>, vm: &VirtualMachine, ) -> PyResult<()> { + let value = value.ok_or_else(|| { + vm.new_attribute_error("attribute 'server_hostname' cannot be deleted") + })?; // Check if handshake is already done if zelf.handshake_completed() { return Err( @@ -3551,7 +3932,13 @@ mod _ssl { } #[pygetset(setter)] - fn set_session(zelf: &Py, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn set_session( + zelf: &Py, + value: PySetterValue, + vm: &VirtualMachine, + ) -> PyResult<()> { + let value = value + .ok_or_else(|| vm.new_attribute_error("attribute 'session' cannot be deleted"))?; let session = value .downcast_ref::() .ok_or_else(|| vm.new_type_error("Value is not a SSLSession."))?; @@ -4018,6 +4405,7 @@ mod _ssl { #[derive(Debug, PyPayload)] struct PySSLSession { context_identity: Arc<()>, + policy_identity: Arc<()>, client_config: Arc, chain_builder: Arc, session_store: Arc, @@ -4184,15 +4572,36 @@ mod _ssl { tuple.into() } + #[pyfunction] + fn get_sigalgs(vm: &VirtualMachine) -> PyResult { + // These are the TLS schemes advertised by the installed provider, in its + // preference order, rather than certificate signature algorithms. + let names = CryptoExt::get_provider() + .signature_verification_algorithms + .supported_schemes() + .into_iter() + .map(|scheme| { + let name = + rustpython_host_env::ssl::sigalg::scheme_name(scheme).ok_or_else(|| { + vm.new_not_implemented_error(format!( + "The TLS provider uses an unrecognized signature scheme {:#06x}", + u16::from(scheme) + )) + })?; + Ok(vm.ctx.new_str(name).into()) + }) + .collect::>>()?; + Ok(vm.ctx.new_list(names)) + } + #[pyfunction] fn RAND_status() -> i32 { 1 // The configured rustls provider supplies cryptographic randomness. } #[pyfunction] - fn RAND_add(_string: PyObjectRef, _entropy: f64) { + fn RAND_add(_string: ArgStrOrBytesLike, _entropy: ArgIntoFloat) { // No-op: the configured rustls provider handles its own entropy. - // Accept any type (str, bytes, bytearray) } #[pyfunction] @@ -4275,12 +4684,48 @@ mod _ssl { } // Windows-specific certificate store enumeration functions + #[cfg(windows)] + #[derive(FromArgs)] + struct CertificateStoreArgs { + #[pyarg(any)] + store_name: PyObjectRef, + } + + #[cfg(windows)] + impl CertificateStoreArgs { + fn validated_name(self, function: &str, vm: &VirtualMachine) -> PyResult { + // Keep conversion after the complete argument-shape check, including + // unexpected keywords, and before any certificate store is opened. + if self + .store_name + .downcast_ref::() + .is_none() + { + let actual = if vm.is_none(&self.store_name) { + "None".to_owned() + } else { + let name = self.store_name.class().name(); + name[..name.floor_char_boundary(name.len().min(50))].to_owned() + }; + return Err(vm.new_type_error(format!( + "{function}() argument 'store_name' must be str, not {actual}" + ))); + } + let name = PyUtf8StrRef::try_from_object(vm, self.store_name)?; + if name.as_str().contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + Ok(name) + } + } + #[cfg(windows)] #[pyfunction] fn enum_certificates( - store_name: PyUtf8StrRef, + args: CertificateStoreArgs, vm: &VirtualMachine, ) -> PyResult> { + let store_name = args.validated_name("enum_certificates", vm)?; let store_name_str = store_name.as_str(); let certs = rustpython_host_env::cert_store::enum_certificates(store_name_str); if !certs.had_open_store { @@ -4320,7 +4765,8 @@ mod _ssl { #[cfg(windows)] #[pyfunction] - fn enum_crls(store_name: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult> { + fn enum_crls(args: CertificateStoreArgs, vm: &VirtualMachine) -> PyResult> { + let store_name = args.validated_name("enum_crls", vm)?; let store_name_str = store_name.as_str(); let crls = rustpython_host_env::cert_store::enum_crls(store_name_str).map_err(|_| { vm.new_os_error(format!( @@ -4365,6 +4811,12 @@ mod _ssl { } } + #[derive(FromArgs)] + struct CertificatePublicBytesArgs { + #[pyarg(any, default = ENCODING_PEM, py_default = "Encoding.PEM")] + format: i32, + } + #[pyclass( flags(IMMUTABLETYPE, DISALLOW_INSTANTIATION), with(Comparable, Hashable, Representable) @@ -4373,10 +4825,10 @@ mod _ssl { #[pymethod] fn public_bytes( zelf: &Py, - format: OptionalArg, + args: CertificatePublicBytesArgs, vm: &VirtualMachine, ) -> PyResult { - let format = format.unwrap_or(ENCODING_PEM); + let format = args.format; match format { x if x == ENCODING_DER => { diff --git a/crates/stdlib/src/ssl/compat.rs b/crates/stdlib/src/ssl/compat.rs index 09c180bcaab..2b1ae129cb8 100644 --- a/crates/stdlib/src/ssl/compat.rs +++ b/crates/stdlib/src/ssl/compat.rs @@ -140,6 +140,7 @@ impl SslError { match self { Self::Rustls(error) => TlsError::from_rustls(error.clone()).is_eof(), Self::Eof => true, + Self::Io(error) => error.kind() == std::io::ErrorKind::UnexpectedEof, _ => false, } } @@ -743,6 +744,24 @@ pub(super) fn ssl_write( data: &[u8], vm: &VirtualMachine, ) -> SslResult { + if !socket.is_bio_mode() { + return ssl_write_chunk(socket, data, vm); + } + + // MemoryBIO accepts the complete ciphertext. Keep rustls' bounded record + // buffer, but do not expose its internal partial writes to SSLObject users: + // CPython does not enable SSL_MODE_ENABLE_PARTIAL_WRITE. In particular, + // asyncio would otherwise repeatedly copy the remaining plaintext suffix. + let mut written = 0; + while written < data.len() { + // A message callback from the previous chunk can initiate shutdown. + socket.check_write_state(vm).map_err(SslError::Py)?; + written += ssl_write_chunk(socket, &data[written..], vm)?; + } + Ok(written) +} + +fn ssl_write_chunk(socket: &Py, data: &[u8], vm: &VirtualMachine) -> SslResult { if data.is_empty() { return Ok(0); } diff --git a/crates/stdlib/src/ssl/handshake.rs b/crates/stdlib/src/ssl/handshake.rs index 3c40c66367f..1d833ebbc03 100644 --- a/crates/stdlib/src/ssl/handshake.rs +++ b/crates/stdlib/src/ssl/handshake.rs @@ -18,6 +18,7 @@ pub(super) enum TlsState { ShuttingDown, ShutDown, SendingAlert { error: PyBaseExceptionRef }, + Failed, } impl TlsState { @@ -40,6 +41,7 @@ impl fmt::Debug for TlsState { Self::ShuttingDown => "ShuttingDown", Self::ShutDown => "ShutDown", Self::SendingAlert { .. } => "SendingAlert", + Self::Failed => "Failed", }) } } diff --git a/crates/stdlib/src/ssl_wasm.rs b/crates/stdlib/src/ssl_wasm.rs index 21f46586c18..1c57ef9f0f1 100644 --- a/crates/stdlib/src/ssl_wasm.rs +++ b/crates/stdlib/src/ssl_wasm.rs @@ -1,3 +1,5 @@ +// cspell: ignore sigalgs + //! Wasm `_ssl` on the rustls-free `rustpython_host_env::ssl` surface. //! //! MemoryBIO, protocol constants, OID lookup, hostname checks, and ALPN @@ -20,7 +22,10 @@ mod _ssl { AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyBytesRef, PyType, PyUtf8StrRef}, - function::{ArgBytesLike, FuncArgs, OptionalArg, PyComparisonValue, PySetterValue}, + function::{ + ArgBytesLike, ArgIntoBool, ArgIntoFloat, ArgStrOrBytesLike, FuncArgs, OptionalArg, + PyComparisonValue, PySetterValue, + }, stdlib::_warnings, types::{Comparable, Constructor, PyComparisonOp, Representable}, }, @@ -137,6 +142,8 @@ mod _ssl { #[pyattr] const HAS_PSK: bool = false; #[pyattr] + const HAS_PSK_TLS13: bool = false; + #[pyattr] const HAS_SSLv2: bool = false; #[pyattr] const HAS_SSLv3: bool = false; @@ -217,7 +224,8 @@ mod _ssl { } #[pygetset(setter)] - fn set_check_hostname(zelf: &Py, value: bool) { + fn set_check_hostname(zelf: &Py, value: ArgIntoBool) { + let value = value.into_bool(); *zelf.check_hostname.write() = value; if value && *zelf.verify_mode.read() == CERT_NONE { *zelf.verify_mode.write() = CERT_REQUIRED; @@ -274,7 +282,8 @@ mod _ssl { } #[pygetset(setter)] - fn set_post_handshake_auth(zelf: &Py, value: bool) { + fn set_post_handshake_auth(zelf: &Py, value: ArgIntoBool) { + let value = value.into_bool(); *zelf.post_handshake_auth.write() = value; } @@ -568,16 +577,17 @@ mod _ssl { args: WrapBioArgs, vm: &VirtualMachine, ) -> PyResult { + let server_side = args.server_side.map_or(false, ArgIntoBool::into_bool); if let Some(hostname) = args.server_hostname { validate_hostname(hostname.as_str(), vm)?; } - if args.server_side.unwrap_or(false) && zelf.protocol == PROTOCOL_TLS_CLIENT { + if server_side && zelf.protocol == PROTOCOL_TLS_CLIENT { return ssl_error( vm, "Cannot create a server socket with a PROTOCOL_TLS_CLIENT context", ); } - if !args.server_side.unwrap_or(false) && zelf.protocol == PROTOCOL_TLS_SERVER { + if !server_side && zelf.protocol == PROTOCOL_TLS_SERVER { return ssl_error( vm, "Cannot create a client socket with a PROTOCOL_TLS_SERVER context", @@ -665,7 +675,7 @@ mod _ssl { #[derive(FromArgs)] struct GetCertArgs { #[pyarg(any, optional)] - binary_form: OptionalArg, + binary_form: OptionalArg, } #[derive(FromArgs)] @@ -685,7 +695,7 @@ mod _ssl { #[allow(dead_code)] outgoing: PyRef, #[pyarg(named, optional)] - server_side: OptionalArg, + server_side: OptionalArg, #[pyarg(named, optional)] server_hostname: Option, #[pyarg(named, optional)] @@ -886,13 +896,18 @@ mod _ssl { .into() } + #[pyfunction] + fn get_sigalgs(vm: &VirtualMachine) -> PyResult { + Err(vm.new_not_implemented_error(UNAVAILABLE)) + } + #[pyfunction] fn RAND_status() -> i32 { 1 } #[pyfunction] - fn RAND_add(_string: PyObjectRef, _entropy: f64) {} + fn RAND_add(_string: ArgStrOrBytesLike, _entropy: ArgIntoFloat) {} #[pyfunction] fn RAND_bytes(n: i32, vm: &VirtualMachine) -> PyResult { diff --git a/crates/stdlib/src/syslog.rs b/crates/stdlib/src/syslog.rs index 5966dced299..fafd971694b 100644 --- a/crates/stdlib/src/syslog.rs +++ b/crates/stdlib/src/syslog.rs @@ -5,11 +5,12 @@ pub(crate) use syslog::module_def; #[pymodule(name = "syslog")] mod syslog { use crate::vm::{ - Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, - builtins::{PyStr, PyStrRef}, - convert::ToPyException, + PyObjectRef, PyPayload, PyResult, VirtualMachine, + builtins::{PyList, PyStr, PyStrRef}, + function::OptionalArg, utils::ToCString, }; + use core::ffi::c_long; use rustpython_host_env::syslog as host_syslog; #[pyattr] @@ -28,73 +29,66 @@ mod syslog { #[pyattr] use host_syslog::{LOG_FTP, LOG_INSTALL, LOG_LAUNCHD, LOG_NETINFO, LOG_RAS, LOG_REMOTEAUTH}; - fn ident_to_utf8_cstring( - ident: &Py, - vm: &VirtualMachine, - ) -> PyResult { - let utf8 = ident.to_str().ok_or_else(|| { - let start = ident - .as_wtf8() - .code_points() - .position(|c| c.to_char().is_none()) - .unwrap_or(0); - vm.new_unicode_encode_error( - vm.ctx.new_str("utf-8"), - ident.to_owned(), - start, - start + 1, - vm.ctx.new_str("surrogates not allowed"), - ) - })?; - alloc::ffi::CString::new(utf8).map_err(|err| err.to_pyexception(vm)) - } - fn get_argv(vm: &VirtualMachine) -> Option { - if let Some(argv) = vm.state.config.settings.argv.first() - && !argv.is_empty() - { - return Some( - PyStr::from(match argv.find('\\') { - Some(value) => &argv[value..], - None => argv, - }) - .into_ref(&vm.ctx), - ); + let argv = vm.sys_module.dict().get_item_opt("argv", vm).ok()??; + let argv = argv.downcast_ref::()?; + let script = argv.borrow_vec().first()?.clone(); + let script = script.downcast::().ok()?; + let name = script.as_wtf8(); + if name.is_empty() { + return None; + } + // syslog is a Unix module: use the final slash in the current sys.argv[0]. + match name.as_bytes().iter().rposition(|&b| b == b'/') { + Some(slash) => Some(PyStr::from(&name[slash + 1..]).into_ref(&vm.ctx)), + None => Some(script), } - None } #[derive(Default, FromArgs)] struct OpenLogArgs { #[pyarg(any, optional)] - ident: Option, + ident: OptionalArg, #[pyarg(any, default)] - logoption: i32, - #[pyarg(any, default = ::LOG_USER)] - facility: i32, + logoption: c_long, + #[pyarg(any, default = LOG_USER as c_long, py_default = "LOG_USER")] + facility: c_long, } #[pyfunction] fn openlog(args: OpenLogArgs, vm: &VirtualMachine) -> PyResult<()> { + if !vm.state.is_main_interpreter() { + return Err(vm.new_runtime_error("subinterpreter can't use syslog.openlog()")); + } let logoption = args.logoption; let facility = args.facility; - let ident = match args.ident.clone() { - Some(ident) => Some(ident_to_utf8_cstring(&ident, vm)?), - None => get_argv(vm) - .map(|argv| ident_to_utf8_cstring(&argv, vm)) - .transpose()?, - } - .map(|ident| ident.into_boxed_c_str()); + let ident = args.ident.into_option().or_else(|| get_argv(vm)); + let c_ident = ident + .as_ref() + .map(|ident| { + let utf8 = ident.try_as_utf8(vm)?; + // openlog accepts a Unicode ident, not a NUL-checked "s" argument. + // Keep the full object for auditing, but pass its C string prefix. + utf8.as_str() + .split('\0') + .next() + .unwrap_or_default() + .to_cstring(vm) + }) + .transpose()? + .map(|ident| ident.into_boxed_c_str()); vm.audit("syslog.openlog", || { - let audit_ident: PyObjectRef = args.ident.map_or_else( - || get_argv(vm).map_or_else(|| vm.ctx.none(), Into::into), - Into::into, - ); - (audit_ident, logoption, facility) + ( + ident + .as_ref() + .map_or_else(|| vm.ctx.none(), |s| s.clone().into()), + logoption, + facility, + ) })?; - host_syslog::openlog(ident, logoption, facility); + host_syslog::openlog(c_ident, logoption as i32, facility as i32); Ok(()) } @@ -103,35 +97,51 @@ mod syslog { #[pyarg(positional)] priority: PyObjectRef, #[pyarg(positional, optional)] - message: Option, + message: OptionalArg, } #[pyfunction] fn syslog(args: SysLogArgs, vm: &VirtualMachine) -> PyResult<()> { - let (priority, msg) = match args.message { - Some(s) => (args.priority.try_into_value(vm)?, s), - None => (LOG_INFO, args.priority.try_into_value(vm)?), + let (priority, msg): (i32, PyStrRef) = match args.message { + OptionalArg::Present(message) => { + // Convert priority before inspecting message, as PyArg_ParseTuple does. + let priority = args.priority.try_into_value(vm)?; + (priority, message.try_into_value(vm)?) + } + OptionalArg::Missing => (LOG_INFO, args.priority.try_into_value(vm)?), }; + // Reject invalid UTF-8 and embedded NUL before auditing or opening the log. + let utf8 = msg.try_as_utf8(vm)?; + let cmsg = utf8.to_cstring(vm)?; - vm.audit("syslog.syslog", || (priority, msg.clone()))?; + vm.audit("syslog.syslog", || { + (priority, vm.ctx.new_str(utf8.as_str())) + })?; if !host_syslog::is_open() { + if !vm.state.is_main_interpreter() { + return Err(vm.new_runtime_error( + "subinterpreter can't use syslog.syslog() until the syslog is opened by the main interpreter", + )); + } openlog( OpenLogArgs { - facility: LOG_USER, + facility: LOG_USER as c_long, ..OpenLogArgs::default() }, vm, )?; } - let cmsg = msg.to_cstring(vm)?; host_syslog::syslog(priority, cmsg.as_c_str()); Ok(()) } #[pyfunction] fn closelog(vm: &VirtualMachine) -> PyResult<()> { + if !vm.state.is_main_interpreter() { + return Err(vm.new_runtime_error("subinterpreter can't use syslog.closelog()")); + } vm.audit("syslog.closelog", || ())?; host_syslog::closelog(); @@ -139,10 +149,10 @@ mod syslog { } #[pyfunction] - fn setlogmask(maskpri: i32, vm: &VirtualMachine) -> PyResult { + fn setlogmask(maskpri: c_long, vm: &VirtualMachine) -> PyResult { vm.audit("syslog.setlogmask", || (maskpri,))?; - Ok(host_syslog::setlogmask(maskpri)) + Ok(host_syslog::setlogmask(maskpri as i32)) } #[inline] diff --git a/crates/stdlib/src/termios.rs b/crates/stdlib/src/termios.rs index ddb3303299a..a3d2a3a6afe 100644 --- a/crates/stdlib/src/termios.rs +++ b/crates/stdlib/src/termios.rs @@ -5,8 +5,8 @@ pub(crate) use self::termios::module_def; #[pymodule] mod termios { use crate::vm::{ - PyObjectRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyBaseExceptionRef, PyBytes, PyInt, PyListRef, PyTypeRef}, + PyObjectRef, PyResult, VirtualMachine, + builtins::{PyBaseExceptionRef, PyBytes, PyInt, PyList, PyListRef, PyTypeRef}, convert::ToPyObject, stdlib::_io::Fildes, }; @@ -173,8 +173,7 @@ mod termios { use host_termios::{VSWTCH, VSWTCH as VSWTC}; #[pyfunction] - fn tcgetattr(fd: PyObjectRef, vm: &VirtualMachine) -> PyResult> { - let fd = Fildes::try_from_object(vm, fd).map(Into::into)?; + fn tcgetattr(Fildes(fd): Fildes, vm: &VirtualMachine) -> PyResult> { let termios = host_termios::tcgetattr(fd).map_err(|e| termios_error(e, vm))?; let noncanon = (termios.c_lflag & host_termios::ICANON) == 0; let cc = termios @@ -200,76 +199,87 @@ mod termios { #[pyfunction] fn tcsetattr( - fd: PyObjectRef, + Fildes(fd): Fildes, when: i32, - attributes: PyListRef, + attributes: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - let fd = Fildes::try_from_object(vm, fd).map(Into::into)?; - let [iflag, oflag, cflag, lflag, ispeed, ospeed, cc] = - <&[PyObjectRef; 7]>::try_from(&*attributes.borrow_vec()) - .map_err(|_| vm.new_type_error("tcsetattr, arg 3: must be 7 element list"))? - .clone(); + let attributes = attributes + .downcast::() + .ok() + .filter(|attributes| attributes.borrow_vec().len() == 7) + .ok_or_else(|| vm.new_type_error("tcsetattr, arg 3: must be 7 element list"))?; let mut termios = host_termios::tcgetattr(fd).map_err(|e| termios_error(e, vm))?; - termios.c_iflag = iflag.try_into_value(vm)?; - termios.c_oflag = oflag.try_into_value(vm)?; - termios.c_cflag = cflag.try_into_value(vm)?; - termios.c_lflag = lflag.try_into_value(vm)?; - host_termios::cfsetispeed(&mut termios, ispeed.try_into_value(vm)?) - .map_err(|e| termios_error(e, vm))?; - host_termios::cfsetospeed(&mut termios, ospeed.try_into_value(vm)?) - .map_err(|e| termios_error(e, vm))?; - let cc = PyListRef::try_from_object(vm, cc)?; - let cc = cc.borrow_vec(); - let cc = <&[PyObjectRef; NCCS]>::try_from(&*cc).map_err(|_| { - vm.new_type_error(format!( - "tcsetattr: attributes[6] must be {NCCS} element list" - )) - })?; - for (cc, x) in termios.c_cc.iter_mut().zip(cc.iter()) { + + // Read each item after converting the previous one: __index__ can + // replace later elements of the attributes list. + let long_at = |index| -> PyResult { + list_item(&attributes, index, vm)? + .try_index(vm)? + .try_to_primitive(vm) + }; + termios.c_iflag = long_at(0)? as _; + termios.c_oflag = long_at(1)? as _; + termios.c_cflag = long_at(2)? as _; + termios.c_lflag = long_at(3)? as _; + let ispeed = long_at(4)?; + let ospeed = long_at(5)?; + + let cc = list_item(&attributes, 6, vm)? + .downcast::() + .ok() + .filter(|cc| cc.borrow_vec().len() == NCCS) + .ok_or_else(|| { + vm.new_type_error(format!( + "tcsetattr: attributes[6] must be {NCCS} element list" + )) + })?; + for (cc, x) in termios.c_cc.iter_mut().zip(cc.borrow_vec().iter()) { *cc = if let Some(c) = x .downcast_ref::() .filter(|b| b.as_bytes().len() == 1) { c.as_bytes()[0] as _ } else if let Some(i) = x.downcast_ref::() { - i.try_to_primitive(vm)? + // CPython checks C long range, then casts to cc_t. Negative + // values and values larger than a byte therefore wrap. + i.try_to_primitive::(vm)? as _ } else { return Err(vm.new_type_error( - "tcsetattr: elements of attributes must be characters or integers", + "tcsetattr: elements of attributes must be bytes objects of length 1 or integers", )); }; } + // Validate all Python values before asking libc to validate the speeds. + host_termios::cfsetispeed(&mut termios, ispeed as _).map_err(|e| termios_error(e, vm))?; + host_termios::cfsetospeed(&mut termios, ospeed as _).map_err(|e| termios_error(e, vm))?; + host_termios::tcsetattr(fd, when, &termios).map_err(|e| termios_error(e, vm))?; Ok(()) } #[pyfunction] - fn tcsendbreak(fd: PyObjectRef, duration: i32, vm: &VirtualMachine) -> PyResult<()> { - let fd = Fildes::try_from_object(vm, fd).map(Into::into)?; + fn tcsendbreak(Fildes(fd): Fildes, duration: i32, vm: &VirtualMachine) -> PyResult<()> { host_termios::tcsendbreak(fd, duration).map_err(|e| termios_error(e, vm))?; Ok(()) } #[pyfunction] - fn tcdrain(fd: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let fd = Fildes::try_from_object(vm, fd).map(Into::into)?; + fn tcdrain(Fildes(fd): Fildes, vm: &VirtualMachine) -> PyResult<()> { host_termios::tcdrain(fd).map_err(|e| termios_error(e, vm))?; Ok(()) } #[pyfunction] - fn tcflush(fd: PyObjectRef, queue: i32, vm: &VirtualMachine) -> PyResult<()> { - let fd = Fildes::try_from_object(vm, fd).map(Into::into)?; + fn tcflush(Fildes(fd): Fildes, queue: i32, vm: &VirtualMachine) -> PyResult<()> { host_termios::tcflush(fd, queue).map_err(|e| termios_error(e, vm))?; Ok(()) } #[pyfunction] - fn tcflow(fd: PyObjectRef, action: i32, vm: &VirtualMachine) -> PyResult<()> { - let fd = Fildes::try_from_object(vm, fd).map(Into::into)?; + fn tcflow(Fildes(fd): Fildes, action: i32, vm: &VirtualMachine) -> PyResult<()> { host_termios::tcflow(fd, action).map_err(|e| termios_error(e, vm))?; Ok(()) } @@ -282,21 +292,30 @@ mod termios { #[pyfunction] fn tcsetwinsize(Fildes(fd): Fildes, winsize: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let size = winsize; - let seq = size.try_sequence(vm)?; - if seq.length(vm)? != 2 { - return Err(vm.new_type_error("tcsetwinsize: size must be a 2 element sequence")); + let seq = winsize.sequence_unchecked(); + if !seq.check() || seq.length(vm).ok() != Some(2) { + return Err(vm.new_type_error("tcsetwinsize, arg 2: must be a two-item sequence")); } - let row = seq.get_item(0, vm)?; - let col = seq.get_item(1, vm)?; + // A row's __index__ may change the next item in the sequence. + let row: libc::c_long = seq.get_item(0, vm)?.try_index(vm)?.try_to_primitive(vm)?; + let col: libc::c_long = seq.get_item(1, vm)?.try_index(vm)?.try_to_primitive(vm)?; - let row: u16 = row.try_index(vm)?.try_to_primitive(vm)?; - let col: u16 = col.try_index(vm)?.try_to_primitive(vm)?; - - host_termios::tcsetwinsize(fd, row, col).map_err(|e| termios_error(e, vm))?; + host_termios::tcsetwinsize(fd, row, col).map_err(|e| match e { + host_termios::SetWinSizeError::Io(e) => termios_error(e, vm), + host_termios::SetWinSizeError::OutOfRange => { + vm.new_overflow_error("winsize value(s) out of range.") + } + })?; Ok(()) } + fn list_item(list: &PyListRef, index: usize, vm: &VirtualMachine) -> PyResult { + list.borrow_vec() + .get(index) + .cloned() + .ok_or_else(|| vm.new_index_error("list index out of range")) + } + fn termios_error(err: std::io::Error, vm: &VirtualMachine) -> PyBaseExceptionRef { vm.new_exception( error_type(vm), diff --git a/crates/stdlib/src/unicodedata.rs b/crates/stdlib/src/unicodedata.rs index 6ef17ecc119..27dd67e2da7 100644 --- a/crates/stdlib/src/unicodedata.rs +++ b/crates/stdlib/src/unicodedata.rs @@ -2,43 +2,273 @@ See also: https://docs.python.org/3/library/unicodedata.html */ -// spell-checker:ignore nfkc unistr unidata +// spell-checker:ignore nfkc unistr unidata ucnhash pub(crate) use unicodedata::module_def; use rustpython_unicode::{self as unicode_core, NormalizeForm}; -use crate::vm::{ - Py, PyObject, PyResult, VirtualMachine, builtins::PyStr, convert::TryFromBorrowedObject, -}; - -struct NormalizeFormArg(NormalizeForm); - -impl<'a> TryFromBorrowedObject<'a> for NormalizeFormArg { - fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { - obj.try_value_with( - |form: &Py| match form.as_bytes() { - b"NFC" => Ok(Self(NormalizeForm::Nfc)), - b"NFKC" => Ok(Self(NormalizeForm::Nfkc)), - b"NFD" => Ok(Self(NormalizeForm::Nfd)), - b"NFKD" => Ok(Self(NormalizeForm::Nfkd)), - _ => Err(vm.new_value_error("invalid normalization form")), - }, - vm, - ) +use crate::vm::{Py, PyResult, VirtualMachine, builtins::PyStr}; + +fn normalize_form(form: &Py, vm: &VirtualMachine) -> PyResult { + match form.as_bytes() { + b"NFC" => Ok(NormalizeForm::Nfc), + b"NFKC" => Ok(NormalizeForm::Nfkc), + b"NFD" => Ok(NormalizeForm::Nfd), + b"NFKD" => Ok(NormalizeForm::Nfkd), + _ => Err(vm.new_value_error("invalid normalization form")), } } #[pymodule] mod unicodedata { - use super::{NormalizeFormArg, unicode_core}; + use alloc::ffi::CString; + use rustpython_unicode::{UNICODE_VERSION, UNICODE_VERSION_LEGACY}; + + use super::{normalize_form, unicode_core}; use crate::vm::{ - Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyModule, PyStr, PyStrRef}, + Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, + builtins::{PyBytes, PyModule, PyStr, PyStrRef, PyUtf8Str}, + common::lock::PyMutex, function::OptionalArg, + protocol::PyIterReturn, + types::{IterNext, Iterable, Representable, SelfIter}, }; use itertools::Itertools; use rustpython_common::wtf8::{CodePoint, Wtf8Buf}; + use unicode_core::grapheme::{self, GraphemeBreakState}; + + fn grapheme_char(character: &Py, vm: &VirtualMachine) -> PyResult { + character + .as_wtf8() + .code_points() + .exactly_one() + .map_err(|_| vm.new_type_error("argument must be a unicode character, not str")) + } + + fn property_char( + character: &PyObject, + function: &str, + vm: &VirtualMachine, + ) -> PyResult { + let Some(character_str) = character.downcast_ref::() else { + let kind = if vm.is_none(character) { + "None".to_owned() + } else { + character.class().slot_name().to_string() + }; + let kind = &kind[..kind.floor_char_boundary(50.min(kind.len()))]; + return Err(vm.new_type_error(format!( + "{function}() argument must be a unicode character, not {kind}" + ))); + }; + character_str + .as_wtf8() + .code_points() + .exactly_one() + .map_err(|_| { + vm.new_type_error(format!( + "{function}(): argument must be a unicode character, not a string of length {}", + character_str.char_len() + )) + }) + } + + /// Return True if the character has the XID_Start property, else False. + #[pyfunction] + fn isxidstart(chr: PyObjectRef, vm: &VirtualMachine) -> PyResult { + Ok(property_char(&chr, "isxidstart", vm)? + .to_char() + .is_some_and(unicode_core::identifier::is_xid_start)) + } + + /// Return True if the character has the XID_Continue property, else False. + #[pyfunction] + fn isxidcontinue(chr: PyObjectRef, vm: &VirtualMachine) -> PyResult { + Ok(property_char(&chr, "isxidcontinue", vm)? + .to_char() + .is_some_and(unicode_core::identifier::is_xid_continue)) + } + + /// Return block assigned to the character chr. + #[pyfunction] + fn block(chr: PyObjectRef, vm: &VirtualMachine) -> PyResult<&'static str> { + property_char(&chr, "block", vm).map(unicode_core::data::block) + } + + #[pyfunction] + fn grapheme_cluster_break(chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> { + grapheme_char(&chr, vm).map(grapheme::grapheme_cluster_break) + } + + #[pyfunction] + fn indic_conjunct_break(chr: PyStrRef, vm: &VirtualMachine) -> PyResult<&'static str> { + grapheme_char(&chr, vm).map(grapheme::indic_conjunct_break) + } + + #[pyfunction] + fn extended_pictographic(chr: PyStrRef, vm: &VirtualMachine) -> PyResult { + grapheme_char(&chr, vm).map(grapheme::extended_pictographic) + } + + #[pyclass(no_attr, name = "Segment", traverse)] + #[derive(Debug, PyPayload)] + struct Segment { + string: PyStrRef, + #[pytraverse(skip)] + start: usize, + #[pytraverse(skip)] + end: usize, + #[pytraverse(skip)] + bytes: core::ops::Range, + } + + #[pyclass(with(Representable), flags(IMMUTABLETYPE, DISALLOW_INSTANTIATION))] + impl Segment { + #[pygetset] + fn start(zelf: &Py) -> usize { + zelf.start + } + + #[pygetset] + fn end(zelf: &Py) -> usize { + zelf.end + } + + #[pymethod] + fn __str__(zelf: &Py, vm: &VirtualMachine) -> PyStrRef { + vm.ctx.new_str(&zelf.string.as_wtf8()[zelf.bytes.clone()]) + } + } + + impl Representable for Segment { + #[inline] + fn repr_str(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + Ok(format!("", zelf.start, zelf.end)) + } + } + + #[derive(Debug)] + struct GraphemePosition { + start: usize, + start_byte: usize, + pos: usize, + pos_byte: usize, + end: usize, + end_byte: usize, + state: GraphemeBreakState, + } + + #[pyclass(no_attr, name = "GraphemeBreakIterator", traverse)] + #[derive(Debug, PyPayload)] + struct GraphemeBreakIterator { + string: PyStrRef, + #[pytraverse(skip)] + position: PyMutex, + } + + #[pyclass(with(IterNext, Iterable), flags(IMMUTABLETYPE, DISALLOW_INSTANTIATION))] + impl GraphemeBreakIterator {} + + impl SelfIter for GraphemeBreakIterator {} + + impl IterNext for GraphemeBreakIterator { + fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let mut position = zelf.position.lock(); + if position.start >= position.end { + return Ok(PyIterReturn::StopIteration(None)); + } + let start = position.start; + let start_byte = position.start_byte; + let scan_byte = position.pos_byte; + let mut points = zelf.string.as_wtf8()[scan_byte..position.end_byte] + .code_point_indices() + .peekable(); + let (end, end_byte) = loop { + let Some((offset, point)) = points.next() else { + position.start = position.pos; + position.start_byte = position.end_byte; + break (position.pos, position.end_byte); + }; + let byte = scan_byte + offset; + let index = position.pos; + let boundary = position.state.advance(point); + position.pos += 1; + position.pos_byte = points + .peek() + .map_or(position.end_byte, |(offset, _)| scan_byte + offset); + if boundary { + position.start = index; + position.start_byte = byte; + break (index, byte); + } + }; + drop(position); + Ok(PyIterReturn::Return( + Segment { + string: zelf.string.clone(), + start, + end, + bytes: start_byte..end_byte, + } + .into_ref(&vm.ctx) + .into(), + )) + } + } + + #[derive(FromArgs)] + struct IterGraphemesArgs { + #[pyarg(positional)] + unistr: PyStrRef, + #[pyarg(positional, optional, py_default = "0")] + start: OptionalArg, + #[pyarg(positional, optional, py_default = "sys.maxsize")] + end: OptionalArg, + } + + #[pyfunction] + fn iter_graphemes( + args: IterGraphemesArgs, + vm: &VirtualMachine, + ) -> PyResult> { + let IterGraphemesArgs { unistr, start, end } = args; + // Convert in argument order, including overflow, before adjusting bounds. + let index = |arg: OptionalArg, default| -> PyResult { + match arg { + OptionalArg::Present(value) => value.try_index(vm)?.try_to_primitive(vm), + OptionalArg::Missing => Ok(default), + } + }; + let mut start = index(start, 0)?; + let mut end = index(end, isize::MAX)?; + let len = unistr.char_len() as isize; + if end > len { + end = len; + } else if end < 0 { + end = (end + len).max(0); + } + if start < 0 { + start = (start + len).max(0); + } + let start = start as usize; + let end = end as usize; + let start_byte = unistr.char_index_to_byte(start); + let end_byte = unistr.char_index_to_byte(end); + Ok(GraphemeBreakIterator { + string: unistr, + position: PyMutex::new(GraphemePosition { + start, + start_byte, + pos: start, + pos_byte: start_byte, + end, + end_byte, + state: GraphemeBreakState::default(), + }), + } + .into_ref(&vm.ctx)) + } pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { __module_exec(vm, module); @@ -76,23 +306,25 @@ mod unicodedata { inner: unicode_core::Ucd, /// Owns the bytes `unidata_version` points at. #[expect(dead_code, reason = "keeps the version string alive")] - version_owner: alloc::ffi::CString, + version_owner: CString, #[pymember] unidata_version: crate::vm::builtins::descriptor::CStrMember, } impl Ucd { pub(super) fn new(modern: bool) -> Self { + let inner = unicode_core::Ucd::new(modern); let text = if modern { - unicode_core::unicode_version() + UNICODE_VERSION } else { - "3.2.0".to_owned() + UNICODE_VERSION_LEGACY }; - let version_owner = alloc::ffi::CString::new(text).unwrap_or_default(); + let version_owner = CString::new(text) + .expect("Embedded Unicode version string should never have internal NULs"); let unidata_version = crate::vm::builtins::descriptor::CStrMember::new(version_owner.as_ptr()); Self { - inner: unicode_core::Ucd::new(modern), + inner, version_owner, unidata_version, } @@ -115,8 +347,17 @@ mod unicodedata { } #[pymethod] - fn lookup(zelf: &Py, name: PyStrRef, vm: &VirtualMachine) -> PyResult { - if let Some(name_str) = name.to_str() + fn lookup(zelf: &Py, name: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let name_bytes = if let Some(bytes) = name.downcast_ref::() { + bytes.as_bytes() + } else { + name.try_downcast_ref::(vm)?.as_bytes() + }; + // CPython's generated Unicode name database limits names to 256 bytes. + if name_bytes.len() > 256 { + return Err(vm.new_key_error(vm.ctx.new_str("name too long").into())); + } + if let Ok(name_str) = core::str::from_utf8(name_bytes) && let Some(found) = zelf.inner.lookup(name_str) { return Ok(match found { @@ -124,9 +365,15 @@ mod unicodedata { unicode_core::LookupResult::Sequence(seq) => seq.to_string(), }); } + // CPython formats the failed name as a NUL-terminated UTF-8 string. + let prefix = name_bytes + .split(|&byte| byte == 0) + .next() + .unwrap_or_default(); + let display = String::from_utf8_lossy(prefix); Err(vm.new_key_error( vm.ctx - .new_str(format!("undefined character name '{name}'")) + .new_str(format!("undefined character name '{display}'")) .into(), )) } @@ -170,13 +417,31 @@ mod unicodedata { } #[pymethod] - fn normalize(_zelf: &Py, form: NormalizeFormArg, unistr: PyStrRef) -> Wtf8Buf { - unicode_core::normalize(form.0, unistr.as_wtf8()) + fn normalize( + zelf: &Py, + form: PyStrRef, + unistr: PyStrRef, + vm: &VirtualMachine, + ) -> PyResult { + if unistr.is_empty() { + return Ok(Wtf8Buf::new()); + } + let form = normalize_form(&form, vm)?; + Ok(zelf.inner.normalize(form, unistr.as_wtf8())) } #[pymethod] - fn is_normalized(_zelf: &Py, form: NormalizeFormArg, unistr: PyStrRef) -> bool { - unicode_core::is_normalized(form.0, unistr.as_wtf8()) + fn is_normalized( + zelf: &Py, + form: PyStrRef, + unistr: PyStrRef, + vm: &VirtualMachine, + ) -> PyResult { + if unistr.is_empty() { + return Ok(true); + } + let form = normalize_form(&form, vm)?; + Ok(zelf.inner.is_normalized(form, unistr.as_wtf8())) } #[pymethod] @@ -244,13 +509,20 @@ mod unicodedata { } } + #[cfg(feature = "ucd_3_2_0")] #[pyattr] - fn ucd_3_2_0(vm: &VirtualMachine) -> PyRef { + fn ucd_3_2_0(vm: &VirtualMachine) -> crate::vm::PyRef { Ucd::new(false).into_ref(&vm.ctx) } + #[pyattr] + #[allow(non_snake_case)] + fn _ucnhash_CAPI(vm: &VirtualMachine) -> crate::vm::PyRef { + vm.new_unicode_name_capsule() + } + #[pyattr] fn unidata_version(_vm: &VirtualMachine) -> String { - unicode_core::unicode_version() + UNICODE_VERSION.into() } } diff --git a/crates/stdlib/src/uuid.rs b/crates/stdlib/src/uuid.rs index c0af2c41945..8dd69dff0db 100644 --- a/crates/stdlib/src/uuid.rs +++ b/crates/stdlib/src/uuid.rs @@ -2,10 +2,17 @@ pub(crate) use _uuid::module_def; #[pymodule] mod _uuid { - use crate::{builtins::PyNone, vm::VirtualMachine}; + #[cfg(not(windows))] + use crate::builtins::PyNone; + use crate::vm::VirtualMachine; + #[cfg(windows)] + use crate::vm::{AsObject, PyResult, convert::ToPyObject}; + #[cfg(not(windows))] use std::sync::OnceLock; + #[cfg(not(windows))] use uuid::{ContextV1, Uuid, timestamp::Timestamp}; + #[cfg(not(windows))] fn hardware_node_id() -> Option<&'static [u8; 6]> { static HARDWARE_NODE_ID: OnceLock> = OnceLock::new(); HARDWARE_NODE_ID @@ -13,6 +20,7 @@ mod _uuid { .as_ref() } + #[cfg(not(windows))] fn get_node_id() -> [u8; 6] { // os_random is expensive, but this is only ever called once hardware_node_id() @@ -20,7 +28,8 @@ mod _uuid { .unwrap_or_else(rustpython_common::rand::os_random::<6>) } - #[pyfunction] + #[cfg(not(windows))] + #[pyfunction(signature_from_flags)] fn generate_time_safe() -> (Vec, PyNone) { static CONTEXT: ContextV1 = ContextV1::new(0); let ts = Timestamp::now(&CONTEXT); @@ -31,6 +40,26 @@ mod _uuid { (Uuid::new_v1(ts, unique_node_id).as_bytes().to_vec(), PyNone) } + #[cfg(windows)] + #[pyfunction(name = "UuidCreate")] + fn uuid_create(vm: &VirtualMachine) -> PyResult> { + use rustpython_host_env::uuid; + + let uuid = uuid::create_sequential(); + match uuid.status { + uuid::STATUS_OK | uuid::STATUS_LOCAL_ONLY | uuid::STATUS_NO_ADDRESS => { + Ok(uuid.bytes.to_vec()) + } + status => { + let errno = rustpython_host_env::os::winerror_to_errno(status); + let exc = vm.new_errno_error(errno, uuid::format_error_message(status)); + exc.as_object() + .set_attr("winerror", status.to_pyobject(vm), vm)?; + Err(exc.upcast()) + } + } + } + #[pyattr] fn has_uuid_generate_time_safe(_vm: &VirtualMachine) -> u32 { 0 @@ -38,6 +67,10 @@ mod _uuid { #[pyattr] fn has_stable_extractable_node(_vm: &VirtualMachine) -> u32 { - hardware_node_id().is_some().into() + #[cfg(windows)] + let has_stable_node = rustpython_host_env::uuid::has_stable_node(); + #[cfg(not(windows))] + let has_stable_node = hardware_node_id().is_some(); + has_stable_node.into() } } diff --git a/crates/stdlib/src/zlib.rs b/crates/stdlib/src/zlib.rs index 0a3082edbaa..9ef978aab4b 100644 --- a/crates/stdlib/src/zlib.rs +++ b/crates/stdlib/src/zlib.rs @@ -7,16 +7,17 @@ mod zlib { use crate::compression::{DecompressArgs, DecompressorArgs}; use crate::vm::{ Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, - builtins::{PyBaseExceptionRef, PyBytes, PyBytesRef, PyType, PyTypeRef}, + builtins::{PyBaseExceptionRef, PyBytes, PyBytesRef, PyIntRef, PyStr, PyType, PyTypeRef}, common::lock::PyMutex, - convert::TryFromBorrowedObject, - function::{ArgBytesLike, ArgIndex, OptionalArg, PySize, PySsize}, + convert::TryFromObject, + function::{ArgBytesLike, ArgCInt, ArgIndex, OptionalArg, PySsize}, object::PyAtomicRef, types::Constructor, }; use adler32::RollingAdler32 as Adler32; use alloc::fmt; use core::sync::atomic::{AtomicBool, Ordering}; + use num_traits::ToPrimitive; use rustpython_common::compression::zlib as backend; #[pyattr] @@ -26,8 +27,19 @@ mod zlib { Z_NO_COMPRESSION, Z_NO_FLUSH, Z_PARTIAL_FLUSH, Z_RLE, Z_SYNC_FLUSH, Z_TREES, }; - #[pyattr(name = "__version__")] - const __VERSION__: &str = "1.0"; + #[pyfunction] + fn __getattr__(name: PyObjectRef, vm: &VirtualMachine) -> PyResult { + if name.downcast_ref::().and_then(|name| name.to_str()) == Some("__version__") { + crate::vm::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "'__version__' is deprecated and slated for removal in Python 3.20".to_owned(), + 1, + vm, + )?; + return Ok(vm.ctx.new_str("1.0").into()); + } + Err(vm.new_attribute_error(format!("module 'zlib' has no attribute {}", name.repr(vm)?))) + } // We statically link libz-rs, so the compile-time and runtime versions // always match. @@ -40,7 +52,7 @@ mod zlib { #[pyattr] const DEF_BUF_SIZE: usize = backend::DEF_BUF_SIZE; #[pyattr] - const DEF_MEM_LEVEL: u8 = backend::DEF_MEM_LEVEL; + const DEF_MEM_LEVEL: i32 = backend::DEF_MEM_LEVEL as i32; #[pyattr(once)] fn error(vm: &VirtualMachine) -> PyTypeRef { @@ -81,7 +93,58 @@ mod zlib { #[pyfunction] fn crc32(args: Crc32Args) -> u32 { let Crc32Args { data, value } = args; - crate::binascii::crc32(data, value) + crate::binascii::crc32_impl(data, value) + } + + struct ChecksumValue(u32); + + impl TryFromObject for ChecksumValue { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let value = obj.try_index(vm)?; + if !value + .as_bigint() + .to_i64() + .is_some_and(|value| (i64::from(i32::MIN)..=i64::from(u32::MAX)).contains(&value)) + { + crate::vm::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "integer value out of range".to_owned(), + 1, + vm, + )?; + } + Ok(Self(value.as_u32_mask())) + } + } + + fn checksum_length(len2: PyIntRef, vm: &VirtualMachine) -> PyResult { + let len2 = len2.try_to_primitive::(vm)?; + if len2 < 0 { + return Err(vm.new_value_error("len2 must be non-negative".to_owned())); + } + Ok(len2) + } + + #[pyfunction] + fn adler32_combine( + adler1: ChecksumValue, + adler2: ChecksumValue, + len2: PyIntRef, + vm: &VirtualMachine, + ) -> PyResult { + let len2 = checksum_length(len2, vm)?; + Ok(backend::adler32_combine(adler1.0, adler2.0, len2)) + } + + #[pyfunction] + fn crc32_combine( + crc1: ChecksumValue, + crc2: ChecksumValue, + len2: PyIntRef, + vm: &VirtualMachine, + ) -> PyResult { + let len2 = checksum_length(len2, vm)?; + Ok(backend::crc32_combine(crc1.0, crc2.0, len2)) } #[derive(FromArgs)] @@ -89,18 +152,17 @@ mod zlib { #[pyarg(positional)] data: ArgBytesLike, #[pyarg(any, default = ::Z_DEFAULT_COMPRESSION)] - level: Level, + level: ArgCInt, #[pyarg(any, default = ::MAX_WBITS)] - wbits: i32, + wbits: ArgCInt, } #[pyfunction] fn compress(args: PyFuncCompressArgs, vm: &VirtualMachine) -> PyResult { let PyFuncCompressArgs { data, level, wbits } = args; - let level = level - .value() - .ok_or_else(|| new_zlib_error("Bad compression level", vm))?; - let encoded = data.with_ref(|data| backend::compress(data, level, wbits)); + let encoded = data.with_ref(|data| { + backend::compress(data, level.into_primitive(), wbits.into_primitive()) + }); encoded .map(|data| vm.ctx.new_bytes(data)) .map_err(|err| new_init_or_zlib_error(err, vm)) @@ -111,9 +173,9 @@ mod zlib { #[pyarg(positional)] data: ArgBytesLike, #[pyarg(any, default = ::MAX_WBITS)] - wbits: i32, - #[pyarg(any, default = ::DEF_BUF_SIZE)] - bufsize: PySize, + wbits: ArgCInt, + #[pyarg(any, default = DEF_BUF_SIZE as isize, py_default = "DEF_BUF_SIZE")] + bufsize: PySsize, } #[pyfunction] @@ -123,14 +185,16 @@ mod zlib { wbits, bufsize, } = args; - data.with_ref(|data| backend::decompress(data, wbits, bufsize)) + let bufsize = usize::try_from(bufsize) + .map_err(|_| vm.new_value_error("bufsize cannot be negative"))?; + data.with_ref(|data| backend::decompress(data, wbits.into_primitive(), bufsize)) .map_err(|err| new_init_or_zlib_error(err, vm)) } #[derive(FromArgs)] struct DecompressobjArgs { #[pyarg(any, default = ::MAX_WBITS)] - wbits: i32, + wbits: ArgCInt, // Missing dictionary is empty bytes. #[pyarg(any, optional, py_default = "b''")] zdict: OptionalArg, @@ -144,8 +208,9 @@ mod zlib { #[pyfunction] fn decompressobj(args: DecompressobjArgs, vm: &VirtualMachine) -> PyResult { - let decompress = backend::Decompressor::new(args.wbits, owned_dict(args.zdict)) - .map_err(|err| new_init_or_zlib_error(err, vm))?; + let decompress = + backend::Decompressor::new(args.wbits.into_primitive(), owned_dict(args.zdict)) + .map_err(|err| new_init_or_zlib_error(err, vm))?; Ok(PyDecompress { inner: PyMutex::new(PyDecompressInner { decompress, @@ -226,7 +291,6 @@ mod zlib { ) -> PyResult> { let max_length: usize = args .raw_max_length() - .unwrap_or(0) .try_into() .map_err(|_| vm.new_value_error("max_length must be non-negative"))?; let max_length = (max_length != 0).then_some(max_length); @@ -263,13 +327,17 @@ mod zlib { zelf.copy_inner(vm) } - #[pymethod(name = "__copy__")] - fn copy_dunder(zelf: &Py, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __copy__(zelf: &Py, vm: &VirtualMachine) -> PyResult { zelf.copy_inner(vm) } - #[pymethod(name = "__deepcopy__")] - fn deepcopy(zelf: &Py, _memo: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __deepcopy__( + zelf: &Py, + _memo: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { zelf.copy_inner(vm) } } @@ -277,17 +345,17 @@ mod zlib { #[derive(FromArgs)] struct CompressobjArgs { #[pyarg(any, default = ::Z_DEFAULT_COMPRESSION)] - level: Level, + level: ArgCInt, #[pyarg(any, default = ::DEFLATED)] - method: i32, + method: ArgCInt, #[pyarg(any, default = ::MAX_WBITS)] - wbits: i32, + wbits: ArgCInt, #[pyarg(any, name = "memLevel", default = ::DEF_MEM_LEVEL)] - mem_level: u8, + mem_level: ArgCInt, #[pyarg(any, default = ::Z_DEFAULT_STRATEGY)] - strategy: i32, - // Missing dictionary is None. - #[pyarg(any, optional, py_default = "None")] + strategy: ArgCInt, + // Omission is distinct from an explicit None. + #[pyarg(any, optional)] zdict: OptionalArg, } @@ -301,16 +369,13 @@ mod zlib { strategy, zdict, } = args; - let level = level - .value() - .ok_or_else(|| vm.new_value_error("Invalid initialization option"))?; let zdict = owned_dict(zdict); let compress = backend::Compressor::new( - level, - method, - wbits, - mem_level.into(), - strategy, + level.into_primitive(), + method.into_primitive(), + wbits.into_primitive(), + mem_level.into_primitive(), + strategy.into_primitive(), zdict.as_deref(), ) .map_err(|err| new_init_or_zlib_error(err, vm))?; @@ -355,12 +420,12 @@ mod zlib { #[pymethod] fn flush( zelf: &Py, - mode: OptionalArg, + mode: OptionalArg, vm: &VirtualMachine, ) -> PyResult> { zelf.inner .lock() - .flush(mode.unwrap_or(Z_FINISH)) + .flush(mode.map(ArgCInt::into_primitive).unwrap_or(Z_FINISH)) .map_err(|err| new_zlib_error(err, vm)) } @@ -369,13 +434,17 @@ mod zlib { zelf.copy_inner(vm) } - #[pymethod(name = "__copy__")] - fn copy_dunder(zelf: &Py, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __copy__(zelf: &Py, vm: &VirtualMachine) -> PyResult { zelf.copy_inner(vm) } - #[pymethod(name = "__deepcopy__")] - fn deepcopy(zelf: &Py, _memo: PyObjectRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __deepcopy__( + zelf: &Py, + _memo: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { zelf.copy_inner(vm) } } @@ -396,38 +465,6 @@ mod zlib { } } - struct Level(Option); - - impl Level { - const fn new(level: i32) -> Self { - if matches!( - level, - Z_DEFAULT_COMPRESSION | Z_NO_COMPRESSION..=Z_BEST_COMPRESSION - ) { - Self(Some(level)) - } else { - Self(None) - } - } - - const fn value(self) -> Option { - self.0 - } - } - - impl From for Level { - fn from(level: i32) -> Self { - Self::new(level) - } - } - - impl<'a> TryFromBorrowedObject<'a> for Level { - fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { - let level: i32 = obj.try_index(vm)?.try_to_primitive(vm)?; - Ok(Self::new(level)) - } - } - struct PyZlibDecompressorInner { decompress: backend::ZlibDecompressor, } @@ -454,11 +491,11 @@ mod zlib { } } - // `decompressobj` shows MAX_WBITS. This constructor shows the integer. + // Keep the symbolic default used by CPython's Clinic signature. #[derive(FromArgs)] struct ZlibDecompressorArgs { - #[pyarg(any, default = MAX_WBITS)] - wbits: i32, + #[pyarg(any, default = ::MAX_WBITS)] + wbits: ArgCInt, // Missing dictionary is empty bytes. #[pyarg(any, optional, py_default = "b''")] zdict: OptionalArg, @@ -468,8 +505,9 @@ mod zlib { type Args = ZlibDecompressorArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let decompress = backend::ZlibDecompressor::new(args.wbits, owned_dict(args.zdict)) - .map_err(|err| new_init_or_zlib_error(err, vm))?; + let decompress = + backend::ZlibDecompressor::new(args.wbits.into_primitive(), owned_dict(args.zdict)) + .map_err(|err| new_init_or_zlib_error(err, vm))?; Ok(Self { inner: PyMutex::new(PyZlibDecompressorInner { decompress }), eof: AtomicBool::new(false), diff --git a/crates/unicode/Cargo.toml b/crates/unicode/Cargo.toml index 4d753293e39..c37679c3a3a 100644 --- a/crates/unicode/Cargo.toml +++ b/crates/unicode/Cargo.toml @@ -8,6 +8,10 @@ repository = { workspace = true } license = { workspace = true } rust-version = { workspace = true } +[features] +default = ["ucd_3_2_0"] +ucd_3_2_0 = [] + [dependencies] rustpython-wtf8 = { workspace = true } @@ -19,6 +23,8 @@ unicode_names2 = { workspace = true } writeable = { workspace = true } [build-dependencies] +icu_casemap = { workspace = true } +icu_locale = { workspace = true } icu_properties = { workspace = true } unicode_names2 = { workspace = true } zlib-rs = { workspace = true } diff --git a/crates/unicode/build.rs b/crates/unicode/build.rs index e32d99d542c..db69ab3056d 100644 --- a/crates/unicode/build.rs +++ b/crates/unicode/build.rs @@ -3,6 +3,7 @@ extern crate alloc; use core::{ + cmp::Ordering, fmt::{Debug, Display}, iter::Iterator, num::NonZeroUsize, @@ -180,6 +181,11 @@ impl UnicodeLine { } } +struct NumericTypeDiffs { + value_diffs: Vec<(u32, u32, f64)>, + none_diffs: Vec<(u32, u32)>, +} + /// Helper to write a vector of condensed start, end char pairs and the associated ICU prop. /// /// The values are impl Display because Debug would break the representation. For example, strs @@ -198,19 +204,19 @@ fn write_slice_display( write_slice_post(writer); } -fn write_slice_debug( - writer: &mut impl Write, - static_name: &str, - array_type: &str, - values: &mut [(u32, u32, impl Debug)], -) { - write_slice_pre(writer, static_name, array_type); - values.sort_unstable_by_key(|(start, _, _)| *start); - for (start, end, id) in values { - write!(writer, "({start}, {end}, {id:?}),").unwrap(); - } - write_slice_post(writer); -} +// fn write_slice_debug( +// writer: &mut impl Write, +// static_name: &str, +// array_type: &str, +// values: &mut [(u32, u32, impl Debug)], +// ) { +// write_slice_pre(writer, static_name, array_type); +// values.sort_unstable_by_key(|(start, _, _)| *start); +// for (start, end, id) in values { +// write!(writer, "({start}, {end}, {id:?}),").unwrap(); +// } +// write_slice_post(writer); +// } /// Helper to write a vector of start, end char pairs. /// @@ -231,18 +237,34 @@ fn write_slice_pairs( /// Helper to write a pre-sorted slice of strs. /// -/// See: [`write_slice_display`] +/// See: [`write_slice_display`]. fn write_slice_unordered( writer: &mut impl Write, static_name: &str, array_type: &str, - values: &mut [impl Display], + values: &[impl Display], ) { - write_slice_pre(writer, static_name, array_type); - for v in values { - write!(writer, "{v},").unwrap(); - } - write_slice_post(writer); + write_slice_raw(writer, static_name, array_type, values, |writer, values| { + for v in values { + write!(writer, "{v},").unwrap(); + } + }); +} + +/// Helper to write a pre-sorted slice of impl Debug. +/// +/// See: [`write_slice_display`]. +fn write_slice_dbg_unordered( + writer: &mut impl Write, + static_name: &str, + array_type: &str, + values: &[impl Debug], +) { + write_slice_raw(writer, static_name, array_type, values, |writer, values| { + for v in values { + write!(writer, "{v:?},").unwrap(); + } + }); } /// Helper to write raw values for data sources that don't follow the common format. @@ -290,6 +312,85 @@ fn open_reader(file_name: &str, modern: bool) -> BufReader { })) } +/// Generate compact full case mappings from the same ICU data as our predicates. +/// Keep this independent of the Rust toolchain's Unicode version. The default +/// lowercase mapping of sigma is contextualized at runtime, like lower_ucs4. +fn generate_case_mappings() { + use icu_casemap::CaseMapper; + use icu_locale::LanguageIdentifier; + use icu_properties::props::{BinaryProperty, CaseIgnorable, Cased, Lowercase, Uppercase}; + + fn write_pages(writer: &mut impl Write, name: &str, values: &[u16]) { + let mut pages = Vec::new(); + let mut known = BTreeMap::new(); + let mut index = Vec::new(); + for page in values.as_chunks::<256>().0 { + let next = u16::try_from(known.len()).expect("too many case mapping pages"); + let id = *known.entry(page.to_vec()).or_insert_with(|| { + pages.extend_from_slice(page); + next + }); + index.push(id); + } + writeln!(writer, "static {name}_INDEX: &[u16] = &{index:?};").unwrap(); + writeln!(writer, "static {name}_PAGES: &[u16] = &{pages:?};").unwrap(); + } + + let mut writer = open_writer("case_mappings.rs"); + let mapper = CaseMapper::new(); + for (name, lower) in [("LOWER", true), ("UPPER", false)] { + let mut indices = vec![0; 0x110000]; + let mut mappings = vec![[char::default(); 3]]; + for (value, index) in indices.iter_mut().enumerate() { + let Some(ch) = char::from_u32(value as u32) else { + continue; + }; + if ch.is_ascii() { + continue; + } + let mut buf = [0; 4]; + let source: &str = ch.encode_utf8(&mut buf); + let mapped = if lower { + mapper.lowercase_to_string(source, &LanguageIdentifier::UNKNOWN) + } else { + mapper.uppercase_to_string(source, &LanguageIdentifier::UNKNOWN) + }; + if mapped == source { + continue; + } + assert!(!mapped.is_empty(), "empty full case mapping for {ch:?}"); + let mut result = [char::default(); 3]; + for (i, ch) in mapped.chars().enumerate() { + assert!( + i < result.len(), + "full case mapping exceeds three characters" + ); + assert_ne!(ch, '\0', "NUL in full case mapping"); + result[i] = ch; + } + *index = u16::try_from(mappings.len()).expect("too many case mappings"); + mappings.push(result); + } + write_pages(&mut writer, name, &indices); + writeln!( + writer, + "static {name}_MAPPINGS: &[[char; 3]] = &{mappings:?};" + ) + .unwrap(); + } + let flags: Vec<_> = (0..0x110000) + .map(|value| { + char::from_u32(value).map_or(0, |ch| { + u16::from(Cased::for_char(ch)) + | (u16::from(CaseIgnorable::for_char(ch)) << 1) + | (u16::from(Lowercase::for_char(ch)) << 2) + | (u16::from(Uppercase::for_char(ch)) << 3) + }) + }) + .collect(); + write_pages(&mut writer, "CASE_FLAGS", &flags); +} + /// Drive parsers that require the latest Unicode data. /// /// The full data is huge so it's ideal to parse it only once. @@ -322,10 +423,32 @@ fn full_data_parsers_latest() { } } + #[cfg(feature = "ucd_3_2_0")] + generate_normalization_changes_3_2(&decomp_lines); generate_decomp(decomp_lines); generate_algo_names(algo_names); } +/// Preserve the pre-4.0 normalization corrections for the Unicode 3.2 view. +#[cfg(feature = "ucd_3_2_0")] +fn generate_normalization_changes_3_2(latest: &[(u32, String)]) { + let mut changes = Vec::new(); + for line in UnicodeLineReader::from_file_name("UnicodeData-3.2.0.txt", false) { + let old = line.field(NonZeroUsize::new(5).unwrap(), None); + if let Ok(i) = latest.binary_search_by_key(&line.start, |(code, _)| *code) + && latest[i].1 != old + { + // Like CPython's previous-version normalization table, each + // correction replaces one character before recursive decomposition. + let replacement = u32::from_str_radix(old, 16) + .expect("normalization corrections have one canonical replacement"); + changes.push((line.start, replacement)); + } + } + let mut writer = open_writer("normalization_3_2.rs"); + write_slice_pairs(&mut writer, "NORMALIZATION_3_2", "(u32, u32)", &mut changes); +} + fn generate_decomp(decomp_lines: Vec<(u32, String)>) { let mut writer = open_writer("decomp.rs"); @@ -368,39 +491,9 @@ fn generate_decomp(decomp_lines: Vec<(u32, String)>) { &mut writer, "DECOMP_COMPAT", "(u32, DecompositionType, usize)", - &mut values, + &values, ); - write_slice_unordered(&mut writer, "DECOMP_RANGE", "u32", &mut decomp_ranges); - - // Normalization corrections is super small - only a handful chars at the time of writing. - let reader = UnicodeLineReader::from_file_name("NormalizationCorrections.txt", true); - let mut values = Vec::new(); - for line in reader { - let field = line.field( - NonZeroUsize::new(1).unwrap(), - Some(&format!( - "field 2 missing from NormalizationCorrections: {}", - line.line - )), - ); - let original = u32::from_str_radix(field.trim(), 16).unwrap_or_else(|e| { - panic!("field 2 of decomp corrections should be a char in hex: {field} {e}") - }); - let version = line.field( - NonZeroUsize::new(3).unwrap(), - Some(&format!( - "field 4 of decomp corrections should be a UCD version: {}", - line.line - )), - ); - - // `version` = when the char was updated. Therefore, we use the incorrect chars past - // 3.2.0 but skip the chars fixed in 3.2.0 because they'll already be right. - if version != "3.2.0" { - values.push((line.start, original)) - } - } - write_slice_pairs(&mut writer, "DECOMP_UPDATES", "(u32, u32)", &mut values); + write_slice_unordered(&mut writer, "DECOMP_RANGE", "u32", &decomp_ranges); } fn generate_algo_names(names: Vec<(u32, Box)>) { @@ -449,6 +542,7 @@ fn generate_algo_names(names: Vec<(u32, Box)>) { /// `lookup_character`. fn generate_name_lookups() { let mut aliases = BTreeMap::new(); + let mut alias_names = Vec::new(); for line in UnicodeLineReader::from_file_name("NameAliases.txt", true) { let name = line .field( @@ -459,10 +553,12 @@ fn generate_name_lookups() { )), ) .to_ascii_uppercase(); + alias_names.push(name.clone()); aliases.insert(name, line.start); } let mut sequences = BTreeMap::new(); + let mut sequence_names = Vec::new(); let mut sequences_reader = UnicodeLineReader::from_file_name("NamedSequences.txt", true); for line in sequences_reader.raw_iter() { let (name, codes) = line @@ -478,10 +574,25 @@ fn generate_name_lookups() { escaped.push_str(&format!("{cp:X}")); escaped.push('}'); } + sequence_names.push(name.clone()); sequences.insert(name, escaped); } let mut writer = open_writer("name_lookups.rs"); + // CPython's makeunicodedata.py reserves these private code points in UCD + // file order, not in the alphabetic order used by the lookup maps. + assert!(alias_names.len() < 0x200); + for (constant, names) in [ + ("CAPI_ALIAS_NAMES", alias_names), + ("CAPI_SEQUENCE_NAMES", sequence_names), + ] { + write_slice_raw(&mut writer, constant, "&str", names, |writer, names| { + for name in names { + writeln!(writer, "{name:?},").unwrap(); + } + }); + } + write_slice_raw( &mut writer, "NAME_ALIASES", @@ -513,7 +624,7 @@ fn generate_name_lookups() { /// Drive parsers that require the full 3.2.0 data. /// /// As the full data set is HUGE, it's more efficient to parse it once then delegate to subparsers. -fn full_data_parsers_3_2(tx: mpsc::Sender>) { +fn full_data_parsers_3_2(tx: mpsc::Sender) { let reader = UnicodeLineReader::from_file_name("UnicodeData-3.2.0.txt", false); // `DerivedNumericValues` writes the value rounded to a few digits, so the @@ -556,9 +667,15 @@ fn full_data_parsers_3_2(tx: mpsc::Sender>) { } } + let mut assigned_ranges: Vec<(u32, u32)> = membership_set.iter().copied().collect(); + let (chunks, &[]) = range_membership.as_chunks::<2>() else { + panic!("Range membership is always in pairs ('First>' and 'Last>'"); + }; + assigned_ranges.extend(chunks.iter().copied().map(<(u32, u32)>::from)); + // Now delegate to parsers that need the full data. generate_membership_3_2(membership_set, range_membership); - generate_numeric_value(ucd32_fractions, tx); + generate_numeric_value(ucd32_fractions, assigned_ranges, tx); } /// Generate a compressed array of Unicode 3.2 membership. @@ -597,7 +714,8 @@ fn generate_membership_3_2(membership_set: BTreeSet<(u32, u32)>, range_membershi fn generate_numeric_value( ucd32_fractions: BTreeMap, - tx: mpsc::Sender>, + assigned_ranges: Vec<(u32, u32)>, + tx: mpsc::Sender, ) { let mut ucd32_diffs = BTreeMap::new(); let numeric_32 = UnicodeLineReader::from_file_name("DerivedNumericValues-3.2.0.txt", false); @@ -617,8 +735,9 @@ fn generate_numeric_value( ucd32_diffs.insert((line.start, line.end), value); } + let mut values_3_2 = ucd32_diffs.clone(); let ucd_latest = UnicodeLineReader::from_file_name("DerivedNumericValues.txt", true); - let mut values_latest = Vec::new(); + let mut ranges_latest = Vec::new(); for line in ucd_latest { // Field 3 holds the fraction; field 1 rounds it to a few digits. let field = line.field( @@ -637,7 +756,7 @@ fn generate_numeric_value( { ucd32_diffs.remove(&(line.start, line.end)); } - values_latest.push((line.start, line.end, value)); + ranges_latest.push((line.start, line.end, value)); } // Han ideograph supplement. This data is huge but we don't need a separate thread for it @@ -668,29 +787,113 @@ fn generate_numeric_value( let field = normalize_unihan_numeric(field); let value = parse_numeric_value(&field); ucd32_diffs.insert((line.start, line.end), value); + values_3_2.insert((line.start, line.end), value); + } + } + + // A character can be assigned in Unicode 3.2 without having a numeric + // value there. Preserve those cases as explicit NumericType::None diffs + // so the runtime does not fall back to a later numeric value. + let mut none_code_points = BTreeSet::new(); + for &(start, end, _) in &ranges_latest { + for ch in start..=end { + let assigned = assigned_ranges + .iter() + .any(|&(assigned_start, assigned_end)| assigned_start <= ch && ch <= assigned_end); + let numeric = values_3_2 + .keys() + .any(|&(numeric_start, numeric_end)| numeric_start <= ch && ch <= numeric_end); + if assigned && !numeric { + none_code_points.insert(ch); + } + } + } + + let mut none_diffs = Vec::new(); + let mut iter = none_code_points.into_iter(); + if let Some(mut start) = iter.next() { + let mut end = start; + for ch in iter { + if ch != end + 1 { + none_diffs.push((start, end)); + start = ch; + } + end = ch; } + none_diffs.push((start, end)); } + // Compress the keys and values. There are two classes of tables: indices and values. Values are + // repetitive so they can compressed into a sorted vector. Indices can be stored in eight byte + // pairs instead of the 16 byte alignment that would be required to store (u32, u32, f64). + let values = ranges_latest + .iter() + .map(|&(_, _, v)| F64Ord(v)) + .chain(ucd32_diffs.iter().map(|((_, _), v)| F64Ord(*v))) + .collect::>() + .into_iter() + .map(|f| f.0) + .collect::>(); let mut writer = open_writer("numeric_value_3_2.rs"); - write_slice_debug( + write_slice_dbg_unordered(&mut writer, "NUMERIC_VALUES", "f64", &values); + + let mut numeric_ranges: Vec<_> = ranges_latest + .iter() + .copied() + .map(|(start, end, value)| { + let offset: u16 = (end - start).try_into().unwrap(); + let index: u16 = values + .binary_search_by(|f| f.total_cmp(&value)) + .unwrap() + .try_into() + .unwrap(); + (start, offset, index) + }) + .collect(); + numeric_ranges.sort_unstable_by_key(|(start, _, _)| *start); + write_slice_dbg_unordered( &mut writer, - "NUMERIC_VALUES", - "(u32, u32, f64)", - &mut values_latest, + "NUMERIC_RANGES", + "(u32, u16, u16)", + &numeric_ranges, ); - let mut ucd32_diffs: Vec<_> = ucd32_diffs - .into_iter() - .map(|((start, end), value)| (start, end, value)) + #[cfg(feature = "ucd_3_2_0")] + let numeric_vals_diff: Vec<_> = ucd32_diffs + .iter() + .map(|(&(start, end), &value)| { + let offset: u16 = (end - start).try_into().unwrap(); + let index: u16 = values + .binary_search_by(|f| f.total_cmp(&value)) + .unwrap() + .try_into() + .unwrap(); + (start, offset, index) + }) .collect(); - write_slice_debug( + + #[cfg(not(feature = "ucd_3_2_0"))] + let numeric_vals_diff: Vec<(u32, u16, u16)> = Vec::new(); + + write_slice_dbg_unordered( &mut writer, "NUMERIC_VALUES_DIFF", - "(u32, u32, f64)", - &mut ucd32_diffs, + "(u32, u16, u16)", + &numeric_vals_diff, ); - tx.send(ucd32_diffs) - .expect("sending numeric value diffs to numeric type thread should succeed"); + #[cfg(feature = "ucd_3_2_0")] + let value_diffs: Vec<(u32, u32, f64)> = ucd32_diffs + .into_iter() + .map(|((start, end), value)| (start, end, value)) + .collect(); + #[cfg(not(feature = "ucd_3_2_0"))] + let value_diffs: Vec<(u32, u32, f64)> = Vec::new(); + + tx.send(NumericTypeDiffs { + value_diffs, + none_diffs, + }) + .expect("sending numeric value diffs to numeric type thread should succeed"); } fn general_category_3_2() { @@ -834,11 +1037,11 @@ fn combining_class_3_2() { ); } -fn generate_numeric_type_3_2(rx: mpsc::Receiver>) { +fn generate_numeric_type_3_2(rx: mpsc::Receiver) { let mut writer = open_writer("num_type_3_2.rs"); let reader = UnicodeLineReader::from_file_name("DerivedNumericType-3.2.0.txt", false); - let mut values = Vec::new(); + let mut values = BTreeMap::new(); for line in reader { let field = line.field( NonZeroUsize::new(1).unwrap(), @@ -857,27 +1060,90 @@ fn generate_numeric_type_3_2(rx: mpsc::Receiver>) { }); if differs { - values.push((line.start, line.end, id)); + for ch in line.start..=line.end { + values.insert(ch, id); + } } } // Extend the 3.2.0 differences with the Unihan data. It's possible that the type matters but we // will treat them as Numeric for now. - let diffs = rx.recv_timeout(Duration::from_mins(10)).unwrap(); - values.extend( - diffs - .into_iter() - .map(|(start, end, _)| (start, end, "NumericType::Numeric")), - ); + let NumericTypeDiffs { + value_diffs, + none_diffs, + } = rx.recv_timeout(Duration::from_mins(10)).unwrap(); + for (start, end, _) in value_diffs { + for ch in start..=end { + values.insert(ch, "NumericType::Numeric"); + } + } + for (start, end) in none_diffs { + for ch in start..=end { + values.insert(ch, "NumericType::None"); + } + } + + let mut ranges = Vec::new(); + let mut iter = values.into_iter(); + if let Some((mut start, mut id)) = iter.next() { + let mut end = start; + for (ch, next_id) in iter { + if ch == end + 1 && next_id == id { + end = ch; + } else { + ranges.push((start, end, id)); + start = ch; + end = ch; + id = next_id; + } + } + ranges.push((start, end, id)); + } write_slice_display( &mut writer, "NUMERIC_TYPE_DIFF", "(u32, u32, NumericType)", - &mut values, + &mut ranges, ); } +/// Block names and ranges from the same Unicode release as the other latest tables. +fn generate_blocks() { + let mut writer = open_writer("blocks.rs"); + write_slice_pre(&mut writer, "BLOCKS", "(u32, u32, &str)"); + for line in UnicodeLineReader::from_file_name("Blocks.txt", true) { + let name = line.field(NonZeroUsize::new(1).unwrap(), None); + writeln!(writer, "({}, {}, {name:?}),", line.start, line.end).unwrap(); + } + write_slice_post(&mut writer); +} + +/// The version string of the latest Unicode database bundled with the standard +/// library (`unicodedata.unidata_version`). +pub fn unicode_version() { + // Report the vendored database version, not the compiler's Unicode version. + let version = open_reader("NameAliases.txt", true) + .lines() + .next() + .expect("should be able to read from vendored NameAliases.txt") + .expect("vendored NameAliases.txt must start with its Unicode version"); + let version = version + .strip_prefix("# NameAliases-") + .expect("NameAliases.txt doesn't start with version info") + .strip_suffix(".txt") + .unwrap() + .trim(); + + println!("cargo:rustc-env=UNICODE_VERSION={version}"); +} + +/// Parsers that are standalone and read small files. +fn small_parsers() { + generate_blocks(); + unicode_version(); +} + /// Run each UCD parser in parallel. fn drive_parsers() { let parsers = [ @@ -888,6 +1154,8 @@ fn drive_parsers() { binary_props_3_2, combining_class_3_2, generate_name_lookups, + generate_case_mappings, + small_parsers, ]; let mut handles = Vec::with_capacity(parsers.len() + 2); @@ -1070,6 +1338,31 @@ fn parse_numeric_value(text: &str) -> f64 { numerator / denominator } +#[derive(Clone, Copy)] +struct F64Ord(pub f64); + +impl PartialEq for F64Ord { + fn eq(&self, other: &Self) -> bool { + assert!(!self.0.is_nan()); + assert!(!other.0.is_nan()); + self.0.total_cmp(&other.0) == Ordering::Equal + } +} + +impl Eq for F64Ord {} + +impl PartialOrd for F64Ord { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for F64Ord { + fn cmp(&self, other: &Self) -> Ordering { + self.0.total_cmp(&other.0) + } +} + fn main() { println!("cargo:rerun-if-changed=unicode/ucd32"); println!("cargo:rerun-if-changed=unicode/latest"); diff --git a/crates/unicode/src/case.rs b/crates/unicode/src/case.rs index d5dd4c3b621..240bbf02ee5 100644 --- a/crates/unicode/src/case.rs +++ b/crates/unicode/src/case.rs @@ -7,10 +7,8 @@ //! predicates expose the derived properties that `str.islower`/`isupper`/ //! `istitle` need. //! -//! Plain `str.lower`/`str.upper` have no such context beyond the final-sigma -//! rule that `str::to_lowercase` already applies, so they stay on -//! `rustpython_wtf8::Wtf8::to_lowercase`/`to_uppercase` rather than being -//! duplicated here. +//! All Unicode mappings use ICU data, matching the rest of this crate rather +//! than the Unicode version bundled with the Rust compiler. // spell-checker:ignore ΟΔΟΣ Οδος @@ -22,12 +20,18 @@ use alloc::{ use icu_casemap::options::{LeadingAdjustment, TitlecaseOptions}; use icu_casemap::{CaseMapper, TitlecaseMapper}; use icu_locale::LanguageIdentifier; -use icu_properties::props::{ - BinaryProperty, CaseIgnorable, Cased, EnumeratedProperty, GeneralCategory, Lowercase, Uppercase, -}; +use icu_properties::props::{EnumeratedProperty, GeneralCategory}; use rustpython_wtf8::{CodePoint, Wtf8, Wtf8Buf, Wtf8Chunk}; use writeable::Writeable; +include!(concat!(env!("OUT_DIR"), "/generated/case_mappings.rs")); + +#[inline(always)] +fn lookup_page(ch: char, index: &[u16], pages: &[u16]) -> usize { + let n = ch as usize; + usize::from(pages[usize::from(index[n >> 8]) * 256 + (n & 255)]) +} + // Code-point mappings /// Simple (one-to-one) lowercase mapping of `c` (`Py_UNICODE_TOLOWER`). @@ -65,13 +69,13 @@ pub fn simple_fold(c: char) -> char { /// Whether `c` has the `Lowercase` property. #[must_use] pub fn is_lowercase(c: char) -> bool { - Lowercase::for_char(c) + lookup_page(c, CASE_FLAGS_INDEX, CASE_FLAGS_PAGES) & 4 != 0 } /// Whether `c` has the `Uppercase` property. #[must_use] pub fn is_uppercase(c: char) -> bool { - Uppercase::for_char(c) + lookup_page(c, CASE_FLAGS_INDEX, CASE_FLAGS_PAGES) & 8 != 0 } /// Whether `c` is a titlecase letter (general category `Lt`). @@ -83,17 +87,93 @@ pub fn is_titlecase(c: char) -> bool { /// Whether `c` has the `Cased` property. #[must_use] pub fn is_cased(c: char) -> bool { - Cased::for_char(c) + lookup_page(c, CASE_FLAGS_INDEX, CASE_FLAGS_PAGES) & 1 != 0 } /// Whether `c` has the `Case_Ignorable` property. #[must_use] pub fn is_case_ignorable(c: char) -> bool { - CaseIgnorable::for_char(c) + lookup_page(c, CASE_FLAGS_INDEX, CASE_FLAGS_PAGES) & 2 != 0 } // String-level mappings +#[inline] +fn ascii_prefix(text: &str) -> (usize, String) { + let end = text + .bytes() + .position(|b| !b.is_ascii()) + .unwrap_or(text.len()); + let mut out = Vec::with_capacity(text.len()); + if UPPERCASE { + out.extend(text.as_bytes()[..end].iter().map(u8::to_ascii_uppercase)); + } else { + out.extend(text.as_bytes()[..end].iter().map(u8::to_ascii_lowercase)); + } + // SAFETY: the converted prefix contains only ASCII. + (end, unsafe { String::from_utf8_unchecked(out) }) +} + +/// Lowercase `text` using the root locale and final-sigma context. +#[must_use] +pub fn lowercase_str(text: &str) -> String { + let (prefix, mut out) = ascii_prefix::(text); + let mut chars = text[prefix..].chars(); + while let Some(ch) = chars.next() { + if ch.is_ascii() { + out.push(ch.to_ascii_lowercase()); + } else if ch == 'Σ' { + out.push(handle_capital_sigma( + text, + text.len() - chars.as_str().len() - ch.len_utf8(), + )); + } else { + let index = lookup_page(ch, LOWER_INDEX, LOWER_PAGES); + push_mapping(ch, index, LOWER_MAPPINGS, |ch| out.push(ch)); + } + } + out +} + +fn lowercase_utf8(text: &str, out: &mut FmtWriter<'_>) { + for (i, ch) in text.char_indices() { + lowercase_or_sigma(ch, text, i, out); + } +} + +/// Lowercase `text`, passing lone surrogates through unchanged. +#[must_use] +pub fn lowercase_wtf8(text: &Wtf8) -> Wtf8Buf { + map_wtf8(text, lowercase_utf8) +} + +/// Uppercase `text` using the root locale. +#[must_use] +pub fn uppercase_str(text: &str) -> String { + let (prefix, mut out) = ascii_prefix::(text); + for ch in text[prefix..].chars() { + if ch.is_ascii() { + out.push(ch.to_ascii_uppercase()); + } else { + let index = lookup_page(ch, UPPER_INDEX, UPPER_PAGES); + push_mapping(ch, index, UPPER_MAPPINGS, |ch| out.push(ch)); + } + } + out +} + +fn uppercase_utf8(text: &str, out: &mut FmtWriter<'_>) { + for ch in text.chars() { + uppercase_char(ch, out); + } +} + +/// Uppercase `text`, passing lone surrogates through unchanged. +#[must_use] +pub fn uppercase_wtf8(text: &Wtf8) -> Wtf8Buf { + map_wtf8(text, uppercase_utf8) +} + /// Full Unicode case fold of `text` (`str.casefold`). #[must_use] pub fn casefold_str(text: &str) -> String { @@ -257,22 +337,23 @@ fn titlecase_segment(s: &str, out: &mut FmtWriter<'_>) { .expect("writing to an in-memory buffer cannot fail"); } +#[inline] fn lowercase_or_sigma(ch: char, s: &str, i: usize, out: &mut FmtWriter<'_>) { let sigma = 'Σ'; - if ch == sigma { + if ch.is_ascii() { + push_char(ch.to_ascii_lowercase(), out); + } else if ch == sigma { push_char(handle_capital_sigma(s, i), out); } else { - for ch in ch.to_lowercase() { - push_char(ch, out); - } + let index = lookup_page(ch, LOWER_INDEX, LOWER_PAGES); + push_mapping(ch, index, LOWER_MAPPINGS, |ch| push_char(ch, out)); } } // Handle context-sensitive sigma. // -// Sigma is handled as a special case. This is more efficient than using icu4x -// to scan the entire string with CaseMapper because CaseMapper would allocate -// to produce a new string. +// Character-by-character title/capitalize/swapcase mappings need the context +// from the original string, as in CPython's lower_ucs4. fn handle_capital_sigma(s: &str, i: usize) -> char { let (left, rest) = s.split_at(i); let right = &rest['Σ'.len_utf8()..]; @@ -292,19 +373,59 @@ fn handle_capital_sigma(s: &str, i: usize) -> char { fn swapcase_utf8(s: &str, out: &mut FmtWriter<'_>) { for (i, ch) in s.char_indices() { - if ch.is_uppercase() { + if ch.is_ascii() { + let mapped = if ch.is_ascii_uppercase() { + ch.to_ascii_lowercase() + } else { + ch.to_ascii_uppercase() + }; + push_char(mapped, out); + } else if is_uppercase(ch) { lowercase_or_sigma(ch, s, i, out); - } else if ch.is_lowercase() { - for ch in ch.to_uppercase() { - push_char(ch, out); - } + } else if is_lowercase(ch) { + uppercase_char(ch, out); } else { push_char(ch, out); } } } +#[inline] +fn uppercase_char(ch: char, out: &mut FmtWriter<'_>) { + if ch.is_ascii() { + push_char(ch.to_ascii_uppercase(), out); + } else { + let index = lookup_page(ch, UPPER_INDEX, UPPER_PAGES); + push_mapping(ch, index, UPPER_MAPPINGS, |ch| push_char(ch, out)); + } +} + +#[inline(always)] +fn push_mapping(ch: char, index: usize, mappings: &[[char; 3]], mut push: impl FnMut(char)) { + if index == 0 { + push(ch); + return; + } + match mappings[index] { + [a, '\0', _] => push(a), + [a, b, '\0'] => { + push(a); + push(b); + } + [a, b, c] => { + push(a); + push(b); + push(c); + } + } +} + +#[inline] fn push_char(ch: char, out: &mut FmtWriter<'_>) { + if ch.is_ascii() { + out.0.push(ch as u8); + return; + } let mut buf = [0u8; 4]; out.0.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes()); } @@ -321,13 +442,53 @@ impl core::fmt::Write for FmtWriter<'_> { #[cfg(test)] mod tests { + use alloc::{format, string::ToString}; use rustpython_wtf8::{CodePoint, Wtf8Buf}; use super::{ capitalize_str, casefold_str, is_case_ignorable, is_cased, is_lowercase, is_titlecase, - is_uppercase, simple_lowercase, simple_uppercase, swapcase_str, title_str, title_wtf8, + is_uppercase, lowercase_str, lowercase_wtf8, simple_lowercase, simple_uppercase, + swapcase_str, title_str, title_wtf8, uppercase_str, uppercase_wtf8, }; + #[test] + fn full_case_mappings_use_unicode_database() { + // These characters acquired mappings in Unicode 18. Rust's Unicode + // data can be newer than the Unicode 17 database used by Python 3.15. + for c in ['\u{0277}', '\u{027c}', '\u{ab4b}', '\u{ab4c}'] { + let s = c.to_string(); + assert_eq!(uppercase_str(&s), s); + assert_eq!(swapcase_str(&s), s); + } + for c in ['\u{a7dd}', '\u{a7e2}', '\u{ab6c}', '\u{ab6d}'] { + let s = c.to_string(); + assert_eq!(lowercase_str(&s), s); + assert_eq!(capitalize_str(&format!("a{s}")), format!("A{s}")); + assert_eq!(title_str(&format!("A{s}")), format!("A{s}")); + assert_eq!(swapcase_str(&s), s); + assert!(!is_uppercase(c)); + } + assert_eq!(lowercase_str("ΟΔΟΣ"), "οδος"); + assert_eq!(lowercase_str("AΣ\u{0301}"), "aς\u{0301}"); + assert_eq!(lowercase_str("AΣ\u{0301}A"), "aσ\u{0301}a"); + assert_eq!(uppercase_str("ß"), "SS"); + } + + #[test] + fn full_case_mappings_preserve_surrogates_and_sigma_boundaries() { + let mut text = Wtf8Buf::from("AΣ"); + text.push(CodePoint::from_u32(0xd800).unwrap()); + text.push_str("ΣAß"); + let mut lower = Wtf8Buf::from("aς"); + lower.push(CodePoint::from_u32(0xd800).unwrap()); + lower.push_str("σaß"); + let mut upper = Wtf8Buf::from("AΣ"); + upper.push(CodePoint::from_u32(0xd800).unwrap()); + upper.push_str("\u{03a3}ASS"); + assert_eq!(lowercase_wtf8(&text), lower); + assert_eq!(uppercase_wtf8(&text), upper); + } + #[test] fn casefold_full_mappings() { // ß case-folds to "ss" @@ -347,6 +508,31 @@ mod tests { assert_eq!(simple_lowercase('Dž'), 'dž'); } + #[test] + fn generated_case_data_matches_icu() { + use icu_properties::props::{BinaryProperty, CaseIgnorable, Cased, Lowercase, Uppercase}; + let mapper = icu_casemap::CaseMapper::new(); + let locale = icu_locale::LanguageIdentifier::UNKNOWN; + for ch in (0..=0x10ffff).filter_map(char::from_u32) { + let mut buf = [0; 4]; + let text = ch.encode_utf8(&mut buf); + assert_eq!( + lowercase_str(text), + mapper.lowercase_to_string(text, &locale), + "{ch:?}" + ); + assert_eq!( + uppercase_str(text), + mapper.uppercase_to_string(text, &locale), + "{ch:?}" + ); + assert_eq!(is_cased(ch), Cased::for_char(ch), "{ch:?}"); + assert_eq!(is_lowercase(ch), Lowercase::for_char(ch), "{ch:?}"); + assert_eq!(is_uppercase(ch), Uppercase::for_char(ch), "{ch:?}"); + assert_eq!(is_case_ignorable(ch), CaseIgnorable::for_char(ch), "{ch:?}"); + } + } + #[test] fn casing_predicates() { assert!(is_lowercase('a')); diff --git a/crates/unicode/src/data.rs b/crates/unicode/src/data.rs index 381a180a420..6a8e58c1e68 100644 --- a/crates/unicode/src/data.rs +++ b/crates/unicode/src/data.rs @@ -19,21 +19,50 @@ use icu_properties::props::{ }; use rustpython_wtf8::CodePoint; +pub const UNICODE_VERSION: &str = env!("UNICODE_VERSION"); +pub const UNICODE_VERSION_LEGACY: &str = "3.2.0"; + +// Latest Unicode +include!(concat!(env!("OUT_DIR"), "/generated/blocks.rs")); include!(concat!(env!("OUT_DIR"), "/generated/algo_names.rs")); include!(concat!(env!("OUT_DIR"), "/generated/name_lookups.rs")); +include!(concat!(env!("OUT_DIR"), "/generated/decomp.rs")); +include!(concat!(env!("OUT_DIR"), "/generated/numeric_value_3_2.rs")); + +// Unicode 3.2.0 +#[cfg(feature = "ucd_3_2_0")] include!(concat!(env!("OUT_DIR"), "/generated/bidi_class_3_2.rs")); +#[cfg(feature = "ucd_3_2_0")] include!(concat!(env!("OUT_DIR"), "/generated/binary_props_3_2.rs")); +#[cfg(feature = "ucd_3_2_0")] include!(concat!( env!("OUT_DIR"), "/generated/combining_class_3_2.rs" )); -include!(concat!(env!("OUT_DIR"), "/generated/decomp.rs")); +#[cfg(feature = "ucd_3_2_0")] include!(concat!(env!("OUT_DIR"), "/generated/eaw_3_2.rs")); +#[cfg(feature = "ucd_3_2_0")] include!(concat!(env!("OUT_DIR"), "/generated/gen_cat_3_2.rs")); +#[cfg(feature = "ucd_3_2_0")] include!(concat!(env!("OUT_DIR"), "/generated/membership_3_2.rs")); -include!(concat!(env!("OUT_DIR"), "/generated/numeric_value_3_2.rs")); +#[cfg(feature = "ucd_3_2_0")] include!(concat!(env!("OUT_DIR"), "/generated/num_type_3_2.rs")); +#[cfg(not(feature = "ucd_3_2_0"))] +const BIDI_CLASS_DIFF: &[(u32, u32, BidiClass)] = &[]; +#[cfg(not(feature = "ucd_3_2_0"))] +const BIDI_MIRRORED: &[(u32, u32)] = &[]; +#[cfg(not(feature = "ucd_3_2_0"))] +const COMBINING_CLASS: &[(u32, u32, CanonicalCombiningClass)] = &[]; +#[cfg(not(feature = "ucd_3_2_0"))] +const EAST_ASIAN_WIDTH: &[(u32, u32, EastAsianWidth)] = &[]; +#[cfg(not(feature = "ucd_3_2_0"))] +const GENERAL_CATEGORY: &[(u32, u32, GeneralCategory)] = &[]; +#[cfg(not(feature = "ucd_3_2_0"))] +const MEMBERSHIP_3_2: &[(u32, u32)] = &[]; +#[cfg(not(feature = "ucd_3_2_0"))] +const NUMERIC_TYPE_DIFF: &[(u32, u32, NumericType)] = &[]; + #[derive(Clone, Copy)] enum DecompositionType { Compat, @@ -98,25 +127,21 @@ impl AlgorithmicName { fn check_name(search_name: &str) -> Option { // CPython compares derived-name prefixes case-insensitively // (`PyOS_strnicmp` in `_getcode`). - let folded: String = search_name - .chars() - .map(|c| c.to_ascii_uppercase()) - .collect(); - if let Some(without_base) = folded.strip_prefix(Self::TangutIdeograph.name_base()) { - // `parse_hex_code` does not skip spaces around the digits. - let hex = without_base.strip_prefix('-')?; - // `_getcode` / `parse_hex_code`: 4–6 digits, no leading zero. - if hex.len() < 4 || hex.len() > 6 || hex.starts_with('0') { - return None; - } - let cp = u32::from_str_radix(hex, 16).ok()?; - let ch = char::from_u32(cp)?; - if lookup_table(ALGO_NAMES, ch)? == Self::TangutIdeograph { - return Some(ch); - } + let tangut = Self::TangutIdeograph.name_base(); + let (head, tail) = search_name.split_at_checked(tangut.len())?; + if !head.eq_ignore_ascii_case(tangut) { + return None; } - None + // `parse_hex_code` does not skip spaces around the digits. + let hex = tail.strip_prefix('-')?; + // `_getcode` / `parse_hex_code`: 4–6 digits, no leading zero. + if hex.len() < 4 || hex.len() > 6 || hex.starts_with('0') { + return None; + } + let cp = u32::from_str_radix(hex, 16).ok()?; + let ch = char::from_u32(cp)?; + (lookup_table(ALGO_NAMES, ch)? == Self::TangutIdeograph).then_some(ch) } } @@ -130,22 +155,40 @@ pub enum LookupResult { Sequence(&'static str), } -fn fold_lookup_name(name: &str) -> String { - name.chars().map(|c| c.to_ascii_uppercase()).collect() +fn cmp_caseless(a: &str, b: &str) -> Ordering { + a.bytes() + .map(|b| b.to_ascii_uppercase()) + .cmp(b.bytes().map(|b| b.to_ascii_uppercase())) +} + +/// Name used by `namereplace`, including CPython's private alias and sequence +/// records. Unlike `unicodedata.name`, this consults two private-use ranges +/// populated in UCD source-file order by CPython's database generator. +#[must_use] +pub fn name_for_namereplace(code: u32) -> Option { + let name = code + .checked_sub(0xF0000) + .and_then(|i| CAPI_ALIAS_NAMES.get(i as usize)) + .or_else(|| { + code.checked_sub(0xF0200) + .and_then(|i| CAPI_SEQUENCE_NAMES.get(i as usize)) + }); + if let Some(name) = name { + return Some(String::from(*name)); + } + char::from_u32(code).and_then(character_name) } fn lookup_alias(name: &str) -> Option { - let key = fold_lookup_name(name); NAME_ALIASES - .binary_search_by_key(&key.as_str(), |(n, _)| *n) + .binary_search_by(|(a, _)| cmp_caseless(a, name)) .ok() .map(|i| NAME_ALIASES[i].1) } fn lookup_named_sequence(name: &str) -> Option<&'static str> { - let key = fold_lookup_name(name); NAMED_SEQUENCES - .binary_search_by_key(&key.as_str(), |(n, _)| *n) + .binary_search_by(|(a, _)| cmp_caseless(a, name)) .ok() .map(|i| NAMED_SEQUENCES[i].1) } @@ -166,12 +209,11 @@ fn lookup_table(table: &[(u32, u32, T)], ch: char) -> Option { .map(|i| table[i].2) } -#[cold] -#[inline(never)] -#[must_use] -pub fn membership_3_2(ch: u32) -> bool { - MEMBERSHIP_3_2 - .binary_search_by(|&(start, end)| { +fn lookup_table_range(table: &[(u32, u16, u16)], ch: char) -> Option { + let ch = ch as u32; + table + .binary_search_by(|&(start, offset, _)| { + let end = start + offset as u32; if ch > end { Ordering::Less } else if ch < start { @@ -180,37 +222,40 @@ pub fn membership_3_2(ch: u32) -> bool { Ordering::Equal } }) - .is_ok() + .ok() + .map(|i| table[i].2) } -fn lookup_property_diff( - table: &[(u32, u32, T)], - diff: &[(u32, u32, T)], - ch: char, - modern: bool, -) -> Option { - if modern { - lookup_table(table, ch) +fn lookup_numeric_value(ch: char, modern: bool) -> Option { + let i = if modern { + lookup_table_range(NUMERIC_RANGES, ch) } else { cold_path(); - lookup_table(diff, ch).or_else(|| { + lookup_table_range(NUMERIC_VALUES_DIFF, ch).or_else(|| { membership_3_2(ch as u32) - .then(|| lookup_table(table, ch)) + .then(|| lookup_table_range(NUMERIC_RANGES, ch)) .flatten() }) - } + }?; + + Some(NUMERIC_VALUES[i as usize]) } -/// The version string of the latest Unicode database bundled with the standard -/// library (`unicodedata.unidata_version`). +#[cold] +#[inline(never)] #[must_use] -pub fn unicode_version() -> String { - format!( - "{}.{}.{}", - char::UNICODE_VERSION.0, - char::UNICODE_VERSION.1, - char::UNICODE_VERSION.2 - ) +pub fn membership_3_2(ch: u32) -> bool { + MEMBERSHIP_3_2 + .binary_search_by(|&(start, end)| { + if ch > end { + Ordering::Less + } else if ch < start { + Ordering::Greater + } else { + Ordering::Equal + } + }) + .is_ok() } /// Look up a name in the latest UCD (`unicodedata.lookup`). @@ -241,13 +286,30 @@ pub fn character_name(ch: char) -> Option { .or_else(|| lookup_table(ALGO_NAMES, ch).map(|v| v.to_name(ch))) } +/// Unicode block name, including ranges containing surrogates or unassigned points. +#[must_use] +pub fn block(c: CodePoint) -> &'static str { + let c = c.to_u32(); + BLOCKS + .binary_search_by(|&(start, end, _)| { + if c > end { + Ordering::Less + } else if c < start { + Ordering::Greater + } else { + Ordering::Equal + } + }) + .map_or("No_Block", |i| BLOCKS[i].2) +} + /// A view over the Unicode character database at a fixed version. /// /// `modern` selects the latest bundled UCD; otherwise the Unicode 3.2.0 tables /// used by `unicodedata.ucd_3_2_0` are consulted. #[derive(Debug, Clone, Copy)] pub struct Ucd { - modern: bool, + pub(crate) modern: bool, } impl Ucd { @@ -274,9 +336,21 @@ impl Ucd { #[must_use] pub fn lookup(self, search_name: &str) -> Option { if let Some(ch) = unicode_names2::character(search_name) + .filter(|&ch| { + character_name(ch).is_some_and(|name| name.eq_ignore_ascii_case(search_name)) + }) .or_else(|| AlgorithmicName::check_name(search_name)) { - return self.membership(ch).then_some(LookupResult::Character(ch)); + if self.modern { + return Some(LookupResult::Character(ch)); + } + cold_path(); + + // 3.2.0 doesn't have aliases but unicode_names2 supports aliases so reject them. + if lookup_alias(search_name).is_some() { + return None; + } + return Some(LookupResult::Character(ch)); } if !self.modern { return None; @@ -304,38 +378,30 @@ impl Ucd { #[must_use] pub fn bidirectional(&self, c: CodePoint) -> &'static str { - c.to_char() - .and_then(|c| { - if self.modern { - Some(BidiClass::for_char(c)) - } else { - cold_path(); - lookup_table(BIDI_CLASS_DIFF, c) - .or_else(|| membership_3_2(c as u32).then(|| BidiClass::for_char(c))) - } - }) - .as_ref() - .map(BidiClass::short_name) - .unwrap_or_default() + let Some(c) = c.to_char() else { + // Surrogates have bidi class L in both the current and 3.2 UCD. + return "L"; + }; + let class = if self.modern { + Some(BidiClass::for_char(c)) + } else { + cold_path(); + lookup_table(BIDI_CLASS_DIFF, c) + .or_else(|| membership_3_2(c as u32).then(|| BidiClass::for_char(c))) + }; + class.as_ref().map_or_default(BidiClass::short_name) } #[must_use] pub fn east_asian_width(&self, c: CodePoint) -> &'static str { c.to_char() .and_then(|c| { - if self.modern { + if self.modern || GeneralCategory::for_char(c) == GeneralCategory::Unassigned { Some(EastAsianWidth::for_char(c)) } else { cold_path(); - // CPython overrides characters in the PUA for 3.2.0. - // Basic Multilingual Plane: - // https://en.wikipedia.org/wiki/Plane_(Unicode)#Basic_Multilingual_Plane - // https://en.wikipedia.org/wiki/Private_Use_Areas - // https://www.unicode.org/reports/tr11/tr11-10.html - // https://www.unicode.org/reports/tr11/ - // - // Currently, this implementation is incomplete because I can't figure - // out what CPython is doing. + // CPython keeps modern width defaults for still-unassigned characters. + // Assigned characters use their 3.2 width, or Neutral if new since 3.2. lookup_table(EAST_ASIAN_WIDTH, c) } }) @@ -387,30 +453,32 @@ impl Ucd { return String::new(); }; - // Decomposition is remarkable stable according to the normalization file, - // so the updates slice is very small - only about four char pairs. Linearly searching - // it is very fast. The file lists the original, incorrect decomp and the fixed char. - // For 3.2.0, we use the original decomp for compatibility while ignoring the update. - // - // Finally, we don't have to do anything for the latest UCD as it's already updated. - if self.modern - && let Some((_, original)) = DECOMP_UPDATES - .iter() - .find(|&&(codep, _original)| codep == ch as u32) - { - format!("{original:04X}") - } else if let Ok(i) = - DECOMP_COMPAT.binary_search_by_key(&(ch as u32), |&(codep, _, _)| codep) - { + if !self.membership(ch) { + return String::new(); + } + + // CPython exposes the full Hangul L/V/T decomposition, not ICU's + // non-recursive LV/T decomposition. + let code = ch as u32; + if (0xAC00..0xD7A4).contains(&code) { + let index = code - 0xAC00; + let leading = 0x1100 + index / (21 * 28); + let vowel = 0x1161 + (index % (21 * 28)) / 28; + let trailing = index % 28; + return if trailing == 0 { + format!("{leading:04X} {vowel:04X}") + } else { + format!("{leading:04X} {vowel:04X} {:04X}", 0x11A7 + trailing) + }; + } + + if let Ok(i) = DECOMP_COMPAT.binary_search_by_key(&(ch as u32), |&(codep, _, _)| codep) { // Compatibility decomposition // `icu4x` doesn't expose a non-recursive, compatibility decomposer so we // have to do it manually for now. let tag = DECOMP_COMPAT[i].1.type_tag(); let end = DECOMP_COMPAT[i].2; - let start = i - .checked_sub(1) - .map(|i| DECOMP_COMPAT[i].2) - .unwrap_or_default(); + let start = i.checked_sub(1).map_or_default(|i| DECOMP_COMPAT[i].2); let decomp = &DECOMP_RANGE[start..end]; let cap = decomp.len() * 10 + decomp.len() + tag.len() + 1; @@ -451,7 +519,7 @@ impl Ucd { pub fn digit(&self, c: CodePoint) -> Option { let expected = [NumericType::Decimal, NumericType::Digit]; self.numeric_type_matches(c, &expected).and_then(|ch| { - let value = lookup_property_diff(NUMERIC_VALUES, &[], ch, true)?; + let value = lookup_numeric_value(ch, true)?; let int = value as u64; (int as f64 == value).then_some(int) }) @@ -462,7 +530,7 @@ impl Ucd { pub fn decimal(&self, c: CodePoint) -> Option { let expected = [NumericType::Decimal]; self.numeric_type_matches(c, &expected).and_then(|ch| { - let value = lookup_property_diff(NUMERIC_VALUES, NUMERIC_VALUES_DIFF, ch, self.modern)?; + let value = lookup_numeric_value(ch, self.modern)?; let int = value as u64; (int as f64 == value).then_some(int) }) @@ -472,17 +540,16 @@ impl Ucd { #[must_use] pub fn numeric(&self, c: CodePoint) -> Option { let expected = &NumericType::ALL_VALUES[1..]; - self.numeric_type_matches(c, expected).and_then(|ch| { - lookup_property_diff(NUMERIC_VALUES, NUMERIC_VALUES_DIFF, ch, self.modern) - }) + self.numeric_type_matches(c, expected) + .and_then(|ch| lookup_numeric_value(ch, self.modern)) } #[must_use] pub fn unidata_version(&self) -> String { if self.modern { - unicode_version() + UNICODE_VERSION.into() } else { - "3.2.0".into() + UNICODE_VERSION_LEGACY.into() } } } @@ -491,12 +558,41 @@ impl Ucd { mod tests { use rustpython_wtf8::CodePoint; - use super::{LookupResult, Ucd, character_name, lookup_character, lookup_name}; + use super::{ + CAPI_ALIAS_NAMES, CAPI_SEQUENCE_NAMES, LookupResult, Ucd, character_name, lookup_character, + lookup_name, name_for_namereplace, + }; fn cp(ch: char) -> CodePoint { CodePoint::from(ch) } + #[test] + fn private_name_records_follow_ucd_file_order() { + for (start, names) in [(0xF0000, CAPI_ALIAS_NAMES), (0xF0200, CAPI_SEQUENCE_NAMES)] { + assert_eq!(name_for_namereplace(start - 1), None); + assert_eq!(name_for_namereplace(start + names.len() as u32), None); + for (index, &name) in names.iter().enumerate() { + let code = start + index as u32; + assert_eq!(name_for_namereplace(code).as_deref(), Some(name)); + assert_eq!(char::from_u32(code).and_then(character_name), None); + } + } + assert_eq!(name_for_namereplace(0xF0000).as_deref(), Some("NULL")); + assert_eq!(name_for_namereplace(0xD800), None); + assert_eq!(name_for_namereplace(0x110000), None); + assert_eq!( + name_for_namereplace(0x41).as_deref(), + Some("LATIN CAPITAL LETTER A") + ); + } + + #[test] + fn version_matches_vendored_database() { + assert_eq!(super::UNICODE_VERSION, "17.0.0"); + assert_eq!(Ucd::new(true).unidata_version(), "17.0.0"); + } + #[test] fn data_queries_match_unicodedata_behavior() { let ucd = Ucd::new(true); @@ -511,12 +607,14 @@ mod tests { } #[test] + #[cfg(feature = "ucd_3_2_0")] fn ucd_3_2_0_view_differs_from_modern() { let legacy = Ucd::new(false); assert_eq!(legacy.unidata_version(), "3.2.0"); } #[test] + #[cfg(feature = "ucd_3_2_0")] fn name_aliases_resolve_and_do_not_replace_the_official_name() { assert_eq!( lookup_character("LATIN CAPITAL LETTER GHA"), @@ -534,6 +632,7 @@ mod tests { } #[test] + #[cfg(feature = "ucd_3_2_0")] fn named_sequences_resolve_only_on_the_modern_view() { assert_eq!( lookup_name("LATIN SMALL LETTER R WITH TILDE"), diff --git a/crates/unicode/src/grapheme.rs b/crates/unicode/src/grapheme.rs new file mode 100644 index 00000000000..b8a097e3710 --- /dev/null +++ b/crates/unicode/src/grapheme.rs @@ -0,0 +1,180 @@ +//! Extended grapheme clusters over Python's full code point domain. +//! +//! State transitions and rule ordering follow CPython's Modules/unicodedata.c +//! at d220409a13b77de7a6c30abe16ea90db01528edc (Unicode 17.0.0). + +// spell-checker:ignore incb + +use icu_properties::{ + CodePointMapData, CodePointSetData, + props::{ExtendedPictographic, GraphemeClusterBreak as Gcb, IndicConjunctBreak as Incb}, +}; +use rustpython_wtf8::CodePoint; + +fn gcb(c: CodePoint) -> Gcb { + CodePointMapData::::new().get32(c.to_u32()) +} + +fn incb(c: CodePoint) -> Incb { + CodePointMapData::::new().get32(c.to_u32()) +} + +/// The long Grapheme_Cluster_Break property name. +#[must_use] +pub fn grapheme_cluster_break(c: CodePoint) -> &'static str { + match gcb(c) { + Gcb::CR => "CR", + Gcb::LF => "LF", + Gcb::Control => "Control", + Gcb::Extend => "Extend", + Gcb::L => "L", + Gcb::V => "V", + Gcb::T => "T", + Gcb::LV => "LV", + Gcb::LVT => "LVT", + Gcb::SpacingMark => "SpacingMark", + Gcb::Prepend => "Prepend", + Gcb::RegionalIndicator => "Regional_Indicator", + Gcb::ZWJ => "ZWJ", + _ => "Other", + } +} + +/// The long Indic_Conjunct_Break property name. +#[must_use] +pub fn indic_conjunct_break(c: CodePoint) -> &'static str { + match incb(c) { + Incb::Consonant => "Consonant", + Incb::Extend => "Extend", + Incb::Linker => "Linker", + _ => "None", + } +} + +/// Whether the code point has the Extended_Pictographic property. +#[must_use] +pub fn extended_pictographic(c: CodePoint) -> bool { + CodePointSetData::new::().contains32(c.to_u32()) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum ExtPictState { + Init, + Started, + Zwj, + Matched, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum IncbState { + Init, + Started, + Linker, + Matched, +} + +/// Streaming break state, initialized afresh at the requested slice start. +/// +/// A code point is consumed before its preceding boundary is returned. Keep +/// this state across cluster yields, rather than processing that point twice. +#[derive(Debug)] +pub struct GraphemeBreakState { + previous: Gcb, + pictographic: ExtPictState, + conjunct: IncbState, + regional_odd: bool, + started: bool, +} + +impl Default for GraphemeBreakState { + fn default() -> Self { + Self { + previous: Gcb::Other, + pictographic: ExtPictState::Init, + conjunct: IncbState::Init, + regional_odd: false, + started: false, + } + } +} + +impl GraphemeBreakState { + /// Consume one code point and report whether a new cluster starts here. + pub fn advance(&mut self, c: CodePoint) -> bool { + let current = gcb(c); + self.pictographic = if extended_pictographic(c) { + if self.pictographic == ExtPictState::Zwj { + ExtPictState::Matched + } else { + ExtPictState::Started + } + } else if matches!( + self.pictographic, + ExtPictState::Started | ExtPictState::Matched + ) { + match current { + Gcb::Extend => ExtPictState::Started, + Gcb::ZWJ => ExtPictState::Zwj, + _ => ExtPictState::Init, + } + } else { + ExtPictState::Init + }; + self.conjunct = match incb(c) { + Incb::Consonant => { + if self.conjunct == IncbState::Linker { + IncbState::Matched + } else { + IncbState::Started + } + } + Incb::Extend if self.conjunct != IncbState::Init => { + if self.conjunct == IncbState::Linker { + IncbState::Linker + } else { + IncbState::Started + } + } + Incb::Linker if self.conjunct != IncbState::Init => IncbState::Linker, + _ => IncbState::Init, + }; + self.regional_odd = current == Gcb::RegionalIndicator && !self.regional_odd; + let boundary = self.started && self.is_break(current); + self.previous = current; + self.started = true; + boundary + } + + fn is_break(&self, current: Gcb) -> bool { + let previous = self.previous; + // GB3, GB4, GB5: controls take precedence over attachment rules. + if previous == Gcb::CR && current == Gcb::LF { + return false; + } + if matches!(previous, Gcb::CR | Gcb::LF | Gcb::Control) + || matches!(current, Gcb::CR | Gcb::LF | Gcb::Control) + { + return true; + } + // GB6, GB7, GB8: Hangul syllables. + if previous == Gcb::L && matches!(current, Gcb::L | Gcb::V | Gcb::LV | Gcb::LVT) + || matches!(previous, Gcb::LV | Gcb::V) && matches!(current, Gcb::V | Gcb::T) + || matches!(previous, Gcb::LVT | Gcb::T) && current == Gcb::T + { + return false; + } + // GB9, GB9a, GB9b, GB9c, GB11. + if matches!(current, Gcb::Extend | Gcb::ZWJ | Gcb::SpacingMark) + || previous == Gcb::Prepend + || self.conjunct == IncbState::Matched + || self.pictographic == ExtPictState::Matched + { + return false; + } + // GB12, GB13: parity includes the current regional indicator. + if previous == Gcb::RegionalIndicator && current == previous { + return self.regional_odd; + } + true // GB999 + } +} diff --git a/crates/unicode/src/lib.rs b/crates/unicode/src/lib.rs index 319271b019e..5f43d25435d 100644 --- a/crates/unicode/src/lib.rs +++ b/crates/unicode/src/lib.rs @@ -12,8 +12,12 @@ extern crate alloc; pub mod case; pub mod classify; pub mod data; +pub mod grapheme; pub mod identifier; pub mod normalize; -pub use data::{LookupResult, Ucd, character_name, lookup_character, lookup_name, unicode_version}; +pub use data::{ + LookupResult, UNICODE_VERSION, UNICODE_VERSION_LEGACY, Ucd, character_name, lookup_character, + lookup_name, +}; pub use normalize::{NormalizeForm, is_normalized, normalize}; diff --git a/crates/unicode/src/normalize.rs b/crates/unicode/src/normalize.rs index e2f80d02439..44e417e0fe5 100644 --- a/crates/unicode/src/normalize.rs +++ b/crates/unicode/src/normalize.rs @@ -2,10 +2,20 @@ // spell-checker:ignore nfkc +use alloc::vec::Vec; use core::str::FromStr; +use icu_normalizer::properties::CanonicalComposition; use icu_normalizer::{ComposingNormalizerBorrowed, DecomposingNormalizerBorrowed}; -use rustpython_wtf8::{Wtf8, Wtf8Buf, Wtf8Chunk}; +use icu_properties::props::{CanonicalCombiningClass, EnumeratedProperty}; +use rustpython_wtf8::{CodePoint, Wtf8, Wtf8Buf, Wtf8Chunk}; + +use crate::Ucd; + +#[cfg(feature = "ucd_3_2_0")] +include!(concat!(env!("OUT_DIR"), "/generated/normalization_3_2.rs")); +#[cfg(not(feature = "ucd_3_2_0"))] +const NORMALIZATION_3_2: &[(u32, u32)] = &[]; /// One of the four Unicode normalization forms. #[derive(Debug, Clone, Copy, Eq, PartialEq)] @@ -78,12 +88,122 @@ pub fn is_normalized(form: NormalizeForm, text: &Wtf8) -> bool { }) } +impl Ucd { + /// Normalize using this database version, including Unicode 3.2 corrections. + #[must_use] + pub fn normalize(self, form: NormalizeForm, text: &Wtf8) -> Wtf8Buf { + if self.modern { + return normalize(form, text); + } + let decomposer = match form { + NormalizeForm::Nfc | NormalizeForm::Nfd => DecomposingNormalizerBorrowed::new_nfd(), + NormalizeForm::Nfkc | NormalizeForm::Nfkd => DecomposingNormalizerBorrowed::new_nfkd(), + }; + let mut decomposed = Vec::new(); + for code in text.code_points() { + match code.to_char() { + Some(ch) if self.membership(ch) => { + let ch = NORMALIZATION_3_2 + .binary_search_by_key(&(ch as u32), |&(code, _)| code) + .ok() + .map_or(ch, |i| char::from_u32(NORMALIZATION_3_2[i].1).unwrap()); + decomposed.extend( + decomposer + .normalize_iter(core::iter::once(ch)) + .map(CodePoint::from), + ); + } + // CPython does not decompose characters unassigned in 3.2. + _ => decomposed.push(code), + } + } + + // CPython uses current combining classes for ordering and composition, + // even for characters that were unassigned in the old database. + let combining = |code: &CodePoint| { + code.to_char().map_or(0, |ch| { + CanonicalCombiningClass::for_char(ch).to_icu4c_value() + }) + }; + let mut start = 0; + for i in 0..=decomposed.len() { + if i == decomposed.len() || combining(&decomposed[i]) == 0 { + decomposed[start..i].sort_by_key(&combining); + start = i + 1; + } + } + if matches!(form, NormalizeForm::Nfc | NormalizeForm::Nfkc) { + let composer = CanonicalComposition::new(); + let mut output: Vec = Vec::with_capacity(decomposed.len()); + let mut starter: Option = None; + let mut previous_class = 0; + for code in decomposed { + let class = combining(&code); + if let Some(i) = starter + && (previous_class == 0 || previous_class < class) + && let (Some(first), Some(second)) = (output[i].to_char(), code.to_char()) + && let Some(composed) = composer.compose(first, second) + { + output[i] = CodePoint::from(composed); + continue; + } + if class == 0 { + starter = Some(output.len()); + } + previous_class = class; + output.push(code); + } + output.into_iter().collect() + } else { + decomposed.into_iter().collect() + } + } + + /// Check normalization with the same version-specific decomposition rules. + #[must_use] + pub fn is_normalized(self, form: NormalizeForm, text: &Wtf8) -> bool { + if self.modern { + is_normalized(form, text) + } else { + // CPython also disables normalization quick checks for old UCDs. + self.normalize(form, text).as_slice() == text + } + } +} + #[cfg(test)] mod tests { use rustpython_wtf8::{CodePoint, Wtf8Buf}; use super::{NormalizeForm, is_normalized, normalize}; + #[test] + #[cfg(feature = "ucd_3_2_0")] + fn old_normalization_keeps_current_ordering_and_composition() { + let old = crate::Ucd::new(false); + for (form, text, expected) in [ + (NormalizeForm::Nfd, "a\u{1ab0}\u{0327}", "a\u{0327}\u{1ab0}"), + (NormalizeForm::Nfc, "\u{1b05}\u{1b35}", "\u{1b06}"), + (NormalizeForm::Nfc, "A\u{1ab0}\u{0300}", "A\u{1ab0}\u{0300}"), + (NormalizeForm::Nfc, "\u{09c7}\u{09be}", "\u{09cb}"), + (NormalizeForm::Nfc, "\u{1100}\u{1161}\u{11a8}", "\u{ac01}"), + (NormalizeForm::Nfkd, "\u{1d2c}", "\u{1d2c}"), + (NormalizeForm::Nfd, "\u{2f868}", "\u{2136a}"), + ] { + let text = Wtf8Buf::from(text); + let expected = Wtf8Buf::from(expected); + assert_eq!(old.normalize(form, &text), expected); + assert_eq!(old.is_normalized(form, &text), text == expected); + } + let mut text = Wtf8Buf::from("\u{2f868}"); + text.push(CodePoint::from_u32(0xd800).unwrap()); + text.push_str("A\u{0300}"); + let mut expected = Wtf8Buf::from("\u{2136a}"); + expected.push(CodePoint::from_u32(0xd800).unwrap()); + expected.push_str("À"); + assert_eq!(old.normalize(NormalizeForm::Nfc, &text), expected); + } + #[test] fn normalization_round_trips() { let composed = Wtf8Buf::from("é"); diff --git a/crates/unicode/tests/data/cpython3.15_graphemes.txt b/crates/unicode/tests/data/cpython3.15_graphemes.txt new file mode 100644 index 00000000000..78de1d3824c --- /dev/null +++ b/crates/unicode/tests/data/cpython3.15_graphemes.txt @@ -0,0 +1,2171 @@ +# CPython d220409a13b77de7a6c30abe16ea90db01528edc; Unicode 17.0.0 +# Inclusive contiguous ranges: start:end GCB InCB Extended_Pictographic +# Reconstructed raw SHA256 9aae5520167e69e08d2241b9899bc7c65b0865d1713ffde698a6e7e1c952284d +000000:000009 Control None 0 +00000A:00000A LF None 0 +00000B:00000C Control None 0 +00000D:00000D CR None 0 +00000E:00001F Control None 0 +000020:00007E Other None 0 +00007F:00009F Control None 0 +0000A0:0000A8 Other None 0 +0000A9:0000A9 Other None 1 +0000AA:0000AC Other None 0 +0000AD:0000AD Control None 0 +0000AE:0000AE Other None 1 +0000AF:0002FF Other None 0 +000300:00036F Extend Extend 0 +000370:000482 Other None 0 +000483:000489 Extend Extend 0 +00048A:000590 Other None 0 +000591:0005BD Extend Extend 0 +0005BE:0005BE Other None 0 +0005BF:0005BF Extend Extend 0 +0005C0:0005C0 Other None 0 +0005C1:0005C2 Extend Extend 0 +0005C3:0005C3 Other None 0 +0005C4:0005C5 Extend Extend 0 +0005C6:0005C6 Other None 0 +0005C7:0005C7 Extend Extend 0 +0005C8:0005FF Other None 0 +000600:000605 Prepend None 0 +000606:00060F Other None 0 +000610:00061A Extend Extend 0 +00061B:00061B Other None 0 +00061C:00061C Control None 0 +00061D:00064A Other None 0 +00064B:00065F Extend Extend 0 +000660:00066F Other None 0 +000670:000670 Extend Extend 0 +000671:0006D5 Other None 0 +0006D6:0006DC Extend Extend 0 +0006DD:0006DD Prepend None 0 +0006DE:0006DE Other None 0 +0006DF:0006E4 Extend Extend 0 +0006E5:0006E6 Other None 0 +0006E7:0006E8 Extend Extend 0 +0006E9:0006E9 Other None 0 +0006EA:0006ED Extend Extend 0 +0006EE:00070E Other None 0 +00070F:00070F Prepend None 0 +000710:000710 Other None 0 +000711:000711 Extend Extend 0 +000712:00072F Other None 0 +000730:00074A Extend Extend 0 +00074B:0007A5 Other None 0 +0007A6:0007B0 Extend Extend 0 +0007B1:0007EA Other None 0 +0007EB:0007F3 Extend Extend 0 +0007F4:0007FC Other None 0 +0007FD:0007FD Extend Extend 0 +0007FE:000815 Other None 0 +000816:000819 Extend Extend 0 +00081A:00081A Other None 0 +00081B:000823 Extend Extend 0 +000824:000824 Other None 0 +000825:000827 Extend Extend 0 +000828:000828 Other None 0 +000829:00082D Extend Extend 0 +00082E:000858 Other None 0 +000859:00085B Extend Extend 0 +00085C:00088F Other None 0 +000890:000891 Prepend None 0 +000892:000896 Other None 0 +000897:00089F Extend Extend 0 +0008A0:0008C9 Other None 0 +0008CA:0008E1 Extend Extend 0 +0008E2:0008E2 Prepend None 0 +0008E3:000902 Extend Extend 0 +000903:000903 SpacingMark None 0 +000904:000914 Other None 0 +000915:000939 Other Consonant 0 +00093A:00093A Extend Extend 0 +00093B:00093B SpacingMark None 0 +00093C:00093C Extend Extend 0 +00093D:00093D Other None 0 +00093E:000940 SpacingMark None 0 +000941:000948 Extend Extend 0 +000949:00094C SpacingMark None 0 +00094D:00094D Extend Linker 0 +00094E:00094F SpacingMark None 0 +000950:000950 Other None 0 +000951:000957 Extend Extend 0 +000958:00095F Other Consonant 0 +000960:000961 Other None 0 +000962:000963 Extend Extend 0 +000964:000977 Other None 0 +000978:00097F Other Consonant 0 +000980:000980 Other None 0 +000981:000981 Extend Extend 0 +000982:000983 SpacingMark None 0 +000984:000994 Other None 0 +000995:0009A8 Other Consonant 0 +0009A9:0009A9 Other None 0 +0009AA:0009B0 Other Consonant 0 +0009B1:0009B1 Other None 0 +0009B2:0009B2 Other Consonant 0 +0009B3:0009B5 Other None 0 +0009B6:0009B9 Other Consonant 0 +0009BA:0009BB Other None 0 +0009BC:0009BC Extend Extend 0 +0009BD:0009BD Other None 0 +0009BE:0009BE Extend Extend 0 +0009BF:0009C0 SpacingMark None 0 +0009C1:0009C4 Extend Extend 0 +0009C5:0009C6 Other None 0 +0009C7:0009C8 SpacingMark None 0 +0009C9:0009CA Other None 0 +0009CB:0009CC SpacingMark None 0 +0009CD:0009CD Extend Linker 0 +0009CE:0009D6 Other None 0 +0009D7:0009D7 Extend Extend 0 +0009D8:0009DB Other None 0 +0009DC:0009DD Other Consonant 0 +0009DE:0009DE Other None 0 +0009DF:0009DF Other Consonant 0 +0009E0:0009E1 Other None 0 +0009E2:0009E3 Extend Extend 0 +0009E4:0009EF Other None 0 +0009F0:0009F1 Other Consonant 0 +0009F2:0009FD Other None 0 +0009FE:0009FE Extend Extend 0 +0009FF:000A00 Other None 0 +000A01:000A02 Extend Extend 0 +000A03:000A03 SpacingMark None 0 +000A04:000A3B Other None 0 +000A3C:000A3C Extend Extend 0 +000A3D:000A3D Other None 0 +000A3E:000A40 SpacingMark None 0 +000A41:000A42 Extend Extend 0 +000A43:000A46 Other None 0 +000A47:000A48 Extend Extend 0 +000A49:000A4A Other None 0 +000A4B:000A4D Extend Extend 0 +000A4E:000A50 Other None 0 +000A51:000A51 Extend Extend 0 +000A52:000A6F Other None 0 +000A70:000A71 Extend Extend 0 +000A72:000A74 Other None 0 +000A75:000A75 Extend Extend 0 +000A76:000A80 Other None 0 +000A81:000A82 Extend Extend 0 +000A83:000A83 SpacingMark None 0 +000A84:000A94 Other None 0 +000A95:000AA8 Other Consonant 0 +000AA9:000AA9 Other None 0 +000AAA:000AB0 Other Consonant 0 +000AB1:000AB1 Other None 0 +000AB2:000AB3 Other Consonant 0 +000AB4:000AB4 Other None 0 +000AB5:000AB9 Other Consonant 0 +000ABA:000ABB Other None 0 +000ABC:000ABC Extend Extend 0 +000ABD:000ABD Other None 0 +000ABE:000AC0 SpacingMark None 0 +000AC1:000AC5 Extend Extend 0 +000AC6:000AC6 Other None 0 +000AC7:000AC8 Extend Extend 0 +000AC9:000AC9 SpacingMark None 0 +000ACA:000ACA Other None 0 +000ACB:000ACC SpacingMark None 0 +000ACD:000ACD Extend Linker 0 +000ACE:000AE1 Other None 0 +000AE2:000AE3 Extend Extend 0 +000AE4:000AF8 Other None 0 +000AF9:000AF9 Other Consonant 0 +000AFA:000AFF Extend Extend 0 +000B00:000B00 Other None 0 +000B01:000B01 Extend Extend 0 +000B02:000B03 SpacingMark None 0 +000B04:000B14 Other None 0 +000B15:000B28 Other Consonant 0 +000B29:000B29 Other None 0 +000B2A:000B30 Other Consonant 0 +000B31:000B31 Other None 0 +000B32:000B33 Other Consonant 0 +000B34:000B34 Other None 0 +000B35:000B39 Other Consonant 0 +000B3A:000B3B Other None 0 +000B3C:000B3C Extend Extend 0 +000B3D:000B3D Other None 0 +000B3E:000B3F Extend Extend 0 +000B40:000B40 SpacingMark None 0 +000B41:000B44 Extend Extend 0 +000B45:000B46 Other None 0 +000B47:000B48 SpacingMark None 0 +000B49:000B4A Other None 0 +000B4B:000B4C SpacingMark None 0 +000B4D:000B4D Extend Linker 0 +000B4E:000B54 Other None 0 +000B55:000B57 Extend Extend 0 +000B58:000B5B Other None 0 +000B5C:000B5D Other Consonant 0 +000B5E:000B5E Other None 0 +000B5F:000B5F Other Consonant 0 +000B60:000B61 Other None 0 +000B62:000B63 Extend Extend 0 +000B64:000B70 Other None 0 +000B71:000B71 Other Consonant 0 +000B72:000B81 Other None 0 +000B82:000B82 Extend Extend 0 +000B83:000BBD Other None 0 +000BBE:000BBE Extend Extend 0 +000BBF:000BBF SpacingMark None 0 +000BC0:000BC0 Extend Extend 0 +000BC1:000BC2 SpacingMark None 0 +000BC3:000BC5 Other None 0 +000BC6:000BC8 SpacingMark None 0 +000BC9:000BC9 Other None 0 +000BCA:000BCC SpacingMark None 0 +000BCD:000BCD Extend Extend 0 +000BCE:000BD6 Other None 0 +000BD7:000BD7 Extend Extend 0 +000BD8:000BFF Other None 0 +000C00:000C00 Extend Extend 0 +000C01:000C03 SpacingMark None 0 +000C04:000C04 Extend Extend 0 +000C05:000C14 Other None 0 +000C15:000C28 Other Consonant 0 +000C29:000C29 Other None 0 +000C2A:000C39 Other Consonant 0 +000C3A:000C3B Other None 0 +000C3C:000C3C Extend Extend 0 +000C3D:000C3D Other None 0 +000C3E:000C40 Extend Extend 0 +000C41:000C44 SpacingMark None 0 +000C45:000C45 Other None 0 +000C46:000C48 Extend Extend 0 +000C49:000C49 Other None 0 +000C4A:000C4C Extend Extend 0 +000C4D:000C4D Extend Linker 0 +000C4E:000C54 Other None 0 +000C55:000C56 Extend Extend 0 +000C57:000C57 Other None 0 +000C58:000C5A Other Consonant 0 +000C5B:000C61 Other None 0 +000C62:000C63 Extend Extend 0 +000C64:000C80 Other None 0 +000C81:000C81 Extend Extend 0 +000C82:000C83 SpacingMark None 0 +000C84:000CBB Other None 0 +000CBC:000CBC Extend Extend 0 +000CBD:000CBD Other None 0 +000CBE:000CBE SpacingMark None 0 +000CBF:000CC0 Extend Extend 0 +000CC1:000CC1 SpacingMark None 0 +000CC2:000CC2 Extend Extend 0 +000CC3:000CC4 SpacingMark None 0 +000CC5:000CC5 Other None 0 +000CC6:000CC8 Extend Extend 0 +000CC9:000CC9 Other None 0 +000CCA:000CCD Extend Extend 0 +000CCE:000CD4 Other None 0 +000CD5:000CD6 Extend Extend 0 +000CD7:000CE1 Other None 0 +000CE2:000CE3 Extend Extend 0 +000CE4:000CF2 Other None 0 +000CF3:000CF3 SpacingMark None 0 +000CF4:000CFF Other None 0 +000D00:000D01 Extend Extend 0 +000D02:000D03 SpacingMark None 0 +000D04:000D14 Other None 0 +000D15:000D3A Other Consonant 0 +000D3B:000D3C Extend Extend 0 +000D3D:000D3D Other None 0 +000D3E:000D3E Extend Extend 0 +000D3F:000D40 SpacingMark None 0 +000D41:000D44 Extend Extend 0 +000D45:000D45 Other None 0 +000D46:000D48 SpacingMark None 0 +000D49:000D49 Other None 0 +000D4A:000D4C SpacingMark None 0 +000D4D:000D4D Extend Linker 0 +000D4E:000D4E Prepend None 0 +000D4F:000D56 Other None 0 +000D57:000D57 Extend Extend 0 +000D58:000D61 Other None 0 +000D62:000D63 Extend Extend 0 +000D64:000D80 Other None 0 +000D81:000D81 Extend Extend 0 +000D82:000D83 SpacingMark None 0 +000D84:000DC9 Other None 0 +000DCA:000DCA Extend Extend 0 +000DCB:000DCE Other None 0 +000DCF:000DCF Extend Extend 0 +000DD0:000DD1 SpacingMark None 0 +000DD2:000DD4 Extend Extend 0 +000DD5:000DD5 Other None 0 +000DD6:000DD6 Extend Extend 0 +000DD7:000DD7 Other None 0 +000DD8:000DDE SpacingMark None 0 +000DDF:000DDF Extend Extend 0 +000DE0:000DF1 Other None 0 +000DF2:000DF3 SpacingMark None 0 +000DF4:000E30 Other None 0 +000E31:000E31 Extend Extend 0 +000E32:000E32 Other None 0 +000E33:000E33 SpacingMark None 0 +000E34:000E3A Extend Extend 0 +000E3B:000E46 Other None 0 +000E47:000E4E Extend Extend 0 +000E4F:000EB0 Other None 0 +000EB1:000EB1 Extend Extend 0 +000EB2:000EB2 Other None 0 +000EB3:000EB3 SpacingMark None 0 +000EB4:000EBC Extend Extend 0 +000EBD:000EC7 Other None 0 +000EC8:000ECE Extend Extend 0 +000ECF:000F17 Other None 0 +000F18:000F19 Extend Extend 0 +000F1A:000F34 Other None 0 +000F35:000F35 Extend Extend 0 +000F36:000F36 Other None 0 +000F37:000F37 Extend Extend 0 +000F38:000F38 Other None 0 +000F39:000F39 Extend Extend 0 +000F3A:000F3D Other None 0 +000F3E:000F3F SpacingMark None 0 +000F40:000F70 Other None 0 +000F71:000F7E Extend Extend 0 +000F7F:000F7F SpacingMark None 0 +000F80:000F84 Extend Extend 0 +000F85:000F85 Other None 0 +000F86:000F87 Extend Extend 0 +000F88:000F8C Other None 0 +000F8D:000F97 Extend Extend 0 +000F98:000F98 Other None 0 +000F99:000FBC Extend Extend 0 +000FBD:000FC5 Other None 0 +000FC6:000FC6 Extend Extend 0 +000FC7:000FFF Other None 0 +001000:00102A Other Consonant 0 +00102B:00102C Other None 0 +00102D:001030 Extend Extend 0 +001031:001031 SpacingMark None 0 +001032:001037 Extend Extend 0 +001038:001038 Other None 0 +001039:001039 Extend Linker 0 +00103A:00103A Extend Extend 0 +00103B:00103C SpacingMark None 0 +00103D:00103E Extend Extend 0 +00103F:00103F Other Consonant 0 +001040:00104F Other None 0 +001050:001055 Other Consonant 0 +001056:001057 SpacingMark None 0 +001058:001059 Extend Extend 0 +00105A:00105D Other Consonant 0 +00105E:001060 Extend Extend 0 +001061:001061 Other Consonant 0 +001062:001064 Other None 0 +001065:001066 Other Consonant 0 +001067:00106D Other None 0 +00106E:001070 Other Consonant 0 +001071:001074 Extend Extend 0 +001075:001081 Other Consonant 0 +001082:001082 Extend Extend 0 +001083:001083 Other None 0 +001084:001084 SpacingMark None 0 +001085:001086 Extend Extend 0 +001087:00108C Other None 0 +00108D:00108D Extend Extend 0 +00108E:00108E Other Consonant 0 +00108F:00109C Other None 0 +00109D:00109D Extend Extend 0 +00109E:0010FF Other None 0 +001100:00115F L None 0 +001160:0011A7 V None 0 +0011A8:0011FF T None 0 +001200:00135C Other None 0 +00135D:00135F Extend Extend 0 +001360:001711 Other None 0 +001712:001715 Extend Extend 0 +001716:001731 Other None 0 +001732:001734 Extend Extend 0 +001735:001751 Other None 0 +001752:001753 Extend Extend 0 +001754:001771 Other None 0 +001772:001773 Extend Extend 0 +001774:00177F Other None 0 +001780:0017B3 Other Consonant 0 +0017B4:0017B5 Extend Extend 0 +0017B6:0017B6 SpacingMark None 0 +0017B7:0017BD Extend Extend 0 +0017BE:0017C5 SpacingMark None 0 +0017C6:0017C6 Extend Extend 0 +0017C7:0017C8 SpacingMark None 0 +0017C9:0017D1 Extend Extend 0 +0017D2:0017D2 Extend Linker 0 +0017D3:0017D3 Extend Extend 0 +0017D4:0017DC Other None 0 +0017DD:0017DD Extend Extend 0 +0017DE:00180A Other None 0 +00180B:00180D Extend Extend 0 +00180E:00180E Control None 0 +00180F:00180F Extend Extend 0 +001810:001884 Other None 0 +001885:001886 Extend Extend 0 +001887:0018A8 Other None 0 +0018A9:0018A9 Extend Extend 0 +0018AA:00191F Other None 0 +001920:001922 Extend Extend 0 +001923:001926 SpacingMark None 0 +001927:001928 Extend Extend 0 +001929:00192B SpacingMark None 0 +00192C:00192F Other None 0 +001930:001931 SpacingMark None 0 +001932:001932 Extend Extend 0 +001933:001938 SpacingMark None 0 +001939:00193B Extend Extend 0 +00193C:001A16 Other None 0 +001A17:001A18 Extend Extend 0 +001A19:001A1A SpacingMark None 0 +001A1B:001A1B Extend Extend 0 +001A1C:001A1F Other None 0 +001A20:001A54 Other Consonant 0 +001A55:001A55 SpacingMark None 0 +001A56:001A56 Extend Extend 0 +001A57:001A57 SpacingMark None 0 +001A58:001A5E Extend Extend 0 +001A5F:001A5F Other None 0 +001A60:001A60 Extend Linker 0 +001A61:001A61 Other None 0 +001A62:001A62 Extend Extend 0 +001A63:001A64 Other None 0 +001A65:001A6C Extend Extend 0 +001A6D:001A72 SpacingMark None 0 +001A73:001A7C Extend Extend 0 +001A7D:001A7E Other None 0 +001A7F:001A7F Extend Extend 0 +001A80:001AAF Other None 0 +001AB0:001ADD Extend Extend 0 +001ADE:001ADF Other None 0 +001AE0:001AEB Extend Extend 0 +001AEC:001AFF Other None 0 +001B00:001B03 Extend Extend 0 +001B04:001B04 SpacingMark None 0 +001B05:001B0A Other None 0 +001B0B:001B0C Other Consonant 0 +001B0D:001B12 Other None 0 +001B13:001B33 Other Consonant 0 +001B34:001B3D Extend Extend 0 +001B3E:001B41 SpacingMark None 0 +001B42:001B43 Extend Extend 0 +001B44:001B44 Extend Linker 0 +001B45:001B4C Other Consonant 0 +001B4D:001B6A Other None 0 +001B6B:001B73 Extend Extend 0 +001B74:001B7F Other None 0 +001B80:001B81 Extend Extend 0 +001B82:001B82 SpacingMark None 0 +001B83:001BA0 Other Consonant 0 +001BA1:001BA1 SpacingMark None 0 +001BA2:001BA5 Extend Extend 0 +001BA6:001BA7 SpacingMark None 0 +001BA8:001BAA Extend Extend 0 +001BAB:001BAB Extend Linker 0 +001BAC:001BAD Extend Extend 0 +001BAE:001BAF Other Consonant 0 +001BB0:001BBA Other None 0 +001BBB:001BBD Other Consonant 0 +001BBE:001BE5 Other None 0 +001BE6:001BE6 Extend Extend 0 +001BE7:001BE7 SpacingMark None 0 +001BE8:001BE9 Extend Extend 0 +001BEA:001BEC SpacingMark None 0 +001BED:001BED Extend Extend 0 +001BEE:001BEE SpacingMark None 0 +001BEF:001BF3 Extend Extend 0 +001BF4:001C23 Other None 0 +001C24:001C2B SpacingMark None 0 +001C2C:001C33 Extend Extend 0 +001C34:001C35 SpacingMark None 0 +001C36:001C37 Extend Extend 0 +001C38:001CCF Other None 0 +001CD0:001CD2 Extend Extend 0 +001CD3:001CD3 Other None 0 +001CD4:001CE0 Extend Extend 0 +001CE1:001CE1 SpacingMark None 0 +001CE2:001CE8 Extend Extend 0 +001CE9:001CEC Other None 0 +001CED:001CED Extend Extend 0 +001CEE:001CF3 Other None 0 +001CF4:001CF4 Extend Extend 0 +001CF5:001CF6 Other None 0 +001CF7:001CF7 SpacingMark None 0 +001CF8:001CF9 Extend Extend 0 +001CFA:001DBF Other None 0 +001DC0:001DFF Extend Extend 0 +001E00:00200A Other None 0 +00200B:00200B Control None 0 +00200C:00200C Extend None 0 +00200D:00200D ZWJ Extend 0 +00200E:00200F Control None 0 +002010:002027 Other None 0 +002028:00202E Control None 0 +00202F:00203B Other None 0 +00203C:00203C Other None 1 +00203D:002048 Other None 0 +002049:002049 Other None 1 +00204A:00205F Other None 0 +002060:00206F Control None 0 +002070:0020CF Other None 0 +0020D0:0020F0 Extend Extend 0 +0020F1:002121 Other None 0 +002122:002122 Other None 1 +002123:002138 Other None 0 +002139:002139 Other None 1 +00213A:002193 Other None 0 +002194:002199 Other None 1 +00219A:0021A8 Other None 0 +0021A9:0021AA Other None 1 +0021AB:002319 Other None 0 +00231A:00231B Other None 1 +00231C:002327 Other None 0 +002328:002328 Other None 1 +002329:0023CE Other None 0 +0023CF:0023CF Other None 1 +0023D0:0023E8 Other None 0 +0023E9:0023F3 Other None 1 +0023F4:0023F7 Other None 0 +0023F8:0023FA Other None 1 +0023FB:0024C1 Other None 0 +0024C2:0024C2 Other None 1 +0024C3:0025A9 Other None 0 +0025AA:0025AB Other None 1 +0025AC:0025B5 Other None 0 +0025B6:0025B6 Other None 1 +0025B7:0025BF Other None 0 +0025C0:0025C0 Other None 1 +0025C1:0025FA Other None 0 +0025FB:0025FE Other None 1 +0025FF:0025FF Other None 0 +002600:002604 Other None 1 +002605:00260D Other None 0 +00260E:00260E Other None 1 +00260F:002610 Other None 0 +002611:002611 Other None 1 +002612:002613 Other None 0 +002614:002615 Other None 1 +002616:002617 Other None 0 +002618:002618 Other None 1 +002619:00261C Other None 0 +00261D:00261D Other None 1 +00261E:00261F Other None 0 +002620:002620 Other None 1 +002621:002621 Other None 0 +002622:002623 Other None 1 +002624:002625 Other None 0 +002626:002626 Other None 1 +002627:002629 Other None 0 +00262A:00262A Other None 1 +00262B:00262D Other None 0 +00262E:00262F Other None 1 +002630:002637 Other None 0 +002638:00263A Other None 1 +00263B:00263F Other None 0 +002640:002640 Other None 1 +002641:002641 Other None 0 +002642:002642 Other None 1 +002643:002647 Other None 0 +002648:002653 Other None 1 +002654:00265E Other None 0 +00265F:002660 Other None 1 +002661:002662 Other None 0 +002663:002663 Other None 1 +002664:002664 Other None 0 +002665:002666 Other None 1 +002667:002667 Other None 0 +002668:002668 Other None 1 +002669:00267A Other None 0 +00267B:00267B Other None 1 +00267C:00267D Other None 0 +00267E:00267F Other None 1 +002680:002691 Other None 0 +002692:002697 Other None 1 +002698:002698 Other None 0 +002699:002699 Other None 1 +00269A:00269A Other None 0 +00269B:00269C Other None 1 +00269D:00269F Other None 0 +0026A0:0026A1 Other None 1 +0026A2:0026A6 Other None 0 +0026A7:0026A7 Other None 1 +0026A8:0026A9 Other None 0 +0026AA:0026AB Other None 1 +0026AC:0026AF Other None 0 +0026B0:0026B1 Other None 1 +0026B2:0026BC Other None 0 +0026BD:0026BE Other None 1 +0026BF:0026C3 Other None 0 +0026C4:0026C5 Other None 1 +0026C6:0026C7 Other None 0 +0026C8:0026C8 Other None 1 +0026C9:0026CD Other None 0 +0026CE:0026CF Other None 1 +0026D0:0026D0 Other None 0 +0026D1:0026D1 Other None 1 +0026D2:0026D2 Other None 0 +0026D3:0026D4 Other None 1 +0026D5:0026E8 Other None 0 +0026E9:0026EA Other None 1 +0026EB:0026EF Other None 0 +0026F0:0026F5 Other None 1 +0026F6:0026F6 Other None 0 +0026F7:0026FA Other None 1 +0026FB:0026FC Other None 0 +0026FD:0026FD Other None 1 +0026FE:002701 Other None 0 +002702:002702 Other None 1 +002703:002704 Other None 0 +002705:002705 Other None 1 +002706:002707 Other None 0 +002708:00270D Other None 1 +00270E:00270E Other None 0 +00270F:00270F Other None 1 +002710:002711 Other None 0 +002712:002712 Other None 1 +002713:002713 Other None 0 +002714:002714 Other None 1 +002715:002715 Other None 0 +002716:002716 Other None 1 +002717:00271C Other None 0 +00271D:00271D Other None 1 +00271E:002720 Other None 0 +002721:002721 Other None 1 +002722:002727 Other None 0 +002728:002728 Other None 1 +002729:002732 Other None 0 +002733:002734 Other None 1 +002735:002743 Other None 0 +002744:002744 Other None 1 +002745:002746 Other None 0 +002747:002747 Other None 1 +002748:00274B Other None 0 +00274C:00274C Other None 1 +00274D:00274D Other None 0 +00274E:00274E Other None 1 +00274F:002752 Other None 0 +002753:002755 Other None 1 +002756:002756 Other None 0 +002757:002757 Other None 1 +002758:002762 Other None 0 +002763:002764 Other None 1 +002765:002794 Other None 0 +002795:002797 Other None 1 +002798:0027A0 Other None 0 +0027A1:0027A1 Other None 1 +0027A2:0027AF Other None 0 +0027B0:0027B0 Other None 1 +0027B1:0027BE Other None 0 +0027BF:0027BF Other None 1 +0027C0:002933 Other None 0 +002934:002935 Other None 1 +002936:002B04 Other None 0 +002B05:002B07 Other None 1 +002B08:002B1A Other None 0 +002B1B:002B1C Other None 1 +002B1D:002B4F Other None 0 +002B50:002B50 Other None 1 +002B51:002B54 Other None 0 +002B55:002B55 Other None 1 +002B56:002CEE Other None 0 +002CEF:002CF1 Extend Extend 0 +002CF2:002D7E Other None 0 +002D7F:002D7F Extend Extend 0 +002D80:002DDF Other None 0 +002DE0:002DFF Extend Extend 0 +002E00:003029 Other None 0 +00302A:00302F Extend Extend 0 +003030:003030 Other None 1 +003031:00303C Other None 0 +00303D:00303D Other None 1 +00303E:003098 Other None 0 +003099:00309A Extend Extend 0 +00309B:003296 Other None 0 +003297:003297 Other None 1 +003298:003298 Other None 0 +003299:003299 Other None 1 +00329A:00A66E Other None 0 +00A66F:00A672 Extend Extend 0 +00A673:00A673 Other None 0 +00A674:00A67D Extend Extend 0 +00A67E:00A69D Other None 0 +00A69E:00A69F Extend Extend 0 +00A6A0:00A6EF Other None 0 +00A6F0:00A6F1 Extend Extend 0 +00A6F2:00A801 Other None 0 +00A802:00A802 Extend Extend 0 +00A803:00A805 Other None 0 +00A806:00A806 Extend Extend 0 +00A807:00A80A Other None 0 +00A80B:00A80B Extend Extend 0 +00A80C:00A822 Other None 0 +00A823:00A824 SpacingMark None 0 +00A825:00A826 Extend Extend 0 +00A827:00A827 SpacingMark None 0 +00A828:00A82B Other None 0 +00A82C:00A82C Extend Extend 0 +00A82D:00A87F Other None 0 +00A880:00A881 SpacingMark None 0 +00A882:00A8B3 Other None 0 +00A8B4:00A8C3 SpacingMark None 0 +00A8C4:00A8C5 Extend Extend 0 +00A8C6:00A8DF Other None 0 +00A8E0:00A8F1 Extend Extend 0 +00A8F2:00A8FE Other None 0 +00A8FF:00A8FF Extend Extend 0 +00A900:00A925 Other None 0 +00A926:00A92D Extend Extend 0 +00A92E:00A946 Other None 0 +00A947:00A951 Extend Extend 0 +00A952:00A952 SpacingMark None 0 +00A953:00A953 Extend Extend 0 +00A954:00A95F Other None 0 +00A960:00A97C L None 0 +00A97D:00A97F Other None 0 +00A980:00A982 Extend Extend 0 +00A983:00A983 SpacingMark None 0 +00A984:00A988 Other None 0 +00A989:00A98B Other Consonant 0 +00A98C:00A98E Other None 0 +00A98F:00A9B2 Other Consonant 0 +00A9B3:00A9B3 Extend Extend 0 +00A9B4:00A9B5 SpacingMark None 0 +00A9B6:00A9B9 Extend Extend 0 +00A9BA:00A9BB SpacingMark None 0 +00A9BC:00A9BD Extend Extend 0 +00A9BE:00A9BF SpacingMark None 0 +00A9C0:00A9C0 Extend Linker 0 +00A9C1:00A9DF Other None 0 +00A9E0:00A9E4 Other Consonant 0 +00A9E5:00A9E5 Extend Extend 0 +00A9E6:00A9E6 Other None 0 +00A9E7:00A9EF Other Consonant 0 +00A9F0:00A9F9 Other None 0 +00A9FA:00A9FE Other Consonant 0 +00A9FF:00AA28 Other None 0 +00AA29:00AA2E Extend Extend 0 +00AA2F:00AA30 SpacingMark None 0 +00AA31:00AA32 Extend Extend 0 +00AA33:00AA34 SpacingMark None 0 +00AA35:00AA36 Extend Extend 0 +00AA37:00AA42 Other None 0 +00AA43:00AA43 Extend Extend 0 +00AA44:00AA4B Other None 0 +00AA4C:00AA4C Extend Extend 0 +00AA4D:00AA4D SpacingMark None 0 +00AA4E:00AA5F Other None 0 +00AA60:00AA6F Other Consonant 0 +00AA70:00AA70 Other None 0 +00AA71:00AA73 Other Consonant 0 +00AA74:00AA79 Other None 0 +00AA7A:00AA7A Other Consonant 0 +00AA7B:00AA7B Other None 0 +00AA7C:00AA7C Extend Extend 0 +00AA7D:00AA7D Other None 0 +00AA7E:00AA7F Other Consonant 0 +00AA80:00AAAF Other None 0 +00AAB0:00AAB0 Extend Extend 0 +00AAB1:00AAB1 Other None 0 +00AAB2:00AAB4 Extend Extend 0 +00AAB5:00AAB6 Other None 0 +00AAB7:00AAB8 Extend Extend 0 +00AAB9:00AABD Other None 0 +00AABE:00AABF Extend Extend 0 +00AAC0:00AAC0 Other None 0 +00AAC1:00AAC1 Extend Extend 0 +00AAC2:00AADF Other None 0 +00AAE0:00AAEA Other Consonant 0 +00AAEB:00AAEB SpacingMark None 0 +00AAEC:00AAED Extend Extend 0 +00AAEE:00AAEF SpacingMark None 0 +00AAF0:00AAF4 Other None 0 +00AAF5:00AAF5 SpacingMark None 0 +00AAF6:00AAF6 Extend Linker 0 +00AAF7:00ABBF Other None 0 +00ABC0:00ABDA Other Consonant 0 +00ABDB:00ABE2 Other None 0 +00ABE3:00ABE4 SpacingMark None 0 +00ABE5:00ABE5 Extend Extend 0 +00ABE6:00ABE7 SpacingMark None 0 +00ABE8:00ABE8 Extend Extend 0 +00ABE9:00ABEA SpacingMark None 0 +00ABEB:00ABEB Other None 0 +00ABEC:00ABEC SpacingMark None 0 +00ABED:00ABED Extend Extend 0 +00ABEE:00ABFF Other None 0 +00AC00:00AC00 LV None 0 +00AC01:00AC1B LVT None 0 +00AC1C:00AC1C LV None 0 +00AC1D:00AC37 LVT None 0 +00AC38:00AC38 LV None 0 +00AC39:00AC53 LVT None 0 +00AC54:00AC54 LV None 0 +00AC55:00AC6F LVT None 0 +00AC70:00AC70 LV None 0 +00AC71:00AC8B LVT None 0 +00AC8C:00AC8C LV None 0 +00AC8D:00ACA7 LVT None 0 +00ACA8:00ACA8 LV None 0 +00ACA9:00ACC3 LVT None 0 +00ACC4:00ACC4 LV None 0 +00ACC5:00ACDF LVT None 0 +00ACE0:00ACE0 LV None 0 +00ACE1:00ACFB LVT None 0 +00ACFC:00ACFC LV None 0 +00ACFD:00AD17 LVT None 0 +00AD18:00AD18 LV None 0 +00AD19:00AD33 LVT None 0 +00AD34:00AD34 LV None 0 +00AD35:00AD4F LVT None 0 +00AD50:00AD50 LV None 0 +00AD51:00AD6B LVT None 0 +00AD6C:00AD6C LV None 0 +00AD6D:00AD87 LVT None 0 +00AD88:00AD88 LV None 0 +00AD89:00ADA3 LVT None 0 +00ADA4:00ADA4 LV None 0 +00ADA5:00ADBF LVT None 0 +00ADC0:00ADC0 LV None 0 +00ADC1:00ADDB LVT None 0 +00ADDC:00ADDC LV None 0 +00ADDD:00ADF7 LVT None 0 +00ADF8:00ADF8 LV None 0 +00ADF9:00AE13 LVT None 0 +00AE14:00AE14 LV None 0 +00AE15:00AE2F LVT None 0 +00AE30:00AE30 LV None 0 +00AE31:00AE4B LVT None 0 +00AE4C:00AE4C LV None 0 +00AE4D:00AE67 LVT None 0 +00AE68:00AE68 LV None 0 +00AE69:00AE83 LVT None 0 +00AE84:00AE84 LV None 0 +00AE85:00AE9F LVT None 0 +00AEA0:00AEA0 LV None 0 +00AEA1:00AEBB LVT None 0 +00AEBC:00AEBC LV None 0 +00AEBD:00AED7 LVT None 0 +00AED8:00AED8 LV None 0 +00AED9:00AEF3 LVT None 0 +00AEF4:00AEF4 LV None 0 +00AEF5:00AF0F LVT None 0 +00AF10:00AF10 LV None 0 +00AF11:00AF2B LVT None 0 +00AF2C:00AF2C LV None 0 +00AF2D:00AF47 LVT None 0 +00AF48:00AF48 LV None 0 +00AF49:00AF63 LVT None 0 +00AF64:00AF64 LV None 0 +00AF65:00AF7F LVT None 0 +00AF80:00AF80 LV None 0 +00AF81:00AF9B LVT None 0 +00AF9C:00AF9C LV None 0 +00AF9D:00AFB7 LVT None 0 +00AFB8:00AFB8 LV None 0 +00AFB9:00AFD3 LVT None 0 +00AFD4:00AFD4 LV None 0 +00AFD5:00AFEF LVT None 0 +00AFF0:00AFF0 LV None 0 +00AFF1:00B00B LVT None 0 +00B00C:00B00C LV None 0 +00B00D:00B027 LVT None 0 +00B028:00B028 LV None 0 +00B029:00B043 LVT None 0 +00B044:00B044 LV None 0 +00B045:00B05F LVT None 0 +00B060:00B060 LV None 0 +00B061:00B07B LVT None 0 +00B07C:00B07C LV None 0 +00B07D:00B097 LVT None 0 +00B098:00B098 LV None 0 +00B099:00B0B3 LVT None 0 +00B0B4:00B0B4 LV None 0 +00B0B5:00B0CF LVT None 0 +00B0D0:00B0D0 LV None 0 +00B0D1:00B0EB LVT None 0 +00B0EC:00B0EC LV None 0 +00B0ED:00B107 LVT None 0 +00B108:00B108 LV None 0 +00B109:00B123 LVT None 0 +00B124:00B124 LV None 0 +00B125:00B13F LVT None 0 +00B140:00B140 LV None 0 +00B141:00B15B LVT None 0 +00B15C:00B15C LV None 0 +00B15D:00B177 LVT None 0 +00B178:00B178 LV None 0 +00B179:00B193 LVT None 0 +00B194:00B194 LV None 0 +00B195:00B1AF LVT None 0 +00B1B0:00B1B0 LV None 0 +00B1B1:00B1CB LVT None 0 +00B1CC:00B1CC LV None 0 +00B1CD:00B1E7 LVT None 0 +00B1E8:00B1E8 LV None 0 +00B1E9:00B203 LVT None 0 +00B204:00B204 LV None 0 +00B205:00B21F LVT None 0 +00B220:00B220 LV None 0 +00B221:00B23B LVT None 0 +00B23C:00B23C LV None 0 +00B23D:00B257 LVT None 0 +00B258:00B258 LV None 0 +00B259:00B273 LVT None 0 +00B274:00B274 LV None 0 +00B275:00B28F LVT None 0 +00B290:00B290 LV None 0 +00B291:00B2AB LVT None 0 +00B2AC:00B2AC LV None 0 +00B2AD:00B2C7 LVT None 0 +00B2C8:00B2C8 LV None 0 +00B2C9:00B2E3 LVT None 0 +00B2E4:00B2E4 LV None 0 +00B2E5:00B2FF LVT None 0 +00B300:00B300 LV None 0 +00B301:00B31B LVT None 0 +00B31C:00B31C LV None 0 +00B31D:00B337 LVT None 0 +00B338:00B338 LV None 0 +00B339:00B353 LVT None 0 +00B354:00B354 LV None 0 +00B355:00B36F LVT None 0 +00B370:00B370 LV None 0 +00B371:00B38B LVT None 0 +00B38C:00B38C LV None 0 +00B38D:00B3A7 LVT None 0 +00B3A8:00B3A8 LV None 0 +00B3A9:00B3C3 LVT None 0 +00B3C4:00B3C4 LV None 0 +00B3C5:00B3DF LVT None 0 +00B3E0:00B3E0 LV None 0 +00B3E1:00B3FB LVT None 0 +00B3FC:00B3FC LV None 0 +00B3FD:00B417 LVT None 0 +00B418:00B418 LV None 0 +00B419:00B433 LVT None 0 +00B434:00B434 LV None 0 +00B435:00B44F LVT None 0 +00B450:00B450 LV None 0 +00B451:00B46B LVT None 0 +00B46C:00B46C LV None 0 +00B46D:00B487 LVT None 0 +00B488:00B488 LV None 0 +00B489:00B4A3 LVT None 0 +00B4A4:00B4A4 LV None 0 +00B4A5:00B4BF LVT None 0 +00B4C0:00B4C0 LV None 0 +00B4C1:00B4DB LVT None 0 +00B4DC:00B4DC LV None 0 +00B4DD:00B4F7 LVT None 0 +00B4F8:00B4F8 LV None 0 +00B4F9:00B513 LVT None 0 +00B514:00B514 LV None 0 +00B515:00B52F LVT None 0 +00B530:00B530 LV None 0 +00B531:00B54B LVT None 0 +00B54C:00B54C LV None 0 +00B54D:00B567 LVT None 0 +00B568:00B568 LV None 0 +00B569:00B583 LVT None 0 +00B584:00B584 LV None 0 +00B585:00B59F LVT None 0 +00B5A0:00B5A0 LV None 0 +00B5A1:00B5BB LVT None 0 +00B5BC:00B5BC LV None 0 +00B5BD:00B5D7 LVT None 0 +00B5D8:00B5D8 LV None 0 +00B5D9:00B5F3 LVT None 0 +00B5F4:00B5F4 LV None 0 +00B5F5:00B60F LVT None 0 +00B610:00B610 LV None 0 +00B611:00B62B LVT None 0 +00B62C:00B62C LV None 0 +00B62D:00B647 LVT None 0 +00B648:00B648 LV None 0 +00B649:00B663 LVT None 0 +00B664:00B664 LV None 0 +00B665:00B67F LVT None 0 +00B680:00B680 LV None 0 +00B681:00B69B LVT None 0 +00B69C:00B69C LV None 0 +00B69D:00B6B7 LVT None 0 +00B6B8:00B6B8 LV None 0 +00B6B9:00B6D3 LVT None 0 +00B6D4:00B6D4 LV None 0 +00B6D5:00B6EF LVT None 0 +00B6F0:00B6F0 LV None 0 +00B6F1:00B70B LVT None 0 +00B70C:00B70C LV None 0 +00B70D:00B727 LVT None 0 +00B728:00B728 LV None 0 +00B729:00B743 LVT None 0 +00B744:00B744 LV None 0 +00B745:00B75F LVT None 0 +00B760:00B760 LV None 0 +00B761:00B77B LVT None 0 +00B77C:00B77C LV None 0 +00B77D:00B797 LVT None 0 +00B798:00B798 LV None 0 +00B799:00B7B3 LVT None 0 +00B7B4:00B7B4 LV None 0 +00B7B5:00B7CF LVT None 0 +00B7D0:00B7D0 LV None 0 +00B7D1:00B7EB LVT None 0 +00B7EC:00B7EC LV None 0 +00B7ED:00B807 LVT None 0 +00B808:00B808 LV None 0 +00B809:00B823 LVT None 0 +00B824:00B824 LV None 0 +00B825:00B83F LVT None 0 +00B840:00B840 LV None 0 +00B841:00B85B LVT None 0 +00B85C:00B85C LV None 0 +00B85D:00B877 LVT None 0 +00B878:00B878 LV None 0 +00B879:00B893 LVT None 0 +00B894:00B894 LV None 0 +00B895:00B8AF LVT None 0 +00B8B0:00B8B0 LV None 0 +00B8B1:00B8CB LVT None 0 +00B8CC:00B8CC LV None 0 +00B8CD:00B8E7 LVT None 0 +00B8E8:00B8E8 LV None 0 +00B8E9:00B903 LVT None 0 +00B904:00B904 LV None 0 +00B905:00B91F LVT None 0 +00B920:00B920 LV None 0 +00B921:00B93B LVT None 0 +00B93C:00B93C LV None 0 +00B93D:00B957 LVT None 0 +00B958:00B958 LV None 0 +00B959:00B973 LVT None 0 +00B974:00B974 LV None 0 +00B975:00B98F LVT None 0 +00B990:00B990 LV None 0 +00B991:00B9AB LVT None 0 +00B9AC:00B9AC LV None 0 +00B9AD:00B9C7 LVT None 0 +00B9C8:00B9C8 LV None 0 +00B9C9:00B9E3 LVT None 0 +00B9E4:00B9E4 LV None 0 +00B9E5:00B9FF LVT None 0 +00BA00:00BA00 LV None 0 +00BA01:00BA1B LVT None 0 +00BA1C:00BA1C LV None 0 +00BA1D:00BA37 LVT None 0 +00BA38:00BA38 LV None 0 +00BA39:00BA53 LVT None 0 +00BA54:00BA54 LV None 0 +00BA55:00BA6F LVT None 0 +00BA70:00BA70 LV None 0 +00BA71:00BA8B LVT None 0 +00BA8C:00BA8C LV None 0 +00BA8D:00BAA7 LVT None 0 +00BAA8:00BAA8 LV None 0 +00BAA9:00BAC3 LVT None 0 +00BAC4:00BAC4 LV None 0 +00BAC5:00BADF LVT None 0 +00BAE0:00BAE0 LV None 0 +00BAE1:00BAFB LVT None 0 +00BAFC:00BAFC LV None 0 +00BAFD:00BB17 LVT None 0 +00BB18:00BB18 LV None 0 +00BB19:00BB33 LVT None 0 +00BB34:00BB34 LV None 0 +00BB35:00BB4F LVT None 0 +00BB50:00BB50 LV None 0 +00BB51:00BB6B LVT None 0 +00BB6C:00BB6C LV None 0 +00BB6D:00BB87 LVT None 0 +00BB88:00BB88 LV None 0 +00BB89:00BBA3 LVT None 0 +00BBA4:00BBA4 LV None 0 +00BBA5:00BBBF LVT None 0 +00BBC0:00BBC0 LV None 0 +00BBC1:00BBDB LVT None 0 +00BBDC:00BBDC LV None 0 +00BBDD:00BBF7 LVT None 0 +00BBF8:00BBF8 LV None 0 +00BBF9:00BC13 LVT None 0 +00BC14:00BC14 LV None 0 +00BC15:00BC2F LVT None 0 +00BC30:00BC30 LV None 0 +00BC31:00BC4B LVT None 0 +00BC4C:00BC4C LV None 0 +00BC4D:00BC67 LVT None 0 +00BC68:00BC68 LV None 0 +00BC69:00BC83 LVT None 0 +00BC84:00BC84 LV None 0 +00BC85:00BC9F LVT None 0 +00BCA0:00BCA0 LV None 0 +00BCA1:00BCBB LVT None 0 +00BCBC:00BCBC LV None 0 +00BCBD:00BCD7 LVT None 0 +00BCD8:00BCD8 LV None 0 +00BCD9:00BCF3 LVT None 0 +00BCF4:00BCF4 LV None 0 +00BCF5:00BD0F LVT None 0 +00BD10:00BD10 LV None 0 +00BD11:00BD2B LVT None 0 +00BD2C:00BD2C LV None 0 +00BD2D:00BD47 LVT None 0 +00BD48:00BD48 LV None 0 +00BD49:00BD63 LVT None 0 +00BD64:00BD64 LV None 0 +00BD65:00BD7F LVT None 0 +00BD80:00BD80 LV None 0 +00BD81:00BD9B LVT None 0 +00BD9C:00BD9C LV None 0 +00BD9D:00BDB7 LVT None 0 +00BDB8:00BDB8 LV None 0 +00BDB9:00BDD3 LVT None 0 +00BDD4:00BDD4 LV None 0 +00BDD5:00BDEF LVT None 0 +00BDF0:00BDF0 LV None 0 +00BDF1:00BE0B LVT None 0 +00BE0C:00BE0C LV None 0 +00BE0D:00BE27 LVT None 0 +00BE28:00BE28 LV None 0 +00BE29:00BE43 LVT None 0 +00BE44:00BE44 LV None 0 +00BE45:00BE5F LVT None 0 +00BE60:00BE60 LV None 0 +00BE61:00BE7B LVT None 0 +00BE7C:00BE7C LV None 0 +00BE7D:00BE97 LVT None 0 +00BE98:00BE98 LV None 0 +00BE99:00BEB3 LVT None 0 +00BEB4:00BEB4 LV None 0 +00BEB5:00BECF LVT None 0 +00BED0:00BED0 LV None 0 +00BED1:00BEEB LVT None 0 +00BEEC:00BEEC LV None 0 +00BEED:00BF07 LVT None 0 +00BF08:00BF08 LV None 0 +00BF09:00BF23 LVT None 0 +00BF24:00BF24 LV None 0 +00BF25:00BF3F LVT None 0 +00BF40:00BF40 LV None 0 +00BF41:00BF5B LVT None 0 +00BF5C:00BF5C LV None 0 +00BF5D:00BF77 LVT None 0 +00BF78:00BF78 LV None 0 +00BF79:00BF93 LVT None 0 +00BF94:00BF94 LV None 0 +00BF95:00BFAF LVT None 0 +00BFB0:00BFB0 LV None 0 +00BFB1:00BFCB LVT None 0 +00BFCC:00BFCC LV None 0 +00BFCD:00BFE7 LVT None 0 +00BFE8:00BFE8 LV None 0 +00BFE9:00C003 LVT None 0 +00C004:00C004 LV None 0 +00C005:00C01F LVT None 0 +00C020:00C020 LV None 0 +00C021:00C03B LVT None 0 +00C03C:00C03C LV None 0 +00C03D:00C057 LVT None 0 +00C058:00C058 LV None 0 +00C059:00C073 LVT None 0 +00C074:00C074 LV None 0 +00C075:00C08F LVT None 0 +00C090:00C090 LV None 0 +00C091:00C0AB LVT None 0 +00C0AC:00C0AC LV None 0 +00C0AD:00C0C7 LVT None 0 +00C0C8:00C0C8 LV None 0 +00C0C9:00C0E3 LVT None 0 +00C0E4:00C0E4 LV None 0 +00C0E5:00C0FF LVT None 0 +00C100:00C100 LV None 0 +00C101:00C11B LVT None 0 +00C11C:00C11C LV None 0 +00C11D:00C137 LVT None 0 +00C138:00C138 LV None 0 +00C139:00C153 LVT None 0 +00C154:00C154 LV None 0 +00C155:00C16F LVT None 0 +00C170:00C170 LV None 0 +00C171:00C18B LVT None 0 +00C18C:00C18C LV None 0 +00C18D:00C1A7 LVT None 0 +00C1A8:00C1A8 LV None 0 +00C1A9:00C1C3 LVT None 0 +00C1C4:00C1C4 LV None 0 +00C1C5:00C1DF LVT None 0 +00C1E0:00C1E0 LV None 0 +00C1E1:00C1FB LVT None 0 +00C1FC:00C1FC LV None 0 +00C1FD:00C217 LVT None 0 +00C218:00C218 LV None 0 +00C219:00C233 LVT None 0 +00C234:00C234 LV None 0 +00C235:00C24F LVT None 0 +00C250:00C250 LV None 0 +00C251:00C26B LVT None 0 +00C26C:00C26C LV None 0 +00C26D:00C287 LVT None 0 +00C288:00C288 LV None 0 +00C289:00C2A3 LVT None 0 +00C2A4:00C2A4 LV None 0 +00C2A5:00C2BF LVT None 0 +00C2C0:00C2C0 LV None 0 +00C2C1:00C2DB LVT None 0 +00C2DC:00C2DC LV None 0 +00C2DD:00C2F7 LVT None 0 +00C2F8:00C2F8 LV None 0 +00C2F9:00C313 LVT None 0 +00C314:00C314 LV None 0 +00C315:00C32F LVT None 0 +00C330:00C330 LV None 0 +00C331:00C34B LVT None 0 +00C34C:00C34C LV None 0 +00C34D:00C367 LVT None 0 +00C368:00C368 LV None 0 +00C369:00C383 LVT None 0 +00C384:00C384 LV None 0 +00C385:00C39F LVT None 0 +00C3A0:00C3A0 LV None 0 +00C3A1:00C3BB LVT None 0 +00C3BC:00C3BC LV None 0 +00C3BD:00C3D7 LVT None 0 +00C3D8:00C3D8 LV None 0 +00C3D9:00C3F3 LVT None 0 +00C3F4:00C3F4 LV None 0 +00C3F5:00C40F LVT None 0 +00C410:00C410 LV None 0 +00C411:00C42B LVT None 0 +00C42C:00C42C LV None 0 +00C42D:00C447 LVT None 0 +00C448:00C448 LV None 0 +00C449:00C463 LVT None 0 +00C464:00C464 LV None 0 +00C465:00C47F LVT None 0 +00C480:00C480 LV None 0 +00C481:00C49B LVT None 0 +00C49C:00C49C LV None 0 +00C49D:00C4B7 LVT None 0 +00C4B8:00C4B8 LV None 0 +00C4B9:00C4D3 LVT None 0 +00C4D4:00C4D4 LV None 0 +00C4D5:00C4EF LVT None 0 +00C4F0:00C4F0 LV None 0 +00C4F1:00C50B LVT None 0 +00C50C:00C50C LV None 0 +00C50D:00C527 LVT None 0 +00C528:00C528 LV None 0 +00C529:00C543 LVT None 0 +00C544:00C544 LV None 0 +00C545:00C55F LVT None 0 +00C560:00C560 LV None 0 +00C561:00C57B LVT None 0 +00C57C:00C57C LV None 0 +00C57D:00C597 LVT None 0 +00C598:00C598 LV None 0 +00C599:00C5B3 LVT None 0 +00C5B4:00C5B4 LV None 0 +00C5B5:00C5CF LVT None 0 +00C5D0:00C5D0 LV None 0 +00C5D1:00C5EB LVT None 0 +00C5EC:00C5EC LV None 0 +00C5ED:00C607 LVT None 0 +00C608:00C608 LV None 0 +00C609:00C623 LVT None 0 +00C624:00C624 LV None 0 +00C625:00C63F LVT None 0 +00C640:00C640 LV None 0 +00C641:00C65B LVT None 0 +00C65C:00C65C LV None 0 +00C65D:00C677 LVT None 0 +00C678:00C678 LV None 0 +00C679:00C693 LVT None 0 +00C694:00C694 LV None 0 +00C695:00C6AF LVT None 0 +00C6B0:00C6B0 LV None 0 +00C6B1:00C6CB LVT None 0 +00C6CC:00C6CC LV None 0 +00C6CD:00C6E7 LVT None 0 +00C6E8:00C6E8 LV None 0 +00C6E9:00C703 LVT None 0 +00C704:00C704 LV None 0 +00C705:00C71F LVT None 0 +00C720:00C720 LV None 0 +00C721:00C73B LVT None 0 +00C73C:00C73C LV None 0 +00C73D:00C757 LVT None 0 +00C758:00C758 LV None 0 +00C759:00C773 LVT None 0 +00C774:00C774 LV None 0 +00C775:00C78F LVT None 0 +00C790:00C790 LV None 0 +00C791:00C7AB LVT None 0 +00C7AC:00C7AC LV None 0 +00C7AD:00C7C7 LVT None 0 +00C7C8:00C7C8 LV None 0 +00C7C9:00C7E3 LVT None 0 +00C7E4:00C7E4 LV None 0 +00C7E5:00C7FF LVT None 0 +00C800:00C800 LV None 0 +00C801:00C81B LVT None 0 +00C81C:00C81C LV None 0 +00C81D:00C837 LVT None 0 +00C838:00C838 LV None 0 +00C839:00C853 LVT None 0 +00C854:00C854 LV None 0 +00C855:00C86F LVT None 0 +00C870:00C870 LV None 0 +00C871:00C88B LVT None 0 +00C88C:00C88C LV None 0 +00C88D:00C8A7 LVT None 0 +00C8A8:00C8A8 LV None 0 +00C8A9:00C8C3 LVT None 0 +00C8C4:00C8C4 LV None 0 +00C8C5:00C8DF LVT None 0 +00C8E0:00C8E0 LV None 0 +00C8E1:00C8FB LVT None 0 +00C8FC:00C8FC LV None 0 +00C8FD:00C917 LVT None 0 +00C918:00C918 LV None 0 +00C919:00C933 LVT None 0 +00C934:00C934 LV None 0 +00C935:00C94F LVT None 0 +00C950:00C950 LV None 0 +00C951:00C96B LVT None 0 +00C96C:00C96C LV None 0 +00C96D:00C987 LVT None 0 +00C988:00C988 LV None 0 +00C989:00C9A3 LVT None 0 +00C9A4:00C9A4 LV None 0 +00C9A5:00C9BF LVT None 0 +00C9C0:00C9C0 LV None 0 +00C9C1:00C9DB LVT None 0 +00C9DC:00C9DC LV None 0 +00C9DD:00C9F7 LVT None 0 +00C9F8:00C9F8 LV None 0 +00C9F9:00CA13 LVT None 0 +00CA14:00CA14 LV None 0 +00CA15:00CA2F LVT None 0 +00CA30:00CA30 LV None 0 +00CA31:00CA4B LVT None 0 +00CA4C:00CA4C LV None 0 +00CA4D:00CA67 LVT None 0 +00CA68:00CA68 LV None 0 +00CA69:00CA83 LVT None 0 +00CA84:00CA84 LV None 0 +00CA85:00CA9F LVT None 0 +00CAA0:00CAA0 LV None 0 +00CAA1:00CABB LVT None 0 +00CABC:00CABC LV None 0 +00CABD:00CAD7 LVT None 0 +00CAD8:00CAD8 LV None 0 +00CAD9:00CAF3 LVT None 0 +00CAF4:00CAF4 LV None 0 +00CAF5:00CB0F LVT None 0 +00CB10:00CB10 LV None 0 +00CB11:00CB2B LVT None 0 +00CB2C:00CB2C LV None 0 +00CB2D:00CB47 LVT None 0 +00CB48:00CB48 LV None 0 +00CB49:00CB63 LVT None 0 +00CB64:00CB64 LV None 0 +00CB65:00CB7F LVT None 0 +00CB80:00CB80 LV None 0 +00CB81:00CB9B LVT None 0 +00CB9C:00CB9C LV None 0 +00CB9D:00CBB7 LVT None 0 +00CBB8:00CBB8 LV None 0 +00CBB9:00CBD3 LVT None 0 +00CBD4:00CBD4 LV None 0 +00CBD5:00CBEF LVT None 0 +00CBF0:00CBF0 LV None 0 +00CBF1:00CC0B LVT None 0 +00CC0C:00CC0C LV None 0 +00CC0D:00CC27 LVT None 0 +00CC28:00CC28 LV None 0 +00CC29:00CC43 LVT None 0 +00CC44:00CC44 LV None 0 +00CC45:00CC5F LVT None 0 +00CC60:00CC60 LV None 0 +00CC61:00CC7B LVT None 0 +00CC7C:00CC7C LV None 0 +00CC7D:00CC97 LVT None 0 +00CC98:00CC98 LV None 0 +00CC99:00CCB3 LVT None 0 +00CCB4:00CCB4 LV None 0 +00CCB5:00CCCF LVT None 0 +00CCD0:00CCD0 LV None 0 +00CCD1:00CCEB LVT None 0 +00CCEC:00CCEC LV None 0 +00CCED:00CD07 LVT None 0 +00CD08:00CD08 LV None 0 +00CD09:00CD23 LVT None 0 +00CD24:00CD24 LV None 0 +00CD25:00CD3F LVT None 0 +00CD40:00CD40 LV None 0 +00CD41:00CD5B LVT None 0 +00CD5C:00CD5C LV None 0 +00CD5D:00CD77 LVT None 0 +00CD78:00CD78 LV None 0 +00CD79:00CD93 LVT None 0 +00CD94:00CD94 LV None 0 +00CD95:00CDAF LVT None 0 +00CDB0:00CDB0 LV None 0 +00CDB1:00CDCB LVT None 0 +00CDCC:00CDCC LV None 0 +00CDCD:00CDE7 LVT None 0 +00CDE8:00CDE8 LV None 0 +00CDE9:00CE03 LVT None 0 +00CE04:00CE04 LV None 0 +00CE05:00CE1F LVT None 0 +00CE20:00CE20 LV None 0 +00CE21:00CE3B LVT None 0 +00CE3C:00CE3C LV None 0 +00CE3D:00CE57 LVT None 0 +00CE58:00CE58 LV None 0 +00CE59:00CE73 LVT None 0 +00CE74:00CE74 LV None 0 +00CE75:00CE8F LVT None 0 +00CE90:00CE90 LV None 0 +00CE91:00CEAB LVT None 0 +00CEAC:00CEAC LV None 0 +00CEAD:00CEC7 LVT None 0 +00CEC8:00CEC8 LV None 0 +00CEC9:00CEE3 LVT None 0 +00CEE4:00CEE4 LV None 0 +00CEE5:00CEFF LVT None 0 +00CF00:00CF00 LV None 0 +00CF01:00CF1B LVT None 0 +00CF1C:00CF1C LV None 0 +00CF1D:00CF37 LVT None 0 +00CF38:00CF38 LV None 0 +00CF39:00CF53 LVT None 0 +00CF54:00CF54 LV None 0 +00CF55:00CF6F LVT None 0 +00CF70:00CF70 LV None 0 +00CF71:00CF8B LVT None 0 +00CF8C:00CF8C LV None 0 +00CF8D:00CFA7 LVT None 0 +00CFA8:00CFA8 LV None 0 +00CFA9:00CFC3 LVT None 0 +00CFC4:00CFC4 LV None 0 +00CFC5:00CFDF LVT None 0 +00CFE0:00CFE0 LV None 0 +00CFE1:00CFFB LVT None 0 +00CFFC:00CFFC LV None 0 +00CFFD:00D017 LVT None 0 +00D018:00D018 LV None 0 +00D019:00D033 LVT None 0 +00D034:00D034 LV None 0 +00D035:00D04F LVT None 0 +00D050:00D050 LV None 0 +00D051:00D06B LVT None 0 +00D06C:00D06C LV None 0 +00D06D:00D087 LVT None 0 +00D088:00D088 LV None 0 +00D089:00D0A3 LVT None 0 +00D0A4:00D0A4 LV None 0 +00D0A5:00D0BF LVT None 0 +00D0C0:00D0C0 LV None 0 +00D0C1:00D0DB LVT None 0 +00D0DC:00D0DC LV None 0 +00D0DD:00D0F7 LVT None 0 +00D0F8:00D0F8 LV None 0 +00D0F9:00D113 LVT None 0 +00D114:00D114 LV None 0 +00D115:00D12F LVT None 0 +00D130:00D130 LV None 0 +00D131:00D14B LVT None 0 +00D14C:00D14C LV None 0 +00D14D:00D167 LVT None 0 +00D168:00D168 LV None 0 +00D169:00D183 LVT None 0 +00D184:00D184 LV None 0 +00D185:00D19F LVT None 0 +00D1A0:00D1A0 LV None 0 +00D1A1:00D1BB LVT None 0 +00D1BC:00D1BC LV None 0 +00D1BD:00D1D7 LVT None 0 +00D1D8:00D1D8 LV None 0 +00D1D9:00D1F3 LVT None 0 +00D1F4:00D1F4 LV None 0 +00D1F5:00D20F LVT None 0 +00D210:00D210 LV None 0 +00D211:00D22B LVT None 0 +00D22C:00D22C LV None 0 +00D22D:00D247 LVT None 0 +00D248:00D248 LV None 0 +00D249:00D263 LVT None 0 +00D264:00D264 LV None 0 +00D265:00D27F LVT None 0 +00D280:00D280 LV None 0 +00D281:00D29B LVT None 0 +00D29C:00D29C LV None 0 +00D29D:00D2B7 LVT None 0 +00D2B8:00D2B8 LV None 0 +00D2B9:00D2D3 LVT None 0 +00D2D4:00D2D4 LV None 0 +00D2D5:00D2EF LVT None 0 +00D2F0:00D2F0 LV None 0 +00D2F1:00D30B LVT None 0 +00D30C:00D30C LV None 0 +00D30D:00D327 LVT None 0 +00D328:00D328 LV None 0 +00D329:00D343 LVT None 0 +00D344:00D344 LV None 0 +00D345:00D35F LVT None 0 +00D360:00D360 LV None 0 +00D361:00D37B LVT None 0 +00D37C:00D37C LV None 0 +00D37D:00D397 LVT None 0 +00D398:00D398 LV None 0 +00D399:00D3B3 LVT None 0 +00D3B4:00D3B4 LV None 0 +00D3B5:00D3CF LVT None 0 +00D3D0:00D3D0 LV None 0 +00D3D1:00D3EB LVT None 0 +00D3EC:00D3EC LV None 0 +00D3ED:00D407 LVT None 0 +00D408:00D408 LV None 0 +00D409:00D423 LVT None 0 +00D424:00D424 LV None 0 +00D425:00D43F LVT None 0 +00D440:00D440 LV None 0 +00D441:00D45B LVT None 0 +00D45C:00D45C LV None 0 +00D45D:00D477 LVT None 0 +00D478:00D478 LV None 0 +00D479:00D493 LVT None 0 +00D494:00D494 LV None 0 +00D495:00D4AF LVT None 0 +00D4B0:00D4B0 LV None 0 +00D4B1:00D4CB LVT None 0 +00D4CC:00D4CC LV None 0 +00D4CD:00D4E7 LVT None 0 +00D4E8:00D4E8 LV None 0 +00D4E9:00D503 LVT None 0 +00D504:00D504 LV None 0 +00D505:00D51F LVT None 0 +00D520:00D520 LV None 0 +00D521:00D53B LVT None 0 +00D53C:00D53C LV None 0 +00D53D:00D557 LVT None 0 +00D558:00D558 LV None 0 +00D559:00D573 LVT None 0 +00D574:00D574 LV None 0 +00D575:00D58F LVT None 0 +00D590:00D590 LV None 0 +00D591:00D5AB LVT None 0 +00D5AC:00D5AC LV None 0 +00D5AD:00D5C7 LVT None 0 +00D5C8:00D5C8 LV None 0 +00D5C9:00D5E3 LVT None 0 +00D5E4:00D5E4 LV None 0 +00D5E5:00D5FF LVT None 0 +00D600:00D600 LV None 0 +00D601:00D61B LVT None 0 +00D61C:00D61C LV None 0 +00D61D:00D637 LVT None 0 +00D638:00D638 LV None 0 +00D639:00D653 LVT None 0 +00D654:00D654 LV None 0 +00D655:00D66F LVT None 0 +00D670:00D670 LV None 0 +00D671:00D68B LVT None 0 +00D68C:00D68C LV None 0 +00D68D:00D6A7 LVT None 0 +00D6A8:00D6A8 LV None 0 +00D6A9:00D6C3 LVT None 0 +00D6C4:00D6C4 LV None 0 +00D6C5:00D6DF LVT None 0 +00D6E0:00D6E0 LV None 0 +00D6E1:00D6FB LVT None 0 +00D6FC:00D6FC LV None 0 +00D6FD:00D717 LVT None 0 +00D718:00D718 LV None 0 +00D719:00D733 LVT None 0 +00D734:00D734 LV None 0 +00D735:00D74F LVT None 0 +00D750:00D750 LV None 0 +00D751:00D76B LVT None 0 +00D76C:00D76C LV None 0 +00D76D:00D787 LVT None 0 +00D788:00D788 LV None 0 +00D789:00D7A3 LVT None 0 +00D7A4:00D7AF Other None 0 +00D7B0:00D7C6 V None 0 +00D7C7:00D7CA Other None 0 +00D7CB:00D7FB T None 0 +00D7FC:00FB1D Other None 0 +00FB1E:00FB1E Extend Extend 0 +00FB1F:00FDFF Other None 0 +00FE00:00FE0F Extend Extend 0 +00FE10:00FE1F Other None 0 +00FE20:00FE2F Extend Extend 0 +00FE30:00FEFE Other None 0 +00FEFF:00FEFF Control None 0 +00FF00:00FF9D Other None 0 +00FF9E:00FF9F Extend Extend 0 +00FFA0:00FFEF Other None 0 +00FFF0:00FFFB Control None 0 +00FFFC:0101FC Other None 0 +0101FD:0101FD Extend Extend 0 +0101FE:0102DF Other None 0 +0102E0:0102E0 Extend Extend 0 +0102E1:010375 Other None 0 +010376:01037A Extend Extend 0 +01037B:0109FF Other None 0 +010A00:010A00 Other Consonant 0 +010A01:010A03 Extend Extend 0 +010A04:010A04 Other None 0 +010A05:010A06 Extend Extend 0 +010A07:010A0B Other None 0 +010A0C:010A0F Extend Extend 0 +010A10:010A13 Other Consonant 0 +010A14:010A14 Other None 0 +010A15:010A17 Other Consonant 0 +010A18:010A18 Other None 0 +010A19:010A35 Other Consonant 0 +010A36:010A37 Other None 0 +010A38:010A3A Extend Extend 0 +010A3B:010A3E Other None 0 +010A3F:010A3F Extend Linker 0 +010A40:010AE4 Other None 0 +010AE5:010AE6 Extend Extend 0 +010AE7:010D23 Other None 0 +010D24:010D27 Extend Extend 0 +010D28:010D68 Other None 0 +010D69:010D6D Extend Extend 0 +010D6E:010EAA Other None 0 +010EAB:010EAC Extend Extend 0 +010EAD:010EF9 Other None 0 +010EFA:010EFF Extend Extend 0 +010F00:010F45 Other None 0 +010F46:010F50 Extend Extend 0 +010F51:010F81 Other None 0 +010F82:010F85 Extend Extend 0 +010F86:010FFF Other None 0 +011000:011000 SpacingMark None 0 +011001:011001 Extend Extend 0 +011002:011002 SpacingMark None 0 +011003:011037 Other None 0 +011038:011046 Extend Extend 0 +011047:01106F Other None 0 +011070:011070 Extend Extend 0 +011071:011072 Other None 0 +011073:011074 Extend Extend 0 +011075:01107E Other None 0 +01107F:011081 Extend Extend 0 +011082:011082 SpacingMark None 0 +011083:0110AF Other None 0 +0110B0:0110B2 SpacingMark None 0 +0110B3:0110B6 Extend Extend 0 +0110B7:0110B8 SpacingMark None 0 +0110B9:0110BA Extend Extend 0 +0110BB:0110BC Other None 0 +0110BD:0110BD Prepend None 0 +0110BE:0110C1 Other None 0 +0110C2:0110C2 Extend Extend 0 +0110C3:0110CC Other None 0 +0110CD:0110CD Prepend None 0 +0110CE:0110FF Other None 0 +011100:011102 Extend Extend 0 +011103:011126 Other Consonant 0 +011127:01112B Extend Extend 0 +01112C:01112C SpacingMark None 0 +01112D:011132 Extend Extend 0 +011133:011133 Extend Linker 0 +011134:011134 Extend Extend 0 +011135:011143 Other None 0 +011144:011144 Other Consonant 0 +011145:011146 SpacingMark None 0 +011147:011147 Other Consonant 0 +011148:011172 Other None 0 +011173:011173 Extend Extend 0 +011174:01117F Other None 0 +011180:011181 Extend Extend 0 +011182:011182 SpacingMark None 0 +011183:0111B2 Other None 0 +0111B3:0111B5 SpacingMark None 0 +0111B6:0111BE Extend Extend 0 +0111BF:0111BF SpacingMark None 0 +0111C0:0111C0 Extend Extend 0 +0111C1:0111C1 Other None 0 +0111C2:0111C3 Prepend None 0 +0111C4:0111C8 Other None 0 +0111C9:0111CC Extend Extend 0 +0111CD:0111CD Other None 0 +0111CE:0111CE SpacingMark None 0 +0111CF:0111CF Extend Extend 0 +0111D0:01122B Other None 0 +01122C:01122E SpacingMark None 0 +01122F:011231 Extend Extend 0 +011232:011233 SpacingMark None 0 +011234:011237 Extend Extend 0 +011238:01123D Other None 0 +01123E:01123E Extend Extend 0 +01123F:011240 Other None 0 +011241:011241 Extend Extend 0 +011242:0112DE Other None 0 +0112DF:0112DF Extend Extend 0 +0112E0:0112E2 SpacingMark None 0 +0112E3:0112EA Extend Extend 0 +0112EB:0112FF Other None 0 +011300:011301 Extend Extend 0 +011302:011303 SpacingMark None 0 +011304:01133A Other None 0 +01133B:01133C Extend Extend 0 +01133D:01133D Other None 0 +01133E:01133E Extend Extend 0 +01133F:01133F SpacingMark None 0 +011340:011340 Extend Extend 0 +011341:011344 SpacingMark None 0 +011345:011346 Other None 0 +011347:011348 SpacingMark None 0 +011349:01134A Other None 0 +01134B:01134C SpacingMark None 0 +01134D:01134D Extend Extend 0 +01134E:011356 Other None 0 +011357:011357 Extend Extend 0 +011358:011361 Other None 0 +011362:011363 SpacingMark None 0 +011364:011365 Other None 0 +011366:01136C Extend Extend 0 +01136D:01136F Other None 0 +011370:011374 Extend Extend 0 +011375:01137F Other None 0 +011380:011389 Other Consonant 0 +01138A:01138A Other None 0 +01138B:01138B Other Consonant 0 +01138C:01138D Other None 0 +01138E:01138E Other Consonant 0 +01138F:01138F Other None 0 +011390:0113B5 Other Consonant 0 +0113B6:0113B7 Other None 0 +0113B8:0113B8 Extend Extend 0 +0113B9:0113BA SpacingMark None 0 +0113BB:0113C0 Extend Extend 0 +0113C1:0113C1 Other None 0 +0113C2:0113C2 Extend Extend 0 +0113C3:0113C4 Other None 0 +0113C5:0113C5 Extend Extend 0 +0113C6:0113C6 Other None 0 +0113C7:0113C9 Extend Extend 0 +0113CA:0113CA SpacingMark None 0 +0113CB:0113CB Other None 0 +0113CC:0113CD SpacingMark None 0 +0113CE:0113CF Extend Extend 0 +0113D0:0113D0 Extend Linker 0 +0113D1:0113D1 Prepend None 0 +0113D2:0113D2 Extend Extend 0 +0113D3:0113E0 Other None 0 +0113E1:0113E2 Extend Extend 0 +0113E3:011434 Other None 0 +011435:011437 SpacingMark None 0 +011438:01143F Extend Extend 0 +011440:011441 SpacingMark None 0 +011442:011444 Extend Extend 0 +011445:011445 SpacingMark None 0 +011446:011446 Extend Extend 0 +011447:01145D Other None 0 +01145E:01145E Extend Extend 0 +01145F:0114AF Other None 0 +0114B0:0114B0 Extend Extend 0 +0114B1:0114B2 SpacingMark None 0 +0114B3:0114B8 Extend Extend 0 +0114B9:0114B9 SpacingMark None 0 +0114BA:0114BA Extend Extend 0 +0114BB:0114BC SpacingMark None 0 +0114BD:0114BD Extend Extend 0 +0114BE:0114BE SpacingMark None 0 +0114BF:0114C0 Extend Extend 0 +0114C1:0114C1 SpacingMark None 0 +0114C2:0114C3 Extend Extend 0 +0114C4:0115AE Other None 0 +0115AF:0115AF Extend Extend 0 +0115B0:0115B1 SpacingMark None 0 +0115B2:0115B5 Extend Extend 0 +0115B6:0115B7 Other None 0 +0115B8:0115BB SpacingMark None 0 +0115BC:0115BD Extend Extend 0 +0115BE:0115BE SpacingMark None 0 +0115BF:0115C0 Extend Extend 0 +0115C1:0115DB Other None 0 +0115DC:0115DD Extend Extend 0 +0115DE:01162F Other None 0 +011630:011632 SpacingMark None 0 +011633:01163A Extend Extend 0 +01163B:01163C SpacingMark None 0 +01163D:01163D Extend Extend 0 +01163E:01163E SpacingMark None 0 +01163F:011640 Extend Extend 0 +011641:0116AA Other None 0 +0116AB:0116AB Extend Extend 0 +0116AC:0116AC SpacingMark None 0 +0116AD:0116AD Extend Extend 0 +0116AE:0116AF SpacingMark None 0 +0116B0:0116B7 Extend Extend 0 +0116B8:01171C Other None 0 +01171D:01171D Extend Extend 0 +01171E:01171E SpacingMark None 0 +01171F:01171F Extend Extend 0 +011720:011721 Other None 0 +011722:011725 Extend Extend 0 +011726:011726 SpacingMark None 0 +011727:01172B Extend Extend 0 +01172C:01182B Other None 0 +01182C:01182E SpacingMark None 0 +01182F:011837 Extend Extend 0 +011838:011838 SpacingMark None 0 +011839:01183A Extend Extend 0 +01183B:0118FF Other None 0 +011900:011906 Other Consonant 0 +011907:011908 Other None 0 +011909:011909 Other Consonant 0 +01190A:01190B Other None 0 +01190C:011913 Other Consonant 0 +011914:011914 Other None 0 +011915:011916 Other Consonant 0 +011917:011917 Other None 0 +011918:01192F Other Consonant 0 +011930:011930 Extend Extend 0 +011931:011935 SpacingMark None 0 +011936:011936 Other None 0 +011937:011938 SpacingMark None 0 +011939:01193A Other None 0 +01193B:01193D Extend Extend 0 +01193E:01193E Extend Linker 0 +01193F:01193F Prepend None 0 +011940:011940 SpacingMark None 0 +011941:011941 Prepend None 0 +011942:011942 SpacingMark None 0 +011943:011943 Extend Extend 0 +011944:0119D0 Other None 0 +0119D1:0119D3 SpacingMark None 0 +0119D4:0119D7 Extend Extend 0 +0119D8:0119D9 Other None 0 +0119DA:0119DB Extend Extend 0 +0119DC:0119DF SpacingMark None 0 +0119E0:0119E0 Extend Extend 0 +0119E1:0119E3 Other None 0 +0119E4:0119E4 SpacingMark None 0 +0119E5:0119FF Other None 0 +011A00:011A00 Other Consonant 0 +011A01:011A0A Extend Extend 0 +011A0B:011A32 Other Consonant 0 +011A33:011A38 Extend Extend 0 +011A39:011A39 SpacingMark None 0 +011A3A:011A3A Other None 0 +011A3B:011A3E Extend Extend 0 +011A3F:011A46 Other None 0 +011A47:011A47 Extend Linker 0 +011A48:011A4F Other None 0 +011A50:011A50 Other Consonant 0 +011A51:011A56 Extend Extend 0 +011A57:011A58 SpacingMark None 0 +011A59:011A5B Extend Extend 0 +011A5C:011A83 Other Consonant 0 +011A84:011A89 Prepend None 0 +011A8A:011A96 Extend Extend 0 +011A97:011A97 SpacingMark None 0 +011A98:011A98 Extend Extend 0 +011A99:011A99 Extend Linker 0 +011A9A:011B5F Other None 0 +011B60:011B60 Extend Extend 0 +011B61:011B61 SpacingMark None 0 +011B62:011B64 Extend Extend 0 +011B65:011B65 SpacingMark None 0 +011B66:011B66 Extend Extend 0 +011B67:011B67 SpacingMark None 0 +011B68:011C2E Other None 0 +011C2F:011C2F SpacingMark None 0 +011C30:011C36 Extend Extend 0 +011C37:011C37 Other None 0 +011C38:011C3D Extend Extend 0 +011C3E:011C3E SpacingMark None 0 +011C3F:011C3F Extend Extend 0 +011C40:011C91 Other None 0 +011C92:011CA7 Extend Extend 0 +011CA8:011CA8 Other None 0 +011CA9:011CA9 SpacingMark None 0 +011CAA:011CB0 Extend Extend 0 +011CB1:011CB1 SpacingMark None 0 +011CB2:011CB3 Extend Extend 0 +011CB4:011CB4 SpacingMark None 0 +011CB5:011CB6 Extend Extend 0 +011CB7:011D30 Other None 0 +011D31:011D36 Extend Extend 0 +011D37:011D39 Other None 0 +011D3A:011D3A Extend Extend 0 +011D3B:011D3B Other None 0 +011D3C:011D3D Extend Extend 0 +011D3E:011D3E Other None 0 +011D3F:011D45 Extend Extend 0 +011D46:011D46 Prepend None 0 +011D47:011D47 Extend Extend 0 +011D48:011D89 Other None 0 +011D8A:011D8E SpacingMark None 0 +011D8F:011D8F Other None 0 +011D90:011D91 Extend Extend 0 +011D92:011D92 Other None 0 +011D93:011D94 SpacingMark None 0 +011D95:011D95 Extend Extend 0 +011D96:011D96 SpacingMark None 0 +011D97:011D97 Extend Extend 0 +011D98:011EF2 Other None 0 +011EF3:011EF4 Extend Extend 0 +011EF5:011EF6 SpacingMark None 0 +011EF7:011EFF Other None 0 +011F00:011F01 Extend Extend 0 +011F02:011F02 Prepend None 0 +011F03:011F03 SpacingMark None 0 +011F04:011F10 Other Consonant 0 +011F11:011F11 Other None 0 +011F12:011F33 Other Consonant 0 +011F34:011F35 SpacingMark None 0 +011F36:011F3A Extend Extend 0 +011F3B:011F3D Other None 0 +011F3E:011F3F SpacingMark None 0 +011F40:011F41 Extend Extend 0 +011F42:011F42 Extend Linker 0 +011F43:011F59 Other None 0 +011F5A:011F5A Extend Extend 0 +011F5B:01342F Other None 0 +013430:01343F Control None 0 +013440:013440 Extend Extend 0 +013441:013446 Other None 0 +013447:013455 Extend Extend 0 +013456:01611D Other None 0 +01611E:016129 Extend Extend 0 +01612A:01612C SpacingMark None 0 +01612D:01612F Extend Extend 0 +016130:016AEF Other None 0 +016AF0:016AF4 Extend Extend 0 +016AF5:016B2F Other None 0 +016B30:016B36 Extend Extend 0 +016B37:016D62 Other None 0 +016D63:016D63 V None 0 +016D64:016D66 Other None 0 +016D67:016D6A V None 0 +016D6B:016F4E Other None 0 +016F4F:016F4F Extend Extend 0 +016F50:016F50 Other None 0 +016F51:016F87 SpacingMark None 0 +016F88:016F8E Other None 0 +016F8F:016F92 Extend Extend 0 +016F93:016FE3 Other None 0 +016FE4:016FE4 Extend Extend 0 +016FE5:016FEF Other None 0 +016FF0:016FF1 Extend Extend 0 +016FF2:01BC9C Other None 0 +01BC9D:01BC9E Extend Extend 0 +01BC9F:01BC9F Other None 0 +01BCA0:01BCA3 Control None 0 +01BCA4:01CEFF Other None 0 +01CF00:01CF2D Extend Extend 0 +01CF2E:01CF2F Other None 0 +01CF30:01CF46 Extend Extend 0 +01CF47:01D164 Other None 0 +01D165:01D169 Extend Extend 0 +01D16A:01D16C Other None 0 +01D16D:01D172 Extend Extend 0 +01D173:01D17A Control None 0 +01D17B:01D182 Extend Extend 0 +01D183:01D184 Other None 0 +01D185:01D18B Extend Extend 0 +01D18C:01D1A9 Other None 0 +01D1AA:01D1AD Extend Extend 0 +01D1AE:01D241 Other None 0 +01D242:01D244 Extend Extend 0 +01D245:01D9FF Other None 0 +01DA00:01DA36 Extend Extend 0 +01DA37:01DA3A Other None 0 +01DA3B:01DA6C Extend Extend 0 +01DA6D:01DA74 Other None 0 +01DA75:01DA75 Extend Extend 0 +01DA76:01DA83 Other None 0 +01DA84:01DA84 Extend Extend 0 +01DA85:01DA9A Other None 0 +01DA9B:01DA9F Extend Extend 0 +01DAA0:01DAA0 Other None 0 +01DAA1:01DAAF Extend Extend 0 +01DAB0:01DFFF Other None 0 +01E000:01E006 Extend Extend 0 +01E007:01E007 Other None 0 +01E008:01E018 Extend Extend 0 +01E019:01E01A Other None 0 +01E01B:01E021 Extend Extend 0 +01E022:01E022 Other None 0 +01E023:01E024 Extend Extend 0 +01E025:01E025 Other None 0 +01E026:01E02A Extend Extend 0 +01E02B:01E08E Other None 0 +01E08F:01E08F Extend Extend 0 +01E090:01E12F Other None 0 +01E130:01E136 Extend Extend 0 +01E137:01E2AD Other None 0 +01E2AE:01E2AE Extend Extend 0 +01E2AF:01E2EB Other None 0 +01E2EC:01E2EF Extend Extend 0 +01E2F0:01E4EB Other None 0 +01E4EC:01E4EF Extend Extend 0 +01E4F0:01E5ED Other None 0 +01E5EE:01E5EF Extend Extend 0 +01E5F0:01E6E2 Other None 0 +01E6E3:01E6E3 Extend Extend 0 +01E6E4:01E6E5 Other None 0 +01E6E6:01E6E6 Extend Extend 0 +01E6E7:01E6ED Other None 0 +01E6EE:01E6EF Extend Extend 0 +01E6F0:01E6F4 Other None 0 +01E6F5:01E6F5 Extend Extend 0 +01E6F6:01E8CF Other None 0 +01E8D0:01E8D6 Extend Extend 0 +01E8D7:01E943 Other None 0 +01E944:01E94A Extend Extend 0 +01E94B:01F003 Other None 0 +01F004:01F004 Other None 1 +01F005:01F02B Other None 0 +01F02C:01F02F Other None 1 +01F030:01F093 Other None 0 +01F094:01F09F Other None 1 +01F0A0:01F0AE Other None 0 +01F0AF:01F0B0 Other None 1 +01F0B1:01F0BF Other None 0 +01F0C0:01F0C0 Other None 1 +01F0C1:01F0CE Other None 0 +01F0CF:01F0D0 Other None 1 +01F0D1:01F0F5 Other None 0 +01F0F6:01F0FF Other None 1 +01F100:01F16F Other None 0 +01F170:01F171 Other None 1 +01F172:01F17D Other None 0 +01F17E:01F17F Other None 1 +01F180:01F18D Other None 0 +01F18E:01F18E Other None 1 +01F18F:01F190 Other None 0 +01F191:01F19A Other None 1 +01F19B:01F1AD Other None 0 +01F1AE:01F1E5 Other None 1 +01F1E6:01F1FF Regional_Indicator None 0 +01F200:01F200 Other None 0 +01F201:01F20F Other None 1 +01F210:01F219 Other None 0 +01F21A:01F21A Other None 1 +01F21B:01F22E Other None 0 +01F22F:01F22F Other None 1 +01F230:01F231 Other None 0 +01F232:01F23A Other None 1 +01F23B:01F23B Other None 0 +01F23C:01F23F Other None 1 +01F240:01F248 Other None 0 +01F249:01F25F Other None 1 +01F260:01F265 Other None 0 +01F266:01F321 Other None 1 +01F322:01F323 Other None 0 +01F324:01F393 Other None 1 +01F394:01F395 Other None 0 +01F396:01F397 Other None 1 +01F398:01F398 Other None 0 +01F399:01F39B Other None 1 +01F39C:01F39D Other None 0 +01F39E:01F3F0 Other None 1 +01F3F1:01F3F2 Other None 0 +01F3F3:01F3F5 Other None 1 +01F3F6:01F3F6 Other None 0 +01F3F7:01F3FA Other None 1 +01F3FB:01F3FF Extend Extend 0 +01F400:01F4FD Other None 1 +01F4FE:01F4FE Other None 0 +01F4FF:01F53D Other None 1 +01F53E:01F548 Other None 0 +01F549:01F54E Other None 1 +01F54F:01F54F Other None 0 +01F550:01F567 Other None 1 +01F568:01F56E Other None 0 +01F56F:01F570 Other None 1 +01F571:01F572 Other None 0 +01F573:01F57A Other None 1 +01F57B:01F586 Other None 0 +01F587:01F587 Other None 1 +01F588:01F589 Other None 0 +01F58A:01F58D Other None 1 +01F58E:01F58F Other None 0 +01F590:01F590 Other None 1 +01F591:01F594 Other None 0 +01F595:01F596 Other None 1 +01F597:01F5A3 Other None 0 +01F5A4:01F5A5 Other None 1 +01F5A6:01F5A7 Other None 0 +01F5A8:01F5A8 Other None 1 +01F5A9:01F5B0 Other None 0 +01F5B1:01F5B2 Other None 1 +01F5B3:01F5BB Other None 0 +01F5BC:01F5BC Other None 1 +01F5BD:01F5C1 Other None 0 +01F5C2:01F5C4 Other None 1 +01F5C5:01F5D0 Other None 0 +01F5D1:01F5D3 Other None 1 +01F5D4:01F5DB Other None 0 +01F5DC:01F5DE Other None 1 +01F5DF:01F5E0 Other None 0 +01F5E1:01F5E1 Other None 1 +01F5E2:01F5E2 Other None 0 +01F5E3:01F5E3 Other None 1 +01F5E4:01F5E7 Other None 0 +01F5E8:01F5E8 Other None 1 +01F5E9:01F5EE Other None 0 +01F5EF:01F5EF Other None 1 +01F5F0:01F5F2 Other None 0 +01F5F3:01F5F3 Other None 1 +01F5F4:01F5F9 Other None 0 +01F5FA:01F64F Other None 1 +01F650:01F67F Other None 0 +01F680:01F6C5 Other None 1 +01F6C6:01F6CA Other None 0 +01F6CB:01F6D2 Other None 1 +01F6D3:01F6D4 Other None 0 +01F6D5:01F6E5 Other None 1 +01F6E6:01F6E8 Other None 0 +01F6E9:01F6E9 Other None 1 +01F6EA:01F6EA Other None 0 +01F6EB:01F6F0 Other None 1 +01F6F1:01F6F2 Other None 0 +01F6F3:01F6FF Other None 1 +01F700:01F7D9 Other None 0 +01F7DA:01F7FF Other None 1 +01F800:01F80B Other None 0 +01F80C:01F80F Other None 1 +01F810:01F847 Other None 0 +01F848:01F84F Other None 1 +01F850:01F859 Other None 0 +01F85A:01F85F Other None 1 +01F860:01F887 Other None 0 +01F888:01F88F Other None 1 +01F890:01F8AD Other None 0 +01F8AE:01F8AF Other None 1 +01F8B0:01F8BB Other None 0 +01F8BC:01F8BF Other None 1 +01F8C0:01F8C1 Other None 0 +01F8C2:01F8CF Other None 1 +01F8D0:01F8D8 Other None 0 +01F8D9:01F8FF Other None 1 +01F900:01F90B Other None 0 +01F90C:01F93A Other None 1 +01F93B:01F93B Other None 0 +01F93C:01F945 Other None 1 +01F946:01F946 Other None 0 +01F947:01F9FF Other None 1 +01FA00:01FA57 Other None 0 +01FA58:01FA5F Other None 1 +01FA60:01FA6D Other None 0 +01FA6E:01FAFF Other None 1 +01FB00:01FBFF Other None 0 +01FC00:01FFFD Other None 1 +01FFFE:0DFFFF Other None 0 +0E0000:0E001F Control None 0 +0E0020:0E007F Extend Extend 0 +0E0080:0E00FF Control None 0 +0E0100:0E01EF Extend Extend 0 +0E01F0:0E0FFF Control None 0 +0E1000:10FFFF Other None 0 diff --git a/crates/unicode/tests/differential.rs b/crates/unicode/tests/differential.rs index 1bed13e7faf..675ea721cae 100644 --- a/crates/unicode/tests/differential.rs +++ b/crates/unicode/tests/differential.rs @@ -11,7 +11,7 @@ //! Both data files use the same run-length format: one `predicate` line per //! str method, followed by comma-separated hex `start:end` inclusive ranges. -// spell-checker:ignore recategorized recategorizations +// spell-checker:ignore recategorized recategorizations incb #[cfg(test)] mod tests { @@ -136,13 +136,11 @@ mod tests { if let Some(first) = iter.next() { let (mut start, mut end) = (first, first); for cp in iter { - if cp == end + 1 { - end = cp; - } else { + if cp != end + 1 { runs.push((start, end)); start = cp; - end = cp; } + end = cp; } runs.push((start, end)); } @@ -421,4 +419,85 @@ mod tests { panic!("{msg}"); } } + + #[test] + fn unicode17_grapheme_properties_exact_final() { + use rustpython_unicode::grapheme; + use rustpython_wtf8::CodePoint; + + const MAX: u32 = 0x110000; + const REFERENCE: &str = include_str!("data/cpython3.15_graphemes.txt"); + const GCB: [&str; 14] = [ + "Other", + "Prepend", + "CR", + "LF", + "Control", + "Extend", + "Regional_Indicator", + "SpacingMark", + "L", + "V", + "T", + "LV", + "LVT", + "ZWJ", + ]; + const INCB: [&str; 4] = ["None", "Linker", "Consonant", "Extend"]; + assert!(REFERENCE.len() <= 1024 * 1024, "oracle size bound"); + assert_eq!( + REFERENCE.lines().next(), + Some("# CPython d220409a13b77de7a6c30abe16ea90db01528edc; Unicode 17.0.0"), + "wrong reference provenance" + ); + let mut next = 0; + let mut rows = 0; + let mut mismatches = 0usize; + let mut first = Vec::new(); + for line in REFERENCE.lines().filter(|line| !line.starts_with('#')) { + rows += 1; + assert!(rows <= 100000, "oracle range count bound"); + let fields: Vec<_> = line.split_whitespace().collect(); + assert_eq!(fields.len(), 4, "invalid oracle row"); + let (start, end) = fields[0].split_once(':').expect("start:end"); + let start = u32::from_str_radix(start, 16).expect("hex start"); + let end = u32::from_str_radix(end, 16).expect("hex end"); + assert_eq!(start, next, "gap, overlap, or unordered oracle range"); + assert!(start <= end && end < MAX, "invalid oracle range"); + assert!( + GCB.contains(&fields[1]) && INCB.contains(&fields[2]), + "invalid property name" + ); + let pictographic = match fields[3] { + "0" => false, + "1" => true, + _ => panic!("invalid Extended_Pictographic value"), + }; + for cp in start..=end { + // Includes surrogates; converting through char would lose coverage. + let point = CodePoint::from_u32(cp).expect("valid code point"); + let actual = ( + grapheme::grapheme_cluster_break(point), + grapheme::indic_conjunct_break(point), + grapheme::extended_pictographic(point), + ); + let expected = (fields[1], fields[2], pictographic); + if actual != expected { + mismatches += 1; + if first.len() < 20 { + first.push(format!("U+{cp:06X}: expected {expected:?}, got {actual:?}")); + } + } + } + next = end + 1; + } + assert_eq!(next, MAX, "oracle does not cover every code point"); + assert_eq!( + mismatches, + 0, + "first {} mismatches: {}", + first.len(), + first.join("; ") + ); + } } diff --git a/crates/unicode/tests/generate_reference.py b/crates/unicode/tests/generate_reference.py index 6a78230de75..4f881153c9c 100644 --- a/crates/unicode/tests/generate_reference.py +++ b/crates/unicode/tests/generate_reference.py @@ -21,6 +21,176 @@ MAX = 0x110000 + +def generate_graphemes(args) -> int: + """Write a new Unicode 17 oracle, without touching the older fixtures.""" + import hashlib + import json + import subprocess + + commit = "d220409a13b77de7a6c30abe16ea90db01528edc" + gcb_names = ( + "Other", + "Prepend", + "CR", + "LF", + "Control", + "Extend", + "Regional_Indicator", + "SpacingMark", + "L", + "V", + "T", + "LV", + "LVT", + "ZWJ", + ) + incb_names = ("None", "Linker", "Consonant", "Extend") + + def digest(path): + h = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(65536), b""): + h.update(chunk) + return h.hexdigest() + + if sys.implementation.name != "cpython" or unicodedata.unidata_version != "17.0.0": + raise RuntimeError("requires the reviewed CPython Unicode 17 oracle") + executable = pathlib.Path(sys.executable).resolve(strict=True) + extension = pathlib.Path(unicodedata.__file__).resolve(strict=True) + if ( + digest(executable) != args.python_sha256 + or digest(extension) != args.unicodedata_sha256 + ): + raise RuntimeError("oracle executable or extension hash mismatch") + source = args.cpython_source.resolve(strict=True) + head = subprocess.check_output( + ["git", "-C", str(source), "rev-parse", "HEAD"], + timeout=5, + text=True, + ).strip() + if head != commit: + raise RuntimeError("CPython source is not the pinned final commit") + header = source / "Modules/unicodedata_db.h" + blob = subprocess.check_output( + ["git", "-C", str(source), "show", f"{commit}:Modules/unicodedata_db.h"], + timeout=5, + ) + if digest(header) != hashlib.sha256(blob).hexdigest(): + raise RuntimeError("CPython Unicode database header differs from pinned source") + + outputs = [ + args.graphemes_output, + args.graphemes_raw_output, + args.graphemes_manifest, + ] + outputs = [p.resolve() for p in outputs] + if len(set(outputs)) != 3: + raise RuntimeError("oracle output paths must be distinct") + old_data = pathlib.Path(__file__).resolve().parent / "data" + for path in outputs: + if path.exists() or path.is_relative_to(old_data): + raise RuntimeError( + "outputs must be new files outside existing fixture directory" + ) + if not path.parent.is_dir(): + raise RuntimeError("output parents must already exist") + + range_path, raw_path, manifest_path = outputs + ranges = [] + start = 0 + previous = None + raw_hash = hashlib.sha256() + # Exclusive creation prevents replacing any existing reference artifact. + with raw_path.open("xb") as raw: + buffer = bytearray() + for cp in range(MAX): + c = chr(cp) + triple = ( + gcb_names.index(unicodedata.grapheme_cluster_break(c)), + incb_names.index(unicodedata.indic_conjunct_break(c)), + int(unicodedata.extended_pictographic(c)), + ) + if triple != previous: + if previous is not None: + ranges.append((start, cp - 1, previous)) + if len(ranges) > 100000: + raise RuntimeError("range oracle exceeds reviewed count bound") + start, previous = cp, triple + buffer.extend(triple) + if len(buffer) >= 65535: + raw.write(buffer) + raw_hash.update(buffer) + buffer.clear() + raw.write(buffer) + raw_hash.update(buffer) + ranges.append((start, MAX - 1, previous)) + if raw_path.stat().st_size != MAX * 3: + raise RuntimeError("raw oracle length mismatch") + lines = [ + f"# CPython {commit}; Unicode 17.0.0", + "# Inclusive contiguous ranges: start:end GCB InCB Extended_Pictographic", + f"# Reconstructed raw SHA256 {raw_hash.hexdigest()}", + ] + for start, end, (gcb, incb, pictographic) in ranges: + lines.append( + f"{start:06X}:{end:06X} {gcb_names[gcb]} {incb_names[incb]} {pictographic}" + ) + text = ("\n".join(lines) + "\n").encode("ascii") + if len(text) > 1024 * 1024 or len(ranges) > 100000: + raise RuntimeError("range oracle exceeds reviewed size bound") + reconstructed = hashlib.sha256() + next_cp = 0 + for line in text.decode("ascii").splitlines(): + if line.startswith("#"): + continue + bounds, gcb, incb, pictographic = line.split() + first, last = (int(value, 16) for value in bounds.split(":")) + if first != next_cp or not first <= last < MAX: + raise RuntimeError("range encoding has a gap, overlap, or invalid bound") + triple = bytes( + (gcb_names.index(gcb), incb_names.index(incb), int(pictographic)) + ) + reconstructed.update(triple * (last - first + 1)) + next_cp = last + 1 + if next_cp != MAX or reconstructed.hexdigest() != raw_hash.hexdigest(): + raise RuntimeError("range reconstruction differs from the raw property oracle") + with range_path.open("xb") as output: + output.write(text) + manifest = { + "cpython_commit": commit, + "unicode_version": unicodedata.unidata_version, + "runtime_version": sys.version, + "runtime_git": getattr(sys, "_git", None), + "python": str(executable), + "python_sha256": digest(executable), + "unicodedata": str(extension), + "unicodedata_sha256": digest(extension), + "database_header_sha256": digest(header), + "generator_sha256": digest(pathlib.Path(__file__)), + "codepoints": MAX, + "properties": 3, + "ranges": len(ranges), + "gcb_encoding": gcb_names, + "incb_encoding": incb_names, + "raw_bytes": MAX * 3, + "raw_sha256": raw_hash.hexdigest(), + "ranges_bytes": len(text), + "ranges_sha256": hashlib.sha256(text).hexdigest(), + } + manifest_bytes = (json.dumps(manifest, indent=2) + "\n").encode("utf-8") + # Total artifact bound, independent of the launcher's per-file rlimit. + if ( + len(manifest_bytes) > 16384 + or MAX * 3 + len(text) + len(manifest_bytes) > 4_407_296 + ): + raise RuntimeError("total oracle artifact budget exceeded") + with manifest_path.open("xb") as output: + output.write(manifest_bytes) + print(json.dumps(manifest, sort_keys=True)) + return 0 + + # str predicates: name -> single-char method. STR_PREDICATES = { "isalpha": str.isalpha, @@ -111,4 +281,18 @@ def main() -> int: if __name__ == "__main__": - raise SystemExit(main()) + if len(sys.argv) == 1: + raise SystemExit(main()) + import argparse + + parser = argparse.ArgumentParser( + description="Generate only a new grapheme property oracle" + ) + parser.add_argument("--graphemes-only", action="store_true", required=True) + parser.add_argument("--graphemes-output", type=pathlib.Path, required=True) + parser.add_argument("--graphemes-raw-output", type=pathlib.Path, required=True) + parser.add_argument("--graphemes-manifest", type=pathlib.Path, required=True) + parser.add_argument("--cpython-source", type=pathlib.Path, required=True) + parser.add_argument("--python-sha256", required=True) + parser.add_argument("--unicodedata-sha256", required=True) + raise SystemExit(generate_graphemes(parser.parse_args())) diff --git a/crates/unicode/unicode/README.md b/crates/unicode/unicode/README.md index fa77fb42603..8aae556cc66 100644 --- a/crates/unicode/unicode/README.md +++ b/crates/unicode/unicode/README.md @@ -7,3 +7,5 @@ The files in `latest` need to be periodically bumped to match `icu4x` and Rust. `NameAliases.txt` and `NamedSequences.txt` feed `unicodedata.lookup` (formal aliases and named sequences). They are not used by `unicodedata.name`, which still reports the official character name. RustPython vendors [Unicode 3.2.0](https://www.unicode.org/reports/tr28/tr28-3.html) to match CPython. CPython uses 3.2.0 to ensure backwards compatibility with a few older modules. Unicode 3.2.0 was released in 2002 and does not need periodic refreshes. + +`Blocks.txt` supplies the ranges and original block names for `unicodedata.block`. The current copy is from [Unicode 17.0.0](https://www.unicode.org/Public/17.0.0/ucd/Blocks.txt). diff --git a/crates/unicode/unicode/latest/Blocks.txt b/crates/unicode/unicode/latest/Blocks.txt new file mode 100644 index 00000000000..5c24ab60cb1 --- /dev/null +++ b/crates/unicode/unicode/latest/Blocks.txt @@ -0,0 +1,383 @@ +# Blocks-17.0.0.txt +# Date: 2025-08-01 +# © 2025 Unicode®, Inc. +# Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the U.S. and other countries. +# For terms of use and license, see https://www.unicode.org/terms_of_use.html +# +# Unicode Character Database +# For documentation, see https://www.unicode.org/reports/tr44/ +# +# Format: +# Start Code..End Code; Block Name + +# ================================================ + +# Note: When comparing block names, casing, whitespace, hyphens, +# and underbars are ignored. +# For example, "Latin Extended-A" and "latin extended a" are equivalent. +# For more information on the comparison of property values, +# see UAX #44: https://www.unicode.org/reports/tr44/ +# +# All block ranges start with a value where (cp MOD 16) = 0, +# and end with a value where (cp MOD 16) = 15. In other words, +# the last hexadecimal digit of the start of range is ...0 +# and the last hexadecimal digit of the end of range is ...F. +# This constraint on block ranges guarantees that allocations +# are done in terms of whole columns, and that code chart display +# never involves splitting columns in the charts. +# +# All code points not explicitly listed for Block +# have the value No_Block. + +# Property: Block +# +# @missing: 0000..10FFFF; No_Block + +0000..007F; Basic Latin +0080..00FF; Latin-1 Supplement +0100..017F; Latin Extended-A +0180..024F; Latin Extended-B +0250..02AF; IPA Extensions +02B0..02FF; Spacing Modifier Letters +0300..036F; Combining Diacritical Marks +0370..03FF; Greek and Coptic +0400..04FF; Cyrillic +0500..052F; Cyrillic Supplement +0530..058F; Armenian +0590..05FF; Hebrew +0600..06FF; Arabic +0700..074F; Syriac +0750..077F; Arabic Supplement +0780..07BF; Thaana +07C0..07FF; NKo +0800..083F; Samaritan +0840..085F; Mandaic +0860..086F; Syriac Supplement +0870..089F; Arabic Extended-B +08A0..08FF; Arabic Extended-A +0900..097F; Devanagari +0980..09FF; Bengali +0A00..0A7F; Gurmukhi +0A80..0AFF; Gujarati +0B00..0B7F; Oriya +0B80..0BFF; Tamil +0C00..0C7F; Telugu +0C80..0CFF; Kannada +0D00..0D7F; Malayalam +0D80..0DFF; Sinhala +0E00..0E7F; Thai +0E80..0EFF; Lao +0F00..0FFF; Tibetan +1000..109F; Myanmar +10A0..10FF; Georgian +1100..11FF; Hangul Jamo +1200..137F; Ethiopic +1380..139F; Ethiopic Supplement +13A0..13FF; Cherokee +1400..167F; Unified Canadian Aboriginal Syllabics +1680..169F; Ogham +16A0..16FF; Runic +1700..171F; Tagalog +1720..173F; Hanunoo +1740..175F; Buhid +1760..177F; Tagbanwa +1780..17FF; Khmer +1800..18AF; Mongolian +18B0..18FF; Unified Canadian Aboriginal Syllabics Extended +1900..194F; Limbu +1950..197F; Tai Le +1980..19DF; New Tai Lue +19E0..19FF; Khmer Symbols +1A00..1A1F; Buginese +1A20..1AAF; Tai Tham +1AB0..1AFF; Combining Diacritical Marks Extended +1B00..1B7F; Balinese +1B80..1BBF; Sundanese +1BC0..1BFF; Batak +1C00..1C4F; Lepcha +1C50..1C7F; Ol Chiki +1C80..1C8F; Cyrillic Extended-C +1C90..1CBF; Georgian Extended +1CC0..1CCF; Sundanese Supplement +1CD0..1CFF; Vedic Extensions +1D00..1D7F; Phonetic Extensions +1D80..1DBF; Phonetic Extensions Supplement +1DC0..1DFF; Combining Diacritical Marks Supplement +1E00..1EFF; Latin Extended Additional +1F00..1FFF; Greek Extended +2000..206F; General Punctuation +2070..209F; Superscripts and Subscripts +20A0..20CF; Currency Symbols +20D0..20FF; Combining Diacritical Marks for Symbols +2100..214F; Letterlike Symbols +2150..218F; Number Forms +2190..21FF; Arrows +2200..22FF; Mathematical Operators +2300..23FF; Miscellaneous Technical +2400..243F; Control Pictures +2440..245F; Optical Character Recognition +2460..24FF; Enclosed Alphanumerics +2500..257F; Box Drawing +2580..259F; Block Elements +25A0..25FF; Geometric Shapes +2600..26FF; Miscellaneous Symbols +2700..27BF; Dingbats +27C0..27EF; Miscellaneous Mathematical Symbols-A +27F0..27FF; Supplemental Arrows-A +2800..28FF; Braille Patterns +2900..297F; Supplemental Arrows-B +2980..29FF; Miscellaneous Mathematical Symbols-B +2A00..2AFF; Supplemental Mathematical Operators +2B00..2BFF; Miscellaneous Symbols and Arrows +2C00..2C5F; Glagolitic +2C60..2C7F; Latin Extended-C +2C80..2CFF; Coptic +2D00..2D2F; Georgian Supplement +2D30..2D7F; Tifinagh +2D80..2DDF; Ethiopic Extended +2DE0..2DFF; Cyrillic Extended-A +2E00..2E7F; Supplemental Punctuation +2E80..2EFF; CJK Radicals Supplement +2F00..2FDF; Kangxi Radicals +2FF0..2FFF; Ideographic Description Characters +3000..303F; CJK Symbols and Punctuation +3040..309F; Hiragana +30A0..30FF; Katakana +3100..312F; Bopomofo +3130..318F; Hangul Compatibility Jamo +3190..319F; Kanbun +31A0..31BF; Bopomofo Extended +31C0..31EF; CJK Strokes +31F0..31FF; Katakana Phonetic Extensions +3200..32FF; Enclosed CJK Letters and Months +3300..33FF; CJK Compatibility +3400..4DBF; CJK Unified Ideographs Extension A +4DC0..4DFF; Yijing Hexagram Symbols +4E00..9FFF; CJK Unified Ideographs +A000..A48F; Yi Syllables +A490..A4CF; Yi Radicals +A4D0..A4FF; Lisu +A500..A63F; Vai +A640..A69F; Cyrillic Extended-B +A6A0..A6FF; Bamum +A700..A71F; Modifier Tone Letters +A720..A7FF; Latin Extended-D +A800..A82F; Syloti Nagri +A830..A83F; Common Indic Number Forms +A840..A87F; Phags-pa +A880..A8DF; Saurashtra +A8E0..A8FF; Devanagari Extended +A900..A92F; Kayah Li +A930..A95F; Rejang +A960..A97F; Hangul Jamo Extended-A +A980..A9DF; Javanese +A9E0..A9FF; Myanmar Extended-B +AA00..AA5F; Cham +AA60..AA7F; Myanmar Extended-A +AA80..AADF; Tai Viet +AAE0..AAFF; Meetei Mayek Extensions +AB00..AB2F; Ethiopic Extended-A +AB30..AB6F; Latin Extended-E +AB70..ABBF; Cherokee Supplement +ABC0..ABFF; Meetei Mayek +AC00..D7AF; Hangul Syllables +D7B0..D7FF; Hangul Jamo Extended-B +D800..DB7F; High Surrogates +DB80..DBFF; High Private Use Surrogates +DC00..DFFF; Low Surrogates +E000..F8FF; Private Use Area +F900..FAFF; CJK Compatibility Ideographs +FB00..FB4F; Alphabetic Presentation Forms +FB50..FDFF; Arabic Presentation Forms-A +FE00..FE0F; Variation Selectors +FE10..FE1F; Vertical Forms +FE20..FE2F; Combining Half Marks +FE30..FE4F; CJK Compatibility Forms +FE50..FE6F; Small Form Variants +FE70..FEFF; Arabic Presentation Forms-B +FF00..FFEF; Halfwidth and Fullwidth Forms +FFF0..FFFF; Specials +10000..1007F; Linear B Syllabary +10080..100FF; Linear B Ideograms +10100..1013F; Aegean Numbers +10140..1018F; Ancient Greek Numbers +10190..101CF; Ancient Symbols +101D0..101FF; Phaistos Disc +10280..1029F; Lycian +102A0..102DF; Carian +102E0..102FF; Coptic Epact Numbers +10300..1032F; Old Italic +10330..1034F; Gothic +10350..1037F; Old Permic +10380..1039F; Ugaritic +103A0..103DF; Old Persian +10400..1044F; Deseret +10450..1047F; Shavian +10480..104AF; Osmanya +104B0..104FF; Osage +10500..1052F; Elbasan +10530..1056F; Caucasian Albanian +10570..105BF; Vithkuqi +105C0..105FF; Todhri +10600..1077F; Linear A +10780..107BF; Latin Extended-F +10800..1083F; Cypriot Syllabary +10840..1085F; Imperial Aramaic +10860..1087F; Palmyrene +10880..108AF; Nabataean +108E0..108FF; Hatran +10900..1091F; Phoenician +10920..1093F; Lydian +10940..1095F; Sidetic +10980..1099F; Meroitic Hieroglyphs +109A0..109FF; Meroitic Cursive +10A00..10A5F; Kharoshthi +10A60..10A7F; Old South Arabian +10A80..10A9F; Old North Arabian +10AC0..10AFF; Manichaean +10B00..10B3F; Avestan +10B40..10B5F; Inscriptional Parthian +10B60..10B7F; Inscriptional Pahlavi +10B80..10BAF; Psalter Pahlavi +10C00..10C4F; Old Turkic +10C80..10CFF; Old Hungarian +10D00..10D3F; Hanifi Rohingya +10D40..10D8F; Garay +10E60..10E7F; Rumi Numeral Symbols +10E80..10EBF; Yezidi +10EC0..10EFF; Arabic Extended-C +10F00..10F2F; Old Sogdian +10F30..10F6F; Sogdian +10F70..10FAF; Old Uyghur +10FB0..10FDF; Chorasmian +10FE0..10FFF; Elymaic +11000..1107F; Brahmi +11080..110CF; Kaithi +110D0..110FF; Sora Sompeng +11100..1114F; Chakma +11150..1117F; Mahajani +11180..111DF; Sharada +111E0..111FF; Sinhala Archaic Numbers +11200..1124F; Khojki +11280..112AF; Multani +112B0..112FF; Khudawadi +11300..1137F; Grantha +11380..113FF; Tulu-Tigalari +11400..1147F; Newa +11480..114DF; Tirhuta +11580..115FF; Siddham +11600..1165F; Modi +11660..1167F; Mongolian Supplement +11680..116CF; Takri +116D0..116FF; Myanmar Extended-C +11700..1174F; Ahom +11800..1184F; Dogra +118A0..118FF; Warang Citi +11900..1195F; Dives Akuru +119A0..119FF; Nandinagari +11A00..11A4F; Zanabazar Square +11A50..11AAF; Soyombo +11AB0..11ABF; Unified Canadian Aboriginal Syllabics Extended-A +11AC0..11AFF; Pau Cin Hau +11B00..11B5F; Devanagari Extended-A +11B60..11B7F; Sharada Supplement +11BC0..11BFF; Sunuwar +11C00..11C6F; Bhaiksuki +11C70..11CBF; Marchen +11D00..11D5F; Masaram Gondi +11D60..11DAF; Gunjala Gondi +11DB0..11DEF; Tolong Siki +11EE0..11EFF; Makasar +11F00..11F5F; Kawi +11FB0..11FBF; Lisu Supplement +11FC0..11FFF; Tamil Supplement +12000..123FF; Cuneiform +12400..1247F; Cuneiform Numbers and Punctuation +12480..1254F; Early Dynastic Cuneiform +12F90..12FFF; Cypro-Minoan +13000..1342F; Egyptian Hieroglyphs +13430..1345F; Egyptian Hieroglyph Format Controls +13460..143FF; Egyptian Hieroglyphs Extended-A +14400..1467F; Anatolian Hieroglyphs +16100..1613F; Gurung Khema +16800..16A3F; Bamum Supplement +16A40..16A6F; Mro +16A70..16ACF; Tangsa +16AD0..16AFF; Bassa Vah +16B00..16B8F; Pahawh Hmong +16D40..16D7F; Kirat Rai +16E40..16E9F; Medefaidrin +16EA0..16EDF; Beria Erfe +16F00..16F9F; Miao +16FE0..16FFF; Ideographic Symbols and Punctuation +17000..187FF; Tangut +18800..18AFF; Tangut Components +18B00..18CFF; Khitan Small Script +18D00..18D7F; Tangut Supplement +18D80..18DFF; Tangut Components Supplement +1AFF0..1AFFF; Kana Extended-B +1B000..1B0FF; Kana Supplement +1B100..1B12F; Kana Extended-A +1B130..1B16F; Small Kana Extension +1B170..1B2FF; Nushu +1BC00..1BC9F; Duployan +1BCA0..1BCAF; Shorthand Format Controls +1CC00..1CEBF; Symbols for Legacy Computing Supplement +1CEC0..1CEFF; Miscellaneous Symbols Supplement +1CF00..1CFCF; Znamenny Musical Notation +1D000..1D0FF; Byzantine Musical Symbols +1D100..1D1FF; Musical Symbols +1D200..1D24F; Ancient Greek Musical Notation +1D2C0..1D2DF; Kaktovik Numerals +1D2E0..1D2FF; Mayan Numerals +1D300..1D35F; Tai Xuan Jing Symbols +1D360..1D37F; Counting Rod Numerals +1D400..1D7FF; Mathematical Alphanumeric Symbols +1D800..1DAAF; Sutton SignWriting +1DF00..1DFFF; Latin Extended-G +1E000..1E02F; Glagolitic Supplement +1E030..1E08F; Cyrillic Extended-D +1E100..1E14F; Nyiakeng Puachue Hmong +1E290..1E2BF; Toto +1E2C0..1E2FF; Wancho +1E4D0..1E4FF; Nag Mundari +1E5D0..1E5FF; Ol Onal +1E6C0..1E6FF; Tai Yo +1E7E0..1E7FF; Ethiopic Extended-B +1E800..1E8DF; Mende Kikakui +1E900..1E95F; Adlam +1EC70..1ECBF; Indic Siyaq Numbers +1ED00..1ED4F; Ottoman Siyaq Numbers +1EE00..1EEFF; Arabic Mathematical Alphabetic Symbols +1F000..1F02F; Mahjong Tiles +1F030..1F09F; Domino Tiles +1F0A0..1F0FF; Playing Cards +1F100..1F1FF; Enclosed Alphanumeric Supplement +1F200..1F2FF; Enclosed Ideographic Supplement +1F300..1F5FF; Miscellaneous Symbols and Pictographs +1F600..1F64F; Emoticons +1F650..1F67F; Ornamental Dingbats +1F680..1F6FF; Transport and Map Symbols +1F700..1F77F; Alchemical Symbols +1F780..1F7FF; Geometric Shapes Extended +1F800..1F8FF; Supplemental Arrows-C +1F900..1F9FF; Supplemental Symbols and Pictographs +1FA00..1FA6F; Chess Symbols +1FA70..1FAFF; Symbols and Pictographs Extended-A +1FB00..1FBFF; Symbols for Legacy Computing +20000..2A6DF; CJK Unified Ideographs Extension B +2A700..2B73F; CJK Unified Ideographs Extension C +2B740..2B81F; CJK Unified Ideographs Extension D +2B820..2CEAF; CJK Unified Ideographs Extension E +2CEB0..2EBEF; CJK Unified Ideographs Extension F +2EBF0..2EE5F; CJK Unified Ideographs Extension I +2F800..2FA1F; CJK Compatibility Ideographs Supplement +30000..3134F; CJK Unified Ideographs Extension G +31350..323AF; CJK Unified Ideographs Extension H +323B0..3347F; CJK Unified Ideographs Extension J +E0000..E007F; Tags +E0100..E01EF; Variation Selectors Supplement +F0000..FFFFF; Supplementary Private Use Area-A +100000..10FFFF; Supplementary Private Use Area-B + +# EOF diff --git a/crates/venvlauncher/src/main.rs b/crates/venvlauncher/src/main.rs index 7087e791e37..f21e81205ff 100644 --- a/crates/venvlauncher/src/main.rs +++ b/crates/venvlauncher/src/main.rs @@ -8,18 +8,20 @@ compile_error!("venvlauncher is only supported on Windows"); use std::env; +use std::ffi::OsString; use std::fs; use std::path::{Path, PathBuf}; -use std::process::ExitCode; -fn main() -> ExitCode { - match run() { - Ok(code) => ExitCode::from(code as u8), +fn main() { + let code = match run() { + Ok(code) => code, Err(e) => { - eprintln!("venvlauncher error: {}", e); - ExitCode::from(1) + eprintln!("venvlauncher error: {e}"); + 1 } - } + }; + // ExitCode::from(u8) would truncate the Windows process status. + std::process::exit(code as i32); } fn run() -> Result> { @@ -31,13 +33,13 @@ fn run() -> Result> { .to_string_lossy(); // 2. Determine target executable name based on launcher name - // pythonw.exe / venvwlauncher -> pythonw.exe (GUI, no console) - // python.exe / venvlauncher -> python.exe (console) + // pythonw.exe / venvwlauncher -> GUI interpreter (no console) + // python.exe / venvlauncher -> console interpreter let exe_name_lower = exe_name.to_lowercase(); - let target_exe = if exe_name_lower.contains("pythonw") || exe_name_lower.contains("venvw") { - "pythonw.exe" + let target_exes = if exe_name_lower.contains("pythonw") || exe_name_lower.contains("venvw") { + ["rustpythonw.exe", "pythonw.exe"] } else { - "python.exe" + ["rustpython.exe", "python.exe"] }; // 3. Find pyvenv.cfg @@ -54,10 +56,11 @@ fn run() -> Result> { let home = read_home(&cfg_path)?; // 5. Locate python executable in home directory - let python_path = PathBuf::from(&home).join(target_exe); - if !python_path.exists() { - return Err(format!("Python not found: {}", python_path.display()).into()); - } + let python_path = target_exes + .iter() + .map(|name| PathBuf::from(&home).join(name)) + .find(|path| path.is_file()) + .ok_or_else(|| format!("Python not found in: {home}"))?; // 6. Set __PYVENV_LAUNCHER__ environment variable // This tells Python it was launched from a venv @@ -67,7 +70,7 @@ fn run() -> Result> { } // 7. Launch Python with same arguments - let args: Vec = env::args().skip(1).collect(); + let args: Vec = env::args_os().skip(1).collect(); launch_process(&python_path, &args) } @@ -95,7 +98,7 @@ fn read_home(cfg_path: &Path) -> Result> { } /// Launch the Python process and wait for it to complete -fn launch_process(exe: &Path, args: &[String]) -> Result> { +fn launch_process(exe: &Path, args: &[OsString]) -> Result> { use std::process::Command; let status = Command::new(exe).args(args).status()?; diff --git a/crates/venvlauncher/tests/launcher.rs b/crates/venvlauncher/tests/launcher.rs new file mode 100644 index 00000000000..94ad46bdaac --- /dev/null +++ b/crates/venvlauncher/tests/launcher.rs @@ -0,0 +1,165 @@ +#![cfg(windows)] + +#[cfg(test)] +mod tests { + use core::sync::atomic::{AtomicUsize, Ordering}; + use std::ffi::OsString; + use std::fs; + use std::os::windows::ffi::OsStringExt; + use std::path::PathBuf; + use std::process::Command; + + struct TestVenv { + root: PathBuf, + } + + impl TestVenv { + fn new() -> Self { + static NEXT_ID: AtomicUsize = AtomicUsize::new(0); + let root = loop { + let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); + let path = std::env::temp_dir().join(format!( + "rustpython-venvlauncher-{}-{id}", + std::process::id() + )); + match fs::create_dir(&path) { + Ok(()) => break path, + Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue, + Err(error) => panic!("cannot create test environment: {error}"), + } + }; + let fixture = Self { root }; + let home = fixture.root.join("home"); + let scripts = fixture.root.join("Scripts"); + fs::create_dir(&home).unwrap(); + fs::create_dir(&scripts).unwrap(); + let system_root = std::env::var_os("SystemRoot").unwrap(); + fs::copy( + PathBuf::from(system_root).join("System32/cmd.exe"), + home.join("python.exe"), + ) + .unwrap(); + fs::copy( + env!("CARGO_BIN_EXE_venvlaunchert"), + scripts.join("python.exe"), + ) + .unwrap(); + fs::write( + fixture.root.join("pyvenv.cfg"), + format!("home = {}\n", home.display()), + ) + .unwrap(); + fixture + } + + fn command(&self) -> Command { + Command::new(self.root.join("Scripts/python.exe")) + } + } + + impl Drop for TestVenv { + fn drop(&mut self) { + fs::remove_dir_all(&self.root).unwrap(); + } + } + + #[test] + fn preserves_windows_exit_codes() { + let fixture = TestVenv::new(); + for code in [0_u32, 255, 256, 4660, 0xC0000005, u32::MAX] { + let output = fixture + .command() + .args(["/d", "/c", "exit", &code.to_string()]) + .output() + .unwrap(); + assert_eq!(output.status.code().map(|code| code as u32), Some(code)); + } + } + + #[test] + fn forwards_windows_wide_arguments() { + let fixture = TestVenv::new(); + for units in [&[0xd800][..], &[0xdc00][..], &[0xd83d, 0xde00][..]] { + let output = fixture + .command() + .args(["/d", "/u", "/c", "echo"]) + .arg(OsString::from_wide(units)) + .output() + .unwrap(); + assert!(output.status.success(), "{:?}", output.stderr); + let expected: Vec<_> = units + .iter() + .copied() + .chain([13, 10]) + .flat_map(u16::to_le_bytes) + .collect(); + assert_eq!(output.stdout, expected); + } + } + + #[test] + fn launches_rustpython_interpreter_names() { + for (launcher, interpreter) in [ + ("python.exe", "rustpython.exe"), + ("pythonw.exe", "rustpythonw.exe"), + ("venvlauncher.exe", "rustpython.exe"), + ("venvwlauncher.exe", "rustpythonw.exe"), + ("venvlaunchert.exe", "rustpython.exe"), + ("venvwlaunchert.exe", "rustpythonw.exe"), + ] { + let fixture = TestVenv::new(); + let home = fixture.root.join("home"); + fs::rename(home.join("python.exe"), home.join(interpreter)).unwrap(); + let launcher = fixture.root.join("Scripts").join(launcher); + fs::copy(env!("CARGO_BIN_EXE_venvlaunchert"), &launcher).unwrap(); + let output = Command::new(launcher) + .args(["/d", "/c", "exit", "23"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(23), "{:?}", output.stderr); + } + } + + #[test] + fn prefers_rustpython_over_legacy_name() { + let fixture = TestVenv::new(); + let home = fixture.root.join("home"); + fs::rename(home.join("python.exe"), home.join("rustpython.exe")).unwrap(); + fs::write(home.join("python.exe"), b"not an executable").unwrap(); + let output = fixture + .command() + .args(["/d", "/c", "exit", "23"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(23), "{:?}", output.stderr); + } + + #[test] + fn retains_legacy_windowed_name() { + let fixture = TestVenv::new(); + let home = fixture.root.join("home"); + fs::rename(home.join("python.exe"), home.join("pythonw.exe")).unwrap(); + let launcher = fixture.root.join("Scripts/pythonw.exe"); + fs::copy(env!("CARGO_BIN_EXE_venvlaunchert"), &launcher).unwrap(); + let output = Command::new(launcher) + .args(["/d", "/c", "exit", "23"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(23), "{:?}", output.stderr); + } + + #[test] + fn does_not_use_console_interpreter_for_windowed_launcher() { + let fixture = TestVenv::new(); + let home = fixture.root.join("home"); + fs::rename(home.join("python.exe"), home.join("rustpython.exe")).unwrap(); + let launcher = fixture.root.join("Scripts/pythonw.exe"); + fs::copy(env!("CARGO_BIN_EXE_venvlaunchert"), &launcher).unwrap(); + let output = Command::new(launcher) + .args(["/d", "/c", "exit", "23"]) + .output() + .unwrap(); + assert_eq!(output.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&output.stderr).contains("Python not found")); + } +} diff --git a/crates/vm/Cargo.toml b/crates/vm/Cargo.toml index 862929c1ae5..7c1935d208d 100644 --- a/crates/vm/Cargo.toml +++ b/crates/vm/Cargo.toml @@ -12,7 +12,9 @@ license.workspace = true [features] default = ["compiler", "wasmbind", "gc", "host_env", "stdio", "doc"] doc = ["dep:rustpython-doc", "dep:xz"] -host_env = ["rustpython-host_env/ctypes"] +host_env = ["host_io", "rustpython-host_env/ctypes"] +# FileIO without unrelated host modules such as ctypes, subprocess and signals. +host_io = ["rustpython-host_env/host_io"] stdio = [] importlib = [] encodings = ["importlib"] @@ -21,7 +23,7 @@ opcode-histogram = [] flame-it = ["flame", "flamer"] freeze-stdlib = ["encodings"] jit = ["rustpython-jit"] -threading = ["rustpython-common/threading"] +threading = ["rustpython-common/threading", "dep:parking_lot_core"] gc = [] compiler = ["parser", "codegen", "rustpython-compiler"] ast = ["ruff_python_ast", "ruff_text_size"] @@ -59,7 +61,6 @@ indexmap = { workspace = true } itertools = { workspace = true } itoa = { workspace = true } is-macro = { workspace = true } -jiff = { workspace = true } libc = { workspace = true } log = { workspace = true } malachite-bigint = { workspace = true } @@ -68,6 +69,7 @@ num-integer = { workspace = true } num-traits = { workspace = true } num_enum = { workspace = true } parking_lot = { workspace = true } +parking_lot_core = { workspace = true, optional = true } paste = { workspace = true } rapidhash = { workspace = true } scopeguard = { workspace = true } @@ -92,6 +94,9 @@ widestring = { workspace = true } [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] wasm-bindgen = { workspace = true, optional = true } +[target.'cfg(not(unix))'.dependencies] +jiff = { workspace = true } + [build-dependencies] glob = { workspace = true } jiff = { workspace = true } diff --git a/crates/vm/Lib/README.md b/crates/vm/Lib/README.md index 84fb7057836..19b1aa764bc 100644 --- a/crates/vm/Lib/README.md +++ b/crates/vm/Lib/README.md @@ -2,5 +2,5 @@ A collection of Python modules frozen into the VM at compile time. -See the comments in [`frozen.rs`](../src/frozen.rs) for explanations of the +See the comments in [`frozen.rs`](../../compiler-core/src/frozen.rs) for explanations of the different files and subdirectories in this directory. diff --git a/crates/vm/Lib/python_builtins/_thread.py b/crates/vm/Lib/python_builtins/_thread.py deleted file mode 120000 index 9079ca9fda3..00000000000 --- a/crates/vm/Lib/python_builtins/_thread.py +++ /dev/null @@ -1 +0,0 @@ -../../../../Lib/_dummy_thread.py \ No newline at end of file diff --git a/crates/vm/Lib/python_builtins/_thread.py b/crates/vm/Lib/python_builtins/_thread.py new file mode 100644 index 00000000000..9a2bac96b20 --- /dev/null +++ b/crates/vm/Lib/python_builtins/_thread.py @@ -0,0 +1,320 @@ +"""Drop-in replacement for the thread module. + +Meant to be used as a brain-dead substitute so that threaded code does +not need to be rewritten for when the thread module is not present. + +Suggested usage is:: + + try: + import _thread + except ImportError: + import _dummy_thread as _thread + +""" + +# Exports only things specified by thread documentation; +# skipping obsolete synonyms allocate(), start_new(), exit_thread(). +__all__ = [ + "error", + "start_new_thread", + "exit", + "get_ident", + "allocate_lock", + "interrupt_main", + "LockType", + "RLock", + "_count", + "start_joinable_thread", + "daemon_threads_allowed", + "_shutdown", + "_make_thread_handle", + "_ThreadHandle", + "_get_main_thread_ident", + "_is_main_interpreter", + "_local", +] + +# A dummy value +TIMEOUT_MAX = 2**31 + +# Main thread ident for dummy implementation +_MAIN_THREAD_IDENT = -1 + +# NOTE: this module can be imported early in the extension building process, +# and so top level imports of other modules should be avoided. Instead, all +# imports are done when needed on a function-by-function basis. Since threads +# are disabled, the import lock should not be an issue anyway (??). + +error = RuntimeError + + +def start_new_thread(function, args, kwargs={}): + """Dummy implementation of _thread.start_new_thread(). + + Compatibility is maintained by making sure that ``args`` is a + tuple and ``kwargs`` is a dictionary. If an exception is raised + and it is SystemExit (which can be done by _thread.exit()) it is + caught and nothing is done; all other exceptions are printed out + by using traceback.print_exc(). + + If the executed function calls interrupt_main the KeyboardInterrupt will be + raised when the function returns. + + """ + if type(args) != type(tuple()): + raise TypeError("2nd arg must be a tuple") + if type(kwargs) != type(dict()): + raise TypeError("3rd arg must be a dict") + global _main + _main = False + try: + function(*args, **kwargs) + except SystemExit: + pass + except: + import traceback + + traceback.print_exc() + _main = True + global _interrupt + if _interrupt: + _interrupt = False + raise KeyboardInterrupt + + +def start_joinable_thread(function, handle=None, daemon=True): + """Dummy implementation of _thread.start_joinable_thread(). + + In dummy thread, we just run the function synchronously. + """ + if handle is None: + handle = _ThreadHandle() + try: + function() + except SystemExit: + pass + except: + import traceback + + traceback.print_exc() + handle._set_done() + return handle + + +def daemon_threads_allowed(): + """Dummy implementation of _thread.daemon_threads_allowed().""" + return True + + +def _shutdown(): + """Dummy implementation of _thread._shutdown().""" + pass + + +def _make_thread_handle(ident): + """Dummy implementation of _thread._make_thread_handle().""" + handle = _ThreadHandle() + handle._ident = ident + return handle + + +def _get_main_thread_ident(): + """Dummy implementation of _thread._get_main_thread_ident().""" + return _MAIN_THREAD_IDENT + + +def _is_main_interpreter(): + """Dummy implementation of _thread._is_main_interpreter().""" + return True + + +def exit(): + """Dummy implementation of _thread.exit().""" + raise SystemExit + + +def get_ident(): + """Dummy implementation of _thread.get_ident(). + + Since this module should only be used when _threadmodule is not + available, it is safe to assume that the current process is the + only thread. Thus a constant can be safely returned. + """ + return _MAIN_THREAD_IDENT + + +def allocate_lock(): + """Dummy implementation of _thread.allocate_lock().""" + return LockType() + + +def stack_size(size=None): + """Dummy implementation of _thread.stack_size().""" + if size is not None: + raise error("setting thread stack size not supported") + return 0 + + +def _set_sentinel(): + """Dummy implementation of _thread._set_sentinel().""" + return LockType() + + +def _count(): + """Dummy implementation of _thread._count().""" + return 0 + + +class LockType(object): + """Class implementing dummy implementation of _thread.LockType. + + Compatibility is maintained by maintaining self.locked_status + which is a boolean that stores the state of the lock. Pickling of + the lock, though, should not be done since if the _thread module is + then used with an unpickled ``lock()`` from here problems could + occur from this class not having atomic methods. + + """ + + def __init__(self): + self.locked_status = False + + def acquire(self, waitflag=None, timeout=-1): + """Dummy implementation of acquire(). + + For blocking calls, self.locked_status is automatically set to + True and returned appropriately based on value of + ``waitflag``. If it is non-blocking, then the value is + actually checked and not set if it is already acquired. This + is all done so that threading.Condition's assert statements + aren't triggered and throw a little fit. + + """ + if waitflag is None or waitflag: + self.locked_status = True + return True + else: + if not self.locked_status: + self.locked_status = True + return True + else: + if timeout > 0: + import time + + time.sleep(timeout) + return False + + __enter__ = acquire + + def __exit__(self, typ, val, tb): + self.release() + + def release(self): + """Release the dummy lock.""" + # XXX Perhaps shouldn't actually bother to test? Could lead + # to problems for complex, threaded code. + if not self.locked_status: + raise error + self.locked_status = False + return True + + def locked(self): + return self.locked_status + + def _at_fork_reinit(self): + self.locked_status = False + + def __repr__(self): + return "<%s %s.%s object at %s>" % ( + "locked" if self.locked_status else "unlocked", + self.__class__.__module__, + self.__class__.__qualname__, + hex(id(self)), + ) + + +class _ThreadHandle: + """Dummy implementation of _thread._ThreadHandle.""" + + def __init__(self): + self._ident = _MAIN_THREAD_IDENT + self._done = False + + @property + def ident(self): + return self._ident + + def _set_done(self): + self._done = True + + def is_done(self): + return self._done + + def join(self, timeout=None): + # In dummy thread, thread is always done + return + + def __repr__(self): + return f"<_ThreadHandle ident={self._ident}>" + + +# Used to signal that interrupt_main was called in a "thread" +_interrupt = False +# True when not executing in a "thread" +_main = True + + +def interrupt_main(): + """Set _interrupt flag to True to have start_new_thread raise + KeyboardInterrupt upon exiting.""" + if _main: + raise KeyboardInterrupt + else: + global _interrupt + _interrupt = True + + +class RLock: + def __init__(self): + self.locked_count = 0 + + def acquire(self, waitflag=None, timeout=-1): + self.locked_count += 1 + return True + + __enter__ = acquire + + def __exit__(self, typ, val, tb): + self.release() + + def release(self): + if not self.locked_count: + raise error + self.locked_count -= 1 + return True + + def locked(self): + return self.locked_count != 0 + + def __repr__(self): + return "<%s %s.%s object owner=%s count=%s at %s>" % ( + "locked" if self.locked_count else "unlocked", + self.__class__.__module__, + self.__class__.__qualname__, + get_ident() if self.locked_count else 0, + self.locked_count, + hex(id(self)), + ) + + +class _local: + """Dummy implementation of _thread._local (thread-local storage). + + There is only one thread, so the instance dict doubles as the per-thread + dict and normal attribute semantics (descriptors included) apply. + """ + + def __new__(cls, *args, **kwargs): + if (args or kwargs) and cls.__init__ is object.__init__: + raise TypeError("Initialization arguments are not supported") + return object.__new__(cls) diff --git a/crates/vm/Lib/python_builtins/zipimport.py b/crates/vm/Lib/python_builtins/zipimport.py new file mode 120000 index 00000000000..48db8e1fa25 --- /dev/null +++ b/crates/vm/Lib/python_builtins/zipimport.py @@ -0,0 +1 @@ +../../../../Lib/zipimport.py \ No newline at end of file diff --git a/crates/vm/build.rs b/crates/vm/build.rs index 867cf577502..8fe451a8bab 100644 --- a/crates/vm/build.rs +++ b/crates/vm/build.rs @@ -3,7 +3,7 @@ reason = "build scripts cannot use rustpython-host_env" )] -use jiff::{Timestamp, Zoned, tz::TimeZone}; +use jiff::{Timestamp, ZonedDateTime, tz::TimeZone}; use std::{ env, io, process::Command, @@ -21,9 +21,10 @@ fn main() { println!("cargo:rerun-if-changed={display}"); } println!("cargo:rerun-if-changed=../../Lib/importlib/_bootstrap.py"); + println!("cargo:rerun-if-changed=../../Lib/zipimport.py"); - // = 3.14.0alpha - python_version(3, 14, 0, "alpha", 0); + // = 3.15.0alpha + python_version(3, 15, 0, "alpha", 0); println!("cargo:rustc-env=RUSTPYTHON_GIT_HASH={}", git_hash()); println!( @@ -114,9 +115,9 @@ fn get_git_timestamp_raw() -> Option { Timestamp::from_second(git_timestamp).ok() } -fn get_git_timestamp_datetime() -> Zoned { - get_git_timestamp_raw().map_or_else(Zoned::now, |timestamp| { - Zoned::new(timestamp, TimeZone::system()) +fn get_git_timestamp_datetime() -> ZonedDateTime { + get_git_timestamp_raw().map_or_else(ZonedDateTime::now, |timestamp| { + ZonedDateTime::new(timestamp, TimeZone::system()) }) } @@ -162,14 +163,16 @@ fn get_version(cpy_version: &str) -> (String, String) { // Windows: include MSC v. for compatibility with ctypes.util.find_library // MSC v.1929 = VS 2019, version 14+ makes find_msvcrt() return None let msc_info = cfg_select! { - windows => {{ - // Include both RustPython identifier and MSC v. for compatibility - if cfg!(target_pointer_width = "64") { - " MSC v.1929 64 bit (AMD64)" - } else { - " MSC v.1929 32 bit (Intel)" + windows => { + { + // Include both RustPython identifier and MSC v. for compatibility + if cfg!(target_pointer_width = "64") { + " MSC v.1929 64 bit (AMD64)" + } else { + " MSC v.1929 32 bit (Intel)" + } } - }}, + } _ => "", }; diff --git a/crates/vm/src/anystr.rs b/crates/vm/src/anystr.rs index f1ea7d7354d..1409029f10e 100644 --- a/crates/vm/src/anystr.rs +++ b/crates/vm/src/anystr.rs @@ -5,11 +5,50 @@ use rustpython_unicode::case; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyInt, PyIntRef, PyTuple}, + builtins::{PyInt, PyTuple}, convert::TryFromBorrowedObject, - function::PySsize, + function::{ArgIndex, PySsize}, }; +pub(crate) fn checked_replace_len( + original: usize, + old: usize, + new: usize, + count: usize, +) -> Option { + let result = if new >= old { + original.checked_add(count.checked_mul(new - old)?)? + } else { + original.checked_sub(count.checked_mul(old - new)?)? + }; + isize::try_from(result).ok().map(|_| result) +} + +pub(crate) fn checked_expandtabs_len( + original: usize, + chars: impl Iterator, + tabsize: usize, +) -> Option { + let mut result = original; + let mut column = 0; + for ch in chars { + if ch == u32::from(b'\t') { + let spaces = if tabsize == 0 { + 0 + } else { + tabsize - column % tabsize + }; + result = checked_replace_len(result, 1, spaces, 1)?; + column += spaces; + } else if ch == u32::from(b'\r') || ch == u32::from(b'\n') { + column = 0; + } else { + column += 1; + } + } + Some(result) +} + #[derive(FromArgs)] pub struct SplitArgs { #[pyarg(any, optional)] @@ -37,45 +76,74 @@ impl ExpandTabsArgs { } #[derive(FromArgs)] +#[from_args(text_signature = "(prefix[, start[, end]], /)")] pub(crate) struct StartsEndsWithArgs { #[pyarg(positional)] affix: PyObjectRef, #[pyarg(positional, default)] - start: Option, + start: Option, #[pyarg(positional, default)] - end: Option, + end: Option, +} + +#[derive(FromArgs)] +#[from_args(text_signature = "(suffix[, start[, end]], /)")] +pub(crate) struct EndsWithArgs { + #[pyarg(flatten)] + pub(crate) inner: StartsEndsWithArgs, } impl StartsEndsWithArgs { - pub(crate) fn get_value(self, len: usize) -> (PyObjectRef, Option>) { + pub(crate) fn parts(&self, len: usize) -> (&PyObject, Option>) { let range = if self.start.is_some() || self.end.is_some() { Some(adjust_indices( - self.start.as_deref(), - self.end.as_deref(), + self.start.as_ref().map(AsRef::as_ref), + self.end.as_ref().map(AsRef::as_ref), len, )) } else { None }; - (self.affix, range) + (&self.affix, range) } - #[inline] - pub(crate) fn prepare(self, s: &S, len: usize, substr: F) -> Option<(PyObjectRef, &S)> + pub(crate) fn matches<'a, T, F>( + &'a self, + len: usize, + func_name: &str, + py_type_name: &str, + predicate: F, + vm: &VirtualMachine, + ) -> PyResult where - S: ?Sized + AnyStr, - F: Fn(&S, Range) -> &S, + T: TryFromBorrowedObject<'a>, + F: Fn(T, Option>) -> bool, { - let (affix, range) = self.get_value(len); - let substr = if let Some(range) = range { - if !range.is_normal() { - return None; - } - substr(s, range) - } else { - s - }; - Some((affix, substr)) + let (affix, range) = self.parts(len); + // Validate each affix even when the requested range cannot match. A + // tuple is still short-circuited after its first successful match. + single_or_tuple_any( + affix, + &|item| Ok(predicate(item, range.clone())), + &|obj, in_tuple| { + let name = obj.class().slot_name(); + if py_type_name == "str" { + let name = &name[..name.floor_char_boundary(100)]; + Some(if in_tuple { + format!("tuple for {func_name} must only contain str, not {name}") + } else { + format!("{func_name} first arg must be str or a tuple of str, not {name}") + }) + } else if in_tuple { + None + } else { + Some(format!( + "{func_name} first arg must be bytes or a tuple of bytes, not {name}" + )) + } + }, + vm, + ) } } @@ -216,35 +284,6 @@ pub(crate) trait AnyStr { where F: Fn(&Self) -> PyObjectRef; - #[inline] - fn py_starts_ends_with<'a, T, F>( - &self, - affix: &'a PyObject, - func_name: &str, - py_type_name: &str, - func: F, - vm: &VirtualMachine, - ) -> PyResult - where - T: TryFromBorrowedObject<'a>, - F: Fn(&Self, T) -> bool, - { - single_or_tuple_any( - affix, - &|s: T| Ok(func(self, s)), - &|o| { - format!( - "{} first arg must be {} or a tuple of {}, not {}", - func_name, - py_type_name, - py_type_name, - o.class(), - ) - }, - vm, - ) - } - #[inline] fn py_strip<'a, S, FC, FD>( &'a self, @@ -478,13 +517,24 @@ pub(crate) fn single_or_tuple_any<'a, T, F, M>( where T: TryFromBorrowedObject<'a>, F: Fn(T) -> PyResult, - M: Fn(&PyObject) -> String, + M: Fn(&PyObject, bool) -> Option, { + let convert = |item: &'a PyObject, in_tuple| { + item.try_to_value::(vm).map_err(|exc| { + if exc.fast_isinstance(vm.ctx.exceptions.type_error) + && let Some(message) = message(item, in_tuple) + { + vm.new_type_error(message) + } else { + exc + } + }) + }; // _Py_bytes_tailmatch: a tuple is taken apart before anything is converted, and // each item is converted on its own terms, so a tuple of tuples is not an affix. if let Some(tuple) = obj.downcast_ref::() { for item in tuple { - if (predicate)(item.try_to_value::(vm)?)? { + if (predicate)(convert(item, true)?)? { return Ok(true); } } @@ -493,12 +543,38 @@ where // Only the argument simply being the wrong kind of object is reported as such; // whatever the conversion itself raised belongs to the caller. - let single = obj.try_to_value::(vm).map_err(|exc| { - if exc.fast_isinstance(vm.ctx.exceptions.type_error) { - vm.new_type_error((message)(obj)) - } else { - exc - } - })?; + let single = convert(obj, false)?; (predicate)(single) } + +#[cfg(test)] +mod tests { + use super::{checked_expandtabs_len, checked_replace_len}; + + #[test] + fn replacement_length_checks_signed_and_unsigned_overflow() { + let max = isize::MAX as usize; + assert_eq!(checked_replace_len(4, 0, 1, 5), Some(9)); + assert_eq!(checked_replace_len(6, 1, 0, 4), Some(2)); + assert_eq!(checked_replace_len(max, 0, 1, 0), Some(max)); + assert_eq!(checked_replace_len(max, 0, 1, 1), None); + assert_eq!(checked_replace_len(1, 0, 2, usize::MAX), None); + } + + #[test] + fn expanded_tabs_check_the_complete_output_before_allocating() { + let max = isize::MAX as usize; + assert_eq!( + checked_expandtabs_len(1, "\t".chars().map(u32::from), max), + Some(max) + ); + assert_eq!( + checked_expandtabs_len(3, "\t\n\t".chars().map(u32::from), max), + None + ); + assert_eq!( + checked_expandtabs_len(3, "a\tb".chars().map(u32::from), 0), + Some(2) + ); + } +} diff --git a/crates/vm/src/buffer.rs b/crates/vm/src/buffer.rs index 15c0050cb9c..a3f9342241e 100644 --- a/crates/vm/src/buffer.rs +++ b/crates/vm/src/buffer.rs @@ -1,10 +1,10 @@ use crate::{ - AsObject, Py, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyBaseExceptionRef, PyBytesRef, PyComplex, PyTuple, PyTupleRef, PyType, PyTypeRef}, + Py, PyObject, PyObjectRef, PyResult, VirtualMachine, + builtins::{PyBaseExceptionRef, PyByteArray, PyBytes, PyTuple, PyTupleRef, PyType, PyTypeRef}, common::{lock::PyRwLock, rc::PyRc, static_cell, str::wchar_t}, convert::ToPyObject, exceptions, - function::{ArgBytesLike, ArgIntoBool, ArgIntoComplex, ArgIntoFloat}, + function::{ArgIntoBool, ArgIntoComplex, ArgIntoFloat, ArgMemoryBuffer}, }; use rustpython_common::wtf8::Wtf8Buf; @@ -17,62 +17,9 @@ use num_complex::Complex64; use num_traits::{PrimInt, ToPrimitive}; use std::{collections::HashMap, os::raw}; -type PackFunc = fn(&VirtualMachine, FormatType, PyObjectRef, &mut [u8]) -> Result<(), PackError>; +type PackFunc = fn(&VirtualMachine, FormatType, &PyObject, &mut dyn FnMut(&[u8])) -> PyResult<()>; type UnpackFunc = fn(&VirtualMachine, &[u8]) -> PyObjectRef; -/// Why a value could not be packed. -/// -/// `struct` reports both as `struct.error`, so the kind travels beside the -/// exception rather than in it; `memoryview`, which reports them as TypeError -/// and ValueError, is what needs to tell them apart. -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum PackErrorKind { - /// The value was not the kind of thing the format takes. - Type, - /// The value was the right kind, and the format has no room for it. - Value, - /// The value's own code raised, and that error is the answer as it is. - Raised, -} - -pub struct PackError { - pub kind: PackErrorKind, - pub exception: PyBaseExceptionRef, -} - -impl PackError { - fn new>(kind: PackErrorKind, vm: &VirtualMachine, msg: T) -> Self { - Self { - kind, - exception: new_struct_error(vm, msg), - } - } - - /// An error raised by something other than the packing itself, such as a - /// conversion running the value's own code. - fn from_exception(exception: PyBaseExceptionRef, vm: &VirtualMachine) -> Self { - let kind = if exception.fast_isinstance(vm.ctx.exceptions.type_error) { - PackErrorKind::Type - } else if exception.fast_isinstance(vm.ctx.exceptions.overflow_error) - || exception.fast_isinstance(vm.ctx.exceptions.value_error) - { - PackErrorKind::Value - } else { - PackErrorKind::Raised - }; - Self { kind, exception } - } - - /// An error that is the answer exactly as it was raised. `pack_single()` - /// leaves `'?'` to `PyObject_IsTrue()` this way, with no message of its own. - fn raised(exception: PyBaseExceptionRef) -> Self { - Self { - kind: PackErrorKind::Raised, - exception, - } - } -} - static OVERFLOW_MSG: &str = "total struct size too long"; // not a const to reduce code size #[derive(Clone, Copy, Debug, Eq, PartialEq)] @@ -171,7 +118,7 @@ impl fmt::Debug for FormatType { } impl FormatType { - fn info(self, e: Endianness) -> &'static FormatInfo { + pub(crate) fn info(self, e: Endianness) -> &'static FormatInfo { use mem::{align_of, size_of}; macro_rules! native_info { @@ -306,9 +253,12 @@ impl FormatCode { let mut codes = vec![]; while chars.peek().is_some() { // Skip whitespace before repeat count or format char - while let Some(b' ' | b'\t' | b'\n' | b'\r') = chars.peek() { + while let Some(b' ' | b'\t' | b'\n' | b'\r' | 0x0b | 0x0c) = chars.peek() { chars.next(); } + if chars.peek().is_none() { + break; + } // determine repeat operator: let repeat = match chars.peek() { @@ -331,86 +281,30 @@ impl FormatCode { // determine format char: let c = match chars.next() { Some(c) => c, - None => { - // If we have a repeat count but only whitespace follows, error - if repeat != 1 { - return Err("repeat count given without format specifier".to_owned()); - } - // Otherwise, we're done parsing - break; - } + None => return Err("repeat count given without format specifier".to_owned()), }; - // Check for embedded null character - if c == 0 { - return Err(exceptions::NulError.to_string()); - } - - // PEP3118: Handle extended format specifiers - // T{...} - struct, X{} - function pointer, (...) - array shape, :name: - field name - if c == b'T' || c == b'X' { - // Skip struct/function pointer: consume until matching '}' - if chars.peek() == Some(&b'{') { - chars.next(); // consume '{' - let mut depth = 1; - while depth > 0 { - match chars.next() { - Some(b'{') => depth += 1, - Some(b'}') => depth -= 1, - None => return Err("unmatched '{' in format".to_owned()), - _ => {} - } - } - continue; - } - } - - if c == b'(' { - // Skip array shape: consume until matching ')' - let mut depth = 1; - while depth > 0 { - match chars.next() { - Some(b'(') => depth += 1, - Some(b')') => depth -= 1, - None => return Err("unmatched '(' in format".to_owned()), - _ => {} - } - } - continue; - } - - if c == b':' { - // Skip field name: consume until next ':' - loop { - match chars.next() { - Some(b':') => break, - None => return Err("unmatched ':' in format".to_owned()), - _ => {} - } + // prepare_s: struct accepts primitive fields, not the extended + // exporter grammar (records, subarrays, names or nested byte order). + let c = if c == b'Z' { + match chars.next() { + Some(b'f') => b'F', + Some(b'd') => b'D', + _ => return Err("bad char in struct format".to_owned()), } - continue; - } - - if c == b'{' - || c == b'}' - || c == b'&' - || c == b'<' - || c == b'>' - || c == b'@' - || c == b'=' - || c == b'!' - { - // Skip standalone braces (pointer targets, etc.), pointer prefix, and nested endianness markers - continue; - } - + } else { + c + }; let code = FormatType::try_from(c) .ok() .filter(|c| match c { - FormatType::SSizeT - | FormatType::SizeT - | FormatType::VoidP - | FormatType::Ucs4Char => endianness == Endianness::Native, + FormatType::SSizeT | FormatType::SizeT | FormatType::VoidP => { + endianness == Endianness::Native + } + FormatType::WideChar + | FormatType::Ucs4Char + | FormatType::LongDouble + | FormatType::PyObject => false, _ => true, }) .ok_or_else(|| "bad char in struct format".to_owned())?; @@ -430,7 +324,10 @@ impl FormatCode { info, pre_padding: padding, }; - arg_count += code.arg_count(); + arg_count = arg_count + .checked_add(code.arg_count()) + .filter(|&count| isize::try_from(count).is_ok()) + .ok_or_else(|| OVERFLOW_MSG.to_owned())?; codes.push(code); offset = (info.size as isize) @@ -478,7 +375,7 @@ pub struct FormatSpec { pub arg_count: usize, } -/// Bounded, interpreter-local cache for the module-level `struct` functions. +/// Bounded, interpreter-local cache for `struct` functions and buffer comparison. /// Keys and specifications contain no Python objects or user callbacks. #[derive(Default)] pub struct FormatSpecCache { @@ -509,8 +406,52 @@ impl FormatSpecCache { } } +trait PackBuffer { + fn clear(&mut self, size: usize); + fn write(&mut self, offset: usize, data: &[u8]); + fn needs_source_snapshot(&self) -> bool { + false + } +} + +impl PackBuffer for [u8] { + fn clear(&mut self, size: usize) { + self[..size].fill(0); + } + + fn write(&mut self, offset: usize, data: &[u8]) { + self[offset..offset + data.len()].copy_from_slice(data); + } +} + +struct MemoryPackBuffer<'a> { + buffer: &'a ArgMemoryBuffer, + offset: usize, +} + +impl PackBuffer for MemoryPackBuffer<'_> { + fn needs_source_snapshot(&self) -> bool { + true + } + + fn clear(&mut self, size: usize) { + self.buffer + .with_ref(|data| data[self.offset..self.offset + size].fill(0)); + } + + fn write(&mut self, offset: usize, bytes: &[u8]) { + let start = self.offset + offset; + self.buffer + .with_ref(|data| data[start..start + bytes.len()].copy_from_slice(bytes)); + } +} + impl FormatSpec { pub fn parse(fmt: &[u8], vm: &VirtualMachine) -> PyResult { + // prepare_s rejects embedded NULs before examining any format code. + if fmt.contains(&0) { + return Err(new_struct_error(vm, exceptions::NulError.to_string())); + } let mut chars = fmt.iter().copied().peekable(); // First determine "@", "<", ">","!" or "=" @@ -529,85 +470,77 @@ impl FormatSpec { } pub fn pack(&self, args: Vec, vm: &VirtualMachine) -> PyResult> { - self.try_pack(args, vm).map_err(|e| e.exception) + let mut data = vm.new_zeroed_bytes(self.size)?; + self.pack_into(&mut data, args, vm)?; + Ok(data) } - /// [`Self::pack`], keeping why a value could not be packed. - pub fn try_pack( + pub fn pack_into( &self, + buffer: &mut [u8], args: Vec, vm: &VirtualMachine, - ) -> Result, PackError> { - // Create data vector: - let mut data = vm - .new_zeroed_bytes(self.size) - .map_err(|e| PackError::from_exception(e, vm))?; - - self.try_pack_into(&mut data, args, vm)?; - - Ok(data) + ) -> PyResult<()> { + self.pack_to(buffer, &args, "pack", vm) } - pub fn pack_into( + pub fn pack_into_buffer( &self, - buffer: &mut [u8], + buffer: &ArgMemoryBuffer, + offset: usize, args: Vec, vm: &VirtualMachine, ) -> PyResult<()> { - self.try_pack_into(buffer, args, vm) - .map_err(|e| e.exception) + self.pack_to( + &mut MemoryPackBuffer { buffer, offset }, + &args, + "pack_into", + vm, + ) } - /// [`Self::pack_into`], keeping why a value could not be packed. - pub fn try_pack_into( + fn pack_to( &self, - mut buffer: &mut [u8], - args: Vec, + buffer: &mut (impl PackBuffer + ?Sized), + args: &[PyObjectRef], + operation: &str, vm: &VirtualMachine, - ) -> Result<(), PackError> { + ) -> PyResult<()> { if self.arg_count != args.len() { - return Err(PackError::new( - PackErrorKind::Type, + return Err(new_struct_error( vm, format!( - "pack expected {} items for packing (got {})", - self.codes.len(), + "{operation} expected {} items for packing (got {})", + self.arg_count, args.len() ), )); } - let mut args = args.into_iter(); + buffer.clear(self.size); + let mut args = args.iter(); + let mut offset = 0; // Loop over all opcodes: for code in &self.codes { - buffer = &mut buffer[code.pre_padding..]; + offset += code.pre_padding; debug!("code: {code:?}"); match code.code { - FormatType::Str => { - let (buf, rest) = buffer.split_at_mut(code.repeat); - pack_string(vm, args.next().unwrap(), buf) - .map_err(|e| PackError::from_exception(e, vm))?; - buffer = rest; - } - FormatType::Pascal => { - let (buf, rest) = buffer.split_at_mut(code.repeat); - pack_pascal(vm, args.next().unwrap(), buf) - .map_err(|e| PackError::from_exception(e, vm))?; - buffer = rest; + FormatType::Str | FormatType::Pascal => { + pack_string(vm, args.next().unwrap(), code, buffer, offset)?; + offset += code.repeat; } FormatType::Pad => { - let (pad_buf, rest) = buffer.split_at_mut(code.repeat); - for el in pad_buf { - *el = 0 - } - buffer = rest; + offset += code.repeat; } _ => { let pack = code.info.pack.unwrap(); for arg in args.by_ref().take(code.repeat) { - let (item_buf, rest) = buffer.split_at_mut(code.info.size); - pack(vm, code.code, arg, item_buf)?; - buffer = rest; + let mut cursor = offset; + pack(vm, code.code, arg, &mut |bytes| { + buffer.write(cursor, bytes); + cursor += bytes.len(); + })?; + offset += code.info.size; } } } @@ -673,23 +606,23 @@ trait Packable { fn pack( vm: &VirtualMachine, code: FormatType, - arg: PyObjectRef, - data: &mut [u8], - ) -> Result<(), PackError>; + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), + ) -> PyResult<()>; fn unpack(vm: &VirtualMachine, data: &[u8]) -> PyObjectRef; } trait PackInt: PrimInt { - fn pack_int(self, data: &mut [u8]); + fn pack_int(self, write: &mut dyn FnMut(&[u8])); fn unpack_int(data: &[u8]) -> Self; } macro_rules! make_pack_prim_int { ($T:ty) => { impl PackInt for $T { - fn pack_int(self, data: &mut [u8]) { + fn pack_int(self, write: &mut dyn FnMut(&[u8])) { let i = E::convert(self); - data.copy_from_slice(&i.to_ne_bytes()); + write(&i.to_ne_bytes()); } #[inline] fn unpack_int(data: &[u8]) -> Self { @@ -703,11 +636,11 @@ macro_rules! make_pack_prim_int { fn pack( vm: &VirtualMachine, code: FormatType, - arg: PyObjectRef, - data: &mut [u8], - ) -> Result<(), PackError> { - let i: $T = get_int_or_index(vm, code, &arg)?; - i.pack_int::(data); + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), + ) -> PyResult<()> { + let i: $T = get_int_or_index(vm, code, arg)?; + i.pack_int::(write); Ok(()) } @@ -719,23 +652,15 @@ macro_rules! make_pack_prim_int { }; } -fn get_int_or_index( - vm: &VirtualMachine, - code: FormatType, - arg: &PyObject, -) -> Result +fn get_int_or_index(vm: &VirtualMachine, code: FormatType, arg: &PyObject) -> PyResult where T: PrimInt + fmt::Display + for<'a> TryFrom<&'a BigInt>, { let index = match arg.try_index_opt(vm) { None => { - return Err(PackError::new( - PackErrorKind::Type, - vm, - "required argument is not an integer", - )); + return Err(new_struct_error(vm, "required argument is not an integer")); } - Some(Err(e)) => return Err(PackError::from_exception(e, vm)), + Some(Err(e)) => return Err(e), Some(Ok(index)) => index, }; index.try_to_primitive(vm).map_err(|_| { @@ -751,7 +676,7 @@ where T::max_value() ) }; - PackError::new(PackErrorKind::Value, vm, msg) + new_struct_error(vm, msg) }) } @@ -772,24 +697,22 @@ macro_rules! make_pack_float { fn pack( vm: &VirtualMachine, _code: FormatType, - arg: PyObjectRef, - data: &mut [u8], - ) -> Result<(), PackError> { - let f_64 = ArgIntoFloat::try_from_object(vm, arg) - .map_err(|e| PackError::from_exception(e, vm))? + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), + ) -> PyResult<()> { + let f_64 = arg + .try_to_value::(vm) + .map_err(|_| new_struct_error(vm, "required argument is not a float"))? .into_float(); let f = f_64 as $T; if f.is_infinite() != f_64.is_infinite() { - return Err(PackError { - kind: PackErrorKind::Value, - exception: vm.new_overflow_error(concat!( - "float too large to pack with ", - $fmt, - " format" - )), - }); + return Err(vm.new_overflow_error(concat!( + "float too large to pack with ", + $fmt, + " format" + ))); } - f.to_bits().pack_int::(data); + f.to_bits().pack_int::(write); Ok(()) } @@ -816,39 +739,24 @@ macro_rules! make_pack_complex { fn pack( vm: &VirtualMachine, _code: FormatType, - arg: PyObjectRef, - data: &mut [u8], - ) -> Result<(), PackError> { - let c = if let Some(value) = arg.downcast_ref::() { - value.as_complex() - } else { - ArgIntoComplex::try_from_object(vm, arg) - .map_err(|_| { - PackError::new( - PackErrorKind::Type, - vm, - "required argument is not a complex", - ) - })? - .into_complex() - }; - for (component, bytes) in [c.re, c.im] - .into_iter() - .zip(data.chunks_exact_mut(size_of::<$Elem>())) - { + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), + ) -> PyResult<()> { + let c = arg + .try_to_value::(vm) + .map_err(|_| new_struct_error(vm, "required argument is not a complex"))? + .into_complex(); + for component in [c.re, c.im] { let narrowed = component as $Elem; // CPython uses native casts for matching-endian complex formats. if E::convert(1u16) != 1 && narrowed.is_infinite() != component.is_infinite() { - return Err(PackError { - kind: PackErrorKind::Value, - exception: vm.new_overflow_error(concat!( - "float too large to pack with ", - $fmt, - " format" - )), - }); + return Err(vm.new_overflow_error(concat!( + "float too large to pack with ", + $fmt, + " format" + ))); } - narrowed.to_bits().pack_int::(bytes); + narrowed.to_bits().pack_int::(write); } Ok(()) } @@ -866,31 +774,94 @@ macro_rules! make_pack_complex { make_pack_complex!(PackFloatComplex, f32, u32, "f"); make_pack_complex!(PackDoubleComplex, f64, u64, "d"); +/// PyFloat_Pack2: round the full binary64 significand to nearest-even and +/// preserve the sign, signaling bit and representable payload of NaNs. +pub(crate) fn pack_float16(value: f64) -> Option { + let bits = value.to_bits(); + let sign = ((bits >> 48) & 0x8000) as u16; + let exponent = ((bits >> 52) & 0x7ff) as i32; + let fraction = bits & 0x000f_ffff_ffff_ffff; + if exponent == 0x7ff { + let mut payload = (fraction >> 42) as u16; + if fraction != 0 && payload == 0 { + payload = 0x0200; + } + return Some(sign | 0x7c00 | payload); + } + let exponent = exponent - 1023; + if exponent > 15 { + return None; + } + if exponent < -25 { + return Some(sign); + } + let significand = (1_u64 << 52) | fraction; + let shift = if exponent < -14 { + (28 - exponent) as u32 + } else { + 42 + }; + let truncated = significand >> shift; + let remainder = significand & ((1_u64 << shift) - 1); + let halfway = 1_u64 << (shift - 1); + let rounded = + truncated + u64::from(remainder > halfway || (remainder == halfway && truncated & 1 != 0)); + let exponent_bits = if exponent < -14 { + 0 + } else { + ((exponent + 14) as u16) << 10 + }; + let magnitude = exponent_bits + rounded as u16; + (magnitude < 0x7c00).then_some(sign | magnitude) +} + +/// PyFloat_Unpack2. A hardware half conversion would quiet signaling NaNs. +fn unpack_float16(bits: u16) -> f64 { + if bits & 0x7fff > 0x7c00 { + f64::from_bits( + (u64::from(bits & 0x8000) << 48) + | 0x7ff0_0000_0000_0000 + | (u64::from(bits & 0x03ff) << 42), + ) + } else { + f16::from_bits(bits).to_f64() + } +} + +/// PyFloat_Unpack4, as used by memoryview's complex scalar conversion. +pub(crate) fn unpack_float32(bits: u32) -> f64 { + if bits & 0x7fff_ffff > 0x7f80_0000 { + f64::from_bits( + (u64::from(bits & 0x8000_0000) << 32) + | 0x7ff0_0000_0000_0000 + | (u64::from(bits & 0x007f_ffff) << 29), + ) + } else { + f32::from_bits(bits) as f64 + } +} + impl Packable for f16 { fn pack( vm: &VirtualMachine, _code: FormatType, - arg: PyObjectRef, - data: &mut [u8], - ) -> Result<(), PackError> { - let f_64 = ArgIntoFloat::try_from_object(vm, arg) - .map_err(|e| PackError::from_exception(e, vm))? + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), + ) -> PyResult<()> { + let f_64 = arg + .try_to_value::(vm) + .map_err(|_| new_struct_error(vm, "required argument is not a float"))? .into_float(); - // "from_f64 should be preferred in any non-`const` context" except it gives the wrong result :/ - let f_16 = Self::from_f64_const(f_64); - if f_16.is_infinite() != f_64.is_infinite() { - return Err(PackError { - kind: PackErrorKind::Value, - exception: vm.new_overflow_error("float too large to pack with e format"), - }); - } - f_16.to_bits().pack_int::(data); + let bits = pack_float16(f_64) + .ok_or_else(|| vm.new_overflow_error("float too large to pack with e format"))?; + bits.pack_int::(write); + Ok(()) } fn unpack(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { let i = PackInt::unpack_int::(rdr); - Self::from_bits(i).to_f64().to_pyobject(vm) + unpack_float16(i).to_pyobject(vm) } } @@ -898,10 +869,10 @@ impl Packable for *mut raw::c_void { fn pack( vm: &VirtualMachine, code: FormatType, - arg: PyObjectRef, - data: &mut [u8], - ) -> Result<(), PackError> { - usize::pack::(vm, code, arg, data) + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), + ) -> PyResult<()> { + usize::pack::(vm, code, arg, write) } fn unpack(vm: &VirtualMachine, rdr: &[u8]) -> PyObjectRef { @@ -913,13 +884,11 @@ impl Packable for bool { fn pack( vm: &VirtualMachine, _code: FormatType, - arg: PyObjectRef, - data: &mut [u8], - ) -> Result<(), PackError> { - let v = ArgIntoBool::try_from_object(vm, arg) - .map_err(PackError::raised)? - .into_bool() as u8; - v.pack_int::(data); + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), + ) -> PyResult<()> { + let v = arg.try_to_value::(vm)?.into_bool() as u8; + v.pack_int::(write); Ok(()) } @@ -932,48 +901,67 @@ impl Packable for bool { fn pack_char( vm: &VirtualMachine, _code: FormatType, - arg: PyObjectRef, - data: &mut [u8], -) -> Result<(), PackError> { - let v = PyBytesRef::try_from_object(vm, arg).map_err(|e| PackError::from_exception(e, vm))?; - let ch = *v.as_bytes().iter().exactly_one().map_err(|_| { - PackError::new( - PackErrorKind::Value, - vm, - "char format requires a bytes object of length 1", - ) - })?; - data[0] = ch; - Ok(()) -} - -fn pack_string(vm: &VirtualMachine, arg: PyObjectRef, buf: &mut [u8]) -> PyResult<()> { - let b = ArgBytesLike::try_from_object(vm, arg)?; - b.with_ref(|data| write_string(buf, data)); + arg: &PyObject, + write: &mut dyn FnMut(&[u8]), +) -> PyResult<()> { + let v = arg.try_to_ref::(vm)?; + let ch = *v + .as_bytes() + .iter() + .exactly_one() + .map_err(|_| new_struct_error(vm, "char format requires a bytes object of length 1"))?; + write(&[ch]); Ok(()) } -fn pack_pascal(vm: &VirtualMachine, arg: PyObjectRef, buf: &mut [u8]) -> PyResult<()> { - if buf.is_empty() { - return Ok(()); +fn pack_string( + vm: &VirtualMachine, + arg: &PyObject, + code: &FormatCode, + buffer: &mut (impl PackBuffer + ?Sized), + offset: usize, +) -> PyResult<()> { + let pascal = code.code == FormatType::Pascal; + let capacity = if pascal { + code.repeat.saturating_sub(1) + } else { + code.repeat + }; + let needs_snapshot = buffer.needs_source_snapshot(); + let mut write = |data: &[u8]| { + let len = data.len().min(capacity); + let start = offset + usize::from(pascal); + if len != 0 { + buffer.write(start, &data[..len]); + } + if pascal && code.repeat != 0 { + buffer.write(offset, &[len.min(255) as u8]); + } + }; + if let Some(bytes) = arg.downcast_ref::() { + write(bytes.as_bytes()); + } else if let Some(bytes) = arg.downcast_ref::() { + if needs_snapshot { + let data = { + let data = bytes.borrow_buf(); + data[..data.len().min(capacity)].to_vec() + }; + write(&data); + } else { + write(&bytes.borrow_buf()); + } + } else { + return Err(new_struct_error( + vm, + format!( + "argument for '{}' must be a bytes object", + code.code as u8 as char + ), + )); } - let b = ArgBytesLike::try_from_object(vm, arg)?; - b.with_ref(|data| { - let string_length = core::cmp::min(core::cmp::min(data.len(), 255), buf.len() - 1); - buf[0] = string_length as u8; - write_string(&mut buf[1..], data); - }); Ok(()) } -fn write_string(buf: &mut [u8], data: &[u8]) { - let len_from_data = core::cmp::min(data.len(), buf.len()); - buf[..len_from_data].copy_from_slice(&data[..len_from_data]); - for byte in &mut buf[len_from_data..] { - *byte = 0 - } -} - fn unpack_char(vm: &VirtualMachine, data: &[u8]) -> PyObjectRef { vm.ctx.new_bytes(vec![data[0]]).into() } @@ -982,7 +970,7 @@ fn unpack_pascal(vm: &VirtualMachine, data: &[u8]) -> PyObjectRef { let (&len, data) = match data.split_first() { Some(x) => x, None => { - // cpython throws an internal SystemError here + // Zero-width Pascal strings unpack to empty bytes (CPython 3.15). return vm.ctx.new_bytes(vec![]).into(); } }; @@ -1009,6 +997,53 @@ mod tests { use super::*; use crate::Interpreter; + #[test] + fn struct_parser_rejects_exporter_extensions_and_dangling_counts() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + for format in ["B\u{b}", "B\u{c}", " \t\n\r\u{b}\u{c}B"] { + assert_eq!(FormatSpec::parse(format.as_bytes(), vm).unwrap().size(), 1); + } + for format in [ + "1", "B1", "0", "1 ", "B@B", " { #[pygetset] fn ag_await(&self, _vm: &VirtualMachine) -> Option { - self.inner.frame_opt().and_then(|f| f.yield_from_target()) + self.inner.yield_from_target() } #[pygetset] fn ag_frame(&self, _vm: &VirtualMachine) -> Option { @@ -162,6 +165,15 @@ impl Py { self.inner.code() } #[pygetset] + fn ag_state(&self) -> &'static str { + self.inner.state_name([ + "AGEN_CREATED", + "AGEN_RUNNING", + "AGEN_SUSPENDED", + "AGEN_CLOSED", + ]) + } + #[pygetset] fn ag_suspended(&self, _vm: &VirtualMachine) -> bool { self.inner.suspended() } @@ -340,8 +352,11 @@ impl PyAsyncGenASend { #[pyclass(with(IterNext, Iterable, Destructor))] impl Py { - #[pymethod(name = "__await__")] - const fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { + #[pymethod] + const fn __await__( + zelf: PyRef, + _vm: &VirtualMachine, + ) -> PyRef { zelf } @@ -512,8 +527,8 @@ impl PyAsyncGenAThrow { #[pyclass(with(IterNext, Iterable, Destructor))] impl Py { - #[pymethod(name = "__await__")] - const fn r#await( + #[pymethod] + const fn __await__( zelf: PyRef, _vm: &VirtualMachine, ) -> PyRef { @@ -720,68 +735,23 @@ impl PyAnextAwaitable { /// Get the awaitable iterator from wrapped object. // = anextawaitable_getiter. fn get_awaitable_iter(&self, vm: &VirtualMachine) -> PyResult { - use crate::builtins::PyCoroutine; use crate::protocol::PyIter; - let wrapped = &self.wrapped; - - // If wrapped is already an async_generator_asend, it's an iterator - if wrapped.class().is(vm.ctx.types.async_generator_asend) - || wrapped.class().is(vm.ctx.types.async_generator_athrow) - { - return Ok(wrapped.clone()); - } - - // _PyCoro_GetAwaitableIter equivalent - let awaitable = if wrapped.class().is(vm.ctx.types.coroutine_type) { - // Coroutine - get __await__ later - wrapped.clone() - } else { - // Check for generator with CO_ITERABLE_COROUTINE flag - if let Some(generator) = wrapped.downcast_ref::() - && generator - .as_coro() - .code() - .flags - .contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE) - { - // Return the generator itself as the iterator - return Ok(wrapped.clone()); - } - // Try to get __await__ method - if let Some(await_method) = vm.get_method(wrapped.clone(), identifier!(vm, __await__)) { - await_method?.call((), vm)? - } else { - return Err(vm.new_type_error(format!( - "'{}' object can't be awaited", - wrapped.class().name() - ))); - } - }; + let awaitable = crate::coroutine::get_awaitable_iter(self.wrapped.clone(), vm)?; // If awaitable is a coroutine, get its __await__ if awaitable.class().is(vm.ctx.types.coroutine_type) { let coro_await = vm.call_method(&awaitable, "__await__", ())?; // Check that __await__ returned an iterator if !PyIter::check(&coro_await) { - return Err(vm.new_type_error("__await__ returned a non-iterable")); + return Err(vm.new_type_error(wtf8_concat!( + "anext_awaitable.__await__() must return an iterable, not ", + coro_await.class().fully_qualified_name(vm)? + ))); } return Ok(coro_await); } - // Check the result is an iterator, not a coroutine - if awaitable.downcast_ref::().is_some() { - return Err(vm.new_type_error("__await__() returned a coroutine")); - } - - // Check that the result is an iterator - if !PyIter::check(&awaitable) { - return Err(vm.new_type_error(format!( - "__await__() returned non-iterator of type '{}'", - awaitable.class().name() - ))); - } - Ok(awaitable) } @@ -799,8 +769,8 @@ impl PyAnextAwaitable { #[pyclass(with(IterNext, Iterable))] impl Py { - #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { + #[pymethod] + fn __await__(zelf: PyRef, _vm: &VirtualMachine) -> PyRef { zelf } diff --git a/crates/vm/src/builtins/bool.rs b/crates/vm/src/builtins/bool.rs index a8c2c019582..88677ae4ba4 100644 --- a/crates/vm/src/builtins/bool.rs +++ b/crates/vm/src/builtins/bool.rs @@ -1,9 +1,8 @@ use super::{PyInt, PyStrRef, PyType, PyTypeRef, PyUtf8StrRef}; -use crate::common::format::FormatSpec; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, class::{PyClassDef, PyClassImpl}, - convert::{IntoPyException, ToPyObject, ToPyResult}, + convert::{ToPyObject, ToPyResult}, function::{FuncArgs, OptionalArg}, protocol::PyNumberMethods, types::{AsNumber, Constructor, Representable}, @@ -124,9 +123,11 @@ impl Py { vm: &VirtualMachine, ) -> PyResult { let new_bool = zelf.try_to_bool(vm)?; - FormatSpec::parse(format_spec.as_str()) - .and_then(|format_spec| format_spec.format_bool(new_bool)) - .map_err(|err| err.into_pyexception(vm)) + crate::format::parse_format_spec(zelf.as_object(), format_spec.as_str(), vm)? + .format_bool(new_bool) + .map_err(|err| { + crate::format::format_spec_error(err, zelf.as_object(), format_spec.as_str(), vm) + }) } } @@ -221,7 +222,7 @@ pub(crate) fn init(context: &'static Context) { .types .bool_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_bool)); } diff --git a/crates/vm/src/builtins/builtin_func.rs b/crates/vm/src/builtins/builtin_func.rs index 79e2c1ca721..1f9019c95e3 100644 --- a/crates/vm/src/builtins/builtin_func.rs +++ b/crates/vm/src/builtins/builtin_func.rs @@ -16,8 +16,6 @@ pub struct PyNativeFunction { #[pytraverse(skip)] pub(crate) value: &'static PyMethodDef, pub(crate) zelf: Option, - // Module that owns this function. Not passed as a call argument. - pub(crate) module_object: Option, #[pymember(name = "__module__", writable)] pub(crate) module: crate::object::PyAtomicRef>, /// Prevent HeapMethodDef from being freed while this function references it @@ -57,11 +55,6 @@ impl PyNativeFunction { self } - pub fn with_module_object(mut self, module: PyObjectRef) -> Self { - self.module_object = Some(module); - self - } - pub fn into_ref(self, ctx: &Context) -> PyRef { PyRef::new_ref( self, @@ -75,10 +68,10 @@ impl PyNativeFunction { if self.value.flags.contains(PyMethodFlags::STATIC) { return None; } - self.zelf.as_deref().or(self.module_object.as_deref()) + self.zelf.as_deref() } - pub const fn as_func(&self) -> &'static dyn PyNativeFn { + pub const fn as_func(&self) -> &dyn PyNativeFn { self.value.func } } @@ -86,17 +79,16 @@ impl PyNativeFunction { impl Callable for PyNativeFunction { type Args = FuncArgs; #[inline] - fn call(zelf: &Py, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let mut callee = Callee::named(zelf.value.name); - if let Some(z) = &zelf.zelf { - // STATIC methods store the class in zelf for qualname/repr purposes, - // but should not prepend it to args (the Rust function doesn't expect it). - if !zelf.value.flags.contains(PyMethodFlags::STATIC) { - args.prepend_arg(z.clone()); - callee = callee.with_instance_arg(true); - } + fn call(zelf: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + if !args.kwargs.is_empty() && !zelf.value.flags.contains(PyMethodFlags::KEYWORDS) { + return Err(native_no_keywords_error(zelf, vm)?); } - (zelf.value.func)(vm, args, callee) + (zelf.value.func)( + vm, + zelf.zelf.as_deref(), + args, + Callee::named(zelf.value.name), + ) } } @@ -110,17 +102,11 @@ impl Comparable for PyNativeFunction { ) -> PyResult { op.eq_only(|| { if let Some(other) = other.downcast_ref::() { - let eq = match (zelf.zelf.as_ref(), other.zelf.as_ref()) { + let eq = match (zelf.zelf.as_deref(), other.zelf.as_deref()) { (Some(z), Some(o)) => z.is(o), (None, None) => true, _ => false, }; - let eq = eq - && match (zelf.module_object.as_ref(), other.module_object.as_ref()) { - (Some(z), Some(o)) => z.is(o), - (None, None) => true, - _ => false, - }; let eq = eq && core::ptr::eq(zelf.value, other.value); Ok(eq.into()) } else { @@ -136,8 +122,8 @@ impl Representable for PyNativeFunction { fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { if let Some(bound) = zelf .zelf - .as_ref() - .filter(|b| !b.class().is(vm.ctx.types.module_type)) + .as_deref() + .filter(|b| !b.class().is_subtype(vm.ctx.types.module_type)) { Ok(format!( "", @@ -165,8 +151,8 @@ impl PyNativeFunction { #[pygetset] fn __qualname__(zelf: NativeFunctionOrMethod, vm: &VirtualMachine) -> PyResult { let zelf = zelf.0; - let qualname = if let Some(bound) = &zelf.zelf { - if bound.class().is(vm.ctx.types.module_type) { + let qualname = if let Some(bound) = zelf.zelf.as_deref() { + if bound.class().is_subtype(vm.ctx.types.module_type) { return Ok(vm.ctx.intern_str(zelf.value.name).to_owned()); } let prefix = if bound.class().is(vm.ctx.types.type_type) { @@ -192,13 +178,9 @@ impl PyNativeFunction { // meth_get__self__ in CPython #[pygetset] fn __self__(zelf: NativeFunctionOrMethod, vm: &VirtualMachine) -> PyObjectRef { - if let Some(bound) = &zelf.0.zelf { - return bound.clone(); - } - if let Some(module) = &zelf.0.module_object { - return module.clone(); - } - vm.ctx.none() + zelf.0 + .get_self() + .map_or_else(|| vm.ctx.none(), ToOwned::to_owned) } // meth_reduce: the name when unbound or bound to a module, otherwise @@ -209,12 +191,12 @@ impl PyNativeFunction { // PyModule_Check: the type or a subtype, same as meth_reduce. if let Some(bound) = zelf .zelf - .as_ref() + .as_deref() .filter(|bound| !bound.class().is_subtype(vm.ctx.types.module_type)) { - let getattr = vm.builtins.get_attr("getattr", vm)?; + let getattr = vm.eval_get_builtin(vm.ctx.intern_str("getattr"))?; Ok(vm - .new_tuple((getattr, (bound.clone(), zelf.value.name))) + .new_tuple((getattr, (bound.to_owned(), zelf.value.name))) .into()) } else { Ok(vm.ctx.new_str(zelf.value.name).into()) @@ -233,16 +215,22 @@ impl PyNativeFunction { } } -// PyCMethodObject in CPython -#[pyclass(name = "builtin_function_or_method", module = false, base = PyNativeFunction, ctx = "builtin_function_or_method_type")] +// Bound METH_METHOD object. The payload starts with PyNativeFunction so it can +// be read as a builtin function. The Python type is `builtin_method`. +#[repr(C)] +#[pyclass( + name = "builtin_method", + module = false, + base = PyNativeFunction, + ctx = "builtin_method_type", + traverse +)] pub struct PyNativeMethod { pub(crate) func: PyNativeFunction, - pub(crate) class: &'static Py, // TODO: the actual life is &'self + #[pytraverse(skip)] + pub(crate) class: &'static Py, } -// All Python-visible behavior (getters, slots) is registered by PyNativeFunction::extend_class. -// PyNativeMethod only extends the Rust-side struct with the defining class reference. -// The func field at offset 0 (#[repr(C)]) allows NativeFunctionOrMethod to read it safely. #[pyclass(flags(HAS_WEAKREF, DISALLOW_INSTANTIATION))] impl PyNativeMethod {} @@ -258,7 +246,7 @@ impl fmt::Debug for PyNativeMethod { } /// Vectorcall for builtin functions (PEP 590). -/// Avoids `prepend_arg` O(n) shift by building args with self at front. +/// The receiver stays borrowed and outside the Python argument vector. fn vectorcall_native_function( zelf_obj: &PyObject, args: Vec, @@ -268,24 +256,43 @@ fn vectorcall_native_function( ) -> PyResult { let zelf: &Py = zelf_obj.downcast_ref().unwrap(); - // Build FuncArgs with self already at position 0 (no insert(0) needed) - let needs_self = zelf - .zelf - .as_ref() - .is_some_and(|_| !zelf.value.flags.contains(PyMethodFlags::STATIC)); - - let func_args = if needs_self { - let self_obj = zelf.zelf.as_ref().unwrap().clone(); - let mut all_args = Vec::with_capacity(args.len() + 1); - all_args.push(self_obj); - all_args.extend(args); - FuncArgs::from_vectorcall_owned(all_args, nargs + 1, kwnames) + if kwnames.is_some_and(|names| !names.is_empty()) + && !zelf.value.flags.contains(PyMethodFlags::KEYWORDS) + { + return Err(native_no_keywords_error(zelf, vm)?); + } + + let func_args = FuncArgs::from_vectorcall_owned(args, nargs, kwnames); + (zelf.value.func)( + vm, + zelf.zelf.as_deref(), + func_args, + Callee::named(zelf.value.name), + ) +} + +#[cold] +fn native_no_keywords_error( + zelf: &Py, + vm: &VirtualMachine, +) -> PyResult { + if zelf.value.flags.contains(PyMethodFlags::VARARGS) { + return Ok(vm.new_type_error(format!("{}() takes no keyword arguments", zelf.value.name))); + } + let qualname = PyNativeFunction::__qualname__(NativeFunctionOrMethod(zelf.to_owned()), vm)?; + let module = zelf + .module + .load_owned() + .filter(|module| !vm.is_none(module)); + let module = module.map(|module| module.str(vm)).transpose()?; + let name = if let Some(module) = module + && module.to_string() != "builtins" + { + format!("{module}.{qualname}") } else { - FuncArgs::from_vectorcall_owned(args, nargs, kwnames) + qualname.to_string() }; - - let callee = Callee::named(zelf.value.name).with_instance_arg(needs_self); - (zelf.value.func)(vm, func_args, callee) + Ok(vm.new_type_error(format!("{name}() takes no keyword arguments"))) } pub(crate) fn init(context: &'static Context) { @@ -296,6 +303,13 @@ pub(crate) fn init(context: &'static Context) { .slots .vectorcall .store(Some(vectorcall_native_function)); + context + .types + .builtin_function_or_method_type + .slots + .flags + .insert(crate::types::PyTypeFlags::HAVE_VECTORCALL); + PyNativeMethod::extend_class(context, context.types.builtin_method_type); } /// Wrapper that provides access to the common PyNativeFunction data @@ -306,12 +320,139 @@ impl TryFromObject for NativeFunctionOrMethod { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { let class = vm.ctx.types.builtin_function_or_method_type; if obj.fast_isinstance(class) { - // Both PyNativeFunction and PyNativeMethod share the same type now. - // PyNativeMethod has `func: PyNativeFunction` as its first field, - // so we can safely treat the data pointer as PyNativeFunction for reading. + // `builtin_method` is a subclass; the payload starts with PyNativeFunction. Ok(Self(unsafe { obj.downcast_unchecked() })) } else { Err(vm.new_downcast_type_error(class, &obj)) } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + Interpreter, PyObjectRef, + function::{PyMethodDef, PyMethodFlags}, + }; + + #[pymodule(name = "receiver_test")] + mod receiver_test { + use crate::{Py, PyRef, VirtualMachine, builtins::PyModule}; + + #[pyfunction] + fn borrowed(module: &Py) -> PyRef { + module.to_owned() + } + + #[pyfunction] + fn borrowed_vm(module: &Py, _vm: &VirtualMachine) -> PyRef { + module.to_owned() + } + + #[pyfunction] + fn ordinary(value: u32) -> u32 { + value + } + + #[pyfunction] + fn target(_module: &Py, target: PyRef) -> PyRef { + target + } + } + + #[test] + fn module_receiver_is_injected_outside_python_arguments() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let definition = receiver_test::module_def(&vm.ctx); + let module = definition.create_module(vm).unwrap(); + let other_module = definition.create_module(vm).unwrap(); + for name in ["borrowed", "borrowed_vm"] { + let function = module + .get_attr(name, vm) + .unwrap() + .downcast::() + .unwrap(); + assert!(function.get_self().unwrap().is(module.as_object())); + let result = PyNativeFunction::call(&function, FuncArgs::default(), vm).unwrap(); + assert!(result.is(module.as_object())); + let result = + vectorcall_native_function(function.as_object(), vec![], 0, None, vm).unwrap(); + assert!(result.is(module.as_object())); + let signature = function + .as_object() + .get_attr("__text_signature__", vm) + .unwrap(); + assert_eq!(signature.str(vm).unwrap().to_string(), "($module, /)"); + } + let ordinary = module.get_attr("ordinary", vm).unwrap(); + let value: PyObjectRef = vm.ctx.new_int(42).into(); + for vectorcall in [false, true] { + let function = ordinary.downcast_ref::().unwrap(); + let result = if vectorcall { + vectorcall_native_function( + ordinary.as_object(), + vec![value.clone()], + 1, + None, + vm, + ) + } else { + PyNativeFunction::call(function, FuncArgs::from(vec![value.clone()]), vm) + } + .unwrap(); + assert_eq!(result.try_into_value::(vm).unwrap(), 42); + } + let target = module.get_attr("target", vm).unwrap(); + assert!( + target + .call((other_module.clone(),), vm) + .unwrap() + .is(other_module.as_object()) + ); + assert!(target.call((), vm).is_err()); + }); + } + + #[test] + fn builtin_method_is_subclass_of_builtin_function() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let function_type = vm.ctx.types.builtin_function_or_method_type; + let method_type = vm.ctx.types.builtin_method_type; + assert!(!function_type.is(method_type)); + assert_eq!(&*function_type.name(), "builtin_function_or_method"); + assert_eq!(&*method_type.name(), "builtin_method"); + assert!(method_type.fast_issubclass(function_type)); + }); + } + + #[test] + fn bound_instance_method_uses_function_type() { + fn identity(value: PyObjectRef) -> PyObjectRef { + value + } + const DEF: PyMethodDef = PyMethodDef::new_method_const( + "identity", + identity, + PyMethodFlags::METHOD, + crate::function::ItemDoc::NONE, + ); + + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let bound = DEF.build_bound_function(&vm.ctx, vm.ctx.none()); + assert!( + bound + .class() + .is(vm.ctx.types.builtin_function_or_method_type) + ); + assert!(!bound.as_object().downcastable::()); + assert!(bound.as_object().call((), vm).unwrap().is(&vm.ctx.none())); + + let method = DEF.build_bound_method(&vm.ctx, vm.ctx.none(), vm.ctx.types.object_type); + assert!(method.class().is(vm.ctx.types.builtin_method_type)); + assert!(method.as_object().downcastable::()); + assert!(method.as_object().downcastable::()); + assert!(method.as_object().call((), vm).unwrap().is(&vm.ctx.none())); + }); + } +} diff --git a/crates/vm/src/builtins/bytearray.rs b/crates/vm/src/builtins/bytearray.rs index 19e149d9df0..2d3f45ae27a 100644 --- a/crates/vm/src/builtins/bytearray.rs +++ b/crates/vm/src/builtins/bytearray.rs @@ -1,34 +1,39 @@ //! Implementation of the python bytearray object. +use super::native_iter::{NativeIterKind, NativeSequenceIter}; use super::{ - PositionIterInternal, PyBytes, PyDictRef, PyGenericAlias, PyStrRef, PyTuple, PyTupleRef, - PyType, PyTypeRef, iter::builtins_iter, locked_next, + PyBytes, PyGenericAlias, PyInt, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, + iter::builtins_iter, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, - anystr::{self, AnyStr}, + anystr::{self, AnyStr, StringRange}, atomic_func, byte::{bytearray_extend_from_object, bytearray_from_object, value_from_object}, bytes_inner::{ ByteInnerFindOptions, ByteInnerHexOptions, ByteInnerNewOptions, ByteInnerPaddingOptions, ByteInnerReplaceOptions, ByteInnerSplitOptions, ByteInnerStripOptions, ByteInnerSub, - ByteInnerTranslateOptions, BytesJoin, DecodeArgs, PyBytesInner, bytes_decode, + ByteInnerTranslateOptions, ByteOr, BytesJoin, PyBytesInner, bytes_decode, }, class::PyClassImpl, - common::{ - atomic::{AtomicUsize, Ordering}, - lock::{ - PyDetachingRwLock, PyDetachingRwLockReadGuard, PyDetachingRwLockWriteGuard, - PyMappedDetachingRwLockReadGuard, PyMappedDetachingRwLockWriteGuard, PyMutex, - }, + codecs::TextCodecArgs, + common::lock::{ + PyDetachingRwLock, PyDetachingRwLockReadGuard, PyDetachingRwLockWriteGuard, + PyMappedDetachingRwLockReadGuard, PyMappedDetachingRwLockWriteGuard, PyMutex, }, convert::{ToPyObject, ToPyResult}, - function::{ArgBytesLike, PyComparisonValue, PySsize}, + function::{ + ArgBytesLike, ArgIndex, ArgumentError, FromArgs, FuncArgs, OptionalArg, Param, + PyComparisonValue, PySsize, + }, protocol::{ BufferDescriptor, BufferFlags, BufferMethods, BufferResizeGuard, PyBuffer, PyIterReturn, - PyMappingMethods, PyNumberMethods, PySequenceMethods, + PyMappingMethods, PyNumber, PyNumberMethods, PySequenceMethods, + }, + sliceable::{ + NameBytearray, SaturatedSlice, SaturatedSliceIter, SequenceIndex, SequenceIndexOp, + SliceableSequenceMutOp, SliceableSequenceOp, }, - sliceable::{SequenceIndex, SliceableSequenceMutOp, SliceableSequenceOp}, types::{ AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, DefaultConstructor, Initializer, IterNext, Iterable, PyComparisonOp, Representable, @@ -37,12 +42,71 @@ use crate::{ }; use bstr::ByteSlice; use core::mem::size_of; +use num_traits::ToPrimitive; #[pyclass(module = false, name = "bytearray", unhashable = true)] #[derive(Debug, Default)] pub struct PyByteArray { inner: PyDetachingRwLock, - exports: AtomicUsize, + exports: PyMutex, +} + +// While count is nonzero, len is the stable logical length of the payload. +// Publish both together; the length is meaningless between export epochs. +#[derive(Debug, Default)] +struct ExportState { + count: usize, + len: usize, +} + +impl ExportState { + fn snapshot(&self) -> Option { + (self.count != 0).then_some(self.len) + } + + fn retain_existing(&mut self) -> Option { + let len = self.snapshot()?; + self.count += 1; + Some(len) + } + + // The caller holds a payload read guard, so first publication cannot + // overlap a resize and an existing epoch has the same length. + fn retain(&mut self, len: usize) { + if self.count == 0 { + self.len = len; + } + self.count += 1; + } + + fn release(&mut self) { + self.count -= 1; + } +} + +struct ByteArrayExportGuard<'a> { + owner: &'a PyByteArray, + len: usize, +} + +impl Drop for ByteArrayExportGuard<'_> { + fn drop(&mut self) { + self.owner.exports.lock().release(); + } +} + +enum ResizeAccess<'a> { + Exclusive(PyDetachingRwLockWriteGuard<'a, PyBytesInner>), + Exported { len: usize }, +} + +impl ResizeAccess<'_> { + fn len(&self) -> usize { + match self { + Self::Exclusive(inner) => inner.elements.len(), + Self::Exported { len } => *len, + } + } } pub(crate) type PyByteArrayRef = PyRef; @@ -65,6 +129,14 @@ impl PyPayload for PyByteArray { } } +// Acquisitions can call Python, and releases must follow acquisition order. +// No bytearray lock may be held when this owner is dropped. +#[derive(Default)] +struct ByteArrayBuffers { + first: Option, + second: Option, +} + /// Fill bytearray class methods dictionary. pub(crate) fn init(context: &'static Context) { PyByteArray::extend_class(context, context.types.bytearray_type); @@ -80,7 +152,7 @@ impl PyByteArray { const fn from_inner(inner: PyBytesInner) -> Self { Self { inner: PyDetachingRwLock::new(inner), - exports: AtomicUsize::new(0), + exports: PyMutex::new(ExportState { count: 0, len: 0 }), } } @@ -88,10 +160,148 @@ impl PyByteArray { PyDetachingRwLockReadGuard::map(self.inner.read(), |inner| &*inner.elements) } + /// Borrow for in-place byte replacement only. Do not change the length, + /// replace or reallocate storage, or hold this guard across Python calls. + /// Operations that may resize or reallocate must use export-checked access. pub fn borrow_buf_mut(&self) -> PyMappedDetachingRwLockWriteGuard<'_, Vec> { PyDetachingRwLockWriteGuard::map(self.inner.write(), |inner| &mut inner.elements) } + fn begin_export(&self) -> ByteArrayExportGuard<'_> { + // Existing epochs need no payload lock, including in codec callbacks + // that already hold a payload read guard. + let existing_len = { self.exports.lock().retain_existing() }; + let len = match existing_len { + Some(len) => len, + None => { + // Never wait for the payload with the metadata lock held. + // An earlier resize must finish before first publication. + let inner = self.inner.read(); + let len = inner.elements.len(); + self.exports.lock().retain(len); + len + } + }; + ByteArrayExportGuard { owner: self, len } + } + + fn resize_access(&self) -> ResizeAccess<'_> { + // An export is a borrow someone else still holds, so it is answered + // before the lock rather than by waiting on it. + let exported_len = { self.exports.lock().snapshot() }; + if let Some(len) = exported_len { + return ResizeAccess::Exported { len }; + } + let inner = self.inner.write(); + // An export may have started while we waited. Capture its length in + // the same decision, without borrowing the payload a second time. + let exported_len = { self.exports.lock().snapshot() }; + match exported_len { + Some(len) => ResizeAccess::Exported { len }, + None => ResizeAccess::Exclusive(inner), + } + } + + fn len_snapshot(&self) -> usize { + let exported_len = { self.exports.lock().snapshot() }; + exported_len.unwrap_or_else(|| self.inner().elements.len()) + } + + fn with_export(&self, f: impl FnOnce(usize) -> R) -> R { + let export = self.begin_export(); + f(export.len) + } + + fn buffer_snapshot(buffer: &PyBuffer, vm: &VirtualMachine) -> PyResult> { + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(buffer.desc.len) + .map_err(|_| vm.no_memory_error())?; + buffer.append_to(&mut bytes); + Ok(bytes) + } + + fn search_exported( + &self, + options: ByteInnerFindOptions, + search: impl FnOnce(&[u8], &[u8], core::ops::Range) -> R, + vm: &VirtualMachine, + ) -> PyResult { + self.with_export(|len| { + let (sub, range) = options.parts(len); + let buffer = if sub.check_buffer() { + Some(PyBuffer::from_object(vm, sub, BufferFlags::SIMPLE)?) + } else { + None + }; + let needle = match &buffer { + Some(buffer) => Self::buffer_snapshot(buffer, vm)?, + None => ByteInnerSub::try_from_object(vm, sub.to_owned())?.into_vec(vm)?, + }; + let result = search(&self.borrow_buf(), &needle, range); + Ok(result) + }) + } + + fn starts_ends_with( + &self, + options: anystr::StartsEndsWithArgs, + ends: bool, + vm: &VirtualMachine, + ) -> PyResult { + self.with_export(|len| { + let (affix, range) = options.parts(len); + let tailmatch = |item: &PyObject| -> PyResult { + // bytes subclasses use their bytes directly, as in tailmatch. + let buffer = if item.downcast_ref::().is_some() { + None + } else { + Some(PyBuffer::from_object(vm, item, BufferFlags::SIMPLE)?) + }; + let needle = match &buffer { + Some(buffer) => Self::buffer_snapshot(buffer, vm)?, + None => item.downcast_ref::().unwrap().as_bytes().to_vec(), + }; + let result = { + let bytes = self.borrow_buf(); + let slice = match &range { + Some(range) if !range.is_normal() => None, + Some(range) => bytes.get(range.clone()), + None => Some(&*bytes), + }; + slice.is_some_and(|slice| { + if ends { + slice.ends_with(&needle) + } else { + slice.starts_with(&needle) + } + }) + }; + Ok(result) + }; + if let Some(tuple) = affix.downcast_ref::() { + for item in tuple { + if tailmatch(item)? { + return Ok(true); + } + } + Ok(false) + } else { + tailmatch(affix).map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + vm.new_type_error(format!( + "{} first arg must be bytes or a tuple of bytes, not {}", + if ends { "endswith" } else { "startswith" }, + affix.class().name() + )) + } else { + error + } + }) + } + }) + } + fn repeat(&self, value: isize, vm: &VirtualMachine) -> PyResult { self.inner().mul(value, vm).map(|x| x.into()) } @@ -107,26 +317,38 @@ impl PyByteArray { value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { - match SequenceIndex::try_from_borrowed_object(vm, needle, "bytearray")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => zelf._setitem_by_index(i, value, vm), - SequenceIndex::Slice(slice) => { - let items = if zelf.is(&value) { - zelf.borrow_buf().to_vec() + SequenceIndex::Slice(mut slice) => { + // A distinct bytearray supplies its storage directly, including + // subclasses with an overridden buffer protocol. Every other + // source is copied before CPython unpacks the slice again. + let direct = value.downcast_ref::().filter(|_| !zelf.is(value)); + let (items, unpack_again) = if let Some(bytes) = direct { + (bytes.borrow_buf().to_vec(), false) } else { - bytearray_from_object(vm, value)? + if PyNumber::check(value) || value.fast_isinstance(vm.ctx.types.str_type) { + return Err(vm.new_type_error( + "can assign only bytes, buffers, or iterables of ints in range(0, 256)", + )); + } + (bytearray_from_object(vm, value)?, true) }; - if let Some(mut w) = zelf.try_resizable_opt() { - w.elements.setitem_by_slice(vm, slice, &items) - } else { - zelf.borrow_buf_mut() - .setitem_by_slice_no_resize(vm, slice, &items) + if unpack_again { + let SequenceIndex::Slice(repeated) = + SequenceIndex::try_from_borrowed_object::(vm, needle)? + else { + unreachable!("an unpacked slice remains a slice"); + }; + slice = repeated; } + zelf.assign_slice(slice, &items, vm) } } } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - match SequenceIndex::try_from_borrowed_object(vm, needle, "bytearray")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => self .borrow_buf() .getitem_by_index(vm, i) @@ -139,32 +361,129 @@ impl PyByteArray { } pub fn _delitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - match SequenceIndex::try_from_borrowed_object(vm, needle, "bytearray")? { - SequenceIndex::Int(i) => self.try_resizable(vm)?.elements.delitem_by_index(vm, i), - SequenceIndex::Slice(slice) => { - // TODO: delete 0 elements don't need resizable - self.try_resizable(vm)?.elements.delitem_by_slice(vm, slice) + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { + SequenceIndex::Int(i) => self.delitem_by_index(i, vm), + SequenceIndex::Slice(slice) => self.assign_slice(slice, &[], vm), + } + } + + fn check_slice_assignment( + slice: SaturatedSlice, + len: usize, + needed: usize, + resizable: bool, + vm: &VirtualMachine, + ) -> PyResult<(core::ops::Range, isize, usize)> { + let (range, step, slice_len) = slice.adjust_indices(len); + // Empty extended-slice assignment means deletion, not a length + // mismatch. Nonempty assignments validate their size before exports. + let resize = if step == 1 { + needed != slice_len + } else if needed == 0 { + // CPython checks exports even for an empty extended deletion. + true + } else if needed != slice_len { + return Err(vm.new_value_error(format!( + "attempt to assign bytes of size {needed} to extended slice of size {slice_len}", + ))); + } else { + false + }; + if resize && !resizable { + return Err(vm.new_buffer_error("Existing exports of data: object cannot be re-sized")); + } + Ok((range, step, slice_len)) + } + + fn assign_slice( + &self, + slice: SaturatedSlice, + items: &[u8], + vm: &VirtualMachine, + ) -> PyResult<()> { + let (mut inner, resizable) = match self.resize_access() { + ResizeAccess::Exclusive(inner) => (inner, true), + ResizeAccess::Exported { len } => { + // Reject resizing without waiting on an exported payload. A + // codec callback may already hold its read lock. + Self::check_slice_assignment(slice, len, items.len(), false, vm)?; + if items.is_empty() { + return Ok(()); + } + let inner = self.inner.write(); + // The export epoch may have ended while we waited. Validate + // again against the locked payload, not the old length. + let resizable = self.exports.lock().snapshot().is_none(); + (inner, resizable) } + }; + let elements = &mut inner.elements; + let (range, step, slice_len) = + Self::check_slice_assignment(slice, elements.len(), items.len(), resizable, vm)?; + if items.is_empty() { + elements.delitem_by_slice(vm, slice) + } else if step == 1 { + if slice_len == items.len() { + // Same-size replacement must keep exported storage intact. + elements[range].copy_from_slice(items); + } else { + elements + .try_reserve(items.len().saturating_sub(slice_len)) + .map_err(|_| vm.no_memory_error())?; + elements.splice(range, items.iter().copied()); + } + Ok(()) + } else { + elements.do_set_indexes( + SaturatedSliceIter::from_adjust_indices(range, step, slice_len), + items, + ); + Ok(()) } } + fn remove_by_index(&self, index: isize, pop: bool, vm: &VirtualMachine) -> PyResult { + let access = self.resize_access(); + let len = access.len(); + let index = index.wrapped_at(len).ok_or_else(|| { + let message = if !pop { + "bytearray index out of range" + } else if len == 0 { + "pop from empty bytearray" + } else { + "pop index out of range" + }; + vm.new_index_error(message) + })?; + // The exported length permits exact bounds checking without waiting + // on a payload lock already held by a codec callback. + let ResizeAccess::Exclusive(mut inner) = access else { + return Err(vm.new_buffer_error("Existing exports of data: object cannot be re-sized")); + }; + Ok(inner.elements.remove(index)) + } + + fn delitem_by_index(&self, index: isize, vm: &VirtualMachine) -> PyResult<()> { + self.remove_by_index(index, false, vm).map(drop) + } + fn irepeat(zelf: &Py, n: isize, vm: &VirtualMachine) -> PyResult<()> { + if n <= 0 { + return zelf.clear(vm); + } if n == 1 { return Ok(()); } - let mut w = match zelf.try_resizable(vm) { - Ok(w) => w, - Err(err) => { - return if zelf.borrow_buf().is_empty() { - // We can multiple an empty vector by any integer - Ok(()) - } else { - Err(err) - }; - } + let access = zelf.resize_access(); + let len = access.len(); + vm.check_repeat_or_overflow_error(len, n)?; + if len == 0 { + return Ok(()); + } + let ResizeAccess::Exclusive(mut inner) = access else { + return Err(vm.new_buffer_error("Existing exports of data: object cannot be re-sized")); }; - - w.imul(n, vm) + inner.imul(n, vm) } } @@ -173,11 +492,6 @@ impl PyByteArray { fn inner(&self) -> PyDetachingRwLockReadGuard<'_, PyBytesInner> { self.inner.read() } - #[inline] - fn inner_mut(&self) -> PyDetachingRwLockWriteGuard<'_, PyBytesInner> { - self.inner.write() - } - fn __len__(&self) -> usize { self.borrow_buf().len() } @@ -187,18 +501,53 @@ impl PyByteArray { } fn __contains__(&self, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + // Exact builtins cannot call Python while preparing the needle. The + // read lock alone protects their search; a temporary export would make + // a concurrent resize fail instead of waiting for that lock. + if let Some(bytes) = needle.downcast_ref_if_exact::(vm) { + return Ok(self.borrow_buf().contains_str(bytes.as_bytes())); + } + let int = if needle.class().is(vm.ctx.types.bool_type) { + needle.downcast_ref::() + } else { + needle.downcast_ref_if_exact::(vm) + }; + if let Some(int) = int { + let byte = int.as_bigint().byte_or(vm)?; + return Ok(self.borrow_buf().contains(&byte)); + } + // Converting the needle runs Python, which must not resize this bytearray. + let _export = self.begin_export(); let needle = ByteInnerSub::from_contains_arg(needle, vm)?; self.inner().contains(needle, vm) } fn __iadd__( zelf: PyRef, - other: ArgBytesLike, + other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - zelf.try_resizable(vm)? - .elements - .extend(&*other.borrow_buf()); + let buffer = ArgBytesLike::try_from_object(vm, other.clone()).map_err(|_| { + vm.new_type_error(format!( + "can't concat {} to {}", + other.class().name(), + zelf.class().name() + )) + })?; + if !buffer.is_empty() { + // Reject aliases before reading their payload: a codec callback + // may already hold that read lock with a writer queued behind it. + drop(zelf.try_resizable(vm)?); + // Snapshot before locking the destination, but retain the export + // until the write finishes, then recheck exports in assign_slice. + let buffer = PyBuffer::from(buffer); + let items = Self::buffer_snapshot(&buffer, vm)?; + zelf.assign_slice( + SaturatedSlice::from_parts(isize::MAX, isize::MAX, 1), + &items, + vm, + )?; + } Ok(zelf) } @@ -221,7 +570,9 @@ impl PyByteArray { fn __mod__(&self, values: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Formatting calls the values' conversion methods, which can reach - // this bytearray, so the format is taken by value. + // this bytearray, so the format is taken by value. It also stays + // exported until formatting ends, so resizing it raises BufferError. + let _export = self.begin_export(); let format = self.inner().clone(); let formatted = format.cformat(values, vm)?; Ok(formatted.into()) @@ -258,8 +609,26 @@ impl PyByteArray {} #[derive(FromArgs)] struct ByteArrayReduceExArgs { - #[pyarg(positional, default)] - proto: usize, + #[pyarg(positional, optional, py_default = "0")] + proto: OptionalArg, +} + +#[derive(FromArgs)] +struct TakeBytesArgs { + #[pyarg(positional, default = None)] + n: Option, +} + +// Expose the actual split parameters without converting them before the +// method acquires its export guard. +struct ByteArraySplitArgs(FuncArgs); + +impl FromArgs for ByteArraySplitArgs { + const PARAMS: Option<&'static [Param]> = ByteInnerSplitOptions::PARAMS; + + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + FuncArgs::from_args(vm, args).map(Self) + } } #[derive(FromArgs)] @@ -281,11 +650,7 @@ impl Py { #[pymethod] fn pop(&self, index: PopArgs, vm: &VirtualMachine) -> PyResult { - let elements = &mut self.try_resizable(vm)?.elements; - let index = elements - .wrap_index(index.index) - .ok_or_else(|| vm.new_index_error("index out of range"))?; - Ok(elements.remove(index)) + self.remove_by_index(index.index, true, vm) } #[pymethod] @@ -293,6 +658,7 @@ impl Py { let value = value_from_object(vm, &item)?; let elements = &mut self.try_resizable(vm)?.elements; let index = elements.saturate_index(index); + elements.try_reserve(1).map_err(|_| vm.no_memory_error())?; elements.insert(index, value); Ok(()) } @@ -300,14 +666,34 @@ impl Py { #[pymethod] fn append(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let value = value_from_object(vm, &item)?; - self.try_resizable(vm)?.elements.push(value); + let elements = &mut self.try_resizable(vm)?.elements; + elements.try_reserve(1).map_err(|_| vm.no_memory_error())?; + elements.push(value); Ok(()) } #[pymethod] fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let byte = value_from_object(vm, &value)?; - let elements = &mut self.try_resizable(vm)?.elements; + let mut inner = match self.resize_access() { + ResizeAccess::Exclusive(inner) => inner, + ResizeAccess::Exported { len } => { + // Missing values precede export rejection. Do not wait for a + // read lock: a reentrant codec can have a writer queued behind + // its existing read guard. + let missing = len == 0 + || self + .inner + .try_read() + .is_some_and(|inner| inner.elements.find_byte(byte).is_none()); + return Err(if missing { + vm.new_value_error("value not found in bytearray") + } else { + vm.new_buffer_error("Existing exports of data: object cannot be re-sized") + }); + } + }; + let elements = &mut inner.elements; let index = elements .find_byte(byte) .ok_or_else(|| vm.new_value_error("value not found in bytearray"))?; @@ -320,6 +706,13 @@ impl Py { if self.is(&iterable_of_ints) { return PyByteArray::irepeat(self, 2, vm); } + // Buffer acquisition can mutate self. The buffer path inserts at the + // old end, whereas the iterable path appends after all conversions. + let start = if iterable_of_ints.check_buffer() { + self.len_snapshot() as isize + } else { + isize::MAX + }; // bytearray_setslice keeps the export alive across the resize, so a value // looking at this bytearray is what stops it from growing. let buffer = iterable_of_ints @@ -336,48 +729,149 @@ impl Py { }) .transpose()?; let items = match &buffer { - Some(buffer) => buffer - .as_contiguous() - .ok_or_else(|| { - vm.new_buffer_error("non-contiguous buffer is not a bytes-like object") - })? - .to_vec(), + Some(buffer) => { + if !buffer.desc.is_contiguous() { + return Err( + vm.new_buffer_error("non-contiguous buffer is not a bytes-like object") + ); + } + if buffer.desc.len == 0 { + return Ok(()); + } + drop(self.try_resizable(vm)?); + PyByteArray::buffer_snapshot(buffer, vm)? + } None => bytearray_extend_from_object(vm, &iterable_of_ints)?, }; - self.try_resizable(vm)?.elements.extend(items); - Ok(()) + self.assign_slice(SaturatedSlice::from_parts(start, start, 1), &items, vm) } #[pymethod] fn clear(&self, vm: &VirtualMachine) -> PyResult<()> { - self.try_resizable(vm)?.elements.clear(); + let _old = match self.resize_access() { + ResizeAccess::Exported { len: 0 } => return Ok(()), + ResizeAccess::Exported { .. } => { + return Err( + vm.new_buffer_error("Existing exports of data: object cannot be re-sized") + ); + } + ResizeAccess::Exclusive(mut inner) => { + if inner.elements.is_empty() { + return Ok(()); + } + core::mem::take(&mut inner.elements) + } + }; Ok(()) } + #[pymethod] + fn take_bytes( + &self, + TakeBytesArgs { n }: TakeBytesArgs, + vm: &VirtualMachine, + ) -> PyResult { + // __index__ can resize self or acquire/release exports. Convert before + // observing either the payload or the export epoch. + let n = match n { + None => None, + Some(n) => { + let index = n + .try_index_opt(vm) + .ok_or_else(|| vm.new_type_error("n must be an integer or None"))??; + Some(index.as_bigint().to_isize().ok_or_else(|| { + vm.new_index_error(format!( + "cannot fit '{}' into an index-sized integer", + n.class().slot_name() + )) + })?) + } + }; + let access = self.resize_access(); + let len = access.len(); + // Vec lengths fit isize. Adding a nonnegative length to a negative + // index cannot overflow; preserve the adjusted index in the error. + let to_take = match n { + None => len as isize, + Some(n) if n < 0 => n + len as isize, + Some(n) => n, + }; + if to_take < 0 || to_take as usize > len { + drop(access); + return Err( + vm.new_index_error(format!("can't take {to_take} bytes outside size {len}")) + ); + } + let ResizeAccess::Exclusive(mut inner) = access else { + return Err(vm.new_buffer_error("Existing exports of data: object cannot be re-sized")); + }; + let to_take = to_take as usize; + let result = if to_take == 0 { + Vec::new() + } else if to_take == len { + core::mem::take(&mut inner.elements) + } else { + let mut result = Vec::new(); + if result.try_reserve_exact(to_take).is_err() { + drop(inner); + return Err(vm.no_memory_error()); + } + result.extend_from_slice(&inner.elements[..to_take]); + inner.elements.drain(..to_take); + result + }; + Ok(PyBytes::from(result)) + } + #[pymethod] fn __reduce_ex__( &self, args: ByteArrayReduceExArgs, vm: &VirtualMachine, - ) -> (PyTypeRef, PyTupleRef, Option) { - let _ = args.proto; - self.__reduce__(vm) + ) -> PyResult<(PyTypeRef, PyTupleRef, PyObjectRef)> { + let proto = match args.proto { + OptionalArg::Present(proto) => { + proto.as_ref().as_bigint().to_i32().ok_or_else(|| { + vm.new_overflow_error("Python int too large to convert to C int") + })? + } + OptionalArg::Missing => 0, + }; + self.common_reduce(proto, vm) } #[pymethod] - fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option) { - let bytes = PyBytes::from(self.borrow_buf().to_vec()).to_pyobject(vm); - ( - self.class().to_owned(), - PyTuple::new_ref(vec![bytes], &vm.ctx), - self.as_object().dict(), - ) + fn __reduce__(&self, vm: &VirtualMachine) -> PyResult<(PyTypeRef, PyTupleRef, PyObjectRef)> { + self.common_reduce(2, vm) + } + + fn common_reduce( + &self, + proto: i32, + vm: &VirtualMachine, + ) -> PyResult<(PyTypeRef, PyTupleRef, PyObjectRef)> { + // Like CPython's _common_reduce, get state before reading the buffer: + // an overridden __getstate__ may change the bytearray contents. + let state = self + .as_object() + .get_attr(identifier!(vm, __getstate__), vm)? + .call((), vm)?; + let bytes = self.borrow_buf(); + let args = if bytes.is_empty() { + PyTuple::new_ref(Vec::new(), &vm.ctx) + } else if proto < 3 { + let text: String = bytes.iter().map(|&byte| char::from(byte)).collect(); + vm.new_tuple((vm.ctx.new_str(text), "latin-1")) + } else { + vm.new_tuple((PyBytes::from(bytes.to_vec()).to_pyobject(vm),)) + }; + Ok((self.class().to_owned(), args, state)) } #[cfg(debug_assertions)] #[pygetset] fn exports(&self) -> usize { - self.exports.load(Ordering::Relaxed) + self.exports.lock().count } #[pymethod] @@ -469,8 +963,12 @@ impl Py { #[pymethod] fn hex(&self, options: ByteInnerHexOptions, vm: &VirtualMachine) -> PyResult { // Measuring the separator runs Python, so it happens before the buffer - // is borrowed. - let (sep, bytes_per_sep) = options.resolve(vm)?; + // is borrowed, with the buffer exported so that resizing this + // bytearray from there raises BufferError. + let (sep, bytes_per_sep) = { + let _export = self.begin_export(); + options.resolve(vm)? + }; Ok(self.inner().hex(sep, bytes_per_sep)) } @@ -488,7 +986,11 @@ impl Py { options: ByteInnerPaddingOptions, vm: &VirtualMachine, ) -> PyResult { - Ok(self.inner().center(options, vm)?.into()) + let (width, fillchar) = options.get_value("center", vm)?; + Ok(self + .inner() + .pad_with(width, fillchar, AnyStr::py_center, vm)? + .into()) } #[pymethod] @@ -497,7 +999,11 @@ impl Py { options: ByteInnerPaddingOptions, vm: &VirtualMachine, ) -> PyResult { - Ok(self.inner().ljust(options, vm)?.into()) + let (width, fillchar) = options.get_value("ljust", vm)?; + Ok(self + .inner() + .pad_with(width, fillchar, AnyStr::py_ljust, vm)? + .into()) } #[pymethod] @@ -506,21 +1012,28 @@ impl Py { options: ByteInnerPaddingOptions, vm: &VirtualMachine, ) -> PyResult { - Ok(self.inner().rjust(options, vm)?.into()) + let (width, fillchar) = options.get_value("rjust", vm)?; + Ok(self + .inner() + .pad_with(width, fillchar, AnyStr::py_rjust, vm)? + .into()) } #[pymethod] fn count(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { - self.inner().count(options, vm) + self.search_exported( + options, + |bytes, needle, range| bytes.py_count(needle, range, |h, n| h.find_iter(n).count()), + vm, + ) } #[pymethod] fn join(&self, iterable_of_bytes: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Export before driving the iterable: resizing is forbidden, but // same-size mutations must be reflected in the joined result. - self.exports.fetch_add(1, Ordering::Release); - scopeguard::defer! { self.exports.fetch_sub(1, Ordering::Release); } - let separator_len = self.__len__(); + let _export = self.begin_export(); + let separator_len = _export.len; let items = BytesJoin::new(iterable_of_bytes, vm)?; Ok(items .join(separator_len, || self.borrow_buf().into(), vm)? @@ -528,20 +1041,8 @@ impl Py { } #[pymethod] - fn endswith(&self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine) -> PyResult { - let borrowed = self.borrow_buf(); - let (affix, substr) = - match options.prepare(&*borrowed, borrowed.len(), |s, r| s.get_bytes(r)) { - Some(x) => x, - None => return Ok(false), - }; - substr.py_starts_ends_with( - &affix, - "endswith", - "bytes", - |s, x: PyBytesInner| s.ends_with(x.as_bytes()), - vm, - ) + fn endswith(&self, options: anystr::EndsWithArgs, vm: &VirtualMachine) -> PyResult { + self.starts_ends_with(options.inner, true, vm) } #[pymethod] @@ -550,42 +1051,48 @@ impl Py { options: anystr::StartsEndsWithArgs, vm: &VirtualMachine, ) -> PyResult { - let borrowed = self.borrow_buf(); - let (affix, substr) = - match options.prepare(&*borrowed, borrowed.len(), |s, r| s.get_bytes(r)) { - Some(x) => x, - None => return Ok(false), - }; - substr.py_starts_ends_with( - &affix, - "startswith", - "bytes", - |s, x: PyBytesInner| s.starts_with(x.as_bytes()), + self.starts_ends_with(options, false, vm) + } + + /// Converting the needle runs Python, which must not resize this + /// bytearray, so the buffer stays exported while it does. + fn find_exported( + &self, + options: ByteInnerFindOptions, + find: F, + vm: &VirtualMachine, + ) -> PyResult> + where + F: Fn(&[u8], &[u8]) -> Option, + { + self.search_exported( + options, + |bytes, needle, range| bytes.py_find(needle, range, find), vm, ) } #[pymethod] fn find(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { - let index = self.inner().find(options, |h, n| h.find(n), vm)?; + let index = self.find_exported(options, |h, n| h.find(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn index(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { - let index = self.inner().find(options, |h, n| h.find(n), vm)?; + let index = self.find_exported(options, |h, n| h.find(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found")) } #[pymethod] fn rfind(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { - let index = self.inner().find(options, |h, n| h.rfind(n), vm)?; + let index = self.find_exported(options, |h, n| h.rfind(n), vm)?; Ok(index.map_or(-1, |v| v as isize)) } #[pymethod] fn rindex(&self, options: ByteInnerFindOptions, vm: &VirtualMachine) -> PyResult { - let index = self.inner().find(options, |h, n| h.rfind(n), vm)?; + let index = self.find_exported(options, |h, n| h.rfind(n), vm)?; index.ok_or_else(|| vm.new_value_error("substring not found")) } @@ -595,17 +1102,37 @@ impl Py { options: ByteInnerTranslateOptions, vm: &VirtualMachine, ) -> PyResult { - Ok(self.inner().translate(options, vm)?.into()) + let mut buffers = ByteArrayBuffers::default(); + if let Some(table) = &options.table { + let buffer = PyBuffer::from_object(vm, table, BufferFlags::SIMPLE)?; + if buffer.desc.len != 256 { + return Err(vm.new_value_error("translation table must be 256 characters long")); + } + buffers.first = Some(buffer); + } + buffers.second = Some(PyBuffer::from_object( + vm, + &options.delete, + BufferFlags::SIMPLE, + )?); + // Both acquisition callbacks finish before any input bytes are read. + let table = match &buffers.first { + Some(buffer) => PyByteArray::buffer_snapshot(buffer, vm)?, + None => (0..=u8::MAX).collect(), + }; + let delete = PyByteArray::buffer_snapshot(buffers.second.as_ref().unwrap(), vm)?; + let result = self.inner().translate_with(&table, &delete).into(); + Ok(result) } #[pymethod] fn strip(&self, options: ByteInnerStripOptions) -> PyByteArray { - self.inner().strip(options.bytes).into() + self.inner().strip(options.bytes).to_vec().into() } #[pymethod] fn removeprefix(&self, prefix: PyBytesInner) -> PyByteArray { - self.inner().removeprefix(prefix).into() + self.inner().removeprefix(prefix).to_vec().into() } #[pymethod] @@ -616,9 +1143,13 @@ impl Py { #[pymethod] fn split( &self, - options: ByteInnerSplitOptions, + ByteArraySplitArgs(args): ByteArraySplitArgs, vm: &VirtualMachine, ) -> PyResult> { + // Converting the separator runs Python, which must not resize this + // bytearray, so the arguments are bound with the buffer exported. + let _export = self.begin_export(); + let options: ByteInnerSplitOptions = args.bind_for(vm, "split")?; self.inner() .split(options, |s, vm| vm.ctx.new_bytearray(s.to_vec()).into(), vm) } @@ -626,9 +1157,11 @@ impl Py { #[pymethod] fn rsplit( &self, - options: ByteInnerSplitOptions, + ByteArraySplitArgs(args): ByteArraySplitArgs, vm: &VirtualMachine, ) -> PyResult> { + let _export = self.begin_export(); + let options: ByteInnerSplitOptions = args.bind_for(vm, "rsplit")?; self.inner() .rsplit(options, |s, vm| vm.ctx.new_bytearray(s.to_vec()).into(), vm) } @@ -660,8 +1193,12 @@ impl Py { } #[pymethod] - fn expandtabs(&self, options: anystr::ExpandTabsArgs) -> PyByteArray { - self.inner().expandtabs(options).into() + fn expandtabs( + &self, + options: anystr::ExpandTabsArgs, + vm: &VirtualMachine, + ) -> PyResult { + self.inner().expandtabs(options, vm).map(Into::into) } #[pymethod] @@ -681,7 +1218,7 @@ impl Py { options: ByteInnerReplaceOptions, vm: &VirtualMachine, ) -> PyResult { - Ok(self.inner().replace(options, vm)?.into()) + Ok(self.inner().replace(options, vm)?.into_owned().into()) } #[pymethod] @@ -704,8 +1241,28 @@ impl Py { if size < 0 { return Err(vm.new_value_error("bytearray.resize(): new size must be >= 0")); } - let mut inner = self.try_resizable(vm)?; let size = size as usize; + // An export's stable length avoids re-entering the payload lock. + let access = self.resize_access(); + let len = access.len(); + if size == len { + return Ok(()); + } + let ResizeAccess::Exclusive(mut inner) = access else { + return Err(vm.new_buffer_error("Existing exports of data: object cannot be re-sized")); + }; + // CPython 3.15's PyByteArray_SIZE_MAX subtracts _PyBytesObject_SIZE. + // The normal GIL build has four pointer-sized header fields and a + // trailing null byte. Vec accepts larger lengths on 32-bit targets. + const MAX_SIZE: usize = isize::MAX as usize - size_of::<[usize; 4]>() - 1; + if size > MAX_SIZE { + return Err(vm.no_memory_error()); + } + if size == 0 { + let _old = core::mem::take(&mut inner.elements); + drop(inner); + return Ok(()); + } let elements = &mut inner.elements; elements .try_reserve_exact(size.saturating_sub(elements.len())) @@ -744,7 +1301,7 @@ impl PyRef { } #[pymethod] - fn decode(self, args: DecodeArgs, vm: &VirtualMachine) -> PyResult { + fn decode(self, args: TextCodecArgs, vm: &VirtualMachine) -> PyResult { bytes_decode(self.into(), args, vm) } } @@ -755,9 +1312,18 @@ impl Initializer for PyByteArray { type Args = ByteInnerNewOptions; fn init(zelf: &Py, options: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - // First unpack bytearray and *then* get a lock to set it. - let mut inner = options.get_inner(bytearray_from_object, vm)?; - core::mem::swap(&mut *zelf.inner_mut(), &mut inner); + // Reject exports and clear existing contents before converting source. + zelf.try_resizable(vm)?.elements = Vec::new(); + // Conversion can call Python, so do not hold the lock across it and + // check again for exports acquired by a callback or another thread. + let (mut inner, zero_count) = + options.get_inner_with_zero_count(bytearray_from_object, vm)?; + // A zero integer count performs no further writes, including when its + // __index__ callback changed this bytearray or acquired an export. + if zero_count { + return Ok(()); + } + core::mem::swap(&mut *zelf.try_resizable(vm)?, &mut inner); Ok(()) } } @@ -769,10 +1335,32 @@ impl Comparable for PyByteArray { op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - if let Some(res) = op.identical_optimization(zelf, other) { - return Ok(res.into()); + if !zelf.as_object().check_buffer() || !other.check_buffer() { + return Ok(PyComparisonValue::NotImplemented); } - Ok(zelf.inner().cmp(other, op, vm)) + let first = match PyBuffer::from_object(vm, zelf.as_object(), BufferFlags::SIMPLE) { + Ok(buffer) => buffer, + Err(_) => return Ok(PyComparisonValue::NotImplemented), + }; + let mut buffers = ByteArrayBuffers { + first: Some(first), + second: None, + }; + buffers.second = match PyBuffer::from_object(vm, other, BufferFlags::SIMPLE) { + Ok(buffer) => Some(buffer), + Err(_) => return Ok(PyComparisonValue::NotImplemented), + }; + let left = buffers.first.as_ref().unwrap(); + let right = buffers.second.as_ref().unwrap(); + let result = if left.desc.len != right.desc.len && op.eval_eq(|| false).is_some() { + op.eval_eq(|| false).unwrap() + } else { + let left = Self::buffer_snapshot(left, vm)?; + let right = Self::buffer_snapshot(right, vm)?; + op.eval_eq(|| left == right) + .unwrap_or_else(|| op.eval_ord(left.cmp(&right))) + }; + Ok(result.into()) } } @@ -785,17 +1373,14 @@ static BUFFER_METHODS: BufferMethods = BufferMethods { ) .into() }, - release: |buffer| { - buffer - .obj_as::() - .exports - .fetch_sub(1, Ordering::Release); - }, + release: |buffer| buffer.obj_as::().exports.lock().release(), retain: |buffer| { + // as_buffer holds the payload read guard until PyBuffer::new returns. buffer .obj_as::() .exports - .fetch_add(1, Ordering::Release); + .lock() + .retain(buffer.desc.len); }, }; @@ -815,9 +1400,11 @@ impl AsBuffer for PyByteArray { } fn as_buffer(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + // Keep the length stable until PyBuffer::new retains the export. + let inner = zelf.inner(); Ok(PyBuffer::new( zelf.to_owned().into(), - BufferDescriptor::simple(zelf.__len__(), false), + BufferDescriptor::simple(inner.elements.len(), false), &BUFFER_METHODS, )) } @@ -827,9 +1414,10 @@ impl BufferResizeGuard for PyByteArray { type Resizable<'a> = PyDetachingRwLockWriteGuard<'a, PyBytesInner>; fn try_resizable_opt(&self) -> Option> { - // An export is a borrow someone else still holds, so it is answered - // before the lock rather than by waiting on it. - (self.exports.load(Ordering::SeqCst) == 0).then(|| self.inner.write()) + match self.resize_access() { + ResizeAccess::Exclusive(inner) => Some(inner), + ResizeAccess::Exported { .. } => None, + } } } @@ -860,10 +1448,41 @@ impl AsSequence for PyByteArray { static AS_SEQUENCE: PySequenceMethods = PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyByteArray::sequence_downcast(seq).__len__())), concat: atomic_func!(|seq, other, vm| { - PyByteArray::sequence_downcast(seq) - .inner() - .concat(other, vm) - .map(|x| PyByteArray::from(x).into_pyobject(vm)) + let concat_error = || { + vm.new_type_error(format!( + "can't concat {} to {}", + other.class().name(), + seq.obj.class().name() + )) + }; + // Protect the left operand before the right buffer callback, + // without holding either operand's lock across Python calls. + let left = PyBuffer::from_object(vm, seq.obj, BufferFlags::SIMPLE) + .map_err(|_| concat_error())?; + let right = match PyBuffer::from_object(vm, other, BufferFlags::SIMPLE) { + Ok(buffer) => buffer, + Err(_) => { + let error = concat_error(); + return Err(error); + } + }; + let result = (|| { + let len = left + .desc + .len + .checked_add(right.desc.len) + .ok_or_else(|| vm.no_memory_error())?; + let mut bytes = Vec::new(); + bytes + .try_reserve_exact(len) + .map_err(|_| vm.no_memory_error())?; + left.append_to(&mut bytes); + right.append_to(&mut bytes); + Ok(PyByteArray::from(bytes).into_pyobject(vm)) + })(); + // Buffer release can run Python too; all slice guards are gone. + drop(left); + result }), repeat: atomic_func!(|seq, n, vm| { PyByteArray::sequence_downcast(seq) @@ -874,23 +1493,22 @@ impl AsSequence for PyByteArray { PyByteArray::sequence_downcast(seq) .borrow_buf() .getitem_by_index(vm, i) - .map(|x| vm.ctx.new_bytes(vec![x]).into()) + .map(|x| vm.ctx.new_int(x).into()) }), ass_item: atomic_func!(|seq, i, value, vm| { let zelf = PyByteArray::sequence_downcast(seq); if let Some(value) = value { zelf._setitem_by_index(i, &value, vm) } else { - zelf.borrow_buf_mut().delitem_by_index(vm, i) + zelf.delitem_by_index(i, vm) } }), contains: atomic_func!(|seq, other, vm| { PyByteArray::sequence_downcast(seq).__contains__(other.to_owned(), vm) }), inplace_concat: atomic_func!(|seq, other, vm| { - let other = ArgBytesLike::try_from_object(vm, other.to_owned())?; let zelf = PyByteArray::sequence_downcast(seq).to_owned(); - PyByteArray::__iadd__(zelf, other, vm).map(|x| x.into()) + PyByteArray::__iadd__(zelf, other.to_owned(), vm).map(|x| x.into()) }), inplace_repeat: atomic_func!(|seq, n, vm| { let zelf = PyByteArray::sequence_downcast(seq).to_owned(); @@ -921,7 +1539,7 @@ impl AsNumber for PyByteArray { impl Iterable for PyByteArray { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { Ok(PyByteArrayIterator { - internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), + internal: NativeSequenceIter::new(zelf, NativeIterKind::ByteArray, 0), } .into_pyobject(vm)) } @@ -936,10 +1554,10 @@ impl Representable for PyByteArray { } } -#[pyclass(module = false, name = "bytearray_iterator")] +#[pyclass(module = false, name = "bytearray_iterator", traverse)] #[derive(Debug)] pub(crate) struct PyByteArrayIterator { - internal: PyMutex>, + internal: NativeSequenceIter, } impl PyPayload for PyByteArrayIterator { @@ -953,14 +1571,14 @@ impl PyPayload for PyByteArrayIterator { impl Py { #[pymethod] fn __length_hint__(&self) -> usize { - self.internal.lock().length_hint(|obj| obj.__len__()) + self.internal.length_hint(|obj| obj.__len__()) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_iter(vm)?; - Ok(self.internal.lock().reduce( + Ok(self.internal.reduce( func, - |x| x.clone().into(), + |x| x.into(), |vm| vm.ctx.empty_tuple.clone().into(), vm, )) @@ -968,20 +1586,59 @@ impl Py { #[pymethod] fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.internal - .lock() - .set_state(&object, |obj, pos| pos.min(obj.__len__()), vm) + self.internal.set_state(&object, |obj| obj.__len__(), vm) } } impl SelfIter for PyByteArrayIterator {} impl IterNext for PyByteArrayIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_next(&zelf.internal, |bytearray, pos| { - let buf = bytearray.borrow_buf(); - Ok(PyIterReturn::from_result( - buf.get(pos).map(|&x| vm.new_pyobj(x)).ok_or(None), - )) - }) + let byte = zelf + .internal + .next(|bytearray, pos| bytearray.borrow_buf().get(pos).copied()); + Ok(PyIterReturn::from_result( + byte.map(|byte| vm.new_pyobj(byte)).ok_or(None), + )) + } +} + +#[cfg(test)] +mod export_state_tests { + use super::ExportState; + + #[test] + fn export_epoch_length_is_stable_until_last_release() { + let mut state = ExportState::default(); + assert_eq!(state.snapshot(), None); + assert_eq!(state.retain_existing(), None); + state.retain(3); + assert_eq!(state.snapshot(), Some(3)); + assert_eq!(state.retain_existing(), Some(3)); + state.retain(3); + assert_eq!(state.count, 3); + state.release(); + state.release(); + assert_eq!(state.count, 1); + assert_eq!(state.snapshot(), Some(3)); + let rejected_length = state.snapshot(); + state.release(); + assert_eq!(state.snapshot(), None); + state.retain(7); + assert_eq!(state.snapshot(), Some(7)); + assert_eq!(rejected_length, Some(3)); + state.release(); + assert_eq!(state.snapshot(), None); + } + + #[test] + fn empty_export_is_distinct_from_no_export() { + let mut state = ExportState::default(); + state.retain(0); + assert_eq!(state.snapshot(), Some(0)); + assert_eq!(state.retain_existing(), Some(0)); + state.release(); + assert_eq!(state.snapshot(), Some(0)); + state.release(); + assert_eq!(state.snapshot(), None); } } diff --git a/crates/vm/src/builtins/bytes.rs b/crates/vm/src/builtins/bytes.rs index 415cf4df4df..bb94f888580 100644 --- a/crates/vm/src/builtins/bytes.rs +++ b/crates/vm/src/builtins/bytes.rs @@ -1,28 +1,29 @@ +use super::native_iter::{NativeIterKind, NativeSequenceIter}; use super::{ - PositionIterInternal, PyDictRef, PyGenericAlias, PyStrRef, PyTuple, PyTupleRef, PyType, - PyTypeRef, iter::builtins_iter, locked_next, + PyDictRef, PyGenericAlias, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, + iter::builtins_iter, }; use crate::common::lock::LazyLock; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, - TryFromBorrowedObject, VirtualMachine, - anystr::{self, AnyStr}, - atomic_func, + TryFromBorrowedObject, VirtualMachine, anystr, atomic_func, byte::bytes_from_object, bytes_inner::{ - ByteInnerFindOptions, ByteInnerHexOptions, ByteInnerNewOptions, ByteInnerPaddingOptions, - ByteInnerReplaceOptions, ByteInnerSplitOptions, ByteInnerStripOptions, ByteInnerSub, - ByteInnerTranslateOptions, BytesJoin, DecodeArgs, PyBytesInner, bytes_decode, + ByteInnerBuffer, ByteInnerFindOptions, ByteInnerHexOptions, ByteInnerNewOptions, + ByteInnerPaddingOptions, ByteInnerReplaceOptions, ByteInnerSplitOptions, + ByteInnerStripOptions, ByteInnerSub, ByteInnerTranslateOptions, BytesJoin, PyBytesInner, + bytes_decode, }, class::{PyClassDef, PyClassImpl}, - common::{hash::PyHash, lock::PyMutex}, + codecs::TextCodecArgs, + common::hash::PyHash, convert::{ToPyObject, ToPyResult}, function::{ArgBytesLike, ArgIndex, FuncArgs, OptionalArg, PyComparisonValue}, protocol::{ BufferDescriptor, BufferFlags, BufferMethods, PyBuffer, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods, }, - sliceable::{SequenceIndex, SliceableSequenceOp}, + sliceable::{NameByte, SequenceIndex, SliceableSequenceOp}, types::{ AsBuffer, AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, @@ -31,6 +32,7 @@ use crate::{ use bstr::ByteSlice; use core::{mem::size_of, ops::Deref}; use memchr::memchr; +use rustpython_common::wtf8::wtf8_concat; #[pyclass(module = false, name = "bytes")] #[derive(Clone, Debug)] @@ -130,15 +132,23 @@ impl Constructor for PyBytes { && let Some(bytes_method) = vm.get_method(obj.clone(), identifier!(vm, __bytes__)) { let bytes = bytes_method?.call((), vm)?; - // If exact bytes type and __bytes__ returns bytes, use it directly - if cls.is(vm.ctx.types.bytes_type) - && let Ok(b) = bytes.clone().downcast::() - { - return Ok(b.into()); + let bytes = bytes.downcast::().map_err(|result| { + match ( + obj.class().fully_qualified_name(vm), + result.class().fully_qualified_name(vm), + ) { + (Ok(source), Ok(result)) => vm.new_type_error(wtf8_concat!( + source, + ".__bytes__() must return a bytes, not ", + result + )), + (Err(error), _) | (_, Err(error)) => error, + } + })?; + if cls.is(vm.ctx.types.bytes_type) { + return Ok(bytes.into()); } - // Otherwise convert to Vec - let inner = PyBytesInner::try_from_borrowed_object(vm, &bytes)?; - let payload = Self::py_new(&cls, inner.elements, vm)?; + let payload = Self::py_new(&cls, bytes.as_bytes().to_vec(), vm)?; return payload.into_ref_with_type(vm, cls).map(Into::into); } @@ -165,7 +175,7 @@ impl PyBytes { } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - match SequenceIndex::try_from_borrowed_object(vm, needle, "byte")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => self .getitem_by_index(vm, i) .map(|x| vm.ctx.new_int(x).into()), @@ -235,7 +245,7 @@ impl PyBytes { #[pyclass( itemsize = 1, - flags(BASETYPE, _MATCH_SELF), + flags(BASETYPE, _MATCH_SELF, BYTES_SUBCLASS), with( Py, PyRef, @@ -280,7 +290,7 @@ impl Py { #[pymethod] fn __reduce_ex__( &self, - _proto: usize, + _protocol: usize, vm: &VirtualMachine, ) -> (PyTypeRef, PyTupleRef, Option) { self.__reduce__(vm) @@ -422,17 +432,16 @@ impl Py { } #[pymethod] - fn endswith(&self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine) -> PyResult { - let (affix, substr) = - match options.prepare(self.as_bytes(), self.len(), |s, r| s.get_bytes(r)) { - Some(x) => x, - None => return Ok(false), - }; - substr.py_starts_ends_with( - &affix, + fn endswith(&self, options: anystr::EndsWithArgs, vm: &VirtualMachine) -> PyResult { + options.inner.matches( + self.len(), "endswith", "bytes", - |s, x: PyBytesInner| s.ends_with(x.as_bytes()), + |affix: ByteInnerBuffer<'_>, range| { + self.as_bytes() + .get(range.unwrap_or(0..self.len())) + .is_some_and(|text| affix.with_ref(|affix| text.ends_with(affix))) + }, vm, ) } @@ -443,16 +452,15 @@ impl Py { options: anystr::StartsEndsWithArgs, vm: &VirtualMachine, ) -> PyResult { - let (affix, substr) = - match options.prepare(self.as_bytes(), self.len(), |s, r| s.get_bytes(r)) { - Some(x) => x, - None => return Ok(false), - }; - substr.py_starts_ends_with( - &affix, + options.matches( + self.len(), "startswith", "bytes", - |s, x: PyBytesInner| s.starts_with(x.as_bytes()), + |affix: ByteInnerBuffer<'_>, range| { + self.as_bytes() + .get(range.unwrap_or(0..self.len())) + .is_some_and(|text| affix.with_ref(|affix| text.starts_with(affix))) + }, vm, ) } @@ -481,30 +489,6 @@ impl Py { index.ok_or_else(|| vm.new_value_error("substring not found")) } - #[pymethod] - fn translate( - &self, - options: ByteInnerTranslateOptions, - vm: &VirtualMachine, - ) -> PyResult { - Ok(self.inner.translate(options, vm)?.into()) - } - - #[pymethod] - fn strip(&self, options: ByteInnerStripOptions) -> PyBytes { - self.inner.strip(options.bytes).into() - } - - #[pymethod] - fn removeprefix(&self, prefix: PyBytesInner) -> PyBytes { - self.inner.removeprefix(prefix).into() - } - - #[pymethod] - fn removesuffix(&self, suffix: PyBytesInner) -> PyBytes { - self.inner.removesuffix(suffix).into() - } - #[pymethod] fn split( &self, @@ -556,8 +540,12 @@ impl Py { } #[pymethod] - fn expandtabs(&self, options: anystr::ExpandTabsArgs) -> PyBytes { - self.inner.expandtabs(options).into() + fn expandtabs( + &self, + options: anystr::ExpandTabsArgs, + vm: &VirtualMachine, + ) -> PyResult { + self.inner.expandtabs(options, vm).map(Into::into) } #[pymethod] @@ -572,27 +560,63 @@ impl Py { } #[pymethod] - fn replace(&self, options: ByteInnerReplaceOptions, vm: &VirtualMachine) -> PyResult { - Ok(self.inner.replace(options, vm)?.into()) + fn title(&self) -> PyBytes { + self.inner.title().into() + } +} + +#[pyclass] +impl PyRef { + // These operations return a subslice, so equal lengths mean unchanged contents. + fn result_from_slice(&self, result: &[u8], vm: &VirtualMachine) -> Self { + if result.len() == self.as_bytes().len() && self.class().is(vm.ctx.types.bytes_type) { + self.clone() + } else { + vm.ctx.new_bytes(result.to_vec()) + } + } + + #[pymethod] + fn __getnewargs__(self, vm: &VirtualMachine) -> PyTupleRef { + vm.new_tuple((self.result_from_slice(self.as_bytes(), vm),)) } #[pymethod] - fn title(&self) -> PyBytes { - self.inner.title().into() + fn strip(self, options: ByteInnerStripOptions, vm: &VirtualMachine) -> Self { + self.result_from_slice(self.inner.strip(options.bytes), vm) } #[pymethod] - fn __getnewargs__(&self, vm: &VirtualMachine) -> PyTupleRef { - let param: Vec = self.elements().map(|x| x.to_pyobject(vm)).collect(); - PyTuple::new_ref(param, &vm.ctx) + fn removeprefix(self, prefix: PyBytesInner, vm: &VirtualMachine) -> Self { + self.result_from_slice(self.inner.removeprefix(prefix), vm) + } + + #[pymethod] + fn removesuffix(self, suffix: PyBytesInner, vm: &VirtualMachine) -> Self { + self.result_from_slice(self.inner.removesuffix(suffix), vm) + } + + #[pymethod] + fn replace(self, options: ByteInnerReplaceOptions, vm: &VirtualMachine) -> PyResult { + Ok(match self.inner.replace(options, vm)? { + alloc::borrow::Cow::Borrowed(result) => self.result_from_slice(result, vm), + alloc::borrow::Cow::Owned(result) => vm.ctx.new_bytes(result), + }) + } + + #[pymethod] + fn translate(self, options: ByteInnerTranslateOptions, vm: &VirtualMachine) -> PyResult { + let result = self.inner.translate(options, vm)?; + if self.class().is(vm.ctx.types.bytes_type) && result == self.as_bytes() { + Ok(self) + } else { + Ok(vm.ctx.new_bytes(result)) + } } -} -#[pyclass] -impl PyRef { #[pymethod] fn __bytes__(self, vm: &VirtualMachine) -> Self { - if self.is(vm.ctx.types.bytes_type) { + if self.class().is(vm.ctx.types.bytes_type) { self } else { PyBytes::from(self.payload.inner.clone()).into_ref(&vm.ctx) @@ -601,27 +625,17 @@ impl PyRef { #[pymethod] fn lstrip(self, options: ByteInnerStripOptions, vm: &VirtualMachine) -> Self { - let stripped = self.payload.inner.lstrip(options.bytes); - if stripped == self.as_bytes() { - self - } else { - vm.ctx.new_bytes(stripped.to_vec()) - } + self.result_from_slice(self.inner.lstrip(options.bytes), vm) } #[pymethod] fn rstrip(self, options: ByteInnerStripOptions, vm: &VirtualMachine) -> Self { - let stripped = self.payload.inner.rstrip(options.bytes); - if stripped == self.as_bytes() { - self - } else { - vm.ctx.new_bytes(stripped.to_vec()) - } + self.result_from_slice(self.inner.rstrip(options.bytes), vm) } // currently, only 'utf-8' and 'ascii' implemented #[pymethod] - fn decode(self, args: DecodeArgs, vm: &VirtualMachine) -> PyResult { + fn decode(self, args: TextCodecArgs, vm: &VirtualMachine) -> PyResult { bytes_decode(self.into(), args, vm) } } @@ -692,7 +706,7 @@ impl AsSequence for PyBytes { PyBytes::sequence_downcast(seq) .as_bytes() .getitem_by_index(vm, i) - .map(|x| vm.ctx.new_bytes(vec![x]).into()) + .map(|x| vm.ctx.new_int(x).into()) }), contains: atomic_func!(|seq, other, vm| { PyBytes::sequence_downcast(seq).__contains__(other.to_owned(), vm) @@ -754,7 +768,7 @@ impl Comparable for PyBytes { impl Iterable for PyBytes { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { Ok(PyBytesIterator { - internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), + internal: NativeSequenceIter::new(zelf, NativeIterKind::Sequence, 0), } .into_pyobject(vm)) } @@ -767,10 +781,10 @@ impl Representable for PyBytes { } } -#[pyclass(module = false, name = "bytes_iterator")] +#[pyclass(module = false, name = "bytes_iterator", traverse)] #[derive(Debug)] pub(crate) struct PyBytesIterator { - internal: PyMutex>, + internal: NativeSequenceIter, } impl PyPayload for PyBytesIterator { @@ -784,15 +798,15 @@ impl PyPayload for PyBytesIterator { impl Py { #[pymethod] fn __length_hint__(&self) -> usize { - self.internal.lock().length_hint(|obj| obj.as_bytes().len()) + self.internal.length_hint(|obj| obj.as_bytes().len()) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_iter(vm)?; - Ok(self.internal.lock().reduce( + Ok(self.internal.reduce( func, - |x| x.clone().into(), + |x| x.into(), |vm| vm.ctx.empty_tuple.clone().into(), vm, )) @@ -801,23 +815,19 @@ impl Py { #[pymethod] fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal - .lock() - .set_state(&object, |obj, pos| pos.min(obj.as_bytes().len()), vm) + .set_state(&object, |obj| obj.as_bytes().len(), vm) } } impl SelfIter for PyBytesIterator {} impl IterNext for PyBytesIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_next(&zelf.internal, |bytes, pos| { - Ok(PyIterReturn::from_result( - bytes - .as_bytes() - .get(pos) - .map(|&x| vm.new_pyobj(x)) - .ok_or(None), - )) - }) + let byte = zelf + .internal + .next(|bytes, pos| bytes.as_bytes().get(pos).copied()); + Ok(PyIterReturn::from_result( + byte.map(|byte| vm.new_pyobj(byte)).ok_or(None), + )) } } diff --git a/crates/vm/src/builtins/classmethod.rs b/crates/vm/src/builtins/classmethod.rs index 28e4b9ff32f..a32b4287293 100644 --- a/crates/vm/src/builtins/classmethod.rs +++ b/crates/vm/src/builtins/classmethod.rs @@ -59,16 +59,13 @@ impl Constructor for PyClassMethod { type Args = ClassMethodArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - // Validate the signature here, but defer storing the callable and - // copying its attributes to `__init__` so that subclasses overriding - // `__init__` without calling `super().__init__()` see `__func__` as - // `None`, matching CPython. - let _: ClassMethodArgs = args.bind_for(vm, Self::NAME)?; - let classmethod = Self { - callable: PyAtomicRef::from(vm.ctx.none()), - }; - let result = PyRef::new_ref(classmethod, cls, Some(vm.ctx.new_dict())); - Ok(PyObjectRef::from(result)) + let args: ClassMethodArgs = args.bind_for(vm, Self::NAME)?; + let result = Self { + callable: PyAtomicRef::from(args.function.clone()), + } + .into_ref_with_type(vm, cls)?; + functools_wraps(result.as_object(), &args.function, vm)?; + Ok(result.into()) } fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { @@ -80,9 +77,7 @@ impl Initializer for PyClassMethod { type Args = ClassMethodArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - let callable = args.function; - zelf.callable.store(callable.clone()); - functools_wraps(zelf.as_object(), &callable, vm) + descriptor_set_callable(zelf.as_object(), &zelf.callable, args.function, vm) } } @@ -95,7 +90,7 @@ impl PyClassMethod { #[pyclass( with(GetDescriptor, Constructor, Initializer, Representable), - flags(BASETYPE, HAS_DICT, HAS_WEAKREF) + flags(BASETYPE, HAS_DICT) )] impl Py { #[pygetset] @@ -143,21 +138,8 @@ impl Py { } #[pygetset] - fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef { - let callable = self.callable.load_owned(); - if let Ok(Some(is_abstract)) = vm.get_attribute_opt(&callable, "__isabstractmethod__") { - is_abstract - } else { - vm.ctx.new_bool(false).into() - } - } - - #[pygetset(setter)] - fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.callable - .load_owned() - .set_attr("__isabstractmethod__", value, vm)?; - Ok(()) + fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyResult { + self.callable.load_owned().is_abstract(vm) } #[pyclassmethod] @@ -252,3 +234,22 @@ pub(crate) fn descriptor_set_wrapped_attribute( PySetterValue::Assign(value) => dict.set_item(name, value, vm), } } + +// Both wrapper types publish the callable before metadata callbacks. A replaced +// callable's finalizer may reinitialize the descriptor, so reload after dropping it. +pub(crate) fn descriptor_set_callable( + wrapper: &PyObject, + slot: &PyAtomicRef, + callable: PyObjectRef, + vm: &VirtualMachine, +) -> PyResult<()> { + if slot.load_owned().is(&callable) { + return Ok(()); + } + drop(slot.store(callable.clone())); + let current = slot.load_owned(); + let result = functools_wraps(wrapper, ¤t, vm); + drop(current); + drop(callable); + result +} diff --git a/crates/vm/src/builtins/code.rs b/crates/vm/src/builtins/code.rs index 6cf1036ab11..86218bb8078 100644 --- a/crates/vm/src/builtins/code.rs +++ b/crates/vm/src/builtins/code.rs @@ -1,18 +1,24 @@ //! Infamous code object. The python class `code` +mod const_cache; + use super::descriptor::{MemberKind, MemberLayout}; use super::{PyBytesRef, PyStrRef, PyTupleRef, PyType, set::PyFrozenSet}; -use crate::common::lock::PyMutex; +use crate::common::lock::{OnceCell, PyMutex}; #[cfg(feature = "host_env")] use crate::convert::ToPyException; use crate::{ - AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, + VirtualMachine, builtins::PyStrInterned, bytecode::{self, BorrowedConstant, CodeFlags, Constant, ConstantBag, Instruction}, class::{PyClassImpl, StaticType}, convert::ToPyObject, frozen, - function::OptionalArg, + function::{ + ArgumentError, FromArgs, FuncArgs, KwArgs, NameChanges, OptionalArg, Param, PosArgs, + }, + object::{Traverse, TraverseFn}, types::{Comparable, Constructor, Hashable, Representable}, }; use alloc::fmt; @@ -23,6 +29,7 @@ use core::{ }; use malachite_bigint::BigInt; use num_traits::Zero; +use rustpython_common::wtf8::Wtf8Buf; use rustpython_compiler_core::{OneIndexed, bytecode::CodeUnits, bytecode::PyCodeLocationInfoKind}; /// State for iterating through code address ranges @@ -141,44 +148,77 @@ impl<'a> PyCodeAddressRange<'a> { } } +#[derive(Clone, Copy)] +struct CodeInt(i32); + +impl TryFromObject for CodeInt { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let value = obj.try_index(vm)?; + i32::try_from(value.as_bigint()) + .map(Self) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C int")) + } +} + +// Keep the caller's objects alive while derived conversion consumes its copy. +// An early __index__ argument must survive later conversions and the audit hook. +pub struct CodeArgs { + values: T, + _owners: FuncArgs, +} + +impl FromArgs for CodeArgs { + const PARAMS: Option<&'static [Param]> = T::PARAMS; + const BINDING_PARAMS: Option<&'static [Param]> = T::BINDING_PARAMS; + + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + let owners = args.clone(); + let values = T::from_args(vm, args)?; + Ok(Self { + values, + _owners: owners, + }) + } +} + #[derive(FromArgs)] -pub struct ReplaceArgs { +struct ReplaceArgs { #[pyarg(named, optional)] - co_posonlyargcount: OptionalArg, + co_argcount: OptionalArg, #[pyarg(named, optional)] - co_argcount: OptionalArg, + co_posonlyargcount: OptionalArg, #[pyarg(named, optional)] - co_kwonlyargcount: OptionalArg, + co_kwonlyargcount: OptionalArg, #[pyarg(named, optional)] - co_filename: OptionalArg, + co_nlocals: OptionalArg, #[pyarg(named, optional)] - co_firstlineno: OptionalArg, + co_stacksize: OptionalArg, #[pyarg(named, optional)] - co_consts: OptionalArg>, + co_flags: OptionalArg, #[pyarg(named, optional)] - co_name: OptionalArg, + co_firstlineno: OptionalArg, #[pyarg(named, optional)] - co_names: OptionalArg>, + co_code: OptionalArg, #[pyarg(named, optional)] - co_flags: OptionalArg, + co_consts: OptionalArg, #[pyarg(named, optional)] - co_varnames: OptionalArg>, + co_names: OptionalArg, #[pyarg(named, optional)] - co_nlocals: OptionalArg, + co_varnames: OptionalArg, #[pyarg(named, optional)] - co_stacksize: OptionalArg, + co_freevars: OptionalArg, #[pyarg(named, optional)] - co_code: OptionalArg, + co_cellvars: OptionalArg, #[pyarg(named, optional)] - co_linetable: OptionalArg, + co_filename: OptionalArg, #[pyarg(named, optional)] - co_exceptiontable: OptionalArg, + co_name: OptionalArg, #[pyarg(named, optional)] - co_freevars: OptionalArg>, + co_qualname: OptionalArg, #[pyarg(named, optional)] - co_cellvars: OptionalArg>, + co_linetable: OptionalArg, #[pyarg(named, optional)] - co_qualname: OptionalArg, + co_exceptiontable: OptionalArg, } #[derive(Clone)] @@ -256,7 +296,34 @@ fn borrow_obj_constant(obj: &PyObject) -> BorrowedConstant<'_, Literal> { }) } +/// `co_consts` viewed as constants. +#[derive(Clone)] +pub struct LiteralTuple(PyTupleRef); + +impl LiteralTuple { + pub const fn as_pytuple(&self) -> &PyTupleRef { + &self.0 + } +} + +impl Deref for LiteralTuple { + type Target = [Literal]; + + fn deref(&self) -> &[Literal] { + let elements = self.0.as_slice(); + // SAFETY: Literal is repr(transparent) over PyObjectRef. + unsafe { &*(elements as *const [PyObjectRef] as *const [Literal]) } + } +} + +impl FromIterator for LiteralTuple { + fn from_iter>(iter: T) -> Self { + Self(Context::genesis().new_tuple(iter.into_iter().map(|c| c.0).collect())) + } +} + impl Constant for Literal { + type Tuple = LiteralTuple; type Name = &'static PyStrInterned; fn borrow_constant(&self) -> BorrowedConstant<'_, Self> { borrow_obj_constant(&self.0) @@ -357,6 +424,15 @@ pub(crate) type CodeObject = bytecode::CodeObject; pub trait IntoCodeObject { fn into_code_object(self, vm: &VirtualMachine) -> CodeObject; + + fn into_pycode(self, vm: &VirtualMachine) -> PyCode + where + Self: Sized, + { + let mut code = PyCode::new(self.into_code_object(vm), &vm.ctx); + code.apply_debug_ranges(vm); + code + } } impl IntoCodeObject for CodeObject { @@ -367,7 +443,11 @@ impl IntoCodeObject for CodeObject { impl IntoCodeObject for bytecode::CodeObject { fn into_code_object(self, vm: &VirtualMachine) -> CodeObject { - self.map_bag(PyVmBag(vm)) + const_cache::into_code_object(self, vm) + } + + fn into_pycode(self, vm: &VirtualMachine) -> PyCode { + const_cache::into_pycode(self, vm) } } @@ -389,20 +469,56 @@ pub struct CoMonitoringData { pub per_instruction_opcodes: Vec, } -#[pyclass(module = false, name = "code")] +impl CoMonitoringData { + fn original_opcode(&self, i: usize, op: Instruction) -> Instruction { + let op = match op { + Instruction::InstrumentedLine => Instruction::try_from(self.line_opcodes[i]) + .expect("INSTRUMENTED_LINE without original opcode"), + op => op, + }; + match op { + Instruction::InstrumentedInstruction => { + Instruction::try_from(self.per_instruction_opcodes[i]) + .expect("INSTRUMENTED_INSTRUCTION without original opcode") + } + op => op, + } + } +} + +/// `_PyCoCached`: objects created on first use. +#[derive(Default)] +struct CoCached { + code: OnceCell, + varnames: OnceCell, + cellvars: OnceCell, + freevars: OnceCell, +} + +#[pyclass(module = false, name = "code", traverse = "manual", clear = false)] pub struct PyCode { #[pymember(name = "co_argcount", path = "arg_count")] #[pymember(name = "co_posonlyargcount", path = "posonlyarg_count")] #[pymember(name = "co_kwonlyargcount", path = "kwonlyarg_count")] #[pymember(name = "co_stacksize", path = "max_stackdepth")] - #[pymember(name = "co_name", path = "obj_name")] - #[pymember(name = "co_qualname", path = "qualname")] #[pymember(name = "co_flags", path = "flags")] pub code: CodeObject, /// Slot-indexed names, equivalent to CPython's `co_localsplusnames`. /// Derived once so frame-local proxy operations do not repeatedly scan /// merged cell variables. localsplus_names: Box<[&'static PyStrInterned]>, + pub(crate) co_name: PyStrRef, + #[pymember(name = "co_qualname")] + qualified_name: PyStrRef, + pub(crate) co_names: PyTupleRef, + pub(crate) co_localsplusnames: PyTupleRef, + pub(crate) co_localspluskinds: PyBytesRef, + pub(crate) co_linetable: PyBytesRef, + pub(crate) co_exceptiontable: PyBytesRef, + co_cached: CoCached, + /// `_co_firsttraceable`: the index of the first `RESUME` that does not + /// start a generator expression, or the code length if there is none. + pub(crate) first_traceable: usize, #[pymember(name = "co_filename")] source_path: AtomicPtr, #[pymember(name = "co_nlocals")] @@ -421,6 +537,34 @@ pub struct PyCode { pub has_exc_handling: bool, } +// SAFETY: Visit each owned reference once, including initialized cache cells. +// Constant elements belong to the constants tuple and are not direct edges. +// Interned names and source paths are borrowed static references. +unsafe impl Traverse for PyCode { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.co_consts().traverse(tracer); + self.co_name.traverse(tracer); + self.qualified_name.traverse(tracer); + self.co_names.traverse(tracer); + self.co_localsplusnames.traverse(tracer); + self.co_localspluskinds.traverse(tracer); + self.co_linetable.traverse(tracer); + self.co_exceptiontable.traverse(tracer); + if let Some(value) = self.co_cached.code.get() { + value.traverse(tracer); + } + if let Some(value) = self.co_cached.varnames.get() { + value.traverse(tracer); + } + if let Some(value) = self.co_cached.cellvars.get() { + value.traverse(tracer); + } + if let Some(value) = self.co_cached.freevars.get() { + value.traverse(tracer); + } + } +} + impl Deref for PyCode { type Target = CodeObject; fn deref(&self) -> &Self::Target { @@ -506,12 +650,17 @@ fn build_localspluskinds( Ok(kinds.into_boxed_slice()) } +fn holds_names(tuple: &super::PyTuple, names: &[&'static PyStrInterned]) -> bool { + tuple.len() == names.len() && tuple.iter().zip(names).all(|(item, name)| item.is(*name)) +} + impl MemberLayout for CodeFlags { const KIND: MemberKind = MemberKind::Int; } impl PyCode { - pub fn new(code: CodeObject) -> Self { + pub fn new(mut code: CodeObject, ctx: &Context) -> Self { + code.instructions.fixup_get_iter(code.flags); let sp = code.source_path as *const PyStrInterned as *mut PyStrInterned; let nlocals = i32::try_from(code.varnames.len()).unwrap_or(i32::MAX); let localsplus_names = { @@ -547,7 +696,28 @@ impl PyCode { | Instruction::InstrumentedEndAsyncFor ) }); + let first_traceable = code + .instructions + .iter() + .position(|unit| { + matches!(unit.op, Instruction::Resume { .. }) + && u32::from(u8::from(unit.arg)) & bytecode::oparg::ResumeContext::LOCATION_MASK + != bytecode::oparg::ResumeLocation::AtGenExprStart.as_u32() + }) + .unwrap_or(code.instructions.len()); + let names_tuple = |names: &[&'static PyStrInterned]| { + ctx.new_tuple(names.iter().map(|name| name.to_object()).collect()) + }; Self { + first_traceable, + co_name: code.obj_name.to_owned(), + qualified_name: code.qualname.to_owned(), + co_names: names_tuple(code.names.as_slice()), + co_localsplusnames: names_tuple(&localsplus_names), + co_localspluskinds: ctx.new_bytes(code.localspluskinds.to_vec()), + co_linetable: ctx.new_bytes(code.linetable.to_vec()), + co_exceptiontable: ctx.new_bytes(code.exceptiontable.to_vec()), + co_cached: CoCached::default(), code, localsplus_names, source_path: AtomicPtr::new(sp), @@ -559,6 +729,59 @@ impl PyCode { } } + /// The code object `r_object` creates from a TYPE_CODE record. It keeps + /// the objects read for the object-valued fields. + pub(crate) fn from_marshal( + mut code: CodeObject, + fields: rustpython_compiler_core::marshal::CodeFields, + ctx: &Context, + ) -> Result { + use rustpython_compiler_core::marshal::MarshalError; + fn downcast(obj: PyObjectRef) -> Result, MarshalError> { + obj.downcast().map_err(|_| MarshalError::BadType) + } + code.constants = bytecode::Constants::new(LiteralTuple(downcast(fields.consts)?)); + // The compiler's string conversion is lossy for surrogates; retain the + // decoded value and apply code construction's exact-string interning. + let qualname = downcast::(fields.qualname)?; + code.qualname = ctx.intern_str(qualname.as_wtf8()); + let mut code = Self::new(code, ctx); + code.set_names(downcast(fields.names)?); + code.set_localsplusnames(downcast(fields.localsplusnames)?); + code.co_localspluskinds = downcast(fields.localspluskinds)?; + code.co_linetable = downcast(fields.linetable)?; + code.co_exceptiontable = downcast(fields.exceptiontable)?; + Ok(code) + } + + /// Keep `names` as `co_names` when it holds the interned names, the way + /// `intern_strings` interns a names tuple in place. + fn set_names(&mut self, names: PyTupleRef) { + if holds_names(&names, self.code.names.as_slice()) { + self.co_names = names; + } + } + + /// Keep `localsplusnames` as `co_localsplusnames`; see [`Self::set_names`]. + fn set_localsplusnames(&mut self, localsplusnames: PyTupleRef) { + if holds_names(&localsplusnames, &self.localsplus_names) { + self.co_localsplusnames = localsplusnames; + } + } + + pub(crate) fn apply_debug_ranges(&mut self, vm: &VirtualMachine) { + if !vm.state.config.settings.code_debug_ranges + && let Some(linetable) = remove_column_info(&self.code.linetable) + { + self.code.linetable = linetable; + self.co_linetable = vm.ctx.new_bytes(self.code.linetable.to_vec()); + } + } + + pub(crate) fn co_qualname(&self) -> PyStrRef { + self.qualified_name.clone() + } + #[inline(always)] pub(crate) fn localsplus_name(&self, index: usize) -> &'static PyStrInterned { // Bytecode operands and frame-proxy indices are validated against @@ -567,6 +790,29 @@ impl PyCode { self.localsplus_names[index] } + pub(crate) fn co_consts(&self) -> &PyTupleRef { + self.code.constants.as_tuple().as_pytuple() + } + + /// `_PyCode_GetCode` + pub(crate) fn get_code(&self, vm: &VirtualMachine) -> PyBytesRef { + self.co_cached + .code + .get_or_init(|| vm.ctx.new_bytes(self.deopt_code())) + .clone() + } + + /// `deopt_code`: the instructions with each opcode replaced by its base + /// opcode (`_Py_GetBaseCodeUnit`) and the inline caches zeroed. + fn deopt_code(&self) -> Vec { + let monitoring_data = self.monitoring_data.lock(); + self.code.instructions.original_bytes_with(|i, op| { + monitoring_data + .as_ref() + .map_or(op, |data| data.original_opcode(i, op)) + }) + } + pub fn source_path(&self) -> &'static PyStrInterned { // SAFETY: always points to a valid &'static PyStrInterned (interned strings are never deallocated) unsafe { &*self.source_path.load(Ordering::Relaxed) } @@ -580,11 +826,17 @@ impl PyCode { } pub fn new_ref_with_bag(vm: &VirtualMachine, code: CodeObject) -> PyRef { - PyRef::new_ref(Self::new(code), vm.ctx.types.code_type.to_owned(), None) + let mut code = Self::new(code, &vm.ctx); + code.apply_debug_ranges(vm); + PyRef::new_ref(code, vm.ctx.types.code_type.to_owned(), None) } pub fn new_ref_from_bytecode(vm: &VirtualMachine, code: bytecode::CodeObject) -> PyRef { - Self::new_ref_with_bag(vm, code.map_bag(PyVmBag(vm))) + PyRef::new_ref( + code.into_pycode(vm), + vm.ctx.types.code_type.to_owned(), + None, + ) } pub fn new_ref_from_frozen>( @@ -650,13 +902,13 @@ fn frozen_co_filename(path: &str) -> Option<&'static str> { } fn apply_frozen_co_filename(code: &PyCode, vm: &VirtualMachine) { - let Some(new) = frozen_co_filename(code.source_path().as_str()) else { + let Some(new) = code.source_path().to_str().and_then(frozen_co_filename) else { return; }; set_source_path_tree(code, vm.ctx.intern_str(new)); } -fn set_source_path_tree(code: &PyCode, interned: &'static PyStrInterned) { +pub(crate) fn set_source_path_tree(code: &PyCode, interned: &'static PyStrInterned) { code.set_source_path(interned); for constant in code.constants.iter() { set_source_path_in_const(&constant.0, interned); @@ -709,18 +961,94 @@ impl PyPayload for PyCode { impl Representable for PyCode { #[inline] - fn repr_str(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + fn repr_wtf8(zelf: &Py, _vm: &VirtualMachine) -> PyResult { let code = &zelf.code; - Ok(format!( - "", + let mut repr = Wtf8Buf::from(format!( + "", code.first_line_number.map_or(-1, |n| n.get() as i32) - )) + )); + Ok(repr) } } +/// `_PyCode_ConstantKey` +pub(crate) fn constant_key(op: &PyObject, vm: &VirtualMachine) -> PyResult { + use super::{PyBool, PyBytes, PyComplex, PyFloat, PyInt, PySlice, PyStr, PyTuple}; + + let ctx = &vm.ctx; + let class = op.class(); + let pair = |first: PyObjectRef| ctx.new_tuple(vec![first, op.to_owned()]).into(); + let triple = |tag: PyObjectRef| { + ctx.new_tuple(vec![class.to_owned().into(), op.to_owned(), tag]) + .into() + }; + let is_neg_zero = |d: f64| d == 0.0 && d.is_sign_negative(); + + let key = if vm.is_none(op) + || op.is(&ctx.ellipsis) + || class.is(PyInt::static_type()) + || class.is(PyStr::static_type()) + || op.downcast_ref::().is_some() + { + // Objects of these types are always different from object of other + // type and from tuples. + op.to_owned() + } else if class.is(PyBool::static_type()) || class.is(PyBytes::static_type()) { + // Make booleans different from integers 0 and 1. + pair(class.to_owned().into()) + } else if let Some(float) = op.downcast_ref_if_exact::(vm) { + if is_neg_zero(float.to_f64()) { + triple(ctx.none()) + } else { + pair(class.to_owned().into()) + } + } else if let Some(complex) = op.downcast_ref_if_exact::(vm) { + // All four complex zeros must be distinguished. + let z = complex.to_complex(); + match (is_neg_zero(z.re), is_neg_zero(z.im)) { + (true, true) => triple(ctx.new_bool(true).into()), + (false, true) => triple(ctx.new_bool(false).into()), + (true, false) => triple(ctx.none()), + (false, false) => pair(class.to_owned().into()), + } + } else if let Some(tuple) = op.downcast_ref_if_exact::(vm) { + let keys = tuple + .iter() + .map(|item| constant_key(item, vm)) + .collect::>()?; + pair(ctx.new_tuple(keys).into()) + } else if let Some(set) = op.downcast_ref_if_exact::(vm) { + let keys = set + .elements() + .iter() + .map(|item| constant_key(item, vm)) + .collect::>>()?; + pair(PyFrozenSet::from_iter(vm, keys)?.into_ref(ctx).into()) + } else if let Some(slice) = op.downcast_ref::() { + let key = |item: Option<&PyObjectRef>| match item { + Some(item) => constant_key(item, vm), + None => Ok(ctx.none()), + }; + let slice_key = PySlice { + start: Some(key(slice.start.as_ref())?), + stop: key(Some(&slice.stop))?, + step: Some(key(slice.step.as_ref())?), + }; + pair(slice_key.into_ref(ctx).into()) + } else { + // For other types, use the object identifier as a unique identifier + // to ensure that they are seen as unequal. + pair(ctx.new_int(op.get_id()).into()) + }; + Ok(key) +} + impl Comparable for PyCode { fn cmp( zelf: &Py, @@ -732,35 +1060,36 @@ impl Comparable for PyCode { let other = class_or_notimplemented!(Self, other); let a = &zelf.code; let b = &other.code; - let eq = a.obj_name == b.obj_name + let eq = vm.bool_eq(zelf.co_name.as_object(), other.co_name.as_object())? && a.arg_count == b.arg_count && a.posonlyarg_count == b.posonlyarg_count && a.kwonlyarg_count == b.kwonlyarg_count && a.flags == b.flags && a.first_line_number == b.first_line_number - && a.instructions.original_bytes() == b.instructions.original_bytes() - && a.linetable == b.linetable - && a.exceptiontable == b.exceptiontable - && a.names == b.names - && a.varnames == b.varnames - && a.freevars == b.freevars - && a.cellvars == b.cellvars + && a.instructions.len() == b.instructions.len() + && zelf.get_code(vm).as_bytes() == other.get_code(vm).as_bytes() && { - let a_consts: Vec<_> = a.constants.iter().map(|c| c.0.clone()).collect(); - let b_consts: Vec<_> = b.constants.iter().map(|c| c.0.clone()).collect(); - if a_consts.len() != b_consts.len() { - false - } else { - let mut eq = true; - for (ac, bc) in a_consts.iter().zip(b_consts.iter()) { - if !vm.bool_eq(ac, bc)? { - eq = false; - break; - } - } - eq - } - }; + let left = constant_key(Self::co_consts(zelf).as_object(), vm)?; + let right = constant_key(Self::co_consts(other).as_object(), vm)?; + let eq = vm.bool_eq(&left, &right); + // Release both temporary keys in comparison order, including + // on errors, before comparing the remaining code fields. + drop(left); + eq? + } + && vm.bool_eq(zelf.co_names.as_object(), other.co_names.as_object())? + && vm.bool_eq( + zelf.co_localsplusnames.as_object(), + other.co_localsplusnames.as_object(), + )? + && vm.bool_eq( + zelf.co_linetable.as_object(), + other.co_linetable.as_object(), + )? + && vm.bool_eq( + zelf.co_exceptiontable.as_object(), + other.co_exceptiontable.as_object(), + )?; Ok(eq.into()) }) } @@ -768,156 +1097,222 @@ impl Comparable for PyCode { impl Hashable for PyCode { fn hash(zelf: &Py, vm: &VirtualMachine) -> PyResult { + use crate::common::hash::{self, PyHash, PyUHash}; + let code = &zelf.code; - // Hash a tuple of key attributes, matching CPython's code_hash - let tuple = vm.ctx.new_tuple(vec![ - vm.ctx.new_str(code.obj_name.as_str()).into(), - vm.ctx.new_int(code.arg_count).into(), - vm.ctx.new_int(code.posonlyarg_count).into(), - vm.ctx.new_int(code.kwonlyarg_count).into(), - vm.ctx.new_int(code.varnames.len()).into(), - vm.ctx.new_int(code.flags.bits()).into(), - vm.ctx - .new_int(code.first_line_number.map_or(0, |n| n.get()) as i64) - .into(), - vm.ctx.new_bytes(code.instructions.original_bytes()).into(), - { - let consts: Vec<_> = code.constants.iter().map(|c| c.0.clone()).collect(); - vm.ctx.new_tuple(consts).into() - }, - ]); - tuple.as_object().hash(vm) + let mut hash: PyUHash = 20_221_211; + let mut scramble = |value: PyUHash| { + hash = (hash ^ value).wrapping_mul(hash::MULTIPLIER as PyUHash); + }; + + // Hash the retained Python objects in code_hash order: subclass hooks + // and exceptions must be observed before reading the instruction stream. + for field in [ + zelf.co_name.as_object(), + Self::co_consts(zelf).as_object(), + zelf.co_names.as_object(), + zelf.co_localsplusnames.as_object(), + zelf.co_linetable.as_object(), + zelf.co_exceptiontable.as_object(), + ] { + scramble(field.hash(vm)? as PyUHash); + } + for value in [ + code.arg_count as PyUHash, + code.posonlyarg_count as PyUHash, + code.kwonlyarg_count as PyUHash, + code.flags.bits() as PyUHash, + code.first_line_number.map_or(0, |n| n.get()) as PyUHash, + code.instructions.len() as PyUHash, + ] { + scramble(value); + } + + // Share co_code's original instruction and cache traversal, without hashing + // adaptive counters or holding the monitoring lock across Python calls. + let monitoring_data = zelf.monitoring_data.lock(); + let instructions = code.instructions.original_instructions_with(|i, op| { + monitoring_data + .as_ref() + .map_or(op, |data| data.original_opcode(i, op)) + }); + for unit in instructions { + scramble(u8::from(unit.op) as PyUHash); + scramble(u8::from(unit.arg) as PyUHash); + } + Ok(hash::fix_sentinel(hash as PyHash)) } } // Arguments for code object constructor #[derive(FromArgs)] pub struct PyCodeNewArgs { - argcount: u32, - posonlyargcount: u32, - kwonlyargcount: u32, - nlocals: u32, - stacksize: u32, - flags: u32, + #[pyarg(positional)] + argcount: CodeInt, + #[pyarg(positional)] + posonlyargcount: CodeInt, + #[pyarg(positional)] + kwonlyargcount: CodeInt, + #[pyarg(positional)] + nlocals: CodeInt, + #[pyarg(positional)] + stacksize: CodeInt, + #[pyarg(positional)] + flags: CodeInt, + #[pyarg(positional)] + codestring: PyBytesRef, + #[pyarg(positional)] + constants: PyTupleRef, + #[pyarg(positional)] + names: PyTupleRef, + #[pyarg(positional)] + varnames: PyTupleRef, + #[pyarg(positional)] + filename: PyStrRef, + #[pyarg(positional)] + name: PyStrRef, + #[pyarg(positional)] + qualname: PyStrRef, + #[pyarg(positional)] + firstlineno: CodeInt, + #[pyarg(positional)] + linetable: PyBytesRef, + #[pyarg(positional)] + exceptiontable: PyBytesRef, + #[pyarg(positional, optional, py_default = "()")] + freevars: OptionalArg, + #[pyarg(positional, optional, py_default = "()")] + cellvars: OptionalArg, +} + +struct CodeConstructor { + argcount: i32, + posonlyargcount: i32, + kwonlyargcount: i32, + nlocals: i32, + stacksize: i32, + flags: i32, co_code: PyBytesRef, consts: PyTupleRef, names: PyTupleRef, varnames: PyTupleRef, + freevars: PyTupleRef, + cellvars: PyTupleRef, filename: PyStrRef, name: PyStrRef, qualname: PyStrRef, firstlineno: i32, linetable: PyBytesRef, exceptiontable: PyBytesRef, - freevars: PyTupleRef, - cellvars: PyTupleRef, } -impl Constructor for PyCode { - type Args = PyCodeNewArgs; - - fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - // Convert names tuple to vector of interned strings - let names: Box<[&'static PyStrInterned]> = args - .names - .as_slice() - .iter() - .map(|obj| { - let s = obj - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("names must be tuple of strings"))?; - Ok(vm.ctx.intern_str(s.as_wtf8())) - }) - .collect::>>()? - .into_boxed_slice(); - - let varnames: Box<[&'static PyStrInterned]> = args - .varnames - .as_slice() - .iter() - .map(|obj| { - let s = obj - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("varnames must be tuple of strings"))?; - Ok(vm.ctx.intern_str(s.as_wtf8())) +fn copy_name_tuple(tuple: &super::PyTuple, vm: &VirtualMachine) -> PyResult { + let values = tuple + .as_slice() + .iter() + .map(|obj| { + let string = obj.downcast_ref::().ok_or_else(|| { + let class = obj.class(); + let name = class.slot_name(); + let name = &name[..name.floor_char_boundary(500)]; + vm.new_type_error(format!( + "name tuples must contain only strings, not '{name}'" + )) + })?; + Ok(if obj.class().is(vm.ctx.types.str_type) { + obj.clone() + } else { + vm.ctx.new_str(string.as_wtf8()).into() }) - .collect::>>()? - .into_boxed_slice(); + }) + .collect::>>()?; + Ok(vm.ctx.new_tuple(values)) +} - let cellvars: Box<[&'static PyStrInterned]> = args - .cellvars - .as_slice() - .iter() - .map(|obj| { - let s = obj - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("cellvars must be tuple of strings"))?; - Ok(vm.ctx.intern_str(s.as_wtf8())) - }) - .collect::>>()? - .into_boxed_slice(); +fn intern_name_tuple( + tuple: &super::PyTuple, + vm: &VirtualMachine, +) -> PyResult> { + // CPython's intern_strings works backwards and requires exact strings. + let mut names = tuple + .as_slice() + .iter() + .rev() + .map(|obj| { + let string = obj + .downcast_ref_if_exact::(vm) + .ok_or_else(|| vm.new_system_error("non-string found in code slot"))?; + Ok(vm.ctx.intern_str(string.as_wtf8())) + }) + .collect::>>()?; + names.reverse(); + Ok(names.into_boxed_slice()) +} - let freevars: Box<[&'static PyStrInterned]> = args - .freevars - .as_slice() - .iter() - .map(|obj| { - let s = obj - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("freevars must be tuple of strings"))?; - Ok(vm.ctx.intern_str(s.as_wtf8())) - }) - .collect::>>()? - .into_boxed_slice(); +fn audit_code_new( + code: &PyBytesRef, + filename: &PyStrRef, + name: &PyStrRef, + integers: [i32; 6], + vm: &VirtualMachine, +) -> PyResult<()> { + vm.audit("code.__new__", || { + let mut values = vec![ + code.clone().into(), + filename.clone().into(), + name.clone().into(), + ]; + values.extend(integers.map(|value| value.to_pyobject(vm))); + PosArgs::new(values) + }) +} - // Check nlocals matches varnames length - if args.nlocals as usize != varnames.len() { - return Err(vm.new_value_error(format!( - "nlocals ({}) != len(varnames) ({})", - args.nlocals, - varnames.len() - ))); +impl CodeConstructor { + fn build(&self, previous: Option<&CodeObject>, vm: &VirtualMachine) -> PyResult { + if self.argcount < self.posonlyargcount + || self.posonlyargcount < 0 + || self.kwonlyargcount < 0 + || self.stacksize < 0 + || self.flags < 0 + { + return Err(vm.new_system_error("bad argument to internal function")); } - - // Parse and validate bytecode from bytes - let bytecode_bytes = args.co_code.as_bytes(); - let instructions = CodeUnits::try_from(bytecode_bytes) + let bytecode = self.co_code.as_bytes(); + if bytecode.len() > i32::MAX as usize { + return Err(vm.new_overflow_error("code: co_code larger than INT_MAX")); + } + if !bytecode.len().is_multiple_of(2) { + return Err(vm.new_value_error("code: co_code is malformed")); + } + let instructions = CodeUnits::try_from(bytecode) .map_err(|e| vm.new_value_error(format!("invalid bytecode: {e}")))?; + let flags = CodeFlags::from_bits_retain(self.flags as u32); + let nargs = self.argcount as u64 + + self.kwonlyargcount as u64 + + u64::from(flags.contains(CodeFlags::VARARGS)) + + u64::from(flags.contains(CodeFlags::VARKEYWORDS)); + if (self.varnames.len() as u64) < nargs { + return Err(vm.new_value_error("code: co_varnames is too small")); + } + if self.nlocals as usize != self.varnames.len() { + return Err(vm.new_value_error("code: co_nlocals != len(co_varnames)")); + } - // Convert constants - let constants = args - .consts - .as_slice() - .iter() - .map(|obj| { - // Convert PyObject to Literal constant. For now, just wrap it - Literal(obj.clone()) - }) - .collect(); - - // Create locations (start and end pairs) - let row = if args.firstlineno > 0 { - OneIndexed::new(args.firstlineno as usize).unwrap_or(OneIndexed::MIN) - } else { - OneIndexed::MIN - }; - let loc = rustpython_compiler_core::SourceLocation { - line: row, - character_offset: OneIndexed::from_zero_indexed(0), - }; - let locations: Box< - [( - rustpython_compiler_core::SourceLocation, - rustpython_compiler_core::SourceLocation, - )], - > = vec![(loc, loc); instructions.len()].into_boxed_slice(); - - let flags = CodeFlags::from_bits_truncate(args.flags); + // Constructor inputs have already been copied to exact strings; + // replace inputs reach this check only after structural validation. + let names = intern_name_tuple(&self.names, vm)?; + let varnames = intern_name_tuple(&self.varnames, vm)?; + let cellvars = intern_name_tuple(&self.cellvars, vm)?; + let freevars = intern_name_tuple(&self.freevars, vm)?; let localspluskinds = build_localspluskinds( &varnames, &cellvars, &freevars, - (args.posonlyargcount, args.argcount, args.kwonlyargcount), + ( + self.posonlyargcount as u32, + self.argcount as u32, + self.kwonlyargcount as u32, + ), flags, &instructions, ) @@ -926,36 +1321,118 @@ impl Constructor for PyCode { "code: LOAD_FAST_AND_CLEAR oparg {index} out of range" )) })?; - - // Build the CodeObject + let first_line_number = if self.firstlineno > 0 { + OneIndexed::new(self.firstlineno as usize) + } else { + None + }; + let locations = if let Some(previous) = previous { + // FIXME: invalid locations. Actually locations is a duplication of linetable. + // It can be removed once we move every other code to use linetable only. + previous.locations.clone() + } else { + let loc = rustpython_compiler_core::SourceLocation { + line: first_line_number.unwrap_or(OneIndexed::MIN), + character_offset: OneIndexed::from_zero_indexed(0), + }; + vec![(loc, loc); instructions.len()].into_boxed_slice() + }; let code = CodeObject { instructions, locations, flags, - posonlyarg_count: args.posonlyargcount, - arg_count: args.argcount, - kwonlyarg_count: args.kwonlyargcount, - source_path: vm.ctx.intern_str(args.filename.as_wtf8()), - first_line_number: if args.firstlineno > 0 { - OneIndexed::new(args.firstlineno as usize) - } else { - None - }, + posonlyarg_count: self.posonlyargcount as u32, + arg_count: self.argcount as u32, + kwonlyarg_count: self.kwonlyargcount as u32, + source_path: vm.ctx.intern_str(self.filename.as_wtf8()), + first_line_number, // Room for one value is always reserved, even where nothing is pushed. - max_stackdepth: args.stacksize.max(1), - obj_name: vm.ctx.intern_str(args.name.as_wtf8()), - qualname: vm.ctx.intern_str(args.qualname.as_wtf8()), - constants, - names, + max_stackdepth: self.stacksize.max(1) as u32, + obj_name: vm.ctx.intern_str(self.name.as_wtf8()), + qualname: vm.ctx.intern_str(self.qualname.as_wtf8()), + constants: bytecode::Constants::new(LiteralTuple(self.consts.clone())), + names: names.into(), varnames, cellvars, freevars, localspluskinds, - linetable: args.linetable.as_bytes().to_vec().into_boxed_slice(), - exceptiontable: args.exceptiontable.as_bytes().to_vec().into_boxed_slice(), + linetable: self.linetable.as_bytes().into(), + exceptiontable: self.exceptiontable.as_bytes().into(), }; + let mut code = PyCode::new(code, &vm.ctx); + code.co_name = self.name.clone(); + if !self.qualname.class().is(vm.ctx.types.str_type) { + code.qualified_name = self.qualname.clone(); + } + code.set_names(self.names.clone()); + code.co_linetable = self.linetable.clone(); + code.co_exceptiontable = self.exceptiontable.clone(); + code.apply_debug_ranges(vm); + Ok(code) + } +} - Ok(Self::new(code)) +impl Constructor for PyCode { + type Args = CodeArgs; + + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + let CodeArgs { + values: args, + _owners, + } = args; + let mut constructor = CodeConstructor { + argcount: args.argcount.0, + posonlyargcount: args.posonlyargcount.0, + kwonlyargcount: args.kwonlyargcount.0, + nlocals: args.nlocals.0, + stacksize: args.stacksize.0, + flags: args.flags.0, + co_code: args.codestring, + consts: args.constants, + names: args.names, + varnames: args.varnames, + freevars: args + .freevars + .unwrap_or_else(|| vm.ctx.new_tuple(Vec::new())), + cellvars: args + .cellvars + .unwrap_or_else(|| vm.ctx.new_tuple(Vec::new())), + filename: args.filename, + name: args.name, + qualname: args.qualname, + firstlineno: args.firstlineno.0, + linetable: args.linetable, + exceptiontable: args.exceptiontable, + }; + audit_code_new( + &constructor.co_code, + &constructor.filename, + &constructor.name, + [ + constructor.argcount, + constructor.posonlyargcount, + constructor.kwonlyargcount, + constructor.nlocals, + constructor.stacksize, + constructor.flags, + ], + vm, + )?; + for (name, value) in [ + ("argcount", constructor.argcount), + ("posonlyargcount", constructor.posonlyargcount), + ("kwonlyargcount", constructor.kwonlyargcount), + ("nlocals", constructor.nlocals), + ] { + if value < 0 { + return Err(vm.new_value_error(format!("code: {name} must not be negative"))); + } + } + constructor.names = copy_name_tuple(&constructor.names, vm)?; + constructor.varnames = copy_name_tuple(&constructor.varnames, vm)?; + constructor.freevars = copy_name_tuple(&constructor.freevars, vm)?; + constructor.cellvars = copy_name_tuple(&constructor.cellvars, vm)?; + constructor.build(None, vm) } } @@ -973,12 +1450,13 @@ impl PyCode { impl Py { #[pygetset] pub fn co_cellvars(&self, vm: &VirtualMachine) -> PyTupleRef { - let cellvars = self + self.co_cached .cellvars - .iter() - .map(|name| name.to_pyobject(vm)) - .collect(); - vm.ctx.new_tuple(cellvars) + .get_or_init(|| { + vm.ctx + .new_tuple(self.cellvars.iter().map(|name| name.to_object()).collect()) + }) + .clone() } #[pygetset] @@ -987,36 +1465,43 @@ impl Py { } #[pygetset] - fn co_consts(&self, vm: &VirtualMachine) -> PyTupleRef { - let consts = self.code.constants.iter().map(|x| x.0.clone()).collect(); - vm.ctx.new_tuple(consts) + fn co_name(&self) -> PyStrRef { + self.co_name.clone() } #[pygetset] - fn co_names(&self, vm: &VirtualMachine) -> PyTupleRef { - let names = self - .code - .names - .deref() - .iter() - .map(|name| name.to_pyobject(vm)) - .collect(); - vm.ctx.new_tuple(names) + fn co_consts(&self) -> PyTupleRef { + PyCode::co_consts(self).clone() + } + + #[pygetset] + fn co_names(&self) -> PyTupleRef { + self.co_names.clone() } #[pygetset] pub fn co_varnames(&self, vm: &VirtualMachine) -> PyTupleRef { - let varnames = self.code.varnames.iter().map(|s| s.to_object()).collect(); - vm.ctx.new_tuple(varnames) + self.co_cached + .varnames + .get_or_init(|| { + vm.ctx.new_tuple( + self.code + .varnames + .iter() + .map(|name| name.to_object()) + .collect(), + ) + }) + .clone() } #[pygetset] - pub fn co_code(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { - vm.ctx.new_bytes(self.code.instructions.original_bytes()) + pub fn co_code(&self, vm: &VirtualMachine) -> PyBytesRef { + self.get_code(vm) } #[pygetset] - pub fn _co_code_adaptive(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { + pub fn _co_code_adaptive(&self, vm: &VirtualMachine) -> PyBytesRef { // Return current (possibly quickened/specialized) bytecode let bytes = unsafe { core::slice::from_raw_parts( @@ -1029,26 +1514,28 @@ impl Py { #[pygetset] pub fn co_freevars(&self, vm: &VirtualMachine) -> PyTupleRef { - let names = self - .code + self.co_cached .freevars - .deref() - .iter() - .map(|name| name.to_pyobject(vm)) - .collect(); - vm.ctx.new_tuple(names) + .get_or_init(|| { + vm.ctx.new_tuple( + self.code + .freevars + .iter() + .map(|name| name.to_object()) + .collect(), + ) + }) + .clone() } #[pygetset] - pub fn co_linetable(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { - // Return the actual linetable from the code object - vm.ctx.new_bytes(self.code.linetable.to_vec()) + pub fn co_linetable(&self) -> PyBytesRef { + self.co_linetable.clone() } #[pygetset] - pub fn co_exceptiontable(&self, vm: &VirtualMachine) -> crate::builtins::PyBytesRef { - // Return the actual exception table from the code object - vm.ctx.new_bytes(self.code.exceptiontable.to_vec()) + pub fn co_exceptiontable(&self) -> PyBytesRef { + self.co_exceptiontable.clone() } // spell-checker: ignore lnotab @@ -1327,198 +1814,122 @@ impl Py { } #[pymethod] - pub fn __replace__(&self, args: ReplaceArgs, vm: &VirtualMachine) -> PyResult { + pub fn __replace__( + &self, + args: KwArgs, + vm: &VirtualMachine, + ) -> PyResult { self.replace(args, vm) } #[pymethod] - pub fn replace(&self, args: ReplaceArgs, vm: &VirtualMachine) -> PyResult { - let ReplaceArgs { - co_posonlyargcount, - co_argcount, - co_kwonlyargcount, - co_filename, - co_firstlineno, - co_consts, - co_name, - co_names, - co_flags, - co_varnames, - co_nlocals, - co_stacksize, - co_code, - co_linetable, - co_exceptiontable, - co_freevars, - co_cellvars, - co_qualname, - } = args; - let posonlyarg_count = match co_posonlyargcount { - OptionalArg::Present(posonlyarg_count) => posonlyarg_count, - OptionalArg::Missing => self.code.posonlyarg_count, - }; - - let arg_count = match co_argcount { - OptionalArg::Present(arg_count) => arg_count, - OptionalArg::Missing => self.code.arg_count, - }; - - let source_path = match co_filename { - OptionalArg::Present(source_path) => source_path, - OptionalArg::Missing => self.source_path().to_owned(), - }; - - let first_line_number = match co_firstlineno { - OptionalArg::Present(first_line_number) => OneIndexed::new(first_line_number as _), - OptionalArg::Missing => self.code.first_line_number, - }; - - let kwonlyarg_count = match co_kwonlyargcount { - OptionalArg::Present(kwonlyarg_count) => kwonlyarg_count, - OptionalArg::Missing => self.code.kwonlyarg_count, - }; - - let constants = match co_consts { - OptionalArg::Present(constants) => constants, - OptionalArg::Missing => self.code.constants.iter().map(|x| x.0.clone()).collect(), - }; - - let obj_name = match co_name { - OptionalArg::Present(obj_name) => obj_name, - OptionalArg::Missing => self.code.obj_name.to_owned(), - }; - - let names = match co_names { - OptionalArg::Present(names) => names, - OptionalArg::Missing => self - .code - .names - .deref() - .iter() - .map(|name| name.to_pyobject(vm)) - .collect(), - }; - - let flags = CodeFlags::from_bits_truncate(match co_flags { - OptionalArg::Present(flags) => flags, - OptionalArg::Missing => self.code.flags.bits(), + pub fn replace( + &self, + args: KwArgs, + vm: &VirtualMachine, + ) -> PyResult { + // _fix_co_filename can change the source path from an __index__ hook. + // Capture the default before conversion, as the Clinic wrapper does. + let default_filename = self.source_path().to_owned(); + let CodeArgs { + values: args, + _owners, + } = FuncArgs::from(args).bind_for::>(vm, "replace")?; + let argcount = args + .co_argcount + .map(|value| value.0) + .unwrap_or(self.code.arg_count as i32); + let posonlyargcount = args + .co_posonlyargcount + .map(|value| value.0) + .unwrap_or(self.code.posonlyarg_count as i32); + let kwonlyargcount = args + .co_kwonlyargcount + .map(|value| value.0) + .unwrap_or(self.code.kwonlyarg_count as i32); + let nlocals = args.co_nlocals.map(|value| value.0).unwrap_or(self.nlocals); + let stacksize = args + .co_stacksize + .map(|value| value.0) + .unwrap_or(self.code.max_stackdepth as i32); + let flags = args + .co_flags + .map(|value| value.0) + .unwrap_or(self.code.flags.bits() as i32); + let firstlineno = args.co_firstlineno.map(|value| value.0).unwrap_or_else(|| { + self.code + .first_line_number + .map_or(0, |line| line.get() as i32) }); - - let varname_objects = match co_varnames { - OptionalArg::Present(varnames) => varnames, - OptionalArg::Missing => self.code.varnames.iter().map(|s| s.to_object()).collect(), - }; - - let qualname = match co_qualname { - OptionalArg::Present(qualname) => qualname, - OptionalArg::Missing => self.code.qualname.to_owned(), - }; - - // Room for one value is always reserved, even where nothing is pushed. - let max_stackdepth = match co_stacksize { - OptionalArg::Present(stacksize) => stacksize, - OptionalArg::Missing => self.code.max_stackdepth, - } - .max(1); - - let instructions = match co_code { - OptionalArg::Present(code_bytes) => { - // Parse and validate bytecode from bytes - CodeUnits::try_from(code_bytes.as_bytes()) - .map_err(|e| vm.new_value_error(format!("invalid bytecode: {e}")))? + for (name, value) in [ + ("co_argcount", argcount), + ("co_posonlyargcount", posonlyargcount), + ("co_kwonlyargcount", kwonlyargcount), + ("co_nlocals", nlocals), + ("co_stacksize", stacksize), + ("co_flags", flags), + ("co_firstlineno", firstlineno), + ] { + if value < 0 { + return Err(vm.new_value_error(format!("{name} must be a positive integer"))); } - OptionalArg::Missing => self.code.instructions.clone(), - }; - - let intern_all = |objs: Vec, field: &str| -> PyResult> { - objs.into_iter() - .map(|o| { - let s = o.downcast_ref::().ok_or_else(|| { - vm.new_type_error(format!("{field} must be a tuple of strings")) - })?; - Ok(vm.ctx.intern_str(s.as_wtf8())) - }) - .collect::>>() - .map(Vec::into_boxed_slice) - }; - - let varnames = intern_all(varname_objects, "co_varnames")?; - - let cellvars = match co_cellvars { - OptionalArg::Present(cellvars) => intern_all(cellvars, "co_cellvars")?, - OptionalArg::Missing => self.code.cellvars.clone(), - }; - - let freevars = match co_freevars { - OptionalArg::Present(freevars) => intern_all(freevars, "co_freevars")?, - OptionalArg::Missing => self.code.freevars.clone(), - }; - - let nlocals = match co_nlocals { - OptionalArg::Present(nlocals) => nlocals as usize, - OptionalArg::Missing => self.code.varnames.len(), - }; - if nlocals != varnames.len() { - return Err(vm.new_value_error(format!( - "co_nlocals ({}) != len(co_varnames) ({})", - nlocals, - varnames.len() - ))); } - - let localspluskinds = build_localspluskinds( - &varnames, - &cellvars, - &freevars, - (posonlyarg_count, arg_count, kwonlyarg_count), - flags, - &instructions, - ) - .map_err(|index| { - vm.new_value_error(format!( - "code: LOAD_FAST_AND_CLEAR oparg {index} out of range" - )) - })?; - - // Handle linetable and exceptiontable - let linetable = match co_linetable { - OptionalArg::Present(linetable) => linetable.as_bytes().to_vec().into_boxed_slice(), - OptionalArg::Missing => self.code.linetable.clone(), - }; - - let exceptiontable = match co_exceptiontable { - OptionalArg::Present(exceptiontable) => { - exceptiontable.as_bytes().to_vec().into_boxed_slice() - } - OptionalArg::Missing => self.code.exceptiontable.clone(), + let co_code = args.co_code.unwrap_or_else(|| self.get_code(vm)); + let filename = args.co_filename.unwrap_or(default_filename); + let name = args.co_name.unwrap_or_else(|| self.co_name.clone()); + audit_code_new( + &co_code, + &filename, + &name, + [ + argcount, + posonlyargcount, + kwonlyargcount, + nlocals, + stacksize, + flags, + ], + vm, + )?; + let names_tuple = |names: &[&'static PyStrInterned]| { + vm.ctx + .new_tuple(names.iter().map(|name| name.to_object()).collect()) }; - - let new_code = CodeObject { + let constructor = CodeConstructor { + argcount, + posonlyargcount, + kwonlyargcount, + nlocals, + stacksize, flags, - posonlyarg_count, - arg_count, - kwonlyarg_count, - source_path: vm.ctx.intern_str(source_path.as_wtf8()), - first_line_number, - obj_name: vm.ctx.intern_str(obj_name.as_wtf8()), - qualname: vm.ctx.intern_str(qualname.as_wtf8()), - - max_stackdepth, - instructions, - // FIXME: invalid locations. Actually locations is a duplication of linetable. - // It can be removed once we move every other code to use linetable only. - locations: self.code.locations.clone(), - constants: constants.into_iter().map(Literal).collect(), - names: intern_all(names, "co_names")?, - varnames, - cellvars, - freevars, - localspluskinds, - linetable, - exceptiontable, + co_code, + consts: args + .co_consts + .unwrap_or_else(|| PyCode::co_consts(self).clone()), + names: args.co_names.unwrap_or_else(|| self.co_names.clone()), + varnames: args + .co_varnames + .unwrap_or_else(|| names_tuple(&self.code.varnames)), + cellvars: args + .co_cellvars + .unwrap_or_else(|| names_tuple(&self.code.cellvars)), + freevars: args + .co_freevars + .unwrap_or_else(|| names_tuple(&self.code.freevars)), + filename, + name, + qualname: args + .co_qualname + .unwrap_or_else(|| self.qualified_name.clone()), + firstlineno, + linetable: args + .co_linetable + .unwrap_or_else(|| self.co_linetable.clone()), + exceptiontable: args + .co_exceptiontable + .unwrap_or_else(|| self.co_exceptiontable.clone()), }; - - Ok(PyCode::new(new_code)) + constructor.build(Some(&self.code), vm) } #[pymethod] @@ -1574,6 +1985,78 @@ impl ToPyObject for bytecode::CodeObject { } } +// Preserve entry lengths and line deltas while dropping columns, as code +// construction does under -X no_debug_ranges in CPython. Decode and re-encode +// signed deltas to normalize redundant encodings, including negative zero. +// Leave unconvertible tables unchanged rather than inventing line deltas or +// introducing new constructor errors. This is not a general table validator. +fn remove_column_info(linetable: &[u8]) -> Option> { + let mut result = Vec::with_capacity(linetable.len()); + let mut reader = LineTableReader::new(linetable); + while let Some(header) = reader.read_byte() { + if header & 0x80 == 0 { + return None; + } + let kind = (header >> 3) & 15; + if kind == PyCodeLocationInfoKind::None as u8 { + result.push(header); + } else { + result.push(0x80 | ((PyCodeLocationInfoKind::NoColumns as u8) << 3) | (header & 7)); + let delta = match PyCodeLocationInfoKind::from_code(kind) { + Some(PyCodeLocationInfoKind::Long | PyCodeLocationInfoKind::NoColumns) => { + read_location_delta(&mut reader)? + } + Some(PyCodeLocationInfoKind::OneLine1) => 1, + Some(PyCodeLocationInfoKind::OneLine2) => 2, + _ => 0, + }; + let mut encoded = (delta.unsigned_abs() << 1) | u32::from(delta < 0); + while encoded >= 64 { + result.push(0x40 | (encoded & 0x3f) as u8); + encoded >>= 6; + } + result.push(encoded as u8); + } + while reader.peek_byte().is_some_and(|byte| byte & 0x80 == 0) { + reader.read_byte(); + } + } + Some(result.into_boxed_slice()) +} + +// Location deltas use an unsigned 32-bit sign/magnitude representation. Allow +// redundant zero groups, but reject overflow and truncation without unchecked +// shifts or consuming the next header. This does not validate absolute lines. +fn read_location_delta(reader: &mut LineTableReader<'_>) -> Option { + let mut value = 0u32; + let mut shift = 0; + loop { + let byte = reader.peek_byte()?; + if byte & 0x80 != 0 { + return None; + } + reader.read_byte(); + let digit = u32::from(byte & 0x3f); + if shift < u32::BITS { + if digit > (u32::MAX >> shift) { + return None; + } + value |= digit << shift; + } else if digit != 0 { + return None; + } + if byte & 0x40 == 0 { + let magnitude = (value >> 1) as i32; + return Some(if value & 1 != 0 { + -magnitude + } else { + magnitude + }); + } + shift = (shift + 6).min(u32::BITS); + } +} + // Helper struct for reading linetable struct LineTableReader<'a> { data: &'a [u8], diff --git a/crates/vm/src/builtins/code/const_cache.rs b/crates/vm/src/builtins/code/const_cache.rs new file mode 100644 index 00000000000..6515219e711 --- /dev/null +++ b/crates/vm/src/builtins/code/const_cache.rs @@ -0,0 +1,148 @@ +//! The compiler's constant cache (`c_const_cache`). +//! +//! Equal constants and code fields produced by one compilation share a single +//! object, merged under their `_PyCode_ConstantKey`. + +use super::*; +use crate::builtins::{PyDict, PyDictRef, PyTuple}; + +/// `const_cache_insert`. Items of a tuple or frozenset constant are created +/// through the cache before the container, so a single non-recursive insert +/// also merges them. +fn const_cache_insert( + const_cache: &Py, + o: PyObjectRef, + vm: &VirtualMachine, +) -> PyResult { + // None and Ellipsis are singletons, and key is the singleton. + if vm.is_none(&o) || o.is(&vm.ctx.ellipsis) { + return Ok(o); + } + let key = constant_key(&o, vm)?; + let key = match const_cache.get_item_opt(&*key, vm)? { + Some(existing) => existing, + None => { + const_cache.set_item(&*key, key.clone(), vm)?; + key + } + }; + // See constant_key() + Ok(match key.downcast_ref_if_exact::(vm) { + Some(key) => key.as_slice()[1].clone(), + None => key, + }) +} + +/// A [`ConstantBag`] creating the constants of one compilation through its +/// constant cache. +#[derive(Clone, Copy)] +struct CompileBag<'a> { + vm: &'a VirtualMachine, + const_cache: &'a Py, +} + +impl CompileBag<'_> { + /// `_PyCompile_ConstCacheMergeOne` + fn merge_one(&self, obj: PyRef) -> PyRef { + self.merge(obj.into()) + .downcast() + .expect("an equal constant key implies the same type") + } + + fn merge(&self, obj: PyObjectRef) -> PyObjectRef { + const_cache_insert(self.const_cache, obj, self.vm) + .expect("constant keys are hashable and comparable") + } + + /// Create a code object whose fields are merged the way `assemble.c` + /// merges them, in the same order. + fn new_code(&self, code: CodeObject) -> PyCode { + let mut code = PyCode::new(code, &self.vm.ctx); + code.apply_debug_ranges(self.vm); + code.co_exceptiontable = self.merge_one(code.co_exceptiontable); + code.co_linetable = self.merge_one(code.co_linetable); + code.co_names = self.merge_one(code.co_names); + let consts = self.merge_one(code.code.constants.as_tuple().as_pytuple().clone()); + code.code.constants = bytecode::Constants::new(LiteralTuple(consts)); + code.co_localsplusnames = self.merge_one(code.co_localsplusnames); + code + } +} + +impl ConstantBag for CompileBag<'_> { + type Constant = Literal; + + fn make_constant(&self, constant: BorrowedConstant<'_, C>) -> Literal { + let vm = self.vm; + let obj = match constant { + BorrowedConstant::Code { code } => return self.make_code(code.map_clone_bag(self)), + BorrowedConstant::Tuple { elements } => vm + .ctx + .new_tuple( + elements + .iter() + .map(|item| self.make_constant(item.borrow_constant()).0) + .collect(), + ) + .into(), + BorrowedConstant::Frozenset { elements } => PyFrozenSet::from_iter( + vm, + elements + .iter() + .map(|item| self.make_constant(item.borrow_constant()).0), + ) + .unwrap() + .into_ref(&vm.ctx) + .into(), + BorrowedConstant::Slice { elements } => { + let [start, stop, step] = elements + .each_ref() + .map(|item| self.make_constant(item.borrow_constant()).0); + crate::builtins::PySlice { + start: Some(start), + stop, + step: Some(step), + } + .into_ref(&vm.ctx) + .into() + } + _ => PyVmBag(vm).make_constant(constant).0, + }; + Literal(self.merge(obj)) + } + + fn make_name(&self, name: &str) -> &'static PyStrInterned { + self.vm.ctx.intern_str(name) + } + + fn make_int(&self, value: BigInt) -> Literal { + Literal(self.merge(self.vm.ctx.new_int(value).into())) + } + + fn make_tuple(&self, elements: impl Iterator) -> Literal { + let tuple = self.vm.ctx.new_tuple(elements.map(|item| item.0).collect()); + Literal(self.merge(tuple.into())) + } + + fn make_code(&self, code: CodeObject) -> Literal { + let code = self.new_code(code).into_ref(&self.vm.ctx); + Literal(self.merge(code.into())) + } +} + +pub(super) fn into_code_object(code: bytecode::CodeObject, vm: &VirtualMachine) -> CodeObject { + let const_cache: PyDictRef = vm.ctx.new_dict(); + code.map_bag(CompileBag { + vm, + const_cache: &const_cache, + }) +} + +pub(super) fn into_pycode(code: bytecode::CodeObject, vm: &VirtualMachine) -> PyCode { + let const_cache: PyDictRef = vm.ctx.new_dict(); + let bag = CompileBag { + vm, + const_cache: &const_cache, + }; + bag.new_code(code.map_bag(bag)) +} diff --git a/crates/vm/src/builtins/complex.rs b/crates/vm/src/builtins/complex.rs index f471c43c580..6970c295452 100644 --- a/crates/vm/src/builtins/complex.rs +++ b/crates/vm/src/builtins/complex.rs @@ -1,11 +1,12 @@ -use super::{PyStr, PyType, PyTypeRef, float}; +use super::{PyFloat, PyInt, PyStr, PyType, PyTypeRef, float}; use crate::{ - AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, + VirtualMachine, builtins::PyUtf8StrRef, class::{PyClassDef, PyClassImpl}, - common::{format::FormatSpec, wtf8::Wtf8Buf}, - convert::{IntoPyException, ToPyObject, ToPyResult}, - function::{FuncArgs, OptionalArg, PyComparisonValue}, + common::{float_ops, wtf8::Wtf8Buf}, + convert::{ToPyObject, ToPyResult}, + function::{ArgIntoComplex, ArgIntoFloat, FuncArgs, OptionalArg, PyComparisonValue}, protocol::PyNumberMethods, stdlib::_warnings, types::{AsNumber, Callable, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, @@ -16,6 +17,7 @@ use core::ptr::NonNull; use num_complex::Complex64; use num_traits::Zero; use rustpython_common::hash; +use rustpython_common::wtf8::wtf8_concat; #[pyclass(module = false, name = "complex")] #[derive(Debug, Copy, Clone, PartialEq)] @@ -90,54 +92,63 @@ impl From for PyComplex { } } -impl PyObjectRef { - /// Tries converting a python object into a complex, returns an option of whether the complex - /// and whether the object was a complex originally or coerced into one +impl PyObject { + /// Convert a constructor argument, preferring an overridden `__complex__`. + /// The flag records whether the result came from a complex value or method, + /// rather than a real-number conversion. pub fn try_complex(&self, vm: &VirtualMachine) -> PyResult> { if let Some(complex) = self.downcast_ref_if_exact::(vm) { return Ok(Some((complex.as_complex(), true))); } - if let Some(method) = vm.get_method(self.clone(), identifier!(vm, __complex__)) { - let result = method?.call((), vm)?; - - let ret_class = result.class().to_owned(); - if let Some(ret) = result.downcast_ref::() - && !result.class().is(vm.ctx.types.complex_type) - { - _warnings::warn( - vm.ctx.exceptions.deprecation_warning, - format!( - "__complex__ returned non-complex (type {ret_class}). \ - The ability to return an instance of a strict subclass of complex \ - is deprecated, and may be removed in a future version of Python." - ), - 1, - vm, - )?; - - return Ok(Some((ret.as_complex(), true))); - } - - return match result.downcast_ref::() { - Some(complex_obj) => Ok(Some((complex_obj.as_complex(), true))), - None => Err(vm.new_type_error(format!( - "__complex__ returned non-complex (type '{}')", - result.class().name() - ))), - }; + if let Some(value) = self.try_complex_special_method(vm)? { + return Ok(Some((value.as_complex(), true))); } - // `complex` does not have a `__complex__` by default, so subclasses might not either, - // use the actual stored value in this case + // A complex subtype whose special method is absent still has a value. if let Some(complex) = self.downcast_ref::() { return Ok(Some((complex.as_complex(), true))); } - if let Some(float) = self.try_float_opt(vm) { - return Ok(Some((Complex64::new(float?.to_f64(), 0.0), false))); + // Unlike the two-component constructor, the single-argument form uses + // PyFloat_AsDouble: read float subclasses without invoking __float__. + if self.downcastable::() || has_real_number_conversion(self) { + let real = self.try_to_value::(vm)?.into_float(); + return Ok(Some((Complex64::new(real, 0.0), false))); } Ok(None) } + + fn try_complex_special_method( + &self, + vm: &VirtualMachine, + ) -> PyResult>> { + let Some(method) = vm.get_method(self.to_owned(), identifier!(vm, __complex__)) else { + return Ok(None); + }; + let result = method?.call((), vm)?; + if let Some(complex) = result.downcast_ref_if_exact::(vm) { + return Ok(Some(complex.to_owned())); + } + + let message = wtf8_concat!( + self.class().fully_qualified_name(vm)?, + ".__complex__() must return a complex, not ", + result.class().fully_qualified_name(vm)? + ); + let Some(complex) = result.downcast_ref::() else { + return Err(vm.new_type_error(message)); + }; + _warnings::warn( + vm.ctx.exceptions.deprecation_warning, + wtf8_concat!( + message, + ". The ability to return an instance of a strict subclass of complex is deprecated, and may be removed in a future version of Python." + ), + 1, + vm, + )?; + Ok(Some(complex.to_owned())) + } } pub(crate) fn init(context: &'static Context) { @@ -155,148 +166,18 @@ fn to_op_complex(value: &PyObject, vm: &VirtualMachine) -> PyResult f64 { - if part.is_infinite() { 1.0 } else { 0.0f64 }.copysign(part) -} - -fn tamed(value: Complex64) -> Complex64 { - Complex64::new(signed_unit(value.re), signed_unit(value.im)) -} - -fn nans_to_zero(value: Complex64) -> Complex64 { - let zeroed = |part: f64| { - if part.is_nan() { - 0.0f64.copysign(part) - } else { - part - } - }; - Complex64::new(zeroed(value.re), zeroed(value.im)) -} - -/// Multiply, recovering the infinities that the plain formula turns into nan, -/// the way C11 Annex G.5.1 does. fn prod(a: Complex64, b: Complex64) -> Complex64 { - let r = a * b; - if !(r.re.is_nan() && r.im.is_nan()) { - return r; - } - - // "Box" an infinite operand into a signed one and turn the other's nans - // into signed zeros, so that the infinity survives a second pass. - let (mut a, mut b) = (a, b); - let a_infinite = a.re.is_infinite() || a.im.is_infinite(); - if a_infinite { - a = tamed(a); - b = nans_to_zero(b); - } - let b_infinite = b.re.is_infinite() || b.im.is_infinite(); - if b_infinite { - b = tamed(b); - a = nans_to_zero(a); - } - // An infinity that overflow lost, rather than one an operand carried. - let overflowed = !a_infinite - && !b_infinite - && ((a.re * b.re).is_infinite() - || (a.im * b.im).is_infinite() - || (a.re * b.im).is_infinite() - || (a.im * b.re).is_infinite()); - if overflowed { - a = nans_to_zero(a); - b = nans_to_zero(b); - } - - if !(a_infinite || b_infinite || overflowed) { - return r; - } - Complex64::new( - f64::INFINITY * (a.re * b.re - a.im * b.im), - f64::INFINITY * (a.re * b.im + a.im * b.re), - ) -} - -/// Divide a real by a complex. Written out rather than routed through `quot` -/// with a zero imaginary part, which would lose the sign of a zero. -fn rc_quot(a: f64, b: Complex64) -> Option { - let abs_re = b.re.abs(); - let abs_im = b.im.abs(); - - let r = if abs_re >= abs_im { - if abs_re == 0.0 { - return None; - } - let ratio = b.im / b.re; - let denom = b.re + b.im * ratio; - Complex64::new(a / denom, -a * ratio / denom) - } else if abs_im >= abs_re { - let ratio = b.re / b.im; - let denom = b.re * ratio + b.im; - Complex64::new(a * ratio / denom, -a / denom) - } else { - // One part of the divisor is a nan, so neither comparison held. - Complex64::new(f64::NAN, f64::NAN) - }; - - // A quotient that came out as nan recovers the way `recovered_quot` does, - // except that a real numerator has no imaginary term to carry a sign. - if r.re.is_nan() && r.im.is_nan() && (b.re.is_infinite() || b.im.is_infinite()) && a.is_finite() - { - let Complex64 { re: x, im: y } = tamed(b); - return Some(Complex64::new(0.0 * (a * x), 0.0 * -(a * y))); - } - - Some(r) + let (re, im) = rustpython_literal::complex::multiply((a.re, a.im), (b.re, b.im)); + Complex64::new(re, im) } -/// Divide by whichever part of the divisor is larger, so that the ratio the -/// other part is scaled by cannot overflow. `None` stands for a divisor of -/// zero. fn quot(a: Complex64, b: Complex64) -> Option { - let abs_re = b.re.abs(); - let abs_im = b.im.abs(); - - let r = if abs_re >= abs_im { - if abs_re == 0.0 { - return None; - } - let ratio = b.im / b.re; - let denom = b.re + b.im * ratio; - Complex64::new((a.re + a.im * ratio) / denom, (a.im - a.re * ratio) / denom) - } else if abs_im >= abs_re { - let ratio = b.re / b.im; - let denom = b.re * ratio + b.im; - Complex64::new((a.re * ratio + a.im) / denom, (a.im * ratio - a.re) / denom) - } else { - // One part of the divisor is a nan, so neither comparison held. - Complex64::new(f64::NAN, f64::NAN) - }; - - Some(recovered_quot(r, a, b)) + rustpython_literal::complex::divide((a.re, a.im), (b.re, b.im)) + .map(|(re, im)| Complex64::new(re, im)) } -/// Recover the infinities and zeros a quotient came out of as nan, the way -/// C11 Annex G.5.2 does. -fn recovered_quot(r: Complex64, a: Complex64, b: Complex64) -> Complex64 { - if !(r.re.is_nan() && r.im.is_nan()) { - return r; - } - - if (a.re.is_infinite() || a.im.is_infinite()) && b.re.is_finite() && b.im.is_finite() { - let Complex64 { re: x, im: y } = tamed(a); - Complex64::new( - f64::INFINITY * (x * b.re + y * b.im), - f64::INFINITY * (y * b.re - x * b.im), - ) - } else if (b.re.is_infinite() || b.im.is_infinite()) && a.re.is_finite() && a.im.is_finite() { - let Complex64 { re: x, im: y } = tamed(b); - Complex64::new(0.0 * (a.re * x + a.im * y), 0.0 * (a.im * x - a.re * y)) - } else { - r - } +fn rc_quot(a: f64, b: Complex64) -> Option { + rustpython_literal::complex::real_divide(a, (b.re, b.im)).map(|(re, im)| Complex64::new(re, im)) } fn inner_div(v1: Complex64, v2: Complex64, vm: &VirtualMachine) -> PyResult { @@ -374,9 +255,20 @@ fn powc(a: Complex64, exp: Complex64) -> Complex64 { Complex64::new(len * phase.cos(), len * phase.sin()) } -/// Whether an underscore sits where a numeric literal does not allow one: -/// they only ever join two digits. -fn has_misplaced_underscore(bytes: &[u8]) -> bool { +/// Whether underscore validation rejects the literal, including an embedded +/// NUL when an underscore occurs before it. +fn invalid_underscored_literal(bytes: &[u8]) -> bool { + // CPython only enters underscore validation if one occurs before a NUL. + let end = bytes + .iter() + .position(|&byte| byte == 0) + .unwrap_or(bytes.len()); + if !bytes[..end].contains(&b'_') { + return false; + } + if end != bytes.len() { + return true; + } let mut prev = b'\0'; for &byte in bytes { if byte == b'_' { @@ -395,13 +287,17 @@ impl Constructor for PyComplex { type Args = ComplexArgs; fn slot_new(cls: PyTypeRef, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult { - // Optimization: return exact complex as-is (only when imag is not provided) - if cls.is(vm.ctx.types.complex_type) - && func_args.args.len() == 1 - && func_args.kwargs.is_empty() - && func_args.args[0].class().is(vm.ctx.types.complex_type) - { - return Ok(func_args.args[0].clone()); + if func_args.kwargs.is_empty() && func_args.args.len() <= 1 { + let payload = if let Some(value) = func_args.args.first() { + if cls.is(vm.ctx.types.complex_type) && value.class().is(vm.ctx.types.complex_type) + { + return Ok(value.clone()); + } + Self::from_single_argument(value, vm)? + } else { + Self::from(Complex64::new(0.0, 0.0)) + }; + return payload.into_ref_with_type(vm, cls).map(Into::into); } let args: Self::Args = func_args.bind_for(vm, Self::NAME)?; @@ -411,35 +307,55 @@ impl Constructor for PyComplex { fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { let imag_missing = args.imag.is_missing(); - let (real, real_was_complex) = match args.real { - OptionalArg::Missing => (Complex64::new(0.0, 0.0), false), - OptionalArg::Present(val) => { - if let Some(c) = val.try_complex(vm)? { - c - } else if let Some(s) = val.downcast_ref::() { - if args.imag.is_present() { - return Err(vm.new_type_error( - "complex() can't take second arg if first is a string", - )); - } - if has_misplaced_underscore(s.as_wtf8().as_bytes()) { - let repr = val.repr(vm)?; - return Err(vm.new_value_error(format!( - "could not convert string to complex: {repr}" - ))); - } - let (re, im) = rustpython_literal::complex::parse_str( - &crate::protocol::numeric_literal_from_str(s), - ) - .ok_or_else(|| vm.new_value_error("complex() arg is a malformed string"))?; - return Ok(Self::from(Complex64 { re, im })); - } else { - return Err(vm.new_type_error(format!( - "complex() argument must be a string or a number, not {}", - val.class().slot_name() - ))); - } + let original_real = match args.real { + OptionalArg::Missing => vm.ctx.new_int(0).into(), + OptionalArg::Present(value) => value, + }; + let converted_real = original_real.try_complex_special_method(vm)?; + if converted_real.is_none() + && original_real.downcast_ref::().is_none() + && !has_real_number_conversion(&original_real) + { + return Err(vm.new_type_error(wtf8_concat!( + "complex() argument 'real' must be a real number, not ", + original_real.class().fully_qualified_name(vm)? + ))); + } + if let OptionalArg::Present(imag) = &args.imag + && imag.downcast_ref::().is_none() + && !has_real_number_conversion(imag) + { + return Err(vm.new_type_error(wtf8_concat!( + "complex() argument 'imag' must be a real number, not ", + imag.class().fully_qualified_name(vm)? + ))); + } + + let complex_real = converted_real + .as_ref() + .map(|value| value.as_complex()) + .or_else(|| { + original_real + .downcast_ref::() + .map(|value| value.as_complex()) + }); + let real_was_complex = complex_real.is_some(); + let real = if let Some(value) = complex_real { + drop(converted_real); + if !has_real_number_conversion(&original_real) { + _warnings::warn( + vm.ctx.exceptions.deprecation_warning, + wtf8_concat!( + "complex() argument 'real' must be a real number, not ", + original_real.class().fully_qualified_name(vm)? + ), + 1, + vm, + )?; } + value + } else { + Complex64::new(original_real.try_float(vm)?.to_f64(), 0.0) }; let (imag, imag_was_complex) = match args.imag { @@ -447,15 +363,19 @@ impl Constructor for PyComplex { // if an imaginary argument is not passed in OptionalArg::Missing => (Complex64::new(real.im, 0.0), false), OptionalArg::Present(obj) => { - if let Some(c) = obj.try_complex(vm)? { - c - } else if obj.class().fast_issubclass(vm.ctx.types.str_type) { - return Err(vm.new_type_error("complex() second arg can't be a string")); + if let Some(value) = obj.downcast_ref::() { + _warnings::warn( + vm.ctx.exceptions.deprecation_warning, + wtf8_concat!( + "complex() argument 'imag' must be a real number, not ", + obj.class().fully_qualified_name(vm)? + ), + 1, + vm, + )?; + (value.as_complex(), true) } else { - return Err(vm.new_type_error(format!( - "complex() second argument must be a number, not '{}'", - obj.class().name() - ))); + (Complex64::new(obj.try_float(vm)?.to_f64(), 0.0), false) } } }; @@ -476,7 +396,34 @@ impl Constructor for PyComplex { } } +fn has_real_number_conversion(value: &PyObject) -> bool { + let number = &value.class().slots().as_number; + number.float.load().is_some() || number.index.load().is_some() +} + impl PyComplex { + fn from_single_argument(value: &PyObjectRef, vm: &VirtualMachine) -> PyResult { + if let Some(string) = value.downcast_ref::() { + let literal = crate::protocol::numeric_literal_from_str(string); + if invalid_underscored_literal(literal.as_bytes()) { + let repr = value.repr(vm)?; + return Err( + vm.new_value_error(format!("could not convert string to complex: {repr}")) + ); + } + let (re, im) = rustpython_literal::complex::parse_str(&literal) + .ok_or_else(|| vm.new_value_error("complex() arg is a malformed string"))?; + return Ok(Self::from(Complex64 { re, im })); + } + match value.try_complex(vm)? { + Some((value, _)) => Ok(Self::from(value)), + None => Err(vm.new_type_error(wtf8_concat!( + "complex() argument must be a string or a number, not ", + value.class().fully_qualified_name(vm)? + ))), + } + } + #[deprecated(note = "use PyComplex::from(...).into_ref() instead")] pub fn new_ref(value: Complex64, ctx: &Context) -> PyRef { Self::from(value).into_ref(ctx) @@ -571,17 +518,16 @@ impl Py { if format_spec.is_empty() { return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned()); } - let format_spec = - FormatSpec::parse(format_spec.as_str()).map_err(|err| err.into_pyexception(vm))?; - let result = if format_spec.has_locale_format() { + let spec = crate::format::parse_format_spec(zelf.as_object(), format_spec.as_str(), vm)?; + let result = if spec.has_locale_format() { let locale = crate::format::get_locale_info(); - format_spec.format_complex_locale(&zelf.as_complex(), &locale) + spec.format_complex_locale(&zelf.as_complex(), &locale) } else { - format_spec.format_complex(&zelf.as_complex()) + spec.format_complex(&zelf.as_complex()) }; - result - .map(Wtf8Buf::from_string) - .map_err(|err| err.into_pyexception(vm)) + result.map(Wtf8Buf::from_string).map_err(|err| { + crate::format::format_spec_error(err, zelf.as_object(), format_spec.as_str(), vm) + }) } #[pyclassmethod] @@ -589,21 +535,15 @@ impl Py { if number.class().is(vm.ctx.types.complex_type) && cls.is(vm.ctx.types.complex_type) { return Ok(number); } - let value = number - .try_complex(vm)? - .ok_or_else(|| { - vm.new_type_error(format!( - "must be real number, not {}", - number.class().name() - )) - })? - .0; + let value = ArgIntoComplex::try_from_object(vm, number.clone())?.into_complex(); let result = vm.ctx.new_complex(value); - if cls.is(vm.ctx.types.complex_type) { + let result = if cls.is(vm.ctx.types.complex_type) { Ok(result.into()) } else { PyType::call(&cls, vec![result.into()].into(), vm) - } + }; + drop(number); + result } } @@ -611,7 +551,7 @@ impl Py { impl PyRef { #[pymethod] fn __complex__(self, vm: &VirtualMachine) -> Self { - if self.is(vm.ctx.types.complex_type) { + if self.class().is(vm.ctx.types.complex_type) { self } else { PyComplex::from(self.as_complex()).into_ref(&vm.ctx) @@ -624,17 +564,20 @@ impl Comparable for PyComplex { zelf: &Py, other: &PyObject, op: PyComparisonOp, - vm: &VirtualMachine, + _vm: &VirtualMachine, ) -> PyResult { op.eq_only(|| { + let value = zelf.as_complex(); let result = if let Some(other) = other.downcast_ref::() { - zelf.as_complex() == other.as_complex() + value == other.as_complex() + } else if let Some(other) = other.downcast_ref::() { + // Compare with the exact integer, as float does, instead of + // rounding the integer to the nearest float first. + value.im == 0.0 && float_ops::eq_int(value.re, other.as_bigint()) + } else if let Some(other) = other.downcast_ref::() { + value == other.to_f64().into() } else { - match float::to_op_float(other, vm) { - Ok(Some(other)) => zelf.as_complex() == other.into(), - Err(_) => false, - Ok(None) => return Ok(PyComparisonValue::NotImplemented), - } + return Ok(PyComparisonValue::NotImplemented); }; Ok(PyComparisonValue::Implemented(result)) }) @@ -695,11 +638,18 @@ impl AsNumber for PyComplex { ) }), power: Some(|a, b, c, vm| { - if vm.is_none(c) { - PyComplex::number_op(a, b, complex_pow, vm) - } else { - Err(vm.new_value_error(String::from("complex modulo"))) - } + PyComplex::number_op( + a, + b, + |a, b, vm| { + if vm.is_none(c) { + complex_pow(a, b, vm) + } else { + Err(vm.new_value_error("complex modulo")) + } + }, + vm, + ) }), negative: Some(|number, vm| { let value = PyComplex::number_downcast(number).as_complex(); @@ -761,10 +711,10 @@ impl Representable for PyComplex { #[derive(FromArgs)] pub struct ComplexArgs { - // Missing real is 0. A string real uses the imag-missing path. + // Component construction defaults the missing real part to 0. #[pyarg(any, default, py_default = "0")] real: OptionalArg, - // Missing imag is 0 and is distinct from imag=0 when real is a string. + // Missing imag retains the imaginary part of a converted real argument. #[pyarg(any, default, py_default = "0")] imag: OptionalArg, } diff --git a/crates/vm/src/builtins/coroutine.rs b/crates/vm/src/builtins/coroutine.rs index 649481c8cc3..b77e851db32 100644 --- a/crates/vm/src/builtins/coroutine.rs +++ b/crates/vm/src/builtins/coroutine.rs @@ -119,8 +119,8 @@ impl Py { self.inner.set_qualname(qualname) } - #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef) -> PyCoroutineWrapper { + #[pymethod] + fn __await__(zelf: PyRef) -> PyCoroutineWrapper { PyCoroutineWrapper { coro: zelf, closed: AtomicCell::new(false), @@ -129,7 +129,7 @@ impl Py { #[pygetset] fn cr_await(&self, _vm: &VirtualMachine) -> Option { - self.inner.frame_opt().and_then(|f| f.yield_from_target()) + self.inner.yield_from_target() } #[pygetset] fn cr_frame(&self, _vm: &VirtualMachine) -> Option { @@ -148,6 +148,15 @@ impl Py { self.inner.code() } #[pygetset] + fn cr_state(&self) -> &'static str { + self.inner.state_name([ + "CORO_CREATED", + "CORO_RUNNING", + "CORO_SUSPENDED", + "CORO_CLOSED", + ]) + } + #[pygetset] fn cr_suspended(&self, _vm: &VirtualMachine) -> bool { self.inner.suspended() } @@ -174,7 +183,7 @@ impl Destructor for PyCoroutine { if zelf.inner.closed() || zelf.inner.running() { return Ok(()); } - if zelf.inner.frame_opt().is_none_or(|f| f.lasti() == 0) { + if !zelf.inner.started() { crate::warn::warn_unawaited_coroutine(zelf.as_object(), &zelf.inner.qualname(), vm); zelf.inner.closed.store(true); return Ok(()); diff --git a/crates/vm/src/builtins/descriptor.rs b/crates/vm/src/builtins/descriptor.rs index b3189e592a8..fcc51dbc93a 100644 --- a/crates/vm/src/builtins/descriptor.rs +++ b/crates/vm/src/builtins/descriptor.rs @@ -1,7 +1,7 @@ use super::{PyStr, PyStrInterned, PyTuple, PyType}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyTypeRef, builtin_func::PyNativeMethod, type_}, + builtins::{PyTypeRef, builtin_func::PyNativeFunction, type_}, class::PyClassImpl, common::hash::PyHash, convert::{ToPyObject, ToPyResult}, @@ -19,6 +19,7 @@ use crate::{ }; use core::mem::{align_of, size_of}; use rustpython_common::lock::PyRwLock; +use rustpython_common::wtf8::wtf8_concat; #[derive(Debug)] pub struct PyDescriptor { @@ -39,7 +40,7 @@ pub struct PyMethodDescriptor { #[pymember(name = "__objclass__", path = "typ")] #[pymember(name = "__name__", path = "name")] pub common: PyDescriptor, - pub method: &'static PyMethodDef, + pub(crate) method: &'static PyMethodDef, // vectorcall: vector_call_func, /// Prevent HeapMethodDef from being freed while this descriptor references it pub(crate) _method_def_owner: Option, @@ -111,21 +112,22 @@ impl GetDescriptor for PyMethodDescriptor { impl Callable for PyMethodDescriptor { type Args = FuncArgs; #[inline] - fn call(zelf: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - if let Some(obj) = args.args.first() { - method_descr_typecheck(zelf, obj, vm)?; + fn call(zelf: &Py, mut args: FuncArgs, vm: &VirtualMachine) -> PyResult { + method_descr_check_self(zelf, args.args.first().map(|obj| &**obj), vm)?; + if !args.kwargs.is_empty() && !zelf.method.flags.contains(PyMethodFlags::KEYWORDS) { + return Err(method_descr_no_keywords_error(zelf, vm)); } - (zelf.method.func)( - vm, - args, - Callee::named(zelf.method.name).with_instance_arg(true), - ) + let receiver = args + .take_positional() + .expect("descriptor receiver was checked"); + (zelf.method.func)(vm, Some(&receiver), args, Callee::named(zelf.method.name)) } } impl PyMethodDescriptor { - pub fn bind(&self, obj: PyObjectRef, ctx: &Context) -> PyRef { - self.method.build_bound_method(ctx, obj, self.common.typ) + pub fn bind(&self, obj: PyObjectRef, ctx: &Context) -> PyRef { + self.method + .build_bound_function_with_owner(ctx, obj, self._method_def_owner.clone()) } } @@ -154,10 +156,12 @@ impl Py { fn __reduce__( &self, vm: &VirtualMachine, - ) -> (Option, (Option, &'static str)) { - let builtins_getattr = vm.builtins.get_attr("getattr", vm).ok(); - let classname = vm.builtins.get_attr(&self.common.typ.__name__(vm), vm).ok(); - (builtins_getattr, (classname, self.method.name)) + ) -> PyResult<(PyObjectRef, (PyTypeRef, &'static str))> { + let builtins_getattr = vm.eval_get_builtin(vm.ctx.intern_str("getattr"))?; + Ok(( + builtins_getattr, + (self.common.typ.to_owned(), self.method.name), + )) } } @@ -167,7 +171,7 @@ impl Representable for PyMethodDescriptor { Ok(format!( "", zelf.method.name, - zelf.common.typ.name() + zelf.common.typ.slot_name() )) } } @@ -178,7 +182,7 @@ pub struct PyClassMethodDescriptor { #[pymember(name = "__objclass__", path = "typ")] #[pymember(name = "__name__", path = "name")] pub common: PyDescriptor, - pub method: &'static PyMethodDef, + pub(crate) method: &'static PyMethodDef, pub(crate) _method_def_owner: Option, } @@ -195,8 +199,9 @@ impl PyClassMethodDescriptor { } } - pub fn bind(&self, obj: PyObjectRef, ctx: &Context) -> PyRef { - self.method.build_bound_method(ctx, obj, self.common.typ) + pub fn bind(&self, obj: PyObjectRef, ctx: &Context) -> PyRef { + self.method + .build_bound_function_with_owner(ctx, obj, self._method_def_owner.clone()) } } @@ -540,12 +545,6 @@ impl MemberCell for core::sync::atomic::AtomicU32 {} // One object pointer. Readonly members may be a plain pointer. Writable // members are an atomic cell: `PyAtomicRef` when the pointer is // never null, or `PyAtomicRef>` when it may be. -impl MemberLayout for PyObjectRef { - const KIND: MemberKind = MemberKind::Object; -} -impl MemberLayout for Option { - const KIND: MemberKind = MemberKind::Object; -} impl MemberLayout for crate::object::PyObjectCell { const KIND: MemberKind = MemberKind::Object; const ATOMIC: bool = true; @@ -850,7 +849,7 @@ impl Py { #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { - let builtins_getattr = vm.builtins.get_attr("getattr", vm)?; + let builtins_getattr = vm.eval_get_builtin(vm.ctx.intern_str("getattr"))?; Ok(vm .ctx .new_tuple(vec![ @@ -1135,10 +1134,12 @@ fn member_get_one( MemberKind::ObjectEx => match obj.get_slot(offset) { Some(value) => value, None => { - return Err(vm.new_attribute_error(format!( - "'{}' object has no attribute '{}'", + return Err(vm.new_attribute_error(wtf8_concat!( + "'", obj.class().fully_qualified_name(vm)?, - member.name + "' object has no attribute '", + member.name, + "'" ))); } }, @@ -1556,25 +1557,70 @@ fn method_descr_typecheck( ))) } +#[inline] +fn method_descr_check_self( + descr: &PyMethodDescriptor, + obj: Option<&PyObject>, + vm: &VirtualMachine, +) -> PyResult<()> { + let obj = obj.ok_or_else(|| method_descr_missing_self_error(descr, vm))?; + method_descr_typecheck(descr, obj, vm) +} + +#[cold] +fn method_descr_missing_self_error( + descr: &PyMethodDescriptor, + vm: &VirtualMachine, +) -> crate::exceptions::types::PyBaseExceptionRef { + vm.new_type_error(format!( + "unbound method {}.{}() needs an argument", + descr.common.typ.name(), + descr.common.name + )) +} + +#[cold] +fn method_descr_no_keywords_error( + descr: &PyMethodDescriptor, + vm: &VirtualMachine, +) -> crate::exceptions::types::PyBaseExceptionRef { + vm.new_type_error(format!( + "{}.{}() takes no keyword arguments", + descr.common.typ.name(), + descr.common.name + )) +} + /// Vectorcall for method_descriptor: calls native method directly fn vectorcall_method_descriptor( zelf_obj: &PyObject, - args: Vec, + mut args: Vec, nargs: usize, kwnames: Option<&[PyObjectRef]>, vm: &VirtualMachine, ) -> PyResult { let zelf: &Py = zelf_obj.downcast_ref().unwrap(); - if nargs > 0 - && let Some(obj) = args.first() + method_descr_check_self( + zelf, + if nargs > 0 { + args.first().map(|obj| &**obj) + } else { + None + }, + vm, + )?; + if kwnames.is_some_and(|names| !names.is_empty()) + && !zelf.method.flags.contains(PyMethodFlags::KEYWORDS) { - method_descr_typecheck(zelf, obj, vm)?; + return Err(method_descr_no_keywords_error(zelf, vm)); } - let func_args = FuncArgs::from_vectorcall_owned(args, nargs, kwnames); + let receiver = args.remove(0); + let func_args = FuncArgs::from_vectorcall_owned(args, nargs - 1, kwnames); (zelf.method.func)( vm, + Some(&receiver), func_args, - Callee::named(zelf.method.name).with_instance_arg(true), + Callee::named(zelf.method.name), ) } @@ -1616,6 +1662,11 @@ pub(crate) fn init(ctx: &'static Context) { .slots .vectorcall .store(Some(vectorcall_method_descriptor)); + ctx.types + .method_descriptor_type + .slots + .flags + .insert(crate::types::PyTypeFlags::HAVE_VECTORCALL); PyClassMethodDescriptor::extend_class(ctx, ctx.types.classmethod_descriptor_type); PyWrapper::extend_class(ctx, ctx.types.wrapper_descriptor_type); ctx.types @@ -1623,6 +1674,11 @@ pub(crate) fn init(ctx: &'static Context) { .slots .vectorcall .store(Some(vectorcall_wrapper)); + ctx.types + .wrapper_descriptor_type + .slots + .flags + .insert(crate::types::PyTypeFlags::HAVE_VECTORCALL); PyMethodWrapper::extend_class(ctx, ctx.types.method_wrapper_type); } @@ -2015,9 +2071,19 @@ impl Callable for PyWrapper { #[pyclass( with(GetDescriptor, Callable, Representable), - flags(DISALLOW_INSTANTIATION) + flags(DISALLOW_INSTANTIATION, METHOD_DESCRIPTOR) )] impl Py { + #[pymethod] + fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { + let getattr = vm.eval_get_builtin(vm.ctx.intern_str("getattr"))?; + let args = vm.ctx.new_tuple(vec![ + self.typ.to_owned().into(), + self.name.to_owned().into(), + ]); + Ok(vm.ctx.new_tuple(vec![getattr, args.into()]).into()) + } + #[pygetset] fn __qualname__(&self) -> String { format!("{}.{}", self.typ.name(), self.name) @@ -2127,7 +2193,7 @@ impl Py { #[pymethod] fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - let builtins_getattr = vm.builtins.get_attr("getattr", vm)?; + let builtins_getattr = vm.eval_get_builtin(vm.ctx.intern_str("getattr"))?; Ok(vm .ctx .new_tuple(vec![ diff --git a/crates/vm/src/builtins/dict.rs b/crates/vm/src/builtins/dict.rs index d709521ea6d..e517ac2b8a9 100644 --- a/crates/vm/src/builtins/dict.rs +++ b/crates/vm/src/builtins/dict.rs @@ -1,45 +1,332 @@ use super::{ - IterStatus, PositionIterInternal, PyBaseExceptionRef, PyFrozenSet, PyGenericAlias, - PyMappingProxy, PySet, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, locked_step, set, - set::PySetInner, + PyBaseExceptionRef, PyFrozenSet, PyGenericAlias, PyMappingProxy, PySet, PyStr, PyStrRef, + PyTupleRef, PyType, PyTypeRef, set, set::PySetInner, }; use crate::common::lock::LazyLock; use crate::object::{Traverse, TraverseFn}; -use crate::stdlib::PyOrderedDictItems; use crate::{ - AsObject, Context, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, + AsObject, Context, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, atomic_func, builtins::{PyList, PyTuple, iter::builtins_iter, type_::PyAttributes}, class::{PyClassDef, PyClassImpl}, - common::{ascii, hash::PyHash}, + common::{ + ascii, + hash::{self, PyHash}, + }, dict_inner::{self, DictKey}, function::{ArgIterable, FuncArgs, KwArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, protocol::{PyIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, recursion::ReprGuard, types::{ AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, DefaultConstructor, - Initializer, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, + Hashable, Initializer, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, vm::VirtualMachine, }; use alloc::fmt; +use core::borrow::Borrow; use core::cell::Cell; use core::ptr::NonNull; use rustpython_common::atomic::{Ordering, PyAtomic, Radium}; use rustpython_common::lock::PyMutex; use rustpython_common::wtf8::Wtf8Buf; +use rustpython_common::wtf8::wtf8_concat; pub(crate) type DictContentType = dict_inner::Dict; +pub(crate) fn key_hash( + key: &K, + mapping_name: &str, + vm: &VirtualMachine, +) -> PyResult { + key.key_hash(vm) + .map_err(|exc| contextualize_hash_error(key, mapping_name, "key", exc, vm)) +} + +pub(crate) fn contextualize_hash_error( + key: &K, + container: &str, + role: &str, + exc: PyBaseExceptionRef, + vm: &VirtualMachine, +) -> PyBaseExceptionRef { + let format_error = || -> PyResult { + match exc { + // Exact TypeError only: exception subclasses retain their identity. + exc if exc.class().is(vm.ctx.exceptions.type_error) => { + let name = key.to_pyobject(vm).class().fully_qualified_name(vm)?; + // Match BaseException_str without the diagnostic formatter's + // fallback: argument __str__/__repr__ failures must propagate. + let args = exc.args(); + let message = match args.as_slice() { + [] => vm.ctx.empty_str.to_owned(), + [arg] => arg.str(vm)?, + _ => args.as_object().str(vm)?, + }; + Ok(vm.new_type_error(wtf8_concat!( + "cannot use '", + name, + "' as a ", + container, + " ", + role, + " (", + message.as_wtf8(), + ")" + ))) + } + exc => Ok(exc), + } + }; + format_error().unwrap_or_else(|exc| exc) +} + #[pyclass(module = false, name = "dict", unhashable = true, traverse = "manual")] #[derive(Default)] // OrderedDict contains eight-byte-aligned fields on 32-bit targets too. #[repr(align(8))] pub struct PyDict { - entries: DictContentType, + pub(crate) entries: DictContentType, } pub type PyDictRef = PyRef; +/// A borrowed view of a dict or frozendict, including subclasses. +/// +/// This is an erased header view, not a shared payload layout. Every payload +/// access downcasts to the actual alternative, preserving its mutability. +#[repr(transparent)] +pub struct PyAnyDict { + object: PyObject, +} + +// SAFETY: this owner contributes exactly one strong reference to the object. +unsafe impl Traverse for PyRef { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + tracer(self.as_object()); + } +} + +impl crate::convert::ToPyObject for PyRef { + fn to_pyobject(self, _vm: &VirtualMachine) -> PyObjectRef { + self.into_object() + } +} + +impl Borrow for PyAnyDict { + fn borrow(&self) -> &PyObject { + &self.object + } +} + +impl Borrow for PyRef { + fn borrow(&self) -> &PyAnyDict { + self + } +} + +impl ToOwned for PyAnyDict { + type Owned = PyRef; + + fn to_owned(&self) -> PyRef { + // SAFETY: this borrowed view already guarantees a dictionary payload. + unsafe { PyRef::::from_object_unchecked(self.object.to_owned()) } + } +} + +impl From for PyRef { + fn from(dict: PyDictRef) -> Self { + // SAFETY: the typed owner guarantees the dict alternative. + unsafe { Self::from_object_unchecked(dict.into()) } + } +} + +impl From> for PyRef { + fn from(dict: PyRef) -> Self { + // SAFETY: the typed owner guarantees the frozendict alternative. + unsafe { Self::from_object_unchecked(dict.into()) } + } +} + +impl From> for PyObjectRef { + fn from(dict: PyRef) -> Self { + dict.into_object() + } +} + +// SAFETY: the transparent PyRef owner has the same layout as PyObjectRef. +// A successful check proves the actual dict or frozendict payload invariant. +unsafe impl crate::convert::TransmuteFromObject for PyRef { + fn check(vm: &VirtualMachine, obj: &PyObject) -> PyResult<()> { + if PyAnyDict::from_object(obj).is_some() { + Ok(()) + } else { + Err(vm.new_type_error(format!( + "expected dict or frozendict, got {}", + obj.class().name() + ))) + } + } +} + +impl TryFromObject for PyRef { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + ::check(vm, &obj)?; + // SAFETY: the shared checker proved the union view's payload invariant. + Ok(unsafe { Self::from_object_unchecked(obj) }) + } +} + +impl PyAnyDict { + pub fn from_object(obj: &PyObject) -> Option<&Self> { + if obj.downcast_ref::().is_some() || obj.downcast_ref::().is_some() { + // SAFETY: PyAnyDict is transparent over PyObject and the payload was checked. + Some(unsafe { &*(obj as *const PyObject).cast::() }) + } else { + None + } + } + + pub(crate) fn as_mutable(&self) -> Option<&Py> { + self.object.downcast_ref() + } + + pub(crate) fn is_frozen(&self) -> bool { + self.object.downcastable::() + } + + // The raw payload is private: callers outside the VM cannot use it to mutate a frozendict. + pub(crate) fn as_dict(&self) -> &PyDict { + if let Some(dict) = self.as_mutable() { + dict + } else { + &self.object.downcast_ref::().unwrap().dict + } + } + + pub(crate) fn uses_builtin_iter(&self, vm: &VirtualMachine) -> bool { + let base = if self.is_frozen() { + vm.ctx.types.frozendict_type + } else { + vm.ctx.types.dict_type + }; + self.as_object() + .class() + .slots + .iter + .load() + .map(crate::types::fn_addr) + == base.slots.iter.load().map(crate::types::fn_addr) + } + + #[must_use] + pub fn __len__(&self) -> usize { + self.as_dict().__len__() + } + #[must_use] + pub fn is_empty(&self) -> bool { + self.as_dict().is_empty() + } + pub fn copy_as_dict(&self, vm: &VirtualMachine) -> PyResult { + let size = self.size(); + // Sparse copies go through merge, where equality between colliding + // keys remains observable. Dense native tables can be cloned directly. + if size.used == 0 || (self.uses_builtin_iter(vm) && size.used >= size.entries_size * 2 / 3) + { + return Ok(self.as_dict().copy()); + } + let copied = PyDict::default(); + copied.merge_mapping(self.as_object().to_owned(), vm)?; + Ok(copied) + } + + #[must_use] + pub fn keys_vec(&self) -> Vec { + self.as_dict().keys_vec() + } + #[must_use] + pub fn values_vec(&self) -> Vec { + self.as_dict().values_vec() + } + #[must_use] + pub fn items_vec(&self) -> Vec<(PyObjectRef, PyObjectRef)> { + self.as_dict().items_vec() + } + #[must_use] + pub fn next_entry(&self, position: usize) -> Option<(usize, PyObjectRef, PyObjectRef)> { + self.as_dict().next_entry(position) + } + pub(crate) fn size(&self) -> crate::dict_inner::DictSize { + self.as_dict().size() + } + pub fn inner_getitem_opt( + &self, + key: &K, + vm: &VirtualMachine, + ) -> PyResult> { + if let Some(dict) = self.as_mutable() { + dict.inner_getitem_opt(key, vm) + } else { + self.object + .downcast_ref::() + .unwrap() + .inner_getitem_opt(key, vm) + } + } + pub fn get_item_opt( + &self, + key: &K, + vm: &VirtualMachine, + ) -> PyResult> { + if let Some(dict) = self.as_mutable() { + return dict.get_item_opt(key, vm); + } + if self.object.class().is(vm.ctx.types.frozendict_type) { + return self.inner_getitem_opt(key, vm); + } + match self.object.get_item(key, vm) { + Ok(value) => Ok(Some(value)), + Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.key_error) => Ok(None), + Err(exc) => Err(exc), + } + } + pub fn get_item(&self, key: &K, vm: &VirtualMachine) -> PyResult { + if let Some(dict) = self.as_mutable() { + dict.get_item(key, vm) + } else { + self.object.get_item(key, vm) + } + } + pub fn contains_key(&self, key: &K, vm: &VirtualMachine) -> bool { + self.inner_getitem_opt(key, vm) + .is_ok_and(|value| value.is_some()) + } + pub fn set_item( + &self, + key: &K, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + match self.as_mutable() { + Some(dict) => dict.set_item(key, value, vm), + None => Err(vm.new_type_error("frozendict object does not support item assignment")), + } + } + pub fn del_item(&self, key: &K, vm: &VirtualMachine) -> PyResult<()> { + match self.as_mutable() { + Some(dict) => dict.del_item(key, vm), + None => Err(vm.new_type_error("frozendict object does not support item deletion")), + } + } +} + +impl<'a> IntoIterator for &'a PyAnyDict { + type Item = (PyObjectRef, PyObjectRef); + type IntoIter = DictIter<'a>; + fn into_iter(self) -> Self::IntoIter { + DictIter::new(self.as_dict()) + } +} + // SAFETY: Traverse properly visits all owned PyObjectRefs unsafe impl Traverse for PyDict { fn traverse(&self, traverse_fn: &mut TraverseFn<'_>) { @@ -136,50 +423,87 @@ impl PyDict { self.entries.items() } - fn merge_object_with_override( + pub(crate) fn items_with_hashes_vec(&self) -> Vec<(PyObjectRef, PyObjectRef, PyHash)> { + self.entries.items_with_hashes() + } + + /// `dict_update_arg`. `mapping_name` names the target type in the + /// unhashable key error, as `dict_unhashable_type` does. + pub(crate) fn update_arg( &self, other: PyObjectRef, override_existing: bool, + mapping_name: &str, vm: &VirtualMachine, ) -> PyResult<()> { - let casted: Result, _> = other.downcast_exact(vm); - let other = match casted { - Ok(dict_other) => { - return self.merge_dict(&dict_other, override_existing, vm); - } - Err(other) => other, - }; + self.merge_arg(other, override_existing, mapping_name, true, vm) + } + + // PyDict_Update accepts mappings, without dict.update's sequence fallback. + pub(crate) fn merge_mapping(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + self.merge_arg(other, true, "dict", false, vm) + } + + fn merge_arg( + &self, + other: PyObjectRef, + override_existing: bool, + mapping_name: &str, + allow_sequence: bool, + vm: &VirtualMachine, + ) -> PyResult<()> { + if let Some(other_dict) = PyAnyDict::from_object(&other) + && other_dict.uses_builtin_iter(vm) + { + return self.merge_dict(other_dict.as_dict(), override_existing, vm); + } let dict = &self.entries; // Use get_attr to properly invoke __getattribute__ for proxy objects - let keys_result = other.get_attr(vm.ctx.intern_str("keys"), vm); - let has_keys = match keys_result { - Ok(keys_method) => { - let keys = PyIter::try_from_object(vm, keys_method.call((), vm)?)?; - while let PyIterReturn::Return(key) = keys.next(vm)? { - if !override_existing && dict.contains(vm, &*key)? { - continue; - } - let val = other.get_item(&*key, vm)?; - dict.insert(vm, &*key, val)?; - } - true + let keys_method = match other.get_attr(vm.ctx.intern_str("keys"), vm) { + Ok(keys_method) => keys_method, + Err(e) if allow_sequence && e.fast_isinstance(vm.ctx.exceptions.attribute_error) => { + return self.merge_seq2(&other, override_existing, mapping_name, vm); } - Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) => false, Err(e) => return Err(e), }; - if !has_keys { - return self.merge_from_seq2(&other, override_existing, vm); + let keys_result = keys_method.call((), vm); + drop(keys_method); + let keys = other.mapping_unchecked().collect_method_output( + vm.ctx.intern_str("keys"), + keys_result?, + vm, + )?; + let keys = PyIter::try_from_object(vm, keys)?; + while let PyIterReturn::Return(key) = keys.next(vm)? { + if !override_existing { + let hash = key_hash(&*key, mapping_name, vm)?; + if dict.contains(vm, &*key, hash)? { + continue; + } + } + let value = match other.get_item(&*key, vm) { + Ok(value) => value, + Err(exc) => { + drop(keys); + return Err(exc); + } + }; + let outcome = key_hash(&*key, mapping_name, vm) + .and_then(|hash| dict.insert(vm, &*key, hash, value.clone())); + // Keep both owners until insertion returns, including on failure. + drop(key); + outcome?; } Ok(()) } // Used in update and ior. pub fn merge_object(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.merge_object_with_override(other, true, vm) + self.update_arg(other, true, "dict", vm) } pub fn merge_object_if_missing(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.merge_object_with_override(other, false, vm) + self.update_arg(other, false, "dict", vm) } fn add_update_sequence_note( @@ -257,6 +581,17 @@ impl PyDict { seq2: &PyObject, override_existing: bool, vm: &VirtualMachine, + ) -> PyResult<()> { + self.merge_seq2(seq2, override_existing, "dict", vm) + } + + /// `dict_merge_from_seq2` + fn merge_seq2( + &self, + seq2: &PyObject, + override_existing: bool, + mapping_name: &str, + vm: &VirtualMachine, ) -> PyResult<()> { let iter = seq2.get_iter(vm)?; let dict = &self.entries; @@ -264,33 +599,41 @@ impl PyDict { for (index, element) in iter.iter::(vm)?.enumerate() { let (key, value) = Self::update_sequence_pair(element?, index, vm)?; - if !override_existing && dict.contains(vm, &*key)? { + let hash = key_hash(&*key, mapping_name, vm)?; + if !override_existing && dict.contains(vm, &*key, hash)? { continue; } - dict.insert(vm, &*key, value)?; + dict.insert(vm, &*key, hash, value)?; } Ok(()) } pub(crate) fn merge_dict( &self, - dict_other: &Py, + dict_other: &Self, override_existing: bool, vm: &VirtualMachine, ) -> PyResult<()> { let dict = &self.entries; - let dict_size = &dict_other.size(); + let source_len = dict_other.__len__(); let mut position = 0; while let Some((next, key, value, hash)) = dict_other.entries.next_entry_with_hash(position) { position = next; - if !override_existing && dict.contains_known_hash(vm, &*key, hash)? { - continue; + let outcome: PyResult<()> = (|| { + if override_existing || !dict.contains(vm, &*key, hash)? { + dict.insert(vm, &*key, hash, value.clone())?; + } + Ok(()) + })(); + // Release current references before checking mutations from + // comparisons or finalizers, including a skipped existing key. + drop(value); + drop(key); + outcome?; + if dict_other.__len__() != source_len { + return Err(vm.new_runtime_error("dict mutated during update")); } - dict.insert_known_hash(vm, &*key, hash, value)?; - } - if dict_other.entries.has_changed_size(dict_size) { - return Err(vm.new_runtime_error("dict mutated during update")); } Ok(()) } @@ -299,6 +642,21 @@ impl PyDict { self.entries.len() == 0 } + /// Hash `key`, turning a hashing failure into the dict-specific + /// "cannot use 'X' as a dict key (...)" wording. + /// + /// The returned hash is passed into the inner map, so the key is hashed + /// exactly once. A `TypeError` from key comparison (e.g. a colliding key's + /// `__eq__`) is raised by the operation itself and must propagate unchanged. + /// Hashing up front also means a `__hash__` that fails only intermittently + /// is still reported. + pub(crate) fn hash_or_unhashable( + key: &K, + vm: &VirtualMachine, + ) -> PyResult { + key_hash(key, "dict", vm) + } + /// Set item variant which can be called with multiple /// key types, such as str to name a notable one. pub fn inner_setitem( @@ -307,15 +665,26 @@ impl PyDict { value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - self.entries.insert(vm, key, value) + let hash = Self::hash_or_unhashable(key, vm)?; + self.entries.insert(vm, key, hash, value) + } + + pub fn inner_delitem(&self, key: &K, vm: &VirtualMachine) -> PyResult<()> { + let hash = Self::hash_or_unhashable(key, vm)?; + if self.entries.delete_if_exists(vm, key, hash)? { + Ok(()) + } else { + Err(vm.new_key_error(key.to_pyobject(vm))) + } } - pub(crate) fn inner_delitem( + pub(crate) fn inner_pop_item( &self, key: &K, vm: &VirtualMachine, - ) -> PyResult<()> { - self.entries.delete(vm, key) + ) -> PyResult> { + let hash = Self::hash_or_unhashable(key, vm)?; + self.entries.remove_if_exists(vm, key, hash) } pub fn get_or_insert( @@ -324,21 +693,24 @@ impl PyDict { key: &PyObject, default: impl FnOnce() -> PyObjectRef, ) -> PyResult { - self.entries.setdefault(vm, key, default) + let hash = Self::hash_or_unhashable(key, vm)?; + self.entries.setdefault(vm, key, hash, default) } pub fn from_attributes(attrs: PyAttributes, vm: &VirtualMachine) -> PyResult { let entries = DictContentType::default(); for (key, value) in attrs { - entries.insert(vm, key, value)?; + let hash = key.key_hash(vm)?; + entries.insert(vm, key, hash, value)?; } Ok(Self { entries }) } pub fn contains_key(&self, key: &K, vm: &VirtualMachine) -> bool { - self.entries.contains(vm, key).unwrap() + let hash = key.key_hash(vm).unwrap(); + self.entries.contains(vm, key, hash).unwrap() } pub fn size(&self) -> dict_inner::DictSize { @@ -354,7 +726,8 @@ impl PyDict { key: &K, vm: &VirtualMachine, ) -> PyResult> { - self.entries.get(vm, key) + let hash = Self::hash_or_unhashable(key, vm)?; + self.entries.get(vm, key, hash) } /// Keys of `obj` with their stored hashes, or `None` if it must be iterated @@ -366,6 +739,8 @@ impl PyDict { ) -> Option> { if let Some(dict) = obj.downcast_ref_if_exact::(vm) { Some(dict.entries.keys_with_hashes()) + } else if let Some(frozen) = obj.downcast_ref_if_exact::(vm) { + Some(frozen.dict.entries.keys_with_hashes()) } else { set::exact_set_keys_with_hashes(obj, vm) } @@ -383,19 +758,55 @@ struct DictGetArgs { #[derive(FromArgs)] struct FromKeysArgs { #[pyarg(positional)] - iterable: ArgIterable, + iterable: PyObjectRef, #[pyarg(positional, optional)] value: Option, } // Python dict methods: impl PyDict { + pub(crate) fn compare_entries( + &self, + other: &Self, + op: PyComparisonOp, + item: bool, + vm: &VirtualMachine, + ) -> PyResult { + if op == PyComparisonOp::Ne { + return Self::compare_entries(self, other, PyComparisonOp::Eq, item, vm) + .map(|x| x.map(|eq| !eq)); + } + if !op.eval_ord(self.__len__().cmp(&other.__len__())) { + return Ok(PyArithmeticValue::Implemented(false)); + } + let mut position = 0; + while let Some((next, k, v1, hash)) = self.entries.next_entry_with_hash(position) { + position = next; + let found = other.entries.get(vm, &*k, hash)?; + match found { + Some(v2) => { + if v1.is(&v2) { + continue; + } + if item && !vm.bool_eq(&v1, &v2)? { + return Ok(PyArithmeticValue::Implemented(false)); + } + } + None => { + return Ok(PyArithmeticValue::Implemented(false)); + } + } + } + Ok(PyArithmeticValue::Implemented(true)) + } + pub fn __len__(&self) -> usize { self.entries.len() } fn __contains__(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult { - self.entries.contains(vm, key) + let hash = Self::hash_or_unhashable(key, vm)?; + self.entries.contains(vm, key, hash) } fn __delitem__(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult<()> { @@ -406,24 +817,14 @@ impl PyDict { self.inner_setitem(key, value, vm) } - pub(crate) fn setdefault( + pub(crate) fn setdefault_value( &self, key: PyObjectRef, default: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - self.entries.setdefault(vm, &*key, || default) - } - - fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // Accept dict subclasses that inherit this implementation. Subclasses with - // their own reflected slot, such as OrderedDict, take precedence in dispatch. - if let Ok(other) = other.downcast::() { - let self_cp = self.copy(); - self_cp.merge_dict(&other, true, vm)?; - return Ok(self_cp.into_pyobject(vm)); - } - Ok(vm.ctx.not_implemented()) + let hash = Self::hash_or_unhashable(&*key, vm)?; + self.entries.setdefault(vm, &*key, hash, || default) } pub(crate) fn __sizeof__(&self) -> usize { @@ -448,7 +849,8 @@ impl PyDict { self.merge_object(dict_obj, vm)?; } for (key, value) in kwargs { - self.entries.insert(vm, &key, value)?; + let hash = Self::hash_or_unhashable(&key, vm)?; + self.entries.insert(vm, &key, hash, value)?; } Ok(()) } @@ -467,96 +869,26 @@ impl PyDict { AsMapping, Representable ), - flags(BASETYPE, MAPPING, _MATCH_SELF) + flags(BASETYPE, MAPPING, _MATCH_SELF, DICT_SUBCLASS) )] impl PyDict {} #[pyclass] impl Py { - pub(crate) fn inner_cmp( - &self, - other: &Self, - op: PyComparisonOp, - item: bool, - vm: &VirtualMachine, - ) -> PyResult { - if op == PyComparisonOp::Ne { - return Self::inner_cmp(self, other, PyComparisonOp::Eq, item, vm) - .map(|x| x.map(|eq| !eq)); - } - if !op.eval_ord(self.__len__().cmp(&other.__len__())) { - return Ok(PyArithmeticValue::Implemented(false)); - } - let (superset, subset) = if self.__len__() < other.__len__() { - (other, self) - } else { - (self, other) - }; - for (k, v1) in subset { - match superset.get_item_opt(&*k, vm)? { - Some(v2) => { - if v1.is(&v2) { - continue; - } - if item && !vm.bool_eq(&v1, &v2)? { - return Ok(PyArithmeticValue::Implemented(false)); - } - } - None => { - return Ok(PyArithmeticValue::Implemented(false)); - } - } - } - Ok(PyArithmeticValue::Implemented(true)) - } - #[cfg_attr(feature = "flame-it", flame("PyDictRef"))] #[pymethod(coexist)] fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.inner_getitem(&*key, vm) } - fn __ror__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let other_dict = other.downcast::(); - if let Ok(other) = other_dict { - let other_cp = other.copy(); - other_cp.merge_dict(self, true, vm)?; - return Ok(other_cp.into_pyobject(vm)); - } - Ok(vm.ctx.not_implemented()) - } - #[pyclassmethod] fn fromkeys(class: PyTypeRef, args: FromKeysArgs, vm: &VirtualMachine) -> PyResult { - let FromKeysArgs { iterable, value } = args; - let value = value.unwrap_or_else(|| vm.ctx.none()); - let d = PyType::call(&class, ().into(), vm)?; - match d.downcast_exact::(vm) { - Ok(pydict) => { - if let Some(keys) = PyDict::fromkeys_known_hashes(iterable.as_object(), vm) { - if class.is(vm.ctx.types.dict_type) { - pydict.entries.reserve_for_empty(keys.len()); - } - for (key, hash) in keys { - pydict - .entries - .insert_known_hash(vm, &*key, hash, value.clone())?; - } - } else { - for key in iterable.iter(vm)? { - let key = key?; - pydict.__setitem__(&key, value.clone(), vm)?; - } - } - Ok(pydict.into_pyref().into()) - } - Err(pyobj) => { - for key in iterable.iter(vm)? { - pyobj.set_item(&*key?, value.clone(), vm)?; - } - Ok(pyobj) - } - } + dict_fromkeys( + class, + args.iterable, + args.value.unwrap_or_else(|| vm.ctx.none()), + vm, + ) } #[pymethod] @@ -571,16 +903,15 @@ impl Py { #[pymethod] fn get(&self, args: DictGetArgs, vm: &VirtualMachine) -> PyResult { - Ok(self - .entries - .get(vm, &*args.key)? - .unwrap_or_else(|| args.default.unwrap_or_else(|| vm.ctx.none()))) + let hash = PyDict::hash_or_unhashable(&*args.key, vm)?; + let found = self.entries.get(vm, &*args.key, hash)?; + Ok(found.unwrap_or_else(|| args.default.unwrap_or_else(|| vm.ctx.none()))) } - #[pymethod(name = "setdefault")] - fn setdefault_py(&self, args: DictGetArgs, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn setdefault(&self, args: DictGetArgs, vm: &VirtualMachine) -> PyResult { let default = args.default.unwrap_or_else(|| vm.ctx.none()); - self.setdefault(args.key, default, vm) + self.setdefault_value(args.key, default, vm) } #[pymethod] @@ -606,7 +937,8 @@ impl Py { default: OptionalArg, vm: &VirtualMachine, ) -> PyResult { - match self.entries.pop(vm, &*key)? { + let hash = PyDict::hash_or_unhashable(&*key, vm)?; + match self.entries.pop(vm, &*key, hash)? { Some(value) => Ok(value), None => default.ok_or_else(|| vm.new_key_error(key)), } @@ -637,23 +969,23 @@ impl Py { #[pyclass] impl PyRef { #[pymethod] - const fn keys(self) -> PyDictKeys { - PyDictKeys::new(self) + fn keys(self) -> PyDictKeys { + PyDictKeys::new(self.into()) } #[pymethod] - const fn values(self) -> PyDictValues { - PyDictValues::new(self) + fn values(self) -> PyDictValues { + PyDictValues::new(self.into()) } #[pymethod] - const fn items(self) -> PyDictItems { - PyDictItems::new(self) + fn items(self) -> PyDictItems { + PyDictItems::new(self.into()) } #[pymethod] fn __reversed__(self) -> PyDictReverseKeyIterator { - PyDictReverseKeyIterator::new(self) + PyDictReverseKeyIterator::new(self.into()) } fn __ior__(self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { @@ -699,9 +1031,12 @@ impl AsMapping for PyDict { impl AsSequence for PyDict { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock = LazyLock::new(|| PySequenceMethods { - contains: atomic_func!(|seq, target, vm| PyDict::sequence_downcast(seq) - .entries - .contains(vm, target)), + contains: atomic_func!(|seq, target, vm| { + let hash = PyDict::hash_or_unhashable(target, vm)?; + PyDict::sequence_downcast(seq) + .entries + .contains(vm, target, hash) + }), ..PySequenceMethods::NOT_IMPLEMENTED }); &AS_SEQUENCE @@ -711,14 +1046,8 @@ impl AsSequence for PyDict { impl AsNumber for PyDict { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { - or: Some(|a, b, vm| { - if let Some(a) = a.downcast_ref::() { - PyDict::__or__(a, b.to_pyobject(vm), vm) - } else { - Ok(vm.ctx.not_implemented()) - } - }), - inplace_or: Some(|a, b, vm| { + or: Some(dict_or), + inplace_or: Some(|a, b, vm| { if let Some(a) = a.downcast_ref::() { a.to_owned() .__ior__(b.to_pyobject(vm), vm) @@ -740,16 +1069,19 @@ impl Comparable for PyDict { op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - op.eq_only(|| { - let other = class_or_notimplemented!(Self, other); - zelf.inner_cmp(other, PyComparisonOp::Eq, true, vm) + op.eq_only(|| match PyAnyDict::from_object(other) { + Some(other) => { + zelf.payload + .compare_entries(other.as_dict(), PyComparisonOp::Eq, true, vm) + } + None => Ok(PyComparisonValue::NotImplemented), }) } } impl Iterable for PyDict { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - Ok(PyDictKeyIterator::new(zelf).into_pyobject(vm)) + Ok(PyDictKeyIterator::new(zelf.into()).into_pyobject(vm)) } } @@ -804,7 +1136,9 @@ impl Py { key: &K, vm: &VirtualMachine, ) -> PyResult { - if let Some(value) = self.entries.get(vm, key)? { + let hash = PyDict::hash_or_unhashable(key, vm)?; + let found = self.entries.get(vm, key, hash)?; + if let Some(value) = found { Ok(value) } else if let Some(value) = self.missing_opt(key, vm)? { Ok(value) @@ -854,7 +1188,7 @@ impl Py { hash: crate::common::hash::PyHash, vm: &VirtualMachine, ) -> PyResult> { - self.entries.get_known_hash(vm, key, hash) + self.entries.get(vm, key, hash) } pub(crate) fn set_item_known_hash( @@ -864,20 +1198,7 @@ impl Py { value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - self.entries.insert_known_hash(vm, key, hash, value) - } - - pub(crate) fn del_item_known_hash( - &self, - key: &PyObject, - hash: crate::common::hash::PyHash, - vm: &VirtualMachine, - ) -> PyResult<()> { - if self.entries.delete_if_exists_known_hash(vm, key, hash)? { - Ok(()) - } else { - Err(vm.new_key_error(key.to_owned())) - } + self.entries.insert(vm, key, hash, value) } pub(crate) fn contains_known_hash( @@ -886,7 +1207,7 @@ impl Py { hash: crate::common::hash::PyHash, vm: &VirtualMachine, ) -> PyResult { - self.entries.contains_known_hash(vm, key, hash) + self.entries.contains(vm, key, hash) } pub fn get_item_opt( @@ -895,7 +1216,8 @@ impl Py { vm: &VirtualMachine, ) -> PyResult> { if self.exact_dict(vm) { - self.entries.get(vm, key) + let hash = PyDict::hash_or_unhashable(key, vm)?; + self.entries.get(vm, key, hash) // Match CPython's exact-dict fast path: __missing__ only participates // for dict subclasses through the generic mapping lookup path below. } else { @@ -916,7 +1238,8 @@ impl Py { vm: &VirtualMachine, ) -> PyResult> { if self.exact_dict(vm) { - self.entries.hint_for_key(vm, key) + let hash = PyDict::hash_or_unhashable(key, vm)?; + self.entries.hint_for_key(vm, key, hash) } else { Ok(None) } @@ -944,15 +1267,28 @@ impl Py { vm: &VirtualMachine, ) -> PyResult)>> { if self.exact_dict(vm) { - if let Some(value) = self.entries.get_hint(vm, key, usize::from(hint))? { + if let Some(value) = self.entries.get_hint(key, usize::from(hint)) { return Ok(Some((value, None))); } - self.entries.get_with_hint(vm, key) + let hash = PyDict::hash_or_unhashable(key, vm)?; + self.entries.get_with_hint(vm, key, hash) } else { Ok(self.get_item_opt(key, vm)?.map(|value| (value, None))) } } + pub(crate) fn replace_if_identity( + &self, + name: &Py, + expected: &PyObject, + replacement: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + let hash = PyDict::hash_or_unhashable(name, vm)?; + self.entries + .replace_if(vm, name, hash, replacement, |current| current.is(expected)) + } + /// Store using a cached entry index hint for the value-replace fast path. /// /// On a hint miss, returns a refreshed hint for the key (`None` when the @@ -965,8 +1301,9 @@ impl Py { vm: &VirtualMachine, ) -> PyResult> { if self.exact_dict(vm) { + let hash = PyDict::hash_or_unhashable(key, vm)?; self.entries - .insert_with_hint(vm, key, usize::from(hint), value) + .insert_with_hint(vm, key, hash, usize::from(hint), value) } else { self.as_object().set_item(key, value, vm)?; Ok(None) @@ -1055,7 +1392,7 @@ impl Py { vm: &VirtualMachine, ) -> PyResult> { if self.exact_dict(vm) { - self.entries.remove_if_exists(vm, key) + self.inner_pop_item(key, vm) } else { let value = self.as_object().get_item(key, vm)?; self.as_object().del_item(key, vm)?; @@ -1085,6 +1422,17 @@ impl Py { } impl PyExact { + pub(crate) fn move_to_end( + &self, + key: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + let hash = PyDict::hash_or_unhashable(&*key, vm)?; + self.entries + .move_to_end(vm, &*key, hash)? + .ok_or_else(|| vm.new_key_error(key)) + } + /// Look up `key` in `self`, falling back to `other`. /// Both dicts must be exact `dict` types (enforced by `PyExact`). pub(crate) fn get_chain_exact( @@ -1095,7 +1443,292 @@ impl PyExact { ) -> PyResult> { debug_assert!(self.class().is(vm.ctx.types.dict_type)); debug_assert!(other.class().is(vm.ctx.types.dict_type)); - self.entries.get_chain(&other.entries, vm, key) + let hash = PyDict::hash_or_unhashable(key, vm)?; + self.entries.get_chain(&other.entries, vm, key, hash) + } +} + +#[pyclass(module = false, name = "frozendict", traverse = "manual")] +#[derive(Debug)] +pub struct PyFrozenDict { + // Own the table directly, never a mutable Python dict visible through gc or a view. + pub(crate) dict: PyDict, + hash: PyAtomic, +} + +unsafe impl Traverse for PyFrozenDict { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.dict.traverse(tracer); + } + fn clear(&mut self, out: &mut Vec) { + Traverse::clear(&mut self.dict, out); + } +} + +impl PyPayload for PyFrozenDict { + fn class(ctx: &Context) -> &'static Py { + ctx.types.frozendict_type + } +} + +impl PyFrozenDict { + pub(crate) fn from_dict(dict: PyDict) -> Self { + Self { + dict, + hash: Radium::new(hash::SENTINEL), + } + } + + /// Hash a dictionary key, adding the frozendict context to an exact TypeError. + pub fn key_hash(key: &K, vm: &VirtualMachine) -> PyResult { + key_hash(key, "frozendict", vm) + } + + pub fn inner_getitem_opt( + &self, + key: &K, + vm: &VirtualMachine, + ) -> PyResult> { + let hash = Self::key_hash(key, vm)?; + self.dict.entries.get(vm, key, hash) + } +} + +impl Constructor for PyFrozenDict { + type Args = (OptionalArg, KwArgs); + fn py_new( + _cls: &Py, + (input, kwargs): Self::Args, + vm: &VirtualMachine, + ) -> PyResult { + // The table is built before the frozendict is published, as + // frozendict_new_untracked keeps it away from the GC. + let dict = PyDict::default(); + if let OptionalArg::Present(input) = input { + dict.update_arg(input, true, "frozendict", vm)?; + } + for (key, value) in kwargs { + dict.inner_setitem(&key, value, vm)?; + } + Ok(Self::from_dict(dict)) + } +} + +#[pyclass( + with( + Py, + PyRef, + Constructor, + Hashable, + Comparable, + Iterable, + AsMapping, + AsSequence, + AsNumber, + Representable + ), + flags(BASETYPE, MAPPING, _MATCH_SELF) +)] +impl PyFrozenDict { + fn __len__(&self) -> usize { + self.dict.__len__() + } + + #[pymethod] + fn get( + zelf: &Py, + DictGetArgs { key, default }: DictGetArgs, + vm: &VirtualMachine, + ) -> PyResult { + Ok(zelf + .inner_getitem_opt(&*key, vm)? + .unwrap_or_else(|| default.unwrap_or_else(|| vm.ctx.none()))) + } + + #[pymethod] + fn __sizeof__(zelf: &Py) -> usize { + zelf.dict.__sizeof__() + core::mem::size_of::>() + } + + #[pyclassmethod] + fn fromkeys( + cls: PyTypeRef, + FromKeysArgs { iterable, value }: FromKeysArgs, + vm: &VirtualMachine, + ) -> PyResult { + dict_fromkeys(cls, iterable, value.unwrap_or_else(|| vm.ctx.none()), vm) + } + + #[pyclassmethod] + fn __class_getitem__( + cls: PyTypeRef, + object: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + PyGenericAlias::from_args(cls, object, vm) + } +} + +#[pyclass] +impl Py { + #[pymethod(coexist)] + fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { + if let Some(value) = self.inner_getitem_opt(&*key, vm)? { + return Ok(value); + } + if !self.class().is(vm.ctx.types.frozendict_type) + && let Some(method) = + vm.get_method(self.to_owned().into(), identifier!(vm, __missing__)) + { + return method?.call((key,), vm); + } + Err(vm.new_key_error(key)) + } + + #[pymethod] + fn copy(&self, vm: &VirtualMachine) -> PyResult> { + if self.class().is(vm.ctx.types.frozendict_type) { + Ok(self.to_owned()) + } else { + let dict = PyDict::default(); + if !self.dict.is_empty() { + dict.update_arg(self.to_owned().into(), true, "frozendict", vm)?; + } + Ok(PyFrozenDict::from_dict(dict).into_ref(&vm.ctx)) + } + } + + #[pymethod] + fn __getnewargs__(&self, vm: &VirtualMachine) -> PyResult { + let dict = vm + .ctx + .types + .dict_type + .as_object() + .call((self.to_owned(),), vm)?; + Ok(vm.new_tuple((dict,))) + } +} + +#[pyclass] +impl PyRef { + #[pymethod] + fn keys(self) -> PyDictKeys { + PyDictKeys::new(self.into()) + } + #[pymethod] + fn values(self) -> PyDictValues { + PyDictValues::new(self.into()) + } + #[pymethod] + fn items(self) -> PyDictItems { + PyDictItems::new(self.into()) + } + #[pymethod] + fn __reversed__(self) -> PyDictReverseKeyIterator { + PyDictReverseKeyIterator::new(self.into()) + } +} + +impl AsMapping for PyFrozenDict { + fn as_mapping() -> &'static PyMappingMethods { + static METHODS: PyMappingMethods = PyMappingMethods { + length: atomic_func!(|obj, _vm| Ok(PyFrozenDict::mapping_downcast(obj).__len__())), + subscript: atomic_func!( + |obj, key, vm| PyFrozenDict::mapping_downcast(obj).__getitem__(key.to_owned(), vm) + ), + ass_subscript: None, + }; + &METHODS + } +} +impl AsSequence for PyFrozenDict { + fn as_sequence() -> &'static PySequenceMethods { + static METHODS: LazyLock = LazyLock::new(|| PySequenceMethods { + contains: atomic_func!(|obj, key, vm| Ok(PyFrozenDict::sequence_downcast(obj) + .inner_getitem_opt(key, vm)? + .is_some())), + ..PySequenceMethods::NOT_IMPLEMENTED + }); + &METHODS + } +} +impl AsNumber for PyFrozenDict { + fn as_number() -> &'static PyNumberMethods { + static METHODS: PyNumberMethods = PyNumberMethods { + or: Some(frozendict_or), + ..PyNumberMethods::NOT_IMPLEMENTED + }; + &METHODS + } +} +impl Iterable for PyFrozenDict { + fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + Ok(PyDictKeyIterator::new(zelf.into()).into_pyobject(vm)) + } +} +impl Comparable for PyFrozenDict { + fn cmp( + zelf: &Py, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult { + op.eq_only(|| match PyAnyDict::from_object(other) { + Some(other) => zelf + .dict + .compare_entries(other.as_dict(), PyComparisonOp::Eq, true, vm), + None => Ok(PyComparisonValue::NotImplemented), + }) + } +} +impl Hashable for PyFrozenDict { + fn hash(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let cached = zelf.hash.load(Ordering::Relaxed); + if cached != hash::SENTINEL { + return Ok(cached); + } + let mut hasher = hash::FrozenSetHash::new(zelf.__len__()); + let mut position = 0; + while let Some((next, _key, value, key_hash)) = + zelf.dict.entries.next_entry_with_hash(position) + { + position = next; + // next_entry releases the table lock before invoking arbitrary Python __hash__. + let pair_hash = hash::hash_tuple([Ok(key_hash), value.hash(vm)])?; + hasher.add(pair_hash); + } + let result = hasher.finish(); + zelf.hash.store(result, Ordering::Relaxed); + Ok(result) + } +} +impl Representable for PyFrozenDict { + fn repr(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let name = zelf.class().name(); + if zelf.dict.is_empty() { + return Ok(vm.ctx.new_str(format!("{name}()"))); + } + let mut result = Wtf8Buf::from(format!("{name}(")); + if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { + result.push_str("{"); + for (index, (key, value)) in DictIter::new(&zelf.dict).enumerate() { + if index != 0 { + result.push_str(", "); + } + result.push_wtf8(key.repr(vm)?.as_wtf8()); + result.push_str(": "); + result.push_wtf8(value.repr(vm)?.as_wtf8()); + } + result.push_str("}"); + } else { + result.push_str("{...}"); + } + result.push_str(")"); + Ok(vm.ctx.new_str(result)) + } + fn repr_str(_zelf: &Py, _vm: &VirtualMachine) -> PyResult { + unreachable!("use repr instead") } } @@ -1160,12 +1793,12 @@ impl ExactSizeIterator for DictIntoIter { } pub struct DictIter<'a> { - dict: &'a Py, + dict: &'a PyDict, position: usize, } impl<'a> DictIter<'a> { - pub const fn new(dict: &'a Py) -> Self { + pub const fn new(dict: &'a PyDict) -> Self { DictIter { dict, position: 0 } } } @@ -1195,8 +1828,7 @@ impl ExactSizeIterator for DictIter<'_> { trait DictView: PyPayload + PyClassDef + Iterable + Representable { type ReverseIter: PyPayload + core::fmt::Debug; - fn dict(&self) -> &Py; - fn item(vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef) -> PyObjectRef; + fn dict(&self) -> &PyAnyDict; fn __len__(&self) -> usize { self.dict().__len__() @@ -1206,6 +1838,174 @@ trait DictView: PyPayload + PyClassDef + Iterable + Representable { fn __reversed__(zelf: &Py) -> Self::ReverseIter; } +#[derive(Debug, Clone)] +struct DictIterState { + dict: Option>, + size: dict_inner::DictSize, + position: usize, + remaining: usize, + changed: bool, + reversed: bool, +} + +// SAFETY: the optional dictionary is the sole owned Python reference and is +// visited once. The remaining fields contain only scalar iterator state. +unsafe impl Traverse for DictIterState { + fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { + self.dict.traverse(tracer_fn) + } +} + +enum DictIterError { + SizeChanged, + KeysChanged, +} + +type DictIterStep = (Result, DictIterError>, Option>); + +impl DictIterState { + fn new(dict: PyRef, reversed: bool) -> Self { + let size = dict.size(); + // usize::MAX represents the position before the first reverse entry. + let position = if reversed { + size.entries_size.wrapping_sub(1) + } else { + 0 + }; + Self { + dict: Some(dict), + position, + remaining: size.used, + size, + changed: false, + reversed, + } + } + + fn length_hint(&self) -> usize { + match &self.dict { + Some(dict) + if !self.changed && dict.size().has_same_used_and_relocations(&self.size) => + { + self.remaining + } + _ => 0, + } + } + + // Only clone the projected references while the table and iterator are + // locked. Allocation and the final release of the dictionary happen later. + fn step(&mut self, project: impl FnOnce(&PyObject, &PyObjectRef) -> T) -> DictIterStep { + let Some(dict) = &self.dict else { + return (Ok(None), None); + }; + if self.changed { + return (Err(DictIterError::SizeChanged), None); + } + let remaining = self.remaining; + let project = + |key: &PyObject, value: &PyObjectRef| (remaining != 0).then(|| project(key, value)); + let entries = &dict.as_dict().entries; + let entry = if self.reversed { + entries.prev_entry_checked(self.position, &self.size, project) + } else { + entries.next_dict_entry_checked(self.position, &self.size, project) + }; + match entry { + Err(dict_inner::DictChanged) => { + // Size failure is sticky and retains the dictionary owner. + self.changed = true; + (Err(DictIterError::SizeChanged), None) + } + Ok(Some((_, None))) => { + // Excess keys exhaust the iterator rather than latching a + // size failure. Its detached dictionary must be dropped unlocked. + (Err(DictIterError::KeysChanged), self.dict.take()) + } + Ok(Some((position, Some(item)))) => { + self.position = if self.reversed { + position.wrapping_sub(1) + } else { + position + }; + self.remaining -= 1; + (Ok(Some(item)), None) + } + Ok(None) => (Ok(None), self.dict.take()), + } + } +} + +fn finish_dict_iter_step(step: DictIterStep, vm: &VirtualMachine) -> PyResult> { + let (result, _released) = step; + result.map_err(|error| { + let message = match error { + DictIterError::SizeChanged => "dictionary changed size during iteration", + DictIterError::KeysChanged => "dictionary keys changed during iteration", + }; + vm.new_runtime_error(message) + }) +} + +macro_rules! dict_iterator { + ($name:ident, $class:ident, $class_name:literal, $reversed:literal, $project:expr, $result:expr) => { + #[pyclass(module = false, name = $class_name, traverse)] + #[derive(Debug)] + pub(crate) struct $name { + internal: PyMutex, + } + + impl PyPayload for $name { + #[inline] + fn class(ctx: &Context) -> &'static Py { + ctx.types.$class + } + } + + impl $name { + pub(crate) fn new(dict: PyRef) -> Self { + Self { + internal: PyMutex::new(DictIterState::new(dict, $reversed)), + } + } + } + + #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] + impl Py<$name> { + #[pymethod] + fn __length_hint__(&self) -> usize { + self.internal.lock().length_hint() + } + + #[pymethod] + fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { + // Walk a copy through the same checks as next(), without + // advancing or invalidating the original iterator on failure. + let mut state = self.internal.lock().clone(); + let mut entries = Vec::new(); + while let Some(item) = finish_dict_iter_step(state.step($project), vm)? { + entries.push(($result)(vm, item)); + } + let list = vm.ctx.new_list(entries); + let iter = builtins_iter(vm)?; + Ok(vm.new_tuple((iter, (list,)))) + } + } + + impl SelfIter for $name {} + + impl IterNext for $name { + fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let step = zelf.internal.lock().step($project); + match finish_dict_iter_step(step, vm)? { + Some(item) => Ok(PyIterReturn::Return(($result)(vm, item))), + None => Ok(PyIterReturn::StopIteration(None)), + } + } + } + }; +} + macro_rules! dict_view { ( $name: ident, @@ -1221,14 +2021,14 @@ macro_rules! dict_view { $project_fn: expr, $result_fn: expr ) => { - #[pyclass(module = false, name = $class_name, unhashable = $unhashable)] + #[pyclass(module = false, name = $class_name, unhashable = $unhashable, traverse)] #[derive(Debug)] pub(crate) struct $name { - pub(crate) dict: PyDictRef, + pub(crate) dict: PyRef, } impl $name { - pub(crate) const fn new(dict: PyDictRef) -> Self { + pub(crate) fn new(dict: PyRef) -> Self { $name { dict } } } @@ -1236,14 +2036,10 @@ macro_rules! dict_view { impl DictView for $name { type ReverseIter = $reverse_iter_name; - fn dict(&self) -> &Py { + fn dict(&self) -> &PyAnyDict { &self.dict } - fn item(vm: &VirtualMachine, key: PyObjectRef, value: PyObjectRef) -> PyObjectRef { - $result_fn(vm, $project_fn(&key, &value)) - } - fn __reversed__(zelf: &Py) -> Self::ReverseIter { $reverse_iter_name::new(zelf.dict.clone()) } @@ -1265,19 +2061,21 @@ macro_rules! dict_view { #[inline] fn repr(zelf: &Py, vm: &VirtualMachine) -> PyResult { let s = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { - let mut result = Wtf8Buf::from(format!("{}([", Self::NAME)); - let mut first = true; - for (key, value) in zelf.dict().clone() { - if !first { - result.push_str(", "); - } - first = false; - result.push_wtf8(Self::item(vm, key, value).repr(vm)?.as_wtf8()); - } - result.push_str("])"); + // CPython snapshots through the view's actual iterator before + // calling element representations, including for OrderedDict subclasses. + let items = ArgIterable::::try_from_object( + vm, + zelf.as_object().to_owned(), + )? + .iter(vm)? + .collect::>>()?; + let list_repr = vm.ctx.new_list(items).as_object().repr(vm)?; + let mut result = Wtf8Buf::from(format!("{}(", zelf.class().slot_name())); + result.push_wtf8(list_repr.as_wtf8()); + result.push_str(")"); vm.ctx.new_str(result) } else { - vm.ctx.intern_str("{...}").to_owned() + vm.ctx.intern_str("...").to_owned() }; Ok(s) } @@ -1288,217 +2086,13 @@ macro_rules! dict_view { } } - #[pyclass(module = false, name = $iter_class_name)] - #[derive(Debug)] - pub(crate) struct $iter_name { - pub(crate) size: dict_inner::DictSize, - /// Whether the dict was found to have changed, which - /// `dictiter_iternextkey()` records by writing a size no dict can - /// have. Sticky: what it makes the iterator answer, it answers - /// from then on. - changed: PyAtomic, - pub(crate) internal: PyMutex>, - } - - impl PyPayload for $iter_name { - #[inline] - fn class(ctx: &Context) -> &'static Py { - ctx.types.$iter_class - } + dict_iterator! { + $iter_name, $iter_class, $iter_class_name, false, $project_fn, $result_fn } - impl $iter_name { - fn new(dict: PyDictRef) -> Self { - $iter_name { - size: dict.size(), - changed: Radium::new(false), - internal: PyMutex::new(PositionIterInternal::new(dict, 0)), - } - } - } - - #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] - impl Py<$iter_name> { - #[pymethod] - fn __length_hint__(&self) -> usize { - // `dictiter_len()` answers for a dict it can no longer walk - // with nothing, comparing the size it captured against the - // dict's own every time it is asked. - if self.changed.load(Ordering::Relaxed) { - return 0; - } - self.internal.lock().length_hint(|dict| { - if dict.size() == self.size { - self.size.entries_size - } else { - 0 - } - }) - } - - #[pymethod] - fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { - let iter = builtins_iter(vm)?; - let internal = self.internal.lock(); - let entries = match &internal.status { - IterStatus::Active(dict) => { - let mut position = internal.position; - let mut entries = Vec::new(); - while let Some((next_position, key, value)) = - dict.entries.next_entry(position) - { - entries.push(($result_fn)(vm, ($project_fn)(&key, &value))); - position = next_position; - } - entries - } - IterStatus::Exhausted => vec![], - }; - Ok(vm.new_tuple((iter, (vm.ctx.new_list(entries),)))) - } - } - - impl SelfIter for $iter_name {} - - impl IterNext for $iter_name { - fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_step(&zelf.internal, |internal| { - let IterStatus::Active(dict) = &internal.status else { - return (Ok(PyIterReturn::StopIteration(None)), None); - }; - let mutated = - || vm.new_runtime_error("dictionary changed size during iteration"); - if zelf.changed.load(Ordering::Relaxed) { - // The dict is not looked at again once it has been - // found to change: an iterator that has raised keeps - // raising. - return (Err(mutated()), None); - } - let entry = - dict.entries - .next_entry_checked(internal.position, &zelf.size, $project_fn); - match entry { - Err(dict_inner::DictChanged) => { - zelf.changed.store(true, Ordering::Relaxed); - (Err(mutated()), None) - } - Ok(Some((position, item))) => { - internal.position = position; - (Ok(PyIterReturn::Return(($result_fn)(vm, item))), None) - } - Ok(None) => (Ok(PyIterReturn::StopIteration(None)), internal.exhaust()), - } - }) - } - } - - #[pyclass(module = false, name = $reverse_iter_class_name)] - #[derive(Debug)] - pub(crate) struct $reverse_iter_name { - pub(crate) size: dict_inner::DictSize, - /// As in `$iter_name`. - changed: PyAtomic, - internal: PyMutex>, - } - - impl PyPayload for $reverse_iter_name { - #[inline] - fn class(ctx: &Context) -> &'static Py { - ctx.types.$reverse_iter_class - } - } - - impl $reverse_iter_name { - fn new(dict: PyDictRef) -> Self { - let size = dict.size(); - let position = size.entries_size.saturating_sub(1); - $reverse_iter_name { - size, - changed: Radium::new(false), - internal: PyMutex::new(PositionIterInternal::new(dict, position)), - } - } - } - - #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] - impl Py<$reverse_iter_name> { - #[pymethod] - fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { - let iter = builtins_iter(vm)?; - let internal = self.internal.lock(); - let entries = match &internal.status { - IterStatus::Active(dict) => { - let mut position = internal.position; - let mut entries = Vec::new(); - while let Some((found_index, key, value)) = - dict.entries.prev_entry(position) - { - entries.push(($result_fn)(vm, ($project_fn)(&key, &value))); - if found_index == 0 { - break; - } - position = found_index - 1; - } - entries - } - IterStatus::Exhausted => vec![], - }; - Ok(vm.new_tuple((iter, (vm.ctx.new_list(entries),)))) - } - - #[pymethod] - fn __length_hint__(&self) -> usize { - // As in `$iter_name`. - if self.changed.load(Ordering::Relaxed) { - return 0; - } - let internal = self.internal.lock(); - match &internal.status { - IterStatus::Active(dict) if dict.size() == self.size => { - internal.rev_length_hint(|_| self.size.entries_size) - } - _ => 0, - } - } - } - - impl SelfIter for $reverse_iter_name {} - - impl IterNext for $reverse_iter_name { - fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_step(&zelf.internal, |internal| { - let IterStatus::Active(dict) = &internal.status else { - return (Ok(PyIterReturn::StopIteration(None)), None); - }; - let mutated = - || vm.new_runtime_error("dictionary changed size during iteration"); - if zelf.changed.load(Ordering::Relaxed) { - // The dict is not looked at again once it has been - // found to change: an iterator that has raised keeps - // raising. - return (Err(mutated()), None); - } - let entry = - dict.entries - .prev_entry_checked(internal.position, &zelf.size, $project_fn); - match entry { - Err(dict_inner::DictChanged) => { - zelf.changed.store(true, Ordering::Relaxed); - (Err(mutated()), None) - } - Ok(Some((found_index, item))) => { - let released = if found_index == 0 { - internal.exhaust() - } else { - internal.position = found_index - 1; - None - }; - (Ok(PyIterReturn::Return(($result_fn)(vm, item))), released) - } - Ok(None) => (Ok(PyIterReturn::StopIteration(None)), internal.exhaust()), - } - }) - } + dict_iterator! { + $reverse_iter_name, $reverse_iter_class, $reverse_iter_class_name, + true, $project_fn, $result_fn } }; } @@ -1550,11 +2144,16 @@ dict_view! { vm.new_tuple((key, value)).into() } +fn set_view_dict(obj: &PyObject) -> Option<&PyAnyDict> { + obj.downcast_ref::() + .map(|view| view.dict()) + .or_else(|| obj.downcast_ref::().map(|view| view.dict())) +} + fn is_set_or_dict_view(obj: &PyObject) -> bool { obj.downcast_ref::().is_some() || obj.downcast_ref::().is_some() - || obj.downcast_ref::().is_some() - || obj.downcast_ref::().is_some() + || set_view_dict(obj).is_some() } // Set operations defined on set-like views of the dictionary. @@ -1566,14 +2165,6 @@ trait ViewSetOps: DictView { op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - if let Some(dictview) = other.downcast_ref::() { - return zelf.dict().inner_cmp( - dictview.dict(), - op, - !zelf.class().is(vm.ctx.types.dict_keys_type), - vm, - ); - } if !is_set_or_dict_view(other) { return Ok(PyComparisonValue::NotImplemented); } @@ -1647,7 +2238,7 @@ impl PyDictKeys { #[pygetset] fn mapping(zelf: PyRef) -> PyMappingProxy { - PyMappingProxy::from(zelf.dict().to_owned()) + PyMappingProxy::from_any_dict(zelf.dict().to_owned()) } } @@ -1667,10 +2258,10 @@ impl AsSequence for PyDictKeys { static AS_SEQUENCE: LazyLock = LazyLock::new(|| PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyDictKeys::sequence_downcast(seq).__len__())), contains: atomic_func!(|seq, target, vm| { - PyDictKeys::sequence_downcast(seq) + Ok(PyDictKeys::sequence_downcast(seq) .dict - .entries - .contains(vm, target) + .inner_getitem_opt(target, vm)? + .is_some()) }), ..PySequenceMethods::NOT_IMPLEMENTED }); @@ -1710,7 +2301,7 @@ impl PyDictItems { } #[pygetset] fn mapping(zelf: PyRef) -> PyMappingProxy { - PyMappingProxy::from(zelf.dict().to_owned()) + PyMappingProxy::from_any_dict(zelf.dict().to_owned()) } } @@ -1772,7 +2363,7 @@ impl AsNumber for PyDictItems { impl PyDictValues { #[pygetset] fn mapping(zelf: PyRef) -> PyMappingProxy { - PyMappingProxy::from(zelf.dict().to_owned()) + PyMappingProxy::from_any_dict(zelf.dict().to_owned()) } } @@ -1786,16 +2377,32 @@ impl AsSequence for PyDictValues { } } +fn dict_view_to_set(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + let mut source = obj; + if let Some(keys) = obj.downcast_ref::() { + let dict = keys.dict(); + if dict.as_object().class().is(vm.ctx.types.dict_type) + || dict.as_object().class().is(vm.ctx.types.frozendict_type) + { + // Exact dictionary keys are already hashed. Subclasses instead + // go through the view iterator, including OrderedDict views. + source = dict.as_object(); + } + } + // Reflected operations can put a set on the left. Reuse the set + // constructor's native paths rather than calling an overridden iterator. + PySetInner::from_object(source.to_owned(), vm) +} + fn set_inner_number_op(a: &PyObject, b: &PyObject, f: F, vm: &VirtualMachine) -> PyResult where - F: FnOnce(PySetInner, ArgIterable) -> PyResult, + F: FnOnce(PySetInner, PyObjectRef) -> PyResult, { - let a = PySetInner::from_iter( - ArgIterable::try_from_object(vm, a.to_owned())?.iter(vm)?, - vm, - )?; - let b = ArgIterable::try_from_object(vm, b.to_owned())?; - Ok(PySet { inner: f(a, b)? }.into_pyobject(vm)) + let a = dict_view_to_set(a, vm)?; + Ok(PySet { + inner: f(a, b.to_owned())?, + } + .into_pyobject(vm)) } pub(crate) fn set_inner_number_subtract( @@ -1807,9 +2414,11 @@ pub(crate) fn set_inner_number_subtract( } pub(crate) fn set_inner_number_and(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { - let a_is_view = - a.downcast_ref::().is_some() || a.downcast_ref::().is_some(); - let (view, other) = if a_is_view { (a, b) } else { (b, a) }; + let (view, other) = if set_view_dict(a).is_some() { + (a, b) + } else { + (b, a) + }; set_view_number_and(view, other, vm) } @@ -1818,60 +2427,225 @@ pub(crate) fn set_view_number_and( other: &PyObject, vm: &VirtualMachine, ) -> PyResult { + let view_len = set_view_dict(view).unwrap().__len__(); + if other.class().is(vm.ctx.types.set_type) && view_len <= other.length(vm)? { + // The set path hashes each candidate once and can stop when the + // result has reached the set's size. It also preserves the key from + // the view, rather than the equal key resident in the set. + return vm.call_method(other, "intersection", (view.to_owned(),)); + } + let (view, other) = if set_view_dict(other).is_some_and(|dict| dict.__len__() > view_len) { + (other, view) + } else { + (view, other) + }; let other = ArgIterable::::try_from_object(vm, other.to_owned())?; let result = PySet::default(); - for item in other.iter(vm)? { - let item = item?; - if view.sequence_unchecked().contains(&item, vm)? { - result.add(item, vm)?; + let mut iterator = other.iter(vm)?; + let mut current = None; + let outcome = (|| -> PyResult<()> { + for item in iterator.by_ref() { + current = Some(item?); + let item = current.as_ref().unwrap(); + if view.sequence_unchecked().contains(item, vm)? { + result.add(item.clone(), vm)?; + } + drop(current.take()); } + Ok(()) + })(); + // On failure, release the iterator and partial result before the current + // item. Retain its owner through both membership and result insertion. + drop(iterator); + if let Err(exc) = outcome { + drop(result); + return Err(exc); } Ok(result.into_pyobject(vm)) } pub(crate) fn set_inner_number_xor(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { - set_inner_number_op(a, b, |a, b| a.symmetric_difference(b, vm), vm) + set_inner_number_op( + a, + b, + |a, b| { + a.symmetric_difference_update(core::iter::once(b), vm)?; + Ok(a) + }, + vm, + ) } -pub(crate) fn set_item_view_number_xor( - a: &PyObject, - b: &PyObject, - both_are_item_views: bool, - vm: &VirtualMachine, -) -> PyResult { - if !both_are_item_views { - return set_inner_number_xor(a, b, vm); - } +fn set_item_view_number_xor(a: &PyDictItems, b: &PyDictItems, vm: &VirtualMachine) -> PyResult { + // Membership comparisons may mutate either original dictionary. Keep + // unmatched left entries in a private copy, as in dictitems_xor. + let remaining = a.dict().copy_as_dict(vm)?; let result = PySet::default(); - let a_iterable = ArgIterable::::try_from_object(vm, a.to_owned())?; - for item in a_iterable.iter(vm)? { - let item = item?; - if !b.sequence_unchecked().contains(&item, vm)? { - result.add(item, vm)?; + let mut current_key = None; + let mut current_value = None; + let outcome = (|| -> PyResult<()> { + // Read the right dictionary live, without a public iterator's size + // check. Release each table guard before calling value comparisons. + let mut position = 0; + while let Some((next_position, key, value, hash)) = + b.dict().as_dict().entries.next_entry_with_hash(position) + { + position = next_position; + current_key = Some(key); + current_value = Some(value); + let key = current_key.as_ref().unwrap().as_object(); + // Only unmatched pairs need to be hashable, and stored key hashes + // must not invoke __hash__ again during lookup or deletion. + let remove = match remaining.entries.get(vm, key, hash)? { + Some(left_value) => { + vm.identical_or_equal(&left_value, current_value.as_ref().unwrap())? + } + None => false, + }; + if remove { + drop(current_value.take()); + remaining.entries.delete(vm, key, hash)?; + drop(current_key.take()); + } else { + let pair = + vm.new_tuple((current_key.take().unwrap(), current_value.take().unwrap())); + result.add(pair.into(), vm)?; + } } - } - let b_iterable = ArgIterable::::try_from_object(vm, b.to_owned())?; - for item in b_iterable.iter(vm)? { - let item = item?; - if !a.sequence_unchecked().contains(&item, vm)? { - result.add(item, vm)?; + // Append the entries still present in the private copy. + let mut position = 0; + while let Some((next_position, key, value)) = remaining.entries.next_entry(position) { + position = next_position; + result.add(vm.new_tuple((key, value)).into(), vm)?; } + Ok(()) + })(); + // On failure, CPython releases the private dictionary and result before + // the current right item. Their finalizers may observe the distinction. + drop(remaining); + if let Err(exc) = outcome { + drop(result); + drop(current_key); + return Err(exc); } Ok(result.into_pyobject(vm)) } fn dict_item_view_number_xor(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { - let is_native_item_view = |obj: &PyObject| { - obj.downcast_ref::().is_some() - || obj.downcast_ref::().is_some() - }; - set_item_view_number_xor(a, b, is_native_item_view(a) && is_native_item_view(b), vm) + match ( + a.downcast_ref::(), + b.downcast_ref::(), + ) { + (Some(a), Some(b)) => set_item_view_number_xor(a, b, vm), + _ => set_inner_number_xor(a, b, vm), + } } pub(crate) fn set_inner_number_or(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { set_inner_number_op(a, b, |a, b| a.union(b, vm), vm) } +/// `_PyDict_Or` +fn dict_or(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { + let (Some(left), Some(_)) = (PyAnyDict::from_object(a), PyAnyDict::from_object(b)) else { + return Ok(vm.ctx.not_implemented()); + }; + // anydict_copy_untracked converts any frozendict to an exact frozendict. + let frozen = left.is_frozen(); + let mapping_name = if frozen { "frozendict" } else { "dict" }; + let dict = PyDict::default(); + if !left.is_empty() { + dict.update_arg(a.to_owned(), true, mapping_name, vm)?; + } + dict.update_arg(b.to_owned(), true, mapping_name, vm)?; + Ok(if frozen { + PyFrozenDict::from_dict(dict).into_pyobject(vm) + } else { + dict.into_pyobject(vm) + }) +} + +fn frozendict_or(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { + if a.class().is(vm.ctx.types.frozendict_type) + && let Some(left) = PyAnyDict::from_object(a) + && let Some(right) = PyAnyDict::from_object(b) + { + // frozendict() | frozendict(...) => frozendict(...) + if left.is_empty() && b.class().is(vm.ctx.types.frozendict_type) { + return Ok(b.to_owned()); + } + // frozendict(...) | frozendict() => frozendict(...) + if right.is_empty() + && (b.class().is(vm.ctx.types.dict_type) || b.class().is(vm.ctx.types.frozendict_type)) + { + return Ok(a.to_owned()); + } + } + dict_or(a, b, vm) +} + +pub(crate) fn dict_fromkeys( + class: PyTypeRef, + iterable: PyObjectRef, + value: PyObjectRef, + vm: &VirtualMachine, +) -> PyResult { + let exact_frozen = class.is(vm.ctx.types.frozendict_type); + let created = if exact_frozen { + None + } else { + Some(PyType::call(&class, ().into(), vm)?) + }; + let frozen_source = created + .as_ref() + .and_then(|obj| obj.downcast_ref::()); + if exact_frozen || frozen_source.is_some() { + let dict = PyDict::default(); + if let Some(source) = frozen_source { + dict.update_arg(source.to_owned().into(), true, "frozendict", vm)?; + } + let iterable = ArgIterable::::try_from_object(vm, iterable)?; + if let Some(keys) = PyDict::fromkeys_known_hashes(iterable.as_object(), vm) { + for (key, hash) in keys { + dict.entries.insert(vm, &*key, hash, value.clone())?; + } + } else { + for key in iterable.iter(vm)? { + let key = key?; + let hash = PyFrozenDict::key_hash(&*key, vm)?; + dict.entries.insert(vm, &*key, hash, value.clone())?; + } + } + let frozen = PyFrozenDict::from_dict(dict).into_ref(&vm.ctx); + return if exact_frozen { + Ok(frozen.into()) + } else { + class.as_object().call((frozen,), vm) + }; + } + let iterable = ArgIterable::::try_from_object(vm, iterable)?; + let created = created.unwrap(); + if let Some(dict) = created.downcast_ref_if_exact::(vm) { + if let Some(keys) = PyDict::fromkeys_known_hashes(iterable.as_object(), vm) { + if class.is(vm.ctx.types.dict_type) { + dict.entries.reserve_for_empty(keys.len()); + } + for (key, hash) in keys { + dict.entries.insert(vm, &*key, hash, value.clone())?; + } + } else { + for key in iterable.iter(vm)? { + dict.inner_setitem(&*key?, value.clone(), vm)?; + } + } + } else { + for key in iterable.iter(vm)? { + created.set_item(&*key?, value.clone(), vm)?; + } + } + Ok(created) +} + fn vectorcall_dict( zelf_obj: &PyObject, args: Vec, @@ -1886,13 +2660,35 @@ fn vectorcall_dict( Ok(obj.into()) } +fn vectorcall_frozendict( + zelf: &PyObject, + args: Vec, + nargs: usize, + kwnames: Option<&[PyObjectRef]>, + vm: &VirtualMachine, +) -> PyResult { + // frozendict(frozendict) returns the same object unmodified + if nargs == 1 + && kwnames.is_none_or(<[_]>::is_empty) + && args[0].class().is(vm.ctx.types.frozendict_type) + && zelf.is(vm.ctx.types.frozendict_type) + { + return Ok(args[0].clone()); + } + PyFrozenDict::slot_new( + zelf.downcast_ref::().unwrap().to_owned(), + FuncArgs::from_vectorcall_owned(args, nargs, kwnames), + vm, + ) +} + pub(crate) fn init(context: &'static Context) { PyDict::extend_class(context, context.types.dict_type); context .types .dict_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_dict)); PyDictKeys::extend_class(context, context.types.dict_keys_type); PyDictKeyIterator::extend_class(context, context.types.dict_keyiterator_type); @@ -1903,4 +2699,86 @@ pub(crate) fn init(context: &'static Context) { PyDictItems::extend_class(context, context.types.dict_items_type); PyDictItemIterator::extend_class(context, context.types.dict_itemiterator_type); PyDictReverseItemIterator::extend_class(context, context.types.dict_reverseitemiterator_type); + PyFrozenDict::extend_class(context, context.types.frozendict_type); + context + .types + .frozendict_type + .slots + .constructor_vectorcall + .store(Some(vectorcall_frozendict)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn anydict_reference_layout_and_ownership() { + static_assertions::assert_not_impl_any!(PyAnyDict: PyPayload); + static_assertions::assert_type_eq_all!( + ::Target, + PyAnyDict + ); + static_assertions::assert_eq_size!(PyRef, PyObjectRef, Option>); + static_assertions::assert_eq_align!(PyRef, PyObjectRef); + static_assertions::assert_eq_size!(PyAnyDict, PyObject); + static_assertions::assert_eq_align!(PyAnyDict, PyObject); + #[cfg(feature = "threading")] + static_assertions::assert_impl_all!(PyRef: Send, Sync); + #[cfg(not(feature = "threading"))] + static_assertions::assert_not_impl_any!(PyRef: Send, Sync); + + let ctx = Context::genesis(); + let dict: PyRef = PyDict::default().into_ref(ctx).into(); + let frozen: PyRef = PyFrozenDict::from_dict(PyDict::default()) + .into_ref(ctx) + .into(); + for owner in [dict, frozen] { + let object = owner.as_object() as *const PyObject; + assert_eq!(owner.as_object().strong_count(), 1); + let borrowed = PyAnyDict::from_object(owner.as_object()).unwrap(); + assert!(core::ptr::eq(borrowed.as_object(), object)); + assert_eq!(owner.as_object().strong_count(), 1); + assert_eq!(borrowed.as_mutable().is_none(), borrowed.is_frozen()); + let copy = borrowed.to_owned(); + assert_eq!(owner.as_object().strong_count(), 2); + let clone = owner.clone(); + assert_eq!(owner.as_object().strong_count(), 3); + let erased = clone.into_object(); + assert_eq!(erased.strong_count(), 3); + assert!(core::ptr::eq(&*erased, object)); + let mut visited = 0; + owner.traverse(&mut |edge| { + assert!(core::ptr::eq(edge, object)); + visited += 1; + }); + assert_eq!(visited, 1); + drop(copy); + drop(owner); + assert_eq!(erased.strong_count(), 1); + } + } + + #[test] + fn anydict_checked_reference_conversion() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let dict = PyDict::default().into_pyobject(vm); + let frozen = PyFrozenDict::from_dict(PyDict::default()).into_pyobject(vm); + for object in [dict, frozen] { + let owner = PyRef::::try_from_object(vm, object.clone()).unwrap(); + assert_eq!(object.strong_count(), 2); + assert!(core::ptr::eq(owner.as_object(), &*object)); + let erased: PyObjectRef = owner.into(); + assert_eq!(object.strong_count(), 2); + assert!(core::ptr::eq(&*erased, &*object)); + drop(erased); + assert_eq!(object.strong_count(), 1); + } + let unrelated: PyObjectRef = vm.ctx.new_int(1000).into(); + assert!(PyAnyDict::from_object(&unrelated).is_none()); + let error = PyRef::::try_from_object(vm, unrelated.clone()).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.type_error)); + assert_eq!(unrelated.strong_count(), 1); + }); + } } diff --git a/crates/vm/src/builtins/enumerate.rs b/crates/vm/src/builtins/enumerate.rs index 76ee3cca2b7..d55443b184f 100644 --- a/crates/vm/src/builtins/enumerate.rs +++ b/crates/vm/src/builtins/enumerate.rs @@ -1,14 +1,15 @@ use super::{ - IterStatus, PositionIterInternal, PyGenericAlias, PyIntRef, PyTupleRef, PyType, PyTypeRef, - iter::builtins_reversed, locked_rev_next, + PyGenericAlias, PyTupleRef, PyType, PyTypeRef, + iter::{SequenceIter, SequenceIterDirection}, }; -use crate::common::lock::{PyMutex, PyRwLock}; +use crate::common::lock::PyRwLock; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, + function::{ArgIndex, FuncArgs}, protocol::{PyIter, PyIterReturn}, raise_if_stop, - types::{Constructor, IterNext, Iterable, SelfIter}, + types::{Constructor, IterNext, Iterable, SelfIter, drop_kwargs_if_init_overridden}, }; use malachite_bigint::BigInt; use num_traits::ToPrimitive; @@ -53,10 +54,11 @@ impl PyPayload for PyEnumerate { #[derive(FromArgs)] pub struct EnumerateArgs { + // Bound as an object so the other arguments are checked before `iter()` runs, as in CPython. #[pyarg(any)] - iterable: PyIter, + iterable: PyObjectRef, #[pyarg(any, default = 0)] - start: PyIntRef, + start: ArgIndex, } impl Constructor for PyEnumerate { @@ -65,8 +67,10 @@ impl Constructor for PyEnumerate { fn py_new( _cls: &Py, Self::Args { iterable, start }: Self::Args, - _vm: &VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { + let iterable = iterable.get_iter(vm)?; + let start = start.into_int_ref(); let counter = match start.as_bigint().to_usize() { Some(n) => Counter::Small(n), None => Counter::Big(start.as_bigint().clone()), @@ -135,7 +139,7 @@ impl IterNext for PyEnumerate { #[pyclass(module = false, name = "reversed", traverse)] #[derive(Debug)] pub(crate) struct PyReverseSequenceIterator { - internal: PyMutex>, + internal: SequenceIter, } impl PyPayload for PyReverseSequenceIterator { @@ -146,50 +150,120 @@ impl PyPayload for PyReverseSequenceIterator { } impl PyReverseSequenceIterator { + pub(crate) fn from_object( + cls: PyTypeRef, + sequence: &PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + // Keep the original sequence alive while binding, calling, and releasing + // the special method, including when it does not retain its receiver. + if let Some(method) = vm.get_method(sequence.clone(), identifier!(vm, __reversed__)) { + let method = method?; + if vm.is_none(&method) { + return Err(Self::not_reversible(sequence, vm)); + } + let result = method.call((), vm); + return result; + } + + Self::py_new( + &cls, + ReversedArgs { + object: sequence.clone(), + }, + vm, + )? + .into_ref_with_type(vm, cls) + .map(Into::into) + } + + fn not_reversible( + sequence: &PyObjectRef, + vm: &VirtualMachine, + ) -> crate::builtins::PyBaseExceptionRef { + vm.new_type_error(format!( + "'{}' object is not reversible", + sequence.class().slot_name() + )) + } + pub(crate) const fn new(obj: PyObjectRef, len: usize) -> Self { - let position = len.saturating_sub(1); + let position = len as isize - 1; Self { - internal: PyMutex::new(PositionIterInternal::new(obj, position)), + internal: SequenceIter::new(obj, position, SequenceIterDirection::Reverse), } } } -#[pyclass(with(IterNext, Iterable))] +#[derive(FromArgs)] +pub(crate) struct ReversedArgs { + #[pyarg(positional)] + object: PyObjectRef, +} + +impl Constructor for PyReverseSequenceIterator { + type Args = ReversedArgs; + + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + // A subtype's custom initializer may consume keywords, but the exact + // type and subtypes inheriting its initializer reject them first. + // Retain the original arguments through callbacks even if keywords + // are removed from the constructor's view of the call. + let constructor_args = + drop_kwargs_if_init_overridden(&cls, vm.ctx.types.reverse_iter_type, args.clone()); + if !constructor_args.kwargs.is_empty() { + return Err(vm.new_type_error("reversed() takes no keyword arguments")); + } + let ReversedArgs { object } = constructor_args.bind_for(vm, "reversed")?; + let result = Self::from_object(cls, &object, vm); + drop(object); + drop(args); + result + } + + fn py_new( + _cls: &Py, + Self::Args { object }: Self::Args, + vm: &VirtualMachine, + ) -> PyResult { + // The slot handles arbitrary __reversed__ results before constructing + // a payload. Checking sequence support must not bind __getitem__. + let protocol = object.sequence_unchecked(); + if !protocol.check() { + return Err(Self::not_reversible(&object, vm)); + } + let len = protocol.length(vm)?; + Ok(Self::new(object, len)) + } +} + +#[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl Py { #[pymethod] fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult { - let internal = self.internal.lock(); - if let IterStatus::Active(obj) = &internal.status - && internal.position <= obj.length(vm)? - { - return Ok(internal.position + 1); - } - Ok(0) + vm.with_recursion(" in __length_hint__", || { + self.internal + .length_hint(vm) + .map(|length| length.unwrap_or(0)) + }) } #[pymethod] - fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.internal.lock().set_state(&state, |_, pos| pos, vm) + fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + self.internal.set_state(&object, vm) } #[pymethod] - fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { - let func = builtins_reversed(vm)?; - Ok(self.internal.lock().reduce( - func, - |x| x.clone(), - |vm| vm.ctx.empty_tuple.clone().into(), - vm, - )) + fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { + let func = self.class().to_owned().into(); + self.internal.reduce(func, vm) } } impl SelfIter for PyReverseSequenceIterator {} impl IterNext for PyReverseSequenceIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_rev_next(&zelf.internal, |obj, pos| { - PyIterReturn::from_getitem_result(obj.get_item(&pos, vm), vm) - }) + zelf.internal.next(vm) } } diff --git a/crates/vm/src/builtins/filter.rs b/crates/vm/src/builtins/filter.rs index 11e11fc2795..fff12b2f88e 100644 --- a/crates/vm/src/builtins/filter.rs +++ b/crates/vm/src/builtins/filter.rs @@ -1,6 +1,6 @@ use super::{PyType, PyTypeRef}; use crate::{ - Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, + AsObject, Context, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, protocol::{PyIter, PyIterReturn}, raise_if_stop, @@ -26,7 +26,7 @@ pub struct FilterArgs { #[pyarg(positional)] function: PyObjectRef, #[pyarg(positional)] - iterable: PyIter, + iterable: PyObjectRef, } impl Constructor for PyFilter { @@ -35,14 +35,11 @@ impl Constructor for PyFilter { fn py_new( _cls: &Py, - Self::Args { - function, - iterable: iterator, - }: Self::Args, - _vm: &VirtualMachine, + Self::Args { function, iterable }: Self::Args, + vm: &VirtualMachine, ) -> PyResult { - Ok(Self { - predicate: function, + iterable.get_iter(vm).map(|iterator| Self { + predicate: function.clone(), iterator, }) } @@ -51,9 +48,9 @@ impl Constructor for PyFilter { #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl Py { #[pymethod] - fn __reduce__(&self, vm: &VirtualMachine) -> (PyTypeRef, (PyObjectRef, PyIter)) { + fn __reduce__(&self) -> (PyTypeRef, (PyObjectRef, PyIter)) { ( - vm.ctx.types.filter_type.to_owned(), + self.class().to_owned(), (self.predicate.clone(), self.iterator.clone()), ) } @@ -66,17 +63,18 @@ impl IterNext for PyFilter { let predicate = &zelf.predicate; loop { let next_obj = raise_if_stop!(zelf.iterator.next(vm)?); - let predicate_value = if vm.is_none(predicate) { - next_obj.clone() + let is_true = if vm.is_none(predicate) || predicate.is(vm.ctx.types.bool_type) { + next_obj.try_to_bool(vm)? } else { // the predicate itself can raise StopIteration which does stop the filter iteration - raise_if_stop!(PyIterReturn::from_pyresult( + let predicate_value = raise_if_stop!(PyIterReturn::from_pyresult( predicate.call((next_obj.clone(),), vm), vm - )?) + )?); + predicate_value.try_to_bool(vm)? }; - if predicate_value.try_to_bool(vm)? { + if is_true { return Ok(PyIterReturn::Return(next_obj)); } } diff --git a/crates/vm/src/builtins/float.rs b/crates/vm/src/builtins/float.rs index 78d3bef7794..0e56f4a668c 100644 --- a/crates/vm/src/builtins/float.rs +++ b/crates/vm/src/builtins/float.rs @@ -1,14 +1,17 @@ use super::{ - PyByteArray, PyBytes, PyInt, PyIntRef, PyStr, PyType, PyTypeRef, PyUtf8StrRef, - try_bigint_to_f64, + PyBaseExceptionRef, PyByteArray, PyBytes, PyInt, PyIntRef, PyStr, PyType, PyTypeRef, + PyUtf8StrRef, try_bigint_to_f64, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, class::{PyClassDef, PyClassImpl}, - common::{float_ops, format::FormatSpec, hash, wtf8::Wtf8Buf}, - convert::{IntoPyException, ToPyObject, ToPyResult}, - function::{ArgBytesLike, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, + common::{float_ops, hash, wtf8::Wtf8Buf}, + convert::{ToPyObject, ToPyResult}, + function::{ + ArgBytesLike, ArgIndex, ArgIntoFloat, FuncArgs, OptionalArg, PyArithmeticValue, + PyComparisonValue, + }, protocol::PyNumberMethods, types::{AsNumber, Callable, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, }; @@ -162,19 +165,70 @@ fn inner_divmod(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult<(f64, f64)> { } pub(crate) fn float_pow(v1: f64, v2: f64, vm: &VirtualMachine) -> PyResult { - if v1.is_zero() && v2.is_sign_negative() { - Err(vm.new_zero_division_error("zero to a negative power")) - } else if v1.is_sign_negative() && (v2.floor() - v2).abs() > f64::EPSILON { - let v1 = Complex64::new(v1, 0.); - let v2 = Complex64::new(v2, 0.); - Ok(super::complex::complex_pow(v1, v2, vm)?.to_pyobject(vm)) - } else { - let ans = v1.powf(v2); - if ans.is_infinite() && !(v1.is_infinite() || v2.is_infinite()) { - Err(vm.new_overflow_error("math range error")) + // Resolve special values before finite negative bases or platform pow. + if v2 == 0.0 { + return Ok(1.0.to_pyobject(vm)); + } + if v1.is_nan() { + return Ok(v1.to_pyobject(vm)); + } + if v2.is_nan() { + return Ok(if v1 == 1.0 { 1.0 } else { v2 }.to_pyobject(vm)); + } + if v2.is_infinite() { + let magnitude = v1.abs(); + let result = if magnitude == 1.0 { + 1.0 + } else if (v2 > 0.0) == (magnitude > 1.0) { + f64::INFINITY + } else { + 0.0 + }; + return Ok(result.to_pyobject(vm)); + } + + let exponent_is_odd = v2.abs() % 2.0 == 1.0; + if v1.is_infinite() { + let result = if v2 > 0.0 { + if exponent_is_odd { v1 } else { v1.abs() } + } else if exponent_is_odd { + 0.0_f64.copysign(v1) } else { - Ok(ans.to_pyobject(vm)) + 0.0 + }; + return Ok(result.to_pyobject(vm)); + } + if v1 == 0.0 { + if v2 < 0.0 { + return Err(vm.new_zero_division_error("zero to a negative power")); } + return Ok(if exponent_is_odd { v1 } else { 0.0 }.to_pyobject(vm)); + } + + let mut magnitude = v1; + let negate_result = if v1 < 0.0 { + if v2 != v2.floor() { + let base = Complex64::new(v1, 0.0); + let exponent = Complex64::new(v2, 0.0); + return Ok(super::complex::complex_pow(base, exponent, vm)?.to_pyobject(vm)); + } + magnitude = -v1; + exponent_is_odd + } else { + false + }; + if magnitude == 1.0 { + return Ok(if negate_result { -1.0 } else { 1.0 }.to_pyobject(vm)); + } + + let mut result = magnitude.powf(v2); + if negate_result { + result = -result; + } + if result.is_infinite() { + Err(vm.new_overflow_error("math range error")) + } else { + Ok(result.to_pyobject(vm)) } } @@ -198,21 +252,12 @@ impl Constructor for PyFloat { // Bind before the fast path so FromArgs::arity decides how many arguments // are acceptable, rather than a count repeated here. Extra keywords are // accepted only when a subclass has replaced tp_init. - let arg: Self::Args = if cls.is(float_type) || uses_float_init { - args.bind_for(vm, Self::NAME)? + let (args, _retained_args) = if cls.is(float_type) || uses_float_init { + (args, None) } else { - match args.args.as_slice() { - [] => Self::Args { - x: OptionalArg::Missing, - }, - [value] => Self::Args { - x: OptionalArg::Present(value.clone()), - }, - slice => { - return Err(vm.new_arity_type_error(Self::NAME, 0..=1, slice.len())); - } - } + (FuncArgs::from(args.args.clone()), Some(args)) }; + let arg: Self::Args = args.bind_for(vm, Self::NAME)?; let arg_value = &arg.x; // Optimization: return exact float as-is @@ -243,37 +288,46 @@ impl Constructor for PyFloat { } pub fn float_from_string(val: &PyObject, vm: &VirtualMachine) -> PyResult { - let (bytearray, buffer, buffer_lock, mapped_string); - let b = if let Some(s) = val.downcast_ref::() { - mapped_string = crate::protocol::numeric_literal_from_str(s); - mapped_string.as_bytes() - } else if let Some(bytes) = val.downcast_ref::() { - bytes.as_bytes() - } else if let Some(buf) = val.downcast_ref::() { - bytearray = buf.borrow_buf(); - &*bytearray - } else if let Ok(b) = ArgBytesLike::try_from_borrowed_object(vm, val) { - buffer = b; - buffer_lock = buffer.borrow_buf(); - &*buffer_lock - } else { - return Err(vm.new_type_error(format!( - "float() argument must be a string or a real number, not '{}'", - val.class().slot_name() - ))); + // Keep the buffer export alive through repr, but release data guards first + // so repr can mutate the original object. + let buffer; + let parsed = { + let (bytearray, buffer_lock, mapped_string); + let b = if let Some(s) = val.downcast_ref::() { + mapped_string = crate::protocol::numeric_literal_from_str(s); + mapped_string.as_bytes() + } else if let Some(bytes) = val.downcast_ref::() { + bytes.as_bytes() + } else if let Some(buf) = val.downcast_ref::() { + bytearray = buf.borrow_buf(); + &*bytearray + } else if let Ok(b) = ArgBytesLike::try_from_borrowed_object(vm, val) { + buffer = b; + buffer_lock = buffer.borrow_buf(); + &*buffer_lock + } else { + return Err(vm.new_type_error(format!( + "float() argument must be a string or a real number, not '{}'", + val.class().slot_name() + ))); + }; + crate::literal::float::parse_bytes(b) }; - crate::literal::float::parse_bytes(b).ok_or_else(|| { - val.repr(vm).map_or_else( - |e| e, - |repr| vm.new_value_error(format!("could not convert string to float: {repr}")), - ) - }) + parsed.ok_or_else(|| invalid_float_literal_error(val, vm)) +} + +/// Build the existing float-conversion error after native parsing has failed. +pub fn invalid_float_literal_error(val: &PyObject, vm: &VirtualMachine) -> PyBaseExceptionRef { + val.repr(vm).map_or_else( + |e| e, + |repr| vm.new_value_error(format!("could not convert string to float: {repr}")), + ) } #[derive(FromArgs)] struct RoundArgs { #[pyarg(positional, optional)] - ndigits: Option, + ndigits: Option, } #[pyclass( @@ -291,21 +345,24 @@ impl Py { if format_spec.is_empty() { return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned()); } - let format_spec = - FormatSpec::parse(format_spec.as_str()).map_err(|err| err.into_pyexception(vm))?; - let result = if format_spec.has_locale_format() { + let spec = crate::format::parse_format_spec(zelf.as_object(), format_spec.as_str(), vm)?; + let result = if spec.has_locale_format() { let locale = crate::format::get_locale_info(); - format_spec.format_float_locale(zelf.to_f64(), &locale) + spec.format_float_locale(zelf.to_f64(), &locale) } else { - format_spec.format_float(zelf.to_f64()) + spec.format_float(zelf.to_f64()) }; - result - .map(Wtf8Buf::from_string) - .map_err(|err| err.into_pyexception(vm)) + result.map(Wtf8Buf::from_string).map_err(|err| { + crate::format::format_spec_error(err, zelf.as_object(), format_spec.as_str(), vm) + }) } - #[pystaticmethod] - fn __getformat__(typestr: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult { + #[pyclassmethod] + fn __getformat__( + _cls: PyTypeRef, + typestr: PyUtf8StrRef, + vm: &VirtualMachine, + ) -> PyResult { if !matches!(typestr.as_str(), "double" | "float") { return Err( vm.new_value_error("__getformat__() argument 1 must be 'double' or 'float'") @@ -341,35 +398,25 @@ impl Py { fn __round__(&self, args: RoundArgs, vm: &VirtualMachine) -> PyResult { let ndigits = args.ndigits; let value = if let Some(ndigits) = ndigits { - let ndigits = ndigits.as_bigint(); + let ndigits = ndigits.as_ref().as_bigint(); let ndigits = match ndigits.to_i32() { Some(n) => n, None if ndigits.is_positive() => i32::MAX, None => i32::MIN, }; let float = float_ops::round_float_digits(self.value, ndigits) - .ok_or_else(|| vm.new_overflow_error("overflow occurred during round"))?; + .ok_or_else(|| vm.new_overflow_error("rounded value too large to represent"))?; vm.ctx.new_float(float).into() } else { - let fract = self.value.fract(); - let value = if (fract.abs() - 0.5).abs() < f64::EPSILON { - if self.value.trunc() % 2.0 == 0.0 { - self.value - fract - } else { - self.value + fract - } - } else { - self.value.round() - }; - let int = try_to_bigint(value, vm)?; + let int = try_to_bigint(self.value.round_ties_even(), vm)?; vm.ctx.new_int(int).into() }; Ok(value) } #[pygetset] - const fn real(zelf: PyRef) -> PyRef { - zelf + fn real(zelf: &Self, vm: &VirtualMachine) -> PyRef { + PyFloat::number_downcast_exact(zelf.as_object().number(), vm) } #[pygetset] @@ -378,8 +425,8 @@ impl Py { } #[pymethod] - const fn conjugate(zelf: PyRef) -> PyRef { - zelf + fn conjugate(zelf: &Self, vm: &VirtualMachine) -> PyRef { + PyFloat::number_downcast_exact(zelf.as_object().number(), vm) } #[pymethod] @@ -410,13 +457,15 @@ impl Py { return Ok(number); } - let value = number.try_float(vm)?.to_f64(); + let value = ArgIntoFloat::try_from_object(vm, number.clone())?.into_float(); let result = vm.ctx.new_float(value); - if cls.is(vm.ctx.types.float_type) { + let result = if cls.is(vm.ctx.types.float_type) { Ok(result.into()) } else { PyType::call(&cls, vec![result.into()].into(), vm) - } + }; + drop(number); + result } #[pyclassmethod] @@ -580,5 +629,5 @@ fn vectorcall_float( #[rustfmt::skip] // to avoid line splitting pub(crate) fn init(context: &'static Context) { PyFloat::extend_class(context, context.types.float_type); - context.types.float_type.slots().vectorcall.store(Some(vectorcall_float)); + context.types.float_type.slots().constructor_vectorcall.store(Some(vectorcall_float)); } diff --git a/crates/vm/src/builtins/frame.rs b/crates/vm/src/builtins/frame.rs index 905cbb582a4..6a1ae32a395 100644 --- a/crates/vm/src/builtins/frame.rs +++ b/crates/vm/src/builtins/frame.rs @@ -2,16 +2,15 @@ */ -use super::{PyAsyncGen, PyCode, PyCoroutine, PyDictRef, PyGenerator, PyIntRef}; +use super::{PyAnyDict, PyAsyncGen, PyCode, PyCoroutine, PyGenerator, PyIntRef}; use crate::{ AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, frame::{FrameObject, FrameOwner}, function::PySetterValue, - types::{Destructor, Representable}, + types::Representable, }; use core::sync::atomic::Ordering::Relaxed; -use num_traits::Zero; #[allow(unused_imports)] use rustpython_common::atomic::Radium; use rustpython_compiler_core::bytecode::{self, Constant, Instruction, StackEffect}; @@ -155,9 +154,24 @@ pub(crate) mod stack_analysis { } /// Analyze bytecode and compute the stack state at each instruction index. - pub(crate) fn mark_stacks(code: &bytecode::CodeObject) -> Vec { + pub(crate) fn mark_stacks(code: &PyCode) -> Vec { let instructions = &*code.instructions; let len = instructions.len(); + let monitoring_data = code.monitoring_data.lock(); + let base_opcode = |i| { + let mut op = code.instructions.read_op(i); + if let Some(data) = monitoring_data.as_ref() { + if matches!(op, Instruction::InstrumentedLine) { + op = Instruction::try_from(data.line_opcodes[i]) + .expect("INSTRUMENTED_LINE without original opcode"); + } + if matches!(op, Instruction::InstrumentedInstruction) { + op = Instruction::try_from(data.per_instruction_opcodes[i]) + .expect("INSTRUMENTED_INSTRUCTION without original opcode"); + } + } + op.to_base().unwrap_or(op).deoptimize() + }; let mut stacks = vec![UNINITIALIZED; len + 1]; stacks[0] = EMPTY_STACK; @@ -169,7 +183,7 @@ pub(crate) mod stack_analysis { let mut i = 0; while i < len { let mut next_stack = stacks[i]; - let mut opcode = instructions[i].op; + let mut opcode = base_opcode(i); let mut oparg: u32 = 0; // Accumulate EXTENDED_ARG prefixes @@ -180,16 +194,13 @@ pub(crate) mod stack_analysis { break; } stacks[i] = next_stack; - opcode = instructions[i].op; + opcode = base_opcode(i); } if i >= len { break; } oparg = (oparg << 8) | u32::from(u8::from(instructions[i].arg)); - // De-instrument and de-specialize: get the underlying base instruction - let opcode = opcode.to_base().unwrap_or(opcode).deoptimize(); - let caches = opcode.cache_entries(); let next_i = i + 1 + caches; @@ -242,29 +253,30 @@ pub(crate) mod stack_analysis { } } } - Instruction::GetIter | Instruction::GetAiter => { + Instruction::GetIter { .. } => { next_stack = push_value(pop_value(next_stack), Kind::Iterator as i64); + next_stack = push_value(next_stack, Kind::Iterator as i64); if next_i < stacks.len() { stacks[next_i] = next_stack; } } - Instruction::ForIter { .. } => { - // Fall-through (iteration continues): pushes the next value - let body_stack = push_value(next_stack, Kind::Object as i64); + Instruction::GetAiter => { + next_stack = push_value(pop_value(next_stack), Kind::Iterator as i64); if next_i < stacks.len() { - stacks[next_i] = body_stack; + stacks[next_i] = next_stack; } - // Exhaustion path: relative forward from after_caches - let mut j = next_i + oparg as usize; - if j < instructions.len() { - let target_op = - instructions[j].op.to_base().unwrap_or(instructions[j].op); - if matches!(target_op, Instruction::EndFor) { - j += 1; - } + } + Instruction::ForIter { .. } => { + // Both the body and the END_FOR target start with the + // next value pushed. + let target_stack = push_value(next_stack, Kind::Object as i64); + if next_i < stacks.len() { + stacks[next_i] = target_stack; } - if j < stacks.len() && stacks[j] == UNINITIALIZED { - stacks[j] = next_stack; + let j = next_i + oparg as usize; + if j < stacks.len() { + debug_assert!(stacks[j] == UNINITIALIZED || stacks[j] == target_stack); + stacks[j] = target_stack; } } Instruction::EndAsyncFor => { @@ -514,19 +526,19 @@ impl Py { ); match owner { FrameOwner::Generator => { - // FRAME_SUSPENDED (lasti > 0) cannot be cleared. FRAME_CREATED - // and finished frames go through the owner finalizer. - if self.lasti() != 0 { - return Err(vm.new_runtime_error("cannot clear a suspended frame")); - } + // RETURN_GENERATOR executes the creation preamble, so lasti + // no longer distinguishes a created frame from a suspended one. if let Some(owner) = self.iframe().generator.to_owned() { - if let Some(coro) = owner.downcast_ref::() { - let _ = PyCoroutine::del(coro, vm); + let coro = if let Some(coro) = owner.downcast_ref::() { + coro.as_coro() } else if let Some(async_gen) = owner.downcast_ref::() { - let _ = PyAsyncGen::del(async_gen, vm); + async_gen.as_coro() } else if let Some(generator) = owner.downcast_ref::() { - let _ = PyGenerator::del(generator, vm); - } + generator.as_coro() + } else { + unreachable!("generator-owned frame has no coroutine owner") + }; + coro.clear_frame(&owner, vm)?; } return Ok(()); } @@ -630,6 +642,11 @@ impl Py { let mut cur = crate::vm::thread::get_current_frame(); while !cur.is_null() { if core::ptr::eq(cur, prev) { + // SAFETY: cur was found on this thread's live active chain. + let cur = unsafe { crate::frame::first_complete_iframe(cur) }; + if cur.is_null() { + return None; + } let iframe_ref = unsafe { &*cur }; let fo = iframe_ref.materialize(vm); return Some(fo.to_owned()); @@ -652,6 +669,11 @@ impl Py { // return and free the stack-allocated iframe at any time. vm.state.stop_the_world.stop_the_world(&vm.state); scopeguard::defer! { vm.state.stop_the_world.start_the_world(&vm.state); } + // SAFETY: the world is stopped, preserving the live chain. + let prev = unsafe { crate::frame::first_complete_iframe(prev) }; + if prev.is_null() { + return None; + } let prev_ref = unsafe { &*prev }; // Fast path: already materialized. if let Some(fo) = prev_ref.frame_obj() { @@ -659,7 +681,7 @@ impl Py { } // Slow path: copy the whole chain, linked through retained_back. // SAFETY: the world is stopped, so the owning thread is parked. - let fo = unsafe { prev_ref.materialize_detached_chain(vm) }; + let fo = unsafe { prev_ref.materialize_complete_detached_chain(vm) }; return Some(fo); } @@ -668,7 +690,7 @@ impl Py { } #[pygetset] - pub fn f_globals(&self) -> PyDictRef { + pub fn f_globals(&self) -> PyRef { self.iframe().globals().to_owned() } @@ -773,7 +795,7 @@ impl Py { ))); } - let stacks = mark_stacks(code); + let stacks = mark_stacks(py_code); let len = self.iframe().code().instructions.len(); // lasti points past the current instruction (already incremented). @@ -944,17 +966,22 @@ impl Py { let was_unset = canonical.cold().trace.lock().is_none(); // Set on the materialized FrameObject. - (*self.iframe().cold().trace.lock()).clone_from(&trace); + // Keep replaced traces alive until both copies are updated and no + // trace lock is held: their finalizers can access this frame again. + let previous = core::mem::replace(&mut *self.iframe().cold().trace.lock(), trace.clone()); // Also propagate to the live source iframe if this is a // materialized copy of a stack-allocated frame, so pdb's // f_trace assignment takes effect on the executing frame. - if !live.is_null() { - *unsafe { &*live }.cold().trace.lock() = trace; - } + let previous_live = if !live.is_null() { + core::mem::replace(&mut *unsafe { &*live }.cold().trace.lock(), trace) + } else { + None + }; if was_unset && trace_is_some { canonical.sync_prev_line_from_lasti(); } + drop((previous, previous_live)); } #[pygetset] @@ -967,11 +994,10 @@ impl Py { fn set_f_trace_opcodes(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { match value { PySetterValue::Assign(value) => { - let value: PyIntRef = value - .downcast() - .map_err(|_| vm.new_type_error("attribute value type must be bool"))?; - - let val = !value.as_bigint().is_zero(); + if !value.class().is(vm.ctx.types.bool_type) { + return Err(vm.new_type_error("attribute value type must be bool")); + } + let val = value.is(&vm.ctx.true_value); *self.iframe().cold().trace_opcodes.lock() = val; // Propagate to live source iframe. let live = self.find_live_source_iframe(); @@ -983,7 +1009,9 @@ impl Py { Ok(()) } - PySetterValue::Delete => Err(vm.new_type_error("can't delete numeric/char attribute")), + PySetterValue::Delete => Err(vm.new_attribute_error( + "attribute 'f_trace_opcodes' of 'frame' objects cannot be deleted", + )), } } } diff --git a/crates/vm/src/builtins/frame_locals_proxy.rs b/crates/vm/src/builtins/frame_locals_proxy.rs index cbd21527da3..4e396290891 100644 --- a/crates/vm/src/builtins/frame_locals_proxy.rs +++ b/crates/vm/src/builtins/frame_locals_proxy.rs @@ -21,6 +21,13 @@ use crate::{ use rustpython_common::lock::LazyLock; use rustpython_common::wtf8::Wtf8Buf; +/// FrameLocalsProxy($frame) +/// -- +/// +/// Create a write-through view of the locals dictionary for a frame. +/// +/// frame +/// the frame object to wrap. #[pyclass( module = false, name = "FrameLocalsProxy", @@ -145,10 +152,10 @@ impl FrameLocalsProxy { return Ok(vm.ctx.not_implemented()); } let result = self.snapshot(vm)?; - if other.downcast_ref::().is_some() { + if let Some(dict) = other.downcast_ref::() { // PyDict_Update reads a dict subclass's stored entries directly; // it does not dispatch to overridden mapping methods. - result.merge_dict(&other.downcast().unwrap(), true, vm)?; + result.merge_dict(dict, true, vm)?; } else { result.merge_object(other, vm)?; } @@ -165,15 +172,18 @@ impl FrameLocalsProxy { } } -#[pyclass(with( - Constructor, - AsMapping, - AsSequence, - AsNumber, - Iterable, - Comparable, - Representable -))] +#[pyclass( + with( + Constructor, + AsMapping, + AsSequence, + AsNumber, + Iterable, + Comparable, + Representable + ), + flags(IMMUTABLETYPE) +)] impl Py { #[pymethod] fn keys(&self, vm: &VirtualMachine) -> PyResult { diff --git a/crates/vm/src/builtins/function.rs b/crates/vm/src/builtins/function.rs index c6c4aaf2b79..3ccf77a835c 100644 --- a/crates/vm/src/builtins/function.rs +++ b/crates/vm/src/builtins/function.rs @@ -2,8 +2,8 @@ mod jit; use super::{ - PyAsyncGen, PyCode, PyCoroutine, PyDictRef, PyGenerator, PyList, PyModule, PyStr, PyStrRef, - PyTuple, PyTupleRef, PyType, object, + PyAnyDict, PyAsyncGen, PyCode, PyCoroutine, PyDict, PyDictRef, PyGenerator, PyModule, PyStr, + PyStrRef, PyTuple, PyTupleRef, PyType, object, }; use crate::common::hash::PyHash; use crate::common::lock::PyMutex; @@ -66,7 +66,7 @@ fn format_missing_args( pub struct PyFunction { pub(crate) code: PyAtomicRef, #[pymember(name = "__globals__")] - pub(crate) globals: PyDictRef, + pub(crate) globals: PyRef, #[pymember(name = "__builtins__")] pub(crate) builtins: PyObjectRef, #[pymember(name = "__closure__")] @@ -179,15 +179,17 @@ impl PyFunction { #[inline] pub(crate) fn new( code: PyRef, - globals: PyDictRef, + globals: PyRef, vm: &VirtualMachine, ) -> PyResult { - let name = PyMutex::new(code.obj_name.to_owned()); - let module = vm.unwrap_or_none(globals.get_item_opt(identifier!(vm, __name__), vm)?); - let builtins = globals.get_item("__builtins__", vm).unwrap_or_else(|_| { - // If not in globals, inherit from current execution context - crate::frame::current_builtins().unwrap_or_else(|| vm.builtins.dict().into()) - }); + let name = PyMutex::new(code.co_name.clone()); + let module = vm.unwrap_or_none(globals.inner_getitem_opt(identifier!(vm, __name__), vm)?); + let builtins = globals + .inner_getitem_opt(identifier!(vm, __builtins__), vm)? + .unwrap_or_else(|| { + // If not in globals, inherit from current execution context. + crate::frame::current_builtins().unwrap_or_else(|| vm.builtins.dict().into()) + }); // If builtins is a module, use its __dict__ instead let builtins = if let Some(module) = builtins.downcast_ref::() { module.dict().into() @@ -200,12 +202,13 @@ impl PyFunction { code.code .constants .first() + .filter(|c| c.as_object().downcast_ref::().is_some()) .map_or_else(|| vm.ctx.none(), |c| c.as_object().to_owned()) } else { vm.ctx.none() }; - let qualname = vm.ctx.new_str(code.qualname.as_str()); + let qualname = code.co_qualname(); let func = Self { code: PyAtomicRef::from(code), globals, @@ -621,7 +624,7 @@ impl Py { } else if let Some(locals) = locals { Some(locals) } else { - Some(ArgMapping::from_dict_exact(self.globals.clone())) + Some(ArgMapping::from_anydict_exact(self.globals.clone())) }; let use_datastack = !is_gen && !is_coro && !is_async_gen; let frame = FrameObject::new_ref( @@ -635,6 +638,7 @@ impl Py { ); self.fill_locals_from_args(&frame, func_args, vm)?; if is_gen || is_coro || is_async_gen { + vm.with_generator_frame(frame.clone(), |f| f.prepare_generator(vm))?; return Ok(self.make_generator_or_coro(frame, vm)); } // Tracing active: use heap frame with full trace support. @@ -654,7 +658,7 @@ impl Py { } else if let Some(locals) = locals { crate::frame::FrameLocals::with_locals(locals) } else { - crate::frame::FrameLocals::with_locals(crate::function::ArgMapping::from_dict_exact( + crate::frame::FrameLocals::with_locals(crate::function::ArgMapping::from_anydict_exact( self.globals.clone(), )) }; @@ -805,7 +809,7 @@ impl Py { let locals = if code.flags.contains(bytecode::CodeFlags::NEWLOCALS) { None } else { - Some(ArgMapping::from_dict_exact(self.globals.clone())) + Some(ArgMapping::from_anydict_exact(self.globals.clone())) }; let frame = FrameObject::new_ref( @@ -842,7 +846,7 @@ impl Py { &self, args: impl ExactSizeIterator, vm: &VirtualMachine, - ) -> PyObjectRef { + ) -> PyResult { let code: PyRef = (*self.code).to_owned(); debug_assert_eq!(args.len(), code.arg_count as usize); @@ -862,7 +866,7 @@ impl Py { let locals = if code.flags.contains(bytecode::CodeFlags::NEWLOCALS) { None } else { - Some(ArgMapping::from_dict_exact(self.globals.clone())) + Some(ArgMapping::from_anydict_exact(self.globals.clone())) }; // Heap-backed: the frame outlives the call that made it. @@ -884,7 +888,8 @@ impl Py { } } - self.make_generator_or_coro(frame, vm) + vm.with_generator_frame(frame.clone(), |f| f.prepare_generator(vm))?; + Ok(self.make_generator_or_coro(frame, vm)) } pub(crate) fn invoke_prepared_exact_args( @@ -897,7 +902,7 @@ impl Py { let locals = if code.flags.contains(bytecode::CodeFlags::NEWLOCALS) { crate::frame::FrameLocals::lazy() } else { - crate::frame::FrameLocals::with_locals(ArgMapping::from_dict_exact( + crate::frame::FrameLocals::with_locals(ArgMapping::from_anydict_exact( self.globals.clone(), )) }; @@ -944,7 +949,7 @@ impl Py { // specialization classification, but calling one produces a // generator/coroutine object instead of running the frame. if self.is_generator_like() { - return Ok(self.make_generator_exact_args(args.into_iter(), vm)); + return self.make_generator_exact_args(args.into_iter(), vm); } self.invoke_prepared_exact_args(args.into_iter(), vm) } @@ -966,7 +971,7 @@ impl Py { // specialization classification, but calling one produces a // generator/coroutine object instead of running the frame. if self.is_generator_like() { - return Ok(self.make_generator_exact_args(taken, vm)); + return self.make_generator_exact_args(taken, vm); } self.invoke_prepared_exact_args(taken, vm) } @@ -1000,22 +1005,44 @@ impl PyPayload for PyFunction { )] impl Py { #[pygetset] - fn __code__(&self) -> PyRef { - (*self.code).to_owned() + fn __code__(&self, vm: &VirtualMachine) -> PyResult> { + vm.audit("object.__getattr__", || (self.to_owned(), "__code__"))?; + Ok((*self.code).to_owned()) } #[pygetset(setter)] - fn set___code__(&self, code: PyRef, vm: &VirtualMachine) -> PyResult<()> { + fn set___code__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let code = value + .into_option() + .and_then(|value| value.downcast::().ok()) + .ok_or_else(|| vm.new_type_error("__code__ must be set to a code object"))?; + vm.audit("object.__setattr__", || { + (self.to_owned(), "__code__", code.clone()) + })?; let n_free = code.freevars.len(); let n_closure = self.closure.as_ref().map_or(0, |c| c.as_slice().len()); if n_closure != n_free { - return Err(vm.new_value_error(format!( - "{}() requires a code object with {} free vars, not {}", - self.qualname.lock(), - n_closure, - n_free, + let name = self.__name__(); + return Err(vm.new_value_error(wtf8_concat!( + name.as_wtf8(), + format!("() requires a code object with {n_closure} free vars, not {n_free}"), ))); } + let mask = bytecode::CodeFlags::GENERATOR + | bytecode::CodeFlags::COROUTINE + | bytecode::CodeFlags::ASYNC_GENERATOR; + let old_flags = self.code.flags; + let new_flags = code.flags; + if (old_flags & mask) != (new_flags & mask) { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "Assigning a code object of non-matching type is deprecated \ + (e.g., from a generator to a plain function)" + .to_owned(), + 1, + vm, + )?; + } #[cfg(feature = "jit")] let mut jit_guard = self.jitted_code.lock(); self.code.swap_to_temporary_refs(code, vm); @@ -1028,32 +1055,74 @@ impl Py { Ok(()) } - #[pygetset] - pub(crate) fn __defaults__(&self) -> Option { + pub(crate) fn defaults(&self) -> Option { self.defaults_and_kwdefaults.lock().0.clone() } + + #[pygetset] + fn __defaults__(&self, vm: &VirtualMachine) -> PyResult> { + vm.audit("object.__getattr__", || (self.to_owned(), "__defaults__"))?; + Ok(self.defaults()) + } + #[pygetset(setter)] - fn set___defaults__(&self, defaults: PySetterValue>) { - self.defaults_and_kwdefaults.lock().0 = match defaults { - PySetterValue::Assign(d) => d, - PySetterValue::Delete => None, - }; + fn set___defaults__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let defaults = value + .into_option() + .filter(|value| !vm.is_none(value)) + .map(|value| { + value + .downcast::() + .map_err(|_| vm.new_type_error("__defaults__ must be set to a tuple object")) + }) + .transpose()?; + if let Some(defaults) = &defaults { + vm.audit("object.__setattr__", || { + (self.to_owned(), "__defaults__", defaults.clone()) + })?; + } else { + vm.audit("object.__delattr__", || (self.to_owned(), "__defaults__"))?; + } + // The old tuple may run finalizers that access this function again. + // Invalidate the version before dropping it, with the lock released. + let _old = core::mem::replace(&mut self.defaults_and_kwdefaults.lock().0, defaults); self.func_version.store(0, Relaxed); crate::stdlib::_testinternalcapi::note_func_modification(); + Ok(()) } - #[pygetset] - pub(crate) fn __kwdefaults__(&self) -> Option { + pub(crate) fn kwdefaults(&self) -> Option { self.defaults_and_kwdefaults.lock().1.clone() } + + #[pygetset] + fn __kwdefaults__(&self, vm: &VirtualMachine) -> PyResult> { + vm.audit("object.__getattr__", || (self.to_owned(), "__kwdefaults__"))?; + Ok(self.kwdefaults()) + } + #[pygetset(setter)] - fn set___kwdefaults__(&self, kwdefaults: PySetterValue>) { - self.defaults_and_kwdefaults.lock().1 = match kwdefaults { - PySetterValue::Assign(d) => d, - PySetterValue::Delete => None, - }; + fn set___kwdefaults__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let kwdefaults = value + .into_option() + .filter(|value| !vm.is_none(value)) + .map(|value| { + value + .downcast::() + .map_err(|_| vm.new_type_error("__kwdefaults__ must be set to a dict object")) + }) + .transpose()?; + if let Some(kwdefaults) = &kwdefaults { + vm.audit("object.__setattr__", || { + (self.to_owned(), "__kwdefaults__", kwdefaults.clone()) + })?; + } else { + vm.audit("object.__delattr__", || (self.to_owned(), "__kwdefaults__"))?; + } + let _old = core::mem::replace(&mut self.defaults_and_kwdefaults.lock().1, kwdefaults); self.func_version.store(0, Relaxed); crate::stdlib::_testinternalcapi::note_func_modification(); + Ok(()) } #[pygetset] @@ -1062,8 +1131,13 @@ impl Py { } #[pygetset(setter)] - fn set___name__(&self, name: PyStrRef) { - *self.name.lock() = name; + fn set___name__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let name = value + .into_option() + .and_then(|value| value.downcast::().ok()) + .ok_or_else(|| vm.new_type_error("__name__ must be set to a string object"))?; + let _old = core::mem::replace(&mut *self.name.lock(), name); + Ok(()) } #[pygetset] @@ -1091,24 +1165,26 @@ impl Py { // Release locks before calling __annotate__ to avoid deadlock if let Some(annotate_fn) = annotate_fn { let one = vm.ctx.new_int(1); - let ann_dict = annotate_fn.call((one,), vm)?; - let ann_dict = ann_dict - .downcast::() - .map_err(|obj| { - vm.new_type_error(format!( - "__annotate__ returned non-dict of type '{}'", - obj.class().name() - )) - })?; + let result = annotate_fn.call((one,), vm); + drop(annotate_fn); + let ann_dict = match result?.downcast::() { + Ok(dict) => dict, + Err(obj) => { + return Err(vm.new_type_error(wtf8_concat!( + "__annotate__() must return a dict, not ", + obj.class().fully_qualified_name(vm)? + ))); + } + }; // Cache the result - *self.annotations.lock() = Some(ann_dict.clone()); + let _old_annotations = self.annotations.lock().replace(ann_dict.clone()); return Ok(ann_dict); } // No __annotate__ or not callable, create empty dict let new_dict = vm.ctx.new_dict(); - *self.annotations.lock() = Some(new_dict.clone()); + let _old_annotations = self.annotations.lock().replace(new_dict.clone()); Ok(new_dict) } @@ -1118,23 +1194,18 @@ impl Py { value: PySetterValue>, vm: &VirtualMachine, ) -> PyResult<()> { - match value { + let annotations = match value { PySetterValue::Assign(Some(value)) => { let annotations = value.downcast::().map_err(|_| { vm.new_type_error("__annotations__ must be set to a dict object") })?; - *self.annotations.lock() = Some(annotations); - *self.annotate.lock() = None; + Some(annotations) } - PySetterValue::Assign(None) => { - *self.annotations.lock() = None; - *self.annotate.lock() = None; - } - PySetterValue::Delete => { - // del only clears cached annotations; __annotate__ is preserved - *self.annotations.lock() = None; - } - } + PySetterValue::Assign(None) | PySetterValue::Delete => None, + }; + let old_annotations = core::mem::replace(&mut *self.annotations.lock(), annotations); + drop(old_annotations); + let _old_annotate = self.annotate.lock().take(); Ok(()) } @@ -1167,8 +1238,6 @@ impl Py { if !value.is_callable() { return Err(vm.new_type_error("__annotate__ must be callable or None")); } - // Clear cached __annotations__ when __annotate__ is set - *self.annotations.lock() = None; Some(value) } PySetterValue::Assign(None) => None, @@ -1176,7 +1245,12 @@ impl Py { return Err(vm.new_type_error("__annotate__ cannot be deleted")); } }; - *self.annotate.lock() = annotate; + let clear_annotations = annotate.is_some(); + let old_annotate = core::mem::replace(&mut *self.annotate.lock(), annotate); + drop(old_annotate); + if clear_annotations { + let _old_annotations = self.annotations.lock().take(); + } Ok(()) } @@ -1192,7 +1266,7 @@ impl Py { let Ok(qualname) = value.downcast::() else { return Err(vm.new_type_error("__qualname__ must be set to a string object")); }; - *self.qualname.lock() = qualname; + let _old = core::mem::replace(&mut *self.qualname.lock(), qualname); } PySetterValue::Delete => { return Err(vm.new_type_error("__qualname__ must be set to a string object")); @@ -1207,19 +1281,12 @@ impl Py { } #[pygetset(setter)] - fn set___type_params__( - &self, - value: PySetterValue, - vm: &VirtualMachine, - ) -> PyResult<()> { - match value { - PySetterValue::Assign(value) => { - *self.type_params.lock() = value; - } - PySetterValue::Delete => { - return Err(vm.new_type_error("__type_params__ must be set to a tuple object")); - } - } + fn set___type_params__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let type_params = value + .into_option() + .and_then(|value| value.downcast::().ok()) + .ok_or_else(|| vm.new_type_error("__type_params__ must be set to a tuple"))?; + let _old = core::mem::replace(&mut *self.type_params.lock(), type_params); Ok(()) } @@ -1268,85 +1335,154 @@ impl Callable for PyFunction { impl Representable for PyFunction { #[inline] - fn repr_str(zelf: &Py, _vm: &VirtualMachine) -> PyResult { - Ok(format!( - "", - zelf.__qualname__(), - zelf.get_id() + fn repr_wtf8(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + let qualname = zelf.__qualname__(); + Ok(wtf8_concat!( + "", zelf.get_id()), )) } } +// Keep all original owners until validation finishes. Eager typed conversion +// can release earlier arguments before formatting a later argument error, +// allowing finalizers to change the error (including direct __new__ calls). #[derive(FromArgs)] pub struct PyFunctionNewArgs { - #[pyarg(positional)] - code: PyRef, - #[pyarg(positional)] - globals: PyDictRef, - #[pyarg(any, optional, error_msg = "arg 3 (name) must be None or string")] - name: OptionalArg, - #[pyarg(any, optional, error_msg = "arg 4 (defaults) must be None or tuple")] - argdefs: Option, - #[pyarg(any, optional, error_msg = "arg 5 (closure) must be None or tuple")] - closure: Option, - #[pyarg(any, optional, error_msg = "arg 6 (kwdefaults) must be None or dict")] - kwdefaults: Option, + #[pyarg(any)] + code: PyObjectRef, + #[pyarg(any)] + globals: PyObjectRef, + #[pyarg(any, optional)] + name: Option, + #[pyarg(any, optional)] + argdefs: Option, + #[pyarg(any, optional)] + closure: Option, + #[pyarg(any, optional)] + kwdefaults: Option, } impl Constructor for PyFunction { type Args = PyFunctionNewArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + let bad_argument = |name, expected, value: &PyObject| { + vm.new_type_error(format!( + "function() argument '{name}' must be {expected}, not {}", + if vm.is_none(value) { + "None".into() + } else { + value.class().slot_name() + } + )) + }; + let code = args + .code + .downcast_ref::() + .ok_or_else(|| bad_argument("code", "code", &args.code))?; + let globals = args + .globals + .downcast_ref::() + .ok_or_else(|| bad_argument("globals", "dict", &args.globals))?; + let name = optional_function_argument::( + args.name.as_deref(), + "arg 3 (name) must be None or string", + vm, + )?; + let argdefs = optional_function_argument::( + args.argdefs.as_deref(), + "arg 4 (defaults) must be None or tuple", + vm, + )?; + let closure = optional_function_argument::( + args.closure.as_deref(), + "arg 5 (closure) must be None or tuple", + vm, + )?; + if closure.is_none() && !code.freevars.is_empty() { + return Err(vm.new_type_error("arg 5 (closure) must be tuple")); + } + let kwdefaults = optional_function_argument::( + args.kwdefaults.as_deref(), + "arg 6 (kwdefaults) must be None or dict", + vm, + )?; // Handle closure - must be a tuple of cells - let closure = if let Some(closure_tuple) = args.closure { + let closure = if let Some(closure_tuple) = closure { // Check that closure length matches code's free variables - if closure_tuple.as_slice().len() != args.code.freevars.len() { - return Err(vm.new_value_error(format!( - "{} requires closure of length {}, not {}", - args.code.obj_name, - args.code.freevars.len(), - closure_tuple.as_slice().len() + if closure_tuple.as_slice().len() != code.freevars.len() { + return Err(vm.new_value_error(wtf8_concat!( + code.co_name.as_wtf8(), + format!( + " requires closure of length {}, not {}", + code.freevars.len(), + closure_tuple.as_slice().len() + ), ))); } // Validate that all items are cells and create typed tuple + for value in closure_tuple.as_slice() { + if value.downcast_ref::().is_none() { + return Err(vm.new_type_error(format!( + "arg 5 (closure) expected cell, found {}", + value.class().slot_name() + ))); + } + } let typed_closure = closure_tuple.try_into_typed::(vm)?; Some(typed_closure) - } else if !args.code.freevars.is_empty() { - return Err(vm.new_type_error("arg 5 (closure) must be tuple")); } else { None }; - let mut func = Self::new(args.code.clone(), args.globals.clone(), vm)?; + vm.audit("function.__new__", || (code.to_owned(),))?; + let mut func = Self::new(code.to_owned(), globals.to_owned().into(), vm)?; // Set function name if provided - if let Some(name) = args.name.into_option() { - *func.name.lock() = name.clone(); - // Also update qualname to match the name - *func.qualname.lock() = name; + if let Some(name) = name { + *func.name.lock() = name; } // Now set additional attributes directly if let Some(closure_tuple) = closure { func.closure = Some(closure_tuple); } - if let Some(argdefs) = args.argdefs { + if let Some(argdefs) = argdefs { func.defaults_and_kwdefaults.lock().0 = Some(argdefs); } - if let Some(kwdefaults) = args.kwdefaults { + if let Some(kwdefaults) = kwdefaults { func.defaults_and_kwdefaults.lock().1 = Some(kwdefaults); } + // Keep the original arguments alive through audits and globals lookups. Ok(func) } } +fn optional_function_argument( + value: Option<&PyObject>, + message: &str, + vm: &VirtualMachine, +) -> PyResult>> { + value + .filter(|value| !vm.is_none(value)) + .map(|value| { + value + .downcast_ref::() + .map(ToOwned::to_owned) + .ok_or_else(|| vm.new_type_error(message)) + }) + .transpose() +} + #[pyclass(module = false, name = "method", traverse)] #[derive(Debug)] pub struct PyBoundMethod { - #[pymember(name = "__self__")] - object: PyObjectRef, #[pymember(name = "__func__")] function: PyObjectRef, + #[pymember(name = "__self__")] + object: PyObjectRef, } impl Callable for PyBoundMethod { @@ -1363,12 +1499,13 @@ impl Comparable for PyBoundMethod { zelf: &Py, other: &PyObject, op: PyComparisonOp, - _vm: &VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); Ok(PyComparisonValue::Implemented( - zelf.function.is(&other.function) && zelf.object.is(&other.object), + vm.identical_or_equal(&zelf.function, &other.function)? + && zelf.object.is(&other.object), )) }) } @@ -1435,7 +1572,7 @@ impl Constructor for PyBoundMethod { impl PyBoundMethod { #[must_use] pub const fn new(object: PyObjectRef, function: PyObjectRef) -> Self { - Self { object, function } + Self { function, object } } #[inline] @@ -1472,9 +1609,28 @@ impl Py { &self, vm: &VirtualMachine, ) -> PyResult<(PyObjectRef, (PyObjectRef, PyObjectRef))> { - let builtins_getattr = vm.builtins.get_attr("getattr", vm)?; let func_self = self.object.clone(); - let func_name = self.function.get_attr("__name__", vm)?; + let mut func_name = self.function.get_attr("__name__", vm)?; + if let Some(name) = func_name.downcast_ref::() + && name.as_bytes().starts_with(b"__") + && !name.as_bytes().ends_with(b"__") + && !name.as_bytes().contains(&b'.') + { + let class = func_self + .downcast_ref::() + .unwrap_or_else(|| func_self.class()); + let class_name = class.__name__(vm); + let class_name = class_name + .as_wtf8() + .trim_start_matches(|ch| ch.to_u32() == u32::from(b'_')); + if !class_name.is_empty() { + func_name = vm + .ctx + .new_str(wtf8_concat!("_", class_name, name.as_wtf8())) + .into(); + } + } + let builtins_getattr = vm.eval_get_builtin(vm.ctx.intern_str("getattr"))?; Ok((builtins_getattr, (func_self, func_name))) } @@ -1482,44 +1638,6 @@ impl Py { fn __doc__(&self, vm: &VirtualMachine) -> PyResult { self.function.get_attr("__doc__", vm) } - - #[pygetset] - fn __module__(&self, vm: &VirtualMachine) -> Option { - self.function.get_attr("__module__", vm).ok() - } - - #[pymethod] - fn __dir__(&self, vm: &VirtualMachine) -> PyResult { - let func_dir = vm.dir(Some(self.function.clone()))?; - - let bound_only = [ - "__self__", - "__func__", - "__doc__", - "__module__", - "__call__", - "__get__", - "__repr__", - ]; - - let mut seen = std::collections::HashSet::new(); - let mut result: Vec = Vec::new(); - - for item in func_dir.borrow_vec().iter() { - if let Ok(s) = item.clone().downcast::() { - seen.insert(s.as_wtf8().to_string()); - } - result.push(item.clone()); - } - - for name in bound_only { - if seen.insert(name.to_owned()) { - result.push(vm.ctx.new_str(name).into()); - } - } - - Ok(PyList::from(result)) - } } impl PyPayload for PyBoundMethod { @@ -1592,12 +1710,11 @@ impl PyCell { // What was here is released after the lock, the way `Py_XSETREF` stores // before it decrefs. Releasing it under the lock would let a `__del__` // that reads this cell wait on a lock this call still holds. - let replaced = core::mem::replace(&mut *self.contents.lock(), x); - drop(replaced); + let _replaced = core::mem::replace(&mut *self.contents.lock(), x); } } -#[pyclass(with(Constructor, Representable))] +#[pyclass(with(Constructor, Representable), flags(IMMUTABLETYPE))] impl Py { #[pyslot] fn slot_richcompare( @@ -1614,7 +1731,11 @@ impl Py { }; // compare cells by contents; empty cells come before anything else match (zelf.get(), other.get()) { - (Some(a), Some(b)) => a.rich_compare(b, op, vm).map(Either::A), + (Some(a), Some(b)) => { + let result = PyObject::rich_compare(&a, &b, op, vm).map(Either::A); + drop(a); + result + } (a, b) => Ok(Either::B(op.eval_ord(b.is_none().cmp(&a.is_none())).into())), } } @@ -1779,7 +1900,7 @@ pub(crate) fn vectorcall_function( // is called in, and a fresh `MAKE_FUNCTION` each time keeps those out // of the call-site specialization that would otherwise catch it. args.truncate(nargs); - return Ok(zelf.make_generator_exact_args(args.into_iter(), vm)); + return zelf.make_generator_exact_args(args.into_iter(), vm); } if !has_kwargs && base_simple && nargs == code.arg_count as usize { @@ -1851,6 +1972,12 @@ pub(crate) fn init(context: &'static Context) { .slots .vectorcall .store(Some(vectorcall_function)); + context + .types + .function_type + .slots + .flags + .insert(crate::types::PyTypeFlags::HAVE_VECTORCALL); PyBoundMethod::extend_class(context, context.types.bound_method_type); context @@ -1859,6 +1986,12 @@ pub(crate) fn init(context: &'static Context) { .slots .vectorcall .store(Some(vectorcall_bound_method)); + context + .types + .bound_method_type + .slots + .flags + .insert(crate::types::PyTypeFlags::HAVE_VECTORCALL); PyCell::extend_class(context, context.types.cell_type); } diff --git a/crates/vm/src/builtins/generator.rs b/crates/vm/src/builtins/generator.rs index 8eb6013e703..19072cbb78a 100644 --- a/crates/vm/src/builtins/generator.rs +++ b/crates/vm/src/builtins/generator.rs @@ -122,6 +122,19 @@ impl Py { self.inner.running() } + #[pygetset] + fn gi_state(&self) -> &'static str { + if self.inner.closed() { + "GEN_CLOSED" + } else if self.inner.running() { + "GEN_RUNNING" + } else if self.inner.started() { + "GEN_SUSPENDED" + } else { + "GEN_CREATED" + } + } + #[pygetset] fn gi_code(&self, _vm: &VirtualMachine) -> PyRef { self.inner.code() @@ -129,7 +142,7 @@ impl Py { #[pygetset] fn gi_yieldfrom(&self, _vm: &VirtualMachine) -> Option { - self.inner.frame_opt().and_then(|f| f.yield_from_target()) + self.inner.yield_from_target() } #[pygetset] diff --git a/crates/vm/src/builtins/genericalias.rs b/crates/vm/src/builtins/genericalias.rs index 31e1b4ef1c7..2e1445f098e 100644 --- a/crates/vm/src/builtins/genericalias.rs +++ b/crates/vm/src/builtins/genericalias.rs @@ -1,16 +1,18 @@ +use rustpython_common::wtf8::wtf8_concat; // spell-checker:ignore iparam gaiterobject -use crate::common::lock::LazyLock; +use crate::common::lock::{LazyLock, PyMutex}; use super::type_; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, atomic_func, - builtins::{PyList, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef}, + builtins::{PyList, PyListRef, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef}, class::{PyClassDef, PyClassImpl}, - common::hash, + common::{hash, wtf8::Wtf8Buf}, convert::ToPyObject, - function::{FuncArgs, PyComparisonValue}, + function::{Either, FuncArgs, PyArithmeticValue, PyComparisonValue}, protocol::{PyMappingMethods, PyNumberMethods}, + stdlib::_typing::typing_type_repr, types::{ AsMapping, AsNumber, Callable, Comparable, Constructor, GetAttr, Hashable, IterNext, Iterable, PyComparisonOp, Representable, @@ -40,7 +42,7 @@ pub struct PyGenericAlias { origin: PyObjectRef, #[pymember(name = "__args__")] args: PyTupleRef, - parameters: PyTupleRef, + parameters: PyMutex>, #[pymember(name = "__unpacked__")] starred: bool, // for __unpacked__ attribute } @@ -105,13 +107,12 @@ impl PyGenericAlias { origin: impl Into, args: PyTupleRef, starred: bool, - vm: &VirtualMachine, + _vm: &VirtualMachine, ) -> PyResult { - let parameters = make_parameters(&args, vm)?; Ok(Self { origin: origin.into(), args, - parameters, + parameters: PyMutex::new(None), starred, }) } @@ -130,43 +131,17 @@ impl PyGenericAlias { Self::new(origin, args, false, vm) } - fn repr(&self, vm: &VirtualMachine) -> PyResult { - fn repr_item(obj: &PyObject, vm: &VirtualMachine) -> PyResult { - if obj.is(&vm.ctx.ellipsis) { - return Ok("...".to_string()); - } - - if vm - .get_attribute_opt(obj, identifier!(vm, __origin__))? - .is_some() - && vm - .get_attribute_opt(obj, identifier!(vm, __args__))? - .is_some() - { - return Ok(obj.repr(vm)?.to_string()); - } - - match ( - vm.get_attribute_opt(obj, identifier!(vm, __qualname__))? - .and_then(|o| o.downcast_ref::().map(|n| n.to_string())), - vm.get_attribute_opt(obj, identifier!(vm, __module__))? - .and_then(|o| o.downcast_ref::().map(|m| m.to_string())), - ) { - (None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()), - (Some(qualname), Some(module)) => Ok(if module == "builtins" { - qualname - } else { - format!("{module}.{qualname}") - }), - } - } + fn parameters(&self, vm: &VirtualMachine) -> PyResult { + cached_parameters(&self.parameters, &self.args, vm) + } - fn repr_arg(obj: &PyObject, vm: &VirtualMachine) -> PyResult { - // ParamSpec args can be lists - format their items with repr_item + fn repr(&self, vm: &VirtualMachine) -> PyResult { + fn repr_arg(repr: &mut Wtf8Buf, obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + // ParamSpec args can be lists - format their items as types. if obj.class().is(vm.ctx.types.list_type) { let list = obj.downcast_ref::().unwrap(); let len = list.borrow_vec().len(); - let mut parts = Vec::with_capacity(len); + repr.push_str("["); // Use indexed access so list mutation during repr causes IndexError for i in 0..len { let item = list @@ -174,41 +149,41 @@ impl PyGenericAlias { .get(i) .cloned() .ok_or_else(|| vm.new_index_error("list index out of range"))?; - parts.push(repr_item(&item, vm)?); + if i > 0 { + repr.push_str(", "); + } + typing_type_repr(repr, &item, vm)?; } - Ok(format!("[{}]", parts.join(", "))) + repr.push_str("]"); + Ok(()) } else { - repr_item(obj, vm) + typing_type_repr(repr, obj, vm) } } - let repr_str = format!( - "{}[{}]", - repr_item(&self.origin, vm)?, - if self.args.as_slice().is_empty() { - "()".to_owned() - } else { - self.args - .as_slice() - .iter() - .map(|o| repr_arg(o, vm)) - .collect::>>()? - .join(", ") - } - ); - // Add * prefix if this is a starred GenericAlias - Ok(if self.starred { - format!("*{repr_str}") + let mut repr = Wtf8Buf::from(if self.starred { "*" } else { "" }); + typing_type_repr(&mut repr, &self.origin, vm)?; + repr.push_str("["); + if self.args.as_slice().is_empty() { + repr.push_str("()"); } else { - repr_str - }) + for (i, arg) in self.args.as_slice().iter().enumerate() { + if i > 0 { + repr.push_str(", "); + } + repr_arg(&mut repr, arg, vm)?; + } + } + repr.push_str("]"); + Ok(repr) } fn __getitem__(zelf: &Py, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let new_args = subs_parameters(zelf.as_object(), &zelf.args, &zelf.parameters, needle, vm)?; + let parameters = zelf.parameters(vm)?; + let new_args = subs_parameters(zelf.as_object(), &zelf.args, ¶meters, needle, vm)?; - Ok(Self::new(zelf.origin.clone(), new_args, false, vm)?.into_pyobject(vm)) + Ok(Self::new(zelf.origin.clone(), new_args, zelf.starred, vm)?.into_pyobject(vm)) } fn __ror__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { @@ -236,8 +211,8 @@ impl PyGenericAlias { )] impl Py { #[pygetset] - fn __parameters__(&self) -> PyObjectRef { - self.parameters.clone().into() + fn __parameters__(&self, vm: &VirtualMachine) -> PyResult { + self.parameters(vm) } #[pygetset] @@ -250,7 +225,7 @@ impl Py { } #[pymethod] - fn __dir__(&self, vm: &VirtualMachine) -> PyResult { + fn __dir__(&self, vm: &VirtualMachine) -> PyResult { let dir = vm.dir(Some(self.origin.clone()))?; for exc in &ATTR_EXCEPTIONS { let exc_obj = (*exc).to_pyobject(vm); @@ -279,7 +254,7 @@ impl Py { } else { Ok(PyTuple::new_ref( vec![ - vm.ctx.types.generic_alias_type.to_owned().into(), + zelf.class().to_owned().into(), PyTuple::new_ref(vec![zelf.origin.clone(), zelf.args.clone().into()], &vm.ctx) .into(), ], @@ -312,11 +287,35 @@ impl Py { } } +pub(crate) fn cached_parameters( + cache: &PyMutex>, + args: &Py, + vm: &VirtualMachine, +) -> PyResult { + let cached = cache.lock().clone(); + if let Some(parameters) = cached { + return Ok(parameters); + } + // Attribute lookup can re-enter this alias or union. Compute without the + // lock, then replace even a cache populated by the re-entrant lookup. + let parameters = make_parameters(args, vm); + let _previous = core::mem::replace(&mut *cache.lock(), parameters.as_ref().ok().cloned()); + // A failed outer lookup clears the cache populated by a nested lookup too. + // Cached parameters can own objects with Python finalizers. + parameters +} + pub(crate) fn make_parameters(args: &Py, vm: &VirtualMachine) -> PyResult { make_parameters_from_slice(args.as_slice(), vm) } fn make_parameters_from_slice(args: &[PyObjectRef], vm: &VirtualMachine) -> PyResult { + vm.with_recursion(" in __parameter__ calculation", || { + make_parameters_inner(args, vm) + }) +} + +fn make_parameters_inner(args: &[PyObjectRef], vm: &VirtualMachine) -> PyResult { let mut parameters: Vec = Vec::with_capacity(args.len()); for arg in args { @@ -326,16 +325,21 @@ fn make_parameters_from_slice(args: &[PyObjectRef], vm: &VirtualMachine) -> PyRe } // Check for __typing_subst__ attribute - if arg.get_attr(identifier!(vm, __typing_subst__), vm).is_ok() { + if vm + .get_attribute_opt(arg, identifier!(vm, __typing_subst__))? + .is_some() + { if tuple_index(¶meters, arg).is_none() { parameters.push(arg.clone()); } - } else if let Ok(subparams) = arg.get_attr(identifier!(vm, __parameters__), vm) - && let Ok(sub_params) = subparams.try_to_ref::(vm) + } else if let Some(subparams) = + vm.get_attribute_opt(arg, identifier!(vm, __parameters__))? { - for sub_param in sub_params { - if tuple_index(¶meters, sub_param).is_none() { - parameters.push(sub_param.clone()); + if let Some(sub_params) = subparams.downcast_ref::() { + for sub_param in sub_params { + if tuple_index(¶meters, sub_param).is_none() { + parameters.push(sub_param.clone()); + } } } } else if arg.try_to_ref::(vm).is_ok() || arg.try_to_ref::(vm).is_ok() { @@ -346,9 +350,7 @@ fn make_parameters_from_slice(args: &[PyObjectRef], vm: &VirtualMachine) -> PyRe let list = arg.downcast_ref::().unwrap(); list.borrow_vec().to_vec() }; - let sub = vm.with_recursion("while computing __parameters__", || { - make_parameters_from_slice(&items, vm) - })?; + let sub = make_parameters_from_slice(&items, vm)?; for sub_param in sub.as_slice() { if tuple_index(¶meters, sub_param).is_none() { parameters.push(sub_param.clone()); @@ -558,7 +560,10 @@ pub(crate) fn subs_parameters( if let Some(iparam) = tuple_index(parameters.as_slice(), arg) { subst.call((arg_items[iparam].clone(),), vm)? } else { - subs_tvars(arg.clone(), parameters, &arg_items, vm)? + return Err(vm.new_type_error(format!( + "argument {} with __typing_subst__ was not found in __parameters__", + arg.repr(vm)? + ))); } } else { subs_tvars(arg.clone(), parameters, &arg_items, vm)? @@ -572,8 +577,11 @@ pub(crate) fn subs_parameters( Err(_) => { let arg_type = arg.class().fully_qualified_name(vm)?; let substituted_type = substituted_arg.class().fully_qualified_name(vm)?; - return Err(vm.new_type_error(format!( - "expected __typing_subst__ of {arg_type} objects to return a tuple, not {substituted_type}", + return Err(vm.new_type_error(wtf8_concat!( + "expected __typing_subst__ of ", + arg_type, + " objects to return a tuple, not ", + substituted_type ))); } }; @@ -627,27 +635,51 @@ impl Callable for PyGenericAlias { } impl Comparable for PyGenericAlias { + fn slot_richcompare( + zelf: &PyObject, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult> { + if !matches!(op, PyComparisonOp::Eq | PyComparisonOp::Ne) { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + } + let (Some(zelf), Some(other)) = (zelf.downcast_ref::(), other.downcast_ref::()) + else { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + }; + let equal = if zelf.starred != other.starred + || !zelf + .origin + .rich_compare_bool(&other.origin, PyComparisonOp::Eq, vm)? + { + vm.ctx.new_bool(false).into() + } else { + // Tuple subclasses can return a non-bool result from equality. + zelf.args + .as_object() + .rich_compare(other.args.as_object(), PyComparisonOp::Eq, vm)? + }; + if op == PyComparisonOp::Ne { + // ga_richcompare negates identity with True, without truth conversion. + Ok(Either::B((!equal.is(&vm.ctx.true_value)).into())) + } else { + Ok(Either::A(equal)) + } + } + fn cmp( zelf: &Py, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - op.eq_only(|| { - let other = class_or_notimplemented!(Self, other); - if zelf.starred != other.starred { - return Ok(PyComparisonValue::Implemented(false)); - } - Ok(PyComparisonValue::Implemented( - zelf.origin - .rich_compare_bool(&other.origin, PyComparisonOp::Eq, vm)? - && zelf.args.as_object().rich_compare_bool( - other.args.as_object(), - PyComparisonOp::Eq, - vm, - )?, - )) - }) + match Self::slot_richcompare(zelf.as_object(), other, op, vm)? { + Either::A(value) => PyArithmeticValue::from_object(vm, value) + .map(|value| value.try_to_bool(vm)) + .transpose(), + Either::B(value) => Ok(value), + } } } @@ -677,7 +709,7 @@ impl GetAttr for PyGenericAlias { impl Representable for PyGenericAlias { #[inline] - fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { zelf.repr(vm) } } @@ -731,11 +763,13 @@ impl Iterable for PyGenericAliasIterator { impl crate::types::IterNext for PyGenericAliasIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { use crate::protocol::PyIterReturn; - let mut guard = zelf.obj.lock(); - let obj = match guard.take() { + let obj = zelf.obj.lock().take(); + let obj = match obj { Some(obj) => obj, None => return Ok(PyIterReturn::StopIteration(None)), }; + // The consumed alias may run a subclass finalizer that re-enters us. + // Keep it alive through result construction, without holding the lock. // Create a starred GenericAlias from the original let alias = obj .downcast_ref::() diff --git a/crates/vm/src/builtins/int.rs b/crates/vm/src/builtins/int.rs index d6799474582..b9d897fdff9 100644 --- a/crates/vm/src/builtins/int.rs +++ b/crates/vm/src/builtins/int.rs @@ -6,15 +6,14 @@ use crate::{ byte::bytes_from_object, class::{PyClassDef, PyClassImpl}, common::{ - format::FormatSpec, hash, int::{bigint_to_finite_float, bytes_to_int, true_div}, wtf8::Wtf8Buf, }, - convert::{IntoPyException, ToPyObject, ToPyResult}, + convert::{ToPyObject, ToPyResult}, function::{ - ArgByteOrder, ArgIntoBool, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue, - PySsize, + ArgByteOrder, ArgBytesLike, ArgIndex, FuncArgs, OptionalArg, PyArithmeticValue, + PyComparisonValue, int_as_ssize, }, protocol::{PyNumberMethods, handle_bytes_to_int_err, numeric_literal_from_str}, types::{AsNumber, Comparable, Constructor, Hashable, PyComparisonOp, Representable}, @@ -23,9 +22,10 @@ use alloc::fmt; use core::cell::Cell; use core::ops::{Neg, Not}; use core::ptr::NonNull; -use malachite_bigint::{BigInt, Sign}; +use malachite_bigint::{BigInt, BigUint, Sign}; use num_integer::{ExtendedGcd, Integer}; use num_traits::{One, Pow, PrimInt, Signed, ToPrimitive, Zero}; +use rustpython_common::wtf8::wtf8_concat; #[pyclass(module = false, name = "int")] #[derive(Debug)] @@ -211,8 +211,14 @@ fn inner_lshift(base: &BigInt, bits: &BigInt, vm: &VirtualMachine) -> PyResult { bits, |base, bits| base << bits, |bits, vm| { - // CPython's limit: `(i64::MAX - 1) / 30` digits of 30 bits. - const MAX_DIGITS: u128 = (i64::MAX as u128 - 1) / 30; + // Match CPython's MAX_LONG_DIGITS for 30-bit, u32 digits. On + // 32-bit platforms the allocation, including the reference count, + // type pointer and digit-count tag, must fit in Py_ssize_t. + const MAX_DIGITS: u128 = if usize::BITS < 64 { + (isize::MAX as u128 - 3 * size_of::() as u128) / size_of::() as u128 + } else { + (i64::MAX as u128 - 1) / 30 + }; let digits = bits.to_u128().map(|shift| { u128::from(base.bits().div_ceil(30)) + shift / 30 + u128::from(shift % 30 != 0) }); @@ -220,8 +226,9 @@ fn inner_lshift(base: &BigInt, bits: &BigInt, vm: &VirtualMachine) -> PyResult { return Err(vm.new_overflow_error("too many digits in integer")); } let shift = bits.to_u64().ok_or_else(|| vm.no_memory_error())?; + let shift_bits = usize::try_from(shift).map_err(|_| vm.no_memory_error())?; reserve_result_bits(base.bits().checked_add(shift), vm)?; - usize::try_from(shift).map_err(|_| vm.no_memory_error()) + Ok(shift_bits) }, vm, ) @@ -296,6 +303,11 @@ impl Constructor for PyInt { return Err(vm.new_type_error("int.__new__(bool) is not safe, use bool.__new__()")); } + // Preserve the keyword-free long_vectorcall arity diagnostic. + if args.kwargs.is_empty() && args.args.len() > 2 { + return Err(vm.new_arity_type_error(Self::NAME, 0..=2, args.args.len())); + } + // Optimization: return exact int as-is (only for exact int type, not subclasses) if cls.is(vm.ctx.types.int_type) && args.args.len() == 1 @@ -333,6 +345,17 @@ impl Constructor for PyInt { } impl PyInt { + /// PyNumber_AsSsize_t with no overflow exception, as used by slice indices. + pub(crate) fn as_saturated_index(&self) -> isize { + self.value.to_isize().unwrap_or_else(|| { + if self.value.is_negative() { + isize::MIN + } else { + isize::MAX + } + }) + } + fn with_value(cls: PyTypeRef, value: T, vm: &VirtualMachine) -> PyResult> where T: Into + ToPrimitive, @@ -409,6 +432,12 @@ impl Py { } } + // PyLong_AsSsize_t after the caller has established the actual int type. + pub(crate) fn as_ssize_t(&self, vm: &VirtualMachine) -> PyResult { + isize::try_from(self.as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C ssize_t")) + } + // PyLong_AsUInt32, PyLong_AsUInt64 and the unsigned argument converters: // a negative value for an unsigned type raises ValueError. pub fn try_to_primitive(&self, vm: &VirtualMachine) -> PyResult @@ -527,19 +556,19 @@ impl Py { #[derive(FromArgs)] struct RoundArgs { #[pyarg(positional, optional)] - ndigits: Option, + ndigits: Option, } #[pyclass( itemsize = 4, - flags(BASETYPE, _MATCH_SELF), + flags(BASETYPE, _MATCH_SELF, LONG_SUBCLASS), with(PyRef, Comparable, Hashable, Constructor, AsNumber, Representable) )] impl Py { #[pymethod] fn __round__(zelf: PyRef, args: RoundArgs, vm: &VirtualMachine) -> PyRef { if let Some(ndigits) = args.ndigits { - let ndigits = ndigits.as_bigint(); + let ndigits = ndigits.as_ref().as_bigint(); // round(12345, -2) == 12300 // If precision >= 0, then any integer is already rounded correctly if let Some(ndigits) = ndigits.neg().to_u32() @@ -601,20 +630,19 @@ impl Py { if format_spec.is_empty() && !zelf.class().is(vm.ctx.types.int_type) { return Ok(zelf.as_object().str(vm)?.as_wtf8().to_owned()); } - let format_spec = - FormatSpec::parse(format_spec.as_str()).map_err(|err| err.into_pyexception(vm))?; - if format_spec.is_decimal_int_format() { + let spec = crate::format::parse_format_spec(zelf.as_object(), format_spec.as_str(), vm)?; + if spec.is_decimal_int_format() { check_int_to_str_digits(zelf.as_bigint(), vm)?; } - let result = if format_spec.has_locale_format() { + let result = if spec.has_locale_format() { let locale = crate::format::get_locale_info(); - format_spec.format_int_locale(zelf.as_bigint(), &locale) + spec.format_int_locale(zelf.as_bigint(), &locale) } else { - format_spec.format_int(zelf.as_bigint()) + spec.format_int(zelf.as_bigint()) }; - result - .map(Wtf8Buf::from_string) - .map_err(|err| err.into_pyexception(vm)) + result.map(Wtf8Buf::from_string).map_err(|err| { + crate::format::format_spec_error(err, zelf.as_object(), format_spec.as_str(), vm) + }) } #[pymethod] @@ -638,71 +666,116 @@ impl Py { } #[pyclassmethod] - fn from_bytes( - cls: PyTypeRef, - args: IntFromByteArgs, - vm: &VirtualMachine, - ) -> PyResult> { - let signed = args.signed.into(); - // PyObject_Bytes, so an iterable of ints is as good as a buffer - let bytes = bytes_from_object(vm, &args.bytes)?; - let value = match (args.byteorder, signed) { - (ArgByteOrder::Big, true) => BigInt::from_signed_bytes_be(&bytes), - (ArgByteOrder::Big, false) => BigInt::from_bytes_be(Sign::Plus, &bytes), - (ArgByteOrder::Little, true) => BigInt::from_signed_bytes_le(&bytes), - (ArgByteOrder::Little, false) => BigInt::from_bytes_le(Sign::Plus, &bytes), - }; - PyInt::with_value(cls, value, vm) + fn from_bytes(cls: PyTypeRef, args: IntFromByteArgs, vm: &VirtualMachine) -> PyResult { + let IntFromByteArgs { + bytes, + byteorder, + signed, + } = args; + (|| { + let (byteorder, signed) = + byte_conversion_options(&byteorder, &signed, "from_bytes", vm)?; + let convert = |bytes: &[u8]| match (byteorder, signed) { + (ArgByteOrder::Big, true) => BigInt::from_signed_bytes_be(bytes), + (ArgByteOrder::Big, false) => BigInt::from_bytes_be(Sign::Plus, bytes), + (ArgByteOrder::Little, true) => BigInt::from_signed_bytes_le(bytes), + (ArgByteOrder::Little, false) => BigInt::from_bytes_le(Sign::Plus, bytes), + }; + // Buffer exporters take precedence over __bytes__. Request SIMPLE, + // rather than copying strided exports as the bytes constructor does. + let value = if let Some(bytes) = bytes.downcast_ref_if_exact::(vm) { + convert(bytes.as_bytes()) + } else if bytes.check_buffer() { + let buffer = ArgBytesLike::try_from_borrowed_object(vm, &bytes)?; + buffer.with_ref(convert) + } else if let Some(method) = crate::vm::PyMethod::get_special_ex::( + &bytes, + identifier!(vm, __bytes__), + vm, + true, + )? { + let result = method.invoke((), vm)?; + let Some(bytes) = result.downcast_ref::() else { + return Err(vm.new_type_error(wtf8_concat!( + bytes.class().fully_qualified_name(vm)?, + ".__bytes__() must return a bytes, not ", + result.class().fully_qualified_name(vm)? + ))); + }; + convert(bytes.as_bytes()) + } else { + convert(&bytes_from_object(vm, &bytes)?) + }; + let value = vm.ctx.new_int(value); + if cls.is(vm.ctx.types.int_type) { + Ok(value.into()) + } else { + cls.as_object().call((value,), vm) + } + })() } #[pymethod] fn to_bytes(&self, args: IntToByteArgs, vm: &VirtualMachine) -> PyResult { - let signed: bool = args.signed.into(); - // Bound as `isize`, so a length past `isize::MAX` is an OverflowError rather - // than a failed allocation later on. - let byte_len = args.length; - let byte_len = usize::try_from(byte_len) - .map_err(|_| vm.new_value_error("length argument must be non-negative"))?; - - let value = self.as_bigint(); - match value.sign() { - Sign::Minus if !signed => { - return Err(vm.new_overflow_error("can't convert negative int to unsigned")); + let IntToByteArgs { + length, + byteorder, + signed, + } = args; + (|| { + // Finish binding before conversions, then validate length before either + // byteorder's type check or signed's truth conversion can run. + let byte_len = match &length { + OptionalArg::Present(length) => { + let index = length.try_index(vm)?; + int_as_ssize(index.as_object(), vm)? + } + OptionalArg::Missing => 1, + }; + let byte_len = usize::try_from(byte_len) + .map_err(|_| vm.new_value_error("length cannot be negative"))?; + let (byteorder, signed) = byte_conversion_options(&byteorder, &signed, "to_bytes", vm)?; + + let value = self.as_bigint(); + match value.sign() { + Sign::Minus if !signed => { + return Err(vm.new_overflow_error("can't convert negative int to unsigned")); + } + Sign::NoSign => return Ok(vm.new_zeroed_bytes(byte_len)?.into()), + _ => {} } - Sign::NoSign => return Ok(vm.new_zeroed_bytes(byte_len)?.into()), - _ => {} - } - - let mut origin_bytes = match (args.byteorder, signed) { - (ArgByteOrder::Big, true) => value.to_signed_bytes_be(), - (ArgByteOrder::Big, false) => value.to_bytes_be().1, - (ArgByteOrder::Little, true) => value.to_signed_bytes_le(), - (ArgByteOrder::Little, false) => value.to_bytes_le().1, - }; - let origin_len = origin_bytes.len(); - if origin_len > byte_len { - return Err(vm.new_overflow_error("int too big to convert")); - } - - let mut append_bytes = vm.new_zeroed_bytes(byte_len - origin_len)?; - if value.sign() == Sign::Minus { - append_bytes.fill(255); - } + let mut origin_bytes = match (byteorder, signed) { + (ArgByteOrder::Big, true) => value.to_signed_bytes_be(), + (ArgByteOrder::Big, false) => value.to_bytes_be().1, + (ArgByteOrder::Little, true) => value.to_signed_bytes_le(), + (ArgByteOrder::Little, false) => value.to_bytes_le().1, + }; - let bytes = match args.byteorder { - ArgByteOrder::Big => { - let mut bytes = append_bytes; - bytes.append(&mut origin_bytes); - bytes + let origin_len = origin_bytes.len(); + if origin_len > byte_len { + return Err(vm.new_overflow_error("int too big to convert")); } - ArgByteOrder::Little => { - let mut bytes = origin_bytes; - bytes.append(&mut append_bytes); - bytes + + let mut append_bytes = vm.new_zeroed_bytes(byte_len - origin_len)?; + if value.sign() == Sign::Minus { + append_bytes.fill(255); } - }; - Ok(bytes.into()) + + let bytes = match byteorder { + ArgByteOrder::Big => { + let mut bytes = append_bytes; + bytes.append(&mut origin_bytes); + bytes + } + ArgByteOrder::Little => { + let mut bytes = origin_bytes; + bytes.append(&mut append_bytes); + bytes + } + }; + Ok(bytes.into()) + })() } #[pygetset] @@ -766,24 +839,29 @@ impl Comparable for PyInt { } /// Pre-format check enforcing `sys.get_int_max_str_digits()` on int → str conversions. -/// Mirrors CPython's PEP 644 DoS mitigation. Cheap fast-path for small values via -/// bit-count upper bound on decimal digits. +/// Like CPython's long_to_decimal_string_internal, reject definitely oversized +/// values from their bit length before doing any allocation or conversion. pub(crate) fn check_int_to_str_digits(value: &BigInt, vm: &VirtualMachine) -> PyResult<()> { let limit = vm.state.int_max_str_digits.load(); if limit == 0 { return Ok(()); } let bits = value.bits(); - // Below ~452 decimal digits: definitely under any reasonable limit. + // Below ~452 decimal digits: definitely under any permitted nonzero limit. if bits < 1500 { return Ok(()); } - // Upper bound on decimal digit count: ⌈bits × log10(2)⌉ + 1, with log10(2) ≈ 0.30103. - // Multiply with the u64 bit count: `bits as usize * 30103` wraps on - // 32-bit (wasm32) once bits ≳ 142_500, which silently accepts over-limit - // conversions. - let digits_upper = bits.saturating_mul(30103) / 100_000 + 1; - if digits_upper > u64::try_from(limit).unwrap_or(u64::MAX) { + // 30102 / 100000 < log10(2) < 30103 / 100000. An n-bit magnitude is + // in [2^(n-1), 2^n), so these bounds can accept/reject without allocating. + // Use u128 products to avoid overflow, including on 32-bit targets. + let digits_upper = u128::from(bits) * 30103 / 100_000 + 1; + if digits_upper <= limit as u128 { + return Ok(()); + } + let digits_lower = u128::from(bits - 1) * 30102 / 100_000 + 1; + // Only the narrow uncertain band needs an exact power-of-ten comparison. + // Borrow the magnitude: abs() would copy the entire integer, even positives. + if digits_lower > limit as u128 || value.magnitude() >= &Pow::pow(BigUint::from(10u8), limit) { return Err(vm.new_value_error(format!( "Exceeds the limit ({limit} digits) for integer string conversion; \ use sys.set_int_max_str_digits() to increase the limit" @@ -884,43 +962,91 @@ pub(crate) struct IntOptions { #[derive(FromArgs)] struct IntFromByteArgs { bytes: PyObjectRef, - #[pyarg(any, default = ArgByteOrder::Big)] - byteorder: ArgByteOrder, - #[pyarg(named, default = ArgIntoBool::FALSE)] - signed: ArgIntoBool, + #[pyarg(any, optional, py_default = "'big'")] + byteorder: OptionalArg, + #[pyarg(named, optional, py_default = "False")] + signed: OptionalArg, } #[derive(FromArgs)] struct IntToByteArgs { - #[pyarg(any, default = 1)] - length: PySsize, - #[pyarg(any, default = ArgByteOrder::Big)] - byteorder: ArgByteOrder, - #[pyarg(named, default = ArgIntoBool::FALSE)] - signed: ArgIntoBool, + #[pyarg(any, optional, py_default = "1")] + length: OptionalArg, + #[pyarg(any, optional, py_default = "'big'")] + byteorder: OptionalArg, + #[pyarg(named, optional, py_default = "False")] + signed: OptionalArg, +} + +fn byte_conversion_options( + byteorder: &OptionalArg, + signed: &OptionalArg, + method: &str, + vm: &VirtualMachine, +) -> PyResult<(ArgByteOrder, bool)> { + // Clinic checks that byteorder is a str before converting signed, but its + // value is checked only once both arguments have been converted. + let byteorder = byteorder + .as_ref() + .map(|obj| { + obj.downcast_ref::().ok_or_else(|| { + let name = if vm.is_none(obj) { + "None".to_owned() + } else { + obj.class().slot_name().to_owned() + }; + let name = &name[..name.floor_char_boundary(name.len().min(50))]; + vm.new_type_error(format!( + "{method}() argument 'byteorder' must be str, not {name}" + )) + }) + }) + .transpose()?; + let signed = signed + .as_ref() + .map(|obj| obj.try_to_bool(vm)) + .transpose()? + .unwrap_or(false); + let byteorder = byteorder + .map(|obj| ArgByteOrder::try_from_borrowed_object(vm, obj.as_object())) + .transpose()? + .unwrap_or(ArgByteOrder::Big); + Ok((byteorder, signed)) +} + +pub(crate) fn from_str_literal( + obj: &Py, + base: u32, + vm: &VirtualMachine, +) -> PyResult { + bytes_to_int( + numeric_literal_from_str(obj).as_bytes(), + base, + vm.state.int_max_str_digits.load(), + ) + .map_err(|error| handle_bytes_to_int_err(error, obj.as_object(), vm)) +} + +pub(crate) fn from_bytes_literal(bytes: &[u8], base: u32, vm: &VirtualMachine) -> PyResult { + bytes_to_int(bytes, base, vm.state.int_max_str_digits.load()).map_err(|error| { + // _PyLong_FromBytes reports a bytes snapshot, never a subclass's repr + // or the mutable exporter. Only its first 200 bytes can be displayed. + let literal = vm.ctx.new_bytes(bytes[..bytes.len().min(200)].to_vec()); + handle_bytes_to_int_err(error, literal.as_object(), vm) + }) } fn try_int_radix(obj: &PyObject, base: u32, vm: &VirtualMachine) -> PyResult { match_class!(match obj.to_owned() { - string @ PyStr => { - let s = numeric_literal_from_str(&string); - bytes_to_int(s.as_bytes(), base, vm.state.int_max_str_digits.load()) - .map_err(|e| handle_bytes_to_int_err(e, obj, vm)) - } - bytes @ PyBytes => { - bytes_to_int(bytes.as_bytes(), base, vm.state.int_max_str_digits.load()) - .map_err(|e| handle_bytes_to_int_err(e, obj, vm)) - } - bytearray @ PyByteArray => { - let inner = bytearray.borrow_buf(); - bytes_to_int(&inner, base, vm.state.int_max_str_digits.load()) - .map_err(|e| handle_bytes_to_int_err(e, obj, vm)) - } + string @ PyStr => from_str_literal(&string, base, vm), + bytes @ PyBytes => from_bytes_literal(bytes.as_bytes(), base, vm), + bytearray @ PyByteArray => from_bytes_literal(&bytearray.borrow_buf(), base, vm), _ => Err(vm.new_type_error("int() can't convert non-string with explicit base")), }) } // Retrieve inner int value: +#[cfg(any(test, feature = "serde", feature = "jit"))] pub(crate) fn get_value(obj: &PyObject) -> &BigInt { obj.downcast_ref::().unwrap().as_bigint() } @@ -948,6 +1074,6 @@ pub(crate) fn init(context: &'static Context) { .types .int_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_int)); } diff --git a/crates/vm/src/builtins/interpolation.rs b/crates/vm/src/builtins/interpolation.rs index 73126102ea9..edda4ab093a 100644 --- a/crates/vm/src/builtins/interpolation.rs +++ b/crates/vm/src/builtins/interpolation.rs @@ -5,13 +5,11 @@ use super::{ use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::PyClassImpl, - common::hash::PyHash, convert::ToPyObject, - function::PyComparisonValue, - types::{Comparable, Constructor, Hashable, PyComparisonOp, Representable}, + function::{ArgSpec, FuncArgs}, + types::{Constructor, Representable}, }; -use itertools::Itertools; -use rustpython_common::wtf8::Wtf8Buf; +use rustpython_common::wtf8::{Wtf8Buf, wtf8_concat}; #[pyclass(module = "string.templatelib", name = "Interpolation")] #[derive(Debug, Clone)] @@ -19,7 +17,7 @@ pub struct PyInterpolation { #[pymember(type = "object_ex")] pub value: PyObjectRef, #[pymember(type = "object_ex")] - pub expression: PyStrRef, + pub expression: PyObjectRef, #[pymember(type = "object_ex")] pub conversion: PyObjectRef, // None or 's', 'r', 'a' #[pymember(type = "object_ex")] @@ -34,22 +32,51 @@ impl PyPayload for PyInterpolation { } impl PyInterpolation { + const INVALID_CONVERSION: &'static str = + "Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'"; + + fn valid_conversion(conversion: &PyObject, vm: &VirtualMachine) -> bool { + vm.is_none(conversion) + || conversion + .downcast_ref::() + .is_some_and(|s| matches!(s.to_str(), Some("s" | "r" | "a"))) + } + + fn string_argument( + value: Option, + name: &str, + vm: &VirtualMachine, + ) -> PyResult { + value.map_or_else( + || Ok(vm.ctx.empty_str.to_owned()), + |value| { + value.downcast::().map_err(|value| { + let type_name = value.class().slot_name(); + // _PyArg_BadArgument limits tp_name to 50 UTF-8 bytes, + // omitting a partial final code point. + let type_name = if vm.is_none(&value) { + "None" + } else { + &type_name[..type_name.floor_char_boundary(50)] + }; + vm.new_type_error(format!( + "Interpolation() argument '{name}' must be str, not {type_name}" + )) + }) + }, + ) + } + pub fn new( value: PyObjectRef, - expression: PyStrRef, + expression: PyObjectRef, conversion: PyObjectRef, format_spec: PyStrRef, vm: &VirtualMachine, ) -> PyResult { // Validate conversion like _PyInterpolation_Build does - let is_valid = vm.is_none(&conversion) - || conversion - .downcast_ref::() - .is_some_and(|s| matches!(s.to_str(), Some("s" | "r" | "a"))); - if !is_valid { - return Err(vm.new_system_error( - "Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'", - )); + if !Self::valid_conversion(&conversion, vm) { + return Err(vm.new_system_error(Self::INVALID_CONVERSION)); } Ok(Self { value, @@ -61,54 +88,41 @@ impl PyInterpolation { } impl Constructor for PyInterpolation { - type Args = InterpolationArgs; + type Args = FuncArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let conversion: PyObjectRef = if let Some(s) = args.conversion { - let has_flag = s - .as_bytes() - .iter() - .exactly_one() - .is_ok_and(|s| matches!(*s, b's' | b'r' | b'a')); - if !has_flag { - return Err(vm.new_value_error( - "Interpolation() argument 'conversion' must be one of 's', 'a' or 'r'", - )); - } - s.into() - } else { - vm.ctx.none() - }; - - let expression = args.expression; - let format_spec = args.format_spec; + // Clinic binds every argument before converting them in declaration order. + let mut bound = ArgSpec { + fname: "Interpolation", + keywords: &["value", "expression", "conversion", "format_spec"], + required: 1, + max_positional: 4, + } + .parse(&args, vm)?; + let value = bound[0].take().unwrap(); + let expression = Self::string_argument(bound[1].take(), "expression", vm)?; + let conversion = bound[2].take().unwrap_or_else(|| vm.ctx.none()); + if !vm.is_none(&conversion) && conversion.downcast_ref::().is_none() { + return Err(vm.new_type_error(wtf8_concat!( + "Interpolation() argument 'conversion' must be str, not ", + conversion.class().fully_qualified_name(vm)?, + ))); + } + if !Self::valid_conversion(&conversion, vm) { + return Err(vm.new_value_error(Self::INVALID_CONVERSION)); + } + let format_spec = Self::string_argument(bound[3].take(), "format_spec", vm)?; Ok(Self { - value: args.value, - expression, + value, + expression: expression.into(), conversion, format_spec, }) } } -#[derive(FromArgs)] -pub struct InterpolationArgs { - #[pyarg(positional)] - value: PyObjectRef, - #[pyarg(any, default = "")] - expression: PyStrRef, - #[pyarg( - any, - optional, - error_msg = "Interpolation() argument 'conversion' must be str or None" - )] - conversion: Option, - #[pyarg(any, default = "")] - format_spec: PyStrRef, -} - -#[pyclass(with(Constructor, Comparable, Hashable, Representable))] +#[pyclass(with(Constructor, Representable))] impl PyInterpolation { #[pyattr] fn __match_args__(ctx: &Context) -> PyTupleRef { @@ -142,63 +156,19 @@ impl PyInterpolation { } } -impl Comparable for PyInterpolation { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - op.eq_only(|| { - let other = class_or_notimplemented!(Self, other); - - let eq = vm.bool_eq(&zelf.value, &other.value)? - && vm.bool_eq(zelf.expression.as_object(), other.expression.as_object())? - && vm.bool_eq(&zelf.conversion, &other.conversion)? - && vm.bool_eq(zelf.format_spec.as_object(), other.format_spec.as_object())?; - - Ok(eq.into()) - }) - } -} - -impl Hashable for PyInterpolation { - fn hash(zelf: &Py, vm: &VirtualMachine) -> PyResult { - // Hash based on (value, expression, conversion, format_spec) - let value_hash = zelf.value.hash(vm)?; - let expr_hash = zelf.expression.as_object().hash(vm)?; - let conv_hash = zelf.conversion.hash(vm)?; - let spec_hash = zelf.format_spec.as_object().hash(vm)?; - - // Combine hashes - Ok(value_hash - .wrapping_add(expr_hash.wrapping_mul(3)) - .wrapping_add(conv_hash.wrapping_mul(5)) - .wrapping_add(spec_hash.wrapping_mul(7))) - } -} - impl Representable for PyInterpolation { #[inline] fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let value_repr = zelf.value.repr(vm)?; - let expr_repr = zelf.expression.repr(vm)?; - let spec_repr = zelf.format_spec.repr(vm)?; - let mut result = Wtf8Buf::from("Interpolation("); - result.push_wtf8(value_repr.as_wtf8()); + // Release each repr result before invoking the next field's callback. + result.push_wtf8(zelf.value.repr(vm)?.as_wtf8()); result.push_str(", "); - result.push_str(&expr_repr); + result.push_wtf8(zelf.expression.repr(vm)?.as_wtf8()); result.push_str(", "); - if vm.is_none(&zelf.conversion) { - result.push_str("None"); - } else { - result.push_wtf8(zelf.conversion.repr(vm)?.as_wtf8()); - } + result.push_wtf8(zelf.conversion.repr(vm)?.as_wtf8()); result.push_str(", "); - result.push_str(&spec_repr); + result.push_wtf8(zelf.format_spec.as_object().repr(vm)?.as_wtf8()); result.push_char(')'); - Ok(result) } } diff --git a/crates/vm/src/builtins/iter.rs b/crates/vm/src/builtins/iter.rs index 85f40c25977..afd947868c6 100644 --- a/crates/vm/src/builtins/iter.rs +++ b/crates/vm/src/builtins/iter.rs @@ -4,14 +4,14 @@ use super::{PyInt, PyTupleRef, PyType}; use crate::{ - Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, + AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, - function::ArgCallable, + function::{ArgCallable, int_as_ssize}, object::{Traverse, TraverseFn}, protocol::PyIterReturn, - types::{IterNext, Iterable, SelfIter}, + types::{IterNext, Iterable, PyComparisonOp, SelfIter}, }; -use rustpython_common::lock::{PyMutex, PyRwLock, PyRwLockUpgradableReadGuard}; +use rustpython_common::lock::{PyMutex, PyRwLock}; /// Marks status of iterator. #[derive(Debug, Clone)] @@ -188,9 +188,8 @@ pub(crate) fn locked_step( step: impl FnOnce(&mut PositionIterInternal) -> (PyResult, Option), ) -> PyResult { let mut guard = internal.lock(); - let (ret, released) = step(&mut guard); + let (ret, _released) = step(&mut guard); drop(guard); - drop(released); ret } @@ -224,10 +223,206 @@ pub fn builtins_reversed(vm: &VirtualMachine) -> PyResult { vm.eval_get_builtin(vm.ctx.intern_str("reversed")) } +#[derive(Debug, Clone, Copy)] +pub(crate) enum SequenceIterDirection { + Forward, + Reverse, +} + +#[derive(Debug, Traverse)] +struct SequenceIterState { + sequence: Option, + #[pytraverse(skip)] + index: isize, +} + +/// State for generic iterators whose sequence slots can execute Python code. +/// Unlike the concrete container iterators, these must release their state +/// lock before invoking a slot, allocating a Python object, or dropping an owner. +#[derive(Debug, Traverse)] +pub(crate) struct SequenceIter { + state: PyMutex, + #[pytraverse(skip)] + direction: SequenceIterDirection, +} + +impl SequenceIter { + pub(crate) const fn new( + sequence: PyObjectRef, + index: isize, + direction: SequenceIterDirection, + ) -> Self { + Self { + state: PyMutex::new(SequenceIterState { + sequence: Some(sequence), + index, + }), + direction, + } + } + + fn snapshot(&self) -> (Option, isize) { + let state = self.state.lock(); + (state.sequence.clone(), state.index) + } + + fn exhaust(&self) { + let _released = { + let mut state = self.state.lock(); + if matches!(self.direction, SequenceIterDirection::Reverse) { + state.index = -1; + } + state.sequence.take() + }; + } + + fn get_item(sequence: &PyObject, mut index: isize, vm: &VirtualMachine) -> PyResult { + let seq = sequence.sequence_unchecked(); + // A reentrant state change can wrap the forward index below zero. + // PySequence_GetItem adjusts it once using the sequence length slot. + // Keep this separate from the concrete containers' index handling. + if index < 0 + && seq.slots().has_item() + && let Some(length) = seq.length_opt(vm) + { + index = index.wrapping_add(length? as isize); + } + seq.get_item(index, vm) + } + + pub(crate) fn next(&self, vm: &VirtualMachine) -> PyResult { + let (sequence, index) = self.snapshot(); + let Some(sequence) = sequence else { + return Ok(PyIterReturn::StopIteration(None)); + }; + match self.direction { + SequenceIterDirection::Forward if index == isize::MAX => { + drop(sequence); + return Err(vm.new_overflow_error("iter index too large")); + } + SequenceIterDirection::Reverse if index < 0 => { + drop(sequence); + self.exhaust(); + return Ok(PyIterReturn::StopIteration(None)); + } + _ => {} + } + + let result = Self::get_item(&sequence, index, vm); + // A reentrant call can have removed the iterator's sequence owner. + // Release our temporary owner before publishing the outer result. + drop(sequence); + match result { + Ok(item) => { + let mut state = self.state.lock(); + state.index = match self.direction { + // Forward iteration advances the current index, including + // changes made by __getitem__ or a nested next(). + // CPython's default no-strict-overflow build wraps if + // that callback restored PY_SSIZE_T_MAX. + SequenceIterDirection::Forward => state.index.wrapping_add(1), + // Reverse iteration instead advances the captured index. + // Keep the sequence at -1 until the next next() call. + SequenceIterDirection::Reverse => index - 1, + }; + Ok(PyIterReturn::Return(item)) + } + Err(error) + if error.fast_isinstance(vm.ctx.exceptions.index_error) + || error.fast_isinstance(vm.ctx.exceptions.stop_iteration) => + { + // Clear the whole exception, including StopIteration.value, + // before publishing exhaustion. Its finalizer may reenter. + drop(error); + self.exhaust(); + Ok(PyIterReturn::StopIteration(None)) + } + Err(error) => { + if matches!(self.direction, SequenceIterDirection::Reverse) { + self.exhaust(); + } + Err(error) + } + } + } + + pub(crate) fn length_hint(&self, vm: &VirtualMachine) -> PyResult> { + let (sequence, index) = self.snapshot(); + let Some(sequence) = sequence else { + return Ok(Some(0)); + }; + if matches!(self.direction, SequenceIterDirection::Reverse) && index < 0 { + return Ok(Some(0)); + } + let seq = sequence.sequence_unchecked(); + if matches!(self.direction, SequenceIterDirection::Forward) + && seq.slots().length.load().is_none() + && sequence.mapping_unchecked().slots().length.load().is_none() + { + return Ok(None); + } + let length = seq.length(vm)?; + drop(sequence); + let remaining = match self.direction { + SequenceIterDirection::Forward => { + // iter_len reads the index after the length callback. + let index = self.state.lock().index; + (length as isize).wrapping_sub(index).max(0) as usize + } + SequenceIterDirection::Reverse => { + // reversed_len uses the index captured before the callback. + let remaining = index as usize + 1; + if length < remaining { 0 } else { remaining } + } + }; + Ok(Some(remaining)) + } + + pub(crate) fn set_state(&self, state: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + // PyLong_AsSsize_t accepts int subclasses, not __index__. Convert even + // when exhausted, and retain the original argument through callbacks. + let index = int_as_ssize(state, vm)?; + match self.direction { + SequenceIterDirection::Forward => { + let mut state = self.state.lock(); + if state.sequence.is_some() { + state.index = index.max(0); + } + } + SequenceIterDirection::Reverse => { + let (sequence, current) = self.snapshot(); + if current < 0 { + return Ok(()); + } + let Some(sequence) = sequence else { + return Ok(()); + }; + let length = sequence.sequence_unchecked().length(vm)?; + drop(sequence); + self.state.lock().index = index.clamp(-1, length as isize - 1); + } + } + Ok(()) + } + + /// Resolve the reconstruction function before taking this snapshot. Tuple + /// allocation can also run GC and finalizers, so it follows the lock scope. + pub(crate) fn reduce(&self, func: PyObjectRef, vm: &VirtualMachine) -> PyTupleRef { + let (sequence, index) = self.snapshot(); + if let Some(sequence) = sequence + && (matches!(self.direction, SequenceIterDirection::Forward) || index >= 0) + { + vm.new_tuple((func, (sequence,), index)) + } else { + vm.new_tuple((func, (vm.ctx.empty_tuple.clone(),))) + } + } +} + #[pyclass(module = false, name = "iterator", traverse)] #[derive(Debug)] pub struct PySequenceIterator { - internal: PyMutex>, + internal: SequenceIter, } impl PyPayload for PySequenceIterator { @@ -241,7 +436,7 @@ impl PySequenceIterator { pub fn new(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { let _seq = obj.try_sequence(vm)?; Ok(Self { - internal: PyMutex::new(PositionIterInternal::new(obj, 0)), + internal: SequenceIter::new(obj, 0, SequenceIterDirection::Forward), }) } } @@ -250,60 +445,37 @@ impl PySequenceIterator { impl Py { #[pymethod] fn __length_hint__(&self, vm: &VirtualMachine) -> PyResult { - vm.with_recursion("in __length_hint__", || { - let (obj, position) = { - let internal = self.internal.lock(); - match &internal.status { - IterStatus::Active(obj) => (Some(obj.clone()), internal.position), - IterStatus::Exhausted => (None, 0), - } - }; - if let Some(obj) = obj { - let seq = obj.sequence_unchecked(); - match seq.length_opt(vm) { - Some(len) => { - len.map(|len| PyInt::from(len.saturating_sub(position)).into_pyobject(vm)) - } - None => Ok(vm.ctx.not_implemented()), - } - } else { - Ok(PyInt::from(0).into_pyobject(vm)) - } + vm.with_recursion(" in __length_hint__", || { + Ok(match self.internal.length_hint(vm)? { + Some(length) => PyInt::from(length).into_pyobject(vm), + None => vm.ctx.not_implemented(), + }) }) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_iter(vm)?; - Ok(self.internal.lock().reduce( - func, - |x| x.clone(), - |vm| vm.ctx.empty_tuple.clone().into(), - vm, - )) + Ok(self.internal.reduce(func, vm)) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.internal.lock().set_state(&state, |_, pos| pos, vm) + self.internal.set_state(&state, vm) } } impl SelfIter for PySequenceIterator {} impl IterNext for PySequenceIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_next(&zelf.internal, |obj, pos| { - let seq = obj.sequence_unchecked(); - PyIterReturn::from_getitem_result(seq.get_item(pos as isize, vm), vm) - }) + zelf.internal.next(vm) } } #[pyclass(module = false, name = "callable_iterator", traverse)] #[derive(Debug)] pub struct PyCallableIterator { - sentinel: PyObjectRef, - status: PyRwLock>, + status: PyRwLock>, } impl PyPayload for PyCallableIterator { @@ -317,21 +489,38 @@ impl PyCallableIterator { #[must_use] pub const fn new(callable: ArgCallable, sentinel: PyObjectRef) -> Self { Self { - sentinel, - status: PyRwLock::new(IterStatus::Active(callable)), + status: PyRwLock::new(IterStatus::Active((callable, sentinel))), } } + + fn exhaust(&self) { + let _released = { + let mut status = self.status.write(); + core::mem::replace(&mut *status, IterStatus::Exhausted) + }; + // Dropping the callable or sentinel can invoke a finalizer that calls + // next() again, so both must be released after the state lock. + } } -#[pyclass(with(IterNext, Iterable))] +#[pyclass(with(IterNext, Iterable), flags(IMMUTABLETYPE))] impl Py { #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_iter(vm)?; - let status = self.status.read(); - if let IterStatus::Active(callable) = &*status { - let callable_obj: PyObjectRef = callable.clone().into(); - Ok(vm.new_tuple((func, (callable_obj, self.sentinel.clone())))) + let active = { + let status = self.status.read(); + match &*status { + IterStatus::Active((callable, sentinel)) => { + let callable: PyObjectRef = callable.clone().into(); + Some((callable, sentinel.clone())) + } + IterStatus::Exhausted => None, + } + }; + // Tuple allocation may collect objects whose finalizers re-enter next(). + if let Some(args) = active { + Ok(vm.new_tuple((func, args))) } else { Ok(vm.new_tuple((func, (vm.ctx.empty_tuple.clone(),)))) } @@ -346,30 +535,42 @@ impl IterNext for PyCallableIterator { let callable = { let status = zelf.status.read(); match &*status { - IterStatus::Active(callable) => callable.clone(), + IterStatus::Active((callable, _)) => callable.clone(), IterStatus::Exhausted => return Ok(PyIterReturn::StopIteration(None)), } }; - let ret = callable.invoke((), vm)?; - - // Re-check before comparing, but don't hold the lock while running - // sentinel equality. User __eq__ code can re-enter this iterator. - { - let status = zelf.status.read(); - if !matches!(&*status, IterStatus::Active(_)) { + let ret = callable.invoke((), vm); + drop(callable); + let ret = match PyIterReturn::from_pyresult(ret, vm)? { + PyIterReturn::Return(ret) => ret, + PyIterReturn::StopIteration(value) => { + drop(value); + zelf.exhaust(); return Ok(PyIterReturn::StopIteration(None)); } - } - - let is_sentinel = vm.identical_or_equal(&ret, &zelf.sentinel)?; + }; - if is_sentinel { - let status = zelf.status.upgradable_read(); - if !matches!(&*status, IterStatus::Active(_)) { - return Ok(PyIterReturn::StopIteration(None)); + // Re-check after calling, and release the lock before equality: either + // callback can re-enter and exhaust this iterator. + let sentinel = { + let status = zelf.status.read(); + match &*status { + IterStatus::Active((_, sentinel)) => sentinel.clone(), + IterStatus::Exhausted => return Ok(PyIterReturn::StopIteration(None)), } - *PyRwLockUpgradableReadGuard::upgrade(status) = IterStatus::Exhausted; + }; + let is_sentinel = if sentinel.is(&ret) { + drop(sentinel); + true + } else { + // Consume the snapshot before truth conversion: __bool__ can + // exhaust us and observe the sentinel's finalizer immediately. + let comparison = sentinel.rich_compare(ret.clone(), PyComparisonOp::Eq, vm)?; + comparison.try_to_bool(vm)? + }; + if is_sentinel { + zelf.exhaust(); Ok(PyIterReturn::StopIteration(None)) } else { Ok(PyIterReturn::Return(ret)) diff --git a/crates/vm/src/builtins/list.rs b/crates/vm/src/builtins/list.rs index d6a2c1669a7..137c9e8d956 100644 --- a/crates/vm/src/builtins/list.rs +++ b/crates/vm/src/builtins/list.rs @@ -1,11 +1,11 @@ +use super::native_iter::{NativeIterKind, NativeSequenceIter}; use super::{ - PositionIterInternal, PyGenericAlias, PyTupleRef, PyType, PyTypeRef, + PyGenericAlias, PyTupleRef, PyType, PyTypeRef, iter::{builtins_iter, builtins_reversed}, - locked_next, locked_rev_next, }; use crate::atomic_func; use crate::common::lock::{ - PyMappedRwLockReadGuard, PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard, + PyMappedRwLockReadGuard, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard, }; use crate::object::{Traverse, TraverseFn}; use crate::{ @@ -13,11 +13,11 @@ use crate::{ builtins::{PyFloat, PyInt, PyStr, PyTuple}, class::{PyClassDef, PyClassImpl}, convert::ToPyObject, - function::{Either, FuncArgs, OptionalArg, PyComparisonValue, PySsize}, + function::{Either, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue, PySsize}, protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods}, recursion::ReprGuard, sequence::{MutObjectSequenceOp, OptionalRangeArgs, SequenceExt, SequenceMutExt}, - sliceable::{SaturatedSlice, SequenceIndex, SliceableSequenceOp}, + sliceable::{NameList, SaturatedSlice, SequenceIndex, SliceableSequenceOp}, sorting::timsort, types::{ AsMapping, AsSequence, Comparable, Constructor, Initializer, IterNext, Iterable, @@ -73,11 +73,14 @@ unsafe impl Traverse for PyList { // This is safe because during GC collection, the object is unreachable // and no other code should be accessing it. if let Some(mut guard) = self.elements.try_write() { + let mut elements = core::mem::take(&mut *guard); + // Only detached children are reversed; callbacks run after unlocking. + elements.reverse(); if out.is_empty() { // Reuse the allocation so deallocation does not need more memory. - *out = core::mem::take(&mut *guard); + *out = elements; } else { - out.extend(guard.drain(..)); + out.extend(elements); } } } @@ -215,13 +218,16 @@ impl PyList { core::mem::swap(&mut *guard, &mut elements); mutated }; - res?; - - if mutated { - return Err(vm.new_value_error("list modified during sort")); - } - - Ok(()) + let result = res.and_then(|()| { + if mutated { + Err(vm.new_value_error("list modified during sort")) + } else { + Ok(()) + } + }); + // The original list is visible and unlocked before finalizers run. + elements.into_iter().rev().for_each(drop); + result } fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { @@ -264,7 +270,7 @@ impl PyList { } fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - match SequenceIndex::try_from_borrowed_object(vm, needle, "list")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => { let vec = self.borrow_vec(); let pos = vec @@ -285,7 +291,7 @@ impl PyList { value: Option, vm: &VirtualMachine, ) -> PyResult<()> { - let removed = { + let _removed = { let mut elements = self.borrow_vec_mut(); let index = elements .wrap_index(index) @@ -296,7 +302,6 @@ impl PyList { elements.remove(index) } }; - drop(removed); Ok(()) } @@ -356,14 +361,12 @@ impl PyList { }; if slice.step() == 1 { removed.into_iter().rev().for_each(drop); - } else { - drop(removed); } Ok(()) } fn _setitem(&self, needle: &PyObject, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - match SequenceIndex::try_from_borrowed_object(vm, needle, "list")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(index) => self.assign_item(index, Some(value), vm), SequenceIndex::Slice(slice) => { let items = extract_cloned(&value, self, vm)?; @@ -396,7 +399,7 @@ impl PyList { } fn _delitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - match SequenceIndex::try_from_borrowed_object(vm, needle, "list")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => self.assign_item(i, None, vm), SequenceIndex::Slice(slice) => self.assign_slice(slice, None, vm), } @@ -417,7 +420,7 @@ impl PyList { AsSequence, Representable ), - flags(BASETYPE, SEQUENCE, _MATCH_SELF) + flags(BASETYPE, SEQUENCE, _MATCH_SELF, LIST_SUBCLASS) )] impl Py { #[pymethod] @@ -521,9 +524,9 @@ impl Py { #[pymethod] fn __reversed__(zelf: PyRef) -> PyListReverseIterator { - let position = zelf.__len__().saturating_sub(1); + let position = zelf.__len__() as isize - 1; PyListReverseIterator { - internal: PyMutex::new(PositionIterInternal::new(zelf, position)), + internal: NativeSequenceIter::new(zelf, NativeIterKind::ListReverse, position), } } @@ -544,12 +547,12 @@ impl Py { range: OptionalRangeArgs, vm: &VirtualMachine, ) -> PyResult { - let (start, stop) = range.saturate(self.__len__(), vm)?; - let index = self.mut_index_range(vm, &value, start..stop)?; + let bounds = range.index_range(|| self.__len__(), vm)?; + let index = self.mut_index_range(vm, &value, bounds)?; if let Some(index) = index.into() { Ok(index) } else { - Err(vm.new_value_error(format!("'{}' is not in list", value.str(vm)?))) + Err(vm.new_value_error("list.index(x): x not in list")) } } @@ -575,14 +578,13 @@ impl Py { if let Some(index) = index.into() { // defer delete out of borrow - let removed = { + let _removed = { let mut elements = self.borrow_vec_mut(); (index < elements.len()).then(|| elements.remove(index)) }; - drop(removed); Ok(()) } else { - Err(vm.new_value_error(format!("'{}' is not in list", value.str(vm)?))) + Err(vm.new_value_error("list.remove(x): x not in list")) } } @@ -767,38 +769,82 @@ impl AsSequence for PyList { impl Iterable for PyList { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { Ok(PyListIterator { - internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), + internal: NativeSequenceIter::new(zelf, NativeIterKind::List, 0), } .into_pyobject(vm)) } } impl Comparable for PyList { + fn slot_richcompare( + zelf: &PyObject, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult> { + let (Some(zelf), Some(other)) = (zelf.downcast_ref::(), other.downcast_ref::()) + else { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + }; + if let Some(equal) = op.identical_optimization(zelf, other) { + return Ok(Either::B(equal.into())); + } + if matches!(op, PyComparisonOp::Eq | PyComparisonOp::Ne) + && zelf.__len__() != other.__len__() + { + return Ok(Either::B((op == PyComparisonOp::Ne).into())); + } + + let mut index = 0; + loop { + let a = zelf.borrow_vec().get(index).cloned(); + let b = other.borrow_vec().get(index).cloned(); + let (Some(a), Some(b)) = (a, b) else { + break; + }; + let equal = vm.identical_or_equal(&a, &b); + // Equality and finalizers may replace, remove, or append elements. + // Release both roots before observing the lists again, left first. + drop(a); + if !equal? { + break; + } + index += 1; + } + + let a_len = zelf.__len__(); + let b_len = other.__len__(); + if index >= a_len || index >= b_len { + return Ok(Either::B(op.eval_ord(a_len.cmp(&b_len)).into())); + } + if let Some(equal) = op.eval_eq(|| false) { + return Ok(Either::B(equal.into())); + } + // CPython reloads the first unequal pair after its equality callback. + let a = zelf.borrow_vec().get(index).cloned(); + let b = other.borrow_vec().get(index).cloned(); + let (Some(a), Some(b)) = (a, b) else { + return Ok(Either::B( + op.eval_ord(zelf.__len__().cmp(&other.__len__())).into(), + )); + }; + let result = PyObject::rich_compare(&a, &b, op, vm); + drop(a); + result.map(Either::A) + } + fn cmp( zelf: &Py, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - if let Some(res) = op.identical_optimization(zelf, other) { - return Ok(res.into()); + match Self::slot_richcompare(zelf.as_object(), other, op, vm)? { + Either::A(value) => PyArithmeticValue::from_object(vm, value) + .map(|value| value.try_to_bool(vm)) + .transpose(), + Either::B(value) => Ok(value), } - let other = class_or_notimplemented!(Self, other); - // Item comparison can mutate either list (clear, resize). Holding the - // element lock across that callback deadlocks on the write side. - crate::iter::richcompare_mutating_seqs( - |i| { - let a = zelf.borrow_vec(); - (a.len(), a.get(i).cloned()) - }, - |i| { - let b = other.borrow_vec(); - (b.len(), b.get(i).cloned()) - }, - op, - vm, - ) - .map(PyComparisonValue::Implemented) } } @@ -1009,39 +1055,27 @@ fn tuple_lt(elem: &Elem, a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyR } } -fn timsort_by(items: &mut [T], reverse: bool, key: &K, mut lt: L) -> PyResult<()> +fn timsort_by(items: &mut [T], key: &K, mut lt: L) -> PyResult<()> where T: Clone, K: Fn(&T) -> &PyObject, L: FnMut(&PyObject, &PyObject) -> PyResult, { - timsort(items, &mut |a, b| { - let (a, b) = if reverse { - (key(b), key(a)) - } else { - (key(a), key(b)) - }; - lt(a, b) - }) + timsort(items, &mut |a, b| lt(key(a), key(b))) } -fn timsort_specialized( - vm: &VirtualMachine, - items: &mut [T], - reverse: bool, - key: K, -) -> PyResult<()> +fn timsort_specialized(vm: &VirtualMachine, items: &mut [T], key: K) -> PyResult<()> where T: Clone, K: Fn(&T) -> &PyObject, { match pre_sort_check(items.iter().map(&key), vm) { - PreSort::Str => timsort_by(items, reverse, &key, |a, b| Ok(str_lt(a, b))), - PreSort::Int => timsort_by(items, reverse, &key, |a, b| Ok(int_lt(a, b))), - PreSort::Float => timsort_by(items, reverse, &key, |a, b| Ok(float_lt(a, b))), - PreSort::Object(cmp) => timsort_by(items, reverse, &key, |a, b| object_lt(cmp, a, b, vm)), - PreSort::Tuple(elem) => timsort_by(items, reverse, &key, |a, b| tuple_lt(&elem, a, b, vm)), - PreSort::Generic => timsort_by(items, reverse, &key, |a, b| { + PreSort::Str => timsort_by(items, &key, |a, b| Ok(str_lt(a, b))), + PreSort::Int => timsort_by(items, &key, |a, b| Ok(int_lt(a, b))), + PreSort::Float => timsort_by(items, &key, |a, b| Ok(float_lt(a, b))), + PreSort::Object(cmp) => timsort_by(items, &key, |a, b| object_lt(cmp, a, b, vm)), + PreSort::Tuple(elem) => timsort_by(items, &key, |a, b| tuple_lt(&elem, a, b, vm)), + PreSort::Generic => timsort_by(items, &key, |a, b| { a.rich_compare_bool(b, PyComparisonOp::Lt, vm) }), } @@ -1054,28 +1088,49 @@ fn do_sort( reverse: bool, ) -> PyResult<()> { if let Some(key_func) = key_func { - let mut items = values - .iter() - .map(|x| Ok((x.clone(), key_func.call((x.clone(),), vm)?))) - .collect::, _>>()?; - timsort_specialized( - vm, - &mut items, - reverse, - |item: &(PyObjectRef, PyObjectRef)| &*item.1, - )?; + let mut items = Vec::new(); + items + .try_reserve_exact(values.len()) + .map_err(|_| vm.no_memory_error())?; + for value in values.iter() { + let key = match key_func.call((value.clone(),), vm) { + Ok(key) => key, + Err(error) => { + // Key construction unwinds in reverse, unlike completed sorting. + items.into_iter().rev().for_each(drop); + return Err(error); + } + }; + items.push((value.clone(), key)); + } + if reverse { + items.reverse(); + } + let result = + timsort_specialized(vm, &mut items, |item: &(PyObjectRef, PyObjectRef)| &*item.1); + // Even a failed comparison may have permuted the elements. Preserve that + // permutation and release keys in its order before restoring the list. *values = items.into_iter().map(|(val, _)| val).collect(); + if reverse { + values.reverse(); + } + result } else { - timsort_specialized(vm, values, reverse, |x| x)? + if reverse { + values.reverse(); + } + let result = timsort_specialized(vm, values, |x| x); + if reverse { + values.reverse(); + } + result } - - Ok(()) } #[pyclass(module = false, name = "list_iterator", traverse)] #[derive(Debug)] pub(crate) struct PyListIterator { - internal: PyMutex>, + internal: NativeSequenceIter, } impl PyPayload for PyListIterator { @@ -1089,22 +1144,20 @@ impl PyPayload for PyListIterator { impl Py { #[pymethod] fn __length_hint__(&self) -> usize { - self.internal.lock().length_hint(|obj| obj.__len__()) + self.internal.length_hint(|obj| obj.__len__()) } #[pymethod] fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.internal - .lock() - .set_state(&object, |obj, pos| pos.min(obj.__len__()), vm) + self.internal.set_state(&object, |obj| obj.__len__(), vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_iter(vm)?; - Ok(self.internal.lock().reduce( + Ok(self.internal.reduce( func, - |x| x.clone().into(), + |x| x.into(), |vm| vm.ctx.new_list(Vec::new()).into(), vm, )) @@ -1114,32 +1167,22 @@ impl Py { impl PyListIterator { /// Fast path for FOR_ITER specialization. pub(crate) fn fast_next(&self) -> Option { - locked_next(&self.internal, |list, pos| { - let vec = list.borrow_vec(); - Ok(PyIterReturn::from_result(vec.get(pos).cloned().ok_or(None))) - }) - .ok() - .and_then(|r| match r { - PyIterReturn::Return(v) => Some(v), - PyIterReturn::StopIteration(_) => None, - }) + self.internal + .next(|list, pos| list.borrow_vec().get(pos).cloned()) } } impl SelfIter for PyListIterator {} impl IterNext for PyListIterator { fn next(zelf: &Py, _vm: &VirtualMachine) -> PyResult { - locked_next(&zelf.internal, |list, pos| { - let vec = list.borrow_vec(); - Ok(PyIterReturn::from_result(vec.get(pos).cloned().ok_or(None))) - }) + Ok(PyIterReturn::from_result(zelf.fast_next().ok_or(None))) } } #[pyclass(module = false, name = "list_reverseiterator", traverse)] #[derive(Debug)] pub(crate) struct PyListReverseIterator { - internal: PyMutex>, + internal: NativeSequenceIter, } impl PyPayload for PyListReverseIterator { @@ -1153,22 +1196,20 @@ impl PyPayload for PyListReverseIterator { impl Py { #[pymethod] fn __length_hint__(&self) -> usize { - self.internal.lock().rev_length_hint(|obj| obj.__len__()) + self.internal.length_hint(|obj| obj.__len__()) } #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.internal - .lock() - .set_state(&state, |obj, pos| pos.min(obj.__len__()), vm) + self.internal.set_state(&state, |obj| obj.__len__(), vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_reversed(vm)?; - Ok(self.internal.lock().reduce( + Ok(self.internal.reduce( func, - |x| x.clone().into(), + |x| x.into(), |vm| vm.ctx.new_list(Vec::new()).into(), vm, )) @@ -1178,10 +1219,11 @@ impl Py { impl SelfIter for PyListReverseIterator {} impl IterNext for PyListReverseIterator { fn next(zelf: &Py, _vm: &VirtualMachine) -> PyResult { - locked_rev_next(&zelf.internal, |list, pos| { - let vec = list.borrow_vec(); - Ok(PyIterReturn::from_result(vec.get(pos).cloned().ok_or(None))) - }) + Ok(PyIterReturn::from_result( + zelf.internal + .next(|list, pos| list.borrow_vec().get(pos).cloned()) + .ok_or(None), + )) } } @@ -1202,7 +1244,10 @@ fn vectorcall_list( pub(crate) fn init(context: &'static Context) { let list_type = &context.types.list_type; PyList::extend_class(context, list_type); - list_type.slots.vectorcall.store(Some(vectorcall_list)); + list_type + .slots + .constructor_vectorcall + .store(Some(vectorcall_list)); PyListIterator::extend_class(context, context.types.list_iterator_type); PyListReverseIterator::extend_class(context, context.types.list_reverseiterator_type); diff --git a/crates/vm/src/builtins/map.rs b/crates/vm/src/builtins/map.rs index 0a62f2d792b..cbaff38bda6 100644 --- a/crates/vm/src/builtins/map.rs +++ b/crates/vm/src/builtins/map.rs @@ -1,9 +1,12 @@ -use super::{PyType, PyTypeRef}; +use super::{ + PyType, PyTypeRef, + zip::{get_iterators, next_item, release_iterables, strict_value}, +}; use crate::{ - AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, + AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::PyTupleRef, class::PyClassImpl, - function::{ArgIntoBool, FuncArgs, PosArgs}, + function::{FuncArgs, OptionalArg, PosArgs}, protocol::{PyIter, PyIterReturn}, types::{Constructor, IterNext, Iterable, SelfIter}, }; @@ -30,21 +33,21 @@ pub struct PyMapNewArgs { #[pyarg(positional)] function: PyObjectRef, #[pyarg(positional)] - iterable: PyIter, + iterable: PyObjectRef, #[pyarg(flatten)] - iterables: PosArgs, - #[pyarg(named, default)] - strict: bool, + iterables: PosArgs, + #[pyarg(named, default, py_default = "False")] + strict: OptionalArg, } #[derive(FromArgs)] struct MapCallArgs { - #[pyarg(positional)] - function: PyObjectRef, + #[pyarg(positional, optional)] + function: OptionalArg, #[pyarg(flatten)] - iterables: PosArgs, - #[pyarg(named, default)] - strict: bool, + iterables: PosArgs, + #[pyarg(named, default, py_default = "False")] + strict: OptionalArg, } impl Constructor for PyMap { @@ -52,31 +55,58 @@ impl Constructor for PyMap { fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let MapCallArgs { - function: mapper, + function, iterables, strict, } = args.bind_for(vm, "map")?; - let iterators = iterables.into_vec(); - if iterators.is_empty() { - return Err(vm.new_type_error("map() must have at least two arguments.")); - } - let payload = Self { - mapper, - iterators, - strict: Radium::new(strict), - }; - payload.into_ref_with_type(vm, cls).map(Into::into) + let result = (|| { + let strict = strict_value(&strict, vm)?; + let mapper = function + .as_ref() + .into_option() + .filter(|_| !iterables.as_ref().is_empty()) + .ok_or_else(|| vm.new_type_error("map() must have at least two arguments."))?; + let payload = Self::from_iterables(mapper, iterables.iter(), strict, vm)?; + payload.into_ref_with_type(vm, cls).map(Into::into) + })(); + release_iterables(strict, iterables); + result } fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let PyMapNewArgs { + let Self::Args { function, iterable, iterables, strict, } = args; - let _ = (function, iterable, iterables, strict); - Err(vm.new_type_error("use slot_new")) + let result = (|| { + let strict = strict_value(&strict, vm)?; + Self::from_iterables( + &function, + core::iter::once(&iterable).chain(iterables.iter()), + strict, + vm, + ) + })(); + release_iterables(strict, iterables); + result + } +} + +impl PyMap { + fn from_iterables<'a>( + mapper: &PyObjectRef, + iterables: impl IntoIterator, + strict: bool, + vm: &VirtualMachine, + ) -> PyResult { + let iterators = get_iterators(iterables, vm)?; + Ok(Self { + mapper: mapper.clone(), + iterators, + strict: Radium::new(strict), + }) } } @@ -96,10 +126,10 @@ impl PyMap { } #[pymethod] - fn __setstate__(zelf: PyRef, object: PyObjectRef, vm: &VirtualMachine) { - if let Ok(obj) = ArgIntoBool::try_from_object(vm, object) { - zelf.strict.store(obj.into(), atomic::Ordering::Release); - } + fn __setstate__(zelf: PyRef, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + let strict = object.try_to_bool(vm)?; + zelf.strict.store(strict, atomic::Ordering::Release); + Ok(()) } } @@ -107,36 +137,10 @@ impl SelfIter for PyMap {} impl IterNext for PyMap { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let mut next_objs = Vec::new(); - for (idx, iterator) in zelf.iterators.iter().enumerate() { - let item = match iterator.next(vm)? { - PyIterReturn::Return(obj) => obj, - PyIterReturn::StopIteration(v) => { - if zelf.strict.load(atomic::Ordering::Acquire) { - if idx > 0 { - let plural = if idx == 1 { " " } else { "s 1-" }; - return Err(vm.new_value_error(format!( - "map() argument {} is shorter than argument{}{}", - idx + 1, - plural, - idx, - ))); - } - for (idx, iterator) in zelf.iterators[1..].iter().enumerate() { - if let PyIterReturn::Return(_) = iterator.next(vm)? { - let plural = if idx == 0 { " " } else { "s 1-" }; - return Err(vm.new_value_error(format!( - "map() argument {} is longer than argument{}{}", - idx + 2, - plural, - idx + 1, - ))); - } - } - } - return Ok(PyIterReturn::StopIteration(v)); - } - }; + let mut next_objs = Vec::with_capacity(zelf.iterators.len()); + for idx in 0..zelf.iterators.len() { + let item = + crate::raise_if_stop!(next_item(&zelf.iterators, idx, &zelf.strict, "map", vm)?); next_objs.push(item); } diff --git a/crates/vm/src/builtins/mappingproxy.rs b/crates/vm/src/builtins/mappingproxy.rs index 9ee9ff17228..5b0600bbcf9 100644 --- a/crates/vm/src/builtins/mappingproxy.rs +++ b/crates/vm/src/builtins/mappingproxy.rs @@ -1,16 +1,17 @@ -use super::{PyDict, PyDictRef, PyGenericAlias, PyList, PyTuple, PyType, PyTypeRef}; +use super::{PyDict, PyDictRef, PyGenericAlias, PyList, PyStrRef, PyTuple, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, - class::PyClassImpl, + class::{PyClassImpl, StaticType}, common::{hash, lock::LazyLock}, convert::ToPyObject, - function::{ArgMapping, OptionalArg, PyArithmeticValue, PyComparisonValue}, + function::{ArgMapping, Either, OptionalArg, PyComparisonValue}, object::{Traverse, TraverseFn}, protocol::{PyMappingMethods, PyNumberMethods, PySequenceMethods}, + stdlib::PyOrderedDict, types::{ - AsMapping, AsNumber, AsSequence, Comparable, Constructor, Hashable, Iterable, - PyComparisonOp, Representable, + AsMapping, AsNumber, AsSequence, Constructor, Hashable, Iterable, PyComparisonOp, + Representable, }, }; use rustpython_common::wtf8::{Wtf8Buf, wtf8_concat}; @@ -59,15 +60,26 @@ impl From for PyMappingProxy { } } +#[derive(FromArgs)] +pub struct MappingProxyArgs { + mapping: PyObjectRef, +} + impl Constructor for PyMappingProxy { - type Args = PyObjectRef; + type Args = MappingProxyArgs; - fn py_new(_cls: &Py, mapping: Self::Args, vm: &VirtualMachine) -> PyResult { - Self::from_object(mapping, vm) + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + Self::from_object(args.mapping, vm) } } impl PyMappingProxy { + pub(crate) fn from_any_dict(dict: PyRef) -> Self { + Self { + mapping: MappingProxyInner::Mapping(ArgMapping::new(dict.into())), + } + } + pub fn from_object(mapping: PyObjectRef, vm: &VirtualMachine) -> PyResult { if mapping.mapping_unchecked().check() && !mapping.downcastable::() @@ -95,12 +107,9 @@ impl PyMappingProxy { key: &PyObject, vm: &VirtualMachine, ) -> PyResult> { - match class.attributes.as_dict() { - Some(dict) => dict.get_item_opt(key, vm), - None => Ok(key - .as_interned_str(vm) - .and_then(|key| class.attributes.get(key))), - } + // Non-string and string-subclass keys retain their hash and equality + // callbacks even when the namespace uses a native attributes map. + class.attributes.get_item_opt(key, vm) } pub fn __getitem__(&self, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { @@ -109,21 +118,7 @@ impl PyMappingProxy { } fn _contains(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult { - match &self.mapping { - MappingProxyInner::Class(class) => Ok(Self::class_contains(class, key, vm)), - MappingProxyInner::Mapping(mapping) => { - mapping.obj().sequence_unchecked().contains(key, vm) - } - } - } - - fn class_contains(class: &Py, key: &PyObject, vm: &VirtualMachine) -> bool { - match class.attributes.as_dict() { - Some(dict) => dict.contains_key(key, vm), - None => key - .as_interned_str(vm) - .is_some_and(|key| class.attributes.contains(key)), - } + self.to_object(vm)?.sequence_unchecked().contains(key, vm) } pub fn __contains__(&self, key: &PyObject, vm: &VirtualMachine) -> PyResult { @@ -133,17 +128,10 @@ impl PyMappingProxy { fn to_object(&self, vm: &VirtualMachine) -> PyResult { Ok(match &self.mapping { MappingProxyInner::Mapping(d) => d.as_ref().to_owned(), - MappingProxyInner::Class(c) => Self::class_to_dict(c, vm)?, + MappingProxyInner::Class(c) => c.attributes.to_dict(vm)?.into(), }) } - fn class_to_dict(class: &Py, vm: &VirtualMachine) -> PyResult { - if let Some(dict) = class.attributes.as_dict() { - return Ok(dict.copy().to_pyobject(vm)); - } - Ok(PyDict::from_attributes(class.attributes.attributes(&vm.ctx), vm)?.to_pyobject(vm)) - } - fn __len__(&self, vm: &VirtualMachine) -> PyResult { let obj = self.to_object(vm)?; obj.length(vm) @@ -151,36 +139,70 @@ impl PyMappingProxy { fn __ior__(&self, _args: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error(format!( - r#""'|=' is not supported by {}; use '|' instead""#, + "'|=' is not supported by {}; use '|' instead", Self::class(&vm.ctx) ))) } - fn __or__(&self, args: &PyObject, vm: &VirtualMachine) -> PyResult { - vm._or(self.copy(vm)?.as_ref(), args) - } - pub fn copy(&self, vm: &VirtualMachine) -> PyResult { - match &self.mapping { - MappingProxyInner::Mapping(d) => { - vm.call_method(d.obj(), identifier!(vm, copy).as_str(), ()) - } - MappingProxyInner::Class(c) => Self::class_to_dict(c, vm), - } + let obj = self.to_object(vm)?; + vm.call_method(&obj, identifier!(vm, copy).as_str(), ()) } } -#[pyclass(with( - AsMapping, - Iterable, - Constructor, - AsSequence, - Comparable, - Hashable, - AsNumber, - Representable -))] +#[pyclass( + with( + AsMapping, + Iterable, + Constructor, + AsSequence, + Hashable, + AsNumber, + Representable + ), + flags(IMMUTABLETYPE) +)] impl Py { + #[pyslot] + fn slot_richcompare( + zelf: &PyObject, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult> { + let zelf = zelf.downcast_ref::().ok_or_else(|| { + vm.new_type_error(format!( + "unexpected payload for {}", + op.method_name(&vm.ctx).as_str() + )) + })?; + if !matches!(op, PyComparisonOp::Eq | PyComparisonOp::Ne) { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + } + let mut obj = zelf.to_object(vm)?; + // Unknown comparison methods must not receive a mutable dictionary + // protected by the proxy, including a live class namespace. + if obj.class().is(vm.ctx.types.dict_type) + && !(other.class().is(vm.ctx.types.dict_type) + || other.class().is(vm.ctx.types.frozendict_type) + || other.class().is(vm.ctx.types.mappingproxy_type) + || (other.downcastable::() + && other.class().is(PyOrderedDict::static_type()))) + { + obj = obj + .downcast_ref::() + .unwrap() + .copy() + .into_pyobject(vm); + } + obj.rich_compare(other.to_owned(), op, vm).map(Either::A) + } + + #[pymethod] + fn __str__(&self, vm: &VirtualMachine) -> PyResult { + self.to_object(vm)?.str(vm) + } + #[pymethod] fn get( &self, @@ -238,23 +260,6 @@ impl Py { } } -impl Comparable for PyMappingProxy { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - let obj = zelf.to_object(vm)?; - // CPython parity (Objects/descrobject.c::mappingproxy_richcompare): - // delegate to PyObject_RichCompare on the underlying mapping. - let res = obj.rich_compare(other.to_owned(), op, vm)?; - PyArithmeticValue::from_object(vm, res) - .map(|o| o.try_to_bool(vm)) - .transpose() - } -} - impl Hashable for PyMappingProxy { #[inline] fn hash(zelf: &Py, vm: &VirtualMachine) -> PyResult { @@ -296,16 +301,15 @@ impl AsNumber for PyMappingProxy { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { or: Some(|a, b, vm| { - // Mirror CPython's mappingproxy_or: when either side is a - // mappingproxy, unwrap to its underlying mapping and delegate - // to PyNumber_Or so `dict | mp`, `mp | dict`, and `mp | mp` - // all produce a `dict` result. + // Unwrap both proxies, preserving the underlying mappings' + // union methods and arbitrary return values. Keep both + // operands alive until dispatch has finished. let a_obj = match a.downcast_ref::() { - Some(mp) => mp.copy(vm)?, + Some(mp) => mp.to_object(vm)?, None => a.to_pyobject(vm), }; let b_obj = match b.downcast_ref::() { - Some(mp) => mp.copy(vm)?, + Some(mp) => mp.to_object(vm)?, None => b.to_pyobject(vm), }; vm._or(a_obj.as_ref(), b_obj.as_ref()) diff --git a/crates/vm/src/builtins/memory.rs b/crates/vm/src/builtins/memory.rs index 2c9e8c62809..855d25ed0f7 100644 --- a/crates/vm/src/builtins/memory.rs +++ b/crates/vm/src/builtins/memory.rs @@ -1,26 +1,27 @@ use super::{ PositionIterInternal, PyBytes, PyBytesRef, PyGenericAlias, PyInt, PyListRef, PySlice, PyStr, - PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, PyUtf8Str, PyUtf8StrRef, iter::builtins_iter, - locked_next, + PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, iter::IterStatus, }; use crate::common::lock::LazyLock; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, atomic_func, - buffer::{FormatSpec, PackErrorKind}, + buffer::FormatSpec, bytes_inner::{ByteInnerHexOptions, bytes_to_hex}, class::{PyClassImpl, StaticType}, + codecs::{ErrorsHandler, PyEncodeContext}, common::{ borrow::{BorrowedValue, BorrowedValueMut}, + encodings::ascii, hash::PyHash, lock::OnceCell, }, convert::ToPyObject, function::Either, - function::{ArgIndex, NameExcInfo, OptionalArg, PosArgs, PyComparisonValue}, + function::{ArgIndex, ArgSliceIndex, NameExcInfo, OptionalArg, PosArgs, PyComparisonValue}, protocol::{ BufferDescriptor, BufferFlags, BufferMethods, PyBuffer, PyIterReturn, PyMappingMethods, - PySequenceMethods, VecBuffer, + PySequenceMethods, VecBuffer, sequence_index_key, }, sliceable::SequenceIndexOp, types::{ @@ -30,9 +31,11 @@ use crate::{ }; use core::{cmp::Ordering, fmt::Debug, ops::Range}; use crossbeam_utils::atomic::AtomicCell; -use itertools::Itertools; use rustpython_common::lock::PyMutex; +mod format; +use format::{NativeFormat, comparison_format}; + /// The most dimensions a view can describe. PyBUF_MAX_NDIM const MAX_NDIM: usize = 64; @@ -62,7 +65,7 @@ pub struct PyMemoryView { #[pytraverse(skip)] restricted: AtomicCell, #[pytraverse(skip)] - format_spec: FormatSpec, + native_format: Option, // memoryview's options could be different from buffer's options #[pytraverse(skip)] desc: BufferDescriptor, @@ -84,38 +87,51 @@ impl Constructor for PyMemoryView { } impl PyMemoryView { - fn parse_format(format: &str, vm: &VirtualMachine) -> PyResult { - FormatSpec::parse(format.as_bytes(), vm) - } - - /// The single native format character a cast is allowed to name, with an + /// The native format character a cast is allowed to name, with an /// optional `@` in front of it. get_native_fmtchar fn native_fmtchar(format: &str) -> Option { - let format = format.strip_prefix('@').unwrap_or(format); - let [c] = *format.as_bytes() else { - return None; - }; - matches!( - c, - b'c' | b'b' - | b'B' - | b'h' - | b'H' - | b'i' - | b'I' - | b'l' - | b'L' - | b'q' - | b'Q' - | b'n' - | b'N' - | b'f' - | b'd' - | b'e' - | b'?' - | b'P' - ) - .then_some(c) + NativeFormat::parse(format).map(NativeFormat::fmtchar) + } + + // adjust_fmt checks the scalar spelling before indexing or assigning, + // even when the operation will not reach an element (for example tolist + // on an empty view). An unknown single character is rejected only when + // an element is actually packed or unpacked. + fn adjusted_format(&self, vm: &VirtualMachine) -> PyResult<&str> { + let format = self + .desc + .format + .strip_prefix('@') + .unwrap_or(&self.desc.format); + if matches!(format.as_bytes(), [c] | [b'Z', c] if *c != 0) { + Ok(format) + } else { + Err(vm.new_not_implemented_error(format!( + "memoryview: unsupported format {}", + self.desc.format + ))) + } + } + + fn scalar_format(&self, vm: &VirtualMachine) -> PyResult { + let format = self.adjusted_format(vm)?; + self.native_format.ok_or_else(|| { + vm.new_not_implemented_error(format!("memoryview: format {format} not supported")) + }) + } + + fn check_iteration(&self, vm: &VirtualMachine) -> PyResult<()> { + self.try_not_released(vm)?; + match self.desc.ndim() { + 0 => return Err(vm.new_type_error("invalid indexing of 0-dim memory")), + 1 => (), + _ => { + return Err( + vm.new_not_implemented_error("multi-dimensional sub-views are not implemented") + ); + } + } + self.adjusted_format(vm).map(|_| ()) } /// this should be the main entrance to create the memoryview @@ -154,21 +170,37 @@ impl PyMemoryView { } } + /// A readonly view with no Python-visible exporter, as for + /// PyMemoryView_FromBuffer with a NULL Py_buffer.obj. Keep the Rust owner + /// alive so a codec retaining the view cannot create dangling storage. + pub(crate) fn from_anonymous_buffer( + mut buffer: PyBuffer, + vm: &VirtualMachine, + ) -> PyResult { + buffer.desc.readonly = true; + let mut desc = BufferDescriptor::simple(buffer.desc.len, true); + desc.offset = buffer.desc.offset; + let window = PyBufferWindow { source: buffer }.into_pyobject(vm); + Self::from_buffer(PyBuffer::new(window, desc, &BUFFER_WINDOW_METHODS), vm) + } + /// don't use this function to create the memoryview if the buffer is exporting /// via another memoryview, use PyMemoryView::new_view() or PyMemoryView::from_object /// to reduce the chain - pub fn from_buffer(buffer: PyBuffer, vm: &VirtualMachine) -> PyResult { + pub fn from_buffer(buffer: PyBuffer, _vm: &VirtualMachine) -> PyResult { // when we get a buffer means the buffered object is size locked // so we can assume the buffer's options will never change as long // as memoryview is still alive - let format_spec = Self::parse_format(&buffer.desc.format, vm)?; + // Exporter formats need not be accepted by struct or scalar access. + // Byte operations and casts can still use their buffer descriptors. + let native_format = NativeFormat::parse(&buffer.desc.format); let desc = buffer.desc.clone(); Ok(Self { buffer, released: AtomicCell::new(false), restricted: AtomicCell::new(false), - format_spec, + native_format, desc, hash: OnceCell::new(), exports: AtomicCell::new(0), @@ -197,7 +229,7 @@ impl PyMemoryView { buffer: self.buffer.clone(), released: AtomicCell::new(false), restricted: AtomicCell::new(false), - format_spec: self.format_spec.clone(), + native_format: self.native_format, desc: self.desc.clone(), hash: OnceCell::new(), exports: AtomicCell::new(0), @@ -213,7 +245,7 @@ impl PyMemoryView { buffer: self.buffer.detached(), released: AtomicCell::new(false), restricted: AtomicCell::new(false), - format_spec: self.format_spec.clone(), + native_format: self.native_format, desc: self.desc.clone(), hash: OnceCell::new(), exports: AtomicCell::new(0), @@ -296,12 +328,15 @@ impl PyMemoryView { } fn getitem_by_idx(&self, i: isize, vm: &VirtualMachine) -> PyResult { + // Index conversion can release the view before memory_item is entered. + self.try_not_released(vm)?; + self.adjusted_format(vm)?; if self.desc.ndim() != 1 { return Err( vm.new_not_implemented_error("multi-dimensional sub-views are not implemented") ); } - let (shape, _, _) = self.desc.dim_desc[0]; + let shape = self.desc.shape()[0] as usize; // ptr_from_index let index = i .wrapped_at(shape) @@ -318,16 +353,25 @@ impl PyMemoryView { Ok(other.into_ref(&vm.ctx).into()) } - fn getitem_by_multi_idx(&self, indexes: &[isize], vm: &VirtualMachine) -> PyResult { + fn getitem_by_multi_idx(&self, indexes: &Py, vm: &VirtualMachine) -> PyResult { + self.try_not_released(vm)?; + self.adjusted_format(vm)?; let pos = self.pos_from_multi_index(indexes, vm)?; self.unpack_single(pos, vm) } - fn setitem_by_idx(&self, i: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn setitem_by_idx( + &self, + index: &PyObject, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { if self.desc.ndim() != 1 { return Err(vm.new_not_implemented_error("sub-views are not implemented")); } - let (shape, _, _) = self.desc.dim_desc[0]; + // Assigning a sub-view is refused before the index can run Python. + let i = SubscriptNeedle::index_value(index, vm)?; + let shape = self.desc.shape()[0] as usize; // ptr_from_index let index = i .wrapped_at(shape) @@ -337,7 +381,7 @@ impl PyMemoryView { fn setitem_by_multi_idx( &self, - indexes: &[isize], + indexes: &Py, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { @@ -349,51 +393,24 @@ impl PyMemoryView { // The value is converted before the destination is borrowed, because the // conversion runs `__index__` or `__float__`, which can read or write the // same buffer. - // TODO: Optimize - // A value of the wrong kind and a value the format has no room for are - // different errors here, though packing reports both the same way. - let data = self.format_spec.try_pack(vec![value], vm).map_err(|err| { - let what = match err.kind { - PackErrorKind::Type => "type", - PackErrorKind::Value => "value", - PackErrorKind::Raised => return err.exception, - }; - let msg = format!( - "memoryview: invalid {what} for format '{}'", - self.desc.format - ); - match err.kind { - PackErrorKind::Type => vm.new_type_error(msg), - _ => vm.new_value_error(msg), - } - })?; - // The conversion, and the index that produced `pos`, could have released - // the view; `pos` addresses a buffer that is no longer there. - // CHECK_RELEASED_INT_AGAIN - self.try_not_released(vm)?; - let mut bytes = self.buffer.obj_bytes_mut(); - bytes[pos..pos + self.format_spec.size()].copy_from_slice(&data); - Ok(()) + let format = self.scalar_format(vm)?; + // Native packing converts and checks release before borrowing storage. + format.pack(self, value, vm, |data| { + self.buffer.obj_bytes_mut()[pos..pos + format.size()].copy_from_slice(data); + }) } fn unpack_single(&self, pos: usize, vm: &VirtualMachine) -> PyResult { // The index that produced `pos` could have released the view. // CHECK_RELEASED_AGAIN self.try_not_released(vm)?; + let format = self.scalar_format(vm)?; let bytes = self.buffer.obj_bytes(); - // TODO: Optimize - self.format_spec - .unpack(&bytes[pos..pos + self.format_spec.size()], vm) - .map(|x| { - if x.as_slice().len() == 1 { - x.as_slice()[0].to_owned() - } else { - x.into() - } - }) + Ok(format.unpack(&bytes[pos..pos + format.size()], vm)) } - fn pos_from_multi_index(&self, indexes: &[isize], vm: &VirtualMachine) -> PyResult { + fn pos_from_multi_index(&self, indexes: &Py, vm: &VirtualMachine) -> PyResult { + let indexes = indexes.as_slice(); match indexes.len().cmp(&self.desc.ndim()) { Ordering::Less => { return Err(vm.new_not_implemented_error("sub-views are not implemented")); @@ -408,11 +425,15 @@ impl PyMemoryView { Ordering::Equal => (), } - Ok(self.desc.position(indexes, vm)? as usize) + // ptr_from_tuple converts one dimension and checks its bounds before + // visiting the next. An invalid tuple length invokes no index methods. + self.desc + .position_with(|dim| SubscriptNeedle::index_value(&indexes[dim], vm), vm) + .map(|pos| pos as usize) } fn init_len(&mut self) { - let product: usize = self.desc.dim_desc.iter().map(|x| x.0).product(); + let product: usize = self.desc.shape().iter().map(|&x| x as usize).product(); self.desc.len = product * self.desc.itemsize; } @@ -420,34 +441,36 @@ impl PyMemoryView { /// outside `dim` is reached through a pointer, in which case its suboffset /// does. fn adjust_position(&mut self, dim: usize, delta: isize) { - match self.desc.dim_desc[..dim] + match self.desc.suboffsets()[..dim] .iter() - .rposition(|&(_, _, suboffset)| suboffset != 0) + .rposition(|&suboffset| suboffset != -1) { - Some(n) => self.desc.dim_desc[n].2 += delta, + Some(n) => self.desc.suboffsets_mut()[n] += delta, None => self.desc.offset += delta, } } fn init_range(&mut self, range: Range, dim: usize) { - let (shape, stride, _) = self.desc.dim_desc[dim]; + let shape = self.desc.shape()[dim] as usize; + let stride = self.desc.strides()[dim]; debug_assert!(shape >= range.len()); self.adjust_position(dim, stride * range.start as isize); - self.desc.dim_desc[dim].0 = range.len(); + self.desc.shape_mut()[dim] = range.len() as isize; } // init_slice fn init_slice(&mut self, slice: &Py, dim: usize, vm: &VirtualMachine) -> PyResult<()> { - let (shape, stride, _) = self.desc.dim_desc[dim]; + let shape = self.desc.shape()[dim] as usize; + let stride = self.desc.strides()[dim]; let slice = slice.to_saturated(vm)?; let (start, slice_len) = slice.adjust_indices_start(shape); // Repeated slicing multiplies the stride by the step every time, which // overflows after about twenty rounds; C wraps there and so does this. self.adjust_position(dim, stride.wrapping_mul(start)); - self.desc.dim_desc[dim].0 = slice_len; - self.desc.dim_desc[dim].1 = stride.wrapping_mul(slice.step()); + self.desc.shape_mut()[dim] = slice_len as isize; + self.desc.strides_mut()[dim] = stride.wrapping_mul(slice.step()); Ok(()) } @@ -459,18 +482,24 @@ impl PyMemoryView { dim: usize, vm: &VirtualMachine, ) -> PyResult { - let (shape, stride, suboffset) = self.desc.dim_desc[dim]; + let shape = self.desc.shape()[dim] as usize; + let stride = self.desc.strides()[dim]; + let suboffset = if self.desc.suboffsets()[dim] == -1 { + 0 + } else { + self.desc.suboffsets()[dim] + }; if dim + 1 == self.desc.ndim() { let mut v = Vec::with_capacity(shape); - for _ in 0..shape { - let pos = (index + suboffset) as usize; - let obj = format_unpack( - &self.format_spec, - &bytes[pos..pos + self.format_spec.size()], - vm, - )?; - v.push(obj); - index += stride; + // Unsupported scalar codes are only rejected if an item is read. + if shape != 0 { + let format = self.scalar_format(vm)?; + for _ in 0..shape { + let pos = (index + suboffset) as usize; + let obj = format.unpack(&bytes[pos..pos + format.size()], vm); + v.push(obj); + index += stride; + } } return Ok(vm.ctx.new_list(v)); } @@ -484,78 +513,100 @@ impl PyMemoryView { Ok(vm.ctx.new_list(v)) } - fn eq(zelf: &Py, other: &PyObject, vm: &VirtualMachine) -> PyResult { - if zelf.is(other) { - return Ok(true); - } + fn eq(zelf: &Py, other: &PyObject, vm: &VirtualMachine) -> PyResult> { if zelf.released.load() { - return Ok(false); + return Ok(Some(zelf.is(other))); + } + // Float and complex values can contain NaNs, so compare their elements + // even when both operands are the same view. memory_richcompare + if zelf.is(other) + && Self::native_fmtchar(&zelf.desc.format) + .is_some_and(|c| b"bBchHiIlLnNqQ?".contains(&c)) + { + return Ok(Some(true)); } - let other = if let Some(mv) = other.downcast_ref::() { + let acquired; + let (other, other_desc, other_native) = if let Some(mv) = other.downcast_ref::() { if mv.released.load() { - return Ok(false); + return Ok(Some(false)); } - // Another view's buffer is read where it lies rather than acquired, - // so that a restricted view still compares. memory_richcompare - let mut view = mv.buffer.detached(); - view.desc = mv.desc.clone(); - view + // Borrow another view directly, without acquiring a new export or + // cloning its dimensions. Restricted views can also compare. + (&mv.buffer, &mv.desc, mv.native_format) } else { - match PyBuffer::try_from_borrowed_object(vm, other) { + acquired = match PyBuffer::try_from_borrowed_object(vm, other) { Ok(buf) => buf, - Err(_) => return Ok(false), - } + Err(_) => return Ok(None), + }; + let native = NativeFormat::parse(&acquired.desc.format); + (&acquired, &acquired.desc, native) }; - if !is_equiv_shape(&zelf.desc, &other.desc) { - return Ok(false); + if !is_equiv_shape(&zelf.desc, other_desc) { + return Ok(Some(false)); } - let a_format_spec = &zelf.format_spec; - let b_format_spec = &Self::parse_format(&other.desc.format, vm)?; + let native = zelf + .native_format + .filter(|format| Some(*format) == other_native); + let specs = if native.is_some() { + None + } else { + let Some(a) = comparison_format(&zelf.desc.format, vm)? else { + return Ok(Some(false)); + }; + let Some(b) = comparison_format(&other_desc.format, vm)? else { + return Ok(Some(false)); + }; + Some((a, b)) + }; // An element is as wide as its format, which a projected descriptor can // make narrower than the item size it steps by. - let a_itemsize = a_format_spec.size(); - let b_itemsize = b_format_spec.size(); + let (a_itemsize, b_itemsize) = match (&specs, native) { + (Some((a, b)), _) => (a.size(), b.size()), + (_, Some(format)) => (format.size(), format.size()), + _ => unreachable!(), + }; + let compare = |a: &[u8], b: &[u8]| { + if let Some(format) = native { + Ok(format.equals(a, b)) + } else { + let (a_spec, b_spec) = specs.as_ref().unwrap(); + let a = format_unpack(a_spec, a, vm)?; + let b = format_unpack(b_spec, b, vm)?; + vm.bool_eq(&a, &b) + } + }; + let a_bytes = zelf.buffer.obj_bytes(); + let b_storage; + // Forwarding views expose the same complete storage. Borrow it once + // when both descriptors address one exporter, including 0-D views. + let b_bytes: &[u8] = if buffer_owner(&zelf.buffer.obj).is(buffer_owner(&other.obj)) { + &a_bytes + } else { + b_storage = other.obj_bytes(); + &b_storage + }; if zelf.desc.ndim() == 0 { let a_pos = zelf.desc.offset as usize; - let b_pos = other.desc.offset as usize; - let a_bytes = zelf.buffer.obj_bytes(); - let a_val = format_unpack(a_format_spec, &a_bytes[a_pos..a_pos + a_itemsize], vm)?; - drop(a_bytes); - let b_bytes = other.obj_bytes(); - let b_val = format_unpack(b_format_spec, &b_bytes[b_pos..b_pos + b_itemsize], vm)?; - drop(b_bytes); - return vm.bool_eq(&a_val, &b_val); + let b_pos = other_desc.offset as usize; + return compare( + &a_bytes[a_pos..a_pos + a_itemsize], + &b_bytes[b_pos..b_pos + b_itemsize], + ) + .map(Some); } - // TODO: optimize cmp by format let mut ret = Ok(true); - let a_bytes = zelf.buffer.obj_bytes(); - let b_bytes = other.obj_bytes(); - zelf.desc.zip_eq(&other.desc, false, |a_range, b_range| { + zelf.desc.zip_eq(other_desc, false, |a_range, b_range| { let a_range = a_range.start as usize..a_range.start as usize + a_itemsize; let b_range = b_range.start as usize..b_range.start as usize + b_itemsize; - let a_val = match format_unpack(a_format_spec, &a_bytes[a_range], vm) { - Ok(val) => val, - Err(e) => { - ret = Err(e); - return true; - } - }; - let b_val = match format_unpack(b_format_spec, &b_bytes[b_range], vm) { - Ok(val) => val, - Err(e) => { - ret = Err(e); - return true; - } - }; - ret = vm.bool_eq(&a_val, &b_val); + ret = compare(&a_bytes[a_range], &b_bytes[b_range]); if let Ok(b) = ret { !b } else { true } }); - ret + ret.map(Some) } fn as_contiguous(&self) -> Option> { @@ -620,27 +671,21 @@ impl Py { vm: &VirtualMachine, ) -> PyResult<()> { if self.desc.ndim() != 1 { - return Err(vm.new_not_implemented_error("sub-view are not implemented")); + return Err(vm.new_not_implemented_error( + "memoryview slice assignments are currently restricted to ndim = 1", + )); } + // Acquire before evaluating the slice. Besides ordering __buffer__ and + // __index__, this prevents releasing a view used as its own source. + // PyObject_GetBuffer(value, &src, PyBUF_FULL_RO) + let src = PyBuffer::try_from_object(vm, src)?; let mut dest = self.borrowed_view(); dest.init_slice(slice, 0, vm)?; dest.init_len(); - if self.is(&src) { - return if !is_equiv_structure(&self.desc, &dest.desc) { - Err(vm.new_value_error( - "memoryview assignment: lvalue and rvalue have different structures", - )) - } else { - // assign self[:] to self - Ok(()) - }; - }; - - // PyObject_GetBuffer(value, &src, PyBUF_FULL_RO) - let src = PyBuffer::try_from_object(vm, src)?; - // Acquiring the source ran `__buffer__`, which can release this view. + // Acquiring the source and evaluating the slice can both release this + // view. Check after the slice, before accessing the borrowed storage. // copy_single: CHECK_RELEASED_INT_AGAIN self.try_not_released(vm)?; @@ -653,17 +698,18 @@ impl Py { // copy_buffer reads the source as it stood before the copy began, which an // overlapping assignment depends on and which also keeps the two borrows // below off the same storage. - let src = if root_exporter(&src).is(&root_exporter(&dest.buffer)) { - let owned = src.to_contiguous(vm); - drop(src); - owned - } else { - src + let may_overlap = match (root_exporter(&src), root_exporter(&dest.buffer)) { + (Some(src), Some(dest)) => src.is(&dest), + _ => true, }; + // Keep the source acquisition alive until after the copy and its byte + // guards: releasing it can run Python that releases or resizes dest. + let snapshot = may_overlap.then(|| src.to_contiguous(vm)); + let copy_src = snapshot.as_ref().unwrap_or(&src); let mut bytes_mut = dest.buffer.obj_bytes_mut(); - let src_bytes = src.obj_bytes(); - dest.desc.zip_eq(&src.desc, true, |a_range, b_range| { + let src_bytes = copy_src.obj_bytes(); + dest.desc.zip_eq(©_src.desc, true, |a_range, b_range| { let a_range = a_range.start as usize..a_range.end as usize; let b_range = b_range.start as usize..b_range.end as usize; bytes_mut[a_range].copy_from_slice(&src_bytes[b_range]); @@ -677,7 +723,7 @@ impl Py { impl PyMemoryView { /// Give up the view's share without asking whether anything is reading it. /// The teardown paths have nowhere to report a refusal. - pub fn release(&self) { + pub fn release_buffer(&self) { if self.released.compare_exchange(false, true).is_ok() { self.buffer.release(); } @@ -708,14 +754,21 @@ impl PyMemoryView { } match SubscriptNeedle::try_from_object(vm, needle)? { - SubscriptNeedle::Index(i) => zelf.getitem_by_idx(i, vm), + SubscriptNeedle::Index(index) => { + let index = SubscriptNeedle::index_value(&index, vm)?; + zelf.getitem_by_idx(index, vm) + } SubscriptNeedle::Slice(slice) => zelf.getitem_by_slice(&slice, vm), SubscriptNeedle::MultiIndex(indices) => zelf.getitem_by_multi_idx(&indices, vm), + SubscriptNeedle::MultiSlice => { + Err(vm.new_not_implemented_error("multi-dimensional slicing is not implemented")) + } } } fn __delitem__(&self, _needle: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.try_not_released(vm)?; + self.adjusted_format(vm)?; // What cannot be written cannot be deleted from either, and that is // the first thing answered. if self.desc.readonly { @@ -731,17 +784,28 @@ impl PyMemoryView { Err(vm.new_type_error("0-dim memory has no length")) } else { // shape for dim[0] - Ok(self.desc.dim_desc[0].0) + Ok(self.desc.shape()[0] as usize) } } - fn cast_to_1d(&self, format: &Py, vm: &VirtualMachine) -> PyResult { - let format_str = format.as_str(); - let Some(dest_char) = Self::native_fmtchar(format_str) else { + fn cast_to_1d(&self, format: &Py, vm: &VirtualMachine) -> PyResult { + // Encode the entire string before interpreting its C-string prefix: + // non-ASCII characters after a NUL still raise UnicodeEncodeError. + let encoded; + let format_str = if format.isascii() { + format.to_str().unwrap() + } else { + let ctx = PyEncodeContext::new(ascii::ENCODING_NAME, format, vm); + encoded = ascii::encode(ctx, &ErrorsHandler::new(None, vm))?; + core::str::from_utf8(&encoded).expect("ASCII encoding returned non-ASCII") + }; + let format_str = format_str.split_once('\0').map_or(format_str, |(s, _)| s); + let Some(native_format) = NativeFormat::parse(format_str) else { return Err(vm.new_value_error( - "memoryview: destination format must be a native single character format prefixed with an optional '@'", + "memoryview: destination format must be a native format prefixed with an optional '@'", )); }; + let dest_char = native_format.fmtchar(); // One side has to be bytes. Casting between two item types would // reinterpret the items rather than re-divide the memory, and the // source items were written by something that chose their type. @@ -749,8 +813,7 @@ impl PyMemoryView { if !source_is_bytes && !is_byte_fmtchar(dest_char) { return Err(vm.new_type_error("memoryview: cannot cast between two non-byte formats")); } - let format_spec = Self::parse_format(format_str, vm)?; - let itemsize = format_spec.size(); + let itemsize = native_format.size(); if !self.desc.len.is_multiple_of(itemsize) { return Err(vm.new_type_error("memoryview: length is not a multiple of itemsize")); } @@ -759,15 +822,15 @@ impl PyMemoryView { buffer: self.buffer.clone(), released: AtomicCell::new(false), restricted: AtomicCell::new(false), - format_spec, - desc: BufferDescriptor { - len: self.desc.len, - offset: self.desc.offset, - readonly: self.desc.readonly, + native_format: Some(native_format), + desc: BufferDescriptor::from_dim_desc( + self.desc.len, + self.desc.offset, + self.desc.readonly, itemsize, - format: format_str.to_owned().into(), - dim_desc: vec![(self.desc.len / itemsize, itemsize as isize, 0)], - }, + format_str.to_owned().into(), + vec![(self.desc.len / itemsize, itemsize as isize, 0)], + ), hash: OnceCell::new(), exports: AtomicCell::new(0), }; @@ -801,6 +864,7 @@ impl Py { vm: &VirtualMachine, ) -> PyResult<()> { self.try_not_released(vm)?; + self.adjusted_format(vm)?; if self.desc.readonly { return Err(vm.new_type_error("cannot modify read-only memory")); } @@ -816,14 +880,17 @@ impl Py { return Err(vm.new_type_error("invalid indexing of 0-dim memory")); } match SubscriptNeedle::try_from_object(vm, needle)? { - SubscriptNeedle::Index(i) => self.setitem_by_idx(i, value, vm), + SubscriptNeedle::Index(index) => self.setitem_by_idx(&index, value, vm), SubscriptNeedle::Slice(slice) => self.setitem_by_slice(&slice, value, vm), SubscriptNeedle::MultiIndex(indices) => self.setitem_by_multi_idx(&indices, value, vm), + SubscriptNeedle::MultiSlice => Err(vm.new_not_implemented_error( + "memoryview slice assignments are currently restricted to ndim = 1", + )), } } #[pymethod] - fn __reduce_ex__(&self, _proto: usize, vm: &VirtualMachine) -> PyResult { + fn __reduce_ex__(&self, _protocol: usize, vm: &VirtualMachine) -> PyResult { self.__reduce__(vm) } @@ -852,8 +919,8 @@ impl Py { PyMemoryView::from_object_with_flags(&args.object, flags, vm).map(|mv| mv.into_ref(&vm.ctx)) } - #[pymethod(name = "release")] - fn py_release(&self, vm: &VirtualMachine) -> PyResult<()> { + #[pymethod] + fn release(&self, vm: &VirtualMachine) -> PyResult<()> { // _memory_release: what still reads this view holds it open. let exports = self.exports.load(); if !self.released.load() && exports > 0 { @@ -862,7 +929,7 @@ impl Py { vm.new_buffer_error(format!("memoryview has {exports} exported buffer{plural}")) ); } - self.release(); + self.release_buffer(); Ok(()) } @@ -903,9 +970,9 @@ impl Py { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc - .dim_desc + .shape() .iter() - .map(|(shape, _, _)| shape.to_pyobject(vm)) + .map(|shape| (*shape as usize).to_pyobject(vm)) .collect(), )) } @@ -915,9 +982,9 @@ impl Py { self.try_not_released(vm)?; Ok(vm.ctx.new_tuple( self.desc - .dim_desc + .strides() .iter() - .map(|(_, stride, _)| stride.to_pyobject(vm)) + .map(|stride| stride.to_pyobject(vm)) .collect(), )) } @@ -927,15 +994,15 @@ impl Py { self.try_not_released(vm)?; let has_suboffsets = self .desc - .dim_desc + .suboffsets() .iter() - .any(|(_, _, suboffset)| *suboffset != 0); + .any(|suboffset| *suboffset != -1); if has_suboffsets { Ok(vm.ctx.new_tuple( self.desc - .dim_desc + .suboffsets() .iter() - .map(|(_, _, suboffset)| suboffset.to_pyobject(vm)) + .map(|suboffset| suboffset.to_pyobject(vm)) .collect(), )) } else { @@ -978,7 +1045,7 @@ impl Py { _exc_info: PosArgs, vm: &VirtualMachine, ) -> PyResult<()> { - self.py_release(vm) + self.release(vm) } #[pymethod] @@ -1015,15 +1082,13 @@ impl Py { // memory_tolist fn tolist(&self, vm: &VirtualMachine) -> PyResult { self.try_not_released(vm)?; + self.adjusted_format(vm)?; let bytes = self.buffer.obj_bytes(); if self.desc.ndim() == 0 { // A 0-dim view holds one element, which is what it unpacks to. let pos = self.desc.offset as usize; - return format_unpack( - &self.format_spec, - &bytes[pos..pos + self.format_spec.size()], - vm, - ); + let format = self.scalar_format(vm)?; + return Ok(format.unpack(&bytes[pos..pos + format.size()], vm)); } self._to_list(&bytes, self.desc.offset, 0, vm) .map(Into::into) @@ -1049,13 +1114,8 @@ impl Py { #[pymethod] fn count(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { - self.try_not_released(vm)?; - if self.desc.ndim() != 1 { - return Err( - vm.new_not_implemented_error("multi-dimensional sub-views are not implemented") - ); - } - let len = self.desc.dim_desc[0].0; + self.check_iteration(vm)?; + let len = self.desc.shape()[0] as usize; let mut count = 0; for i in 0..len { let item = self.getitem_by_idx(i as isize, vm)?; @@ -1069,13 +1129,15 @@ impl Py { #[pymethod] fn index(&self, args: MemoryIndexArgs, vm: &VirtualMachine) -> PyResult { self.try_not_released(vm)?; + if self.desc.ndim() == 0 { + return Err(vm.new_type_error("invalid lookup on 0-dim memory")); + } if self.desc.ndim() != 1 { - return Err( - vm.new_not_implemented_error("multi-dimensional sub-views are not implemented") - ); + return Err(vm.new_not_implemented_error("multi-dimensional lookup is not implemented")); } - let len = self.desc.dim_desc[0].0; + let len = self.desc.shape()[0] as usize; let MemoryIndexArgs { value, start, stop } = args; + let (start, stop) = (start.value, stop.value); let start = if start < 0 { (start + len as isize).max(0) as usize @@ -1094,25 +1156,30 @@ impl Py { return Ok(i); } } - Err(vm.new_value_error("memoryview.index(x): x not in memoryview")) + Err(vm.new_value_error("memoryview.index(x): x not found")) } #[pymethod] fn cast(&self, args: CastArgs, vm: &VirtualMachine) -> PyResult> { + let CastArgs { format, shape } = args; + // Clinic's string conversion follows binding and precedes view checks. + // Encoding belongs after the shape preconditions. self.try_usable(vm)?; if !self.desc.is_contiguous() { return Err(vm.new_type_error("memoryview: casts are restricted to C-contiguous views")); } - let CastArgs { format, shape } = args; + if (matches!(shape, OptionalArg::Present(_)) || self.desc.ndim() != 1) + && self.desc.is_zero_in_shape() + { + return Err( + vm.new_type_error("memoryview: cannot cast view with zeros in shape or strides") + ); + } if let OptionalArg::Present(shape) = shape { - if self.desc.is_zero_in_shape() { - return Err(vm.new_type_error( - "memoryview: cannot cast view with zeros in shape or strides", - )); - } - + let shape = Either::::try_from_object(vm, shape) + .map_err(|_| vm.new_type_error("shape must be a list or a tuple"))?; let tup; let list; let list_borrow; @@ -1148,12 +1215,14 @@ impl Py { vm.new_type_error("memoryview: product(shape) * itemsize != buffer size") ); } - other.desc.dim_desc = vec![]; + other + .desc + .set_dimensions(Box::new([]), Box::new([]), Box::new([])); return Ok(other.into_ref(&vm.ctx)); } let mut product_shape = itemsize; - let mut dim_descriptor = Vec::with_capacity(shape_ndim); + let mut shape_descriptor = Vec::with_capacity(shape_ndim); for x in shape { let x = x @@ -1161,25 +1230,28 @@ impl Py { .ok_or_else(|| { vm.new_type_error("memoryview.cast(): elements of shape must be integers") })? - .try_to_primitive::(vm) - .ok() - .filter(|x| *x > 0) - .ok_or_else(|| { - vm.new_value_error( - "memoryview.cast(): elements of shape must be integers > 0", - ) + .try_to_primitive::(vm) + .map_err(|_| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") })?; + if x <= 0 { + return Err(vm.new_value_error( + "memoryview.cast(): elements of shape must be integers > 0", + )); + } + let x = x as usize; if x > isize::MAX as usize / product_shape { return Err(vm.new_value_error("memoryview.cast(): product(shape) > SSIZE_MAX")); } product_shape *= x; - dim_descriptor.push((x, 0, 0)); + shape_descriptor.push(x as isize); } - dim_descriptor.last_mut().unwrap().1 = itemsize as isize; - for i in (0..dim_descriptor.len() - 1).rev() { - dim_descriptor[i].1 = dim_descriptor[i + 1].1 * dim_descriptor[i + 1].0 as isize; + let mut strides = vec![0isize; shape_descriptor.len()]; + strides[shape_descriptor.len() - 1] = itemsize as isize; + for i in (0..strides.len() - 1).rev() { + strides[i] = strides[i + 1] * shape_descriptor[i + 1]; } if product_shape != other.desc.len { @@ -1188,7 +1260,11 @@ impl Py { ); } - other.desc.dim_desc = dim_descriptor; + other.desc.set_dimensions( + shape_descriptor.into_boxed_slice(), + strides.into_boxed_slice(), + vec![-1; shape_ndim].into_boxed_slice(), + ); Ok(other.into_ref(&vm.ctx)) } else { @@ -1201,11 +1277,11 @@ impl Py { struct MemoryIndexArgs { #[pyarg(positional)] value: PyObjectRef, - #[pyarg(positional, default)] - start: isize, + #[pyarg(positional, default, py_default = "0")] + start: ArgSliceIndex, // Omission is clamped to the view length. - #[pyarg(positional, default = isize::MAX)] - stop: isize, + #[pyarg(positional, default = ArgSliceIndex::MAX, py_default = "sys.maxsize")] + stop: ArgSliceIndex, } #[derive(FromArgs)] @@ -1226,46 +1302,50 @@ enum Order { #[derive(FromArgs)] struct CastArgs { #[pyarg(any)] - format: PyUtf8StrRef, + format: PyStrRef, #[pyarg(any, optional)] - shape: OptionalArg>, + shape: OptionalArg, } enum SubscriptNeedle { - Index(isize), + Index(PyObjectRef), Slice(PyRef), - MultiIndex(Vec), - // MultiSlice(Vec), + MultiIndex(PyTupleRef), + MultiSlice, +} + +impl SubscriptNeedle { + fn index_value(index: &PyObject, vm: &VirtualMachine) -> PyResult { + // A previous tuple index can remove this object's __index__ method + // after classification. Use the normal conversion error in that case. + sequence_index_key(index, vm)?.ok_or_else(|| { + vm.new_type_error(format!( + "'{}' object cannot be interpreted as an integer", + index.class().slot_name() + )) + }) + } } /// memory_subscript /// -/// Which kind of key this is follows from the types in it alone, so an item that -/// answers `__index__` but raises on the way reports that rather than making the -/// whole key invalid. is_multiindex / is_multislice +/// Classify without running Python. Reads and writes convert an index at +/// different points, and tuple indices are converted dimension by dimension. +/// is_multiindex / is_multislice impl TryFromObject for SubscriptNeedle { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { if obj.number().is_index() { - return Ok(Self::Index(obj.try_index(vm)?.try_to_primitive(vm)?)); + return Ok(Self::Index(obj)); } if obj.downcastable::() { return Ok(Self::Slice(unsafe { obj.downcast_unchecked::() })); } if let Some(tuple) = obj.downcast_ref::() { if tuple.as_slice().iter().all(|x| x.number().is_index()) { - // ptr_from_tuple: each item is converted where it sits, and the - // conversion can run Python that releases the view. - let indices = tuple - .as_slice() - .iter() - .map(|x| x.try_index(vm)?.try_to_primitive::(vm)) - .try_collect()?; - return Ok(Self::MultiIndex(indices)); + return Ok(Self::MultiIndex(tuple.to_owned())); } if tuple.as_slice().iter().all(|x| x.downcastable::()) { - return Err( - vm.new_not_implemented_error("multi-dimensional slicing is not implemented") - ); + return Ok(Self::MultiSlice); } } Err(vm.new_type_error("memoryview: invalid slice key")) @@ -1369,18 +1449,17 @@ impl Comparable for PyMemoryView { op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - match op { - PyComparisonOp::Ne => { - Self::eq(zelf, other, vm).map(|x| PyComparisonValue::Implemented(!x)) - } - PyComparisonOp::Eq => Self::eq(zelf, other, vm).map(PyComparisonValue::Implemented), - _ => Err(vm.new_type_error(format!( - "'{}' not supported between instances of '{}' and '{}'", - op.operator_token(), - zelf.class().slot_name(), - other.class().slot_name() - ))), + if !matches!(op, PyComparisonOp::Eq | PyComparisonOp::Ne) { + return Ok(PyComparisonValue::NotImplemented); } + Ok(match Self::eq(zelf, other, vm)? { + Some(equal) => PyComparisonValue::Implemented(if op == PyComparisonOp::Ne { + !equal + } else { + equal + }), + None => PyComparisonValue::NotImplemented, + }) } } @@ -1501,9 +1580,8 @@ static BUFFER_WRAPPER_METHODS: BufferMethods = BufferMethods { }, }; -// Read-only window over an exporter, handed to `__release_buffer__`. It owns no -// export, like a `Py_buffer` whose `obj` is NULL, so releasing it is inert and -// cannot recurse back into the hook. +// Read-only window with no Python-visible exporter. A release-hook window +// borrows a detached source, while a codec window owns its acquisition. #[pyclass(module = false, name = "_buffer_window", traverse)] #[derive(Debug)] struct PyBufferWindow { @@ -1523,7 +1601,7 @@ static BUFFER_WINDOW_METHODS: BufferMethods = BufferMethods { obj_bytes: |buffer| buffer.obj_as::().source.obj_bytes(), obj_bytes_mut: |buffer| buffer.obj_as::().source.obj_bytes_mut(), retain: |_buffer| {}, - release: |_buffer| {}, + release: |buffer| buffer.obj_as::().source.release(), }; /// The object that ultimately owns the bytes a buffer reads, seen through the @@ -1532,20 +1610,27 @@ static BUFFER_WINDOW_METHODS: BufferMethods = BufferMethods { /// /// Two buffers that resolve to the same object address the same storage, so /// borrowing one for writing while the other is borrowed for reading would -/// deadlock on it. -fn root_exporter(buffer: &PyBuffer) -> PyObjectRef { - let mut obj = buffer.obj.clone(); +/// deadlock on a shared lock or create overlapping references with separate locks. +/// Borrowed ctypes storage has no reliable exporter identity: a field, pointer, +/// or from_address view can alias another object without sharing its owner. +/// Return None for that storage so either operand forces a source snapshot. +fn root_exporter(buffer: &PyBuffer) -> Option { + let obj = buffer_owner(&buffer.obj); + (!crate::stdlib::is_borrowed_ctypes_buffer(obj)).then(|| obj.to_owned()) +} + +// Follow forwarding payloads without reacquiring a buffer or invoking Python. +pub(crate) fn buffer_owner(mut obj: &PyObject) -> &PyObject { loop { - let next = if let Some(view) = obj.downcast_ref::() { - view.buffer.obj.clone() + obj = if let Some(view) = obj.downcast_ref::() { + &view.buffer.obj } else if let Some(wrapper) = obj.downcast_ref::() { - wrapper.view.obj.clone() + &wrapper.view.obj } else if let Some(window) = obj.downcast_ref::() { - window.source.obj.clone() + &window.source.obj } else { return obj; }; - obj = next; } } @@ -1599,13 +1684,14 @@ pub(crate) fn release_buffer_from_python( if mv.released.load() { return Err(vm.new_value_error("memoryview's buffer has already been released")); } - mv.release(); + mv.release_buffer(); Ok(()) } // releasebuffer_call_python, for a buffer acquired from a native exporter pub(crate) fn release_buffer_call_python(buffer: &PyBuffer) { crate::vm::thread::try_with_current_vm(|vm| { + let _raised = vm.preserve_raised_exception(); let exporter = buffer.obj.clone(); let window = PyBufferWindow { source: buffer.detached(), @@ -1628,15 +1714,18 @@ pub(crate) fn release_buffer_call_python(buffer: &PyBuffer) { let mv = mv.into_ref(&vm.ctx); call_python_release_buffer(&exporter, mv.clone()); // The window does not outlive the release it was made for. - mv.release(); + mv.release_buffer(); }); } fn call_python_release_buffer(exporter: &PyObject, mv: PyRef) { crate::vm::thread::try_with_current_vm(|vm| { + let _raised = vm.preserve_raised_exception(); + // Drop the captured view before restoring the pending error. + let owned_view = mv; let method = vm.get_special_method(exporter, identifier!(vm, __release_buffer__)); if let Ok(Some(method)) = method - && let Err(exc) = method.invoke((mv,), vm) + && let Err(exc) = method.invoke((owned_view,), vm) { let msg = format!( "Exception ignored in __release_buffer__ of {}", @@ -1670,8 +1759,8 @@ fn is_equiv_shape(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { return false; } - let a_iter = a.dim_desc.iter().map(|x| x.0); - let b_iter = b.dim_desc.iter().map(|x| x.0); + let a_iter = a.shape().iter().copied(); + let b_iter = b.shape().iter().copied(); for (a_shape, b_shape) in a_iter.zip(b_iter) { if a_shape != b_shape { return false; @@ -1685,8 +1774,9 @@ fn is_equiv_shape(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { } fn is_equiv_format(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { - // TODO: skip @ - a.itemsize == b.itemsize && a.format == b.format + let a_format = a.format.strip_prefix('@').unwrap_or(&a.format); + let b_format = b.format.strip_prefix('@').unwrap_or(&b.format); + a.itemsize == b.itemsize && a_format == b_format } fn is_equiv_structure(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { @@ -1695,17 +1785,22 @@ fn is_equiv_structure(a: &BufferDescriptor, b: &BufferDescriptor) -> bool { impl Iterable for PyMemoryView { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + zelf.check_iteration(vm)?; + let length = zelf.desc.shape()[0] as usize; Ok(PyMemoryViewIterator { internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), + length, } .into_pyobject(vm)) } } -#[pyclass(module = false, name = "memory_iterator")] -#[derive(Debug, Traverse)] +#[pyclass(module = false, name = "memory_iterator", traverse)] +#[derive(Debug)] pub(crate) struct PyMemoryViewIterator { internal: PyMutex>>, + #[pytraverse(skip)] + length: usize, } impl PyPayload for PyMemoryViewIterator { @@ -1717,27 +1812,83 @@ impl PyPayload for PyMemoryViewIterator { #[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] impl Py { #[pymethod] - fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { - let func = builtins_iter(vm)?; - Ok(self.internal.lock().reduce( - func, - |x| x.clone().into(), - |vm| vm.ctx.empty_tuple.clone().into(), - vm, - )) + fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { + Err(vm.new_type_error("cannot pickle 'memory_iterator' object")) } } impl SelfIter for PyMemoryViewIterator {} impl IterNext for PyMemoryViewIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_next(&zelf.internal, |mv, pos| { - let len = mv.__len__(vm)?; - Ok(if pos >= len { - PyIterReturn::StopIteration(None) + let (item, _released) = { + let mut internal = zelf.internal.lock(); + if let IterStatus::Active(mv) = &internal.status + && internal.position < zelf.length + { + let item = (mv.clone(), internal.position); + // A released view keeps failing at this index; an unpacking + // error consumes the element. Neither error is built under + // the iterator lock. + if !mv.released.load() { + internal.position += 1; + } + (Some(item), None) } else { - PyIterReturn::Return(mv.getitem_by_idx(pos.try_into().unwrap(), vm)?) - }) - }) + // The cached bound precedes the release check, including + // after the last value and for an originally empty view. + (None, internal.exhaust()) + } + }; + match item { + Some((mv, index)) => { + mv.try_not_released(vm)?; + mv.getitem_by_idx(index as isize, vm) + .map(PyIterReturn::Return) + } + None => Ok(PyIterReturn::StopIteration(None)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Interpreter; + + #[test] + fn comparison_uses_strict_struct_syntax_for_exporter_formats() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let make_view = |format: &str| { + let desc = BufferDescriptor::from_dim_desc( + 1, + 0, + true, + 1, + format.to_owned().into(), + vec![(1, 1, 0)], + ); + let buffer = VecBuffer::from(vec![1_u8]) + .into_ref(&vm.ctx) + .into_pybuffer_with_descriptor(desc); + PyMemoryView::from_buffer(buffer, vm) + .unwrap() + .into_ref(&vm.ctx) + }; + for (format, expected) in [ + ("B\u{b}", true), + ("B\u{c}", true), + ("1", false), + ("B1", false), + ("T{B:value:}", false), + ] { + let a = make_view(format); + let b = make_view(format); + assert_eq!( + PyMemoryView::eq(&a, b.as_object(), vm).unwrap(), + Some(expected), + "{format:?}" + ); + } + }); } } diff --git a/crates/vm/src/builtins/memory/format.rs b/crates/vm/src/builtins/memory/format.rs new file mode 100644 index 00000000000..91fb8b87e99 --- /dev/null +++ b/crates/vm/src/builtins/memory/format.rs @@ -0,0 +1,335 @@ +use super::PyMemoryView; +use crate::{ + AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine, + buffer::{Endianness, FormatSpec, FormatType, pack_float16, unpack_float32}, + builtins::{PyBaseExceptionRef, PyBytes, PyInt}, + common::rc::PyRc, + function::{ArgIntoBool, ArgIntoComplex, ArgIntoFloat}, +}; +use malachite_bigint::{BigInt, Sign}; +use num_traits::PrimInt; +use std::os::raw; + +/// A scalar format accepted by memoryview, rather than the full struct grammar. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub(super) struct NativeFormat(FormatType); + +impl NativeFormat { + pub(super) fn parse(format: &str) -> Option { + let format = format.strip_prefix('@').unwrap_or(format); + let code = match format.as_bytes() { + [b'Z', b'f'] => FormatType::FloatComplex, + [b'Z', b'd'] => FormatType::DoubleComplex, + [code] if b"cbBhHiIlLqQnNP?fde".contains(code) => FormatType::try_from(*code).ok()?, + _ => return None, + }; + Some(Self(code)) + } + + pub(super) fn fmtchar(self) -> u8 { + match self.0 { + FormatType::FloatComplex | FormatType::DoubleComplex => b'Z', + code => code as u8, + } + } + + fn name(self) -> &'static str { + match self.0 { + FormatType::SByte => "b", + FormatType::UByte => "B", + FormatType::Char => "c", + FormatType::Short => "h", + FormatType::UShort => "H", + FormatType::Int => "i", + FormatType::UInt => "I", + FormatType::Long => "l", + FormatType::ULong => "L", + FormatType::LongLong => "q", + FormatType::ULongLong => "Q", + FormatType::SSizeT => "n", + FormatType::SizeT => "N", + FormatType::Float => "f", + FormatType::Double => "d", + FormatType::Half => "e", + FormatType::Bool => "?", + FormatType::VoidP => "P", + FormatType::FloatComplex => "Zf", + FormatType::DoubleComplex => "Zd", + _ => unreachable!("not a native memoryview scalar format"), + } + } + + pub(super) fn size(self) -> usize { + self.0.info(Endianness::Native).size + } + + pub(super) fn unpack(self, bytes: &[u8], vm: &VirtualMachine) -> PyObjectRef { + // memoryview uses PyFloat_Unpack4 for complex components, unlike the + // native struct path's C float-to-double cast, which quiets sNaNs. + if self.0 == FormatType::FloatComplex { + let re = unpack_float32(u32::from_ne_bytes(bytes[..4].try_into().unwrap())); + let im = unpack_float32(u32::from_ne_bytes(bytes[4..8].try_into().unwrap())); + return vm + .ctx + .new_complex(num_complex::Complex64::new(re, im)) + .into(); + } + let unpack = self.0.info(Endianness::Native).unpack.unwrap(); + unpack(vm, &bytes[..self.size()]) + } + + // unpack_cmp: identical native formats need neither Python objects nor + // struct parsing. Floating values and booleans cannot use byte equality. + pub(super) fn equals(self, left: &[u8], right: &[u8]) -> bool { + match self.0 { + FormatType::Bool => (left[0] != 0) == (right[0] != 0), + FormatType::Half => { + let left = half::f16::from_bits(u16::from_ne_bytes(left.try_into().unwrap())); + let right = half::f16::from_bits(u16::from_ne_bytes(right.try_into().unwrap())); + left == right + } + FormatType::Float | FormatType::FloatComplex => left + .as_chunks::<4>() + .0 + .iter() + .zip(right.as_chunks::<4>().0) + .all(|(a, b)| f32::from_ne_bytes(*a) == f32::from_ne_bytes(*b)), + FormatType::Double | FormatType::DoubleComplex => left + .as_chunks::<8>() + .0 + .iter() + .zip(right.as_chunks::<8>().0) + .all(|(a, b)| f64::from_ne_bytes(*a) == f64::from_ne_bytes(*b)), + _ => left == right, + } + } + + fn type_error(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + vm.new_type_error(format!( + "memoryview: invalid type for format '{}'", + self.name() + )) + } + + fn value_error(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + vm.new_value_error(format!( + "memoryview: invalid value for format '{}'", + self.name() + )) + } + + // fix_error_int: conversion errors use the unprefixed native format, but + // exceptions outside these three classes belong to the callback unchanged. + fn fix_error(self, error: PyBaseExceptionRef, vm: &VirtualMachine) -> PyBaseExceptionRef { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + self.type_error(vm) + } else if error.fast_isinstance(vm.ctx.exceptions.overflow_error) + || error.fast_isinstance(vm.ctx.exceptions.value_error) + { + self.value_error(vm) + } else { + error + } + } + + fn integer(self, value: &PyObject, vm: &VirtualMachine) -> PyResult + where + T: PrimInt + for<'a> TryFrom<&'a BigInt>, + { + value + .try_index(vm) + .and_then(|value| value.try_to_primitive_in_range(vm)) + .map_err(|error| self.fix_error(error, vm)) + } + + fn narrow_integer( + self, + view: &PyMemoryView, + value: &PyObject, + vm: &VirtualMachine, + ) -> PyResult + where + T: PrimInt + for<'a> TryFrom<&'a BigInt>, + U: TryFrom, + { + let value: T = self.integer(value, vm)?; + view.try_not_released(vm)?; + U::try_from(value).map_err(|_| self.value_error(vm)) + } + + pub(super) fn pack( + self, + view: &PyMemoryView, + value: PyObjectRef, + vm: &VirtualMachine, + write: impl FnOnce(&[u8]), + ) -> PyResult<()> { + // Conversion can call Python and release the view. Check immediately + // after conversion, before checking a narrower destination's range. + macro_rules! integer { + ($convert:ty, $store:ty) => {{ + let value = self.narrow_integer::<$convert, $store>(view, &value, vm)?; + write(&value.to_ne_bytes()) + }}; + } + + match self.0 { + FormatType::SByte => integer!(raw::c_long, i8), + FormatType::UByte => integer!(raw::c_ulong, u8), + FormatType::Short => integer!(raw::c_long, raw::c_short), + FormatType::UShort => integer!(raw::c_ulong, raw::c_ushort), + FormatType::Int => integer!(raw::c_long, raw::c_int), + FormatType::UInt => integer!(raw::c_ulong, raw::c_uint), + FormatType::Long => integer!(raw::c_long, raw::c_long), + FormatType::ULong => integer!(raw::c_ulong, raw::c_ulong), + FormatType::LongLong => integer!(raw::c_longlong, raw::c_longlong), + FormatType::ULongLong => integer!(raw::c_ulonglong, raw::c_ulonglong), + FormatType::SSizeT => integer!(isize, isize), + FormatType::SizeT => integer!(usize, usize), + FormatType::Float | FormatType::Double | FormatType::Half => { + let value = value + .try_to_value::(vm) + .map_err(|error| self.fix_error(error, vm))? + .into_float(); + view.try_not_released(vm)?; + match self.0 { + // Unlike struct.pack('f'), a native memoryview assignment + // uses a C cast and permits a finite value to become infinity. + FormatType::Float => write(&(value as f32).to_ne_bytes()), + FormatType::Double => write(&value.to_ne_bytes()), + _ => { + let bits = pack_float16(value).ok_or_else(|| self.value_error(vm))?; + write(&bits.to_ne_bytes()) + } + } + } + FormatType::FloatComplex | FormatType::DoubleComplex => { + let value = value + .try_to_value::(vm) + .map_err(|error| self.fix_error(error, vm))? + .into_complex(); + view.try_not_released(vm)?; + if self.0 == FormatType::FloatComplex { + write( + [ + (value.re as f32).to_ne_bytes(), + (value.im as f32).to_ne_bytes(), + ] + .as_flattened(), + ); + } else { + write([value.re.to_ne_bytes(), value.im.to_ne_bytes()].as_flattened()); + } + } + FormatType::Bool => { + // Truth testing preserves even TypeError and ValueError. + let value = value.try_to_value::(vm)?.into_bool(); + view.try_not_released(vm)?; + write(&[u8::from(value)]) + } + FormatType::Char => { + let value = value + .downcast_ref::() + .ok_or_else(|| self.type_error(vm))?; + match value.as_bytes() { + [value] => { + // An index callback can release even a character view. + // Never write through its stale storage in that case. + view.try_not_released(vm)?; + write(&[*value]); + } + _ => return Err(self.value_error(vm)), + } + } + FormatType::VoidP => { + // PyLong_AsVoidPtr accepts actual ints, not __index__, and + // allows signed negative values as well as unsigned positives. + let value = value + .downcast_ref::() + .ok_or_else(|| self.type_error(vm))?; + let value = if value.as_bigint().sign() == Sign::Minus { + value + .try_to_primitive_in_range::(vm) + .map(|value| value as usize) + } else { + value.try_to_primitive_in_range::(vm) + } + .map_err(|error| self.fix_error(error, vm))?; + view.try_not_released(vm)?; + write(&value.to_ne_bytes()) + } + _ => unreachable!("not a native memoryview scalar format"), + }; + Ok(()) + } +} + +/// struct_get_unpacker / fix_struct_error_int. Equality uses the same strict +/// parser and bounded interpreter-local cache as the struct module. +pub(super) fn comparison_format( + format: &str, + vm: &VirtualMachine, +) -> PyResult>> { + match vm + .state + .struct_format_cache + .get_or_parse(format.as_bytes(), vm) + { + Ok(format) => Ok(Some(format)), + Err(error) + if error.fast_isinstance(vm.ctx.exceptions.memory_error) + || error.fast_isinstance(vm.ctx.exceptions.import_error) => + { + Err(error) + } + Err(_) => Ok(None), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn native_comparison_uses_values_not_float_or_bool_bytes() { + let boolean = NativeFormat::parse("?").unwrap(); + assert!(boolean.equals(&[1], &[255])); + assert!(!boolean.equals(&[0], &[255])); + + let half = NativeFormat::parse("e").unwrap(); + assert!(half.equals(&0_u16.to_ne_bytes(), &0x8000_u16.to_ne_bytes())); + for bits in 0..=u16::MAX { + let bytes = bits.to_ne_bytes(); + assert_eq!(half.equals(&bytes, &bytes), bits & 0x7fff <= 0x7c00); + } + + for format in ["f", "@f", "Zf", "@Zf"] { + let format = NativeFormat::parse(format).unwrap(); + let left = [0_f32.to_ne_bytes(), 1_f32.to_ne_bytes()]; + let right = [(-0_f32).to_ne_bytes(), 1_f32.to_ne_bytes()]; + assert!(format.equals( + &left.as_flattened()[..format.size()], + &right.as_flattened()[..format.size()] + )); + for bits in [0x7f80_0001_u32, 0x7fc0_0000, 0xff80_0001, 0xffc0_0000] { + let bytes = [bits.to_ne_bytes(), 1_f32.to_ne_bytes()]; + let bytes = &bytes.as_flattened()[..format.size()]; + assert!(!format.equals(bytes, bytes)); + } + } + for format in ["d", "@d", "Zd", "@Zd"] { + let format = NativeFormat::parse(format).unwrap(); + let left = [0_f64.to_ne_bytes(), 1_f64.to_ne_bytes()]; + let right = [(-0_f64).to_ne_bytes(), 1_f64.to_ne_bytes()]; + assert!(format.equals( + &left.as_flattened()[..format.size()], + &right.as_flattened()[..format.size()] + )); + for bits in [0x7ff0_0000_0000_0001_u64, 0x7ff8_0000_0000_0000] { + let bytes = [bits.to_ne_bytes(), 1_f64.to_ne_bytes()]; + let bytes = &bytes.as_flattened()[..format.size()]; + assert!(!format.equals(bytes, bytes)); + } + } + } +} diff --git a/crates/vm/src/builtins/mod.rs b/crates/vm/src/builtins/mod.rs index c7404fcd169..d246ad6f0b1 100644 --- a/crates/vm/src/builtins/mod.rs +++ b/crates/vm/src/builtins/mod.rs @@ -20,7 +20,7 @@ pub use complex::PyComplex; pub(crate) mod coroutine; pub use coroutine::PyCoroutine; pub(crate) mod dict; -pub use dict::{PyDict, PyDictRef}; +pub use dict::{PyAnyDict, PyDict, PyDictRef, PyFrozenDict}; pub(crate) mod enumerate; pub use enumerate::PyEnumerate; pub(crate) mod filter; @@ -55,10 +55,11 @@ pub use memory::PyMemoryView; pub(crate) mod module; pub use module::{PyModule, PyModuleDef, PyModuleSlots}; pub(crate) mod namespace; +pub(crate) mod native_iter; pub use namespace::PyNamespace; pub(crate) mod object; pub use object::PyBaseObject; -pub use object::{object_generic_set_dict, object_get_dict}; +pub use object::{alloc_default, object_generic_set_dict, object_get_dict}; pub(crate) mod property; pub use property::PyProperty; #[path = "bool.rs"] @@ -75,6 +76,8 @@ pub(crate) mod type_; pub use type_::{PyType, PyTypeRef}; pub(crate) mod range; pub use range::PyRange; +pub(crate) mod sentinel; +pub use sentinel::PySentinel; pub(crate) mod set; pub use set::{PyFrozenSet, PySet}; pub(crate) mod singletons; @@ -105,6 +108,7 @@ pub use descriptor::{ }; pub use float::float_from_string as parse_float_from_string; +pub use float::invalid_float_literal_error; pub use float::try_to_bigint as try_f64_to_bigint; pub use int::try_to_float as try_bigint_to_f64; diff --git a/crates/vm/src/builtins/module.rs b/crates/vm/src/builtins/module.rs index aae75da816a..da0ff118d19 100644 --- a/crates/vm/src/builtins/module.rs +++ b/crates/vm/src/builtins/module.rs @@ -5,9 +5,13 @@ use crate::{ class::PyClassImpl, convert::ToPyObject, function::{FuncArgs, PyMethodDef, PySetterValue}, - import::{get_spec_file_origin, is_possibly_shadowing_path, is_stdlib_module_name}, + import::{ + get_spec_file_origin, is_possibly_shadowing_path, is_spec_initializing, + is_stdlib_module_name, + }, types::{GetAttr, Initializer, Representable}, }; +use rustpython_common::wtf8::wtf8_concat; #[pyclass(module = false, name = "module")] #[derive(Debug)] @@ -65,7 +69,7 @@ impl PyModuleDef { }; // Initialize module dict and methods - PyModule::__init_dict_from_def(vm, &module); + PyModule::__init_dict_from_def(vm, &module)?; module.__init_methods(vm)?; Ok(module) @@ -82,7 +86,7 @@ impl PyModuleDef { } } -#[pyclass(module = false, name = "module")] +#[pyclass(module = false, name = "module", traverse = "manual")] // The dict lives in the object extension, not the payload. The offset is // the dict cell at the front of that extension. #[pymember(name = "__dict__", offset = ::rustpython_vm::object::dict_member_offset())] @@ -90,12 +94,26 @@ impl PyModuleDef { pub struct PyModule { // PyObject *md_dict; pub def: Option<&'static PyModuleDef>, - // state: Any + native_state: crate::object::PyAtomicRef>, // weaklist // for logging purposes after md_dict is cleared pub name: Option<&'static PyStrInterned>, } +// SAFETY: Native state is the only owned Python reference in the payload. +// The module dictionary is visited separately by the object extension. +unsafe impl crate::object::Traverse for PyModule { + fn traverse(&self, tracer: &mut crate::object::TraverseFn<'_>) { + self.native_state.traverse(tracer); + } + + fn clear(&mut self, out: &mut Vec) { + if let Some(state) = self.native_state.store(None) { + out.push(state); + } + } +} + impl PyPayload for PyModule { #[inline] fn class(ctx: &Context) -> &'static Py { @@ -107,7 +125,7 @@ impl PyPayload for PyModule { pub struct ModuleInitArgs { name: PyStrRef, #[pyarg(any, default)] - doc: Option, + doc: Option, } impl PyModule { @@ -119,6 +137,7 @@ impl PyModule { pub const fn new() -> Self { Self { def: None, + native_state: crate::object::PyAtomicRef::new_empty(), name: None, } } @@ -127,13 +146,25 @@ impl PyModule { pub const fn from_def(def: &'static PyModuleDef) -> Self { Self { def: Some(def), + native_state: crate::object::PyAtomicRef::new_empty(), name: Some(def.name), } } - pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py) { - let doc = module.def.unwrap().doc.map(|doc| doc.to_owned()); - module.init_dict(module.name.unwrap(), doc, vm); + /// Interpreter-local native state, retained and traversed with the module. + #[must_use] + pub fn native_state(&self) -> Option { + self.native_state.load_owned() + } + + /// Replace native state without exposing it in the Python module dictionary. + pub fn set_native_state(&self, state: PyObjectRef) { + drop(self.native_state.store(Some(state))); + } + + pub fn __init_dict_from_def(vm: &VirtualMachine, module: &Py) -> PyResult<()> { + let doc = module.def.unwrap().doc.map(|doc| doc.as_object()); + module.init_dict(module.name.unwrap(), doc, vm) } } @@ -142,29 +173,63 @@ impl Py { debug_assert!(self.def.is_some()); for method in self.def.unwrap().methods { let func = method - .to_function() + .to_module_function(self.to_owned()) .with_module(self.name.unwrap()) - .with_module_object(self.to_owned().into()) .into_ref(&vm.ctx); vm.__module_set_attr(self, vm.ctx.intern_str(method.name), func)?; } Ok(()) } - fn getattr_inner(&self, name: &Py, vm: &VirtualMachine) -> PyResult { - if let Some(attr) = self.as_object().generic_getattr_opt(name, None, vm)? { + pub(crate) fn getattr_inner( + &self, + name: &Py, + suppress_cycle: bool, + vm: &VirtualMachine, + ) -> PyResult { + let mut attr = match self.as_object().generic_getattr_opt(name, None, vm) { + Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.attribute_error) => None, + result => result?, + }; + if attr.is_none() { + if let Some(value) = + crate::lazy_import::try_load_submodule(self, name, suppress_cycle, vm)? + { + return Ok(value); + } + // A concurrent import may have bound a child and removed its pending entry. + if self.class().is(vm.ctx.types.module_type) + || self + .class() + .get_attr(vm.ctx.intern_str(name.as_wtf8())) + .is_none_or(|descriptor| descriptor.class().slots().descr_get.load().is_none()) + { + attr = self.dict().get_item_opt(name, vm)?; + } + } + if let Some(attr) = attr { + if let Some(deferred) = + attr.downcast_ref_if_exact::(vm) + { + if suppress_cycle && crate::lazy_import::is_resolving(deferred, vm) { + return Err(vm.new_attribute_error(format!("module has no attribute '{name}'"))); + } + return crate::lazy_import::reify(deferred, name, self.dict().as_object(), vm); + } return Ok(attr); } - if let Ok(getattr) = self.dict().get_item(identifier!(vm, __getattr__), vm) { + if let Some(getattr) = + crate::lazy_import::resolved_dict_item(&self.dict(), identifier!(vm, __getattr__), vm)? + { return getattr.call((name.to_owned(),), vm); } + if suppress_cycle { + return Err(vm.new_attribute_error(format!("module has no attribute '{name}'"))); + } let dict = self.dict(); // Get the raw __name__ object (may be a str subclass) - let mod_name_obj = dict - .get_item_opt(identifier!(vm, __name__), vm) - .ok() - .flatten(); + let mod_name_obj = dict.inner_getitem_opt(identifier!(vm, __name__), vm)?; let mod_name = mod_name_obj .as_ref() .and_then(|n| n.downcast_ref::()); @@ -174,13 +239,9 @@ impl Py { return Err(vm.new_attribute_error(format!("module has no attribute '{name}'"))); }; - let spec = dict - .get_item_opt(vm.ctx.intern_str("__spec__"), vm) - .ok() - .flatten() - .filter(|s| !vm.is_none(s)); + let spec = dict.inner_getitem_opt(vm.ctx.intern_str("__spec__"), vm)?; - let origin = get_spec_file_origin(spec.as_deref(), vm); + let origin = get_spec_file_origin(spec.as_deref(), vm)?; let is_possibly_shadowing = origin .as_ref() @@ -206,7 +267,7 @@ impl Py { and prevents importing that standard library module)" ))) } else { - let is_initializing = PyModule::is_initializing(&dict, vm); + let is_initializing = is_spec_initializing(spec.as_deref(), vm)?; if is_initializing { if is_possibly_shadowing { let origin = origin.as_ref().unwrap(); @@ -230,7 +291,7 @@ impl Py { } } else { // Check for uninitialized submodule - let submodule_initializing = is_uninitialized_submodule(mod_name, name, vm); + let submodule_initializing = is_uninitialized_submodule(spec.as_deref(), name, vm)?; if submodule_initializing { Err(vm.new_attribute_error(format!( "cannot access submodule '{name}' of module '{mod_display}' \ @@ -253,26 +314,21 @@ impl Py { // TODO: should be on PyModule, not Py pub(crate) fn init_dict( &self, - name: &'static PyStrInterned, - doc: Option, + name: &Py, + doc: Option<&PyObject>, vm: &VirtualMachine, - ) { + ) -> PyResult<()> { let dict = self.dict(); - dict.set_item(identifier!(vm, __name__), name.to_object(), vm) - .expect("Failed to set __name__ on module"); - dict.set_item(identifier!(vm, __doc__), doc.to_pyobject(vm), vm) - .expect("Failed to set __doc__ on module"); - dict.set_item("__package__", vm.ctx.none(), vm) - .expect("Failed to set __package__ on module"); - dict.set_item("__loader__", vm.ctx.none(), vm) - .expect("Failed to set __loader__ on module"); - dict.set_item("__spec__", vm.ctx.none(), vm) - .expect("Failed to set __spec__ on module"); + dict.inner_setitem(identifier!(vm, __name__), name.to_owned().into(), vm)?; + dict.inner_setitem(identifier!(vm, __doc__), doc.to_pyobject(vm), vm)?; + dict.inner_setitem(vm.ctx.intern_str("__package__"), vm.ctx.none(), vm)?; + dict.inner_setitem(vm.ctx.intern_str("__loader__"), vm.ctx.none(), vm)?; + dict.inner_setitem(vm.ctx.intern_str("__spec__"), vm.ctx.none(), vm) } pub fn get_attr<'a>(&self, attr_name: impl AsPyStr<'a>, vm: &VirtualMachine) -> PyResult { let attr_name = attr_name.as_pystr(&vm.ctx); - self.getattr_inner(attr_name, vm) + self.getattr_inner(attr_name, false, vm) } pub fn set_attr<'a>( @@ -290,36 +346,42 @@ impl Py { flags(BASETYPE, HAS_DICT, HAS_WEAKREF) )] impl PyModule { + fn load_dict(zelf: &Py, vm: &VirtualMachine) -> PyResult { + zelf.as_object() + .get_attr(identifier!(vm, __dict__), vm)? + .downcast::() + .map_err(|_| vm.new_type_error(".__dict__ is not a dictionary")) + } + #[pyslot] fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { Self::new().into_ref_with_type(vm, cls).map(Into::into) } #[pymethod] - fn __dir__(zelf: &Py, vm: &VirtualMachine) -> PyResult> { + fn __dir__(zelf: &Py, vm: &VirtualMachine) -> PyResult { // First check if __dict__ attribute exists and is actually a dictionary - let dict_attr = zelf.as_object().get_attr(identifier!(vm, __dict__), vm)?; - let dict = dict_attr - .downcast::() - .map_err(|_| vm.new_type_error(".__dict__ is not a dictionary"))?; + let dict = Self::load_dict(zelf, vm)?; // PEP 562: honor a module-level __dir__ if one is defined - if let Some(dir_func) = dict.get_item_opt(identifier!(vm, __dir__), vm)? { - return dir_func.call((), vm)?.try_to_value(vm); + if let Some(dir_func) = + crate::lazy_import::resolved_dict_item(&dict, identifier!(vm, __dir__), vm)? + { + return dir_func.call((), vm); } let attrs = dict.into_iter().map(|(k, _v)| k).collect(); - Ok(attrs) + Ok(vm.ctx.new_list(attrs).into()) } #[pygetset] fn __annotate__(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let dict = zelf.dict(); + let dict = Self::load_dict(zelf, vm)?; // Get __annotate__ from dict; if not present, insert None and return it // See: module_get_annotate() - if let Some(annotate) = dict.get_item_opt(identifier!(vm, __annotate__), vm)? { + if let Some(annotate) = dict.inner_getitem_opt(identifier!(vm, __annotate__), vm)? { Ok(annotate) } else { let none = vm.ctx.none(); - dict.set_item(identifier!(vm, __annotate__), none.clone(), vm)?; + dict.inner_setitem(identifier!(vm, __annotate__), none.clone(), vm)?; Ok(none) } } @@ -332,14 +394,14 @@ impl PyModule { ) -> PyResult<()> { match value { PySetterValue::Assign(value) => { + let dict = Self::load_dict(zelf, vm)?; if !vm.is_none(&value) && !value.is_callable() { return Err(vm.new_type_error("__annotate__ must be callable or None")); } - let dict = zelf.dict(); - dict.set_item(identifier!(vm, __annotate__), value.clone(), vm)?; + dict.inner_setitem(identifier!(vm, __annotate__), value.clone(), vm)?; // Clear __annotations__ if value is not None if !vm.is_none(&value) { - dict.del_item(identifier!(vm, __annotations__), vm).ok(); + dict.inner_pop_item(identifier!(vm, __annotations__), vm)?; } Ok(()) } @@ -349,28 +411,36 @@ impl PyModule { #[pygetset] fn __annotations__(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let dict = zelf.dict(); + let dict = Self::load_dict(zelf, vm)?; // Check if __annotations__ is already in dict (explicitly set) - if let Some(annotations) = dict.get_item_opt(identifier!(vm, __annotations__), vm)? { + if let Some(annotations) = dict.inner_getitem_opt(identifier!(vm, __annotations__), vm)? { return Ok(annotations); } // Check if module is initializing - let is_initializing = Self::is_initializing(&dict, vm); + let spec = zelf + .dict() + .inner_getitem_opt(vm.ctx.intern_str("__spec__"), vm)?; + let is_initializing = is_spec_initializing(spec.as_deref(), vm)?; + drop(spec); // PEP 649: Get __annotate__ and call it if callable let annotations = if let Some(annotate) = - dict.get_item_opt(identifier!(vm, __annotate__), vm)? + dict.inner_getitem_opt(identifier!(vm, __annotate__), vm)? && annotate.is_callable() { // Call __annotate__(1) where 1 is FORMAT_VALUE let result = annotate.call((1i32,), vm)?; - if !result.class().is(vm.ctx.types.dict_type) { - return Err(vm.new_type_error(format!( - "__annotate__ returned non-dict of type '{}'", - result.class().name() - ))); + if !result.downcastable::() { + let error = result.class().fully_qualified_name(vm).map(|name| { + vm.new_type_error(wtf8_concat!( + "__annotate__() must return a dict, not ", + name + )) + }); + drop(annotate); + return Err(error?); } result } else { @@ -379,45 +449,34 @@ impl PyModule { // Cache result unless module is initializing if !is_initializing { - dict.set_item(identifier!(vm, __annotations__), annotations.clone(), vm)?; + dict.inner_setitem(identifier!(vm, __annotations__), annotations.clone(), vm)?; } Ok(annotations) } - /// Check if module is initializing via __spec__._initializing - fn is_initializing(dict: &Py, vm: &VirtualMachine) -> bool { - if let Ok(Some(spec)) = dict.get_item_opt(vm.ctx.intern_str("__spec__"), vm) - && let Ok(initializing) = spec.get_attr(vm.ctx.intern_str("_initializing"), vm) - { - return initializing.try_to_bool(vm).unwrap_or(false); - } - false - } - #[pygetset(setter)] fn set___annotations__( zelf: &Py, value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { - let dict = zelf.dict(); - match value { + let dict = Self::load_dict(zelf, vm)?; + match &value { PySetterValue::Assign(value) => { - dict.set_item(identifier!(vm, __annotations__), value, vm)?; - // Clear __annotate__ from dict - dict.del_item(identifier!(vm, __annotate__), vm).ok(); - Ok(()) + dict.inner_setitem(identifier!(vm, __annotations__), value.clone(), vm)?; } PySetterValue::Delete => { - if dict.del_item(identifier!(vm, __annotations__), vm).is_err() { + if dict + .inner_pop_item(identifier!(vm, __annotations__), vm)? + .is_none() + { return Err(vm.new_attribute_error("__annotations__")); } - // Also clear __annotate__ - dict.del_item(identifier!(vm, __annotate__), vm).ok(); - Ok(()) } } + dict.inner_pop_item(identifier!(vm, __annotate__), vm)?; + Ok(()) } } @@ -431,14 +490,14 @@ impl Initializer for PyModule { .flags .has_feature(crate::types::PyTypeFlags::HAS_DICT) ); - zelf.init_dict(vm.ctx.intern_str(args.name.as_wtf8()), args.doc, vm); - Ok(()) + let ModuleInitArgs { name, doc } = args; + zelf.init_dict(&name, doc.as_deref(), vm) } } impl GetAttr for PyModule { fn getattro(zelf: &Py, name: &Py, vm: &VirtualMachine) -> PyResult { - zelf.getattr_inner(name, vm) + zelf.getattr_inner(name, false, vm) } } @@ -462,31 +521,19 @@ pub(crate) fn init(context: &'static Context) { PyModule::extend_class(context, context.types.module_type); } -/// Check if {module_name}.{name} is an uninitialized submodule in sys.modules. +/// Check the parent module's spec for an uninitialized submodule. fn is_uninitialized_submodule( - module_name: Option<&Py>, + spec: Option<&PyObject>, name: &Py, vm: &VirtualMachine, -) -> bool { - let Some(mod_name) = module_name else { - return false; +) -> PyResult { + let Some(spec) = spec else { + return Ok(false); }; - - let Ok(sys_modules) = vm.sys_module.get_attr("modules", vm) else { - return false; - }; - - let full_name = vm.ctx.new_utf8_str(format!("{}.{name}", mod_name.as_str())); - let Ok(sub_mod) = sys_modules.get_item(&*full_name, vm) else { - return false; - }; - - let spec = match sub_mod.get_attr("__spec__", vm) { - Ok(s) if !vm.is_none(&s) => s, - _ => return false, - }; - - spec.get_attr("_initializing", vm) - .and_then(|v| v.try_to_bool(vm)) - .unwrap_or(false) + match vm.get_attribute_opt(spec, "_uninitialized_submodules")? { + Some(submodules) => submodules + .sequence_unchecked() + .contains(name.as_object(), vm), + None => Ok(false), + } } diff --git a/crates/vm/src/builtins/namespace.rs b/crates/vm/src/builtins/namespace.rs index a872fd6c92e..2fdd8a4fe94 100644 --- a/crates/vm/src/builtins/namespace.rs +++ b/crates/vm/src/builtins/namespace.rs @@ -28,7 +28,7 @@ impl PyPayload for PyNamespace { impl DefaultConstructor for PyNamespace {} #[pyclass( - flags(BASETYPE, HAS_DICT, HAS_WEAKREF), + flags(BASETYPE, HAS_DICT), with(Constructor, Initializer, Comparable, Representable) )] impl PyNamespace { @@ -54,7 +54,7 @@ impl PyNamespace { let cls: PyObjectRef = zelf.class().to_owned().into(); let result = cls.call((), vm)?; - if !zelf.class().is(result.class()) { + if !result.downcastable::() { return Err(vm.new_type_error(format!( "expect {} type, but {}() returned '{}' object", Self::class(&vm.ctx).slot_name(), @@ -72,14 +72,11 @@ impl PyNamespace { // Copy the current namespace dict to the new instance let src_dict = zelf.dict().unwrap(); let dst_dict = result.dict().unwrap(); - for (key, value) in src_dict { - dst_dict.set_item(&*key, value, vm)?; - } + dst_dict.merge_dict(&src_dict, true, vm)?; - // Update with the provided kwargs - for (name, value) in changes { - let name = vm.ctx.new_str(name); - result.set_attr(&name, value, vm)?; + // Bypass attribute setters and retain all argument owners during updates. + for (name, value) in &changes { + dst_dict.inner_setitem(name, value.clone(), vm)?; } Ok(result) @@ -98,38 +95,37 @@ impl Initializer for PyNamespace { type Args = NamespaceArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - // If there's a positional argument, treat it as a mapping - if let OptionalArg::Present(mapping) = args.mapping_or_iterable { - // Convert to dict if not already - let dict: PyRef = if let Some(d) = mapping.downcast_ref::() { - d.to_owned() + // Keep the original input alive through conversion and both updates. + if let OptionalArg::Present(mapping) = &args.mapping_or_iterable { + let dict: PyRef = if mapping.class().is(vm.ctx.types.dict_type) { + mapping.downcast_ref::().unwrap().to_owned() } else { - // Call dict() on the mapping + // Dict subclasses may override the mapping conversion protocol. let dict_type: PyObjectRef = vm.ctx.types.dict_type.to_owned().into(); dict_type - .call((mapping,), vm)? + .call((mapping.clone(),), vm)? .downcast() .map_err(|_| vm.new_type_error("dict() did not return a dict"))? }; - // Validate keys are strings and set attributes - for (key, value) in dict { - let key_str = key - .downcast_ref::() - .ok_or_else(|| { - vm.new_type_error(format!( - "keywords must be strings, not '{}'", - key.class().name() - )) - })?; - zelf.as_object().set_attr(key_str, value, vm)?; + // Validate every key before publishing any of the supplied values. + if dict + .keys_vec() + .iter() + .any(|key| !key.downcastable::()) + { + return Err(vm.new_type_error("keywords must be strings")); } + zelf.as_object() + .dict() + .unwrap() + .merge_dict(&dict, true, vm)?; } - // Apply keyword arguments (these override positional mapping values) - for (name, value) in args.kwargs { - let name = vm.ctx.new_str(name); - zelf.as_object().set_attr(&name, value, vm)?; + // Apply keywords directly to the namespace, without invoking descriptors. + let dict = zelf.as_object().dict().unwrap(); + for (name, value) in &args.kwargs { + dict.inner_setitem(name, value.clone(), vm)?; } Ok(()) } @@ -163,25 +159,37 @@ impl Representable for PyNamespace { let repr = if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { let dict = zelf.as_object().dict().unwrap(); - let mut result = Wtf8Buf::from(format!("{name}(")); - let mut first = true; - for (key, value) in dict { - let Some(key_str) = key.downcast_ref::() else { - continue; - }; - if key_str.as_wtf8().is_empty() { - continue; + // Retain the entire key snapshot, but look up each value after any + // preceding repr callback has had a chance to change the dictionary. + let keys = dict.keys_vec(); + let result: PyResult = (|| { + let mut result = Wtf8Buf::from(format!("{name}(")); + let mut first = true; + for key in &keys { + let Some(key_str) = key.downcast_ref::() else { + continue; + }; + if key_str.as_wtf8().is_empty() { + continue; + } + let Some(value) = dict.get_item_opt(&**key, vm)? else { + continue; + }; + if !first { + result.push_str(", "); + } + first = false; + result.push_wtf8(key_str.as_wtf8()); + result.push_char('='); + result.push_wtf8(value.repr(vm)?.as_wtf8()); } - if !first { - result.push_str(", "); - } - first = false; - result.push_wtf8(key_str.as_wtf8()); - result.push_char('='); - result.push_wtf8(value.repr(vm)?.as_wtf8()); - } - result.push_char(')'); - result + result.push_char(')'); + Ok(result) + })(); + // The key list releases its elements backwards, on success and + // failure, while recursive calls from finalizers still see the guard. + for _key in keys.into_iter().rev() {} + result? } else { Wtf8Buf::from(format!("{name}(...)")) }; diff --git a/crates/vm/src/builtins/native_iter.rs b/crates/vm/src/builtins/native_iter.rs new file mode 100644 index 00000000000..4989e58dd51 --- /dev/null +++ b/crates/vm/src/builtins/native_iter.rs @@ -0,0 +1,153 @@ +use super::PyTupleRef; +use crate::{ + PyObject, PyObjectRef, PyResult, VirtualMachine, + function::int_as_ssize, + object::{Traverse, TraverseFn}, +}; +use rustpython_common::lock::PyMutex; + +#[derive(Debug, Clone, Copy)] +pub(crate) enum NativeIterKind { + Sequence, + List, + ListReverse, + ByteArray, +} + +#[derive(Debug)] +struct NativeIterState { + sequence: Option, + index: isize, +} + +unsafe impl Traverse for NativeIterState { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.sequence.traverse(tracer); + } +} + +// Concrete sequence reads cannot invoke Python slots. Keep the read and cursor +// update together, but allocate results and release owners after unlocking. +// Unlike generic sequence iterators, a negative native cursor can retain its +// owner: lists can restore it with __setstate__, while bytearrays cannot. +#[derive(Debug)] +pub(crate) struct NativeSequenceIter { + state: PyMutex>, + kind: NativeIterKind, +} + +unsafe impl Traverse for NativeSequenceIter { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.state.traverse(tracer); + } +} + +impl NativeSequenceIter { + pub(crate) const fn new(sequence: T, kind: NativeIterKind, index: isize) -> Self { + Self { + state: PyMutex::new(NativeIterState { + sequence: Some(sequence), + index, + }), + kind, + } + } + + // The closure may read native storage and update a cached offset, but must + // not allocate Python objects, release Python owners, or invoke Python. + pub(crate) fn next(&self, read: impl FnOnce(&mut T, usize) -> Option) -> Option { + let mut state = self.state.lock(); + if state.index < 0 { + return None; + } + let index = state.index as usize; + let sequence = state.sequence.as_mut()?; + let item = read(sequence, index); + let _released = if item.is_some() { + state.index += if matches!(self.kind, NativeIterKind::ListReverse) { + -1 + } else { + 1 + }; + None + } else { + state.index = -1; + state.sequence.take() + }; + drop(state); + item + } + + pub(crate) fn length_hint(&self, length: impl FnOnce(&T) -> usize) -> usize { + let state = self.state.lock(); + if state.index < 0 { + return 0; + } + let Some(sequence) = &state.sequence else { + return 0; + }; + let length = length(sequence); + let index = state.index as usize; + if matches!(self.kind, NativeIterKind::ListReverse) { + if index < length { index + 1 } else { 0 } + } else { + length.saturating_sub(index) + } + } + + pub(crate) fn set_state( + &self, + value: &PyObject, + length: impl FnOnce(&mut T) -> usize, + vm: &VirtualMachine, + ) -> PyResult<()> { + // Validate even a permanently exhausted iterator, before taking its + // lock. A rejected state must not invalidate a cached string offset. + let index = int_as_ssize(value, vm)?; + let mut state = self.state.lock(); + if matches!(self.kind, NativeIterKind::ByteArray) && state.index < 0 { + return Ok(()); + } + if let Some(sequence) = &mut state.sequence { + let length = length(sequence) as isize; + let minimum = if matches!(self.kind, NativeIterKind::Sequence) { + 0 + } else { + -1 + }; + let maximum = if matches!(self.kind, NativeIterKind::ListReverse) { + length - 1 + } else { + length + }; + state.index = index.clamp(minimum, maximum); + } + Ok(()) + } + + // Resolve the builtin before this call. Snapshot only native state while + // locked; constructing the reduction can allocate and run finalizers. + pub(crate) fn reduce( + &self, + func: PyObjectRef, + active: impl FnOnce(T) -> PyObjectRef, + empty: impl FnOnce(&VirtualMachine) -> PyObjectRef, + vm: &VirtualMachine, + ) -> PyTupleRef + where + T: Clone, + { + let snapshot = { + let state = self.state.lock(); + if state.index >= 0 { + state.sequence.clone().map(|seq| (seq, state.index)) + } else { + None + } + }; + match snapshot { + Some((sequence, index)) => vm.new_tuple((func, (active(sequence),), index)), + None => vm.new_tuple((func, (empty(vm),))), + } + } +} diff --git a/crates/vm/src/builtins/object.rs b/crates/vm/src/builtins/object.rs index d7de843a7a0..1d318a39583 100644 --- a/crates/vm/src/builtins/object.rs +++ b/crates/vm/src/builtins/object.rs @@ -1,4 +1,7 @@ -use super::{PyDict, PyDictRef, PyList, PyStr, PyStrRef, PyType, PyTypeRef, PyUtf8StrRef}; +use super::{ + PyAnyDict, PyDict, PyDictRef, PyList, PyStr, PyStrRef, PyType, PyTypeRef, PyUtf8StrRef, + builtin_func::PyNativeFunction, descriptor::PyMethodDescriptor, +}; use crate::common::hash::PyHash; use crate::types::PyTypeFlags; use crate::{ @@ -10,11 +13,12 @@ use crate::{ PySetterValue, }, types::{Constructor, Initializer, PyComparisonOp}, + vm::PyMethod, }; use itertools::Itertools; #[pyclass(module = false, name = "object")] -#[derive(Debug)] +#[derive(Debug, Default)] pub struct PyBaseObject; impl PyPayload for PyBaseObject { @@ -27,6 +31,9 @@ impl PyPayload for PyBaseObject { pub struct ObjectArgs; impl FromArgs for ObjectArgs { + // The constructor slots decide acceptance from the class's __new__/__init__. + const BINDING_PARAMS: Option<&'static [Param]> = FuncArgs::BINDING_PARAMS; + const PARAMS: Option<&'static [Param]> = Some(&[]); fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result { @@ -64,7 +71,9 @@ impl Constructor for PyBaseObject { { // Both __new__ and __init__ are object's versions, // so the type accepts no arguments - return Err(vm.new_type_error(format!("{}() takes no arguments", cls.name()))); + return Err( + vm.new_type_error(format!("{}() takes no arguments", cls.slot_name())) + ); } // If tp_init != object_init, then the type has custom __init__ // which might accept arguments, so we allow it @@ -93,7 +102,9 @@ impl Constructor for PyBaseObject { } } - generic_alloc(cls, 0, vm) + // Every type inherits tp_alloc via set_alloc; object keeps generic_alloc. + let alloc = cls.slots.alloc.load().unwrap_or(generic_alloc); + alloc(cls, 0, vm) } fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { @@ -101,20 +112,24 @@ impl Constructor for PyBaseObject { } } -#[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] -pub(crate) fn generic_alloc(cls: PyTypeRef, _nitems: usize, vm: &VirtualMachine) -> PyResult { +/// Allocate `T::default()` with the same HAS_DICT handling as object tp_alloc. +pub fn alloc_default( + cls: PyTypeRef, + _nitems: usize, + vm: &VirtualMachine, +) -> PyResult { // Only create dict if the class has HAS_DICT flag (i.e., __slots__ was not defined // or __dict__ is in __slots__) - let dict = if cls - .slots - .flags - .has_feature(crate::types::PyTypeFlags::HAS_DICT) - { + let dict = if cls.slots.flags.has_feature(PyTypeFlags::HAS_DICT) { Some(vm.ctx.new_dict()) } else { None }; - Ok(crate::PyRef::new_ref(PyBaseObject, cls, dict).into()) + Ok(crate::PyRef::new_ref(T::default(), cls, dict).into()) +} + +pub(crate) fn generic_alloc(cls: PyTypeRef, nitems: usize, vm: &VirtualMachine) -> PyResult { + alloc_default::(cls, nitems, vm) } impl Initializer for PyBaseObject { @@ -151,7 +166,7 @@ impl Initializer for PyBaseObject { { return Err(vm.new_type_error(format!( "{}.__init__() takes exactly one argument (the instance to initialize)", - typ.name() + typ.slot_name() ))); } @@ -225,17 +240,43 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine) let slot_names_len = slot_names.__len__(); if slot_names_len > 0 { let slots = vm.ctx.new_dict(); - for i in 0..slot_names_len { - let borrowed_names = slot_names.borrow_vec(); - // Check if slotnames changed during iteration - if borrowed_names.len() != slot_names_len { - return Err(vm.new_runtime_error("__slotnames__ changed size during iteration")); + let outcome = (|| { + for i in 0..slot_names_len { + // Release the list lock before the attribute lookup: a getter + // or `__getattr__` may mutate `__slotnames__`. + let name = slot_names.borrow_vec().get(i).cloned(); + let name = name.ok_or_else(|| { + vm.new_runtime_error("__slotnames__ changed size during iteration") + })?; + let name = name.downcast::().map_err(|name| { + vm.new_type_error(format!( + "attribute name must be string, not '{}'", + name.class().name() + )) + })?; + if let Some(value) = vm.get_attribute_opt(obj, &name)? { + // Keep the original key and both owners through insertion. + let (_value, name) = (value.clone(), name); + let inserted = slots.set_item(name.as_object(), value, vm); + drop(name); + inserted?; + } else { + drop(name); + } + // The list is stored on the class, so it may change while we + // iterate over it, including when the name is released. + if slot_names.borrow_vec().len() != slot_names_len { + return Err( + vm.new_runtime_error("__slotnames__ changed size during iteration") + ); + } } - let name = borrowed_names[i].downcast_ref::().unwrap(); - let Ok(value) = obj.get_attr(name, vm) else { - continue; - }; - slots.set_item(name.as_wtf8(), value, vm).unwrap(); + Ok(()) + })(); + if let Err(exc) = outcome { + drop(slot_names); + drop(slots); + return Err(exc); } if !slots.is_empty() { @@ -247,35 +288,6 @@ fn object_getstate_default(obj: &PyObject, required: bool, vm: &VirtualMachine) Ok(state) } -// object_getstate -// fn object_getstate( -// obj: &PyObject, -// required: bool, -// vm: &VirtualMachine, -// ) -> PyResult { -// let getstate = obj.get_attr(identifier!(vm, __getstate__), vm)?; -// if vm.is_none(&getstate) { -// return Ok(None); -// } - -// let getstate = match getstate.downcast_exact::(vm) { -// Ok(getstate) -// if getstate -// .get_self() -// .map_or(false, |self_obj| self_obj.is(obj)) -// && std::ptr::addr_eq( -// getstate.as_func() as *const _, -// &PyBaseObject::__getstate__ as &dyn crate::function::PyNativeFn as *const _, -// ) => -// { -// return object_getstate_default(obj, required, vm); -// } -// Ok(getstate) => getstate.into_pyref().into(), -// Err(getstate) => getstate, -// }; -// getstate.call((), vm) -// } - #[pyclass(with(Constructor, Initializer), flags(BASETYPE))] impl PyBaseObject { #[pymethod] @@ -383,36 +395,18 @@ impl PyBaseObject { #[pymethod] pub fn __dir__(zelf: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let mut names: Vec = Vec::new(); - - match zelf.get_attr(identifier!(vm, __dict__), vm) { - Ok(obj) => { - if let Ok(dict) = obj.downcast::() { - names.extend( - dict.into_iter() - .filter_map(|(k, _)| k.downcast_ref::().is_some().then_some(k)), - ); - } - } - Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) => {} - Err(e) => return Err(e), - } - - match zelf.get_attr(identifier!(vm, __class__), vm) { - Ok(cls_obj) => { - if let Some(cls) = cls_obj.downcast_ref::() { - for (name, _) in cls.get_attributes(&vm.ctx) { - names.push(name.to_object()); - } - } - } - Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) => {} - Err(e) => return Err(e), + let dict = match vm.get_attribute_opt(&zelf, identifier!(vm, __dict__))? { + Some(obj) => match obj.downcast::() { + Ok(dict) => PyRef::::from(dict).copy_as_dict(vm)?, + Err(_) => PyDict::default(), + }, + None => PyDict::default(), + }; + let class = vm.get_attribute_opt(&zelf, identifier!(vm, __class__))?; + if let Some(class) = &class { + merge_class_dict(&dict, class, vm)?; } - - let lst = PyList::from(names); - lst.sort(Default::default(), vm)?; - Ok(lst) + Ok(PyList::from(dict.keys_vec())) } #[pymethod] @@ -438,11 +432,15 @@ impl PyBaseObject { #[pygetset(setter)] fn set___class__( instance: PyObjectRef, - value: PyObjectRef, + value: PySetterValue, vm: &VirtualMachine, ) -> PyResult<()> { + let value = value.ok_or_else(|| vm.new_type_error("can't delete __class__ attribute"))?; match value.downcast::() { Ok(cls) => { + vm.audit("object.__setattr__", || { + (instance.clone(), "__class__", cls.clone()) + })?; let current_cls = instance.class(); let both_module = current_cls.fast_issubclass(vm.ctx.types.module_type) && cls.fast_issubclass(vm.ctx.types.module_type); @@ -453,7 +451,13 @@ impl PyBaseObject { && !cls.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE); // FIXME(#1979) cls instances might have a payload if both_mutable || both_module { - super::type_::compatible_for_assignment(current_cls, &cls, "__class__", vm)?; + super::type_::compatible_for_assignment( + current_cls, + &cls, + "__class__", + true, + vm, + )?; instance.set_class(cls, vm); crate::stdlib::_testinternalcapi::note_set_class(); Ok(()) @@ -488,17 +492,25 @@ impl PyBaseObject { } #[pymethod] - fn __reduce_ex__(zelf: PyObjectRef, protocol: usize, vm: &VirtualMachine) -> PyResult { + fn __reduce_ex__(zelf: PyObjectRef, protocol: PyObjectRef, vm: &VirtualMachine) -> PyResult { + // Keep the original argument alive through reducer lookup and dispatch. + let protocol_number = protocol + .try_index(vm)? + .try_to_primitive::(vm) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C int"))?; let __reduce__ = identifier!(vm, __reduce__); if let Some(reduce) = vm.get_attribute_opt(&zelf, __reduce__)? { let object_reduce = vm.ctx.types.object_type.get_attr(__reduce__).unwrap(); let typ_obj: PyObjectRef = zelf.class().to_owned().into(); let class_reduce = typ_obj.get_attr(__reduce__, vm)?; - if !class_reduce.is(&object_reduce) { + let overridden = !class_reduce.is(&object_reduce); + drop(class_reduce); + drop(typ_obj); + if overridden { return reduce.call((), vm); } } - common_reduce(zelf, protocol, vm) + common_reduce(zelf, protocol_number, vm) } #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] @@ -517,6 +529,26 @@ impl PyBaseObject { } } +pub(crate) fn merge_class_dict( + dict: &PyDict, + class: &PyObject, + vm: &VirtualMachine, +) -> PyResult<()> { + vm.with_recursion(" while collecting directory entries", || { + if let Some(class_dict) = vm.get_attribute_opt(class, identifier!(vm, __dict__))? { + dict.merge_mapping(class_dict, vm)?; + } + if let Some(bases) = vm.get_attribute_opt(class, identifier!(vm, __bases__))? { + let sequence = bases.sequence_unchecked(); + for index in 0..sequence.length(vm)? { + let base = sequence.get_item(index as isize, vm)?; + merge_class_dict(dict, &base, vm)?; + } + } + Ok(()) + }) +} + pub fn object_get_dict(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(dict) = obj.dict() { Ok(dict) @@ -589,7 +621,9 @@ fn get_new_arguments( vm: &VirtualMachine, ) -> PyResult<(Option, Option)> { // First try __getnewargs_ex__ - if let Some(getnewargs_ex) = vm.get_special_method(obj, identifier!(vm, __getnewargs_ex__))? { + if let Some(getnewargs_ex) = + PyMethod::get_special_ex::(obj, identifier!(vm, __getnewargs_ex__), vm, true)? + { let newargs = getnewargs_ex.invoke((), vm)?; let newargs_tuple: PyRef = newargs.downcast().map_err(|obj| { @@ -608,26 +642,39 @@ fn get_new_arguments( let args = newargs_tuple.as_slice()[0].clone(); let kwargs = newargs_tuple.as_slice()[1].clone(); + // Releasing the outer tuple can run Python before its items are checked. + drop(newargs_tuple); + + let args_tuple = match args.downcast::() { + Ok(args) => args, + Err(args) => { + let exc = vm.new_type_error(format!( + "first item of the tuple returned by __getnewargs_ex__ must be a tuple, not '{}'", + args.class().name() + )); + return Err(exc); + } + }; - let args_tuple: PyRef = args.downcast().map_err(|obj| { - vm.new_type_error(format!( - "first item of the tuple returned by __getnewargs_ex__ must be a tuple, not '{}'", - obj.class().name() - )) - })?; - - let kwargs_dict: PyRef = kwargs.downcast().map_err(|obj| { - vm.new_type_error(format!( - "second item of the tuple returned by __getnewargs_ex__ must be a dict, not '{}'", - obj.class().name() - )) - })?; + let kwargs_dict = match kwargs.downcast::() { + Ok(kwargs) => kwargs, + Err(kwargs) => { + let exc = vm.new_type_error(format!( + "second item of the tuple returned by __getnewargs_ex__ must be a dict, not '{}'", + kwargs.class().name() + )); + drop(args_tuple); + return Err(exc); + } + }; return Ok((Some(args_tuple), Some(kwargs_dict))); } // Fall back to __getnewargs__ - if let Some(getnewargs) = vm.get_special_method(obj, identifier!(vm, __getnewargs__))? { + if let Some(getnewargs) = + PyMethod::get_special_ex::(obj, identifier!(vm, __getnewargs__), vm, true)? + { let args = getnewargs.invoke((), vm)?; let args_tuple: PyRef = args.downcast().map_err(|obj| { @@ -644,36 +691,32 @@ fn get_new_arguments( Ok((None, None)) } -/// Check if __getstate__ is overridden by comparing with object.__getstate__ -fn is_getstate_overridden(obj: &PyObject, vm: &VirtualMachine) -> bool { - let obj_cls = obj.class(); - let object_type = vm.ctx.types.object_type; - - // If the class is object itself, not overridden - if obj_cls.is(object_type) { - return false; - } - - // Check if __getstate__ in the MRO comes from object or elsewhere - // If the type has its own __getstate__, it's overridden - if let Some(getstate) = obj_cls.get_attr(identifier!(vm, __getstate__)) - && let Some(obj_getstate) = object_type.get_attr(identifier!(vm, __getstate__)) - { - return !getstate.is(&obj_getstate); - } - false -} - /// object_getstate - calls __getstate__ method or default implementation fn object_getstate(obj: &PyObject, required: bool, vm: &VirtualMachine) -> PyResult { - // If __getstate__ is not overridden, use the default implementation with required flag - if !is_getstate_overridden(obj, vm) { - return object_getstate_default(obj, required, vm); - } - - // __getstate__ is overridden, call it without required let getstate = obj.get_attr(identifier!(vm, __getstate__), vm)?; - getstate.call((), vm) + // Only the original built-in bound to this object receives `required`. + // Instance attributes and custom lookup must run before this distinction. + let is_default = + getstate + .downcast_ref::() + .is_some_and(|method| { + method.get_self().is_some_and(|bound| bound.is(obj)) + && vm + .ctx + .types + .object_type + .get_attr(identifier!(vm, __getstate__)) + .is_some_and(|descriptor| { + descriptor.downcast_ref::().is_some_and( + |descriptor| core::ptr::eq(method.value, descriptor.method), + ) + }) + }); + if is_default { + object_getstate_default(obj, required, vm) + } else { + getstate.call((), vm) + } } /// Get list items iterator if obj is a list (or subclass), None iterator otherwise @@ -697,46 +740,56 @@ fn get_items_iter(obj: &PyObject, vm: &VirtualMachine) -> PyResult<(PyObjectRef, /// reduce_newobj - creates reduce tuple for protocol >= 2 fn reduce_newobj(obj: &PyObject, vm: &VirtualMachine) -> PyResult { // Check if type has tp_new - let cls = obj.class(); - if cls.slots.new.load().is_none() { - return Err(vm.new_type_error(format!("cannot pickle '{}' object", cls.name()))); + if obj.class().slots.new.load().is_none() { + return Err(vm.new_type_error(format!("cannot pickle '{}' object", obj.class().name()))); } let (args, kwargs) = get_new_arguments(obj, vm)?; - let copyreg = vm.import("copyreg", 0)?; + let copyreg = match vm.import("copyreg", 0) { + Ok(copyreg) => copyreg, + Err(exc) => { + drop(args); + return Err(exc); + } + }; let has_args = args.is_some(); - let (newobj, newargs): (PyObjectRef, PyObjectRef) = if kwargs.is_none() - || kwargs.as_ref().is_some_and(|k| k.is_empty()) - { - // Use copyreg.__newobj__ - let newobj = copyreg.get_attr("__newobj__", vm)?; - - let args_vec: Vec = args.map(|a| a.as_slice().to_vec()).unwrap_or_default(); - - // Create (cls, *args) tuple - let mut newargs_vec: Vec = vec![cls.to_owned().into()]; - newargs_vec.extend(args_vec); - let newargs = vm.ctx.new_tuple(newargs_vec); - - (newobj, newargs.into()) - } else { - // args == NULL with non-empty kwargs is BadInternalCall - let Some(args) = args else { - return Err(vm.new_system_error("bad internal call")); - }; - // Use copyreg.__newobj_ex__ - let newobj = copyreg.get_attr("__newobj_ex__", vm)?; - let args_tuple: PyObjectRef = args.into(); - let kwargs_dict: PyObjectRef = - kwargs.map_or_else(|| vm.ctx.new_dict().into(), |k| k.into()); - - let newargs = vm - .ctx - .new_tuple(vec![cls.to_owned().into(), args_tuple, kwargs_dict]); - (newobj, newargs.into()) + let (newobj, newargs): (PyObjectRef, PyObjectRef) = match kwargs { + Some(kwargs) if !kwargs.is_empty() => { + // args == NULL with non-empty kwargs is BadInternalCall + let Some(args) = args else { + drop(copyreg); + drop(kwargs); + return Err(vm.new_system_error("bad internal call")); + }; + // Use copyreg.__newobj_ex__ + let newobj = copyreg.get_attr("__newobj_ex__", vm); + drop(copyreg); + let newobj = newobj?; + let newargs = vm.ctx.new_tuple(vec![ + obj.class().to_owned().into(), + args.into(), + kwargs.into(), + ]); + (newobj, newargs.into()) + } + kwargs => { + // Empty kwargs are released before looking up copyreg.__newobj__. + drop(kwargs); + let newobj = copyreg.get_attr("__newobj__", vm); + drop(copyreg); + let newobj = newobj?; + // Create (cls, *args) after callbacks, but before releasing args. + let mut newargs_vec = vec![obj.class().to_owned().into()]; + if let Some(args) = &args { + newargs_vec.extend_from_slice(args.as_slice()); + } + let newargs = vm.ctx.new_tuple(newargs_vec); + drop(args); + (newobj, newargs.into()) + } }; // Determine if state is required @@ -745,9 +798,22 @@ fn reduce_newobj(obj: &PyObject, vm: &VirtualMachine) -> PyResult { let is_dict = obj.fast_isinstance(vm.ctx.types.dict_type); let required = !(has_args || is_list || is_dict); - let state = object_getstate(obj, required, vm)?; + let state = match object_getstate(obj, required, vm) { + Ok(state) => state, + Err(exc) => { + drop(newobj); + return Err(exc); + } + }; - let (listitems, dictitems) = get_items_iter(obj, vm)?; + let (listitems, dictitems) = match get_items_iter(obj, vm) { + Ok(items) => items, + Err(exc) => { + drop(newobj); + drop(newargs); + return Err(exc); + } + }; let result = vm .ctx @@ -755,7 +821,7 @@ fn reduce_newobj(obj: &PyObject, vm: &VirtualMachine) -> PyResult { Ok(result.into()) } -fn common_reduce(obj: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { +fn common_reduce(obj: PyObjectRef, proto: i32, vm: &VirtualMachine) -> PyResult { if proto >= 2 { reduce_newobj(&obj, vm) } else { diff --git a/crates/vm/src/builtins/property.rs b/crates/vm/src/builtins/property.rs index 23185df1a01..7cf2833d3bf 100644 --- a/crates/vm/src/builtins/property.rs +++ b/crates/vm/src/builtins/property.rs @@ -18,12 +18,20 @@ struct SetNameArgs { } impl FromArgs for SetNameArgs { + // CPython uses a bespoke positional-count error in property_set_name. + const BINDING_PARAMS: Option<&'static [Param]> = None; + const PARAMS: Option<&'static [Param]> = Some(&[ Param::positional_only("owner"), Param::positional_only("name"), ]); fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + if !args.kwargs.is_empty() { + return Err(vm + .new_type_error("__set_name__() takes no keyword arguments") + .into()); + } let [owner, name]: [PyObjectRef; 2] = core::mem::take(&mut args.args) .try_into() @@ -99,6 +107,11 @@ impl GetDescriptor for PyProperty { } impl PyProperty { + fn set_property_name(&self, name: Option) { + // The replaced name can run a finalizer that accesses this property. + let _old = core::mem::replace(&mut *self.name.write(), name); + } + // Helper method to get property name // Returns the name if available, None if not found, or propagates errors fn get_property_name(&self, vm: &VirtualMachine) -> PyResult> { @@ -113,18 +126,7 @@ impl PyProperty { return Ok(None); }; - match getter.get_attr("__name__", vm) { - Ok(name) => Ok(Some(name)), - Err(e) => { - // If it's an AttributeError from the getter, return None - // Otherwise, propagate the original exception (e.g., RuntimeError) - if e.class().is(vm.ctx.exceptions.attribute_error) { - Ok(None) - } else { - Err(e) - } - } - } + vm.get_attribute_opt(&getter, "__name__") } pub(crate) fn get_fget(&self) -> Option { @@ -152,41 +154,32 @@ impl PyProperty { new_setter: Option, new_deleter: Option, vm: &VirtualMachine, - ) -> PyResult> { - // Determine doc based on getter_doc flag and whether we're updating the getter - let doc = if zelf.getter_doc.load(Ordering::Relaxed) && new_getter.is_some() { - // If the original property uses getter doc and we have a new getter, - // pass Py_None to let __init__ get the doc from the new getter - Some(vm.ctx.none()) - } else if zelf.getter_doc.load(Ordering::Relaxed) { - // If original used getter_doc but we're not changing the getter, - // pass None to let init get doc from existing getter - Some(vm.ctx.none()) + ) -> PyResult { + let getter = new_getter.or_else(|| zelf.get_fget()); + let setter = new_setter.or_else(|| zelf.get_fset()); + let deleter = new_deleter.or_else(|| zelf.get_fdel()); + let doc = if zelf.getter_doc.load(Ordering::Relaxed) && getter.is_some() { + None } else { - // Otherwise use the existing doc zelf.doc_getter() }; - - // Create property args with updated values - let args = PropertyArgs { - fget: new_getter.or_else(|| zelf.get_fget()), - fset: new_setter.or_else(|| zelf.get_fset()), - fdel: new_deleter.or_else(|| zelf.get_fdel()), - doc, - }; - - // Create new property using py_new and init - let new_prop = Self::slot_new(zelf.class().to_owned(), FuncArgs::default(), vm)?; - let new_prop_ref = new_prop.downcast::().unwrap(); - Self::init(&new_prop_ref, args, vm)?; - - // Copy the name if it exists - let value = zelf.name.read().clone(); - if let Some(name) = value { - *new_prop_ref.name.write() = Some(name); + let new_prop = zelf.class().as_object().call( + ( + getter.unwrap_or_else(|| vm.ctx.none()), + setter.unwrap_or_else(|| vm.ctx.none()), + deleter.unwrap_or_else(|| vm.ctx.none()), + doc.unwrap_or_else(|| vm.ctx.none()), + ), + vm, + )?; + + // A subclass constructor may return an unrelated object. Read the old + // name after that call, since the constructor can change it. + if let Some(property) = new_prop.downcast_ref::() { + let name = zelf.name.read().clone(); + property.set_property_name(name); } - - Ok(new_prop_ref) + Ok(new_prop) } // Helper method to format property error messages @@ -217,10 +210,7 @@ impl PyProperty { } } -#[pyclass( - with(Constructor, Initializer, GetDescriptor), - flags(BASETYPE, HAS_WEAKREF) -)] +#[pyclass(with(Constructor, Initializer, GetDescriptor), flags(BASETYPE))] impl Py { // Descriptor methods @@ -256,22 +246,25 @@ impl Py { } } - #[pygetset(name = "__name__")] - fn name_getter(&self, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __name__(&self, vm: &VirtualMachine) -> PyResult { match self.get_property_name(vm)? { Some(name) => Ok(name), None => Err(vm.new_attribute_error("'property' object has no attribute '__name__'")), } } - #[pygetset(name = "__name__", setter)] - fn name_setter(&self, value: PyObjectRef) { - *self.name.write() = Some(value); + #[pygetset(setter)] + fn set___name__(&self, value: PySetterValue) { + self.set_property_name(match value { + PySetterValue::Assign(value) => Some(value), + PySetterValue::Delete => None, + }); } #[pymethod] fn __set_name__(&self, SetNameArgs { name, .. }: SetNameArgs) { - *self.name.write() = Some(name); + self.set_property_name(Some(name)); } #[pymethod] @@ -279,7 +272,7 @@ impl Py { zelf: PyRef, object: Option, vm: &VirtualMachine, - ) -> PyResult> { + ) -> PyResult { PyProperty::clone_property_with(&zelf, object, None, None, vm) } @@ -288,7 +281,7 @@ impl Py { zelf: PyRef, object: Option, vm: &VirtualMachine, - ) -> PyResult> { + ) -> PyResult { PyProperty::clone_property_with(&zelf, None, object, None, vm) } @@ -297,54 +290,36 @@ impl Py { zelf: PyRef, object: Option, vm: &VirtualMachine, - ) -> PyResult> { + ) -> PyResult { PyProperty::clone_property_with(&zelf, None, None, object, vm) } #[pygetset] fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyResult { - // Helper to check if a method is abstract - let is_abstract = |method: &PyObject| -> PyResult { - match method.get_attr("__isabstractmethod__", vm) { - Ok(isabstract) => isabstract.try_to_bool(vm), - Err(_) => Ok(false), - } - }; - // Clone and release lock before calling Python code to prevent deadlock // Check getter if let Some(getter) = self.getter.load_owned() - && is_abstract(&getter)? + && getter.is_abstract(vm)? { return Ok(vm.ctx.new_bool(true).into()); } // Check setter if let Some(setter) = self.setter.load_owned() - && is_abstract(&setter)? + && setter.is_abstract(vm)? { return Ok(vm.ctx.new_bool(true).into()); } // Check deleter if let Some(deleter) = self.deleter.load_owned() - && is_abstract(&deleter)? + && deleter.is_abstract(vm)? { return Ok(vm.ctx.new_bool(true).into()); } Ok(vm.ctx.new_bool(false).into()) } - - #[pygetset(setter)] - fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - // Clone and release lock before calling Python code to prevent deadlock - let maybe_getter = self.getter.load_owned(); - if let Some(getter) = maybe_getter { - getter.set_attr("__isabstractmethod__", value, vm)?; - } - Ok(()) - } } impl Constructor for PyProperty { @@ -366,52 +341,54 @@ impl Initializer for PyProperty { type Args = PropertyArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - // Set doc and getter_doc flag - let mut getter_doc = false; - - // Helper to get doc from getter - let get_getter_doc = |fget: &PyObject| -> Option { - fget.get_attr("__doc__", vm) - .ok() - .filter(|doc| !vm.is_none(doc)) - }; - - let doc = match args.doc { - Some(doc) if !vm.is_none(&doc) => Some(doc), - _ => { - // No explicit doc or doc is None, try to get from getter - args.fget.as_ref().and_then(|fget| { - get_getter_doc(fget).inspect(|_| { - getter_doc = true; - }) - }) - } + let getter = args.fget.as_ref().filter(|value| !vm.is_none(value)); + let setter = args.fset.as_ref().filter(|value| !vm.is_none(value)); + let deleter = args.fdel.as_ref().filter(|value| !vm.is_none(value)); + + // Publish each field before releasing its old owner. Finalizers can + // reenter and observe the same partially initialized state as CPython. + drop(zelf.getter.store(getter.cloned())); + drop(zelf.setter.store(setter.cloned())); + drop(zelf.deleter.store(deleter.cloned())); + drop(zelf.doc.store(None)); + zelf.set_property_name(None); + zelf.getter_doc.store(false, Ordering::Relaxed); + + let doc = match args + .doc + .as_ref() + .filter(|value| !vm.is_none(value)) + .cloned() + { + Some(doc) => Some(doc), + None => match getter { + Some(getter) => { + let doc = vm + .get_attribute_opt(getter, "__doc__")? + .filter(|value| !vm.is_none(value)); + if doc.is_some() { + zelf.getter_doc.store(true, Ordering::Relaxed); + } + doc + } + None => None, + }, }; - // Check if this is a property subclass - let is_exact_property = zelf.class().is(vm.ctx.types.property_type); - - if is_exact_property { - // For exact property type, store doc in the field - zelf.doc.store(doc); + if zelf.class().is(vm.ctx.types.property_type) { + drop(zelf.doc.store(doc)); } else { - // For property subclass, set __doc__ as an attribute - let doc_to_set = doc.unwrap_or_else(|| vm.ctx.none()); - match zelf.as_object().set_attr("__doc__", doc_to_set, vm) { + // Subclasses may route this through an arbitrary descriptor. + let doc = doc.unwrap_or_else(|| vm.ctx.none()); + match zelf.as_object().set_attr("__doc__", doc, vm) { Ok(()) => {} - Err(e) if !getter_doc && e.class().is(vm.ctx.exceptions.attribute_error) => { - // Silently ignore AttributeError for backwards compatibility - // (only when not using getter_doc) - } + Err(e) + if !zelf.getter_doc.load(Ordering::Relaxed) + && e.fast_isinstance(vm.ctx.exceptions.attribute_error) => {} Err(e) => return Err(e), } } - zelf.getter.store(args.fget); - zelf.setter.store(args.fset); - zelf.deleter.store(args.fdel); - zelf.getter_doc.store(getter_doc, Ordering::Relaxed); - Ok(()) } } diff --git a/crates/vm/src/builtins/range.rs b/crates/vm/src/builtins/range.rs index e8d2c30dbce..680d8e2478c 100644 --- a/crates/vm/src/builtins/range.rs +++ b/crates/vm/src/builtins/range.rs @@ -2,7 +2,7 @@ use super::{ PyGenericAlias, PyInt, PyIntRef, PySlice, PyTupleRef, PyType, PyTypeRef, builtins_iter, tuple::tuple_hash, }; -use crate::common::lock::LazyLock; +use crate::common::lock::{LazyLock, PyMutex}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, atomic_func, @@ -16,51 +16,13 @@ use crate::{ }, }; use core::cell::Cell; -use core::cmp::max; +use core::ffi::c_long; use core::ptr::NonNull; use crossbeam_utils::atomic::AtomicCell; use malachite_bigint::{BigInt, Sign}; use num_integer::Integer; use num_traits::{One, Signed, ToPrimitive, Zero}; -// Search flag passed to iter_search -enum SearchType { - Count, - Contains, - Index, -} - -#[inline] -fn iter_search( - obj: &PyObject, - item: &PyObject, - flag: SearchType, - vm: &VirtualMachine, -) -> PyResult { - let mut count = 0; - let iter = obj.get_iter(vm)?; - for element in iter.iter::(vm)? { - if vm.bool_eq(item, &*element?)? { - match flag { - SearchType::Index => return Ok(count), - SearchType::Contains => return Ok(1), - SearchType::Count => count += 1, - } - } - } - match flag { - SearchType::Count => Ok(count), - SearchType::Contains => Ok(0), - SearchType::Index => Err(vm.new_value_error(format!( - "{} not in range", - item.repr(vm) - .as_ref() - .map_or_else(|_| "value".as_ref(), |s| s.as_wtf8()) - .to_owned() - ))), - } -} - #[pyclass(module = false, name = "range")] #[derive(Debug, Clone)] pub struct PyRange { @@ -140,6 +102,11 @@ impl PyRange { } } + fn contains_int(&self, value: &BigInt) -> bool { + self.offset(value) + .is_some_and(|offset| offset.is_multiple_of(self.step.as_bigint())) + } + #[inline] #[must_use] pub fn is_empty(&self) -> bool { @@ -208,6 +175,61 @@ impl PyRange { Sign::NoSign => unreachable!(), } } + + fn fast_iterator(&self, length: &BigInt, reverse: bool) -> Option { + // CPython uses C long, which can be narrower than isize on Windows. + let start = c_long::try_from(self.start.as_bigint()).ok()?; + let stop = c_long::try_from(self.stop.as_bigint()).ok()?; + let step = c_long::try_from(self.step.as_bigint()).ok()?; + let length = c_long::try_from(length).ok()?; + let (start, step) = if reverse { + let reverse_step = step.checked_neg()?; + let reverse_stop = start.checked_sub(step)?; + // The product may overflow even though the reversed start fits. + ( + reverse_stop.wrapping_add(length.wrapping_mul(step)), + reverse_step, + ) + } else { + if length != 0 { + // Reserve space for the exhausted position, as CPython does. + // Its conservative check uses stop, not the final item. + if step > 0 { + stop.checked_add(step - 1)?; + } else { + stop.checked_add(step + 1)?; + } + } + (start, step) + }; + Some(PyRangeIterator { + index: AtomicCell::new(0), + start: start as isize, + step: step as isize, + length: length as usize, + }) + } + + fn iterator(&self, reverse: bool, vm: &VirtualMachine) -> PyObjectRef { + let length = self.compute_length(); + if let Some(iter) = self.fast_iterator(&length, reverse) { + return iter.into_pyobject(vm); + } + let start = self.start.as_bigint(); + let step = self.step.as_bigint(); + let (start, step) = if reverse { + (start + (&length - 1) * step, -step) + } else { + (start.clone(), step.clone()) + }; + PyLongRangeIterator { + index: PyMutex::new(BigInt::zero()), + start, + step, + length, + } + .into_pyobject(vm) + } } // pub fn get_value(obj: &PyObject) -> PyRange { @@ -221,34 +243,6 @@ pub(crate) fn init(context: &'static Context) { } impl PyRange { - fn new(cls: PyTypeRef, stop: ArgIndex, vm: &VirtualMachine) -> PyResult> { - Self { - start: vm.ctx.new_pyref(0), - stop: stop.into(), - step: vm.ctx.new_pyref(1), - } - .into_ref_with_type(vm, cls) - } - - fn new_from( - cls: PyTypeRef, - start: &PyObject, - stop: &PyObject, - step: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult> { - let step = step.map_or_else(|| vm.ctx.new_int(1), |step| step.into()); - if step.as_bigint().is_zero() { - return Err(vm.new_value_error("range() arg 3 must not be zero")); - } - Self { - start: start.try_index(vm)?, - stop: stop.try_index(vm)?, - step, - } - .into_ref_with_type(vm, cls) - } - fn __len__(&self) -> BigInt { self.compute_length() } @@ -308,81 +302,50 @@ impl PyRange {} #[pyclass] impl Py { - fn contains_inner(&self, needle: &PyObject, vm: &VirtualMachine) -> bool { - // Only accept ints, not subclasses. - if let Some(int) = needle.downcast_ref_if_exact::(vm) { - match self.offset(int.as_bigint()) { - Some(ref offset) => offset.is_multiple_of(self.step.as_bigint()), - None => false, - } + fn search_int<'a>(needle: &'a PyObject, vm: &VirtualMachine) -> Option<&'a Py> { + // Other int subclasses may override equality and must be iterated. + if needle.class().is(vm.ctx.types.bool_type) { + needle.downcast_ref::() } else { - iter_search(self.as_object(), needle, SearchType::Contains, vm).unwrap_or(0) != 0 + needle.downcast_ref_if_exact::(vm) } } - fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> bool { - self.contains_inner(needle, vm) + fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + if let Some(int) = Self::search_int(needle, vm) { + Ok(self.contains_int(int.as_bigint())) + } else { + self.as_object() + .sequence_unchecked() + .iter_contains(needle, vm) + } } #[pymethod] fn index(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult { - if let Ok(int) = object.clone().downcast::() { - match self.index_of(int.as_bigint()) { - Some(idx) => Ok(idx), - None => Err(vm.new_value_error(format!("{int} is not in range"))), - } + if let Some(int) = Self::search_int(&object, vm) { + self.index_of(int.as_bigint()) + .ok_or_else(|| vm.new_value_error("range.index(x): x not in range")) } else { - // Fallback to iteration. - Ok(BigInt::from_bytes_be( - Sign::Plus, - &iter_search(self.as_object(), &object, SearchType::Index, vm)?.to_be_bytes(), - )) + self.as_object() + .sequence_unchecked() + .index(&object, vm) + .map(BigInt::from) } } #[pymethod] fn count(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult { - if let Ok(int) = object.clone().downcast::() { - Ok(usize::from(self.index_of(int.as_bigint()).is_some())) + if let Some(int) = Self::search_int(&object, vm) { + Ok(usize::from(self.contains_int(int.as_bigint()))) } else { - // Dealing with classes who might compare equal with ints in their - // __eq__, slow search. - iter_search(self.as_object(), &object, SearchType::Count, vm) + self.as_object().sequence_unchecked().count(&object, vm) } } #[pymethod] fn __reversed__(&self, vm: &VirtualMachine) -> PyObjectRef { - let start = self.start.as_bigint(); - let step = self.step.as_bigint(); - - // Use CPython calculation for this: - let length = self.__len__(); - let new_stop = start - step; - let start = &new_stop + length.clone() * step; - let step = -step; - - if let (Some(start), Some(step), Some(_)) = - (start.to_isize(), step.to_isize(), new_stop.to_isize()) - { - PyRangeIterator { - index: AtomicCell::new(0), - start, - step, - // Cannot fail. If start, stop and step all successfully convert to isize, then result of zelf.len will - // always fit in a usize. - length: length.to_usize().unwrap_or(0), - } - .into_pyobject(vm) - } else { - PyLongRangeIterator { - index: AtomicCell::new(0), - start, - step, - length, - } - .into_pyobject(vm) - } + self.iterator(true, vm) } #[pymethod] @@ -397,18 +360,38 @@ impl Py { #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let range = if args.args.is_empty() { - return Err(vm.new_arity_type_error(PyRange::NAME, 1..=3, 0)); - } else if args.args.len() == 1 { - let stop = args.bind_for(vm, PyRange::NAME)?; - PyRange::new(cls, stop, vm) + if let Some(error) = args.check_kwargs_empty_for(vm, PyRange::NAME) { + return Err(error); + } + let (first, stop, step): ( + PyObjectRef, + OptionalArg, + OptionalArg, + ) = args.bind_for(vm, PyRange::NAME)?; + // Bind objects before calling __index__, then convert in argument order. + let index = |object: &PyObjectRef| { + ArgIndex::try_from_object(vm, object.clone()).map(ArgIndex::into_int_ref) + }; + let first_index = index(&first)?; + let (start, stop_index) = if let OptionalArg::Present(stop) = &stop { + (first_index, index(stop)?) } else { - let (start, stop, step): (PyObjectRef, PyObjectRef, OptionalArg) = - args.bind_for(vm, PyRange::NAME)?; - PyRange::new_from(cls, &start, &stop, step, vm) - }?; - - Ok(range.into()) + (vm.ctx.new_int(0), first_index) + }; + let step_index = match &step { + OptionalArg::Present(step) => index(step)?, + OptionalArg::Missing => vm.ctx.new_int(1), + }; + if step_index.as_bigint().is_zero() { + return Err(vm.new_value_error("range() arg 3 must not be zero")); + } + PyRange { + start, + stop: stop_index, + step: step_index, + } + .into_ref_with_type(vm, cls) + .map(Into::into) } } @@ -447,7 +430,7 @@ impl AsSequence for PyRange { .ok_or_else(|| vm.new_index_error("index out of range")) }), contains: atomic_func!(|seq, needle, vm| { - Ok(PyRange::sequence_downcast(seq).contains_inner(needle, vm)) + PyRange::sequence_downcast(seq).__contains__(needle, vm) }), ..PySequenceMethods::NOT_IMPLEMENTED }); @@ -521,36 +504,7 @@ impl Comparable for PyRange { impl Iterable for PyRange { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - let (start, stop, step, length) = ( - zelf.start.as_bigint(), - zelf.stop.as_bigint(), - zelf.step.as_bigint(), - zelf.__len__(), - ); - if let (Some(start), Some(step), Some(_), Some(_)) = ( - start.to_isize(), - step.to_isize(), - stop.to_isize(), - (start + step).to_isize(), - ) { - Ok(PyRangeIterator { - index: AtomicCell::new(0), - start, - step, - // Cannot fail. If start, stop and step all successfully convert to isize, then result of zelf.len will - // always fit in a usize. - length: length.to_usize().unwrap_or(0), - } - .into_pyobject(vm)) - } else { - Ok(PyLongRangeIterator { - index: AtomicCell::new(0), - start: start.clone(), - step: step.clone(), - length, - } - .into_pyobject(vm)) - } + Ok(zelf.iterator(false, vm)) } } @@ -566,18 +520,11 @@ impl Representable for PyRange { } } -// Semantically, this is the same as the previous representation. -// -// Unfortunately, since AtomicCell requires a Copy type, no BigInt implementations can -// generally be used. As such, usize::MAX is the upper bound on number of elements (length) -// the range can contain in RustPython. -// -// This doesn't preclude the range from containing large values, since start and step -// can be BigInts, we can store any arbitrary range of values. +// Long ranges need arbitrary-precision positions as well as values. #[pyclass(module = false, name = "longrange_iterator")] #[derive(Debug)] pub(crate) struct PyLongRangeIterator { - index: AtomicCell, + index: PyMutex, start: BigInt, step: BigInt, length: BigInt, @@ -594,7 +541,7 @@ impl PyPayload for PyLongRangeIterator { impl Py { #[pymethod] fn __length_hint__(&self) -> BigInt { - let index = BigInt::from(self.index.load()); + let index = self.index.lock().clone(); if index < self.length { self.length.clone() - index } else { @@ -604,17 +551,29 @@ impl Py { #[pymethod] fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.index.store(range_state(&self.length, &state, vm)?); + let Some(state) = state.downcast_ref_if_exact::(vm) else { + return Err(vm.new_type_error(format!( + "state must be an int, not {}", + state.class().fully_qualified_name(vm)? + ))); + }; + if state.as_bigint().is_positive() { + let mut index = self.index.lock(); + let remaining = &self.length - &*index; + // State skips items from the current position; it cannot rewind. + *index += state.as_bigint().min(&remaining); + } Ok(()) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { + let index = self.index.lock().clone(); range_iter_reduce( self.start.clone(), self.length.clone(), self.step.clone(), - self.index.load(), + index, vm, ) } @@ -623,22 +582,22 @@ impl Py { impl SelfIter for PyLongRangeIterator {} impl IterNext for PyLongRangeIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - // TODO: In pathological case (index == usize::MAX) this can wrap around - // (since fetch_add wraps). This would result in the iterator spinning again - // from the beginning. - let index = BigInt::from(zelf.index.fetch_add(1)); - let r = if index < zelf.length { - let value = zelf.start.clone() + index * zelf.step.clone(); - PyIterReturn::Return(vm.ctx.new_int(value).into()) - } else { - PyIterReturn::StopIteration(None) + let index = { + let mut index = zelf.index.lock(); + if *index >= zelf.length { + return Ok(PyIterReturn::StopIteration(None)); + } + let current = index.clone(); + *index += 1; + current }; - Ok(r) + let value = zelf.start.clone() + index * zelf.step.clone(); + Ok(PyIterReturn::Return(vm.ctx.new_int(value).into())) } } -// When start, stop, step are isize, we can use a faster more compact representation -// that only operates using isize to track values. +// The compact iterator stores isize values for the FOR_ITER specialization. +// Creation still checks the platform's C long bounds required by CPython. #[pyclass(module = false, name = "range_iterator")] #[derive(Debug)] pub(crate) struct PyRangeIterator { @@ -664,9 +623,18 @@ impl Py { } #[pymethod] - fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.index - .store(range_state(&BigInt::from(self.length), &object, vm)?); + fn __setstate__(&self, state: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + // Convert before updating the index: __index__ can advance this iterator. + // Keep the original state alive until after the update. + let index = ArgIndex::try_from_object(vm, state.clone())?; + let advance = c_long::try_from(index.as_ref().as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))? + .max(0) as usize; + let _ = self + .index + .fetch_update(|index| Some(index.saturating_add(advance).min(self.length))); + drop(index); + drop(state); Ok(()) } @@ -676,7 +644,7 @@ impl Py { BigInt::from(self.start), BigInt::from(self.length), BigInt::from(self.step), - self.index.load(), + BigInt::from(self.index.load()), vm, ) } @@ -686,12 +654,14 @@ impl PyRangeIterator { /// Fast path for FOR_ITER specialization. Returns the next isize value /// without allocating PyInt or PyIterReturn. pub(crate) fn fast_next(&self) -> Option { - let index = self.index.fetch_add(1); - if index < self.length { - Some(self.start + (index as isize) * self.step) - } else { - None - } + let index = self + .index + .fetch_update(|index| (index < self.length).then(|| index + 1)) + .ok()?; + Some( + self.start + .wrapping_add((index as isize).wrapping_mul(self.step)), + ) } } @@ -710,13 +680,12 @@ fn range_iter_reduce( start: BigInt, length: BigInt, step: BigInt, - index: usize, + index: BigInt, vm: &VirtualMachine, ) -> PyResult { let iter = builtins_iter(vm)?; - // CPython pickles the remaining range with a None state. next() increments - // the index unconditionally, so clamp it to length before rebasing start. - let index = BigInt::from(index).min(length.clone()); + // CPython pickles the remaining range with a None state. + let index = index.min(length.clone()); let stop = start.clone() + length * step.clone(); let start = start + index * step.clone(); let range = PyRange { @@ -727,20 +696,6 @@ fn range_iter_reduce( Ok(vm.new_tuple((iter, (range,), vm.ctx.none()))) } -// Silently clips state (i.e index) in range [0, usize::MAX]. -fn range_state(length: &BigInt, state: &PyObject, vm: &VirtualMachine) -> PyResult { - if let Some(i) = state.downcast_ref::() { - let mut index = i.as_bigint(); - let max_usize = BigInt::from(usize::MAX); - if index > length { - index = max(length, &max_usize); - } - Ok(index.to_usize().unwrap_or(0)) - } else { - Err(vm.new_type_error("an integer is required.")) - } -} - pub(crate) enum RangeIndex { Int(PyIntRef), Slice(PyRef), @@ -752,12 +707,60 @@ impl TryFromObject for RangeIndex { i @ PyInt => Ok(Self::Int(i)), s @ PySlice => Ok(Self::Slice(s)), obj => { - let val = obj.try_index(vm).map_err(|_| vm.new_type_error(format!( - "sequence indices be integers or slices or classes that override __index__ operator, not '{}'", - obj.class().name() - )))?; + let val = obj.try_index_opt(vm).ok_or_else(|| { + let name = obj.class().slot_name(); + vm.new_type_error(format!( + "range indices must be integers or slices, not {}", + &name[..name.floor_char_boundary(200.min(name.len()))] + )) + })??; Ok(Self::Int(val)) } }) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn long_iterator_preserves_arbitrary_precision_state() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let length: BigInt = BigInt::one() << 100; + let iter = PyLongRangeIterator { + index: PyMutex::new(BigInt::zero()), + start: BigInt::zero(), + step: BigInt::one(), + length: length.clone(), + } + .into_ref(&vm.ctx); + let state: BigInt = &length - 1; + iter.__setstate__(vm.ctx.new_bigint(&state).into(), vm) + .unwrap(); + assert_eq!(iter.__length_hint__(), BigInt::one()); + let PyIterReturn::Return(value) = PyLongRangeIterator::next(&iter, vm).unwrap() else { + panic!("wide iterator state was lost"); + }; + assert_eq!(value.downcast_ref::().unwrap().as_bigint(), &state); + for _ in 0..2 { + assert!(matches!( + PyLongRangeIterator::next(&iter, vm).unwrap(), + PyIterReturn::StopIteration(None) + )); + } + }); + } + + #[test] + fn exhausted_fast_iterator_does_not_wrap_its_index() { + let iter = PyRangeIterator { + index: AtomicCell::new(usize::MAX), + start: 0, + step: 1, + length: usize::MAX, + }; + assert_eq!(iter.fast_next(), None); + assert_eq!(iter.fast_next(), None); + } +} diff --git a/crates/vm/src/builtins/sentinel.rs b/crates/vm/src/builtins/sentinel.rs new file mode 100644 index 00000000000..7f9e7d38d29 --- /dev/null +++ b/crates/vm/src/builtins/sentinel.rs @@ -0,0 +1,118 @@ +use super::{PyStrRef, PyType, union_}; +use crate::{ + Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + class::PyClassImpl, + object::{PyAtomicRef, Traverse, TraverseFn}, + protocol::PyNumberMethods, + types::{AsNumber, Constructor, Representable}, +}; + +/// Create a unique sentinel object with the given name. +#[pyclass(module = false, name = "sentinel", traverse = "manual")] +#[derive(Debug)] +pub struct PySentinel { + #[pymember(name = "__name__", type = "object_ex")] + name: PyStrRef, + #[pymember(name = "__module__", type = "object_ex", writable)] + module: PyAtomicRef>, + repr: Option, +} + +// SAFETY: Visit each owned Python reference once, without cloning it. +unsafe impl Traverse for PySentinel { + fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { + self.name.traverse(tracer_fn); + self.module.traverse(tracer_fn); + self.repr.traverse(tracer_fn); + } + + fn clear(&mut self, out: &mut Vec) { + // String subclasses may own references back to this sentinel. + let name = core::mem::replace(&mut self.name, Context::genesis().empty_str.to_owned()); + out.push(name.into()); + if let Some(module) = self.module.store(None) { + out.push(module); + } + if let Some(repr) = self.repr.take() { + out.push(repr.into()); + } + } +} + +impl PyPayload for PySentinel { + #[inline] + fn class(ctx: &Context) -> &'static Py { + ctx.types.sentinel_type + } +} + +#[derive(FromArgs)] +pub struct SentinelArgs { + #[pyarg(positional, error_msg = "sentinel() argument 1 must be str")] + name: PyStrRef, + #[pyarg( + named, + optional, + error_msg = "sentinel() argument 'repr' must be str or None" + )] + repr: Option, +} + +impl Constructor for PySentinel { + type Args = SentinelArgs; + + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + let module = if let Some(frame) = vm.current_frame() + && let Some(function) = frame.iframe().func_obj() + { + // Use the module captured by the caller function, including the + // synthetic functions used for module, eval, and exec code. + function.get_attr(identifier!(vm, __module__), vm)? + } else { + vm.ctx.none() + }; + Ok(Self { + name: args.name, + module: PyAtomicRef::from(Some(module)), + repr: args.repr, + }) + } +} + +#[pyclass(with(Constructor, Representable, AsNumber), flags(HAVE_GC))] +impl PySentinel { + #[pymethod] + fn __copy__(zelf: PyRef) -> PyRef { + zelf + } + + #[pymethod] + fn __deepcopy__(zelf: PyRef, _object: PyObjectRef) -> PyRef { + zelf + } + + #[pymethod] + fn __reduce__(zelf: &Py) -> PyStrRef { + zelf.name.clone() + } +} + +impl Representable for PySentinel { + fn repr(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + Ok(zelf.repr.as_ref().unwrap_or(&zelf.name).clone()) + } +} + +impl AsNumber for PySentinel { + fn as_number() -> &'static PyNumberMethods { + static AS_NUMBER: PyNumberMethods = PyNumberMethods { + or: Some(|a, b, vm| union_::or_op(a.to_owned(), b.to_owned(), vm)), + ..PyNumberMethods::NOT_IMPLEMENTED + }; + &AS_NUMBER + } +} + +pub(crate) fn init(context: &'static Context) { + PySentinel::extend_class(context, context.types.sentinel_type); +} diff --git a/crates/vm/src/builtins/set.rs b/crates/vm/src/builtins/set.rs index e3e8ade64c4..81c0ee0628c 100644 --- a/crates/vm/src/builtins/set.rs +++ b/crates/vm/src/builtins/set.rs @@ -2,13 +2,13 @@ * Builtin set type with a sequence of unique items. */ use super::{ - IterStatus, PositionIterInternal, PyDict, PyDictRef, PyGenericAlias, PyTupleRef, PyType, - PyTypeRef, builtins_iter, locked_step, + IterStatus, PositionIterInternal, PyAnyDict, PyBaseExceptionRef, PyDict, PyGenericAlias, + PyTupleRef, PyType, PyTypeRef, builtins_iter, locked_step, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, atomic_func, - class::{PyClassDef, PyClassImpl}, + class::{PyClassDef, PyClassImpl, StaticType}, common::{ ascii, hash::PyHash, @@ -16,12 +16,13 @@ use crate::{ rc::PyRc, wtf8::Wtf8Buf, }, - convert::ToPyResult, + convert::{ToPyResult, TransmuteFromObject}, dict_inner::{self, DictSize}, function::{ ArgIterable, FuncArgs, NameOthers, OptionalArg, PosArgs, PyArithmeticValue, PyComparisonValue, }, + object::{Traverse, TraverseFn}, protocol::{PyIterReturn, PyNumberMethods, PySequenceMethods}, recursion::ReprGuard, types::AsNumber, @@ -40,54 +41,89 @@ use rustpython_common::{ pub(crate) type SetContentType = dict_inner::Dict<()>; -#[pyclass(module = false, name = "set", unhashable = true, traverse)] +#[pyclass(module = false, name = "set", unhashable = true, traverse = "manual")] #[derive(Default)] pub struct PySet { pub(super) inner: PySetInner, } +// SAFETY: the inner table visits each exclusively owned reference once. +unsafe impl Traverse for PySet { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.inner.traverse(tracer); + } + + fn clear(&mut self, out: &mut Vec) { + Traverse::clear(&mut self.inner, out); + } +} + impl PySet { + /// Freeze a working set without hashing or comparing its keys again. + pub(super) fn into_frozen(self) -> PyFrozenSet { + PyFrozenSet { + // Working set tables can have mutable aliases; copy the stored + // entries so the result remains immutable after those aliases run. + inner: self.inner.copy(), + ..Default::default() + } + } + #[deprecated(note = "Use `PySet::default().into_ref(ctx)` instead")] pub fn new_ref(ctx: &Context) -> PyRef { Self::default().into_ref(ctx) } + pub(crate) fn marshal_len(&self) -> usize { + self.inner.len() + } + #[must_use] - pub fn elements(&self) -> Vec { - self.inner.elements() + pub fn next_entry(&self, position: usize) -> Option<(usize, PyObjectRef)> { + self.inner + .content + .next_entry(position) + .map(|(next, item, ())| (next, item)) } - fn fold_op( - &self, - others: impl core::iter::Iterator, - op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult, - vm: &VirtualMachine, - ) -> PyResult { - Ok(Self { - inner: self.inner.fold_op(others, op, vm)?, - }) + #[must_use] + pub fn elements(&self) -> Vec { + self.inner.elements() } - fn op( + fn union_multi( &self, - other: AnySet, - op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult { Ok(Self { - inner: self - .inner - .fold_op(core::iter::once(other.into_iterable(vm)?), op, vm)?, + inner: self.inner.union_multi(others, vm)?, }) } } -#[pyclass(module = false, name = "frozenset", unhashable = true)] +#[pyclass( + module = false, + name = "frozenset", + unhashable = true, + traverse = "manual" +)] pub struct PyFrozenSet { inner: PySetInner, hash: PyAtomic, } +// SAFETY: the inner table visits each exclusively owned reference once. +unsafe impl Traverse for PyFrozenSet { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.inner.traverse(tracer); + } + + fn clear(&mut self, out: &mut Vec) { + Traverse::clear(&mut self.inner, out); + } +} + impl Default for PyFrozenSet { fn default() -> Self { Self { @@ -118,28 +154,13 @@ impl PyFrozenSet { self.inner.elements() } - fn fold_op( - &self, - others: impl core::iter::Iterator, - op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult, - vm: &VirtualMachine, - ) -> PyResult { - Ok(Self { - inner: self.inner.fold_op(others, op, vm)?, - ..Default::default() - }) - } - - fn op( + fn union_multi( &self, - other: AnySet, - op: fn(&PySetInner, ArgIterable, &VirtualMachine) -> PyResult, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult { Ok(Self { - inner: self - .inner - .fold_op(core::iter::once(other.into_iterable(vm)?), op, vm)?, + inner: self.inner.union_multi(others, vm)?, ..Default::default() }) } @@ -161,6 +182,9 @@ impl fmt::Debug for PyFrozenSet { } impl PyPayload for PySet { + // Ordinary destruction can release the table directly after untracking. + const CLEAR_ON_DEALLOC: bool = false; + #[inline] fn class(ctx: &Context) -> &'static Py { ctx.types.set_type @@ -168,6 +192,22 @@ impl PyPayload for PySet { } impl PyPayload for PyFrozenSet { + const CLEAR_ON_DEALLOC: bool = false; + + fn needs_gc(&self, class: &Py) -> bool { + // Subclasses can acquire instance state. Shared working tables may + // still be mutated by another owner, so keep those tracked as well. + if !class.is(Self::static_type()) || PyRc::strong_count(&self.inner.content) != 1 { + return true; + } + self.inner.content.any_key(|key| { + // Exact untracked frozensets are immutable and were checked at + // allocation. Other untracked objects may later acquire GC edges. + key.gc_may_have_edges() + && !(key.class().is(Self::static_type()) && !key.is_gc_tracked()) + }) + } + #[inline] fn class(ctx: &Context) -> &'static Py { ctx.types.frozenset_type @@ -179,29 +219,34 @@ pub(super) struct PySetInner { content: PyRc, } -unsafe impl crate::object::Traverse for PySetInner { - fn traverse(&self, tracer_fn: &mut crate::object::TraverseFn<'_>) { - // FIXME(discord9): Rc means shared ref, so should it be traced? - self.content.traverse(tracer_fn) +// SAFETY: a shared table owns only one reference per entry, regardless of its +// number of owners. Only attribute those edges to an exclusive owner; otherwise +// leave them as external roots rather than subtracting the same edges twice. +unsafe impl Traverse for PySetInner { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + if PyRc::strong_count(&self.content) == 1 { + self.content.traverse(tracer); + } } -} -impl PySetInner { - pub(super) fn from_iter(iter: T, vm: &VirtualMachine) -> PyResult - where - T: IntoIterator>, - { - let set = Self::default(); - for item in iter { - let item = item?; - set.add(&item, vm)?; + fn clear(&mut self, out: &mut Vec) { + if let Some(content) = PyRc::get_mut(&mut self.content) { + // Detach before releasing keys: dropping them may re-enter Python. + out.reserve(content.len()); + out.extend(content.drain_entries().map(|(key, ())| key)); } - Ok(set) } +} +impl PySetInner { /// Build a set from an arbitrary object, reusing stored hashes when the - /// source is a set/frozenset/dict. - fn from_object(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult { + /// source is a set/frozenset/dict/frozendict. + pub(super) fn from_object(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult { + if let Some(source) = extract_set(&iterable) { + // A fresh table can copy resident entries without comparing + // colliding keys or invoking a subclass's iterator. + return Ok(source.copy()); + } let set = Self::default(); set.update_internal(iterable, vm)?; Ok(set) @@ -209,32 +254,42 @@ impl PySetInner { /// Elements of `obj` with their stored hashes, or `None` if `obj` keeps /// none and must be iterated generically. Mirrors the `PyAnySet_Check` / - /// `PyDict_CheckExact` fast paths in CPython's `set_update_internal`. + /// `PyAnyDict_CheckExact` fast paths in CPython's `set_update_internal`. fn cached_hashes(obj: &PyObject, vm: &VirtualMachine) -> Option> { if let Some(set) = extract_set(obj) { Some(set.content.keys_with_hashes()) } else { - obj.downcast_ref_if_exact::(vm) - .map(|dict| dict._as_dict_inner().keys_with_hashes()) + Self::exact_dict(obj, vm).map(|dict| dict._as_dict_inner().keys_with_hashes()) + } + } + + fn exact_dict<'a>(obj: &'a PyObject, vm: &VirtualMachine) -> Option<&'a PyDict> { + if obj.class().is(vm.ctx.types.dict_type) || obj.class().is(vm.ctx.types.frozendict_type) { + PyAnyDict::from_object(obj).map(PyAnyDict::as_dict) + } else { + None } } - fn fold_op( + fn union_multi( &self, - others: impl core::iter::Iterator, - op: fn(&Self, O, &VirtualMachine) -> PyResult, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult { - let mut res = self.copy(); + let res = self.copy(); for other in others { - res = op(&res, other, vm)?; + if extract_set(&other).is_some_and(|other| PyRc::ptr_eq(&self.content, &other.content)) + { + continue; + } + res.update_internal(other, vm)?; } Ok(res) } fn intersection_multi( &self, - mut others: impl core::iter::Iterator, + mut others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult { let Some(other) = others.next() else { @@ -249,7 +304,7 @@ impl PySetInner { fn difference_multi( &self, - mut others: impl core::iter::Iterator, + mut others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult { let Some(other) = others.next() else { @@ -275,19 +330,20 @@ impl PySetInner { } fn contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - let result = self - .retry_op_with_frozenset(needle, vm, |needle, vm| self.content.contains(vm, needle)); - Self::wrap_unhashable_error(result, needle, vm) + let hash = needle.hash(vm).or_else(|exc| { + Self::mutable_set_hash(needle, exc, vm).map_err(|exc| Self::hash_error(needle, exc, vm)) + })?; + self.content.contains(vm, needle, hash) } /// Look up a key whose hash is already known, without a frozenset retry. - fn contains_known_hash( + pub(super) fn contains_known_hash( &self, needle: &PyObject, hash: PyHash, vm: &VirtualMachine, ) -> PyResult { - self.content.contains_known_hash(vm, needle, hash) + self.content.contains(vm, needle, hash) } fn compare(&self, other: &Self, op: PyComparisonOp, vm: &VirtualMachine) -> PyResult { @@ -311,28 +367,17 @@ impl PySetInner { Ok(true) } - pub(super) fn union(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - let set = self.clone(); - if let Some(elements) = Self::cached_hashes(other.as_object(), vm) { - for (item, hash) in elements { - set.add_known_hash(&item, hash, vm)?; - } - return Ok(set); - } - for item in other.iter(vm)? { - let item = item?; - set.add(&item, vm)?; - } - - Ok(set) + pub(super) fn union(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + self.update_internal(other, vm)?; + Ok(self.clone()) } - pub(super) fn intersection(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + pub(super) fn intersection(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { if let Some(other_set) = extract_set(other.as_object()) { return self.intersection_set(other_set, vm); } let set = Self::default(); - for item in other.iter(vm)? { + for item in other.get_iter(vm)?.into_iter::(vm) { let obj = item?; let hash = obj.hash(vm)?; if self.contains_known_hash(&obj, hash, vm)? { @@ -363,7 +408,7 @@ impl PySetInner { Ok(set) } - fn difference_new(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + fn difference_new(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Scanning the left side avoids visiting and retaining a much larger // exclusion collection. Match CPython's comparison direction as well. if let Some(other_set) = extract_set(other.as_object()) { @@ -371,11 +416,11 @@ impl PySetInner { return self .difference_by(|key, hash| other_set.contains_known_hash(key, hash, vm), vm); } - } else if let Some(dict) = other.as_object().downcast_ref_if_exact::(vm) + } else if let Some(dict) = Self::exact_dict(other.as_object(), vm) && self.len() >> 2 <= dict._as_dict_inner().len() { return self.difference_by( - |key, hash| dict._as_dict_inner().contains_known_hash(vm, key, hash), + |key, hash| dict._as_dict_inner().contains(vm, key, hash), vm, ); } @@ -383,7 +428,7 @@ impl PySetInner { } // The dict-view caller supplies a private working table. - pub(super) fn difference(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { + pub(super) fn difference(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { self.difference_update(core::iter::once(other), vm)?; Ok(self.clone()) } @@ -404,58 +449,48 @@ impl PySetInner { pub(super) fn symmetric_difference( &self, - other: ArgIterable, + other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - let new_inner = self.clone(); - - if let Some(elements) = Self::cached_hashes(other.as_object(), vm) { - // the source is already duplicate-free - for (item, hash) in elements { - new_inner - .content - .delete_or_insert_known_hash(vm, &item, hash, ())?; - } - return Ok(new_inner); - } - - // We want to remove duplicates in other - let other_set = Self::from_iter(other.iter(vm)?, vm)?; - - for (item, hash) in other_set.content.keys_with_hashes() { - new_inner - .content - .delete_or_insert_known_hash(vm, &item, hash, ())?; - } - - Ok(new_inner) + // Build the right operand first, so its resident keys receive equality + // comparisons and its iterator can mutate the left operand before use. + let result = match extract_set(&other) { + Some(other) => other.copy(), + None => Self::from_object(other.clone(), vm)?, + }; + result.toggle_entries(self.content.keys_with_hashes(), vm)?; + Ok(result) } - fn issuperset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - if let Some(other_set) = extract_set(other.as_object()) { + fn issuperset(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult { + if let Some(other_set) = extract_set(other) { return self.compare(other_set, PyComparisonOp::Ge, vm); } - for item in other.iter(vm)? { - if !self.contains(&*item?, vm)? { + for item in other.get_iter(vm)?.into_iter::(vm) { + let item = item?; + let hash = Self::key_hash(&item, vm)?; + if !self.contains_known_hash(&item, hash, vm)? { return Ok(false); } } Ok(true) } - fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - if let Some(other_set) = extract_set(other.as_object()) { + fn issubset(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult { + if let Some(other_set) = extract_set(other) { return self.compare(other_set, PyComparisonOp::Le, vm); } - Ok(self.intersection(other, vm)?.len() == self.len()) + // The binding owns the source until after the size comparison. Its + // finalizer must not mutate self between intersection and comparison. + Ok(self.intersection(other.to_owned(), vm)?.len() == self.len()) } - pub(super) fn isdisjoint(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - if let Some(other_set) = extract_set(other.as_object()) { + pub(super) fn isdisjoint(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult { + if let Some(other_set) = extract_set(other) { if core::ptr::eq(self, other_set) { return Ok(self.len() == 0); } - let other_type = other.as_object().class(); + let other_type = other.class(); if other_type.is(vm.ctx.types.set_type) || other_type.is(vm.ctx.types.frozenset_type) { let (target, source) = if self.len() < other_set.len() { (other_set, self) @@ -470,8 +505,10 @@ impl PySetInner { return Ok(true); } } - for item in other.iter(vm)? { - if self.contains(&*item?, vm)? { + for item in other.get_iter(vm)?.into_iter::(vm) { + let item = item?; + let hash = Self::key_hash(&item, vm)?; + if self.contains_known_hash(&item, hash, vm)? { return Ok(false); } } @@ -491,26 +528,43 @@ impl PySetInner { } fn add(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - let result = self.content.insert(vm, item, ()); - Self::wrap_unhashable_error(result, item, vm) + let hash = Self::key_hash(item, vm)?; + self.add_known_hash(item, hash, vm) } /// [`Self::add`] with a known hash. fn add_known_hash(&self, item: &PyObject, hash: PyHash, vm: &VirtualMachine) -> PyResult<()> { - let result = self.content.insert_known_hash(vm, item, hash, ()); - Self::wrap_unhashable_error(result, item, vm) + self.insert_known_hash(item, hash, vm) + } + + /// Insert a key without translating exceptions from its equality callback. + pub(super) fn insert_known_hash( + &self, + item: &PyObject, + hash: PyHash, + vm: &VirtualMachine, + ) -> PyResult<()> { + self.content.insert(vm, item, hash, ()) } fn remove(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - let result = - self.retry_op_with_frozenset(item, vm, |item, vm| self.content.delete(vm, item)); - Self::wrap_unhashable_error(result, item, vm) + if self.discard(item, vm)? { + Ok(()) + } else { + Err(vm.new_key_error(item.to_owned())) + } } fn discard(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult { - let result = self - .retry_op_with_frozenset(item, vm, |item, vm| self.content.delete_if_exists(vm, item)); - Self::wrap_unhashable_error(result, item, vm) + self.discard_key(item, vm).or_else(|exc| { + let hash = Self::mutable_set_hash(item, exc, vm)?; + self.content.delete_if_exists(vm, item, hash) + }) + } + + fn discard_key(&self, item: &PyObject, vm: &VirtualMachine) -> PyResult { + let hash = Self::key_hash(item, vm)?; + self.content.delete_if_exists(vm, item, hash) } fn clear(&self) { @@ -532,15 +586,13 @@ impl PySetInner { } fn update_internal(&self, iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - // check AnySet - if let Ok(any_set) = AnySet::try_from_object(vm, iterable.to_owned()) { + // check set or frozenset + if let Ok(any_set) = PyRef::::try_from_object(vm, iterable.to_owned()) { self.merge_set(any_set, vm) - // check Dict - } else if let Ok(dict) = iterable.to_owned().downcast_exact::(vm) { - self.merge_dict(&dict, vm) + } else if let Some(dict) = Self::exact_dict(&iterable, vm) { + self.merge_dict(dict, vm) } else { - // add iterable that is not AnySet or Dict - for item in iterable.try_into_value::(vm)?.iter(vm)? { + for item in iterable.get_iter(vm)?.into_iter::(vm) { let item = item?; self.add(&item, vm)?; } @@ -548,15 +600,25 @@ impl PySetInner { } } - fn merge_set(&self, any_set: AnySet, vm: &VirtualMachine) -> PyResult<()> { + fn merge_set(&self, any_set: PyRef, vm: &VirtualMachine) -> PyResult<()> { + if PyRc::ptr_eq(&self.content, &any_set.as_inner().content) { + return Ok(()); + } for (item, hash) in any_set.as_inner().content.keys_with_hashes() { self.add_known_hash(&item, hash, vm)?; } Ok(()) } - fn merge_dict(&self, dict: &Py, vm: &VirtualMachine) -> PyResult<()> { - for (key, hash) in dict._as_dict_inner().keys_with_hashes() { + fn merge_dict(&self, dict: &PyDict, vm: &VirtualMachine) -> PyResult<()> { + // Equality between colliding keys can change the source dictionary. + // Match the live _PyDict_Next traversal used by set_update_dict. + let mut position = 0; + while let Some((next_position, key, value, hash)) = + dict._as_dict_inner().next_entry_with_hash(position) + { + position = next_position; + drop(value); self.add_known_hash(&key, hash, vm)?; } Ok(()) @@ -564,7 +626,7 @@ impl PySetInner { fn intersection_update( &self, - others: impl core::iter::Iterator, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { let temp_inner = self.intersection_multi(others, vm)?; @@ -575,7 +637,7 @@ impl PySetInner { fn difference_update( &self, - others: impl core::iter::Iterator, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { @@ -594,110 +656,101 @@ impl PySetInner { other_set.content.keys_with_hashes() }) } else { - Self::cached_hashes(iterable.as_object(), vm) + None }; if let Some(elements) = elements { for (item, hash) in elements { - self.content.delete_if_exists_known_hash(vm, &*item, hash)?; + self.content.delete_if_exists(vm, &*item, hash)?; } continue; } - for item in iterable.iter(vm)? { - self.content.delete_if_exists(vm, &*item?)?; + for item in iterable.get_iter(vm)?.into_iter::(vm) { + let item = item?; + self.discard_key(&item, vm)?; } } Ok(()) } - fn symmetric_difference_update( + pub(super) fn symmetric_difference_update( &self, - others: impl core::iter::Iterator, + others: impl core::iter::Iterator, vm: &VirtualMachine, ) -> PyResult<()> { for iterable in others { - if let Some(elements) = Self::cached_hashes(iterable.as_object(), vm) { - // the source is already duplicate-free - for (item, hash) in elements { - self.content - .delete_or_insert_known_hash(vm, &item, hash, ())?; - } + if extract_set(&iterable) + .is_some_and(|other| PyRc::ptr_eq(&self.content, &other.content)) + { + self.clear(); continue; } - // We want to remove duplicates in iterable - let iterable_set = Self::from_iter(iterable.iter(vm)?, vm)?; - for (item, hash) in iterable_set.content.keys_with_hashes() { - self.content - .delete_or_insert_known_hash(vm, &item, hash, ())?; - } + let iterable_set; + let elements = if let Some(elements) = Self::cached_hashes(iterable.as_object(), vm) { + // the source is already duplicate-free + elements + } else { + // We want to remove duplicates in iterable + // Keep the source alive through toggle_entries: its finalizer may mutate the set. + #[allow(clippy::redundant_clone)] + { + iterable_set = Self::from_object(iterable.clone(), vm)?; + } + iterable_set.content.keys_with_hashes() + }; + self.toggle_entries(elements, vm)?; + } + Ok(()) + } + + fn toggle_entries( + &self, + elements: Vec<(PyObjectRef, PyHash)>, + vm: &VirtualMachine, + ) -> PyResult<()> { + for (item, hash) in elements { + self.content.delete_or_insert(vm, &item, hash, ())?; } Ok(()) } fn hash(&self) -> PyHash { - let hasher = self.content.fold_hashes( - hash::FrozenSetHash::new(self.len()), - |mut hasher, element_hash| { - hasher.add(element_hash); - hasher - }, - ); + let hasher = + self.content + .fold_hashes(hash::FrozenSetHash::new, |mut hasher, element_hash| { + hasher.add(element_hash); + hasher + }); hasher.finish() } - // Run operation, on failure, if item is a set/set subclass, convert it - // into a frozenset and try the operation again. Propagates original error - // on failure to convert and restores item in KeyError on failure (remove). - fn retry_op_with_frozenset( - &self, + // Mutable-set lookup borrows the frozenset hash algorithm, not a converted + // key: comparisons must still receive the caller's original object. + fn mutable_set_hash( item: &PyObject, + exc: PyBaseExceptionRef, vm: &VirtualMachine, - op: F, - ) -> PyResult - where - F: Fn(&PyObject, &VirtualMachine) -> PyResult, - { - op(item, vm).or_else(|original_err| { - item.downcast_ref::() - // Keep original error around. - .ok_or(original_err) - .and_then(|set| { - op( - &PyFrozenSet { - inner: set.inner.copy(), - ..Default::default() - } - .into_pyobject(vm), - vm, - ) - // If operation raised KeyError, report original set (set.remove) - .map_err(|op_err| { - if op_err.fast_isinstance(vm.ctx.exceptions.key_error) { - vm.new_key_error(item.to_owned()) - } else { - op_err - } - }) - }) - }) + ) -> PyResult { + if exc.fast_isinstance(vm.ctx.exceptions.type_error) + && let Some(set) = item.downcast_ref::() + { + // Clearing the swallowed exception can mutate the lookup key. + drop(exc); + Ok(set.inner.hash()) + } else { + Err(exc) + } } - fn wrap_unhashable_error( - result: PyResult, + fn key_hash(item: &PyObject, vm: &VirtualMachine) -> PyResult { + item.hash(vm).map_err(|exc| Self::hash_error(item, exc, vm)) + } + + fn hash_error( item: &PyObject, + exc: PyBaseExceptionRef, vm: &VirtualMachine, - ) -> PyResult { - match result { - Err(cause) if cause.fast_isinstance(vm.ctx.exceptions.type_error) => { - let message = cause.as_object().str(vm)?; - let err = vm.new_type_error(format!( - "cannot use '{}' as a set element ({message})", - item.class().name() - )); - err.set_cause(Some(cause)); - Err(err) - } - result => result, - } + ) -> PyBaseExceptionRef { + super::dict::contextualize_hash_error(item, "set", "element", exc, vm) } } @@ -726,15 +779,16 @@ pub(super) fn exact_set_keys_with_hashes( Some(inner.content.keys_with_hashes()) } -fn reduce_set(zelf: &PyObject, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef, Option) { - ( - zelf.class().to_owned(), - #[expect(clippy::or_fun_call, reason = "changing this won't compile")] - vm.new_tuple((extract_set(zelf) - .unwrap_or(&PySetInner::default()) - .elements(),)), - zelf.dict(), - ) +fn reduce_set( + zelf: &PyObject, + vm: &VirtualMachine, +) -> PyResult<(PyTypeRef, PyTupleRef, PyObjectRef)> { + let keys = vm.ctx.new_list(vm.extract_elements_sized(zelf, &|| 0, Ok)?); + let args = vm.new_tuple((keys,)); + let state = zelf + .get_attr(identifier!(vm, __getstate__), vm)? + .call((), vm)?; + Ok((zelf.class().to_owned(), args, state)) } impl PySet { @@ -747,12 +801,10 @@ impl PySet { } fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { - Ok(PyArithmeticValue::Implemented(self.op( - other, - PySetInner::union, - vm, - )?)) + if let Ok(other) = PyRef::::try_from_object(vm, other) { + Ok(PyArithmeticValue::Implemented( + self.union_multi(core::iter::once(other.into_object()), vm)?, + )) } else { Ok(PyArithmeticValue::NotImplemented) } @@ -763,9 +815,9 @@ impl PySet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { + if let Ok(other) = PyRef::::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(Self { - inner: self.inner.intersection(other.into_iterable(vm)?, vm)?, + inner: self.inner.intersection(other.into_object(), vm)?, })) } else { Ok(PyArithmeticValue::NotImplemented) @@ -777,9 +829,9 @@ impl PySet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { + if let Ok(other) = PyRef::::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(Self { - inner: self.inner.difference_new(other.into_iterable(vm)?, vm)?, + inner: self.inner.difference_new(other.into_object(), vm)?, })) } else { Ok(PyArithmeticValue::NotImplemented) @@ -791,11 +843,9 @@ impl PySet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { + if let Ok(other) = PyRef::::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(Self { - inner: other - .as_inner() - .difference_new(ArgIterable::try_from_object(vm, zelf.into())?, vm)?, + inner: other.as_inner().difference_new(zelf.into(), vm)?, })) } else { Ok(PyArithmeticValue::NotImplemented) @@ -807,46 +857,60 @@ impl PySet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { - Ok(PyArithmeticValue::Implemented(self.op( - other, - PySetInner::symmetric_difference, - vm, - )?)) + if let Ok(other) = PyRef::::try_from_object(vm, other) { + Ok(PyArithmeticValue::Implemented(Self { + inner: self.inner.symmetric_difference(other.into_object(), vm)?, + })) } else { Ok(PyArithmeticValue::NotImplemented) } } - fn __ior__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { + fn __ior__( + zelf: PyRef, + set: PyRef, + vm: &VirtualMachine, + ) -> PyResult> { zelf.inner.merge_set(set, vm)?; Ok(zelf) } - fn __iand__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { + fn __iand__( + zelf: PyRef, + set: PyRef, + vm: &VirtualMachine, + ) -> PyResult> { if !set.is(zelf.as_object()) { zelf.inner - .intersection_update(core::iter::once(set.into_iterable(vm)?), vm)?; + .intersection_update(core::iter::once(set.into_object()), vm)?; } Ok(zelf) } - fn __isub__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { + fn __isub__( + zelf: PyRef, + set: PyRef, + vm: &VirtualMachine, + ) -> PyResult> { if set.is(zelf.as_object()) { zelf.inner.clear(); } else { zelf.inner - .difference_update(set.into_iterable_iter(vm)?, vm)?; + .difference_update(core::iter::once(set.into_object()), vm)?; } Ok(zelf) } - fn __ixor__(zelf: PyRef, set: AnySet, vm: &VirtualMachine) -> PyResult> { + fn __ixor__( + zelf: PyRef, + set: PyRef, + vm: &VirtualMachine, + ) -> PyResult> { if set.is(zelf.as_object()) { zelf.inner.clear(); } else { zelf.inner - .symmetric_difference_update(set.into_iterable_iter(vm)?, vm)?; + .symmetric_difference_update(core::iter::once(set.into_object()), vm)?; } Ok(zelf) } @@ -889,16 +953,16 @@ impl Py { #[pymethod] fn union( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult { - self.fold_op(others.into_iter(), PySetInner::union, vm) + self.union_multi(others.into_iter(), vm) } #[pymethod] fn intersection( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult { Ok(PySet { @@ -909,7 +973,7 @@ impl Py { #[pymethod] fn difference( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult { Ok(PySet { @@ -918,27 +982,25 @@ impl Py { } #[pymethod] - fn symmetric_difference(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - self.fold_op( - core::iter::once(other), - PySetInner::symmetric_difference, - vm, - ) + fn symmetric_difference(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { + Ok(PySet { + inner: self.inner.symmetric_difference(other, vm)?, + }) } #[pymethod] fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - self.inner.issubset(other, vm) + self.inner.issubset(other.as_object(), vm) } #[pymethod] fn issuperset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - self.inner.issuperset(other, vm) + self.inner.issuperset(other.as_object(), vm) } #[pymethod] fn isdisjoint(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - self.inner.isdisjoint(other, vm) + self.inner.isdisjoint(other.as_object(), vm) } #[pymethod] @@ -981,7 +1043,7 @@ impl Py { #[pymethod] fn intersection_update( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult<()> { self.inner.intersection_update(others.into_iter(), vm)?; @@ -991,14 +1053,14 @@ impl Py { #[pymethod] fn difference_update( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult<()> { self.inner.difference_update(others.into_iter(), vm) } #[pymethod] - fn symmetric_difference_update(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult<()> { + fn symmetric_difference_update(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.inner .symmetric_difference_update(core::iter::once(other), vm) } @@ -1007,7 +1069,7 @@ impl Py { fn __reduce__( zelf: PyRef, vm: &VirtualMachine, - ) -> (PyTypeRef, PyTupleRef, Option) { + ) -> PyResult<(PyTypeRef, PyTupleRef, PyObjectRef)> { reduce_set(zelf.as_ref(), vm) } @@ -1063,10 +1125,7 @@ impl Comparable for PySet { impl Iterable for PySet { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - Ok(PySetIterator::new(AnySet { - object: zelf.into(), - }) - .into_pyobject(vm)) + Ok(PySetIterator::new(zelf.into()).into_pyobject(vm)) } } @@ -1076,7 +1135,7 @@ impl AsNumber for PySet { // Binary ops check both operands are sets (like CPython's set_sub, etc.) // This is needed because __rsub__ swaps operands: a.__rsub__(b) calls subtract(b, a) subtract: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1091,7 +1150,7 @@ impl AsNumber for PySet { } }), and: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1105,7 +1164,7 @@ impl AsNumber for PySet { } }), xor: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1119,7 +1178,7 @@ impl AsNumber for PySet { } }), or: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1133,33 +1192,57 @@ impl AsNumber for PySet { } }), inplace_subtract: Some(|a, b, vm| { - if let Some(a) = a.downcast_ref::() { - PySet::__isub__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) - .to_pyresult(vm) + if let Some(a) = a.downcast_ref::() + && PyRef::::check(b, vm) + { + PySet::__isub__( + a.to_owned(), + PyRef::::try_from_object(vm, b.to_owned())?, + vm, + ) + .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_and: Some(|a, b, vm| { - if let Some(a) = a.downcast_ref::() { - PySet::__iand__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) - .to_pyresult(vm) + if let Some(a) = a.downcast_ref::() + && PyRef::::check(b, vm) + { + PySet::__iand__( + a.to_owned(), + PyRef::::try_from_object(vm, b.to_owned())?, + vm, + ) + .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_xor: Some(|a, b, vm| { - if let Some(a) = a.downcast_ref::() { - PySet::__ixor__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) - .to_pyresult(vm) + if let Some(a) = a.downcast_ref::() + && PyRef::::check(b, vm) + { + PySet::__ixor__( + a.to_owned(), + PyRef::::try_from_object(vm, b.to_owned())?, + vm, + ) + .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } }), inplace_or: Some(|a, b, vm| { - if let Some(a) = a.downcast_ref::() { - PySet::__ior__(a.to_owned(), AnySet::try_from_object(vm, b.to_owned())?, vm) - .to_pyresult(vm) + if let Some(a) = a.downcast_ref::() + && PyRef::::check(b, vm) + { + PySet::__ior__( + a.to_owned(), + PyRef::::try_from_object(vm, b.to_owned())?, + vm, + ) + .to_pyresult(vm) } else { Ok(vm.ctx.not_implemented()) } @@ -1182,7 +1265,7 @@ impl Representable for PySet { } if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { - let name = (class_name != "set").then_some(class_name); + let name = (!class.is(vm.ctx.types.set_type)).then_some(class_name); zelf.inner.repr(name, vm) } else { Ok(Wtf8Buf::from(format!("{class_name}(...)"))) @@ -1274,12 +1357,10 @@ impl PyFrozenSet { } fn __or__(&self, other: PyObjectRef, vm: &VirtualMachine) -> PyResult> { - if let Ok(set) = AnySet::try_from_object(vm, other) { - Ok(PyArithmeticValue::Implemented(self.op( - set, - PySetInner::union, - vm, - )?)) + if let Ok(set) = PyRef::::try_from_object(vm, other) { + Ok(PyArithmeticValue::Implemented( + self.union_multi(core::iter::once(set.into_object()), vm)?, + )) } else { Ok(PyArithmeticValue::NotImplemented) } @@ -1290,9 +1371,9 @@ impl PyFrozenSet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { + if let Ok(other) = PyRef::::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(Self { - inner: self.inner.intersection(other.into_iterable(vm)?, vm)?, + inner: self.inner.intersection(other.into_object(), vm)?, ..Default::default() })) } else { @@ -1305,9 +1386,9 @@ impl PyFrozenSet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { + if let Ok(other) = PyRef::::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(Self { - inner: self.inner.difference_new(other.into_iterable(vm)?, vm)?, + inner: self.inner.difference_new(other.into_object(), vm)?, ..Default::default() })) } else { @@ -1320,11 +1401,9 @@ impl PyFrozenSet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { + if let Ok(other) = PyRef::::try_from_object(vm, other) { Ok(PyArithmeticValue::Implemented(Self { - inner: other - .as_inner() - .difference_new(ArgIterable::try_from_object(vm, zelf.into())?, vm)?, + inner: other.as_inner().difference_new(zelf.into(), vm)?, ..Default::default() })) } else { @@ -1337,12 +1416,11 @@ impl PyFrozenSet { other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Ok(other) = AnySet::try_from_object(vm, other) { - Ok(PyArithmeticValue::Implemented(self.op( - other, - PySetInner::symmetric_difference, - vm, - )?)) + if let Ok(other) = PyRef::::try_from_object(vm, other) { + Ok(PyArithmeticValue::Implemented(Self { + inner: self.inner.symmetric_difference(other.into_object(), vm)?, + ..Default::default() + })) } else { Ok(PyArithmeticValue::NotImplemented) } @@ -1388,16 +1466,16 @@ impl Py { #[pymethod] fn union( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult { - self.fold_op(others.into_iter(), PySetInner::union, vm) + self.union_multi(others.into_iter(), vm) } #[pymethod] fn intersection( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult { Ok(PyFrozenSet { @@ -1409,7 +1487,7 @@ impl Py { #[pymethod] fn difference( &self, - others: PosArgs, + others: PosArgs, vm: &VirtualMachine, ) -> PyResult { Ok(PyFrozenSet { @@ -1421,36 +1499,35 @@ impl Py { #[pymethod] fn symmetric_difference( &self, - other: ArgIterable, + other: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - self.fold_op( - core::iter::once(other), - PySetInner::symmetric_difference, - vm, - ) + Ok(PyFrozenSet { + inner: self.inner.symmetric_difference(other, vm)?, + ..Default::default() + }) } #[pymethod] fn issubset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - self.inner.issubset(other, vm) + self.inner.issubset(other.as_object(), vm) } #[pymethod] fn issuperset(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - self.inner.issuperset(other, vm) + self.inner.issuperset(other.as_object(), vm) } #[pymethod] fn isdisjoint(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - self.inner.isdisjoint(other, vm) + self.inner.isdisjoint(other.as_object(), vm) } #[pymethod] fn __reduce__( zelf: PyRef, vm: &VirtualMachine, - ) -> (PyTypeRef, PyTupleRef, Option) { + ) -> PyResult<(PyTypeRef, PyTupleRef, PyObjectRef)> { reduce_set(zelf.as_ref(), vm) } @@ -1515,10 +1592,7 @@ impl Comparable for PyFrozenSet { impl Iterable for PyFrozenSet { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - Ok(PySetIterator::new(AnySet { - object: zelf.into(), - }) - .into_pyobject(vm)) + Ok(PySetIterator::new(zelf.into()).into_pyobject(vm)) } } @@ -1528,7 +1602,7 @@ impl AsNumber for PyFrozenSet { // Binary ops check both operands are sets (like CPython's set_sub, etc.) // __rsub__ swaps operands. Result type follows first operand's type. subtract: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1541,7 +1615,7 @@ impl AsNumber for PyFrozenSet { } }), and: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1553,7 +1627,7 @@ impl AsNumber for PyFrozenSet { } }), xor: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1565,7 +1639,7 @@ impl AsNumber for PyFrozenSet { } }), or: Some(|a, b, vm| { - if !AnySet::check(a, vm) || !AnySet::check(b, vm) { + if !PyRef::::check(a, vm) || !PyRef::::check(b, vm) { return Ok(vm.ctx.not_implemented()); } if let Some(a) = a.downcast_ref::() { @@ -1599,66 +1673,117 @@ impl Representable for PyFrozenSet { } } -struct AnySet { - object: PyObjectRef, +/// A borrowed view of either a set or a frozenset, including subclasses. +/// +/// This is an erased header view, not a shared payload layout: every payload +/// access still downcasts to the actual alternative. It cannot be allocated as +/// a payload or constructed without checking the object. +#[repr(transparent)] +pub(crate) struct PyAnySet { + object: PyObject, +} + +// SAFETY: this owner contributes exactly one strong reference to the object. +unsafe impl Traverse for PyRef { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + tracer(self.as_object()); + } } -impl Borrow for AnySet { +impl Borrow for PyAnySet { #[inline(always)] fn borrow(&self) -> &PyObject { &self.object } } -impl AnySet { - /// Check if object is a set or frozenset (including subclasses) - /// Equivalent to CPython's PyAnySet_Check +impl Borrow for PyRef { + fn borrow(&self) -> &PyAnySet { + self + } +} + +impl ToOwned for PyAnySet { + type Owned = PyRef; + + fn to_owned(&self) -> PyRef { + // SAFETY: this borrowed view already guarantees a set payload. + unsafe { PyRef::::from_object_unchecked(self.object.to_owned()) } + } +} + +impl From> for PyRef { + fn from(set: PyRef) -> Self { + // SAFETY: the typed owner guarantees the set alternative. + unsafe { Self::from_object_unchecked(set.into()) } + } +} + +impl From> for PyRef { + fn from(set: PyRef) -> Self { + // SAFETY: the typed owner guarantees the frozenset alternative. + unsafe { Self::from_object_unchecked(set.into()) } + } +} + +impl From> for PyObjectRef { + fn from(set: PyRef) -> Self { + set.into_object() + } +} + +impl PyAnySet { + /// Check if object is a set or frozenset (including subclasses). + /// Equivalent to CPython's PyAnySet_Check. fn check(obj: &PyObject, vm: &VirtualMachine) -> bool { let ctx = &vm.ctx; obj.fast_isinstance(ctx.types.set_type) || obj.fast_isinstance(ctx.types.frozenset_type) } - fn into_iterable(self, vm: &VirtualMachine) -> PyResult { - self.object.try_into_value(vm) + fn as_inner(&self) -> &PySetInner { + extract_set(&self.object).expect("PyAnySet is always PySet or PyFrozenSet") } +} - fn into_iterable_iter( - self, - vm: &VirtualMachine, - ) -> PyResult> { - Ok(core::iter::once(self.into_iterable(vm)?)) +impl PyRef { + fn check(obj: &PyObject, vm: &VirtualMachine) -> bool { + PyAnySet::check(obj, vm) } +} - fn as_inner(&self) -> &PySetInner { - match_class!(match self.object.as_object() { - ref set @ PySet => &set.inner, - ref frozen @ PyFrozenSet => &frozen.inner, - _ => unreachable!("AnySet is always PySet or PyFrozenSet"), // should not be called. - }) +// SAFETY: PyRef is a transparent PyRef owner. A successful check proves +// both the Python class and the actual set/frozenset payload of this object. +unsafe impl TransmuteFromObject for PyRef { + fn check(vm: &VirtualMachine, obj: &PyObject) -> PyResult<()> { + if PyAnySet::check(obj, vm) && extract_set(obj).is_some() { + Ok(()) + } else { + Err(vm.new_type_error(format!( + "{} is not a subtype of set or frozenset", + obj.class() + ))) + } } } -impl TryFromObject for AnySet { +impl TryFromObject for PyRef { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - let class = obj.class(); - if class.fast_issubclass(vm.ctx.types.set_type) - || class.fast_issubclass(vm.ctx.types.frozenset_type) - { - Ok(Self { object: obj }) - } else { - Err(vm.new_type_error(format!("{class} is not a subtype of set or frozenset"))) - } + ::check(vm, &obj)?; + // SAFETY: the shared checker proved the union view's payload invariant. + Ok(unsafe { Self::from_object_unchecked(obj) }) } } -#[pyclass(module = false, name = "set_iterator")] +#[pyclass(module = false, name = "set_iterator", traverse, clear = false)] pub(crate) struct PySetIterator { + #[pytraverse(skip)] size: DictSize, /// Whether the set was found to have changed, which `setiter_iternext()` /// records by writing a size no set can have. Sticky: what it makes the /// iterator answer, it answers from then on. + #[pytraverse(skip)] changed: PyAtomic, - internal: PyMutex>, + internal: PyMutex>>, } impl fmt::Debug for PySetIterator { @@ -1676,7 +1801,7 @@ impl PyPayload for PySetIterator { } impl PySetIterator { - fn new(set: AnySet) -> Self { + fn new(set: PyRef) -> Self { Self { size: set.as_inner().content.size(), changed: Radium::new(false), @@ -1793,7 +1918,7 @@ pub(crate) fn init(context: &'static Context) { .types .set_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_set)); PyFrozenSet::extend_class(context, context.types.frozenset_type); @@ -1801,8 +1926,265 @@ pub(crate) fn init(context: &'static Context) { .types .frozenset_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_frozenset)); PySetIterator::extend_class(context, context.types.set_iterator_type); } + +#[cfg(test)] +mod reference_tests { + use super::*; + + #[test] + fn set_gc_detaches_keys_for_deferred_release() { + use crate::object::MaybeTraverse; + + fn check(mut set: impl MaybeTraverse, key: &PyObjectRef) { + let mut visits = 0; + set.try_traverse(&mut |child| { + assert!(core::ptr::eq(child, &**key)); + visits += 1; + }); + assert_eq!(visits, 1); + let mut edges = Vec::new(); + set.try_clear(&mut edges); + set.try_traverse(&mut |_| panic!("cleared set retained a key")); + set.try_clear(&mut edges); + assert_eq!(edges.len(), 1); + assert!(core::ptr::eq(&*edges[0], &**key)); + assert_eq!(key.strong_count(), 2); + drop(edges); + assert_eq!(key.strong_count(), 1); + } + + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for frozen in [false, true] { + let key: PyObjectRef = vm.ctx.new_int(1000).into(); + let inner = PySetInner::default(); + inner.add(&key, vm).unwrap(); + if frozen { + check( + PyFrozenSet { + inner, + ..Default::default() + }, + &key, + ); + } else { + check(PySet { inner }, &key); + } + } + }); + } + + #[test] + fn set_gc_preserves_shared_table_edges() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let key: PyObjectRef = vm.ctx.new_int(1000).into(); + let mut inner = PySetInner::default(); + inner.add(&key, vm).unwrap(); + let alias = inner.clone(); + inner.traverse(&mut |_| panic!("shared table edge counted")); + alias.traverse(&mut |_| panic!("shared table edge counted")); + let mut edges = Vec::new(); + Traverse::clear(&mut inner, &mut edges); + assert!(edges.is_empty()); + assert!(alias.contains(&key, vm).unwrap()); + drop(alias); + Traverse::clear(&mut inner, &mut edges); + assert_eq!(inner.len(), 0); + assert_eq!(edges.len(), 1); + }); + } + + #[test] + fn frozenset_gc_tracking_covers_native_construction() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let key: PyObjectRef = vm.ctx.new_int(1000).into(); + let atomic = PyRef::new_ref( + PyFrozenSet::from_iter(vm, [key.clone()]).unwrap(), + vm.ctx.types.frozenset_type.to_owned(), + None, + ); + assert!(!atomic.as_object().is_gc_tracked()); + let nested = PyFrozenSet::from_iter(vm, [atomic.into()]) + .unwrap() + .into_ref(&vm.ctx); + assert!(!nested.as_object().is_gc_tracked()); + + // A traversable key must keep the frozen owner visible to GC. + let tuple: PyObjectRef = vm.ctx.new_tuple(vec![key.clone()]).into(); + let owner = PyFrozenSet::from_iter(vm, [tuple]) + .unwrap() + .into_ref(&vm.ctx); + assert!(owner.as_object().is_gc_tracked()); + + let subclass = vm.ctx.new_class( + None, + "FrozenSubclass", + vm.ctx.types.frozenset_type.to_owned(), + Default::default(), + ); + let subclass = PyFrozenSet::default() + .into_ref_with_type(vm, subclass) + .unwrap(); + assert!(subclass.as_object().is_gc_tracked()); + + // A temporary native alias can still add traversable keys. + let inner = PySetInner::default(); + inner.add(&key, vm).unwrap(); + let alias = inner.clone(); + let owner = PyFrozenSet { + inner, + ..Default::default() + } + .into_ref(&vm.ctx); + assert!(owner.as_object().is_gc_tracked()); + drop(alias); + }); + } + + #[test] + fn anyset_reference_layout_and_ownership() { + static_assertions::assert_not_impl_any!(PyAnySet: PyPayload); + static_assertions::assert_type_eq_all!( + ::Target, + PyAnySet + ); + static_assertions::assert_eq_size!(PyRef, PyObjectRef, Option>); + static_assertions::assert_eq_align!(PyRef, PyObjectRef); + static_assertions::assert_eq_size!(PyAnySet, PyObject); + static_assertions::assert_eq_align!(PyAnySet, PyObject); + #[cfg(feature = "threading")] + static_assertions::assert_impl_all!(PyRef: Send, Sync); + #[cfg(not(feature = "threading"))] + static_assertions::assert_not_impl_any!(PyRef: Send, Sync); + + let ctx = Context::genesis(); + let set: PyRef = PySet::default().into_ref(ctx).into(); + let frozen: PyRef = PyFrozenSet::default().into_ref(ctx).into(); + for owner in [set, frozen] { + let object = owner.as_object() as *const PyObject; + assert_eq!(owner.as_object().strong_count(), 1); + let borrowed: &PyAnySet = &owner; + assert!(core::ptr::eq(borrowed.as_object(), object)); + assert!(core::ptr::eq( + borrowed.as_inner(), + extract_set(owner.as_object()).unwrap() + )); + let copy = borrowed.to_owned(); + assert_eq!(owner.as_object().strong_count(), 2); + let clone = owner.clone(); + assert_eq!(owner.as_object().strong_count(), 3); + let erased = clone.into_object(); + assert_eq!(erased.strong_count(), 3); + assert!(core::ptr::eq(&*erased, object)); + drop(copy); + drop(owner); + assert_eq!(erased.strong_count(), 1); + } + } + + #[test] + fn anyset_checked_reference_conversion() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let set = PySet::default().into_pyobject(vm); + let frozen = PyFrozenSet::default().into_pyobject(vm); + for object in [set, frozen] { + let owner = PyRef::::try_from_object(vm, object.clone()).unwrap(); + assert_eq!(object.strong_count(), 2); + assert!(core::ptr::eq(owner.as_object(), &*object)); + let erased: PyObjectRef = owner.into(); + assert_eq!(object.strong_count(), 2); + assert!(core::ptr::eq(&*erased, &*object)); + drop(erased); + assert_eq!(object.strong_count(), 1); + } + let unrelated: PyObjectRef = vm.ctx.new_int(1000).into(); + let error = PyRef::::try_from_object(vm, unrelated.clone()).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.type_error)); + assert_eq!(unrelated.strong_count(), 1); + }); + } + + #[test] + fn anyset_typed_tuple_views_and_refcounts() { + use crate::builtins::PyTuple; + type Typed = PyTuple>; + type Nested = PyTuple>; + static_assertions::assert_not_impl_any!(PyObject: crate::object::PyTypedRefTarget); + static_assertions::assert_impl_all!(PyAnySet: crate::object::PyTypedRefTarget); + static_assertions::assert_impl_all!(Typed: crate::object::PyTypedRefTarget); + static_assertions::assert_eq_size!(Typed, PyTuple); + static_assertions::assert_eq_align!(Typed, PyTuple); + static_assertions::assert_eq_size!(Py, Py); + static_assertions::assert_eq_align!(Py, Py); + + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let set: PyRef = PySet::default().into_ref(&vm.ctx).into(); + let frozen: PyRef = PyFrozenSet::default().into_ref(&vm.ctx).into(); + let tuple = Typed::new_ref_typed(vec![set.clone(), frozen.clone()], &vm.ctx); + assert_eq!(set.as_object().strong_count(), 2); + assert_eq!(frozen.as_object().strong_count(), 2); + assert!( + tuple.as_slice()[0] + .as_object() + .downcast_ref::() + .is_some() + ); + assert!( + tuple.as_slice()[1] + .as_object() + .downcast_ref::() + .is_some() + ); + assert!(core::ptr::eq( + tuple.as_slice()[0].as_inner(), + set.as_inner() + )); + assert!(core::ptr::eq( + tuple.as_slice()[1].as_inner(), + frozen.as_inner() + )); + let erased = tuple.clone().into_untyped(); + assert!(core::ptr::eq(tuple.as_untyped(), &*erased)); + assert_eq!(erased.as_object().strong_count(), 2); + let checked = erased.try_into_typed::(vm).unwrap(); + assert!(core::ptr::eq(&*checked, &*tuple)); + assert_eq!(checked.as_object().strong_count(), 2); + let borrowed_copy = (*checked).to_owned(); + assert_eq!(tuple.as_object().strong_count(), 3); + let nested: PyRef = PyTuple::new_ref_typed(vec![borrowed_copy], &vm.ctx); + assert!(core::ptr::eq(&*nested.as_slice()[0], &*tuple)); + let untyped: PyTupleRef = nested.into(); + assert_eq!(tuple.as_object().strong_count(), 3); + drop(untyped); + drop(checked); + assert_eq!(tuple.as_object().strong_count(), 1); + drop(tuple); + assert_eq!(set.as_object().strong_count(), 1); + assert_eq!(frozen.as_object().strong_count(), 1); + }); + } + + #[test] + fn anyset_typed_tuple_rejects_invalid_element_without_leaking() { + use crate::builtins::PyTuple; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let set = PySet::default().into_pyobject(vm); + let wrong: PyObjectRef = vm.ctx.new_int(1000).into(); + let tuple = PyTuple::new_ref(vec![set.clone(), wrong.clone()], &vm.ctx); + let error = tuple.clone().try_into_typed::(vm).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.type_error)); + assert_eq!(tuple.as_object().strong_count(), 1); + assert!(core::ptr::eq(&*tuple.as_slice()[0], &*set)); + assert!(core::ptr::eq(&*tuple.as_slice()[1], &*wrong)); + assert_eq!(set.strong_count(), 2); + assert_eq!(wrong.strong_count(), 2); + drop(tuple); + assert_eq!(set.strong_count(), 1); + assert_eq!(wrong.strong_count(), 1); + }); + } +} diff --git a/crates/vm/src/builtins/singletons.rs b/crates/vm/src/builtins/singletons.rs index c28be2dd932..4173de4b765 100644 --- a/crates/vm/src/builtins/singletons.rs +++ b/crates/vm/src/builtins/singletons.rs @@ -50,7 +50,10 @@ impl Constructor for PyNone { } } -#[pyclass(with(Constructor, AsNumber, Comparable, Hashable, Representable))] +#[pyclass( + with(Constructor, AsNumber, Comparable, Hashable, Representable), + flags(IMMUTABLETYPE) +)] impl PyNone {} impl Representable for PyNone { @@ -91,7 +94,7 @@ impl Comparable for PyNone { impl Hashable for PyNone { fn hash(_zelf: &Py, _vm: &VirtualMachine) -> PyResult { - Ok(0xFCA86420) + Ok(0xFCA86420u32 as PyHash) } } diff --git a/crates/vm/src/builtins/slice.rs b/crates/vm/src/builtins/slice.rs index 8cc53fd16c1..7525a859eea 100644 --- a/crates/vm/src/builtins/slice.rs +++ b/crates/vm/src/builtins/slice.rs @@ -2,16 +2,18 @@ // spell-checker:ignore sliceobject use core::cell::Cell; use core::ptr::NonNull; -use rustpython_common::wtf8::{Wtf8Buf, wtf8_concat}; +use rustpython_common::wtf8::Wtf8Buf; use super::{PyGenericAlias, PyStrRef, PyTupleRef, PyType, PyTypeRef}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, class::{PyClassDef, PyClassImpl}, common::hash::{PyHash, PyUHash}, - function::{ArgIndex, FuncArgs, OptionalArg, PyComparisonValue}, + function::{Either, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, + iter::PyExactSizeIterator, sliceable::SaturatedSlice, types::{Comparable, Constructor, Hashable, PyComparisonOp, Representable}, + utils::collection_repr, }; use malachite_bigint::{BigInt, ToBigInt}; use num_traits::{One, Signed, Zero}; @@ -36,14 +38,18 @@ unsafe impl crate::object::Traverse for PySlice { } fn clear(&mut self, out: &mut Vec) { - if let Some(start) = self.start.take() { - out.push(start); - } - // stop is not Option, so it will be freed when payload is dropped - // (via drop_in_place on freelist pop, or Box::from_raw on dealloc) + // Release step, start, then stop before the husk enters the freelist. + // Keep the mandatory stop field valid without retaining its old owner. if let Some(step) = self.step.take() { out.push(step); } + if let Some(start) = self.start.take() { + out.push(start); + } + out.push(core::mem::replace( + &mut self.stop, + Context::genesis().none(), + )); } } @@ -111,17 +117,25 @@ impl PySlice { length: &BigInt, vm: &VirtualMachine, ) -> PyResult<(BigInt, BigInt, BigInt)> { + let index = |object: &PyObject| -> PyResult { + let value = object.try_index_opt(vm).transpose()?.ok_or_else(|| { + vm.new_type_error( + "slice indices must be integers or None or have an __index__ method", + ) + })?; + Ok(value.as_bigint().clone()) + }; + // Calculate step let step: BigInt; if vm.is_none(self.step_ref(vm)) { step = One::one(); } else { // Clone the value, not the reference. - let this_step = self.step_ref(vm).try_index(vm)?; - step = this_step.as_bigint().clone(); + step = index(self.step_ref(vm))?; if step.is_zero() { - return Err(vm.new_value_error("slice step cannot be zero.")); + return Err(vm.new_value_error("slice step cannot be zero")); } } @@ -151,8 +165,7 @@ impl PySlice { lower.clone() }; } else { - let this_start = self.start_ref(vm).try_index(vm)?; - start = this_start.as_bigint().clone(); + start = index(self.start_ref(vm))?; if start < Zero::zero() { // From end of array @@ -171,8 +184,7 @@ impl PySlice { if vm.is_none(&self.stop) { stop = if backwards { lower } else { upper }; } else { - let this_stop = self.stop.try_index(vm)?; - stop = this_stop.as_bigint().clone(); + stop = index(&self.stop)?; if stop < Zero::zero() { // From end of array @@ -187,22 +199,23 @@ impl PySlice { Ok((start, stop, step)) } +} - // TODO: Uncomment when Python adds __class_getitem__ to slice - // #[pyclassmethod] +#[pyclass(with(Comparable, Representable, Hashable), flags(IMMUTABLETYPE))] +impl Py { + #[pyclassmethod] fn __class_getitem__( cls: PyTypeRef, - args: PyObjectRef, + object: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - PyGenericAlias::from_args(cls, args, vm) + PyGenericAlias::from_args(cls, object, vm) } -} - -#[pyclass(with(Comparable, Representable, Hashable))] -impl Py { #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + if !args.kwargs.is_empty() { + return Err(vm.new_type_error("slice() takes no keyword arguments")); + } let slice: PySlice = match args.args.len() { 0 => { return Err(vm.new_arity_type_error(PySlice::NAME, 1..=3, 0)); @@ -229,14 +242,17 @@ impl Py { } #[pymethod] - fn indices(&self, object: ArgIndex, vm: &VirtualMachine) -> PyResult { - let length = object.into_int_ref(); - let length = length.as_bigint(); - if length.is_negative() { - return Err(vm.new_value_error("length should not be negative.")); - } - let (start, stop, step) = self.inner_indices(length, vm)?; - Ok(vm.new_tuple((start, stop, step))) + fn indices(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult { + // Keep the original length alive while all slice components convert. + (|| { + let length = object.try_index(vm)?; + let length = length.as_bigint(); + if length.is_negative() { + return Err(vm.new_value_error("length should not be negative")); + } + let (start, stop, step) = self.inner_indices(length, vm)?; + Ok(vm.new_tuple((start, stop, step))) + })() } #[allow(clippy::type_complexity)] @@ -264,17 +280,17 @@ impl Hashable for PySlice { #[inline] fn hash(zelf: &Py, vm: &VirtualMachine) -> PyResult { const XXPRIME_1: PyUHash = if cfg!(target_pointer_width = "64") { - 11400714785074694791 + 11400714785074694791u64 as PyUHash } else { 2654435761 }; const XXPRIME_2: PyUHash = if cfg!(target_pointer_width = "64") { - 14029467366897019727 + 14029467366897019727u64 as PyUHash } else { 2246822519 }; const XXPRIME_5: PyUHash = if cfg!(target_pointer_width = "64") { - 2870177450012600261 + 2870177450012600261u64 as PyUHash } else { 374761393 }; @@ -302,65 +318,54 @@ impl Hashable for PySlice { } impl Comparable for PySlice { + fn slot_richcompare( + zelf: &PyObject, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult> { + let (Some(zelf), Some(other)) = (zelf.downcast_ref::(), other.downcast_ref::()) + else { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + }; + if zelf.is(other) { + return Ok(Either::B(op.eval_ord(core::cmp::Ordering::Equal).into())); + } + [zelf.start_ref(vm), &zelf.stop, zelf.step_ref(vm)] + .into_iter() + .richcompare( + [other.start_ref(vm), &other.stop, other.step_ref(vm)].into_iter(), + op, + vm, + ) + } + fn cmp( zelf: &Py, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { - let other = class_or_notimplemented!(Self, other); - - let ret = match op { - PyComparisonOp::Lt | PyComparisonOp::Le => None - .or_else(|| { - vm.bool_seq_lt(zelf.start_ref(vm), other.start_ref(vm)) - .transpose() - }) - .or_else(|| vm.bool_seq_lt(&zelf.stop, &other.stop).transpose()) - .or_else(|| { - vm.bool_seq_lt(zelf.step_ref(vm), other.step_ref(vm)) - .transpose() - }) - .unwrap_or_else(|| Ok(op == PyComparisonOp::Le))?, - PyComparisonOp::Eq | PyComparisonOp::Ne => { - let eq = vm.identical_or_equal(zelf.start_ref(vm), other.start_ref(vm))? - && vm.identical_or_equal(&zelf.stop, &other.stop)? - && vm.identical_or_equal(zelf.step_ref(vm), other.step_ref(vm))?; - if op == PyComparisonOp::Ne { !eq } else { eq } - } - PyComparisonOp::Gt | PyComparisonOp::Ge => None - .or_else(|| { - vm.bool_seq_gt(zelf.start_ref(vm), other.start_ref(vm)) - .transpose() - }) - .or_else(|| vm.bool_seq_gt(&zelf.stop, &other.stop).transpose()) - .or_else(|| { - vm.bool_seq_gt(zelf.step_ref(vm), other.step_ref(vm)) - .transpose() - }) - .unwrap_or_else(|| Ok(op == PyComparisonOp::Ge))?, - }; - - Ok(PyComparisonValue::Implemented(ret)) + match Self::slot_richcompare(zelf.as_object(), other, op, vm)? { + Either::A(value) => PyArithmeticValue::from_object(vm, value) + .map(|value| value.try_to_bool(vm)) + .transpose(), + Either::B(value) => Ok(value), + } } } impl Representable for PySlice { #[inline] fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let start_repr = zelf.start_ref(vm).repr(vm)?; - let stop_repr = zelf.stop.repr(vm)?; - let step_repr = zelf.step_ref(vm).repr(vm)?; - - Ok(wtf8_concat!( + collection_repr( + None, "slice(", - start_repr.as_wtf8(), - ", ", - stop_repr.as_wtf8(), - ", ", - step_repr.as_wtf8(), - ")" - )) + ")", + "", + [zelf.start_ref(vm), &zelf.stop, zelf.step_ref(vm)].into_iter(), + vm, + ) } } diff --git a/crates/vm/src/builtins/staticmethod.rs b/crates/vm/src/builtins/staticmethod.rs index 387e661a878..61c72a8ccca 100644 --- a/crates/vm/src/builtins/staticmethod.rs +++ b/crates/vm/src/builtins/staticmethod.rs @@ -1,7 +1,8 @@ use super::{ PyGenericAlias, PyStr, PyType, PyTypeRef, classmethod::{ - descriptor_get_wrapped_attribute, descriptor_set_wrapped_attribute, functools_wraps, + descriptor_get_wrapped_attribute, descriptor_set_callable, + descriptor_set_wrapped_attribute, functools_wraps, }, }; use crate::{ @@ -57,16 +58,13 @@ impl Constructor for PyStaticMethod { type Args = StaticMethodArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - // Validate the signature here, but defer storing the callable and - // copying its attributes to `__init__` so that subclasses overriding - // `__init__` without calling `super().__init__()` see `__func__` as - // `None`, matching CPython. - let _: StaticMethodArgs = args.bind_for(vm, Self::NAME)?; + let args: StaticMethodArgs = args.bind_for(vm, Self::NAME)?; let result = Self { - callable: PyAtomicRef::from(vm.ctx.none()), + callable: PyAtomicRef::from(args.function.clone()), } .into_ref_with_type(vm, cls)?; - Ok(PyObjectRef::from(result)) + functools_wraps(result.as_object(), &args.function, vm)?; + Ok(result.into()) } fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { @@ -92,15 +90,13 @@ impl Initializer for PyStaticMethod { type Args = StaticMethodArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - let callable = args.function; - zelf.callable.store(callable.clone()); - functools_wraps(zelf.as_object(), &callable, vm) + descriptor_set_callable(zelf.as_object(), &zelf.callable, args.function, vm) } } #[pyclass( with(Callable, GetDescriptor, Constructor, Initializer, Representable), - flags(BASETYPE, HAS_DICT, HAS_WEAKREF) + flags(BASETYPE, HAS_DICT) )] impl Py { #[pygetset] @@ -148,22 +144,8 @@ impl Py { } #[pygetset] - fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyObjectRef { - let callable = self.callable.load_owned(); - - if let Ok(Some(is_abstract)) = vm.get_attribute_opt(&callable, "__isabstractmethod__") { - is_abstract - } else { - vm.ctx.new_bool(false).into() - } - } - - #[pygetset(setter)] - fn set___isabstractmethod__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.callable - .load_owned() - .set_attr("__isabstractmethod__", value, vm)?; - Ok(()) + fn __isabstractmethod__(&self, vm: &VirtualMachine) -> PyResult { + self.callable.load_owned().is_abstract(vm) } #[pyclassmethod] diff --git a/crates/vm/src/builtins/str.rs b/crates/vm/src/builtins/str.rs index c66b87cfb5c..86805f81f02 100644 --- a/crates/vm/src/builtins/str.rs +++ b/crates/vm/src/builtins/str.rs @@ -1,7 +1,7 @@ +use super::native_iter::{NativeIterKind, NativeSequenceIter}; use super::{ - PositionIterInternal, PyBytesRef, PyDict, PyList, PyTuple, PyTupleRef, PyType, PyTypeRef, - int::{PyInt, PyIntRef}, - iter::{IterStatus, builtins_iter}, + PyAnyDict, PyBytesRef, PyDict, PyList, PyTuple, PyTupleRef, PyType, PyTypeRef, int::PyInt, + iter::builtins_iter, }; use crate::{ AsObject, Context, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, @@ -11,18 +11,19 @@ use crate::{ bytes_inner::{swapcase_ascii, title_ascii}, cformat::cformat_string, class::{PyClassDef, PyClassImpl}, + codecs::TextCodecArgs, common::{ lock::LazyLock, str::{PyKindStr, StrData, StrKind}, }, - convert::{IntoPyException, ToPyException, ToPyObject, ToPyResult}, + convert::{ToPyException, ToPyObject, ToPyResult}, format::{format, format_map}, - function::{ArgIterable, FuncArgs, OptionalArg, PyComparisonValue, PySsize}, - intern::PyInterned, - object::{MaybeTraverse, Traverse, TraverseFn}, - protocol::{ - BufferFlags, PyBuffer, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods, + function::{ + ArgIndex, ArgIterable, ArgNulFreeStr, FuncArgs, OptionalArg, PyComparisonValue, PySsize, }, + intern::PyInterned, + object::{MaybeTraverse, TraverseFn}, + protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, sequence::SequenceExt, sliceable::{SequenceIndex, SliceableSequenceOp}, types::{ @@ -39,11 +40,9 @@ use itertools::Itertools; use memchr::memchr; use num_traits::ToPrimitive; use rustpython_common::{ - ascii, atomic::{self, PyAtomic, Radium}, - format::{FormatSpec, FormatString, FromTemplate}, + format::{FormatString, FromTemplate}, hash, - lock::PyMutex, str::DeduceStrKind, wtf8::{CodePoint, Wtf8, Wtf8Buf, Wtf8Concat}, }; @@ -56,6 +55,13 @@ impl<'a> TryFromBorrowedObject<'a> for String { } } +impl<'a> TryFromBorrowedObject<'a> for Wtf8Buf { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + let pystr: &Py = TryFromBorrowedObject::try_from_borrowed_object(vm, obj)?; + Ok(pystr.as_wtf8().to_owned()) + } +} + impl<'a> TryFromBorrowedObject<'a> for &'a str { fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { let pystr: &Py = TryFromBorrowedObject::try_from_borrowed_object(vm, obj)?; @@ -307,17 +313,17 @@ impl<'a> AsPyStr<'a> for &'a PyUtf8StrInterned { } } -#[pyclass(module = false, name = "str_iterator", traverse = "manual")] -#[derive(Debug)] -pub(crate) struct PyStrIterator { - internal: PyMutex<(PositionIterInternal, usize)>, +#[derive(Debug, Clone, Traverse)] +struct StrIterState { + string: PyStrRef, + #[pytraverse(skip)] + byte_offset: usize, } -unsafe impl Traverse for PyStrIterator { - fn traverse(&self, tracer: &mut TraverseFn<'_>) { - // No need to worry about deadlock, for inner is a PyStr and can't make ref cycle - self.internal.lock().0.traverse(tracer); - } +#[pyclass(module = false, name = "str_iterator", traverse)] +#[derive(Debug)] +pub(crate) struct PyStrIterator { + internal: NativeSequenceIter, } impl PyPayload for PyStrIterator { @@ -330,24 +336,27 @@ impl PyPayload for PyStrIterator { impl Py { #[pymethod] fn __length_hint__(&self) -> usize { - self.internal.lock().0.length_hint(|obj| obj.char_len()) + self.internal.length_hint(|state| state.string.char_len()) } #[pymethod] fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let mut internal = self.internal.lock(); - internal.1 = usize::MAX; - internal - .0 - .set_state(&object, |obj, pos| pos.min(obj.char_len()), vm) + self.internal.set_state( + &object, + |state| { + state.byte_offset = usize::MAX; + state.string.char_len() + }, + vm, + ) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_iter(vm)?; - Ok(self.internal.lock().0.reduce( + Ok(self.internal.reduce( func, - |x| x.clone().into(), + |state| state.string.into(), |vm| vm.ctx.empty_str.to_owned().into(), vm, )) @@ -358,31 +367,76 @@ impl SelfIter for PyStrIterator {} impl IterNext for PyStrIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let mut internal = zelf.internal.lock(); + let ch = zelf.internal.next(|state, index| { + let value = state.string.as_wtf8(); + if state.byte_offset == usize::MAX { + value.code_point_indices().nth(index).map(|(start, ch)| { + state.byte_offset = start + ch.len_wtf8(); + ch + }) + } else { + value + .get(state.byte_offset..)? + .code_points() + .next() + .inspect(|ch| { + state.byte_offset += ch.len_wtf8(); + }) + } + }); + Ok(PyIterReturn::from_result( + ch.map(|ch| ch.to_pyobject(vm)).ok_or(None), + )) + } +} - if let IterStatus::Active(s) = &internal.0.status { - let value = s.as_wtf8(); +#[pyclass(module = false, name = "str_ascii_iterator", traverse)] +#[derive(Debug)] +pub(crate) struct PyStrAsciiIterator { + internal: NativeSequenceIter, +} - if internal.1 == usize::MAX { - if let Some((offset, ch)) = value.code_point_indices().nth(internal.0.position) { - internal.0.position += 1; - internal.1 = offset + ch.len_wtf8(); - return Ok(PyIterReturn::Return(ch.to_pyobject(vm))); - } - } else if let Some(value) = value.get(internal.1..) - && let Some(ch) = value.code_points().next() - { - internal.0.position += 1; - internal.1 += ch.len_wtf8(); - return Ok(PyIterReturn::Return(ch.to_pyobject(vm))); - } - let released = internal.0.exhaust(); - // The string is released after the lock. A `__del__` that iterates - // again would otherwise reach for a lock this call still holds. - drop(internal); - drop(released); - } - Ok(PyIterReturn::StopIteration(None)) +impl PyPayload for PyStrAsciiIterator { + fn class(ctx: &Context) -> &'static Py { + ctx.types.str_ascii_iterator_type + } +} + +#[pyclass(flags(DISALLOW_INSTANTIATION), with(IterNext, Iterable))] +impl Py { + #[pymethod] + fn __length_hint__(&self) -> usize { + self.internal.length_hint(|string| string.byte_len()) + } + + #[pymethod] + fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + self.internal + .set_state(&object, |string| string.byte_len(), vm) + } + + #[pymethod] + fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { + let func = builtins_iter(vm)?; + Ok(self.internal.reduce( + func, + |string| string.into(), + |vm| vm.ctx.empty_str.to_owned().into(), + vm, + )) + } +} + +impl SelfIter for PyStrAsciiIterator {} + +impl IterNext for PyStrAsciiIterator { + fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let byte = zelf + .internal + .next(|string, index| string.as_bytes().get(index).copied()); + Ok(PyIterReturn::from_result( + byte.map(|byte| vm.ctx.latin1_char(byte).into()).ok_or(None), + )) } } @@ -391,15 +445,20 @@ pub struct StrArgs { #[pyarg(any, optional)] object: OptionalArg, #[pyarg(any, optional)] - encoding: OptionalArg, + encoding: OptionalArg, #[pyarg(any, optional)] - errors: OptionalArg, + errors: OptionalArg, } impl Constructor for PyStr { type Args = StrArgs; fn slot_new(cls: PyTypeRef, func_args: FuncArgs, vm: &VirtualMachine) -> PyResult { + // Preserve the keyword-free str_vectorcall arity diagnostic. + if func_args.kwargs.is_empty() && func_args.args.len() > 3 { + return Err(vm.new_arity_type_error(Self::NAME, 0..=3, func_args.args.len())); + } + // Optimization: return exact str as-is (only when no encoding/errors provided) if cls.is(vm.ctx.types.str_type) && func_args.args.len() == 1 @@ -434,34 +493,11 @@ impl Constructor for PyStr { match args.object { OptionalArg::Present(input) => { let encoding = args.encoding.into_option(); - let errors = args.errors.into_option(); + let errors = args.errors.into_option().map(ArgNulFreeStr::into_utf8_ref); // CPython parity: presence of `encoding` OR `errors` triggers // decode mode. When `errors` is given alone, the encoding // defaults to UTF-8. if encoding.is_some() || errors.is_some() { - // CPython rejects str / non-bytes-like input early with - // specific TypeError wording (unicode_new_impl). - if input.fast_isinstance(vm.ctx.types.str_type) { - return Err(vm.new_type_error("decoding str is not supported")); - } - let input = if input.fast_isinstance(vm.ctx.types.bytes_type) - || input.fast_isinstance(vm.ctx.types.bytearray_type) - { - input - } else { - // PyUnicode_FromEncodedObject: whatever an exporter - // complains about, the argument is simply not bytes-like. - let buffer = PyBuffer::from_object(vm, &input, BufferFlags::SIMPLE) - .map_err(|_| { - vm.new_type_error(format!( - "decoding to str: need a bytes-like object, {} found", - input.class().name() - )) - })?; - vm.ctx - .new_bytes(buffer.contiguous_or_collect(<[u8]>::to_vec)) - .into() - }; let enc_str = encoding.as_ref().map_or("utf-8", |e| e.as_str()); let s = vm .state @@ -709,7 +745,12 @@ impl PyStr { #[cold] fn _compute_hash(&self, _vm: &VirtualMachine) -> hash::PyHash { - let hash_val = crate::vm::hash_secret().hash_bytes(self.as_bytes()); + let secret = crate::vm::hash_secret(); + let hash_val = if self.kind().is_ascii() { + secret.hash_bytes(self.as_bytes()) + } else { + secret.hash_wtf8(self.as_wtf8()) + }; debug_assert_ne!(hash_val, hash::SENTINEL); // spell-checker:ignore cmpxchg // like with char_len, we don't need a cmpxchg loop, since it'll always be the same value @@ -791,9 +832,18 @@ impl PyStr { }) } let sep = zelf.as_wtf8(); - let mut len = sep.len().saturating_mul(items.len().saturating_sub(1)); + let mut len = 0usize; + let overflow = || vm.new_overflow_error("join() result is too long for a Python string"); for (i, obj) in items.iter().enumerate() { - len = len.saturating_add(item_str(i, obj, vm)?.as_wtf8().len()); + len = len + .checked_add(item_str(i, obj, vm)?.as_wtf8().len()) + .ok_or_else(overflow)?; + if i > 0 { + len = len.checked_add(sep.len()).ok_or_else(overflow)?; + } + if isize::try_from(len).is_err() { + return Err(overflow()); + } } if let [only] = items { let only = item_str(0, only, vm)?; @@ -801,7 +851,10 @@ impl PyStr { return Ok(only.to_owned()); } } - let mut joined = Wtf8Buf::with_capacity(len); + let mut joined = Wtf8Buf::new(); + joined + .try_reserve_exact(len) + .map_err(|_| vm.new_memory_error(""))?; for (i, obj) in items.iter().enumerate() { if i > 0 { joined.push_wtf8(sep); @@ -862,7 +915,7 @@ impl PyStr { } #[pyclass( - flags(BASETYPE, _MATCH_SELF), + flags(BASETYPE, _MATCH_SELF, UNICODE_SUBCLASS), with( AsMapping, AsNumber, @@ -875,6 +928,16 @@ impl PyStr { ) )] impl Py { + // `part` is a slice of this string. A full-length slice needs no copy, + // except when the operation must return a base str for a subclass. + fn result_from_slice(&self, part: &Wtf8, vm: &VirtualMachine) -> PyStrRef { + if part.len() == self.byte_len() { + PyStr::result_unchanged(self.to_owned(), vm) + } else { + vm.ctx.new_str(part) + } + } + #[pymethod] #[inline(always)] pub fn isascii(&self) -> bool { @@ -890,8 +953,8 @@ impl Py { fn lower(&self) -> PyStr { match self.as_str_kind() { PyKindStr::Ascii(s) => s.to_ascii_lowercase().into(), - PyKindStr::Utf8(s) => s.to_lowercase().into(), - PyKindStr::Wtf8(w) => w.to_lowercase().into(), + PyKindStr::Utf8(s) => case::lowercase_str(s).into(), + PyKindStr::Wtf8(w) => case::lowercase_wtf8(w).into(), } } @@ -913,8 +976,8 @@ impl Py { fn upper(&self) -> PyStr { match self.as_str_kind() { PyKindStr::Ascii(s) => s.to_ascii_uppercase().into(), - PyKindStr::Utf8(s) => s.to_uppercase().into(), - PyKindStr::Wtf8(w) => w.to_uppercase().into(), + PyKindStr::Utf8(s) => case::uppercase_str(s).into(), + PyKindStr::Wtf8(w) => case::uppercase_wtf8(w).into(), } } @@ -1068,18 +1131,15 @@ impl Py { } #[pymethod] - fn endswith(&self, options: anystr::StartsEndsWithArgs, vm: &VirtualMachine) -> PyResult { - let (affix, substr) = match options.prepare(self.as_wtf8(), self.len(), |s, r| { - &s[self.data.char_range_to_bytes(r)] - }) { - Some(x) => x, - None => return Ok(false), - }; - substr.py_starts_ends_with( - &affix, + fn endswith(&self, options: anystr::EndsWithArgs, vm: &VirtualMachine) -> PyResult { + options.inner.matches( + self.len(), "endswith", "str", - |s, x: &Self| s.ends_with(x.as_wtf8()), + |affix: &Self, range| { + self.char_range_bytes(range.unwrap_or_else(|| 0..self.len())) + .is_some_and(|(_, text)| text.ends_with(affix.as_wtf8())) + }, vm, ) } @@ -1090,33 +1150,32 @@ impl Py { options: anystr::StartsEndsWithArgs, vm: &VirtualMachine, ) -> PyResult { - let (affix, substr) = match options.prepare(self.as_wtf8(), self.len(), |s, r| { - &s[self.data.char_range_to_bytes(r)] - }) { - Some(x) => x, - None => return Ok(false), - }; - substr.py_starts_ends_with( - &affix, + options.matches( + self.len(), "startswith", "str", - |s, x: &Self| s.starts_with(x.as_wtf8()), + |affix: &Self, range| { + self.char_range_bytes(range.unwrap_or_else(|| 0..self.len())) + .is_some_and(|(_, text)| text.starts_with(affix.as_wtf8())) + }, vm, ) } #[pymethod] - fn removeprefix(&self, prefix: PyStrRef) -> Wtf8Buf { - self.as_wtf8() - .py_removeprefix(prefix.as_wtf8(), prefix.byte_len(), |s, p| s.starts_with(p)) - .to_owned() + fn removeprefix(&self, prefix: PyStrRef, vm: &VirtualMachine) -> PyStrRef { + let part = self + .as_wtf8() + .py_removeprefix(prefix.as_wtf8(), prefix.byte_len(), |s, p| s.starts_with(p)); + self.result_from_slice(part, vm) } #[pymethod] - fn removesuffix(&self, suffix: PyStrRef) -> Wtf8Buf { - self.as_wtf8() - .py_removesuffix(suffix.as_wtf8(), suffix.byte_len(), |s, p| s.ends_with(p)) - .to_owned() + fn removesuffix(&self, suffix: PyStrRef, vm: &VirtualMachine) -> PyStrRef { + let part = self + .as_wtf8() + .py_removesuffix(suffix.as_wtf8(), suffix.byte_len(), |s, p| s.ends_with(p)); + self.result_from_slice(part, vm) } #[pymethod] @@ -1167,11 +1226,11 @@ impl Py { }; } let zelf = zelf.try_into_utf8(vm)?; - let s = FormatSpec::parse(format_spec.as_str()) - .and_then(|format_spec| { - format_spec.format_string(&CharLenStr(zelf.as_str(), zelf.char_len())) - }) - .map_err(|err| err.into_pyexception(vm))?; + let s = crate::format::parse_format_spec(zelf.as_object(), format_spec.as_str(), vm)? + .format_string(&CharLenStr(zelf.as_str(), zelf.char_len())) + .map_err(|err| { + crate::format::format_spec_error(err, zelf.as_object(), format_spec.as_str(), vm) + })?; Ok(vm.ctx.new_str(s)) } @@ -1204,28 +1263,53 @@ impl Py { } #[pymethod] - fn replace(zelf: PyRef, args: ReplaceArgs, vm: &VirtualMachine) -> PyRef { + fn replace( + zelf: PyRef, + args: ReplaceArgs, + vm: &VirtualMachine, + ) -> PyResult> { let ReplaceArgs { old, new, count } = args; if count == 0 || old.byte_len() > zelf.byte_len() || old.as_wtf8() == new.as_wtf8() { - return PyStr::result_unchanged(zelf, vm); + return Ok(PyStr::result_unchanged(zelf, vm)); } let s = zelf.as_wtf8(); - let replaced = if count < 0 { - s.replace(old.as_wtf8(), new.as_wtf8()) + let limit = if count < 0 { + usize::MAX } else { - let s_is_empty = s.is_empty(); - let old_is_empty = old.is_empty(); - - if s_is_empty && !old_is_empty { - s.to_owned() - } else if s_is_empty && old_is_empty { - new.as_wtf8().to_owned() + count as usize + }; + let capacity = if new.byte_len() > old.byte_len() { + let matches = if old.is_empty() { + (zelf.char_len() + 1).min(limit) } else { - s.replacen(old.as_wtf8(), new.as_wtf8(), count as usize) + s.find_iter(old.as_wtf8()).take(limit).count() + }; + anystr::checked_replace_len(s.len(), old.byte_len(), new.byte_len(), matches) + .ok_or_else(|| vm.new_overflow_error("replace string is too long"))? + } else { + s.len() + }; + let replaced = if old.is_empty() { + s.replacen(old.as_wtf8(), new.as_wtf8(), limit) + } else { + let mut matches = s.find_iter(old.as_wtf8()).take(limit); + let Some(first) = matches.next() else { + drop(matches); + return Ok(PyStr::result_unchanged(zelf, vm)); + }; + let mut result = Vec::with_capacity(capacity); + let mut last = 0; + for start in core::iter::once(first).chain(matches) { + result.extend_from_slice(&s.as_bytes()[last..start]); + result.extend_from_slice(new.as_bytes()); + last = start + old.byte_len(); } + result.extend_from_slice(&s.as_bytes()[last..]); + // SAFETY: A nonempty WTF-8 needle matches only at code point boundaries. + unsafe { Wtf8Buf::from_bytes_unchecked(result) } }; - vm.ctx.new_str(replaced) + Ok(vm.ctx.new_str(replaced)) } #[pymethod] @@ -1336,40 +1420,41 @@ impl Py { #[pymethod] pub fn partition(&self, sep: PyStrRef, vm: &VirtualMachine) -> PyResult { - let (front, has_mid, back) = self.as_wtf8().py_partition( - sep.as_wtf8(), - || self.as_wtf8().splitn(2, sep.as_wtf8()), - vm, - )?; - let partition = ( - self.new_substr(front), - if has_mid { - sep - } else { - vm.ctx.new_str(ascii!("")) - }, - self.new_substr(back), - ); - Ok(partition.to_pyobject(vm)) + self.partition_inner(sep, false, vm) } #[pymethod] pub fn rpartition(&self, sep: PyStrRef, vm: &VirtualMachine) -> PyResult { - let (back, has_mid, front) = self.as_wtf8().py_partition( - sep.as_wtf8(), - || self.as_wtf8().rsplitn(2, sep.as_wtf8()), - vm, - )?; - Ok(( - self.new_substr(front), - if has_mid { - sep + self.partition_inner(sep, true, vm) + } + + fn partition_inner(&self, sep: PyStrRef, reverse: bool, vm: &VirtualMachine) -> PyResult { + if sep.is_empty() { + return Err(vm.new_value_error("empty separator")); + } + let text = self.as_wtf8(); + let index = if reverse { + text.rfind(sep.as_wtf8()) + } else { + text.find(sep.as_wtf8()) + }; + let parts = if let Some(index) = index { + ( + vm.ctx.new_str(&text[..index]), + sep.clone(), + vm.ctx.new_str(&text[index + sep.byte_len()..]), + ) + } else { + let empty = vm.ctx.empty_str.to_owned(); + // partition preserves the original object, including a subclass, + // when there is no separator. + if reverse { + (empty.clone(), empty, self.to_owned()) } else { - vm.ctx.empty_str.to_owned() - }, - self.new_substr(back), - ) - .to_pyobject(vm)) + (self.to_owned(), empty.clone(), empty) + } + }; + Ok(parts.to_pyobject(vm)) } #[pymethod] @@ -1381,13 +1466,13 @@ impl Py { let mut cased = false; let mut previous_is_cased = false; for c in self.as_wtf8().code_points().map(CodePoint::to_char_lossy) { - if c.is_uppercase() || case::is_titlecase(c) { + if case::is_uppercase(c) || case::is_titlecase(c) { if previous_is_cased { return false; } previous_is_cased = true; cased = true; - } else if c.is_lowercase() { + } else if case::is_lowercase(c) { if !previous_is_cased { return false; } @@ -1443,8 +1528,19 @@ impl Py { } #[pymethod] - fn expandtabs(&self, args: anystr::ExpandTabsArgs) -> Wtf8Buf { - rustpython_common::str::expandtabs(self.as_wtf8(), args.tabsize()) + fn expandtabs(&self, args: anystr::ExpandTabsArgs, vm: &VirtualMachine) -> PyResult { + let capacity = anystr::checked_expandtabs_len( + self.byte_len(), + self.as_wtf8().code_points().map(|ch| ch.to_u32()), + args.tabsize(), + ) + .ok_or_else(|| vm.new_overflow_error("new string is too long"))?; + let mut result = Wtf8Buf::new(); + result + .try_reserve_exact(capacity) + .map_err(|_| vm.new_memory_error(""))?; + rustpython_common::str::expandtabs_into(self.as_wtf8(), args.tabsize(), &mut result); + Ok(result) } #[pymethod] @@ -1498,20 +1594,20 @@ impl Py { #[pystaticmethod] fn maketrans( - dict_or_str: PyObjectRef, - to_str: OptionalArg, - none_str: OptionalArg, + x: PyObjectRef, + y: OptionalArg, + z: OptionalArg, vm: &VirtualMachine, ) -> PyResult { let new_dict = vm.ctx.new_dict(); - if let OptionalArg::Present(to_str) = to_str { - match dict_or_str.downcast::() { + if let OptionalArg::Present(y) = y { + match x.downcast::() { Ok(from_str) => { - if to_str.len() == from_str.len() { + if y.len() == from_str.len() { for (c1, c2) in from_str .as_wtf8() .code_points() - .zip(to_str.as_wtf8().code_points()) + .zip(y.as_wtf8().code_points()) { new_dict.set_item( &*vm.new_pyobj(c1.to_u32()), @@ -1519,8 +1615,8 @@ impl Py { vm, )?; } - if let OptionalArg::Present(none_str) = none_str { - for c in none_str.as_wtf8().code_points() { + if let OptionalArg::Present(z) = z { + for c in z.as_wtf8().code_points() { new_dict.set_item(&*vm.new_pyobj(c.to_u32()), vm.ctx.none(), vm)?; } } @@ -1536,17 +1632,14 @@ impl Py { )), } } else { - // dict_str must be a dict - match dict_or_str.downcast::() { - Ok(dict) => { + // The single-argument form accepts exact dict and frozendict objects. + match PyAnyDict::from_object(&x).filter(|_| { + x.class().is(vm.ctx.types.dict_type) || x.class().is(vm.ctx.types.frozendict_type) + }) { + Some(dict) => { for (key, val) in dict { - // FIXME: ints are key-compatible - if let Some(num) = key.downcast_ref::() { - new_dict.set_item( - &*num.as_bigint().to_i32().to_pyobject(vm), - val, - vm, - )?; + if key.downcast_ref::().is_some() { + new_dict.set_item(&*key, val, vm)?; } else if let Some(string) = key.downcast_ref::() { if string.len() == 1 { let num_value = @@ -1565,7 +1658,7 @@ impl Py { } Ok(new_dict.to_pyobject(vm)) } - _ => Err(vm.new_value_error( + _ => Err(vm.new_type_error( "if you give only one argument to maketrans it must be a dict", )), } @@ -1573,8 +1666,13 @@ impl Py { } #[pymethod] - fn encode(zelf: PyRef, args: EncodeArgs, vm: &VirtualMachine) -> PyResult { - encode_string(zelf, args.encoding.as_deref(), args.errors, vm) + fn encode( + zelf: PyRef, + args: TextCodecArgs, + vm: &VirtualMachine, + ) -> PyResult { + let (encoding, errors) = args.into_parts(); + encode_string(zelf, encoding.as_deref(), errors, vm) } #[pymethod] @@ -1678,8 +1776,21 @@ impl Comparable for PyStr { impl Iterable for PyStr { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + if zelf.class().is(vm.ctx.types.str_type) && zelf.isascii() { + return Ok(PyStrAsciiIterator { + internal: NativeSequenceIter::new(zelf, NativeIterKind::Sequence, 0), + } + .into_pyobject(vm)); + } Ok(PyStrIterator { - internal: PyMutex::new((PositionIterInternal::new(zelf, 0), 0)), + internal: NativeSequenceIter::new( + StrIterState { + string: zelf, + byte_offset: 0, + }, + NativeIterKind::Sequence, + 0, + ), } .into_pyobject(vm)) } @@ -1739,16 +1850,6 @@ impl AsSequence for PyStr { } } -#[derive(FromArgs)] -struct EncodeArgs { - // None is filled in as utf-8 when encoding. - #[pyarg(any, optional, py_default = "'utf-8'")] - encoding: Option, - // None is filled in as strict when encoding. - #[pyarg(any, optional, py_default = "'strict'")] - errors: Option, -} - #[derive(FromArgs)] struct StripArgs { #[pyarg(positional, optional)] @@ -1867,18 +1968,23 @@ impl ToPyObject for AsciiChar { type SplitArgs = anystr::SplitArgs; #[derive(FromArgs)] +#[from_args(text_signature = "(sub[, start[, end]], /)")] pub(crate) struct FindArgs { #[pyarg(positional)] sub: PyStrRef, #[pyarg(positional, default)] - start: Option, + start: Option, #[pyarg(positional, default)] - end: Option, + end: Option, } impl FindArgs { fn get_value(self, len: usize) -> (PyStrRef, core::ops::Range) { - let range = adjust_indices(self.start.as_deref(), self.end.as_deref(), len); + let range = adjust_indices( + self.start.as_ref().map(AsRef::as_ref), + self.end.as_ref().map(AsRef::as_ref), + len, + ); (self.sub, range) } } @@ -1912,10 +2018,11 @@ pub(crate) fn init(ctx: &'static Context) { ctx.types .str_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_str)); PyStrIterator::extend_class(ctx, ctx.types.str_iterator_type); + PyStrAsciiIterator::extend_class(ctx, ctx.types.str_ascii_iterator_type); } impl PyStr { @@ -2771,7 +2878,11 @@ mod tests { .unwrap(); table.set_item("b", vm.ctx.none(), vm).unwrap(); table - .set_item("c", vm.ctx.new_str(ascii!("xda")).into(), vm) + .set_item( + "c", + vm.ctx.new_str(rustpython_common::ascii!("xda")).into(), + vm, + ) .unwrap(); let translated = Py::::maketrans( table.into(), diff --git a/crates/vm/src/builtins/super.rs b/crates/vm/src/builtins/super.rs index 9eb76e9df0e..c1cbdd35de4 100644 --- a/crates/vm/src/builtins/super.rs +++ b/crates/vm/src/builtins/super.rs @@ -90,6 +90,15 @@ pub struct InitArgs { impl Initializer for PySuper { type Args = InitArgs; + fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + let zelf = zelf.try_to_ref::(vm)?; + // Reject keywords before either positional arity or type conversion. + if !args.kwargs.is_empty() { + return Err(vm.new_type_error("super() takes no keyword arguments")); + } + Self::init(zelf, args.bind_for(vm, "super")?, vm) + } + fn init( zelf: &Py, Self::Args { py_type, object }: Self::Args, @@ -169,17 +178,15 @@ fn super_init_without_args(vm: &VirtualMachine) -> PyResult<(PyTypeRef, PyObject .and_then(|c| c.get()) .ok_or_else(|| vm.new_runtime_error("super(): empty __class__ cell"))?; typ = Some(class.downcast().map_err(|o| { - vm.new_type_error(format!( + vm.new_runtime_error(format!( "super(): __class__ is not a type ({})", - o.class().name() + o.class().slot_name() )) })?); break; } } - let typ = typ.ok_or_else(|| { - vm.new_type_error("super must be called with 1 argument or from inside class method") - })?; + let typ = typ.ok_or_else(|| vm.new_runtime_error("super(): __class__ cell not found"))?; Ok((typ, obj)) } @@ -206,37 +213,39 @@ impl GetAttr for PySuper { return skip(zelf, name); } - if let Some(name) = vm.ctx.interned_str(name) { - // Walk start_type's MRO by reference (no Vec allocation, no - // per-class clone) up to and including zelf.typ, then look for - // the first class past it that declares `name` directly. - // Both locks are dropped before any arbitrary Python code - // (the descriptor call below) runs, so they can't be held - // across a call that might re-enter and want them again. - let Some(su_type) = zelf.typ.load_owned() else { - return skip(zelf, name); - }; - let descr = { - let mro = start_type.mro.read(); - mro.iter() - .skip_while(|cls| !cls.is(&su_type)) - .skip(1) // skip su->type (if any) - .find_map(|cls| cls.get_direct_attr(name)) - }; - if let Some(descr) = descr { - return vm - .call_get_descriptor_specific( - &descr, - // Only pass 'obj' param if this is instance-mode super (See https://bugs.python.org/issue743267) - if obj.is(&start_type) { - None - } else { - Some(&obj) - }, - Some(start_type.as_object()), - ) - .unwrap_or(Ok(descr)); + let Some(su_type) = zelf.typ.load_owned() else { + return skip(zelf, name); + }; + let descr = { + // Dictionary key callbacks can replace the MRO. Keep its original + // members alive without holding the MRO lock while callbacks run. + let mro = start_type.mro.read().clone(); + let mut descr = None; + for cls in mro.iter().skip_while(|cls| !cls.is(&su_type)).skip(1) { + // Keep the original query object so str-subclass hash/equality + // overrides run, and fresh names reach live class dictionaries. + // Raw lookup must propagate failures rather than try super's + // own attributes or a dictionary subclass's __missing__. + descr = cls.attributes.get_item_opt(name.as_object(), vm)?; + if descr.is_some() { + break; + } } + descr + }; + if let Some(descr) = descr { + return vm + .call_get_descriptor_specific( + &descr, + // Only pass 'obj' param if this is instance-mode super (See https://bugs.python.org/issue743267) + if obj.is(&start_type) { + None + } else { + Some(&obj) + }, + Some(start_type.as_object()), + ) + .unwrap_or(Ok(descr)); } skip(zelf, name) } @@ -275,11 +284,15 @@ impl Representable for PySuper { #[inline] fn repr_str(zelf: &Py, _vm: &VirtualMachine) -> PyResult { let type_name = match zelf.typ.load_owned() { - Some(ty) => ty.name().to_owned(), + Some(ty) => ty.slot_name().to_owned(), None => "NULL".to_owned(), }; let repr = match zelf.obj_type.load_owned() { - Some(ty) => format!(", <{} object>>", type_name, ty.name()), + Some(ty) => format!( + ", <{} object>>", + type_name, + ty.slot_name() + ), None => format!(", NULL>"), }; Ok(repr) @@ -297,8 +310,8 @@ fn super_check(ty: &Py, obj: &PyObject, vm: &VirtualMachine) -> PyResult return Ok(obj.class().to_owned()); } - let class_attr = obj.get_attr("__class__", vm)?; - if let Ok(cls) = class_attr.downcast::() + if let Some(class_attr) = vm.get_attribute_opt(obj, identifier!(vm, __class__))? + && let Ok(cls) = class_attr.downcast::() && !cls.is(obj.class()) && cls.fast_issubclass(ty) { @@ -306,16 +319,20 @@ fn super_check(ty: &Py, obj: &PyObject, vm: &VirtualMachine) -> PyResult } let (type_or_instance, obj_str) = match typ { - Some(t) => ("type", t.name().to_owned()), - None => ("instance of", obj.class().name().to_owned()), + Some(t) => ("type", t.slot_name().to_owned()), + None => ("instance of", obj.class().slot_name().to_owned()), }; - Err(vm.new_type_error(format!( - "super(type, obj): obj ({} {}) is not an instance or subtype of type ({}).", - type_or_instance, - obj_str, - ty.name(), - ))) + let message = { + let type_name = ty.slot_name(); + format!( + "super(type, obj): obj ({} {}) is not an instance or subtype of type ({}).", + type_or_instance, + &obj_str[..obj_str.floor_char_boundary(200)], + &type_name[..type_name.floor_char_boundary(200)], + ) + }; + Err(vm.new_type_error(message)) } pub(crate) fn init(context: &'static Context) { diff --git a/crates/vm/src/builtins/template.rs b/crates/vm/src/builtins/template.rs index b072f4afc81..f0b6531bba3 100644 --- a/crates/vm/src/builtins/template.rs +++ b/crates/vm/src/builtins/template.rs @@ -7,12 +7,9 @@ use crate::{ atomic_func, class::{PyClassDef, PyClassImpl}, common::lock::LazyLock, - function::{FuncArgs, PyComparisonValue}, + function::FuncArgs, protocol::{PyIterReturn, PySequenceMethods}, - types::{ - AsSequence, Comparable, Constructor, IterNext, Iterable, PyComparisonOp, Representable, - SelfIter, - }, + types::{AsSequence, Constructor, IterNext, Iterable, Representable, SelfIter}, }; use rustpython_common::wtf8::{Wtf8Buf, wtf8_concat}; @@ -76,9 +73,9 @@ impl Constructor for PyTemplate { interpolations.push(item.clone()); last_was_str = false; } else { - return Err(vm.new_type_error(format!( - "Template.__new__ *args need to be of type 'str' or 'Interpolation', got {}", - item.class().name() + return Err(vm.new_type_error(wtf8_concat!( + "Template.__new__ *args need to be of type 'str' or 'Interpolation', got ", + item.class().fully_qualified_name(vm)?, ))); } } @@ -97,13 +94,16 @@ impl Constructor for PyTemplate { impl PyTemplate { fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult> { - let other = other.downcast_ref::().ok_or_else(|| { - vm.new_type_error(format!( - r#"can only concatenate {name} (not "{}") to {name}"#, - other.class().slot_name(), - name = Self::TP_NAME, - )) - })?; + let Some(other) = other.downcast_ref::() else { + return Err(vm.new_type_error(wtf8_concat!( + "can only concatenate ", + Self::TP_NAME, + " (not \"", + other.class().fully_qualified_name(vm)?, + "\") to ", + Self::TP_NAME, + ))); + }; // Concatenate the two templates let mut new_strings: Vec = Vec::new(); @@ -163,7 +163,7 @@ impl PyTemplate { } } -#[pyclass(with(Constructor, Comparable, Iterable, Representable, AsSequence))] +#[pyclass(with(Constructor, Iterable, Representable, AsSequence))] impl Py { #[pygetset] fn values(&self, vm: &VirtualMachine) -> PyTupleRef { @@ -220,27 +220,6 @@ impl AsSequence for PyTemplate { } } -impl Comparable for PyTemplate { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - op.eq_only(|| { - let other = class_or_notimplemented!(Self, other); - - let eq = vm.bool_eq(zelf.strings.as_object(), other.strings.as_object())? - && vm.bool_eq( - zelf.interpolations.as_object(), - other.interpolations.as_object(), - )?; - - Ok(eq.into()) - }) - } -} - impl Iterable for PyTemplate { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { Ok(PyTemplateIter::new(zelf).into_pyobject(vm)) diff --git a/crates/vm/src/builtins/traceback.rs b/crates/vm/src/builtins/traceback.rs index a91ec13c86f..4010392a9e7 100644 --- a/crates/vm/src/builtins/traceback.rs +++ b/crates/vm/src/builtins/traceback.rs @@ -45,7 +45,7 @@ impl PyTraceback { } } -#[pyclass(with(Constructor))] +#[pyclass(with(Constructor), flags(IMMUTABLETYPE))] impl Py { #[pygetset] fn tb_lineno(&self) -> usize { @@ -92,19 +92,37 @@ impl Py { } } } - *zelf.next.lock() = value; + // Dropping the old chain can finalize a frame whose locals reenter + // this traceback. Publish the replacement before releasing the lock. + let _old = core::mem::replace(&mut *zelf.next.lock(), value); Ok(()) } } +#[derive(FromArgs)] +pub struct TracebackArgs { + #[pyarg(any)] + tb_next: Option>, + #[pyarg(any)] + tb_frame: FrameObjectRef, + #[pyarg(any)] + tb_lasti: i32, + #[pyarg(any)] + tb_lineno: usize, +} + impl Constructor for PyTraceback { - type Args = (Option>, FrameObjectRef, i32, usize); + type Args = TracebackArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let (next, frame, lasti, lineno) = args; - let lineno = - OneIndexed::new(lineno).ok_or_else(|| vm.new_value_error("lineno must be positive"))?; - Ok(Self::new(next, frame, lasti, lineno)) + let lineno = OneIndexed::new(args.tb_lineno) + .ok_or_else(|| vm.new_value_error("lineno must be positive"))?; + Ok(Self::new( + args.tb_next, + args.tb_frame, + args.tb_lasti, + lineno, + )) } } @@ -128,7 +146,7 @@ impl serde::Serialize for PyTraceback { struc.serialize_field("lineno", &self.lineno.get())?; struc.serialize_field( "filename", - self.frame.iframe().code().source_path().as_str(), + &self.frame.iframe().code().source_path().to_string_lossy(), )?; struc.end() } diff --git a/crates/vm/src/builtins/tuple.rs b/crates/vm/src/builtins/tuple.rs index a1c06e49106..9b38b5a28ba 100644 --- a/crates/vm/src/builtins/tuple.rs +++ b/crates/vm/src/builtins/tuple.rs @@ -1,23 +1,22 @@ -use super::{ - PositionIterInternal, PyGenericAlias, PyInt, PyStrRef, PyType, PyTypeRef, iter::builtins_iter, - locked_next, -}; +use super::native_iter::{NativeIterKind, NativeSequenceIter}; +use super::{PyGenericAlias, PyInt, PyList, PyStrRef, PyType, PyTypeRef, iter::builtins_iter}; +use crate::common::atomic::{Ordering, PyAtomic, Radium}; use crate::common::lock::LazyLock; -use crate::common::{hash, hash::PyHash, lock::PyMutex, wtf8::wtf8_concat}; -use crate::object::{Traverse, TraverseFn}; +use crate::common::{hash, hash::PyHash, wtf8::wtf8_concat}; +use crate::object::{PyTypedRefTarget, Traverse, TraverseFn}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, atomic_func, class::{PyClassDef, PyClassImpl}, convert::{ToPyObject, TransmuteFromObject}, - function::{FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue, PySsize}, + function::{Either, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue, PySsize}, iter::PyExactSizeIterator, - protocol::{PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, + protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods}, recursion::ReprGuard, sequence::{OptionalRangeArgs, SequenceExt}, - sliceable::{SequenceIndex, SliceableSequenceOp}, + sliceable::{NameTuple, SequenceIndex, SliceableSequenceOp}, types::{ - AsMapping, AsNumber, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable, + AsMapping, AsSequence, Comparable, Constructor, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SelfIter, }, utils::collection_repr, @@ -25,40 +24,55 @@ use crate::{ }; use alloc::fmt; use core::cell::{Cell, UnsafeCell}; +use core::marker::PhantomData; +use core::mem::ManuallyDrop; use core::ptr::NonNull; #[pyclass(module = false, name = "tuple", traverse = "manual")] +#[repr(C)] pub struct PyTuple { elements: TupleElements, + hash: PyAtomic, } /// Tuple storage is immutable after publication, but marshal must publish a /// tuple in its reference table before recursively reading its children. /// This mirrors CPython's `PyTuple_New` followed by `PyTuple_SET_ITEM`. -struct TupleElements(UnsafeCell>); +// Every allocation stores erased owners, including when borrowed through a +// typed tuple view. The marker preserves the old storage's invariance and +// ownership relationship to R. +// Safe constructors and checked view conversions only admit R = PyRef, +// and establish each element's target invariant before publishing that view. +#[repr(transparent)] +struct TupleElements(UnsafeCell>, PhantomData>); unsafe impl Send for TupleElements {} unsafe impl Sync for TupleElements {} impl TupleElements { - const fn new(elements: Box<[R]>) -> Self { - Self(UnsafeCell::new(elements)) + fn as_slice(&self) -> &[R] { + // SAFETY: all admitted R are transparent PyRef owners with the same + // size/alignment as PyObjectRef. Their element invariants were proven + // by construction or checked conversion. Published elements cannot be + // replaced, and the returned shared slice borrows this storage. + let elements = unsafe { &*self.0.get() }; + unsafe { core::slice::from_raw_parts(elements.as_ptr().cast(), elements.len()) } } +} - fn as_slice(&self) -> &[R] { - // SAFETY: initialization writes happen only while the tuple is owned by - // the synchronous marshal decoder; afterwards the storage is immutable. - unsafe { &*self.0.get() } +impl TupleElements { + const fn new(elements: Box<[PyObjectRef]>) -> Self { + Self(UnsafeCell::new(elements), PhantomData) } - fn get_mut(&mut self) -> &mut Box<[R]> { + fn get_mut(&mut self) -> &mut Box<[PyObjectRef]> { self.0.get_mut() } /// # Safety /// The tuple must still be in its private initialization phase, and each /// placeholder index must be replaced at most once before it is observable. - unsafe fn set_initializing(&self, index: usize, value: R) { + unsafe fn set_initializing(&self, index: usize, value: PyObjectRef) { unsafe { (*self.0.get())[index] = value }; } } @@ -118,6 +132,7 @@ thread_local! { impl PyPayload for PyTuple { const MAX_FREELIST: usize = 2000; const HAS_FREELIST: bool = true; + const REVERSE_DEALLOC: bool = true; #[inline] fn class(ctx: &Context) -> &'static Py { @@ -249,19 +264,12 @@ impl Constructor for PyTuple { }; let iterable = parsed.iterable; - // Optimizations for exact tuple type if cls.is(vm.ctx.types.tuple_type) { - // Return exact tuple as-is - if let OptionalArg::Present(ref input) = iterable - && let Ok(tuple) = input.clone().downcast_exact::(vm) - { - return Ok(tuple.into_pyref().into()); - } - - // Return empty tuple singleton - if iterable.is_missing() { - return Ok(vm.ctx.empty_tuple.clone().into()); - } + let tuple = match iterable { + OptionalArg::Present(input) => Self::from_sequence(&input, vm)?, + OptionalArg::Missing => vm.ctx.empty_tuple.clone(), + }; + return Ok(tuple.into()); } let elements = if let OptionalArg::Present(iterable) = iterable { @@ -270,11 +278,6 @@ impl Constructor for PyTuple { vec![] }; - // Return empty tuple singleton for exact tuple types (when iterable was empty) - if elements.is_empty() && cls.is(vm.ctx.types.tuple_type) { - return Ok(vm.ctx.empty_tuple.clone().into()); - } - let payload = Self::from_elements(elements); payload.into_ref_with_type(vm, cls).map(Into::into) } @@ -290,9 +293,25 @@ impl Constructor for PyTuple { } impl PyTuple { + /// Convert a sequence to an exact tuple without querying length hints. + pub(crate) fn from_sequence(value: &PyObject, vm: &VirtualMachine) -> PyResult { + if let Some(tuple) = value.downcast_ref_if_exact::(vm) { + return Ok(tuple.to_owned()); + } + let elements = if let Some(list) = value.downcast_ref_if_exact::(vm) { + list.borrow_vec().to_vec() + } else { + // Subclasses must use their iterator. Neither the iterable nor + // its iterator is asked for a length hint by PySequence_Tuple. + value.try_to_value(vm)? + }; + Ok(Self::new_ref(elements, &vm.ctx)) + } + fn from_elements(elements: Vec) -> Self { Self { elements: TupleElements::new(elements.into_boxed_slice()), + hash: PyAtomic::::new(hash::SENTINEL), } } } @@ -346,6 +365,7 @@ impl PyTuple { PyRef::new_ref( Self { elements: TupleElements::new(elements), + hash: PyAtomic::::new(hash::SENTINEL), }, ctx.types.tuple_type.to_owned(), None, @@ -360,6 +380,7 @@ impl PyTuple { pub const fn new_unchecked(elements: Box<[PyObjectRef]>) -> Self { Self { elements: TupleElements::new(elements), + hash: PyAtomic::::new(hash::SENTINEL), } } @@ -384,6 +405,7 @@ impl PyTuple { let elements = v.into_boxed_slice(); Self { elements: TupleElements::new(elements), + hash: PyAtomic::::new(hash::SENTINEL), } .into_ref(&vm.ctx) }) @@ -398,6 +420,38 @@ impl Py> { } impl Py { + fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { + SequenceIndex::Int(i) => { + let index = self + .elements + .wrap_index(i) + .ok_or_else(|| vm.new_index_error("tuple index out of range"))?; + Ok(self.elements[index].clone()) + } + SequenceIndex::Slice(slice) => { + let len = self.as_slice().len(); + let (range, step, slice_len) = slice.adjust_indices(len); + if slice_len != 0 + && range.start == 0 + && step == 1 + && slice_len == len + && self.class().is(vm.ctx.types.tuple_type) + { + Ok(self.to_owned().into()) + } else { + self.elements + .getitem_by_slice(vm, slice) + .map(|x| vm.ctx.new_tuple(x).into()) + } + } + } + } + + fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { + self._getitem(needle, vm) + } + pub fn extract_tuple<'a, T: FromPyTuple<'a>>(&'a self, vm: &VirtualMachine) -> PyResult { T::from_pytuple(self, vm) } @@ -410,8 +464,14 @@ impl PyTuple> { ) -> PyRef { // SAFETY: PyRef has the same layout as PyObjectRef. unsafe { - let elements: Vec = - core::mem::transmute::>, Vec>(elements); + let mut elements = ManuallyDrop::new(elements); + // Preserve the buffer, length and capacity without assuming Vec's + // field order. Each transparent owner transfers its one reference. + let elements = Vec::from_raw_parts( + elements.as_mut_ptr().cast::(), + elements.len(), + elements.capacity(), + ); let tuple = PyRef::new_ref( PyTuple::new_unchecked(elements.into_boxed_slice()), tuple_type, @@ -424,8 +484,14 @@ impl PyTuple> { pub fn new_ref_typed(elements: Vec>, ctx: &Context) -> PyRef { // SAFETY: PyRef has the same layout as PyObjectRef unsafe { - let elements: Vec = - core::mem::transmute::>, Vec>(elements); + let mut elements = ManuallyDrop::new(elements); + // Preserve the buffer, length and capacity without assuming Vec's + // field order. Each transparent owner transfers its one reference. + let elements = Vec::from_raw_parts( + elements.as_mut_ptr().cast::(), + elements.len(), + elements.capacity(), + ); let tuple = PyTuple::::new_ref(elements, ctx); core::mem::transmute::, PyRef>(tuple) } @@ -452,6 +518,7 @@ impl PyTuple { .collect::>(); Self { elements: TupleElements::new(elements), + hash: PyAtomic::::new(hash::SENTINEL), } .into_ref(&vm.ctx) } @@ -469,26 +536,6 @@ impl PyTuple { Self::repeat(zelf, value, vm) } - fn _getitem(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - match SequenceIndex::try_from_borrowed_object(vm, needle, "tuple")? { - SequenceIndex::Int(i) => { - let index = self - .elements - .wrap_index(i) - .ok_or_else(|| vm.new_index_error("tuple index out of range"))?; - Ok(self.elements[index].clone()) - } - SequenceIndex::Slice(slice) => self - .elements - .getitem_by_slice(vm, slice) - .map(|x| vm.ctx.new_tuple(x).into()), - } - } - - fn __getitem__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - self._getitem(needle, vm) - } - fn _contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { for element in &self.elements { if vm.identical_or_equal(element, needle)? { @@ -505,8 +552,8 @@ impl PyTuple { #[pyclass( itemsize = core::mem::size_of::(), - flags(BASETYPE, SEQUENCE, _MATCH_SELF), - with(AsMapping, AsNumber, AsSequence, Hashable, Comparable, Iterable, Constructor, Representable) + flags(BASETYPE, SEQUENCE, _MATCH_SELF, TUPLE_SUBCLASS), + with(AsMapping, AsSequence, Hashable, Comparable, Iterable, Constructor, Representable) )] impl Py { #[pymethod] @@ -527,8 +574,14 @@ impl Py { range: OptionalRangeArgs, vm: &VirtualMachine, ) -> PyResult { - let (start, stop) = range.saturate(self.as_slice().len(), vm)?; - for (index, element) in self.as_slice().iter().enumerate().take(stop).skip(start) { + let bounds = range.index_range(|| self.as_slice().len(), vm)?; + for (index, element) in self + .as_slice() + .iter() + .enumerate() + .take(bounds.end) + .skip(bounds.start) + { if vm.identical_or_equal(element, &value)? { return Ok(index); } @@ -565,9 +618,9 @@ impl AsMapping for PyTuple { length: atomic_func!(|mapping, _vm| { Ok(PyTuple::mapping_downcast(mapping).as_slice().len()) }), - subscript: atomic_func!(|mapping, needle, vm| PyTuple::mapping_downcast(mapping) - .payload - ._getitem(needle, vm)), + subscript: atomic_func!( + |mapping, needle, vm| PyTuple::mapping_downcast(mapping)._getitem(needle, vm) + ), ..PyMappingMethods::NOT_IMPLEMENTED }); &AS_MAPPING @@ -606,51 +659,61 @@ impl AsSequence for PyTuple { } } -impl AsNumber for PyTuple { - fn as_number() -> &'static PyNumberMethods { - static AS_NUMBER: PyNumberMethods = PyNumberMethods { - boolean: Some(|number, _vm| { - let zelf = number.obj.downcast_ref::().unwrap(); - Ok(!zelf.as_slice().is_empty()) - }), - ..PyNumberMethods::NOT_IMPLEMENTED - }; - &AS_NUMBER - } -} - impl Hashable for PyTuple { #[inline] fn hash(zelf: &Py, vm: &VirtualMachine) -> PyResult { - tuple_hash(zelf.as_slice(), vm) + let cached = Radium::load(&zelf.hash, Ordering::Relaxed); + if cached != hash::SENTINEL { + return Ok(cached); + } + let hash = tuple_hash(zelf.as_slice(), vm)?; + Radium::store(&zelf.hash, hash, Ordering::Relaxed); + Ok(hash) + } +} + +impl Iterable for PyTuple { + fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + Ok(PyTupleIterator { + internal: NativeSequenceIter::new(zelf, NativeIterKind::Sequence, 0), + } + .into_pyobject(vm)) } } impl Comparable for PyTuple { - fn cmp( - zelf: &Py, + fn slot_richcompare( + zelf: &PyObject, other: &PyObject, op: PyComparisonOp, vm: &VirtualMachine, - ) -> PyResult { - if let Some(res) = op.identical_optimization(zelf, other) { - return Ok(res.into()); + ) -> PyResult> { + let (Some(zelf), Some(other)) = (zelf.downcast_ref::(), other.downcast_ref::()) + else { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + }; + if let Some(equal) = op.identical_optimization(zelf, other) { + return Ok(Either::B(equal.into())); } - let other = class_or_notimplemented!(Self, other); - zelf.as_slice() - .iter() - .map(|o| &**o) - .richcompare(other.as_slice().iter().map(|o| &**o), op, vm) - .map(PyComparisonValue::Implemented) + zelf.as_slice().iter().map(|o| &**o).richcompare( + other.as_slice().iter().map(|o| &**o), + op, + vm, + ) } -} -impl Iterable for PyTuple { - fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - Ok(PyTupleIterator { - internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), + fn cmp( + zelf: &Py, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult { + match Self::slot_richcompare(zelf.as_object(), other, op, vm)? { + Either::A(value) => PyArithmeticValue::from_object(vm, value) + .map(|value| value.try_to_bool(vm)) + .transpose(), + Either::B(value) => Ok(value), } - .into_pyobject(vm)) } } @@ -686,35 +749,42 @@ impl Representable for PyTuple { } impl PyRef> { - pub fn try_into_typed( + pub fn try_into_typed( self, vm: &VirtualMachine, - ) -> PyResult>>> { + ) -> PyResult>>> + where + PyRef: TransmuteFromObject, + { // Check that all elements are of the correct type for elem in self.as_slice() { as TransmuteFromObject>::check(vm, elem)?; } - // SAFETY: We just verified all elements are of type T + // SAFETY: every element satisfies T's view invariant. C-layout + // tuple payloads retain the same erased storage and hash for every marker; + // this transfers the owner without changing its allocation or count. Ok(unsafe { core::mem::transmute::>>>(self) }) } } -impl PyRef>> { +impl PyRef>> { #[must_use] pub fn into_untyped(self) -> PyRef { - // SAFETY: PyTuple> has the same layout as PyTuple + // SAFETY: C-layout tuple payloads have identical erased storage and hash; + // forgetting the element guarantee does not change the allocation. unsafe { core::mem::transmute::>(self) } } } -impl Py>> { +impl Py>> { pub fn as_untyped(&self) -> &Py { - // SAFETY: PyTuple> has the same layout as PyTuple + // SAFETY: C-layout tuple payloads have identical erased storage and hash; + // forgetting the element guarantee does not change the allocation. unsafe { core::mem::transmute::<&Self, &Py>(self) } } } -impl From>>> for PyTupleRef { +impl From>>> for PyTupleRef { #[inline] fn from(tup: PyRef>>) -> Self { tup.into_untyped() @@ -724,7 +794,7 @@ impl From>>> for PyTupleRef { #[pyclass(module = false, name = "tuple_iterator", traverse)] #[derive(Debug)] pub(crate) struct PyTupleIterator { - internal: PyMutex>, + internal: NativeSequenceIter, } impl PyPayload for PyTupleIterator { @@ -737,22 +807,21 @@ impl PyPayload for PyTupleIterator { impl Py { #[pymethod] fn __length_hint__(&self) -> usize { - self.internal.lock().length_hint(|obj| obj.as_slice().len()) + self.internal.length_hint(|obj| obj.as_slice().len()) } #[pymethod] fn __setstate__(&self, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { self.internal - .lock() - .set_state(&object, |obj, pos| pos.min(obj.as_slice().len()), vm) + .set_state(&object, |obj| obj.as_slice().len(), vm) } #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyResult { let func = builtins_iter(vm)?; - Ok(self.internal.lock().reduce( + Ok(self.internal.reduce( func, - |x| x.clone().into(), + |x| x.into(), |vm| vm.ctx.empty_tuple.clone().into(), vm, )) @@ -762,27 +831,15 @@ impl Py { impl PyTupleIterator { /// Fast path for FOR_ITER specialization. pub(crate) fn fast_next(&self) -> Option { - locked_next(&self.internal, |tuple, pos| { - Ok(PyIterReturn::from_result( - tuple.as_slice().get(pos).cloned().ok_or(None), - )) - }) - .ok() - .and_then(|r| match r { - PyIterReturn::Return(v) => Some(v), - PyIterReturn::StopIteration(_) => None, - }) + self.internal + .next(|tuple, pos| tuple.as_slice().get(pos).cloned()) } } impl SelfIter for PyTupleIterator {} impl IterNext for PyTupleIterator { fn next(zelf: &Py, _vm: &VirtualMachine) -> PyResult { - locked_next(&zelf.internal, |tuple, pos| { - Ok(PyIterReturn::from_result( - tuple.as_slice().get(pos).cloned().ok_or(None), - )) - }) + Ok(PyIterReturn::from_result(zelf.fast_next().ok_or(None))) } } @@ -807,7 +864,7 @@ pub(crate) fn init(context: &'static Context) { .types .tuple_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_tuple)); } diff --git a/crates/vm/src/builtins/type.rs b/crates/vm/src/builtins/type.rs index 3eb9c94df52..78825901a7d 100644 --- a/crates/vm/src/builtins/type.rs +++ b/crates/vm/src/builtins/type.rs @@ -1,6 +1,6 @@ use super::{ - PyClassMethod, PyDict, PyDictRef, PyList, PyStaticMethod, PyStr, PyStrInterned, PyStrRef, - PyTupleRef, PyUtf8StrRef, PyWeak, mappingproxy::PyMappingProxy, object, union_, + PyAnyDict, PyClassMethod, PyDict, PyDictRef, PyList, PyStaticMethod, PyStr, PyStrInterned, + PyStrRef, PyTupleRef, PyUtf8StrRef, PyWeak, mappingproxy::PyMappingProxy, object, union_, }; use crate::{ AsObject, Context, Py, PyAtomicRef, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, @@ -26,9 +26,9 @@ use crate::{ object::{Traverse, TraverseFn}, protocol::{PyIterReturn, PyNumberMethods}, types::{ - AsNumber, Callable, Constructor, GetAttr, Initializer, NewFunc, PyTypeFlags, PyTypeSlots, - Representable, SLOT_DEFS, SetAttr, TypeDataRef, TypeDataRefMut, TypeDataSlot, fn_addr, - new_wrapper, + AsNumber, CSlots, Callable, Constructor, GetAttr, Initializer, OwnedCSlots, PyTypeFlags, + PyTypeSlots, Representable, SLOT_DEFS, SetAttr, TypeDataRef, TypeDataRefMut, TypeDataSlot, + VectorCallFunc, }, }; use core::{ @@ -37,19 +37,45 @@ use core::{ cell::Cell, ops::Deref, pin::Pin, - sync::atomic::{AtomicBool, AtomicPtr, AtomicU32, Ordering}, + sync::atomic::{AtomicBool, AtomicPtr, AtomicU16, AtomicU32, Ordering}, }; use indexmap::{IndexMap, map::Entry}; use itertools::Itertools; use num_traits::ToPrimitive; -use rustpython_common::wtf8::Wtf8; +use rustpython_common::wtf8::{Wtf8, Wtf8Buf, wtf8_concat}; use std::collections::HashSet; pub(crate) type PyTypeTupleRef = PyRef>; +pub(crate) struct CommonTypeDescriptors { + dict: PyRef, + weakref: PyRef, +} + +impl CommonTypeDescriptors { + pub(crate) fn new(ctx: &Context) -> Self { + // These descriptors operate on the instance's layout, not the class + // that first exposes them. Keeping object as their owner also lets an + // annotation closure retain a class namespace without retaining the class. + let dict = super::PyGetSet::new("__dict__", ctx.types.object_type, ctx) + .with_get(subtype_get_dict) + .with_set(subtype_set_dict) + .with_doc(ItemDoc::static_text("dictionary for instance variables")); + let weakref = super::PyGetSet::new("__weakref__", ctx.types.object_type, ctx) + .with_get(subtype_get_weakref) + .with_doc(ItemDoc::static_text( + "list of weak references to the object", + )); + Self { + dict: ctx.new_pyref(dict), + weakref: ctx.new_pyref(weakref), + } + } +} + #[pyclass(module = false, name = "type", traverse = "manual")] pub struct PyType { - // tp_base. Written under the type lock (see `set_bases`); read lock-free. + // tp_base. Written under the type lock (see `set___bases__`); read lock-free. #[pymember(name = "__base__", doc = false)] pub base: PyAtomicRef>, pub bases: PyRwLock, @@ -63,6 +89,9 @@ pub struct PyType { pub heaptype_ext: Option>>, /// Type version tag for inline caching. 0 means unassigned/invalidated. pub tp_version_tag: AtomicU32, + /// CPython-compatible permanent cache exclusion state. Currently only zero + /// and ATTR_CACHE_UNUSED are used; per-type version budgeting is not implemented. + pub(crate) tp_versions_used: AtomicU16, } /// Monotonic counter for type version tags. Once it reaches `u32::MAX`, @@ -71,6 +100,9 @@ pub struct PyType { /// generic path). static NEXT_TYPE_VERSION: AtomicU32 = AtomicU32::new(1); +// CPython _Py_ATTR_CACHE_UNUSED (Include/cpython/object.h). +const ATTR_CACHE_UNUSED: u16 = 30_000; + const MANAGED_DICT_FLAGS: PyTypeFlags = PyTypeFlags::from_slice(&[PyTypeFlags::HAS_DICT, PyTypeFlags::MANAGED_DICT]); @@ -176,6 +208,15 @@ impl TypeCacheEntry { self.sequence.load(Ordering::Relaxed) == previous } + #[inline] + fn matching_version(&self, type_version: &AtomicU32) -> Option { + let entry_version = self.version.load(Ordering::Acquire); + let type_version = type_version.load(Ordering::Acquire); + // Invalidation can clear both versions after the reader selected an + // entry. Zero never identifies a cached result, even when they match. + (entry_version != 0 && entry_version == type_version).then_some(entry_version) + } + /// Null out the cached value pointer. /// Caller must ensure no concurrent reads can observe this entry /// (version should be set to 0 first). @@ -271,6 +312,7 @@ unsafe impl crate::object::Traverse for PyType { self.attributes.traverse(tracer_fn); if let Some(ext) = self.heaptype_ext.as_ref() { ext.specialization_cache.traverse(tracer_fn); + ext.type_data.traverse(tracer_fn); } } @@ -301,6 +343,11 @@ unsafe impl crate::object::Traverse for PyType { self.attributes.drain_into(out); if let Some(ext) = self.heaptype_ext.as_ref() { ext.specialization_cache.clear_into(out); + if let Some(mut data) = ext.type_data.try_write() + && let Some(data) = data.as_mut() + { + data.clear(out); + } } } } @@ -311,6 +358,9 @@ pub struct HeapTypeExt { pub qualname: PyRwLock, pub slots: Option>>, pub type_data: PyRwLock>, + /// The C slot table this type owns, once an extension has filled one in. + /// Types that inherit from it point at this same table. + pub(crate) c_slots: PyRwLock>, pub specialization_cache: TypeSpecializationCache, /// The interpreter this type was created in, or `None` for the types the /// shared context builds before any interpreter exists. @@ -465,6 +515,35 @@ impl TypeNamespace { } } + /// Return the live dictionary, or materialize a native namespace snapshot. + pub(crate) fn to_dict(&self, vm: &VirtualMachine) -> PyResult { + if let Some(dict) = self.as_dict() { + // Views, iterators, and callbacks must use the actual namespace. + return Ok(dict.to_owned()); + } + // Native namespaces without a backing Python dictionary still need a + // snapshot, but must not bypass dict key callbacks. + Ok(PyDict::from_attributes(self.attributes(&vm.ctx), vm)?.into_ref(&vm.ctx)) + } + + /// Look up the original key without suppressing hash or equality errors. + pub(crate) fn get_item_opt( + &self, + key: &PyObject, + vm: &VirtualMachine, + ) -> PyResult> { + if matches!(self, Self::Attributes(_)) + && let Some(name) = key.downcast_ref_if_exact::(vm) + { + // Native map keys are exact interned strings, so this combination + // cannot invoke Python callbacks and does not need a dict snapshot. + return Ok(vm.ctx.interned_str(name).and_then(|name| self.get(name))); + } + // Heap dictionaries can contain arbitrary keys and non-interned names. + // Preserve the original object even when it has a string payload. + self.to_dict(vm)?.inner_getitem_opt(key, vm) + } + /// Build a dict-backed namespace holding `attrs`, or fall back to an /// interned-key map when no VM is running to hash the keys with. fn new(attrs: PyAttributes, ctx: &Context) -> Self { @@ -680,6 +759,9 @@ impl PyType { /// Assign a fresh version tag. Returns 0 if the version counter has been /// exhausted, in which case no new cache entries can be created. fn assign_version_tag_inner(&self) -> u32 { + if self.tp_versions_used.load(Ordering::Acquire) >= ATTR_CACHE_UNUSED { + return 0; + } let v = self.tp_version_tag.load(Ordering::Acquire); if v != 0 { return v; @@ -811,6 +893,7 @@ impl PyType { qualname: PyRwLock::new(name), slots: None, type_data: PyRwLock::new(None), + c_slots: PyRwLock::new(None), specialization_cache: TypeSpecializationCache::new(), interpreter_id: HeapTypeExt::creating_interpreter_id(), }; @@ -844,10 +927,14 @@ impl PyType { } } - let mros = bases + let mut mros: Vec<_> = bases .iter() .map(|base| base.mro_map_collect(|t| t.to_owned())) .collect(); + if bases.len() > 1 { + // C3 also merges the direct bases to preserve their local precedence. + mros.push(bases.to_vec()); + } linearise_mro(mros) } @@ -869,6 +956,58 @@ impl PyType { } } + fn inherit_subclass_flags(slots: &mut PyTypeSlots, bases: &[PyRef]) { + let mut inherited = PyTypeFlags::empty(); + for base in bases { + inherited |= base.slots.flags.load() & PyTypeFlags::SUBCLASS_FLAGS; + } + slots.flags |= inherited; + } + + fn compute_subclass_flags(&self, ctx: &Context) -> PyTypeFlags { + let is_subclass = |base: &Py| self.mro.read().iter().any(|cls| cls.is(base)); + let mut flags = PyTypeFlags::empty(); + if is_subclass(ctx.types.int_type) { + flags.insert(PyTypeFlags::LONG_SUBCLASS); + } + if is_subclass(ctx.types.list_type) { + flags.insert(PyTypeFlags::LIST_SUBCLASS); + } + if is_subclass(ctx.types.tuple_type) { + flags.insert(PyTypeFlags::TUPLE_SUBCLASS); + } + if is_subclass(ctx.types.bytes_type) { + flags.insert(PyTypeFlags::BYTES_SUBCLASS); + } + if is_subclass(ctx.types.str_type) { + flags.insert(PyTypeFlags::UNICODE_SUBCLASS); + } + if is_subclass(ctx.types.dict_type) { + flags.insert(PyTypeFlags::DICT_SUBCLASS); + } + if is_subclass(ctx.exceptions.base_exception_type) { + flags.insert(PyTypeFlags::BASE_EXC_SUBCLASS); + } + if is_subclass(ctx.types.type_type) { + flags.insert(PyTypeFlags::TYPE_SUBCLASS); + } + flags + } + + fn update_subclass_flags_recursive(&self, ctx: &Context) { + self.slots.flags.replace_masked( + PyTypeFlags::SUBCLASS_FLAGS, + self.compute_subclass_flags(ctx), + ); + for weak_ref in self.subclasses.read().iter() { + if let Some(subclass) = weak_ref.upgrade() + && let Some(subclass) = subclass.downcast_ref::() + { + subclass.update_subclass_flags_recursive(ctx); + } + } + } + pub fn has_patma_collection_flag(&self, flag: u8) -> bool { debug_assert!(flag == PyTypeFlags::SEQUENCE || flag == PyTypeFlags::MAPPING); self.slots.flags.has_feature(flag) @@ -1002,6 +1141,8 @@ impl PyType { slots.flags |= WEAKREF_FLAGS; } + Self::inherit_subclass_flags(&mut slots, bases.as_slice()); + // Inherit SEQUENCE and MAPPING flags from base classes Self::inherit_patma_flags(&mut slots, bases.as_slice()); @@ -1036,6 +1177,7 @@ impl PyType { slots, heaptype_ext: Some(Pin::new(Box::new(heaptype_ext))), tp_version_tag: AtomicU32::new(0), + tp_versions_used: AtomicU16::new(0), }, metaclass, None, @@ -1043,16 +1185,16 @@ impl PyType { if !defer_mro { new_type.mro.write().insert(0, new_type.clone()); new_type.init_slots(ctx); - } - let weakref_type = super::PyWeak::static_type(); - for base in new_type.bases.read().as_slice() { - base.subclasses.write().push( - new_type - .as_object() - .downgrade_with_weakref_typ_opt(None, weakref_type.to_owned()) - .unwrap(), - ); + let weakref_type = super::PyWeak::static_type(); + for base in new_type.bases.read().as_slice() { + base.subclasses.write().push( + new_type + .as_object() + .downgrade_with_weakref_typ_opt(None, weakref_type.to_owned()) + .unwrap(), + ); + } } Ok(new_type) @@ -1074,6 +1216,7 @@ impl PyType { // Inherit SEQUENCE and MAPPING flags from base class // For static types, we only have a single base Self::inherit_patma_flags(&mut slots, core::slice::from_ref(&base)); + Self::inherit_subclass_flags(&mut slots, core::slice::from_ref(&base)); if slots.basicsize == 0 { slots.basicsize = base.slots.basicsize; @@ -1098,6 +1241,7 @@ impl PyType { slots, heaptype_ext: None, tp_version_tag: AtomicU32::new(0), + tp_versions_used: AtomicU16::new(0), }, metaclass, None, @@ -1119,7 +1263,7 @@ impl PyType { // Note: inherit_slots is called in PyClassImpl::init_class after // slots are fully initialized by make_slots() - Self::set_new(&new_type.slots, new_type.base.deref()); + Self::set_new(&new_type.slots, new_type.base.deref(), false); Self::set_alloc(&new_type.slots, new_type.base.deref()); let weakref_type = super::PyWeak::static_type(); @@ -1171,7 +1315,7 @@ impl PyType { self.update_slot::(attr_name, ctx); } - Self::set_new(&self.slots, self.base.deref()); + Self::set_new(&self.slots, self.base.deref(), true); Self::set_alloc(&self.slots, self.base.deref()); } @@ -1195,11 +1339,42 @@ impl PyType { } } - fn set_new(slots: &PyTypeSlots, base: Option<&Py>) { + /// type_ready_set_new: a static type with no tp_new whose base is object + /// gets DISALLOW_INSTANTIATION and keeps tp_new unset. Heap types inherit + /// the base's tp_new. A static type that inherits a non-NULL tp_new must + /// have the same basicsize as that base, because the inherited function + /// allocates the base payload. Heap types, including native types flagged + /// HEAPTYPE, reuse the base payload like classes created at runtime. + fn set_new(slots: &PyTypeSlots, base: Option<&Py>, heap: bool) { + let is_heap = heap || slots.flags.has_feature(PyTypeFlags::HEAPTYPE); + + if !is_heap + && slots.new.load().is_none() + && base.is_some_and(|b| core::ptr::eq(b, object::PyBaseObject::static_type())) + { + slots.flags.insert(PyTypeFlags::DISALLOW_INSTANTIATION); + } + if slots.flags.has_feature(PyTypeFlags::DISALLOW_INSTANTIATION) { - slots.new.store(None) + slots.new.store(None); + slots.c_slots.store(None); } else if slots.new.load().is_none() { - slots.new.store(base.and_then(|base| base.slots.new.load())) + let inherited = base.and_then(|base| base.slots.new.load()); + if !is_heap + && inherited.is_some() + && let Some(base) = base + && slots.basicsize != base.slots.basicsize + { + panic!( + "static type '{}' inherits tp_new from '{}' but basicsize {} != {}; \ + the inherited tp_new allocates the base payload", + slots.name, base.slots.name, slots.basicsize, base.slots.basicsize + ); + } + slots.new.store(inherited); + slots + .c_slots + .store(base.and_then(|base| base.slots.c_slots.load())); } } @@ -1212,7 +1387,7 @@ impl PyType { } pub(crate) fn finalize_bootstrap_static(typ: &Py) { - Self::set_new(&typ.slots, typ.base.deref()); + Self::set_new(&typ.slots, typ.base.deref(), false); Self::set_alloc(&typ.slots, typ.base.deref()); } @@ -1272,11 +1447,10 @@ impl PyType { let name_ptr = name as *const _ as *mut _; loop { let seq1 = entry.begin_read(); - let entry_version = entry.version.load(Ordering::Acquire); - let type_version = self.tp_version_tag.load(Ordering::Acquire); - if entry_version != type_version - || !core::ptr::eq(entry.name.load(Ordering::Relaxed), name_ptr) - { + let Some(entry_version) = entry.matching_version(&self.tp_version_tag) else { + break; + }; + if !core::ptr::eq(entry.name.load(Ordering::Relaxed), name_ptr) { break; } let ptr = entry.value.load(Ordering::Acquire); @@ -1291,7 +1465,6 @@ impl PyType { if same_ptr && entry.end_read(seq1) { return (Some(cloned), entry_version); } - drop(cloned); continue; } break; @@ -1488,9 +1661,7 @@ impl PyType { let name_ptr = name as *const _ as *mut _; loop { let seq1 = entry.begin_read(); - let v1 = entry.version.load(Ordering::Acquire); - let type_version = self.tp_version_tag.load(Ordering::Acquire); - if v1 != type_version + if entry.matching_version(&self.tp_version_tag).is_none() || !core::ptr::eq(entry.name.load(Ordering::Relaxed), name_ptr) { break; @@ -1522,8 +1693,34 @@ impl PyType { attributes } + /// Give this type a C tp_new, taking ownership of the table it is read + /// from and installing the trampoline that reaches it. + /// + /// Errors if `self` is not a heap type, which is the only kind that can own + /// a table, or if it already owns one. + pub fn set_c_slots(&self, c_slots: CSlots, vm: &VirtualMachine) -> PyResult<()> { + let ext = self.heaptype_ext.as_ref().ok_or_else(|| { + vm.new_type_error(format!( + "cannot set C slots on static type '{}'", + self.name() + )) + })?; + let mut owned = ext.c_slots.write(); + if owned.is_some() { + return Err(vm.new_type_error(format!("type '{}' already has C slots", self.name()))); + } + let has_new = c_slots.new.load().is_some(); + let table = OwnedCSlots::new(c_slots); + self.slots.c_slots.store(Some(table.as_ptr())); + if has_new { + self.slots.new.store(Some(crate::types::c_new_trampoline)); + } + *owned = Some(table); + Ok(()) + } + // bound method for every type - pub(crate) fn __new__(zelf: PyRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + pub fn __new__(zelf: PyRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let (subtype, args): (PyRef, FuncArgs) = args.bind(vm)?; if !subtype.fast_issubclass(&zelf) { return Err(vm.new_type_error(format!( @@ -1582,19 +1779,26 @@ impl PyType { /// The type's fully qualified name, the way the `%T` format code prints it: /// `module.qualname`, with a `builtins` or `__main__` module left off. - pub fn fully_qualified_name(&self, vm: &VirtualMachine) -> PyResult { + pub fn fully_qualified_name(&self, vm: &VirtualMachine) -> PyResult { + // Static types use tp_name verbatim, including its module prefix. + if !self.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) { + return Ok((&*self.slot_name()).into()); + } + // Read the stored metadata, bypassing metaclass and str-subclass hooks. + // A Python name can contain lone surrogates, so neither this helper nor + // its callers may pass it through Rust's UTF-8 Display formatting. let qualname = self.__qualname__(vm); let qualname = qualname .downcast_ref::() - .and_then(|qualname| qualname.to_str()) - .map_or_else(|| self.name().to_string(), str::to_owned); + .expect("type qualname is a string") + .as_wtf8(); let module = self.__module__(vm)?; - Ok( - match module.downcast_ref::().and_then(|m| m.to_str()) { - Some("builtins" | "__main__") | None => qualname, - Some(module) => format!("{module}.{qualname}"), - }, - ) + match module.downcast_ref::() { + Some(module) if !matches!(module.to_str(), Some("builtins" | "__main__")) => { + Ok(wtf8_concat!(module.as_wtf8(), '.', qualname)) + } + _ => Ok(qualname.to_owned()), + } } pub fn name(&self) -> BorrowedValue<'_, str> { @@ -1609,6 +1813,18 @@ impl PyType { /// Initialize type data for this type. Can only be called once. /// Returns an error if the type is not a heap type or if data is already initialized. pub fn init_type_data(&self, data: T) -> Result<(), String> { + self.init_type_data_slot(TypeDataSlot::new(data)) + } + + /// Initialize extension storage with GC traversal and clearing callbacks. + pub fn init_traced_type_data( + &self, + data: T, + ) -> Result<(), String> { + self.init_type_data_slot(TypeDataSlot::new_traced(data)) + } + + fn init_type_data_slot(&self, data: TypeDataSlot) -> Result<(), String> { let ext = self .heaptype_ext .as_ref() @@ -1618,7 +1834,7 @@ impl PyType { if type_data.is_some() { return Err("Type data already initialized".to_string()); } - *type_data = Some(TypeDataSlot::new(data)); + *type_data = Some(data); Ok(()) } @@ -1727,12 +1943,22 @@ impl PyType { pub fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { or_(zelf, other, vm) } +} +impl Py { fn check_set_special_type_attr( &self, name: &PyStrInterned, + value: PySetterValue, vm: &VirtualMachine, - ) -> PyResult<()> { + ) -> PyResult { + let value = value.ok_or_else(|| { + vm.new_type_error(format!( + "cannot delete '{}' attribute of type '{}'", + name, + self.slot_name() + )) + })?; if self.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) { return Err(vm.new_type_error(format!( "cannot set '{}' attribute of immutable type '{}'", @@ -1740,7 +1966,11 @@ impl PyType { self.slot_name() ))); } - Ok(()) + let name: &Py = name; + vm.audit("object.__setattr__", || { + (self.to_owned(), name.to_owned(), value.clone()) + })?; + Ok(value) } } @@ -1756,7 +1986,7 @@ impl PyType { AsNumber, Representable ), - flags(BASETYPE, HAS_DICT, HAS_WEAKREF) + flags(BASETYPE, HAS_DICT, HAS_WEAKREF, TYPE_SUBCLASS) )] impl PyType {} @@ -1764,6 +1994,9 @@ impl PyType {} struct PrepareArgs; impl FromArgs for PrepareArgs { + // CPython accepts and ignores every argument, independent of the display signature. + const BINDING_PARAMS: Option<&'static [Param]> = FuncArgs::BINDING_PARAMS; + const PARAMS: Option<&'static [Param]> = Some(&[ Param::positional_only("name"), Param::positional_only("bases"), @@ -1798,25 +2031,15 @@ impl Constructor for PyType { })); } - let (name, bases, dict, kwargs): (PyStrRef, PyTupleRef, PyDictRef, KwArgs) = + let (name, bases, dict, kwargs): (PyStrRef, PyTupleRef, PyObjectRef, KwArgs) = args.clone().bind_for(vm, Self::NAME)?; - - // A mapping that is not an exact dict (e.g. OrderedDict) keeps its - // own iteration order; copy via the mapping protocol so that order - // lands in the type dict. - let dict = if args.args[2].class().is(vm.ctx.types.dict_type) { - dict - } else { - let copied = vm.ctx.new_dict(); - copied.merge_object(args.args[2].clone(), vm)?; - copied + let Some(dict) = PyAnyDict::from_object(&dict) else { + return Err(vm.new_type_error(wtf8_concat!( + "type.__new__() argument 3 must be dict or frozendict, not ", + dict.class().fully_qualified_name(vm)? + ))); }; - if name.as_bytes().contains(&0) { - return Err(vm.new_value_error("type name must not contain null characters")); - } - let name = name.try_into_utf8(vm)?; - let (metatype, base, bases, base_is_type) = if bases.as_slice().is_empty() { let base = vm.ctx.types.object_type.to_owned(); let bases = PyTuple::new_ref_typed(vec![base.clone()], &vm.ctx); @@ -1841,11 +2064,11 @@ impl Constructor for PyType { // Search the bases for the proper metatype to deal with this: let winner = calculate_meta_class(metatype.clone(), bases.as_slice(), vm)?; let metatype = if !winner.is(&metatype) { - if let Some(ref slot_new) = winner.slots.new.load() { - // Pass it to the winner - return slot_new(winner, args, vm); - } - winner + let slot_new = winner.slots.new.load().ok_or_else(|| { + vm.new_type_error(format!("cannot create '{}' instances", winner.slot_name())) + })?; + // Pass it to the winner. + return slot_new(winner, args, vm); } else { metatype }; @@ -1856,6 +2079,25 @@ impl Constructor for PyType { (metatype, base.to_owned(), bases, base_is_type) }; + // Copy only after resolving the metaclass: its __new__ receives the + // original namespace. A subclass with a custom iterator (e.g. + // OrderedDict) keeps its own mapping order in the mutable type dict. + let dict = if let Some(dict) = dict.as_object().downcast_ref_if_exact::(vm) { + dict.to_owned() + } else { + let copied = vm.ctx.new_dict(); + // Like dict.copy(), an empty table bypasses subclass hooks. + if !dict.is_empty() { + copied.merge_object(dict.to_owned().into(), vm)?; + } + copied + }; + + if name.as_bytes().contains(&0) { + return Err(vm.new_value_error("type name must not contain null characters")); + } + let name = name.try_into_utf8(vm)?; + let qualname = dict .get_item_opt(identifier!(vm, __qualname__), vm)? .map(|obj| downcast_qualname(obj, vm)) @@ -1885,19 +2127,25 @@ impl Constructor for PyType { if let Some(f) = attributes.get_mut(identifier!(vm, __init_subclass__)) && f.class().is(vm.ctx.types.function_type) { - *f = PyClassMethod::from(f.clone()).into_pyobject(vm); + let callable = f.clone(); + *f = PyClassMethod::from(callable.clone()).into_pyobject(vm); + super::classmethod::functools_wraps(f, &callable, vm)?; } if let Some(f) = attributes.get_mut(identifier!(vm, __class_getitem__)) && f.class().is(vm.ctx.types.function_type) { - *f = PyClassMethod::from(f.clone()).into_pyobject(vm); + let callable = f.clone(); + *f = PyClassMethod::from(callable.clone()).into_pyobject(vm); + super::classmethod::functools_wraps(f, &callable, vm)?; } if let Some(f) = attributes.get_mut(identifier!(vm, __new__)) && f.class().is(vm.ctx.types.function_type) { - *f = PyStaticMethod::from(f.clone()).into_pyobject(vm); + let callable = f.clone(); + *f = PyStaticMethod::from(callable.clone()).into_pyobject(vm); + super::classmethod::functools_wraps(f, &callable, vm)?; } if let Some(globals) = crate::frame::current_globals() { @@ -1949,16 +2197,6 @@ impl Constructor for PyType { tuple.try_into_typed(vm)? }; - // Any nonempty __slots__ is rejected when the base has a variable - // item size, including a tuple of only `__dict__` or `__weakref__`. - // Types like weakref.ref have itemsize 0 and do allow slots. - if !slots.as_slice().is_empty() && base.slots.itemsize > 0 { - return Err(vm.new_type_error(format!( - "nonempty __slots__ not supported for subtype of '{}'", - base.name() - ))); - } - // Validate slot names and track duplicates let mut seen_dict = false; let mut seen_weakref = false; @@ -2030,6 +2268,19 @@ impl Constructor for PyType { .cloned() .collect(); filtered.sort_by(|a, b| a.as_bytes().cmp(b.as_bytes())); + // CPython 3.15 permits named slots on tuple subclasses. Our + // member cells live in the object prefix, independently of the + // tuple's elements. Other variable-size bases still only accept + // the managed __dict__ and __weakref__ slots filtered above. + if !filtered.is_empty() + && base.slots.itemsize > 0 + && !base.fast_issubclass(vm.ctx.types.tuple_type) + { + return Err(vm.new_type_error(format!( + "arbitrary __slots__ not supported for subtype of '{}'", + base.name() + ))); + } let filtered_slots = PyTuple::new_ref_typed(filtered, &vm.ctx); (Some(filtered_slots), has_dict, add_weakref) @@ -2070,10 +2321,21 @@ impl Constructor for PyType { // Add HAS_WEAKREF if: // 1. __slots__ is not defined (automatic weakref support), OR // 2. __weakref__ is in __slots__ - // A variable-size base does not gain a weakref slot. - let may_add_weakref = - base.slots.itemsize == 0 && !base.slots.flags.has_feature(PyTypeFlags::HAS_WEAKREF); - if (heaptype_slots.is_none() && may_add_weakref) || add_weakref { + let may_add_weakref = !base.slots.flags.has_feature(PyTypeFlags::HAS_WEAKREF); + // Match type_new_slots/type_new_slots_bases: variable-size bases do + // not gain automatic weakref storage, but explicit slots may inherit + // it from a secondary base. + let add_weakref = add_weakref + || (may_add_weakref + && if heaptype_slots.is_none() { + base.slots.itemsize == 0 + } else { + bases + .as_slice() + .iter() + .any(|base| base.slots.flags.has_feature(PyTypeFlags::HAS_WEAKREF)) + }); + if add_weakref { flags |= WEAKREF_FLAGS; } @@ -2089,6 +2351,7 @@ impl Constructor for PyType { qualname: PyRwLock::new(qualname), slots: heaptype_slots.clone(), type_data: PyRwLock::new(None), + c_slots: PyRwLock::new(None), specialization_cache: TypeSpecializationCache::new(), interpreter_id: HeapTypeExt::creating_interpreter_id(), }; @@ -2147,6 +2410,7 @@ impl Constructor for PyType { if custom_mro { mro_internal(&typ, vm)?; typ.init_slots(&vm.ctx); + typ.update_subclass_flags_recursive(&vm.ctx); } if let Some(ref slots) = heaptype_slots { @@ -2197,7 +2461,7 @@ impl Constructor for PyType { // Also, type subclasses don't need their own __dict__ descriptor // since they inherit it from type - // Add __dict__ descriptor after type creation to ensure correct __objclass__ + // Share the interpreter's object-owned __dict__ descriptor. // Only add if: // 1. base is not type (type subclasses inherit __dict__ from type) // 2. the class has HAS_DICT flag (i.e., __slots__ was not defined or __dict__ is in __slots__) @@ -2210,17 +2474,16 @@ impl Constructor for PyType { .iter() .any(|base| base.attributes.contains(__dict__)); if !typ.attributes.contains(__dict__) && !has_inherited_dict { - let getset = super::PyGetSet::new("__dict__", &typ, &vm.ctx) - .with_get(subtype_get_dict) - .with_set(subtype_set_dict) - .with_doc(ItemDoc::static_text("dictionary for instance variables")); - let descriptor = PyRef::new_ref(getset, vm.ctx.types.getset_type.to_owned(), None); - typ.attributes.set(__dict__, descriptor.into()); + typ.attributes.set( + __dict__, + vm.state.common_type_descriptors.dict.clone().into(), + ); } } - // Add __weakref__ descriptor for types with HAS_WEAKREF - if typ.slots.flags.has_feature(PyTypeFlags::HAS_WEAKREF) { + // Only a newly added weakref slot introduces a descriptor. Inherited + // support (notably type subclasses) must not expose a new descriptor. + if add_weakref { let __weakref__ = vm.ctx.intern_str("__weakref__"); let has_inherited_weakref = typ .mro @@ -2228,14 +2491,10 @@ impl Constructor for PyType { .iter() .any(|base| base.attributes.contains(__weakref__)); if !typ.attributes.contains(__weakref__) && !has_inherited_weakref { - let getset = super::PyGetSet::new("__weakref__", &typ, &vm.ctx) - .with_get(subtype_get_weakref) - .with_set(subtype_set_weakref) - .with_doc(ItemDoc::static_text( - "list of weak references to the object", - )); - let descriptor = PyRef::new_ref(getset, vm.ctx.types.getset_type.to_owned(), None); - typ.attributes.set(__weakref__, descriptor.into()); + typ.attributes.set( + __weakref__, + vm.state.common_type_descriptors.weakref.clone().into(), + ); } } @@ -2249,6 +2508,26 @@ impl Constructor for PyType { } } + if custom_mro { + // Like CPython's type_ready_publish, expose the type only after + // its MRO and slots are initialized. A failed custom mro() may + // leave the incomplete type alive through a user reference. + Self::with_type_lock(vm, || { + let weak = typ + .as_object() + .downgrade_with_weakref_typ_opt(None, super::PyWeak::static_type().to_owned()) + .unwrap(); + for base in typ.bases.read().as_slice() { + let mut subclasses = base.subclasses.write(); + // A reentrant __bases__ assignment may have registered + // this type already. Callback-free weakrefs are cached. + if !subclasses.iter().any(|existing| existing.is(&weak)) { + subclasses.push(weak.clone()); + } + } + }); + } + // avoid deadlock let attributes = typ .attributes @@ -2298,7 +2577,12 @@ impl Constructor for PyType { const SIGNATURE_END_MARKER: &str = ")\n--\n\n"; fn get_signature(doc: &str) -> Option<&str> { - doc.find(SIGNATURE_END_MARKER).map(|index| &doc[..=index]) + let index = doc.find(SIGNATURE_END_MARKER)?; + // Like CPython's skip_signature, a blank paragraph ends the header search. + if doc[..index].contains("\n\n") { + return None; + } + Some(&doc[..=index]) } fn find_signature<'a>(name: &str, doc: &'a str) -> Option<&'a str> { @@ -2317,13 +2601,12 @@ pub(crate) fn get_text_signature_from_internal_doc<'a>( // _PyType_DocWithoutSignature in CPython fn doc_without_signature<'a>(name: &str, internal_doc: &'a str) -> &'a str { // If the doc starts with the type name and a '(', it's a signature - if let Some(doc_without_sig) = find_signature(name, internal_doc) { - // Find where the signature ends - if let Some(sig_end_pos) = doc_without_sig.find(SIGNATURE_END_MARKER) { - let after_sig = &doc_without_sig[sig_end_pos + SIGNATURE_END_MARKER.len()..]; - // Return the documentation after the signature, or empty string if none - return after_sig; - } + if let Some(doc_without_sig) = find_signature(name, internal_doc) + && let Some(signature) = get_signature(doc_without_sig) + { + let after_sig = &doc_without_sig[signature.len() + SIGNATURE_END_MARKER.len() - 1..]; + // Return the documentation after the signature, or empty string if none + return after_sig; } // If no signature found, return the whole doc internal_doc @@ -2335,6 +2618,36 @@ pub(crate) fn get_doc_from_internal_doc<'a>(name: &str, internal_doc: &'a str) - (!doc.is_empty()).then_some(doc) } +#[cfg(test)] +mod internal_doc_signature_tests { + use super::{get_doc_from_internal_doc, get_text_signature_from_internal_doc}; + + #[test] + fn signatures_stop_before_a_blank_paragraph() { + for doc in [ + "f(x\n\ncontinued)\n--\n\nDocumentation.", + "f(x)\n\nExample: f(y)\n--\n\nDocumentation.", + ] { + assert_eq!(get_text_signature_from_internal_doc("f", doc), None); + assert_eq!(get_doc_from_internal_doc("f", doc), Some(doc)); + } + } + + #[test] + fn multiline_signature_and_documentation_keep_their_boundary() { + let doc = "f($module, x,\n y=None, /)\n--\n\nFirst.\n\nSecond."; + assert_eq!( + get_text_signature_from_internal_doc("mod.f", doc), + Some("($module, x,\n y=None, /)") + ); + assert_eq!( + get_doc_from_internal_doc("mod.f", doc), + Some("First.\n\nSecond.") + ); + assert_eq!(get_doc_from_internal_doc("f", "f()\n--\n\n"), None); + } +} + pub(crate) fn rendered_item_doc(name: &str, doc: ItemDoc) -> Option<&'static str> { if doc.len != 0 { return db_doc(doc.offset, doc.len); @@ -2461,15 +2774,8 @@ impl Py { #[pygetset(setter)] fn set___doc__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { // Similar to CPython's type_set_doc - let value = value.ok_or_else(|| { - vm.new_type_error(format!( - "cannot delete '__doc__' attribute of immutable type '{}'", - self.name() - )) - })?; - // Check if we can set this special type attribute - self.check_set_special_type_attr(identifier!(vm, __doc__), vm)?; + let value = self.check_set_special_type_attr(identifier!(vm, __doc__), value, vm)?; let _prev_value = PyType::with_type_lock(vm, || { self.modified_inner(); @@ -2480,13 +2786,10 @@ impl Py { } #[pymethod] - fn __dir__(&self, vm: &VirtualMachine) -> PyList { - let attributes: Vec = self - .get_attributes(&vm.ctx) - .into_iter() - .map(|(k, _)| k.to_object()) - .collect(); - PyList::from(attributes) + fn __dir__(&self, vm: &VirtualMachine) -> PyResult { + let dict = PyDict::default(); + object::merge_class_dict(&dict, self.as_object(), vm)?; + Ok(PyList::from(dict.keys_vec())) } #[pymethod] @@ -2503,7 +2806,7 @@ impl Py { } #[pyclassmethod] - fn __subclasshook__(_args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef { + fn __subclasshook__(_cls: &Self, _args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef { vm.ctx.not_implemented() } @@ -2519,16 +2822,18 @@ impl Py { fn __bases__(&self, vm: &VirtualMachine) -> PyTupleRef { PyType::with_type_lock(vm, || self.bases.read().clone().into_untyped()) } - #[pygetset(setter, name = "__bases__")] - fn set_bases(zelf: &Self, bases_tuple: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___bases__(zelf: &Self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { // TODO: Assigning to __bases__ is only used in typing.NamedTupleMeta.__new__ // Rather than correctly re-initializing the class, we are skipping a few steps for now - if zelf.slots().flags.has_feature(PyTypeFlags::IMMUTABLETYPE) { - return Err(vm.new_type_error(format!( - "cannot set '__bases__' attribute of immutable type '{}'", - zelf.name() - ))); - } + let value = zelf.check_set_special_type_attr(identifier!(vm, __bases__), value, vm)?; + let bases_tuple = value.downcast::().map_err(|value| { + vm.new_type_error(format!( + "can only assign tuple to {}.__bases__, not {}", + zelf.slot_name(), + value.class().slot_name() + )) + })?; if bases_tuple.as_slice().is_empty() { return Err(vm.new_type_error(format!( "can only assign non-empty tuple to {}.__bases__, not ()", @@ -2553,11 +2858,7 @@ impl Py { // Reject reparenting onto a base whose instances have an incompatible // object layout. - let old_base_owned = zelf.base.load_owned(); - let old_base = old_base_owned - .as_deref() - .unwrap_or(vm.ctx.types.object_type); - compatible_for_assignment(old_base, &new_base, "__bases__", vm)?; + compatible_for_assignment(zelf, &new_base, "__bases__", false, vm)?; // References released inside the critical section are collected here // and dropped after the lock: dropping them inside can run arbitrary @@ -2612,7 +2913,7 @@ impl Py { } }; - let result = PyType::with_type_lock(vm, || { + PyType::with_type_lock(vm, || { for base in bases.as_slice() { if is_subtype_with_mro(&base.mro.read(), base, zelf) || (!base.mro.read().is_empty() && type_is_subtype_base_chain(base, zelf, vm)) @@ -2639,6 +2940,7 @@ impl Py { } let old_mro = core::mem::replace(&mut *cls.mro.write(), new_mro); undo.push((cls.to_owned(), old_mro)); + type_mro_modified(cls, vm); cls.modified_inner(); let subclasses: Vec = cls .subclasses @@ -2689,6 +2991,7 @@ impl Py { if core::ptr::eq(&**zelf.bases.read(), &*bases) { remove_as_subclass(old_bases.as_slice(), &mut retired); add_as_subclass(bases.as_slice()); + zelf.update_subclass_flags_recursive(&vm.ctx); zelf.update_all_slots(&vm.ctx); } @@ -2698,9 +3001,7 @@ impl Py { } crate::stdlib::_testinternalcapi::note_set_bases(); Ok(()) - }); - drop(retired); - result + }) } #[pygetset] @@ -2769,16 +3070,16 @@ impl Py { #[pygetset(setter)] fn set___qualname__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { - self.check_set_special_type_attr(identifier!(vm, __qualname__), vm)?; - let value = value.ok_or_else(|| { + let value = self.check_set_special_type_attr(identifier!(vm, __qualname__), value, vm)?; + + let str_value = value.downcast::().map_err(|value| { vm.new_type_error(format!( - "cannot delete '__qualname__' attribute of immutable type '{}'", - self.name() + "can only assign string to {}.__qualname__, not '{}'", + self.slot_name(), + value.class().slot_name(), )) })?; - let str_value = downcast_qualname(value, vm)?; - let heap_type = self.heaptype_ext.as_ref().ok_or_else(|| { vm.new_type_error(format!( "cannot set '__qualname__' attribute of immutable type '{}'", @@ -2850,20 +3151,21 @@ impl Py { return Err(vm.new_type_error("__annotate__ must be callable or None")); } - let _prev_values = PyType::with_type_lock(vm, || { + let clear_annotations = !vm.is_none(&value); + let old_annotate = PyType::with_type_lock(vm, || { self.modified_inner(); - // Clear cached annotations only when setting to a new callable - let removed = if !vm.is_none(&value) { + self.attributes + .insert(identifier!(vm, __annotate_func__), value) + }); + drop(old_annotate); + // Clear cached annotations only when setting to a new callable. + if clear_annotations { + let _old_annotations = PyType::with_type_lock(vm, || { + self.modified_inner(); self.attributes .remove(identifier!(vm, __annotations_cache__)) - } else { - None - }; - let prev = self - .attributes - .insert(identifier!(vm, __annotate_func__), value); - (removed, prev) - }); + }); + } Ok(()) } @@ -2912,10 +3214,10 @@ impl Py { let annotations = if annotate.is_callable() { // Call __annotate__(1) where 1 is FORMAT_VALUE let result = annotate.call((1i32,), vm)?; - if !result.class().is(vm.ctx.types.dict_type) { - return Err(vm.new_type_error(format!( - "__annotate__ returned non-dict of type '{}'", - result.class().name() + if !result.downcastable::() { + return Err(vm.new_type_error(wtf8_concat!( + "__annotate__() must return a dict, not ", + result.class().fully_qualified_name(vm)? ))); } result @@ -2923,22 +3225,13 @@ impl Py { vm.ctx.new_dict().into() }; - let (result, _prev) = PyType::with_type_lock(vm, || { - if let Some(existing) = self.attributes.get(annotations_key) - && !existing.class().is(vm.ctx.types.getset_type) - { - return (existing, None); - } - if let Some(existing) = self.attributes.get(annotations_cache_key) { - return (existing, None); - } + drop(annotate); + let _old_annotations = PyType::with_type_lock(vm, || { self.modified_inner(); - let prev = self - .attributes - .insert(annotations_cache_key, annotations.clone()); - (annotations, prev) + self.attributes + .insert(annotations_cache_key, annotations.clone()) }); - Ok(result) + Ok(annotations) } #[pygetset(setter)] @@ -2954,49 +3247,41 @@ impl Py { ))); } - let _prev_values = PyType::with_type_lock(vm, || { + let deleting = matches!(&value, PySetterValue::Delete); + let (has_annotations, old_annotations) = PyType::with_type_lock(vm, || { self.modified_inner(); let has_annotations = self.attributes.contains(identifier!(vm, __annotations__)); - - let mut prev = Vec::new(); - match value { - crate::function::PySetterValue::Assign(value) => { - let key = if has_annotations { - identifier!(vm, __annotations__) - } else { - identifier!(vm, __annotations_cache__) - }; - prev.extend(self.attributes.insert(key, value)); - if has_annotations { - prev.extend( - self.attributes - .remove(identifier!(vm, __annotations_cache__)), - ); - } - } - crate::function::PySetterValue::Delete => { - let removed = if has_annotations { - self.attributes.remove(identifier!(vm, __annotations__)) - } else { - self.attributes - .remove(identifier!(vm, __annotations_cache__)) - }; - if removed.is_none() { - return Err(vm.new_attribute_error("__annotations__")); - } - prev.extend(removed); - if has_annotations { - prev.extend( - self.attributes - .remove(identifier!(vm, __annotations_cache__)), - ); - } - } - } - prev.extend(self.attributes.remove(identifier!(vm, __annotate_func__))); - prev.extend(self.attributes.remove(identifier!(vm, __annotate__))); - Ok(prev) - })?; + let key = if has_annotations { + identifier!(vm, __annotations__) + } else { + identifier!(vm, __annotations_cache__) + }; + let old_annotations = match value { + crate::function::PySetterValue::Assign(value) => self.attributes.insert(key, value), + crate::function::PySetterValue::Delete => self.attributes.remove(key), + }; + (has_annotations, old_annotations) + }); + if deleting && old_annotations.is_none() { + return Err(vm.new_attribute_error("__annotations__")); + } + drop(old_annotations); + if has_annotations { + let _old_cache = PyType::with_type_lock(vm, || { + self.modified_inner(); + self.attributes + .remove(identifier!(vm, __annotations_cache__)) + }); + } + for key in [ + identifier!(vm, __annotate_func__), + identifier!(vm, __annotate__), + ] { + let _old_annotate = PyType::with_type_lock(vm, || { + self.modified_inner(); + self.attributes.remove(key) + }); + } Ok(()) } @@ -3007,8 +3292,8 @@ impl Py { } #[pygetset(setter)] - fn set___module__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.check_set_special_type_attr(identifier!(vm, __module__), vm)?; + fn set___module__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let value = self.check_set_special_type_attr(identifier!(vm, __module__), value, vm)?; let _prev_values = PyType::with_type_lock(vm, || { self.modified_inner(); let removed = self.attributes.remove(identifier!(vm, __firstlineno__)); @@ -3018,7 +3303,7 @@ impl Py { Ok(()) } - #[pyclassmethod] + #[pyclassmethod(text_signature = "($cls, name, bases, /, **kwds)")] fn __prepare__(_cls: PyTypeRef, _args: PrepareArgs, vm: &VirtualMachine) -> PyDictRef { vm.ctx.new_dict() } @@ -3054,8 +3339,8 @@ impl Py { } #[pygetset(setter)] - fn set___name__(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.check_set_special_type_attr(identifier!(vm, __name__), vm)?; + fn set___name__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let value = self.check_set_special_type_attr(identifier!(vm, __name__), value, vm)?; let name = value.downcast::().map_err(|value| { vm.new_type_error(format!( "can only assign string to {}.__name__, not '{}'", @@ -3121,18 +3406,11 @@ impl Py { #[pygetset(setter)] fn set___type_params__(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { let key = identifier!(vm, __type_params__); - match value { - PySetterValue::Assign(val) => { - self.check_set_special_type_attr(key, vm)?; - let _prev_value = PyType::with_type_lock(vm, || { - self.modified_inner(); - self.attributes.insert(key, val) - }); - } - PySetterValue::Delete => { - return Err(vm.new_type_error("cannot delete '__type_params__'")); - } - } + let value = self.check_set_special_type_attr(key, value, vm)?; + let _prev_value = PyType::with_type_lock(vm, || { + self.modified_inner(); + self.attributes.insert(key, value) + }); Ok(()) } } @@ -3174,11 +3452,17 @@ impl SetAttr for PyType { } else { let prev_value = zelf.attributes().remove(attr_name); if prev_value.is_none() { - return Err(vm.new_attribute_error(format!( + let exc = vm.new_attribute_error(format!( "type object '{}' has no attribute '{}'", zelf.name(), attr_name, - ))); + )); + vm.set_attribute_error_context( + &exc, + zelf.to_owned().into(), + attr_name.to_owned(), + ); + return Err(exc); } prev_value }; @@ -3369,44 +3653,33 @@ fn subtype_set_dict(obj: PyObjectRef, value: PySetterValue, vm: &VirtualMachine) } // subtype_get_weakref -fn subtype_get_weakref(obj: PyObjectRef, vm: &VirtualMachine) -> PyObjectRef { +fn subtype_get_weakref(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + if !obj + .class() + .slots + .flags + .has_feature(PyTypeFlags::HAS_WEAKREF) + { + return Err(vm.new_attribute_error("This object has no __weakref__")); + } // Return the first weakref in the weakref list, or None let weakref = obj.get_weakrefs(); - weakref.unwrap_or_else(|| vm.ctx.none()) -} - -// subtype_set_weakref: __weakref__ is read-only -fn subtype_set_weakref(obj: PyObjectRef, _value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - Err(vm.new_attribute_error(format!( - "attribute '__weakref__' of '{}' objects is not writable", - obj.class().name() - ))) + Ok(weakref.unwrap_or_else(|| vm.ctx.none())) } /* * The magical type type */ -/// Vectorcall for PyType (PEP 590). -/// Fast path: type(x) returns x.__class__ without constructing FuncArgs. -/// -/// # Implementation note: `slots.vectorcall` dual use -/// -/// CPython has three distinct fields on PyTypeObject: -/// - `tp_vectorcall`: constructor fast path (e.g. `list_vectorcall`) -/// - `tp_vectorcall_offset`: per-instance vectorcall for callables (e.g. functions) -/// - `tp_call`: standard call slot -/// -/// RustPython collapses the first two into a single `slots.vectorcall`. The -/// `call.is_none()` guard below distinguishes the two uses: callable types have -/// `slots.call` set, so their `slots.vectorcall` is for calling instances, -/// not for construction. -/// -/// This heuristic is correct for all current builtins but is not a general -/// solution — `type` itself is both callable and has a constructor vectorcall, -/// handled by the explicit `zelf.is(type_type)` check above the guard. -/// If more such types arise, consider splitting into a dedicated -/// `constructor_vectorcall` slot. +// Types can be visible to custom mro/__classcell__ code during initialization. +// A missing new slot or constructor implementation leaves ordinary call as fallback. +fn resolve_type_vectorcall(obj: &PyObject) -> Option { + let typ = obj.downcast_ref::()?; + typ.slots.new.load()?; + typ.slots.constructor_vectorcall.load() +} + +/// Vectorcall for type's own constructor (PEP 590). fn vectorcall_type( zelf_obj: &PyObject, args: Vec, @@ -3422,12 +3695,6 @@ fn vectorcall_type( if nargs == 1 && no_kwargs { return Ok(args[0].obj_type()); } - } else if zelf.slots().call.load().is_none() && zelf.slots().new.load().is_some() { - // Per-type constructor vectorcall for non-callable types (dict, list, int, etc.) - // Also guard on slots.new to avoid dispatching for DISALLOW_INSTANTIATION types. - if let Some(type_vc) = zelf.slots().vectorcall.load() { - return type_vc(zelf_obj, args, nargs, kwnames, vm); - } } // Fallback: construct FuncArgs and use standard call @@ -3440,8 +3707,18 @@ pub(crate) fn init(ctx: &'static Context) { ctx.types .type_type .slots - .vectorcall + .constructor_vectorcall .store(Some(vectorcall_type)); + ctx.types + .type_type + .slots + .vectorcall_resolver + .store(Some(resolve_type_vectorcall)); + ctx.types + .type_type + .slots + .flags + .insert(PyTypeFlags::HAVE_VECTORCALL); } pub(crate) fn call_slot_new( @@ -3459,15 +3736,22 @@ pub(crate) fn call_slot_new( return Err(vm.new_type_error(format!("cannot create '{}' instances", subtype.slot_name()))); } - // "is not safe" check (tp_new_wrapper). Walk past bases whose tp_new is - // new_wrapper so a Python subclass of a native heap type still reaches - // that type's tp_new; reject object.__new__(dict) and similar. + // "is not safe" check (tp_new_wrapper logic) + // Check that the user doesn't do something silly and unsafe like + // object.__new__(dict). To do this, we check that the most derived base + // that owns a real tp_new is this type. Walking past the types whose slot + // is only the dynamic wrapper, rather than past every heap type, keeps a + // heap type that carries its own tp_new, as one built from a C spec does, + // from being skipped. let mut staticbase = subtype.clone(); while staticbase .slots .new .load() - .is_some_and(|f| fn_addr(f) == fn_addr(new_wrapper as NewFunc)) + .map(|f| crate::types::fn_addr(f)) + == Some(crate::types::fn_addr( + crate::types::new_wrapper as crate::types::NewFunc, + )) { match staticbase.base.load_owned() { Some(base) => staticbase = base, @@ -3475,9 +3759,10 @@ pub(crate) fn call_slot_new( } } - let typ_new = typ.slots.new.load(); - let staticbase_new = staticbase.slots.new.load(); - if typ_new.map(fn_addr) != staticbase_new.map(fn_addr) { + // Check if staticbase's tp_new differs from typ's tp_new. Compare what the + // slot dispatches to, so that two types reached through the same C + // trampoline are still told apart by their C functions. + if typ.slots.new_identity() != staticbase.slots.new_identity() { return Err(vm.new_type_error(format!( "{}.__new__({}) is not safe, use {}.__new__()", typ.slot_name(), @@ -3518,24 +3803,6 @@ fn take_next_base(bases: &mut [Vec]) -> Option { fn linearise_mro(mut bases: Vec>) -> Result, String> { vm_trace!("Linearise MRO: {:?}", bases); - // Python requires that the class direct bases are kept in the same order. - // This is called local precedence ordering. - // This means we must verify that for classes A(), B(A) we must reject C(A, B) even though this - // algorithm will allow the mro ordering of [C, B, A, object]. - // To verify this, we make sure non of the direct bases are in the mro of bases after them. - for (i, base_mro) in bases.iter().enumerate() { - let base = &base_mro[0]; // MROs cannot be empty. - for later_mro in &bases[i + 1..] { - // We start at index 1 to skip direct bases. - // This will not catch duplicate bases, but such a thing is already tested for. - if later_mro[1..].iter().any(|cls| cls.is(base)) { - return Err(format!( - "Cannot create a consistent method resolution order (MRO) for bases {}", - bases.iter().map(|x| x.first().unwrap()).format(", ") - )); - } - } - } let mut result = vec![]; while !bases.is_empty() { @@ -3544,7 +3811,11 @@ fn linearise_mro(mut bases: Vec>) -> Result, Strin // Because this failed, we assume the lists cannot be empty. format!( "Cannot create a consistent method resolution order (MRO) for bases {}", - bases.iter().map(|x| x.first().unwrap()).format(", ") + bases + .iter() + .map(|x| x.first().unwrap()) + .unique_by(|x| x.get_id()) + .format(", ") ) })?; @@ -3664,20 +3935,62 @@ fn mro_invoke(typ: &Py, vm: &VirtualMachine) -> PyResult> .collect() } +// Called under the existing type lock after publishing an MRO. Match +// type_mro_modified() for both tp_mro and tp_bases: disabling is permanent, +// including when a later __bases__ update restores an ordinary hierarchy. +fn type_mro_modified(typ: &Py, vm: &VirtualMachine) { + let custom_mro = !typ.class().is(vm.ctx.types.type_type) + && match ( + typ.class().find_name_in_mro_uncached(identifier!(vm, mro)), + vm.ctx + .types + .type_type + .find_name_in_mro_uncached(identifier!(vm, mro)), + ) { + (Some(actual), Some(default)) => !actual.is(&default), + (None, None) => false, + _ => true, + }; + let mro = typ.mro_collect(); + let bases = typ.bases.read().clone(); + let disabled = custom_mro + || mro.iter().chain(bases.as_slice().iter()).any(|base| { + base.tp_versions_used.load(Ordering::Acquire) >= ATTR_CACHE_UNUSED + || !is_subtype_with_mro(&mro, typ, base) + }); + if disabled { + // Retire the old tag before disabling assignment: modified_inner() + // needs that tag to clear existing MCACHE entries and descendants. + typ.modified_inner(); + if let Some(ext) = typ.heaptype_ext.as_ref() { + ext.specialization_cache.invalidate_for_type_modified(); + } + typ.tp_versions_used + .store(ATTR_CACHE_UNUSED, Ordering::Release); + } +} + fn mro_internal(typ: &Py, vm: &VirtualMachine) -> PyResult { let old_ptr = typ.mro.read().as_ptr(); let new_mro = mro_invoke(typ, vm)?; - if typ.mro.read().as_ptr() != old_ptr { - return Ok(0); - } - *typ.mro.write() = new_mro; - typ.modified(); - Ok(1) + PyType::with_type_lock(vm, || { + if typ.mro.read().as_ptr() != old_ptr { + return Ok(0); + } + *typ.mro.write() = new_mro; + type_mro_modified(typ, vm); + typ.modified_inner(); + Ok(1) + }) } /// Returns true if the two types have different instance layouts. fn shape_differs(t1: &Py, t2: &Py) -> bool { - t1.slots.basicsize != t2.slots.basicsize || t1.slots.itemsize != t2.slots.itemsize + // Prefix member cells do not change basicsize, but still make a base + // solid: unrelated slotted bases cannot share the same member indexes. + t1.slots.basicsize != t2.slots.basicsize + || t1.slots.itemsize != t2.slots.itemsize + || t1.slots.member_count != t2.slots.member_count } fn solid_base<'a>(typ: &'a Py, vm: &VirtualMachine) -> &'a Py { @@ -3735,20 +4048,21 @@ fn type_has_weakref(typ: &Py) -> bool { /// Returns true if `child` adds no instance layout of its own beyond its base, /// so the base can stand in for it when comparing object layouts. -fn compatible_with_base(child: &Py) -> bool { +fn compatible_with_base(child: &Py, set_class: bool) -> bool { let Some(parent) = child.base.deref() else { return false; }; child.slots.basicsize == parent.slots.basicsize && child.slots.itemsize == parent.slots.itemsize && child.slots.member_count == parent.slots.member_count - && type_has_dict(child) == type_has_dict(parent) - && type_has_weakref(child) == type_has_weakref(parent) + && (!set_class + || (type_has_dict(child) == type_has_dict(parent) + && type_has_weakref(child) == type_has_weakref(parent))) } /// Walk up to the most derived base that actually fixes the instance layout. -fn layout_solid_base(mut typ: &Py) -> &Py { - while compatible_with_base(typ) { +fn layout_solid_base(mut typ: &Py, set_class: bool) -> &Py { + while compatible_with_base(typ, set_class) { typ = typ.base.deref().unwrap(); } typ @@ -3756,12 +4070,12 @@ fn layout_solid_base(mut typ: &Py) -> &Py { /// Returns true if `a` and `b`, which share the same base, added the same /// instance layout (`__dict__`, `__weakref__`, and `__slots__`). -fn same_slots_added(a: &Py, b: &Py) -> bool { +fn same_slots_added(a: &Py, b: &Py, set_class: bool) -> bool { if a.slots.basicsize != b.slots.basicsize || a.slots.itemsize != b.slots.itemsize || a.slots.member_count != b.slots.member_count - || type_has_dict(a) != type_has_dict(b) - || type_has_weakref(a) != type_has_weakref(b) + || (set_class + && (type_has_dict(a) != type_has_dict(b) || type_has_weakref(a) != type_has_weakref(b))) { return false; } @@ -3780,25 +4094,44 @@ fn same_slots_added(a: &Py, b: &Py) -> bool { } } -/// Validates that instances of `old_to` and `new_to` share an interchangeable -/// object layout, the check `__class__` and `__bases__` assignment perform. +/// Validates the layout for `__class__` or `__bases__` assignment. For a base +/// change, `original` is the existing class whose allocation must remain valid. /// /// `attr` names the attribute being assigned for the error message; the -/// message reports `new_to` first and `old_to` second. +/// message reports the new type first and the replaced type or base second. pub(crate) fn compatible_for_assignment( - old_to: &Py, + original: &Py, new_to: &Py, attr: &str, + set_class: bool, vm: &VirtualMachine, ) -> PyResult<()> { - let newbase = layout_solid_base(new_to); - let oldbase = layout_solid_base(old_to); + let old_base = if set_class { + None + } else { + original.base.load_owned() + }; + let old_to = old_base.as_deref().unwrap_or(original); + // Reparenting leaves the class's prefix allocation unchanged. A new base + // may use its existing dict/weakref storage, but cannot require storage + // the class never allocated. Payload size and member slots are checked + // separately against the old base, not against the class's own additions. + let storage_compatible = set_class + || ((!type_has_dict(new_to) || type_has_dict(original)) + && (!type_has_weakref(new_to) || type_has_weakref(original))); + let newbase = layout_solid_base(new_to, set_class); + let oldbase = layout_solid_base(old_to, set_class); let bases_equal = match (newbase.base.deref(), oldbase.base.deref()) { (Some(x), Some(y)) => x.is(y), (None, None) => true, _ => false, }; - let compatible = newbase.is(oldbase) || (bases_equal && same_slots_added(newbase, oldbase)); + let compatible = storage_compatible + && (newbase.is(oldbase) + || (bases_equal + && (set_class + || (newbase.heaptype_ext.is_some() && oldbase.heaptype_ext.is_some())) + && same_slots_added(newbase, oldbase, set_class))); if compatible { return Ok(()); } @@ -3825,6 +4158,32 @@ fn mangle_name(class_name: &str, name: &str) -> String { mod tests { use super::*; + #[test] + fn type_cache_rejects_invalidated_versions() { + let entry = TypeCacheEntry::new(); + let type_version = AtomicU32::new(1); + assert_eq!(entry.matching_version(&type_version), None); + + entry.version.store(1, Ordering::Release); + // A valid negative cache entry has a null value and a nonzero version. + assert!(entry.value.load(Ordering::Acquire).is_null()); + assert_eq!(entry.matching_version(&type_version), Some(1)); + + type_version.store(2, Ordering::Release); + assert_eq!(entry.matching_version(&type_version), None); + + // Model invalidation after a reader has selected the cache entry. + type_version.store(0, Ordering::Release); + assert_eq!(entry.matching_version(&type_version), None); + entry.begin_write(); + entry.version.store(0, Ordering::Release); + entry.clear_value(); + entry.end_write(); + let sequence = entry.begin_read(); + assert_eq!(entry.matching_version(&type_version), None); + assert!(entry.end_read(sequence)); + } + fn map_ids(obj: Result, String>) -> Result, String> { Ok(obj?.into_iter().map(|x| x.get_id()).collect()) } diff --git a/crates/vm/src/builtins/union.rs b/crates/vm/src/builtins/union.rs index 83ea3bb54b3..71f3d666ff8 100644 --- a/crates/vm/src/builtins/union.rs +++ b/crates/vm/src/builtins/union.rs @@ -1,15 +1,15 @@ -use super::{genericalias, type_}; -use crate::common::lock::LazyLock; +use super::{dict::contextualize_hash_error, genericalias}; +use crate::common::lock::{LazyLock, PyMutex}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, builtins::{PyFrozenSet, PySet, PyStr, PyTuple, PyTupleRef, PyType}, class::PyClassImpl, - common::hash, + common::{hash, wtf8::Wtf8Buf}, convert::ToPyObject, function::PyComparisonValue, protocol::{PyMappingMethods, PyNumberMethods}, - stdlib::_typing::{TypeAliasType, call_typing_func_object}, + stdlib::_typing::{TypeAliasType, call_typing_func_object, typing_type_repr}, types::{AsMapping, AsNumber, Comparable, GetAttr, Hashable, PyComparisonOp, Representable}, }; use alloc::fmt; @@ -20,11 +20,11 @@ const CLS_ATTRS: &[&str] = &["__module__"]; pub struct PyUnion { #[pymember(name = "__args__")] args: PyTupleRef, - /// Frozenset of hashable args, or None if all args were hashable - hashable_args: Option>, + /// Frozenset of args that were hashable at creation time + hashable_args: PyRef, /// Tuple of initially unhashable args, or None if all args were hashable unhashable_args: Option, - parameters: PyTupleRef, + parameters: PyMutex>, } impl fmt::Debug for PyUnion { @@ -41,17 +41,6 @@ impl PyPayload for PyUnion { } impl PyUnion { - /// Create a new union from dedup result (internal use) - fn from_components(result: UnionComponents, vm: &VirtualMachine) -> PyResult { - let parameters = make_parameters(&result.args, vm)?; - Ok(Self { - args: result.args, - hashable_args: result.hashable_args, - unhashable_args: result.unhashable_args, - parameters, - }) - } - /// Direct access to args field (_Py_union_args) #[inline] #[must_use] @@ -59,50 +48,24 @@ impl PyUnion { &self.args } - fn repr(&self, vm: &VirtualMachine) -> PyResult { - fn repr_item(obj: &PyObject, vm: &VirtualMachine) -> PyResult { - if obj.is(vm.ctx.types.none_type) { - return Ok("None".to_string()); - } - - if vm - .get_attribute_opt(obj, identifier!(vm, __origin__))? - .is_some() - && vm - .get_attribute_opt(obj, identifier!(vm, __args__))? - .is_some() - { - return Ok(obj.repr(vm)?.to_string()); - } - - match ( - vm.get_attribute_opt(obj, identifier!(vm, __qualname__))? - .and_then(|o| o.downcast_ref::().map(|n| n.to_string())), - vm.get_attribute_opt(obj, identifier!(vm, __module__))? - .and_then(|o| o.downcast_ref::().map(|m| m.to_string())), - ) { - (None, _) | (_, None) => Ok(obj.repr(vm)?.to_string()), - (Some(qualname), Some(module)) => Ok(if module == "builtins" { - qualname - } else { - format!("{module}.{qualname}") - }), + fn repr(&self, vm: &VirtualMachine) -> PyResult { + let mut repr = Wtf8Buf::new(); + for (i, arg) in self.args.as_slice().iter().enumerate() { + if i > 0 { + repr.push_str(" | "); } + typing_type_repr(&mut repr, arg, vm)?; } - - Ok(self - .args - .as_slice() - .iter() - .map(|o| repr_item(o, vm)) - .collect::>>()? - .join(" | ")) + Ok(repr) } } impl PyUnion { fn __or__(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - type_::or_(zelf, other, vm) + let mut builder = UnionBuilder::new(true); + builder.add(&zelf, vm)?; + builder.add(&other, vm)?; + builder.finish(vm) } } @@ -127,8 +90,8 @@ impl Py { } #[pygetset] - fn __parameters__(&self) -> PyObjectRef { - self.parameters.clone().into() + fn __parameters__(&self, vm: &VirtualMachine) -> PyResult { + genericalias::cached_parameters(&self.parameters, &self.args, vm) } #[pymethod] @@ -173,7 +136,9 @@ impl Py { _object: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - Err(vm.new_type_error(format!("Cannot subclass {}", zelf.repr(vm)?))) + let mut message = Wtf8Buf::from("Cannot subclass "); + message.push_wtf8(&zelf.repr(vm)?); + Err(vm.new_type_error(message)) } #[pyclassmethod] @@ -182,26 +147,20 @@ impl Py { object: PyObjectRef, vm: &VirtualMachine, ) -> PyResult { - // Convert args to tuple if not already - let args_tuple = if let Some(tuple) = object.downcast_ref::() { - tuple.to_owned() + let mut builder = UnionBuilder::new(true); + if let Some(tuple) = object.downcast_ref_if_exact::(vm) { + builder.add_tuple(tuple, vm)?; } else { - PyTuple::new_ref(vec![object], &vm.ctx) - }; - - // Check for empty union - if args_tuple.as_slice().is_empty() { - return Err(vm.new_type_error("Cannot create empty Union")); + builder.add(&object, vm)?; } - - // Create union using make_union to properly handle None -> NoneType conversion - make_union(&args_tuple, vm) + builder.finish(vm) } } fn is_unionable(obj: &PyObject, vm: &VirtualMachine) -> bool { let cls = obj.class(); - cls.is(vm.ctx.types.none_type) + vm.is_none(obj) + || cls.is(vm.ctx.types.sentinel_type) || obj.downcastable::() || cls.fast_issubclass(vm.ctx.types.generic_alias_type) || cls.is(vm.ctx.types.union_type) @@ -220,180 +179,148 @@ fn type_check(arg: PyObjectRef, vm: &VirtualMachine) -> PyResult { call_typing_func_object(vm, "_type_check", (arg, message_str)) } -fn has_union_operands(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> bool { - let union_type = vm.ctx.types.union_type; - a.class().is(union_type) || b.class().is(union_type) -} - pub(crate) fn or_op(zelf: PyObjectRef, other: PyObjectRef, vm: &VirtualMachine) -> PyResult { - if !has_union_operands(&zelf, &other, vm) - && (!is_unionable(&zelf, vm) || !is_unionable(&other, vm)) - { + if !is_unionable(&zelf, vm) || !is_unionable(&other, vm) { return Ok(vm.ctx.not_implemented()); } - let left = type_check(zelf, vm)?; - let right = type_check(other, vm)?; - let tuple = PyTuple::new_ref(vec![left, right], &vm.ctx); - make_union(&tuple, vm) + // Type, GenericAlias, Sentinel and TypeAliasType have already checked both + // operands. Unlike Union.__or__, their slots do not recheck flattened args. + let mut builder = UnionBuilder::new(false); + builder.add(&zelf, vm)?; + builder.add(&other, vm)?; + builder.finish(vm) +} + +fn contains_arg(args: &[PyObjectRef], needle: &PyObject, vm: &VirtualMachine) -> PyResult { + for arg in args { + if vm.identical_or_equal(arg, needle)? { + return Ok(true); + } + } + Ok(false) } -fn make_parameters(args: &Py, vm: &VirtualMachine) -> PyResult { - let parameters = genericalias::make_parameters(args, vm)?; - let result = dedup_and_flatten_args(¶meters, vm)?; - Ok(result.args) +struct UnionBuilder { + args: Vec, + hashable_args: PySet, + unhashable_args: Vec, + is_checked: bool, } -fn flatten_args(args: &Py, vm: &VirtualMachine) -> PyTupleRef { - let mut total_args = 0; - for arg in args { - if let Some(pyref) = arg.downcast_ref::() { - total_args += pyref.args.as_slice().len(); - } else { - total_args += 1; - }; +impl Drop for UnionBuilder { + fn drop(&mut self) { + // Match list cleanup order, keeping the cached set alive until all + // ordered args have been released and unhashable args alive until last. + for _arg in self.args.drain(..).rev() {} + drop(core::mem::take(&mut self.hashable_args)); + for _arg in self.unhashable_args.drain(..).rev() {} } +} - let mut flattened_args = Vec::with_capacity(total_args); - for arg in args { - if let Some(pyref) = arg.downcast_ref::() { - flattened_args.extend(pyref.args.as_slice().iter().cloned()); - } else if vm.is_none(arg) { - flattened_args.push(vm.ctx.types.none_type.to_owned().into()); - } else if arg.downcast_ref::().is_some() { - // Convert string to ForwardRef - match string_to_forwardref(arg.clone(), vm) { - Ok(fr) => flattened_args.push(fr), - Err(_) => flattened_args.push(arg.clone()), - } - } else { - flattened_args.push(arg.clone()); - }; +impl UnionBuilder { + fn new(is_checked: bool) -> Self { + Self { + args: Vec::new(), + hashable_args: PySet::default(), + unhashable_args: Vec::new(), + is_checked, + } } - PyTuple::new_ref(flattened_args, &vm.ctx) -} + fn add_tuple(&mut self, args: &Py, vm: &VirtualMachine) -> PyResult<()> { + for arg in args { + self.add(arg, vm)?; + } + Ok(()) + } -fn string_to_forwardref(arg: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // Import annotationlib.ForwardRef and create a ForwardRef - let annotationlib = vm.import("annotationlib", 0)?; - let forwardref_cls = annotationlib.get_attr("ForwardRef", vm)?; - forwardref_cls.call((arg,), vm) -} + fn add(&mut self, arg: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + let arg = if vm.is_none(arg) { + vm.ctx.types.none_type.as_object() + } else if let Some(union) = arg.downcast_ref::() { + return self.add_tuple(&union.args, vm); + } else { + arg + }; -/// Components for creating a PyUnion after deduplication -struct UnionComponents { - /// All unique args in order - args: PyTupleRef, - /// Frozenset of hashable args (for fast equality comparison) - hashable_args: Option>, - /// Tuple of unhashable args at creation time (for hash error message) - unhashable_args: Option, -} + if self.is_checked { + // Keep the original input borrowed and the checked result owned + // until insertion finishes, including when checking replaces it. + let checked = type_check(arg.to_owned(), vm)?; + self.add_unchecked(&checked, vm) + } else { + self.add_unchecked(arg, vm) + } + } -fn dedup_and_flatten_args(args: &Py, vm: &VirtualMachine) -> PyResult { - let args = flatten_args(args, vm); - - // Use set-based deduplication like CPython: - // - For hashable elements: use Python's set semantics (hash + equality) - // - For unhashable elements: use equality comparison - // - // This avoids calling __eq__ when hashes differ, so `int | BadType` - // doesn't raise even if BadType.__eq__ raises. - - let mut new_args: Vec = Vec::with_capacity(args.as_slice().len()); - - // Track hashable elements using a Python set (uses hash + equality) - let hashable_set = PySet::default().into_ref(&vm.ctx); - let mut hashable_list: Vec = Vec::new(); - let mut unhashable_list: Vec = Vec::new(); - - for arg in &*args { - // Try to hash the element first - match arg.hash(vm) { - Ok(_) => { - // Element is hashable - use set for deduplication - // Set membership uses hash first, then equality only if hashes match - let contains = vm - .call_method(hashable_set.as_ref(), "__contains__", (arg.clone(),)) - .and_then(|r| r.try_to_bool(vm))?; - if !contains { - hashable_set.add(arg.clone(), vm)?; - hashable_list.push(arg.clone()); - new_args.push(arg.clone()); - } + fn add_unchecked(&mut self, arg: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + // Only the initial hash failure classifies an argument as unhashable. + // Membership and insertion hash again, wrapping only exact TypeErrors + // from hashing. Errors from equality must propagate unchanged. + if arg.hash(vm).is_ok() { + let key_hash = || { + arg.hash(vm) + .map_err(|exc| contextualize_hash_error(arg, "set", "element", exc, vm)) + }; + let hash = key_hash()?; + if self + .hashable_args + .inner + .contains_known_hash(arg, hash, vm)? + { + return Ok(()); } - Err(_) => { - // Element is unhashable - use equality comparison - let mut is_duplicate = false; - for existing in &unhashable_list { - match existing.rich_compare_bool(arg, PyComparisonOp::Eq, vm) { - Ok(true) => { - is_duplicate = true; - break; - } - Ok(false) => continue, - Err(e) => return Err(e), - } - } - if !is_duplicate { - unhashable_list.push(arg.clone()); - new_args.push(arg.clone()); - } + let hash = key_hash()?; + self.hashable_args.inner.insert_known_hash(arg, hash, vm)?; + } else { + if contains_arg(&self.unhashable_args, arg, vm)? { + return Ok(()); } + self.unhashable_args.push(arg.to_owned()); } + self.args.push(arg.to_owned()); + Ok(()) } - new_args.shrink_to_fit(); - - // Create hashable_args frozenset if there are hashable elements - let hashable_args = if !hashable_list.is_empty() { - Some(PyFrozenSet::from_iter(vm, hashable_list)?.into_ref(&vm.ctx)) - } else { - None - }; - - // Create unhashable_args tuple if there are unhashable elements - let unhashable_args = if !unhashable_list.is_empty() { - Some(PyTuple::new_ref(unhashable_list, &vm.ctx)) - } else { - None - }; - - Ok(UnionComponents { - args: PyTuple::new_ref(new_args, &vm.ctx), - hashable_args, - unhashable_args, - }) + fn finish(mut self, vm: &VirtualMachine) -> PyResult { + match self.args.len() { + 0 => Err(vm.new_type_error("Cannot take a Union of no types.")), + 1 => Ok(self.args[0].clone()), + _ => { + // Keep even an empty hashable partition, and preserve its stored + // hashes without another round of user hash/equality callbacks. + let args = PyTuple::new_ref(core::mem::take(&mut self.args), &vm.ctx); + let hashable_args = core::mem::take(&mut self.hashable_args) + .into_frozen() + .into_ref(&vm.ctx); + let unhashable_args = (!self.unhashable_args.is_empty()) + .then(|| PyTuple::new_ref(core::mem::take(&mut self.unhashable_args), &vm.ctx)); + Ok(PyUnion { + args, + hashable_args, + unhashable_args, + parameters: PyMutex::new(None), + } + .to_pyobject(vm)) + } + } + } } pub fn make_union(args: &Py, vm: &VirtualMachine) -> PyResult { - let result = dedup_and_flatten_args(args, vm)?; - Ok(match result.args.as_slice().len() { - 1 => result.args.as_slice()[0].to_owned(), - _ => PyUnion::from_components(result, vm)?.to_pyobject(vm), - }) + let mut builder = UnionBuilder::new(true); + builder.add_tuple(args, vm)?; + builder.finish(vm) } impl PyUnion { fn getitem(zelf: &Py, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let new_args = genericalias::subs_parameters( - zelf.as_object(), - &zelf.args, - &zelf.parameters, - needle, - vm, - )?; - - Ok(if new_args.as_slice().is_empty() { - make_union(&new_args, vm)? - } else { - let mut tmp = new_args.as_slice()[0].to_owned(); - for arg in new_args.as_slice().iter().skip(1) { - tmp = vm._or(&tmp, arg)?; - } - tmp - }) + let parameters = genericalias::cached_parameters(&zelf.parameters, &zelf.args, vm)?; + let new_args = + genericalias::subs_parameters(zelf.as_object(), &zelf.args, ¶meters, needle, vm)?; + + make_union(&new_args, vm) } } @@ -430,56 +357,33 @@ impl Comparable for PyUnion { op.eq_only(|| { let other = class_or_notimplemented!(Self, other); - // Check if lengths are equal - if zelf.args.as_slice().len() != other.args.as_slice().len() { + // Creation-time partitions determine equality, even if a member's + // hashability has changed since either union was constructed. + if !zelf.hashable_args.as_object().rich_compare_bool( + other.hashable_args.as_object(), + PyComparisonOp::Eq, + vm, + )? { return Ok(PyComparisonValue::Implemented(false)); } - // Fast path: if both unions have all hashable args, compare frozensets directly - // Always use Eq here since eq_only handles Ne by negating the result - if zelf.unhashable_args.is_none() - && other.unhashable_args.is_none() - && let (Some(a), Some(b)) = (&zelf.hashable_args, &other.hashable_args) - { - let eq = a - .as_object() - .rich_compare_bool(b.as_object(), PyComparisonOp::Eq, vm)?; - return Ok(PyComparisonValue::Implemented(eq)); - } - - // Slow path: O(n^2) nested loop comparison for unhashable elements - // Check if all elements in zelf.args are in other.args - for arg_a in &*zelf.args { - let mut found = false; - for arg_b in &*other.args { - match arg_a.rich_compare_bool(arg_b, PyComparisonOp::Eq, vm) { - Ok(true) => { - found = true; - break; - } - Ok(false) => continue, - Err(e) => return Err(e), // Propagate comparison errors + match (&zelf.unhashable_args, &other.unhashable_args) { + (Some(a), Some(b)) => { + if a.as_slice().len() != b.as_slice().len() { + return Ok(PyComparisonValue::Implemented(false)); } - } - if !found { - return Ok(PyComparisonValue::Implemented(false)); - } - } - - // Check if all elements in other.args are in zelf.args (for symmetry) - for arg_b in &*other.args { - let mut found = false; - for arg_a in &*zelf.args { - match arg_b.rich_compare_bool(arg_a, PyComparisonOp::Eq, vm) { - Ok(true) => { - found = true; - break; + // Tuple containment compares the stored member to the + // needle, with an identity shortcut, in both directions. + for (needles, haystack) in [(a, b), (b, a)] { + for arg in &**needles { + if !contains_arg(haystack.as_slice(), arg, vm)? { + return Ok(PyComparisonValue::Implemented(false)); + } } - Ok(false) => continue, - Err(e) => return Err(e), // Propagate comparison errors } } - if !found { + (None, None) => {} + _ => { return Ok(PyComparisonValue::Implemented(false)); } } @@ -501,28 +405,10 @@ impl Hashable for PyUnion { } // All previously unhashable args somehow became hashable // But still raise an error to maintain consistent hashing - return Err(vm.new_type_error(format!( - "union contains {} unhashable element{}", - n, - if n > 1 { "s" } else { "" } - ))); + return Err(vm.new_type_error(format!("union contains {n} unhashable elements"))); } - // If we have a stored frozenset of hashable args, use that - if let Some(ref hashable_args) = zelf.hashable_args { - return PyFrozenSet::hash(hashable_args, vm); - } - - // Fallback: compute hash from args - let mut args_to_hash = Vec::new(); - for arg in &*zelf.args { - match arg.hash(vm) { - Ok(_) => args_to_hash.push(arg.clone()), - Err(e) => return Err(e), - } - } - let set = PyFrozenSet::from_iter(vm, args_to_hash)?; - PyFrozenSet::hash(&set.into_ref(&vm.ctx), vm) + PyFrozenSet::hash(&zelf.hashable_args, vm) } } @@ -539,7 +425,7 @@ impl GetAttr for PyUnion { impl Representable for PyUnion { #[inline] - fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { zelf.repr(vm) } } diff --git a/crates/vm/src/builtins/weakproxy.rs b/crates/vm/src/builtins/weakproxy.rs index efd8cb306c5..3d56ef129eb 100644 --- a/crates/vm/src/builtins/weakproxy.rs +++ b/crates/vm/src/builtins/weakproxy.rs @@ -1,19 +1,20 @@ use super::{PyStr, PyStrRef, PyType, PyWeak}; use crate::common::lock::LazyLock; use crate::{ - Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, + AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + atomic_func, class::PyClassImpl, common::hash::PyHash, - function::{FuncArgs, PyArithmeticValue, PyComparisonValue, PySetterValue}, + function::{Either, FuncArgs, PyArithmeticValue, PyComparisonValue, PySetterValue}, protocol::{PyIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, - stdlib::builtins::reversed, types::{ AsMapping, AsNumber, AsSequence, Callable, Comparable, Constructor, GetAttr, Hashable, IterNext, Iterable, PyComparisonOp, Representable, SetAttr, }, }; +use rustpython_common::wtf8::{Wtf8Buf, wtf8_concat}; -#[pyclass(module = "weakref", name = "weakproxy", unhashable = true)] +#[pyclass(module = "weakref", name = "ProxyType", unhashable = true)] #[derive(Debug)] #[repr(transparent)] pub struct PyWeakProxy(PyWeak); @@ -79,7 +80,7 @@ impl PyWeakProxy { #[pyclass( module = "weakref", - name = "weakcallableproxy", + name = "CallableProxyType", base = PyWeakProxy, ctx = "weakcallableproxy_type", unhashable = true @@ -88,7 +89,7 @@ impl PyWeakProxy { #[repr(transparent)] pub struct PyWeakCallableProxy(PyWeakProxy); -#[pyclass(with(Callable, Constructor))] +#[pyclass(with(Callable, Constructor), flags(IMMUTABLETYPE))] impl PyWeakCallableProxy {} impl Constructor for PyWeakCallableProxy { @@ -137,17 +138,45 @@ impl PyWeakProxy { } } -#[pyclass(with( - GetAttr, - SetAttr, - Constructor, - Comparable, - AsNumber, - AsSequence, - AsMapping, - Representable, - IterNext -))] +impl Comparable for PyWeakProxy { + fn slot_richcompare( + zelf: &PyObject, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult> { + proxy_binary_op(zelf, other, vm, |vm, a, b| a.rich_compare(b, op, vm)).map(Either::A) + } + + fn cmp( + zelf: &Py, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult { + match Self::slot_richcompare(zelf.as_object(), other, op, vm)? { + Either::A(value) => PyArithmeticValue::from_object(vm, value) + .map(|value| value.try_to_bool(vm)) + .transpose(), + Either::B(value) => Ok(value), + } + } +} + +#[pyclass( + with( + Comparable, + GetAttr, + SetAttr, + Constructor, + AsNumber, + AsSequence, + AsMapping, + Representable, + IterNext + ), + flags(IMMUTABLETYPE) +)] impl Py { /// Return str(self). #[pymethod] @@ -163,7 +192,7 @@ impl Py { #[pymethod] fn __reversed__(&self, vm: &VirtualMachine) -> PyResult { let obj = self.try_upgrade(vm)?; - reversed(obj, vm) + vm.call_method(&obj, identifier!(vm, __reversed__).as_str(), ()) } } @@ -243,13 +272,16 @@ fn proxy_binary_op( a: &PyObject, b: &PyObject, vm: &VirtualMachine, - op: fn(&VirtualMachine, &PyObject, &PyObject) -> PyResult, + op: impl FnOnce(&VirtualMachine, &PyObject, &PyObject) -> PyResult, ) -> PyResult { let a_up = proxy_upgrade_opt(a, vm)?; let b_up = proxy_upgrade_opt(b, vm)?; let a_ref = a_up.as_deref().unwrap_or(a); let b_ref = b_up.as_deref().unwrap_or(b); - op(vm, a_ref, b_ref) + let result = op(vm, a_ref, b_ref); + // CPython releases unwrapped operands in argument order after the callback. + drop(a_up); + result } macro_rules! proxy_binary_slot { @@ -271,7 +303,10 @@ fn proxy_ternary_op( let a_ref = a_up.as_deref().unwrap_or(a); let b_ref = b_up.as_deref().unwrap_or(b); let c_ref = c_up.as_deref().unwrap_or(c); - op(vm, a_ref, b_ref, c_ref) + let result = op(vm, a_ref, b_ref, c_ref); + drop(a_up); + drop(b_up); + result } macro_rules! proxy_ternary_slot { @@ -335,23 +370,6 @@ impl AsNumber for PyWeakProxy { } } -impl Comparable for PyWeakProxy { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - let obj = zelf.try_upgrade(vm)?; - // CPython parity (Objects/weakref.c::proxy_richcompare): delegate to - // PyObject_RichCompare on the referent, not the bool variant. - let res = obj.rich_compare(other.to_owned(), op, vm)?; - PyArithmeticValue::from_object(vm, res) - .map(|o| o.try_to_bool(vm)) - .transpose() - } -} - impl AsSequence for PyWeakProxy { fn as_sequence() -> &'static PySequenceMethods { static AS_SEQUENCE: LazyLock = LazyLock::new(|| PySequenceMethods { @@ -387,13 +405,18 @@ impl AsMapping for PyWeakProxy { impl Representable for PyWeakProxy { #[inline] - fn repr(zelf: &Py, vm: &VirtualMachine) -> PyResult { - zelf.try_upgrade(vm)?.repr(vm) - } - - #[cold] - fn repr_str(_zelf: &Py, _vm: &VirtualMachine) -> PyResult { - unreachable!("use repr instead") + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let id = zelf.get_id(); + let Some(obj) = zelf.0.upgrade() else { + return Ok(format!("").into()); + }; + let type_name = obj.class().fully_qualified_name(vm)?; + let obj_id = obj.get_id(); + Ok(wtf8_concat!( + format!("") + )) } } diff --git a/crates/vm/src/builtins/weakref.rs b/crates/vm/src/builtins/weakref.rs index 135db6866cb..c4be6196bf4 100644 --- a/crates/vm/src/builtins/weakref.rs +++ b/crates/vm/src/builtins/weakref.rs @@ -1,16 +1,19 @@ use super::{PyGenericAlias, PyType, PyTypeRef}; +#[cfg(not(feature = "threading"))] +use crate::common::atomic::Radium; use crate::common::{ - atomic::{Ordering, Radium}, + atomic::Ordering, hash::{self, PyHash}, }; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, class::PyClassImpl, - function::{FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, + function::{Either, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, types::{ Callable, Comparable, Constructor, Hashable, Initializer, PyComparisonOp, Representable, }, }; +use rustpython_common::wtf8::{Wtf8Buf, wtf8_concat}; pub use crate::object::PyWeak; @@ -24,6 +27,9 @@ pub struct WeakNewArgs { } impl PyPayload for PyWeak { + // WeakRefList::add tracks only after linking and publishing the referent. + const NEW_REF_UNTRACKED: bool = true; + #[inline] fn class(ctx: &Context) -> &'static Py { ctx.types.weakref_type @@ -72,11 +78,57 @@ impl Initializer for PyWeak { } } +impl Comparable for PyWeak { + fn slot_richcompare( + zelf: &PyObject, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult> { + if !matches!(op, PyComparisonOp::Eq | PyComparisonOp::Ne) { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + } + // PyWeakref_Check also accepts both proxy types, which share this payload. + let (Some(zelf), Some(other)) = (zelf.downcast_ref::(), other.downcast_ref::()) + else { + return Ok(Either::B(PyComparisonValue::NotImplemented)); + }; + let a = zelf.upgrade(); + let b = other.upgrade(); + let result = match (&a, &b) { + // PyObject_RichCompare preserves the exact operation and raw result, + // including when both references point to the same object. + (Some(a), Some(b)) => PyObject::rich_compare(a, b, op, vm).map(Either::A), + _ => { + let equal = zelf.is(other); + Ok(Either::B((equal == (op == PyComparisonOp::Eq)).into())) + } + }; + // Release the upgraded referents in argument order, also on errors. + drop(a); + result + } + + fn cmp( + zelf: &Py, + other: &PyObject, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult { + match Self::slot_richcompare(zelf.as_object(), other, op, vm)? { + Either::A(value) => PyArithmeticValue::from_object(vm, value) + .map(|value| value.try_to_bool(vm)) + .transpose(), + Either::B(value) => Ok(value), + } + } +} + #[pyclass( with( Callable, - Hashable, Comparable, + Hashable, Constructor, Initializer, Representable @@ -101,58 +153,27 @@ impl Py { impl Hashable for PyWeak { fn hash(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let hash = match zelf.hash.load(Ordering::Relaxed) { - hash::SENTINEL => { - let obj = zelf - .upgrade() - .ok_or_else(|| vm.new_type_error("weak object has gone away"))?; - let hash = obj.hash(vm)?; - match Radium::compare_exchange( - &zelf.hash, - hash::SENTINEL, - hash::fix_sentinel(hash), - Ordering::Relaxed, - Ordering::Relaxed, - ) { - Ok(_) => hash, - Err(prev_stored) => prev_stored, - } - } - hash => hash, - }; - Ok(hash) - } -} - -impl Comparable for PyWeak { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - op.eq_only(|| { - let other = class_or_notimplemented!(Self, other); - let both = zelf.upgrade().zip(other.upgrade()); - match both { - // CPython parity (Objects/weakref.c::weakref_richcompare): use - // PyObject_RichCompare on the referents, not the bool variant, - // so referent __eq__ runs even when referents share identity. - Some((a, b)) => { - let res = a.rich_compare(b, PyComparisonOp::Eq, vm)?; - PyArithmeticValue::from_object(vm, res) - .map(|obj| obj.try_to_bool(vm)) - .transpose() - } - None => Ok(zelf.is(other).into()), - } - }) + let cached = zelf.hash.load(Ordering::Relaxed); + if cached != hash::SENTINEL { + return Ok(cached); + } + let obj = zelf + .upgrade() + .ok_or_else(|| vm.new_type_error("weak object has gone away"))?; + let result = obj.hash(vm).map(hash::fix_sentinel); + // A recursive hash may have filled the cache. The outer call still + // replaces it, or clears it on failure, before releasing the referent. + zelf.hash.store( + result.as_ref().copied().unwrap_or(hash::SENTINEL), + Ordering::Relaxed, + ); + result } } /// `__name__` when that lookup yields a string. A missing name or a non-string /// value is left off the repr. -fn instance_name(obj: &PyObject, vm: &VirtualMachine) -> PyResult> { +fn instance_name(obj: &PyObject, vm: &VirtualMachine) -> PyResult> { let found = crate::vm::PyMethod::get_special_ex::(obj, identifier!(vm, __name__), vm, true)?; let Some(crate::vm::PyMethod::Attribute(attr)) = found else { @@ -160,25 +181,28 @@ fn instance_name(obj: &PyObject, vm: &VirtualMachine) -> PyResult }; Ok(attr .downcast_ref::() - .and_then(|name| name.to_str()) - .map(str::to_owned)) + .map(|name| name.as_wtf8().to_owned())) } impl Representable for PyWeak { #[inline] - fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { let id = zelf.get_id(); let Some(obj) = zelf.upgrade() else { - return Ok(format!("")); + return Ok(format!("").into()); }; let type_name = obj.class().fully_qualified_name(vm)?; let obj_id = obj.get_id(); let suffix = match instance_name(&obj, vm)? { - Some(name) => format!(" ({name})"), - None => String::new(), + Some(name) => wtf8_concat!(" (", name, ")"), + None => Wtf8Buf::new(), }; - Ok(format!( - "" + Ok(wtf8_concat!( + format!("" )) } } diff --git a/crates/vm/src/builtins/zip.rs b/crates/vm/src/builtins/zip.rs index 3bdaca7f707..7bc819d9575 100644 --- a/crates/vm/src/builtins/zip.rs +++ b/crates/vm/src/builtins/zip.rs @@ -1,9 +1,9 @@ use super::PyType; use crate::{ - AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, + AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::PyTupleRef, class::PyClassImpl, - function::{ArgIntoBool, PosArgs}, + function::{OptionalArg, PosArgs}, protocol::{PyIter, PyIterReturn}, types::{Constructor, IterNext, Iterable, SelfIter}, }; @@ -27,9 +27,9 @@ impl PyPayload for PyZip { #[derive(FromArgs)] pub struct PyZipNewArgs { #[pyarg(flatten)] - iterables: PosArgs, - #[pyarg(named, default)] - strict: bool, + iterables: PosArgs, + #[pyarg(named, default, py_default = "False")] + strict: OptionalArg, } impl Constructor for PyZip { @@ -37,12 +37,19 @@ impl Constructor for PyZip { fn py_new( _cls: &Py, - PyZipNewArgs { iterables, strict }: Self::Args, - _vm: &VirtualMachine, + Self::Args { iterables, strict }: Self::Args, + vm: &VirtualMachine, ) -> PyResult { - let iterators = iterables.into_vec(); - let strict = Radium::new(strict); - Ok(Self { iterators, strict }) + let result = (|| { + let strict = strict_value(&strict, vm)?; + let iterators = get_iterators(iterables.iter(), vm)?; + Ok(Self { + iterators, + strict: Radium::new(strict), + }) + })(); + release_iterables(strict, iterables); + result } } @@ -65,10 +72,10 @@ impl PyZip { } #[pymethod] - fn __setstate__(zelf: PyRef, object: PyObjectRef, vm: &VirtualMachine) { - if let Ok(obj) = ArgIntoBool::try_from_object(vm, object) { - zelf.strict.store(obj.into(), atomic::Ordering::Release); - } + fn __setstate__(zelf: PyRef, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + let strict = object.try_to_bool(vm)?; + zelf.strict.store(strict, atomic::Ordering::Release); + Ok(()) } } @@ -80,41 +87,113 @@ impl IterNext for PyZip { return Ok(PyIterReturn::StopIteration(None)); } let mut next_objs = Vec::with_capacity(zelf.iterators.len()); - for (idx, iterator) in zelf.iterators.iter().enumerate() { - let item = match iterator.next(vm)? { - PyIterReturn::Return(obj) => obj, - PyIterReturn::StopIteration(v) => { - if zelf.strict.load(atomic::Ordering::Acquire) { - if idx > 0 { - let plural = if idx == 1 { " " } else { "s 1-" }; - return Err(vm.new_value_error(format!( - "zip() argument {} is shorter than argument{}{}", - idx + 1, - plural, - idx - ))); - } - for (idx, iterator) in zelf.iterators[1..].iter().enumerate() { - if let PyIterReturn::Return(_obj) = iterator.next(vm)? { - let plural = if idx == 0 { " " } else { "s 1-" }; - return Err(vm.new_value_error(format!( - "zip() argument {} is longer than argument{}{}", - idx + 2, - plural, - idx + 1 - ))); - } - } - } - return Ok(PyIterReturn::StopIteration(v)); - } - }; + for idx in 0..zelf.iterators.len() { + let item = + crate::raise_if_stop!(next_item(&zelf.iterators, idx, &zelf.strict, "zip", vm)?); next_objs.push(item); } Ok(PyIterReturn::Return(vm.ctx.new_tuple(next_objs).into())) } } +pub(super) fn strict_value( + strict: &OptionalArg, + vm: &VirtualMachine, +) -> PyResult { + strict + .as_ref() + .map(|value| value.try_to_bool(vm)) + .transpose() + .map(|value| value.unwrap_or(false)) +} + +pub(super) fn get_iterators<'a>( + iterables: impl IntoIterator, + vm: &VirtualMachine, +) -> PyResult> { + let iterables = iterables.into_iter(); + let mut iterators = Vec::with_capacity(iterables.size_hint().0); + for obj in iterables { + match obj.get_iter(vm) { + Ok(iterator) => iterators.push(iterator), + Err(error) => { + while let Some(_iterator) = iterators.pop() {} + return Err(error); + } + } + } + Ok(iterators) +} + +// Constructor callbacks borrow the complete argument list. Release it only +// afterwards, in call-stack order, including when conversion failed. +pub(super) fn release_iterables( + strict: OptionalArg, + iterables: PosArgs, +) { + drop(strict); + iterables.into_iter().rev().for_each(drop); +} + +// Read strict after the source callback, but before clearing a StopIteration +// exception: either operation can run user code that changes the flag. +pub(super) fn next_item( + iterators: &[PyIter], + index: usize, + strict: &PyAtomic, + name: &str, + vm: &VirtualMachine, +) -> PyResult { + let result = iterators[index].next(vm); + if matches!(&result, Ok(PyIterReturn::Return(_))) || !strict.load(atomic::Ordering::Acquire) { + return result; + } + // Native iterators can surface StopIteration as an exception as well as + // the dedicated return variant (for example, a filter item's __bool__). + // Preserve the original exception in non-strict mode. + match result.or_else(|error| PyIterReturn::from_pyresult(Err(error), vm))? { + PyIterReturn::StopIteration(value) => { + drop(value); + strict_exhausted(iterators, index, name, vm) + } + item => Ok(item), + } +} + +// Both map and zip check the remaining sources only when the first one stops. +// Callers clear its StopIteration value before checking: strict exhaustion does +// not propagate source return values, unlike ordinary shortest-input iteration. +fn strict_exhausted( + iterators: &[PyIter], + stopped: usize, + name: &str, + vm: &VirtualMachine, +) -> PyResult { + let (index, direction) = if stopped > 0 { + (stopped, "shorter") + } else { + let mut longer = None; + for (index, iterator) in iterators.iter().enumerate().skip(1) { + if let PyIterReturn::Return(_item) = iterator + .next(vm) + .or_else(|error| PyIterReturn::from_pyresult(Err(error), vm))? + { + longer = Some(index); + break; + } + } + let Some(index) = longer else { + return Ok(PyIterReturn::StopIteration(None)); + }; + (index, "longer") + }; + let plural = if index == 1 { " " } else { "s 1-" }; + Err(vm.new_value_error(format!( + "{name}() argument {} is {direction} than argument{plural}{index}", + index + 1, + ))) +} + pub(crate) fn init(ctx: &'static Context) { PyZip::extend_class(ctx, ctx.types.zip_type); } diff --git a/crates/vm/src/byte.rs b/crates/vm/src/byte.rs index aadbc518403..53eddff24f4 100644 --- a/crates/vm/src/byte.rs +++ b/crates/vm/src/byte.rs @@ -4,7 +4,7 @@ use num_traits::ToPrimitive; use crate::{ AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine, - protocol::{BufferFlags, PyBuffer}, + protocol::{BufferFlags, PyBuffer, PyIterIter}, }; /// The element error `bytes` reports, which is the one entry point here that does @@ -32,9 +32,35 @@ pub fn bytearray_from_object(vm: &VirtualMachine, obj: &PyObject) -> PyResult PyResult> { - collect_bytes(vm, obj, true, BYTE_ELEMENT_ERROR, |name| { - format!("can't extend bytearray with {name}") - }) + let iter = obj.to_owned().get_iter(vm).map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + vm.new_type_error(format!( + "can't extend bytearray with {}", + obj.class().name() + )) + } else { + error + } + })?; + let hint = vm.length_hint_opt(obj.to_owned())?.unwrap_or(32); + let mut items = Vec::new(); + items + .try_reserve_exact(hint) + .map_err(|_| vm.new_memory_error(""))?; + for item in PyIterIter::::new(vm, iter.as_ref(), Some(hint)) { + let item = item?; + let value = value_from_object(vm, &item).map_err(|error| { + if obj.fast_isinstance(vm.ctx.types.str_type) + && error.fast_isinstance(vm.ctx.exceptions.type_error) + { + vm.new_type_error("expected iterable of integers; got: 'str'") + } else { + error + } + })?; + items.push(value); + } + Ok(items) } /// `measured` is whether the object is asked how long it is; `element` is the error diff --git a/crates/vm/src/bytes_inner.rs b/crates/vm/src/bytes_inner.rs index f38b4dbd408..aa01847e40a 100644 --- a/crates/vm/src/bytes_inner.rs +++ b/crates/vm/src/bytes_inner.rs @@ -5,12 +5,16 @@ use crate::{ anystr::{self, AnyStr, AnyStrContainer, AnyStrWrapper}, builtins::{ PyBaseExceptionRef, PyByteArray, PyBytes, PyBytesRef, PyInt, PyIntRef, PyList, PyListRef, - PyStr, PyStrRef, PyTuple, PyTupleRef, pystr, pystr::PyUtf8StrRef, + PyStr, PyStrRef, PyTuple, PyTupleRef, pystr, }, cformat::cformat_bytes, + codecs::{DEFAULT_ENCODING, TextCodecArgs}, common::wtf8::is_py_ascii_whitespace, common::{borrow::BorrowedValue, hash}, - function::{ArgIterable, Either, OptionalArg, PyComparisonValue}, + function::{ + ArgBytesLike, ArgBytesOrStr, ArgIndex, ArgIterable, ArgNulFreeStr, Either, OptionalArg, + PyComparisonValue, + }, literal::escape::Escape, protocol::{BufferFlags, PyBuffer}, sequence::{SequenceExt, SequenceMutExt}, @@ -21,6 +25,7 @@ use crate::{ /// [`crate::byte::bytearray_from_object`]. pub(crate) type FromObject = fn(&VirtualMachine, &PyObject) -> PyResult>; +use alloc::borrow::Cow; use bstr::ByteSlice; use itertools::Itertools; use malachite_bigint::BigInt; @@ -168,19 +173,20 @@ pub struct ByteInnerNewOptions { #[pyarg(any, optional)] pub source: OptionalArg, #[pyarg(any, optional)] - pub encoding: OptionalArg, + pub encoding: OptionalArg, #[pyarg(any, optional)] - pub errors: OptionalArg, + pub errors: OptionalArg, } impl ByteInnerNewOptions { fn get_value_from_string( s: PyStrRef, - encoding: PyUtf8StrRef, - errors: OptionalArg, + encoding: ArgNulFreeStr, + errors: OptionalArg, vm: &VirtualMachine, ) -> PyResult { - let bytes = pystr::encode_string(s, Some(&encoding), errors.into_option(), vm)?; + let errors = errors.into_option().map(ArgNulFreeStr::into_utf8_ref); + let bytes = pystr::encode_string(s, Some(&encoding), errors, vm)?; Ok(bytes.as_bytes().to_vec().into()) } @@ -225,12 +231,24 @@ impl ByteInnerNewOptions { /// read: `bytes()` and `bytearray()` differ in whether they ask it how long /// it is. pub fn get_inner(self, from_object: FromObject, vm: &VirtualMachine) -> PyResult { - match (self.source, self.encoding, self.errors) { + self.get_inner_with_zero_count(from_object, vm) + .map(|(inner, _)| inner) + } + + pub(crate) fn get_inner_with_zero_count( + self, + from_object: FromObject, + vm: &VirtualMachine, + ) -> PyResult<(PyBytesInner, bool)> { + let mut zero_count = false; + let inner = match (self.source, self.encoding, self.errors) { (OptionalArg::Present(obj), OptionalArg::Missing, OptionalArg::Missing) => { // Try __index__ first to handle int-like objects that might raise custom exceptions if let Some(index_result) = obj.try_index_opt(vm) { match index_result { - Ok(index) => Self::get_value_from_size(&index, vm), + Ok(index) => Self::get_value_from_size(&index, vm).inspect(|inner| { + zero_count = inner.elements.is_empty(); + }), Err(e) => { // Only propagate non-TypeError exceptions // TypeError means the object doesn't support __index__, so fall back @@ -266,7 +284,8 @@ impl ByteInnerNewOptions { (OptionalArg::Present(_), OptionalArg::Missing, OptionalArg::Present(_)) => { Err(vm.new_type_error(STRING_WITHOUT_ENCODING.to_owned())) } - } + }?; + Ok((inner, zero_count)) } } @@ -302,7 +321,7 @@ impl ByteInnerSub { } } - fn into_vec(self, vm: &VirtualMachine) -> PyResult> { + pub(crate) fn into_vec(self, vm: &VirtualMachine) -> PyResult> { Ok(match self { Self::Buffer(buffer) => buffer.elements, Self::Byte(int) => vec![int.as_bigint().byte_or(vm)?], @@ -310,24 +329,72 @@ impl ByteInnerSub { } } +// Tail matching and translation read bytes subclasses directly, but retain +// other exporters until their operation has finished reading the buffer. +pub(crate) enum ByteInnerBuffer<'a> { + Bytes(&'a PyBytes), + Buffer(ArgBytesLike), +} + +impl<'a> TryFromBorrowedObject<'a> for ByteInnerBuffer<'a> { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + match obj.downcast_ref::() { + Some(bytes) => Ok(Self::Bytes(bytes)), + None => ArgBytesLike::try_from_borrowed_object(vm, obj).map(Self::Buffer), + } + } +} + +impl ByteInnerBuffer<'_> { + fn len(&self) -> usize { + match self { + Self::Bytes(bytes) => bytes.len(), + Self::Buffer(buffer) => buffer.len(), + } + } + + pub(crate) fn with_ref(&self, f: impl FnOnce(&[u8]) -> R) -> R { + match self { + Self::Bytes(bytes) => f(bytes.as_bytes()), + Self::Buffer(buffer) => buffer.with_ref(f), + } + } +} + #[derive(FromArgs)] +#[from_args(text_signature = "(sub[, start[, end]], /)")] pub struct ByteInnerFindOptions { #[pyarg(positional)] - sub: ByteInnerSub, + sub: PyObjectRef, #[pyarg(positional, default)] - start: Option, + start: Option, #[pyarg(positional, default)] - end: Option, + end: Option, } impl ByteInnerFindOptions { + pub(crate) fn parts(&self, len: usize) -> (&PyObject, core::ops::Range) { + let range = anystr::adjust_indices( + self.start.as_ref().map(AsRef::as_ref), + self.end.as_ref().map(AsRef::as_ref), + len, + ); + (&self.sub, range) + } + pub fn get_value( self, len: usize, vm: &VirtualMachine, ) -> PyResult<(Vec, core::ops::Range)> { - let sub = self.sub.into_vec(vm)?; - let range = anystr::adjust_indices(self.start.as_deref(), self.end.as_deref(), len); + let range = anystr::adjust_indices( + self.start.as_ref().map(AsRef::as_ref), + self.end.as_ref().map(AsRef::as_ref), + len, + ); + // The needle is converted after the slice indices, and only here, so + // that a caller can guard its buffer while the conversion runs Python. + let sub = ByteInnerSub::try_from_object(vm, self.sub)?.into_vec(vm)?; Ok((sub, range)) } } @@ -341,7 +408,7 @@ pub struct ByteInnerPaddingOptions { } impl ByteInnerPaddingOptions { - fn get_value(self, fn_name: &str, vm: &VirtualMachine) -> PyResult<(isize, u8)> { + pub(crate) fn get_value(self, fn_name: &str, vm: &VirtualMachine) -> PyResult<(isize, u8)> { let fillchar = { let v = self.fillchar; try_as_bytes(v.clone(), |bytes| bytes.iter().copied().exactly_one().ok()) @@ -362,46 +429,65 @@ impl ByteInnerPaddingOptions { #[derive(FromArgs)] pub struct ByteInnerTranslateOptions { #[pyarg(positional)] - table: Option, + pub(crate) table: Option, #[pyarg(any, default = b"")] - delete: PyObjectRef, + pub(crate) delete: PyObjectRef, } -impl ByteInnerTranslateOptions { - pub fn get_value(self, vm: &VirtualMachine) -> PyResult<(Vec, Vec)> { - let table = self.table.map_or_else( - || Ok((0..=u8::MAX).collect::>()), - |v| { - let bytes: PyBytesInner = v.try_into_value(vm)?; - if bytes.elements.len() != 256 { - return Err(vm.new_value_error("translation table must be 256 characters long")); - } - Ok(bytes.elements) - }, - )?; +// Keep this pure transformation separate from the different bytes/bytearray +// buffer lifetimes. Like CPython's trans_table, -1 marks a deleted input byte. +struct ByteTranslationTable([i16; 256]); - let delete = { - let byte: PyBytesInner = self.delete.try_into_value(vm)?; - byte.elements - }; +impl ByteTranslationTable { + fn new(table: Option<&[u8]>) -> Self { + let mut result = Self([0; 256]); + if let Some(table) = table { + for (entry, &byte) in result.0.iter_mut().zip(table) { + *entry = i16::from(byte); + } + } else { + for (i, entry) in result.0.iter_mut().enumerate() { + *entry = i as i16; + } + } + result + } - Ok((table, delete)) + fn delete(&mut self, delete: &[u8]) { + for &byte in delete { + self.0[usize::from(byte)] = -1; + } + } + + fn translate_into(&self, input: &[u8], output: &mut Vec) { + output.extend( + input + .iter() + .filter_map(|&byte| u8::try_from(self.0[usize::from(byte)]).ok()), + ); } } pub(crate) type ByteInnerSplitOptions = anystr::SplitArgs; -fn bytearray_repr_char_len(ch: u8) -> usize { +fn bytearray_repr_char_len(ch: u8, quote: u8) -> usize { + if ch == quote { + return 2; + } match ch { - b'\'' | b'\\' | b'\t' | b'\r' | b'\n' => 2, + b'\\' | b'\t' | b'\r' | b'\n' => 2, 0x20..=0x7e => 1, _ => 4, // \xHH } } -fn write_bytearray_repr_char(ch: u8, buf: &mut String) { +fn write_bytearray_repr_char(ch: u8, quote: u8, buf: &mut String) { + if ch == quote { + buf.push('\\'); + buf.push(ch as char); + return; + } match ch { - b'\'' => buf.push_str(r#"\'"#), b'\\' => buf.push_str(r#"\\"#), b'\t' => buf.push_str(r#"\t"#), b'\n' => buf.push_str(r#"\n"#), @@ -449,7 +535,7 @@ impl PyBytesInner { .elements .iter() .try_fold(0usize, |len, &ch| { - len.checked_add(bytearray_repr_char_len(ch)) + len.checked_add(bytearray_repr_char_len(ch, quote as u8)) }) .ok_or_else(|| Self::new_repr_overflow_error(vm))?; let len = class_name @@ -463,7 +549,7 @@ impl PyBytesInner { buf.push('b'); buf.push(quote); for &ch in &self.elements { - write_bytearray_repr_char(ch, &mut buf); + write_bytearray_repr_char(ch, quote as u8, &mut buf); } buf.push(quote); buf.push(')'); @@ -702,6 +788,16 @@ impl PyBytesInner { vm: &VirtualMachine, ) -> PyResult> { let (width, fillchar) = options.get_value("center", vm)?; + self.pad_with(width, fillchar, pad, vm) + } + + pub(crate) fn pad_with( + &self, + width: isize, + fillchar: u8, + pad: PadFn, + vm: &VirtualMachine, + ) -> PyResult> { let len = self.len(); if len as isize >= width { return Ok(Vec::from(&self.elements[..])); @@ -756,16 +852,12 @@ impl PyBytesInner { pub fn maketrans(from: Self, to: Self, vm: &VirtualMachine) -> PyResult> { if from.len() != to.len() { - return Err(vm.new_value_error("the two maketrans arguments must have equal length")); + return Err(vm.new_value_error("maketrans arguments must have same length")); } - let mut res = vec![]; - - for i in 0..=u8::MAX { - res.push(if let Some(position) = from.elements.find_byte(i) { - to.elements[position] - } else { - i - }); + let mut res: Vec = (0..=u8::MAX).collect(); + // Later occurrences replace earlier mappings, including repeated keys. + for (&from, &to) in from.elements.iter().zip(&to.elements) { + res[usize::from(from)] = to; } Ok(res) @@ -776,31 +868,74 @@ impl PyBytesInner { options: ByteInnerTranslateOptions, vm: &VirtualMachine, ) -> PyResult> { - let (table, delete) = options.get_value(vm)?; + let table = options + .table + .as_ref() + .map(|obj| ByteInnerBuffer::try_from_borrowed_object(vm, obj)) + .transpose()?; + if table.as_ref().is_some_and(|table| table.len() != 256) { + return Err(vm.new_value_error("translation table must be 256 characters long")); + } + // Acquire the deletion buffer while the table is still exported. + // Its callback may change the table, but cannot resize that storage. + let delete = ByteInnerBuffer::try_from_borrowed_object(vm, &options.delete)?; + let mut result = Vec::new(); + if result.try_reserve_exact(self.len()).is_err() { + drop(delete); + drop(table); + return Err(vm.no_memory_error()); + } + if let Some(table_view) = &table + && delete.len() == 0 + { + table_view.with_ref(|table| { + result.extend(self.elements.iter().map(|&byte| table[usize::from(byte)])); + }); + // The no-deletion fast path releases in the opposite order. + return Ok(result); + } + let mut translation = match &table { + Some(table) => table.with_ref(|table| ByteTranslationTable::new(Some(table))), + None => ByteTranslationTable::new(None), + }; + // Releasing the table can mutate the deletion bytes, so read those + // only afterwards. No borrowed payload lock spans either callback. + drop(table); + delete.with_ref(|delete| translation.delete(delete)); + drop(delete); + translation.translate_into(&self.elements, &mut result); + Ok(result) + } + pub(crate) fn translate_with(&self, table: &[u8], delete: &[u8]) -> Vec { let mut res = if delete.is_empty() { Vec::with_capacity(self.elements.len()) } else { Vec::new() }; - for i in &self.elements { - if !delete.contains(i) { - res.push(table[*i as usize]); + // Zero or one deletion byte does not need a separate lookup table. + if delete.len() <= 1 { + for &byte in &self.elements { + if !delete.contains(&byte) { + res.push(table[usize::from(byte)]); + } } + } else { + let mut translation = ByteTranslationTable::new(Some(table)); + translation.delete(delete); + translation.translate_into(&self.elements, &mut res); } - Ok(res) + res } - pub fn strip(&self, chars: Option) -> Vec { - self.elements - .py_strip( - chars, - |s, chars| s.trim_with(|c| chars.contains(&(c as u8))), - |s| s.trim(), - ) - .to_vec() + pub fn strip(&self, chars: Option) -> &[u8] { + self.elements.py_strip( + chars, + |s, chars| s.trim_with(|c| chars.contains(&(c as u8))), + |s| s.trim(), + ) } pub fn lstrip(&self, chars: Option) -> &[u8] { @@ -820,21 +955,19 @@ impl PyBytesInner { } // new in Python 3.9 - pub fn removeprefix(&self, prefix: Self) -> Vec { + pub fn removeprefix(&self, prefix: Self) -> &[u8] { self.elements .py_removeprefix(&prefix.elements, prefix.elements.len(), |s, p| { s.starts_with(p) }) - .to_vec() } // new in Python 3.9 - pub fn removesuffix(&self, suffix: Self) -> Vec { + pub fn removesuffix(&self, suffix: Self) -> &[u8] { self.elements .py_removesuffix(&suffix.elements, suffix.elements.len(), |s, p| { s.ends_with(p) }) - .to_vec() } pub fn split( @@ -898,24 +1031,31 @@ impl PyBytesInner { ) } - pub fn expandtabs(&self, options: anystr::ExpandTabsArgs) -> Vec { + pub fn expandtabs( + &self, + options: anystr::ExpandTabsArgs, + vm: &VirtualMachine, + ) -> PyResult> { let tabsize = options.tabsize(); let mut counter: usize = 0; - let mut res = vec![]; - - if tabsize == 0 { - return self - .elements - .iter() - .copied() - .filter(|x| *x != b'\t') - .collect(); - } + let capacity = anystr::checked_expandtabs_len( + self.len(), + self.elements.iter().copied().map(u32::from), + tabsize, + ) + .ok_or_else(|| vm.new_overflow_error("result too long"))?; + let mut res = Vec::new(); + res.try_reserve_exact(capacity) + .map_err(|_| vm.new_memory_error(""))?; for i in &self.elements { if *i == b'\t' { - let len = tabsize - counter % tabsize; - res.extend_from_slice(&vec![b' '; len]); + let len = if tabsize == 0 { + 0 + } else { + tabsize - counter % tabsize + }; + res.resize(res.len() + len, b' '); counter += len; } else { res.push(*i); @@ -927,7 +1067,7 @@ impl PyBytesInner { } } - res + Ok(res) } pub fn splitlines(&self, options: anystr::SplitLinesArgs, into_wrapper: FW) -> Vec @@ -944,10 +1084,17 @@ impl PyBytesInner { } // len(self)>=1, from="", len(to)>=1, max_count>=1 - fn replace_interleave(&self, to: Self, max_count: Option) -> Vec { + fn replace_interleave( + &self, + to: Self, + max_count: Option, + vm: &VirtualMachine, + ) -> PyResult> { let place_count = self.elements.len() + 1; - let count = max_count.map_or(place_count, |v| core::cmp::min(v, place_count)) - 1; - let capacity = self.elements.len() + count * to.len(); + let insertions = max_count.map_or(place_count, |v| core::cmp::min(v, place_count)); + let capacity = anystr::checked_replace_len(self.len(), 0, to.len(), insertions) + .ok_or_else(|| vm.new_overflow_error("replace bytes is too long"))?; + let count = insertions - 1; let mut result = Vec::with_capacity(capacity); let to_slice = to.elements.as_slice(); result.extend_from_slice(to_slice); @@ -956,10 +1103,10 @@ impl PyBytesInner { result.extend_from_slice(to_slice); } result.extend_from_slice(&self.elements[count..]); - result + Ok(result) } - fn replace_delete(&self, from: Self, max_count: Option) -> Vec { + fn replace_delete(&self, from: Self, max_count: Option) -> Cow<'_, [u8]> { let count = count_substring( self.elements.as_slice(), from.elements.as_slice(), @@ -967,7 +1114,7 @@ impl PyBytesInner { ); if count == 0 { // no matches - return self.elements.clone(); + return Cow::Borrowed(&self.elements); } let result_len = self.len() - (count * from.len()); @@ -985,10 +1132,15 @@ impl PyBytesInner { } } result.extend_from_slice(&self.elements[last_end..]); - result + Cow::Owned(result) } - pub fn replace_in_place(&self, from: Self, to: Self, max_count: Option) -> Vec { + pub fn replace_in_place( + &self, + from: Self, + to: Self, + max_count: Option, + ) -> Cow<'_, [u8]> { let len = from.len(); let mut iter = self.elements.find_iter(&from.elements); @@ -996,11 +1148,11 @@ impl PyBytesInner { let mut new = self.elements.clone(); new[offset..offset + len].clone_from_slice(to.elements.as_slice()); if max_count == Some(1) { - return new; + return Cow::Owned(new); } new } else { - return self.elements.clone(); + return Cow::Borrowed(&self.elements); }; let mut count = max_count.unwrap_or(usize::MAX) - 1; @@ -1011,7 +1163,7 @@ impl PyBytesInner { break; } } - new + Cow::Owned(new) } fn replace_general( @@ -1020,7 +1172,7 @@ impl PyBytesInner { to: Self, max_count: Option, vm: &VirtualMachine, - ) -> PyResult> { + ) -> PyResult> { let count = count_substring( self.elements.as_slice(), from.elements.as_slice(), @@ -1028,20 +1180,14 @@ impl PyBytesInner { ); if count == 0 { // no matches, return unchanged - return Ok(self.elements.clone()); + return Ok(Cow::Borrowed(&self.elements)); } // Check for overflow // result_len = self_len + count * (to_len-from_len) debug_assert!(count > 0); - if to.len() as isize - from.len() as isize - > (isize::MAX - self.elements.len() as isize) / count as isize - { - return Err(vm.new_overflow_error("replace bytes is too long")); - } - let result_len = (self.elements.len() as isize - + count as isize * (to.len() as isize - from.len() as isize)) - as usize; + let result_len = anystr::checked_replace_len(self.len(), from.len(), to.len(), count) + .ok_or_else(|| vm.new_overflow_error("replace bytes is too long"))?; let mut result = Vec::with_capacity(result_len); let mut last_end = 0; @@ -1056,10 +1202,14 @@ impl PyBytesInner { } } result.extend_from_slice(&self.elements[last_end..]); - Ok(result) + Ok(Cow::Owned(result)) } - pub fn replace(&self, args: ByteInnerReplaceOptions, vm: &VirtualMachine) -> PyResult> { + pub fn replace( + &self, + args: ByteInnerReplaceOptions, + vm: &VirtualMachine, + ) -> PyResult> { let ByteInnerReplaceOptions { old: from, new: to, @@ -1069,9 +1219,9 @@ impl PyBytesInner { let max_count = if max_count >= 0 { if max_count == 0 || (self.elements.is_empty() && !from.is_empty()) { // nothing to do; return the original bytes - return Ok(self.elements.clone()); + return Ok(Cow::Borrowed(&self.elements)); } else if self.elements.is_empty() && from.is_empty() { - return Ok(to.elements); + return Ok(Cow::Owned(to.elements)); } Some(max_count as usize) } else { @@ -1082,19 +1232,19 @@ impl PyBytesInner { if from.elements.is_empty() { if to.elements.is_empty() { // nothing to do; return the original bytes - return Ok(self.elements.clone()); + return Ok(Cow::Borrowed(&self.elements)); } // insert the 'to' bytes everywhere. // >>> b"Python".replace(b"", b".") // b'.P.y.t.h.o.n.' - return Ok(self.replace_interleave(to, max_count)); + return self.replace_interleave(to, max_count, vm).map(Cow::Owned); } // Except for b"".replace(b"", b"A") == b"A" there is no way beyond this // point for an empty self bytes to generate a non-empty bytes // Special case so the remaining code always gets a non-empty bytes if self.elements.is_empty() { - return Ok(self.elements.clone()); + return Ok(Cow::Borrowed(&self.elements)); } if to.elements.is_empty() { @@ -1307,30 +1457,17 @@ pub struct ByteInnerReplaceOptions { old: PyBytesInner, #[pyarg(positional)] new: PyBytesInner, - #[pyarg(positional, default = -1)] + #[pyarg(any, default = -1)] count: isize, } -#[derive(FromArgs)] -pub(crate) struct DecodeArgs { - // None is filled in as utf-8 when decoding. - #[pyarg(any, optional, py_default = "'utf-8'")] - encoding: Option, - // None is filled in as strict when decoding. - #[pyarg(any, optional, py_default = "'strict'")] - errors: Option, -} - pub(crate) fn bytes_decode( zelf: PyObjectRef, - args: DecodeArgs, + args: TextCodecArgs, vm: &VirtualMachine, ) -> PyResult { - let DecodeArgs { encoding, errors } = args; - let encoding = match encoding.as_ref() { - None => crate::codecs::DEFAULT_ENCODING, - Some(e) => e.as_str(), - }; + let (encoding, errors) = args.into_parts(); + let encoding = encoding.as_deref().map_or(DEFAULT_ENCODING, |s| s.as_str()); vm.state .codec_registry .decode_text_object(zelf, encoding, errors, vm) @@ -1339,7 +1476,7 @@ pub(crate) fn bytes_decode( #[derive(FromArgs)] pub(crate) struct ByteInnerHexOptions { #[pyarg(any, optional)] - pub sep: OptionalArg>, + pub sep: OptionalArg, #[pyarg(any, default = 1)] pub bytes_per_sep: isize, } @@ -1355,24 +1492,12 @@ impl ByteInnerHexOptions { return Ok((None, bytes_per_sep)); }; - let s_guard; - let b_guard; - let (obj, bytes) = match &sep { - Either::A(s) => { - s_guard = s.as_wtf8(); - (s.as_object(), s_guard.as_bytes()) - } - Either::B(b) => { - b_guard = b.as_bytes(); - (b.as_object(), b_guard) - } - }; - if obj.length(vm)? != 1 { + if sep.as_object().length(vm)? != 1 { return Err(vm.new_value_error("sep must be length 1.")); } // An object that claims a length it does not have separates with NUL, // which is what reading past the end of its data gives. - let sep = bytes.first().copied().unwrap_or(0); + let sep = sep.with_ref(|bytes| bytes.first().copied().unwrap_or(0)); if sep > 127 { return Err(vm.new_value_error("sep must be ASCII.")); } @@ -1390,7 +1515,7 @@ fn hex_impl(bytes: &[u8], sep: u8, bytes_per_sep: isize) -> String { let len = bytes.len(); let buf = if bytes_per_sep < 0 { - let bytes_per_sep = core::cmp::min(len, (-bytes_per_sep) as usize); + let bytes_per_sep = core::cmp::min(len, bytes_per_sep.unsigned_abs()); let chunks = (len - 1) / bytes_per_sep; let chunked = chunks * bytes_per_sep; let unchunked = len - chunked; diff --git a/crates/vm/src/cformat.rs b/crates/vm/src/cformat.rs index c9533835f6c..1518010d201 100644 --- a/crates/vm/src/cformat.rs +++ b/crates/vm/src/cformat.rs @@ -7,37 +7,93 @@ use itertools::Itertools; use num_traits::cast::ToPrimitive; use crate::{ - AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, - VirtualMachine, + AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{ PyBaseExceptionRef, PyByteArray, PyBytes, PyFloat, PyInt, PyStr, int::check_int_to_str_digits, try_f64_to_bigint, tuple, }, common::{ cformat::{ - CCharacterType, CConversionFlags, CFormatBytes, CFormatConversion, CFormatPart, - CFormatPrecision, CFormatQuantity, CFormatSpec, CFormatSpecKeyed, CFormatType, - CFormatWtf8, CNumberType, + CCharacterType, CConversionFlags, CFormatContext, CFormatConversion, CFormatErrorType, + CFormatPrecision, CFormatQuantity, CFormatSpec, CFormatType, CNumberType, FormatBuf, + FormatChar, consume_length, parse_flags, parse_format_type, parse_precision, + parse_quantity, parse_spec_mapping_key, }, - wtf8::{CodePoint, Wtf8, Wtf8Buf}, + wtf8::{CodePoint, Wtf8, Wtf8Buf, wtf8_concat}, }, function::ArgIntoFloat, protocol::{BufferFlags, PyBuffer}, stdlib::builtins, }; +#[derive(Clone, Copy)] +enum FormatArg<'a> { + Single, + Tuple(usize), + Mapping(&'a PyObject), +} + +impl FormatArg<'_> { + fn message(self, vm: &VirtualMachine, message: Wtf8Buf) -> PyResult { + let context = match self { + Self::Single => Wtf8Buf::from("format argument"), + Self::Tuple(index) => wtf8_concat!("format argument ", index), + Self::Mapping(key) => wtf8_concat!("format argument ", key.repr(vm)?.as_wtf8()), + }; + Ok(wtf8_concat!(context, ": ", message)) + } + + fn type_error(self, vm: &VirtualMachine, message: impl Into) -> PyBaseExceptionRef { + match self.message(vm, message.into()) { + Ok(message) => vm.new_type_error(message), + Err(error) => error, + } + } + + fn overflow_error(self, vm: &VirtualMachine, message: String) -> PyBaseExceptionRef { + match self.message(vm, message.into()) { + Ok(message) => vm.new_overflow_error(message), + Err(error) => error, + } + } +} + +fn format_number_error( + vm: &VirtualMachine, + spec: &CFormatSpec, + obj: &PyObject, + arg: FormatArg<'_>, +) -> PyBaseExceptionRef { + let type_name = match obj.class().fully_qualified_name(vm) { + Ok(name) => name, + Err(error) => return error, + }; + let required = match spec.format_type { + CFormatType::Number(CNumberType::Octal | CNumberType::HexLower | CNumberType::HexUpper) => { + "an integer" + } + _ => "a real number", + }; + arg.type_error( + vm, + wtf8_concat!( + "%", + spec.format_type.to_char(), + " requires ", + required, + ", not ", + type_name + ), + ) +} + fn format_decimal_object( vm: &VirtualMachine, spec: &CFormatSpec, obj: &PyObject, + arg: FormatArg<'_>, ) -> PyResult { - let type_error = || { - vm.new_type_error(format!( - "%{} format: a real number is required, not {}", - spec.format_type.to_char(), - obj.class().slot_name() - )) - }; + let type_error = || format_number_error(vm, spec, obj, arg); // Decimal conversions prefer __int__; __index__ is only a fallback when absent. let i = obj .number() @@ -55,17 +111,84 @@ fn format_decimal_object( Ok(spec.format_number(i.as_bigint())) } +fn format_index_object( + vm: &VirtualMachine, + spec: &CFormatSpec, + obj: &PyObject, + arg: FormatArg<'_>, +) -> PyResult { + let type_error = || format_number_error(vm, spec, obj, arg); + let value = obj + .try_index_opt(vm) + .ok_or_else(type_error)? + .map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + type_error() + } else { + error + } + })?; + Ok(spec.format_number(value.as_bigint())) +} + +fn format_float_object( + vm: &VirtualMachine, + spec: &CFormatSpec, + obj: &PyObject, + arg: FormatArg<'_>, +) -> PyResult { + let value = ArgIntoFloat::try_from_object(vm, obj.to_owned()).map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + format_number_error(vm, spec, obj, arg) + } else { + error + } + })?; + Ok(spec.format_float(value.into())) +} + +fn format_character_error( + vm: &VirtualMachine, + obj: &PyObject, + arg: FormatArg<'_>, + context: CFormatContext, +) -> PyBaseExceptionRef { + let what = match context { + CFormatContext::Str => obj + .downcast_ref::() + .map(|s| format!("a string of length {}", s.char_len())), + CFormatContext::Bytes => obj + .downcast_ref::() + .map(|b| format!("a bytes object of length {}", b.as_bytes().len())) + .or_else(|| { + obj.downcast_ref::() + .map(|b| format!("a bytearray object of length {}", b.borrow_buf().len())) + }), + }; + let what = match what.map_or_else( + || obj.class().fully_qualified_name(vm), + |what| Ok(what.into()), + ) { + Ok(what) => what, + Err(error) => return error, + }; + let required = match context { + CFormatContext::Str => "an integer or a unicode character", + CFormatContext::Bytes => "an integer in range(256) or a single byte", + }; + arg.type_error(vm, wtf8_concat!("%c requires ", required, ", not ", what)) +} + fn spec_format_bytes( vm: &VirtualMachine, spec: &CFormatSpec, obj: PyObjectRef, + arg: FormatArg<'_>, ) -> PyResult> { match &spec.format_type { - CFormatType::Unsupported { ch, index } => Err(vm.new_value_error(format!( - "unsupported format character '{}' ({:#x}) at index {index}", - ch.to_char_lossy(), - ch.to_u32(), - ))), + CFormatType::Unsupported { .. } => { + unreachable!("unsupported format was rejected before conversion") + } // Unlike strings, %r and %a are identical for bytes: the behaviour corresponds to // %a for strings (not %r) CFormatType::String(CFormatConversion::Repr | CFormatConversion::Ascii) => { @@ -82,19 +205,30 @@ fn spec_format_bytes( } if let Some(method) = vm.get_special_method(&obj, identifier!(vm, __bytes__))? { let bytes = method.invoke((), vm)?; - let bytes = PyBytes::try_from_borrowed_object(vm, &bytes)?; + let bytes = bytes.downcast_ref::().ok_or_else(|| { + match ( + obj.class().fully_qualified_name(vm), + bytes.class().fully_qualified_name(vm), + ) { + (Ok(source), Ok(result)) => vm.new_type_error(wtf8_concat!( + source, + ".__bytes__() must return a bytes, not ", + result + )), + (Err(error), _) | (_, Err(error)) => error, + } + })?; return Ok(spec.format_bytes(bytes.as_bytes())); } if obj.check_buffer() { let buffer = PyBuffer::from_object(vm, &obj, BufferFlags::FULL_RO)?; return Ok(buffer.contiguous_or_collect(|bytes| spec.format_bytes(bytes))); } - let msg = format!( - "%b requires a bytes-like object, or an object that \ - implements __bytes__, not '{}'", - obj.class().name() + let msg = wtf8_concat!( + "%b requires a bytes-like object, or an object that implements __bytes__, not ", + obj.class().fully_qualified_name(vm)? ); - Err(vm.new_type_error(msg)) + Err(arg.type_error(vm, msg)) } CFormatType::Number(number_type) => match number_type { CNumberType::DecimalD | CNumberType::DecimalI | CNumberType::DecimalU => { @@ -106,7 +240,7 @@ fn spec_format_bytes( check_int_to_str_digits(&bigint, vm)?; Ok(spec.format_number(&bigint).into_bytes()) } else { - format_decimal_object(vm, spec, &obj).map(String::into_bytes) + format_decimal_object(vm, spec, &obj, arg).map(String::into_bytes) } } _ => { @@ -114,31 +248,12 @@ fn spec_format_bytes( // `__index__`, not just PyInt. Mirrors PyNumber_Index dispatch. if let Some(i) = obj.downcast_ref::() { Ok(spec.format_number(i.as_bigint()).into_bytes()) - } else if let Some(int_result) = obj.try_index_opt(vm) { - let i = int_result?; - Ok(spec.format_number(i.as_bigint()).into_bytes()) } else { - Err(vm.new_type_error(format!( - "%{} format: an integer is required, not {}", - spec.format_type.to_char(), - obj.class().name() - ))) + format_index_object(vm, spec, &obj, arg).map(String::into_bytes) } } }, - CFormatType::Float(_) => { - let class = obj.class().to_owned(); - let value = ArgIntoFloat::try_from_object(vm, obj).map_err(|e| { - if e.fast_isinstance(vm.ctx.exceptions.type_error) { - // formatfloat in bytesobject.c generates its own specific exception - // text in this case, mirror it here. - vm.new_type_error(format!("float argument required, not {}", class.name())) - } else { - e - } - })?; - Ok(spec.format_float(value.into()).into_bytes()) - } + CFormatType::Float(_) => format_float_object(vm, spec, &obj, arg).map(String::into_bytes), CFormatType::Character(CCharacterType::Character) => { // CPython parity: bytes `%c` accepts a single byte or any object // with `__index__` in range(256). @@ -146,33 +261,25 @@ fn spec_format_bytes( if b.as_bytes().len() == 1 { return Ok(spec.format_char(b.as_bytes()[0])); } + return Err(format_character_error(vm, &obj, arg, CFormatContext::Bytes)); } else if let Some(ba) = obj.downcast_ref::() { let buf = ba.borrow_buf(); if buf.len() == 1 { return Ok(spec.format_char(buf[0])); } + drop(buf); + return Err(format_character_error(vm, &obj, arg, CFormatContext::Bytes)); } let int = if let Some(i) = obj.downcast_ref::() { i.to_owned() } else if let Some(int_result) = obj.try_index_opt(vm) { int_result? } else { - // A bytes-like argument that is not one byte long is named by - // its length rather than by its type. - let what = if let Some(b) = obj.downcast_ref::() { - format!("a bytes object of length {}", b.as_bytes().len()) - } else if let Some(ba) = obj.downcast_ref::() { - format!("a bytearray object of length {}", ba.borrow_buf().len()) - } else { - obj.class().name().to_string() - }; - return Err(vm.new_type_error(format!( - "%c requires an integer in range(256) or a single byte, not {what}" - ))); + return Err(format_character_error(vm, &obj, arg, CFormatContext::Bytes)); }; let ch = int .try_to_primitive::(vm) - .map_err(|_| vm.new_overflow_error("%c arg not in range(256)"))?; + .map_err(|_| arg.overflow_error(vm, "%c argument not in range(256)".to_owned()))?; Ok(spec.format_char(ch)) } } @@ -182,13 +289,12 @@ fn spec_format_string( vm: &VirtualMachine, spec: &CFormatSpec, obj: PyObjectRef, + arg: FormatArg<'_>, ) -> PyResult { match &spec.format_type { - CFormatType::Unsupported { ch, index } => Err(vm.new_value_error(format!( - "unsupported format character '{}' ({:#x}) at index {index}", - ch.to_char_lossy(), - ch.to_u32(), - ))), + CFormatType::Unsupported { .. } => { + unreachable!("unsupported format was rejected before conversion") + } CFormatType::String(conversion) => { let result = match conversion { CFormatConversion::Ascii => builtins::ascii(obj, vm)?.as_wtf8().to_owned(), @@ -211,7 +317,7 @@ fn spec_format_string( check_int_to_str_digits(&bigint, vm)?; Ok(spec.format_number(&bigint).into()) } else { - format_decimal_object(vm, spec, &obj).map(Into::into) + format_decimal_object(vm, spec, &obj, arg).map(Into::into) } } _ => { @@ -219,304 +325,417 @@ fn spec_format_string( // `__index__`, not just PyInt. Mirrors PyNumber_Index dispatch. if let Some(i) = obj.downcast_ref::() { Ok(spec.format_number(i.as_bigint()).into()) - } else if let Some(int_result) = obj.try_index_opt(vm) { - let i = int_result?; - Ok(spec.format_number(i.as_bigint()).into()) } else { - Err(vm.new_type_error(format!( - "%{} format: an integer is required, not {}", - spec.format_type.to_char(), - obj.class().name() - ))) + format_index_object(vm, spec, &obj, arg).map(Into::into) } } }, - CFormatType::Float(_) => { - let value = ArgIntoFloat::try_from_object(vm, obj)?; - Ok(spec.format_float(value.into()).into()) - } + CFormatType::Float(_) => format_float_object(vm, spec, &obj, arg).map(Into::into), CFormatType::Character(CCharacterType::Character) => { // CPython parity: `%c` accepts a single-char str or any object with // `__index__` (the latter via PyNumber_Index dispatch). - if let Some(s) = obj.downcast_ref::() - && let Ok(ch) = s.as_wtf8().code_points().exactly_one() - { - return Ok(spec.format_char(ch)); + if let Some(s) = obj.downcast_ref::() { + if let Ok(ch) = s.as_wtf8().code_points().exactly_one() { + return Ok(spec.format_char(ch)); + } + return Err(format_character_error(vm, &obj, arg, CFormatContext::Str)); } let int = if let Some(i) = obj.downcast_ref::() { i.to_owned() } else if let Some(int_result) = obj.try_index_opt(vm) { - int_result? + int_result.map_err(|error| { + if error.fast_isinstance(vm.ctx.exceptions.type_error) { + format_character_error(vm, &obj, arg, CFormatContext::Str) + } else { + error + } + })? } else { - // A string argument that is not one character long is named by - // its length rather than by its type. - let what = match obj.downcast_ref::() { - Some(s) => format!("a string of length {}", s.char_len()), - None => obj.class().name().to_string(), - }; - return Err(vm.new_type_error(format!( - "%c requires an int or a unicode character, not {what}" - ))); + return Err(format_character_error(vm, &obj, arg, CFormatContext::Str)); }; let ch = int .as_bigint() .to_u32() .and_then(CodePoint::from_u32) - .ok_or_else(|| vm.new_overflow_error("%c arg not in range(0x110000)"))?; + .ok_or_else(|| { + arg.overflow_error(vm, "%c argument not in range(0x110000)".to_owned()) + })?; Ok(spec.format_char(ch)) } } } -fn get_star_arg(vm: &VirtualMachine, element: Option<&PyObject>) -> PyResult { - match element { - Some(obj) => { - if let Some(i) = obj.downcast_ref::() { - i.try_to_primitive::(vm) - } else { - Err(vm.new_type_error("* wants int")) - } - } - None => Err(vm.new_type_error("not enough arguments for format string")), - } +struct FormatValues<'a> { + object: &'a PyObject, + tuple: Option<&'a [PyObjectRef]>, + consumed: usize, } -fn try_update_quantity_from_tuple<'a, I: Iterator>( - vm: &VirtualMachine, - elements: &mut I, - q: &mut Option, - f: &mut CConversionFlags, -) -> PyResult<()> { - let Some(CFormatQuantity::FromValuesTuple) = q else { - return Ok(()); - }; +impl<'a> FormatValues<'a> { + fn new(object: &'a PyObject) -> Self { + Self { + object, + tuple: object + .downcast_ref::() + .map(|tuple| tuple.as_slice()), + consumed: 0, + } + } - let width = get_star_arg(vm, elements.next())?; - if width < 0 { - f.insert(CConversionFlags::LEFT_ADJUST); + fn count(&self) -> usize { + self.tuple.map_or(1, <[PyObjectRef]>::len) } - *q = Some(CFormatQuantity::Amount(width.unsigned_abs() as usize)); - Ok(()) -} -fn try_update_precision_from_tuple<'a, I: Iterator>( - vm: &VirtualMachine, - elements: &mut I, - p: &mut Option, -) -> PyResult<()> { - let Some(CFormatPrecision::Quantity(CFormatQuantity::FromValuesTuple)) = p else { - return Ok(()); - }; + fn next( + &mut self, + allow_single: bool, + vm: &VirtualMachine, + ) -> PyResult<(PyObjectRef, FormatArg<'static>)> { + let value = if let Some(tuple) = self.tuple { + tuple.get(self.consumed).cloned() + } else if allow_single && self.consumed == 0 { + Some(self.object.to_owned()) + } else { + None + }; + let value = value.ok_or_else(|| { + vm.new_type_error(format!( + "not enough arguments for format string (got {})", + self.count() + )) + })?; + self.consumed += 1; + let arg = if self.tuple.is_some() { + FormatArg::Tuple(self.consumed) + } else { + FormatArg::Single + }; + Ok((value, arg)) + } - let precision = get_star_arg(vm, elements.next())?.max(0) as usize; - *p = Some(CFormatPrecision::Quantity(CFormatQuantity::Amount( - precision, - ))); - Ok(()) + fn star(&mut self, precision: bool, vm: &VirtualMachine) -> PyResult { + let (value, arg) = self.next(false, vm)?; + let Some(value_int) = value.downcast_ref::() else { + return Err(arg.type_error( + vm, + wtf8_concat!( + "* requires int, not ", + value.class().fully_qualified_name(vm)? + ), + )); + }; + let converted = if precision { + value_int.as_bigint().to_i32().map(|value| value as isize) + } else { + value_int + .as_bigint() + .to_isize() + .filter(|&width| width != isize::MIN) + }; + converted.ok_or_else(|| { + arg.overflow_error( + vm, + format!( + "too big for {}", + if precision { "precision" } else { "width" } + ), + ) + }) + } } -fn specifier_error(vm: &VirtualMachine) -> PyBaseExceptionRef { - vm.new_type_error("format requires a mapping") +fn parse_error(vm: &VirtualMachine, error: CFormatErrorType, start: usize) -> PyBaseExceptionRef { + let message = match error { + CFormatErrorType::UnmatchedKeyParentheses => { + format!("stray % or incomplete format key at position {start}") + } + CFormatErrorType::WidthTooBig => format!("width too big at position {start}"), + CFormatErrorType::PrecisionTooBig => format!("precision too big at position {start}"), + _ => format!("stray % at position {start}"), + }; + vm.new_value_error(message) } -pub(crate) fn cformat_bytes( +fn unsupported_format_error( vm: &VirtualMachine, - format_string: &[u8], - values_obj: &PyObject, -) -> PyResult> { - let mut format = CFormatBytes::parse_from_bytes(format_string) - .map_err(|err| vm.new_value_error(err.to_string()))?; - let (num_specifiers, mapping_required) = format - .check_specifiers() - .ok_or_else(|| specifier_error(vm))?; - - let mut result = vec![]; - - let is_mapping = values_obj.class().has_attr(identifier!(vm, __getitem__)) - && !values_obj.fast_isinstance(vm.ctx.types.tuple_type) - && !values_obj.fast_isinstance(vm.ctx.types.bytes_type) - && !values_obj.fast_isinstance(vm.ctx.types.bytearray_type); - - if num_specifiers == 0 { - if !is_mapping - && values_obj - .downcast_ref::() - .is_none_or(|e| !e.as_slice().is_empty()) - { - return Err(vm.new_type_error("not all arguments converted during bytes formatting")); - } - - // literal only - for (_, part) in format.iter_mut() { - if let CFormatPart::Literal(literal) = part { - result.append(literal) - } else { - unreachable!() - } - } - - return Ok(result); + ch: CodePoint, + start: usize, + index: usize, + context: CFormatContext, +) -> PyBaseExceptionRef { + let value = ch.to_u32(); + let c = ch.to_char_lossy(); + if c.is_ascii_alphabetic() { + return vm.new_value_error(format!("unsupported format %{c} at position {start}")); } + let character = if c == '\'' { + "\"'\"".to_owned() + } else if (32..127).contains(&value) { + format!("'{c}'") + } else if context == CFormatContext::Bytes { + format!("with code 0x{value:02x}") + } else if ch + .to_char() + .is_some_and(rustpython_unicode::classify::is_printable) + { + format!("'{c}' (U+{value:04X})") + } else { + format!("U+{value:04X}") + }; + vm.new_value_error(format!( + "stray % at position {start} or unexpected format character {character} at position {index}" + )) +} - if mapping_required { - if !is_mapping { - return Err(vm.new_type_error("format requires a mapping")); - } +trait FormatOutput: FormatBuf { + fn reserve_output(&mut self, additional: usize, vm: &VirtualMachine) -> PyResult<()>; + fn push_output(&mut self, character: Self::Char, vm: &VirtualMachine) -> PyResult<()>; +} - // dict - for (_, part) in format { - match part { - CFormatPart::Literal(literal) => result.extend(literal), - CFormatPart::Spec(CFormatSpecKeyed { mapping_key, spec }) => { - let key = mapping_key.unwrap(); - let value = values_obj.get_item(&key, vm)?; - let part_result = spec_format_bytes(vm, &spec, value)?; - result.extend(part_result); - } - } - } +impl FormatOutput for Vec { + fn reserve_output(&mut self, additional: usize, vm: &VirtualMachine) -> PyResult<()> { + self.try_reserve_exact(additional) + .map_err(|_| vm.new_memory_error("")) + } - return Ok(result); + fn push_output(&mut self, character: u8, vm: &VirtualMachine) -> PyResult<()> { + self.try_reserve(1).map_err(|_| vm.new_memory_error(""))?; + self.push(character); + Ok(()) } +} - // tuple - let mut slice_iter; - let mut once_iter; - let mut value_iter: &mut dyn Iterator = - if let Some(tup) = values_obj.downcast_ref::() { - slice_iter = tup.as_slice().iter().map(|v| &**v); - &mut slice_iter - } else { - once_iter = core::iter::once(values_obj); - &mut once_iter - }; +impl FormatOutput for Wtf8Buf { + fn reserve_output(&mut self, additional: usize, vm: &VirtualMachine) -> PyResult<()> { + self.try_reserve_exact(additional) + .map_err(|_| vm.new_memory_error("")) + } - for (_, part) in format { - match part { - CFormatPart::Literal(literal) => result.extend(literal), - CFormatPart::Spec(CFormatSpecKeyed { mut spec, .. }) => { - try_update_quantity_from_tuple( - vm, - &mut value_iter, - &mut spec.min_field_width, - &mut spec.flags, - )?; - try_update_precision_from_tuple(vm, &mut value_iter, &mut spec.precision)?; - - let Some(value) = value_iter.next() else { - return Err(vm.new_type_error("not enough arguments for format string")); - }; - - let part_result = spec_format_bytes(vm, &spec, value.to_owned())?; - result.extend(part_result); - } - } + fn push_output(&mut self, character: CodePoint, vm: &VirtualMachine) -> PyResult<()> { + self.try_reserve(character.len_wtf8()) + .map_err(|_| vm.new_memory_error(""))?; + self.push(character); + Ok(()) } +} - // check that all arguments were converted - if !is_mapping && value_iter.next().is_some() { - Err(vm.new_type_error("not all arguments converted during bytes formatting")) - } else { - Ok(result) +fn pad_output( + vm: &VirtualMachine, + spec: &CFormatSpec, + mut value: S, +) -> PyResult { + let Some(CFormatQuantity::Amount(width)) = spec.min_field_width else { + return Ok(value); + }; + let fill = width.saturating_sub(value.chars().count()); + if fill == 0 { + return Ok(value); + } + if spec.flags.contains(CConversionFlags::LEFT_ADJUST) { + value.reserve_output(fill, vm)?; + value.extend(core::iter::repeat_n(S::Char::from(b' '), fill)); + return Ok(value); } + let zero_pad = spec.flags.contains(CConversionFlags::ZERO_PAD) + && matches!( + spec.format_type, + CFormatType::Number(_) | CFormatType::Float(_) + ); + let prefix = if zero_pad { + let sign = usize::from( + value + .chars() + .next() + .is_some_and(|c| c.eq_char('-') || c.eq_char('+') || c.eq_char(' ')), + ); + let alternate = spec.flags.contains(CConversionFlags::ALTERNATE_FORM) + && matches!( + spec.format_type, + CFormatType::Number( + CNumberType::Octal | CNumberType::HexLower | CNumberType::HexUpper + ) + ); + sign + if alternate { 2 } else { 0 } + } else { + 0 + }; + let size = value + .len() + .checked_add(fill) + .ok_or_else(|| vm.new_memory_error(""))?; + let mut output = S::default(); + output.reserve_output(size, vm)?; + output.extend(value.chars().take(prefix)); + output.extend(core::iter::repeat_n( + S::Char::from(if zero_pad { b'0' } else { b' ' }), + fill, + )); + output.extend(value.chars().skip(prefix)); + Ok(output) } -pub(crate) fn cformat_string( +fn cformat( vm: &VirtualMachine, - format_string: &Wtf8, + characters: impl Iterator, values_obj: &PyObject, -) -> PyResult { - let format = CFormatWtf8::parse_from_wtf8(format_string) - .map_err(|err| vm.new_value_error(err.to_string()))?; - let (num_specifiers, mapping_required) = format - .check_specifiers() - .ok_or_else(|| specifier_error(vm))?; - - let mut result = Wtf8Buf::new(); - - let is_mapping = values_obj.class().has_attr(identifier!(vm, __getitem__)) - && !values_obj.fast_isinstance(vm.ctx.types.tuple_type) - && !values_obj.fast_isinstance(vm.ctx.types.str_type); - - if num_specifiers == 0 { - if !is_mapping - && values_obj - .downcast_ref::() - .is_none_or(|e| !e.as_slice().is_empty()) + context: CFormatContext, + make_key: impl Fn(S) -> PyObjectRef, + format_value: impl Fn(&VirtualMachine, &CFormatSpec, PyObjectRef, FormatArg<'_>) -> PyResult, +) -> PyResult { + let mut characters = characters.enumerate().peekable(); + let mut values = FormatValues::new(values_obj); + let is_mapping = values_obj.class().slots().as_mapping.has_subscript() + && values.tuple.is_none() + && !values_obj.fast_isinstance(vm.ctx.types.str_type) + && (context == CFormatContext::Str + || (!values_obj.fast_isinstance(vm.ctx.types.bytes_type) + && !values_obj.fast_isinstance(vm.ctx.types.bytearray_type))); + let mut mapping_used = false; + let mut mapped_value = None; + let mut result = S::default(); + + while let Some((start, character)) = characters.next() { + if !character.eq_char('%') { + result.push_output(character, vm)?; + continue; + } + if characters + .next_if(|(_, character)| character.eq_char('%')) + .is_some() { - return Err(vm.new_type_error("not all arguments converted during string formatting")); + result.push_output(S::Char::from(b'%'), vm)?; + continue; } - // literal only - for (_, part) in format.iter() { - if let CFormatPart::Literal(literal) = part { - result.push_wtf8(literal) - } else { - unreachable!() - } + // Fetch mappings and star arguments as their fields are parsed, so + // callbacks and earlier errors precede later malformed fields. + let keyed = characters + .peek() + .is_some_and(|(_, character)| character.eq_char('(')); + if keyed && !is_mapping { + return Err(vm.new_type_error(wtf8_concat!( + "format requires a mapping, not ", + values_obj.class().fully_qualified_name(vm)? + ))); } - - return Ok(result); - } - - if mapping_required { - if !is_mapping { - return Err(vm.new_type_error("format requires a mapping")); + if !keyed && mapping_used { + return Err(vm.new_value_error(format!( + "format requires a parenthesised mapping key at position {start}" + ))); + } + let mapping_key = parse_spec_mapping_key::(&mut characters) + .map_err(|(error, _)| parse_error(vm, error, start))? + .map(&make_key); + if let Some(key) = &mapping_key { + mapping_used = true; + // Release the previous mapped argument before invoking the next lookup. + drop(mapped_value.take()); + mapped_value = Some(values_obj.get_item(key.as_object(), vm)?); } - // dict - for (_, part) in format { - match part { - CFormatPart::Literal(literal) => result.push_wtf8(&literal), - CFormatPart::Spec(CFormatSpecKeyed { mapping_key, spec }) => { - let value = values_obj.get_item(&mapping_key.unwrap(), vm)?; - let part_result = spec_format_string(vm, &spec, value)?; - result.push_wtf8(&part_result); - } + let mut flags = parse_flags(&mut characters); + let mut min_field_width = parse_quantity( + &mut characters, + isize::MAX as usize, + CFormatErrorType::WidthTooBig, + ) + .map_err(|(error, _)| parse_error(vm, error, start))?; + let star_mapping_error = || { + vm.new_value_error(format!( + "* cannot be used with a parenthesised mapping key at position {start}" + )) + }; + if min_field_width == Some(CFormatQuantity::FromValuesTuple) { + if mapping_used { + return Err(star_mapping_error()); } + let width = values.star(false, vm)?; + if width < 0 { + flags.insert(CConversionFlags::LEFT_ADJUST); + } + // star() rejects isize::MIN before negating a negative width. + min_field_width = Some(CFormatQuantity::Amount(width.unsigned_abs())); } - - return Ok(result); - } - - // tuple - let mut slice_iter; - let mut once_iter; - let mut value_iter: &mut dyn Iterator = - if let Some(tup) = values_obj.downcast_ref::() { - slice_iter = tup.as_slice().iter().map(|v| &**v); - &mut slice_iter + let mut precision = + parse_precision(&mut characters).map_err(|(error, _)| parse_error(vm, error, start))?; + if precision == Some(CFormatPrecision::Quantity(CFormatQuantity::FromValuesTuple)) { + if mapping_used { + return Err(star_mapping_error()); + } + precision = Some(CFormatPrecision::Quantity(CFormatQuantity::Amount( + values.star(true, vm)?.max(0) as usize, + ))); + } + consume_length(&mut characters); + let format_type = parse_format_type(&mut characters, context) + .map_err(|(error, _)| parse_error(vm, error, start))?; + let spec = CFormatSpec { + flags, + min_field_width, + precision, + format_type, + }; + let (value, arg) = if let Some(key) = &mapping_key { + ( + mapped_value.as_ref().unwrap().clone(), + FormatArg::Mapping(key), + ) } else { - once_iter = core::iter::once(values_obj); - &mut once_iter + values.next(true, vm)? }; - - for (_, part) in format { - match part { - CFormatPart::Literal(literal) => result.push_wtf8(&literal), - CFormatPart::Spec(CFormatSpecKeyed { mut spec, .. }) => { - try_update_quantity_from_tuple( - vm, - &mut value_iter, - &mut spec.min_field_width, - &mut spec.flags, - )?; - try_update_precision_from_tuple(vm, &mut value_iter, &mut spec.precision)?; - - let Some(value) = value_iter.next() else { - return Err(vm.new_type_error("not enough arguments for format string")); - }; - - let part_result = spec_format_string(vm, &spec, value.to_owned())?; - result.push_wtf8(&part_result); - } + if let CFormatType::Unsupported { ch, index } = format_type { + return Err(unsupported_format_error(vm, ch, start, index, context)); } + // Convert before reserving field padding: user callbacks must still + // run when an otherwise valid width cannot be allocated. + let mut unpadded_spec = spec; + unpadded_spec.min_field_width = None; + let value = format_value(vm, &unpadded_spec, value, arg)?; + let value = pad_output(vm, &spec, value)?; + result.reserve_output(value.len(), vm)?; + result = result.concat(value); } - // check that all arguments were converted - if !is_mapping && value_iter.next().is_some() { - Err(vm.new_type_error("not all arguments converted during string formatting")) - } else { - Ok(result) + if !is_mapping && values.consumed < values.count() { + let kind = match context { + CFormatContext::Str => "string", + CFormatContext::Bytes => "bytes", + }; + return Err(vm.new_type_error(format!( + "not all arguments converted during {kind} formatting (required {}, got {})", + values.consumed, + values.count() + ))); } + Ok(result) +} + +pub(crate) fn cformat_bytes( + vm: &VirtualMachine, + format_string: &[u8], + values_obj: &PyObject, +) -> PyResult> { + cformat( + vm, + format_string.iter().copied(), + values_obj, + CFormatContext::Bytes, + |key| vm.ctx.new_bytes(key).into(), + spec_format_bytes, + ) +} + +pub(crate) fn cformat_string( + vm: &VirtualMachine, + format_string: &Wtf8, + values_obj: &PyObject, +) -> PyResult { + cformat( + vm, + format_string.code_points(), + values_obj, + CFormatContext::Str, + |key| vm.ctx.new_str(key).into(), + spec_format_string, + ) } diff --git a/crates/vm/src/class.rs b/crates/vm/src/class.rs index 8a7a8306d16..24579d5548c 100644 --- a/crates/vm/src/class.rs +++ b/crates/vm/src/class.rs @@ -367,17 +367,23 @@ pub trait PyClassImpl: PyClassDef { // Don't add __new__ attribute if slot_new is inherited from object // (Python doesn't add __new__ to __dict__ for inherited slots) - // Exception: object itself should have __new__ in its dict - if let Some(slot_new) = class.slots().new.load() { + // Exception: object itself should have __new__ in its dict. + // DISALLOW_INSTANTIATION types must not expose an inherited __new__. + if !class + .slots() + .flags + .has_feature(PyTypeFlags::DISALLOW_INSTANTIATION) + && let Some(slot_new) = class.slots().new.load() + { let object_new = ctx.types.object_type.slots().new.load(); let is_object_itself = core::ptr::eq(class, ctx.types.object_type); let is_inherited_from_object = !is_object_itself && object_new.is_some_and(|obj_new| fn_addr(slot_new) == fn_addr(obj_new)); if !is_inherited_from_object { - let bound_new = - ctx.slot_new_wrapper - .build_bound_method(ctx, class.to_owned().into(), class); + let bound_new = ctx + .slot_new_wrapper + .build_bound_function(ctx, class.to_owned().into()); class.set_attr(identifier!(ctx, __new__), bound_new.into()); } } @@ -451,13 +457,38 @@ pub trait PyClassImpl: PyClassDef { /// Trait for Python subclasses that can provide a reference to their base type. /// -/// This trait is automatically implemented by the `#[pyclass]` macro when -/// `base = SomeType` is specified. It provides safe reference access to the -/// base type's payload. +/// The `#[pyclass]` macro implements this trait for `#[repr(transparent)]` +/// subclasses with `base = SomeType`. Other native subclasses can implement +/// it manually when their base is a compatible physical prefix. +/// +/// # Safety +/// +/// Every valid `Self` must contain a valid `Base` at offset zero, returned by +/// `as_base`. Their payload offsets in `Py` and `Py` must match, +/// and `Py` must meet `Py`'s alignment requirement. The base must +/// remain valid for the lifetime of `Self`, independently of the object's +/// Python class or MRO. These guarantees allow safe borrowing and ownership +/// transfer of the same allocation as `Py`. +/// +/// A manual implementation must explicitly acknowledge this contract: +/// +/// ```compile_fail,E0200 +/// use rustpython_vm::{builtins::PyInt, class::PySubclass, pyclass, PyPayload}; +/// +/// #[pyclass(module = false, name = "IntWrapper")] +/// #[derive(Debug, PyPayload)] +/// #[repr(transparent)] +/// struct IntWrapper(PyInt); +/// +/// #[pyclass] +/// impl IntWrapper {} /// -/// For subclasses with `#[repr(transparent)]` -/// which enables ownership transfer via `into_base()`. -pub trait PySubclass: crate::PyPayload { +/// impl PySubclass for IntWrapper { +/// type Base = PyInt; +/// fn as_base(&self) -> &PyInt { &self.0 } +/// } +/// ``` +pub unsafe trait PySubclass: crate::PyPayload { type Base: crate::PyPayload; /// Returns a reference to the base type's payload. diff --git a/crates/vm/src/codecs.rs b/crates/vm/src/codecs.rs index 587701d6528..c0b054d20dc 100644 --- a/crates/vm/src/codecs.rs +++ b/crates/vm/src/codecs.rs @@ -1,5 +1,6 @@ use alloc::borrow::Cow; use core::ops::{Deref, Range}; +use core::sync::atomic::Ordering; use std::collections::HashMap; use rustpython_common::{ @@ -15,14 +16,16 @@ use rustpython_common::{ }; use crate::{ - AsObject, Context, Py, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, + AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, builtins::{ - PyBaseExceptionRef, PyByteArray, PyBytes, PyBytesRef, PyStr, PyStrRef, PyTuple, PyTupleRef, - PyUtf8Str, PyUtf8StrRef, + PyBaseExceptionRef, PyByteArray, PyBytes, PyBytesRef, PyMemoryView, PyStr, PyStrRef, + PyTuple, PyTupleRef, PyUtf8Str, PyUtf8StrRef, }, convert::ToPyObject, - function::{ArgBytesLike, PyMethodDef}, + function::{ArgBytesLike, ArgNulFreeStr, OptionalArg, PyMethodDef}, + protocol::{BufferFlags, PyBuffer}, + types::AsBuffer, }; pub struct CodecsRegistry { @@ -37,6 +40,28 @@ struct RegistryInner { pub(crate) const DEFAULT_ENCODING: &str = "utf-8"; +/// The two optional Clinic string arguments shared by the public codec APIs. +/// Omitting either argument selects its default; passing None is not allowed. +#[derive(FromArgs)] +pub(crate) struct TextCodecArgs { + #[pyarg(any, optional, py_default = "'utf-8'")] + encoding: OptionalArg, + #[pyarg(any, optional, py_default = "'strict'")] + errors: OptionalArg, +} + +impl TextCodecArgs { + #[inline] + pub(crate) fn into_parts(self) -> (Option, Option) { + ( + self.encoding + .into_option() + .map(ArgNulFreeStr::into_utf8_ref), + self.errors.into_option().map(ArgNulFreeStr::into_utf8_ref), + ) + } +} + #[derive(Clone)] #[repr(transparent)] pub struct PyCodec(PyTupleRef); @@ -225,6 +250,41 @@ impl CodecsRegistry { } } + fn check_text_encoding_errors( + &self, + encoding: &str, + errors: Option<&Py>, + vm: &VirtualMachine, + ) -> PyResult<()> { + if !vm.state.config.settings.dev_mode { + return Ok(()); + } + let check_encoding = !matches!(encoding, "utf-8" | "utf8" | "ascii"); + let check_errors = errors.filter(|errors| { + !matches!( + errors.as_str(), + "strict" | "ignore" | "replace" | "surrogateescape" | "surrogatepass" + ) + }); + // Builtin shortcuts require neither a registry lookup nor its lock. + if (!check_encoding && check_errors.is_none()) + || vm.state.finalizing.load(Ordering::Acquire) + || !vm.state.filesystem_codec_ready.load(Ordering::Acquire) + { + return Ok(()); + } + // Match CPython's unicode_check_encoding_errors before text fast paths. + // Codec lookup may call search functions, but does not encode/decode; + // error-handler lookup validates the name without invoking the handler. + if check_encoding { + self.lookup(encoding, vm)?; + } + if let Some(errors) = check_errors { + self.lookup_error(errors.as_str(), vm)?; + } + Ok(()) + } + pub fn register(&self, search_function: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { if !search_function.is_callable() { return Err(vm.new_type_error("argument must be callable")); @@ -241,27 +301,30 @@ impl CodecsRegistry { return; } - for (i, item) in inner.search_path.iter().enumerate() { - if item.get_id() == search_function.get_id() { - if !inner.search_cache.is_empty() { - inner.search_cache.clear(); - } - inner.search_path.remove(i); - return; - } + if let Some(i) = inner + .search_path + .iter() + .position(|item| item.get_id() == search_function.get_id()) + { + let cache = core::mem::take(&mut inner.search_cache); + let function = inner.search_path.remove(i); + drop(inner); + drop((cache, function)); } } pub(crate) fn register_manual(&self, name: &str, codec: PyCodec) { - let name = normalize_encoding_name(name); - self.inner + let name = normalize_registry_name(name); + let _previous = self + .inner .write() .search_cache .insert(name.into_owned(), codec); } pub fn lookup(&self, encoding: &str, vm: &VirtualMachine) -> PyResult { - let encoding = normalize_encoding_name(encoding); + let original_encoding = encoding; + let encoding = normalize_registry_name(encoding); let search_path = { let inner = self.inner.read(); if let Some(codec) = inner.search_cache.get(encoding.as_ref()) { @@ -276,17 +339,21 @@ impl CodecsRegistry { let res = func.call((encoding.clone(),), vm)?; let res: Option = res.try_into_value(vm)?; if let Some(codec) = res { - let mut inner = self.inner.write(); - // someone might have raced us to this, so use theirs - let codec = inner - .search_cache - .entry(encoding.as_str().to_owned()) - .or_insert(codec); - return Ok(codec.clone()); + let cached = { + let mut inner = self.inner.write(); + // someone might have raced us to this, so use theirs + // Keep our tuple alive until the registry lock is released. + inner + .search_cache + .entry(encoding.as_str().to_owned()) + .or_insert_with(|| codec.clone()) + .clone() + }; + return Ok(cached); } } - Err(vm.new_lookup_error(format!("unknown encoding: {encoding}"))) + Err(vm.new_lookup_error(format!("unknown encoding: {original_encoding}"))) } fn _lookup_text_encoding( @@ -307,7 +374,7 @@ impl CodecsRegistry { } pub fn forget(&self, encoding: &str) -> Option { - let encoding = normalize_encoding_name(encoding); + let encoding = normalize_registry_name(encoding); self.inner.write().search_cache.remove(encoding.as_ref()) } @@ -344,28 +411,36 @@ impl CodecsRegistry { errors: Option, vm: &VirtualMachine, ) -> PyResult { - if let Some(b) = - Self::encode_fast(&obj, encoding, errors.as_deref(), vm).inspect_err(|exc| { - Self::add_codec_note(exc, "encoding", encoding, vm); - })? - { + self.check_text_encoding_errors(encoding, errors.as_deref(), vm)?; + if let Some(b) = Self::encode_fast(&obj, encoding, errors.as_deref(), vm)? { return Ok(b); } let codec = self._lookup_text_encoding(encoding, "codecs.encode()", vm)?; - codec - .encode(obj.into(), errors, vm) - .inspect_err(|exc| { - Self::add_codec_note(exc, "encoding", encoding, vm); - })? - .downcast() - .map_err(|obj| { - vm.new_type_error(format!( + let encoded = codec.encode(obj.into(), errors, vm).inspect_err(|exc| { + Self::add_codec_note(exc, "encoding", encoding, vm); + })?; + match encoded.downcast::() { + Ok(bytes) => Ok(bytes), + Err(obj) => { + if let Some(bytes) = obj.downcast_ref::() { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.runtime_warning, + format!( + "encoder {encoding} returned bytearray instead of bytes; use codecs.encode() to encode to arbitrary types" + ), + 1, + vm, + )?; + return Ok(vm.ctx.new_bytes(bytes.borrow_buf().to_vec())); + } + Err(vm.new_type_error(format!( "'{}' encoder returned '{}' instead of 'bytes'; use codecs.encode() to \ encode to arbitrary types", encoding, obj.class().name(), - )) - }) + ))) + } + } } /// The text an encoded object holds. An object holding nothing decodes to @@ -378,17 +453,51 @@ impl CodecsRegistry { errors: Option, vm: &VirtualMachine, ) -> PyResult { - let empty = if let Some(bytes) = obj.downcast_ref::() { - bytes.as_bytes().is_empty() - } else if let Some(bytes) = obj.downcast_ref::() { - bytes.borrow_buf().is_empty() - } else { - false - }; - if empty { + if let Some(bytes) = obj.downcast_ref::() { + if bytes.as_bytes().is_empty() { + self.check_text_encoding_errors(encoding, errors.as_deref(), vm)?; + return Ok(vm.ctx.empty_str.to_owned()); + } + return self.decode_text(obj, encoding, errors, vm); + } + if obj.fast_isinstance(vm.ctx.types.str_type) { + return Err(vm.new_type_error("decoding str is not supported")); + } + // Keep input exported across codec search callbacks, as + // PyUnicode_FromEncodedObject does. Do not hold a data borrow here: + // callbacks may overwrite bytes, but must not resize the exporter. + let buffer = PyBuffer::from_object(vm, &obj, BufferFlags::SIMPLE).map_err(|_| { + vm.new_type_error(format!( + "decoding to str: need a bytes-like object, {} found", + obj.class().name() + )) + })?; + if buffer.desc.len == 0 { + // CPython releases an empty export before validating codec names. + drop(buffer); + self.check_text_encoding_errors(encoding, errors.as_deref(), vm)?; return Ok(vm.ctx.empty_str.to_owned()); } - self.decode_text(obj, encoding, errors, vm) + self.check_text_encoding_errors(encoding, errors.as_deref(), vm)?; + if obj.class().is(vm.ctx.types.bytearray_type) { + return self.decode_text_impl( + obj, + encoding, + errors, + FastCodec::classify_text(encoding), + vm, + ); + } + // Preserve the original acquisition without re-running __buffer__ or + // copying before codec callbacks have had a chance to inspect it. + let view = PyMemoryView::from_buffer(buffer, vm)?.into_ref(&vm.ctx); + self.decode_text_impl( + view.into(), + encoding, + errors, + FastCodec::classify_text(encoding), + vm, + ) } pub fn decode_text( @@ -398,20 +507,62 @@ impl CodecsRegistry { errors: Option, vm: &VirtualMachine, ) -> PyResult { - if let Some(s) = - Self::decode_fast(&obj, encoding, errors.as_deref(), vm).inspect_err(|exc| { - Self::add_codec_note(exc, "decoding", encoding, vm); - })? - { + self.check_text_encoding_errors(encoding, errors.as_deref(), vm)?; + self.decode_text_impl( + obj, + encoding, + errors, + FastCodec::classify_text(encoding), + vm, + ) + } + + fn decode_text_impl( + &self, + obj: PyObjectRef, + encoding: &str, + errors: Option, + fast: Option, + vm: &VirtualMachine, + ) -> PyResult { + if let Some(s) = Self::decode_fast(&obj, fast, errors.as_deref(), vm)? { return Ok(s); } let codec = self._lookup_text_encoding(encoding, "codecs.decode()", vm)?; + Self::decode_text_with_codec(codec, obj, encoding, errors, vm) + } + + fn decode_text_with_codec( + codec: PyCodec, + obj: PyObjectRef, + encoding: &str, + errors: Option, + vm: &VirtualMachine, + ) -> PyResult { + // PyUnicode_Decode passes an anonymous, readonly memoryview to codecs, + // not the input's concrete bytes/bytearray type. + let buffer = if let Some(bytes) = obj.downcast_ref::() { + PyBytes::as_buffer(bytes, vm)? + } else { + PyBuffer::from_object(vm, &obj, BufferFlags::SIMPLE)? + }; + let view = PyMemoryView::from_anonymous_buffer(buffer, vm)?.into_ref(&vm.ctx); codec - .decode(obj, errors, vm) + .decode(view.into(), errors, vm) .inspect_err(|exc| { Self::add_codec_note(exc, "decoding", encoding, vm); })? - .downcast() + .downcast::() + .map(|text| { + // _PyUnicode_Result canonicalizes only empty/Latin-1 singletons. + if text.is_empty() { + vm.ctx.empty_str.to_owned() + } else if let Some(ch) = Context::latin1_singleton_index(&text) { + vm.ctx.latin1_char(ch) + } else { + text + } + }) .map_err(|obj| { vm.new_type_error(format!( "'{}' decoder returned '{}' instead of 'str'; use codecs.decode() to \ @@ -422,8 +573,7 @@ impl CodecsRegistry { }) } - /// Fast path for decoding with the "utf-8", "ascii" or "latin-1" - /// encodings (and their common aliases), used by `bytes.decode()` / + /// Native Unicode, ASCII and Latin-1 decoding shortcuts, used by `bytes.decode()` / /// `str(bytes, encoding)`. /// /// CPython's `PyUnicode_Decode` special-cases a handful of built-in @@ -435,41 +585,66 @@ impl CodecsRegistry { /// pure-Python `encodings.*.decode` wrapper and its 2-tuple result. fn decode_fast( obj: &PyObject, - encoding: &str, + fast: Option, errors: Option<&Py>, vm: &VirtualMachine, ) -> PyResult> { - let Some(fast) = FastCodec::classify(encoding) else { + let Some(fast) = fast else { return Ok(None); }; - let Ok(data) = ArgBytesLike::try_from_object(vm, obj.to_owned()) else { - return Ok(None); + let encoding = match fast { + FastCodec::Utf8 => DEFAULT_ENCODING, + FastCodec::Utf16 => crate::common::encodings::utf16::ENCODING_NAME, + FastCodec::Utf32 => crate::common::encodings::utf32::ENCODING_NAME, + FastCodec::Ascii => crate::common::encodings::ascii::ENCODING_NAME, + FastCodec::Latin1 => crate::common::encodings::latin_1::ENCODING_NAME, + }; + let data; + let ctx = if let Some(bytes) = obj.downcast_ref::() { + // PyUnicode_FromEncodedObject uses a bytes subclass's native + // payload, ignoring any Python __buffer__ override. + PyDecodeContext { + vm, + encoding, + data: PyDecodeData::Original(bytes.as_bytes().into()), + pos: 0, + exception: OnceCell::new(), + } + } else { + let Ok(buffer) = ArgBytesLike::try_from_object(vm, obj.to_owned()) else { + return Ok(None); + }; + data = buffer; + PyDecodeContext::new(encoding, &data, vm) }; let errors_handler = ErrorsHandler::new(errors, vm); let (decoded, _consumed) = match fast { - FastCodec::Utf8 => { - let ctx = PyDecodeContext::new(DEFAULT_ENCODING, &data, vm); - crate::common::encodings::utf8::decode(ctx, &errors_handler, true)? - } - FastCodec::Ascii => { - let ctx = - PyDecodeContext::new(crate::common::encodings::ascii::ENCODING_NAME, &data, vm); - crate::common::encodings::ascii::decode(ctx, &errors_handler)? + FastCodec::Utf8 => crate::common::encodings::utf8::decode(ctx, &errors_handler, true)?, + FastCodec::Utf16 => { + let (text, consumed, _) = crate::common::encodings::utf16::decode( + ctx, + &errors_handler, + crate::common::encodings::utf16::ByteOrder::Native, + true, + )?; + (text, consumed) } - FastCodec::Latin1 => { - let ctx = PyDecodeContext::new( - crate::common::encodings::latin_1::ENCODING_NAME, - &data, - vm, - ); - crate::common::encodings::latin_1::decode(ctx, &errors_handler)? + FastCodec::Utf32 => { + let (text, consumed, _) = crate::common::encodings::utf32::decode( + ctx, + &errors_handler, + crate::common::encodings::utf32::ByteOrder::Native, + true, + )?; + (text, consumed) } + FastCodec::Ascii => crate::common::encodings::ascii::decode(ctx, &errors_handler)?, + FastCodec::Latin1 => crate::common::encodings::latin_1::decode(ctx, &errors_handler)?, }; Ok(Some(vm.ctx.new_str(decoded))) } - /// Fast path for encoding with the "utf-8", "ascii" or "latin-1" - /// encodings (and their common aliases), used by `str.encode()` / + /// Native Unicode, ASCII and Latin-1 encoding shortcuts, used by `str.encode()` / /// `bytes(s, encoding)`. See [`Self::decode_fast`] for the rationale. fn encode_fast( obj: &Py, @@ -477,7 +652,7 @@ impl CodecsRegistry { errors: Option<&Py>, vm: &VirtualMachine, ) -> PyResult> { - let Some(fast) = FastCodec::classify(encoding) else { + let Some(fast) = FastCodec::classify_text(encoding) else { return Ok(None); }; if fast == FastCodec::Utf8 && obj.is_utf8() { @@ -492,6 +667,26 @@ impl CodecsRegistry { let ctx = PyEncodeContext::new(DEFAULT_ENCODING, obj, vm); crate::common::encodings::utf8::encode(ctx, &errors_handler)? } + FastCodec::Utf16 => { + let ctx = + PyEncodeContext::new(crate::common::encodings::utf16::ENCODING_NAME, obj, vm); + crate::common::encodings::utf16::encode( + ctx, + &errors_handler, + crate::common::encodings::utf16::ByteOrder::Native, + true, + )? + } + FastCodec::Utf32 => { + let ctx = + PyEncodeContext::new(crate::common::encodings::utf32::ENCODING_NAME, obj, vm); + crate::common::encodings::utf32::encode( + ctx, + &errors_handler, + crate::common::encodings::utf32::ByteOrder::Native, + true, + )? + } FastCodec::Ascii => { let ctx = PyEncodeContext::new(crate::common::encodings::ascii::ENCODING_NAME, obj, vm); @@ -536,7 +731,8 @@ impl CodecsRegistry { "cannot un-register built-in error handler '{name}'" ))); } - Ok(self.inner.write().errors.remove(name).is_some()) + let handler = self.inner.write().errors.remove(name); + Ok(handler.is_some()) } pub fn lookup_error_opt(&self, name: &str) -> Option { @@ -554,14 +750,45 @@ impl CodecsRegistry { /// native (de)coders are cheap to call directly, bypassing the codec /// registry round trip. Matches the alias sets in `Lib/encodings/aliases.py`. #[derive(Clone, Copy, Eq, PartialEq)] -enum FastCodec { +pub(crate) enum FastCodec { Utf8, + Utf16, + Utf32, Ascii, Latin1, } impl FastCodec { - fn classify(encoding: &str) -> Option { + pub(crate) const fn name(self) -> &'static str { + match self { + Self::Utf8 => "utf-8", + Self::Utf16 => "utf-16", + Self::Utf32 => "utf-32", + Self::Ascii => "ascii", + Self::Latin1 => "iso8859-1", + } + } + + // PyUnicode_Decode/PyUnicode_AsEncodedString only bypass the registry for + // these normalized spellings, not every alias that encodings recognizes. + fn classify_text(encoding: &str) -> Option { + match encoding { + "utf-8" | "utf8" | "UTF-8" => return Some(Self::Utf8), + "ascii" => return Some(Self::Ascii), + "latin-1" | "latin1" | "iso-8859-1" => return Some(Self::Latin1), + _ => {} + } + match normalize_encoding_name(encoding).as_ref() { + "utf_8" | "utf8" => Some(Self::Utf8), + "utf_16" | "utf16" => Some(Self::Utf16), + "utf_32" | "utf32" => Some(Self::Utf32), + "ascii" | "us_ascii" => Some(Self::Ascii), + "latin1" | "latin_1" | "iso_8859_1" | "iso8859_1" => Some(Self::Latin1), + _ => None, + } + } + + pub(crate) fn classify(encoding: &str) -> Option { const UTF8_ALIASES: &[&str] = &[ "utf_8", "utf8", @@ -622,6 +849,26 @@ impl FastCodec { } } +fn normalize_registry_name(encoding: &str) -> Cow<'_, str> { + if !encoding + .bytes() + .any(|b| b.is_ascii_uppercase() || b == b' ') + { + return encoding.into(); + } + encoding + .chars() + .map(|c| { + if c == ' ' { + '-' + } else { + c.to_ascii_lowercase() + } + }) + .collect::() + .into() +} + fn normalize_encoding_name(encoding: &str) -> Cow<'_, str> { // _Py_normalize_encoding: collapse non-alphanumeric/non-dot chars into // single underscore, strip non-ASCII, lowercase ASCII letters. @@ -911,7 +1158,6 @@ pub(crate) struct PyDecodeContext<'a> { vm: &'a VirtualMachine, encoding: &'a str, data: PyDecodeData<'a>, - orig_bytes: Option<&'a Py>, pos: usize, exception: OnceCell, } @@ -933,12 +1179,40 @@ impl Deref for PyDecodeData<'_> { } impl<'a> PyDecodeContext<'a> { + // Native wide codecs choose the diagnostic byte order once, on their + // first error. This also gives surrogatepass the decoder's actual order. + fn effective_encoding(&self) -> &'a str { + match self.encoding { + "utf-16" => { + let big = self.data.starts_with(&[0xfe, 0xff]) + || (cfg!(target_endian = "big") && !self.data.starts_with(&[0xff, 0xfe])); + if big { "utf-16-be" } else { "utf-16-le" } + } + "utf-32" => { + let big = self.data.starts_with(&[0x00, 0x00, 0xfe, 0xff]) + || (cfg!(target_endian = "big") + && !self.data.starts_with(&[0xff, 0xfe, 0x00, 0x00])); + if big { "utf-32-be" } else { "utf-32-le" } + } + encoding => encoding, + } + } + pub(crate) fn new(encoding: &'a str, data: &'a ArgBytesLike, vm: &'a VirtualMachine) -> Self { Self { vm, encoding, data: PyDecodeData::Original(data.borrow_buf()), - orig_bytes: data.as_object().downcast_ref(), + pos: 0, + exception: OnceCell::new(), + } + } + + pub(crate) fn new_owned(encoding: &'a str, data: PyBytesRef, vm: &'a VirtualMachine) -> Self { + Self { + vm, + encoding, + data: PyDecodeData::Modified(data), pos: 0, exception: OnceCell::new(), } @@ -988,6 +1262,15 @@ impl DecodeContext for PyDecodeContext<'_> { Ok(()) } + fn load_unicode_names(&self) -> Result<(), Self::Error> { + self.vm.load_unicode_names().map_err(|_| { + self.vm.new_exception_msg( + self.vm.ctx.exceptions.unicode_error.to_owned(), + "\\N escapes not supported (can't load unicodedata module)".into(), + ) + }) + } + fn error_decoding(&self, byte_range: Range, reason: Option<&str>) -> Self::Error { let vm = self.vm; @@ -1010,11 +1293,9 @@ impl DecodeContext for PyDecodeContext<'_> { let reason = reason.expect( "should only ever pass reason: None if an exception is already set", ); - let data = if let Some(bytes) = self.orig_bytes { - bytes.to_owned() - } else { - vm.ctx.new_bytes(self.data.to_vec()) - }; + // PyUnicodeDecodeError_Create snapshots the input as exact + // bytes, including when the input is a bytes subclass. + let data = vm.ctx.new_bytes(self.data.to_vec()); vm.new_unicode_decode_error( vm.ctx.new_str(self.encoding), data, @@ -1093,6 +1374,7 @@ impl<'a> DecodeErrorHandler> for StandardError { pub(crate) struct ErrorsHandler<'a> { errors: &'a Py, resolved: OnceCell, + use_registry: bool, } enum ResolvedError { @@ -1107,22 +1389,34 @@ impl<'a> ErrorsHandler<'a> { Self { errors, resolved: OnceCell::new(), + use_registry: false, } } else { Self { errors: identifier_utf8!(vm, strict), resolved: OnceCell::from(ResolvedError::Standard(StandardError::Strict)), + use_registry: false, } } } + pub(crate) fn new_registered(errors: Option<&'a Py>, vm: &VirtualMachine) -> Self { + Self { + errors: errors.unwrap_or_else(|| identifier_utf8!(vm, strict)), + resolved: OnceCell::new(), + use_registry: true, + } + } + #[inline] fn resolve(&self, vm: &VirtualMachine) -> PyResult<&ResolvedError> { if let Some(val) = self.resolved.get() { return Ok(val); } let errors_str = self.errors.as_str(); - let val = if let Ok(standard) = errors_str.parse() { + let val = if !self.use_registry + && let Ok(standard) = errors_str.parse() + { ResolvedError::Standard(standard) } else { vm.state @@ -1163,18 +1457,24 @@ impl<'a> EncodeErrorHandler> for ErrorsHandler<'_> { Some([replace, restart]) => (replace.clone(), restart), _ => return Err(tuple_err()), }; + let restart = isize::try_from(restart.try_index(vm)?.as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C ssize_t"))?; let replace = match_class!(match replace { s @ PyStr => EncodeReplace::Str(s), b @ PyBytes => EncodeReplace::Bytes(b), _ => return Err(tuple_err()), }); - let restart = isize::try_from_borrowed_object(vm, restart).map_err(|_| tuple_err())?; let restart = if restart < 0 { - // will still be out of bounds if it underflows ¯\_(ツ)_/¯ - ctx.data.char_len().wrapping_sub(restart.unsigned_abs()) + ctx.data.char_len() as isize + restart } else { - restart as usize + restart }; + if restart < 0 || restart as usize > ctx.data.char_len() { + return Err(vm.new_index_error(format!( + "position {restart} from error handler out of bounds" + ))); + } + let restart = restart as usize; let restart = if restart == range.end.chars { range.end } else { @@ -1200,6 +1500,7 @@ impl<'a> DecodeErrorHandler> for ErrorsHandler<'_> { reason: Option<&str>, ) -> PyResult<(PyStrRef, usize)> { let vm = ctx.vm; + ctx.encoding = ctx.effective_encoding(); let handler = match self.resolve(vm)? { ResolvedError::Standard(standard) => { return standard.handle_decode_error(ctx, byte_range, reason); @@ -1207,35 +1508,53 @@ impl<'a> DecodeErrorHandler> for ErrorsHandler<'_> { ResolvedError::Handler(handler) => handler, }; let decode_exc = ctx.error_decoding(byte_range, reason); - let data_bytes: PyObjectRef = decode_exc.as_object().get_attr("object", vm)?; - let res = handler.call((decode_exc.clone(),), vm)?; - let new_data = decode_exc.as_object().get_attr("object", vm)?; - if !new_data.is(&data_bytes) { - let new_data: PyBytesRef = new_data - .downcast() - .map_err(|_| vm.new_type_error("object attribute must be bytes"))?; - ctx.data = PyDecodeData::Modified(new_data); + if matches!(ctx.data, PyDecodeData::Original(_)) { + // Release the original buffer's read guard before calling Python. + // A retained exception may have been changed by a mapping callback; + // only validate its object after the error handler can repair it. + let data_bytes = decode_exc + .as_object() + .get_attr("object", vm)? + .downcast::() + .map_err(|_| { + vm.new_type_error("UnicodeError 'object' attribute must be a bytes") + })?; + ctx.data = PyDecodeData::Modified(data_bytes); } - let data = &*ctx.data; + let res = handler.call((decode_exc.clone(),), vm)?; let tuple_err = || vm.new_type_error("decoding error handler must return (str, int) tuple"); - match res.downcast_ref::().map(|tup| tup.as_slice()) { + let (replace, restart) = match res.downcast_ref::().map(|tup| tup.as_slice()) { Some([replace, restart]) => { let replace = replace .downcast_ref::() .ok_or_else(tuple_err)? .to_owned(); let restart = - isize::try_from_borrowed_object(vm, restart).map_err(|_| tuple_err())?; - let restart = if restart < 0 { - // will still be out of bounds if it underflows ¯\_(ツ)_/¯ - data.len().wrapping_sub(restart.unsigned_abs()) - } else { - restart as usize - }; - Ok((replace, restart)) + isize::try_from(restart.try_index(vm)?.as_bigint()).map_err(|_| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") + })?; + (replace, restart) } - _ => Err(tuple_err()), + _ => return Err(tuple_err()), + }; + // Result validation (including __index__) precedes re-reading object. + let new_data = decode_exc + .as_object() + .get_attr("object", vm)? + .downcast::() + .map_err(|_| vm.new_type_error("UnicodeError 'object' attribute must be a bytes"))?; + ctx.data = PyDecodeData::Modified(new_data); + let restart = if restart < 0 { + ctx.data.len() as isize + restart + } else { + restart + }; + if restart < 0 || restart as usize > ctx.data.len() { + return Err(vm.new_index_error(format!( + "position {restart} from error handler out of bounds" + ))); } + Ok((replace, restart as usize)) } } @@ -1294,7 +1613,6 @@ where vm, encoding: s_encoding.as_str(), data: PyDecodeData::Original(s.borrow_buf()), - orig_bytes: s.as_object().downcast_ref(), pos: 0, exception: OnceCell::from(err.downcast().unwrap()), }; @@ -1449,6 +1767,7 @@ fn backslashreplace_errors( fn namereplace_errors(err: PyObjectRef, vm: &VirtualMachine) -> PyResult<(PyObjectRef, usize)> { if is_encode_err(&err, vm) { + vm.load_unicode_names()?; call_native_encode_error(errors::NameReplace, err, vm) } else { Err(bad_err_type(&err, vm)) diff --git a/crates/vm/src/compiler.rs b/crates/vm/src/compiler.rs index 9842bc0d1c7..c50fbb74870 100644 --- a/crates/vm/src/compiler.rs +++ b/crates/vm/src/compiler.rs @@ -11,8 +11,8 @@ cfg_select! { _ => { pub use ruff_python_parser as parser; - pub use rustpython_compiler_core::Mode; pub use rustpython_compiler_core as core; + pub use rustpython_compiler_core::Mode; } } diff --git a/crates/vm/src/convert/try_from.rs b/crates/vm/src/convert/try_from.rs index 57d611f90cf..fb6dd803585 100644 --- a/crates/vm/src/convert/try_from.rs +++ b/crates/vm/src/convert/try_from.rs @@ -4,6 +4,7 @@ use num_traits::ToPrimitive; use crate::{ Py, VirtualMachine, builtins::PyFloat, + function::ArgumentError, object::{AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyResult}, }; @@ -14,6 +15,22 @@ use crate::{ pub trait TryFromObject: Sized { /// Attempt to convert a Python object to a value of this type. fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult; + + /// Convert a native method receiver after descriptor binding. Most custom + /// receivers use their ordinary conversion; payload receivers avoid repeating + /// the Python class check while still validating their Rust representation. + #[doc(hidden)] + #[inline] + fn try_from_method_receiver(vm: &VirtualMachine, obj: &PyObject) -> PyResult { + Self::try_from_object(vm, obj.to_owned()) + } + + /// Convert a call argument. `PyRef` turns an isinstance failure into + /// `_PyArg_BadArgument`; other types keep `try_from_object`. + #[inline] + fn try_from_argument(vm: &VirtualMachine, obj: PyObjectRef) -> Result { + Self::try_from_object(vm, obj).map_err(Into::into) + } } /// Rust-side only version of TryFromObject to reduce unnecessary Rc::clone @@ -70,6 +87,21 @@ where { /// Attempt to convert a Python object to a value of this type. fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult; + + #[inline] + fn try_from_borrowed_argument( + vm: &VirtualMachine, + obj: &'a PyObject, + ) -> Result { + Self::try_from_borrowed_object(vm, obj).map_err(Into::into) + } +} + +impl<'a> TryFromBorrowedObject<'a> for &'a PyObject { + #[inline] + fn try_from_borrowed_object(_vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + Ok(obj) + } } impl TryFromObject for PyRef @@ -86,6 +118,27 @@ where Err(vm.new_downcast_type_error(class, &obj)) } } + + #[inline] + fn try_from_method_receiver(vm: &VirtualMachine, obj: &PyObject) -> PyResult { + obj.try_downcast_ref::(vm).map(ToOwned::to_owned) + } + + #[inline] + fn try_from_argument(vm: &VirtualMachine, obj: PyObjectRef) -> Result { + let class = T::class(&vm.ctx); + if obj.fast_isinstance(class) { + T::try_downcast_from(&obj, vm)?; + Ok(unsafe { obj.downcast_unchecked() }) + } else { + Err(ArgumentError::BadArgument { + expected: class, + or_none: false, + found: obj, + name: None, + }) + } + } } impl TryFromObject for PyObjectRef { @@ -103,6 +156,16 @@ impl TryFromObject for Option { T::try_from_object(vm, obj).map(Some) } } + + fn try_from_argument(vm: &VirtualMachine, obj: PyObjectRef) -> Result { + if vm.is_none(&obj) { + Ok(None) + } else { + T::try_from_argument(vm, obj) + .map(Some) + .map_err(ArgumentError::with_or_none) + } + } } impl<'a, T: 'a + TryFromObject> TryFromBorrowedObject<'a> for Vec { @@ -121,6 +184,26 @@ impl<'a, T: PyPayload> TryFromBorrowedObject<'a> for &'a Py { Err(vm.new_downcast_type_error(class, &obj)) } } + + #[inline] + fn try_from_borrowed_argument( + vm: &VirtualMachine, + obj: &'a PyObject, + ) -> Result { + let class = T::class(&vm.ctx); + if obj.fast_isinstance(class) { + obj.try_downcast_ref::(vm).map_err(Into::into) + } else { + Err(ArgumentError::BadArgument { + expected: class, + or_none: false, + // Only an error needs an owning diagnostic, never the call's + // successful borrowed conversion path. + found: obj.to_owned(), + name: None, + }) + } + } } impl TryFromObject for core::time::Duration { diff --git a/crates/vm/src/coroutine.rs b/crates/vm/src/coroutine.rs index 5da8c8272a1..52b07ef9c6a 100644 --- a/crates/vm/src/coroutine.rs +++ b/crates/vm/src/coroutine.rs @@ -10,6 +10,7 @@ use crate::{ vm::GenFrameLink, }; use crossbeam_utils::atomic::AtomicCell; +use rustpython_common::wtf8::wtf8_concat; impl ExecutionResult { /// Turn an ExecutionResult into a PyResult that would be returned from a generator or coroutine @@ -31,6 +32,15 @@ impl ExecutionResult { } } +// Inspection must exclude execution without appearing to execute Python code. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +#[repr(u8)] +enum FrameAccess { + Idle, + Executing, + Inspecting, +} + #[derive(Debug)] pub struct Coro { /// Generator iframe, like `gi_iframe`. Cleared to `None` by take_ownership @@ -39,7 +49,9 @@ pub struct Coro { /// `f_executable`; survives `_PyFrame_ClearExceptCode`. code: PyRef, pub closed: AtomicCell, // TODO: https://github.com/RustPython/RustPython/pull/3183#discussion_r720560652 - running: AtomicCell, + access: AtomicCell, + /// Whether execution has resumed beyond the eager creation preamble. + started: AtomicCell, // _weakreflist name: PyMutex, qualname: PyMutex, @@ -62,7 +74,7 @@ unsafe impl Traverse for Coro { /// An exclusive claim on a generator's frame, released when dropped. /// -/// Only the holder may look at the frame or resume it. Resuming decides from +/// This excludes both inspectors and other executors. Resuming decides from /// the frame state whether the sent value goes on the value stack, so a state /// read taken before the claim can be answered by a frame that another thread /// then advances: resuming it leaves the stack short of what the code after @@ -71,7 +83,17 @@ struct RunningGuard<'a>(&'a Coro); impl Drop for RunningGuard<'_> { fn drop(&mut self) { - self.0.running.store(false); + self.0.access.store(FrameAccess::Idle); + } +} + +// No Python callbacks, safepoints, or owned-reference drops may occur while +// this guard is held. Contenders can therefore wait without parking its owner. +struct InspectionGuard<'a>(&'a Coro); + +impl Drop for InspectionGuard<'_> { + fn drop(&mut self) { + self.0.access.store(FrameAccess::Idle); } } @@ -159,16 +181,16 @@ pub(crate) fn flat_resume_enter( if coro.closed.load() { return Ok(FlatEnter::Exhausted); } - let value = if coro.frame_opt().is_some_and(|f| f.lasti() > 0) { - Some(value) - } else if !vm.is_none(&value) { + if !coro.started() && !vm.is_none(&value) { return Err(vm.new_type_error(format!( "can't send non-None value to a just-started {}", gen_name(&jen, vm), ))); - } else { - None - }; + } + let value = coro + .frame_opt() + .is_some_and(|f| f.lasti() > 0) + .then_some(value); // SAFETY: exclusive access guaranteed by the claim let gen_exc = unsafe { coro.exception.swap(None) }; let frame_ref = coro.frame(); @@ -184,6 +206,7 @@ pub(crate) fn flat_resume_enter( return Err(exc); } }; + coro.started.store(true); // The claim outlives this scope; `flat_resume_exit` drops it. core::mem::forget(_claim); Ok(FlatEnter::Entered { @@ -233,7 +256,8 @@ impl Coro { frame: Some(frame).into(), code, closed: AtomicCell::new(false), - running: AtomicCell::new(false), + access: AtomicCell::new(FrameAccess::Idle), + started: AtomicCell::new(false), exception: PyAtomicRef::from(None), name: PyMutex::new(name), qualname: PyMutex::new(qualname), @@ -286,12 +310,51 @@ impl Coro { /// What the resume depends on -- whether the generator is closed, and /// whether it has started -- has to be read from here onwards. fn claim(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult> { - if self.running.compare_exchange(false, true).is_err() { + if !self.try_claim_execution() { return Err(vm.new_value_error(format!("{} already executing", gen_name(jen, vm)))); } Ok(RunningGuard(self)) } + fn try_claim_execution(&self) -> bool { + loop { + match self + .access + .compare_exchange(FrameAccess::Idle, FrameAccess::Executing) + { + Ok(_) => return true, + Err(FrameAccess::Executing) => return false, + Err(FrameAccess::Inspecting) => std::thread::yield_now(), + Err(FrameAccess::Idle) => continue, + } + } + } + + pub(crate) fn yield_from_target(&self) -> Option { + let _claim = loop { + match self + .access + .compare_exchange(FrameAccess::Idle, FrameAccess::Inspecting) + { + Ok(_) => break InspectionGuard(self), + Err(FrameAccess::Executing) => return None, + Err(FrameAccess::Inspecting) => std::thread::yield_now(), + Err(FrameAccess::Idle) => continue, + } + }; + // clear_frame releases its execution claim before clearing the frame. + // Its closed flag prevents inspectors from touching that retired frame. + if self.closed.load() { + None + } else { + self.frame.deref().and_then(|frame| { + // SAFETY: inspection excludes resume/close and other inspectors. + // This only reads the suspended stack and increments its target. + unsafe { frame.yield_from_target() } + }) + } + } + fn run_claimed( &self, _claim: &RunningGuard<'_>, @@ -307,6 +370,7 @@ impl Coro { let frame = self.frame(); vm.resume_gen_frame(&frame, gen_exc, |f| { + self.started.store(true); let result = func(f); // SAFETY: exclusive access guaranteed by the claim let _old = unsafe { (*exception_ptr).swap(vm.current_exception()) }; @@ -401,16 +465,16 @@ impl Coro { if self.closed.load() { return Self::send_when_closed(jen, vm); } - let value = if self.frame_opt().is_some_and(|f| f.lasti() > 0) { - Some(value) - } else if !vm.is_none(&value) { + if !self.started() && !vm.is_none(&value) { return Err(vm.new_type_error(format!( "can't send non-None value to a just-started {}", gen_name(jen, vm), ))); - } else { - None - }; + } + let value = self + .frame_opt() + .is_some_and(|f| f.lasti() > 0) + .then_some(value); let result = self.run_claimed(&claim, vm, |f| f.resume(value, vm)); self.maybe_close(&result, &claim); drop(claim); @@ -462,7 +526,7 @@ impl Coro { return Ok(vm.ctx.none()); } // FRAME_CREATED: mark finished and clear the iframe. - if self.frame_opt().is_none_or(|f| f.lasti() == 0) { + if !self.started() { self.closed.store(true); self.clear_except_code(); return Ok(vm.ctx.none()); @@ -490,20 +554,59 @@ impl Coro { } } + /// Clear a created generator frame without resuming its body. + pub(crate) fn clear_frame(&self, jen: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + if self.closed.load() { + return Ok(()); + } + if !self.try_claim_execution() { + return Err(vm.new_runtime_error("cannot clear an executing frame")); + } + let claim = RunningGuard(self); + if self.closed.load() { + return Ok(()); + } + if self.started() { + return Err(vm.new_runtime_error("cannot clear a suspended frame")); + } + self.closed.store(true); + // Closed owners cannot resume. Publish that state and release the + // running claim before a warning hook can observe or clear us again. + drop(claim); + if jen.class().is(vm.ctx.types.coroutine_type) { + crate::warn::warn_unawaited_coroutine(jen, &self.qualname(), vm); + } + self.clear_except_code(); + Ok(()) + } + /// Whether the frame has run at all, i.e. is stopped at a `yield` rather /// than at its start. pub(crate) fn started(&self) -> bool { - self.frame_opt().is_some_and(|f| f.lasti() > 0) + self.started.load() + } + + pub(crate) fn state_name(&self, names: [&'static str; 4]) -> &'static str { + // Closing publishes the terminal state before releasing frame locals, + // whose finalizers can observe us while the running claim is held. + let index = if self.closed() { + 3 + } else if self.running() { + 1 + } else if self.started() { + 2 + } else { + 0 + }; + names[index] } pub fn suspended(&self) -> bool { - !self.closed.load() - && !self.running.load() - && self.frame_opt().is_some_and(|f| f.lasti() > 0) + !self.closed.load() && !self.running() && self.started() } pub fn running(&self) -> bool { - self.running.load() + self.access.load() == FrameAccess::Executing } pub fn closed(&self) -> bool { @@ -533,7 +636,8 @@ impl Coro { } pub fn set_name(&self, name: PyStrRef) { - *self.name.lock() = name; + // A string subclass can run a finalizer that reenters this object. + let _old = core::mem::replace(&mut *self.name.lock(), name); } pub fn qualname(&self) -> PyStrRef { @@ -541,7 +645,7 @@ impl Coro { } pub fn set_qualname(&self, qualname: PyStrRef) { - *self.qualname.lock() = qualname; + let _old = core::mem::replace(&mut *self.qualname.lock(), qualname); } pub fn repr(&self, jen: &PyObject, id: usize, vm: &VirtualMachine) -> String { @@ -632,12 +736,16 @@ pub(crate) fn get_awaitable_iter(obj: PyObjectRef, vm: &VirtualMachine) -> PyRes .contains(crate::bytecode::CodeFlags::ITERABLE_COROUTINE) }) { - return Err(vm.new_type_error("__await__() returned a coroutine")); + return Err(vm.new_type_error(wtf8_concat!( + obj.class().fully_qualified_name(vm)?, + ".__await__() must return an iterator, not coroutine" + ))); } if !PyIter::check(&result) { - return Err(vm.new_type_error(format!( - "__await__() returned non-iterator of type '{}'", - result.class().name() + return Err(vm.new_type_error(wtf8_concat!( + obj.class().fully_qualified_name(vm)?, + ".__await__() must return an iterator, not ", + result.class().fully_qualified_name(vm)? ))); } return Ok(result); diff --git a/crates/vm/src/dict_inner.rs b/crates/vm/src/dict_inner.rs index 4a901bfbf0e..058a77c057e 100644 --- a/crates/vm/src/dict_inner.rs +++ b/crates/vm/src/dict_inner.rs @@ -31,7 +31,7 @@ use num_traits::ToPrimitive; /// hash value of an object returned by __hash__ type HashValue = hash::PyHash; /// index calculated by resolving collision -type HashIndex = hash::PyHash; +type HashIndex = hash::PyUHash; /// index into dict.indices type IndexIndex = usize; /// index into dict.entries @@ -184,6 +184,8 @@ impl IndexEntry { struct DictInner { used: usize, filled: usize, + // Only private atomic relocations invalidate same-size reverse iteration. + relocation_epoch: u64, indices: Vec, entries: Vec>>, } @@ -210,7 +212,7 @@ impl Clone for Dict { } // Keep dense copies cheap, but do not carry mostly empty storage into // a new dictionary. pop_back can leave oversized indices without holes. - let inner = if inner.used >= inner.entries.len() - inner.entries.len() / 3 + let mut inner = if inner.used >= inner.entries.len() - inner.entries.len() / 3 && (inner.indices.len() <= 8 || inner.used >= inner.indices.len() / 4) { inner.clone() @@ -218,6 +220,7 @@ impl Clone for Dict { let mut copy = DictInner { used: inner.used, filled: inner.used, + relocation_epoch: 0, indices: Vec::new(), entries: Vec::with_capacity(inner.used), }; @@ -226,6 +229,7 @@ impl Clone for Dict { copy.resize(inner.used * 2); copy }; + inner.relocation_epoch = 0; Self { inner: PyRwLock::new(inner), keys_version: AtomicU32::new(0), @@ -239,6 +243,7 @@ impl Default for Dict { inner: PyRwLock::new(DictInner { used: 0, filled: 0, + relocation_epoch: 0, indices: vec![IndexEntry::FREE; 8], entries: Vec::new(), }), @@ -256,27 +261,34 @@ struct DictEntry { } static_assertions::assert_eq_size!(DictEntry, Option>); -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq)] pub struct DictSize { indices_size: usize, pub entries_size: usize, pub used: usize, filled: usize, + relocation_epoch: u64, } -/// The dict was resized under an iterator holding an older [`DictSize`]. +impl DictSize { + pub(crate) fn has_same_used_and_relocations(&self, other: &Self) -> bool { + self.used == other.used && self.relocation_epoch == other.relocation_epoch + } +} + +/// The dict changed under an iterator holding an older [`DictSize`]. #[derive(Debug)] pub(crate) struct DictChanged; struct GenIndexes { idx: HashIndex, - perturb: HashValue, + perturb: hash::PyUHash, mask: HashIndex, } impl GenIndexes { const fn new(hash: HashValue, mask: HashIndex) -> Self { - let hash = hash.abs(); + let hash = hash as hash::PyUHash; Self { idx: hash, perturb: hash, @@ -291,7 +303,7 @@ impl GenIndexes { .wrapping_add(self.perturb) .wrapping_add(1); self.perturb >>= 5; - (prev & self.mask) as usize + prev & self.mask } } @@ -324,7 +336,7 @@ impl DictInner { self.entries = compacted; } self.indices = vec![IndexEntry::FREE; new_size]; - let mask = (new_size - 1) as i64; + let mask = (new_size - 1) as HashIndex; for (entry_idx, entry) in self.entries.iter_mut().enumerate() { // SAFETY: compaction above removed every hole, so every slot is // occupied here. @@ -387,6 +399,7 @@ impl DictInner { entries_size: self.entries.len(), used: self.used, filled: self.filled, + relocation_epoch: self.relocation_epoch, } } @@ -578,22 +591,14 @@ impl Dict { } } - /// Store a key - pub(crate) fn insert(&self, vm: &VirtualMachine, key: &K, value: T) -> PyResult<()> - where - K: DictKey + ?Sized, - { - let hash = key.key_hash(vm)?; - self.insert_known_hash(vm, key, hash, value) - } - - /// Store a key whose hash the caller already knows. + /// Store a key. /// /// `hash` must be computed for `key` or read from [`Self::keys_with_hashes`] - /// or [`Self::next_entry_with_hash`] on a container holding this same key. + /// or [`Self::items_with_hashes`] or [`Self::next_entry_with_hash`] on a + /// container holding this same key. /// A wrong hash lands the entry in a bucket no lookup probes, silently /// losing the key. - pub(crate) fn insert_known_hash( + pub(crate) fn insert( &self, vm: &VirtualMachine, key: &K, @@ -603,16 +608,16 @@ impl Dict { where K: DictKey + ?Sized, { - self.insert_known_hash_indexed(vm, key, hash, value)?; + self.insert_indexed(vm, key, hash, value)?; Ok(()) } - /// [`Self::insert_known_hash`], also reporting the entry index it stored to. + /// [`Self::insert`], also reporting the entry index it stored to. /// /// The index doubles as a `hint` for [`Self::get_hint`] / /// [`Self::insert_with_hint`], so a caller that wants one gets it from the /// store itself instead of probing the dict a second time. - fn insert_known_hash_indexed( + fn insert_indexed( &self, vm: &VirtualMachine, key: &K, @@ -622,90 +627,50 @@ impl Dict { where K: DictKey + ?Sized, { - let (stored_index, _removed) = loop { - let (entry_index, index_index) = self.lookup(vm, key, hash, None)?; - let mut inner = self.write(); - if let Some(index) = entry_index.index() { - // Update existing key - if let Some(entry) = inner.entries.get_mut(index) { - let Some(entry) = entry.as_mut() else { - // The dict was changed since we did lookup. Let's try again. - // this is very rare to happen - // (and seems only happen with very high freq gc, and about one time in 10000 iters) - // but still possible - continue; - }; - #[expect( - clippy::redundant_else, - reason = "Keeping the empty `else` block here for documentation" - )] - if entry.index == index_index { - let removed = core::mem::replace(&mut entry.value, value); - // defer dec RC - break (index, Some(removed)); - } else { - // stuff shifted around, let's try again - } - } else { - // The dict was changed since we did lookup. Let's try again. - } - } else { - // New key - validate slot is still what lookup found - if inner.indices.get(index_index) != Some(&entry_index) { - // Dict was resized since lookup, retry - continue; + let mut value = Some(value); + let (stored_index, _removed) = self.with_slot_mut_prepared( + vm, + key, + hash, + Some(|| key.to_pyobject(vm)), + |inner, (entry_index, index_index), prepared| { + if let Some(index) = entry_index.index() { + let entry = inner.entries[index].as_mut().unwrap(); + let removed = core::mem::replace(&mut entry.value, value.take().unwrap()); + return (index, Some(removed)); } + let key = prepared.take().unwrap(); self.invalidate_keys_version(); let stored = inner.unchecked_push( index_index, hash, - key.to_pyobject(vm), - value, + key, + value.take().unwrap(), entry_index, ); - break (stored, None); - } - }; + (stored, None) + }, + )?; Ok(stored_index) } + /// [`Self::insert`] for membership. Same hash contract. pub(crate) fn contains( &self, vm: &VirtualMachine, key: &K, - ) -> PyResult { - let key_hash = key.key_hash(vm)?; - self.contains_known_hash(vm, key, key_hash) - } - - /// [`Self::contains`] with a known hash. Same contract as - /// [`Self::insert_known_hash`]. - pub(crate) fn contains_known_hash( - &self, - vm: &VirtualMachine, - key: &K, hash: HashValue, ) -> PyResult { let (entry, _) = self.lookup(vm, key, hash, None)?; Ok(entry.index().is_some()) } - /// Retrieve a key + /// Retrieve a key. Same hash contract as [`Self::insert`]. #[cfg_attr(feature = "flame-it", flame("Dict"))] pub(crate) fn get( &self, vm: &VirtualMachine, key: &K, - ) -> PyResult> { - let hash = key.key_hash(vm)?; - self._get_inner(vm, key, hash) - } - - /// `_PyDict_GetItem_KnownHash`: lookup using a caller-supplied hash. - pub(crate) fn get_known_hash( - &self, - vm: &VirtualMachine, - key: &K, hash: HashValue, ) -> PyResult> { self._get_inner(vm, key, hash) @@ -719,8 +684,8 @@ impl Dict { &self, vm: &VirtualMachine, key: &K, + hash: HashValue, ) -> PyResult> { - let hash = key.key_hash(vm)?; let (entry, _) = self.lookup(vm, key, hash, None)?; let Some(index) = entry.index() else { return Ok(None); @@ -736,22 +701,12 @@ impl Dict { &self, vm: &VirtualMachine, key: &K, + hash: HashValue, ) -> PyResult)>> { - let hash = key.key_hash(vm)?; - let ret = loop { - let (entry, index_index) = self.lookup(vm, key, hash, None)?; - if let Some(index) = entry.index() { - let inner = self.read(); - if let Some(entry) = inner.get_entry_checked(index, index_index) { - // The dict was not changed since we did lookup - break Some((entry.value.clone(), u16::try_from(index).ok())); - } - // The dict was changed since we did lookup. Let's try again. - } else { - break None; - } - }; - Ok(ret) + let ((entry, _), value) = + self.lookup_extract(vm, key, hash, None, |entry| entry.value.clone())?; + let hint = entry.index().and_then(|index| u16::try_from(index).ok()); + Ok(value.map(|value| (value, hint))) } /// Replace the value at entry index `hint` if that entry's key is @@ -763,6 +718,7 @@ impl Dict { &self, vm: &VirtualMachine, key: &K, + hash: HashValue, hint: usize, value: T, ) -> PyResult> { @@ -770,45 +726,25 @@ impl Dict { let mut inner = self.write(); match inner.entries.get_mut(hint) { Some(Some(entry)) if key.key_is(&entry.key) => { - let removed = core::mem::replace(&mut entry.value, value); + let _removed = core::mem::replace(&mut entry.value, value); drop(inner); // defer dec RC until after the lock is released - drop(removed); return Ok(None); } _ => value, } }; - let hash = key.key_hash(vm)?; - let stored = self.insert_known_hash_indexed(vm, key, hash, value)?; + let stored = self.insert_indexed(vm, key, hash, value)?; Ok(u16::try_from(stored).ok()) } /// Fast path lookup using a cached entry index (`hint`). /// - /// Returns `None` if the hint is stale or the key no longer matches. - pub(crate) fn get_hint( - &self, - vm: &VirtualMachine, - key: &K, - hint: usize, - ) -> PyResult> { - let (entry_key, entry_value) = { - let inner = self.read(); - let Some(Some(entry)) = inner.entries.get(hint) else { - return Ok(None); - }; - if key.key_is(&entry.key) { - return Ok(Some(entry.value.clone())); - } - (entry.key.clone(), entry.value.clone()) - }; - // key_eq may run Python __eq__, so must be outside the lock. - if key.key_eq(vm, &entry_key)? { - Ok(Some(entry_value)) - } else { - Ok(None) - } + /// Returns `None` if the hint is stale or its key is not identical to `key`. + pub(crate) fn get_hint(&self, key: &K, hint: usize) -> Option { + let inner = self.read(); + let entry = inner.entries.get(hint)?.as_ref()?; + key.key_is(&entry.key).then(|| entry.value.clone()) } /// Read an entry directly when a cached keys-version still describes the @@ -860,8 +796,8 @@ impl Dict { other: &Self, vm: &VirtualMachine, key: &K, + hash: HashValue, ) -> PyResult> { - let hash = key.key_hash(vm)?; if let Some(x) = self._get_inner(vm, key, hash)? { Ok(Some(x)) } else { @@ -884,36 +820,29 @@ impl Dict { /// Install an owned table, releasing the old entries after unlocking. pub(crate) fn replace_contents(&self, other: Self) { - let replacement = other.inner.into_inner(); + let mut replacement = other.inner.into_inner(); let _removed = { let mut inner = self.write(); self.invalidate_keys_version(); + // Relocation history belongs to this dict, not the incoming table. + replacement.relocation_epoch = inner.relocation_epoch; core::mem::replace(&mut *inner, replacement) }; } - /// Delete a key - pub(crate) fn delete(&self, vm: &VirtualMachine, key: &K) -> PyResult<()> + /// Delete a key. Same hash contract as [`Self::insert`]. + pub(crate) fn delete(&self, vm: &VirtualMachine, key: &K, hash: HashValue) -> PyResult<()> where K: DictKey + ?Sized, { - if self.remove_if_exists(vm, key)?.is_some() { + if self.remove_if_exists(vm, key, hash)?.is_some() { Ok(()) } else { Err(vm.new_key_error(key.to_pyobject(vm))) } } - pub(crate) fn delete_if_exists(&self, vm: &VirtualMachine, key: &K) -> PyResult - where - K: DictKey + ?Sized, - { - self.remove_if_exists(vm, key).map(|opt| opt.is_some()) - } - - /// [`Self::delete_if_exists`] with a known hash. Same contract as - /// [`Self::insert_known_hash`]. - pub(crate) fn delete_if_exists_known_hash( + pub(crate) fn delete_if_exists( &self, vm: &VirtualMachine, key: &K, @@ -922,44 +851,39 @@ impl Dict { where K: DictKey + ?Sized, { - self.remove_if_known_hash(vm, key, hash, |_| Ok(true)) + self.remove_if_exists(vm, key, hash) .map(|opt| opt.is_some()) } - pub(crate) fn delete_if(&self, vm: &VirtualMachine, key: &K, pred: F) -> PyResult + pub(crate) fn delete_if( + &self, + vm: &VirtualMachine, + key: &K, + hash: HashValue, + pred: F, + ) -> PyResult where K: DictKey + ?Sized, F: Fn(&T) -> PyResult, { - self.remove_if(vm, key, pred).map(|opt| opt.is_some()) + self.remove_if(vm, key, hash, pred).map(|opt| opt.is_some()) } - pub(crate) fn remove_if_exists(&self, vm: &VirtualMachine, key: &K) -> PyResult> - where - K: DictKey + ?Sized, - { - self.remove_if(vm, key, |_| Ok(true)) - } - - /// pred should be VERY CAREFUL about what it does as it is called while - /// the dict's internal mutex is held - pub(crate) fn remove_if( + pub(crate) fn remove_if_exists( &self, vm: &VirtualMachine, key: &K, - pred: F, + hash: HashValue, ) -> PyResult> where K: DictKey + ?Sized, - F: Fn(&T) -> PyResult, { - let hash = key.key_hash(vm)?; - self.remove_if_known_hash(vm, key, hash, pred) + self.remove_if(vm, key, hash, |_| Ok(true)) } - /// [`Self::remove_if`] with a known hash. Same contract as - /// [`Self::insert_known_hash`]. - fn remove_if_known_hash( + /// pred should be VERY CAREFUL about what it does as it is called while + /// the dict's internal mutex is held. Same hash contract as [`Self::insert`]. + pub(crate) fn remove_if( &self, vm: &VirtualMachine, key: &K, @@ -980,106 +904,79 @@ impl Dict { Ok(removed.map(|entry| entry.value)) } - /// Delete an existing key or insert a missing key using its known hash. - /// Same contract as [`Self::insert_known_hash`]. - pub(crate) fn delete_or_insert_known_hash( + /// Delete an existing key or insert a missing key. Same hash contract as + /// [`Self::insert`]. + pub(crate) fn delete_or_insert( &self, vm: &VirtualMachine, key: &PyObject, hash: HashValue, value: T, ) -> PyResult<()> { - let _removed = loop { - let lookup = self.lookup(vm, key, hash, None)?; - let (entry, index_index) = lookup; - if entry.index().is_some() { - match self.pop_inner(lookup) { - ControlFlow::Break(Some(entry)) => break Some(entry), - _ => continue, - } - } - - let mut inner = self.write(); - if inner.indices.get(index_index) != Some(&entry) { - continue; - } + // Set symmetric difference performs a discard followed by an add. + // The second lookup is observable through equality callbacks. + let removed = self.with_slot_mut(vm, key, hash, |inner, (entry, index_index)| { + let index = entry.index()?; self.invalidate_keys_version(); - inner.unchecked_push(index_index, hash, key.to_owned(), value, entry); - break None; - }; + inner.indices[index_index] = IndexEntry::DUMMY; + inner.used -= 1; + inner.entries[index].take() + })?; + if removed.is_none() { + self.insert(vm, key, hash, value)?; + } Ok(()) } - pub(crate) fn setdefault(&self, vm: &VirtualMachine, key: &K, default: F) -> PyResult + /// Get the value for `key`, inserting `default()` if it is absent. + /// Same hash contract as [`Self::insert`]. + pub(crate) fn setdefault( + &self, + vm: &VirtualMachine, + key: &K, + hash: HashValue, + default: F, + ) -> PyResult where K: DictKey + ?Sized, F: FnOnce() -> T, { - let hash = key.key_hash(vm)?; - let mut default = Some(default); - loop { - let (index_entry, index_index) = self.lookup(vm, key, hash, None)?; - if let Some(index) = index_entry.index() { - let inner = self.read(); - if let Some(entry) = inner.get_entry_checked(index, index_index) { - return Ok(entry.value.clone()); - } - continue; - } - let mut inner = self.write(); - if inner.indices.get(index_index) != Some(&index_entry) { - continue; - } - let value = default - .take() - .expect("default must only be computed on insertion")(); - self.invalidate_keys_version(); - inner.unchecked_push( - index_index, - hash, - key.to_pyobject(vm), - value.clone(), - index_entry, - ); - return Ok(value); - } + self.setdefault_entry(vm, key, hash, default) + .map(|(_, value)| value) } - #[allow(dead_code)] pub(crate) fn setdefault_entry( &self, vm: &VirtualMachine, key: &K, + hash: HashValue, default: F, ) -> PyResult<(PyObjectRef, T)> where K: DictKey + ?Sized, F: FnOnce() -> T, { - let hash = key.key_hash(vm)?; - let mut default = Some(default); - loop { - let (index_entry, index_index) = self.lookup(vm, key, hash, None)?; - if let Some(index) = index_entry.index() { - let inner = self.read(); - if let Some(entry) = inner.get_entry_checked(index, index_index) { - return Ok((entry.key.clone(), entry.value.clone())); + self.with_slot_mut_prepared( + vm, + key, + hash, + Some(|| { + // Preserve lazy factory-before-key ordering, outside the guard. + let value = default(); + (key.to_pyobject(vm), value) + }), + |inner, (index_entry, index_index), prepared| { + if let Some(index) = index_entry.index() { + let entry = inner.entries[index].as_ref().unwrap(); + return (entry.key.clone(), entry.value.clone()); } - continue; - } - let mut inner = self.write(); - if inner.indices.get(index_index) != Some(&index_entry) { - continue; - } - let value = default - .take() - .expect("default must only be computed on insertion")(); - let key_obj = key.to_pyobject(vm); - let ret = (key_obj.clone(), value.clone()); - self.invalidate_keys_version(); - inner.unchecked_push(index_index, hash, key_obj, value, index_entry); - return Ok(ret); - } + let (key, value) = prepared.take().unwrap(); + let ret = (key.clone(), value.clone()); + self.invalidate_keys_version(); + inner.unchecked_push(index_index, hash, key, value, index_entry); + ret + }, + ) } pub(crate) fn len(&self) -> usize { @@ -1097,13 +994,39 @@ impl Dict { /// another dict lock; it is there so an iterator clones only the field it /// keeps rather than both the key and the value. pub(crate) fn next_entry_checked( + &self, + position: EntryIndex, + old: &DictSize, + project: impl FnOnce(&PyObject, &T) -> R, + ) -> Result, DictChanged> { + self.next_entry_checked_by(position, old, PartialEq::eq, project) + } + + /// Dictionary iterators allow ordinary same-used key replacement, while + /// set iterators retain the stricter layout check above. + pub(crate) fn next_dict_entry_checked( + &self, + position: EntryIndex, + old: &DictSize, + project: impl FnOnce(&PyObject, &T) -> R, + ) -> Result, DictChanged> { + self.next_entry_checked_by( + position, + old, + DictSize::has_same_used_and_relocations, + project, + ) + } + + fn next_entry_checked_by( &self, mut position: EntryIndex, old: &DictSize, + unchanged: impl FnOnce(&DictSize, &DictSize) -> bool, project: impl FnOnce(&PyObject, &T) -> R, ) -> Result, DictChanged> { let inner = self.read(); - if inner.size() != *old { + if !unchanged(&inner.size(), old) { return Err(DictChanged); } loop { @@ -1117,7 +1040,8 @@ impl Dict { } } - /// [`Self::next_entry_checked`] in reverse. + /// Step backward, validating the live size and private relocation history + /// under the same read guard. Ordinary same-size mutations may change layout. pub(crate) fn prev_entry_checked( &self, mut position: EntryIndex, @@ -1125,7 +1049,7 @@ impl Dict { project: impl FnOnce(&PyObject, &T) -> R, ) -> Result, DictChanged> { let inner = self.read(); - if inner.size() != *old { + if !inner.size().has_same_used_and_relocations(old) { return Err(DictChanged); } loop { @@ -1161,27 +1085,18 @@ impl Dict { } } - pub(crate) fn prev_entry(&self, mut position: EntryIndex) -> Option<(usize, PyObjectRef, T)> { - let inner = self.read(); - loop { - let entry = inner.entries.get(position)?; - if let Some(entry) = entry { - break Some((position, entry.key.clone(), entry.value.clone())); - } - if position == 0 { - break None; - } - position -= 1; - } - } - pub(crate) fn len_from_entry_index(&self, position: EntryIndex) -> usize { self.read().entries.len().saturating_sub(position) } - pub(crate) fn has_changed_size(&self, old: &DictSize) -> bool { - let current = self.read().size(); - current != *old + /// Inspect keys without allocating or cloning their references. + /// The predicate must not run Python or mutate this table. + pub(crate) fn any_key(&self, mut predicate: impl FnMut(&PyObject) -> bool) -> bool { + self.read() + .entries + .iter() + .flatten() + .any(|entry| predicate(&entry.key)) } pub(crate) fn keys(&self) -> Vec { @@ -1193,7 +1108,7 @@ impl Dict { } /// All keys paired with the hash stored in their entry, for feeding - /// [`Self::insert_known_hash`] without re-calling `__hash__`. + /// [`Self::insert`] without re-calling `__hash__`. pub(crate) fn keys_with_hashes(&self) -> Vec<(PyObjectRef, HashValue)> { self.read() .entries @@ -1218,12 +1133,24 @@ impl Dict { .collect() } - /// Fold stored hashes under the read lock; the callback must not run Python. - pub(crate) fn fold_hashes(&self, init: Acc, f: Fold) -> Acc + pub(crate) fn items_with_hashes(&self) -> Vec<(PyObjectRef, T, HashValue)> { + self.read() + .entries + .iter() + .filter_map(|v| v.as_ref().map(|v| (v.key.clone(), v.value.clone(), v.hash))) + .collect() + } + + /// Fold the length and stored hashes under one read lock; neither callback + /// may run Python or release owned Python references. + pub(crate) fn fold_hashes(&self, init: Init, f: Fold) -> Acc where + Init: FnOnce(usize) -> Acc, Fold: FnMut(Acc, HashValue) -> Acc, { - self.read() + let inner = self.read(); + let init = init(inner.used); + inner .entries .iter() .filter_map(|v| v.as_ref().map(|v| v.hash)) @@ -1243,30 +1170,29 @@ impl Dict { Ok(ret) } - /// [`Self::lookup`], additionally reading the matched entry when the probe - /// settles it by key identity. + /// [`Self::lookup`], additionally reading the matched entry under the + /// probe's guard, after any equality callback has been revalidated. /// - /// That is the common case, and it is decided while the read guard is still - /// held — so a caller that only wants the entry's value gets it here instead - /// of taking the lock a second time to re-find what the probe already had. + /// Key identity is the common case and is decided while the read guard is + /// still held. After equality, the current entry is read under the guard + /// that revalidated it, without a second lookup by stale coordinates. /// `extract` therefore runs under the guard and must not run Python. It is - /// not called when the key had to be compared with `key_eq`, which does run - /// Python and so releases the guard first. + /// called only after reacquiring the guard when `key_eq` runs Python. #[cfg_attr(feature = "flame-it", flame("Dict"))] - fn lookup_extract( - &self, + fn lookup_extract<'a, K: DictKey + ?Sized, R>( + &'a self, vm: &VirtualMachine, key: &K, hash_value: HashValue, - mut lock: Option>>, + mut lock: Option>>, extract: impl Fn(&DictEntry) -> R, ) -> PyResult<(LookupResult, Option)> { let mut idxs = None; let mut free_slot = None; - let ret = 'outer: loop { - let (entry_key, ret) = { + loop { + let (entry_key, ret, indices_ptr, indices_len) = { let inner = lock.take().unwrap_or_else(|| self.read()); - let mask = (inner.indices.len() - 1) as i64; + let mask = (inner.indices.len() - 1) as HashIndex; let idxs = idxs.get_or_insert_with(|| GenIndexes::new(hash_value, mask)); if idxs.mask != mask { // Dict was resized since last probe, restart @@ -1308,7 +1234,12 @@ impl Dict { if key.key_is(&entry.key) { return Ok((ret, Some(extract(entry)))); } else if entry.hash == hash_value { - break (entry.key.clone(), ret); + break ( + entry.key.clone(), + ret, + inner.indices.as_ptr(), + inner.indices.len(), + ); } else { // entry mismatch } @@ -1318,20 +1249,35 @@ impl Dict { } }; - #[expect( - clippy::redundant_else, - reason = "Keeping the empty `else` block here for documentation" - )] - // This comparison needs to be done outside the lock. - if key.key_eq(vm, &entry_key)? { - break 'outer ret; - } else { - // hash collision + // Equality and releasing its temporary key can both run Python. + // Drop the owner before checking the table, without holding a lock. + let entry_key_id = entry_key.get_id(); + let equal = key.key_eq(vm, &entry_key); + drop(entry_key); + let equal = equal?; + let inner = self.read(); + let entry = inner + .get_entry_checked(ret.0.index().unwrap(), ret.1) + .filter(|entry| { + inner.indices.as_ptr() == indices_ptr + && inner.indices.len() == indices_len + && inner.indices.get(ret.1) == Some(&ret.0) + && entry.hash == hash_value + && entry.key.get_id() == entry_key_id + }); + let Some(entry) = entry else { + // A callback may recycle the same entry and bucket for a + // different key, or rebuild the table around the same key. + idxs = None; + free_slot = None; + continue; + }; + if equal { + return Ok((ret, Some(extract(entry)))); } - - // warn!("Perturb value: {}", i); - }; - Ok((ret, None)) + // Hash collision: continue probing the unchanged table. + lock = Some(inner); + } } // returns Err(()) if changed since lookup @@ -1375,13 +1321,13 @@ impl Dict { Ok(ControlFlow::Break(removed)) } - /// Retrieve and delete a key + /// Retrieve and delete a key. Same hash contract as [`Self::insert`]. pub(crate) fn pop( &self, vm: &VirtualMachine, key: &K, + hash_value: HashValue, ) -> PyResult> { - let hash_value = key.key_hash(vm)?; let removed = loop { let lookup = self.lookup(vm, key, hash_value, None)?; match self.pop_inner(lookup) { @@ -1392,6 +1338,293 @@ impl Dict { Ok(removed) } + // Locate an entry and mutate it under one guard. The operation must not + // run Python or drop owned Python references while the guard is held. + fn with_entry_mut( + &self, + vm: &VirtualMachine, + key: &K, + hash_value: HashValue, + update: impl FnOnce(&mut DictInner, EntryIndex) -> R, + ) -> PyResult> { + let mut update = Some(update); + self.with_slot_mut(vm, key, hash_value, |inner, (entry, _)| { + entry + .index() + .map(|index| update.take().unwrap()(inner, index)) + }) + } + + // Probe and commit under one guard, including when the key is absent. + // The callback must not run Python, allocate Python objects, or drop owned + // Python references (including unused captures) while the guard is held. + fn with_slot_mut( + &self, + vm: &VirtualMachine, + key: &K, + hash_value: HashValue, + update: impl FnOnce(&mut DictInner, LookupResult) -> R, + ) -> PyResult { + self.with_slot_mut_prepared(vm, key, hash_value, None:: ()>, |inner, slot, _| { + update(inner, slot) + }) + } + + // Preparation may run Python, but only after absence was established and + // the guard released. Retain that probe's witnesses so an unchanged route + // does not repeat equality. Unused preparation/captures stay outside guards. + fn with_slot_mut_prepared P, R>( + &self, + vm: &VirtualMachine, + key: &K, + hash_value: HashValue, + mut prepare: Option, + update: impl FnOnce(&mut DictInner, LookupResult, &mut Option

) -> R, + ) -> PyResult { + struct ProbeWitness { + index_index: IndexIndex, + entry_index: IndexEntry, + key: Option<(HashValue, PyObjectRef)>, + } + + impl ProbeWitness { + fn matches(&self, inner: &DictInner) -> bool { + inner.indices.get(self.index_index) == Some(&self.entry_index) + && self.key.as_ref().is_none_or(|(hash, key)| { + inner + .get_entry_checked(self.entry_index.index().unwrap(), self.index_index) + .is_some_and(|entry| entry.hash == *hash && entry.key.is(key)) + }) + } + } + + let mut prepared = None; + let mut pending_vacancy: Option<(LookupResult, IndexIndex)> = None; + let mut idxs = None; + let mut free_slot = None; + let mut prefix = Vec::::new(); + let mut compared: Option<(EntryIndex, IndexIndex, PyObjectRef, bool)> = None; + let mut initial_guard = Some(self.write()); + { + let inner = initial_guard.as_mut().unwrap(); + let mut probes = GenIndexes::new(hash_value, (inner.indices.len() - 1) as HashIndex); + // An identity-only update cannot run Python or invalidate a probe. + // Avoid allocating witnesses for unrelated bucket collisions. Once + // equality or key preparation may run Python, use the full path + // below, retaining the guard while restarting the probe. + loop { + let index_index = probes.next(); + let index_entry = inner.indices[index_index]; + match index_entry { + IndexEntry::FREE => break, + IndexEntry::DUMMY => continue, + _ => {} + } + let entry = inner.entries[index_entry.index().unwrap()] + .as_ref() + .unwrap(); + if key.key_is(&entry.key) { + return Ok(update(inner, (index_entry, index_index), &mut prepared)); + } + if entry.hash == hash_value { + break; + } + } + } + 'lookup: loop { + // Keep the compared key alive until after the guard is released, + // including when equality cleared the dictionary and recycled its + // entry and bucket for a different key. + let comparison = compared.take(); + let mut inner = initial_guard.take().unwrap_or_else(|| self.write()); + let mask = (inner.indices.len() - 1) as HashIndex; + let probes = idxs.get_or_insert_with(|| GenIndexes::new(hash_value, mask)); + if probes.mask != mask { + drop(inner); + prefix.clear(); + idxs = None; + free_slot = None; + pending_vacancy = None; + continue; + } + if let Some((slot, terminal_free)) = pending_vacancy.take() { + // The terminal FREE matters even when insertion chose an earlier + // DUMMY. Every preceding occupied/DUMMY bucket is witnessed. + if inner.indices.get(terminal_free) == Some(&IndexEntry::FREE) + && prefix.iter().all(|witness| witness.matches(&inner)) + { + let result = update(&mut inner, slot, &mut prepared); + return Ok(result); + } + drop(inner); + prefix.clear(); + idxs = None; + free_slot = None; + continue; + } + let matched = if let Some((entry_index, index_index, candidate, equal)) = &comparison { + let valid = inner.indices.get(*index_index).and_then(|i| i.index()) + == Some(*entry_index) + && inner + .get_entry_checked(*entry_index, *index_index) + .is_some_and(|entry| entry.hash == hash_value && entry.key.is(candidate)); + // A false comparison can survive while another previously + // probed bucket changes (including after nested compaction). + // Revalidate the whole prefix before continuing past it. + let prefix_valid = *equal || prefix.iter().all(|witness| witness.matches(&inner)); + if !valid || !prefix_valid { + drop(inner); + prefix.clear(); + idxs = None; + free_slot = None; + continue; + } + equal.then_some((inner.indices[*index_index], *index_index)) + } else { + None + }; + let mut terminal_free = None; + let slot = match matched { + Some(slot) => slot, + None => loop { + let index_index = probes.next(); + let index_entry = inner.indices[index_index]; + match index_entry { + IndexEntry::FREE => { + terminal_free = Some(index_index); + break free_slot.map_or((IndexEntry::FREE, index_index), |index| { + (IndexEntry::DUMMY, index) + }); + } + IndexEntry::DUMMY => { + if free_slot.is_none() { + free_slot = Some(index_index); + } + prefix.push(ProbeWitness { + index_index, + entry_index: index_entry, + key: None, + }); + continue; + } + _ => {} + } + let entry_index = index_entry.index().unwrap(); + let entry = inner.entries[entry_index].as_ref().unwrap(); + if key.key_is(&entry.key) { + break (index_entry, index_index); + } + prefix.push(ProbeWitness { + index_index, + entry_index: index_entry, + key: Some((entry.hash, entry.key.clone())), + }); + if entry.hash == hash_value { + let candidate = entry.key.clone(); + drop(inner); + drop(comparison); + let equal = key.key_eq(vm, &candidate)?; + compared = Some((entry_index, index_index, candidate, equal)); + continue 'lookup; + } + }, + }; + if slot.0.index().is_none() && prepare.is_some() { + pending_vacancy = Some((slot, terminal_free.unwrap())); + drop(inner); + drop(comparison); + prepared = Some(prepare.take().unwrap()()); + continue; + } + let result = update(&mut inner, slot, &mut prepared); + return Ok(result); + } + } + + /// Retrieve a value while revalidating keys after equality callbacks. + /// Unlike a raw lookup result, the returned value cannot refer to a slot + /// cleared and recycled by reentrant Python code. + pub(crate) fn get_reentrant( + &self, + vm: &VirtualMachine, + key: &K, + hash: HashValue, + ) -> PyResult> { + self.with_entry_mut(vm, key, hash, |inner, index| { + inner.entries[index].as_ref().unwrap().value.clone() + }) + } + + /// Remove a verified entry, releasing its key after the table lock is gone. + pub(crate) fn pop_reentrant( + &self, + vm: &VirtualMachine, + key: &K, + hash: HashValue, + ) -> PyResult> { + let removed = self.with_entry_mut(vm, key, hash, |inner, index| { + self.invalidate_keys_version(); + let entry = inner.entries[index].take().unwrap(); + inner.indices[entry.index] = IndexEntry::DUMMY; + inner.used -= 1; + entry + })?; + Ok(removed.map(|entry| entry.value)) + } + + /// Move an existing entry to the end and return its current value without + /// making the key temporarily absent. Equality runs unlocked. + pub(crate) fn move_to_end( + &self, + vm: &VirtualMachine, + key: &K, + hash: HashValue, + ) -> PyResult> { + self.with_entry_mut(vm, key, hash, |inner, entry_index| { + let value = inner.entries[entry_index].as_ref().unwrap().value.clone(); + if inner.entries[entry_index + 1..].iter().any(Option::is_some) { + // Reserve before taking the entry. No reader can observe an + // absent entry, and no hashing, equality or finalizer runs in + // this critical section. + inner.entries.reserve(1); + self.invalidate_keys_version(); + inner.relocation_epoch = inner.relocation_epoch.wrapping_add(1); + let entry = inner.entries[entry_index].take().unwrap(); + let new_index = inner.entries.len(); + inner.indices[entry.index] = unsafe { + // SAFETY: new_index is a valid nonnegative entry index. + IndexEntry::from_index_unchecked(new_index) + }; + inner.entries.push(Some(entry)); + let holes = inner.entries.len() - inner.used; + if holes >= 2 && holes >= inner.used { + // Moves do not increase `filled`, so ordinary insertion's + // resize threshold cannot bound their accumulated holes. + let indices_size = inner.indices.len(); + inner.resize(indices_size); + } + } + value + }) + } + + // Replace only a still-matching value. The predicate must not run Python. + // Keep both the replacement and removed value alive outside the guard. + pub(crate) fn replace_if( + &self, + vm: &VirtualMachine, + key: &K, + hash: HashValue, + replacement: T, + matches: impl FnOnce(&T) -> bool, + ) -> PyResult { + let removed = self.with_entry_mut(vm, key, hash, |inner, index| { + let entry = inner.entries[index].as_mut().unwrap(); + matches(&entry.value).then(|| core::mem::replace(&mut entry.value, replacement.clone())) + })?; + Ok(removed.flatten().is_some()) + } + pub(crate) fn pop_back(&self) -> Option<(PyObjectRef, T)> { let inner = &mut *self.write(); let entry = loop { @@ -1688,7 +1921,7 @@ impl DictKey for Wtf8 { #[inline] fn key_hash(&self, _vm: &VirtualMachine) -> PyResult { // follow a similar route as the hashing of PyStrRef - Ok(crate::vm::hash_secret().hash_bytes(self.as_bytes())) + Ok(crate::vm::hash_secret().hash_wtf8(self)) } #[inline(always)] @@ -1838,15 +2071,441 @@ mod tests { use super::*; use crate::{Interpreter, common::ascii}; + fn hash_key(vm: &VirtualMachine, key: &K) -> HashValue { + key.key_hash(vm).unwrap() + } + + #[test] + fn unicode_key_adapters_match_python_strings() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + for text in ["é", "∑", "𐀀"] { + let string = vm.ctx.new_str(text); + assert_eq!(hash_key(vm, text), string.hash(vm)); + assert_eq!(hash_key(vm, <&Wtf8>::from(text)), string.hash(vm)); + } + }); + } + + #[test] + fn minimum_hash_probing_terminates() { + let mut probes = GenIndexes::new(hash::PyHash::MIN, 7); + let mut seen = 0u8; + for _ in 0..usize::BITS + 8 { + seen |= 1 << probes.next(); + } + assert_eq!(seen, u8::MAX); + } + + fn assert_table_invariants(dict: &Dict) { + let inner = dict.read(); + assert_eq!(inner.entries.iter().flatten().count(), inner.used); + assert_eq!( + inner + .indices + .iter() + .filter(|index| index.index().is_some()) + .count(), + inner.used + ); + assert_eq!( + inner + .indices + .iter() + .filter(|index| **index != IndexEntry::FREE) + .count(), + inner.filled + ); + for (index, entry) in inner.entries.iter().enumerate() { + let Some(entry) = entry else { continue }; + assert_eq!(inner.indices[entry.index].index(), Some(index)); + let mut probes = GenIndexes::new(entry.hash, (inner.indices.len() - 1) as HashIndex); + let mut reached = false; + // After the finite perturb prefix, probing visits the entire table. + for _ in 0..inner.indices.len() + 64 { + let bucket = probes.next(); + assert_ne!(inner.indices[bucket], IndexEntry::FREE); + if bucket == entry.index { + reached = true; + break; + } + } + assert!(reached, "live entry must be reachable before a free bucket"); + } + for (bucket, index) in inner.indices.iter().enumerate() { + if let Some(index) = index.index() { + assert_eq!(inner.entries[index].as_ref().unwrap().index, bucket); + } + } + } + + #[test] + fn insertion_paths_preserve_table_invariants() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let dict = Dict::default(); + let initial_buckets = dict.read().indices.len(); + for key in 0..16usize { + dict.insert(vm, &key, hash_key(vm, &key), key).unwrap(); + assert_table_invariants(&dict); + } + assert!(dict.read().indices.len() > initial_buckets); + let key: PyObjectRef = vm.ctx.new_int(3).into(); + let hash = hash_key(vm, &3usize); + dict.delete_or_insert(vm, &key, hash, 30).unwrap(); + assert_table_invariants(&dict); + let filled = dict.read().filled; + dict.delete_or_insert(vm, &key, hash, 30).unwrap(); + assert_eq!(dict.read().filled, filled); + assert_table_invariants(&dict); + dict.insert(vm, &3usize, hash, 31).unwrap(); + assert_eq!(dict.get(vm, &3usize, hash).unwrap(), Some(31)); + assert_eq!(dict.setdefault(vm, &3usize, hash, || 32).unwrap(), 31); + let (_, value) = dict + .setdefault_entry(vm, &17usize, hash_key(vm, &17usize), || 17) + .unwrap(); + assert_eq!(value, 17); + assert_eq!(dict.len(), 17); + assert_table_invariants(&dict); + }); + } + + #[test] + fn identity_update_across_bucket_collisions() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let dict = Dict::default(); + let first: PyObjectRef = vm.ctx.new_int(0).into(); + let second: PyObjectRef = vm.ctx.new_int(8).into(); + let first_hash = hash_key(vm, &*first); + let second_hash = hash_key(vm, &*second); + let mask = dict.read().indices.len() - 1; + assert_ne!(first_hash, second_hash); + assert_eq!(first_hash as usize & mask, second_hash as usize & mask); + dict.insert(vm, &*first, first_hash, 1).unwrap(); + dict.insert(vm, &*second, second_hash, 2).unwrap(); + dict.insert(vm, &*second, second_hash, 3).unwrap(); + assert_eq!(dict.get(vm, &*second, second_hash).unwrap(), Some(3)); + assert_eq!(dict.len(), 2); + assert_table_invariants(&dict); + + dict.delete(vm, &*first, first_hash).unwrap(); + dict.insert(vm, &*second, second_hash, 4).unwrap(); + assert_eq!(dict.get(vm, &*second, second_hash).unwrap(), Some(4)); + assert_eq!(dict.len(), 1); + assert_table_invariants(&dict); + }); + } + + #[test] + fn insertion_reprobes_after_native_key_preparation() { + struct PreparingKey<'a> { + dict: &'a Dict, + conversions: core::cell::Cell, + } + impl DictKey for PreparingKey<'_> { + type Owned = usize; + fn _to_owned(&self, vm: &VirtualMachine) -> usize { + self.conversions.set(self.conversions.get() + 1); + assert_eq!(self.conversions.get(), 1); + for key in 0..16usize { + self.dict.insert(vm, &key, hash_key(vm, &key), key).unwrap(); + } + 64 + } + fn key_hash(&self, vm: &VirtualMachine) -> PyResult { + 64usize.key_hash(vm) + } + fn key_is(&self, _other: &PyObject) -> bool { + false + } + fn key_eq(&self, vm: &VirtualMachine, other: &PyObject) -> PyResult { + 64usize.key_eq(vm, other) + } + fn key_as_isize(&self, _vm: &VirtualMachine) -> PyResult { + Ok(64) + } + } + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let dict = Dict::default(); + let initial_buckets = dict.read().indices.len(); + let key = PreparingKey { + dict: &dict, + conversions: core::cell::Cell::new(0), + }; + dict.insert(vm, &key, hash_key(vm, &key), 64).unwrap(); + assert_eq!(key.conversions.get(), 1); + assert!(dict.read().indices.len() > initial_buckets); + assert_eq!(dict.len(), 17); + assert_eq!( + dict.get(vm, &64usize, hash_key(vm, &64usize)).unwrap(), + Some(64) + ); + assert_table_invariants(&dict); + }); + } + + #[test] + fn setdefault_reprobes_after_native_factory_inserts_winner() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let dict = Dict::default(); + let calls = core::cell::Cell::new(0); + let hash = hash_key(vm, &64usize); + let (key, value) = dict + .setdefault_entry(vm, &64usize, hash, || { + calls.set(calls.get() + 1); + for key in 0..16usize { + dict.insert(vm, &key, hash_key(vm, &key), key).unwrap(); + } + dict.insert(vm, &64usize, hash, 77).unwrap(); + 99 + }) + .unwrap(); + assert_eq!(calls.get(), 1); + assert_eq!(value, 77); + assert!(64usize.key_eq(vm, &key).unwrap()); + assert_eq!(dict.get(vm, &64usize, hash).unwrap(), Some(77)); + assert_eq!(dict.len(), 17); + assert_table_invariants(&dict); + }); + } + + #[test] + fn insertion_preparation_keeps_unchanged_comparison() { + struct CountedKey { + key: PyObjectRef, + comparisons: core::cell::Cell, + preparations: core::cell::Cell, + } + impl DictKey for CountedKey { + type Owned = PyObjectRef; + fn _to_owned(&self, _vm: &VirtualMachine) -> PyObjectRef { + self.preparations.set(self.preparations.get() + 1); + self.key.clone() + } + fn key_hash(&self, vm: &VirtualMachine) -> PyResult { + self.key.key_hash(vm) + } + fn key_is(&self, other: &PyObject) -> bool { + self.key.is(other) + } + fn key_eq(&self, vm: &VirtualMachine, other: &PyObject) -> PyResult { + self.comparisons.set(self.comparisons.get() + 1); + self.key.key_eq(vm, other) + } + fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult { + self.key.key_as_isize(vm) + } + } + Interpreter::without_stdlib(Default::default()).enter(|vm| { + // Exact native integers with equal hashes, without Python callbacks. + for use_default in [false, true] { + let dict = Dict::default(); + let first: PyObjectRef = vm.ctx.new_int(0).into(); + let key = CountedKey { + key: vm.ctx.new_int(hash::MODULUS).into(), + comparisons: core::cell::Cell::new(0), + preparations: core::cell::Cell::new(0), + }; + let hash = hash_key(vm, &key); + assert_eq!(hash_key(vm, &*first), hash); + dict.insert(vm, &*first, hash, 1).unwrap(); + if use_default { + assert_eq!(dict.setdefault(vm, &key, hash, || 2).unwrap(), 2); + } else { + dict.insert(vm, &key, hash, 2).unwrap(); + } + assert_eq!(key.comparisons.get(), 1); + assert_eq!(key.preparations.get(), 1); + assert_eq!(dict.len(), 2); + assert_table_invariants(&dict); + } + }); + } + + #[test] + fn insertion_preparation_revalidates_same_size_vacancy() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let dict = Dict::default(); + let initial_buckets = dict.read().indices.len(); + let hash = hash_key(vm, &8usize); + let calls = core::cell::Cell::new(0); + // A winner occupies the saved terminal FREE without resizing. + assert_eq!( + dict.setdefault(vm, &8usize, hash, || { + calls.set(calls.get() + 1); + dict.insert(vm, &8usize, hash, 77).unwrap(); + 99 + }) + .unwrap(), + 77 + ); + assert_eq!(calls.get(), 1); + assert_eq!(dict.len(), 1); + assert_eq!(dict.read().indices.len(), initial_buckets); + assert_table_invariants(&dict); + + let dict = Dict::default(); + dict.insert(vm, &0usize, hash_key(vm, &0usize), 0).unwrap(); + dict.delete(vm, &0usize, hash_key(vm, &0usize)).unwrap(); + assert_eq!(dict.read().indices[0], IndexEntry::DUMMY); + // Preparation consumes the saved first DUMMY, but not the terminal + // FREE at bucket 1. Both keys must survive the resulting re-probe. + assert_eq!( + dict.setdefault(vm, &8usize, hash, || { + dict.insert(vm, &16usize, hash_key(vm, &16usize), 16) + .unwrap(); + 8 + }) + .unwrap(), + 8 + ); + assert_eq!(dict.read().indices.len(), initial_buckets); + assert_eq!( + dict.get(vm, &16usize, hash_key(vm, &16usize)).unwrap(), + Some(16) + ); + assert_eq!(dict.get(vm, &8usize, hash).unwrap(), Some(8)); + assert_eq!(dict.len(), 2); + assert_table_invariants(&dict); + }); + } + + #[test] + fn move_to_end_preserves_values_and_invalidates_layout() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let dict = Dict::default(); + let keys = [ + vm.ctx.intern_str("first"), + vm.ctx.intern_str("middle"), + vm.ctx.intern_str("last"), + ]; + for (value, key) in keys.iter().enumerate() { + dict.insert(vm, *key, hash_key(vm, *key), value).unwrap(); + } + let hint = dict + .hint_for_key(vm, keys[1], hash_key(vm, keys[1])) + .unwrap() + .unwrap() as usize; + let version = dict.assign_keys_version(); + let size = dict.size(); + assert_ne!(version, 0); + assert_eq!( + dict.move_to_end(vm, keys[1], hash_key(vm, keys[1])) + .unwrap(), + Some(1) + ); + assert_eq!(dict.values(), vec![0, 2, 1]); + assert_eq!(dict.keys_version(), 0); + assert_eq!(dict.get_index_if_keys_version(version, hint), None); + assert_eq!(dict.get_hint(keys[1], hint), None); + assert!(dict.next_entry_checked(0, &size, |_, v| *v).is_err()); + assert!( + dict.prev_entry_checked(size.entries_size - 1, &size, |_, v| *v) + .is_err() + ); + + let version = dict.assign_keys_version(); + let size = dict.size(); + assert_eq!( + dict.move_to_end(vm, keys[1], hash_key(vm, keys[1])) + .unwrap(), + Some(1) + ); + assert_eq!(dict.keys_version(), version); + assert_eq!(dict.size(), size); + assert_eq!( + dict.move_to_end(vm, "absent", hash_key(vm, "absent")) + .unwrap(), + None + ); + assert_eq!(dict.keys_version(), version); + assert_eq!(dict.size(), size); + assert_eq!(dict.values(), vec![0, 2, 1]); + }); + } + + #[test] + fn move_to_end_compacts_and_keeps_indices_consistent() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + for count in [2, 3, 32] { + let dict = Dict::default(); + for key in 0..count { + dict.insert(vm, &key, hash_key(vm, &key), key).unwrap(); + } + for step in 0..1024 { + let key = step % count; + let size = dict.size(); + let hint = dict + .hint_for_key(vm, &key, hash_key(vm, &key)) + .unwrap() + .unwrap() as usize; + let version = dict.assign_keys_version(); + assert_eq!( + dict.move_to_end(vm, &key, hash_key(vm, &key)).unwrap(), + Some(key) + ); + assert_eq!(dict.get_index_if_keys_version(version, hint), None); + assert!(dict.next_entry_checked(0, &size, |_, v| *v).is_err()); + assert!( + dict.prev_entry_checked(size.entries_size - 1, &size, |_, v| *v) + .is_err() + ); + let inner = dict.read(); + assert_eq!(inner.used, count); + assert_eq!(inner.filled, count); + assert!(inner.entries.len() < 2 * count); + assert!(inner.entries.capacity() <= 4 * count); + let values: Vec<_> = inner.entries.iter().flatten().map(|e| e.value).collect(); + assert_eq!( + values, + (1..=count).map(|i| (key + i) % count).collect::>() + ); + for (index, entry) in inner.entries.iter().enumerate() { + if let Some(entry) = entry { + assert_eq!(inner.indices[entry.index].index(), Some(index)); + assert_eq!(entry.hash, entry.value.key_hash(vm).unwrap()); + } + } + for (bucket, index) in inner.indices.iter().enumerate() { + if let Some(index) = index.index() { + assert_eq!(inner.entries[index].as_ref().unwrap().index, bucket); + } + } + } + } + }); + } + + #[test] + fn move_to_end_restores_only_matching_shared_shapes() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let first = vm.ctx.intern_str("move_first"); + let last = vm.ctx.intern_str("move_last"); + let dict = Dict::default(); + let peer = Dict::default(); + for table in [&dict, &peer] { + table.insert(vm, first, hash_key(vm, first), 1).unwrap(); + table.insert(vm, last, hash_key(vm, last), 2).unwrap(); + } + let version = dict.assign_keys_version(); + assert_eq!(peer.assign_keys_version(), version); + dict.move_to_end(vm, first, hash_key(vm, first)).unwrap(); + assert_ne!(dict.assign_keys_version(), version); + dict.move_to_end(vm, last, hash_key(vm, last)).unwrap(); + // The second move compacts back to the original hole-free layout. + assert_eq!(dict.assign_keys_version(), version); + assert_eq!(dict.get_index_if_keys_version(version, 0), Some(1)); + assert_eq!(dict.get_index_if_keys_version(version, 1), Some(2)); + }); + } + #[test] fn clone_compacts_deleted_entries() { Interpreter::without_stdlib(Default::default()).enter(|vm| { let dict = Dict::default(); for key in 0..128usize { - dict.insert(vm, &key, key).unwrap(); + dict.insert(vm, &key, hash_key(vm, &key), key).unwrap(); } for key in 0..120usize { - dict.delete(vm, &key).unwrap(); + dict.delete(vm, &key, hash_key(vm, &key)).unwrap(); } let version = dict.assign_keys_version(); let copied = dict.clone(); @@ -1863,10 +2522,12 @@ mod tests { } assert_eq!(copied.values(), (120..128).collect::>()); for key in 120..128usize { - assert_eq!(copied.get(vm, &key).unwrap(), Some(key)); + assert_eq!(copied.get(vm, &key, hash_key(vm, &key)).unwrap(), Some(key)); } - copied.insert(vm, &0usize, 0).unwrap(); - assert!(!dict.contains(vm, &0usize).unwrap()); + copied + .insert(vm, &0usize, hash_key(vm, &0usize), 0) + .unwrap(); + assert!(!dict.contains(vm, &0usize, hash_key(vm, &0usize)).unwrap()); }); } @@ -1875,7 +2536,7 @@ mod tests { Interpreter::without_stdlib(Default::default()).enter(|vm| { let dict = Dict::default(); for key in 0..128usize { - dict.insert(vm, &key, ()).unwrap(); + dict.insert(vm, &key, hash_key(vm, &key), ()).unwrap(); } for _ in 0..124 { dict.pop_back().unwrap(); @@ -1884,8 +2545,8 @@ mod tests { assert_eq!(copied.len(), 4); assert!(copied.read().indices.len() < dict.read().indices.len()); for key in 0..4usize { - assert!(copied.contains(vm, &key).unwrap()); - dict.delete(vm, &key).unwrap(); + assert!(copied.contains(vm, &key, hash_key(vm, &key)).unwrap()); + dict.delete(vm, &key, hash_key(vm, &key)).unwrap(); } let empty = dict.clone(); assert_eq!(dict.len(), 0); @@ -1905,10 +2566,14 @@ mod tests { let padding = vm.ctx.intern_str("padding"); let first: Dict = Dict::default(); let second: Dict = Dict::default(); - first.insert(vm, name, 10).unwrap(); - first.insert(vm, padding, 20).unwrap(); - second.insert(vm, padding, 30).unwrap(); - second.insert(vm, name, 40).unwrap(); + first.insert(vm, name, hash_key(vm, name), 10).unwrap(); + first + .insert(vm, padding, hash_key(vm, padding), 20) + .unwrap(); + second + .insert(vm, padding, hash_key(vm, padding), 30) + .unwrap(); + second.insert(vm, name, hash_key(vm, name), 40).unwrap(); let (first_version, first_index) = first.module_attr_cache(name, vm).unwrap(); let (second_version, second_index) = second.module_attr_cache(name, vm).unwrap(); assert_ne!(first_version, second_version); @@ -1933,21 +2598,35 @@ mod tests { ); let foreign_key: PyObjectRef = vm.ctx.new_int(7).into(); - first.insert(vm, &*foreign_key, 50).unwrap(); + first + .insert(vm, &*foreign_key, hash_key(vm, &*foreign_key), 50) + .unwrap(); assert!(first.module_attr_cache(name, vm).is_none()); assert_eq!( first.get_cached_module_attr(name, first_version as usize, first_index.into(), vm), None ); - first.delete(vm, &*foreign_key).unwrap(); first - .insert(vm, vm.ctx.intern_str("__getattr__"), 60) + .delete(vm, &*foreign_key, hash_key(vm, &*foreign_key)) + .unwrap(); + first + .insert( + vm, + vm.ctx.intern_str("__getattr__"), + hash_key(vm, vm.ctx.intern_str("__getattr__")), + 60, + ) .unwrap(); assert!(first.module_attr_cache(name, vm).is_none()); let noninterned: Dict = Dict::default(); noninterned - .insert(vm, &*vm.ctx.new_str("target"), 70) + .insert( + vm, + &*vm.ctx.new_str("target"), + hash_key(vm, &*vm.ctx.new_str("target")), + 70, + ) .unwrap(); let (version, index) = noninterned.module_attr_cache(name, vm).unwrap(); assert_eq!( @@ -1965,27 +2644,31 @@ mod tests { let key1 = vm.new_pyobj(true); let value1 = vm.new_pyobj(ascii!("abc")); - dict.insert(vm, &*key1, value1).unwrap(); + dict.insert(vm, &*key1, hash_key(vm, &*key1), value1) + .unwrap(); assert_eq!(1, dict.len()); let key2 = vm.new_pyobj(ascii!("x")); let value2 = vm.new_pyobj(ascii!("def")); - dict.insert(vm, &*key2, value2.clone()).unwrap(); + dict.insert(vm, &*key2, hash_key(vm, &*key2), value2.clone()) + .unwrap(); assert_eq!(2, dict.len()); - dict.insert(vm, &*key1, value2.clone()).unwrap(); + dict.insert(vm, &*key1, hash_key(vm, &*key1), value2.clone()) + .unwrap(); assert_eq!(2, dict.len()); - dict.delete(vm, &*key1).unwrap(); + dict.delete(vm, &*key1, hash_key(vm, &*key1)).unwrap(); assert_eq!(1, dict.len()); - dict.insert(vm, &*key1, value2.clone()).unwrap(); + dict.insert(vm, &*key1, hash_key(vm, &*key1), value2.clone()) + .unwrap(); assert_eq!(2, dict.len()); - assert!(dict.contains(vm, &*key1).unwrap()); - assert!(dict.contains(vm, "x").unwrap()); + assert!(dict.contains(vm, &*key1, hash_key(vm, &*key1)).unwrap()); + assert!(dict.contains(vm, "x", hash_key(vm, "x")).unwrap()); - let val = dict.get(vm, "x").unwrap().unwrap(); + let val = dict.get(vm, "x", hash_key(vm, "x")).unwrap().unwrap(); vm.bool_eq(&val, &value2) .expect("retrieved value must be equal to inserted value."); }) @@ -2008,12 +2691,16 @@ mod tests { (inner.indices.len(), inner.entries.capacity()) }; for key in 0..count { - dict.insert(vm, &key, vm.ctx.none()).unwrap(); + dict.insert(vm, &key, hash_key(vm, &key), vm.ctx.none()) + .unwrap(); let inner = dict.read(); assert_eq!((inner.indices.len(), inner.entries.capacity()), capacity); } assert_eq!(dict.len(), count); - assert!(dict.contains(vm, &(count - 1)).unwrap()); + assert!( + dict.contains(vm, &(count - 1), hash_key(vm, &(count - 1))) + .unwrap() + ); // Existing and tombstoned layouts are left intact. dict.reserve_for_empty(count * 4); @@ -2022,7 +2709,7 @@ mod tests { assert_eq!((inner.indices.len(), inner.entries.capacity()), capacity); } for key in 0..count { - dict.delete(vm, &key).unwrap(); + dict.delete(vm, &key, hash_key(vm, &key)).unwrap(); } let old_size = dict.read().size(); dict.reserve_for_empty(count * 4); @@ -2061,19 +2748,21 @@ mod tests { fn replace_contents_invalidates_cached_indices() { Interpreter::without_stdlib(Default::default()).enter(|vm| { let dict = Dict::default(); - dict.insert(vm, &1usize, ()).unwrap(); + dict.insert(vm, &1usize, hash_key(vm, &1usize), ()).unwrap(); let old_version = dict.assign_keys_version(); assert_ne!(old_version, 0); let replacement = Dict::default(); - replacement.insert(vm, &2usize, ()).unwrap(); + replacement + .insert(vm, &2usize, hash_key(vm, &2usize), ()) + .unwrap(); assert_ne!(replacement.assign_keys_version(), 0); dict.replace_contents(replacement); assert_eq!(dict.keys_version(), 0); assert_eq!(dict.get_index_if_keys_version(old_version, 0), None); - assert!(!dict.contains(vm, &1usize).unwrap()); - assert!(dict.contains(vm, &2usize).unwrap()); + assert!(!dict.contains(vm, &1usize, hash_key(vm, &1usize)).unwrap()); + assert!(dict.contains(vm, &2usize, hash_key(vm, &2usize)).unwrap()); }); } } diff --git a/crates/vm/src/exception_group.rs b/crates/vm/src/exception_group.rs index 2c61d8ba7c1..9ebb1f33f7e 100644 --- a/crates/vm/src/exception_group.rs +++ b/crates/vm/src/exception_group.rs @@ -2,7 +2,7 @@ //! //! This module implements BaseExceptionGroup and ExceptionGroup with multiple inheritance support. -use crate::builtins::{PyList, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef}; +use crate::builtins::{PyList, PyListRef, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef}; use crate::function::FuncArgs; use crate::object::{Traverse, TraverseFn}; use crate::types::{PyTypeFlags, PyTypeSlots}; @@ -65,7 +65,8 @@ pub(super) mod types { excs_str: PyAtomicRef>, } - impl crate::class::PySubclass for PyBaseExceptionGroup { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PyBaseExceptionGroup { type Base = PyBaseException; fn as_base(&self) -> &Self::Base { &self.base @@ -115,49 +116,8 @@ pub(super) mod types { vm: &VirtualMachine, ) -> PyResult { let matcher = get_condition_matcher(&matcher_value, vm)?; - - // If self matches the condition entirely, return self - let zelf_obj: PyObjectRef = zelf.clone().into(); - if matcher.check(&zelf_obj, vm)? { - return Ok(zelf_obj); - } - - let exceptions = get_exceptions_tuple(&zelf, vm)?; - let mut matching: Vec = Vec::new(); - let mut modified = false; - - for exc in exceptions { - if is_base_exception_group(&exc, vm) { - // Recursive call for nested groups. It pushes no Python - // frame, so a deep enough group runs off the native stack - // unless this guard is here. - let subgroup_result = vm - .with_recursion("in exception group subgroup", || { - vm.call_method(&exc, "subgroup", (matcher_value.clone(),)) - })?; - if !vm.is_none(&subgroup_result) { - matching.push(subgroup_result.clone()); - } - if !subgroup_result.is(&exc) { - modified = true; - } - } else if matcher.check(&exc, vm)? { - matching.push(exc); - } else { - modified = true; - } - } - - if !modified { - return Ok(zelf.into()); - } - - if matching.is_empty() { - return Ok(vm.ctx.none()); - } - - // Create new group with matching exceptions and copy metadata - derive_and_copy_attributes(&zelf, matching, vm) + let result = split_recursive(zelf.as_object(), &matcher, false, vm)?; + Ok(result.matching.unwrap_or_else(|| vm.ctx.none())) } #[pymethod] @@ -167,62 +127,11 @@ pub(super) mod types { vm: &VirtualMachine, ) -> PyResult { let matcher = get_condition_matcher(&matcher_value, vm)?; - - // If self matches the condition entirely - let zelf_obj: PyObjectRef = zelf.clone().into(); - if matcher.check(&zelf_obj, vm)? { - return Ok(vm.ctx.new_tuple(vec![zelf_obj, vm.ctx.none()])); - } - - let exceptions = get_exceptions_tuple(&zelf, vm)?; - let mut matching: Vec = Vec::new(); - let mut rest: Vec = Vec::new(); - - for exc in exceptions { - if is_base_exception_group(&exc, vm) { - // Same as in subgroup: nothing else bounds this recursion - // against the native stack. - let result = vm.with_recursion("in exception group split", || { - vm.call_method(&exc, "split", (matcher_value.clone(),)) - })?; - let result_tuple: PyTupleRef = result.try_into_value(vm)?; - let match_part = result_tuple - .as_slice() - .first() - .cloned() - .unwrap_or_else(|| vm.ctx.none()); - let rest_part = result_tuple - .as_slice() - .get(1) - .cloned() - .unwrap_or_else(|| vm.ctx.none()); - - if !vm.is_none(&match_part) { - matching.push(match_part); - } - if !vm.is_none(&rest_part) { - rest.push(rest_part); - } - } else if matcher.check(&exc, vm)? { - matching.push(exc); - } else { - rest.push(exc); - } - } - - let match_group = if matching.is_empty() { - vm.ctx.none() - } else { - derive_and_copy_attributes(&zelf, matching, vm)? - }; - - let rest_group = if rest.is_empty() { - vm.ctx.none() - } else { - derive_and_copy_attributes(&zelf, rest, vm)? - }; - - Ok(vm.ctx.new_tuple(vec![match_group, rest_group])) + let result = split_recursive(zelf.as_object(), &matcher, true, vm)?; + Ok(vm.ctx.new_tuple(vec![ + result.matching.unwrap_or_else(|| vm.ctx.none()), + result.rest.unwrap_or_else(|| vm.ctx.none()), + ])) } #[pyslot] @@ -248,18 +157,17 @@ pub(super) mod types { let zelf = zelf .downcast_ref::() .expect("exception group must be BaseExceptionGroup"); - let class_name = zelf.class().name().to_owned(); - let message = zelf.msg.repr(vm)?; - let exceptions_str = if let Some(saved) = zelf.excs_str.load_owned() { saved .downcast::() .map_err(|_| vm.new_type_error("__repr__ returned non-string"))? } else { - let args = zelf.base.args(); - let exceptions_obj = if args.as_slice().len() == 2 - && args.as_slice()[1].downcast_ref::().is_some() - { + let use_list = { + let args = zelf.base.args(); + args.as_slice().len() == 2 + && args.as_slice()[1].downcast_ref::().is_some() + }; + let exceptions_obj = if use_list { let list = match zelf.excs.downcast_ref::() { Some(tuple) => vm.ctx.new_list(tuple.as_slice().to_vec()), None => vm.ctx.new_list(vec![]), @@ -271,6 +179,15 @@ pub(super) mod types { exceptions_obj.repr(vm)? }; + // Child repr callbacks can rename the type; message repr callbacks + // run only after its short name has been captured. + let class_name = { + let name = zelf.class().slot_name(); + name.rsplit_once('.') + .map_or(&*name, |(_, name)| name) + .to_owned() + }; + let message = zelf.msg.repr(vm)?; let mut result = Wtf8Buf::new(); write!(result, "{class_name}(").unwrap(); result.push_wtf8(message.as_wtf8()); @@ -286,14 +203,17 @@ pub(super) mod types { type Args = FuncArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - if args.args.len() != 2 { - return Err(vm.new_type_error(format!( - "BaseExceptionGroup.__new__() takes exactly 2 arguments ({} given)", - args.args.len() - ))); - } + // Bind only raw positional objects, retaining the caller's owners. + // __new__ ignores keywords; __init__ rejects them after construction. + let (message, exceptions_arg): (PyObjectRef, PyObjectRef) = + FuncArgs::from(args.args.clone()).bind(vm).map_err(|_| { + // Raw-object binding can fail only on the positional count. + vm.new_type_error(format!( + "BaseExceptionGroup.__new__() takes exactly 2 arguments ({} given)", + args.args.len() + )) + })?; - let message = args.args[0].clone(); if !message.fast_isinstance(vm.ctx.types.str_type) { return Err(vm.new_type_error(format!( "argument 1 must be str, not {}", @@ -301,10 +221,11 @@ pub(super) mod types { ))); } - let exceptions_arg = &args.args[1]; - exceptions_arg.try_sequence(vm).map_err(|_| { - vm.new_type_error("second argument (exceptions) must be a sequence") - })?; + if exceptions_arg.fast_isinstance(vm.ctx.types.dict_type) + || !exceptions_arg.sequence_unchecked().check() + { + return Err(vm.new_type_error("second argument (exceptions) must be a sequence")); + } let is_list = exceptions_arg.downcast_ref::().is_some(); let is_tuple = exceptions_arg.downcast_ref::().is_some(); @@ -314,9 +235,17 @@ pub(super) mod types { None }; - let exceptions: Vec = exceptions_arg.try_to_value(vm).map_err(|_| { - vm.new_type_error("second argument (exceptions) must be a sequence") - })?; + let exceptions = + if let Some(tuple) = exceptions_arg.downcast_ref_if_exact::(vm) { + tuple.to_owned() + } else if let Some(list) = exceptions_arg.downcast_ref_if_exact::(vm) { + vm.ctx.new_tuple(list.borrow_vec().to_vec()) + } else { + // Sequence conversion uses iteration without a length hint and + // must preserve the original exception from any callback. + vm.ctx + .new_tuple(exceptions_arg.try_to_value::>(vm)?) + }; if exceptions.is_empty() { return Err( @@ -331,7 +260,7 @@ pub(super) mod types { "Item {i} of second argument (exceptions) is not an exception" ))); } - if !exc.fast_isinstance(vm.ctx.exceptions.exception_type) { + if !exc.is_instance(vm.ctx.exceptions.exception_type.as_object(), vm)? { has_non_exception = true; } } @@ -361,25 +290,20 @@ pub(super) mod types { cls }; - // Keep an exact tuple as-is so `.exceptions is original` for tuples. - let exceptions_tuple = if exceptions_arg.class().is(vm.ctx.types.tuple_type) { - exceptions_arg - .clone() - .downcast::() - .expect("exact tuple") - } else { - vm.ctx.new_tuple(exceptions) - }; - let payload = Self { base: PyBaseException::new(args.args.clone(), vm), msg: message.into(), - excs: PyObjectRef::from(exceptions_tuple).into(), + excs: PyObjectRef::from(exceptions).into(), excs_str: excs_str.into(), }; - payload + let result = payload .into_ref_with_type_lazy_dict(vm, actual_cls) - .map(Into::into) + .map(Into::into); + // Retain the original owners even if native allocation rejects the + // payload, then release them in their normal scope order. + drop(exceptions_arg); + drop(args); + result } fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { @@ -392,10 +316,11 @@ pub(super) mod types { fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { if !args.kwargs.is_empty() { - return Err(vm.new_type_error(format!( - "{} does not take keyword arguments", - zelf.class().name() - ))); + let name = { + let name = zelf.class().slot_name(); + name[..name.floor_char_boundary(200.min(name.len()))].to_owned() + }; + return Err(vm.new_type_error(format!("{name}() takes no keyword arguments"))); } PyBaseException::slot_init(zelf, args, vm) } @@ -410,17 +335,6 @@ pub(super) mod types { obj.fast_isinstance(vm.ctx.exceptions.base_exception_group) } - fn get_exceptions_tuple( - exc: &Py, - vm: &VirtualMachine, - ) -> PyResult> { - let tuple = exc - .excs - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("exceptions must be a tuple"))?; - Ok(tuple.as_slice().to_vec()) - } - enum ConditionMatcher { Type(PyTypeRef), Types(Vec), @@ -431,6 +345,11 @@ pub(super) mod types { condition: &PyObject, vm: &VirtualMachine, ) -> PyResult { + // A callable tuple subclass is a predicate, not a tuple of types. + if condition.is_callable() && condition.downcast_ref::().is_none() { + return Ok(ConditionMatcher::Callable(condition.to_owned())); + } + // If it's a type and subclass of BaseException if let Some(typ) = condition.downcast_ref::() && typ.fast_issubclass(vm.ctx.exceptions.base_exception_type) @@ -438,33 +357,28 @@ pub(super) mod types { return Ok(ConditionMatcher::Type(typ.to_owned())); } - // If it's a tuple of types - if let Some(tuple) = condition.downcast_ref::() { + // Only exact tuples are accepted, including the empty tuple. + if let Some(tuple) = condition.downcast_ref_if_exact::(vm) { let mut types = Vec::new(); for item in tuple { - let typ: PyTypeRef = item.clone().try_into_value(vm).map_err(|_| { - vm.new_type_error( - "expected a function, exception type or tuple of exception types", - ) - })?; + let Some(typ) = item.downcast_ref::() else { + return Err(invalid_condition(vm)); + }; if !typ.fast_issubclass(vm.ctx.exceptions.base_exception_type) { - return Err(vm.new_type_error( - "expected a function, exception type or tuple of exception types", - )); + return Err(invalid_condition(vm)); } - types.push(typ); - } - if !types.is_empty() { - return Ok(ConditionMatcher::Types(types)); + types.push(typ.to_owned()); } + return Ok(ConditionMatcher::Types(types)); } - // If it's callable (but not a type) - if condition.is_callable() && condition.downcast_ref::().is_none() { - return Ok(ConditionMatcher::Callable(condition.to_owned())); - } + Err(invalid_condition(vm)) + } - Err(vm.new_type_error("expected a function, exception type or tuple of exception types")) + fn invalid_condition(vm: &VirtualMachine) -> crate::exceptions::types::PyBaseExceptionRef { + vm.new_type_error( + "expected an exception type, a tuple of exception types, or a callable (other than a class)", + ) } impl ConditionMatcher { @@ -480,40 +394,123 @@ pub(super) mod types { } } + struct SplitResult { + matching: Option, + rest: Option, + } + + struct SplitLists { + // Both lists outlive the derive calls, and field order releases the + // matching input first, including when a callback raises. + matching: PyListRef, + rest: Option, + } + + fn split_recursive( + exc: &PyObject, + matcher: &ConditionMatcher, + construct_rest: bool, + vm: &VirtualMachine, + ) -> PyResult { + if matcher.check(exc, vm)? { + return Ok(SplitResult { + matching: Some(exc.to_owned()), + rest: None, + }); + } + let Some(group) = exc.downcast_ref::() else { + return Ok(SplitResult { + matching: None, + rest: construct_rest.then(|| exc.to_owned()), + }); + }; + + let exceptions = group + .excs + .downcast_ref::() + .expect("exception group constructor stored an exact tuple"); + let lists = SplitLists { + matching: vm.ctx.new_list(Vec::new()), + rest: construct_rest.then(|| vm.ctx.new_list(Vec::new())), + }; + for child in exceptions { + // Recurse internally, without dispatching overridden subgroup or + // split methods. No Python frame otherwise bounds this recursion. + let result = vm.with_recursion(" in exceptiongroup_split_recursive", || { + split_recursive(child, matcher, construct_rest, vm) + })?; + if let Some(child) = result.matching { + lists.matching.borrow_vec_mut().push(child); + } + if let Some(child) = result.rest { + lists + .rest + .as_ref() + .expect("rest is collected only for split") + .borrow_vec_mut() + .push(child); + } + } + + // Only a group-level match preserves identity. Matching every leaf + // still invokes derive, even for subgroup(), and derive stays dynamic. + let matching = if lists.matching.borrow_vec().is_empty() { + None + } else { + Some(derive_and_copy_attributes_from_list( + group, + &lists.matching, + vm, + )?) + }; + let rest = match &lists.rest { + Some(rest) if !rest.borrow_vec().is_empty() => { + Some(derive_and_copy_attributes_from_list(group, rest, vm)?) + } + _ => None, + }; + Ok(SplitResult { matching, rest }) + } + pub(crate) fn derive_and_copy_attributes( orig: &Py, excs: Vec, vm: &VirtualMachine, ) -> PyResult { - // Call derive method to create new group let excs_seq = vm.ctx.new_list(excs); - let new_group = vm.call_method(orig.as_object(), "derive", (excs_seq,))?; + derive_and_copy_attributes_from_list(orig, &excs_seq, vm) + } + + fn derive_and_copy_attributes_from_list( + orig: &Py, + excs: &PyListRef, + vm: &VirtualMachine, + ) -> PyResult { + // Call derive method to create new group while the caller retains the + // exact list, whose elements the override may replace. + let new_group = vm.call_method(orig.as_object(), "derive", (excs.clone(),))?; // Verify derive returned a BaseExceptionGroup if !is_base_exception_group(&new_group, vm) { return Err(vm.new_type_error("derive must return an instance of BaseExceptionGroup")); } - // Copy traceback + let derived = new_group.try_downcast_ref::(vm)?; if let Some(tb) = orig.base.__traceback__() { - new_group.set_attr("__traceback__", tb, vm)?; - } - - // Copy context - if let Some(ctx) = orig.base.__context__() { - new_group.set_attr("__context__", ctx, vm)?; - } - - // Copy cause - if let Some(cause) = orig.base.__cause__() { - new_group.set_attr("__cause__", cause, vm)?; + derived.base.set_traceback(Some(tb)); } + derived.base.set_context(orig.base.__context__()); + derived.base.set_cause(orig.base.__cause__()); - // Copy notes (if present) - make a copy of the list - if let Ok(notes) = orig.as_object().get_attr("__notes__", vm) - && let Some(notes_list) = notes.downcast_ref::() + // CPython copies notes only when they are a sequence, excluding dicts. + if let Some(notes) = vm.get_attribute_opt(orig.as_object(), "__notes__")? + && !notes.fast_isinstance(vm.ctx.types.dict_type) + && notes.sequence_unchecked().check() { - let notes_copy = vm.ctx.new_list(notes_list.borrow_vec().to_vec()); + let notes_copy = vm + .ctx + .new_list(vm.extract_elements_sized(¬es, &|| 0, Ok)?); + drop(notes); new_group.set_attr("__notes__", notes_copy, vm)?; } diff --git a/crates/vm/src/exceptions.rs b/crates/vm/src/exceptions.rs index 9562ad7a8b5..ef8198f7943 100644 --- a/crates/vm/src/exceptions.rs +++ b/crates/vm/src/exceptions.rs @@ -1,17 +1,17 @@ use self::types::{PyBaseException, PyBaseExceptionRef, PyException, PyMemoryError}; pub use super::exception_group::exception_group; -use crate::common::lock::PyRwLock; +use crate::common::{lock::PyRwLock, wtf8::Wtf8Buf}; use crate::object::{Traverse, TraverseFn}; use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{ - PyList, PyNone, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, + PyDictRef, PyList, PyNone, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, traceback::{PyTraceback, PyTracebackRef}, }, class::{PyClassImpl, StaticType}, convert::{IntoPyException, ToPyException, ToPyObject}, - function::{ArgIterable, FuncArgs, IntoFuncArgs, PySetterValue}, + function::{FuncArgs, IntoFuncArgs, PySetterValue}, py_io::{self, Write}, stdlib::sys, suggestion::offer_suggestions, @@ -32,6 +32,25 @@ unsafe impl Traverse for PyBaseException { self.context.traverse(tracer_fn); self.args.traverse(tracer_fn); } + + /// Detaches traceback, cause, and context references for deferred release. + /// + /// Moving references into `out` breaks these cycles without dropping children + /// during the collector's exclusive payload access. Arguments remain owned by + /// the payload until its destruction. + fn clear(&mut self, out: &mut Vec) { + if let Some(traceback) = self.traceback.get_mut().take() { + out.push(traceback.into()); + } + + if let Some(cause) = self.cause.get_mut().take() { + out.push(cause.into()); + } + + if let Some(context) = self.context.get_mut().take() { + out.push(context.into()); + } + } } impl core::fmt::Debug for PyBaseException { @@ -101,28 +120,125 @@ impl VirtualMachine { /// Print exception chain by calling sys.excepthook pub fn print_exception(&self, exc: &Py) { let vm = self; - let write_fallback = |exc, errstr| { - if let Ok(stderr) = sys::get_stderr(vm) { - let mut stderr = py_io::PyWriter(stderr, vm); - // if this fails stderr might be closed -- ignore it - let _ = writeln!(stderr, "{errstr}"); - let _ = self.write_exception(&mut stderr, exc); - } else { - eprintln!("{errstr}\nlost sys.stderr"); - let _ = self.write_exception(&mut py_io::IoWriter(io::stderr()), exc); - } - }; if let Ok(excepthook) = vm.sys_module.get_attr("excepthook", vm) { let (exc_type, exc_val, exc_tb) = vm.split_exception(exc.to_owned()); if let Err(eh_exc) = excepthook.call((exc_type, exc_val, exc_tb), vm) { - write_fallback(&eh_exc, "Error in sys.excepthook:"); - write_fallback(exc, "Original exception was:"); + writeln!(sys::PyStderr(vm), "Error in sys.excepthook:"); + vm.display_exception(&eh_exc); + writeln!(sys::PyStderr(vm), "Original exception was:"); + vm.display_exception(exc); + } + } else { + writeln!(sys::PyStderr(vm), "missing sys.excepthook"); + vm.display_exception(exc); + } + } + + /// PyErr_Print + /// + /// Record the exception as `sys.last_exc` and display it through + /// `sys.excepthook`. A `SystemExit` exits the process unless inspect mode + /// is enabled. + pub fn print_uncaught_exception(&self, exc: &Py) { + self.handle_system_exit(exc); + let (exc_type, exc_val, exc_tb) = self.split_exception(exc.to_owned()); + for (name, value) in [ + ("last_exc", &exc_val), + ("last_type", &exc_type), + ("last_value", &exc_val), + ("last_traceback", &exc_tb), + ] { + let _ = self.sys_module.set_attr(name, value.clone(), self); + } + let hook = self.sys_module.get_attr("excepthook", self).ok(); + if let Err(audit_exc) = self.audit("sys.excepthook", || { + ( + hook.clone().unwrap_or_else(|| self.ctx.none()), + exc_type.clone(), + exc_val.clone(), + exc_tb.clone(), + ) + }) { + if audit_exc.fast_isinstance(self.ctx.exceptions.runtime_error) { + return; + } + self.run_unraisable( + audit_exc, + Some("Exception ignored in audit hook".to_owned()), + self.ctx.none(), + ); + } + if let Some(hook) = hook { + if let Err(hook_exc) = hook.call((exc_type, exc_val, exc_tb), self) { + self.handle_system_exit(&hook_exc); + let _ = io::Write::flush(&mut io::stdout()); + writeln!(sys::PyStderr(self), "Error in sys.excepthook:"); + self.display_exception(&hook_exc); + writeln!(sys::PyStderr(self), "\nOriginal exception was:"); + self.display_exception(exc); } } else { - write_fallback(exc, "missing sys.excepthook"); + writeln!(sys::PyStderr(self), "sys.excepthook is missing"); + self.display_exception(exc); } } + /// handle_system_exit + fn handle_system_exit(&self, exc: &Py) { + if let Some(exit_code) = self.handle_system_exit_and_keyboard_interrupt(exc) { + self.exit_process(exit_code); + } + } + + /// PyErr_Display + /// + /// Display `exc` on `sys.stderr`; nothing is written when it is `None`. + pub fn display_exception(&self, exc: &Py) { + let file = self.sys_module.dict().get_item_opt("stderr", self); + if let Ok(Some(file)) = &file { + if !self.is_none(file) { + self.display_exception_to(file, exc); + } + return; + } + self.dump_object(exc.as_object()); + eprintln!("lost sys.stderr"); + if let Err(err) = file { + self.dump_object(err.as_object()); + } + } + + /// _PyErr_Display + /// + /// Display `exc` through `traceback._print_exception_bltin`, falling back + /// to the native printer writing to `file`. + pub(crate) fn display_exception_to(&self, file: &PyObject, exc: &Py) { + if self.try_display_exception_to(file, exc.as_object()) { + return; + } + if self + .write_exception(&mut py_io::PyWriter(file.to_owned(), self), exc) + .is_err() + { + self.dump_object(exc.as_object()); + eprintln!("lost sys.stderr"); + } + let _ = self.call_method(file, "flush", ()); + } + + /// Try the shared Python formatter with the caller's retained output file. + /// Reporting paths provide their own native fallback if it is unavailable. + pub(crate) fn try_display_exception_to(&self, file: &PyObject, exc: &PyObject) -> bool { + self.import("traceback", 0) + .and_then(|traceback| traceback.get_attr("_print_exception_bltin", self)) + .is_ok_and(|print_exception| { + print_exception.is_callable() + && print_exception + .call((exc.to_owned(), file.to_owned()), self) + .is_ok() + }) + } + pub fn write_exception( &self, output: &mut W, @@ -185,10 +301,7 @@ impl VirtualMachine { let traceback = exc.traceback.read().clone(); if let Some(tb) = traceback { - writeln!(output, "Traceback (most recent call last):")?; - for tb in tb.iter() { - write_traceback_entry(output, &tb)?; - } + write_traceback(output, &tb, vm)?; } let varargs = exc.args(); @@ -424,7 +537,7 @@ impl VirtualMachine { #[cfg(feature = "host_env")] fn print_source_line( output: &mut W, - filename: &str, + filename: &std::path::Path, lineno: usize, ) -> Result<(), W::Error> { // TODO: use io.open() method instead, when available, according to https://github.com/python/cpython/blob/main/Python/traceback.c#L393 @@ -448,22 +561,50 @@ fn print_source_line( Ok(()) } +pub(crate) fn write_traceback( + output: &mut W, + traceback: &PyTracebackRef, + vm: &VirtualMachine, +) -> Result<(), W::Error> { + writeln!(output, "Traceback (most recent call last):")?; + for entry in traceback.iter() { + write_traceback_entry(output, &entry, vm)?; + } + Ok(()) +} + /// Print exception occurrence location from traceback element fn write_traceback_entry( output: &mut W, tb_entry: &Py, + vm: &VirtualMachine, ) -> Result<(), W::Error> { - let filename = tb_entry.frame.iframe().code().source_path().as_str(); + let filename = tb_entry.frame.iframe().code().source_path(); + // This fallback writer accepts UTF-8, unlike Python's traceback formatter. + // Escape lone surrogates as stderr's backslashreplace handler does, rather + // than replacing them or letting the interned-string UTF-8 accessor panic. + let mut display_filename = String::new(); + for point in filename.as_wtf8().code_points() { + if let Some(ch) = point.to_char() { + display_filename.push(ch); + } else { + display_filename.push_str(&format!("\\u{:04x}", point.to_u32())); + } + } writeln!( output, r##" File "{}", line {}, in {}"##, - filename.trim_start_matches(r"\\?\"), + display_filename.trim_start_matches(r"\\?\"), tb_entry.lineno, tb_entry.frame.iframe().code().obj_name )?; #[cfg(feature = "host_env")] - print_source_line(output, filename, tb_entry.lineno.get())?; + if let Ok(path) = vm.fsencode(filename) { + print_source_line(output, path.as_ref(), tb_entry.lineno.get())?; + } + #[cfg(not(feature = "host_env"))] + let _ = vm; Ok(()) } @@ -549,6 +690,7 @@ pub struct ExceptionZoo { pub attribute_error: &'static Py, pub buffer_error: &'static Py, pub eof_error: &'static Py, + pub import_cycle_error: &'static Py, pub import_error: &'static Py, pub module_not_found_error: &'static Py, pub lookup_error: &'static Py, @@ -628,6 +770,11 @@ macro_rules! extend_exception { }; } +fn truncated_type_name(object: &PyObject, max_bytes: usize) -> String { + let name = object.class().slot_name(); + name[..name.floor_char_boundary(max_bytes.min(name.len()))].to_owned() +} + impl PyBaseException { pub(crate) fn new(args: Vec, vm: &VirtualMachine) -> Self { Self { @@ -642,21 +789,43 @@ impl PyBaseException { pub fn get_arg(&self, idx: usize) -> Option { self.args.read().as_slice().get(idx).cloned() } + + fn init_args(zelf: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + if !args.kwargs.is_empty() { + return Err(vm.new_type_error(format!( + "{}() takes no keyword arguments", + truncated_type_name(zelf.as_object(), 200) + ))); + } + let args = PyTuple::new_ref(args.args, &vm.ctx); + // Retain the supplied tuple: releasing old args can reenter and replace + // the field before a specialized initializer finishes using it. + zelf.set_args_tuple(args.clone()); + Ok(args) + } } impl PyBaseException { + // Replaced references may run Python finalizers. Release their locks + // before dropping the old values so those finalizers can reenter safely. pub fn set_traceback(&self, traceback: Option) { - *self.traceback.write() = traceback; + let _old = core::mem::replace(&mut *self.traceback.write(), traceback); } pub fn set_cause(&self, cause: Option>) { - let mut c = self.cause.write(); - self.set_suppress_context(true); - *c = cause; + let _old = { + let mut current = self.cause.write(); + self.set_suppress_context(true); + core::mem::replace(&mut *current, cause) + }; } pub fn set_context(&self, context: Option>) { - *self.context.write() = context; + let _old = core::mem::replace(&mut *self.context.write(), context); + } + + fn set_args_tuple(&self, args: PyTupleRef) { + let _old = core::mem::replace(&mut *self.args.write(), args); } pub(super) fn __suppress_context__(&self) -> bool { @@ -684,7 +853,7 @@ impl PyBaseException { #[pyclass( with(Py, PyRef, Constructor, Initializer, Representable), - flags(BASETYPE, HAS_DICT) + flags(BASETYPE, HAS_DICT, BASE_EXC_SUBCLASS) )] impl PyBaseException {} @@ -696,7 +865,17 @@ impl Py { } #[pymethod] - pub(super) fn __str__(&self, vm: &VirtualMachine) -> PyStrRef { + pub(super) fn __str__(&self, vm: &VirtualMachine) -> PyResult { + let args = self.args(); + match args.as_slice() { + [] => Ok(vm.ctx.empty_str.to_owned()), + [arg] => arg.str(vm), + _ => args.as_object().str(vm), + } + } + + pub(crate) fn diagnostic_str(&self, vm: &VirtualMachine) -> PyStrRef { + // Internal error decoration must still work if a formatter raises. let str_args = vm.exception_args_as_string(&self.args(), true); match str_args.into_iter().exactly_one() { Err(i) if i.len() == 0 => vm.ctx.empty_str.to_owned(), @@ -706,33 +885,45 @@ impl Py { } #[pymethod] - pub fn add_note(&self, note: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { - let dict = crate::builtins::object::object_get_dict(self.as_object().to_owned(), vm) - .map_err(|_| vm.new_attribute_error("Exception object has no __dict__"))?; - - let notes = if let Ok(notes) = dict.get_item("__notes__", vm) { - notes - } else { - let new_notes = vm.ctx.new_list(vec![]); - dict.set_item("__notes__", new_notes.clone().into(), vm)?; - new_notes.into() + fn add_note(&self, note: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + let note = note.downcast::().map_err(|note| { + let name = if vm.is_none(¬e) { + "None".to_owned() + } else { + truncated_type_name(¬e, 50) + }; + vm.new_type_error(format!("add_note() argument must be str, not {name}")) + })?; + self.add_note_str(note, vm) + } + + pub fn add_note_str(&self, note: PyStrRef, vm: &VirtualMachine) -> PyResult<()> { + let notes = match vm.get_attribute_opt(self.as_object(), "__notes__")? { + Some(notes) => notes + .downcast::() + .map_err(|_| vm.new_type_error("Cannot add note: __notes__ is not a list"))?, + None => { + let notes = vm.ctx.new_list(vec![]); + self.as_object().set_attr("__notes__", notes.clone(), vm)?; + notes + } }; - - let notes = notes - .downcast::() - .map_err(|_| vm.new_type_error("Cannot add note: __notes__ is not a list"))?; - - notes.borrow_vec_mut().push(note.into()); + notes.append(note.into()); Ok(()) } + fn reduce_with_state(&self, state: Option, vm: &VirtualMachine) -> PyTupleRef { + let class = self.class().to_owned(); + let args = self.args(); + match state { + Some(state) => vm.new_tuple((class, args, state)), + None => vm.new_tuple((class, args)), + } + } + #[pymethod] fn __reduce__(&self, vm: &VirtualMachine) -> PyTupleRef { - if let Some(dict) = self.as_object().dict().filter(|x| !x.is_empty()) { - vm.new_tuple((self.class().to_owned(), self.args(), dict)) - } else { - vm.new_tuple((self.class().to_owned(), self.args())) - } + self.reduce_with_state(self.as_object().dict(), vm) } #[pymethod] @@ -743,11 +934,11 @@ impl Py { .map_err(|_| vm.new_type_error("state is not a dictionary"))?; for (key, value) in &dict { - let key_str = key.str(vm)?; - if key_str.as_bytes().starts_with(b"__") { - continue; - } - self.as_object().set_attr(&key_str, value, vm)?; + let key = key.downcast::().map_err(|key| { + let name = truncated_type_name(&key, 200); + vm.new_type_error(format!("attribute name must be string, not '{name}'")) + })?; + self.as_object().set_attr(&key, value, vm)?; } } Ok(vm.ctx.none()) @@ -773,9 +964,8 @@ impl Py { let PySetterValue::Assign(value) = value else { return Err(vm.new_type_error("args may not be deleted")); }; - let args: ArgIterable = value.try_into_value(vm)?; - let args = args.iter(vm)?.collect::>>()?; - *self.args.write() = PyTuple::new_ref(args, &vm.ctx); + let args = PyTuple::from_sequence(&value, vm)?; + self.set_args_tuple(args); Ok(()) } @@ -860,7 +1050,7 @@ impl Py { impl PyRef { #[pymethod] fn with_traceback(self, tb: Option) -> Self { - *self.traceback.write() = tb; + self.set_traceback(tb); self } } @@ -869,16 +1059,14 @@ impl Constructor for PyBaseException { type Args = FuncArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - if cls.is(Self::class(&vm.ctx)) && !args.kwargs.is_empty() { - return Err(vm.new_type_error("BaseException() takes no keyword arguments")); - } Self::new(args.args, vm) .into_ref_with_type_lazy_dict(vm, cls) .map(Into::into) } - fn py_new(_cls: &Py, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult { - unimplemented!("use slot_new") + /// Creates an unallocated base payload preserving the supplied positional arguments. + fn py_new(_cls: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + Ok(Self::new(args.args, vm)) } } @@ -886,17 +1074,32 @@ impl Initializer for PyBaseException { type Args = FuncArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - *zelf.args.write() = PyTuple::new_ref(args.args, &vm.ctx); - Ok(()) + Self::init_args(zelf, args, vm).map(drop) } } impl Representable for PyBaseException { #[inline] - fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let repr_args = vm.exception_args_as_string(&zelf.args(), false); - let cls = zelf.class(); - Ok(format!("{}({})", cls.name(), repr_args.iter().format(", "))) + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { + // Both the type name and args may change while an argument is rendered. + // Own the name before calling Python, without retaining its read lock. + let mut result = Wtf8Buf::from( + zelf.class() + .slot_name() + .rsplit('.') + .next() + .unwrap_or_default(), + ); + let args = zelf.args(); + match args.as_slice() { + [arg] => { + result.push_char('('); + result.push_wtf8(arg.repr(vm)?.as_wtf8()); + result.push_char(')'); + } + _ => result.push_wtf8(args.as_object().repr(vm)?.as_wtf8()), + } + Ok(result) } } @@ -926,6 +1129,7 @@ impl ExceptionZoo { let eof_error = PyEOFError::init_builtin_type(); let import_error = PyImportError::init_builtin_type(); + let import_cycle_error = PyImportCycleError::init_builtin_type(); let module_not_found_error = PyModuleNotFoundError::init_builtin_type(); let lookup_error = PyLookupError::init_builtin_type(); @@ -1010,6 +1214,7 @@ impl ExceptionZoo { attribute_error, buffer_error, eof_error, + import_cycle_error, import_error, module_not_found_error, lookup_error, @@ -1104,6 +1309,7 @@ impl ExceptionZoo { extend_exception!(PyEOFError, ctx, excs.eof_error); extend_exception!(PyImportError, ctx, excs.import_error); + extend_exception!(PyImportCycleError, ctx, excs.import_cycle_error); extend_exception!(PyModuleNotFoundError, ctx, excs.module_not_found_error); extend_exception!(PyLookupError, ctx, excs.lookup_error); @@ -1341,7 +1547,12 @@ impl ToPyException for widestring::error::NulError { } } -#[cfg(any(unix, windows, target_os = "wasi"))] +#[cfg(any( + unix, + windows, + target_os = "wasi", + all(target_arch = "wasm32", target_os = "unknown") +))] pub(crate) fn errno_to_exc_type(errno: i32, vm: &VirtualMachine) -> Option<&'static Py> { use crate::stdlib::errno::errors; let excs = &vm.ctx.exceptions; @@ -1351,7 +1562,7 @@ pub(crate) fn errno_to_exc_type(errno: i32, vm: &VirtualMachine) -> Option<&'sta errors::EALREADY => Some(excs.blocking_io_error), errors::EINPROGRESS => Some(excs.blocking_io_error), errors::EPIPE => Some(excs.broken_pipe_error), - #[cfg(not(target_os = "wasi"))] + #[cfg(any(unix, windows))] errors::ESHUTDOWN => Some(excs.broken_pipe_error), errors::ECHILD => Some(excs.child_process_error), errors::ECONNABORTED => Some(excs.connection_aborted_error), @@ -1365,7 +1576,11 @@ pub(crate) fn errno_to_exc_type(errno: i32, vm: &VirtualMachine) -> Option<&'sta errors::EACCES => Some(excs.permission_error), errors::EPERM => Some(excs.permission_error), // A process without the capability to reach a resource. - #[cfg(target_vendor = "apple")] + #[cfg(any( + target_vendor = "apple", + target_os = "wasi", + all(target_arch = "wasm32", target_os = "unknown") + ))] errors::ENOTCAPABLE => Some(excs.permission_error), errors::ESRCH => Some(excs.process_lookup_error), errors::ETIMEDOUT => Some(excs.timeout_error), @@ -1373,11 +1588,6 @@ pub(crate) fn errno_to_exc_type(errno: i32, vm: &VirtualMachine) -> Option<&'sta } } -#[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] -pub(crate) fn errno_to_exc_type(_errno: i32, _vm: &VirtualMachine) -> Option<&'static Py> { - None -} - pub(crate) trait ToOSErrorBuilder { fn to_os_error_builder(&self, vm: &VirtualMachine) -> OSErrorBuilder; } @@ -1540,7 +1750,7 @@ impl IntoPyException for std::io::Error { } } -#[cfg(all(unix, not(target_os = "redox")))] +#[cfg(unix)] impl ToPyException for rustpython_host_env::fcntl::LockfError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { @@ -1551,27 +1761,52 @@ impl ToPyException for rustpython_host_env::fcntl::LockfError { } } -#[cfg(unix)] -impl ToPyException for rustpython_host_env::posix::AccessError { +#[cfg(all(unix, not(target_os = "redox")))] +impl ToPyException for rustpython_host_env::socket::AncillaryPackError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { - Self::InvalidMode => vm.new_value_error( - "One of the flags is wrong, there are only 4 possibilities F_OK, R_OK, W_OK and X_OK", - ), - Self::Os(errno) => std::io::Error::from_raw_os_error(*errno).to_pyexception(vm), + Self::ItemTooLarge => vm.new_os_error("ancillary data item too large"), + Self::TooMuchData => vm.new_os_error("too much ancillary data"), + Self::UnexpectedNullFirstHeader => { + vm.new_runtime_error("unexpected NULL result from CMSG_FIRSTHDR()") + } + Self::UnexpectedNullNextHeader => { + vm.new_runtime_error("unexpected NULL result from CMSG_NXTHDR()") + } + Self::ItemSizeOutOfRange => vm.new_runtime_error("item size out of range"), + Self::DoesNotFit => { + vm.new_runtime_error("ancillary data does not fit in calculated space") + } } } } -#[cfg(all(unix, not(target_os = "redox")))] -impl ToPyException for rustpython_host_env::socket::AncillaryPackError { +#[cfg(target_os = "linux")] +impl ToPyException for rustpython_host_env::socket::AfAlgControlError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { - Self::ItemTooLarge => vm.new_os_error("ancillary data item too large"), - Self::TooMuchData => vm.new_os_error("too much ancillary data"), - Self::UnexpectedNullHeader => { - vm.new_runtime_error("unexpected NULL result from CMSG_FIRSTHDR/CMSG_NXTHDR") + Self::UnexpectedNullFirstHeader => { + vm.new_runtime_error("unexpected NULL result from CMSG_FIRSTHDR") + } + Self::UnexpectedNullNextHeaderIv => { + vm.new_runtime_error("unexpected NULL result from CMSG_NXTHDR(iv)") } + Self::UnexpectedNullNextHeaderAssoc => { + vm.new_runtime_error("unexpected NULL result from CMSG_NXTHDR(assoc)") + } + Self::NoMemory => vm.no_memory_error(), + } + } +} + +#[cfg(windows)] +impl ToPyException for rustpython_host_env::time::TimestampError { + fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { + match self { + Self::FiletimeOutOfRange => { + vm.new_overflow_error("timestamp out of range for Windows FILETIME") + } + Self::Os(error) => error.to_pyexception(vm), } } } @@ -1597,6 +1832,7 @@ impl ToPyException for rustpython_host_env::time::CheckedTmError { impl ToPyException for rustpython_host_env::winapi::BuildEnvironmentBlockError { fn to_pyexception(&self, vm: &VirtualMachine) -> PyBaseExceptionRef { match self { + Self::Os(error) => error.to_pyexception(vm), Self::ContainsNul => vm.new_value_error("embedded null character"), Self::IllegalName => vm.new_value_error("illegal environment variable name"), } @@ -1697,6 +1933,29 @@ impl ToPyException for rustpython_host_env::multiprocessing::SemError { } } +// Generated `Constructor::py_new` calls this. One-field wrappers override it +// with owned construction; other shapes keep the default and allocate via +// `slot_new`. +#[doc(hidden)] +/// Connects generated exception constructors to shape-specific owned construction. +pub trait PyExceptionOwnedConstructor: crate::class::PyClassDef + Sized { + /// Rejects owned construction unless the wrapper supplies an implementation. + /// + /// The default does not invoke `new_base`. Generated single-field wrappers + /// override it to wrap the base payload and propagate constructor errors. + /// + /// # Panics + /// + /// Panics when this default is called for a shape requiring explicit construction. + fn __pyexception_new(new_base: F) -> crate::PyResult + where + F: FnOnce() -> crate::PyResult, + { + let _ = new_base; + unreachable!("slot_new is defined") + } +} + pub(super) mod types { use crate::class::PyClassDef; use crate::common::lock::PyRwLock; @@ -1706,16 +1965,15 @@ pub(super) mod types { AsObject, Py, PyAtomicRef, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{ - PyInt, PyStrRef, PyTupleRef, PyType, PyTypeRef, traceback::PyTracebackRef, + PyDictRef, PyInt, PyStrRef, PyTupleRef, PyType, PyTypeRef, traceback::PyTracebackRef, tuple::IntoPyTuple, }, convert::ToPyResult, - function::{ArgBytesLike, FuncArgs, KwArgs, PySetterValue}, - types::{Constructor, Initializer}, + function::{ArgBytesLike, ArgSpec, FuncArgs, PySetterValue}, + types::{Constructor, Initializer, Representable}, }; use core::sync::atomic::{AtomicBool, AtomicIsize, Ordering}; use crossbeam_utils::atomic::AtomicCell; - use itertools::Itertools; use rustpython_common::{ str::UnicodeEscapeCodepoint, wtf8::{Wtf8, Wtf8Buf, wtf8_concat}, @@ -1750,7 +2008,8 @@ pub(super) mod types { code: PyAtomicRef>, } - impl crate::class::PySubclass for PySystemExit { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PySystemExit { type Base = PyBaseException; fn as_base(&self) -> &Self::Base { &self.base @@ -1779,12 +2038,14 @@ pub(super) mod types { type Args = FuncArgs; fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { // Call BaseException_init first (handles args) - let code = match args.args.len() { - 0 => vm.ctx.none(), - 1 => args.args[0].clone(), - _ => vm.ctx.new_tuple(args.args.clone()).into(), + let base: &Py = + zelf.downcast_ref().expect("SystemExit is a BaseException"); + let args = PyBaseException::init_args(base, args, vm)?; + let code = match args.as_slice() { + [] => return Ok(()), + [code] => code.clone(), + _ => args.clone().into(), }; - PyBaseException::slot_init(zelf, args, vm)?; let exc: &Py = zelf.downcast_ref::().unwrap(); exc.code.swap_to_temporary_refs(Some(code), vm); Ok(()) @@ -1830,7 +2091,8 @@ pub(super) mod types { value: PyAtomicRef>, } - impl crate::class::PySubclass for PyStopIteration { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PyStopIteration { type Base = PyException; fn as_base(&self) -> &Self::Base { &self.base @@ -1867,11 +2129,14 @@ pub(super) mod types { impl Initializer for PyStopIteration { type Args = FuncArgs; fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let value = match args.args.len() { - 0 => vm.ctx.none(), - _ => args.args[0].clone(), + let base: &Py = zelf + .downcast_ref() + .expect("StopIteration is a BaseException"); + let args = PyBaseException::init_args(base, args, vm)?; + let value = match args.first() { + Some(value) => value.clone(), + None => vm.ctx.none(), }; - PyBaseException::slot_init(zelf, args, vm)?; let exc: &Py = zelf.downcast_ref::().unwrap(); exc.value.swap_to_temporary_refs(Some(value), vm); Ok(()) @@ -1925,7 +2190,8 @@ pub(super) mod types { obj: PyAtomicRef>, } - impl crate::class::PySubclass for PyAttributeError { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PyAttributeError { type Base = PyException; fn as_base(&self) -> &Self::Base { &self.base @@ -1965,17 +2231,21 @@ pub(super) mod types { #[pyexception(with(Constructor, Initializer))] impl PyAttributeError { #[pymethod] - fn __getstate__(zelf: &Py, vm: &VirtualMachine) -> PyResult { + fn __getstate__(zelf: &Py, vm: &VirtualMachine) -> PyResult { let obj = zelf.as_object(); let state = match obj.dict() { Some(dict) => dict.copy().into_ref(&vm.ctx), None => vm.ctx.new_dict(), }; - let _ = state.del_item("obj", vm); if let Some(name) = zelf.name.load_owned() { state.set_item("name", name, vm)?; } - Ok(state.into()) + let base: &Py = obj + .downcast_ref() + .expect("AttributeError is a BaseException"); + // Only the native obj field is excluded, not a user dict entry. + state.set_item("args", base.args().into(), vm)?; + Ok(state) } #[pymethod] @@ -1985,11 +2255,7 @@ pub(super) mod types { .as_object() .downcast_ref() .expect("AttributeError is a BaseException"); - Ok(vm.ctx.new_tuple(vec![ - zelf.class().to_owned().into(), - base.args().into(), - state, - ])) + Ok(base.reduce_with_state(Some(state), vm)) } } @@ -1998,27 +2264,28 @@ pub(super) mod types { fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { // Only 'name' and 'obj' kwargs are allowed - let mut kwargs = args.kwargs.clone(); - let name = kwargs.swap_remove("name"); - let obj = kwargs.swap_remove("obj"); - - // Reject unknown kwargs - if let Some(invalid_key) = kwargs.keys().next() { - return Err(vm.new_unexpected_keyword_type_error( - Some(Self::NAME), - &invalid_key.to_string(), - )); - } - + let kwargs = FuncArgs::from(args.kwargs); // Pass args without kwargs to BaseException_init - let base_args = FuncArgs::new(args.args, KwArgs::default()); - PyBaseException::slot_init(zelf, base_args, vm)?; + let base: &Py = zelf + .downcast_ref() + .expect("AttributeError is a BaseException"); + let _args = PyBaseException::init_args(base, args.args.into(), vm)?; + + // Reject unknown kwargs after publishing args, without changing + // their order or releasing their values before the field updates. + let parsed = ArgSpec { + fname: Self::NAME, + keywords: &["name", "obj"], + required: 0, + max_positional: 0, + } + .parse(&kwargs, vm)?; let exc: &Py = zelf .downcast_ref() .expect("AttributeError instance has AttributeError payload"); - exc.name.swap_to_temporary_refs(name, vm); - exc.obj.swap_to_temporary_refs(obj, vm); + exc.name.swap_to_temporary_refs(parsed[0].clone(), vm); + exc.obj.swap_to_temporary_refs(parsed[1].clone(), vm); Ok(()) } @@ -2051,7 +2318,8 @@ pub(super) mod types { name_from: PyAtomicRef>, } - impl crate::class::PySubclass for PyImportError { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PyImportError { type Base = PyException; fn as_base(&self) -> &Self::Base { &self.base @@ -2096,7 +2364,35 @@ pub(super) mod types { } } - #[pyexception(with(Constructor, Initializer))] + impl Representable for PyImportError { + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let base: &Py = zelf + .as_object() + .downcast_ref() + .expect("ImportError is a BaseException"); + let mut has_args = !base.args().is_empty(); + if zelf.name.load_owned().is_none() && zelf.path.load_owned().is_none() { + return PyBaseException::repr_wtf8(base, vm); + } + let mut result = PyBaseException::repr_wtf8(base, vm)?; + result.pop(); + for (name, field) in [("name", &zelf.name), ("path", &zelf.path)] { + if let Some(value) = field.load_owned() { + if has_args { + result.push_str(", "); + } + result.push_str(name); + result.push_char('='); + result.push_wtf8(value.repr(vm)?.as_wtf8()); + has_args = true; + } + } + result.push_char(')'); + Ok(result) + } + } + + #[pyexception(with(Constructor, Initializer, Representable))] impl PyImportError { #[pyslot] fn slot_str(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { @@ -2110,7 +2406,7 @@ pub(super) mod types { } let base: &Py = zelf.downcast_ref().expect("ImportError is a BaseException"); - Ok(base.__str__(vm)) + base.__str__(vm) } #[pymethod] @@ -2119,31 +2415,27 @@ pub(super) mod types { let exc = zelf; let base: &Py = obj.downcast_ref().expect("ImportError is a BaseException"); - let args: PyObjectRef = match base.get_arg(0) { - Some(arg) => vm.new_tuple((arg,)).into(), - None => base.args().into(), - }; - let mut result: Vec = vec![obj.class().to_owned().into(), args]; - - let mut state = obj - .dict() - .filter(|dict| !dict.is_empty()) - .map(|dict| dict.copy().into_ref(&vm.ctx)); - let mut insert = |key: &str, value: Option| -> PyResult<()> { - let Some(value) = value else { - return Ok(()); + let mut state = obj.dict(); + if exc.name.load_owned().is_some() + || exc.path.load_owned().is_some() + || exc.name_from.load_owned().is_some() + { + let dict = match state { + Some(dict) => dict.copy().into_ref(&vm.ctx), + None => vm.ctx.new_dict(), }; - let dict = state.get_or_insert_with(|| vm.ctx.new_dict()); - dict.set_item(key, value, vm)?; - Ok(()) - }; - insert("name", exc.name.load_owned())?; - insert("path", exc.path.load_owned())?; - insert("name_from", exc.name_from.load_owned())?; - if let Some(state) = state { - result.push(state.into()); + for (key, field) in [ + ("name", &exc.name), + ("path", &exc.path), + ("name_from", &exc.name_from), + ] { + if let Some(value) = field.load_owned() { + dict.set_item(key, value, vm)?; + } + } + state = Some(dict); } - Ok(result.into_pytuple(vm)) + Ok(base.reduce_with_state(state, vm)) } } @@ -2152,32 +2444,31 @@ pub(super) mod types { fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { // Only 'name', 'path', 'name_from' kwargs are allowed - let mut kwargs = args.kwargs.clone(); - let name = kwargs.swap_remove("name"); - let path = kwargs.swap_remove("path"); - let name_from = kwargs.swap_remove("name_from"); - - // Check for any remaining invalid keyword arguments - if let Some(invalid_key) = kwargs.keys().next() { - return Err(vm.new_unexpected_keyword_type_error( - Some("ImportError"), - &invalid_key.to_string(), - )); + let kwargs = FuncArgs::from(args.kwargs); + let base: &Py = + zelf.downcast_ref().expect("ImportError is a BaseException"); + let args = PyBaseException::init_args(base, args.args.into(), vm)?; + + // Validate keyword counts and names before changing native fields. + let parsed = ArgSpec { + fname: Self::NAME, + keywords: &["name", "path", "name_from"], + required: 0, + max_positional: 0, } + .parse(&kwargs, vm)?; - let msg = if args.args.len() == 1 { - Some(args.args[0].clone()) + let msg = if args.len() == 1 { + Some(args[0].clone()) } else { None }; - let base_args = FuncArgs::new(args.args, KwArgs::default()); - PyBaseException::slot_init(zelf, base_args, vm)?; let exc: &Py = zelf .downcast_ref() .expect("ImportError instance has ImportError payload"); - exc.name.swap_to_temporary_refs(name, vm); - exc.path.swap_to_temporary_refs(path, vm); - exc.name_from.swap_to_temporary_refs(name_from, vm); + exc.name.swap_to_temporary_refs(parsed[0].clone(), vm); + exc.path.swap_to_temporary_refs(parsed[1].clone(), vm); + exc.name_from.swap_to_temporary_refs(parsed[2].clone(), vm); exc.msg.swap_to_temporary_refs(msg, vm); Ok(()) } @@ -2187,6 +2478,11 @@ pub(super) mod types { } } + #[pyexception(name, base = PyImportError, ctx = "import_cycle_error", impl)] + #[derive(Debug)] + #[repr(transparent)] + pub struct PyImportCycleError(PyImportError); + #[pyexception(name, base = PyImportError, ctx = "module_not_found_error", impl)] #[derive(Debug)] #[repr(transparent)] @@ -2210,13 +2506,10 @@ pub(super) mod types { #[pyexception] impl PyKeyError { #[pymethod] - fn __str__(zelf: &Py, vm: &VirtualMachine) -> PyStrRef { + fn __str__(zelf: &Py, vm: &VirtualMachine) -> PyResult { let args = zelf.args(); - if args.as_slice().len() == 1 { - vm.exception_args_as_string(&args, false) - .into_iter() - .exactly_one() - .unwrap() + if let [arg] = args.as_slice() { + arg.repr(vm) } else { zelf.__str__(vm) } @@ -2239,19 +2532,9 @@ pub(super) mod types { self.0.0.traverse(tracer_fn); } + /// Delegates cycle breaking to the shared base-exception payload. fn clear(&mut self, out: &mut Vec) { - let base = &mut self.0.0; - if let Some(traceback) = base.traceback.get_mut().take() { - out.push(traceback.into()); - } - - if let Some(cause) = base.cause.get_mut().take() { - out.push(cause.into()); - } - - if let Some(context) = base.context.get_mut().take() { - out.push(context.into()); - } + self.0.0.clear(out); } } @@ -2263,7 +2546,8 @@ pub(super) mod types { name: PyAtomicRef>, } - impl crate::class::PySubclass for PyNameError { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PyNameError { type Base = PyException; fn as_base(&self) -> &Self::Base { &self.base @@ -2304,26 +2588,26 @@ pub(super) mod types { type Args = FuncArgs; fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { // Only 'name' kwarg is allowed - let mut kwargs = args.kwargs.clone(); - let name = kwargs.swap_remove("name"); - - // Reject unknown kwargs - if let Some(invalid_key) = kwargs.keys().next() { - return Err(vm.new_unexpected_keyword_type_error( - Some(Self::NAME), - &invalid_key.to_string(), - )); - } - + let kwargs = FuncArgs::from(args.kwargs); // Pass args without kwargs to BaseException_init - let base_args = FuncArgs::new(args.args, KwArgs::default()); - PyBaseException::slot_init(zelf, base_args, vm)?; + let base: &Py = + zelf.downcast_ref().expect("NameError is a BaseException"); + let _args = PyBaseException::init_args(base, args.args.into(), vm)?; + + // Reject unknown kwargs after publishing args. + let parsed = ArgSpec { + fname: Self::NAME, + keywords: &["name"], + required: 0, + max_positional: 0, + } + .parse(&kwargs, vm)?; let exc: &Py = zelf .downcast_ref() .expect("NameError instance has NameError payload"); // Absent keyword clears the field. Re-init must not keep the old name. - exc.name.swap_to_temporary_refs(name, vm); + exc.name.swap_to_temporary_refs(parsed[0].clone(), vm); Ok(()) } @@ -2357,7 +2641,8 @@ pub(super) mod types { written: AtomicCell, } - impl crate::class::PySubclass for PyOSError { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PyOSError { type Base = PyException; fn as_base(&self) -> &Self::Base { &self.base @@ -2371,11 +2656,9 @@ pub(super) mod types { } unsafe impl Traverse for PyOSError { + /// Visits base-exception references and the operating-system error's object fields. fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { - // `self.base` is a `PyException` newtype whose `MaybeTraverse` is a - // no-op; reach the underlying `PyBaseException` so its traceback, - // cause, context and args are visited by the collector. - self.base.0.traverse(tracer_fn); + self.base.traverse(tracer_fn); if let Some(obj) = self.errno.deref() { tracer_fn(obj); } @@ -2462,7 +2745,7 @@ pub(super) mod types { // We need this method, because of how `CPython` copies `init` // from `BaseException` in `SimpleExtendsException` macro. // See: `BaseException_new` - if *cls.name() == *vm.ctx.exceptions.os_error.name() { + if cls.is(vm.ctx.exceptions.os_error) { let args_vec = args.args.to_vec(); let len = args_vec.len(); if (2..=5).contains(&len) { @@ -2692,7 +2975,7 @@ pub(super) mod types { // fallback to BaseException.__str__ let base: &Py = zelf.downcast_ref().expect("OSError is a BaseException"); - Ok(base.__str__(vm)) + base.__str__(vm) } #[pymethod] @@ -2720,7 +3003,9 @@ pub(super) mod types { .filter(|f| !vm.is_none(f)); let winerror: Option = cfg_select! { - windows => obj.get_attr("winerror", vm).ok().filter(|w| !vm.is_none(w)), + windows => { + obj.get_attr("winerror", vm).ok().filter(|w| !vm.is_none(w)) + } _ => None, }; @@ -2927,7 +3212,8 @@ pub(super) mod types { metadata: PyAtomicRef>, } - impl crate::class::PySubclass for PySyntaxError { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PySyntaxError { type Base = PyException; fn as_base(&self) -> &Self::Base { &self.base @@ -3230,7 +3516,8 @@ pub(super) mod types { reason: PyAtomicRef>, } - impl crate::class::PySubclass for PyUnicodeError { + // SAFETY: pyexception checks the base field offset, payload offset, and alignment. + unsafe impl crate::class::PySubclass for PyUnicodeError { type Base = PyValueError; fn as_base(&self) -> &Self::Base { &self.base @@ -3614,6 +3901,8 @@ fn check_except_star_type_valid(match_type: &PyObject, vm: &VirtualMachine) -> P /// Match exception against except* handler type. /// Returns (rest, match) tuple. +/// A caller matching a naked exception must attach the handler-frame +/// traceback to the resulting wrapper before exposing it. pub fn exception_group_match( exc_value: &PyObject, match_type: &PyObject, @@ -3636,18 +3925,10 @@ pub fn exception_group_match( let matched = if is_eg { exc_value.to_owned() } else { - // Naked exception - wrap it in ExceptionGroup + // Naked exception: let BaseExceptionGroup choose the group type. let excs = vm.ctx.new_tuple(vec![exc_value.to_owned()]); - let eg_type: PyObjectRef = crate::exception_group::exception_group().to_owned().into(); - let wrapped = eg_type.call((vm.ctx.new_str(""), excs), vm)?; - // Copy traceback from original exception - if let Ok(exc) = exc_value.to_owned().downcast::() - && let Some(tb) = exc.traceback() - && let Ok(wrapped_exc) = wrapped.clone().downcast::() - { - wrapped_exc.set_traceback(Some(tb)); - } - wrapped + let eg_type: PyObjectRef = vm.ctx.exceptions.base_exception_group.to_owned().into(); + eg_type.call((vm.ctx.new_str(""), excs), vm)? }; return Ok((vm.ctx.none(), matched)); } @@ -3742,9 +4023,9 @@ pub fn prep_reraise_star(orig: &PyObject, excs: &PyObject, vm: &VirtualMachine) return Ok(raised.into_iter().next().unwrap()); } - // Create new ExceptionGroup for multiple exceptions + // Let BaseExceptionGroup select ExceptionGroup when all children permit it. let excs_tuple = vm.ctx.new_tuple(raised); - let eg_type: PyObjectRef = crate::exception_group::exception_group().to_owned().into(); + let eg_type: PyObjectRef = vm.ctx.exceptions.base_exception_group.to_owned().into(); eg_type.call((vm.ctx.new_str(""), excs_tuple), vm) } diff --git a/crates/vm/src/format.rs b/crates/vm/src/format.rs index d95def76813..4c9b93bab09 100644 --- a/crates/vm/src/format.rs +++ b/crates/vm/src/format.rs @@ -1,9 +1,6 @@ use crate::{ - PyObject, PyResult, VirtualMachine, - builtins::PyBaseExceptionRef, - convert::{IntoPyException, ToPyException}, - function::FuncArgs, - stdlib::builtins, + PyObject, PyResult, VirtualMachine, builtins::PyBaseExceptionRef, convert::ToPyException, + function::FuncArgs, stdlib::builtins, }; use crate::common::format::*; @@ -18,7 +15,12 @@ pub(crate) fn get_locale_info() -> LocaleInfo { reason = "libc::c_char is not u8 on all platforms" )] let mut grouping = lc.grouping.iter().map(|&c| c as u8).collect::>(); - if !grouping.is_empty() { + // A CHAR_MAX terminator is already in the list; otherwise restore the NUL. + if lc + .grouping + .last() + .is_some_and(|&c| c != core::ffi::c_char::MAX) + { grouping.push(0); } LocaleInfo { @@ -41,63 +43,70 @@ pub(crate) fn get_locale_info() -> LocaleInfo { } } -impl IntoPyException for FormatSpecError { - fn into_pyexception(self, vm: &VirtualMachine) -> PyBaseExceptionRef { - match self { - Self::DecimalDigitsTooMany => { - vm.new_value_error("Too many decimal digits in format string") - } - Self::PrecisionTooBig => vm.new_value_error("Precision too big"), - Self::PrecisionMissing => vm.new_value_error("Format specifier missing precision"), - Self::InvalidFormatSpecifier => vm.new_value_error("Invalid format specifier"), - Self::UnspecifiedFormat(c1, c2) => { - let msg = format!("Cannot specify '{c1}' with '{c2}'."); - vm.new_value_error(msg) - } - Self::ExclusiveFormat(c1, c2) => { - let msg = format!("Cannot specify both '{c1}' and '{c2}'."); - vm.new_value_error(msg) - } - Self::UnknownFormatCode(c, s) => { - let msg = format!("Unknown format code '{c}' for object of type '{s}'"); - vm.new_value_error(msg) - } - Self::PrecisionNotAllowed => { - vm.new_value_error("Precision not allowed in integer format specifier") - } - Self::NotAllowed(s) => { - let msg = format!("{s} not allowed with integer format specifier 'c'"); - vm.new_value_error(msg) - } - Self::UnableToConvert => vm.new_value_error("Unable to convert int to float"), - Self::CodeNotInRange => vm.new_overflow_error("%c arg not in range(0x110000)"), - Self::IntTooLargeForCLong => { - vm.new_overflow_error("Python int too large to convert to C long") - } - Self::ZeroPadding => { - vm.new_value_error("Zero padding is not allowed in complex format specifier") - } - Self::AlignmentFlag => { - vm.new_value_error("'=' alignment flag is not allowed in complex format specifier") - } - Self::NegativeZeroCoercionNotAllowed(type_name) => { - let msg = format!( - "Negative zero coercion (z) not allowed in {type_name} format specifier" - ); - vm.new_value_error(msg) - } - Self::StringAlignmentFlag => { - vm.new_value_error("'=' alignment not allowed in string format specifier") - } - Self::StringSpecNotAllowed(s) => { - let msg = format!("{s} not allowed in string format specifier"); - vm.new_value_error(msg) - } - Self::NotImplemented(c, s) => { - let msg = format!("Format code '{c}' for object of type '{s}' not implemented yet"); - vm.new_value_error(msg) - } +pub(crate) fn parse_format_spec( + object: &PyObject, + spec: &str, + vm: &VirtualMachine, +) -> PyResult { + FormatSpec::parse(spec).map_err(|err| format_spec_error(err, object, spec, vm)) +} + +pub(crate) fn format_spec_error( + err: FormatSpecError, + object: &PyObject, + spec: &str, + vm: &VirtualMachine, +) -> PyBaseExceptionRef { + match err { + FormatSpecError::InvalidFormatSpecifier => vm.new_value_error(format!( + "Invalid format specifier '{spec}' for object of type '{}'", + object.class().name() + )), + FormatSpecError::DecimalDigitsTooMany => { + vm.new_value_error("Too many decimal digits in format string") + } + FormatSpecError::PrecisionTooBig => vm.new_value_error("Precision too big"), + FormatSpecError::PrecisionMissing => { + vm.new_value_error("Format specifier missing precision") + } + FormatSpecError::UnspecifiedFormat(c1, c2) => { + vm.new_value_error(format!("Cannot specify '{c1}' with '{c2}'.")) + } + FormatSpecError::ExclusiveFormat(c1, c2) => { + vm.new_value_error(format!("Cannot specify both '{c1}' and '{c2}'.")) + } + FormatSpecError::UnknownFormatCode(c, s) => vm.new_value_error(format!( + "Unknown format code '{c}' for object of type '{s}'" + )), + FormatSpecError::PrecisionNotAllowed => { + vm.new_value_error("Precision not allowed in integer format specifier") + } + FormatSpecError::NotAllowed(s) => { + vm.new_value_error(format!("{s} not allowed with integer format specifier 'c'")) + } + FormatSpecError::UnableToConvert => vm.new_value_error("Unable to convert int to float"), + FormatSpecError::CodeNotInRange => vm.new_overflow_error("%c arg not in range(0x110000)"), + FormatSpecError::IntTooLargeForCLong => { + vm.new_overflow_error("Python int too large to convert to C long") + } + FormatSpecError::ZeroPadding => { + vm.new_value_error("Zero padding is not allowed in complex format specifier") + } + FormatSpecError::AlignmentFlag => { + vm.new_value_error("'=' alignment flag is not allowed in complex format specifier") } + FormatSpecError::NegativeZeroCoercionNotAllowed(type_name) => vm.new_value_error(format!( + "Negative zero coercion (z) not allowed in {type_name} format specifier" + )), + FormatSpecError::StringAlignmentFlag => { + vm.new_value_error("'=' alignment not allowed in string format specifier") + } + FormatSpecError::StringSpecNotAllowed(s) => { + vm.new_value_error(format!("{s} not allowed in string format specifier")) + } + FormatSpecError::NotImplemented(c, s) => vm.new_value_error(format!( + "Format code '{c}' for object of type '{s}' not implemented yet" + )), } } @@ -110,6 +119,7 @@ impl ToPyException for FormatParseError { Self::UnmatchedBracket | Self::MissingRightBracket => { vm.new_value_error("expected '}' before end of string") } + Self::MissingRightSquareBracket => vm.new_value_error("Missing ']' in format string"), Self::MissingStartBracket => { vm.new_value_error("Single '}' encountered in format string") } @@ -121,11 +131,13 @@ impl ToPyException for FormatParseError { vm.new_value_error("Single '{' encountered in format string") } Self::InvalidFormatSpecifier => vm.new_value_error("unmatched '{' in format spec"), - // Reached both for a conversion that is not one character (`{0!xy}`, - // where CPython says "expected ':' after conversion specifier") and for - // an empty one (`{0!}`, "unmatched '{' in format spec"). Telling those - // apart needs the parser to say which, so the generic message stays. - Self::UnknownConversion => vm.new_value_error("Unexpected error parsing format string"), + Self::MissingConversion => { + vm.new_value_error("end of string while looking for conversion specifier") + } + Self::MissingConversionColon => { + vm.new_value_error("expected ':' after conversion specifier") + } + Self::UnexpectedStartBracket => vm.new_value_error("unexpected '{' in field name"), Self::EmptyAttribute => vm.new_value_error("Empty attribute in format string"), Self::InvalidCharacterAfterRightBracket => { vm.new_value_error("Only '.' or '[' may follow ']' in format field specifier") @@ -140,6 +152,7 @@ impl ToPyException for FormatParseError { fn format_internal( vm: &VirtualMachine, format: &FormatString, + recursion_depth: usize, field_func: &mut impl FnMut(FieldType) -> PyResult, ) -> PyResult { let mut final_string = Wtf8Buf::new(); @@ -151,13 +164,13 @@ fn format_internal( conversion_spec, format_spec, } => { - let FieldName { field_type, parts } = - FieldName::parse(field_name).map_err(|e| e.to_pyexception(vm))?; + let (field_type, parts) = + FieldName::split(field_name).map_err(|e| e.to_pyexception(vm))?; let mut argument = field_func(field_type)?; for name_part in parts { - match name_part { + match name_part.map_err(|e| e.to_pyexception(vm))? { FieldNamePart::Attribute(attribute) => { argument = argument.get_attr(&vm.ctx.new_str(attribute), vm)?; } @@ -170,10 +183,6 @@ fn format_internal( } } - let nested_format = - FormatString::from_str(format_spec).map_err(|e| e.to_pyexception(vm))?; - let format_spec = format_internal(vm, &nested_format, field_func)?; - let argument = match conversion_spec { None => argument, Some(c) => match FormatConversion::from_char(*c) { @@ -188,8 +197,23 @@ fn format_internal( }, }; + let expanded_spec; + let format_spec = if format_spec.contains("{".as_ref()) { + // Only replacement-bearing specs consume the expansion budget. + if recursion_depth == 1 { + return Err(vm.new_value_error("Max string recursion exceeded")); + } + let nested_format = + FormatString::from_str(format_spec).map_err(|e| e.to_pyexception(vm))?; + expanded_spec = + format_internal(vm, &nested_format, recursion_depth - 1, field_func)?; + &expanded_spec + } else { + format_spec + }; + // FIXME: compiler can intern specs using parser tree. Then this call can be interned_str - pystr = vm.format(&argument, vm.ctx.new_str(format_spec))?; + pystr = vm.format(&argument, vm.ctx.new_str(format_spec.clone()))?; pystr.as_wtf8() } FormatPart::Literal(literal) => literal, @@ -206,7 +230,7 @@ pub(crate) fn format( ) -> PyResult { let mut auto_argument_index: usize = 0; let mut seen_index = false; - format_internal(vm, format, &mut |field_type| match field_type { + format_internal(vm, format, 2, &mut |field_type| match field_type { FieldType::Auto => { if seen_index { return Err(vm.new_value_error( @@ -247,7 +271,7 @@ pub(crate) fn format_map( dict: &PyObject, vm: &VirtualMachine, ) -> PyResult { - format_internal(vm, format, &mut |field_type| match field_type { + format_internal(vm, format, 2, &mut |field_type| match field_type { FieldType::Auto | FieldType::Index(_) => { Err(vm.new_value_error("Format string contains positional fields")) } diff --git a/crates/vm/src/frame.rs b/crates/vm/src/frame.rs index cc54ad6ee18..91cc0bfc92d 100644 --- a/crates/vm/src/frame.rs +++ b/crates/vm/src/frame.rs @@ -6,9 +6,10 @@ use crate::{ AsObject, Py, PyExact, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, PyStackRef, TryFromObject, VirtualMachine, builtins::{ - PyBaseException, PyBaseExceptionRef, PyBaseObject, PyCode, PyCoroutine, PyDict, PyDictRef, - PyFloat, PyFrozenSet, PyGenerator, PyInt, PyInterpolation, PyList, PyModule, PyProperty, - PySet, PySlice, PyStr, PyStrInterned, PyTemplate, PyTraceback, PyType, PyUtf8Str, + PyAnyDict, PyBaseException, PyBaseExceptionRef, PyBaseObject, PyBytes, PyCode, PyCoroutine, + PyDict, PyDictRef, PyFloat, PyFrozenSet, PyGenerator, PyInt, PyInterpolation, PyList, + PyModule, PyProperty, PySet, PySlice, PyStr, PyStrInterned, PyTemplate, PyTraceback, + PyType, PyUtf8Str, builtin_func::PyNativeFunction, descriptor::{PyMemberDescriptor, PyMethodDescriptor}, frame::stack_analysis, @@ -18,12 +19,14 @@ use crate::{ tuple::{PyTuple, PyTupleIterator, PyTupleRef}, }, bytecode::{ - self, ADAPTIVE_COOLDOWN_VALUE, Instruction, LoadAttr, LoadSuperAttr, Opcode, SpecialMethod, + self, ADAPTIVE_COOLDOWN_VALUE, Instruction, LoadAttr, LoadGlobal, LoadSuperAttr, Opcode, + SpecialMethod, + oparg::{ResumeContext, ResumeLocation}, }, convert::{ToPyObject, ToPyResult}, coroutine::Coro, exceptions::ExceptionCtor, - function::{ArgMapping, Callee, Either, FuncArgs, KwArgs, PyMethodFlags}, + function::{ArgMapping, Callee, Either, FuncArgs, PyMethodFlags}, object::PyAtomicBorrow, object::{Traverse, TraverseFn}, protocol::{PyIter, PyIterReturn}, @@ -48,12 +51,32 @@ use num_traits::{ToPrimitive, Zero}; use rustpython_common::atomic::{PyAtomic, Radium}; use rustpython_common::{ lock::{OnceCell, PyMutex}, - wtf8::{Wtf8, Wtf8Buf, wtf8_concat}, + wtf8::{Wtf8Buf, wtf8_concat}, }; use rustpython_compiler_core::{OneIndexed, SourceLocation}; pub type FrameObjectRef = PyRef; +// CALL_FUNCTION_EX keeps its original containers until a non-Python callable +// returns. Exact Python functions instead transfer their arguments to locals. +// A converted iterable needs only its value storage, not a new tuple object. +struct ExCallOwners { + kwargs: Option, + positional: Either>, +} + +impl ExCallOwners { + fn release(self) { + // Close kwargs before callargs. Tuple elements are released + // in reverse order, including the values of a normalized *iterable. + drop(self.kwargs); + match self.positional { + Either::A(tuple) => drop(tuple), + Either::B(values) => values.into_iter().rev().for_each(drop), + } + } +} + // -- Frame chain utilities -- // The frame chain is a singly-linked list of `*const InterpreterFrame` stored // as `usize` values in `InterpreterFrame.previous` and the TLS @@ -104,10 +127,44 @@ pub fn current_thread_frame_materialize(vm: &VirtualMachine) -> Option *const InterpreterFrame { + while !current.is_null() { + // SAFETY: the caller guarantees the chain remains alive. + let frame = unsafe { &*current }; + if !frame.is_incomplete() { + break; + } + current = frame.previous(); + } + current +} + +/// Resolve the active frame for a legacy trace/profile callback, skipping +/// incomplete generator-creation frames before materializing a frame object. +/// Raw execution-chain users deliberately keep seeing the actual active frame. +pub(crate) fn current_complete_frame_for_trace(vm: &VirtualMachine) -> Option { + // SAFETY: synchronous inspection of the current thread's active chain. + let current = unsafe { first_complete_iframe(crate::vm::thread::get_current_frame()) }; + if current.is_null() { + return None; + } + // SAFETY: the selected frame is alive on this thread's execution chain. + Some(unsafe { (*current).materialize(vm).to_owned() }) +} + /// Read the globals dict from the topmost frame on this thread's chain. /// Returns `None` if the chain is empty. #[must_use] -pub fn current_globals() -> Option { +pub fn current_globals() -> Option> { let ptr = crate::vm::thread::get_current_frame(); if ptr.is_null() { return None; @@ -136,12 +193,13 @@ pub fn current_builtins() -> Option { Some(unsafe { (*ptr).builtins().to_owned() }) } -/// The frame `offset` positions below the current thread's top frame (offset 0 -/// is the top), or `None` if the stack is not that deep. +/// The complete frame `offset` positions below the current thread's first +/// complete frame, or `None` if the stack is not that deep. /// Materializes the FrameObject on demand for stack-allocated frames. #[must_use] pub fn frame_at_offset(offset: usize, vm: &VirtualMachine) -> Option { - let mut cur = crate::vm::thread::get_current_frame(); + // SAFETY: synchronous inspection of this thread's active chain. + let mut cur = unsafe { first_complete_iframe(crate::vm::thread::get_current_frame()) }; let mut remaining = offset; while !cur.is_null() { if remaining == 0 { @@ -149,7 +207,8 @@ pub fn frame_at_offset(offset: usize, vm: &VirtualMachine) -> Option, pub(crate) func_obj: *const PyObject, // nullable - pub(crate) globals: *const Py, + pub(crate) globals: *const PyAnyDict, pub(crate) builtins: *const PyObject, /// Unified storage for local variables and evaluation stack. @@ -982,7 +1040,7 @@ impl InterpreterFrame { #[inline(always)] pub(crate) unsafe fn new( code: &Py, - globals: &Py, + globals: &PyAnyDict, builtins: &PyObject, func_obj: Option<&PyObject>, localsplus: LocalsPlus, @@ -1026,7 +1084,7 @@ impl InterpreterFrame { Some(obj) => obj as *const PyObject, None => core::ptr::null(), }, - globals: globals as *const Py, + globals: globals as *const PyAnyDict, builtins: builtins as *const PyObject, localsplus, locals, @@ -1059,7 +1117,7 @@ impl InterpreterFrame { #[inline(always)] pub(crate) unsafe fn new_on_datastack<'a>( code: &Py, - globals: &Py, + globals: &PyAnyDict, builtins: &PyObject, func_obj: Option<&PyObject>, locals: FrameLocals, @@ -1154,6 +1212,19 @@ impl InterpreterFrame { Some((base, total_bytes)) } + /// `_PyFrame_IsIncomplete`. A generator frame is complete even before its + /// first resume. Its owner is temporarily Thread while it executes, so the + /// owning generator's back-reference is checked too. + pub(crate) fn is_incomplete(&self) -> bool { + if FrameOwner::from_i8(self.owner.load(atomic::Ordering::Acquire)) == FrameOwner::Generator + || self.generator.load().is_some() + { + return false; + } + // lasti is one past the in-flight instruction. + (self.lasti.load(Relaxed) as usize) <= self.code().first_traceable + } + /// Get the last instruction index. #[inline(always)] pub fn get_lasti(&self) -> u32 { @@ -1227,10 +1298,43 @@ impl InterpreterFrame { #[cold] #[inline(never)] pub(crate) unsafe fn materialize_detached_chain(&self, vm: &VirtualMachine) -> FrameObjectRef { + // SAFETY: forwarded unchanged from this method's contract. + unsafe { self.materialize_detached_chain_impl::(vm) } + } + + /// Copy the complete ancestors used by Python-visible `f_back` traversal. + /// The raw snapshot path above deliberately preserves every active node. + /// + /// # Safety + /// The caller must hold the world stopped and select a complete top frame. + #[cfg(feature = "threading")] + #[cold] + #[inline(never)] + pub(crate) unsafe fn materialize_complete_detached_chain( + &self, + vm: &VirtualMachine, + ) -> FrameObjectRef { + // SAFETY: forwarded unchanged from this method's contract. + unsafe { self.materialize_detached_chain_impl::(vm) } + } + + #[cfg(feature = "threading")] + #[cold] + unsafe fn materialize_detached_chain_impl( + &self, + vm: &VirtualMachine, + ) -> FrameObjectRef { let top = unsafe { self.materialize_detached(vm) }; let mut child = top.clone(); let mut cur = self.previous(); - while !cur.is_null() { + loop { + if SKIP_INCOMPLETE { + // SAFETY: the caller holds the owning thread stopped. + cur = unsafe { first_complete_iframe(cur) }; + } + if cur.is_null() { + break; + } let caller = unsafe { &*cur }; let caller_fo = unsafe { caller.materialize_detached(vm) }; { @@ -1265,7 +1369,7 @@ impl InterpreterFrame { // Create a full FrameObject with its own InterpreterFrame copy. // The FrameObject owns references to the same objects (code, globals, etc). let code: PyRef = self.code().to_owned(); - let globals: PyDictRef = self.globals().to_owned(); + let globals = self.globals().to_owned(); let builtins: PyObjectRef = self.builtins().to_owned(); let func_obj: Option = self.func_obj().map(|o| o.to_owned()); @@ -1361,7 +1465,7 @@ impl InterpreterFrame { #[cold] fn materialize_slow_chain(&self, vm: &VirtualMachine) -> FrameObjectRef { let code: PyRef = self.code().to_owned(); - let globals: PyDictRef = self.globals().to_owned(); + let globals = self.globals().to_owned(); let builtins: PyObjectRef = self.builtins().to_owned(); let func_obj: Option = self.func_obj().map(|o| o.to_owned()); @@ -1418,7 +1522,7 @@ impl InterpreterFrame { /// Borrowed globals dict. #[inline(always)] - pub fn globals(&self) -> &Py { + pub fn globals(&self) -> &PyAnyDict { // SAFETY: established by `new` / `init_iframe_ptrs`. unsafe { &*self.globals } } @@ -1527,13 +1631,13 @@ impl InterpreterFrame { #[pyclass(module = false, name = "frame", traverse = "manual")] pub struct FrameObject { // The executing iframe reads this when it points at the frame object. - #[pymember(name = "f_trace_lines", writable)] + #[pymember(writable)] pub(crate) f_trace_lines: core::sync::atomic::AtomicBool, // Owned references — keep the pointed-to objects alive for InterpreterFrame's // raw pointers. Wrapped in Option so Traverse::clear can release them, // allowing GC cycle collection to reclaim referenced objects. pub(crate) owned_code: Option>, - pub(crate) owned_globals: Option, + pub(crate) owned_globals: Option>, pub(crate) owned_builtins: Option, pub(crate) owned_func_obj: Option, @@ -1755,6 +1859,7 @@ pub enum ExecutionResult { /// CACHE <- the parked frame's lasti is here + 1 /// YIELD_VALUE 1 /// resumed_at: RESUME +/// CACHE /// JUMP_BACKWARD_NO_INTERRUPT -> send_idx /// exit: END_SEND /// ``` @@ -1816,7 +1921,7 @@ impl FrameObject { let locals = match scope.locals { Some(locals) => FrameLocals::with_locals(locals), None if code.flags.contains(bytecode::CodeFlags::NEWLOCALS) => FrameLocals::lazy(), - None => FrameLocals::with_locals(ArgMapping::from_dict_exact(scope.globals.clone())), + None => FrameLocals::with_locals(ArgMapping::from_anydict_exact(scope.globals.clone())), }; // Pointers are initially set from owned fields' references but will be @@ -1852,7 +1957,7 @@ impl FrameObject { fn init_iframe_ptrs(self_: &Py) { let iframe = unsafe { self_.iframe_mut() }; iframe.code = &**self_.owned_code.as_ref().unwrap() as *const Py; - iframe.globals = &**self_.owned_globals.as_ref().unwrap() as *const Py; + iframe.globals = &**self_.owned_globals.as_ref().unwrap() as *const PyAnyDict; iframe.builtins = &**self_.owned_builtins.as_ref().unwrap() as *const PyObject; iframe.func_obj = match &self_.owned_func_obj { Some(obj) => &**obj as *const PyObject, @@ -1945,8 +2050,7 @@ impl FrameObject { if localsplus.stack_is_empty() { return; } - let refs = localsplus.take_stack_object_refs(); - drop(refs); + let _refs = localsplus.take_stack_object_refs(); } /// Clear locals and stack after generator/coroutine close. @@ -2496,7 +2600,7 @@ impl Py { }, ) }; - let builtins_dict = if globals.class().is(vm.ctx.types.dict_type) { + let builtins_dict = if globals.as_object().class().is(vm.ctx.types.dict_type) { builtins .downcast_ref_if_exact::(vm) // SAFETY: downcast_ref_if_exact already verified exact type @@ -2528,6 +2632,18 @@ impl Py { self.with_exec(vm, |mut exec| exec.run(vm)) } + /// Execute the eager generator preamble and suspend immediately after + /// RETURN_GENERATOR. The caller links this frame with `vm.with_generator_frame`. + /// The first resume supplies the value consumed by the following POP_TOP. + pub(crate) fn prepare_generator(&self, vm: &VirtualMachine) -> PyResult<()> { + self.with_exec(vm, |mut exec| match exec.run_until::(vm)? { + None => Ok(()), + Some(_) => { + Err(vm.new_runtime_error("generator preamble did not reach RETURN_GENERATOR")) + } + }) + } + /// Resume a suspended generator or coroutine body, pushing `value` as the /// result of the `yield` it stopped at. /// @@ -2568,45 +2684,14 @@ impl Py { self.with_exec(vm, |mut exec| exec.gen_throw(vm, exc_type, exc_val, exc_tb)) } - pub fn yield_from_target(&self) -> Option { - // If the frame is currently executing (owned by thread), it has no - // yield-from target to report. - let owner = FrameOwner::from_i8(self.iframe().owner.load(atomic::Ordering::Acquire)); - if owner == FrameOwner::Thread { - return None; - } - // SAFETY: FrameObject is not executing, so UnsafeCell access is safe. - let iframe = unsafe { self.iframe_mut() }; - // SAFETY: established by `new` / `init_iframe_ptrs`. - let (code, globals, builtins, func_obj) = unsafe { - ( - &*iframe.code, - &*iframe.globals, - &*iframe.builtins, - if iframe.func_obj.is_null() { - None - } else { - Some(&*iframe.func_obj) - }, - ) - }; - let iframe_ptr = iframe as *const InterpreterFrame; - let exec = ExecutingFrame { - code, - localsplus: &mut iframe.localsplus, - locals: &iframe.locals, - globals, - builtins, - builtins_dict: None, - lasti: &iframe.lasti, - iframe: iframe_ptr, - func_obj, - prev_line: &iframe.prev_line, - monitoring_mask: 0, - flatten: Flatten::Nothing, - call_traced: false, - }; - exec.yield_from_target().map(PyObject::to_owned) + /// Read the delegate without constructing a mutable executing-frame view. + /// + /// # Safety + /// Caller must hold the owning Coro's inspection claim and verify it is not + /// closed. This excludes execution and retirement while the stack is read. + pub(crate) unsafe fn yield_from_target(&self) -> Option { + let iframe = self.iframe(); + suspended_delegate(iframe.code(), &iframe.localsplus, self.lasti()).map(PyObject::to_owned) } pub fn is_internal_frame(&self) -> bool { @@ -2632,7 +2717,7 @@ impl Py { /// 0 doubles as "no thread", which is what `attached_tid` wants for a build /// that cannot have a frame running anywhere else. #[inline] -fn current_thread_ident() -> u64 { +pub(crate) fn current_thread_ident() -> u64 { #[cfg(feature = "threading")] { crate::stdlib::_thread::get_ident() @@ -2738,7 +2823,7 @@ fn exec_iframe<'a>( }, ) }; - let builtins_dict = if globals.class().is(vm.ctx.types.dict_type) { + let builtins_dict = if globals.as_object().class().is(vm.ctx.types.dict_type) { builtins .downcast_ref_if_exact::(vm) .map(|d| unsafe { PyExact::ref_unchecked(d) }) @@ -2787,10 +2872,10 @@ pub(crate) fn gen_collapse_allowed(vm: &VirtualMachine) -> bool { /// delegating to, if the trampoline can resume it in this frame's place. /// /// Recognizes the shape documented on [`GenCont`] — `lasti` at the `RESUME` -/// that follows the delegating `YIELD_VALUE`, with the delegate on top of the -/// stack — and requires the `SEND` to have already specialized to `SendGen`, -/// so that a `Send` still collecting specialization feedback keeps running -/// normally. The frame is left untouched; `park_at_send` commits to it. +/// that follows the delegating `YIELD_VALUE`, with the delegate below its +/// index-or-NULL stack slot — and requires the `SEND` to have already +/// specialized to `SendGen`, so that a `Send` still collecting feedback keeps +/// running normally. The frame is left untouched; `park_at_send` commits to it. pub(crate) fn yield_from_delegate( iframe: &InterpreterFrame, vm: &VirtualMachine, @@ -2823,10 +2908,11 @@ pub(crate) fn yield_from_delegate( { return None; } - let delegate = match iframe.localsplus.stack_last() { - Some(Some(top)) => top.as_object(), - _ => return None, - }; + let stack = iframe.localsplus.stack_as_slice(); + let delegate = stack + .get(stack.len().checked_sub(2)?)? + .as_ref()? + .as_object(); // The same guards `SendGen` applies before resuming a generator itself. if delegate.downcast_ref_if_exact::(vm).is_none() && delegate.downcast_ref_if_exact::(vm).is_none() @@ -2930,7 +3016,7 @@ pub(crate) struct ExecutingFrame<'a> { code: &'a Py, localsplus: &'a mut LocalsPlus, locals: &'a FrameLocals, - globals: &'a Py, + globals: &'a PyAnyDict, builtins: &'a PyObject, /// Cached downcast of builtins to PyDict for fast LOAD_GLOBAL. /// Only set when both globals and builtins are exact dict types (not @@ -3071,7 +3157,8 @@ pub(crate) fn release_datastack_frame(frame: &Py, vm: &VirtualMachi { let mut guard = frame.iframe().cold().retained_back.lock(); if guard.is_none() { - let prev = frame.previous_iframe(); + // SAFETY: this frame is returning into its still-active caller. + let prev = unsafe { first_complete_iframe(frame.previous_iframe()) }; *guard = unsafe { owned_chain_frame(prev) }; } } @@ -3098,7 +3185,7 @@ pub(crate) fn release_datastack_frame(frame: &Py, vm: &VirtualMachi } type BinaryOpExtendGuard = fn(&PyObject, &PyObject, &VirtualMachine) -> bool; -type BinaryOpExtendAction = fn(&PyObject, &PyObject, &VirtualMachine) -> Option; +type BinaryOpExtendAction = fn(&PyObject, &PyObject, &VirtualMachine) -> Option; struct BinaryOpExtendSpecializationDescr { oparg: bytecode::BinaryOperator, @@ -3159,10 +3246,10 @@ struct FusedBoolJump { macro_rules! bitwise_longs_action { ($name:ident, $op:tt) => { #[inline] - fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { + fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { let lhs_val = compact_int_from_obj(lhs, vm)?; let rhs_val = compact_int_from_obj(rhs, vm)?; - Some(vm.ctx.new_int(lhs_val $op rhs_val).into()) + Some(Ok(vm.ctx.new_int(lhs_val $op rhs_val).into())) } }; } @@ -3184,10 +3271,10 @@ fn nonzero_float_compactlong_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualM macro_rules! float_long_action { ($name:ident, $op:tt) => { #[inline] - fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { + fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { let lhs_val = exact_float_from_obj(lhs, vm)?; let rhs_val = compact_int_from_obj(rhs, vm)?; - Some(vm.ctx.new_float(lhs_val $op rhs_val as f64).into()) + Some(Ok(vm.ctx.new_float(lhs_val $op rhs_val as f64).into())) } }; } @@ -3210,10 +3297,10 @@ fn nonzero_compactlong_float_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualM macro_rules! long_float_action { ($name:ident, $op:tt) => { #[inline] - fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { + fn $name(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { let lhs_val = compact_int_from_obj(lhs, vm)?; let rhs_val = exact_float_from_obj(rhs, vm)?; - Some(vm.ctx.new_float(lhs_val as f64 $op rhs_val).into()) + Some(Ok(vm.ctx.new_float(lhs_val as f64 $op rhs_val).into())) } }; } @@ -3222,7 +3309,108 @@ long_float_action!(compactlong_float_subtract, -); long_float_action!(compactlong_float_multiply, *); long_float_action!(compactlong_float_true_div, /); +fn sequence_int_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> bool { + (lhs.downcast_ref_if_exact::(vm).is_some() + || lhs.downcast_ref_if_exact::(vm).is_some() + || lhs.downcast_ref_if_exact::(vm).is_some()) + && rhs.downcast_ref_if_exact::(vm).is_some() +} + +fn int_sequence_guard(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> bool { + sequence_int_guard(rhs, lhs, vm) +} + +fn exact_sequence_int_guard( + lhs: &PyObject, + rhs: &PyObject, + vm: &VirtualMachine, +) -> bool { + lhs.downcast_ref_if_exact::(vm).is_some() && rhs.downcast_ref_if_exact::(vm).is_some() +} + +fn exact_int_sequence_guard( + lhs: &PyObject, + rhs: &PyObject, + vm: &VirtualMachine, +) -> bool { + exact_sequence_int_guard::(rhs, lhs, vm) +} + +fn sequence_int_multiply(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { + let count = rhs.downcast_ref_if_exact::(vm)?; + // CPython 3.15's specialized repetition uses PyLong_AsSsize_t, unlike + // the generic sequence dispatch's PyNumber_AsSsize_t conversion. + Some(match count.as_bigint().to_isize() { + Some(count) => lhs.sequence_unchecked().repeat(count, vm), + None => Err(vm.new_overflow_error("Python int too large to convert to C ssize_t")), + }) +} + +fn int_sequence_multiply(lhs: &PyObject, rhs: &PyObject, vm: &VirtualMachine) -> Option { + sequence_int_multiply(rhs, lhs, vm) +} + static BINARY_OP_EXTEND_DESCRIPTORS: &[BinaryOpExtendSpecializationDescr] = &[ + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::Multiply, + guard: exact_sequence_int_guard::, + action: sequence_int_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::Multiply, + guard: exact_int_sequence_guard::, + action: int_sequence_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::InplaceMultiply, + guard: exact_sequence_int_guard::, + action: sequence_int_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::InplaceMultiply, + guard: exact_int_sequence_guard::, + action: int_sequence_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::Multiply, + guard: exact_sequence_int_guard::, + action: sequence_int_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::Multiply, + guard: exact_int_sequence_guard::, + action: int_sequence_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::InplaceMultiply, + guard: exact_sequence_int_guard::, + action: sequence_int_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::InplaceMultiply, + guard: exact_int_sequence_guard::, + action: int_sequence_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::Multiply, + guard: exact_sequence_int_guard::, + action: sequence_int_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::Multiply, + guard: exact_int_sequence_guard::, + action: int_sequence_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::InplaceMultiply, + guard: exact_sequence_int_guard::, + action: sequence_int_multiply, + }, + BinaryOpExtendSpecializationDescr { + oparg: bytecode::BinaryOperator::InplaceMultiply, + guard: exact_int_sequence_guard::, + action: int_sequence_multiply, + }, // long-long arithmetic BinaryOpExtendSpecializationDescr { oparg: bytecode::BinaryOperator::Or, @@ -3338,7 +3526,11 @@ impl ExecutingFrame<'_> { /// (COPY_FREE_VARS / RETURN_GENERATOR that precede it are not a 'call', /// and later RESUMEs in a SEND loop are not a new call either). fn trace_call_from_resume(&mut self, vm: &VirtualMachine, resume_type: u32) -> PyResult<()> { - if self.call_traced { + // RESUME_AT_GEN_EXPR_START runs before the frame is complete. The + // first traceable instruction is the ordinary RESUME after creation. + if resume_type & ResumeContext::LOCATION_MASK == ResumeLocation::AtGenExprStart.as_u32() + || self.call_traced + { return Ok(()); } self.call_traced = true; @@ -3524,7 +3716,22 @@ impl ExecutingFrame<'_> { /// Matches `_PyEval_MonitorRaise` → `PY_MONITORING_EVENT_RAISE` → /// `sys_trace_exception_func` in legacy_tracing.c. fn fire_exception_trace(&self, exc: &Py, vm: &VirtualMachine) -> PyResult<()> { - if vm.use_tracing.get() && self.trace_is_set(vm) { + if !vm.use_tracing.get() { + return Ok(()); + } + let trace_is_set = if self.iframe().is_incomplete() { + // Legacy tracing resolves PyEval_GetFrame to the first complete + // caller while sys.monitoring continues to use this code object. + current_complete_frame_for_trace(vm).is_some_and(|frame| { + frame + .iframe() + .cold_opt() + .is_some_and(|cold| cold.trace.lock().is_some()) + }) + } else { + self.trace_is_set(vm) + }; + if trace_is_set { let exc_type: PyObjectRef = exc.class().to_owned().into(); let exc_value: PyObjectRef = exc.to_owned().into(); let exc_tb: PyObjectRef = exc @@ -3537,6 +3744,14 @@ impl ExecutingFrame<'_> { } fn run(&mut self, vm: &VirtualMachine) -> PyResult { + self.run_until::(vm) + .map(|result| result.expect("ordinary execution cannot stop at a generator preamble")) + } + + fn run_until( + &mut self, + vm: &VirtualMachine, + ) -> PyResult> { flame_guard!(format!( "FrameObject::run({obj_name})", obj_name = self.code.obj_name @@ -3579,7 +3794,7 @@ impl ExecutingFrame<'_> { // principle toggle it, because we refresh `tracing` below right // after that call returns (that cold path is only taken when // tracing was already on, so it costs nothing on the hot path). - let mut tracing = vm.use_tracing.get(); + let mut tracing = !PREPARE_GENERATOR && vm.use_tracing.get(); // Fire 'line' trace event when line number changes. // Only fire if this frame has a per-frame trace function set @@ -3593,7 +3808,9 @@ impl ExecutingFrame<'_> { && self.trace_lines_is_set() && !matches!( self.code.instructions.read_op(idx), - Instruction::Resume { .. } | Instruction::InstrumentedResume + Instruction::Resume { .. } + | Instruction::ResumeCheck + | Instruction::InstrumentedResume ) { let line = self.code.addr2line(idx as i32 * 2); @@ -3624,7 +3841,7 @@ impl ExecutingFrame<'_> { idx = lasti_cell.load(Relaxed) as usize; continue; } - Ok(Some(value)) => break Ok(value), + Ok(Some(value)) => break Ok(Some(value)), Err(e) => break Err(e), } } @@ -3632,7 +3849,7 @@ impl ExecutingFrame<'_> { // The trace callback may have toggled tracing (e.g. via // sys.settrace(None)); refresh before the opcode-trace check // below reuses this flag. - tracing = vm.use_tracing.get(); + tracing = !PREPARE_GENERATOR && vm.use_tracing.get(); // Trace callback may have changed lasti via set_f_lineno. // Re-read and restart the loop from the new position. if lasti_cell.load(Relaxed) != (idx as u32 + 1) { @@ -3679,7 +3896,10 @@ impl ExecutingFrame<'_> { && self.trace_opcodes_is_set() && !matches!( op.into(), - Opcode::Resume | Opcode::InstrumentedResume | Opcode::ExtendedArg + Opcode::Resume + | Opcode::ResumeCheck + | Opcode::InstrumentedResume + | Opcode::ExtendedArg ) { vm.trace_event(crate::protocol::TraceEvent::Opcode, None)?; @@ -3699,19 +3919,26 @@ impl ExecutingFrame<'_> { // the allocation that tripped the threshold. #[cfg(feature = "threading")] vm.run_scheduled_gc(); - Ok(()) + vm.raise_async_exception() } if vm.eval_breaker_tripped() - && let Err(exception) = eval_breaker_work(vm) + && let Err(exception) = { + let result = eval_breaker_work(vm); + // Signal handlers and scheduled GC callbacks may change + // profiling before this instruction is dispatched. + tracing = !PREPARE_GENERATOR && vm.use_tracing.get(); + result + } { #[cold] fn handle_signal_exception( frame: &mut ExecutingFrame<'_>, exception: PyBaseExceptionRef, idx: usize, + complete_frame: bool, vm: &VirtualMachine, ) -> FrameResult { - if let Some((loc, _end_loc)) = frame.code.locations.get(idx) { + if complete_frame && let Some((loc, _end_loc)) = frame.code.locations.get(idx) { let next = exception.traceback(); let new_traceback = PyTraceback::new( next, @@ -3730,10 +3957,10 @@ impl ExecutingFrame<'_> { }, ) } - match handle_signal_exception(self, exception, idx, vm) { + match handle_signal_exception(self, exception, idx, !PREPARE_GENERATOR, vm) { Ok(None) => {} Ok(Some(value)) => { - break Ok(value); + break Ok(Some(value)); } Err(exception) => { break Err(exception); @@ -3757,7 +3984,31 @@ impl ExecutingFrame<'_> { crate::opcode_histogram::record(prev_op, op_byte); prev_op = op_byte; } - let result = self.execute_instruction(op, arg, &mut do_extend_arg, vm); + if PREPARE_GENERATOR && matches!(op, Instruction::ReturnGenerator) { + // The generator takes over the frame with its instruction + // pointer advanced to POP_TOP. The iterator pair a generator + // expression pushed must outlive this execution borrow. + self.localsplus.promote_stack(); + break Ok(None); + } + // Native-call specializations bypass PyCallable's legacy profile + // events. Use the generic call only while tracing, without rewriting + // shared bytecode or touching the specialization's inline caches. + let result = if tracing + && matches!( + op, + Instruction::CallListAppend + | Instruction::CallLen + | Instruction::CallIsinstance + | Instruction::CallMethodDescriptorNoargs + | Instruction::CallMethodDescriptorO + | Instruction::CallMethodDescriptorFast + | Instruction::CallMethodDescriptorFastWithKeywords + ) { + self.execute_call_vectorcall(arg.into(), vm) + } else { + self.execute_instruction(op, arg, &mut do_extend_arg, vm) + }; // Skip inline cache entries if instruction fell through (no jump). // `cache_entries()` is a table lookup, so it is done here rather // than before dispatch: computing it up front kept the count live @@ -3772,70 +4023,64 @@ impl ExecutingFrame<'_> { match result { Ok(None) => {} Ok(Some(value)) => { - break Ok(value); + break Ok(Some(value)); } // Instruction raised an exception Err(exception) => { #[cold] - fn handle_exception( - frame: &mut ExecutingFrame<'_>, - exception: PyBaseExceptionRef, + fn prepare_exception( + frame: &ExecutingFrame<'_>, + exception: &Py, idx: usize, - is_reraise: bool, is_new_raise: bool, + complete_frame: bool, vm: &VirtualMachine, - ) -> FrameResult { - // 1. Extract traceback from exception's '__traceback__' attr. - // 2. Add new entry with current execution position (filename, lineno, code_object) to traceback. - // 3. First, try to find handler in exception table - - // RERAISE instructions should not add traceback entries - they're just - // re-raising an already-processed exception - if !is_reraise { - // Check if the exception already has traceback entries before - // we add ours. If it does, it was propagated from a callee - // function and we should not re-contextualize it. - let had_prior_traceback = exception.traceback().is_some(); - - // PyTraceBack_Here always adds a new entry without - // checking for duplicates. Each time an exception passes through - // a frame (e.g., in a loop with repeated raise statements), - // a new traceback entry is added. - if let Some((loc, _end_loc)) = frame.code.locations.get(idx) { - let next = exception.traceback(); + ) { + // Check if the exception already has traceback entries before + // we add ours. If it does, it was propagated from a callee + // function and we should not re-contextualize it. + let had_prior_traceback = exception.traceback().is_some(); + + // PyTraceBack_Here always adds a new entry without + // checking for duplicates. Each time an exception passes through + // a frame (e.g., in a loop with repeated raise statements), + // a new traceback entry is added. + if complete_frame + && let Some((loc, _end_loc)) = frame.code.locations.get(idx) + { + let next = exception.traceback(); - let new_traceback = PyTraceback::new( - next, - frame.frame_object(vm), - idx as i32 * 2, - loc.line, - ); - vm_trace!( - "Adding to traceback: {:?} {:?}", - new_traceback, - loc.line - ); - exception.set_traceback(Some(new_traceback.into_ref(&vm.ctx))); - } + let new_traceback = PyTraceback::new( + next, + frame.frame_object(vm), + idx as i32 * 2, + loc.line, + ); + vm_trace!("Adding to traceback: {:?} {:?}", new_traceback, loc.line); + exception.set_traceback(Some(new_traceback.into_ref(&vm.ctx))); + } - // _PyErr_SetObject sets __context__ only when the exception - // is first raised. When an exception propagates through frames, - // __context__ must not be overwritten. We contextualize when: - // - It's an explicit raise (raise/raise from) - // - The exception had no prior traceback (originated here) - if is_new_raise || !had_prior_traceback { - vm.contextualize_exception(&exception); - } + // _PyErr_SetObject sets __context__ only when the exception + // is first raised. When an exception propagates through frames, + // __context__ must not be overwritten. We contextualize when: + // - It's an explicit raise (raise/raise from) + // - The exception had no prior traceback (originated here) + if is_new_raise || !had_prior_traceback { + vm.contextualize_exception(exception); } + } - // Use exception table for zero-cost exception handling - frame.unwind_blocks( - vm, - UnwindReason::Raising { - exception, - offset: idx as u32, - }, - ) + #[cold] + fn contextualize_observer_error( + exception: PyBaseExceptionRef, + vm: &VirtualMachine, + ) -> PyBaseExceptionRef { + // A callback can fail while binding its arguments, before + // any Python frame has established the exception chain. + if exception.traceback().is_none() && exception.__context__().is_none() { + vm.contextualize_exception(&exception); + } + exception } // Check if this is a RERAISE instruction @@ -3865,6 +4110,19 @@ impl ExecutingFrame<'_> { ) ); + // CPython's error path attaches the original traceback before + // notifying monitoring tools, then unwinds the resulting exception. + if !is_reraise { + prepare_exception( + self, + &exception, + idx, + is_new_raise, + !PREPARE_GENERATOR && !self.iframe().is_incomplete(), + vm, + ); + } + // Fire RAISE or RERAISE monitoring event. // If the callback raises, replace the original exception. let exception = { @@ -3885,26 +4143,43 @@ impl ExecutingFrame<'_> { let exc_obj: PyObjectRef = exception.clone().into(); match monitoring::fire_raise(vm, self.code, offset, &exc_obj) { Ok(()) => exception, - Err(monitor_exc) => monitor_exc, + Err(monitor_exc) => contextualize_observer_error(monitor_exc, vm), } } else { exception } }; - // Fire 'exception' trace event for sys.settrace. - // Only for new raises, not re-raises (matching the - // `error` label that calls _PyEval_MonitorRaise). - if !is_reraise { - self.fire_exception_trace(&exception, vm)?; - } + // Like monitoring, a failing trace callback replaces the + // original exception without appending this frame a second time. + let exception = if !is_reraise { + match self.fire_exception_trace(&exception, vm) { + Ok(()) => exception, + Err(trace_exc) => contextualize_observer_error(trace_exc, vm), + } + } else { + exception + }; - match handle_exception(self, exception, idx, is_reraise, is_new_raise, vm) { + // Keep instruction unwinding out of the dispatch loop, as + // before traceback preparation moved ahead of callbacks. + #[cold] + #[inline(never)] + fn unwind_instruction_exception( + frame: &mut ExecutingFrame<'_>, + exception: PyBaseExceptionRef, + offset: u32, + vm: &VirtualMachine, + ) -> FrameResult { + frame.unwind_blocks(vm, UnwindReason::Raising { exception, offset }) + } + match unwind_instruction_exception(self, exception, idx as u32, vm) { // The handler unwound to a new position, so the next // index is whatever it left in the frame. Ok(None) => next_idx = lasti_cell.load(Relaxed), - Ok(Some(result)) => break Ok(result), + Ok(Some(result)) => break Ok(Some(result)), Err(exception) => { + monitoring::reset_reraise_pending(); // Fire PY_UNWIND: exception escapes this frame let exception = if vm.state.monitoring_events.load() & MonitoringEvent::PyUnwind.mask() @@ -3933,43 +4208,7 @@ impl ExecutingFrame<'_> { } fn yield_from_target(&self) -> Option<&PyObject> { - // checks gi_frame_state == FRAME_SUSPENDED_YIELD_FROM - // which is set when YIELD_VALUE with oparg >= 1 is executed. - // In RustPython, we check: - // 1. lasti points to RESUME (after YIELD_VALUE) - // 2. The previous instruction was YIELD_VALUE with arg >= 1 - // 3. Stack top is the delegate (receiver) - // - // First check if stack is empty - if so, we can't be in yield-from - if self.localsplus.stack_is_empty() { - return None; - } - let lasti = self.lasti() as usize; - if let Some(unit) = self.code.instructions.get(lasti) { - match &unit.op { - Instruction::Send { .. } => return Some(self.top_value()), - Instruction::Resume { .. } | Instruction::InstrumentedResume => { - // Check if previous instruction was YIELD_VALUE with arg >= 1 - // This indicates yield-from/await context - if lasti > 0 - && let Some(prev_unit) = self.code.instructions.get(lasti - 1) - && matches!( - &prev_unit.op.into(), - Opcode::YieldValue | Opcode::InstrumentedYieldValue - ) - { - // YIELD_VALUE arg: 0 = direct yield, >= 1 = yield-from/await - // OpArgByte.0 is the raw byte value - if u8::from(prev_unit.arg) >= 1 { - // In yield-from/await context, delegate is on top of stack - return Some(self.top_value()); - } - } - } - _ => {} - } - } - None + suspended_delegate(self.code, self.localsplus, self.lasti()) } /// Handle throw() on a generator/coroutine. @@ -4186,6 +4425,7 @@ impl ExecutingFrame<'_> { } Ok(Some(result)) => Ok(result), Err(exception) => { + monitoring::reset_reraise_pending(); // Fire PY_UNWIND: exception escapes the generator frame. let exception = if vm.state.monitoring_events.load() & MonitoringEvent::PyUnwind.mask() != 0 { @@ -4215,15 +4455,14 @@ impl ExecutingFrame<'_> { .get(localsplus_idx) .copied() .unwrap_or(0); + let name = self.localsplus_name(localsplus_idx); if kind & CO_FAST_FREE != 0 { - let name = self.localsplus_name(localsplus_idx); vm.new_name_error( format!("cannot access free variable '{name}' where it is not associated with a value in enclosing scope"), name.to_owned(), ) } else { // Both merged cells (LOCAL|CELL) and non-merged cells get unbound local error - let name = self.localsplus_name(localsplus_idx); vm.new_unbound_local_error(format!( "local variable '{name}' referenced before assignment" )) @@ -4335,6 +4574,23 @@ impl ExecutingFrame<'_> { self.push_value(list_obj.into()); Ok(None) } + Instruction::BuildListFromArg => { + let last_val = self.pop_value(); + let length_hint = match last_val.clone().length_hint(0, vm) { + Ok(hint) => hint, + Err(exc) + if exc.fast_isinstance(vm.ctx.exceptions.system_exit) + || exc.fast_isinstance(vm.ctx.exceptions.keyboard_interrupt) => + { + return Err(exc); + } + Err(_) => 0, + }; + let list_obj = vm.ctx.new_list(Vec::with_capacity(length_hint)); + self.push_value(list_obj.into()); + self.push_value(last_val); + Ok(None) + } Instruction::BuildMap { count: size } => self.execute_build_map(vm, size.get(arg)), Instruction::BuildSet { count: size } => { let set = PySet::default().into_ref(&vm.ctx); @@ -4400,9 +4656,12 @@ impl ExecutingFrame<'_> { vm.ctx.empty_str.to_owned() }; - let expression = self.pop_value().downcast::().map_err(|_| { - vm.new_type_error("BUILD_INTERPOLATION expected str for expression") - })?; + let expression = self.pop_value(); + if !vm.is_none(&expression) && expression.downcast_ref::().is_none() { + return Err(vm.new_type_error( + "BUILD_INTERPOLATION expected str or None for expression", + )); + } let value = self.pop_value(); // conversion: 0=None, 1=Str, 2=Repr, 3=Ascii @@ -4433,8 +4692,7 @@ impl ExecutingFrame<'_> { } Instruction::CallFunctionEx => { // Stack: [callable, self_or_null, args_tuple, kwargs_or_null] - let args = self.collect_ex_args(vm)?; - self.execute_call(args, vm) + self.execute_call_ex::(vm) } Instruction::CallIntrinsic1 { func } => { let value = self.pop_value(); @@ -4452,6 +4710,8 @@ impl ExecutingFrame<'_> { Instruction::CheckEgMatch => { let match_type = self.pop_value(); let exc_value = self.pop_value(); + let naked = !vm.is_none(&exc_value) + && !exc_value.fast_isinstance(vm.ctx.exceptions.base_exception_group); let (rest, matched) = crate::exceptions::exception_group_match(&exc_value, &match_type, vm)?; @@ -4460,6 +4720,21 @@ impl ExecutingFrame<'_> { if !vm.is_none(&matched) && let Some(exc) = matched.downcast_ref::() { + if naked { + // CPython gives a newly wrapped exception its own + // traceback at the except* handler, not the child's + // original traceback. + let idx = self.lasti().saturating_sub(1) as usize; + if let Some((loc, _)) = self.code.locations.get(idx) { + let tb = PyTraceback::new( + None, + self.frame_object(vm), + idx as i32 * 2, + loc.line, + ); + exc.set_traceback(Some(tb.into_ref(&vm.ctx))); + } + } vm.set_exception(Some(exc.to_owned())); } @@ -4537,7 +4812,7 @@ impl ExecutingFrame<'_> { Ok(None) } Instruction::DeleteGlobal { namei: idx } => { - let name = self.code.names[idx.get(arg) as usize]; + let name = self.code.names[idx.get(arg)]; match self.globals.del_item(name, vm) { Ok(()) => {} Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => { @@ -4548,16 +4823,11 @@ impl ExecutingFrame<'_> { Ok(None) } Instruction::DeleteName { namei: idx } => { - let name = self.code.names[idx.get(arg) as usize]; - let res = self.locals.mapping(vm).ass_subscript(name, None, vm); - - match res { - Ok(()) => {} - Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => { - return Err(name_error(name, vm)); - } - Err(e) => return Err(e), - } + let name = self.code.names[idx.get(arg)]; + self.locals + .mapping(vm) + .ass_subscript(name, None, vm) + .map_err(|_| name_error(name, vm))?; Ok(None) } Instruction::DeleteSubscr => self.execute_delete_subscript(vm), @@ -4610,65 +4880,71 @@ impl ExecutingFrame<'_> { let dict: &Py = unsafe { dict_ref.downcast_unchecked_ref() }; - // Get callable for error messages - // Stack: [callable, self_or_null, args_tuple, kwargs_dict] - let callable = self.nth_value(idx + 2); - let func_str = Self::object_function_str(callable, vm); - - // Fast path: source is an exact dict (not a subclass, which may - // override `keys`/`__getitem__`). Iterate its entries natively - // instead of going through the mapping protocol, mirroring - // CPython's `PyDict_Merge` fast path for `PyDict_Check(other)`. - let source = if source.class().is(vm.ctx.types.dict_type) { - let src_dict = source - .downcast_ref::() - .expect("exact dict must have a PyDict payload"); - // Snapshot under a single read lock so a mutation of `source` - // triggered by `dict.set_item` (e.g. via a target subclass, or - // aliasing) can't be observed mid-iteration. - for (key, value) in src_dict.items_vec() { - if dict.contains_key(&*key, vm) { - let key_str = key.str(vm)?; - return Err(vm.new_type_error(format!( - "{} got multiple values for keyword argument '{}'", - func_str, - key_str.as_wtf8() - ))); + let merge_result = (|| -> PyResult> { + // Fast path: source is an exact dict (not a subclass, which may + // override `keys`/`__getitem__`). Iterate its entries natively + // instead of going through the mapping protocol, mirroring + // CPython's `PyDict_Merge` fast path for `PyDict_Check(other)`. + if source.class().is(vm.ctx.types.dict_type) { + let src_dict = source + .downcast_ref::() + .expect("exact dict must have a PyDict payload"); + // Preserve stored hashes: copying an exact dict must not call + // a key's __hash__ before the callable receives its arguments. + // Snapshot under one lock before any equality callbacks run. + for (key, value, hash) in src_dict.items_with_hashes_vec() { + if dict.contains_known_hash(&key, hash, vm)? { + return Ok(Some(key)); + } + dict.set_item_known_hash(&key, hash, value, vm)?; } - dict.set_item(&*key, value, vm)?; + return Ok(None); } - return Ok(None); - } else { - source - }; - // Check if source is a mapping - if vm - .get_method(source.clone(), vm.ctx.intern_str("keys")) - .is_none() - { - return Err(vm.new_type_error(format!( - "{} argument after ** must be a mapping, not {}", - func_str, - source.class().name() - ))); - } + // Merge keys, checking for duplicates. + let keys = source.mapping_unchecked().keys(vm)?; + let keys_iter = PyIter::try_from_object(vm, keys)?; + while let PyIterReturn::Return(key) = keys_iter.next(vm)? { + let hash = PyDict::hash_or_unhashable(&*key, vm)?; + if dict.entries.contains(vm, &*key, hash)? { + return Ok(Some(key)); + } + let value = source.get_item(&*key, vm)?; + dict.set_item(&*key, value, vm)?; + } + Ok(None) + })(); - // Merge keys, checking for duplicates - let keys_iter = vm.call_method(&source, "keys", ())?; - for key in keys_iter.try_to_value::>(vm)? { - if dict.contains_key(&*key, vm) { + match merge_result { + Ok(Some(key)) => { + // Stack: [callable, self_or_null, args_tuple, kwargs_dict] + let callable = self.nth_value(idx + 2); + let func_str = Self::object_function_str(callable, vm); let key_str = key.str(vm)?; - return Err(vm.new_type_error(format!( + Err(vm.new_type_error(format!( "{} got multiple values for keyword argument '{}'", func_str, key_str.as_wtf8() - ))); + ))) + } + Ok(None) => Ok(None), + Err(error) if error.fast_isinstance(vm.ctx.exceptions.attribute_error) => { + // Only missing keys make this a non-mapping. Preserve callback + // errors, chaining a failed recheck as _PyEval_FormatKwargsError does. + match vm.get_attribute_opt(&source, identifier!(vm, keys)) { + Ok(None) => Err(vm.new_type_error(wtf8_concat!( + "Value after ** must be a mapping, not ", + source.class().fully_qualified_name(vm)? + ))), + Ok(Some(_)) => Err(error), + Err(lookup_error) => { + lookup_error.set_context(Some(error)); + Err(lookup_error) + } + } } - let value = vm.call_method(&source, "__getitem__", (key.clone(),))?; - dict.set_item(&*key, value, vm)?; + Err(error) => Err(error), } - Ok(None) } Instruction::EndAsyncFor => { // Pops (awaitable, exc) from stack. @@ -4806,11 +5082,7 @@ impl ExecutingFrame<'_> { // Check if coroutine is already being awaited if let Some(coro) = iter.downcast_ref::() - && coro - .as_coro() - .frame_opt() - .and_then(|f| f.yield_from_target()) - .is_some() + && coro.as_coro().yield_from_target().is_some() { return Err(vm.new_runtime_error("coroutine is being awaited already")); } @@ -4818,36 +5090,23 @@ impl ExecutingFrame<'_> { self.push_value(iter); Ok(None) } - Instruction::GetIter => { - let iterated_obj = self.pop_value(); - let iter_obj = PyIter::try_from_object(vm, iterated_obj)?; - self.push_value(iter_obj.into()); - Ok(None) - } - Instruction::GetYieldFromIter => { - // GET_YIELD_FROM_ITER: prepare iterator for yield from - // If iterable is a coroutine, ensure we're in a coroutine context - // If iterable is a generator, use it directly - // Otherwise, call iter() on it + Instruction::GetIter { mode } => { + // _PyEval_GetIter let iterable = self.pop_value(); - let iter = if iterable.class().is(vm.ctx.types.coroutine_type) { - // Coroutine requires CO_COROUTINE or CO_ITERABLE_COROUTINE flag - if !self.code.flags.intersects( - bytecode::CodeFlags::COROUTINE | bytecode::CodeFlags::ITERABLE_COROUTINE, - ) { + let yield_from = mode.get(arg); + debug_assert_ne!(yield_from, bytecode::oparg::GET_ITER_YIELD_FROM); + let iter = if yield_from != 0 && iterable.class().is(vm.ctx.types.coroutine_type) { + if yield_from == bytecode::oparg::GET_ITER_YIELD_FROM_CORO_CHECK { return Err(vm.new_type_error( "cannot 'yield from' a coroutine object in a non-coroutine generator", )); } iterable - } else if iterable.class().is(vm.ctx.types.generator_type) { - // Generator can be used directly - iterable } else { - // Otherwise, get iterator - PyIter::try_from_object(vm, iterable)?.into() + iterable.get_iter(vm)?.into() }; self.push_value(iter); + self.push_null(); Ok(None) } Instruction::GetLen => { @@ -4863,7 +5122,8 @@ impl ExecutingFrame<'_> { Ok(None) } Instruction::ImportName { namei: idx } => { - self.import(vm, Some(self.code.names[idx.get(arg) as usize]))?; + let namei = idx.get(arg); + self.import(vm, self.code.names[namei.name_idx()], namei.flags())?; Ok(None) } Instruction::IsOp { invert } => { @@ -4984,7 +5244,7 @@ impl ExecutingFrame<'_> { let name = self.localsplus_name(idx); let value = self.mapping_get_optional(&class_dict, name, vm)?; self.push_value(match value { - Some(v) => v, + Some(v) => crate::lazy_import::reify_value(v, name, &class_dict, vm)?, None => self .cell_ref(idx) .get() @@ -4995,29 +5255,17 @@ impl ExecutingFrame<'_> { Instruction::LoadFromDictOrGlobals { i: idx } => { // PEP 649: Pop dict from stack (classdict), check there first, then globals let dict = self.pop_value(); - let name = self.code.names[idx.get(arg) as usize]; + let name = self.code.names[idx.get(arg)]; let value = self.mapping_get_optional(&dict, name, vm)?; self.push_value(match value { - Some(v) => v, + Some(v) => crate::lazy_import::reify_value(v, name, &dict, vm)?, None => self.load_global_or_builtin(name, vm)?, }); Ok(None) } Instruction::LoadConst { consti } => { self.push_value(self.code.constants[consti.get(arg)].clone().into()); - // Mirror CPython's LOAD_CONST family transition. RustPython does - // not currently distinguish immortal constants at runtime. - let instr_idx = self.lasti() as usize - 1; - unsafe { - self.code - .instructions - .replace_op(instr_idx, Instruction::LoadConstMortal); - } - Ok(None) - } - Instruction::LoadConstMortal | Instruction::LoadConstImmortal => { - self.push_value(self.code.constants[u32::from(arg).into()].clone().into()); Ok(None) } Instruction::LoadCommonConstant { idx } => { @@ -5042,6 +5290,11 @@ impl ExecutingFrame<'_> { .expect("builtin_any not initialized"), CommonConstant::BuiltinList => vm.ctx.types.list_type.to_owned().into(), CommonConstant::BuiltinSet => vm.ctx.types.set_type.to_owned().into(), + CommonConstant::None => vm.ctx.none(), + CommonConstant::EmptyStr => vm.ctx.empty_str.to_owned().into(), + CommonConstant::True => vm.ctx.new_bool(true).into(), + CommonConstant::False => vm.ctx.new_bool(false).into(), + CommonConstant::MinusOne => vm.ctx.new_int(-1).into(), }; self.push_value(value); Ok(None) @@ -5138,24 +5391,27 @@ impl ExecutingFrame<'_> { Instruction::LoadGlobal { namei: idx } => { let oparg = idx.get(arg); self.adaptive(|s, ii, cb| s.specialize_load_global(vm, oparg, ii, cb)); - let name = &self.code.names[(oparg >> 1) as usize]; + let name = &self.code.names[oparg.name_idx()]; let x = self.load_global_or_builtin(name, vm)?; self.push_value(x); - if (oparg & 1) != 0 { + if oparg.push_null() { self.push_value_opt(None); } Ok(None) } Instruction::LoadName { namei: idx } => { - let name = self.code.names[idx.get(arg) as usize]; + let name = self.code.names[idx.get(arg)]; let result = self.locals.mapping(vm).subscript(name, vm); - match result { - Ok(x) => self.push_value(x), + let value = match result { + Ok(x) => { + crate::lazy_import::reify_value(x, name, self.locals.as_object(vm), vm)? + } Err(e) if e.fast_isinstance(vm.ctx.exceptions.key_error) => { - self.push_value(self.load_global_or_builtin(name, vm)?); + self.load_name_global_or_builtin(name, vm)? } Err(e) => return Err(e), - } + }; + self.push_value(value); Ok(None) } Instruction::LoadSpecial { method } => { @@ -5518,8 +5774,8 @@ impl ExecutingFrame<'_> { Ok(None) } Instruction::PopTop => { - // Pop value from stack and ignore. - self.pop_stackref(); + // Loop unwinding also uses POP_TOP for index-or-NULL slots. + self.pop_stackref_opt(); Ok(None) } Instruction::EndFor => { @@ -5528,7 +5784,8 @@ impl ExecutingFrame<'_> { Ok(None) } Instruction::PopIter => { - // Pop the iterator from stack (end of for loop) + // Discard the iterator's index-or-NULL slot and the iterator. + self.pop_stackref_opt(); self.pop_stackref(); Ok(None) } @@ -5587,10 +5844,10 @@ impl ExecutingFrame<'_> { Instruction::SetAdd { i } => { let item = self.pop_value(); let obj = self.nth_value(i.get(arg) - 1); - let set: &Py = unsafe { - // SAFETY: trust compiler - obj.downcast_unchecked_ref() - }; + // Annotation tracking can load a user-rebound global here. + let set = obj.downcast_ref_if_exact::(vm).ok_or_else(|| { + vm.new_type_error(format!("'{}' object is not a set", obj.class().name())) + })?; set.add(item, vm)?; Ok(None) } @@ -5724,11 +5981,11 @@ impl ExecutingFrame<'_> { Instruction::StoreGlobal { namei: idx } => { let value = self.pop_value(); self.globals - .set_item(self.code.names[idx.get(arg) as usize], value, vm)?; + .set_item(self.code.names[idx.get(arg)], value, vm)?; Ok(None) } Instruction::StoreName { namei: idx } => { - let name = self.code.names[idx.get(arg) as usize]; + let name = self.code.names[idx.get(arg)]; let value = self.pop_value(); self.locals .mapping(vm) @@ -5833,10 +6090,10 @@ impl ExecutingFrame<'_> { Ok(Some(ExecutionResult::Yield(self.pop_value()))) } Instruction::Send { .. } => { - // (receiver, v -- receiver, retval) + // (receiver, null_or_index, v -- receiver, null_or_index, retval) self.adaptive(|s, ii, cb| s.specialize_send(vm, ii, cb)); let exit_label = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg)); - let receiver = self.nth_value(1); + let receiver = self.nth_value(2); let can_fast_send = !self.specialization_eval_frame_active(vm) && (receiver.downcast_ref_if_exact::(vm).is_some() || receiver.downcast_ref_if_exact::(vm).is_some()) @@ -5844,7 +6101,7 @@ impl ExecutingFrame<'_> { .builtin_coro(receiver) .is_some_and(|coro| !coro.running() && !coro.closed()); let val = self.pop_value(); - let receiver = self.top_value(); + let receiver = self.nth_value(1); let ret = if can_fast_send { let coro = self.builtin_coro(receiver).unwrap(); if vm.is_none(&val) { @@ -5861,7 +6118,12 @@ impl ExecutingFrame<'_> { Ok(None) } PyIterReturn::StopIteration(value) => { - if vm.use_tracing.get() && self.trace_is_set(vm) { + // CPython's INSTRUMENTED_END_SEND synthesizes this event + // only for generator/coroutine receivers, not other awaitables. + if vm.use_tracing.get() + && self.trace_is_set(vm) + && self.builtin_coro(receiver).is_some() + { let stop_exc = vm.new_stop_iteration(value.clone()); self.fire_exception_trace(&stop_exc, vm)?; } @@ -5874,8 +6136,8 @@ impl ExecutingFrame<'_> { } Instruction::SendGen => { let exit_label = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg)); - // Stack: [receiver, val] — peek receiver before popping - let receiver = self.nth_value(1); + // Stack: [receiver, null_or_index, val] — peek before popping + let receiver = self.nth_value(2); let mut started = false; let can_fast_send = !self.specialization_eval_frame_active(vm) && (receiver.downcast_ref_if_exact::(vm).is_some() @@ -5887,7 +6149,7 @@ impl ExecutingFrame<'_> { let val = self.pop_value(); if can_fast_send { - let receiver = self.top_value(); + let receiver = self.nth_value(1); // Hand an already-suspended generator to the trampoline, // which runs its frame in this same eval loop and re-yields // for this frame — no Rust frame and no instruction per @@ -5922,14 +6184,19 @@ impl ExecutingFrame<'_> { } } } - let receiver = self.top_value(); + let receiver = self.nth_value(1); match self._send(receiver, val, vm)? { PyIterReturn::Return(value) => { self.push_value(value); Ok(None) } PyIterReturn::StopIteration(value) => { - if vm.use_tracing.get() && self.trace_is_set(vm) { + // CPython's INSTRUMENTED_END_SEND synthesizes this event + // only for generator/coroutine receivers, not other awaitables. + if vm.use_tracing.get() + && self.trace_is_set(vm) + && self.builtin_coro(receiver).is_some() + { let stop_exc = vm.new_stop_iteration(value.clone()); self.fire_exception_trace(&stop_exc, vm)?; } @@ -5941,9 +6208,9 @@ impl ExecutingFrame<'_> { } } Instruction::EndSend => { - // Stack: (receiver, value) -> (value) - // Pops receiver, leaves value + // (receiver, null_or_index, value) -> (value) let value = self.pop_value(); + self.pop_stackref_opt(); // discard index-or-NULL self.pop_stackref(); // discard receiver self.push_value(value); Ok(None) @@ -5960,39 +6227,24 @@ impl ExecutingFrame<'_> { Ok(None) } Instruction::CleanupThrow => { - // CLEANUP_THROW: (sub_iter, last_sent_val, exc) -> (None, value) OR re-raise - // If StopIteration: pop all 3, extract value, push (None, value) - // Otherwise: pop all 3, return Err(exc) for unwind_blocks to handle - // - // Unlike CPython where exception_unwind pops the triple as part of - // stack cleanup to handler depth, RustPython pops here explicitly - // and lets unwind_blocks find outer handlers. - // Compiler sets handler_depth = base + 2 (before exc is pushed). - - // First peek at exc_value (top of stack) without popping + // (sub_iter, null_in, last_sent_val, exc) -> (None, null_out, value) + // Leave nonmatching exceptions and their stack for unwinding. let exc = self.top_value(); - - // Check if it's a StopIteration if let Some(exc_ref) = exc.downcast_ref::() && exc_ref.fast_isinstance(vm.ctx.exceptions.stop_iteration) { - // Extract value from StopIteration let value = exc_ref.get_arg(0).unwrap_or_else(|| vm.ctx.none()); - // Now pop all three self.pop_stackref(); // exc self.pop_stackref(); // last_sent_val + let index_or_null = self.pop_stackref_opt(); self.pop_stackref(); // sub_iter self.push_value(vm.ctx.none()); + self.push_stackref_opt(index_or_null); self.push_value(value); return Ok(None); } - - // Re-raise other exceptions: pop all three and return Err(exc) - let exc = self.pop_value(); // exc - self.pop_stackref(); // last_sent_val - self.pop_stackref(); // sub_iter - let exc = exc + .to_owned() .downcast::() .map_err(|_| vm.new_type_error("exception expected"))?; Err(exc) @@ -6058,7 +6310,7 @@ impl ExecutingFrame<'_> { Instruction::LoadAttrMethodWithValues => { let oparg = LoadAttr::from_u32(u32::from(arg)); let cache_base = self.lasti() as usize; - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; let owner = self.top_value(); let type_version = self.code.instructions.read_cache_u32(cache_base + 1); @@ -6087,7 +6339,7 @@ impl ExecutingFrame<'_> { Instruction::LoadAttrInstanceValue => { let oparg = LoadAttr::from_u32(u32::from(arg)); let cache_base = self.lasti() as usize; - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; let owner = self.top_value(); let type_version = self.code.instructions.read_cache_u32(cache_base + 1); @@ -6110,7 +6362,7 @@ impl ExecutingFrame<'_> { Instruction::LoadAttrWithHint => { let oparg = LoadAttr::from_u32(u32::from(arg)); let cache_base = self.lasti() as usize; - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; let owner = self.top_value(); let type_version = self.code.instructions.read_cache_u32(cache_base + 1); @@ -6133,11 +6385,9 @@ impl ExecutingFrame<'_> { } } self.pop_stackref(); + self.push_value(value); if oparg.is_method() { - self.push_value(value); self.push_value_opt(None); - } else { - self.push_value(value); } return Ok(None); } @@ -6148,7 +6398,7 @@ impl ExecutingFrame<'_> { Instruction::LoadAttrModule => { let oparg = LoadAttr::from_u32(u32::from(arg)); let cache_base = self.lasti() as usize; - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; let owner = self.top_value(); let type_version = self.code.instructions.read_cache_ptr(cache_base + 6); let keys_version = self.code.instructions.read_cache_ptr(cache_base + 7); @@ -6162,13 +6412,14 @@ impl ExecutingFrame<'_> { module .dict() .get_cached_module_attr(attr_name, keys_version, index, vm) + && value + .downcast_ref_if_exact::(vm) + .is_none() { self.pop_stackref(); + self.push_value(value); if oparg.is_method() { - self.push_value(value); self.push_value_opt(None); - } else { - self.push_value(value); } return Ok(None); } @@ -6186,11 +6437,9 @@ impl ExecutingFrame<'_> { && let Some(attr) = self.try_read_cached_descriptor(cache_base, type_version) { self.pop_stackref(); + self.push_value(attr); if oparg.is_method() { - self.push_value(attr); self.push_value_opt(None); - } else { - self.push_value(attr); } return Ok(None); } @@ -6199,7 +6448,7 @@ impl ExecutingFrame<'_> { Instruction::LoadAttrNondescriptorWithValues => { let oparg = LoadAttr::from_u32(u32::from(arg)); let cache_base = self.lasti() as usize; - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; let owner = self.top_value(); let type_version = self.code.instructions.read_cache_u32(cache_base + 1); @@ -6209,11 +6458,9 @@ impl ExecutingFrame<'_> { // Instance dict has priority — check if attr is shadowed if let Some(value) = self.shadowing_instance_attr(cache_base, attr_name, vm)? { self.pop_stackref(); + self.push_value(value); if oparg.is_method() { - self.push_value(value); self.push_value_opt(None); - } else { - self.push_value(value); } return Ok(None); } @@ -6223,11 +6470,9 @@ impl ExecutingFrame<'_> { return self.load_attr_slow(vm, oparg); }; self.pop_stackref(); + self.push_value(attr); if oparg.is_method() { - self.push_value(attr); self.push_value_opt(None); - } else { - self.push_value(attr); } return Ok(None); } @@ -6246,11 +6491,9 @@ impl ExecutingFrame<'_> { && let Some(attr) = self.try_read_cached_descriptor(cache_base, type_version) { self.pop_stackref(); + self.push_value(attr); if oparg.is_method() { - self.push_value(attr); self.push_value_opt(None); - } else { - self.push_value(attr); } return Ok(None); } @@ -6272,11 +6515,9 @@ impl ExecutingFrame<'_> { && let Some(attr) = self.try_read_cached_descriptor(cache_base, type_version) { self.pop_stackref(); + self.push_value(attr); if oparg.is_method() { - self.push_value(attr); self.push_value_opt(None); - } else { - self.push_value(attr); } return Ok(None); } @@ -6302,7 +6543,7 @@ impl ExecutingFrame<'_> { { debug_assert!(func.has_exact_argcount(2)); let owner = self.pop_value(); - let attr_name = self.code.names[oparg.name_idx() as usize].to_owned().into(); + let attr_name = self.code.names[oparg.name_idx()].to_owned().into(); let result = func.invoke_exact_args_slots(&mut [Some(owner), Some(attr_name)], vm)?; self.push_value(result); @@ -6323,11 +6564,9 @@ impl ExecutingFrame<'_> { self.code.instructions.read_cache_u32(cache_base + 3) as i32 as isize; if let Some(value) = owner.get_slot(slot_offset) { self.pop_stackref(); + self.push_value(value); if oparg.is_method() { - self.push_value(value); self.push_value_opt(None); - } else { - self.push_value(value); } return Ok(None); } @@ -6359,10 +6598,10 @@ impl ExecutingFrame<'_> { self.load_attr_slow(vm, oparg) } Instruction::StoreAttrInstanceValue => { - let attr_idx = u32::from(arg); + let attr_idx = bytecode::NameIdx::from_u32(u32::from(arg)); let instr_idx = self.lasti() as usize - 1; let cache_base = instr_idx + 1; - let attr_name = self.code.names[attr_idx as usize]; + let attr_name = self.code.names[attr_idx]; let owner = self.top_value(); let type_version = self.code.instructions.read_cache_u32(cache_base + 1); @@ -6381,10 +6620,10 @@ impl ExecutingFrame<'_> { self.store_attr(vm, attr_idx) } Instruction::StoreAttrWithHint => { - let attr_idx = u32::from(arg); + let attr_idx = bytecode::NameIdx::from_u32(u32::from(arg)); let instr_idx = self.lasti() as usize - 1; let cache_base = instr_idx + 1; - let attr_name = self.code.names[attr_idx as usize]; + let attr_name = self.code.names[attr_idx]; let owner = self.top_value(); let type_version = self.code.instructions.read_cache_u32(cache_base + 1); @@ -6416,7 +6655,7 @@ impl ExecutingFrame<'_> { owner.set_slot(slot_offset, Some(value)); return Ok(None); } - let attr_idx = u32::from(arg); + let attr_idx = bytecode::NameIdx::from_u32(u32::from(arg)); self.store_attr(vm, attr_idx) } Instruction::StoreSubscrListInt => { @@ -6430,7 +6669,10 @@ impl ExecutingFrame<'_> { { let mut vec = list.borrow_vec_mut(); if i < vec.len() { - vec[i] = value; + // Unlock before dropping the replaced element; its + // finalizer may access this list. + let _old = core::mem::replace(&mut vec[i], value); + drop(vec); return Ok(None); } } @@ -6444,11 +6686,10 @@ impl ExecutingFrame<'_> { let value = self.pop_value(); if let Some(dict) = obj.downcast_ref_if_exact::(vm) { dict.set_item(idx.as_object(), value, vm)?; - Ok(None) } else { obj.set_item(idx.as_object(), value, vm)?; - Ok(None) } + Ok(None) } // Specialized BINARY_OP opcodes Instruction::BinaryOpAddInt => { @@ -6518,7 +6759,7 @@ impl ExecutingFrame<'_> { { self.pop_stackref(); self.pop_stackref(); - self.push_value(result); + self.push_value(result?); Ok(None) } else { self.execute_bin_op(vm, op) @@ -7032,132 +7273,20 @@ impl ExecutingFrame<'_> { self.execute_call_vectorcall(nargs, vm) } Instruction::CallMethodDescriptorNoargs => { - let nargs: u32 = arg.into(); - let stack_len = self.localsplus.stack_len(); - let self_or_null_is_some = self - .localsplus - .stack_index(stack_len - nargs as usize - 1) - .is_some(); - let total_nargs = nargs + u32::from(self_or_null_is_some); - if total_nargs == 1 { - let callable = self.nth_value(nargs + 1); - let self_index = - stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some); - if let Some(descr) = callable.downcast_ref_if_exact::(vm) - && (descr.method.flags - & (PyMethodFlags::VARARGS - | PyMethodFlags::FASTCALL - | PyMethodFlags::NOARGS - | PyMethodFlags::O - | PyMethodFlags::KEYWORDS)) - == PyMethodFlags::NOARGS - && self - .localsplus - .stack_index(self_index) - .as_ref() - .is_some_and(|self_obj| self_obj.class().is(descr.common.typ)) - { - let func = descr.method.func; - let callee = Callee::named(descr.method.name).with_instance_arg(true); - let (_callable, all_args) = self.take_call_args(nargs as usize); - debug_assert_eq!(all_args.len(), total_nargs as usize); - let args = FuncArgs { - args: all_args, - kwargs: Default::default(), - }; - let result = func(vm, args, callee)?; - self.push_value(result); - return Ok(None); - } - } - self.execute_call_vectorcall(nargs, vm) + self.execute_call_method_descriptor(arg.into(), PyMethodFlags::NOARGS, Some(1), vm) } Instruction::CallMethodDescriptorO => { - let nargs: u32 = arg.into(); - let stack_len = self.localsplus.stack_len(); - let self_or_null_is_some = self - .localsplus - .stack_index(stack_len - nargs as usize - 1) - .is_some(); - let total_nargs = nargs + u32::from(self_or_null_is_some); - if total_nargs == 2 { - let callable = self.nth_value(nargs + 1); - let self_index = - stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some); - if let Some(descr) = callable.downcast_ref_if_exact::(vm) - && (descr.method.flags - & (PyMethodFlags::VARARGS - | PyMethodFlags::FASTCALL - | PyMethodFlags::NOARGS - | PyMethodFlags::O - | PyMethodFlags::KEYWORDS)) - == PyMethodFlags::O - && self - .localsplus - .stack_index(self_index) - .as_ref() - .is_some_and(|self_obj| self_obj.class().is(descr.common.typ)) - { - let func = descr.method.func; - let callee = Callee::named(descr.method.name).with_instance_arg(true); - let (_callable, all_args) = self.take_call_args(nargs as usize); - debug_assert_eq!(all_args.len(), total_nargs as usize); - let args = FuncArgs { - args: all_args, - kwargs: Default::default(), - }; - let result = func(vm, args, callee)?; - self.push_value(result); - return Ok(None); - } - } - self.execute_call_vectorcall(nargs, vm) + self.execute_call_method_descriptor(arg.into(), PyMethodFlags::O, Some(2), vm) } Instruction::CallMethodDescriptorFast => { - let nargs: u32 = arg.into(); - let stack_len = self.localsplus.stack_len(); - let self_or_null_is_some = self - .localsplus - .stack_index(stack_len - nargs as usize - 1) - .is_some(); - let total_nargs = nargs + u32::from(self_or_null_is_some); - let callable = self.nth_value(nargs + 1); - let self_index = - stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some); - if total_nargs > 0 - && let Some(descr) = callable.downcast_ref_if_exact::(vm) - && (descr.method.flags - & (PyMethodFlags::VARARGS - | PyMethodFlags::FASTCALL - | PyMethodFlags::NOARGS - | PyMethodFlags::O - | PyMethodFlags::KEYWORDS)) - == PyMethodFlags::FASTCALL - && self - .localsplus - .stack_index(self_index) - .as_ref() - .is_some_and(|self_obj| self_obj.class().is(descr.common.typ)) - { - let func = descr.method.func; - let callee = Callee::named(descr.method.name).with_instance_arg(true); - let (_callable, all_args) = self.take_call_args(nargs as usize); - debug_assert_eq!(all_args.len(), total_nargs as usize); - let args = FuncArgs { - args: all_args, - kwargs: Default::default(), - }; - let result = func(vm, args, callee)?; - self.push_value(result); - return Ok(None); - } - self.execute_call_vectorcall(nargs, vm) + self.execute_call_method_descriptor(arg.into(), PyMethodFlags::FASTCALL, None, vm) } Instruction::CallBuiltinClass => { let nargs: u32 = arg.into(); let callable = self.nth_value(nargs + 1); if let Some(cls) = callable.downcast_ref::() - && cls.slots().vectorcall.load().is_some() + && cls.slots().constructor_vectorcall.load().is_some() + && callable.vectorcall_func().is_some() { let (callable, args_vec) = self.take_call_args(nargs as usize); let effective_nargs = args_vec.len(); @@ -7220,44 +7349,12 @@ impl ExecutingFrame<'_> { } Instruction::CallMethodDescriptorFastWithKeywords => { // Native function interface is uniform regardless of keyword support - let nargs: u32 = arg.into(); - let stack_len = self.localsplus.stack_len(); - let self_or_null_is_some = self - .localsplus - .stack_index(stack_len - nargs as usize - 1) - .is_some(); - let total_nargs = nargs + u32::from(self_or_null_is_some); - let callable = self.nth_value(nargs + 1); - let self_index = - stack_len - nargs as usize - 1 + usize::from(!self_or_null_is_some); - if total_nargs > 0 - && let Some(descr) = callable.downcast_ref_if_exact::(vm) - && (descr.method.flags - & (PyMethodFlags::VARARGS - | PyMethodFlags::FASTCALL - | PyMethodFlags::NOARGS - | PyMethodFlags::O - | PyMethodFlags::KEYWORDS)) - == (PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS) - && self - .localsplus - .stack_index(self_index) - .as_ref() - .is_some_and(|self_obj| self_obj.class().is(descr.common.typ)) - { - let func = descr.method.func; - let callee = Callee::named(descr.method.name).with_instance_arg(true); - let (_callable, all_args) = self.take_call_args(nargs as usize); - debug_assert_eq!(all_args.len(), total_nargs as usize); - let args = FuncArgs { - args: all_args, - kwargs: Default::default(), - }; - let result = func(vm, args, callee)?; - self.push_value(result); - return Ok(None); - } - self.execute_call_vectorcall(nargs, vm) + self.execute_call_method_descriptor( + arg.into(), + PyMethodFlags::FASTCALL | PyMethodFlags::KEYWORDS, + None, + vm, + ) } Instruction::CallBuiltinFastWithKeywords => { // Native function interface is uniform regardless of keyword support @@ -7459,7 +7556,7 @@ impl ExecutingFrame<'_> { } Instruction::LoadSuperAttrAttr => { let oparg = u32::from(arg); - let attr_name = self.code.names[(oparg >> 2) as usize]; + let attr_name = self.code.names[LoadSuperAttr::from_u32(oparg).name_idx()]; // Stack: [global_super, class, self] let self_obj = self.top_value(); let class_obj = self.nth_value(1); @@ -7513,7 +7610,7 @@ impl ExecutingFrame<'_> { } Instruction::LoadSuperAttrMethod => { let oparg = u32::from(arg); - let attr_name = self.code.names[(oparg >> 2) as usize]; + let attr_name = self.code.names[LoadSuperAttr::from_u32(oparg).name_idx()]; // Stack: [global_super, class, self] let self_obj = self.top_value(); let class_obj = self.nth_value(1); @@ -7654,13 +7751,12 @@ impl ExecutingFrame<'_> { self.pop_stackref(); self.take_fused_bool_jump(jump, result); } - Ok(None) } else { let obj = self.pop_stackref(); let result = obj.try_to_bool(vm)?; self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } + Ok(None) } Instruction::ToBoolInt => { let obj = self.top_value(); @@ -7668,26 +7764,24 @@ impl ExecutingFrame<'_> { let result = !int_val.as_bigint().is_zero(); self.pop_stackref(); self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } else { let obj = self.pop_stackref(); let result = obj.try_to_bool(vm)?; self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } + Ok(None) } Instruction::ToBoolNone => { let obj = self.top_value(); if obj.class().is(vm.ctx.types.none_type) { self.pop_stackref(); self.push_bool_or_fused_jump(instruction.cache_entries(), false, vm); - Ok(None) } else { let obj = self.pop_stackref(); let result = obj.try_to_bool(vm)?; self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } + Ok(None) } Instruction::ToBoolList => { let obj = self.top_value(); @@ -7695,13 +7789,12 @@ impl ExecutingFrame<'_> { let result = !list.borrow_vec().is_empty(); self.pop_stackref(); self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } else { let obj = self.pop_stackref(); let result = obj.try_to_bool(vm)?; self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } + Ok(None) } Instruction::ToBoolStr => { let obj = self.top_value(); @@ -7709,13 +7802,12 @@ impl ExecutingFrame<'_> { let result = !s.is_empty(); self.pop_stackref(); self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } else { let obj = self.pop_stackref(); let result = obj.try_to_bool(vm)?; self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } + Ok(None) } Instruction::ToBoolAlwaysTrue => { // Objects without __bool__ or __len__ are always True. @@ -7729,13 +7821,12 @@ impl ExecutingFrame<'_> { { self.pop_stackref(); self.push_bool_or_fused_jump(instruction.cache_entries(), true, vm); - Ok(None) } else { let obj = self.pop_stackref(); let result = obj.try_to_bool(vm)?; self.push_bool_or_fused_jump(instruction.cache_entries(), result, vm); - Ok(None) } + Ok(None) } Instruction::ContainsOpDict => { let b = self.top_value(); // haystack @@ -7751,7 +7842,6 @@ impl ExecutingFrame<'_> { bytecode::Invert::Yes => !found, }; self.push_bool_or_fused_jump(instruction.cache_entries(), value, vm); - Ok(None) } else { let b = self.pop_value(); let a = self.pop_value(); @@ -7762,8 +7852,8 @@ impl ExecutingFrame<'_> { bytecode::Invert::Yes => self._not_in(vm, &a, &b)?, }; self.push_bool_or_fused_jump(instruction.cache_entries(), value, vm); - Ok(None) } + Ok(None) } Instruction::ContainsOpSet => { let b = self.top_value(); // haystack @@ -7781,7 +7871,6 @@ impl ExecutingFrame<'_> { bytecode::Invert::Yes => !found, }; self.push_bool_or_fused_jump(instruction.cache_entries(), value, vm); - Ok(None) } else { let b = self.pop_value(); let a = self.pop_value(); @@ -7792,8 +7881,8 @@ impl ExecutingFrame<'_> { bytecode::Invert::Yes => self._not_in(vm, &a, &b)?, }; self.push_bool_or_fused_jump(instruction.cache_entries(), value, vm); - Ok(None) } + Ok(None) } Instruction::UnpackSequenceTwoTuple => { let obj = self.top_value(); @@ -7846,52 +7935,49 @@ impl ExecutingFrame<'_> { } Instruction::ForIterRange => { let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg)); - let iter = self.top_value(); + let iter = self.nth_value(1); if let Some(range_iter) = iter.downcast_ref_if_exact::(vm) { if let Some(value) = range_iter.fast_next() { self.push_value(vm.ctx.new_int(value).into()); } else { self.for_iter_jump_on_exhausted(target); } - Ok(None) } else { self.execute_for_iter(vm, target)?; - Ok(None) } + Ok(None) } Instruction::ForIterList => { let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg)); - let iter = self.top_value(); + let iter = self.nth_value(1); if let Some(list_iter) = iter.downcast_ref_if_exact::(vm) { if let Some(value) = list_iter.fast_next() { self.push_value(value); } else { self.for_iter_jump_on_exhausted(target); } - Ok(None) } else { self.execute_for_iter(vm, target)?; - Ok(None) } + Ok(None) } Instruction::ForIterTuple => { let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg)); - let iter = self.top_value(); + let iter = self.nth_value(1); if let Some(tuple_iter) = iter.downcast_ref_if_exact::(vm) { if let Some(value) = tuple_iter.fast_next() { self.push_value(value); } else { self.for_iter_jump_on_exhausted(target); } - Ok(None) } else { self.execute_for_iter(vm, target)?; - Ok(None) } + Ok(None) } Instruction::ForIterGen => { let target = bytecode::Label::from_u32(self.lasti() + 1 + u32::from(arg)); - let iter = self.top_value(); + let iter = self.nth_value(1); if self.specialization_eval_frame_active(vm) { self.execute_for_iter(vm, target)?; return Ok(None); @@ -7924,79 +8010,105 @@ impl ExecutingFrame<'_> { } Err(e) => return Err(e), } - Ok(None) } else { self.execute_for_iter(vm, target)?; - Ok(None) } + Ok(None) } Instruction::LoadGlobalModule => { - let oparg = u32::from(arg); + let oparg = LoadGlobal::from_u32(u32::from(arg)); let cache_base = self.lasti() as usize; // Keep specialized opcode on guard miss (JUMP_TO_PREDICTED behavior). let cached_version = self.code.instructions.read_cache_u16(cache_base + 1); let cached_index = self.code.instructions.read_cache_u16(cache_base + 3); if cached_version != 0 - && let Some(x) = self - .globals - .get_item_by_index_and_keys_version(cached_version, cached_index) + && let Some(globals) = self.globals.as_mutable() + && let Some(x) = + globals.get_item_by_index_and_keys_version(cached_version, cached_index) { + let name = self.code.names[oparg.name_idx()]; + let x = crate::lazy_import::reify_value(x, name, self.globals.as_object(), vm)?; self.push_value(x); - if (oparg & 1) != 0 { + if oparg.push_null() { self.push_value_opt(None); } return Ok(None); } - let name = self.code.names[(oparg >> 1) as usize]; + let name = self.code.names[oparg.name_idx()]; let x = self.load_global_or_builtin(name, vm)?; self.push_value(x); - if (oparg & 1) != 0 { + if oparg.push_null() { self.push_value_opt(None); } Ok(None) } Instruction::LoadGlobalBuiltin => { - let oparg = u32::from(arg); + let oparg = LoadGlobal::from_u32(u32::from(arg)); let cache_base = self.lasti() as usize; let cached_globals_ver = self.code.instructions.read_cache_u16(cache_base + 1); let cached_builtins_ver = self.code.instructions.read_cache_u16(cache_base + 2); let cached_index = self.code.instructions.read_cache_u16(cache_base + 3); if cached_globals_ver != 0 && cached_builtins_ver != 0 - && let Ok(current_globals_ver) = u16::try_from(self.globals.keys_version()) + && let Some(globals) = self.globals.as_mutable() + && let Ok(current_globals_ver) = u16::try_from(globals.keys_version()) && cached_globals_ver == current_globals_ver && let Some(builtins_dict) = self.builtins.downcast_ref_if_exact::(vm) && let Some(x) = builtins_dict .get_item_by_index_and_keys_version(cached_builtins_ver, cached_index) { + let name = self.code.names[oparg.name_idx()]; + let x = crate::lazy_import::reify_value(x, name, self.builtins, vm)?; self.push_value(x); - if (oparg & 1) != 0 { + if oparg.push_null() { self.push_value_opt(None); } return Ok(None); } - let name = self.code.names[(oparg >> 1) as usize]; + let name = self.code.names[oparg.name_idx()]; let x = self.load_global_or_builtin(name, vm)?; self.push_value(x); - if (oparg & 1) != 0 { + if oparg.push_null() { self.push_value_opt(None); } Ok(None) } // All INSTRUMENTED_* opcodes delegate to a cold function to keep // the hot instruction loop free of monitoring overhead. - _ => self.execute_instrumented(instruction, arg, vm), + _ => { + let (result, do_extend_arg) = self.execute_instrumented(instruction, arg, vm); + *extend_arg = do_extend_arg; + result + } } } /// Handle all INSTRUMENTED_* opcodes. This function is cold — it only /// runs when sys.monitoring has rewritten the bytecode. #[cold] + #[inline(never)] fn execute_instrumented( &mut self, instruction: Instruction, arg: bytecode::OpArg, vm: &VirtualMachine, + ) -> (FrameResult, bool) { + // Keep the mutable flag inside this cold function so its address does + // not escape the dispatch loop and force a stack access for every opcode. + let mut do_extend_arg = false; + let result = + self.execute_instrumented_from(instruction, arg, false, &mut do_extend_arg, vm); + (result, do_extend_arg) + } + + #[cold] + fn execute_instrumented_from( + &mut self, + instruction: Instruction, + arg: bytecode::OpArg, + wrapper_dispatch: bool, + do_extend_arg: &mut bool, + vm: &VirtualMachine, ) -> FrameResult { debug_assert!( instruction.is_instrumented(), @@ -8095,10 +8207,7 @@ impl ExecutingFrame<'_> { let args = self.collect_keyword_args(u32::from(arg)); self.execute_call_instrumented(args, vm) } - Instruction::InstrumentedCallFunctionEx => { - let args = self.collect_ex_args(vm)?; - self.execute_call_instrumented(args, vm) - } + Instruction::InstrumentedCallFunctionEx => self.execute_call_ex::(vm), Instruction::InstrumentedLoadSuperAttr => { let oparg = bytecode::LoadSuperAttr::from(u32::from(arg)); let offset = (self.lasti() - 1) * 2; @@ -8172,7 +8281,13 @@ impl ExecutingFrame<'_> { if continued { if self.monitoring_mask & MonitoringEvent::BranchLeft.mask() != 0 { let dest_offset = (self.lasti() + 1) * 2; // after caches - monitoring::fire_branch_left(vm, self.code, src_offset, dest_offset)?; + monitoring::fire_branch_left( + vm, + self.code, + src_offset, + src_offset, + dest_offset, + )?; } } else if self.monitoring_mask & MonitoringEvent::BranchRight.mask() != 0 { // INSTRUMENTED_POP_ITER: dest is the instruction after @@ -8183,10 +8298,10 @@ impl ExecutingFrame<'_> { Ok(None) } Instruction::InstrumentedEndFor => { - // Stack: [value, receiver(iter), ...] + // Stack: [..., receiver(iter), null_or_index, value] // PyGen_Check: only fire STOP_ITERATION for generators let is_gen = self - .nth_value(1) + .nth_value(2) .downcast_ref::() .is_some(); let value = self.pop_value(); @@ -8198,6 +8313,7 @@ impl ExecutingFrame<'_> { } Instruction::InstrumentedEndSend => { let value = self.pop_value(); + self.pop_stackref_opt(); let receiver = self.pop_value(); // PyGen_Check || PyCoro_CheckExact let is_gen_or_coro = receiver @@ -8278,14 +8394,20 @@ impl ExecutingFrame<'_> { { branch_idx -= 1; } - let src_offset = (branch_idx as u32) * 2; + let site = not_taken_idx as u32 * 2; + let src_offset = if wrapper_dispatch { + site + } else { + (branch_idx as u32) * 2 + }; let dest_offset = self.lasti() * 2; - monitoring::fire_branch_left(vm, self.code, src_offset, dest_offset)?; + monitoring::fire_branch_left(vm, self.code, site, src_offset, dest_offset)?; } Ok(None) } Instruction::InstrumentedPopIter => { // BRANCH_RIGHT is fired by InstrumentedForIter, not here. + self.pop_stackref_opt(); self.pop_stackref(); Ok(None) } @@ -8332,16 +8454,35 @@ impl ExecutingFrame<'_> { "INSTRUMENTED_LINE at {idx} without stored opcode" ); + let line_active = + monitoring::is_event_active_at(vm, self.code, offset, MonitoringEvent::Line); + let instruction_active = also_instruction + && monitoring::is_event_active_at( + vm, + self.code, + offset, + MonitoringEvent::Instruction, + ); + let wrapper_dispatch = line_active || instruction_active; + // Fire LINE event only if line changed if let Some((loc, _)) = self.code.locations.get(idx) { let line = loc.line.get() as u32; if line != self.prev_line.get() && line > 0 { self.prev_line.set(line); monitoring::fire_line(vm, self.code, offset, line)?; + if self.lasti() != idx as u32 + 1 { + self.apply_pending_lineno_jump(vm); + // Restart at the callback's target without executing the + // old opcode or carrying its EXTENDED_ARG prefix there. + *do_extend_arg = false; + return Ok(None); + } } } - // If the LINE position also had INSTRUCTION, fire that event too + // Disabling LINE does not disable the nested INSTRUCTION event. + // fire_instruction still checks its current subscriptions. if also_instruction { monitoring::fire_instruction(vm, self.code, offset)?; } @@ -8359,10 +8500,15 @@ impl ExecutingFrame<'_> { .expect("invalid opcode in side-table chain"); let lasti_before_dispatch = self.lasti(); let result = if original_op.to_base().is_some() { - self.execute_instrumented(original_op, arg, vm) + self.execute_instrumented_from( + original_op, + arg, + wrapper_dispatch, + do_extend_arg, + vm, + ) } else { - let mut do_extend_arg = false; - self.execute_instruction(original_op, arg, &mut do_extend_arg, vm) + self.execute_instruction(original_op, arg, do_extend_arg, vm) }; let orig_caches = original_op.to_base().unwrap_or(original_op).cache_entries(); if orig_caches > 0 && self.lasti() == lasti_before_dispatch { @@ -8384,6 +8530,13 @@ impl ExecutingFrame<'_> { "INSTRUMENTED_INSTRUCTION at {idx} without stored opcode" ); + let wrapper_dispatch = monitoring::is_event_active_at( + vm, + self.code, + offset, + MonitoringEvent::Instruction, + ); + // Fire INSTRUCTION event monitoring::fire_instruction(vm, self.code, offset)?; @@ -8392,10 +8545,15 @@ impl ExecutingFrame<'_> { .expect("invalid opcode in instruction side-table"); let lasti_before_dispatch = self.lasti(); let result = if original_op.to_base().is_some() { - self.execute_instrumented(original_op, arg, vm) + self.execute_instrumented_from( + original_op, + arg, + wrapper_dispatch, + do_extend_arg, + vm, + ) } else { - let mut do_extend_arg = false; - self.execute_instruction(original_op, arg, &mut do_extend_arg, vm) + self.execute_instruction(original_op, arg, do_extend_arg, vm) }; let orig_caches = original_op.to_base().unwrap_or(original_op).cache_entries(); if orig_caches > 0 && self.lasti() == lasti_before_dispatch { @@ -8435,34 +8593,58 @@ impl ExecutingFrame<'_> { if let Some(builtins_dict) = self.builtins_dict { // Fast path: both globals and builtins are exact dicts // SAFETY: builtins_dict is only set when globals is also exact dict - let globals_exact = unsafe { PyExact::ref_unchecked(self.globals) }; - globals_exact - .get_chain_exact(builtins_dict, name, vm)? - .ok_or_else(|| { - vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned()) - }) + let globals = self + .globals + .as_object() + .downcast_ref::() + .expect("exact dict globals"); + if let Some(value) = globals.get_item_opt(name, vm)? { + return crate::lazy_import::reify_value(value, name, globals.as_object(), vm); + } + let value = builtins_dict.get_item_opt(name, vm)?.ok_or_else(|| { + vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned()) + })?; + crate::lazy_import::reify_value(value, name, builtins_dict.as_object(), vm) } else { // Slow path: builtins is not a dict, use generic __getitem__ if let Some(value) = self.globals.get_item_opt(name, vm)? { - return Ok(value); + return crate::lazy_import::reify_value(value, name, self.globals.as_object(), vm); } - self.builtins.get_item(name, vm).map_err(|e| { - if e.fast_isinstance(vm.ctx.exceptions.key_error) { - vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned()) - } else { - e - } - }) + self.load_builtin(name, vm) + } + } + + fn load_name_global_or_builtin(&self, name: &Py, vm: &VirtualMachine) -> PyResult { + // LOAD_NAME reads the stored global entries even for dict subclasses; + // LOAD_GLOBAL instead honors their __getitem__ implementation. + if let Some(value) = self.globals.inner_getitem_opt(name, vm)? { + return crate::lazy_import::reify_value(value, name, self.globals.as_object(), vm); } + self.load_builtin(name, vm) + } + + fn load_builtin(&self, name: &Py, vm: &VirtualMachine) -> PyResult { + let value = self.builtins.get_item(name, vm).map_err(|e| { + if e.fast_isinstance(vm.ctx.exceptions.key_error) { + vm.new_name_error(format!("name '{name}' is not defined"), name.to_owned()) + } else { + e + } + })?; + crate::lazy_import::reify_value(value, name, self.builtins, vm) } #[cfg_attr(feature = "flame-it", flame("FrameObject"))] - fn import(&mut self, vm: &VirtualMachine, module_name: Option<&Py>) -> PyResult<()> { - let module_name = module_name.unwrap_or(vm.ctx.empty_str); + fn import( + &mut self, + vm: &VirtualMachine, + module_name: &Py, + policy: u32, + ) -> PyResult<()> { let from_list = self.pop_value(); let level = usize::try_from_object(vm, self.pop_value())?; - let module = vm.import_from(module_name, from_list, level)?; + let module = crate::lazy_import::import_name(module_name, from_list, level, policy, vm)?; self.push_value(module); Ok(()) @@ -8471,109 +8653,13 @@ impl ExecutingFrame<'_> { #[cfg_attr(feature = "flame-it", flame("FrameObject"))] fn import_from(&mut self, vm: &VirtualMachine, idx: bytecode::NameIdx) -> PyResult { let module = self.top_value(); - let name = self.code.names[idx as usize]; - - // Load attribute, and transform any error into import error. - if let Some(obj) = vm.get_attribute_opt(module, name)? { - return Ok(obj); - } - // fallback to importing '{module.__name__}.{name}' from sys.modules - let fallback_module = (|| { - let mod_name = module.get_attr(identifier!(vm, __name__), vm).ok()?; - let mod_name = mod_name.downcast_ref::()?; - let full_mod_name = vm.ctx.new_utf8_str(format!("{}.{name}", mod_name.as_str())); - let sys_modules = vm.sys_module.get_attr("modules", vm).ok()?; - sys_modules.get_item(&*full_mod_name, vm).ok() - })(); - - if let Some(sub_module) = fallback_module { - return Ok(sub_module); - } - - use crate::import::{ - get_spec_file_origin, is_possibly_shadowing_path, is_stdlib_module_name, - }; - - // Get module name for the error message - let mod_name_obj = module.get_attr(identifier!(vm, __name__), vm).ok(); - let mod_name = mod_name_obj - .as_ref() - .and_then(|n| n.downcast_ref::()); - let module_name = mod_name.map_or("", |s| s.as_str()); - - let spec = module - .get_attr("__spec__", vm) - .ok() - .filter(|s| !vm.is_none(s)); - - let origin = get_spec_file_origin(spec.as_deref(), vm); - - let is_possibly_shadowing = origin - .as_ref() - .is_some_and(|o| is_possibly_shadowing_path(o, vm)); - let is_possibly_shadowing_stdlib = if is_possibly_shadowing { - if let Some(ref mod_name) = mod_name_obj { - is_stdlib_module_name(mod_name, vm)? - } else { - false - } - } else { - false - }; - - let msg = if is_possibly_shadowing_stdlib { - let origin = origin.as_ref().unwrap(); - format!( - "cannot import name '{name}' from '{module_name}' \ - (consider renaming '{origin}' since it has the same \ - name as the standard library module named '{module_name}' \ - and prevents importing that standard library module)" - ) - } else { - let is_init = is_module_initializing(module, vm); - if is_init { - if is_possibly_shadowing { - let origin = origin.as_ref().unwrap(); - format!( - "cannot import name '{name}' from '{module_name}' \ - (consider renaming '{origin}' if it has the same name \ - as a library you intended to import)" - ) - } else if let Some(ref path) = origin { - format!( - "cannot import name '{name}' from partially initialized module \ - '{module_name}' (most likely due to a circular import) ({path})" - ) - } else { - format!( - "cannot import name '{name}' from partially initialized module \ - '{module_name}' (most likely due to a circular import)" - ) - } - } else if let Some(ref path) = origin { - format!("cannot import name '{name}' from '{module_name}' ({path})") - } else { - format!("cannot import name '{name}' from '{module_name}' (unknown location)") - } - }; - let err = vm.new_import_error( - msg, - match mod_name { - Some(s) => s.to_owned().into_wtf8(), - None => vm.ctx.new_utf8_str("").into_wtf8(), - }, - ); + let name = self.code.names[idx]; - if let Some(ref path) = origin { - let _ignore = err - .as_object() - .set_attr("path", vm.ctx.new_str(path.as_str()), vm); + if let Some(deferred) = module.downcast_ref_if_exact::(vm) + { + return crate::lazy_import::import_from(deferred, name, vm); } - - // name_from = the attribute name that failed to import (best-effort metadata) - let _ignore = err.as_object().set_attr("name_from", name.to_owned(), vm); - - Err(err) + crate::import::import_from_attribute(module, name, vm) } #[cfg_attr(feature = "flame-it", flame("FrameObject"))] @@ -8639,6 +8725,7 @@ impl ExecutingFrame<'_> { if let Some(entry) = bytecode::find_exception_handler(&self.code.exceptiontable, offset) { + monitoring::reset_reraise_pending(); // Fire EXCEPTION_HANDLED before setting up handler. // If the callback raises, the handler is NOT set up and the // new exception propagates instead. @@ -8778,50 +8865,118 @@ impl ExecutingFrame<'_> { FuncArgs::with_kwargs_names(args, kwarg_names) } - fn collect_ex_args(&mut self, vm: &VirtualMachine) -> PyResult { + fn execute_call_ex(&mut self, vm: &VirtualMachine) -> FrameResult { let kwargs_or_null = self.pop_value_opt(); - let mut kwargs = KwArgs::default(); - if let Some(kw_obj) = kwargs_or_null { + // Only uninstrumented exact Python calls consume containers before + // executing the body. Other calls retain them through CALL/RETURN hooks. + let keep_owners = INSTRUMENTED + || self + .nth_value(2) + .downcast_ref_if_exact::(vm) + .is_none(); + let mut kwnames = Vec::new(); + let mut keyword_values = Vec::new(); + if let Some(kw_obj) = &kwargs_or_null { // Stack: [callable, self_or_null, args_tuple] let callable = self.nth_value(2); - let func_str = Self::object_function_str(callable, vm); - - Self::iterate_mapping_keys(vm, &kw_obj, &func_str, |key, value| { + Self::iterate_mapping_keys(vm, kw_obj, callable, |key, value| { // `PyStr`, not `PyUtf8Str`: CPython only checks that the key is a // `str`, not that it is valid UTF-8, so surrogate keys are accepted. - let key_str = key - .downcast_ref::() + key.downcast_ref::() .ok_or_else(|| vm.new_type_error("keywords must be strings"))?; - kwargs.insert(key_str.as_wtf8().to_owned(), value); + // Preserve string-subclass identity until the callee binds or merges keywords. + kwnames.push(key); + keyword_values.push(value); Ok(()) })? }; let args_obj = self.pop_value(); - let args = if let Some(tuple) = args_obj.downcast_ref::() { - tuple.as_slice().to_vec() + let (mut args, positional_owner) = + if let Some(tuple) = args_obj.downcast_ref_if_exact::(vm) { + let mut values = Vec::with_capacity(tuple.len() + keyword_values.len()); + values.extend_from_slice(tuple.as_slice()); + (values, keep_owners.then_some(Either::A(args_obj))) + } else { + // Single *arg passed directly; convert to sequence at runtime. + let not_iterable = args_obj.class().slots().iter.load().is_none() + && args_obj + .get_class_attr(vm.ctx.intern_str("__getitem__")) + .is_none(); + let values = args_obj.try_to_value::>(vm).map_err(|e| { + if not_iterable && e.class().is(vm.ctx.exceptions.type_error) { + vm.new_type_error(format!( + "Value after * must be an iterable, not {}", + args_obj.class().slot_name() + )) + } else { + e + } + })?; + // Normalization releases tuple subclasses and iterables before the + // call, but the resulting positional values still have an owner. + drop(args_obj); + if keep_owners { + let mut call_values = Vec::with_capacity(values.len() + keyword_values.len()); + call_values.extend_from_slice(&values); + (call_values, Some(Either::B(values))) + } else { + (values, None) + } + }; + args.extend(keyword_values); + let owners = positional_owner.map(|positional| ExCallOwners { + kwargs: kwargs_or_null, + positional, + }); + // Stack: [callable, self_or_null] + let self_or_null = self.pop_value_opt(); + let callable = self.pop_value(); + if let Some(self_val) = self_or_null { + args.insert(0, self_val); + } + let nargs = args.len() - kwnames.len(); + let arg0 = if INSTRUMENTED { + args[..nargs].first().cloned() } else { - // Single *arg passed directly; convert to sequence at runtime. - // Stack: [callable, self_or_null] - let callable = self.nth_value(1); - let func_str = Self::object_function_str(callable, vm); - let not_iterable = args_obj.class().slots().iter.load().is_none() - && args_obj - .get_class_attr(vm.ctx.intern_str("__getitem__")) - .is_none(); - args_obj.try_to_value::>(vm).map_err(|e| { - if not_iterable && e.class().is(vm.ctx.exceptions.type_error) { - vm.new_type_error(format!( - "{} argument after * must be an iterable, not {}", - func_str, - args_obj.class().slot_name() - )) + None + }; + let invoke = || { + // CPython CALL_FUNCTION_EX profiles the original callable, not the + // native function wrapped by a method. Bypass only that dispatch's + // profile events; Python callbacks and their native calls still trace. + if vm.use_tracing.get() + && let Some(method) = callable.downcast_ref::() + && method + .function_obj() + .downcast_ref::() + .is_some() + { + let function = method.function_obj(); + let native = function.to_callable().expect("native function is callable"); + args.insert(0, method.self_obj().to_owned()); + if let Some(vectorcall) = native.vectorcall { + vectorcall(function, args, nargs + 1, Some(&kwnames), vm) } else { - e + let args = FuncArgs::from_vectorcall_owned(args, nargs + 1, Some(&kwnames)); + (native.call)(function, args, vm) } - })? + } else { + callable.vectorcall(args, nargs, Some(&kwnames), vm) + } + }; + let result = if INSTRUMENTED { + self.execute_call_instrumented_inner::(&callable, arg0, invoke, vm) + } else { + invoke().map(|value| { + self.push_value(value); + None + }) }; - Ok(FuncArgs { args, kwargs }) + if let Some(owners) = owners { + owners.release(); + } + result } /// Returns a display string for a callable object for use in error messages. @@ -8854,7 +9009,7 @@ impl ExecutingFrame<'_> { fn iterate_mapping_keys( vm: &VirtualMachine, mapping: &PyObject, - func_str: &Wtf8, + callable: &PyObject, mut key_handler: F, ) -> PyResult<()> where @@ -8878,12 +9033,17 @@ impl ExecutingFrame<'_> { let Some(keys_method) = vm.get_method(mapping.to_owned(), vm.ctx.intern_str("keys")) else { return Err(vm.new_type_error(format!( "{} argument after ** must be a mapping, not {}", - func_str, + Self::object_function_str(callable, vm), mapping.class().name() ))); }; - let keys = PyIter::try_from_object(vm, keys_method?.call((), vm)?)?; + let keys = mapping.mapping_unchecked().collect_method_output( + identifier!(vm, keys), + keys_method?.call((), vm)?, + vm, + )?; + let keys = PyIter::try_from_object(vm, keys)?; while let PyIterReturn::Return(key) = keys.next(vm)? { let value = mapping.get_item(&*key, vm)?; key_handler(key, value)?; @@ -8891,6 +9051,61 @@ impl ExecutingFrame<'_> { Ok(()) } + // Keep descriptor-only argument handling out of the main opcode dispatch. + #[inline(never)] + fn execute_call_method_descriptor( + &mut self, + nargs: u32, + expected_flags: PyMethodFlags, + expected_nargs: Option, + vm: &VirtualMachine, + ) -> FrameResult { + let stack_len = self.localsplus.stack_len(); + let has_bound_receiver = self + .localsplus + .stack_index(stack_len - nargs as usize - 1) + .is_some(); + let total_nargs = nargs + u32::from(has_bound_receiver); + if total_nargs == 0 || expected_nargs.is_some_and(|expected| total_nargs != expected) { + return self.execute_call_vectorcall(nargs, vm); + } + let callable = self.nth_value(nargs + 1); + let receiver_index = stack_len - nargs as usize - 1 + usize::from(!has_bound_receiver); + if let Some(descr) = callable.downcast_ref_if_exact::(vm) + && (descr.method.flags + & (PyMethodFlags::VARARGS + | PyMethodFlags::FASTCALL + | PyMethodFlags::NOARGS + | PyMethodFlags::O + | PyMethodFlags::KEYWORDS)) + == expected_flags + && self + .localsplus + .stack_index(receiver_index) + .as_ref() + .is_some_and(|receiver| receiver.class().is(descr.common.typ)) + { + let func = descr.method.func; + let callee = Callee::named(descr.method.name); + let (_callable, receiver, args) = + self.take_native_method_args(nargs as usize, has_bound_receiver); + debug_assert_eq!(args.len() + 1, total_nargs as usize); + let result = func( + vm, + Some(&receiver), + FuncArgs { + args, + kwargs: Default::default(), + }, + callee, + )?; + self.push_value(result); + Ok(None) + } else { + self.execute_call_vectorcall(nargs, vm) + } + } + /// Vectorcall dispatch for Instruction::Call (positional args only). /// Uses vectorcall slot if available, otherwise falls back to FuncArgs. #[inline] @@ -9012,30 +9227,24 @@ impl ExecutingFrame<'_> { Ok(None) } - #[inline] - fn execute_call(&mut self, args: FuncArgs, vm: &VirtualMachine) -> FrameResult { - // Stack: [callable, self_or_null, ...] - let self_or_null = self.pop_value_opt(); // Option - let callable = self.pop_value(); - - let final_args = if let Some(self_val) = self_or_null { - let mut args = args; - args.prepend_arg(self_val); - args - } else { - args - }; - - let value = callable.call(final_args, vm)?; - self.push_value(value); - Ok(None) - } - /// Instrumented version of execute_call: fires CALL, C_RETURN, and C_RAISE events. fn execute_call_instrumented(&mut self, args: FuncArgs, vm: &VirtualMachine) -> FrameResult { let self_or_null = self.pop_value_opt(); let callable = self.pop_value(); + // Match CPython's _MAYBE_EXPAND_METHOD[_KW] before monitoring CALL. + // Calls that already carry a receiver must keep the original callable. + let (callable, self_or_null) = if self_or_null.is_none() + && let Some(method) = callable.downcast_ref_if_exact::(vm) + { + ( + method.function_obj().to_owned(), + Some(method.self_obj().to_owned()), + ) + } else { + (callable, self_or_null) + }; + let final_args = if let Some(self_val) = self_or_null { let mut args = args; args.prepend_arg(self_val); @@ -9044,29 +9253,43 @@ impl ExecutingFrame<'_> { args }; - let is_python_call = callable.downcast_ref_if_exact::(vm).is_some(); + let arg0 = final_args.args.first().cloned(); + self.execute_call_instrumented_inner::( + &callable, + arg0, + || callable.call(final_args, vm), + vm, + ) + } + + fn execute_call_instrumented_inner( + &mut self, + callable: &PyObject, + arg0: Option, + invoke: impl FnOnce() -> PyResult, + vm: &VirtualMachine, + ) -> FrameResult { + // CALL_FUNCTION_EX does not unwrap bound methods for C_RETURN/C_RAISE. + let is_python_call = callable.downcast_ref_if_exact::(vm).is_some() + || (EX && callable.downcast_ref::().is_some()); // Fire CALL event let call_arg0 = if self.monitoring_mask & MonitoringEvent::Call.mask() != 0 { - let arg0 = final_args - .args - .first() - .cloned() - .unwrap_or_else(|| monitoring::get_missing(vm)); + let arg0 = arg0.unwrap_or_else(|| monitoring::get_missing(vm)); let offset = (self.lasti() - 1) * 2; - monitoring::fire_call(vm, self.code, offset, &callable, arg0.clone())?; + monitoring::fire_call(vm, self.code, offset, callable, arg0.clone())?; Some(arg0) } else { None }; - match callable.call(final_args, vm) { + match invoke() { Ok(value) => { if let Some(arg0) = call_arg0 && !is_python_call { let offset = (self.lasti() - 1) * 2; - monitoring::fire_c_return(vm, self.code, offset, &callable, arg0)?; + monitoring::fire_c_return(vm, self.code, offset, callable, arg0)?; } self.push_value(value); Ok(None) @@ -9076,7 +9299,7 @@ impl ExecutingFrame<'_> { && !is_python_call { let offset = (self.lasti() - 1) * 2; - match monitoring::fire_c_raise(vm, self.code, offset, &callable, arg0) { + match monitoring::fire_c_raise(vm, self.code, offset, callable, arg0) { Ok(()) => exc, Err(monitor_exc) => monitor_exc, } @@ -9353,7 +9576,7 @@ impl ExecutingFrame<'_> { value: Option, vm: &VirtualMachine, ) -> PyResult<()> { - let iter = self.top_value(); + let iter = self.nth_value(1); if iter.downcast_ref_if_exact::(vm).is_some() || iter.downcast_ref_if_exact::(vm).is_some() || iter.downcast_ref_if_exact::(vm).is_some() @@ -9377,14 +9600,14 @@ impl ExecutingFrame<'_> { Ok(()) } - /// Advance the iterator on top of stack. + /// Advance the iterator below its index-or-NULL stack slot. /// Returns `true` if iteration continued (item pushed), `false` if exhausted (jumped). fn execute_for_iter( &mut self, vm: &VirtualMachine, target: bytecode::Label, ) -> Result { - let top = self.top_value(); + let top = self.nth_value(1); // FOR_ITER_RANGE: bypass generic iterator protocol for range iterators if let Some(range_iter) = top.downcast_ref_if_exact::(vm) { @@ -9415,10 +9638,7 @@ impl ExecutingFrame<'_> { self.jump(self.for_iter_jump_target(target)); Ok(false) } - Err(next_error) => { - self.pop_stackref(); - Err(next_error) - } + Err(next_error) => Err(next_error), } } @@ -9965,7 +10185,6 @@ impl ExecutingFrame<'_> { { Some(cloned) } else { - drop(cloned); None } } @@ -10102,7 +10321,7 @@ impl ExecutingFrame<'_> { return; } - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; // Match CPython: only specialize module attribute loads when the // current module dict has no __getattr__ override and the attribute is @@ -10356,7 +10575,7 @@ impl ExecutingFrame<'_> { ) { let obj = self.top_value(); let owner_type = obj.downcast_ref::().unwrap(); - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; // Check metaclass: ensure no data descriptor on metaclass for this name let mcl = obj.class(); @@ -10444,7 +10663,7 @@ impl ExecutingFrame<'_> { } fn load_attr_slow(&mut self, vm: &VirtualMachine, oparg: LoadAttr) -> FrameResult { - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; if !oparg.is_method() { // Regular attribute access: `get_attr` reads through the receiver, @@ -10657,6 +10876,11 @@ impl ExecutingFrame<'_> { && b.downcast_ref_if_exact::(vm).is_some() { Some(Instruction::BinaryOpMultiplyFloat) + } else if (sequence_int_guard(a, b, vm) || int_sequence_guard(a, b, vm)) + && let Some(descr) = self.binary_op_extended_specialization(op, a, b, vm) + { + cached_extend_descr = Some(descr); + Some(Instruction::BinaryOpExtend) } else { None } @@ -11105,7 +11329,9 @@ impl ExecutingFrame<'_> { return; } } - if cls.slots().vectorcall.load().is_some() { + if cls.slots().constructor_vectorcall.load().is_some() + && callable.vectorcall_func().is_some() + { self.specialize_at(instr_idx, cache_base, Instruction::CallBuiltinClass); return; } @@ -11315,8 +11541,8 @@ impl ExecutingFrame<'_> { ) { return; } - // Stack: [receiver, val] — receiver is at position 1 - let receiver = self.nth_value(1); + // Stack: [receiver, null_or_index, val] — receiver is at position 2 + let receiver = self.nth_value(2); let is_exact_gen_or_coro = receiver.downcast_ref_if_exact::(vm).is_some() || receiver.downcast_ref_if_exact::(vm).is_some(); if is_exact_gen_or_coro && !self.specialization_eval_frame_active(vm) { @@ -11582,7 +11808,7 @@ impl ExecutingFrame<'_> { ) { return; } - let iter = self.top_value(); + let iter = self.nth_value(1); let new_op = if iter.downcast_ref_if_exact::(vm).is_some() { Some(Instruction::ForIterRange) @@ -11675,7 +11901,7 @@ impl ExecutingFrame<'_> { let locals = if code.flags.contains(bytecode::CodeFlags::NEWLOCALS) { FrameLocals::lazy() } else { - FrameLocals::with_locals(crate::function::ArgMapping::from_dict_exact( + FrameLocals::with_locals(crate::function::ArgMapping::from_anydict_exact( func.globals.clone(), )) }; @@ -11741,7 +11967,7 @@ impl ExecutingFrame<'_> { let locals = if code.flags.contains(bytecode::CodeFlags::NEWLOCALS) { FrameLocals::lazy() } else { - FrameLocals::with_locals(crate::function::ArgMapping::from_dict_exact( + FrameLocals::with_locals(crate::function::ArgMapping::from_anydict_exact( func.globals.clone(), )) }; @@ -11817,7 +12043,7 @@ impl ExecutingFrame<'_> { fn specialize_load_global( &mut self, vm: &VirtualMachine, - oparg: u32, + oparg: LoadGlobal, instr_idx: usize, cache_base: usize, ) { @@ -11827,8 +12053,11 @@ impl ExecutingFrame<'_> { ) { return; } - let name = self.code.names[(oparg >> 1) as usize]; - let Ok(globals_version @ 1..) = u16::try_from(self.globals.assign_keys_version(vm)) else { + let Some(globals) = self.globals.as_mutable() else { + return; + }; + let name = self.code.names[oparg.name_idx()]; + let Ok(globals_version @ 1..) = u16::try_from(globals.assign_keys_version(vm)) else { unsafe { self.code.instructions.write_adaptive_counter( cache_base, @@ -11840,7 +12069,7 @@ impl ExecutingFrame<'_> { return; }; - if let Ok(Some(globals_hint)) = self.globals.hint_for_key(name, vm) { + if let Ok(Some(globals_hint)) = globals.hint_for_key(name, vm) { unsafe { self.code .instructions @@ -12024,12 +12253,11 @@ impl ExecutingFrame<'_> { return; } - let attr_name = self.code.names[attr_idx as usize]; + let attr_name = self.code.names[attr_idx]; let cls_attr = cls.get_attr(attr_name); let has_data_descr = cls_attr.as_ref().is_some_and(|descr| { - let descr_cls = descr.class(); - descr_cls.slots().descr_get.load().is_some() - && descr_cls.slots().descr_set.load().is_some() + // Assignment must honor __set__ even without __get__. + descr.class().slots().descr_set.load().is_some() }); if has_data_descr { @@ -12107,7 +12335,7 @@ impl ExecutingFrame<'_> { } fn load_super_attr(&mut self, vm: &VirtualMachine, oparg: LoadSuperAttr) -> FrameResult { - let attr_name = self.code.names[oparg.name_idx() as usize]; + let attr_name = self.code.names[oparg.name_idx()]; // Stack layout (bottom to top): [super, class, self] // Pop in LIFO order: self, class, super @@ -12145,7 +12373,7 @@ impl ExecutingFrame<'_> { } fn store_attr(&mut self, vm: &VirtualMachine, attr: bytecode::NameIdx) -> FrameResult { - let attr_name = self.code.names[attr as usize]; + let attr_name = self.code.names[attr]; let parent = self.pop_stackref(); let value = self.pop_value(); parent.set_attr(attr_name, value, vm)?; @@ -12153,7 +12381,7 @@ impl ExecutingFrame<'_> { } fn delete_attr(&mut self, vm: &VirtualMachine, attr: bytecode::NameIdx) -> FrameResult { - let attr_name = self.code.names[attr as usize]; + let attr_name = self.code.names[attr]; let parent = self.pop_stackref(); parent.del_attr(attr_name, vm)?; Ok(None) @@ -12470,6 +12698,44 @@ impl ExecutingFrame<'_> { (callable, args) } + // A checked native method's receiver stays out of the argument vector. + // Bound calls keep it in self_or_null; unbound calls pass it as arg1. + fn take_native_method_args( + &mut self, + nargs: usize, + has_bound_receiver: bool, + ) -> (PyObjectRef, PyObjectRef, Vec) { + let stack_len = self.localsplus.stack_len(); + debug_assert!(stack_len >= nargs + 2); + debug_assert!(has_bound_receiver || nargs > 0); + let callable_idx = stack_len - nargs - 2; + let receiver_idx = callable_idx + 1 + usize::from(!has_bound_receiver); + let receiver = self + .localsplus + .stack_index_mut(receiver_idx) + .take() + .expect("native method receiver was checked") + .to_pyobj(); + let mut args = Vec::with_capacity(stack_len - receiver_idx - 1); + for stack_idx in receiver_idx + 1..stack_len { + args.push( + self.localsplus + .stack_index_mut(stack_idx) + .take() + .unwrap() + .to_pyobj(), + ); + } + let callable = self + .localsplus + .stack_index_mut(callable_idx) + .take() + .unwrap() + .to_pyobj(); + self.localsplus.stack_truncate(callable_idx); + (callable, receiver, args) + } + /// Pop multiple values from the stack. Panics if any slot is NULL. fn pop_multiple(&mut self, count: usize) -> impl ExactSizeIterator + '_ { let stack_len = self.localsplus.stack_len(); @@ -12636,19 +12902,6 @@ fn get_special_method_error_msg( } } -fn is_module_initializing(module: &PyObject, vm: &VirtualMachine) -> bool { - let Ok(spec) = module.get_attr(&vm.ctx.new_str("__spec__"), vm) else { - return false; - }; - if vm.is_none(&spec) { - return false; - } - let Ok(initializing_attr) = spec.get_attr(&vm.ctx.new_str("_initializing"), vm) else { - return false; - }; - initializing_attr.try_to_bool(vm).unwrap_or(false) -} - fn expect_unchecked(optional: Option, err_msg: &'static str) -> T { if cfg!(debug_assertions) { optional.expect(err_msg) @@ -12656,3 +12909,53 @@ fn expect_unchecked(optional: Option, err_msg: &'static str) - unsafe { optional.unwrap_unchecked() } } } + +fn suspended_delegate<'a>( + code: &PyCode, + localsplus: &'a LocalsPlus, + lasti: u32, +) -> Option<&'a PyObject> { + // checks gi_frame_state == FRAME_SUSPENDED_YIELD_FROM + // which is set when YIELD_VALUE with oparg >= 1 is executed. + // In RustPython, we check: + // 1. lasti points to RESUME (after YIELD_VALUE) + // 2. The previous instruction was YIELD_VALUE with arg >= 1 + // 3. The delegate (receiver) is below its index-or-NULL slot + // + // First check if stack is empty - if so, we can't be in yield-from + if localsplus.stack_len() < 2 { + return None; + } + let lasti = lasti as usize; + if let Some(unit) = code.instructions.get(lasti) { + match &unit.op { + Instruction::Send { .. } | Instruction::SendGen => { + return localsplus + .stack_index(localsplus.stack_len() - 2) + .map(|value| value.as_object()); + } + Instruction::Resume { .. } | Instruction::InstrumentedResume => { + // Check if previous instruction was YIELD_VALUE with arg >= 1 + // This indicates yield-from/await context + if lasti > 0 + && let Some(prev_unit) = code.instructions.get(lasti - 1) + && matches!( + &prev_unit.op.into(), + Opcode::YieldValue | Opcode::InstrumentedYieldValue + ) + { + // YIELD_VALUE arg: 0 = direct yield, >= 1 = yield-from/await + // OpArgByte.0 is the raw byte value + if u8::from(prev_unit.arg) >= 1 { + // The iterator pair remains after YIELD_VALUE. + return localsplus + .stack_index(localsplus.stack_len() - 2) + .map(|value| value.as_object()); + } + } + } + _ => {} + } + } + None +} diff --git a/crates/vm/src/frozen_resources.rs b/crates/vm/src/frozen_resources.rs new file mode 100644 index 00000000000..c0868433fa9 --- /dev/null +++ b/crates/vm/src/frozen_resources.rs @@ -0,0 +1,719 @@ +//! Resource indexes bound to a particular registration of frozen modules. + +use crate::frozen::FrozenModule; +use alloc::{ + collections::{BTreeMap, BTreeSet}, + sync::Arc, +}; +use core::fmt; +use std::collections::HashMap; + +/// A package-relative logical POSIX path and its embedded contents. +pub type FrozenResource = (&'static str, &'static [u8]); +/// A frozen package name and the resources registered with its code. +pub type FrozenResourceBundle = (&'static str, &'static [FrozenResource]); + +#[derive(Clone, Debug, Eq, PartialEq)] +pub enum ResourceError { + InvalidPath(String), + DuplicatePath(String), + FileDirectoryCollision(String), + DuplicateModule(String), + DuplicateOwner(String), + MissingOwner(String), + OwnerNotPackage(String), + NotFound(String), + IsDirectory(String), + NotDirectory(String), +} + +impl fmt::Display for ResourceError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let (description, path) = match self { + Self::InvalidPath(path) => ("invalid relative resource path", path), + Self::DuplicatePath(path) => ("duplicate resource path", path), + Self::FileDirectoryCollision(path) => ("resource is both a file and directory", path), + Self::DuplicateModule(path) => { + ("duplicate frozen module in resource registration", path) + } + Self::DuplicateOwner(path) => ("duplicate frozen resource owner", path), + Self::MissingOwner(path) => ("resource owner is absent from this registration", path), + Self::OwnerNotPackage(path) => ("resource owner is not a package", path), + Self::NotFound(path) => ("resource does not exist", path), + Self::IsDirectory(path) => ("resource is a directory", path), + Self::NotDirectory(path) => ("resource is not a directory", path), + }; + write!(f, "{description}: {path:?}") + } +} + +impl core::error::Error for ResourceError {} + +fn normalize_relative(path: &str) -> Result { + if path.starts_with('/') || path.contains(['\\', '\0', ':']) { + return Err(ResourceError::InvalidPath(path.to_owned())); + } + let mut parts = Vec::new(); + for part in path.split('/') { + match part { + "" | "." => {} + ".." => return Err(ResourceError::InvalidPath(path.to_owned())), + _ => parts.push(part), + } + } + Ok(parts.join("/")) +} + +/// An immutable tree of embedded files, with explicit inferred directories. +#[derive(Debug)] +pub struct ResourceIndex { + root_name: &'static str, + files: BTreeMap, + directories: BTreeSet, +} + +impl ResourceIndex { + fn add_directory(&mut self, path: &str) -> Result<(), ResourceError> { + let normalized = normalize_relative(path)?; + if normalized != path { + return Err(ResourceError::InvalidPath(path.to_owned())); + } + let mut directory = path; + loop { + if self.files.contains_key(directory) { + return Err(ResourceError::FileDirectoryCollision(directory.to_owned())); + } + self.directories.insert(directory.to_owned()); + let Some((parent, _)) = directory.rsplit_once('/') else { + break; + }; + directory = parent; + } + Ok(()) + } + + fn new(owner: &'static str, resources: &[FrozenResource]) -> Result { + let mut index = Self { + root_name: owner.rsplit('.').next().unwrap_or(owner), + files: BTreeMap::new(), + directories: BTreeSet::from([String::new()]), + }; + for &(path, bytes) in resources { + let normalized = normalize_relative(path)?; + // Manifest paths are canonical; query paths may contain harmless dots or slashes. + if normalized.is_empty() || normalized != path { + return Err(ResourceError::InvalidPath(path.to_owned())); + } + if index.files.contains_key(path) { + return Err(ResourceError::DuplicatePath(path.to_owned())); + } + if index.directories.contains(path) { + return Err(ResourceError::FileDirectoryCollision(path.to_owned())); + } + let mut parent = path; + while let Some((prefix, _)) = parent.rsplit_once('/') { + if index.files.contains_key(prefix) { + return Err(ResourceError::FileDirectoryCollision(prefix.to_owned())); + } + index.directories.insert(prefix.to_owned()); + parent = prefix; + } + index.files.insert(normalized, bytes); + } + Ok(index) + } +} + +/// An immutable snapshot of one directory or file in an embedded resource tree. +#[derive(Clone, Debug)] +pub struct ResourceView { + index: Arc, + prefix: String, +} + +impl ResourceView { + #[must_use] + pub fn name(&self) -> &str { + if self.prefix.is_empty() { + self.index.root_name + } else { + self.prefix.rsplit('/').next().unwrap_or(&self.prefix) + } + } + + #[must_use] + pub fn is_file(&self) -> bool { + self.index.files.contains_key(&self.prefix) + } + + #[must_use] + pub fn is_dir(&self) -> bool { + self.index.directories.contains(&self.prefix) + } + + pub fn join(&self, descendant: &str) -> Result { + let descendant = normalize_relative(descendant)?; + let prefix = match (self.prefix.is_empty(), descendant.is_empty()) { + (_, true) => self.prefix.clone(), + (true, false) => descendant, + (false, false) => format!("{}/{descendant}", self.prefix), + }; + Ok(Self { + index: self.index.clone(), + prefix, + }) + } + + pub fn children(&self) -> Result, ResourceError> { + if !self.is_dir() { + return Err(if self.is_file() { + ResourceError::NotDirectory(self.prefix.clone()) + } else { + ResourceError::NotFound(self.prefix.clone()) + }); + } + let prefix = if self.prefix.is_empty() { + String::new() + } else { + format!("{}/", self.prefix) + }; + let children: BTreeSet<_> = self + .index + .files + .keys() + .chain(self.index.directories.iter()) + .filter(|path| { + path.strip_prefix(prefix.as_str()) + .is_some_and(|rest| !rest.is_empty() && !rest.contains('/')) + }) + .cloned() + .collect(); + Ok(children + .into_iter() + .map(|prefix| Self { + index: self.index.clone(), + prefix, + }) + .collect()) + } + + pub fn bytes(&self) -> Result<&'static [u8], ResourceError> { + self.index.files.get(&self.prefix).copied().ok_or_else(|| { + if self.is_dir() { + ResourceError::IsDirectory(self.prefix.clone()) + } else { + ResourceError::NotFound(self.prefix.clone()) + } + }) + } +} + +pub(crate) struct FrozenRegistration { + modules: Vec<(&'static str, FrozenModule)>, + resources: BTreeMap<&'static str, Arc>, +} + +impl FrozenRegistration { + pub(crate) fn code_only( + modules: impl IntoIterator, + ) -> Self { + Self { + modules: modules.into_iter().collect(), + resources: BTreeMap::new(), + } + } + + pub(crate) fn with_resources( + modules: impl IntoIterator, + resources: &[FrozenResourceBundle], + ) -> Result { + let mut registration = Self::code_only(modules); + let mut names = BTreeMap::new(); + for &(name, module) in ®istration.modules { + if names.insert(name, module.package).is_some() { + return Err(ResourceError::DuplicateModule(name.to_owned())); + } + } + for &(owner, files) in resources { + if owner.is_empty() + || owner.split('.').any(str::is_empty) + || owner.contains(['/', '\\', '\0', ':']) + { + return Err(ResourceError::InvalidPath(owner.to_owned())); + } + match names.get(owner) { + None => return Err(ResourceError::MissingOwner(owner.to_owned())), + Some(false) => return Err(ResourceError::OwnerNotPackage(owner.to_owned())), + Some(true) => {} + } + if registration.resources.contains_key(owner) { + return Err(ResourceError::DuplicateOwner(owner.to_owned())); + } + let mut index = ResourceIndex::new(owner, files)?; + for (&name, &package) in &names { + if package + && let Some(suffix) = name.strip_prefix(owner) + && let Some(relative) = suffix.strip_prefix('.') + { + index.add_directory(&relative.replace('.', "/"))?; + } + } + registration.resources.insert(owner, Arc::new(index)); + } + Ok(registration) + } +} + +#[derive(Clone, Copy)] +struct FrozenEntry { + module: FrozenModule, + registration: u64, +} + +#[derive(Clone)] +struct ResourceBinding { + owner: &'static str, + owner_registration: u64, + anchor_registration: u64, + view: ResourceView, +} + +/// Frozen modules with resource ownership invalidated on every replacement. +/// +/// Mutable map access is deliberately not exposed: even identical-byte replacements +/// are distinct registrations and must not inherit another registration's resources. +#[derive(Clone, Default)] +pub struct FrozenModuleRegistry { + modules: HashMap<&'static str, FrozenEntry, rapidhash::quality::RandomState>, + bindings: BTreeMap<&'static str, ResourceBinding>, + next_registration: u64, +} + +impl FrozenModuleRegistry { + #[must_use] + pub fn new() -> Self { + Self::default() + } + + #[must_use] + pub fn get(&self, name: &str) -> Option<&FrozenModule> { + self.modules.get(name).map(|entry| &entry.module) + } + + pub fn keys(&self) -> impl Iterator { + self.modules.keys() + } + + #[must_use] + pub fn len(&self) -> usize { + self.modules.len() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.modules.is_empty() + } + + #[must_use] + pub fn contains_key(&self, name: &str) -> bool { + self.modules.contains_key(name) + } + + fn next_token(&mut self) -> u64 { + self.next_registration = self + .next_registration + .checked_add(1) + .expect("frozen module registration counter exhausted"); + self.next_registration + } + + fn invalidate(&mut self, name: &str) { + self.bindings.retain(|anchor, binding| { + *anchor != name + && binding.owner != name + && !anchor + .strip_prefix(name) + .is_some_and(|suffix| suffix.starts_with('.')) + }); + } + + pub fn insert(&mut self, name: &'static str, module: FrozenModule) -> Option { + let registration = self.next_token(); + self.invalidate(name); + self.modules + .insert( + name, + FrozenEntry { + module, + registration, + }, + ) + .map(|entry| entry.module) + } + + pub fn remove(&mut self, name: &str) -> Option { + self.invalidate(name); + self.modules.remove(name).map(|entry| entry.module) + } + + pub fn clear(&mut self) { + self.bindings.clear(); + self.modules.clear(); + } + + pub fn register_with_resources( + &mut self, + modules: impl IntoIterator, + resources: &[FrozenResourceBundle], + ) -> Result<(), ResourceError> { + let registration = FrozenRegistration::with_resources(modules, resources)?; + self.apply_registration(registration); + Ok(()) + } + + pub(crate) fn apply_registration(&mut self, batch: FrozenRegistration) { + let registration = self.next_token(); + for &(name, module) in &batch.modules { + self.invalidate(name); + self.modules.insert( + name, + FrozenEntry { + module, + registration, + }, + ); + } + for &(anchor, module) in &batch.modules { + let package = if module.package { + anchor + } else if let Some((package, _)) = anchor.rsplit_once('.') { + package + } else { + continue; + }; + let owner = batch + .resources + .keys() + .copied() + .filter(|owner| { + package == *owner + || package + .strip_prefix(*owner) + .is_some_and(|suffix| suffix.starts_with('.')) + }) + .max_by_key(|owner| owner.len()); + let Some(owner) = owner else { + continue; + }; + // Every containing package down to the owner must belong to this batch. + let mut current = package; + let eligible = + loop { + if !self.modules.get(current).is_some_and(|entry| { + entry.registration == registration && entry.module.package + }) { + break false; + } + if current == owner { + break true; + } + let Some((parent, _)) = current.rsplit_once('.') else { + break false; + }; + current = parent; + }; + if !eligible { + continue; + } + let prefix = package + .strip_prefix(owner) + .unwrap_or_default() + .trim_start_matches('.') + .replace('.', "/"); + let view = ResourceView { + index: batch.resources[owner].clone(), + prefix, + }; + self.bindings.insert( + anchor, + ResourceBinding { + owner, + owner_registration: registration, + anchor_registration: registration, + view, + }, + ); + } + } + + /// Acquire a snapshot only if both the exact anchor and owner are still current. + #[must_use] + pub fn resource_view(&self, fullname: &str) -> Option { + let binding = self.bindings.get(fullname)?; + let anchor = self.modules.get(fullname)?; + let owner = self.modules.get(binding.owner)?; + (anchor.registration == binding.anchor_registration + && owner.registration == binding.owner_registration + && owner.module.package) + .then(|| binding.view.clone()) + } +} + +impl Extend<(&'static str, FrozenModule)> for FrozenModuleRegistry { + fn extend>(&mut self, iter: T) { + self.apply_registration(FrozenRegistration::code_only(iter)); + } +} + +impl FromIterator<(&'static str, FrozenModule)> for FrozenModuleRegistry { + fn from_iter>(iter: T) -> Self { + let mut registry = Self::new(); + registry.extend(iter); + registry + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::frozen::FrozenCodeObject; + + const ASSETS: &[FrozenResource] = + &[("data.txt", b"hello"), ("nested/4.1.3/data.bin", b"\0\xff")]; + const BUNDLES: &[FrozenResourceBundle] = &[("sample", ASSETS)]; + + fn module(package: bool) -> FrozenModule { + FrozenModule { + code: FrozenCodeObject { + bytes: b"same-code", + }, + package, + } + } + + fn registered() -> FrozenModuleRegistry { + let mut registry = FrozenModuleRegistry::new(); + registry + .register_with_resources( + [("sample", module(true)), ("sample.worker", module(false))], + BUNDLES, + ) + .unwrap(); + registry + } + + #[test] + fn replacement_never_inherits_identical_code_resources() { + let mut registry = registered(); + let snapshot = registry.resource_view("sample").unwrap(); + registry.insert("sample", module(true)); + assert!(registry.resource_view("sample").is_none()); + assert!(registry.resource_view("sample.worker").is_none()); + assert_eq!( + snapshot.join("data.txt").unwrap().bytes().unwrap(), + b"hello" + ); + registry + .register_with_resources([("sample", module(true))], BUNDLES) + .unwrap(); + assert!(registry.resource_view("sample").is_some()); + assert!(registry.resource_view("sample.worker").is_none()); + } + + #[test] + fn anchor_replacement_and_unrelated_registration() { + let mut registry = registered(); + registry.extend([("other", module(true)), ("sample.worker", module(false))]); + assert!(registry.resource_view("sample").is_some()); + assert!(registry.resource_view("sample.worker").is_none()); + assert!(registry.resource_view("sample.unknown").is_none()); + assert!(registry.resource_view("samplex").is_none()); + } + + #[test] + fn clones_have_independent_ownership() { + let parent = registered(); + let mut child = parent.clone(); + child.remove("sample"); + assert!(parent.resource_view("sample").is_some()); + assert!(child.resource_view("sample").is_none()); + child.insert("sample", module(true)); + assert!(child.resource_view("sample").is_none()); + } + + #[test] + fn resource_replacement_and_clear_do_not_merge_old_assets() { + const REPLACEMENT: &[FrozenResourceBundle] = &[("sample", &[("new.txt", b"new")])]; + let mut registry = registered(); + registry + .register_with_resources([("sample", module(true))], REPLACEMENT) + .unwrap(); + let view = registry.resource_view("sample").unwrap(); + assert!(!view.join("data.txt").unwrap().is_file()); + assert_eq!(view.join("new.txt").unwrap().bytes().unwrap(), b"new"); + registry.clear(); + registry.extend([("sample", module(true))]); + assert!(registry.resource_view("sample").is_none()); + } + + #[test] + fn invalid_batch_is_atomic() { + let mut registry = registered(); + assert_eq!( + registry.register_with_resources([("other", module(true))], BUNDLES), + Err(ResourceError::MissingOwner("sample".to_owned())) + ); + assert!(!registry.contains_key("other")); + assert!(registry.resource_view("sample").is_some()); + assert_eq!( + registry.register_with_resources([("sample", module(false))], BUNDLES), + Err(ResourceError::OwnerNotPackage("sample".to_owned())) + ); + assert_eq!( + registry.register_with_resources( + [("sample", module(true)), ("sample", module(true))], + BUNDLES + ), + Err(ResourceError::DuplicateModule("sample".to_owned())) + ); + } + + #[test] + fn tree_queries_are_component_based() { + let registry = registered(); + let root = registry.resource_view("sample").unwrap(); + assert_eq!(root.name(), "sample"); + assert!(root.is_dir()); + assert_eq!( + root.children() + .unwrap() + .iter() + .map(ResourceView::name) + .collect::>(), + ["data.txt", "nested"] + ); + assert_eq!( + root.join("./nested//4.1.3/data.bin") + .unwrap() + .bytes() + .unwrap(), + b"\0\xff" + ); + assert!(!root.join("nest").unwrap().is_dir()); + assert!(matches!(root.bytes(), Err(ResourceError::IsDirectory(_)))); + assert!(matches!( + root.join("data.txt").unwrap().children(), + Err(ResourceError::NotDirectory(_)) + )); + let missing = root.join("missing").unwrap(); + assert!(!missing.is_file() && !missing.is_dir()); + assert!(matches!(missing.bytes(), Err(ResourceError::NotFound(_)))); + assert!(matches!( + missing.children(), + Err(ResourceError::NotFound(_)) + )); + } + + #[test] + fn unsafe_paths_are_rejected() { + let root = registered().resource_view("sample").unwrap(); + for path in [ + "../data.txt", + "nested/../data.txt", + "/data.txt", + "C:data.txt", + "C:/data.txt", + "\\\\host\\file", + "nested\\data.txt", + "nul\0name", + ] { + assert!(matches!( + root.join(path), + Err(ResourceError::InvalidPath(_)) + )); + } + assert_eq!(root.join("").unwrap().name(), "sample"); + } + + #[test] + fn manifests_reject_collisions_in_either_order() { + for entries in [ + vec![("a", b"x".as_slice()), ("a/b", b"x".as_slice())], + vec![("a/b", b"x".as_slice()), ("a", b"x".as_slice())], + ] { + assert!(matches!( + ResourceIndex::new("sample", &entries), + Err(ResourceError::FileDirectoryCollision(_)) + )); + } + assert!(matches!( + ResourceIndex::new("sample", &[("a", b"x"), ("a", b"y")]), + Err(ResourceError::DuplicatePath(_)) + )); + assert!(matches!( + ResourceIndex::new("sample", &[("./a", b"x")]), + Err(ResourceError::InvalidPath(_)) + )); + } + + #[test] + fn nested_package_anchors_require_same_registration() { + let mut registry = FrozenModuleRegistry::new(); + registry.insert("sample.nested", module(true)); + registry + .register_with_resources( + [ + ("sample", module(true)), + ("sample.nested.worker", module(false)), + ], + BUNDLES, + ) + .unwrap(); + assert!(registry.resource_view("sample.nested.worker").is_none()); + registry + .register_with_resources( + [ + ("sample", module(true)), + ("sample.nested", module(true)), + ("sample.nested.worker", module(false)), + ], + BUNDLES, + ) + .unwrap(); + let view = registry.resource_view("sample.nested.worker").unwrap(); + assert_eq!(view.name(), "nested"); + assert!(view.is_dir()); + registry.insert("sample.nested", module(true)); + assert!(registry.resource_view("sample.nested.worker").is_none()); + } + + #[test] + fn package_without_files_has_an_empty_directory_view() { + let mut registry = FrozenModuleRegistry::new(); + registry + .register_with_resources( + [("sample", module(true)), ("sample.empty", module(true))], + BUNDLES, + ) + .unwrap(); + let root = registry.resource_view("sample.empty").unwrap(); + assert!(root.is_dir()); + assert!(!root.is_file()); + assert!(root.children().unwrap().is_empty()); + assert!(matches!(root.bytes(), Err(ResourceError::IsDirectory(_)))); + } + + #[test] + fn package_directories_cannot_collide_with_embedded_files() { + const FILE: &[FrozenResourceBundle] = &[("sample", &[("nested", b"file")])]; + let mut registry = FrozenModuleRegistry::new(); + assert_eq!( + registry.register_with_resources( + [("sample", module(true)), ("sample.nested", module(true))], + FILE, + ), + Err(ResourceError::FileDirectoryCollision("nested".to_owned())) + ); + assert!(registry.is_empty()); + } +} diff --git a/crates/vm/src/function/argument.rs b/crates/vm/src/function/argument.rs index 2106a668f77..6cf2054a269 100644 --- a/crates/vm/src/function/argument.rs +++ b/crates/vm/src/function/argument.rs @@ -1,4 +1,4 @@ -use super::signature::Param; +use super::signature::{Param, ParamKind, params_take_no_keywords}; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyBaseExceptionRef, PyTupleRef, PyType}, @@ -6,6 +6,7 @@ use crate::{ convert::ToPyObject, object::{Traverse, TraverseFn}, }; +use alloc::borrow::Cow; use core::ops::{Deref, DerefMut, RangeInclusive}; use indexmap::IndexMap; use itertools::Itertools; @@ -109,6 +110,15 @@ impl FromArgs for FuncArgs { } impl FuncArgs { + /// Release a borrowed native call's owners in evaluation-stack order. + /// Keyword values follow positional values on that stack. Expanded calls + /// retain their tuple/dict owners at the call site instead. + #[inline(always)] + pub(super) fn drop_reverse(self) { + self.kwargs.into_iter().rev().for_each(drop); + self.args.into_iter().rev().for_each(drop); + } + pub fn new(args: A, kwargs: K) -> Self where A: Into, @@ -280,6 +290,91 @@ impl FuncArgs { self.kwargs.drain(..) } + /// Bind a finite borrowed signature without moving, cloning, or allocating + /// any argument storage. Each named field is looked up once; conversion + /// starts only after all Clinic binding errors have been ruled out. + #[inline] + pub fn bind_borrowed( + &self, + vm: &VirtualMachine, + callee: Callee, + ) -> PyResult<[Option<&PyObject>; N]> { + let shape = const { + let shape = match BindingShape::for_parser(T::CLINIC_PARAMS, T::UNPACK_KEYWORDS) { + Some(shape) => shape, + None => panic!("borrowed arguments require a known Clinic signature"), + }; + assert!(shape.fixed == N && !shape.var_positional && !shape.var_keyword); + let params = T::CLINIC_PARAMS.unwrap(); + assert!( + params.len() == N, + "borrowed arguments cannot flatten fields" + ); + let mut i = 0; + while i < N { + assert!(matches!( + params[i].kind, + ParamKind::PositionalOnly + | ParamKind::PositionalOrKeyword + | ParamKind::KeywordOnly + )); + i += 1; + } + shape + }; + if let Some(error) = shape.check_counts(self, callee, vm) { + return Err(error); + } + let mut slots = [None; N]; + if self.kwargs.is_empty() + && self.args.len() >= shape.required_positional + && !shape.required_keyword_only + { + for (slot, value) in slots.iter_mut().zip(&self.args) { + *slot = Some(&**value); + } + return Ok(slots); + } + let mut positional = 0; + let mut duplicate = None; + let mut matched = 0; + for (i, param) in T::CLINIC_PARAMS.unwrap().iter().enumerate() { + let value = match param.kind { + ParamKind::PositionalOnly => { + let value = self.args.get(positional); + positional += 1; + value + } + ParamKind::PositionalOrKeyword | ParamKind::KeywordOnly => { + let keyword = self.kwargs.get(param.name); + matched += usize::from(keyword.is_some()); + if matches!(param.kind, ParamKind::PositionalOrKeyword) { + let value = self.args.get(positional); + positional += 1; + if value.is_some() && keyword.is_some() && duplicate.is_none() { + duplicate = Some((param.name, i + 1)); + } + value.or(keyword) + } else { + keyword + } + } + _ => unreachable!("borrowed signature was checked at compile time"), + }; + if value.is_none() && param.default.is_none() { + return Err(callee.missing_argument(param.name, i + 1, vm)); + } + slots[i] = value.map(|value| &**value); + } + if let Some((name, position)) = duplicate { + return Err(callee.given_by_name_and_position(name, position, vm)); + } + if matched < self.kwargs.len() { + return Err(shape.unexpected_keyword(self, callee, vm).unwrap()); + } + Ok(slots) + } + /// Binds these arguments to their respective values. /// /// If there is an insufficient number of arguments, there are leftover @@ -300,18 +395,26 @@ impl FuncArgs { callee: impl Into, ) -> PyResult { let callee = callee.into(); - // A message describes the parameters the function declares, and the - // instance a method is called on is not one of them. - let instance = callee.instance_args(); let arity = T::arity(); - let arity = arity.start().saturating_sub(instance)..=arity.end().saturating_sub(instance); - let num_given = self.args.len().saturating_sub(instance); + let nargs = self.args.len(); + let num_given = nargs; + + if let Some(err) = T::check_before_convert(&self, &arity, num_given, callee, vm) { + return Err(err); + } - let bound = T::from_args(vm, &mut self) - .map_err(|e| e.into_exception(&arity, num_given, callee, vm))?; + let bound = match T::from_args(vm, &mut self) { + Ok(bound) => bound, + Err(e) => { + // take_positional has just removed the failed argument, so N is + // nargs - remaining. Native receivers never enter FuncArgs. + let pos = nargs.saturating_sub(self.args.len()); + return Err(e.into_exception(&arity, num_given, pos, callee, vm)); + } + }; if !self.args.is_empty() { - Err(ArgumentError::TooManyArgs.into_exception(&arity, num_given, callee, vm)) + Err(ArgumentError::TooManyArgs.into_exception(&arity, num_given, 0, callee, vm)) } else if let Some(err) = self.check_kwargs_empty_for(vm, callee) { Err(err) } else { @@ -342,13 +445,10 @@ impl FuncArgs { /// /// A binding that happens somewhere the name isn't known leaves it off, the way /// `_PyArg_Parser.fname` is NULL. A message describes the parameters the -/// function declares, so a method's instance argument counts as neither an -/// expected parameter nor a given argument, the way `descrobject.c` reports -/// `nargs - 1`. +/// function declares. Native receivers are passed separately from those arguments. #[derive(Clone, Copy, Debug, Default)] pub struct Callee { name: Option<&'static str>, - instance_arg: bool, } impl From<&'static str> for Callee { @@ -361,10 +461,7 @@ impl Callee { /// A function a message can name. #[must_use] pub const fn named(name: &'static str) -> Self { - Self { - name: Some(name), - instance_arg: false, - } + Self { name: Some(name) } } /// The type a slot builds or initializes, named the way a message names it. @@ -379,17 +476,11 @@ impl Callee { Self::for_type(T::class(&vm.ctx)) } - /// Marks a call whose leading argument fills the method's instance parameter. - #[must_use] - pub const fn with_instance_arg(mut self, instance_arg: bool) -> Self { - self.instance_arg = instance_arg; - self - } - - /// How many leading arguments answer for the instance rather than for a - /// parameter the method declares. - const fn instance_args(self) -> usize { - self.instance_arg as usize + pub(crate) fn missing_receiver(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + vm.new_type_error(format!( + "unbound method {} needs an argument", + self.name.unwrap_or("") + )) } /// _PyArg_CheckPositional @@ -408,6 +499,15 @@ impl Callee { vm.new_type_error(unexpected_keyword_message(self.name, keyword)) } + fn given_by_name_and_position( + self, + keyword: &str, + pos: usize, + vm: &VirtualMachine, + ) -> PyBaseExceptionRef { + vm.new_type_error(given_by_name_and_position_message(self.name, keyword, pos)) + } + /// The branch of _PyArg_UnpackKeywords that names a parameter it didn't get. fn missing_argument( self, @@ -417,6 +517,41 @@ impl Callee { ) -> PyBaseExceptionRef { vm.new_type_error(missing_argument_message(self.name, keyword, pos)) } + + /// _PyArg_NoKeywords + fn no_keywords(self, vm: &VirtualMachine) -> PyBaseExceptionRef { + vm.new_type_error(no_keywords_message(self.name)) + } + + /// _PyArg_BadArgument + fn bad_argument( + self, + displayname: &str, + expected: &'static Py, + or_none: bool, + found: &PyObject, + vm: &VirtualMachine, + ) -> PyBaseExceptionRef { + let expected_ty = expected.slot_name(); + let expected = if or_none { + Cow::Owned(format!("{expected_ty} or None")) + } else { + Cow::Borrowed(&*expected_ty) + }; + let class = found.class(); + let found_ty = class.slot_name(); + let found_name = if vm.is_none(found) { + "None" + } else { + &*found_ty + }; + vm.new_type_error(bad_argument_message( + self.name, + displayname, + &expected, + found_name, + )) + } } /// The name a message uses. `tp_name` carries the module along with the type, @@ -464,6 +599,429 @@ pub(crate) fn unexpected_keyword_message(name: Option<&str>, keyword: &str) -> S format!("{name}{parens} got an unexpected keyword argument '{keyword}'") } +/// _PyArg_NoKeywords +pub(crate) fn no_keywords_message(name: Option<&str>) -> String { + let (name, parens) = call_form(name, "this function"); + format!("{name}{parens} takes no keyword arguments") +} + +/// get_displayname +fn get_displayname(name: Option<&str>, pos: usize, meth_o: bool) -> Cow<'static, str> { + if let Some(name) = name { + Cow::Owned(format!("argument '{name}'")) + } else if meth_o { + Cow::Borrowed("argument") + } else { + Cow::Owned(format!("argument {pos}")) + } +} + +/// _PyArg_BadArgument +pub(crate) fn bad_argument_message( + name: Option<&str>, + displayname: &str, + expected: &str, + found: &str, +) -> String { + let (name, parens) = call_form(name, "this function"); + // _PyArg_BadArgument caps UTF-8 byte lengths, excluding a partial code point. + let name = &name[..name.floor_char_boundary(200)]; + let displayname = &displayname[..displayname.floor_char_boundary(200)]; + let expected = &expected[..expected.floor_char_boundary(50)]; + let found = &found[..found.floor_char_boundary(50)]; + format!("{name}{parens} {displayname} must be {expected}, not {found}") +} + +pub(crate) fn given_by_name_and_position_message( + name: Option<&str>, + keyword: &str, + pos: usize, +) -> String { + let (name, parens) = call_form(name, "function"); + format!("argument for {name}{parens} given by name ('{keyword}') and position ({pos})") +} + +/// Compile-time counts for a binding whose entire parameter tree is known. +struct BindingShape { + params: &'static [Param], + fixed: usize, + positional: usize, + required_positional: usize, + required_positional_only: usize, + has_keywords: bool, + var_positional: bool, + var_keyword: bool, + required_keyword_only: bool, + anonymous_positional: bool, +} + +impl BindingShape { + const fn validated(params: Option<&'static [Param]>) -> Option { + const fn known(params: Option<&[Param]>) -> bool { + let Some(params) = params else { + return false; + }; + let mut i = 0; + while i < params.len() { + if let ParamKind::Flatten(inner) = params[i].kind + && !known(inner) + { + return false; + } + i += 1; + } + true + } + + if !known(params) { + return None; + } + assert!( + Self::from_params(params).is_some(), + "FromArgs binding parameters must describe one Clinic signature; use an explicit custom binding override for a staged parser", + ); + Self::from_params(params) + } + + const fn for_parser( + params: Option<&'static [Param]>, + force_unpack_keywords: bool, + ) -> Option { + let Some(mut shape) = Self::validated(params) else { + return None; + }; + if force_unpack_keywords { + shape.has_keywords = true; + shape.anonymous_positional = false; + } + Some(shape) + } + + const fn arity(&self) -> RangeInclusive { + self.required_positional..=if self.var_positional { + usize::MAX + } else { + self.positional + } + } + + const fn from_params(params: Option<&'static [Param]>) -> Option { + let Some(params) = params else { + return None; + }; + let mut shape = Self { + params, + fixed: 0, + positional: 0, + required_positional: 0, + required_positional_only: 0, + has_keywords: false, + var_positional: false, + var_keyword: false, + required_keyword_only: false, + anonymous_positional: false, + }; + if shape.count(params) { + Some(shape) + } else { + None + } + } + + const fn count(&mut self, params: &[Param]) -> bool { + let mut i = 0; + while i < params.len() { + let param = ¶ms[i]; + if self.var_keyword && !matches!(param.kind, ParamKind::Flatten(_)) { + return false; + } + match param.kind { + ParamKind::Flatten(Some(inner)) => { + if !self.count(inner) { + return false; + } + } + ParamKind::Flatten(None) => return false, + ParamKind::PositionalOnly | ParamKind::PositionalOrKeyword => { + // Other tuple compositions are valid Rust binders, but do + // not describe the ordered layout of one Clinic parser. + if self.var_positional + || self.fixed > self.positional + || (matches!(param.kind, ParamKind::PositionalOnly) && self.has_keywords) + { + return false; + } + self.fixed += 1; + self.positional += 1; + if param.default.is_none() { + self.required_positional = self.positional; + } + if matches!(param.kind, ParamKind::PositionalOnly) { + self.anonymous_positional |= param.name.is_empty(); + if param.default.is_none() { + self.required_positional_only = self.positional; + } + } else { + self.has_keywords = true; + } + } + ParamKind::KeywordOnly => { + self.fixed += 1; + self.has_keywords = true; + self.required_keyword_only |= param.default.is_none(); + } + ParamKind::VarPositional => { + if self.var_positional || self.fixed > self.positional { + return false; + } + self.var_positional = true; + } + ParamKind::VarKeyword => { + self.has_keywords = true; + self.var_keyword = true; + } + } + i += 1; + } + true + } + + // Sharing the count checks must not add a call to the existing owned path, + // and borrowed signatures can fold the shape constants into these checks. + #[inline(always)] + fn check_counts( + &self, + args: &FuncArgs, + callee: Callee, + vm: &VirtualMachine, + ) -> Option { + let nargs = args.args.len(); + let nkwargs = args.kwargs.len(); + let binding_arity = self.arity(); + if !self.has_keywords { + if nkwargs > 0 { + return Some(callee.no_keywords(vm)); + } + if nargs >= self.required_positional && nargs <= *binding_arity.end() { + return None; + } + return Some(callee.wrong_arity( + &binding_arity, + nargs < self.required_positional, + nargs, + vm, + )); + } + + // Bare positional Rust arguments use _PyArg_CheckPositional, including + // an outer argument followed by a separately bound options struct. + if self.anonymous_positional + && (nargs > *binding_arity.end() || nargs < self.required_positional_only) + { + return Some(callee.wrong_arity( + &binding_arity, + nargs < self.required_positional, + nargs, + vm, + )); + } + let (name, parens) = call_form(callee.name, "function"); + if !self.anonymous_positional + && !self.var_positional + && !self.var_keyword + && nargs + nkwargs > self.fixed + { + return Some(vm.new_type_error(format!( + "{name}{parens} takes at most {} {}argument{} ({} given)", + self.fixed, + if nargs == 0 { "keyword " } else { "" }, + if self.fixed == 1 { "" } else { "s" }, + nargs + nkwargs, + ))); + } + if !self.var_positional && nargs > self.positional { + return Some(vm.new_type_error(if self.positional == 0 { + format!("{name}{parens} takes no positional arguments") + } else { + format!( + "{name}{parens} takes {} {} positional argument{} ({nargs} given)", + if self.required_positional == self.positional { + "exactly" + } else { + "at most" + }, + self.positional, + if self.positional == 1 { "" } else { "s" }, + ) + })); + } + if nargs < self.required_positional_only { + return Some(vm.new_type_error(format!( + "{name}{parens} takes {} {} positional argument{} ({nargs} given)", + if self.var_positional || self.required_positional_only < self.positional { + "at least" + } else { + "exactly" + }, + self.required_positional_only, + if self.required_positional_only == 1 { + "" + } else { + "s" + }, + ))); + } + + None + } + + fn check( + &self, + args: &FuncArgs, + arity: &RangeInclusive, + callee: Callee, + vm: &VirtualMachine, + ) -> Option { + if let Some(error) = self.check_counts(args, callee, vm) { + return Some(error); + } + let nargs = args.args.len(); + let nkwargs = args.kwargs.len(); + // Walk when a required argument may be missing, or when keywords need + // matching. Optional-only calls with no keywords skip this. + if !args.kwargs.is_empty() + || nargs != 0 + || self.required_positional != 0 + || self.required_keyword_only + { + let mut matched = BindingMatch::new(); + if let Err(missing) = matched.walk(self.params, nargs, &args.kwargs) { + return Some(missing.into_exception(arity, nargs, 0, callee, vm)); + } + // A leftover keyword either names a parameter filled by position, + // lands in **kwargs, or is unexpected. + if matched.found < nkwargs { + if let Some((name, pos)) = + BindingMatch::new().first_duplicate(self.params, nargs, &args.kwargs) + { + return Some(callee.given_by_name_and_position(name, pos, vm)); + } + if !self.var_keyword { + return self.unexpected_keyword(args, callee, vm); + } + } + } + None + } + + /// Reports the first keyword no parameter accepts. Only reached when the + /// call fails, so the linear scan per keyword stays off the call path. + #[cold] + fn unexpected_keyword( + &self, + args: &FuncArgs, + callee: Callee, + vm: &VirtualMachine, + ) -> Option { + args.kwargs + .keys() + .find(|name| !binding_accepts_keyword(self.params, name)) + .map(|name| callee.unexpected_keyword(&name.to_string(), vm)) + } +} + +struct BindingMatch { + positional: usize, + position: usize, + found: usize, +} + +impl BindingMatch { + const fn new() -> Self { + Self { + positional: 0, + position: 0, + found: 0, + } + } + + fn walk( + &mut self, + params: &[Param], + nargs: usize, + kwargs: &KwArgs, + ) -> Result<(), ArgumentError> { + for param in params { + match param.kind { + ParamKind::Flatten(Some(inner)) => self.walk(inner, nargs, kwargs)?, + ParamKind::PositionalOnly => { + self.positional += 1; + self.position += 1; + } + ParamKind::PositionalOrKeyword | ParamKind::KeywordOnly => { + self.position += 1; + if matches!(param.kind, ParamKind::PositionalOrKeyword) { + self.positional += 1; + if self.positional <= nargs { + continue; + } + } + if kwargs.contains_key(param.name) { + self.found += 1; + } else if param.default.is_none() { + return Err(ArgumentError::MissingRequiredArgument { + name: param.name.to_owned(), + pos: self.position, + }); + } + } + ParamKind::Flatten(None) | ParamKind::VarPositional | ParamKind::VarKeyword => {} + } + } + Ok(()) + } + + fn first_duplicate<'a>( + &mut self, + params: &'a [Param], + nargs: usize, + kwargs: &KwArgs, + ) -> Option<(&'a str, usize)> { + for param in params { + match param.kind { + ParamKind::Flatten(Some(inner)) => { + if let Some(duplicate) = self.first_duplicate(inner, nargs, kwargs) { + return Some(duplicate); + } + } + ParamKind::PositionalOnly => { + self.positional += 1; + self.position += 1; + } + ParamKind::PositionalOrKeyword => { + self.positional += 1; + self.position += 1; + if self.positional <= nargs && kwargs.contains_key(param.name) { + return Some((param.name, self.position)); + } + } + ParamKind::KeywordOnly => self.position += 1, + ParamKind::Flatten(None) | ParamKind::VarPositional | ParamKind::VarKeyword => {} + } + } + None + } +} + +fn binding_accepts_keyword(params: &[Param], name: &Wtf8) -> bool { + params.iter().any(|param| match param.kind { + ParamKind::Flatten(Some(inner)) => binding_accepts_keyword(inner, name), + ParamKind::PositionalOrKeyword | ParamKind::KeywordOnly => Wtf8::new(param.name) == name, + ParamKind::VarKeyword => true, + _ => false, + }) +} + /// The branch of _PyArg_UnpackKeywords that names a parameter it didn't get. pub(crate) fn missing_argument_message(name: Option<&str>, keyword: &str, pos: usize) -> String { let (name, parens) = call_form(name, "function"); @@ -482,6 +1040,14 @@ pub enum ArgumentError { /// The function requires an argument for the named parameter, at the given /// 1-based position, but the call didn't pass one. MissingRequiredArgument { name: String, pos: usize }, + /// The argument is not the expected type. `_PyArg_BadArgument`. + /// `name` is `None` for a positional-only parameter. + BadArgument { + expected: &'static Py, + or_none: bool, + found: PyObjectRef, + name: Option<&'static str>, + }, /// An exception was raised while binding arguments to the function /// parameters. Exception(PyBaseExceptionRef), @@ -494,10 +1060,49 @@ impl From for ArgumentError { } impl ArgumentError { - fn into_exception( + /// Attach the parameter name for get_displayname (`argument 'name'`). + #[must_use] + pub fn with_argument_name(self, name: &'static str) -> Self { + match self { + Self::BadArgument { + expected, + or_none, + found, + .. + } => Self::BadArgument { + expected, + or_none, + found, + name: Some(name), + }, + other => other, + } + } + + /// Mark `{expected}` as `X or None`. + #[must_use] + pub(crate) fn with_or_none(self) -> Self { + match self { + Self::BadArgument { + expected, + found, + name, + .. + } => Self::BadArgument { + expected, + or_none: true, + found, + name, + }, + other => other, + } + } + + pub fn into_exception( self, arity: &RangeInclusive, num_given: usize, + pos: usize, callee: Callee, vm: &VirtualMachine, ) -> PyBaseExceptionRef { @@ -506,21 +1111,102 @@ impl ArgumentError { Self::TooManyArgs => callee.wrong_arity(arity, false, num_given, vm), Self::InvalidKeywordArgument(name) => callee.unexpected_keyword(&name, vm), Self::MissingRequiredArgument { name, pos } => callee.missing_argument(&name, pos, vm), + Self::BadArgument { + expected, + or_none, + found, + name, + } => { + if callee.name.is_none() || (name.is_none() && pos == 0) { + vm.new_downcast_type_error(expected, &found) + } else { + let meth_o = *arity.start() == 1 && *arity.end() == 1; + let displayname = get_displayname(name, pos, meth_o); + callee.bad_argument(&displayname, expected, or_none, &found, vm) + } + } Self::Exception(ex) => ex, } } } +/// Binding and display metadata shared by owned and borrowed argument structs. +/// Borrowed structs use the same strict Clinic signature as ordinary `FromArgs`. +pub trait ArgsMetadata { + const TEXT_SIGNATURE: Option<&'static str> = None; + const DISPLAY_PARAMS: Option<&'static [Param]>; + const CLINIC_PARAMS: Option<&'static [Param]> = Self::DISPLAY_PARAMS; + const UNPACK_KEYWORDS: bool = false; +} + +impl ArgsMetadata for T { + const TEXT_SIGNATURE: Option<&'static str> = T::TEXT_SIGNATURE; + const DISPLAY_PARAMS: Option<&'static [Param]> = T::PARAMS; + const CLINIC_PARAMS: Option<&'static [Param]> = T::BINDING_PARAMS; + const UNPACK_KEYWORDS: bool = T::FORCE_UNPACK_KEYWORDS; +} + +/// A family of argument structs borrowing the native call's original storage. +/// `#[from_args(borrowed)]` derives this for a struct with one lifetime. The static +/// member selects the family; only `Bound` is constructed during a call. +pub trait BorrowedArgs: ArgsMetadata + Sized + 'static { + type Bound<'a>; + + fn bind<'a>( + args: &'a FuncArgs, + vm: &VirtualMachine, + callee: Callee, + ) -> PyResult>; +} + +/// Missing-state conversion for borrowed fields. This never creates an owner. +pub trait FromBorrowedArgOptional<'a> { + type Inner: crate::convert::TryFromBorrowedObject<'a>; + fn from_inner(value: Self::Inner) -> Self; +} + +impl<'a, T: crate::convert::TryFromBorrowedObject<'a>> FromBorrowedArgOptional<'a> + for OptionalArg +{ + type Inner = T; + fn from_inner(value: T) -> Self { + Self::Present(value) + } +} + +impl<'a, T: crate::convert::TryFromBorrowedObject<'a>> FromBorrowedArgOptional<'a> for T { + type Inner = Self; + fn from_inner(value: Self) -> Self { + value + } +} + /// Implemented by any type that can be accepted as a parameter to a built-in /// function. /// pub trait FromArgs: Sized { + /// Checked explicit signature for this complete argument spec, without a receiver. + /// Sharing the type shares the override, like an Argument Clinic clone. + /// Incompatible requiredness fails when the checked metadata is evaluated: + /// ```compile_fail + /// use rustpython_vm::{FromArgs, function::FromArgs as FromArgsTrait}; + /// #[derive(FromArgs)] + /// #[from_args(text_signature = "(value=None, /)")] + /// struct Invalid { #[pyarg(positional)] value: u32 } + /// const _: Option<&str> = ::TEXT_SIGNATURE; + /// ``` + const TEXT_SIGNATURE: Option<&'static str> = None; + /// The range of positional arguments permitted by the function signature. /// - /// Returns an empty range if not applicable. + /// By default this is computed from the binding parameters. An explicit + /// custom parser without binding metadata has no positional upper bound. #[must_use] fn arity() -> RangeInclusive { - 0..=0 + match const { BindingShape::validated(Self::BINDING_PARAMS) } { + Some(shape) => shape.arity(), + None => 0..=usize::MAX, + } } /// Parameters this type contributes to a text signature. @@ -531,10 +1217,111 @@ pub trait FromArgs: Sized { /// is ignored. const PARAMS: Option<&'static [Param]> = None; + /// Parameters validated with Clinic rules before any argument conversion. + /// Both manual implementations and derives use `PARAMS` by default; its + /// unnamed scalar is represented here by one positional-only slot. + /// + /// Override this when the accepted arguments differ from the displayed + /// signature. `None` explicitly delegates validation to a custom parser, + /// retaining the conservative checks below. Such exceptions should explain + /// why CPython needs different validation order or diagnostics. + const BINDING_PARAMS: Option<&'static [Param]> = match Self::PARAMS { + Some(params) => Some(params), + None => Some(&[Param::positional_only("")]), + }; + + /// Force `_PyArg_UnpackKeywords` calling and validation conventions, even + /// when every parameter is positional-only. Otherwise they are inferred + /// from the binding parameters. This does not allow passing positional-only + /// parameters by keyword. + const FORCE_UNPACK_KEYWORDS: bool = false; + + /// True when every parameter is positional-only or `*args`. + const TAKES_NO_KEYWORDS: bool = match Self::PARAMS { + Some(params) => params_take_no_keywords(params), + None => false, + }; + + /// Validate a known binding shape before converting any argument, following + /// `_PyArg_UnpackKeywords` error ordering. Explicit custom parsers keep the + /// positional-count and no-keyword checks, but own named validation. + /// Invalid known parameter ordering is rejected at compile time. + /// + /// The missing-argument walk is skipped when every required positional + /// argument is present and the type has no required keyword-only parameter. + #[inline] + fn check_before_convert( + args: &FuncArgs, + arity: &RangeInclusive, + num_given: usize, + callee: Callee, + vm: &VirtualMachine, + ) -> Option { + let shape = + const { BindingShape::for_parser(Self::BINDING_PARAMS, Self::FORCE_UNPACK_KEYWORDS) }; + if let Some(shape) = shape { + if args.kwargs.is_empty() + && num_given >= shape.required_positional + && (shape.var_positional || num_given <= shape.positional) + && !shape.required_keyword_only + { + return None; + } + return shape.check(args, arity, callee, vm); + } + + // A function that takes no keywords refuses them before counting its + // arguments. + if Self::TAKES_NO_KEYWORDS && !args.kwargs.is_empty() { + return Some(callee.no_keywords(vm)); + } + if num_given > *arity.end() { + return Some( + ArgumentError::TooManyArgs.into_exception(arity, num_given, 0, callee, vm), + ); + } + // No keyword can fill a missing parameter of such a function, so too few + // arguments are also reported before any is converted. + if Self::TAKES_NO_KEYWORDS && num_given < *arity.start() { + return Some(ArgumentError::TooFewArgs.into_exception(arity, num_given, 0, callee, vm)); + } + None + } + /// Extracts this item from the next argument(s). fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result; } +/// Select CPython's `_PyArg_UnpackKeywords` calling and validation conventions +/// for typed arguments, including an entirely positional-only signature. +/// Reuses the ordinary binder and preserves `T`'s conversions and signature; +/// positional-only parameters still cannot be passed by keyword. `T` must +/// expose a known binding shape; opaque and legacy parsers retain their own +/// validation order. +#[repr(transparent)] +pub struct UnpackKeywords(pub T); + +impl FromArgs for UnpackKeywords { + const PARAMS: Option<&'static [Param]> = T::PARAMS; + const BINDING_PARAMS: Option<&'static [Param]> = { + assert!( + BindingShape::from_params(T::BINDING_PARAMS).is_some(), + "UnpackKeywords requires a known binding shape" + ); + T::BINDING_PARAMS + }; + const FORCE_UNPACK_KEYWORDS: bool = true; + const TAKES_NO_KEYWORDS: bool = T::TAKES_NO_KEYWORDS; + + fn arity() -> RangeInclusive { + T::arity() + } + + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + T::from_args(vm, args).map(Self) + } +} + pub trait FromArgOptional { type Inner: TryFromObject; fn from_inner(x: Self::Inner) -> Self; @@ -613,9 +1400,11 @@ arg_name! { NameKwds = "kwds", NameKws = "kws", NameObjs = "objs", + NameObjects = "objects", NameIterables = "iterables", NameKeywords = "keywords", NameFields = "fields", + NameValues = "values", } #[derive(Clone, Debug)] @@ -735,6 +1524,10 @@ where { const PARAMS: Option<&'static [Param]> = Some(&[Param::var_keyword(Name::NAME)]); + fn arity() -> RangeInclusive { + 0..=0 + } + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { let mut kwargs = KwArgsMap::default(); for (name, value) in args.remaining_keywords() { @@ -849,7 +1642,7 @@ where fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { let value = args.take_positional().ok_or(ArgumentError::TooFewArgs)?; - Ok(value.try_into_value(vm)?) + T::try_from_argument(vm, value) } } @@ -912,7 +1705,7 @@ where fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { let r = if let Some(value) = args.take_positional() { - Self::Present(value.try_into_value(vm)?) + Self::Present(T::try_from_argument(vm, value)?) } else { Self::Missing }; @@ -925,6 +1718,10 @@ where impl FromArgs for () { const PARAMS: Option<&'static [Param]> = Some(&[]); + fn arity() -> RangeInclusive { + 0..=0 + } + fn from_args(_vm: &VirtualMachine, _args: &mut FuncArgs) -> Result { Ok(()) } @@ -936,6 +1733,25 @@ impl FromArgs for () { // Technically, a tuple can contain tuples, which can contain tuples, and so on, // so this actually represents a tree of values to be bound from arguments, but // in practice this is only used for the top-level parameters. +// +// A pyfunction with one FromArgs struct is bound as `(T,)`. Use T's own +// checks so a `legacy` struct's no-op is not wrapped in the combined +// missing-argument walk. Longer tuples use the default checks. +macro_rules! tuple_check_before_convert { + ($T:ident) => { + fn check_before_convert( + args: &FuncArgs, + arity: &RangeInclusive, + num_given: usize, + callee: Callee, + vm: &VirtualMachine, + ) -> Option { + $T::check_before_convert(args, arity, num_given, callee, vm) + } + }; + ($($T:ident),+) => {}; +} + macro_rules! tuple_from_py_func_args { ($($T:ident),+) => { impl<$($T),+> FromArgs for ($($T,)+) @@ -950,17 +1766,31 @@ macro_rules! tuple_from_py_func_args { } }; + const BINDING_PARAMS: Option<&'static [Param]> = { + if true $(&& $T::BINDING_PARAMS.is_some())* { + Some(&[$(Param::flatten($T::BINDING_PARAMS)),*]) + } else { + None + } + }; + + const FORCE_UNPACK_KEYWORDS: bool = false $(|| $T::FORCE_UNPACK_KEYWORDS)*; + fn arity() -> RangeInclusive { let mut min = 0; let mut max = 0; $( let (start, end) = $T::arity().into_inner(); - min += start; - max += end; + // Both custom required bounds and unbounded upper bounds + // can reach `usize::MAX`; neither composition may overflow. + min = usize::saturating_add(min, start); + max = usize::saturating_add(max, end); )+ min..=max } + tuple_check_before_convert!($($T),+); + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { Ok(($($T::from_args(vm, args)?,)+)) } @@ -979,3 +1809,631 @@ tuple_from_py_func_args!(A, B, C, D, E); tuple_from_py_func_args!(A, B, C, D, E, F); tuple_from_py_func_args!(A, B, C, D, E, F, G); tuple_from_py_func_args!(A, B, C, D, E, F, G, H); + +#[cfg(test)] +mod arity_composition_tests { + use super::*; + + struct Bounds; + + impl FromArgs for Bounds { + // This fixture supplies bounds rather than a fixed parameter list. + const BINDING_PARAMS: Option<&'static [Param]> = None; + + fn arity() -> RangeInclusive { + MIN..=MAX + } + + fn from_args(_vm: &VirtualMachine, _args: &mut FuncArgs) -> Result { + unreachable!("metadata-only fixture; no interpreter is constructed") + } + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct Mixed { + #[pyarg(flatten)] + prefix: Bounds<2, 3>, + #[pyarg(positional)] + required: usize, + #[pyarg(positional, optional)] + optional: OptionalArg, + #[pyarg(positional, default = 0)] + defaulted: usize, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct Nested(#[pyarg(flatten)] (Bounds<1, 2>, Bounds<0, 1>)); + + #[allow(dead_code)] + #[derive(FromArgs)] + struct OptionalOnly { + #[pyarg(flatten)] + prefix: Bounds<0, 2>, + #[pyarg(positional, optional)] + optional: OptionalArg, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct Phantoms { + _phantom: core::marker::PhantomData<()>, + #[pyarg(flatten)] + _phantom_flattened: core::marker::PhantomData<()>, + #[pyarg(positional)] + required: usize, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct Saturated { + #[pyarg(flatten)] + prefix: Bounds<{ usize::MAX }, { usize::MAX }>, + #[pyarg(positional)] + required: usize, + } + + #[test] + fn derived_bounds_include_required_flattened_arguments() { + assert_eq!(Mixed::arity(), 3..=6); + assert_eq!(Nested::arity(), 1..=3); + assert_eq!(Phantoms::arity(), 1..=1); + } + + #[test] + fn optional_only_flattening_preserves_zero_minimum() { + assert_eq!(OptionalOnly::arity(), 0..=3); + assert_eq!(<(Bounds<0, 2>, Bounds<0, 3>)>::arity(), 0..=5); + assert_eq!( + <(Bounds<2, 3>, (Bounds<1, 2>, Bounds<0, 1>))>::arity(), + 3..=6 + ); + } + + #[test] + fn both_tuple_and_derived_bounds_saturate() { + assert_eq!( + <(Bounds<1, 1>, Bounds<0, { usize::MAX }>)>::arity(), + 1..=usize::MAX + ); + assert_eq!(Saturated::arity(), usize::MAX..=usize::MAX); + assert_eq!( + <(Bounds<{ usize::MAX }, { usize::MAX }>, Bounds<1, 1>)>::arity(), + usize::MAX..=usize::MAX, + ); + } +} + +#[cfg(test)] +mod tests { + use super::{ArgumentError, FromArgs, KwArgs}; + use super::{BindingShape, Callee, FuncArgs, PosArgs}; + use crate::{PyObjectRef, VirtualMachine}; + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct BorrowedNamed<'a> { + #[pyarg(any)] + first: &'a crate::PyObject, + #[pyarg(any)] + second: &'a crate::PyObject, + #[pyarg(named, optional, py_default = "None")] + optional: super::OptionalArg<&'a crate::PyObject>, + } + + #[test] + fn borrowed_binding_matches_clinic_errors() { + use super::BorrowedArgs; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for (nargs, names) in [ + (0, vec![]), + (1, vec!["first"]), + (1, vec!["unknown"]), + (2, vec!["first"]), + (2, vec!["unknown"]), + (3, vec![]), + (2, vec!["optional", "unknown"]), + (0, vec!["second", "unknown"]), + (0, vec!["second", "first", "unknown"]), + ] { + let args = FuncArgs::new( + vec![vm.ctx.none(); nargs], + names + .iter() + .map(|&name| (name, vm.ctx.none())) + .collect::(), + ); + let error = match BorrowedNamed::bind(&args, vm, Callee::named("example")) { + Err(error) => error, + Ok(_) => panic!("binding unexpectedly succeeded"), + }; + let message: String = error.args().as_slice()[0].try_to_value(vm).unwrap(); + assert_eq!( + message, + binding_error::(nargs, &names, false, vm) + ); + } + }); + } + + #[test] + fn borrowed_argument_conversion_keeps_payload_validation() { + use crate::{AsObject, Py, builtins::PyUtf8Str, convert::TryFromBorrowedObject}; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let value = vm + .ctx + .new_str(crate::common::wtf8::CodePoint::from(0xd800u16)); + let error = match <&Py>::try_from_borrowed_argument(vm, value.as_object()) { + Err(ArgumentError::Exception(error)) => error, + _ => panic!("a surrogate must fail the UTF-8 payload check"), + }; + assert!(error.class().is(vm.ctx.exceptions.unicode_encode_error)); + }); + } + + #[test] + fn borrowed_binding_preserves_storage_and_reference_counts() { + use super::BorrowedArgs; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let args = FuncArgs::new( + vec![vm.new_pyobj("first")], + [ + ("optional", vm.new_pyobj("optional")), + ("second", vm.new_pyobj("second")), + ] + .into_iter() + .collect::(), + ); + let positional = args.args.as_ptr(); + let counts = [ + args.args[0].strong_count(), + args.kwargs.get("second").unwrap().strong_count(), + args.kwargs.get("optional").unwrap().strong_count(), + ]; + for _ in 0..100 { + let bound = BorrowedNamed::bind(&args, vm, Callee::named("example")) + .unwrap_or_else(|_| panic!("valid binding")); + assert!(core::ptr::eq(bound.first, &*args.args[0])); + assert!(core::ptr::eq( + bound.second, + &**args.kwargs.get("second").unwrap() + )); + assert!(core::ptr::eq( + bound.optional.into_option().unwrap(), + &**args.kwargs.get("optional").unwrap() + )); + assert_eq!(positional, args.args.as_ptr()); + assert_eq!( + [ + args.args[0].strong_count(), + args.kwargs.get("second").unwrap().strong_count(), + args.kwargs.get("optional").unwrap().strong_count() + ], + counts + ); + } + assert_eq!( + args.kwargs + .keys() + .map(|name| name.to_string()) + .collect::>(), + ["optional", "second"] + ); + }); + } + + #[test] + fn duplicate_argument_messages_distinguish_unnamed_callees() { + assert_eq!( + super::given_by_name_and_position_message(None, "dialect", 1), + "argument for function given by name ('dialect') and position (1)", + ); + assert_eq!( + super::given_by_name_and_position_message(Some("example"), "dialect", 1), + "argument for example() given by name ('dialect') and position (1)", + ); + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct NamedRequired { + #[pyarg(any)] + first: i32, + #[pyarg(named)] + second: i32, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct ClinicNamed { + #[pyarg(any)] + first: i32, + #[pyarg(any)] + second: i32, + #[pyarg(named, default)] + optional: i32, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct FlattenedClinic { + #[pyarg(flatten)] + args: (ClinicNamed,), + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct VariadicNamed { + #[pyarg(flatten)] + args: PosArgs, + #[pyarg(named)] + required: i32, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct ExtraKeywords { + #[pyarg(any)] + first: i32, + #[pyarg(flatten)] + rest: KwArgs, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + #[from_args(legacy, fname = "example")] + struct LegacyNamed { + #[pyarg(any)] + first: i32, + #[pyarg(any)] + second: i32, + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct FlattenedLegacy { + #[pyarg(flatten)] + args: (LegacyNamed,), + } + + struct DisplayOnly(FuncArgs); + + impl FromArgs for DisplayOnly { + // An explicit custom parser, unlike the default manual implementation. + const BINDING_PARAMS: Option<&'static [super::Param]> = None; + + const PARAMS: Option<&'static [super::Param]> = + Some(&[super::Param::positional_or_keyword("display")]); + + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + FuncArgs::from_args(vm, args).map(Self) + } + } + + fn binding_error( + nargs: usize, + names: &[&str], + receiver: bool, + vm: &VirtualMachine, + ) -> String { + let args = FuncArgs::new( + vec![vm.ctx.none(); nargs], + names + .iter() + .map(|&name| (name, vm.ctx.none())) + .collect::(), + ); + let callee = Callee::named("example"); + let result = if receiver { + use crate::function::{IntoPyNativeFn, ReceiverFunction}; + ReceiverFunction(|_receiver: PyObjectRef, _args: T| ()) + .call(vm, Some(&vm.ctx.none()), args, callee) + .map(|_| ()) + } else { + args.bind_for::(vm, callee).map(|_| ()) + }; + match result { + Err(error) => error.args().as_slice()[0].try_to_value(vm).unwrap(), + Ok(_) => panic!("binding unexpectedly succeeded"), + } + } + + #[allow(dead_code)] + #[derive(FromArgs)] + struct FlattenedUnpackKeywords { + #[pyarg(flatten)] + args: super::UnpackKeywords, + } + + #[test] + fn unpack_keywords_uses_clinic_order_for_positional_only_parameters() { + type Wrapped = super::UnpackKeywords; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for (nargs, names, expected) in [ + ( + 0, + &[][..], + "example() takes exactly 1 positional argument (0 given)", + ), + (2, &[][..], "example() takes at most 1 argument (2 given)"), + ( + 0, + &["value"][..], + "example() takes exactly 1 positional argument (0 given)", + ), + ( + 0, + &["value", "other"][..], + "example() takes at most 1 keyword argument (2 given)", + ), + ( + 1, + &["value"][..], + "example() takes at most 1 argument (2 given)", + ), + ] { + assert_eq!(binding_error::(nargs, names, false, vm), expected); + assert_eq!( + binding_error::<(Wrapped,)>(nargs, names, true, vm), + expected, + ); + assert_eq!( + binding_error::(nargs, names, false, vm), + expected, + ); + } + let args = FuncArgs::new(vec![vm.ctx.none()], KwArgs::default()); + assert!(args.bind_for::(vm, "example").is_ok()); + assert_eq!( + binding_error::(0, &["value"], false, vm), + "example() takes no keyword arguments", + ); + }); + } + + #[test] + fn clinic_checks_shape_before_converting_and_missing_before_duplicates() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + assert_eq!( + binding_error::(1, &["first"], false, vm), + "example() missing required argument 'second' (pos 2)", + ); + assert_eq!( + binding_error::(1, &[], false, vm), + "example() missing required argument 'second' (pos 2)", + ); + assert_eq!( + binding_error::(2, &["unknown"], false, vm), + "example() got an unexpected keyword argument 'unknown'", + ); + assert_eq!( + binding_error::(3, &[], false, vm), + "example() takes exactly 2 positional arguments (3 given)", + ); + assert_eq!( + binding_error::(2, &["optional", "unknown"], false, vm), + "example() takes at most 3 arguments (4 given)", + ); + assert_eq!( + binding_error::( + 0, + &["first", "second", "optional", "unknown"], + false, + vm + ), + "example() takes at most 3 keyword arguments (4 given)", + ); + }); + } + + #[test] + fn clinic_tuple_and_flatten_validation_exclude_the_native_receiver() { + const { assert!(<(PyObjectRef, ClinicNamed)>::PARAMS.is_none()) }; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + assert_eq!( + binding_error::<(ClinicNamed,)>(1, &["first"], true, vm), + "example() missing required argument 'second' (pos 2)", + ); + assert_eq!( + binding_error::(2, &["first"], true, vm), + "argument for example() given by name ('first') and position (1)", + ); + }); + } + + #[test] + fn clinic_variadic_arguments_keep_named_validation() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + assert_eq!( + binding_error::(5, &[], false, vm), + "example() missing required argument 'required' (pos 1)", + ); + assert_eq!( + binding_error::(1, &["first", "extra"], false, vm), + "argument for example() given by name ('first') and position (1)", + ); + }); + } + + #[test] + fn clinic_validation_preserves_successful_keyword_bindings() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let args = FuncArgs::new( + vec![], + [("first", 1), ("second", 2), ("optional", 3)] + .into_iter() + .map(|(name, value)| (name, vm.ctx.new_int(value).into())) + .collect::(), + ); + let bound = args + .bind_for::(vm, Callee::named("example")) + .unwrap_or_else(|_| panic!("known keywords should bind")); + assert_eq!( + ( + bound.args.0.first, + bound.args.0.second, + bound.args.0.optional + ), + (1, 2, 3), + ); + + let args = FuncArgs::new( + vec![vm.ctx.new_int(42).into()], + core::iter::once(("extra", vm.ctx.none())).collect::(), + ); + let bound = args + .bind_for::(vm, "example") + .unwrap_or_else(|_| panic!("extra keywords should be retained")); + assert_eq!(bound.first, 42); + assert!(bound.rest.contains_key("extra")); + }); + } + + #[test] + fn legacy_binding_remains_opaque_and_converts_first() { + const { assert!(LegacyNamed::BINDING_PARAMS.is_none()) }; + const { assert!(<(PyObjectRef, LegacyNamed)>::BINDING_PARAMS.is_none()) }; + const UNKNOWN: &[super::Param] = &[super::Param::flatten(None)]; + assert!(BindingShape::from_params(Some(UNKNOWN)).is_none()); + assert!(BindingShape::from_params(<(PosArgs, i32)>::BINDING_PARAMS).is_none()); + assert!(BindingShape::from_params(<(KwArgs, ClinicNamed)>::BINDING_PARAMS).is_none()); + assert!(BindingShape::from_params(<(ClinicNamed, i32)>::BINDING_PARAMS).is_none()); + assert!(BindingShape::from_params(<(ClinicNamed, PosArgs)>::BINDING_PARAMS).is_none()); + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let message = binding_error::<(LegacyNamed,)>(1, &[], false, vm); + assert!(message.contains("NoneType"), "{message}"); + assert!(!message.contains("missing required"), "{message}"); + }); + } + + #[test] + fn legacy_conversion_order_survives_receivers_and_flattened_composition() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for message in [ + binding_error::<(LegacyNamed,)>(1, &[], true, vm), + binding_error::(1, &[], true, vm), + binding_error::<(LegacyNamed, ())>(1, &["first"], false, vm), + ] { + assert!(message.contains("NoneType"), "{message}"); + assert!(!message.contains("missing required"), "{message}"); + assert!(!message.contains("given by name"), "{message}"); + } + }); + } + + #[test] + fn method_legacy_parser_keeps_the_outer_arity_check() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + assert_eq!( + binding_error::(3, &[], true, vm), + "example() takes at most 2 arguments (3 given)", + ); + }); + } + + #[test] + fn common_receiver_preserves_legacy_function_and_method_errors() { + use crate::{ + AsObject, Py, + builtins::PyModule, + function::{IntoPyNativeFn, ReceiverFunction}, + }; + + fn message(vm: &VirtualMachine) -> String { + let module = vm.new_module("receiver", vm.ctx.new_dict(), None); + let error = ReceiverFunction(|_receiver: &Py, _args: LegacyNamed| ()) + .call( + vm, + Some(module.as_object()), + FuncArgs::from(vec![vm.ctx.none(); 3]), + Callee::named("example"), + ) + .unwrap_err(); + error.args().as_slice()[0].try_to_value(vm).unwrap() + } + + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + assert_eq!(message(vm), "example() takes at most 2 arguments (3 given)",); + }); + } + + #[test] + fn explicitly_custom_signatures_do_not_opt_in_to_clinic_validation() { + const { assert!(DisplayOnly::BINDING_PARAMS.is_none()) }; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let bound = FuncArgs::default() + .bind_for::(vm, "example") + .unwrap_or_else(|_| panic!("a display signature must not require arguments")); + assert!(bound.0.args.is_empty()); + }); + } + + struct ManualNamed; + + impl FromArgs for ManualNamed { + const PARAMS: Option<&'static [super::Param]> = ClinicNamed::PARAMS; + + fn from_args(_: &VirtualMachine, _: &mut FuncArgs) -> Result { + panic!("invalid calls must be rejected before the manual parser runs") + } + } + + struct ManualPositional; + + impl FromArgs for ManualPositional { + const PARAMS: Option<&'static [super::Param]> = + Some(&[super::Param::positional_only("value")]); + + fn from_args(_: &VirtualMachine, _: &mut FuncArgs) -> Result { + panic!("invalid calls must be rejected before the manual parser runs") + } + } + + #[test] + fn manual_parsers_use_clinic_validation_and_shape_bounds_by_default() { + assert_eq!(ManualNamed::arity(), 2..=2); + assert_eq!(ManualPositional::arity(), 1..=1); + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + assert_eq!( + binding_error::(1, &["first"], false, vm), + "example() missing required argument 'second' (pos 2)", + ); + assert_eq!( + binding_error::(2, &["unknown"], false, vm), + "example() got an unexpected keyword argument 'unknown'", + ); + assert_eq!( + binding_error::(0, &[], false, vm), + "example expected 1 argument, got 0", + ); + assert_eq!( + binding_error::<(ManualPositional,)>(2, &[], true, vm), + "example expected 1 argument, got 2", + ); + }); + } + + #[test] + fn a_receiver_does_not_restore_clinic_validation_for_an_explicit_custom_parser() { + use crate::function::{IntoPyNativeFn, ReceiverFunction}; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + ReceiverFunction(|_receiver: PyObjectRef, bound: DisplayOnly| { + assert!(bound.0.args.is_empty()); + }) + .call( + vm, + Some(&vm.ctx.none()), + FuncArgs::default(), + Callee::named("example"), + ) + .unwrap_or_else(|_| panic!("the custom parser does not require display parameters")); + }); + } + + #[test] + #[should_panic(expected = "must describe one Clinic signature")] + fn malformed_known_compositions_cannot_silently_disable_clinic_validation() { + BindingShape::validated(<(PosArgs, i32)>::BINDING_PARAMS); + } +} diff --git a/crates/vm/src/function/buffer.rs b/crates/vm/src/function/buffer.rs index 51f9dc28ac5..d3fef056c09 100644 --- a/crates/vm/src/function/buffer.rs +++ b/crates/vm/src/function/buffer.rs @@ -1,7 +1,7 @@ use crate::{ AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, - builtins::{PyStr, PyStrRef}, + builtins::{PyBytes, PyBytesRef, PyStr, PyStrRef}, common::borrow::{BorrowedValue, BorrowedValueMut}, protocol::{BufferFlags, PyBuffer}, }; @@ -55,13 +55,12 @@ impl ArgBytesLike { /// `borrow_buf` may answer with a lock that every other thread writing to /// the same object waits on, and a thread waiting on a lock never reaches /// a safepoint, so keeping one across a wait for a peer, a pipe or a - /// signal stops the world from being stopped at all. Bytes reached that - /// way are copied out first. Bytes that lock nothing -- an immutable - /// object's -- are borrowed where they lie, which is all CPython holds in - /// either case. + /// signal stops the world from being stopped at all. Only storage owned + /// by `bytes` can be borrowed across that wait. Other exporters are copied: + /// an unlocked or readonly buffer may still alias writable raw memory. pub fn borrow_buf_unlocked(&self, vm: &VirtualMachine) -> PyResult> { let borrowed = self.borrow_buf(); - if !borrowed.is_locked() { + if !borrowed.is_locked() && self.source_object().downcast_ref::().is_some() { return Ok(UnlockedBuf::Borrowed(borrowed)); } let mut copy = Vec::new(); @@ -236,6 +235,56 @@ impl<'a> TryFromBorrowedObject<'a> for ArgMemoryBuffer { } } +/// A bytes object or text string, including subclasses, without buffer conversion. +#[derive(Debug)] +pub enum ArgBytesOrStr { + Bytes(PyBytesRef), + Str(PyStrRef), +} + +impl ArgBytesOrStr { + #[must_use] + pub fn as_object(&self) -> &PyObject { + match self { + Self::Bytes(b) => b.as_object(), + Self::Str(s) => s.as_object(), + } + } + + /// Borrow the payload directly, using WTF-8 for strings. + pub fn with_ref(&self, f: F) -> R + where + F: FnOnce(&[u8]) -> R, + { + match self { + Self::Bytes(b) => f(b.as_bytes()), + Self::Str(s) => f(s.as_bytes()), + } + } + + /// Borrow an object's payload without allocating or invoking Python conversion. + /// Other objects return `None`, rather than raising a conversion error. + pub fn with_object_ref(obj: &PyObject, f: F) -> Option + where + F: FnOnce(&[u8]) -> R, + { + if let Some(b) = obj.downcast_ref::() { + Some(f(b.as_bytes())) + } else { + obj.downcast_ref::().map(|s| f(s.as_bytes())) + } + } +} + +impl TryFromObject for ArgBytesOrStr { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + obj.downcast() + .map(Self::Bytes) + .or_else(|obj| obj.downcast().map(Self::Str)) + .map_err(|obj| vm.new_type_error(format!("unexpected type {}", obj.class()))) + } +} + /// A text string or bytes-like object. Like the `s*` format code for `PyArg_Parse` in CPython. pub enum ArgStrOrBytesLike { Buf(ArgBytesLike), @@ -316,3 +365,64 @@ impl ArgAsciiBuffer { } } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Interpreter, common::wtf8::Wtf8Buf}; + + #[test] + fn bytes_or_str_borrows_original_payloads() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let expected = [0xed, 0xa0, 0x80]; + let objects: [PyObjectRef; 2] = [ + vm.ctx.new_bytes(expected.to_vec()).into(), + vm.ctx.new_str(Wtf8Buf::from_wide(&[0xd800])).into(), + ]; + for obj in objects { + let original = if let Some(b) = obj.downcast_ref::() { + b.as_bytes() + } else { + obj.downcast_ref::().unwrap().as_bytes() + }; + let ptr = original.as_ptr(); + let arg = ArgBytesOrStr::try_from_object(vm, obj.clone()).unwrap(); + assert!(arg.as_object().is(&obj)); + let count = obj.strong_count(); + let mut calls = 0; + assert_eq!( + ArgBytesOrStr::with_object_ref(&obj, |bytes| { + calls += 1; + assert_eq!(obj.strong_count(), count); + assert_eq!(bytes.as_ptr(), ptr); + assert_eq!(bytes, expected); + }), + Some(()) + ); + assert_eq!(calls, 1); + drop(obj); + arg.with_ref(|bytes| { + assert_eq!(bytes.as_ptr(), ptr); + assert_eq!(bytes, expected); + }); + } + }); + } + + #[test] + fn bytes_or_str_rejects_other_objects_without_borrowing() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let objects: [PyObjectRef; 2] = [ + vm.ctx.new_bytearray(vec![b'*']).into(), + vm.ctx.new_int(42).into(), + ]; + for obj in objects { + assert_eq!( + ArgBytesOrStr::with_object_ref(&obj, |_| panic!("unexpected borrow")), + None::<()> + ); + assert!(ArgBytesOrStr::try_from_object(vm, obj).is_err()); + } + }); + } +} diff --git a/crates/vm/src/function/builtin.rs b/crates/vm/src/function/builtin.rs index b4bd610776d..40105145f69 100644 --- a/crates/vm/src/function/builtin.rs +++ b/crates/vm/src/function/builtin.rs @@ -1,6 +1,7 @@ -use super::{Callee, FromArgs, FuncArgs}; +use super::{BorrowedArgs, Callee, FromArgs, FuncArgs, SigArg}; use crate::{ - Py, PyPayload, PyRef, PyResult, VirtualMachine, convert::ToPyResult, + Py, PyObject, PyPayload, PyResult, VirtualMachine, + convert::{ToPyResult, TryFromObject}, object::PyThreadingConstraint, }; use core::marker::PhantomData; @@ -8,12 +9,16 @@ use core::marker::PhantomData; /// A built-in Python function. // PyCFunction in CPython pub trait PyNativeFn: - Fn(&VirtualMachine, FuncArgs, Callee) -> PyResult + PyThreadingConstraint + 'static + Fn(&VirtualMachine, Option<&PyObject>, FuncArgs, Callee) -> PyResult + + PyThreadingConstraint + + 'static { } impl PyNativeFn for F where - F: Fn(&VirtualMachine, FuncArgs, Callee) -> PyResult + PyThreadingConstraint + 'static + F: Fn(&VirtualMachine, Option<&PyObject>, FuncArgs, Callee) -> PyResult + + PyThreadingConstraint + + 'static { } @@ -37,7 +42,17 @@ impl PyNativeFn for F where /// just pass an unconstrained generic type, e.g. /// `fn foo(f: F) where F: IntoPyNativeFn` pub trait IntoPyNativeFn: Sized + PyThreadingConstraint + 'static { - fn call(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult; + /// Binding metadata of each argument, from which the calling convention + /// is inferred. A `&self` receiver is the `$self` marker. + const ARGS: &'static [SigArg] = &[SigArg::from_arg::("args")]; + + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult; /// `IntoPyNativeFn::into_func()` generates a PyNativeFn that performs the /// appropriate type and arity checking, any requested conversions, and then if @@ -48,7 +63,7 @@ pub trait IntoPyNativeFn: Sized + PyThreadingConstraint + 'static { } const fn into_func, Kind>(f: F) -> impl PyNativeFn { - move |vm: &VirtualMachine, args, callee| f.call(vm, args, callee) + move |vm: &VirtualMachine, receiver, args, callee| f.call(vm, receiver, args, callee) } const fn zst_ref_out_of_thin_air(x: T) -> &'static T { @@ -89,16 +104,31 @@ impl IntoPyNativeFn<(T, R, VM)> for F where F: PyNativeFnInternal, { + const ARGS: &'static [SigArg] = F::ARGS; + #[inline(always)] - fn call(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult { - self.call_(vm, args, callee) + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + self.call_(vm, receiver, args, callee) } } mod sealed { use super::*; pub trait PyNativeFnInternal: Sized + PyThreadingConstraint + 'static { - fn call_(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult; + const ARGS: &'static [SigArg]; + fn call_( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult; } } use sealed::PyNativeFnInternal; @@ -112,6 +142,53 @@ pub struct BorrowedParam(PhantomData); #[doc(hidden)] pub struct RefParam(PhantomData); +#[doc(hidden)] +pub struct BorrowedArgsParam(PhantomData); + +impl PyNativeFnInternal, R, VirtualMachine> for F +where + T: BorrowedArgs, + F: Fn(T, &VirtualMachine) -> R + + for<'a> Fn(T::Bound<'a>, &VirtualMachine) -> R + + PyThreadingConstraint + + 'static, + R: ToPyResult, +{ + const ARGS: &'static [SigArg] = &[SigArg::from_arg::("")]; + + fn call_( + &self, + vm: &VirtualMachine, + _receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + // The original owners outlive conversion, the body, and return-value + // conversion, including every error path. No keepalive copy is needed. + let result = T::bind(&args, vm, callee).and_then(|bound| (self)(bound, vm).to_pyresult(vm)); + args.drop_reverse(); + result + } +} + +/// Common typed adapter for an out-of-band native receiver. +/// The receiver is supplied by the native call ABI and is never a Python +/// argument. Argument metadata and validation describe only those arguments. +#[doc(hidden)] +pub struct ReceiverFunction(pub F); + +#[doc(hidden)] +pub struct ReceiverFunctionKind(PhantomData<(T, R, VM)>); + +#[inline] +fn native_receiver<'a>( + receiver: Option<&'a PyObject>, + callee: Callee, + vm: &VirtualMachine, +) -> PyResult<&'a PyObject> { + receiver.ok_or_else(|| callee.missing_receiver(vm)) +} + // This is the "magic" that allows rust functions of varying signatures to // generate native python functions. // @@ -124,81 +201,192 @@ macro_rules! into_py_native_fn_tuple { $($T: FromArgs,)* R: ToPyResult, { - fn call_(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult { + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; + + fn call_( + &self, + vm: &VirtualMachine, + _receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; (self)($($n,)* vm).to_pyresult(vm) } } - impl PyNativeFnInternal<(BorrowedParam, $(OwnedParam<$T>,)*), R, VirtualMachine> for F + impl PyNativeFnInternal<($(OwnedParam<$T>,)*), R, ()> for F + where + F: Fn($($T,)*) -> R + PyThreadingConstraint + 'static, + $($T: FromArgs,)* + R: ToPyResult, + { + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; + + fn call_( + &self, + vm: &VirtualMachine, + _receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + + (self)($($n,)*).to_pyresult(vm) + } + } + + impl IntoPyNativeFn, $(OwnedParam<$T>,)*), R, VirtualMachine>> for ReceiverFunction + where + F: Fn(S, $($T,)* &VirtualMachine) -> R + PyThreadingConstraint + 'static, + S: TryFromObject, + $($T: FromArgs,)* + R: ToPyResult, + { + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; + + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + let receiver = native_receiver(receiver, callee, vm)?; + // Even when binding checked the Python class, the Rust payload + // still needs validation for safe manual registrations. + let zelf = S::try_from_method_receiver(vm, receiver)?; + let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + (self.0)(zelf, $($n,)* vm).to_pyresult(vm) + } + } + + impl IntoPyNativeFn, $(OwnedParam<$T>,)*), R, VirtualMachine>> for ReceiverFunction where F: Fn(&Py, $($T,)* &VirtualMachine) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { - fn call_(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult { - let (zelf, $($n,)*) = args.bind_for::<(PyRef, $($T,)*)>(vm, callee)?; + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; - (self)(&zelf, $($n,)* vm).to_pyresult(vm) + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + let receiver = native_receiver(receiver, callee, vm)?; + // Even when binding checked the Python class, the Rust payload + // still needs validation for safe manual registrations. + let zelf = receiver.try_downcast_ref::(vm)?; + let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + (self.0)(zelf, $($n,)* vm).to_pyresult(vm) } } - impl PyNativeFnInternal<(RefParam, $(OwnedParam<$T>,)*), R, VirtualMachine> for F + impl IntoPyNativeFn, $(OwnedParam<$T>,)*), R, VirtualMachine>> for ReceiverFunction where F: Fn(&S, $($T,)* &VirtualMachine) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { - fn call_(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult { - let (zelf, $($n,)*) = args.bind_for::<(PyRef, $($T,)*)>(vm, callee)?; + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; - (self)(&zelf, $($n,)* vm).to_pyresult(vm) + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + let receiver = native_receiver(receiver, callee, vm)?; + // Even when binding checked the Python class, the Rust payload + // still needs validation for safe manual registrations. + let zelf = receiver.try_downcast_ref::(vm)?; + let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + (self.0)(zelf, $($n,)* vm).to_pyresult(vm) } } - impl PyNativeFnInternal<($(OwnedParam<$T>,)*), R, ()> for F + impl IntoPyNativeFn, $(OwnedParam<$T>,)*), R, ()>> for ReceiverFunction where - F: Fn($($T,)*) -> R + PyThreadingConstraint + 'static, + F: Fn(S, $($T,)* ) -> R + PyThreadingConstraint + 'static, + S: TryFromObject, $($T: FromArgs,)* R: ToPyResult, { - fn call_(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult { - let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; - (self)($($n,)*).to_pyresult(vm) + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + let receiver = native_receiver(receiver, callee, vm)?; + // Even when binding checked the Python class, the Rust payload + // still needs validation for safe manual registrations. + let zelf = S::try_from_method_receiver(vm, receiver)?; + let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + (self.0)(zelf, $($n,)* ).to_pyresult(vm) } } - impl PyNativeFnInternal<(BorrowedParam, $(OwnedParam<$T>,)*), R, ()> for F + impl IntoPyNativeFn, $(OwnedParam<$T>,)*), R, ()>> for ReceiverFunction where - F: Fn(&Py, $($T,)*) -> R + PyThreadingConstraint + 'static, + F: Fn(&Py, $($T,)* ) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { - fn call_(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult { - let (zelf, $($n,)*) = args.bind_for::<(PyRef, $($T,)*)>(vm, callee)?; + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; - (self)(&zelf, $($n,)*).to_pyresult(vm) + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + let receiver = native_receiver(receiver, callee, vm)?; + // Even when binding checked the Python class, the Rust payload + // still needs validation for safe manual registrations. + let zelf = receiver.try_downcast_ref::(vm)?; + let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + (self.0)(zelf, $($n,)* ).to_pyresult(vm) } } - impl PyNativeFnInternal<(RefParam, $(OwnedParam<$T>,)*), R, ()> for F + impl IntoPyNativeFn, $(OwnedParam<$T>,)*), R, ()>> for ReceiverFunction where - F: Fn(&S, $($T,)*) -> R + PyThreadingConstraint + 'static, + F: Fn(&S, $($T,)* ) -> R + PyThreadingConstraint + 'static, S: PyPayload, $($T: FromArgs,)* R: ToPyResult, { - fn call_(&self, vm: &VirtualMachine, args: FuncArgs, callee: Callee) -> PyResult { - let (zelf, $($n,)*) = args.bind_for::<(PyRef, $($T,)*)>(vm, callee)?; + const ARGS: &'static [SigArg] = &[$(SigArg::from_arg::<$T>("")),*]; - (self)(&zelf, $($n,)*).to_pyresult(vm) + fn call( + &self, + vm: &VirtualMachine, + receiver: Option<&PyObject>, + args: FuncArgs, + callee: Callee, + ) -> PyResult { + let receiver = native_receiver(receiver, callee, vm)?; + // Even when binding checked the Python class, the Rust payload + // still needs validation for safe manual registrations. + let zelf = receiver.try_downcast_ref::(vm)?; + let ($($n,)*) = args.bind_for::<($($T,)*)>(vm, callee)?; + (self.0)(zelf, $($n,)* ).to_pyresult(vm) } } + }; } @@ -234,4 +422,154 @@ mod tests { assert_eq!(size_of_val(&empty_closure.into_func()), 0); assert_eq!(size_of_val(static_func(empty_closure)), 0); } + #[test] + fn common_receiver_adapter_preserves_call_conventions() { + use crate::{ + builtins::PyModule, + function::{ItemDoc, PyMethodDef, PyMethodFlags}, + }; + + fn no_args(_: &Py) {} + fn one_arg(_: &Py, _: u32) {} + fn two_args(_: &Py, _: u32, _: u32) {} + fn arbitrary_args(_: &Py, _: FuncArgs) {} + + macro_rules! check { + ($function:ident, $flags:expr) => {{ + const FUNCTION: PyMethodDef = PyMethodDef::new_const( + "example", + ReceiverFunction($function), + PyMethodFlags::EMPTY, + ItemDoc::NONE, + ); + const METHOD: PyMethodDef = PyMethodDef::new_method_const( + "example", + $function, + PyMethodFlags::METHOD, + ItemDoc::NONE, + ); + assert_eq!(FUNCTION.flags, $flags); + assert_eq!(METHOD.flags, $flags.union(PyMethodFlags::METHOD)); + assert_eq!(size_of_val(&ReceiverFunction($function)), 0); + }}; + } + check!(no_args, PyMethodFlags::NOARGS); + check!(one_arg, PyMethodFlags::O); + check!(two_args, PyMethodFlags::FASTCALL); + check!( + arbitrary_args, + PyMethodFlags::FASTCALL.union(PyMethodFlags::KEYWORDS) + ); + } + + #[test] + fn method_receivers_are_borrowed_outside_python_arguments() { + use crate::{AsObject, PyObjectRef, PyRef, builtins::PyList}; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let receiver = vm.ctx.new_list(vec![]); + let count = receiver.as_object().strong_count(); + let value = vm.ctx.new_int(42).into(); + ReceiverFunction(move |zelf: &Py, args: FuncArgs| { + assert_eq!(zelf.as_object().strong_count(), count); + assert_eq!(args.args.len(), 1); + assert_eq!(args.kwargs.len(), 1); + }) + .call( + vm, + Some(receiver.as_object()), + FuncArgs::new( + vec![value], + core::iter::once(("named", vm.ctx.none())).collect::(), + ), + Callee::named("borrowed"), + ) + .unwrap(); + let payload = core::ptr::from_ref(&**receiver) as usize; + ReceiverFunction(move |zelf: &PyList, _vm: &VirtualMachine| { + assert_eq!(core::ptr::from_ref(zelf) as usize, payload); + }) + .call( + vm, + Some(receiver.as_object()), + FuncArgs::default(), + Callee::named("payload"), + ) + .unwrap(); + ReceiverFunction(move |zelf: PyRef| { + assert_eq!(zelf.as_object().strong_count(), count + 1); + }) + .call( + vm, + Some(receiver.as_object()), + FuncArgs::default(), + Callee::named("owned"), + ) + .unwrap(); + let result = ReceiverFunction(|zelf: PyObjectRef| zelf) + .call( + vm, + Some(receiver.as_object()), + FuncArgs::default(), + Callee::named("object"), + ) + .unwrap(); + assert!(result.is(receiver.as_object())); + }); + } + + #[test] + fn ordinary_functions_ignore_native_receivers() { + use crate::{AsObject, PyRef, builtins::PyList}; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let receiver = vm.ctx.new_str("not the Python argument"); + let argument = vm.ctx.new_list(vec![]); + let function = |value: PyRef| value; + let result = IntoPyNativeFn::call( + &function, + vm, + Some(receiver.as_object()), + FuncArgs::from(vec![argument.clone().into()]), + Callee::named("ordinary"), + ) + .unwrap(); + assert!(result.is(argument.as_object())); + }); + } + + #[test] + fn method_adapters_validate_missing_and_mismatched_payloads() { + use crate::{ + AsObject, + builtins::PyList, + function::{ItemDoc, PyMethodFlags}, + }; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let method = ReceiverFunction(|_zelf: &PyList| ()); + let error = method + .call(vm, None, FuncArgs::default(), Callee::named("example")) + .unwrap_err(); + assert_eq!( + error.args().as_slice()[0] + .try_to_value::(vm) + .unwrap(), + "unbound method example needs an argument" + ); + + // This is a safe public construction API. A descriptor class check + // alone cannot prove the Rust receiver payload matches the adapter. + let definition = + vm.ctx + .new_method_def("example", method, PyMethodFlags::METHOD, ItemDoc::NONE); + let descriptor = definition.build_method(vm.ctx.types.object_type, vm); + let wrong_receiver = vm.ctx.new_str("wrong payload"); + let error = descriptor + .as_object() + .call((wrong_receiver.clone(),), vm) + .unwrap_err(); + assert!(error.class().is(vm.ctx.exceptions.type_error)); + let bound = descriptor.bind(wrong_receiver.into(), &vm.ctx); + let error = bound.as_object().call((), vm).unwrap_err(); + assert!(error.class().is(vm.ctx.exceptions.type_error)); + }); + } } diff --git a/crates/vm/src/function/fspath.rs b/crates/vm/src/function/fspath.rs index 671ef47d8d9..6cfcb9e71e9 100644 --- a/crates/vm/src/function/fspath.rs +++ b/crates/vm/src/function/fspath.rs @@ -84,7 +84,7 @@ impl FsPath { // TODO: FS encodings match self { Self::Str(s) => vm.fsencode(s), - Self::Bytes(b) => Self::bytes_as_os_str(b.as_bytes(), vm).map(Cow::Borrowed), + Self::Bytes(b) => Self::bytes_as_os_str(b.as_bytes(), vm), } } @@ -108,13 +108,22 @@ impl FsPath { pub fn to_path_buf(&self, vm: &VirtualMachine) -> PyResult { let path = match self { Self::Str(s) => PathBuf::from(vm.fsencode(s)?.as_ref() as &OsStr), - Self::Bytes(b) => PathBuf::from(Self::bytes_as_os_str(b.as_bytes(), vm)?), + Self::Bytes(b) => PathBuf::from(Self::bytes_as_os_str(b.as_bytes(), vm)?.into_owned()), }; Ok(path) } pub fn to_cstring(&self, vm: &VirtualMachine) -> PyResult { - alloc::ffi::CString::new(self.as_bytes()).map_err(|e| e.into_pyexception(vm)) + #[cfg(any(unix, all(target_os = "wasi", not(target_env = "p2"))))] + let os_str = self.as_os_str(vm)?; + #[cfg(any(unix, all(target_os = "wasi", not(target_env = "p2"))))] + let bytes = { + use rustpython_host_env::os::ffi::OsStrExt; + os_str.as_bytes() + }; + #[cfg(not(any(unix, all(target_os = "wasi", not(target_env = "p2")))))] + let bytes = self.as_bytes(); + alloc::ffi::CString::new(bytes).map_err(|e| e.into_pyexception(vm)) } #[cfg(windows)] @@ -123,16 +132,40 @@ impl FsPath { .map_err(|err| err.into_pyexception(vm)) } - pub fn bytes_as_os_str<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult<&'a std::ffi::OsStr> { - rustpython_host_env::os::bytes_as_os_str(b).map_err(|e| { - vm.new_unicode_decode_error( - vm.ctx.new_str("utf-8"), - vm.ctx.new_bytes(b.to_vec()), - e.valid_up_to(), - e.error_len().map_or(b.len(), |n| e.valid_up_to() + n), - vm.ctx.new_str("can't decode path for utf-8"), - ) - }) + #[cfg(windows)] + pub fn bytes_as_os_str<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult> { + use std::os::windows::ffi::OsStringExt; + + if !vm.state.config.settings.legacy_windows_fs_encoding + && let Ok(value) = core::str::from_utf8(b) + { + return Ok(Cow::Borrowed(OsStr::new(value))); + } + // CPython path_converter(make_wide=True) decodes bytes with the + // filesystem codec before constructing a Windows wide string. + let decoded = vm.state.codec_registry.decode_text( + vm.ctx.new_bytes(b.to_vec()).into(), + vm.fs_encoding().as_ref(), + Some(vm.fs_encode_errors().to_owned()), + vm, + )?; + let wide: Vec = decoded.as_wtf8().encode_wide().collect(); + Ok(Cow::Owned(std::ffi::OsString::from_wide(&wide))) + } + + #[cfg(not(windows))] + pub fn bytes_as_os_str<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult> { + rustpython_host_env::os::bytes_as_os_str(b) + .map(Cow::Borrowed) + .map_err(|e| { + vm.new_unicode_decode_error( + vm.ctx.new_str("utf-8"), + vm.ctx.new_bytes(b.to_vec()), + e.valid_up_to(), + e.error_len().map_or(b.len(), |n| e.valid_up_to() + n), + vm.ctx.new_str("can't decode path for utf-8"), + ) + }) } } diff --git a/crates/vm/src/function/getargs.rs b/crates/vm/src/function/getargs.rs deleted file mode 100644 index cc335727b7f..00000000000 --- a/crates/vm/src/function/getargs.rs +++ /dev/null @@ -1,123 +0,0 @@ -//! `PyArg_ParseTupleAndKeywords` argument matching. - -use super::FuncArgs; -use crate::{PyObject, PyObjectRef, PyResult, VirtualMachine, common::wtf8::Wtf8}; - -/// The keyword list of a `PyArg_ParseTupleAndKeywords` call together with the -/// `|`, `$` and `:` markers of its format string. Names are matched to the -/// supplied arguments; converting them is left to the caller. -pub(crate) struct ArgSpec<'a> { - /// What the `:name` suffix names the function in error messages. - pub(crate) fname: &'a str, - /// Every parameter name, in `kwlist` order. None may be positional-only. - pub(crate) keywords: &'a [&'a str], - /// Where `|` sits: how many leading parameters are required. Equal to the - /// parameter count when the format string has no `|`. - pub(crate) required: usize, - /// Where `$` sits: how many leading parameters may be given positionally. - /// Equal to the parameter count when the format string has no `$`. - pub(crate) max_positional: usize, -} - -impl ArgSpec<'_> { - pub(crate) fn parse( - &self, - args: &FuncArgs, - vm: &VirtualMachine, - ) -> PyResult>> { - self.parse_with(args, |_, _, _| Ok(()), vm) - } - - /// `check` runs for each supplied argument in `kwlist` order, so a - /// conversion failure is reported ahead of the checks that follow it. - pub(crate) fn parse_with( - &self, - args: &FuncArgs, - check: impl Fn(usize, &PyObject, &VirtualMachine) -> PyResult<()>, - vm: &VirtualMachine, - ) -> PyResult>> { - let fname = self.fname; - let len = self.keywords.len(); - let nargs = args.args.len(); - let mut nkwargs = args.kwargs.len(); - if nargs + nkwargs > len { - // Saying "keyword" when nothing was passed positionally keeps the - // message right for keyword-only signatures. - return Err(vm.new_type_error(format!( - "{fname}() takes at most {len} {}argument{} ({} given)", - if nargs == 0 { "keyword " } else { "" }, - if len == 1 { "" } else { "s" }, - nargs + nkwargs, - ))); - } - - let mut slots = vec![None; len]; - let mut exhausted = false; - for (i, slot) in slots.iter_mut().enumerate() { - if i == self.max_positional && self.max_positional < nargs { - return Err(vm.new_type_error(if self.max_positional == 0 { - format!("{fname}() takes no positional arguments") - } else { - format!( - "{fname}() takes {} {} positional argument{} ({nargs} given)", - if self.required < len { - "at most" - } else { - "exactly" - }, - self.max_positional, - if self.max_positional == 1 { "" } else { "s" }, - ) - })); - } - let current = if i < nargs { - Some(args.args[i].clone()) - } else if nkwargs > 0 { - args.kwargs - .get(self.keywords[i]) - .inspect(|_| nkwargs -= 1) - .cloned() - } else { - None - }; - if let Some(obj) = current { - check(i, &obj, vm)?; - *slot = Some(obj); - continue; - } - if i < self.required { - return Err(vm.new_type_error(format!( - "{fname}() missing required argument '{}' (pos {})", - self.keywords[i], - i + 1 - ))); - } - // All the required arguments are in and no keyword is left over, - // so nothing below can fail. - if nkwargs == 0 { - exhausted = true; - break; - } - } - - if !exhausted && nkwargs > 0 { - for (i, name) in self.keywords.iter().enumerate().take(nargs) { - if args.kwargs.contains_key(name) { - return Err(vm.new_type_error(format!( - "argument for {fname}() given by name ('{name}') and position ({})", - i + 1 - ))); - } - } - for key in args.kwargs.keys() { - if !self.keywords.iter().any(|name| &**key == Wtf8::new(name)) { - return Err(vm.new_type_error(format!( - "{fname}() got an unexpected keyword argument '{key}'" - ))); - } - } - return Err(vm.new_type_error(format!("invalid keyword argument for {fname}()"))); - } - Ok(slots) - } -} diff --git a/crates/vm/src/function/legacy_args.rs b/crates/vm/src/function/legacy_args.rs new file mode 100644 index 00000000000..7f1ceefe6aa --- /dev/null +++ b/crates/vm/src/function/legacy_args.rs @@ -0,0 +1,438 @@ +//! `PyArg_ParseTupleAndKeywords` argument matching. + +use super::{FuncArgs, KwArgs, given_by_name_and_position_message}; +use crate::{ + AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, + builtins::PyBaseExceptionRef, + common::wtf8::{Wtf8, Wtf8Buf}, +}; + +/// The keyword list of a `PyArg_ParseTupleAndKeywords` call together with the +/// `|`, `$` and `:` markers of its format string. Names are matched to the +/// supplied arguments; converting them is left to the caller. +pub struct ArgSpec<'a> { + /// What the `:name` suffix names the function in error messages. + pub fname: &'a str, + /// Every parameter name, in `kwlist` order. None may be positional-only. + pub keywords: &'a [&'a str], + /// Where `|` sits: how many leading parameters are required. Equal to the + /// parameter count when the format string has no `|`. + pub required: usize, + /// Where `$` sits: how many leading parameters may be given positionally. + /// Equal to the parameter count when the format string has no `$`. + pub max_positional: usize, +} + +/// Sequential view of `ArgSpec` slots in kwlist order. +pub struct ArgSlots<'a> { + spec: &'a ArgSpec<'a>, + args: &'a [PyObjectRef], + kwargs: &'a KwArgs, + index: usize, + nkwargs: usize, + exhausted: bool, +} + +impl ArgSpec<'_> { + pub fn parse( + &self, + args: &FuncArgs, + vm: &VirtualMachine, + ) -> PyResult>> { + self.parse_with(args, |_, _, _| Ok(()), vm) + } + + /// `check` runs for each supplied argument in `kwlist` order, so a + /// conversion failure is reported ahead of the checks that follow it. + /// It may retain converted values, avoiding a second conversion after + /// validation and repeated calls to user-defined conversion methods. + pub fn parse_with( + &self, + args: &FuncArgs, + mut check: impl FnMut(usize, &PyObject, &VirtualMachine) -> PyResult<()>, + vm: &VirtualMachine, + ) -> PyResult>> { + self.bind(args, vm, |slots| { + let mut parsed = vec![None; self.keywords.len()]; + for (i, slot) in parsed.iter_mut().enumerate() { + let value = if i < self.required { + Some(slots.required(vm)?) + } else { + slots.optional(vm)? + }; + if let Some(ref obj) = value { + check(i, obj, vm)?; + } + *slot = value; + } + Ok(parsed) + }) + } + + /// Bind the keyword portion of a vectorcall whose positional arguments + /// are handled separately. The caller keeps ownership of both portions. + /// This entry point also supplies CPython's keyword typo suggestions. + pub(crate) fn parse_keywords( + &self, + kwargs: &KwArgs, + vm: &VirtualMachine, + ) -> PyResult>> { + self.bind_parts(&[], kwargs, true, vm, |slots| { + let mut parsed = Vec::with_capacity(self.keywords.len()); + for i in 0..self.keywords.len() { + parsed.push(if i < self.required { + Some(slots.required(vm)?) + } else { + slots.optional(vm)? + }); + } + Ok(parsed) + }) + } + + /// Matches `args` to the kwlist and hands the slots to `bind` in kwlist order. + pub fn bind( + &self, + args: &FuncArgs, + vm: &VirtualMachine, + bind: impl FnOnce(&mut ArgSlots<'_>) -> Result, + ) -> Result + where + E: From, + { + self.bind_parts(&args.args, &args.kwargs, false, vm, bind) + } + + fn bind_parts( + &self, + args: &[PyObjectRef], + kwargs: &KwArgs, + suggest_keywords: bool, + vm: &VirtualMachine, + bind: impl FnOnce(&mut ArgSlots<'_>) -> Result, + ) -> Result + where + E: From, + { + let fname = self.fname; + let len = self.keywords.len(); + let nargs = args.len(); + let nkwargs = kwargs.len(); + if nargs + nkwargs > len { + // Saying "keyword" when nothing was passed positionally keeps the + // message right for keyword-only signatures. + return Err(E::from(vm.new_type_error(format!( + "{fname}() takes at most {len} {}argument{} ({} given)", + if nargs == 0 { "keyword " } else { "" }, + if len == 1 { "" } else { "s" }, + nargs + nkwargs, + )))); + } + + let mut slots = ArgSlots { + spec: self, + args, + kwargs, + index: 0, + nkwargs, + exhausted: false, + }; + let result = bind(&mut slots)?; + while slots.index < len { + debug_assert!( + slots.index >= self.required, + "bind closure skipped a required argument" + ); + let supplied = slots.take_current(vm)?; + debug_assert!( + supplied.is_none(), + "bind closure skipped a supplied argument" + ); + let _ = supplied; + } + if !slots.exhausted && slots.nkwargs > 0 { + for (i, name) in self.keywords.iter().enumerate().take(nargs) { + if kwargs.contains_key(name) { + return Err(E::from(vm.new_type_error( + given_by_name_and_position_message(Some(fname), name, i + 1), + ))); + } + } + for key in kwargs.keys() { + if !self.keywords.iter().any(|name| &**key == Wtf8::new(name)) { + let mut message = + Wtf8Buf::from(format!("{fname}() got an unexpected keyword argument '")); + if suggest_keywords { + // A keyword may contain a lone surrogate. Preserve it + // in the error rather than formatting it as UTF-8. + message.push_wtf8(key); + } else { + message.push_str(&key.to_string()); + } + message.push_str("'"); + // CPython cannot calculate suggestions for a name that + // does not encode as UTF-8, including lone surrogates. + if suggest_keywords && key.as_str().is_ok() { + let names: Vec<_> = self + .keywords + .iter() + .map(|name| vm.ctx.new_str(*name)) + .collect(); + let name = vm.ctx.new_str(&**key); + if let Some(suggestion) = crate::suggestion::calculate_keyword_suggestions( + names.iter().map(|name| name.as_object()), + name.as_object(), + ) { + message.push_str(&format!(". Did you mean '{suggestion}'?")); + } + } + return Err(E::from(vm.new_type_error(message))); + } + } + return Err(E::from( + vm.new_type_error(format!("invalid keyword argument for {fname}()")), + )); + } + Ok(result) + } +} + +impl ArgSlots<'_> { + /// The next slot, which must be filled: the "missing required argument" error otherwise. + pub fn required(&mut self, vm: &VirtualMachine) -> PyResult { + self.check_cursor(vm)?; + debug_assert!( + self.index < self.spec.required, + "bind cursor requested a required argument past the required prefix" + ); + if self.index >= self.spec.required { + return Err(vm.new_system_error(format!( + "{}() bind cursor requested a required argument past the required prefix", + self.spec.fname + ))); + } + let i = self.index; + match self.take_current(vm)? { + Some(obj) => Ok(obj), + None => self.missing_required(i, vm), + } + } + + /// The next slot, `None` when the caller left it out. + pub fn optional(&mut self, vm: &VirtualMachine) -> PyResult> { + self.check_cursor(vm)?; + let i = self.index; + match self.take_current(vm)? { + Some(obj) => Ok(Some(obj)), + None if i < self.spec.required => self.missing_required(i, vm), + None => Ok(None), + } + } + + /// `required` converted with `TryFromObject`. + pub fn required_as(&mut self, vm: &VirtualMachine) -> PyResult { + T::try_from_object(vm, self.required(vm)?) + } + + /// `optional` converted with `TryFromObject`. + pub fn optional_as(&mut self, vm: &VirtualMachine) -> PyResult> { + match self.optional(vm)? { + Some(obj) => T::try_from_object(vm, obj).map(Some), + None => Ok(None), + } + } + + fn check_cursor(&self, vm: &VirtualMachine) -> PyResult<()> { + debug_assert!( + self.index < self.spec.keywords.len(), + "bind cursor moved past the end of the parameter list" + ); + if self.index >= self.spec.keywords.len() { + return Err(vm.new_system_error(format!( + "{}() bind cursor moved past the end of the parameter list", + self.spec.fname + ))); + } + Ok(()) + } + + fn missing_required(&self, i: usize, vm: &VirtualMachine) -> PyResult { + Err(vm.new_type_error(format!( + "{}() missing required argument '{}' (pos {})", + self.spec.fname, + self.spec.keywords[i], + i + 1 + ))) + } + + /// One iteration of the matching loop for the current index. + fn take_current(&mut self, vm: &VirtualMachine) -> PyResult> { + let i = self.index; + self.index += 1; + if self.exhausted { + return Ok(None); + } + let fname = self.spec.fname; + let len = self.spec.keywords.len(); + let nargs = self.args.len(); + if i == self.spec.max_positional && self.spec.max_positional < nargs { + return Err(vm.new_type_error(if self.spec.max_positional == 0 { + format!("{fname}() takes no positional arguments") + } else { + format!( + "{fname}() takes {} {} positional argument{} ({nargs} given)", + if self.spec.required < len { + "at most" + } else { + "exactly" + }, + self.spec.max_positional, + if self.spec.max_positional == 1 { + "" + } else { + "s" + }, + ) + })); + } + let current = if i < nargs { + Some(self.args[i].clone()) + } else if self.nkwargs > 0 { + self.kwargs + .get(self.spec.keywords[i]) + .inspect(|_| self.nkwargs -= 1) + .cloned() + } else { + None + }; + if current.is_none() && i >= self.spec.required && self.nkwargs == 0 { + // All the required arguments are in and no keyword is left over, + // so nothing below can fail. + self.exhausted = true; + } + Ok(current) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::function::KwArgs; + + const SPEC: ArgSpec<'static> = ArgSpec { + fname: "example", + keywords: &["first", "second", "third"], + required: 1, + max_positional: 3, + }; + + #[test] + fn mutable_converters_run_once_in_parameter_order() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let args = FuncArgs::new( + vec![vm.ctx.none()], + core::iter::once(("third", vm.ctx.none())).collect::(), + ); + let mut visited = Vec::new(); + let mut retained = [None, None, None]; + let parsed = match SPEC.parse_with( + &args, + |i, obj, _vm| { + visited.push(i); + retained[i] = Some(obj.to_owned()); + Ok(()) + }, + vm, + ) { + Ok(parsed) => parsed, + Err(_) => panic!("parse_with failed"), + }; + assert_eq!(visited, [0, 2]); + assert_eq!(parsed.len(), 3); + assert!(retained[0].is_some()); + assert!(retained[1].is_none()); + assert!(retained[2].is_some()); + }); + } + + #[test] + fn supplied_values_convert_before_missing_arguments() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let spec = ArgSpec { + required: 2, + ..SPEC + }; + let args = FuncArgs::from(vec![vm.ctx.none()]); + let mut visited = Vec::new(); + let result = spec.parse_with( + &args, + |i, _obj, _vm| { + visited.push(i); + Ok(()) + }, + vm, + ); + assert!(result.is_err()); + assert_eq!(visited, [0]); + }); + } + + #[test] + fn supplied_values_convert_before_leftover_keywords() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for keyword in ["first", "unexpected"] { + let args = FuncArgs::new( + vec![vm.ctx.none()], + core::iter::once((keyword, vm.ctx.none())).collect::(), + ); + let mut visited = Vec::new(); + let result = SPEC.parse_with( + &args, + |i, _obj, _vm| { + visited.push(i); + Ok(()) + }, + vm, + ); + assert!(result.is_err()); + assert_eq!(visited, [0]); + } + }); + } + + #[test] + fn total_argument_overflow_does_not_run_converters() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let args = FuncArgs::from(vec![vm.ctx.none(); 4]); + let mut calls = 0; + let result = SPEC.parse_with( + &args, + |_, _obj, _vm| { + calls += 1; + Ok(()) + }, + vm, + ); + assert!(result.is_err()); + assert_eq!(calls, 0); + }); + } + + #[test] + fn conversion_failure_stops_before_later_parameters() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let args = FuncArgs::from(vec![vm.ctx.none(); 3]); + let mut visited = Vec::new(); + let result = SPEC.parse_with( + &args, + |i, _obj, vm| { + visited.push(i); + Err(vm.new_value_error("conversion failed")) + }, + vm, + ); + assert!(result.is_err()); + assert_eq!(visited, [0]); + }); + } +} diff --git a/crates/vm/src/function/method.rs b/crates/vm/src/function/method.rs index 0a80efc939e..a8f76c2a0d4 100644 --- a/crates/vm/src/function/method.rs +++ b/crates/vm/src/function/method.rs @@ -1,12 +1,13 @@ use crate::{ Context, Py, PyObjectRef, PyPayload, PyRef, VirtualMachine, builtins::{ - PyType, + PyModule, PyStaticMethod, PyType, builtin_func::{PyNativeFunction, PyNativeMethod}, descriptor::{PyClassMethodDescriptor, PyMethodDescriptor}, }, class::PyClassDef, - function::{IntoPyNativeFn, PyNativeFn}, + function::{FuncArgs, IntoPyNativeFn, PyNativeFn, SigArg}, + types::PyTypeFlags, }; bitflags::bitflags! { @@ -49,15 +50,38 @@ bitflags::bitflags! { impl PyMethodFlags { // FIXME: macro temp pub const EMPTY: Self = Self::empty(); + + const CALL_CONVENTION: Self = Self::VARARGS + .union(Self::KEYWORDS) + .union(Self::NOARGS) + .union(Self::O) + .union(Self::FASTCALL); + + /// Adds the calling convention inferred from `args` unless one is set. + pub(crate) const fn with_call_convention(self, args: &[SigArg]) -> Self { + if self.intersects(Self::CALL_CONVENTION) { + return self; + } + self.union(super::signature::native_call_flags(args)) + } } #[macro_export] macro_rules! define_methods { + (@function $func:ident, METHOD) => { + $crate::function::static_func($crate::function::ReceiverFunction($func)) + }; + (@function $func:ident, CLASS) => { + $crate::function::static_func($crate::function::ReceiverFunction($func)) + }; + (@function $func:ident, $flags:ident) => { + $crate::function::static_func($func) + }; // TODO: more flexible syntax ($($name:literal => $func:ident as $flags:ident),+) => { vec![ $( $crate::function::PyMethodDef { name: $name, - func: $crate::function::static_func($func), + func: $crate::define_methods!(@function $func, $flags), flags: $crate::function::PyMethodFlags::$flags, #[cfg(feature = "doc")] doc_off: 0, @@ -115,16 +139,16 @@ impl PyMethodDef { } #[inline] - pub const fn new_const( + pub const fn new_const>( name: &'static str, - func: impl IntoPyNativeFn, + func: F, flags: PyMethodFlags, doc: super::ItemDoc, ) -> Self { Self { name, func: super::static_func(func), - flags, + flags: flags.with_call_convention(F::ARGS), #[cfg(feature = "doc")] doc_off: doc.offset, #[cfg(feature = "doc")] @@ -135,6 +159,20 @@ impl PyMethodDef { } } + /// Construct a method whose first Rust parameter is supplied by native binding. + #[inline] + pub const fn new_method_const( + name: &'static str, + func: F, + flags: PyMethodFlags, + doc: super::ItemDoc, + ) -> Self + where + super::ReceiverFunction: IntoPyNativeFn, + { + Self::new_const(name, super::ReceiverFunction(func), flags, doc) + } + #[inline] pub const fn new_raw_const( name: &'static str, @@ -145,7 +183,7 @@ impl PyMethodDef { Self { name, func: super::static_raw_func(func), - flags, + flags: flags.with_call_convention(&[SigArg::from_arg::("args")]), #[cfg(feature = "doc")] doc_off: doc.offset, #[cfg(feature = "doc")] @@ -166,7 +204,9 @@ impl PyMethodDef { } else if self.flags.contains(PyMethodFlags::CLASS) { self.build_classmethod(ctx, class).into() } else if self.flags.contains(PyMethodFlags::STATIC) { - self.build_staticmethod(ctx, class).into() + PyStaticMethod::new(self.build_staticmethod(ctx, class).into()) + .into_ref(ctx) + .into() } else { unreachable!() } @@ -177,12 +217,18 @@ impl PyMethodDef { PyNativeFunction { zelf: None, value: self, - module_object: None, module: crate::object::PyAtomicRef::new_empty(), _method_def_owner: None, } } + #[must_use] + pub fn to_module_function(&'static self, module: PyRef) -> PyNativeFunction { + let mut function = self.to_function(); + function.zelf = Some(module.into()); + function + } + pub fn to_method( &'static self, class: &'static Py, @@ -200,7 +246,6 @@ impl PyMethodDef { func: PyNativeFunction { zelf: Some(obj), value: self, - module_object: None, module: crate::object::PyAtomicRef::new_empty(), _method_def_owner: None, }, @@ -216,13 +261,21 @@ impl PyMethodDef { &'static self, ctx: &Context, obj: PyObjectRef, + ) -> PyRef { + self.build_bound_function_with_owner(ctx, obj, None) + } + + pub(crate) fn build_bound_function_with_owner( + &'static self, + ctx: &Context, + obj: PyObjectRef, + owner: Option, ) -> PyRef { let function = PyNativeFunction { zelf: Some(obj), value: self, - module_object: None, module: crate::object::PyAtomicRef::new_empty(), - _method_def_owner: None, + _method_def_owner: owner, }; PyRef::new_ref( function, @@ -249,7 +302,7 @@ impl PyMethodDef { ) -> PyRef { PyRef::new_ref( self.to_bound_method(obj, class), - ctx.types.builtin_function_or_method_type.to_owned(), + ctx.types.builtin_method_type.to_owned(), None, ) } @@ -267,18 +320,23 @@ impl PyMethodDef { &'static self, ctx: &Context, class: &'static Py, - ) -> PyRef { + ) -> PyRef { debug_assert!(self.flags.contains(PyMethodFlags::STATIC)); - // Set zelf to the class (m_self = type for static methods). - // Callable::call skips prepending when STATIC flag is set. - let func = PyNativeFunction { - zelf: Some(class.to_owned().into()), - value: self, - module_object: None, - module: crate::object::PyAtomicRef::new_empty(), - _method_def_owner: None, + // Match PyCFunction_NewEx(meth, type, type_module(type)): snapshot + // module metadata here so later mutation/deletion remains observable. + let module = if class.slots.flags.has_feature(PyTypeFlags::HEAPTYPE) { + class.attributes.get(ctx.intern_str("__module__")) + } else { + let name = class.slot_name(); + let module = name + .rsplit_once('.') + .map_or("builtins", |(module, _)| module); + Some(ctx.intern_str(module).to_owned().into()) }; - PyNativeMethod { func, class }.into_ref(ctx) + // m_self is the type; the static adapter ignores it on call. + let function = self.build_bound_function(ctx, class.to_owned().into()); + drop(function.module.store(module)); + function } /// Concatenate method groups. A pending body is copied from `docs`, then cleared. @@ -313,7 +371,7 @@ impl PyMethodDef { ) -> [Self; SUM_LEN] { const NULL_METHOD: PyMethodDef = PyMethodDef { name: "", - func: &|_, _, _| unreachable!(), + func: &|_, _, _, _| unreachable!(), flags: PyMethodFlags::empty(), #[cfg(feature = "doc")] doc_off: 0, @@ -375,15 +433,51 @@ impl core::fmt::Debug for PyMethodDef { // This is not a part of CPython API. // But useful to support dynamically generated methods #[pyclass(name, module = false, ctx = "method_def")] -#[derive(Debug)] pub struct HeapMethodDef { method: PyMethodDef, + _function_owner: Option>, +} + +impl core::fmt::Debug for HeapMethodDef { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + self.method.fmt(f) + } } impl HeapMethodDef { #[must_use] pub const fn new(method: PyMethodDef) -> Self { - Self { method } + Self { + method, + _function_owner: None, + } + } + + pub(crate) fn with_owned_function( + name: &'static str, + function: Box, + flags: PyMethodFlags, + doc: super::ItemDoc, + ) -> Self { + // SAFETY: the box has a stable address and is retained by this payload. + // The definition is private; all functions/descriptors referring to it + // retain this HeapMethodDef and expose no static reference to callers. + let func = unsafe { &*core::ptr::from_ref(&*function) }; + Self { + method: PyMethodDef { + name, + func, + flags, + #[cfg(feature = "doc")] + doc_off: doc.offset, + #[cfg(feature = "doc")] + doc_len: doc.len, + #[cfg(feature = "doc")] + doc_body_pending: false, + doc: doc.text, + }, + _function_owner: Some(function), + } } } @@ -420,6 +514,20 @@ impl Py { None, ) } + + pub fn build_classmethod( + &self, + class: &'static Py, + vm: &VirtualMachine, + ) -> PyRef { + let mut function = PyClassMethodDescriptor::new(unsafe { self.method() }, class, &vm.ctx); + function._method_def_owner = Some(self.to_owned().into()); + PyRef::new_ref( + function, + vm.ctx.types.classmethod_descriptor_type.to_owned(), + None, + ) + } } #[pyclass] @@ -431,3 +539,96 @@ pub(crate) fn init(ctx: &'static Context) { let _ = ctx.intern_str(HeapMethodDef::NAME); } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{AsObject, function::FuncArgs}; + + #[test] + fn generated_functions_own_and_release_their_native_captures() { + use alloc::sync::Arc; + let captured = Arc::new(17); + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let capture = captured.clone(); + let definition = vm.ctx.new_method_def( + "captured", + move |_args: FuncArgs| *capture, + PyMethodFlags::empty(), + super::super::ItemDoc::NONE, + ); + let function = definition.build_function(vm, None); + let descriptor = definition.build_method(vm.ctx.types.object_type, vm); + drop(definition); + assert_eq!(Arc::strong_count(&captured), 2); + assert_eq!( + function + .as_object() + .call((), vm) + .unwrap() + .try_into_value::(vm) + .unwrap(), + 17 + ); + let method = descriptor.bind(vm.ctx.none(), &vm.ctx); + assert!(method._method_def_owner.is_some()); + drop(function); + drop(descriptor); + assert_eq!(Arc::strong_count(&captured), 2); + assert_eq!( + method + .as_object() + .call((), vm) + .unwrap() + .try_into_value::(vm) + .unwrap(), + 17 + ); + drop(method); + assert_eq!(Arc::strong_count(&captured), 1); + }); + } + #[test] + fn bound_native_call_does_not_clone_or_prepend_the_receiver() { + use crate::{builtins::PyList, function::ReceiverFunction}; + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let receiver = vm.ctx.new_list(vec![]); + let count_when_bound = receiver.as_object().strong_count() + 1; + let definition = vm.ctx.new_method_def( + "borrowed", + ReceiverFunction(move |zelf: &Py, args: FuncArgs| { + assert_eq!(zelf.as_object().strong_count(), count_when_bound); + assert_eq!(args.args.len(), 1); + assert_eq!(args.kwargs.len(), 1); + }), + PyMethodFlags::METHOD, + super::super::ItemDoc::NONE, + ); + let function = definition.build_function(vm, Some(receiver.into())); + // Keep one explicit owner in addition to the function's receiver. + let receiver = function.get_self().unwrap().to_owned(); + for vectorcall in [false, true] { + if vectorcall { + let keyword = vm.ctx.new_str("named").into(); + function + .as_object() + .vectorcall(vec![vm.ctx.none(), vm.ctx.none()], 1, Some(&[keyword]), vm) + .unwrap(); + } else { + function + .as_object() + .call( + FuncArgs::new( + vec![vm.ctx.none()], + core::iter::once(("named", vm.ctx.none())) + .collect::(), + ), + vm, + ) + .unwrap(); + } + } + assert_eq!(receiver.strong_count(), count_when_bound); + }); + } +} diff --git a/crates/vm/src/function/mod.rs b/crates/vm/src/function/mod.rs index 0fcbffc96bb..e4cb47aa1e7 100644 --- a/crates/vm/src/function/mod.rs +++ b/crates/vm/src/function/mod.rs @@ -5,8 +5,8 @@ mod builtin; mod doctext; mod either; mod fspath; -mod getargs; mod getset; +mod legacy_args; pub(crate) mod method; mod number; mod protocol; @@ -14,39 +14,92 @@ mod signature; mod time; pub use argument::{ - ArgumentError, Callee, FromArgOptional, FromArgs, FuncArgs, IntoFuncArgs, KwArgs, KwArgsMap, - NameArgs, NameChanges, NameCoordinates, NameExcInfo, NameFields, NameIntegers, NameIterables, - NameKeywords, NameKwargs, NameKwds, NameKws, NameObjs, NameOthers, OptionalArg, - OptionalArgDefault, OptionalOption, PosArgs, PositionalIterable, + ArgsMetadata, ArgumentError, BorrowedArgs, Callee, FromArgOptional, FromArgs, + FromBorrowedArgOptional, FuncArgs, IntoFuncArgs, KwArgs, KwArgsMap, NameArgs, NameChanges, + NameCoordinates, NameExcInfo, NameFields, NameIntegers, NameIterables, NameKeywords, + NameKwargs, NameKwds, NameKws, NameObjects, NameObjs, NameOthers, NameValues, OptionalArg, + OptionalArgDefault, OptionalOption, PosArgs, PositionalIterable, UnpackKeywords, +}; +pub(crate) use argument::{ + arity_message, given_by_name_and_position_message, unexpected_keyword_message, }; -pub(crate) use argument::{arity_message, unexpected_keyword_message}; pub use arithmetic::{PyArithmeticValue, PyComparisonValue}; pub use buffer::{ - ArgAsciiBuffer, ArgBytesLike, ArgContiguousBytesLike, ArgMemoryBuffer, ArgStrOrBytesLike, + ArgAsciiBuffer, ArgBytesLike, ArgBytesOrStr, ArgContiguousBytesLike, ArgMemoryBuffer, + ArgStrOrBytesLike, }; -pub use builtin::{IntoPyNativeFn, PyNativeFn, static_func, static_raw_func}; +pub use builtin::{IntoPyNativeFn, PyNativeFn, ReceiverFunction, static_func, static_raw_func}; pub use doctext::{ItemDoc, db_doc, plain_doc}; pub use either::Either; pub use fspath::FsPath; -pub(crate) use getargs::ArgSpec; pub use getset::PySetterValue; pub(super) use getset::{IntoPyGetterFunc, IntoPySetterFunc, PyGetterFunc, PySetterFunc}; +pub use legacy_args::{ArgSlots, ArgSpec}; pub use method::{HeapMethodDef, PyMethodDef, PyMethodFlags}; +pub(crate) use number::int_as_ssize; pub use number::{ - ArgIndex, ArgIntoBool, ArgIntoComplex, ArgIntoFloat, ArgStrictInt, PySize, PySsize, + ArgCInt, ArgIndex, ArgIntoBool, ArgIntoComplex, ArgIntoFloat, ArgSliceIndex, ArgStrictInt, + PySize, PySsize, }; pub use protocol::{ArgCallable, ArgIterable, ArgMapping, ArgSequence}; pub use signature::{ - DefaultRepr, Param, ParamKind, SigArg, choose_class_params, has_signature, internal_doc_bytes, - internal_doc_len, real_signature, signature_prefix_bytes, signature_prefix_len, + DefaultRepr, Param, ParamKind, SigArg, argument_text_signature, choose_class_params, + has_signature, internal_doc_bytes, internal_doc_len, real_signature, signature_from_flags, + signature_prefix_bytes, signature_prefix_len, text_signature_doc_bytes, text_signature_len, + validate_text_signature, validate_text_signature_without_slash, }; pub use time::TimeoutSeconds; use crate::{ - Py, PyObject, PyResult, VirtualMachine, builtins::PyStr, convert::TryFromBorrowedObject, + Py, PyObject, PyObjectRef, PyResult, VirtualMachine, + builtins::{PyStr, PyUtf8Str, PyUtf8StrRef}, + convert::{TryFromBorrowedObject, TryFromObject}, + exceptions::nul_char_error, }; use builtin::{BorrowedParam, OwnedParam, RefParam}; +/// A `str` argument whose conversion raises `ValueError` when it holds a +/// null character. +#[derive(Debug, Clone)] +pub struct ArgNulFreeStr(PyUtf8StrRef); + +impl ArgNulFreeStr { + #[inline] + #[must_use] + pub fn into_utf8_ref(self) -> PyUtf8StrRef { + self.0 + } + + fn checked(s: PyUtf8StrRef, vm: &VirtualMachine) -> PyResult { + if s.as_str().contains('\0') { + return Err(nul_char_error(vm)); + } + Ok(Self(s)) + } +} + +impl core::ops::Deref for ArgNulFreeStr { + type Target = Py; + + #[inline] + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl TryFromObject for ArgNulFreeStr { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + Self::checked(PyUtf8StrRef::try_from_object(vm, obj)?, vm) + } + + fn try_from_argument(vm: &VirtualMachine, obj: PyObjectRef) -> Result { + Ok(Self::checked( + PyUtf8StrRef::try_from_argument(vm, obj)?, + vm, + )?) + } +} + #[derive(Clone, Copy, PartialEq, Eq)] pub enum ArgByteOrder { Big, diff --git a/crates/vm/src/function/number.rs b/crates/vm/src/function/number.rs index 9fdb06a9717..9cbf716d808 100644 --- a/crates/vm/src/function/number.rs +++ b/crates/vm/src/function/number.rs @@ -1,12 +1,12 @@ use super::argument::OptionalArg; use crate::{ - AsObject, Py, PyObjectRef, PyResult, TryFromObject, VirtualMachine, - builtins::{PyInt, PyIntRef}, + Py, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, TryFromObject, VirtualMachine, + builtins::{PyComplex, PyFloat, PyInt, PyIntRef}, }; -use core::ops::Deref; +use core::{ffi::c_int, ops::Deref}; use malachite_bigint::BigInt; use num_complex::Complex64; -use num_traits::PrimInt; +use num_traits::{PrimInt, ToPrimitive}; /// A Python complex-like object. /// @@ -14,7 +14,7 @@ use num_traits::PrimInt; /// any object that can be transformed into a complex. /// /// If the object is not a Python complex object but has a `__complex__()` -/// method, this method will first be called to convert the object into a float. +/// method, this method will first be called to convert the object into a complex. /// If `__complex__()` is not defined then it falls back to `__float__()`. If /// `__float__()` is not defined it falls back to `__index__()`. #[derive(Debug, PartialEq)] @@ -37,13 +37,23 @@ impl From for Complex64 { } } -impl TryFromObject for ArgIntoComplex { +impl<'a> TryFromBorrowedObject<'a> for ArgIntoComplex { // Equivalent to PyComplex_AsCComplex - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - // We do not care if it was already a complex. - let (value, _) = obj.try_complex(vm)?.ok_or_else(|| { - vm.new_type_error(format!("must be real number, not {}", obj.class().name())) - })?; + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + // Native scalar conversion reads complex subclasses directly. Only the + // complex constructor prefers their overridden __complex__ method. + let value = if let Some(complex) = obj.downcast_ref::() { + complex.as_complex() + } else { + obj.try_complex(vm)? + .ok_or_else(|| { + vm.new_type_error(format!( + "must be real number, not {}", + obj.class().slot_name() + )) + })? + .0 + }; Ok(Self { value }) } } @@ -56,7 +66,7 @@ impl TryFromObject for ArgIntoComplex { /// If the object is not a Python floating point object but has a `__float__()` /// method, this method will first be called to convert the object into a float. /// If `__float__()` is not defined then it falls back to `__index__()`. -#[derive(Debug, PartialEq)] +#[derive(Clone, Copy, Debug, PartialEq)] #[repr(transparent)] pub struct ArgIntoFloat { value: f64, @@ -85,9 +95,15 @@ impl From for f64 { } } -impl TryFromObject for ArgIntoFloat { +impl<'a> TryFromBorrowedObject<'a> for ArgIntoFloat { // Equivalent to PyFloat_AsDouble. - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + // A float subclass is read directly, without calling its __float__. + if let Some(float) = obj.downcast_ref::() { + return Ok(Self { + value: float.to_f64(), + }); + } let value = obj.try_float(vm)?.to_f64(); Ok(Self { value }) } @@ -101,7 +117,7 @@ impl TryFromObject for ArgIntoFloat { /// By default an object is considered true unless its class defines either a /// `__bool__()` method that returns False or a `__len__()` method that returns /// zero, when called with the object. -#[derive(Debug, Default, PartialEq, Eq)] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] pub struct ArgIntoBool { value: bool, } @@ -128,8 +144,8 @@ impl From for bool { } } -impl TryFromObject for ArgIntoBool { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { +impl<'a> TryFromBorrowedObject<'a> for ArgIntoBool { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { Ok(Self { value: obj.try_to_bool(vm)?, }) @@ -149,6 +165,29 @@ impl ArgIndex { pub fn into_int_ref(self) -> PyIntRef { self.value } + + /// Mask a Clinic unsigned bitfield, warning if neither signed nor unsigned + /// storage of the requested width can represent the original integer. + pub fn as_unsigned_bitfield(&self, vm: &VirtualMachine) -> PyResult { + const { assert!(BITS > 0 && BITS <= 64) }; + let minimum = -(1_i128 << (BITS - 1)); + let maximum = (1_i128 << BITS) - 1; + let fits = self + .value + .as_bigint() + .to_i128() + .is_some_and(|value| (minimum..=maximum).contains(&value)); + if !fits { + crate::warn::warn( + vm.ctx.new_str("integer value out of range").into(), + Some(vm.ctx.exceptions.deprecation_warning.to_owned()), + 1, + None, + vm, + )?; + } + Ok(self.value.as_u64_mask() & (u64::MAX >> (64 - BITS))) + } } impl AsRef> for ArgIndex { @@ -163,19 +202,91 @@ impl From for PyIntRef { } } -impl TryFromObject for ArgIndex { - fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { +impl<'a> TryFromBorrowedObject<'a> for ArgIndex { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { Ok(Self { value: obj.try_index(vm)?, }) } } +/// An index argument converted with CPython's `PyLong_AsInt` semantics. +/// +/// Conversion errors raised by `__index__` are preserved. Only an integer +/// outside the C `int` range gets the C integer overflow diagnostic. +#[derive(Debug, Copy, Clone)] +#[repr(transparent)] +pub struct ArgCInt { + pub value: c_int, +} + +impl ArgCInt { + #[inline] + #[must_use] + pub fn into_primitive(self) -> c_int { + self.value + } +} + +impl From for ArgCInt { + fn from(value: c_int) -> Self { + Self { value } + } +} + +impl TryFromObject for ArgCInt { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let value = c_int::try_from(obj.try_index(vm)?.as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C int"))?; + Ok(Self { value }) + } +} + /// A signed size or index argument (`Py_ssize_t`). pub type PySsize = isize; /// An unsigned size argument (`size_t`). pub type PySize = usize; +// PyLong_AsSsize_t differs from index conversion: only actual ints (including +// subclasses) are accepted, and overflow has a size-specific diagnostic. +pub(crate) fn int_as_ssize(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + let int = obj + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("an integer is required"))?; + int.as_ssize_t(vm) +} + +/// Clinic's slice_index(accept={int}): __index__ is accepted and overflow +/// saturates, but None is not an omitted bound. _PyEval_SliceIndexNotNone. +#[derive(Debug, Default)] +pub struct ArgSliceIndex { + pub value: isize, + // Keep a temporary bound alive through the call, without cloning it. + // Its finalizer can mutate or release the sequence being searched. + _source: Option, +} + +impl ArgSliceIndex { + pub const MAX: Self = Self { + value: isize::MAX, + _source: None, + }; +} + +impl TryFromObject for ArgSliceIndex { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let value = crate::sliceable::to_saturated_index( + vm, + &obj, + "slice indices must be integers or have an __index__ method", + )?; + Ok(Self { + value, + _source: Some(obj), + }) + } +} + /// An `int` (or subclass, including `bool`) converted to a Rust primitive. /// /// Unlike the primitive `TryFromObject` impls, this never calls `__index__`. diff --git a/crates/vm/src/function/protocol.rs b/crates/vm/src/function/protocol.rs index 5883a2a4691..0052a314a8e 100644 --- a/crates/vm/src/function/protocol.rs +++ b/crates/vm/src/function/protocol.rs @@ -1,7 +1,7 @@ use super::IntoFuncArgs; use crate::{ - AsObject, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, - builtins::{PyDictRef, iter::PySequenceIterator}, + AsObject, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyAnyDict, PyDictRef, iter::PySequenceIterator}, convert::ToPyObject, object::{Traverse, TraverseFn}, protocol::{PyIter, PyIterIter, PyMapping}, @@ -97,10 +97,12 @@ impl ArgIterable { /// This operation may fail if an exception is raised while invoking the /// `__iter__` method of the iterable object. fn get_iter(&self, vm: &VirtualMachine) -> PyResult { - Ok(PyIter::new(match self.iter_fn { - Some(f) => f(self.iterable.clone(), vm)?, - None => PySequenceIterator::new(self.iterable.clone(), vm)?.into_pyobject(vm), - })) + match self.iter_fn { + Some(_) => PyIter::try_from_object(vm, self.iterable.clone()), + None => Ok(PyIter::new( + PySequenceIterator::new(self.iterable.clone(), vm)?.into_pyobject(vm), + )), + } } /// Returns an iterator over this sequence of objects. See [`PyIter::iter`] @@ -155,6 +157,12 @@ impl ArgMapping { Self { obj: dict.into() } } + #[inline(always)] + #[must_use] + pub fn from_anydict_exact(dict: PyRef) -> Self { + Self { obj: dict.into() } + } + #[inline(always)] #[must_use] pub fn obj(&self) -> &PyObject { diff --git a/crates/vm/src/function/signature.rs b/crates/vm/src/function/signature.rs index 3dfae3ae9df..880106dd45a 100644 --- a/crates/vm/src/function/signature.rs +++ b/crates/vm/src/function/signature.rs @@ -3,7 +3,7 @@ //! The internal doc is `name(params)\n--\n\ndoc`, built in a const context from //! [`FromArgs`] metadata. Nothing here allocates. -use super::argument::FromArgs; +use super::argument::{ArgsMetadata, FromArgs}; #[derive(Clone, Copy, Debug)] pub enum ParamKind { @@ -13,7 +13,8 @@ pub enum ParamKind { VarPositional, VarKeyword, /// Parameters contributed by a nested [`FromArgs`] type. - /// `None` contributes nothing. + /// `None` contributes nothing to display signatures. In binding metadata, + /// it explicitly delegates validation to a custom parser. Flatten(Option<&'static [Param]>), } @@ -30,6 +31,8 @@ pub enum DefaultRepr { Raw(&'static str), /// The argument may be omitted, and that state is not a Python value. Unrepresentable, + /// The Rust default has no declared Python representation. + Unknown, } #[derive(Clone, Copy, Debug)] @@ -104,21 +107,35 @@ impl Param { pub struct SigArg { pub name: &'static str, pub params: Option<&'static [Param]>, + /// Actual accepted arguments, independent of the displayed signature. + /// `None` leaves dispatch permissive so a custom parser owns validation. + pub binding_params: Option<&'static [Param]>, + /// Force `_PyArg_UnpackKeywords` dispatch even for positional-only signatures. + pub force_unpack_keywords: bool, } +const SCALAR_PARAMS: &[Param] = &[Param::positional_only("")]; + impl SigArg { #[must_use] - pub const fn from_arg(name: &'static str) -> Self { + pub const fn from_arg(name: &'static str) -> Self { Self { name, - params: T::PARAMS, + params: T::DISPLAY_PARAMS, + binding_params: T::CLINIC_PARAMS, + force_unpack_keywords: T::UNPACK_KEYWORDS, } } /// `$self` / `$type` receiver marker. Renders as one positional-only parameter. #[must_use] pub const fn marker(name: &'static str) -> Self { - Self { name, params: None } + Self { + name, + params: None, + binding_params: Some(SCALAR_PARAMS), + force_unpack_keywords: false, + } } /// Parameters supplied by the argument a method binds as its receiver. @@ -131,6 +148,380 @@ impl SigArg { Some(ps) => ps, None => &[], }), + binding_params: T::BINDING_PARAMS, + force_unpack_keywords: T::FORCE_UNPACK_KEYWORDS, + } + } +} + +// CPython Objects/typeobject.c::signature_from_flags supplies these when a +// METH_NOARGS/METH_O function has no Clinic internal-doc signature. This is a +// display-only opt-in: module ownership and call dispatch remain unchanged. +#[must_use] +pub const fn signature_from_flags(args: &[SigArg]) -> &'static [SigArg] { + const EMPTY: &[SigArg] = &[SigArg::marker("$self")]; + const ONE: &[SigArg] = &[SigArg::marker("$self"), SigArg::marker("object")]; + let mut display = 0; + let mut binding = 0; + let mut i = 0; + while i < args.len() { + display += match args[i].params { + None => 1, + Some(params) => flags_positional_count(params), + }; + binding += match args[i].binding_params { + Some(params) => flags_positional_count(params), + None => panic!("signature_from_flags requires known argument binding"), + }; + assert!( + !args[i].force_unpack_keywords, + "signature_from_flags cannot unpack keywords" + ); + i += 1; + } + assert!( + display == binding && binding <= 1, + "signature_from_flags requires zero or one required positional-only argument" + ); + if binding == 0 { EMPTY } else { ONE } +} + +const fn flags_positional_count(params: &[Param]) -> usize { + let mut count = 0; + let mut i = 0; + while i < params.len() { + assert!( + params[i].default.is_none(), + "signature_from_flags cannot have optional arguments" + ); + count += match params[i].kind { + ParamKind::PositionalOnly => 1, + ParamKind::Flatten(Some(inner)) => flags_positional_count(inner), + _ => panic!("signature_from_flags requires known positional-only arguments"), + }; + i += 1; + } + count +} + +/// Check an explicit display signature against the actual argument binder. +/// +/// Requiredness, arity and keyword names must agree. Receiver markers are +/// checked by the item macro, not by this user-argument validator. A +/// positional-only optional argument may be displayed as keyword-capable only +/// when the binder also accepts arbitrary keywords (legacy wrappers such as +/// `_csv` forward these to their subsequent parser). Defaults and names of +/// positional-only arguments are presentation, not conversion instructions. +/// Unknown/custom binders are deliberately rejected. +/// +/// ```compile_fail +/// use rustpython_vm::function::{Param, SigArg, validate_text_signature}; +/// const _: () = validate_text_signature(&[SigArg::marker("$self")], &[ +/// Param::positional_only("$self"), Param::positional_only("extra"), +/// ]); +/// ``` +/// +/// An override cannot make a required parameter optional: +/// ```compile_fail +/// use rustpython_vm::function::{DefaultRepr, Param, ParamKind, SigArg, validate_text_signature}; +/// const _: () = validate_text_signature(&[SigArg::marker("sub")], &[Param { +/// name: "sub", kind: ParamKind::PositionalOnly, default: Some(DefaultRepr::None), +/// }]); +/// ``` +/// +/// Documenting a forwarded keyword requires a keyword-accepting binder: +/// ```compile_fail +/// use rustpython_vm::function::{DefaultRepr, Param, ParamKind, SigArg, validate_text_signature}; +/// const DIALECT: Param = Param { +/// name: "dialect", kind: ParamKind::PositionalOnly, +/// default: Some(DefaultRepr::Unrepresentable), +/// }; +/// const _: () = validate_text_signature(&[SigArg { +/// name: "options", params: Some(&[DIALECT]), binding_params: Some(&[DIALECT]), +/// force_unpack_keywords: false, +/// }], &[Param { kind: ParamKind::PositionalOrKeyword, ..DIALECT }]); +/// ``` +/// +/// Unknown binders cannot establish that a display override is valid: +/// ```compile_fail +/// use rustpython_vm::function::{Param, SigArg, validate_text_signature}; +/// const _: () = validate_text_signature(&[SigArg { +/// name: "custom", params: Some(&[Param::positional_only("value")]), +/// binding_params: None, force_unpack_keywords: false, +/// }], &[Param::positional_only("value")]); +/// ``` +pub const fn validate_text_signature(args: &[SigArg], display: &[Param]) { + validate_text_signature_impl(args, display, false); +} + +/// Validate bracket notation that leaves parameter kinds to the binding. +pub const fn validate_text_signature_without_slash(args: &[SigArg], display: &[Param]) { + validate_text_signature_impl(args, display, true); +} + +// A known unrestricted parser can deliberately publish a narrower display +// contract, as CPython does for type.__prepare__. Unknown binders cannot. +const fn override_params(arg: &SigArg) -> &[Param] { + let binding = match arg.binding_params { + Some(params) => params, + None => panic!("text_signature requires known binding metadata"), + }; + if is_bare_funcargs(binding) + && let Some(params) = arg.params + && !is_bare_funcargs(params) + { + return params; + } + binding +} + +const fn validate_text_signature_impl(args: &[SigArg], display: &[Param], omitted_slash: bool) { + let mut count = 0; + let mut var_keyword = false; + let mut i = 0; + while i < args.len() { + let params = override_params(&args[i]); + binding_override_count(params, &mut count, &mut var_keyword); + i += 1; + } + assert!( + count == display.len(), + "text_signature parameter count differs from binding" + ); + let mut index = 0; + i = 0; + while i < args.len() { + validate_override_params( + override_params(&args[i]), + args[i].name, + display, + &mut index, + var_keyword, + omitted_slash, + ); + i += 1; + } +} + +const fn binding_override_count(params: &[Param], count: &mut usize, keywords: &mut bool) { + let mut i = 0; + while i < params.len() { + match params[i].kind { + ParamKind::Flatten(Some(inner)) => binding_override_count(inner, count, keywords), + ParamKind::Flatten(None) => panic!("text_signature requires known binding metadata"), + ParamKind::VarKeyword => { + *count += 1; + *keywords = true; + } + _ => *count += 1, + } + i += 1; + } +} + +const fn validate_override_params( + params: &[Param], + fallback_name: &str, + display: &[Param], + index: &mut usize, + var_keyword: bool, + omitted_slash: bool, +) { + let mut i = 0; + while i < params.len() { + let binding = ¶ms[i]; + if let ParamKind::Flatten(Some(inner)) = binding.kind { + validate_override_params( + inner, + fallback_name, + display, + index, + var_keyword, + omitted_slash, + ); + } else { + let shown = &display[*index]; + let name = if binding.name.is_empty() { + fallback_name + } else { + binding.name + }; + assert!( + binding.default.is_some() == shown.default.is_some(), + "text_signature changes requiredness" + ); + let same_name = name_eq(name, shown.name.as_bytes()); + if omitted_slash { + assert!( + matches!( + binding.kind, + ParamKind::PositionalOnly | ParamKind::PositionalOrKeyword + ), + "bracket signature requires positional parameters" + ); + if matches!(binding.kind, ParamKind::PositionalOrKeyword) { + assert!(same_name, "text_signature changes keyword name"); + } + } else { + match (binding.kind, shown.kind) { + (ParamKind::PositionalOnly, ParamKind::PositionalOnly) => {} + (ParamKind::PositionalOnly, ParamKind::PositionalOrKeyword) => { + assert!( + var_keyword && binding.default.is_some() && same_name, + "text_signature keyword is not accepted by binding" + ); + } + (ParamKind::PositionalOrKeyword, ParamKind::PositionalOrKeyword) + | (ParamKind::KeywordOnly, ParamKind::KeywordOnly) => { + assert!(same_name, "text_signature changes keyword name"); + } + (ParamKind::VarKeyword, ParamKind::VarKeyword) + | (ParamKind::VarPositional, ParamKind::VarPositional) => {} + _ => panic!("text_signature parameter kind differs from binding"), + } + } + *index += 1; + } + i += 1; + } +} + +/// Select the override of one complete argument spec. Composition cannot +/// silently discard an override or apply it to only part of a callable. +#[must_use] +pub const fn argument_text_signature(signatures: &[Option<&'static str>]) -> Option<&'static str> { + let mut i = 0; + while i < signatures.len() { + if let Some(text) = signatures[i] { + assert!( + signatures.len() == 1, + "text_signature requires a single complete argument spec" + ); + return Some(text); + } + i += 1; + } + None +} + +/// Length of an override, adding the receiver supplied by the item macro. +#[must_use] +pub const fn text_signature_len(signature: &str, receiver: Option<&str>) -> usize { + signature.len() + + match receiver { + Some(receiver) => receiver.len() + if signature.len() == 2 { 3 } else { 2 }, + None => 0, + } +} + +/// Compose an already validated override with the selected documentation body. +#[must_use] +pub const fn text_signature_doc_bytes( + name: &str, + signature: &str, + receiver: Option<&str>, + doc: &str, +) -> [u8; N] { + let mut buf = [0; N]; + let n = put_str(&mut buf, 0, name); + let n = if let Some(receiver) = receiver { + let n = put_str(&mut buf, n, "("); + let n = put_str(&mut buf, n, receiver); + let n = put_str(&mut buf, n, if signature.len() == 2 { ", /" } else { ", " }); + let bytes = signature.as_bytes(); + let mut j = 1; + let mut n = n; + while j < bytes.len() { + buf[n] = bytes[j]; + n += 1; + j += 1; + } + n + } else { + put_str(&mut buf, n, signature) + }; + let n = put_str(&mut buf, n, "\n--\n\n"); + let n = put_str(&mut buf, n, doc); + assert!(n == N); + buf +} + +/// Calling-convention bits from each argument's binding metadata. +/// +/// Display signatures must not prevent a custom parser from receiving a call. +/// Native receivers travel outside Python arguments and are excluded from this +/// metadata. A keyword-capable parameter uses `FASTCALL | KEYWORDS`. +#[must_use] +pub(crate) const fn native_call_flags(args: &[SigArg]) -> super::PyMethodFlags { + let mut has_keywords = false; + let mut variable = false; + let mut fixed = 0usize; + let mut i = 0; + while i < args.len() { + has_keywords |= args[i].force_unpack_keywords; + match args[i].binding_params { + Some(params) => count_params(params, &mut has_keywords, &mut variable, &mut fixed), + None => { + has_keywords = true; + variable = true; + } + } + i += 1; + } + if has_keywords { + super::PyMethodFlags::FASTCALL.union(super::PyMethodFlags::KEYWORDS) + } else if variable { + super::PyMethodFlags::FASTCALL + } else { + match fixed { + 0 => super::PyMethodFlags::NOARGS, + 1 => super::PyMethodFlags::O, + _ => super::PyMethodFlags::FASTCALL, + } + } +} + +const fn count_params( + params: &[Param], + has_keywords: &mut bool, + variable: &mut bool, + fixed: &mut usize, +) { + let mut i = 0; + while i < params.len() { + count_param(¶ms[i], has_keywords, variable, fixed); + i += 1; + } +} + +const fn count_param( + param: &Param, + has_keywords: &mut bool, + variable: &mut bool, + fixed: &mut usize, +) { + match param.kind { + ParamKind::PositionalOrKeyword => { + *has_keywords = true; + if param.default.is_some() { + *variable = true; + } else { + *fixed += 1; + } + } + ParamKind::KeywordOnly | ParamKind::VarKeyword => *has_keywords = true, + ParamKind::VarPositional => *variable = true, + ParamKind::PositionalOnly => { + if param.default.is_some() { + *variable = true; + } else { + *fixed += 1; + } + } + ParamKind::Flatten(Some(inner)) => count_params(inner, has_keywords, variable, fixed), + ParamKind::Flatten(None) => { + *has_keywords = true; + *variable = true; } } } @@ -163,21 +554,45 @@ const fn is_bare_funcargs(params: &[Param]) -> bool { const fn params_representable(params: &[Param]) -> bool { let mut i = 0; while i < params.len() { - if let Some(DefaultRepr::Unrepresentable) = params[i].default { + if let Some(DefaultRepr::Unknown) = params[i].default { return false; } - if let ParamKind::Flatten(Some(inner)) = params[i].kind - && !params_representable(inner) - { - return false; + match params[i].kind { + ParamKind::Flatten(Some(inner)) if !params_representable(inner) => return false, + ParamKind::Flatten(_) => {} + _ if params[i].name.is_empty() => return false, + _ => {} + } + i += 1; + } + true +} + +/// True when every parameter is positional-only or `*args`. +#[must_use] +pub(crate) const fn params_take_no_keywords(params: &[Param]) -> bool { + let mut i = 0; + while i < params.len() { + match params[i].kind { + ParamKind::PositionalOnly | ParamKind::VarPositional => {} + ParamKind::Flatten(Some(inner)) => { + if !params_take_no_keywords(inner) { + return false; + } + } + ParamKind::Flatten(None) + | ParamKind::PositionalOrKeyword + | ParamKind::KeywordOnly + | ParamKind::VarKeyword => return false, } i += 1; } true } -/// `None`, a bare `FuncArgs`, and a default of `` contribute -/// no signature. `Some(&[])` is `()`. +/// `None`, a bare `FuncArgs`, and an unknown default contribute no signature. +/// A declared omitted value is rendered as ``, as in Clinic. +/// `Some(&[])` is `()`. #[must_use] pub const fn real_signature(params: Option<&[Param]>) -> Option<&[Param]> { match params { @@ -237,25 +652,47 @@ pub const fn internal_doc_bytes(name: &str, args: &[SigArg], doc buf } +#[derive(Clone, Copy)] struct St { n: usize, emitted: bool, po_left: usize, var_pos_seen: bool, + var_kw_seen: bool, star_emitted: bool, + // Layout is calculated only while constructing the static internal doc. + indent: usize, + column: usize, + tokens: usize, + total_tokens: usize, } const fn write_signature_prefix(buf: &mut [u8], name: &str, args: &[SigArg]) -> usize { let mut n = put_str(buf, 0, name); n = put_byte(buf, n, b'('); + let indent = char_len(name) + 1; + let initial = St { + n, + emitted: false, + po_left: count_po_args(args), + var_pos_seen: false, + var_kw_seen: false, + star_emitted: false, + indent, + column: indent, + tokens: 0, + total_tokens: usize::MAX, + }; + // Clinic counts a token's trailing comma when deciding where to wrap. + // The renderer runs twice at compile time. The counting pass includes synthetic + // '/' and '*' tokens, without a separate traversal that could disagree with the + // actual renderer. + let total_tokens = write_args(&mut [], initial, args).tokens; let st = write_args( buf, St { - n, - emitted: false, - po_left: count_po_args(args), - var_pos_seen: false, - star_emitted: false, + total_tokens, + ..initial }, args, ); @@ -314,19 +751,60 @@ const fn count_po_args(args: &[SigArg]) -> usize { n } -const fn emit_sep(buf: &mut [u8], st: St) -> St { - if st.emitted { - St { - n: put_str(buf, st.n, ", "), - ..st +const fn char_len(text: &str) -> usize { + let bytes = text.as_bytes(); + let mut count = 0; + let mut i = 0; + while i < bytes.len() { + if bytes[i] & 0xc0 != 0x80 { + count += 1; } + i += 1; + } + count +} + +const fn default_char_len(default: DefaultRepr) -> usize { + let bytes = put_default(&mut [], 0, default); + // Non-ASCII text is emitted verbatim for str/raw defaults; bytes defaults + // instead escape every non-ASCII byte. Count characters as Clinic's len(). + match default { + DefaultRepr::Str(text) | DefaultRepr::Raw(text) => bytes - text.len() + char_len(text), + _ => bytes, + } +} + +const fn emit_sep(buf: &mut [u8], mut st: St, token_chars: usize) -> St { + // Tools/clinic/libclinic/dsl_parser.py:add_parameter: wrap at >=72, + // align with the first parameter, and never split a parameter/default. + let trailing_comma = if st.tokens + 1 < st.total_tokens { + 1 } else { - st + 0 + }; + if st.emitted { + st.n = put_byte(buf, st.n, b','); + st.column += 1; + if st.column + 1 + token_chars + trailing_comma >= 72 { + st.n = put_byte(buf, st.n, b'\n'); + let mut i = 0; + while i < st.indent { + st.n = put_byte(buf, st.n, b' '); + i += 1; + } + st.column = st.indent; + } else { + st.n = put_byte(buf, st.n, b' '); + st.column += 1; + } } + st.column += token_chars; + st.tokens += 1; + st } const fn emit_text(buf: &mut [u8], st: St, text: &str) -> St { - let st = emit_sep(buf, st); + let st = emit_sep(buf, st, char_len(text)); St { n: put_str(buf, st.n, text), emitted: true, @@ -341,7 +819,13 @@ const fn emit_named( name: &str, default: Option, ) -> St { - let st = emit_sep(buf, st); + let token_chars = char_len(prefix) + + char_len(name) + + match default { + Some(value) => 1 + default_char_len(value), + None => 0, + }; + let st = emit_sep(buf, st, token_chars); let n = put_str(buf, st.n, prefix); let n = put_str(buf, n, name); let n = if let Some(default) = default { @@ -426,16 +910,12 @@ const fn put_exp(buf: &mut [u8], i: usize, exp: i32) -> usize { (put_byte(buf, i, b'+'), exp) }; let exp = exp as u32; - if exp >= 10 { - let i = put_byte(buf, i, b'0' + (exp / 10) as u8); - put_byte(buf, i, b'0' + (exp % 10) as u8) - } else { - let i = put_byte(buf, i, b'0'); - put_byte(buf, i, b'0' + exp as u8) - } + let i = if exp < 10 { put_byte(buf, i, b'0') } else { i }; + put_u128(buf, i, exp as u128) } -/// Shortest round-trip decimal, matching `float.__repr__` for finite values. +/// Decimal rendering using up to 17 significant digits. +// This normalization-based formatter is not a shortest-round-trip algorithm. const fn put_f64(buf: &mut [u8], i: usize, v: f64) -> usize { if v.is_nan() { return put_str(buf, i, "nan"); @@ -549,7 +1029,7 @@ const fn put_default(buf: &mut [u8], i: usize, default: DefaultRepr) -> usize { put_quoted(buf, i, b, false) } DefaultRepr::Raw(s) => put_str(buf, i, s), - DefaultRepr::Unrepresentable => put_str(buf, i, ""), + DefaultRepr::Unrepresentable | DefaultRepr::Unknown => put_str(buf, i, ""), } } @@ -575,6 +1055,12 @@ const fn write_one(buf: &mut [u8], mut st: St, param: Param, fallback: &str) -> st = emit_named(buf, st, "", name, param.default); st.po_left -= 1; if st.po_left == 0 { + // Python rejects `/` after `*` or `**`. The Rust arguments put a + // keyword or variadic one before a positional one; reorder them. + assert!( + !st.star_emitted && !st.var_pos_seen && !st.var_kw_seen, + "positional-only parameter after `*` or `**`: reorder the Rust arguments" + ); st = emit_text(buf, st, "/"); } st @@ -591,7 +1077,10 @@ const fn write_one(buf: &mut [u8], mut st: St, param: Param, fallback: &str) -> st.var_pos_seen = true; emit_named(buf, st, "*", name, param.default) } - ParamKind::VarKeyword => emit_named(buf, st, "**", name, param.default), + ParamKind::VarKeyword => { + st.var_kw_seen = true; + emit_named(buf, st, "**", name, param.default) + } } } @@ -620,7 +1109,8 @@ const fn write_args(buf: &mut [u8], mut st: St, args: &[SigArg]) -> St { #[cfg(test)] mod tests { - use super::{DefaultRepr, Param, ParamKind, St, write_one}; + use super::{DefaultRepr, Param, ParamKind, SigArg, St, native_call_flags, put_exp, write_one}; + use crate::function::PyMethodFlags; fn rendered(default: DefaultRepr) -> String { let mut buf = [0u8; 64]; @@ -631,7 +1121,12 @@ mod tests { emitted: false, po_left: 0, var_pos_seen: false, + var_kw_seen: false, star_emitted: true, + indent: 0, + column: 0, + tokens: 0, + total_tokens: 1, }, Param { name: "x", @@ -644,6 +1139,215 @@ mod tests { text.split_once('=').unwrap().1.to_owned() } + fn layout(name: &str, params: &'static [Param]) -> String { + let args = [SigArg { + name: "options", + params: Some(params), + binding_params: Some(params), + force_unpack_keywords: false, + }]; + let mut buf = vec![0; super::signature_prefix_len(name, &args)]; + let written = super::write_signature_prefix(&mut buf, name, &args); + assert_eq!(written, buf.len()); + String::from_utf8(buf).unwrap() + } + + #[test] + fn clinic_wraps_at_72_including_a_tokens_trailing_comma() { + const A65: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + const A66: &str = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; + assert_eq!( + layout( + "f", + const { + &[ + Param::positional_or_keyword(A65), + Param::positional_or_keyword("bb"), + ] + } + ), + format!("f({A65}, bb)\n--\n\n") + ); + assert_eq!( + layout( + "f", + const { + &[ + Param::positional_or_keyword(A66), + Param::positional_or_keyword("bb"), + ] + } + ), + format!("f({A66},\n bb)\n--\n\n") + ); + // The comma after bb moves the candidate from 71 to 72 columns. + assert_eq!( + layout( + "f", + const { + &[ + Param::positional_or_keyword(A65), + Param::positional_or_keyword("bb"), + Param::positional_or_keyword("c"), + ] + } + ), + format!("f({A65},\n bb, c)\n--\n\n") + ); + // The first parameter is never wrapped, even if already over width. + assert_eq!( + layout( + "long_name", + const { + &[ + Param::positional_or_keyword(A66), + Param::positional_or_keyword("bb"), + ] + } + ), + format!("long_name({A66},\n bb)\n--\n\n") + ); + } + + #[test] + fn clinic_layout_preserves_default_contents_and_counts_unicode_characters() { + // cspell:disable-next-line + const UNICODE: &str = "ééééééééééééééééééééééééééééééééé"; + const ASCII: &str = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; + assert_eq!( + layout( + "f", + const { + &[ + Param::positional_or_keyword(UNICODE), + Param::positional_or_keyword(ASCII), + ] + } + ), + format!("f({UNICODE}, {ASCII})\n--\n\n") + ); + const TEXT: &str = "é, space, \"quoted\", \\slash"; + const DEFAULT: Param = Param { + name: "text", + kind: ParamKind::PositionalOrKeyword, + default: Some(DefaultRepr::Str(TEXT)), + }; + assert_eq!( + layout( + "f", + const { + &[ + Param::positional_or_keyword( + "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + ), + DEFAULT, + ] + } + ), + "f(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,\n text='é, space, \"quoted\", \\\\slash')\n--\n\n" + ); + assert_eq!(super::default_char_len(DefaultRepr::Str("éé")), 4); + assert_eq!(super::default_char_len(DefaultRepr::Raw("('é, ', 1)")), 11); + } + + #[test] + fn clinic_layout_treats_slash_as_a_separate_token() { + const ARGS: &[SigArg] = &[ + SigArg::marker("$module"), + SigArg::marker("arraytype"), + SigArg::marker("typecode"), + SigArg::marker("mformat_code"), + SigArg::marker("items"), + ]; + const N: usize = super::signature_prefix_len("_array_reconstructor", ARGS); + const TEXT: [u8; N] = super::signature_prefix_bytes::("_array_reconstructor", ARGS); + assert_eq!( + core::str::from_utf8(&TEXT).unwrap(), + "_array_reconstructor($module, arraytype, typecode, mformat_code, items,\n /)\n--\n\n" + ); + } + + #[test] + fn signatures_from_flags_use_noargs_and_o_fallbacks() { + const NOARGS: &[SigArg] = super::signature_from_flags(&[]); + const NOARGS_N: usize = super::signature_prefix_len("sample", NOARGS); + const NOARGS_TEXT: [u8; NOARGS_N] = + super::signature_prefix_bytes::("sample", NOARGS); + const ONE: &[SigArg] = super::signature_from_flags(&[SigArg::marker("custom_name")]); + const ONE_N: usize = super::signature_prefix_len("sample", ONE); + const ONE_TEXT: [u8; ONE_N] = super::signature_prefix_bytes::("sample", ONE); + assert_eq!( + core::str::from_utf8(&NOARGS_TEXT).unwrap(), + "sample($self, /)\n--\n\n" + ); + assert_eq!( + core::str::from_utf8(&ONE_TEXT).unwrap(), + "sample($self, object, /)\n--\n\n" + ); + } + + #[test] + fn signature_from_flags_rejects_other_call_shapes() { + const KEYWORD: &[Param] = &[Param::positional_or_keyword("value")]; + const OPTIONAL: &[Param] = &[Param { + name: "value", + kind: ParamKind::PositionalOnly, + default: Some(DefaultRepr::None), + }]; + const VARARGS: &[Param] = &[Param::var_positional("args")]; + const UNKNOWN: &[Param] = &[Param::flatten(None)]; + const POSITIONAL: &[Param] = &[Param::positional_only("value")]; + for params in [KEYWORD, OPTIONAL, VARARGS, UNKNOWN] { + let args = [SigArg { + name: "arg", + params: Some(params), + binding_params: Some(params), + force_unpack_keywords: false, + }]; + assert!(std::panic::catch_unwind(|| super::signature_from_flags(&args)).is_err()); + } + assert!( + std::panic::catch_unwind(|| super::signature_from_flags(&[ + SigArg::marker("one"), + SigArg::marker("two") + ])) + .is_err() + ); + let custom = SigArg { + name: "arg", + params: None, + binding_params: None, + force_unpack_keywords: false, + }; + assert!(std::panic::catch_unwind(|| super::signature_from_flags(&[custom])).is_err()); + let mismatch = SigArg { + name: "arg", + params: Some(&[]), + binding_params: Some(POSITIONAL), + force_unpack_keywords: false, + }; + assert!(std::panic::catch_unwind(|| super::signature_from_flags(&[mismatch])).is_err()); + } + + #[test] + fn exponent_text_keeps_all_digits() { + for (exp, expected) in [ + (0, "e+00"), + (9, "e+09"), + (-9, "e-09"), + (10, "e+10"), + (-99, "e-99"), + (100, "e+100"), + (308, "e+308"), + (-324, "e-324"), + ] { + let mut buf = [0u8; 16]; + let len = put_exp(&mut buf, 0, exp); + assert_eq!(core::str::from_utf8(&buf[..len]).unwrap(), expected); + assert_eq!(put_exp(&mut [], 0, exp), len); + } + } + #[test] fn default_repr_text() { assert_eq!(rendered(DefaultRepr::None), "None"); @@ -661,5 +1365,342 @@ mod tests { assert_eq!(rendered(DefaultRepr::Bytes(b"a'b")), r"b'a\'b'"); assert_eq!(rendered(DefaultRepr::Raw("sys.maxsize")), "sys.maxsize"); assert_eq!(rendered(DefaultRepr::Unrepresentable), ""); + assert_eq!(rendered(DefaultRepr::Unknown), ""); + } + + #[test] + fn explicit_signature_preserves_known_unrestricted_binding() { + const DISPLAY: &[Param] = &[Param::positional_only("name"), Param::var_keyword("kwds")]; + const RAW: &[Param] = &[Param::var_positional("args"), Param::var_keyword("kwargs")]; + super::validate_text_signature( + &[SigArg { + name: "", + params: Some(DISPLAY), + binding_params: Some(RAW), + force_unpack_keywords: false, + }], + DISPLAY, + ); + } + + #[test] + #[should_panic(expected = "text_signature changes keyword name")] + fn bracket_override_cannot_rename_keyword() { + const ACTUAL: &[Param] = &[Param::positional_or_keyword("actual")]; + super::validate_text_signature_without_slash( + &[SigArg { + name: "", + params: Some(ACTUAL), + binding_params: Some(ACTUAL), + force_unpack_keywords: false, + }], + &[Param::positional_or_keyword("wrong")], + ); + } + + #[test] + fn class_signature_distinguishes_omission_from_unknown_default() { + const OMITTED: &[Param] = &[Param::keyword_only( + "name", + Some(DefaultRepr::Unrepresentable), + )]; + const UNKNOWN: &[Param] = &[Param::keyword_only("name", Some(DefaultRepr::Unknown))]; + assert!(super::real_signature(Some(OMITTED)).is_some()); + assert!(super::real_signature(Some(UNKNOWN)).is_none()); + assert!(super::real_signature(Some(&[Param::flatten(Some(OMITTED))])).is_some()); + assert!(super::real_signature(Some(&[Param::flatten(Some(UNKNOWN))])).is_none()); + const UNNAMED: &[Param] = &[Param::keyword_only("", Some(DefaultRepr::Unrepresentable))]; + assert!(super::real_signature(Some(UNNAMED)).is_none()); + assert!(super::real_signature(Some(&[Param::flatten(Some(UNNAMED))])).is_none()); + } + + #[test] + fn native_call_flags_from_params() { + const fn arg(params: Option<&'static [Param]>) -> SigArg { + SigArg { + name: "", + params, + binding_params: match params { + Some(params) => Some(params), + None => Some(super::SCALAR_PARAMS), + }, + force_unpack_keywords: false, + } + } + let keywords = PyMethodFlags::FASTCALL.union(PyMethodFlags::KEYWORDS); + assert_eq!(native_call_flags(&[]), PyMethodFlags::NOARGS); + assert_eq!(native_call_flags(&[arg(None)]), PyMethodFlags::O); + assert_eq!( + native_call_flags(&[arg(None), arg(None)]), + PyMethodFlags::FASTCALL + ); + + const OPTIONAL: &[Param] = &[Param { + name: "", + kind: ParamKind::PositionalOnly, + default: Some(DefaultRepr::Unrepresentable), + }]; + assert_eq!( + native_call_flags(&[arg(Some(OPTIONAL))]), + PyMethodFlags::FASTCALL + ); + + const KW: &[Param] = &[Param::positional_or_keyword("exp")]; + assert_eq!(native_call_flags(&[arg(Some(KW))]), keywords); + + const FUNCARGS: &[Param] = &[Param::var_positional("args"), Param::var_keyword("kwargs")]; + assert_eq!(native_call_flags(&[arg(Some(FUNCARGS))]), keywords); + + const POSARGS: &[Param] = &[Param::var_positional("args")]; + assert_eq!( + native_call_flags(&[arg(Some(POSARGS))]), + PyMethodFlags::FASTCALL + ); + + const INNER: &[Param] = &[Param::keyword_only( + "reverse", + Some(DefaultRepr::Bool(false)), + )]; + const FLAT: &[Param] = &[Param::flatten(Some(INNER))]; + assert_eq!(native_call_flags(&[arg(Some(FLAT))]), keywords); + } + + #[test] + fn unpack_keywords_keeps_the_positional_signature_and_keyword_dispatch() { + type Wrapped = crate::function::UnpackKeywords; + const ARGS: &[SigArg] = &[ + SigArg::marker("$self"), + SigArg::from_arg::("callback"), + ]; + const FLAGS: PyMethodFlags = native_call_flags(&[SigArg::from_arg::("callback")]); + assert_eq!( + FLAGS, + PyMethodFlags::FASTCALL.union(PyMethodFlags::KEYWORDS) + ); + const N: usize = super::signature_prefix_len("example", ARGS); + const TEXT: [u8; N] = super::signature_prefix_bytes::("example", ARGS); + assert_eq!(&TEXT, b"example($self, callback, /)\n--\n\n"); + } + + #[test] + fn dispatch_uses_binding_overrides_without_changing_display_signatures() { + const ARGS: &[SigArg] = &[SigArg { + name: "ignored", + params: Some(&[]), + binding_params: Some(&[Param::var_positional("args"), Param::var_keyword("kwargs")]), + force_unpack_keywords: false, + }]; + let keywords = PyMethodFlags::FASTCALL.union(PyMethodFlags::KEYWORDS); + assert_eq!(native_call_flags(ARGS), keywords); + const N: usize = super::signature_prefix_len("example", ARGS); + const TEXT: [u8; N] = super::signature_prefix_bytes::("example", ARGS); + assert_eq!(&TEXT, b"example()\n--\n\n"); + } + + #[test] + fn explicit_custom_parsers_receive_keywords_even_when_nested() { + const CUSTOM: SigArg = SigArg { + name: "custom", + params: Some(&[Param::positional_only("display")]), + binding_params: None, + force_unpack_keywords: false, + }; + const NESTED: SigArg = SigArg { + name: "nested", + params: Some(&[]), + binding_params: Some(&[Param::flatten(None)]), + force_unpack_keywords: false, + }; + let keywords = PyMethodFlags::FASTCALL.union(PyMethodFlags::KEYWORDS); + assert_eq!(native_call_flags(&[CUSTOM]), keywords); + assert_eq!(native_call_flags(&[NESTED]), keywords); + } + const OPTIONAL_START: Param = Param { + name: "start", + kind: ParamKind::PositionalOnly, + default: Some(DefaultRepr::None), + }; + const OPTIONAL_END: Param = Param { + name: "end", + ..OPTIONAL_START + }; + const SEARCH_BINDING: &[SigArg] = &[SigArg { + name: "options", + params: Some(&[]), + binding_params: Some(&[ + Param::positional_only("affix"), + Param::flatten(Some(&[OPTIONAL_START, OPTIONAL_END])), + ]), + force_unpack_keywords: false, + }]; + const SEARCH_DISPLAY: &[Param] = &[ + Param::positional_only("prefix"), + OPTIONAL_START, + OPTIONAL_END, + ]; + const DIALECT: Param = Param { + name: "dialect", + default: Some(DefaultRepr::Unrepresentable), + ..OPTIONAL_START + }; + const CSV_BINDING: &[SigArg] = &[ + SigArg::marker("iterable"), + SigArg { + name: "options", + params: Some(&[]), + binding_params: Some(&[ + DIALECT, + Param::flatten(Some(&[Param::var_keyword("kwargs")])), + ]), + force_unpack_keywords: false, + }, + ]; + const CSV_DISPLAY: &[Param] = &[ + Param::positional_only("iterable"), + Param { + kind: ParamKind::PositionalOrKeyword, + default: Some(DefaultRepr::Str("excel")), + ..DIALECT + }, + Param::var_keyword("fmtparams"), + ]; + const _: () = super::validate_text_signature(SEARCH_BINDING, SEARCH_DISPLAY); + const _: () = super::validate_text_signature(CSV_BINDING, CSV_DISPLAY); + + #[test] + fn argument_spec_overrides_are_shared_without_changing_binding() { + use crate::function::{ArgsMetadata, FromArgs}; + type Prefix = crate::anystr::StartsEndsWithArgs; + type Suffix = crate::anystr::EndsWithArgs; + assert_eq!( + ::TEXT_SIGNATURE, + Some("(prefix[, start[, end]], /)") + ); + assert_eq!( + ::TEXT_SIGNATURE, + Some("(suffix[, start[, end]], /)") + ); + assert_eq!(Prefix::arity(), Suffix::arity()); + assert_eq!( + native_call_flags(&[SigArg::from_arg::("")]), + native_call_flags(&[SigArg::from_arg::("")]) + ); + #[derive(crate::FromArgs)] + #[from_args(borrowed, text_signature = "(value, /)")] + struct Borrowed<'a> { + #[pyarg(positional)] + value: &'a crate::PyObject, + } + assert_eq!( + as ArgsMetadata>::TEXT_SIGNATURE, + Some("(value, /)") + ); + // Keep the fixture's payload observable without constructing an interpreter. + fn value(args: Borrowed<'_>) -> &crate::PyObject { + args.value + } + let _ = value; + } + + #[test] + fn shared_override_composition_adds_only_the_item_receiver() { + const TEXT: &str = "(prefix[, start[, end]], /)"; + const N: usize = "startswith".len() + super::text_signature_len(TEXT, Some("$self")) + 5; + const DOC: [u8; N] = + super::text_signature_doc_bytes::("startswith", TEXT, Some("$self"), ""); + assert_eq!( + &DOC, + b"startswith($self, prefix[, start[, end]], /)\n--\n\n" + ); + const EMPTY_LEN: usize = 1 + super::text_signature_len("()", Some("$module")) + 5; + const EMPTY: [u8; EMPTY_LEN] = + super::text_signature_doc_bytes::("f", "()", Some("$module"), ""); + assert_eq!(&EMPTY, b"f($module, /)\n--\n\n"); + assert_eq!(super::argument_text_signature(&[Some(TEXT)]), Some(TEXT)); + assert_eq!(super::argument_text_signature(&[None, None]), None); + assert!( + std::panic::catch_unwind(|| super::argument_text_signature(&[None, Some(TEXT)])) + .is_err() + ); + assert!( + std::panic::catch_unwind(|| super::argument_text_signature(&[Some(TEXT), None])) + .is_err() + ); + } + + #[test] + fn text_signature_overrides_preserve_binding_and_doc_body() { + assert_eq!(native_call_flags(SEARCH_BINDING), PyMethodFlags::FASTCALL); + assert_eq!( + native_call_flags(CSV_BINDING), + PyMethodFlags::FASTCALL.union(PyMethodFlags::KEYWORDS) + ); + const TEXT: &str = "($self, prefix[, start[, end]], /)"; + const BODY: &str = "Return whether the string starts with prefix.\n"; + const N: usize = "startswith".len() + TEXT.len() + 5 + BODY.len(); + const DOC: [u8; N] = super::text_signature_doc_bytes::("startswith", TEXT, None, BODY); + assert_eq!( + core::str::from_utf8(&DOC).unwrap(), + format!("startswith{TEXT}\n--\n\n{BODY}") + ); + const PREFIX: [u8; N - BODY.len()] = + super::text_signature_doc_bytes::<{ N - BODY.len() }>("startswith", TEXT, None, ""); + assert_eq!( + core::str::from_utf8(&PREFIX).unwrap(), + format!("startswith{TEXT}\n--\n\n") + ); + } + + #[test] + fn text_signature_overrides_reject_incompatible_binding() { + let rejected = |args: &[SigArg], display: &[Param]| { + assert!( + std::panic::catch_unwind(|| super::validate_text_signature(args, display)).is_err() + ); + }; + rejected(SEARCH_BINDING, &SEARCH_DISPLAY[..2]); + let mut display = SEARCH_DISPLAY.to_vec(); + display.push(Param::positional_only("extra")); + rejected(SEARCH_BINDING, &display); + display.pop(); + display[0].default = Some(DefaultRepr::None); + rejected(SEARCH_BINDING, &display); + display[0] = SEARCH_DISPLAY[0]; + display[1].default = None; + rejected(SEARCH_BINDING, &display); + display[1] = Param { + kind: ParamKind::PositionalOrKeyword, + ..OPTIONAL_START + }; + rejected(SEARCH_BINDING, &display); + let mut display = CSV_DISPLAY.to_vec(); + display[1].name = "wrong_keyword"; + rejected(CSV_BINDING, &display); + display[1] = CSV_DISPLAY[1]; + display[2] = Param::var_positional("args"); + rejected(CSV_BINDING, &display); + const NAMED: SigArg = SigArg { + name: "options", + params: Some(&[]), + binding_params: Some(&[Param::positional_or_keyword("named")]), + force_unpack_keywords: false, + }; + rejected(&[NAMED], &[Param::positional_or_keyword("renamed")]); + rejected(&[NAMED], &[Param::positional_only("named")]); + rejected( + &[SigArg { + binding_params: None, + ..NAMED + }], + &[Param::positional_or_keyword("named")], + ); + const UNKNOWN: &[Param] = &[Param::flatten(None)]; + rejected( + &[SigArg { + binding_params: Some(UNKNOWN), + ..NAMED + }], + &[Param::positional_or_keyword("named")], + ); } } diff --git a/crates/vm/src/gc_state.rs b/crates/vm/src/gc_state.rs index 774f2ff39ba..6608014d808 100644 --- a/crates/vm/src/gc_state.rs +++ b/crates/vm/src/gc_state.rs @@ -5,9 +5,11 @@ use crate::common::linked_list::LinkedList; use crate::common::lock::{PyMutex, PyRwLock}; use crate::object::{GC_NO_OWNER, GC_PERMANENT, GC_REACHABLE, GC_UNTRACKED, GcLink, GcOwner}; +#[cfg(feature = "threading")] +use crate::vm::stop_the_world::StopTheWorldGroup; use crate::{AsObject, PyObject, PyObjectRef}; use core::ptr::NonNull; -use core::sync::atomic::{AtomicBool, AtomicU16, AtomicU32, AtomicUsize, Ordering}; +use core::sync::atomic::{AtomicBool, AtomicI32, AtomicU16, AtomicU32, AtomicUsize, Ordering}; fn elapsed_secs( #[cfg(target_arch = "wasm32")] _start: (), @@ -62,16 +64,16 @@ pub struct GcStats { /// what its own collections have done. pub struct GcGeneration { /// Threshold for triggering collection - threshold: AtomicU32, + threshold: AtomicI32, /// Collection statistics stats: PyMutex, } impl GcGeneration { #[must_use] - pub const fn new(threshold: u32) -> Self { + pub const fn new(threshold: i32) -> Self { Self { - threshold: AtomicU32::new(threshold), + threshold: AtomicI32::new(threshold), stats: PyMutex::new(GcStats { collections: 0, collected: 0, @@ -84,11 +86,11 @@ impl GcGeneration { /// Relaxed: this is policy read once per allocation, and a collection /// racing `gc.set_threshold()` may use either value. - pub fn threshold(&self) -> u32 { + pub fn threshold(&self) -> i32 { self.threshold.load(Ordering::Relaxed) } - pub fn set_threshold(&self, value: u32) { + pub fn set_threshold(&self, value: i32) { self.threshold.store(value, Ordering::Relaxed); } @@ -191,103 +193,6 @@ type GcBuildHasher = core::hash::BuildHasherDefault; type GcSet = std::collections::HashSet; type GcMap = std::collections::HashMap; -/// RAII barrier that parks every other thread for the pointer-reading phases -/// of a collection and lets them run again before finalizers execute. -/// -/// Reference subtraction, the reachability walk and the strong-reference -/// snapshot dereference the interpreter state of every tracked object, -/// including the `localsplus` of frames that other threads are actively -/// executing. Those writes carry no synchronization, so the reads are only -/// well-defined while all other threads are parked at a safepoint. Restarting -/// happens explicitly once the snapshot has pinned every object; `Drop` is a -/// backstop that also restarts on the early-return paths. -/// -/// A collection acts on one interpreter's objects, but its candidates include -/// the ones no interpreter owns, which every interpreter can reference and so -/// incref. Reading a refcount that another interpreter is changing is what -/// makes an object look unreachable when it is not, so every live interpreter -/// is stopped, not just the collecting one. Stopping in `runtime` id order -/// keeps exclusion acquisition ordered; the `collecting` mutex additionally -/// serializes collections process-wide, so no second collector can take these -/// exclusions in another order. -#[cfg(feature = "threading")] -struct CollectStopTheWorld { - /// Stopped interpreter states, in stop order. Held as strong references so - /// an interpreter cannot be dropped between stop and restart, and kept past - /// the restart so that releasing the last one — which frees that - /// interpreter's objects, and so removes them from these lists — happens - /// after the collection has let go of the generation locks. - stopped: Vec>, - /// Keeps interpreters from registering between the snapshot below and the - /// restart. One registered in that window would be missing from `stopped`, - /// so its bootstrap would keep running — and mutating the shared generation - /// lists — while this collection reads them. - admission: Option>, - restarted: bool, -} - -#[cfg(feature = "threading")] -impl CollectStopTheWorld { - /// Request stop-the-world on every live interpreter when the current thread - /// has an attached VM. Falls back to no barrier when no VM is attached (the - /// tracked-object reads then run without other threads only if the caller - /// guarantees it). - fn new() -> Self { - // No attached VM means no interpreter is running Python on this thread; - // keep the historical no-barrier fallback. - if !crate::vm::thread::current_vm_is_set() { - return Self { - stopped: Vec::new(), - admission: None, - restarted: true, - }; - } - - // Accumulate into a live `Self` rather than a bare Vec: if a later - // `stop_the_world` unwinds, dropping this guard restarts the - // interpreters already stopped, instead of leaving their threads parked - // and their exclusion held forever. - let mut guard = Self { - stopped: Vec::new(), - admission: Some(crate::vm::runtime::lock_admission_for_stop()), - restarted: false, - }; - for state in crate::vm::runtime::live_interpreter_states() { - state.stop_the_world.stop_the_world(&state); - guard.stopped.push(state); - } - guard - } - - /// Restart the world. Idempotent. - fn restart(&mut self) { - if self.restarted { - return; - } - self.restarted = true; - // Reverse of the stop order. The references stay until this guard is - // dropped; see the field comment. - for state in self.stopped.iter().rev() { - state.stop_the_world.start_the_world(state); - } - // Nothing is parked any more, so registration may resume. - self.admission = None; - } - - /// Whether this collection actually stopped the world. - #[cfg(all(unix, debug_assertions))] - fn is_stopped(&self) -> bool { - !self.stopped.is_empty() - } -} - -#[cfg(feature = "threading")] -impl Drop for CollectStopTheWorld { - fn drop(&mut self) { - self.restart(); - } -} - /// The process-wide object lists every interpreter's collections walk. /// /// Interpreter-owned policy and results live in [`GcInterpreterState`]; what is @@ -477,7 +382,6 @@ impl GcState { let mut list = list_lock.write(); // Re-check generation under lock (may have changed due to promotion) if obj_ref.gc_generation() != obj_gen { - drop(list); continue; // Retry with the updated generation } if unsafe { list.remove(obj) }.is_some() { @@ -504,6 +408,15 @@ impl GcState { /// If generation is None, returns all such objects. /// If generation is Some(n), returns those in generation n only. pub fn get_objects(&self, generation: Option, owner: GcOwner) -> Vec { + self.get_objects_impl(generation, owner, true) + } + + fn get_objects_impl( + &self, + generation: Option, + owner: GcOwner, + include_permanent: bool, + ) -> Vec { fn collect_from_list( list: &LinkedList, owner: GcOwner, @@ -520,7 +433,9 @@ impl GcState { for gen_list in &self.generation_lists { result.extend(collect_from_list(&gen_list.read(), owner)); } - result.extend(collect_from_list(&self.permanent_list.read(), owner)); + if include_permanent { + result.extend(collect_from_list(&self.permanent_list.read(), owner)); + } result } Some(g) if (0..=2).contains(&g) => { @@ -542,7 +457,7 @@ impl GcState { // Check gen0 threshold let count0 = self.counts[0].load(Ordering::Relaxed) as u32; let threshold0 = gc.generations[0].threshold(); - if threshold0 > 0 && count0 >= threshold0 { + if threshold0 != 0 && i64::from(count0) > i64::from(threshold0) { #[cfg(feature = "threading")] { // Defer to the next bytecode safepoint. Collecting here would @@ -570,6 +485,17 @@ impl GcState { gc: &GcInterpreterState, generation: usize, force: bool, + ) -> CollectResult { + self.collect_with_callbacks(gc, generation, force, || {}, |_| {}) + } + + fn collect_with_callbacks( + &self, + gc: &GcInterpreterState, + generation: usize, + force: bool, + before: impl FnOnce(), + after: impl FnOnce(&CollectResult), ) -> CollectResult { if !force && !gc.is_enabled() { #[cfg(feature = "threading")] @@ -588,6 +514,15 @@ impl GcState { #[cfg(feature = "threading")] gc.scheduled.store(false, Ordering::Relaxed); + before(); + // Drop the body's generation locks, STW guards and temporary roots + // before Python callbacks run, but retain the collecting lock. + let result = self.collect_locked(gc, generation); + after(&result); + result + } + + fn collect_locked(&self, gc: &GcInterpreterState, generation: usize) -> CollectResult { let start_time = cfg_select! { target_arch = "wasm32" => (), _ => std::time::Instant::now(), @@ -628,7 +563,7 @@ impl GcState { // Closing it fully would require making those locks stop-the-world // aware; the exclusion above only serializes the fork/GC requesters. #[cfg(feature = "threading")] - let mut stw = CollectStopTheWorld::new(); + let mut stw = StopTheWorldGroup::new(); // Step 1: Gather objects from generations 0..=generation // Hold read locks for the entire scan to prevent concurrent modifications. @@ -910,19 +845,24 @@ impl GcState { }) .collect(); - // 6c: Clear existing weakrefs BEFORE calling __del__ + // 6c: Clear callback-bearing weakrefs BEFORE calling __del__. Keep + // callback-free weakrefs usable throughout finalization. + let unreachable_set: GcSet = unreachable.iter().copied().collect(); + let is_unreachable = + |obj: &PyObject| unreachable_set.contains(&GcPtr(core::ptr::NonNull::from(obj))); let mut all_callbacks: Vec<(crate::PyRef, crate::PyObjectRef)> = Vec::new(); for obj_ref in &unreachable_refs { - let callbacks = obj_ref.gc_clear_weakrefs_collect_callbacks(); + let callbacks = obj_ref.gc_clear_weakrefs_collect_callbacks(&is_unreachable); all_callbacks.extend(callbacks); } for (wr, cb) in all_callbacks { - if let Some(Err(e)) = crate::vm::thread::with_vm(&cb, |vm| cb.call((wr.clone(),), vm)) { - crate::vm::thread::with_vm(&cb, |vm| { - vm.run_unraisable(e.clone(), Some("weakref callback".to_owned()), cb.clone()); - }); - } + crate::vm::thread::with_vm(&cb, |vm| { + let _raised = vm.preserve_raised_exception(); + if let Err(e) = cb.call((wr.clone(),), vm) { + vm.run_unraisable(e, Some("weakref callback".to_owned()), cb.clone()); + } + }); } // 6d: Call __del__ on unreachable objects (skip already-finalized). @@ -934,7 +874,6 @@ impl GcState { // Detect resurrection let mut resurrected_set: GcSet = GcSet::default(); - let unreachable_set: GcSet = unreachable.iter().copied().collect(); for obj in &unreachable_refs { let ptr = GcPtr(core::ptr::NonNull::from(obj.as_ref())); @@ -1028,6 +967,14 @@ impl GcState { // skips tp_clear for saved objects). let save_all = debug.contains(GcDebugFlags::SAVEALL); + // Callback-free weakrefs remain usable during finalizers, so a + // thread can still acquire an external reference at this point. + // Stop before taking generation/list locks, and keep the final + // liveness check and weakref closure in the same stopped phase. + // No callbacks, finalizers or tp_clear may run under this guard. + #[cfg(feature = "threading")] + let mut clear_stw = StopTheWorldGroup::new(); + // Untrack dead objects BEFORE clearing them, mirroring the // untrack-then-clear ordering of the refcount dealloc path. // A cleared object (e.g. a frame husk with iframe == None) must @@ -1045,11 +992,10 @@ impl GcState { // One strong reference held by the `truly_dead` vec itself. expected_counts.insert(GcPtr(NonNull::from(obj)), 1); } - // With the objects out of the generation lists, no new external - // reference can appear. Count the references coming from within - // the dead set; any surplus in strong_count means another thread - // grabbed a reference before untracking (late resurrection) and - // the object must not be cleared. + // With the world stopped and these objects off the generation + // lists, count references from within the dead set. Any surplus + // means an external reference appeared before this stopped phase + // (late resurrection), and the object must not be cleared. let mut referents: GcMap>> = GcMap::default(); for obj_ref in &truly_dead { let referent_ptrs = unsafe { obj_ref.gc_get_referent_ptrs() }; @@ -1095,6 +1041,20 @@ impl GcState { unsafe { self.track_object(ptr.0, owner) }; } } + // Clear every weakref in or pointing to objects that will be + // cleared, including weakrefs created by finalizers. Do not run + // or drop callbacks here: all objects must remain intact until + // this pass finishes. Resurrected objects retain their weakrefs. + for obj_ref in &truly_dead { + if !late_resurrected.contains(&GcPtr(NonNull::from(obj_ref.as_ref()))) { + obj_ref.gc_clear_weakrefs(); + } + } + // Every remaining dead object is now unreachable through both + // generation lists and weakrefs. Resume before tp_clear can release + // edges or invoke arbitrary Python through deallocation. + #[cfg(feature = "threading")] + clear_stw.restart(); rustpython_common::refcount::with_deferred_drops(|| { if !save_all { for obj_ref in &truly_dead { @@ -1103,8 +1063,7 @@ impl GcState { continue; } if obj.gc_has_clear() { - let edges = unsafe { obj.gc_clear() }; - drop(edges); + let _edges = unsafe { obj.gc_clear() }; } } } @@ -1342,7 +1301,7 @@ impl GcInterpreterState { /// Get debug flags pub fn get_debug(&self) -> GcDebugFlags { - GcDebugFlags::from_bits_truncate(self.debug.load(Ordering::SeqCst)) + GcDebugFlags::from_bits_retain(self.debug.load(Ordering::SeqCst)) } /// Set debug flags @@ -1351,7 +1310,7 @@ impl GcInterpreterState { } /// Get thresholds for all generations - pub fn get_threshold(&self) -> (u32, u32, u32) { + pub fn get_threshold(&self) -> (i32, i32, i32) { ( self.generations[0].threshold(), self.generations[1].threshold(), @@ -1360,7 +1319,7 @@ impl GcInterpreterState { } /// Set thresholds - pub fn set_threshold(&self, t0: u32, t1: Option, t2: Option) { + pub fn set_threshold(&self, t0: i32, t1: Option, t2: Option) { self.generations[0].set_threshold(t0); if let Some(t1) = t1 { self.generations[1].set_threshold(t1); @@ -1389,11 +1348,30 @@ impl GcInterpreterState { gc_state().collect_inner(self, generation, true) } + /// Keep the existing collector exclusion active through Python callbacks. + pub(crate) fn collect_force_with_callbacks( + &self, + generation: usize, + before: impl FnOnce(), + after: impl FnOnce(&CollectResult), + ) -> CollectResult { + gc_state().collect_with_callbacks(self, generation, true, before, after) + } + /// The tracked objects this interpreter can reach (for gc.get_objects). pub fn get_objects(&self, generation: Option) -> Vec { gc_state().get_objects(generation, self.owner) } + /// Public introspection excludes permanent objects, unlike shutdown's + /// internal snapshot, which must still be able to reach frozen objects. + pub(crate) fn get_objects_for_introspection( + &self, + generation: Option, + ) -> Vec { + gc_state().get_objects_impl(generation, self.owner, false) + } + /// Move the objects this interpreter could collect into the permanent /// generation. pub fn freeze(&self) { @@ -1443,8 +1421,19 @@ pub fn current_owner() -> GcOwner { /// it collect if the allocation pushed gen0 past its threshold. /// /// # Safety -/// obj must be a valid pointer to a PyObject that is not already tracked. +/// obj must be a valid pointer to an untracked PyObject with freshly zeroed `gc_bits`. +#[inline] pub(crate) unsafe fn track_new_object(obj: NonNull) { + unsafe { track_new_object_impl(obj, true) }; +} + +/// Track fresh internal storage, optionally allowing collection before its +/// caller publishes it. +/// +/// # Safety +/// obj must be a valid pointer to an untracked PyObject with freshly zeroed `gc_bits`. +#[inline] +pub(crate) unsafe fn track_new_object_impl(obj: NonNull, allow_collection: bool) { let state = gc_state(); let Some(gc) = crate::vm::thread::current_gc_state() else { // No interpreter is running: the shared context builds its own objects @@ -1455,7 +1444,9 @@ pub(crate) unsafe fn track_new_object(obj: NonNull) { // SAFETY: as in `current_owner`. let gc = unsafe { gc.as_ref() }; unsafe { state.track_object_fresh(obj, gc.owner) }; - state.maybe_collect(gc); + if allow_collection { + state.maybe_collect(gc); + } } /// Track a generator (or coroutine, or async generator) together with the @@ -1565,6 +1556,9 @@ mod tests { first.enter(|vm| { vm.state.gc.set_threshold(1, None, None); assert!(!allocations.maybe_collect(&vm.state.gc)); + assert!(!vm.state.gc.scheduled.load(Ordering::Relaxed)); + allocations.counts[0].store(2, Ordering::Relaxed); + assert!(!allocations.maybe_collect(&vm.state.gc)); }); second.enter(|vm| { assert!(!vm.state.gc.scheduled.load(Ordering::Relaxed)); diff --git a/crates/vm/src/getpath.rs b/crates/vm/src/getpath.rs index eef1417ab14..d814b11765e 100644 --- a/crates/vm/src/getpath.rs +++ b/crates/vm/src/getpath.rs @@ -7,6 +7,8 @@ use crate::vm::{Paths, Settings}; use std::env; +use std::ffi::OsString; +use std::io::{self, Read}; use std::path::{Path, PathBuf}; // Platform-specific landmarks (ref: getpath.py PLATFORM CONSTANTS) @@ -19,6 +21,7 @@ mod platform { pub(super) const BUILD_LANDMARK: &str = "Modules/Setup.local"; pub(super) const VENV_LANDMARK: &str = "pyvenv.cfg"; pub(super) const BUILDSTDLIB_LANDMARK: &str = "Lib/os.py"; + pub(super) const DEFAULT_PROGRAM_NAME: &str = "python3"; pub(super) fn stdlib_subdir() -> String { format!("lib/python{}.{}", version::MAJOR, version::MINOR) @@ -51,6 +54,7 @@ mod platform { pub(super) const VENV_LANDMARK: &str = "pyvenv.cfg"; pub(super) const BUILDSTDLIB_LANDMARK: &str = "Lib\\os.py"; pub(super) const STDLIB_SUBDIR: &str = "Lib"; + pub(super) const DEFAULT_PROGRAM_NAME: &str = "python"; pub(super) fn stdlib_landmarks() -> [String; 2] { ["Lib\\os.py".into(), "Lib\\os.pyc".into()] @@ -101,19 +105,142 @@ fn search_up_dir>(start: P, landmarks: &[&str]) -> Option io::Result<()> { + let Some(executable) = get_executable_path() else { + return Ok(()); + }; + #[cfg(unix)] + let resolved = resolve_executable_symlinks(&executable).filter(|path| *path != executable); + #[cfg(not(unix))] + let resolved: Option = None; + for mut candidate in core::iter::once(executable).chain(resolved) { + if cfg!(windows) + && candidate.extension().is_some_and(|ext| { + ext.as_encoded_bytes().eq_ignore_ascii_case(b"exe") + || ext.as_encoded_bytes().eq_ignore_ascii_case(b"dll") + }) + { + candidate.set_extension(""); + } + candidate.as_mut_os_string().push("._pth"); + #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] + let file = crate::host_env::fs::open(&candidate); + #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] + let file = std::fs::File::open(&candidate); + let Ok(file) = file else { continue }; + let mut content = Vec::new(); + file.take(32 * 1024).read_to_end(&mut content)?; + if content.len() >= 32 * 1024 { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "cannot read ._pth file of 32KB or larger during initialization", + )); + } + // Settings currently stores paths as String, not surrogate-capable text. + // Reject unsupported encoding rather than changing paths or ignoring isolation. + let content = core::str::from_utf8(&content).map_err(|_| { + io::Error::new( + io::ErrorKind::InvalidData, + "non-UTF-8 ._pth paths are unsupported", + ) + })?; + let parent = std::path::absolute(candidate.parent().unwrap_or_else(|| Path::new(".")))?; + let mut search_paths = Vec::new(); + let mut import_site = false; + for line in content.lines() { + let line = line.split('#').next().unwrap_or_default().trim(); + if line.is_empty() { + continue; + } + if line == "import site" { + import_site = true; + } else if line.starts_with("import ") { + eprintln!("unsupported 'import' line in ._pth file"); + } else { + let joined = parent.join(line); + let double_root = cfg!(unix) + && joined + .to_str() + .is_some_and(|path| path.starts_with("//") && !path.starts_with("///")); + let mut normalized = PathBuf::new(); + for part in joined.components() { + match part { + std::path::Component::ParentDir => { + normalized.pop(); + } + std::path::Component::CurDir => {} + _ => normalized.push(part.as_os_str()), + } + } + if double_root && let Ok(relative) = normalized.strip_prefix("/") { + normalized = Path::new("//").join(relative); + } + search_paths.push( + normalized + .to_str() + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "non-UTF-8 ._pth paths are unsupported", + ) + })? + .to_owned(), + ); + } + } + let home = parent + .to_str() + .ok_or_else(|| { + io::Error::new( + io::ErrorKind::InvalidData, + "non-UTF-8 ._pth directory is unsupported", + ) + })? + .to_owned(); + settings.home = Some(home); + if content.is_empty() { + // getpath.py detects this file but skips its final `if pth:` block. + settings.under_pth = Some(UnderPth::Empty); + return Ok(()); + } + settings.under_pth = Some(UnderPth::Isolated); + settings.path_list = search_paths.into_iter().map(OsString::from).collect(); + settings.isolated = true; + settings.ignore_environment = true; + settings.user_site_directory = false; + settings.safe_path = true; + settings.import_site = import_site; + return Ok(()); + } + Ok(()) +} + /// Compute path configuration from Settings /// /// This function should be called before interpreter initialization. /// It returns a Paths struct with all computed path values. pub fn init_path_config(settings: &Settings) -> Paths { - let mut paths = Paths::default(); + let mut paths = Paths { + program_name: program_name(), + ..Paths::default() + }; // Step 0: Get executable path let executable = get_executable_path(); let real_executable = executable .as_ref() - .map(|p| p.to_string_lossy().into_owned()) - .unwrap_or_default(); + .map_or_default(|p| p.to_string_lossy().into_owned()); // Step 1: Check for PYTHONEXECUTABLE / __PYVENV_LAUNCHER__ // When set, these are used as sys.executable and when searching for venvs. @@ -129,55 +256,85 @@ pub fn init_path_config(settings: &Settings) -> Paths { .and_then(|p| p.parent().map(PathBuf::from)) }; - // Step 2: Check for venv (pyvenv.cfg) and get 'home' - let (venv_prefix, home_dir) = detect_venv(exe_dir.as_ref()); + // A readable pyvenv.cfg establishes the environment even without a home key. + let (venv_prefix, configured_home) = detect_venv(exe_dir.as_ref()); + // Explicit PYTHONHOME takes precedence over the configuration's home key, + // including its influence on _base_executable. + let explicit_home = settings.home.as_deref().filter(|home| !home.is_empty()); + let home_dir = if explicit_home.is_some() { + None + } else { + configured_home + }; let search_dir = home_dir.clone().or(exe_dir); - - // Step 3: Check for build directory - let build_prefix = detect_build_directory(search_dir.as_ref()); - - // Step 4: Calculate prefix via landmark search - // When in venv, search_dir is home_dir, so this gives us the base Python's prefix - let calculated_prefix = calculate_prefix(search_dir.as_ref(), build_prefix.as_ref()); - - // Step 5: Set prefix and base_prefix - if venv_prefix.is_some() { - // In venv: prefix = venv directory, base_prefix = original Python's prefix - paths.prefix = venv_prefix.as_ref().map_or_else( - || calculated_prefix.clone(), - |p| p.to_string_lossy().into_owned(), + #[cfg(unix)] + let search_dir = if venv_prefix.is_some() + && home_dir.is_none() + && explicit_home.is_none() + && paths.base_executable.is_empty() + { + // A no-home environment uses the target installation for landmarks, + // while _base_executable retains the invoked executable spelling. + executable + .as_deref() + .and_then(resolve_executable_symlinks) + .and_then(|resolved| resolved.parent().map(PathBuf::from)) + .or(search_dir) + } else { + search_dir + }; + let build_prefix = explicit_home + .is_none() + .then(|| detect_build_directory(search_dir.as_ref())) + .flatten(); + let home_prefixes = explicit_home.map(|home| { + home.split_once(if cfg!(windows) { ';' } else { ':' }) + .unwrap_or((home, home)) + }); + paths.base_prefix = home_prefixes + .map(|(prefix, _)| prefix) + .filter(|prefix| !prefix.is_empty()) + .map_or_else( + || calculate_prefix(search_dir.as_ref(), build_prefix.as_ref()), + str::to_owned, ); - paths.base_prefix = calculated_prefix; + paths.base_exec_prefix = home_prefixes + .map(|(_, exec_prefix)| exec_prefix) + .filter(|exec_prefix| !exec_prefix.is_empty()) + .map_or_else( + || calculate_exec_prefix(search_dir.as_ref(), &paths.base_prefix), + str::to_owned, + ); + // The venv overlays public prefixes, not the base library search paths. + if let Some(venv) = venv_prefix { + paths.prefix = venv.to_string_lossy().into_owned(); + paths.exec_prefix.clone_from(&paths.prefix); } else { - // Not in venv: prefix == base_prefix - paths.prefix.clone_from(&calculated_prefix); - paths.base_prefix = calculated_prefix; + paths.prefix.clone_from(&paths.base_prefix); + paths.exec_prefix.clone_from(&paths.base_exec_prefix); } - - // Step 6: Calculate exec_prefix - paths.exec_prefix = if venv_prefix.is_some() { - // In venv: exec_prefix = prefix (venv directory) - paths.prefix.clone() - } else { - calculate_exec_prefix(search_dir.as_ref(), paths.prefix.as_ref()) - }; - paths.base_exec_prefix.clone_from(&paths.base_prefix); - - // Step 7: Calculate base_executable (if not already set by an env override) if paths.base_executable.is_empty() { paths.base_executable = calculate_base_executable(executable.as_ref(), home_dir.as_ref()); } - - // Step 8: Build module_search_paths - paths.module_search_paths = - build_module_search_paths(settings, &paths.prefix, &paths.exec_prefix); - - // Step 9: Calculate stdlib_dir - paths.stdlib_dir = calculate_stdlib_dir(&paths.prefix); + paths.module_search_paths = if settings.under_pth == Some(UnderPth::Isolated) { + settings.path_list.clone() + } else { + build_module_search_paths(settings, &paths.base_prefix, &paths.base_exec_prefix) + }; + paths.stdlib_dir = calculate_stdlib_dir(&paths.base_prefix); paths } +/// Identify an uninstalled RustPython source library independently of the +/// executable location (Cargo permits targets outside the source tree). +pub(crate) fn source_directory(paths: &Paths) -> Option<&Path> { + let library = Path::new(paths.stdlib_dir.as_deref()?); + let source = library.parent()?; + (library.file_name()? == "Lib" && source.join("crates/vm/Cargo.toml").is_file()) + .then_some(source) +} + /// Get default prefix value used when landmark search fails. /// /// A compile-time `RUSTPYTHON_PREFIX` always wins. Otherwise POSIX uses the @@ -212,20 +369,16 @@ fn detect_venv(exe_dir: Option<&PathBuf>) -> (Option, Option) && let Some(venv_dir) = dir.parent() { let cfg = venv_dir.join(platform::VENV_LANDMARK); - if cfg.exists() - && let Some(home) = parse_pyvenv_home(&cfg) - { - return (Some(venv_dir.to_path_buf()), Some(PathBuf::from(home))); + if let Some(home) = parse_pyvenv_home(&cfg) { + return (Some(venv_dir.to_path_buf()), home.map(PathBuf::from)); } } // Try exe_dir/pyvenv.cfg (alternative layout) if let Some(dir) = exe_dir { let cfg = dir.join(platform::VENV_LANDMARK); - if cfg.exists() - && let Some(home) = parse_pyvenv_home(&cfg) - { - return (Some(dir.clone()), Some(PathBuf::from(home))); + if let Some(home) = parse_pyvenv_home(&cfg) { + return (Some(dir.clone()), home.map(PathBuf::from)); } } @@ -287,32 +440,102 @@ fn calculate_exec_prefix(exe_dir: Option<&PathBuf>, prefix: &str) -> String { #[cfg(not(windows))] { - // POSIX: search for lib-dynload directory - if let Some(dir) = exe_dir { - let landmark = platform::platstdlib_landmark(); - if let Some(exec_prefix) = search_up_dir(dir, &[&landmark]) { - return exec_prefix.to_string_lossy().into_owned(); - } + // Prefer the platform library under prefix before executable ancestors. + let landmark = platform::platstdlib_landmark(); + if Path::new(prefix).join(&landmark).is_dir() { + return prefix.to_owned(); + } + if let Some(dir) = exe_dir + && let Some(exec_prefix) = search_up_dir(dir, &[&landmark]) + { + return exec_prefix.to_string_lossy().into_owned(); } // Fallback: same as prefix prefix.to_owned() } } +/// Resolve final-component links without resolving directory aliases (ref: getpath.c). +#[cfg(unix)] +fn resolve_executable_symlinks(executable: &Path) -> Option { + use std::os::unix::ffi::OsStrExt; + + let mut path = executable.to_path_buf(); + // CPython rejects 40 successful hops, matching the Linux 4.2 kernel limit. + for _ in 0..40 { + let Ok(target) = std::fs::read_link(&path) else { + return Some(path); + }; + if target.is_absolute() { + path = target; + continue; + } + + // Match getpath.c's raw dirname join, then normalize lexically without + // resolving directory symlinks or losing a double-leading-slash root. + let bytes = path.as_os_str().as_bytes(); + let end = bytes.iter().rposition(|&b| b == b'/'); + let dirname = &bytes[..end.unwrap_or(bytes.len())]; + let mut joined = PathBuf::from(std::ffi::OsStr::from_bytes(dirname)); + // Filesystem text uses UTF-8/surrogateescape; count characters, not bytes. + let multiple_chars = + core::str::from_utf8(dirname).map_or(dirname.len() > 1, |s| s.chars().nth(1).is_some()); + if multiple_chars && !dirname.ends_with(b"/") { + joined.as_mut_os_string().push("/"); + } + joined.as_mut_os_string().push(target.as_os_str()); + let bytes = joined.as_os_str().as_bytes(); + let double_root = bytes.starts_with(b"//") && !bytes.starts_with(b"///"); + path.clear(); + for component in joined.components() { + if component == std::path::Component::ParentDir + && !path.as_os_str().is_empty() + && !path.ends_with("..") + { + path.pop(); + } else if component != std::path::Component::CurDir { + path.push(component.as_os_str()); + } + } + if double_root { + path = Path::new("//").join(path.strip_prefix("/").ok()?); + } + } + None +} + /// Calculate base_executable fn calculate_base_executable(executable: Option<&PathBuf>, home_dir: Option<&PathBuf>) -> String { - // If in venv and we have home, construct base_executable from home if let (Some(exe), Some(home)) = (executable, home_dir) && let Some(exe_name) = exe.file_name() { + // Like getpath.py, resolve the executable's final links once, without + // following creator metadata or another environment's configuration. + #[cfg(unix)] + if let Some(resolved) = resolve_executable_symlinks(exe) + && resolved.as_os_str() != exe.as_os_str() + { + return resolved.to_string_lossy().into_owned(); + } + let base = home.join(exe_name); + #[cfg(not(windows))] + if !base.is_file() { + for name in [ + format!("python{}", crate::version::MAJOR), + format!("python{}.{}", crate::version::MAJOR, crate::version::MINOR), + ] { + let candidate = home.join(name); + if candidate.is_file() { + return candidate.to_string_lossy().into_owned(); + } + } + } return base.to_string_lossy().into_owned(); } // Otherwise, base_executable == executable - executable - .map(|p| p.to_string_lossy().into_owned()) - .unwrap_or_default() + executable.map_or_default(|p| p.to_string_lossy().into_owned()) } /// Calculate stdlib_dir (sys._stdlib_dir) @@ -330,8 +553,31 @@ fn calculate_stdlib_dir(prefix: &str) -> Option { } } +/// Add compiled-in library paths after environment entries and the default ZIP. +/// Preserve an embedding hook's custom search order by appending instead when +/// the calculated paths have already been replaced or modified. +pub fn add_build_time_paths(settings: &Settings, paths: &mut Paths, extra: Vec) { + if settings.under_pth.is_some() { + return; + } + let calculated = + build_module_search_paths(settings, &paths.base_prefix, &paths.base_exec_prefix); + let index = if paths.module_search_paths == calculated { + settings.path_list.len() + 1 + } else { + paths.module_search_paths.len() + }; + paths + .module_search_paths + .splice(index..index, extra.into_iter().map(OsString::from)); +} + /// Build the complete module_search_paths (sys.path) -fn build_module_search_paths(settings: &Settings, prefix: &str, exec_prefix: &str) -> Vec { +fn build_module_search_paths( + settings: &Settings, + prefix: &str, + exec_prefix: &str, +) -> Vec { let mut paths = Vec::new(); // 1. PYTHONPATH/RUSTPYTHONPATH from settings @@ -339,27 +585,27 @@ fn build_module_search_paths(settings: &Settings, prefix: &str, exec_prefix: &st // 2. ZIP file path let zip_path = PathBuf::from(prefix).join(platform::zip_landmark()); - paths.push(zip_path.to_string_lossy().into_owned()); + paths.push(zip_path.into_os_string()); // 3. stdlib and platstdlib directories #[cfg(not(windows))] { // POSIX: stdlib first, then lib-dynload let stdlib_dir = PathBuf::from(prefix).join(platform::stdlib_subdir()); - paths.push(stdlib_dir.to_string_lossy().into_owned()); + paths.push(stdlib_dir.into_os_string()); let platstdlib = PathBuf::from(exec_prefix).join(platform::platstdlib_landmark()); - paths.push(platstdlib.to_string_lossy().into_owned()); + paths.push(platstdlib.into_os_string()); } #[cfg(windows)] { // Windows: DLLs first, then Lib let platstdlib = PathBuf::from(exec_prefix).join(platform::platstdlib_landmark()); - paths.push(platstdlib.to_string_lossy().into_owned()); + paths.push(platstdlib.into_os_string()); let stdlib_dir = PathBuf::from(prefix).join(platform::STDLIB_SUBDIR); - paths.push(stdlib_dir.to_string_lossy().into_owned()); + paths.push(stdlib_dir.into_os_string()); } paths @@ -378,22 +624,51 @@ fn env_executable_override() -> Option { None } +/// CALCULATE program_name: `argv[0]`, with the executable suffix added when +/// only the suffixed file exists. +fn program_name() -> OsString { + let program_name = env::args_os() + .next() + .filter(|arg| !arg.is_empty()) + .unwrap_or_else(|| platform::DEFAULT_PROGRAM_NAME.into()); + if cfg!(windows) + && !program_name + .to_string_lossy() + .to_lowercase() + .ends_with(".exe") + { + let mut suffixed = program_name.clone(); + suffixed.push(".exe"); + if Path::new(&suffixed).is_file() { + return suffixed; + } + } + program_name +} + /// Get the current executable path fn get_executable_path() -> Option { - #[cfg(not(target_arch = "wasm32"))] + #[cfg(windows)] + { + // CreateProcess permits argv[0] to differ from the executable filename. + // Like CPython's GetModuleFileNameW, use the loaded image's path. + env::current_exe().ok() + } + #[cfg(all(not(windows), not(target_arch = "wasm32")))] { let exec_arg = env::args_os().next()?; crate::host_env::fs::which(exec_arg) } #[cfg(target_arch = "wasm32")] { - let exec_arg = env::args().next()?; + let exec_arg = env::args_os().next()?; Some(PathBuf::from(exec_arg)) } } /// Parse pyvenv.cfg and extract the 'home' key value -fn parse_pyvenv_home(pyvenv_cfg: &Path) -> Option { +// Outer None means unreadable; Some(None) is a valid configuration without home. +fn parse_pyvenv_home(pyvenv_cfg: &Path) -> Option> { #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] let content = crate::host_env::fs::read_to_string(pyvenv_cfg).ok()?; #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] @@ -401,19 +676,74 @@ fn parse_pyvenv_home(pyvenv_cfg: &Path) -> Option { for line in content.lines() { if let Some((key, value)) = line.split_once('=') - && key.trim().to_lowercase() == "home" + && key.trim().eq_ignore_ascii_case("home") { - return Some(value.trim().to_string()); + return Some(Some(value.trim().to_string())); } } - None + Some(None) } #[cfg(test)] mod tests { use super::*; + #[cfg(windows)] + #[test] + fn executable_is_the_loaded_image() { + assert_eq!(get_executable_path(), env::current_exe().ok()); + } + + #[test] + fn build_time_paths_follow_configured_paths_and_zip() { + for configured in [ + vec![], + vec![OsString::from("first"), OsString::from("second")], + ] { + let settings = Settings { + path_list: configured, + ..Settings::default() + }; + let calculated = build_module_search_paths(&settings, "prefix", "exec-prefix"); + let mut paths = Paths { + base_prefix: "prefix".to_owned(), + base_exec_prefix: "exec-prefix".to_owned(), + module_search_paths: calculated.clone(), + ..Paths::default() + }; + let extra = vec!["build-first".to_owned(), "build-second".to_owned()]; + add_build_time_paths(&settings, &mut paths, extra.clone()); + let boundary = settings.path_list.len() + 1; + let mut expected = calculated[..boundary].to_vec(); + expected.extend(extra.into_iter().map(OsString::from)); + expected.extend_from_slice(&calculated[boundary..]); + assert_eq!(paths.module_search_paths, expected); + } + } + + #[test] + fn build_time_paths_preserve_custom_search_order() { + let settings = Settings { + path_list: vec!["configured".into()], + ..Settings::default() + }; + let mut modified = build_module_search_paths(&settings, "prefix", "exec-prefix"); + modified.push("custom".into()); + for custom in [vec![], modified] { + let mut paths = Paths { + base_prefix: "prefix".to_owned(), + base_exec_prefix: "exec-prefix".to_owned(), + module_search_paths: custom.clone(), + ..Paths::default() + }; + add_build_time_paths(&settings, &mut paths, vec!["build".to_owned()]); + let mut expected = custom; + expected.push("build".into()); + assert_eq!(paths.module_search_paths, expected); + } + } + #[test] fn init_path_config_basic() { let settings = Settings::default(); diff --git a/crates/vm/src/import.rs b/crates/vm/src/import.rs index 3fb6e5fdc2e..825d4c75a0b 100644 --- a/crates/vm/src/import.rs +++ b/crates/vm/src/import.rs @@ -2,12 +2,214 @@ use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, - builtins::{PyCode, PyStr, PyUtf8Str, PyUtf8StrRef, traceback::PyTraceback}, + builtins::{PyCode, PyDict, PyModule, PyStr, PyStrRef, PyUtf8Str, traceback::PyTraceback}, exceptions::types::PyBaseException, scope::Scope, vm::{VirtualMachine, resolve_frozen_alias, thread}, }; +use core::{cell::Cell, sync::atomic::Ordering, time::Duration}; +use std::{io::Write, time::Instant}; + +/// Import for side effects and return the exact named module (PyImport_Import). +/// Unlike ordinary imports, this re-reads globals' builtins and passes globals +/// as both namespace arguments to the selected importer. +pub fn import_module(vm: &VirtualMachine, module_name: &Py) -> PyResult { + let from_list = vm.ctx.new_list(vec![]); + let mut importer: Option = None; + let mut builtins: Option = None; + let mut globals: Option = crate::frame::current_globals().map(Into::into); + let has_globals = globals.is_some(); + // Keep the selected module/error alive across callback-capable cleanup on + // every path, including lookup and invocation failures. + (|| { + let globals = globals.get_or_insert_with(|| vm.ctx.new_dict().into()); + let builtins = builtins.insert(if has_globals { + globals.get_item(identifier!(vm, __builtins__), vm)? + } else { + // Bootstrap without calling this helper or the frame's importer. + let builtins = import_module_level(vm.ctx.intern_str("builtins"), None, None, 0, vm)?; + globals.set_item(identifier!(vm, __builtins__), builtins.clone(), vm)?; + builtins + }); + let importer = importer.insert(if builtins.downcast_ref::().is_some() { + // Dict subclasses keep their subscription callbacks, but every + // lookup failure is replaced, not just KeyError. + builtins + .get_item(identifier!(vm, __import__), vm) + .map_err(|_err| vm.new_key_error(identifier!(vm, __import__).to_owned().into()))? + } else { + builtins.get_attr(identifier!(vm, __import__), vm)? + }); + let imported = importer.call( + ( + module_name.to_owned(), + globals.clone(), + globals.clone(), + from_list.clone(), + 0, + ), + vm, + )?; + drop(imported); + + let modules = vm.sys_modules(); + let selected = match modules.get_item(module_name, vm) { + Ok(module) => Ok(Some(module)), + Err(err) if err.fast_isinstance(vm.ctx.exceptions.key_error) => Ok(None), + Err(err) => Err(err), + }; + drop(modules); + selected?.ok_or_else(|| vm.new_key_error(module_name.to_owned().into())) + })() +} + +/// Return a module from `sys.modules`, creating it if absent or not a module. +/// +/// Exact dictionaries use conditional mutations so concurrent callers agree on +/// the installed module. Dictionary subclasses retain their mapping callbacks; +/// this does not extend the current dictionary-only `sys.modules` contract. +pub fn add_module(vm: &VirtualMachine, name: &str) -> PyResult> { + let sys_modules = vm.sys_modules(); + let modules = sys_modules.try_downcast_ref::(vm)?; + + if !sys_modules.class().is(vm.ctx.types.dict_type) { + if let Some(current) = modules.get_item_opt(name, vm)? + && let Some(module) = current.downcast_ref::() + { + return Ok(module.to_owned()); + } + let module = vm.new_module(name, vm.ctx.new_dict(), None); + sys_modules.set_item(name, module.clone().into(), vm)?; + return Ok(module); + } + + let key = vm.ctx.new_str(name); + loop { + // The factory runs outside the payload guard. setdefault re-probes after + // construction, returning the winner if another caller inserted first. + let current = modules.get_or_insert(vm, key.as_object(), || { + vm.new_module(name, vm.ctx.new_dict(), None).into() + })?; + if let Some(module) = current.downcast_ref::() { + return Ok(module.to_owned()); + } + + let replacement = vm.new_module(name, vm.ctx.new_dict(), None); + // Keep the observed value alive across the identity check. Both module + // construction and destruction of replaced references stay unlocked. + if modules.replace_if_identity(&key, ¤t, replacement.clone().into(), vm)? { + return Ok(replacement); + } + // A competing replacement or removal won. Look up its result instead + // of overwriting a module installed by another caller. + } +} + +/// Nested imports are timed per thread, so concurrent imports do not subtract +/// each other's elapsed time. The output header belongs to the interpreter. +#[derive(Clone, Copy, Default)] +pub(crate) struct ImportTimingState { + depth: usize, + children: Duration, +} + +fn import_time_header(vm: &VirtualMachine) { + let mut stderr = std::io::stderr().lock(); + if !vm.state.import_time_header.swap(true, Ordering::Relaxed) { + let _ = writeln!( + stderr, + "import time: self [us] | cumulative | imported package" + ); + } +} + +fn import_time_name(name: &Py) -> String { + use core::fmt::Write; + let mut output = String::with_capacity(name.as_bytes().len()); + for codepoint in name.as_wtf8().code_points() { + match codepoint.to_char() { + Some(ch) => output.push(ch), + None => { + let _ = write!(output, "\\u{:04x}", codepoint.to_u32()); + } + } + } + output +} + +pub(crate) fn report_cached_import(name: &Py, vm: &VirtualMachine) { + if vm.state.config.settings.import_time == 2 { + import_time_header(vm); + let name = import_time_name(name); + // printf("%*s") counts encoded bytes, not Unicode scalar values. + let padding = (vm.import_timing.get().depth * 2).saturating_sub(name.len()); + let _ = writeln!( + std::io::stderr(), + "import time: cached | cached | {:padding$}{}", + "", + name + ); + } +} + +struct ImportTimer<'a> { + state: &'a Cell, + parent: ImportTimingState, + start: Instant, + name: &'a Py, +} + +impl<'a> ImportTimer<'a> { + fn start(name: &'a Py, vm: &'a VirtualMachine) -> Option { + if vm.state.config.settings.import_time == 0 { + return None; + } + import_time_header(vm); + let parent = vm.import_timing.replace(ImportTimingState { + depth: vm.import_timing.get().depth + 1, + children: Duration::ZERO, + }); + Some(Self { + state: &vm.import_timing, + parent, + start: Instant::now(), + name, + }) + } +} + +impl Drop for ImportTimer<'_> { + fn drop(&mut self) { + let cumulative = self.start.elapsed(); + let own = cumulative.saturating_sub(self.state.get().children); + self.state.set(ImportTimingState { + depth: self.parent.depth, + children: self.parent.children.saturating_add(cumulative), + }); + let width = self.parent.depth * 2; + let _ = writeln!( + std::io::stderr(), + "import time: {:9} | {:10} | {:width$}{}", + own.as_nanos().div_ceil(1000), + cumulative.as_nanos().div_ceil(1000), + "", + import_time_name(self.name), + ); + } +} + +pub(crate) fn find_and_load( + name: &Py, + function: &'static str, + vm: &VirtualMachine, +) -> PyResult { + let _timer = ImportTimer::start(name, vm); + vm.importlib + .get_attr(function, vm)? + .call((name.to_owned(), vm.import_func.clone()), vm) +} + pub(crate) fn check_pyc_magic_number_bytes(buf: &[u8]) -> bool { buf.starts_with(&crate::version::PYC_MAGIC_NUMBER_BYTES) } @@ -26,10 +228,15 @@ pub(crate) fn init_importlib_base(vm: &mut VirtualMachine) -> PyResult PyResult { } pub fn import_builtin(vm: &VirtualMachine, module_name: &str) -> PyResult { - let sys_modules = vm.sys_module.get_attr("modules", vm)?; + let sys_modules = vm.sys_modules(); // Check if already in sys.modules (handles recursive imports) if let Ok(module) = sys_modules.get_item(module_name, vm) { @@ -164,27 +371,49 @@ pub fn import_source(vm: &VirtualMachine, module_name: &str, content: &str) -> P /// import path below and by [`crate::VirtualMachine::import`]'s /// `sys.modules`-cache fast path). pub(crate) fn is_module_initializing(module: &PyObject, vm: &VirtualMachine) -> PyResult { - match vm.get_attribute_opt(module, vm.ctx.intern_str("__spec__"))? { - Some(spec) => match vm.get_attribute_opt(&spec, vm.ctx.intern_str("_initializing"))? { - Some(v) => v.try_to_bool(vm), - None => Ok(false), - }, + let spec = vm.get_attribute_opt(module, vm.ctx.intern_str("__spec__"))?; + is_spec_initializing(spec.as_deref(), vm) +} + +pub(crate) fn is_spec_initializing(spec: Option<&PyObject>, vm: &VirtualMachine) -> PyResult { + let Some(spec) = spec else { + return Ok(false); + }; + match vm.get_attribute_opt(spec, "_initializing")? { + Some(value) => value.try_to_bool(vm), None => Ok(false), } } /// If `__spec__._initializing` is true, wait for the module to finish -/// initializing by calling `_lock_unlock_module`. +/// initializing by calling `_lock_unlock_module`, and return whether it was initializing. fn import_ensure_initialized( module: &PyObject, - name: &Py, + name: &Py, vm: &VirtualMachine, -) -> PyResult<()> { - if is_module_initializing(module, vm)? { +) -> PyResult { + let initializing = is_module_initializing(module, vm)?; + if initializing { let lock_unlock = vm.importlib.get_attr("_lock_unlock_module", vm)?; lock_unlock.call((name.to_owned(),), vm)?; } - Ok(()) + report_cached_import(name, vm); + Ok(initializing) +} + +/// Recheck after inspecting `__spec__` or waiting for initialization: a failed +/// import may have removed or replaced the module while we held its reference. +pub(crate) fn is_cached_module( + modules: &PyObject, + name: &Py, + module: &PyObject, + vm: &VirtualMachine, +) -> PyResult { + match modules.get_item(name, vm) { + Ok(current) => Ok(current.is(module)), + Err(error) if error.fast_isinstance(vm.ctx.exceptions.key_error) => Ok(false), + Err(error) => Err(error), + } } pub fn import_code_obj( @@ -209,7 +438,7 @@ pub fn import_code_obj( let module = vm.new_module(module_name, attrs.clone(), None); // Store module in cache to prevent infinite loop with mutual importing libs: - let sys_modules = vm.sys_module.get_attr("modules", vm)?; + let sys_modules = vm.sys_modules(); sys_modules.set_item(module_name, module.clone().into(), vm)?; // Execute main code in module: @@ -229,14 +458,14 @@ fn remove_importlib_frames_inner( return (None, false); }; - let file_name = traceback.frame.iframe().code().source_path().as_str(); + let file_name = traceback.frame.iframe().code().source_path().as_bytes(); let (inner_tb, mut now_in_importlib) = remove_importlib_frames_inner(vm, traceback.next.lock().clone(), always_trim); - if file_name == "" - || file_name == "" - || file_name == "_frozen_importlib" - || file_name == "_frozen_importlib_external" + if file_name == b"" + || file_name == b"" + || file_name == b"_frozen_importlib" + || file_name == b"_frozen_importlib_external" { if traceback.frame.iframe().code().obj_name.as_str() == "_call_with_frames_removed" { now_in_importlib = true; @@ -278,36 +507,37 @@ pub fn remove_importlib_frames(vm: &VirtualMachine, exc: &Py) { } /// Get origin path from a module spec, checking has_location first. -pub(crate) fn get_spec_file_origin(spec: Option<&PyObject>, vm: &VirtualMachine) -> Option { - let spec = spec?; - - let has_location = spec - .get_attr("has_location", vm) - .ok() - .and_then(|v| v.try_to_bool(vm).ok()) - .unwrap_or(false); +pub(crate) fn get_spec_file_origin( + spec: Option<&PyObject>, + vm: &VirtualMachine, +) -> PyResult> { + let Some(spec) = spec else { + return Ok(None); + }; + let Some(has_location_value) = vm.get_attribute_opt(spec, "has_location")? else { + return Ok(None); + }; + let has_location = has_location_value.try_to_bool(vm)?; + drop(has_location_value); if !has_location { - return None; + return Ok(None); } - spec.get_attr("origin", vm).ok().and_then(|origin| { - if vm.is_none(&origin) { - None - } else { - origin - .downcast_ref::() - .and_then(|s| s.to_str().map(|s| s.to_owned())) - } - }) + Ok(vm + .get_attribute_opt(spec, "origin")? + .and_then(|origin| origin.downcast::().ok())) } /// Check if a module file possibly shadows another module of the same name. /// Compares the module's directory with the original sys.path[0] (derived from sys.argv[0]). -pub(crate) fn is_possibly_shadowing_path(origin: &str, vm: &VirtualMachine) -> bool { +pub(crate) fn is_possibly_shadowing_path(origin: &Py, vm: &VirtualMachine) -> bool { use std::path::Path; if vm.state.config.settings.safe_path { return false; } + let Some(origin) = origin.to_str() else { + return false; + }; let origin_path = Path::new(origin); let parent = match origin_path.parent() { @@ -380,6 +610,41 @@ pub(crate) fn is_stdlib_module_name(name: &PyObject, vm: &VirtualMachine) -> PyR result.try_to_bool(vm) } +/// Resolve an import target without finding or executing its module. +pub(crate) fn absolute_import_name( + name: &Py, + globals: Option<&PyObject>, + level: i32, + vm: &VirtualMachine, +) -> PyResult { + if level < 0 { + return Err(vm.new_value_error("level must be >= 0")); + } + if level == 0 { + if name.is_empty() { + return Err(vm.new_value_error("Empty module name")); + } + return Ok(name.to_owned()); + } + let globals = globals + .ok_or_else(|| vm.new_key_error(vm.ctx.new_str("'__name__' not in globals").into()))?; + let empty: PyObjectRef; + let globals = if vm.is_none(globals) { + empty = vm.ctx.new_dict().into(); + &empty + } else { + globals + }; + let package = calc_package(Some(globals), vm)?; + if package.is_empty() { + return Err(vm.new_import_error( + "attempted relative import with no known parent package", + vm.ctx.new_utf8_str(""), + )); + } + resolve_name(name, &package, level as usize, vm) +} + /// PyImport_ImportModuleLevelObject pub(crate) fn import_module_level( name: &Py, @@ -392,21 +657,6 @@ pub(crate) fn import_module_level( return Err(vm.new_value_error("level must be >= 0")); } - let name = match name.as_utf8() { - Some(name) => name, - None => { - // Name contains surrogates. Try sys.modules lookup with the - // Python string key directly. - if level == 0 { - let sys_modules = vm.sys_module.get_attr("modules", vm)?; - return sys_modules.get_item(name, vm).map_err(|_| { - vm.new_import_error(format!("No module named '{name}'"), name.to_owned()) - }); - } - return Err(vm.new_import_error(format!("No module named '{name}'"), name.to_owned())); - } - }; - // Resolve absolute name let abs_name = if level > 0 { // When globals is not provided (Rust None), raise KeyError @@ -438,16 +688,24 @@ pub(crate) fn import_module_level( }; // import_get_module + import_find_and_load - let sys_modules = vm.sys_module.get_attr("modules", vm)?; + let sys_modules = vm.sys_modules(); let module = match sys_modules.get_item(&*abs_name, vm) { Ok(m) if !vm.is_none(&m) => { - import_ensure_initialized(&m, &abs_name, vm)?; - m + let initializing = import_ensure_initialized(&m, &abs_name, vm)?; + if !is_cached_module(&sys_modules, &abs_name, &m, vm)? { + find_and_load(&abs_name, "_find_and_load", vm)? + } else { + if !initializing { + crate::lazy_import::clear_submodule(&abs_name, true, vm)?; + } + m + } } - _ => { - let find_and_load = vm.importlib.get_attr("_find_and_load", vm)?; - find_and_load.call((abs_name.clone(), vm.import_func.clone()), vm)? + Ok(_) => find_and_load(&abs_name, "_find_and_load", vm)?, + Err(error) if error.fast_isinstance(vm.ctx.exceptions.key_error) => { + find_and_load(&abs_name, "_find_and_load", vm)? } + Err(error) => return Err(error), }; // Handle fromlist @@ -472,24 +730,23 @@ pub(crate) fn import_module_level( Ok(module) } } else if level == 0 || !name.is_empty() { - let name_str = name.as_str(); - match name_str.find('.') { + let name_bytes = name.as_bytes(); + match name_bytes.iter().position(|&byte| byte == b'.') { None => Ok(module), Some(dot) => { let to_return = if level == 0 { - vm.ctx.new_utf8_str(&name_str[..dot]) + vm.ctx.new_str(&name.as_wtf8()[..dot]) } else { - let cut_off = name_str.len() - dot; - let abs = abs_name.as_str(); - vm.ctx.new_utf8_str(&abs[..abs.len() - cut_off]) + let cut_off = name_bytes.len() - dot; + let abs = abs_name.as_wtf8(); + vm.ctx.new_str(&abs[..abs.len() - cut_off]) }; match sys_modules.get_item(&*to_return, vm) { Ok(m) => Ok(m), Err(_) if level == 0 => { // For absolute imports (level 0), try importing the // parent. Matches _bootstrap.__import__ behavior. - let find_and_load = vm.importlib.get_attr("_find_and_load", vm)?; - find_and_load.call((to_return, vm.import_func.clone()), vm) + find_and_load(&to_return, "_find_and_load", vm) } Err(_) => { // For relative imports (level > 0), raise KeyError @@ -509,37 +766,44 @@ pub(crate) fn import_module_level( /// resolve_name in import.c - resolve relative import name fn resolve_name( - name: &Py, - package: &Py, + name: &Py, + package: &Py, level: usize, vm: &VirtualMachine, -) -> PyResult { - // Python: bits = package.rsplit('.', level - 1) - // Rust: rsplitn(level, '.') gives maxsplit=level-1 - let package_str = package.as_str(); - let parts: Vec<&str> = package_str.rsplitn(level, '.').collect(); - if parts.len() < level { - return Err(vm.new_import_error( - "attempted relative import beyond top-level package", - name.to_owned(), - )); +) -> PyResult { + // ASCII dots are character boundaries in WTF-8 too. Keep the original + // Python string, including surrogates, while walking up package components. + let package_bytes = package.as_bytes(); + let mut end = package_bytes.len(); + for _ in 1..level { + end = package_bytes[..end] + .iter() + .rposition(|&byte| byte == b'.') + .ok_or_else(|| { + vm.new_import_error( + "attempted relative import beyond top-level package", + name.to_owned(), + ) + })?; } - // rsplitn returns parts right-to-left, so last() is the leftmost (base) - let base = *parts.last().unwrap(); + let base = &package.as_wtf8()[..end]; let abs_name = if name.is_empty() { - if base.len() == package_str.len() { + if end == package_bytes.len() { package.to_owned() } else { - vm.ctx.new_utf8_str(base) + vm.ctx.new_str(base) } } else { - vm.ctx.new_utf8_str(format!("{base}.{}", name.as_str())) + let mut absolute = base.to_owned(); + absolute.push_str("."); + absolute.push_wtf8(name.as_wtf8()); + vm.ctx.new_str(absolute) }; Ok(abs_name) } /// _calc___package__ - calculate package from globals for relative imports -fn calc_package(globals: Option<&PyObject>, vm: &VirtualMachine) -> PyResult { +fn calc_package(globals: Option<&PyObject>, vm: &VirtualMachine) -> PyResult { let globals = globals.ok_or_else(|| { vm.new_import_error( "attempted relative import with no known parent package", @@ -553,7 +817,7 @@ fn calc_package(globals: Option<&PyObject>, vm: &VirtualMachine) -> PyResult, vm: &VirtualMachine) -> PyResult, vm: &VirtualMachine) -> PyResult, vm: &VirtualMachine) -> PyResult vm.ctx.new_utf8_str(&s[..dot]), - None => vm.ctx.new_utf8_str(""), - }) + let name = mod_name_str.as_wtf8(); + Ok( + match name.as_bytes().iter().rposition(|&byte| byte == b'.') { + Some(dot) => vm.ctx.new_str(&name[..dot]), + None => vm.ctx.new_str(""), + }, + ) } else { Ok(mod_name_str) } } + +pub(crate) fn import_from_attribute( + module: &PyObject, + name: &Py, + vm: &VirtualMachine, +) -> PyResult { + // Load attribute, and transform any error into import error. + if let Some(obj) = vm.get_attribute_opt(module, name)? { + return Ok(obj); + } + // fallback to importing '{module.__name__}.{name}' from sys.modules + let fallback_module = (|| { + let mod_name = module.get_attr(identifier!(vm, __name__), vm).ok()?; + let mod_name = mod_name.downcast_ref::()?; + let full_mod_name = vm.ctx.new_utf8_str(format!("{}.{name}", mod_name.as_str())); + let sys_modules = vm.sys_modules(); + sys_modules.get_item(&*full_mod_name, vm).ok() + })(); + + if let Some(sub_module) = fallback_module { + return Ok(sub_module); + } + + use crate::import::{get_spec_file_origin, is_possibly_shadowing_path, is_stdlib_module_name}; + + // Get module name for the error message + let mod_name_obj = module.get_attr(identifier!(vm, __name__), vm).ok(); + let mod_name = mod_name_obj + .as_ref() + .and_then(|n| n.downcast_ref::()); + let module_name = mod_name.map_or("", |s| s.as_str()); + + let spec = vm.get_attribute_opt(module, vm.ctx.intern_str("__spec__"))?; + + let origin = get_spec_file_origin(spec.as_deref(), vm)?; + + let is_possibly_shadowing = origin + .as_ref() + .is_some_and(|o| is_possibly_shadowing_path(o, vm)); + let is_possibly_shadowing_stdlib = if is_possibly_shadowing { + if let Some(ref mod_name) = mod_name_obj { + is_stdlib_module_name(mod_name, vm)? + } else { + false + } + } else { + false + }; + + let msg = if is_possibly_shadowing_stdlib { + let origin = origin.as_ref().unwrap(); + format!( + "cannot import name '{name}' from '{module_name}' \ + (consider renaming '{origin}' since it has the same \ + name as the standard library module named '{module_name}' \ + and prevents importing that standard library module)" + ) + } else { + let is_init = is_spec_initializing(spec.as_deref(), vm)?; + if is_init { + if is_possibly_shadowing { + let origin = origin.as_ref().unwrap(); + format!( + "cannot import name '{name}' from '{module_name}' \ + (consider renaming '{origin}' if it has the same name \ + as a library you intended to import)" + ) + } else if let Some(ref path) = origin { + format!( + "cannot import name '{name}' from partially initialized module \ + '{module_name}' (most likely due to a circular import) ({path})" + ) + } else { + format!( + "cannot import name '{name}' from partially initialized module \ + '{module_name}' (most likely due to a circular import)" + ) + } + } else if let Some(ref path) = origin { + format!("cannot import name '{name}' from '{module_name}' ({path})") + } else { + format!("cannot import name '{name}' from '{module_name}' (unknown location)") + } + }; + let err = vm.new_import_error( + msg, + match mod_name { + Some(s) => s.to_owned().into_wtf8(), + None => vm.ctx.new_utf8_str("").into_wtf8(), + }, + ); + + if let Some(ref path) = origin { + let _ignore = err.as_object().set_attr("path", path.clone(), vm); + } + + // name_from = the attribute name that failed to import (best-effort metadata) + let _ignore = err.as_object().set_attr("name_from", name.to_owned(), vm); + + Err(err) +} diff --git a/crates/vm/src/intern.rs b/crates/vm/src/intern.rs index bc8209397c3..a12130ced18 100644 --- a/crates/vm/src/intern.rs +++ b/crates/vm/src/intern.rs @@ -56,7 +56,6 @@ impl StringPool { let cache = CachedPyStrRef { inner: s }; let mut inner = zelf.inner.write(); if inner.insert(cache.clone()) { - drop(inner); let interned = unsafe { cache.as_interned_str() }; // `mark_intern` also makes the object immortal: the pool // never gives an entry up and its refcount could already never @@ -65,6 +64,7 @@ impl StringPool { // read-modify-write off every incref and decref of an // attribute name, a dict key or a docstring. unsafe { interned.as_object().mark_intern() }; + // Publish the interned flag before another lookup can return this entry. interned } else { unsafe { diff --git a/crates/vm/src/iter.rs b/crates/vm/src/iter.rs index 9d364f83f4c..146165ce146 100644 --- a/crates/vm/src/iter.rs +++ b/crates/vm/src/iter.rs @@ -1,4 +1,9 @@ -use crate::{PyObject, PyObjectRef, PyResult, types::PyComparisonOp, vm::VirtualMachine}; +use crate::{ + PyObject, PyObjectRef, PyResult, + function::{Either, PyComparisonValue}, + types::PyComparisonOp, + vm::VirtualMachine, +}; use itertools::Itertools; pub trait PyExactSizeIterator<'a>: ExactSizeIterator + Sized { @@ -21,32 +26,20 @@ pub trait PyExactSizeIterator<'a>: ExactSizeIterator + Size other: impl PyExactSizeIterator<'a>, op: PyComparisonOp, vm: &VirtualMachine, - ) -> PyResult { - let less = match op { - PyComparisonOp::Eq => return PyExactSizeIterator::eq(self, other, vm), - PyComparisonOp::Ne => return PyExactSizeIterator::eq(self, other, vm).map(|eq| !eq), - PyComparisonOp::Lt | PyComparisonOp::Le => true, - PyComparisonOp::Gt | PyComparisonOp::Ge => false, - }; - - let lhs = self; - let rhs = other; - let lhs_len = lhs.len(); - let rhs_len = rhs.len(); - for (a, b) in lhs.zip(rhs) { - if vm.bool_eq(a, b)? { + ) -> PyResult> { + let lhs_len = self.len(); + let rhs_len = other.len(); + // Tuple comparison visits the common prefix even for unequal lengths. + for (a, b) in self.zip(other) { + if vm.identical_or_equal(a, b)? { continue; } - let ret = if less { - vm.bool_seq_lt(a, b)? - } else { - vm.bool_seq_gt(a, b)? + return match op.eval_eq(|| false) { + Some(equal) => Ok(Either::B(equal.into())), + None => a.rich_compare(b, op, vm).map(Either::A), }; - if let Some(v) = ret { - return Ok(v); - } } - Ok(op.eval_ord(lhs_len.cmp(&rhs_len))) + Ok(Either::B(op.eval_ord(lhs_len.cmp(&rhs_len)).into())) } } diff --git a/crates/vm/src/lazy_import.rs b/crates/vm/src/lazy_import.rs new file mode 100644 index 00000000000..cc0c1e88f44 --- /dev/null +++ b/crates/vm/src/lazy_import.rs @@ -0,0 +1,913 @@ +//! Native PEP 810 deferred bindings. Dictionaries themselves always expose raw values. + +use crate::{ + AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + builtins::{ + PyBaseException, PyCode, PyDict, PyModule, PySet, PyStr, PyStrRef, PyTuple, PyType, + }, + class::PyClassImpl, + common::{ + lock::{OnceCell, PyMutex}, + wtf8::{Wtf8, Wtf8Buf, wtf8_concat}, + }, + frame, + types::{Constructor, GetAttr, Representable}, +}; +use core::sync::atomic::{AtomicBool, Ordering}; +use std::collections::HashMap; + +type PendingChildren = HashMap>>; + +fn split_parent(name: &Wtf8) -> Option<(&Wtf8, &Wtf8)> { + let dot = name.as_bytes().iter().rposition(|&byte| byte == b'.')?; + // ASCII dots always delimit code points, including next to surrogates. + Some((&name[..dot], &name[dot + 1..])) +} + +pub(crate) struct LazyImportsState { + pub(crate) modules: PyRef, + pub(crate) default_callback: OnceCell, + pub(crate) all: AtomicBool, + filter: PyMutex>, + // Removed declarations must be dropped after releasing this lock. + pending: PyMutex>, +} + +impl LazyImportsState { + pub(crate) fn new(ctx: &Context) -> Self { + Self { + modules: PySet::default().into_ref(ctx), + default_callback: OnceCell::new(), + all: AtomicBool::new(false), + filter: PyMutex::default(), + pending: PyMutex::default(), + } + } + + pub(crate) fn filter(&self) -> Option { + self.filter.lock().clone() + } + + pub(crate) fn set_filter(&self, filter: Option) { + // A removed callable's finalizer can re-enter this API. + let _old = core::mem::replace(&mut *self.filter.lock(), filter); + } + + fn register( + &self, + name: &Py, + source: Option<&Py>, + vm: &VirtualMachine, + ) -> PyResult<()> { + let mut full = name.as_wtf8(); + while let Some((parent, child)) = split_parent(full) { + let cached = raw_imported_module(&vm.ctx.new_str(full), vm)?; + let value = if cached.as_ref().is_some_and(|value| !vm.is_none(value)) { + None + } else { + source.map(ToOwned::to_owned) + }; + let _replaced = { + let mut pending = self.pending.lock(); + let children = pending.entry(parent.to_owned()).or_default(); + if source.is_some() { + children.insert(child.to_owned(), value) + } else { + children.entry(child.to_owned()).or_insert(value); + None + } + }; + full = parent; + } + Ok(()) + } +} + +#[pyclass(module = false, name = "lazy_import", traverse)] +#[derive(Debug)] +pub(crate) struct PyLazyImport { + builtins: PyObjectRef, + name: PyStrRef, + // None is an import, a tuple is an import with fromlist, and a string is one member. + fromlist: Option, + // Attribute projections retain the placeholder returned by IMPORT_NAME. + source: Option>, + declaration: Option>, + #[pytraverse(skip)] + instruction: u32, + #[pytraverse(skip)] + active: AtomicBool, +} + +impl PyPayload for PyLazyImport { + fn class(ctx: &Context) -> &'static Py { + ctx.types.lazy_import_type + } +} + +impl PyLazyImport { + fn new(builtins: PyObjectRef, name: PyStrRef, fromlist: Option) -> Self { + let frame = frame::current_thread_iframe(); + let (declaration, instruction) = if frame.is_null() { + (None, 0) + } else { + // The thread's active frame is live for this call; retain its code, not the frame. + let frame = unsafe { &*frame }; + (Some(frame.code().to_owned()), frame.get_lasti()) + }; + Self { + builtins, + name, + fromlist, + source: None, + declaration, + instruction, + active: AtomicBool::new(false), + } + } + + fn projection(source: &Py, name: &Py) -> Self { + let mut projection = Self::new( + source.builtins.clone(), + source.name.clone(), + Some(name.to_owned().into()), + ); + projection.source = Some(source.to_owned()); + projection + } + + fn root_and_attrs(&self) -> (&Self, Vec) { + let mut root = self; + let mut attrs = Vec::new(); + while let Some(source) = &root.source { + let attr = root + .fromlist + .as_ref() + .unwrap() + .downcast_ref::() + .unwrap(); + attrs.push(attr.to_owned()); + root = source; + } + attrs.reverse(); + (root, attrs) + } + + fn has_fromlist(&self) -> bool { + self.fromlist.as_ref().is_some_and(|from| { + from.downcast_ref::() + .is_none_or(|t| !t.as_slice().is_empty()) + }) + } + + fn path(&self) -> Wtf8Buf { + let (root, attrs) = self.root_and_attrs(); + let mut name = if root.has_fromlist() { + root.name.as_wtf8().to_owned() + } else { + root.name + .as_wtf8() + .split(Wtf8::new(".")) + .next() + .unwrap() + .to_owned() + }; + for attr in attrs { + name.push_char('.'); + name.push_wtf8(attr.as_wtf8()); + } + name + } + + fn display_name(&self) -> Wtf8Buf { + if self.source.is_some() { + self.path() + } else if self.has_fromlist() { + wtf8_concat!(self.name.as_wtf8(), "...") + } else { + self.name.as_wtf8().to_owned() + } + } +} + +#[pyclass(with(Constructor, GetAttr, Representable), flags(IMMUTABLETYPE))] +impl Py { + /// Resolve this import and return its value without changing a containing dictionary. + #[pymethod] + fn resolve(&self, vm: &VirtualMachine) -> PyResult { + resolve(self, vm) + } +} + +impl Constructor for PyLazyImport { + type Args = crate::function::FuncArgs; + fn py_new(_cls: &Py, _args: Self::Args, vm: &VirtualMachine) -> PyResult { + Err(vm.new_type_error("cannot create 'lazy_import' instances")) + } +} + +impl GetAttr for PyLazyImport { + fn getattro(zelf: &Py, name: &Py, vm: &VirtualMachine) -> PyResult { + if let Some(value) = zelf.as_object().generic_getattr_opt(name, None, vm)? { + return Ok(value); + } + Err(vm.new_attribute_error(wtf8_concat!( + "cannot access attribute ", + name.as_object().repr(vm)?.as_wtf8(), + " on unresolved lazy import ", + vm.ctx.new_str(zelf.display_name()).repr(vm)?, + ))) + } +} + +impl Representable for PyLazyImport { + fn repr_wtf8(zelf: &Py, _vm: &VirtualMachine) -> PyResult { + Ok(wtf8_concat!("")) + } +} + +pub(crate) fn init_type(ctx: &'static Context) { + PyLazyImport::extend_class(ctx, ctx.types.lazy_import_type); +} + +pub(crate) fn is_module_level() -> bool { + let frame = frame::current_thread_iframe(); + if frame.is_null() { + return false; + } + let frame = unsafe { &*frame }; + frame + .locals + .get() + .is_some_and(|locals| frame.globals().as_object().is(locals.obj())) +} + +fn optional_item( + mapping: &PyObject, + name: &Py, + vm: &VirtualMachine, +) -> PyResult> { + match mapping.get_item(name, vm) { + Ok(value) => Ok(Some(value)), + Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.key_error) => Ok(None), + Err(exc) => Err(exc), + } +} + +pub(crate) fn import_name( + name: &Py, + fromlist: PyObjectRef, + level: usize, + policy: u32, + vm: &VirtualMachine, +) -> PyResult { + if policy & 2 != 0 { + return vm.import_from(name, fromlist, level); + } + let explicit = policy & 1 != 0; + let globals = vm.current_globals(); + let mut lazy = + explicit || (vm.state.lazy_imports.all.load(Ordering::Acquire) && is_module_level()); + if !lazy + && is_module_level() + && let Some(names) = optional_item( + globals.as_object(), + vm.ctx.intern_str("__lazy_modules__"), + vm, + )? + { + let absolute = + crate::import::absolute_import_name(name, Some(globals.as_object()), level as i32, vm)?; + lazy = names + .sequence_unchecked() + .contains(absolute.as_object(), vm)?; + } + if !lazy { + return vm.import_from(name, fromlist, level); + } + let builtins = frame::current_builtins().unwrap_or_else(|| vm.builtins.dict().into()); + let callback = optional_item(&builtins, vm.ctx.intern_str("__lazy_import__"), vm)? + .ok_or_else(|| vm.new_import_error("__lazy_import__ not found", name.to_owned()))?; + if vm + .state + .lazy_imports + .default_callback + .get() + .is_some_and(|default| callback.is(default)) + { + return create( + name, + globals.as_object(), + Some(fromlist), + level as i32, + builtins, + vm, + ); + } + let locals: PyObjectRef = vm.current_locals()?.into(); + callback.call((name.to_owned(), globals, locals, fromlist, level), vm) +} + +pub(crate) fn create( + name: &Py, + globals: &PyObject, + fromlist: Option, + level: i32, + builtins: PyObjectRef, + vm: &VirtualMachine, +) -> PyResult { + let absolute = crate::import::absolute_import_name(name, Some(globals), level, vm)?; + if !is_module_level() { + return Err(vm.new_exception_msg( + vm.ctx.exceptions.syntax_error.to_owned(), + "'lazy import' is only allowed at module level".into(), + )); + } + let fromlist = match fromlist.filter(|value| !vm.is_none(value)) { + Some(value) if value.downcast_ref::().is_some() => { + Some(PyTuple::new_ref(vec![value], &vm.ctx).into()) + } + value => value, + }; + if let Some(filter) = vm.state.lazy_imports.filter() { + let globals_dict = crate::builtins::PyAnyDict::from_object(globals) + .ok_or_else(|| vm.new_type_error("globals must be a dict or a frozendict"))?; + let importer = globals_dict + .inner_getitem_opt(identifier!(vm, __name__), vm)? + .unwrap_or_else(|| vm.ctx.none()); + let from = fromlist.clone().unwrap_or_else(|| vm.ctx.none()); + if !filter + .call((importer, absolute.clone(), from), vm)? + .try_to_bool(vm)? + { + return crate::import::import_module_level(name, Some(globals), fromlist, level, vm); + } + } + if let Some(value) = &fromlist { + let Some(names) = value.downcast_ref::() else { + return Err( + vm.new_type_error("lazy_import: fromlist must be None, a string, or a tuple") + ); + }; + for name in names.as_slice() { + if name.downcast_ref::().is_none() { + return Err(vm.new_type_error(format!( + "Item in ``from list'' must be str, not {:.200}", + name.class().name() + ))); + } + } + } + let deferred = + PyLazyImport::new(builtins, absolute.clone(), fromlist.clone()).into_ref(&vm.ctx); + let state = &vm.state.lazy_imports; + let existing = track_module(&absolute, vm)?; + if let Some(names) = fromlist + .as_ref() + .and_then(|value| value.downcast_ref::()) + && !names.as_slice().is_empty() + { + for name in names.as_slice() { + let name = name.downcast_ref::().unwrap(); + // Cached attributes are concrete or tracked by their own placeholder. + if let Some(module) = existing.as_ref().and_then(|m| m.downcast_ref::()) + && module.dict().get_item_opt(name, vm)?.is_some() + { + continue; + } + let fullname = vm + .ctx + .new_str(wtf8_concat!(absolute.as_wtf8(), '.', name.as_wtf8())); + track_module(&fullname, vm)?; + state.register(&fullname, None, vm)?; + } + } else { + state.register(&absolute, Some(&deferred), vm)?; + } + Ok(deferred.into()) +} + +pub(crate) fn import_from( + deferred: &Py, + name: &Py, + vm: &VirtualMachine, +) -> PyResult { + if deferred.source.is_none() + && deferred.has_fromlist() + && let Some(value) = loaded_attr(&deferred.name, name, vm)? + { + return Ok(value); + } + Ok(PyLazyImport::projection(deferred, name) + .into_ref(&vm.ctx) + .into()) +} + +struct ResolvingGuard<'a> { + vm: &'a VirtualMachine, + identity: usize, +} + +impl Drop for ResolvingGuard<'_> { + fn drop(&mut self) { + self.vm + .lazy_imports_resolving + .borrow_mut() + .remove(&self.identity); + } +} + +pub(crate) fn is_resolving(deferred: &Py, vm: &VirtualMachine) -> bool { + vm.lazy_imports_resolving + .borrow() + .contains(&deferred.as_object().get_id()) +} + +fn raw_imported_module(name: &Py, vm: &VirtualMachine) -> PyResult> { + let modules = vm.sys_modules(); + optional_item(&modules, name, vm) +} + +// Tracking must not invoke module/spec descriptors or convert a flag to bool. +fn track_module(name: &Py, vm: &VirtualMachine) -> PyResult> { + let module = raw_imported_module(name, vm)?; + let loaded = if let Some(module) = module.as_ref().and_then(|m| m.downcast_ref::()) { + let spec = module + .dict() + .get_item_opt(vm.ctx.intern_str("__spec__"), vm)?; + match spec { + None => true, + Some(spec) if vm.is_none(&spec) => true, + Some(spec) if spec.has_inline_values() => { + let initializing = match spec.dict() { + Some(dict) => dict.get_item_opt(vm.ctx.intern_str("_initializing"), vm)?, + None => None, + }; + initializing.is_none_or(|flag| flag.is(&vm.ctx.false_value)) + } + Some(_) => false, + } + } else { + module.as_ref().is_some_and(|module| !vm.is_none(module)) + }; + if !loaded { + vm.state + .lazy_imports + .modules + .add(name.to_owned().into(), vm)?; + } + Ok(module) +} + +// Attribute caching may inspect __spec__, but never waits for module imports. +fn loaded_attr( + name: &Py, + attr: &Py, + vm: &VirtualMachine, +) -> PyResult> { + let lookup = || -> PyResult> { + let modules = vm.sys_modules(); + let Some(module) = optional_item(&modules, name, vm)? else { + return Ok(None); + }; + let Some(module) = module.downcast_ref::() else { + return Ok(None); + }; + if crate::import::is_module_initializing(module.as_object(), vm)? { + return Ok(None); + } + if !optional_item(&modules, name, vm)?.is_some_and(|m| m.is(module)) { + return Ok(None); + } + Ok(module + .dict() + .get_item_opt(attr, vm)? + .filter(|value| value.downcast_ref_if_exact::(vm).is_none())) + }; + match lookup() { + Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.exception_type) => Ok(None), + result => result, + } +} + +fn add_declaration_context( + deferred: &PyLazyImport, + exc: &Py, + vm: &VirtualMachine, +) { + let Some(code) = &deferred.declaration else { + return; + }; + let offset = deferred.instruction.saturating_sub(1) as usize; + let location = code.locations.get(offset).map(|(location, _)| location); + if exc.__cause__().is_some() || exc.__context__().is_some() || exc.__suppress_context__() { + let note = vm.ctx.new_str(wtf8_concat!( + "lazy import of '", + deferred.display_name(), + format!( + "' declared in {} at {}:{}", + code.obj_name, + code.source_path(), + location.map_or(0, |location| location.line.get()), + ), + )); + // Adding diagnostic context must not replace the original resolution error. + let _ = (|| -> PyResult<()> { + if let Some(notes) = + vm.get_attribute_opt(exc.as_object(), vm.ctx.intern_str("__notes__"))? + && notes.sequence_unchecked().contains(note.as_object(), vm)? + { + return Ok(()); + } + exc.add_note_str(note, vm) + })(); + return; + } + let cause = vm.new_import_error( + wtf8_concat!( + "lazy import of '", + deferred.display_name(), + "' raised an exception during resolution", + ), + deferred.name.clone(), + ); + if let Some(location) = location { + let globals = vm.ctx.new_dict(); + let frame = frame::FrameObject::new_ref( + code.clone(), + crate::scope::Scope::new(None, globals), + deferred.builtins.clone(), + &[], + None, + false, + vm, + ); + frame.set_lasti(deferred.instruction); + let tb = crate::builtins::PyTraceback::new(None, frame, (offset * 2) as i32, location.line) + .into_ref(&vm.ctx); + cause.set_traceback(Some(tb)); + } + exc.set_cause(Some(cause)); +} + +fn resolve_impl( + deferred: &Py, + vm: &VirtualMachine, +) -> PyResult<(PyObjectRef, Option)> { + let (root, attrs) = deferred.root_and_attrs(); + if is_resolving(deferred, vm) { + let exc = vm.new_exception_msg( + vm.ctx.exceptions.import_cycle_error.to_owned(), + wtf8_concat!( + "cannot import name ", + vm.ctx.new_str(deferred.display_name()).repr(vm)?, + " (most likely due to a circular import)", + ), + ); + exc.as_object().set_attr("name", root.name.clone(), vm)?; + return Err(exc); + } + vm.with_recursion(" while resolving a lazy import", || { + let identity = deferred.as_object().get_id(); + vm.lazy_imports_resolving.borrow_mut().insert(identity); + let _resolving = ResolvingGuard { vm, identity }; + let result = (|| -> PyResult<(PyObjectRef, Option)> { + let callback = optional_item(&root.builtins, vm.ctx.intern_str("__import__"), vm)? + .ok_or_else(|| vm.new_import_error("__import__ not found", root.name.clone()))?; + let default_import = callback.is(&vm.import_func); + let fromlist = match attrs.first().filter(|_| root.has_fromlist()) { + Some(first) => PyTuple::new_ref(vec![first.clone().into()], &vm.ctx).into(), + None => root.fromlist.clone().unwrap_or_else(|| vm.ctx.none()), + }; + let mut name = root.name.clone(); + let fullname = root.name.as_wtf8(); + if attrs.is_empty() + && !root.has_fromlist() + && default_import + && root.builtins.is(vm.builtins.dict().as_object()) + && let Some(dot) = fullname.as_bytes().iter().position(|&byte| byte == b'.') + { + let mut regular = true; + let mut complete = true; + for (dot, _) in fullname + .as_bytes() + .iter() + .enumerate() + .filter(|(_, byte)| **byte == b'.') + { + let prefix = vm.ctx.new_str(&fullname[..dot]); + let Some(cached) = loaded_attr(&prefix, identifier!(vm, __name__), vm)? else { + complete = false; + break; + }; + regular = loaded_attr(&prefix, vm.ctx.intern_str("__path__"), vm)?.is_some() + && cached + .downcast_ref::() + .is_some_and(|s| s.as_wtf8() == prefix.as_wtf8()); + if !regular { + break; + } + } + let loaded = loaded_attr(&name, identifier!(vm, __name__), vm)?; + if regular && (!complete || loaded.is_none()) { + name = vm.ctx.new_str(&fullname[..dot]); + } + } + let globals = frame::current_globals() + .map_or_else(|| vm.ctx.none(), |g| g.as_object().to_owned()); + let import = |name: &PyStrRef| { + callback + .call( + ( + name.clone(), + globals.clone(), + globals.clone(), + fromlist.clone(), + 0i32, + ), + vm, + ) + .inspect_err(|exc| crate::import::remove_importlib_frames(vm, exc)) + }; + let mut module = import(&name)?; + if !name.is(&root.name) { + root.active.store(true, Ordering::Relaxed); + let package = match module.downcast_ref_if_exact::(vm) { + Some(module) => module + .dict() + .get_item_opt(vm.ctx.intern_str("__path__"), vm)? + .is_some(), + None => false, + }; + if !package { + module = import(&root.name)?; + } + } else if default_import { + clear_submodule(&name, false, vm)?; + } + let root_value = resolve_value(module, vm)?; + let imported_module = + if default_import && root_value.downcast_ref::().is_some() { + Some(root_value.clone()) + } else { + None + }; + // A custom importer's root must survive all projected attribute lookups. + let mut value = root_value.clone(); + for attr in attrs { + value = + resolve_value(crate::import::import_from_attribute(&value, &attr, vm)?, vm)?; + } + drop(root_value); + vm.state + .lazy_imports + .modules + .discard(vm.ctx.new_str(deferred.path()).into(), vm)?; + Ok((value, imported_module)) + })(); + result.inspect_err(|exc| add_declaration_context(deferred, exc, vm)) + }) +} + +pub(crate) fn resolve(deferred: &Py, vm: &VirtualMachine) -> PyResult { + resolve_impl(deferred, vm).map(|(value, _)| value) +} + +pub(crate) fn resolve_value(value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + match value.downcast_ref_if_exact::(vm) { + Some(deferred) => resolve(deferred, vm), + None => Ok(value), + } +} + +pub(crate) fn reify( + deferred: &Py, + name: &Py, + namespace: &PyObject, + vm: &VirtualMachine, +) -> PyResult { + let (value, imported_module) = resolve_impl(deferred, vm)?; + if let Some(dict) = namespace.downcast_ref_if_exact::(vm) { + let replaced = dict.replace_if_identity(name, deferred.as_object(), value.clone(), vm)?; + if !replaced + && deferred.source.is_some() + && let Some(child) = imported_module + { + let (root, _) = deferred.root_and_attrs(); + if let Some((parent_name, child_name)) = split_parent(root.name.as_wtf8()) + && name.as_wtf8() == child_name + && let Some(parent) = raw_imported_module(&vm.ctx.new_str(parent_name), vm)? + && let Some(parent) = parent.downcast_ref::() + && parent.dict().as_object().is(namespace) + { + dict.replace_if_identity(name, &child, value.clone(), vm)?; + } + } + } else if namespace + .mapping_unchecked() + .slots() + .ass_subscript + .load() + .is_some() + && optional_item(namespace, name, vm)?.is_some_and(|current| current.is(deferred)) + { + namespace.set_item(name, value.clone(), vm)?; + } + Ok(value) +} + +pub(crate) fn reify_value( + value: PyObjectRef, + name: &Py, + namespace: &PyObject, + vm: &VirtualMachine, +) -> PyResult { + match value.downcast_ref_if_exact::(vm) { + Some(deferred) => reify(deferred, name, namespace, vm), + None => Ok(value), + } +} + +pub(crate) fn resolved_dict_item( + dict: &Py, + name: &Py, + vm: &VirtualMachine, +) -> PyResult> { + let Some(value) = dict.inner_getitem_opt(name, vm)? else { + return Ok(None); + }; + if let Some(deferred) = value.downcast_ref_if_exact::(vm) { + if is_resolving(deferred, vm) { + return Ok(None); + } + return reify(deferred, name, dict.as_object(), vm).map(Some); + } + Ok(Some(value)) +} + +fn load_child(source: &Py, name: &Py, vm: &VirtualMachine) -> PyResult { + vm.with_recursion(" while resolving a lazy import", || { + let mut child = PyLazyImport::new(source.builtins.clone(), name.to_owned(), None); + child.declaration = None; + for attr in name.as_wtf8().split(Wtf8::new(".")).skip(1) { + child = PyLazyImport::projection(&child.into_ref(&vm.ctx), &vm.ctx.new_str(attr)); + child.declaration = None; + } + child.declaration.clone_from(&source.declaration); + child.instruction = source.instruction; + let result = resolve(&child.into_ref(&vm.ctx), vm)?; + if let Some(module) = result.downcast_ref::() + && source.name.as_wtf8() != name.as_wtf8() + && module + .dict() + .get_item_opt(vm.ctx.intern_str("__path__"), vm)? + .is_none() + { + return load_child(source, &source.name, vm); + } + Ok(result) + }) +} + +// Keep pending names while their parent is initializing, without retaining +// completed declarations and their namespace mappings indefinitely. +pub(crate) fn clear_submodule(name: &Py, bind: bool, vm: &VirtualMachine) -> PyResult<()> { + let Some((parent_name, child)) = split_parent(name.as_wtf8()) else { + return Ok(()); + }; + let state = &vm.state.lazy_imports; + if !state + .pending + .lock() + .get(parent_name) + .is_some_and(|children| children.contains_key(child)) + { + return Ok(()); + } + if let Some(loaded) = raw_imported_module(name, vm)? { + match crate::import::is_module_initializing(&loaded, vm) { + Ok(true) => return Ok(()), + Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.exception_type) => return Ok(()), + Err(exc) => return Err(exc), + Ok(false) => {} + } + } + let parent = raw_imported_module(&vm.ctx.new_str(parent_name), vm)?; + let initializing = match &parent { + Some(parent) => crate::import::is_module_initializing(parent, vm)?, + None => false, + }; + if bind + && !initializing + && let Some(parent) = parent + .as_ref() + .and_then(|p| p.downcast_ref_if_exact::(vm)) + && let Some(value) = raw_imported_module(name, vm)? + && !vm.is_none(&value) + { + parent + .dict() + .setdefault_value(vm.ctx.new_str(child).into(), value, vm)?; + } + let _removed = { + let mut pending = state.pending.lock(); + if let Some(children) = pending.get_mut(parent_name) { + if initializing { + children.get_mut(child).and_then(Option::take) + } else { + children.remove(child).flatten() + } + } else { + None + } + }; + Ok(()) +} + +pub(crate) fn try_load_submodule( + module: &Py, + name: &Py, + suppress: bool, + vm: &VirtualMachine, +) -> PyResult> { + let Some(module_name) = module.dict().get_item_opt(identifier!(vm, __name__), vm)? else { + return Ok(None); + }; + let Some(module_name) = module_name.downcast_ref::() else { + return Ok(None); + }; + let module_name = module_name.as_wtf8(); + let child = name.as_wtf8(); + let source = vm + .state + .lazy_imports + .pending + .lock() + .get(module_name) + .and_then(|children| children.get(child).cloned()); + let Some(source) = source else { + return Ok(None); + }; + let fullname = vm.ctx.new_str(wtf8_concat!(module_name, '.', child)); + let imported = (|| { + if let Some(source) = &source + && !suppress + && (source.active.load(Ordering::Relaxed) + || module + .dict() + .get_item_opt(identifier!(vm, __getattr__), vm)? + .is_none()) + { + load_child(source, &fullname, vm) + } else { + if let Some(loaded) = raw_imported_module(&fullname, vm)? + && !vm.is_none(&loaded) + { + return Ok(loaded); + } + crate::import::find_and_load(&fullname, "_find_and_load_lazy_submodule", vm) + } + })(); + let imported = match imported { + Ok(imported) => imported, + Err(exc) => { + if let Ok(Some(loaded)) = raw_imported_module(&fullname, vm) + && !vm.is_none(&loaded) + { + let _ = PyDict::hash_or_unhashable(name, vm).and_then(|hash| { + module + .dict() + .entries + .delete_if(vm, name, hash, |value| Ok(value.is(&loaded))) + }); + let mut pending = vm.state.lazy_imports.pending.lock(); + pending + .entry(module_name.to_owned()) + .or_default() + .entry(child.to_owned()) + .or_insert_with(|| source.clone()); + } + crate::import::remove_importlib_frames(vm, &exc); + return Err(exc); + } + }; + if vm.is_none(&imported) { + return Ok(None); + } + let initializing = match crate::import::is_module_initializing(&imported, vm) { + Ok(initializing) => initializing, + Err(exc) if exc.fast_isinstance(vm.ctx.exceptions.exception_type) => false, + Err(exc) => return Err(exc), + }; + if !initializing { + module.dict().set_item(name, imported.clone(), vm)?; + let _removed = vm + .state + .lazy_imports + .pending + .lock() + .get_mut(module_name) + .and_then(|children| children.remove(child)); + } + Ok(Some(imported)) +} diff --git a/crates/vm/src/lib.rs b/crates/vm/src/lib.rs index c6813f63e3a..3a087960444 100644 --- a/crates/vm/src/lib.rs +++ b/crates/vm/src/lib.rs @@ -60,6 +60,7 @@ pub mod convert; mod coroutine; pub mod datastack; mod dict_inner; +mod unicode_names; #[cfg(feature = "rustpython-compiler")] pub mod eval; @@ -68,11 +69,13 @@ mod exception_group; pub mod exceptions; pub mod format; pub mod frame; +pub mod frozen_resources; pub mod function; pub mod getpath; pub mod import; mod intern; pub mod iter; +pub(crate) mod lazy_import; pub mod object; #[cfg(feature = "host_env")] diff --git a/crates/vm/src/object/core.rs b/crates/vm/src/object/core.rs index eb7edc93cca..0af1aa777ec 100644 --- a/crates/vm/src/object/core.rs +++ b/crates/vm/src/object/core.rs @@ -1,15 +1,3 @@ -//! Essential types for object models -//! -//! +-------------------------+--------------+-----------------------+ -//! | Management | Typed | Untyped | -//! +-------------------------+------------------+-------------------+ -//! | Interpreter-independent | [`Py`] | [`PyObject`] | -//! | Reference-counted | [`PyRef`] | [`PyObjectRef`] | -//! | Weak | [`PyWeakRef`] | [`PyRef`] | -//! +-------------------------+--------------+-----------------------+ -//! -//! [`PyRef`] may looking like to be called as PyObjectWeak by the rule, -//! but not to do to remember it is a PyRef object. use super::{ PyAtomicRef, ext::{AsObject, PyRefExact, PyResult}, @@ -156,6 +144,10 @@ mod trashcan { item }; if let Some((obj, dealloc)) = next { + // A queued deallocator may defer more objects, but its + // end() must not start another drain. + t.depth.set(1); + let _draining = scopeguard::guard((), |()| t.depth.set(0)); unsafe { dealloc(obj) }; } else { break; @@ -163,6 +155,34 @@ mod trashcan { } }) } + + #[cfg(test)] + mod tests { + use super::*; + + unsafe fn assert_guarded_dealloc(_: *mut super::super::PyObject) { + assert!(TRASHCAN.with(|t| t.depth.get() > 0)); + } + + #[test] + fn deferred_deallocations_remain_guarded() { + // This callback never dereferences its opaque object pointer. + let obj = core::ptr::null_mut(); + unsafe { + for _ in 0..TRASHCAN_LIMIT { + assert!(begin(obj, assert_guarded_dealloc)); + } + assert!(!begin(obj, assert_guarded_dealloc)); + for _ in 0..TRASHCAN_LIMIT { + end(); + } + } + TRASHCAN.with(|t| { + assert_eq!(t.depth.get(), 0); + assert!(t.queue.take().is_empty()); + }); + } + } } /// Default dealloc: handles __del__, weakref clearing, tp_clear, and memory free. @@ -173,17 +193,14 @@ pub(super) unsafe fn default_dealloc(obj: *mut PyObject) { return; // resurrected by __del__ } - // Only tracked objects take the trashcan recursion guard and untrack path. - // Untracked objects either own no children (int, float, str, ...) or, like - // non-escaped frames, are released at interpreter depth with at most one - // unguarded link before their tracked children (dicts, functions, code) - // re-enter guarded deallocation, so recursion stays bounded. A frame stored - // in an object graph is forced to escape, becoming tracked and guarded here. - // Read once and reuse for both gates below. + // Untracked payloads can still own recursive chains of references, such as + // detached frames returned by sys._current_frames(). Guard traversable + // payloads regardless of tracking, while keeping scalar deallocation cheap. let tracked = obj_ref.is_gc_tracked(); + let guarded = tracked || T::HAS_TRAVERSE; // Trashcan: limit recursive deallocation depth to prevent stack overflow - if tracked && !unsafe { trashcan::begin(obj, default_dealloc::) } { + if guarded && !unsafe { trashcan::begin(obj, default_dealloc::) } { return; // deferred to queue } @@ -213,11 +230,17 @@ pub(super) unsafe fn default_dealloc(obj: *mut PyObject) { // them. Some payloads (e.g. FrameObject) drop children in place inside clear_fn // instead of extracting them, so user code (`__del__`) may run here. let mut edges = Vec::new(); - if let Some(clear_fn) = vtable.clear { + if (T::CLEAR_ON_DEALLOC || T::HAS_FREELIST) + && let Some(clear_fn) = vtable.clear + { unsafe { clear_fn(obj, &mut edges) }; } // Drop extracted child references - may trigger recursive destruction. - drop(edges); + if T::REVERSE_DEALLOC { + edges.into_iter().rev().for_each(drop); + } else { + drop(edges); + } // Try to store in freelist for reuse. This must happen AFTER clear_fn and // after the extracted-children drop: both can run user code (`__del__`) @@ -262,7 +285,7 @@ pub(super) unsafe fn default_dealloc(obj: *mut PyObject) { } // Trashcan: decrement depth and process deferred objects at outermost level - if tracked { + if guarded { unsafe { trashcan::end() }; } } @@ -596,6 +619,9 @@ unsafe impl Traverse for PyObject { } // === Stripe lock for weakref list protection (WEAKREF_LIST_LOCK) === +// Like CPython's _Py_LOCK_DONT_DETACH weakref stripes, these critical sections +// must not run Python, release Python references, or suspend an attached thread. +// Traversal visitors must not recursively acquire a weakref stripe. #[cfg(feature = "threading")] mod weakref_lock { @@ -605,29 +631,46 @@ mod weakref_lock { static LOCKS: [AtomicU8; NUM_WEAKREF_LOCKS] = [const { AtomicU8::new(0) }; NUM_WEAKREF_LOCKS]; + #[derive(Debug)] + pub(super) struct WeakrefLock { + lock: &'static AtomicU8, + } + pub(super) struct WeakrefLockGuard { - idx: usize, + lock: &'static AtomicU8, } impl Drop for WeakrefLockGuard { fn drop(&mut self) { - LOCKS[self.idx].store(0, Ordering::Release); + self.lock.store(0, Ordering::Release); } } - pub(super) fn lock(addr: usize) -> WeakrefLockGuard { - let idx = (addr >> 4) % NUM_WEAKREF_LOCKS; - loop { - if LOCKS[idx] - .compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed) - .is_ok() - { - return WeakrefLockGuard { idx }; + impl WeakrefLock { + pub(super) fn lock(&self) -> WeakrefLockGuard { + loop { + if self + .lock + .compare_exchange_weak(0, 1, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + { + return WeakrefLockGuard { lock: self.lock }; + } + core::hint::spin_loop(); } - core::hint::spin_loop(); } } + pub(super) fn select(addr: usize) -> WeakrefLock { + WeakrefLock { + lock: &LOCKS[(addr >> 4) % NUM_WEAKREF_LOCKS], + } + } + + pub(super) fn lock(addr: usize) -> WeakrefLockGuard { + select(addr).lock() + } + /// Reset all weakref stripe locks after fork in child process. /// Locks held by parent threads would cause infinite spin in the child. #[cfg(all(unix, feature = "host_env"))] @@ -640,14 +683,27 @@ mod weakref_lock { #[cfg(not(feature = "threading"))] mod weakref_lock { + #[derive(Debug)] + pub(super) struct WeakrefLock; + pub(super) struct WeakrefLockGuard; impl Drop for WeakrefLockGuard { fn drop(&mut self) {} } - pub(super) fn lock(_addr: usize) -> WeakrefLockGuard { - WeakrefLockGuard + impl WeakrefLock { + pub(super) fn lock(&self) -> WeakrefLockGuard { + WeakrefLockGuard + } + } + + pub(super) fn select(_addr: usize) -> WeakrefLock { + WeakrefLock + } + + pub(super) fn lock(addr: usize) -> WeakrefLockGuard { + select(addr).lock() } } @@ -711,7 +767,7 @@ unsafe fn try_reuse_weakref(ptr: *mut Py) -> Option> { let node = unsafe { &*ptr }; node.ref_count .safe_inc() - .then(|| unsafe { PyRef::from_raw(ptr) }) + .then(|| unsafe { PyRef::::from_raw(ptr) }) } impl WeakRefList { @@ -750,12 +806,13 @@ impl WeakRefList { } } - // Allocate OUTSIDE the stripe lock. PyRef::new_ref may trigger - // maybe_collect → GC → WeakRefList::clear on another object that - // hashes to the same stripe, which would deadlock on the spinlock. + // Allocate untracked: gc.get_objects() must not expose this node + // before its referent is published. Tracking below can trigger GC, + // so it must also happen outside the stripe lock. let weak_payload = PyWeak { pointers: Pointers::new(), - wr_object: Radium::new(obj as *const PyObject as *mut PyObject), + wr_object: Radium::new(ptr::null_mut()), + weakrefs_lock: weakref_lock::select(obj as *const PyObject as usize), callback: UnsafeCell::new(callback), hash: Radium::new(crate::common::hash::SENTINEL), }; @@ -775,7 +832,7 @@ impl WeakRefList { None }; if let Some(existing) = existing { - // Nullify wr_object so drop_inner won't unlink an + // Nullify wr_object so clear_ref won't unlink an // un-inserted node (which would corrupt the list head). weak.wr_object.store(ptr::null_mut(), Ordering::Relaxed); return existing; @@ -799,6 +856,16 @@ impl WeakRefList { if is_generic { self.generic.store(node_ptr.as_ptr(), Ordering::Relaxed); } + // Only linked nodes may advertise a referent: an allocation unwind + // must never try to unlink an unpublished node. + weak.wr_object + .store(obj as *const PyObject as *mut PyObject, Ordering::Release); + + drop(_lock); + // SAFETY: this fresh allocation opted out of automatic tracking. + // Our strong reference keeps it alive, and it cannot enter a GC + // candidate list before tracking, so its gc_bits are still zero. + unsafe { crate::gc_state::track_new_object(NonNull::from(weak.as_object())) }; weak } @@ -843,7 +910,8 @@ impl WeakRefList { match NonNull::new(candidate_ptr) { Some(candidate) => { let node = unsafe { candidate.as_ref() }; - let has_callback = unsafe { (&*node.payload.callback.get()).is_some() }; + // SAFETY: the referent stripe is held by the caller. + let has_callback = unsafe { &*node.payload.callback.get() }.is_some(); let node_cls = node.class(); // PyWeakref_CheckProxy: the basic-proxy slot is reserved for // the canonical proxy type; subclasses and callback-less ref @@ -864,97 +932,98 @@ impl WeakRefList { /// Called when the owner object is being dropped. // PyObject_ClearWeakRefs fn clear(&self, obj: &PyObject) { - let obj_addr = obj as *const PyObject as usize; - let _lock = weakref_lock::lock(obj_addr); - - // Clear generic cache + // Owners precede the guard so unwinding also drops them after unlock. + let mut callbacks: Vec<(PyRef, Option)> = Vec::new(); + let _lock = weakref_lock::lock(obj as *const PyObject as usize); self.generic.store(ptr::null_mut(), Ordering::Relaxed); - - // Walk the list, collecting weakrefs with callbacks - let mut callbacks: Vec<(PyRef, PyObjectRef)> = Vec::new(); let mut current = NonNull::new(self.head.load(Ordering::Relaxed)); while let Some(node) = current { let next = unsafe { WeakLink::pointers(node).as_ref().get_next() }; - let wr = unsafe { node.as_ref() }; - - // Mark weakref as dead + // Reserve before acquiring a Python owner; push cannot then unwind. + callbacks.reserve(1); + if wr.ref_count.safe_inc() { + let owner = unsafe { PyRef::::from_raw(wr as *const Py) }; + callbacks.push((owner, None)); + // Keep the owner in the outer batch before taking its callback. + let entry = callbacks.last_mut().unwrap(); + // SAFETY: the referent stripe protects the callback as well. + entry.1 = unsafe { &mut *wr.payload.callback.get() }.take(); + } + unsafe { unlink_weakref(self, node) }; + // Publish death only after unlinking, while the original stripe + // still protects this node from a concurrent deallocator. wr.payload .wr_object - .store(ptr::null_mut(), Ordering::Relaxed); - - // Unlink from list - unsafe { - let mut ptrs = WeakLink::pointers(node); - ptrs.as_mut().set_prev(None); - ptrs.as_mut().set_next(None); + .store(ptr::null_mut(), Ordering::Release); + current = next; + } + drop(_lock); + for (wr, callback) in callbacks { + if let Some(cb) = callback { + crate::vm::thread::with_vm(&cb, |vm| { + let _raised = vm.preserve_raised_exception(); + if let Err(e) = cb.call((wr.clone(),), vm) { + vm.run_unraisable(e, Some("weakref callback".to_owned()), cb.clone()); + } + }); } + } + } - // Collect callback only if we can still acquire a strong ref. - if wr.ref_count.safe_inc() { - let wr_ref = unsafe { PyRef::from_raw(wr as *const Py) }; - let cb = unsafe { wr.payload.callback.get().replace(None) }; - if let Some(cb) = cb { - callbacks.push((wr_ref, cb)); + /// Clear callback-bearing weakrefs before finalizers. Retain callback + /// ownership on each weakref until its later tp_clear or deallocation. + fn clear_for_gc_collect_callbacks( + &self, + obj: &PyObject, + is_unreachable: &impl Fn(&PyObject) -> bool, + ) -> Vec<(PyRef, PyObjectRef)> { + let mut owners: Vec> = Vec::new(); + let mut callbacks = Vec::new(); + let _lock = weakref_lock::lock(obj as *const PyObject as usize); + let mut current = NonNull::new(self.head.load(Ordering::Relaxed)); + while let Some(node) = current { + let next = unsafe { WeakLink::pointers(node).as_ref().get_next() }; + let wr = unsafe { node.as_ref() }; + // SAFETY: the referent stripe protects this borrowed callback. + let callback = unsafe { &*wr.payload.callback.get() }; + if callback.is_some() { + owners.reserve(1); + callbacks.reserve(1); + if !is_unreachable(wr.as_object()) && wr.ref_count.safe_inc() { + let owner = unsafe { PyRef::::from_raw(wr as *const Py) }; + owners.push(owner); + let callback = callback.clone(); + if let Some(callback) = callback { + callbacks.push((owners.last().unwrap().clone(), callback)); + } } + unsafe { unlink_weakref(self, node) }; + // No node access after publishing null without a strong pin. + wr.payload + .wr_object + .store(ptr::null_mut(), Ordering::Release); } - current = next; } - self.head.store(ptr::null_mut(), Ordering::Relaxed); - - // Invoke callbacks outside the lock - drop(_lock); - for (wr, cb) in callbacks { - crate::vm::thread::with_vm(&cb, |vm| { - let _ = cb.call((wr.clone(),), vm); - }); - } + callbacks } - /// Clear all weakrefs but DON'T call callbacks. Instead, return them for later invocation. - /// Used by GC to ensure ALL weakrefs are cleared BEFORE any callbacks are invoked. - /// handle_weakrefs() clears all weakrefs first, then invokes callbacks. - fn clear_for_gc_collect_callbacks(&self, obj: &PyObject) -> Vec<(PyRef, PyObjectRef)> { - let obj_addr = obj as *const PyObject as usize; - let _lock = weakref_lock::lock(obj_addr); - - // Clear generic cache + /// Unlink remaining weakrefs without invoking or releasing callbacks. + fn clear_for_gc(&self, obj: &PyObject) { + let _lock = weakref_lock::lock(obj as *const PyObject as usize); self.generic.store(ptr::null_mut(), Ordering::Relaxed); - - let mut callbacks = Vec::new(); let mut current = NonNull::new(self.head.load(Ordering::Relaxed)); while let Some(node) = current { let next = unsafe { WeakLink::pointers(node).as_ref().get_next() }; - let wr = unsafe { node.as_ref() }; - - // Mark weakref as dead + unsafe { unlink_weakref(self, node) }; + // Publishing null is the final access to this unpinned node. wr.payload .wr_object - .store(ptr::null_mut(), Ordering::Relaxed); - - // Unlink from list - unsafe { - let mut ptrs = WeakLink::pointers(node); - ptrs.as_mut().set_prev(None); - ptrs.as_mut().set_next(None); - } - - // Collect callback without invoking only if we can keep weakref alive. - if wr.ref_count.safe_inc() { - let wr_ref = unsafe { PyRef::from_raw(wr as *const Py) }; - let cb = unsafe { wr.payload.callback.get().replace(None) }; - if let Some(cb) = cb { - callbacks.push((wr_ref, cb)); - } - } - + .store(ptr::null_mut(), Ordering::Release); current = next; } - self.head.store(ptr::null_mut(), Ordering::Relaxed); - - callbacks } fn count(&self, obj: &PyObject) -> usize { @@ -971,13 +1040,14 @@ impl WeakRefList { } fn get_weak_references(&self, obj: &PyObject) -> Vec> { - let _lock = weakref_lock::lock(obj as *const PyObject as usize); let mut v = Vec::new(); + let _lock = weakref_lock::lock(obj as *const PyObject as usize); let mut current = NonNull::new(self.head.load(Ordering::Relaxed)); while let Some(node) = current { let wr = unsafe { node.as_ref() }; + v.reserve(1); if wr.ref_count.safe_inc() { - v.push(unsafe { PyRef::from_raw(wr as *const Py) }); + v.push(unsafe { PyRef::::from_raw(wr as *const Py) }); } current = unsafe { WeakLink::pointers(node).as_ref().get_next() }; } @@ -1004,7 +1074,7 @@ unsafe impl Link for WeakLink { #[inline(always)] unsafe fn from_raw(ptr: NonNull) -> Self::Handle { - unsafe { PyRef::from_raw(ptr.as_ptr()) } + unsafe { PyRef::::from_raw(ptr.as_ptr()) } } #[inline(always)] @@ -1015,20 +1085,27 @@ unsafe impl Link for WeakLink { } // PyWeakReference: each weakref holds a direct pointer to its referent. -#[pyclass(name = "ReferenceType", module = "weakref")] +#[pyclass(name = "ReferenceType", module = "weakref", traverse = "manual")] #[derive(Debug)] pub struct PyWeak { pointers: Pointers>, /// Direct pointer to the referent object, null when dead. /// Equivalent to wr_object in PyWeakReference. wr_object: PyAtomic<*mut PyObject>, - /// Protected by stripe lock (keyed on wr_object address). + /// Handle to the original static referent stripe, like CPython's + /// weakrefs_lock. The same stripe protects the callback even after + /// wr_object becomes null and the referent is freed. + weakrefs_lock: weakref_lock::WeakrefLock, + /// Owned callback edge, protected by the original referent stripe. + /// GC can retain this edge after unlinking the weakref. callback: UnsafeCell>, pub(crate) hash: PyAtomic, } cfg_select! { feature = "threading" => { + // SAFETY: mutable callback and list access is serialized by the + // original referent stripe; referent and hash reads are atomic. unsafe impl Send for PyWeak {} unsafe impl Sync for PyWeak {} } @@ -1063,42 +1140,40 @@ impl PyWeak { self.wr_object.load(Ordering::Acquire).is_null() } - /// Get the callback associated with this weak reference. - /// Returns `None` if there is no callback or if the referent has been - /// collected (at which point the callback was already consumed). + /// Get the owned callback, which GC can retain after clearing the referent. pub(crate) fn get_callback(&self) -> Option { - let obj_ptr = self.wr_object.load(Ordering::Acquire); - if obj_ptr.is_null() { - // Dead weakref: callback was consumed during clear - return None; - } - - let _lock = weakref_lock::lock(obj_ptr as usize); - - // Double-check under lock (clear may have run between our check and lock) - let obj_ptr = self.wr_object.load(Ordering::Relaxed); - if obj_ptr.is_null() { - return None; - } - - // Safety: we hold the stripe lock that protects the callback field - let callback = unsafe { &*self.callback.get() }; - callback.clone() + let _lock = self.weakrefs_lock.lock(); + // SAFETY: the original referent stripe protects the callback. + unsafe { &*self.callback.get() }.clone() } - /// weakref_dealloc: remove from list if still linked. - fn drop_inner(&self) { - let obj_ptr = self.wr_object.load(Ordering::Acquire); - if obj_ptr.is_null() { - return; // Already cleared by WeakRefList::clear() + /// Unlink and steal the callback under the original referent stripe. + /// Return ownership so callers release it only after unlocking. + fn clear(&self) -> Option { + let _lock = self.weakrefs_lock.lock(); + // SAFETY: the original referent stripe protects both fields, including + // callbacks retained by GC after the weakref was already unlinked. + unsafe { + self.clear_ref_lock_held(); + (&mut *self.callback.get()).take() } + } - let _lock = weakref_lock::lock(obj_ptr as usize); + /// _PyWeakref_ClearRef: unlink without releasing the callback. + fn clear_ref(&self) { + let _lock = self.weakrefs_lock.lock(); + // SAFETY: the original referent stripe is held. + unsafe { self.clear_ref_lock_held() }; + } - // Double-check under lock + /// Unlink without releasing the callback. + /// + /// # Safety + /// The original referent stripe must be held. + unsafe fn clear_ref_lock_held(&self) { let obj_ptr = self.wr_object.load(Ordering::Relaxed); if obj_ptr.is_null() { - return; // Cleared between our check and lock acquisition + return; } let obj = unsafe { &*obj_ptr }; @@ -1121,12 +1196,31 @@ impl PyWeak { } } +// SAFETY: the callback is the only owned Python edge; wr_object is borrowed. +unsafe impl Traverse for PyWeak { + fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { + // Stripe critical sections never suspend or run Python, so a stopped + // thread cannot own this lock. Also synchronize gc.get_referents(), + // which traverses while other threads are running. + let _lock = self.weakrefs_lock.lock(); + // SAFETY: the original referent stripe protects the callback. + unsafe { &*self.callback.get() }.traverse(tracer_fn); + } + + fn clear(&mut self, out: &mut Vec) { + let callback = Self::clear(self); + if let Some(callback) = callback { + out.push(callback); + } + } +} + impl Drop for PyWeak { #[inline(always)] fn drop(&mut self) { // we do NOT have actual exclusive access! let me: &Self = self; - me.drop_inner(); + drop(me.clear()); } } @@ -1230,10 +1324,7 @@ impl InstanceDict { let dict = vm.ctx.new_dict(); match self.dict.compare_exchange_empty(dict.clone()) { Ok(()) => return dict, - Err(rejected) => { - drop(rejected); - drop(dict); - } + Err(_rejected) => {} } } } @@ -1516,38 +1607,11 @@ impl core::ops::DerefMut for FreeList { /// this reference counting is accounted for by this type. Use the `.clone()` /// method to create a new reference and increment the amount of references /// to the python object by 1. -#[repr(transparent)] -pub struct PyObjectRef { - ptr: NonNull, -} - -impl Clone for PyObjectRef { - #[inline(always)] - fn clone(&self) -> Self { - (**self).to_owned() - } -} - -cfg_select! { - feature = "threading" => { - unsafe impl Send for PyObjectRef {} - unsafe impl Sync for PyObjectRef {} - } - _ => {} -} +pub type PyObjectRef = PyRef; #[repr(transparent)] pub struct PyObject(Py); -impl Deref for PyObjectRef { - type Target = PyObject; - - #[inline(always)] - fn deref(&self) -> &PyObject { - unsafe { self.ptr.as_ref() } - } -} - impl ToOwned for PyObject { type Owned = PyObjectRef; @@ -1555,7 +1619,8 @@ impl ToOwned for PyObject { fn to_owned(&self) -> Self::Owned { self.0.ref_count.inc(); PyObjectRef { - ptr: NonNull::from(self), + ptr: NonNull::from(self).cast(), + marker: PhantomData, } } } @@ -1569,7 +1634,8 @@ impl PyObject { pub fn try_to_owned(&self) -> Option { if self.0.ref_count.safe_inc() { Some(PyObjectRef { - ptr: NonNull::from(self), + ptr: NonNull::from(self).cast(), + marker: PhantomData, }) } else { None @@ -1593,6 +1659,7 @@ impl PyObject { if ref_count.safe_inc() { Some(PyObjectRef { ptr: unsafe { NonNull::new_unchecked(ptr) }, + marker: PhantomData, }) } else { None @@ -1624,7 +1691,10 @@ impl PyObjectRef { #[inline(always)] #[must_use] pub const unsafe fn from_raw(ptr: NonNull) -> Self { - Self { ptr } + Self { + ptr: ptr.cast(), + marker: PhantomData, + } } /// Attempt to downcast this reference to a subclass. @@ -1656,7 +1726,8 @@ impl PyObjectRef { // manual impl to avoid assertion let obj = ManuallyDrop::new(self); PyRef { - ptr: obj.ptr.cast(), + ptr: obj.ptr, + marker: PhantomData, } } @@ -1701,7 +1772,7 @@ impl PyObject { } else { let head = unsafe { &*head_ptr }; if head.ref_count.safe_inc() { - Some(unsafe { PyRef::from_raw(head_ptr) }.into()) + Some(unsafe { PyRef::::from_raw(head_ptr) }.into()) } else { None } @@ -2120,13 +2191,16 @@ impl PyObject { // during __del__, preventing safe_inc from seeing 0. zelf.0.ref_count.inc_by(2); - let del_method = zelf.get_class_attr(identifier!(vm, __del__)).unwrap(); - if let Err(e) = slot_del(zelf, vm) { - let msg = del_method - .repr(vm) - .ok() - .map(|r| format!("Exception ignored while calling deallocator {r}")); - vm.run_unraisable(e, msg, del_method); + { + let _raised = vm.preserve_raised_exception(); + let del_method = zelf.get_class_attr(identifier!(vm, __del__)).unwrap(); + if let Err(e) = slot_del(zelf, vm) { + let msg = del_method + .repr(vm) + .ok() + .map(|r| format!("Exception ignored while calling deallocator {r}")); + vm.run_unraisable(e, msg, vm.ctx.none()); + } } // Undo the temporary resurrection. Always remove both @@ -2168,7 +2242,7 @@ impl PyObject { } // Clear weak refs AFTER __del__. - // Note: This differs from GC behavior which clears weakrefs before finalizers, + // GC clears callback-bearing weakrefs before finalizers and the rest later, // but for direct deallocation (drop_slow_inner), we need to allow the finalizer // to run without triggering use-after-free from WeakRefList operations. if let Some(wrl) = self.weak_ref_list() { @@ -2252,6 +2326,15 @@ impl PyObject { GcBits::from_bits_retain(self.0.gc_bits.load(Ordering::Relaxed)).contains(GcBits::TRACKED) } + /// Whether this object's payload or instance storage can own GC edges. + /// Unlike is_gc_tracked, this also covers temporarily untracked objects. + #[inline] + pub(crate) fn gc_may_have_edges(&self) -> bool { + self.0.vtable.trace.is_some() + || self.class().heaptype_ext.is_some() + || self.0.ext_ref().is_some() + } + /// Get the referents (objects directly referenced) of this object. /// Uses the full traverse including dict and slots. pub fn gc_get_referents(&self) -> Vec { @@ -2281,6 +2364,7 @@ impl PyObject { // This ensures drop_slow_inner() won't call __del__ again self.set_gc_finalized(); let result = crate::vm::thread::with_vm(self, |vm| { + let _raised = vm.preserve_raised_exception(); if let Err(e) = slot_del(self, vm) && let Some(del_method) = self.get_class_attr(identifier!(vm, __del__)) { @@ -2288,25 +2372,37 @@ impl PyObject { .repr(vm) .ok() .map(|r| format!("Exception ignored while calling deallocator {r}")); - vm.run_unraisable(e, msg, del_method); + vm.run_unraisable(e, msg, vm.ctx.none()); } }); let _ = result; } } - /// Clear weakrefs but collect callbacks instead of calling them. - /// This is used by GC to ensure ALL weakrefs are cleared BEFORE any callbacks run. - /// Returns collected callbacks as (PyRef, callback) pairs. - // = handle_weakrefs - pub fn gc_clear_weakrefs_collect_callbacks(&self) -> Vec<(PyRef, PyObjectRef)> { + /// Clear callback-bearing weakrefs before finalizers and return callbacks + /// belonging to reachable weakrefs for invocation outside the list lock. + pub fn gc_clear_weakrefs_collect_callbacks( + &self, + is_unreachable: &impl Fn(&Self) -> bool, + ) -> Vec<(PyRef, PyObjectRef)> { if let Some(wrl) = self.weak_ref_list() { - wrl.clear_for_gc_collect_callbacks(self) + wrl.clear_for_gc_collect_callbacks(self, is_unreachable) } else { vec![] } } + /// Clear weakrefs both in and pointing into the final unreachable set. + /// Callback edges remain owned until tp_clear or deallocation. + pub(crate) fn gc_clear_weakrefs(&self) { + if let Some(weakref) = self.downcast_ref::() { + weakref.clear_ref(); + } + if let Some(wrl) = self.weak_ref_list() { + wrl.clear_for_gc(self); + } + } + /// Get raw pointers to referents without incrementing reference counts. /// This is used during GC to avoid reference count manipulation. /// tp_traverse visits objects without incref @@ -2403,20 +2499,6 @@ impl PyObject { } } -impl Borrow for PyObjectRef { - #[inline(always)] - fn borrow(&self) -> &PyObject { - self - } -} - -impl AsRef for PyObjectRef { - #[inline(always)] - fn as_ref(&self) -> &PyObject { - self - } -} - impl<'a, T: PyPayload> From<&'a Py> for &'a PyObject { #[inline(always)] fn from(py_ref: &'a Py) -> Self { @@ -2424,15 +2506,6 @@ impl<'a, T: PyPayload> From<&'a Py> for &'a PyObject { } } -impl Drop for PyObjectRef { - #[inline] - fn drop(&mut self) { - if self.0.ref_count.dec() { - unsafe { PyObject::drop_slow(self.ptr) } - } - } -} - impl fmt::Debug for PyObject { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { // SAFETY: the vtable contains functions that accept payload types that always match up @@ -2441,12 +2514,6 @@ impl fmt::Debug for PyObject { } } -impl fmt::Debug for PyObjectRef { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - self.as_object().fmt(f) - } -} - const STACKREF_BORROW_TAG: usize = 1; /// A tagged stack reference to a Python object. @@ -2658,14 +2725,15 @@ impl Py { } } -impl ToOwned for Py { +impl> ToOwned for Py { type Owned = PyRef; #[inline(always)] fn to_owned(&self) -> Self::Owned { self.ref_count.inc(); PyRef { - ptr: NonNull::from(self), + ptr: NonNull::from(self).cast(), + marker: PhantomData, } } } @@ -2724,6 +2792,69 @@ impl fmt::Debug for Py { } } +mod ref_target_sealed { + pub trait Sealed {} + impl Sealed for T {} + impl Sealed for super::PyObject {} + impl Sealed for crate::builtins::set::PyAnySet {} + impl Sealed for crate::builtins::PyAnyDict {} + impl Sealed for super::PyTuple> {} +} + +/// Selects the borrowed view of a Python reference. +/// +/// Payloads borrow `Py`; `PyObject` borrows the erased object itself. +/// This trait is sealed so safe code cannot choose an unrelated layout. +/// Typed tuples are immutable views of the ordinary tuple allocation. +/// Internal union views borrow an erased header and dispatch on the payload; +/// they must not assume that their alternative payloads have the same layout. +/// +/// An arbitrary borrowed layout cannot be registered by downstream code: +/// +/// ```compile_fail +/// use rustpython_vm::object::PyRefTarget; +/// struct Unrelated; +/// impl PyRefTarget for Unrelated { +/// type Target = u8; +/// } +/// ``` +pub trait PyRefTarget: ref_target_sealed::Sealed { + type Target; +} + +impl PyRefTarget for T { + type Target = Py; +} + +impl PyRefTarget for PyObject { + type Target = Self; +} + +/// A non-erased reference target that can be an element of a typed tuple view. +/// +/// This is sealed through [`PyRefTarget`]. Payloads, registered union views and +/// recursively typed tuples qualify; `PyObject` does not, since ordinary tuples +/// already implement [`PyPayload`]. This marker selects a layout, not a runtime +/// type check: checked element conversion still requires +/// [`crate::convert::TransmuteFromObject`]. +pub trait PyTypedRefTarget: PyRefTarget {} + +impl>> PyTypedRefTarget for T {} +impl PyTypedRefTarget for crate::builtins::set::PyAnySet {} +impl PyTypedRefTarget for crate::builtins::PyAnyDict {} + +impl PyRefTarget for crate::builtins::PyAnyDict { + type Target = Self; +} + +impl PyRefTarget for crate::builtins::set::PyAnySet { + type Target = Self; +} + +impl PyRefTarget for PyTuple> { + type Target = Py; +} + /// A reference to a Python object. /// /// Note that a `PyRef` can only deref to a shared / immutable reference. @@ -2735,7 +2866,9 @@ impl fmt::Debug for Py { /// where a reference to the same object must be returned. #[repr(transparent)] pub struct PyRef { - ptr: NonNull>, + ptr: NonNull, + // Preserve the variance and auto traits of the former typed pointer. + marker: PhantomData>>, } cfg_select! { @@ -2746,17 +2879,17 @@ cfg_select! { _ => {} } -impl fmt::Debug for PyRef { +impl fmt::Debug for PyRef { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - (**self).fmt(f) + self.as_ref().fmt(f) } } impl Drop for PyRef { #[inline] fn drop(&mut self) { - if self.ref_count.dec() { - unsafe { PyObject::drop_slow(self.ptr.cast::()) } + if unsafe { self.ptr.as_ref() }.0.ref_count.dec() { + unsafe { PyObject::drop_slow(self.ptr) } } } } @@ -2764,14 +2897,48 @@ impl Drop for PyRef { impl Clone for PyRef { #[inline(always)] fn clone(&self) -> Self { - (**self).to_owned() + unsafe { self.ptr.as_ref() }.0.ref_count.inc(); + Self { + ptr: self.ptr, + marker: PhantomData, + } + } +} + +impl PyRef { + /// Transfers ownership from an erased reference to a registered view. + /// + /// # Safety + /// The object must satisfy all invariants of `T::Target`, including its + /// payload restrictions. Registering a target establishes its layout only; + /// the caller must validate this particular object before the transfer. + #[inline] + pub(crate) unsafe fn from_object_unchecked(object: PyObjectRef) -> Self { + let object = ManuallyDrop::new(object); + Self { + ptr: object.ptr, + marker: PhantomData, + } + } +} + +impl PyRef { + /// Erases the borrowed view, transferring the existing strong reference. + #[inline] + #[must_use] + pub fn into_object(self) -> PyObjectRef { + let object = ManuallyDrop::new(self); + PyObjectRef { + ptr: object.ptr, + marker: PhantomData, + } } } impl PyRef { #[inline(always)] pub(super) const fn into_non_null(self) -> NonNull> { - let ptr = self.ptr; + let ptr = self.ptr.cast(); core::mem::forget(self); ptr } @@ -2781,7 +2948,10 @@ impl PyRef { #[must_use] #[inline(always)] pub const unsafe fn from_non_null(ptr: NonNull>) -> Self { - Self { ptr } + Self { + ptr: ptr.cast(), + marker: PhantomData, + } } /// # Safety @@ -2795,15 +2965,13 @@ impl PyRef { #[inline(always)] unsafe fn from_obj_unchecked(obj: PyObjectRef) -> Self { debug_assert!(obj.downcast_ref::().is_some()); - let obj = ManuallyDrop::new(obj); - Self { - ptr: obj.ptr.cast(), - } + // SAFETY: the caller guarantees the payload type. + unsafe { Self::from_object_unchecked(obj) } } #[must_use] pub const fn leak(pyref: Self) -> &'static Py { - let ptr = pyref.ptr; + let ptr = pyref.ptr.cast::>(); core::mem::forget(pyref); unsafe { ptr.as_ref() } } @@ -2812,8 +2980,40 @@ impl PyRef { impl PyRef { #[inline(always)] pub fn new_ref(payload: T, typ: crate::builtins::PyTypeRef, dict: Option) -> Self { + Self::new_ref_impl(payload, typ, dict, true) + } + + /// Allocate and track internal storage without running collection during + /// publication. The next ordinary tracked allocation still checks thresholds. + #[cfg(all( + feature = "host_env", + any( + target_os = "linux", + target_os = "macos", + target_os = "windows", + target_os = "android" + ), + not(any(target_env = "musl", target_env = "sgx")) + ))] + pub(crate) fn new_ref_without_collection( + payload: T, + typ: crate::builtins::PyTypeRef, + dict: Option, + ) -> Self { + Self::new_ref_impl(payload, typ, dict, false) + } + + #[inline(always)] + fn new_ref_impl( + payload: T, + typ: crate::builtins::PyTypeRef, + dict: Option, + allow_collection: bool, + ) -> Self { let has_dict = dict.is_some(); let is_heaptype = typ.heaptype_ext.is_some(); + let track = !T::NEW_REF_UNTRACKED + && (has_dict || is_heaptype || (T::HAS_TRAVERSE && payload.needs_gc(&typ))); // Try to reuse from freelist (no dict, no heaptype) let cached = if !has_dict && !is_heaptype { @@ -2846,22 +3046,23 @@ impl PyRef { }; // Track object if: - // - HAS_TRAVERSE is true (Rust payload implements Traverse), OR + // - HAS_TRAVERSE is true and the payload needs cyclic GC, OR // - has instance dict (user-defined class instances), OR // - heap type (all heap type instances are GC-tracked, like Py_TPFLAGS_HAVE_GC) // unless the payload opts out via NEW_REF_UNTRACKED (e.g. call frames, // which are tracked lazily only on escape). - if (::HAS_TRAVERSE || has_dict || is_heaptype) - && !T::NEW_REF_UNTRACKED - { - // Tracks under the interpreter running now and collects if this - // allocation pushed gen0 past its threshold. + if track { + // Tracks under the interpreter running now and, when allowed, + // collects if this allocation pushed gen0 past its threshold. unsafe { - crate::gc_state::track_new_object(ptr.cast()); + crate::gc_state::track_new_object_impl(ptr.cast(), allow_collection); } } - Self { ptr } + Self { + ptr: ptr.cast(), + marker: PhantomData, + } } } @@ -2870,15 +3071,16 @@ where T::Base: core::fmt::Debug, { /// Converts this reference to the base type (ownership transfer). - /// # Safety - /// T and T::Base must have compatible layouts in size_of::() bytes. #[inline] #[must_use] pub fn into_base(self) -> PyRef { - let obj: PyObjectRef = self.into(); - match obj.downcast() { - Ok(base_ref) => base_ref, - Err(_) => unsafe { core::hint::unreachable_unchecked() }, + // PySubclass establishes the physical prefix; Python may have changed + // the object's class or MRO since this typed reference was constructed. + let ptr = self.ptr.cast(); + core::mem::forget(self); + PyRef { + ptr, + marker: PhantomData, } } #[inline] @@ -2900,9 +3102,8 @@ impl Py { /// Converts `&Py` to `&Py`. #[inline] pub fn to_base(&self) -> &Py { - debug_assert!(self.as_object().downcast_ref::().is_some()); - // SAFETY: T is #[repr(transparent)] over T::Base, - // so Py and Py have the same layout. + // SAFETY: PySubclass guarantees a valid base prefix with matching + // payload offsets and compatible object alignment. unsafe { &*(self as *const Self as *const Py) } } @@ -2918,54 +3119,47 @@ impl Py { } } -impl Borrow for PyRef -where - T: PyPayload, -{ +impl Borrow for PyRef { #[inline(always)] fn borrow(&self) -> &PyObject { - (**self).as_object() + unsafe { self.ptr.as_ref() } } } -impl AsRef for PyRef -where - T: PyPayload, -{ +impl AsRef for PyRef { #[inline(always)] fn as_ref(&self) -> &PyObject { self.borrow() } } -impl From> for PyObjectRef { +impl>> From> for PyObjectRef { #[inline] fn from(value: PyRef) -> Self { - let me = ManuallyDrop::new(value); - Self { ptr: me.ptr.cast() } + value.into_object() } } -impl Borrow> for PyRef { +impl>> Borrow> for PyRef { #[inline(always)] fn borrow(&self) -> &Py { self } } -impl AsRef> for PyRef { +impl>> AsRef> for PyRef { #[inline(always)] fn as_ref(&self) -> &Py { self } } -impl Deref for PyRef { - type Target = Py; +impl Deref for PyRef { + type Target = T::Target; #[inline(always)] - fn deref(&self) -> &Py { - unsafe { self.ptr.as_ref() } + fn deref(&self) -> &Self::Target { + unsafe { self.ptr.cast::().as_ref() } } } @@ -3063,12 +3257,12 @@ pub(crate) fn init_type_hierarchy() -> BootstrapTypeHierarchy { } unsafe fn initial_ref(ptr: *mut Py) -> PyRef { - unsafe { PyRef::from_raw(ptr.cast()) } + unsafe { PyRef::::from_raw(ptr.cast()) } } unsafe fn clone_raw_ref(ptr: *mut Py) -> PyRef { unsafe { &*ptr::addr_of!((*ptr).ref_count) }.inc(); - unsafe { PyRef::from_raw(ptr.cast()) } + unsafe { PyRef::::from_raw(ptr.cast()) } } unsafe fn into_type_tuple(tuple: PyTupleRef) -> PyTypeTupleRef { @@ -3132,6 +3326,7 @@ pub(crate) fn init_type_hierarchy() -> BootstrapTypeHierarchy { slots: PyType::make_slots(), heaptype_ext: None, tp_version_tag: core::sync::atomic::AtomicU32::new(0), + tp_versions_used: core::sync::atomic::AtomicU16::new(0), }; let object_payload = PyType { base: unsafe { PyAtomicRef::from_optional_ref_without_retag(None) }, @@ -3142,6 +3337,7 @@ pub(crate) fn init_type_hierarchy() -> BootstrapTypeHierarchy { slots: object::PyBaseObject::make_slots(), heaptype_ext: None, tp_version_tag: core::sync::atomic::AtomicU32::new(0), + tp_versions_used: core::sync::atomic::AtomicU16::new(0), }; let tuple_payload = PyType { base: unsafe { @@ -3156,6 +3352,7 @@ pub(crate) fn init_type_hierarchy() -> BootstrapTypeHierarchy { slots: tuple::PyTuple::make_slots(), heaptype_ext: None, tp_version_tag: core::sync::atomic::AtomicU32::new(0), + tp_versions_used: core::sync::atomic::AtomicU16::new(0), }; let object_element = @@ -3203,6 +3400,7 @@ pub(crate) fn init_type_hierarchy() -> BootstrapTypeHierarchy { slots: PyWeak::make_slots(), heaptype_ext: None, tp_version_tag: core::sync::atomic::AtomicU32::new(0), + tp_versions_used: core::sync::atomic::AtomicU16::new(0), }; let weakref_type = PyRef::new_ref(weakref_payload, type_type.clone(), None); // Static type: untrack from GC (was tracked by new_ref because PyType has HAS_TRAVERSE) @@ -3248,6 +3446,172 @@ pub(crate) fn init_type_hierarchy() -> BootstrapTypeHierarchy { mod tests { use super::*; + #[derive(Debug)] + struct RefProbe(alloc::sync::Arc); + + impl MaybeTraverse for RefProbe { + fn try_traverse(&self, _traverse_fn: &mut TraverseFn<'_>) {} + } + + impl PyPayload for RefProbe { + fn class(ctx: &crate::Context) -> &'static Py { + ctx.types.object_type + } + } + + impl Drop for RefProbe { + fn drop(&mut self) { + self.0.fetch_add(1, core::sync::atomic::Ordering::SeqCst); + } + } + + #[test] + fn pyref_object_layout_and_views() { + static_assertions::assert_type_eq_all!(PyObjectRef, PyRef); + static_assertions::assert_not_impl_any!(PyObject: PyPayload); + static_assertions::assert_impl_all!(PyRef: Unpin); + static_assertions::assert_eq_size!( + PyObjectRef, + NonNull, + Option, + PyRef, + Option>, + PyRef>> + ); + static_assertions::assert_eq_align!( + PyObjectRef, + NonNull, + PyRef, + PyRef>> + ); + #[cfg(feature = "threading")] + static_assertions::assert_impl_all!(PyRef: Send, Sync); + #[cfg(not(feature = "threading"))] + static_assertions::assert_not_impl_any!(PyRef: Send, Sync); + + fn erased_view(reference: &PyRef) -> &PyObject { + reference + } + fn payload_view(reference: &PyRef) -> &Py { + reference + } + fn tuple_view( + reference: &PyRef>>, + ) -> &Py>> { + reference + } + type NestedTuple = PyTuple>>>; + fn nested_view(reference: &PyRef) -> &Py { + reference + } + fn covariance<'long: 'short, 'short>(reference: PyRef<&'long ()>) -> PyRef<&'short ()> { + reference + } + fn into_object>() {} + into_object::>(); + let _ = ( + erased_view, + payload_view, + tuple_view, + nested_view, + covariance, + ); + } + + #[test] + fn pyref_object_ownership_and_raw_roundtrip() { + let drops = alloc::sync::Arc::new(core::sync::atomic::AtomicUsize::new(0)); + let ctx = crate::Context::genesis(); + let typed = PyRef::new_ref( + RefProbe(drops.clone()), + ctx.types.object_type.to_owned(), + None, + ); + let pointer = typed.as_object() as *const PyObject; + assert_eq!(typed.as_object().strong_count(), 1); + let erased: PyRef = typed.clone().into(); + assert_eq!(erased.strong_count(), 2); + assert!(core::ptr::eq(&*erased, pointer)); + let raw = erased.into_raw(); + assert_eq!(typed.as_object().strong_count(), 2); + let erased = unsafe { PyRef::::from_raw(raw) }; + let erased = erased.downcast::().unwrap_err(); + assert_eq!(erased.strong_count(), 2); + let restored = erased.downcast::().unwrap(); + assert!(core::ptr::eq(&*typed, &*restored)); + let raw = restored.into_non_null(); + let restored = unsafe { PyRef::::from_non_null(raw) }; + drop(typed); + assert_eq!(restored.as_object().strong_count(), 1); + assert_eq!(drops.load(core::sync::atomic::Ordering::SeqCst), 0); + drop(restored); + assert_eq!(drops.load(core::sync::atomic::Ordering::SeqCst), 1); + } + + #[test] + fn pyref_typed_tuple_erased_storage_drops_once() { + let ctx = crate::Context::genesis(); + // Both constructors transfer a Vec allocation into erased tuple storage. + for explicit_type in [false, true] { + let drops = alloc::sync::Arc::new(core::sync::atomic::AtomicUsize::new(0)); + let item = PyRef::new_ref( + RefProbe(drops.clone()), + ctx.types.object_type.to_owned(), + None, + ); + let mut elements = Vec::with_capacity(4); + elements.push(item.clone()); + let tuple = if explicit_type { + PyTuple::new_ref_typed_with_type(elements, ctx.types.tuple_type.to_owned()) + } else { + PyTuple::new_ref_typed(elements, ctx) + }; + assert_eq!(tuple.as_slice()[0].as_object().strong_count(), 2); + let copy = (*tuple).to_owned(); + let object: PyObjectRef = tuple.into(); + let untyped = copy.into_untyped(); + assert_eq!(object.strong_count(), 2); + assert!(core::ptr::eq(untyped.as_object(), &*object)); + assert_eq!(untyped.as_slice()[0].strong_count(), 2); + drop(object); + drop(item); + assert_eq!(drops.load(core::sync::atomic::Ordering::SeqCst), 0); + drop(untyped); + assert_eq!(drops.load(core::sync::atomic::Ordering::SeqCst), 1); + } + } + + #[test] + fn native_base_conversions_ignore_python_mro() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let class = vm.ctx.new_class( + None, + "HiddenOSErrorBase", + vm.ctx.exceptions.os_error.to_owned(), + Default::default(), + ); + let marker: PyObjectRef = vm.ctx.new_int(42).into(); + let error = vm.new_os_subtype_error(class.clone(), None, marker.clone()); + // A custom MRO can omit native bases without changing the allocation. + *class.mro.write() = vec![class.clone(), vm.ctx.types.object_type.to_owned()]; + assert!( + !error + .as_object() + .downcastable::() + ); + + assert!(error.to_base().to_base().get_arg(0).unwrap().is(&marker)); + assert!( + error + .into_base() + .into_base() + .get_arg(0) + .unwrap() + .is(&marker) + ); + }); + } + #[test] fn native_type_basicsize_includes_payload_padding() { use crate::class::PyClassDef; @@ -3391,6 +3755,78 @@ mod tests { drop(obj); } + #[test] + fn weakref_allocation_defers_gc_tracking_until_publication() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let target = vm.ctx.new_class( + None, + "WeakrefTarget", + vm.ctx.types.object_type.to_owned(), + Default::default(), + ); + let subclass = vm.ctx.new_class( + None, + "WeakrefSubclass", + vm.ctx.types.weakref_type.to_owned(), + Default::default(), + ); + for class in [ + vm.ctx.types.weakref_type.to_owned(), + vm.ctx.types.weakproxy_type.to_owned(), + vm.ctx.types.weakcallableproxy_type.to_owned(), + subclass, + ] { + let dict = class + .slots + .flags + .has_feature(crate::types::PyTypeFlags::HAS_DICT) + .then(|| vm.ctx.new_dict()); + // Exercise the allocator boundary directly: an uninitialized + // weakref must not be published through GC generation lists. + let unpublished = PyRef::new_ref( + PyWeak { + pointers: Pointers::new(), + wr_object: Radium::new(ptr::null_mut()), + weakrefs_lock: weakref_lock::select( + target.as_object() as *const PyObject as usize + ), + callback: UnsafeCell::new(None), + hash: Radium::new(crate::common::hash::SENTINEL), + }, + class.clone(), + dict, + ); + assert_eq!(unpublished.as_object().0.gc_bits.load(Ordering::Relaxed), 0); + assert!(!unpublished.as_object().is_gc_tracked()); + assert!( + !vm.state + .gc + .get_objects(None) + .iter() + .any(|object| object.is(unpublished.as_object())) + ); + drop(unpublished); + + let published = target + .as_object() + .downgrade_with_typ(None, class, vm) + .unwrap(); + assert!(published.as_object().is_gc_tracked()); + assert!( + vm.state + .gc + .get_objects(None) + .iter() + .any(|object| object.is(published.as_object())) + ); + assert_eq!( + published.wr_object.load(Ordering::Acquire), + target.as_object() as *const PyObject as *mut PyObject, + ); + } + }); + } + /// A weakref node stays linked into its target's list until its own /// `Drop` unlinks it, and `WeakRefList::add` reads the class off every /// node it walks looking for a proxy to reuse. A node that lost its class diff --git a/crates/vm/src/object/ext.rs b/crates/vm/src/object/ext.rs index 97309722a19..68fea76d4ff 100644 --- a/crates/vm/src/object/ext.rs +++ b/crates/vm/src/object/ext.rs @@ -360,7 +360,7 @@ impl PyAtomicRef { pub unsafe fn swap(&self, pyref: PyRef) -> PyRef { let py = PyRef::leak(pyref) as *const Py as *mut _; let old = Radium::swap(&self.inner, py, Ordering::AcqRel); - unsafe { PyRef::from_raw(old.cast()) } + unsafe { PyRef::::from_raw(old.cast()) } } pub fn swap_to_temporary_refs(&self, pyref: PyRef, vm: &VirtualMachine) { @@ -439,7 +439,11 @@ impl PyAtomicRef> { pub unsafe fn swap(&self, opt_ref: Option>) -> Option> { let val = opt_ref.map_or(null_mut(), |x| PyRef::leak(x) as *const Py as *mut _); let old = Radium::swap(&self.inner, val, Ordering::AcqRel); - unsafe { old.cast::>().as_ref().map(|x| PyRef::from_raw(x)) } + unsafe { + old.cast::>() + .as_ref() + .map(|x| PyRef::::from_raw(x)) + } } pub fn swap_to_temporary_refs(&self, opt_ref: Option>, vm: &VirtualMachine) { diff --git a/crates/vm/src/object/mod.rs b/crates/vm/src/object/mod.rs index 4f028338d4b..1921e3bec67 100644 --- a/crates/vm/src/object/mod.rs +++ b/crates/vm/src/object/mod.rs @@ -1,3 +1,78 @@ +//! Essential types for object models +//! +//! +-------------------------+--------------+-----------------------+ +//! | Management | Typed | Untyped | +//! +-------------------------+------------------+-------------------+ +//! | Interpreter-independent | [`Py`] | [`PyObject`] | +//! | Reference-counted | [`PyRef`] | [`PyObjectRef`] | +//! | Weak | [`PyWeakRef`] | [`PyRef`] | +//! +-------------------------+--------------+-----------------------+ +//! +//! [`PyRef`] may looking like to be called as PyObjectWeak by the rule, +//! but not to do to remember it is a PyRef object. +//! +//! # Reference ownership +//! +//! `PyObjectRef` is an alias for `PyRef`. Typed payload references, +//! erased references, union views, and typed tuple views share the same owning representation. +//! +//! ## Representation and invariants +//! +//! - `PyRef` stores `NonNull` and a zero-sized +//! `PhantomData>>`. The latter preserves the previous typed pointer's +//! covariance and auto-trait/`Unpin` shape. The transparent owner and its `Option` +//! remain one pointer wide with pointer alignment. +//! - The sealed `object::PyRefTarget` selects `Deref::Target`: payload `T` maps to +//! `Py`, `PyObject` maps to itself, and immutable typed tuples map recursively +//! to their existing typed `Py` view. Downstream safe code cannot register an +//! unrelated layout. `PyObject` does not implement `PyPayload`. +//! - `PyAnySet` is an internal transparent `PyObject` view. Its owner is +//! `PyRef`, whose construction validates set/frozenset (including +//! subclasses). Payload access downcasts to the actual alternative; neither +//! `Py` nor a shared set/frozenset payload layout is assumed. +//! `ArgIterable` instead stores a cached iterator function beside its owner, +//! so it remains a wrapper rather than an allocation view. +//! - [`PyTypedRefTarget`] admits non-erased element targets for typed tuple +//! views, including union views and recursively typed tuples. It does not +//! perform validation: `try_into_typed` checks every element before changing +//! the view. Typed constructors instead receive already-typed owners. +//! All tuple views retain erased element storage with transparent wrappers; +//! typed slices reinterpret only the guaranteed transparent reference +//! elements, never a generic `Vec` or `Box` representation. Private marshal +//! initialization finishes before publication; published elements are immutable. +//! - The owner itself has no new generic bound. `Clone` and `Drop` share one +//! implementation over the existing object header. Object allocation, vtable +//! destruction, weakrefs, GC, and trashcan handling are unchanged. +//! - Typed erasure uses `T: PyRefTarget>`. This excludes the erased +//! type from the conversion blanket, avoiding overlap with Rust's identity +//! `From for T`, while retaining typed and nested tuple conversions. +//! Union views provide their own checked conversions; `PyRef::into_object` +//! erases any owning view without adjusting its strong count. +//! - Ownership transfers use `ManuallyDrop` or `forget`, without an extra incref or +//! decrement. The existing raw APIs retain their ownership-transfer contracts. +//! - C-API typed output uses the same target equality. An erased owner supports +//! `*mut PyObject`, but cannot produce the fictitious `*mut Py` output. +//! Duplicate erased owner/member-layout/FFI implementations are removed. +//! - Feature-dependent `Send`/`Sync` behavior is retained. The non-threading erased +//! owner is neither; the threading owner implements both. +//! +//! ## API compatibility considerations +//! +//! Existing payload `PyRef` and `PyObjectRef` use remains supported, but aliasing +//! makes some inference less direct: +//! +//! - Distinct raw constructor signatures remain: erased +//! `PyObjectRef::from_raw(NonNull)` and typed +//! `PyRef::::from_raw(*const Py)`. Unqualified `PyRef::from_raw` can now be +//! ambiguous and require the explicit type parameter. +//! - Associated-target dereferencing can require an explicit downcast type or a +//! `PyRefTarget` equality bound in generic typed-view code. Arbitrary non-payload +//! views no longer automatically gain typed dereferencing; supported internal +//! views must be registered in the sealed selector. +//! - Rust `Debug` formatting now consistently uses the allocation's vtable rather +//! than the statically selected payload's formatter. This is a Rust diagnostic +//! difference, not a Python semantic assertion. + mod core; mod ext; mod payload; diff --git a/crates/vm/src/object/payload.rs b/crates/vm/src/object/payload.rs index a5a4bf35b7f..c52a4158df5 100644 --- a/crates/vm/src/object/payload.rs +++ b/crates/vm/src/object/payload.rs @@ -91,6 +91,25 @@ pub trait PyPayload: MaybeTraverse + PyThreadingConstraint + Sized + 'static { /// which is created untracked and tracked lazily only on escape. const NEW_REF_UNTRACKED: bool = false; + /// Whether this payload needs cyclic GC when first wrapped in an object. + /// Returning false promises that this instance cannot participate in a + /// reference cycle for its entire lifetime, not just at allocation time. + /// The check must not run Python. Instance dictionaries and heap types are + /// still tracked, unless NEW_REF_UNTRACKED opts out explicitly. + #[inline] + fn needs_gc(&self, _class: &Py) -> bool { + true + } + + /// Run tp_clear before ordinary reference-counted destruction. Payloads + /// whose Rust destructor releases their children directly may opt out. + /// Cyclic GC still calls tp_clear; freelists also require a cleared payload. + const CLEAR_ON_DEALLOC: bool = true; + + /// Release the references extracted by tp_clear in reverse order during + /// reference-counted destruction, as required by tuple deallocation. + const REVERSE_DEALLOC: bool = false; + /// Whether this type has a freelist. Types with freelists require /// immediate (non-deferred) GC untracking during dealloc to prevent /// race conditions when the object is reused. diff --git a/crates/vm/src/ospath.rs b/crates/vm/src/ospath.rs index 9bf17f183f9..b581d090a2b 100644 --- a/crates/vm/src/ospath.rs +++ b/crates/vm/src/ospath.rs @@ -63,11 +63,11 @@ impl PathConverter { } /// Format a type error message - fn type_error_msg(&self, type_name: &str, allow_fd: bool) -> String { - let expected = if allow_fd { - "string, bytes, os.PathLike or integer" - } else { - "string, bytes or os.PathLike" + fn type_error_msg(&self, type_name: &str, allow_fd: bool, nullable: bool) -> String { + let expected = match (allow_fd, nullable) { + (true, false) => "string, bytes, os.PathLike or integer", + (true, true) => "string, bytes, os.PathLike, integer or None", + (false, _) => "string, bytes or os.PathLike", }; format!( "{}{} should be {}, not {}", @@ -91,8 +91,28 @@ impl PathConverter { Err(obj) => obj, }; + self.try_pathlike(obj, allow_fd, vm) + } + + /// Convert an object already known not to be a str or bytes. + pub(crate) fn try_pathlike( + &self, + obj: PyObjectRef, + allow_fd: bool, + vm: &VirtualMachine, + ) -> PyResult { + self.try_pathlike_with_nullable(obj, allow_fd, false, vm) + } + + pub(crate) fn try_pathlike_with_nullable( + &self, + obj: PyObjectRef, + allow_fd: bool, + nullable: bool, + vm: &VirtualMachine, + ) -> PyResult { // Call __fspath__ - let type_error_msg = || self.type_error_msg(&obj.class().name(), allow_fd); + let type_error_msg = || self.type_error_msg(&obj.class().name(), allow_fd, nullable); let method = vm.get_method_or_type_error(obj.clone(), identifier!(vm, __fspath__), type_error_msg)?; if vm.is_none(&method) { @@ -103,8 +123,7 @@ impl PathConverter { // Match __fspath__ result self.try_match_str_bytes(result.clone(), vm)?.map_err(|_| { vm.new_type_error(format!( - "{}expected {}.__fspath__() to return str or bytes, not {}", - self.error_prefix(), + "expected {}.__fspath__() to return str or bytes, not {}", obj.class().name(), result.class().name(), )) @@ -112,7 +131,7 @@ impl PathConverter { } /// Try to match str or bytes, returns Err(obj) if neither - fn try_match_str_bytes( + pub(crate) fn try_match_str_bytes( &self, obj: PyObjectRef, vm: &VirtualMachine, @@ -141,7 +160,7 @@ impl PathConverter { } b @ PyBytes => { check_nul(b.as_bytes())?; - let path = FsPath::bytes_as_os_str(b.as_bytes(), vm)?.to_owned(); + let path = FsPath::bytes_as_os_str(b.as_bytes(), vm)?.into_owned(); Ok(Ok(OsPath { path, origin: Some(b.into()), @@ -172,14 +191,22 @@ pub enum OutputMode { } impl OutputMode { - pub(super) fn process_path(self, path: impl Into, vm: &VirtualMachine) -> PyObjectRef { - fn inner(mode: OutputMode, path: PathBuf, vm: &VirtualMachine) -> PyObjectRef { + pub(super) fn process_path(self, path: impl Into, vm: &VirtualMachine) -> PyResult { + fn inner(mode: OutputMode, path: PathBuf, vm: &VirtualMachine) -> PyResult { match mode { - OutputMode::String => vm.fsdecode(path).into(), - OutputMode::Bytes => vm - .ctx - .new_bytes(path.into_os_string().into_encoded_bytes()) - .into(), + OutputMode::String => vm.fsdecode(path).map(Into::into), + OutputMode::Bytes => { + #[cfg(windows)] + if vm.state.config.settings.legacy_windows_fs_encoding { + use std::os::windows::ffi::OsStrExt; + let wide: Vec = path.as_os_str().encode_wide().collect(); + return vm.fsencode_wide(&wide).map(Into::into); + } + Ok(vm + .ctx + .new_bytes(path.into_os_string().into_encoded_bytes()) + .into()) + } } } inner(self, path.into(), vm) @@ -216,9 +243,9 @@ impl OsPath { widestring::WideCString::from_os_str(&self.path).map_err(|err| err.to_pyexception(vm)) } - pub fn filename(&self, vm: &VirtualMachine) -> PyObjectRef { + pub fn filename(&self, vm: &VirtualMachine) -> PyResult { if let Some(ref origin) = self.origin { - origin.clone() + Ok(origin.clone()) } else { // Default to string when no origin (e.g., from new_str) OutputMode::String.process_path(self.path.clone(), vm) @@ -246,3 +273,26 @@ impl TryFromObject for OsPath { PathConverter::new().try_path(obj, vm) } } + +#[cfg(feature = "host_io")] +impl OsPath { + pub(crate) fn from_fspath(fspath: FsPath, vm: &VirtualMachine) -> PyResult { + let path = fspath.as_os_str(vm)?.into_owned(); + let origin = match fspath { + FsPath::Str(s) => s.into(), + FsPath::Bytes(b) => b.into(), + }; + Ok(Self { + path, + origin: Some(origin), + }) + } + + /// Convert an object to OsPath using the os.fspath-style error message. + /// Used by open(), which should report "expected str, bytes or os.PathLike object, not" + /// instead of "should be string, bytes or os.PathLike, not". + pub(crate) fn try_from_fspath(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let fspath = FsPath::try_from_path_like(obj, true, vm)?; + Self::from_fspath(fspath, vm) + } +} diff --git a/crates/vm/src/ospath_fd.rs b/crates/vm/src/ospath_fd.rs index 7e4f8561ee7..a9bcf447080 100644 --- a/crates/vm/src/ospath_fd.rs +++ b/crates/vm/src/ospath_fd.rs @@ -3,20 +3,52 @@ use crate::{ class::StaticType, convert::{IntoPyException, ToPyObject, TryFromObject}, exceptions::OSErrorBuilder, - function::FsPath, ospath::{OsPath, PathConverter}, }; use rustpython_host_env::crt_fd; impl PathConverter { - /// Convert to a path or a file descriptor. Integers are treated as fds - /// before `__fspath__` is considered. + /// Convert str and bytes to paths first, then treat indexable objects as + /// file descriptors before considering `__fspath__`. pub(crate) fn try_path_or_fd<'fd>( &self, obj: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if let Some(int) = obj.try_index_opt(vm) { + self.try_path_or_fd_allow_invalid(obj, vm)?.ok_or_else(|| { + // Preserve the usual EBADF result for the -1 descriptor. + unsafe { crt_fd::Borrowed::try_borrow_raw(-1) } + .expect_err("-1 is not a valid borrowed descriptor") + .into_pyexception(vm) + }) + } + + /// Convert an invalid -1 descriptor to None for path predicates. + pub(crate) fn try_path_or_fd_allow_invalid<'fd>( + &self, + obj: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult>> { + let obj = match self.try_match_str_bytes(obj, vm)? { + Ok(path) => return Ok(Some(OsPathOrFd::Path(path))), + Err(obj) => obj, + }; + + if let Some(fd) = self.try_index_as_fd(&obj, vm) { + return fd; + } + + self.try_pathlike(obj, true, vm) + .map(|path| Some(OsPathOrFd::Path(path))) + } + + fn try_index_as_fd<'fd>( + &self, + obj: &PyObjectRef, + vm: &VirtualMachine, + ) -> Option>>> { + let int = obj.try_index_opt(vm)?; + Some((|| { if obj .class() .is(crate::builtins::bool_::PyBool::static_type()) @@ -29,34 +61,13 @@ impl PathConverter { )?; } let fd = int?.try_to_primitive(vm)?; - return unsafe { crt_fd::Borrowed::try_borrow_raw(fd) } - .map(OsPathOrFd::Fd) - .map_err(|e| e.into_pyexception(vm)); - } - - self.try_path_inner(obj, true, vm).map(OsPathOrFd::Path) - } -} - -impl OsPath { - pub(crate) fn from_fspath(fspath: FsPath, vm: &VirtualMachine) -> PyResult { - let path = fspath.as_os_str(vm)?.into_owned(); - let origin = match fspath { - FsPath::Str(s) => s.into(), - FsPath::Bytes(b) => b.into(), - }; - Ok(Self { - path, - origin: Some(origin), - }) - } - - /// Convert an object to OsPath using the os.fspath-style error message. - /// Used by open(), which should report "expected str, bytes or os.PathLike object, not" - /// instead of "should be string, bytes or os.PathLike, not". - pub(crate) fn try_from_fspath(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let fspath = FsPath::try_from_path_like(obj, true, vm)?; - Self::from_fspath(fspath, vm) + if fd == -1 { + return Ok(None); + } + unsafe { crt_fd::Borrowed::try_borrow_raw(fd) } + .map(|fd| Some(OsPathOrFd::Fd(fd))) + .map_err(|e| e.into_pyexception(vm)) + })()) } } @@ -79,10 +90,10 @@ impl From for OsPathOrFd<'_> { } impl OsPathOrFd<'_> { - pub(crate) fn filename(&self, vm: &VirtualMachine) -> PyObjectRef { + pub(crate) fn filename(&self, vm: &VirtualMachine) -> PyResult { match self { Self::Path(path) => path.filename(vm), - Self::Fd(fd) => fd.as_raw().to_pyobject(vm), + Self::Fd(fd) => Ok(fd.as_raw().to_pyobject(vm)), } } } @@ -97,10 +108,35 @@ impl OSErrorBuilder { // TODO: return type to PyRef use crate::exceptions::ToOSErrorBuilder; let builder = error.to_os_error_builder(vm); - let builder = builder.filename(filename.into().filename(vm)); + let filename = match filename.into().filename(vm) { + Ok(filename) => filename, + Err(error) => return error, + }; + let builder = builder.filename(filename); builder.build(vm).upcast() } + pub(crate) fn with_filenames( + error: &std::io::Error, + first: &OsPath, + second: &OsPath, + vm: &VirtualMachine, + ) -> crate::builtins::PyBaseExceptionRef { + use crate::exceptions::ToOSErrorBuilder; + match first + .filename(vm) + .and_then(|first| second.filename(vm).map(|second| (first, second))) + { + Ok((first, second)) => error + .to_os_error_builder(vm) + .filename(first) + .filename2(second) + .build(vm) + .upcast(), + Err(error) => error, + } + } + /// Like `with_filename`, but strips winerror on Windows. /// Use for C runtime errors (open, fstat, etc.) that should produce /// `[Errno X]` format instead of `[WinError X]`. @@ -114,7 +150,11 @@ impl OSErrorBuilder { let builder = error.to_os_error_builder(vm); #[cfg(windows)] let builder = builder.without_winerror(); - let builder = builder.filename(filename.into().filename(vm)); + let filename = match filename.into().filename(vm) { + Ok(filename) => filename, + Err(error) => return error, + }; + let builder = builder.filename(filename); builder.build(vm).upcast() } } diff --git a/crates/vm/src/protocol/buffer.rs b/crates/vm/src/protocol/buffer.rs index 500ea5992f7..df3c949cc8d 100644 --- a/crates/vm/src/protocol/buffer.rs +++ b/crates/vm/src/protocol/buffer.rs @@ -5,7 +5,7 @@ use crate::{ Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, VirtualMachine, common::{ borrow::{BorrowedValue, BorrowedValueMut}, - lock::{MapImmutable, PyMutex, PyMutexGuard}, + lock::{PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard}, rc::PyRc, }, object::PyObjectPayload, @@ -403,25 +403,110 @@ pub struct BufferDescriptor { pub readonly: bool, pub itemsize: usize, pub format: Cow<'static, str>, - /// (shape, stride, suboffset) for each dimension. A non-zero suboffset means - /// the dimension is reached through a pointer; slicing never introduces one. - pub dim_desc: Vec<(usize, isize, isize)>, + /// Number of dimensions. + ndim: usize, + /// Shape, strides and suboffsets packed as 3 contiguous slices of length `ndim`. + dims: Box<[isize]>, // TODO: flags } impl BufferDescriptor { #[must_use] - pub fn simple(bytes_len: usize, readonly: bool) -> Self { + pub fn from_dim_desc( + len: usize, + offset: isize, + readonly: bool, + itemsize: usize, + format: Cow<'static, str>, + dim_desc: Vec<(usize, isize, isize)>, + ) -> Self { + let ndim = dim_desc.len(); + let mut dims = Vec::with_capacity(ndim * 3); + dims.extend(dim_desc.iter().map(|(shape, _, _)| *shape as isize)); + dims.extend(dim_desc.iter().map(|(_, stride, _)| *stride)); + dims.extend( + dim_desc + .iter() + .map(|(_, _, suboffset)| if *suboffset == 0 { -1 } else { *suboffset }), + ); Self { - len: bytes_len, - offset: 0, + len, + offset, readonly, - itemsize: 1, - format: Cow::Borrowed("B"), - dim_desc: vec![(bytes_len, 1, 0)], + itemsize, + format, + ndim, + dims: dims.into_boxed_slice(), } } + #[must_use] + pub fn shape(&self) -> &[isize] { + debug_assert_eq!(self.dims.len(), self.ndim * 3); + &self.dims[..self.ndim] + } + + #[must_use] + pub fn strides(&self) -> &[isize] { + debug_assert_eq!(self.dims.len(), self.ndim * 3); + &self.dims[self.ndim..self.ndim * 2] + } + + #[must_use] + pub fn suboffsets(&self) -> &[isize] { + debug_assert_eq!(self.dims.len(), self.ndim * 3); + &self.dims[self.ndim * 2..] + } + + pub fn shape_mut(&mut self) -> &mut [isize] { + debug_assert_eq!(self.dims.len(), self.ndim * 3); + &mut self.dims[..self.ndim] + } + + pub fn strides_mut(&mut self) -> &mut [isize] { + debug_assert_eq!(self.dims.len(), self.ndim * 3); + &mut self.dims[self.ndim..self.ndim * 2] + } + + pub fn suboffsets_mut(&mut self) -> &mut [isize] { + debug_assert_eq!(self.dims.len(), self.ndim * 3); + &mut self.dims[self.ndim * 2..] + } + + pub fn set_dimensions( + &mut self, + shape: Box<[isize]>, + strides: Box<[isize]>, + suboffsets: Box<[isize]>, + ) { + let ndim = shape.len(); + debug_assert_eq!(strides.len(), ndim); + debug_assert_eq!(suboffsets.len(), ndim); + + let shape = Vec::from(shape); + let strides = Vec::from(strides); + let suboffsets = Vec::from(suboffsets); + let mut dims = Vec::with_capacity(ndim * 3); + dims.extend(shape); + dims.extend(strides); + dims.extend(suboffsets); + + self.ndim = ndim; + self.dims = dims.into_boxed_slice(); + } + + #[must_use] + pub fn simple(bytes_len: usize, readonly: bool) -> Self { + Self::from_dim_desc( + bytes_len, + 0, + readonly, + 1, + Cow::Borrowed("B"), + vec![(bytes_len, 1, 0)], + ) + } + #[must_use] pub fn format( bytes_len: usize, @@ -429,14 +514,14 @@ impl BufferDescriptor { itemsize: usize, format: Cow<'static, str>, ) -> Self { - Self { - len: bytes_len, - offset: 0, + Self::from_dim_desc( + bytes_len, + 0, readonly, itemsize, format, - dim_desc: vec![(bytes_len / itemsize, itemsize as isize, 0)], - } + vec![(bytes_len / itemsize, itemsize as isize, 0)], + ) } /// The descriptor an exporter hands to a consumer that asked for `flags`: @@ -460,14 +545,19 @@ impl BufferDescriptor { // A request this flat is refused unless the layout is C-contiguous, so // one dimension addresses the same bytes. let shape = desc.len.checked_div(desc.itemsize).unwrap_or(0); - desc.dim_desc = vec![(shape, desc.itemsize as isize, 0)]; + desc.set_dimensions( + Box::new([shape as isize]), + Box::new([desc.itemsize as isize]), + Box::new([-1]), + ); } else if !flags.contains(BufferFlags::STRIDES) { // Shape survives but strides do not, which means C order. let mut stride = desc.itemsize as isize; - for (shape, dim_stride, suboffset) in desc.dim_desc.iter_mut().rev() { - *dim_stride = stride; - *suboffset = 0; - stride *= *shape as isize; + for i in (0..desc.ndim()).rev() { + let dim_shape = desc.shape()[i]; + desc.strides_mut()[i] = stride; + desc.suboffsets_mut()[i] = -1; + stride *= dim_shape; } } desc @@ -490,10 +580,9 @@ impl BufferDescriptor { debug_assert_eq!(self.itemsize, self.len); } else { let mut shape_product = 1; - let has_zero_dim = self.dim_desc.iter().any(|(s, _, _)| *s == 0); - for (shape, stride, suboffset) in self.dim_desc.iter().copied() { - shape_product *= shape; - debug_assert!(suboffset >= 0); + let has_zero_dim = self.shape().contains(&0); + for (&shape, &stride) in self.shape().iter().zip(self.strides().iter()) { + shape_product *= shape as usize; // For empty arrays (any dimension is 0), strides can be 0 if !has_zero_dim { debug_assert_ne!(stride, 0); @@ -506,7 +595,8 @@ impl BufferDescriptor { #[must_use] pub fn ndim(&self) -> usize { - self.dim_desc.len() + debug_assert_eq!(self.dims.len(), self.ndim * 3); + self.ndim } /// Whether the elements are laid out in row-major order. _IsCContiguous @@ -516,11 +606,11 @@ impl BufferDescriptor { return true; } let mut sd = self.itemsize; - for (shape, stride, _) in self.dim_desc.iter().copied().rev() { + for (&shape, &stride) in self.shape().iter().zip(self.strides().iter()).rev() { if shape > 1 && stride != sd as isize { return false; } - sd *= shape; + sd *= shape as usize; } true } @@ -534,11 +624,11 @@ impl BufferDescriptor { return true; } let mut sd = self.itemsize; - for (shape, stride, _) in self.dim_desc.iter().copied() { + for (&shape, &stride) in self.shape().iter().zip(self.strides().iter()) { if shape > 1 && stride != sd as isize { return false; } - sd *= shape; + sd *= shape as usize; } true } @@ -561,23 +651,27 @@ impl BufferDescriptor { /// The same shape, format and item size, laid out in C order from byte zero. #[must_use] pub fn contiguous(&self) -> Self { - let itemsize = self.itemsize; - let mut dim_desc = self.dim_desc.clone(); - if let Some((_, stride, suboffset)) = dim_desc.last_mut() { - *stride = itemsize as isize; - *suboffset = 0; - } - for i in (1..dim_desc.len()).rev() { - dim_desc[i - 1].1 = dim_desc[i].1 * dim_desc[i].0 as isize; - dim_desc[i - 1].2 = 0; + let mut strides = vec![0isize; self.ndim()]; + let mut stride = self.itemsize as isize; + for i in (0..self.ndim()).rev() { + strides[i] = stride; + stride *= self.shape()[i]; } + let shape = self.shape().to_vec().into_boxed_slice(); Self { len: self.len, offset: 0, readonly: self.readonly, itemsize: self.itemsize, format: self.format.clone(), - dim_desc, + ndim: self.ndim, + dims: { + let mut dims = Vec::with_capacity(self.ndim * 3); + dims.extend(shape.iter().copied()); + dims.extend(strides.iter().copied()); + dims.extend(vec![-1; self.ndim]); + dims.into_boxed_slice() + }, } } @@ -585,9 +679,7 @@ impl BufferDescriptor { /// stepping, the layout `PyBUF_INDIRECT` describes. #[must_use] pub fn has_suboffsets(&self) -> bool { - self.dim_desc - .iter() - .any(|(_, _, suboffset)| *suboffset != 0) + self.suboffsets().iter().any(|&suboffset| suboffset != -1) } /// this function do not check the bound @@ -595,29 +687,43 @@ impl BufferDescriptor { #[must_use] pub fn fast_position(&self, indices: &[usize]) -> isize { let mut pos = self.offset; - for (i, (_, stride, suboffset)) in indices - .iter() - .copied() - .zip_eq(self.dim_desc.iter().copied()) - { - pos += i as isize * stride + suboffset; + for (dim, i) in indices.iter().copied().enumerate() { + let suboffset = if self.suboffsets()[dim] == -1 { + 0 + } else { + self.suboffsets()[dim] + }; + pos += i as isize * self.strides()[dim] + suboffset; } pos } /// panic if indices.len() != ndim pub fn position(&self, indices: &[isize], vm: &VirtualMachine) -> PyResult { + assert_eq!(indices.len(), self.ndim()); + self.position_with(|dim| Ok(indices[dim]), vm) + } + + /// Convert and check one index at a time, stopping before later conversions + /// if an earlier dimension is out of bounds. + pub(crate) fn position_with( + &self, + mut index: impl FnMut(usize) -> PyResult, + vm: &VirtualMachine, + ) -> PyResult { let mut pos = self.offset; - for (dim, (i, (shape, stride, suboffset))) in indices + for (dim, ((&shape, &stride), &suboffset)) in self + .shape() .iter() - .copied() - .zip_eq(self.dim_desc.iter().copied()) + .zip(self.strides().iter()) + .zip(self.suboffsets().iter()) .enumerate() { // The dimension is named the way a person counts it. lookup_dimension - let i = i.wrapped_at(shape).ok_or_else(|| { + let i = index(dim)?.wrapped_at(shape as usize).ok_or_else(|| { vm.new_index_error(format!("index out of bounds on dimension {}", dim + 1)) })?; + let suboffset = if suboffset == -1 { 0 } else { suboffset }; pos += i as isize * stride + suboffset; } Ok(pos) @@ -664,15 +770,17 @@ impl BufferDescriptor { let pos = self.offset + indices .iter() - .zip_eq(self.dim_desc.iter()) - .map(|(&i, &(_, stride, suboffset))| i as isize * stride + suboffset) + .zip_eq(self.strides().iter().zip(self.suboffsets().iter())) + .map(|(&i, (&stride, &suboffset))| { + i as isize * stride + if suboffset == -1 { 0 } else { suboffset } + }) .sum::(); f(pos..pos + self.itemsize as isize); let mut dim = 0; loop { indices[dim] += 1; - if indices[dim] < self.dim_desc[dim].0 { + if (indices[dim] as isize) < self.shape()[dim] { break; } indices[dim] = 0; @@ -688,7 +796,13 @@ impl BufferDescriptor { where F: FnMut(Range), { - let (shape, stride, suboffset) = self.dim_desc[dim]; + let shape = self.shape()[dim] as usize; + let stride = self.strides()[dim]; + let suboffset = if self.suboffsets()[dim] == -1 { + 0 + } else { + self.suboffsets()[dim] + }; if dim + 1 == self.ndim() { if CONTIGUOUS { f(index..index + (shape * self.itemsize) as isize); @@ -740,19 +854,32 @@ impl BufferDescriptor { mut b_index: isize, dim: usize, f: &mut F, - ) where + ) -> bool + where F: FnMut(Range, Range) -> bool, { - let (shape, a_stride, a_suboffset) = self.dim_desc[dim]; - let (_b_shape, b_stride, b_suboffset) = other.dim_desc[dim]; - debug_assert_eq!(shape, _b_shape); + let shape = self.shape()[dim] as usize; + let a_stride = self.strides()[dim]; + let a_suboffset = if self.suboffsets()[dim] == -1 { + 0 + } else { + self.suboffsets()[dim] + }; + let b_shape = other.shape()[dim] as usize; + let b_stride = other.strides()[dim]; + let b_suboffset = if other.suboffsets()[dim] == -1 { + 0 + } else { + other.suboffsets()[dim] + }; + debug_assert_eq!(shape, b_shape); if dim + 1 == self.ndim() { if CONTIGUOUS { if f( a_index..a_index + (shape * self.itemsize) as isize, b_index..b_index + (shape * other.itemsize) as isize, ) { - return; + return true; } } else { for _ in 0..shape { @@ -762,37 +889,40 @@ impl BufferDescriptor { a_pos..a_pos + self.itemsize as isize, b_pos..b_pos + other.itemsize as isize, ) { - return; + return true; } a_index += a_stride; b_index += b_stride; } } - return; + return false; } for _ in 0..shape { - self._zip_eq::( + if self._zip_eq::( other, a_index + a_suboffset, b_index + b_suboffset, dim + 1, f, - ); + ) { + return true; + } a_index += a_stride; b_index += b_stride; } + false } #[must_use] fn is_last_dim_contiguous(&self) -> bool { - let (_, stride, suboffset) = self.dim_desc[self.ndim() - 1]; - suboffset == 0 && stride == self.itemsize as isize + let i = self.ndim() - 1; + self.suboffsets()[i] == -1 && self.strides()[i] == self.itemsize as isize } #[must_use] pub fn is_zero_in_shape(&self) -> bool { - self.dim_desc.iter().any(|(shape, _, _)| *shape == 0) + self.shape().contains(&0) } // TODO: support column-major order @@ -813,20 +943,20 @@ pub trait BufferResizeGuard { #[pyclass(module = false, name = "vec_buffer")] #[derive(Debug, PyPayload)] pub struct VecBuffer { - data: PyMutex>, + data: PyRwLock>, } #[pyclass(flags(BASETYPE, DISALLOW_INSTANTIATION))] impl VecBuffer { pub fn take(&self) -> Vec { - core::mem::take(&mut self.data.lock()) + core::mem::take(&mut self.data.write()) } } impl From> for VecBuffer { fn from(data: Vec) -> Self { Self { - data: PyMutex::new(data), + data: PyRwLock::new(data), } } } @@ -834,7 +964,7 @@ impl From> for VecBuffer { impl PyRef { #[must_use] pub fn into_pybuffer(self, readonly: bool) -> PyBuffer { - let len = self.data.lock().len(); + let len = self.data.read().len(); PyBuffer::new( self.into(), BufferDescriptor::simple(len, readonly), @@ -850,11 +980,10 @@ impl PyRef { static VEC_BUFFER_METHODS: BufferMethods = BufferMethods { obj_bytes: |buffer| { - PyMutexGuard::map_immutable(buffer.obj_as::().data.lock(), |x| x.as_slice()) - .into() + PyRwLockReadGuard::map(buffer.obj_as::().data.read(), |x| x.as_slice()).into() }, obj_bytes_mut: |buffer| { - PyMutexGuard::map(buffer.obj_as::().data.lock(), |x| { + PyRwLockWriteGuard::map(buffer.obj_as::().data.write(), |x| { x.as_mut_slice() }) .into() @@ -862,3 +991,32 @@ static VEC_BUFFER_METHODS: BufferMethods = BufferMethods { release: |_| {}, retain: |_| {}, }; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn multidimensional_zip_propagates_early_stop() { + let desc = BufferDescriptor::from_dim_desc( + 8, + 0, + true, + 1, + "B".into(), + vec![(2, 4, -1), (2, 2, -1), (2, 1, -1)], + ); + for contiguous in [false, true] { + let runs = if contiguous { 4 } else { 8 }; + for stop in 1..=runs { + let mut visited = 0; + desc.zip_eq(&desc, contiguous, |a, b| { + assert_eq!(a, b); + visited += 1; + visited == stop + }); + assert_eq!(visited, stop); + } + } + } +} diff --git a/crates/vm/src/protocol/callable.rs b/crates/vm/src/protocol/callable.rs index 49172a15222..04ce4ddc249 100644 --- a/crates/vm/src/protocol/callable.rs +++ b/crates/vm/src/protocol/callable.rs @@ -1,8 +1,8 @@ use crate::{ - builtins::{PyBoundMethod, PyFunction}, + builtins::{builtin_func::PyNativeFunction, descriptor::PyMethodDescriptor}, function::{FuncArgs, IntoFuncArgs}, - types::{GenericMethod, VectorCallFunc}, - {PyObject, PyObjectRef, PyResult, VirtualMachine}, + types::{GenericMethod, GetDescriptor, PyTypeFlags, VectorCallFunc}, + {AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine}, }; impl PyObject { @@ -55,6 +55,125 @@ impl PyObject { }; callable.invoke_vectorcall(args, nargs, kwnames, vm) } + + /// PyVectorcall_Call: invoke retained raw support without automatic eligibility + /// or a tp_call fallback. + pub fn vectorcall_call( + &self, + args: Vec, + nargs: usize, + kwnames: Option<&[PyObjectRef]>, + vm: &VirtualMachine, + ) -> PyResult { + let vc = self.raw_vectorcall_func().ok_or_else(|| { + vm.new_type_error(format!( + "'{}' object does not support vectorcall", + self.class().slot_name() + )) + })?; + self.invoke_vectorcall_func(vc, args, nargs, kwnames, vm) + } + + #[inline] + pub(crate) fn vectorcall_func(&self) -> Option { + if self + .class() + .slots() + .flags + .has_feature(PyTypeFlags::HAVE_VECTORCALL) + { + self.raw_vectorcall_func() + } else { + None + } + } + + #[inline] + fn raw_vectorcall_func(&self) -> Option { + let slots = self.class().slots(); + slots.vectorcall.load().or_else(|| { + slots + .vectorcall_resolver + .load() + .and_then(|resolve| resolve(self)) + }) + } + + #[inline] + fn invoke_vectorcall_func( + &self, + vc: VectorCallFunc, + args: Vec, + nargs: usize, + kwnames: Option<&[PyObjectRef]>, + vm: &VirtualMachine, + ) -> PyResult { + if !vm.use_tracing.get() { + return vc(self, args, nargs, kwnames, vm); + } + let first_arg = self.profile_first_arg(args[..nargs].first(), vm); + let Some(callable) = self.profile_callable(first_arg.as_ref(), vm)? else { + return vc(self, args, nargs, kwnames, vm); + }; + vm.trace_event(TraceEvent::CCall, Some(callable))?; + let result = vc(self, args, nargs, kwnames, vm); + if result.is_ok() { + self.profile_event(TraceEvent::CReturn, first_arg.as_ref(), vm)?; + } else { + let _ = self.profile_event(TraceEvent::CException, first_arg.as_ref(), vm); + } + result + } + + #[cold] + fn profile_event( + &self, + event: TraceEvent, + first_arg: Option<&PyObjectRef>, + vm: &VirtualMachine, + ) -> PyResult<()> { + if let Some(callable) = self.profile_callable(first_arg, vm)? { + vm.trace_event(event, Some(callable))?; + } + Ok(()) + } + + #[cold] + fn profile_first_arg( + &self, + first_arg: Option<&PyObjectRef>, + vm: &VirtualMachine, + ) -> Option { + // Only method descriptors need a receiver for legacy profile callbacks. + // Keep it available for binding independently at call and return. + if self.class().is(vm.ctx.types.method_descriptor_type) { + first_arg.cloned() + } else { + None + } + } + + // CPython legacy_tracing.c: sys_profile_call_or_return. This filter is + // specific to sys.setprofile, not sys.monitoring's general CALL events. + #[cold] + fn profile_callable( + &self, + first_arg: Option<&PyObjectRef>, + vm: &VirtualMachine, + ) -> PyResult> { + if vm.tracing_is_suppressed() || vm.is_none(&vm.profile_func.borrow()) { + return Ok(None); + } + if self.downcast_ref::().is_some() { + return Ok(Some(self.to_owned())); + } + if self.class().is(vm.ctx.types.method_descriptor_type) + && let Some(first_arg) = first_arg + { + return PyMethodDescriptor::descr_get(self, Some(first_arg), None, vm).map(Some); + } + Ok(None) + } } #[derive(Debug)] @@ -68,7 +187,7 @@ impl<'a> PyCallable<'a> { pub fn new(obj: &'a PyObject) -> Option { let slots = obj.class().slots(); let call = slots.call.load()?; - let vectorcall = slots.vectorcall.load(); + let vectorcall = obj.vectorcall_func(); Some(PyCallable { obj, call, @@ -78,30 +197,39 @@ impl<'a> PyCallable<'a> { pub fn invoke(&self, args: impl IntoFuncArgs, vm: &VirtualMachine) -> PyResult { let args = args.into_args(vm); + if self.vectorcall_revoked() { + // A retained wrapper must use current tp_call, not its cached snapshot. + return self.obj.call_with_args(args, vm); + } + if let Some(vc) = self.vectorcall + && args.kwargs.is_empty() + { + let nargs = args.args.len(); + return self + .obj + .invoke_vectorcall_func(vc, args.args, nargs, None, vm); + } if !vm.use_tracing.get() { return (self.call)(self.obj, args, vm); } - // Python functions get 'call'/'return' events from with_frame(). - // Bound methods delegate to the inner callable, which fires its own events. - // All other callables (built-in functions, etc.) get 'c_call'/'c_return'/'c_exception'. - let is_python_callable = self.obj.downcast_ref::().is_some() - || self.obj.downcast_ref::().is_some(); - if is_python_callable { - (self.call)(self.obj, args, vm) + let first_arg = self.obj.profile_first_arg(args.args.first(), vm); + let Some(callable) = self.obj.profile_callable(first_arg.as_ref(), vm)? else { + return (self.call)(self.obj, args, vm); + }; + vm.trace_event(TraceEvent::CCall, Some(callable))?; + let result = (self.call)(self.obj, args, vm); + if result.is_ok() { + self.obj + .profile_event(TraceEvent::CReturn, first_arg.as_ref(), vm)?; } else { - let callable = self.obj.to_owned(); - vm.trace_event(TraceEvent::CCall, Some(callable.clone()))?; - let result = (self.call)(self.obj, args, vm); - if result.is_ok() { - vm.trace_event(TraceEvent::CReturn, Some(callable))?; - } else { - let _ = vm.trace_event(TraceEvent::CException, Some(callable)); - } - result + let _ = self + .obj + .profile_event(TraceEvent::CException, first_arg.as_ref(), vm); } + result } - /// Vectorcall dispatch: use vectorcall slot if available, else fall back to FuncArgs. + /// Use automatic vectorcall if available, else fall back to FuncArgs. #[inline] pub fn invoke_vectorcall( &self, @@ -110,31 +238,29 @@ impl<'a> PyCallable<'a> { kwnames: Option<&[PyObjectRef]>, vm: &VirtualMachine, ) -> PyResult { + if self.vectorcall_revoked() { + return self.obj.vectorcall(args, nargs, kwnames, vm); + } if let Some(vc) = self.vectorcall { - if !vm.use_tracing.get() { - return vc(self.obj, args, nargs, kwnames, vm); - } - let is_python_callable = self.obj.downcast_ref::().is_some() - || self.obj.downcast_ref::().is_some(); - if is_python_callable { - vc(self.obj, args, nargs, kwnames, vm) - } else { - let callable = self.obj.to_owned(); - vm.trace_event(TraceEvent::CCall, Some(callable.clone()))?; - let result = vc(self.obj, args, nargs, kwnames, vm); - if result.is_ok() { - vm.trace_event(TraceEvent::CReturn, Some(callable))?; - } else { - let _ = vm.trace_event(TraceEvent::CException, Some(callable)); - } - result - } + self.obj + .invoke_vectorcall_func(vc, args, nargs, kwnames, vm) } else { // Fallback: convert owned Vec to FuncArgs (move, no clone) let func_args = FuncArgs::from_vectorcall_owned(args, nargs, kwnames); self.invoke(func_args, vm) } } + + #[inline] + fn vectorcall_revoked(&self) -> bool { + self.vectorcall.is_some() + && !self + .obj + .class() + .slots() + .flags + .has_feature(PyTypeFlags::HAVE_VECTORCALL) + } } /// Trace events for sys.settrace and sys.setprofile. @@ -262,7 +388,7 @@ impl VirtualMachine { let is_profile_event = event.is_profile_event(); let is_opcode_event = event.is_opcode_event(); - let Some(frame_ref) = crate::frame::current_thread_frame_materialize(self) else { + let Some(frame_ref) = crate::frame::current_complete_frame_for_trace(self) else { return Ok(None); }; diff --git a/crates/vm/src/protocol/iter.rs b/crates/vm/src/protocol/iter.rs index 9322890f68e..ff45b58f894 100644 --- a/crates/vm/src/protocol/iter.rs +++ b/crates/vm/src/protocol/iter.rs @@ -6,6 +6,7 @@ use crate::{ }; use core::borrow::Borrow; use core::ops::Deref; +use rustpython_common::wtf8::wtf8_concat; /// [Iterator Protocol](https://docs.python.org/3/c-api/iter.html). #[derive(Debug, Clone)] @@ -138,13 +139,14 @@ impl TryFromObject for PyIter { fn try_from_object(vm: &VirtualMachine, iter_target: PyObjectRef) -> PyResult { let get_iter = iter_target.class().slots().iter.load(); if let Some(get_iter) = get_iter { - let iter = get_iter(iter_target, vm)?; + let iter = get_iter(iter_target.clone(), vm)?; if Self::check(&iter) { Ok(Self(iter)) } else { - Err(vm.new_type_error(format!( - "iter() returned non-iterator of type '{}'", - iter.class().slot_name() + Err(vm.new_type_error(wtf8_concat!( + iter_target.class().fully_qualified_name(vm)?, + ".__iter__() must return an iterator, not ", + iter.class().fully_qualified_name(vm)? ))) } } else if let Ok(seq_iter) = PySequenceIterator::new(iter_target.clone(), vm) { diff --git a/crates/vm/src/protocol/mapping.rs b/crates/vm/src/protocol/mapping.rs index e791757901e..b0e8ea6cf89 100644 --- a/crates/vm/src/protocol/mapping.rs +++ b/crates/vm/src/protocol/mapping.rs @@ -1,4 +1,5 @@ use crossbeam_utils::atomic::AtomicCell; +use rustpython_common::wtf8::wtf8_concat; use crate::{ AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine, @@ -184,7 +185,7 @@ impl PyMapping<'_> { pub fn keys(self, vm: &VirtualMachine) -> PyResult { if let Some(dict) = self.obj.downcast_ref_if_exact::(vm) { - PyDictKeys::new(dict.to_owned()).to_pyresult(vm) + PyDictKeys::new(dict.to_owned().into()).to_pyresult(vm) } else { self.method_output_as_list(identifier!(vm, keys), vm) } @@ -192,7 +193,7 @@ impl PyMapping<'_> { pub fn values(self, vm: &VirtualMachine) -> PyResult { if let Some(dict) = self.obj.downcast_ref_if_exact::(vm) { - PyDictValues::new(dict.to_owned()).to_pyresult(vm) + PyDictValues::new(dict.to_owned().into()).to_pyresult(vm) } else { self.method_output_as_list(identifier!(vm, values), vm) } @@ -200,7 +201,7 @@ impl PyMapping<'_> { pub fn items(self, vm: &VirtualMachine) -> PyResult { if let Some(dict) = self.obj.downcast_ref_if_exact::(vm) { - PyDictItems::new(dict.to_owned()).to_pyresult(vm) + PyDictItems::new(dict.to_owned().into()).to_pyresult(vm) } else { self.method_output_as_list(identifier!(vm, items), vm) } @@ -212,21 +213,36 @@ impl PyMapping<'_> { vm: &VirtualMachine, ) -> PyResult { let meth_output = vm.call_method(self.obj, method_name.as_str(), ())?; - if meth_output.is(vm.ctx.types.list_type) { + self.collect_method_output(method_name, meth_output, vm) + } + + pub(crate) fn collect_method_output( + self, + method_name: &'static PyStrInterned, + meth_output: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + if meth_output.class().is(vm.ctx.types.list_type) { return Ok(meth_output); } - let iter = meth_output.get_iter(vm).map_err(|_| { - vm.new_type_error(format!( - "{}.{}() returned a non-iterable (type {})", - self.obj.class().slot_name(), - method_name.as_str(), - meth_output.class().slot_name() - )) - })?; - - // TODO - // PySequence::from(&iter).list(vm).map(|x| x.into()) - vm.ctx.new_list(iter.try_to_value(vm)?).to_pyresult(vm) + let iter = match meth_output.get_iter(vm) { + Ok(iter) => iter, + Err(error) if error.fast_isinstance(vm.ctx.exceptions.type_error) => { + return Err(vm.new_type_error(wtf8_concat!( + self.obj.class().fully_qualified_name(vm)?, + ".", + method_name.as_str(), + "() must return an iterable, not ", + meth_output.class().fully_qualified_name(vm)? + ))); + } + Err(error) => return Err(error), + }; + + drop(meth_output); + let result = vm.ctx.new_list(Vec::new()); + result.extend(iter.into(), vm)?; + Ok(result.into()) } } diff --git a/crates/vm/src/protocol/mod.rs b/crates/vm/src/protocol/mod.rs index 1d191daee31..7244e317d96 100644 --- a/crates/vm/src/protocol/mod.rs +++ b/crates/vm/src/protocol/mod.rs @@ -18,4 +18,5 @@ pub use number::{ PyNumberTernaryFunc, PyNumberTernaryOp, PyNumberUnaryFunc, handle_bytes_to_int_err, numeric_literal_from_str, }; +pub(crate) use object::sequence_index_key; pub use sequence::{PySequence, PySequenceMethods, PySequenceSlots}; diff --git a/crates/vm/src/protocol/number.rs b/crates/vm/src/protocol/number.rs index db14a08d4eb..a0f6140c6cc 100644 --- a/crates/vm/src/protocol/number.rs +++ b/crates/vm/src/protocol/number.rs @@ -1,15 +1,15 @@ use core::ops::Deref; +use rustpython_common::wtf8::wtf8_concat; use crossbeam_utils::atomic::AtomicCell; use crate::{ - AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromBorrowedObject, - VirtualMachine, + AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, TryFromBorrowedObject, VirtualMachine, builtins::{ PyBaseExceptionRef, PyByteArray, PyBytes, PyComplex, PyFloat, PyInt, PyIntRef, PyStr, int, }, common::{ - int::{BytesToIntError, bytes_to_int}, + int::BytesToIntError, str::{PyKindStr, transform_decimal_and_space_to_ascii}, }, function::ArgBytesLike, @@ -27,13 +27,16 @@ use alloc::borrow::Cow; /// a base, and only `int` and `float` accept bytes-like input, so each keeps its own /// entry point around this one. /// -/// A string holding surrogates can never be a valid literal, so it folds to an -/// empty — and therefore invalid — one. +/// Surrogates cannot form a valid literal. Normalize their valid prefix too, +/// so underscore validation can still distinguish a malformed separator from +/// another invalid character. pub fn numeric_literal_from_str(s: &Py) -> Cow<'_, str> { match s.as_str_kind() { - PyKindStr::Ascii(s) => Cow::Borrowed(s.trim().as_str()), - PyKindStr::Utf8(s) => transform_decimal_and_space_to_ascii(s.trim()), - PyKindStr::Wtf8(_) => Cow::Borrowed(""), + PyKindStr::Ascii(s) => Cow::Borrowed(s.as_str()), + PyKindStr::Utf8(s) => transform_decimal_and_space_to_ascii(s), + PyKindStr::Wtf8(s) => { + Cow::Owned(transform_decimal_and_space_to_ascii(&s.to_string_lossy()).into_owned()) + } } } @@ -53,47 +56,50 @@ impl PyObject { } else if let Some(i) = self.downcast_ref::() { Some(Ok(vm.ctx.new_bigint(i.as_bigint()))) } else { - self.number().index(vm) + self.number().index(vm).map(|result| { + let result = result?; + if result.class().is(vm.ctx.types.int_type) { + Ok(result) + } else { + Ok(vm.ctx.new_bigint(result.as_bigint())) + } + }) } } #[inline] pub fn try_index(&self, vm: &VirtualMachine) -> PyResult { self.try_index_opt(vm).transpose()?.ok_or_else(|| { + let name = self.class().slot_name(); + let name = &name[..name.floor_char_boundary(name.len().min(200))]; vm.new_type_error(format!( - "'{}' object cannot be interpreted as an integer", - self.class().slot_name() + "'{name}' object cannot be interpreted as an integer" )) }) } pub fn try_int(&self, vm: &VirtualMachine) -> PyResult { - fn try_convert(obj: &PyObject, lit: &[u8], vm: &VirtualMachine) -> PyResult { - let base = 10; - let digit_limit = vm.state.int_max_str_digits.load(); - - let i = bytes_to_int(lit, base, digit_limit) - .map_err(|e| handle_bytes_to_int_err(e, obj, vm))?; - Ok(PyInt::from(i).into_ref(&vm.ctx)) - } - if let Some(i) = self.downcast_ref_if_exact::(vm) { Ok(i.to_owned()) } else if let Some(i) = self.number().int(vm).or_else(|| self.try_index_opt(vm)) { i } else if let Some(s) = self.downcast_ref::() { - try_convert(self, numeric_literal_from_str(s).as_bytes(), vm) + int::from_str_literal(s, 10, vm).map(|value| vm.ctx.new_int(value)) } else if let Some(bytes) = self.downcast_ref::() { - try_convert(self, bytes.as_bytes(), vm) + int::from_bytes_literal(bytes.as_bytes(), 10, vm).map(|value| vm.ctx.new_int(value)) } else if let Some(bytearray) = self.downcast_ref::() { - try_convert(self, &bytearray.borrow_buf(), vm) + int::from_bytes_literal(&bytearray.borrow_buf(), 10, vm) + .map(|value| vm.ctx.new_int(value)) } else if let Ok(buffer) = ArgBytesLike::try_from_borrowed_object(vm, self) { - // TODO: replace to PyBuffer - try_convert(self, &buffer.borrow_buf(), vm) + // Generic exporters are copied before parsing, as in PyNumber_Long. + // Do not call an exporter's repr while its buffer is borrowed. + let bytes = buffer.borrow_buf().to_vec(); + int::from_bytes_literal(&bytes, 10, vm).map(|value| vm.ctx.new_int(value)) } else { + let name = self.class().slot_name(); + let name = &name[..name.floor_char_boundary(name.len().min(200))]; Err(vm.new_type_error(format!( - "int() argument must be a string, a bytes-like object or a real number, not '{}'", - self.class().slot_name() + "int() argument must be a string, a bytes-like object or a real number, not '{name}'" ))) } } @@ -667,59 +673,46 @@ impl PyNumber<'_> { #[inline] pub fn int(self, vm: &VirtualMachine) -> Option> { self.class().slots().as_number.int.load().map(|f| { - let ret = f(self, vm)?; - - if let Some(ret) = ret.downcast_ref_if_exact::(vm) { - return Ok(ret.to_owned()); - } - - let ret_class = ret.class().to_owned(); - if let Some(ret) = ret.downcast_ref::() { - let msg = format!( - "__int__ returned non-int (type {}). \ -The ability to return an instance of a strict subclass of int is deprecated, \ -and may be removed in a future version of Python.", - ret_class.slot_name() - ); - _warnings::warn(vm.ctx.exceptions.deprecation_warning, msg, 1, vm)?; - - Ok(ret.to_owned()) + let ret = self.int_result(f(self, vm)?, "__int__", vm)?; + if ret.class().is(vm.ctx.types.int_type) { + Ok(ret) } else { - Err(vm.new_type_error(format!( - "__int__ returned non-int (type {})", - ret_class.slot_name() - ))) + Ok(vm.ctx.new_bigint(ret.as_bigint())) } }) } #[inline] pub fn index(self, vm: &VirtualMachine) -> Option> { - self.class().slots().as_number.index.load().map(|f| { - let ret = f(self, vm)?; - - if let Some(ret) = ret.downcast_ref_if_exact::(vm) { - return Ok(ret.to_owned()); - } - - let ret_class = ret.class().to_owned(); - if let Some(ret) = ret.downcast_ref::() { - let msg = format!( - "__index__ returned non-int (type {}). \ -The ability to return an instance of a strict subclass of int is deprecated, \ -and may be removed in a future version of Python.", - ret_class.slot_name() - ); - _warnings::warn(vm.ctx.exceptions.deprecation_warning, msg, 1, vm)?; + self.class() + .slots() + .as_number + .index + .load() + .map(|f| self.int_result(f(self, vm)?, "__index__", vm)) + } - Ok(ret.to_owned()) - } else { - Err(vm.new_type_error(format!( - "__index__ returned non-int (type {})", - ret_class.slot_name() - ))) - } - }) + fn int_result(self, ret: PyObjectRef, method: &str, vm: &VirtualMachine) -> PyResult { + if let Some(ret) = ret.downcast_ref_if_exact::(vm) { + return Ok(ret.to_owned()); + } + let message = wtf8_concat!( + self.class().fully_qualified_name(vm)?, + ".", + method, + "() must return an int, not ", + ret.class().fully_qualified_name(vm)? + ); + let Ok(ret) = ret.downcast::() else { + return Err(vm.new_type_error(message)); + }; + let warning = wtf8_concat!( + message, + ". The ability to return an instance of a strict subclass of int ", + "is deprecated, and may be removed in a future version of Python." + ); + _warnings::warn(vm.ctx.exceptions.deprecation_warning, warning, 1, vm)?; + Ok(ret) } #[inline] @@ -732,23 +725,14 @@ and may be removed in a future version of Python.", } let ret_class = ret.class().to_owned(); + let message = wtf8_concat!(self.class().fully_qualified_name(vm)?, ".__float__() must return a float, not ", ret_class.fully_qualified_name(vm)?); if let Some(ret) = ret.downcast_ref::() { - let msg = format!( - "{}.__float__ returned non-float (type {}). \ -The ability to return an instance of a strict subclass of float is deprecated, \ -and may be removed in a future version of Python.", - self.class().slot_name(), - ret_class.slot_name() - ); + let msg = wtf8_concat!(message, ". The ability to return an instance of a strict subclass of float is deprecated, and may be removed in a future version of Python."); _warnings::warn(vm.ctx.exceptions.deprecation_warning, msg, 1, vm)?; Ok(ret.to_owned()) } else { - Err(vm.new_type_error(format!( - "{}.__float__ returned non-float (type {})", - self.class().slot_name(), - ret_class.slot_name() - ))) + Err(vm.new_type_error(message)) } }) } @@ -775,7 +759,12 @@ pub fn handle_bytes_to_int_err( Ok(v) => v, Err(err) => return err, }; - vm.new_value_error(format!("invalid literal for int() with base {base}: {v}")) + // %.200R is a code-point limit on the repr, not a UTF-8 byte limit. + let end = v.char_index_to_byte(200); + vm.new_value_error(wtf8_concat!( + format!("invalid literal for int() with base {base}: "), + &v.as_wtf8()[..end] + )) } BytesToIntError::InvalidBase => { vm.new_value_error("int() base must be >= 2 and <= 36, or 0") diff --git a/crates/vm/src/protocol/object.rs b/crates/vm/src/protocol/object.rs index 472f33c26f5..226f9bf416b 100644 --- a/crates/vm/src/protocol/object.rs +++ b/crates/vm/src/protocol/object.rs @@ -3,18 +3,31 @@ use crate::{ AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{ - PyBaseObject, PyBytes, PyDict, PyDictRef, PyGenericAlias, PyInt, PyList, PyStr, PyTuple, + PyBaseObject, PyBytes, PyDict, PyDictRef, PyGenericAlias, PyInt, PyListRef, PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef, PyUtf8Str, int::check_int_to_str_digits, pystr::AsPyStr, }, common::{hash::PyHash, str::to_ascii}, convert::ToPyObject, dict_inner::DictKey, function::{Either, FuncArgs, PyArithmeticValue, PySetterValue}, - object::PyPayload, protocol::PyIter, types::{Constructor, PyComparisonOp}, }; +/// Converts an index key the way a sequence does before it refuses the +/// operation, so an error from `__index__` or the size check wins. +pub(crate) fn sequence_index_key(key: &PyObject, vm: &VirtualMachine) -> PyResult> { + let Some(index) = key.try_index_opt(vm) else { + return Ok(None); + }; + index?.try_to_primitive(vm).map(Some).map_err(|_| { + vm.new_index_error(format!( + "cannot fit '{}' into an index-sized integer", + key.class().name() + )) + }) +} + // RustPython doesn't need these items // PyObject *Py_NotImplemented // Py_RETURN_NOTIMPLEMENTED @@ -56,26 +69,20 @@ impl PyObjectRef { } // PyObject *PyObject_Dir(PyObject *o) - pub fn dir(self, vm: &VirtualMachine) -> PyResult { - let attributes = self.class().get_attributes(&vm.ctx); - - let dict = PyDict::from_attributes(attributes, vm)?.into_ref(&vm.ctx); - - if let Some(object_dict) = self.dict() { - vm.call_method( - dict.as_object(), - identifier!(vm, update).as_str(), - (object_dict,), - )?; - } - - let attributes = dict.into_iter().map(|(k, _v)| k).collect::>(); - - Ok(PyList::from(attributes)) + pub fn dir(self, vm: &VirtualMachine) -> PyResult { + vm.dir(Some(self)) } } impl PyObject { + /// Return the truth value of an optional abstract-method marker. + pub(crate) fn is_abstract(&self, vm: &VirtualMachine) -> PyResult { + match vm.get_attribute_opt(self, "__isabstractmethod__")? { + Some(marker) => marker.try_to_bool(vm), + None => Ok(false), + } + } + /// Takes an object and returns an iterator for it. /// This is typically a new iterator but if the argument is an iterator, this /// returns itself. @@ -327,7 +334,7 @@ impl PyObject { ) -> PyResult> { // Single recursion guard for the entire comparison // (do_richcompare in Objects/object.c). - vm.with_recursion("in comparison", || self._cmp_inner(other, op, vm)) + vm.with_recursion(" in comparison", || self._cmp_inner(other, op, vm)) } fn _cmp_inner( @@ -419,7 +426,7 @@ impl PyObject { } pub fn repr(&self, vm: &VirtualMachine) -> PyResult> { - vm.with_recursion("while getting the repr of an object", || { + vm.with_recursion(" while getting the repr of an object", || { self.class().slots().repr.load().map_or_else( || { Err(vm.new_runtime_error(format!( @@ -542,7 +549,7 @@ impl PyObject { debug_assert!(n >= 2); for i in 0..n { - let result = vm.with_recursion("in __issubclass__", || { + let result = vm.with_recursion(" in __issubclass__", || { bases.as_slice()[i].abstract_issubclass(cls, vm) })?; @@ -611,7 +618,7 @@ impl PyObject { // Check if cls is a tuple if let Some(tuple) = cls.downcast_ref::() { for item in tuple { - if vm.with_recursion("in __subclasscheck__", || derived.is_subclass(item, vm))? { + if vm.with_recursion(" in __subclasscheck__", || derived.is_subclass(item, vm))? { return Ok(true); } } @@ -620,7 +627,7 @@ impl PyObject { // Check for __subclasscheck__ method using lookup_special if let Some(checker) = cls.lookup_special(identifier!(vm, __subclasscheck__), vm)? { - let res = vm.with_recursion("in __subclasscheck__", || { + let res = vm.with_recursion(" in __subclasscheck__", || { checker.call((derived.to_owned(),), vm) })?; return res.try_to_bool(vm); @@ -698,7 +705,7 @@ impl PyObject { // Check if cls is a tuple if let Some(tuple) = cls.downcast_ref::() { for item in tuple { - if vm.with_recursion("in __instancecheck__", || { + if vm.with_recursion(" in __instancecheck__", || { self.object_recursive_isinstance(item, vm) })? { return Ok(true); @@ -709,7 +716,7 @@ impl PyObject { // Check for __instancecheck__ method using lookup_special if let Some(checker) = cls.lookup_special(identifier!(vm, __instancecheck__), vm)? { - let res = vm.with_recursion("in __instancecheck__", || { + let res = vm.with_recursion(" in __instancecheck__", || { checker.call((self.to_owned(),), vm) })?; return res.try_to_bool(vm); @@ -721,7 +728,7 @@ impl PyObject { pub fn hash(&self, vm: &VirtualMachine) -> PyResult { if let Some(hash) = self.class().slots().hash.load() { - return vm.with_recursion("while hashing", || hash(self, vm)); + return vm.with_recursion(" while hashing", || hash(self, vm)); } Err(vm.new_type_error(format!("unhashable type: '{}'", self.class().slot_name()))) @@ -812,6 +819,10 @@ impl PyObject { return f(seq, i, Some(value), vm); } + // Every heap type carries a sequence table. + if seq.slots().has_any() || self.class().heaptype_ext().is_some() { + sequence_index_key(&needle.to_pyobject(vm), vm)?; + } Err(vm.new_type_error(format!( "'{}' object does not support item assignment", self.class().slot_name() @@ -836,8 +847,11 @@ impl PyObject { // A type carrying a sequence table turns the deletion down in // PySequence_DelItem's words instead; every heap type carries one. + let index_key = (seq.slots().has_any() || self.class().heaptype_ext().is_some()) + && sequence_index_key(&needle.to_pyobject(vm), vm)?.is_some(); + // Read the name only now: the key's __index__ may have renamed the type. let name = self.class().slot_name(); - let msg = if seq.slots().has_any() || self.class().heaptype_ext().is_some() { + let msg = if index_key { format!("'{name}' object doesn't support item deletion") } else { format!("'{name}' object does not support item deletion") diff --git a/crates/vm/src/protocol/sequence.rs b/crates/vm/src/protocol/sequence.rs index 33b3eb54d81..794b7d1b62b 100644 --- a/crates/vm/src/protocol/sequence.rs +++ b/crates/vm/src/protocol/sequence.rs @@ -474,6 +474,11 @@ impl PySequence<'_> { return f(self, target, vm); } + self.iter_contains(target, vm) + } + + /// Search without dispatching the sequence's contains slot again. + pub(crate) fn iter_contains(self, target: &PyObject, vm: &VirtualMachine) -> PyResult { // CPython parity: when neither __contains__ nor __iter__ is available, // `PySequence_Contains` rewords the get_iter TypeError into the // membership-test wording. Other exception types propagate unchanged. diff --git a/crates/vm/src/py_io.rs b/crates/vm/src/py_io.rs index aa3fea8e545..0a19216c51b 100644 --- a/crates/vm/src/py_io.rs +++ b/crates/vm/src/py_io.rs @@ -2,7 +2,7 @@ use core::{fmt, ops}; use std::io; use crate::{ - PyObject, PyObjectRef, PyResult, VirtualMachine, + AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine, builtins::{PyBaseExceptionRef, PyBytes, PyStr}, common::ascii, }; @@ -68,6 +68,17 @@ impl Write for PyWriter<'_> { } } +// PyFile_WriteObject with Py_PRINT_RAW: resolve the writer before converting +// the object, since either operation can run Python code and replace write. +pub fn file_write_object(file: &PyObject, obj: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + let write = file.get_attr("write", vm)?; + let text = obj.str(vm)?; + let result = write.call((text.clone(),), vm); + drop(text); + drop(write); + result.map(drop) +} + pub fn file_readline(obj: &PyObject, size: Option, vm: &VirtualMachine) -> PyResult { let args = size.map_or_else(Vec::new, |size| vec![vm.ctx.new_int(size).into()]); let ret = vm.call_method(obj, "readline", args)?; @@ -106,7 +117,12 @@ pub fn file_readline(obj: &PyObject, size: Option, vm: &VirtualMachine) - b.into() } } - _ => return Err(vm.new_type_error("object.readline() returned non-string")), + other => + return Err(vm.new_type_error(format!( + "{}.readline() must return a str, not {}", + obj.class().fully_qualified_name(vm)?, + other.class().fully_qualified_name(vm)?, + ))), }); Ok(ret) } diff --git a/crates/vm/src/scope.rs b/crates/vm/src/scope.rs index 772d5c176c8..976cf750772 100644 --- a/crates/vm/src/scope.rs +++ b/crates/vm/src/scope.rs @@ -1,10 +1,14 @@ -use crate::{VirtualMachine, builtins::PyDictRef, function::ArgMapping}; +use crate::{ + PyRef, VirtualMachine, + builtins::{PyAnyDict, PyDictRef}, + function::ArgMapping, +}; use alloc::fmt; #[derive(Clone)] pub struct Scope { pub locals: Option, - pub globals: PyDictRef, + pub globals: PyRef, } impl fmt::Debug for Scope { @@ -17,8 +21,11 @@ impl fmt::Debug for Scope { impl Scope { #[inline] #[must_use] - pub const fn new(locals: Option, globals: PyDictRef) -> Self { - Self { locals, globals } + pub fn new(locals: Option, globals: impl Into>) -> Self { + Self { + locals, + globals: globals.into(), + } } pub fn with_builtins( diff --git a/crates/vm/src/sequence.rs b/crates/vm/src/sequence.rs index 6d3016efd54..d2ec920e8e0 100644 --- a/crates/vm/src/sequence.rs +++ b/crates/vm/src/sequence.rs @@ -1,7 +1,7 @@ use crate::{ AsObject, PyObject, PyObjectRef, PyResult, function::OptionalArg, - sliceable::SequenceIndexOp, + sliceable::to_saturated_index, types::PyComparisonOp, vm::{MAX_MEMORY_SIZE, VirtualMachine}, }; @@ -160,18 +160,47 @@ impl SequenceMutExt for Vec { pub struct OptionalRangeArgs { #[pyarg(positional, default = 0)] start: PyObjectRef, - // Platform ssize maximum. Missing is clamped to the sequence length. - #[pyarg(positional, optional, py_default = "9223372036854775807")] + // Platform ssize maximum; a growing list may reach beyond its initial length. + #[pyarg(positional, optional, py_default = "sys.maxsize")] stop: OptionalArg, } +impl Drop for OptionalRangeArgs { + fn drop(&mut self) { + // Call arguments are released right to left after conversion and search. + // Keep both bounds alive until then, but release stop before start. + drop(core::mem::replace(&mut self.stop, OptionalArg::Missing)); + } +} + impl OptionalRangeArgs { - pub fn saturate(self, len: usize, vm: &VirtualMachine) -> PyResult<(usize, usize)> { - let saturate = |obj: PyObjectRef| -> PyResult<_> { - Ok(obj.try_index(vm)?.as_bigint().saturated_at(len)) + pub fn index_range( + &self, + len: impl FnOnce() -> usize, + vm: &VirtualMachine, + ) -> PyResult> { + let convert = |obj: &PyObject| { + to_saturated_index( + vm, + obj, + "slice indices must be integers or have an __index__ method", + ) + }; + let start = convert(&self.start)?; + let stop = match &self.stop { + OptionalArg::Present(stop) => convert(stop)?, + OptionalArg::Missing => isize::MAX, + }; + // Both conversions may mutate the list. Normalize negative bounds only + // after they finish, and leave positive bounds open to later growth. + let len = len() as isize; + let normalize = |index: isize| { + if index < 0 { + index.saturating_add(len).max(0) as usize + } else { + index as usize + } }; - let start = saturate(self.start)?; - let stop = self.stop.map_or(Ok(len), saturate)?; - Ok((start, stop)) + Ok(normalize(start)..normalize(stop)) } } diff --git a/crates/vm/src/signal.rs b/crates/vm/src/signal.rs index ddd4d58e556..f53f8bcc967 100644 --- a/crates/vm/src/signal.rs +++ b/crates/vm/src/signal.rs @@ -1,5 +1,6 @@ +use alloc::sync::Arc; use core::{ - cell::{Cell, RefCell}, + cell::Cell, fmt, ops::{Deref, DerefMut, Index, IndexMut, Range}, sync::atomic::{AtomicBool, AtomicU8, Ordering}, @@ -55,9 +56,45 @@ const ATOMIC_FALSE: AtomicBool = AtomicBool::new(false); pub(crate) static TRIGGERS: [AtomicBool; NSIG] = [ATOMIC_FALSE; NSIG]; +// Process-global disposition metadata lets interrupt_main run from any +// interpreter without borrowing Python objects owned by the main interpreter. +#[cfg(feature = "host_env")] +pub(crate) static INTERRUPT_IGNORED: [AtomicBool; NSIG] = [ATOMIC_FALSE; NSIG]; + #[cfg(windows)] static SIGINT_EVENT: AtomicIsize = AtomicIsize::new(0); +/// `_PyRuntime.signals.unhandled_keyboard_interrupt` +static UNHANDLED_KEYBOARD_INTERRUPT: AtomicBool = AtomicBool::new(false); + +pub(crate) fn set_unhandled_keyboard_interrupt() { + UNHANDLED_KEYBOARD_INTERRUPT.store(true, Ordering::Relaxed); +} + +pub(crate) fn clear_unhandled_keyboard_interrupt() { + UNHANDLED_KEYBOARD_INTERRUPT.store(false, Ordering::Relaxed); +} + +pub(crate) fn unhandled_keyboard_interrupt() -> bool { + UNHANDLED_KEYBOARD_INTERRUPT.load(Ordering::Relaxed) +} + +/// exit_sigint: exit through the default SIGINT handler so that the parent +/// process sees that a KeyboardInterrupt went unhandled. +pub(crate) fn exit_sigint() -> u32 { + cfg_select! { + unix => { + if crate::host_env::signal::set_sigint_default_onstack().is_ok() { + let _ = crate::host_env::signal::send_sigint_to_self(); + } + libc::SIGINT as u32 + 128 + } + // STATUS_CONTROL_C_EXIT + windows => 0xC000013A, + _ => 2 + 128, + } +} + thread_local! { /// Prevent recursive signal handler invocation. When a Python signal /// handler is running, new signals are deferred until it completes. @@ -75,18 +112,24 @@ impl Drop for SignalHandlerGuard { #[cfg_attr(feature = "flame-it", flame)] #[inline(always)] pub fn check_signals(vm: &VirtualMachine) -> PyResult<()> { - if vm.signal_handlers.get().is_none() { + // Read-only check first: avoids cache-line invalidation on every + // instruction when no signal is pending (the common case). + let user_pending = vm + .signal_rx + .as_ref() + .is_some_and(UserSignalReceiver::is_pending); + if !EVAL_BREAKER.contains(&EvalBreakerFlag::Signal) && !user_pending { return Ok(()); } - // Read-only check first: avoids cache-line invalidation on every - // instruction when no signal is pending (the common case). - if !EVAL_BREAKER.contains(&EvalBreakerFlag::Signal) { + // A thread with neither OS-signal dispatch permission nor its own user + // signal receiver must not consume another VM's wakeup. + if vm.signal_rx.is_none() && !(vm.is_main_thread() && vm.state.is_main_interpreter()) { return Ok(()); } // Atomic RMW only when a signal is actually pending. - if !EVAL_BREAKER.remove(EvalBreakerFlag::Signal) { + if !EVAL_BREAKER.remove(EvalBreakerFlag::Signal) && !user_pending { return Ok(()); } @@ -103,38 +146,88 @@ fn trigger_signals(vm: &VirtualMachine) -> PyResult<()> { } let _guard = SignalHandlerGuard; - let signal_handlers = vm - .signal_handlers - .get() - .expect("should never fail since we check above"); - - for (signum, trigger) in TRIGGERS.iter().enumerate().skip(1) { - let triggered = trigger.swap(false, Ordering::Relaxed); - if !triggered { - continue; + let can_handle_signals = vm.is_main_thread() && vm.state.is_main_interpreter(); + if can_handle_signals { + let signal_handlers = &vm.state.signal_handlers; + let frame = crate::frame::current_complete_frame_for_trace(vm); + + for (signum, trigger) in TRIGGERS.iter().enumerate().skip(1) { + let triggered = trigger.swap(false, Ordering::Relaxed); + if !triggered { + continue; + } + + // SAFETY: TRIGGERS has the same length as the signal_handlers + let signum = unsafe { SignalNum::new_unchecked(signum as i32) }; + + // Read the handler out and drop the lock before running it. A + // handler is free to call signal.signal(), which takes the same lock. + // Release it before calling Python to avoid deadlock. + let handler = signal_handlers.lock()[signum].clone(); + + let handler = handler.filter(|handler| !vm.is_none(handler)); + #[cfg(feature = "host_env")] + let handler = handler.filter(|handler| { + crate::stdlib::_signal::_signal::handler_disposition(handler, vm).is_none() + }); + let Some(handler) = handler else { + vm.run_unraisable( + vm.new_os_error(format!( + "Signal {} ignored due to race condition", + signum.as_i32() + )), + Some("Exception ignored while calling signal handler".to_owned()), + vm.ctx.none(), + ); + continue; + }; + + // A handler can cease to be callable after registration. Invoke it + // normally so that this raises TypeError instead of losing a signal. + // Keep the interrupted complete frame alive across every callback, + // including handlers which re-enter signal dispatch. + if let Err(exc) = handler.call((signum.as_i32(), frame.clone()), vm) { + // On error, re-schedule a call to trigger_signals() for the + // remaining signals and the pending wakeup errors. + set_triggered(); + return Err(exc); + } } - - // SAFETY: TRIGGERS has the same length as the signal_handlers - let signum = unsafe { SignalNum::new_unchecked(signum as i32) }; - - // Read the handler out and drop the borrow before running it. A - // handler is free to call signal.signal(), which takes the same cell - // mutably, and a live read borrow turns that into a panic. - let handler = signal_handlers.borrow()[signum].clone(); - - if let Some(handler) = handler - && let Some(callable) = handler.to_callable() - { - callable.invoke((signum.as_i32(), vm.ctx.none()), vm)?; + } else { + let os_signals_pending = TRIGGERS + .iter() + .skip(1) + .any(|trigger| trigger.load(Ordering::Relaxed)); + #[cfg(all(feature = "host_env", any(unix, windows)))] + let os_signals_pending = + os_signals_pending || crate::stdlib::_signal::_signal::wakeup_errors_pending(); + if os_signals_pending { + // Leave OS signals for the main interpreter's main thread. Re-arm + // before running VM-local callbacks, which may raise. + set_triggered(); } } if let Some(signal_rx) = &vm.signal_rx { + // Clear before draining: a concurrent send after this point sets the + // owning VM's hint again, independently of other VMs and OS signals. + signal_rx.pending.store(false, Ordering::Release); for f in signal_rx.rx.try_iter() { - f(vm)?; + if let Err(exc) = f(vm) { + signal_rx.pending.store(true, Ordering::Release); + set_triggered(); + return Err(exc); + } } } + // Wakeup fd errors are pending calls that only the main interpreter's + // main thread runs. + #[cfg(all(feature = "host_env", any(unix, windows)))] + if can_handle_signals { + crate::stdlib::_signal::_signal::report_wakeup_errors(vm); + } + Ok(()) } @@ -233,6 +326,10 @@ impl SignalNum { #[allow(dead_code, reason = "Not used on all platforms")] pub(crate) const SIGINT: Self = Self(libc::SIGINT); + #[cfg(all(target_os = "wasi", feature = "host_env"))] + #[allow(dead_code, reason = "Not used on all platforms")] + pub(crate) const SIGINT: Self = Self(rustpython_host_env::signal::SIGINT); + /// Construct [`Self`] without any validation on the signalnum value. /// /// # Safety @@ -297,16 +394,10 @@ impl TryFromObject for SignalNum { /// Missing signal handler for the given signal number is silently ignored. #[cfg(all(not(target_arch = "wasm32"), feature = "host_env"))] pub fn set_interrupt_ex(signum: SignalNum) -> PyResult<()> { - use crate::stdlib::_signal::_signal::{SIG_DFL, SIG_IGN, run_signal}; - - match signum.as_usize() { - SIG_DFL | SIG_IGN => Ok(()), - _ => { - // interrupt the main thread with given signal number - run_signal(signum.into()); - Ok(()) - } + if !INTERRUPT_IGNORED[signum.as_usize()].load(Ordering::Relaxed) { + crate::stdlib::_signal::_signal::run_signal(signum.into()); } + Ok(()) } pub type UserSignal = Box PyResult<()> + Send>; @@ -314,11 +405,19 @@ pub type UserSignal = Box PyResult<()> + Send>; #[derive(Clone, Debug)] pub struct UserSignalSender { tx: mpsc::Sender, + pending: Arc, } #[derive(Debug)] pub struct UserSignalReceiver { rx: mpsc::Receiver, + pending: Arc, +} + +impl UserSignalReceiver { + pub(crate) fn is_pending(&self) -> bool { + self.pending.load(Ordering::Acquire) + } } impl UserSignalSender { @@ -326,7 +425,7 @@ impl UserSignalSender { self.tx .send(sig) .map_err(|mpsc::SendError(sig)| UserSignalSendError(sig))?; - set_triggered(); + self.pending.store(true, Ordering::Release); Ok(()) } } @@ -349,7 +448,14 @@ impl fmt::Display for UserSignalSendError { #[must_use] pub fn user_signal_channel() -> (UserSignalSender, UserSignalReceiver) { let (tx, rx) = mpsc::channel(); - (UserSignalSender { tx }, UserSignalReceiver { rx }) + let pending = Arc::new(AtomicBool::new(false)); + ( + UserSignalSender { + tx, + pending: pending.clone(), + }, + UserSignalReceiver { rx, pending }, + ) } #[cfg(windows)] @@ -385,16 +491,18 @@ impl IndexMut for SignalHandlersInner { } } -pub struct SignalHandlers(Box>); +pub struct SignalHandlers(Box>); impl Default for SignalHandlers { fn default() -> Self { - Self(Box::new(RefCell::new(SignalHandlersInner::default()))) + Self(Box::new(crate::common::lock::PyMutex::new( + SignalHandlersInner::default(), + ))) } } impl Deref for SignalHandlers { - type Target = Box>; + type Target = Box>; fn deref(&self) -> &Self::Target { &self.0 diff --git a/crates/vm/src/sliceable.rs b/crates/vm/src/sliceable.rs index e859c7a3a37..d2a141f7a24 100644 --- a/crates/vm/src/sliceable.rs +++ b/crates/vm/src/sliceable.rs @@ -97,17 +97,17 @@ where fn delitem_by_slice(&mut self, _vm: &VirtualMachine, slice: SaturatedSlice) -> PyResult<()> { let (range, step, slice_len) = slice.adjust_indices(self.as_ref().len()); if slice_len == 0 { - Ok(()) - } else if step == 1 || step == -1 { + return Ok(()); + } + if step == 1 || step == -1 { self.do_set_range(range, &[]); - Ok(()) } else { self.do_delete_indexes( range.clone(), SaturatedSliceIter::from_adjust_indices(range, step, slice_len).positive_order(), ); - Ok(()) } + Ok(()) } } @@ -257,6 +257,34 @@ pub enum SequenceIndex { Slice(SaturatedSlice), } +/// Compile-time type name used in sequence index TypeErrors. +/// +/// `&'static str` is not a legal const-generic type, so the name is an associated +/// constant on a marker type, the same pattern as [`crate::function::ArgName`]. +pub trait SequenceIndexName { + const NAME: &'static str; +} + +macro_rules! sequence_index_name { + ($($ty:ident = $name:literal),* $(,)?) => {$( + #[derive(Clone, Copy, Debug)] + pub struct $ty; + impl SequenceIndexName for $ty { + const NAME: &'static str = $name; + } + )*}; +} + +sequence_index_name! { + NameList = "list", + NameTuple = "tuple", + NameByte = "byte", + NameBytearray = "bytearray", + NameArray = "array", + NameMmap = "mmap", + NameElement = "element", +} + impl SequenceIndex { /// The index or slice `obj` stands for, or `None` when it is neither. fn try_from_object_opt(vm: &VirtualMachine, obj: &PyObject) -> Option> { @@ -280,27 +308,47 @@ impl SequenceIndex { } } - pub fn try_from_borrowed_object( + fn try_from_object( vm: &VirtualMachine, obj: &PyObject, - type_name: &str, + err_fmt: fn(&str) -> String, ) -> PyResult { - Self::try_from_object_opt(vm, obj).unwrap_or_else(|| { - Err(vm.new_type_error(format!( - "{type_name} indices must be integers or slices, not {}", - obj.class().slot_name() - ))) - }) + Self::try_from_object_opt(vm, obj) + .unwrap_or_else(|| Self::index_type_error(vm, obj, err_fmt)) + } + + #[cold] + #[inline(never)] + fn index_type_error( + vm: &VirtualMachine, + obj: &PyObject, + err_fmt: fn(&str) -> String, + ) -> PyResult { + let class_name = obj.class().slot_name(); + Err(vm.new_type_error(err_fmt(&class_name))) + } + + fn sequence_index_type_error(class_name: &str) -> String { + format!( + "{} indices must be integers or slices, not {class_name:.200}", + N::NAME + ) + } + + fn str_index_type_error(class_name: &str) -> String { + format!("string indices must be integers, not '{class_name:.200}'") + } + + pub fn try_from_borrowed_object( + vm: &VirtualMachine, + obj: &PyObject, + ) -> PyResult { + Self::try_from_object(vm, obj, Self::sequence_index_type_error::) } /// `unicode_subscript`, which turns down what it cannot use in its own words. pub fn try_from_str_subscript(vm: &VirtualMachine, obj: &PyObject) -> PyResult { - Self::try_from_object_opt(vm, obj).unwrap_or_else(|| { - Err(vm.new_type_error(format!( - "string indices must be integers, not '{}'", - obj.class().slot_name() - ))) - }) + Self::try_from_object(vm, obj, Self::str_index_type_error) } } @@ -543,14 +591,21 @@ fn to_isize_index(vm: &VirtualMachine, obj: &PyObject) -> PyResult if vm.is_none(obj) { return Ok(None); } - let result = obj.try_index_opt(vm).unwrap_or_else(|| { - Err(vm.new_type_error("slice indices must be integers or None or have an __index__ method")) - })?; - let value = result.as_bigint(); - let is_negative = value.is_negative(); - Ok(Some(value.to_isize().unwrap_or(if is_negative { - isize::MIN - } else { - isize::MAX - }))) + to_saturated_index( + vm, + obj, + "slice indices must be integers or None or have an __index__ method", + ) + .map(Some) +} + +pub(crate) fn to_saturated_index( + vm: &VirtualMachine, + obj: &PyObject, + type_error: &'static str, +) -> PyResult { + let result = obj + .try_index_opt(vm) + .unwrap_or_else(|| Err(vm.new_type_error(type_error)))?; + Ok(result.as_saturated_index()) } diff --git a/crates/vm/src/stdlib/_abc.rs b/crates/vm/src/stdlib/_abc.rs index 19cf47415a9..b3aa28b3bc9 100644 --- a/crates/vm/src/stdlib/_abc.rs +++ b/crates/vm/src/stdlib/_abc.rs @@ -160,9 +160,7 @@ mod _abc { let value = &elements[1]; // Check if value has __isabstractmethod__ = True - if let Ok(is_abstract) = value.get_attr("__isabstractmethod__", vm) - && is_abstract.try_to_bool(vm)? - { + if value.is_abstract(vm)? { abstracts.push(key.clone()); } } @@ -180,8 +178,7 @@ mod _abc { // Try to get the attribute from cls - key should be a string if let Some(key_str) = key.downcast_ref::() && let Some(value) = vm.get_attribute_opt(cls, key_str)? - && let Ok(is_abstract) = value.get_attr("__isabstractmethod__", vm) - && is_abstract.try_to_bool(vm)? + && value.is_abstract(vm)? { abstracts.push(key); } @@ -272,7 +269,9 @@ mod _abc { let impl_data = get_impl(&cls, vm)?; // Get instance.__class__ - let subclass = instance.get_attr("__class__", vm)?; + let subclass = vm + .get_attribute_opt(&instance, "__class__")? + .unwrap_or_else(|| instance.class().to_owned().into()); // Check cache if in_weak_set(&impl_data.cache, &subclass, vm)? { diff --git a/crates/vm/src/stdlib/_ast.rs b/crates/vm/src/stdlib/_ast.rs index bba073d5b0c..f66603f08f2 100644 --- a/crates/vm/src/stdlib/_ast.rs +++ b/crates/vm/src/stdlib/_ast.rs @@ -7,6 +7,8 @@ pub(crate) use python::_ast::module_def; mod pyast; +mod source_location; +use source_location::{AstNodeRange, AstSourceContext}; use crate::builtins::{PyInt, PyStr}; use crate::stdlib::_ast::module::{Mod, ModFunctionType, ModInteractive, ModModule}; @@ -99,7 +101,7 @@ fn get_node_field_required( fn get_required_identifier_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, obj: &PyObject, field: &'static str, typ: &str, @@ -113,7 +115,7 @@ fn get_required_identifier_field( fn get_required_node_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, obj: &PyObject, field: &'static str, typ: &str, @@ -140,7 +142,7 @@ fn get_node_field_opt( fn get_node_list_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, obj: &PyObject, field: &'static str, typ: &str, @@ -170,7 +172,7 @@ fn get_node_list_field_object( fn convert_node_list_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, list: &Py, field: &'static str, typ: &str, @@ -202,7 +204,7 @@ fn convert_node_list_field( fn get_node_boxed_slice_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, obj: &PyObject, field: &'static str, typ: &str, @@ -323,50 +325,8 @@ fn get_ast_string_field_opt( } struct PySourceRange { - start: PySourceLocation, - end: PySourceLocation, -} - -pub(crate) struct PySourceLocation { - row: Row, - column: Column, -} - -impl PySourceLocation { - const fn to_source_location(&self) -> SourceLocation { - SourceLocation { - line: self.row.get_one_indexed(), - character_offset: self.column.get_one_indexed(), - } - } -} - -/// A one-based index into the lines. -#[derive(Clone, Copy)] -struct Row(OneIndexed); - -impl Row { - const fn get(self) -> usize { - self.0.get() - } - - const fn get_one_indexed(self) -> OneIndexed { - self.0 - } -} - -/// An UTF-8 index into the line. -#[derive(Clone, Copy)] -struct Column(TextSize); - -impl Column { - const fn get(self) -> usize { - self.0.to_usize() - } - - const fn get_one_indexed(self) -> OneIndexed { - OneIndexed::from_zero_indexed(self.get()) - } + start: SourceLocation, + end: SourceLocation, } fn text_range_to_source_range(source_file: &SourceFile, text_range: TextRange) -> PySourceRange { @@ -375,31 +335,14 @@ fn text_range_to_source_range(source_file: &SourceFile, text_range: TextRange) - if source.is_empty() { return PySourceRange { - start: PySourceLocation { - row: Row(OneIndexed::from_zero_indexed(0)), - column: Column(TextSize::new(0)), - }, - end: PySourceLocation { - row: Row(OneIndexed::from_zero_indexed(0)), - column: Column(TextSize::new(0)), - }, + start: SourceLocation::default(), + end: SourceLocation::default(), }; } - let start_row = index.line_index(text_range.start()); - let end_row = index.line_index(text_range.end()); - let start_col = text_range.start() - index.line_start(start_row, source); - let end_col = text_range.end() - index.line_start(end_row, source); - PySourceRange { - start: PySourceLocation { - row: Row(start_row), - column: Column(start_col), - }, - end: PySourceLocation { - row: Row(end_row), - column: Column(end_col), - }, + start: index.source_location(text_range.start(), source, PositionEncoding::Utf8), + end: index.source_location(text_range.end(), source, PositionEncoding::Utf8), } } @@ -522,12 +465,26 @@ fn copy_ast_passthrough_fields( &["kind"] } else if is_node_instance(vm, target, pyast::NodeExprInterpolation::static_type())? { &["str"] + } else if is_node_instance(vm, target, pyast::NodeStmtImport::static_type())? + || is_node_instance(vm, target, pyast::NodeStmtImportFrom::static_type())? + { + &["is_lazy"] } else { &[] }; for field in fields { if let Some(value) = vm.get_attribute_opt(source, *field)? { + let value = if *field == "is_lazy" { + let value = if vm.is_none(&value) { + 0 + } else { + node_object_to_i32(vm, &value)? + }; + vm.ctx.new_int(value).into() + } else { + value + }; target.set_attr(*field, value, vm)?; } } @@ -704,95 +661,101 @@ fn synthetic_source_from_ast_object(vm: &VirtualMachine, object: &PyObject) -> P fn range_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, name: &str, -) -> PyResult { +) -> PyResult { range_from_object_impl(vm, source_file, object, name, false) } fn type_param_range_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, -) -> PyResult { +) -> PyResult { range_from_object_impl(vm, source_file, object, "type_param", true) } fn expr_range_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, -) -> PyResult { +) -> PyResult { range_from_object_impl(vm, source_file, object, "expr", false) } fn stmt_range_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, -) -> PyResult { +) -> PyResult { range_from_object_impl(vm, source_file, object, "stmt", false) } fn pattern_range_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, -) -> PyResult { +) -> PyResult { range_from_object_impl(vm, source_file, object, "pattern", true) } fn excepthandler_range_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, -) -> PyResult { +) -> PyResult { range_from_object_impl(vm, source_file, object, "excepthandler", false) } fn excepthandler_range_from_object_unvalidated( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, -) -> PyResult { +) -> PyResult { let start_row = get_int_field(vm, object, "lineno", "excepthandler")?; let start_column = get_int_field(vm, object, "col_offset", "excepthandler")?; let end_row = get_opt_int_field(vm, object, "end_lineno")?.unwrap_or(start_row); let end_column = get_opt_int_field(vm, object, "end_col_offset")?.unwrap_or(start_column); let location = PySourceRange { - start: PySourceLocation { - row: Row(if start_row > 0 { + start: SourceLocation { + line: if start_row > 0 { OneIndexed::new(start_row as usize).unwrap_or(OneIndexed::MIN) } else { OneIndexed::MIN - }), - column: Column(TextSize::new(start_column.max(0) as u32)), + }, + character_offset: OneIndexed::from_zero_indexed(start_column.max(0) as usize), }, - end: PySourceLocation { - row: Row(if end_row > 0 { + end: SourceLocation { + line: if end_row > 0 { OneIndexed::new(end_row as usize).unwrap_or(OneIndexed::MIN) } else { OneIndexed::MIN - }), - column: Column(TextSize::new(end_column.max(0) as u32)), + }, + character_offset: OneIndexed::from_zero_indexed(end_column.max(0) as usize), }, }; - Ok(source_range_to_text_range_unvalidated( - source_file, - location, - )) + source_file.register( + vm, + source_range_to_text_range(source_file, location), + Some(rustpython_compiler_core::SourceLocationRange { + line: start_row, + end_line: end_row, + col: start_column, + end_col: end_column, + }), + ) } fn range_from_object_impl( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, name: &str, end_required: bool, -) -> PyResult { +) -> PyResult { let start_row = get_int_field(vm, object, "lineno", name)?; let start_column = get_int_field(vm, object, "col_offset", name)?; let end_row = if end_required { @@ -832,25 +795,34 @@ fn range_from_object_impl( } let location = PySourceRange { - start: PySourceLocation { - row: Row(if start_row_val > 0 { + start: SourceLocation { + line: if start_row_val > 0 { OneIndexed::new(start_row_val as usize).unwrap_or(OneIndexed::MIN) } else { OneIndexed::MIN - }), - column: Column(TextSize::new(start_col_val.max(0) as u32)), + }, + character_offset: OneIndexed::from_zero_indexed(start_col_val.max(0) as usize), }, - end: PySourceLocation { - row: Row(if end_row_val > 0 { + end: SourceLocation { + line: if end_row_val > 0 { OneIndexed::new(end_row_val as usize).unwrap_or(OneIndexed::MIN) } else { OneIndexed::MIN - }), - column: Column(TextSize::new(end_col_val.max(0) as u32)), + }, + character_offset: OneIndexed::from_zero_indexed(end_col_val.max(0) as usize), }, }; - Ok(source_range_to_text_range(source_file, location)) + source_file.register( + vm, + source_range_to_text_range(source_file, location), + Some(rustpython_compiler_core::SourceLocationRange { + line: start_row, + end_line: end_row, + col: start_column, + end_col: end_column, + }), + ) } fn source_range_to_text_range(source_file: &SourceFile, location: PySourceRange) -> TextRange { @@ -861,46 +833,33 @@ fn source_range_to_text_range(source_file: &SourceFile, location: PySourceRange) return TextRange::new(TextSize::new(0), TextSize::new(0)); } - let start = index.offset( - location.start.to_source_location(), - source, - PositionEncoding::Utf8, - ); - let end = index.offset( - location.end.to_source_location(), - source, - PositionEncoding::Utf8, - ); + let start = index.offset(location.start, source, PositionEncoding::Utf8); + let end = index.offset(location.end, source, PositionEncoding::Utf8); - TextRange::new(start, end) + // Navigation is allowed to collapse normalized coordinates; semantic + // signed coordinates remain in AstSourceContext. + TextRange::new(start, end.max(start)) } -fn source_range_to_text_range_unvalidated( - source_file: &SourceFile, - location: PySourceRange, -) -> TextRange { - let index = LineIndex::from_source_text(source_file.clone().source_text()); - let source = &source_file.source_text(); - - if source.is_empty() { - return TextRange::new(TextSize::new(0), TextSize::new(0)); - } - - let start = index.offset( - location.start.to_source_location(), - source, - PositionEncoding::Utf8, - ); - let end = index.offset( - location.end.to_source_location(), - source, - PositionEncoding::Utf8, - ); - - if start <= end { - TextRange::new(start, end) +fn node_add_location_for_node( + dict: &Py, + range: TextRange, + vm: &VirtualMachine, + source_file: &AstSourceContext, + node_index: ast::NodeIndex, +) { + if let Some(location) = source_file.location(node_index) { + for (field, value) in [ + ("lineno", location.line), + ("end_lineno", location.end_line), + ("col_offset", location.col), + ("end_col_offset", location.end_col), + ] { + dict.set_item(field, vm.ctx.new_int(value).into(), vm) + .unwrap(); + } } else { - TextRange::empty(start) + node_add_location(dict, range, vm, source_file); } } @@ -908,22 +867,30 @@ fn node_add_location( dict: &Py, range: TextRange, vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, ) { let range = text_range_to_source_range(source_file, range); - dict.set_item("lineno", vm.ctx.new_int(range.start.row.get()).into(), vm) + dict.set_item("lineno", vm.ctx.new_int(range.start.line.get()).into(), vm) .unwrap(); dict.set_item( "col_offset", - vm.ctx.new_int(range.start.column.get()).into(), + vm.ctx + .new_int(range.start.character_offset.to_zero_indexed()) + .into(), + vm, + ) + .unwrap(); + dict.set_item( + "end_lineno", + vm.ctx.new_int(range.end.line.get()).into(), vm, ) .unwrap(); - dict.set_item("end_lineno", vm.ctx.new_int(range.end.row.get()).into(), vm) - .unwrap(); dict.set_item( "end_col_offset", - vm.ctx.new_int(range.end.column.get()).into(), + vm.ctx + .new_int(range.end.character_offset.to_zero_indexed()) + .into(), vm, ) .unwrap(); @@ -1024,11 +991,12 @@ fn type_comment_parse_error( ParseError { error: parser::ParseErrorType::OtherError(message.to_owned()), raw_location: range, - location: source_range.start.to_source_location(), - end_location: source_range.end.to_source_location(), + location: source_range.start, + end_location: source_range.end, source_path: source_file.name().to_owned(), is_unclosed_bracket: false, is_unclosed_string: false, + eof_token: None, } .into() } @@ -1265,6 +1233,44 @@ fn invalid_type_comment_syntax_error( None } +/// The parser phase where a rejected TYPE_COMMENT stops grammar actions. +/// Use the validator's token-backed location, not a textual comment search. +pub(crate) fn invalid_type_comment_warning_boundary( + source_file: &SourceFile, + parsed: &parser::Parsed, + interactive: bool, +) -> Option { + let comments = TypeCommentSource::new(source_file.source_text(), parsed.tokens()); + match invalid_type_comment_syntax_error(source_file, &comments)? { + CompileError::Parse(error) => { + let offset = error.raw_location.start().to_usize(); + (!interactive || type_comment_precedes_single_boundary(offset, source_file, parsed)) + .then_some(offset) + } + CompileError::Codegen(_) => None, + } +} + +fn type_comment_precedes_single_boundary( + offset: usize, + source_file: &SourceFile, + parsed: &parser::Parsed, +) -> bool { + use rustpython_compiler::SingleModeStatementBoundary; + match rustpython_compiler::single_mode_statement_boundary(parsed) { + Some(SingleModeStatementBoundary::Simple { end, .. }) => offset < end.to_usize(), + Some(SingleModeStatementBoundary::Compound { .. }) => { + // Compound input still requests NEWLINE after the statement. A + // rejected comment may be that next token, before the next AST node. + match rustpython_compiler::single_mode_multiple_statements_error(source_file, parsed) { + Some(CompileError::Parse(error)) => offset < error.raw_location.start().to_usize(), + _ => true, + } + } + None => true, + } +} + fn feature_version_syntax_error( source: &str, source_file: &SourceFile, @@ -1697,71 +1703,145 @@ fn apply_type_comments_to_module( } #[cfg(feature = "parser")] -fn ipython_escape_command_syntax_error( - top: &ast::Mod, - source_file: &SourceFile, -) -> Option { - use ast::visitor::{Visitor, walk_expr, walk_stmt}; +struct ParserAstValidator { + error: Option<(TextRange, ParserAstError)>, + target_version: ast::PythonVersion, +} + +#[cfg(feature = "parser")] +enum ParserAstError { + EscapeCommand, + TypeParamDefault, + ConstantIdentifier(&'static str), +} - #[derive(Default)] - struct IpyEscapeCommandVisitor { - range: Option, +#[cfg(feature = "parser")] +impl ParserAstValidator { + fn new(target_version: ast::PythonVersion) -> Self { + Self { + error: None, + target_version, + } } - impl Visitor<'_> for IpyEscapeCommandVisitor { - fn visit_stmt(&mut self, stmt: &ast::Stmt) { - if self.range.is_some() { - return; - } - match stmt { - ast::Stmt::IpyEscapeCommand(stmt) => { - self.range = Some(stmt.range); - } - _ => walk_stmt(self, stmt), + fn identifier(&mut self, name: &str, range: TextRange) { + if self.error.is_some() { + return; + } + // Imports combine dotted components after CPython has validated each + // component independently while constructing its parser AST. + for name in name.split('.') { + let name = match name { + "None" => "None", + "True" => "True", + "False" => "False", + _ => continue, + }; + self.error = Some((range, ParserAstError::ConstantIdentifier(name))); + break; + } + } + + fn into_error + From>( + self, + vm: &VirtualMachine, + source: &str, + source_file: &SourceFile, + ) -> Option { + let (range, kind) = self.error?; + match kind { + ParserAstError::ConstantIdentifier(name) => Some( + vm.new_value_error(format!( + "identifier field can't represent '{name}' constant" + )) + .into(), + ), + ParserAstError::TypeParamDefault => cpython_unsupported_syntax_error( + &parser::UnsupportedSyntaxError { + kind: parser::UnsupportedSyntaxErrorKind::TypeParamDefault, + range, + target_version: self.target_version, + }, + source, + source_file, + ) + .map(Into::into), + ParserAstError::EscapeCommand => { + let source_range = text_range_to_source_range(source_file, range); + Some( + CompileError::from(ParseError { + error: parser::ParseErrorType::OtherError("invalid syntax".to_owned()), + raw_location: range, + location: source_range.start, + end_location: source_range.end, + source_path: source_file.name().to_owned(), + is_unclosed_bracket: false, + is_unclosed_string: false, + eof_token: None, + }) + .into(), + ) } } + } +} - fn visit_expr(&mut self, expr: &ast::Expr) { - if self.range.is_some() { - return; - } - match expr { - ast::Expr::IpyEscapeCommand(expr) => { - self.range = Some(expr.range); - } - _ => walk_expr(self, expr), - } +#[cfg(feature = "parser")] +impl<'a> ast::visitor::source_order::SourceOrderVisitor<'a> for ParserAstValidator { + fn enter_node( + &mut self, + _node: ast::AnyNodeRef<'a>, + ) -> ast::visitor::source_order::TraversalSignal { + use ast::visitor::source_order::TraversalSignal; + if self.error.is_some() { + TraversalSignal::Skip + } else { + TraversalSignal::Traverse } } - let mut visitor = IpyEscapeCommandVisitor::default(); - match top { - ast::Mod::Module(module) => { - for statement in &module.body { - visitor.visit_stmt(statement); - if visitor.range.is_some() { - break; - } - } + fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { + if self.error.is_some() { + return; } - ast::Mod::Expression(expression) => { - visitor.visit_expr(&expression.body); + if let ast::Stmt::IpyEscapeCommand(stmt) = stmt { + self.error = Some((stmt.range, ParserAstError::EscapeCommand)); + } else { + ast::visitor::source_order::walk_stmt(self, stmt); } } - let range = visitor.range?; - let source_range = text_range_to_source_range(source_file, range); - Some( - ParseError { - error: parser::ParseErrorType::OtherError("invalid syntax".to_owned()), - raw_location: range, - location: source_range.start.to_source_location(), - end_location: source_range.end.to_source_location(), - source_path: source_file.name().to_owned(), - is_unclosed_bracket: false, - is_unclosed_string: false, + + fn visit_expr(&mut self, expr: &'a ast::Expr) { + if self.error.is_some() { + return; } - .into(), - ) + if let ast::Expr::IpyEscapeCommand(expr) = expr { + self.error = Some((expr.range, ParserAstError::EscapeCommand)); + } else if let ast::Expr::Name(expr) = expr { + self.identifier(expr.id.as_str(), expr.range); + } else { + ast::visitor::source_order::walk_expr(self, expr); + } + } + + fn visit_identifier(&mut self, identifier: &'a ast::Identifier) { + self.identifier(identifier.as_str(), identifier.range()); + } + + fn visit_type_param(&mut self, param: &'a ast::TypeParam) { + if self.error.is_some() { + return; + } + ast::visitor::source_order::walk_type_param(self, param); + let has_default = match param { + ast::TypeParam::TypeVar(param) => param.default.is_some(), + ast::TypeParam::TypeVarTuple(param) => param.default.is_some(), + ast::TypeParam::ParamSpec(param) => param.default.is_some(), + }; + if self.error.is_none() && self.target_version.minor < 13 && has_default { + self.error = Some((param.range(), ParserAstError::TypeParamDefault)); + } + } } /// Create an empty `arguments` AST node (no parameters). @@ -1788,7 +1868,7 @@ fn empty_arguments_object(vm: &VirtualMachine) -> PyObjectRef { #[cfg(feature = "parser")] #[allow(clippy::too_many_arguments)] -pub(crate) fn parse( +pub(crate) fn parse + From>( vm: &VirtualMachine, source: &str, filename: &str, @@ -1800,12 +1880,14 @@ pub(crate) fn parse( interactive: bool, explicit_future_features: crate::bytecode::CodeFlags, dont_imply_dedent: bool, -) -> Result { + type_comment_error_offset: Option<&mut Option>, + mut emit_warning: impl FnMut(usize, char) -> Result<(), E>, +) -> Result { let source_file = SourceFileBuilder::new(filename.to_owned(), source.to_owned()).finish(); let mut options = parser::ParseOptions::from(mode); - let target_version = target_version.unwrap_or(ast::PythonVersion::PY314); + let target_version = target_version.unwrap_or(ast::PythonVersion::PY315); if let Some(error) = feature_version_syntax_error(source, &source_file, target_version) { - return Err(error); + return Err(error.into()); } options = options.with_target_version(target_version); let barry_source = rustpython_compiler::prepare_barry_as_flufl_source( @@ -1817,56 +1899,127 @@ pub(crate) fn parse( let parsed = parser::parse_unchecked(barry_source.source(), options); let type_comment_source = type_comments.then(|| TypeCommentSource::new(source, parsed.tokens())); - if let Some(lines) = &type_comment_source - && let Some(error) = invalid_type_comment_syntax_error(&source_file, lines) + let mut type_comment_error = type_comment_source + .as_ref() + .and_then(|lines| invalid_type_comment_syntax_error(&source_file, lines)); + if interactive && parsed.has_valid_syntax() { + // A rejected comment before the first logical-input boundary prevents + // Simple input from succeeding. Compound input still needs NEWLINE, + // so compare its actual next-token error rather than its AST end. + type_comment_error = type_comment_error.filter(|error| match error { + CompileError::Parse(error) => type_comment_precedes_single_boundary( + error.raw_location.start().to_usize(), + &source_file, + &parsed, + ), + CompileError::Codegen(_) => false, + }); + } + if interactive + && !(parsed.has_valid_syntax() && type_comment_error.is_some()) + && let Some(error) = + rustpython_compiler::single_mode_multiple_statements_error(&source_file, &parsed) { - return Err(error); + return Err(error.into()); + } + if let Some(error) = type_comment_error { + if parsed.has_valid_syntax() + && let Some(offset) = type_comment_error_offset + && let CompileError::Parse(error) = &error + { + *offset = Some(error.raw_location.start().to_usize()); + } + return Err(error.into()); } if let Err(errors) = parsed.as_result() { - let parse_error = errors[0].clone(); - if let Some(error) = barry_source.diagnostic(Some(&parse_error), &source_file) { - return Err(error); + if matches!(mode, parser::Mode::Expression) + && let Some(error) = + rustpython_compiler::expression_initial_indent_error(parsed.tokens(), &source_file) + { + return Err(error.into()); + } + if let Some(error) = barry_source.diagnostic(Some(&errors[0]), &source_file) { + return Err(error.into()); } + if let Some(error) = rustpython_compiler::normalize_raise_parse_error(&parsed) { + let compile_mode = if interactive { + rustpython_compiler::Mode::Single + } else { + rustpython_compiler::Mode::Exec + }; + return Err( + CompileError::from_ruff_parse_error(error, &source_file, compile_mode).into(), + ); + } + let parse_error = errors[0].clone(); let range = text_range_to_source_range(&source_file, parse_error.location); - return Err(ParseError { + return Err(CompileError::from(ParseError { error: parse_error.error, raw_location: parse_error.location, - location: range.start.to_source_location(), - end_location: range.end.to_source_location(), + location: range.start, + end_location: range.end, source_path: source_file.name().to_owned(), is_unclosed_bracket: false, is_unclosed_string: false, - } + eof_token: None, + }) .into()); } if let Some(error) = barry_source.diagnostic(None, &source_file) { - return Err(error); + return Err(error.into()); } if dont_imply_dedent && interactive && let Some(error) = rustpython_compiler::dont_imply_dedent_source_error(&source_file) { - return Err(error); + return Err(error.into()); } - if let Some(error) = parsed + // Preserve the depth guard before the recursive AST validation walk. + rustpython_compiler::too_deeply_nested_error( + parsed.syntax(), + &source_file, + rustpython_compiler::CompileOpts::default().recursion_limit, + )?; + use ast::visitor::source_order::SourceOrderVisitor; + let mut validator = ParserAstValidator::new(target_version); + validator.visit_mod(parsed.syntax()); + let unsupported = parsed .unsupported_syntax_errors() .iter() - .find(|error| should_report_unsupported_syntax_error(error)) + .find(|error| should_report_unsupported_syntax_error(error)); + if validator.error.as_ref().is_some_and(|(range, _)| { + unsupported.is_none_or(|error| { + // Defaults are version-checked after their RHS has been parsed. + let action = if matches!( + error.kind, + parser::UnsupportedSyntaxErrorKind::TypeParamDefault + ) { + error.range.end() + } else { + error.range.start() + }; + range.start() < action + }) + }) && let Some(error) = validator.into_error(vm, source, &source_file) { + return Err(error); + } + if let Some(error) = unsupported { if let Some(error) = cpython_unsupported_syntax_error(error, source, &source_file) { - return Err(error); + return Err(error.into()); } let range = text_range_to_source_range(&source_file, error.range()); - return Err(ParseError { + return Err(CompileError::from(ParseError { error: parser::ParseErrorType::OtherError(error.to_string()), raw_location: error.range(), - location: range.start.to_source_location(), - end_location: range.end.to_source_location(), + location: range.start, + end_location: range.end, source_path: source_file.name().to_owned(), is_unclosed_bracket: false, is_unclosed_string: false, - } + eof_token: None, + }) .into()); } @@ -1875,31 +2028,39 @@ pub(crate) fn parse( parsed.tokens(), vm.state.int_max_str_digits.load(), ) { - return Err(error); + return Err(error.into()); } if let Some(error) = rustpython_compiler::leading_byte_order_mark_error(&source_file) { - return Err(error); + return Err(error.into()); } let mut top = parsed.into_syntax(); - rustpython_compiler::too_deeply_nested_error( - &top, - &source_file, - rustpython_compiler::CompileOpts::default().recursion_limit, - )?; if let Some(error) = rustpython_compiler::unsupported_grammar_error(&top, &source_file) { - return Err(error); - } - if let Some(error) = ipython_escape_command_syntax_error(&top, &source_file) { - return Err(error); + return Err(error.into()); } if let Some(error) = feature_version_ast_syntax_error(&top, &source_file, target_version) { - return Err(error); + return Err(error.into()); + } + #[cfg(feature = "codegen")] + let future_features = codegen::preprocess::checked_future_features(&top) + .map_err(|err| future_feature_compile_error(&source_file, err))?; + // Keep original literal spans: preprocessing can fold multiple source + // literals into one node, but each has its own lexical diagnostic. + match &top { + ast::Mod::Module(module) => { + string::emit_format_spec_warnings(&module.body, &[], &source_file, &mut emit_warning)?; + } + ast::Mod::Expression(expression) => { + string::emit_format_spec_warnings( + &[], + core::slice::from_ref(expression.body.as_ref()), + &source_file, + &mut emit_warning, + )?; + } } #[cfg(feature = "codegen")] { - let future_features = codegen::preprocess::checked_future_features(&top) - .map_err(|err| future_feature_compile_error(&source_file, err))?; let future_annotations = explicit_future_features .contains(crate::bytecode::CodeFlags::FUTURE_ANNOTATIONS) || future_features.contains(crate::bytecode::CodeFlags::FUTURE_ANNOTATIONS); @@ -1935,7 +2096,8 @@ pub(crate) fn parse( }), ast::Mod::Expression(e) => Mod::Expression(e), }; - let obj = top.ast_to_object(vm, &source_file); + let ast_context = AstSourceContext::new(source_file.clone()); + let obj = top.ast_to_object(vm, &ast_context); if let Some(lines) = &type_comment_source && obj.class().is(pyast::NodeModModule::static_type()) { @@ -1963,14 +2125,16 @@ pub(crate) fn wrap_interactive(vm: &VirtualMachine, module_obj: &PyObject) -> Py } #[cfg(feature = "parser")] -pub(crate) fn parse_func_type( +pub(crate) fn parse_func_type + From>( vm: &VirtualMachine, source: &str, filename: &str, optimize: u8, target_version: Option, -) -> Result { + mut emit_warning: impl FnMut(usize, char) -> Result<(), E>, +) -> Result { let _ = optimize; + let leading_space = source.len() - source.trim_start().len(); let source = source.trim(); let invalid_func_type = || -> CompileError { ParseError { @@ -1981,6 +2145,7 @@ pub(crate) fn parse_func_type( source_path: filename.to_owned(), is_unclosed_bracket: false, is_unclosed_string: false, + eof_token: None, } .into() }; @@ -2002,7 +2167,7 @@ pub(crate) fn parse_func_type( } let Some(split_at) = split_at else { - return Err(ParseError { + return Err(CompileError::from(ParseError { error: parser::ParseErrorType::OtherError("invalid func_type".to_owned()), raw_location: TextRange::default(), location: SourceLocation::default(), @@ -2010,7 +2175,8 @@ pub(crate) fn parse_func_type( source_path: filename.to_owned(), is_unclosed_bracket: false, is_unclosed_string: false, - } + eof_token: None, + }) .into()); }; @@ -2020,19 +2186,25 @@ pub(crate) fn parse_func_type( let parse_expr = |expr_src: &str| -> Result { let source_file = SourceFileBuilder::new(filename.to_owned(), expr_src.to_owned()).finish(); let options = parser::ParseOptions::from(parser::Mode::Expression) - .with_target_version(target_version.unwrap_or(ast::PythonVersion::PY314)); + .with_target_version(target_version.unwrap_or(ast::PythonVersion::PY315)); let parsed = parser::parse(expr_src, options).map_err(|parse_error| { let range = text_range_to_source_range(&source_file, parse_error.location); - ParseError { + CompileError::from(ParseError { error: parse_error.error, raw_location: parse_error.location, - location: range.start.to_source_location(), - end_location: range.end.to_source_location(), + location: range.start, + end_location: range.end, source_path: source_file.name().to_owned(), is_unclosed_bracket: false, is_unclosed_string: false, - } + eof_token: None, + }) })?; + rustpython_compiler::too_deeply_nested_error( + parsed.syntax(), + &source_file, + rustpython_compiler::CompileOpts::default().recursion_limit, + )?; let ast::Mod::Expression(expression) = parsed.into_syntax() else { unreachable!(); }; @@ -2040,36 +2212,45 @@ pub(crate) fn parse_func_type( }; if !left.starts_with('(') || !left.ends_with(')') { - return Err(invalid_func_type()); + return Err(invalid_func_type().into()); } let inner = left[1..left.len() - 1].trim(); + let inner_start = left.len() - 1 - left[1..left.len() - 1].trim_start().len(); + const ARG_PREFIX: &str = "__rustpython_func_type__("; + let mut arg_source_file = None; let argtypes = if inner.is_empty() { Vec::new() } else { if inner.ends_with(',') { - return Err(invalid_func_type()); + return Err(invalid_func_type().into()); } - let call_source = format!("__rustpython_func_type__({inner})"); + let call_source = format!("{ARG_PREFIX}{inner})"); let source_file = SourceFileBuilder::new(filename.to_owned(), call_source.clone()).finish(); let options = parser::ParseOptions::from(parser::Mode::Expression) - .with_target_version(target_version.unwrap_or(ast::PythonVersion::PY314)); + .with_target_version(target_version.unwrap_or(ast::PythonVersion::PY315)); let parsed = parser::parse(&call_source, options).map_err(|parse_error| { let range = text_range_to_source_range(&source_file, parse_error.location); - ParseError { + CompileError::from(ParseError { error: parse_error.error, raw_location: parse_error.location, - location: range.start.to_source_location(), - end_location: range.end.to_source_location(), + location: range.start, + end_location: range.end, source_path: source_file.name().to_owned(), is_unclosed_bracket: false, is_unclosed_string: false, - } + eof_token: None, + }) })?; + rustpython_compiler::too_deeply_nested_error( + parsed.syntax(), + &source_file, + rustpython_compiler::CompileOpts::default().recursion_limit, + )?; let ast::Mod::Expression(expression) = parsed.into_syntax() else { unreachable!(); }; let ast::Expr::Call(call) = *expression.body else { - return Err(invalid_func_type()); + return Err(invalid_func_type().into()); }; let mut args = Vec::new(); let positional_len = call.arguments.args.len(); @@ -2078,7 +2259,7 @@ pub(crate) fn parse_func_type( match arg { ast::Expr::Starred(starred) => { if seen_star || index + 1 != positional_len { - return Err(invalid_func_type()); + return Err(invalid_func_type().into()); } seen_star = true; args.push(*starred.value); @@ -2089,23 +2270,51 @@ pub(crate) fn parse_func_type( let mut seen_kw_star = false; for keyword in call.arguments.keywords { if keyword.arg.is_some() || seen_kw_star { - return Err(invalid_func_type()); + return Err(invalid_func_type().into()); } seen_kw_star = true; args.push(keyword.value); } + arg_source_file = Some(source_file); args }; let returns = parse_expr(right)?; + use ast::visitor::source_order::SourceOrderVisitor; + let mut validator = + ParserAstValidator::new(target_version.unwrap_or(ast::PythonVersion::PY315)); + for argument in &argtypes { + validator.visit_expr(argument); + } + validator.visit_expr(&returns); + let validation_source = SourceFileBuilder::new(filename.to_owned(), source.to_owned()).finish(); + if let Some(error) = validator.into_error(vm, source, &validation_source) { + return Err(error); + } + + // Func-type nodes are parsed from separate fragments. Keep warning offsets + // in those fragments until the boundary, then map them to the original + // source without changing the AST's existing location representation. + if let Some(source_file) = arg_source_file { + string::emit_format_spec_warnings(&[], &argtypes, &source_file, &mut |offset, ch| { + emit_warning(leading_space + inner_start + offset - ARG_PREFIX.len(), ch) + })?; + } + let return_source_file = SourceFileBuilder::new(filename.to_owned(), right.to_owned()).finish(); + string::emit_format_spec_warnings( + &[], + core::slice::from_ref(&returns), + &return_source_file, + &mut |offset, ch| emit_warning(leading_space + source.len() - right.len() + offset, ch), + )?; let func_type = ModFunctionType { argtypes: argtypes.into_boxed_slice(), returns, runtime_argtypes: None, }; - let source_file = SourceFileBuilder::new("".to_owned(), source.to_owned()).finish(); - Ok(func_type.ast_to_object(vm, &source_file)) + let source_file = SourceFileBuilder::new(filename.to_owned(), source.to_owned()).finish(); + Ok(func_type.ast_to_object(vm, &AstSourceContext::new(source_file))) } fn type_ignores_from_source( @@ -2372,6 +2581,43 @@ fn number_to_complex(number: &ast::Number) -> Option<(f64, f64, bool)> { } } +#[cfg(feature = "codegen")] +fn ast_location_exception( + vm: &VirtualMachine, + error: rustpython_compiler_core::AstLocationError, +) -> crate::builtins::PyBaseExceptionRef { + use rustpython_compiler_core::AstLocationError; + match error { + AstLocationError::ExhaustedNodeIdentities => { + vm.new_memory_error("too many AST location identities") + } + AstLocationError::ConflictingLocation => { + vm.new_system_error("conflicting AST location identity") + } + AstLocationError::CoordinateOverflow => { + vm.new_value_error("AST location coordinate overflow") + } + } +} + +#[cfg(feature = "codegen")] +pub(crate) fn codegen_exception( + vm: &VirtualMachine, + error: codegen::error::CodegenError, + source: Option<&str>, +) -> crate::builtins::PyBaseExceptionRef { + match error.error { + codegen::error::CodegenErrorType::AstLocation(error) => { + return ast_location_exception(vm, error); + } + codegen::error::CodegenErrorType::MixedAstLocationProvenance => { + return vm.new_system_error("mixed AST location provenance"); + } + _ => {} + } + vm.new_syntax_error(&error.into(), source) +} + #[cfg(feature = "codegen")] pub(crate) fn preprocess_ast_object( vm: &VirtualMachine, @@ -2384,7 +2630,8 @@ pub(crate) fn preprocess_ast_object( let original_object = object.clone(); let text = synthetic_source_from_ast_object(vm, &object)?; let source_file = SourceFileBuilder::new(filename.to_owned(), text).finish(); - let ast = Node::ast_from_object(vm, &source_file, object)?; + let ast_context = AstSourceContext::new(source_file.clone()); + let ast = Node::ast_from_object(vm, &ast_context, object)?; validate::validate_mod(vm, &ast)?; let syntax_check_only = !optimized_ast; @@ -2397,12 +2644,17 @@ pub(crate) fn preprocess_ast_object( })?; let future_annotations = explicit_future_annotations || future_features.contains(crate::bytecode::CodeFlags::FUTURE_ANNOTATIONS); - codegen::preprocess::preprocess_mod( - &mut ast, - optimize, - future_annotations, - syntax_check_only, - ); + ast_context + .preprocess_locations(|locations| { + codegen::preprocess::preprocess_mod_with_locations( + &mut ast, + optimize, + future_annotations, + syntax_check_only, + locations, + ) + }) + .map_err(|error| ast_location_exception(vm, error))?; let ast::Mod::Module(processed_module) = ast else { unreachable!(); }; @@ -2418,22 +2670,32 @@ pub(crate) fn preprocess_ast_object( })?; let future_annotations = explicit_future_annotations || future_features.contains(crate::bytecode::CodeFlags::FUTURE_ANNOTATIONS); - codegen::preprocess::preprocess_statements( - &mut interactive.body, - optimize, - future_annotations, - syntax_check_only, - ); + ast_context + .preprocess_locations(|locations| { + codegen::preprocess::preprocess_statements_with_locations( + &mut interactive.body, + optimize, + future_annotations, + syntax_check_only, + locations, + ) + }) + .map_err(|error| ast_location_exception(vm, error))?; Mod::Interactive(interactive) } Mod::Expression(expression) => { let mut ast = ast::Mod::Expression(expression); - codegen::preprocess::preprocess_mod( - &mut ast, - optimize, - explicit_future_annotations, - syntax_check_only, - ); + ast_context + .preprocess_locations(|locations| { + codegen::preprocess::preprocess_mod_with_locations( + &mut ast, + optimize, + explicit_future_annotations, + syntax_check_only, + locations, + ) + }) + .map_err(|error| ast_location_exception(vm, error))?; let ast::Mod::Expression(expression) = ast else { unreachable!(); }; @@ -2441,7 +2703,7 @@ pub(crate) fn preprocess_ast_object( } Mod::FunctionType(function_type) => Mod::FunctionType(function_type), }; - let result = ast.ast_to_object(vm, &source_file); + let result = ast.ast_to_object(vm, &ast_context); copy_ast_passthrough_fields(vm, &original_object, &result)?; Ok(result) } @@ -2450,6 +2712,7 @@ pub(crate) fn preprocess_ast_object( pub(crate) struct RustModFromObject { pub ast: ast::Mod, pub source_file: SourceFile, + pub locations: Option, } #[cfg(feature = "codegen")] @@ -2467,7 +2730,8 @@ pub(crate) fn rust_mod_from_object( } let text = synthetic_source_from_ast_object(vm, &object)?; let source_file = SourceFileBuilder::new(filename.to_owned(), text).finish(); - let ast = Node::ast_from_object(vm, &source_file, object)?; + let ast_context = AstSourceContext::new(source_file.clone()); + let ast = Node::ast_from_object(vm, &ast_context, object)?; validate::validate_mod(vm, &ast)?; let ast = match ast { Mod::Module(m) => ast::Mod::Module(m.module), @@ -2482,7 +2746,11 @@ pub(crate) fn rust_mod_from_object( return Err(vm.new_runtime_error("this compiler does not handle FunctionTypes")); } }; - Ok(RustModFromObject { ast, source_file }) + Ok(RustModFromObject { + ast, + source_file, + locations: ast_context.take_locations(), + }) } #[cfg(feature = "codegen")] @@ -2492,10 +2760,14 @@ pub(crate) fn compile( filename: &str, mode: crate::compiler::Mode, mut opts: codegen::CompileOpts, + module: Option<&Py>, ) -> PyResult { + #[cfg(not(feature = "parser"))] + let _ = module; let text = synthetic_source_from_ast_object(vm, &object)?; let source_file = SourceFileBuilder::new(filename.to_owned(), text.clone()).finish(); - let ast = Node::ast_from_object(vm, &source_file, object)?; + let ast_context = AstSourceContext::new(source_file); + let ast = Node::ast_from_object(vm, &ast_context, object)?; validate::validate_mod(vm, &ast)?; let ast = match ast { Mod::Module(m) => ast::Mod::Module(m.module), @@ -2513,6 +2785,11 @@ pub(crate) fn compile( opts.future_features |= codegen::preprocess::future_features(&ast); let source = text.clone(); let source_file = SourceFileBuilder::new(filename, text).finish(); + let input = codegen::compile::AstInput { + ast, + source_file, + locations: ast_context.take_locations(), + }; #[cfg(feature = "parser")] let code = { let source_path = filename.to_owned(); @@ -2529,7 +2806,7 @@ pub(crate) fn compile( message.into(), fname, location.line.get(), - None, + module.map(|module| module.to_owned().into()), vm.ctx.none(), None, None, @@ -2550,9 +2827,8 @@ pub(crate) fn compile( marker }) }; - let result = codegen::compile::compile_top_with_syntax_warning_handler( - ast, - source_file, + let result = codegen::compile::compile_ast_with_syntax_warning_handler( + input, mode, opts, Some(&mut syntax_warning_handler), @@ -2565,15 +2841,16 @@ pub(crate) fn compile( } }; #[cfg(not(feature = "parser"))] - let code = codegen::compile::compile_top(ast, source_file, mode, opts); - let code = code.map_err(|err| vm.new_syntax_error(&err.into(), Some(source.as_str())))?; + let code = codegen::compile::compile_ast_with_syntax_warning_handler(input, mode, opts, None); + let code = code.map_err(|err| codegen_exception(vm, err, Some(source.as_str())))?; Ok(crate::builtins::PyCode::new_ref_from_bytecode(vm, code).into()) } #[cfg(not(feature = "rustpython-codegen"))] pub(crate) fn validate_ast_object(vm: &VirtualMachine, object: PyObjectRef) -> PyResult<()> { let source_file = SourceFileBuilder::new("".to_owned(), "".to_owned()).finish(); - let ast = Node::ast_from_object(vm, &source_file, object)?; + let ast_context = AstSourceContext::new(source_file.clone()); + let ast = Node::ast_from_object(vm, &ast_context, object)?; validate::validate_mod(vm, &ast)?; Ok(()) } diff --git a/crates/vm/src/stdlib/_ast/argument.rs b/crates/vm/src/stdlib/_ast/argument.rs index 0ea9725a168..47cc602e8f1 100644 --- a/crates/vm/src/stdlib/_ast/argument.rs +++ b/crates/vm/src/stdlib/_ast/argument.rs @@ -1,5 +1,5 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; pub(super) struct PositionalArguments { range: TextRange, @@ -7,14 +7,14 @@ pub(super) struct PositionalArguments { } enum PositionalArgumentsKind { - Args(Box<[ast::Expr]>), + Args(thin_vec::ThinVec), RuntimeValues(Vec>), } impl PositionalArguments { pub(super) fn ast_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -24,7 +24,7 @@ impl PositionalArguments { Ok(Self::from_values(TextRange::default(), values)) } - fn from_args(range: TextRange, args: Box<[ast::Expr]>) -> Self { + fn from_args(range: TextRange, args: thin_vec::ThinVec) -> Self { Self { range, kind: PositionalArgumentsKind::Args(args), @@ -42,14 +42,7 @@ impl PositionalArguments { if values.iter().any(Option::is_none) { Self::from_runtime_values(range, values) } else { - Self::from_args( - range, - values - .into_iter() - .flatten() - .collect::>() - .into_boxed_slice(), - ) + Self::from_args(range, values.into_iter().flatten().collect()) } } @@ -57,32 +50,33 @@ impl PositionalArguments { self.range } - fn into_args_and_runtime_values(self) -> (Box<[ast::Expr]>, Option>>) { + fn into_args_and_runtime_values( + self, + ) -> (thin_vec::ThinVec, Option>>) { match self.kind { PositionalArgumentsKind::Args(args) => (args, None), - PositionalArgumentsKind::RuntimeValues(values) => ( - lower_runtime_expr_list(values.clone()).into_boxed_slice(), - Some(values), - ), + PositionalArgumentsKind::RuntimeValues(values) => { + (lower_runtime_expr_list(values.clone()).into(), Some(values)) + } } } } impl Node for PositionalArguments { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self.kind { - PositionalArgumentsKind::Args(args) => BoxedSlice(args).ast_to_object(vm, source_file), + PositionalArgumentsKind::Args(args) => args.ast_to_object(vm, source_file), PositionalArgumentsKind::RuntimeValues(values) => values.ast_to_object(vm, source_file), } } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { - let args: BoxedSlice<_> = Node::ast_from_object(vm, source_file, object)?; - Ok(Self::from_args(TextRange::default(), args.0)) + let args: thin_vec::ThinVec<_> = Node::ast_from_object(vm, source_file, object)?; + Ok(Self::from_args(TextRange::default(), args)) } } @@ -94,7 +88,7 @@ pub(super) struct KeywordArguments { impl KeywordArguments { pub(super) fn ast_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -107,7 +101,7 @@ impl KeywordArguments { } impl Node for KeywordArguments { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { keywords, range: _ } = self; // TODO: use range BoxedSlice(keywords).ast_to_object(vm, source_file) @@ -115,7 +109,7 @@ impl Node for KeywordArguments { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let keywords: BoxedSlice<_> = Node::ast_from_object(vm, source_file, object)?; @@ -137,7 +131,7 @@ pub(super) fn merge_function_call_arguments( node_index: Default::default(), range, args, - keywords: key_args.keywords.into(), + keywords: key_args.keywords.into_vec().into(), runtime_args, runtime_bases: None, } @@ -173,7 +167,7 @@ pub(super) fn split_function_call_arguments( // debug_assert!(range.contains_range(keyword_arguments_range)); let keyword_arguments = KeywordArguments { range: keyword_arguments_range, - keywords: keywords.into(), + keywords: keywords.into_iter().collect::>().into_boxed_slice(), }; (positional_arguments, keyword_arguments) @@ -214,7 +208,7 @@ pub(super) fn split_class_def_args( // debug_assert!(range.contains_range(keyword_arguments_range)); let keyword_arguments = KeywordArguments { range: keyword_arguments_range, - keywords: keywords.into(), + keywords: keywords.into_iter().collect::>().into_boxed_slice(), }; (Some(positional_arguments), Some(keyword_arguments)) @@ -231,7 +225,7 @@ pub(super) fn merge_class_def_args( let (args, runtime_bases) = if let Some(positional_arguments) = positional_arguments { positional_arguments.into_args_and_runtime_values() } else { - (vec![].into_boxed_slice(), None) + (thin_vec::ThinVec::new(), None) }; let keywords = if let Some(keyword_arguments) = keyword_arguments { keyword_arguments.keywords @@ -243,7 +237,7 @@ pub(super) fn merge_class_def_args( node_index: Default::default(), range: Default::default(), // TODO args, - keywords: keywords.into(), + keywords: keywords.into_vec().into(), runtime_args: None, runtime_bases, })) diff --git a/crates/vm/src/stdlib/_ast/basic.rs b/crates/vm/src/stdlib/_ast/basic.rs index e7143057b0d..a336b020501 100644 --- a/crates/vm/src/stdlib/_ast/basic.rs +++ b/crates/vm/src/stdlib/_ast/basic.rs @@ -1,17 +1,15 @@ +use super::AstSourceContext; use super::*; -use crate::builtins::PyIntRef; -use rustpython_codegen::compile::ruff_int_to_bigint; -use rustpython_compiler_core::SourceFile; impl Node for ast::Identifier { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { let id = self.as_str(); vm.ctx.intern_str(id).to_object() } fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if !object.class().is(vm.ctx.types.str_type) { @@ -23,30 +21,14 @@ impl Node for ast::Identifier { } } -impl Node for ast::Int { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { - vm.ctx.new_int(ruff_int_to_bigint(&self).unwrap()).into() - } - - fn ast_from_object( - vm: &VirtualMachine, - _source_file: &SourceFile, - object: PyObjectRef, - ) -> PyResult { - let value: PyIntRef = object.try_into_value(vm)?; - let value = value.as_bigint().to_string(); - Ok(value.parse().unwrap()) - } -} - impl Node for bool { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { vm.ctx.new_int(self as u8).into() } fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { node_object_to_i32(vm, &object).map(|i| i != 0) diff --git a/crates/vm/src/stdlib/_ast/constant.rs b/crates/vm/src/stdlib/_ast/constant.rs index 61b25f97620..29789f5519e 100644 --- a/crates/vm/src/stdlib/_ast/constant.rs +++ b/crates/vm/src/stdlib/_ast/constant.rs @@ -1,12 +1,14 @@ use super::*; -use crate::builtins::{PyComplex, PyFrozenSet, PyTuple}; +use crate::builtins::{PyComplex, PyFrozenSet, PyIntRef, PyTuple}; use ast::str_prefix::StringLiteralPrefix; +use malachite_bigint::BigInt; use rustpython_codegen::compile::ruff_int_to_bigint; use rustpython_common::wtf8::Wtf8Buf; -use rustpython_compiler_core::{SourceFile, bytecode::ConstantData}; +use rustpython_compiler_core::bytecode::ConstantData; #[derive(Debug)] pub(super) struct Constant { + pub(super) node_index: ast::AtomicNodeIndex, pub(super) range: TextRange, pub(super) value: ConstantLiteral, kind: Option>, @@ -21,6 +23,7 @@ impl Constant { ) -> Self { let value = value.into(); Self { + node_index: ast::AtomicNodeIndex::NONE, range, value: ConstantLiteral::Str { value, prefix }, kind: None, @@ -28,10 +31,11 @@ impl Constant { } } - pub(super) const fn new_int(value: ast::Int, range: TextRange) -> Self { + pub(super) fn new_int(value: ast::Int, range: TextRange) -> Self { Self { + node_index: ast::AtomicNodeIndex::NONE, range, - value: ConstantLiteral::Int(value), + value: ConstantLiteral::Int(ruff_int_to_bigint(&value).unwrap()), kind: None, invalid_type: None, } @@ -39,6 +43,7 @@ impl Constant { pub(super) const fn new_float(value: f64, range: TextRange) -> Self { Self { + node_index: ast::AtomicNodeIndex::NONE, range, value: ConstantLiteral::Float(value), kind: None, @@ -48,6 +53,7 @@ impl Constant { pub(super) const fn new_complex(real: f64, imag: f64, range: TextRange) -> Self { Self { + node_index: ast::AtomicNodeIndex::NONE, range, value: ConstantLiteral::Complex { real, imag }, kind: None, @@ -57,6 +63,7 @@ impl Constant { pub(super) const fn new_bytes(value: Box<[u8]>, range: TextRange) -> Self { Self { + node_index: ast::AtomicNodeIndex::NONE, range, value: ConstantLiteral::Bytes(value), kind: None, @@ -66,6 +73,7 @@ impl Constant { pub(super) const fn new_bool(value: bool, range: TextRange) -> Self { Self { + node_index: ast::AtomicNodeIndex::NONE, range, value: ConstantLiteral::Bool(value), kind: None, @@ -75,6 +83,7 @@ impl Constant { pub(super) const fn new_none(range: TextRange) -> Self { Self { + node_index: ast::AtomicNodeIndex::NONE, range, value: ConstantLiteral::None, kind: None, @@ -84,6 +93,7 @@ impl Constant { pub(super) const fn new_ellipsis(range: TextRange) -> Self { Self { + node_index: ast::AtomicNodeIndex::NONE, range, value: ConstantLiteral::Ellipsis, kind: None, @@ -93,16 +103,18 @@ impl Constant { pub(crate) fn into_expr(self) -> ast::Expr { let Self { + node_index, range, value, kind, invalid_type, } = self; + let kind = kind.or_else(|| constant_literal_kind(&value)); ast::Expr::Constant(ast::ExprConstant { - node_index: Default::default(), + node_index, range, - value: constant_data_to_ast_constant_value(constant_literal_to_constant_data(&value)), - kind: kind.or_else(|| constant_literal_kind(&value)), + value: constant_data_to_ast_constant_value(constant_literal_to_constant_data(value)), + kind, invalid_type: invalid_type.map(String::into_boxed_str), }) } @@ -117,7 +129,7 @@ pub(crate) enum ConstantLiteral { prefix: StringLiteralPrefix, }, Bytes(Box<[u8]>), - Int(ast::Int), + Int(BigInt), Tuple(Vec), FrozenSet(Vec), Float(f64), @@ -152,11 +164,11 @@ pub(super) fn runtime_string_object( pub(super) fn expr_constant_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, expr: ast::ExprConstant, ) -> PyObjectRef { let ast::ExprConstant { - node_index: _, + node_index, range, value, kind, @@ -171,7 +183,7 @@ pub(super) fn expr_constant_to_object( .unwrap(); let kind = kind.map_or_else(|| vm.ctx.none(), |kind| vm.ctx.new_str(kind).into()); dict.set_item("kind", kind, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } @@ -195,34 +207,30 @@ pub(super) fn runtime_stmt_type_comment_object( runtime_string_object(vm, value, bytes) } -fn constant_literal_to_constant_data(value: &ConstantLiteral) -> ConstantData { +fn constant_literal_to_constant_data(value: ConstantLiteral) -> ConstantData { match value { ConstantLiteral::None => ConstantData::None, - ConstantLiteral::Bool(value) => ConstantData::Boolean { value: *value }, - ConstantLiteral::Str { value, .. } => ConstantData::Str { - value: value.clone(), - }, + ConstantLiteral::Bool(value) => ConstantData::Boolean { value }, + ConstantLiteral::Str { value, .. } => ConstantData::Str { value }, ConstantLiteral::Bytes(value) => ConstantData::Bytes { - value: value.to_vec(), - }, - ConstantLiteral::Int(value) => ConstantData::Integer { - value: ruff_int_to_bigint(value).unwrap(), + value: value.into_vec(), }, + ConstantLiteral::Int(value) => ConstantData::Integer { value }, ConstantLiteral::Tuple(value) => ConstantData::Tuple { elements: value - .iter() + .into_iter() .map(constant_literal_to_constant_data) .collect(), }, ConstantLiteral::FrozenSet(value) => ConstantData::Frozenset { elements: value - .iter() + .into_iter() .map(constant_literal_to_constant_data) .collect(), }, - ConstantLiteral::Float(value) => ConstantData::Float { value: *value }, + ConstantLiteral::Float(value) => ConstantData::Float { value }, ConstantLiteral::Complex { real, imag } => ConstantData::Complex { - value: num_complex::Complex::new(*real, *imag), + value: num_complex::Complex::new(real, imag), }, ConstantLiteral::Ellipsis => ConstantData::Ellipsis, } @@ -306,11 +314,10 @@ pub(super) fn ast_constant_value_to_constant_data(value: ast::ConstantValue) -> pub(super) fn constant_object_to_constant_data( vm: &VirtualMachine, - source_file: &SourceFile, value_object: PyObjectRef, ) -> PyResult { - let value = ConstantLiteral::ast_from_object(vm, source_file, value_object)?; - Ok(constant_literal_to_constant_data(&value)) + let value = ConstantLiteral::from_object(vm, value_object)?; + Ok(constant_literal_to_constant_data(value)) } fn runtime_string_from_object( @@ -442,19 +449,17 @@ fn constant_data_to_object(vm: &VirtualMachine, constant: ConstantData) -> PyObj // constructor pub(super) fn constant_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let value_object = get_node_field(vm, object, "value", "Constant")?; - let (value, invalid_type) = - match ConstantLiteral::ast_from_object(vm, source_file, value_object.clone()) { - Ok(value) => (value, None), - Err(_) => ( - ConstantLiteral::None, - Some(first_invalid_constant_type(vm, &value_object)?), - ), - }; + let (value, invalid_type) = match ConstantLiteral::from_object(vm, value_object.clone()) { + Ok(value) => (value, None), + Err(_) => ( + ConstantLiteral::None, + Some(first_invalid_constant_type(vm, &value_object)?), + ), + }; let kind = get_node_field_opt(vm, object, "kind")? .map(|object| { if !object.class().is(vm.ctx.types.str_type) { @@ -465,7 +470,8 @@ pub(super) fn constant_from_object_with_range( .transpose()?; Ok(Constant { - range, + node_index: range.node_index(), + range: range.range, value, kind, invalid_type, @@ -473,8 +479,9 @@ pub(super) fn constant_from_object_with_range( } impl Node for Constant { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { + node_index, range, value, kind, @@ -486,45 +493,41 @@ impl Node for Constant { let kind = kind .or_else(|| constant_literal_kind(&value)) .map_or_else(|| vm.ctx.none(), |kind| vm.ctx.new_str(kind).into()); - let value = value.ast_to_object(vm, source_file); + let value = value.into_object(vm); let dict = node.as_object().dict().unwrap(); dict.set_item("value", value, vm).unwrap(); dict.set_item("kind", kind, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Constant")?; - constant_from_object_with_range(vm, source_file, &object, range) + constant_from_object_with_range(vm, &object, range) } } -impl Node for ConstantLiteral { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { +impl ConstantLiteral { + fn into_object(self, vm: &VirtualMachine) -> PyObjectRef { match self { Self::None => vm.ctx.none(), Self::Bool(value) => vm.ctx.new_bool(value).to_pyobject(vm), Self::Str { value, .. } => vm.ctx.new_str(value).to_pyobject(vm), Self::Bytes(value) => vm.ctx.new_bytes(value.into()).to_pyobject(vm), - Self::Int(value) => value.ast_to_object(vm, source_file), + Self::Int(value) => vm.ctx.new_int(value).into(), Self::Tuple(value) => { - let value = value - .into_iter() - .map(|c| c.ast_to_object(vm, source_file)) - .collect(); + let value = value.into_iter().map(|c| c.into_object(vm)).collect(); vm.ctx.new_tuple(value).to_pyobject(vm) } - Self::FrozenSet(value) => PyFrozenSet::from_iter( - vm, - value.into_iter().map(|c| c.ast_to_object(vm, source_file)), - ) - .unwrap() - .into_pyobject(vm), + Self::FrozenSet(value) => { + PyFrozenSet::from_iter(vm, value.into_iter().map(|c| c.into_object(vm))) + .unwrap() + .into_pyobject(vm) + } Self::Float(value) => vm.ctx.new_float(value).into(), Self::Complex { real, imag } => vm .ctx @@ -534,11 +537,7 @@ impl Node for ConstantLiteral { } } - fn ast_from_object( - vm: &VirtualMachine, - source_file: &SourceFile, - value_object: PyObjectRef, - ) -> PyResult { + fn from_object(vm: &VirtualMachine, value_object: PyObjectRef) -> PyResult { let cls = value_object.class(); let value = if cls.is(vm.ctx.types.none_type) { Self::None @@ -562,7 +561,9 @@ impl Node for ConstantLiteral { } else if cls.is(vm.ctx.types.bytes_type) { Self::Bytes(value_object.try_to_value::>(vm)?.into()) } else if cls.is(vm.ctx.types.int_type) { - Self::Int(Node::ast_from_object(vm, source_file, value_object)?) + // An AST constant stores an integer value, not an unsigned source token. + let value: PyIntRef = value_object.try_into_value(vm)?; + Self::Int(value.as_bigint().clone()) } else if cls.is(vm.ctx.types.tuple_type) { let tuple = value_object.downcast::().map_err(|obj| { vm.new_type_error(format!( @@ -575,9 +576,7 @@ impl Node for ConstantLiteral { .into_iter() .map(|object| { let object = object.clone(); - vm.with_recursion(" during compilation", || { - Node::ast_from_object(vm, source_file, object) - }) + vm.with_recursion(" during compilation", || Self::from_object(vm, object)) }) .collect::>()?; Self::Tuple(tuple) @@ -587,9 +586,7 @@ impl Node for ConstantLiteral { .elements() .into_iter() .map(|object| { - vm.with_recursion(" during compilation", || { - Node::ast_from_object(vm, source_file, object) - }) + vm.with_recursion(" during compilation", || Self::from_object(vm, object)) }) .collect::>()?; Self::FrozenSet(elements) @@ -626,30 +623,31 @@ impl Node for ConstantLiteral { pub(super) fn number_literal_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, constant: ast::ExprNumberLiteral, ) -> PyObjectRef { let ast::ExprNumberLiteral { - node_index: _, + node_index, range, value, .. } = constant; - let c = match value { + let mut c = match value { ast::Number::Int(n) => Constant::new_int(n, range), ast::Number::Float(n) => Constant::new_float(n, range), ast::Number::Complex { real, imag } => Constant::new_complex(real, imag, range), }; + c.node_index = node_index; c.ast_to_object(vm, source_file) } pub(super) fn string_literal_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, constant: ast::ExprStringLiteral, ) -> PyObjectRef { let ast::ExprStringLiteral { - node_index: _, + node_index, range, value, .. @@ -659,65 +657,66 @@ pub(super) fn string_literal_to_object( .next() .map_or(StringLiteralPrefix::Empty, |part| part.flags.prefix()); let value = rustpython_codegen::string_literal_value(source_file, &value); - let c = Constant::new_str(value, prefix, range); + let mut c = Constant::new_str(value, prefix, range); + c.node_index = node_index; c.ast_to_object(vm, source_file) } pub(super) fn bytes_literal_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, constant: ast::ExprBytesLiteral, ) -> PyObjectRef { let ast::ExprBytesLiteral { - node_index: _, + node_index, range, value, .. } = constant; let bytes = value.as_slice().iter().flat_map(|b| b.value.iter()); - let c = Constant::new_bytes(bytes.copied().collect(), range); + let mut c = Constant::new_bytes(bytes.copied().collect(), range); + c.node_index = node_index; c.ast_to_object(vm, source_file) } pub(super) fn boolean_literal_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, constant: ast::ExprBooleanLiteral, ) -> PyObjectRef { let ast::ExprBooleanLiteral { - node_index: _, + node_index, range, value, .. } = constant; - let c = Constant::new_bool(value, range); + let mut c = Constant::new_bool(value, range); + c.node_index = node_index; c.ast_to_object(vm, source_file) } pub(super) fn none_literal_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, constant: ast::ExprNoneLiteral, ) -> PyObjectRef { let ast::ExprNoneLiteral { - node_index: _, - range, - .. + node_index, range, .. } = constant; - let c = Constant::new_none(range); + let mut c = Constant::new_none(range); + c.node_index = node_index; c.ast_to_object(vm, source_file) } pub(super) fn ellipsis_literal_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, constant: ast::ExprEllipsisLiteral, ) -> PyObjectRef { let ast::ExprEllipsisLiteral { - node_index: _, - range, - .. + node_index, range, .. } = constant; - let c = Constant::new_ellipsis(range); + let mut c = Constant::new_ellipsis(range); + c.node_index = node_index; c.ast_to_object(vm, source_file) } diff --git a/crates/vm/src/stdlib/_ast/elif_else_clause.rs b/crates/vm/src/stdlib/_ast/elif_else_clause.rs index ca8187bf32f..0ac33c58351 100644 --- a/crates/vm/src/stdlib/_ast/elif_else_clause.rs +++ b/crates/vm/src/stdlib/_ast/elif_else_clause.rs @@ -1,14 +1,14 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; pub(super) fn ast_to_object( clause: ast::ElifElseClause, mut rest: alloc::vec::IntoIter, vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, ) -> PyObjectRef { let ast::ElifElseClause { - node_index: _, + node_index, range, test, body, @@ -57,15 +57,15 @@ pub(super) fn ast_to_object( }; dict.set_item("orelse", orelse, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } pub(super) fn ast_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let test = get_required_node_field(vm, source_file, object, "test", "If")?; let body: Vec> = get_node_list_field(vm, source_file, object, "body", "If")?; @@ -81,7 +81,7 @@ pub(super) fn ast_from_object_with_range( } else if let [ast::Stmt::If(_)] = &*orelse { let Some(ast::Stmt::If(ast::StmtIf { node_index, - range, + range: nested_range, test, body, mut elif_else_clauses, @@ -95,7 +95,7 @@ pub(super) fn ast_from_object_with_range( 0, ast::ElifElseClause { node_index, - range, + range: nested_range, test: Some(*test), body, runtime_body, @@ -105,8 +105,8 @@ pub(super) fn ast_from_object_with_range( elif_else_clauses } else { vec![ast::ElifElseClause { - node_index: Default::default(), - range, + node_index: range.node_index(), + range: range.range, test: None, body: orelse, runtime_body: runtime_orelse, @@ -115,11 +115,11 @@ pub(super) fn ast_from_object_with_range( }; Ok(ast::StmtIf { - node_index: Default::default(), + node_index: range.node_index(), test, body, elif_else_clauses, - range, + range: range.range, runtime_body, }) } diff --git a/crates/vm/src/stdlib/_ast/exception.rs b/crates/vm/src/stdlib/_ast/exception.rs index 4f179513d59..6f9f992a768 100644 --- a/crates/vm/src/stdlib/_ast/exception.rs +++ b/crates/vm/src/stdlib/_ast/exception.rs @@ -1,5 +1,5 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; fn ensure_excepthandler_node(vm: &VirtualMachine, object: &PyObject) -> PyResult<()> { if vm.is_none(object) @@ -19,14 +19,14 @@ fn ensure_excepthandler_node(vm: &VirtualMachine, object: &PyObject) -> PyResult // sum impl Node for ast::ExceptHandler { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::ExceptHandler(cons) => cons.ast_to_object(vm, source_file), } } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { ensure_excepthandler_node(vm, &object)?; @@ -43,15 +43,15 @@ impl Node for ast::ExceptHandler { // constructor fn except_handler_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let body: Vec> = get_node_list_field(vm, source_file, object, "body", "ExceptHandler")?; let (runtime_body, body) = runtime_stmt_list_from_values(body); Ok(ast::ExceptHandlerExceptHandler { - node_index: Default::default(), + node_index: range.node_index(), type_: get_node_field_opt(vm, object, "type")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, @@ -59,14 +59,14 @@ fn except_handler_from_object_with_range( .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, body, - range, + range: range.range, runtime_body, }) } pub(super) fn except_handler_from_object_unvalidated_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, ) -> PyResult { ensure_excepthandler_node(vm, object)?; @@ -77,9 +77,9 @@ pub(super) fn except_handler_from_object_unvalidated_range( } impl Node for ast::ExceptHandlerExceptHandler { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, type_, name, body, @@ -102,13 +102,13 @@ impl Node for ast::ExceptHandlerExceptHandler { |values| values.ast_to_object(vm, source_file), ); dict.set_item("body", body, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "ExceptHandler")?; diff --git a/crates/vm/src/stdlib/_ast/expression.rs b/crates/vm/src/stdlib/_ast/expression.rs index 6d5e21302fe..5ad939873d9 100644 --- a/crates/vm/src/stdlib/_ast/expression.rs +++ b/crates/vm/src/stdlib/_ast/expression.rs @@ -1,13 +1,13 @@ +use super::AstSourceContext; use super::*; use crate::stdlib::_ast::argument::{ KeywordArguments, PositionalArguments, merge_function_call_arguments, split_function_call_arguments, }; -use rustpython_compiler_core::SourceFile; // sum impl Node for ast::Expr { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::BoolOp(cons) => cons.ast_to_object(vm, source_file), Self::Name(cons) => cons.ast_to_object(vm, source_file), @@ -54,7 +54,7 @@ impl Node for ast::Expr { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if vm.is_none(&object) { @@ -159,7 +159,7 @@ impl Node for ast::Expr { ))); }; let range = expr_range_from_object(vm, source_file, &object)?; - Ok(match kind { + let expression = match kind { ExprKind::BoolOp => Self::BoolOp(expr_bool_op_from_object_with_range( vm, source_file, @@ -278,7 +278,7 @@ impl Node for ast::Expr { &object, range, )?; - string::interpolation_to_expr(vm, source_file, interpolation)? + string::interpolation_to_expr(vm, interpolation)? } ExprKind::JoinedStr => { string::joined_str_from_object_with_range(vm, source_file, &object, range)? @@ -287,11 +287,10 @@ impl Node for ast::Expr { ExprKind::TemplateStr => { let template = string::template_str_from_object_with_range(vm, source_file, &object, range)?; - string::template_str_to_expr(vm, source_file, template)? + string::template_str_to_expr(vm, template)? } ExprKind::Constant => { - constant::constant_from_object_with_range(vm, source_file, &object, range)? - .into_expr() + constant::constant_from_object_with_range(vm, &object, range)?.into_expr() } ExprKind::Attribute => Self::Attribute(expr_attribute_from_object_with_range( vm, @@ -335,37 +334,39 @@ impl Node for ast::Expr { &object, range, )?), - }) + }; + ast::HasNodeIndex::node_index(&expression).set(range.index); + Ok(expression) } } // constructor fn expr_bool_op_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let values: Vec> = get_node_list_field(vm, source_file, object, "values", "BoolOp")?; let (runtime_values, values) = runtime_expr_list_from_values(values); Ok(ast::ExprBoolOp { - node_index: Default::default(), + node_index: range.node_index(), op: Node::ast_from_object( vm, source_file, get_node_field_required(vm, object, "op", "BoolOp")?, )?, values, - range, + range: range.range, runtime_values, }) } impl Node for ast::ExprBoolOp { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, op, values, range, @@ -382,13 +383,13 @@ impl Node for ast::ExprBoolOp { |values| values.ast_to_object(vm, source_file), ); dict.set_item("values", values, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "BoolOp")?; @@ -399,22 +400,22 @@ impl Node for ast::ExprBoolOp { // constructor fn expr_named_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprNamed { - node_index: Default::default(), + node_index: range.node_index(), target: get_required_node_field(vm, source_file, object, "target", "NamedExpr")?, value: get_required_node_field(vm, source_file, object, "value", "NamedExpr")?, - range, + range: range.range, }) } impl Node for ast::ExprNamed { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, target, value, range, @@ -427,13 +428,13 @@ impl Node for ast::ExprNamed { .unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "NamedExpr")?; @@ -444,12 +445,12 @@ impl Node for ast::ExprNamed { // constructor fn expr_bin_op_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprBinOp { - node_index: Default::default(), + node_index: range.node_index(), left: get_required_node_field(vm, source_file, object, "left", "BinOp")?, op: Node::ast_from_object( vm, @@ -457,14 +458,14 @@ fn expr_bin_op_from_object_with_range( get_node_field_required(vm, object, "op", "BinOp")?, )?, right: get_required_node_field(vm, source_file, object, "right", "BinOp")?, - range, + range: range.range, }) } impl Node for ast::ExprBinOp { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, left, op, right, @@ -480,13 +481,13 @@ impl Node for ast::ExprBinOp { .unwrap(); dict.set_item("right", right.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "BinOp")?; @@ -497,26 +498,26 @@ impl Node for ast::ExprBinOp { // constructor fn expr_unary_op_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprUnaryOp { - node_index: Default::default(), + node_index: range.node_index(), op: Node::ast_from_object( vm, source_file, get_node_field_required(vm, object, "op", "UnaryOp")?, )?, operand: get_required_node_field(vm, source_file, object, "operand", "UnaryOp")?, - range, + range: range.range, }) } impl Node for ast::ExprUnaryOp { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, op, operand, range, @@ -529,12 +530,12 @@ impl Node for ast::ExprUnaryOp { .unwrap(); dict.set_item("operand", operand.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "UnaryOp")?; @@ -545,26 +546,26 @@ impl Node for ast::ExprUnaryOp { // constructor fn expr_lambda_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprLambda { - node_index: Default::default(), + node_index: range.node_index(), parameters: Node::ast_from_object( vm, source_file, get_node_field_required(vm, object, "args", "Lambda")?, )?, body: get_required_node_field(vm, source_file, object, "body", "Lambda")?, - range, + range: range.range, }) } impl Node for ast::ExprLambda { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, parameters, body, range: _range, @@ -580,13 +581,13 @@ impl Node for ast::ExprLambda { dict.set_item("args", args, vm).unwrap(); dict.set_item("body", body.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Lambda")?; @@ -597,23 +598,23 @@ impl Node for ast::ExprLambda { // constructor fn expr_if_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprIf { - node_index: Default::default(), + node_index: range.node_index(), test: get_required_node_field(vm, source_file, object, "test", "IfExp")?, body: get_required_node_field(vm, source_file, object, "body", "IfExp")?, orelse: get_required_node_field(vm, source_file, object, "orelse", "IfExp")?, - range, + range: range.range, }) } impl Node for ast::ExprIf { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, test, body, orelse, @@ -629,13 +630,13 @@ impl Node for ast::ExprIf { .unwrap(); dict.set_item("orelse", orelse.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "IfExp")?; @@ -646,9 +647,9 @@ impl Node for ast::ExprIf { // constructor fn expr_dict_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let keys: Vec> = get_node_list_field(vm, source_file, object, "keys", "Dict")?; @@ -664,17 +665,17 @@ fn expr_dict_from_object_with_range( .map(|(key, value)| ast::DictItem { key, value }) .collect(); Ok(ast::ExprDict { - node_index: Default::default(), + node_index: range.node_index(), items, - range, + range: range.range, runtime_values, }) } impl Node for ast::ExprDict { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, items, range, runtime_values, @@ -698,13 +699,13 @@ impl Node for ast::ExprDict { |values| values.ast_to_object(vm, source_file), ); dict.set_item("values", values, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Dict")?; @@ -715,24 +716,24 @@ impl Node for ast::ExprDict { // constructor fn expr_set_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let elts: Vec> = get_node_list_field(vm, source_file, object, "elts", "Set")?; let (runtime_elts, elts) = runtime_expr_list_from_values(elts); Ok(ast::ExprSet { - node_index: Default::default(), + node_index: range.node_index(), elts, - range, + range: range.range, runtime_elts, }) } impl Node for ast::ExprSet { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, elts, range, runtime_elts, @@ -746,12 +747,12 @@ impl Node for ast::ExprSet { |values| values.ast_to_object(vm, source_file), ); dict.set_item("elts", elts, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Set")?; @@ -762,22 +763,22 @@ impl Node for ast::ExprSet { // constructor fn expr_list_comp_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprListComp { - node_index: Default::default(), + node_index: range.node_index(), elt: get_required_node_field(vm, source_file, object, "elt", "ListComp")?, generators: get_node_list_field(vm, source_file, object, "generators", "ListComp")?, - range, + range: range.range, }) } impl Node for ast::ExprListComp { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, elt, generators, range, @@ -790,13 +791,13 @@ impl Node for ast::ExprListComp { .unwrap(); dict.set_item("generators", generators.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "ListComp")?; @@ -807,22 +808,22 @@ impl Node for ast::ExprListComp { // constructor fn expr_set_comp_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprSetComp { - node_index: Default::default(), + node_index: range.node_index(), elt: get_required_node_field(vm, source_file, object, "elt", "SetComp")?, generators: get_node_list_field(vm, source_file, object, "generators", "SetComp")?, - range, + range: range.range, }) } impl Node for ast::ExprSetComp { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, elt, generators, range, @@ -835,13 +836,13 @@ impl Node for ast::ExprSetComp { .unwrap(); dict.set_item("generators", generators.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "SetComp")?; @@ -852,34 +853,42 @@ impl Node for ast::ExprSetComp { // constructor fn expr_dict_comp_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { + // Ruff uses a missing key for unpacking; Python's AST uses a missing value. + let key = get_required_node_field(vm, source_file, object, "key", "DictComp")?; + let value = get_node_field_opt(vm, object, "value")? + .map(|obj| Node::ast_from_object(vm, source_file, obj)) + .transpose()?; + let (key, value) = match value { + Some(value) => (Some(key), value), + None => (None, key), + }; Ok(ast::ExprDictComp { - node_index: Default::default(), - key: Some(get_required_node_field( - vm, - source_file, - object, - "key", - "DictComp", - )?), - value: get_required_node_field(vm, source_file, object, "value", "DictComp")?, - generators: get_node_list_field(vm, source_file, object, "generators", "DictComp")?, - range, + node_index: range.node_index(), + key, + value, + generators: get_node_list_field(vm, source_file, object, "generators", "DictComp")? + .into_boxed_slice(), + range: range.range, }) } impl Node for ast::ExprDictComp { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, key, value, generators, range, } = self; + let (key, value) = match key { + Some(key) => (key, Some(value)), + None => (value, None), + }; let node = NodeAst .into_ref_with_type(vm, pyast::NodeExprDictComp::static_type().to_owned()) .unwrap(); @@ -888,15 +897,19 @@ impl Node for ast::ExprDictComp { .unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - dict.set_item("generators", generators.ast_to_object(vm, source_file), vm) - .unwrap(); - node_add_location(&dict, range, vm, source_file); + dict.set_item( + "generators", + BoxedSlice(generators).ast_to_object(vm, source_file), + vm, + ) + .unwrap(); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "DictComp")?; @@ -907,23 +920,23 @@ impl Node for ast::ExprDictComp { // constructor fn expr_generator_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprGenerator { - node_index: Default::default(), + node_index: range.node_index(), elt: get_required_node_field(vm, source_file, object, "elt", "GeneratorExp")?, generators: get_node_list_field(vm, source_file, object, "generators", "GeneratorExp")?, - range, + range: range.range, parenthesized: true, }) } impl Node for ast::ExprGenerator { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, elt, generators, range, @@ -937,13 +950,13 @@ impl Node for ast::ExprGenerator { .unwrap(); dict.set_item("generators", generators.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "GeneratorExp")?; @@ -954,21 +967,21 @@ impl Node for ast::ExprGenerator { // constructor fn expr_await_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprAwait { - node_index: Default::default(), + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "Await")?, - range, + range: range.range, }) } impl Node for ast::ExprAwait { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, range, } = self; @@ -978,12 +991,12 @@ impl Node for ast::ExprAwait { let dict = node.as_object().dict().unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Await")?; @@ -994,23 +1007,23 @@ impl Node for ast::ExprAwait { // constructor fn expr_yield_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprYield { - node_index: Default::default(), + node_index: range.node_index(), value: get_node_field_opt(vm, object, "value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::ExprYield { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, range, } = self; @@ -1020,13 +1033,13 @@ impl Node for ast::ExprYield { let dict = node.as_object().dict().unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Yield")?; @@ -1037,21 +1050,21 @@ impl Node for ast::ExprYield { // constructor fn expr_yield_from_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprYieldFrom { - node_index: Default::default(), + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "YieldFrom")?, - range, + range: range.range, }) } impl Node for ast::ExprYieldFrom { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, range, } = self; @@ -1061,13 +1074,13 @@ impl Node for ast::ExprYieldFrom { let dict = node.as_object().dict().unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "YieldFrom")?; @@ -1078,30 +1091,32 @@ impl Node for ast::ExprYieldFrom { // constructor fn expr_compare_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { + let left: ast::Expr = get_required_node_field(vm, source_file, object, "left", "Compare")?; let comparators: Vec> = get_node_list_field(vm, source_file, object, "comparators", "Compare")?; let (runtime_comparators, comparators) = runtime_expr_boxed_slice_from_values(comparators); + let mut operands = Vec::with_capacity(comparators.len() + 1); + operands.push(left); + operands.extend(comparators); Ok(ast::ExprCompare { - node_index: Default::default(), - left: get_required_node_field(vm, source_file, object, "left", "Compare")?, + node_index: range.node_index(), ops: get_node_boxed_slice_field(vm, source_file, object, "ops", "Compare")?, - comparators, - range, + operands: operands.into_boxed_slice(), + range: range.range, runtime_comparators, }) } impl Node for ast::ExprCompare { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, - left, + node_index, ops, - comparators, + operands, range, runtime_comparators, } = self; @@ -1109,22 +1124,25 @@ impl Node for ast::ExprCompare { .into_ref_with_type(vm, pyast::NodeExprCompare::static_type().to_owned()) .unwrap(); let dict = node.as_object().dict().unwrap(); + let mut operands = operands.into_vec().into_iter(); + let left = operands.next().expect("A comparison has a left operand"); dict.set_item("left", left.ast_to_object(vm, source_file), vm) .unwrap(); dict.set_item("ops", BoxedSlice(ops).ast_to_object(vm, source_file), vm) .unwrap(); + let comparators: Box<[ast::Expr]> = operands.collect(); let comparators = runtime_comparators.map_or_else( || BoxedSlice(comparators).ast_to_object(vm, source_file), |values| values.ast_to_object(vm, source_file), ); dict.set_item("comparators", comparators, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Compare")?; @@ -1135,17 +1153,17 @@ impl Node for ast::ExprCompare { // constructor fn expr_call_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let mut arguments = merge_function_call_arguments( PositionalArguments::ast_from_field(vm, source_file, object, "args", "Call")?, KeywordArguments::ast_from_field(vm, source_file, object, "keywords", "Call")?, ); - arguments.range = range; + arguments.range = range.range; Ok(ast::ExprCall { - node_index: Default::default(), + node_index: range.node_index(), func: get_required_node_field(vm, source_file, object, "func", "Call")?, arguments, range_start: range.start(), @@ -1153,10 +1171,10 @@ fn expr_call_from_object_with_range( } impl Node for ast::ExprCall { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let range = self.range(); let Self { - node_index: _, + node_index, func, arguments, range_start: _, @@ -1180,13 +1198,13 @@ impl Node for ast::ExprCall { vm, ) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Call")?; @@ -1197,12 +1215,12 @@ impl Node for ast::ExprCall { // constructor fn expr_attribute_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprAttribute { - node_index: Default::default(), + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "Attribute")?, attr: get_required_identifier_field(vm, source_file, object, "attr", "Attribute")?, ctx: Node::ast_from_object( @@ -1210,14 +1228,14 @@ fn expr_attribute_from_object_with_range( source_file, get_node_field_required(vm, object, "ctx", "Attribute")?, )?, - range, + range: range.range, }) } impl Node for ast::ExprAttribute { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, attr, ctx, @@ -1233,13 +1251,13 @@ impl Node for ast::ExprAttribute { .unwrap(); dict.set_item("ctx", ctx.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Attribute")?; @@ -1250,12 +1268,12 @@ impl Node for ast::ExprAttribute { // constructor fn expr_subscript_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprSubscript { - node_index: Default::default(), + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "Subscript")?, slice: get_required_node_field(vm, source_file, object, "slice", "Subscript")?, ctx: Node::ast_from_object( @@ -1263,14 +1281,14 @@ fn expr_subscript_from_object_with_range( source_file, get_node_field_required(vm, object, "ctx", "Subscript")?, )?, - range, + range: range.range, }) } impl Node for ast::ExprSubscript { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, slice, ctx, @@ -1286,12 +1304,12 @@ impl Node for ast::ExprSubscript { .unwrap(); dict.set_item("ctx", ctx.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Subscript")?; @@ -1302,26 +1320,26 @@ impl Node for ast::ExprSubscript { // constructor fn expr_starred_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprStarred { - node_index: Default::default(), + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "Starred")?, ctx: Node::ast_from_object( vm, source_file, get_node_field_required(vm, object, "ctx", "Starred")?, )?, - range, + range: range.range, }) } impl Node for ast::ExprStarred { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, ctx, range, @@ -1334,12 +1352,12 @@ impl Node for ast::ExprStarred { .unwrap(); dict.set_item("ctx", ctx.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Starred")?; @@ -1350,26 +1368,26 @@ impl Node for ast::ExprStarred { // constructor fn expr_name_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprName { - node_index: Default::default(), + node_index: range.node_index(), id: get_required_identifier_field(vm, source_file, object, "id", "Name")?, ctx: Node::ast_from_object( vm, source_file, get_node_field_required(vm, object, "ctx", "Name")?, )?, - range, + range: range.range, }) } impl Node for ast::ExprName { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, id, ctx, range, @@ -1382,13 +1400,13 @@ impl Node for ast::ExprName { .unwrap(); dict.set_item("ctx", ctx.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Name")?; @@ -1399,30 +1417,30 @@ impl Node for ast::ExprName { // constructor fn expr_list_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let elts: Vec> = get_node_list_field(vm, source_file, object, "elts", "List")?; let (runtime_elts, elts) = runtime_expr_list_from_values(elts); Ok(ast::ExprList { - node_index: Default::default(), + node_index: range.node_index(), elts, ctx: Node::ast_from_object( vm, source_file, get_node_field_required(vm, object, "ctx", "List")?, )?, - range, + range: range.range, runtime_elts, }) } impl Node for ast::ExprList { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, elts, ctx, range, @@ -1439,13 +1457,13 @@ impl Node for ast::ExprList { dict.set_item("elts", elts, vm).unwrap(); dict.set_item("ctx", ctx.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "List")?; @@ -1456,31 +1474,31 @@ impl Node for ast::ExprList { // constructor fn expr_tuple_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let elts: Vec> = get_node_list_field(vm, source_file, object, "elts", "Tuple")?; let (runtime_elts, elts) = runtime_expr_list_from_values(elts); Ok(ast::ExprTuple { - node_index: Default::default(), + node_index: range.node_index(), elts, ctx: Node::ast_from_object( vm, source_file, get_node_field_required(vm, object, "ctx", "Tuple")?, )?, - range, + range: range.range, parenthesized: true, runtime_elts, }) } impl Node for ast::ExprTuple { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, elts, ctx, range: _range, @@ -1498,13 +1516,13 @@ impl Node for ast::ExprTuple { dict.set_item("elts", elts, vm).unwrap(); dict.set_item("ctx", ctx.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Tuple")?; @@ -1515,12 +1533,12 @@ impl Node for ast::ExprTuple { // constructor fn expr_slice_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::ExprSlice { - node_index: Default::default(), + node_index: range.node_index(), lower: get_node_field_opt(vm, object, "lower")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, @@ -1530,14 +1548,14 @@ fn expr_slice_from_object_with_range( step: get_node_field_opt(vm, object, "step")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::ExprSlice { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, lower, upper, step, @@ -1553,13 +1571,13 @@ impl Node for ast::ExprSlice { .unwrap(); dict.set_item("step", step.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Slice")?; @@ -1569,7 +1587,7 @@ impl Node for ast::ExprSlice { // sum impl Node for ast::ExprContext { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { let node_type = match self { Self::Load => pyast::NodeExprContextLoad::static_type(), Self::Store => pyast::NodeExprContextStore::static_type(), @@ -1583,7 +1601,7 @@ impl Node for ast::ExprContext { fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok( @@ -1605,7 +1623,7 @@ impl Node for ast::ExprContext { // product impl Node for ast::Comprehension { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { node_index: _, target, @@ -1639,7 +1657,7 @@ impl Node for ast::Comprehension { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let ifs: Vec> = diff --git a/crates/vm/src/stdlib/_ast/module.rs b/crates/vm/src/stdlib/_ast/module.rs index 37a6bc62849..f487f0040a7 100644 --- a/crates/vm/src/stdlib/_ast/module.rs +++ b/crates/vm/src/stdlib/_ast/module.rs @@ -1,6 +1,6 @@ +use super::AstSourceContext; use super::*; use crate::stdlib::_ast::type_ignore::TypeIgnore; -use rustpython_compiler_core::SourceFile; /// Represents the different types of Python module structures. /// @@ -26,7 +26,7 @@ pub(super) enum Mod { // sum impl Node for Mod { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::Module(cons) => cons.ast_to_object(vm, source_file), Self::Interactive(cons) => cons.ast_to_object(vm, source_file), @@ -37,7 +37,7 @@ impl Node for Mod { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok( @@ -74,7 +74,7 @@ pub(super) struct ModModule { // constructor impl Node for ModModule { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { module, type_ignores, @@ -105,7 +105,7 @@ impl Node for ModModule { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let body: Vec> = @@ -132,7 +132,7 @@ pub(super) struct ModInteractive { // constructor impl Node for ModInteractive { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { body, range: _, @@ -152,7 +152,7 @@ impl Node for ModInteractive { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let body: Vec> = @@ -168,7 +168,7 @@ impl Node for ModInteractive { // constructor impl Node for ast::ModExpression { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { node_index: _, body, @@ -185,7 +185,7 @@ impl Node for ast::ModExpression { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(Self { @@ -204,7 +204,7 @@ pub(super) struct ModFunctionType { // constructor impl Node for ModFunctionType { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { argtypes, returns, @@ -226,7 +226,7 @@ impl Node for ModFunctionType { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let argtypes: Vec> = diff --git a/crates/vm/src/stdlib/_ast/node.rs b/crates/vm/src/stdlib/_ast/node.rs index 7737ae076bb..6d0ae239c1b 100644 --- a/crates/vm/src/stdlib/_ast/node.rs +++ b/crates/vm/src/stdlib/_ast/node.rs @@ -1,12 +1,12 @@ +use super::AstSourceContext; use crate::{PyObjectRef, PyResult, VirtualMachine, builtins::PyList}; -use rustpython_compiler_core::SourceFile; use thin_vec::ThinVec; pub(crate) trait Node: Sized { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef; + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef; fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult; @@ -17,7 +17,7 @@ pub(crate) trait Node: Sized { } impl Node for Vec { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { vm.ctx .new_list( self.into_iter() @@ -29,7 +29,7 @@ impl Node for Vec { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let list = object.downcast_ref::().ok_or_else(|| { @@ -50,7 +50,7 @@ impl Node for Vec { } items[i].clone() }; - result.push(vm.with_recursion("while traversing AST node", || { + result.push(vm.with_recursion(" while traversing AST node", || { Node::ast_from_object(vm, source_file, item) })?); if list.borrow_vec().len() != len { @@ -62,7 +62,7 @@ impl Node for Vec { } impl Node for ThinVec { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { vm.ctx .new_list( self.into_iter() @@ -74,7 +74,7 @@ impl Node for ThinVec { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Vec::::ast_from_object(vm, source_file, object).map(Into::into) @@ -82,16 +82,16 @@ impl Node for ThinVec { } impl Node for Box { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { (*self).ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { - vm.with_recursion("while traversing AST node", || { + vm.with_recursion(" while traversing AST node", || { T::ast_from_object(vm, source_file, object).map(Self::new) }) } @@ -102,7 +102,7 @@ impl Node for Box { } impl Node for Option { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Some(node) => node.ast_to_object(vm, source_file), None => vm.ctx.none(), @@ -111,7 +111,7 @@ impl Node for Option { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if vm.is_none(&object) { @@ -126,13 +126,13 @@ impl Node for Option { pub(super) struct BoxedSlice(pub(super) Box<[T]>); impl Node for BoxedSlice { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { self.0.into_vec().ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(Self( diff --git a/crates/vm/src/stdlib/_ast/operator.rs b/crates/vm/src/stdlib/_ast/operator.rs index e05e490bb84..71d8c621769 100644 --- a/crates/vm/src/stdlib/_ast/operator.rs +++ b/crates/vm/src/stdlib/_ast/operator.rs @@ -1,9 +1,9 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; // sum impl Node for ast::BoolOp { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { let node_type = match self { Self::And => pyast::NodeBoolOpAnd::static_type(), Self::Or => pyast::NodeBoolOpOr::static_type(), @@ -13,7 +13,7 @@ impl Node for ast::BoolOp { fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok( @@ -33,7 +33,7 @@ impl Node for ast::BoolOp { // sum impl Node for ast::Operator { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { let node_type = match self { Self::Add => pyast::NodeOperatorAdd::static_type(), Self::Sub => pyast::NodeOperatorSub::static_type(), @@ -54,7 +54,7 @@ impl Node for ast::Operator { fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok( @@ -96,7 +96,7 @@ impl Node for ast::Operator { // sum impl Node for ast::UnaryOp { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { let node_type = match self { Self::Invert => pyast::NodeUnaryOpInvert::static_type(), Self::Not => pyast::NodeUnaryOpNot::static_type(), @@ -108,7 +108,7 @@ impl Node for ast::UnaryOp { fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok( @@ -132,7 +132,7 @@ impl Node for ast::UnaryOp { // sum impl Node for ast::CmpOp { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { let node_type = match self { Self::Eq => pyast::NodeCmpOpEq::static_type(), Self::NotEq => pyast::NodeCmpOpNotEq::static_type(), @@ -150,7 +150,7 @@ impl Node for ast::CmpOp { fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok( diff --git a/crates/vm/src/stdlib/_ast/other.rs b/crates/vm/src/stdlib/_ast/other.rs index 0da6be10c46..3bf7564236a 100644 --- a/crates/vm/src/stdlib/_ast/other.rs +++ b/crates/vm/src/stdlib/_ast/other.rs @@ -1,14 +1,14 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; impl Node for ast::ConversionFlag { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { vm.ctx.new_int(self as i8).into() } fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { match node_object_to_i32(vm, &object)? { @@ -23,13 +23,13 @@ impl Node for ast::ConversionFlag { // /// This is just a string, not strictly an AST node. But it makes AST conversions easier. impl Node for ast::name::Name { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { vm.ctx.intern_str(self.as_str()).to_object() } fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if !object.class().is(vm.ctx.types.str_type) { @@ -43,13 +43,13 @@ impl Node for ast::name::Name { } impl Node for ast::Decorator { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { ast::Expr::ast_to_object(self.expression, vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let expression = ast::Expr::ast_from_object(vm, source_file, object)?; @@ -64,9 +64,9 @@ impl Node for ast::Decorator { // product impl Node for ast::Alias { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, asname, range: _range, @@ -79,29 +79,32 @@ impl Node for ast::Alias { .unwrap(); dict.set_item("asname", asname.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { + let name = get_required_identifier_field(vm, source_file, &object, "name", "alias")?; + let asname = get_node_field_opt(vm, &object, "asname")? + .map(|obj| Node::ast_from_object(vm, source_file, obj)) + .transpose()?; + let range = range_from_object(vm, source_file, &object, "alias")?; Ok(Self { - node_index: Default::default(), - name: get_required_identifier_field(vm, source_file, &object, "name", "alias")?, - asname: get_node_field_opt(vm, &object, "asname")? - .map(|obj| Node::ast_from_object(vm, source_file, obj)) - .transpose()?, - range: range_from_object(vm, source_file, &object, "alias")?, + node_index: range.node_index(), + name, + asname, + range: range.range, }) } } // product impl Node for ast::WithItem { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { node_index: _, context_expr, @@ -129,7 +132,7 @@ impl Node for ast::WithItem { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(Self { diff --git a/crates/vm/src/stdlib/_ast/parameter.rs b/crates/vm/src/stdlib/_ast/parameter.rs index ea324eda48c..f03b16e40e7 100644 --- a/crates/vm/src/stdlib/_ast/parameter.rs +++ b/crates/vm/src/stdlib/_ast/parameter.rs @@ -1,9 +1,9 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; // product impl Node for ast::Parameters { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { node_index: _, posonlyargs, @@ -56,7 +56,7 @@ impl Node for ast::Parameters { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let posonlyargs = PositionalParameters::ast_from_field( @@ -151,9 +151,9 @@ fn validate_parameter_annotations( // product impl Node for ast::Parameter { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, annotation, // type_comment, @@ -180,16 +180,17 @@ impl Node for ast::Parameter { ) .unwrap_or_else(|| vm.ctx.none()); dict.set_item("type_comment", type_comment, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { - let name = get_required_identifier_field(vm, source_file, &_object, "arg", "arg")?; + let mut name: ast::Identifier = + get_required_identifier_field(vm, source_file, &_object, "arg", "arg")?; let annotation = get_node_field_opt(vm, &_object, "annotation")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?; @@ -199,11 +200,12 @@ impl Node for ast::Parameter { super::constant::runtime_string_from_pyobject(vm, &type_comment) }); let range = range_from_object(vm, source_file, &_object, "arg")?; + name.range = range.range; Ok(Self { - node_index: Default::default(), + node_index: range.node_index(), name, annotation, - range, + range: range.range, runtime_type_comment, runtime_type_comment_bytes, }) @@ -212,9 +214,9 @@ impl Node for ast::Parameter { // product impl Node for ast::Keyword { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, arg, value, range: _range, @@ -227,21 +229,24 @@ impl Node for ast::Keyword { .unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { + let arg = get_node_field_opt(vm, &_object, "arg")? + .map(|obj| Node::ast_from_object(vm, source_file, obj)) + .transpose()?; + let value = get_required_node_field(vm, source_file, &_object, "value", "keyword")?; + let range = range_from_object(vm, source_file, &_object, "keyword")?; Ok(Self { - node_index: Default::default(), - arg: get_node_field_opt(vm, &_object, "arg")? - .map(|obj| Node::ast_from_object(vm, source_file, obj)) - .transpose()?, - value: get_required_node_field(vm, source_file, &_object, "value", "keyword")?, - range: range_from_object(vm, source_file, &_object, "keyword")?, + node_index: range.node_index(), + arg, + value, + range: range.range, }) } } @@ -254,7 +259,7 @@ struct PositionalParameters { impl PositionalParameters { fn ast_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -267,13 +272,13 @@ impl PositionalParameters { } impl Node for PositionalParameters { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { BoxedSlice(self.args).ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let args: BoxedSlice<_> = Node::ast_from_object(vm, source_file, object)?; @@ -292,7 +297,7 @@ struct KeywordParameters { impl KeywordParameters { fn ast_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -305,13 +310,13 @@ impl KeywordParameters { } impl Node for KeywordParameters { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { BoxedSlice(self.keywords).ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let keywords: BoxedSlice<_> = Node::ast_from_object(vm, source_file, object)?; @@ -331,7 +336,7 @@ struct ParameterDefaults { impl ParameterDefaults { fn ast_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -345,7 +350,7 @@ impl ParameterDefaults { fn ast_from_field_preserve_none( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -367,13 +372,13 @@ impl ParameterDefaults { } impl Node for ParameterDefaults { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { BoxedSlice(self.defaults).ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let defaults: BoxedSlice<_> = Node::ast_from_object(vm, source_file, object)?; diff --git a/crates/vm/src/stdlib/_ast/pattern.rs b/crates/vm/src/stdlib/_ast/pattern.rs index 667bb5fcf45..f8170da6939 100644 --- a/crates/vm/src/stdlib/_ast/pattern.rs +++ b/crates/vm/src/stdlib/_ast/pattern.rs @@ -1,9 +1,9 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; // product impl Node for ast::MatchCase { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { node_index: _, pattern, @@ -30,7 +30,7 @@ impl Node for ast::MatchCase { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let body: Vec> = @@ -51,7 +51,7 @@ impl Node for ast::MatchCase { // sum impl Node for ast::Pattern { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::MatchValue(cons) => cons.ast_to_object(vm, source_file), Self::MatchSingleton(cons) => cons.ast_to_object(vm, source_file), @@ -65,7 +65,7 @@ impl Node for ast::Pattern { } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if vm.is_none(&object) { @@ -188,7 +188,7 @@ type PatternListField = (RuntimePatternList, Vec); fn pattern_list_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -203,21 +203,21 @@ fn pattern_list_from_field( // constructor fn pattern_match_value_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::PatternMatchValue { - node_index: Default::default(), + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "MatchValue")?, - range, + range: range.range, }) } impl Node for ast::PatternMatchValue { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, range, } = self; @@ -227,13 +227,13 @@ impl Node for ast::PatternMatchValue { let dict = node.as_object().dict().unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchValue")?; @@ -244,25 +244,25 @@ impl Node for ast::PatternMatchValue { // constructor fn pattern_match_singleton_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::PatternMatchSingleton { - node_index: Default::default(), + node_index: range.node_index(), value: Node::ast_from_object( vm, source_file, get_node_field(vm, object, "value", "MatchSingleton")?, )?, - range, + range: range.range, }) } impl Node for ast::PatternMatchSingleton { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, range, } = self; @@ -275,13 +275,13 @@ impl Node for ast::PatternMatchSingleton { let dict = node.as_object().dict().unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchSingleton")?; @@ -290,7 +290,7 @@ impl Node for ast::PatternMatchSingleton { } impl Node for ast::Singleton { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { match self { Self::None => vm.ctx.none(), Self::True => vm.ctx.new_bool(true).into(), @@ -300,7 +300,7 @@ impl Node for ast::Singleton { fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if vm.is_none(&object) { @@ -318,24 +318,30 @@ impl Node for ast::Singleton { // constructor fn pattern_match_sequence_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { - let (runtime_patterns, patterns) = - pattern_list_from_field(vm, source_file, object, "patterns", "MatchSequence", range)?; + let (runtime_patterns, patterns) = pattern_list_from_field( + vm, + source_file, + object, + "patterns", + "MatchSequence", + range.range, + )?; Ok(ast::PatternMatchSequence { - node_index: Default::default(), + node_index: range.node_index(), patterns: patterns.to_vec(), - range, + range: range.range, runtime_patterns, }) } impl Node for ast::PatternMatchSequence { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, patterns, range, runtime_patterns, @@ -352,13 +358,13 @@ impl Node for ast::PatternMatchSequence { |values| values.ast_to_object(vm, source_file), ); dict.set_item("patterns", patterns, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchSequence")?; @@ -369,9 +375,9 @@ impl Node for ast::PatternMatchSequence { // constructor fn pattern_match_mapping_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let keys: Vec> = get_node_list_field(vm, source_file, object, "keys", "MatchMapping")?; @@ -383,22 +389,22 @@ fn pattern_match_mapping_from_object_with_range( .any(Option::is_none) .then(|| patterns.clone()); Ok(ast::PatternMatchMapping { - node_index: Default::default(), - keys: lower_nullable_exprs(&keys, range).into(), - patterns: lower_nullable_patterns(&patterns, range).into(), + node_index: range.node_index(), + keys: lower_nullable_exprs(&keys, range.range).into(), + patterns: lower_nullable_patterns(&patterns, range.range).into(), rest: get_node_field_opt(vm, object, "rest")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, runtime_keys, runtime_patterns, }) } impl Node for ast::PatternMatchMapping { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, keys, patterns, rest, @@ -422,13 +428,13 @@ impl Node for ast::PatternMatchMapping { dict.set_item("patterns", patterns, vm).unwrap(); dict.set_item("rest", rest.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchMapping")?; @@ -439,9 +445,9 @@ impl Node for ast::PatternMatchMapping { // constructor fn pattern_match_class_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let cls = get_required_node_field(vm, source_file, object, "cls", "MatchClass")?; let patterns: Vec> = @@ -461,17 +467,17 @@ fn pattern_match_class_from_object_with_range( let runtime_patterns = has_runtime_shape.then(|| patterns.clone()); let runtime_kwd_attrs = has_runtime_shape.then(|| kwd_attrs.0.clone()); let runtime_kwd_patterns = has_runtime_shape.then(|| kwd_patterns.clone()); - let patterns = PatternMatchClassPatterns(lower_nullable_patterns(&patterns, range)); + let patterns = PatternMatchClassPatterns(lower_nullable_patterns(&patterns, range.range)); let kwd_patterns = - PatternMatchClassKeywordPatterns(lower_nullable_patterns(&kwd_patterns, range)); + PatternMatchClassKeywordPatterns(lower_nullable_patterns(&kwd_patterns, range.range)); let (patterns, keywords) = merge_pattern_match_class(patterns, kwd_attrs, kwd_patterns); Ok(ast::PatternMatchClass { - node_index: Default::default(), + node_index: range.node_index(), cls, - range, + range: range.range, arguments: ast::PatternArguments { - node_index: Default::default(), + node_index: range.node_index(), range: Default::default(), patterns: patterns.into(), keywords, @@ -483,9 +489,9 @@ fn pattern_match_class_from_object_with_range( } impl Node for ast::PatternMatchClass { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, cls, arguments, range, @@ -519,13 +525,13 @@ impl Node for ast::PatternMatchClass { dict.set_item("patterns", patterns, vm).unwrap(); dict.set_item("kwd_attrs", kwd_attrs, vm).unwrap(); dict.set_item("kwd_patterns", kwd_patterns, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchClass")?; @@ -536,13 +542,13 @@ impl Node for ast::PatternMatchClass { struct PatternMatchClassPatterns(Vec); impl Node for PatternMatchClassPatterns { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { self.0.ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(Self(Node::ast_from_object(vm, source_file, object)?)) @@ -554,7 +560,7 @@ struct PatternMatchClassKeywordAttributes(Vec); impl PatternMatchClassKeywordAttributes { fn ast_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -570,13 +576,13 @@ impl PatternMatchClassKeywordAttributes { } impl Node for PatternMatchClassKeywordAttributes { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { self.0.ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(Self(Node::ast_from_object(vm, source_file, object)?)) @@ -586,13 +592,13 @@ impl Node for PatternMatchClassKeywordAttributes { struct PatternMatchClassKeywordPatterns(Vec); impl Node for PatternMatchClassKeywordPatterns { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { self.0.ast_to_object(vm, source_file) } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(Self(Node::ast_from_object(vm, source_file, object)?)) @@ -601,23 +607,23 @@ impl Node for PatternMatchClassKeywordPatterns { // constructor fn pattern_match_star_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::PatternMatchStar { - node_index: Default::default(), + node_index: range.node_index(), name: get_node_field_opt(vm, object, "name")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::PatternMatchStar { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, range, } = self; @@ -627,13 +633,13 @@ impl Node for ast::PatternMatchStar { let dict = node.as_object().dict().unwrap(); dict.set_item("name", name.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchStar")?; @@ -644,26 +650,26 @@ impl Node for ast::PatternMatchStar { // constructor fn pattern_match_as_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::PatternMatchAs { - node_index: Default::default(), + node_index: range.node_index(), pattern: get_node_field_opt(vm, object, "pattern")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, name: get_node_field_opt(vm, object, "name")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::PatternMatchAs { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, pattern, name, range, @@ -676,13 +682,13 @@ impl Node for ast::PatternMatchAs { .unwrap(); dict.set_item("name", name.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchAs")?; @@ -693,24 +699,24 @@ impl Node for ast::PatternMatchAs { // constructor fn pattern_match_or_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let (runtime_patterns, patterns) = - pattern_list_from_field(vm, source_file, object, "patterns", "MatchOr", range)?; + pattern_list_from_field(vm, source_file, object, "patterns", "MatchOr", range.range)?; Ok(ast::PatternMatchOr { - node_index: Default::default(), + node_index: range.node_index(), patterns: patterns.to_vec(), - range, + range: range.range, runtime_patterns, }) } impl Node for ast::PatternMatchOr { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, patterns, range, runtime_patterns, @@ -724,12 +730,12 @@ impl Node for ast::PatternMatchOr { |values| values.ast_to_object(vm, source_file), ); dict.set_item("patterns", patterns, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "MatchOr")?; diff --git a/crates/vm/src/stdlib/_ast/pyast.rs b/crates/vm/src/stdlib/_ast/pyast.rs index 46bf0918d15..4632d6e0381 100644 --- a/crates/vm/src/stdlib/_ast/pyast.rs +++ b/crates/vm/src/stdlib/_ast/pyast.rs @@ -72,17 +72,13 @@ macro_rules! impl_base_node { super::python::_ast::ast_reduce(&zelf, vm) } - #[pymethod] - fn __replace__( - zelf: PyObjectRef, - fields: crate::function::KwArgs, - vm: &VirtualMachine, - ) -> PyResult { - super::python::_ast::ast_replace(&zelf, fields.into(), vm) - } - #[extend_class] fn extend_class(ctx: &Context, class: &'static Py) { + class.set_str_attr( + "__replace__", + super::python::_ast::AST_REPLACE.to_proper_method(class, ctx), + ctx, + ); // AST types are mutable (heap types, not IMMUTABLETYPE). class.slots.flags.remove(crate::types::PyTypeFlags::IMMUTABLETYPE); class.set_attr( @@ -116,17 +112,13 @@ macro_rules! impl_base_node { super::python::_ast::ast_reduce(&zelf, vm) } - #[pymethod] - fn __replace__( - zelf: PyObjectRef, - fields: crate::function::KwArgs, - vm: &VirtualMachine, - ) -> PyResult { - super::python::_ast::ast_replace(&zelf, fields.into(), vm) - } - #[extend_class] fn extend_class_with_fields(ctx: &Context, class: &'static Py) { + class.set_str_attr( + "__replace__", + super::python::_ast::AST_REPLACE.to_proper_method(class, ctx), + ctx, + ); // AST types are mutable (heap types, not IMMUTABLETYPE). class.slots.flags.remove(crate::types::PyTypeFlags::IMMUTABLETYPE); class.set_attr( @@ -351,14 +343,14 @@ impl_node!( impl_node!( #[pyclass(module = "ast", name = "Import", base = NodeStmt)] pub(crate) struct NodeStmtImport, - fields: ["names"], + fields: ["names", "is_lazy"], attributes: ["lineno", "col_offset", "end_lineno", "end_col_offset"], ); impl_node!( #[pyclass(module = "ast", name = "ImportFrom", base = NodeStmt)] pub(crate) struct NodeStmtImportFrom, - fields: ["module", "names", "level"], + fields: ["module", "names", "level", "is_lazy"], attributes: ["lineno", "col_offset", "end_lineno", "end_col_offset"], ); @@ -1209,13 +1201,20 @@ const FIELD_TYPES: &[(&str, &[(&str, FieldType)])] = &[ ("msg", FieldType::Optional("expr")), ], ), - ("Import", &[("names", FieldType::ListOf("alias"))]), + ( + "Import", + &[ + ("names", FieldType::ListOf("alias")), + ("is_lazy", FieldType::OptionalBuiltin("int")), + ], + ), ( "ImportFrom", &[ ("module", FieldType::OptionalBuiltin("str")), ("names", FieldType::ListOf("alias")), ("level", FieldType::OptionalBuiltin("int")), + ("is_lazy", FieldType::OptionalBuiltin("int")), ], ), ("Global", &[("names", FieldType::ListOfBuiltin("str"))]), @@ -1292,7 +1291,7 @@ const FIELD_TYPES: &[(&str, &[(&str, FieldType)])] = &[ "DictComp", &[ ("key", FieldType::Node("expr")), - ("value", FieldType::Node("expr")), + ("value", FieldType::Optional("expr")), ("generators", FieldType::ListOf("comprehension")), ], ), diff --git a/crates/vm/src/stdlib/_ast/python.rs b/crates/vm/src/stdlib/_ast/python.rs index cb9027aeb99..c4db10d7547 100644 --- a/crates/vm/src/stdlib/_ast/python.rs +++ b/crates/vm/src/stdlib/_ast/python.rs @@ -15,6 +15,8 @@ pub(crate) mod _ast { types::{Constructor, Initializer}, warn, }; + use rustpython_common::wtf8::wtf8_concat; + #[pyattr] #[pyclass(module = "ast", name = "AST")] #[derive(Debug, PyPayload)] @@ -34,7 +36,7 @@ pub(crate) mod _ast { class.set_str_attr("_attributes", empty_tuple.clone(), ctx); class.set_str_attr("__match_args__", empty_tuple, ctx); - const AST_DEEPCOPY: PyMethodDef = PyMethodDef::new_const( + const AST_DEEPCOPY: PyMethodDef = PyMethodDef::new_method_const( "__deepcopy__", |zelf: PyObjectRef, memo: PyObjectRef, vm: &VirtualMachine| -> PyResult { ast_deepcopy(&zelf, &memo, vm) @@ -154,22 +156,6 @@ pub(crate) mod _ast { Ok(contained) } - fn ast_replace_set_difference_update( - expecting: &Py, - iterable: Option<&PyObject>, - vm: &VirtualMachine, - ) -> PyResult<()> { - let Some(iterable) = iterable else { - return Ok(()); - }; - let iterable = iterable.to_owned().try_into_value::(vm)?; - for item in iterable.iter(vm)? { - let item = item?; - ast_replace_set_discard(expecting, &item, vm)?; - } - Ok(()) - } - fn ast_set_attr( obj: &PyObject, name: &PyObject, @@ -183,6 +169,17 @@ pub(crate) mod _ast { obj.set_attr(&name, value, vm) } + pub(crate) const AST_REPLACE: PyMethodDef = PyMethodDef::new_method_const( + "__replace__", + |zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine| -> PyResult { + ast_replace(&zelf, args, vm) + }, + PyMethodFlags::METHOD, + crate::function::ItemDoc::static_text( + "__replace__($self, /, **fields)\n--\n\nReturn a copy of the AST node with new values for the specified fields.", + ), + ); + pub(crate) fn ast_replace(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if !args.args.is_empty() { return Err(vm.new_type_error("__replace__() takes no positional arguments")); @@ -193,57 +190,6 @@ pub(crate) mod _ast { let attributes = cls.get_attr(vm.ctx.intern_str("_attributes")); let dict = zelf.as_object().dict(); - let expecting = PySet::default().into_ref(&vm.ctx); - ast_replace_set_update(&expecting, fields.as_deref(), vm)?; - ast_replace_set_update(&expecting, attributes.as_deref(), vm)?; - - for (key, _value) in &args.kwargs { - let key_obj: PyObjectRef = vm.ctx.new_str(key.as_ref()).into(); - if !ast_replace_set_discard(&expecting, &key_obj, vm)? { - return Err(vm.new_type_error(format!( - "{}.__replace__ got an unexpected keyword argument '{}'.", - cls.name(), - key - ))); - } - } - - if let Some(dict) = dict.as_deref() { - for (key, _value) in dict.items_vec() { - ast_replace_set_discard(&expecting, &key, vm)?; - } - ast_replace_set_difference_update(&expecting, attributes.as_deref(), vm)?; - } - - // Discard optional fields (T | None). - if let Some(field_types) = cls.get_attr(vm.ctx.intern_str("_field_types")) - && let Ok(field_types) = field_types.downcast::() - { - for (key, value) in field_types.items_vec() { - if value.fast_isinstance(vm.ctx.types.union_type) { - ast_replace_set_discard(&expecting, &key, vm)?; - } - } - } - - let remaining = expecting.elements(); - if !remaining.is_empty() { - let mut names = Vec::with_capacity(remaining.len()); - for name in &remaining { - names.push(name.repr(vm)?.to_string()); - } - names.sort(); - let missing = names.join(", "); - let count = names.len(); - return Err(vm.new_type_error(format!( - "{}.__replace__ missing {} keyword argument{}: {}.", - cls.name(), - count, - if count == 1 { "" } else { "s" }, - missing - ))); - } - let payload = vm.ctx.new_dict(); if let Some(dict) = dict { ast_replace_update_payload(&payload, fields.as_deref(), &dict, vm)?; @@ -309,10 +255,60 @@ pub(crate) mod _ast { Ok(vm.ctx.new_str(repr)) } + fn abstract_types() -> [&'static Py; 13] { + [ + NodeAst::static_type(), + super::super::pyast::NodeMod::static_type(), + super::super::pyast::NodeStmt::static_type(), + super::super::pyast::NodeExpr::static_type(), + super::super::pyast::NodeExprContext::static_type(), + super::super::pyast::NodeBoolOp::static_type(), + super::super::pyast::NodeOperator::static_type(), + super::super::pyast::NodeUnaryOp::static_type(), + super::super::pyast::NodeCmpOp::static_type(), + super::super::pyast::NodeExceptHandler::static_type(), + super::super::pyast::NodePattern::static_type(), + super::super::pyast::NodeTypeIgnore::static_type(), + super::super::pyast::NodeTypeParam::static_type(), + ] + } + + #[pyfunction(signature_from_flags)] + fn _is_abstract(object: PyObjectRef, vm: &VirtualMachine) -> PyResult { + is_abstract(&object, vm) + } + + fn is_abstract(cls: &PyObject, vm: &VirtualMachine) -> PyResult { + // PySet_Contains rejects mutable sets and preserves comparison errors; + // Python-level set containment has different behavior for both cases. + let hash = match cls.hash(vm) { + Ok(hash) => hash, + Err(err) if err.class().is(vm.ctx.exceptions.type_error) => { + return Err(vm.new_type_error(wtf8_concat!( + "cannot use '", + cls.class().fully_qualified_name(vm)?, + "' as a set element (", + err.as_object().str(vm)?.as_wtf8(), + ")" + ))); + } + Err(err) => return Err(err), + }; + for typ in abstract_types() { + let typ = typ.as_object(); + if typ.hash(vm)? == hash + && typ.rich_compare_bool(cls, crate::types::PyComparisonOp::Eq, vm)? + { + return Ok(true); + } + } + Ok(false) + } + impl Constructor for NodeAst { type Args = FuncArgs; - fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { // Keep _instance for parser-internal shared operator/context nodes, // but match CPython's public constructor behavior by allocating a // fresh object for Python-level ast.Load()/ast.Add()/... calls. @@ -330,10 +326,6 @@ pub(crate) mod _ast { }; let zelf = vm.ctx.new_base_object(cls, dict); - // type.__call__ does not invoke slot_init after slot_new - // for types with a custom slot_new, so we must call it here. - Self::slot_init(&zelf, args, vm)?; - Ok(zelf) } @@ -346,6 +338,21 @@ pub(crate) mod _ast { type Args = FuncArgs; fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + if is_abstract(zelf.class().as_object(), vm)? { + let message = vm.ctx.new_str(wtf8_concat!( + "Instantiating abstract AST node class ", + zelf.class().fully_qualified_name(vm)?, + " is deprecated. This will become an error in Python 3.20" + )); + warn::warn( + message.into(), + Some(vm.ctx.exceptions.deprecation_warning.to_owned()), + 1, + None, + vm, + )?; + } + let fields = zelf .class() .get_attr(vm.ctx.intern_str("_fields")) @@ -387,10 +394,10 @@ pub(crate) mod _ast { let contains = fields_seq.contains(&key_obj, vm)?; if contains { if !ast_replace_set_discard(&remaining_fields, &key_obj, vm)? { - return Err(vm.new_type_error(format!( - "{} got multiple values for argument '{}'", - zelf.class().name(), - key + return Err(vm.new_type_error(wtf8_concat!( + zelf.class().fully_qualified_name(vm)?, + " got multiple values for argument ", + key_obj.repr(vm)?.as_wtf8() ))); } } else { @@ -410,86 +417,94 @@ pub(crate) mod _ast { attributes.as_deref().unwrap() }; if !attrs.sequence_unchecked().contains(&key_obj, vm)? { - let message = vm.ctx.new_str(format!( - "{}.__init__ got an unexpected keyword argument '{}'. \ -Support for arbitrary keyword arguments is deprecated and will be removed in Python 3.15.", - zelf.class().name(), - key - )); - warn::warn( - message.into(), - Some(vm.ctx.exceptions.deprecation_warning.to_owned()), - 1, - None, - vm, - )?; + return Err(vm.new_type_error(wtf8_concat!( + zelf.class().fully_qualified_name(vm)?, + ".__init__ got an unexpected keyword argument ", + key_obj.repr(vm)?.as_wtf8() + ))); } } zelf.set_attr(vm.ctx.intern_str(key), value, vm)?; } - // Use _field_types to determine defaults for unset fields. - // Only built-in AST node classes have _field_types populated. - let field_types = zelf.class().get_attr(vm.ctx.intern_str("_field_types")); - if let Some(Ok(ft_dict)) = - field_types.map(|ft| ft.downcast::()) + // Custom AST subclasses without _field_types retain their permissive + // treatment of fields omitted from the constructor. + if !remaining_fields.elements().is_empty() + && let Some(field_types) = zelf.class().get_attr(vm.ctx.intern_str("_field_types")) { + let ft_dict = field_types + .downcast::() + .map_err(|_| vm.new_system_error("bad argument to internal function"))?; let expr_ctx_type: PyObjectRef = super::super::pyast::NodeExprContext::make_static_type().into(); + let missing_names = PySet::default().into_ref(&vm.ctx); for field in remaining_fields.elements() { - if let Some(ftype) = ft_dict.get_item_opt(&*field, vm)? { - if ftype.fast_isinstance(vm.ctx.types.union_type) { - // Optional field (T | None) — no default - } else if ftype.fast_isinstance(vm.ctx.types.generic_alias_type) { - // List field (list[T]) — default to [] - let empty_list: PyObjectRef = vm.ctx.new_list(vec![]).into(); - ast_set_attr(zelf, &field, empty_list, vm)?; - } else if ftype.is(&expr_ctx_type) { - // expr_context — default to Load() - let load_type = - super::super::pyast::NodeExprContextLoad::make_static_type(); - let load_instance = load_type - .get_attr(vm.ctx.intern_str("_instance")) - .unwrap_or_else(|| { - vm.ctx.new_base_object(load_type, Some(vm.ctx.new_dict())) - }); - ast_set_attr(zelf, &field, load_instance, vm)?; - } else { - // Required field missing: emit DeprecationWarning. - let field_repr = field.repr(vm)?; - let message = vm.ctx.new_str(format!( - "{}.__init__ missing 1 required positional argument: {}. \ -This will become an error in Python 3.15.", - zelf.class().name(), - field_repr - )); - warn::warn( - message.into(), - Some(vm.ctx.exceptions.deprecation_warning.to_owned()), - 1, - None, - vm, - )?; - } + let Some(ftype) = ft_dict.get_item_opt(&*field, vm)? else { + return Err(vm.new_type_error(wtf8_concat!( + "Field ", + field.repr(vm)?.as_wtf8(), + " is missing from ", + zelf.class().fully_qualified_name(vm)?, + "._field_types" + ))); + }; + if ftype.fast_isinstance(vm.ctx.types.union_type) { + // Optional fields already have a None default on the class. + } else if ftype.class().is(vm.ctx.types.generic_alias_type) { + let empty_list: PyObjectRef = vm.ctx.new_list(vec![]).into(); + ast_set_attr(zelf, &field, empty_list, vm)?; + } else if ftype.is(&expr_ctx_type) { + let load_type = + super::super::pyast::NodeExprContextLoad::make_static_type(); + let load_instance = load_type + .get_attr(vm.ctx.intern_str("_instance")) + .unwrap_or_else(|| { + vm.ctx.new_base_object(load_type, Some(vm.ctx.new_dict())) + }); + ast_set_attr(zelf, &field, load_instance, vm)?; } else { - let field_repr = field.repr(vm)?; - let message = vm.ctx.new_str(format!( - "Field {} is missing from {}._field_types. \ -This will become an error in Python 3.15.", - field_repr, - zelf.class().name() - )); - warn::warn( - message.into(), - Some(vm.ctx.exceptions.deprecation_warning.to_owned()), - 1, - None, - vm, - )?; + missing_names.add(field, vm)?; } } + + let count = missing_names.elements().len(); + if count > 0 { + // Match constructor order and preserve non-UTF-8 field names. + let mut message = wtf8_concat!( + zelf.class().fully_qualified_name(vm)?, + ".__init__ missing ", + count, + " required positional argument", + if count == 1 { "" } else { "s" }, + ": " + ); + let mut num_left = count as isize; + for i in 0..numfields { + let field = fields_seq.get_item(i as isize, vm)?; + if missing_names.contains(&field, vm)? { + let field = field + .downcast::() + .map_err(|_| vm.new_system_error("non-string AST field name"))?; + message.push_wtf8("'".as_ref()); + message.push_wtf8(field.as_wtf8()); + message.push_wtf8("'".as_ref()); + let separator = if num_left == 1 { + "" + } else if count == 2 { + " and " + } else if num_left == 2 { + ", and " + } else { + ", " + }; + message.push_wtf8(separator.as_ref()); + num_left -= 1; + } + } + return Err(vm.new_type_error(message)); + } } Ok(()) @@ -561,7 +576,7 @@ This will become an error in Python 3.15.", set_empty_annotations(typ); } - const AST_REDUCE: PyMethodDef = PyMethodDef::new_const( + const AST_REDUCE: PyMethodDef = PyMethodDef::new_method_const( "__reduce__", |zelf: PyObjectRef, vm: &VirtualMachine| -> PyResult { ast_reduce(&zelf, vm) @@ -569,16 +584,6 @@ This will become an error in Python 3.15.", PyMethodFlags::METHOD, crate::function::ItemDoc::static_text("__reduce__($self, /)\n--\n\n"), ); - const AST_REPLACE: PyMethodDef = PyMethodDef::new_const( - "__replace__", - |zelf: PyObjectRef, args: FuncArgs, vm: &VirtualMachine| -> PyResult { - ast_replace(&zelf, args, vm) - }, - PyMethodFlags::METHOD, - crate::function::ItemDoc::static_text( - "__replace__($self, /, **fields)\n--\n\nReturn a copy of the AST node with new values for the specified fields.", - ), - ); let base_type = NodeAst::static_type(); ast_type.set_str_attr( "__reduce__", @@ -602,7 +607,7 @@ This will become an error in Python 3.15.", | Set(expr* elts)\n\ | ListComp(expr elt, comprehension* generators)\n\ | SetComp(expr elt, comprehension* generators)\n\ - | DictComp(expr key, expr value, comprehension* generators)\n\ + | DictComp(expr key, expr? value, comprehension* generators)\n\ | GeneratorExp(expr elt, comprehension* generators)\n\ | Await(expr value)\n\ | Yield(expr? value)\n\ diff --git a/crates/vm/src/stdlib/_ast/source_location.rs b/crates/vm/src/stdlib/_ast/source_location.rs new file mode 100644 index 00000000000..67c1e7c5a91 --- /dev/null +++ b/crates/vm/src/stdlib/_ast/source_location.rs @@ -0,0 +1,93 @@ +//! Per-conversion coordinates for Python AST input and output. + +use crate::{PyResult, VirtualMachine}; +use core::{cell::RefCell, ops::Deref}; +use ruff_python_ast::{AtomicNodeIndex, NodeIndex}; +use ruff_text_size::TextRange; +use rustpython_compiler_core::{AstLocations, SourceFile, SourceLocationRange}; + +pub(super) struct AstSourceContext { + source_file: SourceFile, + // Outbound parser AST conversion never allocates a metadata table. + locations: RefCell>, +} + +#[derive(Clone, Copy)] +pub(super) struct AstNodeRange { + pub range: TextRange, + pub index: NodeIndex, +} + +impl AstNodeRange { + pub(super) fn node_index(self) -> AtomicNodeIndex { + let index = AtomicNodeIndex::NONE; + index.set(self.index); + index + } +} + +impl AstSourceContext { + pub(super) fn new(source_file: SourceFile) -> Self { + Self { + source_file, + locations: RefCell::new(None), + } + } + + /// Coordinates have already been read and validated by the caller. The + /// metadata borrow cannot span Python getters or recursive node conversion. + pub(super) fn register( + &self, + vm: &VirtualMachine, + range: TextRange, + location: Option, + ) -> PyResult { + let id = self + .locations + .borrow_mut() + .get_or_insert_default() + .allocate(location) + .map_err(|_| vm.new_memory_error("too many AST location identities"))?; + Ok(AstNodeRange { + range, + index: NodeIndex::from(id), + }) + } + + pub(super) fn location(&self, index: NodeIndex) -> Option { + let id = index.as_u32()?; + self.locations.borrow().as_ref()?.get(id) + } + + #[cfg(feature = "codegen")] + pub(super) fn preprocess_locations( + &self, + f: impl FnOnce(&mut AstLocations) -> Result<(), rustpython_compiler_core::AstLocationError>, + ) -> Result<(), rustpython_compiler_core::AstLocationError> { + f(self.locations.borrow_mut().get_or_insert_default()) + } + + pub(super) fn has_locations(&self) -> bool { + self.locations.borrow().is_some() + } + + pub(super) fn take_locations(&self) -> Option { + self.locations.borrow_mut().take() + } +} + +impl Deref for AstSourceContext { + type Target = SourceFile; + + fn deref(&self) -> &Self::Target { + &self.source_file + } +} + +impl Deref for AstNodeRange { + type Target = TextRange; + + fn deref(&self) -> &Self::Target { + &self.range + } +} diff --git a/crates/vm/src/stdlib/_ast/statement.rs b/crates/vm/src/stdlib/_ast/statement.rs index cfdf3e5f530..7f0b5d75f5f 100644 --- a/crates/vm/src/stdlib/_ast/statement.rs +++ b/crates/vm/src/stdlib/_ast/statement.rs @@ -1,10 +1,10 @@ +use super::AstSourceContext; use super::*; use crate::stdlib::_ast::argument::{ KeywordArguments, PositionalArguments, merge_class_def_args, split_class_def_args, }; use crate::stdlib::_ast::exception::except_handler_from_object_unvalidated_range; use crate::stdlib::_ast::type_parameters::type_params_from_field; -use rustpython_compiler_core::SourceFile; fn runtime_decorator_expr_list(values: &[Option]) -> Vec> { values @@ -27,7 +27,7 @@ fn lower_runtime_decorator_list(values: Vec>) -> Vec PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::FunctionDef(cons) => cons.ast_to_object(vm, source_file), Self::ClassDef(cons) => cons.ast_to_object(vm, source_file), @@ -98,7 +98,7 @@ impl Node for ast::Stmt { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if vm.is_none(&object) { @@ -336,9 +336,9 @@ impl Node for ast::Stmt { // constructor fn stmt_function_def_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, is_async: bool, ) -> PyResult { let typ = if is_async { @@ -367,14 +367,14 @@ fn stmt_function_def_from_object_with_range( runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); let type_params = type_params_from_field(vm, source_file, object, "type_params", typ)?; Ok(ast::StmtFunctionDef { - node_index: Default::default(), + node_index: range.node_index(), name, parameters, body, decorator_list: decorator_list.into(), returns, type_params, - range, + range: range.range, is_async, runtime_decorator_list, runtime_type_comment, @@ -384,9 +384,9 @@ fn stmt_function_def_from_object_with_range( } impl Node for ast::StmtFunctionDef { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, parameters, body, @@ -450,13 +450,13 @@ impl Node for ast::StmtFunctionDef { vm, ) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let is_async = @@ -474,9 +474,9 @@ impl Node for ast::StmtFunctionDef { // constructor fn stmt_class_def_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let name = get_required_identifier_field(vm, source_file, object, "name", "ClassDef")?; let bases = PositionalArguments::ast_from_field(vm, source_file, object, "bases", "ClassDef")?; @@ -493,22 +493,22 @@ fn stmt_class_def_from_object_with_range( let decorator_list = lower_runtime_decorator_list(decorator_list); let type_params = type_params_from_field(vm, source_file, object, "type_params", "ClassDef")?; Ok(ast::StmtClassDef { - node_index: Default::default(), + node_index: range.node_index(), name, arguments: merge_class_def_args(Some(bases), Some(keywords)), body, decorator_list: decorator_list.into(), type_params, - range, + range: range.range, runtime_decorator_list, runtime_body, }) } impl Node for ast::StmtClassDef { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, arguments, body, @@ -568,12 +568,12 @@ impl Node for ast::StmtClassDef { vm, ) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "ClassDef")?; @@ -583,23 +583,23 @@ impl Node for ast::StmtClassDef { // constructor fn stmt_return_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtReturn { - node_index: Default::default(), + node_index: range.node_index(), value: get_node_field_opt(vm, object, "value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::StmtReturn { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, range: _range, } = self; @@ -609,12 +609,12 @@ impl Node for ast::StmtReturn { let dict = node.as_object().dict().unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Return")?; @@ -624,25 +624,25 @@ impl Node for ast::StmtReturn { // constructor fn stmt_delete_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let targets: Vec> = get_node_list_field(vm, source_file, object, "targets", "Delete")?; let (runtime_targets, targets) = runtime_expr_list_from_values(targets); Ok(ast::StmtDelete { - node_index: Default::default(), + node_index: range.node_index(), targets, - range, + range: range.range, runtime_targets, }) } impl Node for ast::StmtDelete { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, targets, range: _range, runtime_targets, @@ -656,12 +656,12 @@ impl Node for ast::StmtDelete { |values| values.ast_to_object(vm, source_file), ); dict.set_item("targets", targets, vm).unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Delete")?; @@ -672,9 +672,9 @@ impl Node for ast::StmtDelete { // constructor fn stmt_assign_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let targets: Vec> = get_node_list_field(vm, source_file, object, "targets", "Assign")?; @@ -683,10 +683,10 @@ fn stmt_assign_from_object_with_range( let (runtime_type_comment, runtime_type_comment_bytes) = runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); Ok(ast::StmtAssign { - node_index: Default::default(), + node_index: range.node_index(), targets, value, - range, + range: range.range, runtime_targets, runtime_type_comment, runtime_type_comment_bytes, @@ -694,9 +694,9 @@ fn stmt_assign_from_object_with_range( } impl Node for ast::StmtAssign { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, targets, value, range, @@ -721,12 +721,12 @@ impl Node for ast::StmtAssign { vm, ) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Assign")?; @@ -737,23 +737,23 @@ impl Node for ast::StmtAssign { // constructor fn stmt_type_alias_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtTypeAlias { - node_index: Default::default(), + node_index: range.node_index(), name: get_required_node_field(vm, source_file, object, "name", "TypeAlias")?, type_params: type_params_from_field(vm, source_file, object, "type_params", "TypeAlias")?, value: get_required_node_field(vm, source_file, object, "value", "TypeAlias")?, - range, + range: range.range, }) } impl Node for ast::StmtTypeAlias { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, type_params, value, @@ -776,13 +776,13 @@ impl Node for ast::StmtTypeAlias { .unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "TypeAlias")?; @@ -793,12 +793,12 @@ impl Node for ast::StmtTypeAlias { // constructor fn stmt_aug_assign_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtAugAssign { - node_index: Default::default(), + node_index: range.node_index(), target: get_required_node_field(vm, source_file, object, "target", "AugAssign")?, op: Node::ast_from_object( vm, @@ -806,14 +806,14 @@ fn stmt_aug_assign_from_object_with_range( get_node_field_required(vm, object, "op", "AugAssign")?, )?, value: get_required_node_field(vm, source_file, object, "value", "AugAssign")?, - range, + range: range.range, }) } impl Node for ast::StmtAugAssign { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, target, op, value, @@ -829,12 +829,12 @@ impl Node for ast::StmtAugAssign { .unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "AugAssign")?; @@ -845,9 +845,9 @@ impl Node for ast::StmtAugAssign { // constructor fn stmt_ann_assign_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let simple_obj = get_node_field(vm, object, "simple", "AnnAssign")?; let simple = node_object_to_i32(vm, &simple_obj)?; @@ -857,22 +857,22 @@ fn stmt_ann_assign_from_object_with_range( None }; Ok(ast::StmtAnnAssign { - node_index: Default::default(), + node_index: range.node_index(), target: get_required_node_field(vm, source_file, object, "target", "AnnAssign")?, annotation: get_required_node_field(vm, source_file, object, "annotation", "AnnAssign")?, value: get_node_field_opt(vm, object, "value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, simple: simple != 0, - range, + range: range.range, runtime_simple, }) } impl Node for ast::StmtAnnAssign { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, target, annotation, value, @@ -895,12 +895,12 @@ impl Node for ast::StmtAnnAssign { |simple| vm.ctx.new_int(simple).into(), ); dict.set_item("simple", simple, vm).unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "AnnAssign")?; @@ -911,9 +911,9 @@ impl Node for ast::StmtAnnAssign { // constructor fn stmt_for_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, is_async: bool, ) -> PyResult { let typ = if is_async { "AsyncFor" } else { "For" }; @@ -929,12 +929,12 @@ fn stmt_for_from_object_with_range( let (runtime_type_comment, runtime_type_comment_bytes) = runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); Ok(ast::StmtFor { - node_index: Default::default(), + node_index: range.node_index(), target, iter, body, orelse, - range, + range: range.range, is_async, runtime_type_comment, runtime_type_comment_bytes, @@ -944,9 +944,9 @@ fn stmt_for_from_object_with_range( } impl Node for ast::StmtFor { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, is_async, target, iter, @@ -987,13 +987,13 @@ impl Node for ast::StmtFor { vm, ) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { debug_assert!( @@ -1010,9 +1010,9 @@ impl Node for ast::StmtFor { // constructor fn stmt_while_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let body: Vec> = get_node_list_field(vm, source_file, object, "body", "While")?; @@ -1021,20 +1021,20 @@ fn stmt_while_from_object_with_range( let runtime_body = runtime_stmt_list_metadata(&body); let runtime_orelse = runtime_stmt_list_metadata(&orelse); Ok(ast::StmtWhile { - node_index: Default::default(), + node_index: range.node_index(), test: get_required_node_field(vm, source_file, object, "test", "While")?, body: lower_runtime_stmt_list(body), orelse: lower_runtime_stmt_list(orelse), - range, + range: range.range, runtime_body, runtime_orelse, }) } impl Node for ast::StmtWhile { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, test, body, orelse, @@ -1058,13 +1058,13 @@ impl Node for ast::StmtWhile { |values| values.ast_to_object(vm, source_file), ); dict.set_item("orelse", orelse, vm).unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "While")?; @@ -1073,7 +1073,7 @@ impl Node for ast::StmtWhile { } // constructor impl Node for ast::StmtIf { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { node_index, test, @@ -1098,7 +1098,7 @@ impl Node for ast::StmtIf { } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "If")?; @@ -1108,9 +1108,9 @@ impl Node for ast::StmtIf { // constructor fn stmt_with_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, is_async: bool, ) -> PyResult { let typ = if is_async { "AsyncWith" } else { "With" }; @@ -1120,10 +1120,10 @@ fn stmt_with_from_object_with_range( let (runtime_type_comment, runtime_type_comment_bytes) = runtime_stmt_type_comment(vm, get_ast_string_field_opt(vm, object, "type_comment")?); Ok(ast::StmtWith { - node_index: Default::default(), + node_index: range.node_index(), items, body, - range, + range: range.range, is_async, runtime_type_comment, runtime_type_comment_bytes, @@ -1132,9 +1132,9 @@ fn stmt_with_from_object_with_range( } impl Node for ast::StmtWith { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, is_async, items, body, @@ -1165,12 +1165,12 @@ impl Node for ast::StmtWith { vm, ) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { debug_assert!( @@ -1186,22 +1186,22 @@ impl Node for ast::StmtWith { // constructor fn stmt_match_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtMatch { - node_index: Default::default(), + node_index: range.node_index(), subject: get_required_node_field(vm, source_file, object, "subject", "Match")?, cases: get_node_list_field(vm, source_file, object, "cases", "Match")?, - range, + range: range.range, }) } impl Node for ast::StmtMatch { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, subject, cases, range: _range, @@ -1214,12 +1214,12 @@ impl Node for ast::StmtMatch { .unwrap(); dict.set_item("cases", cases.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Match")?; @@ -1229,26 +1229,26 @@ impl Node for ast::StmtMatch { // constructor fn stmt_raise_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtRaise { - node_index: Default::default(), + node_index: range.node_index(), exc: get_node_field_opt(vm, object, "exc")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, cause: get_node_field_opt(vm, object, "cause")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::StmtRaise { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, exc, cause, range: _range, @@ -1261,12 +1261,12 @@ impl Node for ast::StmtRaise { .unwrap(); dict.set_item("cause", cause.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Raise")?; @@ -1276,9 +1276,9 @@ impl Node for ast::StmtRaise { // constructor fn stmt_try_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, is_star: bool, ) -> PyResult { let typ = if is_star { "TryStar" } else { "Try" }; @@ -1288,18 +1288,18 @@ fn stmt_try_from_object_with_range( let finalbody: Vec> = get_node_list_field(vm, source_file, object, "finalbody", typ)?; let (runtime_handler_values, handlers) = - except_handler_list_from_field(vm, source_file, object, typ, is_star, range)?; + except_handler_list_from_field(vm, source_file, object, typ, is_star, range.range)?; let runtime_body = runtime_stmt_list_metadata(&body); let runtime_orelse = runtime_stmt_list_metadata(&orelse); let runtime_finalbody = runtime_stmt_list_metadata(&finalbody); let runtime_handlers = runtime_except_handler_list_metadata(&runtime_handler_values); Ok(ast::StmtTry { - node_index: Default::default(), + node_index: range.node_index(), body: lower_runtime_stmt_list(body), handlers, orelse: lower_runtime_stmt_list(orelse), finalbody: lower_runtime_stmt_list(finalbody), - range, + range: range.range, is_star, runtime_body, runtime_handlers, @@ -1310,7 +1310,7 @@ fn stmt_try_from_object_with_range( fn except_handler_list_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, typ: &str, is_try_star: bool, @@ -1365,9 +1365,9 @@ fn except_handler_list_from_field( } impl Node for ast::StmtTry { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, body, handlers, orelse, @@ -1409,12 +1409,12 @@ impl Node for ast::StmtTry { |values| values.ast_to_object(vm, source_file), ); dict.set_item("finalbody", finalbody, vm).unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let is_star = is_node_instance(vm, &_object, pyast::NodeStmtTryStar::static_type())?; @@ -1431,24 +1431,24 @@ impl Node for ast::StmtTry { // constructor fn stmt_assert_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtAssert { - node_index: Default::default(), + node_index: range.node_index(), test: get_required_node_field(vm, source_file, object, "test", "Assert")?, msg: get_node_field_opt(vm, object, "msg")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::StmtAssert { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, test, msg, range: _range, @@ -1461,12 +1461,12 @@ impl Node for ast::StmtAssert { .unwrap(); dict.set_item("msg", msg.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Assert")?; @@ -1476,25 +1476,29 @@ impl Node for ast::StmtAssert { // constructor fn stmt_import_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtImport { - node_index: Default::default(), + node_index: range.node_index(), names: get_node_list_field(vm, source_file, object, "names", "Import")?, - range, - is_lazy: false, + range: range.range, + is_lazy: get_node_field_opt(vm, object, "is_lazy")? + .map(|value| node_object_to_i32(vm, &value)) + .transpose()? + .unwrap_or(0) + != 0, }) } impl Node for ast::StmtImport { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, names, range: _range, - is_lazy: _, + is_lazy, } = self; let node = NodeAst .into_ref_with_type(vm, pyast::NodeStmtImport::static_type().to_owned()) @@ -1502,13 +1506,15 @@ impl Node for ast::StmtImport { let dict = node.as_object().dict().unwrap(); dict.set_item("names", names.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + dict.set_item("is_lazy", vm.ctx.new_int(i32::from(is_lazy)).into(), vm) + .unwrap(); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Import")?; @@ -1518,21 +1524,25 @@ impl Node for ast::StmtImport { // constructor fn stmt_import_from_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let (level, raw_level) = import_from_level_from_field(vm, object)?; let runtime_level = raw_level.filter(|level| *level < 0); Ok(ast::StmtImportFrom { - node_index: Default::default(), + node_index: range.node_index(), module: get_node_field_opt(vm, object, "module")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, names: get_node_list_field(vm, source_file, object, "names", "ImportFrom")?, level, - range, - is_lazy: false, + range: range.range, + is_lazy: get_node_field_opt(vm, object, "is_lazy")? + .map(|value| node_object_to_i32(vm, &value)) + .transpose()? + .unwrap_or(0) + != 0, runtime_level, }) } @@ -1554,14 +1564,14 @@ fn import_from_level_from_field( } impl Node for ast::StmtImportFrom { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, module, names, level, range, - is_lazy: _, + is_lazy, runtime_level, } = self; let node = NodeAst @@ -1577,13 +1587,15 @@ impl Node for ast::StmtImportFrom { |level| vm.ctx.new_int(level).to_pyobject(vm), ); dict.set_item("level", level, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + dict.set_item("is_lazy", vm.ctx.new_int(i32::from(is_lazy)).into(), vm) + .unwrap(); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "ImportFrom")?; @@ -1593,21 +1605,21 @@ impl Node for ast::StmtImportFrom { // constructor fn stmt_global_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtGlobal { - node_index: Default::default(), + node_index: range.node_index(), names: get_node_list_field(vm, source_file, object, "names", "Global")?, - range, + range: range.range, }) } impl Node for ast::StmtGlobal { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, names, range: _range, } = self; @@ -1617,12 +1629,12 @@ impl Node for ast::StmtGlobal { let dict = node.as_object().dict().unwrap(); dict.set_item("names", names.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Global")?; @@ -1632,21 +1644,21 @@ impl Node for ast::StmtGlobal { // constructor fn stmt_nonlocal_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtNonlocal { - node_index: Default::default(), + node_index: range.node_index(), names: get_node_list_field(vm, source_file, object, "names", "Nonlocal")?, - range, + range: range.range, }) } impl Node for ast::StmtNonlocal { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, names, range: _range, } = self; @@ -1656,12 +1668,12 @@ impl Node for ast::StmtNonlocal { let dict = node.as_object().dict().unwrap(); dict.set_item("names", names.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Nonlocal")?; @@ -1671,21 +1683,21 @@ impl Node for ast::StmtNonlocal { // constructor fn stmt_expr_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::StmtExpr { - node_index: Default::default(), + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "Expr")?, - range, + range: range.range, }) } impl Node for ast::StmtExpr { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, value, range: _range, } = self; @@ -1695,12 +1707,12 @@ impl Node for ast::StmtExpr { let dict = node.as_object().dict().unwrap(); dict.set_item("value", value.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Expr")?; @@ -1708,27 +1720,31 @@ impl Node for ast::StmtExpr { } } // constructor -fn stmt_pass_from_object_with_range(range: TextRange) -> ast::StmtPass { +fn stmt_pass_from_object_with_range(range: AstNodeRange) -> ast::StmtPass { ast::StmtPass { - node_index: Default::default(), - range, + node_index: range.node_index(), + range: range.range, } } impl Node for ast::StmtPass { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, range: _range, } = self; let node = NodeAst .into_ref_with_type(vm, pyast::NodeStmtPass::static_type().to_owned()) .unwrap(); let dict = node.as_object().dict().unwrap(); + if source_file.location(node_index.load()).is_some() { + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); + return node.into(); + } let location = super::text_range_to_source_range(source_file, _range); - let start_row = location.start.row.get(); - let start_col = location.start.column.get(); - let mut end_row = location.end.row.get(); + let start_row = location.start.line.get(); + let start_col = location.start.character_offset.to_zero_indexed(); + let mut end_row = location.end.line.get(); // Align with CPython: when docstring optimization replaces a lone // docstring with `pass`, the end position is on the same line even if @@ -1737,7 +1753,7 @@ impl Node for ast::StmtPass { end_row = start_row; start_col + 4 } else { - location.end.column.get() + location.end.character_offset.to_zero_indexed() }; dict.set_item("lineno", vm.ctx.new_int(start_row).into(), vm) @@ -1752,7 +1768,7 @@ impl Node for ast::StmtPass { } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Pass")?; @@ -1760,30 +1776,30 @@ impl Node for ast::StmtPass { } } // constructor -fn stmt_break_from_object_with_range(range: TextRange) -> ast::StmtBreak { +fn stmt_break_from_object_with_range(range: AstNodeRange) -> ast::StmtBreak { ast::StmtBreak { - node_index: Default::default(), - range, + node_index: range.node_index(), + range: range.range, } } impl Node for ast::StmtBreak { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, range: _range, } = self; let node = NodeAst .into_ref_with_type(vm, pyast::NodeStmtBreak::static_type().to_owned()) .unwrap(); let dict = node.as_object().dict().unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Break")?; @@ -1792,29 +1808,29 @@ impl Node for ast::StmtBreak { } // constructor -fn stmt_continue_from_object_with_range(range: TextRange) -> ast::StmtContinue { +fn stmt_continue_from_object_with_range(range: AstNodeRange) -> ast::StmtContinue { ast::StmtContinue { - node_index: Default::default(), - range, + node_index: range.node_index(), + range: range.range, } } impl Node for ast::StmtContinue { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, range: _range, } = self; let node = NodeAst .into_ref_with_type(vm, pyast::NodeStmtContinue::static_type().to_owned()) .unwrap(); let dict = node.as_object().dict().unwrap(); - node_add_location(&dict, _range, vm, source_file); + node_add_location_for_node(&dict, _range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, _object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &_object, "Continue")?; diff --git a/crates/vm/src/stdlib/_ast/string.rs b/crates/vm/src/stdlib/_ast/string.rs index 553b235c46c..c564cc6d8fe 100644 --- a/crates/vm/src/stdlib/_ast/string.rs +++ b/crates/vm/src/stdlib/_ast/string.rs @@ -1,6 +1,5 @@ use super::constant::{Constant, ConstantLiteral}; use super::*; -use crate::warn; use ast::str_prefix::StringLiteralPrefix; use rustpython_common::wtf8::Wtf8Buf; @@ -21,18 +20,20 @@ fn ruff_fstring_element_into_iter( fn push_ruff_fstring_element( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, flags: ast::AnyStringFlags, element: ast::InterpolatedStringElement, output: &mut Vec, ) { match element { ast::InterpolatedStringElement::Literal(literal) => { - output.push(JoinedStrPart::Constant(Constant::new_str( + let mut constant = Constant::new_str( rustpython_codegen::interpolated_string_literal_value(source_file, &literal, flags), ast::str_prefix::StringLiteralPrefix::Empty, literal.range, - ))); + ); + constant.node_index = literal.node_index; + output.push(JoinedStrPart::Constant(constant)); } ast::InterpolatedStringElement::Interpolation(ast::InterpolatedElement { range, @@ -40,7 +41,7 @@ fn push_ruff_fstring_element( debug_text, mut conversion, format_spec, - node_index: _, + node_index, runtime_str: _, runtime_interpolation_format_spec: _, runtime_formatted_value_format_spec, @@ -58,6 +59,7 @@ fn push_ruff_fstring_element( .map(|joined_str| Box::new(joined_str.into_expr(false))) }); output.push(JoinedStrPart::FormattedValue(FormattedValue { + node_index, value: expression, conversion, format_spec: runtime_format_spec, @@ -69,7 +71,7 @@ fn push_ruff_fstring_element( /// The literal an `{expr=}` interpolation puts in front of its value. fn interpolation_debug_constant( - source_file: &SourceFile, + source_file: &AstSourceContext, debug_text: &ast::DebugText, expression_range: TextRange, ) -> Constant { @@ -175,42 +177,41 @@ fn normalize_template_str_parts(values: Vec) -> Vec( source_file: &SourceFile, range: TextRange, -) { + emit_warning: &mut impl FnMut(usize, char) -> Result<(), E>, +) -> Result<(), E> { let source = source_file.source_text(); let start = range.start().to_usize(); let end = range.end().to_usize(); if start >= end || end > source.len() { - return; - } - let mut raw = &source[start..end]; - if raw.starts_with(':') { - raw = &raw[1..]; + return Ok(()); } - - let mut chars = raw.chars().peekable(); - while let Some(ch) = chars.next() { + let Some(raw) = source.get(start..end) else { + return Ok(()); + }; + let mut chars = raw.char_indices().peekable(); + while let Some((offset, ch)) = chars.next() { if ch != '\\' { continue; } - let Some(next) = chars.next() else { + let Some((_, next)) = chars.next() else { break; }; let valid = match next { '\\' | '\'' | '"' | 'a' | 'b' | 'f' | 'n' | 'r' | 't' | 'v' => true, '\n' => true, '\r' => { - if let Some('\n') = chars.peek().copied() { + if let Some((_, '\n')) = chars.peek().copied() { chars.next(); } true } '0'..='7' => { for _ in 0..2 { - if let Some('0'..='7') = chars.peek().copied() { + if let Some((_, '0'..='7')) = chars.peek().copied() { chars.next(); } else { break; @@ -220,7 +221,7 @@ fn warn_invalid_escape_sequences_in_format_spec( } 'x' => { for _ in 0..2 { - if chars.peek().is_some_and(|c| c.is_ascii_hexdigit()) { + if chars.peek().is_some_and(|(_, c)| c.is_ascii_hexdigit()) { chars.next(); } else { break; @@ -230,7 +231,7 @@ fn warn_invalid_escape_sequences_in_format_spec( } 'u' => { for _ in 0..4 { - if chars.peek().is_some_and(|c| c.is_ascii_hexdigit()) { + if chars.peek().is_some_and(|(_, c)| c.is_ascii_hexdigit()) { chars.next(); } else { break; @@ -240,7 +241,7 @@ fn warn_invalid_escape_sequences_in_format_spec( } 'U' => { for _ in 0..8 { - if chars.peek().is_some_and(|c| c.is_ascii_hexdigit()) { + if chars.peek().is_some_and(|(_, c)| c.is_ascii_hexdigit()) { chars.next(); } else { break; @@ -249,9 +250,9 @@ fn warn_invalid_escape_sequences_in_format_spec( true } 'N' => { - if let Some('{') = chars.peek().copied() { + if let Some((_, '{')) = chars.peek().copied() { chars.next(); - for c in chars.by_ref() { + for (_, c) in chars.by_ref() { if c == '}' { break; } @@ -259,26 +260,207 @@ fn warn_invalid_escape_sequences_in_format_spec( } true } + // CPython's string-parser prepass protects a backslash before a + // non-ASCII codepoint before invoking the escape decoder. + ch if !ch.is_ascii() => true, _ => false, }; if !valid { - let message = vm.ctx.new_str(format!( - "\"\\{next}\" is an invalid escape sequence. Such sequences will not work in the future. Did you mean \"\\\\{next}\"? A raw string is also an option." - )); - let _ = warn::warn( - message.into(), - Some(vm.ctx.exceptions.syntax_warning.to_owned()), - 1, - None, - vm, + return emit_warning(start + offset, next); + } + } + Ok(()) +} + +/// Keep AST parsing's existing format-spec diagnostics at a fallible boundary, +/// rather than emitting warnings from the infallible Python AST conversion. +#[cfg(feature = "parser")] +pub(super) fn emit_format_spec_warnings( + statements: &[ast::Stmt], + expressions: &[ast::Expr], + source_file: &SourceFile, + emit_warning: &mut impl FnMut(usize, char) -> Result<(), E>, +) -> Result<(), E> { + use ast::visitor::{self, Visitor}; + use std::collections::HashSet; + + struct LiteralVisitor<'a, F, E> { + source_file: &'a SourceFile, + emit_warning: F, + emitted: HashSet, + error: Option, + } + + impl LiteralVisitor<'_, F, E> + where + F: FnMut(usize, char) -> Result<(), E>, + { + fn check_literal(&mut self, mut range: TextRange, interpolated: bool) { + if self.error.is_some() { + return; + } + // Ruff leaves the interpolation delimiter outside the literal range. + // Include it so a trailing backslash can still diagnose \{ or \}. + if interpolated + && self + .source_file + .source_text() + .as_bytes() + .get(range.end().to_usize()) + .is_some_and(|byte| matches!(byte, b'{' | b'}')) + { + range = TextRange::new(range.start(), range.end() + TextSize::from(1)); + } + let result = warn_invalid_escape_sequences_in_format_spec( + self.source_file, + range, + &mut |offset, ch| { + if !self.emitted.contains(&offset) { + (self.emit_warning)(offset, ch)?; + self.emitted.insert(offset); + } + Ok(()) + }, ); + if let Err(error) = result { + self.error = Some(error); + } + } + + fn visit_elements<'a>(&mut self, elements: &'a ast::InterpolatedStringElements, raw: bool) + where + Self: Visitor<'a>, + { + for element in elements { + match element { + ast::InterpolatedStringElement::Literal(literal) => { + if !raw { + self.check_literal(literal.range, true); + } + } + ast::InterpolatedStringElement::Interpolation(interpolation) => { + self.visit_expr(&interpolation.expression); + if let Some(spec) = &interpolation.format_spec { + self.visit_elements(&spec.elements, raw); + } + } + } + } + } + } + + // Visit only literal spans within an existing format-spec warning region. + // An enclosing spec can include nested raw strings, nonraw expressions in a + // raw f-string, and comments; scanning its entire source range conflates them. + impl<'a, F, E> Visitor<'a> for LiteralVisitor<'_, F, E> + where + F: FnMut(usize, char) -> Result<(), E>, + { + fn visit_expr(&mut self, expr: &'a ast::Expr) { + if self.error.is_none() { + visitor::walk_expr(self, expr); + } + } + + fn visit_string_literal(&mut self, literal: &'a ast::StringLiteral) { + if !matches!( + literal.flags.prefix(), + ast::str_prefix::StringLiteralPrefix::Raw { .. } + ) { + self.check_literal(literal.range, false); + } + } + + fn visit_bytes_literal(&mut self, literal: &'a ast::BytesLiteral) { + if !literal.flags.prefix().is_raw() { + self.check_literal(literal.range, false); + } + } + + fn visit_f_string(&mut self, fstring: &'a ast::FString) { + self.visit_elements(&fstring.elements, fstring.flags.prefix().is_raw()); + } + + fn visit_t_string(&mut self, tstring: &'a ast::TString) { + self.visit_elements(&tstring.elements, tstring.flags.prefix().is_raw()); + } + } + + struct FormatSpecVisitor<'a, F, E> { + literals: LiteralVisitor<'a, F, E>, + } + + impl<'a, F, E> Visitor<'a> for FormatSpecVisitor<'_, F, E> + where + F: FnMut(usize, char) -> Result<(), E>, + { + fn visit_expr(&mut self, expr: &'a ast::Expr) { + if self.literals.error.is_some() { + return; + } + if let ast::Expr::FString(fstring) = expr { + // Conversion checked all enclosing specs before converting their + // expressions, including across concatenated f-string parts. + for part in &fstring.value { + if let ast::FStringPartRef::FString(part) = part { + self.visit_format_specs(&part.elements, part.flags.prefix().is_raw()); + } + } + } + visitor::walk_expr(self, expr); + } + + fn visit_t_string(&mut self, tstring: &'a ast::TString) { + let raw = tstring.flags.prefix().is_raw(); + for element in &tstring.elements { + if let ast::InterpolatedStringElement::Interpolation(interpolation) = element { + self.visit_expr(&interpolation.expression); + if let Some(spec) = &interpolation.format_spec { + // Template specs become JoinedStr nodes during conversion; + // their nested format specs already emitted warnings too. + self.visit_format_specs(&spec.elements, raw); + for element in &spec.elements { + self.visit_interpolated_string_element(element); + } + } + } + } + } + } + + impl FormatSpecVisitor<'_, F, E> + where + F: FnMut(usize, char) -> Result<(), E>, + { + fn visit_format_specs(&mut self, elements: &ast::InterpolatedStringElements, raw: bool) { + for element in elements { + if let ast::InterpolatedStringElement::Interpolation(interpolation) = element + && let Some(spec) = &interpolation.format_spec + { + self.literals.visit_elements(&spec.elements, raw); + } + } } } + + let mut visitor = FormatSpecVisitor { + literals: LiteralVisitor { + source_file, + emit_warning, + emitted: HashSet::new(), + error: None, + }, + }; + visitor.visit_body(statements); + for expr in expressions { + visitor.visit_expr(expr); + } + visitor.literals.error.map_or(Ok(()), Err) } fn ruff_format_spec_to_joined_str( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, flags: ast::AnyStringFlags, format_spec: Option>, ) -> Option> { @@ -288,7 +470,7 @@ fn ruff_format_spec_to_joined_str( let ast::InterpolatedStringFormatSpec { range, elements, - node_index: _, + node_index, } = *format_spec; // The `:` that opens a format spec belongs to its range, and the // parser leaves it out of the outermost one. @@ -298,7 +480,7 @@ fn ruff_format_spec_to_joined_str( .get(..range.start().to_usize()) .and_then(<[u8]>::last) == Some(&b':'); - let range = if opened_by_colon { + let range = if opened_by_colon && source_file.location(node_index.load()).is_none() { TextRange::new( range.start() - ruff_text_size::TextSize::from(1), range.end(), @@ -310,8 +492,14 @@ fn ruff_format_spec_to_joined_str( for element in ruff_fstring_element_into_iter(elements) { push_ruff_fstring_element(vm, source_file, flags, element, &mut values); } - let values = normalize_joined_str_parts(values).into_boxed_slice(); + let values = if source_file.has_locations() { + values + } else { + normalize_joined_str_parts(values) + } + .into_boxed_slice(); Some(Box::new(JoinedStr { + node_index, range, values, runtime_values: None, @@ -320,6 +508,35 @@ fn ruff_format_spec_to_joined_str( } } +fn dummy_string_literal() -> ast::StringLiteral { + ast::StringLiteral { + node_index: Default::default(), + range: Default::default(), + value: "".into(), + flags: ast::StringLiteralFlags::empty(), + } +} + +fn dummy_fstring() -> ast::FString { + ast::FString { + node_index: Default::default(), + range: Default::default(), + elements: Default::default(), + flags: ast::FStringFlags::empty(), + } +} + +fn take_fstring_part(part: ast::FStringPartMut<'_>) -> ast::FStringPart { + match part { + ast::FStringPartMut::Literal(literal) => { + ast::FStringPart::Literal(core::mem::replace(literal, dummy_string_literal())) + } + ast::FStringPartMut::FString(fstring) => { + ast::FStringPart::FString(core::mem::replace(fstring, dummy_fstring())) + } + } +} + fn ruff_fstring_element_to_ruff_fstring_part( element: ast::InterpolatedStringElement, ) -> ast::FStringPart { @@ -338,9 +555,11 @@ fn ruff_fstring_element_to_ruff_fstring_part( }) } ast::InterpolatedStringElement::Interpolation(ast::InterpolatedElement { - range, .. + range, + ref node_index, + .. }) => ast::FStringPart::FString(ast::FString { - node_index: Default::default(), + node_index: node_index.clone(), range, elements: vec![element].into(), flags: ast::FStringFlags::empty(), @@ -358,28 +577,21 @@ fn format_spec_expr_to_ruff_format_spec( let ast::ExprFString { range, ref mut value, - node_index: _, + node_index, runtime_joined_str: _, runtime_values: _, } = fstring; - let default_part = ast::FStringPart::FString(ast::FString { - node_index: Default::default(), - range: Default::default(), - elements: Default::default(), - flags: ast::FStringFlags::empty(), - }); let mut elements = Vec::new(); - for i in 0..value.as_slice().len() { - let part = core::mem::replace(value.iter_mut().nth(i).unwrap(), default_part.clone()); - match part { + for part in value { + match take_fstring_part(part) { ast::FStringPart::Literal(ast::StringLiteral { range, value, - node_index: _, + node_index, flags: _, }) => elements.push(ast::InterpolatedStringElement::Literal( ast::InterpolatedStringLiteralElement { - node_index: Default::default(), + node_index, range, value, }, @@ -393,7 +605,7 @@ fn format_spec_expr_to_ruff_format_spec( } } Some(Box::new(ast::InterpolatedStringFormatSpec { - node_index: Default::default(), + node_index, range, elements: elements.into(), })) @@ -401,6 +613,7 @@ fn format_spec_expr_to_ruff_format_spec( #[derive(Debug)] pub(super) struct JoinedStr { + node_index: ast::AtomicNodeIndex, pub(super) range: TextRange, pub(super) values: Box<[JoinedStrPart]>, pub(super) runtime_values: Option>>, @@ -409,6 +622,7 @@ pub(super) struct JoinedStr { impl JoinedStr { pub(super) fn into_expr(self, from_ast_object: bool) -> ast::Expr { let Self { + node_index, range, values, runtime_values: mut raw_runtime_values, @@ -437,11 +651,11 @@ impl JoinedStr { } }); ast::Expr::FString(ast::ExprFString { - node_index: Default::default(), + node_index: node_index.clone(), range, value: match values.len() { 0 => ast::FStringValue::single(ast::FString { - node_index: Default::default(), + node_index, range, elements: vec![].into(), flags: ast::FStringFlags::empty(), @@ -451,7 +665,7 @@ impl JoinedStr { .map(|part| joined_str_part_to_ruff_fstring_element(from_ast_object, part)) .map(Option::unwrap) .map(|element| ast::FString { - node_index: Default::default(), + node_index: node_index.clone(), range, elements: vec![element].into(), flags: ast::FStringFlags::empty(), @@ -502,7 +716,7 @@ fn joined_str_part_to_ruff_fstring_element( .flatten(); Some(ast::InterpolatedStringElement::Interpolation( ast::InterpolatedElement { - node_index: Default::default(), + node_index: value.node_index.clone(), range: value.range, expression: value.value.clone(), debug_text: None, @@ -515,13 +729,18 @@ fn joined_str_part_to_ruff_fstring_element( )) } JoinedStrPart::Constant(value) => { - let Constant { range, value, .. } = value; + let Constant { + node_index, + range, + value, + .. + } = value; let ConstantLiteral::Str { value, .. } = value else { return None; }; Some(ast::InterpolatedStringElement::Literal( ast::InterpolatedStringLiteralElement { - node_index: Default::default(), + node_index, range, value: value.to_string_lossy().into(), }, @@ -533,22 +752,24 @@ fn joined_str_part_to_ruff_fstring_element( // constructor pub(super) fn joined_str_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let values: Vec> = get_node_list_field(vm, source_file, object, "values", "JoinedStr")?; Ok(JoinedStr { + node_index: range.node_index(), values: Vec::new().into_boxed_slice(), runtime_values: Some(values), - range, + range: range.range, }) } impl Node for JoinedStr { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { + node_index, values, runtime_values, range, @@ -563,12 +784,12 @@ impl Node for JoinedStr { BoxedSlice(values).ast_to_object(vm, source_file) }; dict.set_item("values", values, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "JoinedStr")?; @@ -584,7 +805,7 @@ pub(super) enum JoinedStrPart { // constructor impl Node for JoinedStrPart { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::FormattedValue(value) => value.ast_to_object(vm, source_file), Self::Constant(value) => value.ast_to_object(vm, source_file), @@ -592,7 +813,7 @@ impl Node for JoinedStrPart { } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if is_node_instance(vm, &object, pyast::NodeExprFormattedValue::static_type())? { @@ -613,6 +834,7 @@ impl Node for JoinedStrPart { #[derive(Debug)] pub(super) struct FormattedValue { + node_index: ast::AtomicNodeIndex, value: Box, conversion: ast::ConversionFlag, format_spec: Option>, @@ -622,11 +844,12 @@ pub(super) struct FormattedValue { // constructor pub(super) fn formatted_value_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(FormattedValue { + node_index: range.node_index(), value: get_required_node_field(vm, source_file, object, "value", "FormattedValue")?, conversion: Node::ast_from_object( vm, @@ -636,13 +859,14 @@ pub(super) fn formatted_value_from_object_with_range( format_spec: get_node_field_opt(vm, object, "format_spec")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for FormattedValue { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { + node_index, value, conversion, format_spec, @@ -662,12 +886,12 @@ impl Node for FormattedValue { vm, ) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "FormattedValue")?; @@ -680,7 +904,9 @@ pub(super) fn formatted_value_to_expr( formatted: FormattedValue, ) -> ast::Expr { let range = formatted.range; + let node_index = formatted.node_index.clone(); JoinedStr { + node_index, range, values: vec![JoinedStrPart::FormattedValue(formatted)].into_boxed_slice(), runtime_values: None, @@ -690,18 +916,19 @@ pub(super) fn formatted_value_to_expr( pub(super) fn fstring_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, expression: ast::ExprFString, ) -> PyObjectRef { let ast::ExprFString { range, mut value, - node_index: _, + node_index, runtime_joined_str, runtime_values, } = expression; if let Some(joined_str) = runtime_joined_str { return JoinedStr { + node_index, range, values: Vec::new().into_boxed_slice(), runtime_values: Some(joined_str.into_iter().map(Some).collect()), @@ -711,6 +938,7 @@ pub(super) fn fstring_to_object( if let Some(values) = runtime_values { return JoinedStr { + node_index, range, values: Vec::new().into_boxed_slice(), runtime_values: Some(values), @@ -718,22 +946,17 @@ pub(super) fn fstring_to_object( .ast_to_object(vm, source_file); } - let default_part = ast::FStringPart::FString(ast::FString { - node_index: Default::default(), - range: Default::default(), - elements: Default::default(), - flags: ast::FStringFlags::empty(), - }); let mut values = Vec::new(); - for i in 0..value.as_slice().len() { - let part = core::mem::replace(value.iter_mut().nth(i).unwrap(), default_part.clone()); - match part { + for part in &mut value { + match take_fstring_part(part) { ast::FStringPart::Literal(literal) => { - values.push(JoinedStrPart::Constant(Constant::new_str( + let mut constant = Constant::new_str( rustpython_codegen::string_literal_part_value(source_file, &literal), literal.flags.prefix(), literal.range, - ))); + ); + constant.node_index = literal.node_index; + values.push(JoinedStrPart::Constant(constant)); } ast::FStringPart::FString(ast::FString { range: _, @@ -747,15 +970,13 @@ pub(super) fn fstring_to_object( } } } - let values = normalize_joined_str_parts(values); - for part in &values { - if let JoinedStrPart::FormattedValue(value) = part - && let Some(format_spec) = &value.format_spec - { - warn_invalid_escape_sequences_in_format_spec(vm, source_file, format_spec.range()); - } - } + let values = if source_file.has_locations() { + values + } else { + normalize_joined_str_parts(values) + }; let c = JoinedStr { + node_index, range, values: values.into_boxed_slice(), runtime_values: None, @@ -767,57 +988,56 @@ pub(super) fn fstring_to_object( fn push_ruff_tstring_element( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, flags: ast::AnyStringFlags, element: ast::InterpolatedStringElement, output: &mut Vec, ) { match element { ast::InterpolatedStringElement::Literal(literal) => { - output.push(TemplateStrPart::Constant(Constant::new_str( + let mut constant = Constant::new_str( rustpython_codegen::interpolated_string_literal_value(source_file, &literal, flags), ast::str_prefix::StringLiteralPrefix::Empty, literal.range, - ))); + ); + constant.node_index = literal.node_index; + output.push(TemplateStrPart::Constant(constant)); } - ast::InterpolatedStringElement::Interpolation(ast::InterpolatedElement { - range, - expression, - debug_text, - mut conversion, - format_spec, - node_index: _, - runtime_str, - runtime_interpolation_format_spec, - runtime_formatted_value_format_spec: _, - }) => { - let expr_range = - extend_expr_range_with_wrapping_parens(source_file, range, expression.range()) - .unwrap_or_else(|| expression.range()); - let expr_str = if let Some(debug_text) = &debug_text { + ast::InterpolatedStringElement::Interpolation(interpolation) => { + let expr_str = + rustpython_codegen::interpolation_expression_text(source_file, &interpolation) + .unwrap_or_else(|| { + source_file + .source_text() + .slice(interpolation.expression.range()) + .to_owned() + }); + let ast::InterpolatedElement { + range, + expression, + debug_text, + mut conversion, + format_spec, + node_index, + runtime_str, + runtime_interpolation_format_spec, + .. + } = interpolation; + if let Some(debug_text) = &debug_text { output.push(TemplateStrPart::Constant(interpolation_debug_constant( source_file, debug_text, expression.range(), ))); conversion = debug_conversion(conversion, format_spec.is_some()); - let expr_source = source_file.source_text().slice(expr_range); - let mut expr_with_debug = String::with_capacity( - debug_text.leading().len() + expr_source.len() + debug_text.trailing().len(), - ); - expr_with_debug.push_str(debug_text.leading()); - expr_with_debug.push_str(expr_source); - expr_with_debug.push_str(debug_text.trailing()); - strip_interpolation_expr(&expr_with_debug) - } else { - tstring_interpolation_expr_str(source_file, range, expr_range) - }; + } let runtime_interpolation = super::constant::runtime_interpolation_object( vm, runtime_str, runtime_interpolation_format_spec, ); output.push(TemplateStrPart::Interpolation(TStringInterpolation { + node_index, value: expression, str: runtime_interpolation .as_ref() @@ -835,87 +1055,9 @@ fn push_ruff_tstring_element( } } -fn tstring_interpolation_expr_str( - source_file: &SourceFile, - interpolation_range: TextRange, - expr_range: TextRange, -) -> String { - let expr_range = - extend_expr_range_with_wrapping_parens(source_file, interpolation_range, expr_range) - .unwrap_or(expr_range); - let start = interpolation_range.start() + TextSize::from(1); - let start = if start > expr_range.end() { - expr_range.start() - } else { - start - }; - let expr_source = source_file - .source_text() - .slice(TextRange::new(start, expr_range.end())); - strip_interpolation_expr(expr_source) -} - -fn extend_expr_range_with_wrapping_parens( - source_file: &SourceFile, - interpolation_range: TextRange, - expr_range: TextRange, -) -> Option { - let left_slice = source_file.source_text().slice(TextRange::new( - interpolation_range.start(), - expr_range.start(), - )); - let mut left_char: Option<(usize, char)> = None; - for (idx, ch) in left_slice - .char_indices() - .collect::>() - .into_iter() - .rev() - { - if !ch.is_whitespace() { - left_char = Some((idx, ch)); - break; - } - } - let (left_idx, left_ch) = left_char?; - if left_ch != '(' { - return None; - } - - let right_slice = source_file - .source_text() - .slice(TextRange::new(expr_range.end(), interpolation_range.end())); - let mut right_char: Option<(usize, char)> = None; - for (idx, ch) in right_slice.char_indices() { - if !ch.is_whitespace() { - right_char = Some((idx, ch)); - break; - } - } - let (right_idx, right_ch) = right_char?; - if right_ch != ')' { - return None; - } - - let left_pos = interpolation_range.start() + TextSize::from(left_idx as u32); - let right_pos = expr_range.end() + TextSize::from(right_idx as u32); - Some(TextRange::new(left_pos, right_pos + TextSize::from(1))) -} - -fn strip_interpolation_expr(expr_source: &str) -> String { - let mut end = expr_source.len(); - for (idx, ch) in expr_source.char_indices().rev() { - if ch.is_whitespace() || ch == '=' { - end = idx; - continue; - } - end = idx + ch.len_utf8(); - break; - } - expr_source[..end].to_owned() -} - #[derive(Debug)] pub(super) struct TemplateStr { + node_index: ast::AtomicNodeIndex, pub(super) range: TextRange, pub(super) values: Box<[TemplateStrPart]>, pub(super) runtime_values: Option>>, @@ -923,18 +1065,18 @@ pub(super) struct TemplateStr { pub(super) fn template_str_to_expr( vm: &VirtualMachine, - source_file: &SourceFile, template: TemplateStr, ) -> PyResult { let TemplateStr { + node_index, range, values, runtime_values: raw_runtime_values, } = template; - let elements = template_parts_to_elements(vm, source_file, values)?; + let elements = template_parts_to_elements(vm, values)?; let tstring = ast::TString { range, - node_index: Default::default(), + node_index: node_index.clone(), elements, flags: ast::TStringFlags::empty(), }; @@ -947,7 +1089,7 @@ pub(super) fn template_str_to_expr( } }); Ok(ast::Expr::TString(ast::ExprTString { - node_index: Default::default(), + node_index, range, value: ast::TStringValue::single(tstring), runtime_template_str, @@ -957,20 +1099,20 @@ pub(super) fn template_str_to_expr( pub(super) fn interpolation_to_expr( vm: &VirtualMachine, - source_file: &SourceFile, interpolation: TStringInterpolation, ) -> PyResult { let range = interpolation.range; + let node_index = interpolation.node_index.clone(); let part = TemplateStrPart::Interpolation(interpolation); - let elements = template_parts_to_elements(vm, source_file, vec![part].into_boxed_slice())?; + let elements = template_parts_to_elements(vm, vec![part].into_boxed_slice())?; let tstring = ast::TString { range, - node_index: Default::default(), + node_index: node_index.clone(), elements, flags: ast::TStringFlags::empty(), }; Ok(ast::Expr::TString(ast::ExprTString { - node_index: Default::default(), + node_index, range, value: ast::TStringValue::single(tstring), runtime_template_str: None, @@ -980,19 +1122,17 @@ pub(super) fn interpolation_to_expr( fn template_parts_to_elements( vm: &VirtualMachine, - source_file: &SourceFile, values: Box<[TemplateStrPart]>, ) -> PyResult { let mut elements = Vec::with_capacity(values.len()); for value in values.into_vec() { - elements.push(template_part_to_element(vm, source_file, value)?); + elements.push(template_part_to_element(vm, value)?); } Ok(ast::InterpolatedStringElements::from(elements)) } fn template_part_to_element( vm: &VirtualMachine, - source_file: &SourceFile, part: TemplateStrPart, ) -> PyResult { match part { @@ -1003,21 +1143,21 @@ fn template_part_to_element( Ok(ast::InterpolatedStringElement::Literal( ast::InterpolatedStringLiteralElement { range: constant.range, - node_index: Default::default(), + node_index: constant.node_index, value: value.to_string_lossy().into(), }, )) } TemplateStrPart::Interpolation(interpolation) => { let TStringInterpolation { + node_index, value, str, conversion, format_spec, range, } = interpolation; - let str_constant = - super::constant::constant_object_to_constant_data(vm, source_file, str)?; + let str_constant = super::constant::constant_object_to_constant_data(vm, str)?; let runtime_str = Some(super::constant::constant_data_to_ast_constant_value( str_constant, )); @@ -1026,7 +1166,7 @@ fn template_part_to_element( Ok(ast::InterpolatedStringElement::Interpolation( ast::InterpolatedElement { range, - node_index: Default::default(), + node_index, expression: value, debug_text: None, conversion, @@ -1043,22 +1183,24 @@ fn template_part_to_element( // constructor pub(super) fn template_str_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let values: Vec> = get_node_list_field(vm, source_file, object, "values", "TemplateStr")?; Ok(TemplateStr { + node_index: range.node_index(), values: Vec::new().into_boxed_slice(), runtime_values: Some(values), - range, + range: range.range, }) } impl Node for TemplateStr { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { + node_index, values, runtime_values, range, @@ -1073,12 +1215,12 @@ impl Node for TemplateStr { BoxedSlice(values).ast_to_object(vm, source_file) }; dict.set_item("values", values, vm).unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "TemplateStr")?; @@ -1094,7 +1236,7 @@ pub(super) enum TemplateStrPart { // constructor impl Node for TemplateStrPart { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::Interpolation(value) => value.ast_to_object(vm, source_file), Self::Constant(value) => value.ast_to_object(vm, source_file), @@ -1102,7 +1244,7 @@ impl Node for TemplateStrPart { } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if is_node_instance(vm, &object, pyast::NodeExprInterpolation::static_type())? { @@ -1123,6 +1265,7 @@ impl Node for TemplateStrPart { #[derive(Debug)] pub(super) struct TStringInterpolation { + node_index: ast::AtomicNodeIndex, value: Box, str: PyObjectRef, conversion: ast::ConversionFlag, @@ -1133,9 +1276,9 @@ pub(super) struct TStringInterpolation { // constructor pub(super) fn tstring_interpolation_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { let value = get_required_node_field(vm, source_file, object, "value", "Interpolation")?; let str = get_node_field(vm, object, "str", "Interpolation")?; @@ -1148,17 +1291,19 @@ pub(super) fn tstring_interpolation_from_object_with_range( .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?; Ok(TStringInterpolation { + node_index: range.node_index(), value, str, conversion, format_spec, - range, + range: range.range, }) } impl Node for TStringInterpolation { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { + node_index, value, str, conversion, @@ -1180,12 +1325,12 @@ impl Node for TStringInterpolation { vm, ) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = range_from_object(vm, source_file, &object, "Interpolation")?; @@ -1195,18 +1340,19 @@ impl Node for TStringInterpolation { pub(super) fn tstring_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, expression: ast::ExprTString, ) -> PyObjectRef { let ast::ExprTString { range, mut value, - node_index: _, + node_index, runtime_template_str, runtime_values, } = expression; if let Some(template_str) = runtime_template_str { return TemplateStr { + node_index, range, values: Vec::new().into_boxed_slice(), runtime_values: Some(template_str.into_iter().map(Some).collect()), @@ -1216,6 +1362,7 @@ pub(super) fn tstring_to_object( if let Some(values) = runtime_values { return TemplateStr { + node_index, range, values: Vec::new().into_boxed_slice(), runtime_values: Some(values), @@ -1252,8 +1399,13 @@ pub(super) fn tstring_to_object( push_ruff_tstring_element(vm, source_file, flags, element, &mut values); } } - let values = normalize_template_str_parts(values); + let values = if source_file.has_locations() { + values + } else { + normalize_template_str_parts(values) + }; let c = TemplateStr { + node_index, range, values: values.into_boxed_slice(), runtime_values: None, @@ -1263,7 +1415,7 @@ pub(super) fn tstring_to_object( fn standalone_tstring_interpolation_to_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, value: &ast::TStringValue, str: PyObjectRef, format_spec: Option>, @@ -1279,6 +1431,7 @@ fn standalone_tstring_interpolation_to_object( return None; } let interpolation = TStringInterpolation { + node_index: interp.node_index.clone(), value: interp.expression.clone(), str, conversion: interp.conversion, diff --git a/crates/vm/src/stdlib/_ast/type_ignore.rs b/crates/vm/src/stdlib/_ast/type_ignore.rs index d51e54f1c5d..ffc69ff856b 100644 --- a/crates/vm/src/stdlib/_ast/type_ignore.rs +++ b/crates/vm/src/stdlib/_ast/type_ignore.rs @@ -1,5 +1,5 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; pub(super) enum TypeIgnore { None, @@ -8,7 +8,7 @@ pub(super) enum TypeIgnore { // sum impl Node for TypeIgnore { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::None => vm.ctx.none(), Self::TypeIgnore(cons) => cons.ast_to_object(vm, source_file), @@ -16,7 +16,7 @@ impl Node for TypeIgnore { } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(if vm.is_none(&object) { @@ -43,7 +43,7 @@ pub(super) struct TypeIgnoreTypeIgnore { // constructor impl Node for TypeIgnoreTypeIgnore { - fn ast_to_object(self, vm: &VirtualMachine, _source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, _source_file: &AstSourceContext) -> PyObjectRef { let Self { lineno, tag } = self; let node = NodeAst .into_ref_with_type( @@ -60,7 +60,7 @@ impl Node for TypeIgnoreTypeIgnore { fn ast_from_object( vm: &VirtualMachine, - _source_file: &SourceFile, + _source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(Self { diff --git a/crates/vm/src/stdlib/_ast/type_parameters.rs b/crates/vm/src/stdlib/_ast/type_parameters.rs index a15e564e53d..dfc321aba0b 100644 --- a/crates/vm/src/stdlib/_ast/type_parameters.rs +++ b/crates/vm/src/stdlib/_ast/type_parameters.rs @@ -1,8 +1,8 @@ +use super::AstSourceContext; use super::*; -use rustpython_compiler_core::SourceFile; impl Node for ast::TypeParams { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { self.runtime_type_params.map_or_else( || self.type_params.ast_to_object(vm, source_file), |values| values.ast_to_object(vm, source_file), @@ -11,7 +11,7 @@ impl Node for ast::TypeParams { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { Ok(type_params_from_values( @@ -27,7 +27,7 @@ impl Node for ast::TypeParams { pub(super) fn type_params_from_field( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, field: &'static str, typ: &str, @@ -45,8 +45,7 @@ fn type_params_from_values( let runtime_type_params = values.iter().any(Option::is_none).then(|| values.clone()); let type_params = lower_nullable_type_params(&values); let range = Option::zip(type_params.first(), type_params.last()) - .map(|(first, last)| first.range().cover(last.range())) - .unwrap_or_default(); + .map_or_default(|(first, last)| first.range().cover(last.range())); ast::TypeParams { node_index: Default::default(), type_params, @@ -61,7 +60,7 @@ fn lower_nullable_type_params(values: &[Option]) -> Vec PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { match self { Self::TypeVar(cons) => cons.ast_to_object(vm, source_file), Self::ParamSpec(cons) => cons.ast_to_object(vm, source_file), @@ -71,7 +70,7 @@ impl Node for ast::TypeParam { fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { if vm.is_none(&object) { @@ -121,12 +120,12 @@ impl Node for ast::TypeParam { // constructor fn type_var_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::TypeParamTypeVar { - node_index: Default::default(), + node_index: range.node_index(), name: get_required_identifier_field(vm, source_file, object, "name", "TypeVar")?, bound: get_node_field_opt(vm, object, "bound")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) @@ -134,14 +133,14 @@ fn type_var_from_object_with_range( default: get_node_field_opt(vm, object, "default_value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::TypeParamTypeVar { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, bound, range, @@ -157,13 +156,13 @@ impl Node for ast::TypeParamTypeVar { .unwrap(); dict.set_item("default_value", default.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = type_param_range_from_object(vm, source_file, &object)?; @@ -174,24 +173,24 @@ impl Node for ast::TypeParamTypeVar { // constructor fn param_spec_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::TypeParamParamSpec { - node_index: Default::default(), + node_index: range.node_index(), name: get_required_identifier_field(vm, source_file, object, "name", "ParamSpec")?, default: get_node_field_opt(vm, object, "default_value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::TypeParamParamSpec { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, range, default, @@ -204,13 +203,13 @@ impl Node for ast::TypeParamParamSpec { .unwrap(); dict.set_item("default_value", default.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = type_param_range_from_object(vm, source_file, &object)?; @@ -221,24 +220,24 @@ impl Node for ast::TypeParamParamSpec { // constructor fn type_var_tuple_from_object_with_range( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: &PyObject, - range: TextRange, + range: AstNodeRange, ) -> PyResult { Ok(ast::TypeParamTypeVarTuple { - node_index: Default::default(), + node_index: range.node_index(), name: get_required_identifier_field(vm, source_file, object, "name", "TypeVarTuple")?, default: get_node_field_opt(vm, object, "default_value")? .map(|obj| Node::ast_from_object(vm, source_file, obj)) .transpose()?, - range, + range: range.range, }) } impl Node for ast::TypeParamTypeVarTuple { - fn ast_to_object(self, vm: &VirtualMachine, source_file: &SourceFile) -> PyObjectRef { + fn ast_to_object(self, vm: &VirtualMachine, source_file: &AstSourceContext) -> PyObjectRef { let Self { - node_index: _, + node_index, name, range, default, @@ -254,13 +253,13 @@ impl Node for ast::TypeParamTypeVarTuple { .unwrap(); dict.set_item("default_value", default.ast_to_object(vm, source_file), vm) .unwrap(); - node_add_location(&dict, range, vm, source_file); + node_add_location_for_node(&dict, range, vm, source_file, node_index.load()); node.into() } fn ast_from_object( vm: &VirtualMachine, - source_file: &SourceFile, + source_file: &AstSourceContext, object: PyObjectRef, ) -> PyResult { let range = type_param_range_from_object(vm, source_file, &object)?; diff --git a/crates/vm/src/stdlib/_ast/validate.rs b/crates/vm/src/stdlib/_ast/validate.rs index cbdc15b53a4..cda5ccb2660 100644 --- a/crates/vm/src/stdlib/_ast/validate.rs +++ b/crates/vm/src/stdlib/_ast/validate.rs @@ -118,6 +118,21 @@ fn validate_nonempty_seq( Ok(()) } +fn validate_import_names( + vm: &VirtualMachine, + names: &[ast::Alias], + owner: &'static str, +) -> PyResult<()> { + validate_nonempty_seq(vm, names.len(), "names", owner)?; + for alias in names { + validate_name(vm, alias.name.id())?; + if let Some(asname) = &alias.asname { + validate_name(vm, asname.id())?; + } + } + Ok(()) +} + fn validate_assignlist( vm: &VirtualMachine, targets: &[ast::Expr], @@ -176,6 +191,13 @@ fn validate_interpolated_elements<'a>( } fn ensure_literal_number(expr: &ast::Expr, allow_real: bool, allow_imaginary: bool) -> bool { + if let Some(constant) = ast_constant_value(expr) { + return match constant { + ConstantData::Integer { .. } | ConstantData::Float { .. } => allow_real, + ConstantData::Complex { .. } => allow_imaginary, + _ => false, + }; + } let ast::Expr::NumberLiteral(number) = expr else { return false; }; @@ -185,11 +207,11 @@ fn ensure_literal_number(expr: &ast::Expr, allow_real: bool, allow_imaginary: bo } } -fn ensure_literal_negative(expr: &ast::Expr, allow_real: bool, allow_imaginary: bool) -> bool { +fn ensure_literal_signed(expr: &ast::Expr, allow_real: bool, allow_imaginary: bool) -> bool { let ast::Expr::UnaryOp(unary) = expr else { return false; }; - if unary.op != ast::UnaryOp::USub { + if !matches!(unary.op, ast::UnaryOp::UAdd | ast::UnaryOp::USub) { return false; } ensure_literal_number(&unary.operand, allow_real, allow_imaginary) @@ -203,7 +225,7 @@ fn ensure_literal_complex(expr: &ast::Expr) -> bool { return false; } let real_left = ensure_literal_number(&bin.left, true, false) - || ensure_literal_negative(&bin.left, true, false); + || ensure_literal_signed(&bin.left, true, false); real_left && ensure_literal_number(&bin.right, false, true) } @@ -229,7 +251,7 @@ fn validate_pattern_match_value(vm: &VirtualMachine, expr: &ast::Expr) -> PyResu Ok(()) } ast::Expr::Attribute(_) => Ok(()), - ast::Expr::UnaryOp(_) if ensure_literal_negative(expr, true, true) => Ok(()), + ast::Expr::UnaryOp(_) if ensure_literal_signed(expr, true, true) => Ok(()), ast::Expr::BinOp(_) if ensure_literal_complex(expr) => Ok(()), ast::Expr::FString(_) | ast::Expr::TString(_) => Ok(()), ast::Expr::BooleanLiteral(_) @@ -593,10 +615,9 @@ fn validate_expr(vm: &VirtualMachine, expr: &ast::Expr, ctx: ast::ExprContext) - } ast::Expr::DictComp(dict) => { validate_comprehension(vm, &dict.generators)?; - let key = dict.key.as_deref().ok_or_else(|| { - vm.new_value_error("field 'key' is required for DictComp".to_owned()) - })?; - validate_expr(vm, key, ast::ExprContext::Load)?; + if let Some(key) = &dict.key { + validate_expr(vm, key, ast::ExprContext::Load)?; + } validate_expr(vm, &dict.value, ast::ExprContext::Load) } ast::Expr::Generator(generator) => { @@ -616,10 +637,11 @@ fn validate_expr(vm: &VirtualMachine, expr: &ast::Expr, ctx: ast::ExprContext) - validate_expr(vm, &await_expr.value, ast::ExprContext::Load) } ast::Expr::Compare(compare) => { - if compare.comparators.is_empty() { + let comparators = compare.operands.get(1..).unwrap_or(&[]); + if comparators.is_empty() { return Err(vm.new_value_error("Compare with no comparators")); } - if compare.comparators.len() != compare.ops.len() { + if comparators.len() != compare.ops.len() { return Err(vm.new_value_error( "Compare has a different number of comparators and operands", )); @@ -629,8 +651,8 @@ fn validate_expr(vm: &VirtualMachine, expr: &ast::Expr, ctx: ast::ExprContext) - compare.runtime_comparators.as_ref(), ast::ExprContext::Load, )?; - validate_exprs(vm, &compare.comparators, ast::ExprContext::Load, false)?; - validate_expr(vm, &compare.left, ast::ExprContext::Load) + validate_exprs(vm, comparators, ast::ExprContext::Load, false)?; + validate_expr(vm, compare.first_operand(), ast::ExprContext::Load) } ast::Expr::Call(call) => { validate_expr(vm, &call.func, ast::ExprContext::Load)?; @@ -738,6 +760,7 @@ fn validate_stmt(vm: &VirtualMachine, stmt: &ast::Stmt) -> PyResult<()> { "FunctionDef" }; validate_body(vm, &func.body, func.runtime_body.as_ref(), owner)?; + validate_name(vm, func.name.id())?; validate_type_params(vm, func.type_params.as_deref())?; validate_parameters(vm, &func.parameters)?; validate_runtime_expr_list_slots( @@ -758,6 +781,7 @@ fn validate_stmt(vm: &VirtualMachine, stmt: &ast::Stmt) -> PyResult<()> { class_def.runtime_body.as_ref(), "ClassDef", )?; + validate_name(vm, class_def.name.id())?; validate_type_params(vm, class_def.type_params.as_deref())?; if let Some(arguments) = &class_def.arguments { validate_runtime_expr_list_slots( @@ -908,6 +932,11 @@ fn validate_stmt(vm: &VirtualMachine, stmt: &ast::Stmt) -> PyResult<()> { if let Some(type_expr) = &handler.type_ { validate_expr(vm, type_expr, ast::ExprContext::Load)?; } + if !try_stmt.is_star + && let Some(name) = &handler.name + { + validate_name(vm, name.id())?; + } validate_body( vm, &handler.body, @@ -927,18 +956,14 @@ fn validate_stmt(vm: &VirtualMachine, stmt: &ast::Stmt) -> PyResult<()> { } Ok(()) } - ast::Stmt::Import(import) => { - validate_nonempty_seq(vm, import.names.len(), "names", "Import")?; - Ok(()) - } + ast::Stmt::Import(import) => validate_import_names(vm, &import.names, "Import"), ast::Stmt::ImportFrom(import) => { if let Some(level) = import.runtime_level && level < 0 { return Err(vm.new_value_error("Negative ImportFrom level")); } - validate_nonempty_seq(vm, import.names.len(), "names", "ImportFrom")?; - Ok(()) + validate_import_names(vm, &import.names, "ImportFrom") } ast::Stmt::Global(global) => { validate_nonempty_seq(vm, global.names.len(), "names", "Global")?; diff --git a/crates/vm/src/stdlib/_codecs.rs b/crates/vm/src/stdlib/_codecs.rs index a17c025f50c..afff3035b5e 100644 --- a/crates/vm/src/stdlib/_codecs.rs +++ b/crates/vm/src/stdlib/_codecs.rs @@ -9,16 +9,47 @@ mod _codecs { use core::hint::cold_path; use crate::codecs::{ErrorsHandler, PyDecodeContext, PyEncodeContext}; - use crate::common::encodings; - use crate::common::wtf8::Wtf8Buf; + use crate::common::encodings::{self, DecodeContext}; + use crate::common::wtf8::{CodePoint, Wtf8Buf}; use crate::{ AsObject, PyObjectRef, PyResult, VirtualMachine, - builtins::{PyBytesRef, PyStrRef, PyUtf8StrRef}, + builtins::{PyBytesRef, PyInt, PyStr, PyStrRef, PyUtf8StrRef}, codecs, convert::TryFromObject, exceptions::nul_char_error, - function::ArgBytesLike, + function::{ArgBytesLike, ArgIntoBool, OptionalOption}, }; + use num_traits::ToPrimitive; + + #[derive(FromArgs)] + struct NormalizeEncodingArgs { + #[pyarg(any)] + encoding: PyStrRef, + } + + #[pyfunction] + fn _normalize_encoding(args: NormalizeEncodingArgs, vm: &VirtualMachine) -> PyResult { + let encoding = args.encoding; + // CPython converts the entire input to UTF-8 before scanning for NUL. + if !encoding.is_utf8() { + let ctx = PyEncodeContext::new(encodings::utf8::ENCODING_NAME, &encoding, vm); + encodings::utf8::encode(ctx, &encodings::errors::Strict)?; + } + let mut normalized = String::with_capacity(encoding.byte_len()); + let mut punct = false; + for byte in encoding.as_bytes().iter().copied().take_while(|b| *b != 0) { + if byte.is_ascii_alphanumeric() || byte == b'.' { + if punct && !normalized.is_empty() { + normalized.push('_'); + } + normalized.push(char::from(byte)); + punct = false; + } else { + punct = true; + } + } + Ok(normalized) + } #[pyfunction] fn register(search_function: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { @@ -45,12 +76,8 @@ mod _codecs { #[derive(FromArgs)] struct CodeArgs { obj: PyObjectRef, - // None is replaced with utf-8 before the codec runs. - #[pyarg(any, optional, py_default = "'utf-8'")] - encoding: Option, - // None is replaced with strict before the codec runs. - #[pyarg(any, optional, py_default = "'strict'")] - errors: Option, + #[pyarg(flatten)] + names: codecs::TextCodecArgs, } impl CodeArgs { @@ -65,17 +92,11 @@ mod _codecs { &VirtualMachine, ) -> PyResult, ) -> PyResult { - let encoding = self - .encoding + let (encoding, errors) = self.names.into_parts(); + let encoding = encoding .as_deref() .map_or(codecs::DEFAULT_ENCODING, |s| s.as_str()); - f( - &vm.state.codec_registry, - self.obj, - encoding, - self.errors, - vm, - ) + f(&vm.state.codec_registry, self.obj, encoding, errors, vm) } } @@ -160,8 +181,8 @@ mod _codecs { data: ArgBytesLike, #[pyarg(positional, optional)] errors: Option, - #[pyarg(positional, name = "final", default)] - final_decode: bool, + #[pyarg(positional, default = ArgIntoBool::FALSE)] + r#final: ArgIntoBool, } impl DecodeArgs { @@ -172,7 +193,7 @@ mod _codecs { { let ctx = PyDecodeContext::new(name, &self.data, vm); let errors = ErrorsHandler::new(self.errors.as_deref(), vm); - decode(ctx, &errors, self.final_decode) + decode(ctx, &errors, self.r#final.into_bool()) } } @@ -211,7 +232,7 @@ mod _codecs { .as_ref() .is_some_and(|s| s.is(identifier!(vm, surrogatepass))) { - return Ok((args.str.as_bytes().to_vec(), args.str.byte_len())); + return Ok((args.str.as_bytes().to_vec(), args.str.char_len())); } do_codec!(utf8::encode, args, vm) } @@ -369,8 +390,8 @@ mod _codecs { data: PyObjectRef, #[pyarg(positional, optional)] errors: Option, - #[pyarg(positional, name = "final", default = true)] - final_decode: bool, + #[pyarg(positional, default = ArgIntoBool::TRUE)] + r#final: ArgIntoBool, } impl EscapeTextDecodeArgs { @@ -390,7 +411,7 @@ mod _codecs { let ctx = PyDecodeContext::new(encodings::unicode_escape::ENCODING_NAME, &data, vm); let errors = ErrorsHandler::new(args.errors.as_deref(), vm); let (text, consumed, note) = - encodings::unicode_escape::decode(ctx, &errors, args.final_decode)?; + encodings::unicode_escape::decode(ctx, &errors, args.r#final.into_bool())?; warn_escape(note, vm)?; Ok((text, consumed)) } @@ -409,7 +430,7 @@ mod _codecs { let data = args.bytes(vm)?; let ctx = PyDecodeContext::new(encodings::raw_unicode_escape::ENCODING_NAME, &data, vm); let errors = ErrorsHandler::new(args.errors.as_deref(), vm); - encodings::raw_unicode_escape::decode(ctx, &errors, args.final_decode) + encodings::raw_unicode_escape::decode(ctx, &errors, args.r#final.into_bool()) } #[pyfunction] @@ -421,7 +442,7 @@ mod _codecs { fn utf_7_decode(args: DecodeArgs, vm: &VirtualMachine) -> DecodeResult { let ctx = PyDecodeContext::new(encodings::utf7::ENCODING_NAME, &args.data, vm); let errors = ErrorsHandler::new(args.errors.as_deref(), vm); - encodings::utf7::decode(ctx, &errors, args.final_decode) + encodings::utf7::decode(ctx, &errors, args.r#final.into_bool()) } #[derive(FromArgs)] @@ -473,7 +494,7 @@ mod _codecs { ctx, &errors, encodings::utf16::ByteOrder::Native, - args.final_decode, + args.r#final.into_bool(), )?; Ok((text, consumed)) } @@ -497,7 +518,7 @@ mod _codecs { ctx, &errors, encodings::utf16::ByteOrder::Little, - args.final_decode, + args.r#final.into_bool(), )?; Ok((text, consumed)) } @@ -521,7 +542,7 @@ mod _codecs { ctx, &errors, encodings::utf16::ByteOrder::Big, - args.final_decode, + args.r#final.into_bool(), )?; Ok((text, consumed)) } @@ -534,8 +555,8 @@ mod _codecs { errors: Option, #[pyarg(positional, default)] byteorder: i32, - #[pyarg(positional, name = "final", default)] - final_decode: bool, + #[pyarg(positional, default = ArgIntoBool::FALSE)] + r#final: ArgIntoBool, } #[pyfunction] @@ -545,7 +566,12 @@ mod _codecs { ) -> PyResult<(Wtf8Buf, usize, i32)> { let ctx = PyDecodeContext::new(encodings::utf16::ENCODING_NAME, &args.data, vm); let errors = ErrorsHandler::new(args.errors.as_deref(), vm); - encodings::utf16::decode(ctx, &errors, wide_order(args.byteorder), args.final_decode) + encodings::utf16::decode( + ctx, + &errors, + wide_order(args.byteorder), + args.r#final.into_bool(), + ) } #[pyfunction] @@ -565,7 +591,7 @@ mod _codecs { ctx, &errors, encodings::utf32::ByteOrder::Native, - args.final_decode, + args.r#final.into_bool(), )?; Ok((text, consumed)) } @@ -589,7 +615,7 @@ mod _codecs { ctx, &errors, encodings::utf32::ByteOrder::Little, - args.final_decode, + args.r#final.into_bool(), )?; Ok((text, consumed)) } @@ -613,7 +639,7 @@ mod _codecs { ctx, &errors, encodings::utf32::ByteOrder::Big, - args.final_decode, + args.r#final.into_bool(), )?; Ok((text, consumed)) } @@ -625,7 +651,12 @@ mod _codecs { ) -> PyResult<(Wtf8Buf, usize, i32)> { let ctx = PyDecodeContext::new(encodings::utf32::ENCODING_NAME, &args.data, vm); let errors = ErrorsHandler::new(args.errors.as_deref(), vm); - encodings::utf32::decode(ctx, &errors, wide_order(args.byteorder), args.final_decode) + encodings::utf32::decode( + ctx, + &errors, + wide_order(args.byteorder), + args.r#final.into_bool(), + ) } macro_rules! delegate_pycodecs { @@ -650,9 +681,9 @@ mod _codecs { #[derive(FromArgs)] struct CharmapDecodeArgs { #[pyarg(positional)] - data: PyObjectRef, - #[pyarg(positional, optional)] - errors: Option, + data: ArgBytesLike, + #[pyarg(positional, optional, py_default = "None")] + errors: OptionalOption, #[pyarg(positional, optional)] mapping: Option, } @@ -681,15 +712,103 @@ mod _codecs { delegate_pycodecs!(charmap_encode, forwarded, vm) } #[pyfunction] - fn charmap_decode(args: CharmapDecodeArgs, vm: &VirtualMachine) -> PyResult { - let mut forwarded = vec![args.data]; - if args.mapping.is_some() && args.errors.is_none() { - forwarded.push(vm.ctx.new_str("strict").into()); + fn charmap_decode(args: CharmapDecodeArgs, vm: &VirtualMachine) -> DecodeResult { + let errors = args.errors.flatten(); + if errors + .as_ref() + .is_some_and(|s| s.as_pystr().contains_nuls()) + { + return Err(nul_char_error(vm)); + } + // Charmap honors registry overrides even for standard error names. + let errors = ErrorsHandler::new_registered(errors.as_deref(), vm); + let Some(mapping) = args.mapping.filter(|mapping| !vm.is_none(mapping)) else { + let ctx = PyDecodeContext::new(encodings::latin_1::ENCODING_NAME, &args.data, vm); + return encodings::latin_1::decode(ctx, &errors); + }; + let consumed = args.data.borrow_buf().len(); + let mut ctx: Option> = None; + let mut pos = 0; + let mut decoded = Wtf8Buf::with_capacity(consumed); + // Only exact strings bypass __getitem__; subclasses can override it. + let string_map = mapping + .downcast_ref_if_exact::(vm) + .map(|s| s.as_wtf8().code_points().take(256).collect::>()); + loop { + // Do not hold a buffer read guard across mapping callbacks: they + // may change the original bytearray without resizing it. + let byte = match &ctx { + Some(ctx) => ctx.full_data().get(pos).copied(), + None => args.data.borrow_buf().get(pos).copied(), + }; + let Some(byte) = byte else { break }; + let defined = if let Some(string_map) = &string_map { + if let Some(&cp) = string_map + .get(usize::from(byte)) + .filter(|cp| cp.to_u32() != 0xfffe) + { + decoded.push(cp); + true + } else { + false + } + } else { + charmap_decode_mapping(&mapping, byte, &mut decoded, vm)? + }; + if defined { + pos += 1; + } else { + // At the first error CPython switches to the exception's + // immutable bytes, including mutations made by this lookup. + let ctx = ctx.get_or_insert_with(|| { + let data = vm.ctx.new_bytes(args.data.borrow_buf().to_vec()); + PyDecodeContext::new_owned("charmap", data, vm) + }); + ctx.restart_from(pos)?; + let replacement = + ctx.handle_error(&errors, pos..pos + 1, Some("character maps to "))?; + decoded.push_wtf8(replacement.as_wtf8()); + pos = ctx.position(); + } + } + // The callback can replace its exception's input, but the codec reports + // the size of the original buffer, as PyUnicode_DecodeCharmap does. + Ok((decoded, consumed)) + } + + fn charmap_decode_mapping( + mapping: &PyObjectRef, + byte: u8, + decoded: &mut Wtf8Buf, + vm: &VirtualMachine, + ) -> PyResult { + let value = match mapping.get_item(vm.ctx.new_int(byte).as_object(), vm) { + Ok(value) => value, + Err(e) if e.fast_isinstance(vm.ctx.exceptions.lookup_error) => return Ok(false), + Err(e) => return Err(e), + }; + if vm.is_none(&value) { + return Ok(false); + } + if let Some(integer) = value.downcast_ref::() { + let cp = integer + .as_bigint() + .to_u32() + .and_then(CodePoint::from_u32) + .ok_or_else(|| vm.new_type_error("character mapping must be in range(0x110000)"))?; + if cp.to_u32() == 0xfffe { + return Ok(false); + } + decoded.push(cp); + } else if let Some(text) = value.downcast_ref::() { + if text.as_wtf8() == "\u{fffe}" { + return Ok(false); + } + decoded.push_wtf8(text.as_wtf8()); } else { - push_optional(&mut forwarded, args.errors); + return Err(vm.new_type_error("character mapping must return integer, None or str")); } - push_optional(&mut forwarded, args.mapping); - delegate_pycodecs!(charmap_decode, forwarded, vm) + Ok(true) } #[pyfunction] fn charmap_build(args: CharmapBuildArgs, vm: &VirtualMachine) -> PyResult { @@ -720,77 +839,25 @@ mod _codecs_windows { builtins::PyStr, builtins::PyStrRef, builtins::PyUtf8StrRef, function::ArgBytesLike, }; use rustpython_host_env::windows as host_windows; - use std::{ffi::OsStr, os::windows::ffi::OsStrExt}; - - fn string_from_utf16( - encoding: &str, - data: &[u8], - wide: &[u16], - vm: &VirtualMachine, - ) -> PyResult { - String::from_utf16(wide).map_err(|err| { - vm.new_unicode_decode_error( - vm.ctx.new_str(encoding), - vm.ctx.new_bytes(data.to_vec()), - 0, - data.len(), - vm.ctx.new_str(format!("{encoding}_decode failed: {err}")), - ) - }) - } #[derive(FromArgs)] struct MbcsEncodeArgs { #[pyarg(positional)] - s: PyStrRef, + str: PyStrRef, #[pyarg(positional, optional)] errors: Option, } #[pyfunction] fn mbcs_encode(args: MbcsEncodeArgs, vm: &VirtualMachine) -> PyResult<(Vec, usize)> { - let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); - let s = match args.s.to_str() { - Some(s) => s, - None => { - // String contains surrogates - not encodable with mbcs - return encode_code_page_errors(host_windows::CP_ACP, &args.s, errors, "mbcs", vm); - } - }; - let char_len = args.s.char_len(); - - if s.is_empty() { - return Ok((Vec::new(), char_len)); - } - - // Convert UTF-8 string to UTF-16 - let wide: Vec<_> = OsStr::new(s).encode_wide().collect(); - - // Get the required buffer size - let (size, _) = host_windows::wide_char_to_multi_byte_len( - host_windows::CP_ACP, - host_windows::WC_NO_BEST_FIT_CHARS, - &wide, - false, - ) - .map_err(|err| vm.new_os_error(format!("mbcs_encode failed: {err}")))?; - - let mut buffer = vec![0u8; size]; - let (result, used_default_char) = host_windows::wide_char_to_multi_byte( - host_windows::CP_ACP, - host_windows::WC_NO_BEST_FIT_CHARS, - &wide, - &mut buffer, - errors == "strict", + code_page_encode( + CodePageEncodeArgs { + code_page: host_windows::CP_ACP as i32, + str: args.str, + errors: args.errors, + }, + vm, ) - .map_err(|err| vm.new_os_error(format!("mbcs_encode failed: {err}")))?; - - if errors == "strict" && used_default_char { - return encode_code_page_errors(host_windows::CP_ACP, &args.s, errors, "mbcs", vm); - } - - buffer.truncate(result); - Ok((buffer, char_len)) } #[derive(FromArgs)] @@ -800,113 +867,40 @@ mod _codecs_windows { #[pyarg(positional, optional)] errors: Option, #[pyarg(positional, default)] - #[allow(dead_code)] r#final: bool, } #[pyfunction] - fn mbcs_decode(args: MbcsDecodeArgs, vm: &VirtualMachine) -> PyResult<(String, usize)> { - let _errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); - let data = args.data.borrow_buf(); - let len = data.len(); - - if data.is_empty() { - return Ok((String::new(), 0)); - } - - // Get the required buffer size for UTF-16 - let size = host_windows::multi_byte_to_wide_len( - host_windows::CP_ACP, - host_windows::MB_ERR_INVALID_CHARS, - data.as_ref(), - ); - - if size.is_err() { - // Try without MB_ERR_INVALID_CHARS for non-strict mode (replacement behavior) - let size = host_windows::multi_byte_to_wide_len(host_windows::CP_ACP, 0, data.as_ref()) - .map_err(|err| vm.new_os_error(format!("mbcs_decode failed: {err}")))?; - - let mut buffer = vec![0u16; size]; - let result = host_windows::multi_byte_to_wide( - host_windows::CP_ACP, - 0, - data.as_ref(), - &mut buffer, - ) - .map_err(|err| vm.new_os_error(format!("mbcs_decode failed: {err}")))?; - buffer.truncate(result); - let s = string_from_utf16("mbcs", data.as_ref(), &buffer, vm)?; - return Ok((s, len)); - } - - // Strict mode succeeded - no invalid characters - let size = size.unwrap(); - let mut buffer = vec![0u16; size]; - let result = host_windows::multi_byte_to_wide( - host_windows::CP_ACP, - host_windows::MB_ERR_INVALID_CHARS, - data.as_ref(), - &mut buffer, + fn mbcs_decode(args: MbcsDecodeArgs, vm: &VirtualMachine) -> PyResult<(PyStrRef, usize)> { + code_page_decode( + CodePageDecodeArgs { + codepage: host_windows::CP_ACP as i32, + data: args.data, + errors: args.errors, + r#final: args.r#final, + }, + vm, ) - .map_err(|err| vm.new_os_error(format!("mbcs_decode failed: {err}")))?; - buffer.truncate(result); - let s = string_from_utf16("mbcs", data.as_ref(), &buffer, vm)?; - - Ok((s, len)) } #[derive(FromArgs)] struct OemEncodeArgs { #[pyarg(positional)] - s: PyStrRef, + str: PyStrRef, #[pyarg(positional, optional)] errors: Option, } #[pyfunction] fn oem_encode(args: OemEncodeArgs, vm: &VirtualMachine) -> PyResult<(Vec, usize)> { - let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); - let s = match args.s.to_str() { - Some(s) => s, - None => { - // String contains surrogates - not encodable with oem - return encode_code_page_errors(host_windows::CP_OEMCP, &args.s, errors, "oem", vm); - } - }; - let char_len = args.s.char_len(); - - if s.is_empty() { - return Ok((Vec::new(), char_len)); - } - - // Convert UTF-8 string to UTF-16 - let wide: Vec<_> = OsStr::new(s).encode_wide().collect(); - - // Get the required buffer size - let (size, _) = host_windows::wide_char_to_multi_byte_len( - host_windows::CP_OEMCP, - host_windows::WC_NO_BEST_FIT_CHARS, - &wide, - false, - ) - .map_err(|err| vm.new_os_error(format!("oem_encode failed: {err}")))?; - - let mut buffer = vec![0u8; size]; - let (result, used_default_char) = host_windows::wide_char_to_multi_byte( - host_windows::CP_OEMCP, - host_windows::WC_NO_BEST_FIT_CHARS, - &wide, - &mut buffer, - errors == "strict", + code_page_encode( + CodePageEncodeArgs { + code_page: host_windows::CP_OEMCP as i32, + str: args.str, + errors: args.errors, + }, + vm, ) - .map_err(|err| vm.new_os_error(format!("oem_encode failed: {err}")))?; - - if errors == "strict" && used_default_char { - return encode_code_page_errors(host_windows::CP_OEMCP, &args.s, errors, "oem", vm); - } - - buffer.truncate(result); - Ok((buffer, char_len)) } #[derive(FromArgs)] @@ -916,60 +910,20 @@ mod _codecs_windows { #[pyarg(positional, optional)] errors: Option, #[pyarg(positional, default)] - #[allow(dead_code)] r#final: bool, } #[pyfunction] - fn oem_decode(args: OemDecodeArgs, vm: &VirtualMachine) -> PyResult<(String, usize)> { - let _errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); - let data = args.data.borrow_buf(); - let len = data.len(); - - if data.is_empty() { - return Ok((String::new(), 0)); - } - - // Get the required buffer size for UTF-16 - let size = host_windows::multi_byte_to_wide_len( - host_windows::CP_OEMCP, - host_windows::MB_ERR_INVALID_CHARS, - data.as_ref(), - ); - - if size.is_err() { - // Try without MB_ERR_INVALID_CHARS for non-strict mode (replacement behavior) - let size = - host_windows::multi_byte_to_wide_len(host_windows::CP_OEMCP, 0, data.as_ref()) - .map_err(|err| vm.new_os_error(format!("oem_decode failed: {err}")))?; - - let mut buffer = vec![0u16; size]; - let result = host_windows::multi_byte_to_wide( - host_windows::CP_OEMCP, - 0, - data.as_ref(), - &mut buffer, - ) - .map_err(|err| vm.new_os_error(format!("oem_decode failed: {err}")))?; - buffer.truncate(result); - let s = string_from_utf16("oem", data.as_ref(), &buffer, vm)?; - return Ok((s, len)); - } - - // Strict mode succeeded - no invalid characters - let size = size.unwrap(); - let mut buffer = vec![0u16; size]; - let result = host_windows::multi_byte_to_wide( - host_windows::CP_OEMCP, - host_windows::MB_ERR_INVALID_CHARS, - data.as_ref(), - &mut buffer, + fn oem_decode(args: OemDecodeArgs, vm: &VirtualMachine) -> PyResult<(PyStrRef, usize)> { + code_page_decode( + CodePageDecodeArgs { + codepage: host_windows::CP_OEMCP as i32, + data: args.data, + errors: args.errors, + r#final: args.r#final, + }, + vm, ) - .map_err(|err| vm.new_os_error(format!("oem_decode failed: {err}")))?; - buffer.truncate(result); - let s = string_from_utf16("oem", data.as_ref(), &buffer, vm)?; - - Ok((s, len)) } #[derive(FromArgs)] @@ -977,7 +931,7 @@ mod _codecs_windows { #[pyarg(positional)] code_page: i32, #[pyarg(positional)] - s: PyStrRef, + str: PyStrRef, #[pyarg(positional, optional)] errors: Option, } @@ -1066,80 +1020,33 @@ mod _codecs_windows { fn encode_code_page_errors( code_page: u32, s: &Py, - errors: &str, + errors: Option<&Py>, encoding_name: &str, vm: &VirtualMachine, ) -> PyResult<(Vec, usize)> { - use crate::{ - Py, - builtins::{PyBytes, PyStr, PyTuple}, - }; - - let char_len = s.char_len(); - let flags = encode_code_page_flags(code_page, errors); + use crate::codecs::{ErrorsHandler, PyEncodeContext}; + use crate::common::encodings::{EncodeContext, EncodeReplace, StrSize}; + + let mut ctx = PyEncodeContext::new(encoding_name, s, vm); + let reason = Some("invalid character"); + if errors.is_none_or(|e| e.as_str() == "strict") { + // CPython reports the failed whole-string conversion with an empty range. + return Err(ctx.error_encoding(StrSize::default()..StrSize::default(), reason)); + } + let handler = ErrorsHandler::new_registered(errors, vm); + let flags = encode_code_page_flags(code_page, errors.map_or("strict", |e| e.as_str())); let use_default_char = code_page != host_windows::CP_UTF8 && code_page != host_windows::CP_UTF7; - let encoding_str = vm.ctx.new_str(encoding_name); - let reason_str = vm.ctx.new_str("invalid character"); - - // For strict mode, find the first unencodable character and raise - if errors == "strict" { - // Find the failing position by trying each character - let mut fail_pos = 0; - for cp in s.as_wtf8().code_points() { - let ch = cp.to_u32(); - if (0xD800..=0xDFFF).contains(&ch) { - break; - } - let mut wchars = [0u16; 2]; - let wchar_len = if ch < 0x10000 { - wchars[0] = ch as u16; - 1 - } else { - wchars[0] = ((ch - 0x10000) >> 10) as u16 + 0xD800; - wchars[1] = ((ch - 0x10000) & 0x3FF) as u16 + 0xDC00; - 2 - }; - match host_windows::wide_char_to_multi_byte_len( - code_page, - flags, - &wchars[..wchar_len], - use_default_char, - ) { - Ok((_outsize, used_default_char)) - if !use_default_char || !used_default_char => - { - fail_pos += 1; - } - _ => break, - } - } - return Err(vm.new_unicode_encode_error( - encoding_str, - s.to_owned(), - fail_pos, - fail_pos + 1, - reason_str, - )); - } - - let error_handler = vm.state.codec_registry.lookup_error(errors, vm)?; let mut output = Vec::new(); - - // Collect code points for random access - let code_points: Vec = s.as_wtf8().code_points().map(|cp| cp.to_u32()).collect(); - - let mut pos = 0usize; - while pos < code_points.len() { - let ch = code_points[pos]; - - // Convert code point to UTF-16 + while let Some(cp) = ctx.remaining_data().code_points().next() { + let start = ctx.position(); + let end = StrSize { + bytes: start.bytes + cp.len_wtf8(), + chars: start.chars + 1, + }; + let ch = cp.to_u32(); let mut wchars = [0u16; 2]; - let is_surrogate = (0xD800..=0xDFFF).contains(&ch); - - let wchar_len = if is_surrogate { - 0 // Can't encode surrogates normally - } else if ch < 0x10000 { + let wchar_len = if ch < 0x10000 { wchars[0] = ch as u16; 1 } else { @@ -1147,75 +1054,39 @@ mod _codecs_windows { wchars[1] = ((ch - 0x10000) & 0x3FF) as u16 + 0xDC00; 2 }; - - if !is_surrogate { - let mut buf = [0u8; 8]; - if let Ok((outsize, used_default_char)) = host_windows::wide_char_to_multi_byte( - code_page, - flags, - &wchars[..wchar_len], - &mut buf, - use_default_char, - ) && (!use_default_char || !used_default_char) - { - output.extend_from_slice(&buf[..outsize]); - pos += 1; + let mut buf = [0u8; 4]; + match host_windows::wide_char_to_multi_byte( + code_page, + flags, + &wchars[..wchar_len], + &mut buf, + use_default_char, + ) { + Ok((size, used_default)) if !use_default_char || !used_default => { + output.extend_from_slice(&buf[..size]); + ctx.restart_from(end)?; continue; } + Ok(_) => {} + Err(err) + if err.raw_os_error() + == Some(host_windows::ERROR_NO_UNICODE_TRANSLATION_I32) => {} + Err(err) => return Err(vm.new_os_error(format!("code_page_encode: {err}"))), } - - // Character can't be encoded - call error handler - let exc = vm.new_unicode_encode_error( - encoding_str.clone(), - s.to_owned(), - pos, - pos + 1, - reason_str.clone(), - ); - - let res = error_handler.call((exc,), vm)?; - let tuple_err = - || vm.new_type_error("encoding error handler must return (str/bytes, int) tuple"); - let tuple: &Py = res.downcast_ref().ok_or_else(tuple_err)?; - let tuple_slice = tuple.as_slice(); - if tuple_slice.len() != 2 { - return Err(tuple_err()); - } - - let replacement = &tuple_slice[0]; - let new_pos_obj = tuple_slice[1].clone(); - - if let Some(bytes) = replacement.downcast_ref::() { - output.extend_from_slice(bytes.as_bytes()); - } else if let Some(rep_str) = replacement.downcast_ref::() { - // Replacement string - try to encode each character - for rcp in rep_str.as_wtf8().code_points() { - let rch = rcp.to_u32(); - if rch > 127 { - return Err(vm.new_unicode_encode_error( - encoding_str, - s.to_owned(), - pos, - pos + 1, - vm.ctx - .new_str("unable to encode error handler result to ASCII"), + match ctx.handle_error(&handler, start..end, reason)? { + EncodeReplace::Bytes(bytes) => output.extend_from_slice(bytes.as_bytes()), + EncodeReplace::Str(replacement) => { + if !replacement.as_wtf8().is_ascii() { + return Err(ctx.error_encoding( + start..end, + Some("unable to encode error handler result to ASCII"), )); } - output.push(rch as u8); + output.extend_from_slice(replacement.as_bytes()); } - } else { - return Err(tuple_err()); } - - let new_pos: isize = new_pos_obj.try_into_value(vm).map_err(|_| tuple_err())?; - pos = if new_pos < 0 { - (code_points.len() as isize + new_pos).max(0) as usize - } else { - new_pos as usize - }; } - - Ok((output, char_len)) + Ok((output, s.char_len())) } #[pyfunction] @@ -1227,9 +1098,8 @@ mod _codecs_windows { return Err(vm.new_value_error("invalid code page number")); } - let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); let code_page = args.code_page as u32; - let char_len = args.s.char_len(); + let char_len = args.str.char_len(); if char_len == 0 { return Ok((Vec::new(), 0)); @@ -1237,22 +1107,26 @@ mod _codecs_windows { let encoding_name = code_page_encoding_name(code_page); - // Fast path: try encoding the whole string at once (only if no surrogates) - if let Some(str_data) = args.s.to_str() { - let wide: Vec<_> = OsStr::new(str_data).encode_wide().collect(); - if let Some(result) = try_encode_code_page_strict(code_page, &wide, vm)? { - return Ok((result, char_len)); - } + // Preserve lone surrogates: UTF-7 accepts them, unlike UTF-8. + let wide: Vec<_> = args.str.as_wtf8().encode_wide().collect(); + if let Some(result) = try_encode_code_page_strict(code_page, &wide, vm)? { + return Ok((result, char_len)); } // Slow path: character by character with error handling - encode_code_page_errors(code_page, &args.s, errors, &encoding_name, vm) + encode_code_page_errors( + code_page, + &args.str, + args.errors.as_deref(), + &encoding_name, + vm, + ) } #[derive(FromArgs)] struct CodePageDecodeArgs { #[pyarg(positional)] - code_page: i32, + codepage: i32, #[pyarg(positional)] data: ArgBytesLike, #[pyarg(positional, optional)] @@ -1310,217 +1184,70 @@ mod _codecs_windows { /// Decode byte by byte with error handling (slow path). fn decode_code_page_errors( code_page: u32, - data: &[u8], - errors: &str, + data: &ArgBytesLike, + errors: Option<&Py>, is_final: bool, encoding_name: &str, vm: &VirtualMachine, ) -> PyResult<(PyStrRef, usize)> { - use crate::common::wtf8::Wtf8Buf; - use crate::{Py, builtins::PyTuple}; - - let len = data.len(); - let encoding_str = vm.ctx.new_str(encoding_name); - let reason_str = vm - .ctx - .new_str("No mapping for the Unicode character exists in the target code page."); - - // For strict+final, find the failing position and raise - if errors == "strict" && is_final { - // Find the exact failing byte position by trying byte by byte - let mut fail_pos = 0; - let mut flags_s: u32 = host_windows::MB_ERR_INVALID_CHARS; - let mut buf = [0u16; 2]; - while fail_pos < len { - let mut in_size = 1; - let mut found = false; - while in_size <= 4 && fail_pos + in_size <= len { - match host_windows::multi_byte_to_wide( - code_page, - flags_s, - &data[fail_pos..fail_pos + in_size], - &mut buf, - ) { - Ok(_outsize) => { - fail_pos += in_size; - found = true; - break; - } - Err(err) => { - let err_code = err.raw_os_error().unwrap_or(0); - if err_code == host_windows::ERROR_INVALID_FLAGS_I32 && flags_s != 0 { - flags_s = 0; - continue; - } - in_size += 1; - if err_code != host_windows::ERROR_NO_UNICODE_TRANSLATION_I32 - && err_code != host_windows::ERROR_INSUFFICIENT_BUFFER_I32 - { - break; - } - } - } - } - if !found { - break; - } - } - let object = vm.ctx.new_bytes(data.to_vec()); - return Err(vm.new_unicode_decode_error( - encoding_str, - object, - fail_pos, - fail_pos + 1, - reason_str, - )); + use crate::codecs::{ErrorsHandler, PyDecodeContext}; + use crate::common::{encodings::DecodeContext, wtf8::Wtf8Buf}; + + let mut ctx = PyDecodeContext::new(encoding_name, data, vm); + let input_len = ctx.full_data().len(); + let reason = Some("No mapping for the Unicode character exists in the target code page."); + if errors.is_none_or(|e| e.as_str() == "strict") && is_final { + return Err(ctx.error_decoding(0..0, reason)); } - - let error_handler = if errors != "strict" - && errors != "ignore" - && errors != "replace" - && errors != "backslashreplace" - && errors != "surrogateescape" - { - Some(vm.state.codec_registry.lookup_error(errors, vm)?) - } else { - None - }; - - let mut wide_buf: Vec = Vec::new(); - let mut pos = 0usize; - let mut flags: u32 = host_windows::MB_ERR_INVALID_CHARS; - - while pos < len { - // Try to decode with increasing byte counts (1, 2, 3, 4) + let handler = ErrorsHandler::new_registered(errors, vm); + let mut wide_buf = Vec::new(); + let mut flags = host_windows::MB_ERR_INVALID_CHARS; + while !ctx.remaining_data().is_empty() { + let pos = ctx.position(); + let len = ctx.full_data().len(); let mut in_size = 1; - let outsize; let mut buffer = [0u16; 2]; - - loop { + let outsize = loop { match host_windows::multi_byte_to_wide( code_page, flags, - &data[pos..pos + in_size], + &ctx.full_data()[pos..pos + in_size], &mut buffer, ) { - Ok(size) => { - outsize = size; - break; - } + Ok(size) => break size, Err(err) => { - let err_code = err.raw_os_error().unwrap_or(0); - if err_code == host_windows::ERROR_INVALID_FLAGS_I32 && flags != 0 { + let code = err.raw_os_error().unwrap_or(0); + if code == host_windows::ERROR_INVALID_FLAGS_I32 && flags != 0 { flags = 0; continue; } - if err_code != host_windows::ERROR_NO_UNICODE_TRANSLATION_I32 - && err_code != host_windows::ERROR_INSUFFICIENT_BUFFER_I32 + if code != host_windows::ERROR_NO_UNICODE_TRANSLATION_I32 + && code != host_windows::ERROR_INSUFFICIENT_BUFFER_I32 { return Err(vm.new_os_error(format!("code_page_decode: {err}"))); } in_size += 1; if in_size > 4 || pos + in_size > len { - outsize = 0; - break; + break 0; } } } - } - + }; if outsize == 0 { - // Can't decode this byte sequence if pos + in_size >= len && !is_final { - // Incomplete sequence at end, not final - stop here break; } - - // Handle the error based on error mode - match errors { - "ignore" => { - pos += 1; - } - "replace" => { - wide_buf.push(0xFFFD); - pos += 1; - } - "backslashreplace" => { - let byte = data[pos]; - for ch in format!("\\x{byte:02x}").encode_utf16() { - wide_buf.push(ch); - } - pos += 1; - } - "surrogateescape" => { - let byte = data[pos]; - wide_buf.push(0xDC00 + byte as u16); - pos += 1; - } - "strict" => { - let object = vm.ctx.new_bytes(data.to_vec()); - return Err(vm.new_unicode_decode_error( - encoding_str, - object, - pos, - pos + 1, - reason_str, - )); - } - _ => { - // Custom error handler - let object = vm.ctx.new_bytes(data.to_vec()); - let exc = vm.new_unicode_decode_error( - encoding_str.clone(), - object, - pos, - pos + 1, - reason_str.clone(), - ); - let handler = error_handler.as_ref().unwrap(); - let res = handler.call((exc,), vm)?; - let tuple_err = || { - vm.new_type_error("decoding error handler must return (str, int) tuple") - }; - let tuple: &Py = res.downcast_ref().ok_or_else(tuple_err)?; - let tuple_slice = tuple.as_slice(); - if tuple_slice.len() != 2 { - return Err(tuple_err()); - } - - let replacement: PyStrRef = tuple_slice[0] - .clone() - .try_into_value(vm) - .map_err(|_| tuple_err())?; - let new_pos: isize = tuple_slice[1] - .clone() - .try_into_value(vm) - .map_err(|_| tuple_err())?; - - for cp in replacement.as_wtf8().code_points() { - let u = cp.to_u32(); - if u < 0x10000 { - wide_buf.push(u as u16); - } else { - wide_buf.push(((u - 0x10000) >> 10) as u16 + 0xD800); - wide_buf.push(((u - 0x10000) & 0x3FF) as u16 + 0xDC00); - } - } - - pos = if new_pos < 0 { - (len as isize + new_pos).max(0) as usize - } else { - new_pos as usize - }; - } - } + let replacement = ctx.handle_error(&handler, pos..pos + 1, reason)?; + wide_buf.extend(replacement.as_wtf8().encode_wide()); } else { - // Successfully decoded wide_buf.extend_from_slice(&buffer[..outsize]); - pos += in_size; + ctx.advance(in_size); } } - - let s = Wtf8Buf::from_wide(&wide_buf); - Ok((vm.ctx.new_str(s), pos)) + Ok(( + vm.ctx.new_str(Wtf8Buf::from_wide(&wide_buf)), + if is_final { input_len } else { ctx.position() }, + )) } #[pyfunction] @@ -1530,31 +1257,31 @@ mod _codecs_windows { ) -> PyResult<(PyStrRef, usize)> { use crate::common::wtf8::Wtf8Buf; - if args.code_page < 0 { + if args.codepage < 0 { return Err(vm.new_value_error("invalid code page number")); } - let errors = args.errors.as_ref().map_or("strict", |s| s.as_str()); - let code_page = args.code_page as u32; - let data = args.data.borrow_buf(); + let code_page = args.codepage as u32; let is_final = args.r#final; - if data.is_empty() { - return Ok((vm.ctx.new_str(""), 0)); - } - - let encoding_name = code_page_encoding_name(code_page); + { + let data = args.data.borrow_buf(); + if data.is_empty() { + return Ok((vm.ctx.new_str(""), 0)); + } - // Fast path: try decoding the whole buffer at once - if let Some(wide) = try_decode_code_page_strict(code_page, data.as_ref(), vm)? { - let s = Wtf8Buf::from_wide(&wide); - return Ok((vm.ctx.new_str(s), data.len())); + // Fast path: try decoding the whole buffer at once. + if let Some(wide) = try_decode_code_page_strict(code_page, data.as_ref(), vm)? { + let s = Wtf8Buf::from_wide(&wide); + return Ok((vm.ctx.new_str(s), data.len())); + } } + let encoding_name = code_page_encoding_name(code_page); decode_code_page_errors( code_page, - data.as_ref(), - errors, + &args.data, + args.errors.as_deref(), is_final, &encoding_name, vm, diff --git a/crates/vm/src/stdlib/_collections.rs b/crates/vm/src/stdlib/_collections.rs index 1e562f0815b..ac36a8b2722 100644 --- a/crates/vm/src/stdlib/_collections.rs +++ b/crates/vm/src/stdlib/_collections.rs @@ -11,10 +11,13 @@ mod _collections { VirtualMachine, atomic_func, builtins::{ IterStatus::{Active, Exhausted}, - PositionIterInternal, PyDict, PyGenericAlias, PyInt, PyList, PyStr, PyTuple, PyType, - PyTypeRef, locked_step, + PositionIterInternal, PyAnyDict, PyDict, PyGenericAlias, PyInt, PyList, PyStr, PyTuple, + PyType, PyTypeRef, + }, + common::lock::{ + PyMappedRwLockReadGuard, PyMappedRwLockWriteGuard, PyMutex, PyRwLock, + PyRwLockReadGuard, PyRwLockWriteGuard, }, - common::lock::{PyMutex, PyRwLock, PyRwLockReadGuard, PyRwLockWriteGuard}, convert::ToPyObject, function::{ ArgIterable, FuncArgs, KwArgs, OptionalArg, PyComparisonValue, PySetterValue, PySsize, @@ -22,7 +25,6 @@ mod _collections { object::{PyAtomicRef, Traverse, TraverseFn}, protocol::{PyIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, recursion::ReprGuard, - sequence::{MutObjectSequenceOp, OptionalRangeArgs}, sliceable::SequenceIndexOp, types::{ AsMapping, AsNumber, AsSequence, Comparable, Constructor, DefaultConstructor, @@ -30,11 +32,12 @@ mod _collections { SelfIter, }, utils::collection_repr, - vm::MAX_MEMORY_SIZE, + vm::{MAX_MEMORY_SIZE, thread::PyOperation}, }; use alloc::collections::VecDeque; use core::{cmp::max, mem::size_of}; use crossbeam_utils::atomic::AtomicCell; + use num_traits::{Signed, ToPrimitive}; #[derive(FromArgs)] struct RotateArgs { @@ -49,31 +52,38 @@ mod _collections { unhashable = true, traverse = "manual" )] - #[derive(Debug, Default, PyPayload)] + #[derive(Debug, PyPayload)] struct PyDeque { - deque: PyRwLock>, - maxlen: Option, + data: PyRwLock, + operation: PyOperation, state: AtomicCell, // incremented whenever the indices move } + #[derive(Debug, Default)] + struct DequeData { + items: VecDeque, + maxlen: Option, + } + // SAFETY: Traverse visits each owned Python reference at most once. unsafe impl Traverse for PyDeque { fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { - if let Some(deque) = self.deque.try_read_recursive() { - for obj in deque.iter() { + if let Some(deque) = self.data.try_read_recursive() { + for obj in &deque.items { obj.traverse(tracer_fn); } } } fn clear(&mut self, out: &mut Vec) { - out.extend(self.deque.get_mut().drain(..)); + out.extend(self.data.get_mut().items.drain(..)); } } type PyDequeRef = PyRef; #[derive(FromArgs)] + #[from_args(text_signature = "([iterable[, maxlen]])")] struct PyDequeOptions { #[pyarg(any, optional)] iterable: OptionalArg, @@ -81,37 +91,95 @@ mod _collections { maxlen: OptionalArg, } + #[derive(FromArgs)] + struct DequeIndexArgs { + #[pyarg(positional, default = 0)] + start: PyObjectRef, + #[pyarg(positional, optional)] + stop: OptionalArg, + } + + fn deque_index_bound(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + let index = obj.try_index_opt(vm).unwrap_or_else(|| { + Err(vm.new_type_error("slice indices must be integers or have an __index__ method")) + })?; + let value = index.as_bigint(); + Ok(value.to_isize().unwrap_or_else(|| { + if value.is_negative() { + isize::MIN + } else { + isize::MAX + } + })) + } + impl PyDeque { - fn borrow_deque(&self) -> PyRwLockReadGuard<'_, VecDeque> { - self.deque.read() + fn new(vm: &VirtualMachine) -> Self { + Self::from_items(VecDeque::new(), None, 0, vm) + } + + fn from_items( + items: VecDeque, + maxlen: Option, + state: usize, + vm: &VirtualMachine, + ) -> Self { + Self { + data: PyRwLock::new(DequeData { items, maxlen }), + operation: PyOperation::new(vm), + state: AtomicCell::new(state), + } } - fn borrow_deque_mut(&self) -> PyRwLockWriteGuard<'_, VecDeque> { - self.deque.write() + fn borrow_deque(&self) -> PyMappedRwLockReadGuard<'_, VecDeque> { + PyRwLockReadGuard::map(self.data.read(), |data| &data.items) + } + + fn borrow_deque_mut(&self) -> PyMappedRwLockWriteGuard<'_, VecDeque> { + PyRwLockWriteGuard::map(self.data.write(), |data| &mut data.items) + } + + fn maxlen_value(&self) -> Option { + self.data.read().maxlen + } + + fn snapshot(&self) -> (VecDeque, Option, usize) { + let data = self.data.read(); + (data.items.clone(), data.maxlen, self.state.load()) } fn append_item(&self, item: PyObjectRef, left: bool, maxlen: Option) { - let removed = { + let _removed = { let mut deque = self.borrow_deque_mut(); + self.push_item(&mut deque, item, left, maxlen) + }; + } + + // Return evicted items to the caller so they can be dropped after unlocking. + fn push_item( + &self, + deque: &mut VecDeque, + item: PyObjectRef, + left: bool, + maxlen: Option, + ) -> Option { + if left { + deque.push_front(item); + } else { + deque.push_back(item); + } + self.state.fetch_add(1); + // Trim after pushing, so that a `maxlen` of zero drops what just + // arrived instead of popping from an empty deque and keeping it. + if maxlen.is_some_and(|maxlen| deque.len() > maxlen) { if left { - deque.push_front(item); - } else { - deque.push_back(item); - } - self.state.fetch_add(1); - // Trim after pushing, so that a `maxlen` of zero drops what just - // arrived instead of popping from an empty deque and keeping it. - if maxlen.is_some_and(|maxlen| deque.len() > maxlen) { - if left { - deque.pop_back() - } else { - deque.pop_front() - } + deque.pop_back() } else { - None + deque.pop_front() } - }; - drop(removed); + } else { + None + } } fn extend_items( @@ -132,6 +200,16 @@ mod _collections { impl PyDeque { fn _extend(&self, iterable: &PyObject, left: bool, vm: &VirtualMachine) -> PyResult<()> { + self.operation + .with(vm, || self.extend_inner(iterable, left, vm)) + } + + fn extend_inner( + &self, + iterable: &PyObject, + left: bool, + vm: &VirtualMachine, + ) -> PyResult<()> { if iterable .downcast_ref::() .is_some_and(|other| core::ptr::eq(self, &**other)) @@ -140,10 +218,14 @@ mod _collections { // subclass overrides of __iter__ are still respected. let elements: Vec = iterable.try_to_value(vm)?; // Retain the snapshot until extension finishes, as a temporary list does. - return self.extend_items(elements.iter().cloned().map(Ok), left, self.maxlen); + return self.extend_items( + elements.iter().cloned().map(Ok), + left, + self.maxlen_value(), + ); } - let maxlen = self.maxlen; + let maxlen = self.maxlen_value(); let class = iterable.class(); if maxlen.is_none() && (class.is(vm.ctx.types.list_type) || class.is(vm.ctx.types.tuple_type)) @@ -186,38 +268,42 @@ mod _collections { } fn __getitem__(&self, idx: isize, vm: &VirtualMachine) -> PyResult { - let deque = self.borrow_deque(); - idx.wrapped_at(deque.len()) - .and_then(|i| deque.get(i).cloned()) - .ok_or_else(|| vm.new_index_error("deque index out of range")) + let item = { + let deque = self.borrow_deque(); + idx.wrapped_at(deque.len()) + .and_then(|i| deque.get(i).cloned()) + }; + item.ok_or_else(|| vm.new_index_error("deque index out of range")) } fn __setitem__(&self, idx: isize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let removed = { - let mut deque = self.borrow_deque_mut(); - let item = idx - .wrapped_at(deque.len()) - .and_then(|i| deque.get_mut(i)) - .ok_or_else(|| vm.new_index_error("deque index out of range"))?; - core::mem::replace(item, value) - }; - drop(removed); - Ok(()) + self.operation.with(vm, || { + let mut value = Some(value); + let removed = { + let mut deque = self.borrow_deque_mut(); + idx.wrapped_at(deque.len()) + .map(|i| core::mem::replace(&mut deque[i], value.take().unwrap())) + }; + let _removed = + removed.ok_or_else(|| vm.new_index_error("deque index out of range"))?; + Ok(()) + }) } fn __delitem__(&self, idx: isize, vm: &VirtualMachine) -> PyResult<()> { - let removed = { - let mut deque = self.borrow_deque_mut(); - let removed = idx - .wrapped_at(deque.len()) - .and_then(|i| deque.remove(i)) - .ok_or_else(|| vm.new_index_error("deque index out of range"))?; - self.state.fetch_add(1); - removed - }; - // Finalizers can mutate the deque, so release the lock first. - drop(removed); - Ok(()) + self.operation.with(vm, || { + let removed = { + let mut deque = self.borrow_deque_mut(); + idx.wrapped_at(deque.len()).and_then(|i| { + let removed = deque.remove(i); + self.state.fetch_add(1); + removed + }) + }; + let _removed = + removed.ok_or_else(|| vm.new_index_error("deque index out of range"))?; + Ok(()) + }) } fn __contains__(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { @@ -225,20 +311,63 @@ mod _collections { } fn _contains(&self, needle: &PyObject, vm: &VirtualMachine) -> PyResult { - let start_state = self.state.load(); - let ret = self.mut_contains(vm, needle)?; - if start_state != self.state.load() { - Err(vm.new_runtime_error("deque mutated during iteration")) - } else { - Ok(ret) + self.operation + .with(vm, || self.find_index(needle, 0, isize::MAX, vm)) + .map(|index| index.is_some()) + } + + fn compare_item( + &self, + index: usize, + needle: &PyObject, + vm: &VirtualMachine, + ) -> PyResult { + let item = self.borrow_deque().get(index).cloned(); + let item = + item.ok_or_else(|| vm.new_runtime_error("deque mutated during iteration"))?; + // Releasing the comparison reference can also mutate the deque. + item.rich_compare_bool(needle, PyComparisonOp::Eq, vm) + } + + // Called inside the deque's operation guard, without holding its data lock + // across comparisons or the finalizers of replaced comparison items. + fn find_index( + &self, + needle: &PyObject, + start: isize, + stop: isize, + vm: &VirtualMachine, + ) -> PyResult> { + let (start, stop, state) = { + let data = self.data.read(); + ( + start.saturated_at(data.items.len()), + stop.saturated_at(data.items.len()), + self.state.load(), + ) + }; + for index in start..stop { + // Both index() and containment accept a successful comparison + // before checking whether its callback changed the deque. + if self.compare_item(index, needle, vm)? { + return Ok(Some(index)); + } + if state != self.state.load() { + return Err(vm.new_runtime_error("deque mutated during iteration")); + } } + Ok(None) } - fn _mul(&self, n: isize, vm: &VirtualMachine) -> PyResult> { - let deque = self.borrow_deque(); + fn _mul( + &self, + n: isize, + vm: &VirtualMachine, + ) -> PyResult<(VecDeque, Option)> { + let (deque, maxlen, _) = self.snapshot(); let n = vm.check_repeat_or_overflow_error(deque.len(), n)?; let mul_len = n * deque.len(); - let result_len = self.maxlen.map_or(mul_len, |maxlen| mul_len.min(maxlen)); + let result_len = maxlen.map_or(mul_len, |maxlen| mul_len.min(maxlen)); if n > 1 && result_len.saturating_mul(size_of::()) >= MAX_MEMORY_SIZE { return Err(vm.no_memory_error()); } @@ -249,59 +378,113 @@ mod _collections { .try_reserve_exact(result_len) .map_err(|_| vm.no_memory_error())?; result.extend(deque.iter().cycle().skip(start).take(result_len).cloned()); - Ok(result) + Ok((result, maxlen)) } - fn __mul__(&self, n: isize, vm: &VirtualMachine) -> PyResult { - let deque = self._mul(n, vm)?; - Ok(Self { - deque: PyRwLock::new(deque), - maxlen: self.maxlen, - state: AtomicCell::new(0), + fn __mul__(zelf: &Py, n: isize, vm: &VirtualMachine) -> PyResult> { + zelf.operation.with(vm, || { + if !zelf.class().is(Self::class(&vm.ctx)) { + return Self::__imul__(Py::::copy(zelf.to_owned(), vm)?, n, vm); + } + let (items, maxlen) = zelf._mul(n, vm)?; + Ok(Self::from_items(items, maxlen, 0, vm).into_ref(&vm.ctx)) }) } fn __imul__(zelf: PyRef, n: isize, vm: &VirtualMachine) -> PyResult> { + zelf.operation.with(vm, || Self::imul_inner(&zelf, n, vm))?; + Ok(zelf) + } + + fn imul_inner(zelf: &Py, n: isize, vm: &VirtualMachine) -> PyResult<()> { if n == 1 || zelf.borrow_deque().is_empty() { - return Ok(zelf); + return Ok(()); + } + let size = zelf.__len__(); + if n > 1 && size > 1 && !zelf.class().is(Self::class(&vm.ctx)) { + let mut repeats = n as usize; + if size > isize::MAX as usize / repeats { + return Err(vm.no_memory_error()); + } + // Snapshot through the iterator protocol without a deque lock. Retain + // the snapshot until all extensions finish, including item finalizers. + let items = vm.extract_elements_sized(zelf.as_object(), &|| 0, Ok)?; + if let Some(maxlen) = zelf.maxlen_value() { + repeats = repeats.min(maxlen.div_ceil(size)); + } + if items.is_empty() || repeats <= 1 { + return Ok(()); + } + if zelf.maxlen_value().is_none() { + // Use the snapshot length: subclass callbacks may change both + // the deque and the items being repeated. Reservation also + // rejects capacities whose byte size cannot be represented. + let additional = items + .len() + .checked_mul(repeats - 1) + .ok_or_else(|| vm.no_memory_error())?; + let reserved = zelf.borrow_deque_mut().try_reserve_exact(additional); + reserved.map_err(|_| vm.no_memory_error())?; + } + for _ in 1..repeats { + let maxlen = zelf.maxlen_value(); + if maxlen == Some(0) { + continue; + } + for item in &items { + let removed = { + let mut deque = zelf.borrow_deque_mut(); + // Finalizers or another thread can discard a previous + // reservation, so check capacity under the push lock. + deque + .try_reserve(1) + .map(|()| zelf.push_item(&mut deque, item.clone(), false, maxlen)) + }; + let _removed = removed.map_err(|_| vm.no_memory_error())?; + } + } + return Ok(()); } - let mut mul_deque = zelf._mul(n, vm)?; + let (mut mul_deque, _) = zelf._mul(n, vm)?; { let mut deque = zelf.borrow_deque_mut(); core::mem::swap(&mut *deque, &mut mul_deque); zelf.state.fetch_add(1); } - drop(mul_deque); - Ok(zelf) + Ok(()) } fn __len__(&self) -> usize { self.borrow_deque().len() } - fn concat(&self, other: &PyObject, vm: &VirtualMachine) -> PyResult { - if let Some(o) = other.downcast_ref::() { - let mut deque = self.borrow_deque().clone(); - let elements = o.borrow_deque().clone(); - deque.extend(elements); + fn concat(zelf: &Py, other: &PyObject, vm: &VirtualMachine) -> PyResult> { + zelf.operation.with(vm, || { + if let Some(o) = other.downcast_ref::() { + if !zelf.class().is(Self::class(&vm.ctx)) + || !other.class().is(Self::class(&vm.ctx)) + { + let result = Py::::copy(zelf.to_owned(), vm)?; + result._extend(other, false, vm)?; + return Ok(result); + } + let (mut deque, maxlen, _) = zelf.snapshot(); + let elements = o.borrow_deque().clone(); + deque.extend(elements); - let skipped = self - .maxlen - .and_then(|maxlen| deque.len().checked_sub(maxlen)) - .unwrap_or(0); - deque.drain(..skipped); + let skipped = maxlen + .and_then(|maxlen| deque.len().checked_sub(maxlen)) + .unwrap_or(0); + deque.drain(..skipped); - Ok(Self { - deque: PyRwLock::new(deque), - maxlen: self.maxlen, - state: AtomicCell::new(0), - }) - } else { - Err(vm.new_type_error(format!( - r#"can only concatenate deque (not "{}") to deque"#, - other.class().name() - ))) - } + Ok(Self::from_items(deque, maxlen, 0, vm).into_ref(&vm.ctx)) + } else { + Err(vm.new_type_error(format!( + r#"can only concatenate deque (not "{}") to deque"#, + other.class().name() + ))) + } + }) } fn __iadd__( @@ -328,49 +511,83 @@ mod _collections { )] impl Py { #[pymethod] - fn append(&self, item: PyObjectRef) { - self.append_item(item, false, self.maxlen); + fn append(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + self.operation.with(vm, || { + self.append_item(item, false, self.maxlen_value()); + Ok(()) + }) } #[pymethod] - fn appendleft(&self, item: PyObjectRef) { - self.append_item(item, true, self.maxlen); + fn appendleft(&self, item: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + self.operation.with(vm, || { + self.append_item(item, true, self.maxlen_value()); + Ok(()) + }) } #[pymethod] - fn clear(&self) { - let removed = { - let mut deque = self.borrow_deque_mut(); - if deque.is_empty() { - return; - } - self.state.fetch_add(1); - core::mem::take(&mut *deque) - }; - // Finalizers may read or repopulate the now-empty deque. - drop(removed); + fn clear(&self, vm: &VirtualMachine) -> PyResult<()> { + self.operation.with(vm, || { + let _removed = { + let mut deque = self.borrow_deque_mut(); + if deque.is_empty() { + return Ok(()); + } + self.state.fetch_add(1); + core::mem::take(&mut *deque) + }; + // Finalizers may read or repopulate the now-empty deque. + Ok(()) + }) } #[pymethod(name = "__copy__")] #[pymethod] fn copy(zelf: PyRef, vm: &VirtualMachine) -> PyResult> { - PyDeque { - deque: PyRwLock::new(zelf.borrow_deque().clone()), - maxlen: zelf.maxlen, - state: AtomicCell::new(zelf.state.load()), - } - .into_ref_with_type(vm, zelf.class().to_owned()) + zelf.operation.with(vm, || { + let cls = zelf.class(); + if !cls.is(PyDeque::class(&vm.ctx)) { + // A subclass constructor may change the contents or maxlen. Do not hold + // the deque lock across Python callbacks, and validate its result. + let result = match zelf.maxlen_value() { + Some(maxlen) => cls.as_object().call((zelf.clone(), maxlen), vm)?, + None => cls.as_object().call((zelf.clone(),), vm)?, + }; + return result.downcast().map_err(|obj| { + vm.new_type_error(format!( + "{}() must return a deque, not {}", + cls.name(), + obj.class().name() + )) + }); + } + let (items, maxlen, state) = zelf.snapshot(); + PyDeque::from_items(items, maxlen, state, vm) + .into_ref_with_type(vm, zelf.class().to_owned()) + }) } #[pymethod] fn count(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let start_state = self.state.load(); - let count = self.mut_count(vm, &value)?; - - if start_state != self.state.load() { - return Err(vm.new_runtime_error("deque mutated during iteration")); - } - Ok(count) + self.operation.with(vm, || { + let (len, state) = { + let data = self.data.read(); + (data.items.len(), self.state.load()) + }; + let mut count = 0; + for index in 0..len { + if self.compare_item(index, &value, vm)? { + count += 1; + } + // Unlike a search, count checks mutation after every result, + // including a match, before comparing any further elements. + if state != self.state.load() { + return Err(vm.new_runtime_error("deque mutated during iteration")); + } + } + Ok(count) + }) } #[pymethod] @@ -383,152 +600,179 @@ mod _collections { self._extend(&iterable, true, vm) } - #[pymethod] + #[pymethod(text_signature = "($self, value, [start, [stop]])")] fn index( &self, needle: PyObjectRef, - range: OptionalRangeArgs, + range: DequeIndexArgs, vm: &VirtualMachine, ) -> PyResult { - let start_state = self.state.load(); - - let (start, stop) = range.saturate(self.__len__(), vm)?; - let index = self.mut_index_range(vm, &needle, start..stop)?; - if start_state != self.state.load() { - Err(vm.new_runtime_error("deque mutated during iteration")) - } else if let Some(index) = index.into() { - Ok(index) - } else { - Err(vm.new_value_error( - needle - .repr(vm) - .map_or_else(|_| String::new(), |repr| format!("{repr} is not in deque")), - )) - } + // Argument conversion runs before the deque's critical section. + let start = deque_index_bound(&range.start, vm)?; + let stop = match range.stop { + OptionalArg::Present(stop) => deque_index_bound(&stop, vm)?, + OptionalArg::Missing => isize::MAX, + }; + self.operation.with(vm, || { + self.find_index(&needle, start, stop, vm)? + .ok_or_else(|| vm.new_value_error("deque.index(x): x not in deque")) + }) } #[pymethod] - fn insert(&self, index: i32, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - self.state.fetch_add(1); - let mut deque = self.borrow_deque_mut(); - - if self.maxlen == Some(deque.len()) { - return Err(vm.new_index_error("deque already at its maximum size")); - } - - let index = if index < 0 { - if -index as usize > deque.len() { - 0 + fn insert(&self, index: PySsize, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + self.operation.with(vm, || { + let mut value = Some(value); + let full = { + let mut data = self.data.write(); + if data.maxlen == Some(data.items.len()) { + true + } else { + let len = data.items.len(); + let index = if index < 0 { + len.saturating_sub(index.unsigned_abs()) + } else { + (index as usize).min(len) + }; + data.items.insert(index, value.take().unwrap()); + self.state.fetch_add(1); + false + } + }; + if full { + Err(vm.new_index_error("deque already at its maximum size")) } else { - deque.len() - ((-index) as usize) + Ok(()) } - } else if index as usize > deque.len() { - deque.len() - } else { - index as usize - }; - - deque.insert(index, value); - - Ok(()) + }) } #[pymethod] fn pop(&self, vm: &VirtualMachine) -> PyResult { - self.state.fetch_add(1); - self.borrow_deque_mut() - .pop_back() - .ok_or_else(|| vm.new_index_error("pop from an empty deque")) + self.operation.with(vm, || { + let item = { + let mut deque = self.borrow_deque_mut(); + let item = deque.pop_back(); + if item.is_some() { + self.state.fetch_add(1); + } + item + }; + item.ok_or_else(|| vm.new_index_error("pop from an empty deque")) + }) } #[pymethod] fn popleft(&self, vm: &VirtualMachine) -> PyResult { - self.state.fetch_add(1); - self.borrow_deque_mut() - .pop_front() - .ok_or_else(|| vm.new_index_error("pop from an empty deque")) + self.operation.with(vm, || { + let item = { + let mut deque = self.borrow_deque_mut(); + let item = deque.pop_front(); + if item.is_some() { + self.state.fetch_add(1); + } + item + }; + item.ok_or_else(|| vm.new_index_error("pop from an empty deque")) + }) } #[pymethod] fn remove(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let start_state = self.state.load(); - let len = self.borrow_deque().len(); - let mutated = || vm.new_index_error("deque mutated during iteration"); - for index in 0..len { - let item = self - .borrow_deque() - .get(index) - .cloned() - .ok_or_else(mutated)?; - let equal = item.rich_compare_bool(&value, PyComparisonOp::Eq, vm)?; - // Releasing the comparison reference can also run a finalizer. - drop(item); - if start_state != self.state.load() { - return Err(mutated()); - } - if equal { - let removed = { - let mut deque = self.borrow_deque_mut(); - if start_state != self.state.load() { - return Err(mutated()); - } - let removed = deque.remove(index).ok_or_else(mutated)?; - self.state.fetch_add(1); - removed - }; - drop(removed); - return Ok(()); + self.operation.with(vm, || { + let (len, state) = { + let data = self.data.read(); + (data.items.len(), self.state.load()) + }; + for index in 0..len { + let item = self.borrow_deque().get(index).cloned(); + let item = + item.ok_or_else(|| vm.new_index_error("deque mutated during iteration"))?; + let equal = item.rich_compare_bool(&value, PyComparisonOp::Eq, vm); + // Releasing the comparison reference can also run a finalizer. + drop(item); + let equal = equal?; + if state != self.state.load() { + return Err(vm.new_index_error("deque mutated during iteration")); + } + if equal { + let removed = { + let mut deque = self.borrow_deque_mut(); + if state != self.state.load() { + None + } else { + let removed = deque.remove(index); + if removed.is_some() { + self.state.fetch_add(1); + } + removed + } + }; + let _removed = removed + .ok_or_else(|| vm.new_index_error("deque mutated during iteration"))?; + return Ok(()); + } } - } - Err(vm.new_value_error("deque.remove(x): x not in deque")) + Err(vm.new_value_error("deque.remove(x): x not in deque")) + }) } #[pymethod] - fn reverse(&self) { - let rev: VecDeque<_> = self.borrow_deque().iter().cloned().rev().collect(); - *self.borrow_deque_mut() = rev; + fn reverse(&self, vm: &VirtualMachine) -> PyResult<()> { + self.operation.with(vm, || { + self.borrow_deque_mut().make_contiguous().reverse(); + Ok(()) + }) } #[pymethod] fn __reversed__(zelf: PyRef) -> PyReverseDequeIterator { + let (state, len) = { + let data = zelf.data.read(); + (zelf.state.load(), data.items.len()) + }; PyReverseDequeIterator { - state: zelf.state.load(), - counter: AtomicCell::new(zelf.__len__()), + state, + counter: AtomicCell::new(len), internal: PyMutex::new(PositionIterInternal::new(zelf, 0)), } } #[pymethod] - fn rotate(&self, args: RotateArgs) { - self.state.fetch_add(1); - let mut deque = self.borrow_deque_mut(); - if !deque.is_empty() { - let n = args.n % deque.len() as isize; - if n.is_negative() { - deque.rotate_left(-n as usize); - } else { - deque.rotate_right(n as usize); + fn rotate(&self, args: RotateArgs, vm: &VirtualMachine) -> PyResult<()> { + self.operation.with(vm, || { + let mut deque = self.borrow_deque_mut(); + if deque.len() > 1 { + self.state.fetch_add(1); + let n = args.n % deque.len() as isize; + if n.is_negative() { + deque.rotate_left(n.unsigned_abs()); + } else { + deque.rotate_right(n as usize); + } } - } + Ok(()) + }) } #[pygetset] fn maxlen(&self) -> Option { - self.maxlen + self.maxlen_value() } #[pymethod] fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - let cls = zelf.class().to_owned(); - let value = match zelf.maxlen { - Some(v) => vm.new_pyobj((vm.ctx.empty_tuple.clone(), v)), - None => vm.ctx.empty_tuple.clone().into(), - }; // Use __getstate__ to capture both __dict__ and __slots__ values so // subclass attributes survive a pickle round-trip (matches CPython's // deque___reduce___impl, which calls _PyObject_GetState). let state = vm.call_method(zelf.as_object(), "__getstate__", ())?; - Ok(vm.new_pyobj((cls, value, state, PyDequeIterator::new(zelf)))) + let iterator = zelf.as_object().get_iter(vm)?; + let cls = zelf.class().to_owned(); + let value = match zelf.maxlen_value() { + Some(v) => vm.new_pyobj((vm.ctx.empty_tuple.clone(), v)), + None => vm.ctx.empty_tuple.clone().into(), + }; + Ok(vm.new_pyobj((cls, value, state, iterator))) } #[pyclassmethod] @@ -541,20 +785,18 @@ mod _collections { } } - impl MutObjectSequenceOp for PyDeque { - type Inner = VecDeque; + impl Constructor for PyDeque { + type Args = FuncArgs; - fn do_get(index: usize, inner: &Self::Inner) -> Option<&PyObject> { - inner.get(index).map(|r| r.as_ref()) + fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { + Self::new(vm).into_ref_with_type(vm, cls).map(Into::into) } - fn do_lock(&self) -> impl core::ops::Deref { - self.borrow_deque() + fn py_new(_cls: &Py, _args: Self::Args, vm: &VirtualMachine) -> PyResult { + Ok(Self::new(vm)) } } - impl DefaultConstructor for PyDeque {} - impl Initializer for PyDeque { type Args = PyDequeOptions; @@ -563,51 +805,44 @@ mod _collections { PyDequeOptions { iterable, maxlen }: Self::Args, vm: &VirtualMachine, ) -> PyResult<()> { - // TODO: This is _basically_ pyobject_to_opt_usize in itertools.rs - // need to move that function elsewhere and refactor usages. - let maxlen = if let Some(obj) = maxlen.into_option() { - if !vm.is_none(&obj) { - let maxlen: isize = obj - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("an integer is required."))? - .try_to_primitive(vm)?; - - if maxlen.is_negative() { - return Err(vm.new_value_error("maxlen must be non-negative.")); + zelf.operation.with(vm, || { + // TODO: This is _basically_ pyobject_to_opt_usize in itertools.rs + // need to move that function elsewhere and refactor usages. + let maxlen = if let Some(obj) = maxlen.into_option() { + if !vm.is_none(&obj) { + let maxlen: isize = obj + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("an integer is required."))? + .try_to_primitive(vm)?; + + if maxlen.is_negative() { + return Err(vm.new_value_error("maxlen must be non-negative.")); + } + Some(maxlen as usize) + } else { + None } - Some(maxlen as usize) } else { None - } - } else { - None - }; + }; - // SAFETY: This is hacky part for read-only field - // Because `maxlen` is only mutated from __init__. We can abuse the lock of deque to ensure this is locked enough. - // If we make a single lock of deque not only for extend but also for setting maxlen, it will be safe. - let removed = { - let mut deque = zelf.borrow_deque_mut(); - unsafe { - // `maxlen` is better to be defined as UnsafeCell in common practice, - // but then more type works without any safety benefits - let unsafe_maxlen = - &zelf.maxlen as *const _ as *const core::cell::UnsafeCell>; - *(*unsafe_maxlen).get() = maxlen; - } - let removed = core::mem::take(&mut *deque); - if !removed.is_empty() { - zelf.state.fetch_add(1); - } - removed - }; - // Release old elements before iterating; their finalizers can add new ones. - drop(removed); + let removed = { + let mut data = zelf.data.write(); + data.maxlen = maxlen; + let removed = core::mem::take(&mut data.items); + if !removed.is_empty() { + zelf.state.fetch_add(1); + } + removed + }; + // Release old elements before iterating; their finalizers can add new ones. + drop(removed); - let Some(iterable) = iterable.into_option() else { - return Ok(()); - }; - zelf._extend(&iterable, false, vm) + let Some(iterable) = iterable.into_option() else { + return Ok(()); + }; + zelf.extend_inner(&iterable, false, vm) + }) } } @@ -629,15 +864,11 @@ mod _collections { static AS_SEQUENCE: PySequenceMethods = PySequenceMethods { length: atomic_func!(|seq, _vm| Ok(PyDeque::sequence_downcast(seq).__len__())), concat: atomic_func!(|seq, other, vm| { - PyDeque::sequence_downcast(seq) - .concat(other, vm) - .map(|x| x.into_ref(&vm.ctx).into()) + PyDeque::concat(PyDeque::sequence_downcast(seq), other, vm).map(Into::into) }), repeat: atomic_func!(|seq, n, vm| { - PyDeque::sequence_downcast(seq) - .__mul__(n, vm) - .map(|x| x.into_ref(&vm.ctx).into()) + PyDeque::__mul__(PyDeque::sequence_downcast(seq), n, vm).map(Into::into) }), item: atomic_func!(|seq, i, vm| PyDeque::sequence_downcast(seq).__getitem__(i, vm)), @@ -670,6 +901,47 @@ mod _collections { } } + /// Compare two iterator streams, applying the requested operation to the first + /// unequal pair. Unlike indexed sequence comparisons, even equality compares + /// that pair again, and inequality dispatches its own comparison method. + fn deque_richcompare_iterators( + lhs: &PyIter, + rhs: &PyIter, + op: PyComparisonOp, + vm: &VirtualMachine, + ) -> PyResult { + loop { + let a = match lhs.next(vm)? { + PyIterReturn::Return(item) => Some(item), + PyIterReturn::StopIteration(_) => None, + }; + // Both streams advance, including when the left stream just ended. + let b = rhs.next(vm).map(|result| match result { + PyIterReturn::Return(item) => Some(item), + PyIterReturn::StopIteration(_) => None, + }); + let result = match (&a, &b) { + (Some(a), Ok(Some(b))) => { + a.rich_compare_bool(b, PyComparisonOp::Eq, vm) + .and_then(|equal| { + if equal { + Ok(None) + } else { + a.rich_compare_bool(b, op, vm).map(Some) + } + }) + } + (_, Ok(b)) => Ok(Some(op.eval_ord(a.is_some().cmp(&b.is_some())))), + (_, Err(error)) => Err(error.clone()), + }; + // Finalizers may mutate either stream before the next iteration. + drop(a); + if let Some(result) = result? { + return Ok(result); + } + } + } + impl Comparable for PyDeque { fn cmp( zelf: &Py, @@ -677,24 +949,25 @@ mod _collections { op: PyComparisonOp, vm: &VirtualMachine, ) -> PyResult { + let other = class_or_notimplemented!(Self, other); if let Some(res) = op.identical_optimization(zelf, other) { return Ok(res.into()); } - let other = class_or_notimplemented!(Self, other); - crate::iter::richcompare_mutating_seqs( - |i| { - let lhs = zelf.borrow_deque(); - (lhs.len(), lhs.get(i).cloned()) - }, - |i| { - let rhs = other.borrow_deque(); - (rhs.len(), rhs.get(i).cloned()) - }, - op, - vm, - ) - .map(PyComparisonValue::Implemented) + if matches!(op, PyComparisonOp::Eq | PyComparisonOp::Ne) { + let lhs_len = zelf.borrow_deque().len(); + let rhs_len = other.borrow_deque().len(); + if lhs_len != rhs_len { + return Ok((op == PyComparisonOp::Ne).into()); + } + } + + let lhs = zelf.as_object().get_iter(vm)?; + let rhs = other.as_object().get_iter(vm)?; + let result = deque_richcompare_iterators(&lhs, &rhs, op, vm); + // Iterator finalizers run in operand order, after item cleanup. + drop(lhs); + result.map(PyComparisonValue::Implemented) } } @@ -704,33 +977,68 @@ mod _collections { } } + fn deque_repr_elements(deque: &Py, vm: &VirtualMachine) -> PyResult> { + let iter = deque.as_object().get_iter(vm)?; + let mut elements = Vec::new(); + let result = (|| { + let hint = vm + .length_hint_opt(deque.as_object().to_owned())? + .unwrap_or(8); + elements + .try_reserve_exact(hint) + .map_err(|_| vm.no_memory_error())?; + for item in iter.iter::(vm)? { + let item = item?; + if elements.len() == elements.capacity() { + elements.try_reserve(1).map_err(|_| vm.no_memory_error())?; + } + elements.push(item); + } + if elements.len() < elements.capacity().div_ceil(2) { + elements.shrink_to_fit(); + } + Ok(()) + })(); + // PySequence_List releases its iterator before a partial list on error. + // Its elements then run finalizers backwards, with the repr guard held. + drop(iter); + if let Err(error) = result { + elements.into_iter().rev().for_each(drop); + return Err(error); + } + Ok(elements) + } + impl Representable for PyDeque { #[inline] fn repr(zelf: &Py, vm: &VirtualMachine) -> PyResult> { - let deque = zelf.borrow_deque().clone(); + let Some(guard) = ReprGuard::enter(vm, zelf.as_object()) else { + return Ok(vm.ctx.intern_str("[...]").to_owned()); + }; + // PySequence_List respects subclass iteration and length hints, + // even when the underlying deque is empty. + let elements = deque_repr_elements(zelf, vm)?; + let maxlen = zelf.maxlen_value(); let class = zelf.class(); - let class_name = class.name(); - let closing_part = zelf - .maxlen - .map_or_else(|| "]".to_owned(), |maxlen| format!("], maxlen={maxlen}")); + let class_name = class.name().to_string(); + let closing_part = + maxlen.map_or_else(|| "]".to_owned(), |maxlen| format!("], maxlen={maxlen}")); let empty = format!("{class_name}([{closing_part})"); - if zelf.__len__() == 0 { - return Ok(vm.ctx.new_str(empty)); - } - - if let Some(_guard) = ReprGuard::enter(vm, zelf.as_object()) { - Ok(vm.ctx.new_str(collection_repr( - Some(&class_name), - "[", - &closing_part, - &empty, - deque.iter().map(|o| &**o), - vm, - )?)) - } else { - Ok(vm.ctx.intern_str("[...]").to_owned()) - } + let result = collection_repr( + Some(&class_name), + "[", + &closing_part, + &empty, + elements.iter().map(|o| &**o), + vm, + ) + .map(|repr| vm.ctx.new_str(repr)); + // The temporary list releases its elements backwards, after the + // recursion guard, including when an element's repr raised. + drop(guard); + elements.into_iter().rev().for_each(drop); + result } fn repr_str(_zelf: &Py, _vm: &VirtualMachine) -> PyResult { @@ -771,21 +1079,20 @@ mod _collections { _vm: &VirtualMachine, ) -> PyResult { let iter = Self::new(deque); - if let OptionalArg::Present(index) = index { - let index = max(index, 0) as usize; - iter.internal.lock().position = index; - iter.counter - .store(iter.counter.load().saturating_sub(index)); - } + deque_iter_skip(&iter.internal, &iter.counter, index); Ok(iter) } } impl PyDequeIterator { pub(crate) fn new(deque: PyDequeRef) -> Self { + let (state, len) = { + let data = deque.data.read(); + (deque.state.load(), data.items.len()) + }; Self { - state: deque.state.load(), - counter: AtomicCell::new(deque.__len__()), + state, + counter: AtomicCell::new(len), internal: PyMutex::new(PositionIterInternal::new(deque, 0)), } } @@ -803,76 +1110,113 @@ mod _collections { zelf: PyRef, vm: &VirtualMachine, ) -> (PyTypeRef, (PyDequeRef, PyObjectRef)) { - let internal = zelf.internal.lock(); - let deque = match &internal.status { - Active(obj) => obj.clone(), - Exhausted => PyDeque::default().into_ref(&vm.ctx), - }; + let (deque, position) = deque_iter_reduce(&zelf.internal, &zelf.counter); ( zelf.class().to_owned(), - (deque, vm.ctx.new_int(internal.position).into()), + (deque, vm.ctx.new_int(position).into()), ) } } impl SelfIter for PyDequeIterator {} - /// Whether the deque moved under an iterator that captured `state`. What is - /// left to walk is emptied before the error goes out, the way - /// `deque_iternext()` zeroes its counter before it raises. - fn deque_moved( - internal: &PositionIterInternal, - state: usize, + fn deque_iter_skip( + internal: &PyMutex>, counter: &AtomicCell, - ) -> bool { - let Active(deque) = &internal.status else { - return false; - }; - if state == deque.state.load() { - return false; + index: OptionalArg, + ) { + if let OptionalArg::Present(index) = index { + let mut internal = internal.lock(); + let index = (max(index, 0) as usize).min(counter.load()); + internal.position = index; + counter.store(counter.load() - index); } - counter.store(0); - true } - /// Hand back the element at the position the iterator keeps, `at` reaching - /// for it. Both deque iterators end here; they differ in whether they look - /// at the deque or at the count first. - fn deque_take( - internal: &mut PositionIterInternal, + fn deque_iter_reduce( + internal: &PyMutex>, counter: &AtomicCell, - at: impl FnOnce(&VecDeque, usize) -> Option, - ) -> (PyResult, Option) { - let item = match &internal.status { - Active(deque) if counter.load() != 0 => at(&deque.borrow_deque(), internal.position), - _ => None, - }; - let Some(item) = item else { - counter.store(0); - return (Ok(PyIterReturn::StopIteration(None)), internal.exhaust()); + ) -> (PyDequeRef, isize) { + let internal = internal.lock(); + // Deque iterators retain their owner even after exhaustion or mutation. + let Active(deque) = &internal.status else { + unreachable!("deque iterators retain their owner"); }; - internal.position += 1; - counter.store(counter.load() - 1); - (Ok(PyIterReturn::Return(item)), None) + let data = deque.data.read(); + let position = data.items.len() as isize - counter.load() as isize; + (deque.clone(), position) } - fn deque_mutated(vm: &VirtualMachine) -> PyResult { - Err(vm.new_runtime_error("deque mutated during iteration")) + enum DequeStep { + Item(PyObjectRef), + Exhausted, + Mutated, } - impl IterNext for PyDequeIterator { - fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_step(&zelf.internal, |internal| { + impl DequeStep { + fn into_result(self, vm: &VirtualMachine) -> PyResult { + match self { + Self::Item(item) => Ok(PyIterReturn::Return(item)), + Self::Exhausted => Ok(PyIterReturn::StopIteration(None)), + Self::Mutated => Err(vm.new_runtime_error("deque mutated during iteration")), + } + } + } + + fn deque_step( + internal: &PyMutex>, + state: usize, + counter: &AtomicCell, + reverse: bool, + ) -> DequeStep { + let mut guard = internal.lock(); + let internal = &mut *guard; + // The count before the deque, as in `dequereviter_next()`, so + // an iterator that has raised once runs out instead. + if reverse && counter.load() == 0 { + return DequeStep::Exhausted; + } + let item = match &internal.status { + Active(deque) => { + let data = deque.data.read(); // The deque before the count, as in `deque_iternext()`, so an // iterator still holding a deque that moved raises again on // every call rather than running out after the first. - if deque_moved(internal, zelf.state, &zelf.counter) { - return (deque_mutated(vm), None); + if state != deque.state.load() { + counter.store(0); + return DequeStep::Mutated; } - deque_take(internal, &zelf.counter, |deque, pos| { - deque.get(pos).cloned() - }) - }) + if counter.load() == 0 { + None + } else { + let index = if reverse { + data.items.len().checked_sub(internal.position + 1) + } else { + Some(internal.position) + }; + let item = index.and_then(|index| data.items.get(index).cloned()); + if item.is_some() { + internal.position += 1; + counter.store(counter.load() - 1); + } else { + counter.store(0); + } + item + } + } + Exhausted => None, + }; + if let Some(item) = item { + DequeStep::Item(item) + } else { + counter.store(0); + DequeStep::Exhausted + } + } + + impl IterNext for PyDequeIterator { + fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + deque_step(&zelf.internal, zelf.state, &zelf.counter, false).into_result(vm) } } @@ -898,12 +1242,7 @@ mod _collections { _vm: &VirtualMachine, ) -> PyResult { let iter = Py::::__reversed__(deque); - if let OptionalArg::Present(index) = index { - let index = max(index, 0) as usize; - iter.internal.lock().position = index; - iter.counter - .store(iter.counter.load().saturating_sub(index)); - } + deque_iter_skip(&iter.internal, &iter.counter, index); Ok(iter) } } @@ -920,14 +1259,10 @@ mod _collections { zelf: PyRef, vm: &VirtualMachine, ) -> (PyTypeRef, (PyDequeRef, PyObjectRef)) { - let internal = zelf.internal.lock(); - let deque = match &internal.status { - Active(obj) => obj.clone(), - Exhausted => PyDeque::default().into_ref(&vm.ctx), - }; + let (deque, position) = deque_iter_reduce(&zelf.internal, &zelf.counter); ( zelf.class().to_owned(), - (deque, vm.ctx.new_int(internal.position).into()), + (deque, vm.ctx.new_int(position).into()), ) } } @@ -936,20 +1271,7 @@ mod _collections { impl IterNext for PyReverseDequeIterator { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - locked_step(&zelf.internal, |internal| { - // The count before the deque, as in `dequereviter_next()`, so - // an iterator that has raised once runs out instead. - if zelf.counter.load() != 0 && deque_moved(internal, zelf.state, &zelf.counter) { - return (deque_mutated(vm), None); - } - deque_take(internal, &zelf.counter, |deque, pos| { - deque - .len() - .checked_sub(pos + 1) - .and_then(|pos| deque.get(pos)) - .cloned() - }) - }) + deque_step(&zelf.internal, zelf.state, &zelf.counter, true).into_result(vm) } } @@ -1006,7 +1328,7 @@ mod _collections { if let Some(f) = factory { let value = f.call((), vm)?; - self.dict.setdefault(object, value, vm) + self.dict.setdefault_value(object, value, vm) } else { Err(vm.new_key_error(object)) } @@ -1061,18 +1383,10 @@ mod _collections { fn __or__(lhs: &PyObject, rhs: PyObjectRef, vm: &VirtualMachine) -> PyResult { let not_implemented = || Ok(vm.ctx.not_implemented.clone().into()); - let (default_factory, dict) = if let Some(zelf) = lhs.downcast_ref::() { - if !rhs.fast_isinstance(vm.ctx.types.dict_type) { - return not_implemented(); - } - - (zelf.default_factory.load_owned(), zelf.dict.copy()) + let (zelf, other) = if let Some(zelf) = lhs.downcast_ref::() { + (zelf, &*rhs) } else if let Some(zelf) = rhs.downcast_ref::() { - let Some(dict) = lhs.downcast_ref::() else { - return not_implemented(); - }; - - (zelf.default_factory.load_owned(), dict.copy()) + (zelf, lhs) } else { return Err(vm.new_type_error(format!( "unsupported operand type(s) for |: '{}' and '{}'", @@ -1080,17 +1394,23 @@ mod _collections { rhs.class().name() ))); }; - - dict.update(rhs.into(), KwArgs::default(), vm)?; - - Ok(Self { - dict, - default_factory: match default_factory { - Some(factory) => PyAtomicRef::from(Some(factory)), - None => PyAtomicRef::new_empty(), - }, + if PyAnyDict::from_object(other).is_none() { + return not_implemented(); } - .to_pyobject(vm)) + + let factory = zelf + .default_factory + .load_owned() + .unwrap_or_else(|| vm.ctx.none()); + let new = zelf + .class() + .as_object() + .call((factory, lhs.to_owned()), vm)?; + let dict = new + .downcast_ref::() + .ok_or_else(|| vm.new_system_error("bad argument to internal function"))?; + dict.merge_object(rhs, vm)?; + Ok(new) } } @@ -1193,11 +1513,11 @@ mod _collections { for key in iter { let key = key?; let hash = key.hash(vm)?; - let count = match entries.get_known_hash(vm, &*key, hash)? { + let count = match entries.get(vm, &*key, hash)? { Some(old) => vm._add(&old, one.as_object())?, None => one.clone().into(), }; - entries.insert_known_hash(vm, &*key, hash, count)?; + entries.insert(vm, &*key, hash, count)?; } return Ok(()); } diff --git a/crates/vm/src/stdlib/_collections/ordered_dict.rs b/crates/vm/src/stdlib/_collections/ordered_dict.rs index 4ba9777fef5..b507d42a249 100644 --- a/crates/vm/src/stdlib/_collections/ordered_dict.rs +++ b/crates/vm/src/stdlib/_collections/ordered_dict.rs @@ -7,18 +7,15 @@ pub(crate) mod ordered_dict { AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, atomic_func, builtins::{ - PyDict, PyGenericAlias, PyMappingProxy, PyTuple, PyTypeRef, - dict::{ - PyDictItems, set_inner_number_or, set_inner_number_subtract, set_inner_number_xor, - set_item_view_number_xor, set_view_number_and, - }, + PyAnyDict, PyDict, PyGenericAlias, PyTypeRef, + dict::{PyDictItems, PyDictKeys, PyDictValues}, iter::builtins_iter, }, class::StaticType, common::{hash::PyHash, lock::PyMutex}, convert::ToPyObject, dict_inner::DictKey, - function::{ArgIterable, FuncArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, + function::{KwArgs, OptionalArg, PyArithmeticValue, PyComparisonValue}, object::{Traverse, TraverseFn}, protocol::{PyIter, PyIterReturn, PyMappingMethods, PyNumberMethods, PySequenceMethods}, recursion::ReprGuard, @@ -137,7 +134,7 @@ pub(crate) mod ordered_dict { traverse = "manual" )] #[derive(Debug)] - struct PyOrderedDict { + pub(crate) struct PyOrderedDict { dict: PyDict, links: PyMutex, } @@ -362,11 +359,26 @@ pub(crate) mod ordered_dict { #[pymethod] fn clear(&self) { self.dict.clear(); - let mut links = self.links.lock(); - *links = ODictLinks { - state: links.state.wrapping_add(1), - ..ODictLinks::default() + let mut detached = { + let mut links = self.links.lock(); + let replacement = ODictLinks { + state: links.state, + ..ODictLinks::default() + }; + core::mem::replace(&mut *links, replacement) }; + // Publish empty links before finalizers run, then release keys in + // linked order, which may differ from allocation/recycled slots. + let mut current = detached.first; + while let Some(idx) = current { + let Some(node) = detached.nodes.get_mut(idx).and_then(Option::take) else { + break; + }; + current = node.next; + } + drop(detached); + let mut links = self.links.lock(); + links.state = links.state.wrapping_add(1); } #[pymethod] @@ -406,17 +418,16 @@ pub(crate) mod ordered_dict { } #[pymethod] - fn update(zelf: PyRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - if args.args.len() > 1 { - return Err(vm.new_type_error(format!( - "update expected at most 1 argument, got {}", - args.args.len() - ))); - } - if let Some(arg) = args.args.first() { - odict_update_arg(zelf.as_object(), arg.clone(), vm)?; + fn update( + zelf: PyRef, + other: OptionalArg, + kwargs: KwArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + if let OptionalArg::Present(other) = other { + odict_update_arg(zelf.as_object(), other, vm)?; } - for (key, value) in args.kwargs { + for (key, value) in kwargs { zelf.as_object().set_item(&key, value, vm)?; } Ok(()) @@ -488,6 +499,17 @@ pub(crate) mod ordered_dict { fn move_to_end(&self, args: ODictMoveToEndArgs, vm: &VirtualMachine) -> PyResult<()> { let key = args.key; let last = args.last; + { + let links = self.links.lock(); + let endpoint = if last { links.last } else { links.first }; + let Some(node) = endpoint.and_then(|idx| links.nodes.get(idx)?.as_ref()) else { + drop(links); + return Err(vm.new_key_error(key)); + }; + if node.key.is(&key) { + return Ok(()); + } + } let hash = key.key_hash(vm)?; let Some(idx) = self.find_node(&key, hash, vm)? else { return Err(vm.new_key_error(key)); @@ -530,17 +552,17 @@ pub(crate) mod ordered_dict { #[pymethod] fn keys(zelf: PyRef, vm: &VirtualMachine) -> PyObjectRef { - PyODictKeys { od: zelf }.to_pyobject(vm) + PyODictKeys::new(zelf).to_pyobject(vm) } #[pymethod] fn values(zelf: PyRef, vm: &VirtualMachine) -> PyObjectRef { - PyODictValues { od: zelf }.to_pyobject(vm) + PyODictValues::new(zelf).to_pyobject(vm) } #[pymethod] fn items(zelf: PyRef, vm: &VirtualMachine) -> PyObjectRef { - PyOrderedDictItems { od: zelf }.to_pyobject(vm) + PyOrderedDictItems::new(zelf).to_pyobject(vm) } #[pymethod] @@ -550,13 +572,11 @@ pub(crate) mod ordered_dict { #[pymethod] fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + // State hooks run before items(), and their result is preserved even + // when a subclass deliberately returns an empty dictionary. + let state = vm.call_method(zelf.as_object(), "__getstate__", ())?; let items = zelf.as_object().get_attr("items", vm)?.call((), vm)?; let items_iter = PyIter::try_from_object(vm, items)?; - let state = vm.call_method(zelf.as_object(), "__getstate__", ())?; - let state = match state.downcast_ref::() { - Some(d) if d.__len__() == 0 => vm.ctx.none(), - _ => state, - }; Ok(vm .ctx .new_tuple(vec![ @@ -600,16 +620,10 @@ pub(crate) mod ordered_dict { impl DefaultConstructor for PyOrderedDict {} impl Initializer for PyOrderedDict { - type Args = FuncArgs; - - fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { - if args.args.len() > 1 { - return Err(vm.new_type_error(format!( - "OrderedDict expected at most 1 argument, got {}", - args.args.len() - ))); - } - Py::::update(zelf.to_owned(), args, vm) + type Args = (OptionalArg, KwArgs); + + fn init(zelf: &Py, (other, kwargs): Self::Args, vm: &VirtualMachine) -> PyResult<()> { + Py::::update(zelf.to_owned(), other, kwargs, vm) } } @@ -687,9 +701,7 @@ pub(crate) mod ordered_dict { fn as_number() -> &'static PyNumberMethods { static AS_NUMBER: PyNumberMethods = PyNumberMethods { or: Some(|a, b, vm| { - if !a.fast_isinstance(vm.ctx.types.dict_type) - || !b.fast_isinstance(vm.ctx.types.dict_type) - { + if PyAnyDict::from_object(a).is_none() || PyAnyDict::from_object(b).is_none() { return Ok(vm.ctx.not_implemented()); } let cls = if let Some(od) = a.downcast_ref::() { @@ -764,32 +776,78 @@ pub(crate) mod ordered_dict { } fn odict_update_arg(zelf: &PyObject, arg: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - if let Some(dict) = arg.downcast_ref_if_exact::(vm) { - for (key, value) in dict { + if (arg.class().is(vm.ctx.types.dict_type) || arg.class().is(vm.ctx.types.frozendict_type)) + && let Some(dict) = PyAnyDict::from_object(&arg) + { + // A destination's __setitem__ can mutate the source. CPython takes + // an items snapshot before calling any of those overrides. + let items = dict.items_vec(); + let result = items + .iter() + .try_for_each(|(key, value)| zelf.set_item(&**key, value.clone(), vm)); + // The snapshot is a list of tuples in CPython: release entries + // backwards, and each value before its key, after all callbacks. + for (_key, _value) in items.into_iter().rev() {} + return result; + } + if let Some(keys_fn) = vm.get_attribute_opt(&arg, "keys")? { + let keys = keys_fn.call((), vm)?; + let iter = PyIter::try_from_object(vm, keys)?; + for key in iter.iter::(vm)? { + let key = key?; + let value = arg.get_item(&*key, vm)?; zelf.set_item(&*key, value, vm)?; } return Ok(()); } - match arg.get_attr("keys", vm) { - Ok(keys_fn) => { - let keys = keys_fn.call((), vm)?; - let iter = PyIter::try_from_object(vm, keys)?; - for key in iter.iter::(vm)? { - let key = key?; - let value = arg.get_item(&*key, vm)?; - zelf.set_item(&*key, value, vm)?; - } - return Ok(()); + let pairs = match vm.get_attribute_opt(&arg, "items")? { + Some(items_fn) => items_fn.call((), vm)?, + None => arg, + }; + odict_add_pairs(zelf, pairs, vm) + } + + fn odict_add_pairs(zelf: &PyObject, pairs: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + // An iterator need not retain its iterable. Keep the container alive + // until all pair callbacks and the outer iterator have finished. + (|| { + let iter = PyIter::try_from_object(vm, pairs.clone())?; + for pair in iter.iter::(vm)? { + let pair = pair?; + let mut pair_iter = None; + let mut key = None; + let mut value = None; + let result = (|| { + let iterator = pair_iter.insert(PyIter::try_from_object(vm, pair.clone())?); + // Unlike dict.update(), OrderedDict unpacks at most three + // values and never consults a pair's length hint. + let key = key.insert(match iterator.next(vm)? { + PyIterReturn::Return(key) => key, + PyIterReturn::StopIteration(_) => { + return Err(vm.new_value_error("need more than 0 values to unpack")); + } + }); + let value = value.insert(match iterator.next(vm)? { + PyIterReturn::Return(value) => value, + PyIterReturn::StopIteration(_) => { + return Err(vm.new_value_error("need more than 1 value to unpack")); + } + }); + if let PyIterReturn::Return(unexpected) = iterator.next(vm)? { + drop(unexpected); + return Err(vm.new_value_error("too many values to unpack (expected 2)")); + } + zelf.set_item(&**key, value.clone(), vm) + })(); + // Finalizers may call back into the destination. Match the pair, + // iterator, key, value release order on both success and failure. + drop(pair); + drop(pair_iter); + drop(key); + result?; } - Err(e) if e.fast_isinstance(vm.ctx.exceptions.attribute_error) => {} - Err(e) => return Err(e), - } - let iter = PyIter::try_from_object(vm, arg)?; - for (index, element) in iter.iter::(vm)?.enumerate() { - let (key, value) = PyDict::update_sequence_pair(element?, index, vm)?; - zelf.set_item(&*key, value, vm)?; - } - Ok(()) + Ok(()) + })() } #[pyattr] @@ -886,15 +944,20 @@ pub(crate) mod ordered_dict { impl PyODictIter { fn collect_remaining(&self, vm: &VirtualMachine) -> PyResult> { - let Some(od) = self.od() else { - return Ok(Vec::new()); - }; + // Reduction consumes a copy through the normal iterator path so + // mutation checks and value lookup callbacks match next(). The + // original iterator must retain its position, including on error. + let copy = Self { + od: self.od.clone(), + kind: self.kind, + size: self.size, + state: self.state, + current: PyMutex::new(self.current.lock().clone()), + } + .into_ref(&vm.ctx); let mut out = Vec::new(); - let mut current = self.current.lock().clone(); - let reversed = self.kind & ODICT_ITER_REVERSED != 0; - while let Some(key) = current { - out.push(self.project(key.clone(), vm)?); - current = od.links.lock().next_after(&key, reversed); + while let PyIterReturn::Return(value) = Self::next(©, vm)? { + out.push(value); } Ok(out) } @@ -927,312 +990,129 @@ pub(crate) mod ordered_dict { } } - fn odict_view_eq( - od: &PyRef, - kind: u8, - other: &PyObject, - vm: &VirtualMachine, - ) -> PyResult { - if kind == ODICT_ITER_VALUES { - return Ok(PyArithmeticValue::NotImplemented); - } - let set_like = other.fast_isinstance(vm.ctx.types.set_type) - || other.fast_isinstance(vm.ctx.types.frozenset_type) - || other.class().is(vm.ctx.types.dict_keys_type) - || other.class().is(vm.ctx.types.dict_items_type) - || other.downcast_ref::().is_some() - || other.downcast_ref::().is_some(); - if !set_like { - return Ok(PyArithmeticValue::NotImplemented); - } - let Ok(other_len) = other.length(vm) else { - return Ok(PyArithmeticValue::NotImplemented); - }; - if od.dict.__len__() != other_len { - return Ok(PyArithmeticValue::Implemented(false)); - } - let iter_obj = PyODictIter::new(od.clone(), kind).to_pyobject(vm); - let a_iter = PyIter::try_from_object(vm, iter_obj)?; - for item in a_iter.iter::(vm)? { - let item = item?; - if !other.sequence_unchecked().contains(&item, vm)? { - return Ok(PyArithmeticValue::Implemented(false)); - } - } - Ok(PyArithmeticValue::Implemented(true)) - } - - fn ordered_view_number_and(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { - let a_is_view = a.downcast_ref::().is_some() - || a.downcast_ref::().is_some(); - let (view, other) = if a_is_view { (a, b) } else { (b, a) }; - set_view_number_and(view, other, vm) - } - - fn ordered_item_view_number_xor(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { - let is_item_view = |obj: &PyObject| { - obj.downcast_ref::().is_some() - || obj.downcast_ref::().is_some() - }; - set_item_view_number_xor(a, b, is_item_view(a) && is_item_view(b), vm) - } - #[pyattr] - #[pyclass(name = "odict_keys", module = "builtins", unhashable = true, traverse)] - #[derive(Debug, PyPayload)] + #[pyclass(name = "odict_keys", module = false, base = PyDictKeys, traverse)] + #[derive(Debug)] struct PyODictKeys { - od: PyRef, + view: PyDictKeys, } - #[pyclass(with(Iterable, Comparable, AsMapping, AsSequence, AsNumber))] - impl Py { - #[pymethod] - fn __reversed__(&self, vm: &VirtualMachine) -> PyObjectRef { - PyODictIter::new(self.od.clone(), ODICT_ITER_KEYS | ODICT_ITER_REVERSED).to_pyobject(vm) - } - - #[pygetset] - fn mapping(&self, vm: &VirtualMachine) -> PyResult { - PyMappingProxy::from_object(self.od.as_object().to_owned(), vm) - } - - #[pymethod] - fn isdisjoint(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - for item in other.iter(vm)? { - if self.od.dict.inner_getitem_opt(&*item?, vm)?.is_some() { - return Ok(false); - } + impl PyODictKeys { + fn new(od: PyRef) -> Self { + let dict = PyAnyDict::from_object(od.as_object()) + .expect("OrderedDict has a dict payload") + .to_owned(); + Self { + view: PyDictKeys::new(dict), } - Ok(true) } - } - impl AsMapping for PyODictKeys { - fn as_mapping() -> &'static PyMappingMethods { - static AS_MAPPING: PyMappingMethods = PyMappingMethods { - length: atomic_func!(|mapping, _vm| Ok(PyODictKeys::mapping_downcast(mapping) - .od - .dict - .__len__())), - ..PyMappingMethods::NOT_IMPLEMENTED - }; - &AS_MAPPING + fn od(&self) -> &Py { + self.view + .dict + .as_object() + .downcast_ref::() + .expect("ordered dict views own an OrderedDict") } } - impl AsSequence for PyODictKeys { - fn as_sequence() -> &'static PySequenceMethods { - static AS_SEQUENCE: PySequenceMethods = PySequenceMethods { - length: atomic_func!(|seq, _vm| Ok(PyODictKeys::sequence_downcast(seq) - .od - .dict - .__len__())), - contains: atomic_func!(|seq, target, vm| { - PyODictKeys::sequence_downcast(seq) - .od - .dict - .inner_getitem_opt(target, vm) - .map(|v| v.is_some()) - }), - ..PySequenceMethods::NOT_IMPLEMENTED - }; - &AS_SEQUENCE + #[pyclass(flags(DISALLOW_INSTANTIATION), with(Iterable))] + impl Py { + #[pymethod] + fn __reversed__(&self, vm: &VirtualMachine) -> PyObjectRef { + PyODictIter::new(self.od().to_owned(), ODICT_ITER_KEYS | ODICT_ITER_REVERSED) + .to_pyobject(vm) } } impl Iterable for PyODictKeys { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - Ok(PyODictIter::new(zelf.od.clone(), ODICT_ITER_KEYS).to_pyobject(vm)) - } - } - - impl Comparable for PyODictKeys { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - op.eq_only(|| odict_view_eq(&zelf.od, ODICT_ITER_KEYS, other, vm)) - } - } - - impl AsNumber for PyODictKeys { - fn as_number() -> &'static PyNumberMethods { - static AS_NUMBER: PyNumberMethods = PyNumberMethods { - subtract: Some(set_inner_number_subtract), - and: Some(ordered_view_number_and), - xor: Some(set_inner_number_xor), - or: Some(set_inner_number_or), - ..PyNumberMethods::NOT_IMPLEMENTED - }; - &AS_NUMBER + Ok(PyODictIter::new(zelf.od().to_owned(), ODICT_ITER_KEYS).to_pyobject(vm)) } } #[pyattr] - #[pyclass(name = "odict_values", module = "builtins", traverse)] - #[derive(Debug, PyPayload)] + #[pyclass(name = "odict_values", module = false, base = PyDictValues, traverse)] + #[derive(Debug)] struct PyODictValues { - od: PyRef, + view: PyDictValues, } - #[pyclass(with(Iterable, Comparable, AsMapping))] - impl Py { - #[pymethod] - fn __reversed__(&self, vm: &VirtualMachine) -> PyObjectRef { - PyODictIter::new(self.od.clone(), ODICT_ITER_VALUES | ODICT_ITER_REVERSED) - .to_pyobject(vm) + impl PyODictValues { + fn new(od: PyRef) -> Self { + let dict = PyAnyDict::from_object(od.as_object()) + .expect("OrderedDict has a dict payload") + .to_owned(); + Self { + view: PyDictValues::new(dict), + } } - #[pygetset] - fn mapping(&self, vm: &VirtualMachine) -> PyResult { - PyMappingProxy::from_object(self.od.as_object().to_owned(), vm) + fn od(&self) -> &Py { + self.view + .dict + .as_object() + .downcast_ref::() + .expect("ordered dict views own an OrderedDict") } } - impl AsMapping for PyODictValues { - fn as_mapping() -> &'static PyMappingMethods { - static AS_MAPPING: PyMappingMethods = PyMappingMethods { - length: atomic_func!(|mapping, _vm| Ok(PyODictValues::mapping_downcast(mapping) - .od - .dict - .__len__())), - ..PyMappingMethods::NOT_IMPLEMENTED - }; - &AS_MAPPING + #[pyclass(flags(DISALLOW_INSTANTIATION), with(Iterable))] + impl Py { + #[pymethod] + fn __reversed__(&self, vm: &VirtualMachine) -> PyObjectRef { + PyODictIter::new( + self.od().to_owned(), + ODICT_ITER_VALUES | ODICT_ITER_REVERSED, + ) + .to_pyobject(vm) } } impl Iterable for PyODictValues { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - Ok(PyODictIter::new(zelf.od.clone(), ODICT_ITER_VALUES).to_pyobject(vm)) - } - } - - impl Comparable for PyODictValues { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - op.eq_only(|| odict_view_eq(&zelf.od, ODICT_ITER_VALUES, other, vm)) + Ok(PyODictIter::new(zelf.od().to_owned(), ODICT_ITER_VALUES).to_pyobject(vm)) } } #[pyattr] - #[pyclass(name = "odict_items", module = "builtins", unhashable = true, traverse)] - #[derive(Debug, PyPayload)] - pub(crate) struct PyOrderedDictItems { - od: PyRef, + #[pyclass(name = "odict_items", module = false, base = PyDictItems, traverse)] + #[derive(Debug)] + struct PyOrderedDictItems { + view: PyDictItems, } - #[pyclass(with(Iterable, Comparable, AsMapping, AsSequence, AsNumber))] - impl Py { - #[pymethod] - fn __reversed__(&self, vm: &VirtualMachine) -> PyObjectRef { - PyODictIter::new(self.od.clone(), ODICT_ITER_ITEMS | ODICT_ITER_REVERSED) - .to_pyobject(vm) - } - - #[pygetset] - fn mapping(&self, vm: &VirtualMachine) -> PyResult { - PyMappingProxy::from_object(self.od.as_object().to_owned(), vm) - } - - #[pymethod] - fn isdisjoint(&self, other: ArgIterable, vm: &VirtualMachine) -> PyResult { - for item in other.iter(vm)? { - let item = item?; - let Some(needle) = item.downcast_ref::() else { - continue; - }; - if needle.as_slice().len() != 2 { - continue; - } - let Some(found) = self.od.dict.inner_getitem_opt(&*needle.as_slice()[0], vm)? - else { - continue; - }; - if vm.identical_or_equal(&found, &needle.as_slice()[1])? { - return Ok(false); - } + impl PyOrderedDictItems { + fn new(od: PyRef) -> Self { + let dict = PyAnyDict::from_object(od.as_object()) + .expect("OrderedDict has a dict payload") + .to_owned(); + Self { + view: PyDictItems::new(dict), } - Ok(true) } - } - impl AsMapping for PyOrderedDictItems { - fn as_mapping() -> &'static PyMappingMethods { - static AS_MAPPING: PyMappingMethods = PyMappingMethods { - length: atomic_func!(|mapping, _vm| Ok(PyOrderedDictItems::mapping_downcast( - mapping - ) - .od + fn od(&self) -> &Py { + self.view .dict - .__len__())), - ..PyMappingMethods::NOT_IMPLEMENTED - }; - &AS_MAPPING + .as_object() + .downcast_ref::() + .expect("ordered dict views own an OrderedDict") } } - impl AsSequence for PyOrderedDictItems { - fn as_sequence() -> &'static PySequenceMethods { - static AS_SEQUENCE: PySequenceMethods = PySequenceMethods { - length: atomic_func!(|seq, _vm| Ok(PyOrderedDictItems::sequence_downcast(seq) - .od - .dict - .__len__())), - contains: atomic_func!(|seq, target, vm| { - let needle: &Py = match target.downcast_ref() { - Some(needle) => needle, - None => return Ok(false), - }; - if needle.as_slice().len() != 2 { - return Ok(false); - } - let zelf = PyOrderedDictItems::sequence_downcast(seq); - let key = &needle.as_slice()[0]; - let Some(found) = zelf.od.dict.inner_getitem_opt(&**key, vm)? else { - return Ok(false); - }; - vm.identical_or_equal(&found, &needle.as_slice()[1]) - }), - ..PySequenceMethods::NOT_IMPLEMENTED - }; - &AS_SEQUENCE + #[pyclass(flags(DISALLOW_INSTANTIATION), with(Iterable))] + impl Py { + #[pymethod] + fn __reversed__(&self, vm: &VirtualMachine) -> PyObjectRef { + PyODictIter::new(self.od().to_owned(), ODICT_ITER_ITEMS | ODICT_ITER_REVERSED) + .to_pyobject(vm) } } impl Iterable for PyOrderedDictItems { fn iter(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - Ok(PyODictIter::new(zelf.od.clone(), ODICT_ITER_ITEMS).to_pyobject(vm)) - } - } - - impl Comparable for PyOrderedDictItems { - fn cmp( - zelf: &Py, - other: &PyObject, - op: PyComparisonOp, - vm: &VirtualMachine, - ) -> PyResult { - op.eq_only(|| odict_view_eq(&zelf.od, ODICT_ITER_ITEMS, other, vm)) - } - } - - impl AsNumber for PyOrderedDictItems { - fn as_number() -> &'static PyNumberMethods { - static AS_NUMBER: PyNumberMethods = PyNumberMethods { - subtract: Some(set_inner_number_subtract), - and: Some(ordered_view_number_and), - xor: Some(ordered_item_view_number_xor), - or: Some(set_inner_number_or), - ..PyNumberMethods::NOT_IMPLEMENTED - }; - &AS_NUMBER + Ok(PyODictIter::new(zelf.od().to_owned(), ODICT_ITER_ITEMS).to_pyobject(vm)) } } } diff --git a/crates/vm/src/stdlib/_ctypes.rs b/crates/vm/src/stdlib/_ctypes.rs index 780b2bc0bd2..d7f2f1f3df2 100644 --- a/crates/vm/src/stdlib/_ctypes.rs +++ b/crates/vm/src/stdlib/_ctypes.rs @@ -16,12 +16,19 @@ use crate::{ }; pub(super) use array::PyCArray; +pub(crate) use base::BufferViewRegistry; pub(super) use base::{CArgValue, PyCData, PyCField, StgInfo, StgInfoFlags}; pub(super) use pointer::PyCPointer; pub(super) use simple::{PyCSimple, PyCSimpleType}; pub(super) use structure::PyCStructure; pub(super) use union::PyCUnion; +pub(super) fn is_borrowed_buffer(obj: &crate::PyObject) -> bool { + obj.downcast_ref::() + .is_some_and(|cdata| cdata.is_borrowed()) + || obj.downcast_ref::().is_some() +} + /// Extension for PyType to get StgInfo /// PyStgInfo_FromType impl Py { @@ -40,8 +47,11 @@ impl Py { .filter(|info| info.initialized) } - /// Get _type_ attribute as String (type code like "i", "d", etc.) + /// Get the scalar converter selected when the storage type was initialized. fn type_code(&self, vm: &VirtualMachine) -> Option { + if let Some(info) = self.stg_info_opt() { + return info.scalar_code.map(|code| code.to_string()); + } self.as_object() .get_attr("_type_", vm) .ok() @@ -56,7 +66,7 @@ impl Py { } else { let mut stg = StgInfo::default(); stg.flags |= StgInfoFlags::DICTFLAG_FINAL; - let _ = base.init_type_data(stg); + let _ = base.init_traced_type_data(stg); } } } @@ -92,24 +102,28 @@ pub(crate) use _ctypes::module_def; #[pymodule] pub(crate) mod _ctypes { use super::{PyCArray, PyCData, PyCPointer, PyCSimple, PyCStructure, PyCUnion}; - use crate::builtins::{PyType, PyTypeRef}; + use crate::builtins::{PyStr, PyType, PyTypeRef}; use crate::class::StaticType; #[cfg(windows)] use crate::convert::ToPyException; use crate::convert::ToPyObject; use crate::function::{ArgStrictInt, Either, OptionalArg}; use crate::types::Representable; + #[cfg(windows)] + use crate::types::{Constructor, Initializer}; use crate::{AsObject, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine}; use num_traits::ToPrimitive; // CArgObject - returned by byref() and paramfunc // tagPyCArgObject - #[pyclass(name = "CArgObject", module = "_ctypes", no_attr)] + #[pyclass(name = "CArgObject", module = "_ctypes", no_attr, traverse)] #[derive(Debug, PyPayload)] pub(crate) struct CArgObject { /// Type tag ('P', 'V', 'i', 'd', etc.) + #[pytraverse(skip)] pub tag: u8, /// The actual foreign-call value (mirrors union value) + #[pytraverse(skip)] pub value: super::CArgValue, /// Reference to original object (for memory safety) pub obj: PyObjectRef, @@ -118,8 +132,11 @@ pub(crate) mod _ctypes { pub keep: Option, /// Size for struct/union ('V' tag) #[allow(dead_code)] + #[pytraverse(skip)] pub size: usize, - /// Offset for byref() + /// Offset for byref(), read by Windows CopyComPointer. + #[cfg_attr(not(windows), allow(dead_code))] + #[pytraverse(skip)] pub offset: isize, } @@ -177,14 +194,16 @@ pub(crate) mod _ctypes { FfiValue::F32(v) => v as f64, _ => 0.0, }; + let v = crate::literal::float::to_string(v); Ok(format!("")) } - b'd' | b'g' => { + b'd' => { let v = match ffi_val { FfiValue::F64(v) => v, FfiValue::F32(v) => v as f64, _ => 0.0, }; + let v = crate::literal::float::to_string(v); Ok(format!("")) } b'c' => { @@ -233,8 +252,22 @@ pub(crate) mod _ctypes { } } - #[pyattr(name = "__version__")] - const __VERSION__: &str = "1.1.0"; + #[pyfunction] + fn __getattr__(name: PyObjectRef, vm: &VirtualMachine) -> PyResult { + if name.downcast_ref::().and_then(|name| name.to_str()) == Some("__version__") { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "'__version__' is deprecated and slated for removal in Python 3.20".to_owned(), + 1, + vm, + )?; + return Ok(vm.ctx.new_str("1.1.0").into()); + } + Err(vm.new_attribute_error(format!( + "module '_ctypes' has no attribute {}", + name.repr(vm)? + ))) + } // TODO: get properly #[pyattr] @@ -263,76 +296,49 @@ pub(crate) mod _ctypes { ) } - #[cfg(target_os = "windows")] - #[pyattr(name = "COMError", once)] - fn com_error(vm: &VirtualMachine) -> PyTypeRef { - use crate::PyObject; - use crate::builtins::type_::PyAttributes; - use crate::function::FuncArgs; - use crate::types::{PyTypeFlags, PyTypeSlots}; - - // Sets hresult, text, details as instance attributes in __init__ - // This function has InitFunc signature for direct slots.init use - fn comerror_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let (hresult, text, details): ( - Option, - Option, - Option, - ) = args.bind(vm)?; - let hresult = hresult.unwrap_or_else(|| vm.ctx.none()); - let text = text.unwrap_or_else(|| vm.ctx.none()); - let details = details.unwrap_or_else(|| vm.ctx.none()); - - // Set instance attributes - zelf.set_attr("hresult", hresult, vm)?; - zelf.set_attr("text", text.clone(), vm)?; - zelf.set_attr("details", details.clone(), vm)?; + /// Raised when a COM method call failed. + #[cfg(windows)] + #[pyattr] + #[pyexception(name = "COMError", module = "_ctypes", base = crate::builtins::PyException)] + #[derive(Debug)] + #[repr(transparent)] + struct PyComError(crate::builtins::PyException); - // self.args = args[1:] = (text, details) - // via: PyObject_SetAttrString(self, "args", PySequence_GetSlice(args, 1, size)) - let args_tuple: PyObjectRef = vm.ctx.new_tuple(vec![text, details]).into(); - zelf.set_attr("args", args_tuple, vm)?; + #[cfg(windows)] + #[pyexception(with(Initializer), flags(HEAPTYPE))] + impl PyComError {} + #[cfg(windows)] + impl Initializer for PyComError { + type Args = crate::function::FuncArgs; + + fn slot_init( + zelf: &crate::PyObject, + args: Self::Args, + vm: &VirtualMachine, + ) -> PyResult<()> { + let (hresult, text, details): (PyObjectRef, PyObjectRef, PyObjectRef) = + args.bind(vm)?; + let full_args = vec![hresult.clone(), text.clone(), details.clone()]; + // Match the observable attribute assignments before restoring the + // base payload directly, without invoking an overriding descriptor. + let short_args: PyObjectRef = + vm.ctx.new_tuple(vec![text.clone(), details.clone()]).into(); + zelf.set_attr("args", short_args, vm)?; + zelf.set_attr("hresult", hresult, vm)?; + zelf.set_attr("text", text, vm)?; + zelf.set_attr("details", details, vm)?; + crate::builtins::PyBaseException::slot_init( + zelf, + crate::function::FuncArgs::from(full_args), + vm, + )?; Ok(()) } - // Create exception type with IMMUTABLETYPE flag - let mut attrs = PyAttributes::default(); - attrs.insert( - vm.ctx.intern_str("__module__"), - vm.ctx.new_str("_ctypes").into(), - ); - attrs.insert( - vm.ctx.intern_str("__doc__"), - vm.ctx - .new_str("Raised when a COM method call failed.") - .into(), - ); - - // Create slots with IMMUTABLETYPE flag - let slots = PyTypeSlots { - name: "COMError", - flags: crate::types::AtomicPyTypeFlags::from_plain( - PyTypeFlags::HEAP_TYPE_DICT_IMMUTABLE, - ), - ..PyTypeSlots::default() - }; - - let exc_type = PyType::new_heap( - "COMError", - vec![vm.ctx.exceptions.exception_type.to_owned()], - attrs, - slots, - vm.ctx.types.type_type.to_owned(), - &vm.ctx, - ) - .unwrap(); - - // Set our custom init after new_heap, which runs init_slots that would - // otherwise overwrite slots.init with init_wrapper (due to __init__ in MRO). - exc_type.slots.init.store(Some(comerror_init)); - - exc_type + fn init(_zelf: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult<()> { + unreachable!("slot_init is defined") + } } #[pyfunction] @@ -400,6 +406,15 @@ pub(crate) mod _ctypes { Err(vm.new_type_error("this type has no size")) } + #[cfg(any(target_os = "linux", target_os = "android"))] + #[pyfunction(signature_from_flags)] + fn dllist(vm: &VirtualMachine) -> PyResult> { + rustpython_host_env::ctypes::dllist() + .into_iter() + .map(|name| vm.fsdecode(name).map(Into::into)) + .collect() + } + #[cfg(windows)] #[pyfunction(name = "LoadLibrary")] fn load_library_windows( @@ -416,8 +431,8 @@ pub(crate) mod _ctypes { } #[cfg(not(windows))] - #[pyfunction(name = "dlopen")] - fn load_library_unix( + #[pyfunction] + fn dlopen( name: Option, load_flags: OptionalArg, vm: &VirtualMachine, @@ -568,13 +583,16 @@ pub(crate) mod _ctypes { #[cfg(target_os = "windows")] #[pyfunction(name = "_check_HRESULT")] - fn check_hresult(_self: PyObjectRef, hr: i32, _vm: &VirtualMachine) -> i32 { - // TODO: fixme + pub(super) fn check_hresult(hr: i32, vm: &VirtualMachine) -> PyResult { if hr < 0 { - // vm.ctx.new_windows_error(hr) - todo!(); + let errno = crate::host_env::os::winerror_to_errno(hr); + let message = crate::host_env::uuid::format_error_message(hr); + let error = crate::exceptions::OSErrorBuilder::with_errno(errno, message, vm) + .winerror(hr.to_pyobject(vm)) + .build(vm); + return Err(error.upcast()); } - hr + Ok(hr) } #[pyfunction] @@ -635,7 +653,7 @@ pub(crate) mod _ctypes { .to_pyobject(vm)) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn alignment(object: Either, vm: &VirtualMachine) -> PyResult { use crate::builtins::PyType; @@ -769,6 +787,9 @@ pub(crate) mod _ctypes { // 5. Resize the buffer let new_size = size as usize; let mut buffer = cdata.buffer.write(); + if new_size == buffer.len() { + return Ok(()); + } let old_data = buffer.to_vec(); *buffer = Cow::Owned(rustpython_host_env::ctypes::resize_owned_bytes( &old_data, new_size, @@ -777,7 +798,7 @@ pub(crate) mod _ctypes { Ok(()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn get_errno() -> i32 { rustpython_host_env::ctypes::get_errno() } @@ -845,7 +866,7 @@ pub(crate) mod _ctypes { super::function::cast_impl(&obj, obj.clone(), &typ, vm) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn buffer_info(object: PyObjectRef, vm: &VirtualMachine) -> PyResult { // Determine if object is a type or an instance let is_type = object @@ -966,13 +987,13 @@ pub(crate) mod _ctypes { } } - #[pyfunction(name = "Py_INCREF")] + #[pyfunction(name = "Py_INCREF", signature_from_flags)] fn py_incref(object: PyObjectRef, _vm: &VirtualMachine) -> PyObjectRef { // TODO: object } - #[pyfunction(name = "Py_DECREF")] + #[pyfunction(name = "Py_DECREF", signature_from_flags)] fn py_decref(object: PyObjectRef, _vm: &VirtualMachine) -> PyObjectRef { // TODO: object @@ -996,9 +1017,11 @@ pub(crate) mod _ctypes { #[cfg(windows)] #[pyfunction(name = "FormatError")] - fn format_error_func(code: OptionalArg, _vm: &VirtualMachine) -> String { - rustpython_host_env::ctypes::format_error_message(code.into_option()) - .unwrap_or_else(|| "".to_string()) + fn format_error_func(code: OptionalArg, _vm: &VirtualMachine) -> String { + rustpython_host_env::ctypes::format_error_message( + code.into_option().map(|code| code as u32), + ) + .unwrap_or_else(|| "".to_string()) } #[cfg(windows)] diff --git a/crates/vm/src/stdlib/_ctypes/array.rs b/crates/vm/src/stdlib/_ctypes/array.rs index 0504688d85c..581861e3a28 100644 --- a/crates/vm/src/stdlib/_ctypes/array.rs +++ b/crates/vm/src/stdlib/_ctypes/array.rs @@ -1,5 +1,5 @@ -use super::StgInfo; use super::base::{CDATA_BUFFER_METHODS, PyCData}; +use super::{StgInfo, StgInfoFlags}; use crate::common::lock::LazyLock; use crate::sliceable::SaturatedSliceIter; use crate::{ @@ -10,17 +10,16 @@ use crate::{ }, class::StaticType, function::{ArgBytesLike, FuncArgs, PySetterValue}, - protocol::{BufferDescriptor, PyBuffer, PyMappingMethods, PyNumberMethods, PySequenceMethods}, - types::{AsBuffer, AsMapping, AsNumber, AsSequence, Constructor, Initializer}, + protocol::{BufferDescriptor, PyBuffer, PyMappingMethods, PySequenceMethods}, + types::{AsBuffer, AsMapping, AsSequence, Constructor, Initializer}, }; use alloc::borrow::Cow; use num_traits::{Signed, ToPrimitive}; use rustpython_host_env::ctypes::{ - ArrayElementWriteValue, DecodedValue, WCHAR_SIZE, WCharArrayWriteError, char_array_field_value, - int_to_sized_bytes, read_array_element, simple_type_size, uint_to_sized_bytes, - wchar_from_bytes, write_array_element, write_char_array_raw, write_char_array_value, - write_wchar_array_value, wstring_from_bytes, zeroed_bytes, + DecodedValue, WCHAR_SIZE, WCharArrayWriteError, char_array_field_value, read_array_element, + simple_type_size, wchar_from_bytes, write_char_array_raw, write_char_array_value, + write_wchar_array_value, wstring_from_bytes, }; fn cow_bytes_as_mut<'buf>(buffer: &'buf mut Cow<'_, [u8]>) -> &'buf mut [u8] { @@ -44,6 +43,27 @@ fn get_size_from_format(fmt: &str) -> usize { code.map_or(1, |c| simple_type_size(&c).unwrap_or(1)) } +pub(super) static CTYPE_SEQUENCE_METHODS: PySequenceMethods = PySequenceMethods { + repeat: Some(|seq, length, vm| repeat_type(seq.obj, length, vm)), + ..PySequenceMethods::NOT_IMPLEMENTED +}; + +pub(super) fn repeat_type(ctype: &PyObject, length: isize, vm: &VirtualMachine) -> PyResult { + if length < 0 { + return Err(vm.new_value_error(format!("Array length must be >= 0, not {length}"))); + } + let cls = ctype + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("expected type"))?; + if let Some(info) = cls.stg_info_opt() + && info.size != 0 + && length as usize > isize::MAX as usize / info.size + { + return Err(vm.new_overflow_error("array too large")); + } + array_type_from_ctype(ctype.to_owned(), length as usize, vm) +} + /// Creates array type for (element_type, length) /// Uses _array_type_cache to ensure identical calls return the same type object pub(super) fn array_type_from_ctype( @@ -256,7 +276,7 @@ impl Initializer for PyCArrayType { }; // 6. Check overflow (item_size != 0 && length > MAX / item_size) - if item_size != 0 && length > usize::MAX / item_size { + if item_size != 0 && length > isize::MAX as usize / item_size { return Err(vm.new_overflow_error("array too large")); } @@ -305,86 +325,31 @@ impl Initializer for PyCArrayType { } } -#[pyclass(flags(IMMUTABLETYPE), with(Initializer, AsNumber))] +#[pyclass(flags(IMMUTABLETYPE), with(Initializer, AsSequence))] impl PyCArrayType { - #[pygetset(name = "__pointer_type__")] - fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __pointer_type__(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { super::base::pointer_type_get(&zelf, vm) } - #[pygetset(name = "__pointer_type__", setter)] - fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___pointer_type__( + zelf: PyTypeRef, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { super::base::pointer_type_set(&zelf, value, vm) } #[pymethod] - fn from_param(zelf: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // zelf is the array type class that from_param was called on - let cls = zelf - .downcast::() - .map_err(|_| vm.new_type_error("from_param: expected a type"))?; - - // 1. If already an instance of the requested type, return it - if value.is_instance(cls.as_object(), vm)? { - return Ok(value); - } - - // 2. Check for CArgObject (PyCArg_CheckExact) - if let Some(carg) = value.downcast_ref::() { - // Check if the wrapped object is an instance of the requested type - if carg.obj.is_instance(cls.as_object(), vm)? { - return Ok(value); // Return the CArgObject as-is - } - } - - // 3. Check for _as_parameter_ attribute - if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); - } - - Err(vm.new_type_error(format!( - "expected {} instance instead of {}", - cls.name(), - value.class().name() - ))) + fn from_param(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + PyCData::from_param(zelf, value, vm) } } -impl AsNumber for PyCArrayType { - fn as_number() -> &'static PyNumberMethods { - static AS_NUMBER: PyNumberMethods = PyNumberMethods { - multiply: Some(|a, b, vm| { - // a is a type object whose metaclass is PyCArrayType (e.g., Array_5) - let n = b - .try_index(vm)? - .as_bigint() - .to_isize() - .ok_or_else(|| vm.new_overflow_error("array size too large"))?; - - if n < 0 { - return Err(vm.new_value_error(format!("Array length must be >= 0, not {n}"))); - } - - // Check for overflow before creating the new array type - let zelf_type = a - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("Expected type"))?; - - if let Some(stg_info) = zelf_type.stg_info_opt() { - let current_size = stg_info.size; - // Check if current_size * n would overflow - if current_size != 0 && (n as usize) > isize::MAX as usize / current_size { - return Err(vm.new_overflow_error("array too large")); - } - } - - // Use cached array type creation - // The element type of the new array is the current array type itself - array_type_from_ctype(a.to_owned(), n as usize, vm) - }), - ..PyNumberMethods::NOT_IMPLEMENTED - }; - &AS_NUMBER +impl AsSequence for PyCArrayType { + fn as_sequence() -> &'static PySequenceMethods { + &super::array::CTYPE_SEQUENCE_METHODS } } @@ -393,12 +358,23 @@ impl AsNumber for PyCArrayType { name = "Array", base = PyCData, metaclass = "PyCArrayType", - module = "_ctypes" + module = "_ctypes", + traverse = "manual" )] #[derive(Debug)] #[repr(transparent)] pub(crate) struct PyCArray(pub PyCData); +// SAFETY: this transparent wrapper owns exactly the references in its base. +unsafe impl crate::object::Traverse for PyCArray { + fn traverse(&self, tracer: &mut crate::object::TraverseFn<'_>) { + self.0.traverse(tracer); + } + fn clear(&mut self, out: &mut Vec) { + self.0.clear(out); + } +} + impl PyCArray { /// Get the type code of array element type (e.g., "c" for c_char, "u" for c_wchar) fn get_element_type_code(zelf: &Py, vm: &VirtualMachine) -> Option { @@ -519,33 +495,6 @@ impl PyCArray { PyGenericAlias::from_args(cls, object, vm) } - fn int_to_bytes(i: &malachite_bigint::BigInt, size: usize) -> Vec { - // Try unsigned first (handles values like 0xFFFFFFFF that overflow signed) - // then fall back to signed (handles negative values) - match size { - 1 => { - if let Some(v) = i.to_u8() { - vec![v] - } else { - vec![i.to_i8().unwrap_or(0) as u8] - } - } - 2 => i.to_u16().map_or_else( - || int_to_sized_bytes(i.to_i16().unwrap_or(0).into(), 2), - |v| uint_to_sized_bytes(v.into(), 2), - ), - 4 => i.to_u32().map_or_else( - || int_to_sized_bytes(i.to_i32().unwrap_or(0).into(), 4), - |v| uint_to_sized_bytes(v.into(), 4), - ), - 8 => i.to_u64().map_or_else( - || int_to_sized_bytes(i.to_i64().unwrap_or(0), 8), - |v| uint_to_sized_bytes(v, 8), - ), - _ => zeroed_bytes(size), - } - } - fn getitem_by_index(zelf: &Py, i: isize, vm: &VirtualMachine) -> PyResult { let stg = zelf.class().stg_info_opt(); let length = stg.as_ref().map_or(0, |i| i.length) as isize; @@ -556,23 +505,52 @@ impl PyCArray { let index = index as usize; let element_size = stg.as_ref().map_or(0, |i| i.element_size); let offset = index * element_size; + if let Some(element_type) = stg.as_ref().and_then(|info| info.element_type.as_ref()) + && !super::simple::returns_scalar(element_type) + { + let length = element_type.stg_info(vm)?.length; + let buffer = zelf.0.buffer.read(); + let Some(data) = buffer.get(offset..offset + element_size) else { + drop(buffer); + return Err(vm.new_index_error("invalid index")); + }; + // SAFETY: this element lies within the array's live buffer. The view + // retains the array; ctypes users must still avoid reallocating or + // concurrently accessing the same native memory through aliases. + let view = unsafe { + PyCData::from_base_obj( + data.as_ptr().cast_mut(), + element_size, + zelf.to_owned().into(), + index, + ) + }; + view.base_offset.store(offset); + view.length.store(length); + drop(buffer); + return view.into_view(element_type.clone(), vm); + } let type_code = Self::get_element_type_code(zelf, vm); - // Get target buffer and offset (base's buffer if available, otherwise own) - let base_obj = zelf.0.base.read().clone(); - let (buffer_lock, final_offset) = if let Some(cdata) = base_obj - .as_ref() - .and_then(|b| b.downcast_ref::()) + let buffer = zelf.0.buffer.read(); + if type_code.as_deref() == Some("O") { + let address = rustpython_host_env::ctypes::read_pointer_from_buffer( + &buffer[offset..offset + element_size], + ); + let slot = buffer.as_ptr().wrapping_add(offset) as usize; + drop(buffer); + return zelf.0.object_at(address, slot, Some(index), vm); + } + if let Some(element_type) = stg.as_ref().and_then(|info| info.element_type.as_ref()) + && super::simple::is_swapped(element_type) { - (&cdata.buffer, zelf.0.base_offset.load() + offset) - } else { - (&zelf.0.buffer, offset) - }; - - let buffer = buffer_lock.read(); + let mut bytes = buffer[offset..offset + element_size].to_vec(); + bytes.reverse(); + return Ok(super::base::bytes_to_pyobject(element_type, &bytes, vm)); + } Ok(Self::read_element_from_buffer( &buffer, - final_offset, + offset, element_size, type_code.as_deref(), vm, @@ -593,256 +571,58 @@ impl PyCArray { DecodedValue::Float(value) => vm.ctx.new_float(value).into(), DecodedValue::Signed(value) => vm.ctx.new_int(value).into(), DecodedValue::Unsigned(value) => vm.ctx.new_int(value).into(), + #[cfg(windows)] + DecodedValue::WideString(value) => vm.ctx.new_str(value).into(), DecodedValue::None => vm.ctx.none(), DecodedValue::Pointer(value) => vm.ctx.new_int(value).into(), DecodedValue::Bool(value) => vm.ctx.new_bool(value).into(), } } - /// Helper to write an element value to a buffer at given offset - /// This is extracted to share code between direct write and base-buffer write - #[allow(clippy::too_many_arguments)] - fn write_element_to_buffer( - buffer: &mut [u8], - offset: usize, - element_size: usize, - type_code: Option<&str>, - value: &PyObject, - zelf: &Py, - index: usize, - vm: &VirtualMachine, - ) -> PyResult<()> { - match type_code { - Some("c") => { - if let Some(b) = value.downcast_ref::() { - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Byte(b.as_bytes().first().copied().unwrap_or(0)), - ); - } else if let Ok(int_val) = value.try_int(vm) { - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Byte(int_val.as_bigint().to_u8().unwrap_or(0)), - ); - } else { - return Err(vm.new_type_error("an integer or bytes of length 1 is required")); - } - } - Some("u") => { - if let Some(s) = value.downcast_ref::() { - let code = s.as_wtf8().code_points().next().map_or(0, |c| c.to_u32()); - write_array_element(buffer, offset, ArrayElementWriteValue::Wchar(code)); - } else { - return Err(vm.new_type_error("unicode string expected")); - } - } - Some("z") => { - let (ptr_val, converted) = if value.is(&vm.ctx.none) { - (0usize, None) - } else if let Some(bytes) = value.downcast_ref::() { - let (kept_alive, ptr) = super::base::ensure_z_null_terminated(bytes, vm); - zelf.0.keep_alive(index, kept_alive); - (ptr, Some(value.to_owned())) - } else if let Some(simple) = value.downcast_ref::() - && value.class().type_code(vm).as_deref() == Some("z") - { - let buffer = simple.0.buffer.read(); - ( - rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer), - None, - ) - } else if let Ok(int_val) = value.try_index(vm) { - (int_val.as_bigint().to_usize().unwrap_or(0), None) - } else { - return Err(vm.new_type_error(format!( - "bytes or integer address expected instead of {} instance", - value.class().name() - ))); - }; - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Pointer { - value: ptr_val, - size: element_size, - }, - ); - if let Some(c) = converted { - return zelf.0.keep_ref(index, c, vm); - } - } - Some("Z") => { - let (ptr_val, converted) = if value.is(&vm.ctx.none) { - (0usize, None) - } else if let Some(s) = value.downcast_ref::() { - let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm); - (ptr, Some(holder)) - } else if let Some(simple) = value.downcast_ref::() - && value.class().type_code(vm).as_deref() == Some("Z") - { - let buffer = simple.0.buffer.read(); - ( - rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer), - None, - ) - } else if let Ok(int_val) = value.try_index(vm) { - (int_val.as_bigint().to_usize().unwrap_or(0), None) - } else { - return Err(vm.new_type_error("unicode string or integer address expected")); - }; - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Pointer { - value: ptr_val, - size: element_size, - }, - ); - if let Some(c) = converted { - return zelf.0.keep_ref(index, c, vm); - } - } - Some("f") => { - // c_float: convert int/float to f32 bytes - let f32_val = if let Ok(float_val) = value.try_float(vm) { - float_val.to_f64() as f32 - } else if let Ok(int_val) = value.try_int(vm) { - int_val.as_bigint().to_f64().unwrap_or(0.0) as f32 - } else { - return Err(vm.new_type_error("a float is required")); - }; - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Float { - value: f32_val.into(), - size: 4, - }, - ); - } - Some("d" | "g") => { - // c_double / c_longdouble: convert int/float to f64 bytes - let f64_val = if let Ok(float_val) = value.try_float(vm) { - float_val.to_f64() - } else if let Ok(int_val) = value.try_int(vm) { - int_val.as_bigint().to_f64().unwrap_or(0.0) - } else { - return Err(vm.new_type_error("a float is required")); - }; - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Float { - value: f64_val, - size: 8, - }, - ); - // For "g" type, remaining bytes stay zero - } - _ => { - // Handle ctypes instances (copy their buffer) - if let Some(cdata) = value.downcast_ref::() { - let src_buffer = cdata.buffer.read(); - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Bytes { - bytes: &src_buffer, - size: element_size, - }, - ); - // Other types: use int_to_bytes - } else if let Ok(int_val) = value.try_int(vm) { - let bytes = Self::int_to_bytes(int_val.as_bigint(), element_size); - write_array_element( - buffer, - offset, - ArrayElementWriteValue::Bytes { - bytes: &bytes, - size: element_size, - }, - ); - } else { - return Err(vm.new_type_error(format!( - "expected {} instance, not {}", - type_code.unwrap_or("value"), - value.class().name() - ))); - } - } - } - - // KeepRef - if super::base::PyCData::should_keep_ref(value) { - let to_keep = super::base::PyCData::get_kept_objects(value, vm); - zelf.0.keep_ref(index, to_keep, vm)?; - } - - Ok(()) - } - fn setitem_by_index( zelf: &Py, i: isize, value: &PyObject, vm: &VirtualMachine, ) -> PyResult<()> { - let stg = zelf.class().stg_info_opt(); - let length = stg.as_ref().map_or(0, |i| i.length) as isize; + let (length, element_size, element_type) = { + let stg = zelf.class().stg_info(vm)?; + ( + stg.length as isize, + stg.element_size, + stg.element_type + .clone() + .ok_or_else(|| vm.new_type_error("no element type"))?, + ) + }; let index = if i < 0 { length + i } else { i }; if index < 0 || index >= length { return Err(vm.new_index_error("invalid index")); } let index = index as usize; - let element_size = stg.as_ref().map_or(0, |i| i.element_size); - let offset = index * element_size; - let type_code = Self::get_element_type_code(zelf, vm); - - // Get target buffer and offset (base's buffer if available, otherwise own) - let base_obj = zelf.0.base.read().clone(); - let (buffer_lock, final_offset) = if let Some(cdata) = base_obj - .as_ref() - .and_then(|b| b.downcast_ref::()) + // A view's buffer already points to its element. Its base can be a + // pointer object, whose own buffer stores an address rather than data. + let write = if element_type + .stg_info(vm)? + .flags + .intersects(StgInfoFlags::TYPEFLAG_ISPOINTER | StgInfoFlags::TYPEFLAG_HASPOINTER) { - (&cdata.buffer, zelf.0.base_offset.load() + offset) + zelf.0 + .register_pyobject_view(index, index * element_size, element_size, vm)? } else { - (&zelf.0.buffer, offset) + super::base::CDataWrite::default() }; - - let mut buffer = buffer_lock.write(); - - // For shared memory (Cow::Borrowed), we need to write directly to the memory - // For owned memory (Cow::Owned), we can write to the owned buffer - match &mut *buffer { - Cow::Borrowed(slice) => { - // SAFETY: For from_buffer, the slice points to writable shared memory. - // Python's from_buffer requires writable buffer, so this is safe. - let owned_slice = - unsafe { rustpython_host_env::ctypes::borrowed_slice_as_mut(slice) }; - Self::write_element_to_buffer( - owned_slice, - final_offset, - element_size, - type_code.as_deref(), - value, - zelf, - index, - vm, - ) - } - Cow::Owned(vec) => Self::write_element_to_buffer( - vec, - final_offset, - element_size, - type_code.as_deref(), - value, - zelf, - index, - vm, - ), - } + let mut prepared = super::base::CDataValue::new( + &element_type, + value, + element_size, + super::simple::is_swapped(&element_type), + vm, + )?; + write.publish(vm)?; + zelf.0 + .write_value_at_offset(index * element_size, &mut prepared.bytes); + prepared.keep(&zelf.0, index, vm) } // Array_subscript @@ -1060,14 +840,14 @@ impl AsBuffer for PyCArray { } dim_desc.reverse(); - BufferDescriptor { - offset: 0, - len: buffer_len, - readonly: false, + BufferDescriptor::from_dim_desc( + buffer_len, + 0, + false, itemsize, - format: alloc::borrow::Cow::Owned(fmt), + alloc::borrow::Cow::Owned(fmt), dim_desc, - } + ) } else { // Fallback to simple buffer if no format/shape info BufferDescriptor::simple(buffer_len, false) diff --git a/crates/vm/src/stdlib/_ctypes/base.rs b/crates/vm/src/stdlib/_ctypes/base.rs index 2b697ef5558..5e6e5338851 100644 --- a/crates/vm/src/stdlib/_ctypes/base.rs +++ b/crates/vm/src/stdlib/_ctypes/base.rs @@ -1,11 +1,14 @@ #![allow(unreachable_pub)] use crate::builtins::{ - PyBytes, PyDict, PyList, PyMemoryView, PyStr, PyTuple, PyType, PyTypeRef, PyUtf8Str, + PyBytes, PyDict, PyInt, PyList, PyMemoryView, PyStr, PyTuple, PyType, PyTypeRef, PyUtf8Str, + memory::buffer_owner, }; use crate::class::StaticType; use crate::convert::ToPyObject; +use crate::dict_inner::DictKey; use crate::function::{ArgBytesLike, ArgStrictInt, OptionalArg, PySetterValue}; +use crate::object::{Traverse, TraverseFn}; use crate::protocol::{BufferMethods, PyBuffer}; use crate::types::{Constructor, GetDescriptor, Representable}; use crate::{ @@ -84,6 +87,8 @@ pub struct StgInfo { pub length: usize, // number of fields (for arrays/structures) pub proto: Option, // Only for Pointer/ArrayObject pub flags: StgInfoFlags, // type flags (TYPEFLAG_*, DICTFLAG_*) + // Scalar assignment uses the converter selected at type initialization. + pub(super) scalar_code: Option, // Array-specific fields pub element_type: Option, // _type_ for arrays @@ -95,6 +100,9 @@ pub struct StgInfo { // Function parameter conversion pub(super) paramfunc: ParamFunc, // how to pass to foreign functions + pub(super) argtypes: Option, + pub(super) restype: Option, + pub(super) checker: Option, // Byte order (for _swappedbytes_) pub big_endian: bool, // true if big endian, false if little endian @@ -122,6 +130,7 @@ impl core::fmt::Debug for StgInfo { .field("length", &self.length) .field("proto", &self.proto) .field("flags", &self.flags) + .field("scalar_code", &self.scalar_code) .field("element_type", &self.element_type) .field("element_size", &self.element_size) .field("format", &self.format) @@ -142,11 +151,15 @@ impl Default for StgInfo { length: 0, proto: None, flags: StgInfoFlags::empty(), + scalar_code: None, element_type: None, element_size: 0, format: None, shape: Vec::new(), paramfunc: ParamFunc::None, + argtypes: None, + restype: None, + checker: None, big_endian: cfg!(target_endian = "big"), // native endian by default field_layouts: Vec::new(), pointer_type: None, @@ -154,6 +167,27 @@ impl Default for StgInfo { } } +// SAFETY: these are the only Python references in the type's storage metadata. +unsafe impl Traverse for StgInfo { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.proto.traverse(tracer); + self.element_type.traverse(tracer); + self.pointer_type.traverse(tracer); + self.argtypes.traverse(tracer); + self.restype.traverse(tracer); + self.checker.traverse(tracer); + } + + fn clear(&mut self, out: &mut Vec) { + out.extend(self.proto.take().map(Into::into)); + out.extend(self.element_type.take().map(Into::into)); + out.extend(self.pointer_type.take()); + out.extend(self.argtypes.take()); + out.extend(self.restype.take()); + out.extend(self.checker.take()); + } +} + impl StgInfo { pub(crate) fn new(size: usize, align: usize) -> Self { Self { @@ -163,11 +197,15 @@ impl StgInfo { length: 0, proto: None, flags: StgInfoFlags::empty(), + scalar_code: None, element_type: None, element_size: 0, format: None, shape: Vec::new(), paramfunc: ParamFunc::None, + argtypes: None, + restype: None, + checker: None, big_endian: cfg!(target_endian = "big"), // native endian by default field_layouts: Vec::new(), pointer_type: None, @@ -213,13 +251,17 @@ impl StgInfo { size, align, length, - proto: None, + proto: Some(element_type.clone()), flags, + scalar_code: None, element_type: Some(element_type), element_size, format, shape, paramfunc: ParamFunc::Array, + argtypes: None, + restype: None, + checker: None, big_endian: cfg!(target_endian = "big"), // native endian by default field_layouts: Vec::new(), pointer_type: None, @@ -240,10 +282,10 @@ impl StgInfo { /// Build the host_env call layout for a ctypes type from its already-borrowed /// `StgInfo`. Aggregate layouts come straight from the type's `field_layouts` /// (built incrementally from the base class, so struct inheritance is -/// reflected); array elements recurse into the element type; simple types read -/// their `_type_` code. The caller passes the borrowed `stg` so this never +/// reflected); array elements recurse into the element type; simple types use +/// their initialized scalar code. The caller passes the borrowed `stg` so this never /// re-locks `ty`'s own type data. -pub(super) fn type_layout(ty: &Py, stg: &StgInfo, vm: &VirtualMachine) -> CTypeLayout { +pub(super) fn type_layout(stg: &StgInfo) -> CTypeLayout { match stg.paramfunc { ParamFunc::Structure => CTypeLayout::Struct { fields: stg.field_layouts.clone(), @@ -257,7 +299,7 @@ pub(super) fn type_layout(ty: &Py, stg: &StgInfo, vm: &VirtualMachine) - let element = stg .element_type .as_ref() - .and_then(|et| et.stg_info_opt().map(|et_stg| type_layout(et, &et_stg, vm))) + .and_then(|et| et.stg_info_opt().map(|et_stg| type_layout(&et_stg))) .unwrap_or(CTypeLayout::Opaque { size: stg.element_size, }); @@ -268,9 +310,8 @@ pub(super) fn type_layout(ty: &Py, stg: &StgInfo, vm: &VirtualMachine) - } } ParamFunc::Pointer => CTypeLayout::Pointer, - ParamFunc::Simple | ParamFunc::None => ty - .type_code(vm) - .and_then(|code| code.chars().next()) + ParamFunc::Simple | ParamFunc::None => stg + .scalar_code .map_or(CTypeLayout::Opaque { size: stg.size }, CTypeLayout::Simple), } } @@ -296,7 +337,8 @@ pub(super) fn pointer_type_set( vm: &VirtualMachine, ) -> PyResult<()> { if let Some(mut info) = zelf.get_type_data_mut::() { - info.pointer_type = Some(value); + let _old = info.pointer_type.replace(value); + drop(info); Ok(()) } else { Err(vm.new_attribute_error(format!("cannot set __pointer_type__ on {}", zelf.name()))) @@ -372,7 +414,16 @@ pub(super) static CDATA_BUFFER_METHODS: BufferMethods = BufferMethods { obj_bytes_mut: |buffer| { rustpython_common::lock::PyRwLockWriteGuard::map( buffer.obj_as::().buffer.write(), - |x| x.to_mut().as_mut_slice(), + |x| match x { + // ctypes buffers are writable, including views into their base object. + // SAFETY: requires valid writable storage and exclusive access. + // This guard only locks this view, not its owner or sibling views; + // ctypes does not enforce these requirements across aliases. + Cow::Borrowed(slice) => unsafe { + rustpython_host_env::ctypes::borrowed_slice_as_mut(slice) + }, + Cow::Owned(vec) => vec.as_mut_slice(), + }, ) .into() }, @@ -402,14 +453,16 @@ pub(super) fn str_to_wchar_bytes(s: &Wtf8, vm: &VirtualMachine) -> (PyObjectRef, } // PyCData - base type for all ctypes data types -#[pyclass(name = "_CData", module = "_ctypes")] +#[pyclass(name = "_CData", module = "_ctypes", traverse = "manual")] #[derive(Debug, PyPayload)] pub struct PyCData { /// Memory buffer - Owned (self-owned) or Borrowed (external reference) /// /// SAFETY: Borrowed variant's 'static lifetime is not actually static. /// When created via from_address or from_base_obj, only valid for the lifetime of the source memory. - /// Same behavior as CPython's b_ptr (user responsibility, kept alive via b_base). + /// A base reference keeps the owner alive but does not pin its allocation. + /// Resizing the owner may invalidate the slice; locks on distinct views + /// do not synchronize access to their shared storage. pub buffer: PyRwLock>, /// pointer to base object or None (b_base) pub base: PyRwLock>, @@ -425,228 +478,1059 @@ pub struct PyCData { /// Used for null-terminated c_char_p buffer copies, since /// RustPython's PyBytes lacks CPython's internal trailing null. /// Keyed by unique_key (hierarchical) so nested fields don't collide. - pub(super) kept_refs: PyRwLock>, + kept_refs: PyRwLock>>, } -impl PyCData { - /// Create from StgInfo (PyCData_MallocBuffer pattern) - pub(crate) fn from_stg_info(stg_info: &StgInfo) -> Self { - Self { - buffer: PyRwLock::new(Cow::Owned(vec![0u8; stg_info.size])), - base: PyRwLock::new(None), - base_offset: AtomicCell::new(0), - index: AtomicCell::new(0), - objects: PyRwLock::new(None), - length: AtomicCell::new(stg_info.length), - kept_refs: PyRwLock::new(std::collections::HashMap::new()), +// SAFETY: visit each owned reference once; slot IDs are not additional owners. +unsafe impl Traverse for PyCData { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.base.traverse(tracer); + self.objects.traverse(tracer); + if let Some(refs) = self.kept_refs.try_read_recursive() + && let Some(refs) = refs.as_ref() + { + refs.traverse(tracer); } } - /// Create from existing bytes (copies data) - pub(crate) fn from_bytes(data: Vec, objects: Option) -> Self { - Self { - buffer: PyRwLock::new(Cow::Owned(data)), - base: PyRwLock::new(None), - base_offset: AtomicCell::new(0), - index: AtomicCell::new(0), - objects: PyRwLock::new(objects), - length: AtomicCell::new(0), - kept_refs: PyRwLock::new(std::collections::HashMap::new()), + fn clear(&mut self, out: &mut Vec) { + // Disconnect a view before its backing owners can be released. Owned + // storage keeps its allocation until deallocation. + if let Some(mut buffer) = self.buffer.try_write() { + match &mut *buffer { + Cow::Owned(_) => {} + Cow::Borrowed(_) => *buffer = Cow::Owned(Vec::new()), + } + } else { + return; + } + if let Some(mut base) = self.base.try_write() { + out.extend(base.take()); + } + if let Some(mut objects) = self.objects.try_write() { + out.extend(objects.take()); + } + if let Some(mut refs) = self.kept_refs.try_write() + && let Some(mut refs) = refs.take() + { + refs.clear(out); } } +} - /// Create from bytes with specified length (for arrays) - pub fn from_bytes_with_length( - data: Vec, - objects: Option, - length: usize, - ) -> Self { - Self { - buffer: PyRwLock::new(Cow::Owned(data)), - base: PyRwLock::new(None), - base_offset: AtomicCell::new(0), - index: AtomicCell::new(0), - objects: PyRwLock::new(objects), - length: AtomicCell::new(length), - kept_refs: PyRwLock::new(std::collections::HashMap::new()), +#[derive(Debug, Clone)] +enum HiddenRefs { + Single(PyObjectRef), + Snapshot(crate::builtins::PyTupleRef), +} + +impl HiddenRefs { + fn id(&self) -> usize { + match self { + Self::Single(obj) => obj.get_id(), + Self::Snapshot(tuple) => tuple.get_id(), } } - /// Create from external memory address - /// - /// # Safety - /// The returned slice's 'static lifetime is a lie. - /// Actually only valid for the lifetime of the memory pointed to by ptr. - /// PyCData_AtAddress - pub unsafe fn at_address(ptr: *const u8, size: usize) -> Self { - // = PyCData_AtAddress - // SAFETY: Caller must ensure ptr is valid for the lifetime of returned PyCData - let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) }; - Self { - buffer: PyRwLock::new(Cow::Borrowed(slice)), - base: PyRwLock::new(None), - base_offset: AtomicCell::new(0), - index: AtomicCell::new(0), - objects: PyRwLock::new(None), - length: AtomicCell::new(0), - kept_refs: PyRwLock::new(std::collections::HashMap::new()), + fn owners(&self) -> &[PyObjectRef] { + match self { + Self::Single(obj) => core::slice::from_ref(obj), + Self::Snapshot(tuple) => tuple.as_slice(), } } - /// Create from base object with offset and data copy - /// - /// Similar to from_base_with_offset, but also stores a copy of the data. - /// This is used for arrays where we need our own buffer for the buffer protocol, - /// but still maintain the base reference for KeepRef and tracking. - pub fn from_base_with_data( - base_obj: PyObjectRef, - offset: usize, - idx: usize, - length: usize, - data: Vec, - ) -> Self { - Self { - buffer: PyRwLock::new(Cow::Owned(data)), // Has its own buffer copy - base: PyRwLock::new(Some(base_obj)), // But still tracks base - base_offset: AtomicCell::new(offset), // And offset for writes - index: AtomicCell::new(idx), - objects: PyRwLock::new(None), - length: AtomicCell::new(length), - kept_refs: PyRwLock::new(std::collections::HashMap::new()), + fn into_object(self) -> PyObjectRef { + match self { + Self::Single(obj) => obj, + Self::Snapshot(tuple) => tuple.into(), } } +} - /// Create from base object's buffer - /// - /// This creates a borrowed view into the base's buffer at the given address. - /// The base object is stored in b_base to keep the memory alive. - /// - /// # Safety - /// ptr must point into base_obj's buffer and remain valid as long as base_obj is alive. - pub unsafe fn from_base_obj( - ptr: *mut u8, - size: usize, - base_obj: PyObjectRef, - idx: usize, - ) -> Self { - // = PyCData_FromBaseObj - // SAFETY: ptr points into base_obj's buffer, kept alive via base reference - let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) }; - Self { - buffer: PyRwLock::new(Cow::Borrowed(slice)), - base: PyRwLock::new(Some(base_obj)), - base_offset: AtomicCell::new(0), - index: AtomicCell::new(idx), - objects: PyRwLock::new(None), - length: AtomicCell::new(0), - kept_refs: PyRwLock::new(std::collections::HashMap::new()), +#[derive(Debug, Default)] +struct PrivateRefs { + writer_prune_remaining: usize, + buffer_alias: Option, + // Exact-key hints only: these IDs never own or reconstruct Python objects. + object_index: Option>, + // A registration cache, not a backing owner; do not copy it with values. + writer_paths: Option, + // Views are temporary; retain their caches on the same root as KeepRef. + view_writer_paths: std::collections::HashMap, + writes: std::collections::HashMap, + slots: std::collections::HashMap, + groups: std::collections::HashMap, + owners: std::collections::HashMap, + snapshot: Option, +} + +impl PrivateRefs { + fn slot_owners(&self, key: &str) -> &[PyObjectRef] { + self.slots + .get(key) + .and_then(|id| self.groups.get(id)) + .map_or(&[], |(group, _)| group.owners()) + } + + fn first(&self, key: &str) -> Option { + self.slot_owners(key).first().cloned() + } + + fn replace(&mut self, key: String, incoming: Option) -> Vec { + let old = if let Some(group) = &incoming { + self.slots.insert(key, group.id()) + } else { + self.slots.remove(&key) + }; + let mut displaced = Vec::new(); + let mut changed = false; + if let Some(group) = incoming { + let id = group.id(); + if let Some((_, count)) = self.groups.get_mut(&id) { + *count += 1; + displaced.push(group.into_object()); + } else { + for obj in group.owners() { + match self.owners.entry(obj.get_id()) { + std::collections::hash_map::Entry::Occupied(mut entry) => { + entry.get_mut().1 += 1 + } + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert((obj.clone(), 1)); + changed = true; + } + } + } + self.groups.insert(id, (group, 1)); + } + } + // Membership is counted per distinct group, not per destination slot. + // Publish incoming owners before removing old ones, including self-copy. + if let Some(id) = old { + let (_, count) = self.groups.get_mut(&id).expect("registered private group"); + *count -= 1; + if *count == 0 { + let (group, _) = self.groups.remove(&id).unwrap(); + for obj in group.owners() { + let id = obj.get_id(); + let (_, count) = self.owners.get_mut(&id).expect("registered private owner"); + *count -= 1; + if *count == 0 { + displaced.push(self.owners.remove(&id).unwrap().0); + changed = true; + } + } + displaced.push(group.into_object()); + } } + if changed { + displaced.extend(self.snapshot.take().map(Into::into)); + } + displaced } - /// Create from buffer protocol object (for from_buffer method) - /// - /// Unlike from_bytes, this shares memory with the source buffer. - /// The source object is stored in objects dict to keep the buffer alive. - /// Python stores with key -1 via KeepRef(result, -1, mv). - /// - /// # Safety - /// ptr must point to valid memory that remains valid as long as source is alive. - pub unsafe fn from_buffer_shared( - ptr: *const u8, - size: usize, - length: usize, - source: PyObjectRef, - vm: &VirtualMachine, - ) -> Self { - // SAFETY: Caller must ensure ptr is valid for the lifetime of source - let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) }; + fn snapshot(&self) -> Vec { + self.owners.values().map(|(obj, _)| obj.clone()).collect() + } +} - // Python stores the reference in a dict with key "-1" (unique_key pattern) - let objects_dict = vm.ctx.new_dict(); - objects_dict - .set_item("-1", source, vm) - .expect("Failed to store buffer reference"); +// SAFETY: visit each stored strong reference once. Shared snapshot elements +// belong to the Python tuple and are traced by that tuple, not by each slot. +// The registration cache owns weakref wrappers, not their referents. +unsafe impl Traverse for PrivateRefs { + #[expect(clippy::iter_over_hash_type, reason = "GC edge order is irrelevant")] + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + if let Some(alias) = &self.buffer_alias { + alias.source.traverse(tracer); + } + for (obj, _) in self.owners.values() { + obj.traverse(tracer); + } + for (group, _) in self.groups.values() { + match group { + HiddenRefs::Single(obj) => obj.traverse(tracer), + HiddenRefs::Snapshot(tuple) => tuple.traverse(tracer), + } + } + self.snapshot.traverse(tracer); + for registration in self.writes.values() { + registration.record.writer.traverse(tracer); + } + for paths in self + .writer_paths + .iter() + .chain(self.view_writer_paths.values()) + { + for path in paths.iter() { + for link in path { + link.source.traverse(tracer); + } + } + } + } + fn clear(&mut self, out: &mut Vec) { + if let Some(alias) = self.buffer_alias.take() { + out.push(alias.source.clone()); + } + self.object_index = None; + out.extend( + self.writes + .drain() + .map(|(_, registration)| registration.record.writer.clone().into()), + ); + self.slots.clear(); + out.extend(self.owners.drain().map(|(_, (obj, _))| obj)); + out.extend( + self.groups + .drain() + .map(|(_, (group, _))| group.into_object()), + ); + out.extend(self.snapshot.take().map(Into::into)); + for paths in self + .writer_paths + .take() + .into_iter() + .chain(self.view_writer_paths.drain().map(|(_, paths)| paths)) + { + for path in paths.iter() { + out.extend(path.iter().map(|link| link.source.clone().into())); + } + } + } +} + +// Per-interpreter reverse provenance for independent from_buffer views. +// Callback-free weakrefs do not retain writers or their py_object values. +#[derive(Debug, Default)] +pub(crate) struct BufferViewRegistry { + views: PyRwLock>>>, + writes: PyRwLock>>, +} + +#[derive(Debug)] +struct RangeEntry { + end: usize, + value: T, +} + +#[derive(Debug)] +struct RangeIndex { + // One entry per view. Size classes keep a large overlapping view from + // widening the search window for every small view of the same exporter. + ranges: alloc::collections::BTreeMap< + usize, + alloc::collections::BTreeMap<(usize, usize), RangeEntry>, + >, +} +impl Default for RangeIndex { + fn default() -> Self { Self { - buffer: PyRwLock::new(Cow::Borrowed(slice)), - base: PyRwLock::new(None), - base_offset: AtomicCell::new(0), - index: AtomicCell::new(0), - objects: PyRwLock::new(Some(objects_dict.into())), - length: AtomicCell::new(length), - kept_refs: PyRwLock::new(std::collections::HashMap::new()), + ranges: Default::default(), } } +} - /// Common implementation for from_buffer class method. - /// Validates buffer, creates memoryview, and returns PyCData sharing memory with source. - /// - /// CDataType_from_buffer_impl - pub fn from_buffer_impl( - cls: &Py, - source: PyObjectRef, - offset: isize, - vm: &VirtualMachine, - ) -> PyResult { - let (size, length) = { - let stg_info = cls - .stg_info_opt() - .ok_or_else(|| vm.new_type_error("not a ctypes type"))?; - (stg_info.size, stg_info.length) - }; +#[derive(Clone, Copy, Debug)] +struct RangeKey { + start: usize, + span: usize, + id: usize, +} - if offset < 0 { - return Err(vm.new_value_error("offset cannot be negative")); +impl RangeKey { + fn new(start: usize, size: usize, id: usize) -> Self { + Self { + start, + span: size.checked_next_power_of_two().unwrap_or(usize::MAX), + id, } - let offset = offset as usize; + } +} - // Get buffer from source (this exports the buffer) - let buffer = PyBuffer::try_from_object(vm, source)?; +impl RangeIndex { + fn insert(&mut self, key: RangeKey, size: usize, value: T) -> Option { + self.ranges + .entry(key.span) + .or_default() + .insert( + (key.start, key.id), + RangeEntry { + end: key.start.saturating_add(size), + value, + }, + ) + .map(|entry| entry.value) + } - // Check if buffer is writable - if buffer.desc.readonly { - return Err(vm.new_type_error("underlying buffer is not writable")); + fn remove(&mut self, key: RangeKey) -> Option { + let ranges = self.ranges.get_mut(&key.span)?; + let removed = ranges.remove(&(key.start, key.id)); + if ranges.is_empty() { + self.ranges.remove(&key.span); } + removed.map(|entry| entry.value) + } - // Check if buffer is C contiguous - if !buffer.desc.is_contiguous() { - return Err(vm.new_type_error("underlying buffer is not C contiguous")); + fn matching(&self, slot: Option) -> Vec { + let mut found = Vec::new(); + for (&span, ranges) in &self.ranges { + if let Some(slot) = slot { + let first = slot.saturating_sub(span - 1); + let end = slot.saturating_add(rustpython_host_env::ctypes::pointer_size()); + for (&(start, _), entry) in ranges.range((first, 0)..(end, 0)) { + if entry.end > slot && entry.end > start { + found.push(entry.value.clone()); + } + } + } else { + found.extend(ranges.values().map(|entry| entry.value.clone())); + } } + found + } +} - // Check if buffer is large enough - let buffer_len = buffer.desc.len; - if offset + size > buffer_len { - return Err(vm.new_value_error(format!( - "Buffer size too small ({} instead of at least {} bytes)", - buffer_len, - offset + size - ))); +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +enum WriteSlot { + Root(usize), + View(String), +} + +struct WriteRange { + root: PyObjectRef, + slot: WriteSlot, + address: usize, + size: usize, +} + +// Pin the destination across user conversions, but publish the actual range +// afterwards: a nested conversion may write through the same retention slot. +#[derive(Default)] +pub(super) struct CDataWrite { + _storage: Option, + range: Option, +} + +impl CDataWrite { + fn new(storage: Option, range: impl FnOnce() -> WriteRange) -> Self { + // Owned CData storage is directly reachable through its buffer views. + // Borrowed/foreign writes can extend beyond every retained source view. + let range = storage + .as_ref() + .is_none_or(|storage| storage.downcast_ref::().unwrap().is_borrowed()) + .then(range); + Self { + _storage: storage, + range, } + } - // Get buffer pointer - the memory is owned by source - let ptr = { - // Contiguity is checked above, so this is the view's own bytes rather - // than the whole exporter's. - let bytes = unsafe { buffer.contiguous_unchecked() }; - bytes.as_ptr().wrapping_add(offset) - }; + pub(super) fn publish(&self, vm: &VirtualMachine) -> PyResult<()> { + if let Some(range) = &self.range { + PyCData::index_write(&range.root, &range.slot, range.address, range.size, vm)?; + } + Ok(()) + } +} - // Create memoryview to keep buffer exported (prevents source from being modified) - // mv = PyMemoryView_FromObject(obj); KeepRef(result, -1, mv); - let memoryview = PyMemoryView::from_buffer(buffer, vm)?; - let mv_obj = memoryview.into_pyobject(vm); +#[derive(Debug)] +struct BufferWrite { + writer: PyRef, + address: usize, + size: usize, +} - // Create CData that shares memory with the buffer - Ok(unsafe { Self::from_buffer_shared(ptr, size, length, mv_obj, vm) }) +// The retention root owns this token. The registry holds only a Rust Weak, +// so the Python weakref wrapper has exactly the GC edge traversed above. +#[derive(Debug)] +struct WriteRegistration { + registry: alloc::sync::Arc, + key: RangeKey, + record: alloc::sync::Arc, +} + +impl Drop for WriteRegistration { + fn drop(&mut self) { + let _removed = self.registry.writes.write().remove(self.key); } +} - /// Common implementation for from_buffer_copy class method. - /// Copies data from buffer and creates new independent instance. - /// - /// CDataType_from_buffer_copy_impl - pub fn from_buffer_copy_impl( - cls: &Py, - source: &[u8], +#[derive(Debug)] +struct BufferAlias { + registry: alloc::sync::Arc, + exporter: usize, + key: RangeKey, + source: PyObjectRef, +} + +impl Drop for BufferAlias { + fn drop(&mut self) { + let _removed = { + let mut views = self.registry.views.write(); + if let Some(aliases) = views.get_mut(&self.exporter) { + let removed = aliases.remove(self.key); + if aliases.ranges.is_empty() { + views.remove(&self.exporter); + } + removed + } else { + None + } + }; + } +} + +impl BufferViewRegistry { + fn owners(&self, exporter: &PyObject, slot: Option) -> Vec { + let exporter = buffer_owner(exporter); + let aliases = { + let views = self.views.read(); + let Some(aliases) = views.get(&exporter.get_id()) else { + return Vec::new(); + }; + aliases.matching(slot) + }; + let mut owners = Vec::new(); + for weak in aliases { + // Do not upgrade or release writers under the registry lock. + let Some(owner) = weak.upgrade() else { + continue; + }; + let source = + owner.downcast_ref::().and_then(|cdata| { + cdata.kept_refs.read().as_ref().and_then(|refs| { + refs.buffer_alias.as_ref().map(|alias| alias.source.clone()) + }) + }); + if source + .as_ref() + .is_some_and(|source| buffer_owner(source).is(exporter)) + { + owners.push(owner); + } + } + owners + } + + fn writers(&self, slot: Option) -> Vec { + let records = self.writes.read().matching(slot); + // Upgrade and release Python references outside the range-index lock. + records + .into_iter() + .filter_map(|record| record.upgrade()?.writer.upgrade()) + .collect() + } +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] +enum WriterKey { + String(String), + Id(usize), + Index(usize), +} + +type WriterPaths = alloc::sync::Arc<[Vec]>; +type WriterSource = (PyObjectRef, WriterOrigin); + +#[derive(Clone, Debug)] +enum WriterOrigin { + Native, + Public(Vec), + Private { + slot: String, + index: usize, + owner: usize, + }, +} + +#[derive(Debug)] +struct WriterLink { + source: PyRef, + origin: WriterOrigin, +} + +// Index direct retention entries, including duplicate values, without retaining +// their keys or values as Python objects. Native writes update a warmed index. +#[derive(Debug)] +struct ObjectIndex { + dictionary: usize, + slots: std::collections::HashMap, + values: std::collections::HashMap, +} + +impl ObjectIndex { + fn set(&mut self, key: WriterKey, value: Option) { + if let Some(old) = self.slots.remove(&key) { + let keys = self.values.get_mut(&old).expect("indexed retention slot"); + if keys.remove(&key) { + self.values.remove(&old); + } + } + if let Some(value) = value { + self.slots.insert(key.clone(), value); + match self.values.entry(value) { + std::collections::hash_map::Entry::Occupied(mut entry) => { + entry.get_mut().insert(key) + } + std::collections::hash_map::Entry::Vacant(entry) => { + entry.insert(ObjectKeys::One(key)); + } + } + } + } +} + +// Most referents occur once. Allocate a tree only for duplicate keys, whose +// removal must not require scanning all other references to the same object. +#[derive(Debug)] +enum ObjectKeys { + One(WriterKey), + Many(alloc::collections::BTreeSet), +} + +impl ObjectKeys { + fn insert(&mut self, key: WriterKey) { + match self { + Self::One(old) if *old == key => {} + Self::One(old) => *self = Self::Many([old.clone(), key].into()), + Self::Many(keys) => { + keys.insert(key); + } + } + } + + // Return true when the last key was removed. + fn remove(&mut self, key: &WriterKey) -> bool { + match self { + Self::One(old) => old == key, + Self::Many(keys) => { + keys.remove(key); + if keys.len() == 1 { + *self = Self::One(keys.pop_first().unwrap()); + } + false + } + } + } + + fn first(&self) -> &WriterKey { + match self { + Self::One(key) => key, + Self::Many(keys) => keys.first().expect("nonempty retention keys"), + } + } + + fn len(&self) -> usize { + match self { + Self::One(_) => 1, + Self::Many(keys) => keys.len(), + } + } +} + +// Retention metadata is user-mutable. Its fast lookup must not call Python +// equality on a colliding key; non-exact string keys use the graph fallback. +struct ObjectKey<'a>(&'a str); + +impl DictKey for ObjectKey<'_> { + type Owned = String; + + fn _to_owned(&self, _vm: &VirtualMachine) -> String { + self.0.to_owned() + } + + fn key_hash(&self, vm: &VirtualMachine) -> PyResult { + self.0.key_hash(vm) + } + + fn key_is(&self, _other: &PyObject) -> bool { + false + } + + fn key_eq(&self, vm: &VirtualMachine, other: &PyObject) -> PyResult { + Ok(other + .downcast_ref_if_exact::(vm) + .is_some_and(|key| key.as_wtf8() == self.0)) + } + + fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult { + self.0.key_as_isize(vm) + } +} + +// cast() stores a strong source reference under id(source). Only exact int +// keys are eligible for the cache; lookup must not invoke user equality. +struct ObjectIdKey(usize); + +impl DictKey for ObjectIdKey { + type Owned = usize; + + fn _to_owned(&self, _vm: &VirtualMachine) -> usize { + self.0 + } + + fn key_hash(&self, vm: &VirtualMachine) -> PyResult { + self.0.key_hash(vm) + } + + fn key_is(&self, _other: &PyObject) -> bool { + false + } + + fn key_eq(&self, vm: &VirtualMachine, other: &PyObject) -> PyResult { + Ok(other + .downcast_ref_if_exact::(vm) + .and_then(|key| key.as_bigint().to_usize()) + == Some(self.0)) + } + + fn key_as_isize(&self, vm: &VirtualMachine) -> PyResult { + self.0.key_as_isize(vm) + } +} + +// Prepare conversions and ownership before writing. Python conversion hooks +// and old-owner finalizers must never run with a storage or metadata lock held. +pub(super) enum CDataBytes { + Integer { + bytes: [u8; 8], + size: usize, + }, + Owned(Vec), + #[cfg(windows)] + BStr(rustpython_host_env::ctypes::BStr), +} + +impl CDataBytes { + // Arguments have no previous destination, but still transfer ownership. + pub(super) fn commit(&mut self) { + #[cfg(windows)] + if let Self::BStr(bstr) = self { + bstr.commit(); + } + } + + // The destination follows ctypes' caller-provided valid-pointer contract. + pub(super) fn replace(&mut self, _previous: &[u8]) { + #[cfg(windows)] + if let Self::BStr(bstr) = self { + // SAFETY: BSTR setters require NULL or a live COM allocation. + unsafe { + bstr.replace(_previous); + } + } + } +} + +impl From> for CDataBytes { + fn from(bytes: Vec) -> Self { + Self::Owned(bytes) + } +} + +impl core::ops::Deref for CDataBytes { + type Target = [u8]; + + fn deref(&self) -> &[u8] { + match self { + Self::Integer { bytes, size } => &bytes[..*size], + Self::Owned(bytes) => bytes, + #[cfg(windows)] + Self::BStr(bstr) => bstr.bytes(), + } + } +} + +pub(super) struct CDataValue { + pub bytes: CDataBytes, + keep: Option, + hidden: Option, + temporary: Option, +} + +impl CDataValue { + pub(super) fn new( + proto: &Py, + value: &PyObject, + size: usize, + swapped: bool, + vm: &VirtualMachine, + ) -> PyResult { + if let Some(source) = value.downcast_ref::() { + if value.fast_isinstance(proto) { + // Snapshot before writing: source and destination may overlap. + let bytes = + rustpython_host_env::ctypes::copy_to_sized_bytes(&source.buffer.read(), size); + let hidden = PyCData::hidden_refs(value, vm); + let keep = PyCData::get_kept_objects(value, vm); + return Ok(Self { + bytes: bytes.into(), + keep: (!vm.is_none(&keep)).then_some(keep), + hidden, + temporary: None, + }); + } + if proto + .class() + .fast_issubclass(super::pointer::PyCPointerType::static_type()) + && let Some(array) = value.downcast_ref::() + && { + let target = proto.stg_info(vm)?; + let array_info = array.class().stg_info(vm)?; + target + .proto + .as_deref() + .zip(array_info.element_type.as_deref()) + .is_some_and(|(target, element)| target.is(element)) + } + { + let address = array.0.buffer.read().as_ptr() as usize; + return Ok(Self { + bytes: rustpython_host_env::ctypes::pointer_to_sized_bytes(address, size) + .into(), + keep: Some( + vm.ctx + .new_tuple(vec![PyCData::get_kept_objects(value, vm), value.to_owned()]) + .into(), + ), + hidden: None, + temporary: None, + }); + } + return Err(vm.new_type_error(format!( + "incompatible types, {} instance instead of {} instance", + value.class().name(), + proto.name() + ))); + } + let metaclass = proto.class(); + let simple_metaclass = super::simple::PyCSimpleType::static_type(); + if metaclass.is(simple_metaclass) || metaclass.fast_issubclass(simple_metaclass) { + // Reading the mutable _type_ here could select a wider converter + // than the allocated slot, or change conversion during callbacks. + let code = proto + .stg_info(vm)? + .scalar_code + .ok_or_else(|| vm.new_type_error("abstract class"))?; + let mut encoded = [0; 4]; + let type_code = code.encode_utf8(&mut encoded); + let (bytes, keep, hidden) = + super::simple::assignment_value(type_code, value, swapped, vm)?; + return Ok(Self { + bytes, + keep, + hidden: hidden.map(HiddenRefs::Single), + temporary: None, + }); + } + if let Some(tuple) = value.downcast_ref::() { + let instance = proto + .as_object() + .call(tuple.as_slice().to_vec(), vm) + .map_err(|e| { + let args = e.args(); + let message = args + .as_slice() + .first() + .and_then(|arg| arg.downcast_ref::()) + .map_or_default(|s| s.to_string()); + vm.new_runtime_error(format!( + "({}) {}: {message}", + proto.name(), + e.class().name() + )) + })?; + let mut prepared = Self::new(proto, &instance, size, swapped, vm)?; + prepared.temporary = Some(instance); + return Ok(prepared); + } + if vm.is_none(value) + && proto + .class() + .fast_issubclass(super::pointer::PyCPointerType::static_type()) + { + return Ok(Self { + bytes: vec![0; size].into(), + keep: None, + hidden: None, + temporary: None, + }); + } + Err(vm.new_type_error(format!( + "expected {} instance, not {}", + proto.name(), + value.class().name() + ))) + } + + #[inline] + pub(super) fn keep( + self, + destination: &PyCData, + index: usize, + vm: &VirtualMachine, + ) -> PyResult<()> { + // Tuple conversion can create an instance with a finalizer. Keep it + // until the bytes and all owners have been published. + let _temporary = self.temporary; + // Like KeepRef(None), preserve previous owners when assigning a raw + // address: it can still point into their private backing allocation. + if self.keep.is_none() && self.hidden.is_none() { + return Ok(()); + } + // Publish every owner before dropping the displaced value, whose + // finalizer may assign this same slot again. + let _old_hidden = destination.replace_hidden(index, self.hidden); + if let Some(keep) = self.keep { + destination.keep_ref(index, keep, vm)?; + } + Ok(()) + } +} + +impl PyCData { + pub(super) fn from_param(cls: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + // If already an instance of the requested type, return it + if value.is_instance(cls.as_object(), vm)? { + return Ok(value); + } + + if let Some(carg) = value.downcast_ref::() { + // Snapshot the initialized prototype before calling Python. An array + // accepts byref(element), not byref(array); aggregates without a + // prototype cannot accept a CArgObject through this conversion. + let proto = cls.stg_info_opt().and_then(|info| info.proto.clone()); + if let Some(proto) = proto + && carg.obj.is_instance(proto.as_object(), vm)? + { + return Ok(value); + } + return Err(vm.new_type_error(format!( + "expected {} instance instead of pointer to {}", + cls.name(), + carg.obj.class().name() + ))); + } + + if let Some(as_parameter) = vm.get_attribute_opt(&value, "_as_parameter_")? { + // Recursive adaptation uses the generic converter, even when the + // initial call came through a pointer type's specialized converter. + return vm.with_recursion(" while processing _as_parameter_", || { + Self::from_param(cls, as_parameter, vm) + }); + } + + Err(vm.new_type_error(format!( + "expected {} instance instead of {}", + cls.name(), + value.class().name() + ))) + } + + /// Create from StgInfo (PyCData_MallocBuffer pattern) + pub(crate) fn from_stg_info(stg_info: &StgInfo) -> Self { + Self { + buffer: PyRwLock::new(Cow::Owned(vec![0u8; stg_info.size])), + base: PyRwLock::new(None), + base_offset: AtomicCell::new(0), + index: AtomicCell::new(0), + objects: PyRwLock::new(None), + length: AtomicCell::new(stg_info.length), + kept_refs: PyRwLock::new(None), + } + } + + /// Create from existing bytes (copies data) + pub(crate) fn from_bytes(data: Vec, objects: Option) -> Self { + Self { + buffer: PyRwLock::new(Cow::Owned(data)), + base: PyRwLock::new(None), + base_offset: AtomicCell::new(0), + index: AtomicCell::new(0), + objects: PyRwLock::new(objects), + length: AtomicCell::new(0), + kept_refs: PyRwLock::new(None), + } + } + + /// Create from bytes with specified length (for arrays) + pub fn from_bytes_with_length( + data: Vec, + objects: Option, + length: usize, + ) -> Self { + Self { + buffer: PyRwLock::new(Cow::Owned(data)), + base: PyRwLock::new(None), + base_offset: AtomicCell::new(0), + index: AtomicCell::new(0), + objects: PyRwLock::new(objects), + length: AtomicCell::new(length), + kept_refs: PyRwLock::new(None), + } + } + + /// Create from external memory address + /// + /// # Safety + /// `ptr` must be non-null and valid for `size` bytes for the lifetime of returned PyCData. + /// `size` must not exceed `isize::MAX`. + /// The returned slice's 'static lifetime is a lie. + /// Actually only valid for the lifetime of the memory pointed to by ptr. + /// PyCData_AtAddress + pub unsafe fn at_address(ptr: *const u8, size: usize) -> Self { + debug_assert!( + !ptr.is_null() && isize::try_from(size).is_ok(), + "PyCData::at_address requires non-null pointer and size <= isize::MAX" + ); + // = PyCData_AtAddress + // SAFETY: Caller must ensure ptr is valid for the lifetime of returned PyCData + let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) }; + Self { + buffer: PyRwLock::new(Cow::Borrowed(slice)), + base: PyRwLock::new(None), + base_offset: AtomicCell::new(0), + index: AtomicCell::new(0), + objects: PyRwLock::new(None), + length: AtomicCell::new(0), + kept_refs: PyRwLock::new(None), + } + } + + /// Create from base object's buffer + /// + /// This creates a borrowed view into the base's buffer at the given address. + /// The base object is stored in b_base to keep the owner alive, not to pin its allocation. + /// + /// # Safety + /// `ptr` must cover `size` valid bytes for the lifetime of the returned view. + /// Keeping `base_obj` alive does not prevent reallocation or incompatible + /// access through another alias; the caller must account for both. + pub unsafe fn from_base_obj( + ptr: *mut u8, + size: usize, + base_obj: PyObjectRef, + idx: usize, + ) -> Self { + // = PyCData_FromBaseObj + // SAFETY: the caller must uphold the storage validity and aliasing requirements above. + let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) }; + Self { + buffer: PyRwLock::new(Cow::Borrowed(slice)), + base: PyRwLock::new(Some(base_obj)), + base_offset: AtomicCell::new(0), + index: AtomicCell::new(idx), + objects: PyRwLock::new(None), + length: AtomicCell::new(0), + kept_refs: PyRwLock::new(None), + } + } + + /// Create from buffer protocol object (for from_buffer method) + /// + /// Unlike from_bytes, this shares memory with the source buffer. + /// The source object is stored in objects dict to keep the buffer alive. + /// Python stores with key -1 via KeepRef(result, -1, mv). + /// + /// # Safety + /// ptr must point to valid memory that remains valid as long as source is alive. + pub unsafe fn from_buffer_shared( + ptr: *const u8, + size: usize, + length: usize, + source: PyObjectRef, + vm: &VirtualMachine, + ) -> Self { + // SAFETY: Caller must ensure ptr is valid for the lifetime of source + let slice = unsafe { rustpython_host_env::ctypes::borrow_memory(ptr, size) }; + + // Python stores the reference in a dict with key "-1" (unique_key pattern) + let objects_dict = vm.ctx.new_dict(); + objects_dict + .set_item("-1", source, vm) + .expect("Failed to store buffer reference"); + + Self { + buffer: PyRwLock::new(Cow::Borrowed(slice)), + base: PyRwLock::new(None), + base_offset: AtomicCell::new(0), + index: AtomicCell::new(0), + objects: PyRwLock::new(Some(objects_dict.into())), + length: AtomicCell::new(length), + kept_refs: PyRwLock::new(None), + } + } + + /// Common implementation for from_buffer class method. + /// Validates buffer, creates memoryview, and returns PyCData sharing memory with source. + /// + /// CDataType_from_buffer_impl + pub fn from_buffer_impl( + cls: &Py, + source: PyObjectRef, + offset: isize, + vm: &VirtualMachine, + ) -> PyResult { + let (size, length) = { + let stg_info = cls + .stg_info_opt() + .ok_or_else(|| vm.new_type_error("not a ctypes type"))?; + (stg_info.size, stg_info.length) + }; + + if offset < 0 { + return Err(vm.new_value_error("offset cannot be negative")); + } + let offset = offset as usize; + + // Get buffer from source (this exports the buffer) + let buffer = PyBuffer::try_from_object(vm, source)?; + + // Check if buffer is writable + if buffer.desc.readonly { + return Err(vm.new_type_error("underlying buffer is not writable")); + } + + // Check if buffer is C contiguous + if !buffer.desc.is_contiguous() { + return Err(vm.new_type_error("underlying buffer is not C contiguous")); + } + + // Check if buffer is large enough + let buffer_len = buffer.desc.len; + if offset + size > buffer_len { + return Err(vm.new_value_error(format!( + "Buffer size too small ({} instead of at least {} bytes)", + buffer_len, + offset + size + ))); + } + + // Get buffer pointer - the memory is owned by source + let ptr = { + // Contiguity is checked above, so this is the view's own bytes rather + // than the whole exporter's. + let bytes = unsafe { buffer.contiguous_unchecked() }; + bytes.as_ptr().wrapping_add(offset) + }; + + // Create memoryview to keep buffer exported (prevents source from being modified) + // mv = PyMemoryView_FromObject(obj); KeepRef(result, -1, mv); + let memoryview = PyMemoryView::from_buffer(buffer, vm)?; + let mv_obj = memoryview.into_pyobject(vm); + + // Create CData that shares memory with the buffer + Ok(unsafe { Self::from_buffer_shared(ptr, size, length, mv_obj, vm) }) + } + + /// Common implementation for from_buffer_copy class method. + /// Copies data from buffer and creates new independent instance. + /// + /// CDataType_from_buffer_copy_impl + pub fn from_buffer_copy_impl( + cls: &Py, + source: &[u8], offset: isize, vm: &VirtualMachine, ) -> PyResult { @@ -700,15 +1584,33 @@ impl PyCData { write_cow_bytes_at_offset(&mut buffer, offset, bytes); } + pub(super) fn write_value_at_offset(&self, offset: usize, bytes: &mut CDataBytes) { + let mut buffer = self.buffer.write(); + let Some(previous) = buffer.get(offset..offset.saturating_add(bytes.len())) else { + return; + }; + bytes.replace(previous); + write_cow_bytes_at_offset(&mut buffer, offset, bytes); + } + /// Generate unique key for nested references (unique_key) /// Creates a hierarchical key by walking up the b_base chain. /// Format: "index:parent_index:grandparent_index:..." pub fn unique_key(&self, index: usize) -> String { let mut key = format!("{index:x}"); // Walk up the base chain to build hierarchical key - if self.base.read().is_some() { - let parent_index = self.index.load(); - key.push_str(&format!(":{parent_index:x}")); + let mut base = self.base.read().clone(); + if base.is_some() { + key.push_str(&format!(":{:x}", self.index.load())); + } + while let Some(parent) = base.take() { + let Some(cdata) = parent.downcast_ref::() else { + break; + }; + base.clone_from(&cdata.base.read()); + if base.is_some() { + key.push_str(&format!(":{:x}", cdata.index.load())); + } } key } @@ -768,106 +1670,1350 @@ impl PyCData { *objects = Some(dict.into()); } + // Replacing a reference can run a finalizer that accesses this object. + let dict_obj = objects.clone(); + drop(objects); // Store in dict with unique key - if let Some(dict_obj) = objects.as_ref() + if let Some(dict_obj) = dict_obj && let Some(dict) = dict_obj.downcast_ref::() { - let key_obj: PyObjectRef = vm.ctx.new_str(key).into(); + let key_obj: PyObjectRef = vm.ctx.new_str(key.as_str()).into(); dict.set_item(&*key_obj, keep, vm)?; + self.update_object_index(dict, &key, vm)?; + } + + Ok(()) + } + + /// Keep a reference alive without exposing it in _objects. + /// Retains a backing allocation used by a scalar's pointer. + pub fn keep_alive(&self, obj: PyObjectRef) { + drop(self.replace_hidden(0, Some(HiddenRefs::Single(obj)))); + } + + fn replace_hidden(&self, index: usize, owners: Option) -> Vec { + let base = self.base.read().clone(); + let root = base.as_ref().map(|base| Self::find_root_object(base)); + let cdata = root + .as_ref() + .and_then(|root| root.downcast_ref::()) + .map_or(self, |cdata| cdata); + if owners.is_none() + && cdata + .kept_refs + .read() + .as_ref() + .is_none_or(|refs| refs.slots.is_empty()) + { + return Vec::new(); + } + let key = self.unique_key(index); + let mut refs = cdata.kept_refs.write(); + if refs.is_none() && owners.is_none() { + return Vec::new(); + } + refs.get_or_insert_with(Default::default) + .replace(key, owners) + } + + /// Find the root object (one without a base) by walking up the base chain + fn find_root_object(obj: &PyObject) -> PyObjectRef { + let mut root = obj.to_owned(); + while let Some(cdata) = root.downcast_ref::() { + let base = cdata.base.read().clone(); + match base { + Some(base) if base.downcast_ref::().is_some() => root = base, + _ => break, + } + } + root + } + + /// Store a value in an object's _objects dict with the given key + fn store_in_object( + obj: &PyObject, + key: &str, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + // Get the objects dict from the object + let objects_lock = if let Some(cdata) = obj.downcast_ref::() { + &cdata.objects + } else { + return Ok(()); // Unknown type, skip + }; + + let mut objects = objects_lock.write(); + + // Initialize if needed + if objects.is_none() { + *objects = Some(vm.ctx.new_dict().into()); + } + + // If not a dict, convert to dict + if let Some(obj) = objects.as_ref() + && obj.downcast_ref::().is_none() + { + let dict = vm.ctx.new_dict(); + let id_key: PyObjectRef = vm.ctx.new_int(obj.get_id() as i64).into(); + dict.set_item(&*id_key, obj.clone(), vm)?; + *objects = Some(dict.into()); + } + + let dict_obj = objects.clone(); + drop(objects); + // Store in dict + if let Some(dict_obj) = dict_obj + && let Some(dict) = dict_obj.downcast_ref::() + { + let key_obj: PyObjectRef = vm.ctx.new_str(key).into(); + dict.set_item(&*key_obj, value, vm)?; + obj.downcast_ref::() + .unwrap() + .update_object_index(dict, key, vm)?; + } + + Ok(()) + } + + /// Get kept objects from a CData instance, initializing its root container. + pub fn get_kept_objects(value: &PyObject, vm: &VirtualMachine) -> PyObjectRef { + let root = Self::find_root_object(value); + let Some(cdata) = root.downcast_ref::() else { + return vm.ctx.none(); + }; + cdata + .objects + .write() + .get_or_insert_with(|| { + if cdata.length.load() == 0 { + vm.ctx.none() + } else { + vm.ctx.new_dict().into() + } + }) + .clone() + } + + // Copying a view must retain its root's references, including private + // backing allocations and aliases through other fields or pointers. + // Share a flat snapshot while the root's owner set is unchanged, including + // when copying between views of that root. Slots only retain group IDs. + fn hidden_refs(value: &PyObject, vm: &VirtualMachine) -> Option { + let root = Self::find_root_object(value); + let cdata = root.downcast_ref::()?; + let mut refs = cdata.kept_refs.write(); + let refs = refs.as_mut()?; + match refs.owners.len() { + 0 => None, + 1 => Some(HiddenRefs::Single( + refs.owners.values().next().unwrap().0.clone(), + )), + _ => { + if refs.snapshot.is_none() { + // Snapshot publication must not call finalizers: raw bytes + // have already been copied, and owners must match those bytes. + // The tuple participates in GC immediately; only collection + // is left to the next ordinary allocation. + refs.snapshot = Some(PyRef::new_ref_without_collection( + PyTuple::new_unchecked(refs.snapshot().into_boxed_slice()), + vm.ctx.types.tuple_type.to_owned(), + None, + )); + } + Some(HiddenRefs::Snapshot( + refs.snapshot.as_ref().unwrap().clone(), + )) + } + } + } + + // A scalar owns one reference; a scalar view stores it in its root instead. + pub(super) fn keep_value( + &self, + value: PyObjectRef, + hidden: Option, + vm: &VirtualMachine, + ) -> PyResult<()> { + if vm.is_none(&value) { + return Ok(()); + } + let _old_hidden = self.replace_hidden(0, hidden.map(HiddenRefs::Single)); + if self.base.read().is_some() { + self.keep_ref(0, value, vm) + } else { + let _old = self.objects.write().replace(value); + Ok(()) + } + } + + pub(super) fn keep_cast_owner(&self, owner: PyObjectRef) { + let _old = self + .kept_refs + .write() + .get_or_insert_with(Default::default) + .replace("@cast".to_owned(), Some(HiddenRefs::Single(owner))); + } + + // Follow provenance, including weak writer links. This is not GC traversal: + // upgrading a weak link does not make it a stored strong ownership edge. + fn provenance_children(obj: &PyObject, pending: &mut Vec) { + if let Some(cdata) = obj.downcast_ref::() { + pending.extend(cdata.objects.read().iter().cloned()); + pending.extend(cdata.base.read().iter().cloned()); + if let Some(refs) = cdata.kept_refs.read().as_ref() { + pending.extend(refs.snapshot()); + pending.extend(refs.buffer_alias.as_ref().map(|alias| alias.source.clone())); + } + } else if let Some(arg) = obj.downcast_ref::() { + pending.push(arg.obj.clone()); + pending.extend(arg.keep.iter().cloned()); + } else if let Some(dict) = obj.downcast_ref::() { + pending.extend(dict.values_vec()); + } else if let Some(tuple) = obj.downcast_ref::() { + pending.extend(tuple.as_slice().iter().cloned()); + } else if obj.downcast_ref::().is_some() { + pending.push(buffer_owner(obj).to_owned()); + } else if let Some(weak) = obj.downcast_ref::() { + pending.extend(weak.upgrade()); + } + } + + // Validate a short chain of native ownership links. The public dictionary + // is mutable: a live weak target and matching address alone prove nothing. + // Exact-key lookups must not run user equality during pointer assignment. + fn retains_writer_source( + parent: &PyObject, + source: &PyObject, + vm: &VirtualMachine, + ) -> PyResult { + if parent.downcast_ref::().is_some() { + return Ok(buffer_owner(parent).is(source)); + } + let Some(cdata) = parent.downcast_ref::() else { + return Ok(false); + }; + let base = cdata.base.read().clone(); + if base.is_some_and(|base| base.is(source)) { + return Ok(true); + } + let objects = cdata.objects.read().clone(); + if let Some(dict) = objects + .as_ref() + .and_then(|obj| obj.downcast_ref::()) + { + for found in [ + dict.inner_getitem_opt(&ObjectKey("1"), vm)?, + dict.inner_getitem_opt(&ObjectIdKey(source.get_id()), vm)?, + ] { + if found.is_some_and(|obj| obj.is(source)) { + return Ok(true); + } + } + } + if cdata + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.buffer_alias.as_ref()) + .is_some_and(|alias| alias.source.is(source)) + { + return Ok(true); + } + let cast = cdata + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.first("@cast")); + Ok(cast + .and_then(|arg| arg.downcast::().ok()) + .is_some_and(|arg| arg.obj.is(source))) + } + + fn writer_link_source( + parent: &PyObject, + link: &WriterLink, + vm: &VirtualMachine, + ) -> PyResult> { + let Some(source) = link.source.upgrade() else { + return Ok(None); + }; + let keys = match &link.origin { + WriterOrigin::Native => { + return Ok(Self::retains_writer_source(parent, &source, vm)?.then_some(source)); + } + WriterOrigin::Private { slot, index, owner } => { + let retained = parent.downcast_ref::().and_then(|cdata| { + let refs = cdata.kept_refs.read(); + let refs = refs.as_ref()?; + refs.slot_owners(slot) + .get(*index) + .filter(|value| value.get_id() == *owner) + .cloned() + }); + let valid = retained.is_some_and(|retained| { + retained.is(&source) + || retained + .downcast_ref::() + .is_some_and(|arg| { + arg.obj.is(&source) + || arg.keep.as_ref().is_some_and(|keep| keep.is(&source)) + }) + }); + return Ok(valid.then_some(source)); + } + WriterOrigin::Public(keys) => keys, + }; + let mut value = parent + .downcast_ref::() + .and_then(|cdata| cdata.objects.read().clone()); + for key in keys { + let Some(current) = value.as_ref() else { + return Ok(None); + }; + value = match key { + WriterKey::String(key) => match current.downcast_ref::() { + Some(dict) => dict.inner_getitem_opt(&ObjectKey(key), vm)?, + None => return Ok(None), + }, + WriterKey::Id(key) => match current.downcast_ref::() { + Some(dict) => dict.inner_getitem_opt(&ObjectIdKey(*key), vm)?, + None => return Ok(None), + }, + WriterKey::Index(index) => current + .downcast_ref::() + .and_then(|tuple| tuple.as_slice().get(*index)) + .cloned(), + }; + } + Ok(value.filter(|value| value.is(&source))) + } + + // A copied aggregate nests dictionaries, whereas writes through its views + // use flat index:parent keys. Follow both layouts without scanning siblings. + fn view_writer_objects( + cdata: &Self, + key: &str, + vm: &VirtualMachine, + ) -> PyResult)>> { + let mut pending: Vec<_> = cdata + .objects + .read() + .iter() + .cloned() + .map(|objects| (objects, key, Vec::new())) + .collect(); + let mut entries = Vec::new(); + let mut visited = std::collections::HashSet::new(); + while let Some((objects, key, path)) = pending.pop() { + if !visited.insert((objects.get_id(), key)) { + continue; + } + let Some(dict) = objects.downcast_ref::() else { + continue; + }; + for internal in ["0", "1"] { + let key = format!("{internal}:{key}"); + if let Some(value) = dict.inner_getitem_opt(&ObjectKey(&key), vm)? { + let mut path = path.clone(); + path.push(WriterKey::String(key)); + entries.push((value, path)); + } + } + for split in + core::iter::once(0).chain(key.match_indices(':').map(|(index, _)| index + 1)) + { + let suffix = &key[split..]; + if let Some(value) = dict.inner_getitem_opt(&ObjectKey(suffix), vm)? { + let mut path = path.clone(); + path.push(WriterKey::String(suffix.to_owned())); + if split == 0 { + entries.push((value, path)); + } else { + pending.push((value, &key[..split - 1], path)); + } + } + } + } + Ok(entries) + } + + // Copying an aggregate flattens its private owners into the aggregate's + // slot. Follow suffixes as for public metadata, but cache the exact member + // of that slot: the same owner can also survive in an unrelated field. + fn private_writer_sources(cdata: &Self, key: &str) -> Vec { + let retained = { + let refs = cdata.kept_refs.read(); + let Some(refs) = refs.as_ref() else { + return Vec::new(); + }; + core::iter::once(0) + .chain(key.match_indices(':').map(|(index, _)| index + 1)) + .flat_map(|split| { + let slot = &key[split..]; + refs.slot_owners(slot) + .iter() + .enumerate() + .map(move |(index, owner)| (slot.to_owned(), index, owner.clone())) + }) + .collect::>() + }; + let mut sources = Vec::new(); + for (slot, index, owner) in retained { + let origin = WriterOrigin::Private { + slot, + index, + owner: owner.get_id(), + }; + if let Some(arg) = owner.downcast_ref::() { + for source in core::iter::once(&arg.obj).chain(arg.keep.iter()) { + if source.downcast_ref::().is_some() + || source.downcast_ref::().is_some() + { + sources.push((source.clone(), origin.clone())); + } + } + } else if owner.downcast_ref::().is_some() + || owner.downcast_ref::().is_some() + { + sources.push((owner, origin)); + } + } + sources + } + + // A byref cast has separate metadata, unlike cast(array), which shares + // its dictionary. Project field keys only when the native layout and + // starting address match; arbitrary casts use the general search. + fn projected_writer_key<'a>( + pointer: &PyObject, + source: &PyObject, + key: &'a str, + ) -> Option<&'a str> { + let proto = { + let info = pointer.class().stg_info_opt()?; + if info.paramfunc != ParamFunc::Pointer { + return None; + } + info.proto.as_ref()?.clone() + }; + let pointer_data = pointer.downcast_ref::()?; + let source_data = source.downcast_ref::()?; + if source_data.base.read().is_some() { + return None; + } + let buffer = pointer_data.buffer.read(); + if buffer.len() < rustpython_host_env::ctypes::pointer_size() + || rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer) + != source_data.buffer.read().as_ptr() as usize + { + return None; + } + let source_info = source.class().stg_info_opt()?; + if source_info.paramfunc == ParamFunc::Array + && source_info + .element_type + .as_ref() + .is_some_and(|element| element.is(&proto)) + { + Some(key) + } else if source.class().is(&proto) { + let (field, index) = key.rsplit_once(':')?; + (index == "0").then_some(field) + } else { + None + } + } + + // Discover once, then validate exact keys without copying growing _objects + // dictionaries. Dictionary paths do not retain the dictionaries or values. + fn writer_paths( + pointer: &PyObject, + address: usize, + size: usize, + vm: &VirtualMachine, + view_key: Option<&str>, + ) -> PyResult)>> { + let mut pending = vec![(pointer.to_owned(), Vec::new())]; + let mut targets = Vec::new(); + let mut visited = std::collections::HashSet::new(); + let mut visited_containers = std::collections::HashSet::new(); + while let Some((obj, path)) = pending.pop() { + if !visited.insert(obj.get_id()) { + continue; + } + if !path.is_empty() && obj.downcast_ref::().is_some() { + let root = Self::find_root_object(&obj); + if let Some(storage) = root.downcast_ref::() { + // Keep smaller overlapping roots for later indexed writes. + // Borrowed roots also need their native exporters registered. + let owned_target = + storage.contains_storage(address, size) && !storage.is_borrowed(); + targets.push((root, path.clone())); + if owned_target { + continue; + } + } + } + let mut children = Vec::new(); + if let Some(cdata) = obj.downcast_ref::() { + let base = cdata.base.read().clone(); + let cast = cdata + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.first("@cast")) + .and_then(|arg| arg.downcast::().ok()); + let native_parent = base.is_some() || cast.is_some(); + let source_key = view_key.and_then(|key| { + if obj.is(pointer) { + Some(key) + } else { + Self::projected_writer_key(pointer, &obj, key) + } + }); + let entries = if let Some(key) = source_key { + Self::view_writer_objects(cdata, key, vm)? + } else { + cdata + .objects + .read() + .iter() + .cloned() + .map(|obj| (obj, Vec::new())) + .collect() + }; + let mut containers = Vec::new(); + for (value, keys) in entries { + if value.downcast_ref::().is_some() + || value.downcast_ref::().is_some() + { + children.push((value, WriterOrigin::Public(keys))); + } else { + containers.push((value, keys)); + } + } + while let Some((container, keys)) = containers.pop() { + if !visited_containers.insert(container.get_id()) { + continue; + } + let entries: Vec<_> = if let Some(dict) = container.downcast_ref::() { + dict.items_vec() + .into_iter() + .filter_map(|(key, value)| { + let key = if let Some(key) = key + .downcast_ref_if_exact::(vm) + .and_then(|key| key.as_wtf8().as_str().ok()) + { + WriterKey::String(key.to_owned()) + } else { + let key = key + .downcast_ref_if_exact::(vm) + .and_then(|key| key.as_bigint().to_usize()) + .filter(|key| *key == value.get_id())?; + WriterKey::Id(key) + }; + Some((key, value)) + }) + .collect() + } else if let Some(tuple) = container.downcast_ref::() { + tuple + .as_slice() + .iter() + .enumerate() + .map(|(index, value)| (WriterKey::Index(index), value.clone())) + .collect() + } else { + continue; + }; + let before = children.len(); + let mut nested = Vec::new(); + for (key, value) in entries { + // Other slots may be arbitrary py_object payloads, not + // native source links. Leave those to the general fallback. + let native_source = match &key { + WriterKey::String(key) => { + key == "1" || key == "-1" || key.starts_with("1:") + } + WriterKey::Id(_) | WriterKey::Index(1) => true, + WriterKey::Index(_) => false, + }; + let mut keys = keys.clone(); + keys.push(key); + if value.downcast_ref::().is_some() + || value.downcast_ref::().is_some() + { + if native_source { + children.push((value, WriterOrigin::Public(keys))); + } + } else if value.downcast_ref::().is_some() + || value.downcast_ref::().is_some() + { + nested.push((value, keys)); + } + } + // A native source already retains its own metadata. Do not + // mistake dictionaries stored as py_object values for more + // source links, making every later write scan all payloads. + if children.len() == before && !native_parent { + containers.extend(nested); + } + } + children.extend( + cdata + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.buffer_alias.as_ref()) + .map(|alias| (alias.source.clone(), WriterOrigin::Native)), + ); + if let Some(key) = source_key { + children.extend(Self::private_writer_sources(cdata, key)); + } + children.extend(base.map(|base| (base, WriterOrigin::Native))); + if let Some(arg) = cast { + children.push((arg.obj.clone(), WriterOrigin::Native)); + } + } else if obj.downcast_ref::().is_some() { + children.push((buffer_owner(&obj).to_owned(), WriterOrigin::Native)); + } + for (child, origin) in children { + let mut path = path.clone(); + path.push((child.clone(), origin)); + pending.push((child, path)); + } + } + Ok(targets) + } + + // Let the original storage find py_object values retained by a live writer. + // Weak links preserve the pointer's ownership lifetime; a normal write to + // the storage cannot leave a hidden strong reference to an obsolete value. + pub(super) fn register_pyobject_writer( + pointer: &PyObject, + address: usize, + size: usize, + index: usize, + vm: &VirtualMachine, + ) -> PyResult { + let storage = Self::find_writer_storage(pointer, address, size, vm)?; + Ok(CDataWrite::new(storage, || { + let root = Self::find_root_object(pointer); + let slot = if root.is(pointer) { + WriteSlot::Root(index) + } else { + WriteSlot::View(pointer.downcast_ref::().unwrap().unique_key(index)) + }; + WriteRange { + root, + slot, + address, + size, + } + })) + } + + fn index_write( + root: &PyObject, + slot: &WriteSlot, + address: usize, + size: usize, + vm: &VirtualMachine, + ) -> PyResult<()> { + if size == 0 { + return Ok(()); + } + let cdata = root.downcast_ref::().expect("ctypes retention root"); + let current = cdata.kept_refs.read().as_ref().is_some_and(|refs| { + refs.writes.get(slot).is_some_and(|registration| { + registration.record.address == address + && registration.record.size == size + && !registration.record.writer.is_dead() + }) + }); + if current { + return Ok(()); + } + // Allocate before locking. An entry is a hint, never permission to + // dereference native memory: readers still find a current owned object. + let record = alloc::sync::Arc::new(BufferWrite { + writer: root.downgrade(None, vm)?, + address, + size, + }); + let registry = vm.state.ctypes_buffer_views.clone(); + // The Arc allocation stays unique while either the token or its Weak + // is alive, so dropping an old token cannot remove a replacement. + let key = RangeKey::new(address, size, alloc::sync::Arc::as_ptr(&record) as usize); + let old = registry + .writes + .write() + .insert(key, size, alloc::sync::Arc::downgrade(&record)); + debug_assert!(old.is_none()); + let registration = WriteRegistration { + registry, + key, + record, + }; + let _old = cdata + .kept_refs + .write() + .get_or_insert_with(Default::default) + .writes + .insert(slot.clone(), registration); + // A slot owns at most its latest range; retargeting cannot accumulate + // unbounded history. The full provenance fallback preserves older aliases. + Ok(()) + } + + fn find_writer_storage( + pointer: &PyObject, + address: usize, + size: usize, + vm: &VirtualMachine, + ) -> PyResult> { + let cache_root = Self::find_root_object(pointer); + let writer = cache_root.downcast_ref::(); + let view_key = (!cache_root.is(pointer)) + .then(|| pointer.downcast_ref::().unwrap().unique_key(0)[2..].to_owned()); + let contents_key = view_key.as_ref().map(|key| format!("1:{key}")); + + // Register current contents separately: it may share the bytes with + // an older cast source that remains reachable through another path. + let direct = Self::register_contents_writer( + &cache_root, + contents_key.as_deref().unwrap_or("1"), + pointer, + address, + size, + vm, + )?; + let cached = writer.and_then(|writer| { + writer + .kept_refs + .read() + .as_ref() + .and_then(|refs| match &view_key { + Some(key) => refs.view_writer_paths.get(key).cloned(), + None => refs.writer_paths.clone(), + }) + }); + if let Some(paths) = cached { + // The common pointer(value) case has exactly one root. Its current + // contents and live registration were already checked above. + if paths.len() == 1 + && paths[0].len() == 1 + && let Some(root) = &direct + && view_key.is_none() + && !root.downcast_ref::().unwrap().is_borrowed() + && paths[0][0] + .source + .upgrade() + .is_some_and(|source| source.is(root)) + { + return Ok(direct); + } + let mut target = None; + let mut valid = true; + let mut direct_covered = direct.is_none(); + for path in paths.iter() { + let mut source = Some(cache_root.clone()); + for link in path { + let parent = source.as_ref().unwrap(); + if !parent.is(pointer) { + // A view's base pointer may change contents while its + // original private byref path is still valid. + Self::register_contents_writer(parent, "1", pointer, address, size, vm)?; + } + source = Self::writer_link_source(parent, link, vm)?; + if source.is_none() { + break; + } + } + let Some(source) = source else { + valid = false; + break; + }; + let Some(root) = Self::register_writer_source(&source, pointer, address, size, vm)? + else { + continue; + }; + // Resurrection may have cleared the registry's weakref even + // though the cached source path still exists. + if direct.as_ref().is_some_and(|direct| direct.is(&root)) { + direct_covered = true; + } + target = Some(root); + } + if valid && direct_covered && (direct.is_some() || target.is_some()) { + return Ok(direct.or(target)); + } + } + let targets = Self::writer_paths(&cache_root, address, size, vm, view_key.as_deref())?; + if !targets.is_empty() { + let mut cache = Vec::new(); + let mut target = None; + for (root, path) in targets { + let destination = Self::register_writer_source(&root, pointer, address, size, vm)?; + let overlaps = destination.is_some(); + // A field needs only paths to its own destination. Retargeting + // invalidates these by identity/range and rediscovers the path; + // retaining every sibling here would create N caches of N paths. + if view_key.is_some() && !overlaps { + continue; + } + if overlaps { + target = destination; + } + cache.push( + path.iter() + .map(|(obj, origin)| { + Ok(WriterLink { + source: obj.downgrade(None, vm)?, + origin: origin.clone(), + }) + }) + .collect::>>()?, + ); + } + if let Some(writer) = writer { + let _old = { + let mut refs = writer.kept_refs.write(); + let refs = refs.get_or_insert_with(Default::default); + match view_key { + Some(key) => refs.view_writer_paths.insert(key, cache.into()), + None => refs.writer_paths.replace(cache.into()), + } + }; + } + if direct.is_some() || target.is_some() { + return Ok(direct.or(target)); + } + } + let mut pending = Vec::new(); + Self::provenance_children(pointer, &mut pending); + let mut visited = std::collections::HashSet::new(); + let mut target = None; + while let Some(obj) = pending.pop() { + if !visited.insert(obj.get_id()) { + continue; + } + if let Some(root) = Self::register_writer_source(&obj, pointer, address, size, vm)? { + let storage = root.downcast_ref::().unwrap(); + let owned = !storage.is_borrowed() && storage.contains_storage(address, size); + target = Some(root); + if owned { + continue; + } + } + Self::provenance_children(&obj, &mut pending); + } + Ok(direct.or(target)) + } + + // A byref cast has separate ownership metadata and can write outside its + // source view while remaining inside the shared exporter. Let other aliases + // reach that writer through the source, including readers created later. + // Only an overlapping source can also pin the write's destination. + fn register_writer_source( + source: &PyObject, + pointer: &PyObject, + address: usize, + size: usize, + vm: &VirtualMachine, + ) -> PyResult> { + let root = Self::find_root_object(source); + let Some(storage) = root.downcast_ref::() else { + return Ok(None); + }; + let overlaps = storage.overlaps_storage(address, size); + let borrowed = storage + .kept_refs + .read() + .as_ref() + .is_some_and(|refs| refs.buffer_alias.is_some()); + if overlaps || borrowed { + Self::register_writer(&root, pointer, vm)?; + } + Ok(overlaps.then_some(root)) + } + + fn register_contents_writer( + parent: &PyObject, + key: &str, + pointer: &PyObject, + address: usize, + size: usize, + vm: &VirtualMachine, + ) -> PyResult> { + let objects = parent + .downcast_ref::() + .and_then(|parent| parent.objects.read().clone()); + let target = if let Some(dict) = objects + .as_ref() + .and_then(|obj| obj.downcast_ref::()) + { + dict.inner_getitem_opt(&ObjectKey(key), vm)? + .and_then(|owner| Self::overlapping_storage_root(&owner, address, size)) + } else { + None + }; + if let Some(root) = &target { + Self::register_writer(root, pointer, vm)?; + } + Ok(target) + } + + fn register_writer(root: &PyObject, pointer: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + // KeepRef stores a view's values in its root. The view itself may be a + // temporary, so the reverse link must follow the same retention owner. + let pointer = Self::find_root_object(pointer); + if root.is(&pointer) { + return Ok(()); + } + let cdata = root.downcast_ref::().expect("ctypes storage root"); + let existing = cdata + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.first("@writers")?.downcast::().ok()); + let views = if let Some(views) = existing { + views + } else { + // Allocation can collect and reenter, so do it before + // locking, then reuse a registry installed by reentry. + let candidate = vm.ctx.new_dict(); + let mut guard = cdata.kept_refs.write(); + let refs = guard.get_or_insert_with(Default::default); + let existing = refs + .first("@writers") + .and_then(|obj| obj.downcast::().ok()); + let (views, _old) = if let Some(views) = existing { + (views, Vec::new()) + } else { + let old = refs.replace( + "@writers".to_owned(), + Some(HiddenRefs::Single(candidate.clone().into())), + ); + (candidate, old) + }; + drop(guard); + // Adding a writer group can invalidate the shared owner snapshot. + // Release it outside the private-metadata lock. + views + }; + let registered = views + .inner_getitem_opt(&ObjectIdKey(pointer.get_id()), vm)? + .filter(|weak| { + weak.downcast_ref::() + .and_then(|weak| weak.upgrade()) + .is_some_and(|owner| owner.is(&pointer)) + }); + if registered.is_none() { + // Amortize dead-link cleanup across new registrations; + // scanning all live writers on every insert is quadratic. + let interval = views.entries.len().max(64); + let prune = { + let mut refs = cdata.kept_refs.write(); + let refs = refs.as_mut().expect("registered writer dictionary"); + if refs.writer_prune_remaining == 0 { + refs.writer_prune_remaining = interval; + true + } else { + refs.writer_prune_remaining -= 1; + false + } + }; + if prune { + for (key, weak) in views.items_vec() { + if weak + .downcast_ref::() + .is_some_and(|weak| weak.is_dead()) + { + let hash = PyDict::hash_or_unhashable(&*key, vm)?; + // Do not remove a replacement registered by another + // thread after this dead weakref was observed. + views.entries.delete_if( + vm, + &*key, + hash, + |current| Ok(current.is(&weak)), + )?; + } + } + } + let key: PyObjectRef = vm.ctx.new_int(pointer.get_id()).into(); + views.set_item(&*key, pointer.downgrade(None, vm)?.into(), vm)?; } - Ok(()) } - /// Keep a reference alive without exposing it in _objects. - /// Walks up to root object (same as keep_ref) so the reference - /// lives as long as the owning ctypes object. - /// Uses unique_key (hierarchical) so nested fields don't collide. - pub fn keep_alive(&self, index: usize, obj: PyObjectRef) { - let key = self.unique_key(index); - let base = self.base.read().clone(); - if let Some(base_obj) = base { - let root = Self::find_root_object(&base_obj); - if let Some(cdata) = root.downcast_ref::() { - cdata.kept_refs.write().insert(key, obj); - return; + fn overlapping_storage_root( + obj: &PyObject, + address: usize, + size: usize, + ) -> Option { + let root = Self::find_root_object(obj); + root.downcast_ref::() + .is_some_and(|storage| storage.overlaps_storage(address, size)) + .then_some(root) + } + + // Register every affected reader, even if the assignment is wider than its + // view. This is provenance bookkeeping, not validation of the native write. + fn overlaps_storage(&self, address: usize, size: usize) -> bool { + let buffer = self.buffer.read(); + let start = buffer.as_ptr() as usize; + self.base + .read() + .as_ref() + .is_none_or(|base| base.downcast_ref::().is_none()) + && size != 0 + && !buffer.is_empty() + && if address >= start { + address - start < buffer.len() + } else { + start - address < size } - } - self.kept_refs.write().insert(key, obj); } - /// Find the root object (one without a base) by walking up the base chain - fn find_root_object(obj: &PyObject) -> PyObjectRef { - // Try to get base from different ctypes types - let base = if let Some(cdata) = obj.downcast_ref::() { - cdata.base.read().clone() - } else { - None + fn contains_storage(&self, address: usize, size: usize) -> bool { + let buffer = self.buffer.read(); + self.base + .read() + .as_ref() + .is_none_or(|base| base.downcast_ref::().is_none()) + && address + .checked_sub(buffer.as_ptr() as usize) + .and_then(|offset| offset.checked_add(size)) + .is_some_and(|end| end <= buffer.len()) + } + + // Writes into a root's own storage already retain their values there. + // Follow only buffer/base links for borrowed storage, without searching + // growing _objects dictionaries or user values for an unrelated target. + fn register_storage_writer( + writer: &PyObject, + address: usize, + size: usize, + vm: &VirtualMachine, + ) -> PyResult> { + let Some(mut storage) = Self::overlapping_storage_root(writer, address, size) else { + return Ok(None); }; + if !storage.downcast_ref::().unwrap().is_borrowed() { + return Ok(Some(storage)); + } + let mut source = storage.clone(); + let mut visited = std::collections::HashSet::new(); + loop { + if !visited.insert(source.get_id()) { + return Ok(Some(storage)); + } + if let Some(cdata) = source.downcast_ref::() { + let Some(root) = Self::overlapping_storage_root(&source, address, size) else { + // A buffer view can be based on a pointer whose contents + // require the regular cast/contents provenance search. + return Ok(None); + }; + Self::register_writer(&root, writer, vm)?; + storage = root; + if !cdata.is_borrowed() { + return Ok(Some(storage)); + } + let base = cdata.base.read().clone(); + let next = if base.is_some() { + base + } else { + let objects = cdata.objects.read().clone(); + if let Some(dict) = objects + .as_ref() + .and_then(|obj| obj.downcast_ref::()) + { + dict.inner_getitem_opt(&ObjectKey("-1"), vm)? + } else { + None + } + }; + let next = next.or_else(|| { + cdata + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.buffer_alias.as_ref()) + .map(|alias| alias.source.clone()) + }); + let Some(next) = next else { + return Ok(Some(storage)); + }; + source = next; + } else if source.downcast_ref::().is_some() { + source = buffer_owner(&source).to_owned(); + } else { + return Ok(Some(storage)); + } + } + } - // Recurse if there's a base, otherwise this is the root - if let Some(base_obj) = base { - Self::find_root_object(&base_obj) - } else { - obj.to_owned() + pub(super) fn register_pyobject_view( + &self, + index: usize, + offset: usize, + size: usize, + vm: &VirtualMachine, + ) -> PyResult { + let base = self.base.read().clone(); + if let Some(base) = base { + let root = Self::find_root_object(&base); + let address = self.buffer.read().as_ptr().wrapping_add(offset) as usize; + let storage = match Self::register_storage_writer(&root, address, size, vm)? { + Some(storage) => Some(storage), + None => Self::find_writer_storage(&root, address, size, vm)?, + }; + return Ok(CDataWrite::new(storage, || WriteRange { + root, + slot: WriteSlot::View(self.unique_key(index)), + address, + size, + })); } + Ok(CDataWrite::default()) } - /// Store a value in an object's _objects dict with the given key - fn store_in_object( - obj: &PyObject, + fn update_object_index( + &self, + dict: &Py, key: &str, - value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - // Get the objects dict from the object - let objects_lock = if let Some(cdata) = obj.downcast_ref::() { - &cdata.objects - } else { - return Ok(()); // Unknown type, skip - }; - - let mut objects = objects_lock.write(); - - // Initialize if needed - if objects.is_none() { - *objects = Some(vm.ctx.new_dict().into()); - } - - // If not a dict, convert to dict - if let Some(obj) = objects.as_ref() - && obj.downcast_ref::().is_none() - { - let dict = vm.ctx.new_dict(); - let id_key: PyObjectRef = vm.ctx.new_int(obj.get_id() as i64).into(); - dict.set_item(&*id_key, obj.clone(), vm)?; - *objects = Some(dict.into()); + if self.kept_refs.read().as_ref().is_none_or(|refs| { + refs.object_index + .as_ref() + .is_none_or(|index| index.dictionary != dict.get_id()) + }) { + return Ok(()); } - - // Store in dict - if let Some(dict_obj) = objects.as_ref() - && let Some(dict) = dict_obj.downcast_ref::() + // set_item can run a displaced owner's finalizer. Observe the value + // after reentry, rather than publishing the outer assignment's value. + let value = dict.inner_getitem_opt(&ObjectKey(key), vm)?; + let len = dict.entries.len(); + let mut refs = self.kept_refs.write(); + if let Some(refs) = refs.as_mut() + && let Some(index) = refs.object_index.as_mut() + && index.dictionary == dict.get_id() { - let key_obj: PyObjectRef = vm.ctx.new_str(key).into(); - dict.set_item(&*key_obj, value, vm)?; + index.set( + WriterKey::String(key.to_owned()), + value.as_ref().map(|v| v.get_id()), + ); + // Direct user edits can remove keys without passing through KeepRef. + // Bound obsolete hints instead of accumulating assignment history. + if index.slots.len() > len.saturating_mul(2).saturating_add(64) { + refs.object_index = None; + } } - + drop(refs); Ok(()) } - /// Get kept objects from a CData instance - /// Returns the _objects of the CData, or an empty dict if None. - pub fn get_kept_objects(value: &PyObject, vm: &VirtualMachine) -> PyObjectRef { - value - .downcast_ref::() - .and_then(|cdata| cdata.objects.read().clone()) - .unwrap_or_else(|| vm.ctx.new_dict().into()) + fn indexed_object(&self, address: usize, vm: &VirtualMachine) -> PyResult> { + // Private owners already have an identity index; do not snapshot them + // merely to find a single retained object. + let private = self + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.owners.get(&address).map(|(value, _)| value.clone())); + if let Some(value) = private { + return Ok(Some(value)); + } + let objects = self.objects.read().clone(); + let Some(dict) = objects + .as_ref() + .and_then(|obj| obj.downcast_ref::()) + else { + return Ok(None); + }; + let build = self.kept_refs.read().as_ref().is_none_or(|refs| { + refs.object_index + .as_ref() + .is_none_or(|index| index.dictionary != dict.get_id()) + }); + if build { + let mut index = ObjectIndex { + dictionary: dict.get_id(), + slots: Default::default(), + values: Default::default(), + }; + // No metadata lock while snapshots release Python references. + for (key, value) in dict.items_vec() { + let key = if let Some(key) = key + .downcast_ref_if_exact::(vm) + .and_then(|key| key.as_wtf8().as_str().ok()) + { + WriterKey::String(key.to_owned()) + } else if let Some(key) = key + .downcast_ref_if_exact::(vm) + .and_then(|key| key.as_bigint().to_usize()) + { + WriterKey::Id(key) + } else { + continue; + }; + index.set(key, Some(value.get_id())); + } + self.kept_refs + .write() + .get_or_insert_with(Default::default) + .object_index = Some(Box::new(index)); + } + let attempts = self + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.object_index.as_ref()) + .filter(|index| index.dictionary == dict.get_id()) + .and_then(|index| index.values.get(&address)) + .map_or(0, ObjectKeys::len); + // Concurrent writers can reinsert stale hints. Bound retries and fall + // back to the ordinary graph search rather than spinning in the cache. + for _ in 0..attempts { + let key = self + .kept_refs + .read() + .as_ref() + .and_then(|refs| refs.object_index.as_ref()) + .filter(|index| index.dictionary == dict.get_id()) + .and_then(|index| index.values.get(&address).map(|keys| keys.first().clone())); + let Some(key) = key else { return Ok(None) }; + let value = match &key { + WriterKey::String(key) => dict.inner_getitem_opt(&ObjectKey(key), vm)?, + WriterKey::Id(key) => dict.inner_getitem_opt(&ObjectIdKey(*key), vm)?, + WriterKey::Index(_) => unreachable!("dictionary retention key"), + }; + // A concurrent write or direct _objects mutation may stale a hint. + // Only the current dictionary reference can establish ownership. + if value + .as_ref() + .is_some_and(|value| value.get_id() == address) + { + return Ok(value); + } + let mut refs = self.kept_refs.write(); + if let Some(index) = refs.as_mut().and_then(|refs| refs.object_index.as_mut()) + && index.dictionary == dict.get_id() + && index.slots.get(&key) == Some(&address) + { + index.set(key, value.as_ref().map(|value| value.get_id())); + } + drop(refs); + } + Ok(None) } - /// Check if a value should be stored in _objects - /// Returns true for ctypes objects and bytes (for c_char_p) - pub(crate) fn should_keep_ref(value: &PyObject) -> bool { - value.downcast_ref::().is_some() || value.downcast_ref::().is_some() + // Resolve a py_object through owned references, never by turning an + // arbitrary integer from native memory into a Rust reference. Views can + // reach the object through nested _objects dictionaries or cast cycles. + // slot is the native location read, distinct from the Python object address. + pub(super) fn object_at( + &self, + address: usize, + slot: usize, + index: Option, + vm: &VirtualMachine, + ) -> PyResult { + if address == 0 { + return Err(vm.new_value_error("PyObject is NULL")); + } + if address == vm.ctx.none.get_id() { + return Ok(vm.ctx.none()); + } + let objects = self.objects.read().clone(); + if let Some(obj) = &objects + && obj.get_id() == address + { + return Ok(obj.clone()); + } + let base = self.base.read().clone(); + let root = base.as_ref().map(|base| Self::find_root_object(base)); + let owners = root + .as_ref() + .and_then(|root| root.downcast_ref::()) + .and_then(|root| root.objects.read().clone()) + .or_else(|| objects.clone()); + if let Some(dict) = owners.as_ref().and_then(|obj| obj.downcast_ref::()) { + let key = self.unique_key(index.unwrap_or(0)); + // A scalar view's setter stores under "0:", whereas + // assignment through its parent stores under "". + let parent_key = if index.is_none() { + key.strip_prefix("0:") + } else { + None + }; + for key in core::iter::once(key.as_str()).chain(parent_key) { + if let Some(obj) = dict.inner_getitem_opt(&ObjectKey(key), vm)? + && obj.get_id() == address + { + return Ok(obj); + } + } + } + // Casts, copied aggregates and buffer views can retain the referent + // through other keys or containers. Search those only on a direct miss. + let mut pending: Vec<_> = objects.into_iter().collect(); + pending.extend(base); + if let Some(refs) = self.kept_refs.read().as_ref() { + pending.extend(refs.snapshot()); + pending.extend(refs.buffer_alias.as_ref().map(|alias| alias.source.clone())); + } + // Written ranges are hints to live retention roots, including writes + // outside a source view and copies whose original exporter view died. + // Only current Python owners with the matching identity can be returned. + pending.extend(vm.state.ctypes_buffer_views.writers(Some(slot))); + let mut visited = std::collections::HashSet::new(); + let mut exporters = std::collections::HashSet::new(); + let mut deferred_exporters: Vec = Vec::new(); + let mut searched_writers = false; + loop { + let Some(obj) = pending.pop() else { + if let Some(exporter) = deferred_exporters.pop() { + // A cast can write beyond its source view's declared extent. + // Preserve the full provenance search only after indexed paths + // miss; ordinary disjoint views never scan all sibling aliases. + pending.extend(vm.state.ctypes_buffer_views.owners(&exporter, None)); + } else if !searched_writers { + // Retargeting replaces a slot's range hint, but KeepRef(None) + // or another retention entry can keep its old value alive. + // Search current owners on a miss instead of storing every + // historical address. No native address becomes a reference. + searched_writers = true; + pending.extend(vm.state.ctypes_buffer_views.writers(None)); + } else { + break; + } + continue; + }; + if obj.get_id() == address { + return Ok(obj); + } + if !visited.insert(obj.get_id()) { + continue; + } + if let Some(cdata) = obj.downcast_ref::() + && let Some(value) = cdata.indexed_object(address, vm)? + { + return Ok(value); + } + if let Some(view) = obj.downcast_ref::() + && exporters.insert(buffer_owner(view.as_object()).get_id()) + { + let exporter = buffer_owner(view.as_object()); + pending.extend(vm.state.ctypes_buffer_views.owners(exporter, Some(slot))); + deferred_exporters.push(exporter.to_owned()); + } + Self::provenance_children(&obj, &mut pending); + } + Err(vm.new_value_error("PyObject is NULL")) } /// PyCData_set @@ -884,11 +3030,10 @@ impl PyCData { vm: &VirtualMachine, ) -> PyResult<()> { // Check if this is a c_char or c_wchar array field - let is_char_array = PyCField::is_char_array(proto, vm); - let is_wchar_array = PyCField::is_wchar_array(proto, vm); + let array_code = PyCField::array_type_code(proto); // For c_char arrays with bytes input, copy only up to first null - if is_char_array { + if array_code == Some('c') { if let Some(bytes_val) = value.downcast_ref::() { let src = bytes_val.as_bytes(); let to_copy = char_array_assignment_bytes(src); @@ -901,7 +3046,7 @@ impl PyCData { } // For c_wchar arrays with str input, convert to wchar_t - if is_wchar_array { + if array_code == Some('u') { if let Some(str_val) = value.downcast_ref::() { let wchar_bytes = rustpython_host_env::ctypes::encode_wtf8_to_wchar_padded( str_val.as_wtf8(), @@ -915,103 +3060,32 @@ impl PyCData { } } - // Special handling for Pointer fields with Array values - if let Some(proto_type) = proto.downcast_ref::() - && proto_type - .class() - .fast_issubclass(super::pointer::PyCPointerType::static_type()) - && let Some(array) = value.downcast_ref::() - { - let buffer_addr = { - let array_buffer = array.0.buffer.read(); - array_buffer.as_ptr() as usize - }; - let addr_bytes = rustpython_host_env::ctypes::pointer_to_sized_bytes(buffer_addr, size); - self.write_bytes_at_offset(offset, &addr_bytes); - self.keep_ref(index, value, vm)?; - return Ok(()); - } - - // For array fields with tuple/list input, instantiate the array type - // and unpack elements as positional args (Array_init expects *args) - if let Some(proto_type) = proto.downcast_ref::() - && let Some(stg) = proto_type.stg_info_opt() - && stg.element_type.is_some() - { - let items: Option> = - if let Some(tuple) = value.downcast_ref::() { - Some(tuple.as_slice().to_vec()) - } else { - value - .downcast_ref::() - .map(|list| list.borrow_vec().to_vec()) - }; - if let Some(items) = items { - let array_obj = proto_type.as_object().call(items, vm).map_err(|e| { - // Wrap errors in RuntimeError with type name prefix - let type_name = proto_type.name().to_string(); - let exc_name = e.class().name().to_string(); - let exc_args = e.args(); - let exc_msg = exc_args - .as_slice() - .first() - .and_then(|a| a.downcast_ref::().map(|s| s.to_string())) - .unwrap_or_default(); - vm.new_runtime_error(format!("({type_name}) {exc_name}: {exc_msg}")) - })?; - if let Some(arr) = array_obj.downcast_ref::() { - let arr_buffer = arr.0.buffer.read(); - let len = core::cmp::min(arr_buffer.len(), size); - self.write_bytes_at_offset(offset, &arr_buffer[..len]); - drop(arr_buffer); - self.keep_ref(index, array_obj, vm)?; - return Ok(()); - } - } - } - - // Get field type code for special handling - let field_type_code = proto - .get_attr("_type_", vm) - .ok() - .and_then(|attr| attr.downcast_ref::().map(|s| s.to_string())); - - // c_char_p (z type) with bytes: store original in _objects, keep - // null-terminated copy alive separately for the pointer. - if field_type_code.as_deref() == Some("z") - && let Some(bytes_val) = value.downcast_ref::() + let proto_type = proto + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("field proto is not a type"))?; + let write = if proto_type + .stg_info(vm)? + .flags + .intersects(StgInfoFlags::TYPEFLAG_ISPOINTER | StgInfoFlags::TYPEFLAG_HASPOINTER) { - let (kept_alive, ptr) = ensure_z_null_terminated(bytes_val, vm); - let result = - rustpython_host_env::ctypes::pointer_to_sized_bytes_endian(ptr, size, needs_swap); - self.write_bytes_at_offset(offset, &result); - self.keep_ref(index, value, vm)?; - self.keep_alive(index, kept_alive); - return Ok(()); - } - - let (mut bytes, converted_value) = if let Some(type_code) = &field_type_code { - PyCField::value_to_bytes_for_type(type_code, &value, size, vm)? + self.register_pyobject_view(index, offset, size, vm)? } else { - (PyCField::value_to_bytes(&value, size, vm), None) + CDataWrite::default() }; + let mut prepared = CDataValue::new(proto_type, &value, size, needs_swap, vm)?; + write.publish(vm)?; + self.write_value_at_offset(offset, &mut prepared.bytes); + prepared.keep(self, index, vm) + } - // Swap bytes for opposite endianness - if needs_swap { - bytes.reverse(); - } - - self.write_bytes_at_offset(offset, &bytes); - - // KeepRef: for z/Z types use converted value, otherwise use original - if let Some(converted) = converted_value { - self.keep_ref(index, converted, vm)?; - } else if Self::should_keep_ref(&value) { - let to_keep = Self::get_kept_objects(&value, vm); - self.keep_ref(index, to_keep, vm)?; + pub(super) fn into_view(self, cls: PyTypeRef, vm: &VirtualMachine) -> PyResult { + if cls.fast_issubclass(super::function::PyCFuncPtr::static_type()) { + super::function::PyCFuncPtr::from_cdata(self, vm) + .into_ref_with_type(vm, cls) + .map(Into::into) + } else { + self.into_ref_with_type(vm, cls).map(Into::into) } - - Ok(()) } /// PyCData_get @@ -1037,7 +3111,7 @@ impl PyCData { && stg.element_type.is_some() { // c_char array → return bytes - if PyCField::is_char_array(proto, vm) { + if PyCField::array_type_code(proto) == Some('c') { let data = &buffer[offset..offset + size]; return Ok(vm .ctx @@ -1046,18 +3120,26 @@ impl PyCData { } // c_wchar array → return str - if PyCField::is_wchar_array(proto, vm) { + if PyCField::array_type_code(proto) == Some('u') { let data = &buffer[offset..offset + size]; return Ok(vm.ctx.new_str(wchar_array_field_value(data)).into()); } - // Other array types - create array with a copy of data from the base's buffer - // The array also keeps a reference to the base for keeping it alive and for writes - let array_data = buffer[offset..offset + size].to_vec(); + // Array fields share their storage with the containing object. + // SAFETY: the field lies within the currently locked base buffer. + // The base reference retains the owner, not the allocation address; + // a reallocating resize can invalidate this view, as with other ctypes views. + let cdata_obj = unsafe { + Self::from_base_obj( + buffer.as_ptr().add(offset).cast_mut(), + size, + base_obj, + index, + ) + }; + cdata_obj.base_offset.store(offset); + cdata_obj.length.store(stg.length); drop(buffer); - - let cdata_obj = - Self::from_base_with_data(base_obj, offset, index, stg.length, array_data); let array_type: PyTypeRef = proto .to_owned() .downcast() @@ -1069,6 +3151,7 @@ impl PyCData { } let buffer_data = buffer[offset..offset + size].to_vec(); + let slot = buffer.as_ptr().wrapping_add(offset) as usize; drop(buffer); // Get proto as type @@ -1080,17 +3163,13 @@ impl PyCData { let proto_metaclass = proto_type.class(); // Simple types: return primitive value - if proto_metaclass.fast_issubclass(super::simple::PyCSimpleType::static_type()) { + if super::simple::returns_scalar(&proto_type) { + if proto_type.type_code(vm).as_deref() == Some("O") { + let address = rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer_data); + return self.object_at(address, slot, Some(index), vm); + } // Check for byte swapping - let needs_swap = base_obj - .class() - .as_object() - .get_attr("_swappedbytes_", vm) - .is_ok() - || proto_type - .as_object() - .get_attr("_swappedbytes_", vm) - .is_ok(); + let needs_swap = super::simple::is_swapped(&proto_type); let data = if needs_swap && size > 1 { let mut swapped = buffer_data; @@ -1107,11 +3186,13 @@ impl PyCData { let ptr = self.buffer.read().as_ptr().wrapping_add(offset) as *mut u8; let cdata_obj = unsafe { Self::from_base_obj(ptr, size, base_obj, index) }; - if proto_metaclass.fast_issubclass(super::structure::PyCStructType::static_type()) + if proto_metaclass.fast_issubclass(super::simple::PyCSimpleType::static_type()) + || proto_metaclass.fast_issubclass(super::structure::PyCStructType::static_type()) || proto_metaclass.fast_issubclass(super::union::PyCUnionType::static_type()) || proto_metaclass.fast_issubclass(super::pointer::PyCPointerType::static_type()) + || proto_type.fast_issubclass(super::function::PyCFuncPtr::static_type()) { - cdata_obj.into_ref_with_type(vm, proto_type).map(Into::into) + cdata_obj.into_view(proto_type, vm) } else { // Fallback Ok(vm.ctx.new_int(0).into()) @@ -1153,7 +3234,51 @@ impl Py { vm: &VirtualMachine, ) -> PyResult { let cdata = PyCData::from_buffer_impl(&cls, source, offset.unwrap_or(0), vm)?; - cdata.into_ref_with_type(vm, cls).map(Into::into) + let cdata = cdata.into_ref_with_type(vm, cls)?; + let objects = cdata + .objects + .read() + .as_ref() + .unwrap() + .clone() + .downcast::() + .unwrap(); + let source = objects.inner_getitem_opt(&ObjectKey("-1"), vm)?.unwrap(); + let exporter = buffer_owner(&source); + let weak = cdata.as_object().downgrade(None, vm)?; + let exporter_id = exporter.get_id(); + let (address, size) = { + let buffer = cdata.buffer.read(); + (buffer.as_ptr() as usize, buffer.len()) + }; + let key = RangeKey::new(address, size, cdata.get_id()); + { + let mut refs = cdata.kept_refs.write(); + let refs = refs.get_or_insert_with(Default::default); + // Scalar assignment can replace _objects. Keep the buffer export + // for the borrowed slice's lifetime and prevent identity reuse. + refs.buffer_alias = Some(BufferAlias { + registry: vm.state.ctypes_buffer_views.clone(), + exporter: exporter_id, + key, + source, + }); + } + let old = vm + .state + .ctypes_buffer_views + .views + .write() + .entry(exporter_id) + .or_default() + .insert(key, size, weak); + drop(old); + // A native CData exporter must also see direct scalar assignments; + // those replace the view's _objects without going through a pointer. + if PyCData::register_storage_writer(cdata.as_object(), address, size, vm)?.is_none() { + PyCData::find_writer_storage(cdata.as_object(), address, size, vm)?; + } + Ok(cdata.into()) } #[pyclassmethod] @@ -1184,6 +3309,19 @@ impl Py { return Err(vm.new_type_error("abstract class")); } + if isize::try_from(size).is_err() { + return Err(vm.new_overflow_error("size too large")); + } + + if address == 0 { + return Err(vm.new_value_error("NULL pointer access")); + } + + let addr = address as usize; + if addr.checked_add(size).is_none() { + return Err(vm.new_overflow_error("address overflow")); + } + // PyCData_AtAddress let cdata = unsafe { PyCData::at_address(address as *const u8, size) }; cdata.into_ref_with_type(vm, cls).map(Into::into) @@ -1205,6 +3343,10 @@ impl Py { return Err(vm.new_type_error("abstract class")); } + if isize::try_from(size).is_err() { + return Err(vm.new_overflow_error("size too large")); + } + // Get the library handle from dll object let handle = if let Ok(int_handle) = dll.try_int(vm) { int_handle @@ -1250,7 +3392,7 @@ impl Py { // PyCField - Field descriptor for Structure/Union types -#[pyclass(name = "CField", module = "ctypes")] +#[pyclass(name = "CField", module = "ctypes", traverse = "manual")] #[derive(Debug, PyPayload)] pub struct PyCField { /// Field name @@ -1271,6 +3413,13 @@ pub struct PyCField { pub(crate) bit_offset_val: u16, } +// SAFETY: proto is the descriptor's only owned Python reference. +unsafe impl Traverse for PyCField { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.proto.traverse(tracer); + } +} + impl PyCField { /// Create a new CField descriptor (non-bitfield) pub fn new( @@ -1314,6 +3463,30 @@ impl PyCField { } } + pub(super) fn checked_bitfield_size( + name: &str, + proto: &Py, + value: &PyObject, + vm: &VirtualMachine, + ) -> PyResult { + let bits = value.try_int(vm)?.as_bigint().to_u16(); + let info = proto.stg_info(vm)?; + let bits = bits + .filter(|&bits| bits > 0 && usize::from(bits) <= info.size * 8) + .ok_or_else(|| { + vm.new_value_error(format!("number of bits invalid for bit field '{name}'")) + })?; + if !matches!( + info.scalar_code, + Some('b' | 'B' | 'h' | 'H' | 'i' | 'I' | 'l' | 'L' | 'q' | 'Q' | '?') + ) { + return Err( + vm.new_type_error(format!("bit fields not allowed for type {}", proto.name())) + ); + } + Ok(bits) + } + /// Get the byte size of the field's underlying type pub fn get_byte_size(&self) -> usize { self.byte_size_val as usize @@ -1410,7 +3583,16 @@ impl Constructor for PyCField { .transpose()?; if let Some(bs) = bit_size_val { - if bs < 0 { + if !matches!( + field_type.stg_info(vm)?.scalar_code, + Some('b' | 'B' | 'h' | 'H' | 'i' | 'I' | 'l' | 'L' | 'q' | 'Q' | '?') + ) { + return Err(vm.new_type_error(format!( + "bit fields not allowed for type {}", + field_type.name() + ))); + } + if bs <= 0 { return Err(vm.new_value_error("number of bits invalid for bit field")); } let bo = bit_offset_val.unwrap_or(0); @@ -1418,7 +3600,7 @@ impl Constructor for PyCField { return Err(vm.new_value_error("bit_offset must be >= 0")); } let type_bits = byte_size * 8; - if bo + bs > type_bits { + if bs > type_bits || bo > type_bits - bs { return Err(vm.new_value_error(format!( "bit field '{name}' overflows its type ({bo} + {bs} > {type_bits})" ))); @@ -1484,6 +3666,33 @@ impl GetDescriptor for PyCField { // Get PyCData from obj (works for both Structure and Union) let cdata = Self::get_cdata_from_obj(&obj, vm)?; + // CPython's c_bool bitfields read the whole byte. User scalar subclasses + // return storage-backed instances rather than decoded primitive values. + if zelf.bitfield_size > 0 + && super::simple::returns_scalar(&zelf.proto) + && zelf.proto.stg_info(vm)?.scalar_code != Some('?') + { + let buffer = cdata.buffer.read(); + let data = buffer + .get(offset..offset.saturating_add(size)) + .ok_or_else(|| vm.new_value_error("field outside the buffer"))?; + let value = zelf.bitfield_word(data); + let bits = zelf.bitfield_size as u32; + let value = (value >> zelf.bit_offset_val) & (u64::MAX >> (64 - bits)); + let signed = matches!( + zelf.proto.stg_info(vm)?.scalar_code, + Some('b' | 'h' | 'i' | 'l' | 'q') + ); + drop(buffer); + return Ok(if signed { + vm.ctx + .new_int(((value << (64 - bits)) as i64) >> (64 - bits)) + .into() + } else { + vm.ctx.new_int(value).into() + }); + } + // PyCData_get cdata.get_field( zelf.proto.as_object(), @@ -1497,204 +3706,25 @@ impl GetDescriptor for PyCField { } impl PyCField { - /// Convert a Python value to bytes - fn value_to_bytes(value: &PyObject, size: usize, vm: &VirtualMachine) -> Vec { - // 1. Handle bytes objects - if let Some(bytes) = value.downcast_ref::() { - rustpython_host_env::ctypes::copy_to_sized_bytes(bytes.as_bytes(), size) - } - // 2. Handle ctypes array instances (copy their buffer) - else if let Some(cdata) = value.downcast_ref::() { - let buffer = cdata.buffer.read(); - rustpython_host_env::ctypes::copy_to_sized_bytes(&buffer, size) - } - // 4. Handle float values (check before int, since float.try_int would truncate) - else if let Some(float_val) = value.downcast_ref::() { - let f = float_val.to_f64(); - match size { - 4 | 8 => rustpython_host_env::ctypes::float_to_sized_bytes(f, size) - .expect("float size checked"), - _ => unreachable!("wrong payload size"), - } - } - // 4. Handle integer values - else if let Ok(int_val) = value.try_int(vm) { - let i = int_val.as_bigint(); - match size { - 1 => rustpython_host_env::ctypes::int_to_sized_bytes( - i.to_i8().unwrap_or(0).into(), - size, - ), - 2 => rustpython_host_env::ctypes::int_to_sized_bytes( - i.to_i16().unwrap_or(0).into(), - size, - ), - 4 => rustpython_host_env::ctypes::int_to_sized_bytes( - i.to_i32().unwrap_or(0).into(), - size, - ), - 8 => rustpython_host_env::ctypes::int_to_sized_bytes(i.to_i64().unwrap_or(0), size), - _ => rustpython_host_env::ctypes::zeroed_bytes(size), - } - } else { - rustpython_host_env::ctypes::zeroed_bytes(size) - } - } - - /// Convert a Python value to bytes with type-specific handling for pointer types. - /// Returns (bytes, optional holder for wchar buffer). - fn value_to_bytes_for_type( - type_code: &str, - value: &PyObject, - size: usize, - vm: &VirtualMachine, - ) -> PyResult<(Vec, Option)> { - match type_code { - // c_float: always convert to float first (f_set) - "f" => { - let f = if let Some(float_val) = value.downcast_ref::() { - float_val.to_f64() - } else if let Ok(int_val) = value.try_int(vm) { - int_val.as_bigint().to_i64().unwrap_or(0) as f64 - } else { - return Err(vm.new_type_error(format!( - "float expected instead of {}", - value.class().name() - ))); - }; - Ok(( - rustpython_host_env::ctypes::float_to_sized_bytes(f, 4) - .expect("c_float size is fixed"), - None, - )) - } - // c_double: always convert to float first (d_set) - "d" => { - let f = if let Some(float_val) = value.downcast_ref::() { - float_val.to_f64() - } else if let Ok(int_val) = value.try_int(vm) { - int_val.as_bigint().to_i64().unwrap_or(0) as f64 - } else { - return Err(vm.new_type_error(format!( - "float expected instead of {}", - value.class().name() - ))); - }; - Ok(( - rustpython_host_env::ctypes::float_to_sized_bytes(f, 8) - .expect("c_double size is fixed"), - None, - )) - } - // c_longdouble: convert to float (treated as f64 in RustPython) - "g" => { - let f = if let Some(float_val) = value.downcast_ref::() { - float_val.to_f64() - } else if let Ok(int_val) = value.try_int(vm) { - int_val.as_bigint().to_i64().unwrap_or(0) as f64 - } else { - return Err(vm.new_type_error(format!( - "float expected instead of {}", - value.class().name() - ))); - }; - Ok(( - rustpython_host_env::ctypes::float_to_sized_bytes(f, 8) - .expect("c_longdouble bytes are stored as f64"), - None, - )) - } - "z" => { - // c_char_p with bytes is handled in set_field before this call. - // This handles integer address and None cases. - // Integer address - if let Ok(int_val) = value.try_index(vm) { - let v = int_val.as_bigint().to_usize().unwrap_or(0); - return Ok(( - rustpython_host_env::ctypes::pointer_to_sized_bytes(v, size), - None, - )); - } - // None -> NULL pointer - if vm.is_none(value) { - return Ok((rustpython_host_env::ctypes::zeroed_bytes(size), None)); - } - Ok((Self::value_to_bytes(value, size, vm), None)) - } - "Z" => { - // c_wchar_p: store pointer to null-terminated wchar_t buffer - if let Some(s) = value.downcast_ref::() { - let (holder, ptr) = str_to_wchar_bytes(s.as_wtf8(), vm); - return Ok(( - rustpython_host_env::ctypes::pointer_to_sized_bytes(ptr, size), - Some(holder), - )); - } - // Integer address - if let Ok(int_val) = value.try_index(vm) { - let v = int_val.as_bigint().to_usize().unwrap_or(0); - return Ok(( - rustpython_host_env::ctypes::pointer_to_sized_bytes(v, size), - None, - )); - } - // None -> NULL pointer - if vm.is_none(value) { - return Ok((rustpython_host_env::ctypes::zeroed_bytes(size), None)); - } - Ok((Self::value_to_bytes(value, size, vm), None)) - } - "P" => { - // c_void_p: store integer as pointer - if let Ok(int_val) = value.try_index(vm) { - let v = int_val.as_bigint().to_usize().unwrap_or(0); - return Ok(( - rustpython_host_env::ctypes::pointer_to_sized_bytes(v, size), - None, - )); - } - // None -> NULL pointer - if vm.is_none(value) { - return Ok((rustpython_host_env::ctypes::zeroed_bytes(size), None)); - } - Ok((Self::value_to_bytes(value, size, vm), None)) - } - _ => Ok((Self::value_to_bytes(value, size, vm), None)), - } - } - - /// Check if the field type is a c_char array (element type has _type_ == 'c') - fn is_char_array(proto: &PyObject, vm: &VirtualMachine) -> bool { - // Get element_type from StgInfo (for array types) - if let Some(proto_type) = proto.downcast_ref::() - && let Some(stg) = proto_type.stg_info_opt() - && let Some(element_type) = &stg.element_type + fn bitfield_word(&self, data: &[u8]) -> u64 { + let mut bytes = [0; 8]; + if self + .proto + .stg_info_opt() + .is_some_and(|info| info.big_endian) { - // Check if element type has _type_ == "c" - if let Ok(type_code) = element_type.as_object().get_attr("_type_", vm) - && let Some(s) = type_code.downcast_ref::() - { - return s.as_bytes() == b"c"; - } + bytes[8 - data.len()..].copy_from_slice(data); + u64::from_be_bytes(bytes) + } else { + bytes[..data.len()].copy_from_slice(data); + u64::from_le_bytes(bytes) } - false } - /// Check if the field type is a c_wchar array (element type has _type_ == 'u') - fn is_wchar_array(proto: &PyObject, vm: &VirtualMachine) -> bool { - // Get element_type from StgInfo (for array types) - if let Some(proto_type) = proto.downcast_ref::() - && let Some(stg) = proto_type.stg_info_opt() - && let Some(element_type) = &stg.element_type - { - // Check if element type has _type_ == "u" - if let Ok(type_code) = element_type.as_object().get_attr("_type_", vm) - && let Some(s) = type_code.downcast_ref::() - { - return s.as_bytes() == b"u"; - } - } - false + // Character-array fields use the element's initialized scalar converter. + fn array_type_code(proto: &PyObject) -> Option { + let info = proto.downcast_ref::()?.stg_info_opt()?; + info.element_type.as_ref()?.stg_info_opt()?.scalar_code } } @@ -1737,17 +3767,44 @@ impl Py { match value { PySetterValue::Assign(value) => { // Check if needs byte swapping - let needs_swap = (obj - .class() - .as_object() - .get_attr("_swappedbytes_", vm) - .is_ok() - || zelf - .proto - .as_object() - .get_attr("_swappedbytes_", vm) - .is_ok()) - && size > 1; + let needs_swap = super::simple::is_swapped(&zelf.proto) && size > 1; + + let code = zelf.proto.stg_info(vm)?.scalar_code; + // Match CPython: c_bool writes the whole byte, even for bitfields. + if zelf.bitfield_size > 0 && code != Some('?') { + let code = code.ok_or_else(|| vm.new_type_error("invalid bitfield type"))?; + let mut encoded = [0; 4]; + // __index__ may reenter and change adjacent fields. Convert + // before locking, then merge into the current storage. + let (bytes, _, _) = super::simple::assignment_value( + code.encode_utf8(&mut encoded), + &value, + needs_swap, + vm, + )?; + let value = zelf.bitfield_word(&bytes); + let bits = zelf.bitfield_size as u32; + let mask = (u64::MAX >> (64 - bits)) << zelf.bit_offset_val; + let mut buffer = cdata.buffer.write(); + let data = buffer + .get(offset..offset.saturating_add(size)) + .ok_or_else(|| vm.new_value_error("field outside the buffer"))?; + let word = (zelf.bitfield_word(data) & !mask) + | ((value << zelf.bit_offset_val) & mask); + let big_endian = zelf.proto.stg_info(vm)?.big_endian; + let bytes = if big_endian { + word.to_be_bytes() + } else { + word.to_le_bytes() + }; + let data = if big_endian { + &bytes[8 - size..] + } else { + &bytes[..size] + }; + write_cow_bytes_at_offset(&mut buffer, offset, data); + return Ok(()); + } // PyCData_set cdata.set_field( @@ -1899,14 +3956,17 @@ fn array_paramfunc(obj: &PyObject, vm: &VirtualMachine) -> PyResult /// PyCPointerType_paramfunc fn pointer_paramfunc(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + use super::function::PyCFuncPtr; use super::pointer::PyCPointer; - let ptr = obj - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("expected pointer"))?; - // parg->value.p = *(void **)self->b_ptr - let ptr_val = ptr.get_ptr_value(); + let ptr_val = if let Some(ptr) = obj.downcast_ref::() { + ptr.get_ptr_value() + } else if let Some(funcptr) = obj.downcast_ref::() { + funcptr.get_func_ptr() + } else { + return Err(vm.new_type_error("expected pointer")); + }; Ok(CArgObject { tag: b'P', @@ -2014,11 +4074,7 @@ pub(super) fn bytes_to_pyobject( bytes: &[u8], vm: &VirtualMachine, ) -> PyObjectRef { - // Try to get _type_ attribute - if let Ok(type_attr) = cls.as_object().get_attr("_type_", vm) - && let Ok(s) = type_attr.str(vm) - { - let ty = s.to_string(); + if let Some(ty) = cls.type_code(vm) { return match rustpython_host_env::ctypes::decode_type_code(ty.as_str(), bytes) { rustpython_host_env::ctypes::DecodedValue::Bytes(value) => { vm.ctx.new_bytes(value).into() @@ -2043,6 +4099,10 @@ pub(super) fn bytes_to_pyobject( rustpython_host_env::ctypes::DecodedValue::String(value) => { vm.ctx.new_str(value).into() } + #[cfg(windows)] + rustpython_host_env::ctypes::DecodedValue::WideString(value) => { + vm.ctx.new_str(value).into() + } rustpython_host_env::ctypes::DecodedValue::None => vm.ctx.none(), }; } @@ -2072,27 +4132,17 @@ pub(super) fn get_usize_attr( Ok(val.to_usize().unwrap_or(default)) } -/// Check if a type is a "simple instance" (direct subclass of a simple type) -/// Returns TRUE for c_int, c_void_p, etc. (simple types with _type_ attribute) -/// Returns FALSE for Structure, Array, POINTER(T), etc. -pub(super) fn is_simple_instance(typ: &Py) -> bool { - // _ctypes_simple_instance - // Check if the type's metaclass is PyCSimpleType - let metaclass = typ.class(); - metaclass.fast_issubclass(super::simple::PyCSimpleType::static_type()) -} - /// Set or initialize StgInfo on a type pub(super) fn set_or_init_stginfo(type_ref: &PyType, stg_info: StgInfo) { - if type_ref.init_type_data(stg_info.clone()).is_err() + if type_ref.init_traced_type_data(stg_info.clone()).is_err() && let Some(mut existing) = type_ref.get_type_data_mut::() { // Preserve pointer_type cache across StgInfo replacement - let old_pointer_type = existing.pointer_type.take(); - *existing = stg_info; + let mut old = core::mem::replace(&mut *existing, stg_info); if existing.pointer_type.is_none() { - existing.pointer_type = old_pointer_type; + existing.pointer_type = old.pointer_type.take(); } + drop(existing); } } diff --git a/crates/vm/src/stdlib/_ctypes/function.rs b/crates/vm/src/stdlib/_ctypes/function.rs index e67e3871d14..940d20a3add 100644 --- a/crates/vm/src/stdlib/_ctypes/function.rs +++ b/crates/vm/src/stdlib/_ctypes/function.rs @@ -1,6 +1,8 @@ // spell-checker:disable #![allow(unreachable_pub)] +use crate::object::{Traverse, TraverseFn}; + use super::{ _ctypes::CArgObject, PyCArray, PyCData, PyCPointer, PyCStructure, PyCUnion, StgInfo, @@ -11,13 +13,15 @@ use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, builtins::{PyBytes, PyDict, PyInt, PyStr, PyTuple, PyType, PyTypeRef}, class::StaticType, - function::FuncArgs, - protocol::{BufferDescriptor, PyBuffer, PyNumberMethods}, - types::{AsBuffer, AsNumber, Callable, Constructor, Initializer, Representable}, - vm::thread::with_current_vm, + function::{FuncArgs, PySetterValue}, + protocol::{BufferDescriptor, PyBuffer, PyNumberMethods, PySequenceMethods}, + types::{AsBuffer, AsNumber, AsSequence, Callable, Constructor, Initializer, Representable}, + vm::thread::{PyOperation, with_current_vm}, }; +#[cfg(windows)] +use crate::{TryFromObject, function::ArgBytesLike}; use alloc::borrow::Cow; -use core::ffi::c_void; +use core::ffi::{c_int, c_long, c_ulong, c_void}; use core::fmt::Debug; use core::ptr::NonNull; use num_traits::{Signed, ToPrimitive}; @@ -27,7 +31,7 @@ use rustpython_host_env::ctypes::ComMethodError; use rustpython_host_env::ctypes::{ CTypeLayout, CallError, CallOptions, CallRet, CallValue, FfiCif, FfiCodePtr, FfiType, RawMemoryView, RawMemoryViewError, StringAtError, call, ffi_pointer_type, ffi_type_from_code, - ffi_void_type, has_pointer_width, offset_address, pointer_bytes, pointer_format, pointer_size, + ffi_void_type, has_pointer_width, pointer_bytes, pointer_format, pointer_size, simple_type_is_pointer, write_pointer_to_buffer_at, write_prefix_limited, }; @@ -41,42 +45,36 @@ pub(super) const INTERNAL_MEMORYVIEW_AT_ADDR: usize = 4; /// Convert any object to a pointer value for c_void_p arguments /// Follows ConvParam logic for pointer types -fn convert_to_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult { +fn convert_to_pointer( + value: &PyObject, + vm: &VirtualMachine, +) -> PyResult<(CArgValue, Option)> { + let pointer = |address| Ok((CArgValue::pointer(address), Some(value.to_owned()))); // 0. CArgObject (from byref()) -> buffer address + offset if let Some(carg) = value.downcast_ref::() { - // Get buffer address from the underlying object - let base_addr = if let Some(cdata) = carg.obj.downcast_ref::() { - cdata.buffer.read().as_ptr() as usize - } else { - return Err(vm.new_type_error(format!( - "byref() argument must be a ctypes instance, not '{}'", - carg.obj.class().name() - ))); - }; - let addr = (base_addr as isize + carg.offset) as usize; - return Ok(CArgValue::pointer(addr)); + return Ok((carg.value.clone(), Some(value.to_owned()))); } // 1. None -> NULL if value.is(&vm.ctx.none) { - return Ok(CArgValue::pointer(0)); + return Ok((CArgValue::pointer(0), None)); } // 2. PyCArray -> buffer address (PyCArrayType_paramfunc) if let Some(array) = value.downcast_ref::() { let addr = array.0.buffer.read().as_ptr() as usize; - return Ok(CArgValue::pointer(addr)); + return pointer(addr); } // 3. PyCPointer -> stored pointer value if let Some(ptr) = value.downcast_ref::() { - return Ok(CArgValue::pointer(ptr.get_ptr_value())); + return pointer(ptr.get_ptr_value()); } // 4. PyCStructure -> buffer address if let Some(struct_obj) = value.downcast_ref::() { let addr = struct_obj.0.buffer.read().as_ptr() as usize; - return Ok(CArgValue::pointer(addr)); + return pointer(addr); } // 5. PyCSimple (c_void_p, c_char_p, etc.) -> value from buffer @@ -84,14 +82,14 @@ fn convert_to_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult buffer address (PyBytes_AsString) + // 6. bytes -> owned, null-terminated buffer if let Some(bytes) = value.downcast_ref::() { - let addr = bytes.as_bytes().as_ptr() as usize; - return Ok(CArgValue::pointer(addr)); + let (owner, address) = super::base::ensure_z_null_terminated(bytes, vm); + return Ok((CArgValue::pointer(address), Some(owner))); } // 7. Integer -> direct value (PyLong_AsVoidPtr behavior) @@ -100,10 +98,10 @@ fn convert_to_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult PyResult { // 1. CArgObject (from byref() or paramfunc) -> use stored value if let Some(carg) = value.downcast_ref::() { return Ok(Argument { - keep: carg.keep.clone(), + // Keep the wrapper, which owns both the source and any auxiliary + // pointer storage. `_as_parameter_` may have created it on demand. + keep: Some(value.to_owned()), value: carg.value.clone(), }); } @@ -141,9 +141,10 @@ fn conv_param(value: &PyObject, vm: &VirtualMachine) -> PyResult { // 3. ctypes objects -> use paramfunc if let Ok(carg) = super::base::call_paramfunc(value, vm) { + let value = carg.value.clone(); return Ok(Argument { - keep: carg.keep, - value: carg.value, + keep: Some(carg.into_ref(&vm.ctx).into()), + value, }); } @@ -175,7 +176,26 @@ fn conv_param(value: &PyObject, vm: &VirtualMachine) -> PyResult { // `__int__` would accept a float and pass its truncated value where the // callee expects a pointer. if let Some(int_val) = value.downcast_ref::() { - let val = int_val.as_bigint().to_i32().unwrap_or(0); + // CPython first accepts the platform's unsigned long / signed long + // range, then stores the low C-int bits in the argument carrier. + let bigint = int_val.as_bigint(); + #[allow( + clippy::useless_conversion, + clippy::unnecessary_cast, + reason = "C long is 32 bits on Windows and 64 bits on LP64 targets" + )] + let val = if bigint.is_negative() { + bigint + .to_i64() + .and_then(|value| c_long::try_from(value).ok()) + .map(|value| value as c_int) + } else { + bigint + .to_u64() + .and_then(|value| c_ulong::try_from(value).ok()) + .map(|value| value as c_int) + } + .ok_or_else(|| vm.new_overflow_error("int too long to convert"))?; return Ok(Argument { keep: None, value: CArgValue::Int(val), @@ -193,6 +213,29 @@ fn conv_param(value: &PyObject, vm: &VirtualMachine) -> PyResult { ))) } +fn conv_param_for_call(value: &PyObject, index: usize, vm: &VirtualMachine) -> PyResult { + match conv_param(value, vm) { + Ok(argument) => Ok(argument), + Err(error) => { + let error_type = vm + .import("_ctypes", 0)? + .get_attr("ArgumentError", vm)? + .downcast::() + .map_err(|_| vm.new_type_error("ArgumentError is not a type"))?; + Err(vm.new_exception_msg( + error_type, + format!( + "argument {}: {}: {}", + index + 1, + error.class().name(), + error.as_object().str(vm)?, + ) + .into(), + )) + } + } +} + trait ArgumentType { /// Convert an argument for this type into a foreign-call value plus an /// optional owner keeping any referenced memory alive. @@ -214,21 +257,16 @@ impl ArgumentType for PyTypeRef { // type must carry a known _type_ code; anything else is unsupported. let type_code = if self.fast_issubclass(CArgObject::static_type()) || self.fast_issubclass(PyCPointer::static_type()) + || self.fast_issubclass(PyCFuncPtr::static_type()) || self.fast_issubclass(PyCStructure::static_type()) || self.fast_issubclass(PyCUnion::static_type()) { None } else { - // Use get_attr to traverse MRO (for subclasses like MyInt(c_int)) + // Converters belong to initialized storage, not mutable _type_. let typ = self - .as_object() - .get_attr(vm.ctx.intern_str("_type_"), vm) - .ok() + .type_code(vm) .ok_or_else(|| vm.new_type_error("Unsupported argument type"))?; - let typ = typ - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("Unsupported argument type"))? - .to_string(); if ffi_type_from_code(&typ).is_none() { return Err(vm.new_type_error(format!("Unsupported argument type: {typ}"))); } @@ -246,7 +284,7 @@ impl ArgumentType for PyTypeRef { // Then pass the converted value to ConvParam logic // CArgObject (from from_param) -> use stored value and keepalive directly if let Some(carg) = converted.downcast_ref::() { - return Ok((carg.value.clone(), carg.keep.clone())); + return Ok((carg.value.clone(), Some(converted.clone()))); } // None -> NULL pointer @@ -254,12 +292,20 @@ impl ArgumentType for PyTypeRef { return Ok((CArgValue::pointer(0), None)); } + if self.fast_issubclass(PyCFuncPtr::static_type()) { + let argument = conv_param(&converted, vm)?; + return Ok((argument.value, argument.keep)); + } + // For pointer types (POINTER(T)), we need to pass the pointer VALUE stored in buffer if self.fast_issubclass(PyCPointer::static_type()) { if let Some(pointer) = converted.downcast_ref::() { - return Ok((CArgValue::pointer(pointer.get_ptr_value()), None)); + return Ok(( + CArgValue::pointer(pointer.get_ptr_value()), + Some(converted.clone()), + )); } - return Ok((convert_to_pointer(&converted, vm)?, None)); + return convert_to_pointer(&converted, vm); } // For structure/union types, pass the aggregate by value: snapshot the @@ -272,19 +318,19 @@ impl ArgumentType for PyTypeRef { let bytes = cdata.buffer.read().to_vec(); let layout = self.stg_info_opt().map_or_else( || CTypeLayout::Opaque { size: bytes.len() }, - |stg| super::base::type_layout(self, &stg, vm), + |stg| super::base::type_layout(&stg), ); // Keep the converted instance alive through the call: the // snapshot may embed pointers into buffers its keep-alive set // owns, which must outlive the foreign call. return Ok((CArgValue::aggregate(layout, bytes), Some(converted.clone()))); } - return Ok((convert_to_pointer(&converted, vm)?, None)); + return convert_to_pointer(&converted, vm); } // For pointer types (c_void_p, c_char_p, c_wchar_p), handle as pointer if matches!(type_code.as_deref(), Some("P" | "z" | "Z")) { - return Ok((convert_to_pointer(&converted, vm)?, None)); + return convert_to_pointer(&converted, vm); } // PyCSimple (already a ctypes instance from from_param) @@ -293,7 +339,7 @@ impl ArgumentType for PyTypeRef { .as_deref() .and_then(|s| s.chars().next()) .ok_or_else(|| vm.new_type_error("Unsupported argument type"))?; - return Ok((simple.to_carg_value(code), None)); + return Ok((simple.to_carg_value(code), Some(simple.into()))); } Err(vm.new_type_error("Unsupported argument type")) @@ -325,21 +371,48 @@ impl Initializer for PyCFuncPtrType { stg_info.length = 1; stg_info.flags |= StgInfoFlags::TYPEFLAG_ISPOINTER; stg_info.paramfunc = ParamFunc::Pointer; // CFuncPtr is passed as a pointer + // Function-type metadata comes from this class's namespace, not its MRO. + stg_info.argtypes = new_type.attributes.get(vm.ctx.intern_str("_argtypes_")); + stg_info.restype = new_type.attributes.get(vm.ctx.intern_str("_restype_")); + stg_info.checker = restype_checker(stg_info.restype.as_deref(), vm)?; - let _ = new_type.init_type_data(stg_info); + let _ = new_type.init_traced_type_data(stg_info); Ok(()) } } -#[pyclass(flags(IMMUTABLETYPE), with(Initializer))] +#[pyclass(flags(IMMUTABLETYPE), with(AsSequence, Initializer))] impl PyCFuncPtrType { - #[pygetset(name = "__pointer_type__")] - fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn from_param(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + if value.is_instance(zelf.as_object(), vm)? { + return Ok(value); + } + + if let Some(as_parameter) = vm.get_attribute_opt(&value, "_as_parameter_")? { + return vm.with_recursion(" while processing _as_parameter_", || { + Self::from_param(zelf, as_parameter, vm) + }); + } + + Err(vm.new_type_error(format!( + "expected {} instance instead of {}", + zelf.name(), + value.class().name() + ))) + } + + #[pygetset] + fn __pointer_type__(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { super::base::pointer_type_get(&zelf, vm) } - #[pygetset(name = "__pointer_type__", setter)] - fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___pointer_type__( + zelf: PyTypeRef, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { super::base::pointer_type_set(&zelf, value, vm) } } @@ -349,7 +422,8 @@ impl PyCFuncPtrType { module = "_ctypes", name = "CFuncPtr", base = PyCData, - metaclass = "PyCFuncPtrType" + metaclass = "PyCFuncPtrType", + traverse = "manual" )] #[repr(C)] pub(super) struct PyCFuncPtr { @@ -364,6 +438,8 @@ pub(super) struct PyCFuncPtr { pub argtypes: PyRwLock>, /// Instance-level restype override pub restype: PyRwLock>, + /// Serialize restype updates while allowing Python finalizers to re-enter. + restype_operation: PyOperation, /// Checker function pub checker: PyRwLock>, /// Error checking function @@ -380,6 +456,56 @@ pub(super) struct PyCFuncPtr { pub paramflags: PyRwLock>, } +// SAFETY: each stored reference is an independent strong edge, including +// thunk when it is also retained by _base.objects. +unsafe impl Traverse for PyCFuncPtr { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self._base.traverse(tracer); + self.thunk.traverse(tracer); + self.callable.traverse(tracer); + self.converters.traverse(tracer); + self.argtypes.traverse(tracer); + self.restype.traverse(tracer); + self.checker.traverse(tracer); + self.errcheck.traverse(tracer); + self.paramflags.traverse(tracer); + #[cfg(windows)] + self.iid.traverse(tracer); + } + + fn clear(&mut self, out: &mut Vec) { + self._base.clear(out); + if let Some(mut value) = self.thunk.try_write() { + out.extend(value.take().map(Into::into)); + } + if let Some(mut value) = self.callable.try_write() { + out.extend(value.take()); + } + if let Some(mut value) = self.converters.try_write() { + out.extend(value.take()); + } + if let Some(mut value) = self.argtypes.try_write() { + out.extend(value.take()); + } + if let Some(mut value) = self.restype.try_write() { + out.extend(value.take()); + } + if let Some(mut value) = self.checker.try_write() { + out.extend(value.take()); + } + if let Some(mut value) = self.errcheck.try_write() { + out.extend(value.take()); + } + if let Some(mut value) = self.paramflags.try_write() { + out.extend(value.take()); + } + #[cfg(windows)] + if let Some(mut value) = self.iid.try_write() { + out.extend(value.take()); + } + } +} + impl Debug for PyCFuncPtr { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCFuncPtr") @@ -388,17 +514,26 @@ impl Debug for PyCFuncPtr { } } +// c_void_p accepts only P-tagged argument wrappers. +fn carg_pointer(arg: &PyObject) -> Option { + let carg = arg.downcast_ref::()?; + if carg.tag != b'P' { + return None; + } + match &carg.value { + CArgValue::Pointer(address) => Some(*address), + CArgValue::Typed { code: 'P', bytes } => { + Some(rustpython_host_env::ctypes::read_pointer_from_buffer(bytes)) + } + _ => None, + } +} + /// Extract pointer value from a ctypes argument (c_void_p conversion) fn extract_ptr_from_arg(arg: &PyObject, vm: &VirtualMachine) -> PyResult { - // Try CArgObject first - extract the wrapped pointer value, applying offset - if let Some(carg) = arg.downcast_ref::() { - if carg.offset != 0 - && let Some(cdata) = carg.obj.downcast_ref::() - { - let base = cdata.buffer.read().as_ptr() as usize; - return Ok(offset_address(base, carg.offset)); - } - return extract_ptr_from_arg(&carg.obj, vm); + // byref() has already stored the address, including its byte offset. + if let Some(address) = carg_pointer(arg) { + return Ok(address); } // Try to get pointer value from various ctypes types if let Some(ptr) = arg.downcast_ref::() { @@ -509,18 +644,17 @@ fn cast_check_pointertype(ctype: &PyObject, vm: &VirtualMachine) -> bool { return true; } - // PyCFuncPtrTypeObject_Check - TODO + // PyCFuncPtrTypeObject_Check + if ctype.class().fast_issubclass(PyCFuncPtrType::static_type()) { + return true; + } - // simple pointer types via StgInfo.proto (c_void_p, c_char_p, etc.) - if let Ok(type_attr) = ctype.get_attr("_type_", vm) - && let Some(s) = type_attr.downcast_ref::() + // Simple pointer types retain the representation selected at creation, + // even if the user later changes the Python-visible _type_ attribute. + if let Some(ty) = ctype.downcast_ref::() + && let Some(code) = ty.type_code(vm) { - let c = s - .to_str() - .expect("_type_ is validated as ASCII at type creation"); - if c.len() == 1 && "sPzUZXO".contains(c) { - return true; - } + return code.len() == 1 && "sPzUZXO".contains(code.as_str()); } false @@ -546,6 +680,8 @@ pub(super) fn cast_impl( let ptr_value: usize = if vm.is_none(obj) { // None → NULL pointer 0 + } else if let Some(address) = carg_pointer(obj) { + address } else if let Ok(int_val) = obj.try_int(vm) { // int/long → direct pointer value int_val.as_bigint().to_usize().unwrap_or(0) @@ -562,6 +698,9 @@ pub(super) fn cast_impl( // Simple type (c_void_p, c_char_p, etc.) → value from buffer let buffer = simple.0.buffer.read(); rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer) + } else if let Some(funcptr) = obj.downcast_ref::() { + // A function pointer stores the executable address in its buffer. + funcptr.get_func_ptr() } else if let Some(cdata) = obj.downcast_ref::() { // Array, Structure, Union → buffer address (b_ptr) cdata.buffer.read().as_ptr() as usize @@ -616,6 +755,13 @@ pub(super) fn cast_impl( } } + if obj.downcast_ref::().is_some() + && let Some(cdata) = result.downcast_ref::() + { + // Preserve provenance privately: byref casts have no public _objects. + cdata.keep_cast_owner(obj.to_owned()); + } + // 5. Store pointer value if let Some(ptr) = result.downcast_ref::() { ptr.set_ptr_value(ptr_value); @@ -628,8 +774,27 @@ pub(super) fn cast_impl( } impl PyCFuncPtr { + pub(super) fn from_cdata(data: PyCData, vm: &VirtualMachine) -> Self { + Self { + _base: data, + thunk: PyRwLock::new(None), + callable: PyRwLock::new(None), + converters: PyRwLock::new(None), + argtypes: PyRwLock::new(None), + restype: PyRwLock::new(None), + restype_operation: PyOperation::new(vm), + checker: PyRwLock::new(None), + errcheck: PyRwLock::new(None), + #[cfg(windows)] + index: PyRwLock::new(None), + #[cfg(windows)] + iid: PyRwLock::new(None), + paramflags: PyRwLock::new(None), + } + } + /// Get function pointer address from buffer - fn get_func_ptr(&self) -> usize { + pub(super) fn get_func_ptr(&self) -> usize { let buffer = self._base.buffer.read(); rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer) } @@ -653,23 +818,9 @@ impl Constructor for PyCFuncPtr { let ptr_size = pointer_size(); if args.args.is_empty() { - return Self { - _base: PyCData::from_bytes(vec![0u8; ptr_size], None), - thunk: PyRwLock::new(None), - callable: PyRwLock::new(None), - converters: PyRwLock::new(None), - argtypes: PyRwLock::new(None), - restype: PyRwLock::new(None), - checker: PyRwLock::new(None), - errcheck: PyRwLock::new(None), - #[cfg(windows)] - index: PyRwLock::new(None), - #[cfg(windows)] - iid: PyRwLock::new(None), - paramflags: PyRwLock::new(None), - } - .into_ref_with_type(vm, cls) - .map(Into::into); + return Self::from_cdata(PyCData::from_bytes(vec![0u8; ptr_size], None), vm) + .into_ref_with_type(vm, cls) + .map(Into::into); } let first_arg = &args.args[0]; @@ -683,19 +834,30 @@ impl Constructor for PyCFuncPtr { #[cfg(windows)] let index = first_arg.try_int(vm)?.as_bigint().to_usize().unwrap_or(0); - // args[3] is iid (GUID struct, optional) - // Also check if args[2] is a GUID (has Data1 attribute) when args[3] is not present + // Retain the accepted IID owner rather than a borrowed raw pointer. + // Mutable CData GUIDs remain observable; copy bytes only at call time. #[cfg(windows)] - let iid = args.args.get(3).cloned().or_else(|| { - args.args.get(2).and_then(|arg| { - // If it's a GUID struct (has Data1 attribute), use it as IID - if arg.get_attr("Data1", vm).is_ok() { - Some(arg.clone()) - } else { - None - } - }) - }); + let iid = if let Some(iid) = args.args.get(3).filter(|arg| !vm.is_none(arg)) { + let owner: PyObjectRef = if let Some(text) = iid.downcast_ref::() { + vm.state + .codec_registry + .encode_text(text.to_owned(), "utf-8", None, vm)? + .into() + } else if iid.downcast_ref::().is_some() + || iid.downcast_ref::().is_some() + { + iid.clone() + } else { + return Err(vm.new_type_error( + "iid must be a read-only bytes-like object, str, or None", + )); + }; + let buffer = ArgBytesLike::try_from_object(vm, owner.clone())?; + let valid_size = buffer.borrow_buf().len() == 16; + valid_size.then_some(owner) + } else { + None + }; // args[2] is paramflags (tuple or None) let paramflags = args.args.get(2).filter(|arg| !vm.is_none(arg)).cloned(); @@ -707,6 +869,7 @@ impl Constructor for PyCFuncPtr { converters: PyRwLock::new(None), argtypes: PyRwLock::new(None), restype: PyRwLock::new(None), + restype_operation: PyOperation::new(vm), checker: PyRwLock::new(None), errcheck: PyRwLock::new(None), #[cfg(windows)] @@ -729,6 +892,7 @@ impl Constructor for PyCFuncPtr { converters: PyRwLock::new(None), argtypes: PyRwLock::new(None), restype: PyRwLock::new(None), + restype_operation: PyOperation::new(vm), checker: PyRwLock::new(None), errcheck: PyRwLock::new(None), #[cfg(windows)] @@ -795,6 +959,7 @@ impl Constructor for PyCFuncPtr { converters: PyRwLock::new(None), argtypes: PyRwLock::new(None), restype: PyRwLock::new(None), + restype_operation: PyOperation::new(vm), checker: PyRwLock::new(None), errcheck: PyRwLock::new(None), #[cfg(windows)] @@ -810,8 +975,25 @@ impl Constructor for PyCFuncPtr { // Check if first argument is a Python callable (callback creation) if first_arg.is_callable() { // Get argument types and result type from the class - let class_argtypes = cls.get_attr(vm.ctx.intern_str("_argtypes_")); - let class_restype = cls.get_attr(vm.ctx.intern_str("_restype_")); + let (class_argtypes, class_restype, class_checker) = + cls.stg_info_opt().map_or_default(|info| { + ( + info.argtypes.clone(), + info.restype.clone(), + info.checker.clone(), + ) + }); + if class_argtypes.is_none() { + return Err( + vm.new_type_error("cannot construct instance of this class: no argtypes") + ); + } + // Missing metadata is not an explicit void return. CPython 3.15 + // dereferences NULL here; reject it rather than build a void thunk + // whose caller would interpret an uninitialized C int result. + if class_restype.is_none() { + return Err(vm.new_type_error("invalid result type for callback function")); + } let class_flags = cls .get_attr(vm.ctx.intern_str("_flags_")) .and_then(|f| f.try_to_value::(vm).ok()) @@ -830,15 +1012,20 @@ impl Constructor for PyCFuncPtr { // Store the thunk as a Python object to keep it alive let thunk_ref: PyRef = thunk.into_ref(&vm.ctx); + let base = PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None); + let objects = vm.ctx.new_dict(); + objects.set_item("0", thunk_ref.clone().into(), vm)?; + *base.objects.write() = Some(objects.into()); return Self { - _base: PyCData::from_bytes(Self::make_ptr_buffer(ptr_val), None), + _base: base, thunk: PyRwLock::new(Some(thunk_ref)), callable: PyRwLock::new(Some(first_arg.clone())), converters: PyRwLock::new(None), argtypes: PyRwLock::new(class_argtypes), restype: PyRwLock::new(class_restype), - checker: PyRwLock::new(None), + restype_operation: PyOperation::new(vm), + checker: PyRwLock::new(class_checker), errcheck: PyRwLock::new(None), #[cfg(windows)] index: PyRwLock::new(None), @@ -931,6 +1118,9 @@ enum RetSpec { struct CallInfo { explicit_arg_types: Option>, restype_obj: Option, + checker: Option, + #[cfg(windows)] + check_hresult: bool, ret: RetSpec, } @@ -974,15 +1164,12 @@ fn compute_ret_spec( return RetSpec::Pointer; } - // Simple type via its _type_ code (traversing MRO) - if let Ok(type_attr) = restype_type - .as_object() - .get_attr(vm.ctx.intern_str("_type_"), vm) - && let Some(s) = type_attr.downcast_ref::() - && let Some(code) = s.to_str() - && ffi_type_from_code(code).is_some() + // Simple type via its initialized scalar converter. + if let Some(code) = restype_type + .type_code(vm) + .filter(|code| ffi_type_from_code(code).is_some()) { - return if simple_type_is_pointer(code) { + return if simple_type_is_pointer(&code) { RetSpec::Pointer } else { RetSpec::Code(code.chars().next().unwrap_or('i')) @@ -994,7 +1181,7 @@ fn compute_ret_spec( if let Some(stg_info) = restype_type.stg_info_opt() { return match stg_info.paramfunc { ParamFunc::Structure | ParamFunc::Union => { - RetSpec::Aggregate(super::base::type_layout(&restype_type, &stg_info, vm)) + RetSpec::Aggregate(super::base::type_layout(&stg_info)) } // Any other aggregate-ish StgInfo without a code: size-approximated // register return, as before. @@ -1014,33 +1201,52 @@ fn compute_ret_spec( RetSpec::Code('i') } +fn restype_checker( + restype: Option<&PyObject>, + vm: &VirtualMachine, +) -> PyResult> { + match restype { + Some(restype) => vm.get_attribute_opt(restype, "_check_retval_"), + _ => Ok(None), + } +} + /// Extract call information (argtypes, restype) from PyCFuncPtr fn extract_call_info(zelf: &Py, vm: &VirtualMachine) -> PyResult { - // Get argtypes - first from instance, then from type's _argtypes_ - let explicit_arg_types: Option> = - if let Some(argtypes_obj) = zelf.argtypes.read().as_ref() { - if !vm.is_none(argtypes_obj) { - Some(extract_arg_types(argtypes_obj, vm)?) - } else { - None // argtypes is None -> use ConvParam - } - } else if let Some(class_argtypes) = zelf - .as_object() - .class() - .get_attr(vm.ctx.intern_str("_argtypes_")) - && !vm.is_none(&class_argtypes) - { - Some(extract_arg_types(&class_argtypes, vm)?) + // Clone before calling Python sequence methods, which can change argtypes. + let argtypes = zelf.argtypes.read().clone(); + // Get argtypes from the instance, then cached class metadata. + let explicit_arg_types: Option> = if let Some(argtypes_obj) = argtypes.as_ref() { + if !vm.is_none(argtypes_obj) { + Some(extract_arg_types(argtypes_obj, vm)?) } else { - None // No argtypes -> use ConvParam - }; + None // argtypes is None -> use ConvParam + } + } else if let Some(class_argtypes) = zelf + .class() + .stg_info_opt() + .and_then(|info| info.argtypes.clone()) + && !vm.is_none(&class_argtypes) + { + Some(extract_arg_types(&class_argtypes, vm)?) + } else { + None // No argtypes -> use ConvParam + }; - // Get restype - first from instance, then from class's _restype_ - let restype_obj = zelf.restype.read().clone().or_else(|| { - zelf.as_object() - .class() - .get_attr(vm.ctx.intern_str("_restype_")) - }); + // Retain both references before argument conversion can re-enter. + let (restype_obj, checker) = { + let restype = zelf.restype.read(); + let checker = zelf.checker.read(); + let class_info = zelf.class().stg_info_opt(); + ( + restype + .clone() + .or_else(|| class_info.as_ref().and_then(|info| info.restype.clone())), + checker + .clone() + .or_else(|| class_info.as_ref().and_then(|info| info.checker.clone())), + ) + }; // Check if restype is explicitly None (return void) let restype_is_none = restype_obj.as_deref().is_some_and(|t| vm.is_none(t)); @@ -1049,6 +1255,10 @@ fn extract_call_info(zelf: &Py, vm: &VirtualMachine) -> PyResult::_flags_(zelf, vm) & StgInfoFlags::FUNCFLAG_HRESULT.bits() + != 0, ret, }) } @@ -1103,10 +1313,10 @@ fn resolve_com_method( zelf: &Py, args: &FuncArgs, vm: &VirtualMachine, -) -> PyResult<(Option, bool)> { +) -> PyResult<(Option, Option)> { let com_index = zelf.index.read(); let Some(idx) = *com_index else { - return Ok((None, false)); + return Ok((None, None)); }; // First arg must be the COM object pointer @@ -1142,7 +1352,7 @@ fn resolve_com_method( } }; - Ok((Some(code_ptr), true)) + Ok((Some(code_ptr), Some(com_ptr))) } /// Single argument for FFI call @@ -1153,8 +1363,13 @@ struct Argument { keep: Option, // Object to keep alive during call } -/// Out buffers for paramflags OUT parameters -type OutBuffers = Vec<(usize, PyObjectRef)>; +/// Values returned for paramflags OUT and IN/OUT parameters. +enum OutValue { + Out(PyObjectRef), + InOut(PyObjectRef), +} + +type OutBuffers = Vec; /// Get buffer address from a ctypes object fn get_buffer_addr(obj: &PyObject) -> Option { @@ -1173,11 +1388,12 @@ fn get_buffer_addr(obj: &PyObject) -> Option { /// Create OUT buffer for a parameter type fn create_out_buffer(arg_type: &Py, vm: &VirtualMachine) -> PyResult { // For POINTER(T) types, create T instance (the pointed-to type) - if arg_type.fast_issubclass(PyCPointer::static_type()) - && let Some(stg_info) = arg_type.stg_info_opt() - && let Some(ref proto) = stg_info.proto - { - return proto.as_object().call((), vm); + if arg_type.fast_issubclass(PyCPointer::static_type()) { + // Constructing the pointed-to type can re-enter pointer type setup. + let proto = arg_type.stg_info_opt().and_then(|info| info.proto.clone()); + if let Some(proto) = proto { + return proto.as_object().call((), vm); + } } // Not a pointer type or no proto, create instance directly arg_type.as_object().call((), vm) @@ -1191,7 +1407,8 @@ fn build_callargs_no_argtypes( let arguments: Vec = args .args .iter() - .map(|arg| conv_param(arg, vm)) + .enumerate() + .map(|(index, arg)| conv_param_for_call(arg, index, vm)) .collect::>>()?; Ok((arguments, Vec::new())) } @@ -1200,18 +1417,30 @@ fn build_callargs_no_argtypes( fn build_callargs_simple( args: &FuncArgs, arg_types: &[PyTypeRef], + allow_variadic: bool, vm: &VirtualMachine, ) -> PyResult<(Vec, OutBuffers)> { + if args.args.len() < arg_types.len() || (!allow_variadic && args.args.len() != arg_types.len()) + { + return Err(vm.new_type_error(format!( + "this function takes {}{} argument{} ({} given)", + if allow_variadic { "at least " } else { "" }, + arg_types.len(), + if arg_types.len() == 1 { "" } else { "s" }, + args.args.len(), + ))); + } let arguments: Vec = args .args .iter() .enumerate() .map(|(n, arg)| { - let arg_type = arg_types - .get(n) - .ok_or_else(|| vm.new_type_error("argument amount mismatch"))?; - let (value, keep) = arg_type.convert_object(arg.clone(), vm)?; - Ok(Argument { value, keep }) + if let Some(arg_type) = arg_types.get(n) { + let (value, keep) = arg_type.convert_object(arg.clone(), vm)?; + Ok(Argument { value, keep }) + } else { + conv_param_for_call(arg, n, vm) + } }) .collect::>>()?; Ok((arguments, Vec::new())) @@ -1257,7 +1486,7 @@ fn build_callargs_with_paramflags( keep: None, value: CArgValue::pointer(addr), }); - out_buffers.push((param_idx, buffer)); + out_buffers.push(OutValue::Out(buffer)); } else { // IN or IN|OUT: get from caller args or default let arg = if caller_arg_idx < args.args.len() { @@ -1271,13 +1500,21 @@ fn build_callargs_with_paramflags( if is_out { // IN|OUT: track for return - out_buffers.push((param_idx, arg.clone())); + out_buffers.push(OutValue::InOut(arg.clone())); } let (value, keep) = arg_type.convert_object(arg, vm)?; arguments.push(Argument { value, keep }); } } + if !arg_types.is_empty() && args.kwargs.is_empty() && caller_arg_idx < args.args.len() { + return Err(vm.new_type_error(format!( + "call takes exactly {} arguments ({} given)", + caller_arg_idx, + args.args.len(), + ))); + } + Ok((arguments, out_buffers)) } @@ -1287,6 +1524,7 @@ fn build_callargs( call_info: &CallInfo, paramflags: Option<&ParsedParamFlags>, is_com_method: bool, + allow_variadic: bool, vm: &VirtualMachine, ) -> PyResult<(Vec, OutBuffers)> { let Some(ref arg_types) = call_info.explicit_arg_types else { @@ -1313,7 +1551,7 @@ fn build_callargs( Ok((arguments, Vec::new())) } else { // Regular function - build_callargs_simple(args, arg_types, vm) + build_callargs_simple(args, arg_types, allow_variadic, vm) } } @@ -1346,36 +1584,67 @@ fn ctypes_callproc( /// Check and handle HRESULT errors (Windows) #[cfg(windows)] -fn check_hresult(hresult: i32, zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { +fn check_hresult( + hresult: i32, + zelf: &Py, + com_ptr: Option, + vm: &VirtualMachine, +) -> PyResult<()> { if hresult >= 0 { return Ok(()); } - if zelf.iid.read().is_some() { - // Raise COMError + let iid = zelf.iid.read().clone(); + if let (Some(com_ptr), Some(iid)) = (com_ptr, iid) { + let iid: [u8; 16] = { + let buffer = ArgBytesLike::try_from_object(vm, iid)?; + let bytes = buffer.borrow_buf(); + bytes + .get(..16) + .ok_or_else(|| vm.new_value_error("IID buffer is too small"))? + .try_into() + .expect("checked IID size") + }; + // The call arguments keep the COM pointer owner alive. No Python data + // guard survives detaching; the native helper owns/releases its COM refs. + let details = vm.allow_threads(|| unsafe { + rustpython_host_env::ctypes::com_error_details(com_ptr, &iid) + }); + let wide = |value: Option>| -> PyObjectRef { + value.map_or_else( + || vm.ctx.none(), + |units| { + vm.ctx + .new_str(rustpython_common::wtf8::Wtf8Buf::from_wide(&units)) + .into() + }, + ) + }; + let details: PyObjectRef = vm + .ctx + .new_tuple(vec![ + wide(details.description), + wide(details.source), + wide(details.helpfile), + vm.ctx.new_int(details.help_context).into(), + wide(details.progid), + ]) + .into(); + let text = rustpython_host_env::ctypes::format_com_error_message(hresult) + .map_or_else(|| vm.ctx.none(), |text| vm.ctx.new_str(text).into()); let ctypes_module = vm.import("_ctypes", 0)?; let com_error_type = ctypes_module.get_attr("COMError", vm)?; let com_error_type = com_error_type .downcast::() .map_err(|_| vm.new_type_error("COMError is not a type"))?; - let hresult_obj: PyObjectRef = vm.ctx.new_int(hresult).into(); - let text: PyObjectRef = vm - .ctx - .new_str(format!("HRESULT: 0x{:08X}", hresult as u32)) - .into(); - let details: PyObjectRef = vm.ctx.none(); - let exc = vm.invoke_exception(&com_error_type, vec![text.to_owned(), details.clone()])?; - let _ = exc.as_object().set_attr("hresult", hresult_obj, vm); - let _ = exc.as_object().set_attr("text", text, vm); - let _ = exc.as_object().set_attr("details", details, vm); - Err(exc) + Err(vm.invoke_exception( + &com_error_type, + vec![vm.ctx.new_int(hresult).into(), text, details], + )?) } else { - // Raise OSError - let exc = vm.new_os_error(format!("HRESULT: 0x{:08X}", hresult as u32)); - let _ = exc - .as_object() - .set_attr("winerror", vm.ctx.new_int(hresult), vm); - Err(exc) + // Use the same native Windows error conversion as _check_HRESULT: + // errno mapping, signed winerror, and the system's formatted message. + super::_ctypes::check_hresult(hresult, vm).map(|_| ()) } } @@ -1385,11 +1654,11 @@ fn convert_raw_result( result: &CallValue, call_info: &CallInfo, vm: &VirtualMachine, -) -> Option { +) -> PyResult> { // Result register image as bytes + size (None for void): pointer/scalar // returns are pointer/register sized. let (result_bytes, result_size) = match result { - CallValue::Void => return None, + CallValue::Void => return Ok(None), CallValue::Pointer(ptr) => (ptr.to_ne_bytes().to_vec(), size_of::()), CallValue::Scalar(bytes) | CallValue::Aggregate(bytes) => (bytes.clone(), bytes.len()), }; @@ -1410,14 +1679,14 @@ fn convert_raw_result( let restype = match &call_info.restype_obj { None => { // Default: return as int - return Some(vm.ctx.new_int(result_word as isize).into()); + return Ok(Some(vm.ctx.new_int(result_word as isize).into())); } Some(r) => r, }; // 2. restype is None → return None if restype.is(&vm.ctx.none()) { - return None; + return Ok(None); } // 3. Get restype as PyType @@ -1425,7 +1694,7 @@ fn convert_raw_result( Ok(t) => t, Err(_) => { // Not a type, call it with int result - return restype.call((result_word as isize,), vm).ok(); + return restype.call((result_word as isize,), vm).map(Some); } }; @@ -1437,7 +1706,7 @@ fn convert_raw_result( return restype_type .as_object() .call((result_word as isize,), vm) - .ok(); + .map(Some); } let info = stg_info.unwrap(); @@ -1446,33 +1715,44 @@ fn convert_raw_result( // finalize it), which would self-deadlock against a held read guard. let is_pointer_type = info.flags.contains(StgInfoFlags::TYPEFLAG_ISPOINTER); let has_proto = info.proto.is_some(); + let scalar_code = info.scalar_code; + let storage_size = info.size; drop(info); // py_object: interpret return value as PyObject* and materialize it. - if let Ok(type_attr) = restype_type - .as_object() - .get_attr(vm.ctx.intern_str("_type_"), vm) - && let Some(type_str) = type_attr.downcast_ref::() - && type_str.to_str() == Some("O") - { - let ptr = NonNull::new(result_word as *mut PyObject).or_else(|| { - vm.set_exception(Some(vm.new_value_error("PyObject is NULL"))); - None - })?; + if scalar_code == Some('O') && super::simple::returns_scalar(&restype_type) { + let ptr = NonNull::new(result_word as *mut PyObject) + .ok_or_else(|| vm.new_value_error("PyObject is NULL"))?; unsafe { let obj = PyObjectRef::from_raw(ptr); - return Some(obj); + return Ok(Some(obj)); } } // 5. Simple type with getfunc → use bytes_to_pyobject (info->getfunc) - // is_simple_instance returns TRUE for c_int, c_void_p, etc. - if super::base::is_simple_instance(&restype_type) { - return Some(super::base::bytes_to_pyobject( + // Only direct simple types return Python scalars; subclasses return instances. + if super::simple::returns_scalar(&restype_type) { + return Ok(Some(super::base::bytes_to_pyobject( &restype_type, &result_bytes, vm, - )); + ))); + } + + if restype_type.fast_issubclass(PyCSimple::static_type()) { + // Native return values bypass Python __new__ and __init__. A py_object + // return transfers an owned reference, retained by the wrapper. + let objects = if scalar_code == Some('O') { + NonNull::new(result_word as *mut PyObject) + .map(|ptr| unsafe { PyObjectRef::from_raw(ptr) }) + } else { + None + }; + let mut bytes = vec![0; storage_size]; + write_prefix_limited(&mut bytes, &result_bytes, result_size); + return PyCSimple(PyCData::from_bytes(bytes, objects)) + .into_ref_with_type(vm, restype_type) + .map(|value| Some(value.into())); } // 6. Complex type → create ctypes instance (PyCData_FromBaseObj) @@ -1482,16 +1762,16 @@ fn convert_raw_result( if is_pointer_type && has_proto && let CallValue::Pointer(ptr) = result - && let Ok(instance) = restype_type.as_object().call((), vm) { + let instance = restype_type.as_object().call((), vm)?; if let Some(pointer) = instance.downcast_ref::() { pointer.set_ptr_value(*ptr); } - return Some(instance); + return Ok(Some(instance)); } // Create instance and copy result data - pycdata_from_ffi_result(&restype_type, &result_bytes, result_size, vm).ok() + pycdata_from_ffi_result(&restype_type, &result_bytes, result_size, vm).map(Some) } /// Create a ctypes instance from FFI result (PyCData_FromBaseObj equivalent) @@ -1513,15 +1793,12 @@ fn pycdata_from_ffi_result( Ok(instance) } -/// Extract values from OUT buffers -fn extract_out_values( - out_buffers: Vec<(usize, PyObjectRef)>, - vm: &VirtualMachine, -) -> Vec { - out_buffers - .into_iter() - .map(|(_, buffer)| buffer.get_attr("value", vm).unwrap_or(buffer)) - .collect() +/// Extract one OUT parameter without consuming its owner. +fn extract_out_value(value: &OutValue, vm: &VirtualMachine) -> PyResult { + match value { + OutValue::Out(buffer) => vm.call_method(buffer, "__ctypes_from_outparam__", ()), + OutValue::InOut(buffer) => Ok(buffer.clone()), + } } /// Build final result (main function) @@ -1531,36 +1808,53 @@ fn build_result( out_buffers: OutBuffers, zelf: &Py, args: &FuncArgs, + #[cfg(windows)] com_ptr: Option, vm: &VirtualMachine, ) -> PyResult { - // Check HRESULT on Windows - #[cfg(windows)] - if let CallValue::Scalar(bytes) = &call_result { - let is_hresult = call_info - .restype_obj - .as_ref() - .and_then(|t| t.to_owned().downcast::().ok()) - .is_some_and(|t| t.name().to_string() == "HRESULT"); - if is_hresult { - let mut word = [0u8; size_of::()]; - let n = bytes.len().min(word.len()); - word[..n].copy_from_slice(&bytes[..n]); - check_hresult(usize::from_ne_bytes(word) as i32, zelf, vm)?; + let convert_result = || -> PyResult> { + let mut result = convert_raw_result(&call_result, call_info, vm)?; + if let Some(checker) = &call_info.checker + && call_info + .restype_obj + .as_ref() + .and_then(|restype| restype.downcast_ref::()) + .is_some_and(|restype| restype.stg_info_opt().is_some()) + && let Some(value) = result.as_ref() + { + result = Some(checker.call((value.clone(),), vm)?); } - } + Ok(result) + }; - // Convert the foreign-call result to a Python object - let mut result = convert_raw_result(&call_result, call_info, vm); + // COM functions request HRESULT checking through their calling convention. + // Ordinary HRESULT restypes use _check_retval_, like other checked types. + #[cfg(windows)] + let result = if (call_info.check_hresult || (com_ptr.is_some() && zelf.iid.read().is_some())) + && let CallValue::Scalar(bytes) = &call_result + { + let mut word = [0u8; size_of::()]; + let n = bytes.len().min(word.len()); + word[..n].copy_from_slice(&bytes[..n]); + let hresult = usize::from_ne_bytes(word) as i32; + check_hresult(hresult, zelf, com_ptr, vm)?; + Some(vm.ctx.new_int(hresult).into()) + } else { + convert_result()? + }; + #[cfg(not(windows))] + let result = convert_result()?; // Apply errcheck if set - if let Some(errcheck) = zelf.errcheck.read().as_ref() { + // Clone before calling Python so the callback can change errcheck. + let errcheck = zelf.errcheck.read().clone(); + if let Some(errcheck) = errcheck.as_ref() { let args_tuple = PyTuple::new_ref(args.args.clone(), &vm.ctx); let func_obj = zelf.as_object().to_owned(); let result_obj = result.clone().unwrap_or_else(|| vm.ctx.none()); let checked = errcheck.call((result_obj, func_obj, args_tuple.clone()), vm)?; // Returning the original args tuple requests normal result processing. if !checked.is(&args_tuple) { - result = Some(checked); + return Ok(checked); } } @@ -1569,11 +1863,17 @@ fn build_result( return result.map_or_else(|| Ok(vm.ctx.none()), Ok); } - let out_values = extract_out_values(out_buffers, vm); - Ok(match <[PyObjectRef; 1]>::try_from(out_values) { - Ok([single]) => single, - Err(v) => PyTuple::new_ref(v, &vm.ctx).into(), - }) + // OUT parameters replace the raw result. Release it before conversion, + // which can invoke user-defined methods. + drop(result); + if let [single] = out_buffers.as_slice() { + return extract_out_value(single, vm); + } + let out_values = out_buffers + .iter() + .map(|value| extract_out_value(value, vm)) + .collect::>>()?; + Ok(PyTuple::new_ref(out_values, &vm.ctx).into()) } impl Callable for PyCFuncPtr { @@ -1586,7 +1886,9 @@ impl Callable for PyCFuncPtr { // 2. Resolve function pointer (COM or direct) #[cfg(windows)] - let (func_ptr, is_com_method) = resolve_com_method(zelf, &args, vm)?; + let (func_ptr, com_ptr) = resolve_com_method(zelf, &args, vm)?; + #[cfg(windows)] + let is_com_method = com_ptr.is_some(); #[cfg(not(windows))] let (func_ptr, is_com_method) = (None::, false); @@ -1597,8 +1899,16 @@ impl Callable for PyCFuncPtr { let paramflags = parse_paramflags(zelf, vm)?; // 5. Build call arguments - let (arguments, out_buffers) = - build_callargs(&args, &call_info, paramflags.as_ref(), is_com_method, vm)?; + let flags = Py::::_flags_(zelf, vm); + let allow_variadic = flags & StgInfoFlags::FUNCFLAG_CDECL.bits() != 0; + let (arguments, out_buffers) = build_callargs( + &args, + &call_info, + paramflags.as_ref(), + is_com_method, + allow_variadic, + vm, + )?; // 6. Function address (usize); the unified `call` rejects a NULL address. let addr = match func_ptr { @@ -1607,27 +1917,59 @@ impl Callable for PyCFuncPtr { }; // 7. Errno / last-error swap options from flags - let flags = Py::::_flags_(zelf, vm); let options = CallOptions { + fixed_arg_count: call_info + .explicit_arg_types + .as_ref() + .map(Vec::len) + .filter(|&fixed| allow_variadic && fixed != 0 && arguments.len() > fixed), use_errno: flags & super::base::StgInfoFlags::FUNCFLAG_USE_ERRNO.bits() != 0, use_last_error: flags & super::base::StgInfoFlags::FUNCFLAG_USE_LASTERROR.bits() != 0, }; - // 8. Call the function through the unified entry point. - let call_result = ctypes_callproc(addr, &arguments, &call_info.ret, options).map_err( - |err| match err { - CallError::NullFunctionPointer => vm.new_value_error("NULL function pointer"), - CallError::UnknownTypeCode(code) => { - vm.new_type_error(format!("Unsupported argument type: {code}")) - } - CallError::BufferTooSmall { expected, got } => vm.new_value_error(format!( - "argument buffer too small: expected {expected}, got {got}" - )), - }, - )?; + // Native calls may block while another thread runs Python. Callbacks + // reattach before executing Python; PythonAPI calls stay attached. + let native_call = || ctypes_callproc(addr, &arguments, &call_info.ret, options); + let call_result = if flags & StgInfoFlags::FUNCFLAG_PYTHONAPI.bits() != 0 { + native_call() + } else { + vm.allow_threads(native_call) + } + .map_err(|err| match err { + CallError::NullFunctionPointer => vm.new_value_error("NULL function pointer"), + CallError::InvalidCallInterface { variadic } => vm.new_runtime_error(if variadic { + "ffi_prep_cif_var failed" + } else { + "ffi_prep_cif failed" + }), + CallError::UnknownTypeCode(code) => { + vm.new_type_error(format!("Unsupported argument type: {code}")) + } + CallError::BufferTooSmall { expected, got } => vm.new_value_error(format!( + "argument buffer too small: expected {expected}, got {got}" + )), + })?; + + // PythonAPI functions report errors through the native raised-error + // slot. Check it before a NULL PyObject* can be decoded, and consume + // the exception exactly once without touching handled exceptions. + if flags & StgInfoFlags::FUNCFLAG_PYTHONAPI.bits() != 0 + && let Some(exception) = vm.take_raised_exception() + { + return Err(exception); + } // 9. Build result - build_result(call_result, &call_info, out_buffers, zelf, &args, vm) + build_result( + call_result, + &call_info, + out_buffers, + zelf, + &args, + #[cfg(windows)] + com_ptr, + vm, + ) } } @@ -1657,14 +1999,7 @@ impl AsBuffer for PyCFuncPtr { } else { (Cow::Borrowed(pointer_format()), pointer_size()) }; - let desc = BufferDescriptor { - offset: 0, - len: itemsize, - readonly: false, - itemsize, - format, - dim_desc: vec![], - }; + let desc = BufferDescriptor::from_dim_desc(itemsize, 0, false, itemsize, format, vec![]); let buf = PyBuffer::new(zelf.to_owned().into(), desc, &CDATA_BUFFER_METHODS); Ok(buf) } @@ -1677,40 +2012,68 @@ impl AsBuffer for PyCFuncPtr { impl Py { // restype getter/setter #[pygetset] - fn restype(&self) -> Option { - self.restype.read().clone() + fn restype(zelf: &Self, vm: &VirtualMachine) -> PyResult> { + zelf.restype_operation.with(vm, || { + let restype = zelf.restype.read().clone(); + Ok(restype.or_else(|| { + zelf.class() + .stg_info_opt() + .and_then(|info| info.restype.clone()) + })) + }) } #[pygetset(setter)] - fn set_restype(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - // Must be type, callable, or None - if vm.is_none(&value) { - *self.restype.write() = None; - } else if value.downcast_ref::().is_some() || value.is_callable() { - *self.restype.write() = Some(value); - } else { - return Err(vm.new_type_error("restype must be a type, a callable, or None")); - } - Ok(()) + fn set_restype(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + self.restype_operation.with(vm, || { + let PySetterValue::Assign(value) = value else { + // Deletion uses the reverse replacement order from assignment. + // Drop each value with no data guard held, allowing finalizers + // to observe and re-enter the current state, as in CPython. + let old_restype = self.restype.write().take(); + drop(old_restype); + let _old_checker = self.checker.write().take(); + return Ok(()); + }; + // Must be type, callable, or None + if !vm.is_none(&value) + && value.downcast_ref::().is_none() + && !value.is_callable() + { + return Err(vm.new_type_error("restype must be a type, a callable, or None")); + } + let checker = restype_checker(Some(&value), vm)?; + // An explicit None requests a void result; it is distinct from unset. + // Match CPython's sequential replacement: the old checker's finalizer + // can still observe the old restype and can re-enter this setter. + let old_checker = core::mem::replace(&mut *self.checker.write(), checker); + drop(old_checker); + let _old_restype = self.restype.write().replace(value); + Ok(()) + }) } // argtypes getter/setter #[pygetset] - fn argtypes(&self, vm: &VirtualMachine) -> PyObjectRef { - self.argtypes - .read() - .clone() - .unwrap_or_else(|| vm.ctx.empty_tuple.clone().into()) + fn argtypes(zelf: &Self, _vm: &VirtualMachine) -> Option { + let argtypes = zelf.argtypes.read().clone(); + argtypes.or_else(|| { + zelf.class() + .stg_info_opt() + .and_then(|info| info.argtypes.clone()) + }) } - #[pygetset(name = "argtypes", setter)] + #[pygetset(setter)] fn set_argtypes(&self, value: PyObjectRef, vm: &VirtualMachine) { - if vm.is_none(&value) { - *self.argtypes.write() = None; + let value = if vm.is_none(&value) { + None } else { // Store the argtypes object directly as it is - *self.argtypes.write() = Some(value); - } + Some(value) + }; + let _old = core::mem::replace(&mut *self.argtypes.write(), value); + // Finalizers on the previous value can re-enter this setter. } // errcheck getter/setter @@ -1721,13 +2084,15 @@ impl Py { #[pygetset(setter)] fn set_errcheck(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - if vm.is_none(&value) { - *self.errcheck.write() = None; + let value = if vm.is_none(&value) { + None } else if value.is_callable() { - *self.errcheck.write() = Some(value); + Some(value) } else { return Err(vm.new_type_error("errcheck must be a callable or None")); - } + }; + let _old = core::mem::replace(&mut *self.errcheck.write(), value); + // Finalizers on the previous callable can re-enter this setter. Ok(()) } @@ -1790,8 +2155,41 @@ fn ffi_to_python( args: *const *const c_void, index: usize, vm: &VirtualMachine, -) -> PyObjectRef { +) -> PyResult { + if ty.fast_issubclass(PyCPointer::static_type()) { + // POINTER(T) uses a pointer argument in the CIF, even though its + // `_type_` is a type object rather than a simple type code. + let rustpython_host_env::ctypes::DecodedValue::Pointer(address) = + (unsafe { rustpython_host_env::ctypes::callback_arg_value_at(Some("P"), args, index) }) + else { + return Err(vm.new_type_error("invalid pointer callback argument")); + }; + let instance = ty.as_object().call((), vm)?; + let pointer = instance + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("pointer constructor returned a non-pointer"))?; + pointer.set_ptr_value(address); + return Ok(instance); + } + let type_code = ty.type_code(vm); + #[cfg(windows)] + if type_code.as_deref() == Some("X") && is_simple_subclass(ty, vm) { + // CPython constructs non-direct simple subclasses without arguments, + // then copies the slot. Decoding and reconstructing a BSTR would allocate + // a different COM string and lose the caller's pointer identity. + let rustpython_host_env::ctypes::DecodedValue::Pointer(address) = + (unsafe { rustpython_host_env::ctypes::callback_arg_value_at(Some("P"), args, index) }) + else { + return Err(vm.new_type_error("invalid BSTR callback argument")); + }; + let instance = ty.as_object().call((), vm)?; + let cdata = instance + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("BSTR constructor returned a non-ctypes object"))?; + cdata.write_bytes_at_offset(0, &address.to_ne_bytes()); + return Ok(instance); + } let raw_value: PyObjectRef = match unsafe { rustpython_host_env::ctypes::callback_arg_value_at(type_code.as_deref(), args, index) } { @@ -1802,15 +2200,20 @@ fn ffi_to_python( rustpython_host_env::ctypes::DecodedValue::Bool(value) => vm.ctx.new_bool(value).into(), rustpython_host_env::ctypes::DecodedValue::Pointer(value) => vm.ctx.new_int(value).into(), rustpython_host_env::ctypes::DecodedValue::String(value) => vm.ctx.new_str(value).into(), + #[cfg(windows)] + rustpython_host_env::ctypes::DecodedValue::WideString(value) => { + vm.ctx.new_str(value).into() + } rustpython_host_env::ctypes::DecodedValue::None => vm.ctx.none(), }; if !is_simple_subclass(ty, vm) { - return raw_value; + return Ok(raw_value); } - ty.as_object() + Ok(ty + .as_object() .call((raw_value.clone(),), vm) - .unwrap_or(raw_value) + .unwrap_or(raw_value)) } /// Convert a Python object to a C value and store it at the result pointer @@ -1856,6 +2259,31 @@ fn python_to_ffi(obj: PyResult, ty: &Py, result: *mut c_void, vm: &Virtu } } } + #[cfg(windows)] + Some("X") => { + match super::simple::assignment_value("X", &obj, false, vm) { + Ok((mut bytes, _, _)) => { + let address = rustpython_host_env::ctypes::read_pointer_from_buffer(&bytes); + // libffi's result slot is fresh storage, not a previous BSTR. + bytes.commit(); + unsafe { + rustpython_host_env::ctypes::write_callback_result( + Some("X"), + result, + rustpython_host_env::ctypes::CallbackResultValue::Pointer(address), + ); + } + } + Err(exc) => vm.run_unraisable( + exc, + Some( + "Exception ignored while converting result of ctypes callback function" + .to_owned(), + ), + obj, + ), + } + } Some("P" | "z" | "Z") => { if let Ok(i) = obj.try_int(vm) { unsafe { @@ -1892,37 +2320,45 @@ unsafe extern "C" fn thunk_callback( userdata: &ThunkUserData, ) { with_current_vm(|vm| { - let use_errno = userdata.flags & StgInfoFlags::FUNCFLAG_USE_ERRNO.bits() != 0; - let py_result = - rustpython_host_env::ctypes::with_callback_errno_preserved(use_errno, || { - let py_args: Vec = userdata - .arg_types - .iter() - .enumerate() - .map(|(i, ty)| ffi_to_python(ty, args, i, vm)) - .collect(); - - userdata.callable.call(py_args, vm) - }); - - // Call unraisable hook if exception occurred - if let Err(exc) = &py_result { - let repr = userdata - .callable - .repr(vm) - .map_or_else(|_| "".to_string(), |s| s.to_string()); - let msg = format!("Exception ignored while calling ctypes callback function {repr}"); - vm.run_unraisable(exc.clone(), Some(msg), vm.ctx.none()); - } + vm.attach_for_callback(|| { + let use_errno = userdata.flags & StgInfoFlags::FUNCFLAG_USE_ERRNO.bits() != 0; + let py_result = + rustpython_host_env::ctypes::with_callback_errno_preserved(use_errno, || { + let py_args: Vec = userdata + .arg_types + .iter() + .enumerate() + .map(|(i, ty)| ffi_to_python(ty, args, i, vm)) + .collect::>>()?; + + userdata.callable.call(py_args, vm) + }); + + // Call unraisable hook if exception occurred + if let Err(exc) = &py_result { + let repr = userdata + .callable + .repr(vm) + .map_or_else(|_| "".to_string(), |s| s.to_string()); + let msg = + format!("Exception ignored while calling ctypes callback function {repr}"); + vm.run_unraisable(exc.clone(), Some(msg), vm.ctx.none()); + } - if let Some(ref res_type) = userdata.res_type { - python_to_ffi(py_result, res_type, result as *mut c_void, vm); - } + if let Some(ref res_type) = userdata.res_type { + python_to_ffi(py_result, res_type, result as *mut c_void, vm); + } + }); }); } // CThunkObject wraps a Python callable to make it callable from C code. -#[pyclass(name = "CThunkObject", module = "_ctypes")] +#[pyclass( + name = "CThunkObject", + module = "_ctypes", + traverse = "manual", + clear = false +)] #[derive(PyPayload)] pub(super) struct PyCThunk { callable: PyObjectRef, @@ -1931,6 +2367,22 @@ pub(super) struct PyCThunk { code_ptr: FfiCodePtr, } +// SAFETY: the thunk owns both callable references, and all type references in +// its userdata. No references are inferred from executable or native pointers. +unsafe impl Traverse for PyCThunk { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + self.callable.traverse(tracer); + if let Some(data) = self.thunk_data.try_read_recursive() + && let Some(data) = data.as_ref() + { + let data = data.userdata(); + data.callable.traverse(tracer); + data.arg_types.traverse(tracer); + data.res_type.traverse(tracer); + } + } +} + impl Debug for PyCThunk { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCThunk") @@ -1964,9 +2416,13 @@ impl PyCThunk { let ffi_arg_types: Vec = arg_type_vec .iter() .map(|ty| { - ty.type_code(vm) - .and_then(|code| ffi_type_from_code(&code)) - .unwrap_or_else(ffi_pointer_type) + if ty.fast_issubclass(PyCPointer::static_type()) { + ffi_pointer_type() + } else { + ty.type_code(vm) + .and_then(|code| ffi_type_from_code(&code)) + .unwrap_or_else(ffi_pointer_type) + } }) .collect(); @@ -2021,3 +2477,179 @@ impl Py { self.callable.clone() } } + +impl AsSequence for PyCFuncPtrType { + fn as_sequence() -> &'static PySequenceMethods { + &super::array::CTYPE_SEQUENCE_METHODS + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{TryFromObject, class::PyClassImpl, function::ArgBytesLike}; + + #[cfg(all(feature = "compiler", not(target_family = "wasm")))] + #[test] + fn native_out_returns_preserve_python_protocol() { + extern "C" fn fill_one(output: *mut i32) -> i32 { + // The ctypes pointer argument owns an initialized C-int buffer. + unsafe { *output = 11 }; + 33 + } + extern "C" fn fill_two(first: *mut i32, second: *mut i32) -> i32 { + // Both arguments are backed by live ctypes C-int buffers. + unsafe { + *first = 11; + *second = 22; + } + 33 + } + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let scope = vm.new_scope_with_builtins(); + scope + .globals + .set_item( + "address_one", + vm.ctx.new_int(fill_one as *const () as usize).into(), + vm, + ) + .unwrap(); + scope + .globals + .set_item( + "address_two", + vm.ctx.new_int(fill_two as *const () as usize).into(), + vm, + ) + .unwrap(); + vm.run_string( + scope.clone(), + r#" +import _ctypes + +class CInt(_ctypes._SimpleCData): + _type_ = "i" + +events = [] +fail = False + +class Out(CInt): + def __ctypes_from_outparam__(self): + events.append(("convert", self.value)) + if fail: + raise ValueError("output conversion failed") + return ("converted", self.value) + +class Pointer(_ctypes._Pointer): + _type_ = Out + +class Raw(CInt): + def __del__(self): + events.append("drop raw result") + +class One(_ctypes.CFuncPtr): + _flags_ = 1 + _argtypes_ = (Pointer,) + _restype_ = Raw + +class Two(_ctypes.CFuncPtr): + _flags_ = 1 + _argtypes_ = (Pointer, Pointer) + _restype_ = Raw + +out_one = One(address_one) +inout_one = One(address_one) +out_two = Two(address_two) +flags_one = ((2, "first"),) +flags_inout = ((3, "first"),) +flags_two = ((2, "first"), (2, "second")) +"#, + "", + ) + .unwrap(); + // The ordinary DLL constructor currently discards paramflags. + // Inject only that metadata, as the COM constructor does, then + // exercise the real Python -> libffi -> Python call path. + for (function, flags) in [ + ("out_one", "flags_one"), + ("inout_one", "flags_inout"), + ("out_two", "flags_two"), + ] { + let function = scope + .globals + .get_item(function, vm) + .unwrap() + .downcast::() + .unwrap(); + *function.paramflags.write() = Some(scope.globals.get_item(flags, vm).unwrap()); + } + vm.run_string( + scope, + r#" +assert out_one() == ("converted", 11) +assert events == ["drop raw result", ("convert", 11)] +events.clear() +value = Out() +assert inout_one(value) is value +assert value.value == 11 +assert events == ["drop raw result"] +events.clear() +assert out_two() == (("converted", 11), ("converted", 22)) +assert events == ["drop raw result", ("convert", 11), ("convert", 22)] +events.clear() +out_one.errcheck = lambda result, function, args: None +assert out_one() is None +assert events == ["drop raw result"] +events.clear() +out_one.errcheck = lambda result, function, args: args +assert out_one() == ("converted", 11) +assert events == ["drop raw result", ("convert", 11)] +events.clear() +fail = True +try: + out_one() +except ValueError as error: + assert str(error) == "output conversion failed" +else: + raise AssertionError("output conversion failure was swallowed") +assert events == ["drop raw result", ("convert", 11)] +"#, + "", + ) + .unwrap(); + }); + } + + #[test] + fn unlocked_raw_buffers_are_copied_even_when_readonly() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let _class = RawMemoryBuffer::make_static_type(); + for readonly in [false, true] { + let mut storage = *b"before"; + let view = memoryview_at_impl( + storage.as_mut_ptr() as usize, + storage.len() as isize, + readonly, + vm, + ) + .unwrap(); + let buffer = ArgBytesLike::try_from_object(vm, view).unwrap(); + let snapshot = buffer.borrow_buf_unlocked(vm).unwrap(); + assert_ne!(snapshot.as_ptr(), storage.as_ptr()); + storage.copy_from_slice(b"after!"); + assert_eq!(&*snapshot, b"before"); + } + + let bytes = vm.ctx.new_bytes(b"bytes".to_vec()); + let view = crate::builtins::PyMemoryView::from_object(bytes.as_object(), vm) + .unwrap() + .into_pyobject(vm); + for obj in [bytes.clone().into(), view] { + let buffer = ArgBytesLike::try_from_object(vm, obj).unwrap(); + let borrowed = buffer.borrow_buf_unlocked(vm).unwrap(); + assert_eq!(borrowed.as_ptr(), bytes.as_bytes().as_ptr()); + } + }); + } +} diff --git a/crates/vm/src/stdlib/_ctypes/pointer.rs b/crates/vm/src/stdlib/_ctypes/pointer.rs index 6a8ebe660a0..f7a5b28fefa 100644 --- a/crates/vm/src/stdlib/_ctypes/pointer.rs +++ b/crates/vm/src/stdlib/_ctypes/pointer.rs @@ -1,19 +1,19 @@ use super::base::CDATA_BUFFER_METHODS; -use super::{PyCArray, PyCData, PyCSimple, PyCStructure, StgInfo, StgInfoFlags}; +use super::{PyCData, StgInfo, StgInfoFlags}; use crate::atomic_func; -use crate::protocol::{BufferDescriptor, PyBuffer, PyMappingMethods, PyNumberMethods}; -use crate::types::{AsBuffer, AsMapping, AsNumber, Constructor, Initializer}; +use crate::protocol::{ + BufferDescriptor, PyBuffer, PyMappingMethods, PyNumberMethods, PySequenceMethods, +}; +use crate::types::{AsBuffer, AsMapping, AsNumber, AsSequence, Constructor, Initializer}; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, - builtins::{PyBytes, PyInt, PyList, PySlice, PyStr, PyType, PyTypeRef}, - class::StaticType, + builtins::{PyInt, PyList, PySlice, PyType, PyTypeRef}, function::{FuncArgs, OptionalArg}, }; use alloc::borrow::Cow; use num_traits::ToPrimitive; use rustpython_host_env::ctypes::{ - AddressValue, AddressWriteValue, IntegerValue, pointer_item_address, read_pointer_char_slice, - read_pointer_wchar_slice, + pointer_item_address, read_pointer_char_slice, read_pointer_wchar_slice, }; #[pyclass(name = "PyCPointerType", base = PyType, module = "_ctypes")] @@ -72,7 +72,7 @@ impl Initializer for PyCPointerType { stg_info.format = Some(format!("&{shape_str}{current_format}")); } - let _ = new_type.init_type_data(stg_info); + let _ = new_type.init_traced_type_data(stg_info); // Cache: set target_type.__pointer_type__ = self (via StgInfo, not as inheritable attr) if let Ok(type_attr) = new_type.as_object().get_attr("_type_", vm) @@ -80,56 +80,46 @@ impl Initializer for PyCPointerType { && let Some(mut target_info) = target_type.get_type_data_mut::() { let zelf_obj: PyObjectRef = zelf.to_owned().into(); - target_info.pointer_type = Some(zelf_obj); + let _old = target_info.pointer_type.replace(zelf_obj); + drop(target_info); } Ok(()) } } -#[pyclass(flags(BASETYPE, IMMUTABLETYPE), with(AsNumber, Initializer))] +#[pyclass(flags(BASETYPE, IMMUTABLETYPE), with(AsSequence, Initializer))] impl PyCPointerType { - #[pygetset(name = "__pointer_type__")] - fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __pointer_type__(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { super::base::pointer_type_get(&zelf, vm) } - #[pygetset(name = "__pointer_type__", setter)] - fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___pointer_type__( + zelf: PyTypeRef, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { super::base::pointer_type_set(&zelf, value, vm) } #[pymethod] - fn from_param(zelf: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // zelf is the pointer type class that from_param was called on - let cls = zelf - .downcast::() - .map_err(|_| vm.new_type_error("from_param: expected a type"))?; - - // 1. None is allowed for pointer types + fn from_param(cls: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + // None is allowed for pointer types if vm.is_none(&value) { return Ok(value); } - // 1.5 CArgObject (from byref()) - check if underlying obj is instance of _type_ - if let Some(carg) = value.downcast_ref::() - && let Ok(type_attr) = cls.as_object().get_attr("_type_", vm) - && let Ok(type_ref) = type_attr.downcast::() - && carg.obj.is_instance(type_ref.as_object(), vm)? - { - return Ok(value); - } - - // 2. If already an instance of the requested type, return it - if value.is_instance(cls.as_object(), vm)? { - return Ok(value); - } + // Conversion follows the initialized prototype, not a later assignment + // to _type_. Release the metadata borrow before instance/subclass checks. + let proto = cls.stg_info(vm)?.proto.clone().ok_or_else(|| { + vm.new_type_error("cannot convert argument: POINTER _type_ type is not set") + })?; - // 3. If value is an instance of _type_ (the pointed-to type), wrap with byref - if let Ok(type_attr) = cls.as_object().get_attr("_type_", vm) - && let Ok(type_ref) = type_attr.downcast::() - && value.is_instance(type_ref.as_object(), vm)? - { + // A direct referent is implicitly passed by reference. This special + // conversion does not apply to values found through _as_parameter_. + if value.is_instance(proto.as_object(), vm)? { // Return byref(value) return super::_ctypes::byref( super::_ctypes::ByRefArgs { @@ -140,49 +130,20 @@ impl PyCPointerType { ); } - // 4. Array/Pointer instances with compatible proto + // Array/Pointer instances with compatible proto // "Array instances are also pointers when the item types are the same." - let is_pointer_or_array = value.downcast_ref::().is_some() - || value.downcast_ref::().is_some(); - - if is_pointer_or_array { - let is_compatible = { - if let Some(value_stginfo) = value.class().stg_info_opt() - && let Some(ref value_proto) = value_stginfo.proto - && let Some(cls_stginfo) = cls.stg_info_opt() - && let Some(ref cls_proto) = cls_stginfo.proto - { - // Check if value's proto is a subclass of target's proto - value_proto.fast_issubclass(cls_proto) - } else { - false - } - }; - if is_compatible { + if value.downcast_ref::().is_some() + || value.downcast_ref::().is_some() + { + let value_proto = value.class().stg_info(vm)?.proto.clone(); + if let Some(value_proto) = value_proto + && value_proto.as_object().is_subclass(proto.as_object(), vm)? + { return Ok(value); } } - // 5. Check for _as_parameter_ attribute - if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); - } - - Err(vm.new_type_error(format!( - "expected {} instance instead of {}", - cls.name(), - value.class().name() - ))) - } - - fn __mul__(cls: PyTypeRef, n: isize, vm: &VirtualMachine) -> PyResult { - use super::array::array_type_from_ctype; - - if n < 0 { - return Err(vm.new_value_error(format!("Array length must be >= 0, not {n}"))); - } - // Use cached array type creation - array_type_from_ctype(cls.into(), n as usize, vm) + PyCData::from_param(cls, value, vm) } // PyCPointerType_set_type: Complete an incomplete pointer type @@ -222,30 +183,17 @@ impl PyCPointerType { // 5. Cache: set target_type.__pointer_type__ = self (via StgInfo) if let Some(mut target_info) = typ_type.get_type_data_mut::() { - target_info.pointer_type = Some(zelf.into()); + let _old = target_info.pointer_type.replace(zelf.into()); + drop(target_info); } Ok(()) } } -impl AsNumber for PyCPointerType { - fn as_number() -> &'static PyNumberMethods { - static AS_NUMBER: PyNumberMethods = PyNumberMethods { - multiply: Some(|a, b, vm| { - let cls = a - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("expected type"))?; - let n = b - .try_index(vm)? - .as_bigint() - .to_isize() - .ok_or_else(|| vm.new_overflow_error("array size too large"))?; - PyCPointerType::__mul__(cls.to_owned(), n, vm) - }), - ..PyNumberMethods::NOT_IMPLEMENTED - }; - &AS_NUMBER +impl AsSequence for PyCPointerType { + fn as_sequence() -> &'static PySequenceMethods { + &super::array::CTYPE_SEQUENCE_METHODS } } @@ -254,12 +202,23 @@ impl AsNumber for PyCPointerType { name = "_Pointer", base = PyCData, metaclass = "PyCPointerType", - module = "_ctypes" + module = "_ctypes", + traverse = "manual" )] #[derive(Debug)] #[repr(transparent)] pub(crate) struct PyCPointer(pub PyCData); +// SAFETY: this transparent wrapper owns exactly the references in its base. +unsafe impl crate::object::Traverse for PyCPointer { + fn traverse(&self, tracer: &mut crate::object::TraverseFn<'_>) { + self.0.traverse(tracer); + } + fn clear(&mut self, out: &mut Vec) { + self.0.clear(out); + } +} + impl Constructor for PyCPointer { type Args = FuncArgs; @@ -310,13 +269,7 @@ impl PyCPointer { /// Set the pointer value in buffer pub(crate) fn set_ptr_value(&self, value: usize) { - let mut buffer = self.0.buffer.write(); - rustpython_host_env::ctypes::write_pointer_to_buffer_at( - buffer.to_mut(), - 0, - rustpython_host_env::ctypes::pointer_size(), - value, - ); + self.0.write_bytes_at_offset(0, &value.to_ne_bytes()); } // contents getter - reads address from b_ptr and creates an instance of the pointed-to type @@ -335,12 +288,13 @@ impl PyCPointer { .stg_info_opt() .map_or_else(rustpython_host_env::ctypes::pointer_size, |info| info.size); - // Create instance that references the memory directly - // PyCData.into_ref_with_type works for all ctypes (simple, structure, union, array, pointer) - let cdata = unsafe { super::base::PyCData::at_address(ptr_val as *const u8, element_size) }; - cdata - .into_ref_with_type(vm, proto_type.to_owned()) - .map(Into::into) + // SAFETY: the pointer must designate valid native memory. Retaining it + // keeps Python-owned referents alive, but cannot validate arbitrary addresses. + let cdata = unsafe { + PyCData::from_base_obj(ptr_val as *mut u8, element_size, zelf.to_owned().into(), 0) + }; + cdata.length.store(proto_type.stg_info(vm)?.length); + cdata.into_view(proto_type.to_owned(), vm) } // contents setter - stores address in b_ptr and keeps reference @@ -422,26 +376,46 @@ impl PyCPointer { // offset = index * iteminfo->size let addr = pointer_item_address(ptr_value, index, element_size); - // Check if it's a simple type (has _type_ attribute) - if let Ok(type_attr) = proto_type.as_object().get_attr("_type_", vm) - && let Ok(type_str) = type_attr.str(vm) - { - let type_code = type_str.to_string(); - return Ok(Self::read_value_at_address( - addr, - element_size, - Some(&type_code), - vm, - )); + // Direct simple types and their generated endian variants return a + // scalar; user subclasses and aggregates return a view. + if super::simple::returns_scalar(proto_type) { + // SAFETY: pointer indexing requires valid native storage covering + // the element. Ownership of arbitrary addresses remains the caller's + // responsibility, as for the view returned below. + let bytes = unsafe { + rustpython_host_env::ctypes::borrow_memory(addr as *const u8, element_size) + }; + if proto_type.stg_info(vm)?.scalar_code == Some('O') { + return zelf.0.object_at( + rustpython_host_env::ctypes::read_pointer_from_buffer(bytes), + addr, + Some(index as usize), + vm, + ); + } + if super::simple::is_swapped(proto_type) { + let mut bytes = bytes.to_vec(); + bytes.reverse(); + return Ok(super::base::bytes_to_pyobject(proto_type, &bytes, vm)); + } + return Ok(super::base::bytes_to_pyobject(proto_type, bytes, vm)); } // Complex type: create instance that references the memory directly (not a copy) // This allows p[i].val = x to modify the original memory - // PyCData.into_ref_with_type works for all ctypes (array, structure, union, pointer) - let cdata = unsafe { super::base::PyCData::at_address(addr as *const u8, element_size) }; - cdata - .into_ref_with_type(vm, proto_type.to_owned()) - .map(Into::into) + // SAFETY: pointer indexing relies on the caller providing valid native + // memory. Retaining the pointer keeps its Python-owned referents alive, + // but does not make arbitrary addresses or concurrent native access safe. + let cdata = unsafe { + PyCData::from_base_obj( + addr as *mut u8, + element_size, + zelf.to_owned().into(), + index as usize, + ) + }; + cdata.length.store(proto_type.stg_info(vm)?.length); + cdata.into_view(proto_type.to_owned(), vm) } // Pointer_subscript slice handling (manual parsing, not PySlice_Unpack) @@ -508,12 +482,7 @@ impl PyCPointer { } else { rustpython_host_env::ctypes::pointer_size() }; - let type_code = stg_info - .proto - .as_ref() - .and_then(|p| p.as_object().get_attr("_type_", vm).ok()) - .and_then(|t| t.str(vm).ok()) - .map(|s| s.to_string()); + let type_code = stg_info.proto.as_ref().and_then(|p| p.type_code(vm)); let ptr_value = zelf.get_ptr_value(); @@ -577,161 +546,41 @@ impl PyCPointer { return Err(vm.new_value_error("NULL pointer access")); } - // Get element type, size and type_code from StgInfo.proto - let stg_info = zelf.class().stg_info(vm)?; - let proto_type = stg_info.proto(); - - // Get type code from proto's _type_ attribute - let type_code: Option = proto_type - .as_object() - .get_attr("_type_", vm) - .ok() - .and_then(|t| t.downcast_ref::().map(|s| s.to_string())); - - let element_size = proto_type - .stg_info_opt() - .map_or_else(rustpython_host_env::ctypes::pointer_size, |info| info.size); - - // Calculate address + let proto_type = zelf.class().stg_info(vm)?.proto().to_owned(); + let element_size = proto_type.stg_info(vm)?.size; let addr = pointer_item_address(ptr_value, index, element_size); - - // Write value at address - // Handle Structure/Array types by copying their buffer - if let Some(cdata) = value.downcast_ref::() - && (cdata.fast_isinstance(PyCStructure::static_type()) - || cdata.fast_isinstance(PyCArray::static_type()) - || cdata.fast_isinstance(PyCSimple::static_type())) + let write = if proto_type + .stg_info(vm)? + .flags + .intersects(StgInfoFlags::TYPEFLAG_ISPOINTER | StgInfoFlags::TYPEFLAG_HASPOINTER) { - let src_buffer = cdata.buffer.read(); - unsafe { - rustpython_host_env::ctypes::copy_bytes_to_address(addr, &src_buffer, element_size); - } + PyCData::register_pyobject_writer( + zelf.as_object(), + addr, + element_size, + index as usize, + vm, + )? } else { - // Handle z/Z specially to store converted value - if type_code.as_deref() == Some("z") - && let Some(bytes) = value.downcast_ref::() - { - let (kept_alive, ptr_val) = super::base::ensure_z_null_terminated(bytes, vm); - unsafe { - rustpython_host_env::ctypes::write_value_to_address( - addr, - element_size, - AddressWriteValue::Pointer(ptr_val), - ); - } - zelf.0.keep_alive(index as usize, kept_alive); - return zelf.0.keep_ref(index as usize, value.clone(), vm); - } else if type_code.as_deref() == Some("Z") - && let Some(s) = value.downcast_ref::() - { - let (holder, ptr_val) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm); - unsafe { - rustpython_host_env::ctypes::write_value_to_address( - addr, - element_size, - AddressWriteValue::Pointer(ptr_val), - ); - } - return zelf.0.keep_ref(index as usize, holder, vm); - } - Self::write_value_at_address(addr, element_size, &value, type_code.as_deref(), vm)?; - } - - // KeepRef: store reference to keep value alive using actual index - zelf.0.keep_ref(index as usize, value, vm) - } - - /// Read a value from memory address - fn read_value_at_address( - addr: usize, - size: usize, - type_code: Option<&str>, - vm: &VirtualMachine, - ) -> PyObjectRef { - match unsafe { rustpython_host_env::ctypes::read_value_at_address(addr, size, type_code) } { - AddressValue::ByteString(byte) => vm.ctx.new_bytes(vec![byte]).into(), - AddressValue::Integer(IntegerValue::Signed(value)) => vm.ctx.new_int(value).into(), - AddressValue::Integer(IntegerValue::Unsigned(value)) => vm.ctx.new_int(value).into(), - AddressValue::Float(value) => vm.ctx.new_float(value).into(), - AddressValue::Pointer(value) => vm.ctx.new_int(value).into(), - AddressValue::Bytes(bytes) => vm.ctx.new_bytes(bytes).into(), - } - } - - /// Write a value to memory address - fn write_value_at_address( - addr: usize, - size: usize, - value: &PyObject, - type_code: Option<&str>, - vm: &VirtualMachine, - ) -> PyResult<()> { + super::base::CDataWrite::default() + }; + let mut prepared = super::base::CDataValue::new( + &proto_type, + &value, + element_size, + super::simple::is_swapped(&proto_type), + vm, + )?; + write.publish(vm)?; + // SAFETY: pointer indexing has the same caller-provided valid-storage + // requirement as reading the element. The source snapshot cannot overlap it. unsafe { - // Handle c_char_p (z) and c_wchar_p (Z) - store pointer address - // Note: PyBytes/PyStr cases are handled by caller (setitem_by_index) - if let Some("z" | "Z") = type_code { - let ptr_val = if vm.is_none(value) { - 0usize - } else if let Ok(int_val) = value.try_index(vm) { - super::simple::bigint_to_i128_wrapping(int_val.as_bigint()) as usize - } else { - return Err(vm.new_type_error("bytes/string or integer address expected")); - }; - rustpython_host_env::ctypes::write_value_to_address( - addr, - size, - AddressWriteValue::Pointer(ptr_val), - ); - return Ok(()); - } - - // Try to get value as integer - // Use write_unaligned for safety on strict-alignment architectures - if let Ok(int_val) = value.try_int(vm) { - let i = int_val.as_bigint(); - let wrapped = super::simple::bigint_to_i128_wrapping(i); - let bytes; - let write_value = match size { - 1 => AddressWriteValue::U8(wrapped as u8), - 2 => AddressWriteValue::I16(wrapped as i16), - 4 => AddressWriteValue::I32(wrapped as i32), - 8 => AddressWriteValue::I64(wrapped as i64), - _ => { - bytes = i.to_signed_bytes_le(); - AddressWriteValue::Bytes(&bytes) - } - }; - rustpython_host_env::ctypes::write_value_to_address(addr, size, write_value); - return Ok(()); - } - - // Try to get value as float - if let Ok(float_val) = value.try_float(vm) { - let f = float_val.to_f64(); - rustpython_host_env::ctypes::write_value_to_address( - addr, - size, - AddressWriteValue::Float(f), - ); - return Ok(()); - } - - // Try bytes - if value.check_buffer() { - let bytes = value.try_bytes_like(vm, |b| b.to_vec())?; - rustpython_host_env::ctypes::write_value_to_address( - addr, - size, - AddressWriteValue::Bytes(&bytes), - ); - return Ok(()); - } - - Err(vm.new_type_error(format!( - "cannot convert {} to ctypes data", - value.class().name() - ))) + let previous = + rustpython_host_env::ctypes::borrow_memory(addr as *const u8, element_size); + prepared.bytes.replace(previous); + rustpython_host_env::ctypes::copy_bytes_to_address(addr, &prepared.bytes, element_size); } + prepared.keep(&zelf.0, index as usize, vm) } } @@ -781,14 +630,7 @@ impl AsBuffer for PyCPointer { .map_or(Cow::Borrowed("&B"), Cow::Owned); let itemsize = stg_info.size; // Pointer types are scalars with ndim=0, shape=() - let desc = BufferDescriptor { - offset: 0, - len: itemsize, - readonly: false, - itemsize, - format, - dim_desc: vec![], - }; + let desc = BufferDescriptor::from_dim_desc(itemsize, 0, false, itemsize, format, vec![]); let buf = PyBuffer::new(zelf.to_owned().into(), desc, &CDATA_BUFFER_METHODS); Ok(buf) } diff --git a/crates/vm/src/stdlib/_ctypes/simple.rs b/crates/vm/src/stdlib/_ctypes/simple.rs index 1a0e12ba457..91e04cd2e25 100644 --- a/crates/vm/src/stdlib/_ctypes/simple.rs +++ b/crates/vm/src/stdlib/_ctypes/simple.rs @@ -1,25 +1,26 @@ use super::_ctypes::CArgObject; use super::array::PyCArray; use super::base::{ - CArgValue, CDATA_BUFFER_METHODS, PyCData, StgInfo, StgInfoFlags, bytes_to_pyobject, + CArgValue, CDATA_BUFFER_METHODS, CDataBytes, ParamFunc, PyCData, StgInfo, StgInfoFlags, + bytes_to_pyobject, }; use super::function::PyCFuncPtr; use super::pointer::PyCPointer; -use crate::builtins::{PyByteArray, PyBytes, PyInt, PyNone, PyStr, PyType, PyTypeRef}; -use crate::convert::ToPyObject; -use crate::function::{Either, FuncArgs, OptionalArg}; -use crate::protocol::{BufferDescriptor, PyBuffer, PyNumberMethods}; -use crate::types::{AsBuffer, AsNumber, Constructor, Initializer, Representable}; +use crate::builtins::{PyByteArray, PyBytes, PyInt, PyStr, PyType, PyTypeRef}; +use crate::class::StaticType; +use crate::convert::{ToPyObject, TryFromObject}; +use crate::function::{ArgIntoFloat, Either, FuncArgs, KwArgs, OptionalArg}; +use crate::protocol::{BufferDescriptor, PyBuffer, PyNumberMethods, PySequenceMethods}; +use crate::types::{AsBuffer, AsNumber, AsSequence, Constructor, Initializer, Representable}; use crate::{ - AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - class::PyClassDef, set_attrs, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, set_attrs, }; use alloc::borrow::Cow; use core::fmt::Debug; use num_traits::ToPrimitive; use rustpython_host_env::ctypes::{ SimpleStorageValue, simple_storage_value_to_bytes_endian, simple_type_align, - simple_type_pep3118_code, simple_type_size, write_simple_storage_buffer, zeroed_bytes, + simple_type_pep3118_code, simple_type_size, zeroed_bytes, }; /// Valid type codes for ctypes simple types @@ -47,6 +48,15 @@ fn new_simple_type( Either::B(typ) => typ.as_object(), }; + if let Some(typ) = cls.downcast_ref::() + && let Some(info) = typ.stg_info_opt() + { + return Ok(PyCSimple(PyCData::from_bytes( + zeroed_bytes(info.size), + None, + ))); + } + let _type_ = cls .get_attr("_type_", vm) .map_err(|_| vm.new_attribute_error("class must define a '_type_' attribute"))?; @@ -57,6 +67,12 @@ fn new_simple_type( let tp_str = _type_.str(vm)?.to_string(); + // Complex ctypes storage and FFI are not implemented. Preserve the + // optional-type AttributeError contract for the PEP 3118 codes. + if matches!(tp_str.as_str(), "Zd" | "Zf" | "Zg") { + return Err(vm.new_attribute_error("complex ctypes types are not supported")); + } + if tp_str.len() != 1 { return Err(vm.new_value_error(format!( "class must define a '_type_' attribute which must be a string of length 1, str: {tp_str}" @@ -74,6 +90,9 @@ fn new_simple_type( } pub(super) fn bigint_to_i128_wrapping(value: &malachite_bigint::BigInt) -> i128 { + if let Some(value) = value.to_i128() { + return value; + } let bytes = value.to_signed_bytes_le(); let fill = bytes .last() @@ -84,157 +103,24 @@ pub(super) fn bigint_to_i128_wrapping(value: &malachite_bigint::BigInt) -> i128 i128::from_le_bytes(wrapped) } -fn set_primitive(_type_: &str, value: &PyObject, vm: &VirtualMachine) -> PyResult { - match _type_ { - "c" => { - // c_set: accepts bytes(len=1), bytearray(len=1), or int(0-255) - if value - .downcast_ref_if_exact::(vm) - .is_some_and(|v| v.as_bytes().len() == 1) - || value - .downcast_ref_if_exact::(vm) - .is_some_and(|v| v.borrow_buf().len() == 1) - || value.downcast_ref_if_exact::(vm).is_some_and(|v| { - v.as_bigint() - .to_i64() - .is_some_and(|n| (0..=255).contains(&n)) - }) - { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error("one character bytes, bytearray or integer expected")) - } - } - "u" => { - if let Some(s) = value.downcast_ref::() { - if s.as_wtf8().code_points().count() == 1 { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error("one character unicode string expected")) - } - } else { - Err(vm.new_type_error(format!( - "unicode string expected instead of {} instance", - value.class().name() - ))) - } - } - "b" | "h" | "H" | "i" | "I" | "l" | "q" | "L" | "Q" => { - // Support __index__ protocol - if value.try_index(vm).is_ok() { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error(format!( - "an integer is required (got type {})", - value.class().name() - ))) - } - } - "f" | "d" | "g" => { - // Handle int specially to check overflow - if let Some(int_obj) = value.downcast_ref_if_exact::(vm) { - // Check if int can fit in f64 - if let Some(f) = int_obj.as_bigint().to_f64() - && f.is_finite() - { - return Ok(value.to_owned()); - } - return Err(vm.new_overflow_error("int too large to convert to float")); - } - // __float__ protocol - if value.try_float(vm).is_ok() { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error(format!("must be real number, not {}", value.class().name()))) - } - } - "?" => Ok(PyObjectRef::from( - vm.ctx.new_bool(value.to_owned().try_to_bool(vm)?), - )), - "v" => { - // VARIANT_BOOL: any truthy → True - Ok(PyObjectRef::from( - vm.ctx.new_bool(value.to_owned().try_to_bool(vm)?), - )) - } - "B" => { - // Support __index__ protocol - if value.try_index(vm).is_ok() { - // Store as-is, conversion to unsigned happens in the getter - Ok(value.to_owned()) - } else { - Err(vm.new_type_error(format!("int expected instead of {}", value.class().name()))) - } - } - "z" => { - if value.is(&vm.ctx.none) - || value.downcast_ref_if_exact::(vm).is_some() - || value.downcast_ref_if_exact::(vm).is_some() - { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error(format!( - "bytes or integer address expected instead of {} instance", - value.class().name() - ))) - } - } - "Z" => { - if value.is(&vm.ctx.none) - || value.downcast_ref_if_exact::(vm).is_some() - || value.downcast_ref_if_exact::(vm).is_some() - { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error(format!( - "unicode string or integer address expected instead of {} instance", - value.class().name() - ))) - } - } - // O_set: py_object accepts any Python object - "O" => Ok(value.to_owned()), - // X_set: BSTR - same as Z (c_wchar_p), accepts None, int, or str - "X" => { - if value.is(&vm.ctx.none) - || value.downcast_ref_if_exact::(vm).is_some() - || value.downcast_ref_if_exact::(vm).is_some() - { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error(format!( - "unicode string or integer address expected instead of {} instance", - value.class().name() - ))) - } - } - _ => { - // "P" - if value.downcast_ref_if_exact::(vm).is_some() - || value.downcast_ref_if_exact::(vm).is_some() - { - Ok(value.to_owned()) - } else { - Err(vm.new_type_error("cannot be converted to pointer")) - } - } - } -} - #[pyclass(module = "_ctypes", name = "PyCSimpleType", base = PyType)] #[derive(Debug)] #[repr(transparent)] pub(crate) struct PyCSimpleType(PyType); -#[pyclass(flags(BASETYPE), with(AsNumber, Initializer))] +#[pyclass(flags(BASETYPE), with(AsSequence, Initializer))] impl PyCSimpleType { - #[pygetset(name = "__pointer_type__")] - fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __pointer_type__(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { super::base::pointer_type_get(&zelf, vm) } - #[pygetset(name = "__pointer_type__", setter)] - fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___pointer_type__( + zelf: PyTypeRef, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { super::base::pointer_type_set(&zelf, value, vm) } @@ -259,26 +145,27 @@ impl PyCSimpleType { } // 2. Get the type code to determine conversion rules - let type_code = cls.type_code(vm); + let code = cls + .stg_info(vm)? + .scalar_code + .ok_or_else(|| vm.new_type_error("abstract class"))?; + let type_code = code.to_string(); // 3. Handle None for pointer types (c_char_p, c_wchar_p, c_void_p) - if vm.is_none(&value) && matches!(type_code.as_deref(), Some("z" | "Z" | "P")) { + if vm.is_none(&value) && matches!(code, 'z' | 'Z' | 'P') { return Ok(value); } - // Helper to create CArgObject wrapping a simple instance - let create_simple_with_value = |type_str: &str, val: &PyObject| -> PyResult { - let simple = new_simple_type(Either::B(&cls), vm)?; - let buffer_bytes = value_to_bytes_endian(type_str, val, false, vm); - *simple.0.buffer.write() = alloc::borrow::Cow::Owned(buffer_bytes.clone()); - let simple_obj: PyObjectRef = simple.into_ref_with_type(vm, cls.clone())?.into(); - // from_param returns CArgObject, not the simple type itself - let tag = type_str.as_bytes().first().copied().unwrap_or(b'?'); + // Foreign-call values are always native endian, even for swapped types. + let create_argument = || -> PyResult { + let (mut bytes, keep, hidden) = assignment_value(&type_code, &value, false, vm)?; + bytes.commit(); + let tag = code as u8; Ok(CArgObject { tag, - value: CArgValue::typed(tag as char, &buffer_bytes), - obj: simple_obj, - keep: None, + value: CArgValue::typed(code, &bytes), + obj: keep.unwrap_or_else(|| vm.ctx.none()), + keep: hidden, size: 0, offset: 0, } @@ -286,45 +173,9 @@ impl PyCSimpleType { }; // 4. Try to convert value based on type code - match type_code.as_deref() { - // Integer types: accept integers - Some(tc @ ("b" | "B" | "h" | "H" | "i" | "I" | "l" | "L" | "q" | "Q")) - if value.try_int(vm).is_ok() => - { - return create_simple_with_value(tc, &value); - } - - // Float types: accept numbers - Some(tc @ ("f" | "d" | "g")) - if value.try_float(vm).is_ok() || value.try_int(vm).is_ok() => - { - return create_simple_with_value(tc, &value); - } - // c_char: 1 byte character - Some("c") => { - if let Some(bytes) = value.downcast_ref::() - && bytes.as_bytes().len() == 1 - { - return create_simple_with_value("c", &value); - } - if let Ok(int_val) = value.try_int(vm) - && int_val.as_bigint().to_u8().is_some() - { - return create_simple_with_value("c", &value); - } - return Err(vm.new_type_error("one character bytes, bytearray or integer expected")); - } - // c_wchar: 1 unicode character - Some("u") => { - if let Some(s) = value.downcast_ref::() - && s.as_wtf8().code_points().count() == 1 - { - return create_simple_with_value("u", &value); - } - return Err(vm.new_type_error("one character unicode string expected")); - } + let error = match code { // c_char_p: bytes pointer - Some("z") => { + 'z' => { // 1. bytes → create CArgObject with null-terminated buffer if let Some(bytes) = value.downcast_ref::() { let (kept_alive, ptr) = super::base::ensure_z_null_terminated(bytes, vm); @@ -348,9 +199,13 @@ impl PyCSimpleType { { return Ok(value.clone()); } + vm.new_type_error(format!( + "'{}' object cannot be interpreted as ctypes.c_char_p", + value.class().name() + )) } // c_wchar_p: unicode pointer - Some("Z") => { + 'Z' => { // 1. str → create CArgObject with null-terminated wchar buffer if let Some(s) = value.downcast_ref::() { let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm); @@ -374,12 +229,16 @@ impl PyCSimpleType { { return Ok(value.clone()); } + vm.new_type_error(format!( + "'{}' object cannot be interpreted as ctypes.c_wchar_p", + value.class().name() + )) } // c_void_p: most flexible - accepts int, bytes, str, any array/pointer, funcptr - Some("P") => { + 'P' => { // 1. int → create c_void_p with that address - if value.try_int(vm).is_ok() { - return create_simple_with_value("P", &value); + if value.downcast_ref::().is_some() { + return create_argument(); } // 2. bytes → create CArgObject with null-terminated buffer if let Some(bytes) = value.downcast_ref::() { @@ -454,71 +313,28 @@ impl PyCSimpleType { .to_pyobject(vm)); } } + vm.new_type_error("wrong type") } - // py_object: pass any Python object as PyObject* - Some("O") => { - return Ok(CArgObject { - tag: b'O', - value: CArgValue::pointer(value.get_id()), - obj: value, - keep: None, - size: 0, - offset: 0, - } - .to_pyobject(vm)); - } - // c_bool - Some("?") => { - let bool_val = value.is_true(vm)?; - let bool_obj: PyObjectRef = vm.ctx.new_bool(bool_val).into(); - return create_simple_with_value("?", &bool_obj); - } - _ => {} - } - - // 5. Check for _as_parameter_ attribute - if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); - } + _ => match create_argument() { + Ok(arg) => return Ok(arg), + Err(error) => error, + }, + }; - // 6. Type-specific error messages - match type_code.as_deref() { - Some("z") => Err(vm.new_type_error(format!( - "'{}' object cannot be interpreted as ctypes.c_char_p", - value.class().name() - ))), - Some("Z") => Err(vm.new_type_error(format!( - "'{}' object cannot be interpreted as ctypes.c_wchar_p", - value.class().name() - ))), - _ => Err(vm.new_type_error("wrong type")), + // A successful _as_parameter_ fallback replaces the conversion error; + // an absent attribute preserves it, and a failing lookup propagates. + if let Some(as_parameter) = vm.get_attribute_opt(&value, "_as_parameter_")? { + return vm.with_recursion(" while processing _as_parameter_", || { + Self::from_param(cls.as_object().to_owned(), as_parameter, vm) + }); } - } - - fn __mul__(cls: PyTypeRef, n: isize, vm: &VirtualMachine) -> PyResult { - Py::::repeat(cls, n, vm) + Err(error) } } -impl AsNumber for PyCSimpleType { - fn as_number() -> &'static PyNumberMethods { - static AS_NUMBER: PyNumberMethods = PyNumberMethods { - multiply: Some(|a, b, vm| { - // a is a PyCSimpleType instance (type object like c_char) - // b is int (array size) - let cls = a - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("expected type"))?; - let n = b - .try_index(vm)? - .as_bigint() - .to_isize() - .ok_or_else(|| vm.new_overflow_error("array size too large"))?; - Py::::repeat(cls.to_owned(), n, vm) - }), - ..PyNumberMethods::NOT_IMPLEMENTED - }; - &AS_NUMBER +impl AsSequence for PyCSimpleType { + fn as_sequence() -> &'static PySequenceMethods { + &super::array::CTYPE_SEQUENCE_METHODS } } @@ -555,6 +371,12 @@ impl Initializer for PyCSimpleType { let type_str = type_attr.str(vm)?.to_string(); // Validate _type_ is a single character + // Complex ctypes storage and FFI are not implemented. Preserve the + // optional-type AttributeError contract for the PEP 3118 codes. + if matches!(type_str.as_str(), "Zd" | "Zf" | "Zg") { + return Err(vm.new_attribute_error("complex ctypes types are not supported")); + } + if type_str.len() != 1 { return Err(vm.new_value_error( "class must define a '_type_' attribute which must be a string of length 1", @@ -572,6 +394,7 @@ impl Initializer for PyCSimpleType { let size = simple_type_size(&type_str).expect("invalid ctypes simple type"); let align = simple_type_align(&type_str).expect("invalid ctypes simple type"); let mut stg_info = StgInfo::new(size, align); + stg_info.scalar_code = type_str.chars().next(); // Set format for PEP 3118 buffer protocol stg_info.format = Some(alloc_format_string_for_type( @@ -589,7 +412,9 @@ impl Initializer for PyCSimpleType { super::base::set_or_init_stginfo(&type_ref, stg_info); // Create __ctype_le__ and __ctype_be__ swapped types - create_swapped_types(&type_ref, &type_str, vm)?; + if type_ref.class().is(Self::static_type()) { + create_swapped_types(&type_ref, &type_str, args, vm)?; + } Ok(()) } @@ -605,18 +430,12 @@ impl Initializer for PyCSimpleType { fn create_swapped_types( type_ref: &Py, type_str: &str, + mut args: FuncArgs, vm: &VirtualMachine, ) -> PyResult<()> { - use crate::builtins::PyDict; - - // Avoid infinite recursion - if __ctype_le__ already exists, skip - if type_ref.as_object().get_attr("__ctype_le__", vm).is_ok() { - return Ok(()); - } - // Types that don't support byte order swapping - no __ctype_le__/__ctype_be__ // c_void_p (P), c_char_p (z), c_wchar_p (Z), c_wchar (u), py_object (O) - let unsupported_types = ["P", "z", "Z", "u", "O"]; + let unsupported_types = ["P", "z", "Z", "X", "u", "O"]; if unsupported_types.contains(&type_str) { return Ok(()); } @@ -637,31 +456,15 @@ fn create_swapped_types( // Check system byte order at compile time let is_little_endian = cfg!(target_endian = "little"); - // Create dict for the swapped (non-native) type - let swapped_dict: crate::PyRef = PyDict::default().into_ref(&vm.ctx); - swapped_dict.set_item("_type_", vm.ctx.new_str(type_str).into(), vm)?; - - // Create the swapped type using the same metaclass - let metaclass = type_ref.class(); - let bases = vm.ctx.new_tuple(vec![type_ref.as_object().to_owned()]); - - // Set placeholder first to prevent recursion - set_attrs!( - type_ref.as_object(), vm, - "__ctype_le__" => vm.ctx.none(), - "__ctype_be__" => vm.ctx.none(), - ); - // Create only the non-native endian type let suffix = if is_little_endian { "_be" } else { "_le" }; - let swapped_type = metaclass.as_object().call( - ( - vm.ctx.new_str(format!("{}{}", type_ref.name(), suffix)), - bases, - swapped_dict.as_object().to_owned(), - ), - vm, - )?; + args.args[0] = vm + .ctx + .new_str(format!("{}{}", type_ref.name(), suffix)) + .into(); + // Endian variants share bases and class attributes; neither subclasses + // the other. Bypass the initializer to avoid generating another pair. + let swapped_type = PyType::slot_new(type_ref.class().to_owned(), args, vm)?; // Set _swappedbytes_ on the swapped type to indicate byte swapping is needed set_attrs!( @@ -670,14 +473,15 @@ fn create_swapped_types( ); // Update swapped type's StgInfo format to use opposite endian prefix - if let Ok(swapped_type_ref) = swapped_type.clone().downcast::() - && let Some(mut sw_stg) = swapped_type_ref.get_type_data_mut::() - { + if let Ok(swapped_type_ref) = swapped_type.clone().downcast::() { + let mut sw_stg = type_ref.stg_info(vm)?.clone(); // Swapped: little-endian system uses big-endian prefix and vice versa + sw_stg.big_endian = is_little_endian; sw_stg.format = Some(alloc_format_string_for_type( type_str.chars().next().unwrap_or('?'), is_little_endian, )); + super::base::set_or_init_stginfo(&swapped_type_ref, sw_stg); } // Set attributes based on system byte order @@ -711,11 +515,22 @@ fn create_swapped_types( module = "_ctypes", name = "_SimpleCData", base = PyCData, - metaclass = "PyCSimpleType" + metaclass = "PyCSimpleType", + traverse = "manual" )] #[repr(transparent)] pub(crate) struct PyCSimple(pub PyCData); +// SAFETY: this transparent wrapper owns exactly the references in its base. +unsafe impl crate::object::Traverse for PyCSimple { + fn traverse(&self, tracer: &mut crate::object::TraverseFn<'_>) { + self.0.traverse(tracer); + } + fn clear(&mut self, out: &mut Vec) { + self.0.clear(out); + } +} + impl Debug for PyCSimple { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCSimple") @@ -724,218 +539,141 @@ impl Debug for PyCSimple { } } -fn value_to_bytes_endian( - _type_: &str, +pub(super) fn is_swapped(cls: &Py) -> bool { + cls.stg_info_opt().is_some_and(|info| { + info.paramfunc == ParamFunc::Simple && info.big_endian != cfg!(target_endian = "big") + }) +} + +pub(super) fn returns_scalar(cls: &Py) -> bool { + cls.base + .deref() + .is_some_and(|base| base.is(PyCSimple::static_type())) +} + +pub(super) fn assignment_value( + type_code: &str, value: &PyObject, swapped: bool, vm: &VirtualMachine, -) -> Vec { - let storage_value = match _type_ { +) -> PyResult<(CDataBytes, Option, Option)> { + let mut keep = None; + let mut hidden = None; + // Convert once before writing: numeric conversion may reenter ctypes. + let storage = match type_code { "c" => { - // c_char - single byte (bytes, bytearray, or int 0-255) - if let Some(bytes) = value.downcast_ref::() - && !bytes.as_bytes().is_empty() - { - SimpleStorageValue::Byte(bytes.as_bytes()[0]) - } else if let Some(bytearray) = value.downcast_ref::() { - let buf = bytearray.borrow_buf(); - if !buf.is_empty() { - SimpleStorageValue::Byte(buf[0]) - } else { - SimpleStorageValue::Zero + let byte = if let Some(bytes) = value.downcast_ref::() { + match bytes.as_bytes() { + [byte] => *byte, + _ => return Err(vm.new_type_error("one character bytes expected")), } - } else if let Ok(int_val) = value.try_int(vm) - && let Some(v) = int_val.as_bigint().to_u8() - { - SimpleStorageValue::Byte(v) - } else { - SimpleStorageValue::Zero - } - } - "u" => { - // c_wchar - platform-dependent size (2 on Windows, 4 on Unix) - if let Some(s) = value.downcast_ref::() { - let mut cps = s.as_wtf8().code_points(); - if let (Some(c), None) = (cps.next(), cps.next()) { - SimpleStorageValue::Wchar(c.to_u32()) - } else { - SimpleStorageValue::Zero + } else if let Some(bytes) = value.downcast_ref::() { + match &*bytes.borrow_buf() { + [byte] => *byte, + _ => return Err(vm.new_type_error("one character bytearray expected")), } } else { - SimpleStorageValue::Zero - } - } - "b" => { - // c_byte - signed char (1 byte) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } - } - "B" => { - // c_ubyte - unsigned char (1 byte) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } - } - "h" => { - // c_short (2 bytes) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } - } - "H" => { - // c_ushort (2 bytes) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } - } - "i" => { - // c_int (4 bytes) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } - } - "I" => { - // c_uint (4 bytes) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } - } - "l" => { - // c_long (platform dependent) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } - } - "L" => { - // c_ulong (platform dependent) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } + value + .downcast_ref::() + .and_then(|integer| integer.as_bigint().to_u8()) + .ok_or_else(|| { + vm.new_type_error("one character bytes, bytearray or integer expected") + })? + }; + SimpleStorageValue::Byte(byte) } - "q" => { - // c_longlong (8 bytes) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) - } else { - SimpleStorageValue::Zero - } + "u" => { + let text = value + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("unicode string expected"))?; + let mut chars = text.as_wtf8().code_points(); + let character = chars + .next() + .filter(|_| chars.next().is_none()) + .ok_or_else(|| vm.new_type_error("one character unicode string expected"))?; + if rustpython_host_env::ctypes::WCHAR_SIZE == 2 && character.to_u32() > 0xffff { + return Err(vm.new_type_error("a single UTF-16 code unit is required")); + } + SimpleStorageValue::Wchar(character.to_u32()) + } + "f" | "d" | "g" => SimpleStorageValue::Float( + ArgIntoFloat::try_from_object(vm, value.to_owned())?.into_float(), + ), + "?" | "v" => SimpleStorageValue::Bool(value.to_owned().try_to_bool(vm)?), + "O" => { + keep = (!vm.is_none(value)).then(|| value.to_owned()); + SimpleStorageValue::ObjectId(value.get_id()) } - "Q" => { - // c_ulonglong (8 bytes) - if let Ok(int_val) = value.try_index(vm) { - SimpleStorageValue::Signed(bigint_to_i128_wrapping(int_val.as_bigint())) + #[cfg(windows)] + "X" => { + let units = if vm.is_none(value) { + None } else { - SimpleStorageValue::Zero - } - } - "f" => { - // c_float (4 bytes) - also accepts int - if let Ok(float_val) = value.try_float(vm) { - SimpleStorageValue::Float(float_val.to_f64()) - } else if let Ok(int_val) = value.try_int(vm) - && let Some(v) = int_val.as_bigint().to_f64() + let text = value.downcast_ref::().ok_or_else(|| { + vm.new_type_error(format!( + "unicode string expected instead of {} instance", + value.class().name() + )) + })?; + let units: Vec = text.as_wtf8().encode_wide().collect(); + if u32::try_from(units.len()).is_err() { + return Err(vm.new_value_error("String too long for BSTR")); + } + Some(units) + }; + let bstr = rustpython_host_env::ctypes::BStr::new(units.as_deref()) + .ok_or_else(|| vm.new_memory_error("could not allocate BSTR"))?; + return Ok((CDataBytes::BStr(bstr), None, None)); + } + "z" | "Z" | "P" => { + let address = if vm.is_none(value) { + 0 + } else if type_code == "z" + && let Some(bytes) = value.downcast_ref::() { - SimpleStorageValue::Float(v) - } else { - SimpleStorageValue::Zero - } - } - "d" => { - // c_double (8 bytes) - also accepts int - if let Ok(float_val) = value.try_float(vm) { - SimpleStorageValue::Float(float_val.to_f64()) - } else if let Ok(int_val) = value.try_int(vm) - && let Some(v) = int_val.as_bigint().to_f64() + let (holder, address) = super::base::ensure_z_null_terminated(bytes, vm); + keep = Some(value.to_owned()); + hidden = Some(holder); + address + } else if type_code == "Z" + && let Some(text) = value.downcast_ref::() { - SimpleStorageValue::Float(v) + let (holder, address) = super::base::str_to_wchar_bytes(text.as_wtf8(), vm); + keep = Some(holder); + address + } else if let Some(integer) = value.downcast_ref::() { + bigint_to_i128_wrapping(integer.as_bigint()) as usize } else { - SimpleStorageValue::Zero - } - } - "g" => { - // long double - platform dependent size - // Store as f64, zero-pad to platform long double size - // Note: This may lose precision on platforms where long double > 64 bits - let value = if let Ok(float_val) = value.try_float(vm) { - float_val.to_f64() - } else if let Ok(int_val) = value.try_int(vm) { - int_val.as_bigint().to_f64().unwrap_or(0.0) - } else { - 0.0 + return Err(vm.new_type_error("integer address expected")); }; - SimpleStorageValue::Float(value) + SimpleStorageValue::Pointer(address) } - "?" => { - // c_bool (1 byte) - if let Ok(b) = value.to_owned().try_to_bool(vm) { - SimpleStorageValue::Bool(b) - } else { - SimpleStorageValue::Zero - } - } - "v" => { - // VARIANT_BOOL: True = 0xFFFF (-1 as i16), False = 0x0000 - if let Ok(b) = value.to_owned().try_to_bool(vm) { - SimpleStorageValue::Bool(b) - } else { - SimpleStorageValue::Zero - } - } - "P" => { - // c_void_p - pointer type (platform pointer size) - if let Ok(int_val) = value.try_index(vm) { - let v = bigint_to_i128_wrapping(int_val.as_bigint()) as usize; - SimpleStorageValue::Pointer(v) - } else { - SimpleStorageValue::Zero - } - } - "z" => { - // c_char_p - pointer to char (stores pointer value from int) - // PyBytes case is handled in slot_new/set_value with make_z_buffer() - if let Ok(int_val) = value.try_index(vm) { - let v = bigint_to_i128_wrapping(int_val.as_bigint()) as usize; - SimpleStorageValue::Pointer(v) + _ => { + let index; + let integer = if let Some(integer) = value.downcast_ref_if_exact::(vm) { + integer } else { - SimpleStorageValue::Zero - } + index = value.try_index(vm)?; + &index + }; + SimpleStorageValue::Signed(bigint_to_i128_wrapping(integer.as_bigint())) } - "Z" => { - // c_wchar_p - pointer to wchar_t (stores pointer value from int) - // PyStr case is handled in slot_new/set_value with make_wchar_buffer() - if let Ok(int_val) = value.try_index(vm) { - let v = bigint_to_i128_wrapping(int_val.as_bigint()) as usize; - SimpleStorageValue::Pointer(v) - } else { - SimpleStorageValue::Zero + }; + let bytes = match (type_code, storage) { + ( + "b" | "B" | "h" | "H" | "i" | "I" | "l" | "L" | "q" | "Q", + SimpleStorageValue::Signed(value), + ) => { + let size = simple_type_size(type_code).expect("integer ctypes size"); + let mut bytes = (value as u64).to_le_bytes(); + if super::base::is_big_endian(swapped) { + bytes[..size].reverse(); } + CDataBytes::Integer { bytes, size } } - "O" => { - // py_object - store object id as non-zero marker - // The actual object is stored in _objects - // Use object's id as a non-zero placeholder (indicates non-NULL) - SimpleStorageValue::ObjectId(value.get_id()) - } - _ => SimpleStorageValue::Zero, + (_, storage) => simple_storage_value_to_bytes_endian(type_code, storage, swapped).into(), }; - simple_storage_value_to_bytes_endian(_type_, storage_value, swapped) + Ok((bytes, keep, hidden)) } /// Check if value is a c_char array or pointer(c_char) @@ -982,64 +720,13 @@ fn is_cwchar_array_or_pointer(value: &PyObject, vm: &VirtualMachine) -> PyResult } impl Constructor for PyCSimple { - type Args = (OptionalArg,); - - fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let args: Self::Args = args.bind_for(vm, Self::NAME)?; - let _type_ = cls - .type_code(vm) - .ok_or_else(|| vm.new_type_error("abstract class"))?; - // Save the initial argument for c_char_p/c_wchar_p _objects - let init_arg = args.0.into_option(); - - // Handle z/Z types with PyBytes/PyStr separately to avoid memory leak - if let Some(ref v) = init_arg { - if _type_ == "z" { - if let Some(bytes) = v.downcast_ref::() { - let (kept_alive, ptr) = super::base::ensure_z_null_terminated(bytes, vm); - let buffer = rustpython_host_env::ctypes::pointer_bytes(ptr); - let cdata = PyCData::from_bytes(buffer, Some(v.clone())); - *cdata.base.write() = Some(kept_alive); - return Self(cdata).into_ref_with_type(vm, cls).map(Into::into); - } - } else if _type_ == "Z" - && let Some(s) = v.downcast_ref::() - { - let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm); - let buffer = rustpython_host_env::ctypes::pointer_bytes(ptr); - let cdata = PyCData::from_bytes(buffer, Some(holder)); - return Self(cdata).into_ref_with_type(vm, cls).map(Into::into); - } - } - - let value = if let Some(ref v) = init_arg { - set_primitive(_type_.as_str(), v, vm)? - } else { - match _type_.as_str() { - "c" | "u" => PyObjectRef::from(vm.ctx.new_bytes(vec![0])), - "b" | "B" | "h" | "H" | "i" | "I" | "l" | "q" | "L" | "Q" => { - PyObjectRef::from(vm.ctx.new_int(0)) - } - "f" | "d" | "g" => PyObjectRef::from(vm.ctx.new_float(0.0)), - "?" => PyObjectRef::from(vm.ctx.new_bool(false)), - _ => vm.ctx.none(), // "z" | "Z" | "P" - } - }; - - // Check if this is a swapped endian type (presence of attribute indicates swapping) - let swapped = cls.as_object().get_attr("_swappedbytes_", vm).is_ok(); - - let buffer = value_to_bytes_endian(&_type_, &value, swapped, vm); - - // For c_char_p (type "z"), c_wchar_p (type "Z"), and py_object (type "O"), - // store the initial value in _objects - let objects = if (_type_ == "z" || _type_ == "Z" || _type_ == "O") && init_arg.is_some() { - init_arg - } else { - None - }; + type Args = FuncArgs; - Self(PyCData::from_bytes(buffer, objects)) + fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { + // Allocation ignores arguments; only __init__ converts the value. + // Do not let new_simple_type's _type_ fallback allocate abstract types. + cls.stg_info(vm)?; + new_simple_type(Either::B(&cls), vm)? .into_ref_with_type(vm, cls) .map(Into::into) } @@ -1050,7 +737,8 @@ impl Constructor for PyCSimple { } impl Initializer for PyCSimple { - type Args = (OptionalArg,); + // Simple_init accepts at most one positional value and ignores keywords. + type Args = (OptionalArg, KwArgs); fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { // If an argument is provided, update the value @@ -1069,11 +757,7 @@ impl Representable for PyCSimple { // Check if base is _SimpleCData (direct simple type like c_int, c_char) // vs subclass of simple type (like class X(c_int): pass) - let bases = cls.bases.read(); - let is_direct_simple = bases - .as_slice() - .iter() - .any(|base| base.name().to_string() == "_SimpleCData"); + let is_direct_simple = returns_scalar(cls); if is_direct_simple { // Direct SimpleCData: "typename(repr(value))" @@ -1104,13 +788,10 @@ impl Py { .downcast_ref() .ok_or_else(|| vm.new_type_error("cannot get value of instance"))?; - // Get _type_ from class let cls = zelf.class(); - let type_attr = cls - .as_object() - .get_attr("_type_", vm) - .map_err(|_| vm.new_type_error("no _type_ attribute"))?; - let type_code = type_attr.str(vm)?.to_string(); + let type_code = cls + .type_code(vm) + .ok_or_else(|| vm.new_type_error("abstract class"))?; // Special handling for c_char_p (z) and c_wchar_p (Z) // z_get, Z_get - dereference pointer to get string @@ -1139,18 +820,13 @@ impl Py { if type_code == "O" { let buffer = zelf.0.buffer.read(); let ptr = rustpython_host_env::ctypes::read_pointer_from_buffer(&buffer); - if ptr == 0 { - return Err(vm.new_value_error("PyObject is NULL")); - } - // Non-NULL: return stored object from _objects if available - if let Some(obj) = zelf.0.objects.read().as_ref() { - return Ok(obj.clone()); - } - return Err(vm.new_value_error("PyObject is NULL")); + let slot = buffer.as_ptr() as usize; + drop(buffer); + return zelf.0.object_at(ptr, slot, None, vm); } - // Check if this is a swapped endian type (presence of attribute indicates swapping) - let swapped = cls.as_object().get_attr("_swappedbytes_", vm).is_ok(); + // Storage metadata belongs to this exact type, unlike inherited attributes. + let swapped = is_swapped(cls); // Read value from buffer, swap bytes if needed let buffer = zelf.0.buffer.read(); @@ -1170,72 +846,43 @@ impl Py { #[pygetset(setter)] fn set_value(instance: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let zelf: PyRef = instance - .clone() .downcast() .map_err(|_| vm.new_type_error("cannot set value of instance"))?; - // Get _type_ from class let cls = zelf.class(); - let type_attr = cls - .as_object() - .get_attr("_type_", vm) - .map_err(|_| vm.new_type_error("no _type_ attribute"))?; - let type_code = type_attr.str(vm)?.to_string(); - - // Handle z/Z types with PyBytes/PyStr separately to avoid memory leak - if type_code == "z" { - if let Some(bytes) = value.downcast_ref::() { - let (kept_alive, ptr) = super::base::ensure_z_null_terminated(bytes, vm); - *zelf.0.buffer.write() = - alloc::borrow::Cow::Owned(rustpython_host_env::ctypes::pointer_bytes(ptr)); - *zelf.0.objects.write() = Some(value); - *zelf.0.base.write() = Some(kept_alive); - return Ok(()); - } - } else if type_code == "Z" - && let Some(s) = value.downcast_ref::() - { - let (holder, ptr) = super::base::str_to_wchar_bytes(s.as_wtf8(), vm); - *zelf.0.buffer.write() = - alloc::borrow::Cow::Owned(rustpython_host_env::ctypes::pointer_bytes(ptr)); - *zelf.0.objects.write() = Some(holder); - return Ok(()); - } + let code = cls + .stg_info(vm)? + .scalar_code + .ok_or_else(|| vm.new_type_error("abstract class"))?; + let type_code = code.to_string(); - let content = set_primitive(&type_code, &value, vm)?; + // Snapshot storage metadata before invoking any conversion callbacks. + let swapped = is_swapped(cls); + let (mut buffer_bytes, keep, hidden) = assignment_value(&type_code, &value, swapped, vm)?; - // Check if this is a swapped endian type (presence of attribute indicates swapping) - let swapped = instance - .class() - .as_object() - .get_attr("_swappedbytes_", vm) - .is_ok(); + let write = if type_code == "O" { + let size = zelf.0.buffer.read().len(); + zelf.0.register_pyobject_view(0, 0, size, vm)? + } else { + super::base::CDataWrite::default() + }; - // Update buffer when value changes - let buffer_bytes = value_to_bytes_endian(&type_code, &content, swapped, vm); + write.publish(vm)?; - // If the buffer is borrowed (from shared memory), write in-place - // Otherwise replace with new owned buffer - let mut buffer = zelf.0.buffer.write(); - write_simple_storage_buffer(&mut buffer, &buffer_bytes); + // Write in place for borrowed storage and preserve any resized tail. + zelf.0.write_value_at_offset(0, &mut buffer_bytes); - // For c_char_p (type "z"), c_wchar_p (type "Z"), and py_object (type "O"), - // keep the reference in _objects - if type_code == "z" || type_code == "Z" || type_code == "O" { - *zelf.0.objects.write() = Some(value); + // Raw z/Z addresses and None do not replace the old owner: the + // address may still point into its buffer (CPython KeepRef(None)). + if let Some(keep) = keep { + zelf.0.keep_value(keep, hidden, vm)?; } Ok(()) } #[pyclassmethod] fn repeat(cls: PyTypeRef, n: isize, vm: &VirtualMachine) -> PyResult { - use super::array::array_type_from_ctype; - - if n < 0 { - return Err(vm.new_value_error(format!("Array length must be >= 0, not {n}"))); - } - // Use cached array type creation - array_type_from_ctype(cls.into(), n as usize, vm) + super::array::repeat_type(cls.as_object(), n, vm) } // Simple_from_outparm - convert output parameter back to Python value @@ -1248,15 +895,7 @@ impl Py { ) -> PyResult { // _ctypes_simple_instance: returns true if NOT a direct subclass of Simple_Type // i.e., c_int (direct) -> false, MyInt(c_int) (subclass) -> true - let is_subclass_of_simple = { - let cls = zelf.class(); - let bases = cls.bases.read(); - // If base is NOT _SimpleCData, then it's a subclass of a subclass - !bases - .as_slice() - .iter() - .any(|base| base.name().to_string() == "_SimpleCData") - }; + let is_subclass_of_simple = !returns_scalar(zelf.class()); if is_subclass_of_simple { // Subclass of simple type (e.g., MyInt(c_int)): return self @@ -1288,14 +927,7 @@ impl AsBuffer for PyCSimple { .map_or(Cow::Borrowed("B"), Cow::Owned); let itemsize = stg_info.size; // Simple types are scalars with ndim=0, shape=() - let desc = BufferDescriptor { - offset: 0, - len: itemsize, - readonly: false, - itemsize, - format, - dim_desc: vec![], - }; + let desc = BufferDescriptor::from_dim_desc(itemsize, 0, false, itemsize, format, vec![]); let buf = PyBuffer::new(zelf.to_owned().into(), desc, &CDATA_BUFFER_METHODS); Ok(buf) } diff --git a/crates/vm/src/stdlib/_ctypes/structure.rs b/crates/vm/src/stdlib/_ctypes/structure.rs index bc4b3d54c8f..a4743a7d34f 100644 --- a/crates/vm/src/stdlib/_ctypes/structure.rs +++ b/crates/vm/src/stdlib/_ctypes/structure.rs @@ -2,13 +2,12 @@ use super::base::{CDATA_BUFFER_METHODS, PyCData, PyCField, StgInfo, StgInfoFlags use crate::builtins::{PyList, PyStr, PyTuple, PyType, PyTypeRef, PyUtf8Str}; use crate::convert::ToPyObject; use crate::function::{ArgStrictInt, FuncArgs, OptionalArg, PySetterValue}; -use crate::protocol::{BufferDescriptor, PyBuffer, PyNumberMethods}; +use crate::protocol::{BufferDescriptor, PyBuffer, PySequenceMethods}; use crate::stdlib::_warnings; -use crate::types::{AsBuffer, AsNumber, Constructor, Initializer, SetAttr}; +use crate::types::{AsBuffer, AsSequence, Constructor, Initializer, SetAttr}; use crate::{AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine}; use alloc::borrow::Cow; use core::fmt::Debug; -use num_traits::ToPrimitive; /// Calculate Structure type size from _fields_ (sum of field sizes) pub(super) fn calculate_struct_size(cls: &Py, vm: &VirtualMachine) -> PyResult { @@ -52,7 +51,7 @@ impl Constructor for PyCStructType { // 4. Initialize StgInfo for the new type (initialized=false, to be set in init) let stg_info = StgInfo::default(); - let _ = new_type.init_type_data(stg_info); + let _ = new_type.init_traced_type_data(stg_info); // Note: _fields_ processing moved to Initializer::init() Ok(new_class) @@ -85,7 +84,10 @@ impl Initializer for PyCStructType { // Process _fields_ if defined directly on this class (not inherited) if let Some(fields_attr) = new_type.get_direct_attr(vm.ctx.intern_str("_fields_")) { - Self::process_fields(&new_type, &fields_attr, vm)?; + // Let the metaclass transform field types, as for later assignment. + new_type + .as_object() + .set_attr(vm.ctx.intern_str("_fields_"), fields_attr, vm)?; } else { // No _fields_ defined - try to copy from base class (PyCStgInfo_clone) let (has_base_info, base_clone) = { @@ -129,40 +131,25 @@ impl Initializer for PyCStructType { } } -#[pyclass(flags(BASETYPE), with(AsNumber, Constructor, Initializer, SetAttr))] +#[pyclass(flags(BASETYPE), with(AsSequence, Constructor, Initializer, SetAttr))] impl PyCStructType { - #[pygetset(name = "__pointer_type__")] - fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __pointer_type__(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { super::base::pointer_type_get(&zelf, vm) } - #[pygetset(name = "__pointer_type__", setter)] - fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___pointer_type__( + zelf: PyTypeRef, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { super::base::pointer_type_set(&zelf, value, vm) } #[pymethod] - fn from_param(zelf: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // zelf is the structure type class that from_param was called on - let cls = zelf - .downcast::() - .map_err(|_| vm.new_type_error("from_param: expected a type"))?; - - // 1. If already an instance of the requested type, return it - if value.is_instance(cls.as_object(), vm)? { - return Ok(value); - } - - // 2. Check for _as_parameter_ attribute - if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); - } - - Err(vm.new_type_error(format!( - "expected {} instance instead of {}", - cls.name(), - value.class().name() - ))) + fn from_param(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + PyCData::from_param(zelf, value, vm) } // CDataType methods - delegated to PyCData implementations @@ -372,7 +359,7 @@ impl PyCStructType { has_bitfield = true; } // Collect the call layout for this field - field_layouts.push(super::base::type_layout(type_obj, &field_stg, vm)); + field_layouts.push(super::base::type_layout(&field_stg)); } // Mark field type as finalized (using type as field finalizes it) @@ -383,7 +370,7 @@ impl PyCStructType { // Create StgInfo with FINAL flag if it doesn't exist let mut stg_info = StgInfo::new(size, field_align); stg_info.flags |= StgInfoFlags::DICTFLAG_FINAL; - let _ = type_obj.init_type_data(stg_info); + let _ = type_obj.init_traced_type_data(stg_info); } } @@ -428,11 +415,8 @@ impl PyCStructType { // Check for bitfield size (optional 3rd element in tuple) let (c_field, field_advances_offset) = if field_tuple.as_slice().len() > 2 { let bit_size_obj = field_tuple.as_slice().get(2).expect("len checked"); - let bit_size = bit_size_obj - .try_int(vm)? - .as_bigint() - .to_u16() - .ok_or_else(|| vm.new_value_error("number of bits invalid for bit field"))?; + let bit_size = + PyCField::checked_bitfield_size(&name, &field_type_ref, bit_size_obj, vm)?; has_bitfield = true; let type_bits = (size * 8) as u16; @@ -467,6 +451,12 @@ impl PyCStructType { bitfield_bit_offset += bit_size; } + let bit_offset = if big_endian { + type_bits - bit_offset - bit_size + } else { + bit_offset + }; + // For packed bitfields that share offset, use the same offset as previous let field_offset = if !advances { offset - size // Reuse the previous field's offset @@ -565,35 +555,11 @@ impl PyCStructType { Ok(()) } - - fn __mul__(cls: PyTypeRef, n: isize, vm: &VirtualMachine) -> PyResult { - use super::array::array_type_from_ctype; - - if n < 0 { - return Err(vm.new_value_error(format!("Array length must be >= 0, not {n}"))); - } - // Use cached array type creation - array_type_from_ctype(cls.into(), n as usize, vm) - } } -impl AsNumber for PyCStructType { - fn as_number() -> &'static PyNumberMethods { - static AS_NUMBER: PyNumberMethods = PyNumberMethods { - multiply: Some(|a, b, vm| { - let cls = a - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("expected type"))?; - let n = b - .try_index(vm)? - .as_bigint() - .to_isize() - .ok_or_else(|| vm.new_overflow_error("array size too large"))?; - PyCStructType::__mul__(cls.to_owned(), n, vm) - }), - ..PyNumberMethods::NOT_IMPLEMENTED - }; - &AS_NUMBER +impl AsSequence for PyCStructType { + fn as_sequence() -> &'static PySequenceMethods { + &super::array::CTYPE_SEQUENCE_METHODS } } @@ -666,11 +632,22 @@ impl SetAttr for PyCStructType { module = "_ctypes", name = "Structure", base = PyCData, - metaclass = "PyCStructType" + metaclass = "PyCStructType", + traverse = "manual" )] #[repr(transparent)] pub(crate) struct PyCStructure(pub PyCData); +// SAFETY: this transparent wrapper owns exactly the references in its base. +unsafe impl crate::object::Traverse for PyCStructure { + fn traverse(&self, tracer: &mut crate::object::TraverseFn<'_>) { + self.0.traverse(tracer); + } + fn clear(&mut self, out: &mut Vec) { + self.0.clear(out); + } +} + impl Debug for PyCStructure { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCStructure") @@ -823,14 +800,14 @@ impl AsBuffer for PyCStructure { // Structure: ndim=0, shape=(), itemsize=struct_size let buf = PyBuffer::new( zelf.to_owned().into(), - BufferDescriptor { - offset: 0, - len: buffer_len, - readonly: false, - itemsize: buffer_len, - format: Cow::Owned(format), - dim_desc: vec![], // ndim=0 means empty dim_desc - }, + BufferDescriptor::from_dim_desc( + buffer_len, + 0, + false, + buffer_len, + Cow::Owned(format), + vec![], // ndim=0 means empty dim_desc + ), &CDATA_BUFFER_METHODS, ); Ok(buf) diff --git a/crates/vm/src/stdlib/_ctypes/union.rs b/crates/vm/src/stdlib/_ctypes/union.rs index 2322d652479..ddd24e8e483 100644 --- a/crates/vm/src/stdlib/_ctypes/union.rs +++ b/crates/vm/src/stdlib/_ctypes/union.rs @@ -3,12 +3,11 @@ use super::{PyCData, PyCField, StgInfo}; use crate::builtins::{PyList, PyStr, PyTuple, PyType, PyTypeRef, PyUtf8Str}; use crate::convert::ToPyObject; use crate::function::{ArgBytesLike, ArgStrictInt, FuncArgs, OptionalArg, PySetterValue}; -use crate::protocol::{BufferDescriptor, PyBuffer}; +use crate::protocol::{BufferDescriptor, PyBuffer, PySequenceMethods}; use crate::stdlib::_warnings; -use crate::types::{AsBuffer, Constructor, Initializer, SetAttr}; +use crate::types::{AsBuffer, AsSequence, Constructor, Initializer, SetAttr}; use crate::{AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine}; use alloc::borrow::Cow; -use num_traits::ToPrimitive; /// Calculate Union type size from _fields_ (max field size) pub(super) fn calculate_union_size(cls: &Py, vm: &VirtualMachine) -> PyResult { @@ -53,7 +52,7 @@ impl Constructor for PyCUnionType { // 4. Initialize StgInfo for the new type (initialized=false, to be set in init) let stg_info = StgInfo::default(); - let _ = new_type.init_type_data(stg_info); + let _ = new_type.init_traced_type_data(stg_info); // Note: _fields_ processing moved to Initializer::init() Ok(new_class) @@ -258,7 +257,7 @@ impl PyCUnionType { has_bitfield = true; } // Collect the call layout for this field - field_layouts.push(super::base::type_layout(type_obj, &field_stg, vm)); + field_layouts.push(super::base::type_layout(&field_stg)); } // Mark field type as finalized (using type as field finalizes it) @@ -269,7 +268,7 @@ impl PyCUnionType { // Create StgInfo with FINAL flag if it doesn't exist let mut stg_info = StgInfo::new(size, field_align); stg_info.flags |= StgInfoFlags::DICTFLAG_FINAL; - let _ = type_obj.init_type_data(stg_info); + let _ = type_obj.init_traced_type_data(stg_info); } } @@ -282,11 +281,8 @@ impl PyCUnionType { // For unions, each field starts fresh (CPython: _layout.py) let c_field = if field_tuple.as_slice().len() > 2 { let bit_size_obj = field_tuple.as_slice().get(2).expect("len checked"); - let bit_size = bit_size_obj - .try_int(vm)? - .as_bigint() - .to_u16() - .ok_or_else(|| vm.new_value_error("number of bits invalid for bit field"))?; + let bit_size = + PyCField::checked_bitfield_size(&name, &field_type_ref, bit_size_obj, vm)?; has_bitfield = true; // Union fields all start at offset 0, so bit_offset = 0 @@ -356,61 +352,25 @@ impl PyCUnionType { } } -#[pyclass(flags(BASETYPE), with(Constructor, Initializer, SetAttr))] +#[pyclass(flags(BASETYPE), with(AsSequence, Constructor, Initializer, SetAttr))] impl PyCUnionType { - #[pygetset(name = "__pointer_type__")] - fn pointer_type(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __pointer_type__(zelf: PyTypeRef, vm: &VirtualMachine) -> PyResult { super::base::pointer_type_get(&zelf, vm) } - #[pygetset(name = "__pointer_type__", setter)] - fn set_pointer_type(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + #[pygetset(setter)] + fn set___pointer_type__( + zelf: PyTypeRef, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { super::base::pointer_type_set(&zelf, value, vm) } #[pymethod] - fn from_param(zelf: PyObjectRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // zelf is the union type class that from_param was called on - let cls = zelf - .downcast::() - .map_err(|_| vm.new_type_error("from_param: expected a type"))?; - - // 1. If already an instance of the requested type, return it - if value.is_instance(cls.as_object(), vm)? { - return Ok(value); - } - - // 2. Check for CArgObject (PyCArg_CheckExact) - if let Some(carg) = value.downcast_ref::() { - // Check against proto (for pointer types) - if let Some(stg_info) = cls.stg_info_opt() - && let Some(ref proto) = stg_info.proto - && carg.obj.is_instance(proto.as_object(), vm)? - { - return Ok(value); - } - // Fallback: check if the wrapped object is an instance of the requested type - if carg.obj.is_instance(cls.as_object(), vm)? { - return Ok(value); // Return the CArgObject as-is - } - // CArgObject but wrong type - return Err(vm.new_type_error(format!( - "expected {} instance instead of pointer to {}", - cls.name(), - carg.obj.class().name() - ))); - } - - // 3. Check for _as_parameter_ attribute - if let Ok(as_parameter) = value.get_attr("_as_parameter_", vm) { - return Self::from_param(cls.as_object().to_owned(), as_parameter, vm); - } - - Err(vm.new_type_error(format!( - "expected {} instance instead of {}", - cls.name(), - value.class().name() - ))) + fn from_param(zelf: PyTypeRef, value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + PyCData::from_param(zelf, value, vm) } // CDataType methods - delegated to PyCData implementations @@ -534,10 +494,26 @@ impl SetAttr for PyCUnionType { } } -#[pyclass(module = "_ctypes", name = "Union", base = PyCData, metaclass = "PyCUnionType")] +#[pyclass( + module = "_ctypes", + name = "Union", + base = PyCData, + metaclass = "PyCUnionType", + traverse = "manual" +)] #[repr(transparent)] pub(crate) struct PyCUnion(pub PyCData); +// SAFETY: this transparent wrapper owns exactly the references in its base. +unsafe impl crate::object::Traverse for PyCUnion { + fn traverse(&self, tracer: &mut crate::object::TraverseFn<'_>) { + self.0.traverse(tracer); + } + fn clear(&mut self, out: &mut Vec) { + self.0.clear(out); + } +} + impl core::fmt::Debug for PyCUnion { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("PyCUnion") @@ -684,16 +660,22 @@ impl AsBuffer for PyCUnion { // Union: ndim=0, shape=(), itemsize=union_size let buf = PyBuffer::new( zelf.to_owned().into(), - BufferDescriptor { - offset: 0, - len: buffer_len, - readonly: false, - itemsize: buffer_len, - format: Cow::Owned(format), - dim_desc: vec![], // ndim=0 means empty dim_desc - }, + BufferDescriptor::from_dim_desc( + buffer_len, + 0, + false, + buffer_len, + Cow::Owned(format), + vec![], // ndim=0 means empty dim_desc + ), &CDATA_BUFFER_METHODS, ); Ok(buf) } } + +impl AsSequence for PyCUnionType { + fn as_sequence() -> &'static PySequenceMethods { + &super::array::CTYPE_SEQUENCE_METHODS + } +} diff --git a/crates/vm/src/stdlib/_functools.rs b/crates/vm/src/stdlib/_functools.rs index 4c9725289f7..1e7f79c02eb 100644 --- a/crates/vm/src/stdlib/_functools.rs +++ b/crates/vm/src/stdlib/_functools.rs @@ -5,11 +5,13 @@ mod _functools { use crate::{ Context, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, builtins::{ - PyBoundMethod, PyDict, PyDictRef, PyGenericAlias, PyTuple, PyType, PyTypeRef, object, + PyBoundMethod, PyDict, PyDictRef, PyGenericAlias, PyStr, PyTuple, PyType, PyTypeRef, + object, }, common::{hash::PyHash, lock::PyRwLock}, function::{ - Either, FuncArgs, KwArgs, OptionalOption, PosArgs, PyComparisonValue, PySetterValue, + ArgIntoBool, Callee, Either, FuncArgs, KwArgs, OptionalOption, PosArgs, + PyComparisonValue, PySetterValue, }, object::{AsObject, PyAtomicRef, TraverseFn}, protocol::PyIter, @@ -33,7 +35,7 @@ mod _functools { function: PyObjectRef, #[pyarg(positional)] iterable: PyIter, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "functools._initial_missing")] initial: OptionalOption, } @@ -125,8 +127,7 @@ mod _functools { PySetterValue::Assign(v) => Some(v), PySetterValue::Delete => None, }; - let old = core::mem::replace(&mut *self.object.write(), value); - drop(old); + let _old = core::mem::replace(&mut *self.object.write(), value); } #[pygetset] @@ -178,16 +179,19 @@ mod _functools { } } - // Placeholder singleton for partial arguments - // The singleton is stored as _instance on the type class + // Keep identity in interpreter state, not on the shared static type. #[pyattr] #[allow(non_snake_case)] fn Placeholder(vm: &VirtualMachine) -> PyObjectRef { + let cell = &vm.state.functools_placeholder; + if let Some(placeholder) = cell.get() { + return placeholder.clone(); + } + // Allocate outside the cell initializer: allocation may trigger GC. + // Another thread can publish first; always return the published winner. let placeholder = PyPlaceholderType.into_pyobject(vm); - // Store the singleton on the type class for slot_new to find - let typ = placeholder.class(); - typ.set_attr(vm.ctx.intern_str("_instance"), placeholder.clone()); - placeholder + let _ = cell.set(placeholder); + cell.get().expect("Placeholder was initialized").clone() } #[pyattr] @@ -198,16 +202,11 @@ mod _functools { impl Constructor for PyPlaceholderType { type Args = FuncArgs; - fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn slot_new(_cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { if !args.args.is_empty() || !args.kwargs.is_empty() { return Err(vm.new_type_error("_PlaceholderType takes no arguments")); } - // Return the singleton stored on the type class - if let Some(instance) = cls.get_attr(vm.ctx.intern_str("_instance")) { - return Ok(instance); - } - // Fallback: create a new instance (shouldn't happen for base type after module init) - Ok(Self.into_pyobject(vm)) + Ok(Placeholder(vm)) } fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { @@ -237,7 +236,7 @@ mod _functools { } fn is_placeholder(obj: &PyObject) -> bool { - &*obj.class().name() == "_PlaceholderType" + obj.downcast_ref::().is_some() } fn count_placeholders(args: &[PyObjectRef]) -> usize { @@ -277,6 +276,106 @@ mod _functools { flags(BASETYPE, HAS_DICT, HAS_WEAKREF) )] impl PyPartial { + #[pyslot] + fn vectorcall( + zelf: &PyObject, + args: Vec, + nargs: usize, + kwnames: Option<&[PyObjectRef]>, + vm: &VirtualMachine, + ) -> PyResult { + let zelf = zelf.downcast_ref::().unwrap(); + // Keep the call's state alive before keyword lookups can execute + // __hash__/__eq__ and replace it through __setstate__. + let func = zelf.func.load_owned(); + let stored_args = zelf.args.load_owned(); + let keywords = zelf.keywords.load_owned(); + let phcount = zelf.phcount.load(Ordering::Relaxed); + + // Check if we have enough args to fill placeholders + if nargs < phcount { + return Err(vm.new_type_error(format!( + "missing positional arguments in 'partial' call; expected at least {phcount}, got {nargs}" + ))); + } + + // Build combined args, replacing placeholders + let mut combined_args = Vec::with_capacity(stored_args.as_slice().len() + args.len()); + let mut new_args_iter = args[..nargs].iter(); + + for stored_arg in stored_args.as_slice() { + if is_placeholder(stored_arg) { + // Replace placeholder with next new arg + if let Some(new_arg) = new_args_iter.next() { + combined_args.push(new_arg.clone()); + } else { + // This shouldn't happen if phcount check passed + combined_args.push(stored_arg.clone()); + } + } else { + combined_args.push(stored_arg.clone()); + } + } + // Append remaining new args + combined_args.extend(new_args_iter.cloned()); + let combined_nargs = combined_args.len(); + + let kwnames = kwnames.unwrap_or_default(); + if func.vectorcall_func().is_none() { + // FuncArgs callables retain their existing keyword binding path. + // In particular, do not introduce vectorcall's hash callbacks + // when the wrapped callable does not support vectorcall. + let mut kwargs = KwArgs::default(); + for (key, value) in keywords.items_vec() { + let key = key + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("keywords must be strings"))?; + kwargs.insert(key.as_wtf8().to_owned(), value); + } + for (key, value) in kwnames.iter().zip(&args[nargs..]) { + let key = key + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("keywords must be strings"))?; + kwargs.insert(key.as_wtf8().to_owned(), value.clone()); + } + return func.call(FuncArgs::new(combined_args, kwargs), vm); + } + if keywords.is_empty() { + combined_args.extend_from_slice(&args[nargs..]); + return func.vectorcall(combined_args, combined_nargs, Some(kwnames), vm); + } + + // Like partial_vectorcall, copy stored keywords only when an incoming + // key replaces one. New keys remain a tail, preserving their identity + // and avoiding extra hash callbacks from an intermediate dictionary. + let mut merged_keywords = None; + let mut tail_names = Vec::new(); + let mut tail_values = Vec::new(); + for (key, value) in kwnames.iter().zip(&args[nargs..]) { + let hash = PyDict::hash_or_unhashable(&**key, vm)?; + if keywords.entries.contains(vm, &**key, hash)? { + let merged = merged_keywords.get_or_insert_with(|| keywords.copy()); + merged.inner_setitem(&**key, value.clone(), vm)?; + } else { + tail_names.push(key.clone()); + tail_values.push(value.clone()); + } + } + + let merged = merged_keywords.as_ref().unwrap_or(&keywords); + let mut combined_names = Vec::with_capacity(merged.__len__() + tail_names.len()); + for (key, value) in merged.items_vec() { + key.downcast_ref::() + .ok_or_else(|| vm.new_type_error("keywords must be strings"))?; + combined_names.push(key); + combined_args.push(value); + } + combined_names.extend(tail_names); + combined_args.extend(tail_values); + + func.vectorcall(combined_args, combined_nargs, Some(&combined_names), vm) + } + #[pygetset] fn __dict__(zelf: &Py, vm: &VirtualMachine) -> PyDictRef { zelf.as_object() @@ -300,9 +399,9 @@ mod _functools { let keywords = zelf.keywords.load_owned(); let partial_type = zelf.class(); - // Get __dict__ if it exists and is not empty + // Preserve the difference between an absent and an allocated empty dict. let dict_obj = match zelf.as_object().dict() { - Some(dict) if !dict.is_empty() => dict.into(), + Some(dict) => dict.into(), _ => vm.ctx.none(), }; @@ -320,94 +419,71 @@ mod _functools { #[pymethod] fn __setstate__(zelf: &Py, object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { - let state = object; - let state_tuple = state - .downcast::() - .map_err(|_| vm.new_type_error("argument to __setstate__ must be a tuple"))?; - - if state_tuple.as_slice().len() != 4 { - return Err(vm.new_type_error(format!( - "expected 4 items in state, got {}", - state_tuple.as_slice().len() - ))); - } - - let func = &state_tuple.as_slice()[0]; - let args = &state_tuple.as_slice()[1]; - let kwds = &state_tuple.as_slice()[2]; - let dict = &state_tuple.as_slice()[3]; - + let invalid_state = || vm.new_type_error("invalid partial state"); + let state = object.downcast::().map_err(|_| invalid_state())?; + let [func, args, keywords, dict] = state.as_slice() else { + return Err(invalid_state()); + }; if !func.is_callable() { - return Err(vm.new_type_error("invalid partial state")); - } - - // Validate that args is a tuple (or subclass) - if !args.fast_isinstance(vm.ctx.types.tuple_type) { - return Err(vm.new_type_error("invalid partial state")); + return Err(invalid_state()); } - // Always convert to base tuple, even if it's a subclass - let args_tuple = match args.clone().downcast::() { - Ok(tuple) if tuple.class().is(vm.ctx.types.tuple_type) => tuple, - _ => { - // It's a tuple subclass, convert to base tuple - let elements: Vec = args.try_to_value(vm)?; - vm.ctx.new_tuple(elements) - } + let args = args + .clone() + .downcast::() + .map_err(|_| invalid_state())?; + let keywords = if vm.is_none(keywords) { + None + } else { + Some( + keywords + .clone() + .downcast::() + .map_err(|_| invalid_state())?, + ) }; - - let keywords_dict = if kwds.is(&vm.ctx.none) { - vm.ctx.new_dict() + let dict = if vm.is_none(dict) { + None } else { - // Always convert to base dict, even if it's a subclass - let dict = kwds - .clone() - .downcast::() - .map_err(|_| vm.new_type_error("invalid partial state"))?; - if dict.class().is(vm.ctx.types.dict_type) { - // It's already a base dict - dict - } else { - // It's a dict subclass, convert to base dict - let new_dict = vm.ctx.new_dict(); - for (key, value) in dict { - new_dict.set_item(&*key, value, vm)?; - } - new_dict - } + Some( + dict.clone() + .downcast::() + .map_err(|_| invalid_state())?, + ) }; - // Validate no trailing placeholders - let args_slice = args_tuple.as_slice(); - if !args_slice.is_empty() && is_placeholder(args_slice.last().unwrap()) { + // Reject invalid state before tuple conversion can execute Python code + // or any of the partial's existing fields are replaced. + if args + .as_slice() + .last() + .is_some_and(|arg| is_placeholder(arg)) + { return Err(vm.new_type_error("trailing Placeholders are not allowed")); } - let phcount = count_placeholders(args_slice); + let phcount = count_placeholders(args.as_slice()); + let args = if args.class().is(vm.ctx.types.tuple_type) { + args + } else { + let elements: Vec = args.as_object().try_to_value(vm)?; + vm.ctx.new_tuple(elements) + }; + let keywords = match keywords { + None => vm.ctx.new_dict(), + Some(dict) if dict.class().is(vm.ctx.types.dict_type) => dict, + // Copy the stored entries, including their hashes, without invoking + // a dict subclass's protocol or rehashing its keys. + Some(dict) => dict.copy().into_ref(&vm.ctx), + }; zelf.func.store(func.clone()); - zelf.args.store(args_tuple); - zelf.keywords.store(keywords_dict); + zelf.args.store(args); + zelf.keywords.store(keywords); zelf.phcount.store(phcount, Ordering::Relaxed); - - // Update __dict__ if provided - let Some(instance_dict) = zelf.as_object().dict() else { - return Ok(()); - }; - - if dict.is(&vm.ctx.none) { - // If dict is None, clear the instance dict - instance_dict.clear(); - return Ok(()); - } - - let dict_obj = dict - .clone() - .downcast::() - .map_err(|_| vm.new_type_error("invalid partial state"))?; - - // Clear existing dict and update with new values - instance_dict.clear(); - for (key, value) in dict_obj { - instance_dict.set_item(&*key, value, vm)?; + // The supplied instance dictionary is installed by identity. Clearing + // and updating the old dictionary would mutate external references, + // lose an absent dictionary, and erase a state dictionary aliased to it. + if let Some(instance_dict) = zelf.as_object().instance_dict() { + instance_dict.set(dict); } Ok(()) @@ -437,87 +513,86 @@ mod _functools { type Args = PartialSig; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let zelf = Self::py_new_funcargs(args, vm)?; - zelf.into_ref_with_type(vm, cls).map(Into::into) + let args = args.bind_for(vm, Callee::of::(vm))?; + let payload = Self::py_new(&cls, args, vm)?; + // An absent instance dictionary permits nested partial flattening; + // allocating even an empty dictionary changes that behavior. + payload + .into_ref_with_type_lazy_dict(vm, cls) + .map(Into::into) } - fn py_new( - _cls: &crate::Py, - _args: Self::Args, - vm: &VirtualMachine, - ) -> PyResult { - let Self::Args { + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + let PartialSig { func, args, keywords, - } = _args; - let _ = (func, args, keywords); - Err(vm.new_type_error("use slot_new")) - } - } - - impl PyPartial { - fn py_new_funcargs(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let (func, args_slice) = args - .args - .split_first() - .ok_or_else(|| vm.new_type_error("partial expected at least 1 argument, got 0"))?; + } = args; + let args_slice = args.as_ref(); if !func.is_callable() { return Err(vm.new_type_error("the first argument must be callable")); } - // Check for placeholders in kwargs - for (key, value) in &args.kwargs { + // Check the arguments supplied to this constructor before flattening: + // a trailing placeholder is invalid even if the inner partial would + // supply a later non-placeholder argument. + if args_slice.last().is_some_and(|arg| is_placeholder(arg)) { + return Err(vm.new_type_error("trailing Placeholders are not allowed")); + } + for value in keywords.values() { if is_placeholder(value) { - return Err(vm.new_type_error(format!( - "Placeholder cannot be passed as a keyword argument to partial(). \ - Did you mean partial(..., {key}=Placeholder, ...)(value)?" - ))); + return Err( + vm.new_type_error("Placeholder cannot be passed as a keyword argument") + ); } } // Handle nested partial objects - let (final_func, final_args, final_keywords) = - if let Some(partial) = func.downcast_ref::() { - let stored_args_obj = partial.args.load_owned(); - let stored_func = partial.func.load_owned(); - let stored_keywords = partial.keywords.load_owned(); - let stored_args = stored_args_obj.as_slice(); - - // Merge placeholders: replace placeholders in stored_args with new args - let mut merged_args = Vec::with_capacity(stored_args.len() + args_slice.len()); - let mut new_args_iter = args_slice.iter(); - - for stored_arg in stored_args { - if is_placeholder(stored_arg) { - // Replace placeholder with next new arg, or keep placeholder - if let Some(new_arg) = new_args_iter.next() { - merged_args.push(new_arg.clone()); - } else { - merged_args.push(stored_arg.clone()); - } + let (final_func, final_args, final_keywords) = if let Some(partial) = func + .downcast_ref::() + .filter(|_| !func.has_instance_dict()) + { + let stored_args_obj = partial.args.load_owned(); + let stored_func = partial.func.load_owned(); + let stored_keywords = partial.keywords.load_owned(); + let stored_args = stored_args_obj.as_slice(); + + // Merge placeholders: replace placeholders in stored_args with new args + let mut merged_args = Vec::with_capacity(stored_args.len() + args_slice.len()); + let mut new_args_iter = args_slice.iter(); + + for stored_arg in stored_args { + if is_placeholder(stored_arg) { + // Replace placeholder with next new arg, or keep placeholder + if let Some(new_arg) = new_args_iter.next() { + merged_args.push(new_arg.clone()); } else { merged_args.push(stored_arg.clone()); } + } else { + merged_args.push(stored_arg.clone()); } - // Append remaining new args - merged_args.extend(new_args_iter.cloned()); - - (stored_func, merged_args, stored_keywords) - } else { - (func.clone(), args_slice.to_vec(), vm.ctx.new_dict()) - }; - - // Trailing placeholders are not allowed - if !final_args.is_empty() && is_placeholder(final_args.last().unwrap()) { - return Err(vm.new_type_error("trailing Placeholders are not allowed")); - } + } + // Append remaining new args + merged_args.extend(new_args_iter.cloned()); + + // Each partial owns its keyword mapping. Sharing the inner + // mapping would make both construction and later mutation of + // the outer partial change the inner partial's calls. + ( + stored_func, + merged_args, + stored_keywords.copy().into_ref(&vm.ctx), + ) + } else { + (func, args_slice.to_vec(), vm.ctx.new_dict()) + }; let phcount = count_placeholders(&final_args); // Add new keywords - for (key, value) in args.kwargs { + for (key, value) in keywords { final_keywords.set_item(vm.ctx.intern_str(key), value, vm)?; } @@ -534,60 +609,14 @@ mod _functools { type Args = FuncArgs; fn call(zelf: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - // Clone and release lock before calling Python code to prevent deadlock - let func = zelf.func.load_owned(); - let stored_args = zelf.args.load_owned(); - let keywords = zelf.keywords.load_owned(); - let phcount = zelf.phcount.load(Ordering::Relaxed); - - // Check if we have enough args to fill placeholders - if phcount > 0 && args.args.len() < phcount { - return Err(vm.new_type_error(format!( - "missing positional arguments in 'partial' call; expected at least {}, got {}", - phcount, - args.args.len() - ))); - } - - // Build combined args, replacing placeholders - let mut combined_args = - Vec::with_capacity(stored_args.as_slice().len() + args.args.len()); - let mut new_args_iter = args.args.iter(); - - for stored_arg in stored_args.as_slice() { - if is_placeholder(stored_arg) { - // Replace placeholder with next new arg - if let Some(new_arg) = new_args_iter.next() { - combined_args.push(new_arg.clone()); - } else { - // This shouldn't happen if phcount check passed - combined_args.push(stored_arg.clone()); - } - } else { - combined_args.push(stored_arg.clone()); - } - } - // Append remaining new args - combined_args.extend(new_args_iter.cloned()); - - // Merge keywords from self.keywords and args.kwargs - let mut final_kwargs = crate::function::KwArgsMap::default(); - - // Add keywords from self.keywords - for (key, value) in &*keywords { - // `expect_str()` would panic on surrogate keys; keep them as WTF-8. - let key_str = key - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("keywords must be strings"))?; - final_kwargs.insert(key_str.as_wtf8().to_owned(), value); - } - - // Add keywords from args.kwargs (these override self.keywords) + let nargs = args.args.len(); + let mut values = args.args; + let mut kwnames = Vec::with_capacity(args.kwargs.len()); for (key, value) in args.kwargs { - final_kwargs.insert(key, value); + kwnames.push(vm.ctx.new_str(key).into()); + values.push(value); } - - func.call(FuncArgs::new(combined_args, KwArgs::new(final_kwargs)), vm) + Self::vectorcall(zelf.as_object(), values, nargs, Some(&kwnames), vm) } } @@ -719,11 +748,11 @@ mod _functools { hits: AtomicU64, misses: AtomicU64, /// Entries are kept in least-to-most-recently-used order: a hit moves its - /// entry to the end by removing and reinserting it, so the front of the dict - /// is always the next eviction candidate. Ordering is only maintained (at the - /// cost of the extra reinsert on a hit) when `maxsize` is `Some`. + /// entry to the end atomically, so the front of the dict is always the next + /// eviction candidate. Moving an entry preserves the original key and does + /// not invoke additional equality callbacks. /// Unbounded caches store results directly, without an LRU entry wrapper. - cache: PyRwLock, + cache: PyDictRef, /// Coarse-grained reentrant lock guarding the cache lookup/insert critical /// sections (not held while calling the user function), matching CPython. lock: RawRMutex, @@ -747,14 +776,15 @@ mod _functools { } #[derive(FromArgs)] + #[from_args(legacy, fname = "lru_cache")] pub(super) struct LruCacheWrapperArgs { - #[pyarg(positional)] - function: PyObjectRef, - #[pyarg(positional)] - maxsize: Option, - #[pyarg(positional)] - typed: bool, - #[pyarg(positional)] + #[pyarg(any)] + user_function: PyObjectRef, + #[pyarg(any)] + maxsize: PyObjectRef, + #[pyarg(any)] + typed: ArgIntoBool, + #[pyarg(any)] cache_info_type: PyObjectRef, } @@ -762,23 +792,33 @@ mod _functools { type Args = LruCacheWrapperArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - if !args.function.is_callable() { + if !args.user_function.is_callable() { return Err(vm.new_type_error("the first argument must be callable")); } - // Negative maxsize is normalized to 0 by `functools.lru_cache` before - // reaching here, but clamp defensively to match that behavior exactly. - let maxsize = args.maxsize.map(|n| n.max(0) as usize); + // The binder has already converted typed's truthiness. Only now + // invoke __index__, after the callable check, as in CPython's OOpO + // constructor. Keep maxsize raw until then to preserve that order. + let maxsize = if vm.is_none(&args.maxsize) { + None + } else { + let size = args + .maxsize + .try_index_opt(vm) + .ok_or_else(|| vm.new_type_error("maxsize should be integer or None"))?? + .try_to_primitive::(vm)?; + Some(size.max(0) as usize) + }; Ok(Self { - func: args.function, + func: args.user_function, maxsize, - typed: args.typed, + typed: args.typed.into_bool(), keyword_marker: vm .ctx .new_base_object(vm.ctx.types.object_type.to_owned(), None), cache_info_type: args.cache_info_type, hits: AtomicU64::new(0), misses: AtomicU64::new(0), - cache: PyRwLock::new(vm.ctx.new_dict()), + cache: vm.ctx.new_dict(), lock: RawRMutex::INIT, }) } @@ -787,6 +827,14 @@ mod _functools { impl PyLruCacheWrapper { /// Build the cache key for a call, following `functools._make_key`. fn make_key(&self, args: &FuncArgs, vm: &VirtualMachine) -> PyObjectRef { + // CPython deliberately uses scalar keys only for exact int and str. + // In particular, (1.0,) and (True,) must not alias the scalar key 1. + if !self.typed && args.kwargs.is_empty() && args.args.len() == 1 { + let arg = &args.args[0]; + if arg.class().is(vm.ctx.types.int_type) || arg.class().is(vm.ctx.types.str_type) { + return arg.clone(); + } + } let mut elements: Vec = args.args.clone(); if !args.kwargs.is_empty() { elements.push(self.keyword_marker.clone()); @@ -807,49 +855,18 @@ mod _functools { } vm.ctx.new_tuple(elements).into() } - - /// Refresh `key`'s recency by moving it to the end of `cache`'s insertion - /// order (removing then reinserting it). `hash` is the already-computed - /// hash of `key`, so `__hash__` is not called again. - fn touch_key( - key: &PyObject, - hash: PyHash, - value: &PyObject, - cache: &Py, - vm: &VirtualMachine, - ) -> PyResult<()> { - cache.del_item_known_hash(key, hash, vm)?; - cache.set_item_known_hash(key, hash, value.to_owned(), vm)?; - Ok(()) - } - - /// Evict the least-recently-used entry (the first item in `cache`'s - /// insertion order) if `cache` grew past `maxsize`. - fn evict_if_full(maxsize: usize, cache: &Py, vm: &VirtualMachine) -> PyResult<()> { - if cache.__len__() <= maxsize { - return Ok(()); - } - let oldest = cache.into_iter().next(); - if let Some((oldest_key, oldest_val)) = oldest { - let Some(elem) = oldest_val.downcast_ref::() else { - return Err(vm.new_type_error("lru cache entry is corrupted")); - }; - cache.del_item_known_hash(oldest_key.as_object(), elem.hash, vm)?; - } - Ok(()) - } } #[pyclass( with(Constructor, Callable, GetDescriptor), - flags(HAS_DICT, HAS_WEAKREF) + flags(HAS_DICT, HAS_WEAKREF, METHOD_DESCRIPTOR) )] impl Py { #[pymethod] fn cache_info(&self, vm: &VirtualMachine) -> PyResult { let hits = self.hits.load(Ordering::Relaxed); let misses = self.misses.load(Ordering::Relaxed); - let currsize = self.cache.read().__len__(); + let currsize = self.cache.__len__(); let maxsize: PyObjectRef = match self.maxsize { Some(n) => vm.ctx.new_int(n).into(), None => vm.ctx.none(), @@ -859,16 +876,14 @@ mod _functools { } #[pymethod] - fn cache_clear(&self, vm: &VirtualMachine) { - let new_cache = vm.ctx.new_dict(); - let old_cache = { - let _guard = RMutexGuard::acquire(&self.lock); - let old_cache = core::mem::replace(&mut *self.cache.write(), new_cache); - self.hits.store(0, Ordering::Relaxed); - self.misses.store(0, Ordering::Relaxed); - old_cache - }; - drop(old_cache); + fn cache_clear(&self) { + let _guard = RMutexGuard::acquire(&self.lock); + self.hits.store(0, Ordering::Relaxed); + self.misses.store(0, Ordering::Relaxed); + // Keep the dict identity: an equality callback can clear the cache + // while a lookup is in progress. DictContent restarts that lookup + // against the empty table and releases entries outside its own lock. + self.cache.clear(); } #[pymethod] @@ -877,12 +892,12 @@ mod _functools { } #[pymethod] - fn __copy__(zelf: PyObjectRef) -> PyObjectRef { + fn __copy__(zelf: PyObjectRef, _args: PosArgs) -> PyObjectRef { zelf } #[pymethod] - fn __deepcopy__(zelf: PyObjectRef, _memo: PyObjectRef) -> PyObjectRef { + fn __deepcopy__(zelf: PyObjectRef, _args: PosArgs) -> PyObjectRef { zelf } @@ -910,20 +925,22 @@ mod _functools { { let _guard = RMutexGuard::acquire(&zelf.lock); - let cache = zelf.cache.read().clone(); - if let Some(value) = cache.get_item_known_hash(key.as_object(), hash, vm)? { + let cache = &zelf.cache; + let value = if zelf.maxsize.is_some() { + cache.entries.move_to_end(vm, key.as_object(), hash)? + } else { + cache.entries.get_reentrant(vm, key.as_object(), hash)? + }; + if let Some(value) = value { let result = if zelf.maxsize.is_some() { let Some(elem) = value.downcast_ref::() else { return Err(vm.new_type_error("lru cache entry is corrupted")); }; elem.result.clone() } else { - value.clone() + value }; zelf.hits.fetch_add(1, Ordering::Relaxed); - if zelf.maxsize.is_some() { - Self::touch_key(&key, hash, &value, &cache, vm)?; - } return Ok(result); } zelf.misses.fetch_add(1, Ordering::Relaxed); @@ -935,25 +952,62 @@ mod _functools { { let _guard = RMutexGuard::acquire(&zelf.lock); - let cache = zelf.cache.read().clone(); - // A reentrant or concurrent call may have already inserted this key - // (e.g. recursive lookups, or another thread finishing first); in that - // case keep the existing entry instead of creating orphan eviction - // links (see CPython issue gh-35780). - if !cache.contains_known_hash(key.as_object(), hash, vm)? { - let entry = if zelf.maxsize.is_some() { - PyLruListElem { + let cache = &zelf.cache; + if let Some(maxsize) = zelf.maxsize { + // Only bounded caches preserve a result inserted by a + // recursive call while the user function was running. + // Revalidate equality callbacks here too, without moving + // an existing entry or changing its recency. + if cache + .entries + .get_reentrant(vm, key.as_object(), hash)? + .is_none() + { + let entry = PyLruListElem { hash, result: result.clone(), } - .into_pyobject(vm) - } else { - result.clone() - }; - cache.set_item_known_hash(key.as_object(), hash, entry, vm)?; - if let Some(maxsize) = zelf.maxsize { - Self::evict_if_full(maxsize, &cache, vm)?; + .into_pyobject(vm); + let _evicted = if cache.__len__() >= maxsize { + if let Some((oldest_key, oldest_value)) = cache.into_iter().next() { + let Some(elem) = oldest_value.downcast_ref::() + else { + return Err(vm.new_type_error("lru cache entry is corrupted")); + }; + // Pop can run equality for colliding keys. A + // callback may clear the cache before it finds + // the eviction candidate, leaving no entry. + if cache + .entries + .pop_reentrant(vm, &*oldest_key, elem.hash)? + .is_none() + { + return Ok(result); + } + Some((oldest_key, oldest_value)) + } else { + None + } + } else { + None + }; + if let Err(error) = + cache.set_item_known_hash(key.as_object(), hash, entry, vm) + { + // CPython releases the failed new entry before the + // evicted key/result. Any of their finalizers can + // reenter and inspect or repopulate the cache. + drop(key); + drop(result); + return Err(error); + } + // Neither keys nor results may be finalized between + // eviction and insertion into the now-consistent cache. } + } else { + // An unbounded cache always installs the newly computed + // result, including after a recursive call for this key. + cache.set_item_known_hash(key.as_object(), hash, result.clone(), vm)?; } } diff --git a/crates/vm/src/stdlib/_imp.rs b/crates/vm/src/stdlib/_imp.rs index a2bb2a0abc6..85b9abaf686 100644 --- a/crates/vm/src/stdlib/_imp.rs +++ b/crates/vm/src/stdlib/_imp.rs @@ -7,6 +7,8 @@ pub(crate) use _imp::module_def; pub(super) use crate::vm::resolve_frozen_alias; +mod resources; + #[cfg(feature = "threading")] #[pymodule(sub, name = "_imp")] mod lock { @@ -180,26 +182,43 @@ fn find_frozen(name: &str, vm: &VirtualMachine) -> Result 0 → true, override < 0 → false, 0 → default (true) + // use_frozen(): override > 0 → true, override < 0 → false, 0 → startup setting // When disabled, non-bootstrap modules are simply not found (same as look_up_frozen) let override_val = vm.state.override_frozen_modules.load(); - if override_val < 0 { + if override_val < 0 + || (override_val == 0 + && vm.import_bootstrap_complete + && !vm.state.config.settings.use_frozen_modules) + { return Err(FrozenError::NotFound); } Ok(frozen) } -#[pymodule(with(lock))] +#[pymodule(with(lock, resources::resources))] mod _imp { use crate::{ - PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyBytesRef, PyCode, PyMemoryView, PyModule, PyStrRef, PyUtf8StrRef}, + AsObject, Py, PyObjectRef, PyPayload, PyRef, PyRefExact, PyResult, VirtualMachine, + builtins::{ + PyBytesRef, PyCode, PyDict, PyImportError, PyMemoryView, PyModule, PyStrRef, + PyUtf8StrRef, + }, import, version, }; use super::FrozenError; + // Private exact-dict relocation primitive for future import-cache ordering. + #[pyfunction] + fn _dict_move_to_end( + modules: PyRefExact, + key: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + modules.move_to_end(key, vm) + } + #[pyattr] fn check_hash_based_pycs(vm: &VirtualMachine) -> PyStrRef { vm.ctx @@ -214,27 +233,94 @@ mod _imp { Vec::new() } + // This hook is also used by eager imports that satisfy pending lazy targets. #[pyfunction] - fn is_builtin(name: PyUtf8StrRef, vm: &VirtualMachine) -> bool { - vm.state.module_defs.contains_key(name.as_str()) + fn _set_lazy_attributes( + _modobj: PyObjectRef, + name: PyStrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + crate::lazy_import::clear_submodule(&name, false, vm)?; + vm.state.lazy_imports.modules.discard(name.into(), vm) } #[pyfunction] - fn is_frozen(name: PyUtf8StrRef, vm: &VirtualMachine) -> bool { - super::find_frozen(name.as_str(), vm).is_ok() + fn is_builtin(name: PyStrRef, vm: &VirtualMachine) -> i32 { + match name.to_str() { + Some("sys" | "builtins") => -1, + Some(name) => i32::from(vm.state.module_defs.contains_key(name)), + None => 0, + } + } + + #[pyfunction] + fn is_frozen(name: PyStrRef, vm: &VirtualMachine) -> bool { + name.to_str() + .is_some_and(|name| super::find_frozen(name, vm).is_ok()) } #[pyfunction] fn create_builtin(spec: PyObjectRef, vm: &VirtualMachine) -> PyResult { - let sys_modules = vm.sys_module.get_attr("modules", vm).unwrap(); - let name: PyUtf8StrRef = spec.get_attr("name", vm)?.try_into_value(vm)?; + let name_obj = spec.get_attr("name", vm)?; + let name: PyStrRef = name_obj.downcast().map_err(|obj| { + vm.new_type_error(format!( + "name must be string, not {:.200}", + obj.class().name() + )) + })?; + if name.is_empty() { + return Err(vm.new_value_error("name must not be empty")); + } + // Builtin module names use ASCII even when an unknown name is supplied. + if !name.as_bytes().is_ascii() { + vm.state + .codec_registry + .encode_text(name.clone(), "ascii", None, vm)?; + } + let name_str = name.as_utf8().expect("ASCII module name").as_str(); + if name_str.contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + if !matches!(name_str, "sys" | "builtins") && !vm.state.module_defs.contains_key(name_str) { + let exc = vm.new_payload_exception::( + vm.ctx.exceptions.module_not_found_error.to_owned(), + vec![ + vm.ctx + .new_str(format!("{name_str} module not found")) + .into(), + ] + .into(), + )?; + exc.as_object().set_attr("name", name.clone(), vm)?; + return Err(exc.upcast()); + } + + // CPython reloads core extensions from per-interpreter initialization + // snapshots, using the original registry even if sys.modules is rebound. + if let Some(snapshot) = match name_str { + "sys" => vm.state.sysdict_copy.get(), + "builtins" => vm.state.builtins_copy.get(), + _ => None, + } { + if !vm.state.is_main_interpreter() + && vm.state.feature_flags.check_multi_interp_extensions + { + return Err(vm.new_import_error( + format!("module {name_str} does not support loading in subinterpreters"), + name.clone(), + )); + } + let module = crate::import::add_module(vm, name_str)?; + module.dict().merge_dict(snapshot, true, vm)?; + return Ok(module.into()); + } - // Check sys.modules first + let sys_modules = vm.sys_modules(); + // Only registered builtins (or the two core modules) may use this cache. if let Ok(module) = sys_modules.get_item(&*name, vm) { return Ok(module); } - let name_str = name.as_str(); if let Some(&def) = vm.state.module_defs.get(name_str) { // Phase 1: Create module (use create slot if provided, else default creation) let module = if let Some(create) = def.slots.create { @@ -247,11 +333,11 @@ mod _imp { // Initialize module dict and methods // Corresponds to PyModule_FromDefAndSpec: md_def, _add_methods_to_object, PyModule_SetDocString - PyModule::__init_dict_from_def(vm, &module); + PyModule::__init_dict_from_def(vm, &module)?; module.__init_methods(vm)?; // Add to sys.modules BEFORE exec (critical for circular import handling) - sys_modules.set_item(name.as_pystr(), module.clone().into(), vm)?; + sys_modules.set_item(&*name, module.clone().into(), vm)?; // Phase 2: Call exec slot (can safely import other modules now) if let Some(exec) = def.slots.exec { @@ -269,7 +355,8 @@ mod _imp { #[pyarg(positional)] spec: PyObjectRef, #[pyarg(positional, optional)] - _file: crate::function::OptionalArg, + #[allow(dead_code)] + file: crate::function::OptionalArg, } #[pyfunction] @@ -289,7 +376,7 @@ mod _imp { return Err(vm.new_value_error("embedded null character".to_owned())); } - let sys_modules = vm.sys_module.get_attr("modules", vm)?; + let sys_modules = vm.sys_modules(); if let Ok(module) = sys_modules.get_item(&*name, vm) { return Ok(module); } @@ -337,12 +424,12 @@ mod _imp { } #[pyfunction] - fn exec_dynamic(_module: PyRef) -> i32 { + fn exec_dynamic(_imp: &Py, _mod: PyRef) -> i32 { 0 } #[pyfunction] - fn exec_builtin(_mod: PyRef) -> i32 { + fn exec_builtin(_imp: &Py, _mod: PyRef) -> i32 { // For multi-phase init modules, exec is already called in create_builtin 0 } @@ -422,7 +509,7 @@ mod _imp { #[derive(FromArgs)] struct FindFrozenArgs { #[pyarg(positional)] - name: PyUtf8StrRef, + name: PyStrRef, #[pyarg(named, default)] withdata: bool, } @@ -434,8 +521,9 @@ mod _imp { vm: &VirtualMachine, ) -> PyResult>, bool, Option)>> { let FindFrozenArgs { name, withdata } = args; - - let name_str = name.as_str(); + let Some(name_str) = name.to_str() else { + return Ok(None); + }; let info = match super::find_frozen(name_str, vm) { Ok(info) => info, Err(FrozenError::NotFound | FrozenError::Disabled | FrozenError::BadName) => { @@ -488,7 +576,7 @@ fn update_code_filenames( new_name: &'static PyStrInterned, ) { let current = code.source_path(); - if !core::ptr::eq(current, old_name) && current.as_str() != old_name.as_str() { + if !core::ptr::eq(current, old_name) && current.as_wtf8() != old_name.as_wtf8() { return; } code.set_source_path(new_name); diff --git a/crates/vm/src/stdlib/_imp/resources.rs b/crates/vm/src/stdlib/_imp/resources.rs new file mode 100644 index 00000000000..6129b393803 --- /dev/null +++ b/crates/vm/src/stdlib/_imp/resources.rs @@ -0,0 +1,275 @@ +//! Read-only resource protocols for explicitly registered frozen assets. + +#[pymodule(sub, name = "_imp")] +pub(super) mod resources { + use crate::{ + AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + builtins::{PyBaseExceptionRef, PyStrRef}, + frozen_resources::{ResourceError, ResourceView}, + function::{FsPath, FuncArgs, OptionalArg, PosArgs}, + protocol::PyNumberMethods, + types::AsNumber, + }; + + fn resource_error(error: ResourceError, vm: &VirtualMachine) -> PyBaseExceptionRef { + let exception = match &error { + ResourceError::InvalidPath(_) => return vm.new_value_error(error.to_string()), + ResourceError::NotFound(_) => vm.ctx.exceptions.file_not_found_error, + ResourceError::IsDirectory(_) => vm.ctx.exceptions.is_a_directory_error, + ResourceError::NotDirectory(_) => vm.ctx.exceptions.not_a_directory_error, + _ => return vm.new_runtime_error(error.to_string()), + }; + vm.new_os_subtype_error(exception.to_owned(), None, error.to_string()) + .upcast() + } + + fn join_resource( + view: &ResourceView, + path: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + let path = FsPath::try_from_path_like(path, false, vm)?; + let FsPath::Str(path) = path else { + return Err(vm.new_type_error("resource paths must be str or os.PathLike[str]")); + }; + let path = path + .to_str() + .ok_or_else(|| vm.new_value_error("resource paths must not contain surrogates"))?; + view.join(path).map_err(|error| resource_error(error, vm)) + } + + fn open_binary(view: &ResourceView, vm: &VirtualMachine) -> PyResult { + let bytes = view.bytes().map_err(|error| resource_error(error, vm))?; + // Import lazily: installing the importer hook must not bootstrap _io. + let io = vm.import("_io", 0)?; + let buffer = io + .get_attr("BytesIO", vm)? + .call((vm.ctx.new_bytes(bytes.to_vec()),), vm)?; + io.get_attr("BufferedReader", vm)?.call((buffer,), vm) + } + + #[derive(FromArgs)] + struct OpenArgs { + #[pyarg(any, optional, py_default = "'r'")] + mode: OptionalArg, + #[pyarg(any, optional)] + encoding: Option, + #[pyarg(any, optional)] + errors: Option, + #[pyarg(any, optional)] + newline: Option, + } + + #[derive(FromArgs)] + struct ReadTextArgs { + #[pyarg(any, optional)] + encoding: Option, + #[pyarg(any, optional)] + errors: Option, + #[pyarg(named, optional)] + newline: Option, + } + + #[pyattr] + #[pyclass(name = "_FrozenResourceReader", module = "_imp")] + #[derive(Debug, PyPayload)] + struct FrozenResourceReader { + view: ResourceView, + } + + #[pyclass(flags(DISALLOW_INSTANTIATION))] + impl FrozenResourceReader { + #[pymethod] + fn open_resource(zelf: &Py, resource: PyObjectRef, vm: &VirtualMachine) -> PyResult { + open_binary(&join_resource(&zelf.view, resource, vm)?, vm) + } + + #[pymethod] + fn resource_path(_zelf: &Py, resource: PyObjectRef, vm: &VirtualMachine) -> PyResult { + // Embedded assets have no filesystem path. importlib.resources.as_file + // performs any requested temporary extraction through Traversable. + Err(vm.new_exception( + vm.ctx.exceptions.file_not_found_error.to_owned(), + vec![resource], + )) + } + + #[pymethod] + fn is_resource( + zelf: &Py, + resource: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + Ok(join_resource(&zelf.view, resource, vm)?.is_file()) + } + + #[pymethod] + fn contents(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let children = zelf + .view + .children() + .map_err(|error| resource_error(error, vm))?; + let names = children + .iter() + .map(|child| vm.ctx.new_str(child.name()).into()) + .collect(); + Ok(vm.ctx.new_tuple(names).as_object().get_iter(vm)?.into()) + } + + #[pymethod] + fn files(zelf: &Py, vm: &VirtualMachine) -> PyRef { + FrozenTraversable { + view: zelf.view.clone(), + } + .into_ref(&vm.ctx) + } + } + + #[pyattr] + #[pyclass(name = "_FrozenTraversable", module = "_imp")] + #[derive(Debug, PyPayload)] + struct FrozenTraversable { + view: ResourceView, + } + + #[pyclass(with(AsNumber), flags(DISALLOW_INSTANTIATION))] + impl FrozenTraversable { + #[pygetset] + fn name(zelf: &Py) -> String { + zelf.view.name().to_owned() + } + + #[pymethod] + fn iterdir(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let children = zelf + .view + .children() + .map_err(|error| resource_error(error, vm))?; + let children = children + .into_iter() + .map(|view| Self { view }.into_ref(&vm.ctx).into()) + .collect(); + Ok(vm.ctx.new_tuple(children).as_object().get_iter(vm)?.into()) + } + + #[pymethod] + fn is_dir(zelf: &Py) -> bool { + zelf.view.is_dir() + } + + #[pymethod] + fn is_file(zelf: &Py) -> bool { + zelf.view.is_file() + } + + #[pymethod] + fn joinpath( + zelf: &Py, + descendants: PosArgs, + vm: &VirtualMachine, + ) -> PyResult> { + let mut view = zelf.view.clone(); + for descendant in descendants { + view = join_resource(&view, descendant, vm)?; + } + Ok(Self { view }.into_ref(&vm.ctx)) + } + + #[pymethod] + fn open(zelf: &Py, args: OpenArgs, vm: &VirtualMachine) -> PyResult { + let mode = match &args.mode { + OptionalArg::Present(mode) => mode.as_bytes(), + OptionalArg::Missing => b"r", + }; + match mode { + b"rb" => { + if args.encoding.is_some() || args.errors.is_some() || args.newline.is_some() { + return Err(vm.new_value_error( + "binary mode does not accept encoding, errors or newline", + )); + } + open_binary(&zelf.view, vm) + } + b"r" => { + let buffer = open_binary(&zelf.view, vm)?; + let mut wrapper_args = FuncArgs::from(vec![buffer]); + for (name, value) in [ + ("encoding", args.encoding), + ("errors", args.errors), + ("newline", args.newline), + ] { + if let Some(value) = value { + wrapper_args.kwargs.insert(name.into(), value); + } + } + vm.import("_io", 0)? + .get_attr("TextIOWrapper", vm)? + .call(wrapper_args, vm) + } + _ => Err(vm.new_value_error("frozen resources support only 'r' and 'rb' modes")), + } + } + + #[pymethod] + fn read_bytes(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let bytes = zelf + .view + .bytes() + .map_err(|error| resource_error(error, vm))?; + Ok(vm.ctx.new_bytes(bytes.to_vec()).into()) + } + + #[pymethod] + fn read_text(zelf: &Py, args: ReadTextArgs, vm: &VirtualMachine) -> PyResult { + let stream = Self::open( + zelf, + OpenArgs { + mode: OptionalArg::Missing, + encoding: args.encoding, + errors: args.errors, + newline: args.newline, + }, + vm, + )?; + let result = vm.call_method(&stream, "read", ()); + let close = vm.call_method(&stream, "close", ()); + match (result, close) { + (Err(read_error), Err(close_error)) => { + close_error.set_context(Some(read_error)); + Err(close_error) + } + (Err(error), Ok(_)) | (Ok(_), Err(error)) => Err(error), + (Ok(contents), Ok(_)) => Ok(contents), + } + } + } + + impl AsNumber for FrozenTraversable { + fn as_number() -> &'static PyNumberMethods { + static AS_NUMBER: PyNumberMethods = PyNumberMethods { + true_divide: Some(|left, right, vm| { + let Some(path) = left.downcast_ref::() else { + return Ok(vm.ctx.not_implemented()); + }; + let view = join_resource(&path.view, right.to_owned(), vm)?; + Ok(FrozenTraversable { view }.into_ref(&vm.ctx).into()) + }), + ..PyNumberMethods::NOT_IMPLEMENTED + }; + &AS_NUMBER + } + } + + #[pyfunction] + fn _get_frozen_resource_reader( + fullname: PyStrRef, + vm: &VirtualMachine, + ) -> Option> { + let name = fullname.to_str()?; + super::super::find_frozen(name, vm).ok()?; + // Resources belong to an explicit exact-fullname registration. Resolving + // an unbound alias to another name would bypass registration ownership. + let view = vm.state.frozen.resource_view(name)?; + Some(FrozenResourceReader { view }.into_ref(&vm.ctx)) + } +} diff --git a/crates/vm/src/stdlib/_interpchannels.rs b/crates/vm/src/stdlib/_interpchannels.rs index d9fde089fd9..b7b41c375c2 100644 --- a/crates/vm/src/stdlib/_interpchannels.rs +++ b/crates/vm/src/stdlib/_interpchannels.rs @@ -15,6 +15,7 @@ pub(crate) mod _interpchannels { convert::ToPyObject, function::{ArgSpec, Either, FuncArgs, PyComparisonValue}, protocol::{PyNumber, PyNumberMethods}, + stdlib::time::pytime, types::{AsNumber, Constructor, Hashable, PyComparisonOp, PyStructSequence, Representable}, vm::crossinterp::{Fallback, SharedValue, UnboundOp}, }; @@ -366,18 +367,23 @@ pub(crate) mod _interpchannels { /// `channel_destroy`: forget the channel entirely. fn channel_destroy(cid: i64) -> ChanResult, bool)>> { - let mut table = channels().lock(); - let entry = table.refs.remove(&cid).ok_or(ChanErr::NotFound)?; - Ok(match entry.chan { - Some(chan) => drain_queue(&mut chan.state.lock()), - None => Vec::new(), - }) + let entry = channels() + .lock() + .refs + .remove(&cid) + .ok_or(ChanErr::NotFound)?; + let items = match entry.chan { + Some(chan) => core::mem::take(&mut chan.state.lock().queue), + None => VecDeque::new(), + }; + Ok(retire_items(items)) } - fn drain_queue(state: &mut ChannelState) -> Vec<(Arc, bool)> { - state - .queue - .drain(..) + // Shared buffers can run owner callbacks when released. Call only after + // unlocking both the directory and channel state. + fn retire_items(items: VecDeque) -> Vec<(Arc, bool)> { + items + .into_iter() .filter_map(|item| item.waiting.map(|w| (w, false))) .collect() } @@ -394,10 +400,12 @@ pub(crate) mod _interpchannels { return Vec::new(); } let entry = table.refs.remove(&cid).expect("just looked it up"); - match entry.chan { - Some(chan) => drain_queue(&mut chan.state.lock()), - None => Vec::new(), - } + drop(table); + let items = match entry.chan { + Some(chan) => core::mem::take(&mut chan.state.lock().queue), + None => VecDeque::new(), + }; + retire_items(items) } /// `_channels_add_id_object`. @@ -456,12 +464,13 @@ pub(crate) mod _interpchannels { state.closing = true; return Ok(Vec::new()); } - let waiters = drain_queue(&mut state); + let items = core::mem::take(&mut state.queue); state.open = false; state.ends.release_all(); drop(state); entry.chan = None; - Ok(waiters) + drop(table); + Ok(retire_items(items)) } /// `channel_release`: close one or both ends for the current interpreter. @@ -486,6 +495,7 @@ pub(crate) mod _interpchannels { .filter_map(|r| r.chan.clone()) .collect(); let mut waiters = Vec::new(); + let mut dropped = Vec::new(); for chan in chans { let mut state = chan.state.lock(); let mut i = 0; @@ -500,17 +510,19 @@ pub(crate) mod _interpchannels { if let Some(w) = item.waiting { waiters.push((w, false)); } + dropped.push(item.data); continue; } // UNBOUND_ERROR / UNBOUND_REPLACE keep the slot but throw the // data away; the item is now "unbound". - item.data = None; + dropped.push(item.data.take()); i += 1; } state.ends.clear_interpreter(interpid); state.open = state.ends.is_open(); } release_waiters_detached(waiters); + drop(dropped); } /// `resolve_unboundop`. @@ -572,7 +584,11 @@ pub(crate) mod _interpchannels { args: &FuncArgs, func: &'static str, vm: &VirtualMachine, - ) -> PyResult>> { + ) -> PyResult<(i64, bool, bool, bool)> { + let mut cid = None; + let mut send = false; + let mut recv = false; + let mut force = false; ArgSpec { fname: func, keywords: &["cid", "send", "recv", "force"], @@ -581,38 +597,40 @@ pub(crate) mod _interpchannels { } .parse_with( args, - |i, obj, vm| match i { - 0 => parse_cid(obj, vm).map(drop), - _ => Ok(()), + |i, obj, vm| { + match i { + 0 => cid = Some(parse_cid(obj, vm)?.0), + 1 => send = flag(obj, vm)?, + 2 => recv = flag(obj, vm)?, + 3 => force = flag(obj, vm)?, + _ => unreachable!(), + } + Ok(()) }, vm, - ) + )?; + Ok((cid.unwrap(), send, recv, force)) } /// The `p` converter: a predicate that only reads truthiness. - fn flag(slot: Option<&PyObject>, vm: &VirtualMachine) -> PyResult { - match slot { - Some(o) => o.to_owned().is_true(vm), - None => Ok(false), - } + fn flag(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + obj.to_owned().is_true(vm) } /// The `i` converter. - fn int_arg(slot: Option<&PyObject>, vm: &VirtualMachine) -> PyResult> { - slot.map(|o| { - let ival = o.try_index(vm)?.as_bigint().to_i64().ok_or_else(|| { + fn int_arg(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + let ival = + obj.try_index(vm)?.as_bigint().to_i64().ok_or_else(|| { vm.new_overflow_error("Python int too large to convert to C long") })?; - i32::try_from(ival).map_err(|_| { - let msg = if ival > i32::MAX as i64 { - "signed integer is greater than maximum" - } else { - "signed integer is less than minimum" - }; - vm.new_overflow_error(msg) - }) + i32::try_from(ival).map_err(|_| { + let msg = if ival > i32::MAX as i64 { + "signed integer is greater than maximum" + } else { + "signed integer is less than minimum" + }; + vm.new_overflow_error(msg) }) - .transpose() } #[pyattr] @@ -711,13 +729,13 @@ pub(crate) mod _interpchannels { } } - #[pygetset(name = "send")] - fn send_end(&self, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn send(&self, vm: &VirtualMachine) -> PyResult { channel_id_from_parts(self.cid, ChannelEnd::Send.as_i32(), true, self.resolve, vm) } - #[pygetset(name = "recv")] - fn recv_end(&self, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn recv(&self, vm: &VirtualMachine) -> PyResult { channel_id_from_parts(self.cid, ChannelEnd::Recv.as_i32(), true, self.resolve, vm) } @@ -751,7 +769,12 @@ pub(crate) mod _interpchannels { /// `_channelid_new`. fn channel_id_new(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { + let mut channel = None; + let mut send = None; + let mut recv = None; + let mut force = false; + let mut resolve = false; + ArgSpec { fname: "ChannelID.__new__", keywords: &["id", "send", "recv", "force", "_resolve"], required: 1, @@ -759,20 +782,20 @@ pub(crate) mod _interpchannels { } .parse_with( &args, - |i, obj, vm| match i { - 0 => parse_cid(obj, vm).map(drop), - _ => Ok(()), + |i, obj, vm| { + match i { + 0 => channel = Some(parse_cid(obj, vm)?), + 1 => send = Some(flag(obj, vm)?), + 2 => recv = Some(flag(obj, vm)?), + 3 => force = flag(obj, vm)?, + 4 => resolve = flag(obj, vm)?, + _ => unreachable!(), + } + Ok(()) }, vm, )?; - let (cid, mut end) = parse_cid(parsed[0].as_deref().unwrap(), vm)?; - let tri = |slot: Option<&PyObject>| -> PyResult> { - slot.map(|o| o.to_owned().is_true(vm)).transpose() - }; - let send = tri(parsed[1].as_deref())?; - let recv = tri(parsed[2].as_deref())?; - let force = flag(parsed[3].as_deref(), vm)?; - let resolve = flag(parsed[4].as_deref(), vm)?; + let (cid, mut end) = channel.unwrap(); match (send, recv) { (Some(false), Some(false)) => { return Err(vm.new_value_error("'send' and 'recv' cannot both be False")); @@ -826,15 +849,26 @@ pub(crate) mod _interpchannels { #[pyfunction] fn create(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { + let mut unboundarg = -1; + let mut fallbackarg = -1; + ArgSpec { fname: "create", keywords: &["unboundop", "fallback"], required: 0, max_positional: 2, } - .parse(&args, vm)?; - let unboundarg = int_arg(parsed[0].as_deref(), vm)?.unwrap_or(-1); - let fallbackarg = int_arg(parsed[1].as_deref(), vm)?.unwrap_or(-1); + .parse_with( + &args, + |i, obj, vm| { + match i { + 0 => unboundarg = int_arg(obj, vm)?, + 1 => fallbackarg = int_arg(obj, vm)?, + _ => unreachable!(), + } + Ok(()) + }, + vm, + )?; let unboundop = resolve_unboundop(unboundarg, UnboundOp::Replace, vm)?; let fallback = resolve_fallback(fallbackarg, Fallback::Full.as_i32(), vm)?; let cid = channel_create(unboundop, fallback.as_i32()); @@ -849,7 +883,7 @@ pub(crate) mod _interpchannels { Ok(()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn list_all(vm: &VirtualMachine) -> PyResult { let chans: Vec<(i64, UnboundOp, i32)> = channels() .lock() @@ -877,7 +911,9 @@ pub(crate) mod _interpchannels { #[pyfunction] fn list_interpreters(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { + let mut cid = None; + let mut send = false; + ArgSpec { fname: "channel_list_interpreters", keywords: &["cid", "send"], required: 2, @@ -885,21 +921,26 @@ pub(crate) mod _interpchannels { } .parse_with( &args, - |i, obj, vm| match i { - 0 => parse_cid(obj, vm).map(drop), - _ => Ok(()), + |i, obj, vm| { + match i { + 0 => cid = Some(parse_cid(obj, vm)?.0), + 1 => send = flag(obj, vm)?, + _ => unreachable!(), + } + Ok(()) }, vm, )?; - let cid = parse_cid(parsed[0].as_deref().unwrap(), vm)?.0; - let send = flag(parsed[1].as_deref(), vm)?; + let cid = cid.unwrap(); let chan = channels_lookup(cid).map_err(|e| e.into_py(cid, vm))?; + let interpreters = crate::vm::runtime::list_interpreters(); let state = chan.state.lock(); if send && state.closing { + drop(state); return Err(ChanErr::Closed.into_py(cid, vm)); } let mut out = Vec::new(); - for info in crate::vm::runtime::list_interpreters() { + for info in interpreters { if state.ends.find(info.id, send).is_some_and(|i| { if send { state.ends.send[i].1 @@ -907,10 +948,18 @@ pub(crate) mod _interpchannels { state.ends.recv[i].1 } }) { - out.push(vm.ctx.new_int(info.id).into()); + out.push(info.id); } } - Ok(vm.ctx.new_list(out).into()) + drop(state); + Ok(vm + .ctx + .new_list( + out.into_iter() + .map(|id| vm.ctx.new_int(id).into()) + .collect(), + ) + .into()) } /// `channel_send` up to its `closing` check, which precedes converting the @@ -982,15 +1031,18 @@ pub(crate) mod _interpchannels { if timed_out { // The send is failing now, so make sure the item won't be received. let mut state = chan.state.lock(); - if let Some(pos) = state.queue.iter().position(|it| { - it.waiting - .as_ref() - .is_some_and(|w| Arc::ptr_eq(w, &waiting)) - }) { - state.queue.remove(pos); - } + let removed = state + .queue + .iter() + .position(|it| { + it.waiting + .as_ref() + .is_some_and(|w| Arc::ptr_eq(w, &waiting)) + }) + .and_then(|pos| state.queue.remove(pos)); drop(state); finish_closing(cid); + drop(removed); if !waiting.state.lock().received { return Err(vm .new_os_subtype_error( @@ -1020,6 +1072,10 @@ pub(crate) mod _interpchannels { bool, Option, )> { + let mut cid = None; + let mut unboundarg = -1; + let mut fallbackarg = -1; + let mut blocking = true; let parsed = ArgSpec { fname: func, keywords: &["cid", "obj", "unboundop", "fallback", "blocking", "timeout"], @@ -1028,21 +1084,20 @@ pub(crate) mod _interpchannels { } .parse_with( args, - |i, obj, vm| match i { - 0 => parse_cid(obj, vm).map(drop), - 2 | 3 => int_arg(Some(obj), vm).map(drop), - _ => Ok(()), + |i, obj, vm| { + match i { + 0 => cid = Some(parse_cid(obj, vm)?.0), + 2 => unboundarg = int_arg(obj, vm)?, + 3 => fallbackarg = int_arg(obj, vm)?, + 4 => blocking = flag(obj, vm)?, + _ => {} + } + Ok(()) }, vm, )?; - let cid = parse_cid(parsed[0].as_deref().unwrap(), vm)?.0; + let cid = cid.unwrap(); let obj = parsed[1].clone().unwrap(); - let unboundarg = int_arg(parsed[2].as_deref(), vm)?.unwrap_or(-1); - let fallbackarg = int_arg(parsed[3].as_deref(), vm)?.unwrap_or(-1); - let blocking = match &parsed[4] { - Some(o) => o.to_owned().is_true(vm)?, - None => true, - }; let timeout = parse_timeout(parsed[5].as_deref(), blocking, vm)?; // The channel is only consulted when one of the arguments needs its default. let (default_unboundop, default_fallback) = if unboundarg < 0 || fallbackarg < 0 { @@ -1089,23 +1144,34 @@ pub(crate) mod _interpchannels { if !blocking { return Err(vm.new_value_error("can't specify a timeout for a non-blocking call")); } - let secs = t.try_float(vm)?.to_f64(); - if secs < 0.0 { + let nanoseconds = pytime::from_seconds_object(t, pytime::Round::Up, vm)?; + if nanoseconds < 0 { return Err(vm.new_value_error("timeout value must be a non-negative number")); } - Ok(Some(Duration::from_secs_f64(secs))) + pytime::check_thread_timeout(nanoseconds, vm)?; + Ok(Some(Duration::from_nanos(nanoseconds as u64))) } #[pyfunction] fn recv(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let mut cid = None; let parsed = ArgSpec { fname: "channel_recv", keywords: &["cid", "default"], required: 1, max_positional: 2, } - .parse(&args, vm)?; - let cid = parse_cid(parsed[0].as_deref().unwrap(), vm)?.0; + .parse_with( + &args, + |i, obj, vm| { + if i == 0 { + cid = Some(parse_cid(obj, vm)?.0); + } + Ok(()) + }, + vm, + )?; + let cid = cid.unwrap(); let default = parsed[1].as_deref(); let popped = channel_next(cid, vm.state.interpreter_id); finish_closing(cid); @@ -1163,11 +1229,7 @@ pub(crate) mod _interpchannels { #[pyfunction] fn close(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let parsed = end_args(&args, "channel_close", vm)?; - let cid = parse_cid(parsed[0].as_deref().unwrap(), vm)?.0; - let send = flag(parsed[1].as_deref(), vm)?; - let recv = flag(parsed[2].as_deref(), vm)?; - let force = flag(parsed[3].as_deref(), vm)?; + let (cid, send, recv, force) = end_args(&args, "channel_close", vm)?; let end = i32::from(send) - i32::from(recv); let waiters = channel_close(cid, end, force).map_err(|e| e.into_py(cid, vm))?; release_waiters(waiters, vm); @@ -1176,10 +1238,8 @@ pub(crate) mod _interpchannels { #[pyfunction] fn release(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let parsed = end_args(&args, "channel_release", vm)?; - let cid = parse_cid(parsed[0].as_deref().unwrap(), vm)?.0; - let mut send = flag(parsed[1].as_deref(), vm)?; - let mut recv = flag(parsed[2].as_deref(), vm)?; + // The legacy parser converts force even though channel_release ignores it. + let (cid, mut send, mut recv, _force) = end_args(&args, "channel_release", vm)?; if !send && !recv { send = true; recv = true; diff --git a/crates/vm/src/stdlib/_interpqueues.rs b/crates/vm/src/stdlib/_interpqueues.rs index 1e9e3945931..b5f5c1643ed 100644 --- a/crates/vm/src/stdlib/_interpqueues.rs +++ b/crates/vm/src/stdlib/_interpqueues.rs @@ -10,14 +10,13 @@ pub(crate) use _interpqueues::{ #[pymodule] pub(crate) mod _interpqueues { use crate::{ - AsObject, Py, PyObject, PyPayload, PyResult, VirtualMachine, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, builtins::{PyBaseExceptionRef, PyModule, PyType, PyTypeRef}, - function::{ArgSpec, FuncArgs}, + function::OptionalArg, types::Constructor, vm::crossinterp::{Fallback, SharedValue, UnboundOp}, }; use alloc::{collections::BTreeMap, collections::VecDeque, sync::Arc}; - use core::cell::Cell; use num_traits::{Signed, ToPrimitive}; use parking_lot::Mutex; use std::sync::OnceLock; @@ -240,7 +239,6 @@ pub(crate) mod _interpqueues { .remove(&qid) .ok_or(QueueErr::NotFound)?; kill_queue(&queue.queue); - drop(queue); Ok(()) } @@ -276,7 +274,6 @@ pub(crate) mod _interpqueues { }; if let Some(queue) = removed { kill_queue(&queue.queue); - drop(queue); } Ok(()) } @@ -339,23 +336,11 @@ pub(crate) mod _interpqueues { Err(vm.new_overflow_error(format!("max queue ID is {}, got {repr}", i64::MAX))) } - fn qid_arg(args: &FuncArgs, func: &'static str, vm: &VirtualMachine) -> PyResult { - let qid = Cell::new(None); - ArgSpec { - fname: func, - keywords: &["qid"], - required: 1, - max_positional: 1, + fn optional_int_arg(arg: &OptionalArg, vm: &VirtualMachine) -> PyResult { + match arg { + OptionalArg::Present(obj) => int_arg(obj, vm), + OptionalArg::Missing => Ok(-1), } - .parse_with( - args, - |_, obj, vm| { - qid.set(Some(parse_qid(obj, vm)?)); - Ok(()) - }, - vm, - )?; - Ok(qid.get().unwrap()) } #[expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature")] @@ -365,39 +350,58 @@ pub(crate) mod _interpqueues { Ok(()) } + // Keep the original inputs alive while applying the queue-specific converters. + #[derive(FromArgs)] + struct QueueIdArgs { + #[pyarg(any)] + qid: PyObjectRef, + } + + #[derive(FromArgs)] + struct CreateArgs { + #[pyarg(any)] + maxsize: PyObjectRef, + #[pyarg(any, optional, py_default = "-1")] + unboundop: OptionalArg, + #[pyarg(any, optional, py_default = "-1")] + fallback: OptionalArg, + } + + #[derive(FromArgs)] + struct PutArgs { + #[pyarg(any)] + qid: PyObjectRef, + #[pyarg(any)] + obj: PyObjectRef, + #[pyarg(any, optional, py_default = "-1")] + unboundop: OptionalArg, + #[pyarg(any, optional, py_default = "-1")] + fallback: OptionalArg, + } + + #[derive(FromArgs)] + struct RegisterHeapTypesArgs { + #[pyarg(any)] + queuetype: PyObjectRef, + #[pyarg(any)] + emptyerror: PyObjectRef, + #[pyarg(any)] + fullerror: PyObjectRef, + } + #[pyfunction] - fn create(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let maxsize = Cell::new(None); - let unboundarg = Cell::new(None); - let fallbackarg = Cell::new(None); - ArgSpec { - fname: "create", - keywords: &["maxsize", "unboundop", "fallback"], - required: 1, - max_positional: 3, - } - .parse_with( - &args, - |i, obj, vm| { - match i { - 0 => maxsize.set(Some(ssize_arg(obj, vm)?)), - 1 => unboundarg.set(Some(int_arg(obj, vm)?)), - 2 => fallbackarg.set(Some(int_arg(obj, vm)?)), - _ => unreachable!(), - } - Ok(()) - }, - vm, - )?; - let unboundop = resolve_unboundop(unboundarg.get().unwrap_or(-1), UnboundOp::Replace, vm)?; - let fallback = - resolve_fallback(fallbackarg.get().unwrap_or(-1), Fallback::Full.as_i32(), vm)?; - queue_create(maxsize.get().unwrap(), unboundop, fallback).map_err(|err| err.into_py(-1, vm)) + fn create(args: CreateArgs, vm: &VirtualMachine) -> PyResult { + let maxsize = ssize_arg(&args.maxsize, vm)?; + let unboundarg = optional_int_arg(&args.unboundop, vm)?; + let fallbackarg = optional_int_arg(&args.fallback, vm)?; + let unboundop = resolve_unboundop(unboundarg, UnboundOp::Replace, vm)?; + let fallback = resolve_fallback(fallbackarg, Fallback::Full.as_i32(), vm)?; + queue_create(maxsize, unboundop, fallback).map_err(|err| err.into_py(-1, vm)) } #[pyfunction] - fn destroy(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let qid = qid_arg(&args, "destroy", vm)?; + fn destroy(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult<()> { + let qid = parse_qid(&args.qid, vm)?; queue_destroy(qid).map_err(|err| err.into_py(qid, vm)) } @@ -429,33 +433,10 @@ pub(crate) mod _interpqueues { } #[pyfunction] - fn put(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let qid = Cell::new(None); - let unboundarg = Cell::new(None); - let fallbackarg = Cell::new(None); - let parsed = ArgSpec { - fname: "put", - keywords: &["qid", "obj", "unboundop", "fallback"], - required: 2, - max_positional: 4, - } - .parse_with( - &args, - |i, obj, vm| { - match i { - 0 => qid.set(Some(parse_qid(obj, vm)?)), - 2 => unboundarg.set(Some(int_arg(obj, vm)?)), - 3 => fallbackarg.set(Some(int_arg(obj, vm)?)), - _ => {} - } - Ok(()) - }, - vm, - )?; - let qid = qid.get().unwrap(); - let obj = parsed[1].as_deref().unwrap(); - let unboundarg = unboundarg.get().unwrap_or(-1); - let fallbackarg = fallbackarg.get().unwrap_or(-1); + fn put(args: PutArgs, vm: &VirtualMachine) -> PyResult<()> { + let qid = parse_qid(&args.qid, vm)?; + let unboundarg = optional_int_arg(&args.unboundop, vm)?; + let fallbackarg = optional_int_arg(&args.fallback, vm)?; // The queue is only consulted when one of the arguments needs its default. let (default_unboundop, default_fallback) = if unboundarg < 0 || fallbackarg < 0 { let (unboundop, fallback) = queue_defaults(qid).map_err(|err| err.into_py(qid, vm))?; @@ -465,7 +446,7 @@ pub(crate) mod _interpqueues { }; let unboundop = resolve_unboundop(unboundarg, default_unboundop, vm)?; let fallback = resolve_fallback(fallbackarg, default_fallback, vm)?; - let value = SharedValue::from_object(obj, fallback, vm)?; + let value = SharedValue::from_object(&args.obj, fallback, vm)?; let queue = queue_lookup(qid).map_err(|err| err.into_py(qid, vm))?; let mut state = queue.lock(); if !state.alive { @@ -484,8 +465,8 @@ pub(crate) mod _interpqueues { } #[pyfunction] - fn get(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let qid = qid_arg(&args, "get", vm)?; + fn get(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult { + let qid = parse_qid(&args.qid, vm)?; let item = { let queue = queue_lookup(qid).map_err(|err| err.into_py(qid, vm))?; let mut state = queue.lock(); @@ -511,20 +492,20 @@ pub(crate) mod _interpqueues { } #[pyfunction] - fn bind(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let qid = qid_arg(&args, "bind", vm)?; + fn bind(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult<()> { + let qid = parse_qid(&args.qid, vm)?; queue_bind(qid).map_err(|err| err.into_py(qid, vm)) } #[pyfunction] - fn release(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let qid = qid_arg(&args, "release", vm)?; + fn release(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult<()> { + let qid = parse_qid(&args.qid, vm)?; queue_release(qid).map_err(|err| err.into_py(qid, vm)) } #[pyfunction] - fn get_maxsize(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let qid = qid_arg(&args, "get_maxsize", vm)?; + fn get_maxsize(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult { + let qid = parse_qid(&args.qid, vm)?; let queue = queue_lookup(qid).map_err(|err| err.into_py(qid, vm))?; let state = queue.lock(); if !state.alive { @@ -534,8 +515,8 @@ pub(crate) mod _interpqueues { } #[pyfunction] - fn get_queue_defaults(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let qid = qid_arg(&args, "get_queue_defaults", vm)?; + fn get_queue_defaults(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult { + let qid = parse_qid(&args.qid, vm)?; let (unboundop, fallback) = queue_defaults(qid).map_err(|err| err.into_py(qid, vm))?; Ok(vm .ctx @@ -547,8 +528,8 @@ pub(crate) mod _interpqueues { } #[pyfunction] - fn is_full(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let qid = qid_arg(&args, "is_full", vm)?; + fn is_full(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult { + let qid = parse_qid(&args.qid, vm)?; let queue = queue_lookup(qid).map_err(|err| err.into_py(qid, vm))?; let state = queue.lock(); if !state.alive { @@ -558,8 +539,8 @@ pub(crate) mod _interpqueues { } #[pyfunction] - fn get_count(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let qid = qid_arg(&args, "get_count", vm)?; + fn get_count(args: QueueIdArgs, vm: &VirtualMachine) -> PyResult { + let qid = parse_qid(&args.qid, vm)?; let queue = queue_lookup(qid).map_err(|err| err.into_py(qid, vm))?; let state = queue.lock(); if !state.alive { @@ -569,29 +550,19 @@ pub(crate) mod _interpqueues { } #[pyfunction] - fn _register_heap_types(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let parsed = ArgSpec { - fname: "_register_heap_types", - keywords: &["queuetype", "emptyerror", "fullerror"], - required: 3, - max_positional: 3, - } - .parse(&args, vm)?; - let queue = parsed[0] - .clone() - .unwrap() + fn _register_heap_types(args: RegisterHeapTypesArgs, vm: &VirtualMachine) -> PyResult<()> { + let queue = args + .queuetype .downcast::() .map_err(|_| vm.new_type_error("expected a type for 'queuetype'"))?; - let empty = parsed[1] - .clone() - .unwrap() + let empty = args + .emptyerror .downcast::() .ok() .filter(|ty| ty.fast_issubclass(vm.ctx.exceptions.base_exception_type)) .ok_or_else(|| vm.new_type_error("expected an exception type for 'emptyerror'"))?; - let full = parsed[2] - .clone() - .unwrap() + let full = args + .fullerror .downcast::() .ok() .filter(|ty| ty.fast_issubclass(vm.ctx.exceptions.base_exception_type)) diff --git a/crates/vm/src/stdlib/_interpreters.rs b/crates/vm/src/stdlib/_interpreters.rs index 903a14f6acc..c11833a4ec5 100644 --- a/crates/vm/src/stdlib/_interpreters.rs +++ b/crates/vm/src/stdlib/_interpreters.rs @@ -2,7 +2,7 @@ //! //! Mirrors CPython `Modules/_interpretersmodule.c`. -pub(crate) use _interpreters::{config_from_pyobject, init_xi_types, module_def}; +pub(crate) use _interpreters::{config_from_pyobject, init_xi_types, module_def, parse_id}; #[cfg_attr(not(feature = "threading"), allow(unused_imports))] pub(crate) use _interpreters::{ interpreter_error, interpreter_not_found, not_shareable_error, xibufferview_from_buffer, @@ -12,9 +12,14 @@ pub(crate) use _interpreters::{ pub(crate) mod _interpreters { use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyBaseExceptionRef, PyCode, PyDict, PyException, PyFunction, PyModule, PyStr}, + builtins::{ + PyBaseExceptionRef, PyCode, PyDict, PyException, PyFunction, PyModule, PyStr, PyTuple, + }, class::PyClassImpl, - function::{ArgSpec, FuncArgs}, + function::{ + ArgIntoBool, ArgumentError, DefaultRepr, FromArgs, FuncArgs, OptionalArg, Param, + ParamKind, + }, protocol::{BufferMethods, PyBuffer}, types::{AsBuffer, Constructor}, vm::{ @@ -170,7 +175,7 @@ pub(crate) mod _interpreters { } /// `_PyInterpreterState_ObjectToID`. - fn parse_id(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + pub(crate) fn parse_id(obj: &PyObject, vm: &VirtualMachine) -> PyResult { if !obj.number().is_index() { return Err(vm.new_type_error(format!( "interpreter ID must be an int, got {}", @@ -222,29 +227,6 @@ pub(crate) mod _interpreters { Ok(id) } - fn require_dict<'a>( - obj: &'a PyObject, - func: &str, - pos: &str, - vm: &VirtualMachine, - ) -> PyResult<&'a Py> { - obj.downcast_ref::() - .ok_or_else(|| bad_argument(func, pos, "dict", obj, vm)) - } - - /// The `p` converter: a predicate that only reads truthiness. - fn flag(slot: Option<&PyObject>, vm: &VirtualMachine) -> PyResult { - match slot { - Some(o) => o.to_owned().is_true(vm), - None => Ok(false), - } - } - - /// The `O!` converter for `PyDict_Type`. - fn check_dict(obj: &PyObject, func: &str, pos: &str, vm: &VirtualMachine) -> PyResult<()> { - require_dict(obj, func, pos, vm).map(drop) - } - /// `_config_dict_get_bool`: only exact `True` / `False` are accepted. fn config_bool(value: &PyObject, name: &str, vm: &VirtualMachine) -> PyResult { if value.is(&vm.ctx.true_value) { @@ -342,12 +324,22 @@ pub(crate) mod _interpreters { .ok_or_else(|| vm.new_value_error(format!("unsupported config name '{name}'"))) } - /// `config_from_object`. + // _testinternalcapi's _init_interp_config_from_object accepts a namespace, + // unlike _interpreters.config_from_object's named configurations. pub(crate) fn config_from_pyobject( obj: &PyObject, vm: &VirtualMachine, ) -> PyResult { - parse_config(Some(obj), vm) + let dict = match obj.get_attr("__dict__", vm) { + Ok(dict) => dict, + Err(_) => return Err(vm.new_type_error(format!("bad config {}", obj.repr(vm)?))), + }; + let dict = dict + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("dict expected"))?; + let mut cfg = InterpreterConfig::ISOLATED; + config_from_dict(&mut cfg, dict, false, vm)?; + Ok(cfg) } /// `config_from_object`. @@ -358,18 +350,7 @@ pub(crate) mod _interpreters { if let Some(s) = obj.downcast_ref::() { return named_config(s.to_str(), vm); } - let dict = obj.get_attr("__dict__", vm).map_err(|_| { - let repr = obj - .repr(vm) - .map_or_else(|_| obj.class().name().to_string(), |s| s.to_string()); - vm.new_type_error(format!("bad config {repr}")) - })?; - let dict = dict - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("dict expected"))?; - let mut cfg = InterpreterConfig::ISOLATED; - config_from_dict(&mut cfg, dict, false, vm)?; - Ok(cfg) + config_from_pyobject(obj, vm) } /// `_PyInterpreterConfig_AsDict` wrapped in a `types.SimpleNamespace`. @@ -395,8 +376,154 @@ pub(crate) mod _interpreters { .into() } + struct NewConfigArgs(FuncArgs); + + impl FromArgs for NewConfigArgs { + // CPython uses a bespoke positional-count error before reading overrides. + const BINDING_PARAMS: Option<&'static [Param]> = None; + + const PARAMS: Option<&'static [Param]> = Some(&[ + Param { + name: "name", + kind: ParamKind::PositionalOnly, + default: Some(DefaultRepr::Str("isolated")), + }, + Param::var_keyword("overrides"), + ]); + + fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + Ok(Self(core::mem::take(args))) + } + } + + // These match the Clinic converters and their order. + // IDs stay objects until the implementation resolves them, after flags. + #[derive(FromArgs)] + struct ListAllArgs { + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + require_ready: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct CreateArgs<'a> { + #[pyarg(any, optional, py_default = "'isolated'")] + config: OptionalArg<&'a PyObject>, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + reqrefs: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct InterpreterIdArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + restrict: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct WhenceArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct ShareableArgs<'a> { + #[pyarg(any)] + obj: &'a PyObject, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct ExecArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + #[pyarg(any)] + code: &'a PyObject, + #[pyarg(any, optional, py_default = "{}")] + shared: OptionalArg<&'a Py>, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + restrict: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct RunStringArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + #[pyarg(any)] + script: &'a Py, + #[pyarg(any, optional, py_default = "{}")] + shared: OptionalArg<&'a Py>, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + restrict: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct RunFuncArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + #[pyarg(any)] + func: &'a PyObject, + #[pyarg(any, optional, py_default = "{}")] + shared: OptionalArg<&'a Py>, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + restrict: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct CallArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + #[pyarg(any)] + callable: &'a PyObject, + #[pyarg(any, optional, py_default = "()")] + args: OptionalArg<&'a Py>, + #[pyarg(any, optional, py_default = "{}")] + kwargs: OptionalArg<&'a Py>, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + // Clinic converts this flag even though the implementation ignores it. + preserve_exc: ArgIntoBool, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + restrict: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct SetMainAttrsArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + #[pyarg(any)] + updates: &'a Py, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + restrict: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct IncrefArgs<'a> { + #[pyarg(any)] + id: &'a PyObject, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + implieslink: ArgIntoBool, + #[pyarg(named, default = ArgIntoBool::FALSE, py_default = "False")] + restrict: ArgIntoBool, + } + + #[derive(FromArgs)] + #[from_args(borrowed)] + struct CaptureExceptionArgs<'a> { + #[pyarg(any, optional, py_default = "None")] + exc: OptionalArg<&'a PyObject>, + } + #[pyfunction] - fn new_config(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn new_config(NewConfigArgs(args): NewConfigArgs, vm: &VirtualMachine) -> PyResult { const FUNCNAME: &str = "_interpreters.new_config"; if args.args.len() > 1 { return Err(vm.new_type_error(format!( @@ -426,17 +553,10 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn create(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { - fname: "create", - keywords: &["config", "reqrefs"], - required: 0, - max_positional: 1, - } - .parse(&args, vm)?; - let reqrefs = flag(parsed[1].as_deref(), vm)?; - let config = parse_config(parsed[0].as_deref(), vm)?; - new_interpreter(config, reqrefs, vm) + fn create(args: CreateArgs<'_>, vm: &VirtualMachine) -> PyResult { + let requires_refs = args.reqrefs.into_bool(); + let config = parse_config(args.config.into_option(), vm)?; + new_interpreter(config, requires_refs, vm) } /// `_PyXI_NewInterpreter`, registered as a runtime-owned interpreter. @@ -470,16 +590,9 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn destroy(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let parsed = ArgSpec { - fname: "destroy", - keywords: &["id", "restrict"], - required: 1, - max_positional: 1, - } - .parse(&args, vm)?; - let restricted = flag(parsed[1].as_deref(), vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; + fn destroy(args: InterpreterIdArgs<'_>, vm: &VirtualMachine) -> PyResult<()> { + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; resolve_interp(Some(id), restricted, false, "destroy", vm)?; if id == vm.state.interpreter_id { return Err(interpreter_error( @@ -502,15 +615,8 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn list_all(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { - fname: "_interpreters.list_all", - keywords: &["require_ready"], - required: 0, - max_positional: 0, - } - .parse(&args, vm)?; - let reqready = flag(parsed[0].as_deref(), vm)?; + fn list_all(args: ListAllArgs, vm: &VirtualMachine) -> PyObjectRef { + let reqready = args.require_ready.into_bool(); let mut items = Vec::new(); for info in runtime::list_interpreters() { if reqready @@ -521,7 +627,7 @@ pub(crate) mod _interpreters { } items.push(summary(info.id, info.whence, vm)); } - Ok(vm.ctx.new_list(items).into()) + vm.ctx.new_list(items).into() } #[pyfunction] @@ -536,45 +642,24 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn is_running(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { - fname: "is_running", - keywords: &["id", "restrict"], - required: 1, - max_positional: 1, - } - .parse(&args, vm)?; - let restricted = flag(parsed[1].as_deref(), vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; + fn is_running(args: InterpreterIdArgs<'_>, vm: &VirtualMachine) -> PyResult { + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; resolve_interp(Some(id), restricted, true, "check if running for", vm)?; Ok(vm.ctx.new_bool(crossinterp::is_running(id)).into()) } #[pyfunction] - fn whence(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { - fname: "whence", - keywords: &["id"], - required: 1, - max_positional: 1, - } - .parse(&args, vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; + fn whence(args: WhenceArgs<'_>, vm: &VirtualMachine) -> PyResult { + let id = parse_id(args.id, vm)?; let state = runtime::lookup_interpreter(id).ok_or_else(|| interpreter_not_found(vm, id))?; Ok(vm.ctx.new_int(state.whence.as_i32()).into()) } #[pyfunction] - fn get_config(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { - fname: "get_config", - keywords: &["id", "restrict"], - required: 1, - max_positional: 1, - } - .parse(&args, vm)?; - let restricted = flag(parsed[1].as_deref(), vm)?; - let id_obj = parsed[0].as_deref().unwrap(); + fn get_config(args: InterpreterIdArgs<'_>, vm: &VirtualMachine) -> PyResult { + let restricted = args.restrict.into_bool(); + let id_obj = args.id; let id = if vm.is_none(id_obj) { None } else { @@ -586,15 +671,8 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn is_shareable(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { - fname: "is_shareable", - keywords: &["obj"], - required: 1, - max_positional: 1, - } - .parse(&args, vm)?; - Ok(crossinterp::is_shareable(parsed[0].as_deref().unwrap(), vm)) + fn is_shareable(args: ShareableArgs<'_>, vm: &VirtualMachine) -> bool { + crossinterp::is_shareable(args.obj, vm) } /// `_run_in_interpreter` for the script forms: `Ok(None)` on success, @@ -652,148 +730,65 @@ pub(crate) mod _interpreters { Err(vm.new_runtime_error("isolated interpreters require threading")) } - /// The shared `(id, , shared=None, *, restrict=False)` prologue. - /// `second_check` is the converter of the format string's second slot. - fn script_args( - args: &FuncArgs, - func: &'static str, - second_name: &'static str, - second_check: fn(&PyObject, &VirtualMachine) -> PyResult<()>, - op: &str, - vm: &VirtualMachine, - ) -> PyResult<(i64, PyObjectRef, Option>)> { - let parsed = ArgSpec { - fname: func, - keywords: &["id", second_name, "shared", "restrict"], - required: 2, - max_positional: 3, - } - .parse_with( - args, - |i, obj, vm| match i { - 1 => second_check(obj, vm), - 2 => check_dict(obj, func, "argument 3", vm), - _ => Ok(()), - }, - vm, - )?; - let restrict = flag(parsed[3].as_deref(), vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; - resolve_interp(Some(id), restrict, true, op, vm)?; - let shared = parsed[2].clone().map(|o| o.downcast::().unwrap()); - Ok((id, parsed[1].clone().unwrap(), shared)) - } - #[pyfunction] - fn exec(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - const FUNCNAME: &str = "_interpreters.exec"; - // The code need not be "pure": globals resolve against __main__. - let (id, code_obj, shared) = - script_args(&args, FUNCNAME, "code", |_, _| Ok(()), "exec code for", vm)?; - let code = crossinterp::script_code(&code_obj, vm)?; - run_code_in(id, code, shared.as_deref(), vm) + fn exec(args: ExecArgs<'_>, vm: &VirtualMachine) -> PyResult { + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; + resolve_interp(Some(id), restricted, true, "exec code for", vm)?; + let code = crossinterp::script_code(args.code, vm)?; + run_code_in(id, code, args.shared.into_option(), vm) } #[pyfunction] - fn run_string(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - const FUNCNAME: &str = "_interpreters.run_string"; - let (id, script, shared) = script_args( - &args, - FUNCNAME, - "script", - |obj, vm| { - // The `U` converter. - obj.downcastable::() - .then_some(()) - .ok_or_else(|| bad_argument(FUNCNAME, "argument 2", "str", obj, vm)) - }, - "run a string in", - vm, - )?; - let code = crossinterp::script_code(&script, vm)?; - run_code_in(id, code, shared.as_deref(), vm) + fn run_string(args: RunStringArgs<'_>, vm: &VirtualMachine) -> PyResult { + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; + resolve_interp(Some(id), restricted, true, "run a string in", vm)?; + let code = crossinterp::script_code(args.script.as_object(), vm)?; + run_code_in(id, code, args.shared.into_option(), vm) } #[pyfunction] - fn run_func(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn run_func(args: RunFuncArgs<'_>, vm: &VirtualMachine) -> PyResult { const FUNCNAME: &str = "_interpreters.run_func"; - // Globals are not checked either; they resolve against __main__. - let (id, func, shared) = script_args( - &args, - FUNCNAME, - "func", - |_, _| Ok(()), - "run a function in", - vm, - )?; - if !func.downcastable::() && !func.downcastable::() { + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; + resolve_interp(Some(id), restricted, true, "run a function in", vm)?; + if !args.func.downcastable::() && !args.func.downcastable::() { return Err(bad_argument( FUNCNAME, "argument 2", "a function", - &func, + args.func, vm, )); } - let code = crossinterp::script_code(&func, vm)?; - run_code_in(id, code, shared.as_deref(), vm) + let code = crossinterp::script_code(args.func, vm)?; + run_code_in(id, code, args.shared.into_option(), vm) } #[pyfunction] - fn call(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - const FUNCNAME: &str = "_interpreters.call"; - let parsed = ArgSpec { - fname: FUNCNAME, - keywords: &[ - "id", - "callable", - "args", - "kwargs", - "preserve_exc", - "restrict", - ], - required: 2, - max_positional: 4, - } - .parse_with( - &args, - |i, obj, vm| match i { - 2 => obj - .downcastable::() - .then_some(()) - .ok_or_else(|| bad_argument(FUNCNAME, "argument 3", "tuple", obj, vm)), - 3 => check_dict(obj, FUNCNAME, "argument 4", vm), - _ => Ok(()), - }, - vm, - )?; - // preserve_exc is accepted and ignored: an unpickled exception is - // always a new object. - let restrict = flag(parsed[5].as_deref(), vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; - resolve_interp(Some(id), restrict, true, "make a call in", vm)?; - - let callable = parsed[1].as_deref().unwrap(); + fn call(args: CallArgs<'_>, vm: &VirtualMachine) -> PyResult { + let _ = args.preserve_exc; + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; + resolve_interp(Some(id), restricted, true, "make a call in", vm)?; + + let callable = args.callable; if !callable.is_callable() { let repr = callable.repr(vm)?; return Err(vm.new_type_error(format!("expected a callable, got {repr}"))); } let func = SharedValue::from_callable(callable, vm)?; - let packed_args = match parsed[2].as_deref() { - Some(o) - if !o - .downcast_ref::() - .unwrap() - .as_slice() - .is_empty() => - { - Some(SharedValue::from_object(o, Fallback::Full, vm)?) + let packed_args = match args.args.as_ref().into_option() { + Some(o) if !o.as_slice().is_empty() => { + Some(SharedValue::from_object(o.as_object(), Fallback::Full, vm)?) } _ => None, }; - let packed_kwargs = match parsed[3].as_deref() { - Some(o) if !o.downcast_ref::().unwrap().is_empty() => { - Some(SharedValue::from_object(o, Fallback::Full, vm)?) + let packed_kwargs = match args.kwargs.as_ref().into_option() { + Some(o) if !o.is_empty() => { + Some(SharedValue::from_object(o.as_object(), Fallback::Full, vm)?) } _ => None, }; @@ -899,30 +894,11 @@ pub(crate) mod _interpreters { } #[pyfunction(name = "set___main___attrs")] - fn set_main_attrs(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - const FUNCNAME: &str = "_interpreters.set___main___attrs"; - let parsed = ArgSpec { - fname: FUNCNAME, - keywords: &["id", "updates", "restrict"], - required: 2, - max_positional: 2, - } - .parse_with( - &args, - |i, obj, vm| match i { - 1 => check_dict(obj, FUNCNAME, "argument 2", vm), - _ => Ok(()), - }, - vm, - )?; - let restrict = flag(parsed[2].as_deref(), vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; - resolve_interp(Some(id), restrict, true, "update __main__ for", vm)?; - let updates = parsed[1] - .as_deref() - .unwrap() - .downcast_ref::() - .unwrap(); + fn set_main_attrs(args: SetMainAttrsArgs<'_>, vm: &VirtualMachine) -> PyResult<()> { + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; + resolve_interp(Some(id), restricted, true, "update __main__ for", vm)?; + let updates = args.updates; if updates.is_empty() { return Err(vm.new_value_error("arg 2 must be a non-empty dict")); } @@ -960,20 +936,13 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn incref(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let parsed = ArgSpec { - fname: "incref", - keywords: &["id", "implieslink", "restrict"], - required: 1, - max_positional: 1, - } - .parse(&args, vm)?; - let implieslink = flag(parsed[1].as_deref(), vm)?; - let restricted = flag(parsed[2].as_deref(), vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; + fn incref(args: IncrefArgs<'_>, vm: &VirtualMachine) -> PyResult<()> { + let implies_link = args.implieslink.into_bool(); + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; resolve_interp(Some(id), restricted, true, "incref", vm)?; let state = runtime::lookup_interpreter(id).ok_or_else(|| interpreter_not_found(vm, id))?; - if implieslink { + if implies_link { // Decref to 0 will destroy the interpreter. state.require_idref.store(true, Ordering::Release); } @@ -982,16 +951,9 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn decref(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - let parsed = ArgSpec { - fname: "decref", - keywords: &["id", "restrict"], - required: 1, - max_positional: 1, - } - .parse(&args, vm)?; - let restricted = flag(parsed[1].as_deref(), vm)?; - let id = parse_id(parsed[0].as_deref().unwrap(), vm)?; + fn decref(args: InterpreterIdArgs<'_>, vm: &VirtualMachine) -> PyResult<()> { + let restricted = args.restrict.into_bool(); + let id = parse_id(args.id, vm)?; resolve_interp(Some(id), restricted, true, "decref", vm)?; let state = runtime::lookup_interpreter(id).ok_or_else(|| interpreter_not_found(vm, id))?; let prev = state.id_refcount.fetch_sub(1, Ordering::AcqRel); @@ -1007,23 +969,11 @@ pub(crate) mod _interpreters { } #[pyfunction] - fn capture_exception(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let parsed = ArgSpec { - fname: "capture_exception", - keywords: &["exc"], - required: 0, - max_positional: 1, - } - .parse(&args, vm)?; - let exc = match parsed - .into_iter() - .next() - .unwrap() - .filter(|e| !vm.is_none(e)) - { + fn capture_exception(args: CaptureExceptionArgs<'_>, vm: &VirtualMachine) -> PyResult { + let exc = match args.exc.into_option().filter(|exc| !vm.is_none(exc)) { Some(e) => e - .downcast::() - .map_err(|e| { + .downcast_ref::() + .ok_or_else(|| { let repr = e .repr(vm) .map_or_else(|_| e.class().name().to_string(), |s| s.to_string()); @@ -1033,6 +983,6 @@ pub(crate) mod _interpreters { // no Python code is running, so there is never one to capture here. None => return Ok(vm.ctx.none()), }; - Ok(ExcInfo::capture(&exc, vm).into_namespace(vm)) + Ok(ExcInfo::capture(exc, vm).into_namespace(vm)) } } diff --git a/crates/vm/src/stdlib/_io.rs b/crates/vm/src/stdlib/_io.rs index d4cd66e1491..2a950cc3d7e 100644 --- a/crates/vm/src/stdlib/_io.rs +++ b/crates/vm/src/stdlib/_io.rs @@ -23,9 +23,44 @@ use crate::{ AsObject, PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyModule, PyOSError}, }; +#[cfg(all(feature = "host_env", feature = "stdio"))] +pub(crate) use _io::default_text_encoding; pub use _io::{OpenArgs, io_open as open}; use rustpython_host_env::io as host_io; +/// Mirror the file descriptor conversion used by FileIO and WindowsConsoleIO. +#[cfg(feature = "host_io")] +fn open_file_descriptor(name: &PyObject, vm: &VirtualMachine) -> PyResult> { + if name.class().is(vm.ctx.types.bool_type) { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.runtime_warning, + "bool is used as a file descriptor".to_owned(), + 1, + vm, + )?; + } + // CPython clears failed integer conversions and then tries a path. Do not + // turn a failed conversion into a negative descriptor error. + let fd = if let Some(i) = name.downcast_ref::() { + i.try_to_primitive::(vm).ok() + } else { + name.try_index_opt(vm) + .and_then(Result::ok) + .and_then(|i| i.try_to_primitive::(vm).ok()) + }; + if fd.is_some_and(|fd| fd < 0) { + return Err(vm.new_value_error("negative file descriptor")); + } + Ok(fd) +} + +/// Return a non-owning descriptor snapshot of a native Windows console stream. +#[doc(hidden)] +#[cfg(all(feature = "host_env", windows))] +pub fn raw_windows_console_fd(obj: &PyObject) -> Option { + winconsoleio::raw_console_fd(obj) +} + fn file_closed(file: &PyObject, vm: &VirtualMachine) -> PyResult { file.get_attr("closed", vm)?.try_to_bool(vm) } @@ -68,6 +103,14 @@ pub struct Fildes(pub i32); impl TryFromObject for Fildes { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { use crate::builtins::int; + if obj.class().is(vm.ctx.types.bool_type) { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.runtime_warning, + "bool is used as a file descriptor".to_owned(), + 1, + vm, + )?; + } let int = match obj.downcast::() { Ok(i) => i, Err(obj) => { @@ -220,28 +263,31 @@ mod _io { } // truncate reports None. Missing still means the current position. - #[derive(Clone, Copy, FromArgs)] + #[derive(FromArgs)] struct OptionalPos { #[pyarg(positional, optional)] - size: Option, + size: Option, } - #[derive(Clone, Copy, FromArgs)] + #[derive(FromArgs)] struct StringIOPos { #[pyarg(positional, optional)] - pos: Option, - } - - impl StringIOPos { - fn as_optional(self) -> OptionalPos { - OptionalPos { size: self.pos } - } + pos: Option, } - impl OptionalPos { - fn try_usize(self, vm: &VirtualMachine) -> PyResult> { - OptionalSize { size: self.size }.try_usize(vm) - } + // Memory streams check closed/exported state before invoking __index__. + // Keep that conversion outside their storage locks, then recheck the state. + fn memory_truncate_pos( + pos: Option, + name: &str, + vm: &VirtualMachine, + ) -> PyResult> { + pos.map(|pos| { + let pos = core::ffi::c_long::try_from_object(vm, pos)?; + usize::try_from(pos) + .map_err(|_| vm.new_value_error(format!("negative {name} value {pos}"))) + }) + .transpose() } // peek ignores the value and returns the buffer. @@ -264,10 +310,10 @@ mod _io { pub whence: i32, } + // IOBase and TextIOWrapper spell the same zero default symbolically. #[derive(FromArgs)] - #[allow(dead_code)] - struct IgnoredWhence { - #[pyarg(positional, default)] + struct SeekWhenceArg { + #[pyarg(positional, default, py_default = "os.SEEK_SET")] whence: i32, } @@ -298,7 +344,7 @@ mod _io { pos: Option, } - #[cfg(feature = "host_env")] + #[cfg(feature = "host_io")] #[derive(FromArgs)] pub(super) struct ObjLen { #[pyarg(positional, optional)] @@ -329,18 +375,6 @@ mod _io { pub(super) fn to_usize(self) -> Option { self.size?.to_usize() } - - pub(super) fn try_usize(self, vm: &VirtualMachine) -> PyResult> { - self.size - .map(|v| { - if v >= 0 { - Ok(v as usize) - } else { - Err(vm.new_value_error(format!("Negative size value {v}"))) - } - }) - .transpose() - } } fn os_err(vm: &VirtualMachine, err: io::Error) -> PyBaseExceptionRef { @@ -355,20 +389,6 @@ mod _io { #[pyattr] const DEFAULT_BUFFER_SIZE: usize = super::DEFAULT_BUFFER_SIZE; - pub(super) fn seekfrom( - vm: &VirtualMachine, - offset: PyObjectRef, - how: i32, - ) -> PyResult { - let seek = match how { - 0 => SeekFrom::Start(offset.try_into_value(vm)?), - 1 => SeekFrom::Current(offset.try_into_value(vm)?), - 2 => SeekFrom::End(offset.try_into_value(vm)?), - _ => return Err(vm.new_value_error("invalid value for how")), - }; - Ok(seek) - } - #[derive(Debug)] struct BufferedIO { cursor: Cursor>, @@ -520,14 +540,14 @@ mod _io { #[pyclass( with(IterNext, Iterable, Destructor), - flags(BASETYPE, HAS_DICT, HAS_WEAKREF) + flags(BASETYPE, HAS_DICT, HAS_WEAKREF, HEAPTYPE) )] impl _IOBase { #[pymethod] fn seek( zelf: PyObjectRef, _offset: PyObjectRef, - _whence: IgnoredWhence, + _whence: SeekWhenceArg, vm: &VirtualMachine, ) -> PyResult { _unsupported(vm, &zelf, "seek") @@ -762,10 +782,13 @@ mod _io { ))); } let n = n as usize; - let mut bytes = b.borrow_buf_mut(); - bytes.truncate(n); - // FIXME: try to use Arc::unwrap on the bytearray to get at the inner buffer - bytes.clone().to_pyobject(vm) + let mut inner = b.try_resizable(vm)?; + let bytes = &mut inner.elements; + bytes + .try_reserve_exact(n.saturating_sub(bytes.len())) + .map_err(|_| vm.no_memory_error())?; + bytes.resize(n, 0); + core::mem::take(bytes).to_pyobject(vm) } }) } else { @@ -946,7 +969,7 @@ mod _io { #[derive(FromArgs, Clone)] struct BufferSize { // 128 * 1024, the module buffer size. - #[pyarg(any, default = 131072)] + #[pyarg(any, default = DEFAULT_BUFFER_SIZE as isize, py_default = "DEFAULT_BUFFER_SIZE")] buffer_size: isize, } @@ -954,7 +977,7 @@ mod _io { struct BufferedInitArgs { #[pyarg(any)] raw: PyObjectRef, - #[pyarg(any, default = 131072)] + #[pyarg(any, default = DEFAULT_BUFFER_SIZE as isize, py_default = "DEFAULT_BUFFER_SIZE")] buffer_size: isize, } @@ -964,7 +987,7 @@ mod _io { reader: PyObjectRef, #[pyarg(positional)] writer: PyObjectRef, - #[pyarg(positional, default = 131072)] + #[pyarg(positional, default = DEFAULT_BUFFER_SIZE as isize, py_default = "DEFAULT_BUFFER_SIZE")] buffer_size: isize, } @@ -1231,7 +1254,7 @@ mod _io { // Restore internal buffer if we borrowed it if let Some(wb) = write_buf { - mem_obj.release(); + mem_obj.release_buffer(); self.buffer = wb.take(); } @@ -1436,6 +1459,7 @@ mod _io { match ($x, written > 0) { (Some(0), _) | (None, true) => { out.truncate(written); + out.shrink_to_fit(); return Ok(Some(out)); } (Some(r), _) => r, @@ -1526,7 +1550,7 @@ mod _io { } }; - mem_obj.release(); + mem_obj.release_buffer(); // Always restore the buffer, even if an error occurred *v = read_buf.take(); @@ -1773,6 +1797,63 @@ mod _io { } } + #[cfg(feature = "threading")] + fn shutdown_buffer_description( + class_name: &str, + raw: Option, + vm: &VirtualMachine, + ) -> String { + // Fatal diagnostics must not acquire an I/O lock or invoke user code. + // Inspect dictionary entries directly, avoiding custom attribute, + // equality, and repr implementations even on unusual raw streams. + // Limit diagnostic metadata; standard stream names are short and are + // among the first attributes installed on their FileIO objects. + let name = raw.and_then(|raw| raw.dict()).and_then(|dict| { + dict.into_iter().take(16).find_map(|(key, value)| { + let key = key.downcast_ref::()?; + if key.as_wtf8() != "name" || !value.class().is(vm.ctx.types.str_type) { + return None; + } + let name = value.downcast_ref::()?; + if name.byte_len() > 1024 { + return None; + } + PyStr::repr(name, vm).ok() + }) + }); + match name { + Some(name) => format!("<_io.{class_name} name={name}>"), + None => format!("<_io.{class_name}>"), + } + } + + #[cfg(feature = "threading")] + fn shutdown_io_lock<'a, T>( + mutex: &'a PyThreadMutex, + vm: &VirtualMachine, + reentrant_error: &'static str, + describe: impl FnOnce() -> String, + ) -> PyResult> { + use crate::common::lock::TryLockThreadError; + // Daemon threads may have parked permanently while owning this lock. + // Match _enter_buffered_busy's one-second grace period, including for + // RustPython's additional TextIOWrapper lock. + match mutex.try_lock_for_wrapped(core::time::Duration::from_secs(1), |wait| { + vm.allow_threads(wait) + }) { + Ok(guard) => Ok(guard), + Err(TryLockThreadError::Current) => Err(vm.new_runtime_error(reentrant_error)), + Err(TryLockThreadError::Other) => { + let message = format!( + "Fatal Python error: _enter_buffered_busy: could not acquire lock for {} at interpreter shutdown, possibly due to daemon threads\n", + describe() + ); + let _ = crate::host_env::crt_fd::write_noraise(2, message.as_bytes()); + crate::host_env::os::abort() + } + } + } + #[pyclass] trait BufferedMixin: PyPayload + StaticType { const CLASS_NAME: &'static str; @@ -1786,6 +1867,21 @@ mod _io { fn finalizing(&self) -> &AtomicBool; fn lock(&self, vm: &VirtualMachine) -> PyResult> { + #[cfg(feature = "threading")] + if vm.state.finalizing.load(Ordering::Acquire) { + return shutdown_io_lock( + self.data(), + vm, + "reentrant call inside buffered io", + || { + shutdown_buffer_description( + Self::CLASS_NAME, + self.raw_cell().load_owned(), + vm, + ) + }, + ); + } self.data() .lock_wrapped(|do_lock| vm.allow_threads(do_lock)) .ok_or_else(|| vm.new_runtime_error("reentrant call inside buffered io")) @@ -1796,7 +1892,7 @@ mod _io { let zelf: &Py = zelf.try_to_ref(vm)?; let (raw, BufferSize { buffer_size }): (PyObjectRef, _) = args.bind(vm).map_err(|e| { - let str_repr = e.__str__(vm).as_wtf8().to_owned(); + let str_repr = e.diagnostic_str(vm).as_wtf8().to_owned(); let msg = format!("{}() {}", Self::CLASS_NAME, str_repr); vm.new_exception_msg(e.class().to_owned(), msg.into()) })?; @@ -1908,20 +2004,28 @@ mod _io { vm.call_method(data.check_init(zelf.raw_cell(), vm)?, "seekable", ()) } - /// Get raw stream without holding the lock (for calling Python code safely) + /// These forwarding operations do not enter CPython's buffered I/O + /// lock. A raw callback may query closed or flush a read-only buffer + /// while readinto holds that lock. RawCell supplies an owned reference + /// without borrowing the mutable BufferedData used by the active read. fn get_raw_unlocked(&self, vm: &VirtualMachine) -> PyResult { + if let Some(raw) = self.raw_cell().load_owned() { + return Ok(raw); + } + // Keep the distinct detached/uninitialized diagnostics. Retry the + // raw lookup under the lock in case initialization raced us. let data = self.lock(vm)?; data.raw_owned(self.raw_cell(), vm) } // Payload helper. BufferedRWPair calls this on its embedded writer. - fn closed(&self, vm: &VirtualMachine) -> PyResult { + fn closed_impl(&self, vm: &VirtualMachine) -> PyResult { self.get_raw_unlocked(vm)?.get_attr("closed", vm) } - #[pygetset(name = "closed")] - fn py_closed(zelf: &Py, vm: &VirtualMachine) -> PyResult { - zelf.closed(vm) + #[pygetset] + fn closed(zelf: &Py, vm: &VirtualMachine) -> PyResult { + zelf.closed_impl(vm) } #[pygetset] @@ -1940,15 +2044,16 @@ mod _io { vm.call_method(data.check_init(zelf.raw_cell(), vm)?, "fileno", ()) } - // Payload helper. BufferedRWPair calls this on its embedded reader and writer. - fn isatty(&self, vm: &VirtualMachine) -> PyResult { - let data = self.lock(vm)?; - vm.call_method(data.check_init(self.raw_cell(), vm)?, "isatty", ()) + // Hold an owned snapshot of the raw stream, not the BufferedData lock, + // across these calls to Python. + fn call_raw_noargs(&self, name: &'static str, vm: &VirtualMachine) -> PyResult { + let raw = self.get_raw_unlocked(vm)?; + vm.call_method(&raw, name, ()) } - #[pymethod(name = "isatty")] - fn py_isatty(zelf: &Py, vm: &VirtualMachine) -> PyResult { - zelf.isatty(vm) + #[pymethod] + fn isatty(zelf: &Py, vm: &VirtualMachine) -> PyResult { + zelf.call_raw_noargs("isatty", vm) } #[pyslot] @@ -2003,13 +2108,21 @@ mod _io { } #[pymethod] - fn readable(_zelf: &Py) -> bool { - Self::READABLE + fn readable(zelf: &Py, vm: &VirtualMachine) -> PyResult { + if Self::READABLE { + zelf.call_raw_noargs("readable", vm) + } else { + Ok(vm.ctx.false_value.clone().into()) + } } #[pymethod] - fn writable(_zelf: &Py) -> bool { - Self::WRITABLE + fn writable(zelf: &Py, vm: &VirtualMachine) -> PyResult { + if Self::WRITABLE { + zelf.call_raw_noargs("writable", vm) + } else { + Ok(vm.ctx.false_value.clone().into()) + } } #[pymethod] @@ -2018,13 +2131,13 @@ mod _io { } #[pymethod] - fn __reduce_ex__(zelf: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { + fn __reduce_ex__(zelf: PyObjectRef, protocol: usize, vm: &VirtualMachine) -> PyResult { if zelf.class().is(Self::static_type()) { return Err( vm.new_type_error(format!("cannot pickle '{}' object", zelf.class().name())) ); } - let _ = proto; + let _ = protocol; reduce_ex_for_subclass(&zelf, vm) } @@ -2144,13 +2257,9 @@ mod _io { #[pymethod] fn flush(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { - // For read-only buffers, flush just calls raw.flush() - // Don't hold the lock while calling Python code to avoid reentrant lock issues - let raw = { - let data = zelf.reader().lock(vm)?; - data.raw_owned(zelf.reader().raw_cell(), vm)? - }; - ensure_unclosed(&raw, "flush of closed file", vm)?; + // BufferedReader uses _Buffered_simple_flush, not the writer's + // flush-and-rewind operation. The raw stream handles closed errors. + let raw = zelf.reader().get_raw_unlocked(vm)?; vm.call_method(&raw, "flush", ())?; Ok(()) } @@ -2296,7 +2405,7 @@ mod _io { } // Payload helper. BufferedRWPair calls this on its embedded writer. - fn flush(&self, vm: &VirtualMachine) -> PyResult<()> { + fn flush_impl(&self, vm: &VirtualMachine) -> PyResult<()> { let mut data = self.writer().lock(vm)?; let raw_cell = self.writer().raw_cell(); let raw = data.check_init(raw_cell, vm)?; @@ -2304,9 +2413,9 @@ mod _io { data.flush_rewind(raw_cell, vm) } - #[pymethod(name = "flush")] - fn py_flush(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { - zelf.flush(vm) + #[pymethod] + fn flush(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + zelf.flush_impl(vm) } } @@ -2567,31 +2676,31 @@ mod _io { impl Py { #[pymethod] fn flush(&self, vm: &VirtualMachine) -> PyResult<()> { - self.write.flush(vm) + self.write.flush_impl(vm) } #[pymethod] - const fn readable(&self) -> bool { - true + fn readable(&self, vm: &VirtualMachine) -> PyResult { + self.read.call_raw_noargs("readable", vm) } + #[pymethod] - const fn writable(&self) -> bool { - true + fn writable(&self, vm: &VirtualMachine) -> PyResult { + self.write.call_raw_noargs("writable", vm) } #[pygetset] fn closed(&self, vm: &VirtualMachine) -> PyResult { - self.write.closed(vm) + self.write.closed_impl(vm) } #[pymethod] fn isatty(&self, vm: &VirtualMachine) -> PyResult { - // read.isatty() or write.isatty() - let res = self.read.isatty(vm)?; - if res.try_to_bool(vm)? { - Ok(res) + let res = self.write.call_raw_noargs("isatty", vm)?; + if res.is(&vm.ctx.false_value) { + self.read.call_raw_noargs("isatty", vm) } else { - self.write.isatty(vm) + Ok(res) } } @@ -2810,9 +2919,19 @@ mod _io { } // TODO: implement legit fast-paths for other encodings - type EncodeFunc = fn(PyStrRef) -> PendingWrite; - const fn textio_encode_utf8(s: PyStrRef) -> PendingWrite { - PendingWrite::Utf8(s) + type EncodeFunc = fn(PyStrRef, &Py, &VirtualMachine) -> PyResult; + fn textio_encode_utf8( + text: PyStrRef, + errors: &Py, + vm: &VirtualMachine, + ) -> PyResult { + use crate::codecs::{ErrorsHandler, PyEncodeContext}; + use crate::common::encodings::utf8; + + let context = PyEncodeContext::new(utf8::ENCODING_NAME, &text, vm); + let errors = ErrorsHandler::new(Some(errors), vm); + let bytes = utf8::encode(context, &errors)?; + Ok(PendingWrite::Bytes(vm.ctx.new_bytes(bytes))) } #[derive(Debug)] @@ -2875,8 +2994,8 @@ mod _io { } } } - fn take(&mut self, vm: &VirtualMachine) -> PyBytesRef { - let Self { num_bytes, data } = core::mem::take(self); + fn into_bytes(self, vm: &VirtualMachine) -> PyBytesRef { + let Self { num_bytes, data } = self; if let PendingWritesData::One(PendingWrite::Bytes(b)) = data { return b; } @@ -3074,7 +3193,6 @@ mod _io { #[derive(Debug)] struct TextIOWrapper { _base: _TextIOBase, - #[pymember] buffer: RawCell, #[pymember] encoding: RawCell, @@ -3118,12 +3236,7 @@ mod _io { TextIOWrapperInitArgs { buffer, args }: Self::Args, vm: &VirtualMachine, ) -> PyResult<()> { - zelf.buffer.store(None); - zelf.encoding.store(None); - zelf.line_buffering.store(false, Ordering::Relaxed); - zelf.write_through.store(false, Ordering::Relaxed); - let mut data = zelf.lock_opt(vm)?; - *data = None; + zelf.clear_for_init(vm)?; let encoding = Self::resolve_encoding(args.encoding, vm)?; @@ -3149,12 +3262,11 @@ mod _io { None => false, }; - zelf.buffer.store(Some(buffer)); zelf.encoding.store(Some(encoding.into())); zelf.line_buffering.store(line_buffering, Ordering::Relaxed); zelf.write_through.store(write_through, Ordering::Relaxed); - *data = Some(TextIOData { + let new_data = TextIOData { encoder, decoder, errors, @@ -3169,31 +3281,83 @@ mod _io { decoded_chars: None, decoded_chars_used: Utf8size::default(), b2cratio: 0.0, - }); + }; + let previous_data; + let _ = { + let mut data = zelf.lock_opt(vm)?; + previous_data = data.replace(new_data); + // Publish the buffer last: an owned non-null buffer is the + // fast-path witness that initialization finished. A slow-path + // reader waits for this guard and rechecks the buffer. + zelf.buffer.store(Some(buffer)) + }; + if let Some(data) = previous_data { + data.clear(); + } Ok(()) } fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { let zelf_ref: &Py = zelf.try_to_ref(vm)?; - { - zelf_ref.buffer.store(None); - zelf_ref.encoding.store(None); - zelf_ref.line_buffering.store(false, Ordering::Relaxed); - zelf_ref.write_through.store(false, Ordering::Relaxed); - let mut data = zelf_ref.lock_opt(vm)?; - *data = None; - } + zelf_ref.clear_for_init(vm)?; let parsed = args.bind_for(vm, Self::NAME)?; Self::init(zelf_ref, parsed, vm) } } impl TextIOWrapper { + fn clear_for_init(&self, vm: &VirtualMachine) -> PyResult<()> { + let previous_data; + let _ = { + let mut data = self.lock_opt(vm)?; + previous_data = data.take(); + // Invalidate both under the same guard. Returned references + // are released outside it, with the buffer released first. + self.buffer.store(None) + }; + self.encoding.store(None); + self.line_buffering.store(false, Ordering::Relaxed); + self.write_through.store(false, Ordering::Relaxed); + if let Some(data) = previous_data { + data.clear(); + } + Ok(()) + } + + fn initialized_buffer(&self, vm: &VirtualMachine) -> PyResult { + if let Some(buffer) = self.buffer.load_owned() { + return Ok(buffer); + } + // None may mean initialization, detachment, or a racing init. + // Checking data first preserves uninitialized-before-detached. + let _data = self.lock(vm)?; + text_buffer(&self.buffer, vm) + } + fn lock_opt( &self, vm: &VirtualMachine, ) -> PyResult>> { + #[cfg(feature = "threading")] + if vm.state.finalizing.load(Ordering::Acquire) { + return shutdown_io_lock(&self.data, vm, "reentrant call inside textio", || { + let Some(buffer) = self.buffer.load_owned() else { + return "<_io.TextIOWrapper>".to_owned(); + }; + let (class_name, raw) = + if let Some(buffer) = buffer.downcast_ref::() { + (BufferedWriter::CLASS_NAME, buffer.raw.load_owned()) + } else if let Some(buffer) = buffer.downcast_ref::() { + (BufferedReader::CLASS_NAME, buffer.raw.load_owned()) + } else if let Some(buffer) = buffer.downcast_ref::() { + (BufferedRandom::CLASS_NAME, buffer.raw.load_owned()) + } else { + return format!("<{}>", buffer.class().slot_name()); + }; + shutdown_buffer_description(class_name, raw, vm) + }); + } self.data .lock_wrapped(|do_lock| vm.allow_threads(do_lock)) .ok_or_else(|| vm.new_runtime_error("reentrant call inside textio")) @@ -3205,6 +3369,145 @@ mod _io { .map_err(|_| vm.new_value_error("I/O operation on uninitialized object")) } + // Python subclasses can finalize on their last reference. Return the + // replaced value out of the guard's scope before releasing it, in the + // same order as CPython's Py_XSETREF / Py_CLEAR operations. + fn set_decoded_chars(&self, chars: Option, vm: &VirtualMachine) -> PyResult<()> { + let _ = { + let mut data = self.lock(vm)?; + core::mem::replace(&mut data.decoded_chars, chars) + }; + self.lock(vm)?.decoded_chars_used = Utf8size::default(); + Ok(()) + } + + fn set_snapshot( + &self, + snapshot: Option<(i32, PyBytesRef)>, + vm: &VirtualMachine, + ) -> PyResult<()> { + let _ = { + let mut data = self.lock(vm)?; + core::mem::replace(&mut data.snapshot, snapshot) + }; + Ok(()) + } + + fn take_decoded_chars( + &self, + append: Option, + vm: &VirtualMachine, + ) -> PyResult { + let empty_str = || vm.ctx.empty_str.to_owned(); + let (chars_pos, decoded_chars) = { + let mut data = self.lock(vm)?; + ( + core::mem::take(&mut data.decoded_chars_used).bytes, + data.decoded_chars.take(), + ) + }; + let decoded_chars = match decoded_chars { + None => return Ok(append.unwrap_or_else(empty_str)), + Some(s) if s.is_empty() => return Ok(append.unwrap_or_else(empty_str)), + Some(s) => s, + }; + let append_len = append.as_ref().map_or(0, |s| s.byte_len()); + if append_len == 0 && chars_pos == 0 { + return Ok(decoded_chars); + } + // TODO: in-place editing of `str` when refcount == 1 + let decoded_chars_unused = &decoded_chars.as_wtf8()[chars_pos..]; + let mut s = Wtf8Buf::with_capacity(decoded_chars_unused.len() + append_len); + s.push_wtf8(decoded_chars_unused); + if let Some(append) = append { + s.push_wtf8(append.as_wtf8()) + } + Ok(PyStr::from(s).into_ref(&vm.ctx)) + } + + fn write_pending(&self, vm: &VirtualMachine) -> PyResult<()> { + let pending = { + let mut data = self.lock(vm)?; + if data.pending.num_bytes == 0 { + return Ok(()); + } + core::mem::take(&mut data.pending) + }; + let pending = pending.into_bytes(vm); + let buffer = text_buffer(&self.buffer, vm)?; + vm.call_method(&buffer, "write", (pending,))?; + Ok(()) + } + + // No TextIOData borrow may cross a Python callback. In particular, a + // raw read can detach this wrapper and a decoder can seek it again. + // Keep the callback's receiver alive, then update the current state. + fn read_chunk(&self, size_hint: usize, vm: &VirtualMachine) -> PyResult { + let (decoder, telling) = { + let data = self.lock(vm)?; + let decoder = data + .decoder + .clone() + .ok_or_else(|| new_unsupported_operation("not readable", vm))?; + (decoder, data.telling) + }; + let dec_state = if telling { + let state = vm.call_method(&decoder, "getstate", ())?; + Some(parse_decoder_state(state, vm)?) + } else { + None + }; + let (method, chunk_size, buffer) = { + let data = self.lock(vm)?; + let size_hint = if size_hint > 0 { + (data.b2cratio.max(1.0) * size_hint as f64) as usize + } else { + size_hint + }; + ( + if data.has_read1 { "read1" } else { "read" }, + core::cmp::max(data.chunk_size, size_hint), + text_buffer(&self.buffer, vm)?, + ) + }; + let input_chunk = vm.call_method(&buffer, method, (chunk_size,))?; + let buf = ArgBytesLike::try_from_borrowed_object(vm, &input_chunk).map_err(|_| { + vm.new_type_error(format!( + "underlying {}() should have returned a bytes-like object, not '{}'", + method, + input_chunk.class().name() + )) + })?; + let nbytes = buf.borrow_buf().len(); + let decoder = self + .lock(vm)? + .decoder + .clone() + .ok_or_else(|| new_unsupported_operation("not readable", vm))?; + let decoded = vm.call_method(&decoder, "decode", (input_chunk, nbytes == 0))?; + let decoded = check_decoded(decoded, vm)?; + let char_len = decoded.char_len(); + self.set_decoded_chars(Some(decoded), vm)?; + let telling = { + let mut data = self.lock(vm)?; + data.b2cratio = if char_len > 0 { + nbytes as f64 / char_len as f64 + } else { + 0.0 + }; + data.telling + }; + if telling && let Some((dec_buffer, dec_flags)) = dec_state { + let mut next_input = dec_buffer.as_bytes().to_vec(); + next_input.extend_from_slice(&buf.borrow_buf()); + self.set_snapshot( + Some((dec_flags, PyBytes::from(next_input).into_ref(&vm.ctx))), + vm, + )?; + } + Ok(nbytes == 0 && char_len == 0) + } + fn validate_errors(errors: &Py, vm: &VirtualMachine) -> PyResult<()> { if errors.as_pystr().contains_nuls() { cold_path(); @@ -3335,7 +3638,7 @@ mod _io { } Err(err) => return Err(err), }; - let encoding_name = vm.get_attribute_opt(&incremental_encoder, "name")?; + let encoding_name = vm.get_attribute_opt(codec.as_tuple().as_object(), "name")?; let encode_func = encoding_name.and_then(|name| { let name = name.downcast_ref::()?; match name.to_str()? { @@ -3381,14 +3684,6 @@ mod _io { } } - #[inline] - fn flush_inner(textio: &mut TextIOData, buffer: &PyObject, vm: &VirtualMachine) -> PyResult { - textio.check_closed(buffer, vm)?; - textio.telling = textio.seekable; - textio.write_pending(buffer, vm)?; - vm.call_method(buffer, "flush", ()) - } - fn text_buffer(cell: &RawCell, vm: &VirtualMachine) -> PyResult { cell.load_owned() .ok_or_else(|| vm.new_value_error("underlying buffer has been detached")) @@ -3424,13 +3719,16 @@ mod _io { args: TextIOWrapperReconfigureArgs, vm: &VirtualMachine, ) -> PyResult<()> { - let mut data = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; - data.check_closed(&buffer, vm)?; - + let buffer = { + let _data = self.lock(vm)?; + text_buffer(&self.buffer, vm)? + }; + check_closed(&buffer, vm)?; let mut encoding = textio_encoding(&self.encoding, vm)?; - let mut errors = data.errors.clone(); - let mut newline = data.newline; + let (mut errors, mut newline) = { + let data = self.lock(vm)?; + (data.errors.clone(), data.newline) + }; let mut encoding_changed = false; let mut errors_changed = false; let mut newline_changed = false; @@ -3469,40 +3767,49 @@ mod _io { write_through = Some(TextIOWrapper::bool_from_index(&value, vm)?); } - if (encoding_changed || newline_changed) - && data.decoder.is_some() - && (data.decoded_chars.is_some() - || data.snapshot.is_some() - || data.decoded_chars_used.chars != 0) { - return Err(new_unsupported_operation( - "cannot reconfigure encoding or newline after reading from the stream", - vm, - )); - } - - if data.pending.num_bytes > 0 { - data.write_pending(&buffer, vm)?; + let data = self.lock(vm)?; + if (encoding_changed || newline_changed) + && data.decoder.is_some() + && (data.decoded_chars.is_some() + || data.snapshot.is_some() + || data.decoded_chars_used.chars != 0) + { + return Err(new_unsupported_operation( + "cannot reconfigure encoding or newline after reading from the stream", + vm, + )); + } } + self.write_pending(vm)?; + let buffer = text_buffer(&self.buffer, vm)?; vm.call_method(&buffer, "flush", ())?; if encoding_changed || errors_changed || newline_changed { - if data.pending.num_bytes > 0 { - data.write_pending(&buffer, vm)?; - } + self.write_pending(vm)?; + let buffer = text_buffer(&self.buffer, vm)?; let (encoder, decoder) = TextIOWrapper::find_coder(&buffer, encoding.as_str(), &errors, newline, vm)?; self.encoding.store(Some(encoding.clone().into())); - data.errors = errors; - data.newline = newline; - data.encoder = encoder; - data.decoder = decoder; - data.set_decoded_chars(None); - data.snapshot = None; - data.decoded_chars_used = Utf8size::default(); - if let Some((encoder, _)) = &data.encoder { + let _ = { + let mut data = self.lock(vm)?; + core::mem::replace(&mut data.errors, errors) + }; + self.lock(vm)?.newline = newline; + let _ = { + let mut data = self.lock(vm)?; + core::mem::replace(&mut data.encoder, encoder) + }; + let _ = { + let mut data = self.lock(vm)?; + core::mem::replace(&mut data.decoder, decoder) + }; + self.set_decoded_chars(None, vm)?; + self.set_snapshot(None, vm)?; + let encoder = self.lock(vm)?.encoder.clone(); + if let Some((encoder, _)) = encoder { TextIOWrapper::adjust_encoder_state_for_bom( - encoder, + &encoder, encoding.as_str(), &buffer, vm, @@ -3521,9 +3828,9 @@ mod _io { #[pymethod] fn detach(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - let mut textio = zelf.lock(vm)?; + vm.call_method(zelf.as_object(), "flush", ())?; + let _data = zelf.lock(vm)?; let buffer = text_buffer(&zelf.buffer, vm)?; - flush_inner(&mut textio, &buffer, vm)?; zelf.buffer.store(None); Ok(buffer) } @@ -3552,13 +3859,19 @@ mod _io { vm.call_method(&buffer, "writable", ()) } + #[pygetset] + fn buffer(&self, vm: &VirtualMachine) -> PyResult { + let _data = self.lock(vm)?; + text_buffer(&self.buffer, vm) + } + #[pygetset] fn newlines(&self, vm: &VirtualMachine) -> PyResult> { - let data = self.lock(vm)?; - let Some(decoder) = &data.decoder else { + let decoder = self.lock(vm)?.decoder.clone(); + let Some(decoder) = decoder else { return Ok(None); }; - vm.get_attribute_opt(decoder, "newlines") + vm.get_attribute_opt(&decoder, "newlines") } #[pygetset(name = "_CHUNK_SIZE")] @@ -3568,35 +3881,36 @@ mod _io { #[pygetset(setter, name = "_CHUNK_SIZE")] fn set_chunksize(&self, value: PySetterValue, vm: &VirtualMachine) -> PyResult<()> { + let PySetterValue::Assign(object_value) = value else { + let class = self.class(); + let type_name = class.slot_name(); + let end = type_name.floor_char_boundary(type_name.len().min(100)); + return Err(vm.new_attribute_error(format!( + "attribute '_CHUNK_SIZE' of '{}' objects cannot be deleted", + &type_name[..end] + ))); + }; { - let textio = self.lock(vm)?; + let _textio = self.lock(vm)?; if self.buffer.deref().is_none() { return Err(vm.new_value_error("underlying buffer has been detached")); } - drop(textio); } - let chunk_size: isize = match value { - PySetterValue::Assign(object_value) => { - let integer = object_value.try_index(vm)?; + let integer = object_value.try_index(vm)?; - integer.try_to_primitive::(vm).map_err(|_| { - let class = object_value.class(); - let type_name = class.name(); - let mut end = type_name.len().min(200); - while !type_name.is_char_boundary(end) { - end -= 1; - } - vm.new_value_error(format!( - "cannot fit '{}' into an index-sized integer", - &type_name[..end] - )) - })? - } - PySetterValue::Delete => { - return Err(vm.new_attribute_error("cannot delete attribute")); + let chunk_size = integer.try_to_primitive::(vm).map_err(|_| { + let class = object_value.class(); + let type_name = class.name(); + let mut end = type_name.len().min(200); + while !type_name.is_char_boundary(end) { + end -= 1; } - }; + vm.new_value_error(format!( + "cannot fit '{}' into an index-sized integer", + &type_name[..end] + )) + })?; if chunk_size <= 0 { return Err(vm.new_value_error("a strictly positive integer is required")); @@ -3614,7 +3928,7 @@ mod _io { fn seek( zelf: PyRef, cookie: PyObjectRef, - whence: HowArg, + whence: SeekWhenceArg, vm: &VirtualMachine, ) -> PyResult { let how = whence.whence; @@ -3627,9 +3941,7 @@ mod _io { } }; - let textio = zelf.lock(vm)?; - - if !textio.seekable { + if !zelf.lock(vm)?.seekable { return Err(new_unsupported_operation( "underlying stream is not seekable", vm, @@ -3642,8 +3954,7 @@ mod _io { // SEEK_CUR 1 => { if vm.bool_eq(&cookie, vm.ctx.new_int(0).as_ref())? { - let buffer = text_buffer(&zelf.buffer, vm)?; - vm.call_method(&buffer, "tell", ())? + vm.call_method(zelf.as_object(), "tell", ())? } else { return Err(new_unsupported_operation( "can't do nonzero cur-relative seeks", @@ -3654,19 +3965,21 @@ mod _io { // SEEK_END 2 => { if vm.bool_eq(&cookie, vm.ctx.new_int(0).as_ref())? { - drop(textio); vm.call_method(zelf.as_object(), "flush", ())?; - let mut textio = zelf.lock(vm)?; - textio.set_decoded_chars(None); - textio.snapshot = None; - if let Some(decoder) = &textio.decoder { - vm.call_method(decoder, "reset", ())?; + let decoder = { + zelf.set_decoded_chars(None, vm)?; + zelf.set_snapshot(None, vm)?; + zelf.lock(vm)?.decoder.clone() + }; + if let Some(decoder) = decoder { + vm.call_method(&decoder, "reset", ())?; } let buffer = text_buffer(&zelf.buffer, vm)?; let res = vm.call_method(&buffer, "seek", (0, 2))?; - if let Some((encoder, _)) = &textio.encoder { + let encoder = zelf.lock(vm)?.encoder.clone(); + if let Some((encoder, _)) = encoder { let start_of_stream = vm.bool_eq(&res, vm.ctx.new_int(0).as_ref())?; - reset_encoder(encoder, start_of_stream)?; + reset_encoder(&encoder, start_of_stream)?; } return Ok(res); } @@ -3687,24 +4000,22 @@ mod _io { vm.new_value_error(format!("negative seek position {}", cookie.repr(vm)?)) ); } - drop(textio); vm.call_method(zelf.as_object(), "flush", ())?; let cookie_obj = crate::builtins::PyIntRef::try_from_object(vm, cookie)?; let cookie = TextIOCookie::parse(cookie_obj.as_bigint()) .ok_or_else(|| vm.new_value_error("invalid cookie"))?; - let mut textio = zelf.lock(vm)?; let buffer = text_buffer(&zelf.buffer, vm)?; vm.call_method(&buffer, "seek", (cookie.start_pos,))?; - textio.set_decoded_chars(None); - textio.snapshot = None; - if let Some(decoder) = &textio.decoder { - cookie.set_decoder_state(decoder, vm)?; + let decoder = { + zelf.set_decoded_chars(None, vm)?; + zelf.set_snapshot(None, vm)?; + zelf.lock(vm)?.decoder.clone() + }; + if let Some(decoder) = decoder { + cookie.set_decoder_state(&decoder, vm)?; } if cookie.chars_to_skip != 0 { - let decoder = textio - .decoder - .clone() - .ok_or_else(|| vm.new_value_error("invalid cookie"))?; + let buffer = text_buffer(&zelf.buffer, vm)?; let input_chunk = vm.call_method(&buffer, "read", (cookie.bytes_to_feed,))?; let input_chunk: PyBytesRef = input_chunk.downcast().map_err(|obj| { vm.new_type_error(format!( @@ -3712,7 +4023,13 @@ mod _io { obj.class().name() )) })?; - textio.snapshot = Some((cookie.dec_flags, input_chunk.clone())); + let decoder = { + zelf.set_snapshot(Some((cookie.dec_flags, input_chunk.clone())), vm)?; + zelf.lock(vm)? + .decoder + .clone() + .ok_or_else(|| vm.new_value_error("invalid cookie"))? + }; let decoded = vm.call_method(&decoder, "decode", (input_chunk, cookie.need_eof))?; let decoded = check_decoded(decoded, vm)?; // The position is stored both as a count of characters and as @@ -3721,68 +4038,86 @@ mod _io { let num_to_skip = cookie.num_to_skip(); let pos_is_valid = num_to_skip.chars <= decoded.char_len() && decoded.as_wtf8().is_code_point_boundary(num_to_skip.bytes); - textio.set_decoded_chars(Some(decoded)); + zelf.set_decoded_chars(Some(decoded), vm)?; if !pos_is_valid { return Err(vm.new_os_error("can't restore logical file position")); } - textio.decoded_chars_used = num_to_skip; + zelf.lock(vm)?.decoded_chars_used = num_to_skip; } else { - textio.snapshot = Some((cookie.dec_flags, PyBytes::from(vec![]).into_ref(&vm.ctx))) + zelf.set_snapshot( + Some((cookie.dec_flags, PyBytes::from(vec![]).into_ref(&vm.ctx))), + vm, + )?; } - if let Some((encoder, _)) = &textio.encoder { + let encoder = zelf.lock(vm)?.encoder.clone(); + if let Some((encoder, _)) = encoder { let start_of_stream = cookie.start_pos == 0 && cookie.dec_flags == 0; - reset_encoder(encoder, start_of_stream)?; + reset_encoder(&encoder, start_of_stream)?; } Ok(cookie_obj.into()) } #[pymethod] fn tell(zelf: PyRef, vm: &VirtualMachine) -> PyResult { - let mut textio = zelf.lock(vm)?; - if !textio.seekable { - return Err(new_unsupported_operation( - "underlying stream is not seekable", - vm, - )); - } - if !textio.telling { - return Err(vm.new_os_error("telling position disabled by next() call")); + { + let data = zelf.lock(vm)?; + if !data.seekable { + return Err(new_unsupported_operation( + "underlying stream is not seekable", + vm, + )); + } + if !data.telling { + return Err(vm.new_os_error("telling position disabled by next() call")); + } } - let buffer = text_buffer(&zelf.buffer, vm)?; - textio.write_pending(&buffer, vm)?; - drop(textio); + zelf.write_pending(vm)?; vm.call_method(zelf.as_object(), "flush", ())?; - let textio = zelf.lock(vm)?; let buffer = text_buffer(&zelf.buffer, vm)?; let pos = vm.call_method(&buffer, "tell", ())?; - let (decoder, (dec_flags, next_input)) = match (&textio.decoder, &textio.snapshot) { - (Some(d), Some(s)) => (d, s), - _ => return Ok(pos), + let ((dec_flags, next_input), decoded_chars_used) = { + let data = zelf.lock(vm)?; + match (&data.decoder, &data.snapshot) { + (Some(_), Some(snapshot)) => (snapshot.clone(), data.decoded_chars_used), + _ => return Ok(pos), + } }; let pos = Offset::try_from_object(vm, pos)?; let mut cookie = TextIOCookie { start_pos: pos - next_input.as_bytes().len() as Offset, - dec_flags: *dec_flags, + dec_flags, ..Default::default() }; - if textio.decoded_chars_used.bytes == 0 { + if decoded_chars_used.bytes == 0 { return Ok(cookie.build().to_pyobject(vm)); } + // A callback may replace the decoder. Like CPython, resolve the + // current decoder for each call, owning only that call's receiver. + let current_decoder = || { + zelf.lock(vm)? + .decoder + .clone() + .ok_or_else(|| new_unsupported_operation("not readable", vm)) + }; let decoder_getstate = || { - let state = vm.call_method(decoder, "getstate", ())?; + let decoder = current_decoder()?; + let state = vm.call_method(&decoder, "getstate", ())?; parse_decoder_state(state, vm) }; let decoder_decode = |b: &[u8]| { - let decoded = vm.call_method(decoder, "decode", (vm.ctx.new_bytes(b.to_vec()),))?; + let decoder = current_decoder()?; + let decoded = + vm.call_method(&decoder, "decode", (vm.ctx.new_bytes(b.to_vec()),))?; let decoded = check_decoded(decoded, vm)?; Ok(Utf8size::len_pystr(&decoded)) }; - let saved_state = vm.call_method(decoder, "getstate", ())?; - let mut num_to_skip = textio.decoded_chars_used; - let mut skip_bytes = (textio.b2cratio * num_to_skip.chars as f64) as isize; + let saved_state = vm.call_method(current_decoder()?.as_object(), "getstate", ())?; + let b2cratio = zelf.lock(vm)?.b2cratio; + let mut num_to_skip = decoded_chars_used; + let mut skip_bytes = (b2cratio * num_to_skip.chars as f64) as isize; let mut skip_back = 1; while skip_bytes > 0 { - cookie.set_decoder_state(decoder, vm)?; + cookie.set_decoder_state(current_decoder()?.as_object(), vm)?; let input = &next_input.as_bytes()[..skip_bytes as usize]; let n_decoded = decoder_decode(input)?; if n_decoded.chars <= num_to_skip.chars { @@ -3801,7 +4136,7 @@ mod _io { } if skip_bytes <= 0 { skip_bytes = 0; - cookie.set_decoder_state(decoder, vm)?; + cookie.set_decoder_state(current_decoder()?.as_object(), vm)?; } let skip_bytes = skip_bytes as usize; @@ -3831,8 +4166,11 @@ mod _io { input = rest; } if input.is_empty() { - let decoded = - vm.call_method(decoder, "decode", (vm.ctx.new_bytes(vec![]), true))?; + let decoded = vm.call_method( + current_decoder()?.as_object(), + "decode", + (vm.ctx.new_bytes(vec![]), true), + )?; let decoded = check_decoded(decoded, vm)?; let final_decoded_chars = n_decoded.chars + decoded.char_len(); cookie.need_eof = true; @@ -3841,15 +4179,18 @@ mod _io { } } } - vm.call_method(decoder, "setstate", (saved_state,))?; + vm.call_method(current_decoder()?.as_object(), "setstate", (saved_state,))?; cookie.set_num_to_skip(num_to_skip); Ok(cookie.build().to_pyobject(vm)) } #[pygetset] fn name(&self, vm: &VirtualMachine) -> PyResult { - let _textio = self.lock(vm)?; - text_buffer(&self.buffer, vm)?.get_attr("name", vm) + let buffer = { + let _textio = self.lock(vm)?; + text_buffer(&self.buffer, vm)? + }; + buffer.get_attr("name", vm) } #[pygetset] @@ -3859,22 +4200,29 @@ mod _io { #[pymethod] fn fileno(&self, vm: &VirtualMachine) -> PyResult { - let _textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; + let buffer = { + let _textio = self.lock(vm)?; + text_buffer(&self.buffer, vm)? + }; vm.call_method(&buffer, "fileno", ()) } #[pymethod] fn read(&self, size: OptionalSize, vm: &VirtualMachine) -> PyResult { + let buffer = self.initialized_buffer(vm)?; + check_closed(&buffer, vm)?; let mut textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; - textio.check_closed(&buffer, vm)?; - let decoder = textio - .decoder - .clone() - .ok_or_else(|| new_unsupported_operation("not readable", vm))?; - - textio.write_pending(&buffer, vm)?; + if textio.decoder.is_none() { + return Err(new_unsupported_operation("not readable", vm)); + } + if textio.pending.num_bytes > 0 { + let pending = core::mem::take(&mut textio.pending); + drop(textio); + let pending = pending.into_bytes(vm); + let buffer = text_buffer(&self.buffer, vm)?; + vm.call_method(&buffer, "write", (pending,))?; + textio = self.lock(vm)?; + } let s = if let Some(mut remaining) = size.to_usize() { let mut chunks = Vec::new(); @@ -3888,11 +4236,15 @@ mod _io { if remaining == 0 { break; } - let eof = textio.read_chunk(&buffer, remaining, vm)?; + drop(textio); + let eof = self.read_chunk(remaining, vm)?; + textio = self.lock(vm)?; if eof { break; } } + // Joining can release the last reference to a str subclass. + drop(textio); if chunks.is_empty() { vm.ctx.empty_str.to_owned() } else if chunks.len() == 1 { @@ -3905,11 +4257,27 @@ mod _io { PyStr::from(ret).into_ref(&vm.ctx) } } else { + drop(textio); + let buffer = text_buffer(&self.buffer, vm)?; let bytes = vm.call_method(&buffer, "read", ())?; + if vm.is_none(&bytes) { + return Err(vm + .new_os_subtype_error( + vm.ctx.exceptions.blocking_io_error.to_owned(), + None, + "Read returned None.", + ) + .upcast()); + } + let decoder = self + .lock(vm)? + .decoder + .clone() + .ok_or_else(|| new_unsupported_operation("not readable", vm))?; let decoded = vm.call_method(&decoder, "decode", (bytes, true))?; let decoded = check_decoded(decoded, vm)?; - let ret = textio.take_decoded_chars(Some(decoded), vm); - textio.snapshot = None; + let ret = self.take_decoded_chars(Some(decoded), vm)?; + self.set_snapshot(None, vm)?; ret }; Ok(s) @@ -3917,9 +4285,9 @@ mod _io { #[pymethod] fn write(&self, text: PyStrRef, vm: &VirtualMachine) -> PyResult { + let buffer = self.initialized_buffer(vm)?; + check_closed(&buffer, vm)?; let mut textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; - textio.check_closed(&buffer, vm)?; let (encoder, encode_func) = textio .encoder @@ -3951,59 +4319,84 @@ mod _io { text }; let chunk = if let Some(encode_func) = *encode_func { - encode_func(chunk) + // UTF-8 is ASCII-compatible, so short ASCII text can be retained + // directly. All other text uses the native codec with errors. + if chunk.kind().is_ascii() && chunk.char_len() <= textio.chunk_size { + PendingWrite::Utf8(chunk) + } else { + let encoded = { + let errors = textio.errors.clone(); + // Registered error handlers may reenter or reinitialize us. + drop(textio); + encode_func(chunk, &errors, vm)? + }; + textio = self.lock(vm)?; + encoded + } } else { - let b = vm.call_method(encoder, "encode", (chunk.clone(),))?; - b.downcast::() - .map(PendingWrite::Bytes) - .or_else(|obj| { - // TODO: not sure if encode() returning the str it was passed is officially - // supported or just a quirk of how the CPython code is written - if obj.is(&chunk) { - Ok(PendingWrite::Utf8(chunk)) - } else { - Err(vm.new_type_error(format!( - "encoder should return a bytes object, not '{}'", - obj.class().name() - ))) - } - })? + let encoded = { + let encoder = encoder.clone(); + drop(textio); + let b = vm.call_method(&encoder, "encode", (chunk.clone(),))?; + b.downcast::() + .map(PendingWrite::Bytes) + .or_else(|obj| { + // TODO: not sure if encode() returning the str it was passed is officially + // supported or just a quirk of how the CPython code is written + if obj.is(&chunk) { + Ok(PendingWrite::Utf8(chunk)) + } else { + Err(vm.new_type_error(format!( + "encoder should return a bytes object, not '{}'", + obj.class().name() + ))) + } + })? + }; + textio = self.lock(vm)?; + encoded }; if textio.pending.num_bytes > 0 && textio.pending.num_bytes + chunk.as_bytes().len() > textio.chunk_size { - let pending = textio.pending.take(vm); + let pending = core::mem::take(&mut textio.pending); drop(textio); - vm.call_method(&buffer, "write", (pending,))?; + { + let pending = pending.into_bytes(vm); + let buffer = text_buffer(&self.buffer, vm)?; + vm.call_method(&buffer, "write", (pending,))?; + } textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; - textio.check_closed(&buffer, vm)?; if textio.pending.num_bytes > 0 { - let pending = textio.pending.take(vm); + let pending = core::mem::take(&mut textio.pending); drop(textio); - vm.call_method(&buffer, "write", (pending,))?; + { + let pending = pending.into_bytes(vm); + let buffer = text_buffer(&self.buffer, vm)?; + vm.call_method(&buffer, "write", (pending,))?; + } textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; - textio.check_closed(&buffer, vm)?; } } textio.pending.push(chunk); - if textio.pending.num_bytes > 0 + let pending = if textio.pending.num_bytes > 0 && (flush || self.write_through.load(Ordering::Relaxed) || textio.pending.num_bytes >= textio.chunk_size) { + Some(core::mem::take(&mut textio.pending)) + } else { + None + }; + drop(textio); + if let Some(pending) = pending { + let pending = pending.into_bytes(vm); let buffer = text_buffer(&self.buffer, vm)?; - let pending = textio.pending.take(vm); - drop(textio); vm.call_method(&buffer, "write", (pending,))?; - textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; - textio.check_closed(&buffer, vm)?; } if flush { let buffer = text_buffer(&self.buffer, vm)?; - let _ = vm.call_method(&buffer, "flush", ()); + vm.call_method(&buffer, "flush", ())?; } Ok(char_len) @@ -4011,48 +4404,74 @@ mod _io { #[pymethod] fn flush(&self, vm: &VirtualMachine) -> PyResult { - let mut textio = self.lock(vm)?; + let buffer = { + let _data = self.lock(vm)?; + text_buffer(&self.buffer, vm)? + }; + check_closed(&buffer, vm)?; + { + let mut data = self.lock(vm)?; + data.telling = data.seekable; + } + self.write_pending(vm)?; let buffer = text_buffer(&self.buffer, vm)?; - flush_inner(&mut textio, &buffer, vm) + vm.call_method(&buffer, "flush", ()) } #[pymethod] fn truncate(zelf: PyRef, pos: KeepNonePos, vm: &VirtualMachine) -> PyResult { - // Implementation follows _pyio.py TextIOWrapper.truncate - let mut textio = zelf.lock(vm)?; + { + let _data = zelf.lock(vm)?; + text_buffer(&zelf.buffer, vm)?; + } + vm.call_method(zelf.as_object(), "flush", ())?; let buffer = text_buffer(&zelf.buffer, vm)?; - flush_inner(&mut textio, &buffer, vm)?; - drop(textio); - - let pos = match pos.pos.into_option() { - Some(p) => p, - None => vm.call_method(zelf.as_object(), "tell", ())?, - }; + let pos = pos.pos.into_option().unwrap_or_else(|| vm.ctx.none()); vm.call_method(&buffer, "truncate", (pos,)) } #[pymethod] fn isatty(&self, vm: &VirtualMachine) -> PyResult { - let textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; - textio.check_closed(&buffer, vm)?; + let buffer = { + let _data = self.lock(vm)?; + text_buffer(&self.buffer, vm)? + }; + check_closed(&buffer, vm)?; vm.call_method(&buffer, "isatty", ()) } #[pymethod] fn readline(&self, size: OptionalSize, vm: &VirtualMachine) -> PyResult { let limit = size.to_usize(); - - let mut textio = self.lock(vm)?; - let buffer = text_buffer(&self.buffer, vm)?; + let buffer = self.initialized_buffer(vm)?; check_closed(&buffer, vm)?; - - textio.write_pending(&buffer, vm)?; + let mut textio = self.lock(vm)?; + if textio.pending.num_bytes > 0 { + let pending = core::mem::take(&mut textio.pending); + drop(textio); + let pending = pending.into_bytes(vm); + let buffer = text_buffer(&self.buffer, vm)?; + vm.call_method(&buffer, "write", (pending,))?; + textio = self.lock(vm)?; + } #[derive(Clone)] struct SlicedStr(PyStrRef, Range); impl SlicedStr { + fn substring(line: &PyStrRef, range: Range, vm: &VirtualMachine) -> Self { + if line.class().is(vm.ctx.types.str_type) { + Self(line.clone(), range) + } else { + // CPython's PyUnicode_Substring returns an exact str, + // not a view retaining the original subclass. Retaining + // it would delay its finalizer until after the next read. + let string = PyStr::from(&line.as_wtf8()[range]).into_ref(&vm.ctx); + let length = string.byte_len(); + Self(string, 0..length) + } + } + #[inline] fn byte_len(&self) -> usize { self.1.len() @@ -4087,6 +4506,21 @@ mod _io { } } + fn join(self, decoded: PyStrRef, vm: &VirtualMachine) -> PyStrRef { + if self.is_full_slice() { + let mut line = self.0; + line.concat_in_place(decoded.as_wtf8(), vm); + line + } else { + let remaining = self.slice(); + let mut joined = + Wtf8Buf::with_capacity(remaining.len() + decoded.byte_len()); + joined.push_wtf8(remaining); + joined.push_wtf8(decoded.as_wtf8()); + PyStr::from(joined).into_ref(&vm.ctx) + } + } + fn utf8_len(&self) -> Utf8size { Utf8size { bytes: self.byte_len(), @@ -4108,10 +4542,14 @@ mod _io { Some(s) if !s.is_empty() => break s, _ => {} } - let eof = textio.read_chunk(&buffer, 0, vm)?; + drop(textio); + let eof = self.read_chunk(0, vm)?; + textio = self.lock(vm)?; if eof { - textio.set_decoded_chars(None); - textio.snapshot = None; + drop(textio); + self.set_decoded_chars(None, vm)?; + self.set_snapshot(None, vm)?; + textio = self.lock(vm)?; start = Utf8size::default(); end_pos = Utf8size::default(); offset_to_buffer = Utf8size::default(); @@ -4127,19 +4565,10 @@ mod _io { Some(remaining) => { assert_eq!(textio.decoded_chars_used.bytes, 0); offset_to_buffer = remaining.utf8_len(); - let decoded_chars = decoded_chars.as_wtf8(); - let line = if remaining.is_full_slice() { - let mut line = remaining.0; - line.concat_in_place(decoded_chars, vm); - line - } else { - let remaining = remaining.slice(); - let mut s = - Wtf8Buf::with_capacity(remaining.len() + decoded_chars.len()); - s.push_wtf8(remaining); - s.push_wtf8(decoded_chars); - PyStr::from(s).into_ref(&vm.ctx) - }; + let decoded_chars = decoded_chars.clone(); + drop(textio); + let line = remaining.join(decoded_chars, vm); + textio = self.lock(vm)?; start = Utf8size::default(); line } @@ -4170,21 +4599,27 @@ mod _io { break Some(line); } if end_pos.bytes > start.bytes { - let chunk = SlicedStr(line.clone(), start.bytes..end_pos.bytes); + let chunk = SlicedStr::substring(&line, start.bytes..end_pos.bytes, vm); chunked += chunk.utf8_len(); chunks.push(chunk); } let line_len = line.byte_len(); + drop(textio); if end_pos.bytes < line_len { - remaining = Some(SlicedStr(line, end_pos.bytes..line_len)); + remaining = Some(SlicedStr::substring(&line, end_pos.bytes..line_len, vm)); } - textio.set_decoded_chars(None); + // Match Py_CLEAR(line) before clearing decoded_chars. A + // subclass must not be kept alive by a deferred slice. + drop(line); + self.set_decoded_chars(None, vm)?; + textio = self.lock(vm)?; }; let cur_line = cur_line.map(|line| { textio.decoded_chars_used = end_pos - offset_to_buffer; SlicedStr(line, start.bytes..end_pos.bytes) }); + drop(textio); // don't need to care about chunked.chars anymore let mut chunked = chunked.bytes; if let Some(remaining) = remaining { @@ -4231,14 +4666,19 @@ mod _io { let _ = vm.call_method(&buffer, "_dealloc_warn", (zelf.as_object().to_owned(),)); } let flush_res = vm.call_method(zelf.as_object(), "flush", ()).map(drop); - let close_res = vm.call_method(&buffer, "close", ()).map(drop); + let close_res = text_buffer(&zelf.buffer, vm) + .and_then(|buffer| vm.call_method(&buffer, "close", ())) + .map(drop); exception_chain(flush_res, close_res) } #[pygetset] fn closed(&self, vm: &VirtualMachine) -> PyResult { - let _textio = self.lock(vm)?; - text_buffer(&self.buffer, vm)?.get_attr("closed", vm) + let buffer = { + let _textio = self.lock(vm)?; + text_buffer(&self.buffer, vm)? + }; + buffer.get_attr("closed", vm) } #[pymethod] @@ -4247,13 +4687,13 @@ mod _io { } #[pymethod] - fn __reduce_ex__(zelf: PyObjectRef, proto: usize, vm: &VirtualMachine) -> PyResult { + fn __reduce_ex__(zelf: PyObjectRef, protocol: usize, vm: &VirtualMachine) -> PyResult { if zelf.class().is(TextIOWrapper::static_type()) { return Err( vm.new_type_error(format!("cannot pickle '{}' object", zelf.class().name())) ); } - let _ = proto; + let _ = protocol; reduce_ex_for_subclass(&zelf, vm) } } @@ -4279,76 +4719,15 @@ mod _io { } impl TextIOData { - fn write_pending(&mut self, buffer: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - if self.pending.num_bytes == 0 { - return Ok(()); - } - let data = self.pending.take(vm); - vm.call_method(buffer, "write", (data,))?; - Ok(()) - } - - /// returns true on EOF - fn read_chunk( - &mut self, - buffer: &PyObject, - size_hint: usize, - vm: &VirtualMachine, - ) -> PyResult { - let decoder = self - .decoder - .as_ref() - .ok_or_else(|| new_unsupported_operation("not readable", vm))?; - - let dec_state = if self.telling { - let state = vm.call_method(decoder, "getstate", ())?; - Some(parse_decoder_state(state, vm)?) - } else { - None - }; - - let method = if self.has_read1 { "read1" } else { "read" }; - let size_hint = if size_hint > 0 { - (self.b2cratio.max(1.0) * size_hint as f64) as usize - } else { - size_hint - }; - let chunk_size = core::cmp::max(self.chunk_size, size_hint); - let input_chunk = vm.call_method(buffer, method, (chunk_size,))?; - - let buf = ArgBytesLike::try_from_borrowed_object(vm, &input_chunk).map_err(|_| { - vm.new_type_error(format!( - "underlying {}() should have returned a bytes-like object, not '{}'", - method, - input_chunk.class().name() - )) - })?; - let nbytes = buf.borrow_buf().len(); - let eof = nbytes == 0; - let decoded = vm.call_method(decoder, "decode", (input_chunk, eof))?; - let decoded = check_decoded(decoded, vm)?; - - let char_len = decoded.char_len(); - self.b2cratio = if char_len > 0 { - nbytes as f64 / char_len as f64 - } else { - 0.0 - }; - let eof = if char_len > 0 { false } else { eof }; - self.set_decoded_chars(Some(decoded)); - - if let Some((dec_buffer, dec_flags)) = dec_state { - // TODO: inplace append to bytes when refcount == 1 - let mut next_input = dec_buffer.as_bytes().to_vec(); - next_input.extend_from_slice(&buf.borrow_buf()); - self.snapshot = Some((dec_flags, PyBytes::from(next_input).into_ref(&vm.ctx))); - } - - Ok(eof) - } - - fn check_closed(&self, buffer: &PyObject, vm: &VirtualMachine) -> PyResult<()> { - check_closed(buffer, vm) + // Initialization has already marked the wrapper uninitialized. Release + // its old owned fields without the data lock, in textio.c clear order. + fn clear(mut self) { + self.encoder = None; + self.decoder = None; + self.decoded_chars = None; + self.pending = PendingWrites::default(); + self.snapshot = None; + // errors is the only Python reference left and drops on return. } /// returns str, str.char_len() (it might not be cached in the str yet but we calculate it @@ -4383,37 +4762,6 @@ mod _io { }; Some((chars, chars_used)) } - - fn set_decoded_chars(&mut self, s: Option) { - self.decoded_chars = s; - self.decoded_chars_used = Utf8size::default(); - } - - fn take_decoded_chars( - &mut self, - append: Option, - vm: &VirtualMachine, - ) -> PyStrRef { - let empty_str = || vm.ctx.empty_str.to_owned(); - let chars_pos = core::mem::take(&mut self.decoded_chars_used).bytes; - let decoded_chars = match core::mem::take(&mut self.decoded_chars) { - None => return append.unwrap_or_else(empty_str), - Some(s) if s.is_empty() => return append.unwrap_or_else(empty_str), - Some(s) => s, - }; - let append_len = append.as_ref().map_or(0, |s| s.byte_len()); - if append_len == 0 && chars_pos == 0 { - return decoded_chars; - } - // TODO: in-place editing of `str` when refcount == 1 - let decoded_chars_unused = &decoded_chars.as_wtf8()[chars_pos..]; - let mut s = Wtf8Buf::with_capacity(decoded_chars_unused.len() + append_len); - s.push_wtf8(decoded_chars_unused); - if let Some(append) = append { - s.push_wtf8(append.as_wtf8()) - } - PyStr::from(s).into_ref(&vm.ctx) - } } impl Destructor for TextIOWrapper { @@ -4518,8 +4866,8 @@ mod _io { if !line.try_to_bool(vm)? { // Restore telling on StopIteration + textio_ref.set_snapshot(None, vm)?; let mut textio = textio_ref.lock(vm)?; - textio.snapshot = None; textio.telling = textio.seekable; Ok(PyIterReturn::StopIteration(None)) } else { @@ -4607,13 +4955,15 @@ mod _io { type Args = IncrementalNewlineDecoderArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { let _ = args.errors; - let mut data = zelf.lock_opt(vm)?; - *data = Some(IncrementalNewlineDecoderData { - decoder: args.decoder, - translate: args.translate, - pendingcr: false, - seennl: SeenNewline::empty(), - }); + let _ = { + let mut data = zelf.lock_opt(vm)?; + data.replace(IncrementalNewlineDecoderData { + decoder: args.decoder, + translate: args.translate, + pendingcr: false, + seennl: SeenNewline::empty(), + }) + }; Ok(()) } } @@ -4642,41 +4992,57 @@ mod _io { impl Py { #[pymethod] fn decode(&self, args: NewlineDecodeArgs, vm: &VirtualMachine) -> PyResult { - self.lock(vm)?.decode(args.input, args.r#final, vm) + let decoder = self.lock(vm)?.decoder.clone(); + let output = if vm.is_none(&decoder) { + args.input + } else { + vm.call_method(&decoder, "decode", (args.input, args.r#final))? + }; + let output = check_decoded(output, vm)?; + // The input subclass remains owned by this scope until after the + // newline-state guard has been released. + let result = self.lock(vm)?.decode(&output, args.r#final, vm); + Ok(result.unwrap_or(output)) } #[pymethod] fn getstate(&self, vm: &VirtualMachine) -> PyResult<(PyObjectRef, u64)> { - let data = self.lock(vm)?; - let (buffer, flag) = if vm.is_none(&data.decoder) { + let decoder = self.lock(vm)?.decoder.clone(); + let (buffer, flag) = if vm.is_none(&decoder) { (vm.ctx.new_bytes(vec![]).into(), 0) } else { - vm.call_method(&data.decoder, "getstate", ())? + vm.call_method(&decoder, "getstate", ())? .try_to_ref::(vm)? .extract_tuple::<(PyObjectRef, u64)>(vm)? }; - let flag = (flag << 1) | (data.pendingcr as u64); + let flag = (flag << 1) | (self.lock(vm)?.pendingcr as u64); Ok((buffer, flag)) } #[pymethod] fn setstate(&self, state: PyTupleRef, vm: &VirtualMachine) -> PyResult<()> { - let mut data = self.lock(vm)?; let (buffer, flag) = state.extract_tuple::<(PyObjectRef, u64)>(vm)?; - data.pendingcr = flag & 1 != 0; - if !vm.is_none(&data.decoder) { - vm.call_method(&data.decoder, "setstate", ((buffer, flag >> 1),))?; + let decoder = { + let mut data = self.lock(vm)?; + data.pendingcr = flag & 1 != 0; + data.decoder.clone() + }; + if !vm.is_none(&decoder) { + vm.call_method(&decoder, "setstate", ((buffer, flag >> 1),))?; } Ok(()) } #[pymethod] fn reset(&self, vm: &VirtualMachine) -> PyResult<()> { - let mut data = self.lock(vm)?; - data.seennl = SeenNewline::empty(); - data.pendingcr = false; - if !vm.is_none(&data.decoder) { - vm.call_method(&data.decoder, "reset", ())?; + let decoder = { + let mut data = self.lock(vm)?; + data.seennl = SeenNewline::empty(); + data.pendingcr = false; + data.decoder.clone() + }; + if !vm.is_none(&decoder) { + vm.call_method(&decoder, "reset", ())?; } Ok(()) } @@ -4699,16 +5065,10 @@ mod _io { impl IncrementalNewlineDecoderData { fn decode( &mut self, - input: PyObjectRef, + orig_output: &PyStr, final_: bool, vm: &VirtualMachine, - ) -> PyResult { - let output = if vm.is_none(&self.decoder) { - input - } else { - vm.call_method(&self.decoder, "decode", (input, final_))? - }; - let orig_output: PyStrRef = output.try_into_value(vm)?; + ) -> Option { // this being Cow::Owned means we need to allocate a new string let mut output = Cow::Borrowed(orig_output.as_wtf8()); if self.pendingcr && (final_ || !output.is_empty()) { @@ -4721,7 +5081,7 @@ mod _io { } if output.is_empty() { - return Ok(vm.ctx.empty_str.to_owned()); + return Some(vm.ctx.empty_str.to_owned()); } if (self.seennl == SeenNewline::LF || self.seennl.is_empty()) @@ -4760,10 +5120,10 @@ mod _io { output = Cow::Owned(new_string); } - Ok(match output { - Cow::Borrowed(_) => orig_output, - Cow::Owned(s) => vm.ctx.new_str(s), - }) + match output { + Cow::Borrowed(_) => None, + Cow::Owned(s) => Some(vm.ctx.new_str(s)), + } } } @@ -4772,17 +5132,90 @@ mod _io { #[derive(Debug)] struct StringIO { _base: _TextIOBase, - buffer: PyRwLock, + buffer: PyRwLock, newline: AtomicCell, seennl: AtomicCell, closed: AtomicCell, } + #[derive(Debug)] + struct StringIOBuffer { + bytes: BufferedIO, + position: usize, + length: usize, + } + + impl StringIOBuffer { + fn new(bytes: Vec) -> Self { + let length = StringIO::text(&bytes).code_points().count(); + Self { + bytes: BufferedIO::new(Cursor::new(bytes)), + position: 0, + length, + } + } + + fn byte_offset(&self, position: usize) -> usize { + let bytes = self.bytes.cursor.get_ref(); + if position >= self.length { + bytes.len() + (position - self.length) + } else { + crate::common::str::codepoint_range_end(StringIO::text(bytes), position).unwrap() + } + } + + fn seek(&mut self, position: usize) { + let byte_position = self.byte_offset(position); + self.bytes.cursor.set_position(byte_position as u64); + self.position = position; + } + + fn read(&mut self, size: usize) -> Vec { + let data = self.bytes.read(Some(size)).unwrap_or_default(); + self.position += StringIO::text(&data).code_points().count(); + data + } + + fn write(&mut self, data: &Wtf8, count: usize, vm: &VirtualMachine) -> PyResult<()> { + if data.is_empty() { + return Ok(()); + } + let position = self + .position + .checked_add(count) + .filter(|&position| isize::try_from(position).is_ok()) + .ok_or_else(|| vm.new_overflow_error("new position too large"))?; + let byte_position = self.bytes.tell() as usize; + let bytes = self.bytes.cursor.get_mut(); + if byte_position > bytes.len() { + bytes.resize(byte_position, 0); + } + let tail = StringIO::text(&bytes[byte_position..]); + let replaced = if count >= self.length.saturating_sub(self.position) { + tail.len() + } else if tail.as_bytes()[..count].is_ascii() { + count + } else { + crate::common::str::codepoint_range_end(tail, count).unwrap() + }; + bytes.splice( + byte_position..byte_position + replaced, + data.as_bytes().iter().copied(), + ); + self.bytes + .cursor + .set_position((byte_position + data.len()) as u64); + self.position = position; + self.length = self.length.max(position); + Ok(()) + } + } + #[derive(FromArgs)] struct StringIONewArgs { // None means an empty buffer. #[pyarg(any, optional, py_default = "''")] - initial_value: Option, + initial_value: Option, // Omitted newline is \n. None selects universal newlines. #[pyarg(any, default, py_default = "'\\n'")] @@ -4795,7 +5228,7 @@ mod _io { fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { Ok(Self { _base: Default::default(), - buffer: PyRwLock::new(BufferedIO::new(Cursor::new(Vec::new()))), + buffer: PyRwLock::new(StringIOBuffer::new(Vec::new())), newline: AtomicCell::new(Newlines::Lf), seennl: AtomicCell::new(SeenNewline::empty()), closed: AtomicCell::new(false), @@ -4812,31 +5245,46 @@ mod _io { initial_value, newline, }: Self::Args, - _vm: &VirtualMachine, + vm: &VirtualMachine, ) -> PyResult<()> { let newline = match newline { OptionalArg::Missing => Newlines::Lf, OptionalArg::Present(None) => Newlines::Universal, OptionalArg::Present(Some(newline)) => newline, }; + // Checked here rather than while binding, so a bad newline is reported first. + let initial_value = initial_value + .map(|value| { + value.downcast::().map_err(|value| { + vm.new_type_error(format!( + "initial_value must be str or None, not {}", + value.class().slot_name() + )) + }) + }) + .transpose()?; let raw_bytes = initial_value.as_ref().map_or_else(Vec::new, |v| { Self::translate_newlines(v.as_wtf8(), newline).into_bytes() }); - *zelf.buffer.write() = BufferedIO::new(Cursor::new(raw_bytes)); + let mut buffer = zelf.buffer.write(); + *buffer = StringIOBuffer::new(raw_bytes); zelf.newline.store(newline); zelf.seennl.store(SeenNewline::empty()); - if let Some(initial_value) = initial_value { + if let Some(initial_value) = initial_value.as_ref() { zelf.observe_newlines(initial_value.as_wtf8(), newline); } + zelf.closed.store(false); Ok(()) } } impl StringIO { - fn buffer(&self, vm: &VirtualMachine) -> PyResult> { + fn buffer(&self, vm: &VirtualMachine) -> PyResult> { + let buffer = self.buffer.write(); if !self.closed.load() { - Ok(self.buffer.write()) + Ok(buffer) } else { + drop(buffer); Err(io_closed_error(vm)) } } @@ -4865,19 +5313,6 @@ mod _io { unsafe { Wtf8::from_bytes_unchecked(bytes) } } - fn char_offset_to_byte(bytes: &[u8], char_offset: usize) -> usize { - let text = Self::text(bytes); - crate::common::str::codepoint_range_end(text, char_offset) - .unwrap_or_else(|| bytes.len() + (char_offset - text.code_points().count())) - } - - fn byte_offset_to_char(bytes: &[u8], byte_offset: usize) -> usize { - let content_len = bytes.len(); - let in_content = byte_offset.min(content_len); - Self::text(&bytes[..in_content]).code_points().count() - + byte_offset.saturating_sub(content_len) - } - fn read_size(buffer: &BufferedIO, size: Option, newline: Option) -> usize { let position = buffer.tell() as usize; let bytes = buffer.cursor.get_ref().get(position..).unwrap_or_default(); @@ -4893,18 +5328,22 @@ mod _io { #[pyclass(flags(BASETYPE, HAS_DICT, HAS_WEAKREF), with(Constructor, Initializer))] impl Py { #[pymethod] - const fn readable(&self) -> bool { - true + fn readable(&self, vm: &VirtualMachine) -> PyResult { + if self.closed.load() { + Err(io_closed_error(vm)) + } else { + Ok(true) + } } #[pymethod] - const fn writable(&self) -> bool { - true + fn writable(&self, vm: &VirtualMachine) -> PyResult { + self.readable(vm) } #[pymethod] - const fn seekable(&self) -> bool { - true + fn seekable(&self, vm: &VirtualMachine) -> PyResult { + self.readable(vm) } #[pygetset] @@ -4923,61 +5362,55 @@ mod _io { #[pymethod] fn close(&self) { + let mut buffer = self.buffer.write(); self.closed.store(true); + *buffer = StringIOBuffer::new(Vec::new()); } - // write string to underlying vector + // Replace characters in the underlying vector, regardless of their byte widths. #[pymethod] fn write(&self, s: PyStrRef, vm: &VirtualMachine) -> PyResult { let newline = self.newline.load(); - let bytes = StringIO::translate_newlines(s.as_wtf8(), newline).into_bytes(); + let text = StringIO::translate_newlines(s.as_wtf8(), newline); + let count = if matches!(newline, Newlines::Universal | Newlines::Crlf) { + text.code_points().count() + } else { + s.char_len() + }; let mut buffer = self.buffer(vm)?; self.observe_newlines(s.as_wtf8(), newline); - buffer - .write(&bytes) - .ok_or_else(|| vm.new_type_error("Error Writing String"))?; + buffer.write(&text, count, vm)?; Ok(s.char_len() as u64) } // return the entire contents of the underlying #[pymethod] fn getvalue(&self, vm: &VirtualMachine) -> PyResult { - let bytes = self.buffer(vm)?.getvalue(); + let bytes = self.buffer(vm)?.bytes.getvalue(); Wtf8Buf::from_bytes(bytes).map_err(|_| vm.new_value_error("Error Retrieving Value")) } // skip to the jth position #[pymethod] - fn seek(&self, pos: PyObjectRef, whence: HowArg, vm: &VirtualMachine) -> PyResult { - let offset: isize = isize::try_from_object(vm, pos)?; + fn seek(&self, pos: PySsize, whence: HowArg, vm: &VirtualMachine) -> PyResult { let how = whence.whence; let mut buffer = self.buffer(vm)?; let char_offset = match how { - 0 if offset >= 0 => offset as usize, - 0 => return Err(vm.new_value_error(format!("negative seek position {offset}"))), - 1 | 2 if offset != 0 => { - let kind = if how == 1 { "cur" } else { "end" }; - return Err(vm.new_os_error(format!("can't do nonzero {kind}-relative seeks"))); - } - 1 | 2 => { - let byte_offset = if how == 1 { - buffer.tell() as usize - } else { - buffer.cursor.get_ref().len() - }; - StringIO::byte_offset_to_char(buffer.cursor.get_ref(), byte_offset) + 0 if pos >= 0 => pos as usize, + 0 => return Err(vm.new_value_error(format!("Negative seek position {pos}"))), + 1 | 2 if pos != 0 => { + return Err(vm.new_os_error("Can't do nonzero cur-relative seeks")); } + 1 => return Ok(buffer.position as u64), + 2 => buffer.length, _ => { return Err( - vm.new_value_error(format!("invalid whence ({how}, should be 0, 1 or 2)")) + vm.new_value_error(format!("Invalid whence ({how}, should be 0, 1 or 2)")) ); } }; - let byte_offset = StringIO::char_offset_to_byte(buffer.cursor.get_ref(), char_offset); - buffer - .seek(SeekFrom::Start(byte_offset as u64)) - .map_err(|err| os_err(vm, err))?; + buffer.seek(char_offset); Ok(char_offset as u64) } @@ -4987,8 +5420,8 @@ mod _io { #[pymethod] fn read(&self, size: OptionalSize, vm: &VirtualMachine) -> PyResult { let mut buffer = self.buffer(vm)?; - let size = StringIO::read_size(&buffer, size.to_usize(), None); - let data = buffer.read(Some(size)).unwrap_or_default(); + let size = StringIO::read_size(&buffer.bytes, size.to_usize(), None); + let data = buffer.read(size); let value = Wtf8Buf::from_bytes(data) .map_err(|_| vm.new_value_error("Error Retrieving Value"))?; @@ -4997,32 +5430,32 @@ mod _io { #[pymethod] fn tell(&self, vm: &VirtualMachine) -> PyResult { - let buffer = self.buffer(vm)?; - Ok( - StringIO::byte_offset_to_char(buffer.cursor.get_ref(), buffer.tell() as usize) - as u64, - ) + Ok(self.buffer(vm)?.position as u64) } #[pymethod] fn readline(&self, size: OptionalSize, vm: &VirtualMachine) -> PyResult { let mut buffer = self.buffer(vm)?; - let size = StringIO::read_size(&buffer, size.to_usize(), Some(self.newline.load())); - let input = buffer.read(Some(size)).unwrap_or_default(); + let size = + StringIO::read_size(&buffer.bytes, size.to_usize(), Some(self.newline.load())); + let input = buffer.read(size); Wtf8Buf::from_bytes(input).map_err(|_| vm.new_value_error("Error Retrieving Value")) } #[pymethod] fn truncate(&self, pos: StringIOPos, vm: &VirtualMachine) -> PyResult { + drop(self.buffer(vm)?); + let pos = memory_truncate_pos(pos.pos, "pos", vm)?; let mut buffer = self.buffer(vm)?; - let pos = match pos.as_optional().try_usize(vm)? { - Some(pos) => pos, - None => { - StringIO::byte_offset_to_char(buffer.cursor.get_ref(), buffer.tell() as usize) - } - }; - let byte_pos = StringIO::char_offset_to_byte(buffer.cursor.get_ref(), pos); - buffer.truncate(Some(byte_pos)); + let pos = pos.unwrap_or(buffer.position); + let byte_pos = buffer.byte_offset(pos); + buffer.bytes.truncate(Some(byte_pos)); + buffer.length = buffer.length.min(pos); + // Truncation keeps the character position, including positions beyond EOF. + if buffer.bytes.tell() as usize > buffer.bytes.cursor.get_ref().len() { + let position = buffer.position; + buffer.seek(position); + } Ok(pos) } @@ -5034,10 +5467,9 @@ mod _io { #[pymethod] fn __getstate__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { let buffer = zelf.buffer(vm)?; - let content = Wtf8Buf::from_bytes(buffer.getvalue()) + let content = Wtf8Buf::from_bytes(buffer.bytes.getvalue()) .map_err(|_| vm.new_value_error("Error Retrieving Value"))?; - let pos = - StringIO::byte_offset_to_char(buffer.cursor.get_ref(), buffer.tell() as usize); + let pos = buffer.position; drop(buffer); // Get __dict__ if it exists and is non-empty @@ -5090,12 +5522,9 @@ mod _io { // Set content and position let raw_bytes = content.as_bytes().to_vec(); - let mut buffer = zelf.buffer.write(); - *buffer = BufferedIO::new(Cursor::new(raw_bytes)); - let byte_pos = StringIO::char_offset_to_byte(buffer.cursor.get_ref(), pos as usize); - buffer - .seek(SeekFrom::Start(byte_pos as u64)) - .map_err(|err| os_err(vm, err))?; + let mut buffer = zelf.buffer(vm)?; + *buffer = StringIOBuffer::new(raw_bytes); + buffer.seek(pos as usize); drop(buffer); zelf.newline.store(newline); let mut seennl = SeenNewline::empty(); @@ -5161,17 +5590,30 @@ mod _io { let raw_bytes = args .initial_bytes + .as_ref() .map_or_else(Vec::new, |input| input.borrow_buf().to_vec()); - *zelf.buffer.write() = BufferedIO::new(Cursor::new(raw_bytes)); + let mut buffer = zelf.try_resizable(vm)?; + *buffer = BufferedIO::new(Cursor::new(raw_bytes)); + zelf.closed.store(false); Ok(()) } } impl BytesIO { + fn check_closed(&self, vm: &VirtualMachine) -> PyResult<()> { + if self.closed.load() { + Err(vm.new_value_error("I/O operation on closed file.")) + } else { + Ok(()) + } + } + fn buffer(&self, vm: &VirtualMachine) -> PyResult> { + let buffer = self.buffer.write(); if !self.closed.load() { - Ok(self.buffer.write()) + Ok(buffer) } else { + drop(buffer); Err(io_closed_error(vm)) } } @@ -5183,18 +5625,19 @@ mod _io { )] impl Py { #[pymethod] - const fn readable(&self) -> bool { - true + fn readable(&self, vm: &VirtualMachine) -> PyResult { + self.check_closed(vm)?; + Ok(true) } #[pymethod] - const fn writable(&self) -> bool { - true + fn writable(&self, vm: &VirtualMachine) -> PyResult { + self.readable(vm) } #[pymethod] - const fn seekable(&self) -> bool { - true + fn seekable(&self, vm: &VirtualMachine) -> PyResult { + self.readable(vm) } #[pymethod] @@ -5211,7 +5654,15 @@ mod _io { let mut buffer = self.try_resizable(vm)?; // Acquiring the buffer can run `__buffer__`, which may have closed us. if self.closed.load() { - return Err(io_closed_error(vm)); + drop(buffer); + return Err(vm.new_value_error("I/O operation on closed file.")); + } + if !b.is_empty() { + buffer + .tell() + .checked_add(b.len() as u64) + .filter(|&position| isize::try_from(position).is_ok()) + .ok_or_else(|| vm.new_overflow_error("new buffer size too large"))?; } b.with_ref(|bytes| buffer.write(bytes)) .ok_or_else(|| vm.new_type_error("Error Writing Bytes")) @@ -5259,21 +5710,31 @@ mod _io { //skip to the jth position #[pymethod] - fn seek(&self, pos: PyObjectRef, whence: HowArg, vm: &VirtualMachine) -> PyResult { - let seek_from = seekfrom(vm, pos, whence.whence)?; + fn seek(&self, pos: PySsize, whence: HowArg, vm: &VirtualMachine) -> PyResult { let mut buffer = self.buffer(vm)?; - - // Handle negative positions by clamping to 0 - match seek_from { - SeekFrom::Current(offset) if offset < 0 => { - let current = buffer.tell(); - let new_pos = current.saturating_add_signed(offset); - buffer - .seek(SeekFrom::Start(new_pos)) - .map_err(|err| os_err(vm, err)) + let base = match whence.whence { + 0 if pos < 0 => { + return Err(vm.new_value_error(format!("negative seek value {pos}"))); } - _ => buffer.seek(seek_from).map_err(|err| os_err(vm, err)), - } + 0 => 0, + 1 => buffer.tell(), + 2 => buffer.cursor.get_ref().len() as u64, + how => { + return Err( + vm.new_value_error(format!("invalid whence ({how}, should be 0, 1 or 2)")) + ); + } + }; + let position = if pos < 0 { + base.saturating_sub(pos.unsigned_abs() as u64) + } else { + base.checked_add(pos as u64) + .filter(|&position| isize::try_from(position).is_ok()) + .ok_or_else(|| vm.new_overflow_error("new position too large"))? + }; + buffer + .seek(SeekFrom::Start(position)) + .map_err(|err| os_err(vm, err)) } #[pymethod] @@ -5286,13 +5747,56 @@ mod _io { self.buffer(vm)?.readline(size.to_usize(), vm) } + #[pymethod] + fn readlines(&self, size: OptionalPos, vm: &VirtualMachine) -> PyResult> { + // Unlike IOBase.readlines, BytesIO checks closed before accepting + // only int/None (not __index__), and reads its storage directly. + let mut buffer = self.buffer.write(); + self.check_closed(vm)?; + let maxsize = match size.size.as_deref() { + None => -1, + Some(obj) => { + let integer = + obj.downcast_ref::() + .ok_or_else(|| { + vm.new_type_error(format!( + "integer argument expected, got '{}'", + obj.class().slot_name(), + )) + })?; + integer.as_bigint().to_isize().ok_or_else(|| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") + })? + } + }; + let mut lines = Vec::new(); + let mut total = 0; + loop { + let line = buffer.readline(None, vm)?; + if line.is_empty() { + break; + } + total += line.len(); + lines.push(vm.ctx.new_bytes(line).into()); + if maxsize > 0 && total >= maxsize as usize { + break; + } + } + Ok(lines) + } + #[pymethod] fn truncate(&self, pos: OptionalPos, vm: &VirtualMachine) -> PyResult { + self.check_closed(vm)?; + drop(self.try_resizable(vm)?); + let pos = memory_truncate_pos(pos.size, "size", vm)?; + // __index__ may close the stream or create a view of its storage. + self.check_closed(vm)?; + let mut buffer = self.try_resizable(vm)?; if self.closed.load() { - return Err(io_closed_error(vm)); + drop(buffer); + return Err(vm.new_value_error("I/O operation on closed file.")); } - let mut buffer = self.try_resizable(vm)?; - let pos = pos.try_usize(vm)?; Ok(buffer.truncate(pos)) } @@ -5308,7 +5812,15 @@ mod _io { vm.new_buffer_error("Existing exports of data: object cannot be closed") ); } + let mut buffer = self.buffer.write(); + if self.exports.load() > 0 { + drop(buffer); + return Err( + vm.new_buffer_error("Existing exports of data: object cannot be closed") + ); + } self.closed.store(true); + *buffer = BufferedIO::new(Cursor::new(Vec::new())); Ok(()) } @@ -5336,42 +5848,63 @@ mod _io { #[pymethod] fn __setstate__( zelf: PyRef, - object: PyTupleRef, + object: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - if zelf.closed.load() { - return Err(vm.new_value_error("__setstate__ on closed file")); - } - if object.as_slice().len() != 3 { - return Err(vm.new_type_error(format!( - "__setstate__ argument should be 3-tuple, got {}", - object.as_slice().len() - ))); - } + let type_name = |object: &PyObject| { + let name = object.class().slot_name().to_string(); + name[..name.floor_char_boundary(200.min(name.len()))].to_owned() + }; + let state = object + .downcast_ref::() + .filter(|state| state.len() >= 3) + .ok_or_else(|| { + vm.new_type_error(format!( + "{}.__setstate__ argument should be 3-tuple, got {}", + type_name(zelf.as_object()), + type_name(&object), + )) + })?; - let content: PyBytesRef = object.as_slice()[0].clone().try_into_value(vm)?; - let pos: u64 = object.as_slice()[1].clone().try_into_value(vm)?; - let dict = &object.as_slice()[2]; + // CPython resets the stream before writing the new buffer, even if + // validating the content or position subsequently fails. + *zelf.try_resizable(vm)? = BufferedIO::new(Cursor::new(Vec::new())); + let content = ArgContiguousBytesLike::try_from_object(vm, state.as_slice()[0].clone())?; + zelf.write(content, vm)?; - // Check exports and set content (like CHECK_EXPORTS) - let mut buffer = zelf.try_resizable(vm)?; - *buffer = BufferedIO::new(Cursor::new(content.as_bytes().to_vec())); - buffer - .seek(SeekFrom::Start(pos)) - .map_err(|err| os_err(vm, err))?; - drop(buffer); + let position = &state.as_slice()[1]; + let position = position + .downcast_ref::() + .ok_or_else(|| { + vm.new_type_error(format!( + "second item of state must be an integer, not {}", + type_name(position), + )) + })?; + let position = position.as_bigint().to_isize().ok_or_else(|| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") + })?; + if position < 0 { + return Err(vm.new_value_error("position value cannot be negative")); + } + zelf.buffer.write().cursor.set_position(position as u64); - // Set __dict__ if provided + let dict = &state.as_slice()[2]; if !vm.is_none(dict) { - let dict_ref: PyRef = dict.clone().try_into_value(vm)?; + let dict = dict.downcast_ref::().ok_or_else(|| { + vm.new_type_error(format!( + "third item of state should be a dict, got a {}", + type_name(dict), + )) + })?; if let Some(obj_dict) = zelf.as_object().dict() { - obj_dict.clear(); - for (key, value) in dict_ref { - obj_dict.set_item(&*key, value, vm)?; - } + obj_dict.merge_object(dict.to_owned().into(), vm)?; + } else { + zelf.as_object() + .set_dict(Some(dict.to_owned())) + .map_err(|_| vm.new_attribute_error("This object has no __dict__"))?; } } - Ok(()) } @@ -5389,15 +5922,18 @@ mod _io { impl PyRef { #[pymethod] fn getbuffer(self, vm: &VirtualMachine) -> PyResult { + let storage = self.buffer.read(); if self.closed.load() { + drop(storage); return Err(vm.new_value_error("I/O operation on closed file.")); } - let len = self.buffer.read().cursor.get_ref().len(); + let len = storage.cursor.get_ref().len(); let buffer = PyBuffer::new( - self.into(), + self.clone().into(), BufferDescriptor::simple(len, false), &BYTES_IO_BUFFER_METHODS, ); + drop(storage); let view = PyMemoryView::from_buffer(buffer, vm)?; Ok(view) } @@ -5500,14 +6036,14 @@ mod _io { impl Mode { const fn rawmode(&self) -> &'static str { match (&self.file, self.plus) { - (FileMode::Read, true) => "rb+", - (FileMode::Read, false) => "rb", - (FileMode::Write, true) => "wb+", - (FileMode::Write, false) => "wb", - (FileMode::Exclusive, true) => "xb+", - (FileMode::Exclusive, false) => "xb", - (FileMode::Append, true) => "ab+", - (FileMode::Append, false) => "ab", + (FileMode::Read, true) => "r+", + (FileMode::Read, false) => "r", + (FileMode::Write, true) => "w+", + (FileMode::Write, false) => "w", + (FileMode::Exclusive, true) => "x+", + (FileMode::Exclusive, false) => "x", + (FileMode::Append, true) => "a+", + (FileMode::Append, false) => "a", } } } @@ -5652,6 +6188,15 @@ mod _io { opts: OpenArgs, vm: &VirtualMachine, ) -> PyResult { + // Match _io.open: numeric objects go to FileIO unchanged; other + // arguments are resolved through the path protocol before mode parsing. + let file = if crate::protocol::PyNumber::check(&file) { + file + } else { + // Keep the original argument alive through opening and wrapper setup. + FsPath::try_from_path_like(file.as_object().to_owned(), false, vm)?.to_pyobject(vm) + }; + // mode is optional: 'rt' is the default mode (open from reading text) let mode_string = mode.unwrap_or("r"); let mode = mode_string @@ -5673,22 +6218,6 @@ mod _io { } } - // Match CPython's _pyio.open (Lib/_pyio.py): resolve PathLike here so - // _io.FileIO still receives (and preserves on .name) the raw argument - // when called directly. - let file = if file.fast_isinstance(vm.ctx.types.int_type) { - file - } else { - FsPath::try_from_path_like(file, true, vm)?.to_pyobject(vm) - }; - - // check file descriptor validity - #[cfg(all(unix, feature = "host_env"))] - if let Ok(crate::ospath::OsPathOrFd::Fd(fd)) = file.clone().try_into_value(vm) { - rustpython_host_env::fcntl::validate_fd(fd.as_raw()) - .map_err(|_| vm.new_last_errno_error())?; - } - // Construct a RawIO (subclass of RawIOBase) // On Windows, use _WindowsConsoleIO for console handles. // This is subsequently consumed by a Buffered Class. @@ -5707,7 +6236,7 @@ mod _io { Some(super::fileio::FileIO::static_type()) } } - feature = "host_env" => Some(super::fileio::FileIO::static_type()), + feature = "host_io" => Some(super::fileio::FileIO::static_type()), _ => None, } .ok_or_else(|| { @@ -5831,6 +6360,11 @@ mod _io { CELL.get_or_init(|| create_unsupported_operation(Context::genesis())) } + #[cfg(all(feature = "host_env", feature = "stdio"))] + pub(crate) fn default_text_encoding(vm: &VirtualMachine) -> PyResult { + TextIOWrapper::resolve_encoding(None, vm) + } + #[pyfunction] fn text_encoding( encoding: PyObjectRef, @@ -5849,8 +6383,8 @@ mod _io { && let Some(code) = crate::frame::current_code() && let Some(stdlib_dir) = vm.state.config.paths.stdlib_dir.as_deref() { - let path = code.source_path().as_str(); - if !path.starts_with(stdlib_dir) { + let path = code.source_path().as_bytes(); + if !path.starts_with(stdlib_dir.as_bytes()) { stacklevel = stacklevel.saturating_sub(1); } } @@ -5871,6 +6405,32 @@ mod _io { mod tests { use super::*; + #[test] + fn closed_memory_streams_release_storage() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let text = StringIO { + _base: Default::default(), + buffer: PyRwLock::new(StringIOBuffer::new(vec![b'x'; 1024])), + newline: AtomicCell::new(Newlines::Lf), + seennl: AtomicCell::new(SeenNewline::empty()), + closed: AtomicCell::new(false), + }; + let text = text.into_ref(&vm.ctx); + text.close(); + assert_eq!(text.buffer.read().bytes.cursor.get_ref().capacity(), 0); + + let bytes = BytesIO { + _base: Default::default(), + buffer: PyRwLock::new(BufferedIO::new(Cursor::new(vec![0; 1024]))), + closed: AtomicCell::new(false), + exports: AtomicCell::new(0), + }; + let bytes = bytes.into_ref(&vm.ctx); + bytes.close(vm).unwrap(); + assert_eq!(bytes.buffer.read().cursor.get_ref().capacity(), 0); + }); + } + #[test] fn buffered_read() { let data = vec![1, 2, 3, 4]; @@ -5906,15 +6466,15 @@ mod _io { } #[cfg_attr( - not(feature = "host_env"), + not(feature = "host_io"), expect(clippy::unnecessary_wraps, reason = "Needs to comply with a signature") )] pub(crate) fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { // Call auto-generated initialization first __module_exec(vm, module); - // Initialize FileIO types (requires host_env for filesystem access) - #[cfg(feature = "host_env")] + // Initialize FileIO types (requires host_io for descriptor access) + #[cfg(feature = "host_io")] super::fileio::module_exec(vm, module)?; // Initialize WindowsConsoleIO type (Windows only) @@ -5929,23 +6489,28 @@ mod _io { Ok(()) } } -// FileIO requires host environment for filesystem access -#[cfg(feature = "host_env")] +// FileIO requires host descriptor access, not the full Python OS module. +#[cfg(feature = "host_io")] #[pymodule] mod fileio { use super::{_io::*, Offset, iobase_finalize}; - use crate::host_env::crt_fd; + use crate::host_env::{ + crt_fd, + errno::errors::{EBADF, EINTR}, + os::ErrorExt, + }; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, - builtins::{PyBaseExceptionRef, PyUtf8Str, PyUtf8StrRef}, + builtins::{PyUtf8Str, PyUtf8StrRef}, common::wtf8::Wtf8Buf, convert::{IntoPyException, ToPyException}, - exceptions::OSErrorBuilder, + exceptions::ToOSErrorBuilder, function::{ArgBytesLike, ArgMemoryBuffer}, - ospath::{OsPath, OsPathOrFd}, - stdlib::os, + ospath::OsPath, types::{Constructor, DefaultConstructor, Destructor, Initializer, Representable}, }; + + use core::sync::atomic::{AtomicBool, Ordering}; use crossbeam_utils::atomic::AtomicCell; use rustpython_host_env::io as host_io; @@ -5959,14 +6524,15 @@ mod fileio { mode: AtomicCell, seekable: AtomicCell>, blksize: AtomicCell, - finalizing: AtomicCell, + #[pymember(name = "_finalizing", writable)] + finalizing: AtomicBool, } #[derive(FromArgs)] pub(super) struct FileIOArgs { #[pyarg(any)] file: PyObjectRef, - // Omitted mode is stored as rb. + // The input default is r; the mode property normalizes it to rb. #[pyarg(any, default, py_default = "'r'")] mode: Option, #[pyarg(any, default = true)] @@ -5984,7 +6550,7 @@ mod fileio { mode: AtomicCell::new(host_io::FileMode::empty()), seekable: AtomicCell::new(None), blksize: AtomicCell::new(super::DEFAULT_BUFFER_SIZE as _), - finalizing: AtomicCell::new(false), + finalizing: AtomicBool::new(false), } } } @@ -5995,40 +6561,37 @@ mod fileio { type Args = FileIOArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { + // Reinitialization detaches the old descriptor before validation or audit. + if zelf.closefd.load() { + zelf.internal_close() + .map_err(|err| err.to_pyexception(vm))?; + } else { + zelf.fd.store(-1); + } // TODO: let atomic_flag_works let name = args.file; - // Check if bool is used as file descriptor - if name.class().is(vm.ctx.types.bool_type) { - crate::stdlib::_warnings::warn( - vm.ctx.exceptions.runtime_warning, - "bool is used as a file descriptor".to_owned(), - 1, - vm, - )?; - } - let arg_fd = if let Some(i) = name.downcast_ref::() { - let fd = i.try_to_primitive(vm)?; - if fd < 0 { - return Err(vm.new_value_error("negative file descriptor")); - } - Some(fd) + let arg_fd = super::open_file_descriptor(&name, vm)?; + // Resolve the path before mode validation, even with a custom opener. + let mut path = if arg_fd.is_none() { + Some(OsPath::try_from_fspath(name.clone(), vm)?) } else { None }; let mode_obj = args .mode - .unwrap_or_else(|| PyUtf8Str::from("rb").into_ref(&vm.ctx)); + .unwrap_or_else(|| PyUtf8Str::from("r").into_ref(&vm.ctx)); let mode_str = mode_obj.as_str(); - let parsed = host_io::parse_fileio_mode(mode_str) + let parsed = host_io::parse_fileio_mode(mode_str, zelf.mode.load()) .map_err(|e| vm.new_value_error(e.error_msg(mode_str)))?; let mode = parsed.mode; let flags = parsed.flags; zelf.mode.store(mode); + vm.audit("open", || (name.clone(), mode_str, flags))?; - let (fd, filename) = if let Some(fd) = arg_fd { + let fd = if let Some(fd) = arg_fd { zelf.closefd.store(args.closefd); - (fd, None) + fd } else { zelf.closefd.store(true); if !args.closefd { @@ -6044,18 +6607,23 @@ mod fileio { if fd < 0 { return Err(vm.new_value_error(format!("opener returned {fd}"))); } - (fd, None) + fd } else { - let path = OsPath::try_from_fspath(name.clone(), vm)?; - #[cfg(any(unix, target_os = "wasi"))] - let fd = host_io::open_path(&path.clone().into_cstring(vm)?, flags, 0o666); + let path = path.take().expect("a filename was resolved above"); + #[cfg(not(windows))] + let raw_path = path.into_cstring(vm)?; #[cfg(windows)] - let fd = host_io::open_path(&path.to_wide_cstring(vm)?, flags, 0o666); - let filename = OsPathOrFd::Path(path); - match fd { - Ok(fd) => (fd.into_raw(), Some(filename)), - Err(e) => { - return Err(OSErrorBuilder::with_filename_from_errno(&e, filename, vm)); + let raw_path = path.to_wide_cstring(vm)?; + loop { + match vm.allow_threads(|| host_io::open_path(&raw_path, flags, 0o666)) { + Ok(fd) => break fd.into_raw(), + Err(e) if e.posix_errno() == EINTR => vm.check_signals()?, + Err(e) => { + return Err(e + .to_os_error_builder(vm) + .filename(name) + .into_pyexception(vm)); + } } } } @@ -6063,8 +6631,6 @@ mod fileio { let fd_is_own = arg_fd.is_none(); zelf.fd.store(fd); let fd = unsafe { crt_fd::Borrowed::borrow_raw(fd) }; - let filename = filename.unwrap_or(OsPathOrFd::Fd(fd)); - // TODO: _Py_set_inheritable match host_io::inspect_file_target(fd) { @@ -6077,12 +6643,19 @@ mod fileio { if host_io::should_forget_fd_after_inspect_error(&err, fd_is_own) { zelf.fd.store(-1); } - return Err(OSErrorBuilder::with_filename(&err, filename, vm)); + if err.posix_errno() == EBADF { + return Err(err.to_pyexception(vm)); + } + // Keep the original name alive through error construction and local cleanup. + return Err(err + .to_os_error_builder(vm) + .filename(name.as_object().to_owned()) + .into_pyexception(vm)); } } #[cfg(windows)] - crate::stdlib::msvcrt::setmode_binary(fd); + crate::host_env::msvcrt::setmode_binary(fd); if let Err(e) = zelf.as_object().set_attr("name", name, vm) { // If fd was passed by user, don't close it on error if !fd_is_own { @@ -6120,18 +6693,12 @@ mod fileio { } impl FileIO { - fn io_error( - zelf: &Py, - error: std::io::Error, - vm: &VirtualMachine, - ) -> PyBaseExceptionRef { - let exc = error.to_pyexception(vm); - if let Ok(name) = zelf.as_object().get_attr("name", vm) { - exc.as_object() - .set_attr("filename", name, vm) - .expect("OSError.filename set must success"); + fn internal_close(&self) -> std::io::Result<()> { + let fd = self.fd.swap(-1); + if fd >= 0 { + host_io::close_owned_fd(unsafe { crt_fd::Owned::from_raw(fd) })?; } - exc + Ok(()) } fn fileno(&self, vm: &VirtualMachine) -> PyResult { @@ -6150,7 +6717,6 @@ mod fileio { /// One `read()` into `buf`, retried on EINTR (PEP 475). `None` on EAGAIN. fn read_once_into( - zelf: &Py, handle: crt_fd::Borrowed<'_>, buf: &mut [u8], vm: &VirtualMachine, @@ -6163,7 +6729,7 @@ mod fileio { } // Non-blocking mode: return None if EAGAIN Err(e) if host_io::is_would_block_error(&e) => return Ok(None), - Err(e) => return Err(Self::io_error(zelf, e, vm)), + Err(e) => return Err(e.to_pyexception(vm)), } } } @@ -6184,8 +6750,8 @@ mod fileio { self.closefd.load() } - #[pygetset(name = "_blksize")] - fn blksize(&self) -> i64 { + #[pygetset] + fn _blksize(&self) -> i64 { self.blksize.load() } @@ -6242,31 +6808,40 @@ mod fileio { Err(e) if host_io::is_would_block_error(&e) => { return Ok(None); } - Err(e) => return Err(FileIO::io_error(zelf, e, vm)), + Err(e) => return Err(e.to_pyexception(vm)), } }; bytes.truncate(n); + bytes.shrink_to_fit(); bytes } else { - let mut bytes = vec![]; - // Loop on EINTR (PEP 475) + let mut bytes = Vec::new(); + let mut used = 0; + // Read one syscall at a time so EINTR reaches the Python + // signal handler instead of being retried inside read_to_end. loop { - match vm.allow_threads(|| host_io::read_all(handle, &mut bytes)) { - Ok(()) => break, - Err(e) if host_io::is_interrupted_error(&e) => { - vm.check_signals()?; - continue; - } - // Non-blocking mode: return None if EAGAIN (only if no data read yet) - Err(e) if host_io::is_would_block_error(&e) => { - if bytes.is_empty() { - return Ok(None); - } - break; - } - Err(e) => return Err(FileIO::io_error(zelf, e, vm)), + if used == bytes.len() { + // Match FileIO's amortized growth while leaving at least + // one byte for the read that detects EOF. + let growth = if used > 65_536 { used >> 3 } else { used + 256 }.max(8192); + let size = used.checked_add(growth).filter(|&n| isize::try_from(n).is_ok()) + .ok_or_else(|| vm.new_overflow_error( + "unbounded read returned more bytes than a Python bytes object can hold" + ))?; + bytes + .try_reserve_exact(growth) + .map_err(|_| vm.no_memory_error())?; + bytes.resize(size, 0); + } + match FileIO::read_once_into(handle, &mut bytes[used..], vm)? { + Some(0) => break, + Some(n) => used += n, + None if used == 0 => return Ok(None), + None => break, } } + bytes.truncate(used); + bytes.shrink_to_fit(); bytes }; @@ -6293,7 +6868,7 @@ mod fileio { // waiting on anyone; write where the caller asked directly. // Seekability is not the question -- a pipe on Windows seeks. let mut buf = buffer.borrow_buf_mut(); - return FileIO::read_once_into(zelf, handle, &mut buf, vm); + return FileIO::read_once_into(handle, &mut buf, vm); } // A pipe, socket or terminal answers only when the other end @@ -6305,7 +6880,7 @@ mod fileio { // across the wait stops the world from being stopped at all. Read // aside and take the lock for the copy. let mut scratch = vm.new_zeroed_bytes(buffer.len())?; - let ret = FileIO::read_once_into(zelf, handle, &mut scratch, vm)?; + let ret = FileIO::read_once_into(handle, &mut scratch, vm)?; if let Some(n) = ret { buffer.borrow_buf_mut()[..n].copy_from_slice(&scratch[..n]); } @@ -6338,7 +6913,7 @@ mod fileio { } // Non-blocking mode: return None if EAGAIN Err(e) if host_io::is_would_block_error(&e) => return Ok(None), - Err(e) => return Err(FileIO::io_error(zelf, e, vm)), + Err(e) => return Err(e.to_pyexception(vm)), } }; @@ -6354,17 +6929,13 @@ mod fileio { return res; } let flush_exc = res.err(); - if zelf.finalizing.load() { + if zelf.finalizing.load(Ordering::Relaxed) { FileIO::dealloc_warn(zelf, zelf.as_object(), vm); } - let fd = zelf.fd.swap(-1); - let close_err = if fd >= 0 { - host_io::close_owned_fd(unsafe { crt_fd::Owned::from_raw(fd) }) - .map_err(|err| FileIO::io_error(zelf, err, vm)) - .err() - } else { - None - }; + let close_err = zelf + .internal_close() + .map_err(|err| err.to_pyexception(vm)) + .err(); match (flush_exc, close_err) { (Some(fe), Some(ce)) => { ce.set_context(Some(fe)); @@ -6407,7 +6978,7 @@ mod fileio { Some(l) => get_offset(&l, vm)?, None => host_io::tell(fd).map_err(|e| e.into_pyexception(vm))?, }; - os::ftruncate(fd, len).map_err(|e| e.into_pyexception(vm))?; + crt_fd::ftruncate(fd, len).map_err(|e| e.into_pyexception(vm))?; Ok(len) } @@ -6423,8 +6994,8 @@ mod fileio { } // fileio_dealloc_warn in Modules/_io/fileio.c - #[pymethod(name = "_dealloc_warn")] - fn _dealloc_warn_method(zelf: &Self, object: PyObjectRef, vm: &VirtualMachine) { + #[pymethod] + fn _dealloc_warn(zelf: &Self, object: PyObjectRef, vm: &VirtualMachine) { FileIO::dealloc_warn(zelf, &object, vm); } } @@ -6451,7 +7022,7 @@ mod fileio { impl Destructor for FileIO { fn slot_del(zelf: &PyObject, vm: &VirtualMachine) -> PyResult<()> { if let Some(fileio) = zelf.downcast_ref::() { - fileio.finalizing.store(true); + fileio.finalizing.store(true, Ordering::Relaxed); } iobase_finalize(zelf, vm); Ok(()) @@ -6474,7 +7045,8 @@ mod winconsoleio { builtins::{PyBaseExceptionRef, PyUtf8StrRef}, common::{lock::PyMutex, wtf8::Wtf8Buf}, convert::{IntoPyException, ToPyException}, - function::{ArgBytesLike, ArgMemoryBuffer}, + exceptions::nul_char_error, + function::{ArgBytesLike, ArgMemoryBuffer, FsPath, OptionalArg}, types::{Constructor, DefaultConstructor, Destructor, Initializer, Representable}, }; use crossbeam_utils::atomic::AtomicCell; @@ -6486,6 +7058,11 @@ mod winconsoleio { const SMALLBUF: usize = 4; const BUFMAX: usize = 32 * 1024 * 1024; + pub(super) fn raw_console_fd(obj: &PyObject) -> Option { + obj.downcast_ref::() + .map(|stream| stream.fd.load()) + } + fn handle_from_fd(fd: i32) -> HANDLE { host_nt::handle_from_fd(fd) } @@ -6498,14 +7075,28 @@ mod winconsoleio { /// Returns 'r' (input), 'w' (output), 'x' (generic CON), or '\0' (not a console). pub(super) fn pyio_get_console_type(path_or_fd: &PyObject, vm: &VirtualMachine) -> char { // Try as integer fd first - if let Ok(fd) = i32::try_from_object(vm, path_or_fd.to_owned()) { + if let Ok(fd) = i32::try_from_object(vm, path_or_fd.to_owned()) + && fd >= 0 + { return host_nt::console_type_from_fd(fd); } // Try as string path - let Ok(name) = path_or_fd.str(vm) else { + let Ok(path) = FsPath::try_from_path_like(path_or_fd.to_owned(), true, vm) else { return '\0'; }; + let name = match &path { + FsPath::Str(name) => name.to_owned(), + FsPath::Bytes(_) => { + let Ok(path) = path.as_os_str(vm) else { + return '\0'; + }; + let Ok(name) = vm.fsdecode(path.into_owned()) else { + return '\0'; + }; + name + } + }; let Some(name_str) = name.to_str() else { // Surrogate strings can't be console device names return '\0'; @@ -6548,8 +7139,8 @@ mod winconsoleio { pub(super) struct WindowsConsoleIOArgs { #[pyarg(positional)] name: PyObjectRef, - #[pyarg(any, default)] - mode: Option, + #[pyarg(any, optional, py_default = "'r'")] + mode: OptionalArg>, #[pyarg(any, default = true)] closefd: bool, #[allow(dead_code)] @@ -6561,6 +7152,19 @@ mod winconsoleio { type Args = WindowsConsoleIOArgs; fn init(zelf: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult<()> { + let mode_str = match &args.mode { + OptionalArg::Present(Some(mode)) => mode.as_str(), + OptionalArg::Present(None) => { + return Err(vm.new_type_error( + "_WindowsConsoleIO() argument 'mode' must be str, not None", + )); + } + OptionalArg::Missing => "r", + }; + if mode_str.contains('\0') { + return Err(nul_char_error(vm)); + } + let nameobj = args.name; if zelf.fd.load() >= 0 { @@ -6571,28 +7175,24 @@ mod winconsoleio { } } - // Warn if bool is used as file descriptor - if nameobj.class().is(vm.ctx.types.bool_type) { - crate::stdlib::_warnings::warn( - vm.ctx.exceptions.runtime_warning, - "bool is used as a file descriptor".to_owned(), - 1, - vm, - )?; - } - - // Try to get fd from integer - let mut fd: i32 = -1; - if let Some(i) = nameobj.downcast_ref::() { - fd = i.try_to_primitive::(vm).unwrap_or(-1); - if fd < 0 { - return Err(vm.new_value_error("negative file descriptor")); - } - } + let mut fd = super::open_file_descriptor(&nameobj, vm)?.unwrap_or(-1); + let path = if fd < 0 { + let path = FsPath::try_from_path_like(nameobj.clone(), true, vm)?; + let decoded = match &path { + FsPath::Str(s) => s.to_owned(), + FsPath::Bytes(_) => vm.fsdecode(path.as_os_str(vm)?.into_owned())?, + }; + let wide = decoded + .as_wtf8() + .to_wide_cstring() + .map_err(|e| e.to_pyexception(vm))?; + let console_type = pyio_get_console_type(decoded.as_object(), vm); + Some((wide, console_type)) + } else { + None + }; // Parse mode - let mode_str: &str = args.mode.as_deref().map_or("r", |s| s.as_str()); - let mut rwa = false; let mut readable = false; let mut writable = false; @@ -6631,8 +7231,9 @@ mod winconsoleio { zelf.writable.store(writable); if fd < 0 { - // Get console type from name - console_type = pyio_get_console_type(&nameobj, vm); + // The decoded name was resolved before mode validation. + let (wide, detected_type) = path.expect("a filename was resolved above"); + console_type = detected_type; if console_type == 'x' { if writable { console_type = 'w'; @@ -6647,12 +7248,6 @@ mod winconsoleio { return Err(vm.new_value_error("Cannot use closefd=False with file name")); } - let name_str = nameobj.str(vm)?; - let wide = name_str - .as_wtf8() - .to_wide_cstring() - .map_err(|e| e.to_pyexception(vm))?; - fd = host_nt::open_console_path_fd(&wide, writable) .map_err(|err| err.to_pyexception(vm))?; } else { @@ -6789,8 +7384,8 @@ mod winconsoleio { self.closefd.load() } - #[pygetset(name = "_blksize")] - fn blksize(&self) -> i64 { + #[pygetset] + fn _blksize(&self) -> i64 { self.blksize.load() } @@ -6943,6 +7538,7 @@ mod winconsoleio { } buf.truncate(read_len); + buf.shrink_to_fit(); Ok(vm.ctx.new_bytes(buf).into()) } @@ -6973,8 +7569,8 @@ mod winconsoleio { .map_err(|err| err.into_pyexception(vm)) } - #[pymethod(name = "__reduce__")] - fn reduce(_zelf: &Self, vm: &VirtualMachine) -> PyResult { + #[pymethod] + fn __reduce__(_zelf: &Self, vm: &VirtualMachine) -> PyResult { Err(vm.new_type_error("cannot pickle '_WindowsConsoleIO' instances")) } } diff --git a/crates/vm/src/stdlib/_lsprof.rs b/crates/vm/src/stdlib/_lsprof.rs new file mode 100644 index 00000000000..b71d0bf0512 --- /dev/null +++ b/crates/vm/src/stdlib/_lsprof.rs @@ -0,0 +1,798 @@ +//! Deterministic profiling driven by the VM's execution monitoring events. +// cspell:ignore pystart pythrow creturn + +pub(crate) use _lsprof::module_def; + +#[pymodule] +mod _lsprof { + use crate::{ + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyResult, VirtualMachine, + builtins::{ + PyFloat, PyModule, PyStr, PyType, + builtin_func::{PyNativeFunction, PyNativeMethod}, + descriptor::PyMethodDescriptor, + }, + common::{lock::PyMutex, wtf8::Wtf8Buf}, + convert::ToPyObject, + function::{ArgIntoBool, FuncArgs, OptionalArg, PyMethodDef}, + object::{Traverse, TraverseFn}, + stdlib::sys::monitoring::MonitoringEvent, + types::{Constructor, Initializer, PyStructSequence}, + vm::thread::{self, critical_section, lock::PyMutex as OperationMutex}, + }; + use std::collections::HashMap; + + const TOOL_ID: i32 = 2; + const CALLBACKS: &[(MonitoringEvent, &str)] = &[ + (MonitoringEvent::PyStart, "_pystart_callback"), + (MonitoringEvent::PyResume, "_pystart_callback"), + (MonitoringEvent::PyThrow, "_pythrow_callback"), + (MonitoringEvent::PyReturn, "_pyreturn_callback"), + (MonitoringEvent::PyYield, "_pyreturn_callback"), + (MonitoringEvent::PyUnwind, "_pyreturn_callback"), + (MonitoringEvent::Call, "_ccall_callback"), + (MonitoringEvent::CReturn, "_creturn_callback"), + (MonitoringEvent::CRaise, "_creturn_callback"), + ]; + + #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] + enum Key { + Python(usize), + Native(usize), + } + + #[derive(Clone, Debug, Default)] + struct Counts { + total: i128, + inline: i128, + calls: usize, + recursive: usize, + depth: isize, + } + + impl Counts { + fn stop(&mut self, total: i128, inline: i128) { + self.depth -= 1; + if self.depth == 0 { + self.total += total; + } else { + self.recursive += 1; + } + self.inline += inline; + self.calls += 1; + } + } + + #[derive(Clone, Debug)] + struct Entry { + code: PyObjectRef, + // Dynamically allocated native method definitions must outlive their keys. + owner: Option, + counts: Counts, + callees: HashMap, + } + + #[derive(Debug)] + struct Context { + id: u64, + key: Key, + start: i128, + subtime: i128, + } + + #[derive(Debug, Default)] + struct State { + entries: HashMap, + stack: Vec, + epoch: u64, + next_context: u64, + missing: Option, + timer: Option, + unit: f64, + enabled: bool, + subcalls: bool, + builtins: bool, + in_timer: bool, + } + + #[pyattr] + #[pyclass(name = "Profiler", module = "_lsprof", traverse = "manual")] + #[derive(Debug, PyPayload)] + struct Profiler { + operation: OperationMutex, + interpreter_id: i64, + state: PyMutex, + } + + impl Profiler { + // Operation exclusion is separate from payload borrowing. Keep this + // profiler interpreter-bound even though PyMutex itself is not. + fn with_operation(&self, vm: &VirtualMachine, f: impl FnOnce() -> R) -> R { + assert_eq!(self.interpreter_id, vm.state.interpreter_id); + assert_eq!( + thread::try_with_current_vm(|current| current.state.interpreter_id), + Some(self.interpreter_id), + "profiler operation requires the current interpreter" + ); + #[cfg(feature = "threading")] + { + let slot = thread::current_thread_slot() + .expect("profiler operation requires a thread slot"); + assert_eq!( + slot.state.load(core::sync::atomic::Ordering::Acquire), + thread::ThreadState::Attached as i32, + "profiler operation requires an attached interpreter" + ); + } + critical_section::with(vm, &self.operation, f) + } + } + + // SAFETY: Each owned Python reference is visited exactly once. Contexts + // contain keys only; they do not own additional references to the entries. + unsafe impl Traverse for Profiler { + fn traverse(&self, tracer: &mut TraverseFn<'_>) { + { + let state = self.state.lock(); + state.timer.traverse(tracer); + state.missing.traverse(tracer); + #[expect( + clippy::iter_over_hash_type, + reason = "GC tracing visits every owned reference regardless of entry order" + )] + for entry in state.entries.values() { + entry.code.traverse(tracer); + entry.owner.traverse(tracer); + } + } + } + + fn clear(&mut self, out: &mut Vec) { + let state = self.state.get_mut(); + out.extend(state.timer.take()); + #[expect( + clippy::iter_over_hash_type, + reason = "GC clearing transfers every owned reference; entry order is irrelevant" + )] + for (_, entry) in state.entries.drain() { + out.push(entry.code); + out.extend(entry.owner); + } + out.extend(state.missing.take()); + state.stack.clear(); + state.enabled = false; + state.in_timer = false; + } + } + + #[derive(FromArgs)] + struct InitArgs { + #[pyarg(any, optional, py_default = "None")] + timer: OptionalArg, + #[pyarg(any, default = 0.0)] + timeunit: f64, + #[pyarg(any, default = ArgIntoBool::TRUE)] + subcalls: ArgIntoBool, + #[pyarg(any, default = ArgIntoBool::TRUE)] + builtins: ArgIntoBool, + } + + #[derive(FromArgs)] + struct EnableArgs { + #[pyarg(any, default = ArgIntoBool::TRUE)] + subcalls: ArgIntoBool, + #[pyarg(any, default = ArgIntoBool::TRUE)] + builtins: ArgIntoBool, + } + + impl Constructor for Profiler { + type Args = FuncArgs; + + fn py_new(_cls: &Py, _args: Self::Args, vm: &VirtualMachine) -> PyResult { + Ok(Self { + operation: OperationMutex::new(), + interpreter_id: vm.state.interpreter_id, + state: PyMutex::new(State::default()), + }) + } + } + + impl Initializer for Profiler { + type Args = InitArgs; + + fn init(zelf: &Py, args: InitArgs, vm: &VirtualMachine) -> PyResult<()> { + let old_timer = { + let mut state = zelf.state.lock(); + state.unit = args.timeunit; + state.subcalls = args.subcalls.into_bool(); + state.builtins = args.builtins.into_bool(); + core::mem::replace(&mut state.timer, args.timer.into_option()) + }; + drop(old_timer); + let monitoring = vm.sys_module.get_attr("monitoring", vm)?; + let missing = monitoring.get_attr("MISSING", vm); + let old_missing = { + let mut state = zelf.state.lock(); + core::mem::replace(&mut state.missing, missing.as_ref().ok().cloned()) + }; + drop(old_missing); + drop(monitoring); + missing.map(|_| ()) + } + } + + // Declared before the callable snapshot so its finalizer still observes + // in_timer during unwinding, as it does on the ordinary call-return path. + struct TimerCallGuard<'a> { + profiler: &'a Profiler, + active: bool, + } + + impl Drop for TimerCallGuard<'_> { + fn drop(&mut self) { + if self.active { + self.profiler.state.lock().in_timer = false; + } + } + } + + impl Profiler { + fn timer(&self, vm: &VirtualMachine) -> i128 { + let mut reset = TimerCallGuard { + profiler: self, + active: false, + }; + let timer = { + let mut state = self.state.lock(); + let timer = state.timer.clone(); + if timer.is_some() { + state.in_timer = true; + reset.active = true; + } + timer + }; + let result = if let Some(timer) = timer { + let value = timer.call((), vm); + // Release our callable root at call return, before clearing the + // flag. A replaced timer's finalizer is still inside the call. + drop(timer); + drop(reset); + // Conversion and result destruction occur with the flag clear. + let unit = self.state.lock().unit; + value.and_then(|value| { + if unit > 0.0 { + value.try_into_value::(vm).map(i128::from) + } else if let Some(value) = value.downcast_ref::() { + let nanos = (value.to_f64() * 1_000_000_000.0).floor(); + if nanos.is_nan() { + Err(vm.new_value_error("Invalid value NaN (not a number)")) + } else if !(i64::MIN as f64..-(i64::MIN as f64)).contains(&nanos) { + Err(vm + .new_overflow_error("timestamp too large to convert to C PyTime_t")) + } else { + Ok(nanos as i64 as i128) + } + } else { + let seconds = value.try_into_value::(vm)?; + seconds + .checked_mul(1_000_000_000) + .map(i128::from) + .ok_or_else(|| { + vm.new_overflow_error( + "timestamp too large to convert to C PyTime_t", + ) + }) + } + }) + } else { + super::super::time::profiler_time(vm).map(|nanos| nanos as i128) + }; + match result { + Ok(time) => time, + Err(error) => { + let timer = self.state.lock().timer.clone(); + let message = + timer + .as_ref() + .and_then(|timer| timer.repr(vm).ok()) + .map(|timer| { + format!("Exception ignored while calling _lsprof timer {timer}") + }); + drop(timer); + vm.run_unraisable(error, message, vm.ctx.none()); + 0 + } + } + } + + fn enter( + &self, + key: Key, + code: PyObjectRef, + owner: Option, + vm: &VirtualMachine, + ) { + // Unused input owners are dropped after the data guard, never in entry(). + let mut incoming = Some(Entry { + code, + owner, + counts: Counts::default(), + callees: HashMap::new(), + }); + let token = { + let mut state = self.state.lock(); + if state.in_timer { + return; + } + state + .entries + .entry(key) + .or_insert_with(|| incoming.take().unwrap()); + state.entries.get_mut(&key).unwrap().counts.depth += 1; + let caller = state + .subcalls + .then(|| state.stack.last().map(|ctx| ctx.key)) + .flatten(); + if let Some(caller) = caller { + state + .entries + .get_mut(&caller) + .unwrap() + .callees + .entry(key) + .or_default() + .depth += 1; + } + let id = state.next_context; + state.next_context = id + .checked_add(1) + .expect("profiler context identity exhausted"); + state.stack.push(Context { + id, + key, + start: 0, + subtime: 0, + }); + (state.epoch, id) + }; + drop(incoming); + let start = self.timer(vm); + let mut state = self.state.lock(); + if state.epoch == token.0 + && let Some(context) = state.stack.iter_mut().find(|context| context.id == token.1) + { + context.start = start; + } + } + + fn leave(&self, key: Key, vm: &VirtualMachine) { + let token = { + let mut state = self.state.lock(); + if state.in_timer { + return; + } + let Some(context) = state.stack.last() else { + return; + }; + let token = (state.epoch, context.id); + if !state.entries.contains_key(&key) { + state.stack.pop(); + return; + } + token + }; + let now = self.timer(vm); + let mut state = self.state.lock(); + // Clear or a reentrant return can retire the exact saved context. + if state.epoch != token.0 { + return; + } + let Some(index) = state.stack.iter().position(|context| context.id == token.1) else { + return; + }; + let context = &state.stack[index]; + let total = now - context.start; + let inline = total - context.subtime; + let caller = index.checked_sub(1).map(|index| state.stack[index].key); + if let Some(parent) = index.checked_sub(1).map(|index| &mut state.stack[index]) { + parent.subtime += total; + } + // Stop restores its saved previous context, even after reentrant entry. + // Retire any discarded suffix without fabricating completed calls. + state.stack.truncate(index); + state + .entries + .get_mut(&key) + .unwrap() + .counts + .stop(total, inline); + if state.subcalls + && let Some(caller) = caller + && let Some(counts) = state + .entries + .get_mut(&caller) + .and_then(|entry| entry.callees.get_mut(&key)) + { + counts.stop(total, inline); + } + } + } + + // Builtin keys use the method definition, never the transient bound method + // object or its receiver. This both aggregates calls and avoids retaining + // every receiver that the application has used while profiling. + enum NativeCall<'a> { + Function(&'a PyNativeFunction), + Descriptor(&'a Py, &'a PyObject), + } + + impl NativeCall<'_> { + fn key(&self) -> Key { + let method = match self { + Self::Function(function) => function.value, + Self::Descriptor(descriptor, _) => descriptor.method, + }; + Key::Native(method as *const PyMethodDef as usize) + } + + fn owner(&self) -> Option { + match self { + Self::Function(function) => function._method_def_owner.clone(), + Self::Descriptor(descriptor, _) => descriptor._method_def_owner.clone(), + } + } + + fn label(&self, vm: &VirtualMachine) -> PyObjectRef { + let function = match self { + Self::Descriptor(descriptor, receiver) => { + let name = descriptor.method.name; + if let Some(attribute) = receiver.class().get_attr(vm.ctx.intern_str(name)) + && let Ok(label) = attribute.repr(vm) + { + return label.into(); + } + return vm.ctx.new_str(format!("")).into(); + } + Self::Function(function) => function, + }; + let name = function.value.name; + // CPython normalizes the raw m_self, including STATIC's hidden + // type receiver, rather than its call-argument accessor. + let receiver = function.zelf.as_deref(); + let module = function.module.load_owned(); + let label = if let Some(receiver) = receiver { + if let Some(descriptor) = receiver.class().get_attr(vm.ctx.intern_str(name)) + && let Ok(label) = descriptor.repr(vm) + { + return label.into(); + } + if let Some(module) = module + .as_ref() + .and_then(|module| module.downcast_ref::()) + { + return qualified_label(module, name, true, vm); + } + format!("") + } else { + let module_name = if let Some(module) = module + .as_ref() + .and_then(|module| module.downcast_ref::()) + { + module + .dict() + .get_item_opt(identifier!(vm, __name__), vm) + .ok() + .flatten() + } else { + module + }; + if let Some(module) = module_name + .as_ref() + .and_then(|module| module.downcast_ref::()) + && module.as_wtf8() != "builtins" + { + return qualified_label(module, name, false, vm); + } + format!("<{name}>") + }; + vm.ctx.new_str(label).into() + } + } + + fn qualified_label( + module: &PyStr, + name: &str, + builtin: bool, + vm: &VirtualMachine, + ) -> PyObjectRef { + let mut label = Wtf8Buf::from(if builtin { ""); + vm.ctx.new_str(label).into() + } + + fn native_call<'a>( + callable: &'a PyObject, + arg: &'a PyObject, + missing: Option<&PyObjectRef>, + ) -> Option> { + if let Some(descriptor) = callable.downcast_ref::() { + if missing.is_some_and(|missing| arg.is(missing)) + || !arg.fast_isinstance(descriptor.common.typ) + { + return None; + } + return Some(NativeCall::Descriptor(descriptor, arg)); + } + let function = if let Some(function) = callable.downcast_ref::() { + &**function + } else { + let method = callable.downcast_ref::()?; + &method.func + }; + Some(NativeCall::Function(function)) + } + + #[pyclass(with(Constructor, Initializer), flags(BASETYPE))] + impl Profiler { + #[pymethod] + fn enable(zelf: &Py, args: EnableArgs, vm: &VirtualMachine) -> PyResult<()> { + zelf.with_operation(vm, || { + { + let mut state = zelf.state.lock(); + state.subcalls = args.subcalls.into_bool(); + state.builtins = args.builtins.into_bool(); + } + let monitoring = vm.sys_module.get_attr("monitoring", vm)?; + vm.call_method(&monitoring, "use_tool_id", (TOOL_ID, "cProfile"))?; + let mut events = 0; + for &(event, method) in CALLBACKS { + let callback = zelf.as_object().get_attr(method, vm)?; + vm.call_method( + &monitoring, + "register_callback", + (TOOL_ID, event.mask(), callback), + )?; + events |= event.mask(); + } + vm.call_method(&monitoring, "set_events", (TOOL_ID, events))?; + drop(monitoring); + zelf.state.lock().enabled = true; + Ok(()) + }) + } + + #[pymethod] + fn disable(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + zelf.with_operation(vm, || { + let (in_timer, enabled) = { + let state = zelf.state.lock(); + (state.in_timer, state.enabled) + }; + if in_timer { + return Err(vm.new_runtime_error("cannot disable profiler in external timer")); + } + if !enabled { + return Ok(()); + } + let monitoring = vm.sys_module.get_attr("monitoring", vm)?; + for &(event, _) in CALLBACKS { + vm.call_method( + &monitoring, + "register_callback", + (TOOL_ID, event.mask(), vm.ctx.none()), + )?; + } + vm.call_method(&monitoring, "set_events", (TOOL_ID, 0))?; + vm.call_method(&monitoring, "free_tool_id", (TOOL_ID,))?; + drop(monitoring); + zelf.state.lock().enabled = false; + loop { + let key = zelf.state.lock().stack.last().map(|ctx| ctx.key); + let Some(key) = key else { + break; + }; + zelf.leave(key, vm); + } + Ok(()) + }) + } + + #[pymethod] + fn clear(zelf: &Py, vm: &VirtualMachine) -> PyResult<()> { + zelf.with_operation(vm, || { + if zelf.state.lock().in_timer { + return Err(vm.new_runtime_error("cannot clear profiler in external timer")); + } + let _entries = { + let mut state = zelf.state.lock(); + state.stack.clear(); + state.epoch = state + .epoch + .checked_add(1) + .expect("profiler epoch exhausted"); + core::mem::take(&mut state.entries) + }; + Ok(()) + }) + } + + #[pymethod] + fn getstats(zelf: &Py, vm: &VirtualMachine) -> Vec { + zelf.with_operation(vm, || { + let (entries, factor) = { + let state = zelf.state.lock(); + let factor = if state.timer.is_some() && state.unit != 0.0 { + state.unit + } else { + 1e-9 + }; + (state.entries.clone(), factor) + }; + entries + .values() + .filter(|entry| entry.counts.calls != 0) + .map(|entry| { + let calls = if entry.callees.is_empty() { + vm.ctx.none() + } else { + vm.ctx + .new_list( + entry + .callees + .iter() + .map(|(key, counts)| { + SubentryData { + code: entries[key].code.clone(), + callcount: counts.calls, + reccallcount: counts.recursive, + totaltime: counts.total as f64 * factor, + inlinetime: counts.inline as f64 * factor, + } + .to_pyobject(vm) + }) + .collect(), + ) + .into() + }; + EntryData { + code: entry.code.clone(), + callcount: entry.counts.calls, + reccallcount: entry.counts.recursive, + totaltime: entry.counts.total as f64 * factor, + inlinetime: entry.counts.inline as f64 * factor, + calls, + } + .to_pyobject(vm) + }) + .collect() + }) + } + + #[pymethod] + fn _pystart_callback( + zelf: &Py, + code: PyObjectRef, + _instruction_offset: PyObjectRef, + vm: &VirtualMachine, + ) { + zelf.with_operation(vm, || { + zelf.enter(Key::Python(code.get_id()), code, None, vm); + }) + } + + #[pymethod] + fn _pythrow_callback( + zelf: &Py, + code: PyObjectRef, + _instruction_offset: PyObjectRef, + _exception: PyObjectRef, + vm: &VirtualMachine, + ) { + zelf.with_operation(vm, || { + zelf.enter(Key::Python(code.get_id()), code, None, vm); + }) + } + + #[pymethod] + fn _pyreturn_callback( + zelf: &Py, + code: PyObjectRef, + _instruction_offset: PyObjectRef, + _retval: PyObjectRef, + vm: &VirtualMachine, + ) { + zelf.with_operation(vm, || { + zelf.leave(Key::Python(code.get_id()), vm); + }) + } + + #[pymethod] + fn _ccall_callback( + zelf: &Py, + _code: PyObjectRef, + _instruction_offset: PyObjectRef, + callable: PyObjectRef, + self_arg: PyObjectRef, + vm: &VirtualMachine, + ) { + zelf.with_operation(vm, || { + let (builtins, missing) = { + let state = zelf.state.lock(); + (state.builtins, state.missing.clone()) + }; + if builtins && let Some(call) = native_call(&callable, &self_arg, missing.as_ref()) + { + if zelf.state.lock().in_timer { + return; + } + let key = call.key(); + let existing = zelf + .state + .lock() + .entries + .get(&key) + .map(|entry| entry.code.clone()); + let code = existing.unwrap_or_else(|| call.label(vm)); + zelf.enter(key, code, call.owner(), vm); + } + }) + } + + #[pymethod] + fn _creturn_callback( + zelf: &Py, + _code: PyObjectRef, + _instruction_offset: PyObjectRef, + callable: PyObjectRef, + self_arg: PyObjectRef, + vm: &VirtualMachine, + ) { + zelf.with_operation(vm, || { + let (builtins, missing) = { + let state = zelf.state.lock(); + (state.builtins, state.missing.clone()) + }; + if builtins && let Some(call) = native_call(&callable, &self_arg, missing.as_ref()) + { + zelf.leave(call.key(), vm); + } + }) + } + } + + #[pystruct_sequence_data] + struct EntryData { + code: PyObjectRef, + callcount: usize, + reccallcount: usize, + totaltime: f64, + inlinetime: f64, + calls: PyObjectRef, + } + + #[pyattr] + #[pystruct_sequence(name = "profiler_entry", module = "_lsprof", data = "EntryData")] + struct ProfilerEntry; + + #[pyclass(with(PyStructSequence))] + impl ProfilerEntry {} + + #[pystruct_sequence_data] + struct SubentryData { + code: PyObjectRef, + callcount: usize, + reccallcount: usize, + totaltime: f64, + inlinetime: f64, + } + + #[pyattr] + #[pystruct_sequence(name = "profiler_subentry", module = "_lsprof", data = "SubentryData")] + struct ProfilerSubentry; + + #[pyclass(with(PyStructSequence))] + impl ProfilerSubentry {} +} diff --git a/crates/vm/src/stdlib/_operator.rs b/crates/vm/src/stdlib/_operator.rs index 975521af1fe..5d566b0a007 100644 --- a/crates/vm/src/stdlib/_operator.rs +++ b/crates/vm/src/stdlib/_operator.rs @@ -3,11 +3,13 @@ pub(crate) use _operator::module_def; #[pymodule] mod _operator { use crate::{ - AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyInt, PyIntRef, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, PyUtf8StrRef}, - class::PyClassDef, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, + builtins::{PyIntRef, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef}, common::wtf8::{Wtf8, Wtf8Buf}, - function::{ArgBytesLike, ArgumentError, Either, FromArgs, FuncArgs, Param}, + function::{ + ArgBytesLike, ArgIndex, ArgumentError, Either, FromArgs, FuncArgs, OptionalArg, Param, + PosArgs, + }, protocol::PyIter, recursion::ReprGuard, types::{Callable, Constructor, PyComparisonOp, Representable}, @@ -158,17 +160,21 @@ mod _operator { // Sequence based operators + // A dict subclass has `__getitem__` but is a mapping, not a sequence. + fn check_concat_receiver(a: &PyObject, vm: &VirtualMachine) -> PyResult<()> { + if a.fast_isinstance(vm.ctx.types.dict_type) { + return Err(vm.new_type_error(format!( + "'{}' object can't be concatenated", + a.class().slot_name() + ))); + } + Ok(()) + } + #[pyfunction] fn concat(a: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // Best attempt at checking that a is sequence-like. - if !a.class().has_attr(identifier!(vm, __getitem__)) - || a.fast_isinstance(vm.ctx.types.dict_type) - { - return Err( - vm.new_type_error(format!("{} object can't be concatenated", a.class().name())) - ); - } - vm._add(&a, &b) + check_concat_receiver(&a, vm)?; + a.sequence_unchecked().concat(&b, vm) } #[pyfunction] @@ -181,7 +187,7 @@ mod _operator { let mut count: usize = 0; for element in a.iter::(vm)? { let element = element?; - if element.is(&b) || vm.bool_eq(&b, &element)? { + if element.is(&b) || vm.bool_eq(&element, &b)? { count += 1; } } @@ -202,7 +208,7 @@ mod _operator { fn index_of(a: PyIter, b: PyObjectRef, vm: &VirtualMachine) -> PyResult { for (index, element) in a.iter::(vm)?.enumerate() { let element = element?; - if element.is(&b) || vm.bool_eq(&b, &element)? { + if element.is(&b) || vm.bool_eq(&element, &b)? { return Ok(index); } } @@ -223,25 +229,20 @@ mod _operator { struct LengthHintArgs { #[pyarg(positional)] obj: PyObjectRef, - // The value is checked as an exact int. - #[pyarg(positional, default = 0)] - default: PyObjectRef, + #[pyarg(positional, optional, py_default = "0")] + default: OptionalArg, } #[pyfunction] - fn length_hint(args: LengthHintArgs, vm: &VirtualMachine) -> PyResult { + fn length_hint(args: LengthHintArgs, vm: &VirtualMachine) -> PyResult { let LengthHintArgs { obj, default } = args; - if !default.fast_isinstance(vm.ctx.types.int_type) { - return Err(vm.new_type_error(format!( - "'{}' object cannot be interpreted as an integer", - default.class().name() - ))); - } - let default: usize = default - .downcast_ref::() - .unwrap() - .try_to_primitive(vm)?; - obj.length_hint(default, vm) + let default = match default { + OptionalArg::Present(index) => index.as_ref().as_ssize_t(vm)?, + OptionalArg::Missing => 0, + }; + Ok(vm + .length_hint_opt(obj)? + .map_or(default, |hint| hint as isize)) } // Inplace Operators @@ -258,16 +259,8 @@ mod _operator { #[pyfunction] fn iconcat(a: PyObjectRef, b: PyObjectRef, vm: &VirtualMachine) -> PyResult { - // Best attempt at checking that a is sequence-like. - if !a.class().has_attr(identifier!(vm, __getitem__)) - || a.fast_isinstance(vm.ctx.types.dict_type) - { - return Err(vm.new_type_error(format!( - "'{}' object can't be concatenated", - a.class().name() - ))); - } - vm._iadd(&a, &b) + check_concat_receiver(&a, vm)?; + a.sequence_unchecked().inplace_concat(&b, vm) } #[pyfunction] @@ -351,28 +344,50 @@ mod _operator { } #[pyattr] - #[pyclass(name = "attrgetter", module = "operator")] + #[pyclass(name = "attrgetter", module = "operator", traverse)] #[derive(Debug, PyPayload)] struct PyAttrGetter { - attrs: Vec, + attrs: Vec>, } impl PyAttrGetter { + // Split at construction, as CPython does. Dotted str subclasses become + // exact strings; names without a dot keep the original string object. + fn prepare_attr(attr: PyStrRef, vm: &VirtualMachine) -> Vec { + if !attr.as_bytes().contains(&b'.') { + return vec![attr]; + } + attr.as_bytes() + .split(|&b| b == b'.') + .map(|part| { + let part = Wtf8::from_bytes(part).expect("originally valid WTF-8"); + vm.ctx.new_str(part) + }) + .collect() + } + + fn attr_name(parts: &[PyStrRef], vm: &VirtualMachine) -> PyStrRef { + if parts.len() == 1 { + return parts[0].clone(); + } + let mut name = Wtf8Buf::new(); + for (index, part) in parts.iter().enumerate() { + if index != 0 { + name.push_char('.'); + } + name.push_wtf8(part.as_wtf8()); + } + vm.ctx.new_str(name) + } + // Go through dotted parts of string and call getattr on whatever is returned. fn get_single_attr( - obj: PyObjectRef, - attr: &Py, + mut obj: PyObjectRef, + parts: &[PyStrRef], vm: &VirtualMachine, ) -> PyResult { - let attr_str = attr.as_bytes(); - let parts = attr_str.split(|&b| b == b'.').collect::>(); - if parts.len() == 1 { - return obj.get_attr(attr, vm); - } - let mut obj = obj; for part in parts { - let part = Wtf8::from_bytes(part).expect("originally valid WTF-8"); - obj = obj.get_attr(&vm.ctx.new_str(part), vm)?; + obj = obj.get_attr(part, vm)?; } Ok(obj) } @@ -387,23 +402,47 @@ mod _operator { #[pymethod] fn __reduce__(zelf: PyRef, vm: &VirtualMachine) -> (PyTypeRef, PyTupleRef) { - let attrs = vm - .ctx - .new_tuple(zelf.attrs.iter().map(|v| v.clone().into()).collect()); + let attrs = vm.ctx.new_tuple( + zelf.attrs + .iter() + .map(|parts| PyAttrGetter::attr_name(parts, vm).into()) + .collect(), + ); (zelf.class().to_owned(), attrs) } } - struct AttrGetterArgs(FuncArgs); + // These constructors reject keywords before checking arity or converting + // values. Keep that ordering while sharing the positional binder. + fn getter_args( + args: &mut FuncArgs, + name: &str, + vm: &VirtualMachine, + ) -> Result, ArgumentError> { + if !args.kwargs.is_empty() { + return Err(vm + .new_type_error(format!("{name}() takes no keyword arguments")) + .into()); + } + if args.args.is_empty() { + return Err(vm.new_arity_type_error(name, 1..=1, 0).into()); + } + Ok(PosArgs::::from_args(vm, args)?.into_vec()) + } + + struct AttrGetterArgs(Vec); impl FromArgs for AttrGetterArgs { + // CPython reports "expected 1 argument" even though this is variadic. + const BINDING_PARAMS: Option<&'static [Param]> = None; + const PARAMS: Option<&'static [Param]> = Some(&[ Param::positional_only("attr"), Param::var_positional("attrs"), ]); - fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result { - Ok(Self(core::mem::take(args))) + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + getter_args(args, "attrgetter", vm).map(Self) } } @@ -411,22 +450,12 @@ mod _operator { type Args = AttrGetterArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let args = args.0; - let n_attr = args.args.len(); - // Check we get no keyword and at least one positional. - if !args.kwargs.is_empty() { - return Err(vm.new_type_error("attrgetter() takes no keyword arguments")); - } - if n_attr == 0 { - return Err(vm.new_arity_type_error(Self::NAME, 1..=1, 0)); - } - let mut attrs = Vec::with_capacity(n_attr); - for o in args.args { - if let Ok(r) = o.try_into_value(vm) { - attrs.push(r); - } else { - return Err(vm.new_type_error("attribute name must be a string")); - } + let mut attrs = Vec::with_capacity(args.0.len()); + for obj in args.0 { + let attr = obj + .downcast::() + .map_err(|_| vm.new_type_error("attribute name must be a string"))?; + attrs.push(Self::prepare_attr(attr, vm)); } Ok(Self { attrs }) } @@ -459,7 +488,7 @@ mod _operator { result.push_str(", "); } first = false; - result.push_wtf8(part.as_object().repr(vm)?.as_wtf8()); + result.push_wtf8(Self::attr_name(part, vm).as_object().repr(vm)?.as_wtf8()); } } else { result.push_str("..."); @@ -470,7 +499,7 @@ mod _operator { } #[pyattr] - #[pyclass(name = "itemgetter", module = "operator")] + #[pyclass(name = "itemgetter", module = "operator", traverse)] #[derive(Debug, PyPayload)] struct PyItemGetter { items: Vec, @@ -489,32 +518,27 @@ mod _operator { vm.new_pyobj((zelf.class().to_owned(), items)) } } - struct ItemGetterArgs(FuncArgs); + struct ItemGetterArgs(Vec); impl FromArgs for ItemGetterArgs { + // CPython reports "expected 1 argument" even though this is variadic. + const BINDING_PARAMS: Option<&'static [Param]> = None; + const PARAMS: Option<&'static [Param]> = Some(&[ Param::positional_only("item"), Param::var_positional("items"), ]); - fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result { - Ok(Self(core::mem::take(args))) + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + getter_args(args, "itemgetter", vm).map(Self) } } impl Constructor for PyItemGetter { type Args = ItemGetterArgs; - fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let args = args.0; - // Check we get no keyword and at least one positional. - if !args.kwargs.is_empty() { - return Err(vm.new_type_error("itemgetter() takes no keyword arguments")); - } - if args.args.is_empty() { - return Err(vm.new_arity_type_error(Self::NAME, 1..=1, 0)); - } - Ok(Self { items: args.args }) + fn py_new(_cls: &Py, args: Self::Args, _vm: &VirtualMachine) -> PyResult { + Ok(Self { items: args.0 }) } } @@ -556,10 +580,10 @@ mod _operator { } #[pyattr] - #[pyclass(name = "methodcaller", module = "operator")] + #[pyclass(name = "methodcaller", module = "operator", traverse)] #[derive(Debug, PyPayload)] struct PyMethodCaller { - name: PyUtf8StrRef, + name: PyStrRef, args: FuncArgs, } @@ -591,32 +615,44 @@ mod _operator { } } - struct MethodCallerArgs(FuncArgs); + struct MethodCallerArgs { + name: PyStrRef, + args: FuncArgs, + } impl FromArgs for MethodCallerArgs { + // CPython names the missing method name in a bespoke constructor error. + const BINDING_PARAMS: Option<&'static [Param]> = None; + const PARAMS: Option<&'static [Param]> = Some(&[ Param::positional_only("name"), Param::var_positional("args"), Param::var_keyword("kwargs"), ]); - fn from_args(_vm: &VirtualMachine, args: &mut FuncArgs) -> Result { - Ok(Self(core::mem::take(args))) + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + let name = OptionalArg::::from_args(vm, args)? + .into_option() + .ok_or_else(|| { + vm.new_type_error("methodcaller needs at least one argument, the method name") + })? + .downcast::() + .map_err(|_| vm.new_type_error("method name must be a string"))?; + Ok(Self { + name, + args: FuncArgs::from_args(vm, args)?, + }) } } impl Constructor for PyMethodCaller { type Args = MethodCallerArgs; - fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let mut args = args.0; - let name = args.take_positional().ok_or_else(|| { - vm.new_type_error("methodcaller needs at least one argument, the method name") - })?; - let name = name - .try_into_value(vm) - .map_err(|_| vm.new_type_error("method name must be a string"))?; - Ok(Self { name, args }) + fn py_new(_cls: &Py, args: Self::Args, _vm: &VirtualMachine) -> PyResult { + Ok(Self { + name: args.name, + args: args.args, + }) } } @@ -625,7 +661,7 @@ mod _operator { #[inline] fn call(zelf: &Py, obj: Self::Args, vm: &VirtualMachine) -> PyResult { - vm.call_method(&obj, zelf.name.as_str(), zelf.args.clone()) + obj.get_attr(&zelf.name, vm)?.call(zelf.args.clone(), vm) } } diff --git a/crates/vm/src/stdlib/_signal.rs b/crates/vm/src/stdlib/_signal.rs index edbff6d5d02..384df69df4f 100644 --- a/crates/vm/src/stdlib/_signal.rs +++ b/crates/vm/src/stdlib/_signal.rs @@ -8,13 +8,14 @@ pub(crate) mod _signal { use crate::{ Py, PyObjectRef, PyResult, VirtualMachine, - signal::{self, SignalHandlers, SignalNum}, + function::ArgIntoBool, + signal::{self, SignalNum}, }; use core::sync::atomic::{self, Ordering}; cfg_select! { - any(unix, windows) => { - use crate::convert::{IntoPyException, TryFromBorrowedObject}; + any(unix, windows, target_os = "wasi") => { + use crate::convert::IntoPyException; use rustpython_host_env::signal as host_signal; } _ => {} @@ -24,12 +25,12 @@ pub(crate) mod _signal { unix => { use crate::{ builtins::{PyBaseExceptionRef, PyTypeRef}, - function::ArgIntoFloat, + stdlib::time::pytime::{self, Round}, }; - use rustpython_host_env::signal::{double_to_timeval, itimerval_to_tuple}; + use rustpython_host_env::signal::itimerval_to_tuple; use std::os::fd::AsFd; - }, + } _ => {} } @@ -41,27 +42,25 @@ pub(crate) mod _signal { cfg_select! { windows => { + use crate::convert::TryFromBorrowedObject; + type WakeupFdRaw = libc::SOCKET; struct WakeupFd(WakeupFdRaw); const INVALID_WAKEUP: libc::SOCKET = host_signal::INVALID_SOCKET; static WAKEUP: atomic::AtomicUsize = atomic::AtomicUsize::new(INVALID_WAKEUP); // windows doesn't use the same fds for files and sockets like windows does, so we need // this to know whether to send() or write() - static WAKEUP_IS_SOCKET: core::sync::atomic::AtomicBool = core::sync::atomic::AtomicBool::new(false); + static WAKEUP_IS_SOCKET: core::sync::atomic::AtomicBool = + core::sync::atomic::AtomicBool::new(false); impl<'a> TryFromBorrowedObject<'a> for WakeupFd { - fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a crate::PyObject) -> PyResult { - use num_traits::One; - - let fd: &crate::Py = obj.try_to_value(vm)?; - match fd.try_to_primitive::(vm) { - Ok(fd) => Ok(Self(fd as _)), - Err(e) => if (-fd.as_bigint()).is_one() { - Ok(Self(INVALID_WAKEUP)) - } else { - Err(e) - }, - } + fn try_from_borrowed_object( + vm: &VirtualMachine, + obj: &'a crate::PyObject, + ) -> PyResult { + // PyLong_AsSocket_t converts through a signed pointer-sized + // integer, including __index__, before casting to SOCKET. + isize::try_from_borrowed_object(vm, obj).map(|fd| Self(fd as _)) } } } @@ -73,11 +72,19 @@ pub(crate) mod _signal { } } + static WARN_ON_FULL_BUFFER: atomic::AtomicBool = atomic::AtomicBool::new(true); + + // Bounded pending-call storage: signal handlers cannot allocate or lock. #[cfg(any(unix, windows))] + static WAKEUP_WRITE_ERRORS: [atomic::AtomicI32; 32] = [const { atomic::AtomicI32::new(0) }; 32]; + #[cfg(windows)] + static WAKEUP_SEND_ERRORS: [atomic::AtomicI32; 32] = [const { atomic::AtomicI32::new(0) }; 32]; + + #[cfg(any(unix, windows, target_os = "wasi"))] #[allow(unused_imports)] pub use host_signal::SIG_ERR; - #[cfg(any(unix, windows))] + #[cfg(any(unix, windows, target_os = "wasi"))] #[pyattr] pub use host_signal::{SIG_DFL, SIG_IGN}; @@ -86,22 +93,22 @@ pub(crate) mod _signal { #[pyattr] use host_signal::{SIG_BLOCK, SIG_SETMASK, SIG_UNBLOCK}; - #[cfg(not(any(unix, windows)))] + #[cfg(not(any(unix, windows, target_os = "wasi")))] #[pyattr] pub const SIG_DFL: sighandler_t = 0; - #[cfg(not(any(unix, windows)))] + #[cfg(not(any(unix, windows, target_os = "wasi")))] #[pyattr] pub const SIG_IGN: sighandler_t = 1; - #[cfg(not(any(unix, windows)))] + #[cfg(not(any(unix, windows, target_os = "wasi")))] #[allow(dead_code)] pub const SIG_ERR: sighandler_t = -1 as _; #[pyattr] use crate::signal::NSIG; - #[cfg(any(unix, windows))] + #[cfg(any(unix, windows, target_os = "wasi"))] #[pyattr] pub use host_signal::{SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM}; @@ -152,15 +159,19 @@ pub(crate) mod _signal { } #[cfg(unix)] - fn new_itimer_error(msg: &str, vm: &VirtualMachine) -> PyBaseExceptionRef { - vm.new_os_subtype_error(itimer_error(vm), None, msg) + fn new_itimer_error(err: std::io::Error, vm: &VirtualMachine) -> PyBaseExceptionRef { + let errno = err.raw_os_error(); + let message = errno + .and_then(rustpython_host_env::errno::strerror_string) + .unwrap_or_else(|| err.to_string()); + vm.new_os_subtype_error(itimer_error(vm), errno, message) .upcast() } const _: () = assert!(SignalNum::VALID_RANGE.start.is_positive()); const _: () = assert!(SignalNum::VALID_RANGE.end.is_positive()); - #[cfg(any(unix, windows))] + #[cfg(any(unix, windows, target_os = "wasi"))] pub(super) fn init_signal_handlers( module: &Py, vm: &VirtualMachine, @@ -175,9 +186,16 @@ pub(crate) mod _signal { let Some(handler) = (unsafe { host_signal::probe_handler(signum) }) else { continue; }; - let py_handler = if handler == SIG_DFL { + let (is_default, is_ignored) = cfg_select! { + target_os = "wasi" => ( + handler == host_signal::Handler::Default, + handler == host_signal::Handler::Ignore, + ), + _ => (handler == SIG_DFL, handler == SIG_IGN), + }; + let py_handler = if is_default { Some(sig_dfl.clone()) - } else if handler == SIG_IGN { + } else if is_ignored { Some(sig_ign.clone()) } else { None @@ -186,20 +204,74 @@ pub(crate) mod _signal { // SAFETY: Trust `SignalNum::VALID_RANGE` let signum = unsafe { SignalNum::new_unchecked(signum) }; - vm.signal_handlers - .get_or_init(SignalHandlers::default) - .borrow_mut()[signum] = py_handler; + signal::INTERRUPT_IGNORED[signum.as_usize()] + .store(is_default || is_ignored, Ordering::Relaxed); + let signal_handlers = &vm.state.signal_handlers; + let _old_handler = + core::mem::replace(&mut signal_handlers.lock()[signum], py_handler); + // Replacing a handler can run its destructor, which may install + // another handler. Release the table lock before dropping it. } - let int_handler = module - .get_attr("default_int_handler", vm) - .expect("_signal does not have this attr?"); + let sigint_handler = vm.state.signal_handlers.lock()[SignalNum::SIGINT].clone(); + let default_sigint = sigint_handler + .is_some_and(|handler| handler_disposition(&handler, vm) == Some(SIG_DFL)); + if default_sigint { + let int_handler = module + .get_attr("default_int_handler", vm) + .expect("_signal does not have this attr?"); + + // An inherited ignored or foreign native handler is not ours + // to replace, even when installing Python's default handlers. + signal(SignalNum::SIGINT.into(), int_handler, vm) + .expect("Failed to set sigint handler"); + } + } + } - signal(SignalNum::SIGINT, int_handler, vm).expect("Failed to set sigint handler"); + /// CPython's _PySignal_Fini: disable native callbacks before user objects + /// are collected, but allow simulated interrupts to report missing handlers. + #[cfg(any(unix, windows, target_os = "wasi"))] + pub(crate) fn finalize_signal_handlers(vm: &VirtualMachine) { + if !vm.state.is_main_interpreter() { + return; } + for raw in SignalNum::VALID_RANGE { + // SAFETY: The range excludes invalid signal table indices. + let signum = unsafe { SignalNum::new_unchecked(raw) }; + signal::TRIGGERS[signum.as_usize()].store(false, Ordering::Relaxed); + let handler = { + let mut handlers = vm.state.signal_handlers.lock(); + signal::INTERRUPT_IGNORED[signum.as_usize()].store(false, Ordering::Relaxed); + handlers[signum].take() + }; + if let Some(handler) = handler { + if !vm.is_none(&handler) && handler_disposition(&handler, vm).is_none() { + let default = cfg_select! { + target_os = "wasi" => host_signal::Handler::Default, + _ => SIG_DFL, + }; + // SAFETY: Only dispositions installed by Python are reset. + let _ = unsafe { host_signal::install_handler(raw, default) }; + } + // A destructor may register another handler. Do not hold the + // table lock or overwrite its disposition after dropping it. + drop(handler); + } + } + } + + pub(crate) fn handler_disposition( + handler: &crate::PyObject, + vm: &VirtualMachine, + ) -> Option { + handler + .downcast_ref_if_exact::(vm) + .and_then(|value| usize::try_from(value.as_bigint()).ok()) + .filter(|&value| matches!(value, SIG_DFL | SIG_IGN)) } - #[cfg(not(any(unix, windows)))] + #[cfg(not(any(unix, windows, target_os = "wasi")))] #[pyfunction] pub fn signal( _signalnum: i32, @@ -209,29 +281,51 @@ pub(crate) mod _signal { Err(vm.new_not_implemented_error("signal is not implemented on this platform")) } - #[cfg(any(unix, windows))] + #[cfg(any(unix, windows, target_os = "wasi"))] #[pyfunction] pub fn signal( - signalnum: SignalNum, + signalnum: i32, handler: PyObjectRef, vm: &VirtualMachine, ) -> PyResult> { - if !vm.is_main_thread() { + #[cfg(windows)] + if !matches!( + signalnum, + SIGABRT | SIGBREAK | SIGFPE | SIGILL | SIGINT | SIGSEGV | SIGTERM + ) { + return Err(vm.new_value_error("invalid signal value")); + } + + if !vm.is_main_thread() || !vm.state.is_main_interpreter() { return Err( vm.new_value_error("signal only works in main thread of the main interpreter") ); } + let signalnum = SignalNum::try_from(signalnum).map_err(|msg| vm.new_value_error(msg))?; + let sig_handler = if handler.is_callable() { - run_signal as *const () as sighandler_t + let callback = run_signal as *const () as sighandler_t; + cfg_select! { + target_os = "wasi" => host_signal::Handler::Custom(callback), + _ => callback, + } } else { const MSG: &str = "signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object"; - usize::try_from_borrowed_object(vm, &handler) - .ok() - .filter(|&v| matches!(v, SIG_DFL | SIG_IGN)) - .ok_or_else(|| vm.new_type_error(MSG))? + let disposition = + handler_disposition(&handler, vm).ok_or_else(|| vm.new_type_error(MSG))?; + cfg_select! { + target_os = "wasi" => { + if disposition == SIG_DFL { + host_signal::Handler::Default + } else { + host_signal::Handler::Ignore + } + }, + _ => disposition, + } }; signal::check_signals(vm)?; @@ -239,23 +333,30 @@ pub(crate) mod _signal { unsafe { host_signal::install_handler(signalnum.into(), sig_handler) } .map_err(|err| err.into_pyexception(vm))?; - let signal_handlers = vm.signal_handlers.get_or_init(SignalHandlers::default); - let old_handler = signal_handlers.borrow_mut()[signalnum].replace(handler); + let signal_handlers = &vm.state.signal_handlers; + let old_handler = { + let mut handlers = signal_handlers.lock(); + signal::INTERRUPT_IGNORED[signalnum.as_usize()].store( + handler_disposition(&handler, vm).is_some(), + Ordering::Relaxed, + ); + handlers[signalnum].replace(handler) + }; Ok(old_handler) } #[pyfunction] fn getsignal(signalnum: SignalNum, vm: &VirtualMachine) -> PyObjectRef { - let signal_handlers = vm.signal_handlers.get_or_init(SignalHandlers::default); - signal_handlers.borrow()[signalnum] + let signal_handlers = &vm.state.signal_handlers; + signal_handlers.lock()[signalnum] .clone() .unwrap_or_else(|| vm.ctx.none()) } #[cfg(unix)] #[pyfunction] - fn alarm(seconds: u32) -> u32 { - rustpython_host_env::signal::alarm(seconds) + fn alarm(seconds: i32) -> u32 { + rustpython_host_env::signal::alarm(seconds as u32) } #[cfg(unix)] @@ -272,9 +373,9 @@ pub(crate) mod _signal { #[pyarg(positional)] which: i32, #[pyarg(positional)] - seconds: ArgIntoFloat, - #[pyarg(positional, default = 0.0)] - interval: ArgIntoFloat, + seconds: PyObjectRef, + #[pyarg(positional, optional, py_default = "0.0")] + interval: crate::function::OptionalArg, } #[cfg(unix)] @@ -285,15 +386,39 @@ pub(crate) mod _signal { seconds, interval, } = args; - let seconds: f64 = seconds.into(); - let interval: f64 = interval.into(); + let it_value = timer_timeval(&seconds, vm)?; + let it_interval = match interval { + crate::function::OptionalArg::Present(interval) => timer_timeval(&interval, vm)?, + crate::function::OptionalArg::Missing => libc::timeval { + tv_sec: 0, + tv_usec: 0, + }, + }; let new = libc::itimerval { - it_value: double_to_timeval(seconds), - it_interval: double_to_timeval(interval), + it_value, + it_interval, }; host_signal::setitimer(which, &new) .map(|old| itimerval_to_tuple(&old)) - .map_err(|err| new_itimer_error(&err.to_string(), vm)) + .map_err(|err| new_itimer_error(err, vm)) + } + + #[cfg(unix)] + fn timer_timeval(object: &crate::PyObject, vm: &VirtualMachine) -> PyResult { + let nanoseconds = pytime::from_seconds_object(object, Round::Ceiling, vm)?; + let microseconds = Round::Ceiling.divide(nanoseconds, 1_000); + let seconds = microseconds.div_euclid(1_000_000); + #[allow( + clippy::useless_conversion, + reason = "time_t may be narrower on 32-bit targets" + )] + let tv_sec = seconds + .try_into() + .map_err(|_| vm.new_overflow_error("timestamp out of range for platform time_t"))?; + Ok(libc::timeval { + tv_sec, + tv_usec: microseconds.rem_euclid(1_000_000) as _, + }) } #[cfg(unix)] @@ -301,36 +426,30 @@ pub(crate) mod _signal { fn getitimer(which: i32, vm: &VirtualMachine) -> PyResult<(f64, f64)> { host_signal::getitimer(which) .map(|old| itimerval_to_tuple(&old)) - .map_err(|err| new_itimer_error(&err.to_string(), vm)) + .map_err(|err| new_itimer_error(err, vm)) } #[pyfunction] - fn default_int_handler( - _signalnum: PyObjectRef, - _frame: PyObjectRef, - vm: &VirtualMachine, - ) -> PyResult { + fn default_int_handler(_signalnum: i32, _frame: PyObjectRef, vm: &VirtualMachine) -> PyResult { Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned())) } #[derive(FromArgs)] struct SetWakeupFdArgs { #[pyarg(positional)] - fd: WakeupFd, - #[pyarg(named, default = true)] - warn_on_full_buffer: bool, + fd: PyObjectRef, + #[pyarg(named, default = ArgIntoBool::TRUE)] + warn_on_full_buffer: ArgIntoBool, } #[pyfunction] fn set_wakeup_fd(args: SetWakeupFdArgs, vm: &VirtualMachine) -> PyResult { - // TODO: implement warn_on_full_buffer - let _ = args.warn_on_full_buffer; - let fd = cfg_select! { - windows => args.fd.0, - _ => args.fd, - }; + // The keyword truth value is parsed before the fd conversion in CPython. + let fd = args.fd.try_to_value::(vm)?; + #[cfg(windows)] + let fd = fd.0; - if !vm.is_main_thread() { + if !vm.is_main_thread() || !vm.state.is_main_interpreter() { return Err(vm.new_value_error( "set_wakeup_fd only works in main thread of the main interpreter", )); @@ -360,6 +479,7 @@ pub(crate) mod _signal { } let old_fd = WAKEUP.swap(fd, Ordering::Relaxed); + WARN_ON_FULL_BUFFER.store(args.warn_on_full_buffer.into_bool(), Ordering::Relaxed); #[cfg(windows)] WAKEUP_IS_SOCKET.store(is_socket, Ordering::Relaxed); @@ -373,44 +493,52 @@ pub(crate) mod _signal { } #[cfg(any(target_os = "android", target_os = "linux"))] - use crate::function::OptionalArg; + #[derive(FromArgs)] + struct PidfdSendSignalArgs { + #[pyarg(positional)] + pidfd: i32, + #[pyarg(positional)] + signalnum: core::ffi::c_int, + #[pyarg(positional, default = None)] + siginfo: Option, + #[pyarg(positional, default)] + flags: core::ffi::c_int, + } #[cfg(any(target_os = "android", target_os = "linux"))] #[pyfunction] fn pidfd_send_signal( - pidfd: i32, - sig: SignalNum, - siginfo: OptionalArg, - flags: OptionalArg, + PidfdSendSignalArgs { + pidfd, + signalnum, + siginfo, + flags, + }: PidfdSendSignalArgs, vm: &VirtualMachine, ) -> PyResult<()> { - if let OptionalArg::Present(obj) = siginfo - && !vm.is_none(&obj) - { + if siginfo.is_some() { return Err(vm.new_type_error("siginfo must be None")); } - let flags = flags.unwrap_or(0); - host_signal::pidfd_send_signal(pidfd, sig.into(), flags) + host_signal::pidfd_send_signal(pidfd, signalnum, flags as u32) .map_err(|_| vm.new_last_errno_error()) } #[cfg(all(unix, not(target_os = "redox")))] - #[pyfunction(name = "siginterrupt")] - fn py_siginterrupt(signalnum: SignalNum, flag: i32, vm: &VirtualMachine) -> PyResult<()> { + #[pyfunction] + fn siginterrupt(signalnum: SignalNum, flag: i32, vm: &VirtualMachine) -> PyResult<()> { host_signal::siginterrupt(signalnum.into(), flag).map_err(|_| vm.new_last_errno_error()) } - #[cfg(any(unix, windows))] + #[cfg(any(unix, windows, target_os = "wasi"))] #[pyfunction] fn raise_signal(signalnum: i32, vm: &VirtualMachine) -> PyResult<()> { let signalnum = SignalNum::try_from(signalnum).map_err(cfg_select! { - windows => { - |_| vm.new_errno_error(libc::EINVAL, "Invalid argument").upcast() + windows => |_| { + vm.new_errno_error(libc::EINVAL, "Invalid argument") + .upcast() }, - _ => { - |msg| vm.new_value_error(msg) - } + _ => |msg| vm.new_value_error(msg), })?; vm.allow_threads(|| host_signal::raise_signal(signalnum.into())) @@ -506,18 +634,102 @@ pub(crate) mod _signal { sigset_to_pyset(old_mask, vm) } - #[cfg(any(unix, windows))] + #[cfg(any(unix, windows, target_os = "wasi"))] pub extern "C" fn run_signal(signum: i32) { + // Asynchronously executing signal handlers should not mutate errno + // under the feet of the interrupted code. + let save_errno = rustpython_host_env::os::get_errno(); + trip_signal(signum); + rustpython_host_env::os::set_errno(save_errno); + } + + #[cfg(any(unix, windows, target_os = "wasi"))] + fn trip_signal(signum: i32) { signal::TRIGGERS[signum as usize].store(true, Ordering::Relaxed); signal::set_triggered(); - host_signal::notify_signal( - signum, - WAKEUP.load(Ordering::Relaxed), - #[cfg(windows)] - WAKEUP_IS_SOCKET.load(Ordering::Relaxed), - #[cfg(windows)] - signal::get_sigint_event(), + #[cfg(target_os = "wasi")] + host_signal::notify_signal(signum, WAKEUP.load(Ordering::Relaxed)); + + #[cfg(any(unix, windows))] + { + let error = host_signal::notify_signal( + signum, + WAKEUP.load(Ordering::Relaxed), + #[cfg(windows)] + WAKEUP_IS_SOCKET.load(Ordering::Relaxed), + #[cfg(windows)] + signal::get_sigint_event(), + ); + if let Some(error) = error + && (WARN_ON_FULL_BUFFER.load(Ordering::Relaxed) || !error.is_would_block()) + { + let (errors, errno) = match error { + host_signal::WakeupError::Write(errno) => (&WAKEUP_WRITE_ERRORS, errno), + #[cfg(windows)] + host_signal::WakeupError::Send(errno) => (&WAKEUP_SEND_ERRORS, errno), + }; + for pending in errors { + if pending + .compare_exchange(0, errno, Ordering::Relaxed, Ordering::Relaxed) + .is_ok() + { + // The VM may have handled the signal on another thread + // before the failed wakeup write completed. + signal::set_triggered(); + break; + } + } + } + } + } + + #[cfg(any(unix, windows))] + pub(crate) fn wakeup_errors_pending() -> bool { + let pending = WAKEUP_WRITE_ERRORS + .iter() + .any(|error| error.load(Ordering::Relaxed) != 0); + #[cfg(windows)] + let pending = pending + || WAKEUP_SEND_ERRORS + .iter() + .any(|error| error.load(Ordering::Relaxed) != 0); + pending + } + + #[cfg(any(unix, windows))] + pub(crate) fn report_wakeup_errors(vm: &VirtualMachine) { + fn report( + errors: &[atomic::AtomicI32], + make_error: fn(i32) -> host_signal::WakeupError, + operation: &str, + vm: &VirtualMachine, + ) { + for pending in errors { + let errno = pending.swap(0, Ordering::Relaxed); + if errno != 0 { + vm.run_unraisable( + make_error(errno).into_io_error().into_pyexception(vm), + Some(format!( + "Exception ignored while trying to {operation} to the signal wakeup fd" + )), + vm.ctx.none(), + ); + } + } + } + report( + &WAKEUP_WRITE_ERRORS, + host_signal::WakeupError::Write, + "write", + vm, + ); + #[cfg(windows)] + report( + &WAKEUP_SEND_ERRORS, + host_signal::WakeupError::Send, + "send", + vm, ); } @@ -535,7 +747,7 @@ pub(crate) mod _signal { ) -> PyResult<()> { __module_exec(vm, module); - #[cfg(any(unix, windows))] + #[cfg(any(unix, windows, target_os = "wasi"))] init_signal_handlers(module, vm); Ok(()) diff --git a/crates/vm/src/stdlib/_sre.rs b/crates/vm/src/stdlib/_sre.rs index af5b75fc8a7..1c1b5ecdebb 100644 --- a/crates/vm/src/stdlib/_sre.rs +++ b/crates/vm/src/stdlib/_sre.rs @@ -12,7 +12,7 @@ mod _sre { common::wtf8::{Wtf8, Wtf8Buf, wtf8_concat}, common::{ascii, hash::PyHash}, convert::ToPyObject, - function::{ArgCallable, OptionalArg, PosArgs, PyComparisonValue}, + function::{ArgCallable, DefaultRepr, PosArgs, PyComparisonValue}, protocol::{BufferFlags, PyBuffer, PyCallable, PyMappingMethods}, stdlib::sys, types::{AsMapping, Comparable, Hashable, Representable}, @@ -59,7 +59,17 @@ mod _sre { fn slice(&self, start: usize, end: usize, vm: &VirtualMachine) -> PyObjectRef; fn create_request(self, pattern: &Pattern, start: usize, end: usize) -> Request<'_, Self> { - Request::new(self, start, end, &pattern.code, false) + let request = Request::new(self, start, end, &pattern.code, false); + #[cfg(all(feature = "host_env", any(unix, windows)))] + let request = Request { + locale: rustpython_sre_engine::Locale { + is_alnum: rustpython_host_env::locale::byte_isalnum, + to_lower: rustpython_host_env::locale::byte_tolower, + to_upper: rustpython_host_env::locale::byte_toupper, + }, + ..request + }; + request } } @@ -216,7 +226,7 @@ mod _sre { #[pyarg(any)] pattern: PyObjectRef, #[pyarg(any)] - flags: u16, + flags: i32, #[pyarg(any)] code: PyObjectRef, #[pyarg(any)] @@ -246,7 +256,7 @@ mod _sre { let code = code.try_to_value(vm)?; Ok(Pattern { pattern, - flags: SreFlag::from_bits_truncate(flags), + flags, code, groups, groupindex, @@ -328,18 +338,36 @@ mod _sre { #[derive(FromArgs)] struct DefaultArg { // Missing default is None. - #[pyarg(any, optional, py_default = "None")] - default: OptionalArg, + #[pyarg(any, default = None)] + default: Option, + } + + /// A position in the searched string, taken as a Py_ssize_t; a negative + /// one means the start of the string. + #[derive(Clone, Copy)] + struct StringPos(usize); + + impl StringPos { + const fn py_default(self) -> DefaultRepr { + DefaultRepr::Int(self.0 as i128) + } + } + + impl TryFromObject for StringPos { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let pos: isize = obj.try_into_value(vm)?; + Ok(Self(pos.max(0) as usize)) + } } #[derive(FromArgs)] struct StringArgs { string: PyObjectRef, - #[pyarg(any, default)] - pos: usize, + #[pyarg(any, default = StringPos(0))] + pos: StringPos, // Platform ssize maximum, shown as sys.maxsize. - #[pyarg(any, default = sys::MAXSIZE as usize, py_default = "sys.maxsize")] - endpos: usize, + #[pyarg(any, default = StringPos(sys::MAXSIZE as usize), py_default = "sys.maxsize")] + endpos: StringPos, } #[derive(FromArgs)] @@ -348,7 +376,7 @@ mod _sre { repl: PyObjectRef, string: PyObjectRef, #[pyarg(any, default)] - count: usize, + count: isize, } #[derive(FromArgs)] @@ -363,7 +391,7 @@ mod _sre { #[derive(Debug, PyPayload)] pub(crate) struct Pattern { pub pattern: PyObjectRef, - pub flags: SreFlag, + pub flags: i32, pub code: Vec, pub groups: usize, pub groupindex: PyDictRef, @@ -372,11 +400,16 @@ mod _sre { } macro_rules! with_sre_str { - ($pattern:expr, $string:expr, $vm:expr, $f:expr) => {{ + ($pattern:expr, $string:expr, $vm:expr, $f:expr) => { + with_sre_str!($pattern, $string, $vm, $f, None::<&PyBuffer>) + }; + ($pattern:expr, $string:expr, $vm:expr, $f:expr, $buffer:expr) => {{ // Bind once: the branches only borrow the subject, and callers pass // a temporary (`&x.clone()`) that would otherwise be rebuilt per arm. let subject = $string; - if $pattern.isbytes { + if let Some(buffer) = $buffer { + buffer.contiguous_or_collect($f) + } else if $pattern.isbytes { Pattern::with_bytes(subject, $vm, $f) } else if Pattern::is_ascii_str(subject) { Pattern::with_ascii_str(subject, $vm, $f) @@ -393,13 +426,6 @@ mod _sre { }) } - fn with_str(string: &PyObject, vm: &VirtualMachine, f: F) -> PyResult - where - F: FnOnce(&Wtf8) -> PyResult, - { - f(Self::downcast_str(string, vm)?.as_wtf8()) - } - /// Whether a `str` subject can take the [`AsciiStr`] drive. /// /// `PyStr` already knows: `StrKind` is decided when the string is @@ -454,64 +480,124 @@ mod _sre { let filter = if let Some(callable) = repl.to_callable() { FilterType::Callable(callable) } else { - let is_template = if zelf.isbytes { - Self::with_bytes(&repl, vm, |x| Ok(x.contains(&b'\\')))? + // Literal detection is independent of the pattern's type. A + // mismatched literal only fails when a match actually uses it. + // Other objects must go through re's template compiler, which + // also supplies the replacement conversion errors. + let literal = if let Some(repl) = repl.downcast_ref::() { + !repl.as_wtf8().contains("\\".as_ref()) } else { - Self::with_str(&repl, vm, |x| Ok(x.contains("\\".as_ref())))? + Self::with_bytes(&repl, vm, |x| Ok(!x.contains(&b'\\'))).unwrap_or(false) }; - - if is_template { - FilterType::Template(Template::compile(zelf.to_owned(), repl, vm)?) - } else { + if literal { FilterType::Literal(repl) + } else { + let template = Template::compile(zelf.to_owned(), repl, vm)?; + if template.items.is_empty() { + FilterType::Literal(template.literal.clone()) + } else { + FilterType::Template(template) + } } }; - with_sre_str!(zelf, &string, vm, |s| { - let req = s.create_request(zelf, 0, usize::MAX); - let state = State::default(); - let mut sub_list: Vec = Vec::new(); - let mut iter = SearchIter { req, state }; - let mut n = 0; - let mut last_pos = 0; - - while (count == 0 || n < count) && iter.next().is_some() { - if last_pos < iter.state.start { - /* get segment before this match */ - sub_list.push(s.slice(last_pos, iter.state.start, vm)); - } - - match &filter { - FilterType::Literal(literal) => sub_list.push(literal.clone()), - FilterType::Callable(callable) => { - let m = Match::new(&mut iter.state, zelf.to_owned(), string.clone()) - .into_ref(&vm.ctx); - sub_list.push(callable.invoke((m,), vm)?); + // Keep the export until searching finishes, but never hold a byte + // borrow while invoking a replacement. Callbacks may mutate bytes + // in place or inspect their match; resizing must remain forbidden. + let buffer = if zelf.isbytes { + Some(PyBuffer::from_object(vm, &string, BufferFlags::SIMPLE)?) + } else { + Self::downcast_str(&string, vm)?; + None + }; + let mut sub_list: Vec = Vec::new(); + let mut n = 0; + let mut last_pos = 0; + let mut must_advance = false; + let mut state = State::default(); + + while count == 0 || n < count { + let matched = with_sre_str!( + zelf, + &string, + vm, + |s| { + let mut req = s.create_request(zelf, last_pos, usize::MAX); + req.must_advance = must_advance; + // Reuse mark storage, replacing the cursor with one + // from this borrow before the engine can read it. + state.reset(&req, last_pos); + if !state.search(req) { + return Ok(None); } - FilterType::Template(template) => { - let m = Match::new(&mut iter.state, zelf.to_owned(), string.clone()); - m.expand_template(template, s, &mut sub_list, vm); + + if last_pos < state.start { + sub_list.push(s.slice(last_pos, state.start, vm)); } - }; + last_pos = state.cursor.position; + must_advance = last_pos == state.start; + let callback = match &filter { + FilterType::Literal(literal) => { + sub_list.push(literal.clone()); + None + } + FilterType::Template(template) => { + let matched = + Match::new(&mut state, zelf.to_owned(), string.clone()); + matched.expand_template(template, s, &mut sub_list, vm); + None + } + FilterType::Callable(callable) => { + let mut matched = + Match::new(&mut state, zelf.to_owned(), string.clone()); + matched.pos = 0; + matched.endpos = s.count(); + Some((matched, callable)) + } + }; + Ok(Some(callback)) + }, + buffer.as_ref() + )?; + let Some(matched) = matched else { + break; + }; - last_pos = iter.state.cursor.position; - n += 1; + if let Some((matched, callable)) = matched { + // Only offsets and the original subject escape the search + // borrow. Reacquiring it next time observes in-place edits. + let replacement = callable.invoke((matched.into_ref(&vm.ctx),), vm)?; + if !vm.is_none(&replacement) { + sub_list.push(replacement); + } } + n += 1; + } - /* get segment following last match */ - sub_list.push(s.slice(last_pos, iter.req.end, vm)); - - let list = PyList::from(sub_list).into_pyobject(vm); - - let join_type: PyObjectRef = if zelf.isbytes { - vm.ctx.new_bytes(vec![]).into() - } else { - vm.ctx.new_str(ascii!("")).into() - }; - let ret = vm.call_method(&join_type, "join", (list,))?; - - Ok(if subn { (ret, n).to_pyobject(vm) } else { ret }) - }) + with_sre_str!( + zelf, + &string, + vm, + |s| { + if last_pos < s.count() { + sub_list.push(s.slice(last_pos, s.count(), vm)); + } + Ok(()) + }, + buffer.as_ref() + )?; + // Joining can itself access buffer-valued replacements. Release + // the subject export and replacement filter before that step. + drop(buffer); + drop(filter); + let list = PyList::from(sub_list).into_pyobject(vm); + let join_type: PyObjectRef = if zelf.isbytes { + vm.ctx.new_bytes(vec![]).into() + } else { + vm.ctx.new_str(ascii!("")).into() + }; + let ret = vm.call_method(&join_type, "join", (list,))?; + Ok(if subn { (ret, n).to_pyobject(vm) } else { ret }) } } @@ -521,6 +607,17 @@ mod _sre { flags(HAS_WEAKREF) )] impl Py { + #[pymethod] + fn __copy__(zelf: PyRef) -> PyRef { + zelf + } + + #[pymethod] + fn __deepcopy__(zelf: PyRef, _memo: PyObjectRef) -> PyRef { + zelf + } + + #[pymethod(name = "prefixmatch")] #[pymethod(name = "match")] fn py_match( zelf: PyRef, @@ -533,7 +630,7 @@ mod _sre { endpos, } = string_args; with_sre_str!(zelf, &string.clone(), vm, |x| { - let req = x.create_request(&zelf, pos, endpos); + let req = x.create_request(&zelf, pos.0, endpos.0); let mut state = State::default(); Ok(state .py_match(&req) @@ -548,7 +645,7 @@ mod _sre { vm: &VirtualMachine, ) -> PyResult>> { with_sre_str!(zelf, &string_args.string.clone(), vm, |x| { - let mut req = x.create_request(&zelf, string_args.pos, string_args.endpos); + let mut req = x.create_request(&zelf, string_args.pos.0, string_args.endpos.0); req.match_all = true; let mut state = State::default(); Ok(state.py_match(&req).then(|| { @@ -564,7 +661,7 @@ mod _sre { vm: &VirtualMachine, ) -> PyResult>> { with_sre_str!(zelf, &string_args.string.clone(), vm, |x| { - let req = x.create_request(&zelf, string_args.pos, string_args.endpos); + let req = x.create_request(&zelf, string_args.pos.0, string_args.endpos.0); let mut state = State::default(); Ok(state.search(req).then(|| { Match::new(&mut state, zelf.clone(), string_args.string).into_ref(&vm.ctx) @@ -579,7 +676,7 @@ mod _sre { vm: &VirtualMachine, ) -> PyResult> { with_sre_str!(zelf, &string_args.string, vm, |s| { - let req = s.create_request(&zelf, string_args.pos, string_args.endpos); + let req = s.create_request(&zelf, string_args.pos.0, string_args.endpos.0); let state = State::default(); let mut match_list: Vec = Vec::new(); let mut iter = SearchIter { req, state }; @@ -604,7 +701,7 @@ mod _sre { } else { m.groups( DefaultArg { - default: OptionalArg::Present(empty.clone()), + default: Some(empty.clone()), }, vm, )? @@ -624,14 +721,7 @@ mod _sre { string_args: StringArgs, vm: &VirtualMachine, ) -> PyResult { - let scanner = SreScanner { - pattern: zelf, - string: string_args.string, - start: AtomicCell::new(string_args.pos), - end: string_args.endpos, - must_advance: AtomicCell::new(false), - } - .into_ref(&vm.ctx); + let scanner = Self::scanner(zelf, string_args, vm)?; let search = vm.get_str_method(scanner.into(), "search").unwrap()?; let search = ArgCallable::try_from_object(vm, search)?; let iterator = PyCallableIterator::new(search, vm.ctx.none()); @@ -643,15 +733,26 @@ mod _sre { zelf: PyRef, string_args: StringArgs, vm: &VirtualMachine, - ) -> PyRef { - SreScanner { + ) -> PyResult> { + let buffer = if zelf.isbytes { + Some(PyBuffer::from_object( + vm, + &string_args.string, + BufferFlags::SIMPLE, + )?) + } else { + Pattern::downcast_str(&string_args.string, vm)?; + None + }; + Ok(SreScanner { pattern: zelf, string: string_args.string, - start: AtomicCell::new(string_args.pos), - end: string_args.endpos, + buffer, + start: AtomicCell::new(string_args.pos.0), + end: string_args.endpos.0, must_advance: AtomicCell::new(false), } - .into_ref(&vm.ctx) + .into_ref(&vm.ctx)) } #[pymethod] @@ -702,8 +803,8 @@ mod _sre { } #[pygetset] - fn flags(&self) -> u16 { - self.flags.bits() + fn flags(&self) -> i32 { + self.flags } #[pygetset] @@ -742,8 +843,8 @@ mod _sre { let hash = zelf.pattern.hash(vm)?; let (_, code, _) = unsafe { zelf.code.align_to::() }; let hash = hash ^ crate::vm::hash_secret().hash_bytes(code); - let hash = hash ^ (zelf.flags.bits() as PyHash); - let hash = hash ^ (zelf.isbytes as i64); + let hash = hash ^ (zelf.flags as PyHash); + let hash = hash ^ (zelf.isbytes as PyHash); Ok(hash) } } @@ -790,17 +891,24 @@ mod _sre { /* Omit re.UNICODE for valid string patterns. */ let mut flags = zelf.flags; if !zelf.isbytes - && (flags & (SreFlag::LOCALE | SreFlag::UNICODE | SreFlag::ASCII)) - == SreFlag::UNICODE + && (flags & i32::from((SreFlag::LOCALE | SreFlag::UNICODE | SreFlag::ASCII).bits())) + == i32::from(SreFlag::UNICODE.bits()) { - flags &= !SreFlag::UNICODE; + flags &= !i32::from(SreFlag::UNICODE.bits()); } - let flags = flag_names - .iter() - .filter(|(_, flag)| flags.contains(*flag)) - .map(|(name, _)| name) - .join("|"); + let mut flag_items = Vec::new(); + for (name, flag) in flag_names { + let flag = i32::from(flag.bits()); + if flags & flag != 0 { + flag_items.push(name.to_owned()); + flags &= !flag; + } + } + if flags != 0 { + flag_items.push(format!("0x{:x}", flags as u32)); + } + let flags = flag_items.join("|"); let pattern = zelf.pattern.repr(vm)?; let mut result = Wtf8Buf::from("re.compile("); @@ -944,6 +1052,16 @@ mod _sre { flags(DISALLOW_INSTANTIATION) )] impl Py { + #[pymethod] + fn __copy__(zelf: PyRef) -> PyRef { + zelf + } + + #[pymethod] + fn __deepcopy__(zelf: PyRef, _memo: PyObjectRef) -> PyRef { + zelf + } + #[pygetset] fn pos(&self) -> usize { self.pos @@ -1119,13 +1237,17 @@ mod _sre { } #[pyattr] - #[pyclass(name = "SRE_Scanner")] + #[pyclass(name = "SRE_Scanner", traverse)] #[derive(Debug, PyPayload)] struct SreScanner { pattern: PyRef, string: PyObjectRef, + buffer: Option, + #[pytraverse(skip)] start: AtomicCell, + #[pytraverse(skip)] end: usize, + #[pytraverse(skip)] must_advance: AtomicCell, } @@ -1139,23 +1261,30 @@ mod _sre { self.pattern.clone() } + #[pymethod(name = "prefixmatch")] #[pymethod(name = "match")] fn py_match(&self, vm: &VirtualMachine) -> PyResult>> { - with_sre_str!(self.pattern, &self.string.clone(), vm, |s| { - let mut req = s.create_request(&self.pattern, self.start.load(), self.end); - let mut state = State::default(); - req.must_advance = self.must_advance.load(); - let has_matched = state.py_match(&req); - - self.must_advance - .store(state.cursor.position == state.start); - self.start.store(state.cursor.position); - - Ok(has_matched.then(|| { - Match::new(&mut state, self.pattern.clone(), self.string.clone()) - .into_ref(&vm.ctx) - })) - }) + with_sre_str!( + self.pattern, + &self.string.clone(), + vm, + |s| { + let mut req = s.create_request(&self.pattern, self.start.load(), self.end); + let mut state = State::default(); + req.must_advance = self.must_advance.load(); + let has_matched = state.py_match(&req); + + self.must_advance + .store(state.cursor.position == state.start); + self.start.store(state.cursor.position); + + Ok(has_matched.then(|| { + Match::new(&mut state, self.pattern.clone(), self.string.clone()) + .into_ref(&vm.ctx) + })) + }, + self.buffer.as_ref() + ) } #[pymethod] @@ -1163,22 +1292,28 @@ mod _sre { if self.start.load() > self.end { return Ok(None); } - with_sre_str!(self.pattern, &self.string.clone(), vm, |s| { - let mut req = s.create_request(&self.pattern, self.start.load(), self.end); - let mut state = State::default(); - req.must_advance = self.must_advance.load(); - - let has_matched = state.search(req); - - self.must_advance - .store(state.cursor.position == state.start); - self.start.store(state.cursor.position); - - Ok(has_matched.then(|| { - Match::new(&mut state, self.pattern.clone(), self.string.clone()) - .into_ref(&vm.ctx) - })) - }) + with_sre_str!( + self.pattern, + &self.string.clone(), + vm, + |s| { + let mut req = s.create_request(&self.pattern, self.start.load(), self.end); + let mut state = State::default(); + req.must_advance = self.must_advance.load(); + + let has_matched = state.search(req); + + self.must_advance + .store(state.cursor.position == state.start); + self.start.store(state.cursor.position); + + Ok(has_matched.then(|| { + Match::new(&mut state, self.pattern.clone(), self.string.clone()) + .into_ref(&vm.ctx) + })) + }, + self.buffer.as_ref() + ) } } } diff --git a/crates/vm/src/stdlib/_stat.rs b/crates/vm/src/stdlib/_stat.rs index 42d02d58f2c..ece04140373 100644 --- a/crates/vm/src/stdlib/_stat.rs +++ b/crates/vm/src/stdlib/_stat.rs @@ -275,76 +275,76 @@ mod _stat { const S_IMODE: Mode = 0o7777; - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISDIR(object: ModeArg) -> bool { (object.0 & S_IFMT) == S_IFDIR } - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISCHR(object: ModeArg) -> bool { (object.0 & S_IFMT) == S_IFCHR } - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISREG(object: ModeArg) -> bool { (object.0 & S_IFMT) == S_IFREG } - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISBLK(object: ModeArg) -> bool { (object.0 & S_IFMT) == S_IFBLK } - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISFIFO(object: ModeArg) -> bool { (object.0 & S_IFMT) == S_IFIFO } - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISLNK(object: ModeArg) -> bool { (object.0 & S_IFMT) == S_IFLNK } - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISSOCK(object: ModeArg) -> bool { (object.0 & S_IFMT) == S_IFSOCK } // TODO: RUSTPYTHON Support Solaris - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISDOOR(_object: ModeArg) -> bool { false } // TODO: RUSTPYTHON Support Solaris - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISPORT(_object: ModeArg) -> bool { false } // TODO: RUSTPYTHON Support BSD - #[pyfunction] + #[pyfunction(signature_from_flags)] #[allow(non_snake_case)] const fn S_ISWHT(_object: ModeArg) -> bool { false } - #[pyfunction(name = "S_IMODE")] + #[pyfunction(name = "S_IMODE", signature_from_flags)] #[allow(non_snake_case)] const fn S_IMODE_method(object: ModeArg) -> Mode { object.0 & S_IMODE } - #[pyfunction(name = "S_IFMT")] + #[pyfunction(name = "S_IFMT", signature_from_flags)] #[allow(non_snake_case)] const fn S_IFMT_method(object: ModeArg) -> Mode { object.0 & S_IFMT @@ -379,7 +379,7 @@ mod _stat { } // Convert file mode to string representation - #[pyfunction] + #[pyfunction(signature_from_flags)] fn filemode(object: ModeArg) -> String { let mut result = String::with_capacity(10); diff --git a/crates/vm/src/stdlib/_string.rs b/crates/vm/src/stdlib/_string.rs index f55a62e40e6..522d3cd72a5 100644 --- a/crates/vm/src/stdlib/_string.rs +++ b/crates/vm/src/stdlib/_string.rs @@ -7,14 +7,17 @@ pub(crate) use _string::module_def; mod _string { use crate::common::ascii; use crate::common::format::{ - FieldName, FieldNamePart, FieldType, FormatPart, FormatString, FromTemplate, + FieldName, FieldNamePart, FieldNameParts, FieldType, FormatPart, FormatString, FromTemplate, }; use crate::common::wtf8::{CodePoint, Wtf8Buf}; use crate::{ - PyObjectRef, PyResult, VirtualMachine, + Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, builtins::{PyList, PyStrRef}, + common::lock::PyMutex, convert::ToPyException, convert::ToPyObject, + protocol::PyIterReturn, + types::{IterNext, Iterable, SelfIter}, }; use core::mem; @@ -34,7 +37,7 @@ mod _string { tuple.to_pyobject(vm) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn formatter_parser(object: PyStrRef, vm: &VirtualMachine) -> PyResult { let format_string = FormatString::from_str(object.as_wtf8()).map_err(|e| e.to_pyexception(vm))?; @@ -71,29 +74,50 @@ mod _string { Ok(result.into()) } - #[pyfunction] + #[pyclass(no_attr, name = "fieldnameiterator", module = "builtins", traverse)] + #[derive(Debug, PyPayload)] + struct FieldNameIterator { + #[pytraverse(skip)] + parts: PyMutex, + } + + #[pyclass(with(IterNext, Iterable), flags(DISALLOW_INSTANTIATION))] + impl FieldNameIterator {} + + impl SelfIter for FieldNameIterator {} + + impl IterNext for FieldNameIterator { + fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let part = zelf.parts.lock().next(); + let Some(part) = part else { + return Ok(PyIterReturn::StopIteration(None)); + }; + let value = match part.map_err(|e| e.to_pyexception(vm))? { + FieldNamePart::Attribute(attribute) => (true, attribute).to_pyobject(vm), + FieldNamePart::StringIndex(index) => (false, index).to_pyobject(vm), + FieldNamePart::Index(index) => (false, index).to_pyobject(vm), + }; + Ok(PyIterReturn::Return(value)) + } + } + + #[pyfunction(signature_from_flags)] fn formatter_field_name_split( object: PyStrRef, vm: &VirtualMachine, - ) -> PyResult<(PyObjectRef, PyList)> { - let field_name = FieldName::parse(object.as_wtf8()).map_err(|e| e.to_pyexception(vm))?; + ) -> PyResult<(PyObjectRef, PyObjectRef)> { + let (field_type, parts) = + FieldName::split(object.as_wtf8()).map_err(|e| e.to_pyexception(vm))?; - let first = match field_name.field_type { + let first = match field_type { FieldType::Auto => vm.ctx.new_str(ascii!("")).into(), FieldType::Index(index) => index.to_pyobject(vm), FieldType::Keyword(attribute) => attribute.to_pyobject(vm), }; - - let rest = field_name - .parts - .iter() - .map(|p| match p { - FieldNamePart::Attribute(attribute) => (true, attribute).to_pyobject(vm), - FieldNamePart::StringIndex(index) => (false, index).to_pyobject(vm), - FieldNamePart::Index(index) => (false, *index).to_pyobject(vm), - }) - .collect(); - - Ok((first, rest)) + let rest = FieldNameIterator { + parts: PyMutex::new(parts), + } + .into_ref(&vm.ctx); + Ok((first, rest.into())) } } diff --git a/crates/vm/src/stdlib/_symtable.rs b/crates/vm/src/stdlib/_symtable.rs index c2d781dbba4..0a91a830ff8 100644 --- a/crates/vm/src/stdlib/_symtable.rs +++ b/crates/vm/src/stdlib/_symtable.rs @@ -3,11 +3,12 @@ pub(crate) use _symtable::module_def; #[pymodule] mod _symtable { use crate::{ - AsObject, Py, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyBaseExceptionRef, PyDictRef, PyListRef, PyStr, PyUtf8StrRef}, + AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyBaseExceptionRef, PyDictRef, PyListRef, PyStr, PyStrRef, PyUtf8StrRef}, compiler, function::{ArgStrOrBytesLike, FsPath}, types::Representable, + vm::VmCompileError, }; use alloc::fmt; use rustpython_codegen::symboltable::{CompilerScope, SymbolFlags, SymbolScope, SymbolTable}; @@ -96,13 +97,26 @@ mod _symtable { #[pyattr] pub(super) const TYPE_TYPE_VARIABLE: i32 = 6; - #[pyfunction] - fn symtable( + #[derive(FromArgs)] + struct SymtableArgs { + #[pyarg(positional)] source: ArgStrOrBytesLike, + #[pyarg(positional)] filename: FsPath, + #[pyarg(positional)] startstr: PyUtf8StrRef, - vm: &VirtualMachine, - ) -> PyResult> { + #[pyarg(named, optional)] + module: Option, + } + + #[pyfunction] + fn symtable(args: SymtableArgs, vm: &VirtualMachine) -> PyResult> { + let SymtableArgs { + source, + filename, + startstr, + module, + } = args; let mode = startstr .as_str() .parse::() @@ -111,8 +125,8 @@ mod _symtable { let filename_obj = match &filename { FsPath::Str(filename) => filename.clone(), FsPath::Bytes(filename) => { - let filename = FsPath::bytes_as_os_str(filename.as_bytes(), vm)?.to_owned(); - vm.fsdecode(filename) + let filename = FsPath::bytes_as_os_str(filename.as_bytes(), vm)?.into_owned(); + vm.fsdecode(filename)? } }; let filename = filename_obj.to_string_lossy(); @@ -128,10 +142,35 @@ mod _symtable { "source code string cannot contain null bytes".into(), )); } - let symtable = compiler::compile_symtable(&source, mode, &filename).map_err(|err| { - let err = vm.new_syntax_error(&err, Some(&source)); - set_syntax_error_filename(err, &filename_obj, vm) - })?; + let module = module.filter(|module| !vm.is_none(module)); + let module = module + .map(|module| { + PyStrRef::try_from_object(vm, module.clone()).map_err(|_| { + vm.new_type_error(format!( + "symtable() argument 'module' must be str or None, not {}", + module.class().name() + )) + }) + }) + .transpose()?; + let symtable = vm + .compile_symtable_with_module( + &source, + mode, + &filename, + &filename_obj, + module.as_deref(), + ) + .map_err(|err| match err { + VmCompileError::Exception(error) => error, + VmCompileError::Compile(err) => { + let err = vm.new_syntax_error(&err, Some(&source)); + set_syntax_error_filename(err, &filename_obj, vm) + } + // Warning hooks may raise their own exception, including a + // SyntaxError subclass. Propagate it without changing attributes. + warning @ VmCompileError::Warning(_) => warning.into_pyexception(vm, Some(&source)), + })?; Ok(to_py_symbol_table(symtable, vm)) } @@ -221,7 +260,13 @@ mod _symtable { impl Py { #[pygetset] fn name(&self) -> String { - self.symtable.name.to_string() + match self.symtable.typ { + CompilerScope::Lambda => "".to_owned(), + CompilerScope::Comprehension if self.symtable.name.as_str() == "genexpr" => { + "".to_owned() + } + _ => self.symtable.name.to_string(), + } } #[pygetset(name = "type")] diff --git a/crates/vm/src/stdlib/_sysconfig.rs b/crates/vm/src/stdlib/_sysconfig.rs index 2de27d71ac9..4464c528fbe 100644 --- a/crates/vm/src/stdlib/_sysconfig.rs +++ b/crates/vm/src/stdlib/_sysconfig.rs @@ -1,24 +1,83 @@ pub(crate) use _sysconfig::module_def; #[pymodule] -pub(crate) mod _sysconfig { +pub(crate) mod _missing_stdlib_info { use crate::{VirtualMachine, builtins::PyDictRef, convert::ToPyObject}; + #[pyattr(name = "_MISSING_STDLIB_MODULE_MESSAGES")] + fn missing_stdlib_module_messages(vm: &VirtualMachine) -> PyDictRef { + let messages = vm.ctx.new_dict(); + // CPython's Tools/build/check_extension_modules.py emits these entries + // unconditionally, including on Windows. Do not infer disabled build + // features from CPython's module inventory: ours is different. + for name in [ + "_overlapped", + "_testconsole", + "_winapi", + "_wmi", + "msvcrt", + "nt", + "winreg", + "winsound", + ] { + let message = + format!("Unsupported platform for Windows-only standard library module '{name}'"); + messages + .set_item(name, message.to_pyobject(vm), vm) + .unwrap(); + } + // This module is only implemented for macOS in our stdlib as well. + #[cfg(not(target_os = "macos"))] + messages + .set_item( + "_scproxy", + "Unsupported platform for standard library module '_scproxy'".to_pyobject(vm), + vm, + ) + .unwrap(); + messages + } +} + +#[pymodule] +pub(crate) mod _sysconfig { + #[cfg(windows)] + use crate::builtins::PyStrRef; + use crate::{PyResult, VirtualMachine, builtins::PyDictRef, convert::ToPyObject}; + + #[cfg(windows)] + #[pyfunction] + fn get_platform() -> Option<&'static str> { + match std::env::consts::ARCH { + "x86_64" => Some("win-amd64"), + "aarch64" => Some("win-arm64"), + "x86" => Some("win32"), + "arm" => Some("win-arm32"), + _ => None, + } + } + #[pyfunction] - fn config_vars(vm: &VirtualMachine) -> PyDictRef { + fn config_vars(vm: &VirtualMachine) -> PyResult { let vars = vm.ctx.new_dict(); + #[cfg(windows)] + { + let source: PyStrRef = vm.sys_module.get_attr("_vpath", vm)?.try_into_value(vm)?; + if !source.as_wtf8().is_empty() { + vars.set_item("srcdir", source.into(), vm)?; + } + } + // FIXME: This is an entirely wrong implementation of EXT_SUFFIX. // EXT_SUFFIX must be a string starting with "." for pip compatibility // Using ".pyd" causes pip's _generic_abi() to fall back to _cpython_abis() - vars.set_item("EXT_SUFFIX", ".pyd".to_pyobject(vm), vm) - .unwrap(); - vars.set_item("SOABI", vm.ctx.none(), vm).unwrap(); + vars.set_item("EXT_SUFFIX", ".pyd".to_pyobject(vm), vm)?; + vars.set_item("SOABI", vm.ctx.none(), vm)?; - vars.set_item("Py_GIL_DISABLED", (1).to_pyobject(vm), vm) - .unwrap(); - vars.set_item("Py_DEBUG", (0).to_pyobject(vm), vm).unwrap(); + vars.set_item("Py_GIL_DISABLED", (1).to_pyobject(vm), vm)?; + vars.set_item("Py_DEBUG", (0).to_pyobject(vm), vm)?; - vars + Ok(vars) } } diff --git a/crates/vm/src/stdlib/_sysconfigdata.rs b/crates/vm/src/stdlib/_sysconfigdata.rs index dd77caff255..e3c0abad17f 100644 --- a/crates/vm/src/stdlib/_sysconfigdata.rs +++ b/crates/vm/src/stdlib/_sysconfigdata.rs @@ -1,4 +1,4 @@ -// spell-checker: words LDSHARED ARFLAGS CPPFLAGS CCSHARED BASECFLAGS BLDSHARED +// spell-checker: words LDSHARED LDCXXSHARED ARFLAGS CPPFLAGS CCSHARED BASECFLAGS BLDSHARED pub(crate) use _sysconfigdata::module_def; @@ -19,6 +19,16 @@ mod _sysconfigdata { let paths = &vm.state.config.paths; build_time_vars.set_item("prefix", paths.prefix.clone().to_pyobject(vm), vm)?; build_time_vars.set_item("exec_prefix", paths.exec_prefix.clone().to_pyobject(vm), vm)?; + if let Some(source_dir) = crate::getpath::source_directory(paths) { + build_time_vars.set_item( + "srcdir", + source_dir.to_string_lossy().as_ref().to_pyobject(vm), + vm, + )?; + } + if let Some(stdlib_dir) = &paths.stdlib_dir { + build_time_vars.set_item("LIBDEST", stdlib_dir.to_pyobject(vm), vm)?; + } let bindir = format!("{}/bin", paths.exec_prefix); build_time_vars.set_item("BINDIR", bindir.to_pyobject(vm), vm)?; @@ -26,7 +36,7 @@ mod _sysconfigdata { // Ensure the module is registered under the platform-specific name // (import_builtin() already handles this, but double-check for safety) - let sys_modules = vm.sys_module.get_attr("modules", vm)?; + let sys_modules = vm.sys_modules(); let sysconfigdata_name = sysconfigdata_name(); sys_modules.set_item(sysconfigdata_name.as_str(), module.to_owned().into(), vm)?; @@ -60,6 +70,7 @@ mod _sysconfigdata { "CPPFLAGS" => "", "LDFLAGS" => "", "LDSHARED" => "cc -shared", + "LDCXXSHARED" => "c++ -shared", "CCSHARED" => "", "SHLIB_SUFFIX" => ".so", "SO" => ".so", diff --git a/crates/vm/src/stdlib/_testinternalcapi.rs b/crates/vm/src/stdlib/_testinternalcapi.rs index caafcf5ab57..36ff0271d47 100644 --- a/crates/vm/src/stdlib/_testinternalcapi.rs +++ b/crates/vm/src/stdlib/_testinternalcapi.rs @@ -27,22 +27,24 @@ pub(crate) fn note_func_modification() { #[pymodule] mod _testinternalcapi { use super::*; + use crate::vm::crossinterp::test_support::CrossinterpData; use crate::{ - AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - atomic_func, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, + VirtualMachine, atomic_func, builtins::{ - PyBytesRef, PyCode, PyDict, PyDictRef, PyStrRef, PyType, PyTypeRef, - descriptor::PyWrapper, + PyBytesRef, PyCapsule, PyCode, PyDict, PyDictRef, PyStrRef, PyType, PyTypeRef, + PyUtf8StrRef, descriptor::PyWrapper, }, common::{hash::PyHash, lock::LazyLock}, dict_inner, frame::FrameObject, - function::{OptionalArg, PyComparisonValue}, + function::{ArgIntoBool, FuncArgs, OptionalArg, PyComparisonValue}, object::{Traverse, TraverseFn}, protocol::{PyIterReturn, PyMappingMethods, PySequenceMethods}, + stdlib::time::pytime::{self, Round}, types::{ - AsMapping, AsSequence, Comparable, IterNext, Iterable, PyComparisonOp, PyTypeFlags, - SelfIter, + AsMapping, AsSequence, Comparable, Constructor, IterNext, Iterable, PyComparisonOp, + PyTypeFlags, SelfIter, }, }; use std::collections::HashMap; @@ -51,6 +53,48 @@ mod _testinternalcapi { #[pyattr] const SPECIALIZATION_THRESHOLD: usize = 2; + #[pyattr] + #[pyclass(name, module = "_testcapi")] + #[derive(Debug, PyPayload)] + struct SelfInterruptingContextManager { + within: core::sync::atomic::AtomicBool, + } + + impl Constructor for SelfInterruptingContextManager { + type Args = FuncArgs; + + fn py_new(_cls: &Py, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult { + Ok(Self { + within: core::sync::atomic::AtomicBool::new(false), + }) + } + } + + #[pyclass(with(Constructor), flags(IMMUTABLETYPE))] + impl SelfInterruptingContextManager { + #[pymethod] + fn __enter__(zelf: PyRef, vm: &VirtualMachine) -> PyResult> { + zelf.within.store(true, Ordering::Relaxed); + let Some(_old) = vm.replace_async_exception(Some( + vm.ctx.exceptions.keyboard_interrupt.to_owned().into(), + )) else { + return Err(vm.new_runtime_error("the current thread state is being cleared")); + }; + vm.notify_async_exception(); + Ok(zelf) + } + + #[pymethod] + fn within(zelf: &Py) -> bool { + zelf.within.load(Ordering::Relaxed) + } + + #[pymethod] + fn __exit__(zelf: &Py, _args: crate::function::PosArgs) { + zelf.within.store(false, Ordering::Relaxed); + } + } + // ADAPTIVE_COOLDOWN_VALUE + 1 #[pyattr] const SPECIALIZATION_COOLDOWN: usize = 53; @@ -69,7 +113,8 @@ mod _testinternalcapi { const SIZEOF_PYOBJECT: usize = core::mem::size_of::(); #[pyattr] - const SIZEOF_TIME_T: usize = 8; + #[cfg_attr(target_env = "musl", allow(deprecated))] + const SIZEOF_TIME_T: usize = core::mem::size_of::(); // JUMP_BACKWARD_INITIAL_VALUE + 1 #[pyattr] @@ -148,6 +193,66 @@ mod _testinternalcapi { crate::vm::crossinterp::code_returns_only_none(&code) } + static CROSSINTERP_DATA_TAG: u8 = 0; + + fn crossinterp_data_tag() -> *mut core::ffi::c_void { + core::ptr::from_ref(&CROSSINTERP_DATA_TAG).cast_mut().cast() + } + + unsafe extern "C" fn release_crossinterp_data(obj: *mut PyObject) { + // SAFETY: this is installed only as a PyCapsule destructor; the object + // remains alive for the duration of the call. + let Some(capsule) = (unsafe { &*obj }).downcast_ref::() else { + return; + }; + if capsule.context() != crossinterp_data_tag() { + return; + } + let data = capsule.pointer().cast::(); + capsule.set_pointer(core::ptr::null_mut()); + if !data.is_null() { + // SAFETY: get_crossinterp_data transferred this Box to the capsule. + // Clearing the pointer above prevents a second release. + drop(unsafe { Box::from_raw(data) }); + } + } + + #[derive(FromArgs)] + struct GetCrossinterpDataArgs { + obj: PyObjectRef, + #[pyarg(any, optional)] + mode: OptionalArg, + } + + #[pyfunction] + fn get_crossinterp_data(args: GetCrossinterpDataArgs, vm: &VirtualMachine) -> PyResult { + let mode = args.mode.into_option(); + let data = CrossinterpData::from_object(&args.obj, mode.as_deref(), vm)?; + let data = Box::into_raw(Box::new(data)).cast(); + let capsule = vm + .ctx + .new_capsule(data, None, Some(release_crossinterp_data)); + capsule.set_context(crossinterp_data_tag()); + Ok(capsule.into()) + } + + #[pyfunction] + fn restore_crossinterp_data(obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let invalid = + || vm.new_value_error("PyCapsule_GetPointer called with invalid PyCapsule object"); + let capsule = obj.downcast_ref::().ok_or_else(invalid)?; + if capsule.name().is_some() + || capsule.context() != crossinterp_data_tag() + || capsule.pointer().is_null() + { + return Err(invalid()); + } + // SAFETY: only get_crossinterp_data creates capsules with this context. + // `obj` owns the capsule during the clone, so the payload cannot be freed. + let data = unsafe { &*capsule.pointer().cast::() }.clone(); + data.into_object(vm) + } + #[pyfunction] fn get_co_localskinds(code: PyRef, vm: &VirtualMachine) -> PyResult { let kinds = vm.ctx.new_dict(); @@ -237,7 +342,7 @@ mod _testinternalcapi { #[pyfunction(name = "EncodeLocaleEx")] fn encode_locale_ex( text: PyStrRef, - _current_locale: OptionalArg, + current_locale: OptionalArg, errors: OptionalArg, vm: &VirtualMachine, ) -> PyResult { @@ -246,6 +351,7 @@ mod _testinternalcapi { "encode", errors.into_option(), "encode error", + current_locale.unwrap_or(0) != 0, vm, ) } @@ -253,7 +359,7 @@ mod _testinternalcapi { #[pyfunction(name = "DecodeLocaleEx")] fn decode_locale_ex( encoded: PyBytesRef, - _current_locale: OptionalArg, + current_locale: OptionalArg, errors: OptionalArg, vm: &VirtualMachine, ) -> PyResult { @@ -262,31 +368,67 @@ mod _testinternalcapi { "decode", errors.into_option(), "decode error", + current_locale.unwrap_or(0) != 0, vm, ) } + // PyArg_ParseTuple's "s" conversion must precede later arguments' callbacks. + // Keep a typed string without allocating a second copy of its UTF-8 data. + struct InterpreterSource(PyUtf8StrRef); + + impl TryFromObject for InterpreterSource { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let source = PyUtf8StrRef::try_from_object(vm, obj)?; + if source.as_str().contains('\0') { + return Err(vm.new_value_error("embedded null character")); + } + Ok(Self(source)) + } + } + + // The fixture parses whence as C long, including on Windows and 32-bit hosts. + struct InterpreterWhenceArg(core::ffi::c_long); + + impl TryFromObject for InterpreterWhenceArg { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + obj.try_index(vm)? + .as_bigint() + .try_into() + .map(Self) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long")) + } + } + + #[derive(FromArgs)] + struct RunInSubinterpArgs { + #[pyarg(any)] + code: InterpreterSource, + #[pyarg(any)] + config: PyObjectRef, + #[pyarg(named, default = false)] + xi: ArgIntoBool, + } + #[pyfunction] fn run_in_subinterp_with_config( - code: PyStrRef, - config: PyObjectRef, - xi: OptionalArg, + args: RunInSubinterpArgs, vm: &VirtualMachine, ) -> PyResult { - if xi.unwrap_or(false) { - return Err(vm.new_runtime_error("cross-interpreter execution is not supported")); - } - let config = crate::stdlib::_interpreters::config_from_pyobject(&config, vm)?; - let source = code - .to_str() - .ok_or_else(|| vm.new_value_error("surrogates not allowed in interpreter source"))?; + let config = crate::stdlib::_interpreters::config_from_pyobject(&args.config, vm)?; + let source = args.code.0.as_str(); + let whence = if args.xi.into_bool() { + crate::vm::InterpreterWhence::Xi + } else { + crate::vm::InterpreterWhence::Capi + }; #[cfg(feature = "threading")] { - run_string_in_new_subinterp(source, config, vm) + run_string_in_new_subinterp(source, config, whence, vm) } #[cfg(not(feature = "threading"))] { - let _ = (source, config); + let _ = (source, config, whence); Err(vm.new_runtime_error("isolated interpreters require threading")) } } @@ -423,7 +565,7 @@ mod _testinternalcapi { global.set_item("dev_mode", vm.ctx.new_bool(settings.dev_mode).into(), vm)?; global.set_item("verbose", vm.ctx.new_int(settings.verbose).into(), vm)?; global.set_item("quiet", vm.ctx.new_bool(settings.quiet).into(), vm)?; - global.set_item("inspect", vm.ctx.new_bool(settings.inspect).into(), vm)?; + global.set_item("inspect", vm.ctx.new_bool(vm.config_inspect()).into(), vm)?; global.set_item( "interactive", vm.ctx.new_bool(settings.interactive).into(), @@ -461,49 +603,276 @@ mod _testinternalcapi { Ok(settings) } - #[pyfunction] - fn create_interpreter( + #[derive(FromArgs)] + struct CreateInterpreterArgs { + #[pyarg(any, optional)] config: OptionalArg, - _whence: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult { - let cfg = match config.into_option() { - Some(obj) if !vm.is_none(&obj) => { - crate::stdlib::_interpreters::config_from_pyobject(&obj, vm)? + #[pyarg(named, default = InterpreterWhenceArg(4), py_default = "4")] + whence: InterpreterWhenceArg, + } + + #[pyfunction] + fn create_interpreter(args: CreateInterpreterArgs, vm: &VirtualMachine) -> PyResult { + use crate::vm::{InterpreterConfig, InterpreterWhence}; + let config = args.config.into_option().filter(|obj| !vm.is_none(obj)); + let cfg = if matches!(args.whence.0, 0 | 2) { + if config.is_some() { + return Err(vm.new_value_error("got unexpected config")); } - _ => crate::vm::InterpreterConfig::ISOLATED, + InterpreterConfig::LEGACY + } else if let Some(config) = config { + crate::stdlib::_interpreters::config_from_pyobject(&config, vm)? + } else { + InterpreterConfig::ISOLATED + }; + // CPython resolves the config before _new_interpreter validates whence. + let whence = match args.whence.0 { + 0 => InterpreterWhence::Unknown, + 2 => InterpreterWhence::LegacyCapi, + 3 => InterpreterWhence::Capi, + 4 => InterpreterWhence::Xi, + value => return Err(vm.new_value_error(format!("unsupported whence {value}"))), }; #[cfg(feature = "threading")] { - let interp = crate::Interpreter::create_subinterpreter_from_vm(vm, cfg) - .map_err(|msg| crate::stdlib::_interpreters::interpreter_error(vm, msg))?; + let interp = + crate::Interpreter::create_subinterpreter_from_vm_with_whence(vm, cfg, whence) + .map_err(|msg| crate::stdlib::_interpreters::interpreter_error(vm, msg))?; Ok(crate::vm::runtime::store_owned_interpreter(interp)) } #[cfg(not(feature = "threading"))] { - let _ = cfg; + let _ = (cfg, whence); Err(vm.new_runtime_error("isolated interpreters require threading")) } } + #[pyfunction] + fn next_interpreter_id() -> i64 { + crate::vm::runtime::next_interpreter_id() + } + + #[derive(FromArgs)] + struct DestroyInterpreterArgs { + #[pyarg(any)] + id: PyObjectRef, + #[pyarg(any, default = false)] + basic: ArgIntoBool, + } + + #[pyfunction] + fn destroy_interpreter(args: DestroyInterpreterArgs, vm: &VirtualMachine) -> PyResult<()> { + use crate::stdlib::_interpreters::{interpreter_error, interpreter_not_found}; + use crate::vm::{crossinterp, runtime}; + let id = crate::stdlib::_interpreters::parse_id(&args.id, vm)?; + runtime::lookup_interpreter(id).ok_or_else(|| interpreter_not_found(vm, id))?; + if id == vm.state.interpreter_id { + return Err(interpreter_error( + vm, + "cannot destroy the current interpreter", + )); + } + if crossinterp::is_running(id) { + return Err(interpreter_error(vm, "interpreter running")); + } + #[cfg(feature = "threading")] + { + let interp = + runtime::take_owned_interpreter(id).ok_or_else(|| interpreter_not_found(vm, id))?; + if args.basic.into_bool() && interp.global_state.ready.load(Ordering::Acquire) { + // Exercise out-of-order VM-state destruction before ending the + // interpreter, as the basic C-API fixture does with thread states. + let first = interp.new_thread(); + let second = interp.new_thread(); + second.run(|_| drop(first)); + drop(second); + } + let _ = interp.finalize(None); + Ok(()) + } + #[cfg(not(feature = "threading"))] + { + let _ = args.basic; + Err(vm.new_runtime_error("isolated interpreters require threading")) + } + } + + #[derive(FromArgs)] + struct ExecInterpreterArgs { + #[pyarg(any)] + id: PyObjectRef, + #[pyarg(any)] + code: InterpreterSource, + #[pyarg(named, default = false)] + main: ArgIntoBool, + } + + #[pyfunction] + fn exec_interpreter(args: ExecInterpreterArgs, vm: &VirtualMachine) -> PyResult { + let source = args.code.0.as_str(); + let id = crate::stdlib::_interpreters::parse_id(&args.id, vm)?; + let state = crate::vm::runtime::lookup_interpreter(id) + .ok_or_else(|| crate::stdlib::_interpreters::interpreter_not_found(vm, id))?; + if !state.ready.load(Ordering::Acquire) { + return Err(crate::stdlib::_interpreters::interpreter_error( + vm, + "interpreter not ready", + )); + } + #[cfg(feature = "threading")] + { + if args.main.into_bool() { + crate::vm::crossinterp::with_interpreter(id, vm, |target| { + Ok(run_interpreter_source(source, target)) + }) + } else if id == vm.state.interpreter_id { + Ok(vm + .new_thread() + .run(|target| run_interpreter_source(source, target))) + } else { + let thread = crate::vm::runtime::new_interpreter_thread(id) + .ok_or_else(|| crate::stdlib::_interpreters::interpreter_not_found(vm, id))?; + Ok(thread.run(|target| run_interpreter_source(source, target))) + } + } + #[cfg(not(feature = "threading"))] + { + let _ = (source, args.main); + Err(vm.new_runtime_error("isolated interpreters require threading")) + } + } + + fn pytime_args<'a, const N: usize>( + args: &'a FuncArgs, + name: &str, + vm: &VirtualMachine, + ) -> PyResult<&'a [PyObjectRef; N]> { + // These CPython test helpers use METH_VARARGS, not keyword parsing. + if !args.kwargs.is_empty() { + return Err(vm.new_type_error(format!("{name}() takes no keyword arguments"))); + } + args.args.as_slice().try_into().map_err(|_| { + vm.new_type_error(format!( + "function takes exactly {} argument{} ({} given)", + N, + if N == 1 { "" } else { "s" }, + args.args.len() + )) + }) + } + + // PyArg_ParseTuple's "i" first converts to C long, then checks C int bounds. + fn pytime_c_int(object: &PyObject, vm: &VirtualMachine) -> PyResult { + let value: core::ffi::c_long = object + .try_index(vm)? + .as_bigint() + .try_into() + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))?; + num_traits::ToPrimitive::to_i32(&value).ok_or_else(|| { + vm.new_overflow_error(if value < 0 { + "signed integer is less than minimum" + } else { + "signed integer is greater than maximum" + }) + }) + } + + fn pytime_i64(object: &PyObject, vm: &VirtualMachine) -> PyResult { + object + .try_index(vm)? + .as_bigint() + .try_into() + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C int64_t")) + } + + #[pyfunction(name = "_PyTime_FromSeconds")] + fn pytime_from_seconds(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let [seconds] = pytime_args::<1>(&args, "_PyTime_FromSeconds", vm)?; + Ok(pytime::from_seconds(pytime_c_int(seconds, vm)?)) + } + + #[pyfunction(name = "_PyTime_FromSecondsObject")] + fn pytime_from_seconds_object(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let [object, round] = pytime_args::<2>(&args, "_PyTime_FromSecondsObject", vm)?; + let round = Round::from_int(pytime_c_int(round, vm)?, vm)?; + pytime::from_seconds_object(object, round, vm) + } + + fn pytime_as_subseconds( + args: FuncArgs, + name: &str, + divisor: i64, + vm: &VirtualMachine, + ) -> PyResult { + let [ns, round] = pytime_args::<2>(&args, name, vm)?; + let round = pytime_c_int(round, vm)?; + // These two C wrappers convert the timestamp before validating the mode. + let ns = pytime_i64(ns, vm)?; + Ok(Round::from_int(round, vm)?.divide(ns, divisor)) + } + + #[pyfunction(name = "_PyTime_AsMilliseconds")] + fn pytime_as_milliseconds(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + pytime_as_subseconds(args, "_PyTime_AsMilliseconds", 1_000_000, vm) + } + + #[pyfunction(name = "_PyTime_AsMicroseconds")] + fn pytime_as_microseconds(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + pytime_as_subseconds(args, "_PyTime_AsMicroseconds", 1_000, vm) + } + #[pyfunction(name = "_PyTime_AsTimespec")] - fn pytime_as_timespec(ns: i64) -> (i64, i64) { - let sec = ns.div_euclid(1_000_000_000); - let nsec = ns.rem_euclid(1_000_000_000); - (sec, nsec) + fn pytime_as_timespec(args: FuncArgs, vm: &VirtualMachine) -> PyResult<(i64, i64)> { + let [ns] = pytime_args::<1>(&args, "_PyTime_AsTimespec", vm)?; + pytime::as_timespec(pytime_i64(ns, vm)?, false, vm) } #[pyfunction(name = "_PyTime_AsTimespec_clamp")] - fn pytime_as_timespec_clamp(ns: i64) -> (i64, i64) { - pytime_as_timespec(ns) + fn pytime_as_timespec_clamp(args: FuncArgs, vm: &VirtualMachine) -> PyResult<(i64, i64)> { + let [ns] = pytime_args::<1>(&args, "_PyTime_AsTimespec_clamp", vm)?; + pytime::as_timespec(pytime_i64(ns, vm)?, true, vm) + } + + #[pyfunction(name = "_PyTime_AsTimeval")] + fn pytime_as_timeval(args: FuncArgs, vm: &VirtualMachine) -> PyResult<(i64, i64)> { + let [ns, round] = pytime_args::<2>(&args, "_PyTime_AsTimeval", vm)?; + let round = Round::from_int(pytime_c_int(round, vm)?, vm)?; + pytime::as_timeval(pytime_i64(ns, vm)?, round, false, vm) } #[pyfunction(name = "_PyTime_AsTimeval_clamp")] - fn pytime_as_timeval_clamp(ns: i64, _rnd: OptionalArg) -> (i64, i64) { - let us = ns.div_euclid(1000); - let sec = us.div_euclid(1_000_000); - let usec = us.rem_euclid(1_000_000); - (sec, usec) + fn pytime_as_timeval_clamp(args: FuncArgs, vm: &VirtualMachine) -> PyResult<(i64, i64)> { + let [ns, round] = pytime_args::<2>(&args, "_PyTime_AsTimeval_clamp", vm)?; + let round = Round::from_int(pytime_c_int(round, vm)?, vm)?; + pytime::as_timeval(pytime_i64(ns, vm)?, round, true, vm) + } + + #[pyfunction(name = "_PyTime_ObjectToTime_t")] + fn pytime_object_to_time_t(args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let [object, round] = pytime_args::<2>(&args, "_PyTime_ObjectToTime_t", vm)?; + let round = Round::from_int(pytime_c_int(round, vm)?, vm)?; + pytime::object_to_time_t(object, round, vm) + } + + fn pytime_object_to_denominator( + args: FuncArgs, + name: &str, + denominator: i64, + vm: &VirtualMachine, + ) -> PyResult<(i64, i64)> { + let [object, round] = pytime_args::<2>(&args, name, vm)?; + let round = Round::from_int(pytime_c_int(round, vm)?, vm)?; + pytime::object_to_denominator(object, denominator, round, vm) + } + + #[pyfunction(name = "_PyTime_ObjectToTimeval")] + fn pytime_object_to_timeval(args: FuncArgs, vm: &VirtualMachine) -> PyResult<(i64, i64)> { + pytime_object_to_denominator(args, "_PyTime_ObjectToTimeval", 1_000_000, vm) + } + + #[pyfunction(name = "_PyTime_ObjectToTimespec")] + fn pytime_object_to_timespec(args: FuncArgs, vm: &VirtualMachine) -> PyResult<(i64, i64)> { + pytime_object_to_denominator(args, "_PyTime_ObjectToTimespec", 1_000_000_000, vm) } #[pyfunction] @@ -611,7 +980,18 @@ mod _testinternalcapi { } } - #[pyclass(flags(HAS_WEAKREF), with(AsMapping, AsSequence, Comparable, Iterable))] + impl Constructor for Hamt { + type Args = FuncArgs; + + fn py_new(_cls: &Py, _args: FuncArgs, _vm: &VirtualMachine) -> PyResult { + Ok(Self::default()) + } + } + + #[pyclass( + flags(HAS_WEAKREF), + with(Constructor, AsMapping, AsSequence, Comparable, Iterable) + )] impl Py { #[pymethod] fn set( @@ -837,13 +1217,17 @@ mod _testinternalcapi { ..rustpython_codegen::CompileOpts::default() }; opts.future_features |= rustpython_codegen::preprocess::future_features(&converted.ast); - let output = rustpython_codegen::compile::compile_codegen( - converted.ast, - converted.source_file, + let output = rustpython_codegen::compile::compile_codegen_ast( + rustpython_codegen::compile::AstInput { + ast: converted.ast, + source_file: converted.source_file, + locations: converted.locations, + }, mode, opts, + None, ) - .map_err(|err| vm.new_syntax_error(&crate::compiler::CompileError::from(err), None))?; + .map_err(|err| crate::stdlib::_ast::codegen_exception(vm, err, None))?; let seq = PyInstructionSequence::from_rust(output.seq, vm); let metadata = vm.ctx.new_dict(); metadata.set_item("argcount", vm.ctx.new_int(output.argcount).into(), vm)?; @@ -950,7 +1334,28 @@ mod _testinternalcapi { } #[cfg(feature = "codegen")] - #[pyclass(with(Py))] + impl Constructor for PyInstructionSequence { + type Args = FuncArgs; + + fn py_new(cls: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + if cls.is(Self::class(&vm.ctx)) { + if !args.args.is_empty() { + return Err(vm.new_type_error( + "InstructionSequenceType() takes no positional arguments", + )); + } + if !args.kwargs.is_empty() { + return Err( + vm.new_type_error("InstructionSequenceType() takes no keyword arguments") + ); + } + } + Ok(Self::empty()) + } + } + + #[cfg(feature = "codegen")] + #[pyclass(with(Constructor, Py))] impl PyInstructionSequence {} #[cfg(feature = "codegen")] @@ -1125,11 +1530,16 @@ fn expandtabs(input: &str, tab_size: usize) -> String { expanded } -type CodeNamespaces = (PyRef, Option>, Option>); +type CodeNamespaces = ( + PyRef, + Option>, + Option>, +); fn code_or_function(obj: &PyObject, vm: &VirtualMachine) -> PyResult { if let Ok(func) = obj.to_owned().downcast::() { - let builtins = func.builtins.clone().downcast::().ok(); + let builtins = + crate::builtins::PyAnyDict::from_object(&func.builtins).map(ToOwned::to_owned); return Ok(( (*func.code).to_owned(), Some(func.globals.clone()), @@ -1142,19 +1552,22 @@ fn code_or_function(obj: &PyObject, vm: &VirtualMachine) -> PyResult>>( override_ns: OptionalArg, - default: Option>, + default: Option, name: &str, vm: &VirtualMachine, -) -> PyResult>> { +) -> PyResult> { match override_ns.into_option() { - Some(obj) => obj.downcast::().map(Some).map_err(|obj| { - vm.new_type_error(format!( - "expected a dict for \"{name}\", got {}", - obj.class().name() - )) - }), + Some(obj) => obj + .downcast::() + .map(|dict| Some(dict.into())) + .map_err(|obj| { + vm.new_type_error(format!( + "expected a dict for \"{name}\", got {}", + obj.class().name() + )) + }), None => Ok(default), } } @@ -1280,8 +1693,8 @@ fn set_unbound_var_counts( counts: &mut VarCounts, globalnames: Option, attrnames: Option, - globalsns: Option<&Py>, - builtinsns: Option<&Py>, + globalsns: Option<&crate::builtins::PyAnyDict>, + builtinsns: Option<&crate::builtins::PyAnyDict>, vm: &VirtualMachine, ) -> PyResult<()> { let globalnames = optional_set(globalnames, "globalnames", vm)?; @@ -1317,8 +1730,8 @@ fn identify_unbound_names( code: &Py, globalnames: Option>, attrnames: Option>, - globalsns: Option<&Py>, - builtinsns: Option<&Py>, + globalsns: Option<&crate::builtins::PyAnyDict>, + builtinsns: Option<&crate::builtins::PyAnyDict>, vm: &VirtualMachine, ) -> PyResult<(UnboundCounts, i32)> { let mut seen_globals = HashSet::new(); @@ -1328,7 +1741,7 @@ fn identify_unbound_names( for (_, instr, arg) in crate::vm::crossinterp::walk_instructions(code) { match instr { Instruction::LoadAttr { namei } => { - let name = code.names[namei.get(arg).name_idx() as usize]; + let name = code.names[namei.get(arg).name_idx()]; if name_already_seen(&seen_attrs, attrnames.as_deref(), name, vm)? { continue; } @@ -1343,7 +1756,7 @@ fn identify_unbound_names( } } Instruction::LoadGlobal { namei } => { - let name = code.names[(namei.get(arg) >> 1) as usize]; + let name = code.names[namei.get(arg).name_idx()]; if name_already_seen(&seen_globals, globalnames.as_deref(), name, vm)? { continue; } @@ -1479,10 +1892,28 @@ fn locale_codec( method: &str, errors: Option, kind: &str, + current_locale: bool, vm: &VirtualMachine, ) -> PyResult { let errors = locale_error_handler(errors, vm)?; - let encoding: PyObjectRef = vm.fs_encoding().to_owned().into(); + // Py_Decode/EncodeLocaleEx use the current LC_CTYPE, not the filesystem + // snapshot. UTF-8 mode overrides it only when current_locale is false. + #[cfg(all(feature = "host_env", target_os = "linux"))] + let encoding = if (current_locale || vm.state.config.settings.utf8_mode == 0) + && let Some(codeset) = rustpython_host_env::locale::nl_langinfo_codeset() + && let Ok(name) = String::from_utf8(codeset) + && !name.is_empty() + { + name + } else { + "utf-8".to_owned() + }; + #[cfg(not(all(feature = "host_env", target_os = "linux")))] + let encoding = { + let _ = current_locale; + "utf-8".to_owned() + }; + let encoding: PyObjectRef = vm.ctx.new_str(encoding).into(); match vm.call_method(obj, method, (encoding, errors)) { Ok(value) => Ok(value), Err(exc) => { @@ -1629,38 +2060,47 @@ fn sep_or_end(path: &[char], idx: usize, size: usize) -> bool { fn run_string_in_new_subinterp( source: &str, config: crate::vm::InterpreterConfig, + whence: crate::vm::InterpreterWhence, vm: &VirtualMachine, ) -> PyResult { - let interp = crate::Interpreter::create_subinterpreter_from_vm(vm, config).map_err(|msg| { - let cause = vm.new_runtime_error(msg.to_owned()); - let exc = - crate::stdlib::_interpreters::interpreter_error(vm, "sub-interpreter creation failed"); - exc.set_context(Some(cause)); - exc - })?; + let interp = crate::Interpreter::create_subinterpreter_from_vm_with_whence(vm, config, whence) + .map_err(|msg| { + let cause = vm.new_runtime_error(msg.to_owned()); + let exc = crate::stdlib::_interpreters::interpreter_error( + vm, + "sub-interpreter creation failed", + ); + exc.set_context(Some(cause)); + exc + })?; let id = crate::vm::runtime::store_owned_interpreter(interp); - let outcome = crate::vm::crossinterp::with_interpreter(id, vm, |target| { - match target.compile(source, crate::compiler::Mode::Exec, "") { - Ok(code) => { - let ns = target.main_namespace()?; - let scope = crate::scope::Scope::with_builtins(None, ns, target); - match target.run_code_obj(code, scope) { - Ok(_) => Ok(0), - Err(exc) => { - target.print_exception(&exc); - Ok(-1) - } - } - } - Err(err) => { - let exc = err.into_pyexception(target, Some(source)); - target.print_exception(&exc); - Ok(-1) - } - } - }); + let outcome = { + let thread = crate::vm::runtime::new_interpreter_thread(id) + .ok_or_else(|| crate::stdlib::_interpreters::interpreter_not_found(vm, id))?; + thread.run(|target| run_interpreter_source(source, target)) + }; let _ = crate::vm::runtime::destroy_owned_interpreter(id); - outcome + Ok(outcome) +} + +#[cfg(feature = "threading")] +fn run_interpreter_source(source: &str, target: &VirtualMachine) -> i32 { + let result = (|| { + let ns = target.add_main_module()?.dict(); + let code = target + .compile(source, crate::compiler::Mode::Exec, "") + .map_err(|err| err.into_pyexception(target, Some(source)))?; + let scope = crate::scope::Scope::with_builtins(None, ns, target); + target.audit("exec", || (code.clone(),))?; + target.run_code_obj(code, scope) + })(); + match result { + Ok(_) => 0, + Err(exc) => { + target.print_uncaught_exception(&exc); + -1 + } + } } #[cfg(feature = "codegen")] @@ -1801,10 +2241,7 @@ fn py_to_constant_data( } if let Ok(code) = obj.clone().downcast::() { return Ok(ConstantData::Code { - code: Box::new( - code.code - .map_clone_bag(&rustpython_compiler_core::bytecode::BasicBag), - ), + code: Box::new(snapshot_code_constant(&code, vm)?), }); } Err(vm.new_type_error(format!( @@ -1813,6 +2250,89 @@ fn py_to_constant_data( ))) } +#[cfg(feature = "codegen")] +fn snapshot_code_constant( + code: &Py, + vm: &VirtualMachine, +) -> PyResult { + use rustpython_compiler_core::bytecode::{BasicBag, CodeObject, CodeUnits, ConstantBag}; + + // get_code resolves monitoring wrappers under the owning code's lock and + // omits execution caches. Release that lock before visiting nested code. + let instructions = CodeUnits::try_from(code.get_code(vm).as_bytes()) + .map_err(|err| vm.new_value_error(format!("invalid bytecode: {err}")))?; + let source = &code.code; + let constants = source + .constants + .iter() + .map(|constant| snapshot_literal_constant(constant, vm)) + .collect::>>()?; + let map_name = + |name: &PyStrInterned| -> String { BasicBag.make_name(AsRef::::as_ref(name)) }; + let map_names = |names: &[&PyStrInterned]| -> Box<[String]> { + names.iter().map(|name| map_name(name)).collect() + }; + Ok(CodeObject { + instructions, + constants: constants.into_iter().collect(), + names: map_names(source.names.as_slice()).into(), + varnames: map_names(&source.varnames), + cellvars: map_names(&source.cellvars), + freevars: map_names(&source.freevars), + source_path: map_name(code.source_path()), + obj_name: map_name(source.obj_name), + qualname: map_name(source.qualname), + locations: source.locations.clone(), + flags: source.flags, + posonlyarg_count: source.posonlyarg_count, + arg_count: source.arg_count, + kwonlyarg_count: source.kwonlyarg_count, + first_line_number: source.first_line_number, + max_stackdepth: source.max_stackdepth, + localspluskinds: source.localspluskinds.clone(), + linetable: source.linetable.clone(), + exceptiontable: source.exceptiontable.clone(), + }) +} + +#[cfg(feature = "codegen")] +fn snapshot_literal_constant( + constant: &crate::builtins::code::Literal, + vm: &VirtualMachine, +) -> PyResult { + use rustpython_compiler_core::bytecode::{BorrowedConstant, Constant, ConstantData}; + + // Do not erase a live PyCode's owner through BorrowedConstant::Code. + let object: PyObjectRef = constant.clone().into(); + if let Some(code) = object.downcast_ref::() { + return Ok(ConstantData::Code { + code: Box::new(snapshot_code_constant(code, vm)?), + }); + } + Ok(match constant.borrow_constant() { + BorrowedConstant::Tuple { elements } => ConstantData::Tuple { + elements: elements + .iter() + .map(|item| snapshot_literal_constant(item, vm)) + .collect::>>()?, + }, + BorrowedConstant::Frozenset { elements } => ConstantData::Frozenset { + elements: elements + .iter() + .map(|item| snapshot_literal_constant(item, vm)) + .collect::>>()?, + }, + BorrowedConstant::Slice { elements } => ConstantData::Slice { + elements: Box::new([ + snapshot_literal_constant(&elements[0], vm)?, + snapshot_literal_constant(&elements[1], vm)?, + snapshot_literal_constant(&elements[2], vm)?, + ]), + }, + scalar => scalar.to_owned(), + }) +} + #[cfg(feature = "codegen")] fn metadata_to_code_unit( metadata: &Py, diff --git a/crates/vm/src/stdlib/_thread.rs b/crates/vm/src/stdlib/_thread.rs index 984a0865560..6e74012a694 100644 --- a/crates/vm/src/stdlib/_thread.rs +++ b/crates/vm/src/stdlib/_thread.rs @@ -23,14 +23,15 @@ pub(crate) mod _thread { builtins::{ PyBaseExceptionRef, PyDictRef, PyIntRef, PyStr, PyStrRef, PyTupleRef, PyType, PyTypeRef, }, - common::{lock::PyMutex, wtf8::Wtf8Buf}, + common::{lock::PyMutex, rc::PyRc, wtf8::Wtf8Buf}, convert::ToPyException, frame::FrameObjectRef, function::{ - ArgCallable, ArgumentError, DefaultRepr, FromArgs, FuncArgs, KwArgs, NameExcInfo, - OptionalArg, Param, ParamKind, PosArgs, PySetterValue, TimeoutSeconds, + ArgCallable, ArgIndex, ArgumentError, DefaultRepr, FromArgs, FuncArgs, KwArgs, + OptionalArg, Param, ParamKind, PySetterValue, }, object::{Traverse, TraverseFn}, + stdlib::time::pytime, types::{Constructor, GetAttr, PyStructSequence, Representable, SetAttr}, }; @@ -53,12 +54,6 @@ pub(crate) mod _thread { _ => None, }; - const TIMEOUT_MAX_IN_MICROSECONDS: i64 = if cfg!(target_os = "windows") { - 0xffffffff * 1_000 - } else { - i64::MAX / 1_000 - }; - /// [CPython `SYSTEM_PAGE_SIZE`](https://github.com/python/cpython/blob/v3.14.5/Include/internal/pycore_obmalloc.h#L170) const SYSTEM_PAGE_SIZE: usize = 4 * 1024; @@ -81,52 +76,115 @@ pub(crate) mod _thread { // this is a value in seconds #[pyattr] - const TIMEOUT_MAX: f64 = (TIMEOUT_MAX_IN_MICROSECONDS / 1_000_000) as f64; + const TIMEOUT_MAX: f64 = pytime::THREAD_TIMEOUT_MAX_SECONDS as f64; #[pyattr] fn error(vm: &VirtualMachine) -> PyTypeRef { vm.ctx.exceptions.runtime_error.to_owned() } - #[derive(FromArgs)] + #[derive(Debug, FromArgs)] struct AcquireArgs { - #[pyarg(any, default = true)] - blocking: bool, - // No timeout; blocks until the lock is acquired. - #[pyarg(any, default = TimeoutSeconds::new(-1.0), py_default = "-1")] - timeout: TimeoutSeconds, + // Finish binding before truthiness or timeout conversion can run callbacks. + #[pyarg(any, optional, py_default = "True")] + blocking: OptionalArg, + // No timeout; blocks until the lock is acquired. Explicit None is invalid. + #[pyarg(any, optional, py_default = "-1")] + timeout: OptionalArg, } fn default_acquire_args() -> AcquireArgs { AcquireArgs { - blocking: true, - timeout: TimeoutSeconds::new(-1.0), + blocking: OptionalArg::Missing, + timeout: OptionalArg::Missing, } } + fn validate_acquire_args( + args: &AcquireArgs, + vm: &VirtualMachine, + ) -> PyResult<(bool, Option)> { + let blocking = match &args.blocking { + OptionalArg::Present(value) => value.try_to_bool(vm)?, + OptionalArg::Missing => true, + }; + let unset_timeout = pytime::from_seconds(-1); + let timeout = match &args.timeout { + OptionalArg::Present(value) => { + pytime::from_seconds_object(value, pytime::Round::Up, vm)? + } + OptionalArg::Missing => unset_timeout, + }; + // CPython converts and rounds before checking the indefinite-wait sentinel. + if !blocking && timeout != unset_timeout { + return Err(vm.new_value_error("can't specify a timeout for a non-blocking call")); + } + if timeout < 0 && timeout != unset_timeout { + return Err(vm.new_value_error("timeout value must be a non-negative number")); + } + let duration = if timeout == unset_timeout { + None + } else { + pytime::check_thread_timeout(timeout, vm)?; + Some(Duration::from_nanos(timeout as u64)) + }; + Ok((blocking, duration)) + } + macro_rules! acquire_lock_impl { - ($mu:expr, $args:expr, $vm:expr) => {{ - let (mu, args, vm) = ($mu, $args, $vm); - let timeout = args.timeout.to_secs_f64(); - match args.blocking { - true if timeout == -1.0 => { - vm.allow_threads(|| mu.lock()); - Ok(true) + ($mu:expr, $blocking:expr, $timeout:expr, $vm:expr) => {{ acquire_lock_impl!($mu, $blocking, $timeout, $vm, false) }}; + ($mu:expr, $blocking:expr, $timeout:expr, $vm:expr, $owned:expr) => {{ + let (mu, blocking, timeout, vm) = ($mu, $blocking, $timeout, $vm); + let started = std::time::Instant::now(); + let mut remaining = timeout; + loop { + // Ownership gained in a signal handler does not make an + // already pending acquisition recursive. + let owned = $owned; + if !owned && mu.try_lock() { + break Ok(true); } - true if timeout < 0.0 => { - Err(vm.new_value_error("timeout value must be a non-negative number")) + if !blocking || remaining.is_some_and(|remaining| remaining.is_zero()) { + break Ok(false); } - true => { - if timeout > TIMEOUT_MAX { - return Err(vm.new_overflow_error("timeout value is too large")); + if vm + .state + .finalizing + .load(core::sync::atomic::Ordering::Acquire) + { + // Other Python threads cannot release the lock once + // finalization begins. Uncontested calls still work. + break Err(vm.new_python_finalization_error( + "cannot acquire lock at interpreter finalization", + )); + } + let interval = Duration::from_millis(50); + let wait = match timeout { + Some(timeout) => match timeout.checked_sub(started.elapsed()) { + Some(remaining) if !remaining.is_zero() => remaining.min(interval), + _ => break Ok(false), + }, + None => interval, + }; + // parking_lot waits are not interrupted by OS signals. Poll + // without restarting the deadline or acquiring a lock before + // running callbacks. A handler may itself retain an RLock. + let acquired = vm.allow_threads(|| { + if owned { + thread::sleep(wait); + false + } else { + mu.try_lock_for(wait) } - - Ok(vm.allow_threads(|| mu.try_lock_for(Duration::from_secs_f64(timeout)))) + }); + if acquired { + break Ok(true); } - false if timeout != -1.0 => { - Err(vm.new_value_error("can't specify a timeout for a non-blocking call")) + if timeout.is_some_and(|timeout| started.elapsed() >= timeout) { + break Ok(false); } - false => Ok(mu.try_lock()), + vm.check_signals()?; + remaining = timeout.map(|timeout| timeout.saturating_sub(started.elapsed())); } }}; } @@ -166,7 +224,8 @@ pub(crate) mod _thread { #[pymethod] #[pymethod(name = "acquire_lock")] fn acquire(&self, args: AcquireArgs, vm: &VirtualMachine) -> PyResult { - acquire_lock_impl!(&self.mu, args, vm) + let (blocking, timeout) = validate_acquire_args(&args, vm)?; + acquire_lock_impl!(&self.mu, blocking, timeout, vm) } #[pymethod] @@ -195,7 +254,9 @@ pub(crate) mod _thread { #[pymethod] fn __exit__( &self, - _args: PosArgs, + _exc_type: crate::PyObjectRef, + _exc_value: crate::PyObjectRef, + _exc_tb: crate::PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self.release(vm) @@ -240,7 +301,18 @@ pub(crate) mod _thread { #[pyclass(with(Representable), flags(BASETYPE, HAS_WEAKREF))] impl Py { #[pyslot] - fn slot_new(cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let rlock_type = RLock::class(&vm.ctx); + let cls_init = cls.slots.init.load().map(crate::types::fn_addr); + let rlock_init = rlock_type.slots.init.load().map(crate::types::fn_addr); + if cls.is(rlock_type) || cls_init == rlock_init { + if !args.args.is_empty() { + return Err(vm.new_type_error("RLock() takes no positional arguments")); + } + if !args.kwargs.is_empty() { + return Err(vm.new_type_error("RLock() takes no keyword arguments")); + } + } RLock { mu: RawRMutex::INIT, count: core::sync::atomic::AtomicUsize::new(0), @@ -252,6 +324,7 @@ pub(crate) mod _thread { #[pymethod] #[pymethod(name = "acquire_lock")] fn acquire(&self, args: AcquireArgs, vm: &VirtualMachine) -> PyResult { + let (blocking, timeout) = validate_acquire_args(&args, vm)?; if self.mu.is_owned_by_current_thread() { // Re-entrant acquisition: just increment our count. // parking_lot stays at 1 level; we track recursion ourselves. @@ -259,7 +332,13 @@ pub(crate) mod _thread { .fetch_add(1, core::sync::atomic::Ordering::Relaxed); return Ok(true); } - let result = acquire_lock_impl!(&self.mu, args, vm)?; + let result = acquire_lock_impl!( + &self.mu, + blocking, + timeout, + vm, + self.mu.is_owned_by_current_thread() + )?; if result { self.count.store(1, core::sync::atomic::Ordering::Relaxed); } @@ -347,7 +426,9 @@ pub(crate) mod _thread { #[pymethod] fn __exit__( &self, - _args: PosArgs, + _exc_type: crate::PyObjectRef, + _exc_value: crate::PyObjectRef, + _exc_tb: crate::PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { self.release(vm) @@ -506,15 +587,20 @@ pub(crate) mod _thread { } #[cfg(any(target_os = "linux", target_os = "macos"))] { - let os_name = vm.fsencode(&name)?; - host_thread::set_current_thread_name_bytes(os_name.as_encoded_bytes()); + let os_name = vm.state.codec_registry.encode_text( + name, + "utf-8", + Some(vm.ctx.new_utf8_str("replace")), + vm, + )?; + host_thread::set_current_thread_name_bytes(os_name.as_bytes()); } Ok(()) } #[cfg(any(windows, target_os = "linux", target_os = "macos"))] - #[pyfunction(name = "_get_name")] - fn get_name(vm: &VirtualMachine) -> PyResult { + #[pyfunction] + fn _get_name(vm: &VirtualMachine) -> PyResult { #[cfg(windows)] { let units = @@ -527,7 +613,7 @@ pub(crate) mod _thread { host_thread::current_thread_name(host_thread::NAME_MAXLEN.saturating_add(1)) .map_err(|e| e.to_pyexception(vm))?; let os = unsafe { std::ffi::OsString::from_encoded_bytes_unchecked(bytes) }; - Ok(vm.fsdecode(os).into()) + Ok(vm.fsdecode(os)?.into()) } } @@ -614,21 +700,8 @@ pub(crate) mod _thread { ]); fn from_args(vm: &VirtualMachine, f_args: &mut FuncArgs) -> Result { - if !f_args.kwargs.is_empty() { - return Err(vm - .new_type_error("start_new_thread() takes no keyword arguments") - .into()); - } - - let given = f_args.args.len(); - if !(2..=3).contains(&given) { - return Err(vm - .new_arity_type_error("start_new_thread", 2..=3, given) - .into()); - } - - let func_obj = f_args.take_positional().unwrap(); - let args_obj = f_args.take_positional().unwrap(); + let func_obj = f_args.take_positional().ok_or(ArgumentError::TooFewArgs)?; + let args_obj = f_args.take_positional().ok_or(ArgumentError::TooFewArgs)?; let kwargs_obj = f_args.take_positional(); if func_obj.to_callable().is_none() { @@ -728,12 +801,12 @@ pub(crate) mod _thread { func: &ArgCallable, vm: &VirtualMachine, ) { - let msg = func - .as_ref() - .repr(vm) - .ok() - .map(|repr| format!("Exception ignored in thread started by {}", repr.as_wtf8())); - vm.run_unraisable(exc, msg, vm.ctx.none()); + let msg = func.as_ref().repr(vm).ok().map(|repr| { + let mut message = Wtf8Buf::from("Exception ignored in thread started by "); + message.push_wtf8(repr.as_wtf8()); + vm.ctx.new_str(message) + }); + vm.run_unraisable_with_message(exc, msg, vm.ctx.none()); } fn run_thread(func: ArgCallable, args: FuncArgs, vm: &VirtualMachine) { @@ -761,6 +834,7 @@ pub(crate) mod _thread { // Clean up thread-local storage while VM context is still active // This ensures __del__ methods are called properly cleanup_thread_local_data(); + vm.clear_async_exception(); // Clean up frame tracking crate::vm::thread::cleanup_current_thread_frames(vm); vm.state.thread_count.fetch_sub(1); @@ -811,8 +885,7 @@ pub(crate) mod _thread { fn cleanup_thread_local_data() { // Move all guards out before dropping them. A local dict's __del__ may // re-enter thread-local access and borrow LOCAL_GUARDS again. - let guards = LOCAL_GUARDS.take(); - drop(guards); + let _guards = LOCAL_GUARDS.take(); } #[cfg(all(not(target_arch = "wasm32"), feature = "host_env"))] @@ -847,23 +920,22 @@ pub(crate) mod _thread { #[derive(FromArgs)] struct StackSizeArgs { #[pyarg(positional, default = 0)] - size: PyIntRef, + size: ArgIndex, } #[pyfunction] fn stack_size(args: StackSizeArgs, vm: &VirtualMachine) -> PyResult { - const MIN_SIZE: usize = PY_OS_MIN_STACK_SIZE + SYSTEM_PAGE_SIZE; + const MIN_SIZE: isize = (PY_OS_MIN_STACK_SIZE + SYSTEM_PAGE_SIZE) as isize; let StackSizeArgs { size } = args; - let Ok(size) = size.try_to_primitive(vm) else { - return Err(vm.new_value_error(format!("size must be at least {MIN_SIZE} bytes"))); - }; + let size = isize::try_from(size.as_ref().as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C ssize_t"))?; if size != 0 && size < MIN_SIZE { return Err(vm.new_value_error(format!("size must be at least {MIN_SIZE} bytes"))); } - Ok(vm.state.stacksize.swap(size)) + Ok(vm.state.stacksize.swap(size as usize)) } #[pyfunction] @@ -883,7 +955,7 @@ pub(crate) mod _thread { ); #[pyfunction] - fn _shutdown(vm: &VirtualMachine) { + pub(crate) fn _shutdown(vm: &VirtualMachine) { // Wait for all non-daemon threads to finish let current_ident = get_ident(); @@ -891,12 +963,10 @@ pub(crate) mod _thread { // Find a thread that's not finished and not the current thread let handle_to_join = { let mut handles = vm.state.shutdown_handles.lock(); - // Clean up finished entries - handles.retain(|(inner_weak, _): &ShutdownEntry| { - inner_weak.upgrade().is_some_and(|inner| { - let guard = inner.lock(); - guard.state != ThreadHandleState::Done && guard.ident != current_ident - }) + // Drop expired entries, but retain the current thread's entry: + // another thread may need to wait for its teardown. + handles.retain(|(inner_weak, done_event_weak): &ShutdownEntry| { + inner_weak.upgrade().is_some() && done_event_weak.upgrade().is_some() }); // Find first unfinished handle @@ -906,16 +976,24 @@ pub(crate) mod _thread { let inner = inner_weak.upgrade()?; let done_event = done_event_weak.upgrade()?; let guard = inner.lock(); - if guard.state != ThreadHandleState::Done && guard.ident != current_ident { - Some((inner.clone(), done_event)) - } else { + if guard.ident == current_ident { None + } else { + Some((inner.clone(), done_event)) } }) }; match handle_to_join { Some((inner, done_event)) => { + // The starter publishes Running after the child reports its + // identity. Let it finish instead of reporting an unraisable + // "thread not started" during that window. + let starting = inner.lock().state == ThreadHandleState::Starting; + if starting { + vm.allow_threads(std::thread::yield_now); + continue; + } if let Err(exc) = ThreadHandle::join_internal(&inner, &done_event, None, vm) { vm.run_unraisable( exc, @@ -933,6 +1011,20 @@ pub(crate) mod _thread { } } + // The caller stops the world before using this to decide finalization. + pub(crate) fn has_pending_shutdown_threads(vm: &VirtualMachine) -> bool { + let current_ident = get_ident(); + vm.state + .shutdown_handles + .lock() + .iter() + .any(|(inner, event)| { + inner.upgrade().is_some_and(|inner| { + event.upgrade().is_some() && inner.lock().ident != current_ident + }) + }) + } + /// Add a non-daemon thread handle to the shutdown registry fn add_to_shutdown_handles( vm: &VirtualMachine, @@ -948,7 +1040,15 @@ pub(crate) mod _thread { inner: &Arc>, done_event: &Arc<(parking_lot::Mutex, parking_lot::Condvar)>, ) { - let mut handles = vm.state.shutdown_handles.lock(); + remove_from_shutdown_handles_for_state(&vm.state, inner, done_event); + } + + fn remove_from_shutdown_handles_for_state( + state: &crate::vm::PyGlobalState, + inner: &Arc>, + done_event: &Arc<(parking_lot::Mutex, parking_lot::Condvar)>, + ) { + let mut handles = state.shutdown_handles.lock(); handles.retain(|(inner_weak, done_event_weak): &ShutdownEntry| { let Some(registered_inner) = inner_weak.upgrade() else { return false; @@ -961,6 +1061,32 @@ pub(crate) mod _thread { }); } + // Keep the shutdown entry until the VM has detached and been dropped. + // This guard also signals joiners if the worker unwinds. + struct WorkerCompletion { + vm: Option, + state: PyRc, + inner: Arc>, + done_event: Arc<(parking_lot::Mutex, parking_lot::Condvar)>, + } + + impl Drop for WorkerCompletion { + fn drop(&mut self) { + let state = self.state.clone(); + let inner = self.inner.clone(); + let done_event = self.done_event.clone(); + // Publish completion even if dropping the VM unwinds. + let _publish = scopeguard::guard((), move |_| { + inner.lock().state = ThreadHandleState::Done; + remove_from_shutdown_handles_for_state(&state, &inner, &done_event); + let (lock, cvar) = &*done_event; + *lock.lock() = true; + cvar.notify_all(); + }); + drop(self.vm.take()); + } + } + #[derive(FromArgs)] struct MakeThreadHandleArgs { // An `int` only; the range is checked separately so it stays an OverflowError. @@ -1022,7 +1148,7 @@ pub(crate) mod _thread { fn extend_pyclass(ctx: &crate::vm::Context, class: &'static Py) { // (type, (sequence, dict)). Set before the trait installs its default. const EXCEPT_HOOK_ARGS_REDUCE: crate::function::PyMethodDef = - crate::function::PyMethodDef::new_const( + crate::function::PyMethodDef::new_method_const( "__reduce__", |zelf: crate::PyRef, vm: &VirtualMachine| @@ -1137,8 +1263,7 @@ pub(crate) mod _thread { if let Some(local_data) = self.local.upgrade() { // Remove from map while holding the lock, but drop the value // outside the lock to prevent deadlock if __del__ accesses _local - let removed = local_data.state.lock().dicts.remove(&self.thread_id); - drop(removed); + let _removed = local_data.state.lock().dicts.remove(&self.thread_id); } } } @@ -1271,8 +1396,7 @@ pub(crate) mod _thread { if let Some(guard) = guard { drop(guard); } else { - let removed = self.inner.state.lock().dicts.remove(&thread_id); - drop(removed); + let _removed = self.inner.state.lock().dicts.remove(&thread_id); } } @@ -1294,8 +1418,8 @@ pub(crate) mod _thread { Ok(dict) } - #[pygetset(name = "__dict__")] - fn dict(zelf: PyRef, vm: &VirtualMachine) -> PyResult { + #[pygetset] + fn __dict__(zelf: PyRef, vm: &VirtualMachine) -> PyResult { Self::l_dict(&zelf, vm) } @@ -1356,6 +1480,14 @@ pub(crate) mod _thread { ))) } else { let dict = Self::l_dict(zelf, vm)?; + // Data descriptors on the class (e.g. property setters) take + // precedence over the per-thread dict, as in generic setattr. + if let Some(attr_name) = vm.ctx.interned_str(attr) + && let Some(descr) = zelf.as_object().get_class_attr(attr_name) + && let Some(descr_set) = descr.class().slots().descr_set.load() + { + return descr_set(&descr, zelf.as_object().to_owned(), value, vm); + } if let PySetterValue::Assign(value) = value { dict.set_item(attr, value, vm)?; } else { @@ -1492,37 +1624,15 @@ pub(crate) mod _thread { return false; }; - // Reinit this per-handle lock in case a dead thread held it - reinit_parking_lot_mutex(&inner); - let mut inner_guard = inner.lock(); - - if inner_guard.ident == current_ident { - return true; - } - if inner_guard.state == ThreadHandleState::NotStarted { - return true; - } - - inner_guard.state = ThreadHandleState::Done; - // The OS thread did not survive the fork. Dropping JoinHandle - // would pthread_detach a copied thread descriptor. - if let Some(handle) = inner_guard.join_handle.take() { - core::mem::forget(handle); - } - drop(inner_guard); - - // Reinit and set the done event. Do not notify: no other - // thread exists in the child, and notify_all would unpark - // waiters that did not survive the fork. - let (lock, cvar) = &*done_event; - reinit_parking_lot_mutex(lock); - reinit_parking_lot_condvar(cvar); - *lock.lock() = true; + // SAFETY: only the forking thread survives in the child. + unsafe { reinit_handle_after_fork(&inner, &done_event, current_ident) }; true }); } + // Every shutdown entry comes from ThreadHandle::new and is also in + // thread_handles, so its completion event was already reset above. // Clean up shutdown_handles. { let mut handles = vm.state.shutdown_handles.lock(); @@ -1557,6 +1667,42 @@ pub(crate) mod _thread { } } + /// Repair a copied handle before any child thread cleanup or join. + /// + /// Unlike CPython's atomic completion event, ours includes a mutex that a + /// parent joiner can hold while detached. Even the surviving thread's + /// completion mutex and condvar must lose that dead owner's/waiter's state. + /// Its completion value remains unchanged until the thread really exits. + /// + /// # Safety + /// Only call in the single-threaded post-fork child, with no live guards or + /// waiters on these locks. + #[cfg(all(unix, feature = "host_env"))] + unsafe fn reinit_handle_after_fork( + inner: &parking_lot::Mutex, + done_event: &(parking_lot::Mutex, parking_lot::Condvar), + current_ident: u64, + ) { + reinit_parking_lot_mutex(inner); + let (lock, cvar) = done_event; + reinit_parking_lot_mutex(lock); + reinit_parking_lot_condvar(cvar); + let mut inner_guard = inner.lock(); + if inner_guard.ident == current_ident || inner_guard.state == ThreadHandleState::NotStarted + { + return; + } + + inner_guard.state = ThreadHandleState::Done; + // The OS thread did not survive. Do not pthread_detach a copied handle. + if let Some(handle) = inner_guard.join_handle.take() { + core::mem::forget(handle); + } + drop(inner_guard); + // Do not notify waiters: none survived the fork. + *lock.lock() = true; + } + /// Take a thread handle's completion mutex, detaching first. /// /// A joiner holds this mutex across its `allow_threads` wait, so it can @@ -1645,6 +1791,12 @@ pub(crate) mod _thread { Self { inner, done_event } } + fn join_wait_slice(timeout: Duration, elapsed: Duration) -> Duration { + timeout.saturating_sub(elapsed).min(Duration::from_micros( + pytime::THREAD_TIMEOUT_MAX_MICROSECONDS as u64, + )) + } + fn join_internal( inner: &Arc>, done_event: &Arc<(parking_lot::Mutex, parking_lot::Condvar)>, @@ -1653,8 +1805,7 @@ pub(crate) mod _thread { ) -> PyResult<()> { Self::check_started(inner, vm)?; - let deadline = - timeout_duration.and_then(|timeout| std::time::Instant::now().checked_add(timeout)); + let started = std::time::Instant::now(); // Wait for thread completion using Condvar (supports timeout) // Loop to handle spurious wakeups @@ -1687,17 +1838,13 @@ pub(crate) mod _thread { while !*done { if let Some(timeout) = timeout_duration { - let remaining = deadline.map_or(timeout, |deadline| { - deadline.saturating_duration_since(std::time::Instant::now()) - }); - if remaining.is_zero() { - return Ok(()); - } - let result = vm.allow_threads(|| cvar.wait_for(&mut done, remaining)); - if result.timed_out() && !*done { - // Timeout occurred and done is still false + let wait = Self::join_wait_slice(timeout, started.elapsed()); + if wait.is_zero() { return Ok(()); } + // Keep each Windows wait below INFINITE and retain the + // original timeout budget after a slice or spurious wakeup. + vm.allow_threads(|| cvar.wait_for(&mut done, wait)); } else { // Infinite wait vm.allow_threads(|| cvar.wait(&mut done)); @@ -1790,44 +1937,11 @@ pub(crate) mod _thread { timeout_obj: Option, vm: &VirtualMachine, ) -> PyResult> { - const JOIN_TIMEOUT_MAX_SECONDS: i64 = TIMEOUT_MAX_IN_MICROSECONDS / 1_000_000; let Some(timeout_obj) = timeout_obj else { return Ok(None); }; - - if let Some(t) = timeout_obj.try_index_opt(vm) { - let t: i64 = t?.try_to_primitive(vm).map_err(|_| { - vm.new_overflow_error("timestamp too large to convert to C PyTime_t") - })?; - if !(-JOIN_TIMEOUT_MAX_SECONDS..=JOIN_TIMEOUT_MAX_SECONDS).contains(&t) { - return Err( - vm.new_overflow_error("timestamp too large to convert to C PyTime_t") - ); - } - if t < 0 { - return Ok(None); - } - return Ok(Some(Duration::from_secs(t as u64))); - } - - if let Some(t) = timeout_obj.try_float_opt(vm) { - let t = t?.to_f64(); - if t.is_nan() { - return Err(vm.new_value_error("Invalid value NaN (not a number)")); - } - if !t.is_finite() || !(-TIMEOUT_MAX..=TIMEOUT_MAX).contains(&t) { - return Err(vm.new_overflow_error("timestamp out of range for platform time_t")); - } - if t < 0.0 { - return Ok(None); - } - return Ok(Some(Duration::from_secs_f64(t))); - } - - Err(vm.new_type_error(format!( - "'{}' object cannot be interpreted as an integer or float", - timeout_obj.class().name() - ))) + let nanoseconds = pytime::from_seconds_object(&timeout_obj, pytime::Round::Up, vm)?; + Ok((nanoseconds >= 0).then(|| Duration::from_nanos(nanoseconds as u64))) } } @@ -1900,6 +2014,9 @@ pub(crate) mod _thread { } impl FromArgs for StartJoinableThreadArgs { + // PyArg_ParseTupleAndKeywords converts daemon before checking unknown names. + const BINDING_PARAMS: Option<&'static [Param]> = None; + const PARAMS: Option<&'static [Param]> = Some(&[ Param::positional_or_keyword("function"), Param { @@ -2035,7 +2152,7 @@ pub(crate) mod _thread { vm.audit("_thread.start_joinable_thread", || { ( function_obj, - daemon, + i32::from(daemon), handle .as_ref() .map_or_else(|| vm.ctx.none(), |h| h.clone().into()), @@ -2101,91 +2218,86 @@ pub(crate) mod _thread { let handle_ready_event_clone = Arc::clone(&handle_ready_event); let thread_builder = apply_thread_stack_size(thread::Builder::new(), vm); + let worker_vm = vm.new_thread(); + let worker_state = vm.state.clone(); let join_handle = thread_builder - .spawn(vm.new_thread().make_spawn_func(move |vm| { - // Publish ident for the parent starter thread. - { - inner_clone.lock().ident = get_ident(); - } - { - let (started_lock, started_cvar) = &*started_event_clone; - *started_lock.lock().unwrap() = true; - started_cvar.notify_all(); - } - // Don't execute the target function until parent marks the - // handle as running. Detach while blocked so a concurrent - // stop-the-world (e.g. a GC on another thread) can park this - // thread instead of stalling waiting for it to reach a - // safepoint it will not reach until released. - { - let (ready_lock, ready_cvar) = &*handle_ready_event_clone; - vm.allow_threads(|| { - let mut ready = ready_lock.lock().unwrap(); - while !*ready { - // Short timeout so we stay responsive to STW requests. - let (guard, _) = ready_cvar - .wait_timeout(ready, core::time::Duration::from_millis(1)) - .unwrap(); - ready = guard; - } - }); - } - - // Ensure cleanup happens even if the function panics - let inner_for_cleanup = inner_clone.clone(); - let done_event_for_cleanup = done_event_clone.clone(); - let vm_state = vm.state.clone(); - scopeguard::defer! { - // Mark as done - inner_for_cleanup.lock().state = ThreadHandleState::Done; - - // Handle sentinels - for lock in SENTINELS.take() { - if lock.mu.is_locked() { - unsafe { lock.mu.unlock() }; - } + .spawn(move || { + let completion = WorkerCompletion { + vm: Some(worker_vm), + state: worker_state, + inner: inner_clone.clone(), + done_event: done_event_clone, + }; + completion.vm.as_ref().unwrap().run(move |vm| { + // Publish ident for the parent starter thread. + { + inner_clone.lock().ident = get_ident(); + } + { + let (started_lock, started_cvar) = &*started_event_clone; + *started_lock.lock().unwrap() = true; + started_cvar.notify_all(); + } + // Don't execute the target function until parent marks the + // handle as running. Detach while blocked so a concurrent + // stop-the-world (e.g. a GC on another thread) can park this + // thread instead of stalling waiting for it to reach a + // safepoint it will not reach until released. + { + let (ready_lock, ready_cvar) = &*handle_ready_event_clone; + vm.allow_threads(|| { + let mut ready = ready_lock.lock().unwrap(); + while !*ready { + // Short timeout so we stay responsive to STW requests. + let (guard, _) = ready_cvar + .wait_timeout(ready, core::time::Duration::from_millis(1)) + .unwrap(); + ready = guard; + } + }); } - // Clean up thread-local data while VM context is still active - cleanup_thread_local_data(); - - // Clean up frame tracking - crate::vm::thread::cleanup_current_thread_frames(vm); + // Ensure cleanup happens even if the function panics. + let vm_state = vm.state.clone(); + scopeguard::defer! { + // Handle sentinels + for lock in SENTINELS.take() { + if lock.mu.is_locked() { + unsafe { lock.mu.unlock() }; + } + } - vm_state.thread_count.fetch_sub(1); + // Clean up thread-local data while VM context is still active + cleanup_thread_local_data(); + vm.clear_async_exception(); - // The runtime no longer needs to wait for this thread. - remove_from_shutdown_handles(vm, &inner_for_cleanup, &done_event_for_cleanup); + // Clean up frame tracking + crate::vm::thread::cleanup_current_thread_frames(vm); - // Signal waiting threads that this thread is done - // This must be LAST to ensure all cleanup is complete before join() returns - { - let (lock, cvar) = &*done_event_for_cleanup; - *lock_done(lock, vm) = true; - cvar.notify_all(); + vm_state.thread_count.fetch_sub(1); } - } - // Increment thread count when thread actually starts executing - vm_state.thread_count.fetch_add(1); + // Increment thread count when thread actually starts executing + vm_state.thread_count.fetch_add(1); - // Inner scope: drop `func` (and its Python refs) before the - // outer scopeguard::defer tears down the thread slot. As a - // `move` closure capture, `func` would otherwise drop after - // all locals (including the scopeguard `_guard`), and a - // weakref callback fired during that drop would panic in - // push_thread_frame. - { - let func = func; - // Run the function - if let Err(exc) = func.invoke((), vm) - && !exc.fast_isinstance(vm.ctx.exceptions.system_exit) + // Inner scope: drop `func` (and its Python refs) before the + // outer scopeguard::defer tears down the thread slot. As a + // `move` closure capture, `func` would otherwise drop after + // all locals (including the scopeguard `_guard`), and a + // weakref callback fired during that drop would panic in + // push_thread_frame. { - report_unraisable_thread_exception(exc, &func, vm); + let func = func; + // Run the function + if let Err(exc) = func.invoke((), vm) + && !exc.fast_isinstance(vm.ctx.exceptions.system_exit) + { + report_unraisable_thread_exception(exc, &func, vm); + } } - } - })) + }); + }) .map_err(|_err| { // force_done + remove_from_shutdown_handles on start failure. { @@ -2244,10 +2356,333 @@ pub(crate) mod _thread { #[cfg(test)] mod tests { - #[cfg(all(debug_assertions, any(target_os = "linux", target_os = "macos")))] use super::*; - #[cfg(all(debug_assertions, any(target_os = "linux", target_os = "macos")))] - use crate::Interpreter; + use crate::{Interpreter, class::PyClassImpl, protocol::PyNumberMethods, types::AsNumber}; + + #[test] + fn join_wait_slices_preserve_the_timeout_budget() { + let limit = Duration::from_micros(pytime::THREAD_TIMEOUT_MAX_MICROSECONDS as u64); + let tail = Duration::from_nanos(1); + let timeout = limit + tail; + assert_eq!( + ThreadHandle::join_wait_slice(timeout, Duration::ZERO), + limit + ); + assert_eq!(ThreadHandle::join_wait_slice(timeout, limit), tail); + assert_eq!( + ThreadHandle::join_wait_slice(timeout, timeout), + Duration::ZERO + ); + assert_eq!( + ThreadHandle::join_wait_slice(timeout, timeout + tail), + Duration::ZERO + ); + #[cfg(windows)] + assert!(limit.as_millis() < u128::from(u32::MAX)); + } + + #[pyclass(name = "AcquireConversion", module = false)] + #[derive(Debug, PyPayload)] + struct AcquireConversion { + calls: Arc>>, + fail_truth: bool, + } + + #[pyclass(with(AsNumber))] + impl AcquireConversion {} + + impl AsNumber for AcquireConversion { + fn as_number() -> &'static PyNumberMethods { + static METHODS: PyNumberMethods = PyNumberMethods { + boolean: Some(|number, vm| { + let value = number.obj.downcast_ref::().unwrap(); + value.calls.lock().push("bool"); + if value.fail_truth { + Err(vm.new_value_error("truth conversion failed")) + } else { + Ok(true) + } + }), + index: Some(|number, vm| { + let value = number.obj.downcast_ref::().unwrap(); + value.calls.lock().push("index"); + Ok(vm.ctx.new_int(0).into()) + }), + float: Some(|number, vm| { + let value = number.obj.downcast_ref::().unwrap(); + value.calls.lock().push("float"); + Err(vm.new_value_error("index must take precedence")) + }), + ..PyNumberMethods::NOT_IMPLEMENTED + }; + &METHODS + } + } + + #[test] + fn acquire_defaults_preserve_signature_and_missing_values() { + let params = AcquireArgs::PARAMS.unwrap(); + assert_eq!(params.len(), 2); + for (param, name, default) in [ + (¶ms[0], "blocking", "True"), + (¶ms[1], "timeout", "-1"), + ] { + assert_eq!(param.name, name); + assert!(matches!(param.kind, ParamKind::PositionalOrKeyword)); + assert!(matches!(param.default, Some(DefaultRepr::Raw(value)) if value == default)); + } + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let args = FuncArgs::default().bind::(vm).unwrap(); + assert!(args.blocking.is_missing()); + assert!(args.timeout.is_missing()); + assert_eq!(validate_acquire_args(&args, vm).unwrap(), (true, None)); + let args = AcquireArgs { + timeout: OptionalArg::Present(vm.ctx.none()), + ..default_acquire_args() + }; + let error = validate_acquire_args(&args, vm).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.type_error)); + }); + } + + #[test] + fn acquire_blocking_accepts_general_truthiness() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + for (value, expected) in [ + (vm.ctx.none(), false), + (vm.ctx.new_list(vec![]).into(), false), + (vm.ctx.new_list(vec![vm.ctx.none()]).into(), true), + (vm.ctx.new_str("").into(), false), + (vm.ctx.new_str("blocking").into(), true), + ] { + let args = FuncArgs::from(vec![value]).bind::(vm).unwrap(); + assert_eq!(validate_acquire_args(&args, vm).unwrap(), (expected, None)); + } + }); + } + + #[test] + fn acquire_converts_once_in_parameter_order() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let _class = AcquireConversion::make_static_type(); + for fail_truth in [false, true] { + let calls = Arc::new(PyMutex::new(Vec::new())); + let value: PyObjectRef = AcquireConversion { + calls: calls.clone(), + fail_truth, + } + .into_ref(&vm.ctx) + .into(); + let args = FuncArgs::new( + vec![], + [("timeout", value.clone()), ("blocking", value)] + .into_iter() + .collect::(), + ) + .bind::(vm) + .unwrap(); + assert!(calls.lock().is_empty()); + let result = validate_acquire_args(&args, vm); + if fail_truth { + assert!( + result + .unwrap_err() + .fast_isinstance(vm.ctx.exceptions.value_error) + ); + assert_eq!(&*calls.lock(), &["bool"]); + } else { + assert_eq!(result.unwrap(), (true, Some(Duration::ZERO))); + assert_eq!(&*calls.lock(), &["bool", "index"]); + } + } + }); + } + + #[test] + fn acquire_binding_errors_do_not_run_converters() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let _class = AcquireConversion::make_static_type(); + let calls = Arc::new(PyMutex::new(Vec::new())); + let value: PyObjectRef = AcquireConversion { + calls: calls.clone(), + fail_truth: false, + } + .into_ref(&vm.ctx) + .into(); + for args in [ + FuncArgs::from(vec![value.clone(); 3]), + FuncArgs::new( + vec![value.clone()], + core::iter::once(("blocking", value.clone())).collect::(), + ), + FuncArgs::new( + vec![value.clone()], + core::iter::once(("unexpected", value)).collect::(), + ), + ] { + let error = args.bind::(vm).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.type_error)); + assert!(calls.lock().is_empty()); + } + }); + } + + #[test] + fn acquire_timeout_uses_rounded_signed_nanoseconds() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + for (seconds, expected) in [ + (-1.0, None), + (-1.0 + f64::EPSILON / 2.0, None), + (0.0, Some(Duration::ZERO)), + (-0.0, Some(Duration::ZERO)), + (1e-300, Some(Duration::from_nanos(1))), + ( + TIMEOUT_MAX + 0.1, + Some(Duration::from_nanos( + ((TIMEOUT_MAX + 0.1) * 1_000_000_000.0).ceil() as u64, + )), + ), + ] { + let args = AcquireArgs { + timeout: OptionalArg::Present(vm.ctx.new_float(seconds).into()), + ..default_acquire_args() + }; + assert_eq!(validate_acquire_args(&args, vm).unwrap(), (true, expected)); + } + for seconds in [-1.0, -1.0 + f64::EPSILON / 2.0] { + let args = AcquireArgs { + blocking: OptionalArg::Present(vm.ctx.none()), + timeout: OptionalArg::Present(vm.ctx.new_float(seconds).into()), + }; + assert_eq!(validate_acquire_args(&args, vm).unwrap(), (false, None)); + } + let args = AcquireArgs { + blocking: OptionalArg::Present(vm.ctx.none()), + timeout: OptionalArg::Present(vm.ctx.new_int(0).into()), + }; + let error = validate_acquire_args(&args, vm).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.value_error)); + }); + } + + #[test] + fn acquire_timeout_errors_precede_nonblocking_restriction() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + for (timeout, expected) in [ + (vm.ctx.none(), vm.ctx.exceptions.type_error), + ( + vm.ctx.new_float(f64::NAN).into(), + vm.ctx.exceptions.value_error, + ), + ( + vm.ctx.new_float(f64::INFINITY).into(), + vm.ctx.exceptions.overflow_error, + ), + ( + vm.ctx.new_int(i128::MAX).into(), + vm.ctx.exceptions.overflow_error, + ), + ] { + let args = AcquireArgs { + blocking: OptionalArg::Present(vm.ctx.none()), + timeout: OptionalArg::Present(timeout), + }; + let error = validate_acquire_args(&args, vm).unwrap_err(); + assert!(error.fast_isinstance(expected)); + if error.fast_isinstance(vm.ctx.exceptions.value_error) { + let message = error.get_arg(0).unwrap(); + assert_eq!( + message.downcast_ref::().unwrap().as_wtf8().as_str(), + Ok("Invalid value NaN (not a number)"), + ); + } + } + for blocking in [false, true] { + for seconds in [-1e-300, -2.0] { + let args = AcquireArgs { + blocking: OptionalArg::Present(vm.ctx.new_bool(blocking).into()), + timeout: OptionalArg::Present(vm.ctx.new_float(seconds).into()), + }; + let error = validate_acquire_args(&args, vm).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.value_error)); + let message = error.get_arg(0).unwrap(); + assert_eq!( + message.downcast_ref::().unwrap().as_wtf8().as_str(), + Ok(if blocking { + "timeout value must be a non-negative number" + } else { + "can't specify a timeout for a non-blocking call" + }), + ); + } + } + }); + } + + /// Exercise only the native completion-state invariant, without Python + /// execution or actual fork in the multithreaded Rust test harness. + #[test] + #[cfg(all(unix, feature = "host_env"))] + fn fork_reinitializes_surviving_handle_completion_lock() { + for (ident, state, completed, expected_state, expected_completed) in [ + ( + 7, + ThreadHandleState::Running, + false, + ThreadHandleState::Running, + false, + ), + ( + 0, + ThreadHandleState::NotStarted, + false, + ThreadHandleState::NotStarted, + false, + ), + ( + 8, + ThreadHandleState::Running, + false, + ThreadHandleState::Done, + true, + ), + ( + 8, + ThreadHandleState::Done, + true, + ThreadHandleState::Done, + true, + ), + ] { + let inner = parking_lot::Mutex::new(ThreadHandleInner { + state, + ident, + join_handle: None, + joining: false, + joined: false, + }); + let done_event = ( + parking_lot::Mutex::new(completed), + parking_lot::Condvar::new(), + ); + // Model the bytes inherited from a parent joiner that held the + // mutex at fork. No guard remains live and no other thread can + // access these exclusively owned fixtures. + core::mem::forget(done_event.0.lock()); + assert!(done_event.0.try_lock().is_none()); + // SAFETY: these private fixtures have no live guards/waiters, + // exactly as in a child after its parent lock owner vanished. + unsafe { reinit_handle_after_fork(&inner, &done_event, 7) }; + let completed = done_event + .0 + .try_lock() + .expect("copied completion lock must be unlocked"); + assert_eq!(*completed, expected_completed); + let inner = inner.lock(); + assert_eq!(inner.state, expected_state); + assert_eq!(inner.ident, ident); + } + } /// Regression test for #7941: a Python thread started without an /// explicit `threading.stack_size()` must not run on Rust's 2 MiB diff --git a/crates/vm/src/stdlib/_types.rs b/crates/vm/src/stdlib/_types.rs index d1d02f7202e..f45d513fc5d 100644 --- a/crates/vm/src/stdlib/_types.rs +++ b/crates/vm/src/stdlib/_types.rs @@ -58,6 +58,16 @@ mod _types { vm.ctx.types.ellipsis_type.to_owned().into() } + #[pyattr] + fn FrameLocalsProxyType(vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.types.frame_locals_proxy_type.to_owned().into() + } + + #[pyattr] + fn LazyImportType(vm: &VirtualMachine) -> PyObjectRef { + vm.ctx.types.lazy_import_type.to_owned().into() + } + #[pyattr] fn FrameType(vm: &VirtualMachine) -> PyObjectRef { vm.ctx.types.frame_type.to_owned().into() diff --git a/crates/vm/src/stdlib/_typing.rs b/crates/vm/src/stdlib/_typing.rs index 863dd8367b2..25bb9b84427 100644 --- a/crates/vm/src/stdlib/_typing.rs +++ b/crates/vm/src/stdlib/_typing.rs @@ -1,7 +1,10 @@ // spell-checker:ignore typevarobject funcobj typevartuples use crate::{ - Context, PyResult, VirtualMachine, builtins::pystr::AsPyStr, class::PyClassImpl, - function::IntoFuncArgs, + AsObject, Context, PyObject, PyResult, VirtualMachine, + builtins::{PyStr, pystr::AsPyStr}, + class::PyClassImpl, + common::wtf8::Wtf8Buf, + function::{Either, IntoFuncArgs}, }; pub use crate::stdlib::typevar::{ @@ -26,16 +29,75 @@ pub fn call_typing_func_object<'a>( func.call(args, vm) } +/// Write the shared type representation used by aliases, unions and annotations. +/// Equivalent of _Py_typing_type_repr. +pub(crate) fn typing_type_repr( + writer: &mut Wtf8Buf, + obj: &PyObject, + vm: &VirtualMachine, +) -> PyResult<()> { + if obj.is(&vm.ctx.ellipsis) { + writer.push_str("..."); + return Ok(()); + } + if obj.is(vm.ctx.types.none_type) { + writer.push_str("None"); + return Ok(()); + } + + // has_attr releases each temporary value before the next lookup or repr. + if obj.has_attr(identifier!(vm, __origin__), vm)? + && obj.has_attr(identifier!(vm, __args__), vm)? + { + writer.push_wtf8(obj.repr(vm)?.as_object().str(vm)?.as_wtf8()); + return Ok(()); + } + + let Some(qualname) = vm.get_attribute_opt(obj, identifier!(vm, __qualname__))? else { + writer.push_wtf8(obj.repr(vm)?.as_object().str(vm)?.as_wtf8()); + return Ok(()); + }; + let module = vm.get_attribute_opt(obj, identifier!(vm, __module__))?; + let result = (|| { + let Some(module) = module.as_ref().filter(|module| !vm.is_none(module)) else { + return obj.repr(vm).map(Either::A); + }; + if module + .downcast_ref::() + .is_some_and(|module| module.as_wtf8() == "builtins") + { + return qualname.str(vm).map(Either::A); + } + let mut repr = module.str(vm)?.as_wtf8().to_owned(); + repr.push_str("."); + repr.push_wtf8(qualname.str(vm)?.as_wtf8()); + Ok(Either::B(repr)) + })(); + // Attribute values can own finalizers; release them in lookup order, + // before releasing the string returned by __str__ or __repr__. + drop(qualname); + drop(module); + match result? { + // PyUnicodeWriter_WriteStr applies str() to a returned str subclass. + Either::A(repr) => writer.push_wtf8(repr.as_object().str(vm)?.as_wtf8()), + Either::B(repr) => writer.push_wtf8(&repr), + } + Ok(()) +} + #[pymodule(name = "_typing", with(super::typevar::typevar))] pub(crate) mod decl { + use super::typing_type_repr; use crate::class::PyClassDef; use crate::common::lock::LazyLock; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, atomic_func, - builtins::{PyGenericAlias, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, type_}, + builtins::{ + PyFunction, PyGenericAlias, PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, type_, + }, common::wtf8::Wtf8Buf, - function::FuncArgs, + function::{FuncArgs, OptionalArg, PySetterValue}, protocol::{PyMappingMethods, PyNumberMethods}, types::{AsMapping, AsNumber, Callable, Constructor, Iterable, Representable}, }; @@ -125,65 +187,31 @@ pub(crate) mod decl { } } - /// String representation of a type for annotation purposes. - /// Equivalent of _Py_typing_type_repr. - fn typing_type_repr(obj: &PyObject, vm: &VirtualMachine) -> PyResult { - // Ellipsis - if obj.is(&vm.ctx.ellipsis) { - return Ok("...".to_owned()); - } - // NoneType -> "None" - if obj.is(&vm.ctx.types.none_type.as_object()) { - return Ok("None".to_owned()); - } - // Generic aliases (has __origin__ and __args__) -> repr - let has_origin = obj.get_attr("__origin__", vm).is_ok(); - let has_args = obj.get_attr("__args__", vm).is_ok(); - if has_origin && has_args { - return Ok(obj.repr(vm)?.to_string()); - } - // Has __qualname__ and __module__ - if let Ok(qualname) = obj.get_attr("__qualname__", vm) - && let Ok(module) = obj.get_attr("__module__", vm) - && !vm.is_none(&module) - && let Some(module_str) = module.downcast_ref::() - { - if module_str.as_bytes() == b"builtins" { - return Ok(qualname.str_utf8(vm)?.as_str().to_owned()); - } - return Ok(format!( - "{}.{}", - module_str.as_wtf8(), - qualname.str_utf8(vm)?.as_str() - )); - } - // Fallback to repr - Ok(obj.repr(vm)?.to_string()) - } - /// Format a value as a string for ANNOTATE_FORMAT_STRING. /// Handles tuples specially by wrapping in parentheses. fn typing_type_repr_value(value: &PyObject, vm: &VirtualMachine) -> PyResult { - if let Ok(tuple) = value.try_to_ref::(vm) { - let mut parts = Vec::with_capacity(tuple.as_slice().len()); - for item in tuple { - parts.push(typing_type_repr(item, vm)?); + let mut repr = Wtf8Buf::new(); + if let Some(tuple) = value.downcast_ref::() { + repr.push_str("("); + for (i, item) in tuple.as_slice().iter().enumerate() { + if i > 0 { + repr.push_str(", "); + } + typing_type_repr(&mut repr, item, vm)?; } - let inner = if parts.len() == 1 { - format!("{},", parts[0]) - } else { - parts.join(", ") - }; - Ok(vm.ctx.new_str(format!("({inner})")).into()) + repr.push_str(")"); } else { - Ok(vm.ctx.new_str(typing_type_repr(value, vm)?).into()) + typing_type_repr(&mut repr, value, vm)?; } + Ok(vm.ctx.new_str(repr).into()) } impl Representable for ConstEvaluator { - fn repr_str(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let value_repr = zelf.value.repr(vm)?; - Ok(format!("")) + fn repr_wtf8(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let mut repr = Wtf8Buf::from(""); + Ok(repr) } } @@ -197,12 +225,26 @@ pub(crate) mod decl { pub(crate) struct TypeAliasType { #[pymember(name = "__name__")] name: PyStrRef, + #[pymember(name = "__qualname__")] + qualname: PyStrRef, type_params: PyTupleRef, compute_value: PyObjectRef, cached_value: crate::common::lock::PyMutex>, - module: Option, + module: crate::common::lock::PyMutex>, is_lazy: bool, } + #[derive(FromArgs)] + pub(crate) struct TypeAliasArgs { + #[pyarg(any)] + name: PyObjectRef, + #[pyarg(any)] + value: PyObjectRef, + #[pyarg(named, optional, py_default = "()")] + type_params: OptionalArg, + #[pyarg(named, optional, py_default = "None")] + qualname: OptionalArg, + } + impl TypeAliasType { /// Create from intrinsic: compute_value is a callable that returns the value pub(crate) fn new( @@ -210,12 +252,19 @@ pub(crate) mod decl { type_params: PyTupleRef, compute_value: PyObjectRef, ) -> Self { + let qualname = compute_value + .downcast_ref::() + .expect("type alias evaluator must be a function") + .code + .qualname + .to_owned(); Self { name, + qualname, type_params, compute_value, cached_value: crate::common::lock::PyMutex::new(None), - module: None, + module: crate::common::lock::PyMutex::new(None), is_lazy: true, } } @@ -223,16 +272,18 @@ pub(crate) mod decl { /// Create with an eagerly evaluated value (used by constructor) fn new_eager( name: PyStrRef, + qualname: PyStrRef, type_params: PyTupleRef, value: PyObjectRef, module: Option, ) -> Self { Self { name, + qualname, type_params, compute_value: value.clone(), cached_value: crate::common::lock::PyMutex::new(Some(value)), - module, + module: crate::common::lock::PyMutex::new(module), is_lazy: false, } } @@ -250,40 +301,44 @@ pub(crate) mod decl { Ok(PyGenericAlias::new(origin, args_tuple, false, vm)?.into_pyobject(vm)) } - /// Check type_params ordering: non-default params must precede default params. - /// Uses __default__ attribute to check if a type param has a default value, - /// comparing against typing.NoDefault sentinel (like get_type_param_default). + // Validate native type parameters before evaluating their defaults. Arbitrary + // objects with a __default__ attribute are not type parameters. fn check_type_params( type_params: &Py, vm: &VirtualMachine, - ) -> PyResult> { + ) -> PyResult { if type_params.as_slice().is_empty() { - return Ok(None); + return Ok(vm.ctx.empty_tuple.clone()); } let no_default = &vm.ctx.typing_no_default; let mut default_seen = false; for param in type_params { - let dflt = param.get_attr("__default__", vm).map_err(|_| { - vm.new_type_error(format!( - "Expected a type param, got {}", - param - .repr(vm) - .map_or_else(|_| "?".to_owned(), |s| s.to_string()) - )) - })?; - let is_no_default = dflt.is(no_default); - if is_no_default { + let class = param.class(); + if !class.is(super::TypeVar::class(&vm.ctx)) + && !class.is(super::ParamSpec::class(&vm.ctx)) + && !class.is(super::TypeVarTuple::class(&vm.ctx)) + { + let repr = param.repr(vm)?; + let mut message = Wtf8Buf::from("Expected a type param, got "); + message.push_wtf8(repr.as_wtf8()); + return Err(vm.new_type_error(message)); + } + // These immutable native types supply the default descriptor. Let + // a lazy default's exception propagate without reclassifying it. + let dflt = param.get_attr("__default__", vm)?; + if dflt.is(no_default) { if default_seen { - return Err(vm.new_type_error(format!( - "non-default type parameter '{}' follows default type parameter", - param.repr(vm)? - ))); + let repr = param.repr(vm)?; + let mut message = Wtf8Buf::from("non-default type parameter '"); + message.push_wtf8(repr.as_wtf8()); + message.push_str("' follows default type parameter"); + return Err(vm.new_type_error(message)); } } else { default_seen = true; } } - Ok(Some(type_params.to_owned())) + Ok(type_params.to_owned()) } } @@ -317,16 +372,24 @@ pub(crate) mod decl { #[pygetset] fn __module__(&self, vm: &VirtualMachine) -> PyObjectRef { - if let Some(ref module) = self.module { - return module.clone(); + let module = self.module.lock().clone(); + if let Some(module) = module { + return module; } // Fall back to compute_value's __module__ (like PyFunction_GetModule) - if let Ok(module) = self.compute_value.get_attr("__module__", vm) { + if self.is_lazy + && let Ok(module) = self.compute_value.get_attr("__module__", vm) + { return module; } vm.ctx.none() } + #[pygetset(setter)] + fn set___module__(&self, value: PySetterValue) { + let _previous = core::mem::replace(&mut *self.module.lock(), value.into_option()); + } + #[pymethod] fn __reduce__(zelf: &Self, _vm: &VirtualMachine) -> PyObjectRef { zelf.name.clone().into() @@ -347,57 +410,28 @@ pub(crate) mod decl { } impl Constructor for TypeAliasType { - type Args = FuncArgs; - - fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - // typealias(name, value, *, type_params=()) - // name and value are positional-or-keyword; type_params is keyword-only. - - // Reject unexpected keyword arguments. - for key in args.kwargs.keys() { - if !matches!(key.as_str(), Ok("name" | "value" | "type_params")) { - return Err( - vm.new_unexpected_keyword_type_error(Some("typealias"), &key.to_string()) - ); - } - } - - // Reject too many positional arguments - if args.args.len() > 2 { - return Err(vm.new_type_error(format!( - "typealias() takes exactly 2 positional arguments ({} given)", - args.args.len() - ))); - } - - // Resolve name: positional[0] or kwarg - let name = if !args.args.is_empty() { - if args.kwargs.contains_key("name") { - return Err(vm.new_type_error( - "argument for typealias() given by name ('name') and position (1)", - )); - } - args.args[0].clone() - } else { - args.kwargs.get("name").cloned().ok_or_else(|| { - vm.new_type_error("typealias() missing required argument 'name' (pos 1)") - })? - }; - - // Resolve value: positional[1] or kwarg - let value = if args.args.len() >= 2 { - if args.kwargs.contains_key("value") { - return Err(vm.new_type_error( - "argument for typealias() given by name ('value') and position (2)", - )); - } - args.args[1].clone() - } else { - args.kwargs.get("value").cloned().ok_or_else(|| { - vm.new_type_error("typealias() missing required argument 'value' (pos 2)") - })? + type Args = TypeAliasArgs; + + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let args: Self::Args = args.bind_for(vm, "typealias")?; + // Empty tuple subclasses are normalized away, but their finalizers + // must not run before the alias object has been allocated. + let _original_type_params = match &args.type_params { + OptionalArg::Present(tp) => Some(tp.clone()), + OptionalArg::Missing => None, }; + Self::py_new(&cls, args, vm) + .and_then(|payload| payload.into_ref_with_type(vm, cls).map(Into::into)) + } + fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { + // Bind raw objects first, so call-shape errors precede conversion. + let TypeAliasArgs { + name, + value, + type_params, + qualname, + } = args; let name = name.downcast::().map_err(|obj| { vm.new_type_error(format!( "typealias() argument 'name' must be str, not {}", @@ -405,28 +439,44 @@ pub(crate) mod decl { )) })?; - let type_params = if let Some(tp) = args.kwargs.get("type_params") { - let tp = tp - .clone() - .downcast::() - .map_err(|_| vm.new_type_error("type_params must be a tuple"))?; - Self::check_type_params(&tp, vm)?; - tp - } else { - vm.ctx.empty_tuple.clone() + let checked_type_params = match &type_params { + OptionalArg::Present(tp) => { + let tp = tp + .clone() + .downcast::() + .map_err(|_| vm.new_type_error("type_params must be a tuple"))?; + Self::check_type_params(&tp, vm)? + } + OptionalArg::Missing => vm.ctx.empty_tuple.clone(), + }; + + let qualname = match qualname { + OptionalArg::Present(qualname) if !vm.is_none(&qualname) => qualname + .downcast::() + .map_err(|_| vm.new_type_error("qualname must be a string"))?, + _ => name.clone(), }; - // Get caller's module name from frame globals, like typevar.rs caller() - let module = - crate::frame::current_globals().and_then(|g| g.get_item("__name__", vm).ok()); + // Like CPython's caller(), use the function's cached module metadata, + // which can differ from the current globals' __name__ entry. + let function = vm + .current_frame() + .and_then(|frame| frame.iframe().func_obj().map(|obj| obj.to_owned())); + let module = function.and_then(|func| func.get_attr("__module__", vm).ok()); - Ok(Self::new_eager(name, type_params, value, module)) + Ok(Self::new_eager( + name, + qualname, + checked_type_params, + value, + module, + )) } } impl Representable for TypeAliasType { fn repr_wtf8(zelf: &Py, _vm: &VirtualMachine) -> PyResult { - Ok(zelf.name.as_wtf8().to_owned()) + Ok(zelf.qualname.as_wtf8().to_owned()) } } diff --git a/crates/vm/src/stdlib/_warnings.rs b/crates/vm/src/stdlib/_warnings.rs index 8a8f92b77da..870e988021c 100644 --- a/crates/vm/src/stdlib/_warnings.rs +++ b/crates/vm/src/stdlib/_warnings.rs @@ -1,15 +1,16 @@ pub(crate) use _warnings::module_def; use crate::{Py, PyResult, VirtualMachine, builtins::PyType}; +use rustpython_common::wtf8::Wtf8Buf; pub fn warn( category: &Py, - message: String, + message: impl Into, stack_level: usize, vm: &VirtualMachine, ) -> PyResult<()> { crate::warn::warn( - vm.new_pyobj(message), + vm.ctx.new_str(message.into()).into(), Some(category.to_owned()), isize::try_from(stack_level).unwrap_or(isize::MAX), None, @@ -21,10 +22,11 @@ pub fn warn( mod _warnings { use crate::{ AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine, - builtins::{PyDictRef, PyListRef, PyStrRef, PyTupleRef, PyTypeRef}, + builtins::{PyAnyDict, PyDictRef, PyListRef, PyStrRef, PyTupleRef, PyTypeRef}, convert::TryFromObject, function::OptionalArg, }; + use rustpython_common::wtf8::wtf8_concat; #[pyattr] fn filters(vm: &VirtualMachine) -> PyListRef { @@ -84,13 +86,13 @@ mod _warnings { struct WarnArgs { #[pyarg(any)] message: PyObjectRef, - #[pyarg(any, optional)] - category: OptionalArg, + #[pyarg(any, default = None)] + category: Option, #[pyarg(any, default = 1)] - stacklevel: i32, - #[pyarg(any, optional)] - source: OptionalArg, - #[pyarg(named, optional)] + stacklevel: isize, + #[pyarg(any, default = None)] + source: Option, + #[pyarg(named, optional, py_default = "()")] skip_file_prefixes: OptionalArg, } @@ -100,15 +102,12 @@ mod _warnings { category: Option, vm: &VirtualMachine, ) -> PyResult> { + if message.fast_isinstance(vm.ctx.exceptions.warning) { + return Ok(Some(message.class().to_owned())); + } let cat_obj = match category { Some(c) if !vm.is_none(&c) => c, - _ => { - return Ok(if message.fast_isinstance(vm.ctx.exceptions.warning) { - Some(message.class().to_owned()) - } else { - None // will default to UserWarning in warn_explicit - }); - } + _ => return Ok(None), // will default to UserWarning in warn_explicit }; let cat = PyTypeRef::try_from_object(vm, cat_obj.clone()).map_err(|_| { @@ -119,9 +118,10 @@ mod _warnings { })?; if !cat.fast_issubclass(vm.ctx.exceptions.warning) { - return Err(vm.new_type_error(format!( - "category must be a Warning subclass, not '{}'", - cat.class().name() + return Err(vm.new_type_error(wtf8_concat!( + "category must be a Warning subclass, not class '", + cat.fully_qualified_name(vm)?, + "'" ))); } @@ -130,9 +130,9 @@ mod _warnings { #[pyfunction] fn warn(args: WarnArgs, vm: &VirtualMachine) -> PyResult<()> { - let level = args.stacklevel as isize; + let level = args.stacklevel; - let category = get_category(&args.message, args.category.into_option(), vm)?; + let category = get_category(&args.message, args.category, vm)?; // Validate skip_file_prefixes: each element must be a str let skip_prefixes = args.skip_file_prefixes.into_option(); @@ -148,7 +148,7 @@ mod _warnings { args.message, category, level, - args.source.into_option(), + args.source, skip_prefixes.as_deref(), vm, ) @@ -166,11 +166,11 @@ mod _warnings { lineno: usize, #[pyarg(any, optional)] module: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "None")] registry: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "None")] module_globals: OptionalArg, - #[pyarg(any, optional)] + #[pyarg(any, optional, py_default = "None")] source: OptionalArg, } @@ -183,10 +183,10 @@ mod _warnings { let source_line = if let Some(mg) = args.module_globals.into_option() { if vm.is_none(&mg) { None - } else if !mg.class().is(vm.ctx.types.dict_type) { - return Err(vm.new_type_error(format!( - "module_globals must be a dict, not '{}'", - mg.class().name() + } else if PyAnyDict::from_object(&mg).is_none() { + return Err(vm.new_type_error(wtf8_concat!( + "module_globals must be a dict or a frozendict, not ", + mg.class().fully_qualified_name(vm)? ))); } else { crate::warn::get_source_line(&mg, args.lineno, vm)? diff --git a/crates/vm/src/stdlib/_weakref.rs b/crates/vm/src/stdlib/_weakref.rs index 767f793fdf9..624a1d511b2 100644 --- a/crates/vm/src/stdlib/_weakref.rs +++ b/crates/vm/src/stdlib/_weakref.rs @@ -52,8 +52,9 @@ mod _weakref { #[pyfunction] fn _remove_dead_weakref(dct: PyDictRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + let hash = key.hash(vm)?; dct._as_dict_inner() - .delete_if(vm, &*key, |wr| { + .delete_if(vm, &*key, hash, |wr| { let wr = wr .downcast_ref::() .ok_or_else(|| vm.new_type_error("not a weakref"))?; diff --git a/crates/vm/src/stdlib/_winapi.rs b/crates/vm/src/stdlib/_winapi.rs index 36bd9afbdfa..806e6366078 100644 --- a/crates/vm/src/stdlib/_winapi.rs +++ b/crates/vm/src/stdlib/_winapi.rs @@ -6,21 +6,51 @@ pub(crate) use _winapi::module_def; #[pymodule] mod _winapi { use crate::{ - Py, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, + AsObject, Py, PyObjectRef, PyPayload, PyResult, TryFromObject, VirtualMachine, builtins::PyStrRef, common::lock::{PyMutex, PyMutexGuard}, - convert::ToPyException, + convert::{ToPyException, ToPyObject}, exceptions::nul_char_error, - function::{ArgMapping, ArgSequence, OptionalArg}, + function::{ArgBytesLike, ArgMapping, ArgSequence, OptionalArg}, types::Constructor, windows::{WinHandle, WindowsSysResult}, }; use core::ptr::null_mut; + use num_traits::ToPrimitive; use rustpython_common::wtf8::Wtf8Buf; use rustpython_host_env::overlapped as host_overlapped; use rustpython_host_env::winapi as host_winapi; use rustpython_host_env::windows::ToWideString; + // Argument Clinic converts LPCWSTR arguments in positional order. Keep the + // conversion here, not in the body after later __index__ calls can run. + struct ArgWideString { + wide: widestring::WideCString, + // Argument Clinic keeps the original argument alive through the call. + _owner: PyStrRef, + } + + impl TryFromObject for ArgWideString { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let value = PyStrRef::try_from_object(vm, obj)?; + let wide = value + .as_wtf8() + .to_wide_cstring() + .map_err(|_| nul_char_error(vm))?; + Ok(Self { + wide, + _owner: value, + }) + } + } + + fn audit_wide(value: Option<&widestring::WideCStr>, vm: &VirtualMachine) -> PyObjectRef { + value.map_or_else( + || vm.ctx.none(), + |value| vm.ctx.new_str(Wtf8Buf::from_wide(value.as_slice())).into(), + ) + } + #[pyattr] use host_winapi::{ ABOVE_NORMAL_PRIORITY_CLASS, BELOW_NORMAL_PRIORITY_CLASS, @@ -38,6 +68,8 @@ mod _winapi { ERROR_ALREADY_EXISTS, ERROR_BROKEN_PIPE, ERROR_IO_PENDING, ERROR_MORE_DATA, ERROR_NETNAME_DELETED, ERROR_NO_DATA, ERROR_NO_SYSTEM_RESOURCES, ERROR_OPERATION_ABORTED, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, ERROR_PRIVILEGE_NOT_HELD, ERROR_SEM_TIMEOUT, + EVENTLOG_AUDIT_FAILURE, EVENTLOG_AUDIT_SUCCESS, EVENTLOG_ERROR_TYPE, + EVENTLOG_INFORMATION_TYPE, EVENTLOG_SUCCESS, EVENTLOG_WARNING_TYPE, FILE_FLAG_FIRST_PIPE_INSTANCE, FILE_FLAG_OVERLAPPED, FILE_GENERIC_READ, FILE_GENERIC_WRITE, FILE_MAP_ALL_ACCESS, FILE_MAP_COPY, FILE_MAP_EXECUTE, FILE_MAP_READ, FILE_MAP_WRITE, FILE_TYPE_CHAR, FILE_TYPE_DISK, FILE_TYPE_PIPE, FILE_TYPE_REMOTE, FILE_TYPE_UNKNOWN, @@ -66,12 +98,80 @@ mod _winapi { #[pyattr] const INVALID_HANDLE_VALUE: isize = host_overlapped::INVALID_HANDLE_VALUE_ISIZE; + #[derive(FromArgs)] + struct DuplicateOptions { + #[pyarg(positional, default)] + options: u32, + } + + #[derive(FromArgs)] + struct WaitTimeout { + #[pyarg(positional, default = host_winapi::INFINITE_TIMEOUT)] + milliseconds: u32, + } + + #[derive(FromArgs)] + struct PeekSize { + #[pyarg(positional, default)] + size: i32, + } + #[pyattr] const INFINITE: u32 = host_winapi::INFINITE_TIMEOUT; #[pyfunction] - fn CloseHandle(handle: WinHandle) -> WindowsSysResult { - WindowsSysResult(host_winapi::close_handle(handle.0)) + fn CloseHandle(handle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = WinHandle::from_bitfield(&handle, vm, "CloseHandle", "argument")?; + WindowsSysResult(host_winapi::close_handle(value.0)).into_pyresult(vm)?; + Ok(vm.ctx.none()) + } + + #[pyfunction] + fn RegisterEventSource( + unc_server_name: Option, + source_name: PyStrRef, + vm: &VirtualMachine, + ) -> PyResult { + let unc_server_name = unc_server_name + .map(|unc_server_name| unc_server_name.as_wtf8().to_wide_cstring()) + .transpose() + .map_err(|_| nul_char_error(vm))?; + let source_name = source_name + .as_wtf8() + .to_wide_cstring() + .map_err(|_| nul_char_error(vm))?; + vm.allow_threads(|| { + host_winapi::register_event_source_w(unc_server_name.as_deref(), &source_name) + }) + .map(WinHandle) + .map_err(|error| error.to_pyexception(vm)) + } + + #[pyfunction] + fn DeregisterEventSource(handle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = WinHandle::from_bitfield(&handle, vm, "DeregisterEventSource", "argument")?; + vm.allow_threads(|| host_winapi::deregister_event_source(value.0)) + .map_err(|error| error.to_pyexception(vm))?; + Ok(vm.ctx.none()) + } + + #[pyfunction] + fn ReportEvent( + handle: WinHandle, + r#type: u16, + category: u16, + event_id: u32, + string: PyStrRef, + vm: &VirtualMachine, + ) -> PyResult<()> { + let string = string + .as_wtf8() + .to_wide_cstring() + .map_err(|_| nul_char_error(vm))?; + vm.allow_threads(|| { + host_winapi::report_event_w(handle.0, r#type, category, event_id, &string) + }) + .map_err(|error| error.to_pyexception(vm)) } /// CreateFile - Create or open a file or I/O device. @@ -81,7 +181,7 @@ mod _winapi { )] #[pyfunction] fn CreateFile( - file_name: PyStrRef, + file_name: ArgWideString, desired_access: u32, share_mode: u32, _security_attributes: PyObjectRef, // Always NULL (0) @@ -90,12 +190,18 @@ mod _winapi { _template_file: PyObjectRef, // Always NULL (0) vm: &VirtualMachine, ) -> PyResult { - let file_name_wide = file_name - .as_wtf8() - .to_wide_cstring() - .map_err(|_| nul_char_error(vm))?; + let file_name_wide = &file_name.wide; + vm.audit("_winapi.CreateFile", || { + ( + audit_wide(Some(file_name_wide), vm), + desired_access, + share_mode, + creation_disposition, + flags_and_attributes, + ) + })?; host_winapi::create_file_w( - &file_name_wide, + file_name_wide, desired_access, share_mode, creation_disposition, @@ -106,13 +212,12 @@ mod _winapi { } #[pyfunction] - fn GetStdHandle( - std_handle: host_winapi::StdHandle, - vm: &VirtualMachine, - ) -> PyResult> { - host_winapi::get_std_handle(std_handle) + fn GetStdHandle(std_handle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = WinHandle::unsigned_long_bitfield(&std_handle, vm, "GetStdHandle", "argument")?; + let handle = host_winapi::get_std_handle(value) .map(|handle| handle.map(WinHandle)) - .map_err(|e| e.to_pyexception(vm)) + .map_err(|e| e.to_pyexception(vm))?; + Ok(handle.to_pyobject(vm)) } #[pyfunction] @@ -121,6 +226,7 @@ mod _winapi { size: u32, vm: &VirtualMachine, ) -> PyResult<(WinHandle, WinHandle)> { + vm.audit("_winapi.CreatePipe", || ())?; host_winapi::create_pipe(size) .map(|(read, write)| (WinHandle(read), WinHandle(write))) .map_err(|e| e.to_pyexception(vm)) @@ -128,21 +234,21 @@ mod _winapi { #[pyfunction] fn DuplicateHandle( - src_process: WinHandle, - src: WinHandle, - target_process: WinHandle, - access: u32, - inherit: i32, - options: OptionalArg, + source_process_handle: WinHandle, + source_handle: WinHandle, + target_process_handle: WinHandle, + desired_access: u32, + inherit_handle: i32, + DuplicateOptions { options }: DuplicateOptions, vm: &VirtualMachine, ) -> PyResult { host_winapi::duplicate_handle( - src_process.0, - src.0, - target_process.0, - access, - inherit, - options.unwrap_or(0), + source_process_handle.0, + source_handle.0, + target_process_handle.0, + desired_access, + inherit_handle, + options, ) .map(WinHandle) .map_err(|e| e.to_pyexception(vm)) @@ -176,21 +282,23 @@ mod _winapi { #[derive(FromArgs)] struct CreateProcessArgs { #[pyarg(positional)] - name: Option, + application_name: Option, #[pyarg(positional)] - command_line: Option, + command_line: PyObjectRef, #[pyarg(positional)] - _proc_attrs: PyObjectRef, + #[allow(dead_code)] + proc_attrs: PyObjectRef, #[pyarg(positional)] - _thread_attrs: PyObjectRef, + #[allow(dead_code)] + thread_attrs: PyObjectRef, #[pyarg(positional)] inherit_handles: i32, #[pyarg(positional)] creation_flags: u32, #[pyarg(positional)] - env_mapping: Option, + env_mapping: PyObjectRef, #[pyarg(positional)] - current_dir: Option, + current_directory: Option, #[pyarg(positional)] startup_info: PyObjectRef, } @@ -200,20 +308,41 @@ mod _winapi { args: CreateProcessArgs, vm: &VirtualMachine, ) -> PyResult<(WinHandle, WinHandle, u32, u32)> { + let app_name = args + .application_name + .as_ref() + .map(|name| name.wide.as_ucstr()); + let current_dir = args + .current_directory + .as_ref() + .map(|name| name.wide.as_ucstr()); + vm.audit("_winapi.CreateProcess", || { + ( + audit_wide(app_name, vm), + args.command_line.clone(), + audit_wide(current_dir, vm), + ) + })?; + + // Default failed startup attribute lookups as CPython does. Keep value + // conversion errors separate from lookup failures. macro_rules! si_attr { ($attr:ident, $t:ty) => {{ - >::try_from_object( - vm, - args.startup_info.get_attr(stringify!($attr), vm)?, - )? - .unwrap_or(0) as _ + args.startup_info + .get_attr(stringify!($attr), vm) + .ok() + .map(|obj| >::try_from_object(vm, obj)) + .transpose()? + .flatten() + .unwrap_or(0) as _ }}; ($attr:ident) => {{ - >::try_from_object( - vm, - args.startup_info.get_attr(stringify!($attr), vm)?, - )? - .unwrap_or(0) + args.startup_info + .get_attr(stringify!($attr), vm) + .ok() + .map(|obj| TryFromObject::try_from_object(vm, obj)) + .transpose()? + .unwrap_or(0) }}; } let startup_info = host_winapi::StartupInfoData { @@ -224,35 +353,51 @@ mod _winapi { std_error: si_attr!(hStdError, isize), }; - let env = args - .env_mapping - .map(|m| getenvironment(m, vm)) + let env_mapping = if vm.is_none(&args.env_mapping) { + None + } else { + Some(ArgMapping::try_from_object(vm, args.env_mapping)?) + }; + let env = env_mapping + .as_ref() + .map(|mapping| getenvironment(mapping, vm)) .transpose()?; - let handle_list = get_handle_list(args.startup_info.get_attr("lpAttributeList", vm)?, vm)?; + let handle_list = args + .startup_info + .get_attr("lpAttributeList", vm) + .ok() + .map(|obj| get_handle_list(obj, vm)) + .transpose()? + .flatten(); - // Validate no embedded null bytes in command name and command line - // before handing the strings off; to_wide_cstring rejects interior NULs. - let wcstring = |s: PyStrRef| { - s.as_wtf8() - .to_wide_cstring() - .map_err(|_| nul_char_error(vm)) + let mut command_line = if vm.is_none(&args.command_line) { + None + } else { + let line = args + .command_line + .downcast_ref::() + .ok_or_else(|| { + vm.new_type_error(format!( + "CreateProcess() argument 2 must be str or None, not {}", + args.command_line.class().name() + )) + })?; + Some( + line.as_wtf8() + .to_wide_cstring() + .map_err(|_| nul_char_error(vm))? + .into_vec_with_nul(), + ) }; - let app_name = args.name.map(wcstring).transpose()?; - let current_dir = args.current_dir.map(wcstring).transpose()?; - let mut command_line = args - .command_line - .map(|s| wcstring(s).map(widestring::WideCString::into_vec_with_nul)) - .transpose() - .map_err(|_| nul_char_error(vm))?; let procinfo = host_winapi::create_process( - app_name.as_deref(), + app_name, command_line.as_deref_mut(), args.inherit_handles, args.creation_flags, env.as_deref(), - current_dir.as_deref(), + current_dir, startup_info, handle_list, ) @@ -269,18 +414,19 @@ mod _winapi { #[pyfunction] fn OpenProcess( desired_access: u32, - inherit_handle: bool, + inherit_handle: i32, process_id: u32, vm: &VirtualMachine, ) -> PyResult { - host_winapi::open_process(desired_access, inherit_handle, process_id) + vm.audit("_winapi.OpenProcess", || (process_id, desired_access))?; + host_winapi::open_process(desired_access, inherit_handle != 0, process_id) .map(WinHandle) .map_err(|e| e.to_pyexception(vm)) } #[pyfunction] - fn ExitProcess(exit_code: u32) { - host_winapi::exit_process(exit_code) + fn ExitProcess(ExitCode: u32) { + host_winapi::exit_process(ExitCode) } #[pyfunction] @@ -294,16 +440,28 @@ mod _winapi { #[pyfunction] fn CreateJunction( - src_path: PyStrRef, - dest_path: PyStrRef, + src_path: ArgWideString, + dst_path: ArgWideString, vm: &VirtualMachine, ) -> PyResult<()> { - let src_path = std::path::Path::new(src_path.expect_str()); - let dest_path = std::path::Path::new(dest_path.expect_str()); - host_winapi::create_junction(src_path, dest_path).map_err(|e| e.to_pyexception(vm)) + use std::os::windows::ffi::OsStringExt; + let src_wide = &src_path.wide; + let dst_wide = &dst_path.wide; + if src_wide.as_slice().starts_with(&[92, 63, 63, 92]) { + return Err(std::io::Error::from_raw_os_error(87).to_pyexception(vm)); + } + vm.audit("_winapi.CreateJunction", || { + ( + audit_wide(Some(src_wide), vm), + audit_wide(Some(dst_wide), vm), + ) + })?; + let src = std::path::PathBuf::from(std::ffi::OsString::from_wide(src_wide.as_slice())); + let dst = std::path::PathBuf::from(std::ffi::OsString::from_wide(dst_wide.as_slice())); + host_winapi::create_junction(&src, &dst).map_err(|e| e.to_pyexception(vm)) } - fn getenvironment(env: ArgMapping, vm: &VirtualMachine) -> PyResult> { + fn getenvironment(env: &ArgMapping, vm: &VirtualMachine) -> PyResult> { let keys = env.mapping().keys(vm)?; let values = env.mapping().values(vm)?; @@ -317,9 +475,9 @@ mod _winapi { let mut entries = Vec::with_capacity(keys.len()); for (k, v) in keys.into_iter().zip(values) { let k = PyStrRef::try_from_object(vm, k)?; - let k = k.expect_str().to_owned(); + let k = k.as_wtf8().encode_wide().collect(); let v = PyStrRef::try_from_object(vm, v)?; - let v = v.expect_str().to_owned(); + let v = v.as_wtf8().encode_wide().collect(); entries.push((k, v)); } @@ -346,24 +504,45 @@ mod _winapi { } #[pyfunction] - fn WaitForSingleObject(h: WinHandle, ms: i64, vm: &VirtualMachine) -> PyResult { - // Negative values (e.g., -1) map to INFINITE (0xFFFFFFFF) - let ms = if ms < 0 { - host_winapi::INFINITE_TIMEOUT - } else if ms > u32::MAX as i64 { - return Err(vm.new_overflow_error("timeout value is too large")); - } else { - ms as u32 + fn WaitForSingleObject( + handle: WinHandle, + milliseconds: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + let Some(index) = milliseconds.try_index_opt(vm) else { + let actual = if vm.is_none(&milliseconds) { + "None".to_owned() + } else { + let name = milliseconds.class().slot_name(); + name[..name.floor_char_boundary(50.min(name.len()))].to_owned() + }; + return Err(vm.new_type_error(format!( + "WaitForSingleObject() argument 2 must be int, not {actual}" + ))); }; - vm.allow_threads(|| host_winapi::wait_for_single_object(h.0, ms)) + let index = index?; + let fits = index + .as_bigint() + .to_i64() + .is_some_and(|value| (i32::MIN as i64..=u32::MAX as i64).contains(&value)); + if !fits { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "integer value out of range".to_owned(), + 1, + vm, + )?; + } + let milliseconds = index.as_u32_mask(); + vm.allow_threads(|| host_winapi::wait_for_single_object(handle.0, milliseconds)) .map_err(|e| e.to_pyexception(vm)) } #[pyfunction] fn WaitForMultipleObjects( handle_seq: ArgSequence, - wait_all: bool, - milliseconds: u32, + wait_flag: bool, + WaitTimeout { milliseconds }: WaitTimeout, vm: &VirtualMachine, ) -> PyResult { let handles: Vec = handle_seq @@ -381,19 +560,25 @@ mod _winapi { } vm.allow_threads(|| { - host_winapi::wait_for_multiple_objects(&handles, wait_all, milliseconds) + host_winapi::wait_for_multiple_objects(&handles, wait_flag, milliseconds) }) .map_err(|e| e.to_pyexception(vm)) } #[pyfunction] - fn GetExitCodeProcess(h: WinHandle, vm: &VirtualMachine) -> PyResult { - host_winapi::get_exit_code_process(h.0).map_err(|e| e.to_pyexception(vm)) + fn GetExitCodeProcess(process: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = WinHandle::from_bitfield(&process, vm, "GetExitCodeProcess", "argument")?; + let code = host_winapi::get_exit_code_process(value.0).map_err(|e| e.to_pyexception(vm))?; + Ok(vm.ctx.new_int(code).into()) } #[pyfunction] - fn TerminateProcess(h: WinHandle, exit_code: u32) -> WindowsSysResult { - WindowsSysResult(host_winapi::terminate_process(h.0, exit_code)) + fn TerminateProcess(handle: WinHandle, exit_code: u32, vm: &VirtualMachine) -> PyResult<()> { + vm.audit("_winapi.TerminateProcess", || { + (handle.0 as isize, exit_code) + })?; + WindowsSysResult(host_winapi::terminate_process(handle.0, exit_code)).into_pyresult(vm)?; + Ok(()) } #[derive(FromArgs)] @@ -439,30 +624,37 @@ mod _winapi { } #[pyfunction] - fn GetModuleFileName(handle: isize, vm: &VirtualMachine) -> PyResult { + fn GetModuleFileName(module_handle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = WinHandle::from_bitfield(&module_handle, vm, "GetModuleFileName", "argument")?; let mut path: Vec = vec![0; host_winapi::MAX_PATH_USIZE]; - let length = host_winapi::get_module_file_name(handle as _, &mut path); + let length = host_winapi::get_module_file_name(value.0, &mut path); if length == 0 { return Err(vm.new_runtime_error("GetModuleFileName failed")); } let (path, _) = path.split_at(length as usize); - Ok(String::from_utf16(path).unwrap()) + Ok(vm.ctx.new_str(String::from_utf16(path).unwrap()).into()) } - #[pyfunction] - fn OpenMutexW( + #[derive(FromArgs)] + #[from_args(legacy, fname = "OpenMutexW")] + struct OpenMutexWArgs { + #[pyarg(any)] desired_access: u32, - inherit_handle: bool, - name: PyStrRef, - vm: &VirtualMachine, - ) -> PyResult { - let name = name - .as_wtf8() - .to_wide_cstring() - .map_err(|_| nul_char_error(vm))?; - host_winapi::open_mutex_w(desired_access, inherit_handle, &name) + #[pyarg(any)] + inherit_handle: i32, + #[pyarg(any)] + name: ArgWideString, + } + + #[pyfunction] + fn OpenMutexW(args: OpenMutexWArgs, vm: &VirtualMachine) -> PyResult { + let name = &args.name.wide; + vm.audit("_winapi.OpenMutexW", || { + (args.desired_access, audit_wide(Some(name), vm)) + })?; + host_winapi::open_mutex_w(args.desired_access, args.inherit_handle != 0, name) .map(WinHandle) .map_err(|e| e.to_pyexception(vm)) } @@ -482,13 +674,22 @@ mod _winapi { // LCMapStringEx - Map a string to another string using locale-specific rules // This is used by ntpath.normcase() for proper Windows case conversion - #[pyfunction] - fn LCMapStringEx( + #[derive(FromArgs)] + #[from_args(legacy, fname = "LCMapStringEx")] + struct LCMapStringExArgs { + #[pyarg(any)] locale: PyStrRef, + #[pyarg(any)] flags: u32, + #[pyarg(any)] src: PyStrRef, - vm: &VirtualMachine, - ) -> PyResult { + } + + #[pyfunction] + fn LCMapStringEx(args: LCMapStringExArgs, vm: &VirtualMachine) -> PyResult { + let locale = args.locale; + let flags = args.flags; + let src = args.src; // Reject unsupported flags if flags & (host_winapi::LCMAP_SORTHANDLE_FLAG @@ -524,7 +725,7 @@ mod _winapi { #[derive(FromArgs)] struct CreateNamedPipeArgs { #[pyarg(positional)] - name: PyStrRef, + name: ArgWideString, #[pyarg(positional)] open_mode: u32, #[pyarg(positional)] @@ -538,19 +739,19 @@ mod _winapi { #[pyarg(positional)] default_timeout: u32, #[pyarg(positional)] - _security_attributes: PyObjectRef, // Ignored, can be None + #[allow(dead_code)] + security_attributes: PyObjectRef, // Ignored, can be None } // CreateNamedPipe - Create a named pipe #[pyfunction] fn CreateNamedPipe(args: CreateNamedPipeArgs, vm: &VirtualMachine) -> PyResult { - let name = args - .name - .as_wtf8() - .to_wide_cstring() - .map_err(|_| nul_char_error(vm))?; + let name = &args.name.wide; + vm.audit("_winapi.CreateNamedPipe", || { + (audit_wide(Some(name), vm), args.open_mode, args.pipe_mode) + })?; host_winapi::create_named_pipe_w( - &name, + name, args.open_mode, args.pipe_mode, args.max_instances, @@ -644,14 +845,14 @@ mod _winapi { struct ConnectNamedPipeArgs { #[pyarg(any)] handle: WinHandle, - #[pyarg(any, optional)] - overlapped: OptionalArg, + #[pyarg(any, default)] + overlapped: bool, } #[pyfunction] fn ConnectNamedPipe(args: ConnectNamedPipeArgs, vm: &VirtualMachine) -> PyResult { let handle = args.handle; - let use_overlapped = args.overlapped.unwrap_or(false); + let use_overlapped = args.overlapped; if use_overlapped { let ov = Overlapped::new_with_handle(handle.0, vm)?; @@ -676,8 +877,15 @@ mod _winapi { vm.ctx.new_str(result_str) } + #[derive(FromArgs)] + struct PathNameArgs { + #[pyarg(any)] + path: PyStrRef, + } + #[pyfunction] - fn GetShortPathName(path: PyStrRef, vm: &VirtualMachine) -> PyResult { + fn GetShortPathName(args: PathNameArgs, vm: &VirtualMachine) -> PyResult { + let path = args.path; let path = path .as_wtf8() .to_wide_cstring() @@ -687,7 +895,8 @@ mod _winapi { } #[pyfunction] - fn GetLongPathName(path: PyStrRef, vm: &VirtualMachine) -> PyResult { + fn GetLongPathName(args: PathNameArgs, vm: &VirtualMachine) -> PyResult { + let path = args.path; let path = path .as_wtf8() .to_wide_cstring() @@ -710,11 +919,9 @@ mod _winapi { #[pyfunction] fn PeekNamedPipe( handle: WinHandle, - size: OptionalArg, + PeekSize { size }: PeekSize, vm: &VirtualMachine, ) -> PyResult { - let size = size.unwrap_or(0); - if size < 0 { return Err(vm.new_value_error("negative size")); } @@ -722,7 +929,8 @@ mod _winapi { if size > 0 { let result = host_winapi::peek_named_pipe(handle.0, Some(size as u32)) .map_err(|e| e.to_pyexception(vm))?; - let buf = result.data.unwrap_or_default(); + let mut buf = result.data.unwrap_or_default(); + buf.shrink_to_fit(); let bytes: PyObjectRef = vm.ctx.new_bytes(buf).into(); Ok(vm .ctx @@ -746,21 +954,27 @@ mod _winapi { } // CreateEventW - Create or open a named or unnamed event object. - #[pyfunction] - fn CreateEventW( - security_attributes: isize, // Always NULL (0) - manual_reset: bool, - initial_state: bool, - name: Option, - vm: &VirtualMachine, - ) -> PyResult { - let _ = security_attributes; // Ignored, always NULL + #[derive(FromArgs)] + #[from_args(legacy, fname = "CreateEventW")] + struct CreateEventWArgs { + #[pyarg(any)] + security_attributes: isize, + #[pyarg(any)] + manual_reset: i32, + #[pyarg(any)] + initial_state: i32, + #[pyarg(any)] + name: Option, + } - let name = name - .map(|n| n.as_wtf8().to_wide_cstring()) - .transpose() - .map_err(|_| nul_char_error(vm))?; - host_winapi::create_event_w(manual_reset, initial_state, name.as_deref()) + #[pyfunction] + fn CreateEventW(args: CreateEventWArgs, vm: &VirtualMachine) -> PyResult { + let _ = args.security_attributes; + let name = args.name.as_ref().map(|name| name.wide.as_ucstr()); + vm.audit("_winapi.CreateEventW", || { + (args.manual_reset, args.initial_state, audit_wide(name, vm)) + })?; + host_winapi::create_event_w(args.manual_reset != 0, args.initial_state != 0, name) .map(WinHandle) .map_err(|e| e.to_pyexception(vm)) } @@ -772,11 +986,12 @@ mod _winapi { } #[derive(FromArgs)] + #[from_args(legacy, fname = "WriteFile")] struct WriteFileArgs { #[pyarg(any)] handle: WinHandle, #[pyarg(any)] - buffer: crate::function::ArgBytesLike, + buffer: ArgBytesLike, #[pyarg(any, default)] overlapped: bool, } @@ -812,6 +1027,7 @@ mod _winapi { } #[derive(FromArgs)] + #[from_args(legacy, fname = "ReadFile")] struct ReadFileArgs { #[pyarg(any)] handle: WinHandle, @@ -840,9 +1056,10 @@ mod _winapi { return Ok(result.into()); } - let result = vm + let mut result = vm .allow_threads(|| host_winapi::read_file(handle.0, size)) .map_err(|e| e.to_pyexception(vm))?; + result.data.shrink_to_fit(); Ok(vm .ctx .new_tuple(vec![ @@ -879,36 +1096,48 @@ mod _winapi { } // CreateMutexW - Create or open a named or unnamed mutex object. - #[pyfunction] - fn CreateMutexW( + #[derive(FromArgs)] + #[from_args(legacy, fname = "CreateMutexW")] + struct CreateMutexWArgs { + #[pyarg(any)] security_attributes: isize, - initial_owner: bool, - name: Option, - vm: &VirtualMachine, - ) -> PyResult { - let _ = security_attributes; - let name = name - .map(|n| n.as_wtf8().to_wide_cstring()) - .transpose() - .map_err(|_| nul_char_error(vm))?; - host_winapi::create_mutex_w(initial_owner, name.as_deref()) + #[pyarg(any)] + initial_owner: i32, + #[pyarg(any)] + name: Option, + } + + #[pyfunction] + fn CreateMutexW(args: CreateMutexWArgs, vm: &VirtualMachine) -> PyResult { + let _ = args.security_attributes; + let name = args.name.as_ref().map(|name| name.wide.as_ucstr()); + vm.audit("_winapi.CreateMutexW", || { + (args.initial_owner, audit_wide(name, vm)) + })?; + host_winapi::create_mutex_w(args.initial_owner != 0, name) .map(WinHandle) .map_err(|e| e.to_pyexception(vm)) } // OpenEventW - Open an existing named event object. - #[pyfunction] - fn OpenEventW( + #[derive(FromArgs)] + #[from_args(legacy, fname = "OpenEventW")] + struct OpenEventWArgs { + #[pyarg(any)] desired_access: u32, - inherit_handle: bool, - name: PyStrRef, - vm: &VirtualMachine, - ) -> PyResult { - let name = name - .as_wtf8() - .to_wide_cstring() - .map_err(|_| nul_char_error(vm))?; - host_winapi::open_event_w(desired_access, inherit_handle, &name) + #[pyarg(any)] + inherit_handle: i32, + #[pyarg(any)] + name: ArgWideString, + } + + #[pyfunction] + fn OpenEventW(args: OpenEventWArgs, vm: &VirtualMachine) -> PyResult { + let name = &args.name.wide; + vm.audit("_winapi.OpenEventW", || { + (args.desired_access, audit_wide(Some(name), vm)) + })?; + host_winapi::open_event_w(args.desired_access, args.inherit_handle != 0, name) .map(WinHandle) .map_err(|e| e.to_pyexception(vm)) } @@ -1059,40 +1288,61 @@ mod _winapi { // UnmapViewOfFile - Unmap a mapped view of a file. #[pyfunction] - fn UnmapViewOfFile(address: isize, vm: &VirtualMachine) -> PyResult<()> { - host_winapi::unmap_view_of_file(address).map_err(|e| e.to_pyexception(vm)) + fn UnmapViewOfFile(address: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = WinHandle::from_bitfield(&address, vm, "UnmapViewOfFile", "argument")?; + host_winapi::unmap_view_of_file(value.0 as isize).map_err(|e| e.to_pyexception(vm))?; + Ok(vm.ctx.none()) } // VirtualQuerySize - Return the size of a memory region. #[pyfunction] - fn VirtualQuerySize(address: isize, vm: &VirtualMachine) -> PyResult { - host_winapi::virtual_query_size(address).map_err(|e| e.to_pyexception(vm)) + fn VirtualQuerySize(address: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let value = WinHandle::from_bitfield(&address, vm, "VirtualQuerySize", "argument")?; + let size = + host_winapi::virtual_query_size(value.0 as isize).map_err(|e| e.to_pyexception(vm))?; + Ok(vm.ctx.new_int(size).into()) } - #[pyfunction] - fn CopyFile2( - existing_file_name: PyStrRef, - new_file_name: PyStrRef, + #[derive(FromArgs)] + #[from_args(legacy, fname = "CopyFile2")] + struct CopyFile2Args { + #[pyarg(any)] + existing_file_name: ArgWideString, + #[pyarg(any)] + new_file_name: ArgWideString, + #[pyarg(any)] flags: u32, - _progress_routine: OptionalArg, - vm: &VirtualMachine, - ) -> PyResult<()> { - let src_wide = existing_file_name - .as_wtf8() - .to_wide_cstring() - .map_err(|_| nul_char_error(vm))?; - let dst_wide = new_file_name - .as_wtf8() - .to_wide_cstring() - .map_err(|_| nul_char_error(vm))?; - host_winapi::copy_file2(&src_wide, &dst_wide, flags).map_err(|e| e.to_pyexception(vm)) + #[pyarg(any, default)] + progress_routine: Option, } #[pyfunction] - fn _mimetypes_read_windows_registry( + fn CopyFile2(args: CopyFile2Args, vm: &VirtualMachine) -> PyResult<()> { + let _ = args.progress_routine; + let src_wide = &args.existing_file_name.wide; + let dst_wide = &args.new_file_name.wide; + vm.audit("_winapi.CopyFile2", || { + ( + audit_wide(Some(src_wide), vm), + audit_wide(Some(dst_wide), vm), + args.flags, + ) + })?; + host_winapi::copy_file2(src_wide, dst_wide, args.flags).map_err(|e| e.to_pyexception(vm)) + } + + #[derive(FromArgs)] + struct MimeRegistryArgs { + #[pyarg(any)] on_type_read: PyObjectRef, + } + + #[pyfunction] + fn _mimetypes_read_windows_registry( + args: MimeRegistryArgs, vm: &VirtualMachine, ) -> PyResult<()> { + let on_type_read = args.on_type_read; host_winapi::read_windows_mimetype_registry_in_batches(|entries| { for (mime_type, ext) in entries.drain(..) { on_type_read.call((vm.ctx.new_str(mime_type), vm.ctx.new_str(ext)), vm)?; diff --git a/crates/vm/src/stdlib/_wmi.rs b/crates/vm/src/stdlib/_wmi.rs index e1549ef12d0..a0e509c7f0d 100644 --- a/crates/vm/src/stdlib/_wmi.rs +++ b/crates/vm/src/stdlib/_wmi.rs @@ -10,17 +10,35 @@ mod _wmi { use crate::{PyResult, VirtualMachine}; use rustpython_host_env::wmi as host_wmi; - #[pyfunction] - fn exec_query(query: PyStrRef, vm: &VirtualMachine) -> PyResult { - let query_str = query.expect_str(); + #[derive(FromArgs)] + struct ExecQueryArgs { + #[pyarg(any)] + query: PyStrRef, + } - if !query_str + #[pyfunction] + fn exec_query(args: ExecQueryArgs, vm: &VirtualMachine) -> PyResult { + // Bind all keywords before converting the query, as Argument Clinic does. + let query = args.query; + vm.audit("_wmi.exec_query", || (query.clone(),))?; + let mut code_units = query.as_wtf8().encode_wide().collect::>(); + // Adding the terminator first makes even a trailing input NUL interior. + code_units.push(0); + let wide = widestring::WideCString::from_vec(code_units) + .map_err(|_| vm.new_value_error("embedded null character"))?; + if !query + .as_wtf8() + .as_bytes() .get(..7) - .is_some_and(|s| s.eq_ignore_ascii_case("select ")) + .is_some_and(|s| s.eq_ignore_ascii_case(b"select ")) { return Err(vm.new_value_error("only SELECT queries are supported")); } - - host_wmi::exec_query(query_str).map_err(|err| err.to_pyexception(vm)) + host_wmi::exec_query_wide(&wide) + .map(|result| { + vm.ctx + .new_str(crate::common::wtf8::Wtf8Buf::from_wide(&result)) + }) + .map_err(|err| err.to_pyexception(vm)) } } diff --git a/crates/vm/src/stdlib/atexit.rs b/crates/vm/src/stdlib/atexit.rs index 0260b0f115d..7a9dad43b28 100644 --- a/crates/vm/src/stdlib/atexit.rs +++ b/crates/vm/src/stdlib/atexit.rs @@ -3,9 +3,7 @@ pub(crate) use atexit::module_def; #[pymodule] mod atexit { - use crate::{ - AsObject, PyObjectRef, PyResult, VirtualMachine, common::rc::PyRc, function::FuncArgs, - }; + use crate::{PyObjectRef, PyResult, VirtualMachine, common::rc::PyRc, function::FuncArgs}; #[pyfunction] fn register(func: PyObjectRef, args: FuncArgs, vm: &VirtualMachine) -> PyObjectRef { @@ -19,7 +17,9 @@ mod atexit { #[pyfunction] fn _clear(vm: &VirtualMachine) { - vm.state.atexit_funcs.lock().clear(); + let funcs = core::mem::take(&mut *vm.state.atexit_funcs.lock()); + // Like clearing the callback list, release entries backwards and unlocked. + for _entry in funcs.into_iter().rev() {} } #[pyfunction] @@ -71,22 +71,22 @@ mod atexit { #[pyfunction] pub fn _run_exitfuncs(vm: &VirtualMachine) { - let funcs: Vec<_> = core::mem::take(&mut *vm.state.atexit_funcs.lock()); + let funcs = vm.state.atexit_funcs.lock().clone(); // Callbacks stored in LIFO order, iterate forward - for entry in funcs { - let (func, args) = PyRc::try_unwrap(entry).unwrap_or_else(|e| (*e).clone()); - if let Err(e) = func.call(args, vm) { - let exit = e.fast_isinstance(vm.ctx.exceptions.system_exit); + for entry in &funcs { + let (func, args) = &**entry; + if let Err(e) = func.call(args.clone(), vm) { let msg = func .repr(vm) .ok() .map(|r| format!("Exception ignored in atexit callback {}", r.as_wtf8())); vm.run_unraisable(e, msg, vm.ctx.none()); - if exit { - break; - } } } + // Keep the whole snapshot alive through every callback, then release it + // before clearing the live registry, as atexit_callfuncs does. + for _entry in funcs.into_iter().rev() {} + _clear(vm); } #[pyfunction] diff --git a/crates/vm/src/stdlib/builtins.rs b/crates/vm/src/stdlib/builtins.rs index fbced8423a7..fae277a7770 100644 --- a/crates/vm/src/stdlib/builtins.rs +++ b/crates/vm/src/stdlib/builtins.rs @@ -3,7 +3,7 @@ //! Implements the list of [builtin Python functions](https://docs.python.org/3/library/builtins.html). use crate::{Py, VirtualMachine, builtins::PyModule, class::PyClassImpl}; pub(crate) use builtins::{DOC, module_def}; -pub use builtins::{ascii, print, reversed}; +pub use builtins::{ascii, print}; #[pymodule] mod builtins { @@ -11,57 +11,73 @@ mod builtins { AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, VirtualMachine, builtins::{ - PyByteArray, PyBytes, PyDictRef, PyStr, PyStrRef, PyTuple, PyTupleRef, PyType, - PyUtf8StrRef, - enumerate::PyReverseSequenceIterator, + PyAnyDict, PyByteArray, PyBytes, PyComplex, PyFloat, PyInt, PyStr, PyStrRef, PyTuple, + PyTupleRef, PyType, PyUtf8StrRef, function::{PyCell, PyCellRef, PyFunction}, iter::PyCallableIterator, - list::{PyList, SortOptions}, + list::{PyList, PyListRef, SortOptions}, + try_bigint_to_f64, }, bytecode, common::hash::PyHash, function::{ - ArgCallable, ArgIndex, ArgIntoBool, ArgIterable, ArgMapping, ArgStrOrBytesLike, Either, - FsPath, FuncArgs, KwArgs, NameKws, OptionalArg, PosArgs, + ArgCallable, ArgIndex, ArgIntoBool, ArgMapping, ArgNulFreeStr, ArgSpec, + ArgStrOrBytesLike, ArgumentError, Either, FromArgs, FsPath, FuncArgs, KwArgs, + NameObjects, OptionalArg, Param, PosArgs, }, protocol::{PyIter, PyIterReturn}, py_io, - readline::{Readline, ReadlineResult}, - stdlib::sys, + readline::ReadlineResult, types::PyComparisonOp, vm::compile_mode::{CompileStart, CompilerFlags, compile_future_features_from_flags}, }; use itertools::Itertools; + use num_complex::Complex64; use num_traits::{Signed, ToPrimitive}; - use rustpython_common::wtf8::CodePoint; + use rustpython_common::wtf8::{CodePoint, wtf8_concat}; #[cfg(not(feature = "rustpython-compiler"))] const CODEGEN_NOT_SUPPORTED: &str = "can't compile() to bytecode when the `codegen` feature of rustpython is disabled"; #[pyfunction] - fn abs(x: PyObjectRef, vm: &VirtualMachine) -> PyResult { - vm._abs(&x) + fn abs(number: PyObjectRef, vm: &VirtualMachine) -> PyResult { + vm._abs(&number) } #[pyfunction] - fn all(iterable: ArgIterable, vm: &VirtualMachine) -> PyResult { - for item in iterable.iter(vm)? { - if !item?.into_bool() { - return Ok(false); - } - } - Ok(true) + fn all(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult { + all_or_any(&iterable, false, vm) } #[pyfunction] - fn any(iterable: ArgIterable, vm: &VirtualMachine) -> PyResult { - for item in iterable.iter(vm)? { - if item?.into_bool() { - return Ok(true); + fn any(iterable: PyObjectRef, vm: &VirtualMachine) -> PyResult { + all_or_any(&iterable, true, vm) + } + + fn all_or_any(iterable: &PyObject, short_circuit: bool, vm: &VirtualMachine) -> PyResult { + let iter = iterable.get_iter(vm)?; + // Cache the slot, not __next__: the wrapper still looks up the method + // after callbacks mutate the iterator's type. + let next = iter.class().slots().iternext.load().ok_or_else(|| { + vm.new_type_error(format!( + "'{}' object is not an iterator", + iter.class().slot_name() + )) + })?; + loop { + match next(&iter, vm)? { + PyIterReturn::Return(item) => { + let truth = item.try_to_bool(vm); + if truth? == short_circuit { + return Ok(short_circuit); + } + } + PyIterReturn::StopIteration(_value) => { + return Ok(!short_circuit); + } } } - Ok(false) } #[pyfunction] @@ -70,8 +86,8 @@ mod builtins { } #[pyfunction] - fn bin(number: ArgIndex) -> String { - let number = number.into_int_ref(); + fn bin(integer: ArgIndex) -> String { + let number = integer.into_int_ref(); let x = number.as_bigint(); if x.is_negative() { format!("-0b{:b}", x.abs()) @@ -100,11 +116,8 @@ mod builtins { #[allow(dead_code)] struct CompileArgs { source: PyObjectRef, - // Resolved to FsPath at the start of compile() so that bytearray / - // memoryview / other buffer-protocol objects raise TypeError, matching - // CPython's PyUnicode_FSDecoder (str / bytes / __fspath__ only). - filename: PyObjectRef, - mode: PyUtf8StrRef, + filename: FsPath, + mode: ArgNulFreeStr, // CPython parity: flags / optimize accept any object with __index__, // not just exact int. Matches the argument conversion used by // builtin_compile_impl. @@ -118,6 +131,8 @@ mod builtins { dont_inherit: ArgIntoBool, #[pyarg(any, default = -1)] optimize: i32, + #[pyarg(named, optional)] + module: Option, #[pyarg(named, default = -1)] _feature_version: i32, } @@ -184,11 +199,7 @@ mod builtins { } #[cfg(feature = "ast")] { - // CPython parity: PyUnicode_FSDecoder accepts only str / bytes / - // __fspath__-bearing objects. Reject buffer-protocol types like - // bytearray and memoryview that would otherwise pass through - // `FsPath::TryFromObject`'s permissive fallback. - let filename = FsPath::try_from_path_like(args.filename, true, vm)?; + let filename = args.filename; use crate::{class::PyClassImpl, stdlib::_ast}; @@ -208,6 +219,17 @@ mod builtins { 0..=2 => optimize as u8, _ => return Err(vm.new_value_error("compile(): invalid optimize value")), }; + let module = args.module.filter(|module| !vm.is_none(module)); + let module = module + .map(|module| { + PyStrRef::try_from_object(vm, module.clone()).map_err(|_| { + vm.new_type_error(format!( + "compile() argument 'module' must be str or None, not {}", + module.class().name() + )) + }) + }) + .transpose()?; let dont_inherit = args.dont_inherit.into_bool(); let is_ast_only = cf.contains(CompilerFlags::ONLY_AST); let future_features = merge_compile_future_features(flags, dont_inherit, vm); @@ -297,7 +319,14 @@ mod builtins { opts.optimize = optimize; opts.allow_top_level_await = cf.contains(CompilerFlags::ALLOW_TOP_LEVEL_AWAIT); opts.future_features = future_features; - return _ast::compile(vm, args.source, &filename.to_string_lossy(), mode, opts); + return _ast::compile( + vm, + args.source, + &filename.to_string_lossy(), + mode, + opts, + module.as_deref(), + ); } } @@ -314,13 +343,14 @@ mod builtins { let mut compile_flags = flags | future_features.bits() as i32; #[cfg(feature = "rustpython-compiler")] let compile_source = |source: &[u8], compile_flags: i32| { - vm.compile_string_object_with_flags( + vm.compile_string_object_with_flags_and_module( source, &filename.to_string_lossy(), start.as_i32(), compile_flags, feature_version, optimize as i32, + module.as_deref(), ) }; match &source { @@ -387,7 +417,7 @@ mod builtins { } #[pyfunction] - fn dir(obj: OptionalArg, vm: &VirtualMachine) -> PyResult { + fn dir(obj: OptionalArg, vm: &VirtualMachine) -> PyResult { vm.dir(obj.into_option()) } @@ -401,78 +431,111 @@ mod builtins { #[pyarg(any, optional)] globals: Option, #[pyarg(any, optional)] - locals: Option, + locals: Option, } - impl ScopeArgs { - fn make_scope( - self, - vm: &VirtualMachine, - func_name: &'static str, - ) -> PyResult { - fn validate_globals_dict( - globals: &PyObject, - vm: &VirtualMachine, - func_name: &'static str, - ) -> PyResult<()> { - if !globals.fast_isinstance(vm.ctx.types.dict_type) { - return Err(match func_name { - "eval" => { - let is_mapping = globals.mapping_unchecked().check(); - vm.new_type_error(if is_mapping { - "globals must be a real dict; try eval(expr, {}, mapping)" - } else { - "globals must be a dict" - }) - } - "exec" => vm.new_type_error(format!( - "exec() globals must be a dict, not {}", - globals.class().name() - )), - _ => vm.new_type_error("globals must be a dict"), - }); - } - Ok(()) - } + /// `_PyEval_EnsureBuiltins` + fn ensure_builtins(globals: &PyAnyDict, vm: &VirtualMachine) -> PyResult<()> { + if globals + .inner_getitem_opt(identifier!(vm, __builtins__), vm)? + .is_some() + { + return Ok(()); + } + // PyEval_GetBuiltins + let builtins = + crate::frame::current_builtins().unwrap_or_else(|| vm.builtins.dict().into()); + match globals.as_mutable() { + Some(dict) => dict.inner_setitem(identifier!(vm, __builtins__), builtins, vm), + None => globals + .as_object() + .set_item(identifier!(vm, __builtins__), builtins, vm) + .map_err(|_| vm.new_type_error("cannot assign __builtins__ to frozendict globals")), + } + } - let (globals, locals) = match self.globals { - Some(globals) => { - validate_globals_dict(&globals, vm, func_name)?; + #[derive(Clone, Copy)] + enum ScopeKind { + Eval, + Exec, + } - let globals = PyDictRef::try_from_object(vm, globals)?; - if !globals.contains_key(identifier!(vm, __builtins__), vm) { - let builtins_dict = vm.builtins.dict().into(); - globals.set_item(identifier!(vm, __builtins__), builtins_dict, vm)?; - } - ( - globals.clone(), - self.locals - .unwrap_or_else(|| ArgMapping::from_dict_exact(globals.clone())), - ) + impl ScopeKind { + fn globals(self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult> { + let obj = match obj.downcast::() { + Ok(dict) => return Ok(dict.into()), + Err(obj) => obj, + }; + let obj = match obj.downcast::() { + Ok(dict) => return Ok(dict.into()), + Err(obj) => obj, + }; + let message = match self { + Self::Eval if obj.mapping_unchecked().check() => { + return Err(vm.new_type_error( + "globals must be a real dict or a frozendict; try eval(expr, {}, mapping)", + )); } - None => ( - vm.current_globals(), - if let Some(locals) = self.locals { - locals - } else { - vm.current_locals()? - }, + Self::Eval => { + return Err(vm.new_type_error("globals must be a dict or a frozendict")); + } + Self::Exec => wtf8_concat!( + "exec() globals must be a dict or a frozendict, not ", + obj.class().fully_qualified_name(vm)?, ), }; + Err(vm.new_type_error(message)) + } + + fn locals(self, obj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + if obj.mapping_unchecked().check() { + return Ok(ArgMapping::new(obj)); + } + Err(match self { + Self::Eval => vm.new_type_error("locals must be a mapping"), + Self::Exec => { + let name = obj.class().slot_name(); + let name = &name[..name.floor_char_boundary(name.len().min(100))]; + vm.new_type_error(format!("locals must be a mapping or None, not {name}")) + } + }) + } + } + + impl ScopeArgs { + fn make_scope(self, vm: &VirtualMachine, kind: ScopeKind) -> PyResult { + let Self { globals, locals } = self; + let explicit_globals = globals.is_some(); + let convert_globals = || globals.map(|obj| kind.globals(obj, vm)).transpose(); + let convert_locals = || locals.map(|obj| kind.locals(obj, vm)).transpose(); + // eval checks locals first; exec checks globals first. + let (globals, locals) = match kind { + ScopeKind::Eval => { + let locals = convert_locals()?; + (convert_globals()?, locals) + } + ScopeKind::Exec => (convert_globals()?, convert_locals()?), + }; + let globals = globals.unwrap_or_else(|| vm.current_globals()); + let locals = match locals { + Some(locals) => locals, + None if explicit_globals => ArgMapping::from_anydict_exact(globals.clone()), + None => vm.current_locals()?, + }; - let scope = crate::scope::Scope::with_builtins(Some(locals), globals, vm); - Ok(scope) + ensure_builtins(&globals, vm)?; + Ok(crate::scope::Scope::new(Some(locals), globals)) } } #[derive(FromArgs)] struct ExecArgs { #[pyarg(positional)] - source: Either, ArgStrOrBytesLike>, + source: PyObjectRef, #[pyarg(any, optional)] globals: Option, #[pyarg(any, optional)] - locals: Option, + locals: Option, #[pyarg(named, optional)] closure: Option, } @@ -520,17 +583,26 @@ mod builtins { }) } - #[pyfunction] - fn eval( - source: Either, ArgStrOrBytesLike>, - scope: ScopeArgs, + fn eval_exec_text_source( + source: PyObjectRef, vm: &VirtualMachine, - ) -> PyResult { - let scope = scope.make_scope(vm, "eval")?; + func_name: &str, + ) -> PyResult { + ArgStrOrBytesLike::try_from_object(vm, source).map_err(|_| { + vm.new_type_error(format!( + "{func_name}() arg 1 must be a string, bytes or code object" + )) + }) + } + + #[pyfunction] + fn eval(source: PyObjectRef, scope: ScopeArgs, vm: &VirtualMachine) -> PyResult { + let scope = scope.make_scope(vm, ScopeKind::Eval)?; - // source as string - let code = match source { - Either::B(either) => { + // Convert the source only after the scope has been prepared, as in CPython. + let code = match source.downcast::() { + Err(source) => { + let either = eval_exec_text_source(source, vm, "eval")?; let source = match &either { ArgStrOrBytesLike::Str(source) => { let source = source.try_as_utf8(vm)?.as_str(); @@ -559,7 +631,7 @@ mod builtins { }; Ok(Either::B(vm.ctx.new_utf8_str(source))) } - Either::A(code) => Ok(Either::A(code)), + Ok(code) => Ok(Either::A(code)), }?; run_code(vm, code, scope, crate::compiler::Mode::Eval, "eval", None) } @@ -572,14 +644,15 @@ mod builtins { locals, closure, } = args; - let scope = ScopeArgs { globals, locals }.make_scope(vm, "exec")?; - let (source, closure) = match source { - Either::B(either) => { + let scope = ScopeArgs { globals, locals }.make_scope(vm, ScopeKind::Exec)?; + let (source, closure) = match source.downcast::() { + Err(source) => { if closure.is_some() { return Err( vm.new_type_error("closure can only be used when source is a code object") ); } + let either = eval_exec_text_source(source, vm, "exec")?; let source = match &either { ArgStrOrBytesLike::Str(source) => { let source = source.try_as_utf8(vm)?.as_str(); @@ -606,7 +679,7 @@ mod builtins { }; (Either::B(vm.ctx.new_utf8_str(source)), None) } - Either::A(code) => { + Ok(code) => { let closure = exec_closure(&code, closure, vm)?; (Either::A(code), closure) } @@ -629,6 +702,7 @@ mod builtins { func: &str, closure: Option>>, ) -> PyResult { + let from_string = matches!(&source, Either::B(_)); // Determine code object: let code_obj = match source { #[cfg(feature = "rustpython-compiler")] @@ -638,8 +712,18 @@ mod builtins { if let Some(code) = crate::frame::current_code() { opts.future_features = code.flags & bytecode::CodeFlags::FUTURE_MASK; } - vm.compile_with_opts(source, mode, "", opts) - .map_err(|err| err.into_pyexception(vm, Some(source)))? + let module = scope + .globals + .inner_getitem_opt(identifier!(vm, __name__), vm)?; + vm.compile_with_opts_and_module_object( + source, + mode, + "", + opts, + module.as_deref(), + &[], + ) + .map_err(|err| err.into_pyexception(vm, Some(source)))? } #[cfg(not(feature = "rustpython-compiler"))] Either::B(_) => return Err(vm.new_type_error(CODEGEN_NOT_SUPPORTED)), @@ -654,6 +738,18 @@ mod builtins { ))); } + // run_eval_code_obj: set globals['__builtins__'] if it doesn't exist + if from_string + && scope + .globals + .inner_getitem_opt(identifier!(vm, __builtins__), vm)? + .is_none() + { + scope + .globals + .set_item(identifier!(vm, __builtins__), vm.builtins.dict().into(), vm)?; + } + // Run the code: vm.run_code_obj_with_closure(code_obj, scope, closure) } @@ -670,7 +766,7 @@ mod builtins { struct InputArgs { // Missing means an empty prompt. #[pyarg(positional, optional, py_default = "''")] - prompt: OptionalArg, + prompt: OptionalArg, } #[pyfunction] @@ -700,7 +796,7 @@ mod builtins { } #[pyfunction] - fn globals(vm: &VirtualMachine) -> PyDictRef { + fn globals(vm: &VirtualMachine) -> PyRef { vm.current_globals() } @@ -720,28 +816,41 @@ mod builtins { obj.hash(vm) } + // Only the displayed keyword collector name differs from FuncArgs. Keep + // its move-only conversion and binding metadata unchanged. + struct BreakpointArgs(FuncArgs); + + impl FromArgs for BreakpointArgs { + const PARAMS: Option<&'static [Param]> = + Some(&[Param::var_positional("args"), Param::var_keyword("kws")]); + const BINDING_PARAMS: Option<&'static [Param]> = FuncArgs::BINDING_PARAMS; + + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + FuncArgs::from_args(vm, args).map(Self) + } + } + #[pyfunction] - fn breakpoint( - args: PosArgs, - kws: KwArgs, - vm: &VirtualMachine, - ) -> PyResult { - let args = FuncArgs { - args: args.into_vec(), - kwargs: kws.into_default(), - }; - match vm + fn breakpoint(BreakpointArgs(args): BreakpointArgs, vm: &VirtualMachine) -> PyResult { + // PySys_GetAttr reads the dictionary, bypassing module attribute hooks. + // A present None is still selected and audited before the call fails. + let hook = vm .sys_module - .get_attr(vm.ctx.intern_str("breakpointhook"), vm) - { - Ok(hook) => hook.as_ref().call(args, vm), - Err(_) => Err(vm.new_runtime_error("lost sys.breakpointhook")), - } + .dict() + .get_item_opt("breakpointhook", vm)? + .ok_or_else(|| vm.new_runtime_error("lost sys.breakpointhook"))?; + vm.audit("builtins.breakpoint", || (hook.clone(),))?; + + // Audit callbacks can replace sys.breakpointhook. Invoke the selected + // hook, retaining the original arguments until that hook is released. + // Scope cleanup drops the later hook binding before the retained args. + let (_retained_args, hook) = (args.clone(), hook); + hook.call(args, vm) } #[pyfunction] - fn hex(number: ArgIndex) -> String { - let number = number.into_int_ref(); + fn hex(integer: ArgIndex) -> String { + let number = integer.into_int_ref(); let n = number.as_bigint(); format!("{n:#x}") } @@ -756,29 +865,52 @@ mod builtins { let prompt = args.prompt; use std::io::IsTerminal; - let stdin = sys::get_stdin(vm)?; - let stdout = sys::get_stdout(vm)?; - let stderr = sys::get_stderr(vm)?; + // PySys_GetAttr bypasses a sys module subclass's attribute hooks. + // Keep all three selected streams alive across the callbacks below. + let get_stream = |name| { + vm.sys_module + .dict() + .get_item_opt(name, vm)? + .filter(|stream| !vm.is_none(stream)) + .ok_or_else(|| vm.new_runtime_error(format!("lost sys.{name}"))) + }; + let stdin = get_stream("stdin")?; + let stdout = get_stream("stdout")?; + let stderr = get_stream("stderr")?; + + vm.audit("builtins.input", || { + (match &prompt { + OptionalArg::Present(prompt) => prompt.clone(), + OptionalArg::Missing => vm.ctx.none(), + },) + })?; let _ = vm.call_method(&stderr, "flush", ()); - let fd_matches = |obj, expected| { - vm.call_method(obj, "fileno", ()) - .and_then(|o| i64::try_from_object(vm, o)) - .is_ok_and(|fd| fd == expected) + let fd_matches = |obj, expected| -> PyResult { + // A failed fileno call selects the fallback, but conversion errors + // from a successfully returned descriptor must propagate. + let Ok(fileno) = vm.call_method(obj, "fileno", ()) else { + return Ok(false); + }; + let index = fileno.try_index(vm)?; + let fd = core::ffi::c_long::try_from(index.as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C long"))?; + Ok(fd == expected) }; - let tty = fd_matches(&stdin, 0) - && fd_matches(&stdout, 1) + let tty = fd_matches(&stdin, 0)? && std::io::stdin().is_terminal() + && fd_matches(&stdout, 1)? && std::io::stdout().is_terminal(); // Encode the prompt with stdout's encoding and reject embedded NULs // (`strlen` on the encoded bytes). - if tty && let OptionalArg::Present(prompt) = &prompt { + let tty_prompt = if tty && let OptionalArg::Present(prompt) = &prompt { let _ = vm.call_method(&stdout, "flush", ()); let encoding = stdout.get_attr("encoding", vm)?; let errors = stdout.get_attr("errors", vm)?; + let prompt = prompt.str(vm)?; if !vm.is_none(&encoding) { let encoded = vm.call_method(prompt.as_object(), "encode", (encoding, errors))?; let bytes = encoded @@ -790,21 +922,30 @@ mod builtins { )); } } - } + Some(prompt) + } else { + None + }; // rustyline is the interactive tty reader. Skip it in a PTY child // (`pty.fork` + `setsid`): raw mode hangs there. - let prompt_str = match &prompt { - OptionalArg::Present(s) => s.to_str(), - OptionalArg::Missing => Some(""), + let prompt_str = match &tty_prompt { + Some(s) => s.to_str(), + None => Some(""), }; let use_rustyline = tty && !is_pty_child() && prompt_str.is_some(); if use_rustyline { let prompt = prompt_str.unwrap(); - let mut readline = Readline::new(()); - match readline.readline(prompt) { - ReadlineResult::Line(s) => Ok(vm.ctx.new_str(s).into()), + let result = vm + .allow_threads(|| crate::readline::input_readline(prompt)) + .map_err(|_| vm.new_runtime_error("can't re-enter readline"))?; + match result { + ReadlineResult::Line(s) => { + let result = vm.ctx.new_str(s); + vm.audit("builtins.input/result", || (result.clone(),))?; + Ok(result.into()) + } ReadlineResult::Eof => { Err(vm.new_exception_empty(vm.ctx.exceptions.eof_error.to_owned())) } @@ -817,8 +958,12 @@ mod builtins { ReadlineResult::Other(e) => Err(vm.new_runtime_error(e.to_string())), } } else { - if let OptionalArg::Present(prompt) = prompt { - vm.call_method(&stdout, "write", (prompt,))?; + if let Some(prompt) = &tty_prompt { + // The TTY guard may still select the stream fallback. Reuse + // the already converted prompt rather than calling str twice. + vm.call_method(&stdout, "write", (prompt.clone(),))?; + } else if let OptionalArg::Present(prompt) = &prompt { + py_io::file_write_object(&stdout, prompt, vm)?; } let _ = vm.call_method(&stdout, "flush", ()); py_io::file_readline(&stdin, None, vm) @@ -880,23 +1025,23 @@ mod builtins { #[pyfunction] fn anext( - aiter: PyObjectRef, - default_value: OptionalArg, + async_iterator: PyObjectRef, + default: OptionalArg, vm: &VirtualMachine, ) -> PyResult { use crate::builtins::asyncgenerator::PyAnextAwaitable; // Check if object is an async iterator (has __anext__ method) - if !aiter.class().has_attr(identifier!(vm, __anext__)) { + if !async_iterator.class().has_attr(identifier!(vm, __anext__)) { return Err(vm.new_type_error(format!( "'{}' object is not an async iterator", - aiter.class().name() + async_iterator.class().name() ))); } - let awaitable = vm.call_method(&aiter, "__anext__", ())?; + let awaitable = vm.call_method(&async_iterator, "__anext__", ())?; - if let OptionalArg::Present(default) = default_value { + if let OptionalArg::Present(default) = default { Ok(PyAnextAwaitable::new(awaitable, default) .into_ref(&vm.ctx) .into()) @@ -915,8 +1060,32 @@ mod builtins { vm.current_locals() } + enum MinMaxCandidates<'a> { + Positional(core::slice::Iter<'a, PyObjectRef>), + Iterable(PyIter), + } + + impl MinMaxCandidates<'_> { + fn next(&mut self, vm: &VirtualMachine) -> PyResult> { + match self { + Self::Positional(args) => Ok(args.next().cloned()), + Self::Iterable(iter) => match iter.next(vm)? { + PyIterReturn::Return(item) => Ok(Some(item)), + PyIterReturn::StopIteration(_) => Ok(None), + }, + } + } + } + + // Field order is also release order: replacing the incumbent or unwinding + // an error must release its key before its item. + struct MinMaxBest { + key: PyObjectRef, + item: PyObjectRef, + } + fn min_or_max( - mut args: FuncArgs, + args: &FuncArgs, vm: &VirtualMachine, func_name: &'static str, op: PyComparisonOp, @@ -926,63 +1095,67 @@ mod builtins { return Err(vm.new_arity_type_error(func_name, 1..=usize::MAX, 0)); } - let default = args.take_keyword("default"); - let key_func = args.take_keyword("key"); - - if let Some(err) = args.check_kwargs_empty_for(vm, func_name) { - return Err(err); + let options = ArgSpec { + fname: func_name, + keywords: &["key", "default"], + required: 0, + max_positional: 0, } + .parse_keywords(&args.kwargs, vm)?; + let default = options[1].as_ref(); - let candidates = if args.args.len() > 1 { + let mut candidates = if args.args.len() > 1 { if default.is_some() { return Err(vm.new_type_error(format!( "Cannot specify a default for {func_name}() with multiple positional arguments" ))); } - args.args + // Keep the caller's slots alive, cloning only the current item. + MinMaxCandidates::Positional(args.args.iter()) } else { - args.args[0].try_to_value(vm)? - }; - - let mut candidates_iter = candidates.into_iter(); - let mut x = match candidates_iter.next() { - Some(x) => x, - None => { - return default.ok_or_else(|| { - vm.new_value_error(format!("{func_name}() iterable argument is empty")) - }); - } + MinMaxCandidates::Iterable(args.args[0].get_iter(vm)?) }; - - let key_func = key_func.filter(|f| !vm.is_none(f)); - if let Some(ref key_func) = key_func { - let mut x_key = key_func.call((x.clone(),), vm)?; - for y in candidates_iter { - let y_key = key_func.call((y.clone(),), vm)?; - if y_key.rich_compare_bool(&x_key, op, vm)? { - x = y; - x_key = y_key; - } - } - } else { - for y in candidates_iter { - if y.rich_compare_bool(&x, op, vm)? { - x = y; - } + let key_func = options[0].as_ref().filter(|f| !vm.is_none(f)); + + // Declare the incumbent after the iterator so error unwinding releases + // its key and item before releasing the iterator. + let mut best: Option = None; + while let Some(item) = candidates.next(vm)? { + // No later item is requested until this key and comparison finish. + // A key failure releases item before best; a comparison failure + // releases key, item, best's key and item, then the iterator. + let key = match key_func { + Some(key_func) => key_func.call((item.clone(),), vm)?, + None => item.clone(), + }; + let replace = match &best { + Some(best) => key.rich_compare_bool(&best.key, op, vm)?, + None => true, + }; + if replace { + best = Some(MinMaxBest { key, item }); + } else { + // Rejected candidates have the opposite release order. + drop(item); } } - Ok(x) + match best { + Some(MinMaxBest { key: _key, item }) => Ok(item), + None => default.cloned().ok_or_else(|| { + vm.new_value_error(format!("{func_name}() iterable argument is empty")) + }), + } } #[pyfunction] fn max(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - min_or_max(args, vm, "max", PyComparisonOp::Gt) + min_or_max(&args, vm, "max", PyComparisonOp::Gt) } #[pyfunction] fn min(args: FuncArgs, vm: &VirtualMachine) -> PyResult { - min_or_max(args, vm, "min", PyComparisonOp::Lt) + min_or_max(&args, vm, "min", PyComparisonOp::Lt) } #[pyfunction] @@ -1008,8 +1181,8 @@ mod builtins { } #[pyfunction] - fn oct(number: ArgIndex, vm: &VirtualMachine) -> PyObjectRef { - let number = number.into_int_ref(); + fn oct(integer: ArgIndex, vm: &VirtualMachine) -> PyObjectRef { + let number = integer.into_int_ref(); let n = number.as_bigint(); let s = if n.is_negative() { format!("-0o{:o}", n.abs()) @@ -1056,8 +1229,8 @@ mod builtins { struct PowArgs { base: PyObjectRef, exp: PyObjectRef, - #[pyarg(any, optional, name = "mod")] - modulus: Option, + #[pyarg(any, optional)] + r#mod: Option, } #[pyfunction] @@ -1065,7 +1238,7 @@ mod builtins { let PowArgs { base: x, exp: y, - modulus, + r#mod: modulus, } = args; let modulus = modulus .as_deref() @@ -1083,41 +1256,79 @@ mod builtins { pub struct PrintOptions { // None means a space; the string is filled in when printing. #[pyarg(named, default, py_default = "' '")] - sep: Option, + sep: Option, // None means a newline; the string is filled in when printing. #[pyarg(named, default, py_default = "'\\n'")] - end: Option, + end: Option, #[pyarg(named, optional)] file: Option, - #[pyarg(named, default = ArgIntoBool::FALSE)] - flush: ArgIntoBool, + #[pyarg(named, default, py_default = "False")] + flush: Option, } #[pyfunction] - pub fn print(objects: PosArgs, options: PrintOptions, vm: &VirtualMachine) -> PyResult<()> { - let file = match options.file { - Some(f) => f, - None => sys::get_stdout(vm)?, + pub fn print( + objects: PosArgs, + options: PrintOptions, + vm: &VirtualMachine, + ) -> PyResult<()> { + // Bind raw controls first, so unknown keywords fail before callbacks. + // Keep their owners until all writes and the final flush have finished. + let flush = options + .flush + .as_ref() + .map(|flush| flush.try_to_bool(vm)) + .transpose()? + .unwrap_or(false); + let file = match &options.file { + Some(f) => f.clone(), + None => vm + .sys_module + .dict() + .get_item_opt("stdout", vm)? + .ok_or_else(|| vm.new_runtime_error("lost sys.stdout"))?, }; - let write = |obj: PyStrRef| vm.call_method(&file, "write", (obj,)); - - let sep = options.sep.unwrap_or_else(|| vm.ctx.new_str(" ")); + // stdout can be None when the process has no connected output stream. + if vm.is_none(&file) { + return Ok(()); + } - let mut first = true; - for object in objects { - if first { - first = false; - } else { - write(sep.clone())?; + for (name, value) in [("sep", &options.sep), ("end", &options.end)] { + if let Some(value) = value + && value.downcast_ref::().is_none() + { + return Err(vm.new_type_error(format!( + "{name} must be None or a string, not {}", + value.class().slot_name(), + ))); } - - write(object.str(vm)?)?; } - let end = options.end.unwrap_or_else(|| vm.ctx.new_str("\n")); - write(end)?; + let default_sep; + let sep = match options.sep.as_deref() { + Some(sep) => sep, + None => { + default_sep = vm.ctx.new_str(" "); + default_sep.as_object() + } + }; + let default_end; + let end = match options.end.as_deref() { + Some(end) => end, + None => { + default_end = vm.ctx.new_str("\n"); + default_end.as_object() + } + }; + for (i, object) in objects.iter().enumerate() { + if i > 0 { + py_io::file_write_object(&file, sep, vm)?; + } + py_io::file_write_object(&file, object, vm)?; + } + py_io::file_write_object(&file, end, vm)?; - if options.flush.into() { + if flush { vm.call_method(&file, "flush", ())?; } @@ -1129,22 +1340,6 @@ mod builtins { obj.repr(vm) } - #[pyfunction] - pub fn reversed(sequence: PyObjectRef, vm: &VirtualMachine) -> PyResult { - if let Some(reversed_method) = - vm.get_method(sequence.clone(), identifier!(vm, __reversed__)) - { - reversed_method?.call((), vm) - } else { - vm.get_method_or_type_error(sequence.clone(), identifier!(vm, __getitem__), || { - "argument to reversed() must be a sequence".to_owned() - })?; - let len = sequence.length(vm)?; - let obj_iterator = PyReverseSequenceIterator::new(sequence, len); - Ok(obj_iterator.into_pyobject(vm)) - } - } - #[derive(FromArgs)] pub(super) struct RoundArgs { number: PyObjectRef, @@ -1163,10 +1358,9 @@ mod builtins { )) })?; match ndigits { - Some(obj) => { - let ndigits = obj.try_index(vm)?; - meth.invoke((ndigits,), vm) - } + // Like CPython, pass ndigits through as-is; the __round__ implementation + // decides what it accepts (float and int apply __index__ themselves). + Some(obj) => meth.invoke((obj,), vm), None => { // without a parameter, the result type is coerced to int meth.invoke((), vm) @@ -1206,7 +1400,7 @@ mod builtins { #[derive(FromArgs)] pub(super) struct SumArgs { #[pyarg(positional)] - iterable: ArgIterable, + iterable: PyObjectRef, // The int object needs the VM, so the default is not a literal. #[pyarg(any, default = 0)] start: PyObjectRef, @@ -1214,7 +1408,11 @@ mod builtins { #[pyfunction] fn sum(SumArgs { iterable, start }: SumArgs, vm: &VirtualMachine) -> PyResult { - let mut sum = start; + // Acquire and validate the iterator before rejecting a start type. + let items = iterable.get_iter(vm)?.into_iter::(vm); + // Keep the original argument alive independently of the accumulator. + // Declaring the accumulator last also releases it before the iterator. + let (_start, mut items, mut sum) = (start.clone(), items, start); match_class!(match sum { PyStr => @@ -1228,12 +1426,124 @@ mod builtins { _ => (), }); - for item in iterable.iter(vm)? { - sum = vm._add(&sum, &*item?)?; + // Fast paths after CPython's builtin_sum_impl: an exact int accumulator + // hands over to the float one, which hands over to the complex one. + if let Some(mut total) = sum + .downcast_ref_if_exact::(vm) + .and_then(|int| int.as_bigint().to_isize()) + { + let rest = loop { + let Some(item) = items.next().transpose()? else { + break None; + }; + let class = item.class(); + if (class.is(vm.ctx.types.int_type) || class.is(vm.ctx.types.bool_type)) + && let Some(next) = item + .downcast_ref::() + .and_then(|int| int.as_bigint().to_isize()) + .and_then(|x| total.checked_add(x)) + { + total = next; + continue; + } + break Some(item); + }; + let total = vm.ctx.new_int(total); + let Some(item) = rest else { + return Ok(total.into()); + }; + sum = vm._add(total.as_object(), &item)?; + } + + if let Some(float) = sum.downcast_ref_if_exact::(vm) { + let mut re = CompensatedSum::new(float.to_f64()); + let rest = loop { + let Some(item) = items.next().transpose()? else { + break None; + }; + if let Some(x) = item.downcast_ref_if_exact::(vm) { + re.add(x.to_f64()); + } else if let Some(x) = item.downcast_ref::() { + re.add(try_bigint_to_f64(x.as_bigint(), vm)?); + } else { + break Some(item); + } + }; + let total = vm.ctx.new_float(re.total()); + let Some(item) = rest else { + return Ok(total.into()); + }; + sum = vm._add(total.as_object(), &item)?; + } + + if let Some(complex) = sum.downcast_ref_if_exact::(vm) { + let z = complex.to_complex(); + let (mut re, mut im) = (CompensatedSum::new(z.re), CompensatedSum::new(z.im)); + let rest = loop { + let Some(item) = items.next().transpose()? else { + break None; + }; + if let Some(x) = item.downcast_ref_if_exact::(vm) { + let z = x.to_complex(); + re.add(z.re); + im.add(z.im); + } else if let Some(x) = item.downcast_ref::() { + re.add(try_bigint_to_f64(x.as_bigint(), vm)?); + } else if let Some(x) = item.downcast_ref::() { + re.add(x.to_f64()); + } else { + break Some(item); + } + }; + let total = vm.ctx.new_complex(Complex64::new(re.total(), im.total())); + let Some(item) = rest else { + return Ok(total.into()); + }; + sum = vm._add(total.as_object(), &item)?; + } + + for item in items.by_ref() { + let item = item?; + let result = vm._add(&sum, &item); + // On both success and failure, release the old total before the + // item, and only then propagate an addition error to the iterator. + drop(sum); + sum = result?; } Ok(sum) } + /// Compensated summation, as in CPython's `CompensatedSum`. + struct CompensatedSum { + hi: f64, + lo: f64, + } + + impl CompensatedSum { + fn new(x: f64) -> Self { + Self { hi: x, lo: 0.0 } + } + + fn add(&mut self, x: f64) { + let t = self.hi + x; + self.lo += if self.hi.abs() >= x.abs() { + (self.hi - t) + x + } else { + (x - t) + self.hi + }; + self.hi = t; + } + + fn total(&self) -> f64 { + // Keep a negative zero's sign, and do not turn an infinite sum into nan. + if self.lo != 0.0 && self.lo.is_finite() { + self.hi + self.lo + } else { + self.hi + } + } + } + #[derive(FromArgs)] struct ImportArgs { #[pyarg(any)] @@ -1267,11 +1577,58 @@ mod builtins { ) } + #[derive(FromArgs)] + struct LazyImportArgs { + #[pyarg(any)] + name: PyObjectRef, + #[pyarg(any, optional, py_default = "None")] + globals: OptionalArg, + #[pyarg(any, optional)] + locals: Option, + #[pyarg(any, default, py_default = "()")] + fromlist: Option, + #[pyarg(any, default)] + level: i32, + } + + #[pyfunction] + fn __lazy_import__(args: LazyImportArgs, vm: &VirtualMachine) -> PyResult { + let globals = args + .globals + .into_option() + .or_else(|| crate::frame::current_globals().map(Into::into)) + .ok_or_else(|| { + vm.new_type_error("__lazy_import__() missing globals when called without a frame") + })?; + let globals_dict = globals + .downcast_ref::() + .ok_or_else(|| { + vm.new_type_error(format!( + "expect dict for globals, got {}", + globals.class().name() + )) + })?; + let builtins = globals_dict + .inner_getitem_opt(identifier!(vm, __builtins__), vm)? + .ok_or_else(|| vm.new_value_error("unable to get builtins for lazy import"))?; + let builtins = if let Some(module) = builtins.downcast_ref::() { + module.dict().into() + } else { + builtins + }; + let name = args + .name + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("module name must be a string"))?; + let _ = args.locals; + crate::lazy_import::create(name, &globals, args.fromlist, args.level, builtins, vm) + } + #[pyfunction] fn vars(obj: OptionalArg, vm: &VirtualMachine) -> PyResult { if let OptionalArg::Present(obj) = obj { - obj.get_attr(identifier!(vm, __dict__), vm) - .map_err(|_| vm.new_type_error("vars() argument must have __dict__ attribute")) + vm.get_attribute_opt(&obj, identifier!(vm, __dict__))? + .ok_or_else(|| vm.new_type_error("vars() argument must have __dict__ attribute")) } else { Ok(vm.current_locals()?.into()) } @@ -1469,7 +1826,9 @@ pub fn init_module(vm: &VirtualMachine, module: &Py) { "complex" => ctx.types.complex_type.to_owned(), "dict" => ctx.types.dict_type.to_owned(), "enumerate" => ctx.types.enumerate_type.to_owned(), + "reversed" => ctx.types.reverse_iter_type.to_owned(), "float" => ctx.types.float_type.to_owned(), + "frozendict" => ctx.types.frozendict_type.to_owned(), "frozenset" => ctx.types.frozenset_type.to_owned(), "filter" => ctx.types.filter_type.to_owned(), "int" => ctx.types.int_type.to_owned(), @@ -1479,6 +1838,7 @@ pub fn init_module(vm: &VirtualMachine, module: &Py) { "object" => ctx.types.object_type.to_owned(), "property" => ctx.types.property_type.to_owned(), "range" => ctx.types.range_type.to_owned(), + "sentinel" => ctx.types.sentinel_type.to_owned(), "set" => ctx.types.set_type.to_owned(), "slice" => ctx.types.slice_type.to_owned(), "staticmethod" => ctx.types.staticmethod_type.to_owned(), @@ -1515,6 +1875,7 @@ pub fn init_module(vm: &VirtualMachine, module: &Py) { "BufferError" => ctx.exceptions.buffer_error.to_owned(), "EOFError" => ctx.exceptions.eof_error.to_owned(), "ImportError" => ctx.exceptions.import_error.to_owned(), + "ImportCycleError" => ctx.exceptions.import_cycle_error.to_owned(), "ModuleNotFoundError" => ctx.exceptions.module_not_found_error.to_owned(), "LookupError" => ctx.exceptions.lookup_error.to_owned(), "IndexError" => ctx.exceptions.index_error.to_owned(), diff --git a/crates/vm/src/stdlib/errno.rs b/crates/vm/src/stdlib/errno.rs index 0921ebac64a..df26cd35169 100644 --- a/crates/vm/src/stdlib/errno.rs +++ b/crates/vm/src/stdlib/errno.rs @@ -25,7 +25,6 @@ mod errno_mod { pub use rustpython_host_env::errno::errors; -#[cfg(any(unix, windows, target_os = "wasi"))] macro_rules! e { ($name:ident) => { (stringify!($name), errors::$name as _) @@ -722,7 +721,10 @@ const ERROR_CODES: &[(&str, i32)] = &[ ), e!(cfg(target_vendor = "apple"), EPWROFF), e!(cfg(target_vendor = "apple"), EQFULL), - e!(cfg(target_vendor = "apple"), ENOTCAPABLE), + e!( + cfg(any(target_vendor = "apple", target_os = "wasi")), + ENOTCAPABLE + ), e!( cfg(any( target_os = "dragonfly", @@ -749,4 +751,36 @@ const ERROR_CODES: &[(&str, i32)] = &[ ]; #[cfg(not(any(unix, windows, target_os = "wasi")))] -const ERROR_CODES: &[(&str, i32)] = &[]; +const ERROR_CODES: &[(&str, i32)] = &[ + e!(EPERM), + e!(ENOENT), + e!(ESRCH), + e!(EINTR), + e!(EIO), + e!(EBADF), + e!(ECHILD), + e!(EACCES), + e!(EEXIST), + e!(ENOTDIR), + e!(EISDIR), + e!(EINVAL), + e!(EMFILE), + e!(EFBIG), + e!(ENOSPC), + e!(ESPIPE), + e!(EROFS), + e!(EPIPE), + e!(EAGAIN), + e!(EWOULDBLOCK), + e!(EINPROGRESS), + e!(EALREADY), + e!(ENOTSUP), + e!(EAFNOSUPPORT), + e!(ECONNABORTED), + e!(ECONNRESET), + e!(ETIMEDOUT), + e!(ECONNREFUSED), + e!(ENAMETOOLONG), + e!(EOVERFLOW), + e!(ENOTCAPABLE), +]; diff --git a/crates/vm/src/stdlib/gc.rs b/crates/vm/src/stdlib/gc.rs index 92679b98503..cacf4df9ca0 100644 --- a/crates/vm/src/stdlib/gc.rs +++ b/crates/vm/src/stdlib/gc.rs @@ -3,9 +3,9 @@ pub(crate) use gc::module_def; #[pymodule] mod gc { use crate::{ - PyObjectRef, PyResult, VirtualMachine, - builtins::PyListRef, - function::{NameObjs, OptionalArg, PosArgs}, + AsObject, PyObject, PyObjectRef, PyResult, TryFromBorrowedObject, VirtualMachine, + builtins::{PyListRef, PyTupleRef}, + function::{ArgCInt, FuncArgs, NameObjs, OptionalArg, PosArgs}, gc_state, }; @@ -40,36 +40,34 @@ mod gc { #[derive(FromArgs)] struct CollectArgs { #[pyarg(any, default = 2)] - generation: i32, + generation: ArgCInt, } #[pyfunction] fn collect(args: CollectArgs, vm: &VirtualMachine) -> PyResult { - let generation_num = args.generation; + let generation_num = args.generation.into_primitive(); if !(0..=2).contains(&generation_num) { return Err(vm.new_value_error("invalid generation")); } - // Invoke callbacks with "start" phase - invoke_callbacks(vm, "start", generation_num as usize, &Default::default()); - - // Manual gc.collect() should run even if GC is disabled let gc = &vm.state.gc; - let result = gc.collect_force(generation_num as usize); - - // Publish what the collection saved as gc.garbage (for DEBUG_SAVEALL) - { - let mut state_garbage = gc.garbage.lock(); - if !state_garbage.is_empty() { - let mut garbage_vec = gc.py_garbage.borrow_vec_mut(); - for obj in state_garbage.drain(..) { - garbage_vec.push(obj); + let result = gc.collect_force_with_callbacks( + generation_num as usize, + || invoke_callbacks(vm, "start", generation_num as usize, &Default::default()), + |result| { + // Publish DEBUG_SAVEALL objects before the stop callbacks. + { + let mut state_garbage = gc.garbage.lock(); + if !state_garbage.is_empty() { + let mut garbage_vec = gc.py_garbage.borrow_vec_mut(); + for obj in state_garbage.drain(..) { + garbage_vec.push(obj); + } + } } - } - } - - // Invoke callbacks with "stop" phase - invoke_callbacks(vm, "stop", generation_num as usize, &result); + invoke_callbacks(vm, "stop", generation_num as usize, result); + }, + ); Ok((result.collected + result.uncollectable) as i32) } @@ -86,18 +84,44 @@ mod gc { .into() } + // set_threshold uses the legacy "i" converter, unlike Clinic's + // PyLong_AsInt converters for collect and set_debug. + struct Threshold(i32); + + impl<'a> TryFromBorrowedObject<'a> for Threshold { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + let index = obj.try_index(vm)?; + i32::try_from(index.as_bigint()).map(Self).map_err(|_| { + let message = if core::ffi::c_long::try_from(index.as_bigint()).is_err() { + "Python int too large to convert to C long" + } else if index.as_bigint().sign() == malachite_bigint::Sign::Minus { + "signed integer is less than minimum" + } else { + "signed integer is greater than maximum" + }; + vm.new_overflow_error(message) + }) + } + } + #[pyfunction] - fn set_threshold( - threshold0: u32, - threshold1: OptionalArg, - threshold2: OptionalArg, - vm: &VirtualMachine, - ) { + fn set_threshold(args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + // The generated optional-group wrapper checks the argument count + // before running any of its sequential integer conversions. + if !args.kwargs.is_empty() { + return Err(vm.new_type_error("set_threshold() takes no keyword arguments")); + } + if !(1..=3).contains(&args.args.len()) { + return Err(vm.new_type_error("gc.set_threshold requires 1 to 3 arguments")); + } + let (threshold0, threshold1, threshold2) = + args.bind::<(Threshold, OptionalArg, OptionalArg)>(vm)?; vm.state.gc.set_threshold( - threshold0, - threshold1.into_option(), - threshold2.into_option(), + threshold0.0, + threshold1.into_option().map(|value| value.0), + threshold2.into_option().map(|value| value.0), ); + Ok(()) } #[pyfunction] @@ -113,15 +137,17 @@ mod gc { } #[pyfunction] - fn get_debug(vm: &VirtualMachine) -> u32 { - vm.state.gc.get_debug().bits() + fn get_debug(vm: &VirtualMachine) -> i32 { + vm.state.gc.get_debug().bits() as i32 } #[pyfunction] - fn set_debug(flags: u32, vm: &VirtualMachine) { + fn set_debug(flags: ArgCInt, vm: &VirtualMachine) { vm.state .gc - .set_debug(gc_state::GcDebugFlags::from_bits_truncate(flags)); + .set_debug(gc_state::GcDebugFlags::from_bits_retain( + flags.into_primitive() as u32, + )); } #[pyfunction] @@ -146,27 +172,57 @@ mod gc { Ok(vm.ctx.new_list(result)) } + // Clinic's optional Py_ssize_t conversion accepts __index__, but reports + // missing-index and overflow errors using the original argument's type. + struct Generation(isize); + + impl<'a> TryFromBorrowedObject<'a> for Generation { + fn try_from_borrowed_object(vm: &VirtualMachine, obj: &'a PyObject) -> PyResult { + let index = obj.try_index_opt(vm).ok_or_else(|| { + let name = obj.class().slot_name(); + let name = &name[..name.floor_char_boundary(name.len().min(200))]; + vm.new_type_error(format!("argument should be integer or None, not '{name}'")) + })??; + isize::try_from(index.as_bigint()).map(Self).map_err(|_| { + let name = obj.class().slot_name(); + let name = &name[..name.floor_char_boundary(name.len().min(200))]; + vm.new_overflow_error(format!("cannot fit '{name}' into an index-sized integer")) + }) + } + } + /// Return the list of objects tracked by the collector. #[derive(FromArgs)] struct GetObjectsArgs { #[pyarg(any, optional)] - generation: Option, + generation: Option, } #[pyfunction] fn get_objects(args: GetObjectsArgs, vm: &VirtualMachine) -> PyResult { - let generation_opt = args.generation; - if let Some(g) = generation_opt - && !(0..=2).contains(&g) - { - return Err(vm.new_value_error(format!("generation must be in range(0, 3), not {g}"))); + let generation = args.generation.map_or(-1, |generation| generation.0); + vm.audit("gc.get_objects", || (generation,))?; + if generation >= 3 { + return Err(vm.new_value_error( + "generation parameter must be less than the number of available generations (3)", + )); + } + if generation < -1 { + return Err(vm.new_value_error("generation parameter cannot be negative")); } - let objects = vm.state.gc.get_objects(generation_opt); + let generation = (generation != -1).then_some(generation as i32); + let objects = vm.state.gc.get_objects_for_introspection(generation); Ok(vm.ctx.new_list(objects)) } #[pyfunction] - fn get_referents(objs: PosArgs, vm: &VirtualMachine) -> PyListRef { + fn get_referents( + objs: PosArgs, + vm: &VirtualMachine, + ) -> PyResult { + vm.audit("gc.get_referents", || { + (vm.ctx.new_tuple(objs.as_ref().to_vec()),) + })?; let mut result = Vec::new(); for obj in objs.iter() { @@ -174,13 +230,26 @@ mod gc { result.extend(obj.gc_get_referents()); } - vm.ctx.new_list(result) + Ok(vm.ctx.new_list(result)) } #[pyfunction] - fn get_referrers(objs: PosArgs, vm: &VirtualMachine) -> PyListRef { + fn get_referrers( + objs: PosArgs, + vm: &VirtualMachine, + ) -> PyResult { use std::collections::HashSet; + // CPython excludes its varargs tuple from the referrer scan. Build and + // retain that tuple only when an audit hook actually needs it. + let mut audit_objects: Option = None; + vm.audit("gc.get_referrers", || { + let tuple = vm.ctx.new_tuple(objs.as_ref().to_vec()); + audit_objects = Some(tuple.clone()); + (tuple,) + })?; + let audit_objects_id = audit_objects.as_ref().map(|tuple| tuple.get_id()); + // Build a set of target object pointers for fast lookup let targets: HashSet = objs .iter() @@ -208,7 +277,7 @@ mod gc { let mut result = Vec::new(); // Scan all tracked objects across all generations - let all_objects = vm.state.gc.get_objects(None); + let all_objects = vm.state.gc.get_objects_for_introspection(None); for obj in all_objects { let obj_ptr = obj.as_ref() as *const crate::PyObject as usize; // Generator/coroutine frames are embedded in their owner, so @@ -221,7 +290,7 @@ mod gc { } continue; } - if stack_frames.contains(&obj_ptr) { + if Some(obj_ptr) == audit_objects_id || stack_frames.contains(&obj_ptr) { continue; } if refers_to_target(obj.as_ref()) { @@ -229,7 +298,7 @@ mod gc { } } - vm.ctx.new_list(result) + Ok(vm.ctx.new_list(result)) } #[pyfunction] @@ -278,8 +347,7 @@ mod gc { result: &gc_state::CollectResult, ) { let callbacks_list = &vm.state.gc.py_callbacks; - let callbacks: Vec = callbacks_list.borrow_vec().to_vec(); - if callbacks.is_empty() { + if callbacks_list.borrow_vec().is_empty() { return; } @@ -295,8 +363,19 @@ mod gc { let _ = info.set_item("candidates", vm.ctx.new_int(result.candidates).into(), vm); let _ = info.set_item("duration", vm.ctx.new_float(result.duration).into(), vm); - for callback in callbacks { - let _ = callback.call((phase_str.clone(), info.clone()), vm); + let mut index = 0; + loop { + let Some(callback) = callbacks_list.borrow_vec().get(index).cloned() else { + break; + }; + index += 1; + if let Err(error) = callback.call((phase_str.clone(), info.clone()), vm) { + let message = callback + .repr(vm) + .ok() + .map(|repr| format!("Exception ignored while calling GC callback {repr}")); + vm.run_unraisable(error, message, vm.ctx.none()); + } } } } diff --git a/crates/vm/src/stdlib/itertools.rs b/crates/vm/src/stdlib/itertools.rs index 371e3ee68c2..c3f085673fe 100644 --- a/crates/vm/src/stdlib/itertools.rs +++ b/crates/vm/src/stdlib/itertools.rs @@ -3,28 +3,23 @@ pub(crate) use decl::module_def; #[pymodule(name = "itertools")] mod decl { use crate::{ - AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, PyWeakRef, TryFromObject, - VirtualMachine, - builtins::{ - PyGenericAlias, PyInt, PyIntRef, PyList, PyTuple, PyTupleRef, PyType, PyTypeRef, int, - }, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, PyWeakRef, + TryFromBorrowedObject, TryFromObject, VirtualMachine, + builtins::{PyGenericAlias, PyInt, PyList, PyTuple, PyTupleRef, PyType, PyTypeRef}, class::PyClassDef, - common::lock::{PyMutex, PyRwLock, PyRwLockWriteGuard}, + common::lock::{PyMutex, PyRwLock}, convert::ToPyObject, - function::{FuncArgs, NameIterables, PosArgs}, + function::{FuncArgs, NameIterables, OptionalArg, PosArgs}, protocol::{PyIter, PyIterReturn, PyNumber}, raise_if_stop, - stdlib::sys, types::{Constructor, IterNext, Iterable, Representable, SelfIter}, }; use core::sync::atomic::{AtomicBool, Ordering}; use crossbeam_utils::atomic::AtomicCell; - use malachite_bigint::BigInt; - use num_traits::One; use rustpython_common::wtf8::Wtf8Buf; use alloc::fmt; - use num_traits::{Signed, ToPrimitive}; + use num_traits::{One, ToPrimitive}; #[pyattr] #[pyclass(name = "chain", traverse)] @@ -83,8 +78,8 @@ mod decl { impl Constructor for PyItertoolsChain { type Args = PosArgs; - fn py_new(_cls: &Py, _args: Self::Args, vm: &VirtualMachine) -> PyResult { - Err(vm.new_type_error("use slot_new")) + fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { + unimplemented!("use slot_new") } } @@ -103,17 +98,17 @@ mod decl { break Ok(PyIterReturn::Return(ok)); } Ok(PyIterReturn::StopIteration(_)) => { - *zelf.active.write() = None; + let _previous = zelf.active.write().take(); } Err(err) => { - break Err(err); + return Err(err); } } } else { match source.next(vm) { Ok(PyIterReturn::Return(ok)) => match PyIter::try_from_object(vm, ok) { Ok(iter) => { - *zelf.active.write() = Some(iter); + let _previous = zelf.active.write().replace(iter); } Err(err) => { break Err(err); @@ -154,9 +149,9 @@ mod decl { #[derive(FromArgs)] struct CompressNewArgs { #[pyarg(any)] - data: PyIter, + data: PyObjectRef, #[pyarg(any)] - selectors: PyIter, + selectors: PyObjectRef, } impl Constructor for PyItertoolsCompress { @@ -165,9 +160,14 @@ mod decl { fn py_new( _cls: &Py, Self::Args { data, selectors }: Self::Args, - _vm: &VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { - Ok(Self { data, selectors }) + let data_iter = data.get_iter(vm)?; + let selectors_iter = selectors.get_iter(vm)?; + Ok(Self { + data: data_iter, + selectors: selectors_iter, + }) } } @@ -179,12 +179,13 @@ mod decl { impl IterNext for PyItertoolsCompress { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { loop { + // Match zip(data, selectors): consume data before the selector, + // and stop as soon as either input is exhausted. + let data_obj = raise_if_stop!(zelf.data.next(vm)?); let sel_obj = raise_if_stop!(zelf.selectors.next(vm)?); - let verdict = sel_obj.try_to_bool(vm)?; - let data_obj = zelf.data.next(vm)?; - - if verdict { - return Ok(data_obj); + let selected = sel_obj.try_to_bool(vm)?; + if selected { + return Ok(PyIterReturn::Return(data_obj)); } } } @@ -219,6 +220,19 @@ mod decl { return Err(vm.new_type_error("a number is required")); } + let step_is_one = step + .downcast_ref::() + .is_some_and(|step| step.as_bigint().is_one()); + let (start, step) = match start + .downcast_ref::() + .and_then(|start| start.as_bigint().to_isize()) + { + Some(value) if step_is_one => { + (vm.ctx.new_int(value).into(), vm.ctx.new_int(1).into()) + } + _ => (start, step), + }; + Ok(Self { cur: PyRwLock::new(start), step, @@ -226,7 +240,7 @@ mod decl { } } - #[pyclass(with(IterNext, Iterable, Constructor, Representable))] + #[pyclass(with(IterNext, Iterable, Constructor, Representable), flags(BASETYPE))] impl PyItertoolsCount {} impl SelfIter for PyItertoolsCount {} @@ -263,12 +277,17 @@ mod decl { #[pyclass(name = "cycle", traverse)] #[derive(Debug, PyPayload)] struct PyItertoolsCycle { - iter: PyIter, - saved: PyRwLock>, + state: PyRwLock, #[pytraverse(skip)] index: AtomicCell, } + #[derive(Debug, Traverse)] + struct CycleState { + iter: Option, + saved: Vec, + } + impl Constructor for PyItertoolsCycle { type Args = IterablePosArg; const DROP_KWARGS_WHEN_INIT_OVERRIDDEN: bool = true; @@ -276,8 +295,10 @@ mod decl { fn py_new(_cls: &Py, args: Self::Args, _vm: &VirtualMachine) -> PyResult { let iter = args.iterable; Ok(Self { - iter, - saved: PyRwLock::new(Vec::new()), + state: PyRwLock::new(CycleState { + iter: Some(iter), + saved: Vec::new(), + }), index: AtomicCell::new(0), }) } @@ -290,27 +311,55 @@ mod decl { impl IterNext for PyItertoolsCycle { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - let item = if let PyIterReturn::Return(item) = zelf.iter.next(vm)? { - zelf.saved.write().push(item.clone()); - item - } else { - let saved = zelf.saved.read(); - if saved.is_empty() { - return Ok(PyIterReturn::StopIteration(None)); + let iterator = zelf.state.read().iter.clone(); + let restarting = if let Some(iterator) = iterator { + let next = iterator.next(vm); + drop(iterator); + match next? { + PyIterReturn::Return(item) => { + zelf.state.write().saved.push(item.clone()); + return Ok(PyIterReturn::Return(item)); + } + PyIterReturn::StopIteration(value) => { + drop(value); + let _previous = { + let mut state = zelf.state.write(); + zelf.index.store(0); + state.iter.take() + }; + // Publish replay mode before releasing the source. Its + // finalizer may advance this cycle, but this call still + // starts replay at its own index zero. + true + } } + } else { + false + }; - // Advance and wrap in a single atomic step. A separate - // fetch_add followed by a reset lets a second thread observe - // an index past the end of `saved`. - let last_index = match zelf.index.fetch_update(|index| { - let next = index + 1; - Some(if next < saved.len() { next } else { 0 }) - }) { - Ok(index) | Err(index) => index, - }; + let state = zelf.state.read(); + let saved = &state.saved; + if saved.is_empty() { + return Ok(PyIterReturn::StopIteration(None)); + } - saved[last_index].clone() + // Advance and wrap in a single atomic step. A separate + // fetch_add followed by a reset lets a second thread observe + // an index past the end of `saved`. + let last_index = match zelf.index.fetch_update(|index| { + let index = if restarting { 0 } else { index }; + let next = index + 1; + Some(if next < saved.len() { next } else { 0 }) + }) { + Ok(index) | Err(index) => { + if restarting { + 0 + } else { + index + } + } }; + let item = saved[last_index].clone(); Ok(PyIterReturn::Return(item)) } @@ -329,7 +378,7 @@ mod decl { struct PyRepeatNewArgs { object: PyObjectRef, #[pyarg(any, optional)] - times: Option, + times: OptionalArg, } impl Constructor for PyItertoolsRepeat { @@ -341,13 +390,12 @@ mod decl { vm: &VirtualMachine, ) -> PyResult { let times = match times { - Some(obj) => { - let int = obj.try_index(vm)?; - let val: isize = int.try_to_primitive(vm)?; + OptionalArg::Present(obj) => { + let val = index_to_ssize(&obj, vm)?; // times always >= 0. Some(PyRwLock::new(val.to_usize().unwrap_or(0))) } - None => None, + OptionalArg::Missing => None, }; Ok(Self { object, times }) } @@ -436,7 +484,17 @@ mod decl { match obj { PyIterReturn::Return(obj) => { let args: Vec<_> = obj.try_to_value(vm)?; - PyIterReturn::from_pyresult(function.call(args, vm), vm) + let original = if obj.class().is(vm.ctx.types.tuple_type) { + Some(obj) + } else { + // Conversion consumes a non-exact tuple before the + // function runs, including any reentrant finalizer. + drop(obj); + None + }; + let result = function.call(args, vm); + drop(original); + PyIterReturn::from_pyresult(result, vm) } PyIterReturn::StopIteration(v) => Ok(PyIterReturn::StopIteration(v)), } @@ -496,11 +554,13 @@ mod decl { let obj = raise_if_stop!(zelf.iterable.next(vm)?); let predicate = &zelf.predicate; - let verdict = predicate.call((obj.clone(),), vm)?; - let verdict = verdict.try_to_bool(vm)?; + let pred_value = predicate.call((obj.clone(),), vm)?; + let verdict = pred_value.try_to_bool(vm)?; + drop(pred_value); if verdict { Ok(PyIterReturn::Return(obj)) } else { + drop(obj); zelf.stop_flag.store(true); Ok(PyIterReturn::StopIteration(None)) } @@ -555,17 +615,19 @@ mod decl { let predicate = &zelf.predicate; let iterable = &zelf.iterable; - if !zelf.start_flag.load() { - loop { - let obj = raise_if_stop!(iterable.next(vm)?); - let pred_value = predicate.call((obj.clone(),), vm)?; - if !pred_value.try_to_bool(vm)? { - zelf.start_flag.store(true); - return Ok(PyIterReturn::Return(obj)); - } + loop { + let obj = raise_if_stop!(iterable.next(vm)?); + if zelf.start_flag.load() { + return Ok(PyIterReturn::Return(obj)); + } + let pred_value = predicate.call((obj.clone(),), vm)?; + let verdict = pred_value.try_to_bool(vm)?; + drop(pred_value); + if !verdict { + zelf.start_flag.store(true); + return Ok(PyIterReturn::Return(obj)); } } - iterable.next(vm) } } @@ -589,11 +651,8 @@ mod decl { } impl GroupByState { - fn is_current(&self, grouper: &Py) -> bool { - self.grouper - .as_ref() - .and_then(|g| g.upgrade()) - .is_some_and(|current_grouper| grouper.is(¤t_grouper)) + fn current_grouper(&self) -> Option> { + self.grouper.as_ref().and_then(|g| g.upgrade()) } } @@ -619,7 +678,7 @@ mod decl { #[derive(FromArgs)] struct GroupByArgs { #[pyarg(any)] - iterable: PyIter, + iterable: PyObjectRef, #[pyarg(any, optional)] key: Option, } @@ -630,17 +689,18 @@ mod decl { fn py_new( _cls: &Py, Self::Args { iterable, key }: Self::Args, - _vm: &VirtualMachine, + vm: &VirtualMachine, ) -> PyResult { + let iterator = iterable.get_iter(vm)?; Ok(Self { - iterable, + iterable: iterator, key_func: key, state: PyMutex::new(GroupByState::default()), }) } } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsGroupBy { pub(super) fn advance( &self, @@ -680,18 +740,35 @@ mod decl { } } let (value, key) = raise_if_stop!(zelf.advance(vm)?); - let mut state = zelf.state.lock(); - state.current_value = Some(value); - state.current_key = Some(key); + let (_old_value, _old_key) = { + let mut state = zelf.state.lock(); + ( + state.current_value.replace(value), + state.current_key.replace(key), + ) + }; } - let mut state = zelf.state.lock(); - let currkey = state.current_key.clone().unwrap(); - state.tgtkey = Some(currkey.clone()); + let old_tgtkey = { + let mut state = zelf.state.lock(); + let Some(currkey) = state.current_key.clone() else { + return Ok(PyIterReturn::StopIteration(None)); + }; + state.tgtkey.replace(currkey) + }; + drop(old_tgtkey); + let mut state = zelf.state.lock(); + // A target-key finalizer may have reentered and consumed the current item. + let Some(currkey) = state.current_key.clone() else { + return Ok(PyIterReturn::StopIteration(None)); + }; + let Some(tgtkey) = state.tgtkey.clone() else { + return Ok(PyIterReturn::StopIteration(None)); + }; let grouper = PyItertoolsGrouper { groupby: zelf.to_owned(), - tgtkey: currkey.clone(), + tgtkey, } .into_ref(&vm.ctx); @@ -708,42 +785,89 @@ mod decl { tgtkey: PyObjectRef, } - #[pyclass(with(IterNext, Iterable), flags(HAS_WEAKREF))] + #[derive(FromArgs)] + struct GrouperArgs { + #[pyarg(positional)] + parent: PyRef, + #[pyarg(positional)] + tgtkey: PyObjectRef, + } + + impl Constructor for PyItertoolsGrouper { + type Args = GrouperArgs; + + // The new grouper becomes the parent's current grouper. + fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let args: Self::Args = args.bind_for(vm, crate::function::Callee::of::(vm))?; + let grouper = Self::py_new(&cls, args, vm)?.into_ref_with_type(vm, cls)?; + grouper.groupby.state.lock().grouper = Some(grouper.downgrade(None, vm)?); + Ok(grouper.into()) + } + + fn py_new( + _cls: &Py, + Self::Args { parent, tgtkey }: Self::Args, + _vm: &VirtualMachine, + ) -> PyResult { + Ok(Self { + groupby: parent, + tgtkey, + }) + } + } + + #[pyclass(with(Constructor, IterNext, Iterable), flags(HAS_WEAKREF))] impl PyItertoolsGrouper {} impl SelfIter for PyItertoolsGrouper {} impl IterNext for PyItertoolsGrouper { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - if !zelf.groupby.state.lock().is_current(zelf) { + let current = zelf.groupby.state.lock().current_grouper(); + if !current.as_ref().is_some_and(|g| zelf.is(g)) { return Ok(PyIterReturn::StopIteration(None)); } + drop(current); if zelf.groupby.state.lock().current_value.is_none() { let (value, key) = raise_if_stop!(zelf.groupby.advance(vm)?); - let mut state = zelf.groupby.state.lock(); - state.current_value = Some(value); - state.current_key = Some(key); + let (_old_value, _old_key) = { + let mut state = zelf.groupby.state.lock(); + ( + state.current_value.replace(value), + state.current_key.replace(key), + ) + }; } + let current; let currkey = { let state = zelf.groupby.state.lock(); - if !state.is_current(zelf) { + current = state.current_grouper(); + if !current.as_ref().is_some_and(|g| zelf.is(g)) { return Ok(PyIterReturn::StopIteration(None)); } - state.current_key.clone().unwrap() + let Some(currkey) = state.current_key.clone() else { + return Ok(PyIterReturn::StopIteration(None)); + }; + currkey }; + drop(current); let tgtkey = zelf.tgtkey.clone(); if !vm.bool_eq(&tgtkey, &currkey)? { return Ok(PyIterReturn::StopIteration(None)); } - let mut state = zelf.groupby.state.lock(); - if !state.is_current(zelf) { - return Ok(PyIterReturn::StopIteration(None)); - } - let value = state.current_value.take(); - state.current_key = None; + let current; + let (value, _old_key) = { + let mut state = zelf.groupby.state.lock(); + current = state.current_grouper(); + if !current.as_ref().is_some_and(|g| zelf.is(g)) { + return Ok(PyIterReturn::StopIteration(None)); + } + (state.current_value.take(), state.current_key.take()) + }; + drop(current); match value { Some(v) => Ok(PyIterReturn::Return(v)), None => Ok(PyIterReturn::StopIteration(None)), @@ -766,86 +890,65 @@ mod decl { step: usize, } - fn pyobject_to_opt_usize( - obj: &PyObject, - name: &'static str, - vm: &VirtualMachine, - ) -> PyResult { - let value = match obj.try_index(vm) { - Ok(i) => int::get_value(i.as_object()).to_usize(), - Err(e) - if e.fast_isinstance(vm.ctx.exceptions.type_error) - || e.fast_isinstance(vm.ctx.exceptions.overflow_error) => - { - None - } - Err(e) => return Err(e), - }; - if let Some(value) = value - && value <= sys::MAXSIZE as usize - { - return Ok(value); - } - Err(vm.new_value_error(format!( - "{name} argument for islice() must be None or an integer: 0 <= x <= sys.maxsize." - ))) - } - #[pyclass(with(IterNext, Iterable), flags(BASETYPE))] impl PyItertoolsIslice { #[pyslot] fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { let args = crate::types::drop_kwargs_if_init_overridden(&cls, Self::class(&vm.ctx), args); - let (iter, start, stop, step) = match args.args.len() { - 0 | 1 => { - return Err(vm.new_arity_type_error(Self::NAME, 2..=4, args.args.len())); + let (iter, a1, a2, a3): ( + PyObjectRef, + PyObjectRef, + OptionalArg, + OptionalArg, + ) = args.bind_for(vm, Self::NAME)?; + + // CPython clears index conversion errors and reports the appropriate + // islice ValueError after converting arguments in this order. + let to_ssize = |obj: &PyObject| isize::try_from_borrowed_object(vm, obj).unwrap_or(-1); + let mut start = 0; + let mut stop = -1; + if let OptionalArg::Present(a2) = &a2 { + if !vm.is_none(&a1) { + start = to_ssize(&a1); } - 2 => { - let (iter, stop): (PyObjectRef, PyObjectRef) = args.bind_for(vm, Self::NAME)?; - (iter, 0usize, stop, 1usize) + if !vm.is_none(a2) { + stop = to_ssize(a2); + if stop == -1 { + return Err(vm.new_value_error( + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.", + )); + } } - _ => { - let (iter, start, stop, step) = if args.args.len() == 3 { - let (iter, start, stop): (PyObjectRef, PyObjectRef, PyObjectRef) = - args.bind_for(vm, Self::NAME)?; - (iter, start, stop, 1usize) - } else { - let (iter, start, stop, step): ( - PyObjectRef, - PyObjectRef, - PyObjectRef, - PyObjectRef, - ) = args.bind_for(vm, Self::NAME)?; - - let step = if !vm.is_none(&step) { - let step = pyobject_to_opt_usize(&step, "Step", vm)?; - if step == 0 { - return Err(vm.new_value_error( - "Step for islice() must be a positive integer or None.", - )); - } - step - } else { - 1usize - }; - (iter, start, stop, step) - }; - let start = if !vm.is_none(&start) { - pyobject_to_opt_usize(&start, "Start", vm)? - } else { - 0usize - }; - - (iter, start, stop, step) + } else if !vm.is_none(&a1) { + stop = to_ssize(&a1); + if stop == -1 { + return Err(vm.new_value_error( + "Stop argument for islice() must be None or an integer: 0 <= x <= sys.maxsize.", + )); } - }; + } + if start < 0 || stop < -1 { + return Err(vm.new_value_error( + "Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize.", + )); + } - let stop = if !vm.is_none(&stop) { - Some(pyobject_to_opt_usize(&stop, "Stop", vm)?) + let step = if let OptionalArg::Present(a3) = &a3 + && !vm.is_none(a3) + { + to_ssize(a3) } else { - None + 1 }; + if step < 1 { + return Err( + vm.new_value_error("Step for islice() must be a positive integer or None.") + ); + } + let start = start as usize; + let stop = (stop >= 0).then_some(stop as usize); + let step = step as usize; let iter = PyIter::try_from_object(vm, iter)?; @@ -861,6 +964,20 @@ mod decl { } } + impl PyItertoolsIslice { + fn clear_iterable(&self) { + let _previous = self.iterable.lock().take(); + } + + fn next_source(&self, iterable: &PyIter, vm: &VirtualMachine) -> PyResult { + let result = iterable.next(vm); + if !matches!(&result, Ok(PyIterReturn::Return(_))) { + self.clear_iterable(); + } + result + } + } + impl SelfIter for PyItertoolsIslice {} impl IterNext for PyItertoolsIslice { @@ -871,27 +988,15 @@ mod decl { let stop = zelf.stop.unwrap_or(usize::MAX); while zelf.cur.load() < zelf.next.load() { - raise_if_stop!({ - let result = iterable.next(vm)?; - if matches!(result, PyIterReturn::StopIteration(_)) { - *zelf.iterable.lock() = None; - } - result - }); + raise_if_stop!(zelf.next_source(&iterable, vm)?); zelf.cur.fetch_add(1); } if zelf.cur.load() >= stop { - *zelf.iterable.lock() = None; + zelf.clear_iterable(); return Ok(PyIterReturn::StopIteration(None)); } - let obj = raise_if_stop!({ - let result = iterable.next(vm)?; - if matches!(result, PyIterReturn::StopIteration(_)) { - *zelf.iterable.lock() = None; - } - result - }); + let obj = raise_if_stop!(zelf.next_source(&iterable, vm)?); zelf.cur.fetch_add(1); let oldnext = zelf.next.load(); let (newnext, ovf) = oldnext.overflowing_add(zelf.step); @@ -951,7 +1056,8 @@ mod decl { predicate.call((obj.clone(),), vm)? }; - if !pred_value.try_to_bool(vm)? { + let verdict = pred_value.try_to_bool(vm)?; + if !verdict { return Ok(PyIterReturn::Return(obj)); } } @@ -964,14 +1070,16 @@ mod decl { struct PyItertoolsAccumulate { iterable: PyIter, bin_op: Option, - initial: Option, + initial: PyRwLock>, + #[pytraverse(skip)] + has_initial: bool, acc_value: PyRwLock>, } #[derive(FromArgs)] struct AccumulateArgs { #[pyarg(any)] - iterable: PyIter, + iterable: PyObjectRef, #[pyarg(any, optional)] func: Option, #[pyarg(named, optional)] @@ -981,17 +1089,19 @@ mod decl { impl Constructor for PyItertoolsAccumulate { type Args = AccumulateArgs; - fn py_new(_cls: &Py, args: AccumulateArgs, _vm: &VirtualMachine) -> PyResult { + fn py_new(_cls: &Py, args: AccumulateArgs, vm: &VirtualMachine) -> PyResult { + let iterator = args.iterable.get_iter(vm)?; Ok(Self { - iterable: args.iterable, + iterable: iterator, bin_op: args.func, - initial: args.initial, + has_initial: args.initial.is_some(), + initial: PyRwLock::new(args.initial), acc_value: PyRwLock::new(None), }) } } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsAccumulate {} impl SelfIter for PyItertoolsAccumulate {} @@ -1000,22 +1110,33 @@ mod decl { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { let iterable = &zelf.iterable; - let acc_value = zelf.acc_value.read().clone(); + if zelf.has_initial { + let mut acc = zelf.acc_value.write(); + if acc.is_none() { + let initial = zelf.initial.write().take(); + if let Some(initial) = initial { + *acc = Some(initial.clone()); + return Ok(PyIterReturn::Return(initial)); + } + } + } + let obj = raise_if_stop!(iterable.next(vm)?); + // The source callback can reenter and replace the running total. + let acc_value = zelf.acc_value.read().clone(); let next_acc_value = match acc_value { - None => match &zelf.initial { - None => raise_if_stop!(iterable.next(vm)?), - Some(obj) => obj.clone(), - }, - Some(value) => { - let obj = raise_if_stop!(iterable.next(vm)?); - match &zelf.bin_op { - None => vm._add(&value, &obj)?, - Some(op) => op.call((value, obj), vm)?, + None => obj, + Some(value) => match &zelf.bin_op { + None => { + let result = vm._add(&value, &obj); + drop(value); + drop(obj); + result? } - } + Some(op) => op.call((value, obj), vm)?, + }, }; - *zelf.acc_value.write() = Some(next_acc_value.clone()); + let _previous = zelf.acc_value.write().replace(next_acc_value.clone()); Ok(PyIterReturn::Return(next_acc_value)) } @@ -1027,47 +1148,30 @@ mod decl { struct PyItertoolsTeeData { iterable: PyIter, values: PyMutex>, + next: PyMutex>>, #[pytraverse(skip)] running: AtomicBool, } #[pyclass(flags(DISALLOW_INSTANTIATION))] impl PyItertoolsTeeData { + const BLOCK_SIZE: usize = 64; + fn new(iterable: PyIter, vm: &VirtualMachine) -> PyRef { Self { iterable, - values: PyMutex::new(vec![]), + values: PyMutex::new(Vec::with_capacity(Self::BLOCK_SIZE)), + next: PyMutex::new(None), running: AtomicBool::new(false), } .into_ref(&vm.ctx) } - fn get_item(&self, vm: &VirtualMachine, index: usize) -> PyResult { - // Return cached value if available - { - let Some(values) = self.values.try_lock() else { - return Err(vm.new_runtime_error("cannot re-enter the tee iterator")); - }; - if index < values.len() { - return Ok(PyIterReturn::Return(values[index].clone())); - } - } - // Prevent concurrent/reentrant calls to iterable.next(). The claim - // covers caching the value as well: released any earlier, a second - // tee at the same index fetches a value of its own and one of the - // two is dropped without ever reaching a caller. - if self.running.swap(true, Ordering::Acquire) { - return Err(vm.new_runtime_error("cannot re-enter the tee iterator")); - } - scopeguard::defer! { self.running.store(false, Ordering::Release) } - let obj = raise_if_stop!(self.iterable.next(vm)?); - let Some(mut values) = self.values.try_lock() else { - return Err(vm.new_runtime_error("cannot re-enter the tee iterator")); - }; - if values.len() == index { - values.push(obj); - } - Ok(PyIterReturn::Return(values[index].clone())) + fn next_block(&self, vm: &VirtualMachine) -> PyRef { + self.next + .lock() + .get_or_insert_with(|| Self::new(self.iterable.clone(), vm)) + .clone() } } @@ -1075,25 +1179,33 @@ mod decl { #[pyclass(name = "_tee", traverse)] #[derive(Debug, PyPayload)] struct PyItertoolsTee { - tee_data: PyRef, + tee_data: PyMutex>, #[pytraverse(skip)] index: AtomicCell, #[pytraverse(skip)] advancing: AtomicBool, } + #[derive(FromArgs)] + struct TeeNewArgs { + #[pyarg(positional)] + iterable: PyObjectRef, + } + impl Constructor for PyItertoolsTee { - type Args = IterablePosArg; + type Args = TeeNewArgs; fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let iterator = args.iterable; + // Keep the source alive until an existing tee's position is copied: + // its finalizer can advance the iterator returned by __iter__. + let iterator = args.iterable.get_iter(vm)?; // An iterator that is already a tee shares its buffer rather than // getting one of its own. if let Some(tee) = iterator.as_object().downcast_ref::() { return Ok(tee.__copy__()); } Ok(Self { - tee_data: PyItertoolsTeeData::new(iterator, vm), + tee_data: PyMutex::new(PyItertoolsTeeData::new(iterator, vm)), index: AtomicCell::new(0), advancing: AtomicBool::new(false), }) @@ -1102,12 +1214,14 @@ mod decl { impl PyItertoolsTee { fn from_iter(iterator: PyIter, vm: &VirtualMachine) -> PyResult { + // An iterator is asked for its iterator again, which validates its __iter__. + let iterator = iterator.get_iter(vm)?; let class = Self::class(&vm.ctx); if iterator.class().is(class) { return vm.call_special_method(&iterator, identifier!(vm, __copy__), ()); } Ok(Self { - tee_data: PyItertoolsTeeData::new(iterator, vm), + tee_data: PyMutex::new(PyItertoolsTeeData::new(iterator, vm)), index: AtomicCell::new(0), advancing: AtomicBool::new(false), } @@ -1120,8 +1234,11 @@ mod decl { impl Py { #[pymethod] fn __copy__(&self) -> PyItertoolsTee { + // A block transition resets the index under this lock, so the pair + // is a consistent snapshot even while another thread advances us. + let data = self.tee_data.lock(); PyItertoolsTee { - tee_data: self.tee_data.clone(), + tee_data: PyMutex::new(data.clone()), index: AtomicCell::new(self.index.load()), advancing: AtomicBool::new(false), } @@ -1131,30 +1248,32 @@ mod decl { #[derive(FromArgs)] struct TeeArgs { #[pyarg(positional)] - iterable: PyIter, - #[pyarg(positional, default = 2)] - n: isize, + iterable: PyObjectRef, + #[pyarg(positional, optional, py_default = "2")] + n: OptionalArg, } #[pyfunction] fn tee(args: TeeArgs, vm: &VirtualMachine) -> PyResult { let TeeArgs { iterable, n } = args; - if n < 0 { - return Err(vm.new_value_error("n must be >= 0")); - } - let n = n as usize; - - // Only an iterator that cannot copy itself needs a tee to buffer it. - let copyable = if iterable.class().has_attr(identifier!(vm, __copy__)) { - iterable.into() - } else { - PyItertoolsTee::from_iter(iterable, vm)? + let n_value = match &n { + OptionalArg::Present(value) => index_to_ssize(value, vm)?, + OptionalArg::Missing => 2, }; + if n_value < 0 { + return Err(vm.new_value_error("n cannot be negative")); + } + let n = n_value as usize; let mut tee_vec: Vec = Vec::new(); tee_vec .try_reserve_exact(n) .map_err(|_| vm.no_memory_error())?; + if n == 0 { + return Ok(vm.ctx.empty_tuple.clone()); + } + + let copyable = PyItertoolsTee::from_iter(iterable.get_iter(vm)?, vm)?; for _ in 0..n { tee_vec.push(vm.call_special_method(©able, identifier!(vm, __copy__), ())?); } @@ -1164,15 +1283,65 @@ mod decl { impl SelfIter for PyItertoolsTee {} impl IterNext for PyItertoolsTee { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let mut current = zelf.tee_data.lock(); // Reading the index and moving it on is one step: two callers that // read the same index hand out the same value twice and leave the // buffer to be filled out of order. - if zelf.advancing.swap(true, Ordering::Acquire) { + // The block lock serializes claims; an atomic exchange is not needed. + if zelf.advancing.load(Ordering::Acquire) { + drop(current); return Err(vm.new_runtime_error("cannot re-enter the tee iterator")); } + zelf.advancing.store(true, Ordering::Relaxed); scopeguard::defer! { zelf.advancing.store(false, Ordering::Release) } + if zelf.index.load() == PyItertoolsTeeData::BLOCK_SIZE { + let data = current.clone(); + drop(current); + let next = data.next_block(vm); + current = zelf.tee_data.lock(); + let previous = core::mem::replace(&mut *current, next); + zelf.index.store(0); + drop(current); + // Releasing a consumed block may run item finalizers. No cursor + // or buffer lock may be held when the last owner lets it go. + drop(data); + drop(previous); + current = zelf.tee_data.lock(); + } + + // Cached reads neither call Python nor release the block, so they + // can update the cursor without cloning its data reference. let index = zelf.index.load(); - let value = raise_if_stop!(zelf.tee_data.get_item(vm, index)?); + let cached = { + let values = current.values.lock(); + if let Some(value) = values.get(index) { + Some(value.clone()) + } else { + // Claim the source while the cache is locked: another tee + // cannot fill this slot between the check and the claim. + if current.running.load(Ordering::Acquire) { + drop(values); + drop(current); + return Err(vm.new_runtime_error("cannot re-enter the tee iterator")); + } + current.running.store(true, Ordering::Relaxed); + None + } + }; + if let Some(value) = cached { + zelf.index.store(index + 1); + return Ok(PyIterReturn::Return(value)); + } + + let data = current.clone(); + drop(current); + // Prevent concurrent/reentrant calls to iterable.next(). The claim + // covers caching the value as well: released any earlier, a second + // tee at the same index fetches a value of its own and one of the + // two is dropped without ever reaching a caller. + scopeguard::defer! { data.running.store(false, Ordering::Release) } + let value = raise_if_stop!(data.iterable.next(vm)?); + data.values.lock().push(value.clone()); zelf.index.store(index + 1); Ok(PyIterReturn::Return(value)) } @@ -1182,12 +1351,10 @@ mod decl { #[pyclass(name = "product", traverse)] #[derive(Debug, PyPayload)] struct PyItertoolsProduct { - pools: Vec>, + pools: Vec, #[pytraverse(skip)] idxs: PyRwLock>, #[pytraverse(skip)] - cur: AtomicCell, - #[pytraverse(skip)] stop: AtomicCell, } @@ -1222,12 +1389,19 @@ mod decl { .filter(|n| *n <= isize::MAX as usize / size_of::()) .ok_or_else(|| vm.new_overflow_error("repeat argument too large"))?; - let mut single: Vec> = Vec::new(); - for arg in iterables.iter() { - single.push(arg.try_to_value(vm)?); + let mut single = Vec::new(); + if repeat != 0 { + for arg in iterables.iter() { + let pool = if let Some(tuple) = arg.downcast_ref_if_exact::(vm) { + tuple.to_owned() + } else { + PyTuple::new_ref(arg.try_to_value(vm)?, &vm.ctx) + }; + single.push(pool); + } } - let mut pools: Vec> = Vec::new(); + let mut pools: Vec = Vec::new(); pools .try_reserve_exact(npools) .map_err(|_| vm.no_memory_error())?; @@ -1242,46 +1416,34 @@ mod decl { .map_err(|_| vm.no_memory_error())?; idxs.resize(npools, 0); - let l = pools.len(); + let empty = pools.iter().any(|pool| pool.is_empty()); Ok(Self { pools, idxs: PyRwLock::new(idxs), - cur: AtomicCell::new(l.wrapping_sub(1)), - stop: AtomicCell::new(false), + stop: AtomicCell::new(empty), }) } } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsProduct { - fn update_idxs(&self, mut idxs: PyRwLockWriteGuard<'_, Vec>) { - if idxs.is_empty() { - self.stop.store(true); - return; - } - - let cur = self.cur.load(); - let lst_idx = &self.pools[cur].len() - 1; - - if idxs[cur] == lst_idx { - if cur == 0 { - self.stop.store(true); + fn update_idxs(&self, idxs: &mut [usize]) { + for (index, pool) in idxs.iter_mut().zip(&self.pools).rev() { + *index += 1; + if *index < pool.len() { return; } - idxs[cur] = 0; - self.cur.fetch_sub(1); - self.update_idxs(idxs); - } else { - idxs[cur] += 1; - self.cur.store(idxs.len() - 1); + *index = 0; } + self.stop.store(true); } } impl SelfIter for PyItertoolsProduct {} impl IterNext for PyItertoolsProduct { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + let mut idxs = zelf.idxs.write(); // stop signal if zelf.stop.load() { return Ok(PyIterReturn::StopIteration(None)); @@ -1289,13 +1451,6 @@ mod decl { let pools = &zelf.pools; - for p in pools { - if p.is_empty() { - return Ok(PyIterReturn::StopIteration(None)); - } - } - - let idxs = zelf.idxs.write(); let res = vm.ctx.new_tuple( pools .iter() @@ -1304,7 +1459,7 @@ mod decl { .collect(), ); - zelf.update_idxs(idxs); + zelf.update_idxs(&mut idxs); Ok(PyIterReturn::Return(res.into())) } @@ -1329,7 +1484,28 @@ mod decl { #[pyarg(any)] iterable: PyObjectRef, #[pyarg(any)] - r: PyIntRef, + r: PyObjectRef, + } + + fn index_to_ssize(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + let index; + let int = if let Some(int) = obj.downcast_ref::() { + int + } else { + index = obj.try_index(vm)?; + &index + }; + int.as_bigint() + .to_isize() + .ok_or_else(|| vm.new_overflow_error("Python int too large to convert to C ssize_t")) + } + + fn combinations_r(r: &PyObject, vm: &VirtualMachine) -> PyResult { + let value = index_to_ssize(r, vm)?; + if value < 0 { + return Err(vm.new_value_error("r cannot be negative")); + } + Ok(value as usize) } impl Constructor for PyItertoolsCombinations { @@ -1340,16 +1516,9 @@ mod decl { Self::Args { iterable, r }: Self::Args, vm: &VirtualMachine, ) -> PyResult { + let r_value = combinations_r(&r, vm)?; let pool: Vec<_> = iterable.try_to_value(vm)?; - - let r = r.as_bigint(); - if r.is_negative() { - return Err(vm.new_value_error("r must be non-negative")); - } - let r = r.to_isize().ok_or_else(|| { - vm.new_overflow_error("Python int too large to convert to C ssize_t") - })? as usize; - + let r = r_value; let n = pool.len(); let mut indices = Vec::new(); @@ -1368,7 +1537,7 @@ mod decl { } } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsCombinations {} impl SelfIter for PyItertoolsCombinations {} @@ -1453,15 +1622,9 @@ mod decl { Self::Args { iterable, r }: Self::Args, vm: &VirtualMachine, ) -> PyResult { + let r_value = combinations_r(&r, vm)?; let pool: Vec<_> = iterable.try_to_value(vm)?; - let r = r.as_bigint(); - if r.is_negative() { - return Err(vm.new_value_error("r must be non-negative")); - } - let r = r.to_isize().ok_or_else(|| { - vm.new_overflow_error("Python int too large to convert to C ssize_t") - })? as usize; - + let r = r_value; let n = pool.len(); let mut indices = Vec::new(); @@ -1479,7 +1642,7 @@ mod decl { } } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsCombinationsWithReplacement {} impl SelfIter for PyItertoolsCombinationsWithReplacement {} @@ -1567,19 +1730,20 @@ mod decl { let n = pool.len(); // If r is not provided, r == n. If provided, r must be a positive integer, or None. // If None, it behaves the same as if it was not provided. - let r = match r { + let r = match &r { Some(r) => { - let val = r + let value = r .downcast_ref::() .ok_or_else(|| vm.new_type_error("Expected int as r"))? - .as_bigint(); - - if val.is_negative() { + .as_bigint() + .to_isize() + .ok_or_else(|| { + vm.new_overflow_error("Python int too large to convert to C ssize_t") + })?; + if value < 0 { return Err(vm.new_value_error("r must be non-negative")); } - val.to_isize().ok_or_else(|| { - vm.new_overflow_error("Python int too large to convert to C ssize_t") - })? as usize + value as usize } None => n, }; @@ -1595,7 +1759,7 @@ mod decl { } } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsPermutations {} impl SelfIter for PyItertoolsPermutations {} @@ -1687,44 +1851,91 @@ mod decl { ) -> PyResult { let fillvalue = args.fillvalue.unwrap_or_else(|| vm.ctx.none()); let iterators = iterators.into_vec(); + let num_active = iterators.len(); + let mut slots = Vec::new(); + slots + .try_reserve_exact(iterators.len()) + .map_err(|_| vm.no_memory_error())?; + slots.extend(iterators.into_iter().map(Some)); Ok(Self { - iterators, + state: PyMutex::new(ZipLongestState { + iterators: slots, + num_active, + }), fillvalue: PyRwLock::new(fillvalue), }) } } + #[derive(Debug, Traverse)] + struct ZipLongestState { + iterators: Vec>, + #[pytraverse(skip)] + num_active: usize, + } + #[pyattr] #[pyclass(name = "zip_longest", traverse)] #[derive(Debug, PyPayload)] struct PyItertoolsZipLongest { - iterators: Vec, + state: PyMutex, fillvalue: PyRwLock, } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsZipLongest {} impl SelfIter for PyItertoolsZipLongest {} impl IterNext for PyItertoolsZipLongest { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { - if zelf.iterators.is_empty() { - return Ok(PyIterReturn::StopIteration(None)); - } + let len = { + let state = zelf.state.lock(); + if state.num_active == 0 { + return Ok(PyIterReturn::StopIteration(None)); + } + state.iterators.len() + }; let mut result: Vec = Vec::new(); - let mut num_active = zelf.iterators.len(); - - for idx in 0..zelf.iterators.len() { - let next_obj = match zelf.iterators[idx].next(vm)? { - PyIterReturn::Return(obj) => obj, - PyIterReturn::StopIteration(v) => { - num_active -= 1; - if num_active == 0 { - return Ok(PyIterReturn::StopIteration(v)); + for idx in 0..len { + let iterator = zelf.state.lock().iterators[idx].clone(); + let next_obj = if let Some(iterator) = iterator { + let next = iterator.next(vm); + drop(iterator); + match next { + Ok(PyIterReturn::Return(obj)) => obj, + Ok(PyIterReturn::StopIteration(value)) => { + drop(value); + let (terminal, previous) = { + let mut state = zelf.state.lock(); + // A reentrant or competing call may already + // have exhausted this slot or the whole zip. + if state.num_active > 0 && state.iterators[idx].is_some() { + state.num_active -= 1; + } + let terminal = state.num_active == 0; + let previous = if terminal { + None + } else { + state.iterators[idx].take() + }; + (terminal, previous) + }; + if terminal { + // The final exhausted source remains owned, + // unlike exhausted sources in earlier slots. + return Ok(PyIterReturn::StopIteration(None)); + } + drop(previous); + zelf.fillvalue.read().clone() + } + Err(err) => { + zelf.state.lock().num_active = 0; + return Err(err); } - zelf.fillvalue.read().clone() } + } else { + zelf.fillvalue.read().clone() }; result.push(next_obj); } @@ -1736,47 +1947,108 @@ mod decl { #[pyclass(name = "pairwise", traverse)] #[derive(Debug, PyPayload)] struct PyItertoolsPairwise { - iterator: PyIter, - old: PyRwLock>, + state: PyRwLock, + #[pytraverse(skip)] + terminal: AtomicBool, + } + + #[derive(Debug, Traverse)] + struct PairwiseState { + iterator: Option, + old: Option, } impl Constructor for PyItertoolsPairwise { type Args = IterablePosArg; + const DROP_KWARGS_WHEN_INIT_OVERRIDDEN: bool = true; + fn py_new(_cls: &Py, args: Self::Args, _vm: &VirtualMachine) -> PyResult { let iterator = args.iterable; Ok(Self { - iterator, - old: PyRwLock::new(None), + state: PyRwLock::new(PairwiseState { + iterator: Some(iterator), + old: None, + }), + terminal: AtomicBool::new(false), }) } } - #[pyclass(with(IterNext, Iterable, Constructor))] + #[pyclass(with(IterNext, Iterable, Constructor), flags(BASETYPE))] impl PyItertoolsPairwise {} impl SelfIter for PyItertoolsPairwise {} + impl PyItertoolsPairwise { + fn next_item(&self, vm: &VirtualMachine) -> PyResult { + let Some(iterator) = self.state.read().iterator.clone() else { + return Ok(PyIterReturn::StopIteration(None)); + }; + iterator.next(vm) + } + + fn clear_iterator(&self) { + self.terminal.store(true, Ordering::Release); + let _previous = self.state.write().iterator.take(); + } + + fn clear_old(&self) { + let _previous = self.state.write().old.take(); + } + } + impl IterNext for PyItertoolsPairwise { fn next(zelf: &Py, vm: &VirtualMachine) -> PyResult { + if zelf.terminal.load(Ordering::Acquire) { + return Ok(PyIterReturn::StopIteration(None)); + } let old_clone = { - let guard = zelf.old.read(); - guard.clone() + let state = zelf.state.read(); + state.old.clone() }; let old = match old_clone { - None => match zelf.iterator.next(vm)? { - PyIterReturn::Return(obj) => { - // Needed for when we reenter - *zelf.old.write() = Some(obj.clone()); - obj + None => { + let next = zelf.next_item(vm); + let previous = { + let mut state = zelf.state.write(); + match &next { + Ok(PyIterReturn::Return(obj)) => state.old.replace(obj.clone()), + _ => state.old.take(), + } + }; + // The first source callback can publish an old item by + // reentering. Replace it before clearing a failed source. + drop(previous); + match next { + Ok(PyIterReturn::Return(obj)) => { + if zelf.terminal.load(Ordering::Acquire) { + zelf.clear_old(); + return Ok(PyIterReturn::StopIteration(None)); + } + obj + } + result => { + zelf.clear_iterator(); + return result; + } } - PyIterReturn::StopIteration(v) => return Ok(PyIterReturn::StopIteration(v)), - }, + } Some(obj) => obj, }; - let new = raise_if_stop!(zelf.iterator.next(vm)?); - *zelf.old.write() = Some(new.clone()); + let new = match zelf.next_item(vm) { + Ok(PyIterReturn::Return(obj)) => obj, + result => { + // For the second input, release the source before both + // the stored previous item and this call's owned copy. + zelf.clear_iterator(); + zelf.clear_old(); + return result; + } + }; + let previous = zelf.state.write().old.replace(new.clone()); + drop(previous); Ok(PyIterReturn::Return(vm.new_tuple((old, new)).into())) } @@ -1800,9 +2072,9 @@ mod decl { #[pyarg(any)] iterable: PyObjectRef, #[pyarg(any)] - n: PyIntRef, - #[pyarg(named, default)] - strict: bool, + n: PyObjectRef, + #[pyarg(named, optional, py_default = "False")] + strict: Option, } impl Constructor for PyItertoolsBatched { @@ -1817,20 +2089,21 @@ mod decl { }: Self::Args, vm: &VirtualMachine, ) -> PyResult { - let n = n.as_bigint(); - if n.lt(&BigInt::one()) { + let n_value = index_to_ssize(&n, vm)?; + let strict_value = match &strict { + Some(value) => value.try_to_bool(vm)?, + None => false, + }; + if n_value < 1 { return Err(vm.new_value_error("n must be at least one")); } - let n = n - .to_usize() - .ok_or_else(|| vm.new_overflow_error("Python int too large to convert to usize"))?; let iterable = PyIter::try_from_object(vm, iterable)?; Ok(Self { iterable, - n: AtomicCell::new(n), + n: AtomicCell::new(n_value as usize), exhausted: AtomicCell::new(false), - strict: AtomicCell::new(strict), + strict: AtomicCell::new(strict_value), }) } } @@ -1848,14 +2121,21 @@ mod decl { let mut result: Vec = Vec::new(); let n = zelf.n.load(); for _ in 0..n { - match zelf.iterable.next(vm)? { - PyIterReturn::Return(obj) => { + match zelf.iterable.next(vm) { + Ok(PyIterReturn::Return(obj)) => { result.push(obj); } - PyIterReturn::StopIteration(_) => { - zelf.exhausted.store(true); + Ok(PyIterReturn::StopIteration(value)) => { + drop(value); + if result.is_empty() || zelf.strict.load() { + zelf.exhausted.store(true); + } break; } + Err(err) => { + zelf.exhausted.store(true); + return Err(err); + } } } let res_len = result.len(); @@ -1863,6 +2143,7 @@ mod decl { 0 => Ok(PyIterReturn::StopIteration(None)), _ => { if zelf.strict.load() && res_len != n { + drop(result); Err(vm.new_value_error("batched(): incomplete batch")) } else { Ok(PyIterReturn::Return(vm.ctx.new_tuple(result).into())) diff --git a/crates/vm/src/stdlib/marshal.rs b/crates/vm/src/stdlib/marshal.rs index 2624e9c0edd..6055317a9fd 100644 --- a/crates/vm/src/stdlib/marshal.rs +++ b/crates/vm/src/stdlib/marshal.rs @@ -4,22 +4,23 @@ pub(crate) use decl::module_def; #[pymodule(name = "marshal")] mod decl { use crate::builtins::code::{CodeObject, Literal, PyVmBag}; + use crate::builtins::dict::DictIter; use crate::class::StaticType; use crate::common::wtf8::Wtf8; use crate::{ PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{ - PyBaseExceptionRef, PyBool, PyByteArray, PyBytes, PyCode, PyComplex, PyDict, - PyEllipsis, PyFloat, PyFrozenSet, PyInt, PyList, PyMemoryView, PyNone, PySet, - PyStopIteration, PyStr, PyTuple, + PyAnyDict, PyBaseExceptionRef, PyBool, PyByteArray, PyBytes, PyCode, PyComplex, PyDict, + PyEllipsis, PyFloat, PyFrozenDict, PyFrozenSet, PyInt, PyList, PyMemoryView, PyNone, + PySet, PyStopIteration, PyStr, PyTuple, }, convert::ToPyObject, - function::ArgBytesLike, + function::{ArgBytesLike, ArgIntoBool}, object::{AsObject, PyPayload}, }; use core::cell::RefCell; use malachite_bigint::BigInt; - use num_traits::Zero; + use num_traits::{ToPrimitive, Zero}; use rustpython_compiler_core::marshal::{self, DumpableValue}; #[pyattr(name = "version")] @@ -76,6 +77,10 @@ mod decl { let entries = pydict.into_iter().collect::>(); f(DumpableValue::Dict(&entries)) } + ref pyfrozen @ PyFrozenDict => { + let entries = DictIter::new(&pyfrozen.dict).collect::>(); + f(DumpableValue::Frozendict(&entries)) + } ref bytes @ PyBytes => { f(DumpableValue::Bytes(bytes.as_bytes())) } @@ -95,10 +100,10 @@ mod decl { struct DumpsArgs { #[pyarg(positional)] value: PyObjectRef, - #[pyarg(positional, default = 5)] + #[pyarg(positional, default = 6, py_default = "version")] version: i32, - #[pyarg(named, default = true)] - allow_code: bool, + #[pyarg(named, default = ArgIntoBool::TRUE)] + allow_code: ArgIntoBool, } #[pyfunction] @@ -108,10 +113,10 @@ mod decl { allow_code, version, } = args; + let allow_code = allow_code.into(); vm.audit("marshal.dumps", || (value.clone(), version))?; - check_exact_type(&value, vm)?; let mut buf = Vec::new(); let mut refs = if version >= 3 { Some(WriterRefTable::new()) @@ -124,6 +129,8 @@ mod decl { struct WriterRefEntry { idx: u32, + // The table holds a reference, as w_ref does, so the id stays unique. + _owner: PyObjectRef, /// Set between `reserve` and `complete` for the object kinds whose /// immutable representation cannot be rebuilt from a back-reference. incomplete: bool, @@ -158,8 +165,14 @@ mod decl { } fn reserve(&mut self, obj: &PyObject, incomplete: bool) -> u32 { let idx = self.next_idx; - self.map - .insert(obj.get_id(), WriterRefEntry { idx, incomplete }); + self.map.insert( + obj.get_id(), + WriterRefEntry { + idx, + incomplete, + _owner: obj.to_owned(), + }, + ); self.next_idx += 1; idx } @@ -226,6 +239,7 @@ mod decl { if depth == 0 { return Err(vm.new_value_error("object too deeply nested to marshal")); } + check_exact_type(obj, vm)?; // Singletons: no FLAG_REF needed let is_singleton = vm.is_none(obj) @@ -233,8 +247,14 @@ mod decl { || obj.is(PyStopIteration::static_type()) || obj.downcast_ref::().is_some(); - // FLAG_REF: check if already written, otherwise reserve slot - if !is_singleton && let Some(rt) = refs.as_mut() { + // If it has only one reference, it definitely isn't shared. But + // TYPE_REF is always used for interned strings, to keep PYC files as + // stable as possible. + let use_ref = refs.is_some() + && !is_singleton + && (obj.strong_count() != 1 + || (obj.class().is(PyStr::static_type()) && obj.is_interned())); + if use_ref && let Some(rt) = refs.as_mut() { match rt.try_ref(buf, obj) { Ok(true) => return Ok(()), Ok(false) => {} @@ -247,13 +267,13 @@ mod decl { } } let type_pos = buf.len(); - let use_ref = refs.is_some() && !is_singleton; - // A code or slice entry stays incomplete until its contents are - // written: the reader rebuilds both from their fields, so a + // A code, slice or frozendict entry stays incomplete until its contents are + // written: the reader rebuilds them from their fields, so a // back-reference issued while those fields are still being emitted // would name an object that does not exist yet. let requires_completion = obj.downcast_ref::().is_some() - || obj.downcast_ref::().is_some(); + || obj.downcast_ref::().is_some() + || obj.downcast_ref::().is_some(); if use_ref { refs.as_mut().unwrap().reserve(obj, requires_completion); } @@ -325,7 +345,9 @@ mod decl { write_float_str(buf, cv.re); write_float_str(buf, cv.im); } - } else if let Some(s) = obj.downcast_ref::() { + } else if let Some(s) = obj.downcast_ref::() + && obj.class().is(PyStr::static_type()) + { let bytes = s.as_wtf8().as_bytes(); // Only the formats that carry back-references tell an interned // string apart, and only those from 4 on have the ascii-only forms. @@ -372,32 +394,78 @@ mod decl { for elem in items.iter() { write_object_depth(buf, elem, refs, version, allow_code, vm, depth - 1)?; } - } else if let Some(d) = obj.downcast_ref::() { - buf.write_u8(b'{'); - for (k, v) in d { + } else if let Some(d) = PyAnyDict::from_object(obj) { + let typ = if d.is_frozen() { + if version < 6 || !obj.class().is(vm.ctx.types.frozendict_type) { + return Err(vm.new_value_error("unmarshallable object")); + } + b'}' + } else { + b'{' + }; + buf.write_u8(typ); + for (k, v) in DictIter::new(d.as_dict()) { write_object_depth(buf, &k, refs, version, allow_code, vm, depth - 1)?; write_object_depth(buf, &v, refs, version, allow_code, vm, depth - 1)?; } buf.write_u8(b'0'); // TYPE_NULL terminator } else if let Some(s) = obj.downcast_ref::() { buf.write_u8(b'<'); - write_set_elements(buf, &s.elements(), refs, version, allow_code, vm, depth)?; + let size = s.marshal_len(); + let mut position = 0; + let elements = core::iter::from_fn(|| { + let (next, value) = s.next_entry(position)?; + position = next; + Some(value) + }); + write_set_elements(buf, (size, elements), refs, version, allow_code, vm, depth)?; } else if let Some(s) = obj.downcast_ref::() { buf.write_u8(b'>'); - write_set_elements(buf, &s.elements(), refs, version, allow_code, vm, depth)?; + let elements = s.elements(); + write_set_elements( + buf, + (elements.len(), elements.into_iter()), + refs, + version, + allow_code, + vm, + depth, + )?; } else if let Some(co) = obj.downcast_ref::() { if !allow_code { return Err(vm.new_value_error("marshalling code objects is disallowed")); } buf.write_u8(b'c'); - // `Literal` holds the exact object a constant was built from, so - // route `co_consts` back through the object writer: it reaches the - // values `BorrowedConstant` cannot describe and shares the one - // reference table the reader indexes against. - marshal::serialize_code_with(buf, &co.code, |buf, constant| { - let constant = PyObjectRef::from(constant.clone()); - write_object_depth(buf, &constant, refs, version, allow_code, vm, depth - 1) - })?; + let code = &co.code; + for value in [ + code.arg_count, + code.posonlyarg_count, + code.kwonlyarg_count, + code.max_stackdepth, + code.flags.bits(), + ] { + buf.write_u32(value); + } + let co_code = co.get_code(vm); + let co_qualname = co.co_qualname(); + let mut write_field = |buf: &mut Vec, field: &PyObject| { + write_object_depth(buf, field, refs, version, allow_code, vm, depth - 1) + }; + for field in [ + co_code.as_object(), + co.co_consts().as_object(), + co.co_names.as_object(), + co.co_localsplusnames.as_object(), + co.co_localspluskinds.as_object(), + co.source_path().as_object(), + co.co_name.as_object(), + co_qualname.as_object(), + ] { + write_field(buf, field)?; + } + buf.write_u32(code.first_line_number.map_or(0, |n| n.get() as u32)); + write_field(buf, co.co_linetable.as_object())?; + write_field(buf, co.co_exceptiontable.as_object())?; } else if let Some(sl) = obj.downcast_ref::() { if version < 5 { return Err(vm.new_value_error("unmarshallable object")); @@ -444,7 +512,7 @@ mod decl { /// Serialize set elements in `sorted(v, key=marshal.dumps)` order. fn write_set_elements( buf: &mut Vec, - elems: &[PyObjectRef], + (size, elems): (usize, impl Iterator), refs: &mut Option, version: i32, allow_code: bool, @@ -452,13 +520,21 @@ mod decl { depth: usize, ) -> PyResult<()> { use marshal::Write; - buf.write_u32(elems.len() as u32); - let mut pairs = Vec::with_capacity(elems.len()); + buf.write_u32(size as u32); + let mut pairs = Vec::with_capacity(size); + // Take one owned entry at a time. Serializing it can invoke Python + // callbacks that mutate the set; no collection lock crosses that call. for elem in elems { + if pairs.len() == size { + return Err(vm.new_runtime_error("set changed size during iteration")); + } let mut dumped = Vec::new(); let mut inner_refs = (version >= 3).then(WriterRefTable::new); - write_object(&mut dumped, elem, &mut inner_refs, version, allow_code, vm)?; - pairs.push((dumped, elem.clone())); + write_object(&mut dumped, &elem, &mut inner_refs, version, allow_code, vm)?; + pairs.push((dumped, elem)); + } + if pairs.len() != size { + return Err(vm.new_runtime_error("set changed size during iteration")); } pairs.sort_by(|a, b| a.0.cmp(&b.0)); for (_, elem) in &pairs { @@ -473,14 +549,14 @@ mod decl { value: PyObjectRef, #[pyarg(positional)] file: PyObjectRef, - #[pyarg(positional, default = 5)] + #[pyarg(positional, default = 6, py_default = "version")] version: i32, - #[pyarg(named, default = true)] - allow_code: bool, + #[pyarg(named, default = ArgIntoBool::TRUE)] + allow_code: ArgIntoBool, } #[pyfunction] - fn dump(args: DumpArgs, vm: &VirtualMachine) -> PyResult<()> { + fn dump(args: DumpArgs, vm: &VirtualMachine) -> PyResult { let dumped = dumps( DumpsArgs { value: args.value, @@ -489,8 +565,7 @@ mod decl { }, vm, )?; - vm.call_method(&args.file, "write", (dumped,))?; - Ok(()) + vm.call_method(&args.file, "write", (dumped,)) } #[derive(Copy, Clone)] @@ -593,14 +668,20 @@ mod decl { unsafe { tuple.payload.set_marshal_item(index, value) }; Ok(()) } - fn make_code(&self, code: CodeObject) -> Result { + fn make_code( + &self, + code: CodeObject, + fields: marshal::CodeFields, + ) -> Result { if !self.allow_code { return Err(self.remember_python_error( self.vm .new_value_error("unmarshalling code objects is disallowed"), )); } - Ok(crate::builtins::PyCode::new_ref_with_bag(self.vm, code).into()) + let mut code = PyCode::from_marshal(code, fields, &self.vm.ctx)?; + code.apply_debug_ranges(self.vm); + Ok(code.into_ref(&self.vm.ctx).into()) } fn make_stop_iter(&self) -> Result { Ok(self.vm.ctx.exceptions.stop_iteration.to_owned().into()) @@ -677,6 +758,12 @@ mod decl { fn make_dict_placeholder(&self) -> Option { Some(self.vm.ctx.new_dict().into()) } + fn freeze_dict(&self, source: Self::Value) -> Result { + let dict = PyDict::default(); + dict.update_arg(source, true, "frozendict", self.vm) + .map_err(|error| self.remember_python_error(error))?; + Ok(PyFrozenDict::from_dict(dict).into_ref(&self.vm.ctx).into()) + } fn insert_dict_item( &self, dict: &Self::Value, @@ -737,27 +824,35 @@ mod decl { fn deserialize_value( rdr: &mut impl marshal::Read, + pending_error: &RefCell>, allow_code: bool, vm: &VirtualMachine, ) -> PyResult { - let pending_error = RefCell::new(None); - match marshal::deserialize_value(rdr, PyMarshalBag::new(vm, &pending_error, allow_code)) { - Ok(value) => Ok(value), - Err(error) => Err(pending_error.into_inner().unwrap_or_else(|| match error { - marshal::MarshalError::Eof => vm.new_eof_error("EOF read where not expected"), - marshal::MarshalError::EofObject => { - vm.new_eof_error("EOF read where object expected") - } - marshal::MarshalError::DataTooShort => vm.new_eof_error("marshal data too short"), - error @ marshal::MarshalError::NullObject => vm.new_type_error(error.to_string()), - error @ (marshal::MarshalError::BadSize(_) - | marshal::MarshalError::UnknownType - | marshal::MarshalError::InvalidRef) => { - vm.new_value_error(format!("bad marshal data ({error})")) - } - _ => vm.new_value_error("bad marshal data"), - })), - } + let result = + marshal::deserialize_value(rdr, PyMarshalBag::new(vm, pending_error, allow_code)); + let pending = pending_error.borrow_mut().take(); + if let Some(error) = pending { + // r_object replaces an EOFError while reading a type marker, + // but preserves other exceptions from the stream or __index__. + if matches!(result, Err(marshal::MarshalError::EofObject)) + && error.fast_isinstance(vm.ctx.exceptions.eof_error) + { + return Err(vm.new_eof_error("EOF read where object expected")); + } + return Err(error); + } + result.map_err(|error| match error { + marshal::MarshalError::Eof => vm.new_eof_error("EOF read where not expected"), + marshal::MarshalError::EofObject => vm.new_eof_error("EOF read where object expected"), + marshal::MarshalError::DataTooShort => vm.new_eof_error("marshal data too short"), + error @ marshal::MarshalError::NullObject => vm.new_type_error(error.to_string()), + error @ (marshal::MarshalError::BadSize(_) + | marshal::MarshalError::UnknownType + | marshal::MarshalError::InvalidRef) => { + vm.new_value_error(format!("bad marshal data ({error})")) + } + _ => vm.new_value_error("bad marshal data"), + }) } #[derive(FromArgs)] @@ -765,59 +860,49 @@ mod decl { #[pyarg(positional)] // marshal_loads_impl takes `bytes: Py_buffer`, a y* argument. bytes: ArgBytesLike, - #[pyarg(named, default = true)] - allow_code: bool, + #[pyarg(named, default = ArgIntoBool::TRUE)] + allow_code: ArgIntoBool, } #[pyfunction] fn loads(args: LoadsArgs, vm: &VirtualMachine) -> PyResult { let LoadsArgs { bytes, allow_code } = args; + let allow_code = allow_code.into(); + vm.audit("marshal.loads", || { + (vm.ctx.new_bytes(bytes.borrow_buf().to_vec()),) + })?; let buf = bytes.borrow_buf(); - deserialize_value(&mut &buf[..], allow_code, vm) + deserialize_value(&mut &buf[..], &RefCell::new(None), allow_code, vm) } #[derive(FromArgs)] struct LoadArgs { #[pyarg(positional)] file: PyObjectRef, - #[pyarg(named, default = true)] - allow_code: bool, + #[pyarg(named, default = ArgIntoBool::TRUE)] + allow_code: ArgIntoBool, } #[pyfunction] fn load(args: LoadArgs, vm: &VirtualMachine) -> PyResult { + let data = vm.call_method(&args.file, "read", (0,))?; + if data.downcast_ref::().is_none() { + let name = data.class().slot_name(); + return Err(vm.new_type_error(format!( + "file.read() returned not bytes but {}", + &name[..name.floor_char_boundary(100.min(name.len()))] + ))); + } + vm.audit("marshal.load", || ())?; + let pending_error = RefCell::new(None); let mut rdr = ReadableFile { file: args.file, vm, buf: Vec::new(), - error: None, + pending_error: &pending_error, }; - let pending_error = RefCell::new(None); - let result = marshal::deserialize_value( - &mut rdr, - PyMarshalBag::new(vm, &pending_error, args.allow_code), - ); - if let Some(err) = rdr.error.take() { - return Err(err); - } - match result { - Ok(value) => Ok(value), - Err(error) => Err(pending_error.into_inner().unwrap_or_else(|| match error { - marshal::MarshalError::Eof => vm.new_eof_error("EOF read where not expected"), - marshal::MarshalError::EofObject => { - vm.new_eof_error("EOF read where object expected") - } - marshal::MarshalError::DataTooShort => vm.new_eof_error("marshal data too short"), - error @ marshal::MarshalError::NullObject => vm.new_type_error(error.to_string()), - error @ (marshal::MarshalError::BadSize(_) - | marshal::MarshalError::UnknownType - | marshal::MarshalError::InvalidRef) => { - vm.new_value_error(format!("bad marshal data ({error})")) - } - _ => vm.new_value_error("bad marshal data"), - })), - } + deserialize_value(&mut rdr, &pending_error, args.allow_code.into(), vm) } /// File-backed marshal reader. `r_string` fills a scratch buffer via @@ -826,23 +911,46 @@ mod decl { file: PyObjectRef, vm: &'a VirtualMachine, buf: Vec, - error: Option, + pending_error: &'a RefCell>, } impl ReadableFile<'_> { fn r_string(&mut self, n: usize) -> PyResult<()> { self.buf.clear(); - let bytearray = PyByteArray::from(vec![0u8; n]).into_ref(&self.vm.ctx); + // Both allocations depend on the stream's length, so allocation + // failure must become MemoryError rather than aborting the process. + self.buf + .try_reserve_exact(n) + .map_err(|_| self.vm.no_memory_error())?; + let mut scratch = Vec::new(); + scratch + .try_reserve_exact(n) + .map_err(|_| self.vm.no_memory_error())?; + scratch.resize(n, 0); + let bytearray = PyByteArray::from(scratch).into_ref(&self.vm.ctx); let memoryview = PyMemoryView::from_object_with_flags( bytearray.as_object(), crate::protocol::BufferFlags::CONTIG, self.vm, )? .into_ref(&self.vm.ctx); + // Keep our own export even if readinto releases its memoryview. + // The returned object's __index__ can run Python too; neither + // callback may resize the scratch buffer before it is copied. + let _export = memoryview.clone_buffer(); let nread_obj = self.vm.call_method(&self.file, "readinto", (memoryview,))?; - let nread = nread_obj - .try_index(self.vm)? - .try_to_primitive::(self.vm)?; + let index = nread_obj.try_index(self.vm)?; + let nread = index.as_bigint().to_isize().ok_or_else(|| { + let name = nread_obj.class().slot_name(); + self.vm.new_value_error(format!( + "cannot fit '{}' into an index-sized integer", + &name[..name.floor_char_boundary(200.min(name.len()))] + )) + })?; + // r_string decrefs the result before inspecting the count or + // copying bytes; its finalizer may still write through the view. + drop(index); + drop(nread_obj); let n_isize = isize::try_from(n).unwrap_or(isize::MAX); if nread != n_isize { if nread > n_isize { @@ -859,11 +967,11 @@ mod decl { impl marshal::Read for ReadableFile<'_> { fn read_slice(&mut self, n: u32) -> Result<&[u8], marshal::MarshalError> { - if self.error.is_some() { + if self.pending_error.borrow().is_some() { return Err(marshal::MarshalError::Eof); } if let Err(e) = self.r_string(n as usize) { - self.error = Some(e); + *self.pending_error.borrow_mut() = Some(e); return Err(marshal::MarshalError::Eof); } Ok(&self.buf) diff --git a/crates/vm/src/stdlib/mod.rs b/crates/vm/src/stdlib/mod.rs index 73b816c579c..96aa5ce1f9b 100644 --- a/crates/vm/src/stdlib/mod.rs +++ b/crates/vm/src/stdlib/mod.rs @@ -3,10 +3,11 @@ mod _abc; pub(crate) mod _ast; mod _codecs; mod _collections; -pub(crate) use _collections::ordered_dict::ordered_dict::PyOrderedDictItems; +pub(crate) use _collections::ordered_dict::ordered_dict::PyOrderedDict; mod _functools; mod _imp; pub mod _io; +mod _lsprof; mod _operator; mod _sre; mod _stat; @@ -52,7 +53,7 @@ pub mod posix_unix_like; ), not(any(target_env = "musl", target_env = "sgx")) ))] -mod _ctypes; +pub(crate) mod _ctypes; #[cfg(all(feature = "host_env", windows))] pub(crate) mod msvcrt; @@ -83,6 +84,36 @@ mod winsound; use crate::{Context, builtins::PyModuleDef}; +// Keep ctypes-specific alias detection available to memoryview on all targets. +pub(crate) fn is_borrowed_ctypes_buffer(_obj: &crate::PyObject) -> bool { + #[cfg(all( + feature = "host_env", + any( + target_os = "linux", + target_os = "macos", + target_os = "windows", + target_os = "android" + ), + not(any(target_env = "musl", target_env = "sgx")) + ))] + { + _ctypes::is_borrowed_buffer(_obj) + } + #[cfg(not(all( + feature = "host_env", + any( + target_os = "linux", + target_os = "macos", + target_os = "windows", + target_os = "android" + ), + not(any(target_env = "musl", target_env = "sgx")) + )))] + { + false + } +} + /// Returns module definitions for multi-phase init modules. /// /// These modules use multi-phase initialization pattern: @@ -119,6 +150,7 @@ pub fn builtin_module_defs(ctx: &Context) -> Vec<&'static PyModuleDef> { msvcrt::module_def(ctx), #[cfg(all(feature = "host_env", windows))] nt::module_def(ctx), + _lsprof::module_def(ctx), _operator::module_def(ctx), #[cfg(all(feature = "host_env", any(unix, target_os = "wasi")))] posix::module_def(ctx), @@ -140,6 +172,7 @@ pub fn builtin_module_defs(ctx: &Context) -> Vec<&'static PyModuleDef> { _symtable::module_def(ctx), _sysconfigdata::module_def(ctx), _sysconfig::module_def(ctx), + _sysconfig::_missing_stdlib_info::module_def(ctx), #[cfg(feature = "threading")] _thread::module_def(ctx), _interpchannels::module_def(ctx), diff --git a/crates/vm/src/stdlib/msvcrt.rs b/crates/vm/src/stdlib/msvcrt.rs index 774b3cf087d..a0f7b180d91 100644 --- a/crates/vm/src/stdlib/msvcrt.rs +++ b/crates/vm/src/stdlib/msvcrt.rs @@ -20,10 +20,6 @@ mod msvcrt { SEM_NOOPENFILEERRORBOX, }; - pub(crate) fn setmode_binary(fd: crt_fd::Borrowed<'_>) { - host_msvcrt::setmode_binary(fd); - } - // Locking mode constants #[pyattr] const LK_UNLCK: i32 = host_msvcrt::LK_UNLCK; // Unlock diff --git a/crates/vm/src/stdlib/nt.rs b/crates/vm/src/stdlib/nt.rs index 812bca83b78..62408e46bd2 100644 --- a/crates/vm/src/stdlib/nt.rs +++ b/crates/vm/src/stdlib/nt.rs @@ -9,11 +9,11 @@ pub(crate) mod module { AsObject, Py, PyObjectRef, PyResult, TryFromObject, VirtualMachine, builtins::{PyBytes, PyCapsule, PyDictRef, PyListRef, PyStr, PyStrRef, PyTupleRef}, convert::ToPyException, - exceptions::{self, OSErrorBuilder, ToOSErrorBuilder}, + exceptions::{self, OSErrorBuilder}, function::{ArgMapping, Either, FsPath, OptionalArg}, host_env::crt_fd, - ospath::{OsPath, OsPathOrFd}, - stdlib::os::{_os, DirFd, SupportFunc, SymlinkArgs}, + ospath::{OsPath, OsPathOrFd, PathConverter}, + stdlib::os::{_os, AccessArgs, DirFd, SupportFunc, SymlinkArgs}, }; use core::hint::cold_path; use libc::intptr_t; @@ -24,6 +24,18 @@ pub(crate) mod module { use std::os::windows::ffi::{OsStrExt, OsStringExt}; use std::os::windows::io::AsRawHandle; + #[pyfunction] + fn get_blocking(fd: crt_fd::Borrowed<'_>, vm: &VirtualMachine) -> PyResult { + vm.allow_threads(|| host_nt::get_blocking(fd)) + .map_err(|err| err.to_pyexception(vm)) + } + + #[pyfunction] + fn set_blocking(fd: crt_fd::Borrowed<'_>, blocking: bool, vm: &VirtualMachine) -> PyResult<()> { + vm.allow_threads(|| host_nt::set_blocking(fd, blocking)) + .map_err(|err| err.to_pyexception(vm)) + } + #[pyattr] use rustpython_host_env::os::{ O_BINARY, O_NOINHERIT, O_RANDOM, O_SEQUENTIAL, O_TEMPORARY, O_TEXT, @@ -34,24 +46,15 @@ pub(crate) mod module { EX_OK, O_SHORT_LIVED, P_DETACH, P_NOWAIT, P_NOWAITO, P_OVERLAY, P_WAIT, TMP_MAX, }; - fn utf8_from_bytes<'a>(bytes: &'a [u8], vm: &VirtualMachine) -> PyResult<&'a str> { - core::str::from_utf8(bytes).map_err(|err| { - let reason = match err.error_len() { - None => "unexpected end of data", - Some(_) => match bytes[err.valid_up_to()] { - 0xc2..=0xf4 => "invalid continuation byte", - _ => "invalid start byte", - }, - }; - vm.new_unicode_decode_error( - vm.ctx.new_str("utf-8"), - vm.ctx.new_bytes(bytes.to_vec()), - err.valid_up_to(), - err.error_len() - .map_or(bytes.len(), |len| err.valid_up_to() + len), - vm.ctx.new_str(reason), - ) - }) + fn fsdecode_bytes(bytes: &Py, vm: &VirtualMachine) -> PyResult { + // Match path_converter(make_wide=True): Windows paths use the + // filesystem codec, including its surrogatepass error handler. + vm.state.codec_registry.decode_text( + bytes.to_owned().into(), + vm.fs_encoding().as_ref(), + Some(vm.fs_encode_errors().to_owned()), + vm, + ) } #[pyattr] @@ -64,9 +67,21 @@ pub(crate) mod module { }; #[pyfunction] - pub(super) fn access(path: OsPath, mode: u8, vm: &VirtualMachine) -> PyResult { - let _ = path.to_wide_cstring(vm)?; - Ok(host_nt::access(path.as_ref(), mode)) + pub(super) fn access(args: AccessArgs<'_>, vm: &VirtualMachine) -> PyResult { + let [] = args.dir_fd.0; + if !args.follow_symlinks.0 { + return Err(vm.new_not_implemented_error( + "access: follow_symlinks unavailable on this platform", + )); + } + if args.effective_ids { + return Err( + vm.new_not_implemented_error("access: effective_ids unavailable on this platform") + ); + } + let wide = args.path.to_wide_cstring(vm)?; + + Ok(host_nt::access(&wide, args.mode)) } #[pyfunction] @@ -97,11 +112,9 @@ pub(crate) mod module { &dst, args.target_is_directory.target_is_directory, ) { - let builder = err.to_os_error_builder(vm); - let builder = builder - .filename(args.src.filename(vm)) - .filename2(args.dst.filename(vm)); - return Err(builder.build(vm).upcast()); + return Err(OSErrorBuilder::with_filenames( + &err, &args.src, &args.dst, vm, + )); } Ok(()) @@ -119,22 +132,22 @@ pub(crate) mod module { #[pyattr] fn environ(vm: &VirtualMachine) -> PyDictRef { - let environ = vm.ctx.new_dict(); - - for (key, value) in host_nt::visible_env_vars() { - if key.starts_with('=') { - continue; - } - environ.set_item(&key, vm.new_pyobj(value), vm).unwrap(); - } - environ + _create_environ(vm) } #[pyfunction] fn _create_environ(vm: &VirtualMachine) -> PyDictRef { let environ = vm.ctx.new_dict(); for (key, value) in host_nt::visible_env_vars() { - environ.set_item(&key, vm.new_pyobj(value), vm).unwrap(); + // Like PyUnicode_FromWideChar, combine UTF-16 pairs while preserving + // isolated surrogates instead of requiring Unicode scalar values. + let key = vm + .ctx + .new_str(Wtf8Buf::from_wide(&key.encode_wide().collect::>())); + let value = vm + .ctx + .new_str(Wtf8Buf::from_wide(&value.encode_wide().collect::>())); + environ.set_item(&*key, value.into(), vm).unwrap(); } environ } @@ -219,9 +232,18 @@ pub(crate) mod module { path: crate::PyObjectRef, } + #[derive(FromArgs)] + struct OsPathArg { + #[pyarg(any)] + path: OsPath, + } + impl PathArg { - fn to_path_or_fd(&self, vm: &VirtualMachine) -> Option> { - OsPathOrFd::try_from_object(vm, self.path.clone()).ok() + fn to_path_or_fd(&self, vm: &VirtualMachine) -> PyResult>> { + match PathConverter::new().try_path_or_fd_allow_invalid(self.path.clone(), vm) { + Err(err) if err.fast_isinstance(vm.ctx.exceptions.value_error) => Ok(None), + result => result, + } } } @@ -306,56 +328,63 @@ pub(crate) mod module { // return _testFileType(path, PY_IFDIR) #[pyfunction] - fn _path_isdir(args: PathArg, vm: &VirtualMachine) -> bool { - args.to_path_or_fd(vm) - .is_some_and(|p| _test_file_type(&p, PY_IFDIR)) + fn _path_isdir(path: PyObjectRef, vm: &VirtualMachine) -> PyResult { + Ok(PathArg { path } + .to_path_or_fd(vm)? + .is_some_and(|p| _test_file_type(&p, PY_IFDIR))) } // return _testFileType(path, PY_IFREG) #[pyfunction] - fn _path_isfile(args: PathArg, vm: &VirtualMachine) -> bool { - args.to_path_or_fd(vm) - .is_some_and(|p| _test_file_type(&p, PY_IFREG)) + fn _path_isfile(args: PathArg, vm: &VirtualMachine) -> PyResult { + Ok(args + .to_path_or_fd(vm)? + .is_some_and(|p| _test_file_type(&p, PY_IFREG))) } // return _testFileType(path, PY_IFLNK) #[pyfunction] - fn _path_islink(args: PathArg, vm: &VirtualMachine) -> bool { - args.to_path_or_fd(vm) - .is_some_and(|p| _test_file_type(&p, PY_IFLNK)) + fn _path_islink(args: PathArg, vm: &VirtualMachine) -> PyResult { + Ok(args + .to_path_or_fd(vm)? + .is_some_and(|p| _test_file_type(&p, PY_IFLNK))) } // return _testFileType(path, PY_IFMNT) #[pyfunction] - fn _path_isjunction(args: PathArg, vm: &VirtualMachine) -> bool { - args.to_path_or_fd(vm) - .is_some_and(|p| _test_file_type(&p, PY_IFMNT)) + fn _path_isjunction(args: PathArg, vm: &VirtualMachine) -> PyResult { + Ok(args + .to_path_or_fd(vm)? + .is_some_and(|p| _test_file_type(&p, PY_IFMNT))) } // return _testFileExists(path, TRUE) #[pyfunction] - fn _path_exists(args: PathArg, vm: &VirtualMachine) -> bool { - args.to_path_or_fd(vm) - .is_some_and(|p| _test_file_exists(&p, true)) + fn _path_exists(args: PathArg, vm: &VirtualMachine) -> PyResult { + Ok(args + .to_path_or_fd(vm)? + .is_some_and(|p| _test_file_exists(&p, true))) } // return _testFileExists(path, FALSE) #[pyfunction] - fn _path_lexists(args: PathArg, vm: &VirtualMachine) -> bool { - args.to_path_or_fd(vm) - .is_some_and(|p| _test_file_exists(&p, false)) + fn _path_lexists(args: PathArg, vm: &VirtualMachine) -> PyResult { + Ok(args + .to_path_or_fd(vm)? + .is_some_and(|p| _test_file_exists(&p, false))) } #[pyfunction] - fn _path_isdevdrive(path: OsPath, vm: &VirtualMachine) -> PyResult { + fn _path_isdevdrive(args: OsPathArg, vm: &VirtualMachine) -> PyResult { + let path = args.path; let path = path.to_wide_cstring(vm)?; host_nt::path_isdevdrive(&path).map_err(|err| err.to_pyexception(vm)) } #[cfg(target_env = "msvc")] #[pyfunction] - fn waitpid(pid: intptr_t, opt: i32, vm: &VirtualMachine) -> PyResult<(intptr_t, u64)> { - let (pid, status) = host_nt::cwait(pid, opt).map_err(|_| vm.new_last_errno_error())?; + fn waitpid(pid: intptr_t, options: i32, vm: &VirtualMachine) -> PyResult<(intptr_t, u64)> { + let (pid, status) = host_nt::cwait(pid, options).map_err(|_| vm.new_last_errno_error())?; // Cast to unsigned to handle large exit codes (like 0xC000013A) // then shift left by 8 to match POSIX waitpid format let ustatus = (status as u32) as u64; @@ -369,8 +398,8 @@ pub(crate) mod module { } #[pyfunction] - fn kill(pid: i32, sig: isize, vm: &VirtualMachine) -> PyResult<()> { - host_nt::kill(pid as u32, sig as u32).map_err(|err| err.to_pyexception(vm)) + fn kill(pid: i32, signal: isize, vm: &VirtualMachine) -> PyResult<()> { + host_nt::kill(pid as u32, signal as u32).map_err(|err| err.to_pyexception(vm)) } #[pyfunction] @@ -397,8 +426,15 @@ pub(crate) mod module { let path = path.to_wide_cstring(vm)?; let argv = vm.extract_elements_with(argv.as_ref(), |obj| { - let fspath = FsPath::try_from_path_like(obj, true, vm)?; - fspath.to_wide_cstring(vm) + FsPath::try_from_path_like(obj, true, vm) + .and_then(|fspath| fspath.to_wide_cstring(vm)) + .map_err(|err| { + if err.fast_isinstance(vm.ctx.exceptions.type_error) { + vm.new_type_error("spawnv() arg 2 must contain only strings") + } else { + err + } + }) })?; let first = argv @@ -565,7 +601,7 @@ pub(crate) mod module { let wide = path.to_wide_cstring(vm)?; let final_path = host_nt::getfinalpathname(&wide) .map_err(|err| OSErrorBuilder::with_filename(&err, path.clone(), vm))?; - Ok(path.mode().process_path(final_path, vm)) + path.mode().process_path(final_path, vm) } #[pyfunction] @@ -573,11 +609,12 @@ pub(crate) mod module { let wide = path.to_wide_cstring(vm)?; let buffer = host_nt::getfullpathname(&wide) .map_err(|err| OSErrorBuilder::with_filename(&err, path.clone(), vm))?; - Ok(path.mode().process_path(buffer, vm)) + path.mode().process_path(buffer, vm) } #[pyfunction] - fn _getvolumepathname(path: OsPath, vm: &VirtualMachine) -> PyResult { + fn _getvolumepathname(args: OsPathArg, vm: &VirtualMachine) -> PyResult { + let path = args.path; let wide = path.to_wide_cstring(vm)?; let buflen = core::cmp::max(wide.len(), host_nt::MAX_PATH_USIZE); if buflen > u32::MAX as usize { @@ -585,7 +622,7 @@ pub(crate) mod module { } let buffer = host_nt::getvolumepathname(&wide) .map_err(|err| OSErrorBuilder::with_filename(&err, path.clone(), vm))?; - Ok(path.mode().process_path(buffer, vm)) + path.mode().process_path(buffer, vm) } /// Implements _Py_skiproot logic for Windows paths @@ -669,15 +706,14 @@ pub(crate) mod module { path }; - // Convert to wide string, validating UTF-8 for bytes input + // Convert through the filesystem codec for bytes input let (wide, is_bytes): (Vec, bool) = if let Some(s) = path.downcast_ref::() { // Use encode_wide which handles WTF-8 (including surrogates) let wide: Vec = s.as_wtf8().encode_wide().collect(); (wide, false) } else if let Some(b) = path.downcast_ref::() { - // On Windows, bytes must be valid UTF-8 - this raises UnicodeDecodeError if not - let s = utf8_from_bytes(b.as_bytes(), vm)?; - let wide: Vec = s.encode_utf16().collect(); + let s = fsdecode_bytes(b, vm)?; + let wide: Vec = s.as_wtf8().encode_wide().collect(); (wide, true) } else { return Err(vm.new_type_error(format!( @@ -696,14 +732,11 @@ pub(crate) mod module { // Return as bytes if input was bytes, preserving the original content if is_bytes { - // Convert UTF-16 back to UTF-8 for bytes output - let drv = Wtf8Buf::from_wide(&wide[..drv_size]).into_bytes(); - let root = Wtf8Buf::from_wide(&wide[drv_size..drv_size + root_size]).into_bytes(); - let tail = Wtf8Buf::from_wide(&wide[drv_size + root_size..]).into_bytes(); Ok(vm.ctx.new_tuple(vec![ - vm.ctx.new_bytes(drv).into(), - vm.ctx.new_bytes(root).into(), - vm.ctx.new_bytes(tail).into(), + vm.fsencode_wide(&wide[..drv_size])?.into(), + vm.fsencode_wide(&wide[drv_size..drv_size + root_size])? + .into(), + vm.fsencode_wide(&wide[drv_size + root_size..])?.into(), ])) } else { // For str output, use WTF-8 to handle surrogates @@ -877,20 +910,24 @@ pub(crate) mod module { } #[pyfunction] - fn _path_normpath(path: crate::PyObjectRef, vm: &VirtualMachine) -> PyResult { - // Handle path-like objects via os.fspath - let path = if let Some(fspath) = vm.get_method(path.clone(), identifier!(vm, __fspath__)) { - fspath?.call((), vm)? - } else { - path - }; + fn _path_normpath(args: PathArg, vm: &VirtualMachine) -> PyResult { + let path = args.path; + // Direct strings and bytes take precedence over __fspath__, including subclasses. + let path = + if path.downcast_ref::().is_some() || path.downcast_ref::().is_some() { + path + } else if let Some(fspath) = vm.get_method(path.clone(), identifier!(vm, __fspath__)) { + fspath?.call((), vm)? + } else { + path + }; let (wide, is_bytes): (Vec, bool) = if let Some(s) = path.downcast_ref::() { let wide: Vec = s.as_wtf8().encode_wide().collect(); (wide, false) } else if let Some(b) = path.downcast_ref::() { - let s = utf8_from_bytes(b.as_bytes(), vm)?; - let wide: Vec = s.encode_utf16().collect(); + let s = fsdecode_bytes(b, vm)?; + let wide: Vec = s.as_wtf8().encode_wide().collect(); (wide, true) } else { return Err(vm.new_type_error(format!( @@ -902,8 +939,7 @@ pub(crate) mod module { let normalized = normpath_wide(&wide); if is_bytes { - let bytes = Wtf8Buf::from_wide(&normalized).into_bytes(); - Ok(vm.ctx.new_bytes(bytes).into()) + vm.fsencode_wide(&normalized).map(Into::into) } else { let s = Wtf8Buf::from_wide(&normalized); Ok(vm.ctx.new_str(s).into()) @@ -911,7 +947,8 @@ pub(crate) mod module { } #[pyfunction] - fn _getdiskusage(path: OsPath, vm: &VirtualMachine) -> PyResult<(u64, u64)> { + fn _getdiskusage(args: OsPathArg, vm: &VirtualMachine) -> PyResult<(u64, u64)> { + let path = args.path; let path = path.to_wide_cstring(vm)?; host_nt::getdiskusage(&path).map_err(|err| err.to_pyexception(vm)) } @@ -957,8 +994,15 @@ pub(crate) mod module { Ok(vm.ctx.new_list(result)) } + #[derive(FromArgs)] + struct VolumeArg { + #[pyarg(any)] + volume: OsPath, + } + #[pyfunction] - fn listmounts(volume: OsPath, vm: &VirtualMachine) -> PyResult { + fn listmounts(args: VolumeArg, vm: &VirtualMachine) -> PyResult { + let volume = args.volume; let volume = volume.to_wide_cstring(vm)?; let result = host_nt::listmounts(&volume) .map_err(|err| err.to_pyexception(vm))? @@ -1035,7 +1079,7 @@ pub(crate) mod module { let mode = path.mode(); let wide = path.to_wide_cstring(vm)?; match host_nt::readlink(&wide) { - Ok(result_path) => Ok(mode.process_path(std::path::PathBuf::from(result_path), vm)), + Ok(result_path) => mode.process_path(std::path::PathBuf::from(result_path), vm), Err(host_nt::ReadlinkError::Io(err)) => { Err(OSErrorBuilder::with_filename(&err, path, vm)) } @@ -1070,7 +1114,8 @@ pub(crate) mod module { } #[pyfunction] - fn _add_dll_directory(path: OsPath, vm: &VirtualMachine) -> PyResult { + fn _add_dll_directory(args: OsPathArg, vm: &VirtualMachine) -> PyResult { + let path = args.path; let wide = path.to_wide_cstring(vm)?; let cookie = host_winapi::add_dll_directory(&wide) .map_err(|err| OSErrorBuilder::with_filename(&err, path, vm))?; @@ -1080,8 +1125,15 @@ pub(crate) mod module { .into()) } + #[derive(FromArgs)] + struct DllDirectoryCookieArg { + #[pyarg(any)] + cookie: PyObjectRef, + } + #[pyfunction] - fn _remove_dll_directory(cookie: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + fn _remove_dll_directory(args: DllDirectoryCookieArg, vm: &VirtualMachine) -> PyResult<()> { + let cookie = args.cookie; let not_a_cookie = || vm.new_type_error("Provided cookie was not returned from os.add_dll_directory"); let capsule = cookie @@ -1138,4 +1190,37 @@ pub(crate) mod module { ) .map_err(|err| OSErrorBuilder::with_filename(&err, args.filepath, vm)) } + + #[cfg(test)] + #[cfg(target_env = "msvc")] + mod tests { + use super::*; + + #[test] + fn spawnv_argument_errors_preserve_non_type_errors() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for (arg, expected_type) in [ + (vm.ctx.new_int(123).into(), vm.ctx.exceptions.type_error), + ( + vm.ctx.new_str("embedded\0null").into(), + vm.ctx.exceptions.value_error, + ), + ] { + let argv = vm.ctx.new_list(vec![vm.ctx.new_str("unused").into(), arg]); + let err = + spawnv(0, OsPath::new_str("unused"), Either::A(argv), vm).unwrap_err(); + assert!(err.fast_isinstance(expected_type)); + if expected_type.is(vm.ctx.exceptions.type_error) { + assert_eq!( + err.args().as_slice()[0] + .downcast_ref::() + .unwrap() + .as_wtf8(), + "spawnv() arg 2 must contain only strings", + ); + } + } + }); + } + } } diff --git a/crates/vm/src/stdlib/os.rs b/crates/vm/src/stdlib/os.rs index 527643822b8..9dab59a272f 100644 --- a/crates/vm/src/stdlib/os.rs +++ b/crates/vm/src/stdlib/os.rs @@ -97,6 +97,10 @@ impl<'fd, KW: DirFdKeyword> DirFd<'fd, 1, KW> { impl FromArgs for DirFd<'_, AVAILABLE, KW> { const PARAMS: Option<&'static [Param]> = Some(KW::PARAMS); + fn arity() -> core::ops::RangeInclusive { + 0..=0 + } + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { let fd = match args.take_keyword(KW::NAME) { Some(o) if vm.is_none(&o) => Ok(DEFAULT_DIR_FD), @@ -140,6 +144,20 @@ pub(super) struct FollowSymlinks( #[pyarg(named, name = "follow_symlinks", default = true)] pub bool, ); +#[derive(FromArgs)] +pub(super) struct AccessArgs<'fd> { + #[pyarg(any)] + pub(super) path: OsPath, + #[pyarg(any)] + pub(super) mode: u8, + #[pyarg(flatten)] + pub(super) dir_fd: DirFd<'fd, { _os::ACCESS_DIR_FD as usize }>, + #[pyarg(named, default)] + pub(super) effective_ids: bool, + #[pyarg(flatten)] + pub(super) follow_symlinks: FollowSymlinks, +} + #[cfg(not(windows))] fn bytes_as_os_str<'a>(b: &'a [u8], vm: &VirtualMachine) -> PyResult<&'a std::ffi::OsStr> { rustpython_host_env::os::bytes_as_os_str(b).map_err(|e| { @@ -199,22 +217,28 @@ impl ToPyObject for crt_fd::Borrowed<'_> { #[pymodule(sub, name = "posix")] pub(super) mod _os { - use super::{DirFd, DstDirFd, FollowSymlinks, RawMode, SrcDirFd, SupportFunc}; + use super::{ + AT_FDCWD, DefaultDirFd, DirFd, DirFdKeyword, DstDirFd, FollowSymlinks, RawMode, SrcDirFd, + SupportFunc, warn_if_bool_fd, + }; #[cfg(not(windows))] use crate::exceptions; use crate::host_env::fileutils::StatStruct; #[cfg(any(unix, windows))] use crate::utils::ToCString; use crate::{ - AsObject, Py, PyObjectRef, PyPayload, PyRef, PyResult, TryFromObject, + AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, builtins::{ - PyBytesRef, PyGenericAlias, PyIntRef, PyStrRef, PyTuple, PyTupleRef, PyTypeRef, + PyBytes, PyBytesRef, PyFloat, PyGenericAlias, PyIntRef, PyStr, PyStrRef, PyTuple, + PyTupleRef, PyTypeRef, }, class::PyClassDef, common::lock::{OnceCell, PyRwLock}, - convert::{IntoPyException, ToPyObject}, - exceptions::{OSErrorBuilder, ToOSErrorBuilder}, - function::{ArgBytesLike, ArgMemoryBuffer, FsPath, FuncArgs}, + convert::{IntoPyException, ToPyException, ToPyObject}, + exceptions::OSErrorBuilder, + function::{ + ArgBytesLike, ArgMemoryBuffer, ArgumentError, Either, FromArgs, FsPath, FuncArgs, Param, + }, host_env::crt_fd, ospath::{OsPath, OsPathOrFd, OutputMode, PathConverter}, protocol::PyIterReturn, @@ -225,11 +249,12 @@ pub(super) mod _os { }, vm::VirtualMachine, }; + use core::hint::cold_path; #[cfg(not(windows))] use core::marker::PhantomData; - use core::{hint::cold_path, time::Duration}; use crossbeam_utils::atomic::AtomicCell; use rustpython_common::wtf8::Wtf8Buf; + use rustpython_host_env::os::{FileTime, FileTimeSeconds}; #[cfg(windows)] use rustpython_host_env::{nt as host_nt, windows::ToWideString}; @@ -237,6 +262,15 @@ pub(super) mod _os { use rustpython_host_env::posix as host_posix; use std::{fs, io, path::PathBuf, time::SystemTime}; + pub(crate) const ACCESS_DIR_FD: bool = cfg!(all( + unix, + not(any( + target_os = "android", + target_os = "espidf", + target_os = "horizon", + target_os = "vita", + )) + )); const OPEN_DIR_FD: bool = cfg!(not(any(windows, target_os = "redox"))); pub(crate) const MKDIR_DIR_FD: bool = cfg!(any(unix, target_os = "wasi")); const STAT_DIR_FD: bool = cfg!(not(any(windows, target_os = "redox"))); @@ -272,27 +306,64 @@ pub(super) mod _os { #[pyfunction] fn closerange(fd_low: i32, fd_high: i32) { - for fileno in fd_low..fd_high { - if let Ok(fd) = unsafe { crt_fd::Owned::try_from_raw(fileno) } { - drop(fd); + crt_fd::closerange(fd_low, fd_high); + } + + // Signal callbacks can close this descriptor between open attempts. + #[cfg(any(unix, windows, target_os = "wasi"))] + struct OpenDirFd(crt_fd::Raw); + + #[cfg(any(unix, windows, target_os = "wasi"))] + impl FromArgs for OpenDirFd { + const PARAMS: Option<&'static [Param]> = Some(DefaultDirFd::PARAMS); + + fn arity() -> core::ops::RangeInclusive { + 0..=0 + } + + fn from_args(vm: &VirtualMachine, args: &mut FuncArgs) -> Result { + let fd = match args.take_keyword("dir_fd") { + Some(o) if vm.is_none(&o) => AT_FDCWD, + None => AT_FDCWD, + Some(o) => { + warn_if_bool_fd(&o, vm).map_err(Into::::into)?; + let fd = o.try_index_opt(vm).unwrap_or_else(|| { + Err(vm.new_type_error(format!( + "argument should be integer or None, not {}", + o.class().name() + ))) + })?; + fd.try_to_primitive(vm)? + } + }; + if fd == -1 { + return Err(io::Error::from_raw_os_error(libc::EBADF) + .to_pyexception(vm) + .into()); } + if !OPEN_DIR_FD && fd != AT_FDCWD { + return Err(vm + .new_not_implemented_error("dir_fd unavailable on this platform") + .into()); + } + Ok(Self(fd)) } } #[cfg(any(unix, windows, target_os = "wasi"))] #[derive(FromArgs)] - struct OpenArgs<'fd> { + struct OpenArgs { path: OsPath, flags: i32, #[pyarg(any, default = 0o777)] mode: i32, #[pyarg(flatten)] - dir_fd: DirFd<'fd, { OPEN_DIR_FD as usize }>, + dir_fd: OpenDirFd, } #[pyfunction] - fn open(args: OpenArgs<'_>, vm: &VirtualMachine) -> PyResult { - os_open(args.path, args.flags, args.mode, args.dir_fd, vm) + fn open(args: OpenArgs, vm: &VirtualMachine) -> PyResult { + os_open(args.path, args.flags, args.mode, args.dir_fd.0, vm) } #[cfg(any(unix, windows, target_os = "wasi"))] @@ -300,34 +371,50 @@ pub(super) mod _os { name: OsPath, flags: i32, mode: i32, - dir_fd: DirFd<'_, { OPEN_DIR_FD as usize }>, + dir_fd: crt_fd::Raw, vm: &VirtualMachine, ) -> PyResult { + use crate::host_env::os::ErrorExt; + #[cfg(windows)] - let fd = { - let [] = dir_fd.0; - let name = name.to_wide_cstring(vm)?; - let flags = flags | crate::host_env::os::O_NOINHERIT; - crt_fd::wopen(&name, flags, mode) - }; + let raw_name = name.to_wide_cstring(vm)?; #[cfg(not(windows))] - let fd = { - let name = name.clone().into_cstring(vm)?; - #[cfg(not(target_os = "wasi"))] - let flags = flags | crate::host_env::os::O_CLOEXEC; - #[cfg(not(target_os = "redox"))] - if let Some(dir_fd) = dir_fd.get_opt() { - crt_fd::openat(dir_fd, &name, flags, mode) - } else { - crt_fd::open(&name, flags, mode) - } - #[cfg(target_os = "redox")] - { - let [] = dir_fd.0; - crt_fd::open(&name, flags, mode) + let raw_name = name.clone().into_cstring(vm)?; + #[cfg(windows)] + let flags = flags | crate::host_env::os::O_NOINHERIT; + #[cfg(all(not(windows), not(target_os = "wasi")))] + let flags = flags | crate::host_env::os::O_CLOEXEC; + + loop { + let fd = vm.allow_threads(|| { + #[cfg(windows)] + { + let _ = dir_fd; + crt_fd::wopen(&raw_name, flags, mode) + } + #[cfg(not(windows))] + { + #[cfg(not(target_os = "redox"))] + if dir_fd != AT_FDCWD { + crt_fd::openat_raw(dir_fd, &raw_name, flags, mode) + } else { + crt_fd::open(&raw_name, flags, mode) + } + #[cfg(target_os = "redox")] + { + let _ = dir_fd; + crt_fd::open(&raw_name, flags, mode) + } + } + }); + match fd { + Ok(fd) => return Ok(fd), + Err(err) if err.posix_errno() == libc::EINTR => vm.check_signals()?, + Err(err) => { + return Err(OSErrorBuilder::with_filename_from_errno(&err, name, vm)); + } } - }; - fd.map_err(|err| OSErrorBuilder::with_filename_from_errno(&err, name, vm)) + } } #[derive(FromArgs)] @@ -348,6 +435,7 @@ pub(super) mod _os { match vm.allow_threads(|| crt_fd::read(fd, &mut buffer)) { Ok(n) => { buffer.truncate(n); + buffer.shrink_to_fit(); return Ok(vm.ctx.new_bytes(buffer)); } Err(e) if e.raw_os_error() == Some(libc::EINTR) => { @@ -404,9 +492,9 @@ pub(super) mod _os { #[pyfunction] fn write(fd: crt_fd::Borrowed<'_>, data: ArgBytesLike, vm: &VirtualMachine) -> PyResult { - let owned = data.with_ref(|b| b.to_vec()); + let buffer = data.borrow_buf_unlocked(vm)?; loop { - match vm.allow_threads(|| crt_fd::write(fd, &owned)) { + match vm.allow_threads(|| crt_fd::write(fd, &buffer)) { Ok(n) => return Ok(n), Err(e) if e.raw_os_error() == Some(libc::EINTR) => { vm.check_signals()?; @@ -483,19 +571,41 @@ pub(super) mod _os { .unwrap_or_else(|| OsPathOrFd::Path(OsPath::new_str("."))); let list = match path { OsPathOrFd::Path(path) => { - let dir_iter = match crate::host_env::fs::read_dir(&path) { - Ok(iter) => iter, - Err(err) => { - return Err(OSErrorBuilder::with_filename(&err, path, vm)); + #[cfg(windows)] + { + let wide = path + .path + .to_wide_cstring() + .map_err(|err| OSErrorBuilder::with_filename(&err, path.clone(), vm))?; + let mut dir = host_nt::scandir(&wide) + .map_err(|err| OSErrorBuilder::with_filename(&err, path.clone(), vm))?; + let mut names = Vec::new(); + while let Some(entry) = dir + .next_entry() + .map_err(|err| OSErrorBuilder::with_filename(&err, path.clone(), vm))? + { + if !entry.is_dot_or_dotdot() { + names.push(path.mode().process_path(entry.name, vm)?); + } } - }; - let mode = path.mode(); - dir_iter - .map(|entry| match entry { - Ok(entry_path) => Ok(mode.process_path(entry_path.file_name(), vm)), - Err(err) => Err(OSErrorBuilder::with_filename(&err, path.clone(), vm)), - }) - .collect::>()? + names + } + #[cfg(not(windows))] + { + let dir_iter = match crate::host_env::fs::read_dir(&path) { + Ok(iter) => iter, + Err(err) => { + return Err(OSErrorBuilder::with_filename(&err, path, vm)); + } + }; + let mode = path.mode(); + dir_iter + .map(|entry| match entry { + Ok(entry_path) => mode.process_path(entry_path.file_name(), vm), + Err(err) => Err(OSErrorBuilder::with_filename(&err, path.clone(), vm)), + }) + .collect::>()? + } } OsPathOrFd::Fd(fno) => { #[cfg(not(all(unix, not(target_os = "redox"))))] @@ -516,7 +626,7 @@ pub(super) mod _os { rustpython_host_env::os::bytes_as_os_str(&entry.name) .expect("unix dir entry names are arbitrary bytes"), vm, - ), + )?, ); } list @@ -659,7 +769,7 @@ pub(super) mod _os { let [] = args.dir_fd.0; let path = fs::read_link(&path).map_err(|err| OSErrorBuilder::with_filename(&err, path, vm))?; - Ok(mode.process_path(path, vm)) + mode.process_path(path, vm) } #[pyattr] @@ -803,12 +913,12 @@ pub(super) mod _os { #[pyclass(flags(DISALLOW_INSTANTIATION), with(Representable))] impl Py { #[pygetset] - fn name(&self, vm: &VirtualMachine) -> PyObjectRef { + fn name(&self, vm: &VirtualMachine) -> PyResult { self.mode.process_path(&self.file_name, vm) } #[pygetset] - fn path(&self, vm: &VirtualMachine) -> PyObjectRef { + fn path(&self, vm: &VirtualMachine) -> PyResult { self.mode.process_path(&self.pathval, vm) } @@ -940,7 +1050,7 @@ pub(super) mod _os { } #[pymethod] - fn __fspath__(&self, vm: &VirtualMachine) -> PyObjectRef { + fn __fspath__(&self, vm: &VirtualMachine) -> PyResult { self.path(vm) } @@ -1553,12 +1663,12 @@ pub(super) mod _os { #[pyfunction] fn getcwd(vm: &VirtualMachine) -> PyResult { - Ok(OutputMode::String.process_path(curdir_inner(vm)?, vm)) + OutputMode::String.process_path(curdir_inner(vm)?, vm) } #[pyfunction] fn getcwdb(vm: &VirtualMachine) -> PyResult { - Ok(OutputMode::Bytes.process_path(curdir_inner(vm)?, vm)) + OutputMode::Bytes.process_path(curdir_inner(vm)?, vm) } #[derive(FromArgs)] @@ -1620,12 +1730,8 @@ pub(super) mod _os { #[cfg(not(any(unix, target_os = "wasi")))] let dst_dir_fd = None; - crate::host_env::posix::rename(&src, src_dir_fd, &dst, dst_dir_fd).map_err(|err| { - let builder = err.to_os_error_builder(vm); - let builder = builder.filename(src.filename(vm)); - let builder = builder.filename2(dst.filename(vm)); - builder.build(vm).upcast() - }) + crate::host_env::posix::rename(&src, src_dir_fd, &dst, dst_dir_fd) + .map_err(|err| OSErrorBuilder::with_filenames(&err, &src, &dst, vm)) } #[pyfunction] @@ -1649,12 +1755,8 @@ pub(super) mod _os { #[cfg(not(any(unix, target_os = "wasi")))] let dst_dir_fd = None; - crate::host_env::posix::replace(&src, src_dir_fd, &dst, dst_dir_fd).map_err(|err| { - let builder = err.to_os_error_builder(vm); - let builder = builder.filename(src.filename(vm)); - let builder = builder.filename2(dst.filename(vm)); - builder.build(vm).upcast() - }) + crate::host_env::posix::replace(&src, src_dir_fd, &dst, dst_dir_fd) + .map_err(|err| OSErrorBuilder::with_filenames(&err, &src, &dst, vm)) } #[pyfunction] @@ -1689,7 +1791,7 @@ pub(super) mod _os { #[pyfunction] fn _exit(status: ExitStatus) { - crate::host_env::os::exit(status.status) + crate::host_env::os::exit_immediately(status.status) } #[pyfunction] @@ -1763,10 +1865,7 @@ pub(super) mod _os { dst_cstr.as_c_str(), follow_symlinks, ) { - let builder = err.to_os_error_builder(vm); - let builder = builder.filename(src.filename(vm)); - let builder = builder.filename2(dst.filename(vm)); - return Err(builder.build(vm).upcast()); + return Err(OSErrorBuilder::with_filenames(&err, &src, &dst, vm)); } Ok(()) @@ -1786,12 +1885,8 @@ pub(super) mod _os { .to_wide_cstring() .map_err(|err| err.into_pyexception(vm))?; let dst_wide = dst.to_wide_cstring(vm)?; - rustpython_host_env::winapi::create_hard_link(&dst_wide, &src_wide).map_err(|err| { - let builder = err.to_os_error_builder(vm); - let builder = builder.filename(src.filename(vm)); - let builder = builder.filename2(dst.filename(vm)); - builder.build(vm).upcast() - }) + rustpython_host_env::winapi::create_hard_link(&dst_wide, &src_wide) + .map_err(|err| OSErrorBuilder::with_filenames(&err, &src, &dst, vm)) } #[cfg(not(any(unix, windows)))] @@ -1804,12 +1899,8 @@ pub(super) mod _os { PathBuf::from(src.path.clone()) }; - fs::hard_link(&src_path, &dst.path).map_err(|err| { - let builder = err.to_os_error_builder(vm); - let builder = builder.filename(src.filename(vm)); - let builder = builder.filename2(dst.filename(vm)); - builder.build(vm).upcast() - }) + fs::hard_link(&src_path, &dst.path) + .map_err(|err| OSErrorBuilder::with_filenames(&err, &src, &dst, vm)) } } @@ -1832,7 +1923,7 @@ pub(super) mod _os { #[derive(FromArgs)] struct UtimeArgs<'fd> { path: OsPath, - #[pyarg(any, default)] + #[pyarg(any, default = None)] times: Option, #[pyarg(named, default)] ns: Option, @@ -1842,6 +1933,50 @@ pub(super) mod _os { follow_symlinks: FollowSymlinks, } + fn file_time_seconds(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + obj.try_index(vm) + .and_then(|value| value.try_to_primitive(vm)) + .map_err(|err| { + if err.fast_isinstance(vm.ctx.exceptions.overflow_error) { + vm.new_overflow_error("timestamp out of range for platform time_t") + } else { + err + } + }) + } + + fn file_time(obj: &PyObject, vm: &VirtualMachine) -> PyResult { + if obj.number().is_index() { + return Ok(FileTime { + seconds: file_time_seconds(obj, vm)?, + nanoseconds: 0, + }); + } + let value = if let Some(float) = obj.downcast_ref::() { + float.to_f64() + } else { + obj.try_float(vm)?.to_f64() + }; + if value.is_nan() { + return Err(vm.new_value_error("Invalid value NaN (not a number)")); + } + let mut seconds = value.trunc(); + let mut nanoseconds = (value.fract() * 1_000_000_000.0).floor(); + if nanoseconds < 0.0 { + nanoseconds += 1_000_000_000.0; + seconds -= 1.0; + } + let minimum = FileTimeSeconds::MIN as f64; + // The signed maximum rounds up when represented by f64. + if !(minimum..-minimum).contains(&seconds) { + return Err(vm.new_overflow_error("timestamp out of range for platform time_t")); + } + Ok(FileTime { + seconds: seconds as FileTimeSeconds, + nanoseconds: nanoseconds as libc::c_long, + }) + } + #[pyfunction] fn utime(args: UtimeArgs<'_>, vm: &VirtualMachine) -> PyResult<()> { let parse_tup = |tup: &Py| -> Option<(PyObjectRef, PyObjectRef)> { @@ -1856,13 +1991,13 @@ pub(super) mod _os { let (a, m) = parse_tup(&t).ok_or_else(|| { vm.new_type_error("utime: 'times' must be either a tuple of two ints or None") })?; - (a.try_into_value(vm)?, m.try_into_value(vm)?) + (file_time(&a, vm)?, file_time(&m, vm)?) } (None, Some(ns)) => { let (a, m) = parse_tup(&ns) .ok_or_else(|| vm.new_type_error("utime: 'ns' must be a tuple of two ints"))?; let ns_in_sec: PyObjectRef = vm.ctx.new_int(1_000_000_000).into(); - let ns_to_dur = |obj: PyObjectRef| { + let ns_to_time = |obj: PyObjectRef| { let divmod = vm._divmod(&obj, &ns_in_sec)?; let (div, rem) = divmod .downcast_ref::() @@ -1874,16 +2009,31 @@ pub(super) mod _os { divmod.class().name() )) })?; - let secs = div.try_index(vm)?.try_to_primitive(vm)?; - let ns = rem.try_index(vm)?.try_to_primitive(vm)?; - Ok(Duration::new(secs, ns)) + let seconds = file_time_seconds(&div, vm)?; + let rem = rem.try_index(vm)?; + let nanoseconds = rem.try_to_primitive::(vm).map_err(|err| { + if err.fast_isinstance(vm.ctx.exceptions.overflow_error) { + vm.new_overflow_error("Python int too large to convert to C long") + } else { + err + } + })?; + Ok(FileTime { + seconds, + nanoseconds, + }) }; - // TODO: do validation to make sure this doesn't.. underflow? - (ns_to_dur(a)?, ns_to_dur(m)?) + (ns_to_time(a)?, ns_to_time(m)?) } (None, None) => { let now = SystemTime::now(); let now = now.duration_since(SystemTime::UNIX_EPOCH).unwrap(); + let now = FileTime { + seconds: now.as_secs().try_into().map_err(|_| { + vm.new_overflow_error("timestamp out of range for platform time_t") + })?, + nanoseconds: now.subsec_nanos() as libc::c_long, + }; (now, now) } (Some(_), Some(_)) => { @@ -1897,8 +2047,8 @@ pub(super) mod _os { fn utime_impl( path: OsPath, - acc: Duration, - modif: Duration, + acc: FileTime, + modif: FileTime, dir_fd: DirFd<'_, { UTIME_DIR_FD as usize }>, _follow_symlinks: FollowSymlinks, vm: &VirtualMachine, @@ -1938,8 +2088,15 @@ pub(super) mod _os { )); } - crate::host_env::os::set_file_times(&path, acc, modif) - .map_err(|err| OSErrorBuilder::with_filename(&err, path, vm)) + let wide_path = path.to_wide_cstring(vm)?; + host_nt::set_file_times( + &wide_path, + acc.seconds, + acc.nanoseconds.into(), + modif.seconds, + modif.nanoseconds.into(), + ) + .map_err(|err| OSErrorBuilder::with_filename(&err, path, vm)) } } @@ -2010,15 +2167,15 @@ pub(super) mod _os { #[cfg(target_os = "linux")] #[derive(FromArgs)] struct CopyFileRangeArgs<'fd> { - #[pyarg(positional)] + #[pyarg(any)] src: crt_fd::Borrowed<'fd>, - #[pyarg(positional)] + #[pyarg(any)] dst: crt_fd::Borrowed<'fd>, - #[pyarg(positional)] + #[pyarg(any)] count: i64, - #[pyarg(any, default)] + #[pyarg(any, default = None)] offset_src: Option, - #[pyarg(any, default)] + #[pyarg(any, default = None)] offset_dst: Option, } @@ -2056,8 +2213,25 @@ pub(super) mod _os { } #[pyfunction] - pub(crate) fn ftruncate(fd: crt_fd::Borrowed<'_>, length: crt_fd::Offset) -> io::Result<()> { - crt_fd::ftruncate(fd, length) + fn ftruncate(fd: i32, length: crt_fd::Offset, vm: &VirtualMachine) -> PyResult<()> { + ftruncate_impl(fd, length, vm) + } + + fn ftruncate_impl( + fd: crt_fd::Raw, + length: crt_fd::Offset, + vm: &VirtualMachine, + ) -> PyResult<()> { + use crate::host_env::os::ErrorExt; + + vm.audit("os.truncate", || (fd, length))?; + loop { + match vm.allow_threads(|| crt_fd::ftruncate_raw(fd, length)) { + Ok(()) => return Ok(()), + Err(err) if err.posix_errno() == libc::EINTR => vm.check_signals()?, + Err(err) => return Err(err.into_pyexception(vm)), + } + } } #[derive(FromArgs)] @@ -2065,17 +2239,35 @@ pub(super) mod _os { #[pyarg(any)] path: PyObjectRef, #[pyarg(any)] - length: crt_fd::Offset, + length: PyObjectRef, } #[pyfunction] fn truncate(args: TruncateArgs, vm: &VirtualMachine) -> PyResult<()> { let TruncateArgs { path, length } = args; - match path.clone().try_into_value::>(vm) { - Ok(fd) => return ftruncate(fd, length).map_err(|e| e.into_pyexception(vm)), - Err(e) if e.fast_isinstance(vm.ctx.exceptions.warning) => return Err(e), - Err(_) => {} - } + let index = + if path.downcast_ref::().is_some() || path.downcast_ref::().is_some() { + None + } else { + path.try_index_opt(vm) + }; + let path = if let Some(index) = index { + super::warn_if_bool_fd(&path, vm)?; + Either::A(index?.try_to_primitive::(vm)?) + } else { + Either::B( + PathConverter::new() + .function("truncate") + .try_path_inner(path, true, vm)?, + ) + }; + let length = length.try_into_value::(vm)?; + let path = match path { + Either::A(fd) => { + return ftruncate_impl(fd, length, vm); + } + Either::B(path) => path, + }; #[cold] fn error( @@ -2086,14 +2278,15 @@ pub(super) mod _os { OSErrorBuilder::with_filename(&error, path, vm) } - let path = OsPath::try_from_object(vm, path)?; + let filename = path.filename(vm)?; + vm.audit("os.truncate", || (filename, length))?; + // TODO: just call libc::truncate() on POSIX let f = match crate::host_env::fs::open_write(&path) { Ok(f) => f, Err(e) => return Err(error(vm, e, path)), }; f.set_len(length as u64).map_err(|e| error(vm, e, path))?; - drop(f); Ok(()) } @@ -2153,12 +2346,15 @@ pub(super) mod _os { } #[pyfunction] - fn device_encoding(fd: DeviceEncodingArgs, _vm: &VirtualMachine) -> Option { + fn device_encoding(fd: DeviceEncodingArgs, vm: &VirtualMachine) -> Option { let fd = fd.fd; - if !isatty(fd) { + if cfg!(not(windows)) && !isatty(fd) { return None; } + if cfg!(not(windows)) && vm.state.config.settings.utf8_mode > 0 { + return Some("utf-8".to_owned()); + } rustpython_host_env::os::device_encoding(fd) } @@ -2295,7 +2491,28 @@ pub(super) mod _os { let mut supports = super::platform::module::support_funcs(); supports.extend(vec![ SupportFunc::new("open", Some(false), Some(OPEN_DIR_FD), Some(false)), - SupportFunc::new("access", Some(false), Some(false), None), + SupportFunc::new( + "access", + Some(false), + Some(ACCESS_DIR_FD), + Some(cfg!(all( + unix, + not(any( + target_os = "espidf", + target_os = "horizon", + target_os = "vita", + )), + ))), + ) + .with_effective_ids(Some(cfg!(all( + unix, + not(any( + target_os = "android", + target_os = "espidf", + target_os = "horizon", + target_os = "vita", + )), + )))), SupportFunc::new("chdir", None, Some(false), Some(false)), // chflags Some, None Some SupportFunc::new("link", Some(false), Some(false), Some(cfg!(unix))), @@ -2311,6 +2528,7 @@ pub(super) mod _os { SupportFunc::new("rmdir", Some(false), Some(RMDIR_DIR_FD), Some(false)), SupportFunc::new("scandir", Some(SCANDIR_FD), Some(false), Some(false)), SupportFunc::new("stat", Some(true), Some(STAT_DIR_FD), Some(true)), + SupportFunc::new("lstat", Some(false), Some(STAT_DIR_FD), Some(false)), SupportFunc::new("fstat", Some(false), Some(false), Some(false)), SupportFunc::new("symlink", Some(false), Some(SYMLINK_DIR_FD), Some(false)), SupportFunc::new("truncate", Some(true), Some(false), Some(false)), @@ -2326,7 +2544,6 @@ pub(super) mod _os { supports } } -pub(crate) use _os::ftruncate; pub(crate) struct SupportFunc { name: &'static str, @@ -2336,6 +2553,7 @@ pub(crate) struct SupportFunc { fd: Option, dir_fd: Option, follow_symlinks: Option, + effective_ids: Option, } impl SupportFunc { @@ -2350,8 +2568,14 @@ impl SupportFunc { fd, dir_fd, follow_symlinks, + effective_ids: None, } } + + pub(crate) const fn with_effective_ids(mut self, effective_ids: Option) -> Self { + self.effective_ids = effective_ids; + self + } } pub fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { @@ -2359,6 +2583,7 @@ pub fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { let supports_fd = PySet::default().into_ref(&vm.ctx); let supports_dir_fd = PySet::default().into_ref(&vm.ctx); let supports_follow_symlinks = PySet::default().into_ref(&vm.ctx); + let supports_effective_ids = PySet::default().into_ref(&vm.ctx); for support in support_funcs { let func_obj = module.get_attr(support.name, vm)?; if support.fd.unwrap_or(false) { @@ -2368,7 +2593,10 @@ pub fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { supports_dir_fd.clone().add(func_obj.clone(), vm)?; } if support.follow_symlinks.unwrap_or(false) { - supports_follow_symlinks.clone().add(func_obj, vm)?; + supports_follow_symlinks.clone().add(func_obj.clone(), vm)?; + } + if support.effective_ids.unwrap_or(false) { + supports_effective_ids.clone().add(func_obj, vm)?; } } @@ -2376,32 +2604,43 @@ pub fn module_exec(vm: &VirtualMachine, module: &Py) -> PyResult<()> { "supports_fd" => supports_fd, "supports_dir_fd" => supports_dir_fd, "supports_follow_symlinks" => supports_follow_symlinks, + "supports_effective_ids" => supports_effective_ids, "error" => vm.ctx.exceptions.os_error.to_owned(), }); Ok(()) } -/// Convert a mapping (e.g. os._Environ) to a plain dict for use by execve/posix_spawn. -/// -/// For `os._Environ`, accesses the internal `_data` dict directly at the Rust level. -/// This avoids Python-level method calls that can deadlock after fork() when -/// parking_lot locks are held by threads that no longer exist. +/// The existing direct-dict path also avoids Python callbacks for os._Environ +/// after fork, when locks inherited from vanished threads may still be held. #[cfg(any(unix, windows))] -pub(crate) fn envobj_to_dict( - env: crate::function::ArgMapping, +pub(crate) fn envobj_fast_dict( + env: &crate::function::ArgMapping, vm: &VirtualMachine, -) -> PyResult { +) -> Option { let obj = env.obj(); if let Some(dict) = obj.downcast_ref_if_exact::(vm) { - return Ok(dict.to_owned()); + return Some(dict.to_owned()); } if let Some(inst_dict) = obj.dict() && let Ok(Some(data)) = inst_dict.get_item_opt("_data", vm) && let Some(dict) = data.downcast_ref_if_exact::(vm) { - return Ok(dict.to_owned()); + return Some(dict.to_owned()); } + None +} + +/// Convert a mapping to a plain dict for Windows execve. +#[cfg(windows)] +pub(crate) fn envobj_to_dict( + env: crate::function::ArgMapping, + vm: &VirtualMachine, +) -> PyResult { + if let Some(dict) = envobj_fast_dict(&env, vm) { + return Ok(dict); + } + let obj = env.obj(); let keys = vm.call_method(obj, "keys", ())?; let dict = vm.ctx.new_dict(); for key in keys.get_iter(vm)?.into_iter::(vm) { diff --git a/crates/vm/src/stdlib/posix.rs b/crates/vm/src/stdlib/posix.rs index 1f123812fc2..31cf400776b 100644 --- a/crates/vm/src/stdlib/posix.rs +++ b/crates/vm/src/stdlib/posix.rs @@ -3,10 +3,14 @@ pub(crate) use module::module_def; pub use rustpython_host_env::posix::set_inheritable; +#[cfg(target_os = "linux")] +mod xattr; #[pymodule(name = "posix", with( super::os::_os, super::posix_unix_like::_posix_unix_like, + #[cfg(target_os = "linux")] + xattr::_xattr, #[cfg(any( target_os = "linux", target_os = "netbsd", @@ -17,14 +21,15 @@ pub use rustpython_host_env::posix::set_inheritable; ))] pub mod module { use crate::{ - AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine, + AsObject, Py, PyObjectRef, PyResult, VirtualMachine, builtins::{PyBytesRef, PyDictRef, PyInt, PyListRef, PyTuple, PyTupleRef, PyUtf8Str}, - convert::{IntoPyException, ToPyException, ToPyObject, TryFromObject}, + convert::{IntoPyException, ToPyObject, TryFromObject}, exceptions::OSErrorBuilder, function::{ArgBytesLike, ArgMapping, Either, OptionalArg, PySsize}, ospath::{OsPath, OsPathOrFd}, stdlib::os::{ - _os, DirFd, FollowSymlinks, SupportFunc, SymlinkArgs, fs_metadata, warn_if_bool_fd, + _os, AccessArgs, DirFd, FollowSymlinks, SupportFunc, SymlinkArgs, fs_metadata, + warn_if_bool_fd, }, }; #[cfg(any( @@ -36,7 +41,7 @@ pub mod module { use crate::{builtins::PyUtf8StrRef, utils::ToCString}; use alloc::ffi::CString; use core::ffi::CStr; - use rustpython_host_env::os::ffi::OsStringExt; + use rustpython_host_env::os::{AT_FDCWD, ffi::OsStringExt}; use rustpython_host_env::posix as host_posix; use std::{ fs, io, @@ -49,6 +54,10 @@ pub mod module { #[pyattr] use rustpython_host_env::posix::PIDFD_NONBLOCK; + #[cfg(all(target_os = "linux", target_env = "gnu"))] + #[pyattr] + use rustpython_host_env::posix::NODEV; + #[cfg(target_os = "macos")] #[pyattr] use rustpython_host_env::posix::{ @@ -393,35 +402,58 @@ pub mod module { .collect()) } - #[derive(FromArgs)] - pub(super) struct AccessArgs<'a> { - #[pyarg(any)] - path: OsPath, - #[pyarg(any)] - mode: u8, - #[pyarg(flatten)] - dir_fd: DirFd<'a, 0>, - #[pyarg(named, default)] - effective_ids: bool, - #[pyarg(flatten)] - follow_symlinks: FollowSymlinks, - } - + #[allow(clippy::unnecessary_wraps)] #[pyfunction] - pub(super) fn access(args: AccessArgs<'_>, vm: &VirtualMachine) -> PyResult { - let [] = args.dir_fd.0; + pub(super) fn access( + args: AccessArgs<'_>, + #[allow(unused_variables)] vm: &VirtualMachine, + ) -> PyResult { + #[cfg(any( + target_os = "android", + target_os = "espidf", + target_os = "horizon", + target_os = "vita", + ))] if args.effective_ids { return Err( vm.new_not_implemented_error("access: effective_ids unavailable on this platform") ); } + #[cfg(any(target_os = "espidf", target_os = "horizon", target_os = "vita",))] if !args.follow_symlinks.0 { return Err(vm.new_not_implemented_error( "access: follow_symlinks unavailable on this platform", )); } - rustpython_host_env::posix::check_access(args.path.as_ref(), args.mode) - .map_err(|err| err.to_pyexception(vm)) + + #[cfg(all( + unix, + not(any( + target_os = "android", + target_os = "espidf", + target_os = "horizon", + target_os = "vita", + )), + ))] + let dir_fd = args.dir_fd.get_opt(); + #[cfg(not(all( + unix, + not(any( + target_os = "android", + target_os = "espidf", + target_os = "horizon", + target_os = "vita", + )), + )))] + let dir_fd = None; + + Ok(rustpython_host_env::posix::check_access( + dir_fd, + args.path.as_ref(), + args.mode, + args.effective_ids, + args.follow_symlinks.0, + )) } #[pyfunction] @@ -677,7 +709,12 @@ pub mod module { } } - fn py_os_before_fork(vm: &VirtualMachine) { + #[cfg(feature = "threading")] + use crate::vm::stop_the_world::ForkStopTheWorld; + #[cfg(not(feature = "threading"))] + struct ForkStopTheWorld; + + fn py_os_before_fork(vm: &VirtualMachine) -> ForkStopTheWorld { let before_forkers: Vec = vm.state.before_forkers.lock().clone(); // functions must be executed in reversed order as they are registered // only for before_forkers, refer: test_register_at_fork in test_posix @@ -688,10 +725,21 @@ pub mod module { crate::stdlib::_imp::acquire_imp_lock_for_fork(vm); #[cfg(feature = "threading")] - vm.state.stop_the_world.stop_the_world(&vm.state); + { + ForkStopTheWorld::new() + } + #[cfg(not(feature = "threading"))] + { + ForkStopTheWorld + } } - fn py_os_after_fork_child(vm: &VirtualMachine) { + fn py_os_after_fork_child(vm: &VirtualMachine, _stopped: &mut ForkStopTheWorld) { + #[cfg(feature = "threading")] + unsafe { + _stopped.begin_child_repair(); + } + // The interpreter registry is reachable from every thread, so repair it // before anything enumerates interpreters. #[cfg(all(unix, feature = "threading"))] @@ -707,20 +755,14 @@ pub mod module { // if we try to acquire them. This must happen before anything else. #[cfg(feature = "threading")] reinit_locks_after_fork(vm); + #[cfg(feature = "threading")] + _stopped.retain_thread_slots(&vm.state); // The collector stops every interpreter, so interpreters other than the // forking one must be repaired too; otherwise the child's first // collection waits for threads that did not survive the fork. #[cfg(all(unix, feature = "threading"))] - reinit_other_interpreters_after_fork(vm); - - // Reinit per-object IO buffer locks on std streams. - // BufferedReader/Writer/TextIOWrapper use PyThreadMutex which can be - // held by dead parent threads, causing deadlocks on any IO in the child. - #[cfg(feature = "threading")] - unsafe { - crate::stdlib::_io::reinit_std_streams_after_fork(vm) - }; + reinit_other_interpreters_after_fork(vm, _stopped); // Phase 2: Reset low-level atomic state (no locks needed). crate::signal::clear_after_fork(); @@ -751,6 +793,8 @@ pub mod module { crate::object::qsbr::QSBR.reset_after_fork() }; + vm.state.reinit_running_main(); + // Phase 3: Clean up thread state. Locks are now reinit'd so we can // acquire them normally instead of using try_lock(). #[cfg(feature = "threading")] @@ -763,10 +807,19 @@ pub mod module { crate::stdlib::_imp::after_fork_child_imp_lock_release() }; - // Initialize signal handlers for the child's main thread. - // When forked from a worker thread, the OnceCell is empty. - vm.signal_handlers - .get_or_init(crate::signal::SignalHandlers::default); + #[cfg(feature = "threading")] + _stopped.finish_child_repair(); + + // Reinit per-object IO buffer locks on std streams. + // BufferedReader/Writer/TextIOWrapper use PyThreadMutex which can be + // held by dead parent threads, causing deadlocks on any IO in the child. + // Lookup can call Python (for example sys.__getattr__), so core repair + // and transaction release must precede it. Such hooks must still avoid + // using inherited IO locks before this existing repair completes. + #[cfg(feature = "threading")] + unsafe { + crate::stdlib::_io::reinit_std_streams_after_fork(vm) + }; // Phase 4: Run Python-level at-fork callbacks. let after_forkers_child: Vec = vm.state.after_forkers_child.lock().clone(); @@ -792,6 +845,7 @@ pub mod module { reinit_mutex_after_fork(&vm.state.global_profile_func); reinit_mutex_after_fork(&vm.state.type_mutex); reinit_mutex_after_fork(&vm.state.monitoring); + reinit_mutex_after_fork(&vm.state.signal_handlers); // PyGlobalState parking_lot::Mutex locks reinit_mutex_after_fork(&vm.state.thread_frames); @@ -825,7 +879,7 @@ pub mod module { /// # Safety /// Must only be called after `fork()` in the child, when no other threads exist. #[cfg(all(unix, feature = "threading"))] - fn reinit_other_interpreters_after_fork(vm: &VirtualMachine) { + fn reinit_other_interpreters_after_fork(vm: &VirtualMachine, stopped: &mut ForkStopTheWorld) { use rustpython_common::lock::reinit_mutex_after_fork; for state in crate::vm::runtime::live_interpreter_states() { @@ -842,6 +896,7 @@ pub mod module { reinit_mutex_after_fork(&state.global_profile_func); reinit_mutex_after_fork(&state.type_mutex); reinit_mutex_after_fork(&state.monitoring); + reinit_mutex_after_fork(&state.signal_handlers); reinit_mutex_after_fork(&state.thread_frames); reinit_mutex_after_fork(&state.thread_handles); reinit_mutex_after_fork(&state.shutdown_handles); @@ -851,6 +906,7 @@ pub mod module { } state.stop_the_world.reset_after_fork(); + stopped.retain_thread_slots(&state); // Every thread registered here belongs to the parent, including any // slot the forking thread itself registered before the fork. @@ -862,9 +918,9 @@ pub mod module { crate::vm::thread::purge_other_interpreter_slots_after_fork(vm.state.interpreter_id); } - fn py_os_after_fork_parent(vm: &VirtualMachine) { + fn py_os_after_fork_parent(vm: &VirtualMachine, _stopped: &mut ForkStopTheWorld) { #[cfg(feature = "threading")] - vm.state.stop_the_world.start_the_world(&vm.state); + _stopped.restart(); #[cfg(feature = "threading")] crate::stdlib::_imp::release_imp_lock_after_fork_parent(); @@ -881,7 +937,11 @@ pub mod module { /// Warn if forking from a multi-threaded process. /// `num_os_threads` should be captured before parent after-fork hooks run. - fn warn_if_multi_threaded(name: &str, num_os_threads: isize, vm: &VirtualMachine) { + fn warn_if_multi_threaded( + name: &str, + num_os_threads: isize, + vm: &VirtualMachine, + ) -> PyResult<()> { let num_threads = if num_os_threads > 0 { num_os_threads as usize } else { @@ -895,7 +955,7 @@ pub mod module { .and_then(|m| m.get_item("threading", vm)) { Ok(m) => m, - Err(_) => return, + Err(_) => return Ok(()), }; let active = threading.get_attr("_active", vm).ok(); let limbo = threading.get_attr("_limbo", vm).ok(); @@ -920,10 +980,9 @@ pub mod module { ); // Match PyErr_WarnFormat(..., stacklevel=1) in CPython. - // Best effort: ignore failures like CPython does in this path. - let _ = - crate::stdlib::_warnings::warn(vm.ctx.exceptions.deprecation_warning, msg, 1, vm); + crate::stdlib::_warnings::warn(vm.ctx.exceptions.deprecation_warning, msg, 1, vm)?; } + Ok(()) } #[pyfunction] @@ -946,25 +1005,25 @@ pub mod module { vm.audit("os.fork", || ())?; - py_os_before_fork(vm); + let mut stopped = py_os_before_fork(vm); let pid = rustpython_host_env::posix::fork(); match pid { Ok(0) => { - py_os_after_fork_child(vm); + py_os_after_fork_child(vm, &mut stopped); Ok(0) } Ok(pid) => { // Capture this before parent after-fork hooks in case those // hooks start threads. let num_os_threads = get_number_of_os_threads(); - py_os_after_fork_parent(vm); + py_os_after_fork_parent(vm, &mut stopped); // Warn only after parent callback path resumes the world. - warn_if_multi_threaded("fork", num_os_threads, vm); + warn_if_multi_threaded("fork", num_os_threads, vm)?; Ok(pid) } Err(err) => { - py_os_after_fork_parent(vm); + py_os_after_fork_parent(vm, &mut stopped); Err(err.into_pyexception(vm)) } } @@ -991,27 +1050,112 @@ pub mod module { vm.audit("os.forkpty", || ())?; - py_os_before_fork(vm); + let mut stopped = py_os_before_fork(vm); let result = rustpython_host_env::posix::forkpty(); match result { Ok((0, master)) => { - py_os_after_fork_child(vm); + py_os_after_fork_child(vm, &mut stopped); Ok((0, master)) } Ok((pid, master)) => { let num_os_threads = get_number_of_os_threads(); - py_os_after_fork_parent(vm); - warn_if_multi_threaded("forkpty", num_os_threads, vm); + py_os_after_fork_parent(vm, &mut stopped); + warn_if_multi_threaded("forkpty", num_os_threads, vm)?; Ok((pid, master)) } Err(err) => { - py_os_after_fork_parent(vm); + py_os_after_fork_parent(vm, &mut stopped); Err(err.into_pyexception(vm)) } } } + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] + struct MkfifoPath(OsPath); + + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] + impl TryFromObject for MkfifoPath { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + crate::ospath::PathConverter::new() + .function("mkfifo") + .try_path(obj, vm) + .map(Self) + } + } + + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] + struct MkfifoMode(i32); + + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] + impl TryFromObject for MkfifoMode { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let mode = obj.try_index(vm)?; + i32::try_from(mode.as_bigint()) + .map(Self) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C int")) + } + } + + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] + #[derive(FromArgs)] + struct MkfifoArgs { + #[pyarg(any)] + path: MkfifoPath, + #[pyarg(any, default = MkfifoMode(0o666), py_default = "438")] + mode: MkfifoMode, + #[pyarg(named, default = None)] + dir_fd: Option, + } + + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] + #[pyfunction] + fn mkfifo(args: MkfifoArgs, vm: &VirtualMachine) -> PyResult<()> { + let c_path = args.path.0.into_cstring(vm)?; + let mode = args.mode.0 as libc::mode_t; + // Keep a raw C int: even -1 is valid with an absolute path, for which + // mkfifoat ignores dir_fd. BorrowedFd cannot represent that value. + let dir_fd = match args.dir_fd { + Some(fd) => { + warn_if_bool_fd(&fd, vm)?; + let fd = fd.try_index_opt(vm).unwrap_or_else(|| { + Err(vm.new_type_error(format!( + "argument should be integer or None, not {}", + fd.class().name() + ))) + })?; + let fd = i32::try_from(fd.as_bigint()).map_err(|_| { + let message = if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + "fd is less than minimum" + } else { + "fd is greater than maximum" + }; + vm.new_overflow_error(message) + })?; + (fd != rustpython_host_env::os::AT_FDCWD).then_some(fd) + } + None => None, + }; + if dir_fd.is_some() && !host_posix::has_mkfifoat() { + return Err(vm.new_not_implemented_error("dir_fd unavailable on this platform")); + } + + loop { + let result = vm.allow_threads(|| { + #[cfg(not(target_os = "android"))] + if let Some(dir_fd) = dir_fd { + return host_posix::mkfifoat(dir_fd, &c_path, mode); + } + host_posix::mkfifo(&c_path, mode) + }); + match result { + Ok(()) => return Ok(()), + Err(err) if err.raw_os_error() == Some(libc::EINTR) => vm.check_signals()?, + Err(err) => return Err(err.into_pyexception(vm)), + } + } + } + #[cfg(not(target_os = "redox"))] const MKNOD_DIR_FD: bool = cfg!(not(target_vendor = "apple")); @@ -1129,6 +1273,7 @@ pub mod module { match vm.allow_threads(|| rustpython_host_env::posix::pread(fd, &mut buffer, offset)) { Ok(n) => { buffer.truncate(n); + buffer.shrink_to_fit(); return Ok(vm.ctx.new_bytes(buffer)); } Err(err) if err.raw_os_error() == Some(libc::EINTR) => { @@ -1184,33 +1329,39 @@ pub mod module { fn _chmod( path: OsPath, - dir_fd: DirFd<'_, 0>, + dir_fd: i32, mode: u32, - follow_symlinks: FollowSymlinks, + follow_symlinks: bool, vm: &VirtualMachine, ) -> PyResult<()> { - let [] = dir_fd.0; - #[cfg(all( - unix, - not(target_os = "redox"), - not(any(target_os = "macos", target_os = "freebsd", target_os = "netbsd")) - ))] - if !follow_symlinks.0 { + #[cfg(target_os = "redox")] + let _ = dir_fd; + #[cfg(not(target_os = "redox"))] + if dir_fd != AT_FDCWD || !follow_symlinks { let err_path = path.clone(); let c_path = path.into_cstring(vm)?; + let flags = if follow_symlinks { + 0 + } else { + libc::AT_SYMLINK_NOFOLLOW + }; return rustpython_host_env::posix::fchmodat( - libc::AT_FDCWD, + dir_fd, &c_path, mode as libc::mode_t, - libc::AT_SYMLINK_NOFOLLOW, + flags, ) .map_err(|err| { let enotsup = err.raw_os_error() == Some(libc::EOPNOTSUPP) || err.raw_os_error() == Some(libc::ENOTSUP); - if enotsup { - vm.new_not_implemented_error( - "chmod: follow_symlinks unavailable on this platform".to_owned(), - ) + if !follow_symlinks && enotsup { + if dir_fd != AT_FDCWD { + vm.new_value_error("chmod: cannot use dir_fd and follow_symlinks together") + } else { + vm.new_not_implemented_error( + "chmod: follow_symlinks unavailable on this platform".to_owned(), + ) + } } else { OSErrorBuilder::with_filename(&err, err_path, vm) } @@ -1219,7 +1370,7 @@ pub mod module { let err_path = path.clone(); let body = move || { use std::os::unix::fs::PermissionsExt; - let meta = fs_metadata(&path, follow_symlinks.0)?; + let meta = fs_metadata(&path, follow_symlinks)?; let mut permissions = meta.permissions(); permissions.set_mode(mode); fs::set_permissions(&path, permissions) @@ -1232,19 +1383,59 @@ pub mod module { rustpython_host_env::posix::fchmod(fd, mode).map_err(|err| err.into_pyexception(vm)) } + // Absolute paths ignore dir_fd, so even -1 must reach fchmodat unchanged. #[cfg(not(target_os = "redox"))] - #[pyfunction] - fn chmod( - path: OsPathOrFd<'_>, - dir_fd: DirFd<'_, 0>, + struct ChmodDirFd(i32); + + #[cfg(not(target_os = "redox"))] + impl TryFromObject for ChmodDirFd { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + warn_if_bool_fd(&obj, vm)?; + let fd = obj.try_index_opt(vm).unwrap_or_else(|| { + Err(vm.new_type_error(format!( + "argument should be integer or None, not {}", + obj.class().name() + ))) + })?; + i32::try_from(fd.as_bigint()).map(Self).map_err(|_| { + let message = if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + "fd is less than minimum" + } else { + "fd is greater than maximum" + }; + vm.new_overflow_error(message) + }) + } + } + + #[cfg(not(target_os = "redox"))] + #[derive(FromArgs)] + struct ChmodArgs<'fd> { + #[pyarg(any)] + path: OsPathOrFd<'fd>, + #[pyarg(any)] mode: u32, - follow_symlinks: FollowSymlinks, - vm: &VirtualMachine, - ) -> PyResult<()> { + #[pyarg(named, default = None)] + dir_fd: Option, + // CPython writes the platform expression; on posix it is always true. + #[pyarg(named, default = true, py_default = "(os.name != 'nt')")] + follow_symlinks: bool, + } + + #[cfg(not(target_os = "redox"))] + #[pyfunction] + fn chmod(args: ChmodArgs<'_>, vm: &VirtualMachine) -> PyResult<()> { + let ChmodArgs { + path, + mode, + dir_fd, + follow_symlinks, + } = args; + let dir_fd = dir_fd.map_or(AT_FDCWD, |fd| fd.0); match path { OsPathOrFd::Path(path) => { #[cfg(any(target_os = "macos", target_os = "freebsd", target_os = "netbsd",))] - if !follow_symlinks.0 && dir_fd == Default::default() { + if !follow_symlinks && dir_fd == AT_FDCWD { return lchmod(LchmodArgs { path, mode }, vm); } _chmod(path, dir_fd, mode, follow_symlinks, vm) @@ -1254,15 +1445,30 @@ pub mod module { } #[cfg(target_os = "redox")] - #[pyfunction] - fn chmod( + #[derive(FromArgs)] + struct ChmodArgs { + #[pyarg(any)] path: OsPath, - dir_fd: DirFd<0>, + #[pyarg(any)] mode: u32, - follow_symlinks: FollowSymlinks, - vm: &VirtualMachine, - ) -> PyResult<()> { - _chmod(path, dir_fd, mode, follow_symlinks, vm) + #[pyarg(flatten)] + dir_fd: DirFd<'static, 0>, + // CPython writes the platform expression; on posix it is always true. + #[pyarg(named, default = true, py_default = "(os.name != 'nt')")] + follow_symlinks: bool, + } + + #[cfg(target_os = "redox")] + #[pyfunction] + fn chmod(args: ChmodArgs, vm: &VirtualMachine) -> PyResult<()> { + let ChmodArgs { + path, + mode, + dir_fd, + follow_symlinks, + } = args; + let [] = dir_fd.0; + _chmod(path, AT_FDCWD, mode, follow_symlinks, vm) } #[cfg(not(target_os = "redox"))] @@ -1336,6 +1542,52 @@ pub mod module { env: ArgMapping, } + fn execve_environment(env: &ArgMapping, vm: &VirtualMachine) -> PyResult> { + fn make_entry( + key: PyObjectRef, + value: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult { + let key_bytes = OsPath::try_from_object(vm, key.clone())?.into_bytes(); + let value_bytes = OsPath::try_from_object(vm, value.clone())?.into_bytes(); + if key_bytes.is_empty() || memchr::memchr(b'=', &key_bytes).is_some() { + return Err(vm.new_value_error("illegal environment variable name")); + } + let mut entry = key_bytes; + entry.push(b'='); + entry.extend_from_slice(&value_bytes); + let entry = CString::new(entry).map_err(|err| err.into_pyexception(vm)); + drop((key, value)); + entry + } + + if let Some(dict) = crate::stdlib::os::envobj_fast_dict(env, vm) { + // Snapshot references before any path conversion can mutate the mapping. + #[allow(clippy::needless_collect, reason = "the snapshot is intentional")] + let pairs: Vec<_> = dict.into_iter().collect(); + return pairs + .into_iter() + .map(|(key, value)| make_entry(key, value, vm)) + .collect(); + } + + // CPython obtains length, keys and values separately, rather than + // looking up each key. Exact lists returned by user code remain live. + let len = env.mapping().length(vm)?; + let keys = PyListRef::try_from_object(vm, env.mapping().keys(vm)?)?; + let values = PyListRef::try_from_object(vm, env.mapping().values(vm)?)?; + let mut result = Vec::new(); + for index in 0..len { + // Acquire owned references before __fspath__ can mutate either list. + let key = { keys.borrow_vec().get(index).cloned() } + .ok_or_else(|| vm.new_index_error("list index out of range"))?; + let value = { values.borrow_vec().get(index).cloned() } + .ok_or_else(|| vm.new_index_error("list index out of range"))?; + result.push(make_entry(key, value, vm)?); + } + Ok(result) + } + #[pyfunction] fn execve(args: ExecveArgs, vm: &VirtualMachine) -> PyResult<()> { let ExecveArgs { path, argv, env } = args; @@ -1359,26 +1611,7 @@ pub mod module { return Err(vm.new_value_error("execve() arg 2 first element cannot be empty")); } - let env = crate::stdlib::os::envobj_to_dict(env, vm)?; - let env = env - .into_iter() - .map(|(k, v)| -> PyResult<_> { - let (key, value) = ( - OsPath::try_from_object(vm, k)?.into_bytes(), - OsPath::try_from_object(vm, v)?.into_bytes(), - ); - - if key.is_empty() || memchr::memchr(b'=', &key).is_some() { - return Err(vm.new_value_error("illegal environment variable name")); - } - - let mut entry = key; - entry.push(b'='); - entry.extend_from_slice(&value); - - CString::new(entry).map_err(|err| err.into_pyexception(vm)) - }) - .collect::, _>>()?; + let env = execve_environment(&env, vm)?; let env: Vec<&CStr> = env.iter().map(|entry| entry.as_c_str()).collect(); @@ -1487,47 +1720,53 @@ pub mod module { rustpython_host_env::posix::tcsetpgrp(fd, pgid).map_err(|err| err.into_pyexception(vm)) } - fn try_from_id(vm: &VirtualMachine, obj: &PyObject, typ_name: &str) -> PyResult { - use core::cmp::Ordering; - let i = obj - .try_to_ref::(vm) - .map_err(|_| { - vm.new_type_error(format!( - "an integer is required (got type {})", - obj.class().name() - )) - })? - .try_to_primitive::(vm)?; - - match i.cmp(&-1) { - Ordering::Greater => Ok(i.try_into().map_err(|_| { - vm.new_overflow_error(format!("{typ_name} is larger than maximum")) - })?), - Ordering::Less => { - Err(vm.new_overflow_error(format!("{typ_name} is less than minimum"))) + fn try_from_id(vm: &VirtualMachine, obj: PyObjectRef, typ_name: &str) -> PyResult { + let index = crate::function::ArgIndex::try_from_object(vm, obj.clone()).map_err(|_| { + let name = obj.class().slot_name().to_string(); + let name = &name[..name.floor_char_boundary(200.min(name.len()))]; + vm.new_type_error(format!("{typ_name} should be integer, not {name}")) + })?; + let index = index.into_int_ref(); + let value = index.as_bigint(); + // CPython first converts through C long, including its -1 sentinel. + // Truncation in this branch is reported as underflow, even for positives. + if let Ok(value) = libc::c_long::try_from(value) { + if value == -1 { + // -1 means does not change the value + // In CPython, this is `(uid_t) -1`, rustc gets mad when we try to declare + // a negative unsigned integer :). + return Ok(u32::MAX); } - // -1 means does not change the value - // In CPython, this is `(uid_t) -1`, rustc gets mad when we try to declare - // a negative unsigned integer :). - Ordering::Equal => Ok(-1i32 as u32), + return u32::try_from(value) + .map_err(|_| vm.new_overflow_error(format!("{typ_name} is less than minimum"))); + } + if value < &0.into() { + return Err(vm.new_overflow_error(format!("{typ_name} is less than minimum"))); } + // A positive value outside signed long may still fit unsigned long, + // but must not become the sentinel or be truncated to the ID width. + libc::c_ulong::try_from(value) + .ok() + .and_then(|value| u32::try_from(value).ok()) + .filter(|&value| value != u32::MAX) + .ok_or_else(|| vm.new_overflow_error(format!("{typ_name} is greater than maximum"))) } #[derive(Clone, Copy)] - struct RawUid(u32); + pub struct RawUid(pub u32); #[derive(Clone, Copy)] - struct RawGid(u32); + pub struct RawGid(pub u32); impl TryFromObject for RawUid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, &obj, "uid").map(Self) + try_from_id(vm, obj, "uid").map(Self) } } impl TryFromObject for RawGid { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { - try_from_id(vm, &obj, "gid").map(Self) + try_from_id(vm, obj, "gid").map(Self) } } @@ -1998,14 +2237,21 @@ pub mod module { rustpython_host_env::posix::wtermsig(status.status) } + #[cfg(target_os = "linux")] + #[derive(FromArgs)] + struct PidfdOpenArgs { + #[pyarg(any)] + pid: libc::pid_t, + #[pyarg(any, default)] + flags: u32, + } + #[cfg(target_os = "linux")] #[pyfunction] fn pidfd_open( - pid: libc::pid_t, - flags: OptionalArg, + PidfdOpenArgs { pid, flags }: PidfdOpenArgs, vm: &VirtualMachine, ) -> PyResult { - let flags = flags.unwrap_or(0); rustpython_host_env::posix::pidfd_open(pid, flags).map_err(|err| err.into_pyexception(vm)) } @@ -2166,8 +2412,8 @@ pub mod module { vec![ SupportFunc::new( "chmod", - Some(false), - Some(false), + Some(cfg!(not(target_os = "redox"))), + Some(cfg!(not(target_os = "redox"))), Some(cfg!(any( target_os = "macos", target_os = "freebsd", @@ -2182,6 +2428,13 @@ pub mod module { SupportFunc::new("lchown", None, None, None), #[cfg(not(target_os = "redox"))] SupportFunc::new("fchown", Some(true), None, Some(true)), + #[cfg(not(any(target_os = "redox", target_os = "wasi")))] + SupportFunc::new( + "mkfifo", + Some(false), + Some(host_posix::has_mkfifoat()), + Some(false), + ), #[cfg(not(target_os = "redox"))] SupportFunc::new("mknod", Some(true), Some(MKNOD_DIR_FD), Some(false)), SupportFunc::new("umask", Some(false), Some(false), Some(false)), @@ -2193,23 +2446,10 @@ pub mod module { } #[pyfunction] - fn getlogin(vm: &VirtualMachine) -> PyResult { - // Get a pointer to the login name string. The string is statically - // allocated and might be overwritten on subsequent calls to this - // function or to `cuserid()`. See man getlogin(3) for more information. - let Some(login) = rustpython_host_env::posix::getlogin() else { - return Err(vm.new_os_error("unable to determine login name")); - }; - login.to_str().map(|s| s.to_owned()).map_err(|e| { - vm.new_unicode_decode_error( - vm.ctx.new_str("utf-8"), - vm.ctx.new_bytes(login.as_bytes().to_vec()), - e.valid_up_to(), - e.error_len() - .map_or(login.as_bytes().len(), |n| e.valid_up_to() + n), - vm.ctx.new_str("unable to decode login name"), - ) - }) + fn getlogin(vm: &VirtualMachine) -> PyResult { + let login = + rustpython_host_env::posix::getlogin().map_err(|err| err.into_pyexception(vm))?; + vm.fsdecode(std::ffi::OsString::from_vec(login.into_bytes())) } // cfg from nix @@ -2714,10 +2954,16 @@ pub mod module { #[cfg(any(target_os = "linux", target_os = "macos"))] #[derive(FromArgs)] - struct SendFileArgs<'fd> { - out_fd: BorrowedFd<'fd>, - in_fd: BorrowedFd<'fd>, + struct SendFileArgs { + out_fd: i32, + in_fd: i32, + #[cfg(target_os = "linux")] + offset: PyObjectRef, + #[cfg(target_os = "macos")] offset: rustpython_host_env::crt_fd::Offset, + #[cfg(target_os = "linux")] + count: isize, + #[cfg(target_os = "macos")] count: i64, #[cfg(target_os = "macos")] // Missing means an empty header list. @@ -2728,35 +2974,58 @@ pub mod module { #[pyarg(any, optional, py_default = "()")] trailers: OptionalArg, #[cfg(target_os = "macos")] - #[allow(dead_code)] #[pyarg(any, default)] - // TODO: not implemented flags: i32, } #[cfg(target_os = "linux")] #[pyfunction] - fn sendfile(args: SendFileArgs<'_>, vm: &VirtualMachine) -> PyResult { - let mut file_offset = args.offset; + fn sendfile(args: SendFileArgs, vm: &VirtualMachine) -> PyResult { + if args.count < 0 { + return Err(vm.new_value_error("count cannot be negative")); + } + let mut file_offset = if vm.is_none(&args.offset) { + None + } else { + Some(args.offset.try_into_value(vm)?) + }; - let res = rustpython_host_env::posix::sendfile( - args.out_fd, - args.in_fd, - &mut file_offset, - args.count as usize, - ) - .map_err(|err| err.into_pyexception(vm))?; - Ok(vm.ctx.new_int(res as u64).into()) + loop { + let result = vm.allow_threads(|| { + rustpython_host_env::posix::sendfile( + args.out_fd, + args.in_fd, + file_offset.as_mut(), + args.count as usize, + ) + }); + match result { + Ok(written) => return Ok(vm.ctx.new_int(written).into()), + Err(err) if err.raw_os_error() == Some(libc::EINTR) => vm.check_signals()?, + Err(err) => return Err(err.into_pyexception(vm)), + } + } } #[cfg(target_os = "macos")] fn _extract_vec_bytes( x: OptionalArg, + kind: &str, vm: &VirtualMachine, ) -> PyResult>> { x.into_option() .map(|x| { - let v: Vec = x.try_to_value(vm)?; + let sequence = x.try_sequence(vm).map_err(|_| { + vm.new_type_error(format!("sendfile() {kind}s must be a sequence")) + })?; + let count = sequence.length(vm)?; + if count > i32::MAX as usize { + return Err(vm.new_overflow_error(format!("sendfile() {kind} is too large"))); + } + let mut v = Vec::with_capacity(count); + for index in 0..count { + v.push(sequence.get_item(index as isize, vm)?.try_into_value(vm)?); + } Ok(if v.is_empty() { None } else { Some(v) }) }) .transpose() @@ -2765,52 +3034,95 @@ pub mod module { #[cfg(target_os = "macos")] #[pyfunction] - fn sendfile(args: SendFileArgs<'_>, vm: &VirtualMachine) -> PyResult { - let headers = _extract_vec_bytes(args.headers, vm)?; - let count = headers - .as_ref() - .map_or(0, |v| v.iter().map(|s| s.len()).sum()) as i64 - + args.count; + fn sendfile(args: SendFileArgs, vm: &VirtualMachine) -> PyResult { + if args.count < 0 { + return Err(vm.new_value_error("count cannot be negative")); + } + let headers = _extract_vec_bytes(args.headers, "header", vm)?; + let mut count = args.count; + if let Some(headers) = &headers { + for header in headers { + let length = i64::try_from(header.len()) + .map_err(|_| vm.new_overflow_error("sendfile() header is too large"))?; + if count >= i64::MAX - length { + return Err(vm.new_overflow_error("sendfile() header is too large")); + } + count += length; + } + } + let trailers = _extract_vec_bytes(args.trailers, "trailer", vm)?; + // Complete all Python argument callbacks before snapshotting mutable + // exporters. No buffer lock may survive another callback or blocking I/O. let headers = headers .as_ref() - .map(|v| v.iter().map(|b| b.borrow_buf()).collect::>()); + .map(|v| { + v.iter() + .map(|b| b.borrow_buf_unlocked(vm)) + .collect::>>() + }) + .transpose()?; let headers = headers .as_ref() .map(|v| v.iter().map(|borrowed| &**borrowed).collect::>()); let headers = headers.as_deref(); - let trailers = _extract_vec_bytes(args.trailers, vm)?; let trailers = trailers .as_ref() - .map(|v| v.iter().map(|b| b.borrow_buf()).collect::>()); + .map(|v| { + v.iter() + .map(|b| b.borrow_buf_unlocked(vm)) + .collect::>>() + }) + .transpose()?; let trailers = trailers .as_ref() .map(|v| v.iter().map(|borrowed| &**borrowed).collect::>()); let trailers = trailers.as_deref(); - let (res, written) = rustpython_host_env::posix::sendfile( - args.in_fd, - args.out_fd, - args.offset, - count, - headers, - trailers, - ); - // On macOS, sendfile can return EAGAIN even when some bytes were written. - // In that case, we should return the number of bytes written rather than - // raising an exception. Only raise an error if no bytes were written. - if let Err(err) = res - && written == 0 - { - return Err(err.into_pyexception(vm)); + let mut written = count; + loop { + let result = vm.allow_threads(|| { + rustpython_host_env::posix::sendfile( + args.in_fd, + args.out_fd, + args.offset, + &mut written, + headers, + trailers, + args.flags, + ) + }); + match result { + Ok(()) => return Ok(vm.ctx.new_int(written).into()), + Err(err) if err.raw_os_error() == Some(libc::EINTR) => vm.check_signals()?, + // CPython permits partial success only for EAGAIN or EBUSY. + Err(err) + if written != 0 + && matches!(err.raw_os_error(), Some(libc::EAGAIN | libc::EBUSY)) => + { + return Ok(vm.ctx.new_int(written).into()); + } + Err(err) => return Err(err.into_pyexception(vm)), + } } - Ok(vm.ctx.new_int(written as u64).into()) + } + + #[cfg(target_os = "linux")] + #[derive(FromArgs)] + struct GetRandomArgs { + #[pyarg(any)] + size: isize, + #[pyarg(any, default)] + flags: core::ffi::c_int, } #[cfg(target_os = "linux")] #[pyfunction] - fn getrandom(size: isize, flags: OptionalArg, vm: &VirtualMachine) -> PyResult> { + fn getrandom( + GetRandomArgs { size, flags }: GetRandomArgs, + vm: &VirtualMachine, + ) -> PyResult> { let size = usize::try_from(size) .map_err(|_| vm.new_os_error(format!("Invalid argument for size: {size}")))?; let mut buf = Vec::with_capacity(size); @@ -2818,11 +3130,12 @@ pub mod module { let len = rustpython_host_env::posix::getrandom( buf.as_mut_ptr() as *mut libc::c_void, size, - flags.unwrap_or(0), + flags as u32, ) .map_err(|_| vm.new_last_os_error())?; buf.set_len(len); } + buf.shrink_to_fit(); Ok(buf) } @@ -2851,7 +3164,7 @@ pub mod module { #[pymodule(sub, name = "posix")] mod posix_sched { use crate::{ - AsObject, Py, PyObject, PyObjectRef, PyResult, VirtualMachine, + AsObject, PyObject, PyObjectRef, PyResult, VirtualMachine, builtins::PyTupleRef, class::PyClassDef, convert::{IntoPyException, ToPyObject}, @@ -2890,26 +3203,12 @@ mod posix_sched { .map(Into::into) } - #[extend_class] - fn extend_pyclass(ctx: &crate::vm::Context, class: &'static Py) { - // Override __reduce__ to return (type, (sched_priority,)) - // instead of the generic structseq (type, ((sched_priority,),)). - // The trait's extend_class checks contains_key before setting default. - const SCHED_PARAM_REDUCE: crate::function::PyMethodDef = - crate::function::PyMethodDef::new_const( - "__reduce__", - |zelf: crate::PyRef, - vm: &VirtualMachine| - -> PyTupleRef { - vm.new_tuple((zelf.class().to_owned(), (zelf.as_slice()[0].clone(),))) - }, - crate::function::PyMethodFlags::METHOD, - crate::function::ItemDoc::NONE, - ); - class.set_attr( - ctx.intern_str("__reduce__"), - SCHED_PARAM_REDUCE.to_proper_method(class, ctx), - ); + #[pymethod] + fn __reduce__( + zelf: crate::PyRef, + vm: &VirtualMachine, + ) -> PyTupleRef { + vm.new_tuple((zelf.class().to_owned(), (zelf.as_slice()[0].clone(),))) } } @@ -2948,13 +3247,13 @@ mod posix_sched { #[pyarg(positional)] policy: i32, #[pyarg(positional)] - sched_param: PyObjectRef, + param: PyObjectRef, } #[cfg(not(target_env = "musl"))] #[pyfunction] fn sched_setscheduler(args: SchedSetschedulerArgs, vm: &VirtualMachine) -> PyResult { - let libc_sched_param = convert_sched_param(&args.sched_param, vm)?; + let libc_sched_param = convert_sched_param(&args.param, vm)?; rustpython_host_env::posix::sched_setscheduler(args.pid, args.policy, &libc_sched_param) .map_err(|err| err.into_pyexception(vm)) } @@ -2977,13 +3276,13 @@ mod posix_sched { #[pyarg(positional)] pid: i32, #[pyarg(positional)] - sched_param: PyObjectRef, + param: PyObjectRef, } #[cfg(not(target_env = "musl"))] #[pyfunction] fn sched_setparam(args: SchedSetParamArgs, vm: &VirtualMachine) -> PyResult { - let libc_sched_param = convert_sched_param(&args.sched_param, vm)?; + let libc_sched_param = convert_sched_param(&args.param, vm)?; rustpython_host_env::posix::sched_setparam(args.pid, &libc_sched_param) .map_err(|err| err.into_pyexception(vm)) } diff --git a/crates/vm/src/stdlib/posix/xattr.rs b/crates/vm/src/stdlib/posix/xattr.rs new file mode 100644 index 00000000000..8af5eb8861d --- /dev/null +++ b/crates/vm/src/stdlib/posix/xattr.rs @@ -0,0 +1,222 @@ +// spell-checker:disable + +#[pymodule(sub, name = "posix")] +pub(super) mod _xattr { + use crate::{ + PyObjectRef, PyResult, VirtualMachine, + builtins::{PyBytesRef, PyListRef}, + convert::TryFromObject, + exceptions::ToOSErrorBuilder, + function::{ArgBytesLike, ArgIntoBool}, + ospath::PathConverter, + stdlib::os::warn_if_bool_fd, + }; + use alloc::ffi::CString; + use rustpython_host_env::{os::ffi::OsStringExt, posix::xattr::Target}; + use std::{ffi::OsString, io}; + + #[pyattr] + use rustpython_host_env::posix::xattr::XATTR_SIZE_MAX; + + const GET: usize = 0; + const SET: usize = 1; + const REMOVE: usize = 2; + const LIST: usize = 3; + const NAME: [&str; 4] = ["getxattr", "setxattr", "removexattr", "listxattr"]; + + enum Location { + Path(CString), + Fd(i32), + } + + struct Path { + location: Location, + original: PyObjectRef, + } + + impl TryFromObject for Path { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let converter = PathConverter::new().function(NAME[OP]); + + let to_path = |path: crate::ospath::OsPath| -> PyResult { + let original = path.filename(vm)?; + let location = Location::Path(path.into_cstring(vm)?); + Ok(Self { location, original }) + }; + + let obj = match converter.try_match_str_bytes(obj, vm)? { + Ok(path) => return to_path(path), + Err(obj) => obj, + }; + if let Some(fd) = obj.try_index_opt(vm) { + warn_if_bool_fd(&obj, vm)?; + let fd = fd?; + let fd = i32::try_from(fd.as_bigint()).map_err(|_| { + let message = if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + "fd is less than minimum" + } else { + "fd is greater than maximum" + }; + vm.new_overflow_error(message) + })?; + Ok(Self { + location: Location::Fd(fd), + original: obj, + }) + } else { + to_path(converter.try_pathlike_with_nullable(obj, true, OP == LIST, vm)?) + } + } + } + + impl Path { + fn cwd(vm: &VirtualMachine) -> Self { + Self { + location: Location::Path(c".".into()), + original: vm.ctx.none(), + } + } + + fn target(&self, follow_symlinks: bool, vm: &VirtualMachine) -> PyResult> { + match &self.location { + Location::Path(path) if follow_symlinks => Ok(Target::Follow(path)), + Location::Path(path) => Ok(Target::NoFollow(path)), + Location::Fd(fd) if follow_symlinks => Ok(Target::Fd(*fd)), + Location::Fd(_) => Err(vm.new_value_error(format!( + "{}: cannot use fd and follow_symlinks together", + NAME[OP], + ))), + } + } + + fn error( + &self, + err: io::Error, + vm: &VirtualMachine, + ) -> crate::builtins::PyBaseExceptionRef { + if err.kind() == io::ErrorKind::OutOfMemory && err.raw_os_error().is_none() { + vm.no_memory_error() + } else { + err.to_os_error_builder(vm) + .filename(self.original.clone()) + .build(vm) + .upcast() + } + } + } + + struct Attribute(CString, PyObjectRef); + + impl TryFromObject for Attribute { + fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { + let path = PathConverter::new() + .function(NAME[OP]) + .argument("attribute") + .try_path(obj, vm)?; + let original = path.filename(vm)?; + Ok(Self(path.into_cstring(vm)?, original)) + } + } + + #[derive(FromArgs)] + struct AttributeArgs { + #[pyarg(any)] + path: Path, + #[pyarg(any)] + attribute: Attribute, + #[pyarg(named, default = ArgIntoBool::TRUE)] + follow_symlinks: ArgIntoBool, + } + + #[pyfunction] + fn getxattr(args: AttributeArgs, vm: &VirtualMachine) -> PyResult { + let AttributeArgs { + path, + attribute, + follow_symlinks, + } = args; + let target = path.target(follow_symlinks.into_bool(), vm)?; + vm.audit("os.getxattr", || (path.original.clone(), attribute.1))?; + vm.allow_threads(|| target.get(&attribute.0)) + .map(|value| vm.ctx.new_bytes(value)) + .map_err(|err| path.error(err, vm)) + } + + #[derive(FromArgs)] + struct SetArgs { + #[pyarg(any)] + path: Path, + #[pyarg(any)] + attribute: Attribute, + #[pyarg(any)] + value: ArgBytesLike, + #[pyarg(any, default = 0)] + flags: i32, + #[pyarg(named, default = ArgIntoBool::TRUE)] + follow_symlinks: ArgIntoBool, + } + + #[pyfunction] + fn setxattr(args: SetArgs, vm: &VirtualMachine) -> PyResult<()> { + let SetArgs { + path, + attribute, + value, + flags, + follow_symlinks, + } = args; + let target = path.target(follow_symlinks.into_bool(), vm)?; + vm.audit("os.setxattr", || { + ( + path.original.clone(), + attribute.1, + value.with_ref(|buf| vm.ctx.new_bytes(buf.to_vec())), + flags, + ) + })?; + let value = value.borrow_buf_unlocked(vm)?; + vm.allow_threads(|| target.set(&attribute.0, &value, flags)) + .map_err(|err| path.error(err, vm)) + } + + #[pyfunction] + fn removexattr(args: AttributeArgs, vm: &VirtualMachine) -> PyResult<()> { + let AttributeArgs { + path, + attribute, + follow_symlinks, + } = args; + let target = path.target(follow_symlinks.into_bool(), vm)?; + vm.audit("os.removexattr", || (path.original.clone(), attribute.1))?; + vm.allow_threads(|| target.remove(&attribute.0)) + .map_err(|err| path.error(err, vm)) + } + + #[derive(FromArgs)] + struct ListArgs { + #[pyarg(any, default = None)] + path: Option>, + #[pyarg(named, default = ArgIntoBool::TRUE)] + follow_symlinks: ArgIntoBool, + } + + #[pyfunction] + fn listxattr(args: ListArgs, vm: &VirtualMachine) -> PyResult { + let path = args.path.unwrap_or_else(|| Path::cwd(vm)); + let target = path.target(args.follow_symlinks.into_bool(), vm)?; + vm.audit("os.listxattr", || (path.original.clone(),))?; + let attrs = vm + .allow_threads(|| target.list()) + .map_err(|err| path.error(err, vm))?; + // The OS returns a sequence of NUL-terminated names, not UTF-8. + let names = attrs + .split_inclusive(|b| *b == 0) + .filter_map(|name| name.strip_suffix(&[0])) + .map(|name| { + vm.fsdecode(OsString::from_vec(name.to_vec())) + .map(Into::into) + }) + .collect::>>()?; + Ok(vm.ctx.new_list(names)) + } +} diff --git a/crates/vm/src/stdlib/posix_compat.rs b/crates/vm/src/stdlib/posix_compat.rs index 4ac80a03d37..e4aebc8e970 100644 --- a/crates/vm/src/stdlib/posix_compat.rs +++ b/crates/vm/src/stdlib/posix_compat.rs @@ -10,6 +10,8 @@ pub(crate) use module::module_def; super::posix_unix_like::_posix_unix_like, ))] pub(crate) mod module { + #[cfg(target_os = "wasi")] + use crate::{AsObject, function::OptionalArg, ospath::PathConverter}; use crate::{ Py, PyObjectRef, PyResult, VirtualMachine, builtins::PyStrRef, @@ -17,6 +19,65 @@ pub(crate) mod module { stdlib::os::{_os, DirFd, SupportFunc, SymlinkArgs, TargetIsDirectory}, }; + #[cfg(target_os = "wasi")] + #[derive(FromArgs)] + struct ChmodArgs { + #[pyarg(any)] + path: PyObjectRef, + #[pyarg(any)] + mode: PyObjectRef, + #[pyarg(named, default = None)] + dir_fd: Option, + #[pyarg(named, optional, py_default = "(os.name != 'nt')")] + follow_symlinks: OptionalArg, + } + + #[cfg(target_os = "wasi")] + #[pyfunction] + fn chmod(args: ChmodArgs, vm: &VirtualMachine) -> PyResult<()> { + // Keep the clinic conversion order even though WASI has no chmod syscall. + let path = PathConverter::new() + .function("chmod") + .argument("path") + .try_path(args.path, vm)?; + let mode = args.mode.try_index(vm)?; + let mode = i32::try_from(mode.as_bigint()) + .map_err(|_| vm.new_overflow_error("Python int too large to convert to C int"))?; + if let Some(dir_fd) = args.dir_fd { + super::super::os::warn_if_bool_fd(&dir_fd, vm)?; + let fd = dir_fd.try_index_opt(vm).unwrap_or_else(|| { + Err(vm.new_type_error(format!( + "argument should be integer or None, not {}", + dir_fd.class().name() + ))) + })?; + let fd = i32::try_from(fd.as_bigint()).map_err(|_| { + vm.new_overflow_error(if fd.as_bigint().sign() == malachite_bigint::Sign::Minus { + "fd is less than minimum" + } else { + "fd is greater than maximum" + }) + })?; + if fd != rustpython_host_env::os::AT_FDCWD { + return Err(vm.new_not_implemented_error("dir_fd unavailable on this platform")); + } + } + let follow_symlinks = match args.follow_symlinks { + OptionalArg::Present(value) => value.try_to_bool(vm)?, + OptionalArg::Missing => true, + }; + if !follow_symlinks { + return Err( + vm.new_not_implemented_error("chmod: follow_symlinks unavailable on this platform") + ); + } + let filename = path.filename(vm)?; + vm.audit("os.chmod", || (filename, mode, -1))?; + // CPython 3.15 posixmodule.c explicitly ignores the absent WASI syscall + // after argument conversion and auditing. No supports_* capability is set. + Ok(()) + } + #[derive(FromArgs)] struct AccessArgs<'a> { #[pyarg(any)] diff --git a/crates/vm/src/stdlib/pwd.rs b/crates/vm/src/stdlib/pwd.rs index bfa7eb034e5..97404112892 100644 --- a/crates/vm/src/stdlib/pwd.rs +++ b/crates/vm/src/stdlib/pwd.rs @@ -5,17 +5,14 @@ pub(crate) use pwd::module_def; #[pymodule] mod pwd { use crate::{ - PyResult, VirtualMachine, - builtins::{PyIntRef, PyUtf8StrRef}, - convert::IntoPyException, - exceptions, - types::PyStructSequence, + AsObject, PyObjectRef, PyResult, VirtualMachine, builtins::PyUtf8StrRef, + convert::TryFromObject, exceptions, stdlib::posix::module::RawUid, types::PyStructSequence, }; use core::hint::cold_path; use rustpython_host_env::pwd as host_pwd; #[cfg(not(target_os = "android"))] - use crate::{PyObjectRef, convert::ToPyObject}; + use crate::convert::ToPyObject; #[pystruct_sequence_data] struct PasswdData { @@ -68,17 +65,30 @@ mod pwd { } #[pyfunction] - fn getpwuid(uidobj: PyIntRef, vm: &VirtualMachine) -> PyResult { - let uid_t = libc::uid_t::try_from(uidobj.as_bigint()).ok(); - let user = uid_t - .map(host_pwd::getpwuid) - .transpose() - .map_err(|err| err.into_pyexception(vm))? - .flatten(); + fn getpwuid(uidobj: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let uid = RawUid::try_from_object(vm, uidobj) + .map_err(|err| { + if err.fast_isinstance(vm.ctx.exceptions.overflow_error) { + vm.new_key_error(vm.ctx.new_str("getpwuid(): uid not found").into()) + } else { + err + } + })? + .0; + let user = match host_pwd::getpwuid(uid) { + Ok(user) => user, + Err(err) if err.raw_os_error() == Some(libc::ENOMEM) => { + return Err(vm.no_memory_error()); + } + Err(_) => None, + }; let user = user.ok_or_else(|| { vm.new_key_error( vm.ctx - .new_str(format!("getpwuid(): uid not found: {}", uidobj.as_bigint())) + .new_str(format!( + "getpwuid(): uid not found: {}", + if uid == u32::MAX { -1 } else { i64::from(uid) } + )) .into(), ) })?; diff --git a/crates/vm/src/stdlib/sys.rs b/crates/vm/src/stdlib/sys.rs index a77fbb10fd3..3cdf06bacec 100644 --- a/crates/vm/src/stdlib/sys.rs +++ b/crates/vm/src/stdlib/sys.rs @@ -45,8 +45,8 @@ pub mod sys { }, convert::ToPyObject, frame::FrameObjectRef, - function::{FuncArgs, KwArgs, OptionalArg, PosArgs}, - stdlib::{_warnings::warn, builtins}, + function::{FuncArgs, OptionalArg, PosArgs}, + stdlib::_warnings::warn, types::PyStructSequence, version, vm::{Settings, VirtualMachine}, @@ -56,7 +56,7 @@ pub mod sys { use num_traits::ToPrimitive; use std::{ env, - io::{IsTerminal, Read, Write}, + io::{IsTerminal, Write}, }; // Rust target triple (e.g., "x86_64-unknown-linux-gnu") @@ -208,13 +208,13 @@ pub mod sys { .to_owned() } - #[pygetset(name = "name")] - fn name_prop(&self) -> String { + #[pygetset] + fn name(&self) -> String { self.name.clone() } - #[pygetset(name = "mode")] - fn mode_prop(&self) -> String { + #[pygetset] + fn mode(&self) -> String { self.mode.clone() } } @@ -250,21 +250,23 @@ pub mod sys { target_os = "ios" => c"ios", windows => c"win32", target_os = "wasi" => c"wasi", - _ => c"unknown" + _ => c"unknown", }; - #[pyattr(name = "ps1")] - const PS1: &str = ">>> "; - #[pyattr(name = "ps2")] - const PS2: &str = "... "; - #[cfg(windows)] #[pyattr(name = "_vpath")] - const VPATH: Option<&'static str> = None; // TODO: actual VPATH value + fn vpath(vm: &VirtualMachine) -> String { + crate::getpath::source_directory(&vm.state.config.paths) + .and_then(|source| std::path::absolute(source).ok()) + .map_or_default(|source| source.to_string_lossy().into_owned()) + } #[cfg(windows)] - #[pyattr(name = "dllhandle")] - const DLLHANDLE: usize = 0; + #[pyattr] + fn dllhandle(_vm: &VirtualMachine) -> usize { + crate::host_env::windows::runtime_module_handle() + .expect("the running RustPython image must have a module handle") + } #[pyattr] fn prefix(vm: &VirtualMachine) -> String { @@ -291,16 +293,20 @@ pub mod sys { vm.state.config.paths.stdlib_dir.clone().to_pyobject(vm) } + #[pyattr] + fn _is_python_build(vm: &VirtualMachine) -> bool { + crate::getpath::source_directory(&vm.state.config.paths).is_some() + } + // alphabetical order with segments of pyattr and others - #[pyattr] - fn argv(vm: &VirtualMachine) -> Vec { + pub(super) fn argv(vm: &VirtualMachine) -> PyResult> { vm.state .config .settings .argv .iter() - .map(|arg| vm.ctx.new_str(arg.clone()).into()) + .map(|arg| vm.fsdecode(arg.clone()).map(Into::into)) .collect() } @@ -559,9 +565,6 @@ pub mod sys { "socket", "socketserver", "sqlite3", - "sre_compile", - "sre_constants", - "sre_parse", "ssl", "stat", "statistics", @@ -639,6 +642,16 @@ pub mod sys { .to_owned() } + #[pyattr] + fn abi_info(vm: &VirtualMachine) -> PyRef { + py_namespace!(vm, { + "pointer_bits" => vm.ctx.new_int(usize::BITS), + "free_threaded" => vm.ctx.new_bool(true), + "debug" => vm.ctx.new_bool(false), + "byteorder" => byteorder(vm), + }) + } + #[pyattr] fn _base_executable(vm: &VirtualMachine) -> String { vm.state.config.paths.base_executable.clone() @@ -667,8 +680,8 @@ pub mod sys { fn implementation(vm: &VirtualMachine) -> PyRef { const NAME: &str = "rustpython"; - // cache tag uses 'cpython' because our compiler is cpython compatible - let cache_tag = format!("cpython-{}{}", version::MAJOR, version::MINOR); + // Keep implementation-specific bytecode caches separate. + let cache_tag = format!("{NAME}-{}{}", version::MAJOR, version::MINOR); let ctx = &vm.ctx; py_namespace!(vm, { "name" => ctx.new_str(NAME), @@ -686,19 +699,19 @@ pub mod sys { Vec::new() } - #[pyattr] - fn orig_argv(vm: &VirtualMachine) -> Vec { - env::args().map(|arg| vm.ctx.new_str(arg).into()).collect() + pub(super) fn orig_argv(vm: &VirtualMachine) -> PyResult> { + env::args_os() + .map(|arg| vm.fsdecode(arg).map(Into::into)) + .collect() } - #[pyattr] - fn path(vm: &VirtualMachine) -> Vec { + pub(super) fn path(vm: &VirtualMachine) -> PyResult> { vm.state .config .paths .module_search_paths .iter() - .map(|path| vm.ctx.new_str(path.clone()).into()) + .map(|path| vm.fsdecode(path.clone()).map(Into::into)) .collect() } @@ -712,9 +725,14 @@ pub mod sys { vm.ctx.new_dict() } - #[pyattr] - fn pycache_prefix(vm: &VirtualMachine) -> PyObjectRef { - vm.ctx.none() + pub(super) fn pycache_prefix(vm: &VirtualMachine) -> PyResult> { + vm.state + .config + .settings + .pycache_prefix + .clone() + .map(|value| vm.fsdecode(value)) + .transpose() } #[pyattr(name = "version")] @@ -752,17 +770,11 @@ pub mod sys { #[cfg(feature = "rustpython-compiler")] #[pyfunction] - fn _baserepl(vm: &VirtualMachine) -> PyResult<()> { - // read stdin to end - let stdin = std::io::stdin(); - let mut handle = stdin.lock(); - let mut source = String::new(); - handle - .read_to_string(&mut source) - .map_err(|e| vm.new_os_error(format!("Error reading from stdin: {e}")))?; - vm.compile(&source, crate::compiler::Mode::Single, "") - .map_err(|e| e.into_pyexception(vm, Some(&source)))?; - Ok(()) + fn _baserepl(vm: &VirtualMachine) { + // PyRun_AnyFileExFlags(stdin, "", 0, &cf) + if let Err(exc) = vm.run_any_stdin() { + vm.print_uncaught_exception(&exc); + } } #[pyfunction] @@ -824,10 +836,7 @@ pub mod sys { #[pyfunction] fn call_tracing(func: PyObjectRef, args: PyTupleRef, vm: &VirtualMachine) -> PyResult { - // CPython temporarily enables tracing state around this call. - // RustPython does not currently model the full C-level tracing toggles, - // but call semantics (func(*args)) are matched. - func.call(PosArgs::new(args.as_slice().to_vec()), vm) + vm.with_tracing_enabled(|| func.call(PosArgs::new(args.as_slice().to_vec()), vm)) } #[pyfunction] @@ -835,6 +844,40 @@ pub mod sys { vm.topmost_exception() } + fn displayhook_encoding_fallback( + stdout: &PyObject, + object: &PyObject, + vm: &VirtualMachine, + ) -> PyResult<()> { + let encoding = stdout + .get_attr("encoding", vm)? + .downcast::() + .map_err(|_| vm.new_type_error("bad argument type for built-in operation"))?; + let encoding = encoding.try_as_utf8(vm)?.as_str(); + // CPython passes the validated UTF-8 encoding name as a C string. + let encoding = encoding.split('\0').next().unwrap(); + let repr = object.repr(vm)?; + let encoded = vm.state.codec_registry.encode_text( + repr, + encoding, + Some(vm.ctx.new_utf8_str("backslashreplace")), + vm, + )?; + if let Some(buffer) = vm.get_attribute_opt(stdout, "buffer")? { + vm.call_method(&buffer, "write", (encoded,))?; + } else { + let escaped = vm.state.codec_registry.decode_text_object( + encoded.into(), + encoding, + Some(vm.ctx.new_utf8_str("strict")), + vm, + )?; + let write = stdout.get_attr("write", vm)?; + write.call((escaped.as_object().str(vm)?,), vm)?; + } + Ok(()) + } + #[pyfunction(name = "__displayhook__")] #[pyfunction] fn displayhook(object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { @@ -844,9 +887,27 @@ pub mod sys { } // set to none to avoid recursion while printing vm.builtins.set_attr("_", vm.ctx.none(), vm)?; - // TODO: catch encoding errors - let repr = object.repr(vm)?.into(); - builtins::print(PosArgs::new(vec![repr]), Default::default(), vm)?; + let stdout = vm + .sys_module + .dict() + .get_item_opt("stdout", vm)? + .filter(|stdout| !vm.is_none(stdout)) + .ok_or_else(|| vm.new_runtime_error("lost sys.stdout"))?; + let result = (|| { + // PyFile_WriteObject obtains the writer before calling repr. + let write = stdout.get_attr("write", vm)?; + let repr = object.repr(vm)?; + write.call((repr,), vm) + })(); + if let Err(exc) = result { + if !exc.fast_isinstance(vm.ctx.exceptions.unicode_encode_error) { + return Err(exc); + } + drop(exc); + displayhook_encoding_fallback(&stdout, &object, vm)?; + } + vm.call_method(&stdout, "write", (vm.ctx.new_str("\n"),))?; + drop(stdout); vm.builtins.set_attr("_", object, vm)?; Ok(()) } @@ -859,7 +920,6 @@ pub mod sys { traceback: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { - let stderr = super::get_stderr(vm)?; // Keep runtime SyntaxErrors on the normal traceback path. let has_traceback = !vm.is_none(&traceback); match vm.normalize_exception(exctype, value.clone(), traceback) { @@ -879,19 +939,11 @@ pub mod sys { .and_then(|text| text.downcast::().ok()) .is_some_and(|text| text.to_string_lossy().trim_end() == "\\"); if native_syntax_error_display { + let stderr = super::get_stderr(vm)?; return vm.write_exception(&mut crate::py_io::PyWriter(stderr, vm), &exc); } - // PyErr_Display: try traceback._print_exception_bltin first - if let Ok(tb_mod) = vm.import("traceback", 0) - && let Ok(print_exc_builtin) = tb_mod.get_attr("_print_exception_bltin", vm) - && print_exc_builtin - .call((exc.as_object().to_owned(),), vm) - .is_ok() - { - return Ok(()); - } - // Fallback to Rust-level exception printing - vm.write_exception(&mut crate::py_io::PyWriter(stderr, vm), &exc) + vm.display_exception(&exc); + Ok(()) } Err(_) => { let type_name = value.class().name(); @@ -899,6 +951,7 @@ pub mod sys { "TypeError: print_exception(): Exception expected for value, {type_name} found\n" ); use crate::py_io::Write; + let stderr = super::get_stderr(vm)?; write!(&mut crate::py_io::PyWriter(stderr, vm), "{msg}")?; Ok(()) } @@ -909,57 +962,150 @@ pub mod sys { #[pyfunction] pub fn breakpointhook(args: FuncArgs, vm: &VirtualMachine) -> PyResult { #[cfg(feature = "host_env")] - let env_var = crate::host_env::os::var("PYTHONBREAKPOINT") - .and_then(|env_var| { - if env_var.is_empty() { - Err(std::env::VarError::NotPresent) - } else { - Ok(env_var) - } - }) - .unwrap_or_else(|_| "pdb.set_trace".to_owned()); + let env_var = if vm.state.config.settings.ignore_environment { + None + } else { + crate::host_env::os::var("PYTHONBREAKPOINT").ok() + }; #[cfg(not(feature = "host_env"))] - let env_var = "pdb.set_trace".to_owned(); + let env_var: Option = None; + + // Own the environment value before importing: import callbacks can + // change the environment while the selected hook is being resolved. + let env_var = env_var + .filter(|value| !value.is_empty()) + .unwrap_or_else(|| "pdb.set_trace".to_owned()); - if env_var.eq("0") { + if env_var == "0" { return Ok(vm.ctx.none()); - }; + } let print_unimportable_module_warn = || { warn( vm.ctx.exceptions.runtime_warning, - format!("Ignoring unimportable $PYTHONBREAKPOINT: \"{env_var}\"",), + format!("Ignoring unimportable $PYTHONBREAKPOINT: \"{env_var}\""), 0, vm, )?; Ok(vm.ctx.none()) }; - let last = match env_var.rsplit_once('.') { - Some((_, last)) => last, - None if !env_var.is_empty() => env_var.as_str(), - _ => return print_unimportable_module_warn(), + let (module_path, attr_name) = match env_var.rsplit_once('.') { + // A leading separator has no module to import. A trailing one + // still imports the module and looks up the empty attribute. + Some(("", _)) => return print_unimportable_module_warn(), + Some((module_path, attr_name)) => (module_path, attr_name), + None => ("builtins", env_var.as_str()), }; - let (module_path, attr_name) = if last == env_var { - ("builtins", env_var.as_str()) - } else { - (&env_var[..(env_var.len() - last.len() - 1)], last) + let module_name = vm.ctx.new_str(module_path); + let module = crate::import::import_module(vm, &module_name); + drop(module_name); + let module = match module { + Ok(module) => module, + Err(err) if err.fast_isinstance(vm.ctx.exceptions.import_error) => { + drop(err); + return print_unimportable_module_warn(); + } + Err(err) => return Err(err), }; - let module = match vm.import(&vm.ctx.new_str(module_path), 0) { - Ok(module) => module, - Err(_) => { + // AttributeError is the only lookup failure treated as an unavailable + // hook. Release the module before warning or invoking the hook: its + // attribute callback may have removed it from sys.modules. + let hook = module.get_attr(&vm.ctx.new_str(attr_name), vm); + drop(module); + let hook = match hook { + Ok(hook) => hook, + Err(err) if err.fast_isinstance(vm.ctx.exceptions.attribute_error) => { + drop(err); return print_unimportable_module_warn(); } + Err(err) => return Err(err), }; - match vm.get_attribute_opt(&module, &vm.ctx.new_str(attr_name)) { - Ok(Some(hook)) => hook.as_ref().call(args, vm), - _ => print_unimportable_module_warn(), + // Calling consumes FuncArgs. Keep the original owners alive through + // release of the resolved callable, including when its call fails. + // Scope cleanup drops the later hook binding before the retained args. + let (_retained_args, hook) = (args.clone(), hook); + hook.call(args, vm) + } + + #[pyfunction] + fn get_lazy_imports(vm: &VirtualMachine) -> &'static str { + if vm + .state + .lazy_imports + .all + .load(core::sync::atomic::Ordering::Acquire) + { + "all" + } else { + "normal" } } + #[derive(FromArgs)] + struct SetLazyImportsArgs { + #[pyarg(any)] + mode: PyObjectRef, + } + + #[pyfunction] + fn set_lazy_imports(args: SetLazyImportsArgs, vm: &VirtualMachine) -> PyResult<()> { + let mode = args.mode; + let mode = mode + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("mode must be a string: 'normal' or 'all'"))?; + let all = match mode.to_str() { + Some("normal") => false, + Some("all") => true, + _ => return Err(vm.new_value_error("mode must be 'normal' or 'all'")), + }; + vm.state + .lazy_imports + .all + .store(all, core::sync::atomic::Ordering::Release); + Ok(()) + } + + #[pyfunction] + fn get_lazy_imports_filter(vm: &VirtualMachine) -> PyObjectRef { + vm.state + .lazy_imports + .filter() + .unwrap_or_else(|| vm.ctx.none()) + } + + #[derive(FromArgs)] + struct SetLazyImportsFilterArgs { + #[pyarg(any)] + filter: PyObjectRef, + } + + #[pyfunction] + fn set_lazy_imports_filter( + args: SetLazyImportsFilterArgs, + vm: &VirtualMachine, + ) -> PyResult<()> { + let filter = args.filter; + let filter = if vm.is_none(&filter) { + None + } else { + if !filter.is_callable() { + return Err(vm.new_value_error("filter provided but is not callable")); + } + Some(filter) + }; + vm.state.lazy_imports.set_filter(filter); + Ok(()) + } + + #[pyattr] + fn lazy_modules(vm: &VirtualMachine) -> PyObjectRef { + vm.state.lazy_imports.modules.clone().into() + } + #[pyfunction] fn exc_info(vm: &VirtualMachine) -> (PyObjectRef, PyObjectRef, PyObjectRef) { match vm.topmost_exception() { @@ -973,6 +1119,36 @@ pub mod sys { PyFlags::from_data(FlagsData::from_settings(&vm.state.config.settings), vm) } + /// _PySys_SetFlagObj + pub(crate) fn set_flag_obj( + vm: &VirtualMachine, + name: &str, + value: PyObjectRef, + ) -> PyResult<()> { + use crate::{class::StaticType, types::PyStructSequenceData}; + + let old_flags = vm + .sys_module + .get_attr("flags", vm) + .map_err(|_| vm.new_runtime_error("lost sys.flags"))?; + let old_flags = old_flags + .downcast_ref::() + .filter(|flags| { + flags.len() + == FlagsData::REQUIRED_FIELD_NAMES.len() + FlagsData::OPTIONAL_FIELD_NAMES.len() + }) + .ok_or_else(|| vm.new_type_error("sys.flags must be a sys.flags instance"))?; + let pos = FlagsData::REQUIRED_FIELD_NAMES + .iter() + .position(|field| *field == name) + .expect("unknown sys.flags field"); + let mut values = old_flags.as_slice().to_vec(); + values[pos] = value; + let new_flags = PyTuple::new_unchecked(values.into_boxed_slice()) + .into_ref_with_type(vm, PyFlags::static_type().to_owned())?; + vm.sys_module.set_attr("flags", new_flags, vm) + } + #[pyattr] fn float_info(vm: &VirtualMachine) -> PyTupleRef { PyFloatInfo::from_data(FloatInfoData::INFO, vm) @@ -1146,110 +1322,100 @@ pub mod sys { Ok(PyWindowsVersion::from_data(winver, vm)) } - fn _unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) -> PyResult<()> { - use super::PyStderr; + /// Shared by sys.__unraisablehook__ and the fallback when a user hook fails. + /// Only the outer unraisable dispatcher discards reporting failures. + pub(crate) fn write_unraisable( + unraisable: UnraisableHookArgsData, + vm: &VirtualMachine, + ) -> PyResult<()> { + let Some(file) = vm.sys_module.dict().get_item_opt("stderr", vm)? else { + return Ok(()); + }; + if vm.is_none(&file) { + return Ok(()); + } + let write = |value: PyObjectRef| vm.call_method(&file, "write", (value,)).map(drop); + let text = |value: &str| write(vm.ctx.new_str(value).into()); - let stderr = PyStderr(vm); if !vm.is_none(&unraisable.object) { if !vm.is_none(&unraisable.err_msg) { - write!(stderr, "{}: ", unraisable.err_msg.str(vm)?); + write(unraisable.err_msg.str(vm)?.into())?; + text(": ")?; } else { - write!(stderr, "Exception ignored in: "); + text("Exception ignored in: ")?; } - // exception in del will be ignored but printed - let repr = &unraisable.object.repr(vm); - let str = match repr { - Ok(v) => v.to_string(), - Err(_) => format!( - "", - unraisable.object.class().name() - ), - }; - writeln!(stderr, "{str}"); + if unraisable + .object + .repr(vm) + .and_then(|value| write(value.into())) + .is_err() + { + text("")?; + } + text("\n")?; } else if !vm.is_none(&unraisable.err_msg) { - writeln!(stderr, "{}:", unraisable.err_msg.str(vm)?); + write(unraisable.err_msg.str(vm)?.into())?; + text(":\n")?; } - // Print traceback (using actual exc_traceback, not current stack) - if !vm.is_none(&unraisable.exc_traceback) { - let tb_module = vm.import("traceback", 0)?; - let print_tb = tb_module.get_attr("print_tb", vm)?; - let stderr_obj = super::get_stderr(vm)?; - let kwargs: KwArgs = core::iter::once(("file".to_string(), stderr_obj)).collect(); - let _ = print_tb.call( - FuncArgs::new(vec![unraisable.exc_traceback.clone()], kwargs), - vm, - ); + if vm.try_display_exception_to(&file, &unraisable.exc_value) { + return Ok(()); } - // Check exc_type - if vm.is_none(unraisable.exc_type.as_object()) { - return Ok(()); + // Imports can fail during teardown. Keep a native fallback, and keep + // printing the exception even if writing its traceback fails. + if let Ok(traceback) = unraisable + .exc_traceback + .downcast::() + { + let mut writer = crate::py_io::PyWriter(file.clone(), vm); + let _ = crate::exceptions::write_traceback(&mut writer, &traceback, vm); } - assert!( - unraisable - .exc_type - .fast_issubclass(vm.ctx.exceptions.base_exception_type) - ); - - // Print module name (if not builtins or __main__). - // A failed lookup or a non-str `__module__` is discarded: print - // `` with no trailing `.`, then the qualname. - let module_name = unraisable.exc_type.__module__(vm).ok(); + + let module_name = unraisable + .exc_type + .as_object() + .get_attr("__module__", vm) + .ok(); if let Some(module_str) = module_name .as_ref() .and_then(|name| name.downcast_ref::()) { let module = module_str.as_wtf8(); if module != "builtins" && module != "__main__" { - write!(stderr, "{module}."); + write(module_str.to_owned().into())?; + text(".")?; } } else { - write!(stderr, ""); + text("")?; } - // Print qualname let qualname = unraisable.exc_type.__qualname__(vm); if let Ok(qualname_str) = qualname.downcast::() { - write!(stderr, "{}", qualname_str.as_wtf8()); + write(qualname_str.into())?; } else { - write!(stderr, "{}", unraisable.exc_type.name()); + text("")?; } - // Print exception value if !vm.is_none(&unraisable.exc_value) { - write!(stderr, ": "); - if let Ok(str) = unraisable.exc_value.str(vm) { - write!(stderr, "{}", str.as_wtf8()); - } else { - write!(stderr, ""); + text(": ")?; + if unraisable + .exc_value + .str(vm) + .and_then(|value| write(value.into())) + .is_err() + { + text("")?; } } - writeln!(stderr); - - // Flush stderr - if let Ok(stderr_obj) = super::get_stderr(vm) - && let Ok(flush) = stderr_obj.get_attr("flush", vm) - { - let _ = flush.call((), vm); - } - - Ok(()) + text("\n")?; + vm.call_method(&file, "flush", ()).map(drop) } #[pyattr] #[pyfunction(name = "__unraisablehook__")] - fn unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) { - if let Err(e) = _unraisablehook(unraisable, vm) { - let stderr = super::PyStderr(vm); - writeln!( - stderr, - "{}", - e.as_object() - .repr(vm) - .unwrap_or_else(|_| vm.ctx.empty_str.to_owned()) - ); - } + fn unraisablehook(unraisable: UnraisableHookArgsData, vm: &VirtualMachine) -> PyResult<()> { + write_unraisable(unraisable, vm) } #[pyattr] @@ -1262,6 +1428,11 @@ pub mod sys { vm.ctx.intern_str(string).to_owned() } + #[pyfunction] + fn _is_interned(string: PyRef) -> bool { + string.as_object().is_interned() + } + #[pyattr] fn int_info(vm: &VirtualMachine) -> PyTupleRef { PyIntInfo::from_data(IntInfoData::INFO, vm) @@ -1301,11 +1472,12 @@ pub mod sys { #[pyfunction] fn setprofile(function: PyObjectRef, vm: &VirtualMachine) { #[cfg(feature = "threading")] - if let Some(slot) = crate::vm::thread::current_thread_slot() { - *slot.profile_func.lock() = function.clone(); - } - vm.profile_func.replace(function); + let old_slot = crate::vm::thread::current_thread_slot() + .map(|slot| core::mem::replace(&mut *slot.profile_func.lock(), function.clone())); + let _old_vm = vm.profile_func.replace(function); update_use_tracing(vm); + #[cfg(feature = "threading")] + drop(old_slot); } #[pyfunction] @@ -1317,6 +1489,10 @@ pub mod sys { if limit > recursion_depth { vm.recursion_limit.set(limit); + #[cfg(feature = "threading")] + if let Some(factory) = &vm.thread_factory { + factory.recursion_limit.store(limit); + } Ok(()) } else { Err(vm.new_recursion_error(format!( @@ -1328,10 +1504,9 @@ pub mod sys { #[pyfunction] fn settrace(function: PyObjectRef, vm: &VirtualMachine) { #[cfg(feature = "threading")] - if let Some(slot) = crate::vm::thread::current_thread_slot() { - *slot.trace_func.lock() = function.clone(); - } - vm.trace_func.replace(function); + let old_slot = crate::vm::thread::current_thread_slot() + .map(|slot| core::mem::replace(&mut *slot.trace_func.lock(), function.clone())); + let _old_vm = vm.trace_func.replace(function); update_use_tracing(vm); // The rest of the current line already started before tracing was // enabled; sync prev_line so leftover opcodes on this line do not @@ -1339,44 +1514,100 @@ pub mod sys { if let Some(frame) = vm.current_frame() { frame.iframe().sync_prev_line_from_lasti(); } + #[cfg(feature = "threading")] + drop(old_slot); } #[pyfunction] - fn _settraceallthreads(function: PyObjectRef, vm: &VirtualMachine) { + #[cfg_attr( + not(feature = "threading"), + expect( + clippy::unnecessary_wraps, + reason = "threading builds can fail to reserve callback storage" + ) + )] + fn _settraceallthreads(function: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let func = (!vm.is_none(&function)).then(|| function.clone()); - *vm.state.global_trace_func.lock() = func; + // Retain replaced callbacks until every registry and slot lock has + // been released: their finalizers can reenter these APIs. + let old_global; + #[cfg(feature = "threading")] + let mut old_slots = Vec::new(); #[cfg(feature = "threading")] { let registry = vm.state.thread_frames.lock(); + if old_slots.try_reserve(registry.len()).is_err() { + drop(registry); + return Err(vm.no_memory_error()); + } + old_global = core::mem::replace(&mut *vm.state.global_trace_func.lock(), func); #[expect( clippy::iter_over_hash_type, reason = "every thread slot, order is irrelevant" )] for slot in registry.values() { - *slot.trace_func.lock() = function.clone(); + old_slots.push(core::mem::replace( + &mut *slot.trace_func.lock(), + function.clone(), + )); } } - vm.trace_func.replace(function); + #[cfg(not(feature = "threading"))] + { + old_global = core::mem::replace(&mut *vm.state.global_trace_func.lock(), func); + } + let _old_vm = vm.trace_func.replace(function); update_use_tracing(vm); + drop(old_global); + #[cfg(feature = "threading")] + drop(old_slots); + Ok(()) } #[pyfunction] - fn _setprofileallthreads(function: PyObjectRef, vm: &VirtualMachine) { + #[cfg_attr( + not(feature = "threading"), + expect( + clippy::unnecessary_wraps, + reason = "threading builds can fail to reserve callback storage" + ) + )] + fn _setprofileallthreads(function: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { let func = (!vm.is_none(&function)).then(|| function.clone()); - *vm.state.global_profile_func.lock() = func; + // Retain replaced callbacks until every registry and slot lock has + // been released: their finalizers can reenter these APIs. + let old_global; + #[cfg(feature = "threading")] + let mut old_slots = Vec::new(); #[cfg(feature = "threading")] { let registry = vm.state.thread_frames.lock(); + if old_slots.try_reserve(registry.len()).is_err() { + drop(registry); + return Err(vm.no_memory_error()); + } + old_global = core::mem::replace(&mut *vm.state.global_profile_func.lock(), func); #[expect( clippy::iter_over_hash_type, reason = "every thread slot, order is irrelevant" )] for slot in registry.values() { - *slot.profile_func.lock() = function.clone(); + old_slots.push(core::mem::replace( + &mut *slot.profile_func.lock(), + function.clone(), + )); } } - vm.profile_func.replace(function); + #[cfg(not(feature = "threading"))] + { + old_global = core::mem::replace(&mut *vm.state.global_profile_func.lock(), func); + } + let _old_vm = vm.profile_func.replace(function); update_use_tracing(vm); + drop(old_global); + #[cfg(feature = "threading")] + drop(old_slots); + Ok(()) } #[cfg(feature = "threading")] @@ -1503,7 +1734,7 @@ pub mod sys { #[pystruct_sequence(name = "asyncgen_hooks", data = "AsyncgenHooksData")] pub(super) struct PyAsyncgenHooks; - #[pyclass(with(PyStructSequence))] + #[pyclass(with(PyStructSequence), flags(IMMUTABLETYPE))] impl PyAsyncgenHooks {} #[pyfunction] @@ -1550,12 +1781,12 @@ pub mod sys { dev_mode: bool, /// -X utf8 utf8_mode: u8, - /// -X int_max_str_digits=number - int_max_str_digits: i64, - /// -P, `PYTHONSAFEPATH` - safe_path: bool, /// -X warn_default_encoding, PYTHONWARNDEFAULTENCODING warn_default_encoding: u8, + /// -P, `PYTHONSAFEPATH` + safe_path: bool, + /// -X int_max_str_digits=number + int_max_str_digits: i64, } impl FlagsData { @@ -1590,7 +1821,7 @@ pub mod sys { #[pystruct_sequence(name = "flags", data = "FlagsData", no_attr)] pub(super) struct PyFlags; - #[pyclass(with(PyStructSequence))] + #[pyclass(with(PyStructSequence), flags(IMMUTABLETYPE))] impl Py { #[pyslot] fn slot_new(_cls: PyTypeRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult { @@ -1598,13 +1829,23 @@ pub mod sys { } #[pygetset] - fn context_aware_warnings(&self, vm: &VirtualMachine) -> bool { - vm.state.config.settings.context_aware_warnings + const fn gil(&self) -> u8 { + 0 + } + + #[pygetset] + fn context_aware_warnings(&self, vm: &VirtualMachine) -> u8 { + vm.state.config.settings.context_aware_warnings as u8 } #[pygetset] - fn thread_inherit_context(&self, vm: &VirtualMachine) -> bool { - vm.state.config.settings.thread_inherit_context + fn thread_inherit_context(&self, vm: &VirtualMachine) -> u8 { + vm.state.config.settings.thread_inherit_context as u8 + } + + #[pygetset] + fn lazy_imports(&self, vm: &VirtualMachine) -> i8 { + vm.state.config.settings.lazy_imports } } @@ -1620,9 +1861,9 @@ pub mod sys { impl ThreadInfoData { const INFO: Self = Self { name: crate::stdlib::_thread::_thread::PYTHREAD_NAME, - // As I know, there's only way to use lock as "Mutex" in Rust - // with satisfying python document spec. - lock: Some("mutex+cond"), + // RustPython uses parking_lot rather than CPython's PyMutex. + // None denotes a lock implementation without a Python ABI name. + lock: None, version: None, }; } @@ -1632,7 +1873,7 @@ pub mod sys { pub(super) struct PyThreadInfo; #[cfg(feature = "threading")] - #[pyclass(with(PyStructSequence))] + #[pyclass(with(PyStructSequence), flags(IMMUTABLETYPE))] impl PyThreadInfo {} #[pystruct_sequence_data] @@ -1669,7 +1910,7 @@ pub mod sys { #[pystruct_sequence(name = "float_info", data = "FloatInfoData", no_attr)] pub(super) struct PyFloatInfo; - #[pyclass(with(PyStructSequence))] + #[pyclass(with(PyStructSequence), flags(IMMUTABLETYPE))] impl PyFloatInfo {} #[pystruct_sequence_data] @@ -1705,7 +1946,7 @@ pub mod sys { #[pystruct_sequence(name = "hash_info", data = "HashInfoData", no_attr)] pub(super) struct PyHashInfo; - #[pyclass(with(PyStructSequence))] + #[pyclass(with(PyStructSequence), flags(IMMUTABLETYPE))] impl PyHashInfo {} #[pystruct_sequence_data] @@ -1728,7 +1969,7 @@ pub mod sys { #[pystruct_sequence(name = "int_info", data = "IntInfoData", no_attr)] pub(super) struct PyIntInfo; - #[pyclass(with(PyStructSequence))] + #[pyclass(with(PyStructSequence), flags(IMMUTABLETYPE))] impl PyIntInfo {} #[derive(Default, Debug)] @@ -1762,7 +2003,7 @@ pub mod sys { #[pystruct_sequence(name = "version_info", data = "VersionInfoData", no_attr)] pub struct PyVersionInfo; - #[pyclass(with(PyStructSequence))] + #[pyclass(with(PyStructSequence), flags(IMMUTABLETYPE))] impl PyVersionInfo { #[pyslot] fn slot_new( @@ -1951,11 +2192,30 @@ fn sys_module_doc() -> Option<&'static str> { } } -pub(crate) fn init_module(vm: &VirtualMachine, module: &Py, builtins: &Py) { - module.__init_methods(vm).unwrap(); - sys::module_exec(vm, module).unwrap(); +pub(crate) fn init_module( + vm: &VirtualMachine, + module: &Py, + builtins: &Py, +) -> PyResult<()> { + module.__init_methods(vm)?; + let _ = vm + .state + .sysdict_copy + .set(module.dict().copy().into_ref(&vm.ctx)); + sys::module_exec(vm, module)?; + // These values decode OS bytes and can fail before the codec registry is ready. + // Initialize them outside infallible #[pyattr] functions so startup can report errors. + module.set_attr("path", vm.ctx.new_list(sys::path(vm)?), vm)?; + module.set_attr("argv", vm.ctx.new_list(sys::argv(vm)?), vm)?; + module.set_attr("orig_argv", vm.ctx.new_list(sys::orig_argv(vm)?), vm)?; + module.set_attr( + "pycache_prefix", + sys::pycache_prefix(vm)?.to_pyobject(vm), + vm, + )?; let modules = vm.ctx.new_dict(); + let _ = vm.state.modules.set(modules.clone()); modules .set_item("sys", module.to_owned().into(), vm) .unwrap(); @@ -1972,6 +2232,7 @@ pub(crate) fn init_module(vm: &VirtualMachine, module: &Py, builtins: "modules" => modules, "_jit" => jit_module, }); + Ok(()) } pub(crate) fn set_bootstrap_stderr(vm: &VirtualMachine) -> PyResult<()> { diff --git a/crates/vm/src/stdlib/sys/monitoring.rs b/crates/vm/src/stdlib/sys/monitoring.rs index aa180daeb96..1dcb8450f23 100644 --- a/crates/vm/src/stdlib/sys/monitoring.rs +++ b/crates/vm/src/stdlib/sys/monitoring.rs @@ -9,8 +9,7 @@ use std::collections::{HashMap, HashSet}; pub(crate) const TOOL_LIMIT: usize = 6; const EVENTS_COUNT: usize = 19; -const LOCAL_EVENTS_COUNT: usize = 11; -const UNGROUPED_EVENTS_COUNT: usize = 18; +const UNGROUPED_EVENTS_COUNT: usize = 16; /// Event identifier (`PY_MONITORING_EVENT_*`), stored in `tstate->what_event`. /// `None` on the VM field is the `< 0` sentinel (not in a monitoring callback). @@ -99,8 +98,11 @@ pub struct MonitoringState { pub global_events: [u32; TOOL_LIMIT], pub local_events: HashMap<(usize, usize), u32>, pub callbacks: HashMap<(usize, usize), PyObjectRef>, - /// Per-instruction disabled tools: (code_id, offset, tool) - pub disabled: HashSet<(usize, usize, usize)>, + // Legacy BRANCH callbacks also check whether the source instruction was + // disabled. Direct BRANCH_LEFT/RIGHT registrations bypass that check. + legacy_branch_callbacks: HashSet<(usize, usize)>, + /// Per-instruction disabled tools: (code_id, offset, event, tool) + pub disabled: HashSet<(usize, usize, usize, usize)>, /// Cached MISSING sentinel singleton pub missing: Option, /// Cached DISABLE sentinel singleton @@ -114,6 +116,7 @@ impl Default for MonitoringState { global_events: [0; TOOL_LIMIT], local_events: HashMap::new(), callbacks: HashMap::new(), + legacy_branch_callbacks: HashSet::new(), disabled: HashSet::new(), missing: None, disable: None, @@ -204,6 +207,11 @@ fn parse_single_event(event: i32, vm: &VirtualMachine) -> PyResult { Ok(event_id) } +/// `PY_MONITORING_IS_INSTRUMENTED_EVENT` +const fn is_instrumented_event(event_id: usize) -> bool { + event_id <= MonitoringEvent::StopIteration as usize +} + fn normalize_event_set(event_set: i32, local: bool, vm: &VirtualMachine) -> PyResult { let kind = if local { "local event set" @@ -232,7 +240,7 @@ fn normalize_event_set(event_set: i32, local: bool, vm: &VirtualMachine) -> PyRe event_set |= MonitoringEvent::BranchLeft.mask() | MonitoringEvent::BranchRight.mask(); } - if local && event_set >= (1 << LOCAL_EVENTS_COUNT) { + if local && event_set >= (1 << UNGROUPED_EVENTS_COUNT) { return Err(vm.new_value_error(format!("invalid local event set 0x{event_set:x}"))); } @@ -281,23 +289,6 @@ fn opcode_event_is_active( event_for_opcode(op, oparg).is_some_and(|ev| events & ev.mask() != 0) } -/// Walk real instructions, skipping specialization CACHE payloads. -/// Cache slots may contain pointer bits that are not valid opcodes. -fn for_each_instruction( - code: &Py, - mut f: impl FnMut(usize, rustpython_compiler_core::bytecode::Instruction, u8), -) { - let len = code.code.instructions.len(); - let mut i = 0; - while i < len { - let op = code.code.instructions.read_op(i); - let oparg = code.code.instructions.read_arg(i).as_u8(); - let caches = op.deoptimize().cache_entries(); - f(i, op, oparg); - i += 1 + caches; - } -} - /// Rewrite a code object's bytecode in-place with layered instrumentation. /// /// Three layers (outermost first): @@ -402,26 +393,12 @@ pub(crate) fn instrument_code(code: &Py, events: u32) { data.line_opcodes.resize(len, 0); data.per_instruction_opcodes.resize(len, 0); - // Find _co_firsttraceable: index of first RESUME instruction - let mut first_traceable = None; - for_each_instruction(code, |i, op, _| { - if first_traceable.is_none() - && matches!( - op, - Instruction::Resume { .. } - | Instruction::ResumeCheck - | Instruction::InstrumentedResume - ) - { - first_traceable = Some(i); - } - }); - let first_traceable = first_traceable.unwrap_or(0); + let first_traceable = code.first_traceable; // Phase 4: Place regular INSTRUMENTED_* opcodes whose event is active. // Walk by cache_entries so specialized CACHE payloads are not decoded as opcodes. { - let mut i = 0; + let mut i = first_traceable; while i < len { let op = code.code.instructions.read_op(i); let oparg = code.code.instructions.read_arg(i).as_u8(); @@ -469,6 +446,14 @@ pub(crate) fn instrument_code(code: &Py, events: u32) { // Mirrors CPython's initialize_lines: first determine which positions // are line starts, then mark branch/jump targets, then place opcodes. if events & MonitoringEvent::Line.mask() != 0 { + let base_opcode = |i| { + let mut op = code.code.instructions.read_op(i); + if matches!(op, Instruction::InstrumentedInstruction) { + op = Instruction::try_from(data.per_instruction_opcodes[i]) + .expect("INSTRUMENTED_INSTRUCTION without original opcode"); + } + op.to_base().unwrap_or(op) + }; // is_line_start[i] = true if position i should have INSTRUMENTED_LINE let mut is_line_start = vec![false; len]; let line_locations = rustpython_compiler_core::marshal::linetable_to_locations( @@ -482,16 +467,8 @@ pub(crate) fn instrument_code(code: &Py, events: u32) { // First pass: mark positions where the source line changes let mut prev_line: Option = None; - for (i, unit) in code - .code - .instructions - .iter() - .enumerate() - .take(len) - .skip(first_traceable) - { - let op = unit.op; - let base = op.to_base().unwrap_or(op); + for (i, is_start) in is_line_start.iter_mut().enumerate().skip(first_traceable) { + let base = base_opcode(i); if matches!(base, Instruction::ExtendedArg) { continue; } @@ -516,7 +493,7 @@ pub(crate) fn instrument_code(code: &Py, events: u32) { let is_new = prev_line != Some(line); prev_line = Some(line); if is_new && line > 0 { - is_line_start[i] = true; + *is_start = true; } } } @@ -528,8 +505,8 @@ pub(crate) fn instrument_code(code: &Py, events: u32) { let mut arg_state = bytecode::OpArgState::default(); let mut instr_idx = first_traceable; for unit in code.code.instructions[first_traceable..len].iter().copied() { - let (op, arg) = arg_state.get(unit); - let base = op.to_base().unwrap_or(op); + let (_, arg) = arg_state.get(unit); + let base = base_opcode(instr_idx); if matches!(base, Instruction::ExtendedArg) || matches!(base, Instruction::Cache) { instr_idx += 1; @@ -563,8 +540,7 @@ pub(crate) fn instrument_code(code: &Py, events: u32) { && !is_line_start[target_idx] && !no_loc_mask.get(target_idx).copied().unwrap_or(false) { - let target_op = code.code.instructions[target_idx].op; - let target_base = target_op.to_base().unwrap_or(target_op); + let target_base = base_opcode(target_idx); // Skip synthetic cleanup targets. if matches!(target_base, Instruction::PopIter) { instr_idx += 1; @@ -586,8 +562,7 @@ pub(crate) fn instrument_code(code: &Py, events: u32) { && !is_line_start[target_idx] && !no_loc_mask.get(target_idx).copied().unwrap_or(false) { - let target_op = code.code.instructions.read_op(target_idx); - let target_base = target_op.to_base().unwrap_or(target_op); + let target_base = base_opcode(target_idx); if !matches!(target_base, Instruction::PopIter) && let Some((loc, _)) = line_locations.get(target_idx) && loc.line.get() > 0 @@ -662,33 +637,44 @@ fn use_tool_id(tool_id: i32, name: &str, vm: &VirtualMachine) -> PyResult<()> { } fn clear_tool_id(tool_id: i32, vm: &VirtualMachine) -> PyResult<()> { - let tool = check_valid_tool(tool_id, vm)?; - let mut state = vm.state.monitoring.lock(); - if state.tool_names[tool].is_some() { - state.global_events[tool] = 0; - state - .local_events - .retain(|(local_tool, _), _| *local_tool != tool); - state.callbacks.retain(|(cb_tool, _), _| *cb_tool != tool); - state.disabled.retain(|&(_, _, t)| t != tool); - } - update_events_mask(vm, &state); - Ok(()) + release_tool_callbacks(tool_id, false, vm) } fn free_tool_id(tool_id: i32, vm: &VirtualMachine) -> PyResult<()> { + release_tool_callbacks(tool_id, true, vm) +} + +fn release_tool_callbacks(tool_id: i32, free: bool, vm: &VirtualMachine) -> PyResult<()> { let tool = check_valid_tool(tool_id, vm)?; - let mut state = vm.state.monitoring.lock(); - if state.tool_names[tool].is_some() { - state.global_events[tool] = 0; - state - .local_events - .retain(|(local_tool, _), _| *local_tool != tool); - state.callbacks.retain(|(cb_tool, _), _| *cb_tool != tool); - state.disabled.retain(|&(_, _, t)| t != tool); - state.tool_names[tool] = None; + let callbacks = { + let mut state = vm.state.monitoring.lock(); + let callbacks = if state.tool_names[tool].is_some() { + state.global_events[tool] = 0; + state + .local_events + .retain(|(local_tool, _), _| *local_tool != tool); + let callbacks: Vec<_> = state + .callbacks + .extract_if(|(cb_tool, _), _| *cb_tool == tool) + .map(|(_, callback)| callback) + .collect(); + state.disabled.retain(|&(_, _, _, t)| t != tool); + state + .legacy_branch_callbacks + .retain(|(cb_tool, _)| *cb_tool != tool); + callbacks + } else { + Vec::new() + }; + update_events_mask(vm, &state); + callbacks + }; + // Callback finalizers may reenter monitoring; release owners after unlocking. + drop(callbacks); + // Keep the name visible during callback finalization, as CPython does. + if free { + vm.state.monitoring.lock().tool_names[tool] = None; } - update_events_mask(vm, &state); Ok(()) } @@ -709,28 +695,34 @@ fn register_callback( vm.audit("sys.monitoring.register_callback", || (func.clone(),))?; - let mut state = vm.state.monitoring.lock(); - let prev = state - .callbacks - .remove(&(tool, event_id)) - .unwrap_or_else(|| vm.ctx.none()); - let branch_id = MonitoringEvent::Branch as usize; - let branch_left_id = MonitoringEvent::BranchLeft as usize; - let branch_right_id = MonitoringEvent::BranchRight as usize; - if !vm.is_none(&func) { - state.callbacks.insert((tool, event_id), func.clone()); - // BRANCH is a composite event: also register for BRANCH_LEFT/RIGHT - if event_id == branch_id { - state.callbacks.insert((tool, branch_left_id), func.clone()); - state.callbacks.insert((tool, branch_right_id), func); + let (prev, _displaced) = { + let mut state = vm.state.monitoring.lock(); + let prev = state + .callbacks + .remove(&(tool, event_id)) + .unwrap_or_else(|| vm.ctx.none()); + let mut displaced = Vec::new(); + state.legacy_branch_callbacks.remove(&(tool, event_id)); + if !vm.is_none(&func) { + state.callbacks.insert((tool, event_id), func.clone()); } - } else { - // Also clear BRANCH_LEFT/RIGHT when clearing BRANCH - if event_id == branch_id { - state.callbacks.remove(&(tool, branch_left_id)); - state.callbacks.remove(&(tool, branch_right_id)); + // BRANCH replaces both edge registrations, including independently + // registered callbacks. Keep their owners alive until after unlocking. + if event_id == MonitoringEvent::Branch as usize { + for edge in [MonitoringEvent::BranchLeft, MonitoringEvent::BranchRight] { + let key = (tool, edge as usize); + let old = if vm.is_none(&func) { + state.legacy_branch_callbacks.remove(&key); + state.callbacks.remove(&key) + } else { + state.legacy_branch_callbacks.insert(key); + state.callbacks.insert(key, func.clone()) + }; + displaced.extend(old); + } } - } + (prev, displaced) + }; Ok(prev) } @@ -846,6 +838,19 @@ fn fire( code: &Py, offset: u32, cb_extra: &[PyObjectRef], +) -> PyResult<()> { + fire_at(vm, event, code, offset, offset, cb_extra) +} + +// The physical instruction owns DISABLE state; branch callback source offsets +// can differ from that instruction when NOT_TAKEN follows a branch or wrapper. +fn fire_at( + vm: &VirtualMachine, + event: MonitoringEvent, + code: &Py, + offset: u32, + source_offset: u32, + cb_extra: &[PyObjectRef], ) -> PyResult<()> { // Prevent recursive event firing if vm.tracing_is_suppressed() || FIRING.with(|f| f.get()) { @@ -855,6 +860,11 @@ fn fire( let event_id = event as usize; let event_mask = event.mask(); let code_id = code.get_id(); + let disabled_event = if matches!(event, MonitoringEvent::CReturn | MonitoringEvent::CRaise) { + MonitoringEvent::Call as usize + } else { + event_id + }; // C_RETURN and C_RAISE are implicitly enabled when CALL is set. let check_bit = if matches!(event, MonitoringEvent::CReturn | MonitoringEvent::CRaise) { @@ -863,9 +873,18 @@ fn fire( event_mask }; - // Collect callbacks and snapshot the DISABLE sentinel under a single lock. - let (callbacks, disable_sentinel): (Vec<(usize, PyObjectRef)>, Option) = { - let state = vm.state.monitoring.lock(); + let branch_source = if matches!( + event, + MonitoringEvent::BranchLeft | MonitoringEvent::BranchRight + ) { + Some(branch_source_events(code, source_offset)) + } else { + None + }; + + // Collect callbacks without holding the monitoring lock across Python code. + let callbacks = { + let mut state = vm.state.monitoring.lock(); let mut cbs = Vec::new(); for tool in 0..TOOL_LIMIT { let global = state.global_events[tool]; @@ -877,14 +896,32 @@ fn fire( if ((global | local) & check_bit) == 0 { continue; } - if state.disabled.contains(&(code_id, offset as usize, tool)) { + if state + .disabled + .contains(&(code_id, offset as usize, disabled_event, tool)) + { continue; } - if let Some(cb) = state.callbacks.get(&(tool, event_id)) { - cbs.push((tool, cb.clone())); + if state.callbacks.contains_key(&(tool, event_id)) { + let legacy_branch = state.legacy_branch_callbacks.contains(&(tool, event_id)); + if legacy_branch + && branch_source.as_ref().is_some_and(|events| { + !events.iter().any(|source_event| { + event_active_at(&state, code_id, source_offset, *source_event) + }) + }) + { + // The legacy wrapper returns DISABLE without calling the + // user when the source instruction is no longer instrumented. + state + .disabled + .insert((code_id, offset as usize, event_id, tool)); + continue; + } + cbs.push((tool, state.callbacks[&(tool, event_id)].clone())); } } - (cbs, state.disable.clone()) + cbs }; if callbacks.is_empty() { @@ -896,35 +933,126 @@ fn fire( args_vec.extend_from_slice(cb_extra); let args = FuncArgs::from(args_vec); - FIRING.with(|f| f.set(true)); - vm.enter_tracing(); - let old_what = vm.what_event.replace(Some(event)); - let result = (|| { - for (tool, cb) in callbacks { - let result = cb.call(args.clone(), vm)?; - if disable_sentinel.as_ref().is_some_and(|d| result.is(d)) { - // Only local events (event_id < LOCAL_EVENTS_COUNT) can be disabled. - // Non-local events (RAISE, EXCEPTION_HANDLED, PY_UNWIND, etc.) - // cannot be disabled per code object. - if event_id >= LOCAL_EVENTS_COUNT { - // Remove the callback. - let mut state = vm.state.monitoring.lock(); - state.callbacks.remove(&(tool, event_id)); - return Err(vm.new_value_error(format!( - "Cannot disable {} events. Callback removed.", - EVENT_NAMES[event_id] - ))); - } + for (tool, cb) in callbacks { + if call_instrument(vm, event, &cb, args.clone())? { + if is_instrumented_event(event_id) { + let mut state = vm.state.monitoring.lock(); + state + .disabled + .insert((code_id, offset as usize, event_id, tool)); + } else if event_id < UNGROUPED_EVENTS_COUNT { + // Non-instrumented events are disabled for this whole code + // object by removing only the local subscription. Global + // subscriptions continue to fire, including for this code. let mut state = vm.state.monitoring.lock(); - state.disabled.insert((code_id, offset as usize, tool)); + if let Some(local) = state.local_events.get_mut(&(tool, code_id)) { + *local &= !event_mask; + if *local == 0 { + state.local_events.remove(&(tool, code_id)); + } + update_events_mask(vm, &state); + } + } else { + return Err(cannot_disable(vm, event, tool)); } } - Ok(()) - })(); + } + Ok(()) +} + +fn event_active_at( + state: &MonitoringState, + code_id: usize, + offset: u32, + event: MonitoringEvent, +) -> bool { + (0..TOOL_LIMIT).any(|tool| { + let active = state.global_events[tool] + | state + .local_events + .get(&(tool, code_id)) + .copied() + .unwrap_or(0); + state.tool_names[tool].is_some() + && active & event.mask() != 0 + && !state + .disabled + .contains(&(code_id, offset as usize, event as usize, tool)) + }) +} + +pub(crate) fn is_event_active_at( + vm: &VirtualMachine, + code: &Py, + offset: u32, + event: MonitoringEvent, +) -> bool { + event_active_at(&vm.state.monitoring.lock(), code.get_id(), offset, event) +} + +// Model the source's instrumentation layers without changing its bytecode. +// A layer stays instrumented until its last subscribed tool disables it. +fn branch_source_events(code: &Py, offset: u32) -> Vec { + use rustpython_compiler_core::bytecode::Instruction; + let index = offset as usize / 2; + let data = code.monitoring_data.lock(); + let mut events = Vec::with_capacity(3); + let mut op = code.code.instructions.read_op(index); + if let Some(data) = data.as_ref() { + if matches!(op, Instruction::InstrumentedLine) { + events.push(MonitoringEvent::Line); + op = Instruction::try_from(data.line_opcodes[index]) + .expect("INSTRUMENTED_LINE without original opcode"); + } + if matches!(op, Instruction::InstrumentedInstruction) { + events.push(MonitoringEvent::Instruction); + op = Instruction::try_from(data.per_instruction_opcodes[index]) + .expect("INSTRUMENTED_INSTRUCTION without original opcode"); + } + } + if let Some(event) = event_for_opcode(op, code.code.instructions.read_arg(index).as_u8()) { + events.push(event); + } + events +} + +// Restore tracing state before processing a callback result or exception. +fn call_instrument( + vm: &VirtualMachine, + event: MonitoringEvent, + callback: &PyObject, + args: FuncArgs, +) -> PyResult { + if vm.tracing_is_suppressed() || FIRING.with(|f| f.get()) { + return Ok(false); + } + let disable_sentinel = vm.state.monitoring.lock().disable.clone(); + FIRING.with(|f| f.set(true)); + vm.enter_tracing(); + let old_what = vm.what_event.replace(Some(event)); + let result = callback.call(args, vm); vm.what_event.set(old_what); vm.leave_tracing(); FIRING.with(|f| f.set(false)); - result + let result = result?; + let disable = disable_sentinel.as_ref().is_some_and(|d| result.is(d)); + Ok(disable) +} + +fn cannot_disable( + vm: &VirtualMachine, + event: MonitoringEvent, + tool: usize, +) -> crate::builtins::PyBaseExceptionRef { + let callback = { + let mut state = vm.state.monitoring.lock(); + state.callbacks.remove(&(tool, event as usize)) + }; + drop(callback); + vm.new_value_error(format!( + "Cannot disable {} events. Callback removed.", + EVENT_NAMES[event as usize] + )) } // Public dispatch functions (called from frame.rs) @@ -1071,6 +1199,12 @@ pub(crate) fn fire_raise( ) } +/// End suppression when the exception reaches a handler or escapes a frame, +/// independently of whether either lifecycle event has a registered callback. +pub(crate) fn reset_reraise_pending() { + RERAISE_PENDING.with(|f| f.set(false)); +} + /// Only fires if no RERAISE has been fired since the last EXCEPTION_HANDLED, /// preventing duplicate events from chained cleanup handlers. pub(crate) fn fire_reraise( @@ -1102,7 +1236,7 @@ pub(crate) fn fire_exception_handled( offset: u32, exception: &PyObject, ) -> PyResult<()> { - RERAISE_PENDING.with(|f| f.set(false)); + reset_reraise_pending(); fire( vm, MonitoringEvent::ExceptionHandled, @@ -1118,7 +1252,7 @@ pub(crate) fn fire_py_unwind( offset: u32, exception: &PyObject, ) -> PyResult<()> { - RERAISE_PENDING.with(|f| f.set(false)); + reset_reraise_pending(); fire( vm, MonitoringEvent::PyUnwind, @@ -1186,13 +1320,15 @@ pub(crate) fn fire_jump( pub(crate) fn fire_branch_left( vm: &VirtualMachine, code: &Py, + site: u32, offset: u32, destination: u32, ) -> PyResult<()> { - fire( + fire_at( vm, MonitoringEvent::BranchLeft, code, + site, offset, &[ vm.ctx.new_int(offset).into(), @@ -1230,13 +1366,13 @@ pub(super) mod sys_monitoring { #[pyclass] impl MonitoringSentinel {} - #[pyattr(name = "DEBUGGER_ID")] + #[pyattr] const DEBUGGER_ID: u8 = 0; - #[pyattr(name = "COVERAGE_ID")] + #[pyattr] const COVERAGE_ID: u8 = 1; - #[pyattr(name = "PROFILER_ID")] + #[pyattr] const PROFILER_ID: u8 = 2; - #[pyattr(name = "OPTIMIZER_ID")] + #[pyattr] const OPTIMIZER_ID: u8 = 5; #[pyattr(once, name = "DISABLE")] diff --git a/crates/vm/src/stdlib/time.rs b/crates/vm/src/stdlib/time.rs index 70b6479a5d3..f06af86f71b 100644 --- a/crates/vm/src/stdlib/time.rs +++ b/crates/vm/src/stdlib/time.rs @@ -5,20 +5,23 @@ // https://docs.python.org/3/library/time.html pub use decl::time; +pub mod pytime; pub(crate) use decl::module_def; +pub(crate) use decl::perf_counter_ns as profiler_time; #[pymodule(name = "time", with(#[cfg(any(unix, windows))] platform))] mod decl { #![allow(unreachable_pub)] #[cfg(any(unix, windows))] - use crate::builtins::PyBaseExceptionRef; + use crate::convert::{ToPyException, ToPyObject}; use crate::{ - AsObject, Py, PyObjectRef, PyResult, VirtualMachine, - builtins::{PyStr, PyStrRef, PyTypeRef}, - class::PyClassDef, - function::{Either, FuncArgs, OptionalArg, OptionalOption}, + AsObject, Py, PyObjectRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyStr, PyStrRef, PyTuple, PyTypeRef}, + class::{PyClassDef, StaticType}, + common::wtf8::Wtf8Buf, + function::{FuncArgs, OptionalArg, OptionalOption}, types::{PyStructSequence, PyStructSequenceData, struct_sequence_new}, }; #[cfg(target_os = "wasi")] @@ -26,14 +29,9 @@ mod decl { PyRef, builtins::{PyNamespace, PyUtf8StrRef}, }; - #[cfg(any(unix, windows))] - use crate::{ - common::wtf8::Wtf8Buf, - convert::{ToPyException, ToPyObject}, - }; use core::time::Duration; #[cfg(not(any(unix, windows)))] - use jiff::{Timestamp, Zoned, civil::DateTime, tz::TimeZone}; + use jiff::{Timestamp, ZonedDateTime, civil::DateTime, tz::TimeZone}; #[cfg(target_os = "wasi")] use rustpython_host_env::time::ClockId; #[cfg(any(unix, windows))] @@ -124,25 +122,17 @@ mod decl { duration_since_system_now(vm) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn sleep(object: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { vm.audit("time.sleep", || (object.clone(),))?; - let seconds_type_name = object.class().name().to_owned(); - let dur = object.try_into_value::(vm).map_err(|e| { - if e.class().is(vm.ctx.exceptions.value_error) - && let Some(s) = e.args().as_slice().first().and_then(|arg| arg.str(vm).ok()) - && s.as_bytes() == b"negative duration" - { - return vm.new_value_error("sleep length must be non-negative"); - } - if e.class().is(vm.ctx.exceptions.type_error) { - return vm.new_type_error(format!( - "'{seconds_type_name}' object cannot be interpreted as an integer or float" - )); - } - e - })?; + // _PyTime_ROUND_TIMEOUT rounds away from zero. + let nanoseconds = + super::pytime::from_seconds_object(&object, super::pytime::Round::Up, vm)?; + if nanoseconds < 0 { + return Err(vm.new_value_error("sleep length must be non-negative")); + } + let dur = Duration::from_nanos(nanoseconds as u64); #[cfg(unix)] { @@ -181,12 +171,12 @@ mod decl { Ok(()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn time_ns(vm: &VirtualMachine) -> PyResult { Ok(duration_since_system_now(vm)?.as_nanos() as u64) } - #[pyfunction] + #[pyfunction(signature_from_flags)] pub fn time(vm: &VirtualMachine) -> PyResult { _time(vm) } @@ -225,23 +215,23 @@ mod decl { Err(vm.new_not_implemented_error("time.time")) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn monotonic(vm: &VirtualMachine) -> PyResult { Ok(get_monotonic_time(vm)?.as_secs_f64()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn monotonic_ns(vm: &VirtualMachine) -> PyResult { Ok(get_monotonic_time(vm)?.as_nanos()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn perf_counter(vm: &VirtualMachine) -> PyResult { Ok(get_perf_time(vm)?.as_secs_f64()) } - #[pyfunction] - fn perf_counter_ns(vm: &VirtualMachine) -> PyResult { + #[pyfunction(signature_from_flags)] + pub(crate) fn perf_counter_ns(vm: &VirtualMachine) -> PyResult { Ok(get_perf_time(vm)?.as_nanos()) } @@ -324,25 +314,17 @@ mod decl { } #[cfg(not(any(unix, windows)))] - fn pyobj_to_timestamp(value: Either, vm: &VirtualMachine) -> PyResult { - let secs = match value { - Either::A(float) => { - if !float.is_finite() { - return Err(vm.new_value_error("Invalid value for timestamp")); - } - float.floor() as i64 - } - Either::B(int) => int, - }; + fn pyobj_to_timestamp(value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + let secs = super::pytime::object_to_time_t(&value, super::pytime::Round::Floor, vm)?; Timestamp::from_second(secs) .map_err(|_| vm.new_overflow_error("timestamp out of range for platform time_t")) } #[cfg(not(any(unix, windows)))] - fn naive_or_local(secs: Option>, vm: &VirtualMachine) -> PyResult { + fn naive_or_local(secs: Option, vm: &VirtualMachine) -> PyResult { Ok(match secs { - Some(secs) => pyobj_to_timestamp(secs, vm)?.to_zoned(TimeZone::system()), - None => Zoned::now(), + Some(secs) => pyobj_to_timestamp(secs, vm)?.to_zoned_datetime(TimeZone::system()), + None => ZonedDateTime::now(), }) } @@ -350,111 +332,10 @@ mod decl { fn checked_tm_from_struct_time( t: &StructTimeData, vm: &VirtualMachine, - func_name: &'static str, ) -> PyResult { - let invalid_tuple = - || vm.new_type_error(format!("{func_name}(): illegal time tuple argument")); - let classify_err = |e: PyBaseExceptionRef| { - if e.class().is(vm.ctx.exceptions.overflow_error) { - vm.new_overflow_error(format!("{func_name} argument out of range")) - } else { - invalid_tuple() - } - }; - - let year: i64 = t.tm_year.clone().try_into_value(vm).map_err(|e| { - if e.class().is(vm.ctx.exceptions.overflow_error) { - vm.new_overflow_error("year out of range") - } else { - invalid_tuple() - } - })?; - if year < i64::from(i32::MIN) + 1900 || year > i64::from(i32::MAX) { - return Err(vm.new_overflow_error("year out of range")); - } - let year = year as i32; - let tm_mon = t - .tm_mon - .clone() - .try_into_value::(vm) - .map_err(classify_err)? - - 1; - let tm_mday = t.tm_mday.clone().try_into_value(vm).map_err(classify_err)?; - let tm_hour = t.tm_hour.clone().try_into_value(vm).map_err(classify_err)?; - let tm_min = t.tm_min.clone().try_into_value(vm).map_err(classify_err)?; - let tm_sec = t.tm_sec.clone().try_into_value(vm).map_err(classify_err)?; - let tm_wday = (t - .tm_wday - .clone() - .try_into_value::(vm) - .map_err(classify_err)? - + 1) - % 7; - let tm_yday = t - .tm_yday - .clone() - .try_into_value::(vm) - .map_err(classify_err)? - - 1; - let tm_isdst = t - .tm_isdst - .clone() - .try_into_value(vm) - .map_err(classify_err)?; - - #[cfg(unix)] - { - use crate::builtins::PyUtf8StrRef; - let zone = if t.tm_zone.is(&vm.ctx.none) { - None - } else { - let zone: PyUtf8StrRef = t - .tm_zone - .clone() - .try_into_value(vm) - .map_err(|_| invalid_tuple())?; - Some(zone.as_str().to_owned()) - }; - let gmtoff = if t.tm_gmtoff.is(&vm.ctx.none) { - None - } else { - Some( - t.tm_gmtoff - .clone() - .try_into_value::(vm) - .map_err(classify_err)?, - ) - }; - host_time::checked_tm_from_parts(host_time::CheckedTmParts { - year: year.into(), - tm_mon, - tm_mday, - tm_hour, - tm_min, - tm_sec, - tm_wday, - tm_yday, - tm_isdst, - zone, - gmtoff, - }) - .map_err(|err| err.to_pyexception(vm)) - } - #[cfg(windows)] - { - host_time::checked_tm_from_parts(host_time::CheckedTmParts { - year: year.into(), - tm_mon, - tm_mday, - tm_hour, - tm_min, - tm_sec, - tm_wday, - tm_yday, - tm_isdst, - }) - .map_err(|err| err.to_pyexception(vm)) - } + let mut tm = tm_from_struct_time(t, vm)?; + host_time::check_tm(&mut tm.tm).map_err(|err| err.to_pyexception(vm))?; + Ok(tm) } #[cfg(not(any(unix, windows)))] @@ -462,17 +343,14 @@ mod decl { fn naive_or_local(self, vm: &VirtualMachine) -> PyResult { Ok(match self { Self::Present(t) => t.to_date_time(vm)?, - Self::Missing => Zoned::now().datetime(), + Self::Missing => ZonedDateTime::now().datetime(), }) } } // https://docs.python.org/3/library/time.html?highlight=gmtime#time.gmtime #[pyfunction] - fn gmtime( - secs: OptionalOption>, - vm: &VirtualMachine, - ) -> PyResult { + fn gmtime(secs: OptionalOption, vm: &VirtualMachine) -> PyResult { // `[seconds]` has no text signature; None is the same as missing. let secs = secs.flatten(); cfg_select! { @@ -485,8 +363,8 @@ mod decl { } _ => { let instant = match secs { - Some(secs) => pyobj_to_timestamp(secs, vm)?.to_zoned(TimeZone::UTC), - None => Zoned::now().with_time_zone(TimeZone::UTC), + Some(secs) => pyobj_to_timestamp(secs, vm)?.to_zoned_datetime(TimeZone::UTC), + None => ZonedDateTime::now().with_time_zone(TimeZone::UTC), }; Ok(StructTimeData::new_utc(vm, instant)) } @@ -495,7 +373,7 @@ mod decl { #[pyfunction] fn localtime( - secs: OptionalOption>, + secs: OptionalOption, vm: &VirtualMachine, ) -> PyResult { // `[seconds]` has no text signature; None is the same as missing. @@ -515,7 +393,7 @@ mod decl { } } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn mktime(object: StructTimeData, vm: &VirtualMachine) -> PyResult { #[cfg(unix)] { @@ -532,7 +410,7 @@ mod decl { let datetime = object.to_date_time(vm)?; // mktime interprets struct_time as local time let local_dt = datetime - .to_zoned(TimeZone::system()) + .to_zoned_datetime(TimeZone::system()) .map_err(|_| vm.new_overflow_error("mktime argument out of range"))?; let seconds_since_epoch = local_dt.timestamp().as_second() as f64; Ok(seconds_since_epoch) @@ -547,13 +425,11 @@ mod decl { #[cfg(any(unix, windows))] { let tm = match t { - OptionalArg::Present(value) => { - checked_tm_from_struct_time(&value, vm, "asctime")?.tm - } + OptionalArg::Present(value) => checked_tm_from_struct_time(&value, vm)?.tm, OptionalArg::Missing => { let now = current_time_t(); let local = localtime_from_timestamp(now, vm)?; - checked_tm_from_struct_time(&local, vm, "asctime")?.tm + checked_tm_from_struct_time(&local, vm)?.tm } }; Ok(vm.ctx.new_str(asctime_from_tm(&tm)).into()) @@ -568,7 +444,7 @@ mod decl { } #[pyfunction] - fn ctime(secs: OptionalOption>, vm: &VirtualMachine) -> PyResult { + fn ctime(secs: OptionalOption, vm: &VirtualMachine) -> PyResult { // `[seconds]` has no text signature; None is the same as missing. let secs = secs.flatten(); #[cfg(any(unix, windows))] @@ -578,7 +454,7 @@ mod decl { None => current_time_t(), }; let local = localtime_from_timestamp(ts, vm)?; - let tm = checked_tm_from_struct_time(&local, vm, "asctime")?.tm; + let tm = checked_tm_from_struct_time(&local, vm)?.tm; Ok(asctime_from_tm(&tm)) } @@ -651,11 +527,11 @@ mod decl { #[cfg(any(unix, windows))] { let checked_tm = match t { - OptionalArg::Present(value) => checked_tm_from_struct_time(&value, vm, "strftime")?, + OptionalArg::Present(value) => checked_tm_from_struct_time(&value, vm)?, OptionalArg::Missing => { let now = current_time_t(); let local = localtime_from_timestamp(now, vm)?; - checked_tm_from_struct_time(&local, vm, "strftime")? + checked_tm_from_struct_time(&local, vm)? } }; strftime_crt(&format, checked_tm, vm) @@ -709,12 +585,12 @@ mod decl { Err(vm.new_not_implemented_error("thread time unsupported in this system")) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn thread_time(vm: &VirtualMachine) -> PyResult { Ok(get_thread_time(vm)?.as_secs_f64()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn thread_time_ns(vm: &VirtualMachine) -> PyResult { Ok(get_thread_time(vm)?.as_nanos() as u64) } @@ -752,18 +628,18 @@ mod decl { Err(vm.new_not_implemented_error("process time unsupported in this system")) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn process_time(vm: &VirtualMachine) -> PyResult { Ok(get_process_time(vm)?.as_secs_f64()) } - #[pyfunction] + #[pyfunction(signature_from_flags)] fn process_time_ns(vm: &VirtualMachine) -> PyResult { Ok(get_process_time(vm)?.as_nanos() as u64) } /// Data struct for struct_time - #[pystruct_sequence_data(try_from_object)] + #[pystruct_sequence_data] pub struct StructTimeData { pub tm_year: PyObjectRef, pub tm_mon: PyObjectRef, @@ -788,7 +664,7 @@ mod decl { impl StructTimeData { #[cfg(not(any(unix, windows)))] - fn new_inner(vm: &VirtualMachine, tm: Zoned, isdst: i32) -> Self { + fn new_inner(vm: &VirtualMachine, tm: ZonedDateTime, isdst: i32) -> Self { Self { tm_year: vm.ctx.new_int(tm.year()).into(), tm_mon: vm.ctx.new_int(tm.month()).into(), @@ -806,14 +682,14 @@ mod decl { /// Create struct_time for UTC (gmtime) #[cfg(not(any(unix, windows)))] - fn new_utc(vm: &VirtualMachine, tm: Zoned) -> Self { + fn new_utc(vm: &VirtualMachine, tm: ZonedDateTime) -> Self { Self::new_inner(vm, tm, 0) } /// Create struct_time for local timezone (localtime) #[cfg(not(any(unix, windows)))] fn new_local(vm: &VirtualMachine, tm: DateTime, isdst: i32) -> PyResult { - tm.to_zoned(TimeZone::system()) + tm.to_zoned_datetime(TimeZone::system()) .map(|tm| Self::new_inner(vm, tm, isdst)) .map_err(|_| { vm.new_overflow_error("timestamp is ambiguous for the system timezone") @@ -857,79 +733,100 @@ mod decl { } } - /// Extract fields from StructTimeData into a libc::tm for mktime. + impl TryFromObject for StructTimeData { + fn try_from_object(vm: &VirtualMachine, object: PyObjectRef) -> PyResult { + let tuple = object + .downcast_ref::() + .ok_or_else(|| vm.new_type_error("Tuple or struct_time argument required"))?; + let fields = tuple.as_slice(); + let is_struct_time = object.class().is(PyStructTime::static_type()); + let expected = if is_struct_time { _STRUCT_TM_ITEMS } else { 9 }; + if fields.len() != expected { + return Err(vm.new_type_error("illegal time tuple argument")); + } + // Read tuple storage directly, without invoking subclass iteration. + // The two hidden fields are only meaningful for time.struct_time. + Ok(Self { + tm_year: fields[0].clone(), + tm_mon: fields[1].clone(), + tm_mday: fields[2].clone(), + tm_hour: fields[3].clone(), + tm_min: fields[4].clone(), + tm_sec: fields[5].clone(), + tm_wday: fields[6].clone(), + tm_yday: fields[7].clone(), + tm_isdst: fields[8].clone(), + tm_zone: if is_struct_time { + fields[9].clone() + } else { + vm.ctx.none() + }, + tm_gmtoff: if is_struct_time { + fields[10].clone() + } else { + vm.ctx.none() + }, + }) + } + } + + // Match CPython: convert all nine fields in tuple order, then check the + // adjusted year, then read the optional timezone fields. Do not replace + // exceptions raised by user-defined __index__ implementations. #[cfg(any(unix, windows))] pub(super) fn tm_from_struct_time( t: &StructTimeData, vm: &VirtualMachine, - ) -> PyResult { - let invalid_tuple = || vm.new_type_error("mktime(): illegal time tuple argument"); - let classify_err = |e: PyBaseExceptionRef| { - if e.class().is(vm.ctx.exceptions.overflow_error) { - vm.new_overflow_error("mktime argument out of range") - } else { - invalid_tuple() - } - }; - let year: i32 = t.tm_year.clone().try_into_value(vm).map_err(classify_err)?; + ) -> PyResult { + let year: i32 = t.tm_year.try_to_value(vm)?; + let tm_mon: i32 = t.tm_mon.try_to_value(vm)?; + let tm_mday = t.tm_mday.try_to_value(vm)?; + let tm_hour = t.tm_hour.try_to_value(vm)?; + let tm_min = t.tm_min.try_to_value(vm)?; + let tm_sec = t.tm_sec.try_to_value(vm)?; + let tm_wday: i32 = t.tm_wday.try_to_value(vm)?; + let tm_yday: i32 = t.tm_yday.try_to_value(vm)?; + let tm_isdst = t.tm_isdst.try_to_value(vm)?; if year < i32::MIN + 1900 { return Err(vm.new_overflow_error("year out of range")); } - - host_time::mktime_tm_from_parts(host_time::MktimeTmParts { - year, - tm_sec: t.tm_sec.clone().try_into_value(vm).map_err(classify_err)?, - tm_min: t.tm_min.clone().try_into_value(vm).map_err(classify_err)?, - tm_hour: t.tm_hour.clone().try_into_value(vm).map_err(classify_err)?, - tm_mday: t.tm_mday.clone().try_into_value(vm).map_err(classify_err)?, - tm_mon: t - .tm_mon - .clone() - .try_into_value::(vm) - .map_err(classify_err)?, - tm_yday: t - .tm_yday - .clone() - .try_into_value::(vm) - .map_err(classify_err)?, - tm_isdst: t - .tm_isdst - .clone() - .try_into_value(vm) - .map_err(classify_err)?, - }) - .map_err(|err| match err { - host_time::CheckedTmError::YearOutOfRange => vm.new_overflow_error("year out of range"), - _ => vm.new_type_error("mktime(): illegal time tuple argument"), + #[cfg(unix)] + let zone = if vm.is_none(&t.tm_zone) { + None + } else { + let zone: crate::builtins::PyUtf8StrRef = t.tm_zone.clone().try_into_value(vm)?; + Some(zone.as_str().to_owned()) + }; + #[cfg(unix)] + #[allow(clippy::unnecessary_cast)] // c_long is 32-bit on some Unix targets. + let gmtoff = if vm.is_none(&t.tm_gmtoff) { + None + } else { + Some(t.tm_gmtoff.try_to_value::(vm)? as i64) + }; + host_time::tm_from_parts(host_time::CheckedTmParts { + year: year.into(), + tm_mon: tm_mon.wrapping_sub(1), + tm_mday, + tm_hour, + tm_min, + tm_sec, + tm_wday: tm_wday.wrapping_add(1) % 7, + tm_yday: tm_yday.wrapping_sub(1), + tm_isdst, + #[cfg(unix)] + zone, + #[cfg(unix)] + gmtoff, }) + .map_err(|err| err.to_pyexception(vm)) } #[cfg(any(unix, windows))] #[cfg_attr(target_env = "musl", allow(deprecated))] - fn pyobj_to_time_t(value: Either, vm: &VirtualMachine) -> PyResult { - match value { - Either::A(float) => { - if !float.is_finite() { - return Err(vm.new_value_error("Invalid value for timestamp")); - } - let secs = float.floor(); - #[cfg_attr(target_env = "musl", allow(deprecated))] - if secs < libc::time_t::MIN as f64 || secs > libc::time_t::MAX as f64 { - return Err(vm.new_overflow_error("timestamp out of range for platform time_t")); - } - #[cfg_attr(target_env = "musl", allow(deprecated))] - Ok(secs as libc::time_t) - } - Either::B(int) => { - // try_into is needed on 32-bit platforms where time_t != i64 - #[allow(clippy::useless_conversion)] - #[cfg_attr(target_env = "musl", allow(deprecated))] - let ts: libc::time_t = int.try_into().map_err(|_| { - vm.new_overflow_error("timestamp out of range for platform time_t") - })?; - Ok(ts) - } - } + fn pyobj_to_time_t(value: PyObjectRef, vm: &VirtualMachine) -> PyResult { + super::pytime::object_to_time_t(&value, super::pytime::Round::Floor, vm) + .map(|seconds| seconds as host_time::TimeT) } #[cfg(any(unix, windows))] @@ -1063,8 +960,10 @@ mod platform { } pub(super) fn unix_mktime(t: &StructTimeData, vm: &VirtualMachine) -> PyResult { - let mut tm = super::decl::tm_from_struct_time(t, vm)?; - let timestamp = host_time::mktime(&mut tm); + let mut checked = super::decl::tm_from_struct_time(t, vm)?; + let tm = &mut checked.tm; + tm.tm_wday = -1; + let timestamp = host_time::mktime(tm); if timestamp == -1 && tm.tm_wday == -1 { return Err(vm.new_overflow_error("mktime argument out of range")); } @@ -1248,6 +1147,7 @@ mod platform { use crate::{ PyRef, PyResult, VirtualMachine, builtins::{PyNamespace, PyUtf8StrRef}, + convert::ToPyException, }; use core::time::Duration; use rustpython_host_env::time as host_time; @@ -1281,8 +1181,8 @@ mod platform { when: host_time::TimeT, vm: &VirtualMachine, ) -> PyResult { - let tm = host_time::gmtime_from_timestamp(when) - .ok_or_else(|| vm.new_overflow_error("timestamp out of range for platform time_t"))?; + let tm = + host_time::gmtime_from_timestamp(when).map_err(|error| error.to_pyexception(vm))?; Ok(struct_time_from_tm(vm, tm, "UTC", 0)) } @@ -1290,8 +1190,8 @@ mod platform { when: host_time::TimeT, vm: &VirtualMachine, ) -> PyResult { - let tm = host_time::localtime_from_timestamp(when) - .ok_or_else(|| vm.new_overflow_error("timestamp out of range for platform time_t"))?; + let tm = + host_time::localtime_from_timestamp(when).map_err(|error| error.to_pyexception(vm))?; // Get timezone info from Windows API let info = get_tz_info(); @@ -1301,14 +1201,34 @@ mod platform { (info.standard_bias, &info.standard_name) }; - let gmtoff = -(info.bias + bias) * 60; + let gmtoff = if when < 0 { + // FILETIME marks historical DST as unknown. Derive the offset from + // the converted wall time rather than treating unknown as standard. + let wall_time = jiff::civil::DateTime::new( + (tm.tm_year + 1900) as i16, + (tm.tm_mon + 1) as i8, + tm.tm_mday as i8, + tm.tm_hour as i8, + tm.tm_min as i8, + tm.tm_sec as i8, + 0, + ) + .and_then(|dt| dt.to_zoned_datetime(jiff::tz::TimeZone::UTC)) + .map_err(|_| vm.new_overflow_error("timestamp out of range for Windows FILETIME"))?; + i32::try_from(wall_time.timestamp().as_second() - when) + .map_err(|_| vm.new_overflow_error("timezone offset out of range"))? + } else { + -(info.bias + bias) * 60 + }; Ok(struct_time_from_tm(vm, tm, name, gmtoff)) } pub(super) fn win_mktime(t: &StructTimeData, vm: &VirtualMachine) -> PyResult { - let mut tm = super::decl::tm_from_struct_time(t, vm)?; - let timestamp = host_time::mktime(&mut tm); + let mut checked = super::decl::tm_from_struct_time(t, vm)?; + let tm = &mut checked.tm; + tm.tm_wday = -1; + let timestamp = host_time::mktime(tm); if timestamp == -1 && tm.tm_wday == -1 { return Err(vm.new_overflow_error("mktime argument out of range")); } diff --git a/crates/vm/src/stdlib/time/pytime.rs b/crates/vm/src/stdlib/time/pytime.rs new file mode 100644 index 00000000000..2898dc88312 --- /dev/null +++ b/crates/vm/src/stdlib/time/pytime.rs @@ -0,0 +1,268 @@ +//! Signed nanosecond timestamps and the rounding used by Python's time APIs. + +#![cfg_attr(target_env = "musl", allow(deprecated))] + +use crate::{AsObject, PyObject, PyResult, VirtualMachine, builtins::PyFloat}; +use num_traits::ToPrimitive; +use rustpython_host_env::time::{SEC_TO_NS, SEC_TO_US, US_TO_NS}; + +#[cfg(any(unix, windows))] +pub(crate) use rustpython_host_env::time::TimeT; +#[cfg(not(any(unix, windows)))] +pub(crate) type TimeT = i64; + +const TIME_T_MIN: i64 = TimeT::MIN as _; +const TIME_T_MAX: i64 = TimeT::MAX as _; +const PYTIME_OVERFLOW: &str = "timestamp out of range for C PyTime_t"; +const TIME_T_OVERFLOW: &str = "timestamp out of range for platform time_t"; + +/// `PY_TIMEOUT_MAX`: the longest finite native thread wait, in microseconds. +pub(crate) const THREAD_TIMEOUT_MAX_MICROSECONDS: i64 = cfg_select! { + windows => 0xffff_fffe * 1_000, + unix => i64::MAX / 1_000, + _ => i64::MAX, +}; + +/// `_thread.TIMEOUT_MAX` also respects the signed nanosecond representation. +#[cfg(feature = "threading")] +pub(crate) const THREAD_TIMEOUT_MAX_SECONDS: i64 = { + let platform_max = THREAD_TIMEOUT_MAX_MICROSECONDS / 1_000_000; + let pytime_max = i64::MAX / 1_000_000_000; + if platform_max < pytime_max { + platform_max + } else { + pytime_max + } +}; + +#[derive(Clone, Copy)] +pub enum Round { + Floor, + Ceiling, + HalfEven, + Up, +} + +impl Round { + pub(crate) fn from_int(value: i32, vm: &VirtualMachine) -> PyResult { + match value { + 0 => Ok(Self::Floor), + 1 => Ok(Self::Ceiling), + 2 => Ok(Self::HalfEven), + 3 => Ok(Self::Up), + _ => Err(vm.new_value_error("invalid rounding")), + } + } + + fn round(self, value: f64) -> f64 { + match self { + Self::Floor => value.floor(), + Self::Ceiling => value.ceil(), + Self::HalfEven => value.round_ties_even(), + Self::Up if value >= 0.0 => value.ceil(), + Self::Up => value.floor(), + } + } + + #[must_use] + pub fn divide(self, value: i64, divisor: i64) -> i64 { + debug_assert!(divisor > 1); + let quotient = value / divisor; + let remainder = value % divisor; + let round_away = match self { + Self::Floor => remainder < 0, + Self::Ceiling => remainder > 0, + Self::HalfEven => { + let remainder = remainder.abs(); + remainder > divisor / 2 + || (divisor % 2 == 0 && remainder == divisor / 2 && quotient % 2 != 0) + } + Self::Up => remainder != 0, + }; + // Adjust the quotient, not the input: adding to i64::MAX or + // subtracting from i64::MIN before dividing would overflow. + quotient + if round_away { value.signum() } else { 0 } + } +} + +pub(crate) fn from_seconds(seconds: i32) -> i64 { + i64::from(seconds) * SEC_TO_NS +} + +fn index_seconds(object: &PyObject, message: &str, vm: &VirtualMachine) -> PyResult { + let seconds = object.try_index(vm).map_err(|err| { + if err.fast_isinstance(vm.ctx.exceptions.overflow_error) { + vm.new_overflow_error(message) + } else { + err + } + })?; + seconds + .as_bigint() + .to_i64() + .ok_or_else(|| vm.new_overflow_error(message)) +} + +fn float_seconds(object: &PyObject, vm: &VirtualMachine) -> PyResult { + // PyFloat_AsDouble bypasses __float__ overrides on float subclasses. + let seconds = match object.downcast_ref::() { + Some(float) => float.to_f64(), + None => object.try_float(vm)?.to_f64(), + }; + if seconds.is_nan() { + return Err(vm.new_value_error("Invalid value NaN (not a number)")); + } + Ok(seconds) +} + +pub fn from_seconds_object(object: &PyObject, round: Round, vm: &VirtualMachine) -> PyResult { + from_object(object, SEC_TO_NS, round, vm) +} + +pub fn from_milliseconds_object( + object: &PyObject, + round: Round, + vm: &VirtualMachine, +) -> PyResult { + from_object(object, SEC_TO_NS / 1000, round, vm) +} + +fn from_object(object: &PyObject, scale: i64, round: Round, vm: &VirtualMachine) -> PyResult { + // _PyTime_FromSecondsObject and _PyTime_FromMillisecondsObject use + // __index__ before __float__ and bound the result to signed nanoseconds. + if object.number().is_index() { + index_seconds(object, PYTIME_OVERFLOW, vm)? + .checked_mul(scale) + .ok_or_else(|| vm.new_overflow_error(PYTIME_OVERFLOW)) + } else { + let nanoseconds = round.round(float_seconds(object, vm)? * scale as f64); + let minimum = i64::MIN as f64; + // The maximum rounds up to 2**63 as a double, so use an exclusive bound. + if !(minimum..-minimum).contains(&nanoseconds) { + return Err(vm.new_overflow_error(PYTIME_OVERFLOW)); + } + Ok(nanoseconds as i64) + } +} + +/// Check the platform wait limit after the caller has handled negative values +/// and any API-specific indefinite-wait sentinel. +pub fn check_thread_timeout(nanoseconds: i64, vm: &VirtualMachine) -> PyResult<()> { + if Round::Up.divide(nanoseconds, 1_000) > THREAD_TIMEOUT_MAX_MICROSECONDS { + Err(vm.new_overflow_error("timeout value is too large")) + } else { + Ok(()) + } +} + +fn check_time_t(seconds: i64, vm: &VirtualMachine) -> PyResult { + if !(TIME_T_MIN..=TIME_T_MAX).contains(&seconds) { + return Err(vm.new_overflow_error(TIME_T_OVERFLOW)); + } + Ok(seconds) +} + +fn float_to_time_t(seconds: f64, vm: &VirtualMachine) -> PyResult { + let minimum = TIME_T_MIN as f64; + if !(minimum..-minimum).contains(&seconds) { + return Err(vm.new_overflow_error(TIME_T_OVERFLOW)); + } + Ok(seconds as i64) +} + +pub(crate) fn object_to_time_t( + object: &PyObject, + round: Round, + vm: &VirtualMachine, +) -> PyResult { + if object.number().is_index() { + check_time_t(index_seconds(object, TIME_T_OVERFLOW, vm)?, vm) + } else { + float_to_time_t(round.round(float_seconds(object, vm)?), vm) + } +} + +pub(crate) fn object_to_denominator( + object: &PyObject, + denominator: i64, + round: Round, + vm: &VirtualMachine, +) -> PyResult<(i64, i64)> { + if object.number().is_index() { + return Ok(( + check_time_t(index_seconds(object, TIME_T_OVERFLOW, vm)?, vm)?, + 0, + )); + } + let value = float_seconds(object, vm)?; + let mut seconds = value.trunc(); + let denominator = denominator as f64; + let mut numerator = round.round(value.fract() * denominator); + if numerator >= denominator { + numerator -= denominator; + seconds += 1.0; + } else if numerator < 0.0 { + numerator += denominator; + seconds -= 1.0; + } + Ok((float_to_time_t(seconds, vm)?, numerator as i64)) +} + +fn as_time_pair(value: i64, denominator: i64, minimum: i64, maximum: i64) -> (i64, i64) { + let seconds = value.div_euclid(denominator); + if seconds < minimum { + (minimum, 0) + } else if seconds > maximum { + (maximum, 0) + } else { + (seconds, value.rem_euclid(denominator)) + } +} + +pub(crate) fn as_timespec( + nanoseconds: i64, + clamp: bool, + vm: &VirtualMachine, +) -> PyResult<(i64, i64)> { + if !clamp { + check_time_t(nanoseconds.div_euclid(SEC_TO_NS), vm)?; + } + Ok(as_time_pair(nanoseconds, SEC_TO_NS, TIME_T_MIN, TIME_T_MAX)) +} + +pub(crate) fn as_timeval( + nanoseconds: i64, + round: Round, + clamp: bool, + vm: &VirtualMachine, +) -> PyResult<(i64, i64)> { + // Windows uses C long for timeval.tv_sec even when time_t is 64-bit. + #[cfg(windows)] + let (minimum, maximum) = (i64::from(i32::MIN), i64::from(i32::MAX)); + #[cfg(not(windows))] + let (minimum, maximum) = (TIME_T_MIN, TIME_T_MAX); + let microseconds = round.divide(nanoseconds, US_TO_NS); + let seconds = microseconds.div_euclid(SEC_TO_US); + if !clamp && !(minimum..=maximum).contains(&seconds) { + return Err(vm.new_overflow_error(TIME_T_OVERFLOW)); + } + Ok(as_time_pair(microseconds, SEC_TO_US, minimum, maximum)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn thread_wait_bound_checks_rounded_up_microseconds() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + if let Some(max_nanoseconds) = THREAD_TIMEOUT_MAX_MICROSECONDS.checked_mul(1_000) { + assert!(check_thread_timeout(max_nanoseconds, vm).is_ok()); + let error = check_thread_timeout(max_nanoseconds + 1, vm).unwrap_err(); + assert!(error.fast_isinstance(vm.ctx.exceptions.overflow_error)); + } else { + assert!(check_thread_timeout(i64::MAX, vm).is_ok()); + } + }); + } +} diff --git a/crates/vm/src/stdlib/typevar.rs b/crates/vm/src/stdlib/typevar.rs index 19ad3562540..3dc6fa52dd4 100644 --- a/crates/vm/src/stdlib/typevar.rs +++ b/crates/vm/src/stdlib/typevar.rs @@ -6,14 +6,75 @@ pub use typevar::*; pub(crate) mod typevar { use crate::{ AsObject, Context, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine, - builtins::{PyTuple, PyTupleRef, PyType, PyTypeRef, make_union}, - common::lock::PyMutex, - function::{FuncArgs, PyComparisonValue}, + builtins::{PyStr, PyTuple, PyTupleRef, PyType, PyTypeRef, make_union}, + common::{lock::PyMutex, wtf8::Wtf8Buf}, + function::{FromArgs, FuncArgs, OptionalArg, PosArgs, PyComparisonValue}, protocol::PyNumberMethods, stdlib::_typing::{call_typing_func_object, decl::const_evaluator_alloc}, types::{AsNumber, Comparable, Constructor, Iterable, PyComparisonOp, Representable}, }; + // Bind raw objects first: Clinic rejects the complete argument layout before + // checking the name or invoking any variance flag's __bool__ method. + // Keep unused raw fields alive in slot_new through __module__ setup too. + #[derive(FromArgs)] + struct TypeParameterArgs { + #[pyarg(any)] + name: PyObjectRef, + #[pyarg(flatten)] + constraints: Constraints, + #[pyarg(named, optional)] + bound: OptionalArg, + #[pyarg(named, optional)] + default: OptionalArg, + #[pyarg(named, optional)] + covariant: OptionalArg, + #[pyarg(named, optional)] + contravariant: OptionalArg, + #[pyarg(named, optional)] + infer_variance: OptionalArg, + } + + type TypeVarArgs = TypeParameterArgs; + + struct Variance { + covariant: bool, + contravariant: bool, + infer_variance: bool, + } + + impl TypeParameterArgs { + fn variance(&self, constructor: &str, vm: &VirtualMachine) -> PyResult { + if !self.name.downcastable::() { + return Err(vm.new_type_error(format!( + "{constructor}() argument 'name' must be str, not {}", + self.name.class().name() + ))); + } + + // Borrow the raw flags so their finalizers cannot run between the + // conversions or before the constructor has finished using them. + let truth = |value: &OptionalArg| match value { + OptionalArg::Present(value) => value.try_to_bool(vm), + OptionalArg::Missing => Ok(false), + }; + let covariant = truth(&self.covariant)?; + let contravariant = truth(&self.contravariant)?; + let infer_variance = truth(&self.infer_variance)?; + if covariant && contravariant { + return Err(vm.new_value_error("Bivariant types are not supported.")); + } + if infer_variance && (covariant || contravariant) { + return Err(vm.new_value_error("Variance cannot be specified with infer_variance.")); + } + Ok(Variance { + covariant, + contravariant, + infer_variance, + }) + } + } + fn type_check(arg: PyObjectRef, msg: &str, vm: &VirtualMachine) -> PyResult { // Calling typing.py here leads to bootstrapping problems if vm.is_none(&arg) { @@ -301,115 +362,55 @@ pub(crate) mod typevar { type Args = FuncArgs; fn slot_new(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { - let typevar = ::py_new(&cls, args, vm)?; - let obj = typevar.into_ref_with_type(vm, cls)?; - let obj_ref: PyObjectRef = obj.into(); - set_module_from_caller(&obj_ref, vm)?; - Ok(obj_ref) - } - - fn py_new(_cls: &Py, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let mut kwargs = args.kwargs; - // Parse arguments manually - let (name, constraints) = if args.args.is_empty() { - // Check if name is provided as keyword argument - if let Some(name) = kwargs.swap_remove("name") { - (name, vec![]) - } else { - return Err( - vm.new_type_error("TypeVar() missing required argument: 'name' (pos 1)") - ); - } - } else if args.args.len() == 1 { - (args.args[0].clone(), vec![]) - } else { - let name = args.args[0].clone(); - let constraints = args.args[1..].to_vec(); - (name, constraints) - }; - - let bound = kwargs.swap_remove("bound"); - let covariant = kwargs - .swap_remove("covariant") - .map(|v| v.try_to_bool(vm)) - .transpose()? - .unwrap_or(false); - let contravariant = kwargs - .swap_remove("contravariant") - .map(|v| v.try_to_bool(vm)) - .transpose()? - .unwrap_or(false); - let infer_variance = kwargs - .swap_remove("infer_variance") - .map(|v| v.try_to_bool(vm)) - .transpose()? - .unwrap_or(false); - let default = kwargs.swap_remove("default"); - - // Check for unexpected keyword arguments - if let Some(invalid_key) = kwargs.keys().next() { - return Err( - vm.new_unexpected_keyword_type_error(Some("typevar"), &invalid_key.to_string()) - ); - } - - // Check for invalid combinations - if covariant && contravariant { - return Err(vm.new_value_error("Bivariant type variables are not supported.")); - } - - if infer_variance && (covariant || contravariant) { - return Err(vm.new_value_error("Variance cannot be specified with infer_variance")); - } - - // Handle constraints and bound - let (constraints_obj, evaluate_constraints) = if !constraints.is_empty() { - // Check for single constraint - if constraints.len() == 1 { - return Err(vm.new_type_error("A single constraint is not allowed")); - } - if bound.is_some() { - return Err(vm.new_type_error("Constraints cannot be used with bound")); + let parameter: TypeVarArgs = args.bind_for(vm, "typevar")?; + let Variance { + covariant, + contravariant, + infer_variance, + } = parameter.variance("typevar", vm)?; + let constraints = parameter.constraints; + + // An explicit None is the same as an omitted bound. Check a real + // bound before reporting constraint count or bound conflicts. + let bound = match ¶meter.bound { + OptionalArg::Present(bound) if !vm.is_none(bound) => { + Some(type_check(bound.clone(), "Bound must be a type.", vm)?) } - let constraints_tuple = vm.ctx.new_tuple(constraints); - (constraints_tuple.into(), vm.ctx.none()) - } else { - (vm.ctx.none(), vm.ctx.none()) + _ => None, }; - - // Handle bound - let (bound_obj, evaluate_bound) = if let Some(bound) = bound { - if vm.is_none(&bound) { - (vm.ctx.none(), vm.ctx.none()) - } else { - // Type check the bound - let bound = type_check(bound, "Bound must be a type.", vm)?; - (bound, vm.ctx.none()) + let constraints = match constraints.as_ref().len() { + 0 => vm.ctx.none(), + 1 => return Err(vm.new_type_error("A single constraint is not allowed")), + _ if bound.is_some() => { + return Err(vm.new_type_error("Constraints cannot be combined with bound=...")); } - } else { - (vm.ctx.none(), vm.ctx.none()) + _ => vm.ctx.new_tuple(constraints.into_vec()).into(), }; - - // Handle default value - let (default_value, evaluate_default) = if let Some(default) = default { - (default, vm.ctx.none()) - } else { - // If no default provided, use NoDefault singleton - (vm.ctx.typing_no_default.clone().into(), vm.ctx.none()) - }; - - Ok(Self { - name, - bound: PyMutex::new(bound_obj), - evaluate_bound, - constraints: PyMutex::new(constraints_obj), - evaluate_constraints, + let default_value = parameter + .default + .unwrap_or_else(|| vm.ctx.typing_no_default.clone().into()); + + let typevar = Self { + name: parameter.name, + bound: PyMutex::new(bound.unwrap_or_else(|| vm.ctx.none())), + evaluate_bound: vm.ctx.none(), + constraints: PyMutex::new(constraints), + evaluate_constraints: vm.ctx.none(), default_value: PyMutex::new(default_value), - evaluate_default: PyMutex::new(evaluate_default), + evaluate_default: PyMutex::new(vm.ctx.none()), covariant, contravariant, infer_variance, - }) + }; + + let obj = typevar.into_ref_with_type(vm, cls)?; + let obj_ref: PyObjectRef = obj.into(); + set_module_from_caller(&obj_ref, vm)?; + Ok(obj_ref) + } + + fn py_new(_cls: &Py, _args: Self::Args, _vm: &VirtualMachine) -> PyResult { + unimplemented!("use slot_new") } } @@ -566,67 +567,19 @@ pub(crate) mod typevar { type Args = FuncArgs; fn slot_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let mut kwargs = args.kwargs; - // Parse arguments manually - let name = if args.args.is_empty() { - // Check if name is provided as keyword argument - if let Some(name) = kwargs.swap_remove("name") { - name - } else { - return Err( - vm.new_type_error("ParamSpec() missing required argument: 'name' (pos 1)") - ); - } - } else if args.args.len() == 1 { - args.args[0].clone() - } else { - return Err(vm.new_type_error("ParamSpec() takes at most 1 positional argument")); - }; - - let bound = kwargs - .swap_remove("bound") - .map(|b| type_check(b, "Bound must be a type.", vm)) - .transpose()?; - let covariant = kwargs - .swap_remove("covariant") - .map(|v| v.try_to_bool(vm)) - .transpose()? - .unwrap_or(false); - let contravariant = kwargs - .swap_remove("contravariant") - .map(|v| v.try_to_bool(vm)) - .transpose()? - .unwrap_or(false); - let infer_variance = kwargs - .swap_remove("infer_variance") - .map(|v| v.try_to_bool(vm)) - .transpose()? - .unwrap_or(false); - let default = kwargs.swap_remove("default"); - - // Check for unexpected keyword arguments - if let Some(invalid_key) = kwargs.keys().next() { - return Err(vm.new_unexpected_keyword_type_error( - Some("paramspec"), - &invalid_key.to_string(), - )); - } - - // Check for invalid combinations - if covariant && contravariant { - return Err(vm.new_value_error("Bivariant type variables are not supported.")); - } - - if infer_variance && (covariant || contravariant) { - return Err(vm.new_value_error("Variance cannot be specified with infer_variance")); - } - - // Handle default value - let default_value = default.unwrap_or_else(|| vm.ctx.typing_no_default.clone().into()); + let args: TypeParameterArgs = args.bind_for(vm, "paramspec")?; + let Variance { + covariant, + contravariant, + infer_variance, + } = args.variance("paramspec", vm)?; + let default_value = args + .default + .unwrap_or_else(|| vm.ctx.typing_no_default.clone().into()); let paramspec = Self { - name, - bound, + name: args.name, + bound: args.bound.into_option(), default_value: PyMutex::new(default_value), evaluate_default: PyMutex::new(vm.ctx.none()), covariant, @@ -678,8 +631,16 @@ pub(crate) mod typevar { pub struct TypeVarTuple { #[pymember(name = "__name__")] name: PyObjectRef, + #[pymember(name = "__bound__")] + bound: Option, default_value: PyMutex, evaluate_default: PyMutex, + #[pymember(name = "__covariant__")] + covariant: bool, + #[pymember(name = "__contravariant__")] + contravariant: bool, + #[pymember(name = "__infer_variance__")] + infer_variance: bool, } #[pyclass( @@ -774,45 +735,24 @@ pub(crate) mod typevar { type Args = FuncArgs; fn slot_new(cls: PyTypeRef, args: Self::Args, vm: &VirtualMachine) -> PyResult { - let mut kwargs = args.kwargs; - // Parse arguments manually - let name = if args.args.is_empty() { - // Check if name is provided as keyword argument - if let Some(name) = kwargs.swap_remove("name") { - name - } else { - return Err(vm.new_type_error( - "TypeVarTuple() missing required argument: 'name' (pos 1)", - )); - } - } else if args.args.len() == 1 { - args.args[0].clone() - } else { - return Err(vm.new_type_error("TypeVarTuple() takes at most 1 positional argument")); - }; - - let default = kwargs.swap_remove("default"); - - // Check for unexpected keyword arguments - if let Some(invalid_key) = kwargs.keys().next() { - return Err(vm.new_unexpected_keyword_type_error( - Some("typevartuple"), - &invalid_key.to_string(), - )); - } - - // Handle default value - let (default_value, evaluate_default) = if let Some(default) = default { - (default, vm.ctx.none()) - } else { - // If no default provided, use NoDefault singleton - (vm.ctx.typing_no_default.clone().into(), vm.ctx.none()) - }; + let args: TypeParameterArgs = args.bind_for(vm, "typevartuple")?; + let Variance { + covariant, + contravariant, + infer_variance, + } = args.variance("typevartuple", vm)?; + let default_value = args + .default + .unwrap_or_else(|| vm.ctx.typing_no_default.clone().into()); let typevartuple = Self { - name, + name: args.name, + bound: args.bound.into_option(), default_value: PyMutex::new(default_value), - evaluate_default: PyMutex::new(evaluate_default), + evaluate_default: PyMutex::new(vm.ctx.none()), + covariant, + contravariant, + infer_variance, }; let obj = typevartuple.into_ref_with_type(vm, cls)?; @@ -828,9 +768,23 @@ pub(crate) mod typevar { impl Representable for TypeVarTuple { #[inline(always)] - fn repr_str(zelf: &crate::Py, vm: &VirtualMachine) -> PyResult { - let name = zelf.name.str(vm)?; - Ok(name.to_string()) + fn repr_wtf8(zelf: &crate::Py, _vm: &VirtualMachine) -> PyResult { + let name = zelf + .name + .downcast_ref::() + .expect("TypeVarTuple name must be a string"); + let prefix = if zelf.infer_variance { + "" + } else if zelf.covariant { + "+" + } else if zelf.contravariant { + "-" + } else { + "~" + }; + let mut result = Wtf8Buf::from(prefix); + result.push_wtf8(name.as_wtf8()); + Ok(result) } } @@ -838,8 +792,12 @@ pub(crate) mod typevar { pub fn new(name: PyObjectRef, vm: &VirtualMachine) -> Self { Self { name, + bound: None, default_value: PyMutex::new(vm.ctx.typing_no_default.clone().into()), evaluate_default: PyMutex::new(vm.ctx.none()), + covariant: false, + contravariant: false, + infer_variance: true, } } } diff --git a/crates/vm/src/stdlib/winreg.rs b/crates/vm/src/stdlib/winreg.rs index f7ca0f95f72..e3e0dc66096 100644 --- a/crates/vm/src/stdlib/winreg.rs +++ b/crates/vm/src/stdlib/winreg.rs @@ -9,11 +9,11 @@ mod winreg { use crate::common::hash::PyHash; use crate::convert::{ToPyException, TryFromObject}; use crate::exceptions::nul_char_error; - use crate::function::FuncArgs; + use crate::function::PyComparisonValue; use crate::object::AsObject; use crate::protocol::PyNumberMethods; - use crate::types::{AsNumber, Hashable}; - use crate::{Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine}; + use crate::types::{AsNumber, Comparable, Hashable, PyComparisonOp}; + use crate::{Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine}; use core::ptr; use crossbeam_utils::atomic::AtomicCell; use malachite_bigint::Sign; @@ -33,21 +33,52 @@ mod winreg { std::io::Error::from_raw_os_error(code).to_pyexception(vm) } - /// Wrapper type for HKEY that can be created from PyHkey or int - struct HKEYArg(host_winreg::HKEY); + // Snapshot the handle during argument conversion, keeping its owner alive + // while later argument conversions or audit hooks can invoke Python code. + #[derive(Debug)] + struct HKEYArg(host_winreg::HKEY, #[allow(dead_code)] Option>); impl TryFromObject for HKEYArg { fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult { // Try PyHkey first - if let Some(hkey_obj) = obj.downcast_ref::() { - return Ok(Self(hkey_obj.hkey.load())); + let obj = match obj.downcast::() { + Ok(key) => return Ok(Self(key.hkey.load(), Some(key))), + Err(obj) => obj, + }; + if vm.is_none(&obj) { + return Err(vm.new_type_error("None is not a valid HKEY in this context")); + } + let Some(value) = obj.downcast_ref::() else { + return Err(vm.new_type_error("The object is not a PyHKEY object")); + }; + let value = value.as_bigint(); + let negative = value.sign() == Sign::Minus; + let handle = if negative { + value.to_isize().map(|v| v as usize) + } else { + value.to_usize() } - // Then try int - let handle = usize::try_from_object(vm, obj)?; - Ok(Self(handle as host_winreg::HKEY)) + .ok_or_else(|| { + let message = if cfg!(target_pointer_width = "64") { + "int too big to convert" + } else if negative { + "Python int too large to convert to C long" + } else { + "Python int too large to convert to C unsigned long" + }; + vm.new_overflow_error(message) + })?; + Ok(Self(handle as host_winreg::HKEY, None)) } } + fn audit_wide(value: Option<&widestring::WideCStr>, vm: &VirtualMachine) -> PyObjectRef { + value.map_or_else( + || vm.ctx.none(), + |value| vm.ctx.new_str(Wtf8Buf::from_wide(value.as_slice())).into(), + ) + } + // access rights #[pyattr] pub(super) use host_winreg::{ @@ -153,7 +184,7 @@ mod winreg { } } - #[pyclass(with(AsNumber, Hashable))] + #[pyclass(with(AsNumber, Comparable, Hashable))] impl Py { #[pygetset] fn handle(&self) -> usize { @@ -172,15 +203,15 @@ mod winreg { if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("RegCloseKey failed with error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pymethod] - fn Detach(&self) -> usize { - // Atomically swap the handle with null and return the old value - let old_hkey = self.hkey.swap(core::ptr::null_mut()); - old_hkey as usize + fn Detach(&self, vm: &VirtualMachine) -> PyResult { + vm.audit("winreg.PyHKEY.Detach", || (self.hkey.load() as isize,))?; + // Read again after the hook: it may have detached or closed us. + Ok(self.hkey.swap(core::ptr::null_mut()) as usize) } #[pymethod] @@ -189,7 +220,13 @@ mod winreg { } #[pymethod] - fn __exit__(zelf: PyRef, _args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { + fn __exit__( + zelf: PyRef, + _exc_type: PyObjectRef, + _exc_value: PyObjectRef, + _traceback: PyObjectRef, + vm: &VirtualMachine, + ) -> PyResult<()> { zelf.Close(vm) } @@ -208,6 +245,26 @@ mod winreg { } } + impl Comparable for PyHkey { + fn cmp( + zelf: &Py, + other: &PyObject, + op: PyComparisonOp, + _vm: &VirtualMachine, + ) -> PyResult { + op.eq_only(|| { + if other.class().is(zelf.class()) + && let Some(other) = other.downcast_ref::() + { + return Ok(PyComparisonValue::Implemented( + zelf.hkey.load() == other.hkey.load(), + )); + } + Ok(PyComparisonValue::NotImplemented) + }) + } + } + impl Hashable for PyHkey { // CPython uses PyObject_GenericHash which hashes the object's address fn hash(zelf: &Py, _vm: &VirtualMachine) -> PyResult { @@ -257,17 +314,19 @@ mod winreg { #[pyfunction] fn ConnectRegistry( computer_name: Option, - key: PyRef, + key: HKEYArg, vm: &VirtualMachine, ) -> PyResult { let computer_name = computer_name .map(WideCString::from_str) .transpose() .map_err(|e| e.to_pyexception(vm))?; + vm.audit("winreg.ConnectRegistry", || { + (audit_wide(computer_name.as_deref(), vm), key.0 as isize) + })?; let mut ret_key = core::ptr::null_mut(); - let res = unsafe { - host_winreg::connect_registry(computer_name.as_deref(), key.hkey.load(), &mut ret_key) - }; + let res = + unsafe { host_winreg::connect_registry(computer_name.as_deref(), key.0, &mut ret_key) }; if res == 0 { Ok(PyHkey::new(ret_key)) } else { @@ -276,12 +335,29 @@ mod winreg { } #[pyfunction] - fn CreateKey(key: PyRef, sub_key: String, vm: &VirtualMachine) -> PyResult { - let sub_key = WideCString::from_str(sub_key).map_err(|e| e.to_pyexception(vm))?; + fn CreateKey( + key: HKEYArg, + sub_key: Option>, + vm: &VirtualMachine, + ) -> PyResult { + let sub_key = sub_key + .as_ref() + .map(|value| value.as_wtf8().to_wide_cstring()) + .transpose() + .map_err(|_| nul_char_error(vm))?; + vm.audit("winreg.CreateKey", || { + ( + key.0 as isize, + audit_wide(sub_key.as_deref(), vm), + host_winreg::KEY_WRITE as isize, + ) + })?; let mut out_key = core::ptr::null_mut(); - let res = unsafe { host_winreg::create_key(key.hkey.load(), &sub_key, &mut out_key) }; + let res = unsafe { host_winreg::create_key(key.0, sub_key.as_deref(), &mut out_key) }; if res == 0 { - Ok(PyHkey::new(out_key)) + let result = PyHkey::new(out_key); + vm.audit("winreg.OpenKey/result", || (out_key as isize,))?; + Ok(result) } else { Err(os_error_from_windows_code(vm, res as i32)) } @@ -290,105 +366,174 @@ mod winreg { #[derive(FromArgs, Debug)] struct CreateKeyExArgs { #[pyarg(any)] - key: PyRef, + key: HKEYArg, #[pyarg(any)] - sub_key: String, + sub_key: Option>, #[pyarg(any, default)] - reserved: u32, - #[pyarg(any, default = host_winreg::KEY_WRITE, py_default = "winreg.KEY_WRITE")] - access: u32, + reserved: i32, + #[pyarg(any, default = host_winreg::KEY_WRITE as i32, py_default = "winreg.KEY_WRITE")] + access: i32, } #[pyfunction] fn CreateKeyEx(args: CreateKeyExArgs, vm: &VirtualMachine) -> PyResult { - let wide_sub_key = WideCString::from_str(args.sub_key).map_err(|e| e.to_pyexception(vm))?; + let wide_sub_key = args + .sub_key + .as_ref() + .map(|value| value.as_wtf8().to_wide_cstring()) + .transpose() + .map_err(|_| nul_char_error(vm))?; + vm.audit("winreg.CreateKey", || { + ( + args.key.0 as isize, + audit_wide(wide_sub_key.as_deref(), vm), + args.access as u32 as isize, + ) + })?; let mut res: host_winreg::HKEY = core::ptr::null_mut(); let err = unsafe { - let key = args.key.hkey.load(); + let key = args.key.0; host_winreg::create_key_ex( key, - &wide_sub_key, - args.reserved, + wide_sub_key.as_deref(), + args.reserved as u32, core::ptr::null_mut(), host_winreg::REG_OPTION_NON_VOLATILE, - args.access, + args.access as u32, core::ptr::null(), &mut res, core::ptr::null_mut(), ) }; if err == 0 { - Ok(PyHkey { - #[allow(clippy::arc_with_non_send_sync)] - hkey: AtomicHKEY::new(res), - }) + let result = PyHkey::new(res); + vm.audit("winreg.OpenKey/result", || (res as isize,))?; + Ok(result) } else { - Err(vm.new_os_error(format!("error code: {err}"))) + Err(os_error_from_windows_code(vm, err as i32)) } } #[pyfunction] - fn CloseKey(hkey: PyRef, vm: &VirtualMachine) -> PyResult<()> { - hkey.Close(vm) + fn CloseKey(hkey: PyObjectRef, vm: &VirtualMachine) -> PyResult<()> { + if let Some(key) = hkey.downcast_ref::() { + return key.Close(vm); + } + if vm.is_none(&hkey) { + return Ok(()); + } + let key = HKEYArg::try_from_object(vm, hkey)?.0; + let res = if key.is_null() { + 0 + } else { + host_winreg::close_key(key) + }; + if res == 0 { + Ok(()) + } else { + Err(os_error_from_windows_code(vm, res as i32)) + } } #[pyfunction] - fn DeleteKey(key: PyRef, sub_key: String, vm: &VirtualMachine) -> PyResult<()> { + fn DeleteKey(key: HKEYArg, sub_key: String, vm: &VirtualMachine) -> PyResult<()> { let sub_key = WideCString::from_str(sub_key).map_err(|e| e.to_pyexception(vm))?; - let res = unsafe { host_winreg::delete_key(key.hkey.load(), &sub_key) }; + vm.audit("winreg.DeleteKey", || { + (key.0 as isize, audit_wide(Some(&sub_key), vm), 0) + })?; + let res = unsafe { host_winreg::delete_key(key.0, &sub_key) }; + if res == 0 { + Ok(()) + } else { + Err(os_error_from_windows_code(vm, res as i32)) + } + } + + #[derive(FromArgs)] + struct DeleteTreeSubKey { + #[pyarg(positional, optional)] + sub_key: Option>, + } + + #[pyfunction] + fn DeleteTree( + key: HKEYArg, + DeleteTreeSubKey { sub_key }: DeleteTreeSubKey, + vm: &VirtualMachine, + ) -> PyResult<()> { + let wide_sub_key = sub_key + .as_ref() + .map(|s| WideCString::from_vec(s.as_wtf8().encode_wide().collect::>())) + .transpose() + .map_err(|_| nul_char_error(vm))?; + vm.audit("winreg.DeleteTree", || (key.0 as isize, sub_key))?; + let res = vm + .allow_threads(|| unsafe { host_winreg::delete_tree(key.0, wide_sub_key.as_deref()) }); if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pyfunction] - fn DeleteValue(key: PyRef, value: Option, vm: &VirtualMachine) -> PyResult<()> { + fn DeleteValue(key: HKEYArg, value: Option, vm: &VirtualMachine) -> PyResult<()> { let wide_value = value .map(WideCString::from_str) .transpose() .map_err(|e| e.to_pyexception(vm))?; - let res = unsafe { host_winreg::delete_value(key.hkey.load(), wide_value.as_deref()) }; + vm.audit("winreg.DeleteValue", || { + (key.0 as isize, audit_wide(wide_value.as_deref(), vm)) + })?; + let res = unsafe { host_winreg::delete_value(key.0, wide_value.as_deref()) }; if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[derive(FromArgs, Debug)] struct DeleteKeyExArgs { #[pyarg(any)] - key: PyRef, + key: HKEYArg, #[pyarg(any)] sub_key: String, - #[pyarg(any, default = host_winreg::KEY_WOW64_64KEY, py_default = "winreg.KEY_WOW64_64KEY")] - access: u32, + #[pyarg(any, default = host_winreg::KEY_WOW64_64KEY as i32, py_default = "winreg.KEY_WOW64_64KEY")] + access: i32, #[pyarg(any, default)] - reserved: u32, + reserved: i32, } #[pyfunction] fn DeleteKeyEx(args: DeleteKeyExArgs, vm: &VirtualMachine) -> PyResult<()> { let wide_sub_key = WideCString::from_str(args.sub_key).map_err(|e| e.to_pyexception(vm))?; + vm.audit("winreg.DeleteKey", || { + ( + args.key.0 as isize, + audit_wide(Some(&wide_sub_key), vm), + args.access as u32 as isize, + ) + })?; let res = unsafe { host_winreg::delete_key_ex( - args.key.hkey.load(), + args.key.0, &wide_sub_key, - args.access, - args.reserved, + args.access as u32, + args.reserved as u32, ) }; if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pyfunction] - fn EnumKey(key: PyRef, index: i32, vm: &VirtualMachine) -> PyResult { + fn EnumKey(key: HKEYArg, index: i32, vm: &VirtualMachine) -> PyResult { + let hkey = key.0; + vm.audit("winreg.EnumKey", || (hkey as isize, index))?; // The Windows docs claim that the max key name length is 255 // characters, plus a terminating nul character. However, // empirical testing demonstrates that it is possible to @@ -397,9 +542,8 @@ mod winreg { // retrieve such a key name. let mut tmpbuf = [0u16; 257]; let mut len = tmpbuf.len() as u32; - let res = unsafe { - host_winreg::enum_key_ex(key.hkey.load(), index as u32, tmpbuf.as_mut_ptr(), &mut len) - }; + let res = + unsafe { host_winreg::enum_key_ex(hkey, index as u32, tmpbuf.as_mut_ptr(), &mut len) }; if res != 0 { return Err(os_error_from_windows_code(vm, res as i32)); } @@ -408,11 +552,12 @@ mod winreg { } #[pyfunction] - fn EnumValue(hkey: PyRef, index: u32, vm: &VirtualMachine) -> PyResult { + fn EnumValue(key: HKEYArg, index: i32, vm: &VirtualMachine) -> PyResult { + vm.audit("winreg.EnumValue", || (key.0 as isize, index))?; // Query registry for the required buffer sizes. let mut ret_value_size: u32 = 0; let mut ret_data_size: u32 = 0; - let hkey: host_winreg::HKEY = hkey.hkey.load(); + let hkey: host_winreg::HKEY = key.0; let rc = unsafe { host_winreg::query_info_key( hkey, @@ -423,7 +568,7 @@ mod winreg { ) }; if rc != 0 { - return Err(vm.new_os_error(format!("RegQueryInfoKeyW failed with error code {rc}"))); + return Err(os_error_from_windows_code(vm, rc as i32)); } // Include room for null terminators. @@ -444,7 +589,7 @@ mod winreg { let rc = unsafe { host_winreg::enum_value( hkey, - index, + index as u32, ret_value_buf.as_mut_ptr(), &mut current_value_size as *mut u32, &mut reg_type as *mut u32, @@ -464,7 +609,7 @@ mod winreg { continue; } if rc != 0 { - return Err(vm.new_os_error(format!("RegEnumValueW failed with error code {rc}"))); + return Err(os_error_from_windows_code(vm, rc as i32)); } // Convert the registry value name from UTF‑16. @@ -477,7 +622,7 @@ mod winreg { // Slice the data buffer to the actual size returned. let data_slice = &ret_data_buf[..current_data_size as usize]; - let py_data = reg_to_py(vm, data_slice, reg_type)?; + let py_data = reg_to_py(vm, data_slice, reg_type); // Return tuple (value_name, data, type) return Ok(vm @@ -492,18 +637,18 @@ mod winreg { } #[pyfunction] - fn FlushKey(key: PyRef, vm: &VirtualMachine) -> PyResult<()> { - let res = host_winreg::flush_key(key.hkey.load()); + fn FlushKey(key: HKEYArg, vm: &VirtualMachine) -> PyResult<()> { + let res = host_winreg::flush_key(key.0); if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pyfunction] fn LoadKey( - key: PyRef, + key: HKEYArg, sub_key: String, file_name: String, vm: &VirtualMachine, @@ -514,40 +659,60 @@ mod winreg { ) else { return Err(nul_char_error(vm)); }; - let res = unsafe { host_winreg::load_key(key.hkey.load(), &sub_key, &file_name) }; + vm.audit("winreg.LoadKey", || { + ( + key.0 as isize, + audit_wide(Some(&sub_key), vm), + audit_wide(Some(&file_name), vm), + ) + })?; + let res = unsafe { host_winreg::load_key(key.0, &sub_key, &file_name) }; if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[derive(Debug, FromArgs)] struct OpenKeyArgs { #[pyarg(any)] - key: PyRef, + key: HKEYArg, #[pyarg(any)] - sub_key: String, + sub_key: Option>, #[pyarg(any, default)] - reserved: u32, - #[pyarg(any, default = host_winreg::KEY_READ, py_default = "winreg.KEY_READ")] - access: u32, + reserved: i32, + #[pyarg(any, default = host_winreg::KEY_READ as i32, py_default = "winreg.KEY_READ")] + access: i32, } #[pyfunction] #[pyfunction(name = "OpenKeyEx")] fn OpenKey(args: OpenKeyArgs, vm: &VirtualMachine) -> PyResult { - let sub_key = WideCString::from_str(args.sub_key).map_err(|e| e.to_pyexception(vm))?; + let sub_key = args + .sub_key + .as_ref() + .map(|s| WideCString::from_vec(s.as_wtf8().encode_wide().collect::>())) + .transpose() + .map_err(|_| nul_char_error(vm))?; + let key = args.key.0; + vm.audit("winreg.OpenKey", || { + (key as isize, args.sub_key, args.access as u32 as isize) + })?; let mut res: host_winreg::HKEY = core::ptr::null_mut(); - let err = unsafe { - let key = args.key.hkey.load(); - host_winreg::open_key_ex(key, &sub_key, args.reserved, args.access, &mut res) - }; + let err = vm.allow_threads(|| unsafe { + host_winreg::open_key_ex( + key, + sub_key.as_deref(), + args.reserved as u32, + args.access as u32, + &mut res, + ) + }); if err == 0 { - Ok(PyHkey { - #[allow(clippy::arc_with_non_send_sync)] - hkey: AtomicHKEY::new(res), - }) + let result = PyHkey::new(res); + vm.audit("winreg.OpenKey/result", || (res as isize,))?; + Ok(result) } else { Err(os_error_from_windows_code(vm, err as i32)) } @@ -556,8 +721,9 @@ mod winreg { #[pyfunction] fn QueryInfoKey(key: HKEYArg, vm: &VirtualMachine) -> PyResult> { let key = key.0; + vm.audit("winreg.QueryInfoKey", || (key as isize,))?; let info = host_winreg::query_info_key_full(key) - .map_err(|err| vm.new_os_error(format!("error code: {err}")))?; + .map_err(|err| os_error_from_windows_code(vm, err as i32))?; let tup: Vec = vec![ vm.ctx.new_int(info.sub_keys).into(), vm.ctx.new_int(info.values).into(), @@ -567,9 +733,25 @@ mod winreg { } #[pyfunction] - fn QueryValue(key: HKEYArg, sub_key: Option, vm: &VirtualMachine) -> PyResult { + fn QueryValue( + key: HKEYArg, + sub_key: Option, + vm: &VirtualMachine, + ) -> PyResult> { let hkey = key.0; + let sub_key = sub_key + .as_ref() + .map(|s| s.to_wide_cstring().map_err(|_| nul_char_error(vm))) + .transpose()?; + vm.audit("winreg.QueryValue", || { + let sub_key: PyObjectRef = sub_key.as_ref().map_or_else( + || vm.ctx.none(), + |s| vm.ctx.new_str(Wtf8Buf::from_wide(s.as_slice())).into(), + ); + (hkey as isize, sub_key, vm.ctx.none()) + })?; + if hkey == host_winreg::HKEY_PERFORMANCE_DATA { return Err(os_error_from_windows_code( vm, @@ -577,62 +759,88 @@ mod winreg { )); } - let sub_key = sub_key - .map(WideCString::from_str) - .transpose() - .map_err(|e| e.to_pyexception(vm))?; - host_winreg::query_default_value(hkey, sub_key.as_deref()) + host_winreg::query_default_value_wtf8(hkey, sub_key.as_deref()) + .map(|value| vm.ctx.new_str(value)) .map_err(|err| err.to_pyexception(vm)) } #[pyfunction] - fn QueryValueEx(key: HKEYArg, name: String, vm: &VirtualMachine) -> PyResult> { + fn QueryValueEx( + key: HKEYArg, + name: Option>, + vm: &VirtualMachine, + ) -> PyResult> { let hkey = key.0; - let wide_name = WideCString::from_str(name).map_err(|e| e.to_pyexception(vm))?; - let (ret_buf, typ) = host_winreg::query_value_bytes(hkey, &wide_name) + let wide_name = name + .as_ref() + .map(|name| { + name.as_wtf8() + .to_wide_cstring() + .map_err(|_| nul_char_error(vm)) + }) + .transpose()?; + vm.audit("winreg.QueryValue", || { + let name: PyObjectRef = wide_name.as_ref().map_or_else( + || vm.ctx.none(), + |name| vm.ctx.new_str(Wtf8Buf::from_wide(name.as_slice())).into(), + ); + (hkey as isize, vm.ctx.none(), name) + })?; + let (ret_buf, typ) = host_winreg::query_value_bytes(hkey, wide_name.as_deref()) .map_err(|err| os_error_from_windows_code(vm, err as i32))?; - let obj = reg_to_py(vm, &ret_buf, typ)?; + let obj = reg_to_py(vm, &ret_buf, typ); // Return tuple (value, type) Ok(vm.ctx.new_tuple(vec![obj, vm.ctx.new_int(typ).into()])) } #[pyfunction] - fn SaveKey(key: PyRef, file_name: String, vm: &VirtualMachine) -> PyResult<()> { + fn SaveKey(key: HKEYArg, file_name: String, vm: &VirtualMachine) -> PyResult<()> { let file_name = WideCString::from_str(file_name).map_err(|e| e.to_pyexception(vm))?; - let res = unsafe { host_winreg::save_key(key.hkey.load(), &file_name) }; + vm.audit("winreg.SaveKey", || { + (key.0 as isize, audit_wide(Some(&file_name), vm)) + })?; + let res = unsafe { host_winreg::save_key(key.0, &file_name) }; if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pyfunction] fn SetValue( - key: PyRef, + key: HKEYArg, sub_key: String, - typ: u32, + r#type: u32, value: String, vm: &VirtualMachine, ) -> PyResult<()> { - if typ != host_winreg::REG_SZ { + if r#type != host_winreg::REG_SZ { return Err(vm.new_type_error("type must be winreg.REG_SZ")); } - let hkey = key.hkey.load(); - if hkey == host_winreg::HKEY_PERFORMANCE_DATA { - return Err(os_error_from_windows_code( - vm, - host_winreg::ERROR_INVALID_HANDLE as i32, - )); - } + let hkey = key.0; let sub_key = WideCString::from_str(sub_key).map_err(|e| e.to_pyexception(vm))?; // Value can contain interior NULs. let mut wide_value = WideString::with_capacity(value.len() + 1); wide_value.push_str(&value); wide_value.push_str("\0"); - let res = host_winreg::set_default_value(hkey, &sub_key, typ, &wide_value); + vm.audit("winreg.SetValue", || { + ( + hkey as isize, + audit_wide(Some(&sub_key), vm), + r#type as isize, + value, + ) + })?; + if hkey == host_winreg::HKEY_PERFORMANCE_DATA { + return Err(os_error_from_windows_code( + vm, + host_winreg::ERROR_INVALID_HANDLE as i32, + )); + } + let res = host_winreg::set_default_value(hkey, &sub_key, r#type, &wide_value); if res == 0 { Ok(()) @@ -641,7 +849,7 @@ mod winreg { } } - fn reg_to_py(vm: &VirtualMachine, ret_data: &[u8], typ: u32) -> PyResult { + fn reg_to_py(vm: &VirtualMachine, ret_data: &[u8], typ: u32) -> PyObjectRef { match typ { REG_DWORD => { // If there isn’t enough data, return 0. @@ -649,31 +857,30 @@ mod winreg { .first_chunk::<4>() .copied() .map_or(0, u32::from_ne_bytes); - Ok(vm.ctx.new_int(val).into()) + vm.ctx.new_int(val).into() } REG_QWORD => { let val = ret_data .first_chunk::<8>() .copied() .map_or(0, u64::from_ne_bytes); - Ok(vm.ctx.new_int(val).into()) + vm.ctx.new_int(val).into() } REG_SZ | REG_EXPAND_SZ => { - let u16_slice = host_winreg::bytes_as_wide_slice(ret_data); + let u16_slice = host_winreg::registry_wide_units(ret_data); // Only use characters up to the first NUL. let len = u16_slice .iter() .position(|&c| c == 0) .unwrap_or(u16_slice.len()); - let s = String::from_utf16(&u16_slice[..len]) - .map_err(|e| vm.new_value_error(format!("UTF16 error: {e}")))?; - Ok(vm.ctx.new_str(s).into()) + let s = Wtf8Buf::from_wide(&u16_slice[..len]); + vm.ctx.new_str(s).into() } REG_MULTI_SZ => { if ret_data.is_empty() { - Ok(vm.ctx.new_list(vec![]).into()) + vm.ctx.new_list(vec![]).into() } else { - let u16_slice = host_winreg::bytes_as_wide_slice(ret_data); + let u16_slice = host_winreg::registry_wide_units(ret_data); let u16_count = u16_slice.len(); // Remove trailing null if present (like countStrings) @@ -687,41 +894,39 @@ mod winreg { let mut start = 0; for i in 0..len { if u16_slice[i] == 0 { - let s = String::from_utf16(&u16_slice[start..i]) - .map_err(|e| vm.new_value_error(format!("UTF16 error: {e}")))?; + let s = Wtf8Buf::from_wide(&u16_slice[start..i]); strings.push(vm.ctx.new_str(s).into()); start = i + 1; } } // Handle last string if not null-terminated if start < len { - let s = String::from_utf16(&u16_slice[start..len]) - .map_err(|e| vm.new_value_error(format!("UTF16 error: {e}")))?; + let s = Wtf8Buf::from_wide(&u16_slice[start..len]); strings.push(vm.ctx.new_str(s).into()); } - Ok(vm.ctx.new_list(strings).into()) + vm.ctx.new_list(strings).into() } } // For REG_BINARY and any other unknown types, return a bytes object if data exists. _ => { if ret_data.is_empty() { - Ok(vm.ctx.none()) + vm.ctx.none() } else { - Ok(vm.ctx.new_bytes(ret_data.to_vec()).into()) + vm.ctx.new_bytes(ret_data.to_vec()).into() } } } } - fn py2reg(value: PyObjectRef, typ: u32, vm: &VirtualMachine) -> PyResult>> { + fn py2reg(value: &PyObjectRef, typ: u32, vm: &VirtualMachine) -> PyResult>> { + let invalid_data = + || vm.new_value_error("Could not convert the data to the specified type."); match typ { REG_DWORD => { - if vm.is_none(&value) { + if vm.is_none(value) { return Ok(Some(0u32.to_le_bytes().to_vec())); } - let val = value - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("value must be an integer"))?; + let val = value.downcast_ref::().ok_or_else(invalid_data)?; let bigint = val.as_bigint(); // Check for negative value - raise OverflowError if bigint.sign() == Sign::Minus { @@ -733,12 +938,10 @@ mod winreg { Ok(Some(val.to_le_bytes().to_vec())) } REG_QWORD => { - if vm.is_none(&value) { + if vm.is_none(value) { return Ok(Some(0u64.to_le_bytes().to_vec())); } - let val = value - .downcast_ref::() - .ok_or_else(|| vm.new_type_error("value must be an integer"))?; + let val = value.downcast_ref::().ok_or_else(invalid_data)?; let bigint = val.as_bigint(); // Check for negative value - raise OverflowError if bigint.sign() == Sign::Minus { @@ -750,14 +953,14 @@ mod winreg { Ok(Some(val.to_le_bytes().to_vec())) } REG_SZ | REG_EXPAND_SZ => { - if vm.is_none(&value) { + if vm.is_none(value) { // Return empty string as UTF-16 null terminator return Ok(Some(vec![0u8, 0u8])); } // Registry values are allowed to contain interior NULs. let bytes: Vec = value - .downcast::() - .map_err(|_| vm.new_type_error("value must be a string"))? + .downcast_ref::() + .ok_or_else(invalid_data)? .as_wtf8() .encode_wide() .chain([0u16]) @@ -766,74 +969,84 @@ mod winreg { Ok(Some(bytes)) } REG_MULTI_SZ => { - if vm.is_none(&value) { - // Empty list = double null terminator - return Ok(Some(vec![0u8, 0u8, 0u8, 0u8])); + if vm.is_none(value) { + return Ok(Some(vec![0u8, 0u8])); } let list = value - .downcast::() - .map_err(|_| vm.new_type_error("value must be a list of strings"))?; - - let mut encoded = Vec::new(); - for item in list.borrow_vec().iter() { - // The final vector is a list of NUL terminated strings. The list itself is - // NUL terminated as well. Unlike REG_SZ, interior NULs are forbidden because - // it would truncate the list. - // https://learn.microsoft.com/en-us/windows/win32/sysinfo/registry-value-types + .downcast_ref::() + .ok_or_else(invalid_data)?; + + let items = list.borrow_vec(); + for item in items.iter() { + if !item.downcastable::() { + return Err(invalid_data()); + } + } + let mut encoded = Vec::::new(); + for item in items.iter() { let s = item .downcast_ref::() - .ok_or_else(|| vm.new_type_error("list items must be strings"))? - .as_wtf8() - .to_wide_cstring() - .map(WideCString::into_vec_with_nul) - .map_err(|e| e.to_pyexception(vm))?; - encoded.extend(s); + .expect("all list items were checked above"); + for unit in s.as_wtf8().encode_wide().chain([0u16]) { + encoded.extend_from_slice(&unit.to_le_bytes()); + } } - let bytes = encoded - .into_iter() - .flat_map(u16::to_le_bytes) - .chain(0u16.to_le_bytes()) - .collect(); - Ok(Some(bytes)) + encoded.extend_from_slice(&0u16.to_le_bytes()); + Ok(Some(encoded)) } // REG_BINARY and other types _ => { - if vm.is_none(&value) { + if vm.is_none(value) { return Ok(None); } - // Try to get bytes - if let Some(bytes) = value.downcast_ref::() { + // Exact bytes need no buffer acquisition; subclasses and other + // exporters must use their buffer protocol implementation. + if value.class().is(vm.ctx.types.bytes_type) { + let bytes = value + .downcast_ref::() + .expect("the exact bytes type has a bytes payload"); return Ok(Some(bytes.as_bytes().to_vec())); } - Err(vm.new_type_error(format!( - "Objects of type '{}' can not be used as binary registry values", - value.class().name() - ))) + if !value.check_buffer() { + return Err(vm.new_type_error(format!( + "Objects of type '{}' can not be used as binary registry values", + value.class().name() + ))); + } + value.try_bytes_like(vm, |bytes| Some(bytes.to_vec())) } } } #[pyfunction] fn SetValueEx( - key: PyRef, + key: HKEYArg, value_name: Option, _reserved: PyObjectRef, - typ: u32, + r#type: u32, value: PyObjectRef, vm: &VirtualMachine, ) -> PyResult<()> { + let hkey = key.0; let value_name = value_name .map(WideCString::from_str) .transpose() .map_err(|e| e.to_pyexception(vm))?; - let reg_value = py2reg(value, typ, vm)?; + let reg_value = py2reg(&value, r#type, vm)?; + vm.audit("winreg.SetValue", || { + ( + hkey as isize, + audit_wide(value_name.as_deref(), vm), + r#type as isize, + value, + ) + })?; let (ptr, len) = match ®_value { Some(v) => (v.as_ptr(), v.len() as u32), None => (core::ptr::null(), 0), }; - let res = unsafe { - host_winreg::set_value_ex(key.hkey.load(), value_name.as_deref(), typ, ptr, len) - }; + let res = + unsafe { host_winreg::set_value_ex(hkey, value_name.as_deref(), r#type, ptr, len) }; if res != 0 { return Err(os_error_from_windows_code(vm, res as i32)); } @@ -841,41 +1054,50 @@ mod winreg { } #[pyfunction] - fn DisableReflectionKey(key: PyRef, vm: &VirtualMachine) -> PyResult<()> { - let res = host_winreg::disable_reflection_key(key.hkey.load()); + fn DisableReflectionKey(key: HKEYArg, vm: &VirtualMachine) -> PyResult<()> { + vm.audit("winreg.DisableReflectionKey", || (key.0 as isize,))?; + let res = host_winreg::disable_reflection_key(key.0); if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pyfunction] - fn EnableReflectionKey(key: PyRef, vm: &VirtualMachine) -> PyResult<()> { - let res = host_winreg::enable_reflection_key(key.hkey.load()); + fn EnableReflectionKey(key: HKEYArg, vm: &VirtualMachine) -> PyResult<()> { + vm.audit("winreg.EnableReflectionKey", || (key.0 as isize,))?; + let res = host_winreg::enable_reflection_key(key.0); if res == 0 { Ok(()) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pyfunction] - fn QueryReflectionKey(key: PyRef, vm: &VirtualMachine) -> PyResult { + fn QueryReflectionKey(key: HKEYArg, vm: &VirtualMachine) -> PyResult { + vm.audit("winreg.QueryReflectionKey", || (key.0 as isize,))?; let mut result: i32 = 0; - let res = unsafe { host_winreg::query_reflection_key(key.hkey.load(), &mut result) }; + let res = unsafe { host_winreg::query_reflection_key(key.0, &mut result) }; if res == 0 { Ok(result != 0) } else { - Err(vm.new_os_error(format!("error code: {res}"))) + Err(os_error_from_windows_code(vm, res as i32)) } } #[pyfunction] - fn ExpandEnvironmentStrings(i: PyRef, vm: &VirtualMachine) -> PyResult> { - let i = WideCString::from_vec(i.as_wtf8().encode_wide().collect::>()) + fn ExpandEnvironmentStrings( + string: PyRef, + vm: &VirtualMachine, + ) -> PyResult> { + let string = WideCString::from_vec(string.as_wtf8().encode_wide().collect::>()) .map_err(|_| nul_char_error(vm))?; - let expanded = host_winreg::expand_environment_strings_wide(&i) + vm.audit("winreg.ExpandEnvironmentStrings", || { + (audit_wide(Some(&string), vm),) + })?; + let expanded = host_winreg::expand_environment_strings_wide(&string) .map_err(|err| err.to_pyexception(vm))?; Ok(vm.ctx.new_str(Wtf8Buf::from_wide(&expanded))) } diff --git a/crates/vm/src/stdlib/winsound.rs b/crates/vm/src/stdlib/winsound.rs index 6dd3fd38883..92e7962104a 100644 --- a/crates/vm/src/stdlib/winsound.rs +++ b/crates/vm/src/stdlib/winsound.rs @@ -49,6 +49,9 @@ mod winsound { } if flags & SND_MEMORY != 0 { + if flags & SND_ASYNC != 0 { + return Err(vm.new_runtime_error("Cannot play asynchronously from memory")); + } let buffer = PyBuffer::from_object(vm, &sound, BufferFlags::SIMPLE)?; let buf = buffer .as_contiguous() @@ -111,6 +114,9 @@ mod winsound { }; // Check for embedded null characters + if path.contains(&0) { + return Err(vm.new_value_error("embedded null character")); + } let wide_cstr = widestring::WideCString::from_vec(path).map_err(|e| e.to_pyexception(vm))?; play_sound(PlaySoundSource::Name(&wide_cstr), flags).map_err(map_play_err(vm)) @@ -147,4 +153,44 @@ mod winsound { fn MessageBeep(args: MessageBeepArgs, vm: &VirtualMachine) -> PyResult<()> { rustpython_host_env::winsound::message_beep(args.r#type).map_err(|e| e.into_pyexception(vm)) } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn async_memory_rejected_before_buffer_conversion() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + for sound in [ + vm.ctx.new_str("none").into(), + vm.ctx.new_bytes(vec![]).into(), + ] { + let err = PlaySound( + PlaySoundArgs { + sound, + flags: (SND_ASYNC | SND_MEMORY) as i32, + }, + vm, + ) + .unwrap_err(); + assert!(err.class().is(vm.ctx.exceptions.runtime_error)); + } + }); + } + + #[test] + fn embedded_null_rejected_before_playback() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + let err = PlaySound( + PlaySoundArgs { + sound: vm.ctx.new_str("bad\0").into(), + flags: 0, + }, + vm, + ) + .unwrap_err(); + assert!(err.class().is(vm.ctx.exceptions.value_error)); + }); + } + } } diff --git a/crates/vm/src/suggestion.rs b/crates/vm/src/suggestion.rs index c21b295358e..9160ab15884 100644 --- a/crates/vm/src/suggestion.rs +++ b/crates/vm/src/suggestion.rs @@ -16,6 +16,23 @@ const MAX_CANDIDATE_ITEMS: usize = 750; pub fn calculate_suggestions<'a>( dir_iter: impl ExactSizeIterator, name: &PyObject, +) -> Option { + calculate_suggestions_with_length(dir_iter, name, |name| name.len()) +} + +/// Keyword diagnostics use the UTF-8 byte lengths that CPython supplies to +/// its edit-distance calculation, rather than Python string lengths. +pub(crate) fn calculate_keyword_suggestions<'a>( + dir_iter: impl ExactSizeIterator, + name: &PyObject, +) -> Option { + calculate_suggestions_with_length(dir_iter, name, |name| name.as_bytes().len()) +} + +fn calculate_suggestions_with_length<'a>( + dir_iter: impl ExactSizeIterator, + name: &PyObject, + length: impl Fn(&Py) -> usize, ) -> Option { if dir_iter.len() >= MAX_CANDIDATE_ITEMS { return None; @@ -32,7 +49,7 @@ pub fn calculate_suggestions<'a>( } // No more than 1/3 of the characters should need changed let max_distance = usize::min( - (name.len() + item_name.len() + 3) * MOVE_COST / 6, + (length(name) + length(item_name) + 3) * MOVE_COST / 6, suggestion_distance - 1, ); let current_distance = diff --git a/crates/vm/src/types/c_slots.rs b/crates/vm/src/types/c_slots.rs new file mode 100644 index 00000000000..207b015023b --- /dev/null +++ b/crates/vm/src/types/c_slots.rs @@ -0,0 +1,317 @@ +//! Type slots supplied by an extension module. +//! +//! The slot table keeps its Rust signatures. A slot filled from C is held here +//! instead, and the matching Rust slot gets a trampoline that marshals the +//! arguments and calls it. A type that has any of these owns one [`CSlots`], +//! and [`PyTypeSlots::c_slots`] points at it; a subclass inherits the pointer +//! alongside the trampoline, so it reaches the C function without a lookup the +//! way an inherited slot pointer does. +//! +//! Only the slots that can currently be filled from C are listed. Adding one +//! means adding a field here, a trampoline beside the ones below, and a +//! [`CSlotId`] entry. +//! +//! The reverse direction pairs a Rust slot function with an `extern "C"` +//! function instantiated for it in [`StaticCSlots`]. The pair is stored +//! on the type that defines the slot. [`PyType::c_tp_new`] walks the MRO and +//! returns that C function, so a subclass reports the base implementation +//! rather than its own. + +use crate::{ + AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, + builtins::{PyDict, PyDictRef, PyStr, PyTuple, PyType, PyTypeRef}, + function::{FuncArgs, KwArgs}, + types::{CNewFunc, NewFunc}, + vm::{VirtualMachine, thread::with_current_vm}, +}; +use core::marker::PhantomData; +use core::ptr::NonNull; +use crossbeam_utils::atomic::AtomicCell; + +/// The C functions an extension supplied for one type. +/// +/// Each entry is written once, when the type is built, and read through a +/// shared pointer afterwards. +#[derive(Default)] +pub struct CSlots { + /// tp_new. Reached through [`c_new_trampoline`], never called directly. + pub new: AtomicCell>, +} + +impl CSlots { + #[must_use] + pub fn new() -> Self { + Self::default() + } +} + +/// Slot ids from `typeslots.h`. Only the ones that can be installed are listed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[repr(i32)] +pub enum CSlotId { + TpNew = 65, +} + +impl CSlotId { + /// The id an extension passes in a `PyType_Slot`, or `None` when this layer + /// does not handle it. + #[must_use] + pub const fn from_raw(id: i32) -> Option { + match id { + 65 => Some(Self::TpNew), + _ => None, + } + } +} + +/// Split arguments into the `(args, kwds)` pair a keyword-taking C function +/// takes. A call without keywords yields no dict: the convention is to pass a +/// NULL kwds, which is what a function that rejects keywords tests for. +pub fn split_args( + vm: &VirtualMachine, + args: FuncArgs, +) -> PyResult<(PyRef, Option)> { + let arg_tuple = vm.ctx.new_tuple(args.args); + if args.kwargs.is_empty() { + return Ok((arg_tuple, None)); + } + let dict = vm.ctx.new_dict(); + for (k, v) in args.kwargs { + dict.set_item(&*k, v, vm)?; + } + Ok((arg_tuple, Some(dict))) +} + +#[must_use] +pub fn kwargs_ptr(kwargs: Option<&PyDictRef>) -> *mut PyObject { + kwargs.map_or(core::ptr::null_mut(), |d| d.as_object().as_raw().cast_mut()) +} + +/// Turn what a C function returned into a `PyResult`. A NULL return means the +/// exception it raised is pending. +pub fn ret_ptr_to_pyresult(vm: &VirtualMachine, ret_ptr: *mut PyObject) -> PyResult { + let ret_ptr = NonNull::new(ret_ptr).ok_or_else(|| { + vm.take_raised_exception() + .expect("Native function returned NULL, but there was no exception set") + })?; + Ok(unsafe { PyObjectRef::from_raw(ret_ptr) }) +} + +/// Build [`FuncArgs`] from the `(args, kwds)` pair a C caller passes. +/// +/// `kwds == NULL` means there are no keywords. A keyword name that is not a +/// `str` is a `TypeError`. +/// +/// # Safety +/// `args` must point at a live object and `kwds` must be NULL or point at a +/// live object. +pub(crate) unsafe fn func_args_from_ptrs( + vm: &VirtualMachine, + args: *mut PyObject, + kwds: *mut PyObject, +) -> PyResult { + let pos_args = unsafe { &*args } + .try_downcast_ref::(vm)? + .iter() + .cloned() + .collect(); + let kwargs = if kwds.is_null() { + KwArgs::default() + } else { + kwargs_from_dict(vm, unsafe { &*kwds }.try_downcast_ref::(vm)?)? + }; + Ok(FuncArgs { + args: pos_args, + kwargs, + }) +} + +fn kwargs_from_dict(vm: &VirtualMachine, dict: &Py) -> PyResult { + dict.items_vec() + .into_iter() + .map(|(key, value)| { + // Keep WTF-8 so a lone-surrogate key round-trips. + let key = key + .downcast_ref::() + .map(|key| key.as_wtf8().to_owned()) + .ok_or_else(|| vm.new_type_error("keywords must be strings"))?; + Ok((key, value)) + }) + .collect() +} + +/// Hand a `PyResult` back to C. `NULL` means `exc` is now the raised exception +/// a C caller reads with `PyErr_Occurred`. +pub(crate) fn pyresult_to_ret_ptr(vm: &VirtualMachine, result: PyResult) -> *mut PyObject { + match result { + Ok(obj) => obj.into_raw().as_ptr(), + Err(exc) => { + vm.set_raised_exception(Some(exc)); + core::ptr::null_mut() + } + } +} + +/// Drives the C tp_new of the type it is called with. Installed in the `new` +/// slot, which every instantiation path goes through. +/// +/// The C function is read off `cls` rather than captured, so a subclass that +/// inherited this trampoline reaches the same function and passes itself as +/// `subtype`, matching `type->tp_new(subtype, ...)`. +pub fn c_new_trampoline(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + let tp_new = cls.slots.c_slots().and_then(|c| c.new.load()); + let tp_new = tp_new.ok_or_else(|| { + vm.new_system_error(format!("type '{}' has no C tp_new to call", cls.name())) + })?; + let (arg_tuple, kwargs) = split_args(vm, args)?; + let ret_ptr = unsafe { + tp_new( + core::ptr::from_ref(&*cls).cast_mut(), + arg_tuple.as_object().as_raw().cast_mut(), + kwargs_ptr(kwargs.as_ref()), + ) + }; + ret_ptr_to_pyresult(vm, ret_ptr) +} + +/// A Rust `tp_new` that has a single statically instantiated C entry point. +pub trait StaticNew { + fn call(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult; +} + +/// [`StaticNew`] for a payload whose `tp_new` is [`Constructor::slot_new`]. +pub struct ViaConstructor(PhantomData); + +impl StaticNew for ViaConstructor +where + T: crate::types::Constructor, +{ + fn call(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + ::slot_new(cls, args, vm) + } +} + +/// [`StaticNew`] for a Python-level `__new__`, dispatched through [`new_wrapper`]. +pub struct PythonNew; + +impl StaticNew for PythonNew { + fn call(cls: PyTypeRef, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + super::slot::new_wrapper(cls, args, vm) + } +} + +/// C ABI `newfunc` for the Rust implementation `S`. +/// +/// Instantiated once per `S`, so the function pointer identifies that +/// implementation. A caller passes `subtype` through; `S` must run its own +/// body with that class rather than reading `subtype`'s slot again. +/// +/// # Safety +/// `subtype` must point at a live type, `args` at a tuple, and `kwds` must be +/// NULL or a dict. The current thread must have a VM attached. +pub unsafe extern "C" fn c_new_for( + subtype: *mut Py, + args: *mut PyObject, + kwds: *mut PyObject, +) -> *mut PyObject { + with_current_vm(|vm| { + let result = (|| { + let cls = unsafe { &*subtype }.to_owned(); + let func_args = unsafe { func_args_from_ptrs(vm, args, kwds) }?; + S::call(cls, func_args, vm) + })(); + pyresult_to_ret_ptr(vm, result) + }) +} + +/// One Rust slot function and the C function that calls it. +#[derive(Copy, Clone)] +pub struct CSlotPair { + pub rust: R, + pub c: C, +} + +/// The Rust slot functions a type defines, each paired with its C twin. +/// +/// Another slot is another field. Only `new` is filled in today. +pub struct StaticCSlots { + pub new: Option>, +} + +/// `new_wrapper` and the C function that calls it. +/// +/// A heap type whose `new` slot is the Python `__new__` dispatcher resolves +/// here when no defining type recorded that function in its own table. +pub static PYTHON_C_SLOTS: StaticCSlots = StaticCSlots { + new: Some(CSlotPair { + rust: super::slot::new_wrapper as NewFunc, + c: c_new_for:: as CNewFunc, + }), +}; + +/// Associated [`StaticCSlots`] for the payload that defines a Rust `tp_new`. +/// +/// Generated next to `#[pyclass(with(Constructor))]`. The const is what +/// promotes the table to `'static`. +pub trait HasStaticCSlots { + const TABLE: StaticCSlots; +} + +fn c_new_matching(table: Option<&StaticCSlots>, addr: usize) -> Option { + let pair = table?.new.as_ref()?; + (super::slot::fn_addr(pair.rust) == addr).then_some(pair.c) +} + +impl PyType { + /// The C `newfunc` for this type's `tp_new`. + /// + /// A slot installed from C is the function stored in [`CSlots`]. A Rust + /// slot is the C twin recorded for the type in the MRO that defines that + /// same Rust function. A Python-level `__new__` resolves to + /// [`PYTHON_C_SLOTS`]. + #[must_use] + pub fn c_tp_new(&self) -> Option { + let new = self.slots.new.load()?; + if is_c_trampoline(new) { + return self.slots.c_slots().and_then(|c| c.new.load()); + } + let addr = super::slot::fn_addr(new); + let defined = c_new_matching(self.slots.static_c_slots.load(), addr).or_else(|| { + let mro = self.mro.read(); + mro.iter() + .find_map(|cls| c_new_matching(cls.slots.static_c_slots.load(), addr)) + }); + defined.or_else(|| c_new_matching(Some(&PYTHON_C_SLOTS), addr)) + } +} + +/// A pointer to the [`CSlots`] a type reaches, shared with every type that +/// inherited from its owner. +/// +/// The table is owned by the heap type that installed it and lives as long as +/// that type. A type that holds this pointer keeps the owner alive through its +/// `mro`, so the target outlives every reader. +pub(crate) type CSlotsPtr = NonNull; + +/// Wrappers a type's C slots are reached through, one per slot that can be +/// filled from C. Recognizing these is how a slot that is only a trampoline is +/// told apart from one a type implements itself. +pub(crate) fn is_c_trampoline(func: crate::types::NewFunc) -> bool { + crate::types::fn_addr(func) == crate::types::fn_addr(c_new_trampoline as crate::types::NewFunc) +} + +/// The table a type owns. Boxed so the pointer handed to subclasses stays +/// valid for the owner's lifetime. +pub struct OwnedCSlots(Box); + +impl OwnedCSlots { + #[must_use] + pub fn new(slots: CSlots) -> Self { + Self(Box::new(slots)) + } + + #[must_use] + pub(crate) fn as_ptr(&self) -> CSlotsPtr { + CSlotsPtr::from(&*self.0) + } +} diff --git a/crates/vm/src/types/mod.rs b/crates/vm/src/types/mod.rs index ab88f40e3db..28b58dc3c1a 100644 --- a/crates/vm/src/types/mod.rs +++ b/crates/vm/src/types/mod.rs @@ -1,8 +1,13 @@ +pub mod c_slots; mod slot; pub mod slot_defs; mod structseq; mod zoo; +pub use c_slots::{ + CSlotId, CSlotPair, CSlots, HasStaticCSlots, OwnedCSlots, PYTHON_C_SLOTS, PythonNew, + StaticCSlots, StaticNew, ViaConstructor, c_new_for, c_new_trampoline, +}; pub use slot::*; pub use slot_defs::{SLOT_DEFS, SLOT_DEFS_COUNT, SlotAccessor, SlotDef}; pub use structseq::{ diff --git a/crates/vm/src/types/slot.rs b/crates/vm/src/types/slot.rs index 03eb703f55b..a0f23b04c61 100644 --- a/crates/vm/src/types/slot.rs +++ b/crates/vm/src/types/slot.rs @@ -14,6 +14,7 @@ use crate::{ BufferFlags, PyBuffer, PyIterReturn, PyMapping, PyMappingMethods, PyMappingSlots, PyNumber, PyNumberMethods, PyNumberSlots, PySequence, PySequenceMethods, PySequenceSlots, }, + types::c_slots::{CSlots, CSlotsPtr, StaticCSlots, is_c_trampoline}, types::slot_defs::{SlotAccessor, find_slot_defs_by_name}, vm::Context, }; @@ -21,6 +22,7 @@ use core::{any::Any, any::TypeId, borrow::Borrow, cmp::Ordering, ops::Deref}; use crossbeam_utils::atomic::AtomicCell; use num_traits::{Signed, ToPrimitive}; use rustpython_common::wtf8::Wtf8Buf; +use rustpython_common::wtf8::wtf8_concat; /// Predicate used by [`PyTypeSlots::del_needed`]. pub type DelNeededFunc = fn(&PyObject) -> bool; @@ -30,6 +32,8 @@ pub struct TypeDataSlot { // PyObject_GetTypeData type_id: TypeId, data: Box, + traverse: Option)>, + clear: Option)>, } impl TypeDataSlot { @@ -38,9 +42,19 @@ impl TypeDataSlot { Self { type_id: TypeId::of::(), data: Box::new(data), + traverse: None, + clear: None, } } + /// Create extension storage whose Python references participate in GC. + pub fn new_traced(data: T) -> Self { + let mut slot = Self::new(data); + slot.traverse = Some(|data, tracer| data.downcast_ref::().unwrap().traverse(tracer)); + slot.clear = Some(|data, out| data.downcast_mut::().unwrap().clear(out)); + slot + } + /// Get a reference to the data if the type matches. #[must_use] pub fn get(&self) -> Option<&T> { @@ -61,6 +75,20 @@ impl TypeDataSlot { } } +// SAFETY: callbacks are installed together with the matching concrete type. +unsafe impl crate::object::Traverse for TypeDataSlot { + fn traverse(&self, tracer: &mut crate::object::TraverseFn<'_>) { + if let Some(traverse) = self.traverse { + traverse(&*self.data, tracer); + } + } + fn clear(&mut self, out: &mut Vec) { + if let Some(clear) = self.clear { + clear(&mut *self.data, out); + } + } +} + /// Read guard for type data access, using mapped guard for zero-cost deref. pub struct TypeDataRef<'a, T: 'static> { guard: PyMappedRwLockReadGuard<'a, T>, @@ -149,7 +177,12 @@ pub struct PyTypeSlots { // More standard operations (here for binary compatibility) pub hash: AtomicCell>, pub call: AtomicCell>, + /// Retained instance-call implementation, independent of automatic eligibility. pub vectorcall: AtomicCell>, + /// Nullable per-object lookup used by type's constructor dispatch. + pub(crate) vectorcall_resolver: AtomicCell>, + /// Constructor implementation for this type object; never inherited. + pub constructor_vectorcall: AtomicCell>, pub str: AtomicCell>, pub repr: AtomicCell>, pub getattro: AtomicCell>, @@ -190,6 +223,15 @@ pub struct PyTypeSlots { // tp_alloc pub alloc: AtomicCell>, pub new: AtomicCell>, + /// The slots an extension supplied, shared with every type that inherited + /// them. Reached through the trampolines held in the matching Rust slots, + /// never read directly by the interpreter. + pub(crate) c_slots: AtomicCell>, + /// C ABI entry points for the Rust slots this type defines. + /// + /// Written once, on the type that defines the slot. Subclasses do not copy + /// it; the MRO walk in [`PyType::c_tp_new`] finds the definition. + pub static_c_slots: AtomicCell>, // tp_free // tp_is_gc // tp_bases @@ -233,6 +275,35 @@ impl PyTypeSlots { */ Self::default() } + + /// The C slots this type reaches, if any. + #[must_use] + pub fn c_slots(&self) -> Option<&CSlots> { + // SAFETY: the pointer is set only from a table owned by a live heap + // type, and a type that holds it keeps that owner alive through its + // mro, so the target outlives this borrow. + self.c_slots.load().map(|ptr| unsafe { &*ptr.as_ptr() }) + } + + /// What tp_new ultimately dispatches to, for the "is not safe" comparison. + /// + /// Every type whose tp_new came from C shares one trampoline, so comparing + /// `new` alone cannot tell two of them apart. Opening the trampoline down + /// to the C function it reads restores the distinction. + #[must_use] + pub fn new_identity(&self) -> Option { + let new = self.new.load()?; + if is_c_trampoline(new) { + // A type carrying the trampoline without a table is malformed; + // fall back to the trampoline itself rather than claiming no slot. + return Some( + self.c_slots() + .and_then(|c| c.new.load()) + .map_or_else(|| fn_addr(new), fn_addr), + ); + } + Some(fn_addr(new)) + } } impl core::fmt::Debug for PyTypeSlots { @@ -253,12 +324,22 @@ bitflagset::bitflagset! { const IMMUTABLETYPE = 8; const HEAPTYPE = 9; const BASETYPE = 10; + const HAVE_VECTORCALL = 11; + const HAVE_GC = 14; const METHOD_DESCRIPTOR = 17; const IS_ABSTRACT = 20; // Built-in types that match the subject itself in pattern matching // (bool, int, float, str, bytes, bytearray, list, tuple, dict, set, frozenset). // This is not a stable API. const _MATCH_SELF = 22; + const LONG_SUBCLASS = 24; + const LIST_SUBCLASS = 25; + const TUPLE_SUBCLASS = 26; + const BYTES_SUBCLASS = 27; + const UNICODE_SUBCLASS = 28; + const DICT_SUBCLASS = 29; + const BASE_EXC_SUBCLASS = 30; + const TYPE_SUBCLASS = 31; const HAS_DICT = 40; const HAS_WEAKREF = 41; #[cfg(debug_assertions)] @@ -281,6 +362,17 @@ impl PyTypeFlags { ); pub const COLLECTION: Self = Self::from_slice(&[Self::SEQUENCE, Self::MAPPING]); + + pub const SUBCLASS_FLAGS: Self = Self::from_slice(&[ + Self::LONG_SUBCLASS, + Self::LIST_SUBCLASS, + Self::TUPLE_SUBCLASS, + Self::BYTES_SUBCLASS, + Self::UNICODE_SUBCLASS, + Self::DICT_SUBCLASS, + Self::BASE_EXC_SUBCLASS, + Self::TYPE_SUBCLASS, + ]); } impl AtomicPyTypeFlags { @@ -368,6 +460,7 @@ pub(crate) type VectorCallFunc = fn( Option<&[PyObjectRef]>, // kwnames (keyword argument names) &VirtualMachine, ) -> PyResult; +type VectorcallResolver = fn(&PyObject) -> Option; pub(crate) type HashFunc = fn(&PyObject, &VirtualMachine) -> PyResult; // CallFunc = GenericMethod pub(crate) type StringifyFunc = fn(&PyObject, &VirtualMachine) -> PyResult>; @@ -390,6 +483,14 @@ pub(crate) type DescrSetFunc = fn(&PyObject, PyObjectRef, PySetterValue, &VirtualMachine) -> PyResult<()>; pub(crate) type AllocFunc = fn(PyTypeRef, usize, &VirtualMachine) -> PyResult; pub(crate) type NewFunc = fn(PyTypeRef, FuncArgs, &VirtualMachine) -> PyResult; +/// tp_new supplied by an extension module. It is never called through this +/// slot directly: `new` holds the trampoline that marshals the arguments and +/// reads this, so the two are stored and inherited together. +pub type CNewFunc = unsafe extern "C" fn( + subtype: *mut Py, + args: *mut PyObject, + kwds: *mut PyObject, +) -> *mut PyObject; pub(crate) type InitFunc = fn(&PyObject, FuncArgs, &VirtualMachine) -> PyResult<()>; pub(crate) type DelFunc = fn(&PyObject, &VirtualMachine) -> PyResult<()>; @@ -451,6 +552,23 @@ macro_rules! number_binary_op_wrapper { |a, b, vm| vm.call_special_method(a, identifier!(vm, $name), (b.to_owned(),)) }; } +// binary_op1 needs one function address across slot updates and deletions. +fn number_add_wrapper(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { + vm.call_special_method(a, identifier!(vm, __add__), (b.to_owned(),)) +} +fn number_multiply_wrapper(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { + vm.call_special_method(a, identifier!(vm, __mul__), (b.to_owned(),)) +} +fn number_right_multiply_wrapper(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { + vm.call_special_method(b, identifier!(vm, __rmul__), (a.to_owned(),)) +} +fn number_inplace_add_wrapper(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { + vm.call_special_method(a, identifier!(vm, __iadd__), (b.to_owned(),)) +} +fn number_inplace_multiply_wrapper(a: &PyObject, b: &PyObject, vm: &VirtualMachine) -> PyResult { + vm.call_special_method(a, identifier!(vm, __imul__), (b.to_owned(),)) +} + macro_rules! number_binary_right_op_wrapper { ($name:ident) => { |a, b, vm| vm.call_special_method(b, identifier!(vm, $name), (a.to_owned(),)) @@ -462,7 +580,10 @@ macro_rules! number_ternary_op_wrapper { if vm.is_none(c) { vm.call_special_method(a, identifier!(vm, $name), (b.to_owned(),)) } else { - vm.call_special_method(a, identifier!(vm, $name), (b.to_owned(), c.to_owned())) + // The modulus's slot is called with the original operands, + // so the first one may not define the method at all. + vm.call_special_method_opt(a, identifier!(vm, $name), (b.to_owned(), c.to_owned())) + .map(|ret| ret.unwrap_or_else(|| vm.ctx.not_implemented())) } } }; @@ -550,12 +671,14 @@ fn sequence_contains_wrapper( fn repr_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult> { let ret = vm.call_special_method(zelf, identifier!(vm, __repr__), ())?; - ret.downcast::().map_err(|obj| { - vm.new_type_error(format!( - "__repr__ returned non-string (type {})", - obj.class() - )) - }) + match ret.downcast::() { + Ok(value) => Ok(value), + Err(obj) => Err(vm.new_type_error(wtf8_concat!( + zelf.class().fully_qualified_name(vm)?, + ".__repr__() must return a str, not ", + obj.class().fully_qualified_name(vm)? + ))), + } } fn str_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult> { @@ -575,7 +698,7 @@ fn hash_wrapper(zelf: &PyObject, vm: &VirtualMachine) -> PyResult { .ok_or_else(|| vm.new_type_error("__hash__ method should return an integer"))?; let big_int = py_int.as_bigint(); let hash = big_int - .to_i64() + .to_isize() .map_or_else(|| hash_bigint(big_int), fix_sentinel); Ok(hash) } @@ -588,7 +711,7 @@ pub fn hash_not_implemented(zelf: &PyObject, vm: &VirtualMachine) -> PyResult PyResult { // `__call__` can name the object being called, and dispatching it pushes no // Python frame, so nothing else counts the nesting. - vm.with_recursion("while calling a Python object", || { + vm.with_recursion(" while calling a Python object", || { vm.call_special_method(zelf, identifier!(vm, __call__), args) }) } @@ -773,13 +896,21 @@ fn descr_get_wrapper( cls: Option<&PyObject>, vm: &VirtualMachine, ) -> PyResult { - // A descriptor whose `__get__` is the descriptor itself resolves it by - // fetching `__get__` again, and none of that pushes a Python frame. - vm.with_recursion("while calling a Python object", || { - vm.call_special_method( - zelf, - identifier!(vm, __get__), - (obj.map(PyObject::to_owned), cls.map(PyObject::to_owned)), + // slot_tp_descr_get calls the raw type attribute with all three arguments. + // Binding it first would omit self for builtin functions and incorrectly + // invoke the descriptor protocol of static/class/custom __get__ objects. + // Keep both the callable and self owned across user code that deletes them. + vm.with_recursion(" while calling a Python object", || { + let Some(get) = zelf.class().get_attr(identifier!(vm, __get__)) else { + return Ok(zelf.to_owned()); + }; + get.call( + ( + zelf.to_owned(), + obj.map(PyObject::to_owned), + cls.map(PyObject::to_owned), + ), + vm, ) }) } @@ -887,7 +1018,7 @@ impl PyType { name: &'static PyStrInterned, ctx: &Context, ) { - use crate::builtins::descriptor::SlotFunc; + use crate::builtins::descriptor::{PyWrapper, SlotFunc}; // Helper macro for main slots macro_rules! update_main_slot { @@ -986,6 +1117,19 @@ impl PyType { }}; } + macro_rules! native_sequence_wrapper { + ($name:ident, $slot:pat) => { + self.get_attr(identifier!(ctx, $name)).is_some_and(|attr| { + attr.class().is(ctx.types.wrapper_descriptor_type) + && attr.downcast_ref::().is_some_and(|descr| { + descr.name.as_str() == stringify!($name) + && self.mro.read().iter().any(|cls| cls.is(descr.typ)) + && matches!(descr.wrapped, $slot) + }) + }) + }; + } + match accessor { // === Main slots === SlotAccessor::TpRepr => update_main_slot!(repr, repr_wrapper, Repr), @@ -1027,21 +1171,29 @@ impl PyType { } SlotAccessor::TpCall => { update_main_slot!(call, call_wrapper, Call); - // When __call__ is overridden in Python, clear vectorcall - // so the slow path through call_wrapper is used. - if ADD { - self.slots.vectorcall.store(None); + // Generic __call__ disables automatic dispatch, not retained raw support. + // A missing call slot alone does not revoke the CPython eligibility flag. + if self.slots.call.load().map(fn_addr) + == Some(fn_addr(call_wrapper as GenericMethod)) + { + self.slots.flags.remove(PyTypeFlags::HAVE_VECTORCALL); } } SlotAccessor::TpIter => update_main_slot!(iter, iter_wrapper, Iter), SlotAccessor::TpIternext => update_main_slot!(iternext, iternext_wrapper, IterNext), - SlotAccessor::TpInit => { - update_main_slot!(init, init_wrapper, Init); - if ADD { - self.slots.vectorcall.store(None); - } - } + SlotAccessor::TpInit => update_main_slot!(init, init_wrapper, Init), SlotAccessor::TpNew => { + // A type that owns a C tp_new keeps its trampoline: its + // `__new__` entry is the wrapper over that slot, not a + // definition replacing it. A type that merely inherited the + // slot is not exempt, since `__new__` can be defined over it. + let own = self.slots.c_slots.load(); + let owns_table = own.is_some() + && own != self.base.deref().and_then(|base| base.slots.c_slots.load()); + if owns_table { + return; + } + // __new__ is a staticmethod, not a PyWrapper descriptor, so // lookup_slot_in_mro cannot classify it. Resolve __new__ // through the MRO dicts instead: a Python-level definition @@ -1062,53 +1214,57 @@ impl PyType { }) }; if needs_wrapper { + // A Python-level __new__ replaces the C slot outright, so + // the table goes with the trampoline it was reached by. self.slots.new.store(Some(new_wrapper)); + self.slots.c_slots.store(None); self.slots.vectorcall.store(None); } else { - let inherited = self.base.deref().and_then(|base| base.slots.new.load()); - self.slots.new.store(inherited); + let base = self.base.deref(); + self.slots + .new + .store(base.and_then(|base| base.slots.new.load())); + self.slots + .c_slots + .store(base.and_then(|base| base.slots.c_slots.load())); } } SlotAccessor::TpDel => update_main_slot!(del, del_wrapper, Del), SlotAccessor::TpGetattro => { - // __getattribute__ and __getattr__ both map to TpGetattro. - // If __getattr__ is defined anywhere in MRO, we must use the wrapper - // because the native slot won't call __getattr__. - let __getattr__ = identifier!(ctx, __getattr__); - let has_getattr = { - // mro[0] is self, so skip it - self.attributes.contains(__getattr__) - || self - .mro - .read() - .iter() - .skip(1) - .any(|cls| cls.attributes.contains(__getattr__)) + // __getattribute__ and __getattr__ share the same slot, so both + // names must be resolved together: a Python-level definition of + // either one forces the dispatching wrapper, and the native + // slot is only usable when every resolved name agrees on it. + // __getattr__ has no native wrapper, so finding it anywhere in + // the MRO always selects the wrapper. + // This resolution reads the current attribute dicts, so it + // applies the same whether a name was just added or removed. + let extract = |sf: &SlotFunc| match sf { + SlotFunc::GetAttro(f) => Some(*f), + _ => None, }; - - if has_getattr { - // Must use wrapper to handle __getattr__ - self.slots.getattro.store(Some(getattro_wrapper)); - } else if ADD { - match self.lookup_slot_in_mro(name, ctx, |sf| { - if let SlotFunc::GetAttro(f) = sf { - Some(*f) + let getattribute = + self.lookup_slot_in_mro(identifier!(ctx, __getattribute__), ctx, extract); + let getattr = self.lookup_slot_in_mro(identifier!(ctx, __getattr__), ctx, extract); + use SlotLookupResult::{NativeSlot, NotFound, PythonMethod}; + match (getattribute, getattr) { + (PythonMethod, _) | (_, PythonMethod) => { + self.slots.getattro.store(Some(getattro_wrapper)); + } + (NativeSlot(getattribute), NativeSlot(getattr)) => { + let func = if fn_addr(getattribute) == fn_addr(getattr) { + getattribute } else { - None - } - }) { - SlotLookupResult::NativeSlot(func) => { - self.slots.getattro.store(Some(func)); - } - SlotLookupResult::PythonMethod => { - self.slots.getattro.store(Some(getattro_wrapper)); - } - SlotLookupResult::NotFound => { - accessor.inherit_from_mro(self); - } + getattro_wrapper + }; + self.slots.getattro.store(Some(func)); + } + (NativeSlot(func), NotFound) | (NotFound, NativeSlot(func)) => { + self.slots.getattro.store(Some(func)); + } + (NotFound, NotFound) => { + accessor.inherit_from_mro(self); } - } else { - accessor.inherit_from_mro(self); } } SlotAccessor::TpSetattro => { @@ -1249,23 +1405,51 @@ impl PyType { number_binary_right_op_wrapper!(__radd__), NumBinary ) + } + let native_concat = self + .get_attr(identifier!(ctx, __add__)) + .is_some_and(|attr| { + attr.class().is(ctx.types.wrapper_descriptor_type) + && attr.downcast_ref::().is_some_and(|descr| { + descr.name.as_str() == "__add__" + && self.mro.read().iter().any(|cls| cls.is(descr.typ)) + && matches!(descr.wrapped, SlotFunc::SeqConcat(_)) + }) + }); + if native_concat { + // Native sequence addition stays in sq_concat unless nb_add + // already participates or __radd__ needs its shared dispatcher. + // Like CPython's resolve_slotdups, preserve an existing numeric + // wrapper when an override is replaced or deleted. + let needs_numeric = self.slots.as_number.add.load().is_some() + || self.slots.as_sequence.concat.load().is_none() + || self.get_attr(identifier!(ctx, __radd__)).is_some(); + self.slots + .as_number + .add + .store(needs_numeric.then_some(number_add_wrapper)); + } else if name.as_str() == "__add__" { + update_sub_slot!(as_number, add, number_add_wrapper, NumBinary) + } + } + SlotAccessor::NbInplaceAdd => { + if native_sequence_wrapper!(__iadd__, SlotFunc::SeqConcat(_)) { + // Unlike repeat wrappers, both inplace-add slots accept an + // object argument. Keep the numeric dispatcher ahead of + // reflected addition, including after deleting an override. + self.slots + .as_number + .inplace_add + .store(Some(number_inplace_add_wrapper)); } else { update_sub_slot!( as_number, - add, - number_binary_op_wrapper!(__add__), + inplace_add, + number_inplace_add_wrapper, NumBinary ) } } - SlotAccessor::NbInplaceAdd => { - update_sub_slot!( - as_number, - inplace_add, - number_binary_op_wrapper!(__iadd__), - NumBinary - ) - } SlotAccessor::NbSubtract => { if name.as_str() == "__rsub__" { update_sub_slot!( @@ -1292,30 +1476,55 @@ impl PyType { ) } SlotAccessor::NbMultiply => { - if name.as_str() == "__rmul__" { + let native_left = native_sequence_wrapper!(__mul__, SlotFunc::SeqRepeat(_)); + let native_right = native_sequence_wrapper!(__rmul__, SlotFunc::SeqRepeat(_)); + // CPython has a single numeric multiply slot for both names. + // Keep native repeat in sq_repeat unless either name needs the + // numeric dispatcher, or that dispatcher was already installed. + let needs_numeric = self.slots.as_number.multiply.load().is_some() + || self.slots.as_number.right_multiply.load().is_some() + || self.slots.as_sequence.repeat.load().is_none() + || (!native_left && self.get_attr(identifier!(ctx, __mul__)).is_some()) + || (!native_right && self.get_attr(identifier!(ctx, __rmul__)).is_some()); + if native_right { + self.slots + .as_number + .right_multiply + .store(needs_numeric.then_some(number_right_multiply_wrapper)); + } else if name.as_str() == "__rmul__" { update_sub_slot!( as_number, right_multiply, - number_binary_right_op_wrapper!(__rmul__), + number_right_multiply_wrapper, NumBinary ) + } + if native_left { + self.slots + .as_number + .multiply + .store(needs_numeric.then_some(number_multiply_wrapper)); + } else if name.as_str() == "__mul__" { + update_sub_slot!(as_number, multiply, number_multiply_wrapper, NumBinary) + } + } + SlotAccessor::NbInplaceMultiply => { + if native_sequence_wrapper!(__imul__, SlotFunc::SeqRepeat(_)) { + let needs_numeric = self.slots.as_number.inplace_multiply.load().is_some() + || self.slots.as_sequence.inplace_repeat.load().is_none(); + self.slots + .as_number + .inplace_multiply + .store(needs_numeric.then_some(number_inplace_multiply_wrapper)); } else { update_sub_slot!( as_number, - multiply, - number_binary_op_wrapper!(__mul__), + inplace_multiply, + number_inplace_multiply_wrapper, NumBinary ) } } - SlotAccessor::NbInplaceMultiply => { - update_sub_slot!( - as_number, - inplace_multiply, - number_binary_op_wrapper!(__imul__), - NumBinary - ) - } SlotAccessor::NbRemainder => { if name.as_str() == "__rmod__" { update_sub_slot!( @@ -1655,10 +1864,20 @@ impl PyType { }; self.slots.as_sequence.concat.store(concat); } - SlotAccessor::SqInplaceConcat if !ADD => { - // Sequence concat uses sq_concat slot - no generic wrapper needed - // (handled by number protocol fallback) - accessor.inherit_from_mro(self); + SlotAccessor::SqInplaceConcat => { + // Python __iadd__ overrides use nb_inplace_add, not the + // inherited sq_inplace_concat. + let inplace_concat = match self.lookup_slot_in_mro(name, ctx, |sf| { + if let SlotFunc::SeqConcat(f) = sf { + Some(*f) + } else { + None + } + }) { + SlotLookupResult::NativeSlot(func) => Some(func), + SlotLookupResult::PythonMethod | SlotLookupResult::NotFound => None, + }; + self.slots.as_sequence.inplace_concat.store(inplace_concat); } SlotAccessor::SqRepeat | SlotAccessor::SqInplaceRepeat => { // Python `__mul__`/`__rmul__`/`__imul__` overrides use the number slots and @@ -1944,7 +2163,14 @@ pub trait Constructor: PyPayload + core::fmt::Debug { }; let args: Self::Args = args.bind_for(vm, Callee::of::(vm))?; let payload = Self::py_new(&cls, args, vm)?; - payload.into_ref_with_type(vm, cls).map(Into::into) + // Exception reduction distinguishes an absent dictionary from an + // allocated empty one, including exceptions with specialized payloads. + let instance = if cls.slots.flags.has_feature(PyTypeFlags::BASE_EXC_SUBCLASS) { + payload.into_ref_with_type_lazy_dict(vm, cls) + } else { + payload.into_ref_with_type(vm, cls) + }; + instance.map(Into::into) } /// Creates the payload for this type. In most cases, just implement this method @@ -2001,26 +2227,14 @@ pub trait Initializer: PyPayload { #[inline] #[pyslot] fn slot_init(zelf: &PyObject, args: FuncArgs, vm: &VirtualMachine) -> PyResult<()> { - #[cfg(debug_assertions)] - let class_name_for_debug = zelf.class().name().to_string(); - let zelf = match zelf.try_to_ref::(vm) { Ok(zelf) => zelf, Err(err) => { - #[cfg(debug_assertions)] - { - if let Ok(msg) = err.as_object().repr(vm) { - let double_appearance = msg - .to_string_lossy() - .matches(&class_name_for_debug as &str) - .count() - == 2; - assert!( - !double_appearance, - "This type `{class_name_for_debug}` doesn't seem to support `init`. Override `slot_init` instead: {msg}" - ) - } - } + debug_assert!( + !zelf.fast_isinstance(Self::class(&vm.ctx)), + "This type `{}` doesn't seem to support `init`. Override `slot_init` instead", + zelf.class().name() + ); return Err(err); } }; diff --git a/crates/vm/src/types/slot_defs.rs b/crates/vm/src/types/slot_defs.rs index 14b41af0aa0..3e1013eb2d0 100644 --- a/crates/vm/src/types/slot_defs.rs +++ b/crates/vm/src/types/slot_defs.rs @@ -2,7 +2,7 @@ //! //! This module provides a centralized array of all slot definitions, -use super::{PyComparisonOp, PyTypeSlots, fn_addr}; +use super::{PyComparisonOp, PyTypeFlags, PyTypeSlots, fn_addr}; use crate::builtins::descriptor::SlotFunc; use num_enum::TryFromPrimitive; @@ -465,23 +465,7 @@ impl SlotAccessor { Self::TpHash => inherit_main!(hash), Self::TpRepr => inherit_main!(repr), Self::TpStr => inherit_main!(str), - Self::TpCall => { - inherit_main!(call); - // CPython does not inherit tp_vectorcall to heap types at all; it only - // inherits tp_vectorcall_offset (the per-instance callable fast path). - // RustPython approximates this by inheriting vectorcall only from types - // with a call slot (instance-call vectorcall), not from types that use - // vectorcall as a constructor fast path (call=None). - // See vectorcall_type() in type.rs for the dual-use design rationale. - let inherited_vc = mro.iter().find_map(|cls| { - if cls.payload().slots.call.load().is_some() { - cls.payload().slots.vectorcall.load() - } else { - None - } - }); - typ.slots.vectorcall.store(inherited_vc); - } + Self::TpCall => inherit_main!(call), Self::TpIter => inherit_main!(iter), Self::TpIternext => inherit_main!(iternext), Self::TpInit => inherit_main!(init), @@ -617,14 +601,21 @@ impl SlotAccessor { Self::TpRepr => copy_main!(repr), Self::TpStr => copy_main!(str), Self::TpCall => { - copy_main!(call); - // See inherit_from_mro TpCall for rationale. + // Initial/idempotent role inheritance, not concurrent role replacement. if typ.slots.vectorcall.load().is_none() - && base.slots.call.load().is_some() - && let Some(base_val) = base.slots.vectorcall.load() + && typ.slots.vectorcall_resolver.load().is_none() + { + typ.slots.vectorcall.store(base.slots.vectorcall.load()); + typ.slots + .vectorcall_resolver + .store(base.slots.vectorcall_resolver.load()); + } + if typ.slots.call.load().is_none() + && base.slots.flags.has_feature(PyTypeFlags::HAVE_VECTORCALL) { - typ.slots.vectorcall.store(Some(base_val)); + typ.slots.flags.insert(PyTypeFlags::HAVE_VECTORCALL); } + copy_main!(call); } Self::TpIter => copy_main!(iter), Self::TpIternext => copy_main!(iternext), @@ -646,14 +637,27 @@ impl SlotAccessor { Self::TpDel => copy_main!(del), Self::TpGetattro => copy_main!(getattro), Self::TpSetattro => copy_main!(setattro), - Self::TpDescrGet => copy_main!(descr_get), + Self::TpDescrGet => { + copy_main!(descr_get); + if typ.slots.flags.has_feature(PyTypeFlags::IMMUTABLETYPE) + && base.slots.flags.has_feature(PyTypeFlags::METHOD_DESCRIPTOR) + && let Some(descr_get) = typ.slots.descr_get.load() + && base.slots.descr_get.load().map(fn_addr) == Some(fn_addr(descr_get)) + { + typ.slots.flags.insert(PyTypeFlags::METHOD_DESCRIPTOR); + } + } Self::TpDescrSet => copy_main!(descr_set), Self::TpRichcompare => copy_main!(richcompare), // Number slots Self::NbAdd => copy_number!(add), Self::NbSubtract => copy_number!(subtract), - Self::NbMultiply => copy_number!(multiply), + Self::NbMultiply => { + // CPython inherits one nb_multiply slot for both directions. + copy_number!(multiply); + copy_number!(right_multiply); + } Self::NbRemainder => copy_number!(remainder), Self::NbDivmod => copy_number!(divmod), Self::NbPower => copy_number!(power), diff --git a/crates/vm/src/types/structseq.rs b/crates/vm/src/types/structseq.rs index 09822495075..0ab657e099d 100644 --- a/crates/vm/src/types/structseq.rs +++ b/crates/vm/src/types/structseq.rs @@ -11,12 +11,12 @@ use crate::{ }, iter::PyExactSizeIterator, protocol::{PyMappingMethods, PySequenceMethods}, - sliceable::{SequenceIndex, SliceableSequenceOp}, + sliceable::{NameTuple, SequenceIndex, SliceableSequenceOp}, types::PyComparisonOp, vm::Context, }; -const DEFAULT_STRUCTSEQ_REDUCE: PyMethodDef = PyMethodDef::new_const( +const DEFAULT_STRUCTSEQ_REDUCE: PyMethodDef = PyMethodDef::new_method_const( "__reduce__", |zelf: PyRef, vm: &VirtualMachine| -> PyTupleRef { vm.new_tuple(( @@ -217,7 +217,7 @@ static STRUCT_SEQUENCE_AS_MAPPING: LazyLock = let tuple = mapping.obj.downcast_ref::().unwrap(); let visible_elements = &tuple.as_slice()[..n_seq]; - match SequenceIndex::try_from_borrowed_object(vm, needle, "tuple")? { + match SequenceIndex::try_from_borrowed_object::(vm, needle)? { SequenceIndex::Int(i) => visible_elements.getitem_by_index(vm, i), SequenceIndex::Slice(slice) => visible_elements .getitem_by_slice(vm, slice) @@ -372,11 +372,11 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { } #[pymethod] - fn __getitem__(zelf: PyRef, needle: PyObjectRef, vm: &VirtualMachine) -> PyResult { + fn __getitem__(zelf: PyRef, key: PyObjectRef, vm: &VirtualMachine) -> PyResult { let n_seq = get_visible_len(zelf.as_ref(), vm)?; let visible_elements = &zelf.as_slice()[..n_seq]; - match SequenceIndex::try_from_borrowed_object(vm, &needle, "tuple")? { + match SequenceIndex::try_from_borrowed_object::(vm, &key)? { SequenceIndex::Int(i) => visible_elements.getitem_by_index(vm, i), SequenceIndex::Slice(slice) => visible_elements .getitem_by_slice(vm, slice) @@ -460,15 +460,12 @@ pub trait PyStructSequence: StaticType + PyClassImpl + Sized + 'static { .richcompare .store(Some(struct_sequence_richcompare)); - // Default __reduce__: only set if not already overridden by the impl's extend_class. - // This allows struct sequences like sched_param to provide a custom __reduce__ - // (equivalent to METH_COEXIST in structseq.c). - if !class.attributes.contains(ctx.intern_str("__reduce__")) { - class.set_attr( - ctx.intern_str("__reduce__"), - DEFAULT_STRUCTSEQ_REDUCE.to_proper_method(class, ctx), - ); - } + // An impl's own __reduce__ method replaces this default, because method + // definitions are installed after class extension. + class.set_attr( + ctx.intern_str("__reduce__"), + DEFAULT_STRUCTSEQ_REDUCE.to_proper_method(class, ctx), + ); } } @@ -530,5 +527,4 @@ fn struct_sequence_richcompare( .iter() .map(|o| &**o) .richcompare(other_visible.iter().map(|o| &**o), op, vm) - .map(|v| Either::B(PyComparisonValue::Implemented(v))) } diff --git a/crates/vm/src/types/zoo.rs b/crates/vm/src/types/zoo.rs index 0d3c5d0fb92..6d2d630fdf5 100644 --- a/crates/vm/src/types/zoo.rs +++ b/crates/vm/src/types/zoo.rs @@ -4,8 +4,8 @@ use crate::{ asyncgenerator, bool_, builtin_func, bytearray, bytes, capsule, classmethod, code, complex, coroutine, descriptor, dict, enumerate, filter, float, frame, frame_locals_proxy, function, generator, genericalias, getset, int, interpolation, iter, list, map, mappingproxy, memory, - module, namespace, object, property, pystr, range, set, singletons, slice, staticmethod, - super_, template, traceback, tuple, + module, namespace, object, property, pystr, range, sentinel, set, singletons, slice, + staticmethod, super_, template, traceback, tuple, type_::{self, PyType}, union_, weakproxy, weakref, zip, }, @@ -40,16 +40,19 @@ pub struct TypeZoo { pub float_type: &'static Py, pub frame_type: &'static Py, pub frame_locals_proxy_type: &'static Py, + pub frozendict_type: &'static Py, pub frozenset_type: &'static Py, pub generator_type: &'static Py, pub int_type: &'static Py, pub iter_type: &'static Py, pub reverse_iter_type: &'static Py, pub complex_type: &'static Py, + pub lazy_import_type: &'static Py, pub list_type: &'static Py, pub list_iterator_type: &'static Py, pub list_reverseiterator_type: &'static Py, pub str_iterator_type: &'static Py, + pub str_ascii_iterator_type: &'static Py, pub dict_keyiterator_type: &'static Py, pub dict_reversekeyiterator_type: &'static Py, pub dict_valueiterator_type: &'static Py, @@ -64,6 +67,7 @@ pub struct TypeZoo { pub memoryviewiterator_type: &'static Py, pub tuple_type: &'static Py, pub tuple_iterator_type: &'static Py, + pub sentinel_type: &'static Py, pub set_type: &'static Py, pub set_iterator_type: &'static Py, pub staticmethod_type: &'static Py, @@ -120,7 +124,7 @@ impl TypeZoo { let weakref_type = weakref::PyWeak::init_manually(hierarchy.weakref_type); let int_type = int::PyInt::init_builtin_type(); - // builtin_function_or_method and builtin_method share the same type (CPython behavior) + // `builtin_method` is a subclass and is initialized once this base exists. let builtin_function_or_method_type = builtin_func::PyNativeFunction::init_builtin_type(); let types = Self { @@ -138,13 +142,16 @@ impl TypeZoo { dict_type: dict::PyDict::init_builtin_type(), enumerate_type: enumerate::PyEnumerate::init_builtin_type(), float_type: float::PyFloat::init_builtin_type(), + frozendict_type: dict::PyFrozenDict::init_builtin_type(), frozenset_type: set::PyFrozenSet::init_builtin_type(), filter_type: filter::PyFilter::init_builtin_type(), + lazy_import_type: crate::lazy_import::PyLazyImport::init_builtin_type(), list_type: list::PyList::init_builtin_type(), map_type: map::PyMap::init_builtin_type(), memoryview_type: memory::PyMemoryView::init_builtin_type(), property_type: property::PyProperty::init_builtin_type(), range_type: range::PyRange::init_builtin_type(), + sentinel_type: sentinel::PySentinel::init_builtin_type(), set_type: set::PySet::init_builtin_type(), slice_type: slice::PySlice::init_builtin_type(), staticmethod_type: staticmethod::PyStaticMethod::init_builtin_type(), @@ -162,7 +169,7 @@ impl TypeZoo { anext_awaitable: asyncgenerator::PyAnextAwaitable::init_builtin_type(), bound_method_type: function::PyBoundMethod::init_builtin_type(), builtin_function_or_method_type, - builtin_method_type: builtin_function_or_method_type, + builtin_method_type: builtin_func::PyNativeMethod::init_builtin_type(), bytearray_iterator_type: bytearray::PyByteArrayIterator::init_builtin_type(), bytes_iterator_type: bytes::PyBytesIterator::init_builtin_type(), callable_iterator: iter::PyCallableIterator::init_builtin_type(), @@ -198,6 +205,7 @@ impl TypeZoo { long_range_iterator_type: range::PyLongRangeIterator::init_builtin_type(), set_iterator_type: set::PySetIterator::init_builtin_type(), str_iterator_type: pystr::PyStrIterator::init_builtin_type(), + str_ascii_iterator_type: pystr::PyStrAsciiIterator::init_builtin_type(), traceback_type: traceback::PyTraceback::init_builtin_type(), tuple_iterator_type: tuple::PyTupleIterator::init_builtin_type(), weakproxy_type: weakproxy::PyWeakProxy::init_builtin_type(), @@ -233,6 +241,7 @@ impl TypeZoo { set::init(context); tuple::init(context); dict::init(context); + crate::lazy_import::init_type(context); builtin_func::init(context); function::init(context); staticmethod::init(context); @@ -265,6 +274,7 @@ impl TypeZoo { weakref::init(context); weakproxy::init(context); singletons::init(context); + sentinel::init(context); module::init(context); namespace::init(context); mappingproxy::init(context); diff --git a/crates/vm/src/unicode_names.rs b/crates/vm/src/unicode_names.rs new file mode 100644 index 00000000000..f5bfae72929 --- /dev/null +++ b/crates/vm/src/unicode_names.rs @@ -0,0 +1,129 @@ +//! Lazy loading of the Unicode name database used by the codecs. +// spell-checker:ignore ucnhash + +use core::sync::atomic::Ordering; + +use crate::{PyRef, PyResult, VirtualMachine, builtins::PyCapsule}; + +const CAPSULE_NAME: &core::ffi::CStr = c"unicodedata._ucnhash_CAPI"; + +// The capsule pointer identifies the bundled name database and is never +// dereferenced. +static NAME_DATABASE: u8 = 0; + +impl VirtualMachine { + /// Create the native module's private Unicode-name capsule. + pub fn new_unicode_name_capsule(&self) -> PyRef { + self.ctx.new_capsule( + core::ptr::from_ref(&NAME_DATABASE).cast_mut().cast(), + Some(CAPSULE_NAME), + None, + ) + } + + pub(crate) fn load_unicode_names(&self) -> PyResult<()> { + if self.state.unicode_names_loaded.load(Ordering::Acquire) { + return Ok(()); + } + // Do not hold an initialization lock across import: import can reenter + // the interpreter. Failed imports must not poison the successful cache. + let module = self.import("unicodedata", 0).map_err(|_| { + self.new_exception_msg( + self.ctx.exceptions.import_error.to_owned(), + "PyCapsule_Import could not import module \"unicodedata\"".into(), + ) + })?; + let object = module.get_attr("_ucnhash_CAPI", self)?; + let valid = object + .downcast_ref_if_exact::(self) + .is_some_and(|capsule| { + capsule.name() == Some(CAPSULE_NAME) + && core::ptr::eq( + capsule.pointer(), + core::ptr::from_ref(&NAME_DATABASE).cast_mut().cast(), + ) + }); + if !valid { + return Err(self.new_attribute_error( + "PyCapsule_Import \"unicodedata._ucnhash_CAPI\" is not valid", + )); + } + self.state + .unicode_names_loaded + .store(true, Ordering::Release); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::Interpreter; + + #[test] + fn missing_unicodedata_is_an_error() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let modules = vm.sys_module.get_attr("modules", vm).unwrap(); + modules.set_item("unicodedata", vm.ctx.none(), vm).unwrap(); + assert!(vm.load_unicode_names().is_err()); + }); + } + + #[test] + fn foreign_pointer_is_rejected_and_not_cached() { + static FOREIGN: u8 = 0; + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let modules = vm.sys_module.get_attr("modules", vm).unwrap(); + let dict = vm.ctx.new_dict(); + let capsule = vm.ctx.new_capsule( + core::ptr::from_ref(&FOREIGN).cast_mut().cast(), + Some(CAPSULE_NAME), + None, + ); + dict.set_item("_ucnhash_CAPI", capsule.into(), vm).unwrap(); + let module = vm.new_module("unicodedata", dict, None); + modules.set_item("unicodedata", module.into(), vm).unwrap(); + assert!(vm.load_unicode_names().is_err()); + + let dict = vm.ctx.new_dict(); + dict.set_item("_ucnhash_CAPI", vm.new_unicode_name_capsule().into(), vm) + .unwrap(); + let module = vm.new_module("unicodedata", dict, None); + modules.set_item("unicodedata", module.into(), vm).unwrap(); + assert!(vm.load_unicode_names().is_ok()); + }); + } + + #[test] + fn successful_load_is_cached_after_module_removal() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let modules = vm.sys_module.get_attr("modules", vm).unwrap(); + let dict = vm.ctx.new_dict(); + dict.set_item("_ucnhash_CAPI", vm.new_unicode_name_capsule().into(), vm) + .unwrap(); + let module = vm.new_module("unicodedata", dict, None); + modules.set_item("unicodedata", module.into(), vm).unwrap(); + assert!(vm.load_unicode_names().is_ok()); + modules.del_item("unicodedata", vm).unwrap(); + assert!(vm.load_unicode_names().is_ok()); + }); + } + + #[test] + fn cache_is_interpreter_local() { + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let modules = vm.sys_module.get_attr("modules", vm).unwrap(); + let dict = vm.ctx.new_dict(); + dict.set_item("_ucnhash_CAPI", vm.new_unicode_name_capsule().into(), vm) + .unwrap(); + let module = vm.new_module("unicodedata", dict, None); + modules.set_item("unicodedata", module.into(), vm).unwrap(); + assert!(vm.load_unicode_names().is_ok()); + }); + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let modules = vm.sys_module.get_attr("modules", vm).unwrap(); + modules.set_item("unicodedata", vm.ctx.none(), vm).unwrap(); + assert!(vm.load_unicode_names().is_err()); + }); + } +} diff --git a/crates/vm/src/utils.rs b/crates/vm/src/utils.rs index 50022ad6127..73da45374a2 100644 --- a/crates/vm/src/utils.rs +++ b/crates/vm/src/utils.rs @@ -52,6 +52,7 @@ where return Ok(Wtf8Buf::from(empty)); }; repr.push_wtf8(first.as_wtf8()); + drop(first); for part in parts_iter { repr.push_str(", "); repr.push_wtf8(part?.as_wtf8()); diff --git a/crates/vm/src/version.rs b/crates/vm/src/version.rs index 05eb12a2942..bd421f7ca6e 100644 --- a/crates/vm/src/version.rs +++ b/crates/vm/src/version.rs @@ -69,8 +69,8 @@ pub const RUSTPYTHON_VERSION: &str = const { }; // Must be aligned to Lib/importlib/_bootstrap_external.py -// Matches CPython 3.14 (Include/internal/pycore_magic_number.h). -pub const PYC_MAGIC_NUMBER: u16 = 3627; +// Matches CPython 3.15 (Include/internal/pycore_magic_number.h). +pub const PYC_MAGIC_NUMBER: u16 = 3666; // CPython format: magic_number | ('\r' << 16) | ('\n' << 24) // This protects against text-mode file reads diff --git a/crates/vm/src/vm/async_exception.rs b/crates/vm/src/vm/async_exception.rs new file mode 100644 index 00000000000..e459391359d --- /dev/null +++ b/crates/vm/src/vm/async_exception.rs @@ -0,0 +1,150 @@ +use super::VirtualMachine; +use crate::{ + AsObject, PyAtomicRef, PyObject, PyObjectRef, PyResult, + builtins::{PyBaseException, PyType}, + common::wtf8::Wtf8Buf, +}; +use core::cell::Cell; + +/// Owned by one execution context, like `PyThreadState.async_exc`. +/// This is an external GC root, not an edge owned by a Python object. +/// The VM is not Sync: only its owning execution thread accesses these flags. +/// Cross-thread requests would require a separate synchronized API and wakeup. +pub(super) struct PendingAsyncException { + exception: PyAtomicRef>, + pending: Cell, + closed: Cell, +} + +impl Default for PendingAsyncException { + fn default() -> Self { + Self { + exception: PyAtomicRef::new_empty(), + pending: Cell::new(false), + closed: Cell::new(false), + } + } +} + +impl PendingAsyncException { + pub(super) fn is_pending(&self) -> bool { + self.pending.get() + } + + pub(super) fn has_reference(&self) -> bool { + !self.exception.load_ptr().is_null() + } + + fn replace(&self, exception: Option) -> Option> { + if self.closed.get() { + return None; + } + Some(self.exception.store(exception)) + } + + fn notify(&self) { + if !self.closed.get() { + self.pending.set(true); + } + } + + fn take(&self) -> Option { + if !self.pending.replace(false) { + return None; + } + self.exception.store(None) + } + + fn close(&self) { + // A cleared thread state cannot accept another request. Rejecting + // reentrant requests makes this a single clear, not a finalizer drain. + self.closed.set(true); + self.pending.set(false); + drop(self.exception.store(None)); + } +} + +impl VirtualMachine { + /// Replace the currently attached thread state's asynchronous exception. + /// The outer `None` means that this VM is inactive or is being cleared. + /// The old owner is returned so callers can release it outside all locks, + /// either before or after notification as required by their API contract. + /// `None` as the input cancels; validation happens only during delivery. + pub(crate) fn replace_async_exception( + &self, + exception: Option, + ) -> Option> { + if !super::thread::try_with_current_vm(|vm| core::ptr::eq(vm, self)).unwrap_or(false) { + return None; + } + self.async_exception.replace(exception) + } + + pub(crate) fn notify_async_exception(&self) { + self.async_exception.notify(); + } + + /// Called only at bytecode safepoints, after pending signals and GC. + pub(crate) fn raise_async_exception(&self) -> PyResult<()> { + let Some(exception) = self.async_exception.take() else { + return Ok(()); + }; + let class = match exception.downcast::() { + Ok(class) if class.fast_issubclass(self.ctx.exceptions.base_exception_type) => class, + object => { + let object: PyObjectRef = match object { + Ok(class) => class.into(), + Err(object) => object, + }; + let mut message = Wtf8Buf::from("_PyErr_SetObject: exception "); + message.push_wtf8(object.repr(self)?.as_wtf8()); + message.push_str(" is not a BaseException subclass"); + return Err(self.new_system_error(message)); + } + }; + + // `_PyErr_SetNone` invokes the class through its metaclass, including + // user __call__/__new__/__init__, rather than allocating a bare payload. + let result = class.as_object().call((), self).and_then(|object| { + object.downcast::().map_err(|object| { + let mut message = Wtf8Buf::from("calling "); + match class.as_object().repr(self) { + Ok(repr) => message.push_wtf8(repr.as_wtf8()), + Err(error) => return error, + } + message.push_str(" should have returned an instance of BaseException, not "); + message.push_str(&object.class().slot_name()); + self.new_type_error(message) + }) + }); + let exception = match result { + Ok(exception) => exception, + Err(error) => { + // CPython represents the NULL value passed by SetNone as + // ''; failure in repr's signal check uses ''. + #[cfg(not(target_arch = "wasm32"))] + let args = if crate::signal::check_signals(self).is_ok() { + "" + } else { + "" + }; + #[cfg(target_arch = "wasm32")] + let args = ""; + let note = self.ctx.new_str(format!( + "Normalization failed: type={} args={args}", + class.slot_name() + )); + // A failed attempt to append the note must not replace the + // exception raised by the class constructor. + let _ = error.add_note_str(note, self); + error + } + }; + Err(exception) + } + + /// Clear a thread-state root while its VM and frame slot are still usable. + pub(crate) fn clear_async_exception(&self) { + self.async_exception.close(); + } +} diff --git a/crates/vm/src/vm/compile.rs b/crates/vm/src/vm/compile.rs index 626659f19e1..dc1a89e2919 100644 --- a/crates/vm/src/vm/compile.rs +++ b/crates/vm/src/vm/compile.rs @@ -5,14 +5,25 @@ use core::fmt; use crate::{ - AsObject, PyObjectRef, PyRef, PyResult, VirtualMachine, - builtins::{PyBaseExceptionRef, PyCode}, + AsObject, Py, PyObject, PyObjectRef, PyRef, PyResult, VirtualMachine, + builtins::{PyBaseExceptionRef, PyCode, PyStr, PyStrRef}, compiler::{self, CompileError, CompileOpts}, vm::compile_mode::{CompileStart, CompilerFlags, compile_future_features_from_flags}, }; +/// Warnings already emitted while reading one interactive statement. +/// +/// The source is warned about again after each line is read, but the +/// tokenizer warns about each token only once. +#[cfg(feature = "parser")] +#[derive(Default)] +pub(super) struct InteractiveWarnings { + emitted: alloc::collections::BTreeSet<(usize, String)>, +} + #[derive(Debug)] pub enum VmCompileError { + Exception(PyBaseExceptionRef), Compile(CompileError), Warning(CompileWarningError), } @@ -21,9 +32,11 @@ pub enum VmCompileError { pub struct CompileWarningError { exception: PyBaseExceptionRef, filename: String, + original_filename: Option, lineno: usize, offset: usize, replacement: Option, + diagnostic_text: Option, } #[derive(Debug)] @@ -32,6 +45,12 @@ struct SyntaxErrorReplacement { end_offset: usize, } +impl From for VmCompileError { + fn from(error: PyBaseExceptionRef) -> Self { + Self::Exception(error) + } +} + impl From for VmCompileError { fn from(err: CompileError) -> Self { Self::Compile(err) @@ -41,6 +60,7 @@ impl From for VmCompileError { impl fmt::Display for VmCompileError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::Exception(_) => f.write_str("AST validation raised an exception"), Self::Compile(err) => err.fmt(f), Self::Warning(_) => f.write_str("compiler warning raised as an exception"), } @@ -63,12 +83,15 @@ impl VmCompileError { vm.new_syntax_error_maybe_incomplete(&err, source, allow_incomplete) } Self::Warning(err) => err.into_pyexception(vm, source), + Self::Exception(error) => error, } } } impl CompileWarningError { fn into_pyexception(self, vm: &VirtualMachine, source: Option<&str>) -> PyBaseExceptionRef { + let source = source.map(compiler::core::normalize_newlines); + let source = source.as_deref(); if !self .exception .fast_isinstance(vm.ctx.exceptions.syntax_warning) @@ -105,26 +128,43 @@ impl CompileWarningError { } syntax_error .as_object() - .set_attr("filename", vm.ctx.new_str(self.filename), vm) + .set_attr( + "filename", + self.original_filename + .unwrap_or_else(|| vm.ctx.new_str(self.filename)), + vm, + ) .unwrap(); - let text = source - .and_then(|source| source.split('\n').nth(self.lineno.saturating_sub(1))) - .map_or_else( - || vm.ctx.none(), - |line| { - vm.ctx - .new_str(format!("{}\n", line.trim_end_matches('\r'))) - .into() - }, - ); + let text = self.diagnostic_text.map_or_else( + || { + source + .and_then(|source| source.split('\n').nth(self.lineno.saturating_sub(1))) + .map_or_else( + || vm.ctx.none(), + |line| { + vm.ctx + .new_str(format!("{}\n", line.trim_end_matches('\r'))) + .into() + }, + ) + }, + |text| vm.ctx.new_str(text).into(), + ); syntax_error.as_object().set_attr("text", text, vm).unwrap(); syntax_error } } +#[cfg(feature = "parser")] +struct SourceEncoding { + name: String, + lineno: usize, + line: core::ops::Range, +} + impl VirtualMachine { #[cfg(feature = "parser")] - fn detect_source_encoding(source: &[u8]) -> Option { + fn detect_source_encoding(source: &[u8]) -> Option { fn find_encoding_in_line(line: &[u8]) -> Option { let hash_pos = line.iter().position(|&b| b == b'#')?; if !line[..hash_pos] @@ -134,40 +174,60 @@ impl VirtualMachine { return None; } let after_hash = &line[hash_pos..]; - let coding_pos = after_hash.windows(6).position(|w| w == b"coding")?; - let after_coding = &after_hash[coding_pos + 6..]; - let rest = if after_coding.first() == Some(&b':') || after_coding.first() == Some(&b'=') - { - &after_coding[1..] - } else { - return None; - }; - let name: String = rest - .iter() - .copied() - .skip_while(|&b| b == b' ' || b == b'\t') - .take_while(|&b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.') - .map(|b| b as char) - .collect(); - (!name.is_empty()).then(|| VirtualMachine::normalize_source_encoding(&name)) + for (coding_pos, candidate) in after_hash.windows(6).enumerate() { + if candidate != b"coding" { + continue; + } + let after_coding = &after_hash[coding_pos + 6..]; + if !matches!(after_coding.first(), Some(b':' | b'=')) { + continue; + } + let name: String = after_coding[1..] + .iter() + .copied() + .skip_while(|&b| b == b' ' || b == b'\t') + .take_while(|&b| { + b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.' + }) + .map(|b| b as char) + .collect(); + if !name.is_empty() { + return Some(VirtualMachine::normalize_source_encoding(&name)); + } + } + None } - let mut lines = source.splitn(3, |&b| b == b'\n'); - if let Some(first) = lines.next() { - let first = first.strip_prefix(b"\xef\xbb\xbf").unwrap_or(first); - if let Some(enc) = find_encoding_in_line(first) { - return Some(enc); + let mut start = if source.starts_with(b"\xef\xbb\xbf") { + 3 + } else { + 0 + }; + for lineno in 1..=2 { + let end = source[start..] + .iter() + .position(|&b| b == b'\r' || b == b'\n') + .map_or(source.len(), |offset| start + offset); + let line = &source[start..end]; + if let Some(name) = find_encoding_in_line(line) { + return Some(SourceEncoding { + name, + lineno, + line: start..end, + }); } - let trimmed = first + let first_nonspace = line .iter() - .skip_while(|&&b| b == b' ' || b == b'\t' || b == b'\x0c' || b == b'\r') - .copied() - .collect::>(); - if !trimmed.is_empty() && trimmed[0] != b'#' { + .find(|&&b| b != b' ' && b != b'\t' && b != b'\x0c'); + if first_nonspace.is_some_and(|&b| b != b'#') || end == source.len() { return None; } + start = end + 1; + if source[end] == b'\r' && source.get(start) == Some(&b'\n') { + start += 1; + } } - lines.next().and_then(find_encoding_in_line) + None } #[cfg(feature = "parser")] @@ -205,7 +265,21 @@ impl VirtualMachine { /// the in-memory line; compiler errors read the file named by the /// exception, and get None when that file cannot be opened. #[cfg(any(feature = "parser", feature = "compiler"))] - pub(crate) fn program_text(&self, filename: &str, lineno: usize) -> Option { + pub(crate) fn program_text( + &self, + filename: impl AsRef, + lineno: usize, + ) -> Option { + self.program_text_with_newlines(filename, lineno, false) + } + + #[cfg(any(feature = "parser", feature = "compiler"))] + fn program_text_with_newlines( + &self, + filename: impl AsRef, + lineno: usize, + universal: bool, + ) -> Option { if lineno == 0 { return None; } @@ -215,7 +289,7 @@ impl VirtualMachine { let decoded = { #[cfg(feature = "parser")] { - let encoding = Self::detect_source_encoding(&buf); + let encoding = Self::detect_source_encoding(&buf).map(|cookie| cookie.name); if encoding.as_deref().is_none_or(Self::is_utf8_encoding) { String::from_utf8_lossy(&buf).into_owned() } else if encoding.as_deref() == Some("iso-8859-1") { @@ -240,6 +314,11 @@ impl VirtualMachine { if remaining.starts_with('\u{feff}') { remaining = &remaining['\u{feff}'.len_utf8()..]; } + let remaining = if universal { + compiler::core::normalize_newlines(remaining) + } else { + alloc::borrow::Cow::Borrowed(remaining) + }; remaining .split_inclusive('\n') .nth(lineno.checked_sub(1)?) @@ -247,7 +326,7 @@ impl VirtualMachine { } #[cfg(not(feature = "host_env"))] { - let _ = filename; + let _ = (filename, universal); None } } @@ -255,7 +334,7 @@ impl VirtualMachine { #[cfg(feature = "parser")] fn new_non_utf8_syntax_error( &self, - filename: &str, + filename: &Py, src: &[u8], error_at: usize, ) -> PyBaseExceptionRef { @@ -272,18 +351,19 @@ impl VirtualMachine { .position(|&b| b == b'\n') .map_or(src.len(), |i| line_start + i); let text = String::from_utf8_lossy(&src[line_start..line_end]).into_owned(); - let in_file = if filename.starts_with('<') { - String::new() - } else { - format!(" in file {filename}") - }; - let msg = format!( - "Non-UTF-8 code starting with '\\x{bad_byte:02x}'{in_file} \ - on line {lineno}, but no encoding declared; \ + let mut msg = crate::common::wtf8::Wtf8Buf::from(format!( + "Non-UTF-8 code starting with '\\x{bad_byte:02x}'" + )); + if !filename.as_bytes().starts_with(b"<") { + msg.push_str(" in file "); + msg.push_wtf8(filename.as_wtf8()); + } + msg.push_str(&format!( + " on line {lineno}, but no encoding declared; \ see https://peps.python.org/pep-0263/ for details" - ); + )); let location = self.ctx.new_tuple(vec![ - self.ctx.new_str(filename).into(), + filename.to_owned().into(), self.ctx.new_int(lineno).into(), self.ctx.new_int(offset).into(), self.ctx.new_str(text).into(), @@ -292,10 +372,10 @@ impl VirtualMachine { ]); self.invoke_exception( self.ctx.exceptions.syntax_error, - vec![self.ctx.new_str(msg.as_str()).into(), location.into()], + vec![self.ctx.new_str(msg.clone()).into(), location.into()], ) .unwrap_or_else(|_| { - self.new_exception_msg(self.ctx.exceptions.syntax_error.to_owned(), msg.into()) + self.new_exception_msg(self.ctx.exceptions.syntax_error.to_owned(), msg) }) } @@ -305,6 +385,16 @@ impl VirtualMachine { source: &[u8], filename: &str, ignore_cookie: bool, + ) -> PyResult { + self.decode_source_bytes_with_filename(source, &self.ctx.new_str(filename), ignore_cookie) + } + + #[cfg(feature = "parser")] + pub(crate) fn decode_source_bytes_with_filename( + &self, + source: &[u8], + filename: &Py, + ignore_cookie: bool, ) -> PyResult { // `ignore_cookie` marks source that was handed over as text. A byte // order mark belongs to the byte encoding, so text keeps whatever it @@ -315,60 +405,94 @@ impl VirtualMachine { } else { Self::detect_source_encoding(source) }; - let is_utf8 = encoding.as_deref().is_none_or(Self::is_utf8_encoding); + let encoding_name = encoding.as_ref().map(|cookie| cookie.name.as_str()); + let is_utf8 = encoding_name.is_none_or(Self::is_utf8_encoding); if has_bom && !is_utf8 { - let enc = encoding.as_deref().unwrap_or("utf-8"); - let after_bom = &source[3..]; - let line_end = after_bom + let cookie = encoding.as_ref().unwrap(); + let enc = cookie.name.as_str(); + let line = &source[cookie.line.clone()]; + let text = String::from_utf8_lossy(line).into_owned(); + // CPython's string tokenizer includes the line terminator for + // the second coding line. Its range-error helper converts this + // byte column by counting non-continuation bytes in the prefix. + let end_byte_offset = line.len() + usize::from(cookie.lineno == 2); + let end_offset = 1 + line[..end_byte_offset - 1] .iter() - .position(|&b| b == b'\n') - .unwrap_or(after_bom.len()); - let text = String::from_utf8_lossy(&after_bom[..line_end]).into_owned(); - let end_offset = text.chars().count() as i32; + .filter(|&&byte| byte & 0xc0 != 0x80) + .count(); let msg = format!("encoding problem: {enc} with BOM"); let location = self.ctx.new_tuple(vec![ - self.ctx.new_str(filename).into(), - self.ctx.new_int(1).into(), + filename.to_owned().into(), + self.ctx.new_int(cookie.lineno).into(), self.ctx.new_int(0).into(), self.ctx.new_str(text).into(), - self.ctx.new_int(1).into(), + self.ctx.new_int(cookie.lineno).into(), self.ctx.new_int(end_offset).into(), ]); return Err(self .invoke_exception( self.ctx.exceptions.syntax_error, - vec![self.ctx.new_str(msg.as_str()).into(), location.into()], + vec![self.ctx.new_str(msg.clone()).into(), location.into()], ) .unwrap_or_else(|_| { self.new_exception_msg(self.ctx.exceptions.syntax_error.to_owned(), msg.into()) })); } - if is_utf8 { + let decoded = if is_utf8 { let src = if has_bom { &source[3..] } else { source }; match core::str::from_utf8(src) { - Ok(s) => Ok(s.to_owned()), - Err(e) => Err(self.new_non_utf8_syntax_error(filename, src, e.valid_up_to())), + Ok(s) => s.to_owned(), + Err(e) => { + return Err(self.new_non_utf8_syntax_error(filename, src, e.valid_up_to())); + } } } else { - let encoding = encoding.as_deref().unwrap(); + let encoding = encoding_name.unwrap(); let bytes = self.ctx.new_bytes(source.to_vec()); let decoded = self .state .codec_registry .decode_text(bytes.into(), encoding, None, self) .map_err(|exc| { - if exc.fast_isinstance(self.ctx.exceptions.lookup_error) { - self.new_exception_msg( - self.ctx.exceptions.syntax_error.to_owned(), - format!("unknown encoding for '{filename}': {encoding}").into(), + if exc.fast_isinstance(self.ctx.exceptions.syntax_error) { + match exc + .as_object() + .set_attr("filename", filename.to_owned(), self) + { + Ok(()) => exc, + Err(error) => error, + } + } else if exc.fast_isinstance(self.ctx.exceptions.lookup_error) + || exc.fast_isinstance(self.ctx.exceptions.value_error) + { + let message = match exc.as_object().str(self) { + Ok(message) => message, + Err(error) => return error, + }; + let location = self.ctx.new_tuple(vec![ + filename.to_owned().into(), + self.ctx.new_int(0).into(), + self.ctx.new_int(-1).into(), + self.ctx.none(), + ]); + self.invoke_exception( + self.ctx.exceptions.syntax_error, + vec![message.into(), location.into()], ) + .unwrap_or_else(|error| error) } else { exc } })?; - Ok(decoded.to_string_lossy().into_owned()) - } + decoded.to_string_lossy().into_owned() + }; + // Normalize the source before parsing so literal values, warning ranges, + // and diagnostic text all refer to the same universal-newline input. + Ok(match compiler::core::normalize_newlines(&decoded) { + alloc::borrow::Cow::Borrowed(_) => decoded, + alloc::borrow::Cow::Owned(normalized) => normalized, + }) } #[cfg(feature = "parser")] @@ -381,7 +505,29 @@ impl VirtualMachine { feature_version: i32, optimize: i32, ) -> PyResult { - use crate::convert::ToPyException; + self.compile_string_object_with_flags_and_module( + source, + filename, + start, + flags, + feature_version, + optimize, + None, + ) + } + + #[cfg(feature = "parser")] + #[allow(clippy::too_many_arguments)] + pub(crate) fn compile_string_object_with_flags_and_module( + &self, + source: &[u8], + filename: &str, + start: i32, + flags: i32, + feature_version: i32, + optimize: i32, + module: Option<&Py>, + ) -> PyResult { use crate::stdlib::_ast; let cf = CompilerFlags::from_bits_retain(flags); @@ -411,10 +557,53 @@ impl VirtualMachine { None }; + let emitted_parser_escapes = if is_ast_only { + self.emit_ast_parser_warnings( + source, + filename, + None, + module, + start, + escape_warnings::AstParserWarningOptions { + inherited_barry_as_flufl: future_features + .contains(crate::bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL), + type_comments, + require_relative_import: false, + }, + ) + .map_err(|warning| { + VmCompileError::Warning(warning).into_pyexception(self, Some(source)) + })? + } else { + Vec::new() + }; + let mut emit_ast_warning = |offset, ch| { + if emitted_parser_escapes.binary_search(&offset).is_ok() { + return Ok(()); + } + escape_warnings::warn_invalid_escape_sequence( + source, + escape_warnings::InvalidEscape::Char { ch, offset }, + filename, + None, + module.map(AsObject::as_object), + self, + ) + .map_err(VmCompileError::Warning) + }; if is_ast_only { if start == CompileStart::FuncType { - return _ast::parse_func_type(self, source, filename, optimize, target_version) - .map_err(|e| (e, Some(source), allow_incomplete).to_pyexception(self)); + return _ast::parse_func_type( + self, + source, + filename, + optimize, + target_version, + &mut emit_ast_warning, + ) + .map_err(|e| { + e.into_pyexception_maybe_incomplete(self, Some(source), allow_incomplete) + }); } let (parser_mode, interactive) = match start { CompileStart::Single => (ruff_python_parser::Mode::Module, true), @@ -434,8 +623,12 @@ impl VirtualMachine { interactive, future_features, dont_imply_dedent, + None, + &mut emit_ast_warning, ) - .map_err(|e| (e, Some(source), allow_incomplete).to_pyexception(self))?; + .map_err(|e| { + e.into_pyexception_maybe_incomplete(self, Some(source), allow_incomplete) + })?; if start == CompileStart::Single { return _ast::wrap_interactive(self, &parsed); } @@ -443,12 +636,14 @@ impl VirtualMachine { } if type_comments { + let mut pending_ast_warnings = Vec::new(); + let mut type_comment_error_offset = None; let parser_mode = match start { CompileStart::Single | CompileStart::File => ruff_python_parser::Mode::Module, CompileStart::Eval => ruff_python_parser::Mode::Expression, CompileStart::FuncType => ruff_python_parser::Mode::Module, }; - _ast::parse( + let validation = _ast::parse( self, source, filename, @@ -460,8 +655,59 @@ impl VirtualMachine { start == CompileStart::Single, future_features, dont_imply_dedent, - ) - .map_err(|e| (e, Some(source), allow_incomplete).to_pyexception(self))?; + Some(&mut type_comment_error_offset), + |offset, ch| { + // Successful validation shares the ordinary collector's + // tokenizer/parser order instead of emitting format specs + // prematurely. Preserve reached callbacks if validation fails. + pending_ast_warnings.push((offset, ch)); + Ok::<(), VmCompileError>(()) + }, + ); + if let Err(error) = validation { + // The raw grammar may have reached a relative-import action + // before validation failed. With no type-comment boundary, + // leave the established callback path alone unless there was + // such an action to include. + let emitted = if type_comment_error_offset.is_some() || source.contains("import") { + self.emit_ast_parser_warnings( + source, + filename, + None, + module, + start, + escape_warnings::AstParserWarningOptions { + inherited_barry_as_flufl: future_features + .contains(crate::bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL), + type_comments: true, + require_relative_import: type_comment_error_offset.is_none(), + }, + ) + .map_err(|warning| { + VmCompileError::Warning(warning).into_pyexception(self, Some(source)) + })? + } else { + Vec::new() + }; + for (offset, ch) in pending_ast_warnings { + if type_comment_error_offset.is_none() && emitted.binary_search(&offset).is_ok() + { + continue; + } + emit_ast_warning(offset, ch).map_err(|error| { + error.into_pyexception_maybe_incomplete( + self, + Some(source), + allow_incomplete, + ) + })?; + } + return Err(error.into_pyexception_maybe_incomplete( + self, + Some(source), + allow_incomplete, + )); + } } let mode = match start { @@ -476,7 +722,7 @@ impl VirtualMachine { opts.future_features = future_features; opts.dont_imply_dedent = dont_imply_dedent; let code = self - .compile_with_opts(source, mode, filename, opts) + .compile_with_opts_and_module(source, mode, filename, opts, module, &[]) .map_err(|err| { err.into_pyexception_maybe_incomplete(self, Some(source), allow_incomplete) })?; @@ -499,14 +745,159 @@ impl VirtualMachine { source_path: impl Into, opts: CompileOpts, ) -> Result, VmCompileError> { - let source_path = source_path.into(); + self.compile_with_opts_and_module(source, mode, source_path, opts, None, &[]) + } + + pub(crate) fn compile_symtable_with_module( + &self, + source: &str, + mode: compiler::Mode, + filename: &str, + original_filename: &Py, + module: Option<&Py>, + ) -> Result { + let source = compiler::core::normalize_newlines(source); + let source = source.as_ref(); + #[cfg(feature = "parser")] + { + let start = match mode { + compiler::Mode::Exec | compiler::Mode::BlockExpr => CompileStart::File, + compiler::Mode::Eval => CompileStart::Eval, + compiler::Mode::Single => CompileStart::Single, + }; + // A symbol table observes parser warnings, but does not compile + // bytecode or emit code-generation and AST-preprocessing warnings. + self.emit_ast_parser_warnings( + source, + filename, + Some(original_filename), + module, + start, + escape_warnings::AstParserWarningOptions::default(), + ) + .map_err(VmCompileError::Warning)?; + } + #[cfg(not(feature = "parser"))] + let _ = (module, original_filename); + compiler::compile_symtable(source, mode, filename).map_err(VmCompileError::Compile) + } + + pub(crate) fn compile_with_opts_and_module( + &self, + source: &str, + mode: compiler::Mode, + source_path: impl Into, + opts: CompileOpts, + module: Option<&Py>, + emitted_escapes: &[usize], + ) -> Result, VmCompileError> { + self.compile_with_opts_and_module_object( + source, + mode, + source_path, + opts, + module.map(AsObject::as_object), + emitted_escapes, + ) + } + + // eval()/exec() forward globals["__name__"] unchanged. In particular, + // an absent name and an explicit None have different warning semantics. + pub(crate) fn compile_with_opts_and_module_object( + &self, + source: &str, + mode: compiler::Mode, + source_path: impl Into, + opts: CompileOpts, + module: Option<&PyObject>, + emitted_escapes: &[usize], + ) -> Result, VmCompileError> { + let filename = self.ctx.new_str(source_path.into()); + self.compile_with_python_filename(source, mode, &filename, opts, module, emitted_escapes) + } + + pub(crate) fn compile_with_filename( + &self, + source: &str, + mode: compiler::Mode, + filename: &Py, + opts: CompileOpts, + module: Option<&Py>, + ) -> PyResult> { + self.compile_with_python_filename( + source, + mode, + filename, + opts, + module.map(AsObject::as_object), + &[], + ) + .map_err(|error| match error { + VmCompileError::Compile(error) => { + self.new_syntax_error_with_filename(&error, Some(source), false, Some(filename)) + } + VmCompileError::Warning(error) => error.into_pyexception(self, Some(source)), + VmCompileError::Exception(error) => error, + }) + } + + fn compile_with_python_filename( + &self, + source: &str, + mode: compiler::Mode, + filename: &Py, + opts: CompileOpts, + module: Option<&PyObject>, + emitted_escapes: &[usize], + ) -> Result, VmCompileError> { + #[cfg(not(feature = "parser"))] + let _ = (module, emitted_escapes); + let source = compiler::core::normalize_newlines(source); + let source = source.as_ref(); #[cfg(feature = "parser")] { - self.emit_tokenizer_syntax_warnings(source, &source_path) - .map_err(VmCompileError::Warning)?; - self.emit_string_escape_warnings(source, &source_path) - .map_err(VmCompileError::Warning)?; + self.emit_standard_parser_warnings( + source, + filename, + module, + mode, + opts.future_features + .contains(crate::bytecode::CodeFlags::FUTURE_BARRY_AS_BDFL), + emitted_escapes, + ) + .map_err(VmCompileError::Warning)?; } + self.compile_after_parser_warnings_object(source, mode, filename, opts, module) + } + + pub(super) fn compile_after_parser_warnings( + &self, + source: &str, + mode: compiler::Mode, + source_path: impl Into, + opts: CompileOpts, + module: Option<&Py>, + ) -> Result, VmCompileError> { + self.compile_after_parser_warnings_object( + source, + mode, + &self.ctx.new_str(source_path.into()), + opts, + module.map(AsObject::as_object), + ) + } + + fn compile_after_parser_warnings_object( + &self, + source: &str, + mode: compiler::Mode, + filename: &Py, + opts: CompileOpts, + module: Option<&PyObject>, + ) -> Result, VmCompileError> { + let source_path = filename.to_string_lossy(); + #[cfg(not(feature = "parser"))] + let _ = module; #[cfg(feature = "parser")] let code = { // A warning the filter escalates to an exception is stashed here so @@ -514,7 +905,7 @@ impl VirtualMachine { let escalated: core::cell::Cell> = core::cell::Cell::new(None); let mut syntax_warning_handler = |location, message| { - escape_warnings::warn_syntax_at_location(&source_path, location, message, self) + escape_warnings::warn_syntax_at_location(filename, module, location, message, self) .map_err(|warning| { escalated.set(Some(warning)); // Recovered below via `escalated`, so this is never surfaced. @@ -524,7 +915,7 @@ impl VirtualMachine { error: compiler::codegen::error::CodegenErrorType::SyntaxError( String::new(), ), - source_path: source_path.clone(), + source_path: source_path.to_string(), } }) }; @@ -545,6 +936,14 @@ impl VirtualMachine { let code = code .map(|code| PyCode::new_ref_from_bytecode(self, code)) .map_err(VmCompileError::Compile)?; + // The parser's UTF-8 diagnostic label is not the Python filename. + // Preserve the original in all nested runtime code objects. + if !filename.is_utf8() { + crate::builtins::code::set_source_path_tree( + &code, + self.ctx.intern_str(filename.as_wtf8()), + ); + } Ok(code) } } @@ -559,17 +958,13 @@ impl VirtualMachine { mod escape_warnings { use super::*; use crate::warn; - use ruff_python_ast::{self as ast, visitor::Visitor}; - use ruff_text_size::TextRange; - - /// Calculate 1-indexed line number at byte offset in source. - fn line_number_at(source: &str, offset: usize) -> usize { - source[..offset.min(source.len())] - .bytes() - .filter(|&b| b == b'\n') - .count() - + 1 - } + use ruff_python_ast::{ + self as ast, + token::{Token, TokenKind, Tokens}, + visitor::Visitor, + }; + use ruff_python_parser::{ExpressionKind, LexicalErrorType, ParseError, ParseErrorType}; + use ruff_text_size::{Ranged as _, TextRange, TextSize}; fn line_offset_at(source: &str, offset: usize) -> (usize, usize) { let offset = offset.min(source.len()); @@ -580,19 +975,43 @@ mod escape_warnings { (lineno, column) } + // Tokenizer errors use universal-newline physical positions even though + // the caller retains the original source bytes for diagnostic text. + fn tokenizer_line_offset_at(source: &str, offset: usize) -> (usize, usize) { + let offset = offset.min(source.len()); + let bytes = source.as_bytes(); + let mut lineno = 1; + let mut line_start = 0; + for index in 0..offset { + if bytes[index] == b'\r' { + lineno += 1; + line_start = index + 1; + } else if bytes[index] == b'\n' { + if index == 0 || bytes[index - 1] != b'\r' { + lineno += 1; + } + line_start = index + 1; + } + } + (lineno, source[line_start..offset].chars().count() + 1) + } + fn compile_warning_error( exception: PyBaseExceptionRef, source: &str, filename: &str, + original_filename: Option<&Py>, offset: usize, ) -> CompileWarningError { - let (lineno, offset) = line_offset_at(source, offset); + let (lineno, offset) = tokenizer_line_offset_at(source, offset); CompileWarningError { exception, filename: filename.to_owned(), + original_filename: original_filename.map(ToOwned::to_owned), lineno, offset, replacement: None, + diagnostic_text: None, } } @@ -618,64 +1037,355 @@ mod escape_warnings { if cs <= ce { Some((cs, ce)) } else { None } } - enum InvalidEscape { + pub(super) enum InvalidEscape { Char { ch: char, offset: usize }, Octal { digits: [u8; 3], offset: usize }, } - impl InvalidEscape { - fn offset(&self) -> usize { - match self { - Self::Char { offset, .. } | Self::Octal { offset, .. } => *offset, - } - } + #[derive(Clone, Copy, PartialEq, Eq)] + enum EscapeOrigin { + Parser, + Tokenizer, + } - fn octal_text(digits: [u8; 3]) -> [char; 3] { - [digits[0] as char, digits[1] as char, digits[2] as char] - } + #[derive(Clone, Copy, PartialEq, Eq)] + enum InterpolatedBodyDiagnostics { + Legacy, + TokenAnchored { implicit_final_newline: bool }, + } - fn warning_message(&self) -> String { - match self { - Self::Char { ch, .. } => format!( - "\"\\{ch}\" is an invalid escape sequence. \ - Such sequences will not work in the future. \ - Did you mean \"\\\\{ch}\"? A raw string is also an option." - ), - Self::Octal { digits, .. } => { - let [a, b, c] = Self::octal_text(*digits); - format!( - "\"\\{a}{b}{c}\" is an invalid octal escape sequence. \ - Such sequences will not work in the future. \ - Did you mean \"\\\\{a}{b}{c}\"? A raw string is also an option." - ) - } - } - } + struct EscapeDiagnosticLocation { + emission_offset: usize, + lineno: usize, + offset: usize, + end_offset: usize, + text_start: usize, + text_end: usize, + append_newline: bool, + } - fn syntax_error_message(&self) -> String { - match self { - Self::Char { ch, .. } => format!( - "\"\\{ch}\" is an invalid escape sequence. \ - Did you mean \"\\\\{ch}\"? A raw string is also an option." - ), - Self::Octal { digits, .. } => { - let [a, b, c] = Self::octal_text(*digits); - format!( - "\"\\{a}{b}{c}\" is an invalid octal escape sequence. \ - Did you mean \"\\\\{a}{b}{c}\"? A raw string is also an option." - ) + #[derive(Clone, Copy)] + struct InterpolatedTokenAnchor { + token_start: usize, + token_end: usize, + quote_len: usize, + } + + fn interpolated_body_anchor(source: &str, range: TextRange) -> Option { + let (_, closing_start) = content_bounds(source, range)?; + Some(InterpolatedTokenAnchor { + token_start: closing_start, + token_end: range.end().to_usize(), + quote_len: range.end().to_usize() - closing_start, + }) + } + + struct SourceDiagnosticLine { + start: usize, + end: usize, + terminated: bool, + } + + struct NonAsciiScalar { + start: usize, + len: usize, + excess_before: usize, + } + + // Built lazily once per collector, only if an anchored warning is found. + // ASCII contributes no scalar-index entries. Per-warning metadata stays + // constant-sized even when many MIDDLE fragments share one long line. + struct SourceDiagnosticIndex { + lines: Vec, + non_ascii: Vec, + } + + impl SourceDiagnosticIndex { + fn new(source: &str) -> Self { + let bytes = source.as_bytes(); + let mut lines = Vec::new(); + let mut start = 0; + let mut cursor = 0; + while cursor < bytes.len() { + if matches!(bytes[cursor], b'\r' | b'\n') { + lines.push(SourceDiagnosticLine { + start, + end: cursor, + terminated: true, + }); + if bytes[cursor] == b'\r' && bytes.get(cursor + 1) == Some(&b'\n') { + cursor += 1; + } + start = cursor + 1; } + cursor += 1; } + lines.push(SourceDiagnosticLine { + start, + end: source.len(), + terminated: false, + }); + let mut excess = 0; + let non_ascii = source + .char_indices() + .filter_map(|(start, ch)| { + if ch.is_ascii() { + return None; + } + let len = ch.len_utf8(); + let entry = NonAsciiScalar { + start, + len, + excess_before: excess, + }; + excess += len - 1; + Some(entry) + }) + .collect(); + Self { lines, non_ascii } + } + + // A partial final UTF8 scalar counts as one replacement character, + // matching the parser's decode-with-replacement prefix conversion. + fn character_count(&self, byte_offset: usize) -> usize { + let count = self + .non_ascii + .partition_point(|entry| entry.start < byte_offset); + let excess = count.checked_sub(1).map_or(0, |index| { + let entry = &self.non_ascii[index]; + entry.excess_before + (byte_offset - entry.start).min(entry.len) - 1 + }); + byte_offset - excess } } - /// Scan `source[start..end]` for the first invalid escape sequence. - /// - /// When `is_bytes` is true, `\u`, `\U`, and `\N` are treated as invalid - /// (bytes literals only support byte-oriented escapes). - /// - /// Only reports the **first** invalid escape per string literal, matching - /// `_PyUnicode_DecodeUnicodeEscapeInternal2` which stores only the first + #[derive(Clone, Copy)] + struct InterpolatedLiteralContext<'a> { + anchor: InterpolatedTokenAnchor, + index: &'a core::cell::OnceCell, + implicit_final_newline: bool, + } + + // CPython decodes ordinary interpolated body constants with the END token, + // not the MIDDLE token used for format-spec constants. Keep the actual escape + // offset separate: it still owns deduplication and input boundaries. + fn interpolated_literal_location( + source: &str, + start: usize, + end: usize, + escape_offset: usize, + context: InterpolatedLiteralContext<'_>, + ) -> EscapeDiagnosticLocation { + debug_assert!(start <= escape_offset && escape_offset < end); + let anchor = context.anchor; + let index = context + .index + .get_or_init(|| SourceDiagnosticIndex::new(source)); + let line_index = index + .lines + .partition_point(|line| line.start <= anchor.token_start) + - 1; + let line = &index.lines[line_index]; + let token_lineno = line_index + 1; + let mut lineno = token_lineno; + let mut column = anchor.token_start - line.start; + // string_parser.c rewrites non-ASCII codepoints to \UXXXXXXXX before + // computing the first invalid escape pointer. Backslash + non-ASCII + // uses \u005c followed by that rewrite. Include the invalid backslash, + // not the following character to which first_invalid_escape points. + let mut chars = source[start..=escape_offset].chars().peekable(); + while let Some(mut ch) = chars.next() { + if ch == '\\' { + column += if chars.peek().is_some_and(|ch| !ch.is_ascii()) { + 6 + } else { + 1 + }; + let Some(next) = chars.next() else { + break; + }; + ch = next; + } + if ch == '\r' { + if chars.peek() == Some(&'\n') { + chars.next(); + } + ch = '\n'; + } + if ch == '\n' { + lineno += 1; + column = 0; + } else { + column += if ch.is_ascii() { 1 } else { 10 }; + } + } + if lineno == token_lineno { + column += anchor.quote_len; + } + let current_line_index = index + .lines + .partition_point(|line| line.start <= anchor.token_end) + - 1; + // pegen_errors.c uses the tokenizer's current line when the diagnostic + // is at or beyond it. Otherwise it looks up the earlier source line, + // without its LF. END anchors always take the current-line branch; + // multiline format-spec MIDDLE tokens can take either branch. + let use_current_line = current_line_index < lineno; + let line = &index.lines[if use_current_line { + current_line_index + } else { + lineno - 1 + }]; + let append_newline = + use_current_line && (line.terminated || context.implicit_final_newline); + // A physical CR/CRLF becomes LF. Only file input synthesizes a final + // LF when absent. pegen.c then clamps to that line plus its NUL. + let content_len = line.end - line.start; + let base_characters = index.character_count(line.start); + let character_offset = |offset: usize| { + index.character_count(line.start + offset.min(content_len)) - base_characters + + usize::from(append_newline && offset > content_len) + + usize::from(offset > content_len + usize::from(append_newline)) + }; + EscapeDiagnosticLocation { + emission_offset: anchor.token_end, + lineno, + offset: character_offset(column), + end_offset: character_offset(column + 2), + text_start: line.start, + text_end: line.end, + append_newline, + } + } + + struct RelativeLazyImportWarning { + module: TextRange, + statement_end: usize, + lookahead: Option, + level: u32, + } + + impl RelativeLazyImportWarning { + fn message(&self) -> String { + let dots = ".".repeat(self.level as usize); + format!( + "'from {dots} lazy import' is the same as 'from {dots}lazy import'; \ + did you mean 'lazy from {dots} import'?" + ) + } + } + + enum ParserWarning { + RelativeLazyImport(RelativeLazyImportWarning), + TokenizerRecoveryError(ParseError, compiler::Mode, bool), + /// The escape, where it is reported from, and for a bytes literal + /// escape on the literal's first line, the error column that + /// string_parser.c reports. + Escape( + InvalidEscape, + EscapeOrigin, + Option, + Option, + ), + Numeric { + offset: usize, + last_offset: usize, + message: String, + in_interpolation: bool, + }, + } + + impl ParserWarning { + fn offset(&self) -> usize { + match self { + Self::Escape(escape, ..) => escape.offset(), + Self::Numeric { offset, .. } => *offset, + Self::RelativeLazyImport(import) => import.module.start().to_usize(), + Self::TokenizerRecoveryError(error, ..) => error.location.start().to_usize(), + } + } + + fn emission_offset(&self) -> usize { + match self { + // The grammar decodes body constants only after consuming the + // END token. Expressions and format specs have already been + // parsed by then, even if their escapes occur later in source. + Self::Escape(_, _, _, Some(diagnostic)) => diagnostic.emission_offset, + Self::RelativeLazyImport(import) => { + import.lookahead.unwrap_or(import.statement_end) + } + _ => self.offset(), + } + } + + fn type_comment_boundary_offset(&self) -> usize { + match self { + Self::RelativeLazyImport(import) => import.statement_end, + _ => self.emission_offset(), + } + } + + fn is_parser_origin(&self) -> bool { + matches!( + self, + Self::Escape(_, EscapeOrigin::Parser, ..) | Self::RelativeLazyImport(_) + ) + } + } + + impl InvalidEscape { + fn offset(&self) -> usize { + match self { + Self::Char { offset, .. } | Self::Octal { offset, .. } => *offset, + } + } + + fn octal_text(digits: [u8; 3]) -> [char; 3] { + [digits[0] as char, digits[1] as char, digits[2] as char] + } + + fn warning_message(&self) -> String { + match self { + Self::Char { ch, .. } => format!( + "\"\\{ch}\" is an invalid escape sequence. \ + Such sequences will not work in the future. \ + Did you mean \"\\\\{ch}\"? A raw string is also an option." + ), + Self::Octal { digits, .. } => { + let [a, b, c] = Self::octal_text(*digits); + format!( + "\"\\{a}{b}{c}\" is an invalid octal escape sequence. \ + Such sequences will not work in the future. \ + Did you mean \"\\\\{a}{b}{c}\"? A raw string is also an option." + ) + } + } + } + + fn syntax_error_message(&self) -> String { + match self { + Self::Char { ch, .. } => format!( + "\"\\{ch}\" is an invalid escape sequence. \ + Did you mean \"\\\\{ch}\"? A raw string is also an option." + ), + Self::Octal { digits, .. } => { + let [a, b, c] = Self::octal_text(*digits); + format!( + "\"\\{a}{b}{c}\" is an invalid octal escape sequence. \ + Did you mean \"\\\\{a}{b}{c}\"? A raw string is also an option." + ) + } + } + } + } + + /// Scan `source[start..end]` for the first invalid escape sequence. + /// + /// When `is_bytes` is true, `\u`, `\U`, and `\N` are treated as invalid + /// (bytes literals only support byte-oriented escapes). + /// + /// Only reports the **first** invalid escape per string literal, matching + /// `_PyUnicode_DecodeUnicodeEscapeInternal2` which stores only the first /// `first_invalid_escape_char`. fn first_invalid_escape( source: &str, @@ -761,6 +1471,10 @@ mod escape_warnings { true } } + // string_parser.c protects a backslash before a non-ASCII + // codepoint as \\u005c before passing the rewritten buffer to + // the Unicode escape decoder. It cannot be an invalid escape. + ch if !is_bytes && !ch.is_ascii() => true, _ => false, }; if !valid { @@ -773,22 +1487,51 @@ mod escape_warnings { /// Emit `SyntaxWarning` for an invalid escape sequence. /// /// `warn_invalid_escape_sequence()` in `Parser/string_parser.c` - fn warn_invalid_escape_sequence( + pub(super) fn warn_invalid_escape_sequence( source: &str, escape: InvalidEscape, filename: &str, + original_filename: Option<&Py>, + module: Option<&PyObject>, vm: &VirtualMachine, ) -> Result<(), CompileWarningError> { - let (lineno, column) = line_offset_at(source, escape.offset()); + warn_invalid_escape_sequence_at( + source, + escape, + filename, + original_filename, + module, + None, + vm, + ) + } + + fn warn_invalid_escape_sequence_at( + source: &str, + escape: InvalidEscape, + filename: &str, + original_filename: Option<&Py>, + module: Option<&PyObject>, + diagnostic: Option, + vm: &VirtualMachine, + ) -> Result<(), CompileWarningError> { + let (lineno, column) = diagnostic.as_ref().map_or_else( + || line_offset_at(source, escape.offset()), + |location| (location.lineno, location.offset), + ); + let end_offset = diagnostic + .as_ref() + .map_or(column + 2, |location| location.end_offset); let warning = escape.warning_message(); let syntax_error = escape.syntax_error_message(); - let fname = vm.ctx.new_str(filename); + let fname = + original_filename.map_or_else(|| vm.ctx.new_str(filename), |name| name.to_owned()); warn::warn_explicit( Some(vm.ctx.exceptions.syntax_warning.to_owned()), vm.ctx.new_str(warning).into(), fname, lineno, - None, + module.map(ToOwned::to_owned), vm.ctx.none(), None, None, @@ -797,11 +1540,19 @@ mod escape_warnings { .map_err(|exception| CompileWarningError { exception, filename: filename.to_owned(), + original_filename: original_filename.map(ToOwned::to_owned), lineno, offset: column, replacement: Some(SyntaxErrorReplacement { message: syntax_error, - end_offset: column + 2, + end_offset, + }), + diagnostic_text: diagnostic.map(|location| { + let mut text = source[location.text_start..location.text_end].to_owned(); + if location.append_newline { + text.push('\n'); + } + text }), }) } @@ -809,41 +1560,45 @@ mod escape_warnings { fn warn_syntax_at_offset( source: &str, filename: &str, + original_filename: Option<&Py>, + module: Option<&PyObject>, offset: usize, message: String, vm: &VirtualMachine, ) -> Result<(), CompileWarningError> { - let lineno = line_number_at(source, offset); - let fname = vm.ctx.new_str(filename); + let (lineno, _) = tokenizer_line_offset_at(source, offset); + let fname = + original_filename.map_or_else(|| vm.ctx.new_str(filename), |name| name.to_owned()); let message = vm.ctx.new_str(message); warn::warn_explicit( Some(vm.ctx.exceptions.syntax_warning.to_owned()), message.into(), fname, lineno, - None, + module.map(ToOwned::to_owned), vm.ctx.none(), None, None, vm, ) - .map_err(|err| compile_warning_error(err, source, filename, offset)) + .map_err(|err| compile_warning_error(err, source, filename, original_filename, offset)) } pub(super) fn warn_syntax_at_location( - filename: &str, + filename: &Py, + module: Option<&PyObject>, location: compiler::core::SourceLocation, message: String, vm: &VirtualMachine, ) -> Result<(), CompileWarningError> { - let fname = vm.ctx.new_str(filename); + let fname = filename.to_owned(); let message = vm.ctx.new_str(message); warn::warn_explicit( Some(vm.ctx.exceptions.syntax_warning.to_owned()), message.into(), fname, location.line.get(), - None, + module.map(ToOwned::to_owned), vm.ctx.none(), None, None, @@ -851,10 +1606,12 @@ mod escape_warnings { ) .map_err(|exception| CompileWarningError { exception, - filename: filename.to_owned(), + filename: filename.to_string_lossy().into_owned(), + original_filename: Some(filename.to_owned()), lineno: location.line.get(), offset: location.character_offset.get(), replacement: None, + diagnostic_text: None, }) } @@ -1078,36 +1835,66 @@ mod escape_warnings { ) } - fn warn_quoted_literal( + fn collect_quoted_literal_warning( source: &str, - quote_index: usize, + literal_start: usize, end: usize, is_bytes: bool, - filename: &str, - vm: &VirtualMachine, - ) -> Result<(), CompileWarningError> { + warnings: &mut Vec, + ) { if let Some((start, content_end)) = - content_bounds(source, text_range_from_bounds(quote_index, end)) + content_bounds(source, text_range_from_bounds(literal_start, end)) && let Some(escape) = first_invalid_escape(source, start, content_end, is_bytes) { - warn_invalid_escape_sequence(source, escape, filename, vm)?; + let before_escape = &source[start..escape.offset()]; + // string_parser.c counts leading quotes from the token start. + // A bytes prefix contributes none to its first-line error range. + // Keep the actual escape offset for warning order and deduplication. + let error_column = (is_bytes && !before_escape.contains(['\r', '\n'])).then(|| { + let (_, column) = line_offset_at(source, escape.offset()); + column.saturating_sub(start - literal_start) + }); + warnings.push(ParserWarning::Escape( + escape, + EscapeOrigin::Parser, + error_column, + None, + )); } - Ok(()) } - fn warn_fstring_literal_part( + fn collect_fstring_literal_warning( source: &str, start: usize, end: usize, - filename: &str, - vm: &VirtualMachine, - ) -> Result<(), CompileWarningError> { + warnings: &mut Vec, + anchor: Option>, + ) { if start >= end || end > source.len() { - return Ok(()); + return; } if let Some(escape) = first_invalid_escape(source, start, end, false) { - return warn_invalid_escape_sequence(source, escape, filename, vm); - } + let origin = if matches!(&escape, InvalidEscape::Char { ch: '{' | '}', .. }) { + EscapeOrigin::Tokenizer + } else { + EscapeOrigin::Parser + }; + let diagnostic = if origin == EscapeOrigin::Parser { + anchor.map(|anchor| { + interpolated_literal_location(source, start, end, escape.offset(), anchor) + }) + } else { + None + }; + warnings.push(ParserWarning::Escape(escape, origin, None, diagnostic)); + return; + } + // In CPython, _PyTokenizer_warn_invalid_escape_sequence handles + // `\{` and `\}` for FSTRING_MIDDLE/FSTRING_END tokens. Ruff + // splits the literal element before the interpolation delimiter, + // so the `\` sits at the end of the literal range and the `{`/`}` + // sits just after it. Only warn when the number of trailing + // backslashes is odd (an even count means they are all escaped). let trailing_bs = source.as_bytes()[start..end] .iter() .rev() @@ -1117,17 +1904,16 @@ mod escape_warnings { && let Some(&after) = source.as_bytes().get(end) && (after == b'{' || after == b'}') { - warn_invalid_escape_sequence( - source, + warnings.push(ParserWarning::Escape( InvalidEscape::Char { ch: after as char, offset: end - 1, }, - filename, - vm, - )?; + EscapeOrigin::Tokenizer, + None, + None, + )); } - Ok(()) } fn find_interpolation_end(bytes: &[u8], open: usize, limit: usize) -> usize { @@ -1184,9 +1970,8 @@ mod escape_warnings { start: usize, end: usize, is_raw: bool, - filename: &str, - vm: &VirtualMachine, - ) -> Result<(), CompileWarningError> { + warnings: &mut Vec, + ) { let bytes = source.as_bytes(); let mut index = start; let mut literal_start = start; @@ -1197,18 +1982,23 @@ mod escape_warnings { } b'{' => { if !is_raw { - warn_fstring_literal_part(source, literal_start, index, filename, vm)?; + collect_fstring_literal_warning( + source, + literal_start, + index, + warnings, + None, + ); } let close = find_interpolation_end(bytes, index, end); let body_end = if close > index + 1 { close - 1 } else { close }; - emit_string_escape_warnings_in_range( + collect_string_escape_warnings_in_range( source, index + 1, body_end, Some(is_raw), - filename, - vm, - )?; + warnings, + ); index = close.max(index + 1); literal_start = index; } @@ -1220,29 +2010,19 @@ mod escape_warnings { } } if !is_raw { - warn_fstring_literal_part(source, literal_start, end, filename, vm)?; + collect_fstring_literal_warning(source, literal_start, end, warnings, None); } - Ok(()) } /// Scan quoted literals without a successful parse, matching the tokenizer /// path that warns before the parser rejects the rest of the source. - fn emit_string_escape_warnings_unparsed( - source: &str, - filename: &str, - vm: &VirtualMachine, - ) -> Result<(), CompileWarningError> { - emit_string_escape_warnings_in_range(source, 0, source.len(), None, filename, vm) - } - - fn emit_string_escape_warnings_in_range( + fn collect_string_escape_warnings_in_range( source: &str, start: usize, end: usize, format_spec_raw: Option, - filename: &str, - vm: &VirtualMachine, - ) -> Result<(), CompileWarningError> { + warnings: &mut Vec, + ) { let bytes = source.as_bytes(); let end = end.min(bytes.len()); let mut index = start; @@ -1274,18 +2054,24 @@ mod escape_warnings { content_start, content_end.min(end), is_raw, - filename, - vm, - )?; + warnings, + ); } } else if !is_raw { - warn_quoted_literal( - source, index, quote_end, is_bytes, filename, vm, - )?; + collect_quoted_literal_warning( + // Non-raw ordinary prefixes are one-byte b/u. + source, + index - 1, + quote_end, + is_bytes, + warnings, + ); } } StringPrefix::None => { - warn_quoted_literal(source, index, quote_end, false, filename, vm)?; + collect_quoted_literal_warning( + source, index, quote_end, false, warnings, + ); } StringPrefix::Invalid => {} } @@ -1296,8 +2082,8 @@ mod escape_warnings { && bracket == 0 && brace == 0 => { - scan_interpolated_content(source, index + 1, end, is_raw, filename, vm)?; - return Ok(()); + scan_interpolated_content(source, index + 1, end, is_raw, warnings); + return; } b'(' if format_spec_raw.is_some() => { paren += 1; @@ -1326,14 +2112,9 @@ mod escape_warnings { _ => index += 1, } } - Ok(()) } - fn emit_numeric_literal_warnings( - source: &str, - filename: &str, - vm: &VirtualMachine, - ) -> Result<(), CompileWarningError> { + fn collect_numeric_literal_warnings(source: &str, warnings: &mut Vec) { let bytes = source.as_bytes(); let mut index = 0; while index < bytes.len() { @@ -1360,51 +2141,421 @@ mod escape_warnings { continue; }; if end > index && numeric_keyword_suffix(&bytes[end..]) { - warn_syntax_at_offset( - source, - filename, - index, - format!("invalid {kind} literal"), - vm, - )?; + warnings.push(ParserWarning::Numeric { + offset: index, + last_offset: end - 1, + message: format!("invalid {kind} literal"), + in_interpolation: false, + }); } index = end.max(index + 1); } _ => index += 1, } } - Ok(()) } - struct EscapeWarningVisitor<'a> { + fn collect_interpolated_fragment_warning( + source: &str, + start: usize, + end: usize, + warnings: &mut Vec, + anchor: Option>, + ) { + if let Some(escape) = first_invalid_escape(source, start, end, false) + && !matches!(escape, InvalidEscape::Char { ch: '{' | '}', .. }) + { + // The tokenizer reports braces independently. The decoder still + // stops at its first invalid escape, including an already-reported + // brace; it must not search past that brace for a parser warning. + let diagnostic = anchor.map(|context| { + interpolated_literal_location(source, start, end, escape.offset(), context) + }); + warnings.push(ParserWarning::Escape( + escape, + EscapeOrigin::Parser, + None, + diagnostic, + )); + } + } + + fn collect_interpolated_tokenizer_warnings( + source: &str, + start: usize, + end: usize, + index: &core::cell::OnceCell, + warnings: &mut Vec, + ) { + let bytes = source.as_bytes(); + let mut cursor = start; + while cursor < end { + if bytes[cursor] != b'\\' { + cursor += source[cursor..end].chars().next().unwrap().len_utf8(); + continue; + } + let escape_offset = cursor; + cursor += 1; + if let Some(&brace) = bytes.get(cursor) + && matches!(brace, b'{' | b'}') + { + let index = index.get_or_init(|| SourceDiagnosticIndex::new(source)); + let line_index = index.lines.partition_point(|line| line.start <= cursor) - 1; + let line = &index.lines[line_index]; + // helpers.c reports the tokenizer cursor after reading the + // brace, a zero-width range, and the physical line without LF. + let column = index.character_count(cursor + 1) - index.character_count(line.start); + warnings.push(ParserWarning::Escape( + InvalidEscape::Char { + ch: brace as char, + offset: escape_offset, + }, + EscapeOrigin::Tokenizer, + None, + Some(EscapeDiagnosticLocation { + emission_offset: escape_offset, + lineno: line_index + 1, + offset: column, + end_offset: column, + text_start: line.start, + text_end: line.end, + append_newline: false, + }), + )); + } else if cursor < end { + cursor += source[cursor..end].chars().next().unwrap().len_utf8(); + if bytes.get(cursor - 1) == Some(&b'\r') && bytes.get(cursor) == Some(&b'\n') { + cursor += 1; + } + } + } + } + + fn collect_interpolated_literal_warnings( + source: &str, + start: usize, + end: usize, + body_anchor: Option, + index: &core::cell::OnceCell, + implicit_final_newline: bool, + warnings: &mut Vec, + ) { + // CPython emits a separate MIDDLE token after doubled braces and named + // Unicode escapes. Doubled braces are only literal outside format specs. + // Ruff can keep these inside one literal element. + let bytes = source.as_bytes(); + let mut collect_fragment = |start: usize, end: usize| { + let anchor = body_anchor.unwrap_or_else(|| { + // string_parser.c counts the initial run of quote characters + // in the actual token, even for format-spec MIDDLE tokens. + let quote_len = bytes.get(start).map_or(0, |quote| { + bytes[start..end] + .iter() + .take_while(|&&byte| matches!(byte, b'\'' | b'"')) + .filter(|&byte| byte == quote) + .count() + }); + InterpolatedTokenAnchor { + token_start: start, + token_end: end, + quote_len, + } + }); + collect_interpolated_fragment_warning( + source, + start, + end, + warnings, + Some(InterpolatedLiteralContext { + anchor, + index, + implicit_final_newline, + }), + ); + }; + let mut fragment_start = start; + let mut cursor = start; + while cursor < end { + match bytes[cursor] { + b'{' | b'}' + if body_anchor.is_some() && bytes.get(cursor + 1) == Some(&bytes[cursor]) => + { + collect_fragment(fragment_start, cursor + 1); + cursor += 2; + fragment_start = cursor; + } + b'\\' => { + if bytes.get(cursor + 1) == Some(&b'N') + && bytes.get(cursor + 2) == Some(&b'{') + && let Some(close) = source[cursor + 3..end].find('}') + { + cursor += 3 + close + 1; + collect_fragment(fragment_start, cursor); + fragment_start = cursor; + continue; + } + cursor += 1; + if cursor < end && !matches!(bytes[cursor], b'{' | b'}') { + // Paired backslashes must not turn the second slash + // into a new named-Unicode escape introducer. + cursor += source[cursor..end].chars().next().unwrap().len_utf8(); + if bytes.get(cursor - 1) == Some(&b'\r') + && bytes.get(cursor) == Some(&b'\n') + { + cursor += 1; + } + } + } + _ => cursor += source[cursor..end].chars().next().unwrap().len_utf8(), + } + } + collect_fragment(fragment_start, end); + } + + // In CPython a tokenizer exception, unlike a rejected token, can + // preempt a parser-action SyntaxError during full-source tokenization. + fn tokenizer_recovery_error(error: &ParseError) -> bool { + matches!( + &error.error, + ParseErrorType::Lexical(kind) + if kind.is_tokenizer_error() + && !matches!( + kind, + LexicalErrorType::FStringError(_) + | LexicalErrorType::TStringError(_) + | LexicalErrorType::UnclosedBracket { .. } + | LexicalErrorType::Eof + ) + ) + } + + fn is_inside_interpolation(tokens: &Tokens, offset: TextSize) -> bool { + let mut depth = 0usize; + for token in tokens.iter().take_while(|token| token.start() < offset) { + match token.kind() { + TokenKind::FStringStart | TokenKind::TStringStart => depth += 1, + TokenKind::FStringEnd | TokenKind::TStringEnd => depth = depth.saturating_sub(1), + _ => {} + } + } + depth != 0 + } + + struct RelativeImportWarnings<'a> { + tokens: &'a Tokens, + errors: &'a [ParseError], + first_error: Option, + tokenizer_error: Option, + } + + impl RelativeImportWarnings<'_> { + fn tokens_from(&self, offset: TextSize) -> impl Iterator { + let index = self.tokens.partition_point(|token| token.start() < offset); + self.tokens[index..] + .iter() + .filter(|token| !token.kind().is_trivia()) + } + + // Ruff may point a recovery diagnostic at a token CPython already + // accepted. Use exact token/alias ownership only for this action. + fn recovered_target_diagnostic( + &self, + error: &ParseError, + import: &ast::StmtImportFrom, + first: &Token, + ) -> bool { + match &error.error { + ParseErrorType::OtherError(message) + if first.kind() == TokenKind::Star + && message == "star import must be the only import" => + { + error.location.start() == first.start() + && error.location.end() <= import.range.end() + } + ParseErrorType::InvalidImportTarget(ExpressionKind::Name) => { + import.names.iter().any(|alias| { + let Some(name) = alias.asname.as_ref() else { + return false; + }; + if name.id.is_empty() + || error.location != name.range + || alias.range.end() != name.end() + { + return false; + } + let mut tokens = self.tokens_from(alias.name.end()); + tokens + .next() + .is_some_and(|token| token.kind() == TokenKind::As) + && tokens.next().is_some_and(|token| { + token.range() == name.range + && (token.kind() == TokenKind::Identifier + || token.kind().is_soft_keyword()) + }) + }) + } + _ => false, + } + } + + // The recovered AST supplies the aliases. Check only their terminal + // syntax, since Ruff can keep a node with a missing ')' or a trailing + // comma that the PEG action would never reach. + fn recovered_targets( + &self, + import: &ast::StmtImportFrom, + module_end: TextSize, + ) -> Option<(TextSize, Option)> { + let mut targets = self.tokens_from(module_end); + if targets.next()?.kind() != TokenKind::Import { + return None; + } + let first = targets.next()?; + let cutoff = self + .first_error + .filter(|&error| error > import.range.end()) + .or_else(|| { + self.errors + .iter() + .filter(|error| !self.recovered_target_diagnostic(error, import, first)) + .map(|error| error.location.start()) + .min() + }); + if cutoff.is_some_and(|error| error < first.end()) { + return None; + } + if first.kind() == TokenKind::Star { + return Some((first.end(), None)); + } + if first.kind() == TokenKind::Lpar { + let end = import.range.end(); + if cutoff.is_some_and(|error| error < end) { + return None; + } + let index = self.tokens.partition_point(|token| token.start() < end); + return self.tokens[..index] + .last() + .filter(|token| token.kind() == TokenKind::Rpar && token.end() == end) + .map(|_| (end, None)); + } + let alias = import.names.iter().rev().find(|alias| { + !alias.name.id.is_empty() && cutoff.is_none_or(|error| alias.name.end() <= error) + })?; + let asname = alias.asname.as_ref().filter(|name| { + !name.id.is_empty() && cutoff.is_none_or(|error| name.end() <= error) + }); + let end = asname.unwrap_or(&alias.name).end(); + let mut lookahead = self.tokens_from(end); + let mut next = lookahead.next()?; + if asname.is_none() && next.kind() == TokenKind::As { + // An optional malformed 'as NAME' leaves the name accepted, + // but the attempted NAME can already have been tokenized. + next = lookahead.next()?; + } else if next.kind() == TokenKind::Comma { + return None; + } + Some((end, Some(next.start()))) + } + + fn check(&self, import: &ast::StmtImportFrom) -> Option { + let module = import.module.as_ref()?; + if import.is_lazy + || import.level == 0 + || import.names.is_empty() + || module.id != "lazy" + || self + .first_error + .is_some_and(|error| error < module.range.end()) + { + return None; + } + let start = module.range.start(); + let index = self.tokens.partition_point(|token| token.start() < start); + let previous = self.tokens.get(index.checked_sub(1)?)?; + if !matches!(previous.kind(), TokenKind::Dot | TokenKind::Ellipsis) + || previous.end() >= start + { + return None; + } + let (end, lookahead) = if self.first_error.is_some() { + self.recovered_targets(import, module.range.end())? + } else { + (import.range.end(), None) + }; + // Finishing an unparenthesized name list needs lookahead. A + // tokenizer exception on that token stops the grammar action. + if let (Some(error), Some(lookahead)) = (self.tokenizer_error, lookahead) + && error <= lookahead + { + return None; + } + Some(RelativeLazyImportWarning { + module: module.range, + statement_end: end.to_usize(), + lookahead: lookahead.map(|offset| offset.to_usize()), + level: import.level, + }) + } + } + + struct EscapeWarningVisitor<'a, 'w> { source: &'a str, - filename: &'a str, - vm: &'a VirtualMachine, - error: Option, + warnings: &'w mut Vec, + relative_imports: Option>, + ast_only: bool, + interpolated_body_diagnostics: InterpolatedBodyDiagnostics, + diagnostic_index: core::cell::OnceCell, + interpolation_depth: usize, /// This pass runs before the compile that rejects an over-nested /// tree, so it has to stop itself. depth: usize, + statement_depth: usize, depth_limit: usize, } - impl<'a> EscapeWarningVisitor<'a> { - fn record_warning(&mut self, result: Result<(), CompileWarningError>) { - if self.error.is_none() - && let Err(err) = result - { - self.error = Some(err); - } - } - + impl<'a> EscapeWarningVisitor<'a, '_> { /// Check a quoted string/bytes literal for invalid escapes. /// The range must include the prefix and quote delimiters. fn check_quoted_literal(&mut self, range: TextRange, is_bytes: bool) { - if let Some((start, end)) = content_bounds(self.source, range) - && let Some(escape) = first_invalid_escape(self.source, start, end, is_bytes) + let previous_len = self.warnings.len(); + collect_quoted_literal_warning( + self.source, + range.start().to_usize(), + range.end().to_usize(), + is_bytes, + self.warnings, + ); + if !is_bytes + && self.warnings.len() != previous_len + && let InterpolatedBodyDiagnostics::TokenAnchored { + implicit_final_newline, + } = self.interpolated_body_diagnostics + && let Some(ParserWarning::Escape(escape, _, _, diagnostic)) = + self.warnings.last_mut() { - let result = - warn_invalid_escape_sequence(self.source, escape, self.filename, self.vm); - self.record_warning(result); + let index = self + .diagnostic_index + .get_or_init(|| SourceDiagnosticIndex::new(self.source)); + let line = index.lines.last().unwrap(); + if escape.offset() >= line.start && !line.terminated { + // Use one physical index for warning/error coordinates + // and final-line text, including bare CR. File input adds + // a final LF; eval/single leave this line unterminated. + // Keep existing LF/CRLF columns and source emission order. + let lineno = index.lines.len(); + let column = index.character_count(escape.offset()) + - index.character_count(line.start) + + 1; + *diagnostic = Some(EscapeDiagnosticLocation { + emission_offset: escape.offset(), + lineno, + offset: column, + end_offset: column + 2, + text_start: line.start, + text_end: line.end, + append_newline: implicit_final_newline, + }); + } } } @@ -1414,74 +2565,123 @@ mod escape_warnings { /// Also handles `\{` / `\}` at the literal–interpolation boundary, /// equivalent to `_PyTokenizer_warn_invalid_escape_sequence` handling /// `FSTRING_MIDDLE` / `FSTRING_END` tokens. - fn check_fstring_literal(&mut self, range: TextRange) { - let start = range.start().to_usize(); - let end = range.end().to_usize(); - if start >= end || end > self.source.len() { - return; - } - if let Some(escape) = first_invalid_escape(self.source, start, end, false) { - let result = - warn_invalid_escape_sequence(self.source, escape, self.filename, self.vm); - self.record_warning(result); - return; - } - // In CPython, _PyTokenizer_warn_invalid_escape_sequence handles - // `\{` and `\}` for FSTRING_MIDDLE/FSTRING_END tokens. Ruff - // splits the literal element before the interpolation delimiter, - // so the `\` sits at the end of the literal range and the `{`/`}` - // sits just after it. Only warn when the number of trailing - // backslashes is odd (an even count means they are all escaped). - let trailing_bs = self.source.as_bytes()[start..end] - .iter() - .rev() - .take_while(|&&b| b == b'\\') - .count(); - if trailing_bs % 2 == 1 - && let Some(&after) = self.source.as_bytes().get(end) - && (after == b'{' || after == b'}') + fn check_fstring_literal( + &mut self, + range: TextRange, + anchor: Option, + ) { + if let InterpolatedBodyDiagnostics::TokenAnchored { + implicit_final_newline, + } = self.interpolated_body_diagnostics { - let result = warn_invalid_escape_sequence( + collect_interpolated_tokenizer_warnings( self.source, - InvalidEscape::Char { - ch: after as char, - offset: end - 1, - }, - self.filename, - self.vm, + range.start().to_usize(), + range.end().to_usize(), + &self.diagnostic_index, + self.warnings, + ); + collect_interpolated_literal_warnings( + self.source, + range.start().to_usize(), + range.end().to_usize(), + anchor, + &self.diagnostic_index, + implicit_final_newline, + self.warnings, + ); + } else { + collect_fstring_literal_warning( + self.source, + range.start().to_usize(), + range.end().to_usize(), + self.warnings, + None, ); - self.record_warning(result); } } /// Visit f-string elements, checking literals and recursing into /// interpolation expressions and format specs. - fn visit_fstring_elements(&mut self, elements: &'a ast::InterpolatedStringElements) { + fn visit_fstring_elements( + &mut self, + elements: &'a ast::InterpolatedStringElements, + raw: bool, + anchor: Option, + ) { for element in elements { - if self.error.is_some() { - return; - } match element { ast::InterpolatedStringElement::Literal(lit) => { - self.check_fstring_literal(lit.range); + if !raw { + self.check_fstring_literal(lit.range, anchor); + } } ast::InterpolatedStringElement::Interpolation(interp) => { + self.interpolation_depth += 1; self.visit_expr(&interp.expression); if let Some(spec) = &interp.format_spec { - self.visit_fstring_elements(&spec.elements); + self.visit_fstring_elements(&spec.elements, raw, None); } + self.interpolation_depth -= 1; } } } } } - impl<'a> Visitor<'a> for EscapeWarningVisitor<'a> { + impl<'a> Visitor<'a> for EscapeWarningVisitor<'a, '_> { + fn visit_stmt(&mut self, stmt: &'a ast::Stmt) { + if let Some(imports) = &self.relative_imports { + if imports + .first_error + .is_some_and(|error| error < stmt.start()) + { + return; + } + if let ast::Stmt::ImportFrom(import) = stmt + && let Some(warning) = imports.check(import) + { + self.warnings + .push(ParserWarning::RelativeLazyImport(warning)); + } + } + if self.statement_depth < self.depth_limit { + self.statement_depth += 1; + ast::visitor::walk_stmt(self, stmt); + self.statement_depth -= 1; + } + } + fn visit_expr(&mut self, expr: &'a ast::Expr) { - if self.error.is_some() { + // On syntax errors, string escapes are recovered by the scanner; + // only the accepted import productions come from the partial AST. + if self + .relative_imports + .as_ref() + .is_some_and(|imports| imports.first_error.is_some()) + { return; } match expr { + ast::Expr::NumberLiteral(number) + if matches!( + self.interpolated_body_diagnostics, + InterpolatedBodyDiagnostics::TokenAnchored { .. } + ) => + { + let start = number.range.start().to_usize(); + let bytes = self.source.as_bytes(); + if let Some((kind, end)) = number_literal_end(bytes, start) + && numeric_keyword_suffix(&bytes[end..]) + { + self.warnings.push(ParserWarning::Numeric { + offset: start, + last_offset: end - 1, + message: format!("invalid {kind} literal"), + in_interpolation: self.interpolation_depth != 0, + }); + } + } // Regular string literals — decode_unicode_with_escapes path ast::Expr::StringLiteral(string) => { for part in string.value.as_slice() { @@ -1506,9 +2706,9 @@ mod escape_warnings { } // F-string literals — tokenizer + string_parser paths ast::Expr::FString(fstring_expr) => { - for part in fstring_expr.value.as_slice() { + for part in &fstring_expr.value { match part { - ast::FStringPart::Literal(string_lit) => { + ast::FStringPartRef::Literal(string_lit) => { // Plain string part in f-string concatenation if !matches!( string_lit.flags.prefix(), @@ -1517,18 +2717,36 @@ mod escape_warnings { self.check_quoted_literal(string_lit.range, false); } } - ast::FStringPart::FString(fstring) => { - if matches!( - fstring.flags.prefix(), - ast::str_prefix::FStringPrefix::Raw { .. } - ) { + ast::FStringPartRef::FString(fstring) => { + if !self.ast_only + && matches!( + fstring.flags.prefix(), + ast::str_prefix::FStringPrefix::Raw { .. } + ) + { continue; } - self.visit_fstring_elements(&fstring.elements); + self.visit_fstring_elements( + &fstring.elements, + matches!( + fstring.flags.prefix(), + ast::str_prefix::FStringPrefix::Raw { .. } + ), + interpolated_body_anchor(self.source, fstring.range), + ); } } } } + ast::Expr::TString(tstring) if self.ast_only => { + for part in tstring.value.as_slice() { + self.visit_fstring_elements( + &part.elements, + part.flags.prefix().is_raw(), + interpolated_body_anchor(self.source, part.range), + ); + } + } _ => { if self.depth < self.depth_limit { self.depth += 1; @@ -1540,55 +2758,716 @@ mod escape_warnings { } } + struct CollectedParserWarnings { + warnings: Vec, + tokenizer_recovery: bool, + has_valid_syntax: bool, + single_boundary: Option, + type_comment_error_offset: Option, + } + + impl CollectedParserWarnings { + fn has_relative_import(&self) -> bool { + self.warnings + .iter() + .any(|warning| matches!(warning, ParserWarning::RelativeLazyImport(_))) + } + } + + fn collect_parser_warnings( + source: &str, + filename: &str, + mode: Option, + inherited_barry_as_flufl: bool, + interpolated_body_diagnostics: InterpolatedBodyDiagnostics, + single_mode: bool, + type_comments: bool, + ) -> CollectedParserWarnings { + let mut ast_tokenizer_recovery = true; + let mut has_valid_syntax = false; + let mut single_boundary = None; + let mut type_comment_error_offset = None; + let mut warnings = Vec::new(); + collect_numeric_literal_warnings(source, &mut warnings); + // The compile that follows rejects this source; parsing it here + // would build a tree that exhausts the stack when dropped. + let source_file = compiler::core::SourceFileBuilder::new(filename, source).finish(); + if compiler::pre_parse_source_error(&source_file).is_ok() + && let Some(mode) = mode + { + let options = ruff_python_parser::ParseOptions::from(mode); + let barry_source = compiler::prepare_barry_as_flufl_source( + source, + options.clone(), + inherited_barry_as_flufl, + ); + let parsed = ruff_python_parser::parse_unchecked(barry_source.source(), options); + let first_error = parsed + .errors() + .iter() + .map(|error| error.location.start()) + .min(); + let tokenizer_error = parsed + .errors() + .iter() + .filter(|error| tokenizer_recovery_error(error)) + .min_by_key(|error| error.location.start()); + if single_mode { + single_boundary = compiler::single_mode_statement_boundary(&parsed); + } + if parsed.has_valid_syntax() { + has_valid_syntax = true; + if type_comments { + type_comment_error_offset = + crate::stdlib::_ast::invalid_type_comment_warning_boundary( + &source_file, + &parsed, + single_mode, + ); + } + if matches!( + interpolated_body_diagnostics, + InterpolatedBodyDiagnostics::TokenAnchored { .. } + ) { + // AST literal ranges include numbers inside interpolations + // without mistaking numeric-looking string contents for + // tokens. The text scanner remains the invalid-source path. + warnings.clear(); + } + } else { + ast_tokenizer_recovery = false; + // The tokenizer can read the token at which parsing fails, + // but later recovered statements were never parsed by + // CPython and must not produce string/parser warnings. + let end = parsed + .errors() + .iter() + // An unclosed-bracket diagnostic points back to its + // opening token, not where parsing stopped. Other + // errors retain that boundary; otherwise it was EOF. + .filter(|error| { + !matches!( + error.error, + ruff_python_parser::ParseErrorType::Lexical( + ruff_python_parser::LexicalErrorType::UnclosedBracket { .. } + ) + ) + }) + .min_by_key(|error| error.location.start()) + .map_or(source.len(), |error| { + // Tokens after a complete statement or eval + // expression were not decoded by CPython. + if matches!( + error.error, + ruff_python_parser::ParseErrorType::SimpleStatementsOnSameLine + | ruff_python_parser::ParseErrorType::UnexpectedExpressionToken + ) { + error.location.start().to_usize() + } else { + error.location.end().to_usize() + } + }); + collect_string_escape_warnings_in_range(source, 0, end, None, &mut warnings); + } + let mut visitor = EscapeWarningVisitor { + source, + warnings: &mut warnings, + relative_imports: Some(RelativeImportWarnings { + tokens: parsed.tokens(), + errors: parsed.errors(), + first_error, + tokenizer_error: tokenizer_error.map(|error| error.location.start()), + }), + ast_only: true, + interpolated_body_diagnostics, + diagnostic_index: core::cell::OnceCell::new(), + interpolation_depth: 0, + depth: 0, + statement_depth: 0, + depth_limit: compiler::CompileOpts::default().recursion_limit, + }; + match parsed.syntax() { + ast::Mod::Module(module) => { + for stmt in &module.body { + visitor.visit_stmt(stmt); + } + } + ast::Mod::Expression(expr) => visitor.visit_expr(&expr.body), + } + if let Some(error) = tokenizer_error + && warnings + .iter() + .any(|warning| matches!(warning, ParserWarning::RelativeLazyImport(_))) + { + let mode = if single_mode { + compiler::Mode::Single + } else if mode == ruff_python_parser::Mode::Expression { + compiler::Mode::Eval + } else { + compiler::Mode::Exec + }; + warnings.push(ParserWarning::TokenizerRecoveryError( + error.clone(), + mode, + is_inside_interpolation(parsed.tokens(), error.location.start()), + )); + } + } else if mode.is_none() && compiler::pre_parse_source_error(&source_file).is_ok() { + ast_tokenizer_recovery = false; + // Function-type input has a separate AST parser; its return + // expression follows an arrow that expression mode rejects. + // There are no import statements in this grammar. + collect_string_escape_warnings_in_range(source, 0, source.len(), None, &mut warnings); + } + // Stable ordering retains fragment order for constants decoded by the + // same END token. Source offsets remain separate for input boundaries. + warnings.sort_by_key(ParserWarning::emission_offset); + // The legacy scanner cannot reconstruct separate tokenizer/parser + // events. Token-anchored collection preserves both phases instead. + if interpolated_body_diagnostics == InterpolatedBodyDiagnostics::Legacy + && warnings.iter().any(|warning| { + matches!( + warning, + ParserWarning::Escape(_, EscapeOrigin::Tokenizer, ..) + ) + }) + { + ast_tokenizer_recovery = false; + } + CollectedParserWarnings { + warnings, + tokenizer_recovery: ast_tokenizer_recovery, + has_valid_syntax, + single_boundary, + type_comment_error_offset, + } + } + + #[derive(Default)] + pub(super) struct AstParserWarningOptions { + pub(super) inherited_barry_as_flufl: bool, + pub(super) type_comments: bool, + pub(super) require_relative_import: bool, + } + + #[derive(Default)] + struct ParserWarningBoundaries { + single: Option, + type_comment_error_offset: Option, + } + + enum WarningEmission<'a> { + Standard { + emitted_escapes: &'a [usize], + tokenizer_recovery: bool, + original_filename: &'a Py, + }, + Ast { + tokenizer_recovery: bool, + original_filename: Option<&'a Py>, + }, + Interactive(&'a mut super::InteractiveWarnings), + } + impl VirtualMachine { - /// Emit tokenizer-level SyntaxWarnings raised before - /// code generation. + pub(super) fn emit_standard_parser_warnings( + &self, + source: &str, + original_filename: &Py, + module: Option<&PyObject>, + mode: compiler::Mode, + inherited_barry_as_flufl: bool, + emitted_escapes: &[usize], + ) -> Result<(), CompileWarningError> { + let filename = original_filename.to_string_lossy(); + let filename = filename.as_ref(); + let implicit_final_newline = matches!(mode, compiler::Mode::Exec); + let is_single = matches!(mode, compiler::Mode::Single); + let mode = match mode { + compiler::Mode::Eval => ruff_python_parser::Mode::Expression, + compiler::Mode::Exec | compiler::Mode::Single | compiler::Mode::BlockExpr => { + ruff_python_parser::Mode::Module + } + }; + let collected = collect_parser_warnings( + source, + filename, + Some(mode), + inherited_barry_as_flufl, + InterpolatedBodyDiagnostics::TokenAnchored { + implicit_final_newline, + }, + is_single, + false, + ); + if !collected.has_valid_syntax && !collected.has_relative_import() { + // Invalid source still needs the legacy recovery contract; + // a valid mixed batch already has separate tokenizer events. + self.emit_tokenizer_syntax_warnings(source, original_filename, module)?; + return self.emit_string_escape_warnings( + source, + original_filename, + module, + emitted_escapes, + ); + } + self.emit_parser_warning_batch( + source, + filename, + module, + collected.warnings, + ParserWarningBoundaries { + single: collected.single_boundary, + type_comment_error_offset: None, + }, + WarningEmission::Standard { + emitted_escapes, + tokenizer_recovery: true, + original_filename, + }, + ) + .map(|_| ()) + } + + // Preserve the existing invalid-source warning order and recovery surface. pub(super) fn emit_tokenizer_syntax_warnings( &self, source: &str, - filename: &str, + original_filename: &Py, + module: Option<&PyObject>, ) -> Result<(), CompileWarningError> { - emit_numeric_literal_warnings(source, filename, self) + let filename = original_filename.to_string_lossy(); + let filename = filename.as_ref(); + let mut warnings = Vec::new(); + collect_numeric_literal_warnings(source, &mut warnings); + self.emit_parser_warning_batch( + source, + filename, + module, + warnings, + ParserWarningBoundaries::default(), + WarningEmission::Standard { + emitted_escapes: &[], + tokenizer_recovery: false, + original_filename, + }, + ) + .map(|_| ()) } - /// Walk all string literals in `source` and emit `SyntaxWarning` for - /// each that contains an invalid escape sequence. pub(super) fn emit_string_escape_warnings( &self, source: &str, - filename: &str, + original_filename: &Py, + module: Option<&PyObject>, + emitted_escapes: &[usize], ) -> Result<(), CompileWarningError> { - // The compile that follows rejects this source; parsing it here - // would build a tree that exhausts the stack when dropped. + let filename = original_filename.to_string_lossy(); + let filename = filename.as_ref(); let source_file = compiler::core::SourceFileBuilder::new(filename, source).finish(); if compiler::pre_parse_source_error(&source_file).is_err() { return Ok(()); } - let Ok(parsed) = + let mut warnings = Vec::new(); + if let Ok(parsed) = ruff_python_parser::parse(source, ruff_python_parser::Mode::Module.into()) - else { - return emit_string_escape_warnings_unparsed(source, filename, self); - }; - let ast = parsed.into_syntax(); - let mut visitor = EscapeWarningVisitor { + { + let mut visitor = EscapeWarningVisitor { + source, + warnings: &mut warnings, + relative_imports: None, + ast_only: false, + interpolated_body_diagnostics: InterpolatedBodyDiagnostics::Legacy, + diagnostic_index: core::cell::OnceCell::new(), + interpolation_depth: 0, + depth: 0, + statement_depth: 0, + depth_limit: compiler::CompileOpts::default().recursion_limit, + }; + match parsed.syntax() { + ast::Mod::Module(module) => { + for stmt in &module.body { + visitor.visit_stmt(stmt); + } + } + ast::Mod::Expression(expr) => visitor.visit_expr(&expr.body), + } + } else { + collect_string_escape_warnings_in_range( + source, + 0, + source.len(), + None, + &mut warnings, + ); + } + self.emit_parser_warning_batch( source, filename, - vm: self, - error: None, - depth: 0, - depth_limit: compiler::CompileOpts::default().recursion_limit, + module, + warnings, + ParserWarningBoundaries::default(), + WarningEmission::Standard { + emitted_escapes, + tokenizer_recovery: false, + original_filename, + }, + ) + .map(|_| ()) + } + + pub(super) fn emit_ast_parser_warnings( + &self, + source: &str, + filename: &str, + original_filename: Option<&Py>, + module: Option<&Py>, + start: CompileStart, + options: AstParserWarningOptions, + ) -> Result, CompileWarningError> { + let mode = match start { + CompileStart::Single | CompileStart::File => Some(ruff_python_parser::Mode::Module), + CompileStart::Eval => Some(ruff_python_parser::Mode::Expression), + CompileStart::FuncType => None, }; - match &ast { - ast::Mod::Module(module) => { - for stmt in &module.body { - visitor.visit_stmt(stmt); + let collected = collect_parser_warnings( + source, + filename, + mode, + options.inherited_barry_as_flufl, + InterpolatedBodyDiagnostics::TokenAnchored { + implicit_final_newline: matches!(start, CompileStart::File), + }, + matches!(start, CompileStart::Single), + options.type_comments, + ); + let has_relative_import = collected.has_relative_import(); + if options.require_relative_import && !has_relative_import { + return Ok(Vec::new()); + } + let tokenizer_recovery = collected.tokenizer_recovery || has_relative_import; + let single = collected.single_boundary.filter(|_| tokenizer_recovery); + self.emit_parser_warning_batch( + source, + filename, + module.map(AsObject::as_object), + collected.warnings, + ParserWarningBoundaries { + single, + type_comment_error_offset: collected.type_comment_error_offset, + }, + WarningEmission::Ast { + // Unlike an interactive prompt, Single compile input recovers + // after a parser warning becomes an error. Later numeric + // tokenizer warnings raised as errors still take precedence, + // including on a following logical line. + tokenizer_recovery: tokenizer_recovery + && matches!( + start, + CompileStart::File | CompileStart::Eval | CompileStart::Single + ), + original_filename, + }, + ) + } + + /// Emit the tokenizer warnings for the interactive input read so far. + pub(in crate::vm) fn emit_interactive_parser_warnings( + &self, + source: &str, + filename: &str, + module: Option<&Py>, + inherited_barry_as_flufl: bool, + emitted: &mut super::InteractiveWarnings, + ) -> Result<(), CompileWarningError> { + let collected = collect_parser_warnings( + source, + filename, + Some(ruff_python_parser::Mode::Module), + inherited_barry_as_flufl, + InterpolatedBodyDiagnostics::Legacy, + false, + false, + ); + self.emit_parser_warning_batch( + source, + filename, + module.map(AsObject::as_object), + collected.warnings, + ParserWarningBoundaries::default(), + WarningEmission::Interactive(emitted), + ) + .map(|_| ()) + } + + fn emit_parser_warning_batch( + &self, + source: &str, + filename: &str, + module: Option<&PyObject>, + warnings: Vec, + boundaries: ParserWarningBoundaries, + emission: WarningEmission<'_>, + ) -> Result, CompileWarningError> { + let ParserWarningBoundaries { + single: single_boundary, + type_comment_error_offset, + } = boundaries; + let (emitted_escapes, ast_tokenizer_recovery, original_filename, mut interactive) = + match emission { + WarningEmission::Standard { + emitted_escapes, + tokenizer_recovery, + original_filename, + } => ( + emitted_escapes, + tokenizer_recovery, + Some(original_filename), + None, + ), + WarningEmission::Ast { + tokenizer_recovery, + original_filename, + } => (&[][..], tokenizer_recovery, original_filename, None), + WarningEmission::Interactive(emitted) => (&[][..], false, None, Some(emitted)), + }; + let mut considered_escapes = alloc::collections::BTreeSet::new(); + let mut parser_error: Option = None; + for warning in warnings { + let pending_error_interpolated_tokenizer = (type_comment_error_offset + .is_some_and(|offset| warning.offset() >= offset) + || matches!( + single_boundary, + Some(compiler::SingleModeStatementBoundary::Compound { end }) + if warning.offset() >= end.to_usize() + )) + && matches!( + &warning, + ParserWarning::Escape(_, EscapeOrigin::Tokenizer, _, Some(_)) + | ParserWarning::Numeric { + in_interpolation: true, + .. + } + ); + // A successful single input does not parse later statements. + // Keep those numeric events for recovery after an earlier + // parser warning escalates, rather than truncating the source. + if parser_error.is_none() + && type_comment_error_offset.is_none() + && let Some(boundary) = single_boundary + { + let end = match (boundary, &warning) { + (compiler::SingleModeStatementBoundary::Simple { end, .. }, _) => Some(end), + (compiler::SingleModeStatementBoundary::Compound { end }, warning) + if warning.is_parser_origin() => + { + Some(end) + } + // Compound input requests another token and can emit + // tokenizer warnings while rejecting the next statement. + _ => None, + }; + if end.is_some_and(|end| warning.offset() >= end.to_usize()) { + continue; + } + } + // CPython resumes tokenization after a parser-origin SyntaxError. + // Preserve ordinary warning order and never replay prior warnings. + if (parser_error.is_some() + || type_comment_error_offset + .is_some_and(|offset| warning.type_comment_boundary_offset() >= offset)) + && warning.is_parser_origin() + { + continue; + } + if let Some(state) = interactive.as_deref_mut() { + let message = match &warning { + ParserWarning::TokenizerRecoveryError(..) => break, + ParserWarning::Escape(escape, ..) => escape.warning_message(), + ParserWarning::Numeric { message, .. } => message.clone(), + ParserWarning::RelativeLazyImport(import) => import.message(), + }; + if !state.emitted.insert((warning.offset(), message)) { + continue; } } - ast::Mod::Expression(expr) => { - visitor.visit_expr(&expr.body); + match warning { + ParserWarning::TokenizerRecoveryError(error, mode, in_interpolation) => { + if !in_interpolation && let Some(mut pending) = parser_error.take() { + let source_file = + compiler::core::SourceFileBuilder::new(filename, source).finish(); + let error = + CompileError::from_ruff_parse_error(error, &source_file, mode); + pending.exception = self.new_syntax_error_with_filename( + &error, + Some(source), + false, + original_filename, + ); + return Err(pending); + } + break; + } + ParserWarning::RelativeLazyImport(import) => { + let message = import.message(); + let start = import.module.start().to_usize(); + if let Err(mut error) = warn_syntax_at_offset( + source, + filename, + original_filename, + module, + start, + message.clone(), + self, + ) { + if !error + .exception + .fast_isinstance(self.ctx.exceptions.syntax_warning) + { + return Err(error); + } + // Grammar actions use UTF-8 byte columns and load the + // diagnostic's line from the named file, if it exists. + let line_start = + source[..start].rfind(['\r', '\n']).map_or(0, |i| i + 1); + let filename = original_filename + .map_or_else(|| self.ctx.new_str(filename), ToOwned::to_owned); + let text = self + .fsencode(&filename) + .ok() + .and_then(|path| { + self.program_text_with_newlines(path, error.lineno, true) + }) + .map_or_else( + || self.ctx.none(), + |text| self.ctx.new_str(text).into(), + ); + let line = self.ctx.new_int(error.lineno); + let location = self.ctx.new_tuple(vec![ + filename.into(), + line.clone().into(), + self.ctx.new_int(start - line_start + 1).into(), + text, + line.into(), + self.ctx + .new_int(import.module.end().to_usize() - line_start + 1) + .into(), + ]); + error.exception = self.new_exception( + self.ctx.exceptions.syntax_error.to_owned(), + vec![self.ctx.new_str(message).into(), location.into()], + ); + if interactive.is_some() { + return Err(error); + } + parser_error = Some(error); + } + } + ParserWarning::Escape(escape, origin, error_column, diagnostic) => { + let offset = escape.offset(); + if !considered_escapes.insert(offset) { + continue; + } + if emitted_escapes.binary_search(&offset).is_err() { + let result = warn_invalid_escape_sequence_at( + source, + escape, + filename, + original_filename, + module, + diagnostic, + self, + ) + .map_err(|mut error| { + if let Some(column) = error_column { + error.offset = column; + if let Some(replacement) = &mut error.replacement { + replacement.end_offset = column + 2; + } + } + error + }); + if let Err(error) = result { + if ast_tokenizer_recovery + && origin == EscapeOrigin::Parser + && error + .exception + .fast_isinstance(self.ctx.exceptions.syntax_warning) + { + parser_error = Some(error); + } else if origin == EscapeOrigin::Tokenizer + && let Some(parser_error) = parser_error.take() + { + // _PyPegen_tokenize_full_source preserves + // the original parser error if recovery + // fails while inside an interpolated string. + return Err(parser_error); + } else if pending_error_interpolated_tokenizer { + // Single or TYPE_COMMENT validation already + // failed. Recovery invokes the warning, but + // an error inside that string must preserve + // the pending syntax error. Stop here and + // let the following validation report it. + break; + } else { + return Err(error); + } + } + } + } + ParserWarning::Numeric { + last_offset, + message, + in_interpolation, + .. + } => { + let result = warn_syntax_at_offset( + source, + filename, + original_filename, + module, + last_offset, + message.clone(), + self, + ) + .map_err(|mut error| { + // Tokenizer numeric warnings become a zero-width + // error at the literal's last character, in character + // columns rather than grammar-action byte columns. + error.replacement = Some(SyntaxErrorReplacement { + message, + end_offset: error.offset, + }); + // helpers.c:_syntaxerror_range uses the physical + // tokenizer line without its terminating LF in + // every compile mode, not only interactive input. + let line_start = source[..last_offset] + .rfind(['\r', '\n']) + .map_or(0, |index| index + 1); + let line_end = source[last_offset..] + .find(['\r', '\n']) + .map_or(source.len(), |index| last_offset + index); + error.diagnostic_text = Some(source[line_start..line_end].to_owned()); + error + }); + if let Err(error) = result { + if in_interpolation && let Some(parser_error) = parser_error.take() { + return Err(parser_error); + } + if pending_error_interpolated_tokenizer { + break; + } + return Err(error); + } + } } } - visitor.error.map_or(Ok(()), Err) + if let Some(error) = parser_error { + return Err(error); + } + // AST warning callbacks use binary search on these source offsets, + // which need not be emitted in source order. + Ok(considered_escapes.into_iter().collect()) } } diff --git a/crates/vm/src/vm/context.rs b/crates/vm/src/vm/context.rs index 78e6bc6fef8..e0547451d34 100644 --- a/crates/vm/src/vm/context.rs +++ b/crates/vm/src/vm/context.rs @@ -356,12 +356,12 @@ impl Context { let names = unsafe { ConstName::new(&string_pool, types.str_type) }; - let slot_new_wrapper = PyMethodDef::new_const( + let slot_new_wrapper = PyMethodDef::new_method_const( names.__new__.as_str(), PyType::__new__, PyMethodFlags::METHOD, ItemDoc::static_text( - "__new__($type, /, *args, **kwargs)\n--\n\nCreate and return a new object. See help(type) for accurate signature.", + "__new__($type, *args, **kwargs)\n--\n\nCreate and return a new object. See help(type) for accurate signature.", ), ); let empty_str = unsafe { string_pool.intern("", types.str_type.to_owned()) }; @@ -508,7 +508,7 @@ impl Context { } #[inline] - fn latin1_singleton_index(s: &PyStr) -> Option { + pub(crate) fn latin1_singleton_index(s: &PyStr) -> Option { let mut cps = s.as_wtf8().code_points(); let cp = cps.next()?; @@ -659,19 +659,23 @@ impl Context { where F: IntoPyNativeFn, { - let def = PyMethodDef { + let payload = HeapMethodDef::with_owned_function( name, - func: Box::leak(Box::new(f.into_func())), - flags, - #[cfg(feature = "doc")] - doc_off: doc.offset, - #[cfg(feature = "doc")] - doc_len: doc.len, - #[cfg(feature = "doc")] - doc_body_pending: false, - doc: doc.text, - }; - let payload = HeapMethodDef::new(def); + Box::new(f.into_func()), + flags.with_call_convention(F::ARGS), + doc, + ); + PyRef::new_ref(payload, self.types.method_def.to_owned(), None) + } + + pub fn new_raw_method_def( + &self, + name: &'static str, + f: impl crate::function::PyNativeFn, + flags: PyMethodFlags, + doc: ItemDoc, + ) -> PyRef { + let payload = HeapMethodDef::with_owned_function(name, Box::new(f), flags, doc); PyRef::new_ref(payload, self.types.method_def.to_owned(), None) } diff --git a/crates/vm/src/vm/crossinterp.rs b/crates/vm/src/vm/crossinterp.rs index 2b799bf0031..a9144eafc82 100644 --- a/crates/vm/src/vm/crossinterp.rs +++ b/crates/vm/src/vm/crossinterp.rs @@ -2,7 +2,7 @@ //! //! Interpreters do not share `PyObject` graphs. Shareable values are converted //! to an interpreter-neutral payload and rebuilt in the destination. -// cspell:ignore unpickler +// cspell:ignore unpickler unmarshalled #[cfg(not(feature = "threading"))] use crate::protocol::BufferDescriptor; @@ -14,12 +14,15 @@ use crate::{ PyMemoryView, PyStr, PyStrInterned, PyTuple, }, bytecode::{ - BorrowedConstant, CodeFlags, Constant, Instruction, - oparg::{OpArg, OpArgState}, + CodeFlags, Instruction, + oparg::{CommonConstant, OpArg, OpArgState}, }, protocol::PyBuffer, }; -use core::sync::atomic::{AtomicBool, Ordering}; +use core::{ + borrow::Borrow, + sync::atomic::{AtomicBool, Ordering}, +}; use num_traits::ToPrimitive; use rustpython_common::wtf8::Wtf8Buf; @@ -227,7 +230,7 @@ impl SharedValue { t.as_slice() .iter() .map(|item| { - vm.with_recursion("while sharing a tuple", || { + vm.with_recursion(" while sharing a tuple", || { Self::from_object(item, fallback, vm) }) }) @@ -340,7 +343,7 @@ impl SharedValue { // Stateless functions have no globals, so `__main__` is used, // just like for builtins such as exec(). let globals = vm.main_namespace()?; - Ok(PyFunction::new(code, globals, vm)?.into_pyobject(vm)) + Ok(PyFunction::new(code, globals.into(), vm)?.into_pyobject(vm)) } Self::Pickled(data) => pickle_loads(&data, vm), } @@ -348,17 +351,23 @@ impl SharedValue { } fn marshal_dumps(obj: &PyObject, vm: &VirtualMachine) -> PyResult> { - let dumps = vm.import("marshal", 0)?.get_attr("dumps", vm)?; - let bytes = dumps.call((obj.to_owned(),), vm)?; - let bytes = bytes - .downcast::() - .map_err(|_| vm.new_type_error("marshal.dumps() did not return bytes"))?; - Ok(bytes.as_bytes().to_vec()) + let dump = || -> PyResult> { + let dumps = vm.import("marshal", 0)?.get_attr("dumps", vm)?; + let bytes = dumps.call((obj.to_owned(),), vm)?; + let bytes = bytes + .downcast::() + .map_err(|_| vm.new_type_error("marshal.dumps() did not return bytes"))?; + Ok(bytes.as_bytes().to_vec()) + }; + dump().map_err(|cause| not_shareable_error_from(vm, "object could not be marshalled", cause)) } fn marshal_loads(data: &[u8], vm: &VirtualMachine) -> PyResult { - let loads = vm.import("marshal", 0)?.get_attr("loads", vm)?; - loads.call((vm.ctx.new_bytes(data.to_vec()),), vm) + let load = || -> PyResult { + let loads = vm.import("marshal", 0)?.get_attr("loads", vm)?; + loads.call((vm.ctx.new_bytes(data.to_vec()),), vm) + }; + load().map_err(|cause| not_shareable_error_from(vm, "object could not be unmarshalled", cause)) } /// `_memoryview_from_xid`. @@ -420,7 +429,7 @@ fn pickle_loads(data: &PickledData, vm: &VirtualMachine) -> PyResult { let original = unpickler.get_attr("find_class", vm)?; let state = vm.ctx.new_tuple(vec![isolated, original]); const FIND_CLASS: crate::function::PyMethodDef = - crate::function::PyMethodDef::new_const( + crate::function::PyMethodDef::new_method_const( "find_class", find_main_class, crate::function::PyMethodFlags::empty(), @@ -505,7 +514,7 @@ fn isolated_main(mainfile: &str, vm: &VirtualMachine) -> PyResult { let namespace = run_path.call((mainfile, vm.ctx.none(), ""), vm)?; loaded.dict().merge_object(namespace, vm)?; // The native module owns this cache so normal module teardown releases it. - state.setdefault(vm.ctx.new_str("_cached_main").into(), loaded.into(), vm) + state.setdefault_value(vm.ctx.new_str("_cached_main").into(), loaded.into(), vm) } fn not_shareable_error(vm: &VirtualMachine, msg: impl Into) -> PyBaseExceptionRef { @@ -733,7 +742,7 @@ fn verify_stateless( /// The `co_names` entries `identify_unbound_names` reaches through `LOAD_GLOBAL`. pub(crate) fn global_names(code: &Py) -> impl Iterator + '_ { walk_instructions(code).filter_map(|(_, instr, arg)| match instr { - Instruction::LoadGlobal { namei } => Some(code.names[(namei.get(arg) >> 1) as usize]), + Instruction::LoadGlobal { namei } => Some(code.names[namei.get(arg).name_idx()]), _ => None, }) } @@ -763,20 +772,22 @@ pub(crate) fn walk_instructions( /// `_PyFunction_VerifyStateless`. fn verify_stateless_function(func: &Py, vm: &VirtualMachine) -> PyResult<()> { - // `__globals__` is a dict by construction, so only the builtins are checked. + let globals = func.globals.as_mutable().ok_or_else(|| { + vm.new_type_error(format!( + "unsupported globals {}", + render_repr(func.globals.as_object(), vm) + )) + })?; let builtins = func.builtins.downcast_ref::().ok_or_else(|| { vm.new_type_error(format!( "unsupported builtins {}", render_repr(&func.builtins, vm) )) })?; - if func - .__defaults__() - .is_some_and(|d| !d.as_slice().is_empty()) - { + if func.defaults().is_some_and(|d| !d.as_slice().is_empty()) { return Err(vm.new_value_error("defaults not supported")); } - if func.__kwdefaults__().is_some_and(|d| !d.is_empty()) { + if func.kwdefaults().is_some_and(|d| !d.is_empty()) { return Err(vm.new_value_error("keyword defaults not supported")); } if func @@ -786,7 +797,7 @@ fn verify_stateless_function(func: &Py, vm: &VirtualMachine) -> PyRe { return Err(vm.new_value_error("closures not supported")); } - verify_stateless(&func.code, Some((&func.globals, builtins)), vm) + verify_stateless(&func.code, Some((globals, builtins)), vm) } /// `verify_script`: a script takes no arguments and returns only None. @@ -823,53 +834,41 @@ pub(crate) fn code_returns_only_none(code: &Py) -> bool { if !is_pure_function(code) { return false; } - let units = &code.instructions; - let Some(last) = units.len().checked_sub(1) else { - return true; - }; - // The last instruction either returns or raises. We can take advantage - // of that for a quick exit. - let final_op = units.read_op(last).deoptimize(); - - // Look up None in co_consts. - let Some(none_index) = code - .constants - .iter() - .position(|c| matches!(c.borrow_constant(), BorrowedConstant::None)) - else { - // None wasn't there, which means there was no implicit return, - // "return", or "return None". - - // That means there must be an explicit return (non-None), or it only - // raises. - if matches!(final_op, Instruction::ReturnValue) { - // It was an explicit return (non-None). - return false; - } - // It must end with a raise then. We still have to walk the bytecode - // to see if there's any explicit return (non-None). - return !walk_instructions(code).any(|(_, op, _)| matches!(op, Instruction::ReturnValue)); - }; - // Walk the bytecode, looking for RETURN_VALUE. - for (at, op, _) in walk_instructions(code) { - if !matches!(op, Instruction::ReturnValue) { + let mut previous_loads_none = false; + for (_, instruction, arg) in walk_instructions(code) { + if matches!(instruction, Instruction::ExtendedArg) { continue; } - // Ignore it if it returns None. - if let Some(prev) = at.checked_sub(1) - && matches!(units.read_op(prev).deoptimize(), Instruction::LoadConst { .. }) - // We don't worry about EXTENDED_ARG for now. - && usize::from(u8::from(units.read_arg(prev))) == none_index - { - continue; + if matches!(instruction, Instruction::ReturnValue) && !previous_loads_none { + return false; } - return false; + previous_loads_none = match instruction { + Instruction::LoadCommonConstant { idx } => { + matches!(idx.try_get(arg), Ok(CommonConstant::None)) + } + Instruction::LoadConst { consti } => code + .constants + .get(consti.get(arg).as_usize()) + .is_some_and(|constant| { + let object: &PyObject = constant.borrow(); + object.is(&crate::Context::genesis().none) + }), + _ => false, + }; } true } /// Extract a script code object from source text / function / code object. pub fn script_code(obj: &PyObject, vm: &VirtualMachine) -> PyResult> { + script_code_with_purity(obj, false, vm) +} + +fn script_code_with_purity( + obj: &PyObject, + pure: bool, + vm: &VirtualMachine, +) -> PyResult> { let code = if let Ok(code) = obj.to_owned().downcast::() { code } else if let Some(func) = obj.downcast_ref::() { @@ -888,6 +887,22 @@ pub fn script_code(obj: &PyObject, vm: &VirtualMachine) -> PyResult() { + verify_stateless_function(func, vm)?; + } else { + let builtins = + crate::frame::current_builtins().unwrap_or_else(|| vm.builtins.dict().into()); + let builtins = builtins.downcast_ref::().ok_or_else(|| { + vm.new_type_error(format!( + "unsupported builtins {}", + render_repr(&builtins, vm) + )) + })?; + let globals = vm.ctx.new_dict(); + verify_stateless(&code, Some((&globals, builtins)), vm)?; + } + } verify_script(&code, vm)?; Ok(code) } @@ -943,16 +958,7 @@ where )); } - if state - .running_main - .compare_exchange( - false, - true, - core::sync::atomic::Ordering::AcqRel, - core::sync::atomic::Ordering::Acquire, - ) - .is_err() - { + if !state.set_running_main() { return Err(crate::stdlib::_interpreters::interpreter_error( caller, "interpreter already running", @@ -962,20 +968,20 @@ where struct RunningGuard<'a>(&'a crate::vm::PyGlobalState); impl Drop for RunningGuard<'_> { fn drop(&mut self) { - self.0 - .running_main - .store(false, core::sync::atomic::Ordering::Release); + self.0.set_not_running_main(); } } let _guard = RunningGuard(&state); - let tvm = crate::vm::runtime::owned_new_thread(id) + let tvm = crate::vm::runtime::new_interpreter_thread(id) .ok_or_else(|| crate::stdlib::_interpreters::interpreter_not_found(caller, id))?; tvm.run(f) } #[must_use] pub fn is_running(id: i64) -> bool { - crate::vm::runtime::lookup_interpreter(id) - .is_some_and(|s| s.is_main || s.running_main.load(core::sync::atomic::Ordering::Acquire)) + crate::vm::runtime::lookup_interpreter(id).is_some_and(|s| s.is_running_main()) } + +// Bridges for canonical _testinternalcapi cross-interpreter tests. +pub(crate) mod test_support; diff --git a/crates/vm/src/vm/crossinterp/test_support.rs b/crates/vm/src/vm/crossinterp/test_support.rs new file mode 100644 index 00000000000..425eaae97e2 --- /dev/null +++ b/crates/vm/src/vm/crossinterp/test_support.rs @@ -0,0 +1,74 @@ +//! Serialization modes exposed only by the canonical cross-interpreter test hooks. +//! Keep fixture-specific modes out of the production SharedValue representation. + +use super::*; +use crate::builtins::PyUtf8Str; + +#[derive(Clone)] +pub(crate) enum CrossinterpData { + Shared(SharedValue), + Marshalled(Vec), +} + +impl CrossinterpData { + pub(crate) fn from_object( + obj: &PyObject, + mode: Option<&PyObject>, + vm: &VirtualMachine, + ) -> PyResult { + let mode_obj = mode.filter(|mode| !vm.is_none(mode)); + let mode = match mode_obj { + None => "xidata", + Some(mode) => { + if !mode.downcastable::() { + return Err( + vm.new_type_error(format!("expected mode str, got {}", mode.repr(vm)?)) + ); + } + // CPython compares a NUL-terminated UTF-8 string. + mode.try_downcast_ref::(vm)? + .as_str() + .split('\0') + .next() + .unwrap_or_default() + } + }; + let data = match mode { + "" | "xidata" => SharedValue::from_object(obj, Fallback::XidataOnly, vm), + "fallback" => SharedValue::from_object(obj, Fallback::Full, vm), + "pickle" => pickle_dumps(obj, vm) + .map(SharedValue::Pickled) + .map_err(|cause| { + not_shareable_error_from(vm, "object could not be pickled", cause) + }), + "marshal" => return marshal_dumps(obj, vm).map(Self::Marshalled), + "code" => { + let code = obj.downcast_ref::().ok_or_else(|| { + not_shareable_error(vm, format!("expected code, got {}", render_repr(obj, vm))) + })?; + SharedValue::from_code(code, vm) + } + "func" => SharedValue::from_function(obj, vm), + "script" | "script-pure" => { + let code = + script_code_with_purity(obj, mode == "script-pure", vm).map_err(|cause| { + not_shareable_error_from(vm, "object not a valid script", cause) + })?; + SharedValue::from_code(&code, vm) + } + _ => { + return Err( + vm.new_value_error(format!("unsupported mode {}", mode_obj.unwrap().repr(vm)?)) + ); + } + }?; + Ok(Self::Shared(data)) + } + + pub(crate) fn into_object(self, vm: &VirtualMachine) -> PyResult { + match self { + Self::Shared(data) => data.into_object(vm), + Self::Marshalled(data) => marshal_loads(&data, vm), + } + } +} diff --git a/crates/vm/src/vm/filesystem.rs b/crates/vm/src/vm/filesystem.rs new file mode 100644 index 00000000000..3774e5943a7 --- /dev/null +++ b/crates/vm/src/vm/filesystem.rs @@ -0,0 +1,236 @@ +use super::{Settings, VirtualMachine}; +use crate::{ + AsObject, Py, PyResult, + builtins::{PyStr, PyStrInterned, PyStrRef, PyUtf8Str, PyUtf8StrInterned}, + codecs::FastCodec, +}; +use alloc::borrow::Cow; +use core::sync::atomic::Ordering; +use std::{ + ffi::{OsStr, OsString}, + sync::OnceLock, +}; + +/// The filesystem codec belongs to the interpreter configuration, not LC_CTYPE. +/// Subinterpreters share this snapshot, but initialize their own codec registry. +pub(super) struct FilesystemCodec { + encoding: String, + error: Option, + canonical_name: OnceLock, + #[cfg(all(feature = "host_env", target_os = "linux", target_env = "gnu"))] + locale: Result, +} + +impl FilesystemCodec { + pub(super) fn new(settings: &Settings) -> Self { + #[cfg(all(feature = "host_env", target_os = "linux", target_env = "gnu"))] + let locale = rustpython_host_env::locale::LocaleSnapshot::capture() + .map_err(|error| error.to_string()); + #[allow(unused_mut)] + let mut error = None; + let encoding = (|| { + if cfg!(windows) && settings.legacy_windows_fs_encoding { + return "mbcs".to_owned(); + } + // CPython 3.15 enables UTF-8 mode by default. These platforms use + // UTF-8 for filesystem paths independently of the UTF-8 mode flag. + if settings.utf8_mode != 0 + || cfg!(any( + windows, + target_vendor = "apple", + target_os = "android", + target_os = "vxworks" + )) + || !cfg!(feature = "host_env") + { + return "utf-8".to_owned(); + } + #[cfg(all(feature = "host_env", target_os = "linux", target_env = "gnu"))] + match &locale { + Ok(locale) => return locale.encoding().to_owned(), + Err(message) => error = Some(message.clone()), + } + #[cfg(all(feature = "host_env", target_os = "linux", not(target_env = "gnu")))] + if let Some(encoding) = rustpython_host_env::locale::nl_langinfo_codeset() + .and_then(|name| String::from_utf8(name).ok()) + .filter(|name| !name.is_empty()) + { + // Other Linux libc targets have no native bootstrap snapshot + // yet. Keep their existing UTF-8 behavior for wider codecs. + if FastCodec::classify(&encoding).is_some() { + return encoding; + } + } + "utf-8".to_owned() + })(); + // Native aliases must also be usable before encodings is imported. + let encoding = + FastCodec::classify(&encoding).map_or(encoding, |codec| codec.name().to_owned()); + Self { + encoding, + error, + canonical_name: OnceLock::new(), + #[cfg(all(feature = "host_env", target_os = "linux", target_env = "gnu"))] + locale, + } + } + + fn encoding(&self) -> &str { + self.canonical_name.get().unwrap_or(&self.encoding) + } +} + +impl VirtualMachine { + pub fn fs_encoding(&self) -> &'static PyStrInterned { + self.ctx.intern_str(self.state.config.filesystem.encoding()) + } + + pub fn fs_encode_errors(&self) -> &'static PyUtf8StrInterned { + if cfg!(windows) { + if self.state.config.settings.legacy_windows_fs_encoding { + return identifier_utf8!(self, replace); + } + identifier_utf8!(self, surrogatepass) + } else { + identifier_utf8!(self, surrogateescape) + } + } + + #[cfg(windows)] + pub(crate) fn fsencode_wide(&self, wide: &[u16]) -> PyResult { + let value = crate::common::wtf8::Wtf8Buf::from_wide(wide); + if !self.state.config.settings.legacy_windows_fs_encoding { + return Ok(self.ctx.new_bytes(value.into_bytes())); + } + self.state.codec_registry.encode_text( + self.ctx.new_str(value), + self.fs_encoding().as_ref(), + Some(self.fs_encode_errors().to_owned()), + self, + ) + } + + pub(super) fn check_filesystem_config(&self) -> PyResult<()> { + match &self.state.config.filesystem.error { + Some(error) => Err(self.new_runtime_error(error.clone())), + None => Ok(()), + } + } + + pub(super) fn init_filesystem_codec(&self) -> PyResult<()> { + self.check_filesystem_config()?; + let filesystem = &self.state.config.filesystem; + // Do not share Python codec objects between interpreters. Even when a + // parent has finalized the name, this interpreter needs its own lookup. + let codec = self + .state + .codec_registry + .lookup(filesystem.encoding(), self)?; + let name: crate::PyRef = codec + .as_tuple() + .as_object() + .get_attr("name", self)? + .try_into_value(self)?; + let _ = filesystem.canonical_name.set(name.as_str().to_owned()); + self.state + .filesystem_codec_ready + .store(true, Ordering::Release); + Ok(()) + } + + pub fn fsdecode(&self, value: impl Into) -> PyResult { + self.check_filesystem_config()?; + let value = value.into(); + #[cfg(windows)] + if self.state.config.settings.legacy_windows_fs_encoding { + // Native paths are UTF-16, never bytes in the filesystem codec. + use std::os::windows::ffi::OsStrExt; + let wide: Vec = value.encode_wide().collect(); + return Ok(self + .ctx + .new_str(crate::common::wtf8::Wtf8Buf::from_wide(&wide))); + } + let filesystem = &self.state.config.filesystem; + let encoding = filesystem.encoding(); + if FastCodec::classify(encoding) == Some(FastCodec::Utf8) + && let Some(value) = value.to_str() + { + return Ok(self.ctx.new_str(value)); + } + let bytes = value.into_encoded_bytes(); + #[cfg(all(feature = "host_env", target_os = "linux", target_env = "gnu"))] + if !self.state.filesystem_codec_ready.load(Ordering::Acquire) + && FastCodec::classify(encoding).is_none() + { + let locale = filesystem + .locale + .as_ref() + .map_err(|error| self.new_runtime_error(error.clone()))?; + let value = locale + .decode(&bytes) + .map_err(|error| self.new_runtime_error(error.to_string()))?; + return Ok(self.ctx.new_str(value)); + } + self.state.codec_registry.decode_text( + self.ctx.new_bytes(bytes).into(), + encoding, + Some(self.fs_encode_errors().to_owned()), + self, + ) + } + + pub fn fsencode<'a>(&self, value: &'a Py) -> PyResult> { + self.check_filesystem_config()?; + let filesystem = &self.state.config.filesystem; + let encoding = filesystem.encoding(); + if cfg!(windows) + || (FastCodec::classify(encoding) == Some(FastCodec::Utf8) && value.is_utf8()) + { + // XXX: this is sketchy on windows; it's not guaranteed that the + // OsStr encoding will always be compatible with WTF-8. + return Ok(Cow::Borrowed(unsafe { + OsStr::from_encoded_bytes_unchecked(value.as_bytes()) + })); + } + #[cfg(all(feature = "host_env", target_os = "linux", target_env = "gnu"))] + if !self.state.filesystem_codec_ready.load(Ordering::Acquire) + && FastCodec::classify(encoding).is_none() + { + let locale = filesystem + .locale + .as_ref() + .map_err(|error| self.new_runtime_error(error.clone()))?; + let bytes = locale.encode(value.as_wtf8()).map_err(|error| { + use rustpython_host_env::locale::LocaleEncodeError; + match error { + LocaleEncodeError::Native(error) => self.new_runtime_error(error.to_string()), + LocaleEncodeError::Character { index, reason } => self + .new_unicode_encode_error( + self.ctx.new_str(encoding), + value.to_owned(), + index, + index + 1, + self.ctx.new_str(reason), + ), + } + })?; + return Ok(Cow::Owned(unsafe { + OsString::from_encoded_bytes_unchecked(bytes) + })); + } + let bytes = self + .state + .codec_registry + .encode_text( + value.to_owned(), + encoding, + Some(self.fs_encode_errors().to_owned()), + self, + )? + .as_bytes() + .to_vec(); + Ok(Cow::Owned(unsafe { + OsString::from_encoded_bytes_unchecked(bytes) + })) + } +} diff --git a/crates/vm/src/vm/interpreter.rs b/crates/vm/src/vm/interpreter.rs index 75f31574d5c..09e4172ce36 100644 --- a/crates/vm/src/vm/interpreter.rs +++ b/crates/vm/src/vm/interpreter.rs @@ -7,7 +7,14 @@ use super::{ thread, }; use crate::{ - PyResult, builtins, common::rc::PyRc, frozen::FrozenModule, getpath, py_freeze, stdlib::atexit, + PyResult, builtins, + common::rc::PyRc, + frozen::FrozenModule, + frozen_resources::{ + FrozenModuleRegistry, FrozenRegistration, FrozenResourceBundle, ResourceError, + }, + getpath, py_freeze, + stdlib::atexit, vm::PyBaseExceptionRef, }; use alloc::collections::BTreeMap; @@ -37,7 +44,7 @@ pub struct InterpreterBuilder { settings: Settings, pub ctx: PyRc, module_defs: Vec<&'static builtins::PyModuleDef>, - frozen_modules: Vec<(&'static str, FrozenModule)>, + frozen_modules: Vec, init_hooks: Vec, } @@ -46,7 +53,7 @@ struct InitializeVmOpts<'a> { settings: Settings, ctx: PyRc, module_defs: Vec<&'static builtins::PyModuleDef>, - frozen_modules: Vec<(&'static str, FrozenModule)>, + frozen_modules: Vec, init_hooks: Vec, is_main: bool, whence: InterpreterWhence, @@ -74,7 +81,7 @@ where use crate::codecs::CodecsRegistry; use crate::common::lock::PyMutex; use crate::warn::WarningsState; - use core::sync::atomic::{AtomicBool, AtomicI64, AtomicU64}; + use core::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize}; use crossbeam_utils::atomic::AtomicCell; // Before any lock this interpreter's threads can contend on exists. @@ -84,8 +91,12 @@ where let (config, all_module_defs, frozen, int_max_str_digits) = if let Some(parent) = parent_state { // Subinterpreter: clone config and module tables from parent, fresh runtime state. let int_max_str_digits = AtomicCell::new(parent.int_max_str_digits.load()); + let mut config = parent.config.clone(); + // The executable startup snapshot applies only to its initial interpreter. + config.settings.closed_stdio = [false; 3]; + config.settings.inspect = parent.inspect.load(Ordering::Relaxed); ( - parent.config.clone(), + config, parent.module_defs.clone(), parent.frozen.clone(), int_max_str_digits, @@ -120,12 +131,10 @@ where other => other, } as usize); - let mut frozen: std::collections::HashMap< - &'static str, - FrozenModule, - rapidhash::quality::RandomState, - > = core_frozen_inits().collect(); - frozen.extend(frozen_modules); + let mut frozen: FrozenModuleRegistry = core_frozen_inits().collect(); + for registration in frozen_modules { + frozen.apply_registration(registration); + } (config, all_module_defs, frozen, int_max_str_digits) }; @@ -133,6 +142,7 @@ where // Per-interpreter ephemeral state (must not be shared across interpreters). let codec_registry = CodecsRegistry::new(&ctx); let warnings = WarningsState::init_state(&ctx); + let lazy_imports = crate::lazy_import::LazyImportsState::new(&ctx); let interpreter_id = runtime::alloc_interpreter_id(); let runtime_root_id = parent_state.map_or(interpreter_id, |parent| parent.runtime_root_id); @@ -153,15 +163,37 @@ where runtime_root_id, whence, is_main, + inspect: AtomicBool::new(config.settings.inspect), + interactive_src_count: AtomicUsize::new(0), config, + modules: Default::default(), + builtins_copy: Default::default(), + sysdict_copy: Default::default(), module_defs: all_module_defs, frozen, stacksize: AtomicCell::new(0), thread_count: AtomicCell::new(0), atexit_funcs: PyMutex::default(), audit_hooks: PyMutex::default(), + signal_handlers: Default::default(), codec_registry, + filesystem_codec_ready: AtomicBool::new(false), + unicode_names_loaded: AtomicBool::new(false), + import_time_header: AtomicBool::new(false), + lazy_imports, struct_format_cache: crate::buffer::FormatSpecCache::default(), + #[cfg(all( + feature = "host_env", + any( + target_os = "linux", + target_os = "macos", + target_os = "windows", + target_os = "android" + ), + not(any(target_env = "musl", target_env = "sgx")) + ))] + ctypes_buffer_views: Default::default(), + functools_placeholder: Default::default(), finalizing: AtomicBool::new(false), #[cfg(feature = "threading")] finalizing_thread_ident: AtomicCell::new(0), @@ -175,6 +207,7 @@ where global_trace_func: PyMutex::default(), global_profile_func: PyMutex::default(), type_mutex: PyMutex::default(), + common_type_descriptors: crate::builtins::type_::CommonTypeDescriptors::new(&ctx), #[cfg(feature = "threading")] main_thread_ident, #[cfg(feature = "threading")] @@ -190,7 +223,7 @@ where stop_the_world: StopTheWorldState::new(), feature_flags, own_gil, - running_main: AtomicBool::new(false), + running_main: AtomicCell::new(None), ready: AtomicBool::new(false), id_refcount: AtomicI64::new(0), require_idref: AtomicBool::new(false), @@ -218,10 +251,21 @@ where // `initialize()` runs Python bytecode directly (e.g. importing `codecs` // and `encodings`) before any `enter_vm` scope exists, so attach this // thread for the duration so type cache reads see it as ATTACHED. - let vm_guard = thread::VmBootstrapGuard::new(&vm); - vm.initialize(); - vm.state.ready.store(true, Ordering::Release); - drop(vm_guard); + if whence != InterpreterWhence::Unknown { + let _vm_guard = thread::VmBootstrapGuard::new(&vm); + vm.initialize(); + } + + if whence != InterpreterWhence::Unknown && vm.startup_error.is_none() { + #[cfg(feature = "threading")] + { + let factory = alloc::sync::Arc::new(thread::InterpreterThreadFactory::new(&vm)); + vm.thread_factory = Some(factory.clone()); + runtime::publish_thread_factory(vm.state.interpreter_id, &factory); + } + // Publish readiness only after arbitrary-ID thread creation is available. + vm.state.ready.store(true, Ordering::Release); + } // Clone global_state for Interpreter after all initialization is done let global_state = vm.state.clone(); @@ -232,6 +276,7 @@ where fn create_subinterpreter_from_parent( parent: &VirtualMachine, config: runtime::InterpreterConfig, + whence: InterpreterWhence, ) -> Result { config.check()?; // Suspend the caller's current VM attachment (if any) for the duration @@ -258,17 +303,23 @@ fn create_subinterpreter_from_parent( frozen_modules: Vec::new(), init_hooks: Vec::new(), is_main: false, - whence: InterpreterWhence::Stdlib, + whence, parent_state: Some(&parent.state), interp_config: config, }, |_| {}, ); let interp = Interpreter { global_state, vm }; + if interp.vm.startup_error.is_some() { + return Err("subinterpreter initialization failed"); + } // Every interpreter has a `__main__` module once it is initialized. - interp.enter(|vm| { - let _ = vm.ensure_main_module(); - }); + if whence != InterpreterWhence::Unknown { + interp.enter(|vm| { + let _ = vm.ensure_main_module(); + vm.apply_startup_lazy_imports(); + }); + } Ok(interp) } @@ -358,6 +409,8 @@ impl InterpreterBuilder { /// /// Frozen modules are Python modules compiled into the binary. /// This method accepts any iterator of (name, FrozenModule) pairs. + /// It registers code only. To include embedded package data, use + /// [`Self::add_frozen_modules_with_resources`] with the matching resource bundle. /// /// # Example /// ``` @@ -372,13 +425,34 @@ impl InterpreterBuilder { where I: IntoIterator, { - self.frozen_modules.extend(frozen); + self.frozen_modules + .push(FrozenRegistration::code_only(frozen)); self } + /// Add frozen code and resources as one ownership-preserving registration. + /// + /// Every resource owner must be a package in this registration. Replacing a + /// package or module in a later registration never inherits its old resources, + /// even if the replacement contains identical bytecode. + pub fn add_frozen_modules_with_resources( + mut self, + frozen: I, + resources: &'static [FrozenResourceBundle], + ) -> Result + where + I: IntoIterator, + { + self.frozen_modules + .push(FrozenRegistration::with_resources(frozen, resources)?); + Ok(self) + } + /// Build the interpreter. /// - /// This consumes the configuration and returns a fully initialized Interpreter. + /// This consumes the configuration and initializes an interpreter. + /// Use `VirtualMachine::check_initialization` before executing Python code + /// to handle a startup configuration or codec error without panicking. #[must_use] pub fn build(self) -> Interpreter { let (vm, global_state) = initialize_vm( @@ -440,6 +514,12 @@ pub struct Interpreter { vm: VirtualMachine, } +impl Drop for Interpreter { + fn drop(&mut self) { + thread::clear_async_exception_on_owner_drop(&self.vm); + } +} + impl Interpreter { /// Create a new interpreter configuration builder. /// @@ -566,7 +646,16 @@ impl Interpreter { parent: &VirtualMachine, config: runtime::InterpreterConfig, ) -> Result { - create_subinterpreter_from_parent(parent, config) + create_subinterpreter_from_parent(parent, config, InterpreterWhence::Stdlib) + } + + #[cfg(feature = "threading")] + pub(crate) fn create_subinterpreter_from_vm_with_whence( + parent: &VirtualMachine, + config: runtime::InterpreterConfig, + whence: InterpreterWhence, + ) -> Result { + create_subinterpreter_from_parent(parent, config, whence) } /// Create a subinterpreter with an explicit PEP 734 / `PyInterpreterConfig`. @@ -574,7 +663,7 @@ impl Interpreter { &self, config: runtime::InterpreterConfig, ) -> Result { - create_subinterpreter_from_parent(&self.vm, config) + create_subinterpreter_from_parent(&self.vm, config, InterpreterWhence::Stdlib) } /// Spawn a new OS-thread VM that shares this interpreter's `sys` / builtins. @@ -583,6 +672,24 @@ impl Interpreter { self.vm.new_thread() } + /// Move the main execution context into a separate owner, leaving this + /// handle available to create worker VMs for the same interpreter. + /// + /// The returned interpreter must run and finalize on the original thread. + /// This handle should only create worker VMs and must not be finalized. + /// Unlike `new_thread()`, this preserves the main VM's signal handlers and + /// all of its other thread-local state. + #[cfg(feature = "threading")] + #[must_use] + pub fn take_main_thread(&mut self) -> Self { + let replacement = self.vm.new_thread_vm(); + let vm = core::mem::replace(&mut self.vm, replacement); + Self { + global_state: self.global_state.clone(), + vm, + } + } + /// Run a function with the main virtual machine and return a PyResult of the result. /// /// To enter vm context multiple times or to avoid buffer/exception management, this function is preferred. @@ -631,14 +738,33 @@ impl Interpreter { self.finalize(res.err()) } + /// Py_RunMain + /// + /// Run a function that reports its own errors and returns the exit code, + /// then finalize with that exit code. An unhandled `KeyboardInterrupt` + /// exits through the default SIGINT handler instead. + pub fn run_main(self, f: F) -> u32 + where + F: FnOnce(&VirtualMachine) -> u32, + { + crate::signal::clear_unhandled_keyboard_interrupt(); + let exit_code = self.enter(f); + let exit_code = self.finalize_with_exit_code(exit_code); + if crate::signal::unhandled_keyboard_interrupt() { + crate::signal::exit_sigint() + } else { + exit_code + } + } + /// Finalize vm and turns an exception to exit code. /// /// Finalization steps (matching Py_FinalizeEx): - /// 1. Flush stdout and stderr. /// 1. Handle exit exception and turn it to exit code. /// 1. Call threading._shutdown() to join non-daemon threads. /// 1. Run atexit exit functions. /// 1. Set finalizing flag and hang remaining daemon threads. + /// 1. Flush stdout and stderr. /// 1. Forced GC collection pass (collect cycles while builtins are available). /// 1. Module finalization (finalize_modules). /// 1. Clear interpreter-owned cross-interpreter data. @@ -646,93 +772,141 @@ impl Interpreter { /// /// Note that calling `finalize` is not necessary by purpose though. pub fn finalize(self, exc: Option) -> u32 { - self.enter(|vm| { - let mut flush_status = vm.flush_std(); + self.finalize_inner(|vm| exc.map_or(0, |exc| vm.handle_exit_exception(exc))) + } + /// Finalize vm with an exit code the caller has already determined. + /// + /// See [`Interpreter::finalize`] for the finalization steps. + pub fn finalize_with_exit_code(self, exit_code: u32) -> u32 { + self.finalize_inner(|_| exit_code) + } + + fn finalize_inner(self, exit_code: impl FnOnce(&VirtualMachine) -> u32) -> u32 { + // A PyInterpreterState_New-style state has never run Python and has + // no modules, streams or shutdown callbacks to finalize. + if self.whence() == InterpreterWhence::Unknown { + return exit_code(&self.vm); + } + self.enter(|vm| { // See if any exception leaked out: - let exit_code = if let Some(exc) = exc { - vm.handle_exit_exception(exc) + let exit_code = exit_code(vm); + + // A failed shutdown flush overrides even an explicit nonzero exit code. + if vm.finalize_ex() < 0 { + EXITCODE_FLUSH_FAILURE } else { - 0 - }; - - // Wait for thread shutdown - call threading._shutdown() if available. - // This waits for all non-daemon threads to complete. - // threading module may not be imported, so ignore import errors. - #[cfg(feature = "threading")] - if let Ok(threading) = vm.import("threading", 0) - && let Ok(shutdown) = threading.get_attr("_shutdown", vm) - && let Err(e) = shutdown.call((), vm) - { - vm.run_unraisable( - e, - Some("Exception ignored in threading shutdown".to_owned()), - threading, - ); + exit_code } + }) + } +} - // Run atexit handlers before setting finalizing flag. - // This allows unraisable exceptions from atexit handlers to be reported. - atexit::_run_exitfuncs(vm); +impl VirtualMachine { + /// Py_Exit + /// + /// Finalize the interpreter and exit the process with `status`. + pub fn exit_process(&self, status: u32) -> ! { + if self.state.thread_is_running_main() { + self.state.set_not_running_main(); + } + let status = if self.finalize_ex() < 0 { + EXITCODE_FLUSH_FAILURE + } else { + status + }; + crate::host_env::os::exit(status as i32) + } - // Clean up any lingering subinterpreters. This has to happen before - // the finalizing flag is set, or else threads might get prematurely - // blocked. - #[cfg(feature = "threading")] - finalize_subinterpreters(vm); + /// The steps of Py_FinalizeEx. + /// Return a negative value if any flush failed. + fn finalize_ex(&self) -> i32 { + let vm = self; + // Wait for thread shutdown - call threading._shutdown() if available. + // This waits for all non-daemon threads to complete. + // threading module may not be imported, so ignore import errors. + #[cfg(feature = "threading")] + if let Ok(threading) = vm.import("threading", 0) + && let Ok(shutdown) = threading.get_attr("_shutdown", vm) + && let Err(e) = shutdown.call((), vm) + { + vm.run_unraisable( + e, + Some("Exception ignored in threading shutdown".to_owned()), + threading, + ); + } - // Remaining daemon threads hang in `_PyThreadState_HangThread` when - // they next attach (or at the eval-breaker if they are already - // running). Their `_ThreadHandle` stays not-done so `is_alive()` - // is still true for `join()` during the GC that follows. - #[cfg(feature = "threading")] - { - vm.state.stop_the_world.stop_the_world(&vm.state); - vm.state - .finalizing_thread_ident - .store(crate::stdlib::_thread::get_ident()); + // Exit callbacks and subinterpreter cleanup can start non-daemon + // threads. Recheck after stopping all interpreters so new work cannot + // race the transition to finalization. + #[cfg(feature = "threading")] + loop { + atexit::_run_exitfuncs(vm); + finalize_subinterpreters(vm); + crate::stdlib::_thread::_thread::_shutdown(vm); + + let mut stopped = super::stop_the_world::StopTheWorldGroup::new(); + let has_callbacks = !vm.state.atexit_funcs.lock().is_empty(); + let has_subinterpreters = vm.state.is_main + && !runtime::owned_interpreter_ids_for(vm.state.runtime_root_id).is_empty(); + let has_threads = crate::stdlib::_thread::_thread::has_pending_shutdown_threads(vm); + if has_callbacks || has_subinterpreters || has_threads { + stopped.restart(); + continue; } + + // Remaining daemon threads hang when they next attach or reach a + // safepoint. Publish finalization while the world is still stopped. + vm.state + .finalizing_thread_ident + .store(crate::stdlib::_thread::get_ident()); vm.state.finalizing.store(true, Ordering::Release); - #[cfg(feature = "threading")] - { - thread::set_other_threads_shutting_down(&vm.state); - vm.state.stop_the_world.start_the_world(&vm.state); - crate::signal::set_finalizing_bit(); - } + thread::set_other_threads_shutting_down(&vm.state); + stopped.restart(); + crate::signal::set_finalizing_bit(); + break; + } - // GC pass - collect cycles before module cleanup - vm.state.gc.collect_force(2); + #[cfg(not(feature = "threading"))] + { + atexit::_run_exitfuncs(vm); + vm.state.finalizing.store(true, Ordering::Release); + } - // Module finalization: remove modules from sys.modules, GC collect - // (while builtins is still available for __del__), then clear module dicts. - vm.finalize_modules(); + // Exit callbacks have finished, but modules and the user unraisable + // hook are still available to report a failed stream flush. + let mut flush_status = vm.flush_std(); - // CPython clears low-level cross-interpreter container data from - // _PyAtExit_Fini(), after Python atexit callbacks and module - // finalization. In particular, values sent by an atexit callback - // must also become unbound when this interpreter goes away. - let interpreter_id = vm.state.interpreter_id; - crate::stdlib::_interpchannels::clear_interpreter(interpreter_id); - crate::stdlib::_interpqueues::clear_interpreter(interpreter_id); + #[cfg(all(feature = "host_env", any(unix, windows, target_os = "wasi")))] + crate::stdlib::_signal::_signal::finalize_signal_handlers(vm); - if vm.flush_std() < 0 && flush_status == 0 { - flush_status = -1; - } + // GC pass - collect cycles before module cleanup + vm.state.gc.collect_force(2); - // Match CPython: if exit_code is 0 and stdout flush failed, exit 120 - let exit_code = if exit_code == 0 && flush_status < 0 { - EXITCODE_FLUSH_FAILURE - } else { - exit_code - }; + // Module finalization: remove modules from sys.modules, GC collect + // (while builtins is still available for __del__), then clear module dicts. + vm.finalize_modules(); - // Daemon threads may still exist, so use the safe `process()`, - // not `drain_all()`. - #[cfg(feature = "threading")] - crate::object::qsbr::QSBR.process(); + // CPython clears low-level cross-interpreter container data from + // _PyAtExit_Fini(), after Python atexit callbacks and module + // finalization. In particular, values sent by an atexit callback + // must also become unbound when this interpreter goes away. + let interpreter_id = vm.state.interpreter_id; + crate::stdlib::_interpchannels::clear_interpreter(interpreter_id); + crate::stdlib::_interpqueues::clear_interpreter(interpreter_id); - exit_code - }) + if vm.flush_std() < 0 && flush_status == 0 { + flush_status = -1; + } + + // Daemon threads may still exist, so use the safe `process()`, + // not `drain_all()`. + #[cfg(feature = "threading")] + crate::object::qsbr::QSBR.process(); + + vm.clear_async_exception(); + flush_status } } @@ -896,6 +1070,19 @@ mod tests { }) } + #[test] + fn uninitialized_interpreter_preserves_exit_code() { + let parent = Interpreter::without_stdlib(Default::default()); + let raw = create_subinterpreter_from_parent( + &parent.vm, + runtime::InterpreterConfig::ISOLATED, + InterpreterWhence::Unknown, + ) + .unwrap(); + assert!(!raw.vm.initialized); + assert_eq!(raw.finalize_with_exit_code(23), 23); + } + /// Main interpreter is marked main with Runtime whence and is registered. #[test] fn main_interpreter_identity() { @@ -1287,7 +1474,6 @@ mod tests { let thread_vm = vm.new_thread(); std::thread::spawn(move || { thread_vm.run(|vm| { - main_started_worker.store(true, Ordering::Release); let deadline = Instant::now() + Duration::from_secs(30); let mut operations = 0; while !sub_finished_worker.load(Ordering::Acquire) && Instant::now() < deadline @@ -1297,6 +1483,11 @@ mod tests { let result = vm._add(&a, &b).unwrap(); assert_eq!(*int::get_value(&result), 42_i32.to_bigint().unwrap()); operations += 1; + if operations == 1 { + // Publish readiness only after actual progress. Otherwise + // the sub can finish before this loop's first iteration. + main_started_worker.store(true, Ordering::Release); + } // The protocol calls above never reach a safepoint on // their own; a bytecode loop would. Without this, a // concurrent stop-the-world could not finish while this @@ -1314,7 +1505,12 @@ mod tests { let sub_worker = sub.enter(|vm| { let thread_vm = vm.new_thread(); std::thread::spawn(move || { + let deadline = Instant::now() + Duration::from_secs(30); while !main_started_worker.load(Ordering::Acquire) { + assert!( + Instant::now() < deadline, + "main interpreter made no progress before the readiness deadline" + ); std::thread::yield_now(); } thread_vm.run(|vm| { @@ -1464,6 +1660,7 @@ mod tests { let sub = main.create_subinterpreter(); let sub_scope = sub.enter(|vm| { + vm.state.gc.disable(); let scope = vm.new_scope_with_builtins(); run(vm, &scope, CYCLE); assert_eq!(live_nodes(vm), 2); diff --git a/crates/vm/src/vm/mod.rs b/crates/vm/src/vm/mod.rs index 445ff7474a0..d29360a569f 100644 --- a/crates/vm/src/vm/mod.rs +++ b/crates/vm/src/vm/mod.rs @@ -3,6 +3,7 @@ //! See also: //! +mod async_exception; #[cfg(feature = "rustpython-compiler")] mod compile; pub(crate) mod compile_mode; @@ -10,12 +11,17 @@ pub(crate) mod compile_mode; pub use compile::VmCompileError; mod context; pub mod crossinterp; +mod filesystem; mod interpreter; mod method; #[cfg(feature = "rustpython-compiler")] mod python_run; +#[cfg(feature = "rustpython-compiler")] +pub use python_run::InteractiveLine; pub mod runtime; mod setting; +#[cfg(feature = "threading")] +pub(crate) mod stop_the_world; pub mod thread; mod vm_new; mod vm_object; @@ -24,9 +30,8 @@ mod vm_ops; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, builtins::{ - self, PyBaseExceptionRef, PyBaseObject, PyDict, PyDictRef, PyFrozenSet, PyInt, PyList, - PyModule, PySet, PyStr, PyStrInterned, PyStrRef, PyTypeRef, PyUtf8Str, PyUtf8StrInterned, - PyWeak, + self, PyAnyDict, PyBaseExceptionRef, PyBaseObject, PyDict, PyFrozenSet, PyInt, PyList, + PyModule, PySet, PyStr, PyStrInterned, PyStrRef, PyTypeRef, PyUtf8Str, PyWeak, code::PyCode, dict::{PyDictItems, PyDictKeys, PyDictValues}, pystr::AsPyStr, @@ -37,28 +42,27 @@ use crate::{ convert::ToPyObject, exceptions::types::{PyBaseException, PyMemoryError}, frame::{ExecutionResult, FrameObject, FrameObjectRef}, - frozen::FrozenModule, + frozen_resources::FrozenModuleRegistry, function::{ArgMapping, FuncArgs, PySetterValue}, import, protocol::{PyIterIter, PyIterReturn}, scope::Scope, signal::{self, SignalHandlers}, stdlib, - types::{GetattroFunc, fn_addr}, + types::{GetAttr, GetattroFunc, fn_addr}, warn::WarningsState, }; -use alloc::{borrow::Cow, collections::BTreeMap}; +use alloc::collections::BTreeMap; #[cfg(all(not(unix), feature = "threading"))] use core::ptr::NonNull; use core::{ - cell::{Cell, OnceCell, RefCell}, - sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}, + cell::{Cell, RefCell}, + sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering}, }; use crossbeam_utils::atomic::AtomicCell; -use std::{ - collections::{HashMap, HashSet}, - ffi::{OsStr, OsString}, -}; +#[cfg(feature = "threading")] +use std::collections::HashMap; +use std::collections::HashSet; pub use context::Context; pub use interpreter::{Interpreter, InterpreterBuilder}; @@ -83,6 +87,8 @@ pub const MAX_MEMORY_SIZE: usize = isize::MAX as usize; /// /// To construct the main VM of an interpreter, use [`Interpreter`]. pub struct VirtualMachine { + #[cfg(feature = "threading")] + pub(crate) thread_factory: Option>, pub builtins: PyRef, pub sys_module: PyRef, pub ctx: PyRc, @@ -93,6 +99,7 @@ pub struct VirtualMachine { exceptions: RefCell, pub import_func: PyObjectRef, pub(crate) importlib: PyObjectRef, + pub(crate) import_timing: Cell, pub profile_func: RefCell, pub trace_func: RefCell, pub use_tracing: Cell, @@ -101,16 +108,18 @@ pub struct VirtualMachine { pub(crate) what_event: Cell>, tracing_depth: Cell, pub recursion_limit: Cell, - pub(crate) signal_handlers: OnceCell, pub(crate) signal_rx: Option, pub repr_guards: RefCell>, + pub(crate) lazy_imports_resolving: RefCell>, pub state: PyRc, pub initialized: bool, + pub(crate) import_bootstrap_complete: bool, + startup_error: Option, recursion_depth: Cell, /// Depth of native recursion that pushes no Python frame, counted only - /// where the stack pointer cannot be read. Everywhere else the native - /// stack itself answers, and nothing needs counting. - #[cfg(any(miri, target_env = "musl"))] + /// where the stack pointer cannot measure every stack in use. Wasm has + /// a separate engine call stack in addition to its linear-memory stack. + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] native_recursion_depth: Cell, /// C stack soft limit for detecting stack overflow (like c_stack_soft_limit) #[cfg_attr(any(miri, target_env = "musl"), allow(dead_code))] @@ -148,6 +157,9 @@ pub struct VirtualMachine { /// UnsafeCell because the VM is per-thread and no reference into the Vec /// is held across anything that could push to it. trampoline_stack: core::cell::UnsafeCell>, + // Keep the closed state alive through the release of every other VM root. + // A callback during field destruction must not reserve another exception. + async_exception: async_exception::PendingAsyncException, } /// Non-owning frame pointer for the non-unix threading frames stack. @@ -176,6 +188,8 @@ unsafe impl Send for FramePtr {} #[derive(Debug)] struct ExceptionStack { + /// Pending native C API error, independent of handled `sys.exception()`. + raised: Option, /// Linked list of handled-exception slots (`_PyErr_StackItem` chain). /// Bottom element is the thread's base slot; generator/coroutine resume /// pushes an additional slot. Normal frame calls do **not** push/pop. @@ -185,7 +199,72 @@ struct ExceptionStack { impl Default for ExceptionStack { fn default() -> Self { // Thread's base `_PyErr_StackItem` – always present. - Self { stack: vec![None] } + Self { + raised: None, + stack: vec![None], + } + } +} + +/// Serializes complete stop/restart transactions across interpreters. +/// A collector holds one permit while stopping every interpreter; other callers +/// transfer their permit to the stopped state until the matching restart. +#[cfg(feature = "threading")] +pub(crate) struct StopTheWorldTransaction { + _private: (), +} + +#[cfg(feature = "threading")] +static STW_TRANSACTION: AtomicU64 = AtomicU64::new(0); + +#[cfg(feature = "threading")] +static NEXT_STW_REQUESTER: AtomicU64 = AtomicU64::new(1); + +#[cfg(feature = "threading")] +thread_local! { + // OS thread IDs can be reused after a requester exits, even while another + // thread still owes its matching restart. Logical IDs are never reused. + static STW_REQUESTER: u64 = NEXT_STW_REQUESTER + .try_update(Ordering::Relaxed, Ordering::Relaxed, |id| id.checked_add(1)) + .expect("stop-the-world requester IDs exhausted"); +} + +#[cfg(feature = "threading")] +impl StopTheWorldTransaction { + pub(crate) fn acquire() -> Self { + let requester = STW_REQUESTER.with(|id| *id); + loop { + match STW_TRANSACTION.compare_exchange( + 0, + requester, + Ordering::AcqRel, + Ordering::Relaxed, + ) { + Ok(_) => return Self { _private: () }, + Err(owner) => assert_ne!( + owner, requester, + "stop-the-world transactions cannot be nested on the same thread" + ), + } + let wait = || { + while STW_TRANSACTION.load(Ordering::Acquire) != 0 { + std::thread::yield_now(); + } + }; + // Wait detached from the CURRENT interpreter, not the interpreter + // we intend to stop. Reattach without owning the permit, then retry: + // a suspended or shutting-down waiter must not strand ownership. + if thread::try_with_current_vm(|vm| vm.allow_threads(wait)).is_none() { + wait(); + } + } + } +} + +#[cfg(feature = "threading")] +impl Drop for StopTheWorldTransaction { + fn drop(&mut self) { + STW_TRANSACTION.store(0, Ordering::Release); } } @@ -199,10 +278,9 @@ pub struct StopTheWorldState { world_stopped: AtomicBool, /// Ident of the thread that requested the stop (like `stw->requester`) requester: AtomicU64, - /// Single exclusion held for the whole stop→start span. Fork and GC are - /// both stop-the-world requesters driving this shared state; only one may - /// hold it at a time. Acquired before any stop bookkeeping (see - /// `acquire_exclusion`) and released by `start_the_world`/`reset_after_fork`. + /// Ownership transferred by a successful public stop. GC retains its + /// transaction externally and leaves this false. Only a matching restart + /// or the forking owner's child reset may release this ownership. exclusion: AtomicBool, /// Signaled by suspending threads when their state transitions to SUSPENDED notify_mutex: std::sync::Mutex<()>, @@ -401,50 +479,11 @@ impl StopTheWorldState { forced_parks != 0 && self.thread_countdown.load(Ordering::Acquire) == 0 } - /// Acquire the single stop-the-world exclusion in a park-friendly way. - /// - /// Fork and GC both request stop-the-world through the same shared state; - /// without this exclusion their `requester`/`requested`/countdown words - /// could be clobbered by an interleaving requester, so the completion - /// check could never converge and a requester would wait on itself forever. - /// - /// The acquire must be park-friendly. While another requester's stop is in - /// progress it sets this thread's stop bit and waits for it to suspend; - /// blocking on a plain lock here would keep this thread from ever reaching - /// that safepoint, so the active requester would wait for this thread while - /// this thread waits for the lock — a deadlock swap. Instead we poll and - /// honor the suspend request between tries. Suspending here is safe as long - /// as any lock a spinning requester still holds is never acquired - /// attached-blocking by another thread. The fork requester holds IMP_LOCK, - /// but its acquisition detaches (`allow_threads`), so no attached thread - /// blocks on it; the GC requester holds only the `collecting` mutex, which - /// is only ever `try_lock`'d. The active requester therefore force-parks - /// this thread, finishes its whole stop→start span, releases the exclusion, - /// and only then does this thread resume and acquire it. - fn acquire_exclusion(&self, state: &PyGlobalState) { - if self - .exclusion - .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) - .is_ok() - { - return; - } - loop { - crate::vm::thread::suspend_if_needed(state); - std::thread::yield_now(); - if self - .exclusion - .compare_exchange(false, true, Ordering::AcqRel, Ordering::Relaxed) - .is_ok() - { - return; - } - } - } - - /// Release the stop-the-world exclusion taken by `acquire_exclusion`. + /// Release only a transaction owned by this state, after every wake/clear. fn release_exclusion(&self) { - self.exclusion.store(false, Ordering::Release); + if self.exclusion.swap(false, Ordering::AcqRel) { + drop(StopTheWorldTransaction { _private: () }); + } } /// Stop all non-requester threads (`stop_the_world`). @@ -454,11 +493,27 @@ impl StopTheWorldState { /// 3. Waits (polling with 1 ms condvar timeout) for attached threads /// to self-suspend in `check_signals`. /// - /// Takes the shared exclusion first so at most one requester (fork or GC) - /// drives the stop→start span at a time; it is released by - /// `start_the_world`/`reset_after_fork`. + /// Public calls own one process-wide transaction until the matching start. + /// The caller must finish stop before invoking start, including when those + /// calls occur on different threads; concurrent duplicate starts are invalid. + /// Transactions are non-reentrant: a nested stop on the requesting thread + /// panics before changing any stop state or releasing the outer transaction. pub fn stop_the_world(&self, state: &PyGlobalState) { - self.acquire_exclusion(state); + let transaction = StopTheWorldTransaction::acquire(); + self.stop_with_transaction(state, &transaction); + self.exclusion.store(true, Ordering::Release); + core::mem::forget(transaction); + } + + /// Stop one state within a transaction retained by the caller (notably GC). + pub(crate) fn stop_with_transaction( + &self, + state: &PyGlobalState, + _transaction: &StopTheWorldTransaction, + ) { + // A partial stop must clear requests and wake parked slots before its + // caller releases the transaction or rolls back previously stopped VMs. + let rollback = scopeguard::guard((), |_| self.resume_threads(state, false)); let start = std::time::Instant::now(); let requester_ident = crate::stdlib::_thread::get_ident(); self.requester.store(requester_ident, Ordering::Relaxed); @@ -478,6 +533,7 @@ impl StopTheWorldState { stw_trace(format_args!( "stop end requester={requester_ident} wait_ns=0 polls=0" )); + scopeguard::ScopeGuard::into_inner(rollback); return; } @@ -493,7 +549,6 @@ impl StopTheWorldState { // a thread may have suspended and notified right before we enter wait. let guard = self.notify_mutex.lock().unwrap(); if self.all_non_requester_suspended(state) { - drop(guard); break; } let _ = self @@ -526,10 +581,17 @@ impl StopTheWorldState { stw_trace(format_args!( "stop end requester={requester_ident} wait_ns={wait_ns} polls={polls}" )); + scopeguard::ScopeGuard::into_inner(rollback); } /// Resume all suspended threads (`start_the_world`). pub fn start_the_world(&self, state: &PyGlobalState) { + self.resume_threads(state, true); + self.release_exclusion(); + } + + /// Rollback also permits threads that never reached SUSPENDED. + fn resume_threads(&self, state: &PyGlobalState, fully_stopped: bool) { use thread::ThreadState; let requester = self.requester.load(Ordering::Relaxed); stw_trace(format_args!("start begin requester={requester}")); @@ -560,7 +622,7 @@ impl StopTheWorldState { continue; } debug_assert!( - state == ThreadState::Suspended as i32, + !fully_stopped || state == ThreadState::Suspended as i32, "non-requester thread not suspended at start-the-world: id={id} state={state}" ); if state == ThreadState::Suspended as i32 { @@ -579,9 +641,6 @@ impl StopTheWorldState { crate::signal::clear_stop_bit(); #[cfg(debug_assertions)] self.debug_assert_all_non_requester_detached(state); - // Release the exclusion last, ending the stop→start span so the next - // requester (fork or GC) can proceed. - self.release_exclusion(); stw_trace(format_args!("start end requester={requester}")); } @@ -595,8 +654,9 @@ impl StopTheWorldState { // Only one thread survives fork; any stop-the-world bit inherited // from the parent is stale. crate::signal::clear_stop_bit(); - // The surviving child thread inherited the exclusion taken by the - // pre-fork `stop_the_world`; release it (no start_the_world runs here). + // A single-state stop owns the transaction through this flag. A fork + // group instead retains its shared transaction through child repair; + // its member states do not own exclusion and must not release it here. self.release_exclusion(); stw_trace(format_args!("reset-after-fork")); } @@ -813,8 +873,17 @@ pub struct PyGlobalState { /// becomes *the* process main — see [`runtime::main_interpreter_id`]. pub is_main: bool, pub config: PyConfig, + /// `config.inspect`, which `PyConfig_Set` can change at runtime. + pub(crate) inspect: AtomicBool, + /// `_interactive_src_count`: numbers the code filenames of interactive inputs. + pub(crate) interactive_src_count: AtomicUsize, + // Core extension reload state belongs to the interpreter, not a thread or + // the process-wide native module definitions. + pub(crate) modules: crate::common::lock::OnceCell>, + pub(crate) builtins_copy: crate::common::lock::OnceCell>, + pub(crate) sysdict_copy: crate::common::lock::OnceCell>, pub module_defs: BTreeMap<&'static str, &'static builtins::PyModuleDef>, - pub frozen: HashMap<&'static str, FrozenModule, rapidhash::quality::RandomState>, + pub frozen: FrozenModuleRegistry, pub stacksize: AtomicCell, pub thread_count: AtomicCell, /// Registered `atexit` callbacks, newest first. Shared ownership so @@ -823,8 +892,26 @@ pub struct PyGlobalState { pub atexit_funcs: PyMutex>>, /// `sys.addaudithook` hooks, shared by all threads of this interpreter. pub(crate) audit_hooks: PyMutex>, + pub(crate) signal_handlers: SignalHandlers, pub codec_registry: CodecsRegistry, + pub(crate) filesystem_codec_ready: AtomicBool, + pub(crate) unicode_names_loaded: AtomicBool, + pub(crate) import_time_header: AtomicBool, + pub(crate) lazy_imports: crate::lazy_import::LazyImportsState, pub struct_format_cache: crate::buffer::FormatSpecCache, + #[cfg(all( + feature = "host_env", + any( + target_os = "linux", + target_os = "macos", + target_os = "windows", + target_os = "android" + ), + not(any(target_env = "musl", target_env = "sgx")) + ))] + pub(crate) ctypes_buffer_views: alloc::sync::Arc, + /// Placeholder identity shared by all threads and fresh imports in this interpreter. + pub(crate) functools_placeholder: crate::common::lock::OnceCell, pub finalizing: AtomicBool, /// The thread performing finalization, which need not be the process main thread. #[cfg(feature = "threading")] @@ -842,6 +929,8 @@ pub struct PyGlobalState { pub global_profile_func: PyMutex>, /// Global type mutation/versioning mutex for CPython-style FT type operations. pub type_mutex: PyMutex<()>, + /// Object-owned descriptors shared by heap types in this interpreter. + pub(crate) common_type_descriptors: builtins::type_::CommonTypeDescriptors, /// Main thread identifier (pthread_self on Unix) #[cfg(feature = "threading")] pub main_thread_ident: AtomicCell, @@ -870,8 +959,8 @@ pub struct PyGlobalState { pub feature_flags: runtime::InterpFeatureFlags, /// Whether the interpreter was configured with `gil="own"`. pub own_gil: bool, - /// Whether `__main__` is currently executing via `_interpreters.exec` / `run_*`. - pub running_main: AtomicBool, + /// `threads.main`: the ident of the thread running `__main__`, if any. + pub running_main: AtomicCell>, /// True after `initialize()` has finished (CPython "ready"). pub ready: AtomicBool, /// Optional ID refcount used by `_interpreters.create(reqrefs=True)`. @@ -911,6 +1000,45 @@ impl PyGlobalState { self.feature_flags.allow_daemon_threads } + /// _PyInterpreterState_SetRunningMain + /// + /// Record the calling thread as the one running `__main__`. Return `false` + /// when a thread already does. + pub fn set_running_main(&self) -> bool { + self.running_main + .compare_exchange(None, Some(crate::frame::current_thread_ident())) + .is_ok() + } + + /// _PyInterpreterState_SetNotRunningMain + pub fn set_not_running_main(&self) { + debug_assert!(self.thread_is_running_main()); + self.running_main.store(None); + } + + /// _PyInterpreterState_IsRunningMain + #[must_use] + pub fn is_running_main(&self) -> bool { + self.running_main.load().is_some() + } + + /// _PyThreadState_IsRunningMain + #[must_use] + pub fn thread_is_running_main(&self) -> bool { + self.running_main.load() == Some(crate::frame::current_thread_ident()) + } + + /// _PyInterpreterState_ReinitRunningMain + /// + /// After a fork only the forking thread survives, so `__main__` is no + /// longer running unless that thread was running it. + #[cfg(all(feature = "host_env", unix))] + pub(crate) fn reinit_running_main(&self) { + if !self.thread_is_running_main() { + self.running_main.store(None); + } + } + /// The config this interpreter was created with, rebuilt from the flags it /// kept (`_PyInterpreterConfig_InitFromState`). #[must_use] @@ -1227,6 +1355,17 @@ impl VirtualMachine { } } + // Native imports keep the interpreter's original registry. Rebinding the + // Python-visible sys.modules does not replace this dictionary. + pub(crate) fn sys_modules(&self) -> PyObjectRef { + self.state + .modules + .get() + .expect("initialized module registry") + .clone() + .into() + } + /// Create a new `VirtualMachine` structure. pub(crate) fn new(ctx: PyRc, state: PyRc) -> Self { flame_guard!("new VirtualMachine"); @@ -1249,7 +1388,6 @@ impl VirtualMachine { let importlib = ctx.none(); let profile_func = RefCell::new(ctx.none()); let trace_func = RefCell::new(ctx.none()); - let signal_handlers = OnceCell::from(SignalHandlers::default()); let vm = Self { builtins, @@ -1260,19 +1398,24 @@ impl VirtualMachine { exceptions: RefCell::default(), import_func, importlib, + import_timing: Cell::default(), profile_func, trace_func, use_tracing: Cell::new(false), what_event: Cell::new(None), tracing_depth: Cell::new(0), + #[cfg(feature = "threading")] + thread_factory: None, recursion_limit: Cell::new(if cfg!(debug_assertions) { 256 } else { 1000 }), - signal_handlers, signal_rx: None, repr_guards: RefCell::default(), + lazy_imports_resolving: RefCell::default(), state, initialized: false, + import_bootstrap_complete: false, + startup_error: None, recursion_depth: Cell::new(0), - #[cfg(any(miri, target_env = "musl"))] + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] native_recursion_depth: Cell::new(0), c_stack_soft_limit: Cell::new(Self::calculate_c_stack_soft_limit()), async_gen_firstiter: RefCell::new(None), @@ -1285,20 +1428,25 @@ impl VirtualMachine { pending_tailcall_owner: core::cell::UnsafeCell::new(None), pending_gen_resume: core::cell::UnsafeCell::new(None), trampoline_stack: core::cell::UnsafeCell::new(Vec::new()), + async_exception: async_exception::PendingAsyncException::default(), }; - vm.builtins.init_dict( - vm.ctx.intern_str("builtins"), - crate::function::plain_doc(stdlib::builtins::DOC) - .map(|doc| vm.ctx.intern_str(doc).to_owned()), - &vm, - ); - vm.sys_module.init_dict( - vm.ctx.intern_str("sys"), - crate::function::plain_doc(stdlib::sys::DOC) - .map(|doc| vm.ctx.intern_str(doc).to_owned()), - &vm, - ); + vm.builtins + .init_dict( + vm.ctx.intern_str("builtins"), + crate::function::plain_doc(stdlib::builtins::DOC) + .map(|doc| vm.ctx.intern_str(doc).as_object()), + &vm, + ) + .expect("Failed to initialize the fresh builtins dictionary"); + vm.sys_module + .init_dict( + vm.ctx.intern_str("sys"), + crate::function::plain_doc(stdlib::sys::DOC) + .map(|doc| vm.ctx.intern_str(doc).as_object()), + &vm, + ) + .expect("Failed to initialize the fresh sys dictionary"); // let name = vm.sys_module.get_attr("__name__", &vm).unwrap(); vm } @@ -1308,15 +1456,18 @@ impl VirtualMachine { #[cfg(feature = "encodings")] fn import_encodings(&mut self) -> PyResult<()> { self.import("encodings", 0).map_err(|import_err| { - let rustpythonpath_env = crate::host_env::os::var("RUSTPYTHONPATH").ok(); - let pythonpath_env = crate::host_env::os::var("PYTHONPATH").ok(); + if self.state.config.settings.home.is_some() { + return import_err; + } + let rustpythonpath_env = crate::host_env::os::var_os("RUSTPYTHONPATH"); + let pythonpath_env = crate::host_env::os::var_os("PYTHONPATH"); let env_set = rustpythonpath_env.as_ref().is_some() || pythonpath_env.as_ref().is_some(); let path_contains_env = self.state.config.paths.module_search_paths.iter().any(|s| { - Some(s.as_str()) == rustpythonpath_env.as_deref() || Some(s.as_str()) == pythonpath_env.as_deref() + Some(s.as_os_str()) == rustpythonpath_env.as_deref() || Some(s.as_os_str()) == pythonpath_env.as_deref() }); let guide_message = if cfg!(feature = "freeze-stdlib") { - "`rustpython_pylib` may not be set while using `freeze-stdlib` feature. Try using `rustpython::InterpreterBuilder::init_stdlib` or manually call `builder.add_frozen_modules(rustpython_pylib::FROZEN_STDLIB)` in `rustpython_vm::Interpreter::builder()`." + "`rustpython_pylib` may not be set while using `freeze-stdlib` feature. Try using `rustpython::InterpreterBuilder::init_stdlib` or manually call `builder.add_frozen_modules_with_resources(rustpython_pylib::FROZEN_STDLIB, rustpython_pylib::FROZEN_STDLIB_RESOURCES)` in `rustpython_vm::Interpreter::builder()`." } else if !env_set { "Neither RUSTPYTHONPATH nor PYTHONPATH is set. Try setting one of them to the stdlib directory." } else if path_contains_env { @@ -1351,7 +1502,7 @@ impl VirtualMachine { // Use dotted names when freeze-stdlib is enabled (modules come from Lib/encodings/), // otherwise use underscored names (modules come from core_modules/). let (ascii_module_name, utf8_module_name, latin1_module_name) = - if cfg!(feature = "freeze-stdlib") { + if cfg!(feature = "freeze-stdlib") && self.state.config.settings.use_frozen_modules { ("encodings.ascii", "encodings.utf_8", "encodings.latin_1") } else { ("encodings_ascii", "encodings_utf_8", "encodings_latin_1") @@ -1360,7 +1511,7 @@ impl VirtualMachine { // __import__("encodings.ascii") returns top-level "encodings", so // look up the actual submodule in sys.modules. self.import(ascii_module_name, 0)?; - let sys_modules = self.sys_module.get_attr(identifier!(self, modules), self)?; + let sys_modules = self.sys_modules(); let ascii_module = sys_modules.get_item(ascii_module_name, self)?; let getregentry = ascii_module.get_attr("getregentry", self)?; let codec_info = getregentry.call((), self)?; @@ -1397,6 +1548,143 @@ impl VirtualMachine { Ok(()) } + // PyUnicode_InitEncodings completes filesystem setup before creating stdio. + fn init_stdio(&self) -> PyResult<()> { + let io = import::import_builtin(self, "_io")?; + + // CPython normalizes configured stdio encodings to CodecInfo.name. + #[cfg(all(feature = "host_env", feature = "stdio"))] + let stdio_encoding: PyRef = { + let encoding = match self.state.config.settings.stdio_encoding.as_deref() { + Some(encoding) => self.ctx.new_utf8_str(encoding), + None => crate::stdlib::_io::default_text_encoding(self)?, + }; + self.state + .codec_registry + .lookup(encoding.as_str(), self)? + .as_tuple() + .as_object() + .get_attr("name", self)? + .try_into_value(self)? + }; + + // Full stdio: FileIO → BufferedWriter → TextIOWrapper + #[cfg(all(feature = "host_env", feature = "stdio"))] + let make_stdio = |name: &str, fd: i32, write: bool| -> PyResult { + #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] + if self.state.config.settings.closed_stdio[fd as usize] + || !rustpython_host_env::fileutils::is_valid_fd(fd) + { + return Ok(self.ctx.none()); + } + + let result = (|| { + let buffered_stdio = self.state.config.settings.buffered_stdio; + let unbuffered = write && !buffered_stdio; + let buf = crate::stdlib::_io::open( + self.ctx.new_int(fd).into(), + Some(if write { "wb" } else { "rb" }), + crate::stdlib::_io::OpenArgs { + buffering: if unbuffered { 0 } else { -1 }, + closefd: false, + ..Default::default() + }, + self, + )?; + let raw = if unbuffered { + buf.clone() + } else { + buf.get_attr("raw", self)? + }; + raw.set_attr("name", self.ctx.new_str(format!("<{name}>")), self)?; + let isatty = self.call_method(&raw, "isatty", ())?.is_true(self)?; + let write_through = !buffered_stdio; + let line_buffering = buffered_stdio && (isatty || fd == 2); + + let newline = if cfg!(windows) { None } else { Some("\n") }; + let encoding = stdio_encoding.clone(); + // stderr always uses backslashreplace (ignores stdio_errors) + let errors = if fd == 2 { + Some("backslashreplace") + } else { + self.state + .config + .settings + .stdio_errors + .as_deref() + .or_else(|| { + Some(if self.state.config.settings.stdio_encoding.is_some() { + "strict" + } else { + "surrogateescape" + }) + }) + }; + + let stdio = self.call_method( + &io, + "TextIOWrapper", + ( + buf, + encoding, + errors, + newline, + line_buffering, + write_through, + ), + )?; + let mode = if write { "w" } else { "r" }; + stdio.set_attr("mode", self.ctx.new_str(mode), self)?; + Ok::<_, self::PyBaseExceptionRef>(stdio) + })(); + + #[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))] + if let Err(ref exc) = result + && exc.fast_isinstance(self.ctx.exceptions.os_error) + && !rustpython_host_env::fileutils::is_valid_fd(fd) + { + return Ok(self.ctx.none()); + } + result + }; + + // Sandbox stdio: lightweight wrapper using Rust's std::io directly + #[cfg(all(not(feature = "host_env"), feature = "stdio"))] + let make_stdio = |name: &str, fd: i32, write: bool| { + let mode = if write { "w" } else { "r" }; + let stdio = stdlib::sys::SandboxStdio { + fd, + name: format!("<{name}>"), + mode: mode.to_owned(), + } + .into_ref(&self.ctx); + Ok(stdio.into()) + }; + + // No stdio: set to None (embedding use case) + #[cfg(not(feature = "stdio"))] + let make_stdio = |_name: &str, _fd: i32, _write: bool| Ok(self.ctx.none()); + + let set_stdio = |name, fd, write| { + let stdio: PyObjectRef = make_stdio(name, fd, write)?; + let dunder_name = self.ctx.intern_str(format!("__{name}__")); + self.sys_module.set_attr( + dunder_name, // e.g. __stdin__ + stdio.clone(), + self, + )?; + self.sys_module.set_attr(name, stdio, self)?; + Ok(()) + }; + set_stdio("stdin", 0, false)?; + set_stdio("stdout", 1, true)?; + set_stdio("stderr", 2, true)?; + + let io_open = io.get_attr("open", self)?; + self.builtins.set_attr("open", io_open, self)?; + Ok(()) + } + fn initialize(&mut self) { flame_guard!("init VirtualMachine"); @@ -1415,9 +1703,25 @@ impl VirtualMachine { drop(prewarmed_memory_errors); stdlib::builtins::init_module(self, &self.builtins); + let _ = self + .state + .builtins_copy + .set(self.builtins.dict().copy().into_ref(&self.ctx)); + // Explicit lazy imports can occur in frozen startup code. + let lazy_callback = self.builtins.get_attr("__lazy_import__", self); + let lazy_callback = + self.expect_pyresult(lazy_callback, "failed to initialize lazy imports"); + let _ = self.state.lazy_imports.default_callback.set(lazy_callback); let callable_cache_init = self.init_callable_cache(); self.expect_pyresult(callable_cache_init, "failed to initialize callable cache"); - stdlib::sys::init_module(self, &self.sys_module, &self.builtins); + if let Err(error) = self.check_filesystem_config() { + self.startup_error = Some(error); + return; + } + if let Err(error) = stdlib::sys::init_module(self, &self.sys_module, &self.builtins) { + self.startup_error = Some(error); + return; + } self.expect_pyresult( stdlib::sys::set_bootstrap_stderr(self), "failed to initialize bootstrap stderr", @@ -1434,114 +1738,18 @@ impl VirtualMachine { let importlib = import::init_importlib_base(self)?; self.import_ascii_utf8_encodings()?; - { - let io = import::import_builtin(self, "_io")?; - - // Full stdio: FileIO → BufferedWriter → TextIOWrapper - #[cfg(all(feature = "host_env", feature = "stdio"))] - let make_stdio = |name: &str, fd: i32, write: bool| -> PyResult { - let buffered_stdio = self.state.config.settings.buffered_stdio; - let unbuffered = write && !buffered_stdio; - let buf = crate::stdlib::_io::open( - self.ctx.new_int(fd).into(), - Some(if write { "wb" } else { "rb" }), - crate::stdlib::_io::OpenArgs { - buffering: if unbuffered { 0 } else { -1 }, - closefd: false, - ..Default::default() - }, - self, - )?; - let raw = if unbuffered { - buf.clone() - } else { - buf.get_attr("raw", self)? - }; - raw.set_attr("name", self.ctx.new_str(format!("<{name}>")), self)?; - let isatty = self.call_method(&raw, "isatty", ())?.is_true(self)?; - let write_through = !buffered_stdio; - let line_buffering = buffered_stdio && (isatty || fd == 2); - - let newline = if cfg!(windows) { None } else { Some("\n") }; - let encoding = self.state.config.settings.stdio_encoding.as_deref(); - // stderr always uses backslashreplace (ignores stdio_errors) - let errors = if fd == 2 { - Some("backslashreplace") - } else { - self.state - .config - .settings - .stdio_errors - .as_deref() - .or_else(|| { - Some(if self.state.config.settings.stdio_encoding.is_some() { - "strict" - } else { - "surrogateescape" - }) - }) - }; - - let stdio = self.call_method( - &io, - "TextIOWrapper", - ( - buf, - encoding, - errors, - newline, - line_buffering, - write_through, - ), - )?; - let mode = if write { "w" } else { "r" }; - stdio.set_attr("mode", self.ctx.new_str(mode), self)?; - Ok::<_, self::PyBaseExceptionRef>(stdio) - }; - - // Sandbox stdio: lightweight wrapper using Rust's std::io directly - #[cfg(all(not(feature = "host_env"), feature = "stdio"))] - let make_stdio = |name: &str, fd: i32, write: bool| { - let mode = if write { "w" } else { "r" }; - let stdio = stdlib::sys::SandboxStdio { - fd, - name: format!("<{name}>"), - mode: mode.to_owned(), - } - .into_ref(&self.ctx); - Ok(stdio.into()) - }; - - // No stdio: set to None (embedding use case) - #[cfg(not(feature = "stdio"))] - let make_stdio = |_name: &str, _fd: i32, _write: bool| { - Ok(crate::builtins::PyNone.into_pyobject(self)) - }; - - let set_stdio = |name, fd, write| { - let stdio: PyObjectRef = make_stdio(name, fd, write)?; - let dunder_name = self.ctx.intern_str(format!("__{name}__")); - self.sys_module.set_attr( - dunder_name, // e.g. __stdin__ - stdio.clone(), - self, - )?; - self.sys_module.set_attr(name, stdio, self)?; - Ok(()) - }; - set_stdio("stdin", 0, false)?; - set_stdio("stdout", 1, true)?; - set_stdio("stderr", 2, true)?; - - let io_open = io.get_attr("open", self)?; - self.builtins.set_attr("open", io_open, self)?; - } - Ok(importlib) }; let res = essential_init(); - let importlib = self.expect_pyresult(res, "essential initialization failed"); + let importlib = match res { + Ok(importlib) => importlib, + Err(error) => { + self.startup_error = Some(error); + return; + } + }; + self.import_bootstrap_complete = true; #[cfg(feature = "host_env")] if self.state.config.settings.allow_external_library @@ -1563,10 +1771,14 @@ impl VirtualMachine { #[cfg(feature = "encodings")] if _expect_stdlib { if let Err(e) = self.import_encodings() { - eprintln!( - "encodings initialization failed. Only utf-8 encoding will be supported." - ); - self.print_exception(&e); + if self.state.config.settings.home.is_some() { + self.startup_error = Some(e); + } else { + eprintln!( + "encodings initialization failed. Only utf-8 encoding will be supported." + ); + self.print_exception(&e); + } } } else { // Here may not be the best place to give general `path_list` advice, @@ -1578,9 +1790,75 @@ impl VirtualMachine { ); } + if let Err(error) = self.init_filesystem_codec() { + self.startup_error = Some(error); + return; + } + if let Err(error) = self.init_stdio() { + self.startup_error = Some(error); + return; + } self.initialized = true; } + /// Check initialization without printing diagnostics or exiting the process. + /// Embedding applications should call this before executing Python code. + pub fn check_initialization(&self) -> PyResult<()> { + self.startup_error.clone().map_or(Ok(()), Err) + } + + /// Report an invalid explicit standard-library configuration to a command-line + /// host. Embedding applications can use `check_initialization` without diagnostics. + pub fn check_stdlib_initialization(&self) -> PyResult<()> { + let Some(error) = &self.startup_error else { + return Ok(()); + }; + let settings = &self.state.config.settings; + let paths = &self.state.config.paths; + let repr = |value: &str| { + self.ctx + .new_str(value) + .repr(self) + .unwrap_or_else(|_| "?".to_owned()) + }; + eprintln!("Python path configuration:"); + eprintln!( + " PYTHONHOME = {}", + settings + .home + .as_deref() + .map_or_else(|| "(not set)".to_owned(), repr) + ); + eprintln!(" isolated = {}", u8::from(settings.isolated)); + eprintln!(" environment = {}", u8::from(!settings.ignore_environment)); + eprintln!(" sys.executable = {}", repr(&paths.executable)); + eprintln!(" sys.prefix = {}", repr(&paths.prefix)); + eprintln!(" sys.exec_prefix = {}", repr(&paths.exec_prefix)); + eprintln!(" sys.path = ["); + for path in &paths.module_search_paths { + let value = self + .fsdecode(path.clone()) + .and_then(|path| path.repr(self)) + .unwrap_or_else(|_| "?".to_owned()); + eprintln!(" {value},"); + } + eprintln!(" ]"); + // A startup import failure is fatal even if the imported module raised + // SystemExit(0) or SystemExit(None). Keep its exception as the cause, + // without passing its exit code to ordinary user-code finalization. + let startup_error = self.new_runtime_error("Failed to initialize interpreter"); + startup_error.set_cause(Some(error.clone())); + Err(startup_error) + } + + /// Apply configured global lazy imports after startup imports, including site. + /// Hosts that perform their own main-module setup can call this at that boundary. + pub fn apply_startup_lazy_imports(&self) { + if self.state.config.settings.lazy_imports == 1 { + self.state.lazy_imports.all.store(true, Ordering::Release); + } + } + /// Set the custom signal channel for the interpreter pub fn set_user_signal_channel(&mut self, signal_rx: signal::UserSignalReceiver) { self.signal_rx = Some(signal_rx); @@ -1609,14 +1887,14 @@ impl VirtualMachine { /// ```no_run /// use rustpython_vm::Interpreter; /// Interpreter::without_stdlib(Default::default()).enter(|vm| { - /// let bytes = std::fs::read("__pycache__/.rustpython-314.pyc").unwrap(); + /// let bytes = std::fs::read("__pycache__/.rustpython-315.pyc").unwrap(); /// let main_scope = vm.new_scope_with_main().unwrap(); /// vm.run_pyc_bytes(&bytes, main_scope); /// }); /// ``` pub fn run_pyc_bytes(&self, pyc_bytes: &[u8], scope: Scope) -> PyResult<()> { let code = PyCode::from_pyc(pyc_bytes, Some(""), None, None, self)?; - self.with_simple_run("", |_module_dict| { + self.with_simple_run(&self.ctx.new_str(""), |_module_dict| { self.run_code_obj(code, scope)?; Ok(()) }) @@ -1645,84 +1923,81 @@ impl VirtualMachine { #[cold] pub fn run_unraisable(&self, e: PyBaseExceptionRef, msg: Option, object: PyObjectRef) { - // During interpreter finalization, sys.unraisablehook may not be available, - // but we still need to report exceptions (especially from atexit callbacks). - // Write directly to stderr like PyErr_FormatUnraisable. - if self.state.finalizing.load(Ordering::Acquire) { - self.write_unraisable_to_stderr(&e, msg.as_deref(), &object); - return; - } - - let sys_module = self.import("sys", 0).unwrap(); - let unraisablehook = sys_module.get_attr("unraisablehook", self).unwrap(); + self.run_unraisable_with_message(e, msg.map(|msg| self.ctx.new_str(msg)), object); + } - let exc_type = e.class().to_owned(); - let exc_traceback = e.traceback().to_pyobject(self); // TODO: actual traceback - let exc_value = e.into(); + #[cold] + pub(crate) fn run_unraisable_with_message( + &self, + e: PyBaseExceptionRef, + msg: Option, + object: PyObjectRef, + ) { + let write_original = || { + self.write_unraisable_to_stderr(&e, msg.clone(), &object); + }; let args = stdlib::sys::UnraisableHookArgsData { - exc_type, - exc_value, - exc_traceback, - err_msg: self.new_pyobj(msg), - object, + exc_type: e.class().to_owned(), + exc_value: e.clone().into(), + exc_traceback: e.traceback().to_pyobject(self), + err_msg: msg.clone().to_pyobject(self), + object: object.clone(), + } + .to_pyobject(self); + let unraisablehook = match self.sys_module.dict().get_item_opt("unraisablehook", self) { + Ok(Some(hook)) => hook, + Ok(None) => { + write_original(); + return; + } + Err(error) => { + self.write_unraisable_to_stderr( + &error, + Some(self.ctx.new_str("Exception ignored in sys.unraisablehook")), + &self.ctx.none(), + ); + return; + } }; - if let Err(e) = unraisablehook.call((args,), self) { - println!("{}", e.as_object().repr(self).unwrap()); + if let Err(error) = self.audit("sys.unraisablehook", || { + (unraisablehook.clone(), args.clone()) + }) { + self.write_unraisable_to_stderr( + &error, + Some(self.ctx.new_str("Exception ignored in audit hook")), + &self.ctx.none(), + ); + return; + } + if self.is_none(&unraisablehook) { + write_original(); + return; + } + if let Err(error) = unraisablehook.call((args,), self) { + self.write_unraisable_to_stderr( + &error, + Some(self.ctx.new_str("Exception ignored in sys.unraisablehook")), + &unraisablehook, + ); } } - /// Write unraisable exception to stderr during finalization. + /// Write an unraisable exception when its hook cannot be used. /// Similar to _PyErr_WriteUnraisableDefaultHook in CPython. fn write_unraisable_to_stderr( &self, e: &Py, - msg: Option<&str>, + msg: Option, object: &PyObject, ) { - // Get stderr once and reuse it - let stderr = crate::stdlib::sys::get_stderr(self).ok(); - - let write_to_stderr = |s: &str, stderr: &Option, vm: &Self| { - if let Some(stderr) = stderr { - let _ = vm.call_method(stderr, "write", (s.to_owned(),)); - } else { - eprint!("{s}"); - } - }; - - if self.is_none(object) { - if let Some(msg) = msg { - write_to_stderr(&format!("{msg}:\n"), &stderr, self); - } - } else { - let msg_str = if let Some(msg) = msg { - format!("{msg}: ") - } else { - "Exception ignored in: ".to_owned() - }; - write_to_stderr(&msg_str, &stderr, self); - - let repr_result = object.repr(self); - let repr_wtf8 = repr_result - .as_ref() - .map_or_else(|_| "".as_ref(), |s| s.as_wtf8()); - write_to_stderr(&format!("{repr_wtf8}\n"), &stderr, self); - } - - // Write exception type and message - let exc_type_name = e.class().name(); - let msg = match e.as_object().str(self) { - Ok(exc_str) if !exc_str.as_wtf8().is_empty() => { - format!("{}: {}\n", exc_type_name, exc_str.as_wtf8()) - } - _ => format!("{exc_type_name}\n"), + let args = stdlib::sys::UnraisableHookArgsData { + exc_type: e.class().to_owned(), + exc_value: e.to_owned().into(), + exc_traceback: e.traceback().to_pyobject(self), + err_msg: msg.to_pyobject(self), + object: object.to_owned(), }; - write_to_stderr(&msg, &stderr, self); - - // Flush stderr to ensure output is visible - if let Some(ref stderr) = stderr { - let _ = self.call_method(stderr, "flush", ()); - } + let _ = stdlib::sys::sys::write_unraisable(args, self); } /// Store a callee frame pointer for the trampoline to pick up after @@ -2245,32 +2520,24 @@ impl VirtualMachine { /// Run `run` with main scope. fn with_simple_run( &self, - path: &str, + path: &Py, run: impl FnOnce(&Py) -> PyResult<()>, ) -> PyResult<()> { - let sys_modules = self.sys_module.get_attr(identifier!(self, modules), self)?; - let main_module = sys_modules.get_item(identifier!(self, __main__), self)?; - let module_dict = main_module.dict().expect("main module must have __dict__"); + let module_dict = self.add_main_module()?.dict(); // Track whether we set __file__ (for cleanup) let set_file_name = !module_dict.contains_key(identifier!(self, __file__), self); if set_file_name { - module_dict.set_item( - identifier!(self, __file__), - self.ctx.new_str(path).into(), - self, - )?; - module_dict.set_item(identifier!(self, __cached__), self.ctx.none(), self)?; + module_dict.set_item(identifier!(self, __file__), path.to_owned().into(), self)?; } let result = run(&module_dict); self.flush_io(); - // Cleanup __file__ and __cached__ after execution + // Cleanup __file__ after execution if set_file_name { let _ = module_dict.del_item(identifier!(self, __file__), self); - let _ = module_dict.del_item(identifier!(self, __cached__), self); } result @@ -2317,6 +2584,16 @@ impl VirtualMachine { // Phase 7: Clear sys and builtins dicts last self.finalize_clear_sys_builtins_dict(); + // Do not keep initialization snapshots alive after interpreter teardown. + for dict in [ + &self.state.builtins_copy, + &self.state.sysdict_copy, + &self.state.modules, + ] { + if let Some(dict) = dict.get() { + dict.clear(); + } + } } /// Phase 1: Set special sys attributes to None and restore stdio. @@ -2365,10 +2642,7 @@ impl VirtualMachine { fn finalize_remove_modules(&self) -> Vec<(String, PyRef)> { let mut module_weakrefs = Vec::new(); - let Ok(modules) = self.sys_module.get_attr(identifier!(self, modules), self) else { - return module_weakrefs; - }; - let Some(modules_dict) = modules.downcast_ref::() else { + let Some(modules_dict) = self.state.modules.get() else { return module_weakrefs; }; @@ -2378,8 +2652,7 @@ impl VirtualMachine { for (key, value) in items { let name = key .downcast_ref::() - .map(|s| s.as_str().to_owned()) - .unwrap_or_default(); + .map_or_default(|s| s.as_str().to_owned()); // Save weakref to module (for later dict clearing) if value.downcast_ref::().is_some() @@ -2397,10 +2670,8 @@ impl VirtualMachine { /// Phase 3: Clear sys.modules dict. fn finalize_clear_modules_dict(&self) { - if let Ok(modules) = self.sys_module.get_attr(identifier!(self, modules), self) - && let Some(modules_dict) = modules.downcast_ref::() - { - modules_dict.clear(); + if let Some(modules) = self.state.modules.get() { + modules.clear(); } } @@ -2483,9 +2754,16 @@ impl VirtualMachine { /// (`Py_C_RECURSION_LIMIT`). A native step costs far more stack than a /// Python one and debug builds cost more again, so this sits well under /// what a default stack holds rather than at what it would just fit. - #[cfg(any(miri, target_env = "musl"))] - const NATIVE_RECURSION_LIMIT_UNMEASURED: usize = - if cfg!(debug_assertions) { 500 } else { 1500 }; + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] + const NATIVE_RECURSION_LIMIT_UNMEASURED: usize = if cfg!(target_arch = "wasm32") { + // The engine call stack cannot be measured by psm's linear-memory + // stack pointer. Keep headroom for calls between successive guards. + if cfg!(debug_assertions) { 64 } else { 128 } + } else if cfg!(debug_assertions) { + 500 + } else { + 1500 + }; /// Get the stack boundaries using platform-specific APIs. /// Returns (base, top) where base is the lowest address and top is the highest. @@ -2585,6 +2863,31 @@ impl VirtualMachine { false } + /// Enter a native-recursion section equivalent to `Py_EnterRecursiveCall`. + pub fn enter_recursive_call(&self, _where: &str) -> PyResult<()> { + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] + let counted_too_deep = + self.native_recursion_depth.get() >= Self::NATIVE_RECURSION_LIMIT_UNMEASURED; + #[cfg(not(any(miri, target_env = "musl", target_arch = "wasm32")))] + let counted_too_deep = false; + + if counted_too_deep || self.check_c_stack_overflow() { + return Err(self.new_recursion_depth_error(_where)); + } + + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] + self.native_recursion_depth.update(|d| d + 1); + + Ok(()) + } + + /// Leave a native-recursion section equivalent to + /// `Py_LeaveRecursiveCall`. + pub fn leave_recursive_call(&self) { + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] + self.native_recursion_depth.update(|d| d.saturating_sub(1)); + } + /// Used to run the body of a (possibly) recursive function. It will raise a /// RecursionError if recursive functions are nested far too many times, /// preventing a stack overflow. @@ -2593,22 +2896,20 @@ impl VirtualMachine { /// frame limit `sys.setrecursionlimit()` sets, so nesting counted here does /// not come out of what Python code has left to call with. pub fn with_recursion PyResult>(&self, _where: &str, f: F) -> PyResult { - // `check_c_stack_overflow()` answers no unconditionally where the stack - // pointer cannot be read, which would leave this guard with nothing to - // stop. A count of the nesting stands in for the measurement there. - #[cfg(any(miri, target_env = "musl"))] + // Count nesting where the stack pointer is unavailable or cannot + // measure the engine call stack, as on Wasm. Keep the linear-memory + // stack probe enabled there as an independent guard. + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] let counted_too_deep = self.native_recursion_depth.get() >= Self::NATIVE_RECURSION_LIMIT_UNMEASURED; - #[cfg(not(any(miri, target_env = "musl")))] + #[cfg(not(any(miri, target_env = "musl", target_arch = "wasm32")))] let counted_too_deep = false; if counted_too_deep || self.check_c_stack_overflow() { - return Err( - self.new_recursion_error(format!("maximum recursion depth exceeded {_where}")) - ); + return Err(self.new_recursion_depth_error(_where)); } - #[cfg(any(miri, target_env = "musl"))] + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] let _native_depth_guard = { self.native_recursion_depth.update(|d| d + 1); scopeguard::guard((), |()| { @@ -2623,6 +2924,25 @@ impl VirtualMachine { &self, frame: FrameObjectRef, f: F, + ) -> PyResult { + self.with_frame_impl::(frame, f) + } + + /// Run the incomplete frame of a generator being created. Its caller link + /// must not escape, as RETURN_GENERATOR copies the frame with + /// `previous = NULL`. + pub(crate) fn with_generator_frame PyResult>( + &self, + frame: FrameObjectRef, + f: F, + ) -> PyResult { + self.with_frame_impl::(frame, f) + } + + fn with_frame_impl PyResult>( + &self, + frame: FrameObjectRef, + f: F, ) -> PyResult { self.check_recursive_call("")?; @@ -2632,7 +2952,7 @@ impl VirtualMachine { // code -- an `__add__` chain, a sort key that sorts -- takes more than // the margin in that many. if self.check_c_stack_overflow() { - return Err(self.new_recursion_error(String::new())); + return Err(self.new_recursion_depth_error("")); } self.recursion_depth.update(|d| d + 1); @@ -2669,7 +2989,7 @@ impl VirtualMachine { // Capture f_back before clearing previous so code holding a // reference to this FrameObject can walk the chain after return. - if !old_chain.is_null() { + if RETAIN_BACK && !old_chain.is_null() { let strong = frame.as_object().strong_count(); // Only set retained_back if someone else holds a reference (escaped) // AND the caller already has a FrameObject. Materializing the caller @@ -2680,8 +3000,11 @@ impl VirtualMachine { if strong > 1 { let mut guard = frame.iframe().cold().retained_back.lock(); if guard.is_none() { - let prev_iframe = unsafe { &*old_chain }; - if let Some(fo) = prev_iframe.frame_obj() { + // SAFETY: old_chain remains live until this synchronous entry exits. + let visible = unsafe { crate::frame::first_complete_iframe(old_chain) }; + if let Some(prev_iframe) = unsafe { visible.as_ref() } + && let Some(fo) = prev_iframe.frame_obj() + { *guard = Some(fo.to_owned()); } } @@ -2739,7 +3062,7 @@ impl VirtualMachine { iframe: &mut crate::frame::InterpreterFrame, ) -> PyResult { if self.check_c_stack_overflow() { - return Err(self.new_recursion_error(String::new())); + return Err(self.new_recursion_depth_error("")); } self.recursion_depth.update(|d| d + 1); @@ -2807,8 +3130,9 @@ impl VirtualMachine { // The slots above are the last write this thread makes into // the frame object, so it is now readable from anywhere. fo.iframe().detach(); - if !old_chain.is_null() { - let prev_iframe = unsafe { &*old_chain }; + // SAFETY: old_chain belongs to this still-active thread chain. + let visible = unsafe { crate::frame::first_complete_iframe(old_chain) }; + if let Some(prev_iframe) = unsafe { visible.as_ref() } { let back_fo = prev_iframe.materialize_chain(self); *fo.iframe().cold().retained_back.lock() = Some(back_fo); } @@ -2880,7 +3204,7 @@ impl VirtualMachine { ) -> PyResult { self.check_recursive_call("")?; if self.check_c_stack_overflow() { - return Err(self.new_recursion_error(String::new())); + return Err(self.new_recursion_depth_error("")); } self.recursion_depth.update(|d| d + 1); @@ -2994,10 +3318,19 @@ impl VirtualMachine { if result.is_err() && self.use_tracing.get() && (!self.is_none(&self.profile_func.borrow()) - || frame - .iframe() - .cold_opt() - .is_some_and(|c| c.trace.lock().is_some())) + || if frame.iframe().is_incomplete() { + crate::frame::current_complete_frame_for_trace(self).is_some_and(|visible| { + visible + .iframe() + .cold_opt() + .is_some_and(|c| c.trace.lock().is_some()) + }) + } else { + frame + .iframe() + .cold_opt() + .is_some_and(|c| c.trace.lock().is_some()) + }) { let ret_result = self.trace_event_what( TraceEvent::Return, @@ -3024,6 +3357,7 @@ impl VirtualMachine { future_features: crate::bytecode::CodeFlags::empty(), dont_imply_dedent: false, recursion_limit: self.recursion_limit.get(), + build_list_from_arg: false, } } @@ -3059,10 +3393,40 @@ impl VirtualMachine { self.tracing_depth.get() != 0 } + // _PyEval_CallTracing: suspend callback recursion suppression for an + // explicit call, then restore the surrounding callback's tracing state. + pub(crate) fn with_tracing_enabled(&self, f: impl FnOnce() -> PyResult) -> PyResult { + let depth = self.tracing_depth.replace(0); + let enabled = + !self.is_none(&self.trace_func.borrow()) || !self.is_none(&self.profile_func.borrow()); + let previous_enabled = self.use_tracing.replace(enabled); + let result = f(); + self.tracing_depth.set(depth); + if depth != 0 { + self.use_tracing.set(previous_enabled); + } + result + } + + /// `where_` is empty, or a suffix that already includes the leading space. + #[cold] + fn new_recursion_depth_error(&self, where_: &str) -> PyBaseExceptionRef { + debug_assert!( + where_.is_empty() || where_.starts_with(' '), + "recursion where-clause must be empty or start with a space: {where_:?}" + ); + let msg = if where_.is_empty() { + "maximum recursion depth exceeded".to_string() + } else { + format!("maximum recursion depth exceeded{where_}") + }; + self.new_recursion_error(msg) + } + // To be called right before raising the recursion depth. fn check_recursive_call(&self, _where: &str) -> PyResult<()> { if self.recursion_depth.get() >= self.recursion_limit.get() { - Err(self.new_recursion_error(format!("maximum recursion depth exceeded {_where}"))) + Err(self.new_recursion_depth_error(_where)) } else { Ok(()) } @@ -3079,7 +3443,7 @@ impl VirtualMachine { .locals(self) } - pub fn current_globals(&self) -> PyDictRef { + pub fn current_globals(&self) -> PyRef { let ptr = crate::vm::thread::get_current_frame(); if !ptr.is_null() { return unsafe { (*ptr).globals().to_owned() }; @@ -3136,7 +3500,7 @@ impl VirtualMachine { pub fn eval_get_builtin(&self, name: &'static PyStrInterned) -> PyResult { let builtins = crate::frame::current_builtins().unwrap_or_else(|| self.builtins.dict().into()); - if let Some(dict) = builtins.downcast_ref::() { + if let Some(dict) = builtins.downcast_ref_if_exact::(self) { match dict.get_item_opt(name, self)? { Some(value) => Ok(value), None => Err(self.new_attribute_error(name.to_string())), @@ -3168,6 +3532,7 @@ impl VirtualMachine { && builtins.is(self.builtins.dict().as_object()) && let Some(cached) = self.try_import_cached(module)? { + import::report_cached_import(module, self); return Ok(cached); } @@ -3192,7 +3557,7 @@ impl VirtualMachine { // Locals fallback: use the heavy frame if available, otherwise // use globals as locals (light frame locals are on the data stack). let locals_mapping = self.current_frame().map_or_else( - || ArgMapping::from_dict_exact(globals.clone()), + || ArgMapping::from_anydict_exact(globals.clone()), |f| f.iframe().locals.clone_mapping(self), ); (Some(locals_mapping), Some(globals)) @@ -3231,13 +3596,17 @@ impl VirtualMachine { let Some(name_str) = module.to_str() else { return Ok(None); }; - let sys_modules = self.sys_module.get_attr("modules", self)?; + let sys_modules = self.sys_modules(); let Ok(found) = sys_modules.get_item(name_str, self) else { return Ok(None); }; if self.is_none(&found) || import::is_module_initializing(&found, self)? { return Ok(None); } + if !import::is_cached_module(&sys_modules, module, &found, self)? { + return Ok(None); + } + crate::lazy_import::clear_submodule(module, true, self)?; let Some(dot) = name_str.find('.') else { return Ok(Some(found)); @@ -3390,6 +3759,12 @@ impl VirtualMachine { where F: FnMut(PyObjectRef) -> PyResult, { + // A subclass may override __iter__, so only the exact types are read + // directly. + let cls = obj.class(); + if !cls.is(self.ctx.types.list_type) && !cls.is(self.ctx.types.tuple_type) { + return Ok(self.map_py_iter(obj, hint, f)); + } match_class!(match obj { ref l @ PyList => { let mut i: usize = 0; @@ -3477,6 +3852,10 @@ impl VirtualMachine { let getattro = obj.class().slots().getattro.load().unwrap(); let result = if fn_addr(getattro) == fn_addr(PyBaseObject::getattro as GetattroFunc) { obj.generic_getattr_opt(attr_name, None, self) + } else if fn_addr(getattro) == fn_addr(PyModule::slot_getattro as GetattroFunc) + && let Some(module) = obj.downcast_ref::() + { + module.getattr_inner(attr_name, true, self).map(Some) } else { obj.get_attr_inner(attr_name, self).map(Some) }; @@ -3548,13 +3927,19 @@ impl VirtualMachine { /// `check_signals` and never park, so `stop_the_world` waits forever. #[inline] pub(crate) fn eval_breaker_tripped(&self) -> bool { + if self.async_exception.is_pending() { + return true; + } #[cfg(feature = "threading")] if thread::stop_requested_for_current_thread() || self.state.gc.collection_ready() { return true; } #[cfg(not(target_arch = "wasm32"))] { - crate::signal::eval_breaker_pending() + self.signal_rx + .as_ref() + .is_some_and(signal::UserSignalReceiver::is_pending) + || crate::signal::eval_breaker_pending() } #[cfg(target_arch = "wasm32")] { @@ -3655,9 +4040,8 @@ impl VirtualMachine { "set_exception called with empty exception stack" ); if let Some(top) = excs.stack.last_mut() { - let prev = core::mem::replace(top, exc); + let _prev = core::mem::replace(top, exc); drop(excs); - drop(prev); } else { excs.stack.push(exc); drop(excs); @@ -3685,17 +4069,26 @@ impl VirtualMachine { } } + /// Keep teardown callbacks from observing or replacing a pending C error. + /// Create this guard before callback-owned locals so they drop before restoration. + #[must_use] + pub(crate) fn preserve_raised_exception(&self) -> impl Drop + '_ { + scopeguard::guard(self.take_raised_exception(), |saved| { + self.set_raised_exception(saved); + }) + } + + pub fn raised_exception(&self) -> Option { + self.exceptions.borrow().raised.clone() + } + + pub fn set_raised_exception(&self, exc: Option) { + let _previous = core::mem::replace(&mut self.exceptions.borrow_mut().raised, exc); + // Release the RefCell borrow before dropping a potentially final reference. + } + pub fn take_raised_exception(&self) -> Option { - let mut excs = self.exceptions.borrow_mut(); - if let Some(top) = excs.stack.last_mut() { - let exc = top.take(); - drop(excs); - #[cfg(feature = "threading")] - thread::update_thread_exception(self.topmost_exception()); - exc - } else { - None - } + self.exceptions.borrow_mut().raised.take() } /// `_PyErr_ChainStackItem`: if the current `exc_info` slot is occupied, @@ -3740,58 +4133,77 @@ impl VirtualMachine { excs.stack.iter().rev().find_map(|e| e.clone()) } + /// The current `config.inspect`. + pub fn config_inspect(&self) -> bool { + self.state.inspect.load(Ordering::Relaxed) + } + + /// `PyConfig_Set("inspect", value)`: update the config and `sys.flags.inspect`. + pub fn config_set_inspect(&self, inspect: bool) -> PyResult<()> { + let value: PyObjectRef = self.ctx.new_int(u8::from(inspect)).into(); + self.audit("cpython.PyConfig_Set", || ("inspect", value.clone()))?; + self.state.inspect.store(inspect, Ordering::Relaxed); + stdlib::sys::sys::set_flag_obj(self, "inspect", value) + } + + /// pymain_exit_err_print + /// + /// Report an exception that reached the top level and return the exit code. pub fn handle_exit_exception(&self, exc: PyBaseExceptionRef) -> u32 { - if exc.fast_isinstance(self.ctx.exceptions.system_exit) { - let code = exc - .as_object() - .get_attr("code", self) - .unwrap_or_else(|_| exc.as_object().to_owned()); - let msg = match_class!(match code { - ref i @ PyInt => { - use num_traits::cast::ToPrimitive; - // Try u32 first, then i32 (for negative values), else -1 for overflow - let code = i - .as_bigint() - .to_u32() - .or_else(|| i.as_bigint().to_i32().map(|v| v as u32)) - .unwrap_or(-1i32 as u32); - return code; - } - code => { - if self.is_none(&code) { - return 0; - } - code.str(self).ok() - } - }); - if let Some(msg) = msg { - // Write using Python's write() to use stderr's error handler (backslashreplace) - if let Ok(stderr) = stdlib::sys::get_stderr(self) { - let _ = self.call_method(&stderr, "write", (msg,)); - let _ = self.call_method(&stderr, "write", ("\n",)); - } - } - 1 - } else if exc.fast_isinstance(self.ctx.exceptions.keyboard_interrupt) { - self.print_exception(&exc); - cfg_select! { - unix => { - if crate::host_env::signal::set_sigint_default_onstack().is_ok() { - self.flush_std(); - crate::host_env::signal::send_sigint_to_self() - .expect("Expect to be killed."); - } + if let Some(exit_code) = self.handle_system_exit_and_keyboard_interrupt(&exc) { + return exit_code; + } + self.print_uncaught_exception(&exc); + 1 + } - (libc::SIGINT as u32) + 128 + /// _Py_HandleSystemExitAndKeyboardInterrupt + /// + /// Return the exit code of a `SystemExit` that should end the process. + /// A `KeyboardInterrupt` is remembered so that the process exits through SIGINT. + pub fn handle_system_exit_and_keyboard_interrupt( + &self, + exc: &Py, + ) -> Option { + if exc.fast_isinstance(self.ctx.exceptions.keyboard_interrupt) { + crate::signal::set_unhandled_keyboard_interrupt(); + return None; + } + // Don't exit if -i flag was given. This flag is set to 0 + // when entering interactive mode for inspecting. + if self.config_inspect() || !exc.fast_isinstance(self.ctx.exceptions.system_exit) { + return None; + } + let code = exc + .as_object() + .get_attr("code", self) + .unwrap_or_else(|_| exc.as_object().to_owned()); + let msg = match_class!(match code { + ref i @ PyInt => { + use num_traits::cast::ToPrimitive; + // Try u32 first, then i32 (for negative values), else -1 for overflow + let code = i + .as_bigint() + .to_u32() + .or_else(|| i.as_bigint().to_i32().map(|v| v as u32)) + .unwrap_or(-1i32 as u32); + return Some(code); + } + code => { + if self.is_none(&code) { + return Some(0); } - // STATUS_CONTROL_C_EXIT - same as CPython - windows => 0xC000013A, - _ => 1, + code.str(self).ok() + } + }); + if let Some(msg) = msg { + // Write using Python's write() to use stderr's error handler (backslashreplace) + if let Ok(stderr) = stdlib::sys::get_stderr(self) { + let _ = self.call_method(&stderr, "write", (msg,)); + let _ = self.call_method(&stderr, "write", ("\n",)); } - } else { - self.print_exception(&exc); - 1 } + Some(1) } #[doc(hidden)] @@ -3819,55 +4231,6 @@ impl VirtualMachine { run_module_as_main.call((module,), self)?; Ok(()) } - - pub fn fs_encoding(&self) -> &'static PyStrInterned { - identifier!(self, utf_8) - } - - pub fn fs_encode_errors(&self) -> &'static PyUtf8StrInterned { - if cfg!(windows) { - identifier_utf8!(self, surrogatepass) - } else { - identifier_utf8!(self, surrogateescape) - } - } - - pub fn fsdecode(&self, s: impl Into) -> PyStrRef { - match s.into().into_string() { - Ok(s) => self.ctx.new_str(s), - Err(s) => { - let bytes = self.ctx.new_bytes(s.into_encoded_bytes()); - let errors = self.fs_encode_errors().to_owned(); - let res = self.state.codec_registry.decode_text( - bytes.into(), - "utf-8", - Some(errors), - self, - ); - self.expect_pyresult(res, "fsdecode should be lossless and never fail") - } - } - } - - pub fn fsencode<'a>(&self, s: &'a Py) -> PyResult> { - if cfg!(windows) || s.is_utf8() { - // XXX: this is sketchy on windows; it's not guaranteed that the - // OsStr encoding will always be compatible with WTF-8. - let s = unsafe { OsStr::from_encoded_bytes_unchecked(s.as_bytes()) }; - return Ok(Cow::Borrowed(s)); - } - let errors = self.fs_encode_errors().to_owned(); - let bytes = self - .state - .codec_registry - .encode_text(s.to_owned(), "utf-8", Some(errors), self)? - .as_bytes() - .to_vec(); - // XXX: this is sketchy on windows; it's not guaranteed that the - // OsStr encoding will always be compatible with WTF-8. - let s = unsafe { OsString::from_encoded_bytes_unchecked(bytes) }; - Ok(Cow::Owned(s)) - } } impl AsRef for VirtualMachine { @@ -3898,6 +4261,56 @@ pub fn resolve_frozen_alias(name: &str) -> &str { mod tests { use super::*; + #[test] + fn raised_error_guards_preserve_storage_on_unwind() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let handled = vm.new_type_error("handled"); + let outer = vm.new_type_error("outer"); + let inner = vm.new_type_error("inner"); + vm.set_exception(Some(handled.clone())); + vm.set_raised_exception(Some(outer.clone())); + let result = std::panic::catch_unwind(core::panic::AssertUnwindSafe(|| { + let _outer_guard = vm.preserve_raised_exception(); + assert!(vm.raised_exception().is_none()); + vm.set_raised_exception(Some(inner.clone())); + { + let _inner_guard = vm.preserve_raised_exception(); + assert!(vm.raised_exception().is_none()); + assert!(vm.current_exception().unwrap().is(&handled)); + } + assert!(vm.raised_exception().unwrap().is(&inner)); + panic!("exercise raised-error guard unwinding"); + })); + assert!(result.is_err()); + assert!(vm.take_raised_exception().unwrap().is(&outer)); + assert!(vm.raised_exception().is_none()); + assert!(vm.current_exception().unwrap().is(&handled)); + vm.set_exception(None); + }); + } + + #[cfg(not(feature = "stdio"))] + #[test] + fn no_stdio_streams_are_none_singleton() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + for name in [ + "stdin", + "stdout", + "stderr", + "__stdin__", + "__stdout__", + "__stderr__", + ] { + let stream = vm.sys_module.get_attr(name, vm).unwrap(); + assert!(vm.is_none(&stream), "sys.{name} must be the None singleton"); + } + }); + } + #[test] fn nested_frozen() { use rustpython_vm as vm; diff --git a/crates/vm/src/vm/python_run.rs b/crates/vm/src/vm/python_run.rs index b8b83a240d1..e2f217a74d0 100644 --- a/crates/vm/src/vm/python_run.rs +++ b/crates/vm/src/vm/python_run.rs @@ -1,11 +1,14 @@ //! Python code execution functions. use crate::{ - Py, PyObjectRef, PyResult, VirtualMachine, - builtins::PyCode, + AsObject, Py, PyObjectRef, PyResult, VirtualMachine, + builtins::{PyBaseException, PyBaseExceptionRef, PyCode, PyModule, PyStr}, + bytecode::CodeFlags, compiler::{self}, scope::Scope, + stdlib, }; +use core::sync::atomic::Ordering; impl VirtualMachine { /// PyRun_SimpleString @@ -20,12 +23,26 @@ impl VirtualMachine { /// /// Execute a string of Python code with explicit scope and source path. pub fn run_string(&self, scope: Scope, source: &str, source_path: &str) -> PyResult { - let code_obj = self - .compile(source, compiler::Mode::Exec, source_path) - .map_err(|err| err.into_pyexception(self, Some(source)))?; + self.run_string_with_filename(scope, source, &self.ctx.new_str(source_path)) + } + + /// Execute source while retaining a Python filename, including surrogates. + pub fn run_string_with_filename( + &self, + scope: Scope, + source: &str, + filename: &Py, + ) -> PyResult { + let code = self.compile_with_filename( + source, + compiler::Mode::Exec, + filename, + self.compile_opts(), + None, + )?; // linecache._register_code(code, source, filename) - let _ = self.register_code_in_linecache(&code_obj, source); - self.run_code_obj(code_obj, scope) + let _ = self.register_code_in_linecache(&code, source); + self.run_code_obj(code, scope) } /// Register a code object's source in linecache._interactive_cache @@ -34,7 +51,7 @@ impl VirtualMachine { let linecache = self.import("linecache", 0)?; let register = linecache.get_attr("_register_code", self)?; let source_str = self.ctx.new_str(source); - let filename = self.ctx.new_str(code.source_path().as_str()); + let filename = code.source_path().to_owned(); register.call( (PyObjectRef::from(code.to_owned()), source_str, filename), self, @@ -58,22 +75,29 @@ impl VirtualMachine { #[cfg(feature = "host_env")] mod file_run { use crate::{ - AsObject, Py, PyResult, VirtualMachine, - builtins::{PyBaseExceptionRef, PyCode, PyDict}, + Py, PyResult, VirtualMachine, + builtins::{PyCode, PyDict, PyStr}, compiler::{self}, scope::Scope, }; + use std::path::Path; + impl VirtualMachine { /// _PyRun_AnyFileObject (internal) /// - /// Execute a Python file. Currently always delegates to run_simple_file - /// (interactive mode is handled separately in shell.rs). + /// Execute a Python file. A named file is not interactive, so this + /// always delegates to run_simple_file; see `run_any_stdin` for stdin. /// /// Note: This is an internal function. Use `run_file` for the public interface. #[doc(hidden)] - pub fn run_any_file(&self, scope: Scope, path: &str) -> PyResult<()> { - let path = if path.is_empty() { "???" } else { path }; + pub fn run_any_file(&self, scope: Scope, path: impl AsRef) -> PyResult<()> { + let path = path.as_ref(); + let path = if path.as_os_str().is_empty() { + Path::new("???") + } else { + path + }; self.run_simple_file(scope, path) } @@ -81,9 +105,10 @@ mod file_run { /// /// Execute a Python file with __main__ module setup. /// Sets __file__ and __cached__ before execution, removes them after. - fn run_simple_file(&self, scope: Scope, path: &str) -> PyResult<()> { - self.with_simple_run(path, |module_dict| { - self.run_simple_file_inner(module_dict, scope, path) + fn run_simple_file(&self, scope: Scope, path: &Path) -> PyResult<()> { + let filename = self.fsdecode(path.as_os_str())?; + self.with_simple_run(&filename, |module_dict| { + self.run_simple_file_inner(module_dict, scope, path, &filename) }) } @@ -91,12 +116,13 @@ mod file_run { &self, module_dict: &Py, scope: Scope, - path: &str, + path: &Path, + filename: &Py, ) -> PyResult<()> { let pyc = maybe_pyc_file(path); if pyc { // pyc file execution - set_main_loader(module_dict, path, "SourcelessFileLoader", self)?; + set_main_loader(module_dict, filename, "SourcelessFileLoader", self)?; let loader = module_dict.get_item("__loader__", self)?; let get_code = loader.get_attr("get_code", self)?; let code_obj = get_code.call((identifier!(self, __main__).to_owned(),), self)?; @@ -105,23 +131,33 @@ mod file_run { .map_err(|_| self.new_runtime_error("Bad code object in .pyc file"))?; self.run_code_obj(code, scope)?; } else { - if path != "" { - set_main_loader(module_dict, path, "SourceFileLoader", self)?; + if path != Path::new("") { + set_main_loader(module_dict, filename, "SourceFileLoader", self)?; } match crate::host_env::fs::read(path) { Ok(source_bytes) => { if let Some(null_at) = source_bytes.iter().position(|&b| b == 0) { - return Err(null_byte_syntax_error(self, path, &source_bytes, null_at)); + return Err(super::null_byte_syntax_error( + self, + filename, + &source_bytes, + null_at, + )); } #[cfg(feature = "parser")] // Match compile() by honoring BOMs and encoding cookies in files. - let source = self.decode_source_bytes(&source_bytes, path, false)?; + let source = + self.decode_source_bytes_with_filename(&source_bytes, filename, false)?; #[cfg(not(feature = "parser"))] let source = String::from_utf8(source_bytes) .map_err(|err| self.new_os_error(err.to_string()))?; - let code_obj = self - .compile(&source, compiler::Mode::Exec, path) - .map_err(|err| err.into_pyexception(self, Some(&source)))?; + let code_obj = self.compile_with_filename( + &source, + compiler::Mode::Exec, + filename, + self.compile_opts(), + Some(identifier!(self, __main__)), + )?; self.run_code_obj(code_obj, scope)?; } Err(err) => { @@ -138,43 +174,21 @@ mod file_run { } } - fn null_byte_syntax_error( - vm: &VirtualMachine, - path: &str, - source_bytes: &[u8], - null_at: usize, - ) -> PyBaseExceptionRef { - let before = &source_bytes[..null_at]; - let lineno = before.iter().filter(|&&b| b == b'\n').count() + 1; - let line_start = before - .iter() - .rposition(|&b| b == b'\n') - .map_or(0, |i| i + 1); - let line = String::from_utf8_lossy(&source_bytes[line_start..null_at]); - let syntax_error = vm.new_exception_msg( - vm.ctx.exceptions.syntax_error.to_owned(), - "source code cannot contain null bytes".into(), - ); - let obj = syntax_error.as_object(); - obj.set_attr("filename", vm.ctx.new_str(path), vm).unwrap(); - obj.set_attr("lineno", vm.ctx.new_int(lineno), vm).unwrap(); - obj.set_attr("text", vm.ctx.new_str(format!("{line}\n")), vm) - .unwrap(); - syntax_error - } - fn set_main_loader( module_dict: &Py, - filename: &str, + filename: &Py, loader_name: &str, vm: &VirtualMachine, ) -> PyResult<()> { vm.import("importlib.machinery", 0)?; - let sys_modules = vm.sys_module.get_attr(identifier!(vm, modules), vm)?; + let sys_modules = vm.sys_modules(); let machinery = sys_modules.get_item("importlib.machinery", vm)?; let loader_name = vm.ctx.new_str(loader_name); let loader_class = machinery.get_attr(&loader_name, vm)?; - let loader = loader_class.call((identifier!(vm, __main__).to_owned(), filename), vm)?; + let loader = loader_class.call( + (identifier!(vm, __main__).to_owned(), filename.to_owned()), + vm, + )?; module_dict.set_item("__loader__", loader, vm)?; Ok(()) } @@ -184,16 +198,15 @@ mod file_run { /// Detection is performed by: /// 1. Checking if the filename ends with ".pyc" /// 2. If not, reading the first 2 bytes and comparing with the magic number - fn maybe_pyc_file(path: &str) -> bool { - if path.ends_with(".pyc") { + fn maybe_pyc_file(path: &Path) -> bool { + if path.as_os_str().as_encoded_bytes().ends_with(b".pyc") { return true; } maybe_pyc_file_with_magic(path).unwrap_or(false) } - fn maybe_pyc_file_with_magic(path: &str) -> std::io::Result { - let path_obj = std::path::Path::new(path); - if !path_obj.is_file() { + fn maybe_pyc_file_with_magic(path: &Path) -> std::io::Result { + if !path.is_file() { return Ok(false); } @@ -216,6 +229,403 @@ mod file_run { } } +/// One line of interactive input: raw bytes read from stdin, or text from a +/// line editor. +pub enum InteractiveLine { + Bytes(Vec), + Text(String), +} + +/// Source of one interactive statement, ready to be compiled. +struct InteractiveSource { + source: String, + parsed: compiler::InteractiveInput, +} + +impl VirtualMachine { + /// _Py_FdIsInteractive(stdin, "") + pub fn stdin_is_interactive(&self) -> bool { + use std::io::IsTerminal; + std::io::stdin().is_terminal() || self.state.config.settings.interactive + } + + /// _PyRun_AnyFile(stdin, "") + /// + /// Run stdin as an interactive session or as a script. + pub fn run_any_stdin(&self) -> PyResult<()> { + if self.stdin_is_interactive() { + self.run_interactive_loop(|prompt| self.stdio_readline(prompt)) + } else { + self.run_simple_stdin() + } + } + + /// _PyRun_InteractiveLoop + /// + /// `readline` plays the role of `PyOS_Readline`: it returns `Ok(None)` at + /// the end of input. + pub fn run_interactive_loop( + &self, + mut readline: impl FnMut(&str) -> PyResult>, + ) -> PyResult<()> { + for (name, default) in [("ps1", ">>> "), ("ps2", "... ")] { + if self.sys_module.dict().get_item_opt(name, self)?.is_none() { + let _ = self + .sys_module + .set_attr(name, self.ctx.new_str(default), self); + } + } + let mut flags = CodeFlags::empty(); + let mut nomem_count = 0; + loop { + match self.run_interactive_one(&mut readline, &mut flags) { + Ok(true) => nomem_count = 0, + // E_EOF + Ok(false) => return Ok(()), + Err(exc) => { + // Prevent an endless loop after multiple consecutive + // MemoryErrors while still allowing an interactive + // command to fail with a MemoryError. + if exc.fast_isinstance(self.ctx.exceptions.memory_error) { + nomem_count += 1; + if nomem_count > 16 { + return Err(exc); + } + } else { + nomem_count = 0; + } + if !self.config_inspect() + && exc.fast_isinstance(self.ctx.exceptions.system_exit) + { + return Err(exc); + } + self.print_uncaught_exception(&exc); + } + } + } + } + + /// _PyRun_InteractiveOne + /// + /// Read, compile and run one interactive statement in `__main__`. + /// Return `Ok(false)` at the end of input. + fn run_interactive_one( + &self, + readline: &mut impl FnMut(&str) -> PyResult>, + flags: &mut CodeFlags, + ) -> PyResult { + let Some(InteractiveSource { source, parsed }) = + self.interactive_parse(readline, *flags)? + else { + return Ok(false); + }; + let main_module = self.add_main_module()?; + // _PyAST_Compile merges the future features of the parsed statement + // into the flags before code generation. + *flags |= parsed.future_features; + self.run_interactive_mod(&source, parsed.empty, *flags, &main_module) + .inspect_err(|exc| self.fix_syntax_error_text(exc, &source))?; + self.flush_io(); + Ok(true) + } + + /// pyrun_one_parse_ast + /// + /// Read lines with `sys.ps1` and `sys.ps2` prompts until they form one + /// complete interactive statement. Return `None` at the end of input. + fn interactive_parse( + &self, + readline: &mut impl FnMut(&str) -> PyResult>, + flags: CodeFlags, + ) -> PyResult> { + let encoding = self + .sys_module + .get_attr("stdin", self) + .and_then(|stdin| stdin.get_attr("encoding", self)) + .ok() + .and_then(|encoding| encoding.downcast::().ok()) + .and_then(|encoding| encoding.to_str().map(str::to_owned)) + .unwrap_or_else(|| "utf-8".to_owned()); + let prompt = |name| { + self.sys_module + .get_attr(name, self) + .and_then(|prompt| prompt.str(self)) + .ok() + .and_then(|prompt| prompt.to_str().map(str::to_owned)) + .unwrap_or_default() + }; + let ps1 = prompt("ps1"); + let ps2 = prompt("ps2"); + + // _PyParser_InteractiveASTFromFile + self.audit("compile", || (self.ctx.none(), self.ctx.new_str("")))?; + let mut source = String::new(); + let mut raw_source = Vec::new(); + #[cfg(feature = "parser")] + let mut warnings = super::compile::InteractiveWarnings::default(); + loop { + let line = readline(if source.is_empty() { &ps1 } else { &ps2 }); + // tok_underflow_interactive ends the prompt line at EOF or on an + // interrupted read. + if !matches!(line, Ok(Some(_))) { + writeln!(stdlib::sys::PyStderr(self)); + } + let (terminated, unterminated_fragment, eof) = match line? { + None if source.is_empty() => return Ok(None), + None => { + if !source.ends_with('\n') { + source.push('\n'); + } + (true, false, true) + } + Some(InteractiveLine::Text(mut line)) => { + if !line.ends_with('\n') { + line.push('\n'); + } + let line = line.replace("\r\n", "\n"); + let terminated = line == "\n"; + source.push_str(&line); + (terminated, false, false) + } + Some(InteractiveLine::Bytes(line)) => { + let unterminated_fragment = !line.ends_with(b"\n"); + let terminated = line == b"\n" || line == b"\r\n"; + raw_source.extend_from_slice(&line); + source = self + .state + .codec_registry + .decode_text( + self.ctx.new_bytes(raw_source.clone()).into(), + &encoding, + None, + self, + )? + .to_str() + .ok_or_else(|| { + self.new_exception_msg( + self.ctx.exceptions.unicode_error.to_owned(), + "stdin source contains surrogates".into(), + ) + })? + .replace("\r\n", "\n"); + (terminated, unterminated_fragment, false) + } + }; + #[cfg(feature = "parser")] + self.emit_interactive_parser_warnings( + &source, + "", + Some(identifier!(self, __main__)), + flags.contains(CodeFlags::FUTURE_BARRY_AS_BDFL), + &mut warnings, + ) + .map_err(|error| { + super::compile::VmCompileError::Warning(error).into_pyexception(self, Some(&source)) + })?; + let parsed = match compiler::interactive_input(&source, "", flags, terminated) { + Ok(Some(parsed)) => parsed, + Ok(None) => continue, + Err(error) => { + let unclosed = matches!(&error, compiler::CompileError::Parse(error) + if error.is_unclosed_bracket || error.is_unclosed_string); + let error = super::compile::VmCompileError::Compile(error) + .into_pyexception_maybe_incomplete(self, Some(&source), !terminated); + if !eof + && (unclosed + || (!terminated + && error + .fast_isinstance(self.ctx.exceptions.incomplete_input_error))) + { + continue; + } + return Err(error); + } + }; + // A final fragment without a newline is not a complete line yet. + // Its warnings and definitive syntax errors are reported now, but + // it is only accepted once the next read reports EOF. + if unterminated_fragment { + continue; + } + return Ok(Some(InteractiveSource { source, parsed })); + } + } + + /// run_mod for interactive input + fn run_interactive_mod( + &self, + source: &str, + empty: bool, + flags: CodeFlags, + main_module: &Py, + ) -> PyResult<()> { + let filename = get_interactive_filename( + "", + self.state + .interactive_src_count + .fetch_add(1, Ordering::Relaxed), + ); + let mode = if empty { + compiler::Mode::Exec + } else { + compiler::Mode::Single + }; + let opts = compiler::CompileOpts { + future_features: flags, + ..self.compile_opts() + }; + let code = self + .compile_after_parser_warnings( + source, + mode, + filename, + opts, + Some(identifier!(self, __main__)), + ) + .map_err(|error| error.into_pyexception(self, Some(source)))?; + let linecache = self.import("linecache", 0)?; + linecache.get_attr("_register_code", self)?.call( + ( + code.clone(), + self.ctx.new_str(source), + self.ctx.new_str(""), + ), + self, + )?; + self.audit("exec", || (code.clone(),))?; + let globals = main_module.dict(); + self.run_code_obj(code, Scope::with_builtins(None, globals, self))?; + Ok(()) + } + + /// Fix the `text` attribute of a SyntaxError raised by interactive input. + fn fix_syntax_error_text(&self, exc: &Py, source: &str) { + if !exc.fast_isinstance(self.ctx.exceptions.syntax_error) { + return; + } + let source = self.ctx.new_str(source); + let lines = source.splitlines(crate::anystr::SplitLinesArgs { keepends: true }, self); + let Ok(lineno) = exc + .as_object() + .get_attr("lineno", self) + .and_then(|lineno| lineno.try_into_value::(self)) + else { + return; + }; + if lineno > 0 + && let Some(line) = lines.get((lineno - 1) as usize) + { + let _ = exc.as_object().set_attr("text", line.clone(), self); + } + } + + /// PyOS_StdioReadline + /// + /// Write the prompt to stderr and read one line from stdin. + fn stdio_readline(&self, prompt: &str) -> PyResult> { + let mut line = Vec::new(); + let mut prompt = prompt; + loop { + let result = crate::readline::stdio_readline_bytes(prompt, &mut line); + prompt = ""; + match result { + Ok(0) if line.is_empty() => return Ok(None), + Ok(_) => return Ok(Some(InteractiveLine::Bytes(line))), + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => { + self.check_signals()?; + } + // A read error ends the input like EOF. + Err(_) if line.is_empty() => return Ok(None), + Err(_) => return Ok(Some(InteractiveLine::Bytes(line))), + } + } + } + + /// _PyRun_SimpleFile(stdin, "") + fn run_simple_stdin(&self) -> PyResult<()> { + use std::io::Read; + self.with_simple_run(&self.ctx.new_str(""), |module_dict| { + // _PyParser_ASTFromFile + self.audit("compile", || (self.ctx.none(), self.ctx.new_str("")))?; + let mut bytes = Vec::new(); + let mut buf = [0; 8192]; + loop { + match std::io::stdin().read(&mut buf) { + Ok(0) => break, + Ok(n) => bytes.extend_from_slice(&buf[..n]), + Err(error) if error.kind() == std::io::ErrorKind::Interrupted => { + self.check_signals()?; + } + // A read error ends the input like EOF. + Err(_) => break, + } + } + if let Some(null_at) = bytes.iter().position(|&b| b == 0) { + return Err(null_byte_syntax_error( + self, + &self.ctx.new_str(""), + &bytes, + null_at, + )); + } + #[cfg(feature = "parser")] + let source = self.decode_source_bytes(&bytes, "", false)?; + #[cfg(not(feature = "parser"))] + let source = + String::from_utf8(bytes).map_err(|error| self.new_os_error(error.to_string()))?; + let code = self + .compile_with_opts_and_module( + &source, + compiler::Mode::Exec, + "", + self.compile_opts(), + Some(identifier!(self, __main__)), + &[], + ) + .map_err(|error| error.into_pyexception(self, Some(&source)))?; + self.audit("exec", || (code.clone(),))?; + let scope = Scope::with_builtins(None, module_dict.to_owned(), self); + self.run_code_obj(code, scope).map(drop) + }) + } +} + +fn null_byte_syntax_error( + vm: &VirtualMachine, + path: &Py, + source_bytes: &[u8], + null_at: usize, +) -> PyBaseExceptionRef { + let before = &source_bytes[..null_at]; + let lineno = before.iter().filter(|&&b| b == b'\n').count() + 1; + let line_start = before + .iter() + .rposition(|&b| b == b'\n') + .map_or(0, |i| i + 1); + let line = String::from_utf8_lossy(&source_bytes[line_start..null_at]); + let syntax_error = vm.new_exception_msg( + vm.ctx.exceptions.syntax_error.to_owned(), + "source code cannot contain null bytes".into(), + ); + let obj = syntax_error.as_object(); + obj.set_attr("filename", path.to_owned(), vm).unwrap(); + obj.set_attr("lineno", vm.ctx.new_int(lineno), vm).unwrap(); + obj.set_attr("text", vm.ctx.new_str(format!("{line}\n")), vm) + .unwrap(); + syntax_error +} + +/// get_interactive_filename +fn get_interactive_filename(filename: &str, count: usize) -> String { + match filename + .strip_prefix('<') + .and_then(|name| name.strip_suffix('>')) + { + Some(middle) => format!("<{middle}-{count}>"), + None => format!("{filename}-{count}"), + } +} + #[cfg(test)] mod tests { use crate::object::AsObject; diff --git a/crates/vm/src/vm/runtime.rs b/crates/vm/src/vm/runtime.rs index 3f447fcbd3c..3994e80b6c6 100644 --- a/crates/vm/src/vm/runtime.rs +++ b/crates/vm/src/vm/runtime.rs @@ -48,6 +48,8 @@ pub struct InterpreterInfo { } struct RegistryEntry { + #[cfg(feature = "threading")] + thread_factory: alloc::sync::Weak, whence: InterpreterWhence, /// Weak handle so the registry does not keep interpreters alive. /// Type matches `PyRc` (Arc when threading, Rc otherwise). @@ -296,6 +298,10 @@ pub(crate) fn alloc_interpreter_id() -> i64 { registry().next_id.fetch_add(1, Ordering::Relaxed) } +pub(crate) fn next_interpreter_id() -> i64 { + registry().next_id.load(Ordering::Relaxed) +} + /// Gate between registering an interpreter and a collection's stop-the-world. /// /// A collection snapshots the registry, stops every interpreter in the @@ -334,6 +340,8 @@ fn insert_registry_entry(state: &PyRc) { entries.insert( state.interpreter_id, RegistryEntry { + #[cfg(feature = "threading")] + thread_factory: alloc::sync::Weak::new(), whence: state.whence, state: PyRc::downgrade(state), }, @@ -371,6 +379,35 @@ pub fn lookup_interpreter(id: i64) -> Option> { entries.get(&id).and_then(|e| e.state.upgrade()) } +#[cfg(feature = "threading")] +pub(crate) fn publish_thread_factory( + id: i64, + factory: &alloc::sync::Arc, +) { + if let Some(entry) = registry().entries.lock().get_mut(&id) { + entry.thread_factory = alloc::sync::Arc::downgrade(factory); + } +} + +/// Create a fresh thread state for any live, initialized interpreter, including +/// an externally owned main interpreter. Never execute or drop Python roots +/// while holding the registry lock. +#[cfg(feature = "threading")] +pub(crate) fn new_interpreter_thread(id: i64) -> Option { + let (state, factory) = { + let entries = registry().entries.lock(); + let entry = entries.get(&id)?; + (entry.state.clone(), entry.thread_factory.clone()) + }; + let state = state.upgrade()?; + if !state.ready.load(Ordering::Acquire) || state.finalizing.load(Ordering::Acquire) { + return None; + } + // Thread attachment checks finalization again, closing the race with a + // finalizer that starts after this lookup. + Some(factory.upgrade()?.new_thread(state)) +} + /// List all currently registered (still-alive) interpreters. #[must_use] pub fn list_interpreters() -> Vec { diff --git a/crates/vm/src/vm/setting.rs b/crates/vm/src/vm/setting.rs index f582e51f1e1..4dc9b8def25 100644 --- a/crates/vm/src/vm/setting.rs +++ b/crates/vm/src/vm/setting.rs @@ -1,10 +1,11 @@ use core::num::NonZeroI32; -#[cfg(feature = "flame-it")] use std::ffi::OsString; /// Path configuration computed at runtime (like PyConfig path outputs) #[derive(Debug, Clone, Default)] pub struct Paths { + /// program_name: the name the interpreter was invoked as + pub program_name: OsString, /// sys.executable pub executable: String, /// sys._base_executable (original interpreter in venv) @@ -19,8 +20,8 @@ pub struct Paths { pub base_exec_prefix: String, /// sys._stdlib_dir pub stdlib_dir: Option, - /// Computed module_search_paths (complete sys.path) - pub module_search_paths: Vec, + /// Computed native search paths, decoded with the filesystem codec into sys.path. + pub module_search_paths: Vec, } /// Combined configuration: user settings + computed paths @@ -30,12 +31,24 @@ pub struct Paths { pub struct PyConfig { pub settings: Settings, pub paths: Paths, + pub(super) filesystem: alloc::sync::Arc, } impl PyConfig { #[must_use] - pub fn new(settings: Settings, paths: Paths) -> Self { - Self { settings, paths } + pub fn new(mut settings: Settings, paths: Paths) -> Self { + if cfg!(windows) && settings.legacy_windows_fs_encoding { + settings.utf8_mode = 0; + } + if settings.utf8_mode < 0 { + settings.utf8_mode = 1; + } + let filesystem = alloc::sync::Arc::new(super::filesystem::FilesystemCodec::new(&settings)); + Self { + settings, + paths, + filesystem, + } } } @@ -62,20 +75,20 @@ pub struct Settings { // int tracemalloc; // int perf_profiling; - // int import_time; + /// -X importtime, PYTHONPROFILEIMPORTTIME: 2 also reports cached imports. + pub import_time: u8, /// -X no_debug_ranges: disable column info in bytecode pub code_debug_ranges: bool, // int show_ref_count; // int dump_refs; // wchar_t *dump_refs_file; // int malloc_stats; - // wchar_t *filesystem_encoding; - // wchar_t *filesystem_errors; - // wchar_t *pycache_prefix; + /// -X pycache_prefix, PYTHONPYCACHEPREFIX + pub pycache_prefix: Option, // int parse_argv; // PyWideStringList orig_argv; - /// sys.argv - pub argv: Vec, + /// sys.argv, decoded with the filesystem encoding during sys initialization. + pub argv: Vec, // spell-checker:ignore Xfoo /// -Xfoo[=bar] @@ -100,6 +113,10 @@ pub struct Settings { /// -X context_aware_warnings, whether warnings are context aware pub context_aware_warnings: bool, + /// -X lazy_imports, PYTHON_LAZY_IMPORTS: -1 for normal, 1 for all. + /// This startup value is independent of later sys.set_lazy_imports() calls. + pub lazy_imports: i8, + /// -i pub inspect: bool, @@ -124,15 +141,22 @@ pub struct Settings { /// -u, PYTHONUNBUFFERED=x pub buffered_stdio: bool, + /// Standard descriptors closed at executable startup, before runtime sanitization. + /// Embeddings normally leave this unset and inspect current descriptors instead. + pub closed_stdio: [bool; 3], + /// PYTHONIOENCODING - stdio encoding pub stdio_encoding: Option, /// PYTHONIOENCODING - stdio error handler pub stdio_errors: Option, pub utf8_mode: i8, + /// Windows-only legacy filesystem bytes codec (PEP 529). + pub legacy_windows_fs_encoding: bool, /// --check-hash-based-pycs pub check_hash_pycs_mode: CheckHashPycsMode, - // int use_frozen_modules; + /// -X frozen_modules=on|off (bootstrap modules remain available). + pub use_frozen_modules: bool, /// -P pub safe_path: bool, @@ -145,10 +169,14 @@ pub struct Settings { // /* --- Path configuration inputs ------------ */ // int pathconfig_warnings; // wchar_t *program_name; - /// Environment PYTHONPATH (and RUSTPYTHONPATH) - pub path_list: Vec, + /// Native PYTHONPATH (and RUSTPYTHONPATH) entries, retained without Unicode loss. + pub path_list: Vec, + + /// Standalone CLI ._pth path override; embedded applications do not discover these files. + pub under_pth: Option, - // wchar_t *home; + /// PYTHONHOME: explicit prefix, optionally followed by the exec prefix. + pub home: Option, // wchar_t *platlibdir; /// -d command line switch pub debug: u8, @@ -180,7 +208,7 @@ pub enum CheckHashPycsMode { impl Settings { #[must_use] pub fn with_path(mut self, path: String) -> Self { - self.path_list.push(path); + self.path_list.push(path.into()); self } } @@ -196,6 +224,7 @@ impl Default for Settings { install_signal_handlers: true, user_site_directory: true, import_site: true, + use_frozen_modules: true, ignore_environment: false, verbose: 0, quiet: false, @@ -208,18 +237,25 @@ impl Default for Settings { warn_default_encoding: false, thread_inherit_context: false, context_aware_warnings: false, + lazy_imports: -1, warnoptions: vec![], path_list: vec![], + under_pth: None, + home: None, argv: vec![], hash_seed: None, faulthandler: false, + import_time: 0, + pycache_prefix: None, code_debug_ranges: true, buffered_stdio: true, + closed_stdio: [false; 3], check_hash_pycs_mode: CheckHashPycsMode::Default, allow_external_library: cfg!(feature = "importlib"), stdio_encoding: None, stdio_errors: None, utf8_mode: -1, + legacy_windows_fs_encoding: false, int_max_str_digits: 4300, cpu_count: None, #[cfg(feature = "flame-it")] diff --git a/crates/vm/src/vm/stop_the_world.rs b/crates/vm/src/vm/stop_the_world.rs new file mode 100644 index 00000000000..a8b43c595a5 --- /dev/null +++ b/crates/vm/src/vm/stop_the_world.rs @@ -0,0 +1,175 @@ +/// RAII barrier that parks every other thread for the pointer-reading phases +/// of a collection and lets them run again before finalizers execute. +/// +/// Reference subtraction, the reachability walk and the strong-reference +/// snapshot dereference the interpreter state of every tracked object, +/// including the `localsplus` of frames that other threads are actively +/// executing. Those writes carry no synchronization, so the reads are only +/// well-defined while all other threads are parked at a safepoint. Restarting +/// happens explicitly once the snapshot has pinned every object; `Drop` is a +/// backstop that also restarts on the early-return paths. +/// +/// A collection acts on one interpreter's objects, but its candidates include +/// the ones no interpreter owns, which every interpreter can reference and so +/// incref. Reading a refcount that another interpreter is changing is what +/// makes an object look unreachable when it is not, so every live interpreter +/// is stopped, not just the collecting one. Stopping in `runtime` id order +/// is deterministic. One process-wide STW transaction covers the entire group, +/// preventing a single-interpreter requester from stopping a collector while +/// that collector waits for a different interpreter. +#[cfg(feature = "threading")] +pub(crate) struct StopTheWorldGroup { + /// Entire interpreter snapshot, retained through restart even on unwind. + /// Dropping the last state can release Python objects and run finalizers, + /// so both stopped and not-yet-stopped states must outlive the transaction + /// and the collection's generation locks. + states: Vec>, + stopped_count: usize, + /// Keeps interpreters from registering between the snapshot below and the + /// restart. One registered in that window would be missing from `states`, + /// so its bootstrap would keep running — and mutating the shared generation + /// lists — while this collection reads them. + admission: Option>, + /// Acquired before admission and retained until every state is restarted. + transaction: Option, + restarted: bool, +} + +#[cfg(feature = "threading")] +impl StopTheWorldGroup { + /// Request stop-the-world on every live interpreter when the current thread + /// has an attached VM. Falls back to no barrier when no VM is attached (the + /// tracked-object reads then run without other threads only if the caller + /// guarantees it). + pub(crate) fn new() -> Self { + // No attached VM means no interpreter is running Python on this thread; + // keep the historical no-barrier fallback. + if !crate::vm::thread::current_vm_is_set() { + return Self { + states: Vec::new(), + stopped_count: 0, + admission: None, + transaction: None, + restarted: true, + }; + } + + // Accumulate into a live `Self` rather than a bare Vec: if a later + // `stop_the_world` unwinds, dropping this guard restarts the + // interpreters already stopped, instead of leaving their threads parked + // and their exclusion held forever. + let transaction = crate::vm::StopTheWorldTransaction::acquire(); + let mut guard = Self { + states: Vec::new(), + stopped_count: 0, + admission: Some(crate::vm::runtime::lock_admission_for_stop()), + transaction: Some(transaction), + restarted: false, + }; + guard.states = crate::vm::runtime::live_interpreter_states(); + for state in &guard.states { + state + .stop_the_world + .stop_with_transaction(state, guard.transaction.as_ref().unwrap()); + guard.stopped_count += 1; + } + guard + } + + /// Restart the world. Idempotent. + pub(crate) fn restart(&mut self) { + if self.restarted { + return; + } + self.restarted = true; + // Reverse of the stop order. The references stay until this guard is + // dropped; see the field comment. + for state in self.states[..self.stopped_count].iter().rev() { + state.stop_the_world.start_the_world(state); + } + // Nothing is parked any more, so registration may resume. + self.admission = None; + self.transaction = None; + } + + /// Whether this collection actually stopped the world. + #[cfg(all(unix, debug_assertions))] + pub(crate) fn is_stopped(&self) -> bool { + self.stopped_count != 0 + } +} + +#[cfg(feature = "threading")] +impl Drop for StopTheWorldGroup { + fn drop(&mut self) { + self.restart(); + } +} + +/// Fork owns the same barrier as GC, with child-only repair and deferred drops. +#[cfg(all(unix, feature = "host_env"))] +pub(crate) struct ForkStopTheWorld { + // ThreadSlot owns Python exception/trace/profile references. Keep removed + // slots alive until repair has finished and the transaction is released. + retained_slots: Vec, + // Field order keeps interpreter states alive while deferred Python roots + // above are destroyed, after Drop has released the transaction. + group: StopTheWorldGroup, + child_repair_incomplete: bool, +} + +#[cfg(all(unix, feature = "host_env"))] +impl ForkStopTheWorld { + pub(crate) fn new() -> Self { + let group = StopTheWorldGroup::new(); + Self { + retained_slots: Vec::new(), + group, + child_repair_incomplete: false, + } + } + + pub(crate) fn restart(&mut self) { + self.group.restart(); + } + + /// # Safety + /// Call only in the single surviving child immediately after fork. + pub(crate) unsafe fn begin_child_repair(&mut self) { + self.child_repair_incomplete = true; + // Never restart inherited thread registries on child unwind. + self.group.restarted = true; + // The dependency's automatic atfork registration can race its first + // parker. Explicitly reset queues before even unlocking admission. + parking_lot_core::reinit_after_fork(); + // runtime::reinit_after_fork must not zero a mutex with a live guard. + self.group.admission = None; + crate::vm::thread::retain_cached_slots_after_fork(&mut self.retained_slots); + } + + /// Preserve registry-owned Python references before child cleanup clears it. + /// The registry's lock must already have been reset in the child. + pub(crate) fn retain_thread_slots(&mut self, state: &crate::vm::PyGlobalState) { + self.retained_slots + .extend(state.thread_frames.lock().values().cloned()); + } + + /// Repair must be complete before Python callbacks or deferred slot drops. + pub(crate) fn finish_child_repair(&mut self) { + self.group.transaction = None; + self.child_repair_incomplete = false; + } +} + +#[cfg(all(unix, feature = "host_env"))] +impl Drop for ForkStopTheWorld { + fn drop(&mut self) { + if self.child_repair_incomplete { + // Partial child repair cannot support Rust unwind recovery or + // Python destruction. Like a fatal child-setup failure, abort + // before destroying the retained interpreter/thread roots. + rustpython_host_env::os::abort(); + } + self.group.restart(); + } +} diff --git a/crates/vm/src/vm/thread.rs b/crates/vm/src/vm/thread.rs index e1bc40c44b0..460bc8de750 100644 --- a/crates/vm/src/vm/thread.rs +++ b/crates/vm/src/vm/thread.rs @@ -27,6 +27,10 @@ use itertools::Itertools; use std::collections::HashMap; use std::thread_local; +pub(crate) mod critical_section; +pub use critical_section::PyOperation; +pub(crate) mod lock; + /// Thread states for stop-the-world support (`_Py_THREAD_*`). /// /// DETACHED: not executing Python bytecode (in native code, or idle) @@ -96,6 +100,9 @@ pub struct ThreadSlot { pub thread: std::thread::Thread, /// QSBR state for deferred memory reclamation. pub(crate) qsbr: Arc, + /// `tstate->critical_section`: tagged pointer to the top-most critical + /// section. Only the owning thread reads or writes it. + pub(crate) critical_section: AtomicUsize, } #[cfg(feature = "threading")] @@ -142,7 +149,11 @@ thread_local! { /// drops it while the VM is still current, so object destructors can still find /// their VM. #[cfg(feature = "threading")] - static GILSTATE_VM: RefCell>> = const { RefCell::new(None) }; + static GILSTATE_VM: GilStateVm = const { GilStateVm(RefCell::new(None)) }; + + // No destructor: this remains readable while other TLS keys are torn down. + // An unmatched GILState attachment cannot run Python from its TLS destructor. + static PYTHON_CALLBACKS_DISABLED: Cell = const { Cell::new(false) }; pub(crate) static COROUTINE_ORIGIN_TRACKING_DEPTH: Cell = const { Cell::new(0) }; @@ -156,6 +167,12 @@ thread_local! { static INTERP_THREAD_SLOTS: RefCell> = RefCell::new(HashMap::new()); + /// Critical sections of the slots `purge_other_interpreter_slots_after_fork` + /// dropped, carried into the slot the next enter of that interpreter builds. + #[cfg(feature = "threading")] + static FORKED_CRITICAL_SECTIONS: RefCell> = + RefCell::new(HashMap::new()); + /// Current thread's slot for the currently entered interpreter. #[cfg(feature = "threading")] static CURRENT_THREAD_SLOT: RefCell> = const { RefCell::new(None) }; @@ -181,6 +198,85 @@ thread_local! { } +#[cfg(feature = "threading")] +struct GilStateVm(RefCell>>); + +#[cfg(feature = "threading")] +impl core::ops::Deref for GilStateVm { + type Target = RefCell>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +#[cfg(feature = "threading")] +impl Drop for GilStateVm { + fn drop(&mut self) { + if let Some(_owner) = self.0.get_mut().take() { + // Matched release takes the owner before this TLS destructor runs. + // This is only defensive cleanup for an unmatched attachment: + // arbitrary callback TLS may already have been destroyed. + PYTHON_CALLBACKS_DISABLED.with(|disabled| disabled.set(true)); + } + } +} + +fn without_python_callbacks(f: impl FnOnce() -> R) -> R { + PYTHON_CALLBACKS_DISABLED.with(|disabled| { + let old = disabled.replace(true); + scopeguard::defer! { disabled.set(old); } + f() + }) +} + +/// Drop only the asynchronous-exception root, before its owner loses its VM. +/// Unlike an enter/run scope, this is a terminal operation on the thread state. +pub(super) fn clear_async_exception_on_owner_drop(vm: &VirtualMachine) { + if !vm.async_exception.has_reference() { + vm.clear_async_exception(); + return; + } + if PYTHON_CALLBACKS_DISABLED.with(Cell::get) { + vm.clear_async_exception(); + return; + } + #[cfg(feature = "threading")] + let can_attach = (!vm.state.finalizing.load(Ordering::Acquire) + || crate::stdlib::_thread::get_ident() == vm.state.finalizing_thread_ident.load()) + && INTERP_THREAD_SLOTS + .try_with(|slots| { + slots + .borrow() + .get(&vm.state.interpreter_id) + .is_none_or(|slot| { + slot.state.load(Ordering::Acquire) != ThreadState::ShuttingDown as i32 + }) + }) + .unwrap_or(false); + #[cfg(not(feature = "threading"))] + let can_attach = true; + + if !can_attach { + // Python may no longer execute on this thread. Do not attach and hang, + // or route a dead interpreter's finalizers through an enclosing VM. + without_python_callbacks(|| vm.clear_async_exception()); + return; + } + #[cfg(feature = "threading")] + let had_slot = + INTERP_THREAD_SLOTS.with(|slots| slots.borrow().contains_key(&vm.state.interpreter_id)); + enter_vm(vm, || { + vm.clear_async_exception(); + #[cfg(feature = "threading")] + if !had_slot { + // A drop-only attachment must not leave a newly registered slot. + // Existing slots may belong to an enclosing VM and stay untouched. + cleanup_current_thread_frames(vm); + } + }); +} + #[must_use] pub fn current_vm_is_set() -> bool { VM_STACK.with(|vms| !vms.borrow().is_empty()) @@ -399,6 +495,9 @@ pub fn release_current_thread(state: CurrentVmAttachState) { } let gilstate_vm = GILSTATE_VM.with(|gilstate_vm| gilstate_vm.borrow_mut().take()); + if let Some(owner) = &gilstate_vm { + owner.vm.clear_async_exception(); + } drop(gilstate_vm); VM_STACK.with(|vms| { @@ -457,7 +556,14 @@ fn ensure_thread_slot(vm: &VirtualMachine) -> CurrentFrameSlot { .unwrap_or_else(|| vm.ctx.none()), ), state: core::sync::atomic::AtomicI32::new( - if vm.state.stop_the_world.requested.load(Ordering::Acquire) { + if vm.state.finalizing.load(Ordering::Acquire) + && vm.state.finalizing_thread_ident.load() != thread_id + { + // A daemon may first attach after the shutdown stop. + // Mark the slot rather than hanging here: switching VMs + // must detach the enclosing interpreter first. + ThreadState::ShuttingDown as i32 + } else if vm.state.stop_the_world.requested.load(Ordering::Acquire) { // Match init_threadstate(): new thread-state starts // suspended while stop-the-world is active. ThreadState::Suspended as i32 @@ -468,6 +574,11 @@ fn ensure_thread_slot(vm: &VirtualMachine) -> CurrentFrameSlot { stop_requested: core::sync::atomic::AtomicBool::new(false), thread: std::thread::current(), qsbr: crate::object::qsbr::QSBR.register(), + critical_section: AtomicUsize::new( + FORKED_CRITICAL_SECTIONS + .with(|forked| forked.borrow_mut().remove(&interp_id)) + .unwrap_or(0), + ), }); registry.insert(thread_id, new_slot.clone()); drop(registry); @@ -483,6 +594,13 @@ pub fn current_thread_slot() -> Option { CURRENT_THREAD_SLOT.with(|slot| slot.borrow().clone()) } +/// Keep cached/orphaned slots alive until child repair permits Python drops. +#[cfg(all(unix, feature = "threading", feature = "host_env"))] +pub(crate) fn retain_cached_slots_after_fork(retained: &mut Vec) { + INTERP_THREAD_SLOTS.with(|slots| retained.extend(slots.borrow().values().cloned())); + CURRENT_THREAD_SLOT.with(|slot| retained.extend(slot.borrow().iter().cloned())); +} + /// Make `slot` the current thread slot (and the cached top-frame pointer). #[cfg(feature = "threading")] fn set_current_thread_slot(slot: CurrentFrameSlot) { @@ -586,6 +704,7 @@ fn hang_thread() -> ! { pub fn hang_current_thread(state: &PyGlobalState) -> ! { CURRENT_THREAD_SLOT.with(|slot| { if let Some(s) = slot.borrow().as_ref() { + critical_section::suspend_all(s); let prev = s .state .swap(ThreadState::ShuttingDown as i32, Ordering::AcqRel); @@ -663,6 +782,11 @@ fn attach_thread(vm: &VirtualMachine) { } } }); + if let Some(s) = current_thread_slot() { + // Resume previous critical section. This acquires the lock(s) from the + // top-most critical section. + critical_section::resume(&s); + } // A stop-the-world may have been requested while this thread was detached. // Honoring it here (rather than only at the next bytecode safepoint) keeps // a thread doing rapid allow_threads calls from re-attaching and running @@ -679,6 +803,7 @@ fn attach_thread(vm: &VirtualMachine) { fn detach_thread() { CURRENT_THREAD_SLOT.with(|slot| { if let Some(s) = slot.borrow().as_ref() { + critical_section::suspend_all(s); match s.state.compare_exchange( ThreadState::Attached as i32, ThreadState::Detached as i32, @@ -721,10 +846,8 @@ pub fn allow_threads(vm: &VirtualMachine, f: impl FnOnce() -> R) -> R { } detach_thread(); - let reattach_guard = scopeguard::guard(vm, attach_thread); - let result = f(); - drop(reattach_guard); - result + let _reattach_guard = scopeguard::guard(vm, attach_thread); + f() } /// No-op on non-threading builds. @@ -760,10 +883,8 @@ pub fn attach_for_callback(vm: &VirtualMachine, f: impl FnOnce() -> R) -> R { attach_thread(vm); // Detach again even if `f` unwinds, so the `allow_threads` this is nested // inside still finds the state it left behind. - let redetach_guard = scopeguard::guard((), |()| detach_thread()); - let result = f(); - drop(redetach_guard); - result + let _redetach_guard = scopeguard::guard((), |()| detach_thread()); + f() } /// No-op on non-threading builds. @@ -828,10 +949,10 @@ pub fn suspend_if_needed(state: &PyGlobalState) { #[cold] fn do_suspend(state: &PyGlobalState) { let stw = &state.stop_the_world; - CURRENT_THREAD_SLOT.with(|slot| { + let reattached = CURRENT_THREAD_SLOT.with(|slot| { let borrowed = slot.borrow(); let Some(s) = borrowed.as_ref() else { - return; + return false; }; // Decide whether to park while holding the thread registry. Both edges @@ -845,6 +966,12 @@ fn do_suspend(state: &PyGlobalState) { let park = { let _registry = state.thread_frames.lock(); if stw.requested.load(Ordering::Acquire) { + // Release critical sections before publishing SUSPENDED. Only + // this thread moves its slot out of ATTACHED, except to + // SHUTTING_DOWN, which hangs it below. + if s.state.load(Ordering::Acquire) == ThreadState::Attached as i32 { + critical_section::suspend_all(s); + } Some(s.state.compare_exchange( ThreadState::Attached as i32, ThreadState::Suspended as i32, @@ -861,7 +988,7 @@ fn do_suspend(state: &PyGlobalState) { match park { None => { super::stw_trace(format_args!("suspend skip not-requested")); - return; + return false; } Some(Ok(_)) => { // Consumed this thread's stop request bit. @@ -871,13 +998,13 @@ fn do_suspend(state: &PyGlobalState) { Some(ThreadState::Detached) => { // Leaving VM; caller will re-check on next entry. super::stw_trace(format_args!("suspend skip DETACHED")); - return; + return false; } Some(ThreadState::Suspended) => { // Already parked by another path. s.stop_requested.store(false, Ordering::Release); super::stw_trace(format_args!("suspend skip already-suspended")); - return; + return false; } Some(ThreadState::ShuttingDown) => { s.stop_requested.store(false, Ordering::Release); @@ -886,7 +1013,7 @@ fn do_suspend(state: &PyGlobalState) { } _ => { debug_assert!(false, "unexpected thread state in suspend: {state}"); - return; + return false; } }, } @@ -931,7 +1058,11 @@ fn do_suspend(state: &PyGlobalState) { } s.stop_requested.store(false, Ordering::Release); super::stw_trace(format_args!("suspend resume -> ATTACHED")); + true }); + if reattached && let Some(s) = current_thread_slot() { + critical_section::resume(&s); + } } #[cfg(feature = "threading")] @@ -1094,12 +1225,12 @@ pub fn get_current_frame() -> *const InterpreterFrame { /// Called from push_exception/pop_exception/set_exception. #[cfg(feature = "threading")] pub fn update_thread_exception(exc: Option) { - CURRENT_THREAD_SLOT.with(|slot| { - if let Some(s) = slot.borrow().as_ref() { - // SAFETY: Called only from the owning thread. The old ref is dropped - // here on the owning thread, which is safe. - let _old = unsafe { s.exception.swap(exc) }; - } + // Release the TLS borrow before dropping either exception: traceback + // locals can finalize another interpreter and re-enter this thread slot. + let slot = current_thread_slot(); + let _old = slot.and_then(|s| { + // SAFETY: Called only from the owning thread. + unsafe { s.exception.swap(exc) } }); } @@ -1125,6 +1256,12 @@ pub fn cleanup_current_thread_frames(vm: &VirtualMachine) { let slot_for_interp = INTERP_THREAD_SLOTS.with(|slots| slots.borrow_mut().remove(&interp_id)); let current_slot = CURRENT_THREAD_SLOT.with(|slot| slot.borrow().as_ref().cloned()); let slot_to_clean = slot_for_interp.or(current_slot); + debug_assert!( + slot_to_clean + .as_ref() + .is_none_or(|slot| slot.critical_section.load(Ordering::Relaxed) == 0), + "thread cleanup cannot abandon a critical section" + ); // A dying thread should not remain logically ATTACHED while its // thread-state slot is being removed. @@ -1221,6 +1358,9 @@ pub fn reinit_frame_slot_after_fork(vm: &VirtualMachine) { } }; let top_iframe_ptr = get_current_frame() as usize; + // The surviving thread keeps its critical sections. + let critical_section = + current_thread_slot().map_or(0, |slot| slot.critical_section.load(Ordering::Relaxed)); let new_slot = Arc::new(ThreadSlot { // The surviving child thread keeps executing its current frame chain. // Only publish heavy frames for signal safety. @@ -1236,6 +1376,7 @@ pub fn reinit_frame_slot_after_fork(vm: &VirtualMachine) { stop_requested: core::sync::atomic::AtomicBool::new(false), thread: std::thread::current(), qsbr: crate::object::qsbr::QSBR.register(), + critical_section: AtomicUsize::new(critical_section), }); FRAME_SLOT_CACHE.with(|cache| { #[cfg(unix)] @@ -1268,7 +1409,14 @@ pub fn reinit_frame_slot_after_fork(vm: &VirtualMachine) { #[cfg(feature = "threading")] pub fn purge_other_interpreter_slots_after_fork(keep_id: i64) { INTERP_THREAD_SLOTS.with(|slots| { - slots.borrow_mut().retain(|&id, _| id == keep_id); + slots.borrow_mut().retain(|&id, slot| { + let critical_section = slot.critical_section.load(Ordering::Relaxed); + if id != keep_id && critical_section != 0 { + FORKED_CRITICAL_SECTIONS + .with(|forked| forked.borrow_mut().insert(id, critical_section)); + } + id == keep_id + }); }); } @@ -1300,6 +1448,9 @@ pub fn with_vm(obj: &PyObject, f: F) -> Option where F: Fn(&VirtualMachine) -> R, { + if PYTHON_CALLBACKS_DISABLED.with(Cell::get) { + return None; + } let vm_owns_obj = |interp: NonNull| { // SAFETY: all references in VM_STACK should be valid let vm = unsafe { interp.as_ref() }; @@ -1372,6 +1523,13 @@ pub struct ThreadedVirtualMachine { pub(super) vm: VirtualMachine, } +#[cfg(feature = "threading")] +impl Drop for ThreadedVirtualMachine { + fn drop(&mut self) { + clear_async_exception_on_owner_drop(&self.vm); + } +} + #[cfg(feature = "threading")] impl ThreadedVirtualMachine { /// Create a `FnOnce()` that can easily be passed to a function like [`std::thread::Builder::spawn`] @@ -1453,45 +1611,134 @@ impl VirtualMachine { /// specific guaranteed behavior. #[cfg(feature = "threading")] pub fn new_thread(&self) -> ThreadedVirtualMachine { - let global_trace = self.state.global_trace_func.lock().clone(); - let global_profile = self.state.global_profile_func.lock().clone(); - let use_tracing = global_trace.is_some() || global_profile.is_some(); + ThreadedVirtualMachine { + vm: self.new_thread_vm(), + } + } + + #[cfg(feature = "threading")] + pub(super) fn new_thread_vm(&self) -> Self { + InterpreterThreadRoots::new(self).into_vm( + self.state.clone(), + self.recursion_limit.get(), + self.thread_factory.clone(), + ) + } +} - let vm = Self { - builtins: self.builtins.clone(), - sys_module: self.sys_module.clone(), - ctx: self.ctx.clone(), +/// Shared roots needed to create a thread state, without sharing any mutable +/// thread-local VM fields. VMs own this factory; the runtime registry is weak. +#[cfg(feature = "threading")] +pub(crate) struct InterpreterThreadFactory { + roots: InterpreterThreadRoots, + pub(crate) recursion_limit: crossbeam_utils::atomic::AtomicCell, +} + +#[cfg(feature = "threading")] +#[derive(Clone)] +struct InterpreterThreadRoots { + builtins: crate::PyRef, + sys_module: crate::PyRef, + ctx: crate::common::rc::PyRc, + wasm_id: Option, + import_func: PyObjectRef, + importlib: PyObjectRef, + initialized: bool, + import_bootstrap_complete: bool, + callable_cache: super::CallableCache, + startup_error: Option, +} + +#[cfg(feature = "threading")] +impl InterpreterThreadRoots { + fn new(vm: &VirtualMachine) -> Self { + Self { + builtins: vm.builtins.clone(), + sys_module: vm.sys_module.clone(), + ctx: vm.ctx.clone(), + wasm_id: vm.wasm_id.clone(), + import_func: vm.import_func.clone(), + importlib: vm.importlib.clone(), + initialized: vm.initialized, + import_bootstrap_complete: vm.import_bootstrap_complete, + callable_cache: vm.callable_cache.clone(), + startup_error: vm.startup_error.clone(), + } + } + + fn into_vm( + self, + state: crate::common::rc::PyRc, + recursion_limit: usize, + factory: Option>, + ) -> VirtualMachine { + let global_trace = state.global_trace_func.lock().clone(); + let global_profile = state.global_profile_func.lock().clone(); + let use_tracing = global_trace.is_some() || global_profile.is_some(); + let profile_func = RefCell::new(global_profile.unwrap_or_else(|| self.ctx.none())); + let trace_func = RefCell::new(global_trace.unwrap_or_else(|| self.ctx.none())); + + VirtualMachine { + thread_factory: factory, + builtins: self.builtins, + sys_module: self.sys_module, + ctx: self.ctx, datastack: core::cell::UnsafeCell::new(crate::datastack::DataStack::new()), - wasm_id: self.wasm_id.clone(), + wasm_id: self.wasm_id, exceptions: RefCell::default(), - import_func: self.import_func.clone(), - importlib: self.importlib.clone(), - profile_func: RefCell::new(global_profile.unwrap_or_else(|| self.ctx.none())), - trace_func: RefCell::new(global_trace.unwrap_or_else(|| self.ctx.none())), + import_func: self.import_func, + importlib: self.importlib, + import_timing: Cell::default(), + profile_func, + trace_func, use_tracing: Cell::new(use_tracing), what_event: Cell::new(None), tracing_depth: Cell::new(0), - recursion_limit: self.recursion_limit.clone(), - signal_handlers: core::cell::OnceCell::new(), + recursion_limit: Cell::new(recursion_limit), signal_rx: None, repr_guards: RefCell::default(), - state: self.state.clone(), + lazy_imports_resolving: RefCell::default(), + state, initialized: self.initialized, + import_bootstrap_complete: self.import_bootstrap_complete, + startup_error: self.startup_error, recursion_depth: Cell::new(0), - #[cfg(any(miri, target_env = "musl"))] + #[cfg(any(miri, target_env = "musl", target_arch = "wasm32"))] native_recursion_depth: Cell::new(0), - c_stack_soft_limit: Cell::new(Self::calculate_c_stack_soft_limit()), + c_stack_soft_limit: Cell::new(VirtualMachine::calculate_c_stack_soft_limit()), async_gen_firstiter: RefCell::new(None), async_gen_finalizer: RefCell::new(None), asyncio_running_loop: RefCell::new(None), asyncio_running_task: RefCell::new(None), context_stack: RefCell::default(), - callable_cache: self.callable_cache.clone(), + callable_cache: self.callable_cache, pending_tailcall_frame: Cell::new(None), pending_tailcall_owner: core::cell::UnsafeCell::new(None), pending_gen_resume: core::cell::UnsafeCell::new(None), trampoline_stack: core::cell::UnsafeCell::new(Vec::new()), - }; - ThreadedVirtualMachine { vm } + async_exception: super::async_exception::PendingAsyncException::default(), + } + } +} + +#[cfg(feature = "threading")] +impl InterpreterThreadFactory { + pub(super) fn new(vm: &VirtualMachine) -> Self { + Self { + roots: InterpreterThreadRoots::new(vm), + recursion_limit: crossbeam_utils::atomic::AtomicCell::new(vm.recursion_limit.get()), + } + } + + pub(crate) fn new_thread( + self: &Arc, + state: crate::common::rc::PyRc, + ) -> ThreadedVirtualMachine { + ThreadedVirtualMachine { + vm: self + .roots + .clone() + .into_vm(state, self.recursion_limit.load(), Some(self.clone())), + } } } diff --git a/crates/vm/src/vm/thread/critical_section.rs b/crates/vm/src/vm/thread/critical_section.rs new file mode 100644 index 00000000000..fb6752b9eef --- /dev/null +++ b/crates/vm/src/vm/thread/critical_section.rs @@ -0,0 +1,811 @@ +//! Critical sections over [`PyMutex`]es. +//! +//! Each thread state keeps a stack of the critical sections it has entered. +//! Detaching releases the mutexes of every section on the stack, and attaching +//! again reacquires only the top-most one; the others are reacquired as the +//! sections above them end. Code inside a section must therefore revalidate +//! its state after anything that can detach, such as calling Python. +//! +//! Without the `threading` feature critical sections are no-ops. + +use super::lock::PyMutex; +use crate::{PyResult, VirtualMachine}; + +/// Interpreter-bound operation exclusion that permits Python callbacks. +/// +/// Detaching or reentering can release this exclusion. Payload borrows must +/// use separate short guards and be revalidated after callbacks or drops. +#[derive(Debug)] +pub struct PyOperation { + mutex: PyMutex, + interpreter_id: i64, +} + +impl PyOperation { + pub fn new(vm: &VirtualMachine) -> Self { + Self { + mutex: PyMutex::new(), + interpreter_id: vm.state.interpreter_id, + } + } + + pub fn with(&self, vm: &VirtualMachine, f: impl FnOnce() -> PyResult) -> PyResult { + assert_eq!( + super::try_with_current_vm(|current| current.state.interpreter_id), + Some(vm.state.interpreter_id), + "operation requires the current interpreter" + ); + #[cfg(feature = "threading")] + { + let slot = super::current_thread_slot().expect("operation requires a thread slot"); + assert_eq!( + slot.state.load(core::sync::atomic::Ordering::Acquire), + super::ThreadState::Attached as i32, + "operation requires an attached interpreter" + ); + } + // The critical-section slow path may bypass this mutex while this + // interpreter's world is stopped. It cannot cover another interpreter. + if self.interpreter_id != vm.state.interpreter_id { + return Err(vm.new_runtime_error("operation belongs to a different interpreter")); + } + with(vm, &self.mutex, f) + } +} + +/// `Py_BEGIN_CRITICAL_SECTION_MUTEX(m)` ... `Py_END_CRITICAL_SECTION()` +pub(crate) fn with(vm: &VirtualMachine, m: &PyMutex, f: impl FnOnce() -> R) -> R { + #[cfg(feature = "threading")] + { + threaded::with(vm, m, f) + } + #[cfg(not(feature = "threading"))] + { + let _ = (vm, m); + f() + } +} + +/// `Py_BEGIN_CRITICAL_SECTION2_MUTEX(m1, m2)` ... `Py_END_CRITICAL_SECTION2()` +#[cfg_attr( + not(all(test, feature = "threading")), + expect(dead_code, reason = "Removed when the profiler consumer is wired") +)] +pub(crate) fn with2( + vm: &VirtualMachine, + m1: &PyMutex, + m2: &PyMutex, + f: impl FnOnce() -> R, +) -> R { + #[cfg(feature = "threading")] + { + threaded::with2(vm, m1, m2, f) + } + #[cfg(not(feature = "threading"))] + { + let _ = (vm, m1, m2); + f() + } +} + +#[cfg(feature = "threading")] +pub(super) use threaded::{resume, suspend_all}; + +#[cfg(feature = "threading")] +mod threaded { + use super::PyMutex; + use crate::VirtualMachine; + use crate::vm::thread::{self, ThreadSlot}; + use core::ptr; + use core::sync::atomic::{AtomicPtr, AtomicUsize, Ordering}; + + /// The section's mutexes are released; it is resumed when it becomes the + /// top-most section of an attached thread. + const INACTIVE: usize = 0x1; + /// The tagged pointer refers to a [`PyCriticalSection2`]. + const TWO_MUTEXES: usize = 0x2; + const MASK: usize = 0x3; + + /// `PyCriticalSection` + /// + /// Only the owning thread touches a section; the fields are atomics + /// because the thread state that links them is shared. + #[repr(C, align(4))] + struct PyCriticalSection { + /// Tagged pointer to the previous critical section. + prev: AtomicUsize, + /// Mutex held by this section. Null while it is being acquired, and + /// for a section that skipped locking. + mutex: AtomicPtr, + } + + /// `PyCriticalSection2` + #[repr(C)] + struct PyCriticalSection2 { + base: PyCriticalSection, + mutex2: AtomicPtr, + } + + impl PyCriticalSection { + const fn new() -> Self { + Self { + prev: AtomicUsize::new(0), + mutex: AtomicPtr::new(ptr::null_mut()), + } + } + } + + fn mutex_ptr(m: &PyMutex) -> *mut PyMutex { + ptr::from_ref(m).cast_mut() + } + + /// # Safety + /// A non-null `m` must be a mutex of a live critical section. + unsafe fn lock(m: *mut PyMutex) { + unsafe { &*m }.lock(); + } + + /// # Safety + /// A non-null `m` must be a mutex of a live critical section. + unsafe fn unlock(m: *mut PyMutex) { + unsafe { &*m }.unlock(); + } + + fn untag(tag: usize) -> *const PyCriticalSection { + (tag & !MASK) as *const PyCriticalSection + } + + /// `_PyCriticalSection_IsActive` + fn is_active(tag: usize) -> bool { + tag != 0 && tag & INACTIVE == 0 + } + + fn tstate() -> thread::CurrentFrameSlot { + thread::current_thread_slot().expect("critical section requires a thread state") + } + + /// The thread state of a thread entering a critical section, which must + /// be attached: a detached thread would push a section that attaching + /// again tries to resume while it is still held. + fn attached_tstate() -> thread::CurrentFrameSlot { + let tstate = tstate(); + debug_assert_eq!( + tstate.state.load(Ordering::Acquire), + thread::ThreadState::Attached as i32, + "critical section requires an attached thread state" + ); + tstate + } + + fn world_stopped(vm: &VirtualMachine) -> bool { + vm.state + .stop_the_world + .world_stopped + .load(Ordering::Acquire) + } + + pub(super) fn with(vm: &VirtualMachine, m: &PyMutex, f: impl FnOnce() -> R) -> R { + let c = PyCriticalSection::new(); + begin_mutex(vm, &attached_tstate(), &c, m); + // The thread state is looked up again at the end, because fork + // replaces the slot of the surviving thread. + let _end = scopeguard::guard(&c, |c| end(&tstate(), c)); + f() + } + + pub(super) fn with2( + vm: &VirtualMachine, + m1: &PyMutex, + m2: &PyMutex, + f: impl FnOnce() -> R, + ) -> R { + let c = PyCriticalSection2 { + base: PyCriticalSection::new(), + mutex2: AtomicPtr::new(ptr::null_mut()), + }; + begin2_mutex(vm, &attached_tstate(), &c, m1, m2); + let _end = scopeguard::guard(&c, |c| end2(&tstate(), c)); + f() + } + + /// `_PyCriticalSection_BeginMutex` + fn begin_mutex(vm: &VirtualMachine, tstate: &ThreadSlot, c: &PyCriticalSection, m: &PyMutex) { + if m.lock_fast() { + c.mutex.store(mutex_ptr(m), Ordering::Relaxed); + c.prev.store( + tstate.critical_section.load(Ordering::Relaxed), + Ordering::Relaxed, + ); + tstate + .critical_section + .store(ptr::from_ref(c) as usize, Ordering::Relaxed); + } else { + begin_slow(vm, tstate, c, m); + } + } + + /// `_PyCriticalSection_BeginSlow` + #[cold] + fn begin_slow(vm: &VirtualMachine, tstate: &ThreadSlot, c: &PyCriticalSection, m: &PyMutex) { + // As an optimisation for locking the same mutex recursively, skip + // locking if the mutex is currently locked by the top-most critical + // section. If the top-most critical section is a two-mutex critical + // section, then locking is skipped if either mutex is m. + let top = tstate.critical_section.load(Ordering::Relaxed); + if top != 0 { + // SAFETY: the stack links live sections of this thread. + let prev = unsafe { &*untag(top) }; + if prev.mutex.load(Ordering::Relaxed) == mutex_ptr(m) { + c.mutex.store(ptr::null_mut(), Ordering::Relaxed); + c.prev.store(0, Ordering::Relaxed); + return; + } + if top & TWO_MUTEXES != 0 { + // SAFETY: the tag marks a two-mutex section. + let prev2 = unsafe { &*untag(top).cast::() }; + if prev2.mutex2.load(Ordering::Relaxed) == mutex_ptr(m) { + c.mutex.store(ptr::null_mut(), Ordering::Relaxed); + c.prev.store(0, Ordering::Relaxed); + return; + } + } + } + // If the world is stopped, we don't need to acquire the lock because + // there are no other threads that could be accessing the object. + // Without this check, acquiring a critical section while the world is + // stopped could lead to a deadlock. + if world_stopped(vm) { + c.mutex.store(ptr::null_mut(), Ordering::Relaxed); + c.prev.store(0, Ordering::Relaxed); + return; + } + c.mutex.store(ptr::null_mut(), Ordering::Relaxed); + c.prev.store(top, Ordering::Relaxed); + tstate + .critical_section + .store(ptr::from_ref(c) as usize, Ordering::Relaxed); + + m.lock(); + c.mutex.store(mutex_ptr(m), Ordering::Relaxed); + } + + /// `_PyCriticalSection2_BeginMutex` + fn begin2_mutex( + vm: &VirtualMachine, + tstate: &ThreadSlot, + c: &PyCriticalSection2, + m1: &PyMutex, + m2: &PyMutex, + ) { + if ptr::eq(m1, m2) { + // If the two mutex arguments are the same, treat this as a + // critical section with a single mutex. + c.mutex2.store(ptr::null_mut(), Ordering::Relaxed); + begin_mutex(vm, tstate, &c.base, m1); + return; + } + + // Sort the mutexes so that the lower address is locked first. The + // exact order does not matter, but we need to acquire the mutexes in + // a consistent order to avoid lock ordering deadlocks. + let (m1, m2) = if mutex_ptr(m2) < mutex_ptr(m1) { + (m2, m1) + } else { + (m1, m2) + }; + + if m1.lock_fast() { + if m2.lock_fast() { + c.base.mutex.store(mutex_ptr(m1), Ordering::Relaxed); + c.mutex2.store(mutex_ptr(m2), Ordering::Relaxed); + c.base.prev.store( + tstate.critical_section.load(Ordering::Relaxed), + Ordering::Relaxed, + ); + tstate + .critical_section + .store(ptr::from_ref(c) as usize | TWO_MUTEXES, Ordering::Relaxed); + } else { + begin2_slow(vm, tstate, c, m1, m2, true); + } + } else { + begin2_slow(vm, tstate, c, m1, m2, false); + } + } + + /// `_PyCriticalSection2_BeginSlow` + #[cold] + fn begin2_slow( + vm: &VirtualMachine, + tstate: &ThreadSlot, + c: &PyCriticalSection2, + m1: &PyMutex, + m2: &PyMutex, + is_m1_locked: bool, + ) { + if world_stopped(vm) { + c.base.mutex.store(ptr::null_mut(), Ordering::Relaxed); + c.mutex2.store(ptr::null_mut(), Ordering::Relaxed); + c.base.prev.store(0, Ordering::Relaxed); + return; + } + // Same optimization as in begin_slow: skip locking when recursively + // acquiring the same locks. + let top = tstate.critical_section.load(Ordering::Relaxed); + if top != 0 && top & TWO_MUTEXES != 0 { + // SAFETY: the tag marks a live two-mutex section of this thread. + let prev2 = unsafe { &*untag(top).cast::() }; + debug_assert!(mutex_ptr(m1) < mutex_ptr(m2)); + debug_assert!( + prev2.base.mutex.load(Ordering::Relaxed) < prev2.mutex2.load(Ordering::Relaxed) + ); + if prev2.base.mutex.load(Ordering::Relaxed) == mutex_ptr(m1) + && prev2.mutex2.load(Ordering::Relaxed) == mutex_ptr(m2) + { + c.base.mutex.store(ptr::null_mut(), Ordering::Relaxed); + c.mutex2.store(ptr::null_mut(), Ordering::Relaxed); + c.base.prev.store(0, Ordering::Relaxed); + return; + } + } + c.base.mutex.store(ptr::null_mut(), Ordering::Relaxed); + c.mutex2.store(ptr::null_mut(), Ordering::Relaxed); + c.base.prev.store(top, Ordering::Relaxed); + tstate + .critical_section + .store(ptr::from_ref(c) as usize | TWO_MUTEXES, Ordering::Relaxed); + + if !is_m1_locked { + m1.lock(); + } + m2.lock(); + c.base.mutex.store(mutex_ptr(m1), Ordering::Relaxed); + c.mutex2.store(mutex_ptr(m2), Ordering::Relaxed); + } + + /// `_PyCriticalSection_Pop`: removes the top-most critical section from + /// the thread's stack. If the new top-most section is inactive, then it + /// is resumed. + fn pop(tstate: &ThreadSlot, c: &PyCriticalSection) { + let prev = c.prev.load(Ordering::Relaxed); + tstate.critical_section.store(prev, Ordering::Relaxed); + if prev & INACTIVE != 0 { + resume_top(tstate); + } + } + + /// `_PyCriticalSection_End` + fn end(tstate: &ThreadSlot, c: &PyCriticalSection) { + // If the mutex is null, we used the fast path in begin_slow for locks + // already held in the top-most critical section, and we shouldn't + // unlock or pop this critical section. + let m = c.mutex.load(Ordering::Relaxed); + if m.is_null() { + return; + } + // SAFETY: an active section holds its mutex. + unsafe { unlock(m) }; + pop(tstate, c); + } + + /// `_PyCriticalSection2_End` + fn end2(tstate: &ThreadSlot, c: &PyCriticalSection2) { + // If mutex1 is null, we used the fast path in either begin_slow or + // begin2_slow for mutexes that are already held, and mutex2 should + // also be null. + let m1 = c.base.mutex.load(Ordering::Relaxed); + if m1.is_null() { + debug_assert!(c.mutex2.load(Ordering::Relaxed).is_null()); + return; + } + let m2 = c.mutex2.load(Ordering::Relaxed); + // SAFETY: an active section holds its mutexes. + unsafe { + if !m2.is_null() { + unlock(m2); + } + unlock(m1); + } + pop(tstate, &c.base); + } + + /// `_PyCriticalSection_SuspendAll`: release all locks held by critical + /// sections. Called before the thread stops being ATTACHED. + pub(crate) fn suspend_all(tstate: &ThreadSlot) { + let mut tagptr = &tstate.critical_section; + loop { + let tag = tagptr.load(Ordering::Relaxed); + if !is_active(tag) { + break; + } + // SAFETY: the stack links live sections of this thread. + let c = unsafe { &*untag(tag) }; + let m = c.mutex.load(Ordering::Relaxed); + if !m.is_null() { + // SAFETY: an active section holds its mutexes. + unsafe { unlock(m) }; + if tag & TWO_MUTEXES != 0 { + // SAFETY: the tag marks a two-mutex section. + let c2 = unsafe { &*untag(tag).cast::() }; + let m2 = c2.mutex2.load(Ordering::Relaxed); + if !m2.is_null() { + // SAFETY: as above. + unsafe { unlock(m2) }; + } + } + } + + tagptr.store(tag | INACTIVE, Ordering::Relaxed); + tagptr = &c.prev; + } + } + + /// Resume the top-most critical section after the thread attached. + pub(crate) fn resume(tstate: &ThreadSlot) { + if tstate.critical_section.load(Ordering::Relaxed) != 0 { + resume_top(tstate); + } + } + + /// `_PyCriticalSection_Resume` + fn resume_top(tstate: &ThreadSlot) { + let p = tstate.critical_section.load(Ordering::Relaxed); + // SAFETY: the stack links live sections of this thread. + let c = unsafe { &*untag(p) }; + debug_assert!(!is_active(p)); + + let m1 = c.mutex.swap(ptr::null_mut(), Ordering::Relaxed); + let (c2, m2) = if p & TWO_MUTEXES != 0 { + // SAFETY: the tag marks a two-mutex section. + let c2 = unsafe { &*untag(p).cast::() }; + (Some(c2), c2.mutex2.swap(ptr::null_mut(), Ordering::Relaxed)) + } else { + (None, ptr::null_mut()) + }; + + // SAFETY: the mutexes belong to a live section that released them. + unsafe { + if !m1.is_null() { + lock(m1); + } + if !m2.is_null() { + lock(m2); + } + } + + c.mutex.store(m1, Ordering::Relaxed); + if let Some(c2) = c2 + && !m2.is_null() + { + c2.mutex2.store(m2, Ordering::Relaxed); + } + + let p = tstate.critical_section.load(Ordering::Relaxed); + tstate + .critical_section + .store(p & !INACTIVE, Ordering::Relaxed); + } +} + +#[cfg(test)] +#[cfg(feature = "threading")] +mod tests { + use super::*; + #[cfg(all(unix, feature = "host_env"))] + use crate::AsObject; + use crate::Interpreter; + use crate::vm::stop_the_world::StopTheWorldGroup; + use alloc::sync::Arc; + use core::{ + panic::AssertUnwindSafe, + sync::atomic::{AtomicBool, AtomicUsize, Ordering}, + }; + + fn assert_empty() { + let slot = crate::vm::thread::current_thread_slot().unwrap(); + assert_eq!(slot.critical_section.load(Ordering::Relaxed), 0); + } + + #[test] + fn nested_sections_restore_ownership() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let first = PyMutex::new(); + let second = PyMutex::new(); + with(vm, &first, || { + with(vm, &first, || assert!(first.is_locked())); + with(vm, &second, || { + assert!(first.is_locked()); + // Not the top-most section: locking it again detaches, + // which suspends every section of this thread. + with(vm, &first, || { + assert!(first.is_locked()); + assert!(!second.is_locked()); + }); + assert!(second.is_locked()); + assert!(!first.is_locked()); + }); + assert!(first.is_locked()); + }); + assert!(!first.is_locked()); + assert!(!second.is_locked()); + assert_empty(); + }); + } + + #[test] + fn two_mutex_sections() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let first = PyMutex::new(); + let second = PyMutex::new(); + with2(vm, &second, &first, || { + assert!(first.is_locked() && second.is_locked()); + with2(vm, &first, &second, || {}); + with(vm, &second, || {}); + vm.allow_threads(|| assert!(!first.is_locked() && !second.is_locked())); + assert!(first.is_locked() && second.is_locked()); + }); + with2(vm, &first, &first, || assert!(first.is_locked())); + assert!(!first.is_locked() && !second.is_locked()); + assert_empty(); + }); + } + + #[test] + fn detachment_and_unwind_restore_sections() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let m = PyMutex::new(); + let result = std::panic::catch_unwind(AssertUnwindSafe(|| { + with(vm, &m, || { + vm.allow_threads(|| assert!(!m.is_locked())); + assert!(m.is_locked()); + panic!("unwind the critical section"); + }); + })); + assert!(result.is_err()); + assert!(!m.is_locked()); + assert_empty(); + with(vm, &m, || assert!(m.is_locked())); + }); + } + + #[test] + fn interpreter_switch_restores_only_its_own_sections() { + let first = Interpreter::builder(Default::default()).build(); + let second = Interpreter::builder(Default::default()).build(); + first.enter(|first_vm| { + let first_lock = PyMutex::new(); + with(first_vm, &first_lock, || { + second.enter(|second_vm| { + assert!(!first_lock.is_locked()); + let second_lock = PyMutex::new(); + with(second_vm, &second_lock, || { + first.enter(|restored_vm| { + assert!(first_lock.is_locked()); + assert!(!second_lock.is_locked()); + with(restored_vm, &first_lock, || {}); + }); + assert!(second_lock.is_locked()); + }); + }); + assert!(first_lock.is_locked()); + }); + }); + } + + #[test] + fn opposite_order_contention_completes() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let first = Arc::new(PyMutex::new()); + let second = Arc::new(PyMutex::new()); + let completed = Arc::new(AtomicUsize::new(0)); + let workers: Vec<_> = [false, true] + .into_iter() + .map(|reverse| { + let (outer, inner) = if reverse { + (second.clone(), first.clone()) + } else { + (first.clone(), second.clone()) + }; + let completed = completed.clone(); + vm.start_thread(move |vm| { + for _ in 0..1000 { + with(vm, &outer, || { + with(vm, &inner, || { + completed.fetch_add(1, Ordering::Relaxed); + }) + }); + } + }) + }) + .collect(); + vm.allow_threads(|| { + for worker in workers { + worker.join().unwrap(); + } + }); + assert_eq!(completed.load(Ordering::Relaxed), 2000); + assert!(!first.is_locked()); + assert!(!second.is_locked()); + }); + } + + #[test] + fn stop_the_world_releases_critical_sections() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let m = Arc::new(PyMutex::new()); + let finished = Arc::new(AtomicBool::new(false)); + let (ready, started) = std::sync::mpsc::channel(); + let worker = { + let m = m.clone(); + let finished = finished.clone(); + vm.start_thread(move |vm| { + with(vm, &m, || { + ready.send(()).unwrap(); + while !finished.load(Ordering::Acquire) { + crate::vm::thread::suspend_if_needed(&vm.state); + std::thread::yield_now(); + } + assert!(m.is_locked()); + }); + }) + }; + vm.allow_threads(|| started.recv().unwrap()); + let mut stopped = StopTheWorldGroup::new(); + assert!(!m.is_locked()); + finished.store(true, Ordering::Release); + stopped.restart(); + vm.allow_threads(|| worker.join().unwrap()); + assert!(!m.is_locked()); + }); + } + + #[test] + fn stopped_world_skips_locking() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let m = PyMutex::new(); + m.lock(); + let mut stopped = StopTheWorldGroup::new(); + with(vm, &m, assert_empty); + stopped.restart(); + m.unlock(); + }); + } + + // Run this exact test alone in an owned process under an external timeout. + // It forks while a critical section is active in another interpreter, and + // keeps lexical sections in both interpreters alive across the child's + // slot repair. + #[cfg(all(unix, feature = "host_env"))] + #[test] + #[ignore = "requires an isolated process and external process-tree timeout"] + fn fork_preserves_nested_interpreter_sections() { + let first = Interpreter::builder(Default::default()).build(); + let second = Interpreter::builder(Default::default()).build(); + first.enter(|first_vm| { + let outer = PyMutex::new(); + let worker_lock = Arc::new(PyMutex::new()); + let finished = Arc::new(AtomicBool::new(false)); + let (ready, started) = std::sync::mpsc::channel(); + let worker = { + let m = worker_lock.clone(); + let finished = finished.clone(); + first_vm.start_thread(move |vm| { + with(vm, &m, || { + ready.send(()).unwrap(); + while !finished.load(Ordering::Acquire) { + crate::vm::thread::suspend_if_needed(&vm.state); + std::thread::yield_now(); + } + }); + }) + }; + first_vm.allow_threads(|| started.recv().unwrap()); + with(first_vm, &outer, || { + second.enter(|vm| { + let inner = PyMutex::new(); + let posix = vm.import("posix", 0).unwrap(); + let lookups = Arc::new(AtomicUsize::new(0)); + let hook = { + let lookups = lookups.clone(); + vm.new_function( + "__getattr__", + move |_name: crate::PyObjectRef, + vm: &VirtualMachine| + -> crate::PyResult { + // Stream repair can reenter Python. Its native + // callback must be able to acquire a fresh STW + // transaction after core child repair. + let mut stopped = StopTheWorldGroup::new(); + stopped.restart(); + lookups.fetch_add(1, Ordering::Relaxed); + Err(vm.new_attribute_error("missing test stream")) + }, + ) + }; + vm.sys_module.set_attr("__getattr__", hook, vm).unwrap(); + let _ = vm.sys_module.dict().del_item("stdin", vm); + with(vm, &inner, || { + lookups.store(0, Ordering::Relaxed); + let pid = vm + .call_method(posix.as_object(), "fork", ()) + .unwrap() + .try_into_value::(vm) + .unwrap(); + if pid == 0 { + assert!(lookups.load(Ordering::Relaxed) > 0); + assert!(inner.is_locked()); + assert!(!worker_lock.is_locked()); + first.enter(|vm| { + assert!(outer.is_locked()); + assert!(!inner.is_locked()); + with(vm, &worker_lock, || {}); + }); + assert!(inner.is_locked()); + // The inherited shared transaction was released. + let mut stopped = StopTheWorldGroup::new(); + stopped.restart(); + // SAFETY: this owned child must not return into the + // parent test runner or join the vanished worker. + unsafe { libc::_exit(0) }; + } + finished.store(true, Ordering::Release); + let mut status = 0; + vm.allow_threads(|| { + rustpython_host_env::posix::waitpid(pid, &mut status, 0).unwrap(); + }); + assert!(libc::WIFEXITED(status)); + assert_eq!(libc::WEXITSTATUS(status), 0); + }); + }); + assert!(outer.is_locked()); + }); + first_vm.allow_threads(|| worker.join().unwrap()); + }); + } + + // The worker deliberately remains parked until the owned test process exits. + #[test] + #[ignore = "requires an isolated process and external process-tree timeout"] + fn shutting_down_releases_critical_sections() { + Interpreter::builder(Default::default()) + .build() + .enter(|vm| { + let m = Arc::new(PyMutex::new()); + let (ready, started) = std::sync::mpsc::channel(); + let worker = { + let m = m.clone(); + vm.start_thread(move |vm| { + with(vm, &m, || { + ready + .send(crate::vm::thread::current_thread_slot().unwrap()) + .unwrap(); + crate::vm::thread::hang_current_thread(&vm.state); + }); + }) + }; + let slot = vm.allow_threads(|| started.recv().unwrap()); + vm.allow_threads(|| { + while slot.state.load(Ordering::Acquire) + != crate::vm::thread::ThreadState::ShuttingDown as i32 + { + std::thread::yield_now(); + } + }); + assert!(!m.is_locked()); + with(vm, &m, || assert!(m.is_locked())); + drop(worker); + }); + } +} diff --git a/crates/vm/src/vm/thread/lock.rs b/crates/vm/src/vm/thread/lock.rs new file mode 100644 index 00000000000..81b9252b041 --- /dev/null +++ b/crates/vm/src/vm/thread/lock.rs @@ -0,0 +1,297 @@ +//! One-byte mutex whose blocking acquire detaches the waiting thread. +//! +//! Only the two least significant bits of the state are used: +//! 0b00 unlocked, 0b01 locked, 0b10 unlocked with parked threads, +//! 0b11 locked with parked threads. + +use core::sync::atomic::AtomicU8; +#[cfg(feature = "threading")] +use core::sync::atomic::Ordering; + +#[cfg(feature = "threading")] +const UNLOCKED: u8 = 0; +#[cfg(feature = "threading")] +const LOCKED: u8 = 1; +#[cfg(feature = "threading")] +const HAS_PARKED: u8 = 2; + +/// `PyMutex`. Zero is the unlocked state. +#[derive(Debug, Default)] +#[repr(transparent)] +pub(crate) struct PyMutex { + bits: AtomicU8, +} + +impl PyMutex { + pub(crate) const fn new() -> Self { + Self { + bits: AtomicU8::new(0), + } + } +} + +#[cfg(feature = "threading")] +mod threaded { + use super::{HAS_PARKED, LOCKED, Ordering, PyMutex, UNLOCKED}; + use core::cell::Cell; + use core::time::Duration; + use parking_lot_core::{FilterOp, ParkResult, ParkToken, UnparkToken}; + use std::time::Instant; + + /// A waiter blocked longer than this is handed the lock directly by the + /// unlocking thread, which avoids starvation. + const TIME_TO_BE_FAIR: Duration = Duration::from_millis(1); + + /// Spin for a bit before parking the thread. + const MAX_SPIN_COUNT: usize = 40; + + const TOKEN_NORMAL: UnparkToken = UnparkToken(0); + const TOKEN_HANDED_OFF: UnparkToken = UnparkToken(1); + + /// `struct mutex_entry`; its address is the waiter's park token. + struct MutexEntry { + /// After this point the unlocking thread hands off ownership directly. + time_to_be_fair: Instant, + } + + impl PyMutex { + /// `PyMutex_LockFast` + #[inline] + pub(crate) fn lock_fast(&self) -> bool { + self.bits + .compare_exchange(UNLOCKED, LOCKED, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + } + + /// `PyMutex_Lock`. A thread attached to an interpreter detaches while + /// it is parked. + #[inline] + pub(crate) fn lock(&self) { + if !self.lock_fast() { + self.lock_slow(); + } + } + + /// `_PyMutex_LockTimed` with no timeout and `_PY_LOCK_DETACH`. + #[cold] + fn lock_slow(&self) { + let mut v = self.bits.load(Ordering::Relaxed); + if v & LOCKED == 0 + && self + .bits + .compare_exchange(v, v | LOCKED, Ordering::Acquire, Ordering::Relaxed) + .is_ok() + { + return; + } + + let entry = MutexEntry { + time_to_be_fair: Instant::now() + TIME_TO_BE_FAIR, + }; + + let mut spin_count = 0; + loop { + if v & LOCKED == 0 { + // The lock is unlocked. Try to grab it. + match self.bits.compare_exchange( + v, + v | LOCKED, + Ordering::Acquire, + Ordering::Relaxed, + ) { + Ok(_) => return, + Err(actual) => { + v = actual; + continue; + } + } + } + + if v & HAS_PARKED == 0 && spin_count < MAX_SPIN_COUNT { + // Spin for a bit. + std::thread::yield_now(); + spin_count += 1; + continue; + } + + let mut newv = v; + if v & HAS_PARKED == 0 { + // We are the first waiter. Set the HAS_PARKED flag. + newv = v | HAS_PARKED; + if let Err(actual) = + self.bits + .compare_exchange(v, newv, Ordering::Relaxed, Ordering::Relaxed) + { + v = actual; + continue; + } + } + + if self.park(newv, &entry) == ParkResult::Unparked(TOKEN_HANDED_OFF) { + // We own the lock now. + debug_assert!(self.bits.load(Ordering::Relaxed) & LOCKED != 0); + return; + } + + v = self.bits.load(Ordering::Relaxed); + } + } + + /// `_PyParkingLot_Park` on this mutex, detached when attached. + fn park(&self, expected: u8, entry: &MutexEntry) -> ParkResult { + let result = Cell::new(ParkResult::Invalid); + crate::vm::thread::wait_detached_from_interpreter(&|| { + // SAFETY: the key is this mutex's address, used only by this + // mutex. The validate and timed-out callbacks only load an + // atomic or do nothing, so they neither panic nor reenter the + // parking lot. The entry outlives the park, and the unparking + // thread reads it under the bucket lock while this thread is + // still queued. + result.set(unsafe { + parking_lot_core::park( + self.key(), + || self.bits.load(Ordering::Relaxed) == expected, + || {}, + |_, _| {}, + ParkToken(core::ptr::from_ref(entry) as usize), + None, + ) + }); + }); + result.get() + } + + /// `PyMutex_Unlock` + #[inline] + pub(crate) fn unlock(&self) { + if self + .bits + .compare_exchange(LOCKED, UNLOCKED, Ordering::Release, Ordering::Relaxed) + .is_err() + { + self.unlock_slow(); + } + } + + /// `_PyMutex_UnlockSlow` + #[cold] + fn unlock_slow(&self) { + assert!( + self.try_unlock().is_ok(), + "unlocking mutex that is not locked" + ); + } + + /// `_PyMutex_TryUnlock` + fn try_unlock(&self) -> Result<(), ()> { + let mut v = self.bits.load(Ordering::Acquire); + loop { + if v & LOCKED == 0 { + // error: the mutex is not locked + return Err(()); + } else if v & HAS_PARKED != 0 { + // wake up a single thread + self.unpark(); + return Ok(()); + } + match self + .bits + .compare_exchange(v, UNLOCKED, Ordering::Release, Ordering::Relaxed) + { + // fast-path: no waiters + Ok(_) => return Ok(()), + Err(actual) => v = actual, + } + } + } + + /// `_PyParkingLot_Unpark` with `mutex_unpark`. + fn unpark(&self) { + let waiter = Cell::new(None); + // SAFETY: the key is this mutex's address. The filter and callback + // run under the bucket lock, do not panic and do not reenter the + // parking lot. A token is the address of a `MutexEntry` its waiter + // keeps alive while it is queued. + unsafe { + parking_lot_core::unpark_filter( + self.key(), + |token| { + if waiter.get().is_some() { + return FilterOp::Stop; + } + waiter.set(Some(token.0 as *const MutexEntry)); + FilterOp::Unpark + }, + |result| { + let mut v = UNLOCKED; + let mut token = TOKEN_NORMAL; + if let Some(entry) = waiter.get() { + let should_be_fair = Instant::now() > (*entry).time_to_be_fair; + if should_be_fair { + v |= LOCKED; + token = TOKEN_HANDED_OFF; + } + if result.have_more_threads { + v |= HAS_PARKED; + } + } + self.bits.store(v, Ordering::Release); + token + }, + ); + } + } + + /// `PyMutex_IsLocked` + #[cfg_attr( + not(test), + expect(dead_code, reason = "Removed when the profiler consumer is wired") + )] + pub(crate) fn is_locked(&self) -> bool { + self.bits.load(Ordering::Acquire) & LOCKED != 0 + } + + fn key(&self) -> usize { + core::ptr::from_ref(&self.bits) as usize + } + } +} + +#[cfg(test)] +#[cfg(feature = "threading")] +mod tests { + use super::{HAS_PARKED, PyMutex}; + use alloc::sync::Arc; + use core::{sync::atomic::Ordering, time::Duration}; + + #[test] + fn unlock_hands_off_to_starved_waiter() { + let m = Arc::new(PyMutex::new()); + let (release_waiter, wait_for_release) = std::sync::mpsc::channel::<()>(); + m.lock(); + let waiter = { + let m = m.clone(); + std::thread::spawn(move || { + m.lock(); + // Keep ownership until the parent has checked the handoff. + let _ = wait_for_release.recv(); + m.unlock(); + }) + }; + while m.bits.load(Ordering::Relaxed) & HAS_PARKED == 0 { + std::thread::yield_now(); + } + // Long past the waiter's fairness deadline. + std::thread::sleep(Duration::from_millis(20)); + m.unlock(); + // Check immediately, without waiting for the waiter to run again. + let acquired = m.lock_fast(); + if acquired { + m.unlock(); + } + drop(release_waiter); + waiter.join().unwrap(); + assert!(!acquired); + assert!(!m.is_locked()); + } +} diff --git a/crates/vm/src/vm/vm_new.rs b/crates/vm/src/vm/vm_new.rs index c8f8d72efb2..96d743ea80f 100644 --- a/crates/vm/src/vm/vm_new.rs +++ b/crates/vm/src/vm/vm_new.rs @@ -1,7 +1,5 @@ #[cfg(feature = "parser")] -use ruff_python_ast::token::TokenKind; - -use ruff_python_parser::{InterpolatedStringErrorType, LexicalErrorType, ParseErrorType}; +use ruff_python_parser::{LexicalErrorType, ParseErrorType}; use rustpython_common::wtf8::Wtf8Buf; use rustpython_compiler_core::SourceLocation; @@ -9,7 +7,7 @@ use rustpython_compiler_core::SourceLocation; use core::ops::RangeInclusive; #[cfg(feature = "parser")] -use rustpython_compiler::{CompileError, ParseError, is_blank_python_source}; +use rustpython_compiler::is_blank_python_source; use crate::{ AsObject, Py, PyObject, PyObjectRef, PyPayload, PyRef, PyResult, @@ -49,262 +47,6 @@ macro_rules! define_exception_fn { }; } -#[derive(Clone, Debug)] -struct SyntaxErrorInfo { - msg: String, - narrow_caret: bool, -} - -impl SyntaxErrorInfo { - #[must_use] - const fn new(msg: String, narrow_caret: bool) -> Self { - Self { msg, narrow_caret } - } - - #[cfg(feature = "parser")] - #[must_use] - const fn handle_expected_token(expected: TokenKind, found: TokenKind) -> &'static str { - match (expected, found) { - (TokenKind::Colon, TokenKind::Newline) => "expected ':'", - - (TokenKind::Lpar, _) => "expected '('", - - (TokenKind::Else, y) if !matches!(y, TokenKind::Colon) => { - "expected 'else' after 'if' expression" - } - - _ => "invalid syntax", - } - } - - #[cfg(feature = "parser")] - fn analyze_compile_error(&mut self, compile_error: &CompileError) { - let CompileError::Parse(ParseError { - error, location, .. - }) = compile_error - else { - return; - }; - - let msg = match error { - ParseErrorType::FStringError(InterpolatedStringErrorType::UnterminatedString) - | ParseErrorType::Lexical(LexicalErrorType::FStringError( - InterpolatedStringErrorType::UnterminatedString, - )) => "unterminated f-string literal".into(), - - ParseErrorType::TStringError(InterpolatedStringErrorType::UnterminatedString) - | ParseErrorType::Lexical(LexicalErrorType::TStringError( - InterpolatedStringErrorType::UnterminatedString, - )) => "unterminated t-string literal".into(), - - ParseErrorType::FStringError( - InterpolatedStringErrorType::UnterminatedTripleQuotedString, - ) - | ParseErrorType::Lexical(LexicalErrorType::FStringError( - InterpolatedStringErrorType::UnterminatedTripleQuotedString, - )) => "unterminated triple-quoted f-string literal".into(), - - ParseErrorType::TStringError( - InterpolatedStringErrorType::UnterminatedTripleQuotedString, - ) - | ParseErrorType::Lexical(LexicalErrorType::TStringError( - InterpolatedStringErrorType::UnterminatedTripleQuotedString, - )) => "unterminated triple-quoted t-string literal".into(), - - // ruff already prefixes these with `f-string: ` / `t-string: `, matching CPython. - // It quotes braces with backticks where CPython uses single quotes. - ParseErrorType::FStringError(_) - | ParseErrorType::TStringError(_) - | ParseErrorType::Lexical( - LexicalErrorType::FStringError(_) | LexicalErrorType::TStringError(_), - ) => self.msg.replace('`', "'"), - - ParseErrorType::UnexpectedExpressionToken => "invalid syntax".into(), - - ParseErrorType::ExpectedToken { expected, found } => { - Self::handle_expected_token(*expected, *found).into() - } - - ParseErrorType::InvalidStarredExpressionUsage => { - self.narrow_caret = true; - "invalid syntax".into() - } - - ParseErrorType::InvalidDeleteTarget => "invalid syntax".into(), - - ParseErrorType::Lexical(LexicalErrorType::LineContinuationError) => { - "unexpected character after line continuation character".into() - } - - ParseErrorType::Lexical(LexicalErrorType::UnclosedStringError) => { - format!( - "unterminated string literal (detected at line {})", - location.line - ) - } - - ParseErrorType::EmptyTypeParams => "Type parameter list cannot be empty".into(), - - ParseErrorType::InvalidStarPatternUsage => { - self.narrow_caret = true; - "cannot use starred expression here".into() - } - - ParseErrorType::ExpectedKeywordParam => "named arguments must follow bare *".into(), - - ParseErrorType::EmptyImportNames => "Expected one or more names after 'import'".into(), - - ParseErrorType::UnparenthesizedGeneratorExpression => { - "Generator expression must be parenthesized".into() - } - - ParseErrorType::NonDefaultParamAfterDefaultParam => { - "parameter without a default follows parameter with a default".into() - } - - ParseErrorType::VarParameterWithDefault => { - "var-positional argument cannot have default value".into() - } - - ParseErrorType::PositionalAfterKeywordArgument => { - "positional argument follows keyword argument".into() - } - - ParseErrorType::PositionalAfterKeywordUnpacking => { - "positional argument follows keyword argument unpacking".into() - } - - ParseErrorType::InvalidArgumentUnpackingOrder => { - "iterable argument unpacking follows keyword argument unpacking".into() - } - - ParseErrorType::ParamAfterVarKeywordParam => { - "arguments cannot follow var-keyword argument".into() - } - - ParseErrorType::InvalidAnnotatedAssignmentTarget => { - "illegal target for annotation".into() - } - - ParseErrorType::Lexical(LexicalErrorType::UnrecognizedToken { .. }) - | ParseErrorType::SimpleStatementsOnSameLine - | ParseErrorType::SimpleAndCompoundStatementOnSameLine - | ParseErrorType::ExpectedExpression => "invalid syntax".into(), - - ParseErrorType::OtherError(s) if s.starts_with("Expected an identifier") => { - "invalid syntax".into() - } - - // What the parser says when it cannot continue the list it is - // recovering; each of these situations is a plain "invalid syntax". - ParseErrorType::OtherError(s) - if matches!( - s.as_str(), - "Expected a statement" - | "Expected an `elif` or `else` clause, or the end of the `if` statement." - | "Expected an `except` or `finally` clause or the end of the `try` statement." - | "The keyword is not allowed as a variable declaration name" - | "Expected an assignment target" - | "Expected a type parameter or the end of the type parameter list" - | "Expected an import name or a ')'" - | "Expected an import name" - | "Expected an expression or the end of the slice list" - | "Expected an expression or a ']'" - | "Expected an expression or a '}'" - | "Expected an expression or a ')'" - | "Expected an expression" - | "Expected a pattern or the end of the sequence pattern" - | "Expected a mapping pattern or the end of the mapping pattern" - | "Expected a pattern or a ')'" - | "Expected a delete target" - | "Expected a parameter or the end of the parameter list" - | "Expected an expression or the end of the with item list" - ) => - { - "invalid syntax".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case( - "bytes literal cannot be mixed with non-bytes literals", - ) => - { - "cannot mix bytes and nonbytes literals".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case("positional patterns cannot follow keyword patterns") => - { - "positional patterns follow keyword patterns".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case("boolean 'not' expression cannot be used here") => - { - "'not' after an operator must be parenthesized".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case("trailing comma not allowed") => - { - "trailing comma not allowed without surrounding parentheses".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case( - "multiple exception types must be parenthesized when using `as`", - ) => - { - "multiple exception types must be parenthesized when using 'as'".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case( - "position-only parameter separator not allowed as first parameter", - ) => - { - "at least one argument must precede /".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case("only one '/' separator allowed") => - { - "/ may appear only once".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case("'/' parameter must appear before '*' parameter") => - { - "/ must be ahead of *".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case("expected `except` or `finally` after `try` block") => - { - "expected 'except' or 'finally' block".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case("only one '*' parameter allowed") => - { - "* argument may appear only once".into() - } - - ParseErrorType::OtherError(s) - if s.eq_ignore_ascii_case( - r#"cannot have both 'except' and 'except*' on the same 'try'"#, - ) => - { - r#"cannot have both 'except' and 'except*' on the same 'try'"#.into() - } - - _ => return, - }; - - self.msg = msg; - } -} - /// Collection of object creation helpers impl VirtualMachine { /// Create a new python object @@ -313,27 +55,44 @@ impl VirtualMachine { } pub fn new_code(&self, code: impl IntoCodeObject) -> PyRef { - let code = code.into_code_object(self); - PyRef::new_ref(PyCode::new(code), self.ctx.types.code_type.to_owned(), None) + let code = code.into_pycode(self); + PyRef::new_ref(code, self.ctx.types.code_type.to_owned(), None) } pub fn new_tuple(&self, value: impl IntoPyTuple) -> PyTupleRef { value.into_pytuple(self) } + /// Create a native module from a dictionary that cannot invoke failing callbacks. + /// Use `try_new_module` for dictionaries exposed to Python code. pub fn new_module( &self, name: &str, dict: PyDictRef, doc: Option, ) -> PyRef { + self.try_new_module(name, dict, doc) + .expect("Failed to initialize a native module dictionary") + } + + /// Create a module, propagating errors from its initial dictionary writes. + pub fn try_new_module( + &self, + name: &str, + dict: PyDictRef, + doc: Option, + ) -> PyResult> { let module = PyRef::new_ref( PyModule::new(), self.ctx.types.module_type.to_owned(), Some(dict), ); - module.init_dict(self.ctx.intern_str(name), doc, self); - module + module.init_dict( + self.ctx.intern_str(name), + doc.as_ref().map(|doc| doc.as_object()), + self, + )?; + Ok(module) } pub fn new_scope_with_builtins(&self) -> Scope { @@ -341,22 +100,20 @@ impl VirtualMachine { } pub fn new_scope_with_main(&self) -> PyResult { - let scope = self.new_scope_with_builtins(); - let main_module = self.new_module("__main__", scope.globals.clone(), None); + let globals = self.ctx.new_dict(); + let scope = Scope::with_builtins(None, globals.clone(), self); + let main_module = self.new_module("__main__", globals.clone(), None); - self.sys_module.get_attr("modules", self)?.set_item( - "__main__", - main_module.into(), - self, - )?; - self.set_main_builtin_importer(&scope.globals)?; + self.sys_modules() + .set_item("__main__", main_module.into(), self)?; + self.set_main_builtin_importer(&globals)?; Ok(scope) } /// Create `__main__` if it is missing and return it. pub fn ensure_main_module(&self) -> PyResult> { - let sys_modules = self.sys_module.get_attr("modules", self)?; + let sys_modules = self.sys_modules(); let module = if let Ok(existing) = sys_modules.get_item("__main__", self) && let Ok(module) = existing.downcast::() { @@ -371,6 +128,19 @@ impl VirtualMachine { Ok(module) } + /// PyImport_AddModuleRef("__main__") + pub fn add_main_module(&self) -> PyResult> { + let modules = self.sys_modules(); + if let Ok(module) = modules.get_item(identifier!(self, __main__), self) + && let Ok(module) = module.downcast::() + { + return Ok(module); + } + let module = self.new_module("__main__", self.ctx.new_dict(), None); + modules.set_item(identifier!(self, __main__), module.clone().into(), self)?; + Ok(module) + } + /// Set `__main__.__loader__` to BuiltinImporter when it is missing or None. pub fn set_main_builtin_importer( &self, @@ -381,7 +151,7 @@ impl VirtualMachine { { return Ok(()); } - let sys_modules = self.sys_module.get_attr("modules", self)?; + let sys_modules = self.sys_modules(); let Ok(importlib) = sys_modules.get_item("_frozen_importlib", self) else { return Ok(()); }; @@ -416,11 +186,11 @@ impl VirtualMachine { f: F, ) -> PyRef where - F: IntoPyNativeFn, + crate::function::ReceiverFunction: IntoPyNativeFn, { let def = self.ctx.new_method_def( name, - f, + crate::function::ReceiverFunction(f), PyMethodFlags::METHOD, crate::function::ItemDoc::NONE, ); @@ -703,38 +473,6 @@ impl VirtualMachine { .expect("UnicodeEncodeError constructor") } - #[cfg(feature = "parser")] - fn source_has_mixed_tabs_and_spaces(source: Option<&str>, error_line: usize) -> bool { - source.is_some_and(|source| { - let mut has_space_indent = false; - let mut has_tab_indent = false; - for (i, line) in source.lines().enumerate() { - if i + 1 > error_line { - break; - } - let rest = line.trim_start_matches([' ', '\t']); - // Blank and comment-only lines do not participate in indent. - if rest.is_empty() || rest.starts_with('#') { - continue; - } - let indent = &line.as_bytes()[..line.len() - rest.len()]; - if indent.is_empty() { - continue; - } - if indent.contains(&b' ') && indent.contains(&b'\t') { - return true; - } - if indent.contains(&b' ') { - has_space_indent = true; - } - if indent.contains(&b'\t') { - has_tab_indent = true; - } - } - has_space_indent && has_tab_indent - }) - } - // TODO: don't take ownership should make the success path faster pub fn new_key_error(&self, obj: PyObjectRef) -> PyBaseExceptionRef { let key_error = self.ctx.exceptions.key_error.to_owned(); @@ -747,6 +485,17 @@ impl VirtualMachine { error: &crate::compiler::CompileError, source: Option<&str>, allow_incomplete: bool, + ) -> PyBaseExceptionRef { + self.new_syntax_error_with_filename(error, source, allow_incomplete, None) + } + + #[cfg(any(feature = "parser", feature = "compiler"))] + pub(super) fn new_syntax_error_with_filename( + &self, + error: &crate::compiler::CompileError, + source: Option<&str>, + allow_incomplete: bool, + filename: Option<&Py>, ) -> PyBaseExceptionRef { if matches!( error, @@ -758,6 +507,9 @@ impl VirtualMachine { return self.new_recursion_error(error.to_string()); } + let source = source.map(crate::compiler::core::normalize_newlines); + let source = source.as_deref(); + let incomplete_or_syntax = |allow| -> &'static Py { if allow { self.ctx.exceptions.incomplete_input_error @@ -767,31 +519,33 @@ impl VirtualMachine { }; let syntax_error_type = match &error { + #[cfg(feature = "parser")] + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + error: ParseErrorType::Lexical(LexicalErrorType::TabError), + .. + }) => self.ctx.exceptions.tab_error, #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: - ruff_python_parser::ParseErrorType::Lexical( - ruff_python_parser::LexicalErrorType::IndentationError, + ParseErrorType::Lexical( + LexicalErrorType::IndentationError | LexicalErrorType::TooDeepIndentation, ) - | ruff_python_parser::ParseErrorType::UnexpectedIndentation, - location, + | ParseErrorType::UnexpectedIndentation, .. - }) => { - if Self::source_has_mixed_tabs_and_spaces(source, location.line.get()) { - self.ctx.exceptions.tab_error - } else { - self.ctx.exceptions.indentation_error - } - } + }) => self.ctx.exceptions.indentation_error, #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::Lexical( - ruff_python_parser::LexicalErrorType::Eof, + ruff_python_parser::LexicalErrorType::Eof + | ruff_python_parser::LexicalErrorType::UnclosedBracket { + incomplete: true, + .. + }, ), .. }) => incomplete_or_syntax(allow_incomplete), - // Unclosed bracket errors (converted from Eof by from_ruff_parse_error) + // The parser distinguishes incomplete brackets from invalid earlier tokens. #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { is_unclosed_bracket: true, @@ -807,67 +561,53 @@ impl VirtualMachine { error: ruff_python_parser::ParseErrorType::Lexical( ruff_python_parser::LexicalErrorType::FStringError( - ruff_python_parser::InterpolatedStringErrorType::UnterminatedTripleQuotedString, + ruff_python_parser::InterpolatedStringErrorType::UnterminatedTripleQuotedString { .. }, ) | ruff_python_parser::LexicalErrorType::TStringError( - ruff_python_parser::InterpolatedStringErrorType::UnterminatedTripleQuotedString, + ruff_python_parser::InterpolatedStringErrorType::UnterminatedTripleQuotedString { .. }, ), ), .. }) => incomplete_or_syntax(allow_incomplete), #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { - error: - ruff_python_parser::ParseErrorType::Lexical( - ruff_python_parser::LexicalErrorType::UnclosedStringError, - ), + error: ruff_python_parser::ParseErrorType::ExpectedIndentedBlock { .. }, + raw_location, .. }) => { - if allow_incomplete { - incomplete_or_syntax(source.is_some_and(unclosed_string_is_incomplete)) + // The block can still follow when the error is found at whitespace, that is, at + // the end of the input. + let at_end = source.is_some_and(|source| { + source + .get(raw_location.start().to_usize()..raw_location.end().to_usize()) + .is_some_and(|text| text.chars().all(|c| c.is_ascii_whitespace())) + }); + if allow_incomplete && at_end { + self.ctx.exceptions.incomplete_input_error } else { - self.ctx.exceptions.syntax_error + self.ctx.exceptions.indentation_error } } + // _is_end_of_source: the parser failed at the end of the input, + // where more input can still follow. + #[cfg(feature = "parser")] + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + error, + raw_location, + .. + }) if !matches!(error, ParseErrorType::Lexical(_)) + && source + .is_some_and(|source| raw_location.start().to_usize() >= source.len()) => + { + incomplete_or_syntax(allow_incomplete) + } #[cfg(feature = "parser")] crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { error: ruff_python_parser::ParseErrorType::OtherError(s), raw_location, .. }) => { - if s.starts_with("Expected an indented block after") - || s.starts_with("expected an indented block after") - { - if allow_incomplete { - // Check that all chars in the error are whitespace, if so, the source is - // incomplete. Otherwise, we've found code that might violates - // indentation rules. - let mut is_incomplete = true; - if let Some(source) = source { - let start = raw_location.start().to_usize(); - let end = raw_location.end().to_usize(); - let mut iter = source.chars(); - iter.nth(start); - for _ in start..end { - if let Some(c) = iter.next() { - if !c.is_ascii_whitespace() { - is_incomplete = false; - } - } else { - break; - } - } - } - - if is_incomplete { - self.ctx.exceptions.incomplete_input_error - } else { - self.ctx.exceptions.indentation_error // not syntax_error - } - } else { - self.ctx.exceptions.indentation_error - } - } else if allow_incomplete + if allow_incomplete && (s == "incomplete input" || (s == "unexpected EOF while parsing" && source.is_some_and(|source| { @@ -902,58 +642,33 @@ impl VirtualMachine { // Tokenizer/parser errors attach the current source line. Compiler // errors load that line with ProgramText, which is None when the // filename cannot be opened (compile of a string). - let mut statement = if matches!(error, crate::compiler::CompileError::Codegen(_)) { - self.program_text(error.source_path(), error.python_location().0) + let eof_token = match error { + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + eof_token: Some(eof_token), + .. + }) => Some(eof_token), + _ => None, + }; + let mut statement = if let Some(eof_token) = eof_token { + Some(eof_token.line.clone()) + } else if matches!(error, crate::compiler::CompileError::Codegen(_)) { + match filename { + Some(filename) => self + .fsencode(filename) + .ok() + .and_then(|path| self.program_text(path, error.python_location().0)), + None => self.program_text(error.source_path(), error.python_location().0), + } } else { source.and_then(|src| get_statement(src, error.location())) }; - let mut msg = error.to_string(); - if !msg.starts_with("Exceeds the limit ") - && !msg.starts_with("Did you mean ") - && !msg.starts_with("Invalid star expression") - && !msg.starts_with("Function parameters cannot be parenthesized") - && !msg.starts_with("Lambda expression parameters cannot be parenthesized") - && !msg.starts_with("Cannot have two type comments on def") - && !msg.starts_with("Variable annotation syntax is") - && !msg.starts_with("The '@' operator is") - && !msg.starts_with("Async functions are") - && !msg.starts_with("Async comprehensions are") - && !msg.starts_with("Async for loops are") - && !msg.starts_with("Async with statements are") - && !msg.starts_with("Exception groups are") - && !msg.starts_with("Positional-only parameters are") - && !msg.starts_with("Pattern matching is") - && !msg.starts_with("Type statement is") - && !msg.starts_with("Type parameter lists are") - && !msg.starts_with("Type parameter defaults are") - && !msg.starts_with("Assignment expressions are") - && !msg.starts_with("Await expressions are") - && !msg.starts_with("Underscores in numeric literals are") - && !msg.starts_with("Missing parentheses") - && let Some(msg) = msg.get_mut(..1) - { - msg.make_ascii_lowercase(); - } - - cfg_select! { - feature = "parser" => { - let mut syntax_error_info = SyntaxErrorInfo::new(msg, false); - syntax_error_info.analyze_compile_error(error); - } - _ => { - let syntax_error_info = SyntaxErrorInfo::new(msg, false); - } + let msg = if syntax_error_type.is(self.ctx.exceptions.incomplete_input_error) { + String::from("incomplete input") + } else { + error.to_string() }; - if syntax_error_type.is(self.ctx.exceptions.tab_error) { - syntax_error_info.msg = - String::from("inconsistent use of tabs and spaces in indentation"); - } else if syntax_error_type.is(self.ctx.exceptions.incomplete_input_error) { - syntax_error_info.msg = String::from("incomplete input"); - } - - let SyntaxErrorInfo { msg, narrow_caret } = syntax_error_info; let unterminated_triple_quoted_string = msg.starts_with("unterminated triple-quoted"); let unexpected_eof_error = msg == "unexpected EOF while parsing"; if unterminated_triple_quoted_string @@ -970,6 +685,52 @@ impl VirtualMachine { || msg.starts_with("except expressions without parentheses are") || msg.starts_with("Pattern matching is"); let line_end_binary_operator_error = msg.starts_with("The '@' operator is"); + // Tokenizer errors other than unexpected EOF end where the tokenizer stopped, which is + // reported as end offset 0 or -1, or where they start. + let tokenizer_end_offset = cfg_select! { + feature = "parser" => { + match error { + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + error: + ParseErrorType::Lexical( + LexicalErrorType::TabError + | LexicalErrorType::TooDeepIndentation + | LexicalErrorType::LineContinuationError + | LexicalErrorType::UnclosedBracket { .. }, + ), + .. + }) => Some(0), + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + error: + ParseErrorType::Lexical(LexicalErrorType::IndentationError) + | ParseErrorType::UnexpectedIndentation, + .. + }) => Some(-1), + // The span runs from the last character of the key to the end of the line. + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + error: ParseErrorType::ExpectedColonAfterDictionaryKey, + .. + }) => Some(0), + // Other tokenizer errors end where they start, except those reported + // over a range. + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + error: ParseErrorType::Lexical(lexical), + .. + }) if lexical.is_tokenizer_error() + && !matches!( + lexical, + LexicalErrorType::Eof + | LexicalErrorType::LeadingZerosInDecimalInteger + | LexicalErrorType::IncompatibleStringPrefixes { .. } + ) => + { + Some(error.python_location().1 as isize) + } + _ => None, + } + } + _ => None, + }; let unclosed_bracket_error = cfg_select! { feature = "parser" => { matches!( @@ -1003,23 +764,40 @@ impl VirtualMachine { // Set end_lineno and end_offset if available if let Some((end_lineno, end_offset)) = error.python_end_location() { // EOF errors have no source span in CPython. + let standalone_case_suite = cfg_select! { + feature = "parser" => { + matches!( + error, + crate::compiler::CompileError::Parse(rustpython_compiler::ParseError { + error: ruff_python_parser::ParseErrorType::ExpectedIndentedBlock { + clause: ruff_python_parser::BlockClause::StandaloneCase, + .. + }, + .. + }) + ) + } + _ => false, + }; let no_end_offset = unexpected_eof_error + || standalone_case_suite || (check_version_suite_error && statement .as_deref() .and_then(|line| line.chars().next()) .is_some_and(|ch| ch.is_ascii_whitespace())); - let (end_lineno, end_offset) = if no_end_offset { + let (end_lineno, end_offset) = if let Some(eof_token) = eof_token { + (eof_token.lineno, eof_token.end_offset()) + } else if no_end_offset { (end_lineno, -1) + } else if let Some(end_offset) = tokenizer_end_offset { + (end_lineno, end_offset) } else if unclosed_bracket_error { // The bracket that was never closed is marked where it opened, // and the span stops there. (end_lineno, 0) } else if line_end_binary_operator_error && end_offset == offset_raw { (end_lineno, (end_offset + 1) as isize) - } else if narrow_caret { - let (l, o) = error.python_location(); - (l, (o + 1) as isize) } else { (end_lineno, end_offset as isize) }; @@ -1035,7 +813,9 @@ impl VirtualMachine { set_attrs!( syntax_error.as_object(), self, unwrap, "text" => statement.to_pyobject(self), - "filename" => self.ctx.new_str(error.source_path()) + "filename" => filename.map_or_else( + || self.ctx.new_str(error.source_path()), ToOwned::to_owned, + ) ); // Set _metadata for keyword typo suggestions in traceback module. @@ -1207,119 +987,3 @@ impl VirtualMachine { .upcast() } } - -#[cfg(feature = "parser")] -enum QuotedStringScan { - Closed(usize), - Unclosed { - triple: bool, - unescaped_newline: bool, - }, -} - -/// An unclosed string is incomplete when more input could still finish it. -/// A non-triple string that already hit an unescaped newline is a hard error. -#[cfg(feature = "parser")] -fn unclosed_string_is_incomplete(source: &str) -> bool { - let bytes = source.as_bytes(); - let mut index = 0; - while index < bytes.len() { - match bytes[index] { - b'#' => { - while index < bytes.len() && bytes[index] != b'\n' { - index += 1; - } - } - b'\'' | b'"' => match scan_quoted_string_for_incomplete(bytes, index) { - QuotedStringScan::Closed(end) => index = end, - QuotedStringScan::Unclosed { - triple, - unescaped_newline, - } => { - // Single-quoted f/t-strings never set E_EOLS. - if !triple && interpolated_string_prefix_at(bytes, index) { - return false; - } - return triple || !unescaped_newline; - } - }, - _ => index += 1, - } - } - false -} - -#[cfg(feature = "parser")] -fn interpolated_string_prefix_at(bytes: &[u8], quote: usize) -> bool { - let Some(&prev) = quote.checked_sub(1).and_then(|index| bytes.get(index)) else { - return false; - }; - let lower = prev.to_ascii_lowercase(); - let marker_index = if matches!(lower, b'f' | b't') { - if quote >= 2 && bytes[quote - 2].eq_ignore_ascii_case(&b'r') { - quote - 2 - } else { - quote - 1 - } - } else if lower == b'r' - && quote >= 2 - && matches!(bytes[quote - 2].to_ascii_lowercase(), b'f' | b't') - { - quote - 2 - } else { - return false; - }; - marker_index == 0 || !identifier_continue_before(bytes, marker_index) -} - -#[cfg(feature = "parser")] -fn identifier_continue_before(bytes: &[u8], index: usize) -> bool { - if index == 0 { - return false; - } - if bytes[index - 1].is_ascii() { - return bytes[index - 1] == b'_' || bytes[index - 1].is_ascii_alphanumeric(); - } - let mut start = index - 1; - while start > 0 && bytes[start] & 0b1100_0000 == 0b1000_0000 { - start -= 1; - } - ::core::str::from_utf8(&bytes[start..index]) - .ok() - .and_then(|text| text.chars().next_back()) - .is_some_and(|ch| ch == '_' || ch.is_alphanumeric()) -} - -#[cfg(feature = "parser")] -fn scan_quoted_string_for_incomplete(bytes: &[u8], quote_index: usize) -> QuotedStringScan { - let quote = bytes[quote_index]; - let triple = - bytes.get(quote_index + 1) == Some("e) && bytes.get(quote_index + 2) == Some("e); - let mut index = quote_index + if triple { 3 } else { 1 }; - while index < bytes.len() { - if bytes[index] == b'\\' { - index = (index + 2).min(bytes.len()); - continue; - } - if triple { - if bytes.get(index) == Some("e) - && bytes.get(index + 1) == Some("e) - && bytes.get(index + 2) == Some("e) - { - return QuotedStringScan::Closed(index + 3); - } - } else if bytes[index] == quote { - return QuotedStringScan::Closed(index + 1); - } else if bytes[index] == b'\n' { - return QuotedStringScan::Unclosed { - triple: false, - unescaped_newline: true, - }; - } - index += 1; - } - QuotedStringScan::Unclosed { - triple, - unescaped_newline: false, - } -} diff --git a/crates/vm/src/vm/vm_object.rs b/crates/vm/src/vm/vm_object.rs index baa0c8095c6..261f4d69fbc 100644 --- a/crates/vm/src/vm/vm_object.rs +++ b/crates/vm/src/vm/vm_object.rs @@ -1,14 +1,30 @@ use super::PyMethod; use crate::{ - builtins::{PyBaseExceptionRef, PyList, PyStrInterned, pystr::AsPyStr}, + builtins::{PyBaseExceptionRef, PyList, PyListRef, PyStrInterned, pystr::AsPyStr}, function::IntoFuncArgs, object::{AsObject, PyObject, PyObjectRef, PyResult}, - stdlib::sys, vm::VirtualMachine, }; /// PyObject support impl VirtualMachine { + /// PyObject_Dump + /// + /// Write a description of `obj` to the process stderr, bypassing + /// `sys.stderr`. + pub fn dump_object(&self, obj: &PyObject) { + let class = obj.class(); + eprintln!("object address : {obj:p}"); + eprintln!("object refcount : {}", obj.strong_count()); + eprintln!("object type : {class:p}"); + eprintln!("object type name: {}", class.slot_name()); + eprint!("object repr : "); + if let Ok(repr) = obj.repr(self) { + eprint!("{}", repr.as_wtf8()); + } + eprintln!(); + } + #[track_caller] #[cold] fn _py_panic_failed(&self, exc: PyBaseExceptionRef, msg: &str) -> ! { @@ -51,23 +67,29 @@ impl VirtualMachine { } pub(crate) fn flush_std(&self) -> i32 { - let vm = self; - let status = if let Ok(stdout) = sys::get_stdout(vm) - && !vm.is_none(&stdout) - && !vm.file_is_closed(&stdout) - && let Err(e) = vm.call_method(&stdout, identifier!(vm, flush).as_str(), ()) - { - vm.run_unraisable(e, None, stdout); - -1 - } else { - 0 - }; - - if let Ok(stderr) = sys::get_stderr(vm) - && !vm.is_none(&stderr) - && !vm.file_is_closed(&stderr) - { - let _ = vm.call_method(&stderr, identifier!(vm, flush).as_str(), ()); + let mut status = 0; + for name in ["stdout", "stderr"] { + // Keep the stream alive until its failure has been reported: a + // flush or hook can replace the reference stored in sys.__dict__. + let file = self.sys_module.dict().get_item_opt(name, self); + let result = match &file { + Ok(Some(file)) if !self.is_none(file) && !self.file_is_closed(file) => { + self.call_method(file, "flush", ()).map(drop) + } + Ok(_) => Ok(()), + Err(error) => Err(error.clone()), + }; + if let Err(error) = result { + status = -1; + if name == "stdout" { + self.run_unraisable( + error, + Some("Exception ignored while flushing sys.stdout".to_owned()), + self.ctx.none(), + ); + } + // Reporting a stderr failure could require the broken stream. + } } status } @@ -140,20 +162,33 @@ impl VirtualMachine { PyMethod::get(obj.to_owned(), name, self)?.invoke(args, self) } - pub fn dir(&self, obj: Option) -> PyResult { - let seq = match obj { - Some(obj) => self - .get_special_method(&obj, identifier!(self, __dir__))? - .ok_or_else(|| self.new_type_error("object does not provide __dir__"))? - .invoke((), self)?, - None => self.call_method( - self.current_locals()?.as_object(), - identifier!(self, keys).as_str(), - (), - )?, + pub fn dir(&self, obj: Option) -> PyResult { + // Keep the input alive until collection and sorting have both finished. + let lst = match obj.as_ref() { + Some(obj) => { + let seq = + PyMethod::get_special_ex::(obj, identifier!(self, __dir__), self, true)? + .ok_or_else(|| self.new_type_error("object does not provide __dir__"))? + .invoke((), self)?; + // PySequence_List asks the returned iterable for its length hint. + let items = self.extract_elements_sized(&seq, &|| 0, Ok); + drop(seq); + self.ctx.new_list(items?) + } + None => { + let locals = self.current_locals()?; + let keys = locals.mapping().keys(self)?; + // Mapping keys preserve an exact list returned by user code. + // The exact-dict fast path instead supplies a keys view. + match keys.downcast::() { + Ok(list) => list, + Err(keys) => { + self.ctx + .new_list(self.extract_elements_sized(&keys, &|| 0, Ok)?) + } + } + } }; - let items: Vec<_> = seq.try_to_value(self)?; - let lst = PyList::from(items); lst.sort(Default::default(), self)?; Ok(lst) } @@ -167,6 +202,20 @@ impl VirtualMachine { PyMethod::get_special::(obj, method, self) } + /// Call a special method, treating AttributeError from descriptor binding + /// as a missing method. Errors raised by the method itself are preserved. + #[doc(hidden)] + pub fn call_special_method_opt( + &self, + obj: &PyObject, + method: &'static PyStrInterned, + args: impl IntoFuncArgs, + ) -> PyResult> { + self.get_special_method(obj, method)? + .map(|method| method.invoke(args, self)) + .transpose() + } + /// NOT PUBLIC API #[doc(hidden)] pub fn call_special_method( diff --git a/crates/vm/src/vm/vm_ops.rs b/crates/vm/src/vm/vm_ops.rs index b2a5edba28f..b7fbb586364 100644 --- a/crates/vm/src/vm/vm_ops.rs +++ b/crates/vm/src/vm/vm_ops.rs @@ -8,6 +8,7 @@ use crate::{ types::PyComparisonOp, }; use num_traits::ToPrimitive; +use rustpython_common::wtf8::wtf8_concat; /// [CPython `method_is_overloaded`](https://github.com/python/cpython/blob/v3.14.3/Objects/typeobject.c#L9849-L9879) fn method_is_overloaded( @@ -126,36 +127,35 @@ impl VirtualMachine { } } } - let hint = match self.get_method(iter, identifier!(self, __length_hint__)) { - Some(hint) => hint?, - None => return Ok(None), + let result = { + let Some(hint) = iter.lookup_special(identifier!(self, __length_hint__), self)? else { + return Ok(None); + }; + // Release the bound method before checking the result. + hint.call((), self) }; - let result = match hint.call((), self) { - Ok(res) => { - if res.is(&self.ctx.not_implemented) { - return Ok(None); - } - res - } - Err(e) => { - return if e.fast_isinstance(self.ctx.exceptions.type_error) { - Ok(None) - } else { - Err(e) - }; - } + let hint = { + let result = match result { + Ok(result) if !result.is(&self.ctx.not_implemented) => result, + Ok(_) => return Ok(None), + Err(e) if e.fast_isinstance(self.ctx.exceptions.type_error) => return Ok(None), + Err(e) => return Err(e), + }; + let Some(hint) = result.downcast_ref::() else { + return Err(self.new_type_error(wtf8_concat!( + iter.class().fully_qualified_name(self)?, + ".__length_hint__() must return an int, not ", + result.class().fully_qualified_name(self)?, + ))); + }; + // Release the integer before formatting a negative-size error. + hint.as_ssize_t(self)? }; - let hint = result - .downcast_ref::() - .ok_or_else(|| { - self.new_type_error(format!( - "'{}' object cannot be interpreted as an integer", - result.class().name() - )) - })? - .try_to_primitive::(self)?; if hint.is_negative() { - Err(self.new_value_error("__length_hint__() should return >= 0")) + Err(self.new_value_error(wtf8_concat!( + iter.class().fully_qualified_name(self)?, + ".__length_hint__() must return a non-negative int", + ))) } else { Ok(Some(hint as usize)) } @@ -163,13 +163,14 @@ impl VirtualMachine { /// Checks that the multiplication is able to be performed. On Ok returns the /// index as a usize for sequences to be able to use immediately. + /// Overflow raises MemoryError, matching CPython's allocation checks. pub fn check_repeat_or_overflow_error(&self, length: usize, n: isize) -> PyResult { if n <= 0 { Ok(0) } else { let n = n as usize; if length > crate::stdlib::sys::MAXSIZE as usize / n { - Err(self.new_overflow_error("repeated value are too long")) + Err(self.no_memory_error()) } else { Ok(n) } @@ -630,3 +631,24 @@ impl VirtualMachine { seq.contains(needle, self) } } + +#[cfg(test)] +mod tests { + use crate::AsObject; + + #[test] + fn overflowing_sequence_repetition_raises_memory_error() { + crate::Interpreter::without_stdlib(Default::default()).enter(|vm| { + assert_eq!(vm.check_repeat_or_overflow_error(3, -1).unwrap(), 0); + assert_eq!(vm.check_repeat_or_overflow_error(3, 2).unwrap(), 2); + assert_eq!( + vm.check_repeat_or_overflow_error(0, isize::MAX).unwrap(), + isize::MAX as usize, + ); + let err = vm + .check_repeat_or_overflow_error(isize::MAX as usize, 2) + .unwrap_err(); + assert!(err.fast_isinstance(vm.ctx.exceptions.memory_error)); + }); + } +} diff --git a/crates/vm/src/warn.rs b/crates/vm/src/warn.rs index 3d8e7cb6fb1..0f155f961d2 100644 --- a/crates/vm/src/warn.rs +++ b/crates/vm/src/warn.rs @@ -2,8 +2,8 @@ use crate::{ AsObject, Context, Py, PyAtomicRef, PyObject, PyObjectRef, PyResult, VirtualMachine, anystr::SplitLinesArgs, builtins::{ - PyBaseExceptionRef, PyDict, PyDictRef, PyList, PyListRef, PyStr, PyStrInterned, PyStrRef, - PyTuple, PyTupleRef, PyType, PyTypeRef, + PyAnyDict, PyBaseExceptionRef, PyDict, PyDictRef, PyList, PyListRef, PyStr, PyStrInterned, + PyStrRef, PyTuple, PyTupleRef, PyType, PyTypeRef, }, convert::TryFromObject, }; @@ -100,14 +100,33 @@ impl WarningsState { /// None matches everything; plain strings do exact comparison; /// regex objects use .match(). -fn check_matched(obj: &PyObject, arg: &PyObject, vm: &VirtualMachine) -> PyResult { +fn check_matched( + obj: &PyObject, + arg: Option<&PyObject>, + arg2: Option<&Py>, + vm: &VirtualMachine, +) -> PyResult { + // A 'None' filter always matches if vm.is_none(obj) { return Ok(true); } + // An internal plain text default filter must match exactly if obj.class().is(vm.ctx.types.str_type) { - return obj.rich_compare_bool(arg, crate::types::PyComparisonOp::Eq, vm); + return match arg { + Some(arg) => obj.rich_compare_bool(arg, crate::types::PyComparisonOp::Eq, vm), + None => Ok(false), + }; } - let result = vm.call_method(obj, "match", (arg.to_owned(),))?; + // Otherwise assume a regex filter and call its match() method + let result = match arg { + Some(arg) => vm.call_method(obj, "match", (arg.to_owned(),))?, + None => { + let match_filename = vm + .import("_py_warnings", 0)? + .get_attr("_match_filename", vm)?; + match_filename.call((obj.to_owned(), arg2.map(|f| f.to_owned())), vm)? + } + }; result.is_true(vm) } @@ -128,7 +147,7 @@ fn get_warnings_attr( Err(e) => return Err(e), } } else { - let Ok(modules) = vm.sys_module.get_attr(identifier!(vm, modules), vm) else { + let Some(modules) = vm.state.modules.get() else { return Ok(None); }; match modules.get_item(vm.ctx.intern_str("warnings"), vm) { @@ -200,22 +219,35 @@ pub(crate) fn get_source_line( return Ok(None); }; - let module_name = if let Some(dict) = module_globals.downcast_ref::() { - match dict.get_item_opt(identifier!(vm, __name__), vm)? { + let Some(globals) = PyAnyDict::from_object(module_globals) else { + return Ok(None); + }; + // A script's __name__ can be __main__, while its loader requires the + // importable name recorded by the module spec. Use internal dictionary + // lookup, not a subclass override of __getitem__. + let spec = globals.inner_getitem_opt(vm.ctx.intern_str("__spec__"), vm)?; + let spec_name = match spec { + Some(spec) => vm.get_attribute_opt(&spec, vm.ctx.intern_str("name"))?, + None => None, + }; + let module_name = match spec_name.filter(|name| !vm.is_none(name)) { + Some(name) => name, + None => match globals.inner_getitem_opt(identifier!(vm, __name__), vm)? { Some(name) => name, None => return Ok(None), - } - } else { - match module_globals.get_item(identifier!(vm, __name__), vm) { - Ok(name) => name, - Err(_) => return Ok(None), - } + }, }; let Some(get_source) = vm.get_attribute_opt(&loader, vm.ctx.intern_str("get_source"))? else { return Ok(None); }; - let source = get_source.call((module_name,), vm)?; + let source = match get_source.call((module_name,), vm) { + Ok(source) => source, + Err(error) if error.fast_isinstance(vm.ctx.exceptions.import_error) => { + return Ok(None); + } + Err(error) => return Err(error), + }; if vm.is_none(&source) { return Ok(None); } @@ -224,14 +256,10 @@ pub(crate) fn get_source_line( return Err(vm.new_type_error(format!("expected str, not {}", source.class().name()))); }; let lines = source_str.splitlines(SplitLinesArgs { keepends: false }, vm); - if lineno == 0 { - return Err(vm.new_index_error("list index out of range")); - } - lines - .get(lineno - 1) - .cloned() - .ok_or_else(|| vm.new_index_error("list index out of range")) - .map(Some) + Ok(lineno + .checked_sub(1) + .and_then(|index| lines.get(index)) + .cloned()) } /// Get the default action from `sys.modules['warnings'].defaultaction`, @@ -336,22 +364,14 @@ fn update_registry( already_warned(registry, &altkey, true, vm) } -fn normalize_module(filename: &Py, vm: &VirtualMachine) -> PyObjectRef { - match filename.byte_len() { - 0 => vm.new_pyobj(""), - len if len >= 3 && filename.as_bytes().ends_with(b".py") => { - vm.new_pyobj(&filename.as_wtf8()[..len - 3]) - } - _ => filename.as_object().to_owned(), - } -} - /// Search a filters list for a matching action. +#[allow(clippy::too_many_arguments)] fn filter_search( category: &PyObject, text: &PyObject, lineno: usize, - module: &PyObject, + module: Option<&PyObject>, + filename: &Py, filters: &PyListRef, list_name: &str, vm: &VirtualMachine, @@ -378,9 +398,9 @@ fn filter_search( action.class().name() ))); } - let good_msg = check_matched(&tmp_item.as_slice()[1], text, vm)?; + let good_msg = check_matched(&tmp_item.as_slice()[1], Some(text), None, vm)?; let is_subclass = category.is_subclass(&tmp_item.as_slice()[2], vm)?; - let good_mod = check_matched(&tmp_item.as_slice()[3], module, vm)?; + let good_mod = check_matched(&tmp_item.as_slice()[3], module, Some(filename), vm)?; let ln: usize = tmp_item.as_slice()[4] .try_int(vm) .map_or(0, |v| v.as_u32_mask() as _); @@ -397,7 +417,8 @@ fn get_filter( category: &PyObject, text: &PyObject, lineno: usize, - module: &PyObject, + module: Option<&PyObject>, + filename: &Py, vm: &VirtualMachine, ) -> PyResult { if let Some(context_filters) = get_warnings_context_filters(vm)? { @@ -406,6 +427,7 @@ fn get_filter( text, lineno, module, + filename, &context_filters, "_warnings_context _filters", vm, @@ -416,7 +438,9 @@ fn get_filter( } let filters = get_warnings_filters(vm)?; - if let Some(action) = filter_search(category, text, lineno, module, &filters, "filters", vm)? { + if let Some(action) = filter_search( + category, text, lineno, module, filename, &filters, "filters", vm, + )? { return Ok(action); } get_default_action(vm) @@ -504,9 +528,11 @@ pub fn warn_explicit( source: Option, vm: &VirtualMachine, ) -> PyResult<()> { - // Normalize module. None → silent return (late-shutdown safety). - let module = module.unwrap_or_else(|| normalize_module(&filename, vm)); - if vm.is_none(&module) { + // module can be None if a warning is emitted late during Python shutdown. + // In this case, the Python warnings module was probably unloaded, filters + // are no more available to choose as action. It is safer to ignore the + // warning and do nothing. + if module.as_ref().is_some_and(|module| vm.is_none(module)) { return Ok(()); } @@ -543,7 +569,14 @@ pub fn warn_explicit( } // Get filter action - let action = get_filter(category.as_object(), text.as_object(), lineno, &module, vm)?; + let action = get_filter( + category.as_object(), + text.as_object(), + lineno, + module.as_deref(), + &filename, + vm, + )?; let action_str = PyStrRef::try_from_object(vm, action) .map_err(|_| vm.new_type_error("action must be a string"))?; @@ -603,6 +636,7 @@ pub fn warn_explicit( lineno_obj, source_line, source, + module, vm, ) } @@ -617,10 +651,10 @@ fn call_show_warning( lineno_obj: PyObjectRef, source_line: Option, source: Option, + module: Option, vm: &VirtualMachine, ) -> PyResult<()> { - let Some(show_fn) = get_warnings_attr(vm, identifier!(vm, _showwarnmsg), source.is_some())? - else { + let Some(show_fn) = get_warnings_attr(vm, identifier!(vm, _showwarnmsg), true)? else { show_warning(&filename, lineno, text, &category, source_line, vm); return Ok(()); }; @@ -640,8 +674,9 @@ fn call_show_warning( filename.into(), lineno_obj, vm.ctx.none(), - vm.ctx.none(), + vm.unwrap_or_none(source_line), vm.unwrap_or_none(source), + vm.unwrap_or_none(module), ], vm, )?; @@ -718,20 +753,16 @@ fn setup_context( // Stack level comparisons to Python code is off by one as there is no // warnings-related stack level to avoid. if stack_level <= 0 || f.as_ref().is_some_and(|frame| frame.is_internal_frame()) { - while { + while stack_level > 1 { stack_level -= 1; - stack_level > 0 - } { match f { Some(tmp) => f = tmp.f_back(vm), None => break, } } } else { - while { + while stack_level > 1 { stack_level -= 1; - stack_level > 0 - } { match f { Some(tmp) => f = next_external_frame_with_skip(&tmp, skip_file_prefixes, vm), None => break, @@ -745,15 +776,8 @@ fn setup_context( f.iframe().code().source_path(), f.lineno().max(0) as usize, ) - } else if let Some(frame) = vm.current_frame() { - // We have a frame but it wasn't found during stack walking - ( - frame.iframe().globals().to_owned(), - vm.ctx.intern_str(""), - 1, - ) } else { - // No frames on the stack - use sys.__dict__ (interp->sysdict) + // An exhausted stack walk uses sys.__dict__ (interp->sysdict). let globals = vm .sys_module .as_object() @@ -762,12 +786,12 @@ fn setup_context( d.downcast::() .map_err(|_| vm.new_type_error("sys.__dict__ is not a dictionary")) })?; - (globals, vm.ctx.intern_str(""), 0) + (globals.into(), vm.ctx.intern_str(""), 0) }; - let registry = match globals.get_item("__warningregistry__", vm) { - Ok(r) => r, - Err(_) => { + let registry = match globals.inner_getitem_opt("__warningregistry__", vm)? { + Some(r) => r, + None => { let r = vm.ctx.new_dict(); globals.set_item("__warningregistry__", r.clone().into(), vm)?; r.into() @@ -776,7 +800,8 @@ fn setup_context( // Setup module. let module = globals - .get_item("__name__", vm) - .unwrap_or_else(|_| vm.new_pyobj("")); + .inner_getitem_opt("__name__", vm)? + .filter(|module| vm.is_none(module) || module.downcastable::()) + .unwrap_or_else(|| vm.new_pyobj("")); Ok((filename.to_owned(), lineno, Some(module), registry)) } diff --git a/crates/vm/src/windows.rs b/crates/vm/src/windows.rs index aed2b3fd689..ab7e1492b94 100644 --- a/crates/vm/src/windows.rs +++ b/crates/vm/src/windows.rs @@ -1,13 +1,104 @@ use crate::{ - PyObjectRef, PyResult, TryFromObject, VirtualMachine, + PyObject, PyObjectRef, PyResult, TryFromObject, VirtualMachine, + builtins::PyInt, convert::{ToPyObject, ToPyResult}, }; +use num_traits::ToPrimitive; use rustpython_host_env::nt as host_nt; /// Windows HANDLE wrapper for Python interop #[derive(Clone, Copy)] pub struct WinHandle(pub host_nt::Handle); +impl WinHandle { + /// Convert an F_HANDLE bitfield after the caller has finished binding. + /// The caller must keep the original argument alive through its operation. + pub(crate) fn from_bitfield( + obj: &PyObject, + vm: &VirtualMachine, + callee: &str, + argument: &str, + ) -> PyResult { + let value = Self::parse_bitfield::<{ usize::BITS }>(obj, vm, callee, argument)?; + Ok(Self(value as host_nt::Handle)) + } + + /// Convert a Windows `unsigned long` (`k`) after argument binding. + pub(crate) fn unsigned_long_bitfield( + obj: &PyObject, + vm: &VirtualMachine, + callee: &str, + argument: &str, + ) -> PyResult { + Ok(Self::parse_bitfield::<32>(obj, vm, callee, argument)? as u32) + } + + fn parse_bitfield( + obj: &PyObject, + vm: &VirtualMachine, + callee: &str, + argument: &str, + ) -> PyResult { + let (handle, fits) = { + let owned; + let int = if let Some(int) = obj.downcast_ref::() { + int + } else if let Some(index) = obj.try_index_opt(vm) { + owned = index?; + &owned + } else { + let actual = if vm.is_none(obj) { + b"None".to_vec() + } else { + let name = obj.class().slot_name(); + name.as_bytes()[..name.len().min(50)].to_vec() + }; + let mut message = format!("{callee}() {argument} must be int, not ").into_bytes(); + message.extend_from_slice(&actual); + return Err(match String::from_utf8(message) { + Ok(message) => vm.new_type_error(message), + Err(error) => { + let start = error.utf8_error().valid_up_to(); + let bytes = error.into_bytes(); + let end = bytes.len(); + vm.new_unicode_decode_error( + vm.ctx.new_str("utf-8"), + vm.ctx.new_bytes(bytes), + start, + end, + vm.ctx.new_str("unexpected end of data"), + ) + } + }); + }; + if WIDTH == 32 { + if let Some(value) = int.as_bigint().to_i32() { + (value as u32 as usize, true) + } else if let Some(value) = int.as_bigint().to_u32() { + (value as usize, true) + } else { + (int.as_u32_mask() as usize, false) + } + } else if let Some(value) = int.as_bigint().to_isize() { + (value as usize, true) + } else if let Some(value) = int.as_bigint().to_usize() { + (value, true) + } else { + (int.as_u64_mask() as usize, false) + } + }; + if !fits { + crate::stdlib::_warnings::warn( + vm.ctx.exceptions.deprecation_warning, + "integer value out of range".to_owned(), + 1, + vm, + )?; + } + Ok(handle) + } +} + pub(crate) trait WindowsSysResultValue { type Ok: ToPyObject; diff --git a/crates/vm/tests/exception_payload.rs b/crates/vm/tests/exception_payload.rs new file mode 100644 index 00000000000..41b7f9d3d68 --- /dev/null +++ b/crates/vm/tests/exception_payload.rs @@ -0,0 +1,138 @@ +#![cfg(test)] +#![cfg(all(feature = "compiler", feature = "gc"))] + +extern crate alloc; + +use alloc::sync::Arc; +use core::sync::atomic::{AtomicBool, Ordering}; +use rustpython_vm::{ + AsObject, Interpreter, Py, PyObjectRef, PyPayload, PyResult, VirtualMachine, + builtins::{PyBaseException, PyType, PyValueError}, + class::{PyClassImpl, PySubclass}, + function::FuncArgs, + object::{Traverse, TraverseFn}, + pyclass, + types::Constructor, +}; + +static SERIAL: std::sync::Mutex<()> = std::sync::Mutex::new(()); + +#[pyclass(module = "exception_payload_test", name = "DropError", base = PyValueError, traverse = "manual")] +#[repr(C)] +#[derive(Debug)] +struct DropError { + base: PyValueError, + dropped: Arc, +} + +// SAFETY: repr(C) keeps the valid base first; pyclass checks offset and alignment. +unsafe impl PySubclass for DropError { + type Base = PyValueError; + + fn as_base(&self) -> &Self::Base { + &self.base + } +} + +// SAFETY: The base owns every Python reference; the flag owns none. +unsafe impl Traverse for DropError { + fn traverse(&self, tracer_fn: &mut TraverseFn<'_>) { + self.base.traverse(tracer_fn); + } + + fn clear(&mut self, out: &mut Vec) { + self.base.clear(out); + } +} + +#[pyclass(with(Constructor))] +impl DropError {} + +impl Constructor for DropError { + type Args = FuncArgs; + + fn py_new(cls: &Py, args: FuncArgs, vm: &VirtualMachine) -> PyResult { + Ok(Self { + base: PyValueError::py_new(cls, args, vm)?, + dropped: Arc::new(AtomicBool::new(false)), + }) + } +} + +impl Drop for DropError { + fn drop(&mut self) { + self.dropped.store(true, Ordering::SeqCst); + } +} + +#[test] +fn owned_native_exception_round_trips_through_python() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let class = DropError::make_static_type(); + let argument = vm.ctx.new_str("payload"); + let payload = DropError::py_new(&class, vec![argument.clone().into()].into(), vm).unwrap(); + let dropped = payload.dropped.clone(); + let exception = payload.into_ref_with_type(vm, class).unwrap(); + let base = exception.as_base().as_base().as_base(); + assert!(base.__traceback__().is_none()); + assert!(base.__cause__().is_none()); + assert!(base.__context__().is_none()); + assert!( + !exception + .as_object() + .get_attr("__suppress_context__", vm) + .unwrap() + .try_to_bool(vm) + .unwrap() + ); + assert!(!dropped.load(Ordering::SeqCst)); + + let scope = vm.new_scope_with_builtins(); + scope.globals.set_item("exc", exception.into(), vm).unwrap(); + scope.globals.set_item("arg", argument.into(), vm).unwrap(); + let source = r#" +try: + raise exc +except ValueError as e: + assert e.args == (arg,) + assert isinstance(e, ValueError) + caught = e +"#; + let code = vm + .compile( + source, + rustpython_vm::compiler::Mode::Exec, + "", + ) + .map_err(|error| error.into_pyexception(vm, Some(source))) + .unwrap(); + if let Err(error) = vm.run_code_obj(code, scope.clone()) { + vm.print_exception(&error); + panic!("owned native exception round-trip failed"); + } + let caught = scope.globals.get_item("caught", vm).unwrap(); + let native = caught.downcast::().unwrap(); + assert!(Arc::ptr_eq(&native.dropped, &dropped)); + assert!(!native.dropped.load(Ordering::SeqCst)); + }); +} + +#[test] +fn context_cycle_destroys_owned_exception_payload() { + let _serial = SERIAL.lock().unwrap_or_else(|e| e.into_inner()); + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let class = DropError::make_static_type(); + let payload = DropError::py_new(&class, FuncArgs::default(), vm).unwrap(); + let dropped = payload.dropped.clone(); + let exception = payload.into_ref_with_type(vm, class).unwrap(); + let base = exception.as_base().as_base().as_base(); + base.set_context(Some(exception.clone().upcast::())); + assert!(base.__context__().unwrap().is(exception.as_object())); + assert!(!dropped.load(Ordering::SeqCst)); + drop(exception); + assert!(!dropped.load(Ordering::SeqCst)); + vm.state.gc.collect_force(2); + assert!(dropped.load(Ordering::SeqCst)); + }); +} diff --git a/crates/vm/tests/host_io.rs b/crates/vm/tests/host_io.rs new file mode 100644 index 00000000000..f9e663b7623 --- /dev/null +++ b/crates/vm/tests/host_io.rs @@ -0,0 +1,165 @@ +//! Embedding feature coverage, separate from the Python test_io behavior suite. +#![cfg(all(feature = "host_io", feature = "compiler", not(target_arch = "wasm32")))] + +#[cfg(test)] +mod tests { + use rustpython_vm::Interpreter; + #[cfg(unix)] + use std::{ + io::Write, + os::fd::{AsRawFd, FromRawFd, OwnedFd}, + }; + + #[cfg(unix)] + fn pipe() -> (OwnedFd, std::fs::File) { + let mut fds = [-1; 2]; + // SAFETY: pipe writes two descriptors to the supplied array. + assert_eq!(unsafe { libc::pipe(fds.as_mut_ptr()) }, 0); + // SAFETY: a successful pipe call transfers ownership of both descriptors. + unsafe { + ( + OwnedFd::from_raw_fd(fds[0]), + std::fs::File::from_raw_fd(fds[1]), + ) + } + } + + #[test] + #[cfg(unix)] + fn fileio_available_without_other_host_modules() { + let (reader, mut writer) = pipe(); + writer.write_all(b"host pipe").unwrap(); + drop(writer); + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let scope = vm.new_scope_with_builtins(); + scope + .globals + .set_item("read_fd", vm.ctx.new_int(reader.as_raw_fd()).into(), vm) + .unwrap(); + scope + .globals + .set_item( + "full_host", + vm.ctx.new_bool(cfg!(feature = "host_env")).into(), + vm, + ) + .unwrap(); + let source = r#" +import _io, sys +if not full_host: + assert 'posix' not in sys.builtin_module_names + assert '_ctypes' not in sys.builtin_module_names +with _io.FileIO(read_fd, 'rb', closefd=False) as raw: + assert not raw.seekable() + with _io.BufferedReader(raw) as buffered: + data = bytearray(9) + assert buffered.readinto(data) == 9 + assert data == b'host pipe' + assert buffered.read() == b'' +assert raw.closed +"#; + if let Err(error) = vm.run_block_expr(scope, source) { + let mut message = String::new(); + vm.write_exception(&mut message, &error).unwrap(); + panic!("{message}"); + } + }); + // The embedding host still owns the descriptor after Python closes its wrapper. + assert!(unsafe { libc::fcntl(reader.as_raw_fd(), libc::F_GETFD) } >= 0); + } + + #[test] + #[cfg(unix)] + fn fileio_preserves_nonblocking_descriptor_result() { + let (reader, _writer) = pipe(); + // SAFETY: reader owns a valid descriptor; F_SETFL takes integer flags. + assert_eq!( + unsafe { libc::fcntl(reader.as_raw_fd(), libc::F_SETFL, libc::O_NONBLOCK) }, + 0 + ); + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let scope = vm.new_scope_with_builtins(); + scope + .globals + .set_item("read_fd", vm.ctx.new_int(reader.as_raw_fd()).into(), vm) + .unwrap(); + if let Err(error) = vm.run_block_expr( + scope, + r#" +import _io +with _io.FileIO(read_fd, 'rb', closefd=False) as raw: + assert raw.read(1) is None + assert raw.readinto(bytearray(1)) is None +"#, + ) { + let mut message = String::new(); + vm.write_exception(&mut message, &error).unwrap(); + panic!("{message}"); + } + }); + } + + #[test] + fn fileio_path_open_truncate_and_filename_error() { + let unique = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let directory = rustpython_host_env::os::temp_dir().join(format!( + "rustpython-host-io-{}-{unique}", + rustpython_host_env::os::process_id() + )); + rustpython_host_env::fs::create_dir_all(&directory).unwrap(); + struct Cleanup(std::path::PathBuf); + impl Drop for Cleanup { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + let _cleanup = Cleanup(directory.clone()); + let filename = directory.join("data.bin"); + let missing = directory.join("missing.bin"); + Interpreter::without_stdlib(Default::default()).enter(|vm| { + let scope = vm.new_scope_with_builtins(); + scope + .globals + .set_item( + "filename", + vm.ctx.new_str(filename.to_str().unwrap()).into(), + vm, + ) + .unwrap(); + scope + .globals + .set_item( + "missing", + vm.ctx.new_str(missing.to_str().unwrap()).into(), + vm, + ) + .unwrap(); + if let Err(error) = vm.run_block_expr( + scope, + r#" +import _io +with _io.FileIO(filename, 'w+b') as file: + assert file.write(b'abcdef') == 6 + assert file.tell() == 6 + assert file.truncate(3) == 3 + assert file.seek(0) == 0 + assert file.read() == b'abc' +try: + _io.FileIO(missing, 'rb') +except FileNotFoundError as error: + assert error.filename == missing +else: + raise AssertionError('missing file unexpectedly opened') +"#, + ) { + let mut message = String::new(); + vm.write_exception(&mut message, &error).unwrap(); + panic!("{message}"); + } + }); + assert_eq!(rustpython_host_env::fs::read(filename).unwrap(), b"abc"); + } +} diff --git a/crates/vm/tests/signal_wakeup.rs b/crates/vm/tests/signal_wakeup.rs new file mode 100644 index 00000000000..a1e912bb8ab --- /dev/null +++ b/crates/vm/tests/signal_wakeup.rs @@ -0,0 +1,96 @@ +#![cfg(test)] +#![cfg(feature = "threading")] + +extern crate alloc; + +// Keep this process-global signal-breaker regression in its own test binary: +// VM unit tests can clear or consume the breaker concurrently. +use rustpython_vm::Interpreter; + +#[test] +fn unrelated_thread_states_preserve_user_signal_wakeup() { + use alloc::sync::Arc; + use core::sync::atomic::{AtomicBool, Ordering}; + + let (sender, receiver) = rustpython_vm::signal::user_signal_channel(); + let interp = Interpreter::with_init(Default::default(), |vm| { + vm.set_user_signal_channel(receiver); + }); + let worker = interp.enter(|vm| vm.new_thread()); + let helper = interp.enter(|vm| vm.new_thread()); + let called = Arc::new(AtomicBool::new(false)); + let callback_called = called.clone(); + sender + .send(Box::new(move |_| { + callback_called.store(true, Ordering::Release); + Ok(()) + })) + .unwrap(); + std::thread::spawn(move || { + worker.run(|vm| rustpython_vm::signal::check_signals(vm).unwrap()); + }) + .join() + .unwrap(); + // Like exec_interpreter(main=False), this helper runs on the native main + // thread and may dispatch OS signals, but owns no user-signal receiver. + helper.run(|vm| rustpython_vm::signal::check_signals(vm).unwrap()); + assert!(!called.load(Ordering::Acquire)); + interp.enter(|vm| rustpython_vm::signal::check_signals(vm).unwrap()); + assert!(called.load(Ordering::Acquire)); + + // A different receiver must not consume this channel's wakeup either. + let (other_sender, other_receiver) = rustpython_vm::signal::user_signal_channel(); + let other = Interpreter::with_init(Default::default(), |vm| { + vm.set_user_signal_channel(other_receiver); + }); + called.store(false, Ordering::Release); + let callback_called = called.clone(); + sender + .send(Box::new(move |_| { + callback_called.store(true, Ordering::Release); + Ok(()) + })) + .unwrap(); + other.enter(|vm| rustpython_vm::signal::check_signals(vm).unwrap()); + assert!(!called.load(Ordering::Acquire)); + interp.enter(|vm| rustpython_vm::signal::check_signals(vm).unwrap()); + assert!(called.load(Ordering::Acquire)); + drop(other); + assert!(other_sender.send(Box::new(|_| Ok(()))).is_err()); + + // A failing callback must leave the rest of its queue pending. + called.store(false, Ordering::Release); + sender + .send(Box::new(|vm| Err(vm.new_runtime_error("callback failed")))) + .unwrap(); + let callback_called = called.clone(); + sender + .send(Box::new(move |_| { + callback_called.store(true, Ordering::Release); + Ok(()) + })) + .unwrap(); + assert!(interp.enter(rustpython_vm::signal::check_signals).is_err()); + assert!(!called.load(Ordering::Acquire)); + interp.enter(|vm| rustpython_vm::signal::check_signals(vm).unwrap()); + assert!(called.load(Ordering::Acquire)); + + // The bytecode fast path must see the channel-local hint without an OS + // signal. Direct check_signals calls alone would not exercise that path. + #[cfg(feature = "compiler")] + { + called.store(false, Ordering::Release); + let callback_called = called.clone(); + sender + .send(Box::new(move |_| { + callback_called.store(true, Ordering::Release); + Ok(()) + })) + .unwrap(); + interp.enter(|vm| { + vm.run_string(vm.new_scope_with_builtins(), "pass", "") + .unwrap(); + }); + assert!(called.load(Ordering::Acquire)); + } +} diff --git a/crates/wasi_host/Cargo.toml b/crates/wasi_host/Cargo.toml new file mode 100644 index 00000000000..04ae11e4ef7 --- /dev/null +++ b/crates/wasi_host/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "rustpython-wasi-host" +description = "Capability-scoped WASI preview1 host operations for RustPython" +version.workspace = true +authors.workspace = true +edition.workspace = true +rust-version.workspace = true +repository.workspace = true +license.workspace = true + +[dependencies] +cap-std = "4.0.3" diff --git a/crates/wasi_host/src/guest_memory.rs b/crates/wasi_host/src/guest_memory.rs new file mode 100644 index 00000000000..2f170f7e7a2 --- /dev/null +++ b/crates/wasi_host/src/guest_memory.rs @@ -0,0 +1,259 @@ +// cspell:ignore iovecs iovs nwritten fdflags fdstat +use super::*; + +/// A guest's linear memory. Implementations must report bounds failures as `FAULT`. +/// Memory must not shrink during a call. The adapter validates every buffer before I/O. +pub trait GuestMemory { + /// Validate that the guest has supplied a memory before interpreting pointers. + fn validate(&self) -> Result<(), u16> { + Ok(()) + } + fn size(&self) -> u64; + fn read(&self, offset: u32, bytes: &mut [u8]) -> Result<(), u16>; + fn write(&self, offset: u32, bytes: &[u8]) -> Result<(), u16>; +} + +fn abi(errno: Result<(), u16>) -> i32 { + i32::from(errno.err().unwrap_or(SUCCESS)) +} + +fn guest_u32(ptr: i32) -> Result { + u32::try_from(ptr).map_err(|_| FAULT) +} + +pub(crate) fn check_range(size: u64, ptr: u32, len: u32) -> Result<(), u16> { + match u64::from(ptr).checked_add(u64::from(len)) { + Some(end) if end <= size => Ok(()), + _ => Err(FAULT), + } +} + +fn mem_read(view: &impl GuestMemory, ptr: u32, buf: &mut [u8]) -> Result<(), u16> { + check_range(view.size(), ptr, buf.len() as u32)?; + view.read(ptr, buf) +} + +fn mem_write(view: &impl GuestMemory, ptr: u32, buf: &[u8]) -> Result<(), u16> { + check_range(view.size(), ptr, buf.len() as u32)?; + view.write(ptr, buf) +} + +fn mem_read_u32(view: &impl GuestMemory, ptr: u32) -> Result { + let mut bytes = [0u8; 4]; + mem_read(view, ptr, &mut bytes)?; + Ok(u32::from_le_bytes(bytes)) +} + +fn mem_write_u32(view: &impl GuestMemory, ptr: u32, value: u32) -> Result<(), u16> { + mem_write(view, ptr, &value.to_le_bytes()) +} + +fn mem_write_u64(view: &impl GuestMemory, ptr: u32, value: u64) -> Result<(), u16> { + mem_write(view, ptr, &value.to_le_bytes()) +} + +fn read_iovecs(view: &impl GuestMemory, iovs: i32, iovs_len: i32) -> Result, u16> { + let n = u32::try_from(iovs_len).map_err(|_| INVAL)?; + let iovs = guest_u32(iovs)?; + let bytes = n.checked_mul(8).ok_or(INVAL)?; + check_range(view.size(), iovs, bytes)?; + let mut out = Vec::new(); + for i in 0..n { + let base = iovs + i * 8; + let buf = mem_read_u32(view, base)?; + let len = mem_read_u32(view, base + 4)?; + if len != 0 { + check_range(view.size(), buf, len)?; + } + out.push((buf, len)); + } + Ok(out) +} + +pub fn fd_read( + table: &mut Table, + view: &impl GuestMemory, + fd: i32, + iovs: i32, + iovs_len: i32, + nread: i32, +) -> i32 { + abi((|| { + view.validate()?; + let nread = guest_u32(nread)?; + check_range(view.size(), nread, 4)?; + let iovecs = read_iovecs(view, iovs, iovs_len)?; + let mut storage: Vec> = iovecs + .iter() + .map(|&(_, len)| vec![0u8; len as usize]) + .collect(); + let mut slices: Vec<&mut [u8]> = storage.iter_mut().map(|buf| buf.as_mut_slice()).collect(); + let n = table.fd_read(fd, &mut slices)?; + if n > MAX_TRANSFER { + return Err(IO); + } + let mut remaining = n; + for ((ptr, len), buf) in iovecs.iter().zip(storage.iter()) { + if remaining == 0 { + break; + } + let take = remaining.min(*len as usize); + mem_write(view, *ptr, &buf[..take])?; + remaining -= take; + } + let written = u32::try_from(n).map_err(|_| OVERFLOW)?; + mem_write_u32(view, nread, written) + })()) +} + +pub fn fd_write( + table: &mut Table, + view: &impl GuestMemory, + fd: i32, + iovs: i32, + iovs_len: i32, + nwritten: i32, +) -> i32 { + abi((|| { + view.validate()?; + let nwritten = guest_u32(nwritten)?; + check_range(view.size(), nwritten, 4)?; + let iovecs = read_iovecs(view, iovs, iovs_len)?; + let mut storage = Vec::new(); + for (ptr, len) in &iovecs { + let mut buf = vec![0u8; *len as usize]; + if *len != 0 { + mem_read(view, *ptr, &mut buf)?; + } + storage.push(buf); + } + let slices: Vec<&[u8]> = storage.iter().map(|buf| buf.as_slice()).collect(); + let n = table.fd_write(fd, &slices)?; + if n > MAX_TRANSFER { + return Err(IO); + } + let written = u32::try_from(n).map_err(|_| OVERFLOW)?; + mem_write_u32(view, nwritten, written) + })()) +} + +pub fn fd_seek( + table: &mut Table, + view: &impl GuestMemory, + fd: i32, + offset: i64, + whence: i32, + newoffset: i32, +) -> i32 { + abi((|| { + view.validate()?; + let newoffset = guest_u32(newoffset)?; + check_range(view.size(), newoffset, 8)?; + let pos = table.fd_seek(fd, offset, whence)?; + mem_write_u64(view, newoffset, pos) + })()) +} + +pub fn fd_close(table: &mut Table, fd: i32) -> i32 { + abi(table.close(fd)) +} + +pub fn fd_sync(table: &mut Table, fd: i32) -> i32 { + abi(table.fd_sync(fd)) +} + +pub fn fd_filestat_set_size(table: &mut Table, fd: i32, size: i64) -> i32 { + abi(table.fd_filestat_set_size(fd, size)) +} + +pub fn fd_fdstat_get(table: &mut Table, view: &impl GuestMemory, fd: i32, buf: i32) -> i32 { + abi((|| { + view.validate()?; + let buf = guest_u32(buf)?; + check_range(view.size(), buf, 24)?; + let (filetype, fdflags, rights_base, rights_inheriting) = table.fdstat(fd)?; + let mut bytes = [0u8; 24]; + bytes[0] = filetype; + bytes[2..4].copy_from_slice(&fdflags.to_le_bytes()); + bytes[8..16].copy_from_slice(&rights_base.to_le_bytes()); + bytes[16..24].copy_from_slice(&rights_inheriting.to_le_bytes()); + mem_write(view, buf, &bytes) + })()) +} + +pub fn fd_prestat_get(table: &mut Table, view: &impl GuestMemory, fd: i32, buf: i32) -> i32 { + abi((|| { + view.validate()?; + let buf = guest_u32(buf)?; + check_range(view.size(), buf, 8)?; + let name = table.prestat(fd)?; + let name_len = u32::try_from(name.len()).map_err(|_| NAMETOOLONG)?; + let mut bytes = [0u8; 8]; + bytes[4..8].copy_from_slice(&name_len.to_le_bytes()); + mem_write(view, buf, &bytes) + })()) +} + +pub fn fd_prestat_dir_name( + table: &mut Table, + view: &impl GuestMemory, + fd: i32, + path: i32, + path_len: i32, +) -> i32 { + abi((|| { + let path_len = u32::try_from(path_len).map_err(|_| INVAL)?; + view.validate()?; + let path = guest_u32(path)?; + check_range(view.size(), path, path_len)?; + let name = table.prestat(fd)?; + if name.len() > path_len as usize { + return Err(NAMETOOLONG); + } + mem_write(view, path, name) + })()) +} + +#[allow(clippy::too_many_arguments)] +pub fn path_open( + table: &mut Table, + view: &impl GuestMemory, + dirfd: i32, + dirflags: i32, + path: i32, + path_len: i32, + oflags: i32, + fs_rights_base: i64, + fs_rights_inheriting: i64, + fdflags: i32, + fd: i32, +) -> i32 { + abi((|| { + let path_len = match u32::try_from(path_len) { + Ok(n) if n > MAX_PATH => return Err(NAMETOOLONG), + Ok(n) => n, + Err(_) => return Err(INVAL), + }; + let oflags = oflags as u16; + let fdflags = fdflags as u16; + view.validate()?; + let path_ptr = guest_u32(path)?; + let fd_ptr = guest_u32(fd)?; + check_range(view.size(), path_ptr, path_len)?; + check_range(view.size(), fd_ptr, 4)?; + let mut bytes = vec![0u8; path_len as usize]; + if path_len != 0 { + mem_read(view, path_ptr, &mut bytes)?; + } + let opened = table.path_open( + dirfd, + dirflags, + &bytes, + oflags, + fs_rights_base as u64, + fs_rights_inheriting as u64, + fdflags, + )?; + mem_write_u32(view, fd_ptr, opened as u32) + })()) +} diff --git a/crates/wasi_host/src/lib.rs b/crates/wasi_host/src/lib.rs new file mode 100644 index 00000000000..0df70565153 --- /dev/null +++ b/crates/wasi_host/src/lib.rs @@ -0,0 +1,1039 @@ +// cspell:ignore ACCES BADF DEADLK ILSEQ MFILE NOSPC SPIPE TXTBSY FDFLAGS fdflags fdstat iovecs iovs nwritten badf +//! WASI preview1 subset used by the no-JS `host-io` guest. +//! +//! Import module: `wasi_snapshot_preview1`. Access is decided by preopens and +//! per-descriptor rights. Guest integers index this table; they are never +//! native descriptors. `path_open` paths must be valid UTF-8, as WASI +//! preview1 requires. + +use cap_std::{ + ambient_authority, + fs::{Dir, File, OpenOptions}, +}; +use std::{ + io::{self, Read, Seek, SeekFrom, Write}, + path::{Component, Path, PathBuf}, +}; + +pub const MODULE: &str = "wasi_snapshot_preview1"; +pub const FUNCTIONS: &[&str] = &[ + "fd_read", + "fd_write", + "fd_seek", + "fd_close", + "fd_sync", + "fd_filestat_set_size", + "fd_fdstat_get", + "fd_prestat_get", + "fd_prestat_dir_name", + "path_open", +]; + +pub const SUCCESS: u16 = 0; +pub const TOOBIG: u16 = 1; +pub const ACCES: u16 = 2; +pub const ADDRINUSE: u16 = 3; +pub const ADDRNOTAVAIL: u16 = 4; +pub const AGAIN: u16 = 6; +pub const BADF: u16 = 8; +pub const BUSY: u16 = 10; +pub const CONNABORTED: u16 = 13; +pub const CONNREFUSED: u16 = 14; +pub const CONNRESET: u16 = 15; +pub const DEADLK: u16 = 16; +pub const DQUOT: u16 = 19; +pub const EXIST: u16 = 20; +pub const FAULT: u16 = 21; +pub const FBIG: u16 = 22; +pub const ILSEQ: u16 = 25; +pub const INTR: u16 = 27; +pub const INVAL: u16 = 28; +pub const IO: u16 = 29; +pub const ISDIR: u16 = 31; +pub const MFILE: u16 = 33; +pub const MLINK: u16 = 34; +pub const NAMETOOLONG: u16 = 37; +pub const NOENT: u16 = 44; +pub const NOMEM: u16 = 48; +pub const NOSPC: u16 = 51; +pub const NOTSUP: u16 = 58; +pub const NOTDIR: u16 = 54; +pub const NOTEMPTY: u16 = 55; +pub const NOTCONN: u16 = 53; +pub const OVERFLOW: u16 = 61; +pub const PERM: u16 = 63; +pub const PIPE: u16 = 64; +pub const ROFS: u16 = 69; +pub const SPIPE: u16 = 70; +pub const STALE: u16 = 72; +pub const TIMEDOUT: u16 = 73; +pub const TXTBSY: u16 = 74; +pub const XDEV: u16 = 75; +pub const NOTCAPABLE: u16 = 76; + +const FILETYPE_UNKNOWN: u8 = 0; +const FILETYPE_DIRECTORY: u8 = 3; +const FILETYPE_REGULAR_FILE: u8 = 4; + +#[cfg(test)] +const LOOKUP_SYMLINK_FOLLOW: i32 = 1; + +const OFLAGS_CREAT: u16 = 1; +const OFLAGS_DIRECTORY: u16 = 2; +const OFLAGS_EXCL: u16 = 4; +const OFLAGS_TRUNC: u16 = 8; + +const FDFLAGS_APPEND: u16 = 1; + +const RIGHTS_FD_DATASYNC: u64 = 1 << 0; +const RIGHTS_FD_READ: u64 = 1 << 1; +const RIGHTS_FD_SEEK: u64 = 1 << 2; +const RIGHTS_FD_SYNC: u64 = 1 << 4; +const RIGHTS_FD_TELL: u64 = 1 << 5; +const RIGHTS_FD_WRITE: u64 = 1 << 6; +const RIGHTS_FD_ALLOCATE: u64 = 1 << 8; +const RIGHTS_PATH_CREATE_DIRECTORY: u64 = 1 << 9; +const RIGHTS_PATH_CREATE_FILE: u64 = 1 << 10; +const RIGHTS_PATH_LINK_SOURCE: u64 = 1 << 11; +const RIGHTS_PATH_LINK_TARGET: u64 = 1 << 12; +const RIGHTS_PATH_OPEN: u64 = 1 << 13; +const RIGHTS_PATH_RENAME_SOURCE: u64 = 1 << 16; +const RIGHTS_PATH_RENAME_TARGET: u64 = 1 << 17; +const RIGHTS_PATH_FILESTAT_SET_SIZE: u64 = 1 << 19; +const RIGHTS_PATH_FILESTAT_SET_TIMES: u64 = 1 << 20; +#[cfg(test)] +const RIGHTS_FD_FILESTAT_GET: u64 = 1 << 21; +const RIGHTS_FD_FILESTAT_SET_SIZE: u64 = 1 << 22; +const RIGHTS_FD_FILESTAT_SET_TIMES: u64 = 1 << 23; +const RIGHTS_PATH_SYMLINK: u64 = 1 << 24; +const RIGHTS_PATH_REMOVE_DIRECTORY: u64 = 1 << 25; +const RIGHTS_PATH_UNLINK_FILE: u64 = 1 << 26; + +const RIGHTS_ALL: u64 = (1 << 30) - 1; + +const RIGHTS_WRITE_RELATED: u64 = RIGHTS_FD_WRITE + | RIGHTS_FD_ALLOCATE + | RIGHTS_FD_FILESTAT_SET_SIZE + | RIGHTS_FD_FILESTAT_SET_TIMES + | RIGHTS_PATH_CREATE_DIRECTORY + | RIGHTS_PATH_CREATE_FILE + | RIGHTS_PATH_LINK_SOURCE + | RIGHTS_PATH_LINK_TARGET + | RIGHTS_PATH_RENAME_SOURCE + | RIGHTS_PATH_RENAME_TARGET + | RIGHTS_PATH_FILESTAT_SET_SIZE + | RIGHTS_PATH_FILESTAT_SET_TIMES + | RIGHTS_PATH_SYMLINK + | RIGHTS_PATH_REMOVE_DIRECTORY + | RIGHTS_PATH_UNLINK_FILE; + +/// Rights that must be granted when requested; extra bits are masked off. +const RIGHTS_CRITICAL: u64 = RIGHTS_FD_READ + | RIGHTS_FD_WRITE + | RIGHTS_FD_SEEK + | RIGHTS_FD_TELL + | RIGHTS_FD_SYNC + | RIGHTS_FD_DATASYNC + | RIGHTS_FD_ALLOCATE + | RIGHTS_FD_FILESTAT_SET_SIZE + | RIGHTS_PATH_OPEN + | RIGHTS_PATH_CREATE_FILE + | RIGHTS_PATH_CREATE_DIRECTORY + | RIGHTS_PATH_FILESTAT_SET_SIZE; + +const MAX_TRANSFER: usize = 64 * 1024; +const MAX_PATH: u32 = 65536; + +const WHENCE_SET: i32 = 0; +const WHENCE_CUR: i32 = 1; +const WHENCE_END: i32 = 2; + +pub struct Preopen { + pub host: PathBuf, + pub guest: Vec, + pub write: bool, +} + +enum Resource { + File(File), + Dir { + dir: Dir, + preopen_name: Option>, + }, +} + +struct Entry { + resource: Resource, + rights_base: u64, + rights_inheriting: u64, + fdflags: u16, + filetype: u8, +} + +impl Entry { + fn has(&self, right: u64) -> bool { + self.rights_base & right != 0 + } + + fn require(&self, right: u64) -> Result<(), u16> { + if self.has(right) { + Ok(()) + } else { + Err(NOTCAPABLE) + } + } + + fn is_dir(&self) -> bool { + self.filetype == FILETYPE_DIRECTORY + } + + fn is_readonly_dir(&self) -> bool { + self.is_dir() && self.rights_inheriting & RIGHTS_FD_WRITE == 0 + } +} + +pub struct Table { + entries: Vec>, +} + +impl Default for Table { + fn default() -> Self { + Self { + entries: vec![None, None, None], + } + } +} + +impl Table { + pub fn with_preopens(preopens: impl IntoIterator) -> io::Result { + let mut table = Self::default(); + for preopen in preopens { + let dir = Dir::open_ambient_dir(&preopen.host, ambient_authority())?; + let rights = if preopen.write { + RIGHTS_ALL + } else { + RIGHTS_ALL & !RIGHTS_WRITE_RELATED + }; + table + .push(Entry { + resource: Resource::Dir { + dir, + preopen_name: Some(preopen.guest), + }, + rights_base: rights, + rights_inheriting: rights, + fdflags: 0, + filetype: FILETYPE_DIRECTORY, + }) + .map_err(|_| io::Error::other("descriptor table full"))?; + } + Ok(table) + } + + fn push(&mut self, entry: Entry) -> Result { + let index = self + .entries + .iter() + .enumerate() + .skip(3) + .find_map(|(index, slot)| slot.is_none().then_some(index)) + .unwrap_or(self.entries.len().max(3)); + let fd = i32::try_from(index).map_err(|_| MFILE)?; + if index >= self.entries.len() { + self.entries.resize_with(index + 1, || None); + } + self.entries[index] = Some(entry); + Ok(fd) + } + + fn get(&self, fd: i32) -> Result<&Entry, u16> { + usize::try_from(fd) + .ok() + .and_then(|fd| self.entries.get(fd)) + .and_then(Option::as_ref) + .ok_or(BADF) + } + + fn get_mut(&mut self, fd: i32) -> Result<&mut Entry, u16> { + usize::try_from(fd) + .ok() + .and_then(|fd| self.entries.get_mut(fd)) + .and_then(Option::as_mut) + .ok_or(BADF) + } + + pub fn close(&mut self, fd: i32) -> Result<(), u16> { + let Some(entry) = usize::try_from(fd) + .ok() + .and_then(|fd| self.entries.get_mut(fd)) + .and_then(Option::take) + else { + return Err(BADF); + }; + drop(entry); + Ok(()) + } + + #[allow(clippy::too_many_arguments)] + pub fn path_open( + &mut self, + dirfd: i32, + _dirflags: i32, + path: &[u8], + oflags: u16, + fs_rights_base: u64, + fs_rights_inheriting: u64, + fdflags: u16, + ) -> Result { + if path.len() > MAX_PATH as usize { + return Err(NAMETOOLONG); + } + let path = guest_path(path)?; + let (dir, dir_rights_base, dir_rights_inheriting, readonly) = { + let dir_entry = self.get(dirfd)?; + match &dir_entry.resource { + Resource::Dir { dir, .. } => { + dir_entry.require(RIGHTS_PATH_OPEN)?; + ( + dir.try_clone().map_err(wasi_from_io)?, + dir_entry.rights_base, + dir_entry.rights_inheriting, + dir_entry.is_readonly_dir(), + ) + } + Resource::File(_) => return Err(NOTDIR), + } + }; + + if readonly + && (oflags & (OFLAGS_CREAT | OFLAGS_TRUNC | OFLAGS_EXCL) != 0 + || fdflags & FDFLAGS_APPEND != 0) + { + return Err(NOTCAPABLE); + } + + let mut needed_dir = RIGHTS_PATH_OPEN; + if oflags & OFLAGS_CREAT != 0 { + needed_dir |= RIGHTS_PATH_CREATE_FILE; + } + if oflags & OFLAGS_TRUNC != 0 { + needed_dir |= RIGHTS_PATH_FILESTAT_SET_SIZE; + } + if dir_rights_base & needed_dir != needed_dir { + return Err(NOTCAPABLE); + } + if fs_rights_base & RIGHTS_CRITICAL & !dir_rights_inheriting != 0 { + return Err(NOTCAPABLE); + } + + let granted_base = fs_rights_base & dir_rights_inheriting; + let granted_inheriting = fs_rights_inheriting & dir_rights_inheriting; + + if oflags & OFLAGS_DIRECTORY != 0 { + let opened = dir.open_dir(path).map_err(wasi_from_io)?; + return self.push(Entry { + resource: Resource::Dir { + dir: opened, + preopen_name: None, + }, + rights_base: granted_base, + rights_inheriting: granted_inheriting, + fdflags: fdflags & FDFLAGS_APPEND, + filetype: FILETYPE_DIRECTORY, + }); + } + + let want_read = granted_base & RIGHTS_FD_READ != 0; + let want_write = granted_base & RIGHTS_FD_WRITE != 0; + if !want_read && !want_write { + return Err(INVAL); + } + + let mut opts = OpenOptions::new(); + opts.read(want_read); + if want_write { + opts.write(true); + if fdflags & FDFLAGS_APPEND != 0 { + opts.append(true); + } + if oflags & OFLAGS_TRUNC != 0 { + opts.truncate(true); + } + if oflags & OFLAGS_CREAT != 0 && oflags & OFLAGS_EXCL != 0 { + opts.create_new(true); + } else if oflags & OFLAGS_CREAT != 0 { + opts.create(true); + } + } else { + // Read-only at the OS as well as in the rights mask. + opts.write(false); + } + + let file = dir.open_with(path, &opts).map_err(wasi_from_io)?; + let metadata = file.metadata().map_err(wasi_from_io)?; + if metadata.is_dir() { + let dir = Dir::from_std_file(file.into_std()); + return self.push(Entry { + resource: Resource::Dir { + dir, + preopen_name: None, + }, + rights_base: granted_base, + rights_inheriting: granted_inheriting, + fdflags: fdflags & FDFLAGS_APPEND, + filetype: FILETYPE_DIRECTORY, + }); + } + let filetype = if metadata.is_file() { + FILETYPE_REGULAR_FILE + } else { + FILETYPE_UNKNOWN + }; + self.push(Entry { + resource: Resource::File(file), + rights_base: granted_base, + rights_inheriting: granted_inheriting, + fdflags: fdflags & FDFLAGS_APPEND, + filetype, + }) + } + + pub fn fd_read(&mut self, fd: i32, bufs: &mut [&mut [u8]]) -> Result { + let entry = self.get_mut(fd)?; + entry.require(RIGHTS_FD_READ)?; + if entry.is_dir() { + return Err(ISDIR); + } + let Resource::File(file) = &mut entry.resource else { + return Err(ISDIR); + }; + transfer_read(file, bufs) + } + + pub fn fd_write(&mut self, fd: i32, bufs: &[&[u8]]) -> Result { + let entry = self.get_mut(fd)?; + entry.require(RIGHTS_FD_WRITE)?; + if entry.is_dir() { + return Err(ISDIR); + } + let Resource::File(file) = &mut entry.resource else { + return Err(ISDIR); + }; + transfer_write(file, bufs) + } + + pub fn fd_seek(&mut self, fd: i32, offset: i64, whence: i32) -> Result { + if !matches!(whence, WHENCE_SET | WHENCE_CUR | WHENCE_END) { + return Err(INVAL); + } + let entry = self.get_mut(fd)?; + if whence == WHENCE_CUR && offset == 0 { + if !entry.has(RIGHTS_FD_TELL) && !entry.has(RIGHTS_FD_SEEK) { + return Err(NOTCAPABLE); + } + } else { + entry.require(RIGHTS_FD_SEEK)?; + } + if entry.is_dir() { + return Err(ISDIR); + } + let Resource::File(file) = &mut entry.resource else { + return Err(ISDIR); + }; + let pos = match whence { + WHENCE_SET => { + let offset = u64::try_from(offset).map_err(|_| INVAL)?; + SeekFrom::Start(offset) + } + WHENCE_CUR => SeekFrom::Current(offset), + WHENCE_END => SeekFrom::End(offset), + _ => return Err(INVAL), + }; + file.seek(pos).map_err(wasi_from_io) + } + + pub fn fd_sync(&mut self, fd: i32) -> Result<(), u16> { + let entry = self.get_mut(fd)?; + entry.require(RIGHTS_FD_SYNC)?; + match &mut entry.resource { + Resource::File(file) => file.sync_all().map_err(wasi_from_io), + Resource::Dir { dir, .. } => dir + .try_clone() + .and_then(|clone| clone.into_std_file().sync_all()) + .map_err(wasi_from_io), + } + } + + pub fn fd_filestat_set_size(&mut self, fd: i32, size: i64) -> Result<(), u16> { + let size = u64::try_from(size).map_err(|_| INVAL)?; + let entry = self.get_mut(fd)?; + entry.require(RIGHTS_FD_FILESTAT_SET_SIZE)?; + if entry.is_dir() { + return Err(ISDIR); + } + let Resource::File(file) = &mut entry.resource else { + return Err(ISDIR); + }; + file.set_len(size).map_err(wasi_from_io) + } + + pub fn fdstat(&self, fd: i32) -> Result<(u8, u16, u64, u64), u16> { + let entry = self.get(fd)?; + Ok(( + entry.filetype, + entry.fdflags, + entry.rights_base, + entry.rights_inheriting, + )) + } + + pub fn prestat(&self, fd: i32) -> Result<&[u8], u16> { + let entry = self.get(fd)?; + match &entry.resource { + Resource::Dir { + preopen_name: Some(name), + .. + } => Ok(name.as_slice()), + _ => Err(BADF), + } + } +} + +fn transfer_read(file: &mut File, bufs: &mut [&mut [u8]]) -> Result { + let mut total = 0usize; + let mut remaining = MAX_TRANSFER; + for buf in bufs { + if remaining == 0 { + break; + } + let n = buf.len().min(remaining); + if n == 0 { + continue; + } + match file.read(&mut buf[..n]) { + Ok(0) => break, + Ok(k) => { + total += k; + remaining -= k; + if k < n { + break; + } + } + Err(err) if total > 0 => { + if err.kind() == io::ErrorKind::Interrupted { + break; + } + return Err(wasi_from_io(err)); + } + Err(err) => return Err(wasi_from_io(err)), + } + } + Ok(total) +} + +fn transfer_write(file: &mut File, bufs: &[&[u8]]) -> Result { + let mut total = 0usize; + let mut remaining = MAX_TRANSFER; + for buf in bufs { + if remaining == 0 { + break; + } + let n = buf.len().min(remaining); + if n == 0 { + continue; + } + match file.write(&buf[..n]) { + Ok(0) => break, + Ok(k) => { + total += k; + remaining -= k; + if k < n { + break; + } + } + Err(err) if total > 0 => { + if err.kind() == io::ErrorKind::Interrupted { + break; + } + return Err(wasi_from_io(err)); + } + Err(err) => return Err(wasi_from_io(err)), + } + } + Ok(total) +} + +fn guest_path(bytes: &[u8]) -> Result<&Path, u16> { + if bytes.is_empty() { + return Ok(Path::new(".")); + } + if bytes.contains(&0) { + return Err(INVAL); + } + let text = std::str::from_utf8(bytes).map_err(|_| INVAL)?; + let path = Path::new(text); + if path.is_absolute() + || path + .components() + .any(|part| matches!(part, Component::Prefix(_) | Component::RootDir)) + { + return Err(NOTCAPABLE); + } + Ok(path) +} + +fn wasi_from_io(err: io::Error) -> u16 { + match err.kind() { + io::ErrorKind::NotFound => NOENT, + io::ErrorKind::PermissionDenied => match err.raw_os_error() { + Some(13) => ACCES, + Some(1) => PERM, + _ => NOTCAPABLE, + }, + io::ErrorKind::AlreadyExists => EXIST, + io::ErrorKind::WouldBlock => AGAIN, + io::ErrorKind::Interrupted => INTR, + io::ErrorKind::InvalidInput => INVAL, + io::ErrorKind::InvalidData => ILSEQ, + io::ErrorKind::UnexpectedEof => IO, + io::ErrorKind::OutOfMemory => NOMEM, + io::ErrorKind::Unsupported => NOTSUP, + io::ErrorKind::TimedOut => TIMEDOUT, + io::ErrorKind::BrokenPipe => PIPE, + io::ErrorKind::AddrInUse => ADDRINUSE, + io::ErrorKind::AddrNotAvailable => ADDRNOTAVAIL, + io::ErrorKind::ConnectionAborted => CONNABORTED, + io::ErrorKind::ConnectionRefused => CONNREFUSED, + io::ErrorKind::ConnectionReset => CONNRESET, + io::ErrorKind::NotConnected => NOTCONN, + io::ErrorKind::IsADirectory => ISDIR, + io::ErrorKind::NotADirectory => NOTDIR, + io::ErrorKind::DirectoryNotEmpty => NOTEMPTY, + io::ErrorKind::ReadOnlyFilesystem => ROFS, + io::ErrorKind::StorageFull => NOSPC, + io::ErrorKind::NotSeekable => SPIPE, + io::ErrorKind::FileTooLarge => FBIG, + io::ErrorKind::TooManyLinks => MLINK, + io::ErrorKind::QuotaExceeded => DQUOT, + io::ErrorKind::Deadlock => DEADLK, + io::ErrorKind::ArgumentListTooLong => TOOBIG, + io::ErrorKind::CrossesDevices => XDEV, + io::ErrorKind::ExecutableFileBusy => TXTBSY, + io::ErrorKind::StaleNetworkFileHandle => STALE, + io::ErrorKind::ResourceBusy => BUSY, + _ => IO, + } +} + +pub mod guest_memory; + +#[cfg(test)] +mod tests { + use super::*; + use crate::guest_memory::check_range; + use crate::guest_memory::*; + use std::{ + path::PathBuf, + sync::atomic::{AtomicUsize, Ordering}, + }; + + struct Fixture(PathBuf); + impl Fixture { + fn new() -> Self { + static NEXT: AtomicUsize = AtomicUsize::new(0); + loop { + let path = std::env::temp_dir().join(format!( + "rustpython-wasi-fs-{}-{}", + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + )); + match std::fs::create_dir(&path) { + Ok(()) => return Self(path), + Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) => panic!("{e}"), + } + } + } + } + impl Drop for Fixture { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn rights_read() -> u64 { + RIGHTS_FD_READ + | RIGHTS_FD_SEEK + | RIGHTS_FD_TELL + | RIGHTS_FD_SYNC + | RIGHTS_FD_FILESTAT_GET + | RIGHTS_FD_FILESTAT_SET_TIMES + } + + fn rights_write() -> u64 { + rights_read() | RIGHTS_FD_WRITE | RIGHTS_FD_ALLOCATE | RIGHTS_FD_FILESTAT_SET_SIZE + } + + #[test] + fn read_only_preopen_denies_write_flags_without_touching_the_file() { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("inside"), b"unchanged").unwrap(); + let mut table = Table::with_preopens([Preopen { + host: fixture.0.clone(), + guest: b"/".to_vec(), + write: false, + }]) + .unwrap(); + for oflags in [ + OFLAGS_CREAT, + OFLAGS_TRUNC, + OFLAGS_EXCL, + OFLAGS_CREAT | OFLAGS_TRUNC, + ] { + assert_eq!( + table + .path_open( + 3, + LOOKUP_SYMLINK_FOLLOW, + b"inside", + oflags, + rights_write(), + 0, + 0 + ) + .unwrap_err(), + NOTCAPABLE + ); + } + assert_eq!( + table + .path_open( + 3, + LOOKUP_SYMLINK_FOLLOW, + b"inside", + 0, + rights_write(), + 0, + FDFLAGS_APPEND, + ) + .unwrap_err(), + NOTCAPABLE + ); + assert_eq!( + table + .path_open(3, LOOKUP_SYMLINK_FOLLOW, b"inside", 0, rights_write(), 0, 0) + .unwrap_err(), + NOTCAPABLE + ); + let fd = table + .path_open(3, LOOKUP_SYMLINK_FOLLOW, b"inside", 0, rights_read(), 0, 0) + .unwrap(); + assert_eq!(table.fd_write(fd, &[b"x"]).unwrap_err(), NOTCAPABLE); + assert_eq!(table.fd_filestat_set_size(fd, 0).unwrap_err(), NOTCAPABLE); + assert_eq!( + std::fs::read(fixture.0.join("inside")).unwrap(), + b"unchanged" + ); + } + + #[test] + fn escape_and_absolute_paths_are_notcapable() { + let fixture = Fixture::new(); + std::fs::create_dir(fixture.0.join("child")).unwrap(); + let mut table = Table::with_preopens([Preopen { + host: fixture.0.clone(), + guest: b"/".to_vec(), + write: true, + }]) + .unwrap(); + for path in [ + b"..".as_slice(), + b"../outside", + b"/etc/passwd", + b"child/../../outside", + ] { + assert_eq!( + table + .path_open(3, LOOKUP_SYMLINK_FOLLOW, path, 0, rights_read(), 0, 0) + .unwrap_err(), + NOTCAPABLE, + "{}", + String::from_utf8_lossy(path) + ); + } + } + + #[test] + fn close_once_then_badf() { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("f"), b"ab").unwrap(); + let mut table = Table::with_preopens([Preopen { + host: fixture.0.clone(), + guest: b"/".to_vec(), + write: true, + }]) + .unwrap(); + let fd = table + .path_open(3, LOOKUP_SYMLINK_FOLLOW, b"f", 0, rights_read(), 0, 0) + .unwrap(); + table.close(fd).unwrap(); + assert_eq!(table.close(fd), Err(BADF)); + assert_eq!(table.fd_read(fd, &mut [&mut [0; 1]]), Err(BADF)); + assert!(matches!(table.get(0), Err(BADF))); + assert!(matches!(table.get(1), Err(BADF))); + assert!(matches!(table.get(2), Err(BADF))); + assert!(matches!(table.get(-1), Err(BADF))); + } + + #[test] + fn path_open_requires_utf8() { + let fixture = Fixture::new(); + std::fs::write(fixture.0.join("café"), b"coffee").unwrap(); + let mut table = Table::with_preopens([Preopen { + host: fixture.0.clone(), + guest: b"/".to_vec(), + write: true, + }]) + .unwrap(); + assert_eq!( + table + .path_open( + 3, + LOOKUP_SYMLINK_FOLLOW, + b"raw-\xff", + 0, + rights_read(), + 0, + 0, + ) + .unwrap_err(), + INVAL + ); + let fd = table + .path_open( + 3, + LOOKUP_SYMLINK_FOLLOW, + "café".as_bytes(), + 0, + rights_read(), + 0, + 0, + ) + .unwrap(); + let mut buf = [0u8; 16]; + let n = table.fd_read(fd, &mut [&mut buf]).unwrap(); + assert_eq!(&buf[..n], b"coffee"); + } + + #[test] + #[cfg(unix)] + fn confined_symlinks() { + let fixture = Fixture::new(); + let outside = Fixture::new(); + std::fs::write(outside.0.join("secret"), b"secret").unwrap(); + std::fs::write(fixture.0.join("inside"), b"inside").unwrap(); + std::os::unix::fs::symlink("inside", fixture.0.join("internal")).unwrap(); + std::os::unix::fs::symlink(outside.0.join("secret"), fixture.0.join("escape")).unwrap(); + std::os::unix::fs::symlink(&outside.0, fixture.0.join("escape-dir")).unwrap(); + let mut table = Table::with_preopens([Preopen { + host: fixture.0.clone(), + guest: b"/".to_vec(), + write: true, + }]) + .unwrap(); + let fd = table + .path_open( + 3, + LOOKUP_SYMLINK_FOLLOW, + b"internal", + 0, + rights_read(), + 0, + 0, + ) + .unwrap(); + let mut buf = [0u8; 8]; + let n = table.fd_read(fd, &mut [&mut buf]).unwrap(); + assert_eq!(&buf[..n], b"inside"); + assert_eq!( + table + .path_open(3, LOOKUP_SYMLINK_FOLLOW, b"escape", 0, rights_read(), 0, 0) + .unwrap_err(), + NOTCAPABLE + ); + assert_eq!( + table + .path_open( + 3, + LOOKUP_SYMLINK_FOLLOW, + b"escape-dir/secret", + 0, + rights_read(), + 0, + 0, + ) + .unwrap_err(), + NOTCAPABLE + ); + } + + #[test] + fn guest_range_check() { + assert!(check_range(65536, 65536, 0).is_ok()); + assert_eq!(check_range(65536, 65536, 1).unwrap_err(), FAULT); + assert_eq!(check_range(65536, u32::MAX, u32::MAX).unwrap_err(), FAULT); + + struct MissingMemory; + impl GuestMemory for MissingMemory { + fn validate(&self) -> Result<(), u16> { + Err(IO) + } + fn size(&self) -> u64 { + unreachable!() + } + fn read(&self, _: u32, _: &mut [u8]) -> Result<(), u16> { + unreachable!() + } + fn write(&self, _: u32, _: &[u8]) -> Result<(), u16> { + unreachable!() + } + } + let mut table = Table::default(); + let memory = MissingMemory; + assert_eq!(fd_read(&mut table, &memory, -1, -1, -1, -1), i32::from(IO)); + assert_eq!( + fd_prestat_dir_name(&mut table, &memory, -1, -1, -1), + i32::from(INVAL) + ); + assert_eq!( + fd_prestat_dir_name(&mut table, &memory, -1, -1, 0), + i32::from(IO) + ); + assert_eq!( + path_open(&mut table, &memory, -1, 0, -1, -1, 0, 0, 0, 0, -1), + i32::from(INVAL) + ); + assert_eq!( + path_open( + &mut table, + &memory, + -1, + 0, + -1, + MAX_PATH as i32 + 1, + 0, + 0, + 0, + 0, + -1 + ), + i32::from(NAMETOOLONG) + ); + assert_eq!( + path_open(&mut table, &memory, -1, 0, -1, 0, 0, 0, 0, 0, -1), + i32::from(IO) + ); + } + + #[test] + fn permission_denied_without_os_code_is_notcapable() { + assert_eq!( + wasi_from_io(io::Error::new(io::ErrorKind::PermissionDenied, "escape")), + NOTCAPABLE + ); + assert_eq!( + wasi_from_io(io::Error::new(io::ErrorKind::NotFound, "missing")), + NOENT + ); + } + + #[test] + #[cfg(unix)] + fn invalid_guest_range_returns_fault_without_consuming_pipe_data() { + use std::io::Write; + use std::os::fd::{FromRawFd, IntoRawFd}; + use std::os::unix::net::UnixStream; + + let (reader, mut writer) = UnixStream::pair().unwrap(); + reader.set_nonblocking(true).unwrap(); + let raw = reader.into_raw_fd(); + // SAFETY: `raw` is the unique owner of the stream descriptor. + let file = File::from_std(unsafe { std::fs::File::from_raw_fd(raw) }); + let mut table = Table::default(); + let fd = table + .push(Entry { + resource: Resource::File(file), + rights_base: RIGHTS_FD_READ | RIGHTS_FD_SEEK | RIGHTS_FD_TELL, + rights_inheriting: 0, + fdflags: 0, + filetype: FILETYPE_UNKNOWN, + }) + .unwrap(); + + struct Memory(std::cell::RefCell>); + impl GuestMemory for Memory { + fn size(&self) -> u64 { + self.0.borrow().len() as u64 + } + fn read(&self, offset: u32, bytes: &mut [u8]) -> Result<(), u16> { + let memory = self.0.borrow(); + let data = memory + .get(offset as usize..offset as usize + bytes.len()) + .ok_or(FAULT)?; + bytes.copy_from_slice(data); + Ok(()) + } + fn write(&self, offset: u32, bytes: &[u8]) -> Result<(), u16> { + let mut memory = self.0.borrow_mut(); + let data = memory + .get_mut(offset as usize..offset as usize + bytes.len()) + .ok_or(FAULT)?; + data.copy_from_slice(bytes); + Ok(()) + } + } + let memory = Memory(std::cell::RefCell::new(vec![0; 65536])); + fn write_iovec(memory: &impl GuestMemory, ptr: u32, buf: u32, len: u32) { + let mut bytes = [0u8; 8]; + bytes[..4].copy_from_slice(&buf.to_le_bytes()); + bytes[4..].copy_from_slice(&len.to_le_bytes()); + memory.write(ptr, &bytes).unwrap(); + } + + write_iovec(&memory, 16, 100, 3); + assert_eq!( + fd_read(&mut table, &memory, fd, 16, 1, 32), + i32::from(AGAIN) + ); + + writer.write_all(b"abc").unwrap(); + write_iovec(&memory, 16, 65535, 3); + assert_eq!( + fd_read(&mut table, &memory, fd, 16, 1, 32), + i32::from(FAULT) + ); + + write_iovec(&memory, 16, 100, 3); + assert_eq!( + fd_read(&mut table, &memory, fd, 16, 1, 32), + i32::from(SUCCESS) + ); + let mut nread = [0u8; 4]; + memory.read(32, &mut nread).unwrap(); + assert_eq!(u32::from_le_bytes(nread), 3); + let mut got = [0u8; 3]; + memory.read(100, &mut got).unwrap(); + assert_eq!(&got, b"abc"); + + drop(writer); + assert_eq!( + fd_read(&mut table, &memory, fd, 16, 1, 32), + i32::from(SUCCESS) + ); + memory.read(32, &mut nread).unwrap(); + assert_eq!(u32::from_le_bytes(nread), 0); + assert_eq!(fd_close(&mut table, fd), i32::from(SUCCESS)); + assert_eq!(fd_close(&mut table, fd), i32::from(BADF)); + assert_eq!(fd_read(&mut table, &memory, fd, 16, 1, 32), i32::from(BADF)); + } +} diff --git a/crates/wasm/Cargo.toml b/crates/wasm/Cargo.toml index f9ea3ab9e3d..def85c07298 100644 --- a/crates/wasm/Cargo.toml +++ b/crates/wasm/Cargo.toml @@ -12,9 +12,10 @@ license.workspace = true crate-type = ["cdylib", "rlib"] [features] -default = ["freeze-stdlib", "doc"] +default = ["freeze-stdlib", "doc", "ucd_3_2_0"] doc = ["rustpython-vm/doc", "rustpython-stdlib?/doc"] freeze-stdlib = ["rustpython-vm/freeze-stdlib", "rustpython-pylib/freeze-stdlib", "rustpython-stdlib", "rustpython-stdlib/ssl"] +ucd_3_2_0 = ["rustpython-stdlib?/ucd_3_2_0"] no-start-func = [] [dependencies] diff --git a/crates/wasm/src/browser_module.rs b/crates/wasm/src/browser_module.rs index f6b20769449..f2544a9fede 100644 --- a/crates/wasm/src/browser_module.rs +++ b/crates/wasm/src/browser_module.rs @@ -133,8 +133,7 @@ mod _browser { let args = vec![vm.ctx.new_float(time).into()]; let _ = func.invoke(args, vm); - let closure = f.borrow_mut().take(); - drop(closure); + let _closure = f.borrow_mut().take(); }) }) as Box)); diff --git a/crates/wasm/src/js_module.rs b/crates/wasm/src/js_module.rs index 2ef56c85a39..db7fe8e66b8 100644 --- a/crates/wasm/src/js_module.rs +++ b/crates/wasm/src/js_module.rs @@ -581,8 +581,8 @@ mod _js { ) } - #[pymethod(name = "__await__")] - fn r#await(zelf: PyRef) -> AwaitPromise { + #[pymethod] + fn __await__(zelf: PyRef) -> AwaitPromise { AwaitPromise { obj: Some(zelf.into()).into(), } diff --git a/crates/wasm/src/ssl.rs b/crates/wasm/src/ssl.rs index 2504c44cfce..e71f1ef955f 100644 --- a/crates/wasm/src/ssl.rs +++ b/crates/wasm/src/ssl.rs @@ -16,7 +16,7 @@ mod _ssl { PyUtf8StrRef, }, common::lock::{PyMutex, PyRwLock}, - function::{ArgBytesLike, OptionalArg}, + function::{ArgBytesLike, ArgIntoBool, ArgIntoFloat, ArgStrOrBytesLike, OptionalArg}, stdlib::_warnings, types::Constructor, }; @@ -354,8 +354,8 @@ mod _ssl { struct WrapBioArgs { incoming: PyRef, outgoing: PyRef, - server_side: bool, - #[pyarg(named, optional)] + server_side: ArgIntoBool, + #[pyarg(any, optional)] server_hostname: Option, #[pyarg(named, optional)] owner: Option, @@ -366,8 +366,8 @@ mod _ssl { #[derive(FromArgs)] struct WrapSocketArgs { sock: PyObjectRef, - server_side: bool, - #[pyarg(positional, optional)] + server_side: ArgIntoBool, + #[pyarg(any, optional)] server_hostname: Option, #[pyarg(named, optional)] owner: Option, @@ -383,8 +383,12 @@ mod _ssl { } #[pygetset(setter)] - fn set_check_hostname(zelf: &Py, value: bool) { + fn set_check_hostname(zelf: &Py, value: ArgIntoBool) { + let value = value.into_bool(); *zelf.check_hostname.write() = value; + if value && *zelf.verify_mode.read() == CERT_NONE { + *zelf.verify_mode.write() = CERT_REQUIRED; + } } #[pygetset] @@ -528,7 +532,7 @@ mod _ssl { args: WrapBioArgs, vm: &VirtualMachine, ) -> PyResult> { - let server_side = args.server_side; + let server_side = args.server_side.into_bool(); let hostname = match args.server_hostname { Some(name) => { let hostname = name.as_str(); @@ -846,7 +850,7 @@ mod _ssl { args: GetCertArgs, vm: &VirtualMachine, ) -> PyResult> { - let binary = args.der; + let binary = args.der.into_bool(); let der = { let guard = zelf.connection.lock(); let Some(conn) = guard.as_ref() else { @@ -934,14 +938,14 @@ mod _ssl { #[derive(FromArgs)] struct CaCertsArgs { - #[pyarg(any, default)] - binary_form: bool, + #[pyarg(any, default = ArgIntoBool::FALSE)] + binary_form: ArgIntoBool, } #[derive(FromArgs)] struct GetCertArgs { - #[pyarg(positional, default)] - der: bool, + #[pyarg(positional, default = ArgIntoBool::FALSE)] + der: ArgIntoBool, } #[derive(FromArgs)] @@ -1002,7 +1006,7 @@ mod _ssl { } #[pyfunction] - fn RAND_add(_string: PyObjectRef, _entropy: f64) {} + fn RAND_add(_string: ArgStrOrBytesLike, _entropy: ArgIntoFloat) {} #[pyfunction] fn RAND_bytes(n: i32, vm: &VirtualMachine) -> PyResult { diff --git a/crates/wasm/src/vm_class.rs b/crates/wasm/src/vm_class.rs index 4b3d6f4cb77..72d71374595 100644 --- a/crates/wasm/src/vm_class.rs +++ b/crates/wasm/src/vm_class.rs @@ -83,7 +83,11 @@ impl StoredVirtualMachine { let defs = rustpython_stdlib::stdlib_module_defs(&builder.ctx); builder = builder .add_native_modules(&defs) - .add_frozen_modules(rustpython_pylib::FROZEN_STDLIB); + .add_frozen_modules_with_resources( + rustpython_pylib::FROZEN_STDLIB, + rustpython_pylib::FROZEN_STDLIB_RESOURCES, + ) + .expect("validated embedded standard-library resources"); } // Browser rustls `_ssl` overrides the rustls-free stdlib `_ssl`. @@ -199,13 +203,8 @@ impl VMStore { pub fn destroy(id: String) { STORED_VMS.with_borrow_mut(|vms| { - if let Some(stored_vm) = vms.remove(&id) { - // for f in stored_vm.drop_handlers.iter() { - // f(); - // } - // deallocate the VM - drop(stored_vm); - } + // Deallocate the VM after removing it from the registry. + let _stored_vm = vms.remove(&id); }); } @@ -384,7 +383,7 @@ impl WASMVirtualMachine { ) .into_js(vm)?; - let module = vm.new_module(&name, attrs, None); + let module = vm.try_new_module(&name, attrs, None).into_js(vm)?; let sys_modules = vm.sys_module.get_attr("modules", vm).into_js(vm)?; sys_modules.set_item(&name, module.into(), vm).into_js(vm)?; diff --git a/example_projects/frozen_stdlib/src/main.rs b/example_projects/frozen_stdlib/src/main.rs index 8ff316faed8..b585fe5be7d 100644 --- a/example_projects/frozen_stdlib/src/main.rs +++ b/example_projects/frozen_stdlib/src/main.rs @@ -27,7 +27,11 @@ fn interpreter_with_config() { fn interpreter_with_vm() { let interpreter = rustpython_vm::Interpreter::builder(Default::default()) - .add_frozen_modules(rustpython_pylib::FROZEN_STDLIB) + .add_frozen_modules_with_resources( + rustpython_pylib::FROZEN_STDLIB, + rustpython_pylib::FROZEN_STDLIB_RESOURCES, + ) + .expect("validated embedded standard-library resources") .build(); // Use interpreter.enter to reuse the same interpreter later interpreter.run(|vm| run("rustpython_vm::Interpreter::builder", vm)); diff --git a/example_projects/wasm32_without_js/.gitignore b/example_projects/wasm32_without_js/.gitignore index 50a623b5daa..a1d5b637c1c 100644 --- a/example_projects/wasm32_without_js/.gitignore +++ b/example_projects/wasm32_without_js/.gitignore @@ -1,2 +1,2 @@ */target/ -*/Cargo.lock +rustpython-without-js/Cargo.lock diff --git a/example_projects/wasm32_without_js/README.md b/example_projects/wasm32_without_js/README.md index 67fef3fba47..30d4f32d87e 100644 --- a/example_projects/wasm32_without_js/README.md +++ b/example_projects/wasm32_without_js/README.md @@ -1,18 +1,109 @@ # RustPython wasm32 build without JS -To test, build rustpython to wasm32-unknown-unknown target first. +This example runs Python source on `wasm32-unknown-unknown` in a native Wasmer +host. The guest has no JavaScript or WASI dependency and no operating-system +services. It imports `env.print`, `env.kv_get`, and `env.kv_put`. The host +rejects any other import. The `kv` module (`kv.get` / `kv.put`) reads and +writes byte storage owned by the host; the map is empty for each run. + +## Build and run + +Install the `wasm32-unknown-unknown` Rust target, then build the guest from its +own directory so that Cargo reads its `.cargo/config.toml`: + +```shell +rustup target add wasm32-unknown-unknown +(cd rustpython-without-js && cargo build) +cargo build --locked --release --manifest-path wasm-runtime/Cargo.toml +``` ```shell -cd rustpython-without-js # due to `.cargo/config.toml` -cargo build -cd .. +wasm-runtime/target/release/wasm-runtime \ + rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm \ + -c '1 + 3' +wasm-runtime/target/release/wasm-runtime \ + rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm \ + example.py ``` -Then there will be `rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm` file. +Guest output is written to stdout. Exit status is 0 on success, 1 for a Python +exception, and 2 for invalid input or a host/runtime error. -Now we can run the wasm file with wasm runtime: +## Contract tests ```shell -cargo run --release --manifest-path wasm-runtime/Cargo.toml rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm +python3 test_runtime.py -v \ + --runtime wasm-runtime/target/release/wasm-runtime \ + --module rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm ``` +The existing WASM CI job runs these checks. + +This is a no-OS build: `Interpreter::builder` with a native `kv` module, host-lent +storage, a fixed hash seed, and unsupported entropy. + + +## Opt-in host file I/O (WASI preview1 subset) + +The default guest above remains no-OS. A separate opt-in `host-io` guest feature +imports a WASI preview1 subset (`wasi_snapshot_preview1`) for path opening and +descriptor I/O. The host decides access through preopens: + +```shell +(cd rustpython-without-js && cargo build --features host-io) +wasm-runtime/target/release/wasm-runtime \ + rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm \ + --dir directory -c "import _io; _io.FileIO('source.py', 'rb').read()" +``` + +`--dir HOST[::GUEST]` preopens a read-write directory; `--ro-dir` is the +read-only form. `GUEST` defaults to `/`. Guest FD numbers 0, 1 and 2 are +absent; preopens start at 3 in command-line order. Without a preopen the +runner rejects the WASI imports. The host limits each transfer to 64 KiB; +Python buffered I/O handles short transfers normally. + +A read-only preopen does not grant write, create, truncate, or similar rights. +`path_open` that asks for an ungranted right, or uses create/truncate/exclusive +or append flags under a read-only preopen, fails without touching the +filesystem. Absolute paths and escapes (`..` past the root, symlinks that +leave the directory) are denied. Paths must be valid UTF-8, as WASI +preview1 requires. + +The capability table and guest-memory validation live in the workspace +`rustpython-wasi-host` crate, which depends only on `cap-std` and `std`. +The runner supplies thin Wasmer memory bindings; the shared core does not +depend on Wasmer or the VM. Native `host_io` and browser integration are +separate work and are not enabled by this extraction. + +The same contract tests run against this runner and against `wasm32-wasip1` +RustPython under `wasmer`: + +```shell +cargo test --locked --manifest-path ../../Cargo.toml -p rustpython-wasi-host +cargo test --locked --release --manifest-path wasm-runtime/Cargo.toml +python3 test_wasi_fs.py -v \ + --runtime wasm-runtime/target/release/wasm-runtime \ + --module rustpython-without-js/target/wasm32-unknown-unknown/debug/rustpython_without_js.wasm +python3 test_wasi_fs.py -v \ + --wasmer "$(command -v wasmer)" \ + --wasi-module ../../target/wasm32-wasip1/wasm-release/rustpython.wasm +``` + +This stage enables path-based FileIO only. Metadata queries and directory +operations are not implemented. The guest still lacks filesystem `posix` hooks +and external importlib integration; this is not a working `-m test` runner. + +### Errno compatibility + +The no-JS and browser `wasm32-unknown-unknown` builds use WASI preview1 +errno numbers for their supported errno names, matching `wasm32-wasip1`, +rather than the previous BSD numbers. This does not add the full WASI errno +name table; host errors without an exported name still retain their raw value. +Use symbolic `errno.E*` constants instead of numeric literals. `ESHUTDOWN` +is no longer exported on wasm32-unknown: WASI preview1 does not define it. +Native host builds retain their platform errno values. + +To compare the errno tables directly, supply both pairs of runtime/module +arguments to `test_wasi_fs.py`. The ordinary tests use the no-JS runner in +that invocation; the comparison executes both guests. Run the wasmer-only +command above separately for the complete WASI contract suite. diff --git a/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml b/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml index f987fe94a24..a47a2369981 100644 --- a/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml +++ b/example_projects/wasm32_without_js/rustpython-without-js/Cargo.toml @@ -6,8 +6,11 @@ edition = "2024" [lib] crate-type = ["cdylib"] +[features] +host-io = ["rustpython-vm/host_io"] + [dependencies] -getrandom = "0.3" +getrandom = "0.4" rustpython-vm = { path = "../../../crates/vm", default-features = false, features = ["compiler"] } [workspace] diff --git a/example_projects/wasm32_without_js/rustpython-without-js/src/lib.rs b/example_projects/wasm32_without_js/rustpython-without-js/src/lib.rs index 4219b698753..44fddb06880 100644 --- a/example_projects/wasm32_without_js/rustpython-without-js/src/lib.rs +++ b/example_projects/wasm32_without_js/rustpython-without-js/src/lib.rs @@ -1,46 +1,100 @@ -use rustpython_vm::Interpreter; +use rustpython_vm::{Interpreter, Settings, pymodule}; #[link(wasm_import_module = "env")] unsafe extern "C" { - fn kv_get(kp: i32, kl: i32, vp: i32, vl: i32) -> i32; - - /// kp and kl are the key pointer and length in wasm memory, vp and vl are for the value - fn kv_put(kp: i32, kl: i32, vp: i32, vl: i32) -> i32; - fn print(p: i32, l: i32) -> i32; + fn kv_put(key_ptr: i32, key_len: i32, value_ptr: i32, value_len: i32) -> i32; + fn kv_get(key_ptr: i32, key_len: i32, buf_ptr: i32, buf_len: i32) -> i32; } +// The host writes source into guest-owned memory before calling eval. #[unsafe(no_mangle)] -pub unsafe extern "C" fn eval(s: *const u8, l: usize) -> i32 { - // let src = unsafe { std::slice::from_raw_parts(s, l) }; - // let src = std::str::from_utf8(src).unwrap(); - // TODO: use src - let src = "1 + 3"; - - // 2. Execute Python code - let interpreter = Interpreter::without_stdlib(Default::default()); - let result = interpreter.enter(|vm| { - let scope = vm.new_scope_with_builtins(); - let res = match vm.run_block_expr(scope, src) { - Ok(val) => val, - Err(_) => return Err(-1), // Python execution error - }; - let repr_str = match res.repr(vm) { - Ok(repr) => repr.to_string(), - Err(_) => return Err(-1), // Failed to get string representation - }; - Ok(repr_str) - }); - let result = match result { - Ok(r) => r, - Err(code) => return code, - }; +pub extern "C" fn alloc_source(len: usize) -> *mut u8 { + Box::into_raw(vec![0u8; len].into_boxed_slice()).cast::() +} + +fn report(message: &str) { + unsafe { print(message.as_ptr() as i32, message.len() as i32) }; +} - let msg = format!("eval result: {result}"); +#[pymodule] +mod kv { + use rustpython_vm::builtins::PyBytesRef; - unsafe { print(msg.as_str().as_ptr() as usize as i32, msg.len() as i32) }; + #[pyfunction] + fn put(key: PyBytesRef, value: PyBytesRef) { + let key = key.as_bytes(); + let value = value.as_bytes(); + unsafe { + super::kv_put( + key.as_ptr() as i32, + key.len() as i32, + value.as_ptr() as i32, + value.len() as i32, + ); + } + } - 0 + #[pyfunction] + fn get(key: PyBytesRef) -> Option> { + let key = key.as_bytes(); + let key_ptr = key.as_ptr() as i32; + let key_len = key.len() as i32; + let mut buf = vec![0u8; 64]; + loop { + let len = unsafe { + super::kv_get(key_ptr, key_len, buf.as_mut_ptr() as i32, buf.len() as i32) + }; + // A negative length means the key is missing. + let len = usize::try_from(len).ok()?; + if len <= buf.len() { + buf.truncate(len); + return Some(buf); + } + buf.resize(len, 0); + } + } +} + +/// Execute UTF-8 Python source. Return 0 on success, 1 for a Python exception, +/// or 2 for invalid UTF-8. The result or exception is sent to env.print. +/// +/// # Safety +/// `source` must be the pointer returned by `alloc_source` for `len` bytes. +/// This function takes ownership of that buffer and frees it. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn eval(source: *mut u8, len: usize) -> i32 { + let bytes = unsafe { Box::from_raw(std::ptr::slice_from_raw_parts_mut(source, len)) }; + let Ok(source) = std::str::from_utf8(&bytes) else { + report("source is not valid UTF-8"); + return 2; + }; + + // This no-OS example has no entropy provider. Use a deterministic hash seed + // rather than pretending that the custom getrandom backend produced bytes. + let mut settings = Settings::default(); + settings.hash_seed = Some(0); + let builder = Interpreter::builder(settings); + let def = kv::module_def(&builder.ctx); + let interpreter = builder.add_native_module(def).build(); + interpreter.enter(|vm| { + let scope = vm.new_scope_with_builtins(); + match vm + .run_block_expr(scope, source) + .and_then(|value| value.repr_utf8(vm)) + { + Ok(value) => { + report(value.as_str()); + 0 + } + Err(exc) => { + let mut message = String::new(); + vm.write_exception(&mut message, &exc).unwrap(); + report(&message); + 1 + } + } + }) } #[unsafe(no_mangle)] @@ -48,8 +102,5 @@ unsafe extern "Rust" fn __getrandom_v03_custom( _dest: *mut u8, _len: usize, ) -> Result<(), getrandom::Error> { - // Err(getrandom::Error::UNSUPPORTED) - - // WARNING: This function **MUST** perform proper getrandom - Ok(()) + Err(getrandom::Error::UNSUPPORTED) } diff --git a/example_projects/wasm32_without_js/test_runtime.py b/example_projects/wasm32_without_js/test_runtime.py new file mode 100644 index 00000000000..3d51423ee92 --- /dev/null +++ b/example_projects/wasm32_without_js/test_runtime.py @@ -0,0 +1,134 @@ +"""Host-side contract tests for the non-JS, no-OS WASM interpreter.""" + +import argparse +import subprocess +import tempfile +import unittest +from pathlib import Path + + +class RuntimeTests(unittest.TestCase): + runtime: Path + module: Path + + def run_guest(self, *args, module=None, exit_code=0): + proc = subprocess.run( + [str(self.runtime), str(module or self.module), *args], + capture_output=True, + encoding="utf-8", + timeout=120, + ) + self.assertEqual(proc.returncode, exit_code, (proc.stdout, proc.stderr)) + return proc.stdout + + def test_supplied_source_and_no_os(self): + source = """ +import sys +assert sys.platform == 'unknown', sys.platform +assert sys.maxsize == 2**31 - 1, sys.maxsize +assert 'posix' not in sys.builtin_module_names +assert 'nt' not in sys.builtin_module_names +assert 'js' not in sys.builtin_module_names +values = [i * i for i in range(6)] +assert values == [0, 1, 4, 9, 16, 25] +assert (1 << 100).bit_length() == 101 +try: + 1 / 0 +except ZeroDivisionError: + pass +else: + assert False +class Value: + def __init__(self, value): + self.value = value +assert Value('한글').value == '한글' +f'guest:{sum(values)}:한글' +""" + self.assertEqual(self.run_guest("-c", source), "'guest:55:한글'\n") + + def test_host_storage(self): + source = """ +import kv +assert kv.get(b'missing') is None +kv.put(b'k', b'v') +assert kv.get(b'k') == b'v' +kv.put(b'k', b'replaced') +big = bytes(range(256)) * 64 +kv.put(b'big', big) +assert kv.get(b'big') == big +(kv.get(b'k'), len(kv.get(b'big'))) +""" + self.assertEqual(self.run_guest("-c", source), "(b'replaced', 16384)\n") + + def test_file_source(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "source with spaces.py" + source.write_text("assert 6 * 7 == 42\n'from file: 한글'", encoding="utf-8") + self.assertEqual(self.run_guest(str(source)), "'from file: 한글'\n") + + def test_empty_source(self): + self.assertEqual(self.run_guest("-c", ""), "None\n") + + def test_python_exceptions(self): + cases = ( + ( + "assert False, 'deliberate failure'", + "AssertionError: deliberate failure", + ), + ("if :", "SyntaxError"), + ( + "class C:\n def __repr__(self):\n raise ValueError('repr failed')\nC()", + "ValueError: repr failed", + ), + ) + for source, needle in cases: + with self.subTest(source=source): + self.assertIn(needle, self.run_guest("-c", source, exit_code=1)) + + def test_invalid_utf8(self): + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "invalid.py" + source.write_bytes(b"\xff") + self.run_guest(str(source), exit_code=2) + + def test_missing_source(self): + self.run_guest(exit_code=2) + + def test_unexpected_import(self): + with tempfile.TemporaryDirectory() as directory: + module = Path(directory) / "contract.wat" + module.write_text( + '(module (import "wasi_snapshot_preview1" "fd_write" (func)))', + encoding="utf-8", + ) + proc = subprocess.run( + [str(self.runtime), str(module), "-c", ""], + capture_output=True, + encoding="utf-8", + timeout=120, + ) + self.assertEqual(proc.returncode, 2, (proc.stdout, proc.stderr)) + self.assertIn("unexpected import", proc.stderr) + + def test_trap(self): + with tempfile.TemporaryDirectory() as directory: + module = Path(directory) / "contract.wat" + module.write_text( + """(module + (memory (export "memory") 1) + (func (export "alloc_source") (param i32) (result i32) i32.const 0) + (func (export "eval") (param i32 i32) (result i32) unreachable) + )""", + encoding="utf-8", + ) + self.run_guest("-c", "", module=module, exit_code=2) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--runtime", type=Path, required=True) + parser.add_argument("--module", type=Path, required=True) + options, unittest_args = parser.parse_known_args() + RuntimeTests.runtime = options.runtime.resolve(strict=True) + RuntimeTests.module = options.module.resolve(strict=True) + unittest.main(argv=[__file__, *unittest_args]) diff --git a/example_projects/wasm32_without_js/test_wasi_fs.py b/example_projects/wasm32_without_js/test_wasi_fs.py new file mode 100644 index 00000000000..cb9f79b4927 --- /dev/null +++ b/example_projects/wasm32_without_js/test_wasi_fs.py @@ -0,0 +1,514 @@ +"""WASI preview1 filesystem contract tests for the no-JS guest and wasm32-wasip1.""" + +from __future__ import annotations + +import argparse +import ast +import os +import subprocess +import tempfile +import unittest +from pathlib import Path + +_PARSER = argparse.ArgumentParser(add_help=False) +_PARSER.add_argument("--runtime", type=Path) +_PARSER.add_argument("--module", type=Path) +_PARSER.add_argument("--wasmer", type=Path) +_PARSER.add_argument("--wasi-module", type=Path) +_EARLY, _ = _PARSER.parse_known_args() +RUNTIME_MODE = _EARLY.runtime is not None +WASMER_MODE = _EARLY.wasmer is not None + +REPO_ROOT = Path(__file__).resolve().parents[2] +LIB_DIR = REPO_ROOT / "Lib" + + +class WasiFsTests(unittest.TestCase): + runtime: Path | None = None + module: Path | None = None + wasmer: Path | None = None + wasi_module: Path | None = None + + def run_snippet( + self, + source, + *, + dirs=(), + ro_dirs=(), + marker="wasi-fs-ok", + extra_runtime_args=(), + ): + wrapped = ( + f"{source}\n{marker!r}\n" + if RUNTIME_MODE + else f"{source}\nprint({marker!r})\n" + ) + dirs = _map_mounts(dirs) + ro_dirs = _map_mounts(ro_dirs) + if RUNTIME_MODE: + command = [str(self.runtime), str(self.module), *extra_runtime_args] + for host, guest in dirs: + command += ["--dir", _mount_spec(host, guest)] + for host, guest in ro_dirs: + command += ["--ro-dir", _mount_spec(host, guest)] + command += ["-c", wrapped] + env = None + else: + if ro_dirs: + self.skipTest("wasmer mode has no read-only preopen flag") + command = [str(self.wasmer), "run"] + for host, guest in dirs: + command += ["--volume", f"{host}:{guest}"] + guest_pwd = dirs[0][1] if dirs else _guest_path_for_index(0) + command += [ + "--env", + f"PWD={guest_pwd}", + "--env", + f"RUSTPYTHONPATH={LIB_DIR}", + str(self.wasi_module), + "--", + "-c", + wrapped, + ] + env = os.environ.copy() + result = subprocess.run( + command, + capture_output=True, + encoding="utf-8", + timeout=120, + env=env, + ) + self.assertEqual(result.returncode, 0, (result.stdout, result.stderr)) + self.assertIn(marker, result.stdout) + return result + + @unittest.skipUnless( + RUNTIME_MODE and WASMER_MODE, "requires both wasm modules for comparison" + ) + def test_errno_numbers_match_wasip1(self): + # Compare exports, not hard-coded errno numbers or platform errno from + # the Python interpreter running this harness. + expression = "{name: getattr(errno, name) for name in dir(errno) if name.startswith('E') and isinstance(getattr(errno, name), int)}" + with tempfile.TemporaryDirectory() as directory: + commands = ( + [ + str(self.runtime), + str(self.module), + "--dir", + directory, + "-c", + "import errno\n" + expression, + ], + [ + str(self.wasmer), + "run", + str(self.wasi_module), + "--", + "-c", + "import errno; print(" + expression + ")", + ], + ) + tables = [] + for command in commands: + result = subprocess.run( + command, capture_output=True, encoding="utf-8", timeout=120 + ) + self.assertEqual(result.returncode, 0, (result.stdout, result.stderr)) + tables.append(ast.literal_eval(result.stdout.strip())) + guest, wasi = tables + self.assertNotIn("ESHUTDOWN", guest) + self.assertLessEqual(guest.keys(), wasi.keys()) + for name in guest: + self.assertEqual(guest[name], wasi[name], name) + for name in ("ENOENT", "EACCES", "ENOTCAPABLE", "EINVAL"): + self.assertIn(name, guest) + self.assertIn(name, wasi) + + def test_errno_exception_classes(self): + with tempfile.TemporaryDirectory() as directory: + self.run_snippet( + """ +import errno +for name, cls in ( + ('ENOENT', FileNotFoundError), + ('EACCES', PermissionError), + ('EAGAIN', BlockingIOError), + ('EPIPE', BrokenPipeError), + ('EINVAL', OSError), + ('ENOTSUP', OSError), +): + value = getattr(errno, name) + assert type(OSError(value, 'contract')) is cls, name + assert getattr(errno, errno.errorcode[value]) == value, name +assert errno.EAGAIN == errno.EWOULDBLOCK +""", + dirs=[(directory, "/")], + ) + + def test_read_write_seek_truncate_and_buffering(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "lent file" + path.write_bytes(b"host data") + (Path(directory) / "buffered").touch() + self.run_snippet( + """ +import _io +raw = _io.FileIO('lent file', 'rb+') +assert raw.seekable() +assert not raw.isatty() +assert raw.read() == b'host data' +assert raw.read() == b'' +assert raw.seek(0) == 0 +buf = bytearray(4) +assert raw.readinto(buf) == 4 +assert buf == b'host' +assert raw.tell() == 4 +assert raw.seek(-4, 1) == 0 +assert raw.write(b'WASM') == 4 +assert raw.truncate(4) == 4 +raw.close() +with _io.FileIO('lent file', 'rb') as raw: + assert raw.read() == b'WASM' + +raw = _io.FileIO('buffered', 'wb') +data = b'x' * 200000 +n = raw.write(data) +assert isinstance(n, int) and 0 < n <= len(data) +assert raw.seek(0) == 0 +raw.truncate(0) +with _io.BufferedWriter(raw) as buffered: + assert buffered.write(data) == len(data) +with _io.BufferedReader(_io.FileIO('buffered', 'rb')) as buffered: + buffered.seek(0) + assert buffered.read() == data +""", + dirs=[(directory, "/")], + marker="fileio-ok", + ) + self.assertEqual(path.read_bytes(), b"WASM") + self.assertEqual((Path(directory) / "buffered").read_bytes(), b"x" * 200000) + + @unittest.skipUnless(RUNTIME_MODE, "no-JS runner caps a transfer at 64 KiB") + def test_runner_caps_raw_write_at_64kib(self): + with tempfile.TemporaryDirectory() as directory: + (Path(directory) / "short").touch() + self.run_snippet( + """ +import _io +raw = _io.FileIO('short', 'wb') +assert raw.write(b'x' * 200000) == 65536 +""", + dirs=[(directory, "/")], + marker="short-ok", + ) + + @unittest.skipUnless(RUNTIME_MODE, "no-JS guest has no stdio descriptors") + def test_no_stdio_descriptors(self): + with tempfile.TemporaryDirectory() as directory: + self.run_snippet( + """ +import _io, errno, sys +assert 'posix' not in sys.builtin_module_names +assert 'nt' not in sys.builtin_module_names +for fd in (0, 1, 2, 9999): + try: + _io.FileIO(fd, 'rb') + except OSError as e: + assert e.errno == errno.EBADF, (fd, e) + else: + assert False, fd +try: + _io.FileIO(3, 'rb') +except OSError as e: + assert e.errno == errno.EISDIR, e +else: + assert False +""", + dirs=[(directory, "/")], + marker="nostdio-ok", + ) + + @unittest.skipUnless(RUNTIME_MODE, "read-only preopen is a runner flag") + def test_readonly_preopen_denies_write_modes(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "source.py").write_bytes(b"answer = 42\n") + self.run_snippet( + """ +import _io, errno +with _io.FileIO('source.py', 'rb') as f: + assert f.read() == b'answer = 42\\n' + assert f.fileno() >= 3 +for mode in ('w', 'a', 'x', 'r+'): + try: + _io.FileIO('source.py', mode) + except PermissionError as e: + assert e.errno in (errno.ENOTCAPABLE, errno.EACCES, errno.EPERM, errno.EROFS), (mode, e) + else: + assert False, mode +""", + ro_dirs=[(directory, "/")], + marker="readonly-fs-ok", + ) + self.assertEqual((root / "source.py").read_bytes(), b"answer = 42\n") + + def test_missing_file_and_escapes(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "source.py").write_bytes(b"answer = 42\n") + host_outside = str(root / "source.py") + self.run_snippet( + f""" +import _io, errno +RUNTIME = {RUNTIME_MODE!r} +DotDot = PermissionError if RUNTIME else FileNotFoundError +try: + _io.FileIO('missing', 'r') +except FileNotFoundError as e: + assert e.errno == errno.ENOENT, e +else: + assert False + +def denied(path, cls): + try: + _io.FileIO(path, 'r') + except cls: + return + else: + assert False, path + +denied('../escape', DotDot) +denied({host_outside!r}, FileNotFoundError) +""", + dirs=[(directory, "/")], + marker="errors-ok", + ) + + @unittest.skipUnless(os.name == "posix", "Unix symlink and byte-path contract") + def test_confined_symlinks_and_byte_paths(self): + with ( + tempfile.TemporaryDirectory() as directory, + tempfile.TemporaryDirectory() as other, + ): + root = Path(directory) + (root / "inside").write_bytes(b"inside") + (root / "café").write_bytes(b"coffee") + (Path(other) / "secret").write_bytes(b"secret") + (root / "internal").symlink_to("inside") + (root / "external").symlink_to(Path(other) / "secret") + (root / "external_dir").symlink_to(other, target_is_directory=True) + have_bytes_name = True + try: + with open(os.fsencode(directory) + b"/raw-\xff", "wb") as file: + file.write(b"bytes") + except OSError: + have_bytes_name = False + byte_name_check = ( + """ +try: + _io.FileIO(b'raw-\\xff', 'r') +except Exception as e: + assert isinstance(e, OSError) +else: + assert False +""" + if have_bytes_name + else "" + ) + self.run_snippet( + f""" +import _io +RUNTIME = {RUNTIME_MODE!r} +Escape = PermissionError if RUNTIME else OSError +with _io.FileIO('internal', 'r') as f: + assert f.read() == b'inside' +with _io.FileIO('café'.encode(), 'r') as f: + assert f.read() == b'coffee' +{byte_name_check} +def denied(path): + try: + _io.FileIO(path, 'r') + except Escape: + return + else: + assert False, path + +denied('external') +denied('external_dir/secret') +""", + dirs=[(directory, "/")], + marker="symlink-ok", + ) + + def test_bytes_identity_precedence_and_descriptor_rights(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "inside").write_bytes(b"unchanged") + self.run_snippet( + f""" +import _io, errno +RUNTIME = {RUNTIME_MODE!r} +missing_str = 'no-such-file' +try: + _io.FileIO(missing_str, 'r') +except OSError as e: + assert e.errno == errno.ENOENT + assert e.filename is missing_str +else: + assert False + +missing = b'missing-\\xff' +try: + _io.FileIO(missing, 'r') +except OSError as e: + assert e.filename is missing +else: + assert False + +class PathLike: + calls = 0 + def __fspath__(self): + self.calls += 1 + return missing +pathlike = PathLike() +try: + _io.FileIO(pathlike, 'r') +except OSError as e: + assert e.filename is pathlike +else: + assert False +assert pathlike.calls == 1 + +name = 'inside' +try: + _io.FileIO(name, 'r') +except OSError: + assert False +else: + pass + +try: + _io.FileIO(b'bad\\0path', '?') +except ValueError as e: + assert 'null' in str(e) +else: + assert False + +class PathFailure(Exception): + pass +class FailingPath: + def __fspath__(self): + raise PathFailure('path first') +try: + _io.FileIO(FailingPath(), '?') +except PathFailure: + pass +else: + assert False + +opener_calls = [] +def opener(name, flags): + opener_calls.append((name, flags)) + raise AssertionError('must validate path first') +try: + _io.FileIO(b'bad\\0path', 'r', opener=opener) +except ValueError as e: + assert 'null' in str(e) +else: + assert False +assert not opener_calls + +before = pathlike.calls +class OpenerSeen(Exception): + pass +def lend(name, flags): + assert name is pathlike + raise OpenerSeen +try: + _io.FileIO(pathlike, 'r', opener=lend) +except OpenerSeen: + pass +else: + assert False +assert pathlike.calls == before + 1 + +if RUNTIME: + with _io.FileIO('inside', 'r') as original: + writer = _io.FileIO(original.fileno(), 'r+', closefd=False) + try: + writer.write(b'changed') + except OSError: + pass + else: + assert False, 'readonly descriptor accepted write' + try: + writer.truncate(0) + except OSError: + pass + else: + assert False, 'readonly descriptor accepted truncate' + writer.close() + original.seek(0) + assert original.read() == b'unchanged' +""", + dirs=[(directory, "/")], + marker="bytes-contract-ok", + ) + self.assertEqual((root / "inside").read_bytes(), b"unchanged") + + @unittest.skipUnless(RUNTIME_MODE, "fail-closed imports are a runner check") + def test_wasi_imports_require_a_preopen(self): + result = subprocess.run( + [str(self.runtime), str(self.module), "-c", "1"], + capture_output=True, + encoding="utf-8", + timeout=120, + ) + self.assertEqual(result.returncode, 2) + self.assertIn("unexpected import: wasi_snapshot_preview1.", result.stderr) + + +def _guest_path_for_index(index): + """Guest path for the Nth test mount. + + The no-JS runner's current directory is fixed at `/`, so the first mount + stays there. Wasmer mounts at `/work`, `/work2`, ... so writes reach the + host: a volume on guest `/` does not persist to the host. + """ + if RUNTIME_MODE: + return "/" if index == 0 else f"/work{index + 1}" + return "/work" if index == 0 else f"/work{index + 1}" + + +def _map_mounts(mounts): + return [ + (host, _guest_path_for_index(index)) for index, (host, _) in enumerate(mounts) + ] + + +def _mount_spec(host, guest): + if guest in ("/", ""): + return str(host) + return f"{host}::{guest}" + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--runtime", type=Path) + parser.add_argument("--module", type=Path) + parser.add_argument("--wasmer", type=Path) + parser.add_argument("--wasi-module", type=Path) + args, remaining = parser.parse_known_args() + if (args.runtime is None) != (args.module is None): + parser.error("provide both --runtime and --module") + if (args.wasmer is None) != (args.wasi_module is None): + parser.error("provide both --wasmer and --wasi-module") + if args.runtime is None and args.wasmer is None: + parser.error("provide --runtime/--module and/or --wasmer/--wasi-module") + if args.runtime is not None: + WasiFsTests.runtime = args.runtime.resolve(strict=True) + WasiFsTests.module = args.module.resolve(strict=True) + if args.wasmer is not None: + WasiFsTests.wasmer = args.wasmer.resolve(strict=True) + WasiFsTests.wasi_module = args.wasi_module.resolve(strict=True) + unittest.main(argv=[__file__, *remaining]) diff --git a/example_projects/wasm32_without_js/wasm-runtime/.gitignore b/example_projects/wasm32_without_js/wasm-runtime/.gitignore index 2e2101b5066..48bd4864116 100644 --- a/example_projects/wasm32_without_js/wasm-runtime/.gitignore +++ b/example_projects/wasm32_without_js/wasm-runtime/.gitignore @@ -1,4 +1,3 @@ *.wasm target -Cargo.lock !wasm/rustpython.wasm diff --git a/example_projects/wasm32_without_js/wasm-runtime/Cargo.lock b/example_projects/wasm32_without_js/wasm-runtime/Cargo.lock new file mode 100644 index 00000000000..e3de618303c --- /dev/null +++ b/example_projects/wasm32_without_js/wasm-runtime/Cargo.lock @@ -0,0 +1,2733 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "addr2line" +version = "0.27.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e567177890eb1617b1f774005b66b26b2377afd138a2ca37aae7d8f0c81429d4" +dependencies = [ + "cpp_demangle 0.5.1", + "fallible-iterator", + "gimli 0.34.0", + "memmap2 0.9.12", + "object", + "rustc-demangle", + "smallvec", + "typed-arena", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "ambient-authority" +version = "0.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9d4ee0d472d1cd2e28c97dfa124b3d8d992e10eb0a035f33f5d12e3a177ba3b" + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "atomic-take" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a8ab6b55fe97976e46f91ddbed8d147d966475dc29b2032757ba47e02376fbc3" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "backtrace" +version = "0.3.77" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42f4220217f3288537b83684130f42fad43320b1c3b805f1910d683d52ded24f" +dependencies = [ + "addr2line", + "cfg-if", + "libc", + "miniz_oxide", + "object", + "rustc-demangle", + "windows-link", +] + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "blake3" +version = "1.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d9e454fc11f76977dc803893aff6304ed33d6a26efae8696573bea74baa27ae" +dependencies = [ + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "cpufeatures", + "rayon-core", +] + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" +dependencies = [ + "allocator-api2", +] + +[[package]] +name = "bumpalo-herd" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a57952053bc5530247762011239f17c49e82376130cdcd03da0dc49ab8bd6c3" +dependencies = [ + "bumpalo", +] + +[[package]] +name = "bytecheck" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26333eeac754f0ad8a6bcd0eb0ac012156302e4e16b852b72ee399aea4f12c29" +dependencies = [ + "bytecheck_derive", + "ptr_meta", + "rancor", + "simdutf8", +] + +[[package]] +name = "bytecheck_derive" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46d07918caa9eeaaf06b7873925c53a61daac173539b4f7715090745e44e4e69" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "bytesize" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7354288c522e7e980fafd2075d63d1285794c3a6a16cdd492f189ea406e5f18b" + +[[package]] +name = "cap-primitives" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b5f74729fd2f44701d1a8eb47e906cdb3ccd9ec0f02baad85a744b791940b18" +dependencies = [ + "ambient-authority", + "fs-set-times", + "io-extras", + "io-lifetimes 3.0.1", + "ipnet", + "maybe-owned", + "rustix", + "rustix-linux-procfs", + "windows-sys 0.61.2", + "winx", +] + +[[package]] +name = "cap-std" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1ec78e242cfa2cfe276807ac2ecc00315a6c97786977414bcd1c3963b6c91b8" +dependencies = [ + "cap-primitives", + "io-extras", + "io-lifetimes 3.0.1", + "rustix", +] + +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cobs" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" +dependencies = [ + "thiserror", +] + +[[package]] +name = "colored" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "colosseum" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "370c83b49aedf022ee27942e8ae1d9de1cf40dc9653ee6550e4455d08f6406f9" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "corosensei" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6886a0c0f263965933c438626e7179139a62b978a33aa18281cbf0cd5a975f34" +dependencies = [ + "autocfg", + "cfg-if", + "libc", + "scopeguard", + "windows-sys 0.59.0", +] + +[[package]] +name = "cpp_demangle" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2bb79cb74d735044c972aae58ed0aaa9a837e85b01106a54c39e42e97f62253" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cpp_demangle" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0667304c32ea56cb4cd6d2d7c0cfe9a2f8041229db8c033af7f8d69492429def" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "cranelift-assembler-x64" +version = "0.136.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "249a61efca6a54425e027f5704a6f68a0232b4df527e05a3ef947d89dbdcb078" +dependencies = [ + "cranelift-assembler-x64-meta", +] + +[[package]] +name = "cranelift-assembler-x64-meta" +version = "0.136.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5336a46e05db2d515440b1ce8a9363e7bc04b608c0f66cc98dddc5492a66fbf" +dependencies = [ + "cranelift-srcgen", +] + +[[package]] +name = "cranelift-bforest" +version = "0.136.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06c9b7896b744283c68051c6fa53dff5919bdca5f3ad30f2502cbe03346fc27c" +dependencies = [ + "cranelift-entity", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-bitset" +version = "0.136.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2d44fd93e9b7d5d76846a5d7e96f4f31c84e7c84079bf69e2bf17e5d08f8d607" +dependencies = [ + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen" +version = "0.136.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24cca39a8327756e489ee65c7f2ff79a6f7c8f2837f83fef046d1899c781c59d" +dependencies = [ + "bumpalo", + "cranelift-assembler-x64", + "cranelift-bforest", + "cranelift-bitset", + "cranelift-codegen-meta", + "cranelift-codegen-shared", + "cranelift-control", + "cranelift-entity", + "cranelift-isle", + "gimli 0.33.0", + "hashbrown 0.17.1", + "libm", + "log", + "regalloc2", + "rustc-hash", + "serde", + "smallvec", + "target-lexicon", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-codegen-meta" +version = "0.136.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c5e6323d458486d95781defdb5016a1176fc911d8bc8e64b696adbda6e9044" +dependencies = [ + "cranelift-assembler-x64-meta", + "cranelift-codegen-shared", + "cranelift-srcgen", + "heck", +] + +[[package]] +name = "cranelift-codegen-shared" +version = "0.136.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1260aa93b0bd48e8e55c1c7fd9ff6a260f1a1bc46e1f0151a5055b124e5b15d" + +[[package]] +name = "cranelift-control" +version = "0.136.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50c179632a09850f81f1a1e9116cb09330c734a86689f3ee4c3f4ec81543acbd" +dependencies = [ + "arbitrary", +] + +[[package]] +name = "cranelift-entity" +version = "0.136.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589be6584f586f8b21fe17e68cb10505d1cb9a3aa42af1173b8024a12f3ec96d" +dependencies = [ + "cranelift-bitset", + "wasmtime-internal-core", +] + +[[package]] +name = "cranelift-frontend" +version = "0.136.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413f3f1d97d6157bd2c4e2edf1f22966a849b8d524834558e563c5a4a3bc5791" +dependencies = [ + "cranelift-codegen", + "hashbrown 0.17.1", + "log", + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cranelift-isle" +version = "0.136.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b46ea04636aa506eb49e5a61c54270314912de7f1c33ad7f7c2c57cb0784e23" + +[[package]] +name = "cranelift-srcgen" +version = "0.136.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f016b9994e39cad68107f33fa5b8dcee8fb7e38332bde3f97690e5e8abe1b10" + +[[package]] +name = "crc32fast" +version = "1.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dashmap" +version = "6.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6361d5c062261c78a176addb82d4c821ae42bed6089de0e12603cd25de2059c" +dependencies = [ + "cfg-if", + "crossbeam-utils", + "hashbrown 0.14.5", + "lock_api", + "once_cell", + "parking_lot_core", +] + +[[package]] +name = "debugid" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d" +dependencies = [ + "uuid", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "embedded-io" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef1a6892d9eef45c8fa6b9e0086428a2cca8491aca8f787c534a3d6d0bcb3ced" + +[[package]] +name = "embedded-io" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edd0f118536f44f5ccd48bcb8b111bdc3de888b58c74639dfb034a357d0f206d" + +[[package]] +name = "enum-iterator" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4549325971814bda7a44061bf3fe7e487d447cba01e4220a4b454d630d7a016" +dependencies = [ + "enum-iterator-derive", +] + +[[package]] +name = "enum-iterator-derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685adfa4d6f3d765a26bc5dbc936577de9abf756c1feeb3089b01dd395034842" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "enumset" +version = "1.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6bd2d7c76d078cd7a460fa169f778c42c026fe16d90e37d7a45d37181bdce5" +dependencies = [ + "enumset_derive", +] + +[[package]] +name = "enumset_derive" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60587c2044cabd91c4d4c73e3912e9f1ea7d76905f31c7eec51869305dae044" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fallible-iterator" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649" + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "fs-set-times" +version = "0.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" +dependencies = [ + "io-lifetimes 2.0.4", + "rustix", + "windows-sys 0.59.0", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "gimli" +version = "0.33.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" +dependencies = [ + "fnv", + "hashbrown 0.16.1", + "indexmap", + "stable_deref_trait", +] + +[[package]] +name = "gimli" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1033caf0b349c518623b5396bfb2cf0bddf44f0306d543a250e5743297aafd10" +dependencies = [ + "fnv", + "hashbrown 0.17.1", + "indexmap", + "stable_deref_trait", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "io-extras" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20fd6de4ccfcc187e38bc21cfa543cb5a302cb86a8b114eb7f0bf0dc9f8ac00f" +dependencies = [ + "io-lifetimes 3.0.1", + "windows-sys 0.60.2", +] + +[[package]] +name = "io-lifetimes" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06432fb54d3be7964ecd3649233cddf80db2832f47fec34c01f65b3d9d774983" + +[[package]] +name = "io-lifetimes" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f0fb0570afe1fed943c5c3d4102d5358592d8625fda6a0007fdbe65a92fba96" + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "leb128" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c83bff1d572d6b9aeef67ddfc8448e4a3737909cb28e81f97c791b9018703e52" + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libunwind" +version = "1.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c6639b70a7ce854b79c70d7e83f16b5dc0137cc914f3d7d03803b513ecc67ac" + +[[package]] +name = "libwild" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f7edaa8ff7a14a1a9915d5ff85c65b24426d81edc0362635a687c70ce7c1ccc" +dependencies = [ + "anyhow", + "atomic-take", + "bitflags", + "blake3", + "bumpalo-herd", + "bytesize", + "cc", + "colored", + "colosseum", + "crossbeam-queue", + "crossbeam-utils", + "derive_more", + "flate2", + "foldhash", + "gimli 0.34.0", + "glob", + "hashbrown 0.17.1", + "hex", + "indexmap", + "itertools 0.15.0", + "jobserver", + "leb128", + "libc", + "linker-layout", + "linker-trace", + "linker-utils", + "memchr", + "memmap2 0.9.12", + "nix", + "object", + "perf-event", + "perfetto-recorder", + "rayon", + "serde", + "serde_yaml", + "sha2", + "sharded-offset-map", + "sharded-vec-writer", + "smallvec", + "strum", + "symbolic-common", + "symbolic-demangle", + "thread_local", + "tracing", + "tracing-subscriber", + "uuid", + "wasm-encoder 0.255.0", + "wasmparser 0.255.0", + "winnow", + "zerocopy", + "zlib-rs", +] + +[[package]] +name = "linker-layout" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9b117d6790188a855ea548db622f1b9d3ae8fc7df7bc66f296defd78f7c2e10" +dependencies = [ + "anyhow", + "postcard", + "serde", +] + +[[package]] +name = "linker-trace" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728b8a0f9a835c0debd6ae954531169bc76cb430fae909a701303b907e5b518f" +dependencies = [ + "anyhow", + "postcard", + "serde", +] + +[[package]] +name = "linker-utils" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "198c6aa21803baa1398e7fb169adadba421164c27ee7946b3a7dcc57d40b1f7e" +dependencies = [ + "anyhow", + "leb128", + "object", + "paste", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "mach2" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0d28e293f2b8c9d2b2d1c0193bd3c1cbdc0d2cf396888dc01162f7cf9d6c3f3" + +[[package]] +name = "macho-unwind-info" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb4bdc8b0ce69932332cf76d24af69c3a155242af95c226b2ab6c2e371ed1149" +dependencies = [ + "thiserror", + "zerocopy", + "zerocopy-derive", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "maybe-owned" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4facc753ae494aeb6e3c22f839b158aebd4f9270f55cd3c79906c45476c47ab4" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d28bba84adfe6646737845bc5ebbfa2c08424eb1c37e94a1fd2a82adb56a872" +dependencies = [ + "libc", +] + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "more-asserts" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fafa6961cabd9c63bcd77a45d7e3b7f3b552b70417831fb0f56db717e72407e" + +[[package]] +name = "munge" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e17401f259eba956ca16491461b6e8f72913a0a114e39736ce404410f915a0c" +dependencies = [ + "munge_macro", +] + +[[package]] +name = "munge_macro" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4568f25ccbd45ab5d5603dc34318c1ec56b117531781260002151b8530a9f931" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "object" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd229a0361b9d0d4396176e02d65897f487eebeab7caa6d443855ee152ca0b9c" +dependencies = [ + "crc32fast", + "flate2", + "hashbrown 0.17.1", + "indexmap", + "memchr", + "ruzstd", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "perf-event" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4d6393d9238342159080d79b78cb59c67399a8e7ecfa5d410bd614169e4e823" +dependencies = [ + "libc", + "perf-event-open-sys", +] + +[[package]] +name = "perf-event-open-sys" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c44fb1c7651a45a3652c4afc6e754e40b3d6e6556f1487e2b230bfc4f33c2a8" +dependencies = [ + "libc", +] + +[[package]] +name = "perfetto-recorder" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee50f00666bf0c681a805a241afcf131ca3b9da28e79c49d3563be86099e002f" +dependencies = [ + "libc", + "nix", + "prost", + "rand", + "windows-sys 0.61.2", +] + +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "postcard" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6764c3b5dd454e283a30e6dfe78e9b31096d9e32036b5d1eaac7a6119ccb9a24" +dependencies = [ + "cobs", + "embedded-io 0.4.0", + "embedded-io 0.6.1", + "serde", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro-error-attr2" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96de42df36bb9bba5542fe9f1a054b8cc87e172759a1868aa05c1f3acc89dfc5" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "proc-macro-error2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11ec05c52be0a07b08061f7dd003e7d7092e0472bc731b4af7bb1ef876109802" +dependencies = [ + "proc-macro-error-attr2", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ef0b569d1d907ab3a28596aee62cf1f61dacb0529a4bedcd8e7460e2d5228b4" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad9c5423459fa2f729b8d9235fab810aa29628b171467744fc86d21460ad70d" +dependencies = [ + "anyhow", + "itertools 0.15.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "ptr_meta" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743da816b98c921cdbe8628ef7381b76f25ecf4da599fc80aca90eae7ef70cc0" +dependencies = [ + "ptr_meta_derive", +] + +[[package]] +name = "ptr_meta_derive" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c8d9ca532f185d5d4db7a7c9d51420b452168ea1c2b913953281bd6fe1fcbd0" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rancor" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b534442d0fcdb55d66f373d9cac6d33b6293a2335bc2136dbd06ce0e87d2572" +dependencies = [ + "ptr_meta", +] + +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rangemap" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a611d15b50743feb4c76b7d03edcb0e64f399c26961e4efe6975bc398be6aa3d" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regalloc2" +version = "0.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "757712e8e61590d6d4f5d563483755538b5aa13467837a3b41cd9832509a7f85" +dependencies = [ + "allocator-api2", + "bumpalo", + "hashbrown 0.17.1", + "log", + "rustc-hash", + "smallvec", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "region" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bc10200af9f8297cb52df7e0e1db8d9ad3e8782981d69b25eedf858f5455ca2" +dependencies = [ + "bitflags", + "libc", + "mach2", + "windows-sys 0.61.2", +] + +[[package]] +name = "rend" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "663ba70707f96e871406fe10d68128412e619b06d1d47cb91c3a4c6501176240" +dependencies = [ + "bytecheck", +] + +[[package]] +name = "rkyv" +version = "0.8.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9776093b7ca170454ab1406954f7b7d97a57c51dc6c0642957fb2ef25c2d399" +dependencies = [ + "bytecheck", + "bytes", + "hashbrown 0.17.1", + "indexmap", + "munge", + "ptr_meta", + "rancor", + "rend", + "rkyv_derive", + "tinyvec", + "uuid", +] + +[[package]] +name = "rkyv_derive" +version = "0.8.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c25ef604ac7dd839d44d64648952ea23c97866f124ff671b0ed2cf3ad9bb06e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "rustc-demangle" +version = "0.1.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustix-linux-procfs" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" +dependencies = [ + "once_cell", + "rustix", +] + +[[package]] +name = "rustpython-wasi-host" +version = "0.6.1" +dependencies = [ + "cap-std", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ruzstd" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69e4ce4a039f42bf25920b95667e4d789e98749ab11bbb8d2c2936f788421bb5" +dependencies = [ + "twox-hash", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "self_cell" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ab42ca02749e120097e328d91d415325bdf43b1c72c4c8badf37375fe40a813" + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-offset-map" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d39ce062cd707cdf07301f39c6bef3a58c75ca2d1139998edc75e7bff54248c6" +dependencies = [ + "sharded-vec-writer", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "sharded-vec-writer" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b990b2e423f971a9afaea1fdf46ab3e42197d2577e8ef89f2266c1c26a0731a6" + +[[package]] +name = "shared-buffer" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6c99835bad52957e7aa241d3975ed17c1e5f8c92026377d117a606f36b84b16" +dependencies = [ + "bytes", + "memmap2 0.6.2", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "symbolic-common" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddfa0014ff4e423a1bb8881453c7a29181eb14fe1dbc8e0197ebfa081903f3ed" +dependencies = [ + "debugid", + "memmap2 0.9.12", + "stable_deref_trait", + "uuid", +] + +[[package]] +name = "symbolic-demangle" +version = "13.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a213276280a1a737ff5fb89ae2a70ba51d1d4608e74736beb92f257f125f1aa" +dependencies = [ + "bitflags", + "cpp_demangle 0.4.5", + "itoa", + "rustc-demangle", + "symbolic-common", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "target-lexicon" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c447be3a2abfa84b2d91680c56600bd6b2873866de27b36ec911be705e291da" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.19+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "thread_local", + "tracing", + "tracing-core", +] + +[[package]] +name = "twox-hash" +version = "2.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2" + +[[package]] +name = "typed-arena" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6af6ae20167a9ece4bcb41af5b80f8a1f1df981f6391189ce00fd257af04126a" + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + +[[package]] +name = "uuid" +version = "1.29.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c" +dependencies = [ + "getrandom", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b524283fb5df62eec102ed0574838961bdd7ba5ac9c50d38e2756c51c971a42" +dependencies = [ + "leb128fmt", +] + +[[package]] +name = "wasm-encoder" +version = "0.263.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b883a26aea02eaabe2d2c3fba7eb039ef5cdcb5d5201ae5551e73d5e251a81f" +dependencies = [ + "leb128fmt", + "wasmparser 0.263.0", +] + +[[package]] +name = "wasm-runtime" +version = "0.1.0" +dependencies = [ + "rustpython-wasi-host", + "wasmer", +] + +[[package]] +name = "wasmer" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddfde3972691f1082774c71c42e21add1d1838cb6482a6921a0ba8a993e0046a" +dependencies = [ + "bindgen", + "bytes", + "cmake", + "dashmap", + "derive_more", + "indexmap", + "itertools 0.15.0", + "js-sys", + "more-asserts", + "paste", + "rkyv", + "serde", + "serde-wasm-bindgen", + "shared-buffer", + "symbolic-demangle", + "tar", + "target-lexicon", + "thiserror", + "tracing", + "wasm-bindgen", + "wasmer-compiler", + "wasmer-compiler-cranelift", + "wasmer-derive", + "wasmer-types", + "wasmer-vm", + "wasmparser 0.259.0", + "wat", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmer-compiler" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a657969bd92c09676e72916b6fed181ebb239f441266458edff37c5e13eb1f8" +dependencies = [ + "addr2line", + "backtrace", + "bytes", + "cc", + "crossbeam-channel", + "enum-iterator", + "enumset", + "gimli 0.34.0", + "itertools 0.15.0", + "leb128", + "libc", + "libwild", + "macho-unwind-info", + "memmap2 0.9.12", + "more-asserts", + "object", + "phf", + "rangemap", + "rayon", + "region", + "rkyv", + "self_cell", + "shared-buffer", + "smallvec", + "strum", + "target-lexicon", + "tempfile", + "thiserror", + "wasmer-types", + "wasmer-vm", + "wasmparser 0.259.0", + "which", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmer-compiler-cranelift" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3554998433d7f02c7154b663e3f8f2337b3476968ef341ce1d527eeef2bb6" +dependencies = [ + "cranelift-codegen", + "cranelift-entity", + "cranelift-frontend", + "indexmap", + "itertools 0.15.0", + "leb128", + "more-asserts", + "object", + "rayon", + "regalloc2", + "smallvec", + "target-lexicon", + "tracing", + "wasmer-compiler", + "wasmer-types", +] + +[[package]] +name = "wasmer-derive" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e65a98d988cf249317ec2af01526e04aafafc32503e23525e9d5fbe1c498d2db" +dependencies = [ + "proc-macro-error2", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "wasmer-types" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1a2572e35ea0fe9ac0d3c289b83ee457220e2b1a0b0d9e74a8dfef240064223" +dependencies = [ + "bytecheck", + "crc32fast", + "enum-iterator", + "enumset", + "getrandom", + "hex", + "indexmap", + "itertools 0.15.0", + "more-asserts", + "num_enum", + "rkyv", + "sha2", + "target-lexicon", + "thiserror", +] + +[[package]] +name = "wasmer-vm" +version = "7.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b60bc87e4993702174a81a6dd4503d915331b1d50caf868fd0998f61f34afa5" +dependencies = [ + "backtrace", + "bytesize", + "cc", + "corosensei", + "crossbeam-queue", + "dashmap", + "enum-iterator", + "fnv", + "gimli 0.34.0", + "indexmap", + "itertools 0.15.0", + "libc", + "libunwind", + "mach2", + "more-asserts", + "parking_lot", + "region", + "rustversion", + "scopeguard", + "thiserror", + "wasmer-types", + "windows-sys 0.61.2", +] + +[[package]] +name = "wasmparser" +version = "0.255.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e329ef4b5d46e73b91d3ac6924417cad55a8cbbf869c199283383427c3320b" +dependencies = [ + "bitflags", + "hashbrown 0.17.1", + "indexmap", +] + +[[package]] +name = "wasmparser" +version = "0.259.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f7c12eac7bb587801590f6a67ff0bc84d0748513864b71108e4b311cc3df694" +dependencies = [ + "bitflags", +] + +[[package]] +name = "wasmparser" +version = "0.263.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f5fa0a054ae153606df820eb0a84213e28cda41bbe04ba2628e71b6ba100fcb" +dependencies = [ + "bitflags", + "indexmap", + "semver", +] + +[[package]] +name = "wasmtime-internal-core" +version = "49.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f24a558f82f07e4e76a8b848288901d9f663e4e95c25f6d73627daca5f4ce93" +dependencies = [ + "hashbrown 0.17.1", + "libm", +] + +[[package]] +name = "wast" +version = "263.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69d90bcf581b501aa1c358bc5dc0faa979cd375796908860ebcb6d1d70b907c7" +dependencies = [ + "bumpalo", + "leb128fmt", + "memchr", + "unicode-width", + "wasm-encoder 0.263.0", +] + +[[package]] +name = "wat" +version = "1.263.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbc9c5aca783b3f1838be89f3f9937c528b90ec5faa6fb62d809726c16a7d8f7" +dependencies = [ + "wast", +] + +[[package]] +name = "which" +version = "8.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bae2f2b2b816647a1cab1acc91f5bd20812d53cb344382635ec2181940c8034f" +dependencies = [ + "libc", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "winx" +version = "0.36.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f3fd376f71958b862e7afb20cfe5a22830e1963462f3a17f49d82a6c1d1f42d" +dependencies = [ + "bitflags", + "windows-sys 0.59.0", +] + +[[package]] +name = "xattr" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "963d6fab92d5504b971dc8bd90ca743c2575e590bc8071ea5bc571598667ae08" +dependencies = [ + "libc", + "rustix", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" diff --git a/example_projects/wasm32_without_js/wasm-runtime/Cargo.toml b/example_projects/wasm32_without_js/wasm-runtime/Cargo.toml index a1d0de51719..5a56cb7839c 100644 --- a/example_projects/wasm32_without_js/wasm-runtime/Cargo.toml +++ b/example_projects/wasm32_without_js/wasm-runtime/Cargo.toml @@ -4,6 +4,7 @@ version = "0.1.0" edition = "2024" [dependencies] -wasmer = "6.1.0" +rustpython-wasi-host = { path = "../../../crates/wasi_host" } +wasmer = "7.5.0" -[workspace] \ No newline at end of file +[workspace] diff --git a/example_projects/wasm32_without_js/wasm-runtime/README.md b/example_projects/wasm32_without_js/wasm-runtime/README.md index 2fa2f9e119a..fa3eb00ea29 100644 --- a/example_projects/wasm32_without_js/wasm-runtime/README.md +++ b/example_projects/wasm32_without_js/wasm-runtime/README.md @@ -1,19 +1,23 @@ -# Simple WASM Runtime +# Native non-JS WASM host -WebAssembly runtime POC with wasmer with HashMap-based KV store. -First make sure to install wat2wasm and rust. +See the [example README](../README.md) for build, CLI, and test commands. -```bash -# following command installs rust -curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh +The guest imports: -cargo run --release -``` +- `env.print(ptr: i32, len: i32) -> i32`: write a UTF-8 message to stdout + followed by a newline +- `env.kv_put(key_ptr: i32, key_len: i32, value_ptr: i32, value_len: i32) -> i32`: + copy the value under the key and return 0 +- `env.kv_get(key_ptr: i32, key_len: i32, buf_ptr: i32, buf_len: i32) -> i32`: + return -1 if the key is missing, otherwise the full value length. The value + is copied into the buffer only when it fits; otherwise the caller retries + with a buffer of that length. -## WASM binary requirements +The guest exports: -Entry point is `eval(code_ptr: i32, code_len: i32) -> i32`, following are exported functions, on error return -1: +- `memory` +- `alloc_source(len: i32) -> i32` +- `eval(ptr: i32, len: i32) -> i32` -- `kv_put(key_ptr: i32, key_len: i32, val_ptr: i32, val_len: i32) -> i32` -- `kv_get(key_ptr: i32, key_len: i32, val_ptr: i32, val_len: i32) -> i32` -- `print(msg_ptr: i32, msg_len: i32) -> i32` +`eval` takes ownership of the `alloc_source` buffer and frees it. It returns 0 +on success, 1 on a Python exception, or 2 for invalid UTF-8. diff --git a/example_projects/wasm32_without_js/wasm-runtime/src/main.rs b/example_projects/wasm32_without_js/wasm-runtime/src/main.rs index 8ca7d581ce4..86b613f23d3 100644 --- a/example_projects/wasm32_without_js/wasm-runtime/src/main.rs +++ b/example_projects/wasm32_without_js/wasm-runtime/src/main.rs @@ -1,133 +1,212 @@ -use std::collections::HashMap; +use std::{ + collections::HashMap, + ffi::{OsStr, OsString}, + path::PathBuf, + process::ExitCode, +}; + use wasmer::{ - Function, FunctionEnv, FunctionEnvMut, Instance, Memory, Module, Store, Value, imports, + AsStoreRef, Function, FunctionEnv, FunctionEnvMut, Instance, Memory, Module, RuntimeError, + Store, imports, }; -struct Ctx { +mod wasi; + +const USAGE: &str = "usage: wasm-runtime MODULE.wasm [--dir HOST[::GUEST]]... [--ro-dir HOST[::GUEST]]... (-c CODE | FILE.py)"; + +struct Context { + memory: Option, kv: HashMap, Vec>, - mem: Option, + table: wasi::Table, } -/// kp and kl are the key pointer and length in wasm memory, vp and vl are for the return value -/// if read value is bigger than vl then it will be truncated to vl, returns read bytes -fn kv_get(mut ctx: FunctionEnvMut, kp: i32, kl: i32, vp: i32, vl: i32) -> i32 { - let (c, s) = ctx.data_and_store_mut(); - let mut key = vec![0u8; kl as usize]; - if c.mem - .as_ref() - .unwrap() - .view(&s) - .read(kp as u64, &mut key) - .is_err() - { - return -1; - } - match c.kv.get(&key) { - Some(val) => { - let len = val.len().min(vl as usize); - if c.mem - .as_ref() - .unwrap() - .view(&s) - .write(vp as u64, &val[..len]) - .is_err() - { - return -1; - } - len as i32 - } - None => 0, +impl Context { + fn memory(&self) -> Result<&Memory, RuntimeError> { + self.memory + .as_ref() + .ok_or_else(|| RuntimeError::new("guest memory is not initialized")) } } -/// kp and kl are the key pointer and length in wasm memory, vp and vl are for the value -fn kv_put(mut ctx: FunctionEnvMut, kp: i32, kl: i32, vp: i32, vl: i32) -> i32 { - let (c, s) = ctx.data_and_store_mut(); - let mut key = vec![0u8; kl as usize]; - let mut val = vec![0u8; vl as usize]; - let m = c.mem.as_ref().unwrap().view(&s); - if m.read(kp as u64, &mut key).is_err() || m.read(vp as u64, &mut val).is_err() { - return -1; - } - c.kv.insert(key, val); - 0 +fn read_memory( + context: &Context, + store: &impl AsStoreRef, + ptr: u32, + len: u32, +) -> Result, RuntimeError> { + let mut bytes = vec![0; len as usize]; + context + .memory()? + .view(store) + .read(u64::from(ptr), &mut bytes) + .map_err(|err| RuntimeError::new(err.to_string()))?; + Ok(bytes) } -// // p and l are the buffer pointer and length in wasm memory. -// fn get_code(mut ctx:FunctionEnvMut, p: i32, l: i32) -> i32 { -// let file_name = std::env::args().nth(2).expect("file_name is not given"); -// let code : String = std::fs::read_to_string(file_name).expect("file read failed"); -// if code.len() > l as usize { -// eprintln!("code is too long"); -// return -1; -// } - -// let (c, s) = ctx.data_and_store_mut(); -// let m = c.mem.as_ref().unwrap().view(&s); -// if m.write(p as u64, code.as_bytes()).is_err() { -// return -2; -// } +fn print(mut ctx: FunctionEnvMut, ptr: u32, len: u32) -> Result { + let (context, store) = ctx.data_and_store_mut(); + let bytes = read_memory(context, &store, ptr, len)?; + let message = std::str::from_utf8(&bytes).map_err(|err| RuntimeError::new(err.to_string()))?; + println!("{message}"); + Ok(0) +} -// 0 -// } +fn kv_put( + mut ctx: FunctionEnvMut, + key_ptr: u32, + key_len: u32, + value_ptr: u32, + value_len: u32, +) -> Result { + let (context, store) = ctx.data_and_store_mut(); + let key = read_memory(context, &store, key_ptr, key_len)?; + let value = read_memory(context, &store, value_ptr, value_len)?; + context.kv.insert(key, value); + Ok(0) +} -// p and l are the message pointer and length in wasm memory. -fn print(mut ctx: FunctionEnvMut, p: i32, l: i32) -> i32 { - let (c, s) = ctx.data_and_store_mut(); - let mut msg = vec![0u8; l as usize]; - let m = c.mem.as_ref().unwrap().view(&s); - if m.read(p as u64, &mut msg).is_err() { - return -1; +fn kv_get( + mut ctx: FunctionEnvMut, + key_ptr: u32, + key_len: u32, + buf_ptr: u32, + buf_len: u32, +) -> Result { + let (context, store) = ctx.data_and_store_mut(); + let key = read_memory(context, &store, key_ptr, key_len)?; + let Some(value) = context.kv.get(&key) else { + return Ok(-1); + }; + let len = i32::try_from(value.len()).map_err(|err| RuntimeError::new(err.to_string()))?; + if value.len() <= buf_len as usize { + context + .memory()? + .view(&store) + .write(u64::from(buf_ptr), value) + .map_err(|err| RuntimeError::new(err.to_string()))?; } - let s = std::str::from_utf8(&msg).expect("print got non-utf8 str"); - println!("{s}"); - 0 + Ok(len) } -fn main() { - let mut store = Store::default(); - let module = Module::new( - &store, - &std::fs::read(&std::env::args().nth(1).unwrap()).unwrap(), - ) - .unwrap(); +fn parse_dir_spec(value: OsString) -> (PathBuf, Vec) { + let bytes = value.as_encoded_bytes(); + match bytes.windows(2).position(|pair| pair == b"::") { + Some(index) => { + // SAFETY: `::` is ASCII, so both sides remain valid os-encoded bytes. + let host = unsafe { OsStr::from_encoded_bytes_unchecked(&bytes[..index]) }; + let guest = &bytes[index + 2..]; + let guest = if guest.is_empty() { + b"/".to_vec() + } else { + guest.to_vec() + }; + (PathBuf::from(host), guest) + } + None => (PathBuf::from(value), b"/".to_vec()), + } +} - // Prepare initial KV store with Python code - let mut initial_kv = HashMap::new(); - initial_kv.insert( - b"code".to_vec(), - b"a=10;b='str';f'{a}{b}'".to_vec(), // Python code to execute - ); +fn run() -> Result> { + let mut args = std::env::args_os().skip(1); + let module_path = PathBuf::from(args.next().ok_or(USAGE)?); + let mut source_arg = args.next().ok_or(USAGE)?; + let mut preopens = Vec::new(); + loop { + let write = if source_arg == "--dir" { + true + } else if source_arg == "--ro-dir" { + false + } else { + break; + }; + let value = args.next().ok_or(USAGE)?; + let (host, guest) = parse_dir_spec(value); + preopens.push(wasi::Preopen { host, guest, write }); + source_arg = args.next().ok_or(USAGE)?; + } + let source = if source_arg == "-c" { + args.next() + .ok_or(USAGE)? + .into_string() + .map_err(|_| "-c source is not valid UTF-8")? + } else if source_arg.as_encoded_bytes().starts_with(b"-") { + return Err(USAGE.into()); + } else { + std::fs::read_to_string(&source_arg)? + }; + if args.next().is_some() { + return Err(USAGE.into()); + } + let mut store = Store::default(); + let module = Module::new(&store, std::fs::read(&module_path)?)?; + let host_io = !preopens.is_empty(); + // Fail closed if a future build accidentally acquires OS or JS imports. + for import in module.imports() { + let allowed = (import.module() == "env" + && matches!(import.name(), "print" | "kv_get" | "kv_put")) + || (host_io + && import.module() == wasi::MODULE + && wasi::FUNCTIONS.contains(&import.name())); + if !allowed { + return Err(format!("unexpected import: {}.{}", import.module(), import.name()).into()); + } + } let env = FunctionEnv::new( &mut store, - Ctx { - kv: initial_kv, - mem: None, + Context { + memory: None, + kv: HashMap::new(), + table: wasi::Table::with_preopens(preopens)?, }, ); let imports = imports! { "env" => { + "print" => Function::new_typed_with_env(&mut store, &env, print), "kv_get" => Function::new_typed_with_env(&mut store, &env, kv_get), "kv_put" => Function::new_typed_with_env(&mut store, &env, kv_put), - // "get_code" => Function::new_typed_with_env(&mut store, &env, get_code), - "print" => Function::new_typed_with_env(&mut store, &env, print), + }, + "wasi_snapshot_preview1" => { + "fd_read" => Function::new_typed_with_env(&mut store, &env, wasi::fd_read), + "fd_write" => Function::new_typed_with_env(&mut store, &env, wasi::fd_write), + "fd_seek" => Function::new_typed_with_env(&mut store, &env, wasi::fd_seek), + "fd_close" => Function::new_typed_with_env(&mut store, &env, wasi::fd_close), + "fd_sync" => Function::new_typed_with_env(&mut store, &env, wasi::fd_sync), + "fd_filestat_set_size" => Function::new_typed_with_env(&mut store, &env, wasi::fd_filestat_set_size), + "fd_fdstat_get" => Function::new_typed_with_env(&mut store, &env, wasi::fd_fdstat_get), + "fd_prestat_get" => Function::new_typed_with_env(&mut store, &env, wasi::fd_prestat_get), + "fd_prestat_dir_name" => Function::new_typed_with_env(&mut store, &env, wasi::fd_prestat_dir_name), + "path_open" => Function::new_typed_with_env(&mut store, &env, wasi::path_open), } }; - let inst = Instance::new(&mut store, &module, &imports).unwrap(); - env.as_mut(&mut store).mem = inst.exports.get_memory("memory").ok().cloned(); - let res = inst + let instance = Instance::new(&mut store, &module, &imports)?; + let memory = instance.exports.get_memory("memory")?.clone(); + env.as_mut(&mut store).memory = Some(memory.clone()); + let alloc = instance + .exports + .get_typed_function::(&store, "alloc_source")?; + let eval = instance .exports - .get_function("eval") - .unwrap() - // TODO: actually pass source code - .call(&mut store, &[wasmer::Value::I32(0), wasmer::Value::I32(0)]) - .unwrap(); - println!( - "Result: {}", - match res[0] { - Value::I32(v) => v, - _ => -1, + .get_typed_function::<(u32, u32), i32>(&store, "eval")?; + let len = u32::try_from(source.len())?; + let ptr = alloc.call(&mut store, len)?; + memory + .view(&store) + .write(u64::from(ptr), source.as_bytes())?; + Ok(eval.call(&mut store, ptr, len)?) +} + +fn main() -> ExitCode { + match run() { + Ok(0) => ExitCode::SUCCESS, + Ok(1) => ExitCode::from(1), + Ok(status) => { + eprintln!("guest failed with status {status}"); + ExitCode::from(2) } - ); + Err(error) => { + eprintln!("{error}"); + ExitCode::from(2) + } + } } diff --git a/example_projects/wasm32_without_js/wasm-runtime/src/wasi.rs b/example_projects/wasm32_without_js/wasm-runtime/src/wasi.rs new file mode 100644 index 00000000000..3da03abf80f --- /dev/null +++ b/example_projects/wasm32_without_js/wasm-runtime/src/wasi.rs @@ -0,0 +1,138 @@ +// cspell:ignore iovecs iovs nwritten fdflags fdstat +//! Wasmer bindings for the shared capability-scoped WASI host. +use super::Context; +use rustpython_wasi_host::guest_memory::{self, GuestMemory}; +pub(crate) use rustpython_wasi_host::{FUNCTIONS, MODULE, Preopen, Table}; +use wasmer::{FunctionEnvMut, MemoryView}; + +struct Memory<'a>(Option>); +impl GuestMemory for Memory<'_> { + fn validate(&self) -> Result<(), u16> { + self.0.as_ref().map(|_| ()).ok_or(rustpython_wasi_host::IO) + } + fn size(&self) -> u64 { + self.0.as_ref().map_or(0, MemoryView::data_size) + } + fn read(&self, offset: u32, bytes: &mut [u8]) -> Result<(), u16> { + self.0 + .as_ref() + .ok_or(rustpython_wasi_host::IO)? + .read(u64::from(offset), bytes) + .map_err(|_| rustpython_wasi_host::FAULT) + } + fn write(&self, offset: u32, bytes: &[u8]) -> Result<(), u16> { + self.0 + .as_ref() + .ok_or(rustpython_wasi_host::IO)? + .write(u64::from(offset), bytes) + .map_err(|_| rustpython_wasi_host::FAULT) + } +} + +pub(crate) fn fd_read( + mut ctx: FunctionEnvMut, + fd: i32, + iovs: i32, + iovs_len: i32, + nread: i32, +) -> i32 { + let (context, store) = ctx.data_and_store_mut(); + let memory = context.memory.clone(); + let view = Memory(memory.as_ref().map(|m| m.view(&store))); + guest_memory::fd_read(&mut context.table, &view, fd, iovs, iovs_len, nread) +} + +pub(crate) fn fd_write( + mut ctx: FunctionEnvMut, + fd: i32, + iovs: i32, + iovs_len: i32, + nwritten: i32, +) -> i32 { + let (context, store) = ctx.data_and_store_mut(); + let memory = context.memory.clone(); + let view = Memory(memory.as_ref().map(|m| m.view(&store))); + guest_memory::fd_write(&mut context.table, &view, fd, iovs, iovs_len, nwritten) +} + +pub(crate) fn fd_seek( + mut ctx: FunctionEnvMut, + fd: i32, + offset: i64, + whence: i32, + newoffset: i32, +) -> i32 { + let (context, store) = ctx.data_and_store_mut(); + let memory = context.memory.clone(); + let view = Memory(memory.as_ref().map(|m| m.view(&store))); + guest_memory::fd_seek(&mut context.table, &view, fd, offset, whence, newoffset) +} + +pub(crate) fn fd_close(mut ctx: FunctionEnvMut, fd: i32) -> i32 { + guest_memory::fd_close(&mut ctx.data_mut().table, fd) +} + +pub(crate) fn fd_sync(mut ctx: FunctionEnvMut, fd: i32) -> i32 { + guest_memory::fd_sync(&mut ctx.data_mut().table, fd) +} + +pub(crate) fn fd_filestat_set_size(mut ctx: FunctionEnvMut, fd: i32, size: i64) -> i32 { + guest_memory::fd_filestat_set_size(&mut ctx.data_mut().table, fd, size) +} + +pub(crate) fn fd_fdstat_get(mut ctx: FunctionEnvMut, fd: i32, buf: i32) -> i32 { + let (context, store) = ctx.data_and_store_mut(); + let memory = context.memory.clone(); + let view = Memory(memory.as_ref().map(|m| m.view(&store))); + guest_memory::fd_fdstat_get(&mut context.table, &view, fd, buf) +} + +pub(crate) fn fd_prestat_get(mut ctx: FunctionEnvMut, fd: i32, buf: i32) -> i32 { + let (context, store) = ctx.data_and_store_mut(); + let memory = context.memory.clone(); + let view = Memory(memory.as_ref().map(|m| m.view(&store))); + guest_memory::fd_prestat_get(&mut context.table, &view, fd, buf) +} + +pub(crate) fn fd_prestat_dir_name( + mut ctx: FunctionEnvMut, + fd: i32, + path: i32, + path_len: i32, +) -> i32 { + let (context, store) = ctx.data_and_store_mut(); + let memory = context.memory.clone(); + let view = Memory(memory.as_ref().map(|m| m.view(&store))); + guest_memory::fd_prestat_dir_name(&mut context.table, &view, fd, path, path_len) +} + +#[allow(clippy::too_many_arguments)] +pub(crate) fn path_open( + mut ctx: FunctionEnvMut, + dirfd: i32, + dirflags: i32, + path: i32, + path_len: i32, + oflags: i32, + fs_rights_base: i64, + fs_rights_inheriting: i64, + fdflags: i32, + fd: i32, +) -> i32 { + let (context, store) = ctx.data_and_store_mut(); + let memory = context.memory.clone(); + let view = Memory(memory.as_ref().map(|m| m.view(&store))); + guest_memory::path_open( + &mut context.table, + &view, + dirfd, + dirflags, + path, + path_len, + oflags, + fs_rights_base, + fs_rights_inheriting, + fdflags, + fd, + ) +} diff --git a/examples/custom_tls_providers.rs b/examples/custom_tls_providers.rs index 355f75342cc..65efbd15ede 100644 --- a/examples/custom_tls_providers.rs +++ b/examples/custom_tls_providers.rs @@ -5,7 +5,6 @@ use std::env; use rustls::crypto::ring; -use rustpython_pylib::FROZEN_STDLIB; use rustpython_stdlib::{ssl::providers::CryptoExt, stdlib_module_defs}; use rustpython_vm::Interpreter; @@ -56,7 +55,11 @@ fn main() { let defs = stdlib_module_defs(&builder.ctx); let result = builder .add_native_modules(&defs) - .add_frozen_modules(FROZEN_STDLIB) + .add_frozen_modules_with_resources( + rustpython_pylib::FROZEN_STDLIB, + rustpython_pylib::FROZEN_STDLIB_RESOURCES, + ) + .expect("validated embedded standard-library resources") .build() .run(|vm| { let scope = vm.new_scope_with_builtins(); diff --git a/examples/package_embed.rs b/examples/package_embed.rs index cf2593facd8..415868a2256 100644 --- a/examples/package_embed.rs +++ b/examples/package_embed.rs @@ -18,7 +18,7 @@ fn py_main(interp: &Interpreter) -> vm::PyResult { fn main() -> ExitCode { // Add standard library path let mut settings = vm::Settings::default(); - settings.path_list.push("Lib".to_owned()); + settings.path_list.push("Lib".into()); let builder = vm::Interpreter::builder(settings); let defs = rustpython_stdlib::stdlib_module_defs(&builder.ctx); let interp = builder.add_native_modules(&defs).build(); diff --git a/extra_tests/README.md b/extra_tests/README.md index 7ca29fd42c0..3bc23832b37 100644 --- a/extra_tests/README.md +++ b/extra_tests/README.md @@ -15,3 +15,12 @@ Simply run `pytest -v` in this directory, and the tests should run (and hopefull pass). If it hangs for a long time, that's because it's building RustPython in release mode, which should take less time than it would to run every test snippet with RustPython compiled in debug mode. + +## Regression result collector + +`jsontests.py` uses the canonical regrtest process setup before discovery. Its +JSON and tables count each parent test once; failed subtests make their parent +fail. The standard unittest summary counts individual failure/error/skip events +and can therefore differ. Each case retains its full `id` and all subtest +callbacks reported by unittest, including their IDs, outcomes and tracebacks. +Historical result files are not rewritten. diff --git a/extra_tests/custom_text_test_runner.py b/extra_tests/custom_text_test_runner.py index 865265750f4..95c82afa170 100644 --- a/extra_tests/custom_text_test_runner.py +++ b/extra_tests/custom_text_test_runner.py @@ -32,20 +32,46 @@ import re import sys import time -import traceback import unittest from functools import reduce from unittest.runner import registerResult, result +from _colorize import decolor + + +def _case_id(test): + try: + label = test.id() + if isinstance(label, str): + return label + except Exception: + pass + # Some tests use self.id for their own state. Keep unittest's default + # label instead of allowing optional reporting metadata to stop execution. + if isinstance(test, unittest.TestCase): + return unittest.TestCase.id(test) + return str(test) + + +def _subtest_id(case_id, subtest): + try: + if type(subtest) is unittest.case._SubTest: + # _SubTest.id calls the parent id again; this can change in setUp. + return f"{case_id} {subtest._subDescription()}" + return _case_id(subtest) + except Exception as exc: + # Parameter formatting must not change the test's outcome. + return f"{case_id} ()" + def _get_method_dict(test): """Get the __dict__ of the underlying function for a test method. Works for both bound methods (__func__.__dict__) and plain functions. """ - method = getattr(test, test._testMethodName) + method = getattr(test, getattr(test, "_testMethodName", ""), None) func = getattr(method, "__func__", method) - return func.__dict__ + return getattr(func, "__dict__", {}) class TablePrinter(object): @@ -228,9 +254,10 @@ def __init__( self.show_test_info = verbosity > 1 self.show_individual_suite_results = verbosity > 2 self.show_errors = verbosity > 3 - self.show_errors_detail = verbosity > 4 + self.show_errors_detail = verbosity > 1 self.show_all = verbosity > 4 self.suite = None + self.current_test = None self.total_execution_time = 0 self.separator1 = "=" * CustomTextTestResult._num_formatting_chars self.separator2 = "-" * CustomTextTestResult._num_formatting_chars @@ -239,6 +266,10 @@ def __init__( self.separator_failure = "!" * CustomTextTestResult._num_formatting_chars self.separator_pre_result = "." * CustomTextTestResult._num_formatting_chars + def _exc_info_to_string(self, err, test): + # JSON and terminal details share these strings; keep both plain text. + return decolor(super()._exc_info_to_string(err, test)) + def getDescription(self, test): doc_first_line = test.shortDescription() if self.descriptions and doc_first_line: @@ -306,6 +337,10 @@ def stopTestRun(self): json.dump(self.results, f) def startTest(self, test): + super().startTest(test) + self._start_case(test) + + def _start_case(self, test): suite_base_category = ( test.__class__.base_test_category if hasattr(test.__class__, "base_test_category") @@ -317,8 +352,10 @@ def startTest(self, test): if hasattr(test.__class__, "name") else test.__class__.__name__, ) - self.case = test._testMethodName - super(CustomTextTestResult, self).startTest(test) + self.current_test = test + case_id = _case_id(test) + method_name = getattr(test, "_testMethodName", case_id) + self.case = method_name if not self.suite or self.suite != self.next_suite: if self.suite: self.results["suites"][self.suite_map[self.suite]]["execution_time"] = ( @@ -341,7 +378,7 @@ def startTest(self, test): self.case = name_override if name_override else self.case if self.show_test_info: # self.stream.writeln(self.separator2) - self.stream.write("CASE: %s" % self.case) + self.stream.write("CASE: %s" % case_id) if desc := test.shortDescription(): self.stream.write(" (Description: %s)" % desc) self.stream.write("... ") @@ -368,16 +405,13 @@ def startTest(self, test): "execution_time": None, } self.suite_number += 1 - self.num_cases = 0 - self.num_passed = 0 - self.num_failed = 0 - self.num_skipped = 0 - self.num_expected_failures = 0 self.results["suites"][self.suite_map[self.suite]]["cases"][ self.case_number ] = { "name": self.case, - "method": test._testMethodName, + "method": method_name, + "id": case_id, + "subtests": [], "result": None, "description": test.shortDescription(), "note": None, @@ -409,42 +443,49 @@ def startTest(self, test): break def stopTest(self, test): + super().stopTest(test) + self._finish_case() + + def _finish_case(self): + case = self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ] + if case["result"] is None and any( + subtest["result"] == "skipped" for subtest in case["subtests"] + ): + # A skipped subtest prevents unittest from calling addSuccess. + case["result"] = "skipped" + if self.show_test_info: + self.stream.writeln("SKIPPED (subtest)") self.end_time = time.time() self.execution_time = self.end_time - self.start_time self.suite_execution_time += self.execution_time self.total_execution_time += self.execution_time - super(CustomTextTestResult, self).stopTest(test) - self.num_cases += 1 - self.results["suites"][self.suite_map[self.suite]]["num_passed"] = ( - self.num_passed - ) - self.results["suites"][self.suite_map[self.suite]]["num_failed"] = ( - self.num_failed - ) - self.results["suites"][self.suite_map[self.suite]]["num_skipped"] = ( - self.num_skipped - ) - self.results["suites"][self.suite_map[self.suite]]["num_expected_failures"] = ( - self.num_expected_failures - ) + # JSON/table totals count parent cases once. The standard unittest + # summary still counts individual failure/error/skip events, including + # subtests; keep those two metrics distinct. + suite = self.results["suites"][self.suite_map[self.suite]] + status = case["result"] + outcome = { + "passed": "passed", + "failed": "failed", + "error": "failed", + "unexpected_success": "failed", + "skipped": "skipped", + "expected_failure": "expected_failures", + }.get(status) + if outcome is not None: + key = "num_" + outcome + suite[key] += 1 + self.results[key] += 1 self.results["suites"][self.suite_map[self.suite]]["cases"][ self.current_case_number ]["execution_time"] = format( self.execution_time, ".%sf" % CustomTextTestResult._execution_time_significant_digits, ) - self.results["num_passed"] += self.num_passed - self.results["num_failed"] += self.num_failed - self.results["num_skipped"] += self.num_skipped - self.results["num_expected_failures"] += self.num_expected_failures self.case_number += 1 - - def print_error_string(self, err): - error_string = "".join(traceback.format_exception(err[0], err[1], err[2])) - if self.show_errors: - self.stream.writeln(self.separator_failure) - self.stream.write(error_string) - return error_string + self.current_test = None def addScreenshots(self, test): for root, dirs, files in os.walk(self.result_screenshots_dir): @@ -462,11 +503,38 @@ def addSuccess(self, test): self.results["suites"][self.suite_map[self.suite]]["cases"][ self.current_case_number ]["result"] = "passed" - self.num_passed += 1 self.addScreenshots(test) + def addSubTest(self, test, subtest, err): + super().addSubTest(test, subtest, err) + case = self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ] + subtest_id = _subtest_id(case["id"], subtest) + status = "passed" + traceback_text = None + if err is not None: + status = "failed" if issubclass(err[0], test.failureException) else "error" + traceback_text = self._exc_info_to_string(err, subtest) + if case["result"] != "error": + case["result"] = status + key = "failures" if status == "failed" else "errors" + case[key] = (case[key] or "") + subtest_id + "\n" + traceback_text + if self.show_test_info: + self.stream.writeln("%s: %s" % (status.upper(), subtest_id)) + case["subtests"].append( + { + "id": subtest_id, + "result": status, + "traceback": traceback_text, + } + ) + def addError(self, test, err): - error_string = self.print_error_string(err) + fixture = self.current_test is None + if fixture: + self._start_case(test) + error_string = self._exc_info_to_string(err, test) super(CustomTextTestResult, self).addError(test, err) if self.show_test_info: # self.stream.writeln(self.separator_pre_result) @@ -477,12 +545,18 @@ def addError(self, test, err): ]["result"] = "error" self.results["suites"][self.suite_map[self.suite]]["cases"][ self.current_case_number - ]["errors"] = error_string - self.num_failed += 1 + ]["errors"] = ( + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["errors"] + or "" + ) + error_string self.addScreenshots(test) + if fixture: + self._finish_case() def addFailure(self, test, err): - error_string = self.print_error_string(err) + error_string = self._exc_info_to_string(err, test) super(CustomTextTestResult, self).addFailure(test, err) if self.show_test_info: # self.stream.writeln(self.separator_pre_result) @@ -490,15 +564,43 @@ def addFailure(self, test, err): self.stream.flush() self.results["suites"][self.suite_map[self.suite]]["cases"][ self.current_case_number - ]["result"] = "failed" + ]["result"] = ( + "error" + if self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["errors"] + else "failed" + ) self.results["suites"][self.suite_map[self.suite]]["cases"][ self.current_case_number - ]["failures"] = error_string - self.num_failed += 1 + ]["failures"] = ( + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["failures"] + or "" + ) + error_string self.addScreenshots(test) def addSkip(self, test, reason): + fixture = self.current_test is None + if fixture: + self._start_case(test) super(CustomTextTestResult, self).addSkip(test, reason) + case = self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ] + if test is not self.current_test: + case["subtests"].append( + { + "id": _subtest_id(case["id"], test), + "result": "skipped", + "reason": reason, + } + ) + return + if case["result"] in ("failed", "error"): + case["note"] = reason + return if self.show_test_info: # self.stream.writeln(self.separator_pre_result) self.stream.writeln("SKIPPED {0!r}".format(reason)) @@ -509,7 +611,8 @@ def addSkip(self, test, reason): self.results["suites"][self.suite_map[self.suite]]["cases"][ self.current_case_number ]["note"] = reason - self.num_skipped += 1 + if fixture: + self._finish_case() def addExpectedFailure(self, test, err): super(CustomTextTestResult, self).addExpectedFailure(test, err) @@ -520,7 +623,6 @@ def addExpectedFailure(self, test, err): self.results["suites"][self.suite_map[self.suite]]["cases"][ self.current_case_number ]["result"] = "expected_failure" - self.num_expected_failures += 1 self.addScreenshots(test) def addUnexpectedSuccess(self, test): @@ -529,7 +631,9 @@ def addUnexpectedSuccess(self, test): # self.stream.writeln(self.separator_pre_result) self.stream.writeln("UNEXPECTED SUCCESS") self.stream.flush() - self.num_failed += 1 + self.results["suites"][self.suite_map[self.suite]]["cases"][ + self.current_case_number + ]["result"] = "unexpected_success" self.addScreenshots(test) def printOverallSuiteResults(self, r): @@ -703,12 +807,7 @@ def printErrorsDetail(self, r): ) for case in failures_and_errors: case_ref = r[suite]["cases"][case] - case_str = "%s%s" % ( - case_ref["name"], - " (%s)" % case_ref["method"] - if case_ref["name"] != case_ref["method"] - else "", - ) + case_str = case_ref.get("id", case_ref["method"]) errors = case_ref["errors"] failures = case_ref["failures"] self.stream.writeln(self.separator1) diff --git a/extra_tests/jsontests.py b/extra_tests/jsontests.py index f3213ac09d1..aab2966e99c 100644 --- a/extra_tests/jsontests.py +++ b/extra_tests/jsontests.py @@ -3,14 +3,12 @@ from custom_text_test_runner import CustomTextTestRunner as Runner from test.libregrtest.findtests import findtests - -testnames = findtests() -# idk why this fixes the hanging, if it does -testnames.remove("test_importlib") -testnames.insert(0, "test_importlib") +from test.libregrtest.setup import setup_process def loadTestsOrSkip(loader, name): + if not name.startswith("test."): + name = "test." + name try: return loader.loadTestsFromName(name) except unittest.SkipTest as exc: @@ -24,16 +22,25 @@ def testSkipped(self): return loader.suiteClass((TestClass(name),)) -loader = unittest.defaultTestLoader -suite = loader.suiteClass( - [loadTestsOrSkip(loader, "test." + name) for name in testnames] -) +def main(): + setup_process() + testnames = findtests() + # idk why this fixes the hanging, if it does + testnames.remove("test_importlib") + testnames.insert(0, "test_importlib") + + loader = unittest.defaultTestLoader + suite = loader.suiteClass([loadTestsOrSkip(loader, name) for name in testnames]) + + resultsfile = os.path.join(os.path.dirname(__file__), "cpython_tests_results.json") + if os.path.exists(resultsfile): + os.remove(resultsfile) + + runner = Runner(results_file_path=resultsfile, verbosity=2) + runner.run(suite) -resultsfile = os.path.join(os.path.dirname(__file__), "cpython_tests_results.json") -if os.path.exists(resultsfile): - os.remove(resultsfile) + print("Done! results are available in", resultsfile) -runner = Runner(results_file_path=resultsfile, verbosity=2) -runner.run(suite) -print("Done! results are available in", resultsfile) +if __name__ == "__main__": + main() diff --git a/extra_tests/rustpython_wasi.sh b/extra_tests/rustpython_wasi.sh new file mode 100755 index 00000000000..c3db52dee84 --- /dev/null +++ b/extra_tests/rustpython_wasi.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd) +# RustPython uses PWD to set its working directory on WASI preview 1. +exec wasmer run --volume "$repo_root" \ + --env "PWD=$repo_root" \ + --env "RUSTPYTHONPATH=$repo_root/Lib" \ + "$repo_root/target/wasm32-wasip1/wasm-release/rustpython.wasm" -- "$@" diff --git a/extra_tests/snippets/builtin___main__.py b/extra_tests/snippets/builtin___main__.py index 97e76ce324a..14cd3f3b984 100644 --- a/extra_tests/snippets/builtin___main__.py +++ b/extra_tests/snippets/builtin___main__.py @@ -2,4 +2,4 @@ main_module = sys.modules["__main__"] assert main_module.__file__.endswith("builtin___main__.py") -assert main_module.__cached__ is None +assert not hasattr(main_module, "__cached__") diff --git a/extra_tests/snippets/builtin_bytearray.py b/extra_tests/snippets/builtin_bytearray.py index d897ec94782..38b5e07e6dc 100644 --- a/extra_tests/snippets/builtin_bytearray.py +++ b/extra_tests/snippets/builtin_bytearray.py @@ -1,4 +1,5 @@ import pickle +import struct import sys from testutils import assert_raises @@ -6,6 +7,19 @@ with assert_raises(MemoryError): bytearray(b"ab").resize(sys.maxsize) +# The backing bytes header also excludes lengths just below sys.maxsize. +for size in (sys.maxsize - 4 * struct.calcsize("n"), sys.maxsize - 1): + original = bytearray(b"unchanged") + with assert_raises(MemoryError): + original.resize(size) + assert original == b"unchanged" + + # An existing export is rejected before the allocation limit is checked. + with memoryview(original): + with assert_raises(BufferError): + original.resize(size) + assert original == b"unchanged" + # new assert bytearray([1, 2, 3]) assert bytearray((1, 2, 3)) @@ -19,6 +33,26 @@ bytearray("bla") with assert_raises(TypeError): bytearray("bla", encoding=b"jilj") +with assert_raises(ValueError): + bytearray("bla", "utf-8\x00") +with assert_raises(ValueError): + bytearray("bla", "utf-8", "strict\x00") +with assert_raises(ValueError): + bytearray(b"bla", "\x00", []) + + +class IterList(list): + def __iter__(self): + return iter([65, 66]) + + +class IterTuple(tuple): + def __iter__(self): + return iter([67]) + + +assert bytearray(IterList([1, 2, 3])) == bytearray(b"AB") +assert bytearray(IterTuple((9,))) == bytearray(b"C") assert bytearray( b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" @@ -733,6 +767,17 @@ def join_resize_separator(): a.clear() assert len(a) == 0 +# Clearing an empty exported buffer is a no-op and keeps its export alive. +empty = bytearray() +with memoryview(empty) as view: + assert empty.clear() is None + assert bytes(view) == b"" + assert empty.clear() is None + with assert_raises(BufferError): + empty.append(1) +empty.append(1) +assert empty == b"\x01" + b = bytearray(b"test") assert len(b) == 4 b.pop() @@ -913,3 +958,841 @@ class B(bytearray): empty = bytearray() empty *= sys.maxsize assert empty == bytearray() + + +def test_bytearray_exports(): + """Resizing paths must respect outstanding bytearray exports.""" + + import io + + from testutils import assert_raises + + for args in ((), (b"abc",), (b"x",), (b"",), (object(),)): + value = bytearray(b"abc") + with memoryview(value) as view: + with assert_raises(BufferError): + value.__init__(*args) + assert value == b"abc" + assert view.tobytes() == b"abc" + value.__init__(b"released") + assert value == b"released" + + value = bytearray(b"abc") + with assert_raises(TypeError): + value.__init__(object()) + assert value == b"" + value = bytearray(b"abc") + value.__init__(value) + assert value == b"" + + class ExportDuringInit: + def __init__(self, count, payload=b""): + self.count = count + self.payload = payload + self.calls = 0 + + def __index__(self): + self.calls += 1 + value.extend(self.payload) + self.view = memoryview(value) + return self.count + + value = bytearray(b"abc") + source = ExportDuringInit(2) + with assert_raises(BufferError): + value.__init__(source) + assert value == b"" + assert source.view.tobytes() == b"" + assert source.calls == 1 + source.view.release() + value.extend(b"released") + assert value == b"released" + + value = bytearray(b"abc") + source = ExportDuringInit(0) + value.__init__(source) + assert value == b"" + assert source.view.tobytes() == b"" + source.view.release() + + value = bytearray(b"abc") + source = ExportDuringInit(0, b"xy") + value.__init__(source) + assert value == b"xy" + assert source.view.tobytes() == b"xy" + assert source.calls == 1 + source.view.release() + + class FailingIndex: + def __index__(self): + assert value == b"" + raise ValueError("conversion failed") + + value = bytearray(b"abc") + with assert_raises(ValueError): + value.__init__(FailingIndex()) + assert value == b"" + + for key in (0, slice(0, 1)): + value = bytearray(b"abc") + with memoryview(value) as view: + with assert_raises(BufferError): + del value[key] + assert view.tobytes() == b"abc" + del value[key] + assert value == b"bc" + + class Reader(io.RawIOBase): + def __init__(self, count, retain, payload=b"abcd"): + self.count = count + self.retain = retain + self.payload = payload + + def readinto(self, buffer): + buffer[:] = self.payload + self.buffer = buffer + if self.retain: + self.view = memoryview(buffer) + return self.count + + for count in (0, 2, 4): + reader = Reader(count, False) + assert reader.read(4) == b"abcd"[:count] + assert reader.buffer == b"" + + reader = Reader(count, True) + with assert_raises(BufferError): + reader.read(4) + assert reader.view.tobytes() == b"abcd" + reader.view.release() + reader.buffer.clear() + + for count in (-1, 5): + reader = Reader(count, True) + with assert_raises(ValueError): + reader.read(4) + assert reader.view.tobytes() == b"abcd" + reader.view.release() + + reader = Reader(None, True) + assert reader.read(4) is None + assert reader.view.tobytes() == b"abcd" + reader.view.release() + + # The callback can shrink the temporary buffer, so slicing by the original + # requested size without checking the current buffer is not safe. + reader = Reader(2, False, b"xy") + assert reader.read(4) == b"xy" + assert reader.buffer == b"" + + reader = Reader(4, False, b"xy") + result = reader.read(4) + assert len(result) == 4 + assert result[:2] == b"xy" + # The contents of the newly grown region are unspecified by CPython. + assert reader.buffer == b"" + + +test_bytearray_exports() + + +def test_bytearray_threading(): + """Acquiring a bytearray export must be atomic with respect to resizing.""" + + import threading + + def exercise_exports(): + payload = b"x" * 65536 + value = bytearray(payload) + barrier = threading.Barrier(3, timeout=5) + errors = [] + + def worker(operation): + try: + for _ in range(256): + barrier.wait() + operation() + barrier.wait() + except BaseException as exc: + errors.append(exc) + barrier.abort() + + def resize(): + try: + value.clear() + value.extend(payload) + except BufferError: + pass + + def decode(): + result = value.decode("ascii") + assert result in ("", "x" * len(payload)) + + def export(): + with memoryview(value) as view: + size = len(view) + assert size in (0, len(payload)) + # The acquired export keeps its original length and contents even + # if the resizing thread runs between these two reads. + assert view.tobytes() == payload[:size] + assert len(view) == size + + threads = [ + threading.Thread(target=worker, args=(operation,), daemon=True) + for operation in (resize, decode, export) + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=10) + assert not any(thread.is_alive() for thread in threads), "worker did not finish" + if errors: + raise errors[0] + + exercise_exports() + + +test_bytearray_threading() + + +def test_bytearray_init_exports(): + """Initializer storage and integer-deletion ordering with buffer exports.""" + + from testutils import assert_raises + + class Zero: + def __init__(self, value): + self.value = value + self.observations = [] + + def __index__(self): + self.observations.append((len(self.value), self.value.__alloc__())) + return 0 + + # Final CPython rejects even an empty exported initializer before conversion. + for kind in ("missing", "integer", "callback"): + value = bytearray() + source = Zero(value) + with memoryview(value) as view: + with assert_raises(BufferError): + if kind == "missing": + value.__init__() + elif kind == "integer": + value.__init__(0) + else: + value.__init__(source) + assert value == b"" + assert view.tobytes() == b"" + assert source.observations == [] + + # Clearing an initializer must release its old storage before callbacks and + # before the successful zero-count early return. + for kind in ("missing", "integer", "callback"): + value = bytearray(b"x" * 64) + source = Zero(value) + assert value.__alloc__() > 0 + if kind == "missing": + value.__init__() + elif kind == "integer": + value.__init__(0) + else: + value.__init__(source) + assert source.observations == [(0, 0)] + assert value == b"" + assert value.__alloc__() == 0 + + # An invalid integer index is rejected before checking whether resizing is + # blocked, and neither error path may alter the exported bytes. + for initial, indices in ((b"abc", (3, -4)), (b"", (0, -1))): + for index in indices: + value = bytearray(initial) + with memoryview(value) as view: + try: + del value[index] + except IndexError as exc: + assert str(exc) == "bytearray index out of range" + else: + raise AssertionError("invalid index was accepted") + assert value == initial + assert view.tobytes() == initial + + for index in (0, -1): + value = bytearray(b"abc") + with memoryview(value) as view: + with assert_raises(BufferError): + del value[index] + assert view.tobytes() == b"abc" + del value[index] + assert value == (b"bc" if index == 0 else b"ab") + + +test_bytearray_init_exports() + + +def test_bytearray_concat_exports(): + import operator + + from testutils import assert_raises + + for concat in (operator.add, operator.concat, bytearray.__add__): + target = bytearray(b"a") + events = [] + + class ReentrantBuffer: + def __buffer__(self, flags): + events.append("acquire") + with assert_raises(BufferError): + target.__init__(object()) + with assert_raises(BufferError): + target.append(120) + target[0] = ord("A") + return memoryview(b"b") + + def __release_buffer__(self, view): + events.append("release") + # The left operand's export must already have been released. + target.append(99) + + assert concat(target, ReentrantBuffer()) == bytearray(b"Ab") + assert events == ["acquire", "release"] + assert target == bytearray(b"Ac") + target.append(100) + + class FailingBuffer: + def __buffer__(self, flags): + raise ValueError("buffer acquisition failed") + + with assert_raises(TypeError) as error: + concat(target, FailingBuffer()) + assert str(error.exception) == "can't concat FailingBuffer to bytearray" + target.append(101) + + events = [] + + class Left(bytearray): + def __buffer__(self, flags): + events.append("left acquire") + return memoryview(b"L") + + def __release_buffer__(self, view): + events.append("left release") + + class Right: + def __buffer__(self, flags): + events.append("right acquire") + return memoryview(b"R") + + def __release_buffer__(self, view): + events.append("right release") + + assert concat(Left(b"ignored"), Right()) == bytearray(b"LR") + assert events == [ + "left acquire", + "right acquire", + "left release", + "right release", + ] + + events = [] + with assert_raises(TypeError) as error: + concat(Left(), FailingBuffer()) + assert str(error.exception) == "can't concat FailingBuffer to Left" + assert events == ["left acquire", "left release"] + + class FailingLeft(bytearray): + def __buffer__(self, flags): + events.append("left acquire") + raise ValueError("left acquisition failed") + + events = [] + with assert_raises(TypeError) as error: + concat(FailingLeft(), Right()) + assert str(error.exception) == "can't concat Right to FailingLeft" + assert events == ["left acquire"] + + +test_bytearray_concat_exports() + + +def test_bytearray_callback_exports(): + import operator + + from testutils import assert_raises + + def check_comparison(): + for compare, expected in ( + (operator.eq, False), + (operator.ne, True), + (operator.lt, True), + (operator.le, True), + (operator.gt, False), + (operator.ge, False), + ): + target = bytearray(b"a") + events = [] + + class Other: + def __buffer__(self, flags): + events.append("acquire") + with assert_raises(BufferError): + target.__init__(object()) + target[0] = ord("A") + return memoryview(b"B") + + def __release_buffer__(self, view): + events.append("release") + target[0] = ord("Z") + target.append(99) + + assert compare(target, Other()) is expected + assert target == b"Zc" + assert events == ["acquire", "release"] + + events = [] + + class Left(bytearray): + def __buffer__(self, flags): + events.append("acquire") + return memoryview(b"L") + + def __release_buffer__(self, view): + events.append("release") + + left = Left(b"ignored") + assert left.__eq__(left) is True + assert events == ["acquire", "acquire", "release", "release"] + events.clear() + assert left.__eq__(object()) is NotImplemented + assert events == [] + + class Failing: + def __buffer__(self, flags): + raise ValueError("no buffer") + + assert left.__eq__(Failing()) is NotImplemented + assert events == ["acquire", "release"] + left.append(0) + + def check_search(): + for method, expected in ( + ("find", 0), + ("index", 0), + ("rfind", 2), + ("rindex", 2), + ("count", 2), + ): + target = bytearray(b"xxx") + events = [] + + class Needle: + def __buffer__(self, flags): + events.append("acquire") + with assert_raises(BufferError): + target.__init__(object()) + target[:] = b"aba" + return memoryview(b"a") + + def __release_buffer__(self, view): + events.append("release") + with assert_raises(BufferError): + target.append(0) + target[:] = b"zzz" + + assert getattr(target, method)(Needle()) == expected + assert target == b"zzz" + assert events == ["acquire", "release"] + target.append(0) + + target = bytearray(b"xxx") + + class IndexNeedle: + def __index__(self): + with assert_raises(BufferError): + target.__init__(object()) + target[:] = b"aba" + return ord("a") + + assert getattr(target, method)(IndexNeedle()) == expected + + target = bytearray(b"ab") + + class Start: + def __index__(self): + target.extend(b"ab") + return 1 + + assert target.count(ord("a"), Start()) == 1 + assert target == b"abab" + + def check_affixes(): + for method in ("startswith", "endswith"): + target = bytearray(b"aaa") + events = [] + + class Affix: + def __init__(self, value, after): + self.value = value + self.after = after + + def __buffer__(self, flags): + events.append(self.value) + with assert_raises(BufferError): + target.__init__(object()) + target[0] = target[0] + return memoryview(self.value) + + def __release_buffer__(self, view): + events.append("release") + with assert_raises(BufferError): + target.append(0) + target[:] = self.after + + class Unvisited: + def __buffer__(self, flags): + raise AssertionError("tuple must short-circuit") + + assert getattr(target, method)( + (Affix(b"x", b"yyy"), Affix(b"y", b"zzz"), Unvisited()) + ) + assert target == b"zzz" + assert events == [b"x", "release", b"y", "release"] + target.append(0) + + target = bytearray(b"aaa") + events.clear() + assert getattr(target, method)(Affix(b"a", b"zzz")) + assert target == b"zzz" + assert events == [b"a", "release"] + + events.clear() + assert not getattr(target, method)(Affix(b"z", b"aaa"), 100) + assert events == [b"z", "release"] + with assert_raises(TypeError): + getattr(target, method)((Affix(b"x", b"aaa"), object())) + target.append(0) + + class BytesAffix(bytes): + def __buffer__(self, flags): + raise AssertionError("bytes subclasses use their stored bytes") + + assert getattr(bytearray(b"a"), method)(BytesAffix(b"a")) + + def check_translate(): + target = bytearray(b"x") + table = bytearray(range(256)) + events = [] + + class Table: + def __buffer__(self, flags): + events.append("table acquire") + target.__init__(b"a") + return memoryview(table) + + def __release_buffer__(self, view): + events.append("table release") + target.__init__(b"t") + + class Delete: + def __buffer__(self, flags): + events.append("delete acquire") + with assert_raises(BufferError): + table.append(0) + table[ord("a")] = ord("b") + target.__init__(b"aa") + return memoryview(b"") + + def __release_buffer__(self, view): + events.append("delete release") + target.__init__(b"d") + + assert target.translate(Table(), delete=Delete()) == b"bb" + assert target == b"d" + assert events == [ + "table acquire", + "delete acquire", + "table release", + "delete release", + ] + table.append(0) + table.pop() + events.clear() + + class BadDelete: + def __buffer__(self, flags): + events.append("delete failure") + with assert_raises(BufferError): + table.append(0) + raise ValueError("bad delete") + + with assert_raises(ValueError): + target.translate(Table(), delete=BadDelete()) + assert events == ["table acquire", "delete failure", "table release"] + table.append(0) + + def check_padding(): + for method in ("center", "ljust", "rjust"): + target = bytearray(b"x") + assert getattr(target, method)(3, target) == b"xxx" + + class Width: + def __index__(self): + target.__init__(b"y") + return 3 + + assert getattr(target, method)(Width(), target) == b"yyy" + + check_comparison() + check_search() + check_affixes() + check_translate() + check_padding() + + +test_bytearray_callback_exports() + + +def test_bytearray_contains_builtin_and_callback_exports(): + for value in (b"", b"a", b"ab\x00\xff", b"\x01"): + target = bytearray(value) + for needle in ( + b"", + b"a", + b"ab", + b"z", + b"\x00", + b"\xff", + 0, + 97, + 255, + False, + True, + ): + assert (needle in target) == (needle in value) + assert target in target + + def must_raise_buffer_error(action): + try: + action() + except BufferError: + return + raise AssertionError("resize was not rejected") + + target = bytearray(b"a") + view = memoryview(target) + try: + assert b"a" in target + assert 97 in target + must_raise_buffer_error(lambda: target.append(0)) + target[:] = b"b" + assert b"b" in target + assert 98 in target + finally: + view.release() + target.append(0) + assert target == b"b\x00" + + class IndexNeedle: + def __index__(self): + must_raise_buffer_error(lambda: target.append(0)) + target[0] = 98 + return 98 + + class BytesNeedle(bytes): + __index__ = IndexNeedle.__index__ + + for needle in (IndexNeedle(), BytesNeedle(b"\xdd")): + target[:] = b"a" + assert needle in target + assert target == b"b" + target.append(0) + assert target == b"b\x00" + + for needle in (-1, 256): + with assert_raises(ValueError): + needle in target + + events = [0, 0] + + class BufferNeedle: + def __buffer__(self, flags): + must_raise_buffer_error(lambda: target.append(0)) + target[0] = 98 + events[0] += 1 + return memoryview(b"b") + + def __release_buffer__(self, view): + must_raise_buffer_error(lambda: target.append(0)) + events[1] += 1 + + target[:] = b"a" + assert BufferNeedle() in target + assert events == [1, 1] + target.append(0) + assert target == b"b\x00" + + +test_bytearray_contains_builtin_and_callback_exports() + + +def test_bytearray_take_bytes_bounded(): + for n, expected, remaining in ( + (None, b"abcd", b""), + (0, b"", b"abcd"), + (1, b"a", b"bcd"), + (2, b"ab", b"cd"), + (4, b"abcd", b""), + (-1, b"abc", b"d"), + (-4, b"", b"abcd"), + (True, b"a", b"bcd"), + ): + target = bytearray(b"abcd") + result = target.take_bytes(n) + assert type(result) is bytes + assert result == expected + assert target == remaining + target[:] = b"z" + assert result == expected + target = bytearray(b"abc") + assert target.take_bytes() == b"abc" + assert target == b"" + for n in (None, 0): + assert bytearray().take_bytes(n) == b"" + for n in (5, -5, sys.maxsize + 1, -sys.maxsize - 2): + target = bytearray(b"abcd") + with assert_raises(IndexError): + target.take_bytes(n) + assert target == b"abcd" + for n in (1.0, "1", b"1", object()): + with assert_raises(TypeError): + bytearray(b"a").take_bytes(n) + with assert_raises(TypeError): + bytearray(b"a").take_bytes(n=1) + with assert_raises(TypeError): + bytearray(b"a").take_bytes(1, 2) + for content in (b"", b"abcd"): + target = bytearray(content) + view = memoryview(target) + try: + for n in (None, 0, len(content)): + with assert_raises(BufferError): + target.take_bytes(n) + assert target == content + for n in (len(content) + 1, -len(content) - 1): + with assert_raises(IndexError): + target.take_bytes(n) + assert target == content + finally: + view.release() + assert target.take_bytes() == content + target = bytearray(b"abcd") + parent = memoryview(target) + child = parent[1:3] + clone = memoryview(parent) + parent.release() + try: + with assert_raises(BufferError): + target.take_bytes(0) + child.release() + with assert_raises(BufferError): + target.take_bytes(1) + finally: + child.release() + clone.release() + assert target.take_bytes() == b"abcd" + + +def test_bytearray_take_bytes_reentrant_bounded(): + class Index: + def __init__(self, action, result): + self.action = action + self.result = result + + def __index__(self): + self.action() + return self.result + + for replacement, n, expected, remaining in ( + (b"ab", 2, b"ab", b""), + (b"", 0, b"", b""), + (b"abcdef", 5, b"abcde", b"f"), + (b"ab", -1, b"a", b"b"), + ): + target = bytearray(b"abcd") + index = Index(lambda: target.__setitem__(slice(None), replacement), n) + assert target.take_bytes(index) == expected + assert target == remaining + target = bytearray(b"abcd") + with assert_raises(IndexError): + target.take_bytes(Index(target.clear, 1)) + assert target == b"" + for n, error in ((1, BufferError), (5, IndexError)): + target = bytearray(b"abcd") + views = [] + try: + with assert_raises(error): + target.take_bytes(Index(lambda: views.append(memoryview(target)), n)) + assert target == b"abcd" + finally: + for view in views: + view.release() + for n, error in ((2, None), (5, IndexError)): + target = bytearray(b"abcd") + view = memoryview(target) + try: + index = Index(view.release, n) + if error is None: + assert target.take_bytes(index) == b"ab" + assert target == b"cd" + else: + with assert_raises(error): + target.take_bytes(index) + assert target == b"abcd" + finally: + view.release() + target = bytearray(b"abcd") + with assert_raises(TypeError): + target.take_bytes(Index(lambda: None, "wrong")) + assert target == b"abcd" + + def raises(): + raise ValueError("index callback") + + with assert_raises(ValueError): + target.take_bytes(Index(raises, 1)) + assert target == b"abcd" + + class MembershipIndex: + def __index__(self): + with assert_raises(IndexError): + target.take_bytes(5) + with assert_raises(BufferError): + target.take_bytes(0) + return ord("a") + + assert MembershipIndex() in target + assert target.take_bytes() == b"abcd" + + +def test_bytearray_take_bytes_codec_callback_bounded(): + import codecs + + target = bytearray(b"\xff") + calls = [] + + def handler(error): + with assert_raises(IndexError): + target.take_bytes(2) + with assert_raises(BufferError): + target.take_bytes(0) + calls.append(error.start) + return ("?", error.end) + + codecs.register_error("bytearray_take_bytes_bounded", handler) + assert target.decode("ascii", "bytearray_take_bytes_bounded") == "?" + assert calls == [0] + assert target.take_bytes() == b"\xff" + + +test_bytearray_take_bytes_bounded() +test_bytearray_take_bytes_reentrant_bounded() +test_bytearray_take_bytes_codec_callback_bounded() diff --git a/extra_tests/snippets/builtin_bytes.py b/extra_tests/snippets/builtin_bytes.py index f30ae89e0ec..9ca22d0ef6e 100644 --- a/extra_tests/snippets/builtin_bytes.py +++ b/extra_tests/snippets/builtin_bytes.py @@ -13,6 +13,26 @@ bytes("bla") with assert_raises(TypeError): bytes("bla", encoding=b"jilj") +with assert_raises(ValueError): + bytes("bla", "utf-8\x00") +with assert_raises(ValueError): + bytes("bla", "utf-8", "strict\x00") +with assert_raises(ValueError): + bytes(b"bla", "\x00", []) + + +class IterList(list): + def __iter__(self): + return iter([65, 66]) + + +class IterTuple(tuple): + def __iter__(self): + return iter([67]) + + +assert bytes(IterList([1, 2, 3])) == b"AB" +assert bytes(IterTuple((9,))) == b"C" assert ( b"\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff" @@ -767,6 +787,26 @@ class SubBytes(bytes): pass +# Unchanged operations reuse exact bytes but must not preserve a subclass. +for method, args in ( + ("strip", ()), + ("lstrip", ()), + ("rstrip", ()), + ("removeprefix", (b"!",)), + ("removesuffix", (b"!",)), + ("replace", (b"!", b"?")), + ("replace", (b"!", b"")), + ("replace", (b"!", b"longer")), + ("replace", (b"", b"")), + ("replace", (b"a", b"b", 0)), +): + original = b"unchanged payload" + assert getattr(original, method)(*args) is original + result = getattr(SubBytes(original), method)(*args) + assert result == original + assert type(result) is bytes + + b = SubBytes(b"0123abc*&") assert id(b) == id(b) assert id(b) != id(b * -1) @@ -829,12 +869,13 @@ def __new__(cls, value): def test_huge_size(): - # sizes that cannot be allocated are MemoryError, not an aborted process + # An unrepresentable size overflows before allocation on 32-bit builds. + size_error = MemoryError if sys.maxsize >= 2**62 else OverflowError for factory in (bytes, bytearray): - assert_raises(MemoryError, lambda factory=factory: factory(2**62)) + assert_raises(size_error, lambda factory=factory: factory(2**62)) for meth in ("center", "ljust", "rjust", "zfill"): assert_raises( - MemoryError, + size_error, lambda factory=factory, meth=meth: getattr(factory(b"a"), meth)( 1 << 62 ), @@ -911,3 +952,13 @@ def out_of_range(fn, message): out_of_range(lambda: bytearray([256]), "byte must be in range(0, 256)") out_of_range(lambda: bytearray(iter([256])), "byte must be in range(0, 256)") out_of_range(lambda: bytearray().extend([256]), "byte must be in range(0, 256)") + + +class NewArgsBytes(bytes): + pass + + +for bytes_type in (bytes, NewArgsBytes): + newargs = bytes_type(b"a\x00b").__getnewargs__() + assert newargs == (b"a\x00b",) + assert type(newargs[0]) is bytes diff --git a/extra_tests/snippets/builtin_compile.py b/extra_tests/snippets/builtin_compile.py index 9c3cc9a5a94..fc6e7a2b10b 100644 --- a/extra_tests/snippets/builtin_compile.py +++ b/extra_tests/snippets/builtin_compile.py @@ -34,6 +34,11 @@ def _check_optimize_error(value): # vs C int) — checking the type only, matching test_compile.py. assert_raises(OverflowError, compile, "x = 1", "", "exec", optimize=1 << 1000) +# A null character in `mode` is rejected before `flags` is converted, and +# after `filename` is. +assert_raises(ValueError, compile, "x = 1", "", "ex\x00ec", {}) +assert_raises(TypeError, compile, "x = 1", bytearray(b""), "ex\x00ec") + # Unrecognised `flags` bits raise ValueError. CPython uses British spelling # ("unrecognised") so the message must match exactly. @@ -223,3 +228,88 @@ def _expect_syntax(source, mode): # reported rather than assumed away. with assert_raises(UnicodeEncodeError): compile(chr(0xD800), "", "eval") + +# Initial indentation in eval input precedes later tokenizer errors, with the +# same locations whether compile returns bytecode or an AST. +for source, line, column in ( + (" 1", 1, 1), + ("\n -1", 2, 1), + ("\n\t-1", 2, 1), + ("\n\f -1", 2, 2), + ("\n # comment\n -1", 3, 2), + ("\n \\\n -1", 3, 2), + ("\n \\\n (\\\n\\ ", 3, 4), +): + for flags in (0, ast.PyCF_ONLY_AST): + try: + compile(source, "", "eval", flags=flags) + except IndentationError as exc: + assert exc.msg == "unexpected indent" + assert (exc.lineno, exc.offset, exc.end_lineno, exc.end_offset) == ( + line, + column, + line, + -1, + ) + else: + raise AssertionError("initial eval indentation was accepted") + +assert eval(compile("(\n 1\n)", "", "eval")) == 1 + +# Physical CR and CRLF are translated before lexing, even inside literals. +# Keep explicit backslash-r escapes distinct from physical line endings. +for ending in ("\r", "\r\n", "\n\r", "\r\r\n"): + normalized = ending.replace("\r\n", "\n").replace("\r", "\n") + for prefix in ("", "r", "b", "f"): + source = prefix + '"""a' + ending + 'b"""' + expected = "a" + normalized + "b" + if prefix == "b": + expected = expected.encode() + assert eval(source) == expected + assert eval(source.encode()) == expected + assert eval(compile(source, "", "eval")) == expected + tree = ast.parse(source, mode="eval") + assert eval(compile(tree, "", "eval")) == expected + namespace = {} + exec("value = " + source, namespace) + assert namespace["value"] == expected + assert eval('t"""a' + ending + 'b"""').strings == ("a" + normalized + "b",) + namespace = {} + exec('def f():\r """a' + ending + ' b"""\r pass', namespace) + assert namespace["f"].__doc__ == "a" + normalized + "b" + assert eval('"a\\' + ending[:1] + 'b"') == "ab" +assert eval(r'"a\rb"') == "a\rb" +assert eval(r'r"a\rb"') == r"a\rb" + +# Warnings and SyntaxError text must use the same source as the parser. +import warnings + +for source in ('"""a\r\\q"""', '"""a\r\\q""" + )', "1\r+", '"a\rb"'): + results = [] + for text in (source, source.replace("\r", "\n")): + with warnings.catch_warnings(record=True) as captured: + warnings.simplefilter("always") + try: + eval(text) + except SyntaxError as exc: + result = (exc.msg, exc.lineno, exc.offset, exc.text) + else: + result = None + results.append((result, [(str(w.message), w.lineno) for w in captured])) + assert results[0] == results[1], (source, results) + +# Audit hooks see the caller's bytes, not the parser's translated buffer. +import sys + +newline_audit_events = [] +newline_audit_source = '"""audit\rsource"""' + + +def record_newline_compile(event, args): + if event == "compile" and args[0] == newline_audit_source.encode(): + newline_audit_events.append(args[0]) + + +sys.addaudithook(record_newline_compile) +assert eval(newline_audit_source) == "audit\nsource" +assert newline_audit_events == [newline_audit_source.encode()] diff --git a/extra_tests/snippets/builtin_compile_module.py b/extra_tests/snippets/builtin_compile_module.py new file mode 100644 index 00000000000..8ff58583b41 --- /dev/null +++ b/extra_tests/snippets/builtin_compile_module.py @@ -0,0 +1,330 @@ +import ast +import warnings + +from testutils import assert_raises, skip_if_unsupported + + +def test_compile_module(): + class ModuleName(str): + pass + + for module in (None, "", "package.module", ModuleName("package.module"), "\ud800"): + code = compile("value = 42", "", "exec", module=module) + assert code.co_filename == "" + namespace = {} + exec(code, namespace) + assert namespace["value"] == 42 + + for module in (1, False, b"package.module", [], {}, object()): + with assert_raises(TypeError) as caught: + compile("", "", "exec", module=module) + assert "argument 'module' must be str or None" in str(caught.exception) + + # module is keyword-only; _feature_version stays keyword-only too. + with assert_raises(TypeError): + compile("", "", "exec", 0, False, -1, "package.module") + + lexical_sources = [ + "x = 1or 0", + r"'\z'", + r"'\400'", + r'f"{1:\z}"', + r'f"\{1}"', + ] + codegen_sources = [ + "assert (1, 2)", + "1 is 1", + "def f():\n try:\n pass\n finally:\n return 1\n", + ] + + # Default source compilation uses module for matching, while diagnostics retain + # the real source filename. Test both text and bytes compilation. + for source in lexical_sources + codegen_sources: + for input_source in (source, source.encode()): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("error", SyntaxWarning) + warnings.filterwarnings( + "always", category=SyntaxWarning, module=r"^package\.module$" + ) + compile( + input_source, "", "exec", module="package.module" + ) + assert len(caught) == 1, (source, caught) + assert caught[0].filename == "" + assert caught[0].category is SyntaxWarning + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + warnings.filterwarnings( + "error", category=SyntaxWarning, module=r"^package\.module$" + ) + with assert_raises(SyntaxError): + compile( + input_source, + "", + "exec", + module="package.module", + ) + + # Compiling a pre-existing AST must use the module too. + for source in codegen_sources: + tree = ast.parse(source) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("error", SyntaxWarning) + warnings.filterwarnings( + "always", category=SyntaxWarning, module=r"^package\.module$" + ) + compile(tree, "", "exec", module="package.module") + assert len(caught) == 1, (source, caught) + assert caught[0].filename == "" + + # A following compile, with omitted or None module, must not inherit the override. + for kwargs in ({}, {"module": None}): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("error", SyntaxWarning) + warnings.filterwarnings( + "always", category=SyntaxWarning, module=r"^$" + ) + compile("1 is 1", "", "exec", **kwargs) + assert len(caught) == 1 + + # Failed parses use the fallback string scanner, which must retain the module. + for source in (r"b'\z' )", r'f"{1:\z}" )'): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("error", SyntaxWarning) + warnings.filterwarnings( + "always", category=SyntaxWarning, module=r"^package\.module$" + ) + with assert_raises(SyntaxError): + compile(source, "", "exec", module="package.module") + assert len(caught) == 1, (source, caught) + assert caught[0].filename == "" + + # AST conversion must use the same fallible, source-located warning boundary. + # TYPE_COMMENTS validates through the AST parser before compiling the source; + # the later compiler must not filter or emit the same escape a second time. + for flags in ( + ast.PyCF_ONLY_AST, + ast.PyCF_TYPE_COMMENTS, + ast.PyCF_ONLY_AST | ast.PyCF_TYPE_COMMENTS, + ast.PyCF_ONLY_AST | ast.PyCF_OPTIMIZED_AST, + ): + source = '\nπ = f"{1:\\z}"\n' + for kwargs, expected_module in ( + ({}, ""), + ({"module": None}, ""), + ({"module": "package.module"}, "package.module"), + ): + modules = [] + + class ModuleMatcher: + def match(self, module): + modules.append(module) + return True + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", SyntaxWarning) + warnings.filters.insert( + 0, ("always", None, SyntaxWarning, ModuleMatcher(), 0) + ) + compile(source, "", "exec", flags, **kwargs) + assert modules == [expected_module], (flags, kwargs, modules) + assert len(caught) == 1, (flags, kwargs, caught) + assert (caught[0].filename, caught[0].lineno) == ("", 2) + + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + warnings.filterwarnings( + "error", category=SyntaxWarning, module=r"^package\.module$" + ) + with assert_raises(SyntaxError) as caught: + compile( + source, "", "exec", flags, module="package.module" + ) + error = caught.exception + assert error.filename == "" + assert (error.lineno, error.offset, error.end_lineno, error.end_offset) == ( + 2, + 10, + 2, + 12, + ) + assert error.text == 'π = f"{1:\\z}"\n' + assert "Such sequences will not work in the future" not in error.msg + + # Warning handlers may raise arbitrary exceptions, which must survive intact. + failure = RuntimeError("warning handler failed") + + def showwarning(*args, **kwargs): + raise failure + + with warnings.catch_warnings(): + warnings.simplefilter("always", SyntaxWarning) + warnings.showwarning = showwarning + with assert_raises(RuntimeError) as caught: + compile( + source, "", "exec", flags, module="package.module" + ) + assert caught.exception is failure + + # Nested compile calls must not share module overrides or duplicate tracking. + modules = [] + locations = [] + + class ModuleMatcher: + def match(self, module): + modules.append(module) + return True + + def showwarning(message, category, filename, lineno, *args, **kwargs): + locations.append((filename, lineno)) + if len(locations) == 1: + compile(r'f"{1:\z}"', "", "exec", flags, module="package.inner") + + with warnings.catch_warnings(): + warnings.simplefilter("always", SyntaxWarning) + warnings.filters.insert( + 0, ("always", None, SyntaxWarning, ModuleMatcher(), 0) + ) + warnings.showwarning = showwarning + compile( + 'f"{1:\\z}"\nf"{2:\\q}"', + "", + "exec", + flags, + module="package.outer", + ) + assert modules == ["package.outer", "package.inner", "package.outer"], modules + assert locations == [("", 1), ("", 1), ("", 2)], locations + + # These warnings already came from AST conversion. Retain them instead of + # replacing that path with a broader scanner before every AST parse. + for source in ('''rf"{1:{'\\z'}}"''', '''f"{1:{t'\\z'}}"'''): + for flags in ( + ast.PyCF_ONLY_AST, + ast.PyCF_TYPE_COMMENTS, + ast.PyCF_ONLY_AST | ast.PyCF_TYPE_COMMENTS, + ): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("error", SyntaxWarning) + warnings.filterwarnings( + "always", category=SyntaxWarning, module=r"^package\.module$" + ) + compile( + source, "", "exec", flags, module="package.module" + ) + assert len(caught) == 1, (source, flags, caught) + assert (caught[0].filename, caught[0].lineno) == ("", 1) + + for flags in (ast.PyCF_ONLY_AST, ast.PyCF_ONLY_AST | ast.PyCF_TYPE_COMMENTS): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", SyntaxWarning) + with assert_raises(SyntaxError): + compile( + '!!!\nf"{1:\\z}"', + "", + "exec", + flags, + module="package.module", + ) + assert not caught + + # A filter changed by showwarning must affect the next distinct diagnostic, + # rather than treating the already-considered format escape as a new warning. + with warnings.catch_warnings(): + warnings.simplefilter("always", SyntaxWarning) + + def showwarning(*args, **kwargs): + warnings.simplefilter("error", SyntaxWarning) + + warnings.showwarning = showwarning + with assert_raises(SyntaxError) as caught: + compile( + 'f"{1:\\z}"\n"\\q"', + "", + "exec", + ast.PyCF_TYPE_COMMENTS, + module="package.module", + ) + assert caught.exception.lineno == 2 + assert "\\q" in caught.exception.msg + + # Raw literal text is not an invalid escape. Nested nonraw expressions still + # retain the diagnostics previously emitted during AST conversion. + for flags in ( + ast.PyCF_ONLY_AST, + ast.PyCF_TYPE_COMMENTS, + ast.PyCF_ONLY_AST | ast.PyCF_TYPE_COMMENTS, + ): + for source in ( + r'rf"{1:\z}"', + r'rf"{1:{2:\z}}"', + r'tr"{1:{2:\z}}"', + "f\"{1:{r'\\z'}}\"", + ): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("error", SyntaxWarning) + compile( + source, "", "exec", flags, module="package.module" + ) + assert not caught, (source, flags, caught) + for source in ("rf\"{f'{2:\\z}'}\"", "rf\"{1:{'\\z'}}\""): + with warnings.catch_warnings(): + warnings.simplefilter("error", SyntaxWarning) + with assert_raises(SyntaxError): + compile( + source, + "", + "exec", + flags, + module="package.module", + ) + + # Func-type parsing trims its source before converting the parsed nodes. + # Already-detected escapes must still point into the original source. + for prefix in ("", "\n\n"): + source = prefix + '(int) -> f"{1:aaaaaaaaaaaa\\zbbbbbbbbbbbb}"' + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", SyntaxWarning) + compile( + source, + "", + "func_type", + ast.PyCF_ONLY_AST, + module="package.module", + ) + assert len(caught) == 1, (source, caught) + assert caught[0].filename == "" + assert caught[0].lineno == prefix.count("\n") + 1 + + # Warn for the first invalid escape in each original literal, including + # literals later folded together. Comments are not literal source text. + for source, count in ( + (r'f"{1:\z\q}"', 1), + (r'f"{1:\{2}}"', 1), + (r'f"{1:\\{2}}"', 0), + ('f"{1:{(\n1 # \\z\n)}}"', 0), + ("f\"{1:{'\\z' + '\\q'}}\"", 2), + ("f\"{1:{'\\z' '\\q'}}\"", 2), + ("f\"{1:{('\\z', '\\q')[0]}}\"", 2), + ): + for flags in ( + ast.PyCF_ONLY_AST, + ast.PyCF_TYPE_COMMENTS, + ast.PyCF_ONLY_AST | ast.PyCF_OPTIMIZED_AST, + ): + for optimize in (0, 2): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", SyntaxWarning) + compile( + source, + "", + "exec", + flags, + optimize=optimize, + module="package.module", + ) + assert len(caught) == count, (source, flags, optimize, caught) + assert all(w.filename == "" for w in caught) + + +skip_if_unsupported(3, 15, test_compile_module) diff --git a/extra_tests/snippets/builtin_complex.py b/extra_tests/snippets/builtin_complex.py index ae84cac53e6..fe5785dff73 100644 --- a/extra_tests/snippets/builtin_complex.py +++ b/extra_tests/snippets/builtin_complex.py @@ -58,6 +58,10 @@ # assert 1j ** 2 == -1 assert complex(1) ** 2 == 1 assert 2 ** complex(2) == 4 +assert_raises(ValueError, pow, complex(1, 2), 2, 3) +assert_raises(ValueError, pow, 2, complex(1, 2), 3) +assert_raises(TypeError, pow, complex(1, 2), "x", 3) +assert_raises(TypeError, pow, "x", complex(1, 2), 3) # __pos__ @@ -284,3 +288,8 @@ class complex_subclass(complex): assert repr(-788830060729777.2 + 2j) == "(-788830060729777.2+2j)" assert repr(complex(0.0, 1959276370239205.2)) == "1959276370239205.2j" assert repr(complex(-1818262230632059.2, 0.0)) == "(-1818262230632059.2+0j)" + +# Constant folding must preserve the distinction between real and complex zero. +assert repr(0j - 0j) == "0j" +assert repr((-0j) + 0.0) == "-0j" +assert repr(0.0 + (-0j)) == "-0j" diff --git a/extra_tests/snippets/builtin_dict.py b/extra_tests/snippets/builtin_dict.py index 5dca75b9b9d..3d7347a5041 100644 --- a/extra_tests/snippets/builtin_dict.py +++ b/extra_tests/snippets/builtin_dict.py @@ -378,6 +378,25 @@ def __eq__(self, other): assert_raises(StopIteration, next, it) assert it.__length_hint__() == 0 +# Reverse hints count live entries, including when storage has deleted slots. +for reverse_iter in ( + reversed, + lambda d: reversed(d.keys()), + lambda d: reversed(d.values()), + lambda d: reversed(d.items()), +): + d = {0: 0, 1: 1, 2: 2, 3: 3} + del d[1] + it = reverse_iter(d) + for remaining in (3, 2, 1): + assert it.__length_hint__() == remaining + next(it) + assert it.__length_hint__() == 0 + # Exhaustion is observed by next(), rather than the final successful yield. + d[4] = 4 + assert_raises(RuntimeError, next, it) + assert it.__length_hint__() == 0 + # Test dictionary unpacking with non-mapping objects # This should raise TypeError for non-mapping objects with assert_raises(TypeError) as cm: @@ -745,3 +764,406 @@ def __getitem__(self, key): hash(od.keys()) with assert_raises(TypeError): hash(od.items()) + + +# A TypeError raised while *comparing* keys (e.g. from a colliding key's +# __eq__) must propagate unchanged, not be rewritten as an unhashable-key +# error. Only genuine hashing failures get the dict-specific "unhashable" +# wording. +class BadEq: + def __hash__(self): + return 42 # fixed hash forces a collision + + def __eq__(self, other): + raise TypeError("nope") + + +bad = {} +bad[BadEq()] = 1 +with assert_raises(TypeError) as cm: + bad[BadEq()] # hashes fine (42), then compares against the colliding key +assert "nope" in str(cm.exception), str(cm.exception) +assert "dict key" not in str(cm.exception), ( + f"comparison error mislabeled as unhashable: {cm.exception}" +) + +# A genuinely unhashable key still reports the dict-specific message. +with assert_raises(TypeError) as cm: + {}[[]] +assert "as a dict key" in str(cm.exception), str(cm.exception) + +# The message reaches every insertion path, not just __setitem__: the +# constructor, update() and |= all go through the same wrapping. +for make in ( + lambda: dict([([], 1)]), + lambda: {}.update([([], 1)]), + lambda: {}.__ior__([([], 1)]), +): + with assert_raises(TypeError) as cm: + make() + assert "as a dict key" in str(cm.exception), str(cm.exception) + + +# The key is hashed once up front, so a __hash__ that fails only on its first +# call is still reported (a re-hash on the error path would let it escape). +class FlakyHash: + _calls = 0 + + def __hash__(self): + FlakyHash._calls += 1 + if FlakyHash._calls == 1: + raise TypeError("first call fails") + return 0 + + +with assert_raises(TypeError) as cm: + {}[FlakyHash()] +assert "as a dict key" in str(cm.exception), str(cm.exception) + + +# The type name is the fully qualified one, like CPython's %T. +def _make_nested(): + class Nested: + __hash__ = None + + return Nested + + +with assert_raises(TypeError) as cm: + {}[_make_nested()()] +assert "_make_nested..Nested" in str(cm.exception), str(cm.exception) + + +# A __hash__ raising a *subclass* of TypeError is left unchanged (CPython +# checks the exact type), so `except MySubclass` still catches it. +class MyTypeError(TypeError): + pass + + +class SubclassHash: + def __hash__(self): + raise MyTypeError("custom") + + +with assert_raises(MyTypeError) as cm: + {}[SubclassHash()] +assert "as a dict key" not in str(cm.exception), str(cm.exception) + + +# Every operation hashes the key exactly once (the hash is threaded into the +# inner map), so a __hash__ that would fail on a second call is never called +# twice. setdefault() and pop() went through their own lookup before. +class CountingHash: + calls = 0 + + def __hash__(self): + CountingHash.calls += 1 + if CountingHash.calls >= 2: + raise TypeError("must not hash twice") + return 7 + + +CountingHash.calls = 0 +{}.setdefault(CountingHash(), 1) +assert CountingHash.calls == 1, CountingHash.calls + +CountingHash.calls = 0 +with assert_raises(KeyError): + # A non-empty dict so the lookup must hash the key (CPython skips hashing + # entirely when popping from an empty dict). + {1: 1}.pop(CountingHash()) +assert CountingHash.calls == 1, CountingHash.calls + + +# frozendict as a namespace, beyond what CPython's own tests cover. +import builtins +import gc +import sys +import types +import unittest + + +class FrozenDictDescriptorTests(unittest.TestCase): + def test_unrelated_descriptors_cannot_mutate_or_access(self): + frozen = frozendict(protected=23) + for method, args in ( + (dict.__init__, ({"replacement": 8},)), + (dict.__setitem__, ("protected", 99)), + (dict.__delitem__, ("protected",)), + (dict.update, ({"replacement": 8},)), + (dict.clear, ()), + (dict.get, ("protected",)), + ): + with self.subTest(method=method), self.assertRaises(TypeError): + method(frozen, *args) + with self.assertRaises(TypeError): + frozendict.get({"protected": 23}, "protected") + self.assertEqual(frozen, {"protected": 23}) + for name in ( + "clear", + "update", + "pop", + "popitem", + "setdefault", + "__setitem__", + "__delitem__", + "__ior__", + ): + self.assertFalse(hasattr(frozen, name), name) + + +class FrozenGlobalsTests(unittest.TestCase): + def setUp(self): + self.ns = frozendict( + __builtins__=builtins.__dict__, + __name__="frozen_test", + answer=42, + sys=sys, + ) + + def test_eval_and_implicit_scope(self): + self.assertIs(eval("globals()", self.ns), self.ns) + self.assertIs(eval("locals()", self.ns), self.ns) + self.assertEqual(eval("eval('answer')", self.ns), 42) + self.assertEqual(eval("(lambda: answer)()", self.ns), 42) + + def test_function_and_materialized_frame(self): + local = {} + exec("def f():\n return sys._getframe(), globals(), answer\n", self.ns, local) + f = local["f"] + self.assertIs(f.__globals__, self.ns) + self.assertEqual(f.__module__, "frozen_test") + for _ in range(300): + frame, ns, answer = f() + self.assertIs(frame.f_globals, self.ns) + self.assertIs(ns, self.ns) + self.assertEqual(answer, 42) + gc.collect() + self.assertIs(frame.f_globals, self.ns) + + def test_generator_frames(self): + local = {} + exec( + "def gen():\n yield sys._getframe(), globals(), answer\n yield answer\n", + self.ns, + local, + ) + gen = local["gen"]() + self.assertIs(gen.gi_frame.f_globals, self.ns) + frame, ns, answer = next(gen) + self.assertIs(frame.f_globals, self.ns) + self.assertIs(ns, self.ns) + self.assertEqual(answer, 42) + self.assertEqual(next(gen), 42) + with self.assertRaises(StopIteration): + next(gen) + gc.collect() + self.assertIs(frame.f_globals, self.ns) + + def test_coroutine_frames(self): + local = {} + exec( + "async def coro():\n return sys._getframe(), globals(), answer\n", + self.ns, + local, + ) + coro = local["coro"]() + self.assertIs(coro.cr_frame.f_globals, self.ns) + with self.assertRaises(StopIteration) as stopped: + coro.send(None) + frame, ns, answer = stopped.exception.value + self.assertIs(frame.f_globals, self.ns) + self.assertIs(ns, self.ns) + self.assertEqual(answer, 42) + + def test_async_generator_frames(self): + local = {} + exec( + "async def agen():\n yield sys._getframe(), globals(), answer\n", + self.ns, + local, + ) + agen = local["agen"]() + self.assertIs(agen.ag_frame.f_globals, self.ns) + with self.assertRaises(StopIteration) as stopped: + agen.asend(None).send(None) + frame, ns, answer = stopped.exception.value + self.assertIs(frame.f_globals, self.ns) + self.assertIs(ns, self.ns) + self.assertEqual(answer, 42) + with self.assertRaises(StopIteration): + agen.aclose().send(None) + + def test_local_namespace_and_imports(self): + local = {} + exec( + "import math\nclass C:\n value = answer\ndef f():\n import math\n return math.sqrt(answer)\n", + self.ns, + local, + ) + self.assertEqual(local["C"].value, 42) + self.assertEqual(local["C"].__module__, "frozen_test") + self.assertEqual(local["f"](), local["math"].sqrt(42)) + self.assertNotIn("math", self.ns) + + def test_missing_builtins(self): + for func, source in [(eval, ""), (exec, "")]: + with self.assertRaises(TypeError) as caught: + func(source, frozendict()) + self.assertEqual( + str(caught.exception), + "cannot assign __builtins__ to frozendict globals", + ) + + def test_writes_and_deletes(self): + for source, error in [ + ("answer = 0", "'frozendict' object does not support item assignment"), + ( + "global answer; answer = 0", + "frozendict object does not support item assignment", + ), + ( + "global answer; del answer", + "frozendict object does not support item deletion", + ), + ( + "global missing; del missing", + "frozendict object does not support item deletion", + ), + ]: + with self.assertRaises(TypeError) as caught: + exec(source, self.ns) + self.assertEqual(str(caught.exception), error) + self.assertEqual(self.ns["answer"], 42) + with self.assertRaises(NameError): + exec("del answer", self.ns) + + def test_explicit_function_constructor_stays_dict_only(self): + with self.assertRaises(TypeError): + types.FunctionType((lambda: 42).__code__, self.ns) + + def test_subclass_name_and_global_lookup(self): + class F(frozendict): + def __getitem__(self, key): + if key == "answer": + return 81 + return super().__getitem__(key) + + ns = F(self.ns) + self.assertEqual(eval("answer", ns), 81) + self.assertEqual(eval("(lambda: answer)()", ns), 81) + self.assertEqual(eval("answer", ns, {}), 42) + + def test_subclass_function_metadata_reads_storage(self): + class F(frozendict): + def __getitem__(self, key): + if key == "__name__": + return "wrong_name" + if key == "__builtins__": + return {"len": lambda x: 99} + return super().__getitem__(key) + + ns = F(self.ns) + f = eval("lambda: len([])", ns) + self.assertEqual(f.__module__, "frozen_test") + self.assertIs(f.__globals__, ns) + self.assertEqual(f(), 0) + + def test_subclass_builtins_assignment_hook(self): + calls = [] + + class F(frozendict): + def __setitem__(self, key, value): + calls.append((key, value)) + + for operation, source, mode, expected in ( + (eval, "1", "eval", 1), + (exec, "pass", "exec", None), + ): + namespace = F() + calls.clear() + self.assertEqual( + operation(compile(source, "", mode), namespace), + expected, + ) + self.assertEqual(calls, [("__builtins__", builtins.__dict__)]) + self.assertNotIn("__builtins__", namespace) + calls.clear() + with self.assertRaisesRegex( + TypeError, "frozendict object does not support item assignment" + ): + operation(source, namespace) + self.assertEqual(calls, [("__builtins__", builtins.__dict__)]) + + def test_implicit_frozen_builtins_namespace_counts(self): + import _testinternalcapi + + function = eval( + "lambda: len(())", + frozendict(__builtins__=frozendict(len=len)), + ) + counts = _testinternalcapi.get_code_var_counts(function) + self.assertEqual( + counts["unbound"]["globals"], + {"total": 1, "numglobal": 0, "numbuiltin": 1, "numunknown": 0}, + ) + for argument in ("globalsns", "builtinsns"): + with self.assertRaises(TypeError): + _testinternalcapi.get_code_var_counts( + function, **{argument: frozendict()} + ) + + def test_warning_context_reads_frozen_storage(self): + import warnings + + class F(frozendict): + def __getitem__(self, key): + if key in ("__warningregistry__", "__name__"): + raise AssertionError("warning context must read stored entries") + return super().__getitem__(key) + + for has_registry in (False, True): + entries = dict(self.ns, warn=warnings.warn) + if has_registry: + entries["__warningregistry__"] = {} + function = eval("lambda: warn('probe')", F(entries)) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + if has_registry: + function() + self.assertEqual(len(caught), 1) + self.assertEqual(str(caught[0].message), "probe") + else: + with self.assertRaisesRegex( + TypeError, + "frozendict object does not support item assignment", + ): + function() + self.assertEqual(caught, []) + + def test_frozen_builtins(self): + ns = frozendict(__builtins__=frozendict({"len": len})) + self.assertEqual(eval("(lambda: len([1, 2]))()", ns), 2) + + def test_shared_code_does_not_keep_mutable_global_specialization(self): + code = compile("lambda: answer", "", "eval") + mutable = {"__builtins__": builtins.__dict__, "answer": 19} + f = eval(code, mutable) + for _ in range(300): + self.assertEqual(f(), 19) + frozen_f = eval(code, self.ns) + for _ in range(300): + self.assertEqual(frozen_f(), 42) + self.assertEqual(f(), 19) + mutable["answer"] = 23 + self.assertEqual(f(), 23) + self.assertEqual(frozen_f(), 42) + + +frozen_suite = unittest.TestSuite( + unittest.defaultTestLoader.loadTestsFromTestCase(case) + for case in (FrozenDictDescriptorTests, FrozenGlobalsTests) +) +frozen_result = unittest.TextTestRunner(verbosity=2).run(frozen_suite) +assert frozen_result.wasSuccessful() +assert not frozen_result.skipped diff --git a/extra_tests/snippets/builtin_enumerate.py b/extra_tests/snippets/builtin_enumerate.py index 0f107ea7aea..84de34c7340 100644 --- a/extra_tests/snippets/builtin_enumerate.py +++ b/extra_tests/snippets/builtin_enumerate.py @@ -1,3 +1,5 @@ +from testutils import TestFailingIter, assert_raises + assert list(enumerate(["a", "b", "c"])) == [(0, "a"), (1, "b"), (2, "c")] assert type(enumerate([])) == enumerate @@ -25,3 +27,11 @@ def __iter__(self): it = enumerate(Counter()) assert next(it) == (0, 1) assert next(it) == (1, 2) + + +# start and the argument count are checked before iter() is called +assert_raises(TypeError, enumerate, TestFailingIter(), {}) +assert_raises(TypeError, enumerate, TestFailingIter(), 0, 0) +assert_raises(TypeError, enumerate, TestFailingIter(), foo=1) +assert_raises(TypeError, enumerate, iterable=TestFailingIter(), start={}) +assert_raises(RuntimeError, enumerate, TestFailingIter(), 0) diff --git a/extra_tests/snippets/builtin_exceptions.py b/extra_tests/snippets/builtin_exceptions.py index 080294a3c8a..388beb42e07 100644 --- a/extra_tests/snippets/builtin_exceptions.py +++ b/extra_tests/snippets/builtin_exceptions.py @@ -410,3 +410,22 @@ class SubError(MyError): assert restored.args == ("m",) assert restored.name == "n" assert restored.path == "p" + + +# Same-named subclasses must not take the builtin's errno dispatch path. +def check_oserror_type_identity(): + import errno + + class OSError(builtins.OSError): + pass + + class RenamedError(builtins.OSError): + pass + + RenamedError.__name__ = "OSError" + for cls in (OSError, RenamedError): + for code in (errno.ENOENT, errno.EACCES): + assert type(cls(code, "message")) is cls + + +check_oserror_type_identity() diff --git a/extra_tests/snippets/builtin_format.py b/extra_tests/snippets/builtin_format.py index 920256c0dc5..8d314edbf7c 100644 --- a/extra_tests/snippets/builtin_format.py +++ b/extra_tests/snippets/builtin_format.py @@ -24,6 +24,12 @@ def test_zero_padding(): test_zero_padding() +assert format("x", "٥") == "x " +assert format(3, "٥d") == " 3" +assert format(3, "१२") == " 3" +assert format(1.5, "٨.٣f") == " 1.500" +assert_raises(ValueError, format, "x", "²") + try: format("result", "=8s") except ValueError as error: diff --git a/extra_tests/snippets/builtin_hash.py b/extra_tests/snippets/builtin_hash.py index d4bf1168323..f63de63dca4 100644 --- a/extra_tests/snippets/builtin_hash.py +++ b/extra_tests/snippets/builtin_hash.py @@ -20,7 +20,7 @@ def __hash__(self): return 1 << 63 -assert hash(Evil()) == 4 +assert hash(Evil()) == hash(1 << 63) with assert_raises(TypeError): hash({}) @@ -35,10 +35,10 @@ def __hash__(self): # slot dispatch is what recurses, so that is where the depth is checked. if sys.implementation.name == "rustpython": - # Deep enough to reach the native stack guard; CPython, which also runs - # this snippet, dies on the same value. + # Deep enough to reach the native stack guard in release; CPython, which + # also runs this snippet, dies on the same value. deep_tuple = () - for _ in range(100_000): + for _ in range(500_000): deep_tuple = (deep_tuple,) with assert_raises(RecursionError): hash(deep_tuple) @@ -74,3 +74,17 @@ class Unhashable: test_unhashable_names_the_type_as_written() + + +# The minimum signed hash must probe a dict/set without signed abs overflow. +class MinimumHash: + def __hash__(self): + return -sys.maxsize - 1 + + +keys = [MinimumHash() for _ in range(20)] +values = {key: index for index, key in enumerate(keys)} +members = set(keys) +for index, key in enumerate(keys): + assert values[key] == index + assert key in members diff --git a/extra_tests/snippets/builtin_int.py b/extra_tests/snippets/builtin_int.py index d887c9a793d..e1f979628cb 100644 --- a/extra_tests/snippets/builtin_int.py +++ b/extra_tests/snippets/builtin_int.py @@ -396,6 +396,28 @@ class SubInt(int): assert format(huge, "o") assert format(huge, "b") + # The bit-length estimate can overstate the decimal length by one. Even + # values whose leading digit is 9 must round-trip at the configured limit. + for max_digits in (640, 4300, 5000): + sys.set_int_max_str_digits(max_digits) + digits = "9" * max_digits + boundary = int(digits) + assert str(boundary) == digits + assert repr(boundary) == digits + assert format(boundary, "d") == digits + assert format(-boundary, "d") == "-" + digits + assert "%d" % boundary == digits + assert b"%d" % boundary == digits.encode() + assert format(boundary, ",d").replace(",", "") == digits + assert f"{boundary}" == digits + if max_digits == 4300: + assert len(str(2**14284)) == 4300 + + for too_many in (10**max_digits, -(10**max_digits)): + for formatter in (str, repr, lambda n: format(n, "d"), lambda n: "%d" % n): + with assert_raises(ValueError): + formatter(too_many) + # Limit disabled: no check. sys.set_int_max_str_digits(0) assert str(huge) @@ -403,16 +425,56 @@ class SubInt(int): sys.set_int_max_str_digits(_orig_limit) # to_bytes is handed the length to allocate, so one that cannot be satisfied -# must raise. Zero and non-zero take different paths to the same buffer. +# must raise. A length outside Py_ssize_t overflows before allocation. +# Zero and non-zero take different paths to the same buffer. for value in (0, 1, -1): - with assert_raises(MemoryError): + with assert_raises(MemoryError if sys.maxsize >= 2**60 else OverflowError): value.to_bytes(2**60, "big", signed=True) -# Results too large to allocate raise MemoryError instead of aborting -assert_raises(MemoryError, lambda: 2**62 << 2**62) -assert_raises(MemoryError, lambda: 1 << 9223372036854775770) +# A shift beyond the platform's digit-count range overflows before allocation. +assert_raises( + MemoryError + if sys.maxsize * sys.int_info.bits_per_digit >= 2**62 + else OverflowError, + lambda: 2**62 << 2**62, +) +assert_raises( + MemoryError + if sys.maxsize * sys.int_info.bits_per_digit >= 9223372036854775770 + else OverflowError, + lambda: 1 << 9223372036854775770, +) assert_raises(OverflowError, lambda: 1 << 9223372036854775771) assert_raises(OverflowError, lambda: 1 << 2**64) assert_raises(OverflowError, lambda: -5 << 10**30) assert 0 << 2**64 == 0 assert pow(1, 2**63) == 1 and pow(-1, 2**63 + 1) == -1 and pow(0, 2**63) == 0 + +# Check the allocation boundary itself, including a carry digit for a partial +# shift and the digits already occupied by the left operand. CPython's 32-bit +# PyLong header has three pointer-sized fields before its u32 digit array. +_digit_bits = sys.int_info.bits_per_digit +_max_digits = ( + (sys.maxsize - 12) // sys.int_info.sizeof_digit + if sys.maxsize < 2**32 + else (2**63 - 2) // _digit_bits +) +for _base in (1, -1, 2**30, -(2**30), 2**62, -(2**62)): + _base_digits = (_base.bit_length() + _digit_bits - 1) // _digit_bits + _last_shift = (_max_digits - _base_digits) * _digit_bits + # On 32-bit CPython this could actually allocate approximately 2 GiB. + if sys.maxsize > 2**32: + with assert_raises(MemoryError): + _base << _last_shift + for _shift in (_last_shift + 1, _last_shift + _digit_bits, 2**63, 2**128): + with assert_raises(OverflowError) as _error: + _base << _shift + assert str(_error.exception) == "too many digits in integer" + +# Check the negative-count message even when zero or overflow could otherwise +# short-circuit the shift. +for _shift in (_max_digits * _digit_bits, 2**128): + for _base in (0, 1, -1): + with assert_raises(ValueError) as _error: + _base << -_shift + assert str(_error.exception) == "negative shift count" diff --git a/extra_tests/snippets/builtin_list.py b/extra_tests/snippets/builtin_list.py index 189f794774b..3e8e3c76681 100644 --- a/extra_tests/snippets/builtin_list.py +++ b/extra_tests/snippets/builtin_list.py @@ -496,7 +496,7 @@ def set_index_out_of_bounds_low(): assert x == zz -# A huge length hint is a MemoryError, not an aborted process +# A representable huge length hint reaches allocation; a wider one overflows. class HugeLen: def __len__(self): return 2**62 @@ -508,7 +508,7 @@ def __getitem__(self, i): slice_target = [3, 1, 2] -with assert_raises(MemoryError): +with assert_raises(MemoryError if sys.maxsize >= 2**62 else OverflowError): slice_target[1::-1] = HugeLen() @@ -1388,3 +1388,22 @@ def failing_source(): test_slice_replacement_lifetime() + + +def test_subscript_typeerror_message(): + def message(index): + try: + [0, 1, 2][index] + except TypeError as err: + return str(err) + raise AssertionError("TypeError was not raised") + + assert message("x") == "list indices must be integers or slices, not str" + + Long = type("A" * 250, (), {}) + assert message(Long()) == "list indices must be integers or slices, not {}".format( + "A" * 200 + ) + + +test_subscript_typeerror_message() diff --git a/extra_tests/snippets/builtin_mappingproxy.py b/extra_tests/snippets/builtin_mappingproxy.py index fdd653c408d..8adf4d7e9bb 100644 --- a/extra_tests/snippets/builtin_mappingproxy.py +++ b/extra_tests/snippets/builtin_mappingproxy.py @@ -23,3 +23,64 @@ def b(): assert A.__dict__.get("not here", "default") == "default" assert A.__dict__.get("a", "default") is A.a assert A.__dict__.get("not here") is None + + +# A mappingproxy preserves arbitrary equality-comparison results unchanged. +def check_mappingproxy_comparison_results(): + import operator + from types import MappingProxyType + + from testutils import assert_raises + + class Result: + def __bool__(self): + raise AssertionError("comparison result must not be coerced to bool") + + result = Result() + calls = [] + + def compare(name): + def method(self, other): + calls.append(name) + return result + + return method + + class Compared: + __eq__ = compare("eq") + __ne__ = compare("ne") + __lt__ = compare("lt") + __le__ = compare("le") + __gt__ = compare("gt") + __ge__ = compare("ge") + + class CustomMapping(Compared, dict): + pass + + for operation, reflected in ( + (operator.eq, "eq"), + (operator.ne, "ne"), + ): + calls.clear() + assert operation(MappingProxyType(CustomMapping()), {}) is result + assert calls == [operation.__name__], calls + calls.clear() + assert operation(MappingProxyType({}), Compared()) is result + assert calls == [reflected], calls + + for operation, reflected in ( + (operator.lt, "gt"), + (operator.le, "ge"), + (operator.gt, "lt"), + (operator.ge, "le"), + ): + calls.clear() + with assert_raises(TypeError): + operation(MappingProxyType(CustomMapping()), {}) + assert calls == [], calls + calls.clear() + assert operation(MappingProxyType({}), Compared()) is result + assert calls == [reflected], calls + + +check_mappingproxy_comparison_results() diff --git a/extra_tests/snippets/builtin_memoryview.py b/extra_tests/snippets/builtin_memoryview.py index ef28ffc3d79..6e8bdabcf3c 100644 --- a/extra_tests/snippets/builtin_memoryview.py +++ b/extra_tests/snippets/builtin_memoryview.py @@ -399,7 +399,7 @@ def test_cast_rejects_non_native_format(): memoryview(b"").cast(fmt) raise AssertionError(f"cast accepted {fmt!r}") except ValueError as e: - assert "native single character format" in str(e), e + assert "native format" in str(e), e assert memoryview(bytes(8)).cast("@i").itemsize == 4 @@ -733,6 +733,104 @@ def test_index_error_names_the_dimension(): test_index_error_names_the_dimension() +def test_index_clinic_bounds_and_reflected_comparisons(): + view = memoryview(b"abcd") + assert view.index(97, -(1 << 100), 1 << 100) == 0 + + class HugeIndex: + def __index__(self): + return 1 << 100 + + assert view.index(97, 0, HugeIndex()) == 0 + for args, expected, message in ( + ((0, 1 << 100), ValueError, "memoryview.index(x): x not found"), + ( + (0, None), + TypeError, + "slice indices must be integers or have an __index__ method", + ), + ): + with assert_raises(expected) as caught: + view.index(*args) + assert str(caught.exception) == message + + class Reflected: + def __eq__(self, other): + return "equal" + + def __ne__(self, other): + return "not equal" + + def __gt__(self, other): + return "greater" + + other = Reflected() + assert (view == other) == "equal" + assert (view != other) == "not equal" + assert (view < other) == "greater" + + +test_index_clinic_bounds_and_reflected_comparisons() + + +def test_cast_clinic_validation_before_conversion(): + view = memoryview(b"abcd") + for args, keywords, message in ( + ((1,), {}, "cast() argument 'format' must be str, not int"), + ((None,), {}, "cast() argument 'format' must be str, not None"), + ((1,), {"unknown": 1}, "cast() got an unexpected keyword argument 'unknown'"), + ( + (1,), + {"format": "B"}, + "argument for cast() given by name ('format') and position (1)", + ), + ): + with assert_raises(TypeError) as caught: + view.cast(*args, **keywords) + assert str(caught.exception) == message + + view.release() + with assert_raises(TypeError) as caught: + view.cast(1) + assert str(caught.exception) == "cast() argument 'format' must be str, not int" + + +test_cast_clinic_validation_before_conversion() + + +def test_half_rounding_and_signaling_payloads(): + import math + import struct + import sys + + view = memoryview(bytearray(2)).cast("e") + # The bits below binary32 precision still determine which side of an + # exactly representable binary16 midpoint a binary64 value falls on. + view[0] = math.nextafter(1.00048828125, 2.0) + assert view.tobytes() == (0x3C01).to_bytes(2, sys.byteorder) + + for half_bits in (0x7C01, 0x7DFF, 0xFC01, 0xFDFF): + raw = half_bits.to_bytes(2, sys.byteorder) + value = memoryview(raw).cast("e")[0] + expected = ( + ((half_bits & 0x8000) << 48) + | 0x7FF0000000000000 + | ((half_bits & 0x3FF) << 42) + ) + assert struct.pack("=d", value) == expected.to_bytes(8, sys.byteorder) + view[0] = value + assert view.tobytes() == raw + + raw = (0x7F800001).to_bytes(4, sys.byteorder) + bytes(4) + value = memoryview(raw).cast("Zf")[0] + assert struct.pack("=d", value.real) == (0x7FF0000020000000).to_bytes( + 8, sys.byteorder + ) + + +test_half_rounding_and_signaling_payloads() + + def test_release_refuses_while_exported(): ba = bytearray(b"abc") mv = memoryview(ba) @@ -961,3 +1059,107 @@ def __bool__(self): test_bool_format_keeps_its_own_error() + + +def test_cast_clinic_type_name_bytes(): + import struct + + view = memoryview(b"a") + for value, expected in ( + (type("A" * 70, (), {})(), "A" * 50), + (type("é" * 30, (), {})(), "é" * 25), + (type("😀" * 20, (), {})(), "😀" * 12), + (struct.Struct("B"), "_struct.Struct"), + ): + try: + view.cast(value) + except TypeError as error: + assert str(error) == ( + "cast() argument 'format' must be str, not " + expected + ), error + else: + raise AssertionError("accepted a non-string format") + + +test_cast_clinic_type_name_bytes() + + +def test_scalar_assignment_keeps_temporary_value_until_write(): + import struct + + for fmt, method, converted in ( + ("d", "__float__", 2.5), + ("f", "__float__", 2.5), + ("e", "__float__", 2.5), + ("Zf", "__complex__", 1 + 2j), + ("Zd", "__complex__", 1 + 2j), + ("?", "__bool__", True), + ): + data = bytearray(struct.calcsize(fmt)) + view = memoryview(data).cast(fmt) + seen = [] + + def convert(self): + return converted + + def finalize(self): + seen.append(view[0]) + view.release() + + value_type = type("Temporary", (), {method: convert, "__del__": finalize}) + view[0] = value_type() + assert seen == [converted], (fmt, seen) + assert struct.unpack(fmt, data) == (converted,), fmt + + +test_scalar_assignment_keeps_temporary_value_until_write() + + +def test_index_keeps_temporary_bounds_until_search_finishes(): + for which in ("start", "stop"): + view = memoryview(b"x") + events = [] + + class Bound: + def __index__(self): + events.append("index") + return 0 if which == "start" else 1 + + def __del__(self): + events.append("del") + view.release() + + result = ( + view.index(120, Bound()) + if which == "start" + else view.index(120, 0, Bound()) + ) + assert result == 0 + assert events == ["index", "del"], events + + +test_index_keeps_temporary_bounds_until_search_finishes() + + +def test_buffered_writer_can_compare_its_buffer_views(): + import io + + class Raw(io.RawIOBase): + def writable(self): + return True + + def write(self, view): + assert view == view[:] + scalar = view[:1].cast("B", []) + assert scalar == scalar.cast("B").cast("B", []) + return len(view) + + stream = io.BufferedWriter(Raw(), buffer_size=4) + assert stream.write(b"abc") == 3 + stream.flush() + assert stream.write(b"abcdef") == 6 + stream.flush() + stream.close() + + +test_buffered_writer_can_compare_its_buffer_views() diff --git a/extra_tests/snippets/builtin_object.py b/extra_tests/snippets/builtin_object.py index 0b90c44a320..66e5dcf831b 100644 --- a/extra_tests/snippets/builtin_object.py +++ b/extra_tests/snippets/builtin_object.py @@ -161,3 +161,93 @@ def __getattr__(self, name): with assert_raises(ValueError) as caught: RaisingAttributeHook().absent assert caught.exception.__context__ is outer + + +# The descriptor slot calls the raw __get__ attribute without binding it first. +class RawGetDescriptor: + __get__ = staticmethod(lambda *args: args) + + +class RawGetOwner: + value = RawGetDescriptor() + + +raw_descriptor = vars(RawGetOwner)["value"] +raw_instance = RawGetOwner() +assert raw_instance.value == (raw_descriptor, raw_instance, RawGetOwner) +assert RawGetOwner.value == (raw_descriptor, None, RawGetOwner) + + +class CallableGet: + def __get__(self, instance, owner): + raise AssertionError("__get__ must not be bound before the slot call") + + def __call__(self, *args): + return args + + +RawGetDescriptor.__get__ = CallableGet() +assert raw_instance.value == (raw_descriptor, raw_instance, RawGetOwner) +RawGetDescriptor.__get__ = classmethod(lambda *args: args) +with assert_raises(TypeError): + raw_instance.value +RawGetDescriptor.__get__ = lambda self, instance, owner: (self, instance, owner) +assert raw_instance.value == (raw_descriptor, raw_instance, RawGetOwner) + + +# object.__getstate__ reads names from a cached __slotnames__ list +class NonStrSlotName: + __slotnames__ = [1] + + +with assert_raises(TypeError) as caught: + NonStrSlotName().__getstate__() +assert str(caught.exception) == "attribute name must be string, not 'int'" + + +class GrowingSlotNames: + __slotnames__ = ["a", "b"] + + def __getattr__(self, name): + if name == "a": + GrowingSlotNames.__slotnames__.append("c") + return 1 + raise AttributeError(name) + + +with assert_raises(RuntimeError): + GrowingSlotNames().__getstate__() + + +class RaisingSlot: + __slotnames__ = ["x"] + + def __getattr__(self, name): + raise ValueError("boom") + + +with assert_raises(ValueError): + RaisingSlot().__getstate__() + + +class MissingSlot: + __slotnames__ = ["x", "y"] + y = 2 + + +assert MissingSlot().__getstate__() == (None, {"y": 2}) + + +# deleting __getattr__ from a base must not drop a subclass's __getattribute__ +class _GABase: + pass + + +class _GAProxy(_GABase): + def __getattribute__(self, name): + return "hooked" + + +_GABase.__getattr__ = lambda self, name: "fallback" +del _GABase.__getattr__ +assert _GAProxy().x == "hooked" diff --git a/extra_tests/snippets/builtin_pow.py b/extra_tests/snippets/builtin_pow.py index 3ba481faa73..e391487617c 100644 --- a/extra_tests/snippets/builtin_pow.py +++ b/extra_tests/snippets/builtin_pow.py @@ -182,3 +182,12 @@ def test_bug705231(): tests = [f for name, f in locals().items() if name.startswith("test_")] for f in tests: f() + + +class PowOnlyAsModulus: + def __pow__(self, other, mod=None): + return "called" + + +assert_raises(TypeError, pow, None, None, PowOnlyAsModulus()) +assert_raises(TypeError, pow, "a", 2, PowOnlyAsModulus()) diff --git a/extra_tests/snippets/builtin_round.py b/extra_tests/snippets/builtin_round.py index 83725420a40..e41277fb589 100644 --- a/extra_tests/snippets/builtin_round.py +++ b/extra_tests/snippets/builtin_round.py @@ -111,3 +111,32 @@ class MyInt(int): assert type(round(MyInt(5), 2)) is int # A negative ndigits already produced a fresh exact int. assert type(round(MyInt(15), -1)) is int + + +# round() passes ndigits to __round__ unchanged, like CPython's builtin_round_impl(). +class Echo: + def __round__(self, *args): + return args + + +assert round(Echo(), []) == ([],) +assert round(Echo(), 1.5) == (1.5,) +assert type(round(Echo(), True)[0]) is bool + + +class Index: + def __index__(self): + return -1 + + +assert type(round(Echo(), Index())[0]) is Index + +# int.__round__ and float.__round__ apply __index__ to ndigits themselves. +assert round(15, Index()) == 20 +assert round(1.25, Index()) == 0.0 +assert (15).__round__(Index()) == 20 +assert (1.25).__round__(Index()) == 0.0 +with assert_raises(TypeError): + (15).__round__(1.0) +with assert_raises(TypeError): + (1.25).__round__([]) diff --git a/extra_tests/snippets/builtin_set.py b/extra_tests/snippets/builtin_set.py index 8e96a095962..a2cf3066099 100644 --- a/extra_tests/snippets/builtin_set.py +++ b/extra_tests/snippets/builtin_set.py @@ -1,3 +1,5 @@ +import operator + from testutils import assert_raises assert set([1, 2]) == set([1, 2]) @@ -496,6 +498,56 @@ def __iter__(self): assert_raises(RuntimeError, set_type([3]).isdisjoint, subclass) +# A disabled iterator does not disable the predicates' native set paths. +for set_type in (set, frozenset): + + class DisabledIterator(set_type): + __iter__ = None + + subclass = DisabledIterator([1]) + assert set_type([1]).issubset(subclass) + assert set_type([1, 2]).issuperset(subclass) + assert not subclass.isdisjoint(subclass) + empty_subclass = DisabledIterator() + assert empty_subclass.isdisjoint(empty_subclass) + assert_raises(TypeError, set_type([2]).isdisjoint, subclass) + + +class InvalidPredicateIterator: + def __iter__(self): + return [] + + +# Typed bindings must preserve both binder errors and GetIter validation. +with assert_raises(TypeError) as invalid_iterator: + iter(InvalidPredicateIterator()) +for set_type in (set, frozenset): + for method_name in ("issubset", "issuperset", "isdisjoint"): + predicate = getattr(set_type([1]), method_name) + with assert_raises(TypeError) as rejected_keyword: + predicate(42, unexpected=True) + assert "takes no keyword arguments" in str(rejected_keyword.exception) + with assert_raises(TypeError) as rejected_iterator: + predicate(InvalidPredicateIterator()) + assert str(rejected_iterator.exception) == str(invalid_iterator.exception) + + +# A temporary source remains alive through issubset's final size comparison. +subset_target = {1} + + +class TemporarySubsetSource: + def __iter__(self): + return iter([1]) + + def __del__(self): + subset_target.clear() + + +assert subset_target.issubset(TemporarySubsetSource()) +assert subset_target == set() + + # Intersections retain the key from the smaller operand, or RHS on a tie. small_key = float("1") small = {small_key} @@ -706,3 +758,42 @@ def __del__(self): intersection_target.intersection_update({1}) assert not intersection_target assert intersection_events == [True, True] + + +# Unsupported right operands must reach their reflected set operation. +keys = {2: None, 3: None}.keys() +for method, operation, expected in ( + (set.__ior__, operator.ior, {1, 2, 3}), + (set.__iand__, operator.iand, {2}), + (set.__isub__, operator.isub, {1}), + (set.__ixor__, operator.ixor, {1, 3}), +): + source = {1, 2} + assert method(source, keys) is NotImplemented + assert operation(source, keys) == expected + assert source == {1, 2} + + +# Predicates on an iterable hash its elements; only membership coerces a set. +for predicate in (set().issuperset, frozenset().isdisjoint): + with assert_raises(TypeError): + predicate([{1}]) + + +# A subclass named like the builtin still needs the subclass repr wrapper. +SetNamedSet = type("set", (set,), {}) +assert repr(SetNamedSet([1])) == "set({1})" +assert repr(SetNamedSet()) == "set()" +assert repr({1}) == "{1}" + + +class RenamedSet(set): + pass + + +renamed_set = RenamedSet([1]) +assert repr(renamed_set) == "RenamedSet({1})" +RenamedSet.__name__ = "set" +assert repr(renamed_set) == "set({1})" +RenamedSet.__name__ = "RenamedAgain" +assert repr(renamed_set) == "RenamedAgain({1})" diff --git a/extra_tests/snippets/builtin_signature.py b/extra_tests/snippets/builtin_signature.py index be0d53e9e3c..dc7e9a57ea9 100644 --- a/extra_tests/snippets/builtin_signature.py +++ b/extra_tests/snippets/builtin_signature.py @@ -1,5 +1,9 @@ +import builtins import inspect import os +import sys + +from testutils import assert_raises # __text_signature__ is generated from the Rust parameter list, so it must not # describe parameters the function does not actually take, and must mark the @@ -19,7 +23,7 @@ raise AssertionError("len() should not accept keyword arguments") assert str(inspect.signature(len)) == "(obj, /)" -assert str(inspect.signature(abs)) == "(x, /)" +assert str(inspect.signature(abs)) == "(number, /)" assert str(inspect.signature(hash)) == "(obj, /)" assert str(inspect.signature(chr)) == "(i, /)" assert str(inspect.signature(callable)) == "(obj, /)" @@ -28,8 +32,21 @@ inspect.signature(len).parameters["obj"].kind == inspect.Parameter.POSITIONAL_ONLY ) -# *args/**kwargs cannot be followed by `/`. The parameter names themselves still -# differ from CPython here, which is out of scope. +# *args/**kwargs cannot be followed by `/`; collector names also match Clinic. +assert breakpoint.__text_signature__ == "($module, /, *args, **kws)" +assert str(inspect.signature(breakpoint)) == "(*args, **kws)" +# Collector names are descriptive, not reserved keyword parameters. +import sys + +original_breakpointhook = sys.breakpointhook +try: + sys.breakpointhook = lambda *args, **kws: (args, kws) + assert breakpoint(1, args=2, kws=3, kwargs=4) == ( + (1,), + {"args": 2, "kws": 3, "kwargs": 4}, + ) +finally: + sys.breakpointhook = original_breakpointhook breakpoint_kinds = [p.kind for p in inspect.signature(breakpoint).parameters.values()] assert breakpoint_kinds == [ inspect.Parameter.VAR_POSITIONAL, @@ -37,7 +54,7 @@ ], breakpoint_kinds # Parameter names follow CPython, so signatures are directly comparable. -assert str(inspect.signature(bin)) == "(number, /)" +assert str(inspect.signature(bin)) == "(integer, /)" assert str(inspect.signature(ord)) == "(character, /)" assert str(inspect.signature(divmod)) == "(x, y, /)" assert str(inspect.signature(hasattr)) == "(obj, name, /)" @@ -58,9 +75,667 @@ assert str(inspect.signature([].__dir__)) == "()" assert str(inspect.signature(float.fromhex)) == "(string, /)" +import _socket + +if hasattr(_socket.socket, "sendmsg"): + # CPython 3.15.0 used unrepresentable defaults; 3.15.1 corrected them. + if sys.implementation.name == "cpython" and sys.version_info[:3] == (3, 15, 0): + assert _socket.socket.sendmsg.__text_signature__ == ( + "($self, buffers, ancdata=, flags=0,\n" + " address=, /)" + ) + assert_raises(ValueError, inspect.signature, _socket.socket.sendmsg) + else: + assert _socket.socket.sendmsg.__text_signature__ == ( + "($self, buffers, ancdata=(), flags=0, address=None, /)" + ) + assert str(inspect.signature(_socket.socket.sendmsg)) == ( + "(self, buffers, ancdata=(), flags=0, address=None, /)" + ) + # Functions whose arguments come from a FromArgs struct report the struct's # parameters. assert round.__text_signature__ == "($module, /, number, ndigits=None)" assert sum.__text_signature__ == "($module, iterable, /, start=0)" assert str(inspect.signature(round)) == "(number, ndigits=None)" assert str(inspect.signature(sum)) == "(iterable, /, start=0)" + +# A keyword-only argument between two positional ones used to put `/` after +# `*`, which inspect cannot parse. Arguments are ordered like CPython's, so +# path and mode take keywords. Windows renders follow_symlinks differently. +if hasattr(os, "chmod"): + chmod_signature = os.chmod.__text_signature__ + assert chmod_signature.startswith("($module, /, path, mode, *, dir_fd=None"), ( + chmod_signature + ) + +# Omitted arguments keep their runtime sentinels while displaying CPython 3.15's +# public defaults. In particular, an omitted compression dictionary is not None. +import binascii +import signal +import zlib + +for f in (binascii.hexlify, binascii.b2a_hex): + assert f.__text_signature__ == ( + "($module, /, data, sep=, bytes_per_sep=1)" + ) + assert f(b"abc", b":") == f(b"abc", b":", 1) == b"61:62:63" + +if hasattr(signal, "setitimer"): + assert signal.setitimer.__text_signature__ == ( + "($module, which, seconds, interval=0.0, /)" + ) + assert inspect.signature(signal.setitimer).parameters["interval"].default == 0.0 + +assert " ".join(zlib.compressobj.__text_signature__.split()) == ( + "($module, /, level=Z_DEFAULT_COMPRESSION, method=DEFLATED, " + "wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, " + "strategy=Z_DEFAULT_STRATEGY, zdict=)" +) +try: + zlib.compressobj(zdict=None) +except TypeError: + pass +else: + raise AssertionError("None is not an omitted compression dictionary") + +assert zlib._ZlibDecompressor.__text_signature__ == "(wbits=MAX_WBITS, zdict=b'')" +assert ( + inspect.signature(zlib._ZlibDecompressor).parameters["wbits"].default + == zlib.MAX_WBITS +) +assert zlib._ZlibDecompressor().decompress(zlib.compress(b"signature defaults")) == ( + b"signature defaults" +) + +# Clinic keeps platform-dependent defaults symbolic rather than hard-coding +# the 64-bit value. inspect resolves the symbol for the running interpreter. +import sys + +for sequence_type in (list, tuple): + assert sequence_type.index.__text_signature__ == ( + "($self, value, start=0, stop=sys.maxsize, /)" + ) + index_signature = inspect.signature(sequence_type.index) + assert index_signature.parameters["stop"].default == sys.maxsize + +assert str.maketrans.__text_signature__ == ( + "(x, y=, z=, /)" +) + +if hasattr(os, "utime"): + # ns is deliberately unrepresentable; only times has a None default. + assert " ".join(os.utime.__text_signature__.split()) == ( + "($module, /, path, times=None, *, ns=, " + "dir_fd=None, follow_symlinks=True)" + ) + +# Buffered stream constructors retain Clinic's symbolic module default. +import _io + +for stream_type in (_io.BufferedReader, _io.BufferedWriter, _io.BufferedRandom): + assert stream_type.__text_signature__ == "(raw, buffer_size=DEFAULT_BUFFER_SIZE)" + assert ( + inspect.signature(stream_type).parameters["buffer_size"].default + == _io.DEFAULT_BUFFER_SIZE + ) + +assert _io.BufferedRWPair.__text_signature__ == ( + "(reader, writer, buffer_size=DEFAULT_BUFFER_SIZE, /)" +) +assert ( + inspect.signature(_io.BufferedRWPair).parameters["buffer_size"].default + == _io.DEFAULT_BUFFER_SIZE +) + +# Module defaults retain their symbolic spelling without changing conversion. +import _codecs +import _imp +import _warnings +import array +import faulthandler +import marshal +import time + +assert array.array.index.__text_signature__ == ( + "($self, v, start=0, stop=sys.maxsize, /)" +) +assert _codecs.charmap_decode.__text_signature__ == ( + "($module, data, errors=None, mapping=None, /)" +) +assert _imp.create_dynamic.__text_signature__ == ( + "($module, spec, file=, /)" +) +assert " ".join(_warnings.warn_explicit.__text_signature__.split()) == ( + "($module, /, message, category, filename, lineno, " + "module=, registry=None, module_globals=None, source=None)" +) +assert marshal.dumps.__text_signature__ == ( + "($module, value, version=version, /, *, allow_code=True)" +) +assert marshal.dump.__text_signature__ == ( + "($module, value, file, version=version, /, *, allow_code=True)" +) +assert inspect.signature(marshal.dumps).parameters["version"].default == marshal.version +assert faulthandler._sigsegv.__text_signature__ == ("($module, release_gil=False, /)") +assert " ".join(faulthandler.dump_traceback.__text_signature__.split()) == ( + "($module, /, file=sys.stderr, all_threads=True, *, max_threads=100)" +) +if hasattr(faulthandler, "dump_c_stack"): + assert ( + faulthandler.dump_c_stack.__text_signature__ == "($module, /, file=sys.stderr)" + ) + +try: + import _blake2 +except ImportError: + pass +else: + for hash_type in (_blake2.blake2b, _blake2.blake2s): + assert ( + "digest_size=_blake2." + hash_type.__name__ + ".MAX_DIGEST_SIZE" + in hash_type.__text_signature__ + ) + +try: + import select +except ImportError: + pass +else: + if hasattr(select, "epoll"): + assert " ".join(select.epoll.register.__text_signature__.split()) == ( + "($self, /, fd, eventmask=select.EPOLLIN | select.EPOLLPRI | select.EPOLLOUT)" + ) + +for sequence_type in (os.stat_result, os.terminal_size, time.struct_time): + assert sequence_type.__getitem__.__text_signature__ == "($self, key, /)" + +# Symbolic defaults and omitted callback contexts carry distinct introspection +# metadata even when the Rust-side converter is shared with other callables. +import _asyncio +import _io + +for _future_type in (_asyncio.Future, _asyncio.Task): + assert _future_type.add_done_callback.__text_signature__ == ( + "($self, fn, /, *, context=)" + ) + try: + inspect.signature(_future_type.add_done_callback) + except ValueError: + pass + else: + raise AssertionError("an omitted context is not a representable default") + +assert _io._IOBase.seek.__text_signature__ == ("($self, offset, whence=os.SEEK_SET, /)") +assert _io.TextIOWrapper.seek.__text_signature__ == ( + "($self, cookie, whence=os.SEEK_SET, /)" +) +assert inspect.signature(_io.TextIOWrapper.seek).parameters["whence"].default == ( + os.SEEK_SET +) +# Other seek methods keep their literal defaults. +assert _io.BytesIO.seek.__text_signature__ == "($self, pos, whence=0, /)" +assert _io.BufferedReader.seek.__text_signature__ == "($self, target, whence=0, /)" + +# CPython's tp_new_wrapper hides its bound defining type, but still requires +# the caller to supply the subtype as the first positional argument. The raw +# signature intentionally has no slash, unlike other slot descriptors. +new_wrapper_types = ( + "object", + "type", + "bool", + "bytearray", + "bytes", + "complex", + "dict", + "float", + "frozenset", + "int", + "list", + "memoryview", + "range", + "set", + "slice", + "str", + "tuple", + "BaseException", + "Exception", + "ArithmeticError", + "AssertionError", + "AttributeError", + "EOFError", + "ImportError", + "IndexError", + "KeyError", + "LookupError", + "MemoryError", + "NameError", + "NotImplementedError", + "OSError", + "OverflowError", + "ReferenceError", + "RuntimeError", + "StopIteration", + "SyntaxError", + "SystemError", + "SystemExit", + "TypeError", + "ValueError", + "ZeroDivisionError", + "Warning", + "UserWarning", + "RuntimeWarning", + "DeprecationWarning", + "FutureWarning", + "UnicodeError", +) +for type_name in new_wrapper_types: + cls = getattr(builtins, type_name) + new = cls.__new__ + assert new.__text_signature__ == "($type, *args, **kwargs)", type_name + assert str(inspect.signature(new)) == "(*args, **kwargs)", type_name + assert isinstance(new.__self__, type), type_name + + +class NewList(list): + pass + + +assert NewList.__new__ is list.__new__ +assert NewList.__new__.__self__ is list +assert dict.__new__(dict, answer=42) == {} +assert int.__new__(int, "10", base=2) == 2 +# The hidden $type in the raw signature does not make the explicit subtype +# keyword-bindable. Do not silently alter dispatch when matching its spelling. +for new, kwargs in ((object.__new__, {"type": object}), (list.__new__, {"cls": list})): + try: + new(**kwargs) + except TypeError: + pass + else: + raise AssertionError("the subtype must remain positional") +# CPython falls back to METH_NOARGS/METH_O signatures for these non-Clinic +# functions. The hidden marker is $self even though they bind a module. +import importlib + +flags_signatures = { + "_ast": { + "_is_abstract": "($self, object, /)", + }, + "_codecs_cn": { + "getcodec": "($self, object, /)", + }, + "_codecs_hk": { + "getcodec": "($self, object, /)", + }, + "_codecs_iso2022": { + "getcodec": "($self, object, /)", + }, + "_codecs_jp": { + "getcodec": "($self, object, /)", + }, + "_codecs_kr": { + "getcodec": "($self, object, /)", + }, + "_codecs_tw": { + "getcodec": "($self, object, /)", + }, + "_ctypes": { + "Py_DECREF": "($self, object, /)", + "Py_INCREF": "($self, object, /)", + "alignment": "($self, object, /)", + "buffer_info": "($self, object, /)", + "dllist": "($self, /)", + "get_errno": "($self, /)", + }, + "_interpchannels": { + "list_all": "($self, /)", + }, + "_socket": { + "close": "($self, object, /)", + "dup": "($self, object, /)", + "getdefaulttimeout": "($self, /)", + "gethostname": "($self, /)", + "if_nameindex": "($self, /)", + "setdefaulttimeout": "($self, object, /)", + }, + "_stat": { + "S_IFMT": "($self, object, /)", + "S_IMODE": "($self, object, /)", + "S_ISBLK": "($self, object, /)", + "S_ISCHR": "($self, object, /)", + "S_ISDIR": "($self, object, /)", + "S_ISDOOR": "($self, object, /)", + "S_ISFIFO": "($self, object, /)", + "S_ISLNK": "($self, object, /)", + "S_ISPORT": "($self, object, /)", + "S_ISREG": "($self, object, /)", + "S_ISSOCK": "($self, object, /)", + "S_ISWHT": "($self, object, /)", + "filemode": "($self, object, /)", + }, + "_string": { + "formatter_field_name_split": "($self, object, /)", + "formatter_parser": "($self, object, /)", + }, + "_uuid": { + "generate_time_safe": "($self, /)", + }, + "time": { + "mktime": "($self, object, /)", + "monotonic": "($self, /)", + "monotonic_ns": "($self, /)", + "perf_counter": "($self, /)", + "perf_counter_ns": "($self, /)", + "process_time": "($self, /)", + "process_time_ns": "($self, /)", + "sleep": "($self, object, /)", + "thread_time": "($self, /)", + "thread_time_ns": "($self, /)", + "time": "($self, /)", + "time_ns": "($self, /)", + }, +} +for module_name, signatures in flags_signatures.items(): + try: + module = importlib.import_module(module_name) + except ImportError: + # Some native modules are unavailable on WASI or disabled by features. + continue + for function_name, expected in signatures.items(): + function = getattr(module, function_name, None) + if function is None: + # Unix-only symbols are not present on every platform. + continue + assert function.__text_signature__ == expected, ( + module_name, + function_name, + function.__text_signature__, + ) + assert function.__self__ is module, (module_name, function_name) + displayed = "(object, /)" if "object" in expected else "()" + assert str(inspect.signature(function)) == displayed + +# Ordinary Clinic functions keep their module marker and real parameter names. +assert len.__text_signature__ == "($module, obj, /)" +# Public positional-only names still matter to signature consumers. +assert anext.__text_signature__ == ( + "($module, async_iterator, default=, /)" +) +assert reversed.__setstate__.__text_signature__ == "($self, object, /)" +assert str(inspect.signature(reversed.__setstate__)) == "(self, object, /)" + +try: + import _hashlib +except ImportError: + pass +else: + assert _hashlib.HASHXOF.update.__text_signature__ == "($self, obj, /)" + assert str(inspect.signature(_hashlib.HASHXOF.update)) == "(self, obj, /)" +# Pickle protocol parameters retain the public spelling even when ignored. +import _io + +for pickle_type in ( + bytes, + memoryview, + _io.BufferedReader, + _io.BufferedWriter, + _io.BufferedRandom, + _io.TextIOWrapper, +): + reduce_ex = pickle_type.__reduce_ex__ + assert reduce_ex.__text_signature__ == "($self, protocol, /)" + parameters = inspect.signature(reduce_ex).parameters + assert list(parameters) == ["self", "protocol"] + assert parameters["protocol"].kind == inspect.Parameter.POSITIONAL_ONLY +# Clinic wraps whole parameter chunks at column 72, including the function +# name and trailing comma in the width. Preserve the raw spelling, including +# spaces inside defaults; inspect.signature equivalence alone cannot check it. +import importlib + +clinic_wrapped_signatures = { + "builtins": { + "__import__": "($module, /, name, globals=None, locals=None, fromlist=(),\n level=0)", + "__lazy_import__": "($module, /, name, globals=None, locals=None,\n fromlist=(), level=0)", + "compile": "($module, /, source, filename, mode, flags=0,\n dont_inherit=False, optimize=-1, *, module=None,\n _feature_version=-1)", + }, + "array": { + "_array_reconstructor": "($module, arraytype, typecode, mformat_code, items,\n /)" + }, + "binascii": { + "a2b_ascii85": "($module, data, /, *, foldspaces=False, adobe=False,\n ignorechars=b'', canonical=False)", + "a2b_base32": "($module, data, /, *, padded=True, alphabet=BASE32_ALPHABET,\n ignorechars=b'', canonical=False)", + "a2b_base64": "($module, data, /, *, strict_mode=,\n padded=True, alphabet=BASE64_ALPHABET,\n ignorechars=, canonical=False)", + "a2b_base85": "($module, data, /, *, alphabet=BASE85_ALPHABET,\n ignorechars=b'', canonical=False)", + "b2a_ascii85": "($module, data, /, *, foldspaces=False, wrapcol=0,\n pad=False, adobe=False)", + "b2a_base32": "($module, data, /, *, padded=True, wrapcol=0,\n alphabet=BASE32_ALPHABET)", + "b2a_base64": "($module, data, /, *, padded=True, wrapcol=0, newline=True,\n alphabet=BASE64_ALPHABET)", + "b2a_base85": "($module, data, /, *, pad=False, wrapcol=0,\n alphabet=BASE85_ALPHABET)", + }, + "_codecs": { + "utf_16_ex_decode": "($module, data, errors=None, byteorder=0, final=False,\n /)", + "utf_32_ex_decode": "($module, data, errors=None, byteorder=0, final=False,\n /)", + }, + "datetime": { + "datetime": "(year, month, day, hour=0, minute=0, second=0, microsecond=0,\n tzinfo=None, *, fold=0)", + "timedelta": "(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0,\n hours=0, weeks=0)", + "datetime.replace": "($self, /, year=unchanged, month=unchanged, day=unchanged,\n hour=unchanged, minute=unchanged, second=unchanged,\n microsecond=unchanged, tzinfo=unchanged, *, fold=unchanged)", + "time.replace": "($self, /, hour=unchanged, minute=unchanged, second=unchanged,\n microsecond=unchanged, tzinfo=unchanged, *, fold=unchanged)", + }, + "_functools": { + "reduce": "($module, function, iterable, /,\n initial=functools._initial_missing)" + }, + "_hashlib": { + "openssl_sha224": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_sha256": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_sha384": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_sha3_224": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_sha3_256": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_sha3_384": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_sha3_512": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_sha512": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_shake_128": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "openssl_shake_256": "($module, /, data=b'', *, usedforsecurity=True,\n string=None)", + "pbkdf2_hmac": "($module, /, hash_name, password, salt, iterations,\n dklen=None)", + }, + "_io": { + "TextIOWrapper": "(buffer, encoding=None, errors=None, newline=None,\n line_buffering=False, write_through=False)", + "open": "($module, /, file, mode='r', buffering=-1, encoding=None,\n errors=None, newline=None, closefd=True, opener=None)", + "TextIOWrapper.reconfigure": "($self, /, *, encoding=None, errors=None, newline=None,\n line_buffering=None, write_through=None)", + }, + "_lsprof": { + "Profiler._creturn_callback": "($self, code, instruction_offset, callable, self_arg,\n /)" + }, + "_pickle": { + "Unpickler": "(file, *, fix_imports=True, encoding='ASCII', errors='strict',\n buffers=())", + "dump": "($module, /, obj, file, protocol=None, *, fix_imports=True,\n buffer_callback=None)", + "dumps": "($module, /, obj, protocol=None, *, fix_imports=True,\n buffer_callback=None)", + "load": "($module, /, file, *, fix_imports=True, encoding='ASCII',\n errors='strict', buffers=())", + "loads": "($module, data, /, *, fix_imports=True, encoding='ASCII',\n errors='strict', buffers=())", + }, + "posix": { + "access": "($module, /, path, mode, *, dir_fd=None, effective_ids=False,\n follow_symlinks=True)", + "chmod": "($module, /, path, mode, *, dir_fd=None,\n follow_symlinks=(os.name != 'nt'))", + "copy_file_range": "($module, /, src, dst, count, offset_src=None,\n offset_dst=None)", + "link": "($module, /, src, dst, *, src_dir_fd=None, dst_dir_fd=None,\n follow_symlinks=(os.name != 'nt'))", + "posix_spawn": "($module, path, argv, env, /, *, file_actions=(),\n setpgroup=None, resetids=False, setsid=False,\n setsigmask=(), setsigdef=(), scheduler=None)", + "posix_spawnp": "($module, path, argv, env, /, *, file_actions=(),\n setpgroup=None, resetids=False, setsid=False,\n setsigmask=(), setsigdef=(), scheduler=None)", + "register_at_fork": "($module, /, *, before=,\n after_in_child=,\n after_in_parent=)", + "utime": "($module, /, path, times=None, *, ns=,\n dir_fd=None, follow_symlinks=True)", + }, + "_posixsubprocess": { + "fork_exec": "($module, args, executable_list, close_fds, pass_fds, cwd,\n env, p2cread, p2cwrite, c2pread, c2pwrite, errread, errwrite,\n errpipe_read, errpipe_write, restore_signals, call_setsid,\n pgid_to_set, gid, extra_groups, uid, child_umask, preexec_fn,\n /)" + }, + "pyexpat": { + "ParserCreate": "($module, /, encoding=None, namespace_separator=None,\n intern=)" + }, + "_remote_debugging": { + "BinaryWriter.set_stats": "($self, /, duration_sec, sample_rate, error_rate=None,\n missed_samples=None)" + }, + "_sre": { + "compile": "($module, /, pattern, flags, code, groups, groupindex,\n indexgroup)" + }, + "_ssl": { + "_SSLContext._wrap_bio": "($self, /, incoming, outgoing, server_side,\n server_hostname=None, *, owner=None, session=None)", + "_SSLContext._wrap_socket": "($self, /, sock, server_side, server_hostname=None, *,\n owner=None, session=None)", + }, + "syslog": { + "openlog": "($module, /, ident=, logoption=0,\n facility=LOG_USER)" + }, + "_warnings": { + "warn": "($module, /, message, category=None, stacklevel=1, source=None, *,\n skip_file_prefixes=())" + }, + "zlib": { + "compressobj": "($module, /, level=Z_DEFAULT_COMPRESSION, method=DEFLATED,\n wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL,\n strategy=Z_DEFAULT_STRATEGY, zdict=)" + }, +} +for module_name, signatures in clinic_wrapped_signatures.items(): + try: + module = importlib.import_module(module_name) + except ImportError: + # Native modules vary with the platform and build features. + continue + for attribute_path, expected in signatures.items(): + if module_name == "posix": + if attribute_path == "copy_file_range" and sys.platform != "linux": + # copy_file_range is a Linux-only syscall. + continue + if sys.platform == "wasi" and attribute_path in ( + "posix_spawn", + "posix_spawnp", + "register_at_fork", + ): + # WASI does not provide process creation or fork hooks. + continue + function = module + for component in attribute_path.split("."): + function = getattr(function, component) + assert function.__text_signature__ == expected, ( + module_name, + attribute_path, + function.__text_signature__, + expected, + ) + +# Explicit optional groups are public text, not Python parameter-list syntax. +for sequence_type in (str, bytes, bytearray): + value = sequence_type("abc", "ascii") if sequence_type is not str else "abc" + needle = sequence_type("b", "ascii") if sequence_type is not str else "b" + for method_name in ( + "count", + "find", + "index", + "rfind", + "rindex", + "startswith", + "endswith", + ): + parameter = {"startswith": "prefix", "endswith": "suffix"}.get( + method_name, "sub" + ) + method = getattr(sequence_type, method_name) + assert method.__text_signature__ == f"($self, {parameter}[, start[, end]], /)" + bound = getattr(value, method_name) + for target in (method, bound): + try: + inspect.signature(target) + except ValueError: + pass + else: + raise AssertionError("optional group should not be inspect-parsable") + assert bound(needle) == bound(needle, None, None) + assert bound(needle, 1) == bound(needle, 1, None) + events = [] + + class Index: + def __init__(self, name, value): + self.name, self.value = name, value + + def __index__(self): + events.append(self.name) + return self.value + + assert bound(needle, Index("start", 0), Index("end", 3)) == bound(needle) + assert events == ["start", "end"] + for args, kwargs in ( + ((needle,), {"start": 0}), + ((), {}), + ((needle, 0, 3, 4), {}), + ): + try: + bound(*args, **kwargs) + except TypeError: + pass + else: + raise AssertionError("positional-only argument validation changed") + +import _csv + +for _function, _first in ( + (_csv.reader, "iterable"), + (_csv.writer, "fileobj"), + (_csv.register_dialect, "name"), +): + assert _function.__text_signature__ == ( + f"($module, {_first}, /, dialect='excel', **fmtparams)" + ) + assert str(inspect.signature(_function)) == ( + f"({_first}, /, dialect='excel', **fmtparams)" + ) + + +# Explicit overrides and generated NULL defaults are useful raw metadata even +# when inspect.Signature cannot represent optional groups or sentinel defaults. +import collections +import datetime + +for obj, raw, doc in ( + ( + collections.deque, + "([iterable[, maxlen]])", + "A list-like sequence optimized for data accesses near its endpoints.", + ), + ( + collections.deque.index, + "($self, value, [start, [stop]])", + "Return first index of value.\n\n" + "Raises ValueError if the value is not present.", + ), + ( + collections.deque().index, + "($self, value, [start, [stop]])", + "Return first index of value.\n\n" + "Raises ValueError if the value is not present.", + ), + ( + datetime.timezone, + "(offset, name=)", + "Fixed offset from UTC implementation of tzinfo.", + ), +): + assert obj.__text_signature__ == raw + assert obj.__doc__ == doc + try: + inspect.signature(obj) + except ValueError: + pass + else: + raise AssertionError(f"signature should remain unrepresentable: {obj}") + +# __prepare__ uses $cls, unlike the $type receiver of most native classmethods. +# The descriptor and its bound form must expose the same header but strip the +# bound receiver only from the latter's inspected signature. +prepare = type.__dict__["__prepare__"] +assert prepare.__text_signature__ == "($cls, name, bases, /, **kwds)" +assert str(inspect.signature(prepare)) == "(cls, name, bases, /, **kwds)" +assert type.__prepare__.__text_signature__ == prepare.__text_signature__ +assert str(inspect.signature(type.__prepare__)) == "(name, bases, /, **kwds)" +assert type.__prepare__.__doc__ == "Create the namespace for the class statement" +assert type.__prepare__.__self__ is type + +# A display signature must not impose Clinic binding on __prepare__: CPython's +# implementation ignores every supplied argument and returns a fresh namespace. +for arguments in ((), (object(),), (object(), object(), object())): + namespace = type.__prepare__(*arguments, unexpected=object()) + assert namespace == {} + assert namespace is not type.__prepare__(*arguments, unexpected=object()) diff --git a/extra_tests/snippets/builtin_slice.py b/extra_tests/snippets/builtin_slice.py index 9a5c1bc78d8..8b8c24e48ca 100644 --- a/extra_tests/snippets/builtin_slice.py +++ b/extra_tests/snippets/builtin_slice.py @@ -191,7 +191,7 @@ def test_all_slices(): except AssertionError: failures.append( "start: {} ,stop: {}, step {}. Expected: {}, found: {}".format( - s, e, t, lhs, slices_res[count] + s, e, t, slices_res[count], lhs ) ) count += 1 @@ -199,7 +199,7 @@ def test_all_slices(): if failures: for f in failures: print(f) - print(len(failures), "slices failed") + raise AssertionError(f"{len(failures)} slices failed") test_all_slices() diff --git a/extra_tests/snippets/builtin_str.py b/extra_tests/snippets/builtin_str.py index d114e2d5727..20a59d84d5f 100644 --- a/extra_tests/snippets/builtin_str.py +++ b/extra_tests/snippets/builtin_str.py @@ -28,7 +28,22 @@ assert str() == "" assert str("abc") == "abc" +assert type(iter("abc")).__name__ == "str_ascii_iterator" +assert type(iter("")).__name__ == "str_ascii_iterator" +assert type(iter("\xe9")).__name__ == "str_iterator" +ascii_iterator = iter("abc") +assert next(ascii_iterator) == "a" +assert ascii_iterator.__length_hint__() == 2 +assert ascii_iterator.__reduce__() == (iter, ("abc",), 1) +ascii_iterator.__setstate__(2) +assert list(ascii_iterator) == ["c"] + assert_raises(TypeError, lambda: str("abc", "utf-8")) +assert_raises(ValueError, lambda: str(b"abc", "utf-8\x00")) +assert_raises(ValueError, lambda: str(b"abc", "utf-8", "strict\x00")) +assert_raises(ValueError, lambda: str(b"abc", "\x00", [])) +assert_raises(ValueError, lambda: str(encoding="\x00")) +assert_raises(ValueError, lambda: str(errors="\x00")) assert str(b"abc", "utf-8") == "abc" assert str(b"abc", encoding="ascii") == "abc" @@ -411,7 +426,10 @@ def __int__(self): for value in (None, TypeError("conversion failed")): with assert_raises(TypeError) as cm: template % PercentInt(value) - assert str(cm.exception).endswith("a real number is required, not PercentInt") + conversion = chr(template[-1]) if isinstance(template, bytes) else template[-1] + assert str(cm.exception) == ( + f"format argument: %{conversion} requires a real number, not PercentInt" + ) assert_raises( RuntimeError, template.__mod__, PercentInt(RuntimeError("conversion failed")) ) @@ -427,6 +445,31 @@ def __int__(self): assert "%x" % PercentInt(3) == "7" assert b"%o" % PercentInt(3) == b"7" + +def test_percent_character_subclasses(): + for base, value, templates in ( + (str, "ab", ("%c",)), + (bytes, b"ab", (b"%c", bytearray(b"%c"))), + (bytearray, b"ab", (b"%c", bytearray(b"%c"))), + ): + + class Indexable(base): + def __index__(self): + raise AssertionError("%c must check the character length first") + + for template in templates: + assert template % Indexable(value[:1]) == template % value[:1] + for text in (value[:0], value): + with assert_raises(TypeError) as expected: + template % base(text) + with assert_raises(TypeError) as actual: + template % Indexable(text) + assert str(actual.exception) == str(expected.exception) + assert template % PercentIndex() == template % 7 + + +test_percent_character_subclasses() + assert ( "%(first)s %(second)s" % {"second": "World!", "first": "Hello,"} == "Hello, World!" ) @@ -1027,10 +1070,11 @@ class MyString(str): def test_huge_width(): - # A width that cannot be allocated is a MemoryError, not an aborted - # process, and a tabsize wider than a C int does not fit at all. + # A representable width reaches allocation; a wider one overflows first. + # A tabsize wider than a C int does not fit at all. + width_error = MemoryError if sys.maxsize >= 1 << 62 else OverflowError for meth in ("center", "ljust", "rjust", "zfill"): - assert_raises(MemoryError, lambda meth=meth: getattr("a", meth)(1 << 62)) + assert_raises(width_error, lambda meth=meth: getattr("a", meth)(1 << 62)) assert_raises(OverflowError, lambda: "\ta".expandtabs(1 << 62)) assert_raises(OverflowError, lambda: "\ta".expandtabs(2**31)) # The widest tabsize that still fits is accepted. With no tab to expand @@ -1098,6 +1142,23 @@ def test_replace_unchanged(): test_replace_unchanged() +def test_replace_missing_pattern(): + for text in ("ordinary text", "\u00e1\u03b2\U0001f600", "a\ud800b\udfff"): + for count in (-1, 1, 10): + assert text.replace("\r", "replacement", count) is text + result = MyString(text).replace("\r", "replacement", count) + assert type(result) is str + assert result == text + + # Continue the same search after the first match, including lone surrogates. + assert "ababa".replace("aba", "x") == "xba" + assert "\ud800x\ud800".replace("\ud800", "\udfff", 1) == "\udfffx\ud800" + assert "\ud800x\ud800".replace("\ud800", "\udfff") == "\udfffx\udfff" + + +test_replace_missing_pattern() + + def test_expandtabs_zero_tabsize(): # With no width to advance to, the tabs come out and nothing else moves. # A tab that followed a character used to ask for a run of usize::MAX @@ -1160,3 +1221,459 @@ def __radd__(self, other): test_concat_error_message() + + +def test_subscript_typeerror_message(): + def message(index): + try: + "abc"[index] + except TypeError as err: + return str(err) + raise AssertionError("TypeError was not raised") + + assert message("def") == "string indices must be integers, not 'str'" + assert message(object()) == "string indices must be integers, not 'object'" + assert message(1.5) == "string indices must be integers, not 'float'" + assert message(None) == "string indices must be integers, not 'NoneType'" + + Long = type("A" * 250, (), {}) + assert message(Long()) == "string indices must be integers, not '{}'".format( + "A" * 200 + ) + + +test_subscript_typeerror_message() + + +# Decimal conversion errors identify the consumed argument, including star arguments. +for is_bytes in (False, True): + for conversion in "diu": + for template, values, context in ( + ("%" + conversion, "bad", ""), + ("%" + conversion, ("bad",), " 1"), + ("%s %" + conversion, ("ok", "bad"), " 2"), + ("%*.*" + conversion, (5, 2, "bad"), " 3"), + ("%(value)" + conversion, {"value": "bad"}, " 'value'"), + ): + if is_bytes: + template = template.encode() + if isinstance(values, dict): + values = {b"value": "bad"} + context = " b'value'" + elif isinstance(values, tuple) and len(values) == 2: + values = (b"ok", "bad") + with assert_raises(TypeError) as caught: + template % values + assert str(caught.exception) == ( + f"format argument{context}: %{conversion} requires a real number, not str" + ) + + +def test_percent_callback_order_bounded(): + for template in ("%r %", b"%r %", bytearray(b"%r %")): + calls = [] + + class Value: + def __repr__(self): + calls.append("repr") + return "value" + + with assert_raises(ValueError): + template % (Value(),) + assert calls == ["repr"] + + for template, key in ( + ("%(x)*r", "x"), + (b"%(x)*r", b"x"), + (bytearray(b"%(x)*r"), b"x"), + ): + calls = [] + + class Mapping: + def __getitem__(self, name): + calls.append(name) + return 5 + + with assert_raises(ValueError): + template % Mapping() + assert calls == [key] + + +test_percent_callback_order_bounded() + + +class PartitionString(str): + pass + + +partition_string = PartitionString("abc") +assert partition_string.partition(":")[0] is partition_string +assert partition_string.rpartition(":")[2] is partition_string + + +# Codec searches run while nonempty input is exported, but after an empty +# export is released. They must see the original storage, not a prior copy. +def test_decode_codec_search_buffer_lifetime(): + import codecs + + for kind in (bytearray, memoryview): + for initial in (b"x", b""): + data = bytearray(initial) + source = data if kind is bytearray else memoryview(data) + events = [] + name = "snippet_buffer_%s_%s" % (kind.__name__, len(initial)) + + def search(encoding): + if encoding != name: + return None + try: + data.extend(b"y") + events.append("resized") + except BufferError: + events.append("exported") + if initial: + data[0] = ord("z") + return codecs.lookup("utf-8") + + codecs.register(search) + try: + assert str(source, name) == ("z" if initial else "") + # Normal mode never looks up the encoding for empty input. + if initial or sys.flags.dev_mode: + expected = ( + "exported" if initial or kind is memoryview else "resized" + ) + assert events == [expected], events + else: + assert events == [] + finally: + codecs.unregister(search) + if kind is memoryview: + source.release() + data.extend(b"released") + + class Exporter: + def __init__(self, data): + self.data = data + self.events = [] + + def __buffer__(self, flags): + self.events.append("acquire") + return memoryview(self.data) + + def __release_buffer__(self, view): + self.events.append("release") + + for initial in (b"x", b""): + exporter = Exporter(bytearray(initial)) + name = "snippet_exporter_%s" % len(initial) + + def search(encoding): + if encoding != name: + return None + exporter.events.append("lookup") + if initial: + exporter.data[0] = ord("z") + return codecs.lookup("utf-8") + + codecs.register(search) + try: + assert str(exporter, name) == ("z" if initial else "") + expected = ( + ["acquire", "lookup", "release"] if initial else ["acquire", "release"] + ) + if not initial and sys.flags.dev_mode: + expected.append("lookup") + assert exporter.events == expected, exporter.events + finally: + codecs.unregister(search) + + +test_decode_codec_search_buffer_lifetime() + + +class CodecBufferBytearray(bytearray): + exports = 0 + + def __buffer__(self, flags): + self.exports += 1 + return memoryview(b"first" if self.exports == 1 else b"second") + + +codec_buffer = CodecBufferBytearray(b"unused") +assert str(codec_buffer, "ascii") == "first" +assert codec_buffer.exports == 1 + + +if sys.flags.dev_mode: + import codecs + import encodings + + utf8_codec = codecs.lookup("utf8") + codecs.unregister(encodings.search_function) + codec_input = bytearray(b"x") + codec_events = [] + + def search_utf8_alias(name): + if name != "utf8": + return None + with assert_raises(BufferError): + codec_input.extend(b"y") + codec_input[0] = ord("z") + codec_events.append(name) + return utf8_codec + + codecs.register(search_utf8_alias) + try: + assert str(codec_input, "UTF8") == "z" + assert codec_events == ["utf8"] + finally: + codecs.unregister(search_utf8_alias) + codecs.register(encodings.search_function) + codec_input.extend(b"released") + + +def test_decode_callback_input(): + import array + import codecs + + class BytesWithBuffer(bytes): + def __buffer__(self, flags): + raise AssertionError("bytes decoding must use the native payload") + + assert str(BytesWithBuffer(b"native"), "ascii") == "native" + bad_bytes = BytesWithBuffer(b"\xffA") + with assert_raises(UnicodeDecodeError) as caught: + bad_bytes.decode("ascii") + assert type(caught.exception.object) is bytes + assert ( + caught.exception.object == bad_bytes + and caught.exception.object is not bad_bytes + ) + for wrap in (bytes, BytesWithBuffer, bytearray, memoryview): + data = bytearray(b"x") + source = wrap(data) + name = "snippet_decoder_input_%s" % wrap.__name__.lower() + + def decode(view, errors="strict"): + assert type(view) is memoryview + assert view.readonly and view.obj is None + with assert_raises(TypeError): + view[0] = ord("z") + if wrap is bytearray: + source[0] = ord("z") + elif wrap is memoryview: + data[0] = ord("z") + return (chr(view[0]), len(view)) + + def search(encoding): + if encoding == name: + return codecs.CodecInfo(name=name, encode=None, decode=decode) + + codecs.register(search) + try: + assert str(source, name) == ("x" if issubclass(wrap, bytes) else "z") + finally: + codecs.unregister(search) + if wrap is memoryview: + source.release() + + for source in (array.array("I", [0x61]), memoryview(b"_abc")[1:]): + expected_bytes = bytes(source) + + def decode_bytes(view, errors="strict"): + assert view.itemsize == 1 and view.format == "B" + assert view.shape == (len(expected_bytes),) and view.strides == (1,) + assert view.readonly and view.obj is None + assert bytes(view) == expected_bytes + return ("ok", len(view)) + + def search_bytes(encoding): + if encoding == "snippet_decoder_layout": + return codecs.CodecInfo(name=encoding, encode=None, decode=decode_bytes) + + codecs.register(search_bytes) + try: + assert str(source, "snippet_decoder_layout") == "ok" + finally: + codecs.unregister(search_bytes) + + data = bytearray(b"\xffA") + + def mutate_original(exc): + # The input remains exported, but its read lock must not surround Python. + with assert_raises(BufferError): + data.extend(b"y") + data[1] = ord("B") + return ("X", exc.end) + + codecs.register_error("snippet_mutate_original", mutate_original) + assert data.decode("ascii", "snippet_mutate_original") == "XA" + assert data == b"\xffB" + data.extend(b"released") + + def change_object_from_index(exc): + class Restart: + def __index__(self): + exc.object = b"\xffZ" + return 1 + + return ("X", Restart()) + + codecs.register_error("snippet_restart_index", change_object_from_index) + assert b"\xffA".decode("ascii", "snippet_restart_index") == "XZ" + + for position, error, message in ( + (10**100, OverflowError, "Python int too large to convert to C ssize_t"), + ("x", TypeError, "'str' object cannot be interpreted as an integer"), + (-100, IndexError, "position -99 from error handler out of bounds"), + ): + + def invalid_position(exc): + return ("X", position) + + codecs.register_error("snippet_invalid_position", invalid_position) + with assert_raises(error) as caught: + b"\xff".decode("ascii", "snippet_invalid_position") + assert str(caught.exception) == message + + +test_decode_callback_input() + + +def test_text_codec_aliases_use_registry(): + import codecs + import encodings + + aliases = ("u8", "utf", "latin", "646") + + def search(encoding): + if encoding in aliases + ("utf16", "utf32"): + return codecs.CodecInfo( + name=encoding, + encode=lambda obj, errors="strict": (b"custom", len(obj)), + decode=lambda obj, errors="strict": ("custom", len(obj)), + ) + + codecs.unregister(encodings.search_function) + codecs.register(search) + try: + for alias in aliases: + assert "x".encode(alias) == b"custom" + assert b"x".decode(alias) == "custom" + # CPython's actual fast-path spellings still bypass custom codecs. + assert "x".encode("utf8") == b"x" + assert b"x".decode("ascii") == "x" + for name, native_encode in ( + ("utf16", codecs.utf_16_encode), + ("utf32", codecs.utf_32_encode), + ): + encoded = native_encode("x")[0] + assert "x".encode(name) == encoded + assert encoded.decode(name) == "x" + finally: + codecs.unregister(search) + codecs.register(encodings.search_function) + + +test_text_codec_aliases_use_registry() + + +def test_text_codec_error_boundaries(): + import codecs + import warnings + + for encoding in ("ascii", "utf8", "utf16", "utf32"): + with assert_raises(UnicodeEncodeError) as caught: + "\ud800".encode(encoding) + assert not hasattr(caught.exception, "__notes__") + with assert_raises(UnicodeDecodeError) as caught: + b"\xff".decode("ascii") + assert not hasattr(caught.exception, "__notes__") + with assert_raises(UnicodeDecodeError) as caught: + b"\xff".decode("u8") + assert caught.exception.__notes__ == ["decoding with 'u8' codec failed"] + + result = bytearray(b"x") + + def search(encoding): + if encoding == "snippet_bytearray_encoder": + return codecs.CodecInfo( + name=encoding, + encode=lambda obj, errors="strict": (result, len(obj)), + decode=None, + ) + + codecs.register(search) + try: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert "x".encode("snippet_bytearray_encoder") == b"x" + assert len(caught) == 1 and caught[0].category is RuntimeWarning + assert ( + str(caught[0].message) + == "encoder snippet_bytearray_encoder returned bytearray instead of bytes; use codecs.encode() to encode to arbitrary types" + ) + with warnings.catch_warnings(): + warnings.simplefilter("error") + with assert_raises(RuntimeWarning) as caught: + "x".encode("snippet_bytearray_encoder") + assert not hasattr(caught.exception, "__notes__") + finally: + codecs.unregister(search) + + +test_text_codec_error_boundaries() + + +for wide_encoding, invalid, error_encoding in ( + ("utf-16", b"\xff\xfe\x00\xdc", "utf-16-le"), + ("utf-16", b"\xfe\xff\xdc\x00", "utf-16-be"), + ("utf-32", b"\xff\xfe\x00\x00\x00\x00\x11\x00", "utf-32-le"), + ("utf-32", b"\x00\x00\xfe\xff\x00\x11\x00\x00", "utf-32-be"), +): + with assert_raises(UnicodeDecodeError) as caught: + invalid.decode(wide_encoding) + assert caught.exception.encoding == error_encoding + assert not hasattr(caught.exception, "__notes__") + + +for wide_encoding, surrogate in ( + ("utf-16", b"\xff\xfe\x00\xd8"), + ("utf-16", b"\xfe\xff\xd8\x00"), + ("utf-32", b"\xff\xfe\x00\x00\x00\xd8\x00\x00"), + ("utf-32", b"\x00\x00\xfe\xff\x00\x00\xd8\x00"), +): + assert surrogate.decode(wide_encoding, "surrogatepass") == "\ud800" + + +def test_text_decoder_str_subclass(): + import codecs + + class Text(str): + def __str__(self): + raise AssertionError("decoder result normalization must use its payload") + + def search(name): + if name == "snippet_str_subclass": + return codecs.CodecInfo( + name=name, + encode=None, + decode=lambda obj, errors="strict": (text, len(obj)), + ) + + codecs.register(search) + try: + for value in ("", "a", "é", "Ā", "decoded"): + text = Text(value) + result = b"x".decode("snippet_str_subclass") + assert result == value + if not value or len(value) == 1 and ord(value) <= 255: + assert type(result) is str and result is value + else: + assert result is text + finally: + codecs.unregister(search) + + +test_text_decoder_str_subclass() diff --git a/extra_tests/snippets/builtin_str_add.py b/extra_tests/snippets/builtin_str_add.py index 075939ae8d2..cafedc6a5e4 100644 --- a/extra_tests/snippets/builtin_str_add.py +++ b/extra_tests/snippets/builtin_str_add.py @@ -86,3 +86,94 @@ class Child(Override): del Override.__add__ for cls in (Override, Child): assert operator.add(cls(left), right) == left + right + + +# Inheriting native concatenation must leave reflected numeric addition first. +for base, left in ( + (str, "a"), + (bytes, b"a"), + (tuple, (1,)), + (list, [1]), + (bytearray, b"a"), +): + + class Native(base): + pass + + class Child(Native): + pass + + class Explicit(base): + __add__ = base.__add__ + + for cls in (Native, Child, Explicit): + for result in ("reflected", NotImplemented): + other = Reflected(result) + if result is NotImplemented: + assert_raises(TypeError, operator.add, cls(left), other) + else: + assert operator.add(cls(left), other) == result + assert other.calls == 1 + + class ReflectedSequence(base): + calls = 0 + + def __radd__(self, other): + self.calls += 1 + return NotImplemented + + other = ReflectedSequence(left) + assert operator.add(Native(left), other) == base(left) + base(left) + assert other.calls == 1 + + class AddOverride(ReflectedSequence): + def __add__(self, other): + return "overridden" + + other = AddOverride(left) + assert operator.add(ReflectedSequence(left), other) == base(left) + base(left) + assert other.calls == 0 + del AddOverride.__add__ + other = AddOverride(left) + assert operator.add(ReflectedSequence(left), other) == base(left) + base(left) + assert other.calls == 0 + + # CPython keeps numeric dispatch after either addition method is overridden, + # including when deletion or replacement exposes the native __add__ again. + Native.__radd__ = lambda self, other: NotImplemented + for change in ( + lambda: None, + lambda: delattr(Native, "__radd__"), + lambda: setattr(Native, "__add__", base.__add__), + lambda: delattr(Native, "__add__"), + ): + change() + for cls in (Native, Child): + other = Reflected("reflected") + assert_raises(TypeError, operator.add, cls(left), other) + assert other.calls == 0 + + +# A differently named descriptor assigned to __add__ needs numeric dispatch. +class InplaceAlias(list): + __add__ = list.__iadd__ + + +other = Reflected("reflected") +assert_raises(TypeError, operator.add, InplaceAlias([1]), other) +assert other.calls == 0 + + +class NativeIntAdd(int): + __add__ = int.__add__ + + def __radd__(self, other): + raise AssertionError("inherited reflected addition took priority") + + +class IntAddOverride(NativeIntAdd): + def __add__(self, other): + return "overridden" + + +assert operator.add(NativeIntAdd(1), IntAddOverride(2)) == 3 diff --git a/extra_tests/snippets/builtin_str_encode.py b/extra_tests/snippets/builtin_str_encode.py index b4cd3043fb0..bce00f1fb2b 100644 --- a/extra_tests/snippets/builtin_str_encode.py +++ b/extra_tests/snippets/builtin_str_encode.py @@ -1,3 +1,7 @@ +import _codecs +import codecs +import inspect + from testutils import assert_raises try: @@ -56,3 +60,51 @@ def round_trip(s, encoding="utf-8"): with assert_raises(UnicodeEncodeError) as cm: "é".encode("ascii") assert str(cm.exception).startswith("'ascii' codec"), str(cm.exception) + + +# The public Codec Clinic defaults apply to omitted arguments, not to None. +# The same conversion also rejects NUL before lookup or encoding starts. +class CodecName(str): + pass + + +codec_calls = ( + (b"x".decode, (), "x"), + (bytearray(b"x").decode, (), "x"), + ("x".encode, (), b"x"), + (_codecs.decode, (b"x",), "x"), + (_codecs.encode, ("x",), b"x"), + (codecs.decode, (b"x",), "x"), + (codecs.encode, ("x",), b"x"), +) +for codec_call, args, result in codec_calls: + method = codec_call.__name__ + assert codec_call(*args) == result + assert codec_call(*args, CodecName("UTF8"), CodecName("strict")) == result + default_controls = "(encoding='utf-8', errors='strict')" + if args: + default_controls = "(obj, " + default_controls[1:] + assert str(inspect.signature(codec_call)) == default_controls + + for values, kwargs, invalid, actual in ( + ((None,), {}, "encoding", "None"), + ((), {"encoding": None}, "encoding", "None"), + (("utf-8", None), {}, "errors", "None"), + ((), {"errors": None}, "errors", "None"), + ((None, 42), {}, "encoding", "None"), + ((42, None), {}, "encoding", "int"), + (("not_a_registered_encoding", None), {}, "errors", "None"), + ): + with assert_raises(TypeError) as caught: + codec_call(*args, *values, **kwargs) + assert str(caught.exception) == ( + f"{method}() argument '{invalid}' must be str, not {actual}" + ) + + for values, kwargs in ( + (("utf-8\0", 42), {}), + ((), {"errors": "strict\0"}), + ): + with assert_raises(ValueError) as caught: + codec_call(*args, *values, **kwargs) + assert str(caught.exception) == "embedded null character" diff --git a/extra_tests/snippets/builtin_sum.py b/extra_tests/snippets/builtin_sum.py new file mode 100644 index 00000000000..59a04ab1f76 --- /dev/null +++ b/extra_tests/snippets/builtin_sum.py @@ -0,0 +1,17 @@ +import math +from fractions import Fraction + +# Float and complex accumulators keep a compensation term, as in CPython 3.14 +assert sum([0.1, 0.2, 0.3]) == 0.6 +assert sum(b"/%\x97!\x17", 8.962552828027274) == 299.9625528280273 +assert sum([0.1, 0.2, 0.3], 0j) == 0.6 + 0j +assert sum([1j, 0.1, 0.2, 0.3]) == 0.6 + 1j +assert sum([0.1j, 0.2j, 0.3j]) == 0.6j + +# The first item of another type falls back to plain addition +assert sum([0.5, Fraction(1, 4)]) == 0.75 +assert sum([0.5j, Fraction(1, 4)]) == 0.25 + 0.5j + +# The compensation never turns an infinite sum into nan or drops a zero's sign +assert sum([math.inf, 1.0]) == math.inf +assert repr(sum([-0.0j], -0.0j)) == "(-0-0j)" diff --git a/extra_tests/snippets/builtin_thread.py b/extra_tests/snippets/builtin_thread.py index e9696cce6d4..78fd46294ea 100644 --- a/extra_tests/snippets/builtin_thread.py +++ b/extra_tests/snippets/builtin_thread.py @@ -1,3 +1,39 @@ import _thread assert _thread.TIMEOUT_MAX in [9223372036.0, 4294967.0] + +from testutils import assert_raises + +# Reentrant calls must validate arguments before incrementing the count. +for error, kwargs in ( + (ValueError, {"blocking": False, "timeout": 1}), + (ValueError, {"timeout": -2}), + (OverflowError, {"timeout": _thread.TIMEOUT_MAX + 1}), + (OverflowError, {"blocking": False, "timeout": 2**63 / 1e9}), + (OverflowError, {"blocking": False, "timeout": -9_223_372_037}), + (OverflowError, {"timeout": -9_223_372_037}), + (OverflowError, {"blocking": False, "timeout": float("inf")}), + (OverflowError, {"timeout": float("inf")}), + (OverflowError, {"blocking": False, "timeout": float("-inf")}), + (OverflowError, {"timeout": float("-inf")}), + (ValueError, {"timeout": -(2**63) / 1e9}), + (ValueError, {"blocking": False, "timeout": 4_294_968}), + (ValueError, {"timeout": -4_294_968}), +): + lock = _thread.RLock() + assert lock.acquire() + try: + with assert_raises(error): + lock.acquire(**kwargs) + assert lock._recursion_count() == 1 + finally: + while lock._is_owned(): + lock.release() + +with assert_raises(OverflowError): + _thread.stack_size(2**64) +with assert_raises(OverflowError): + _thread.stack_size(2**63) +with assert_raises(OverflowError): + _thread.stack_size(-(2**63) - 1) +assert _thread.stack_size() == 0 diff --git a/extra_tests/snippets/builtin_tuple.py b/extra_tests/snippets/builtin_tuple.py index a679d2a99a8..c60fc5563cb 100644 --- a/extra_tests/snippets/builtin_tuple.py +++ b/extra_tests/snippets/builtin_tuple.py @@ -100,3 +100,43 @@ def __eq__(self, x): # that product must raise instead of wrapping into a short allocation. with assert_raises(MemoryError): (1,) * sys.maxsize + + +# Releasing a tuple visits its elements backwards, including nested tuples and +# tuple subclasses. Observe finalizers rather than implementation refcounts. +tuple_events = [] + + +class TupleItem: + def __init__(self, name): + self.name = name + + def __del__(self): + tuple_events.append(self.name) + + +class DestructibleTuple(tuple): + def __del__(self): + tuple_events.append("tuple") + + +for tuple_type in (tuple, DestructibleTuple): + tuple_events.clear() + items = tuple_type( + (TupleItem("a"), (TupleItem("b"), TupleItem("c")), TupleItem("d")) + ) + assert tuple_events == [] + del items + expected = ["d", "c", "b", "a"] + if tuple_type is DestructibleTuple: + expected.insert(0, "tuple") + assert tuple_events == expected, tuple_events + + +class EmptyLenTuple(tuple): + def __len__(self): + return 0 + + +assert not hasattr(tuple, "__bool__") +assert bool(EmptyLenTuple((1, 2))) is False diff --git a/extra_tests/snippets/builtin_type.py b/extra_tests/snippets/builtin_type.py index 06b40fe41f6..b6bf6261201 100644 --- a/extra_tests/snippets/builtin_type.py +++ b/extra_tests/snippets/builtin_type.py @@ -241,6 +241,25 @@ class C(B, BB): assert C.mro() == [C, B, A, BB, AA, object] +# Direct base order must also constrain ancestors shared with an earlier base. +class D(B, AA, A): + pass + + +assert D.mro() == [D, B, AA, A, object] + + +class E(AA, A): + pass + + +class F(D, E): + pass + + +assert F.mro() == [F, D, B, E, AA, A, object] + + class TypeA: def __init__(self): self.a = 1 @@ -654,7 +673,12 @@ def my_repr_func(): # https://github.com/RustPython/RustPython/issues/3100 +assert types.BuiltinMethodType is types.BuiltinFunctionType assert issubclass(types.BuiltinMethodType, types.BuiltinFunctionType) +assert type(len) is types.BuiltinFunctionType +assert type([].append) is types.BuiltinFunctionType +assert type([].append).__name__ == "builtin_function_or_method" +assert type(len).__name__ == "builtin_function_or_method" assert type.__dict__["__dict__"].__objclass__ is type assert ( @@ -743,3 +767,123 @@ class StrKey(str): warnings.simplefilter("error") with assert_raises(RuntimeWarning): type("NonStringKeyRaises", (), {6: 7}) + + +class Left: + __slots__ = ("left",) + + +class Right: + __slots__ = ("right",) + + +with assert_raises(TypeError): + + class Conflict(Left, Right): + pass + + +with assert_raises(TypeError): + + class ReverseConflict(Right, Left): + pass + + +class Empty: + __slots__ = () + + +class Compatible(Left, Empty): + pass + + +value = Compatible() +value.left = 42 +assert value.left == 42 + + +class FirstChild(Left): + __slots__ = () + + +class SecondChild(Left): + __slots__ = () + + +class Diamond(FirstChild, SecondChild): + pass + + +value = Diamond() +value.left = 43 +assert value.left == 43 + +# Native static methods retain their descriptor in the class dictionary. +native_static = str.__dict__["maketrans"] +assert isinstance(native_static, staticmethod) +assert native_static.__func__ is str.maketrans +assert native_static.__wrapped__ is str.maketrans +assert str.maketrans("a", "b") == {97: 98} +assert "".maketrans("a", "b") == {97: 98} + + +# Metaclasses inherit weakref storage from type without introducing a data +# descriptor that would shadow their instances' own __weakref__ descriptor. +def check_metaclass_weakref_descriptor(): + import weakref + + class Meta(type): + pass + + class SubMeta(Meta): + pass + + for metaclass in (Meta, SubMeta): + assert "__weakref__" not in metaclass.__dict__ + assert not hasattr(metaclass, "__weakref__") + + class Example(metaclass=metaclass): + pass + + descriptor = Example.__dict__["__weakref__"] + assert Example.__weakref__ is descriptor + instance = Example() + assert instance.__weakref__ is None + ref = weakref.ref(instance) + assert instance.__weakref__ is ref + assert weakref.ref(Example)() is Example + + class Slotted(metaclass=metaclass): + __slots__ = () + + assert not hasattr(Slotted, "__weakref__") + assert weakref.ref(Slotted)() is Slotted + + +check_metaclass_weakref_descriptor() + + +# A secondary base can supply weakref storage despite explicit empty slots. +class WeakrefPrimary: + __slots__ = ("value",) + + +class WeakrefSecondary: + __slots__ = ("__weakref__",) + + +del WeakrefSecondary.__weakref__ + + +class WeakrefCombined(WeakrefPrimary, WeakrefSecondary): + __slots__ = () + + +assert WeakrefCombined.__base__ is WeakrefPrimary +assert "__weakref__" in WeakrefCombined.__dict__ +assert WeakrefCombined().__weakref__ is None + +for variable_base in (tuple, int, bytes): + Combined = type("Combined", (variable_base, WeakrefSecondary), {"__slots__": ()}) + assert "__weakref__" in Combined.__dict__ + assert Combined().__weakref__ is None diff --git a/extra_tests/snippets/builtins_module.py b/extra_tests/snippets/builtins_module.py index bf762425c89..a3a35a29739 100644 --- a/extra_tests/snippets/builtins_module.py +++ b/extra_tests/snippets/builtins_module.py @@ -42,3 +42,26 @@ def test_func(): __builtins__ # noqa: F821 assert print + + +from types import ModuleType + + +class AnnotationDict(dict): + pass + + +module = ModuleType("annotated_module") +annotations = AnnotationDict(answer=int) +calls = [] + + +def annotate(format): + calls.append(format) + return annotations + + +module.__annotate__ = annotate +assert module.__annotations__ is annotations +assert module.__annotations__ is annotations +assert calls == [1] diff --git a/extra_tests/snippets/import.py b/extra_tests/snippets/import.py index 435e622418e..9e87fb4a609 100644 --- a/extra_tests/snippets/import.py +++ b/extra_tests/snippets/import.py @@ -76,3 +76,33 @@ def fake_import(name, globals=None, locals=None, fromlist=(), level=0): with assert_raises(SyntaxError): exec("import") + +# Reading __spec__ can replace an already cached module without starting an +# import. Check both direct __import__ and the IMPORT_NAME cache fast path. +import sys +import types + + +class ReplacingSpec: + @property + def _initializing(self): + sys.modules[replacement.__name__] = replacement + return False + + +for use_statement in (False, True): + name = "_replaced_import_cache" + cached = types.ModuleType(name) + replacement = types.ModuleType(name) + cached.__spec__ = ReplacingSpec() + sys.modules[name] = cached + try: + if use_statement: + namespace = {} + exec("import _replaced_import_cache", namespace) + result = namespace[name] + else: + result = __import__(name) + assert result is replacement + finally: + del sys.modules[name] diff --git a/extra_tests/snippets/import_atomic_reorder.py b/extra_tests/snippets/import_atomic_reorder.py new file mode 100644 index 00000000000..b7c8a9d356b --- /dev/null +++ b/extra_tests/snippets/import_atomic_reorder.py @@ -0,0 +1,189 @@ +"""Private exact-dict relocation and callback-reentry regression coverage.""" + +import _imp +import sys + + +def raises(kind, call, expected=None): + try: + call() + except kind as exc: + if expected is not None: + assert exc is expected + return exc + raise AssertionError(f"{kind.__name__} was not raised") + + +def check_native_helper(): + move = _imp._dict_move_to_end + first, middle, last = object(), object(), object() + mapping = {"first": first, "middle": middle, "last": last} + assert move(mapping, "middle") is middle + assert list(mapping) == ["first", "last", "middle"] + assert len(mapping) == 3 + assert move(mapping, "middle") is middle + assert list(mapping) == ["first", "last", "middle"] + single = {"only": None} + assert move(single, "only") is None + assert single == {"only": None} + missing = object() + exc = raises(KeyError, lambda: move(mapping, missing)) + assert exc.args[0] is missing + assert list(mapping) == ["first", "last", "middle"] + + class Subclass(dict): + pass + + raises(TypeError, lambda: move(Subclass(mapping), "middle")) + raises(TypeError, lambda: move([], "middle")) + stored = "".join(["equal", " key"]) + equal = "".join(["equal ", "key"]) + assert stored == equal and stored is not equal + mapping = {stored: middle, "after": last} + assert move(mapping, equal) is middle + assert list(mapping)[-1] is stored + + failure = ValueError("hash failure") + + class Hashed(str): + count = 0 + fail = False + + def __hash__(self): + self.count += 1 + if self.fail: + raise failure + return super().__hash__() + + lookup = Hashed(stored) + assert move(mapping, lookup) is middle + assert lookup.count == 1 + lookup.fail = True + raises(ValueError, lambda: move(mapping, lookup), failure) + assert lookup.count == 2 + + class Collision: + def __init__(self, label, action=None): + self.label = label + self.action = action + + def __hash__(self): + return 42 + + def __eq__(self, other): + action, self.action = self.action, None + if action is not None: + action() + return isinstance(other, Collision) and self.label == other.label + + lookup = Collision("target") + stored = Collision("target") + impostor = Collision("different") + mapping = {stored: first, "after": last} + + def replace_key(): + mapping.clear() + mapping[impostor] = middle + + stored.action = replace_key + raises(KeyError, lambda: move(mapping, lookup)) + assert list(mapping) == [impostor] + assert mapping[impostor] is middle + + stored = Collision("target") + mapping = {stored: first, "after": last} + stored.action = lambda: mapping.__setitem__(stored, middle) + assert move(mapping, lookup) is middle + assert list(mapping)[-1] is stored + + stored = Collision("target") + mapping = {stored: first, "after": last} + stored.action = lambda: mapping.clear() + raises(KeyError, lambda: move(mapping, lookup)) + assert mapping == {} + + stored = Collision("target") + mapping = {stored: first, "after": last} + + def resize(): + mapping.clear() + for i in range(100): + mapping[i] = i + mapping[stored] = middle + mapping["after"] = last + + stored.action = resize + assert move(mapping, lookup) is middle + assert list(mapping)[-1] is stored + assert len(mapping) == 102 + + # A surviving false candidate alone does not certify the probe prefix. + # Nested relocation compacts T into P's earlier bucket, while A keeps its + # key identity, bucket and physical entry index. T never becomes absent. + prefix_key = Collision("prefix") + candidate = Collision("candidate") + target = Collision("target") + mapping = {prefix_key: first, candidate: last, target: middle} + + def compact_prefix(): + del mapping[prefix_key] + assert move(mapping, candidate) is last + assert list(mapping) == [target, candidate] + + candidate.action = compact_prefix + assert move(mapping, lookup) is middle + assert list(mapping) == [candidate, target] + + # Inserting in a previously visited DUMMY bucket also requires a restart. + mapping = {prefix_key: first, candidate: last} + del mapping[prefix_key] + candidate.action = lambda: mapping.__setitem__(lookup, middle) + assert move(mapping, lookup) is middle + assert list(mapping) == [candidate, lookup] + + failure = RuntimeError("equality failure") + + def fail(): + raise failure + + stored = Collision("target", fail) + mapping = {stored: first, "after": last} + before = list(mapping) + raises(RuntimeError, lambda: move(mapping, lookup), failure) + assert list(mapping) == before + + class HashMutation: + def __hash__(self): + mapping.clear() + mapping["kept"] = last + return 42 + + raises(KeyError, lambda: move(mapping, HashMutation())) + assert mapping == {"kept": last} + + # Releasing the removed candidate must not run its finalizer under the + # dictionary lock. The only owners are the dict and the lookup's witness. + finalized = [] + + class Finalized(Collision): + def __del__(self): + mapping["finalized"] = True + finalized.append(True) + + mapping = {Finalized("target", lambda: mapping.clear()): first} + raises(KeyError, lambda: move(mapping, lookup)) + assert finalized == [True] + assert mapping == {"finalized": True} + + mapping = {"a": 1, "b": 2} + for i in range(100): + forward, backward = iter(mapping), reversed(mapping) + key = "a" if i % 2 == 0 else "b" + move(mapping, key) + raises(RuntimeError, lambda: next(forward)) + raises(RuntimeError, lambda: next(backward)) + assert list(mapping)[-1] == key + + +if sys.implementation.name == "rustpython": + check_native_helper() diff --git a/extra_tests/snippets/operator_arithmetic.py b/extra_tests/snippets/operator_arithmetic.py index 14763107b5c..469ef49dba6 100644 --- a/extra_tests/snippets/operator_arithmetic.py +++ b/extra_tests/snippets/operator_arithmetic.py @@ -1,4 +1,4 @@ -from operator import imul, mul +from operator import iadd, imul, mul from testutils import assert_raises @@ -89,11 +89,21 @@ def __getitem__(self, index): # Native sequence slots use the same count conversion in both directions. for value in ([1], (1,), "a", b"a", bytearray(b"a")): - for operation in (mul, lambda seq, count: count * seq, imul): + namespace = {} + exec("def reverse(seq, count):\n return count * seq", namespace) + for operation_index, operation in enumerate((mul, namespace["reverse"], imul)): + for _ in range(64): + operation(value, 1) for count, error, message in ( (1.5, TypeError, "can't multiply sequence by non-int of type 'float'"), (2**100, OverflowError, "cannot fit 'int' into an index-sized integer"), ): + if ( + type(value) in (str, bytes, tuple) + and operation_index == 1 + and error is OverflowError + ): + message = "Python int too large to convert to C ssize_t" check_repeat_error(error, message, operation, value, count) @@ -123,6 +133,79 @@ def __index__(self): ) +# Each expression has fresh bytecode so cold and warmed paths are both checked. +for value in ("a", b"a", (1,), "", b"", ()): + for expression in ( + "return seq * count", + "return count * seq", + "seq *= count; return seq", + "count *= seq; return count", + ): + namespace = {} + exec("def repeat(seq, count):\n " + expression, namespace) + repeat = namespace["repeat"] + check_repeat_error( + OverflowError, + "cannot fit 'int' into an index-sized integer", + repeat, + value, + 2**100, + ) + for _ in range(64): + assert repeat(value, 2) == mul(value, 2) + assert repeat(value, -2) == value[:0] + assert repeat(value, 0) == value[:0] + assert repeat(value, 1) == value + for count in (2**100, -(2**100)): + check_repeat_error( + OverflowError, + "Python int too large to convert to C ssize_t", + repeat, + value, + count, + ) + for other in ("a", b"a", (1,)): + if type(other) is not type(value): + check_repeat_error( + OverflowError, + "cannot fit 'int' into an index-sized integer", + repeat, + other, + 2**100, + ) + if expression == "count *= seq; return count": + check_repeat_error( + TypeError, + f"unsupported operand type(s) for *=: 'RepeatIndex' and '{type(value).__name__}'", + repeat, + value, + RepeatIndex(2), + ) + else: + assert repeat(value, RepeatIndex(2)) == mul(value, 2) + check_repeat_error( + OverflowError, + "cannot fit 'RepeatIndex' into an index-sized integer", + repeat, + value, + RepeatIndex(2**100), + ) + subclass = type("RepeatSubclass", (type(value),), {})(value) + assert repeat(subclass, 2) == mul(value, 2) + overridden = type( + "OverrideRepeat", + (type(value),), + { + "__mul__": lambda self, count: "forward", + "__rmul__": lambda self, count: "reverse", + }, + )(value) + expected = ( + "forward" if expression.startswith(("return seq", "seq *=")) else "reverse" + ) + assert repeat(overridden, 2) == expected + + class DeclineRepeat(GetItemOnly): calls = [] @@ -170,3 +253,52 @@ class RepeatInt(int): assert_raises(TypeError, operation, value) delattr(RepeatList, method) assert operation(value) == [1, 1] + + +# Inherited sequence slots must leave reflected numeric dispatch its priority. +class ReflectedCount(int): + def __rmul__(self, value): + return "reflected" + + +class InheritedRepeat(list): + pass + + +for operation in (mul, imul): + value = InheritedRepeat([1]) + assert operation(value, ReflectedCount(2)) == "reflected" + assert value == [1] + + +class RepeatMixin: + def __rmul__(self, value): + return "mixin" + + +class MixedRepeat(list, RepeatMixin): + pass + + +# A secondary base can supply the numeric slot even if list hides its method. +assert mul(MixedRepeat([1]), ReflectedCount(2)) == [1, 1] +assert imul(ReflectedCount(2), MixedRepeat([1])) == [1, 1] + +# Removing an override preserves an already installed numeric dispatcher. +InheritedRepeat.__imul__ = lambda self, other: NotImplemented +del InheritedRepeat.__imul__ +value = InheritedRepeat([1]) +assert imul(value, ReflectedCount(2)) is value +assert value == [1, 1] + + +class ReflectedAdd(list): + def __radd__(self, value): + return "reflected" + + +InheritedRepeat.__iadd__ = lambda self, other: NotImplemented +del InheritedRepeat.__iadd__ +value = InheritedRepeat([1]) +assert iadd(value, ReflectedAdd([2])) is value +assert value == [1, 2] diff --git a/extra_tests/snippets/protocol_callable.py b/extra_tests/snippets/protocol_callable.py index 1df0e717935..ed8aeae5fde 100644 --- a/extra_tests/snippets/protocol_callable.py +++ b/extra_tests/snippets/protocol_callable.py @@ -1,3 +1,6 @@ +import sys + + class Callable: def __init__(self): self.count = 0 @@ -19,3 +22,174 @@ class Inherited(Callable): i = Inherited() assert 1 == i() + + +# CALL_FUNCTION_EX consumes argument containers for exact Python functions, +# but keeps them alive while invoking bound methods and other callables. +call_events = [] + + +class CallItem: + def __init__(self, name): + self.name = name + + def __del__(self): + call_events.append(self.name) + + def __str__(self): + return self.name + + +def consume_call_item(x, fail=False): + del x + call_events.append("body") + if fail: + raise ValueError + + +class CallConsumer: + def method(self, x, fail=False): + del x + call_events.append("body") + if fail: + raise ValueError + + __call__ = method + + +class CallArgs(tuple): + def __del__(self): + call_events.append("args") + + +def generate_call_args(): + yield CallItem("x") + call_events.append("exhausted") + + +for consume, is_function, is_method in ( + (consume_call_item, True, False), + (CallConsumer().method, False, True), + (CallConsumer(), False, False), +): + kinds = ("keywords", "tuple_subclass", "generator") + if is_function or is_method: + kinds = ("direct", *kinds) + for fail in (False, True): + for kind in kinds: + # Exercise both cold and specialized call sites. + for _ in range(32): + call_events.clear() + raised = False + try: + if kind == "direct": + consume(x=CallItem("x"), fail=fail) + elif kind == "keywords": + consume(**dict(x=CallItem("x"), fail=fail)) + elif kind == "tuple_subclass": + consume(*CallArgs((CallItem("x"),)), fail=fail) + else: + consume(*generate_call_args(), fail=fail) + except ValueError: + raised = True + assert raised == fail + expected = [] + if kind == "tuple_subclass": + expected.append("args") + elif kind == "generator": + expected.append("exhausted") + if is_function or (is_method and kind == "direct"): + expected.extend(("x", "body")) + else: + expected.extend(("body", "x")) + assert call_events == expected, (kind, fail, call_events) + + +class ReplacingCallArgs(CallArgs): + def __iter__(self): + call_events.append("iter") + return iter((CallItem("replacement"),)) + + +# Tuple subclasses must be normalized through iteration, not copied as exact +# tuples. Their original members can die before the replacement is passed on. +for consume, is_function in ( + (consume_call_item, True), + (CallConsumer().method, False), +): + call_events.clear() + consume(*ReplacingCallArgs((CallItem("original"),))) + expected = ["iter", "args", "original"] + if is_function: + expected.extend(("replacement", "body")) + else: + expected.extend(("body", "replacement")) + assert call_events == expected, call_events + + +class CallSeparator(str): + def __del__(self): + call_events.append(str(self)) + + +class CallSink: + def write(self, text): + # All keyword values must survive throughout the native invocation. + assert not call_events, call_events + + def __del__(self): + call_events.append("file") + + +# Native CALL_FUNCTION_EX releases keywords in insertion order, followed by +# positional values in reverse tuple order, on both success and conversion error. +call_events.clear() +print( + *(CallItem("a"), CallItem("b")), + **dict(sep=CallSeparator("sep"), end=CallSeparator("end"), file=CallSink()), +) +assert call_events == ["sep", "end", "file", "b", "a"], call_events + +call_events.clear() +try: + print( + *(CallItem("a"), CallItem("b")), + **dict(sep=CallItem("sep"), end=CallItem("end"), file=CallSink()), + ) +except TypeError: + pass +else: + raise AssertionError("print accepted a non-string separator") +assert call_events == ["sep", "end", "file", "b", "a"], call_events + + +# Instrumented CALL_FUNCTION_EX retains the containers even for an exact +# Python function. Disabling instrumentation restores ordinary ownership. +def monitored_consume_call_item(fail): + consume_call_item(**dict(x=CallItem("x"), fail=fail)) + + +monitoring = sys.monitoring +monitoring.use_tool_id(2, "call-argument-ownership") +try: + monitoring.register_callback(2, monitoring.events.CALL, lambda *args: None) + for enabled in (False, True, False): + monitoring.set_local_events( + 2, + monitored_consume_call_item.__code__, + monitoring.events.CALL if enabled else 0, + ) + for fail in (False, True): + call_events.clear() + raised = False + try: + monitored_consume_call_item(fail) + except ValueError: + raised = True + assert raised == fail + expected = ["body", "x"] if enabled else ["x", "body"] + assert call_events == expected, (enabled, fail, call_events) +finally: + monitoring.set_local_events(2, monitored_consume_call_item.__code__, 0) + monitoring.register_callback(2, monitoring.events.CALL, None) + monitoring.free_tool_id(2) diff --git a/extra_tests/snippets/protocol_index_argument.py b/extra_tests/snippets/protocol_index_argument.py index c67a078ef05..ada8be24085 100644 --- a/extra_tests/snippets/protocol_index_argument.py +++ b/extra_tests/snippets/protocol_index_argument.py @@ -312,3 +312,65 @@ def __length_hint__(self): with assert_raises(TypeError): operator.length_hint(HintIndex()) + + +# Arguments bound as `int` objects accept `__index__` as well. +assert "abcabc".find("a", Index(1)) == 3 +assert "abcabc".rfind("a", 0, Index(3)) == 0 +assert "abcabc".index("c", Index(3)) == 5 +assert "abcabc".rindex("a", Index(1), Index(4)) == 3 +assert "aaaaaa".count("a", Index(2), Index(-1)) == 3 +assert "abcdef".startswith("d", Index(3)) +assert "abcdef".endswith("c", 0, Index(3)) +assert b"abcabc".find(b"a", Index(1)) == 3 +assert b"abcabc".count(b"b", Index(2)) == 1 +assert b"abcdef".startswith(b"d", Index(3)) +assert bytearray(b"abcabc").rindex(b"a", 0, Index(3)) == 0 +assert bytearray(b"abcdef").endswith(b"c", 0, Index(3)) + +assert list(enumerate("ab", Index(3))) == [(3, "a"), (4, "b")] +assert list(enumerate("ab", start=Index(3))) == [(3, "a"), (4, "b")] + +import itertools + +assert list(itertools.combinations("abc", Index(2))) == [ + ("a", "b"), + ("a", "c"), + ("b", "c"), +] +assert list(itertools.combinations_with_replacement("ab", Index(2))) == [ + ("a", "a"), + ("a", "b"), + ("b", "b"), +] +assert list(itertools.batched("abcde", Index(2))) == [("a", "b"), ("c", "d"), ("e",)] + +assert _thread.stack_size(Index(0)) == 0 + +import mmap + +mapped = mmap.mmap(-1, 6) +mapped.write(b"abcdef") +mapped.move(Index(0), Index(3), Index(3)) +assert mapped[:] == b"defdef" +if hasattr(mapped, "madvise"): + mapped.madvise(mmap.MADV_NORMAL, Index(0), Index(6)) + +if sys.platform != "win32": + import fcntl + import grp + import pwd + import resource + import tempfile + + assert pwd.getpwuid(Index(0)).pw_uid == 0 + assert grp.getgrgid(Index(0)).gr_gid == 0 + + nofile = resource.getrlimit(resource.RLIMIT_NOFILE) + assert resource.getrlimit(Index(resource.RLIMIT_NOFILE)) == nofile + resource.setrlimit(Index(resource.RLIMIT_NOFILE), nofile) + + with tempfile.TemporaryFile() as f: + assert fcntl.fcntl(f, fcntl.F_SETFD, Index(fcntl.FD_CLOEXEC)) == 0 + assert fcntl.fcntl(f, fcntl.F_GETFD) == fcntl.FD_CLOEXEC + fcntl.lockf(f, fcntl.LOCK_SH | fcntl.LOCK_NB, Index(0), Index(0)) diff --git a/extra_tests/snippets/protocol_index_bad.py b/extra_tests/snippets/protocol_index_bad.py index 51d90426023..5387faf3a91 100644 --- a/extra_tests/snippets/protocol_index_bad.py +++ b/extra_tests/snippets/protocol_index_bad.py @@ -1,6 +1,7 @@ """Test that indexing ops don't hang when an object with a mutating __index__ is used.""" +import operator from array import array from testutils import assert_raises @@ -33,3 +34,57 @@ def run_delslice(): for e in instances: run_setslice() run_delslice() + + +# An exception from __index__ propagates before the operation is refused. +class RaisingIndex: + def __index__(self): + raise ZeroDivisionError + + +class Plain: + pass + + +t = () +with assert_raises(ZeroDivisionError): + t[RaisingIndex()] = 0 +with assert_raises(ZeroDivisionError): + del t[RaisingIndex()] +with assert_raises(ZeroDivisionError): + operator.setitem(b"", RaisingIndex(), 0) +with assert_raises(ZeroDivisionError): + operator.delitem("", RaisingIndex()) +with assert_raises(ZeroDivisionError): + Plain()[RaisingIndex()] = 0 +with assert_raises(ZeroDivisionError): + del Plain()[RaisingIndex()] +with assert_raises(IndexError): + t[2**70] = 0 +with assert_raises(IndexError): + del t[2**70] + +with assert_raises(TypeError) as cm: + del t[0] +assert str(cm.exception) == "'tuple' object doesn't support item deletion" +with assert_raises(TypeError) as cm: + del t["a"] +assert str(cm.exception) == "'tuple' object does not support item deletion" +with assert_raises(TypeError) as cm: + del object()[RaisingIndex()] +assert str(cm.exception) == "'object' object does not support item deletion" + + +class Renamed: + pass + + +class RenamingIndex: + def __index__(self): + Renamed.__name__ = "Other" + return 0 + + +with assert_raises(TypeError) as cm: + del Renamed()[RenamingIndex()] +assert str(cm.exception) == "'Other' object doesn't support item deletion" diff --git a/extra_tests/snippets/recursion.py b/extra_tests/snippets/recursion.py index 4b61a74b438..fe7daa5d69a 100644 --- a/extra_tests/snippets/recursion.py +++ b/extra_tests/snippets/recursion.py @@ -44,3 +44,32 @@ class Descr: pass else: raise AssertionError("descr.x should not resolve") + + +def recurse(): + recurse() + + +try: + recurse() +except RecursionError as e: + msg = str(e) + assert msg, f"empty RecursionError message: {e!r}" + assert not msg.endswith(" "), f"trailing space in RecursionError: {e!r}" + +import sys + +prev_limit = sys.getrecursionlimit() +try: + sys.setrecursionlimit(50) + try: + recurse() + except RecursionError as e: + assert str(e) == "maximum recursion depth exceeded", ( + f"unexpected message: {e!r}" + ) + assert e.args == ("maximum recursion depth exceeded",), ( + f"unexpected args: {e.args!r}" + ) +finally: + sys.setrecursionlimit(prev_limit) diff --git a/extra_tests/snippets/stdlib_abc.py b/extra_tests/snippets/stdlib_abc.py index 30b4ef37068..df1833a419f 100644 --- a/extra_tests/snippets/stdlib_abc.py +++ b/extra_tests/snippets/stdlib_abc.py @@ -36,3 +36,28 @@ class SubConcrete(Concrete): assert isinstance(Concrete(), CustomInterface) assert isinstance(SubConcrete(), CustomInterface) assert not isinstance((), CustomInterface) + + +class NoClassAttribute: + @property + def __class__(self): + raise AttributeError("no class attribute") + + +instance = NoClassAttribute() +assert not isinstance(instance, CustomInterface) +CustomInterface.register(NoClassAttribute) +assert isinstance(instance, CustomInterface) + +class_error = RuntimeError("class lookup failed") + + +class BrokenClassAttribute: + @property + def __class__(self): + raise class_error + + +with assert_raises(RuntimeError) as caught: + isinstance(BrokenClassAttribute(), CustomInterface) +assert caught.exception is class_error diff --git a/extra_tests/snippets/stdlib_array.py b/extra_tests/snippets/stdlib_array.py index 540bc0796c1..f8a0e5ba682 100644 --- a/extra_tests/snippets/stdlib_array.py +++ b/extra_tests/snippets/stdlib_array.py @@ -346,3 +346,176 @@ def source(): test_array_search_sees_appended_items() test_array_insert_converts_without_lock() test_array_extend_callbacks_and_partial_progress() + + +def test_array_fromlist_callbacks(): + for code in ("i", "d"): + values = array(code, [1]) + source = [] + + class Number: + def __index__(self): + assert len(values) == 3 + values[0] = 9 + source[1] = 8 + return 7 + + def __float__(self): + return float(self.__index__()) + + source[:] = [Number(), 2] + values.fromlist(source) + assert list(values) == [9, 7, 8] + + values = array("i", [1]) + + class Append: + def __index__(self): + values.append(9) + return 7 + + values.fromlist([Append()]) + assert list(values) == [1, 7, 9] + + +def test_array_fromlist_rollback(): + for mutate in (lambda source: source.clear(), lambda source: source.append(3)): + values = array("i", [1]) + + class ChangeList: + def __index__(self): + values[0] = 9 + mutate(source) + return 7 + + source = [ChangeList(), 2] + with assert_raises(RuntimeError): + values.fromlist(source) + assert list(values) == [9] + + values = array("i", [1]) + + class Fail: + def __index__(self): + assert values[1] == 2 + raise ValueError("conversion failed") + + with assert_raises(ValueError): + values.fromlist([2, Fail()]) + assert list(values) == [1] + + class Clear: + def __index__(self): + values.clear() + return 7 + + with assert_raises(IndexError): + values.fromlist([Clear()]) + assert len(values) == 1 + + +def test_array_fromlist_exports(): + values = array("i", [1]) + with memoryview(values): + values.fromlist([]) + with assert_raises(BufferError): + values.fromlist([2]) + + views = [] + + class Export: + def __index__(self): + views.append(memoryview(values)) + return 7 + + values.fromlist([Export()]) + assert list(views.pop()) == [1, 7] + + class ExportAndFail: + def __index__(self): + views.append(memoryview(values)) + raise ValueError("conversion failed") + + with assert_raises(BufferError): + values.fromlist([ExportAndFail()]) + assert len(values) == len(views[0]) == 3 + views.pop().release() + + +test_array_fromlist_callbacks() +test_array_fromlist_rollback() +test_array_fromlist_exports() + + +def test_array_reconstructor_integer_abi(): + from array import _array_reconstructor + from struct import pack + + class SubArray(array): + pass + + long_width = array("l").itemsize + other_width = 4 if long_width == 8 else 8 + expected_recode = {"l": "i", "L": "I"} if other_width == 4 else {"l": "q", "L": "Q"} + native_width_codes = { + 4: {"l": (8, "i"), "L": (6, "I")}, + 8: {"l": (12, "q"), "L": (10, "Q")}, + } + for code, mid in (("l", -123), ("L", 123)): + sign_bit = int(code == "l") + foreign_values = (mid, 2 ** (8 * other_width - sign_bit) - 1) + foreign_fmt, foreign_struct_code = native_width_codes[other_width][code] + for fmt, endian in ((foreign_fmt, "<"), (foreign_fmt + 1, ">")): + data = pack(endian + foreign_struct_code * 2, *foreign_values) + restored = _array_reconstructor(SubArray, code, fmt, data) + assert type(restored) is SubArray + assert restored.typecode == expected_recode[code] + assert restored.itemsize == other_width + assert restored.tolist() == list(foreign_values) + assert restored.tobytes() == pack( + "=" + foreign_struct_code * 2, *foreign_values + ) + + values = (mid, 2 ** (8 * long_width - sign_bit) - 1) + native_fmt, native_struct_code = native_width_codes[long_width][code] + if sys.byteorder == "big": + native_fmt += 1 + data = pack("=" + native_struct_code * 2, *values) + restored = _array_reconstructor(array, code, native_fmt, data) + # An already native format must preserve even the aliased type code. + assert restored.typecode == code + assert restored.tobytes() == data + + # Endianness alone takes the slow path and its last-descriptor rule. + opposite = ">" if sys.byteorder == "little" else "<" + foreign = pack(opposite + native_struct_code * 2, *values) + restored = _array_reconstructor(array, code, native_fmt ^ 1, foreign) + assert restored.typecode == ( + {"l": "q", "L": "Q"}[code] if long_width == 8 else code + ) + assert restored.tobytes() == data + + +def test_array_reconstructor_index(): + from array import _array_reconstructor + from struct import pack + + calls = [] + + class Format: + def __index__(self): + calls.append("index") + return 8 if sys.byteorder == "little" else 9 + + data = pack("=i", 177) + assert _array_reconstructor(array, "i", Format(), data).tolist() == [177] + assert calls == ["index"] + + # Clinic converts the index before the implementation checks the class. + with assert_raises(TypeError): + _array_reconstructor(object(), "i", Format(), data) + assert calls == ["index", "index"] + + +test_array_reconstructor_integer_abi() +test_array_reconstructor_index() diff --git a/extra_tests/snippets/stdlib_ast.py b/extra_tests/snippets/stdlib_ast.py index 2dd2276723c..9b83d9f62a6 100644 --- a/extra_tests/snippets/stdlib_ast.py +++ b/extra_tests/snippets/stdlib_ast.py @@ -69,12 +69,13 @@ def foo(): def _cyclic_cases(): # Box descents - u = ast.UnaryOp(op=ast.Not(), lineno=0, col_offset=0) + u = ast.UnaryOp(op=ast.Not(), operand=None, lineno=0, col_offset=0) u.operand = u yield "UnaryOp", u b = ast.BinOp( op=ast.Add(), + left=None, right=ast.Constant(value=0, lineno=0, col_offset=0), lineno=0, col_offset=0, @@ -82,11 +83,11 @@ def _cyclic_cases(): b.left = b yield "BinOp", b - c = ast.Call(args=[], keywords=[], lineno=0, col_offset=0) + c = ast.Call(func=None, args=[], keywords=[], lineno=0, col_offset=0) c.func = c yield "Call", c - a = ast.Attribute(attr="x", ctx=ast.Load(), lineno=0, col_offset=0) + a = ast.Attribute(value=None, attr="x", ctx=ast.Load(), lineno=0, col_offset=0) a.value = a yield "Attribute", a @@ -108,3 +109,288 @@ def _cyclic_cases(): raise AssertionError(f"cyclic {name} should raise RecursionError") except RecursionError: pass # expected; matches CPython + + +# Python 3.15 rejects omitted required fields and unknown constructor keywords. +from testutils import assert_raises + +with assert_raises(TypeError) as exc: + ast.Name() +assert ( + str(exc.exception) + == "ast.Name.__init__ missing 1 required positional argument: 'id'" +) + +with assert_raises(TypeError) as exc: + ast.BinOp() +assert str(exc.exception) == ( + "ast.BinOp.__init__ missing 3 required positional arguments: 'left', 'op', and 'right'" +) + +with assert_raises(TypeError) as exc: + ast.BinOp(op=ast.Add()) +assert str(exc.exception) == ( + "ast.BinOp.__init__ missing 2 required positional arguments: 'left' and 'right'" +) + +with assert_raises(TypeError) as exc: + ast.Name(id="x", extra=True) +assert ( + str(exc.exception) == "ast.Name.__init__ got an unexpected keyword argument 'extra'" +) + +with assert_raises(TypeError) as exc: + ast.Name("x", id="y") +assert str(exc.exception) == "ast.Name got multiple values for argument 'id'" + +# Constructor defaults and explicit placeholders still work. +assert ast.Name("x").ctx is ast.Name("y").ctx +assert isinstance(ast.Name("x").ctx, ast.Load) +assert ast.FunctionDef(name="f", args=ast.arguments()).returns is None +assert ast.Module().body == [] +assert ast.Module().body is not ast.Module().body +assert ast.BinOp(left=None, op=None, right=None).left is None + + +class FieldsWithoutTypes(ast.AST): + _fields = ("value",) + + +assert not hasattr(FieldsWithoutTypes(), "value") +assert FieldsWithoutTypes(value=1).value == 1 + + +class IncompleteFieldTypes(ast.AST): + _fields = ("value",) + _field_types = {} + + +with assert_raises(TypeError) as exc: + IncompleteFieldTypes() +assert ( + str(exc.exception) + == "Field 'value' is missing from IncompleteFieldTypes._field_types" +) + + +for key in ("a'b", "line\nbreak"): + with assert_raises(TypeError) as exc: + ast.Name(id="x", **{key: 1}) + assert str(exc.exception) == ( + f"ast.Name.__init__ got an unexpected keyword argument {key!r}" + ) + + +# Explicit AST positions must survive normalized Rust navigation ranges. +import dis + + +def store_positions(tree): + code = compile(tree, "", "exec").co_consts[0] + return [ + tuple(instruction.positions) + for instruction in dis.get_instructions(code) + if instruction.opname == "STORE_FAST" + ] + + +# These two nodes have the same normalized navigation range but different +# semantic columns. Position metadata must therefore use node identity. +tree = ast.parse("def f():\n x = 1\n y = 2\n") +first, second = tree.body[0].body +for statement in (first, second): + for node in ast.walk(statement): + if hasattr(node, "lineno"): + node.lineno = node.end_lineno = 2 +first.targets[0].col_offset = first.targets[0].end_col_offset = 0 +second.targets[0].col_offset = second.targets[0].end_col_offset = -1 +assert store_positions(tree) == [(2, 2, 0, 0), (2, 2, None, None)] + + +def set_location(node, line, col, end_col): + node.lineno = node.end_lineno = line + node.col_offset = col + node.end_col_offset = end_col + return node + + +# Outbound conversion must not merge or drop explicitly supplied literal nodes. +values = [set_location(ast.Constant(value=s), 1, -1, -1) for s in ("a", "", "b")] +joined = set_location(ast.JoinedStr(values=values), 1, 0, 8) +result = compile( + ast.Expression(body=joined), + "", + "eval", + ast.PyCF_ONLY_AST | ast.PyCF_OPTIMIZED_AST, + optimize=0, +) +assert [node.value for node in result.body.values] == ["a", "", "b"] +assert all(node.col_offset == node.end_col_offset == -1 for node in result.body.values) + +# The replacement Pass derives from the statement, not its string value. +tree = ast.parse('def f():\n "doc"\n') +set_location(tree.body[0].body[0], 2, -1, -1) +set_location(tree.body[0].body[0].value, 2, 4, 9) +result = compile( + tree, "", "exec", ast.PyCF_ONLY_AST | ast.PyCF_OPTIMIZED_AST, optimize=2 +) +replacement = result.body[0].body[0] +assert isinstance(replacement, ast.Pass) +assert ( + replacement.lineno, + replacement.end_lineno, + replacement.col_offset, + replacement.end_col_offset, +) == (2, 2, -1, 3) + +# The optimizer's generated format spec is an artificial Constant; the argument +# and the outer expression retain their own distinct source locations. +tree = ast.parse("'%3s' % (value,)", mode="eval") +set_location(tree.body, 1, -1, -1) +set_location(tree.body.right.elts[0], 1, 8, 13) +result = compile( + tree, "", "eval", ast.PyCF_ONLY_AST | ast.PyCF_OPTIMIZED_AST, optimize=0 +) +formatted = result.body.values[0] +assert (result.body.col_offset, result.body.end_col_offset) == (-1, -1) +assert (formatted.col_offset, formatted.end_col_offset) == (8, 13) +assert isinstance(formatted.format_spec, ast.Constant) +assert formatted.format_spec.value == ">3" +spec = formatted.format_spec +assert (spec.lineno, spec.end_lineno, spec.col_offset, spec.end_col_offset) == ( + -1, + -1, + -1, + -1, +) + +# Parameter diagnostics preserve the complete ast.arg range through AST input, +# including annotations but excluding the * and ** prefixes. +for source, name, location in [ + ("def f(x, x): pass", "x", (1, 10, 1, 11)), + ("def f(x: int, x: str): pass", "x", (1, 15, 1, 21)), + ("def f(x, *, x): pass", "x", (1, 13, 1, 14)), + ("def f(x, *x): pass", "x", (1, 11, 1, 12)), + ("def f(x, **x): pass", "x", (1, 12, 1, 13)), + ("class C:\n def f(__x,_C__x): pass", "_C__x", (2, 12, 2, 17)), + ("def f(é, é): pass", "é", (1, 11, 1, 13)), + ("lambda x,x: None", "x", (1, 10, 1, 11)), +]: + for input_source in (source, ast.parse(source)): + try: + compile(input_source, "", "exec") + except SyntaxError as error: + assert error.msg == f"duplicate parameter '{name}' in function definition" + assert ( + error.lineno, + error.offset, + error.end_lineno, + error.end_offset, + ) == location + else: + raise AssertionError("duplicate parameter accepted") + +# Validate normalized identifiers before AST optimization, in source order, +# including function-type fragments and dotted import components. +for source, mode, constant in [ + ("if False:\n x = Truᵉ", "exec", "True"), + ("(Truᵉ) -> int", "func_type", "True"), + ("(int) -> Falſe", "func_type", "False"), + ("import a.Nºne", "exec", "None"), + ("@Truᵉ\ndef Falſe(): pass", "exec", "True"), + ("{1: Truᵉ, Falſe: 2}", "eval", "True"), + ("f(Truᵉ=1, *Falſe)", "eval", "True"), +]: + for optimize in (0, 1, 2): + try: + ast.parse(source, mode=mode, optimize=optimize) + except ValueError as error: + assert ( + str(error) == f"identifier field can't represent '{constant}' constant" + ) + else: + raise AssertionError((source, mode, optimize)) + +# Grouping parentheses remain part of the default's parser span, and an +# earlier variadic default takes precedence over a later ordinary default. +for source, offset in [ + ("type X[**P=(int)] = int", 17), + ("type X[**P=(((int)))]=int", 21), + ("type X[*Ts=int,T=int] = int", 15), +]: + try: + ast.parse(source, feature_version=(3, 12)) + except SyntaxError as error: + assert ( + error.msg + == "Type parameter defaults are only supported in Python 3.13 and greater" + ) + assert (error.lineno, error.offset, error.end_lineno, error.end_offset) == ( + 1, + offset, + 1, + offset + 1, + ) + else: + raise AssertionError(source) + + +def match_values(tree): + value, mapping = tree.body[0].cases + return value.pattern.value, mapping.pattern.keys[0] + + +# Match-only folding also runs at optimization level zero when an optimized AST +# is requested. Both a source parse and an AST-object input produce constants. +for pattern, expected in [ + ("-1", -1), + ("-0", 0), + ("-9223372036854775808", -(1 << 63)), + ("-0x10000000000000001", -((1 << 64) + 1)), + ("9223372036854775808+1j", complex(1 << 63, 1)), + ("-9223372036854775808-1j", complex(-(1 << 63), -1)), + ("0x10000000000000001+2j", complex((1 << 64) + 1, 2)), + ("-0.0-0j", complex(-0.0, -0.0)), + ("-0j", complex(-0.0, -0.0)), +]: + source = ( + f"match subject:\n" + f" case {pattern}: matched = 'value'\n" + f" case {{{pattern}: _}}: matched = 'mapping'\n" + ) + plain = compile(source, "", "exec", ast.PyCF_ONLY_AST, optimize=0) + + assert all(isinstance(n, (ast.UnaryOp, ast.BinOp)) for n in match_values(plain)) + source_result = compile( + source, "", "exec", ast.PyCF_OPTIMIZED_AST, optimize=0 + ) + object_result = compile( + plain, "", "exec", ast.PyCF_OPTIMIZED_AST, optimize=0 + ) + for result in (source_result, object_result): + for orig, folded in zip(match_values(plain), match_values(result), strict=True): + assert isinstance(folded, ast.Constant) + assert type(folded.value) is type(expected) + if isinstance(expected, complex): + assert folded.value.real.hex() == expected.real.hex() + assert folded.value.imag.hex() == expected.imag.hex() + else: + assert folded.value == expected + coords = ("lineno", "col_offset", "end_lineno", "end_col_offset") + assert all(getattr(folded, k) == getattr(orig, k) for k in coords) + for subject, matched in ((expected, "value"), ({expected: 0}, "mapping")): + namespace = {"subject": subject} + exec(compile(result, "", "exec", optimize=0), namespace) + assert namespace["matched"] == matched + +# A Python integer too large to convert to double does not turn into infinity +# in the optimized AST. Only the preceding unary sign can be folded. +huge = "1" + "0" * 310 +source = f"match subject:\n case -{huge}+1j: pass\n" +plain = compile(source, "", "exec", ast.PyCF_ONLY_AST, optimize=0) +for input_tree in (source, plain): + result = compile(input_tree, "", "exec", ast.PyCF_OPTIMIZED_AST, optimize=0) + value = result.body[0].cases[0].pattern.value + assert isinstance(value, ast.BinOp) + assert isinstance(value.left, ast.Constant) + assert value.left.value == -int(huge) diff --git a/extra_tests/snippets/stdlib_asyncio.py b/extra_tests/snippets/stdlib_asyncio.py index a6a55509036..78aaa8fa1f8 100644 --- a/extra_tests/snippets/stdlib_asyncio.py +++ b/extra_tests/snippets/stdlib_asyncio.py @@ -5,10 +5,63 @@ these only run where they are reachable. """ +import subprocess import sys from testutils import assert_raises +# An unclosed event loop must not deadlock during interpreter shutdown. +subprocess.run( + [ + sys.executable, + "-c", + "import asyncio; loop = asyncio.new_event_loop(); " + "asyncio.set_event_loop(loop); loop.run_until_complete(asyncio.sleep(0))", + ], + check=True, + timeout=10, +) + +# An omitted callback context captures registration context; an explicit None +# delegates context selection to call_soon at completion. These are different +# states even though an Option-based Rust argument used to collapse them. +import asyncio +import contextvars + +callback_value = contextvars.ContextVar("callback_value", default="unset") +callback_loop = asyncio.new_event_loop() +try: + for already_done in (False, True): + callback_events = [] + callback_future = callback_loop.create_future() + if already_done: + callback_future.set_result(None) + callback_value.set("registration") + callback_future.add_done_callback( + lambda f: callback_events.append(("omitted", callback_value.get())) + ) + callback_future.add_done_callback( + lambda f: callback_events.append(("none", callback_value.get())), + context=None, + ) + explicit_context = contextvars.copy_context() + explicit_context.run(callback_value.set, "explicit") + callback_future.add_done_callback( + lambda f: callback_events.append(("explicit", callback_value.get())), + context=explicit_context, + ) + callback_value.set("completion") + if not already_done: + callback_future.set_result(None) + callback_loop.run_until_complete(asyncio.sleep(0)) + assert callback_events == [ + ("omitted", "registration"), + ("none", "registration" if already_done else "completion"), + ("explicit", "explicit"), + ], callback_events +finally: + callback_loop.close() + if sys.implementation.name != "rustpython": sys.exit(0) @@ -76,9 +129,9 @@ def __new__(cls, *args): # to the same future; the field must not be locked while that runs. -class Reentrant: +class Reentrant(_asyncio.Future): def __hash__(self): - _asyncio.future_add_to_awaited_by(awaited, Reentrant()) + _asyncio.future_add_to_awaited_by(awaited, Reentrant(loop=object())) return 1 def __eq__(self, other): @@ -86,15 +139,15 @@ def __eq__(self, other): awaited = _asyncio.Future(loop=object()) -_asyncio.future_add_to_awaited_by(awaited, Reentrant()) +_asyncio.future_add_to_awaited_by(awaited, Reentrant(loop=object())) with assert_raises(RecursionError): # converting the single waiter into a set hashes both of them - _asyncio.future_add_to_awaited_by(awaited, Reentrant()) + _asyncio.future_add_to_awaited_by(awaited, Reentrant(loop=object())) plain = _asyncio.Future(loop=object()) -waiter = object() +waiter = _asyncio.Future(loop=object()) _asyncio.future_add_to_awaited_by(plain, waiter) -_asyncio.future_add_to_awaited_by(plain, object()) +_asyncio.future_add_to_awaited_by(plain, _asyncio.Future(loop=object())) assert waiter in plain._asyncio_awaited_by _asyncio.future_discard_from_awaited_by(plain, waiter) assert waiter not in plain._asyncio_awaited_by diff --git a/extra_tests/snippets/stdlib_binascii.py b/extra_tests/snippets/stdlib_binascii.py index c4c2121fa46..2ba5df6030d 100644 --- a/extra_tests/snippets/stdlib_binascii.py +++ b/extra_tests/snippets/stdlib_binascii.py @@ -57,3 +57,69 @@ ]: assert exc.__module__ == "binascii" assert exc.__name__ == expected_name + +# Module-bound functions retain their defining module when stored elsewhere. +# Both owned and borrowed Rust module receivers use the same Python binding. +for name, encoded, decoded in ( + ("a2b_base64", b"YQ==", b"a"), + ("a2b_base32", b"ME======", b"a"), + ("a2b_base85", b"VE", b"a"), +): + function = getattr(binascii, name) + assert function.__self__ is binascii + assert function.__module__ == "binascii" + assert function(encoded) == decoded + assert function.__text_signature__.startswith("($module, data, /, *") + +# The database supplies the full decoder documentation, not only its summary. +for function in (binascii.a2b_base32, binascii.a2b_base64, binascii.a2b_base85): + assert "\n ignorechars\n" in function.__doc__ + assert "\n canonical\n" in function.__doc__ +for function in (binascii.a2b_base32, binascii.a2b_base64): + assert "\n padded\n" in function.__doc__ +assert "Set to True by default if ignorechars is specified" in dec_b64.__doc__ + +# Flags are converted by truth value, not by type. +assert binascii.a2b_qp(b"a_b", None) == b"a_b" +assert binascii.a2b_qp(b"a_b", "x") == b"a b" +assert binascii.b2a_qp(b"a b\t\n", None) == b"a b=09\n" +assert binascii.b2a_qp(b"a b\t\n", "x") == b"a=20b=09\n" +assert binascii.b2a_qp(b"a\nb", False, None) == b"a=0Ab" +assert binascii.b2a_qp(b"a\nb", False, "x") == b"a\nb" +assert binascii.b2a_qp(b"a b", False, True, None) == b"a b" +assert binascii.b2a_qp(b"a b", False, True, "x") == b"a_b" +assert binascii.b2a_uu(b"", backtick=None) == b" \n" +assert binascii.b2a_uu(b"", backtick="x") == b"`\n" + +# A Python-visible module argument must not be mistaken for a bound receiver. +import _imp +import sys + +assert _imp.exec_builtin(sys) == 0 +with assert_raises(TypeError): + _imp.exec_builtin() + +# Receiver injection must not change the Python-facing callable metadata. +import math + +for module, function in ( + (math, math.sqrt), + (_imp, _imp.exec_builtin), + (_imp, _imp.exec_dynamic), + (binascii, binascii.a2b_base32), + (binascii, binascii.a2b_base64), + (binascii, binascii.a2b_base85), +): + assert function.__self__ is module + assert function.__module__ == module.__name__ + assert function.__qualname__ == function.__name__ + assert repr(function) == f"" + assert function.__reduce__() == function.__name__ + alias = getattr(module, function.__name__) + assert function == alias + assert hash(function) == hash(alias) + assert function.__text_signature__.startswith("($module,") + +assert _imp.exec_dynamic(sys) == 0 +with assert_raises(TypeError): + _imp.exec_dynamic() diff --git a/extra_tests/snippets/stdlib_bisect.py b/extra_tests/snippets/stdlib_bisect.py index 9aa6863491f..22c5b5f6939 100644 --- a/extra_tests/snippets/stdlib_bisect.py +++ b/extra_tests/snippets/stdlib_bisect.py @@ -1,3 +1,8 @@ +import _bisect +import functools +import gc +import sys +import weakref from bisect import bisect_left, bisect_right, insort, insort_left, insort_right # A key decides where the item goes, but the item is what gets stored. @@ -71,3 +76,153 @@ def counting_key(value): sizes = ["a", "bb", "ccc"] assert bisect_left(sizes, 2, key=len) == 1 assert bisect_right(sizes, 2, key=len) == 2 + + +# Clinic rejects malformed calls before converting bounds, and finishes lo's +# validation before starting hi's conversion. +class Index: + def __init__(self, name, value): + self.name = name + self.value = value + + def __index__(self): + events.append(self.name) + return self.value + + +for fn in ( + _bisect.bisect_left, + _bisect.bisect_right, + _bisect.insort_left, + _bisect.insort_right, +): + events = [] + try: + fn([], 0, Index("lo", 0), unknown=True) + except TypeError: + pass + else: + raise AssertionError("unknown keyword accepted") + assert events == [], events + + for value, error, message in ( + (-1, ValueError, "lo cannot be negative"), + ( + sys.maxsize + 1, + OverflowError, + "Python int too large to convert to C ssize_t", + ), + ): + events = [] + try: + fn([], 0, Index("lo", value), Index("hi", 0)) + except error as exc: + assert str(exc) == message, str(exc) + else: + raise AssertionError("invalid lo accepted") + assert events == ["lo"], events + + events = [] + try: + fn([], 0, hi=Index("hi", sys.maxsize + 1)) + except OverflowError as exc: + assert str(exc) == "cannot fit 'Index' into an index-sized integer", str(exc) + else: + raise AssertionError("overflowing hi accepted") + assert events == ["hi"], events + + try: + fn([], 0, hi=object()) + except TypeError as exc: + assert str(exc) == "argument should be integer or None, not 'object'", str(exc) + else: + raise AssertionError("non-index hi accepted") + + for methods, error, template in ( + ({}, TypeError, "argument should be integer or None, not '{}'"), + ( + {"__index__": lambda self: sys.maxsize + 1}, + OverflowError, + "cannot fit '{}' into an index-sized integer", + ), + ): + LongName = type("A" * 201, (), methods) + try: + fn([], 0, hi=LongName()) + except error as exc: + assert str(exc) == template.format("A" * 200), str(exc) + else: + raise AssertionError("invalid hi accepted") + + # No Python frame is entered by the recursive comparison. The search must + # guard its native same-type shortcut rather than relying on generic richcmp. + class Recursive: + pass + + recursive_item = Recursive() + recursive_items = [recursive_item] + Recursive.__lt__ = staticmethod(functools.partial(fn, recursive_items)) + try: + fn(recursive_items, recursive_item) + except RecursionError: + pass + else: + raise AssertionError("native bisect recursion was not stopped") + + +# Keeping a cached comparison slot must not retain the old needle class after +# a callback changes __class__ and collects it. +for fn in (_bisect.bisect_left, _bisect.bisect_right): + events = [] + + class Replacement: + def __lt__(self, other): + events.append("compare") + return False + + Original = type("Original", (), {"__lt__": lambda self, other: False}) + needle = Original() + old_class = weakref.ref(Original, lambda ref: events.append("collected")) + del Original + + def replace_class(): + # RustPython retains a reassigned class until the assigning frame exits. + # Isolate that lifetime from the search's cached type ownership. + needle.__class__ = Replacement + + class Sequence: + def __len__(self): + return 1 + + def __getitem__(self, index): + replace_class() + gc.collect() + events.append("getitem") + return Replacement() + + fn(Sequence(), needle) + assert events == ["collected", "getitem", "compare"], events + + +# insort discards a custom insert result while all original arguments are alive. +for fn in (_bisect.insort_left, _bisect.insort_right): + events = [] + + class Item: + def __del__(self): + events.append("item-del") + + class InsertResult: + def __del__(self): + events.append("result-del") + + class Sequence: + def __getitem__(self, index): + raise AssertionError("an empty interval must not fetch an item") + + def insert(self, index, item): + events.append("insert") + return InsertResult() + + assert fn(Sequence(), Item(), hi=0) is None + assert events == ["insert", "result-del", "item-del"], events diff --git a/extra_tests/snippets/stdlib_codecs_wide.py b/extra_tests/snippets/stdlib_codecs_wide.py index d5a7d68fe8c..64bddfe2f69 100644 --- a/extra_tests/snippets/stdlib_codecs_wide.py +++ b/extra_tests/snippets/stdlib_codecs_wide.py @@ -21,6 +21,10 @@ import _codecs +# Encoder counts are characters consumed, not the size of the encoded bytes. +assert _codecs.utf_8_encode("é😀") == (b"\xc3\xa9\xf0\x9f\x98\x80", 2) +assert _codecs.utf_8_encode("a\ud800b", "surrogatepass") == (b"a\xed\xa0\x80b", 3) + assert _codecs.escape_encode(b"a\tb") == (b"a\\tb", 3) assert _codecs.escape_decode(rb"a\tb") == (b"a\tb", 4) assert _codecs.utf_16_ex_decode(b"\xff\xfeh\x00i\x00", "strict", 0, True)[0] == "hi" @@ -28,3 +32,309 @@ _codecs.utf_32_ex_decode(b"\xff\xfe\x00\x00h\x00\x00\x00", "strict", 0, True)[0] == "h" ) + +# `final` is converted by truth value, not by type. +assert _codecs.utf_8_decode(b"\xc3", "strict", None) == ("", 0) +assert _codecs.utf_8_decode(b"a", "strict", "x") == ("a", 1) +assert _codecs.utf_7_decode(b"+", "strict", None) == ("", 0) +assert _codecs.utf_16_le_decode(b"a", "strict", None) == ("", 0) +assert _codecs.utf_16_ex_decode(b"a", "strict", 0, None) == ("", 0, 0) +assert _codecs.utf_32_decode(b"a", "strict", None) == ("", 0) +assert _codecs.unicode_escape_decode(b"\\", "strict", None) == ("", 0) +assert _codecs.raw_unicode_escape_decode(b"\\u00", "strict", []) == ("", 0) + + +# Lookup errors preserve the requested spelling, while search hooks receive +# the Python 3.15 normalized registry key. +import codecs + +seen_encoding_names = [] + + +def record_unknown_encoding(name): + seen_encoding_names.append(name) + return None + + +codecs.register(record_unknown_encoding) +try: + for requested, normalized in ( + ("NO Such Codec!", "no-such--codec!"), + ("x_ weird--Ω .Ab", "x_-weird--Ω-.ab"), + ): + for lookup in ( + codecs.lookup, + lambda name: codecs.encode("value", name), + lambda name: codecs.decode(b"value", name), + lambda name: "value".encode(name), + lambda name: b"value".decode(name), + ): + try: + lookup(requested) + except LookupError as error: + assert str(error) == "unknown encoding: " + requested + else: + assert False, "unknown encoding was accepted" + assert seen_encoding_names[-1] == normalized +finally: + codecs.unregister(record_unknown_encoding) + + +# The encodings helper preserves case and dots, unlike registry lookup keys. +import encodings +import warnings + + +class EncodingName(str): + pass + + +for encoding, expected in ( + ("", ""), + ("UTF-8", "UTF_8"), + (" .UTF--8. ", ".UTF_8."), + ("---", ""), + ("A__-- B", "A_B"), + ("AéB", "A_B"), + ("éUTF-8Ω", "UTF_8"), + ("A😀B", "A_B"), + ("UTF-8\x00ignored", "UTF_8"), + ("\x00UTF-8", ""), +): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert _codecs._normalize_encoding(encoding) == expected + assert _codecs._normalize_encoding(encoding=EncodingName(encoding)) == expected + assert not caught + +for encoding in (b"UTF-8", bytearray(b"UTF-8"), None, 1): + try: + _codecs._normalize_encoding(encoding) + except TypeError: + pass + else: + assert False, "non-string encoding was accepted" + +# UTF-8 validation precedes scanning, including a surrogate after NUL. +for encoding in ("A\ud800B", "A\x00\ud800B"): + try: + _codecs._normalize_encoding(encoding) + except UnicodeEncodeError as error: + assert error.encoding == "utf-8" + assert error.object == encoding + assert error.start == encoding.index("\ud800") + assert error.end == error.start + 1 + else: + assert False, "surrogate encoding was accepted" + +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + assert encodings.normalize_encoding(b"UTF-8") == "UTF_8" + assert not caught + assert encodings.normalize_encoding("AéB") == "A_B" + assert len(caught) == 1 + assert caught[0].category is DeprecationWarning + +try: + encodings.normalize_encoding(b"UTF-\xff") +except UnicodeDecodeError: + pass +else: + assert False, "non-ASCII bytes encoding was accepted" + +for args, kwargs in ( + ((), {}), + (("UTF-8", "ASCII"), {}), + (("UTF-8",), {"encoding": "ASCII"}), + ((), {"name": "UTF-8"}), +): + try: + _codecs._normalize_encoding(*args, **kwargs) + except TypeError: + pass + else: + assert False, "invalid normalization arguments were accepted" + + +# Registry removal and competing lookup results may run Python destructors. +def test_registry_reentrant_cleanup(): + released = [] + + class ErrorHandler: + def __call__(self, error): + raise AssertionError("handler should not be called") + + def __del__(self): + codecs.lookup_error("strict") + released.append("handler") + + codecs.register_error("test_registry_cleanup", ErrorHandler()) + assert _codecs._unregister_error("test_registry_cleanup") + assert released == ["handler"] + released.clear() + + class Codec(tuple): + def __new__(cls, label): + result = super().__new__(cls, (None, None, None, None)) + result.label = label + return result + + def __del__(self): + codecs.lookup_error("strict") + released.append(self.label) + + def search(name): + if name == "test_registry_cleanup": + return Codec("cached") + + codecs.register(search) + codecs.lookup("test_registry_cleanup") + codecs.unregister(search) + assert released == ["cached"] + released.clear() + + entered = False + + def reentrant_search(name): + nonlocal entered + if name == "test_registry_reentry": + if not entered: + entered = True + codecs.lookup(name) + return Codec("outer") + return Codec("inner") + + codecs.register(reentrant_search) + try: + codecs.lookup("test_registry_reentry") + assert len(released) == 1 + finally: + codecs.unregister(reentrant_search) + assert sorted(released) == ["inner", "outer"] + + +test_registry_reentrant_cleanup() + + +def test_charmap_invalid_callback_object_diagnostic(): + def handler(exc): + exc.object = None + return ("", 1) + + name = "test_charmap_invalid_callback_object" + codecs.register_error(name, handler) + try: + try: + codecs.charmap_decode(b"!", name, {}) + except TypeError as exc: + assert str(exc) == "UnicodeError 'object' attribute must be a bytes" + else: + raise AssertionError("invalid callback input was accepted") + finally: + _codecs._unregister_error(name) + + +test_charmap_invalid_callback_object_diagnostic() + + +def test_charmap_handler_repairs_retained_exception(): + state = {} + + class Mapping: + def __getitem__(self, key): + if key == ord("a"): + state["exception"].object = None + return "A" + return None + + def handler(exc): + if "exception" not in state: + state["exception"] = exc + return ("X", 1) + exc.object = b"!a?" + return ("Y", 3) + + name = "test_charmap_repair_retained_exception" + codecs.register_error(name, handler) + try: + assert codecs.charmap_decode(b"!a?", name, Mapping()) == ("XAY", 3) + finally: + _codecs._unregister_error(name) + + +test_charmap_handler_repairs_retained_exception() + + +def test_encode_handler_restart_validation(): + # Exercise the shared encoder path as well as the Windows code-page caller. + encoders = [lambda handler: _codecs.utf_8_encode("\ud800", handler)] + if hasattr(_codecs, "code_page_encode"): + encoders.append( + lambda handler: _codecs.code_page_encode(65001, "\ud800", handler) + ) + encoders.append(lambda handler: _codecs.mbcs_encode("\ud800", handler)) + encoders.append(lambda handler: _codecs.oem_encode("\ud800", handler)) + name = "test_encode_restart_validation" + try: + for encode in encoders: + for position, exception, message in ( + (-2, IndexError, "position -1 from error handler out of bounds"), + (2, IndexError, "position 2 from error handler out of bounds"), + (2**100, OverflowError, "Python int too large to convert to C ssize_t"), + ): + codecs.register_error(name, lambda exc: (b"?", position)) + try: + encode(name) + except exception as exc: + assert str(exc) == message, str(exc) + else: + assert False, position + + class Position: + def __index__(self): + raise RuntimeError("position conversion first") + + codecs.register_error(name, lambda exc: (None, Position())) + try: + encode(name) + except RuntimeError as exc: + assert str(exc) == "position conversion first" + else: + assert False + finally: + _codecs._unregister_error(name) + + +test_encode_handler_restart_validation() + + +def test_code_page_handler_context(): + if not hasattr(_codecs, "code_page_decode"): + return + name = "test_code_page_context" + seen = [] + + def handler(exc): + seen.append(exc) + exc.object = b"\xffA\xffZ" + return ("?", exc.end) + + codecs.register_error(name, handler) + try: + assert _codecs.code_page_decode(65001, b"\xff", name, True) == ("?A?Z", 1) + assert len(seen) == 2 and seen[0] is seen[1] + for operation in ( + lambda: _codecs.code_page_encode(65001, "a\ud800", "strict"), + lambda: _codecs.code_page_decode(65001, b"a\xff", "strict", True), + ): + try: + operation() + except UnicodeError as exc: + assert (exc.start, exc.end) == (0, 0) + else: + assert False + finally: + _codecs._unregister_error(name) + + +test_code_page_handler_context() diff --git a/extra_tests/snippets/stdlib_collections.py b/extra_tests/snippets/stdlib_collections.py index e4602d1c9ce..5bae826dddc 100644 --- a/extra_tests/snippets/stdlib_collections.py +++ b/extra_tests/snippets/stdlib_collections.py @@ -91,6 +91,60 @@ def __repr__(self): ordered = OrderedDict() _count_elements(ordered, "bab") assert list(ordered.items()) == [("b", 2), ("a", 1)] + + +# OrderedDict views show their contents in insertion order, including recursion. +def check_ordered_dict_view_repr(): + ordered = OrderedDict([("b", 2), ("a", 1)]) + for method, contents in ( + ("keys", "['b', 'a']"), + ("values", "[2, 1]"), + ("items", "[('b', 2), ('a', 1)]"), + ): + assert repr(getattr(OrderedDict(), method)()) == "odict_" + method + "([])" + assert ( + repr(getattr(ordered, method)()) == "odict_" + method + "(" + contents + ")" + ) + + recursive = OrderedDict() + values = recursive.values() + items = recursive.items() + recursive["self"] = values + assert repr(values) == "odict_values([...])" + recursive["self"] = items + assert repr(items) == "odict_items([('self', ...)])" + + # Repr must snapshot the contents before arbitrary repr code mutates them. + for method in ("keys", "values", "items"): + + class MutatingRepr: + def __repr__(self): + ordered.clear() + return "mutated" + + item = MutatingRepr() + ordered = OrderedDict([(item, item), ("tail", "last")]) + expected = { + "keys": "odict_keys([mutated, 'tail'])", + "values": "odict_values([mutated, 'last'])", + "items": "odict_items([(mutated, mutated), ('tail', 'last')])", + } + assert repr(getattr(ordered, method)()) == expected[method] + assert not ordered + + class BadRepr: + def __repr__(self): + raise ValueError("view repr") + + ordered = OrderedDict([(BadRepr(), BadRepr())]) + for method in ("keys", "values", "items"): + with assert_raises(ValueError) as caught: + repr(getattr(ordered, method)()) + assert str(caught.exception) == "view repr" + + +check_ordered_dict_view_repr() + factory = defaultdict(lambda: 100) _count_elements(factory, "a") assert factory == {"a": 1} @@ -116,3 +170,94 @@ def get(self, key, default=None): assert custom_get == {"a": 101, "b": 101} with assert_raises(AttributeError): _count_elements([], "a") + + +class IterReturnsInt: + def __iter__(self): + return 1 + + +with assert_raises(TypeError): + _count_elements([], IterReturnsInt()) + + +# defaultdict union constructs the subclass with its factory and left operand. +def check_defaultdict_subclass_union(): + calls = [] + + class DefaultSubclass(defaultdict): + def __init__(self, factory=None, initial=()): + calls.append((factory, initial)) + super().__init__(factory, initial) + + def update(self, *args, **kwargs): + raise AssertionError("union must use native dict update") + + def __setitem__(self, key, value): + raise AssertionError("union must not call overridden __setitem__") + + for factory in (None, list): + left = DefaultSubclass(factory, {"shared": 1, "left": 2}) + right = {"right": 3, "shared": 4} + calls.clear() + result = left | right + assert type(result) is DefaultSubclass + assert result.default_factory is factory + assert list(result.items()) == [("shared", 4), ("left", 2), ("right", 3)] + assert len(calls) == 1 and calls[0][0] is factory and calls[0][1] is left + + calls.clear() + result = right | left + assert type(result) is DefaultSubclass + assert result.default_factory is factory + assert list(result.items()) == [("right", 3), ("shared", 1), ("left", 2)] + assert len(calls) == 1 and calls[0][0] is factory and calls[0][1] is right + assert left == {"shared": 1, "left": 2} + assert right == {"right": 3, "shared": 4} + + calls.clear() + assert left.__or__([("x", 1)]) is NotImplemented + assert left.__ror__([("x", 1)]) is NotImplemented + assert calls == [] + + class FailingSubclass(defaultdict): + fail = False + + def __init__(self, *args): + if self.fail: + raise ValueError("union constructor") + super().__init__(*args) + + left = FailingSubclass(int, {"a": 1}) + FailingSubclass.fail = True + with assert_raises(ValueError) as caught: + left | {} + assert str(caught.exception) == "union constructor" + with assert_raises(ValueError) as caught: + {} | left + assert str(caught.exception) == "union constructor" + + class ReplacingSubclass(defaultdict): + replacement = None + + def __new__(cls, *args): + if cls.replacement is not None: + return cls.replacement + return super().__new__(cls) + + left = ReplacingSubclass(int, {"left": 1}) + replacement = {"replacement": 2} + ReplacingSubclass.replacement = replacement + assert left | {"right": 3} is replacement + assert replacement == {"replacement": 2, "right": 3} + replacement.clear() + assert {"right": 3} | left is replacement + assert replacement == {"left": 1} + ReplacingSubclass.replacement = object() + with assert_raises(SystemError): + left | {} + with assert_raises(SystemError): + {} | left + + +check_defaultdict_subclass_union() diff --git a/extra_tests/snippets/stdlib_collections_deque.py b/extra_tests/snippets/stdlib_collections_deque.py index 4d46384f1ff..7007a028c01 100644 --- a/extra_tests/snippets/stdlib_collections_deque.py +++ b/extra_tests/snippets/stdlib_collections_deque.py @@ -153,7 +153,7 @@ class D(deque): assert list(d) == ["z", "b", "c"] # Repeating a bounded deque keeps only the last maxlen items without walking the rest -assert deque([1], maxlen=3) * 2**62 == deque([1, 1, 1]) +assert deque([1], maxlen=3) * min(2**62, sys.maxsize) == deque([1, 1, 1]) assert deque([1, 2, 3], maxlen=4) * 3 == deque([3, 1, 2, 3]) @@ -565,3 +565,39 @@ def __del__(self): test_deque_extend_noops_preserve_iterators() test_deque_self_extension_retains_snapshot_until_complete() test_deque_eviction_can_mutate_source_list() + + +# Copying and arithmetic construct the subclass, including its Python state. +class TaggedDeque(deque): + def __init__(self, values=(), maxlen=None): + super().__init__(values, maxlen) + self.tag = "initialized" + + +original = TaggedDeque([1, 2], 3) +for result, expected in ( + (original.copy(), [1, 2]), + (original * 2, [2, 1, 2]), + (original + deque([3, 4]), [2, 3, 4]), +): + assert type(result) is TaggedDeque + assert result.tag == "initialized" + assert result.maxlen == 3 + assert list(result) == expected +assert list(original) == [1, 2] + + +class IteratedDeque(deque): + def __iter__(self): + return iter([9]) + + +assert deque([1]) + IteratedDeque([2]) == deque([1, 9]) + + +class OffsetDeque(deque): + def __iter__(self): + return (item + 10 for item in deque.__iter__(self)) + + +assert list(deque.__iter__(OffsetDeque([1, 2]) * 2)) == [11, 12, 21, 22] diff --git a/extra_tests/snippets/stdlib_contextvars.py b/extra_tests/snippets/stdlib_contextvars.py index 915f732d188..a54d6a3a618 100644 --- a/extra_tests/snippets/stdlib_contextvars.py +++ b/extra_tests/snippets/stdlib_contextvars.py @@ -84,3 +84,35 @@ def __eq__(self, other): for var, value in copy_context().items() if var.name == "child_marker" ] == [] + + +def context_cache_does_not_outlive_its_context(): + import contextvars + + for factory_name in ("new", "copy"): + for _ in range(100): + var = contextvars.ContextVar("var", default="default") + empty = contextvars.Context() + ctx = contextvars.Context() if factory_name == "new" else empty.copy() + ctx.run(var.set, "cached") + del ctx + ctx = contextvars.Context() if factory_name == "new" else empty.copy() + assert list(ctx.items()) == [] + assert ctx.run(var.get) == "default" + assert ctx.run(var.get, "explicit default") == "explicit default" + + missing = contextvars.ContextVar("missing") + ctx.run(missing.set, "cached") + del ctx + ctx = contextvars.Context() if factory_name == "new" else empty.copy() + try: + ctx.run(missing.get) + except LookupError: + pass + else: + raise AssertionError( + "an empty context returned a destroyed context value" + ) + + +context_cache_does_not_outlive_its_context() diff --git a/extra_tests/snippets/stdlib_csv.py b/extra_tests/snippets/stdlib_csv.py index c80847bc741..1044148f068 100644 --- a/extra_tests/snippets/stdlib_csv.py +++ b/extra_tests/snippets/stdlib_csv.py @@ -361,3 +361,532 @@ def __str__(self): test_quote_nonnumeric_writer() + + +def test_dialect_truth_conversion(): + def registered(dialect, **kwargs): + name = "truth_conversion" + try: + csv.register_dialect(name, dialect, **kwargs) + return csv.get_dialect(name) + finally: + if name in csv.list_dialects(): + csv.unregister_dialect(name) + + constructors = ( + lambda dialect, **kwargs: csv.reader([], dialect, **kwargs).dialect, + lambda dialect, **kwargs: csv.writer(io.StringIO(), dialect, **kwargs).dialect, + _csv.Dialect, + registered, + ) + + class TruthError: + def __init__(self, error): + self.error = error + self.calls = 0 + + def __bool__(self): + self.calls += 1 + raise self.error + + class InvalidTruth: + def __bool__(self): + return 1 + + for construct in constructors: + for field in ("strict", "doublequote", "skipinitialspace"): + for error_type in (RuntimeError, AttributeError, TypeError): + for use_class in (False, True): + error = error_type("dialect truth conversion") + value = TruthError(error) + + class Dialect(csv.excel): + def __new__(cls): + raise AssertionError( + "dialect classes must not be instantiated" + ) + + dialect = Dialect if use_class else csv.excel() + setattr(dialect, field, value) + try: + construct(dialect) + except error_type as caught: + assert caught is error + else: + raise AssertionError("dialect truth error was suppressed") + assert value.calls == 1 + + # An explicit option replaces the attribute before conversion. + result = construct(dialect, **{field: True}) + assert getattr(result, field) is True + assert value.calls == 1 + + value = TruthError(error) + try: + construct(None, **{field: value}) + except error_type as caught: + assert caught is error + else: + raise AssertionError("keyword truth error was replaced") + assert value.calls == 1 + + for value in (None, False, True, 0, 1, [], [1]): + dialect = csv.excel() + setattr(dialect, field, value) + assert getattr(construct(dialect), field) is bool(value) + assert getattr(construct(None, **{field: value}), field) is bool(value) + + dialect = csv.excel() + setattr(dialect, field, InvalidTruth()) + with assert_raises(TypeError): + construct(dialect) + with assert_raises(TypeError): + construct(None, **{field: InvalidTruth()}) + + # csv.Dialect's Python validation wrapper translates TypeError to csv.Error. + for error_type in (RuntimeError, AttributeError, TypeError): + error = error_type("direct Python dialect validation") + value = TruthError(error) + + class Dialect(csv.excel): + strict = value + + expected = csv.Error if error_type is TypeError else error_type + try: + Dialect() + except expected as caught: + assert str(caught) == str(error) + if error_type is not TypeError: + assert caught is error + else: + raise AssertionError("Python dialect validation swallowed the error") + assert value.calls == 1 + + +test_dialect_truth_conversion() + + +def test_dialect_lookup_and_conversion_order(): + fields = ( + "delimiter", + "doublequote", + "escapechar", + "lineterminator", + "quotechar", + "quoting", + "skipinitialspace", + "strict", + ) + defaults = (",", True, None, "\r\n", '"', csv.QUOTE_MINIMAL, False, False) + constructors = ( + lambda dialect, **kwargs: csv.reader([], dialect, **kwargs).dialect, + lambda dialect, **kwargs: csv.writer(io.StringIO(), dialect, **kwargs).dialect, + _csv.Dialect, + ) + + for construct in constructors: + for error_type in (AttributeError, RuntimeError, KeyboardInterrupt): + events = [] + + class Missing: + def __getattribute__(self, name): + events.append(name) + raise error_type(name) + + if error_type is AttributeError: + result = construct(Missing()) + assert tuple(getattr(result, field) for field in fields) == defaults + assert events == list(fields) + else: + with assert_raises(error_type) as caught: + construct(Missing()) + assert caught.exception.args == ("delimiter",) + assert events == ["delimiter"] + for dialect in (None, object(), _csv.Dialect(csv.excel)): + result = construct(dialect) + assert tuple(getattr(result, field) for field in fields) == defaults + + events = [] + + class Truth: + def __init__(self, name): + self.name = name + + def __bool__(self): + events.append("bool:" + self.name) + return False + + values = dict(zip(fields, defaults)) + for field in ("doublequote", "skipinitialspace", "strict"): + values[field] = Truth(field) + + class Dialect: + def __getattribute__(self, name): + events.append(name) + return values[name] + + construct(Dialect()) + assert events == list(fields) + [ + "bool:doublequote", + "bool:skipinitialspace", + "bool:strict", + ] + + events.clear() + construct(Dialect(), strict=True, doublequote=True) + assert events == [ + field for field in fields if field not in ("strict", "doublequote") + ] + ["bool:skipinitialspace"] + + events.clear() + construct( + None, + strict=Truth("strict"), + skipinitialspace=Truth("skipinitialspace"), + doublequote=Truth("doublequote"), + ) + assert events == ["bool:doublequote", "bool:skipinitialspace", "bool:strict"] + + # Collect every attribute before starting conversions, even on failure. + events.clear() + values["delimiter"] = "too long" + with assert_raises(TypeError): + construct(Dialect()) + assert events == list(fields) + + error = RuntimeError("truth conversion wins") + + class BadTruth: + def __bool__(self): + raise error + + # Conversion order differs from option-validation order. + for options in ( + {"doublequote": BadTruth(), "escapechar": "too long"}, + {"strict": BadTruth(), "quoting": 42}, + {"strict": BadTruth(), "quotechar": None, "quoting": csv.QUOTE_ALL}, + {"strict": BadTruth(), "delimiter": "\n"}, + ): + try: + construct(None, **options) + except RuntimeError as caught: + assert caught is error + else: + raise AssertionError("conversion order did not preserve truth error") + for options in ( + {"delimiter": "too long", "doublequote": BadTruth()}, + {"lineterminator": None, "skipinitialspace": BadTruth()}, + {"quoting": None, "strict": BadTruth()}, + {"unknown_option": None, "strict": BadTruth()}, + ): + with assert_raises(TypeError): + construct(None, **options) + + class IntegerSubclass(int): + pass + + class Index: + def __index__(self): + raise AssertionError("quoting must not call __index__") + + for value in (True, IntegerSubclass(0), Index()): + with assert_raises(TypeError): + construct(None, quoting=value) + with assert_raises(OverflowError): + construct(None, quoting=2**40, strict=BadTruth()) + + # None quotechar disables quoting only when quoting was not supplied. + assert construct(None, quotechar=None).quoting == csv.QUOTE_NONE + with assert_raises(TypeError): + construct(csv.excel, quotechar=None) + with assert_raises(TypeError): + construct(None, quotechar=None, quoting=csv.QUOTE_MINIMAL) + + assert _csv.Dialect().strict is False + assert _csv.Dialect(strict=True).strict is True + for constructor, arg in ((csv.reader, []), (csv.writer, io.StringIO())): + with assert_raises(TypeError): + constructor(arg, None, None, strict=BadTruth()) + + +test_dialect_lookup_and_conversion_order() + + +def test_field_size_limit_types(): + index_calls = [] + + class IntSubclass(int): + pass + + class Index: + def __index__(self): + index_calls.append(True) + return 17 + + old_limit = csv.field_size_limit() + try: + assert csv.field_size_limit(23) == old_limit + for value in (True, IntSubclass(17), Index()): + with assert_raises(TypeError): + csv.field_size_limit(value) + assert csv.field_size_limit() == 23 + assert index_calls == [] + with assert_raises(OverflowError): + csv.field_size_limit(2**100) + assert csv.field_size_limit() == 23 + finally: + csv.field_size_limit(old_limit) + + +test_field_size_limit_types() + + +def test_non_ascii_dialect_chars(): + for kwargs in ( + {"delimiter": "€"}, + {"quotechar": "€"}, + {"escapechar": "€", "quoting": csv.QUOTE_NONE}, + ): + out = io.StringIO() + csv.writer(out, **kwargs).writerow(["a€b", 'é"x', "plain"]) + out.seek(0) + assert list(csv.reader(out, **kwargs)) == [["a€b", 'é"x', "plain"]] + + assert csv.writer(io.StringIO(), delimiter="€").dialect.delimiter == "€" + assert list(csv.reader(['a€b€"c€d"'], delimiter="€")) == [["a", "b", "c€d"]] + + for bad in ("", "€€"): + with assert_raises(TypeError): + csv.writer(io.StringIO(), delimiter=bad) + with assert_raises(ValueError): + csv.writer(io.StringIO(), delimiter="€", quotechar="€") + + +test_non_ascii_dialect_chars() + + +# Reject the name before validating conflicting dialect arguments. +with assert_raises(TypeError) as error: + _csv.register_dialect(1, None, dialect=None) +assert str(error.exception) == "dialect name must be a string" + + +def test_dialect_name_hashing(): + class UnhashableName: + def __hash__(self): + raise ValueError("unhashable name") + + with assert_raises(TypeError): + csv.get_dialect([]) + with assert_raises(ValueError): + csv.get_dialect(UnhashableName()) + with assert_raises(TypeError): + csv.unregister_dialect([]) + with assert_raises(ValueError): + csv.unregister_dialect(UnhashableName()) + + class UnhashableStr(str): + def __hash__(self): + raise ValueError("unhashable name") + + with assert_raises(ValueError): + csv.register_dialect(UnhashableStr("excel")) + with assert_raises(ValueError): + csv.get_dialect(UnhashableStr("excel")) + with assert_raises(ValueError): + csv.unregister_dialect(UnhashableStr("excel")) + with assert_raises(TypeError): + csv.register_dialect(UnhashableStr("excel"), delimiter="ab") + + # An empty registry misses before the name is hashed. + csv.unregister_dialect("excel") + csv.unregister_dialect("excel-tab") + csv.unregister_dialect("unix") + with assert_raises(csv.Error): + csv.unregister_dialect([]) + with assert_raises(csv.Error): + csv.unregister_dialect(UnhashableName()) + + +test_dialect_name_hashing() + + +# Signature metadata describes dialect as a keyword, but it must still be +# processed after the first argument's operation in CPython's legacy wrapper. +class SignatureBadIterable: + def __iter__(self): + raise LookupError("iterate before dialect") + + +class SignatureBadWriter: + @property + def write(self): + raise LookupError("write lookup before dialect") + + +with assert_raises(LookupError) as error: + _csv.reader(SignatureBadIterable(), None, dialect=None) +assert str(error.exception) == "iterate before dialect" + +with assert_raises(LookupError) as error: + _csv.writer(SignatureBadWriter(), None, dialect=None) +assert str(error.exception) == "write lookup before dialect" + +for function, first in ( + (_csv.reader, []), + (_csv.writer, io.StringIO()), + (_csv.register_dialect, "__signature_dialect"), +): + with assert_raises(TypeError) as error: + function(first, None, dialect=None) + assert str(error.exception) == ( + "argument for function given by name ('dialect') and position (1)" + ) + with assert_raises(TypeError): + function(first, None, None) + +assert _csv.reader([], dialect=None).dialect.delimiter == "," +assert _csv.writer(io.StringIO(), dialect=None).dialect.delimiter == "," +_csv.register_dialect("__signature_dialect", dialect=None) +_csv.unregister_dialect("__signature_dialect") + +# The preceding tests removed the registered excel dialect. The displayed +# default must not turn omission into an actual lookup of that name. +assert _csv.reader([]).dialect.delimiter == "," +assert _csv.writer(io.StringIO()).dialect.delimiter == "," +with assert_raises(_csv.Error): + _csv.reader([], "excel") +with assert_raises(_csv.Error): + _csv.writer(io.StringIO(), "excel") + + +# Positional arity is checked even before iteration or write lookup. +with assert_raises(TypeError): + _csv.reader(SignatureBadIterable(), None, None) +with assert_raises(TypeError): + _csv.writer(SignatureBadWriter(), None, None) + +_csv.register_dialect("__signature_default") +_csv.unregister_dialect("__signature_default") +with assert_raises(_csv.Error): + _csv.register_dialect("__signature_default", "excel") + + +def test_writerow_streams_field_conversion(): + events = [] + callback_error = LookupError("field conversion") + iterator_error = ValueError("row iteration") + result = object() + + class Sink: + def write(self, text): + events.append(("write", text)) + return result + + class Field: + def __init__(self, name, value): + self.name = name + self.value = value + + def __str__(self): + events.append(("str", self.name)) + if self.value is callback_error: + raise callback_error + return self.value + + def row(*fields, error=None): + for index, field in enumerate(fields): + events.append(("next", index)) + yield field + events.append(("next", "end")) + if error is not None: + raise error + + writer = csv.writer(Sink()) + assert writer.writerow(row(Field("a", "a"), Field("b", "b"))) is result + assert events == [ + ("next", 0), + ("str", "a"), + ("next", 1), + ("str", "b"), + ("next", "end"), + ("write", "a,b\r\n"), + ] + + events.clear() + with assert_raises(LookupError) as error: + writer.writerow(row(Field("bad", callback_error), error=iterator_error)) + assert error.exception is callback_error + assert events == [("next", 0), ("str", "bad")] + + events.clear() + with assert_raises(ValueError) as error: + writer.writerow(row(Field("first", "ok"), error=iterator_error)) + assert error.exception is iterator_error + assert events == [("next", 0), ("str", "first"), ("next", "end")] + + events.clear() + assert writer.writerow(row(Field("ok", "ok"))) is result + assert events == [("next", 0), ("str", "ok"), ("next", "end"), ("write", "ok\r\n")] + + # Classification occurs before __str__, which can alter the type's slots. + class BecomesNumeric: + def __str__(self): + type(self).__int__ = lambda self: 1 + return "first" + + quoting = csv.writer(Sink(), quoting=csv.QUOTE_NONNUMERIC) + value = BecomesNumeric() + assert quoting.writerow([value]) is result + assert events[-1] == ("write", '"first"\r\n') + assert quoting.writerow([value]) is result + assert events[-1] == ("write", "first\r\n") + + +def test_writerow_streams_dialect_validation(): + events = [] + buffer = io.StringIO() + later = ValueError("late iterator error") + + def row(value, fail_at_end): + events.append("field") + yield value + events.append("end") + if fail_at_end: + raise later + + quote_none = csv.writer(buffer, quoting=csv.QUOTE_NONE) + with assert_raises(csv.Error) as error: + quote_none.writerow(row("needs,escape", True)) + assert str(error.exception) == "need to escape, but no escapechar set" + assert events == ["field"] + assert buffer.getvalue() == "" + + # The single empty field check, unlike a field's escape/space check, + # cannot happen until the iterator has successfully completed. + events.clear() + with assert_raises(ValueError) as error: + quote_none.writerow(row("", True)) + assert error.exception is later + assert events == ["field", "end"] + events.clear() + with assert_raises(csv.Error) as error: + quote_none.writerow(row("", False)) + assert str(error.exception) == "single empty field record must be quoted" + assert events == ["field", "end"] + + space = csv.writer( + buffer, delimiter=" ", skipinitialspace=True, quoting=csv.QUOTE_NONE + ) + events.clear() + with assert_raises(csv.Error) as error: + space.writerow(row("", True)) + assert str(error.exception) == ( + "empty field must be quoted if delimiter is a space and skipinitialspace is true" + ) + assert events == ["field"] + assert buffer.getvalue() == "" + + +test_writerow_streams_field_conversion() +test_writerow_streams_dialect_validation() diff --git a/extra_tests/snippets/stdlib_ctypes.py b/extra_tests/snippets/stdlib_ctypes.py index 827fc598826..a60131ea960 100644 --- a/extra_tests/snippets/stdlib_ctypes.py +++ b/extra_tests/snippets/stdlib_ctypes.py @@ -1,8 +1,10 @@ import ctypes +import gc import itertools import os as _os import sys as _sys import types as _types +import weakref from _ctypes import RTLD_GLOBAL, RTLD_LOCAL, Array, _SimpleCData, sizeof from _ctypes import CFuncPtr as _CFuncPtr from struct import calcsize as _calcsize @@ -458,4 +460,1385 @@ def get_win_folder_via_ctypes(csidl_name: str) -> str: else: raise AssertionError("an unallocatable array was created") +# A function-pointer cast retains the callback and its executable address. +Unary = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int) +callback = Unary(lambda value: value + 1) +address = ctypes.cast(callback, ctypes.c_void_p) +roundtrip = ctypes.cast(address, Unary) +assert roundtrip._objects[id(callback)] is callback +del callback, address +gc.collect() +assert roundtrip(41) == 42 + + +# All ctypes metaclasses use sequence repetition in either direction. +class RepeatStruct(ctypes.Structure): + _fields_ = [("value", ctypes.c_int)] + + +class RepeatUnion(ctypes.Union): + _fields_ = [("value", ctypes.c_int)] + + +for element_type in ( + ctypes.c_int, + ctypes.c_int * 1, + ctypes.POINTER(ctypes.c_int), + RepeatStruct, + RepeatUnion, + Unary, +): + assert 2 * element_type is element_type * 2 + + +class ArrayLength: + def __index__(self): + return 2 + + +assert ArrayLength() * ctypes.c_int is ctypes.c_int * 2 + + +class ReflectedLength(ArrayLength): + def __rmul__(self, other): + return "reflected" + + +assert ctypes.c_int * ReflectedLength() == "reflected" + + +class ArrayField(ctypes.Structure): + _fields_ = [("prefix", ctypes.c_int), ("values", ctypes.c_int * 3)] + + +owner = ArrayField(99, (1, 2, 3)) +view = owner.values +assert view._b_base_ is owner +assert ctypes.addressof(view) == ctypes.addressof(owner) + ArrayField.values.offset +ctypes.resize(owner, ctypes.sizeof(owner)) +assert ctypes.addressof(view) == ctypes.addressof(owner) + ArrayField.values.offset +pointer = ctypes.cast(view, ctypes.POINTER(ctypes.c_int)) +pointer[1] = 42 +assert list(owner.values) == [1, 42, 3] +owner.values[0] = 7 +assert bytes(view) == bytes(owner.values) +memoryview(view).cast("B")[:] = bytes((ctypes.c_int * 3)(7, 42, 9)) +assert list(owner.values) == [7, 42, 9] +del owner +assert list(view) == [7, 42, 9] + + +class OverlappingFields(ctypes.Union): + _fields_ = [("a", ctypes.c_ubyte * 8), ("b", ctypes.c_ubyte * 8)] + + +overlap = OverlappingFields() +overlap.a[:] = range(8) +memoryview(overlap.a).cast("B")[::2] = memoryview(overlap.b).cast("B")[:4] +assert list(overlap.a) == [0, 1, 1, 3, 2, 5, 3, 7] + +backing = bytearray(range(8)) +view = (ctypes.c_ubyte * 7).from_buffer(backing, 1) +view._objects.clear() # Alias detection must not depend on mutable retention metadata. +memoryview(view).cast("B")[::2] = memoryview(backing)[:4] +assert list(backing) == [0, 0, 2, 1, 4, 2, 6, 3] + +raw_owner = (ctypes.c_ubyte * 8)() +raw_views = [type(raw_owner).from_address(ctypes.addressof(raw_owner))] +if _sys.version_info >= (3, 14): + raw_views.append( + ctypes.memoryview_at(ctypes.addressof(raw_owner), ctypes.sizeof(raw_owner)) + ) +for raw_view in raw_views: + for source, dest in ((raw_owner, raw_view), (raw_view, raw_owner)): + raw_owner[:] = range(8) + memoryview(dest).cast("B")[::2] = memoryview(source).cast("B")[:4] + assert list(raw_owner) == [0, 1, 1, 3, 2, 5, 3, 7] + + +# A snapshotted source's release hook must run after the destination write. +raw_owner[:] = range(8) +destination_buffer = bytearray(b"abcdefgh") +destination_view = memoryview(destination_buffer) +release_events = [] + + +class ReleasingBuffer: + def __buffer__(self, flags): + return memoryview(raw_views[0]).cast("B") + + def __release_buffer__(self, view): + release_events.append(bytes(destination_buffer)) + destination_view.release() + destination_buffer.clear() + + +destination_view[:] = ReleasingBuffer() +assert release_events == [bytes(raw_owner)] +assert destination_buffer == b"" + + +# byref carries an address, including its byte offset, rather than the value +# stored in the referenced object. +pair = (ctypes.c_int * 2)(42, 99) +for offset in (0, ctypes.sizeof(ctypes.c_int)): + ref = ctypes.byref(pair, offset) + assert ctypes.cast(ref, ctypes.c_void_p).value == ctypes.addressof(pair) + offset + assert ( + ctypes.string_at(ref, ctypes.sizeof(ctypes.c_int)) + == bytes(pair)[offset : offset + ctypes.sizeof(ctypes.c_int)] + ) +zero = ctypes.c_size_t(0) +assert ctypes.string_at(ctypes.byref(zero), ctypes.sizeof(zero)) == bytes(zero) +param = ctypes.c_void_p.from_param(ctypes.addressof(zero)) +assert ctypes.cast(param, ctypes.c_void_p).value == ctypes.addressof(zero) +assert ctypes.string_at(param, ctypes.sizeof(zero)) == bytes(zero) +for read in ( + lambda p: ctypes.cast(p, ctypes.c_void_p), + lambda p: ctypes.string_at(p, 0), +): + try: + read(ctypes.c_char_p.from_param(b"x")) + except (TypeError, ctypes.ArgumentError): + pass + else: + raise AssertionError("non-pointer argument wrapper accepted") + print("done") + + +# Indexed compound objects are views of the element, not decoded scalars. +class IndexedPoint(ctypes.Structure): + _fields_ = [("x", ctypes.c_int)] + + +class IndexedInt(ctypes.c_int): + pass + + +for _element in (IndexedPoint, IndexedInt, ctypes.c_int * 2): + _owner = (_element * 2)() + _view = _owner[1] + assert type(_view) is _element + assert _view._b_base_ is _owner + assert ctypes.addressof(_view) == ctypes.addressof(_owner) + ctypes.sizeof(_element) + _pointer = ctypes.cast(_owner, ctypes.POINTER(_element)) + _pointer[1] = _pointer[1] + assert bytes(_pointer[1]) == bytes(_view) + +_array = (ctypes.c_int * 2)(1, 2) +_pointer = ctypes.pointer(_array) +for _value, _view in enumerate((_pointer[0], _pointer.contents), 42): + assert _view._b_base_ is _pointer + assert len(_view) == 2 + _view[1] = _value + assert _array[1] == _value + +_callback_type = ctypes.CFUNCTYPE(ctypes.c_int) +_callbacks = (_callback_type * 1)(_callback_type(lambda: 42)) +_callback = _callbacks[0] +assert _callback._b_base_ is _callbacks +_copied_callbacks = (_callback_type * 1)(_callback) +del _callback, _callbacks +gc.collect() +assert _copied_callbacks[0]() == 42 + + +class CallbackField(ctypes.Structure): + _fields_ = [("callback", _callback_type)] + + +assert CallbackField(_copied_callbacks[0]).callback() == 42 + +# Nested element keys and copies must retain both pointees after the source dies. +_nested = (((ctypes.POINTER(ctypes.c_int) * 1) * 1) * 2)() +_refs = [] +for _index in range(2): + _item = ctypes.c_int(_index) + _refs.append(weakref.ref(_item)) + _nested[_index][0][0] = ctypes.pointer(_item) +_copy = type(_nested)(*_nested) +del _nested, _item +gc.collect() +assert [ref().value for ref in _refs] == [0, 1] + +# Replacing a pointer view's contents updates its slot and retains the pointee. +_replacement = ctypes.c_int(42) +_replacement_ref = weakref.ref(_replacement) +_view = _copy[1][0][0] +_view.contents = _replacement +del _replacement, _view +gc.collect() +assert _replacement_ref() is not None +assert _copy[1][0][0].contents.value == 42 + +# Replacing a callback may reenter the same array from its finalizer. +_finalized = [] + + +class ReenteringCallback: + def __call__(self): + return 1 + + def __del__(self): + _finalized.append(_copied_callbacks[0]()) + _copied_callbacks[0] = _callback_type(lambda: 3) + + +_copied_callbacks[0] = _callback_type(ReenteringCallback()) +_copied_callbacks[0] = _callback_type(lambda: 2) +assert _finalized == [2] +assert _copied_callbacks[0]() == 3 + +# Pointer-valued scalar views retain their owner and write through to it. +for _type, _old, _new in ( + (ctypes.c_char_p, b"old", b"new"), + (ctypes.c_wchar_p, "old", "new"), +): + + class IndexedStringPointer(_type): + pass + + _owner = (IndexedStringPointer * 1)(_old) + _view = _owner[0] + _view.value = _new + assert _view._b_base_ is _owner + assert _owner[0].value == _new + _copy = type(_owner)(_view) + del _owner, _view + gc.collect() + assert _copy[0].value == _new + + +# Reentry must see matching pointer bytes and owners, including private copies. +class StringField(ctypes.Structure): + _fields_ = [("text", ctypes.c_char_p)] + + +class ReenteringBytes(bytes): + def __del__(self): + if _replace_record: + _strings[0] = StringField(_inner) + _events.append(_strings[0].text) + else: + _strings.text = _inner + _events.append(_strings.text) + + +_inner = b"inner replacement" * 20 +for _replace_record in (False, True): + _events = [] + if _replace_record: + _strings = (StringField * 1)(StringField(ReenteringBytes(b"old"))) + _strings[0] = StringField(b"outer replacement") + assert _strings[0].text == _inner + else: + _strings = StringField(ReenteringBytes(b"old")) + _strings.text = b"outer replacement" + assert _strings.text == _inner + assert _events == [_inner] + + +# py_object views locate the referent in their owner, including after a copy. +class IndexedObject(ctypes.py_object): + pass + + +_object = {} +_object_scalar = IndexedObject(_object) +_objects = (IndexedObject * 1)(_object_scalar) +assert type(_objects).from_buffer(memoryview(_objects))[0].value is _object +_object_pointer = ctypes.cast(_objects, ctypes.POINTER(IndexedObject)) +_object_pointer[0] = _object_scalar +_object_scalar.value = object() +assert _object_pointer[0].value is _object +_copy = type(_objects)(_objects[0]) +del _objects, _object_pointer +gc.collect() +assert _copy[0].value is _object +_copy[0].value = None +assert _copy[0].value is None + + +class RetentionKey(str): + __hash__ = str.__hash__ + + def __eq__(self, other): + raise AssertionError("py_object lookup called key equality") + + +_copy[0].value = _object +_copy._objects.clear() +_copy._objects[RetentionKey("0:0")] = _object +assert _copy[0].value is _object + +# Generated endian types return scalars, but their user subclasses return views. +_swapped = ( + ctypes.c_uint32.__ctype_be__ + if _sys.byteorder == "little" + else ctypes.c_uint32.__ctype_le__ +) +_words = (_swapped * 1).from_buffer_copy(b"\x01\x02\x03\x04") +_word_pointer = ctypes.cast(_words, ctypes.POINTER(_swapped)) +_expected = int.from_bytes( + bytes(_words), "big" if _sys.byteorder == "little" else "little" +) +assert type(_words[0]) is type(_word_pointer[0]) is int +assert _words[0] == _word_pointer[0] == _expected +_words[0] = 0x11223344 +assert bytes(_words) == bytes(_swapped(0x11223344)) +_word_pointer[0] = 0x55667788 +assert bytes(_words) == bytes(_swapped(0x55667788)) + + +class IndexedSwapped(_swapped): + pass + + +_words = (IndexedSwapped * 1).from_buffer_copy(b"\x01\x02\x03\x04") +assert type(_words[0]) is IndexedSwapped +assert _words[0].value == int.from_bytes(bytes(_words), _sys.byteorder) + +# Field assignment copies encoded instances; only numeric inputs are converted. +for _base in (ctypes.Structure, ctypes.Union): + for _field_type in (_swapped, IndexedSwapped): + + class EndianField(_base): + _fields_ = [("word", _field_type)] + + _value = _field_type(0x01020304) + _aggregate = EndianField(_value) + assert bytes(_aggregate) == bytes(_value) + _field = EndianField.from_buffer_copy(bytes(_value)).word + assert getattr(_field, "value", _field) == _value.value + if _field_type is IndexedSwapped: + _aggregate.word = 0x55667788 + assert bytes(_aggregate) == bytes(IndexedSwapped(0x55667788)) + +# Endian fields reject the native sibling rather than converting its bytes. +assert not issubclass(_swapped, ctypes.c_uint32) +for _base in ( + (ctypes.BigEndianStructure, ctypes.BigEndianUnion) + if _sys.byteorder == "little" + else (ctypes.LittleEndianStructure, ctypes.LittleEndianUnion) +): + + class ConvertedEndianField(_base): + _fields_ = [("word", ctypes.c_uint32)] + + assert ConvertedEndianField._fields_[0][1] is _swapped + try: + ConvertedEndianField(ctypes.c_uint32(0x01020304)) + except TypeError: + pass + else: + raise AssertionError("incompatible native field value accepted") + _value = _swapped(0x01020304) + assert bytes(ConvertedEndianField(_value)) == bytes(_value) + + +# Array assignment cannot complete a pointer field's missing target type. +class IncompletePointer(ctypes._Pointer): + pass + + +class IncompletePointerField(ctypes.Structure): + _fields_ = [("value", IncompletePointer)] + + +_field = IncompletePointerField() +_before = bytes(_field) +try: + _field.value = (ctypes.c_int * 1)(42) +except TypeError: + pass +else: + raise AssertionError("array accepted for an incomplete pointer field") +assert bytes(_field) == _before + +# Indexed writes use the element's conversion, not the input object's layout. +for _container, _input, _expected in ( + (ctypes.pointer(ctypes.c_float()), 1.5, 1.5), + ((ctypes.c_char * 1)(), ctypes.c_char(b"x"), b"x"), + ((ctypes.c_byte * 1)(), 257, 1), +): + _container[0] = _input + assert _container[0] == _expected + +for _container in ((ctypes.c_int * 1)(), ctypes.pointer(ctypes.c_int())): + try: + _container[0] = ctypes.c_float(1.5) + except TypeError: + pass + else: + raise AssertionError("incompatible indexed value accepted") + assert _container[0] == 0 + + +class FailingFloat: + def __float__(self): + raise LookupError("conversion failed") + + +for _base in (ctypes.Structure, ctypes.Union): + + class ObjectAndFloat(_base): + _fields_ = [("object", ctypes.py_object), ("number", ctypes.c_float)] + + _record = ObjectAndFloat() + _value = object() + _record.object = _value + assert _record.object is _value + _before = bytes(_record) + try: + _record.number = FailingFloat() + except LookupError: + pass + else: + raise AssertionError("conversion error suppressed") + assert bytes(_record) == _before + + +# Tuple temporaries are finalized after their bytes have reached the target. +_events = [] + + +class TemporaryRecord(ctypes.Structure): + _fields_ = [("number", ctypes.c_int)] + + def __del__(self): + if self._b_base_ is None: + _events.append(_records[0].number) + _records[0].number = 99 + + +_records = (TemporaryRecord * 1)() +_records[0] = (42,) +assert _events == [42] +assert _records[0].number == 99 + + +# Raw addresses can point inside the buffer already owned by a scalar view. +_events = [] + + +class OwnedBytes(bytes): + def __del__(self): + _events.append("released") + + +class StringPointer(ctypes.c_char_p): + pass + + +class OwnedStringField(ctypes.Structure): + _fields_ = [("text", StringPointer)] + + +_record = OwnedStringField() +_record.text.value = OwnedBytes(b"owner") +_address = ctypes.cast(_record.text, ctypes.c_void_p).value +_record.text.value = _address + 1 +gc.collect() +assert _events == [] +assert _record.text.value == b"wner" + +# Self-copy must not build a new private holder around every previous copy. +_marker = b"ctypes-self-copy-backing-store" +_strings = (StringField * 1)(StringField(_marker)) +for _ in range(32): + _strings[0] = _strings[0] +gc.collect() +assert ( + sum( + type(obj) is tuple + and any(type(item) is bytes and item == _marker + b"\0" for item in obj) + for obj in gc.get_objects() + ) + <= 1 +) +assert _strings[0].text == _marker + +# Mutating _type_ must not change the initialized setter or its write width. +for _code in ("h", "q", "f"): + + class MutableInt(ctypes.c_int): + pass + + _array = (MutableInt * 2)(0, 0x1234) + MutableInt._type_ = _code + _array[0] = -2 + assert bytes(_array) == bytes(ctypes.c_int(-2)) + bytes(ctypes.c_int(0x1234)) + assert _array[0].value == -2 + assert MutableInt(-3).value == -3 + +# Native calls must use the same initialized converter for arguments and results. +MutableInt._type_ = "h" +_identity = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int)(lambda value: value) +_identity.argtypes = [MutableInt] +assert _identity(MutableInt(-65537)) == -65537 +_identity.argtypes = [ctypes.c_int] +_identity.restype = MutableInt +_result = _identity(-65537) +assert getattr(_result, "value", _result) == -65537 + + +class MutablePointer(ctypes.c_void_p): + pass + + +MutablePointer._type_ = "i" +assert ctypes.cast(ctypes.c_void_p(123), MutablePointer).value == 123 +MutableInt._type_ = "P" +try: + ctypes.cast(ctypes.c_void_p(123), MutableInt) +except TypeError: + pass +else: + raise AssertionError("cast accepted a scalar integer type") + + +class SubclassBits(ctypes.Structure): + _fields_ = [("field", MutableInt, 3)] + + +_bits = SubclassBits(3) +assert isinstance(_bits.field, MutableInt) +_bits.field.value = 2 +assert _bits.field.value == 2 + +for _scalar, _text_value in ((ctypes.c_char, b"ab"), (ctypes.c_wchar, "ab")): + + class MutableChar(_scalar): + pass + + class TextField(ctypes.Structure): + _fields_ = [("text", MutableChar * 4)] + + _text = TextField(_text_value) + MutableChar._type_ = "i" + assert _text.text == _text_value + _text.text = _text_value + assert _text.text == _text_value + +if _sys.platform == "win32": + + class BSTR(ctypes._SimpleCData): + _type_ = "X" + + _bstr = (BSTR * 1)() + _bstr[0] = None + assert bytes(_bstr) == bytes(ctypes.sizeof(ctypes.c_void_p)) + + +# The py_object payload, not only the instance dictionary, closes this cycle. +class ObjectOwner: + pass + + +_owner = ObjectOwner() +_owner.value = ctypes.py_object(_owner) +_ref = weakref.ref(_owner) +del _owner +gc.collect() +assert _ref() is None + + +# Values written through a pointer remain visible through sibling views. +for _borrowed in (False, True): + _storage = bytearray(ctypes.sizeof(ctypes.py_object)) + _value = ctypes.py_object.from_buffer(_storage) if _borrowed else ctypes.py_object() + _value.value = None + _pointer = ctypes.cast(ctypes.byref(_value), ctypes.POINTER(ctypes.py_object)) + _sibling = ctypes.pointer(_value) + _object = object() + _pointer[0] = _object + assert _value.value is _object and _sibling[0] is _object + _pointer.contents.value = object() + assert _value.value is _pointer[0] is _sibling[0] + +if _sys.implementation.name == "rustpython": + _cast_value = ctypes.py_object(None) + _cast_ref = weakref.ref(_cast_value) + _cast_pointer = ctypes.cast( + ctypes.byref(_cast_value), ctypes.POINTER(ctypes.py_object) + ) + del _cast_value + gc.collect() + assert _cast_ref() is not None + del _cast_pointer + gc.collect() + assert _cast_ref() is None + + +# A temporary pointer field writes ownership into its containing structure. +class ObjectPointerHolder(ctypes.Structure): + _fields_ = [("pointer", ctypes.POINTER(ctypes.py_object))] + + +_temporary_array = (ctypes.py_object * 1)(None) +_temporary_holder = ObjectPointerHolder( + ctypes.cast(_temporary_array, ctypes.POINTER(ctypes.py_object)) +) +_temporary_value = ObjectOwner() +_temporary_ref = weakref.ref(_temporary_value) +_temporary_holder.pointer[0] = _temporary_value +assert _temporary_array[0] is _temporary_value +# A weak writer registration must not extend the holder or value's lifetime. +del _temporary_value, _temporary_holder +gc.collect() +assert _temporary_ref() is None + +# Pointer writes through a borrowed view must remain visible to its exporter. +_exporter_array = (ctypes.py_object * 1)(None) +_exporter_pointer = ctypes.pointer(ctypes.py_object.from_buffer(_exporter_array)) +for _exporter_value in (object(), object()): + _exporter_pointer[0] = _exporter_value + assert _exporter_array[0] is _exporter_value +del _exporter_pointer, _exporter_array, _exporter_value + +# A warmed writer must follow contents changes without retaining old storage. +_value = ctypes.py_object(None) +_pointer = ctypes.pointer(_value) +_pointer[0] = object() +_ref = weakref.ref(_value) +_value = ctypes.py_object(None) +_pointer.contents = _value +assert _ref() is None +_pointer[0] = _object +assert _value.value is _object + +# Different owners can describe the same address. +_value = ctypes.py_object.from_buffer(_storage) +_pointer = ctypes.pointer(_value) +_pointer[0] = _object +_other = ctypes.py_object.from_buffer(_storage) +_pointer.contents = _other +_pointer[0] = object() +assert _other.value is _pointer[0] + +_pointer = ctypes.cast(ctypes.byref(_value), ctypes.POINTER(ctypes.py_object)) +_pointer.contents = _other +_pointer[0] = object() +assert _other.value is _pointer[0] +assert _value.value is _pointer[0] + +# A cast array view also registers its enclosing allocation, not just contents. +_nested = ((ctypes.py_object * 1) * 1)() +_nested[0][0] = None +_pointer = ctypes.cast(_nested[0], ctypes.POINTER(ctypes.py_object)) +_other = ctypes.py_object.from_buffer(_nested) +_pointer.contents = _other +_pointer[0] = object() +assert _nested[0][0] is _other.value is _pointer[0] + +# Changing the index can bring a smaller cast source back into range. +_pair_type = ctypes.py_object * 2 +_buffer = bytearray(ctypes.sizeof(_pair_type)) +_small = (ctypes.py_object * 1).from_buffer(_buffer) +_large = _pair_type.from_buffer(_buffer) +_inner = ctypes.cast(ctypes.byref(_small), ctypes.POINTER(_pair_type)) +_inner.contents = _large +_pointer = ctypes.cast(_inner.contents, ctypes.POINTER(ctypes.py_object)) +_pointer[1] = object() +_pointer[0] = object() +assert _small[0] is _large[0] is _pointer[0] + +_backing = bytearray(ctypes.sizeof(ctypes.py_object)) +_value = ctypes.py_object.from_buffer(_backing) +_value.value = None +try: + _backing.extend(b"x") +except BufferError: + pass +else: + raise AssertionError("assigning None released the buffer export") + + +# An aggregate assignment can overlap a reader smaller than the written value. +_small = (ctypes.py_object * 1).from_buffer(bytearray(ctypes.sizeof(_pair_type))) +_pointer = ctypes.cast(ctypes.byref(_small), ctypes.POINTER(_pair_type)) +for _value in (object(), object()): + _pointer[0] = _pair_type(_value, None) + assert _small[0] is _value + + +# Independent exports share provenance without retaining the writer or value. +_storage = bytearray(ctypes.sizeof(ctypes.py_object)) +_writer = ctypes.py_object.from_buffer(_storage) +_reader = ctypes.py_object.from_buffer(memoryview(_storage)) +_pointer = ctypes.pointer(_writer) +for _direct in (False, True): + _value = ObjectOwner() + if _direct: + _writer.value = _value + else: + _pointer[0] = _value + assert _reader.value is _value +_ref = weakref.ref(_value) +del _value, _writer, _pointer +gc.collect() +assert _ref() is None + +# Field caches on a cast pointer follow later assignments to the source array. +_roots = [ctypes.py_object(None), ctypes.py_object(None)] +_holders = (ObjectPointerHolder * 2)( + *(ObjectPointerHolder(ctypes.pointer(_root)) for _root in _roots) +) +_pointer = ctypes.cast(_holders, ctypes.POINTER(ObjectPointerHolder)) +for _index in range(2): + _pointer[_index].pointer[0] = object() +_replacement = ctypes.py_object(None) +_holders[1].pointer = ctypes.pointer(_replacement) +_pointer[1].pointer[0] = _object +assert _replacement.value is _object + +# A native exporter must see direct writes as well as pointer writes. +_native = (ctypes.py_object * 1)(None) +_view = ctypes.py_object.from_buffer(_native) +_view.value = _object +assert _native[0] is _object + + +# Pointer-backed exporters need the contents provenance fallback. +_source = ctypes.py_object(None) +_exporter = ctypes.pointer(_source) +_view = ctypes.py_object.from_buffer(_exporter.contents) +_view.value = _object +assert _source.value is _object + +# A cast can retain a value beyond its source view's declared extent. +_storage = bytearray(2 * ctypes.sizeof(ctypes.py_object)) +_writer = (ctypes.py_object * 1).from_buffer(_storage) +_reader = ctypes.py_object.from_buffer(_storage, ctypes.sizeof(ctypes.py_object)) +_pointer = ctypes.cast(_writer, ctypes.POINTER(ctypes.py_object)) +_pointer[1] = _object +assert _reader.value is _object + +# byref keeps separate metadata; later aliases must still find its writes. +_pointer = ctypes.cast(ctypes.byref(_writer), ctypes.POINTER(ctypes.py_object)) +_pointer[1] = object() +del _reader +_reader = ctypes.py_object.from_buffer(_storage, ctypes.sizeof(ctypes.py_object)) +assert _reader.value is _pointer[1] + + +# A copied pointer outlives its original buffer view. Reentrant conversion +# must publish the outer write's range even when it redirects the pointer. +class ReentrantObjectCell(ctypes.Structure): + _fields_ = [("number", ctypes.c_int), ("value", ctypes.py_object)] + + +class ReentrantObjectHolder(ctypes.Structure): + _fields_ = [("pointer", ctypes.POINTER(ReentrantObjectCell))] + + +_pointer_size = ctypes.sizeof(ctypes.c_void_p) +_cell_size = ctypes.sizeof(ReentrantObjectCell) +_storage = bytearray(_pointer_size + 2 * _cell_size) +_source = ctypes.POINTER(ReentrantObjectCell).from_buffer(_storage) +_address = ctypes.addressof(_source) + _pointer_size +ctypes.memmove( + ctypes.addressof(_source), ctypes.byref(ctypes.c_void_p(_address)), _pointer_size +) +_holder = ReentrantObjectHolder(_source) +del _source +_redirected = ReentrantObjectCell.from_address(_address + _cell_size) +_outer_value, _inner_value = object(), object() + + +class RedirectObjectWrite: + def __index__(self): + _holder.pointer.contents = _redirected + _holder.pointer[0] = ReentrantObjectCell(3, _inner_value) + return 7 + + +_holder.pointer[0] = (RedirectObjectWrite(), _outer_value) +assert ReentrantObjectCell.from_buffer(_storage, _pointer_size).value is _outer_value +assert ReentrantObjectCell.from_buffer(_storage, _pointer_size).number == 7 + + +# Retargeting must not hide old addresses while the writer still owns the value. +_object = object() +_original = ctypes.py_object() +_redirected = ctypes.py_object() +_pointer = ctypes.cast( + ctypes.c_void_p(ctypes.addressof(_original)), ctypes.POINTER(ctypes.py_object) +) +_pointer[0] = _object +_pointer.contents = ctypes.py_object.from_address(ctypes.addressof(_redirected)) +for _value in ( + None, + _object, + ctypes.py_object.from_address(ctypes.addressof(_original)), +): + _pointer[0] = _value + assert _original.value is _object + assert _redirected.value is (None if _value is None else _object) + + +# These identity and checker-cache cases extend the canonical ctypes tests. +import sys as _sys +import unittest as _unittest + + +class _CtypesTypeIdentityTests(_unittest.TestCase): + def test_callback_requires_class_local_argtypes_metadata(self): + class Base(ctypes._CFuncPtr): + _flags_ = ctypes._FUNCFLAG_CDECL + _argtypes_ = () + _restype_ = c_int + + class Child(Base): + _flags_ = ctypes._FUNCFLAG_CDECL + _restype_ = c_int + + for _ in range(2): + with self.assertRaisesRegex(TypeError, "no argtypes"): + Child(lambda: 37) + Child._argtypes_ = () + + callback = ctypes.CFUNCTYPE(c_int)(lambda: 37) + ordinary = Child(ctypes.cast(callback, ctypes.c_void_p).value) + self.assertIsNone(ordinary.argtypes) + self.assertEqual(ordinary(), 37) + + def test_function_uses_cached_argtypes_metadata(self): + class Prototype(ctypes._CFuncPtr): + _flags_ = ctypes._FUNCFLAG_CDECL + _argtypes_ = () + _restype_ = c_int + + Prototype._argtypes_ = (c_int,) + function = Prototype(lambda: 37) + self.assertEqual(function.argtypes, ()) + self.assertEqual(function(), 37) + ordinary = Prototype(ctypes.cast(function, ctypes.c_void_p).value) + self.assertEqual(ordinary.argtypes, ()) + self.assertEqual(ordinary(), 37) + ordinary.argtypes = (c_int,) + self.assertEqual(ordinary.argtypes, (c_int,)) + ordinary.argtypes = None + self.assertEqual(ordinary.argtypes, ()) + self.assertEqual(ordinary(), 37) + + @_unittest.skipUnless( + _sys.implementation.name == "rustpython", + "CPython 3.15 crashes on missing callback restype", + ) + def test_callback_missing_restype_is_rejected_safely(self): + class Prototype(ctypes._CFuncPtr): + _flags_ = ctypes._FUNCFLAG_CDECL + _argtypes_ = () + + with self.assertRaisesRegex( + TypeError, "invalid result type for callback function" + ): + Prototype(lambda: 37) + + def test_restype_deletion_restores_class_checker(self): + class Checked(c_int): + _check_retval_ = staticmethod(lambda value: ("class", value.value)) + + class Prototype(ctypes._CFuncPtr): + _flags_ = ctypes._FUNCFLAG_CDECL + _argtypes_ = () + _restype_ = Checked + + callback = ctypes.CFUNCTYPE(c_int)(lambda: 23) + function = Prototype(ctypes.cast(callback, ctypes.c_void_p).value) + function.restype = None + del function.restype + self.assertIs(function.restype, Checked) + self.assertEqual(function(), ("class", 23)) + del function.restype + self.assertEqual(function(), ("class", 23)) + + def test_restype_deletion_reenters_before_clearing_checker(self): + function = ctypes.CFUNCTYPE(c_int)(lambda: 17) + events = [] + + class Nested(c_int): + _check_retval_ = staticmethod(lambda value: ("nested", value.value)) + + class Restype: + def __call__(self, value): + return value + + def __del__(self): + events.append(function.restype) + function.restype = Nested + + function.restype = Restype() + del function.restype + self.assertEqual(events, [c_int]) + self.assertIs(function.restype, Nested) + result = function() + self.assertIs(type(result), Nested) + self.assertEqual(result.value, 17) + + def test_redundant_simple_base_uses_primary_base(self): + class Redundant(c_int, ctypes._SimpleCData): + pass + + value = Redundant(42) + self.assertIs(Redundant.__base__, c_int) + self.assertTrue(repr(value).startswith(" 0 + assert gc.is_tracked(frozen_referrer) + assert not contains(gc.get_objects(), frozen_referrer) + assert not contains(gc.get_objects(None), frozen_referrer) + assert not contains(gc.get_objects(-1), frozen_referrer) + for generation in range(3): + assert not contains(gc.get_objects(generation), frozen_referrer) + referrers = gc.get_referrers(target) + assert not contains(referrers, frozen_referrer) + assert contains(referrers, fresh_referrer) + # Freezing changes the scanned generations, not the object's edges. + assert gc.get_referents(frozen_referrer) == [target] + + gc.unfreeze() + assert contains(gc.get_objects(2), frozen_referrer) + assert contains(gc.get_referrers(target), frozen_referrer) + finally: + gc.unfreeze() + if enabled: + gc.enable() + + +check_frozen_introspection() + + +def check_gc_configuration(): + import struct + import unittest + + test = unittest.TestCase() + old_thresholds = gc.get_threshold() + old_debug = gc.get_debug() + enabled = gc.isenabled() + gc.disable() + try: + for flags in (0, 1 << 30, -128): + gc.set_debug(flags) + assert gc.get_debug() == flags + gc.set_debug(0) + for values in ((-1, -2, -3), (0, 10, 20), (2**31 - 1, -(2**31), 0)): + gc.set_threshold(*values) + assert gc.get_threshold() == values + gc.set_threshold(7) + assert gc.get_threshold() == (7, -(2**31), 0) + gc.set_threshold(8, 9) + assert gc.get_threshold() == (8, 9, 0) + + calls = [] + + class Index: + def __init__(self, value): + self.value = value + + def __index__(self): + calls.append(self.value) + return self.value + + gc.set_threshold(Index(12), Index(13), Index(14)) + assert calls == [12, 13, 14] + assert gc.get_threshold() == (12, 13, 14) + calls.clear() + for args in ((), (Index(1), Index(2), Index(3), Index(4))): + with test.assertRaises(TypeError) as error: + gc.set_threshold(*args) + assert str(error.exception) == "gc.set_threshold requires 1 to 3 arguments" + with test.assertRaises(TypeError) as error: + gc.set_threshold(Index(1), threshold1=Index(2)) + assert str(error.exception) == "set_threshold() takes no keyword arguments" + assert calls == [] + + # A failing later conversion must not partially update the settings. + with test.assertRaises(TypeError): + gc.set_threshold(Index(21), object()) + assert calls == [21] + assert gc.get_threshold() == (12, 13, 14) + long_is_int = struct.calcsize("l") == 4 + for value, message in ( + ( + 2**31, + "Python int too large to convert to C long" + if long_is_int + else "signed integer is greater than maximum", + ), + ( + -(2**31) - 1, + "Python int too large to convert to C long" + if long_is_int + else "signed integer is less than minimum", + ), + (2**100, "Python int too large to convert to C long"), + (-(2**100), "Python int too large to convert to C long"), + ): + with test.assertRaises(OverflowError) as error: + gc.set_threshold(value) + assert str(error.exception) == message + for function in (gc.collect, gc.set_debug): + for value in (2**31, -(2**31) - 1, 2**100): + with test.assertRaises(OverflowError) as error: + function(value) + assert ( + str(error.exception) == "Python int too large to convert to C int" + ) + finally: + gc.set_debug(old_debug) + gc.set_threshold(*old_thresholds) + if enabled: + gc.enable() + + +check_gc_configuration() + + +def check_gc_callback_semantics(): + import sys + + enabled = gc.isenabled() + saved_callbacks = gc.callbacks[:] + saved_hook = sys.unraisablehook + gc.disable() + gc.callbacks.clear() + try: + calls = [] + + def recursive(phase, info): + calls.append(phase) + calls.append(gc.collect()) + + gc.callbacks.append(recursive) + gc.collect() + assert calls == ["start", 0, "stop", 0] + + def second(phase, info): + calls.append(("second", phase)) + + def appended(phase, info): + calls.append(("appended", phase)) + + def first(phase, info): + calls.append(("first", phase)) + if phase == "start": + if mutation == "remove": + gc.callbacks.remove(first) + elif mutation == "append": + gc.callbacks.append(appended) + else: + gc.callbacks.clear() + + for mutation, expected in ( + ("remove", [("first", "start"), ("second", "stop")]), + ( + "append", + [ + ("first", "start"), + ("second", "start"), + ("appended", "start"), + ("first", "stop"), + ("second", "stop"), + ("appended", "stop"), + ], + ), + ("clear", [("first", "start")]), + ): + calls.clear() + gc.callbacks[:] = [first, second] + gc.collect() + assert calls == expected, calls + + errors = [] + error = ValueError("callback failed") + + def unraisable(args): + assert gc.collect() == 0 + errors.append((args.exc_value, args.err_msg, args.object)) + + sys.unraisablehook = unraisable + + def failing(phase, info): + raise error + + class BadRepr: + def __call__(self, phase, info): + raise error + + def __repr__(self): + raise RuntimeError("repr failed") + + for callback, message in ( + (failing, "Exception ignored while calling GC callback " + repr(failing)), + (BadRepr(), None), + ): + errors.clear() + calls.clear() + gc.callbacks[:] = [callback, second] + gc.collect() + assert calls == [("second", "start"), ("second", "stop")] + assert errors == [(error, message, None), (error, message, None)] + finally: + gc.callbacks[:] = saved_callbacks + sys.unraisablehook = saved_hook + if enabled: + gc.enable() + + +check_gc_callback_semantics() + print("ok") diff --git a/extra_tests/snippets/stdlib_genericalias.py b/extra_tests/snippets/stdlib_genericalias.py new file mode 100644 index 00000000000..ddfb6d5587a --- /dev/null +++ b/extra_tests/snippets/stdlib_genericalias.py @@ -0,0 +1,226 @@ +from types import GenericAlias + +from testutils import assert_raises + + +class Parameter: + def __typing_subst__(self, value): + return value + + +parameter = Parameter() + + +# Construction does not inspect arguments. Both entry points populate the cache +# using the attributes present at the first lookup, rather than construction. +class LateParameter: + __parameters__ = (parameter,) + + def __repr__(self): + return "late_parameter" + + +for materialize in (False, True): + late = LateParameter() + alias = GenericAlias(list, late) + if materialize: + cached = alias.__parameters__ + assert cached == (parameter,) + late.__typing_subst__ = lambda value: value + if materialize: + with assert_raises(TypeError) as caught: + alias[int] + assert str(caught.exception) == ( + "argument late_parameter with __typing_subst__ was not found in __parameters__" + ) + assert alias.__parameters__ is cached + else: + assert alias[int] == list[int] + cached = alias.__parameters__ + assert cached == (late,) + assert alias.__parameters__ is cached + +late = LateParameter() +alias = GenericAlias(list, late) +late.__typing_subst__ = lambda value: value +assert alias.__parameters__ == (late,) +assert alias[int] == list[int] + +# Empty tuples are cached too, even if parameters appear later. +empty = LateParameter() +empty.__parameters__ = () +alias = GenericAlias(list, empty) +cached = alias.__parameters__ +empty.__typing_subst__ = lambda value: value +assert alias.__parameters__ is cached +assert cached == () +with assert_raises(TypeError): + alias[int] + + +# Lookup errors happen lazily and leave the cache uninitialized for a retry. +class FailingParameter: + def __init__(self, failing_attribute): + self.failing_attribute = failing_attribute + self.fail = True + self.lookups = [] + + def __getattribute__(self, name): + if name in ("__typing_subst__", "__parameters__"): + self.lookups.append(name) + if name == self.failing_attribute and self.fail: + raise RuntimeError("parameter lookup failed") + return object.__getattribute__(self, name) + + __parameters__ = (parameter,) + + +for attribute in ("__typing_subst__", "__parameters__"): + for subscribe in (False, True): + failing = FailingParameter(attribute) + alias = GenericAlias(list, failing) + assert failing.lookups == [] + with assert_raises(RuntimeError) as caught: + if subscribe: + alias[int] + else: + alias.__parameters__ + assert str(caught.exception) == "parameter lookup failed" + failing.fail = False + cached = alias.__parameters__ + assert cached == (parameter,) + count = len(failing.lookups) + assert alias.__parameters__ is cached + assert len(failing.lookups) == count + + +# A nested lookup may populate the cache, but the outer calculation replaces it. +inner_parameter = Parameter() +outer_parameter = Parameter() + + +class ReentrantParameter: + entered = False + + @property + def __parameters__(self): + if not self.entered: + self.entered = True + self.inner = self.alias.__parameters__ + return (outer_parameter,) + return (inner_parameter,) + + +reentrant = ReentrantParameter() +reentrant.alias = GenericAlias(list, reentrant) +cached = reentrant.alias.__parameters__ +assert reentrant.inner == (inner_parameter,) +assert cached == (outer_parameter,) +assert cached is reentrant.alias.__parameters__ +assert cached is not reentrant.inner + + +# A cyclic parameter lookup raises rather than deadlocking or overflowing Rust. +class RecursiveParameter: + recurse = True + + @property + def __parameters__(self): + if self.recurse: + return self.alias.__parameters__ + return (parameter,) + + +recursive = RecursiveParameter() +recursive.alias = GenericAlias(list, recursive) +with assert_raises(RecursionError): + recursive.alias.__parameters__ +recursive.recurse = False +assert recursive.alias.__parameters__ == (parameter,) + +# Substitution and unpacking construct aliases with their own lazy caches. +failing = FailingParameter("__parameters__") +result = GenericAlias(list, parameter)[failing] +assert failing.lookups == [] +with assert_raises(RuntimeError): + result.__parameters__ + +failing = FailingParameter("__parameters__") +original = GenericAlias(tuple, failing) +starred = next(iter(original)) +assert failing.lookups == [] +with assert_raises(RuntimeError): + starred.__parameters__ +failing.fail = False +assert starred.__parameters__ == (parameter,) +failing.__parameters__ = () +assert original.__parameters__ == () +assert starred.__parameters__ == (parameter,) + +# Concurrent descriptor callbacks can overlap without holding the cache lock. +import threading + +barrier = threading.Barrier(2) + + +class ConcurrentParameter: + @property + def __parameters__(self): + barrier.wait(timeout=10) + return (parameter,) + + +concurrent = GenericAlias(list, ConcurrentParameter()) +results = [] +errors = [] + + +def read_parameters(): + try: + results.append(concurrent.__parameters__) + except BaseException as error: + errors.append(error) + + +threads = [threading.Thread(target=read_parameters) for _ in range(2)] +for thread in threads: + thread.start() +for thread in threads: + thread.join(timeout=15) +assert all(not thread.is_alive() for thread in threads) +assert errors == [] +assert results == [(parameter,), (parameter,)] +cached = concurrent.__parameters__ +assert any(cached is result for result in results) +assert concurrent.__parameters__ is cached + + +# Failure in the outer calculation clears an inner successful cache as well. +class ReentrantFailure: + entered = False + fail = True + + @property + def __parameters__(self): + if not self.entered: + self.entered = True + self.inner = self.alias.__parameters__ + if self.fail: + raise RuntimeError("outer lookup failed") + return (inner_parameter,) if self.fail else (outer_parameter,) + + +for subscribe in (False, True): + failure = ReentrantFailure() + failure.alias = GenericAlias(list, failure) + with assert_raises(RuntimeError) as caught: + if subscribe: + failure.alias[int] + else: + failure.alias.__parameters__ + assert str(caught.exception) == "outer lookup failed" + assert failure.inner == (inner_parameter,) + failure.fail = False + cached = failure.alias.__parameters__ + assert cached == (outer_parameter,) + assert failure.alias.__parameters__ is cached diff --git a/extra_tests/snippets/stdlib_hashlib.py b/extra_tests/snippets/stdlib_hashlib.py index f3400aed57d..9cbc6bffc7e 100644 --- a/extra_tests/snippets/stdlib_hashlib.py +++ b/extra_tests/snippets/stdlib_hashlib.py @@ -1,5 +1,7 @@ +import _hashlib import _md5 import _sha1 +import array import hashlib from testutils import assert_raises @@ -64,3 +66,17 @@ # narrower than the length asked for, converting the argument fails first. with assert_raises(OverflowError): hashlib.pbkdf2_hmac("sha256", b"password", b"salt", 1, 2**62) + + +# Invalid names use the native constructor's bounded type diagnostic. +for value, name in ( + (None, "None"), + (42, "int"), + (b"sha256", "bytes"), + (array.array("b"), "array.array"), + (type("x" * 60, (), {})(), "x" * 50), + (type("€" * 17, (), {})(), "€" * 16), +): + with assert_raises(TypeError) as caught: + _hashlib.new(value) + assert str(caught.exception) == f"new() argument 'name' must be str, not {name}" diff --git a/extra_tests/snippets/stdlib_imp.py b/extra_tests/snippets/stdlib_imp.py index 9fd5f8a36fa..b5184e89a01 100644 --- a/extra_tests/snippets/stdlib_imp.py +++ b/extra_tests/snippets/stdlib_imp.py @@ -1,7 +1,7 @@ import _imp import time as import_time -from testutils import assert_raises +from testutils import assert_raises, skip_if_unsupported assert _imp.is_builtin("time") == True assert _imp.is_builtin("os") == False @@ -23,7 +23,8 @@ def __init__(self, name): # assert imp_time.sleep == import_time.sleep B = FakeSpec("not existing module") -assert _imp.create_builtin(B) == None +with assert_raises(ModuleNotFoundError): + _imp.create_builtin(B) _imp.exec_builtin(imp_time) == 0 @@ -42,3 +43,45 @@ def __init__(self, name): assert ispkg is False assert origname == "__hello__" assert _imp.get_frozen_object("__hello__", data).co_name == "" + + +def test_lazy_attributes_eager_registry(): + # CPython accepts any first argument and a string name. In an eager-only + # interpreter there are no pending lazy module names to remove. + for modobj in (None, object(), {}, 42): + assert _imp._set_lazy_attributes(modobj, "package.module") is None + assert _imp._set_lazy_attributes(modobj, "\ud800") is None + + for name in (None, 1, b"package.module", [], {}): + with assert_raises(TypeError): + _imp._set_lazy_attributes(None, name) + + with assert_raises(TypeError): + _imp._set_lazy_attributes(modobj=None, name="package.module") + + class ModuleName(str): + hashes = 0 + + def __hash__(self): + self.hashes += 1 + return 42 + + name = ModuleName("package.module") + assert _imp._set_lazy_attributes(None, name) is None + assert name.hashes == 1 + + class UnhashableName(str): + __hash__ = None + + with assert_raises(TypeError): + _imp._set_lazy_attributes(None, UnhashableName("package.module")) + + class HashErrorName(str): + def __hash__(self): + raise RuntimeError("name hash failed") + + with assert_raises(RuntimeError): + _imp._set_lazy_attributes(None, HashErrorName("package.module")) + + +skip_if_unsupported(3, 15, test_lazy_attributes_eager_registry) diff --git a/extra_tests/snippets/stdlib_input_readline.py b/extra_tests/snippets/stdlib_input_readline.py new file mode 100644 index 00000000000..5340e3dbf2f --- /dev/null +++ b/extra_tests/snippets/stdlib_input_readline.py @@ -0,0 +1,144 @@ +"""Interactive input read-ahead belongs to the terminal, not its caller thread.""" + +import os +import sys + +if os.name == "posix" and hasattr(os, "openpty"): + import errno + import select + import subprocess + import time + + def read_until(fd, marker, buffers, closed): + deadline = time.monotonic() + 20 + while marker not in buffers[fd]: + remaining = deadline - time.monotonic() + assert remaining > 0, (marker, buffers) + # Drain both terminals, even while waiting for the other one's + # prompt. On BSD, unread output can block tcsetattr(TCSADRAIN) + # when the first input restores its terminal mode. + ready, _, _ = select.select( + [stream for stream in buffers if stream not in closed], + [], + [], + remaining, + ) + assert ready, (marker, buffers) + for stream in ready: + try: + chunk = os.read(stream, 4096) + except OSError as error: + # Linux PTY masters report EIO after their last slave closes. + if error.errno != errno.EIO: + raise + chunk = b"" + if chunk: + buffers[stream].extend(chunk) + else: + closed.add(stream) + assert fd not in closed or marker in buffers[fd], (marker, buffers) + end = buffers[fd].index(marker) + len(marker) + del buffers[fd][:end] + + def exercise(code, switch_terminal=False, output_terminal=False): + master, slave = os.openpty() + other_master, other_slave = os.openpty() + env = dict(os.environ, TERM="xterm") + # Do not use pty.fork()/setsid(): those deliberately select RustPython's + # stdio fallback instead of the interactive line editor. + process = subprocess.Popen( + [sys.executable, "-c", code, str(other_slave)], + stdin=slave, + stdout=slave, + stderr=slave, + pass_fds=(other_slave,), + env=env, + ) + os.close(slave) + os.close(other_slave) + buffers = {master: bytearray(), other_master: bytearray()} + closed = set() + try: + read_until(master, b"FIRST>", buffers, closed) + os.write(master, b"one\ntwo\n") + if switch_terminal: + read_until(other_master, b"SECOND>", buffers, closed) + os.write(other_master, b"fresh\n") + read_until(other_master, b"RESULT=fresh", buffers, closed) + elif output_terminal: + read_until(other_master, b"RESULT=two", buffers, closed) + else: + read_until(master, b"RESULT=two", buffers, closed) + assert process.wait(timeout=20) == 0 + finally: + if process.poll() is None: + process.kill() + process.wait() + os.close(master) + os.close(other_master) + + exercise( + """ +import threading +values = [] +def first(): + values.append(input('FIRST>')) +t = threading.Thread(target=first) +t.start() +t.join() +assert values == ['one'], values +print('RESULT=' + input('SECOND>'), flush=True) +""" + ) + exercise( + """ +import os, sys +assert input('FIRST>') == 'one' +fd = int(sys.argv[1]) +os.dup2(fd, 0) +os.dup2(fd, 1) +os.dup2(fd, 2) +os.close(fd) +print('RESULT=' + input('SECOND>'), flush=True) +""", + switch_terminal=True, + ) + + # Presentation changes must not discard bytes belonging to unchanged stdin. + exercise( + """ +import os +assert input('FIRST>') == 'one' +os.environ['TERM'] = 'vt100' +print('RESULT=' + input('SECOND>'), flush=True) +""" + ) + exercise( + """ +import os, sys +assert input('FIRST>') == 'one' +fd = int(sys.argv[1]) +os.dup2(fd, 1) +os.dup2(fd, 2) +os.close(fd) +print('RESULT=' + input('SECOND>'), flush=True) +""", + output_terminal=True, + ) + + # The result audit runs after native reading and may start another input. + # It must not inherit an active reader borrow or lose the retained next line. + exercise( + """ +import sys +results = [] +def audit(event, args): + if event == 'builtins.input/result' and not results: + results.append(args[0]) + results.append(input('SECOND>')) +sys.addaudithook(audit) +assert input('FIRST>') == 'one' +assert results == ['one', 'two'], results +print('RESULT=' + results[1], flush=True) +""" + ) diff --git a/extra_tests/snippets/stdlib_io.py b/extra_tests/snippets/stdlib_io.py index 8346ddbb62d..17c73d360d1 100644 --- a/extra_tests/snippets/stdlib_io.py +++ b/extra_tests/snippets/stdlib_io.py @@ -1,8 +1,42 @@ import os +import sys from io import BufferedReader, BytesIO, FileIO, RawIOBase, StringIO, TextIOWrapper from testutils import assert_raises +# Overwriting replaces characters, even when their encoded widths differ. +for initial, replacement in ( + ("abc", "é"), + ("ébc", "a"), + ("а😀в", "XY"), + ("a\ud800c", "\udfffé"), +): + stream = StringIO("prefix:" + initial) + stream.seek(7) + assert stream.write(replacement) == len(replacement) + assert stream.getvalue() == "prefix:" + replacement + initial[len(replacement) :] + assert stream.tell() == 7 + len(replacement) + assert stream.read() == initial[len(replacement) :] + assert stream.tell() == 7 + len(initial) + +# Truncation keeps the character position, then pads in characters on writing. +stream = StringIO("é😀abc") +stream.seek(4) +stream.truncate(1) +assert stream.tell() == 4 +assert stream.read() == "" +assert stream.tell() == 4 +assert stream.write("") == 0 +assert stream.getvalue() == "é" +state = stream.__getstate__() +stream = StringIO() +stream.__setstate__(state) +assert stream.tell() == 4 +stream.write("Ж") +assert stream.getvalue() == "é\0\0\0Ж" +assert stream.tell() == 5 + + fi = FileIO("README.md") assert fi.seekable() bb = BufferedReader(fi) @@ -166,10 +200,40 @@ def __index__(self): "underlying buffer has been detached", lambda: setattr(detached_textio, "_CHUNK_SIZE", 16), ) -expect_value_error( - "underlying buffer has been detached", - lambda: delattr(detached_textio, "_CHUNK_SIZE"), -) +# CI also runs this snippet on CPython 3.15.0, whose setter checks +# attachment before deletion. RustPython targets the 3.15.2 Clinic contract. +legacy_chunk_size_deletion = sys.implementation.name == "cpython" and sys.version_info[ + :3 +] == (3, 15, 0) +for wrapper, legacy_error, legacy_message in ( + (textio, AttributeError, "cannot delete attribute"), + (uninitialized_textio, ValueError, "I/O operation on uninitialized object"), + (detached_textio, ValueError, "underlying buffer has been detached"), +): + error_type = legacy_error if legacy_chunk_size_deletion else AttributeError + message = ( + legacy_message + if legacy_chunk_size_deletion + else "attribute '_CHUNK_SIZE' of '_io.TextIOWrapper' objects cannot be deleted" + ) + with assert_raises(error_type) as error: + del wrapper._CHUNK_SIZE + assert str(error.exception) == message + + +for wrapper_name in ("ChunkWrapper", "€" * 34): + wrapper_type = type(wrapper_name, (TextIOWrapper,), {}) + wrapper = wrapper_type(BytesIO()) + with assert_raises(AttributeError) as error: + del wrapper._CHUNK_SIZE + truncated_name = wrapper_name.encode("utf-8")[:100].decode("utf-8", "ignore") + message = ( + "cannot delete attribute" + if legacy_chunk_size_deletion + else f"attribute '_CHUNK_SIZE' of '{truncated_name}' objects cannot be deleted" + ) + assert str(error.exception) == message + wrapper.close() long_type_name = "X" * 250 @@ -242,3 +306,180 @@ def _text_cookie( else: assert _textio.read(50) is not None _textio.tell() + + +# Reinitialization releases arguments after unlocking the stream. +for _type, _content in ((BytesIO, b"hello"), (StringIO, "hello")): + _stream = _type(_content) + _stream.close() + _stream.__init__(_content) + assert not _stream.closed + assert _stream.getvalue() == _content + + class ClosingValue(type(_content)): + def __del__(self): + _stream.close() + + _stream.__init__(ClosingValue(_content)) + assert _stream.closed + + +_stream = BytesIO(b"old") +_released_values = [] + + +class ClosingBuffer: + def __buffer__(self, flags): + return memoryview(b"new") + + def __release_buffer__(self, view): + _released_values.append(_stream.getvalue()) + _stream.close() + + +_stream.__init__(ClosingBuffer()) +assert _released_values == [b"new"] +assert _stream.closed + + +# OSError.filename is the original FileIO path argument, including path-like objects. +class PathLikeName: + def __fspath__(self): + return "/nonexistent/x" + + +path_like_name = PathLikeName() +try: + FileIO(path_like_name, "r") +except OSError as error: + assert error.filename is path_like_name +else: + raise AssertionError("expected OSError") + +for original in ("/nonexistent/x", b"/nonexistent/x"): + try: + FileIO(original, "r") + except OSError as error: + assert error.filename is original + else: + raise AssertionError("expected OSError") + +with FileIO(__file__, "rbb") as rbb: + assert rbb.mode == "rb" + + +def test_buffered_stream_capabilities(): + from _io import BufferedRandom, BufferedReader, BufferedRWPair, BufferedWriter + + events = [] + result = object() + + class Raw(BytesIO): + def __init__(self, label): + super().__init__(b"data") + self.label = label + self.can_read = True + self.can_write = True + + def readable(self): + events.append((self.label, "readable")) + return self.can_read + + def writable(self): + events.append((self.label, "writable")) + return self.can_write + + for wrapper, forwards_read, forwards_write in ( + (BufferedReader, True, False), + (BufferedWriter, False, True), + (BufferedRandom, True, True), + (BufferedRWPair, True, True), + ): + reader = Raw("reader") + writer = Raw("writer") if wrapper is BufferedRWPair else reader + args = (reader, writer) if wrapper is BufferedRWPair else (reader,) + with wrapper(*args) as stream: + # Change the raw capabilities after initialization. + reader.can_read = result + writer.can_write = 0 + events.clear() + assert stream.readable() is (result if forwards_read else False) + assert stream.writable() is (writer.can_write if forwards_write else False) + assert events == [ + (label, method) + for flag, label, method in ( + (forwards_read, reader.label, "readable"), + (forwards_write, writer.label, "writable"), + ) + if flag + ] + + plain_raw = BytesIO() + args = (plain_raw, BytesIO()) if wrapper is BufferedRWPair else (plain_raw,) + closed = wrapper(*args) + closed.close() + for forwarded, operation in ( + (forwards_read, closed.readable), + (forwards_write, closed.writable), + ): + if forwarded: + assert_raises(ValueError, operation) + else: + assert operation() is False + + with BytesIO() as raw: + detached = BufferedRandom(raw) + assert detached.detach() is raw + for operation in (detached.readable, detached.writable): + with assert_raises(ValueError) as error: + operation() + assert str(error.exception) == "raw stream has been detached" + + +def test_buffered_pair_isatty_forwarding(): + from _io import BufferedRWPair + + events = [] + failure = LookupError("isatty failure") + + class NotABoolean: + def __bool__(self): + raise AssertionError("BufferedRWPair must not truth-test the result") + + class Raw(BytesIO): + def __init__(self, label): + super().__init__() + self.label = label + self.result = False + + def isatty(self): + events.append(self.label) + if self.result is failure: + raise failure + return self.result + + reader, writer = Raw("reader"), Raw("writer") + with BufferedRWPair(reader, writer) as pair: + reader.result = failure + for value in (True, 0, NotABoolean()): + events.clear() + writer.result = value + assert pair.isatty() is value + assert events == ["writer"] + + reader.result = NotABoolean() + writer.result = False + events.clear() + assert pair.isatty() is reader.result + assert events == ["writer", "reader"] + + events.clear() + writer.result = failure + with assert_raises(LookupError) as error: + pair.isatty() + assert error.exception is failure + assert events == ["writer"] + + +test_buffered_stream_capabilities() +test_buffered_pair_isatty_forwarding() diff --git a/extra_tests/snippets/stdlib_io_bytesio.py b/extra_tests/snippets/stdlib_io_bytesio.py index 9344c50d947..c9b006ba0df 100644 --- a/extra_tests/snippets/stdlib_io_bytesio.py +++ b/extra_tests/snippets/stdlib_io_bytesio.py @@ -114,3 +114,138 @@ def test_07(): assert _bio.readinto(_bio.getbuffer()) == 60 _bio = BytesIO(b"x" * 60) assert _bio.readinto(memoryview(_bio.getbuffer())) == 60 + + +def test_readlines_bytesio_semantics(): + import inspect + import sys + + assert BytesIO.readlines.__text_signature__ == "($self, size=None, /)" + assert str(inspect.signature(BytesIO.readlines)) == "(self, size=None, /)" + + class IndexOnly: + def __index__(self): + raise AssertionError("BytesIO.readlines must not call __index__") + + class Integer(int): + def __index__(self): + raise AssertionError("must use the stored integer value") + + def __int__(self): + raise AssertionError("must use the stored integer value") + + # The positive limit is inclusive, unlike IOBase.readlines' hint. + for size, expected in ( + (None, [b"a\n", b"bb\n", b"tail"]), + (-1, [b"a\n", b"bb\n", b"tail"]), + (0, [b"a\n", b"bb\n", b"tail"]), + (False, [b"a\n", b"bb\n", b"tail"]), + (True, [b"a\n"]), + (2, [b"a\n"]), + (Integer(2), [b"a\n"]), + (3, [b"a\n", b"bb\n"]), + (5, [b"a\n", b"bb\n"]), + (sys.maxsize, [b"a\n", b"bb\n", b"tail"]), + ): + stream = BytesIO(b"a\nbb\ntail") + assert stream.readlines(size) == expected, size + assert stream.tell() == sum(map(len, expected)), size + assert BytesIO(b"a\nb").readlines() == [b"a\n", b"b"] + + for value in (IndexOnly(), 1.5, "2"): + stream = BytesIO(b"a\nb") + try: + stream.readlines(value) + except TypeError as exc: + assert str(exc) == ( + f"integer argument expected, got '{type(value).__name__}'" + ) + else: + raise AssertionError("non-int size accepted") + assert stream.tell() == 0 + + for value in (sys.maxsize + 1, -sys.maxsize - 2): + stream = BytesIO(b"a\nb") + try: + stream.readlines(value) + except OverflowError as exc: + assert str(exc) == "Python int too large to convert to C ssize_t" + else: + raise AssertionError("overflowing size accepted") + assert stream.tell() == 0 + + # Closed state beats type/range conversion, but call-shape errors beat it. + stream = BytesIO() + stream.close() + for value in (None, IndexOnly(), "2", sys.maxsize + 1): + try: + stream.readlines(value) + except ValueError as exc: + assert str(exc) == "I/O operation on closed file." + else: + raise AssertionError("closed stream accepted") + for args, kwargs in (((1, 2), {}), ((), {"size": None})): + try: + stream.readlines(*args, **kwargs) + except TypeError: + pass + else: + raise AssertionError("invalid call shape accepted") + + class Overrides(BytesIO): + def readline(self, *args): + raise AssertionError("readline override called") + + def read(self, *args): + raise AssertionError("read override called") + + def __iter__(self): + raise AssertionError("iterator override called") + + def __next__(self): + raise AssertionError("next override called") + + stream = Overrides(b"a\nbb\ntail") + view = stream.getbuffer() + assert stream.readlines(2) == [b"a\n"] + assert stream.readlines() == [b"bb\n", b"tail"] + assert bytes(view) == b"a\nbb\ntail" + view.release() + stream.seek(1) + assert stream.readlines(1) == [b"\n"] + assert stream.tell() == 2 + stream.seek(100) + assert stream.readlines() == [] + assert stream.tell() == 100 + assert BytesIO().readlines() == [] + + # Retain an int subclass argument through the read. Its finalizer may + # reenter this stream and must not run with the storage lock held. + positions = [] + stream = BytesIO(b"a\nb") + + class TemporarySize(int): + def __del__(self): + positions.append(stream.tell()) + + assert stream.readlines(TemporarySize(2)) == [b"a\n"] + assert positions == [2] + + +test_readlines_bytesio_semantics() + + +# BytesIO's non-int error uses tp_name, including static-type module names, +# without the truncation used by some other IO diagnostics. +import datetime + +for value, expected_name in ( + (datetime.date(2026, 1, 1), "datetime.date"), + (type("L" * 300, (), {})(), "L" * 300), +): + try: + BytesIO().readlines(value) + except TypeError as exc: + assert str(exc) == f"integer argument expected, got '{expected_name}'" + else: + raise AssertionError("non-int size accepted") diff --git a/extra_tests/snippets/stdlib_io_stringio.py b/extra_tests/snippets/stdlib_io_stringio.py index 0adf0edac0b..d70068c54b5 100644 --- a/extra_tests/snippets/stdlib_io_stringio.py +++ b/extra_tests/snippets/stdlib_io_stringio.py @@ -1,5 +1,7 @@ from io import StringIO +from testutils import assert_raises + def test_01(): """ @@ -84,6 +86,17 @@ def test_06(): assert False +def test_07(): + """ + Test that newline is validated before initial_value + """ + assert_raises(ValueError, StringIO, True, "7") + with assert_raises(TypeError) as cm: + StringIO(True) + assert str(cm.exception) == "initial_value must be str or None, not bool" + assert StringIO(None, "\r").getvalue() == "" + + if __name__ == "__main__": test_01() test_02() @@ -91,3 +104,4 @@ def test_06(): test_04() test_05() test_06() + test_07() diff --git a/extra_tests/snippets/stdlib_itertools.py b/extra_tests/snippets/stdlib_itertools.py index ef06ce52985..2c9c3ebffbe 100644 --- a/extra_tests/snippets/stdlib_itertools.py +++ b/extra_tests/snippets/stdlib_itertools.py @@ -1,4 +1,5 @@ import itertools +import sys from testutils import assert_raises @@ -87,6 +88,27 @@ assert next(c) == 5 assert next(c) == 5 +c = itertools.count(True) +assert repr(c) == "count(1)" +assert type(next(c)) is int + +c = itertools.count(True, 2) +assert repr(c) == "count(True, 2)" +assert next(c) is True + + +class RaisingAdd(int): + def __add__(self, other): + raise RuntimeError + + def __radd__(self, other): + raise RuntimeError + + +c = itertools.count(RaisingAdd(0), RaisingAdd(1)) +assert next(c) == 0 +assert next(c) == 1 + # itertools.count TODOs: kwargs and floats # step kwarg @@ -367,7 +389,54 @@ def assert_matches_seq(it, seq): assert list(t[0]) == [1, 2, 3] assert list(t[0]) == [] + +class NoneIter: + def __iter__(self): + return None + + +with assert_raises(ValueError): + itertools.tee(NoneIter(), -1) +assert itertools.tee(NoneIter(), 0) == () + + +class BadIterator: + def __iter__(self): + return None + + def __next__(self): + return None + + +class BadIterable: + def __iter__(self): + return BadIterator() + + +with assert_raises(TypeError): + itertools.tee(BadIterable()) + + +class CopyRaisingIterator: + def __iter__(self): + return self + + def __next__(self): + raise StopIteration + + def __copy__(self): + raise RuntimeError + + +t0, t1 = itertools.tee(CopyRaisingIterator()) +assert list(t0) == list(t1) == [] + # itertools.product + +product_source = iter([1]) +assert list(itertools.product(product_source, repeat=0)) == [()] +assert next(product_source) == 1 + it = itertools.product([1, 2], [3, 4]) assert (1, 3) == next(it) assert (1, 4) == next(it) @@ -536,9 +605,9 @@ def __iter__(self): with assert_raises(OverflowError): factory(range(5), 2**64) -with assert_raises(MemoryError): +with assert_raises(MemoryError if sys.maxsize >= 2**44 else OverflowError): itertools.combinations(range(5), 2**44) -with assert_raises(MemoryError): +with assert_raises(MemoryError if sys.maxsize >= 2**44 else OverflowError): itertools.combinations_with_replacement(range(5), 2**44) # repeat is an arbitrary Python int: a negative one is refused, and one whose @@ -551,7 +620,7 @@ def __iter__(self): # The pools are filled by their own count, so a repeat with nothing to repeat # answers at once instead of counting up to it. -assert list(itertools.product(repeat=2**62)) == [()] +assert list(itertools.product(repeat=min(2**62, sys.maxsize))) == [()] assert list(itertools.product(repeat=0)) == [()] @@ -569,3 +638,267 @@ def __iter__(self): with assert_raises(OverflowError): itertools.product(Watched(), repeat=2**62) assert ran == [] + + +# compress consumes data, then the selector, then tests the selector's truth. +def check_compress_consumption(): + events = [] + + def tracked(name, values): + for value in values: + events.append(name) + yield value + events.append(name + " exhausted") + + class Selector: + def __init__(self, value): + self.value = value + + def __bool__(self): + events.append("bool") + return self.value + + assert list( + itertools.compress( + tracked("data", [1, 2]), + tracked("selectors", [Selector(False), Selector(True), Selector(True)]), + ) + ) == [2] + assert events == [ + "data", + "selectors", + "bool", + "data", + "selectors", + "bool", + "data exhausted", + ], events + + events.clear() + data = tracked("data", [1, 2, 3]) + assert list(itertools.compress(data, tracked("selectors", [True]))) == [1] + assert events == ["data", "selectors", "data", "selectors exhausted"], events + assert next(data) == 3 + + events.clear() + assert ( + list(itertools.compress(tracked("data", []), tracked("selectors", [True]))) + == [] + ) + assert events == ["data exhausted"], events + + def failing(name): + events.append(name) + raise ValueError(name) + yield + + events.clear() + with assert_raises(ValueError) as caught: + next(itertools.compress(failing("data"), tracked("selectors", [True]))) + assert str(caught.exception) == "data" + assert events == ["data"], events + + events.clear() + with assert_raises(ValueError) as caught: + next(itertools.compress(tracked("data", [1]), failing("selectors"))) + assert str(caught.exception) == "selectors" + assert events == ["data", "selectors"], events + + class BadSelector: + def __bool__(self): + events.append("bool") + raise ValueError("truth") + + events.clear() + with assert_raises(ValueError) as caught: + next(itertools.compress(tracked("data", [1]), [BadSelector()])) + assert str(caught.exception) == "truth" + assert events == ["data", "bool"], events + + +check_compress_consumption() + + +# These public iterator types also support Python subclasses. +for base, args in ( + (itertools.count, ()), + (itertools.groupby, ([1],)), + (itertools.accumulate, ([1],)), + (itertools.product, ([1],)), + (itertools.combinations, ([1], 1)), + (itertools.combinations_with_replacement, ([1], 1)), + (itertools.permutations, ([1],)), + (itertools.zip_longest, ([1],)), + (itertools.pairwise, ([1, 2],)), +): + + class Subclass(base): + pass + + instance = Subclass(*args) + assert type(instance) is Subclass + next(instance) + + +class PairwiseWithLabel(itertools.pairwise): + def __init__(self, iterable, *, label): + self.label = label + + +pairs = PairwiseWithLabel([1, 2], label="pairs") +assert pairs.label == "pairs" +assert next(pairs) == (1, 2) + + +# Consumed tee values must not remain alive for the lifetime of the iterators. +import weakref + + +class TeeItem: + pass + + +tee_left, tee_right = itertools.tee(TeeItem() for _ in range(200)) +tee_first = next(tee_left) +tee_ref = weakref.ref(tee_first) +del tee_first +next(tee_right) +for _ in range(199): + next(tee_left) + next(tee_right) +assert tee_ref() is None + + +def check_positional_constructor_binding(): + events = [] + + class Source: + def __iter__(self): + events.append("iter") + return iter(()) + + for base, prefix in ( + (itertools.cycle, ()), + (itertools.starmap, (None,)), + (itertools.takewhile, (None,)), + (itertools.dropwhile, (None,)), + (itertools.filterfalse, (None,)), + (itertools.pairwise, ()), + ): + for constructor, leading in ((base, ()), (base.__new__, (base,))): + events.clear() + with assert_raises(TypeError): + constructor(*leading, *prefix, Source(), unexpected=True) + assert events == [], (base, events) + + with assert_raises(TypeError): + constructor(*leading, *prefix, Source(), None) + assert events == [], (base, events) + + constructor(*leading, *prefix, Source()) + assert events == ["iter"], (base, events) + + class Subclass(base): + def __init__(self, *args, label): + events.append(label) + + events.clear() + Subclass(*prefix, Source(), label="init") + assert events == ["iter", "init"], (base, events) + + +check_positional_constructor_binding() + + +def check_tee_source_lifetime(): + for construct, leading in ( + (itertools._tee, ()), + (itertools._tee.__new__, (itertools._tee,)), + ): + original = itertools._tee(range(3)) + events = [] + + class Source: + def __iter__(self): + return original + + def __del__(self): + events.append(next(original)) + + copied = construct(*leading, Source()) + assert events == [0], events + assert next(copied) == 0 + assert next(original) == 1 + + +check_tee_source_lifetime() + + +# Source finalizers can reenter after the iterator has published terminal/replay +# state. No state lock may remain held when the finalizer runs. +def check_cycle_source_finalizer(): + events = [] + + class Source: + def __init__(self): + self.items = iter((1, 2)) + + def __iter__(self): + return self + + def __next__(self): + return next(self.items) + + def __del__(self): + events.append(next(cycled)) + + source = Source() + source_ref = weakref.ref(source) + cycled = itertools.cycle(source) + del source + assert next(cycled) == 1 + assert next(cycled) == 2 + assert next(cycled) == 1 + assert source_ref() is None + assert events == [1] + # The outer call retains its own replay index across finalizer reentry. + assert next(cycled) == 2 + + +check_cycle_source_finalizer() + + +def check_pairwise_source_finalizer(count): + events = [] + + class Item: + def __del__(self): + events.append(("item", next(pairs, None))) + + items = iter([Item()] if count else []) + + class Source: + # A native next avoids a Python traceback retaining self at exhaustion. + __next__ = staticmethod(items.__next__) + + def __iter__(self): + return self + + def __del__(self): + events.append(("source", next(pairs, None))) + + source = Source() + source_ref = weakref.ref(source) + pairs = itertools.pairwise(source) + del source + assert next(pairs, None) is None + assert source_ref() is None + expected = [("source", None)] + if count: + expected.append(("item", None)) + assert events == expected + assert next(pairs, None) is None + + +check_pairwise_source_finalizer(0) +check_pairwise_source_finalizer(1) diff --git a/extra_tests/snippets/stdlib_json.py b/extra_tests/snippets/stdlib_json.py index e55382c8223..8366a19cd66 100644 --- a/extra_tests/snippets/stdlib_json.py +++ b/extra_tests/snippets/stdlib_json.py @@ -67,6 +67,24 @@ def json_load(obj): assert "{}" == json_dump({}) assert round_trip_test({"a": "b"}) + +class EmptyDictWithItems(dict): + def items(self): + raise AssertionError("items() must not be called for an empty dictionary") + + +for sort_keys in (False, True): + assert json.dumps(EmptyDictWithItems(), sort_keys=sort_keys) == "{}" + assert json.dumps([EmptyDictWithItems()], sort_keys=sort_keys) == "[{}]" + + +class NonemptyDictWithItems(dict): + def items(self): + return [("replacement", 2)] + + +assert json.dumps(NonemptyDictWithItems(original=1)) == '{"replacement": 2}' + # should reject non-str keys in jsons assert_raises(json.JSONDecodeError, lambda: json.loads('{3: "abc"}')) assert_raises(json.JSONDecodeError, lambda: json_load('{3: "abc"}')) diff --git a/extra_tests/snippets/stdlib_locale.py b/extra_tests/snippets/stdlib_locale.py new file mode 100644 index 00000000000..3c6edbbbf7c --- /dev/null +++ b/extra_tests/snippets/stdlib_locale.py @@ -0,0 +1,14 @@ +import locale +import sys + +from testutils import assert_raises + +# Windows counts the modifier toward the code-page length before calling the CRT. +if sys.platform == "win32": + for category, name in ( + (locale.LC_CTYPE, "English.1252@" + "x" * 16), + (locale.LC_ALL, "LC_CTYPE=English.1252@" + "x" * 16), + ): + with assert_raises(locale.Error) as caught: + locale.setlocale(category, name) + assert caught.exception.args == ("unsupported locale setting",) diff --git a/extra_tests/snippets/stdlib_marshal.py b/extra_tests/snippets/stdlib_marshal.py index 4e224fb313f..e709140fd81 100644 --- a/extra_tests/snippets/stdlib_marshal.py +++ b/extra_tests/snippets/stdlib_marshal.py @@ -146,6 +146,15 @@ def test_null_object(self): with self.assertRaises(TypeError): marshal.loads(b"0") + def test_nested_subclass(self): + class FloatSubclass(float): + pass + + with self.assertRaises(ValueError): + marshal.dumps([FloatSubclass(0.5)]) + with self.assertRaises(ValueError): + marshal.dumps({"key": FloatSubclass(0.5)}) + def test_invalid_reference(self): import struct diff --git a/extra_tests/snippets/stdlib_math.py b/extra_tests/snippets/stdlib_math.py index 00d6c5f3ab1..7b41f039e83 100644 --- a/extra_tests/snippets/stdlib_math.py +++ b/extra_tests/snippets/stdlib_math.py @@ -7,6 +7,81 @@ INF = float("inf") NINF = float("-inf") + +def test_math_315_apis(): + import math.integer + import sys + + import _math_integer + + assert math.integer is _math_integer + assert sys.modules["math.integer"] is math.integer + assert math.integer.__name__ == "math.integer" + for name, args, expected in ( + ("comb", (5, 2), 10), + ("factorial", (5,), 120), + ("gcd", (12, 18), 6), + ("isqrt", (17,), 4), + ("lcm", (4, 6), 12), + ("perm", (5, 2), 20), + ): + function = getattr(math, name) + assert function is getattr(math.integer, name) + assert function.__module__ == "math.integer" + assert function(*args) == expected + + for value in (1.0, -1.0, sys.float_info.min, sys.float_info.max): + assert math.isnormal(value) is True + assert math.issubnormal(value) is False + for value in (sys.float_info.min / 2, -sys.float_info.min / 2): + assert math.isnormal(value) is False + assert math.issubnormal(value) is True + for value in (0.0, -0.0, INF, NINF, NAN): + assert math.isnormal(value) is False + assert math.issubnormal(value) is False + for value in (0.0, 1.0, INF, NAN): + assert math.signbit(math.copysign(value, 1.0)) is False + assert math.signbit(math.copysign(value, -1.0)) is True + + class FloatArgument: + def __float__(self): + return -2.0 + + class IndexArgument: + def __index__(self): + return 2 + + for function in (math.isnormal, math.issubnormal, math.signbit): + assert function(FloatArgument()) == function(-2.0) + assert function(IndexArgument()) == function(2.0) + assert_raises(TypeError, function, object()) + assert_raises(TypeError, function, x=1.0) + assert_raises(TypeError, function) + assert_raises(TypeError, function, 1.0, 2.0) + + for function, expected in ((math.fmax, 2.0), (math.fmin, -2.0)): + assert function(-2.0, 2.0) == expected + assert function(2.0, -2.0) == expected + assert type(function(1, 2)) is float + assert function(FloatArgument(), IndexArgument()) == expected + assert math.isnan(function(NAN, NAN)) + for value in (0.0, -0.0, 1.0, -1.0, INF, NINF): + for result in (function(NAN, value), function(value, NAN)): + assert result == value + assert math.signbit(result) == math.signbit(value) + assert function(0.0, -0.0) == 0.0 + assert function(-0.0, 0.0) == 0.0 + assert_raises(TypeError, function, object(), 1.0) + assert_raises(TypeError, function, 1.0, object()) + assert_raises(TypeError, function, x=1.0, y=2.0) + assert_raises(TypeError, function, 1.0) + assert_raises(TypeError, function, 1.0, 2.0, 3.0) + assert math.fmax(NINF, INF) == INF + assert math.fmin(NINF, INF) == NINF + + +test_math_315_apis() + # assert(math.exp(2) == math.exp(2.0)) # assert(math.exp(True) == math.exp(1.0)) # @@ -17,6 +92,114 @@ # # assert math.log(1.1111) == math.log(Conversible()) +# A logarithm can fit in a float even when its integer base cannot. +assert math.isclose(math.log(2**4000, 2**2000), 2.0) +assert math.isclose(math.log(2.0, 2**2000), 1.0 / 2000) + +for value in (1, 8.0, INF, NAN): + assert_raises(ZeroDivisionError, math.log, value, 1) +assert_raises(TypeError, math.log, object(), 1) +assert_raises(ValueError, math.log, 8, -(2**2000)) + +log_conversions = [] + + +class LogFloat: + def __init__(self, name, value): + self.name = name + self.value = value + + def __float__(self): + log_conversions.append(self.name) + return self.value + + +assert math.isclose(math.log(LogFloat("x", 8.0), LogFloat("base", 2.0)), 3.0) +assert log_conversions == ["x", "base"] +log_conversions.clear() +assert_raises(ValueError, math.log, -1, LogFloat("base", 2.0)) +assert log_conversions == [] + + +class LogFloatOverflow: + def __float__(self): + log_conversions.append("float") + raise OverflowError("float conversion failed") + + def __index__(self): + log_conversions.append("index") + return 2**2000 + + +class LogIndexOnly: + def __index__(self): + return 2**2000 + + +for logarithm in (math.log, math.log2, math.log10): + log_conversions.clear() + assert math.isclose(logarithm(LogFloatOverflow()), logarithm(2**2000)) + assert log_conversions == ["float", "index"] + assert math.isclose(logarithm(LogIndexOnly()), logarithm(2**2000)) + + for error_type in (TypeError, ValueError, RuntimeError): + error = error_type("float conversion failed") + + class FailedFloat(LogFloatOverflow): + def __float__(self): + raise error + + with assert_raises(error_type) as caught: + logarithm(FailedFloat()) + assert caught.exception is error + + error = RuntimeError("index conversion failed") + + class FailedIndex(LogFloatOverflow): + def __index__(self): + raise error + + with assert_raises(RuntimeError) as caught: + logarithm(FailedIndex()) + assert caught.exception is error + + class NegativeIndex(LogFloatOverflow): + def __index__(self): + return -1 + + assert_raises(ValueError, logarithm, NegativeIndex()) + + class InvalidIndex(LogFloatOverflow): + def __index__(self): + return 1.0 + + assert_raises(TypeError, logarithm, InvalidIndex()) + + class NoIndex: + __float__ = LogFloatOverflow.__float__ + + assert_raises(OverflowError, logarithm, NoIndex()) + + class SuccessfulFloat: + def __float__(self): + return 8.0 + + def __index__(self): + raise AssertionError("successful float conversion must not retry index") + + assert logarithm(SuccessfulFloat()) == logarithm(8.0) + +assert math.isclose(math.log(8, LogFloatOverflow()), 3 / 2000) +assert math.isclose(math.log(8, LogIndexOnly()), 3 / 2000) + + +class LogInt(int): + def __float__(self): + raise AssertionError("integer logarithms use the native integer value") + + +assert math.isclose(math.log(LogInt(2**4000), LogInt(2**2000)), 2.0) + # roundings assert int.__trunc__ assert int.__floor__ @@ -358,3 +541,33 @@ def assertAllNotClose(examples, *args, **kwargs): assert math.perm(5) == math.perm(5, None) == 120 assert math.perm(2**64, 0) == 1 assert math.comb(2**64, 2**64 - 1) == 2**64 + + +class LdexpFloat: + def __float__(self): + return 1.5 + + +class LdexpIndex: + def __index__(self): + return 3 + + +class LdexpRaisingFloat: + def __float__(self): + raise RuntimeError + + +assert math.ldexp(LdexpFloat(), 1) == 3.0 +assert math.ldexp(LdexpIndex(), 1) == 6.0 +assert_raises(RuntimeError, math.ldexp, LdexpRaisingFloat(), 1) +assert_raises(OverflowError, math.ldexp, 10**400, 1) + + +class FloatSubclass(float): + def __float__(self): + return 9.0 + + +assert math.sqrt(FloatSubclass(4.0)) == 2.0 +assert math.ldexp(FloatSubclass(1.0), 1) == 2.0 diff --git a/extra_tests/snippets/stdlib_mmap.py b/extra_tests/snippets/stdlib_mmap.py index 9d4414e5552..761b31f729d 100644 --- a/extra_tests/snippets/stdlib_mmap.py +++ b/extra_tests/snippets/stdlib_mmap.py @@ -25,9 +25,9 @@ assert mapped.rfind(b"") == 3 assert mapped.find(b"", 1, 2) == 1 assert mapped.rfind(b"", 1, 2) == 2 -# offsets past the end are clamped and negative ones count from the end -assert mapped.find(b"", 5) == 3 -assert mapped.rfind(b"", 5) == 3 +# starts past the end find nothing and negative offsets count from the end +assert mapped.find(b"", 5) == -1 +assert mapped.rfind(b"", 5) == -1 assert mapped.find(b"", -1) == 2 assert mapped.rfind(b"", 0, -1) == 2 # an inverted range holds nothing, not even the empty subsequence @@ -39,3 +39,173 @@ mapped.find(b"") with assert_raises(ValueError): mapped.rfind(b"") + + +# Buffer acquisition must reject a closed mapping before returning a view. +with assert_raises(ValueError): + memoryview(mapped) + +mapped = mmap.mmap(-1, 4) +mapped[:] = b"data" +view = memoryview(mapped) +child = view[1:] +view.release() +with assert_raises(BufferError): + mapped.close() +assert not mapped.closed +assert child.tobytes() == b"ata" +child.release() +mapped.close() +mapped.close() + +# On Windows resize must neither invalidate an export nor revive a closed map. +import sys + +if sys.platform == "win32": + mapped = mmap.mmap(-1, 4) + mapped[:] = b"data" + with memoryview(mapped) as view: + with assert_raises(BufferError): + mapped.resize(8) + with assert_raises(BufferError): + mapped.resize(0) + assert view.tobytes() == b"data" + mapped.resize(8) + with memoryview(mapped) as view: + assert view.tobytes() == b"data" + b"\0" * 4 + mapped.close() + with assert_raises(ValueError): + mapped.resize(4) + assert mapped.closed + + +# Assignment validates current storage after argument conversion, even if empty. +with mmap.mmap(-1, 4) as mapped: + with assert_raises(ValueError): + mapped[4] = 256 + mapped[0:0] = b"" +with assert_raises(ValueError): + mapped[0:0] = b"" + +with mmap.mmap(-1, 4, access=mmap.ACCESS_READ) as mapped: + with assert_raises(TypeError): + mapped[0:0] = b"" + + +class CloseOnIndex: + def __init__(self, mapped): + self.mapped = mapped + + def __index__(self): + self.mapped.close() + return 0 + + +for close_from in ("key", "value", "slice"): + mapped = mmap.mmap(-1, 4) + closer = CloseOnIndex(mapped) + try: + with assert_raises(ValueError): + if close_from == "key": + mapped[closer] = 0 + elif close_from == "value": + mapped[0] = closer + else: + mapped[closer:0] = b"" + assert mapped.closed + finally: + mapped.close() + + +class FailingIndex: + def __index__(self): + raise RuntimeError + + +# CPython parses mmap() with PyArg_ParseTupleAndKeywords, which converts fileno +# before it reports the missing length. +with assert_raises(RuntimeError): + mmap.mmap(FailingIndex()) + + +# resize uses Clinic's index conversion before checking the mapping. Unlike +# read/write past a resized end, tell() retains the original cursor. +if hasattr(mmap.mmap, "resize"): + + class ResizeIndex: + def __index__(self): + return 8 + + with mmap.mmap(-1, 16) as mapped: + mapped.seek(12) + mapped.resize(ResizeIndex()) + assert len(mapped) == 8 + assert mapped.tell() == 12 + assert mapped.read() == b"" + with assert_raises(OverflowError): + mapped.resize(1 << 100) + with assert_raises(ValueError): + mapped.resize(-1) + + mapped = mmap.mmap(-1, 16) + with assert_raises(ValueError): + mapped.resize(CloseOnIndex(mapped)) + assert mapped.closed + + +import os + +if os.name == "nt": + import tempfile + import uuid + + # Named file mappings retain the file handle, not just the view length. + with tempfile.TemporaryFile() as backing: + backing.write(b"x" * 32) + backing.flush() + tag = str(uuid.uuid4()) + backing.seek(5) + with mmap.mmap(backing.fileno(), 8, tagname=tag) as mapped: + assert os.lseek(backing.fileno(), 0, os.SEEK_CUR) == 0 + assert mapped.size() == 32 + mapped.resize(16) + assert len(mapped) == mapped.size() == 16 + assert mapped[:] == b"x" * 16 + + # A unique named anonymous map can grow. Once another view is opened the + # same resize must fail without losing either the data or the cursor. + tag = str(uuid.uuid4()) + with mmap.mmap(-1, 8, tagname=tag) as mapped: + mapped[:] = b"abcdefgh" + mapped.resize(16) + assert mapped[:8] == b"abcdefgh" + with mmap.mmap(-1, 16, tagname=tag) as other: + with assert_raises(OSError): + mapped.resize(32) + assert len(mapped) == 16 + assert mapped[:8] == other[:8] == b"abcdefgh" + mapped.resize(32) + assert mapped[:8] == b"abcdefgh" + + # Unnamed anonymous mappings must validate the offset too. + with assert_raises(OSError): + mmap.mmap(-1, 8, offset=1) + with mmap.mmap(-1, 8, offset=mmap.ALLOCATIONGRANULARITY) as mapped: + assert len(mapped) == 8 + mapped[:] = b"abcdefgh" + mapped.resize(16) + assert mapped[:8] == b"abcdefgh" + + # A failed resize can invalidate the map while retaining the backing file. + # close() must release that handle even though closed already reports True. + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "mapping") + with open(path, "w+b") as backing: + backing.write(b"abcdefgh") + backing.flush() + mapped = mmap.mmap(backing.fileno(), 8) + with assert_raises(OSError): + mapped.resize(0) + assert mapped.closed + mapped.close() + os.unlink(path) diff --git a/extra_tests/snippets/stdlib_multiprocessing_condition.py b/extra_tests/snippets/stdlib_multiprocessing_condition.py index 6d38dc0db9b..2ab4e17b943 100644 --- a/extra_tests/snippets/stdlib_multiprocessing_condition.py +++ b/extra_tests/snippets/stdlib_multiprocessing_condition.py @@ -2,6 +2,7 @@ import multiprocessing import threading +from _multiprocessing import SemLock def wait_on_condition(cond, started, woken): @@ -80,6 +81,17 @@ def notify_one_then_the_other(ctx): if __name__ == "__main__": multiprocessing.freeze_support() + # Low-level callers can supply every constructor parameter by name. + name = f"/rustpython_kw_{multiprocessing.current_process().pid}" + for args, kwargs in ( + ((1, 1, 1), {"name": name, "unlink": True}), + ((), {"kind": 1, "value": 1, "maxvalue": 1, "name": name, "unlink": True}), + ): + sem = SemLock(*args, **kwargs) + assert sem.acquire(False) + assert not sem.acquire(False) + sem.release() + del sem methods = ["spawn"] if "forkserver" in multiprocessing.get_all_start_methods(): methods.append("forkserver") diff --git a/extra_tests/snippets/stdlib_operator.py b/extra_tests/snippets/stdlib_operator.py index d0954b12261..16a6288a5ef 100644 --- a/extra_tests/snippets/stdlib_operator.py +++ b/extra_tests/snippets/stdlib_operator.py @@ -1,5 +1,182 @@ import _operator +from collections import Counter + +from testutils import assert_raises assert _operator._compare_digest("abcdef", "abcdef") assert not _operator._compare_digest("abcdef", "abc") assert not _operator._compare_digest("abc", "abcdef") + + +def check_operator_reference_cycles(): + import gc + import weakref + + class Holder: + pass + + class Name(str): + pass + + for make, make_payload in ( + (_operator.itemgetter, Holder), + (lambda value: _operator.methodcaller("method", value), Holder), + (lambda value: _operator.methodcaller("method", value=value), Holder), + (_operator.attrgetter, lambda: Name("attribute")), + ): + payload = make_payload() + wrapper = make(payload) + payload.wrapper = wrapper + reference = weakref.ref(payload) + del wrapper, payload + gc.collect() + assert reference() is None + + +check_operator_reference_cycles() + + +class Index: + def __index__(self): + return 5 + + +class RaisingIndex: + def __index__(self): + raise ZeroDivisionError + + +class TupleHint: + def __length_hint__(self): + return () + + +assert _operator.length_hint(object(), Index()) == 5 +assert_raises(ZeroDivisionError, _operator.length_hint, [], RaisingIndex()) +assert _operator.length_hint(object(), -1) == -1 +assert _operator.length_hint([], -1) == 0 +assert_raises(TypeError, _operator.length_hint, TupleHint(), -1) +assert_raises(OverflowError, _operator.length_hint, object(), -(2**70)) + + +def check_length_hint_result_diagnostics(): + import sys + + class Example: + class Result: + pass + + class Source: + def __init__(self, result): + self.result = result + + def __iter__(self): + return self + + def __next__(self): + raise StopIteration + + def __len__(self): + raise TypeError("try __length_hint__ instead") + + def __length_hint__(self): + return self.result + + Example.Source.__module__ = "length_hint_example" + Example.Result.__module__ = "length_hint_result" + source_type = f"length_hint_example.{Example.Source.__qualname__}" + result_type = f"length_hint_result.{Example.Result.__qualname__}" + for consume in (_operator.length_hint, list, bytes): + with assert_raises(TypeError) as caught: + consume(Example.Source(Example.Result())) + assert str(caught.exception) == ( + f"{source_type}.__length_hint__() must return an int, not {result_type}" + ) + + with assert_raises(ValueError) as caught: + consume(Example.Source(-1)) + assert str(caught.exception) == ( + f"{source_type}.__length_hint__() must return a non-negative int" + ) + + for overrun in (sys.maxsize + 1, -sys.maxsize - 2): + with assert_raises(OverflowError) as caught: + _operator.length_hint(Example.Source(overrun)) + assert str(caught.exception) == "Python int too large to convert to C ssize_t" + with assert_raises(OverflowError) as caught: + _operator.length_hint(Example.Source(-1), overrun) + assert str(caught.exception) == "Python int too large to convert to C ssize_t" + + +def check_length_hint_diagnostic_lifetimes(): + events = [] + + class Result(int): + def __del__(self): + events.append("result") + Source.__qualname__ = "SourceAfterResult" + + class Hint: + def __call__(self): + return Result(-1) + + def __del__(self): + events.append("hint") + Source.__qualname__ = "SourceAfterHint" + + class Descriptor: + def __get__(self, instance, owner): + return Hint() + + class Source: + __module__ = "length_hint_example" + __length_hint__ = Descriptor() + + with assert_raises(ValueError) as caught: + _operator.length_hint(Source()) + assert events == ["hint", "result"] + assert str(caught.exception) == ( + "length_hint_example.SourceAfterResult.__length_hint__() must return a non-negative int" + ) + + +check_length_hint_result_diagnostics() +check_length_hint_diagnostic_lifetimes() + + +class AddsAnything: + def __getitem__(self, index): + return 0 + + def __add__(self, other): + return "added" + + def __iadd__(self, other): + return "iadded" + + +class ListWithIadd(list): + def __iadd__(self, other): + return "iadded" + + +class ListWithBoth(list): + def __add__(self, other): + return "added" + + def __iadd__(self, other): + return "iadded" + + +assert _operator.concat(AddsAnything(), [1]) == "added" +assert_raises(TypeError, _operator.concat, AddsAnything(), 1) +assert _operator.iconcat(AddsAnything(), [1]) == "iadded" +assert_raises(TypeError, _operator.iconcat, AddsAnything(), 1) +receiver = ListWithIadd([1]) +result = _operator.iconcat(receiver, [2]) +assert type(result) is list +assert result == [1, 2] +assert receiver == [1] +assert _operator.iconcat(ListWithBoth([1]), [2]) == "iadded" +assert_raises(TypeError, _operator.concat, Counter(a=1), Counter(b=1)) +assert_raises(TypeError, _operator.iconcat, Counter(a=1), Counter(b=1)) diff --git a/extra_tests/snippets/stdlib_os.py b/extra_tests/snippets/stdlib_os.py index a1f40ef4c45..483eb2078e7 100644 --- a/extra_tests/snippets/stdlib_os.py +++ b/extra_tests/snippets/stdlib_os.py @@ -2,12 +2,118 @@ import os import stat import sys +import tempfile import time from testutils import assert_raises assert os.name == "posix" or os.name == "nt" + +def windows_stat_preserves_time64(): + import tempfile + + with tempfile.TemporaryDirectory() as directory: + filename = os.path.join(directory, "time64") + with open(filename, "wb"): + pass + timestamp = 2_208_988_800 # 2040-01-01, beyond signed 32-bit seconds. + os.utime(filename, (timestamp, timestamp)) + with open(filename, "rb") as file: + results = [os.stat(filename), os.fstat(file.fileno())] + with os.scandir(directory) as entries: + results.append(next(entries).stat()) + for result in results: + assert result.st_mtime == timestamp + assert result.st_mtime_ns == timestamp * 1_000_000_000 + + +if sys.platform == "win32": + windows_stat_preserves_time64() + + +def stat_rejects_negative_file_descriptors(): + import errno + import os + + for stat in (os.stat, os.fstat): + for fd in (-1, -5, -9, -100, -(2**31)): + try: + stat(fd) + except OSError as exc: + assert exc.errno == errno.EBADF, (stat, fd, exc) + else: + raise AssertionError((stat, fd, "accepted a negative file descriptor")) + + +# Keep the original RustPython-only coverage: CPython treats -1 as a path sentinel. +if os.name == "posix" and sys.implementation.name == "rustpython": + stat_rejects_negative_file_descriptors() + + +def chmod_supports_directory_descriptors(): + import errno + import tempfile + + assert os.chmod in os.supports_dir_fd + assert os.chmod in os.supports_fd + with tempfile.TemporaryDirectory() as directory: + filename = os.path.join(directory, "file") + with open(filename, "wb"): + pass + dir_fd = os.open(directory, os.O_RDONLY) + try: + os.chmod("file", 0o640, dir_fd=dir_fd) + assert stat.S_IMODE(os.stat(filename).st_mode) == 0o640 + + # Absolute paths ignore even an invalid directory descriptor. + os.chmod(path=filename, mode=0o600, dir_fd=-1) + assert stat.S_IMODE(os.stat(filename).st_mode) == 0o600 + + class DirectoryDescriptor: + def __index__(self): + return dir_fd + + os.chmod(b"file", 0o640, dir_fd=DirectoryDescriptor()) + assert stat.S_IMODE(os.stat(filename).st_mode) == 0o640 + with assert_raises(OSError) as error: + os.chmod("file", 0o600, dir_fd=-1) + assert error.exception.errno == errno.EBADF + assert error.exception.filename == "file" + for invalid, message in ( + (-(2**31) - 1, "fd is less than minimum"), + (2**31, "fd is greater than maximum"), + ): + with assert_raises(OverflowError) as error: + os.chmod(filename, 0o600, dir_fd=invalid) + assert str(error.exception) == message + + link = os.path.join(directory, "link") + os.symlink("file", link) + os.chmod("link", 0o600, dir_fd=dir_fd) + assert stat.S_IMODE(os.stat(filename).st_mode) == 0o600 + for path, options, error_type, message in ( + (link, {}, NotImplementedError, "follow_symlinks unavailable"), + ( + "link", + {"dir_fd": dir_fd}, + ValueError, + "cannot use dir_fd and follow_symlinks together", + ), + ): + try: + os.chmod(path, 0o640, follow_symlinks=False, **options) + except error_type as error: + assert message in str(error) + assert stat.S_IMODE(os.stat(filename).st_mode) == 0o600 + finally: + os.close(dir_fd) + + +if os.name == "posix" and hasattr(os, "fchmod"): + chmod_supports_directory_descriptors() + + fd = os.open("README.md", os.O_RDONLY) assert fd > 0 @@ -125,6 +231,11 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert os.write(fd, CONTENT2) == len(CONTENT2) os.close(fd) + # A valid negative access time must reach the invalid modification time. + for atime in (-1, -0.25): + assert_raises(TypeError, os.utime, fname, (atime, object())) + assert_raises(TypeError, os.utime, fname, ns=(-1, object())) + fd = os.open(fname, os.O_WRONLY | os.O_APPEND) assert os.write(fd, CONTENT3) == len(CONTENT3) os.close(fd) @@ -530,6 +641,11 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert os.access("README.md", os.F_OK) is True assert os.access("README.md", os.R_OK) is True +# os.access - CPython returns False for invalid modes for Unix +if os.name != "nt": + with tempfile.NamedTemporaryFile() as tmp: + assert not os.access(tmp.name, 255) + # argv and the group list are sequences; an arbitrary iterable must be rejected # rather than drained. if hasattr(os, "posix_spawn"): @@ -545,3 +661,290 @@ def __exit__(self, exc_type, exc_val, exc_tb): assert os.stat_result(tuple(range(10)), {"st_atime": 1.5}).st_atime == 1.5 with assert_raises(TypeError): os.stat_result(tuple(range(10)), ["st_atime"]) + + +def mkfifo_paths_and_directory_descriptors(): + import errno + import inspect + import tempfile + import warnings + + assert str(inspect.signature(os.mkfifo)) == "(path, mode=438, *, dir_fd=None)" + assert os.mkfifo not in os.supports_fd + assert os.mkfifo not in os.supports_follow_symlinks + if sys.platform.startswith("linux"): + assert os.mkfifo in os.supports_dir_fd + + class Path: + def __init__(self, value): + self.value = value + + def __fspath__(self): + return self.value + + class Index: + def __init__(self, value): + self.value = value + + def __index__(self): + return self.value + + class BadIndex: + def __index__(self): + raise RuntimeError("mkfifo index marker") + + # Never open a FIFO: creating, inspecting and unlinking it cannot wait for + # another process to connect. All paths belong to this temporary directory. + with tempfile.TemporaryDirectory(prefix="rustpython-mkfifo-") as directory: + path = os.path.join(directory, "fifo") + for value in (path, os.fsencode(path), Path(path), Path(os.fsencode(path))): + assert os.mkfifo(path=value, mode=0) is None + info = os.stat(path) + assert stat.S_ISFIFO(info.st_mode) + assert stat.S_IMODE(info.st_mode) == 0 + with assert_raises(FileExistsError) as error: + os.mkfifo(value) + assert error.exception.errno == errno.EEXIST + assert error.exception.filename is None + os.unlink(path) + + assert os.mkfifo(path, dir_fd=None) is None + assert stat.S_ISFIFO(os.stat(path).st_mode) + assert stat.S_IMODE(os.stat(path).st_mode) & ~0o666 == 0 + os.unlink(path) + + for value in (None, 1.5): + assert_raises(TypeError, os.mkfifo, path, value) + for value in (2**31, -(2**31) - 1, 2**100, -(2**100)): + with assert_raises(OverflowError) as error: + os.mkfifo(path, value) + assert str(error.exception) == "Python int too large to convert to C int" + with assert_raises(OverflowError) as error: + os.mkfifo(path, dir_fd=value) + expected = ( + "fd is greater than maximum" if value > 0 else "fd is less than minimum" + ) + assert str(error.exception) == expected + for value in (1.5, "fd"): + assert_raises(TypeError, os.mkfifo, path, dir_fd=value) + for value in (None, 1): + with assert_raises(TypeError) as error: + os.mkfifo(value) + expected = "NoneType" if value is None else "int" + assert str(error.exception) == ( + "mkfifo: path should be string, bytes or os.PathLike, not " + expected + ) + assert_raises(TypeError, os.mkfifo, Path(None)) + for value in (path + "\0", os.fsencode(path) + b"\0"): + with assert_raises(ValueError) as error: + os.mkfifo(value) + assert str(error.exception) == "mkfifo: embedded null character in path" + assert_raises(TypeError, os.mkfifo, path, 0o600, None) + for options in ({"mode": BadIndex()}, {"dir_fd": BadIndex()}): + with assert_raises(RuntimeError) as error: + os.mkfifo(path, **options) + assert str(error.exception) == "mkfifo index marker" + with assert_raises(FileNotFoundError) as error: + os.mkfifo(os.path.join(directory, "missing", "fifo")) + assert error.exception.errno == errno.ENOENT + assert error.exception.filename is None + + directory_fd = os.open(directory, os.O_RDONLY) + try: + if os.mkfifo in os.supports_dir_fd: + assert ( + os.mkfifo(Path(b"fifo"), Index(0o600), dir_fd=Index(directory_fd)) + is None + ) + assert stat.S_ISFIFO(os.stat(path).st_mode) + assert stat.S_IMODE(os.stat(path).st_mode) & ~0o600 == 0 + os.unlink(path) + for value in (-1, -(2**31)): + assert os.mkfifo(path, dir_fd=value) is None + assert stat.S_ISFIFO(os.stat(path).st_mode) + os.unlink(path) + with assert_raises(OSError) as error: + os.mkfifo("fifo", dir_fd=-1) + assert error.exception.errno == errno.EBADF + assert error.exception.filename is None + with warnings.catch_warnings(record=True) as records: + warnings.simplefilter("always") + assert os.mkfifo(path, dir_fd=True) is None + assert len(records) == 1 + assert records[0].category is RuntimeWarning + assert str(records[0].message) == "bool is used as a file descriptor" + os.unlink(path) + else: + with assert_raises(NotImplementedError) as error: + os.mkfifo(path, dir_fd=directory_fd) + assert str(error.exception) == "dir_fd unavailable on this platform" + finally: + os.close(directory_fd) + + +if sys.platform.startswith("linux"): + assert hasattr(os, "mkfifo") +if hasattr(os, "mkfifo"): + mkfifo_paths_and_directory_descriptors() + + +import errno + + +def nonblocking_windows_pipe(): + reader, writer = os.pipe() + try: + for fd in (reader, writer): + assert os.get_blocking(fd) + os.set_blocking(fd, False) + assert not os.get_blocking(fd) + os.set_blocking(fd, True) + assert os.get_blocking(fd) + os.set_blocking(fd, False) + + assert os.read(reader, 0) == b"" + assert os.write(writer, b"") == 0 + try: + os.read(reader, 1) + except BlockingIOError as error: + assert error.errno == errno.EAGAIN + else: + raise AssertionError("empty nonblocking pipe did not raise") + finally: + os.close(reader) + os.close(writer) + + +if os.name == "nt": + nonblocking_windows_pipe() + + +if os.name == "nt": + # Windows filesystem bytes preserve lone surrogates via surrogatepass. + import nt + + for character in ("\ud800", "\udcff", "\udfff"): + path = "C:\\" + character + "\\leaf" + encoded = os.fsencode(path) + assert nt._path_splitroot_ex(encoded) == ( + b"C:", + b"\\", + os.fsencode(character + "\\leaf"), + ) + assert nt._path_normpath(encoded) == encoded + for operation in (nt._path_splitroot_ex, nt._path_normpath): + with assert_raises(UnicodeDecodeError): + operation(b"\xff") + + # Exercise the shared bytes-to-native-path converter, not only nt helpers. + # A surrogate pair encoded as two surrogatepass sequences must also become + # the same native UTF-16 path as its non-BMP character spelling. + with tempfile.TemporaryDirectory() as directory: + for character in ("\ud800", "\udcff", "\udfff", "\ud800\udc00"): + path = os.path.join(directory, character) + encoded = os.fsencode(path) + os.mkdir(encoded) + try: + native_path = ( + os.path.join(directory, "\U00010000") + if character == "\ud800\udc00" + else path + ) + assert stat.S_ISDIR(os.stat(native_path).st_mode) + assert stat.S_ISDIR(os.stat(encoded).st_mode) + finally: + os.rmdir(encoded) + for invalid in (b"\xff", b"\xed\xa0", b"\xc0\x80"): + with assert_raises(UnicodeDecodeError): + os.mkdir(os.fsencode(directory) + b"\\" + invalid) + + # CreateProcess must preserve UTF-16 environment keys and values, including + # lone surrogates. Valid pairs become a single code point on import. + # Normalization keeps the last caseless key; CRT environ hides drive entries. + import subprocess + + environment = os.environ.copy() + environment.update( + { + "RUSTPYTHON_SURROGATE_VALUE": "\ud800\udcff\udfff", + "RUSTPYTHON_\ud800_KEY": "surrogate key", + "\u00e9_FIRST": "non-ASCII initial", + "RustPython_Case_Test": "first", + "RUSTPYTHON_CASE_TEST": "last", + "=Z:": "Z:\\", + } + ) + subprocess.run( + [ + sys.executable, + "-S", + "-c", + "import os; " + "assert os.environ['RUSTPYTHON_SURROGATE_VALUE'] == '\\U000100ff\\udfff'; " + "assert os.environ['RUSTPYTHON_\\ud800_KEY'] == 'surrogate key'; " + "assert os.environ['\\u00e9_FIRST'] == 'non-ASCII initial'; " + "assert os.environ['RUSTPYTHON_CASE_TEST'] == 'last'; " + "assert '=Z:' not in os.environ", + ], + env=environment, + check=True, + ) + # Key normalization reaches LCMapStringEx before the validation pass. + with assert_raises(OSError) as error: + subprocess.run([sys.executable, "-S", "-c", "pass"], env={"": "x"}) + assert error.exception.winerror == 87 + for key, value in (("a=b", "x"), ("a\0b", "x"), ("a", "b\0c")): + with assert_raises(ValueError): + subprocess.run([sys.executable, "-S", "-c", "pass"], env={key: value}) + + +if sys.platform == "win32": + # Legacy filesystem bytes must not reinterpret native UTF-16 paths, argv, + # or environment values as bytes in the ANSI code page. + import subprocess + import textwrap + + environment = os.environ.copy() + environment["PYTHONLEGACYWINDOWSFSENCODING"] = "1" + environment["RUSTPYTHON_LEGACY_WIDE"] = "\U0001f40d\ud800" + subprocess.run( + [ + sys.executable, + "-c", + textwrap.dedent(r""" + import os + import sys + import tempfile + + assert sys.getfilesystemencoding() == "mbcs" + assert sys.getfilesystemencodeerrors() == "replace" + assert sys.argv[1] == "\U0001f40d\ud800" + assert os.environ["RUSTPYTHON_LEGACY_WIDE"] == sys.argv[1] + assert os.getcwdb() == os.fsencode(os.getcwd()) + with tempfile.TemporaryDirectory() as directory: + name = "native-\U0001f40d\ud800" + path = os.path.join(directory, name) + with open(path, "wb") as file: + file.write(b"wide") + assert name in os.listdir(directory) + byte_directory = os.fsencode(directory) + assert os.fsencode(name) in os.listdir(byte_directory) + with os.scandir(byte_directory) as entries: + assert os.fsencode(name) in [entry.name for entry in entries] + assert os.stat(path).st_size == 4 + # Valid UTF-8 bytes still require decoding with mbcs here. + encoded = b"legacy-\xc3\xa9" + decoded = encoded.decode("mbcs", "replace") + assert os.path.normpath(encoded) == os.fsencode(decoded) + assert os.path.splitroot(encoded)[2] == os.fsencode(decoded) + if not any(c in decoded for c in '<>:"/\\|?*'): + with open(os.path.join(directory, decoded), "wb") as file: + file.write(b"bytes") + bytepath = os.fsencode(directory) + b"\\" + encoded + assert os.stat(bytepath).st_size == 5 + """), + "\U0001f40d\ud800", + ], + env=environment, + check=True, + ) diff --git a/extra_tests/snippets/stdlib_pickle.py b/extra_tests/snippets/stdlib_pickle.py new file mode 100644 index 00000000000..ecafea1b18f --- /dev/null +++ b/extra_tests/snippets/stdlib_pickle.py @@ -0,0 +1,159 @@ +import _pickle +import gc +import io +import sys +import weakref +from types import MappingProxyType, MethodType + +from testutils import assert_raises + +# BINPUT leaves holes; MEMOIZE uses the number of present entries. +unpickler = _pickle.Unpickler(io.BytesIO(b"\x80\x04]q\x07\x94h\x01\x86.")) +left, right = unpickler.load() +assert left is right +memo = unpickler.memo.copy() +assert list(memo) == [1, 7] +assert memo[1] is left +assert memo[7] is left + +# Slot wrapper descriptors reduce to lookup on their defining class. +assert object.__str__.__reduce__() == (getattr, (object, "__str__")) +assert _pickle.loads(_pickle.dumps(object.__str__)) is object.__str__ + +# Oversized advertised lengths are rejected before trying to read or allocate. +for opcode, name in ( + (b"\x8e", "BINBYTES"), + (b"\x8d", "BINUNICODE"), + (b"\x95", "FRAME"), +): + data = b"\x80\x04" + opcode + (sys.maxsize + 1).to_bytes(8, "little") + for load in ( + _pickle.loads, + lambda data: _pickle.Unpickler(io.BytesIO(data)).load(), + ): + with assert_raises(OverflowError) as caught: + load(data) + if name == "FRAME": + expected = f"FRAME length exceeds system's maximum of {sys.maxsize} bytes" + else: + expected = f"{name} exceeds system's maximum size of {sys.maxsize} bytes" + assert str(caught.exception) == expected + + +# Reduction returns getattr from the active frame's builtins without calling it. +class ReductionOwner: + __slots__ = ("slot",) + + def method(self): + pass + + +owner = ReductionOwner() +items = [] +replacement_getattr = object() +for descriptor, receiver, name in ( + (object.__str__, object, "__str__"), + (str.join, str, "join"), + (io.BytesIO.getvalue, io.BytesIO, "getvalue"), + (ReductionOwner.slot, ReductionOwner, "slot"), + (owner.__str__, owner, "__str__"), + (items.append, items, "append"), + (dict.fromkeys, dict, "fromkeys"), + (owner.method, owner, "method"), +): + for builtins_type in (dict, MappingProxyType): + namespace = { + "__builtins__": builtins_type({"getattr": replacement_getattr}), + "descriptor": descriptor, + } + exec("reduced = descriptor.__reduce__()", namespace) + assert namespace["reduced"] == (replacement_getattr, (receiver, name)) + + namespace["__builtins__"] = builtins_type({}) + with assert_raises(AttributeError) as caught: + exec("descriptor.__reduce__()", namespace) + assert caught.exception.args == ("getattr",) + +# Module-bound functions reduce to a name without looking up getattr. +namespace = {"__builtins__": {}, "function": len} +exec("reduced = function.__reduce__()", namespace) +assert namespace["reduced"] == "len" + + +class MissingBuiltin(dict): + def __getitem__(self, key): + raise KeyError(key) + + def __missing__(self, key): + raise AssertionError("must not retry __missing__ after custom __getitem__") + + +for descriptor, name in ( + (object.__str__, "getattr"), + (iter([1]), "iter"), + (reversed([1]), "reversed"), +): + namespace = {"__builtins__": MissingBuiltin(), "descriptor": descriptor} + with assert_raises(AttributeError) as caught: + exec("descriptor.__reduce__()", namespace) + assert caught.exception.args == (name,) + + +name_error = RuntimeError("function name first") + + +class NamedCallable: + def __call__(self, *args): + pass + + @property + def __name__(self): + raise name_error + + +namespace = { + "__builtins__": {}, + "method": MethodType(NamedCallable(), owner), +} +with assert_raises(RuntimeError) as caught: + exec("method.__reduce__()", namespace) +assert caught.exception is name_error + + +# Unpickler payloads can retain a cycle through their memo proxy. +class UnpicklerCycleStream: + def __init__(self): + self.source = io.BytesIO(_pickle.dumps([1, 2, 3], protocol=4)) + self.read = self.source.read + self.readline = self.source.readline + self.peek = self.peek_bytes + + def peek_bytes(self, size=0): + position = self.source.tell() + data = self.source.read(size) + self.source.seek(position) + return data + + +class UnpicklerCycleBuffers: + def __iter__(self): + return self + + def __next__(self): + raise StopIteration + + +def unpickler_payload_cycle(kind): + stream = UnpicklerCycleStream() + buffers = UnpicklerCycleBuffers() + unpickler = _pickle.Unpickler(stream, buffers=buffers) + holder = stream if kind == "stream" else buffers + holder.proxy = unpickler.memo + return weakref.ref(holder) + + +for kind in ("stream", "buffers"): + reference = unpickler_payload_cycle(kind) + for _ in range(3): + gc.collect() + assert reference() is None, kind diff --git a/extra_tests/snippets/stdlib_pyexpat.py b/extra_tests/snippets/stdlib_pyexpat.py new file mode 100644 index 00000000000..dc83ccf4037 --- /dev/null +++ b/extra_tests/snippets/stdlib_pyexpat.py @@ -0,0 +1,412 @@ +import codecs +import io +import sys +from xml.parsers import expat + +# Without namespace expansion, element and attribute names retain prefixes. +for separator, expected_name, expected_attribute in ( + (None, "p:x", "p:a"), + ("!", "urn:p!x", "urn:p!a"), +): + for ordered in (False, True): + parser = expat.ParserCreate(namespace_separator=separator) + parser.ordered_attributes = ordered + starts = [] + ends = [] + parser.StartElementHandler = lambda name, attrs: starts.append((name, attrs)) + parser.EndElementHandler = ends.append + parser.Parse('', True) + assert [name for name, attrs in starts] == ["r", expected_name] + assert ends == [expected_name, "r"] + expected_attributes = ( + [expected_attribute, "v", "a", "u"] + if ordered + else {expected_attribute: "v", "a": "u"} + ) + assert starts[1][1] == expected_attributes + +# Parse accepts contiguous buffer objects, including views of mutable input. +for xml in (bytearray(b"ok"), memoryview(b"ok")): + parser = expat.ParserCreate() + text = [] + parser.CharacterDataHandler = text.append + assert parser.Parse(xml, True) == 1 + assert "".join(text) == "ok" + +try: + expat.ParserCreate().Parse(memoryview(b"")[::2], True) +except BufferError: + pass +else: + raise AssertionError("Parse accepted a non-contiguous buffer") + +# Keep the export alive through callbacks without retaining its read lock. +xml = bytearray(b"") +parser = expat.ParserCreate() +parser.StartElementHandler = lambda *_: xml.extend(b" ") +try: + parser.Parse(xml, True) +except BufferError: + pass +else: + raise AssertionError("Parse released its input buffer before the callback") +xml.extend(b" ") + + +# Expat's Error* positions alias Current* even before a parse error. +def check_position_aliases(parser): + for suffix in ("LineNumber", "ColumnNumber", "ByteIndex"): + assert getattr(parser, "Error" + suffix) == getattr(parser, "Current" + suffix) + try: + setattr(parser, "Error" + suffix, 0) + except AttributeError: + pass + else: + raise AssertionError("error positions must be read-only") + + +parser = expat.ParserCreate() +check_position_aliases(parser) +parser.StartElementHandler = lambda *_: check_position_aliases(parser) +parser.Parse(b"", False) +check_position_aliases(parser) +try: + parser.Parse(b"", True) +except expat.ExpatError: + check_position_aliases(parser) +else: + raise AssertionError("incomplete XML accepted") + +# Unicode input overrides encoding declarations only before parsing starts. +for declaration in ("iso-8859-1", "utf-16", "unknown-encoding"): + parser = expat.ParserCreate() + text = [] + parser.CharacterDataHandler = text.append + parser.Parse(f'', False) + parser.Parse("£€", True) + assert "".join(text) == "£€" + +for first, tail, expected in ( + ("", '£', "£"), + (b"", '£', "£"), + ('', b"\xc2\xa3", "£"), + (b'', "£", "£"), + (b'', b"\xa3", "£"), +): + parser = expat.ParserCreate() + text = [] + parser.CharacterDataHandler = text.append + parser.Parse(first, False) + parser.Parse(tail, True) + assert "".join(text) == expected + +# Declaration metadata is not the parser's effective encoding: omitted +# encoding stays None, spelling is preserved, and no declaration means no event. +for encoding in ("UTF-8", "UTF-16", "UTF-16LE", "UTF-16BE", "ISO-8859-1", "US-ASCII"): + for declaration, expected in ( + ("", []), + ('', [("1.0", None, -1)]), + ('', [("1.7", None, 1)]), + ( + '', + [("1.0", "uTf-8", 0)], + ), + ): + # An explicit encoding wins over a conflicting declaration, even when + # BOMs, code units, and the declaration terminator cross Parse calls. + document = (declaration + "abc").encode(encoding) + for chunk_size in (1, len(document)): + parser = expat.ParserCreate(encoding) + declarations = [] + text = [] + parser.XmlDeclHandler = lambda *args: declarations.append(args) + parser.CharacterDataHandler = text.append + for offset in range(0, len(document), chunk_size): + parser.Parse(document[offset : offset + chunk_size], False) + parser.Parse(b"", True) + assert declarations == expected, (encoding, declaration, declarations) + assert "".join(text) == "abc" + +# Native byte decoding must be used rather than UTF-8 preprocessing. +for encoding, character in (("ISO-8859-1", "£"), ("UTF-16LE", "𝄞"), ("UTF-16BE", "𝄞")): + parser = expat.ParserCreate(encoding) + text = [] + parser.CharacterDataHandler = text.append + for byte in ("" + character + "").encode(encoding): + parser.Parse(bytes([byte]), False) + parser.Parse(b"", True) + assert "".join(text) == character + +# No declaration callback is allowed before the whole declaration is valid. +for declaration in ( + '', + '', +): + parser = expat.ParserCreate() + declarations = [] + parser.XmlDeclHandler = lambda *args: declarations.append(args) + try: + for byte in (declaration + "").encode(): + parser.Parse(bytes([byte]), False) + parser.Parse(b"", True) + except expat.ExpatError: + pass + else: + raise AssertionError("malformed declaration accepted") + assert not declarations + + +# Buffer configuration uses integer objects, not the __index__ protocol. +class BufferIndex: + def __index__(self): + return 32 + + +parser = expat.ParserCreate() +assert parser.buffer_size == 8192 +assert parser.buffer_used == 0 +parser.buffer_size = 8192 +assert parser.buffer_text is False # Identical size does not enable buffering. +for value in (BufferIndex(), "32"): + try: + parser.buffer_size = value + except TypeError as exc: + assert str(exc) == "buffer_size must be an integer" + else: + raise AssertionError("non-integer buffer size accepted") +parser.buffer_size = True +assert parser.buffer_size == 1 and parser.buffer_text is True +parser.buffer_text = False +assert parser.buffer_size == 1 and parser.buffer_used == 0 +for name in ("buffer_size", "buffer_text", "CharacterDataHandler"): + try: + delattr(parser, name) + except RuntimeError as exc: + assert str(exc) == "Cannot delete attribute" + else: + raise AssertionError("parser attribute deleted") + +# CPython 3.15.0 retains pending data during callbacks; 3.15.2 fixes +# reentrant flushes. Mutating callbacks can recursively redeliver data or +# invalidate the old buffer, so guard their execution, not just assertions. +# Always exercise the corrected behavior on RustPython. +callback_safe_flush = sys.implementation.name != "cpython" or sys.version_info >= ( + 3, + 15, + 2, +) + +if callback_safe_flush: + # Flushed data is detached before invoking callbacks. + # A callback may change the buffer without leaving a Rust lock held. + parser = expat.ParserCreate() + parser.buffer_text = True + observed = [] + resized = False + + def resize_during_flush(text): + global resized + observed.append((text, parser.buffer_used)) + if not resized: + resized = True + parser.buffer_size = 64 + + parser.CharacterDataHandler = resize_during_flush + parser.Parse("éz", True) + assert observed == [("éz", 0)] + assert parser.buffer_size == 64 and parser.buffer_used == 0 + + # CharacterDataHandler replacement flushes existing data to the old handler. + parser = expat.ParserCreate() + parser.buffer_text = True + old_text, new_text = [], [] + parser.CharacterDataHandler = old_text.append + + def replace_from_character_callback(text): + old_text.append(text) + if len(old_text) == 1: + parser.CharacterDataHandler = new_text.append + + parser.CharacterDataHandler = replace_from_character_callback + parser.Parse(b"ab", True) + assert old_text == ["ab"] and new_text == [] + assert parser.CharacterDataHandler is not replace_from_character_callback + assert parser.buffer_used == 0 + +# Flush exceptions propagate; the used count is reset even on failure. +parser = expat.ParserCreate() +parser.buffer_text = True + + +def fail_buffered_text(text): + if callback_safe_flush: + assert parser.buffer_used == 0 + raise ValueError("buffer callback failure") + + +parser.CharacterDataHandler = fail_buffered_text +try: + parser.Parse("é", True) +except ValueError as exc: + assert str(exc) == "buffer callback failure" +else: + raise AssertionError("buffer callback exception swallowed") +assert parser.buffer_used == 0 + +# An external parser inherits configuration but not pending character data. +parser = expat.ParserCreate() +parser.buffer_size = 64 +parser.CharacterDataHandler = lambda text: None +child = parser.ExternalEntityParserCreate("context") +assert child.buffer_text is True and child.buffer_size == 64 +assert child.buffer_used == 0 +assert child.CharacterDataHandler is parser.CharacterDataHandler +child.buffer_text = False +assert parser.buffer_text is True + +if callback_safe_flush: + # An overflow-triggered flush rechecks callback changes before delivering the + # new backend event. Disabling buffering must not discard that new text; + # removing the character handler must discard it. + for remove_handler in (False, True): + parser = expat.ParserCreate() + parser.buffer_size = 2 + delivered = [] + + def change_during_overflow(text): + delivered.append(text) + if len(delivered) == 1: + if remove_handler: + parser.CharacterDataHandler = None + else: + parser.buffer_text = False + + parser.CharacterDataHandler = change_during_overflow + parser.Parse(b"abc", True) + assert delivered == (["a"] if remove_handler else ["a", "bc"]) + assert parser.buffer_used == 0 + +# Callback failure clears all handlers and cannot resume queued events on a +# subsequent Parse call, regardless of character buffering. +for buffered in (False, True): + parser = expat.ParserCreate() + parser.buffer_text = buffered + parser.StartElementHandler = lambda *args: None + parser.EndElementHandler = lambda *args: None + + def fail_character_callback(text): + raise ValueError("stop parser") + + parser.CharacterDataHandler = fail_character_callback + try: + parser.Parse(b"xy", False) + except ValueError as exc: + assert str(exc) == "stop parser" + else: + raise AssertionError("callback exception swallowed") + assert parser.CharacterDataHandler is None + assert parser.StartElementHandler is None + assert parser.EndElementHandler is None + assert parser.buffer_used == 0 + try: + parser.Parse(b"", True) + except expat.ExpatError as exc: + assert exc.code == expat.errors.codes[expat.errors.XML_ERROR_FINISHED] + else: + raise AssertionError("aborted parser resumed") + +# A callback return conversion error is not a callback exception: Expat keeps +# the handlers and permits a subsequent Parse call to finish the document. +parser = expat.ParserCreate() +parser.SetParamEntityParsing(expat.XML_PARAM_ENTITY_PARSING_ALWAYS) +invalid_result = lambda *args: object() +parser.ExternalEntityRefHandler = invalid_result +try: + parser.Parse(b'', False) +except TypeError: + pass +else: + raise AssertionError("non-integer external handler result accepted") +assert parser.ExternalEntityRefHandler is invalid_result +assert parser.Parse(b"", True) == 1 + +# Declaration callbacks participate in the same non-resumable error cleanup. +parser = expat.ParserCreate() + + +def fail_declaration(*args): + raise ValueError("declaration failure") + + +parser.XmlDeclHandler = fail_declaration +parser.StartElementHandler = lambda *args: None +try: + parser.Parse(b'', True) +except ValueError as exc: + assert str(exc) == "declaration failure" +else: + raise AssertionError("declaration exception swallowed") +assert parser.XmlDeclHandler is None +assert parser.StartElementHandler is None + + +# Codec failures preserve the original exception, but leave the parser failed. +class ProbeError(Exception): + pass + + +marker = ProbeError("codec probe") +calls = [] + + +def decode(data, errors="strict"): + calls.append((bytes(data), errors)) + raise marker + + +def search(name): + if name == "xmlprobeexception": + return codecs.CodecInfo( + name=name, encode=lambda s, e: (b"", len(s)), decode=decode + ) + + +codecs.register(search) +for final in (False, True): + p = expat.ParserCreate() + events = [] + p.StartElementHandler = lambda *args: events.append(args) + before = len(calls) + try: + p.Parse(b'', final) + except ProbeError as e: + assert e is marker + else: + raise AssertionError("codec exception lost") + assert calls[-1] == (bytes(range(256)), "replace") + for retry in ( + lambda: p.Parse(b"", True), + lambda: p.ParseFile(io.BytesIO(b"")), + ): + try: + retry() + except expat.ExpatError as e: + assert e.code == 18 + else: + raise AssertionError("failed parser accepted a document") + assert len(calls) == before + 1 and not events +for xml in (b"", b''): + p = expat.ParserCreate() + try: + p.Parse(xml, True) + except expat.ExpatError as first: + code = first.code + else: + raise AssertionError("malformed document accepted") + try: + p.Parse(b"", True) + except expat.ExpatError as second: + assert second.code == code + else: + raise AssertionError("parse error reset") +codecs.unregister(search) diff --git a/extra_tests/snippets/stdlib_re.py b/extra_tests/snippets/stdlib_re.py index 80006aaf3e8..120b2c89329 100644 --- a/extra_tests/snippets/stdlib_re.py +++ b/extra_tests/snippets/stdlib_re.py @@ -126,3 +126,31 @@ def test_findall_group_that_did_not_participate(): test_findall_group_that_did_not_participate() + + +def test_backtracking_restores_repeat_state(): + # A {m,n} repeat that stopped at its maximum kept the extra count when the + # rest of the pattern failed and the matcher went back into the repeat. + assert re.match(r"(?:a*|b){2}x", "bbx").span() == (0, 3) + assert re.fullmatch(r"(?:b*|a){2}", "aa").span() == (0, 2) + assert re.fullmatch(r"(?:b*|a){1,2}", "aa").span() == (0, 2) + + # A lazy repeat nested in another one. + assert re.fullmatch(r"(?:x(?:ab)*?){2,3}?", "xabxab").span() == (0, 6) + + # A group set before a lookaround must be unset again when the matcher + # backtracks past it. + assert re.match(r"(a)?(? 0, ("native stdin child timed out", output) + return timeout + + def read_output(timeout): + nonlocal output_eof + ready, _, _ = select.select([process.stdout], [], [], min(timeout, remaining())) + if ready: + try: + chunk = os.read(process.stdout.fileno(), 4096) + except BlockingIOError: + return + if chunk: + output.extend(chunk) + assert len(output) <= 65536, ("child output limit", output) + else: + output_eof = True + + def expect(marker, start=0, interrupt=False): + observed = len(output) + retry_at = time.monotonic() + attempts = 0 + while marker not in output[start:]: + assert not output_eof, ("child exited before marker", marker, output) + timeout = remaining() + if interrupt and len(output) == observed and attempts < 10: + # Drain bytes already available before deciding to retry. + read_output(0) + if len(output) != observed or output_eof: + continue + now = time.monotonic() + if now >= retry_at: + # Prompt emission precedes read(). Retry only this child + # to cover that race; never send input to wake the read. + assert process.poll() is None, ("child exited", output) + process.send_signal(signal.SIGINT) + attempts += 1 + retry_at = now + 0.5 + timeout = min(timeout, max(0, retry_at - time.monotonic())) + # Any response stops retries, including a partial traceback or + # marker, so another SIGINT does not interrupt its reporting. + read_output(timeout) + + def write_input(data): + offset = 0 + while offset < len(data): + _, ready, _ = select.select([], [process.stdin], [], remaining()) + if ready: + try: + written = os.write(process.stdin.fileno(), data[offset:]) + except BlockingIOError: + continue + assert written > 0 + offset += written + + try: + os.set_blocking(process.stdin.fileno(), False) + os.set_blocking(process.stdout.fileno(), False) + expect(prompt) + after_prompt = len(output) + source = b"print('__NATIVE_' + 'STDIN_EXECUTED__', flush=True)" + # Keep the pipe empty until the native reader dispatches the signal. + # Only then provide a complete line and EOF; this does not assert + # CPython's behavior for a partial libc fgets interrupted by a signal. + expect(handled, after_prompt, interrupt=True) + write_input(source + b"\n") + process.stdin.close() + expect(executed, after_prompt) + while not output_eof: + read_output(remaining()) + returncode = process.wait(timeout=remaining()) + assert returncode == 0, (returncode, output) + assert output.count(executed) == 1, output + assert b"KeyboardInterrupt" not in output, output + finally: + process.stdin.close() + process.stdout.close() + if process.poll() is None: + process.kill() + process.wait(timeout=5.0) + + +check_native_stdin_eintr() + + +# A helper thread state on the native main thread must use the interpreter's +# handlers, both when querying/replacing them and when dispatching a signal. +def check_interpreter_helper_handlers(): + import _testinternalcapi + + import _interpreters + + calls = [] + + def handler(signum, frame): + calls.append(signum) + + previous = signal.signal(signal.SIGINT, handler) + try: + assert ( + _testinternalcapi.exec_interpreter( + _interpreters.get_current()[0], + "import signal; " + "assert callable(signal.getsignal(signal.SIGINT)); " + "signal.raise_signal(signal.SIGINT); " + "signal.signal(signal.SIGINT, signal.SIG_IGN)", + main=False, + ) + == 0 + ) + assert calls == [signal.SIGINT] + assert signal.getsignal(signal.SIGINT) == signal.SIG_IGN + finally: + signal.signal(signal.SIGINT, previous) + + +if "_thread" in sys.builtin_module_names: + check_interpreter_helper_handlers() diff --git a/extra_tests/snippets/stdlib_socket.py b/extra_tests/snippets/stdlib_socket.py index d9dadeb4a4b..29a697c43d8 100644 --- a/extra_tests/snippets/stdlib_socket.py +++ b/extra_tests/snippets/stdlib_socket.py @@ -186,3 +186,142 @@ pass with assert_raises(ValueError): sizes.recvfrom(-1) + + +import sys + + +def receive_sizes_and_truncation(): + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as receiver: + receiver.bind(("127.0.0.1", 0)) + receiver.settimeout(2) + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sender: + for method in (receiver.recv_into, receiver.recvfrom_into): + for size in (-1, 5): + try: + method(bytearray(4), size) + except ValueError: + pass + else: + raise AssertionError("invalid receive size accepted") + sender.sendto(b"abc", receiver.getsockname()) + destination = bytearray(b"------") + result = method(memoryview(destination)[1:5], 0) + assert (result[0] if isinstance(result, tuple) else result) == 3 + assert destination == b"-abc--" + + if sys.platform.startswith("linux"): + for method in (receiver.recv_into, receiver.recvfrom_into): + sender.sendto(b"abcdefgh", receiver.getsockname()) + for flags in (socket.MSG_PEEK | socket.MSG_TRUNC, socket.MSG_TRUNC): + destination = bytearray(b"------") + result = method(memoryview(destination)[1:5], 3, flags) + assert (result[0] if isinstance(result, tuple) else result) == 8 + assert destination == b"-abc--" + for method in (receiver.recv, receiver.recvfrom, receiver.recvmsg): + sender.sendto(b"abcdefgh", receiver.getsockname()) + result = ( + method(3, 0, socket.MSG_TRUNC) + if method == receiver.recvmsg + else method(3, socket.MSG_TRUNC) + ) + data = result[0] if isinstance(result, tuple) else result + assert data[:3] == b"abc" + if sys.implementation.name == "rustpython": + # Some CPython recv paths enlarge the bytes result to the + # reported datagram length, including an unwritten tail. + assert data == b"abc" + + +def tcp_truncation_preserves_buffer(protocol=0): + import signal + + try: + listener = socket.socket(socket.AF_INET, socket.SOCK_STREAM, protocol) + except OSError: + if protocol: + return # MPTCP is optional in the running kernel. + raise + with listener: + listener.bind(("127.0.0.1", 0)) + listener.listen() + with socket.create_connection(listener.getsockname()) as sender: + receiver, _ = listener.accept() + with receiver: + receiver.settimeout(2) + for method in (receiver.recv_into, receiver.recvfrom_into): + destination = bytearray(b"original") + + def send_after_mutation(signum, frame): + destination[0] = ord("X") + sender.sendall(b"abc") + + previous = signal.signal(signal.SIGALRM, send_after_mutation) + try: + signal.setitimer(signal.ITIMER_REAL, 0.05) + result = method(destination, 0, socket.MSG_TRUNC) + assert (result[0] if isinstance(result, tuple) else result) == 3 + assert destination == b"Xriginal" + finally: + signal.setitimer(signal.ITIMER_REAL, 0) + signal.signal(signal.SIGALRM, previous) + + +receive_sizes_and_truncation() +if sys.platform.startswith("linux"): + tcp_truncation_preserves_buffer() + if hasattr(socket, "IPPROTO_MPTCP"): + tcp_truncation_preserves_buffer(socket.IPPROTO_MPTCP) + + +if hasattr(socket, "NETLINK_USERSOCK"): + with ( + socket.socket( + socket.AF_NETLINK, socket.SOCK_DGRAM, socket.NETLINK_USERSOCK + ) as sender, + socket.socket( + socket.AF_NETLINK, socket.SOCK_DGRAM, socket.NETLINK_USERSOCK + ) as receiver, + ): + sender.settimeout(2) + receiver.settimeout(2) + # AF_NETLINK parses unsigned 32-bit pid/group values, including masking. + sender.bind((2**32, 0)) + receiver.bind((0, 0)) + with assert_raises(TypeError): + sender.sendto(b"message", (0,)) + with assert_raises(TypeError): + sender.sendto(b"message", ("pid", 0)) + sender.sendto(b"message", receiver.getsockname()) + assert receiver.recvfrom(32) == (b"message", sender.getsockname()) + sender.connect(receiver.getsockname()) + assert sender.getpeername() == receiver.getsockname() + + +# Exhaust the iterable before exporting its writable buffers. +if hasattr(socket.socket, "recvmsg_into"): + first, second = bytearray(2), bytearray(2) + + def receive_buffers(): + yield first + first.extend(b"xx") + yield second + + reader, writer = socket.socketpair() + try: + writer.sendall(b"abcdef") + assert reader.recvmsg_into(receive_buffers())[0] == 6 + assert (first, second) == (b"abcd", b"ef") + finally: + reader.close() + writer.close() + +# Interface names are filesystem-encoded, so a lone surrogate that +# surrogateescape cannot produce is rejected before the lookup. +if os.name == "posix": + with assert_raises(UnicodeEncodeError): + socket.if_nametoindex("\ud800") + with assert_raises(OSError): + socket.if_nametoindex("\udcff\udcfe") + name = socket.if_indextoname(1) + assert socket.if_nametoindex(name) == 1 diff --git a/extra_tests/snippets/stdlib_sqlite.py b/extra_tests/snippets/stdlib_sqlite.py index 83fc7db94f0..769f2079a35 100644 --- a/extra_tests/snippets/stdlib_sqlite.py +++ b/extra_tests/snippets/stdlib_sqlite.py @@ -1,6 +1,52 @@ import sqlite3 as sqlite +import sys import unittest +assert sqlite.adapt.__text_signature__ == ( + "($module, obj, proto=PrepareProtocolType, alt=, /)" +) +# Check the shared parameter metadata separately from Clinic's line wrapping. +assert " ".join(sqlite.connect.__text_signature__.split()) == ( + "($module, /, database, *, timeout=5.0, detect_types=0, " + "isolation_level='', check_same_thread=True, factory=ConnectionType, " + "cached_statements=128, uri=False, " + "autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL)" +) +assert " ".join(sqlite.Connection.backup.__text_signature__.split()) == ( + "($self, /, target, *, pages=-1, progress=None, name='main', sleep=0.25)" +) + + +def check_connect_factory_signature(): + calls = [] + result = object() + database = object() + timeout = object() + + def factory(*args, **kwargs): + calls.append((args, kwargs)) + return result + + # The displayed Connection signature must not validate, convert, or add + # defaults to a custom factory's call. CPython forwards even missing or + # duplicate database arguments, unknown keywords, and unconverted values. + cases = [ + ((), {}), + ((database,), {"timeout": timeout, "extra": result}), + ((), {"database": database}), + ((database,), {"database": database}), + ] + for args, kwargs in cases: + kwargs = {"factory": factory, **kwargs} + assert sqlite.connect(*args, **kwargs) is result + assert calls.pop() == (args, kwargs) + with unittest.TestCase().assertRaises(TypeError): + sqlite.connect(database, timeout, factory=factory) + assert not calls + + +check_connect_factory_signature() + rows = [(3,), (4,)] cx = sqlite.connect(":memory:") cx.execute(";") @@ -54,19 +100,1297 @@ def finalize(self): cur.execute("select aggtxt(key) from foo") assert cur.fetchone()[0] == "341011" -# Blob extended-slice assignment with negative step -# Guard: CPython 3.11 has a SystemError bug with negative-step Blob slicing; -# this test only runs on RustPython where the fix is being validated. -# TODO: remove this once https://github.com/python/cpython/pull/150450 is released and RustPython CI uses it. -import sys +# Aggregate instances belong to a query, including its error and cancellation paths. +import gc +import weakref + +from testutils import assert_raises + + +def check_aggregate_lifetime(failure): + refs = [] + + class TrackedAggregate: + def __init__(self): + refs.append(weakref.ref(self)) + + def step(self, value): + if failure == "step": + raise ValueError("step") + + def finalize(self): + if failure == "finalize": + raise ValueError("finalize") + return object() if failure == "result" else 1 + + cx.create_aggregate("tracked", 1, TrackedAggregate) + query = "SELECT tracked(key) FROM foo GROUP BY key % 2" + if failure: + with assert_raises(sqlite.OperationalError): + cx.execute(query).fetchall() + else: + assert cx.execute(query).fetchall() == [(1,), (1,)] + assert refs + gc.collect() + assert all(ref() is None for ref in refs), failure + + # xFinal may run without any preceding xStep. + refs.clear() + assert cx.execute("SELECT tracked(key) FROM foo WHERE 0").fetchall() == [(None,)] + assert not refs + + +for failure in (None, "step", "finalize", "result"): + check_aggregate_lifetime(failure) + + +# Window functions share aggregate finalization, including an unfinished cursor. +window_refs = [] + + +class TrackedWindow: + def __init__(self): + window_refs.append(weakref.ref(self)) + + def step(self, value): + pass + + def inverse(self, value): + pass + + def value(self): + return 1 + + def finalize(self): + return 1 + + +cx.create_window_function("tracked_window", 1, TrackedWindow) +window_query = """ + SELECT tracked_window(key) OVER ( + ORDER BY key ROWS BETWEEN 1 PRECEDING AND CURRENT ROW + ) FROM foo +""" +assert cx.execute(window_query).fetchall() == [(1,)] * 4 +assert window_refs +assert all(ref() is None for ref in window_refs) +window_refs.clear() +window_cursor = cx.execute(window_query) +assert window_cursor.fetchone() == (1,) +window_cursor.close() +gc.collect() +assert window_refs and all(ref() is None for ref in window_refs) + + +# Releasing the last reference can run Python that reads the cursor/connection. +def check_aggregate_destructor(operation): + connection = sqlite.connect(":memory:") + cursor = connection.cursor() + cursor_ref = weakref.ref(cursor) + released = [] + + class Aggregate: + def step(self, value): + pass + + def value(self): + return 1 + + finalize = value + + def __del__(self): + current = cursor_ref() + if current is not None: + try: + current.description + except sqlite.ProgrammingError: + pass # The cursor may already have been closed. + released.append(connection.total_changes) + + connection.create_aggregate("tracked", 1, Aggregate) + expected = 1 + if operation == "execute": + cursor.execute("SELECT tracked(1)") + elif operation == "script": + cursor.executescript("SELECT tracked(1);") + elif operation == "many": + connection.execute("CREATE TABLE results(value)") + cursor.executemany("INSERT INTO results SELECT tracked(?)", [(1,), (2,)]) + expected = 2 + else: + connection.create_window_function("tracked_window", 1, Aggregate) + cursor.execute(""" + SELECT tracked_window(x) OVER (ROWS UNBOUNDED PRECEDING) + FROM (SELECT 1 AS x UNION ALL SELECT 2 UNION ALL SELECT 3) + """) + assert not released + if operation == "fetch": + assert cursor.fetchall() == [(1,), (1,), (1,)] + elif operation == "close": + cursor.close() + elif operation == "replace": + cursor.execute("SELECT 2") + else: + del cursor + gc.collect() + assert len(released) == expected, (operation, released) + connection.close() + + +for operation in ("execute", "script", "many", "fetch", "close", "replace", "drop"): + check_aggregate_destructor(operation) + + +# A nested query must not release its aggregate while an outer callback holds locks. +def check_nested_aggregate_destructor(operation): + outer = sqlite.connect(":memory:", autocommit=False) + nested = sqlite.connect(":memory:") + released = [] + inspect = lambda: outer.total_changes + + class Aggregate: + def step(self, value): + pass + + def finalize(self): + return 1 + + def __del__(self): + try: + inspect() + except sqlite.ProgrammingError: + pass # Closing the outer connection may finish before cleanup. + released.append(True) + + nested.create_aggregate("tracked", 1, Aggregate) + outer.set_trace_callback(lambda sql: nested.execute("SELECT tracked(1)")) + if operation == "commit": + outer.commit() + elif operation == "rollback": + outer.rollback() + elif operation == "autocommit": + outer.autocommit = True + elif operation in ("blobopen", "blob_index"): + outer.execute("CREATE TABLE blobs(data BLOB)") + outer.execute("INSERT INTO blobs VALUES (zeroblob(1))") + released.clear() + + def progress(): + nested.execute("SELECT tracked(1)") + return 0 + + outer.set_progress_handler(progress, 1) + blob = outer.blobopen("blobs", "data", 1) + outer.set_progress_handler(None, 0) + if operation != "blobopen": + released.clear() + inspect = lambda: len(blob) + + class Index: + def __index__(self): + nested.execute("SELECT tracked(1)") + return 0 + + index = Index() + assert blob[index] == 0 + blob[index] = 1 + assert len(released) == 2 + blob.close() + elif operation == "replace_callback": + + class Callback: + def __call__(self): + return 1 + + def __del__(self): + nested.execute("SELECT tracked(1)") + + for register in ( + lambda cb: outer.create_function("hook", 0, cb), + lambda cb: outer.create_aggregate("hook", 0, cb), + lambda cb: outer.create_window_function("hook", 0, cb), + lambda cb: outer.create_collation("hook", cb), + ): + released.clear() + register(Callback()) + register(None) + assert released + else: + outer.close() + assert released, operation + if operation != "close": + outer.set_trace_callback(None) + outer.close() + nested.close() + + +for operation in ( + "commit", + "rollback", + "autocommit", + "close", + "blobopen", + "blob_index", + "replace_callback", +): + check_nested_aggregate_destructor(operation) + + +class BlobIndex: + def __init__(self, value): + self.value = value + + def __index__(self): + return self.value + + +class BlobInt(int): + pass + + +class BrokenBlobIndex: + def __index__(self): + raise OverflowError("index conversion failed") + + +cx.execute("CREATE TABLE blobindices(b BLOB)") +cx.execute("INSERT INTO blobindices(b) VALUES (?)", (b"abc",)) +with cx.blobopen("blobindices", "b", 1) as blob: + assert blob[BlobIndex(-1)] == ord("c") + blob[BlobIndex(0)] = ord("A") + assert blob[0] == ord("A") + + test = unittest.TestCase() + for index in (sys.maxsize, -sys.maxsize - 1): + with test.assertRaisesRegex(IndexError, "^Blob index out of range$"): + blob[index] + with test.assertRaisesRegex(IndexError, "^Blob index out of range$"): + blob[index] = 0 + + for value in (sys.maxsize + 1, -sys.maxsize - 2): + for index in (value, BlobInt(value), BlobIndex(value)): + message = ( + f"^cannot fit '{type(index).__name__}' into an index-sized integer$" + ) + with test.assertRaisesRegex(IndexError, message): + blob[index] + with test.assertRaisesRegex(IndexError, message): + blob[index] = 0 + + for name, bounded_name in (("X" * 250, "X" * 200), ("€" * 67, "€" * 66)): + long_index = type(name, (), {"__index__": lambda self: sys.maxsize + 1})() + message = f"^cannot fit '{bounded_name}' into an index-sized integer$" + with test.assertRaisesRegex(IndexError, message): + blob[long_index] + with test.assertRaisesRegex(IndexError, message): + blob[long_index] = 0 + + with test.assertRaisesRegex(OverflowError, "^index conversion failed$"): + blob[BrokenBlobIndex()] + with test.assertRaisesRegex(OverflowError, "^index conversion failed$"): + blob[BrokenBlobIndex()] = 0 + assert blob[:] == b"Abc" + + +import sqlite3 + + +def statement_cache_reuse(): + for capacity, expected in ((0, 3), (-1, 3), (2, 1), (None, 1)): + options = {} if capacity is None else {"cached_statements": capacity} + with sqlite3.connect(":memory:", **options) as connection: + prepared = [] + + def authorizer(action, *args): + if action == sqlite3.SQLITE_SELECT: + prepared.append(action) + return sqlite3.SQLITE_OK + + connection.set_authorizer(authorizer) + for parameter in (1, 2, 3): + assert connection.execute("SELECT ?", (parameter,)).fetchall() == [ + (parameter,) + ] + assert len(prepared) == expected + if capacity == 2: + prepared.clear() + for value in (1, 2, 1, 3, 2): + assert connection.execute(f"SELECT {value}").fetchall() == [ + (value,) + ] + assert len(prepared) == 4 + connection.close() + + +statement_cache_reuse() + + +def cache_reprepare_with_authorizer(): + connection = sqlite3.connect(":memory:") + connection.execute("CREATE TABLE words(word TEXT COLLATE NOCASE)") + connection.execute("CREATE INDEX word_index ON words(word)") + connection.executemany("INSERT INTO words VALUES (?)", [("alpha",), ("beta",)]) + sql = "SELECT word FROM words WHERE word LIKE ?" + assert connection.execute(sql, ("a%",)).fetchall() == [("alpha",)] + authorizations = [] + + def authorizer(action, *args): + if action == sqlite3.SQLITE_SELECT and not authorizations: + authorizations.append(True) + return sqlite3.SQLITE_OK + + connection.set_authorizer(authorizer) + for prefix, result in (("b%", "beta"), ("a%", "alpha")): + authorizations.clear() + assert connection.execute(sql, (prefix,)).fetchall() == [(result,)] + assert authorizations == [True] + connection.execute("ALTER TABLE words ADD COLUMN extra") + authorizations.clear() + assert connection.execute(sql, ("b%",)).fetchall() == [("beta",)] + assert authorizations == [True] + connection.close() + + +cache_reprepare_with_authorizer() + + +def statement_cache_connection_lifetime(): + # CPython 3.14 can crash when an adapter closes its connection. + if sys.implementation.name != "rustpython": + return + test = unittest.TestCase() + for phase in ("bind", "step", "fetch", "iterate"): + connection = sqlite3.connect(":memory:") + connection.execute("CREATE TABLE t(x)") + + def change_connection(): + connection.close() + + class Parameter: + def __conform__(self, protocol): + change_connection() + return 1 + + def change_on(value): + if phase == "step" or value == 2: + change_connection() + return value + + def parameters(): + yield (1,) + change_connection() + yield (2,) + + connection.create_function("change_on", 1, change_on) + with test.assertRaises(sqlite3.ProgrammingError): + if phase == "bind": + connection.execute("SELECT ?", (Parameter(),)) + elif phase == "step": + connection.execute("SELECT change_on(1)") + elif phase == "fetch": + cursor = connection.execute( + "SELECT change_on(1) UNION ALL SELECT change_on(2)" + ) + cursor.fetchone() + else: + connection.executemany("INSERT INTO t VALUES (?)", parameters()) + connection.close() + + +statement_cache_connection_lifetime() + + +def statement_cache_deferred_cleanup(): + # CPython can block when closing a populated cache from a callback's thread. + if sys.implementation.name != "rustpython": + return + import threading + + test = unittest.TestCase() + for action in ("close", "reinit"): + for autocommit in (sqlite3.LEGACY_TRANSACTION_CONTROL, False): + connection = sqlite3.connect( + ":memory:", check_same_thread=False, autocommit=autocommit + ) + connection.execute("SELECT 123").fetchall() + traced = [] + connection.set_trace_callback(traced.append) + completed = [] + workers = [] + failures = [] + + def change_connection(): + try: + if action == "close": + connection.close() + else: + connection.__init__(":memory:", check_same_thread=False) + except Exception as error: + failures.append(error) + + def callback(): + worker = threading.Thread(target=change_connection, daemon=True) + workers.append(worker) + worker.start() + worker.join(5) + completed.append(not worker.is_alive()) + return 1 + + connection.create_function("callback", 0, callback) + if action == "close": + with test.assertRaises(sqlite3.ProgrammingError): + connection.execute("SELECT callback()") + else: + assert connection.execute("SELECT callback()").fetchall() == [(1,)] + assert connection.execute("SELECT 456").fetchall() == [(456,)] + for worker in workers: + worker.join(5) + assert not worker.is_alive() + assert not failures, failures + assert completed == [True], (action, autocommit) + if autocommit is False: + assert "ROLLBACK" in traced, traced + connection.close() + + +def concurrent_sqlite_error_snapshots(): + # CPython also races when reading the connection's last error after a call. + if sys.implementation.name != "rustpython": + return + import threading + + connection = sqlite3.connect(":memory:", check_same_thread=False, autocommit=True) + for index in range(4): + connection.execute(f"CREATE TABLE t{index}(x UNIQUE)") + connection.execute(f"INSERT INTO t{index} VALUES (1)") + + for prepare in (True, False): + barrier = threading.Barrier(4) + failures = [] + completed = [0] * 4 + + def worker(index): + if prepare: + sql = f"SELECT * FROM missing_table_{index}" + expected = ( + sqlite3.OperationalError, + f"no such table: missing_table_{index}", + sqlite3.SQLITE_ERROR, + ) + else: + sql = f"INSERT INTO t{index} VALUES (1)" + expected = ( + sqlite3.IntegrityError, + f"UNIQUE constraint failed: t{index}.x", + sqlite3.SQLITE_CONSTRAINT_UNIQUE, + ) + barrier.wait() + for _ in range(1000): + try: + connection.execute(sql) + except sqlite3.Error as error: + actual = (type(error), str(error), error.sqlite_errorcode) + if actual == expected: + completed[index] += 1 + continue + failures.append((expected, actual)) + else: + failures.append((expected, "no error")) + break + + workers = [ + threading.Thread(target=worker, args=(i,), daemon=True) for i in range(4) + ] + for thread in workers: + thread.start() + for thread in workers: + thread.join(10) + assert not thread.is_alive(), "concurrent SQLite call blocked" + assert not failures, failures + assert completed == [1000] * 4, completed + connection.close() + + +statement_cache_deferred_cleanup() +concurrent_sqlite_error_snapshots() + + +def script_stops_after_close(): + # CPython can crash when its connection closes inside a callback. + if sys.implementation.name != "rustpython": + return + test = unittest.TestCase() + for phase in ("prepare", "step", "commit"): + connection = sqlite3.connect(":memory:") + continued = [] + connection.create_function("tail", 0, lambda: continued.append(True)) + connection.create_function("closeme", 0, connection.close) + if phase == "prepare": + + def authorizer(*args): + connection.close() + return sqlite3.SQLITE_OK + + connection.set_authorizer(authorizer) + elif phase == "commit": + connection.execute("CREATE TABLE t(x)") + connection.execute("INSERT INTO t VALUES (1)") + connection.set_trace_callback(lambda sql: connection.close()) + script = ( + "SELECT closeme(); SELECT tail();" if phase == "step" else "SELECT tail();" + ) + with test.assertRaises(sqlite3.ProgrammingError): + connection.executescript(script) + assert not continued, phase + + +def concurrent_sqlite_results(): + # CPython also races when reading connection-wide result metadata/errors. + if sys.implementation.name != "rustpython": + return + import threading + + connection = sqlite3.connect(":memory:", check_same_thread=False, autocommit=True) + connection.execute("CREATE TABLE t(id INTEGER PRIMARY KEY, value)") + connection.executemany("INSERT INTO t VALUES (?, 0)", [(i,) for i in range(4)]) + for operation in ("insert", "update", "many", "returning", "backup"): + barrier = threading.Barrier(4, timeout=10) + failures = [] + completed = [0] * 4 + + def worker(index): + source = sqlite3.connect(":memory:") if operation == "backup" else None + try: + barrier.wait() + for iteration in range(500): + expected = index + 1 + if source is not None: + try: + source.backup(connection, name=f"missing_{index}") + except sqlite3.OperationalError as error: + assert str(error) == f"unknown database missing_{index}", ( + str(error) + ) + assert error.sqlite_errorcode == sqlite3.SQLITE_ERROR + else: + raise AssertionError("backup accepted an unknown schema") + elif operation == "insert": + expected = 1000 + index * 10000 + iteration + cursor = connection.execute( + "INSERT INTO t VALUES (?, 0)", (expected,) + ) + assert cursor.lastrowid == expected, ( + expected, + cursor.lastrowid, + ) + assert cursor.rowcount == 1 + else: + sql = "UPDATE t SET value=value+1 WHERE id < ?" + if operation == "many": + cursor = connection.executemany( + sql, [(expected,), (expected,)] + ) + expected *= 2 + else: + if operation == "returning": + sql += " RETURNING id" + cursor = connection.execute(sql, (expected,)) + cursor.fetchall() + assert cursor.rowcount == expected, ( + operation, + expected, + cursor.rowcount, + ) + assert not connection.in_transaction + assert connection.total_changes >= 4 + completed[index] += 1 + except Exception as error: + failures.append(error) + finally: + if source is not None: + source.close() + + workers = [ + threading.Thread(target=worker, args=(i,), daemon=True) for i in range(4) + ] + for worker_thread in workers: + worker_thread.start() + for worker_thread in workers: + worker_thread.join(15) + assert not worker_thread.is_alive(), operation + assert not failures, failures + assert completed == [500] * 4, (operation, completed) + connection.close() + + +def sqlite_callbacks_use_calling_thread(): + import threading + + connection = sqlite3.connect(":memory:", check_same_thread=False) + connection.create_function("exception", 0, lambda: str(sys.exception())) + traced = [] + connection.set_trace_callback(lambda sql: traced.append(str(sys.exception()))) + results = [] + + def worker(): + try: + raise ValueError("worker") + except ValueError: + results.append(connection.execute("SELECT exception()").fetchone()[0]) + + try: + raise RuntimeError("main") + except RuntimeError: + thread = threading.Thread(target=worker, daemon=True) + thread.start() + thread.join(5) + assert not thread.is_alive() + assert str(sys.exception()) == "main" + assert results == ["worker"], results + assert traced == ["worker"], traced + connection.close() + + +sqlite_callbacks_use_calling_thread() + + +def concurrent_sqlite_transactions(): + if sys.implementation.name != "rustpython": + return + import threading + import time + + connection = sqlite3.connect(":memory:", check_same_thread=False) + connection.execute("CREATE TABLE t(x)") + queries = ("INSERT INTO t VALUES (1)", "INSERT INTO t VALUES (2)") + for query in queries: + connection.execute(query) + connection.rollback() + entered = threading.Event() + started = threading.Event() + failures = [] + + def trace(sql): + if sql.startswith("BEGIN") and not entered.is_set(): + entered.set() + started.wait(5) + # Let the competing cached execute reach its implicit BEGIN check. + time.sleep(0.05) + + def insert(): + try: + assert entered.wait(5) + started.set() + connection.execute(queries[1]) + except Exception as error: + failures.append(error) + + connection.set_trace_callback(trace) + worker = threading.Thread(target=insert, daemon=True) + worker.start() + connection.execute(queries[0]) + worker.join(5) + assert not worker.is_alive() + assert not failures, failures + assert connection.execute("SELECT count(*) FROM t").fetchone() == (2,) + connection.set_trace_callback(None) + connection.rollback() + + # Either ordering of legacy DML and autocommit=False must be rollbackable. + barrier = threading.Barrier(3, timeout=10) + rounds = 500 + + def run(setter): + for _ in range(rounds): + barrier.wait() + try: + if setter: + connection.autocommit = False + else: + connection.execute(queries[0]) + except Exception as error: + failures.append(error) + barrier.wait() + + workers = [ + threading.Thread(target=run, args=(setter,), daemon=True) + for setter in (False, True) + ] + for worker in workers: + worker.start() + remaining = [] + for _ in range(rounds): + connection.autocommit = True + connection.autocommit = sqlite3.LEGACY_TRANSACTION_CONTROL + barrier.wait() + barrier.wait() + connection.rollback() + remaining.append(connection.execute("SELECT count(*) FROM t").fetchone()[0]) + for worker in workers: + worker.join(5) + assert not worker.is_alive() + assert not failures, failures + assert not any(remaining), remaining + connection.close() + + +script_stops_after_close() +concurrent_sqlite_results() +concurrent_sqlite_transactions() + + +def callback_registration_lifetimes(): + class Callback: + def __init__(self, connection): + self.connection = connection + + def __call__(self, *args): + return sqlite.SQLITE_OK + + def __del__(self): + if action in ("reinit", "reentrant_reinit"): + events.append("drop") + try: + self.connection.close() + except sqlite.ProgrammingError: + pass + if action == "reentrant_reinit" and len(events) == 1: + self.connection.__init__(":memory:") + register(Callback(self.connection), *args) + + for method, args in ( + ("set_trace_callback", ()), + ("set_authorizer", ()), + ("set_progress_handler", (1,)), + ("set_progress_handler", (0,)), + ): + for action in ("disable", "replace", "close", "reinit", "reentrant_reinit"): + if args == (0,) and action != "disable": + continue + events = [] + connection = sqlite.connect(":memory:") + cursor = connection.execute("SELECT 1 UNION ALL SELECT 2") + register = getattr(connection, method) + callback = Callback(connection) + reference = weakref.ref(callback) + register(callback, *args) + del callback + assert reference() is not None + if action == "disable": + register(None, *args) + elif action == "replace": + register(lambda *args: 0, *args) + elif action == "close": + connection.close() + else: + connection.__init__(":memory:") + assert events == ["drop"] * (2 if action == "reentrant_reinit" else 1) + assert connection.execute("SELECT 1").fetchone() == (1,) + assert reference() is None, (method, args, action) + del cursor + connection.close() + + +def callback_self_removal_lifetime(): + for method, args in ( + ("set_trace_callback", ()), + ("set_authorizer", ()), + ("set_progress_handler", (1,)), + ): + connection = sqlite.connect(":memory:") + register = getattr(connection, method) + events = [] + + class Result: + def __bool__(self): + assert events == ["call"] + return False + + class Callback: + def __call__(self, *unused): + register(None, *args) + events.append("call") + return Result() if args else sqlite.SQLITE_OK + + def __del__(self): + events.append(("drop", connection.execute("SELECT 2").fetchone())) + + register(Callback(), *args) + # The callable connection also prepares statements and invokes authorizers. + if method == "set_authorizer": + connection("SELECT 1") + else: + connection.execute("SELECT 1").fetchall() + assert events == ["call", ("drop", (2,))], (method, events) + connection.close() + + +callback_registration_lifetimes() +callback_self_removal_lifetime() + + +def blob_close_during_cursor_reset(): + import tempfile + import threading + + with tempfile.TemporaryDirectory() as directory: + path = directory + "/blob.db" + connection = sqlite.connect(path, isolation_level=None, check_same_thread=False) + connection.execute("CREATE TABLE t(value)") + connection.execute("INSERT INTO t VALUES (zeroblob(1)), (zeroblob(1))") + resetting = threading.Event() + release = threading.Event() + cursor_closed = threading.Event() + blob_closed = threading.Event() + failures = [] + + class Window: + def step(self, value): + pass + + def value(self): + return 0 + + def finalize(self): + resetting.set() + if not release.wait(5): + failures.append("cursor reset timed out") + return 0 + + connection.create_window_function("hold", 1, Window) + blob = connection.blobopen("t", "value", 1) + cursor = connection.execute( + "SELECT hold(rowid) OVER (ROWS UNBOUNDED PRECEDING) FROM t" + ) + + def close(resource, finished): + resource.close() + finished.set() + + resetter = threading.Thread( + target=close, args=(cursor, cursor_closed), daemon=True + ) + closer = threading.Thread(target=close, args=(blob, blob_closed), daemon=True) + resetter.start() + assert resetting.wait(5) + closer.start() + # CPython waits for reset; RustPython may queue the BLOB for later cleanup. + blob_closed.wait(0.2) + release.set() + resetter.join(5) + closer.join(5) + assert not resetter.is_alive() and not closer.is_alive() + assert cursor_closed.is_set() and blob_closed.is_set() + assert not failures, failures + other = sqlite.connect(path, timeout=0, isolation_level=None) + try: + # No intervening call on connection may be needed to release its lock. + other.execute("UPDATE t SET value=zeroblob(1)") + finally: + other.close() + connection.close() + + +blob_close_during_cursor_reset() + + +def reinit_during_isolation_cleanup(): + import threading + + failures = [] + armed = False + + class Callback: + def __call__(self, sql): + pass + + def __del__(self): + try: + connection.close() + except Exception as exc: + failures.append(exc) + + def replace(): + try: + connection.__init__(":memory:", check_same_thread=False, autocommit=True) + connection.set_trace_callback(Callback()) + except Exception as exc: + failures.append(exc) + + class Level(str): + def __del__(self): + # CPython releases this subclass during argument conversion; + # RustPython retains it until the isolation level is replaced. + if armed: + worker = threading.Thread(target=replace, daemon=True) + worker.start() + worker.join(5) + if worker.is_alive(): + failures.append("reentrant initializer blocked") + + connection = sqlite.connect( + ":memory:", isolation_level=Level(""), check_same_thread=False + ) + armed = True + try: + connection.__init__(":memory:", check_same_thread=False, autocommit=False) + assert not failures, failures + assert connection.execute("SELECT 1").fetchone() == (1,) + assert connection.autocommit is False + assert connection.in_transaction + finally: + connection.close() + + +reinit_during_isolation_cleanup() + + +def reinit_restores_factories_after_callback_cleanup(): + connection = sqlite.connect(":memory:") + events = [] + + class Callback: + def __call__(self, sql): + pass + + def __del__(self): + connection.row_factory = sqlite.Row + connection.text_factory = bytes + events.append("factories changed") + + connection.set_trace_callback(Callback()) + try: + connection.__init__(":memory:") + assert events == ["factories changed"] + assert connection.row_factory is None + assert connection.text_factory is str + assert connection.execute("SELECT 'hello'").fetchone() == ("hello",) + finally: + connection.close() + + +reinit_restores_factories_after_callback_cleanup() + + +# Expressions have no declared type; column-name converters still take priority. +sqlite.register_converter("METADATA", lambda value: value.decode().upper()) +try: + con = sqlite.connect( + ":memory:", detect_types=sqlite.PARSE_DECLTYPES | sqlite.PARSE_COLNAMES + ) + try: + assert con.execute( + "SELECT 1, NULL, 'value' AS \"name [METADATA]\"" + ).fetchone() == (1, None, "VALUE") + assert con.execute( + "SELECT 'value' AS \"name [METADATA\", 'value' AS \"name [[METADATA]\"" + ).fetchone() == ("value", "VALUE") + finally: + con.close() +finally: + del sqlite.converters["METADATA"] + + +# Cursor checks apply to operations, not passive getters or fetchmany(0). +def cursor_thread_error_priority(): + import threading + + for state in ("open", "cursor_closed", "connection_closed", "both_closed"): + con = sqlite.connect(":memory:") + cur = con.cursor() + if state in ("cursor_closed", "both_closed"): + cur.close() + if state in ("connection_closed", "both_closed"): + con.close() + outcomes = [] + + def run(): + for operation in (cur.fetchone, cur.close): + try: + operation() + except sqlite.ProgrammingError as exc: + outcomes.append(str(exc)) + else: + outcomes.append("no error") + # CPython does not iterate when zero rows are requested. + outcomes.append(cur.fetchmany(0)) + if state == "open": + outcomes.append(cur.rowcount) + + worker = threading.Thread(target=run) + worker.start() + worker.join() + con.close() + thread_message = "SQLite objects created in a thread can only be used" + if state in ("cursor_closed", "both_closed"): + assert outcomes[0] == "Cannot operate on a closed cursor." + else: + assert outcomes[0].startswith(thread_message), outcomes + # close() checks the connection's thread even for a closed cursor. + assert outcomes[1].startswith(thread_message), outcomes + assert outcomes[2] == [] + if state == "open": + assert outcomes[3] == -1 + + +cursor_thread_error_priority() + + +# Finalization warns with source=self, rolls back, and ignores thread ownership. +def connection_finalization(): + import gc + import threading + import warnings + + with warnings.catch_warnings(record=True) as records: + warnings.simplefilter("always", ResourceWarning) + events = [] + con = sqlite.connect(":memory:", autocommit=False) + con.set_trace_callback(events.append) + del con + gc.collect() + assert len(records) == 1 + assert str(records[0].message).startswith("unclosed database in ") + with unittest.TestCase().assertRaisesRegex( + sqlite.ProgrammingError, "closed database" + ): + records[0].source.execute("SELECT 1") + assert events == ["ROLLBACK"], events + + with warnings.catch_warnings(record=True) as records: + warnings.simplefilter("always", ResourceWarning) + con = sqlite.connect(":memory:") + con.close() + del con + con = sqlite.Connection.__new__(sqlite.Connection) + del con + gc.collect() + assert not records + + with warnings.catch_warnings(record=True) as records: + warnings.simplefilter("always", ResourceWarning) + owners = [sqlite.connect(":memory:")] + + def release(): + owners.pop() + + worker = threading.Thread(target=release) + worker.start() + worker.join() + gc.collect() + assert len(records) == 1 + with unittest.TestCase().assertRaisesRegex( + sqlite.ProgrammingError, "closed database" + ): + records[0].source.execute("SELECT 1") + + +connection_finalization() + + +def connection_warning_error_still_closes(): + import gc + import os + import tempfile + import warnings + + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "finalize.db") + con = sqlite.connect(path) + con.execute("CREATE TABLE data(value)") + con.close() + errors = [] + previous_hook = sys.unraisablehook + sys.unraisablehook = lambda event: errors.append( + (event.exc_type, event.err_msg, event.object) + ) + try: + with warnings.catch_warnings(): + warnings.simplefilter("error", ResourceWarning) + con = sqlite.connect(path, autocommit=False) + con.execute("INSERT INTO data VALUES(1)") + del con + gc.collect() + assert len(errors) == 1, errors + assert errors[0][0] is ResourceWarning + assert errors[0][1].startswith( + "Exception ignored while finalizing database connection <" + ) + assert errors[0][2] is None + con = sqlite.connect(path, timeout=0) + try: + assert con.execute("SELECT * FROM data").fetchall() == [] + con.execute("INSERT INTO data VALUES(2)") + con.commit() + finally: + con.close() + finally: + sys.unraisablehook = previous_hook + + +connection_warning_error_still_closes() + + +def connection_teardown_disables_callbacks(): + import subprocess + + process = subprocess.run( + [ + sys.executable, + "-Wignore::ResourceWarning", + "-c", + "import sqlite3; con = sqlite3.connect(':memory:', autocommit=False); " + "con.set_trace_callback(lambda sql: print('UNEXPECTED_CALLBACK'))", + ], + capture_output=True, + text=True, + ) + assert process.returncode == 0, process.stderr + assert "UNEXPECTED_CALLBACK" not in process.stdout, process.stdout + + +connection_teardown_disables_callbacks() + + +# Audit hooks observe the original path before filesystem conversion and an +# unpublished connection before it can be used. Keep hooks inert after testing. +def check_connection_audit(): + import sys + + events = [] + mode = None + retained = [] + + class Denied(Exception): + pass + + def hook(event, args): + nonlocal mode + if mode is None or not event.startswith("sqlite3.connect"): + return + events.append((event, args)) + if event == "sqlite3.connect": + if mode == "deny_path": + raise Denied + return + connection = args[0] + if mode in ("reenter", "reenter_thread"): + threaded = mode == "reenter_thread" + mode = "record" + if threaded: + import threading + + errors = [] + + def initialize(): + try: + connection.__init__(":memory:", autocommit=True) + except Exception as error: + errors.append(error) + + thread = threading.Thread(target=initialize) + thread.start() + thread.join() + assert not errors + else: + connection.__init__(":memory:", autocommit=True) + assert connection.execute("select 1").fetchone() == (1,) + return + if mode == "record": + return + assert connection.row_factory is None + assert connection.text_factory is str + operations = [ + lambda: connection.execute("select 1"), + connection.cursor, + connection.close, + lambda: connection.in_transaction, + lambda: connection.isolation_level, + lambda: connection.autocommit, + lambda: connection.total_changes, + ] + for operation in operations: + try: + operation() + except sqlite.ProgrammingError as error: + assert str(error) == "Base Connection.__init__ not called." + else: + raise AssertionError("audit exposed initialized connection") + if mode == "deny_handle": + retained.append(connection) + raise Denied + + sys.addaudithook(hook) + try: + connection = sqlite.connect(":memory:") + connection.execute("create table preserved(value)") + + class Path: + def __fspath__(self): + raise AssertionError("filesystem conversion preceded audit") + + class InvalidCacheSize: + def __index__(self): + raise Denied + + mode = "record" + try: + sqlite.connect(":memory:", cached_statements=InvalidCacheSize()) + except Denied: + pass + else: + raise AssertionError("argument conversion failure ignored") + assert not events + + path = Path() + mode = "deny_path" + try: + connection.__init__(path) + except Denied: + pass + else: + raise AssertionError("audit denial ignored") + assert events == [("sqlite3.connect", (path,))] + connection.execute("select * from preserved") + connection.close() + + mode = "deny_handle" + try: + sqlite.connect(":memory:") + except Denied: + pass + else: + raise AssertionError("handle audit denial ignored") + mode = None + denied = retained.pop() + try: + denied.execute("select 1") + except sqlite.ProgrammingError as error: + assert str(error) == "Base Connection.__init__ not called." + else: + raise AssertionError("denied connection is usable") + denied.__init__(":memory:") + denied.close() + + mode = "inspect" + connection = sqlite.Connection(":memory:", autocommit=False) + assert connection.in_transaction + connection.close() + + mode = "reenter" + connection = sqlite.connect(":memory:", autocommit=False) + assert connection.autocommit is True + assert connection.in_transaction + connection.close() + + mode = "reenter_thread" + connection = sqlite.connect(":memory:", autocommit=False) + assert connection.in_transaction + mode = None + connection.__init__(":memory:") + connection.close() + finally: + mode = None + -if sys.implementation.name == "rustpython": - cx.execute("CREATE TABLE blobtest(b BLOB)") - data = b"this blob data string is exactly fifty bytes long!" - cx.execute("INSERT INTO blobtest(b) VALUES (?)", (data,)) - blob = cx.blobopen("blobtest", "b", 1) - blob[9:0:-2] = b"12345" # writes to indices 9, 7, 5, 3, 1 - actual = cx.execute("select b from blobtest").fetchone()[0] - expected = b"t5i4 3l2b1" + data[10:] - assert actual == expected, f"got {actual!r}, expected {expected!r}" - blob.close() +check_connection_audit() diff --git a/extra_tests/snippets/stdlib_ssl.py b/extra_tests/snippets/stdlib_ssl.py index cad505eebc1..057a88a3049 100644 --- a/extra_tests/snippets/stdlib_ssl.py +++ b/extra_tests/snippets/stdlib_ssl.py @@ -1,5 +1,10 @@ import pathlib +import socket import ssl +import threading +import time + +from test.test_ssl import HOST, ThreadedEchoServer, testing_context CERT = ( pathlib.Path(__file__).resolve().parent.parent.parent @@ -23,6 +28,18 @@ client = client_context.wrap_bio(client_in, client_out) server = server_context.wrap_bio(server_in, server_out, server_side=True) +# A write that starts the handshake must release its caller's buffer on WANT. +# Save the valid retry before resizing and changing the original exporter. +exporter = bytearray(b"saved application bytes before WANT_READ") +saved_write = bytes(exporter) +try: + client.write(exporter) +except ssl.SSLWantReadError: + exporter[:] = b"changed after WANT" + exporter.extend(b"; no outstanding buffer export") +else: + raise AssertionError("write before the peer handshake did not need a read") + for _ in range(5): try: client.do_handshake() @@ -37,6 +54,105 @@ client.do_handshake() server.do_handshake() + +def test_failed_server_handshake_sends_one_alert(): + # Once initialization sends its fatal alert, the caller must not enqueue + # another alert or replace the original TLS failure with a send failure. + rejecting_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + rejecting_context.minimum_version = ssl.TLSVersion.TLSv1_3 + rejecting_context.load_cert_chain(str(CERT)) + incoming, outgoing = ssl.MemoryBIO(), ssl.MemoryBIO() + peer_in, peer_out = ssl.MemoryBIO(), ssl.MemoryBIO() + peer = client_context.wrap_bio(peer_in, peer_out) + rejecting = rejecting_context.wrap_bio(incoming, outgoing, server_side=True) + try: + peer.do_handshake() + except ssl.SSLWantReadError: + pass + incoming.write(peer_out.read()) + try: + rejecting.do_handshake() + except ssl.SSLError: + pass + else: + raise AssertionError("TLS 1.2 client connected to TLS 1.3-only server") + # One fatal protocol_version alert, not a second generic handshake_failure. + assert outgoing.read() == b"\x15\x03\x03\x00\x02\x02\x46" + + +test_failed_server_handshake_sends_one_alert() + + +def test_certificate_public_bytes(connection): + import _ssl + import inspect + + cert = connection._sslobj.get_unverified_chain()[0] + assert _ssl.Certificate.public_bytes.__text_signature__ == ( + "($self, /, format=Encoding.PEM)" + ) + # Encoding is not exported by _ssl, so inspect cannot resolve this default + # in CPython either. Do not substitute a different public default spelling. + try: + inspect.signature(_ssl.Certificate.public_bytes) + except ValueError: + pass + else: + raise AssertionError("symbolic Encoding.PEM unexpectedly resolved") + + pem = cert.public_bytes() + der = cert.public_bytes(_ssl.ENCODING_DER) + assert cert.public_bytes(format=_ssl.ENCODING_PEM) == pem + assert cert.public_bytes(format=_ssl.ENCODING_DER) == der + assert ssl.PEM_cert_to_DER_cert(pem) == der + + class Format: + calls = 0 + + def __index__(self): + self.calls += 1 + return _ssl.ENCODING_DER + + format = Format() + assert cert.public_bytes(format=format) == der + assert format.calls == 1 + + for args, kwargs, error in ( + ((), {"format": None}, TypeError), + ((), {"format": 1 << 40}, OverflowError), + ((), {"format": 0}, ValueError), + ((format,), {"format": format}, TypeError), + ((format, format), {}, TypeError), + ((), {"unknown": format}, TypeError), + ): + format.calls = 0 + try: + cert.public_bytes(*args, **kwargs) + except error: + pass + else: + raise AssertionError((args, kwargs, error)) + assert format.calls == 0, "invalid call shape must precede conversion" + + +test_certificate_public_bytes(client) + +# OpenSSL retries require the original content and length. Never retry with +# the mutated exporter: behavior for an invalid retry is not a parity claim. +assert client.write(saved_write) == len(saved_write) +server_in.write(client_out.read()) +assert server.read(len(saved_write)) == saved_write + +# SSLObject writes complete the input even when rustls has a smaller internal +# record buffer. Exposing partial writes makes asyncio copy large suffixes. +payload = b"bio complete write" * 4096 +assert client.write(payload) == len(payload) +server_in.write(client_out.read()) +received = bytearray() +while len(received) < len(payload): + received.extend(server.read(len(payload) - len(received))) +assert received == payload + try: server.unwrap() except ssl.SSLWantReadError: @@ -44,3 +160,285 @@ client_in.write(server_out.read() + TAIL) client.unwrap() assert client_in.read() == TAIL + + +TIMEOUT = 10.0 + + +class BoundedEchoServer(ThreadedEchoServer): + # Keep the canonical accept, handshake and echo implementation. Its normal + # context manager and handler joins need bounds for a deadlock regression. + class ConnectionHandler(ThreadedEchoServer.ConnectionHandler): + def __init__(self, server, connsock, addr): + super().__init__(server, connsock, addr) + self.sock.settimeout(TIMEOUT) + server.handlers.append(self) + + def run(self): + try: + try: + super().run() + finally: + self.close() + except BaseException as exc: + self.server.errors.append(exc) + + def join(self, timeout=TIMEOUT * 10): + super().join(timeout) + if self.is_alive(): + self.server.errors.append( + AssertionError("echo connection handler did not stop") + ) + self.server.stop() + + def __init__(self, context): + self.errors = [] + self.handlers = [] + super().__init__(context=context, chatty=False) + + def __enter__(self): + assert not self._in_context + self._in_context = True + self.start(threading.Event()) + if not self.flag.wait(TIMEOUT): + self.__exit__() + raise AssertionError("echo server did not start") + return self + + def run(self): + try: + try: + super().run() + finally: + self.close() + except BaseException as exc: + self.errors.append(exc) + + def __exit__(self, *args): + self.stop() + self.join(TIMEOUT * 2) + self._in_context = False + assert not self.is_alive(), "echo server did not stop" + for handler in self.handlers: + handler.join(TIMEOUT) + assert not handler.is_alive(), "echo connection handler did not stop" + if self.errors: + raise self.errors[0] + assert not self.conn_errors, self.conn_errors + + +def test_write_return_during_reader_callback(): + client_context, server_context, hostname = testing_context() + client_context.maximum_version = ssl.TLSVersion.TLSv1_2 + server_context.maximum_version = ssl.TLSVersion.TLSv1_2 + writer_thread = threading.current_thread() + reader_thread = None + round_active = False + + def message_callback(conn, direction, version, content_type, msg_type, data): + if ( + not round_active + or conn is not connection + or content_type != ssl._TLSContentType.HEADER + or msg_type != ssl._TLSContentType.APPLICATION_DATA + ): + return + current_thread = threading.current_thread() + if ( + direction == "write" + and current_thread is writer_thread + and not write_started.is_set() + ): + write_started.set() + assert reader_started.wait(TIMEOUT), "reader did not start" + # Encourage the reader to queue behind the native writer. Python + # cannot force its acquisition into the native cleanup window. + time.sleep(0.01) + elif ( + direction == "read" + and current_thread is reader_thread + and not read_callback_seen.is_set() + ): + read_callback_seen.set() + assert write_returned.wait(TIMEOUT), ( + "write did not return while another thread's read callback ran" + ) + + client_context._msg_callback = message_callback + with BoundedEchoServer(server_context) as echo_server: + with client_context.wrap_socket( + socket.socket(), server_hostname=hostname + ) as connection: + connection.settimeout(TIMEOUT) + connection.connect((HOST, echo_server.port)) + try: + # This is a cleanup/callback race, not another generic duplex + # smoke test. The canonical duplex test remains authoritative. + for _ in range(20): + payload = b"WRITE RETURN DURING READER CALLBACK\n" + write_started = threading.Event() + reader_started = threading.Event() + write_returned = threading.Event() + read_callback_seen = threading.Event() + errors = [] + + def read_echo(): + try: + assert write_started.wait(TIMEOUT), ( + "writer did not enter its application-record callback" + ) + reader_started.set() + received = b"" + while len(received) < len(payload): + chunk = connection.read(len(payload) - len(received)) + assert chunk, ( + "unexpected EOF in echoed application data" + ) + received += chunk + assert received == payload.lower(), received + except BaseException as exc: + errors.append(exc) + + reader_thread = threading.Thread(target=read_echo, daemon=True) + round_active = True + reader_thread.start() + try: + assert connection.write(payload) == len(payload) + finally: + # Set only after the Python write call has returned or + # raised. The reader callback never waits on itself. + write_returned.set() + reader_thread.join(TIMEOUT * 2) + if reader_thread.is_alive(): + # Interrupt transport I/O without starting SSL I/O. + try: + socket.socket.shutdown(connection, socket.SHUT_RDWR) + except OSError: + pass + reader_thread.join(TIMEOUT * 2) + round_active = False + assert not reader_thread.is_alive(), "reader did not stop" + if errors: + raise errors[0] + assert write_started.is_set(), "write callback was not exercised" + assert read_callback_seen.is_set(), ( + "read callback was not exercised" + ) + connection.write(b"over\n") + finally: + round_active = False + client_context._msg_callback = None + + +test_write_return_during_reader_callback() + + +# Limit initial nonblocking writes to 4 MiB. Small socket buffers plus a peer +# paused after its handshake must actually produce WANT_WRITE on this platform. +WRITE_SIZE = 64 * 1024 +MAX_INITIAL_WRITES = 64 + + +class PausedSinkServer(BoundedEchoServer): + class ConnectionHandler(BoundedEchoServer.ConnectionHandler): + def __init__(self, server, connsock, addr): + super().__init__(server, connsock, addr) + self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 4096) + + def read(self): + assert self.server.read_enabled.wait(TIMEOUT), "sink was not released" + data = super().read() + if not data: + self.server.reached_eof.set() + else: + assert data == b"x" * len(data), "pending write data changed" + self.server.received += len(data) + assert self.server.received <= (MAX_INITIAL_WRITES + 1) * WRITE_SIZE + return data + + def write(self, data): + # Data was checked before canonical echo processing normalizes it. + # Send nothing back, avoiding two-peer application backpressure. + pass + + def run(self): + try: + super().run() + finally: + self.server.finished.set() + + def __init__(self, context): + self.read_enabled = threading.Event() + self.finished = threading.Event() + self.reached_eof = threading.Event() + self.received = 0 + super().__init__(context) + + +def test_exporter_release_after_application_want_write(): + client_context, server_context, hostname = testing_context() + client_context.maximum_version = ssl.TLSVersion.TLSv1_2 + server_context.maximum_version = ssl.TLSVersion.TLSv1_2 + with PausedSinkServer(server_context) as sink: + try: + with client_context.wrap_socket( + socket.socket(), server_hostname=hostname + ) as connection: + connection.settimeout(TIMEOUT) + connection.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096) + connection.connect((HOST, sink.port)) + connection.setblocking(False) + exporter = bytearray(b"x" * WRITE_SIZE) + saved_write = bytes(exporter) + acknowledged = 0 + for _ in range(MAX_INITIAL_WRITES): + try: + acknowledged += connection.write(exporter) + except ssl.SSLWantWriteError: + break + else: + raise AssertionError( + "bounded application writes never reached WANT_WRITE" + ) + + # Returning WANT must release the export while native retries + # retain stable original bytes. Resize and mutate only the old + # exporter; the retry still uses identical saved bytes/length. + exporter[:] = b"changed after application WANT_WRITE" + exporter.extend(b"; exporter is no longer held") + sink.read_enabled.set() + # A successful write may accept a prefix. The first retry + # must still use identical bytes/length; advance only after a + # positive result, and keep the same pending slice on WANT. + retry_deadline = time.monotonic() + TIMEOUT + accepted = 0 + pending = saved_write + for _ in range(64): + remaining = retry_deadline - time.monotonic() + assert remaining > 0, "saved-byte retry deadline expired" + connection.settimeout(remaining) + try: + count = connection.write(pending) + except (ssl.SSLWantReadError, ssl.SSLWantWriteError): + continue + assert 0 < count <= len(pending), count + accepted += count + if accepted == len(saved_write): + break + pending = saved_write[accepted:] + else: + raise AssertionError("saved-byte retry exceeded 64 attempts") + assert accepted == len(saved_write) + + # TCP EOF follows every sent TLS byte. Let the sink consume to + # EOF before checking the total, so extra replay is detected. + socket.socket.shutdown(connection, socket.SHUT_WR) + assert sink.finished.wait(TIMEOUT), "sink did not consume through EOF" + assert sink.reached_eof.is_set(), "sink stopped before observing EOF" + assert sink.received == acknowledged + len(saved_write), sink.received + finally: + # Setup or oracle failure must not strand the paused peer. + sink.read_enabled.set() + + +test_exporter_release_after_application_want_write() diff --git a/extra_tests/snippets/stdlib_struct.py b/extra_tests/snippets/stdlib_struct.py index c80f5511713..194b35f88ed 100644 --- a/extra_tests/snippets/stdlib_struct.py +++ b/extra_tests/snippets/stdlib_struct.py @@ -1,4 +1,5 @@ import struct +import sys from testutils import assert_raises @@ -42,6 +43,15 @@ with assert_raises(Exception): struct.pack("H", "'H' format requires 0 <= number <= 65535"), (">i", "'i' format requires -2147483648 <= number <= 2147483647"), - ("N", "'N' format requires 0 <= number <= 18446744073709551615"), + ("N", f"'N' format requires 0 <= number <= {2 ** (8 * struct.calcsize('N')) - 1}"), ("P", "int too large to convert"), ): try: @@ -128,7 +137,7 @@ def __index__(self): # A format that cannot be read leaves the Struct as it was. for bad in ("\udc00", "$"): - with assert_raises((UnicodeEncodeError, struct.error)): + with assert_raises((ValueError, struct.error)): s.__init__(bad) assert s.format == ">hh" assert s.pack(1, 2) == b"\x00\x01\x00\x02" @@ -145,8 +154,9 @@ def __init__(self): # Until __init__ runs there is no format to answer with. blank = struct.Struct.__new__(struct.Struct) assert blank.size == -1 +with assert_raises(AttributeError): + blank.format for call in ( - lambda: blank.format, lambda: blank.pack(1), lambda: blank.unpack(b"aa"), lambda: blank.unpack_from(b"aaaa"), @@ -159,8 +169,8 @@ def __init__(self): # The buffer a format asks for is sized by the format: one too large to -# allocate must raise instead of aborting. -with assert_raises(MemoryError): +# allocate must raise instead of aborting; an unrepresentable size fails earlier. +with assert_raises(MemoryError if sys.maxsize >= 2**60 else struct.error): struct.pack("%dx" % (2**60)) @@ -184,3 +194,21 @@ def __index__(self): buffer = bytearray(2) struct.pack_into("h", b">h"): + s = cls(format=fmt) + assert s.format == ">h" + assert s.pack(7) == b"\x00\x07" + s.__init__(format=">hh") + assert s.unpack(b"\x00\x01\x00\x02") == (1, 2) + with assert_raises(struct.error): + s.__init__(format="$") + assert s.format == ">hh" + assert s.pack(1, 2) == b"\x00\x01\x00\x02" diff --git a/extra_tests/snippets/stdlib_subinterpreters.py b/extra_tests/snippets/stdlib_subinterpreters.py index 3ca0be27411..24e0a279735 100644 --- a/extra_tests/snippets/stdlib_subinterpreters.py +++ b/extra_tests/snippets/stdlib_subinterpreters.py @@ -117,3 +117,506 @@ def receive(): encoding="utf-8", ) subprocess.run([sys.executable, str(script)], check=True, timeout=30) + + +# Releasing queued buffers can run a finalizer which reenters the channel API. +subprocess.run( + [ + sys.executable, + "-c", + """ +import _interpchannels as channels +import _interpreters +import sys + +released = [] + +class Exporter(bytearray): + def __del__(self): + channels.list_all() + released.append(True) + +for operation in ("destroy", "close", "drop", "timeout"): + # CPython 3.14.6 also deadlocks when close/drop releases a reentrant exporter. + if sys.implementation.name == "cpython" and operation in ("close", "drop"): + continue + channel = channels.create(3) + released.clear() + if operation == "timeout": + try: + channels.send_buffer(channel, Exporter(b"data"), timeout=0) + except TimeoutError: + pass + else: + raise AssertionError("send must time out without a receiver") + else: + channels.send_buffer(channel, Exporter(b"data"), blocking=False) + assert not released + if operation == "destroy": + channels.destroy(channel) + elif operation == "close": + channels.close(channel, force=True) + else: + del channel + assert released == [True], operation +""", + ], + check=True, + timeout=30, +) + + +def check_preserve_exc_conversion(): + trace = [] + + class Flag: + def __init__(self, name, raises=False): + self.name = name + self.raises = raises + + def __bool__(self): + trace.append(self.name) + if self.raises: + raise RuntimeError(self.name) + return False + + def __del__(self): + trace.append("del-" + self.name) + + class Id: + def __index__(self): + trace.append("id") + return -1 + + # Conversion is required even when preserve_exc's value is unused. It must + # precede restrict conversion and the implementation's id lookup. + try: + _interpreters.call( + Id(), + None, + preserve_exc=Flag("preserve", True), + restrict=Flag("restrict", True), + ) + except RuntimeError as exc: + assert str(exc) == "preserve" + else: + raise AssertionError("preserve_exc was not converted") + assert [event for event in trace if not event.startswith("del-")] == ["preserve"] + + trace.clear() + try: + _interpreters.call( + Id(), None, preserve_exc=Flag("preserve"), restrict=Flag("restrict", True) + ) + except RuntimeError as exc: + assert str(exc) == "restrict" + else: + raise AssertionError("restrict was not converted") + assert trace[:2] == ["preserve", "restrict"], trace + + # The original kwargs ownership must survive conversion. Both **dict + # insertion orders retain the original inputs through id resolution. + for reverse in (False, True): + trace.clear() + try: + if reverse: + _interpreters.call( + Id(), + None, + **{"restrict": Flag("restrict"), "preserve_exc": Flag("preserve")}, + ) + else: + _interpreters.call( + Id(), + None, + **{"preserve_exc": Flag("preserve"), "restrict": Flag("restrict")}, + ) + except ValueError: + pass + else: + raise AssertionError("negative id was accepted") + cleanup = ( + ["del-restrict", "del-preserve"] + if reverse + else ["del-preserve", "del-restrict"] + ) + assert trace == ["preserve", "restrict", "id"] + cleanup, trace + + # Existing tuple/dict conversions still take precedence over the flags. + for bad in ({"args": None}, {"kwargs": None}): + trace.clear() + try: + _interpreters.call(Id(), None, preserve_exc=Flag("preserve", True), **bad) + except TypeError: + pass + else: + raise AssertionError("invalid call arguments were accepted") + assert [event for event in trace if not event.startswith("del-")] == [], trace + + +check_preserve_exc_conversion() + + +# Clinic binding must finish before module-specific id/config interpretation. +def check_interpreter_clinic(): + import inspect + + signatures = { + "list_all": "(*, require_ready=False)", + "create": "(config='isolated', *, reqrefs=False)", + "destroy": "(id, *, restrict=False)", + "is_running": "(id, *, restrict=False)", + "whence": "(id)", + "get_config": "(id, *, restrict=False)", + "is_shareable": "(obj)", + "exec": "(id, code, shared={}, *, restrict=False)", + "run_string": "(id, script, shared={}, *, restrict=False)", + "run_func": "(id, func, shared={}, *, restrict=False)", + "call": "(id, callable, args=(), kwargs={}, *, preserve_exc=False, restrict=False)", + "set___main___attrs": "(id, updates, *, restrict=False)", + "incref": "(id, *, implieslink=False, restrict=False)", + "decref": "(id, *, restrict=False)", + "capture_exception": "(exc=None)", + } + for name, expected in signatures.items(): + func = getattr(_interpreters, name) + assert str(inspect.signature(func)) == expected, name + raw = " ".join(func.__text_signature__.split()) + assert raw == "($module, /, " + expected[1:], (name, raw) + + trace = [] + + class Flag: + def __init__(self, label, raises=False): + self.label = label + self.raises = raises + + def __bool__(self): + trace.append(self.label) + if self.raises: + raise RuntimeError(self.label) + return False + + class Id: + def __index__(self): + trace.append("id") + return -1 + + def __repr__(self): + return "negative-id" + + def check_error(func, args, kwargs, error, message, expected_trace=()): + trace.clear() + try: + func(*args, **kwargs) + except error as exc: + assert str(exc) == message, (func.__name__, str(exc), message) + else: + raise AssertionError(func.__name__) + assert trace == list(expected_trace), (func.__name__, trace, expected_trace) + + for name, missing in [ + ("exec", "code"), + ("run_string", "script"), + ("run_func", "func"), + ("call", "callable"), + ("set___main___attrs", "updates"), + ]: + check_error( + getattr(_interpreters, name), + (), + {"id": -1}, + TypeError, + f"{name}() missing required argument '{missing}' (pos 2)", + ) + + # The unused preserve_exc flag still runs its Clinic bool converter, before id. + check_error( + _interpreters.call, + (Id(), None), + {"preserve_exc": Flag("preserve", True)}, + RuntimeError, + "preserve", + ["preserve"], + ) + check_error( + _interpreters.call, + (Id(), None), + {"preserve_exc": Flag("preserve"), "restrict": Flag("restrict", True)}, + RuntimeError, + "restrict", + ["preserve", "restrict"], + ) + check_error( + _interpreters.incref, + (Id(),), + {"implieslink": Flag("implieslink"), "restrict": Flag("restrict")}, + ValueError, + "interpreter ID must be a non-negative int, got negative-id", + ["implieslink", "restrict", "id"], + ) + + # Real typed arguments are checked in Clinic order, before later flags and id. + for name, args, kwargs, parameter, expected_type in [ + ("exec", (Id(), None), {"shared": None}, "shared", "dict"), + ("run_func", (Id(), None), {"shared": None}, "shared", "dict"), + ("run_string", (Id(), None), {"shared": None}, "script", "str"), + ("call", (Id(), None), {"args": None, "kwargs": None}, "args", "tuple"), + ("call", (Id(), None), {"kwargs": None}, "kwargs", "dict"), + ("set___main___attrs", (Id(), None), {}, "updates", "dict"), + ]: + kwargs["restrict"] = Flag("restrict", True) + check_error( + getattr(_interpreters, name), + args, + kwargs, + TypeError, + f"{name}() argument '{parameter}' must be {expected_type}, not None", + ) + + # Full keyword binding rejects duplicates/unknown names before conversion. + check_error( + _interpreters.call, + (-1, None), + {"id": 2, "preserve_exc": Flag("preserve", True)}, + TypeError, + "argument for call() given by name ('id') and position (1)", + ) + check_error( + _interpreters.call, + (-1, None), + {"unexpected": 1, "preserve_exc": Flag("preserve", True)}, + TypeError, + "call() got an unexpected keyword argument 'unexpected'", + ) + + # O! accepts subclasses without invoking user conversion protocols. + class TupleSubclass(tuple): + pass + + class DictSubclass(dict): + pass + + class StrSubclass(str): + pass + + for name, args, kwargs in [ + ("call", (-1, None), {"args": TupleSubclass(), "kwargs": DictSubclass()}), + ("run_string", (-1, StrSubclass("pass")), {"shared": DictSubclass()}), + ("exec", (-1, None), {"shared": DictSubclass()}), + ("set___main___attrs", (-1, DictSubclass()), {}), + ]: + check_error( + getattr(_interpreters, name), + args, + kwargs, + ValueError, + "interpreter ID must be a non-negative int, got -1", + ) + assert _interpreters.capture_exception() is None + assert _interpreters.capture_exception(None) is None + assert _interpreters.is_shareable(obj=None) + + # The native wrapper keeps original owners, including failed conversions. + class TemporaryFlag(Flag): + def __del__(self): + trace.append("del-" + self.label) + + for raises in (False, True): + for mode in range(4): + trace.clear() + try: + if mode == 0: + _interpreters.call( + Id(), + None, + preserve_exc=TemporaryFlag("preserve"), + restrict=TemporaryFlag("restrict", raises), + ) + elif mode == 1: + _interpreters.call( + Id(), + None, + restrict=TemporaryFlag("restrict", raises), + preserve_exc=TemporaryFlag("preserve"), + ) + elif mode == 2: + _interpreters.call( + Id(), + None, + **{ + "preserve_exc": TemporaryFlag("preserve"), + "restrict": TemporaryFlag("restrict", raises), + }, + ) + else: + _interpreters.call( + Id(), + None, + **{ + "restrict": TemporaryFlag("restrict", raises), + "preserve_exc": TemporaryFlag("preserve"), + }, + ) + except (ValueError, RuntimeError): + pass + else: + raise AssertionError(mode) + expected = ["preserve", "restrict"] + ([] if raises else ["id"]) + # Direct calls release the evaluation stack in reverse, whereas + # expanded calls release the keyword mapping in insertion order. + reverse = mode % 2 == 1 + if mode < 2: + reverse = not reverse + if raises: + # The __bool__ traceback owns restrict until exception cleanup. + reverse = False + expected += ( + ["del-restrict", "del-preserve"] + if reverse + else ["del-preserve", "del-restrict"] + ) + assert trace == expected, (mode, raises, trace) + + class TemporaryId(Id): + def __del__(self): + trace.append("del-id") + + class TemporaryValue: + def __init__(self, name): + self.name = name + + def __del__(self): + trace.append("del-" + self.name) + + class TemporaryTuple(tuple): + def __del__(self): + trace.append("del-args") + + class TemporaryDict(dict): + def __del__(self): + trace.append("del-kwargs") + + # Positional values and borrowed payloads have the same owners as flags. + # Binding failures must also release those owners without any conversion. + for invoke, converted, destroyed in ( + ( + lambda: _interpreters.call( + TemporaryId(), + TemporaryValue("callable"), + TemporaryTuple(), + TemporaryDict(), + preserve_exc=TemporaryFlag("preserve"), + restrict=TemporaryFlag("restrict"), + ), + ["preserve", "restrict", "id"], + ["restrict", "preserve", "kwargs", "args", "callable", "id"], + ), + ( + lambda: _interpreters.call( + restrict=TemporaryFlag("restrict"), + callable=TemporaryValue("callable"), + id=TemporaryId(), + kwargs=TemporaryDict(), + preserve_exc=TemporaryFlag("preserve"), + args=TemporaryTuple(), + ), + ["preserve", "restrict", "id"], + ["args", "preserve", "kwargs", "id", "callable", "restrict"], + ), + ( + lambda: _interpreters.call( + TemporaryId(), + TemporaryValue("callable"), + TemporaryTuple(), + TemporaryDict(), + **dict( + restrict=TemporaryFlag("restrict"), + preserve_exc=TemporaryFlag("preserve"), + ), + ), + ["preserve", "restrict", "id"], + ["restrict", "preserve", "kwargs", "args", "callable", "id"], + ), + ( + lambda: _interpreters.call( + **dict( + id=TemporaryId(), + callable=TemporaryValue("callable"), + args=TemporaryTuple(), + kwargs=TemporaryDict(), + preserve_exc=TemporaryFlag("preserve"), + restrict=TemporaryFlag("restrict"), + ) + ), + ["preserve", "restrict", "id"], + ["id", "callable", "args", "kwargs", "preserve", "restrict"], + ), + ( + lambda: _interpreters.call( + TemporaryId(), + TemporaryValue("callable"), + preserve_exc=TemporaryFlag("preserve"), + restrict=TemporaryFlag("restrict"), + unexpected=TemporaryValue("unexpected"), + ), + [], + ["unexpected", "restrict", "preserve", "callable", "id"], + ), + ( + lambda: _interpreters.call( + TemporaryId(), + TemporaryValue("callable"), + **dict( + preserve_exc=TemporaryFlag("preserve"), + restrict=TemporaryFlag("restrict"), + unexpected=TemporaryValue("unexpected"), + ), + ), + [], + ["preserve", "restrict", "unexpected", "callable", "id"], + ), + ): + for _ in range(32): + trace.clear() + try: + invoke() + except (TypeError, ValueError): + pass + else: + raise AssertionError("invalid call succeeded") + assert trace == converted + ["del-" + name for name in destroyed], trace + + class TemporaryCurrentId(TemporaryId): + def __index__(self): + trace.append("id") + return _interpreters.get_current()[0] + + for invoke, destroyed in ( + ( + lambda: _interpreters.is_running( + TemporaryCurrentId(), restrict=TemporaryFlag("restrict") + ), + ["restrict", "id"], + ), + ( + lambda: _interpreters.is_running( + **dict(id=TemporaryCurrentId(), restrict=TemporaryFlag("restrict")) + ), + ["id", "restrict"], + ), + ): + trace.clear() + assert isinstance(invoke(), bool) + assert trace == ["restrict", "id"] + ["del-" + name for name in destroyed] + + check_error( + _interpreters.call, + (-1, None), + {"args": None, "unexpected": 1}, + TypeError, + "call() got an unexpected keyword argument 'unexpected'", + ) + + +check_interpreter_clinic() diff --git a/extra_tests/snippets/stdlib_subprocess.py b/extra_tests/snippets/stdlib_subprocess.py index 014011ea145..41821280c42 100644 --- a/extra_tests/snippets/stdlib_subprocess.py +++ b/extra_tests/snippets/stdlib_subprocess.py @@ -25,12 +25,19 @@ def sleep(secs): p = subprocess.Popen(echo("test")) -time.sleep(0.1) - assert p.returncode is None -assert p.poll() == 0 -assert p.returncode == 0 +# Process startup may exceed 100 ms on a busy runner. Keep testing poll() +# without assuming when the child gets scheduled. +try: + deadline = time.monotonic() + 30 + while p.poll() is None and time.monotonic() < deadline: + time.sleep(0.01) + assert p.returncode == 0 +finally: + if p.returncode is None: + p.kill() + p.wait() p = subprocess.Popen(sleep(2)) diff --git a/extra_tests/snippets/stdlib_sys.py b/extra_tests/snippets/stdlib_sys.py index 9dba301fb01..4e5da8c0089 100644 --- a/extra_tests/snippets/stdlib_sys.py +++ b/extra_tests/snippets/stdlib_sys.py @@ -1,7 +1,10 @@ import os +import shutil import subprocess import sys +import tempfile import warnings +from pathlib import Path from testutils import assert_raises @@ -25,6 +28,13 @@ assert isinstance(sys.implementation.name, str) assert isinstance(sys.implementation.cache_tag, str) +assert sys.version_info[:3] == (3, 15, 0) +assert sys.hexversion >> 8 == 0x030F00 +assert sys.version.startswith("3.15.0") +assert sys.implementation.cache_tag == ( + f"{sys.implementation.name}-{sys.version_info.major}{sys.version_info.minor}" +) + assert sys.getfilesystemencoding() == "utf-8" assert sys.getfilesystemencodeerrors().startswith("surrogate") @@ -59,6 +69,238 @@ def demo(x): assert ("demo", "call", None) in events +# The eager iterator prefix of a generator expression is not traced, but +# monitoring still reports the error it raises. + + +class GoodIterable: + def __iter__(self): + return iter([1]) + + +class BadIterable: + def __iter__(self): + raise ValueError("eager iterator") + + +def create_genexpr(iterable): + return (value for value in iterable) + + +events = [] + + +def trc(frame, event, arg): + if frame.f_code.co_name in ("create_genexpr", "", "__iter__"): + events.append((frame.f_code.co_name, event)) + return trc + + +sys.settrace(trc) +try: + create_genexpr(GoodIterable()).close() + try: + create_genexpr(BadIterable()) + except ValueError as error: + tb_names = [] + tb = error.__traceback__ + while tb is not None: + tb_names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + else: + raise AssertionError("expected eager iterator error") +finally: + sys.settrace(None) +assert events == [ + ("create_genexpr", "call"), + ("create_genexpr", "line"), + ("__iter__", "call"), + ("__iter__", "line"), + ("__iter__", "return"), + ("create_genexpr", "return"), + ("create_genexpr", "call"), + ("create_genexpr", "line"), + ("__iter__", "call"), + ("__iter__", "line"), + ("__iter__", "exception"), + ("__iter__", "return"), + ("create_genexpr", "exception"), + ("create_genexpr", "return"), + ("create_genexpr", "exception"), + ("create_genexpr", "return"), +], events +assert tb_names == ["", "create_genexpr", "__iter__"], tb_names + +monitoring = sys.monitoring +event_names = ("PY_START", "PY_RESUME", "PY_UNWIND", "RAISE", "LINE", "INSTRUCTION") +records = [] +monitoring.use_tool_id(2, "genexpr-prefix") +try: + for name in event_names: + + def callback(code, *args, name=name): + if code.co_name == "": + records.append(name) + + monitoring.register_callback(2, getattr(monitoring.events, name), callback) + monitoring.set_events( + 2, sum(getattr(monitoring.events, name) for name in event_names) + ) + create_genexpr(GoodIterable()).close() + assert records == [], records + with assert_raises(ValueError): + create_genexpr(BadIterable()) +finally: + monitoring.set_events(2, 0) + monitoring.free_tool_id(2) +assert records == ["RAISE", "PY_UNWIND"], records + + +# Unlike starred calls, ordinary monitored calls expand a bound method before +# reporting the callable and first argument. +def test_monitored_bound_methods(): + from types import MethodType + + class Receiver: + def method(self, x=1): + if x < 0: + raise ValueError("negative") + return x + + class Callable: + def __call__(self, receiver): + assert receiver is instance + return 1 + + instance = Receiver() + receiver = [1] + bound = instance.method + native = MethodType(len, receiver) + wrapped = Callable() + bound_callable = MethodType(wrapped, instance) + + cases = ( + (lambda: instance.method(1), Receiver.method, instance, ()), + (lambda: bound(), Receiver.method, instance, ()), + (lambda: bound(x=1), Receiver.method, instance, ()), + (lambda: bound(-1), Receiver.method, instance, ()), + (lambda: native(), len, receiver, ("C_RETURN",)), + (lambda: native(1), len, receiver, ("C_RAISE",)), + (lambda: bound_callable(), wrapped, instance, ("C_RETURN",)), + ) + + events = monitoring.events + records = [] + monitoring.use_tool_id(2, "bound-method") + try: + for name in ("CALL", "C_RETURN", "C_RAISE"): + + def callback(code, offset, func, arg, name=name): + records.append((name, func, arg)) + + monitoring.register_callback(2, getattr(events, name), callback) + + for index, (invoke, func, arg, returns) in enumerate(cases): + records.clear() + monitoring.set_local_events(2, invoke.__code__, events.CALL) + try: + if index == 3: + with assert_raises(ValueError): + invoke() + elif index == 5: + with assert_raises(TypeError): + invoke() + else: + assert invoke() == 1 + finally: + monitoring.set_local_events(2, invoke.__code__, 0) + assert tuple(name for name, _, _ in records) == ("CALL", *returns), records + assert all(f is func and a is arg for _, f, a in records), records + finally: + for name in ("CALL", "C_RETURN", "C_RAISE"): + monitoring.register_callback(2, getattr(events, name), None) + monitoring.free_tool_id(2) + + +test_monitored_bound_methods() + +# A loop body large enough to require EXTENDED_ARG on its jump targets. +namespace = {} +exec( + "def large_loop(skip=False):\n if skip:\n return 'done'\n" + " total = 0\n for x in (1, 2):\n" + " total += x\n" * 100 + " return total\n", + namespace, +) +large_loop = namespace["large_loop"] + + +def jump_out_of_large_loop(code, line): + global loop_hits + if code is large_loop.__code__ and line == 5: + loop_hits += 1 + if loop_hits == 2: + sys._getframe(1).f_lineno = 3 + + +def jump_after_large_loop(code, line): + if code is large_loop.__code__ and line == 5: + sys._getframe(1).f_lineno = 106 + + +monitoring.use_tool_id(2, "extended-arg") +try: + for event in (monitoring.events.LINE, monitoring.events.INSTRUCTION): + monitoring.register_callback(2, event, lambda *args: None) + for events in ( + monitoring.events.LINE, + monitoring.events.LINE | monitoring.events.INSTRUCTION, + ): + monitoring.set_local_events(2, large_loop.__code__, events) + assert large_loop() == 300 + loop_hits = 0 + monitoring.register_callback(2, monitoring.events.LINE, jump_out_of_large_loop) + monitoring.set_local_events(2, large_loop.__code__, monitoring.events.LINE) + assert large_loop() == "done" + assert loop_hits == 2 + monitoring.register_callback(2, monitoring.events.LINE, jump_after_large_loop) + assert large_loop() == 0 +finally: + monitoring.set_local_events(2, large_loop.__code__, 0) + for event in (monitoring.events.LINE, monitoring.events.INSTRUCTION): + monitoring.register_callback(2, event, None) + monitoring.free_tool_id(2) + + +# Combined instruction events must preserve loop-header line events. +def monitored_loop(): + total = 0 + for value in (1, 2): + total += value + return total + + +lines = [] +monitoring.use_tool_id(2, "combined-lines") +try: + monitoring.register_callback( + 2, + monitoring.events.LINE, + lambda code, line: lines.append(line - code.co_firstlineno), + ) + monitoring.register_callback(2, monitoring.events.INSTRUCTION, lambda *args: None) + monitoring.set_local_events( + 2, + monitored_loop.__code__, + monitoring.events.LINE | monitoring.events.INSTRUCTION, + ) + assert monitored_loop() == 3 + assert lines == [1, 2, 3, 2, 3, 2, 4] +finally: + monitoring.set_local_events(2, monitored_loop.__code__, 0) + for event in (monitoring.events.LINE, monitoring.events.INSTRUCTION): + monitoring.register_callback(2, event, None) + monitoring.free_tool_id(2) + assert sys.exc_info() == (None, None, None) try: @@ -149,6 +391,41 @@ def recursive_call(n): assert proc.stdout.rstrip() == "True" assert proc.returncode == 0, proc +# Native environment paths must survive startup before the codecs are imported. +if os.name == "posix" and sys.platform not in ("wasi", "emscripten"): + with tempfile.TemporaryDirectory() as directory: + native_paths = [ + os.fsencode(directory) + b"/first-\xff", + os.fsencode(directory) + b"/second-\xfe", + ] + path_env = dict(os.environ) + path_env.pop("RUSTPYTHONPATH", None) + path_env["PYTHONPATH"] = os.fsdecode(os.pathsep.encode().join(native_paths)) + for mode in ("0", "1"): + for flag in (None, "-E", "-I"): + code = ( + "import os, sys; " + f"expected = {native_paths!r}; " + "actual = [os.fsencode(p) for p in sys.path]; " + f"assert all((p in actual) == {flag is None} for p in expected)" + ) + args = [sys.executable, "-S", "-X", f"utf8={mode}"] + if flag is not None: + args.append(flag) + subprocess.run(args + ["-c", code], env=path_env, check=True) + + +# -S must prevent the site import itself, not just its customizations. +subprocess.run( + [ + sys.executable, + "-S", + "-c", + "import sys; assert sys.flags.no_site; assert 'site' not in sys.modules", + ], + check=True, +) + assert sys._getframemodulename() == "__main__", sys._getframemodulename() @@ -174,3 +451,401 @@ def test_getframemodulename(): del os.environ["PYTHONBREAKPOINT"] else: os.environ["PYTHONBREAKPOINT"] = saved_breakpoint_env + + +# A venv's symlink target takes precedence over home/. +if os.name == "posix" and sys.platform not in ("wasi", "emscripten"): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory).resolve() + interpreter = Path(sys.executable).resolve() + # A framework build can also run its embedded app directly. Match the + # installed launcher's file identity before applying launcher semantics. + framework_base = ( + Path(sys.base_prefix) + / "bin" + / f"python{sys.version_info.major}.{sys.version_info.minor}" + ) + framework_launcher = ( + sys.platform == "darwin" + and bool(getattr(sys, "_framework", "")) + and framework_base.is_file() + and interpreter.samefile(framework_base) + ) + home = root / "home" + home.mkdir() + venv_env = dict(os.environ) + for name in ("PYTHONHOME", "PYTHONEXECUTABLE", "__PYVENV_LAUNCHER__"): + venv_env.pop(name, None) + # Keep startup imports available even with the synthetic home directory. + venv_env["PYTHONPATH"] = os.pathsep.join(sys.path) + path_code = ( + "import sys; print(sys.executable); " + "print(sys._base_executable); print(sys.prefix)" + ) + + def executable_paths(executable, *, cwd=None, env=venv_env): + result = subprocess.run( + [str(executable), "-B", "-S", "-c", path_code], + cwd=cwd, + env=env, + capture_output=True, + text=True, + timeout=10, + ) + assert result.returncode == 0, result.stderr + return result.stdout.splitlines() + + for kind in ("absolute", "relative", "chain"): + bin_dir = root / kind / "bin" + bin_dir.mkdir(parents=True) + # Exercise both parent and adjacent pyvenv.cfg discovery. + prefix = bin_dir if kind == "chain" else bin_dir.parent + (prefix / "pyvenv.cfg").write_text(f"home = {home}\n") + executable = bin_dir / kind + # This regular file must never be preferred to a symlink's target. + (home / kind).touch() + if kind == "absolute": + executable.symlink_to(interpreter) + elif kind == "relative": + executable.symlink_to(os.path.relpath(interpreter, bin_dir)) + else: + (bin_dir / "target").symlink_to(interpreter) + executable.symlink_to("target") + invocation = f"./bin/{kind}" if kind == "relative" else executable + assert executable_paths(invocation, cwd=bin_dir.parent) == [ + str(executable), + str(framework_base if framework_launcher else interpreter), + str(prefix), + ] + + # Framework launchers preset their base; ordinary binaries keep argv[0]. + plain = root / "plain" / "python" + plain.parent.mkdir() + plain.symlink_to(interpreter) + assert executable_paths(plain)[:2] == [ + str(plain), + str(framework_base if framework_launcher else plain), + ] + + # Without a launcher preset, copies fall back to home/. + copied = root / "copied" / "python" + copied.parent.mkdir() + shutil.copy2(interpreter, copied) + (home / copied.name).touch() + (copied.parent / "pyvenv.cfg").write_text(f"home = {home}\n") + assert executable_paths(copied) == [ + str(copied), + str(framework_base if framework_launcher else home / copied.name), + str(copied.parent), + ] + + # A directory alias does not turn a copied executable into a symlink. + directory_alias = root / "directory-alias" + directory_alias.symlink_to(copied.parent, target_is_directory=True) + aliased_copy = directory_alias / copied.name + # The framework launcher canonicalizes its directory before dispatch. + assert executable_paths(aliased_copy) == [ + str(copied if framework_launcher else aliased_copy), + str(framework_base if framework_launcher else home / copied.name), + str(copied.parent if framework_launcher else directory_alias), + ] + + # Without a launcher preset, final-link resolution preserves target aliases. + target_link = root / "linked" / "python" + target_link.parent.mkdir() + (target_link.parent / "pyvenv.cfg").write_text(f"home = {home}\n") + target_link.symlink_to("../directory-alias/python") + assert executable_paths(target_link) == [ + str(target_link), + str(framework_base if framework_launcher else aliased_copy), + str(target_link.parent), + ] + + # macOS framework builds use a framework-derived base for overrides. + if sys.platform == "linux": + # Relative targets also preserve a double-leading-slash directory. + double_target = root / "double-target" + double_target.symlink_to("directory-alias/python") + target_link.unlink() + target_link.symlink_to("/" + str(double_target)) + assert executable_paths(target_link) == [ + str(target_link), + "/" + str(aliased_copy), + str(target_link.parent), + ] + + override_env = dict(venv_env, __PYVENV_LAUNCHER__=str(executable)) + assert executable_paths(plain, env=override_env) == [ + str(executable), + str(plain), + str(prefix), + ] + +# sys.call_tracing explicitly re-enters tracing/profile callbacks, then restores +# callback suppression on both normal returns and Python exceptions. + + +def _exercise_call_tracing(set_hook, get_hook, fail): + events = [] + + def nested(): + if fail: + raise LookupError("nested") + return 42 + + def suppressed(): + return 0 + + def trigger(): + return 0 + + def hook(frame, event, arg): + name = frame.f_code.co_name + if name in ("nested", "suppressed"): + events.append((name, event)) + if name == "trigger" and event == "call": + try: + result = sys.call_tracing(nested, ()) + assert result == 42 + except LookupError as e: + assert fail and str(e) == "nested" + suppressed() + return hook + + old = get_hook() + try: + set_hook(hook) + trigger() + assert get_hook() is hook + finally: + set_hook(old) + assert ("nested", "call") in events, events + assert ("nested", "return") in events, events + assert not any(name == "suppressed" for name, _ in events), events + return events + + +for set_hook, get_hook in [ + (sys.settrace, sys.gettrace), + (sys.setprofile, sys.getprofile), +]: + for fail in [False, True]: + _exercise_call_tracing(set_hook, get_hook, fail) + + def hook(*args): + return hook + + old = get_hook() + try: + sys.call_tracing(set_hook, (hook,)) + assert get_hook() is hook + sys.call_tracing(set_hook, (None,)) + assert get_hook() is None + finally: + set_hook(old) +assert sys.call_tracing(lambda x: x + 1, (41,)) == 42 + +# Changes made by an explicitly traced callback remain installed, without +# allowing ordinary callback code to recursively trace itself afterward. +for set_hook, get_hook in [ + (sys.settrace, sys.gettrace), + (sys.setprofile, sys.getprofile), +]: + for replace_hook in (False, True): + changed_events = [] + + def replacement(frame, event, arg): + if frame.f_code.co_name in ("later", "suppressed_after_change"): + changed_events.append((frame.f_code.co_name, event)) + return replacement + + selected_hook = replacement if replace_hook else None + + def suppressed_after_change(): + pass + + def trigger_change(): + pass + + def later(): + pass + + def original(frame, event, arg): + if frame.f_code.co_name == "trigger_change" and event == "call": + sys.call_tracing(set_hook, (selected_hook,)) + assert get_hook() is selected_hook + suppressed_after_change() + return original + + old = get_hook() + try: + set_hook(original) + trigger_change() + assert get_hook() is selected_hook + later() + finally: + set_hook(old) + assert not any(name == "suppressed_after_change" for name, _ in changed_events) + assert (("later", "call") in changed_events) == replace_hook + + +# Legacy profiling excludes constructors and callable instances, and binds a +# method descriptor independently for each event (legacy_tracing.c). +def check_profile_callables(): + class Constructor: + pass + + class CallableInstance: + def __call__(self): + pass + + import _lsprof + + # cProfile's table width includes the profiler's disable descriptor label. + assert ( + repr(_lsprof.Profiler.disable) + == "" + ) + + events = [] + + def record(frame, event, arg): + if event.startswith("c_") and arg is not sys.setprofile: + events.append((event, arg)) + + def capture(func): + events.clear() + sys.setprofile(record) + try: + func() + except TypeError: + pass + finally: + sys.setprofile(None) + return list(events) + + assert capture(Constructor) == [] + assert capture(list) == [] + assert capture(CallableInstance()) == [] + assert capture(lambda: list.append()) == [] + assert capture(lambda: list.append(1, 2)) == [] + receiver = [] + result = capture(lambda: list.append(receiver, 1)) + assert [event for event, _ in result] == ["c_call", "c_return"] + assert all(type(arg) is type(len) and arg.__self__ is receiver for _, arg in result) + assert result[0][1] is not result[1][1] + result = capture(lambda: list.append(receiver)) + assert [event for event, _ in result] == ["c_call", "c_exception"] + assert all(type(arg) is type(len) and arg.__self__ is receiver for _, arg in result) + result = capture(lambda: len(1)) + assert result == [("c_call", len), ("c_exception", len)] + + class NativeMethod: + select = classmethod(max) + + method = NativeMethod.select + assert capture(lambda: method(1)) == [("c_call", max), ("c_exception", max)] + assert capture(lambda: method(*(1,))) == [] + + def key_with_native_call(value): + return len(()) + + # EX suppresses only the wrapped native dispatch, not calls in callbacks. + assert capture(lambda: method(*(1,), key=key_with_native_call)) == [ + ("c_call", len), + ("c_return", len), + ("c_call", len), + ("c_return", len), + ] + + def native_calls(): + values = [] + for value in range(20): + values.append(value) + len(values) + isinstance(value, int) + values.count(value) + "aaa".replace("a", "b") + values.sort(reverse=True) + values.sort() + values.clear() + + native_calls() # Warm native-call specializations before profiling. + for _ in range(3): + result = capture(native_calls) + assert len(result) == 320 + assert [event for event, _ in result] == ["c_call", "c_return"] * 160 + native_calls() # Disable/re-enable must preserve warmed call sites. + + # Enabling profiling inside an unprofiled native call must not invent an + # unmatched c_return, even when sys.settrace was already active. + events.clear() + + def enable_profile(value): + sys.setprofile(record) + return value + + sys.settrace(lambda *args: None) + try: + sorted([1], key=enable_profile) + finally: + sys.setprofile(None) + sys.settrace(None) + assert not any(arg is sorted for _, arg in events) + + +check_profile_callables() + + +def check_bound_ex_monitoring(): + class NativeMethod: + select = classmethod(max) + + def success(): + return NativeMethod.select(*(1,), key=lambda value: 0) + + def failure(): + return NativeMethod.select(*(1,)) + + monitoring.use_tool_id(2, "bound-ex") + try: + for function in (success, failure): + events = [] + for name in ("CALL", "C_RETURN", "C_RAISE"): + + def callback(code, offset, callee, arg, name=name): + if ( + code is function.__code__ + and getattr(callee, "__func__", None) is max + ): + events.append(name) + + monitoring.register_callback( + 2, getattr(monitoring.events, name), callback + ) + monitoring.set_events( + 2, + monitoring.events.CALL + | monitoring.events.C_RETURN + | monitoring.events.C_RAISE, + ) + try: + if function is success: + assert function() is NativeMethod + else: + try: + function() + except TypeError: + pass + else: + raise AssertionError( + "bound max must reject incomparable operands" + ) + finally: + monitoring.set_events(2, 0) + assert events == ["CALL"], events + finally: + monitoring.free_tool_id(2) + + +check_bound_ex_monitoring() diff --git a/extra_tests/snippets/stdlib_sys_audit.py b/extra_tests/snippets/stdlib_sys_audit.py index fb177cd3598..95f415207f8 100644 --- a/extra_tests/snippets/stdlib_sys_audit.py +++ b/extra_tests/snippets/stdlib_sys_audit.py @@ -53,3 +53,538 @@ def add_hook(i): for w in workers: w.join() assert sorted(counts) == list(range(N)), counts + + +# Native open events must precede file access and custom openers, but follow +# FileIO's argument/path/mode validation. +def check_open_audit(): + import io + import os + import ssl + import tempfile + + import _remote_debugging + + events = [] + active = False + + class Denied(Exception): + pass + + def hook(event, args): + if active and event == "open": + events.append(args) + raise Denied + + def opener(*args): + raise AssertionError("opener ran before audit") + + sys.addaudithook(hook) + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "not-created") + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + try: + active = True + for operation in ( + lambda: open(path, "wb", opener=opener), + lambda: io.FileIO(path, "rb"), + lambda: io.FileIO(path, "w", opener=opener), + lambda: io.FileIO(path, "w", closefd=False), + lambda: io.FileIO(2**30, "r", closefd=False), + lambda: _remote_debugging.BinaryWriter(path, 1000, 0), + lambda: _remote_debugging.BinaryReader(path), + lambda: context.load_dh_params(path), + ): + previous = len(events) + try: + operation() + except Denied: + pass + else: + raise AssertionError("native open ignored hook denial") + assert len(events) == previous + 1 + assert events[0][:2] == (path, "w") + assert events[1][:2] == (path, "rb") + assert not os.path.exists(path) + assert events[-3:] == [(path, "wb", 0), (path, "rb", 0), (path, "rb", 0)] + + previous = len(events) + try: + io.FileIO(path, "invalid-mode") + except ValueError: + pass + else: + raise AssertionError("invalid mode accepted") + assert len(events) == previous + + class InvalidPath: + def __fspath__(self): + raise LookupError("path conversion") + + for operation in ( + lambda: _remote_debugging.BinaryWriter(InvalidPath(), 1000, 0), + lambda: _remote_debugging.BinaryReader(InvalidPath()), + lambda: context.load_dh_params(InvalidPath()), + ): + try: + operation() + except Denied: + pass + else: + raise AssertionError("Py_fopen path conversion ran before audit") + previous = len(events) + try: + _remote_debugging.BinaryWriter(path, 1000, 0, mode=5) + except ValueError: + pass + else: + raise AssertionError("invalid profiling mode accepted") + assert len(events) == previous + + try: + io.FileIO(InvalidPath()) + except LookupError: + pass + else: + raise AssertionError("path conversion failure ignored") + assert len(events) == previous + finally: + active = False + + +check_open_audit() + + +def check_fileio_reinitialization_audit(): + import io + import os + import tempfile + + active = False + events = [] + stream = None + + class Denied(Exception): + pass + + def hook(event, args): + if active and event == "open": + events.append(args) + if stream is not None: + assert stream.closed + assert stream.mode == "rb+" + raise Denied + + sys.addaudithook(hook) + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "existing") + with open(path, "wb") as output: + output.write(b"retained") + try: + active = True + try: + io.FileIO(path) + except Denied: + pass + else: + raise AssertionError("omitted-mode audit denial ignored") + assert events[-1][1] == "r" + active = False + for closefd in (True, False): + fd = os.open(path, os.O_RDWR) + stream = io.FileIO(fd, "r+", closefd=closefd) + active = True + try: + stream.__init__(path) + except Denied: + pass + else: + raise AssertionError("reinitialization audit denial ignored") + active = False + assert stream.closed + assert events[-1][1] == "r" + assert events[-1][2] & os.O_RDWR + try: + os.fstat(fd) + except OSError: + assert closefd + else: + assert not closefd + os.close(fd) + stream.close() + stream = None + assert open(path, "rb").read() == b"retained" + finally: + active = False + if stream is not None: + stream.close() + + +check_fileio_reinitialization_audit() + + +def check_winreg_audit_boundaries(): + if sys.platform != "win32": + return + import winreg + + class RegistryDenied(Exception): + pass + + blocked = None + events = [] + + def hook(event, args): + if event == blocked: + events.append(args) + raise RegistryDenied + + sys.addaudithook(hook) + # Valid conversion reaches the hook before accessing an invalid native handle. + negative_access = (1 << 32) - 1 if sys.maxsize > (1 << 32) else -1 + cases = [ + ("ConnectRegistry", (None, 0), "ConnectRegistry", (None, 0)), + ("CreateKey", (0, "x"), "CreateKey", (0, "x", winreg.KEY_WRITE)), + ("CreateKey", (0, None), "CreateKey", (0, None, winreg.KEY_WRITE)), + ("CreateKeyEx", (0, None), "CreateKey", (0, None, winreg.KEY_WRITE)), + ("CreateKeyEx", (0, "x", -1, -1), "CreateKey", (0, "x", negative_access)), + ("OpenKey", (0, "x", -1, -1), "OpenKey", (0, "x", negative_access)), + ("DeleteKeyEx", (0, "x", -1, -1), "DeleteKey", (0, "x", negative_access)), + ( + "CreateKeyEx", + (0, "x", 0, winreg.KEY_READ), + "CreateKey", + (0, "x", winreg.KEY_READ), + ), + ("DeleteKey", (0, "x"), "DeleteKey", (0, "x", 0)), + ( + "DeleteKeyEx", + (0, "x", winreg.KEY_WOW64_64KEY), + "DeleteKey", + (0, "x", winreg.KEY_WOW64_64KEY), + ), + ("DeleteValue", (0, None), "DeleteValue", (0, None)), + ("EnumValue", (0, -1), "EnumValue", (0, -1)), + ("LoadKey", (0, "x", "x.dat"), "LoadKey", (0, "x", "x.dat")), + ("SaveKey", (0, "x.dat"), "SaveKey", (0, "x.dat")), + ( + "SetValue", + (0, "x", winreg.REG_SZ, "a\0b"), + "SetValue", + (0, "x", winreg.REG_SZ, "a\0b"), + ), + ( + "SetValueEx", + (0, None, None, winreg.REG_SZ, "a\0b"), + "SetValue", + (0, None, winreg.REG_SZ, "a\0b"), + ), + ("DisableReflectionKey", (0,), "DisableReflectionKey", (0,)), + ("EnableReflectionKey", (0,), "EnableReflectionKey", (0,)), + ("QueryReflectionKey", (0,), "QueryReflectionKey", (0,)), + ( + "ExpandEnvironmentStrings", + ("%PATH%",), + "ExpandEnvironmentStrings", + ("%PATH%",), + ), + ] + for name, args, event, expected in cases: + blocked = "winreg." + event + events.clear() + try: + getattr(winreg, name)(*args) + except RegistryDenied: + pass + else: + raise AssertionError(name) + assert events == [expected], (name, events) + # Argument Clinic rejects values outside C int before emitting the event. + for name, event in ( + ("CreateKeyEx", "CreateKey"), + ("OpenKey", "OpenKey"), + ("DeleteKeyEx", "DeleteKey"), + ): + for invalid in (1 << 31, -(1 << 31) - 1): + for parameter in ("access", "reserved"): + blocked = "winreg." + event + events.clear() + try: + getattr(winreg, name)(0, "x", **{parameter: invalid}) + except OverflowError: + pass + else: + raise AssertionError((name, parameter, invalid)) + assert events == [] + blocked = "winreg.SetValue" + events.clear() + for kind, value in ( + (winreg.REG_DWORD, "bad"), + (winreg.REG_QWORD, "bad"), + (winreg.REG_SZ, 0), + (winreg.REG_EXPAND_SZ, 0), + (winreg.REG_MULTI_SZ, "bad"), + (winreg.REG_MULTI_SZ, ["ok", 0]), + ): + try: + winreg.SetValueEx(0, None, None, kind, value) + except ValueError as exc: + assert str(exc) == "Could not convert the data to the specified type." + else: + raise AssertionError("data conversion must precede audit") + assert events == [] + for kind, value in ( + (winreg.REG_DWORD, -1), + (winreg.REG_DWORD, 1 << 32), + (winreg.REG_QWORD, -1), + (winreg.REG_QWORD, 1 << 64), + ): + try: + winreg.SetValueEx(0, None, None, kind, value) + except OverflowError: + pass + else: + raise AssertionError("numeric overflow must precede audit") + assert events == [] + try: + winreg.SetValueEx(0, None, None, winreg.REG_BINARY, object()) + except TypeError: + pass + else: + raise AssertionError("binary conversion must precede audit") + assert events == [] + + blocked = None + key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software") + for count in (2, 4): + try: + key.__exit__(*([None] * count)) + except TypeError: + pass + else: + raise AssertionError("incorrect context exit arity accepted") + assert int(key) != 0 + try: + handle = int(key) + blocked = "winreg.PyHKEY.Detach" + try: + key.Detach() + except RegistryDenied: + pass + else: + raise AssertionError("detach veto ignored") + assert int(key) == handle + blocked = None + assert key.Detach() == handle + assert int(key) == 0 + winreg.CloseKey(handle) + winreg.CloseKey(None) + winreg.CloseKey(0) + finally: + blocked = None + key.__exit__(None, None, None) + winreg.CloseKey(key) + + # A reentrant hook may detach first; the outer call must return zero. + key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software") + nested = [] + active = True + + def detach_again(event, args): + nonlocal active + if active and event == "winreg.PyHKEY.Detach": + active = False + nested.append(key.Detach()) + + sys.addaudithook(detach_again) + try: + assert key.Detach() == 0 + winreg.CloseKey(nested[0]) + finally: + active = False + key.Close() + + # The temporary key must survive argument conversion and the hook. + class Index: + def __index__(self): + import gc + + gc.collect() + return -1 + + try: + winreg.EnumKey(winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software"), Index()) + except OSError as error: + assert error.winerror == 259 # No more items, not invalid handle (6). + else: + raise AssertionError("out-of-range enumeration succeeded") + + # A result hook can reject the newly created owner; its handle must not leak. + for open_key in (winreg.OpenKey, winreg.CreateKey, winreg.CreateKeyEx): + blocked = "winreg.OpenKey/result" + events.clear() + try: + open_key(winreg.HKEY_CURRENT_USER, "Software") + except RegistryDenied: + pass + else: + raise AssertionError("result veto ignored") + blocked = None + rejected_handle = events[-1][0] + try: + # Closing probes validity without requiring KEY_QUERY_VALUE, which + # CreateKeyEx's default KEY_WRITE handle does not grant. + winreg.CloseKey(rejected_handle) + except OSError as error: + assert error.winerror == 6 + else: + # CPython fixed result-audit handle cleanup in 3.15.1. The CI + # reference is still 3.15.0; RustPython must always close it. + # A successful close has also cleaned up that old reference leak. + if not ( + sys.implementation.name == "cpython" and sys.version_info < (3, 15, 1) + ): + raise AssertionError("rejected registry handle leaked") + + +check_winreg_audit_boundaries() + + +def check_winapi_audit_boundaries(): + if sys.platform != "win32": + return + import _winapi + + class Denied(Exception): + pass + + class Name(str): + pass + + blocked = None + seen = [] + + def hook(event, args): + if event == blocked: + seen.append(args) + raise Denied + + sys.addaudithook(hook) + cases = [ + ("CreateEventW", (0, -1, 256, Name("audit-event")), (-1, 256, "audit-event")), + ("CreateMutexW", (0, 2, None), (2, None)), + ( + "CreateFile", + (Name("missing-audit-file"), 0, 0, 0, 3, 0, 0), + ("missing-audit-file", 0, 0, 3, 0), + ), + ( + "CreateNamedPipe", + (Name(r"\\.\pipe\audit-boundary"), 3, 8, 1, 0, 0, 0, 0), + (r"\\.\pipe\audit-boundary", 3, 8), + ), + ("CreatePipe", (None, 0), ()), + ( + "CreateJunction", + (Name("missing-audit-source"), Name("missing-audit-destination")), + ("missing-audit-source", "missing-audit-destination"), + ), + ("OpenEventW", (1, 2, Name("missing-audit-event")), (1, "missing-audit-event")), + ( + "OpenMutexW", + (1, -1, Name("missing-audit-mutex")), + (1, "missing-audit-mutex"), + ), + ("OpenProcess", (1, 2, 0), (0, 1)), + ("TerminateProcess", (0, 123), (0, 123)), + ( + "CopyFile2", + (Name("missing-audit-source"), Name("missing-audit-destination"), 0), + ("missing-audit-source", "missing-audit-destination", 0), + ), + ] + for name, args, expected in cases: + blocked = "_winapi." + name + seen.clear() + try: + getattr(_winapi, name)(*args) + except Denied: + pass + else: + raise AssertionError(name) + assert seen == [expected], (name, seen) + assert all( + type(actual) is type(want) for actual, want in zip(seen[0], expected) + ) + + if sys.implementation.name == "rustpython": + # CPython's Unicode-format audit path is unsafe for this sentinel. + accesses = [] + + class Unused: + def __getattribute__(self, name): + accesses.append(name) + raise AssertionError("CreateProcess processed arguments before audit") + + command_line = object() + blocked = "_winapi.CreateProcess" + seen.clear() + try: + _winapi.CreateProcess( + None, command_line, None, None, 0, 0, Unused(), None, Unused() + ) + except Denied: + pass + else: + raise AssertionError("CreateProcess audit did not deny the call") + assert seen == [(None, command_line, None)] + assert seen[0][1] is command_line + assert not accesses + + # Unicode conversion must run before a later integer converter or audit. + calls = [] + + class Index: + def __index__(self): + calls.append("index") + return 0 + + blocked = "_winapi.CreateFile" + seen.clear() + try: + _winapi.CreateFile("bad\0name", Index(), 0, 0, 3, 0, 0) + except ValueError: + pass + else: + raise AssertionError("embedded NUL accepted") + assert not calls and not seen + + # BOOL arguments use C int conversion, not truth testing. + class Truth: + def __bool__(self): + raise AssertionError("BOOL must not call __bool__") + + blocked = "_winapi.CreateEventW" + seen.clear() + try: + _winapi.CreateEventW(0, Truth(), 0, None) + except TypeError: + pass + else: + raise AssertionError("BOOL accepted a truth-only object") + assert not seen + + # CreateJunction performs its invalid-prefix check before the audit. + blocked = "_winapi.CreateJunction" + seen.clear() + try: + _winapi.CreateJunction(r"\??\invalid", "unused") + except OSError as error: + assert error.winerror == 87 + else: + raise AssertionError("invalid junction prefix accepted") + assert not seen + blocked = None + + +check_winapi_audit_boundaries() diff --git a/extra_tests/snippets/stdlib_sys_getframe.py b/extra_tests/snippets/stdlib_sys_getframe.py index 50447ce8822..80b63187d67 100644 --- a/extra_tests/snippets/stdlib_sys_getframe.py +++ b/extra_tests/snippets/stdlib_sys_getframe.py @@ -23,3 +23,26 @@ def __init__(self): TestClass() + + +# A frame entered from a generator expression's eager iterator prefix sees +# the creating function as its caller. +iterator_frames = [] + + +class Iterable: + def __iter__(self): + iterator_frames.append((sys._getframe(), sys._getframe(1))) + return iter([7]) + + +def create(): + return (value for value in Iterable()) + + +generator = create() +frame, caller = iterator_frames[0] +assert caller.f_code.co_name == "create" +assert frame.f_back is caller +assert generator.gi_frame.f_back is None +assert list(generator) == [7] diff --git a/extra_tests/snippets/stdlib_sys_prompts.py b/extra_tests/snippets/stdlib_sys_prompts.py new file mode 100644 index 00000000000..78be7a44a88 --- /dev/null +++ b/extra_tests/snippets/stdlib_sys_prompts.py @@ -0,0 +1,6 @@ +import sys + +# Importing sys in a non-interactive program must not create REPL prompts. +# Their absence also lets inline pdb distinguish scripts from a REPL session. +assert not hasattr(sys, "ps1") +assert not hasattr(sys, "ps2") diff --git a/extra_tests/snippets/stdlib_threading.py b/extra_tests/snippets/stdlib_threading.py index cb989e1fd33..4afaaace508 100644 --- a/extra_tests/snippets/stdlib_threading.py +++ b/extra_tests/snippets/stdlib_threading.py @@ -118,3 +118,30 @@ def runner(): scope = run_exec("module = __import__('multiprocessing.connection', fromlist=['*'])") assert scope["module"].__name__ == "multiprocessing.connection" + + +class LocalWithProperty(threading.local): + def __init__(self, value): + self.name = value + + @property + def name(self): + return self._name + + @name.setter + def name(self, value): + self._name = value + + +local_with_property = LocalWithProperty("main") +assert local_with_property.name == "main" +assert "name" not in local_with_property.__dict__ +assert local_with_property.__dict__["_name"] == "main" + +local_property_results = [] +local_property_thread = threading.Thread( + target=lambda: local_property_results.append(local_with_property.name) +) +local_property_thread.start() +local_property_thread.join() +assert local_property_results == ["main"] diff --git a/extra_tests/snippets/stdlib_threading_current_frames.py b/extra_tests/snippets/stdlib_threading_current_frames.py index e93a222148e..332c29eb5e7 100644 --- a/extra_tests/snippets/stdlib_threading_current_frames.py +++ b/extra_tests/snippets/stdlib_threading_current_frames.py @@ -97,4 +97,48 @@ def f123(): leave.set() t.join() + +def release_deep_snapshot(): + # Detached snapshots can own a deep chain of untracked frames. Releasing + # one on a small native stack must not recurse through the entire chain. + depth = 5000 + ready = threading.Event() + release = threading.Event() + disposed = threading.Event() + + def recurse(n): + if n: + recurse(n - 1) + else: + ready.set() + release.wait() + + def inspect(): + frame = sys._current_frames()[worker.ident] + del frame + disposed.set() + + old_limit = sys.getrecursionlimit() + old_stack = threading.stack_size() + worker = threading.Thread(target=recurse, args=(depth,), daemon=True) + try: + sys.setrecursionlimit(depth + 100) + worker.start() + assert ready.wait(30), "worker did not reach the bottom of its stack" + threading.stack_size(256 * 1024) + observer = threading.Thread(target=inspect, daemon=True) + observer.start() + observer.join(30) + assert not observer.is_alive(), "snapshot disposal did not finish" + assert disposed.is_set(), "snapshot disposal failed" + finally: + threading.stack_size(old_stack) + release.set() + worker.join(30) + sys.setrecursionlimit(old_limit) + assert not worker.is_alive(), "worker did not finish" + + +release_deep_snapshot() + print("ok") diff --git a/extra_tests/snippets/stdlib_time.py b/extra_tests/snippets/stdlib_time.py index b74d5bbc638..1aa2627ce42 100644 --- a/extra_tests/snippets/stdlib_time.py +++ b/extra_tests/snippets/stdlib_time.py @@ -1,6 +1,118 @@ import sys import time +from testutils import assert_raises + +if sys.platform == "win32": + # Record the native runtime before evaluating the range regression below. + print("Windows time runtime:", sys.version, sys.implementation, sys.flags) + print("Windows time word size:", sys.maxsize) + if hasattr(sys, "getwindowsversion"): + print("Windows version:", sys.getwindowsversion()) + try: + import sysconfig + + build_keys = ( + "Py_DEBUG", + "Py_GIL_DISABLED", + "Py_ENABLE_SHARED", + "SIZEOF_TIME_T", + "CC", + "CFLAGS", + ) + print( + "Windows time build:", + dict(zip(build_keys, sysconfig.get_config_vars(*build_keys))), + ) + except Exception as error: + print("Windows time build unavailable:", type(error).__name__, str(error)) + for converter in (time.gmtime, time.localtime, time.ctime): + for timestamp in ( + 0, + -1, + -43200, + -43201, + -86400, + 2**40, + 2**63 - 1, + -(2**63), + -float(2**63), + float(2**63), + ): + try: + result = converter(timestamp) + except Exception as error: + print( + "Windows time result:", + converter.__name__, + repr(timestamp), + type(error).__name__, + str(error), + getattr(error, "errno", None), + getattr(error, "winerror", None), + ) + else: + print( + "Windows time result:", + converter.__name__, + repr(timestamp), + "success", + repr(result), + ) + +if sys.platform != "wasi": + for converter in (time.gmtime, time.localtime, time.ctime): + # 2**63 is outside signed time_t even though its maximum rounds up to + # that value when represented as a float. + try: + converter(float(2**63)) + except OverflowError: + pass + else: + raise AssertionError("out-of-range timestamp did not raise OverflowError") + +if sys.platform == "win32": + import errno + + for converter in (time.gmtime, time.localtime, time.ctime): + # Non-negative timestamps still use UCRT and preserve errno. + for timestamp in (2**40, 2**63 - 1): + try: + converter(timestamp) + except OSError as error: + assert error.errno == errno.EINVAL, (converter, timestamp, error) + else: + raise AssertionError("UCRT timestamp failure did not raise OSError") + + # Negative timestamps use FILETIME, whose epoch is 1601-01-01. + for timestamp in (-11_644_473_601, -(2**63), -float(2**63)): + try: + converter(timestamp) + except OverflowError as error: + assert str(error) == "timestamp out of range for Windows FILETIME" + else: + raise AssertionError( + "pre-FILETIME timestamp did not raise OverflowError" + ) + + assert time.gmtime(-11_644_473_600) == (1601, 1, 1, 0, 0, 0, 0, 1, 0) + assert time.gmtime(-86400) == (1969, 12, 31, 0, 0, 0, 2, 365, 0) + assert time.gmtime(-1) == (1969, 12, 31, 23, 59, 59, 2, 365, 0) + # Leap-year accounting uses the historical date, including century rules. + assert time.gmtime(-2_203_891_200).tm_yday == 60 # 1900-03-01 + assert time.gmtime(-2_330_035_200).tm_yday == 61 # 1896-03-01 + for timestamp in (-15_897_600, -86400, -43201, -1): + local = time.localtime(timestamp) + assert local.tm_isdst == -1 + assert local[:6] == time.gmtime(timestamp + local.tm_gmtoff)[:6] + assert time.ctime(timestamp) == time.asctime(local) + +if sys.platform == "win32": + # The explicit 64-bit CRT ABI must accept timestamps beyond 2038. + for timestamp in (2_208_988_800, 2_208_988_800.0): + assert time.gmtime(timestamp) == (2040, 1, 1, 0, 0, 0, 6, 1, 0) + + x = time.gmtime(1000) assert x.tm_year == 1970 @@ -12,6 +124,29 @@ # print(s) assert s == "1970-01-01-00-16-40" +if sys.platform in ("linux", "darwin"): + import locale + + old_locale = locale.setlocale(locale.LC_ALL) + try: + # Locale output must be Unicode even when the locale is not UTF-8. + # Keep LC_CTYPE and LC_TIME consistent for wcsftime on macOS. + # These locales are optional on the host running the snippet. + for time_locale in ("fr_FR.ISO8859-1", "fr_FR.UTF-8"): + try: + locale.setlocale(locale.LC_ALL, time_locale) + except locale.Error: + continue + february = (2024, 2, 1, 12, 0, 0, 3, 32, 0) + assert time.strftime("%B", february) == "février" + assert ( + time.strftime("[%B] 🐍 \ud800\0%Y", february) + == "[février] 🐍 \ud800\0" + "2024" + ) + assert time.strftime("%B" * 300, february) == "février" * 300 + finally: + locale.setlocale(locale.LC_ALL, old_locale) + if sys.platform != "wasi": # _strptime depends on time.tzname, which is not available on WASI yet. x2 = time.strptime(s, "%Y-%m-%d-%H-%M-%S") @@ -83,6 +218,62 @@ assert monotonic_elapsed >= 0.01 assert perf_elapsed >= 0.01 +# Sleep validates signed nanoseconds before rejecting negative durations. +for duration in ( + 2**63, + -(2**63) - 1, + 2**34, + -(2**34), + 2**63 / 1_000_000_000, + -1e10, + float("inf"), + -float("inf"), +): + with assert_raises(OverflowError) as error: + time.sleep(duration) + assert str(error.exception) == "timestamp out of range for C PyTime_t" +assert_raises(ValueError, time.sleep, float("nan")) + + +class SleepTypeNamespace: + class Invalid: + pass + + +for module in ("__main__", "sleep_test"): + SleepTypeNamespace.Invalid.__module__ = module + with assert_raises(TypeError) as error: + time.sleep(SleepTypeNamespace.Invalid()) + assert str(error.exception) == "must be real number, not Invalid" + + +class FloatSleepDuration: + def __float__(self): + return -0.5 + + +class IndexedSleepDuration(FloatSleepDuration): + def __index__(self): + return -1 + + def __float__(self): + raise AssertionError("sleep must prefer __index__") + + +class InvalidIndexedSleepDuration(FloatSleepDuration): + def __index__(self): + raise TypeError("index conversion failed") + + +for duration in (FloatSleepDuration(), IndexedSleepDuration()): + with assert_raises(ValueError) as error: + time.sleep(duration) + assert str(error.exception) == "sleep length must be non-negative" + +with assert_raises(TypeError) as error: + time.sleep(InvalidIndexedSleepDuration()) +assert str(error.exception) == "index conversion failed" + # The optional second argument fills the fields that are not part of the # sequence. fields = (2024, 1, 2, 3, 4, 5, 6, 7, 0) diff --git a/extra_tests/snippets/stdlib_tokenize.py b/extra_tests/snippets/stdlib_tokenize.py new file mode 100644 index 00000000000..e8729e2cad5 --- /dev/null +++ b/extra_tests/snippets/stdlib_tokenize.py @@ -0,0 +1,46 @@ +import io +import tokenize + +# Pending f-string parts must use the correct source line after CRLF lines. +source = 'pass\r\npass\r\nf"a}}b"\r\n' +tokens = list(tokenize.generate_tokens(io.StringIO(source).readline)) +parts = [tok for tok in tokens if tok.type == tokenize.FSTRING_MIDDLE] +assert parts +assert all(tok.line == 'f"a}}b"\r\n' for tok in parts) + +# Each doubled brace ends a middle token, with positions in source characters. +for prefix, middle_type in ( + ("f", tokenize.FSTRING_MIDDLE), + ("t", tokenize.TSTRING_MIDDLE), +): + for body, expected in ( + ( + "a{{b}}c", + [("a{", (1, 2), (1, 4)), ("b}", (1, 5), (1, 7)), ("c", (1, 8), (1, 9))], + ), + ( + "é{{a}}b", + [("é{", (1, 2), (1, 4)), ("a}", (1, 5), (1, 7)), ("b", (1, 8), (1, 9))], + ), + ( + "x{{{{y", + [("x{", (1, 2), (1, 4)), ("{", (1, 5), (1, 6)), ("y", (1, 7), (1, 8))], + ), + ( + "x}}}}y", + [("x}", (1, 2), (1, 4)), ("}", (1, 5), (1, 6)), ("y", (1, 7), (1, 8))], + ), + ): + source = prefix + '"' + body + '"' + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + actual = [(t.string, t.start, t.end) for t in tokens if t.type == middle_type] + assert actual == expected, (source, actual) + + source = prefix + '"""a\n{{b}}c"""' + tokens = tokenize.generate_tokens(io.StringIO(source).readline) + actual = [(t.string, t.start, t.end) for t in tokens if t.type == middle_type] + assert actual == [ + ("a\n{", (1, 4), (2, 1)), + ("b}", (2, 2), (2, 4)), + ("c", (2, 5), (2, 6)), + ], actual diff --git a/extra_tests/snippets/stdlib_types.py b/extra_tests/snippets/stdlib_types.py index d913095f2f9..7cb665ee2b2 100644 --- a/extra_tests/snippets/stdlib_types.py +++ b/extra_tests/snippets/stdlib_types.py @@ -43,25 +43,55 @@ def _run_missing_type_params_regression(): _run_missing_type_params_regression() -if sys.implementation.name == "rustpython": - # __parameters__ is computed when the alias is built, and the walk descends - # into every list and tuple argument, so a self-referential or deeply - # nested argument must be caught. CPython, which also runs this snippet, - # does not walk into plain lists at all. - self_referential = [] - self_referential.append(self_referential) - with assert_raises(RecursionError): - list[self_referential] +# GenericAlias construction is lazy. Python 3.15 walks nested lists and tuples +# when parameters are first needed, including during subscription. +self_referential = [] +self_referential.append(self_referential) +alias = list[self_referential] +with assert_raises(RecursionError): + alias.__parameters__ +with assert_raises(RecursionError): + alias[int] +if sys.implementation.name == "rustpython": + # Finite-depth stack exhaustion depends on the interpreter build and OS stack. + # Keep this native stress case separate from the shared cyclic contract above. nested = [0] for _ in range(100_000): nested = [nested] + alias = list[nested] with assert_raises(RecursionError): - list[nested] + alias.__parameters__ + with assert_raises(RecursionError): + alias[int] - # hashing an alias walks the same shape + # hashing an alias walks the same shape. Release inlining of the hash + # slot needs more depth than debug to trip the native stack guard. deep_alias = int - for _ in range(100_000): + for _ in range(500_000): deep_alias = list[deep_alias] with assert_raises(RecursionError): hash(deep_alias) + + +# FunctionType preserves the code qualified name when a name is supplied. +def outer(): + def nested(): + pass + + return nested + + +original = outer() +for name in ("renamed", ""): + function = types.FunctionType(original.__code__, globals(), name) + assert function.__name__ == name + assert function.__qualname__ == "outer..nested" + +tb = types.TracebackType( + tb_next=None, tb_frame=sys._getframe(), tb_lasti=0, tb_lineno=7 +) +assert tb.tb_next is None +assert tb.tb_frame is sys._getframe() +assert tb.tb_lasti == 0 +assert tb.tb_lineno == 7 diff --git a/extra_tests/snippets/stdlib_typing.py b/extra_tests/snippets/stdlib_typing.py index 4082d683f8d..7c87af7dd7b 100644 --- a/extra_tests/snippets/stdlib_typing.py +++ b/extra_tests/snippets/stdlib_typing.py @@ -1,7 +1,7 @@ +import _typing from collections.abc import Awaitable, Callable from typing import TypeVar -import _typing from testutils import assert_raises T = TypeVar("T") @@ -63,3 +63,409 @@ def method(self, value: Union[int, float]) -> Union[str, bytes]: repr(nested) except RecursionError: pass + + +# Python 3.14.8 retains ParamSpec bounds without converting or validating them. +assert ParamSpec("Unbounded").__bound__ is None +for bound in (None, "int", "not valid Python!", (int, str), object()): + assert ParamSpec("BoundSpec", bound=bound).__bound__ is bound + +# Eager aliases without a caller module never inspect their aliased value. +alias_module_lookups = [] + + +class AliasModuleValue: + @property + def __module__(self): + alias_module_lookups.append(True) + return "unexpected_value_module" + + +for alias_value in (int, AliasModuleValue()): + alias_namespace = {"value": alias_value} + exec( + "from typing import TypeAliasType; alias = TypeAliasType('Alias', value)", + alias_namespace, + ) + assert alias_namespace["alias"].__module__ is None +assert alias_module_lookups == [] + + +# GenericAlias rejects parameters added after its parameter tuple was cached. +from types import GenericAlias + + +class LateParameter: + def __repr__(self): + return "late_parameter" + + +first = LateParameter() +first.__typing_subst__ = lambda value: value +late = LateParameter() +alias = GenericAlias(dict, (first, late)) +assert alias.__parameters__ == (first,) +late.__typing_subst__ = lambda value: value +with assert_raises(TypeError) as caught: + alias[0] +assert str(caught.exception) == ( + "argument late_parameter with __typing_subst__ was not found in __parameters__" +) + + +def test_union_lazy_parameters(): + import threading + from types import GenericAlias + from typing import Union + + from testutils import assert_raises + + class Parameter: + def __typing_subst__(self, value): + return value + + parameter = Parameter() + + class LateParameter: + __parameters__ = (parameter,) + + def __repr__(self): + return "late_parameter" + + # Building a union must not freeze the nested alias's parameter cache. + for materialize in (False, True): + for subscribe_first in (False, True): + late = LateParameter() + alias = GenericAlias(list, late) + union = alias | int + if materialize: + cached = union.__parameters__ + assert cached == (parameter,) + late.__typing_subst__ = lambda value: value + if materialize: + with assert_raises(TypeError) as caught: + union[str] + assert str(caught.exception) == ( + "argument late_parameter with __typing_subst__ was not found in __parameters__" + ) + assert union.__parameters__ is cached + else: + if not subscribe_first: + assert union.__parameters__ == (late,) + assert union[str] == (list[str] | int) + assert alias[str] == list[str] + cached = union.__parameters__ + assert cached == (late,) + assert union.__parameters__ is cached + + # typing.Union and flattening an existing union preserve the same lazy boundary. + for make_union in ( + lambda alias: Union[alias, int], + lambda alias: (alias | bytes) | int, + ): + late = LateParameter() + alias = GenericAlias(list, late) + union = make_union(alias) + late.__typing_subst__ = lambda value: value + assert union[str] == make_union(list[str]) + assert alias[str] == list[str] + + # Nested descriptor failures occur on first use and do not poison either cache. + class FailingParameter: + fail = True + lookups = 0 + + @property + def __parameters__(self): + self.lookups += 1 + if self.fail: + raise RuntimeError("lazy union failure") + return (parameter,) + + for subscribe in (False, True): + failing = FailingParameter() + alias = GenericAlias(list, failing) + union = alias | int + assert failing.lookups == 0 + with assert_raises(RuntimeError) as caught: + if subscribe: + union[str] + else: + union.__parameters__ + assert str(caught.exception) == "lazy union failure" + failing.fail = False + cached = union.__parameters__ + assert cached == (parameter,) + count = failing.lookups + assert union.__parameters__ is cached + assert failing.lookups == count + + # Parameter collection uses identity, not union argument hash/equality rules. + parameter_comparisons = [] + + class EqualParameter(Parameter): + def __hash__(self): + parameter_comparisons.append("hash") + return 0 + + def __eq__(self, other): + parameter_comparisons.append("eq") + return True + + first = EqualParameter() + second = EqualParameter() + union = GenericAlias(tuple, (first, second)) | int + parameter_comparisons.clear() + cached = union.__parameters__ + assert len(cached) == 2 + assert cached[0] is first and cached[1] is second + assert parameter_comparisons == [] + assert union.__parameters__ is cached + + # Empty caches are also stable when a nested alias's descriptor changes. + state = {"parameters": ()} + + class ChangingAlias(GenericAlias): + @property + def __parameters__(self): + return state["parameters"] + + union = ChangingAlias(list, int) | str + cached = union.__parameters__ + assert cached == () + state["parameters"] = (parameter,) + assert union.__parameters__ is cached + with assert_raises(TypeError): + union[bytes] + + # Reentrant callbacks may populate the cache. The outer calculation replaces + # that cache on success and clears it on failure, allowing another attempt. + inner_parameter = Parameter() + outer_parameter = Parameter() + + for fail in (False, True): + state = {"entered": False, "parameters": (inner_parameter,)} + + class ReentrantAlias(GenericAlias): + @property + def __parameters__(self): + if not state["entered"]: + state["entered"] = True + state["inner"] = state["union"].__parameters__ + if fail: + raise RuntimeError("outer union failure") + return (outer_parameter,) + return state["parameters"] + + state["union"] = ReentrantAlias(list, int) | str + union = state["union"] + if fail: + with assert_raises(RuntimeError) as caught: + union.__parameters__ + assert str(caught.exception) == "outer union failure" + state["parameters"] = (outer_parameter,) + cached = union.__parameters__ + assert state["inner"] == (inner_parameter,) + assert cached == (outer_parameter,) + assert cached is not state["inner"] + assert union.__parameters__ is cached + + # Concurrent callbacks must run without holding the union's parameter lock. + barrier = threading.Barrier(2) + + class ConcurrentAlias(GenericAlias): + @property + def __parameters__(self): + barrier.wait(timeout=10) + return (parameter,) + + union = ConcurrentAlias(list, int) | str + results = [] + errors = [] + + def read_parameters(): + try: + results.append(union.__parameters__) + except BaseException as error: + errors.append(error) + + threads = [threading.Thread(target=read_parameters) for _ in range(2)] + for thread in threads: + thread.start() + for thread in threads: + thread.join(timeout=15) + assert all(not thread.is_alive() for thread in threads) + assert errors == [] + assert results == [(parameter,), (parameter,)] + cached = union.__parameters__ + assert any(cached is result for result in results) + assert union.__parameters__ is cached + + +test_union_lazy_parameters() + + +# Python 3.15 type alias qualified names and writable module metadata. +def test_type_alias_metadata(): + from typing import TypeAliasType + + class Name(str): + def __str__(self): + raise AssertionError("must use stored string contents") + + name = Name("Alias\ud800") + qualname = Name("Scope.Alias\udfff") + for explicit in (None, qualname): + alias = TypeAliasType(name, int, qualname=explicit) + expected = name if explicit is None else qualname + assert alias.__name__ is name + assert alias.__qualname__ is expected + assert repr(alias) == expected + assert alias.__reduce__() is name + with assert_raises(AttributeError): + alias.__qualname__ = "Other" + with assert_raises(AttributeError): + del alias.__qualname__ + for module in (object(), None, 42, "another_module"): + alias.__module__ = module + assert alias.__module__ is module + del alias.__module__ + assert alias.__module__ is None + del alias.__module__ + assert alias.__module__ is None + + assert TypeAliasType(name="Alias", value=int).__qualname__ == "Alias" + with assert_raises(TypeError): + TypeAliasType("Alias", int, qualname=42) + + type Local = int + assert Local.__qualname__ == "test_type_alias_metadata..Local" + assert repr(Local) == Local.__qualname__ + assert Local.__reduce__() == "Local" + original_module = Local.__module__ + Local.__module__ = None + assert Local.__module__ is None + del Local.__module__ + assert Local.__module__ == original_module + + class Container: + type Nested = int + + assert Container.Nested.__qualname__ == ( + "test_type_alias_metadata..Container.Nested" + ) + + +def test_typevartuple_bound_and_variance(): + from typing import NoDefault, TypeVarTuple + + class Name(str): + def __str__(self): + raise AssertionError("must use stored string contents") + + name = Name("Ts\ud800") + for options, prefix, flags in ( + ({}, "~", (False, False, False)), + ({"covariant": True}, "+", (True, False, False)), + ({"contravariant": True}, "-", (False, True, False)), + ({"infer_variance": True}, "", (False, False, True)), + ): + parameter = TypeVarTuple(name, **options) + assert parameter.__name__ is name + assert repr(parameter) == prefix + name + assert parameter.__bound__ is None + assert parameter.__default__ is NoDefault + assert not parameter.has_default() + assert ( + parameter.__covariant__, + parameter.__contravariant__, + parameter.__infer_variance__, + ) == flags + for attr in ( + "__bound__", + "__covariant__", + "__contravariant__", + "__infer_variance__", + ): + with assert_raises(AttributeError): + setattr(parameter, attr, None) + with assert_raises(AttributeError): + delattr(parameter, attr) + + for bound in (None, "not valid Python!", (int, str), object()): + default = object() + parameter = TypeVarTuple(name="Ts", bound=bound, default=default) + assert parameter.__bound__ is bound + assert parameter.__default__ is default + assert parameter.has_default() + + for options, message in ( + ( + {"covariant": True, "contravariant": True, "infer_variance": True}, + "Bivariant types are not supported.", + ), + ( + {"covariant": True, "infer_variance": True}, + "Variance cannot be specified with infer_variance.", + ), + ( + {"contravariant": True, "infer_variance": True}, + "Variance cannot be specified with infer_variance.", + ), + ): + with assert_raises(ValueError) as caught: + TypeVarTuple("Ts", **options) + assert str(caught.exception) == message + + calls = [] + + class Truth: + def __init__(self, label, fail=False): + self.label = label + self.fail = fail + + def __bool__(self): + calls.append(self.label) + if self.fail: + raise RuntimeError(self.label) + return False + + for positional, extra in ( + (("Ts",), {"unexpected": None}), + (("Ts",), {"name": "Duplicate"}), + ((42,), {}), + (("Ts", "extra"), {}), + ((), {}), + ): + with assert_raises(TypeError): + TypeVarTuple(*positional, covariant=Truth("not called", fail=True), **extra) + assert calls == [] + + TypeVarTuple( + "Ts", + infer_variance=Truth("infer"), + contravariant=Truth("contra"), + covariant=Truth("co"), + ) + assert calls == ["co", "contra", "infer"] + calls.clear() + with assert_raises(RuntimeError): + TypeVarTuple( + "Ts", + covariant=Truth("co", fail=True), + contravariant=Truth("contra"), + infer_variance=Truth("infer"), + ) + assert calls == ["co"] + + type Variadic[*Ts] = tuple[*Ts] + (parameter,) = Variadic.__type_params__ + assert parameter.__infer_variance__ is True + assert parameter.__covariant__ is False + assert parameter.__contravariant__ is False + assert parameter.__bound__ is None + assert repr(parameter) == "Ts" + + +test_type_alias_metadata() +test_typevartuple_bound_and_variance() diff --git a/extra_tests/snippets/stdlib_unicode_shared.py b/extra_tests/snippets/stdlib_unicode.py similarity index 54% rename from extra_tests/snippets/stdlib_unicode_shared.py rename to extra_tests/snippets/stdlib_unicode.py index e9ea79cab95..3f4c50567d1 100644 --- a/extra_tests/snippets/stdlib_unicode_shared.py +++ b/extra_tests/snippets/stdlib_unicode.py @@ -1,3 +1,55 @@ +# Check provider acquisition before any successful Unicode-name use. +# Keep named-escape literals inside runtime eval calls below so compiling this +# file does not prime the provider cache before these failed-import checks. +import codecs +import sys + +sys.modules["unicodedata"] = None +try: + codecs.namereplace_errors(ValueError()) +except TypeError: + pass +else: + raise AssertionError("exception type must be checked before import") +decoder = codecs.getincrementaldecoder("unicode_escape")("ignore") +try: + decoder.decode(rb"\N", final=False) +except UnicodeError as exc: + assert str(exc) == "\\N escapes not supported (can't load unicodedata module)" +else: + raise AssertionError("incomplete named escape must acquire the provider") +for data in (rb"\N", rb"\N{INVALID}", rb"\N{LATIN CAPITAL LETTER A}"): + try: + data.decode("unicode_escape", "ignore") + except UnicodeError as exc: + assert ( + str(exc) == "\\N escapes not supported (can't load unicodedata module)" + ), str(exc) + else: + raise AssertionError("the import failure must precede name validation") +try: + codecs.namereplace_errors(UnicodeEncodeError("ascii", "", 0, 0, "reason")) +except ImportError as exc: + assert str(exc) == 'PyCapsule_Import could not import module "unicodedata"' +else: + raise AssertionError("even an empty namereplace range acquires the provider") +import types + +sys.modules["unicodedata"] = types.SimpleNamespace(_ucnhash_CAPI=42) +try: + codecs.namereplace_errors(UnicodeEncodeError("ascii", "", 0, 0, "reason")) +except AttributeError as exc: + assert str(exc) == 'PyCapsule_Import "unicodedata._ucnhash_CAPI" is not valid' +else: + raise AssertionError("an invalid provider must not be cached") +del sys.modules["unicodedata"] +assert rb"\N{LATIN CAPITAL LETTER A}".decode("unicode_escape") == "A" +assert "unicodedata" in sys.modules +# A cached provider is shared with namereplace and remains valid after unload. +del sys.modules["unicodedata"] +assert chr(0x2603).encode("ascii", "namereplace") == rb"\N{SNOWMAN}" +assert "unicodedata" not in sys.modules + # Exercises the Unicode semantics routed through the shared rustpython-unicode # crate: str predicates, casefold, identifier rules, unicodedata queries, # normalization, \N{} escapes, and re character classes. @@ -79,11 +131,13 @@ assert unicodedata.normalize("NFD", composed) == decomposed assert unicodedata.is_normalized("NFC", composed) assert not unicodedata.is_normalized("NFD", composed) +assert unicodedata.normalize("X", "") == "" +assert unicodedata.is_normalized("X", "") is True # --- \N{} escapes (compiler) --------------------------------------------- -assert "\N{SNOWMAN}" == "☃" -assert "\N{GREEK SMALL LETTER ALPHA}" == "α" +assert eval(r'"\N{SNOWMAN}"') == "☃" +assert eval(r'"\N{GREEK SMALL LETTER ALPHA}"') == "α" # --- re character classes ------------------------------------------------- @@ -100,4 +154,27 @@ # case-insensitive matching routes through the shared case helpers assert re.fullmatch(r"straße", "STRAßE", re.IGNORECASE) is not None -print("stdlib_unicode_shared: OK") +# Surrogates retain their UCD properties even though they are not Rust chars. +for database in (unicodedata, unicodedata.ucd_3_2_0): + for codepoint in (0xD800, 0xDBFF, 0xDC00, 0xDFFF): + assert database.bidirectional(chr(codepoint)) == "L" + +# Existing characters must not acquire numeric values introduced after 3.2. +for character, value in (("\u09f8", 0.75), ("\u3405", 5.0), ("\u3483", 2.0)): + assert unicodedata.numeric(character) == value + assert unicodedata.ucd_3_2_0.numeric(character, None) is None + try: + unicodedata.ucd_3_2_0.numeric(character) + except ValueError: + pass + else: + raise AssertionError("modern numeric property leaked into Unicode 3.2") +assert unicodedata.ucd_3_2_0.numeric("\u4e00") == 1.0 + +# Native name consumers use the UCD file-order private alias/sequence records. +assert chr(0xF0000).encode("ascii", "namereplace") == rb"\N{NULL}" +assert chr(0xF0200).encode("ascii", "namereplace") == rb"\N{KEYCAP NUMBER SIGN}" +assert unicodedata.name(chr(0xF0000), None) is None +assert unicodedata.name(chr(0xF0200), None) is None + +print("stdlib_unicode: OK") diff --git a/extra_tests/snippets/stdlib_warnings.py b/extra_tests/snippets/stdlib_warnings.py index 95092e50668..38d4fdceae6 100644 --- a/extra_tests/snippets/stdlib_warnings.py +++ b/extra_tests/snippets/stdlib_warnings.py @@ -1,3 +1,76 @@ import _warnings +import sys _warnings.warn("Test") + + +import warnings + + +class CustomWarning(UserWarning): + pass + + +for category in (None, DeprecationWarning, int, 42): + message = CustomWarning("sentinel") + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + warnings.warn(message, category) + assert len(caught) == 1 + assert caught[0].message is message + assert caught[0].category is CustomWarning + + +from importlib.machinery import ModuleSpec + +events = [] + + +class WarningLoader: + def get_source(self, name): + events.append(("source", name)) + return "source line\n" + + +class WarningGlobals(dict): + def get(self, key, default=None): + events.append(("get", key)) + return super().get(key, default) + + def __getitem__(self, key): + raise AssertionError("module name must use stored dict lookup") + + __missing__ = __getitem__ + + +loader = WarningLoader() +module_globals = WarningGlobals( + __name__="stored_name", + __loader__=loader, + __spec__=ModuleSpec("stored_name", loader), +) +for has_name in (True, False): + events.clear() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + warnings.warn_explicit( + "subclass globals", + UserWarning, + "fixed_ascii.py", + 1, + module_globals=module_globals, + ) + assert len(caught) == 1 + expected = [ + ("get", "__loader__"), + ("get", "__spec__"), + ] + # CPython 3.15.0, still used by CI, requires __name__. Since 3.15.1 + # it prefers __spec__.name; RustPython must follow the newer behavior. + if has_name or not ( + sys.implementation.name == "cpython" and sys.version_info < (3, 15, 1) + ): + expected.append(("source", "stored_name")) + if has_name: + del module_globals["__name__"] + assert events == expected diff --git a/extra_tests/snippets/stdlib_weakref.py b/extra_tests/snippets/stdlib_weakref.py index 05d72275e9f..406649051b3 100644 --- a/extra_tests/snippets/stdlib_weakref.py +++ b/extra_tests/snippets/stdlib_weakref.py @@ -51,3 +51,7 @@ def __init__(self, h): del g assert_raises(ReferenceError, lambda: p.h) + +assert_raises(TypeError, ref, staticmethod(len)) +assert_raises(TypeError, ref, classmethod(len)) +assert_raises(TypeError, ref, property(len)) diff --git a/extra_tests/snippets/stdlib_winapi.py b/extra_tests/snippets/stdlib_winapi.py new file mode 100644 index 00000000000..31aca07626a --- /dev/null +++ b/extra_tests/snippets/stdlib_winapi.py @@ -0,0 +1,89 @@ +"""Check Windows event-log conversions without invoking host operations.""" + +import sys + +from testutils import assert_raises + +if sys.platform != "win32": + sys.exit(0) + +import _winapi + +# Every call fails before a host operation. ReportEvent overflow cases +# also retain an embedded NUL as an independent safety barrier. +assert _winapi.EVENTLOG_SUCCESS == 0 +assert _winapi.EVENTLOG_ERROR_TYPE == 1 +assert _winapi.EVENTLOG_WARNING_TYPE == 2 +assert _winapi.EVENTLOG_INFORMATION_TYPE == 4 +assert _winapi.EVENTLOG_AUDIT_SUCCESS == 8 +assert _winapi.EVENTLOG_AUDIT_FAILURE == 16 + +assert_raises(TypeError, _winapi.RegisterEventSource, 1, "source\0") +assert_raises(TypeError, _winapi.RegisterEventSource, None, 1) +assert_raises(TypeError, _winapi.RegisterEventSource, None, None) +assert_raises(ValueError, _winapi.RegisterEventSource, None, "source\0") +assert_raises(ValueError, _winapi.RegisterEventSource, "server\0", "source\0") +assert_raises(ValueError, _winapi.RegisterEventSource, "", "source\0") +assert_raises(TypeError, _winapi.DeregisterEventSource, "invalid handle") +assert_raises(TypeError, _winapi.DeregisterEventSource, None) +assert_raises(TypeError, _winapi.ReportEvent, "invalid handle", 0, 0, 0, "message\0") +assert_raises(ValueError, _winapi.ReportEvent, 0, 0, 0, 0, "message\0") +assert_raises(TypeError, _winapi.ReportEvent, 0, 0, 0, 0, None) +for index, bits in ((1, 16), (2, 16), (3, 32)): + for invalid, exception in ((-1, ValueError), (1 << bits, OverflowError)): + arguments = [0, 0, 0, 0, "message\0"] + arguments[index] = invalid + assert_raises(exception, _winapi.ReportEvent, *arguments) + arguments = [0, 0, 0, 0, "message\0"] + arguments[index] = "invalid integer" + assert_raises(TypeError, _winapi.ReportEvent, *arguments) + + +import subprocess + + +class PartialStartupInfo: + dwFlags = 0 + + def __getattr__(self, name): + raise ValueError(name) + + +for startup in (None, PartialStartupInfo()): + process, thread, _, _ = _winapi.CreateProcess( + sys.executable, + subprocess.list2cmdline([sys.executable, "-c", "pass"]), + None, + None, + False, + _winapi.CREATE_NO_WINDOW, + None, + None, + startup, + ) + try: + status = _winapi.WaitForSingleObject(process, 10000) + if status != _winapi.WAIT_OBJECT_0: + _winapi.TerminateProcess(process, 1) + _winapi.WaitForSingleObject(process, 10000) + assert status == _winapi.WAIT_OBJECT_0 + assert _winapi.GetExitCodeProcess(process) == 0 + finally: + _winapi.CloseHandle(thread) + _winapi.CloseHandle(process) + +startup = subprocess.STARTUPINFO() +startup.dwFlags = "invalid" +assert_raises( + TypeError, + _winapi.CreateProcess, + None, + "invalid\0", + None, + None, + False, + 0, + None, + None, + startup, +) diff --git a/extra_tests/snippets/stdlib_xml.py b/extra_tests/snippets/stdlib_xml.py index 34f1a726e4c..2540e5aa015 100644 --- a/extra_tests/snippets/stdlib_xml.py +++ b/extra_tests/snippets/stdlib_xml.py @@ -1,4 +1,6 @@ +import array import xml.sax +from xml.etree.ElementTree import Element from xml.parsers import expat from testutils import assert_raises @@ -66,3 +68,91 @@ def endElement(self, name): ("characters", "text"), ("end-cdata",), ] + +root = Element("root") +for value, type_name in ( + (None, "None"), + (1, "int"), + ("child", "str"), + (array.array("b"), "array.array"), + (type("A" * 60, (), {})(), "A" * 50), + (type("€" * 20, (), {})(), "€" * 16), +): + with assert_raises(TypeError) as caught: + root.remove(value) + assert str(caught.exception) == ( + "remove() argument must be xml.etree.ElementTree.Element, not " + type_name + ) + + +def test_element_frozen_attrib_identity_bounded(): + class Frozen(frozendict): + def __getitem__(self, key): + raise AssertionError("Element.get must use the stored entries") + + def keys(self): + raise AssertionError("Element.keys must use the stored entries") + + def items(self): + raise AssertionError("Element.items must use the stored entries") + + for mapping in (frozendict(), frozendict(a=1), Frozen(a=1)): + element = Element("root") + element.attrib = mapping + assert element.attrib is mapping + assert element.get("a", 7) == (1 if mapping else 7) + assert element.get("missing", 7) == 7 + assert element.keys() == (["a"] if mapping else []) + assert element.items() == ([("a", 1)] if mapping else []) + with assert_raises(AttributeError): + del element.attrib + assert element.attrib is mapping + element.clear() + assert type(element.attrib) is dict and element.attrib == {} + element.set("new", 2) + assert element.attrib == {"new": 2} + assert dict(mapping) == ({"a": 1} if mapping else {}) + + +def test_element_frozen_attrib_mutation_bounded(): + class Key: + def __hash__(self): + raise AssertionError("frozen assignment must fail before hashing") + + element = Element("root") + mapping = frozendict(a=1) + element.attrib = mapping + for key in ("a", "new", Key()): + with assert_raises(TypeError) as caught: + element.set(key, 2) + assert str(caught.exception) == ( + "frozendict object does not support item assignment" + ) + assert element.attrib is mapping and mapping == {"a": 1} + + +def test_element_frozen_attrib_copy_state_bounded(): + import copy + + for mapping in (frozendict(), frozendict(a=[1])): + element = Element("root") + element.attrib = mapping + shallow = copy.copy(element) + assert shallow is not element and shallow.attrib is mapping + deep = copy.deepcopy(element) + assert deep is not element + assert type(deep.attrib) is frozendict and deep.attrib == mapping + if mapping: + assert deep.attrib["a"] is not mapping["a"] + deep.attrib["a"].append(2) + assert mapping["a"] == [1] + state = element.__getstate__() + assert state["attrib"] is mapping + restored = Element("restored") + restored.__setstate__(state) + assert restored.attrib is mapping + + +test_element_frozen_attrib_identity_bounded() +test_element_frozen_attrib_mutation_bounded() +test_element_frozen_attrib_copy_state_bounded() diff --git a/extra_tests/snippets/stdlib_zlib.py b/extra_tests/snippets/stdlib_zlib.py index dfadf7eebdc..cd3f91b61d5 100644 --- a/extra_tests/snippets/stdlib_zlib.py +++ b/extra_tests/snippets/stdlib_zlib.py @@ -79,3 +79,45 @@ assert d.flush() == b"" assert d.unconsumed_tail == tail assert d.unused_data == b"NEXT" + tail + + +# Raw deflate has no trailer, so inflate can consume the last input byte and +# still hold output. decompress(b"", n) and flush() must return that output. +def drained_raw_deflate(): + c = zlib.compressobj(6, zlib.DEFLATED, -15) + raw = c.compress(b"x" * 1168) + c.flush() + d = zlib.decompressobj(-15) + out = d.decompress(raw, 100) + while d.unconsumed_tail: + out += d.decompress(d.unconsumed_tail, 100) + assert len(out) == 1100 + assert not d.eof + return d, out + + +d, out = drained_raw_deflate() +more = d.decompress(b"", 100) +assert len(more) == 68 +assert d.eof +assert d.flush() == b"" +assert out + more == b"x" * 1168 + +d, out = drained_raw_deflate() +rest = d.flush() +assert len(rest) == 68 +assert d.eof +assert out + rest == b"x" * 1168 + +# An empty input before any compressed data does not end the stream. +d = zlib.decompressobj() +assert d.decompress(b"") == b"" +assert not d.eof +assert d.flush() == b"" +assert not d.eof +assert d.decompress(zlib.compress(b"later input")) == b"later input" +assert d.eof + +# The one-shot decompress drains the same pending output with a small bufsize. +raw = zlib.compress(b"x" * 1168, 6, -15) +for bufsize in (1, 100): + assert zlib.decompress(raw, -15, bufsize) == b"x" * 1168 diff --git a/extra_tests/snippets/stdlib_zoneinfo.py b/extra_tests/snippets/stdlib_zoneinfo.py new file mode 100644 index 00000000000..c8004585f81 --- /dev/null +++ b/extra_tests/snippets/stdlib_zoneinfo.py @@ -0,0 +1,19 @@ +import io +import struct +from zoneinfo import ZoneInfo + +from testutils import assert_raises + +# Minimal TZif v3 data with no transitions and a POSIX rule in the footer. +header = (b"TZif3" + b"\0" * 15 + struct.pack(">6l", 0, 0, 0, 0, 0, 0)) * 2 + + +def zone_from_rule(rule): + return ZoneInfo.from_file(io.BytesIO(header + b"\n" + rule + b"\n")) + + +for rule in (b"<>5", b"AAA4<>,M3.2.0/2,M11.1.0/3"): + assert_raises(ValueError, zone_from_rule, rule) + +# Quoting still permits nonempty numeric abbreviations. +assert zone_from_rule(b"<+05>-5").tzname(None) == "+05" diff --git a/extra_tests/snippets/syntax_annotations.py b/extra_tests/snippets/syntax_annotations.py index 0f78bdc2be1..e83ec136879 100644 --- a/extra_tests/snippets/syntax_annotations.py +++ b/extra_tests/snippets/syntax_annotations.py @@ -1,5 +1,20 @@ from typing import get_type_hints +from testutils import assert_raises + +# Future f-string annotations canonicalize fields, not their literal padding. +for formatted, expected in ( + ("f'{ value }'", "f'{value}'"), + ("f'{ value = }'", "f' value = {value!r}'"), + ("f'{ value : >8}'", "f'{value: >8}'"), + ("f'{ {1, 2} }'", "f'{ {1, 2}}'"), +): + formatted_code = compile( + "from __future__ import annotations\nx: " + formatted, "", "exec" + ) + assert expected in formatted_code.co_consts + + def func(s: str) -> int: return int(s) @@ -8,3 +23,40 @@ def func(s: str) -> int: # The order of type hints matters for certain functions # e.g. functools.singledispatch assert list(hints.items()) == [('s', str), ('return', int)] + + +# Template format specs use canonical expression text inside future annotations. +for template, expected in ( + ("t'{value:04}'", "t'{value:04}'"), + ("t'{value:{(width)}}'", "t'{value:{width}}'"), + ("t'{(value):{(width)!r}}'", "t'{(value):{width!r}}'"), +): + annotation_code = compile( + "from __future__ import annotations\nx: " + template, "", "exec" + ) + assert expected in annotation_code.co_consts + + +# Conditional annotations belong to the inner class, not an enclosing scope. +for future in ("", "from __future__ import annotations\n"): + namespace = {} + exec( + future + + """ +class Outer: + class Inner: + if True: + included: int + if False: + omitted: str +""", + namespace, + ) + assert get_type_hints(namespace["Outer"].Inner) == {"included": int} + +with assert_raises(SyntaxError): + compile( + "class C:\n if True: x: int\n global __conditional_annotations__", + "", + "exec", + ) diff --git a/extra_tests/snippets/syntax_doc.py b/extra_tests/snippets/syntax_doc.py index bdfc1fe7788..37aebb43dbd 100644 --- a/extra_tests/snippets/syntax_doc.py +++ b/extra_tests/snippets/syntax_doc.py @@ -13,3 +13,77 @@ def f2(): """ assert f2.__doc__ == '\nx\n y\n' + + +# Regression test: a module docstring must be stored through module name +# resolution, so a nested `global __doc__` declaration makes the module body +# emit STORE_GLOBAL (writing module globals) instead of STORE_NAME (writing +# the provided locals mapping). Mirrors CPython codegen_nameop behavior. + +import dis + + +def opnames(code): + return [instr.opname for instr in dis.get_instructions(code)] + + +def run_split(src, optimize=0): + code = compile(src, "", "exec", optimize=optimize) + g, loc = {}, {} + exec(code, g, loc) + return code, g, loc + + +# A nested function declaring `global __doc__` makes the module docstring +# store target module globals. +src_global = '"module doc"\ndef f():\n global __doc__\n' +code, g, loc = run_split(src_global) +ops = opnames(code) +assert "STORE_GLOBAL" in ops, ops +assert "STORE_NAME" not in ops or "__doc__" not in [ + instr.argval for instr in dis.get_instructions(code) if instr.opname == "STORE_NAME" +], ops +assert g.get("__doc__") == "module doc", g +assert "__doc__" not in loc, loc + +# The declaration may be nested more than one scope deep. +src_deep = '"module doc"\ndef f():\n def g():\n global __doc__\n' +code, g, loc = run_split(src_deep) +assert "STORE_GLOBAL" in opnames(code), opnames(code) +assert g.get("__doc__") == "module doc", g +assert "__doc__" not in loc, loc + +# Control: without a nested global declaration the docstring stays a +# STORE_NAME and lands in the provided locals mapping. +src_plain = '"module doc"\nx = 1\n' +code, g, loc = run_split(src_plain) +doc_stores = [ + instr.opname + for instr in dis.get_instructions(code) + if instr.argval == "__doc__" and instr.opname.startswith("STORE_") +] +assert doc_stores == ["STORE_NAME"], doc_stores +assert loc.get("__doc__") == "module doc", loc +assert "__doc__" not in g, g + +# optimize=1 keeps the docstring and the same global resolution. +code, g, loc = run_split(src_global, optimize=1) +assert "STORE_GLOBAL" in opnames(code), opnames(code) +assert g.get("__doc__") == "module doc", g + +# optimize=2 strips the docstring entirely: no __doc__ store in either dict. +code, g, loc = run_split(src_global, optimize=2) +assert not any( + instr.argval == "__doc__" and instr.opname.startswith("STORE_") + for instr in dis.get_instructions(code) +), opnames(code) +assert "__doc__" not in g and "__doc__" not in loc, (g, loc) + +# A class docstring still belongs to the class namespace even when a nested +# scope declares `global __doc__`. +src_class = '"module doc"\ndef f():\n global __doc__\nclass C:\n "class doc"\n' +g, loc = {}, {} +exec(compile(src_class, "", "exec"), g, loc) +assert g.get("__doc__") == "module doc", g +assert loc["C"].__doc__ == "class doc", loc["C"].__doc__ +assert "__doc__" not in loc, loc diff --git a/extra_tests/snippets/syntax_function.py b/extra_tests/snippets/syntax_function.py index 071cc9beff2..4575678006e 100644 --- a/extra_tests/snippets/syntax_function.py +++ b/extra_tests/snippets/syntax_function.py @@ -71,3 +71,34 @@ def kwargs_are_variable(x=[]): assert [1] == kwargs_are_variable() assert [1, 1] == kwargs_are_variable() + + +# Direct constructor calls must retain original argument owners during errors. +# Eager conversion of a later argument must not finalize earlier arguments +# before formatting its error. Do not assert the later cleanup order: that +# order differs between CPython versions. +def check_function_constructor_error_owners(): + import types + + class BadGlobals: + pass + + class CodeConstant: + def __del__(self): + BadGlobals.__name__ = "FinalizedGlobals" + + try: + types.FunctionType.__new__( + types.FunctionType, + (lambda: None).__code__.replace(co_consts=(CodeConstant(),)), + BadGlobals(), + ) + except TypeError as exc: + assert str(exc) == ( + "function() argument 'globals' must be dict, not BadGlobals" + ), str(exc) + else: + assert False, "invalid globals accepted" + + +check_function_constructor_error_owners() diff --git a/extra_tests/snippets/syntax_function_args.py b/extra_tests/snippets/syntax_function_args.py index eb4f94b8a36..6fd39c951e7 100644 --- a/extra_tests/snippets/syntax_function_args.py +++ b/extra_tests/snippets/syntax_function_args.py @@ -1,6 +1,90 @@ from testutils import assert_raises +def error(call, expected): + try: + call() + except TypeError as exc: + assert str(exc) == expected, (str(exc), expected) + else: + raise AssertionError("expected TypeError") + + +error(lambda: id(obj=1), "id() takes no keyword arguments") +error(lambda: id(**{"obj": 1}), "id() takes no keyword arguments") +error(lambda: id(1, 2, obj=1), "id() takes no keyword arguments") +error(lambda: list.append(x=1), "unbound method list.append() needs an argument") +error(lambda: list.append(**{"x": 1}), "unbound method list.append() needs an argument") +error( + lambda: list.append(1, x=1), + "descriptor 'append' for 'list' objects doesn't apply to a 'int' object", +) +error(lambda: list.append([], x=1), "list.append() takes no keyword arguments") +error(lambda: list.append([], **{"x": 1}), "list.append() takes no keyword arguments") +error(lambda: [].append(x=1), "list.append() takes no keyword arguments") +error(lambda: [].clear(1, x=1), "list.clear() takes no keyword arguments") + + +class Index: + def __index__(self): + raise AssertionError("conversion ran before keyword check") + + +error(lambda: bin(Index(), x=1), "bin() takes no keyword arguments") +assert id(1, **{}) == id(1) +assert round(1.25, ndigits=1) == 1.2 +assert pow(2, exp=3) == 8 +assert sorted([2, 1], reverse=True) == [2, 1] +assert sum([1, 2], start=4) == 7 +values = [] +list.append(values, 1) +values.append(2) +assert values == [1, 2] +list.clear(values) +assert values == [] + +# Keyword metadata must forward raw arguments without changing body validation. +for choose in (min, max): + assert choose([], default=42) == 42 + assert choose([1, 2], key=lambda value: -value) == (2 if choose is min else 1) + try: + choose(bogus=1) + except TypeError as exc: + assert str(exc) == f"{choose.__name__} expected at least 1 argument, got 0" + else: + raise AssertionError("missing positional argument was accepted") + try: + choose(1, 2, default=0) + except TypeError as exc: + assert str(exc) == ( + f"Cannot specify a default for {choose.__name__}() " + "with multiple positional arguments" + ) + else: + raise AssertionError("default with multiple arguments was accepted") + +# Named fields in argument structs must override positional-only arguments. +assert eval("value", globals={"value": 42}) == 42 +namespace = {} +exec("value = 42", globals=namespace) +assert namespace["value"] == 42 +assert compile(source="42", filename="", mode="eval") +assert __import__(name="sys").__name__ == "sys" + +from io import StringIO + +output = StringIO() +print(1, 2, sep=":", end="!", file=output) +assert output.getvalue() == "1:2!" + +# Methods using a keyword-only argument struct must keep accepting keywords. +values = [1, 2] +values.sort(reverse=True) +assert values == [2, 1] + +# Definitions built without the macros infer their calling convention too. +assert int.__new__(int, "11", base=2) == 3 + def sum(x, y): return x+y @@ -129,3 +213,50 @@ def f(a, b, /, c, d, *, e, f): f(1,2,3,4,5,f=6) with assert_raises(TypeError): f(1,2,3,4,5,6) + + +def test_keyword_dict_stored_hashes(): + class Keyword(str): + def __hash__(self): + assert not getattr(self, "hashed", False), "keyword was rehashed" + self.hashed = True + return str.__hash__(self) + + def accept(*, value): + return value + + source = {Keyword("value"): 42} + assert accept(**source) == 42 + with assert_raises(TypeError) as raised: + accept(value=1, **source) + assert str(raised.exception).endswith( + "got multiple values for keyword argument 'value'" + ) + + class NonString: + def __hash__(self): + assert not getattr(self, "hashed", False), "non-string key was rehashed" + self.hashed = True + return 0 + + source = {NonString(): 42} + with assert_raises(TypeError) as raised: + accept(**source) + assert str(raised.exception) == "keywords must be strings" + + failure = RuntimeError("keyword comparison failed") + + class BadEquality(str): + __hash__ = str.__hash__ + + def __eq__(self, other): + raise failure + + left = {BadEquality("value"): 1} + right = {BadEquality("value"): 2} + with assert_raises(RuntimeError) as raised: + accept(**left, **right) + assert raised.exception is failure + + +test_keyword_dict_stored_hashes() diff --git a/extra_tests/snippets/syntax_invalid.py b/extra_tests/snippets/syntax_invalid.py index 37a3805a295..00acf6cfb16 100644 --- a/extra_tests/snippets/syntax_invalid.py +++ b/extra_tests/snippets/syntax_invalid.py @@ -77,3 +77,46 @@ def valid_func(): from __future__ import print_function """ compile(src, 'test.py', 'exec') + + +# CPython reports the unparenthesized `except ... as` error with a range that starts at the +# first exception type and stops just before the `:` closing the clause. `end_offset` is an +# exclusive 1-based *character* column, so that end lands on the column the `:` sits on. +# +# The cases below pin the parts that are easy to get wrong: the column counts characters +# rather than UTF-8 bytes, and an explicit line join may sit anywhere between the exception +# types and the `:`. Values verified against CPython 3.14. +except_as_ranges = [ + # (clause, (lineno, offset), (end_lineno, end_offset)) + ("except A, B as e:", (3, 8), (3, 17)), + ("except A, B as e :", (3, 8), (3, 18)), + ("except A, B as e :", (3, 8), (3, 20)), + ("except A, B as e\t:", (3, 8), (3, 18)), + ("except A, B, C as blech:", (3, 8), (3, 24)), + ("except* A, B, C as e:", (3, 9), (3, 21)), + # A non-ASCII name must not push the column right by its extra UTF-8 bytes. + ("except Ä, B as e:", (3, 8), (3, 17)), + ("except 사과, B as e:", (3, 8), (3, 18)), + ("except A, B as 오:", (3, 8), (3, 17)), + # An explicit line join may precede or follow `as`, or close the clause on its own line. + ("except A, B as exc\\\n :", (3, 8), (4, 5)), + ("except A, B \\\nas exc:", (3, 8), (4, 7)), + ("except A, \\\nB as exc:", (3, 8), (4, 9)), + ("except A, B as \\\nexc:", (3, 8), (4, 4)), +] + +for clause, start, end in except_as_ranges: + src = "try:\n pass\n%s\n pass\n" % clause + with assert_raises(SyntaxError) as ae: + compile(src, "test.py", "exec") + exc = ae.exception + assert exc.msg == "multiple exception types must be parenthesized when using 'as'", ( + clause, + exc.msg, + ) + assert (exc.lineno, exc.offset) == start, (clause, (exc.lineno, exc.offset), start) + assert (exc.end_lineno, exc.end_offset) == end, ( + clause, + (exc.end_lineno, exc.end_offset), + end, + ) diff --git a/extra_tests/snippets/vm_argument_errors.py b/extra_tests/snippets/vm_argument_errors.py index 0fe6ff7fdce..6c3e973895a 100644 --- a/extra_tests/snippets/vm_argument_errors.py +++ b/extra_tests/snippets/vm_argument_errors.py @@ -2,15 +2,31 @@ # the arguments the caller wrote, and agrees with itself about singular and # plural. Every message here is the one CPython raises, so this file is run # against both. +import _functools import array +import codecs import collections import csv +import datetime +import hashlib import itertools +import math import operator +import sys import typing import weakref -from testutils import assert_raises +from testutils import TestFailingIter, assert_raises + + +class FailingIndex: + def __index__(self): + raise RuntimeError + + +class FailingBool: + def __bool__(self): + raise RuntimeError def check(exc_type, message, fn, *args, **kwargs): @@ -150,6 +166,272 @@ def test_a_keyword_check_of_its_own_says_the_same_thing(): ) +def test_grouper_arguments(): + G = type(next(itertools.groupby("a"))[1]) + check(TypeError, "_grouper expected 2 arguments, got 0", G) + check(TypeError, "_grouper expected 2 arguments, got 1", G, 1) + check(TypeError, "_grouper expected 2 arguments, got 3", G, 1, 2, 3) + check(TypeError, "_grouper() takes no keyword arguments", G, x=1) + check( + TypeError, + "_grouper() argument 1 must be itertools.groupby, not int", + G, + 1, + "a", + ) + check( + TypeError, + "_grouper() argument 1 must be itertools.groupby, not None", + G, + None, + "a", + ) + g = itertools.groupby("aab") + next(g) + assert list(G(g, "a")) == ["a", "a"] + + class GroupBy(itertools.groupby): + pass + + g = GroupBy("aab") + next(g) + assert list(G(g, "a")) == ["a", "a"] + + +def test_bad_argument_type(): + check(TypeError, "lookup() argument must be str, not int", codecs.lookup, 1) + G = type(next(itertools.groupby("a"))[1]) + check( + TypeError, + "_grouper() argument 1 must be itertools.groupby, not int", + G, + 1, + "a", + ) + check(TypeError, "lookup() argument must be str, not None", codecs.lookup, None) + check( + TypeError, + "tobytes() argument 'order' must be str or None, not int", + memoryview(b"a").tobytes, + 1, + ) + + +def test_too_many_arguments_are_counted_before_any_is_converted(): + class FailingIndex: + def __index__(self): + raise RuntimeError + + check( + TypeError, + "filter expected 2 arguments, got 3", + filter, + None, + TestFailingIter(), + 0, + ) + with assert_raises(TypeError): + hex(FailingIndex(), 1) + + +def test_a_missing_argument_is_reported_before_any_is_converted(): + class FailingIndex: + def __index__(self): + raise RuntimeError + + check( + TypeError, + "compress() missing required argument 'selectors' (pos 2)", + itertools.compress, + TestFailingIter(), + ) + check( + TypeError, + "compress() missing required argument 'selectors' (pos 2)", + itertools.compress, + data=TestFailingIter(), + ) + check( + TypeError, + "compress() missing required argument 'selectors' (pos 2)", + itertools.compress, + TestFailingIter(), + sel=1, + ) + check( + TypeError, + "date() missing required argument 'month' (pos 2)", + datetime.date, + FailingIndex(), + ) + check( + TypeError, + "comb expected 2 arguments, got 1", + math.comb, + FailingIndex(), + ) + check( + TypeError, + "insert expected 2 arguments, got 1", + [].insert, + FailingIndex(), + ) + + +def test_required_keyword_only_is_reported_before_conversion(): + # Modules/clinic/_hashopenssl.c.h + check( + TypeError, + "scrypt() missing required argument 'salt' (pos 2)", + hashlib.scrypt, + FailingIndex(), + ) + + +def test_clinic_checks_all_arguments_before_conversion(): + class FailingFloat: + def __float__(self): + raise RuntimeError + + check( + TypeError, + "isclose() missing required argument 'b' (pos 2)", + math.isclose, + FailingFloat(), + a=1, + ) + check( + TypeError, + "isclose() got an unexpected keyword argument 'unexpected'", + math.isclose, + FailingFloat(), + 1, + unexpected=1, + ) + check( + TypeError, + "argument for isclose() given by name ('a') and position (1)", + math.isclose, + FailingFloat(), + 2, + a=1, + bogus=1, + ) + check( + TypeError, + "compress() takes at most 2 arguments (3 given)", + itertools.compress, + TestFailingIter(), + [], + unexpected=1, + ) + check( + TypeError, + "sort() got an unexpected keyword argument 'unexpected'", + [].sort, + reverse=FailingBool(), + unexpected=1, + ) + + +def test_legacy_parsers_convert_before_a_missing_argument(): + def f(): + pass + + with assert_raises(RuntimeError): + _functools._lru_cache_wrapper(f, 1, FailingBool()) + + try: + import _posixshmem + except ImportError: + pass + else: + try: + _posixshmem.shm_open(1) + except TypeError as e: + message = str(e) + assert "missing required argument" not in message, message + else: + raise AssertionError("shm_open(1) did not raise TypeError") + + try: + _posixshmem.shm_open(1, 2, path="x") + except TypeError as e: + message = str(e) + assert "given by name" not in message, message + else: + raise AssertionError("shm_open(1, 2, path='x') did not raise TypeError") + + assert ( + _posixshmem.shm_open.__text_signature__ + == "($module, /, path, flags, mode=511)" + ) + + try: + import mmap + except ImportError: + pass + else: + try: + mmap.mmap("x") + except TypeError as e: + message = str(e) + assert "missing required argument" not in message, message + else: + raise AssertionError("mmap.mmap('x') did not raise TypeError") + + import _json + + with assert_raises(RuntimeError): + _json.make_encoder(None, None, None, None, ",", ",", FailingBool()) + + +def test_custom_parsers_preserve_their_conversion_boundaries(): + # The reader starts iteration before its separate dialect parser runs. + with assert_raises(RuntimeError): + csv.reader(TestFailingIter(), "excel", dialect="excel") + with assert_raises(RuntimeError): + csv.reader(TestFailingIter(), unexpected=1) + check( + TypeError, + "argument for function given by name ('dialect') and position (1)", + csv.reader, + [], + "excel", + dialect="excel", + ) + + try: + import _thread + except ImportError: + pass + else: + if "_thread" in sys.builtin_module_names: + # This legacy parser converts daemon before rejecting unknown names. + with assert_raises(RuntimeError): + _thread.start_joinable_thread(None, daemon=FailingBool(), unexpected=1) + else: + # The no-thread fallback is a Python function, not a native parser. + check( + TypeError, + "start_joinable_thread() got an unexpected keyword argument 'unexpected'", + _thread.start_joinable_thread, + None, + daemon=FailingBool(), + unexpected=1, + ) + + # Native dispatch must allow the custom parser to choose its diagnostic. + check( + TypeError, + "__set_name__() takes no keyword arguments", + property().__set_name__, + object, + "name", + unexpected=1, + ) + + test_the_message_names_the_function() test_a_method_does_not_count_its_instance() test_one_argument_is_singular() @@ -158,3 +440,11 @@ def test_a_keyword_check_of_its_own_says_the_same_thing(): test_a_type_is_named_by_the_type_it_builds() test_a_slot_that_counts_its_own_arguments_says_the_same_thing() test_a_keyword_check_of_its_own_says_the_same_thing() +test_grouper_arguments() +test_bad_argument_type() +test_too_many_arguments_are_counted_before_any_is_converted() +test_a_missing_argument_is_reported_before_any_is_converted() +test_required_keyword_only_is_reported_before_conversion() +test_clinic_checks_all_arguments_before_conversion() +test_legacy_parsers_convert_before_a_missing_argument() +test_custom_parsers_preserve_their_conversion_boundaries() diff --git a/extra_tests/snippets/vm_frame_locals.py b/extra_tests/snippets/vm_frame_locals.py index 608167c2a17..4313b07dbda 100644 --- a/extra_tests/snippets/vm_frame_locals.py +++ b/extra_tests/snippets/vm_frame_locals.py @@ -230,6 +230,33 @@ def frame_with_overwritten_fast_local(): frame.clear() self.assertEqual(len(events), 1) + def test_closed_coroutine_state_is_visible_to_frame_local_finalizers(self): + events = [] + + class ReentrantFinalizer: + def __del__(self): + events.append(getattr(owner, state_attribute)) + + async def coroutine(value): + return value + + async def async_generator(value): + yield value + + for factory, state_attribute, closed in ( + (coroutine, "cr_state", "CORO_CLOSED"), + (async_generator, "ag_state", "AGEN_CLOSED"), + ): + with self.subTest(state_attribute=state_attribute): + events.clear() + owner = factory(ReentrantFinalizer()) + if state_attribute == "cr_state": + owner.close() + else: + with self.assertRaises(StopIteration): + owner.aclose().send(None) + self.assertEqual(events, [closed]) + def test_unoptimized_frame_locals_are_readable_from_another_thread(self): ready = threading.Event() release = threading.Event() diff --git a/extra_tests/snippets/vm_specialization.py b/extra_tests/snippets/vm_specialization.py index b1d201e8ac1..99b7af51780 100644 --- a/extra_tests/snippets/vm_specialization.py +++ b/extra_tests/snippets/vm_specialization.py @@ -342,3 +342,50 @@ def read(): module_attribute_custom_dict_key() + + +## STORE_SUBSCR_LIST_INT: the replaced element's finalizer can read the list + + +def store_subscr_list_int_finalizer_reads_list(): + target = [None] + seen = [] + + class Item: + def __init__(self, value): + self.value = value + + def __del__(self): + seen.append((self.value, len(target), target[0] is self)) + + def store(value): + target[0] = value + + for i in range(300): + store(Item(i)) + assert any( + op.opname == "STORE_SUBSCR_LIST_INT" + for op in dis.get_instructions(store, adaptive=True) + ) + store(None) + assert seen == [(i, 1, False) for i in range(300)] + + +store_subscr_list_int_finalizer_reads_list() + + +def store_attr_uses_setter_without_getter(): + class IntegerField: + def __set__(self, obj, value): + obj.__dict__["value"] = int(value) + + class Model: + value = IntegerField() + + obj = Model() + for _ in range(300): + obj.value = "42" + assert obj.value == 42 + + +store_attr_uses_setter_without_getter() diff --git a/extra_tests/test_custom_text_test_runner.py b/extra_tests/test_custom_text_test_runner.py new file mode 100644 index 00000000000..087921c23e1 --- /dev/null +++ b/extra_tests/test_custom_text_test_runner.py @@ -0,0 +1,472 @@ +"""Infrastructure regression tests; the nested cases deliberately fail.""" + +import io +import json +import os +import pathlib +import sys +import tempfile +import types +import unittest +from unittest import mock + +from _colorize import decolor +from custom_text_test_runner import CustomTextTestRunner + + +class RunnerResultTests(unittest.TestCase): + def test_json_tracebacks_are_plain_under_forced_colors(self): + class Cases(unittest.TestCase): + def test_failure(self): + self.fail("ordinary failure") + + def test_error(self): + raise ValueError("ordinary error") + + def test_subtests(self): + with self.subTest(kind="failure"): + self.fail("subtest failure") + with self.subTest(kind="error"): + raise ValueError("subtest error") + + for color_env in ({}, {"FORCE_COLOR": "1"}, {"PYTHON_COLORS": "1"}): + with self.subTest(color_env=color_env), mock.patch.dict(os.environ): + for name in ("FORCE_COLOR", "PYTHON_COLORS", "NO_COLOR"): + os.environ.pop(name, None) + os.environ.update(color_env) + with tempfile.TemporaryDirectory() as temp: + path = pathlib.Path(temp) / "results.json" + log = io.StringIO() + result = CustomTextTestRunner( + stream=log, verbosity=2, results_file_path=str(path) + ).run(unittest.defaultTestLoader.loadTestsFromTestCase(Cases)) + data = json.loads(path.read_text()) + cases = { + case["method"]: case + for suite in data["suites"].values() + for case in suite["cases"].values() + } + subtests = cases["test_subtests"]["subtests"] + tracebacks = [ + ( + cases["test_failure"]["failures"], + "AssertionError: ordinary failure", + ), + (cases["test_error"]["errors"], "ValueError: ordinary error"), + ( + cases["test_subtests"]["failures"], + "AssertionError: subtest failure", + ), + (cases["test_subtests"]["errors"], "ValueError: subtest error"), + (subtests[0]["traceback"], "AssertionError: subtest failure"), + (subtests[1]["traceback"], "ValueError: subtest error"), + ] + for text, message in tracebacks: + self.assertNotIn("\x1b[", text) + self.assertIn(message, text) + self.assertIn(message, log.getvalue()) + self.assertEqual(result.testsRun, 3) + self.assertEqual(len(result.failures), 2) + self.assertEqual(len(result.errors), 2) + self.assertFalse(result.wasSuccessful()) + self.assertEqual(data["num_failed"], 3) + self.assertEqual(data["num_passed"], 0) + self.assertEqual(data["num_skipped"], 0) + self.assertEqual(data["num_expected_failures"], 0) + self.assertEqual(cases["test_failure"]["result"], "failed") + self.assertEqual(cases["test_error"]["result"], "error") + self.assertEqual(cases["test_subtests"]["result"], "error") + self.assertEqual( + [sub["result"] for sub in subtests], ["failed", "error"] + ) + + def test_records_parent_and_subtest_outcomes(self): + class Cases(unittest.TestCase): + def test_pass(self): + for x in range(2): + with self.subTest(x=x): + self.assertTrue(True) + + def test_fail_error(self): + with self.subTest(x="fail"): + self.fail("subfailure") + with self.subTest(x="error"): + raise ValueError("suberror") + + def test_skip(self): + with self.subTest(x="skip"): + self.skipTest("subskip") + + def test_parent_error(self): + with self.subTest(x="fail"): + self.fail("before parent") + raise RuntimeError("parent error") + + def test_parent_failure(self): + with self.subTest(x="error"): + raise ValueError("before parent") + self.fail("parent failure") + + def test_nested(self): + with self.subTest(outer=1): + with self.subTest(inner=2): + self.assertTrue(True) + + def test_plain(self): + pass + + @unittest.expectedFailure + def test_unexpected(self): + with self.subTest(x=1): + pass + + @unittest.expectedFailure + def test_expected(self): + with self.subTest(x=1): + self.fail("expected") + + def test_skip_after_failure(self): + with self.subTest(x=1): + self.fail("before skip") + self.skipTest("parent skip") + + def test_cleanup_error(self): + def cleanup(): + raise ValueError("cleanup") + + self.addCleanup(cleanup) + self.fail("parent") + + class Other(unittest.TestCase): + def test_other(self): + pass + + names = [ + "test_pass", + "test_fail_error", + "test_skip", + "test_parent_error", + "test_parent_failure", + "test_nested", + "test_plain", + "test_plain", + "test_unexpected", + "test_expected", + "test_skip_after_failure", + "test_cleanup_error", + ] + + def suite(): + return unittest.TestSuite( + [Cases(names[0]), Other("test_other"), *(Cases(n) for n in names[1:])] + ) + + standard = unittest.TestResult() + suite().run(standard) + with tempfile.TemporaryDirectory() as temp: + log = io.StringIO() + path = pathlib.Path(temp) / "results.json" + actual = CustomTextTestRunner( + stream=log, verbosity=2, results_file_path=str(path) + ).run(suite()) + for attr in ( + "testsRun", + "failures", + "errors", + "skipped", + "expectedFailures", + "unexpectedSuccesses", + ): + a, b = getattr(actual, attr), getattr(standard, attr) + assert (a if isinstance(a, int) else len(a)) == ( + b if isinstance(b, int) else len(b) + ), attr + data = json.loads(path.read_text()) + cases = [c for s in data["suites"].values() for c in s["cases"].values()] + assert len(cases) == len(names) + 1, (len(cases), len(names)) + assert all(c["result"] is not None for c in cases) + assert sum(c["result"] == "passed" for c in cases) == 5, cases + assert data["num_passed"] == 5, data + assert data["num_failed"] == 6, data + assert data["num_skipped"] == 1, data + subs = [sub for c in cases for sub in c["subtests"]] + assert len(subs) == 11, subs + for t, e in actual.errors + actual.failures: + assert t.id() in log.getvalue(), t.id() + assert e.strip() in log.getvalue(), e + assert sum(c["id"].endswith(".test_plain") for c in cases) == 2 + assert data["num_expected_failures"] == 1 + + def test_fixture_outcomes_without_start_test(self): + for boundary in ( + "setUpModule", + "tearDownModule", + "setUpClass", + "tearDownClass", + "class_cleanup", + "module_cleanup", + ): + for skipped in (False, True): + with ( + self.subTest(boundary=boundary, skipped=skipped), + tempfile.TemporaryDirectory() as temp, + ): + module = types.ModuleType("runner_fixture_probe") + + def problem(): + if skipped: + raise unittest.SkipTest("fixture skip") + raise ValueError("fixture error") + + class Fixture(unittest.TestCase): + def test_body(self): + pass + + Fixture.__module__ = module.__name__ + if boundary in ("setUpModule", "tearDownModule"): + setattr(module, boundary, problem) + elif boundary == "module_cleanup": + module.setUpModule = lambda: unittest.addModuleCleanup(problem) + elif boundary == "class_cleanup": + + @classmethod + def setup(cls): + cls.addClassCleanup(problem) + + Fixture.setUpClass = setup + else: + setattr(Fixture, boundary, classmethod(lambda cls: problem())) + sys.modules[module.__name__] = module + try: + expected = unittest.TestResult() + unittest.TestSuite([Fixture("test_body")]).run(expected) + path = pathlib.Path(temp) / "results.json" + actual = CustomTextTestRunner( + stream=io.StringIO(), + verbosity=2, + results_file_path=str(path), + ).run(unittest.TestSuite([Fixture("test_body")])) + self.assertEqual(actual.testsRun, expected.testsRun) + self.assertEqual(len(actual.errors), len(expected.errors)) + self.assertEqual(len(actual.skipped), len(expected.skipped)) + cases = [ + case + for suite in json.loads(path.read_text())["suites"].values() + for case in suite["cases"].values() + ] + fixtures = [ + case + for case in cases + if case["id"] != Fixture("test_body").id() + ] + self.assertEqual(len(fixtures), 1) + self.assertIn( + { + "class_cleanup": "tearDownClass", + "module_cleanup": "tearDownModule", + }.get(boundary, boundary), + fixtures[0]["id"], + ) + self.assertEqual( + fixtures[0]["result"], "skipped" if skipped else "error" + ) + finally: + del sys.modules[module.__name__] + + def test_unprintable_subtest_parameters(self): + self.addCleanup(sys.set_int_max_str_digits, sys.get_int_max_str_digits()) + sys.set_int_max_str_digits(4300) + + class BadRepr: + def __repr__(self): + raise ValueError("unprintable parameter") + + class Cases(unittest.TestCase): + def test_body(self): + for value in (10**5000, BadRepr()): + for outcome in ("passed", "failed", "error", "skipped"): + with self.subTest(value=value, outcome=outcome): + if outcome == "failed": + self.fail("original failure") + if outcome == "error": + raise RuntimeError("original error") + if outcome == "skipped": + self.skipTest("original skip") + + with tempfile.TemporaryDirectory() as temp: + path = pathlib.Path(temp) / "results.json" + log = io.StringIO() + result = CustomTextTestRunner( + stream=log, verbosity=2, results_file_path=str(path) + ).run(unittest.TestSuite([Cases("test_body")])) + self.assertEqual( + ( + result.testsRun, + len(result.failures), + len(result.errors), + len(result.skipped), + ), + (1, 2, 2, 2), + ) + data = json.loads(path.read_text()) + case = next(iter(next(iter(data["suites"].values()))["cases"].values())) + self.assertEqual( + [s["result"] for s in case["subtests"]], + ["passed", "failed", "error", "skipped"] * 2, + ) + self.assertTrue( + all( + s["id"].startswith(Cases("test_body").id()) + and "id unavailable: ValueError" in s["id"] + for s in case["subtests"] + ) + ) + self.assertIn("RuntimeError: original error", decolor(log.getvalue())) + self.assertIn("AssertionError: original failure", decolor(log.getvalue())) + + def test_subtests_keep_outcomes_when_setup_shadows_id(self): + class Cases(unittest.TestCase): + def setUp(self): + self.id = 7 + + def test_mix(self): + outcomes = ("passed", "passed", "failed", "error", "skipped") + for outcome in outcomes: + with self.subTest("ordinary", outcome=outcome): + if outcome == "failed": + self.fail("original assertion") + if outcome == "error": + raise ValueError("original exception") + if outcome == "skipped": + self.skipTest("original skip") + + def test_skip_only(self): + with self.subTest(number=1): + self.skipTest("only skip") + + loader = unittest.TestLoader() + expected = unittest.TestResult() + loader.loadTestsFromTestCase(Cases).run(expected) + with tempfile.TemporaryDirectory() as temp: + path = pathlib.Path(temp) / "results.json" + log = io.StringIO() + result = CustomTextTestRunner( + stream=log, verbosity=2, results_file_path=str(path) + ).run(loader.loadTestsFromTestCase(Cases)) + self.assertEqual(result.testsRun, expected.testsRun) + self.assertEqual( + [len(getattr(result, k)) for k in ("failures", "errors", "skipped")], + [len(getattr(expected, k)) for k in ("failures", "errors", "skipped")], + ) + data = json.loads(path.read_text()) + cases = { + case["method"]: case + for suite in data["suites"].values() + for case in suite["cases"].values() + } + case = cases["test_mix"] + self.assertEqual(case["id"], Cases("test_mix").id()) + self.assertEqual(case["result"], "error") + records = case["subtests"] + self.assertEqual( + [record["result"] for record in records], + ["passed", "passed", "failed", "error", "skipped"], + ) + self.assertEqual(records[0]["id"], records[1]["id"]) + self.assertIn("[ordinary] (outcome='passed')", records[0]["id"]) + self.assertIn(records[2]["id"], log.getvalue()) + self.assertIn("AssertionError: original assertion", records[2]["traceback"]) + self.assertIn("ValueError: original exception", records[3]["traceback"]) + self.assertEqual(records[4]["reason"], "original skip") + self.assertEqual(cases["test_skip_only"]["result"], "skipped") + self.assertEqual((data["num_failed"], data["num_skipped"]), (1, 1)) + + def test_case_id_falls_back_only_for_invalid_labels(self): + class Case(unittest.TestCase): + def test_body(self): + with self.subTest(case="first"): + pass + + class Shadowed(Case): + id = 7 + + class Throwing(Case): + def id(self): + raise RuntimeError("optional metadata") + + class NonString(Case): + def id(self): + return None + + id_calls = [] + + class Qualified(Case): + def id(self): + id_calls.append(self) + return "custom.qualified" + + types = (Shadowed, Throwing, NonString, Qualified) + suite = unittest.TestSuite(cls("test_body") for cls in types) + with tempfile.TemporaryDirectory() as temp: + path = pathlib.Path(temp) / "results.json" + result = CustomTextTestRunner( + stream=io.StringIO(), results_file_path=str(path) + ).run(suite) + data = json.loads(path.read_text()) + cases = [ + case + for group in data["suites"].values() + for case in group["cases"].values() + ] + expected_ids = [ + *(unittest.TestCase.id(cls("test_body")) for cls in types[:-1]), + "custom.qualified", + ] + self.assertEqual(result.testsRun, 4) + self.assertEqual(data["num_passed"], 4) + self.assertEqual(len(id_calls), 1) + self.assertEqual([case["id"] for case in cases], expected_ids) + self.assertEqual( + [case["subtests"][0]["id"] for case in cases], + [label + " (case='first')" for label in expected_ids], + ) + + def test_discovery_preserves_qualified_names_and_import_errors(self): + from jsontests import loadTestsOrSkip + + loader = unittest.TestLoader() + with mock.patch.object(loader, "loadTestsFromName") as load: + for name in ("test_example", "test.test_package.test_example"): + loadTestsOrSkip(loader, name) + self.assertEqual( + load.call_args_list, + [ + mock.call("test.test_example"), + mock.call("test.test_package.test_example"), + ], + ) + result = unittest.TestResult() + loadTestsOrSkip(loader, "test.__runner_missing_module__").run(result) + self.assertEqual(len(result.errors), 1) + self.assertIn("__runner_missing_module__", result.errors[0][1]) + self.assertNotIn("test.test.__runner_missing_module__", result.errors[0][1]) + + def test_interruption_keeps_original_exception(self): + class Interrupted(unittest.TestCase): + def test_body(self): + raise KeyboardInterrupt("owned mock interruption") + + with tempfile.TemporaryDirectory() as temp: + path = pathlib.Path(temp) / "results.json" + with self.assertRaisesRegex(KeyboardInterrupt, "owned mock interruption"): + CustomTextTestRunner( + stream=io.StringIO(), results_file_path=str(path) + ).run(unittest.TestSuite([Interrupted("test_body")])) + data = json.loads(path.read_text()) + self.assertEqual( + data["num_passed"] + data["num_failed"] + data["num_skipped"], 0 + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/extra_tests/test_snippet_selection.py b/extra_tests/test_snippet_selection.py new file mode 100644 index 00000000000..6bc2cada142 --- /dev/null +++ b/extra_tests/test_snippet_selection.py @@ -0,0 +1,33 @@ +import unittest +from unittest.mock import patch + +import test_snippets + + +class SnippetSelectionTests(unittest.TestCase): + def make_test(self, method, name): + class Tests: + pass + + test_snippets.create_test_function(Tests, f"snippets/{name}.py", method, None) + return getattr(Tests, f"test_{method}_{name}") + + def test_exclusion_matches_the_whole_snippet_name(self): + with patch.object(test_snippets, "RUSTPYTHON_SNIPPET_EXCLUDE", {"builtin_str"}): + excluded = self.make_test("rustpython", "builtin_str") + sibling = self.make_test("rustpython", "builtin_str_add") + + self.assertTrue(excluded.__unittest_skip__) + self.assertFalse(getattr(sibling, "__unittest_skip__", False)) + + def test_exclusion_does_not_change_cpython_reference_tests(self): + with patch.object(test_snippets, "RUSTPYTHON_SNIPPET_EXCLUDE", {"builtin_str"}): + reference = self.make_test("cpython", "builtin_str") + + self.assertFalse(getattr(reference, "__unittest_skip__", False)) + + def test_no_exclusions_keeps_the_native_default(self): + with patch.object(test_snippets, "RUSTPYTHON_SNIPPET_EXCLUDE", set()): + test = self.make_test("rustpython", "builtin_str") + + self.assertFalse(getattr(test, "__unittest_skip__", False)) diff --git a/extra_tests/test_snippets.py b/extra_tests/test_snippets.py index d58b86f66b2..dd828635991 100644 --- a/extra_tests/test_snippets.py +++ b/extra_tests/test_snippets.py @@ -51,6 +51,9 @@ def run_via_cpython(filename): ROOT_DIR, "target/release/rustpython" ) RUSTPYTHON_BINARY = os.path.abspath(RUSTPYTHON_BINARY) +RUSTPYTHON_SNIPPET_EXCLUDE = set( + os.environ.get("RUSTPYTHON_SNIPPET_EXCLUDE", "").split() +) def run_via_rustpython(filename, test_type): @@ -71,6 +74,14 @@ def create_test_function(cls, filename, method, test_type): def test_function(self): perform_test(filename, method, test_type) + if ( + method == "rustpython" + and os.path.splitext(snippet_filename)[0] in RUSTPYTHON_SNIPPET_EXCLUDE + ): + test_function = unittest.skip("excluded by RUSTPYTHON_SNIPPET_EXCLUDE")( + test_function + ) + if hasattr(cls, test_function_name): raise ValueError("Duplicate test case {}".format(test_function_name)) setattr(cls, test_function_name, test_function) diff --git a/scripts/check_redundant_patches.py b/scripts/check_redundant_patches.py old mode 100644 new mode 100755 diff --git a/scripts/dis_dump.py b/scripts/dis_dump.py index 813de22e658..a149f724af9 100755 --- a/scripts/dis_dump.py +++ b/scripts/dis_dump.py @@ -170,12 +170,22 @@ def _resolve_arg_fallback(code, opname, arg): "LOAD_ATTR", "STORE_ATTR", "DELETE_ATTR", - "IMPORT_NAME", "IMPORT_FROM", "LOAD_FROM_DICT_OR_GLOBALS", ): if 0 <= arg < len(code.co_names): return code.co_names[arg] + elif opname == "IMPORT_NAME": + name_idx, policy = arg, 0 + if sys.version_info >= (3, 15): + name_idx, policy = arg >> 2, arg & 3 + if 0 <= name_idx < len(code.co_names): + name = code.co_names[name_idx] + if policy & 1 and name: + return f"{name} + lazy" + if policy & 2 and name: + return f"{name} + eager" + return name elif opname == "LOAD_SUPER_ATTR": name_idx = arg >> 2 if 0 <= name_idx < len(code.co_names): diff --git a/scripts/libc_posix.py b/scripts/libc_posix.py index 82f3eb96d83..8c0a177b477 100644 --- a/scripts/libc_posix.py +++ b/scripts/libc_posix.py @@ -4,11 +4,10 @@ import pathlib import re import subprocess -import urllib.request - import tomllib +import urllib.request -CPYTHON_VERSION = "3.14" +CPYTHON_VERSION = "3.15" CONSTS_PATTERN = re.compile(r"\b_*[A-Z]+(?:_+[A-Z]+)*_*\b") diff --git a/scripts/tests/test_whatsleft.py b/scripts/tests/test_whatsleft.py new file mode 100644 index 00000000000..70d34fa0079 --- /dev/null +++ b/scripts/tests/test_whatsleft.py @@ -0,0 +1,841 @@ +"""Tests for whats_left's selected top-level reference discovery. + +Checks for ambiguity in whats_left's flattened reference inventory. +Tests for scan coverage and reference-signature error accounting. +""" + +import ast +import inspect +import io +import json +import os +import pathlib +import re +import sys +import tempfile +import types +import unittest +import warnings +from contextlib import redirect_stdout + +SOURCE = pathlib.Path(__file__).resolve().parents[1] / "whats_left.py" +tree = ast.parse(SOURCE.read_text(encoding="utf-8")) + +names = { + "record_reference_discovery", + "scan_modules", + "gen_modules", + "record_reference_issue", + "reference_direct_names", + "ensure_reference_class_scope", +} +nodes = [ + node + for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name in names +] +discovery_namespace = { + "_discovery_type": type, + "_discovery_str": str, + "_discovery_len": len, + "_MAX_DISCOVERY_RECORDS": 16384, + "_MAX_DISCOVERY_CHARS": 1048576, + "_reference_type": type, + "_reference_str": str, + "_reference_len": len, + "_reference_set": set, + "_reference_sum": sum, + "_reference_any": any, + "_reference_chars_used": [0], + "_MAX_REFERENCE_FIELD_CHARS": 4096, + "_MAX_REFERENCE_TOTAL_CHARS": 32768, + "_MAX_REFERENCE_ISSUES": 1024, + "reference_inventory_diagnostics": {"issues": [], "truncated": False}, + "reference_class_selection": {}, + "warnings": warnings, + "sys": sys, +} +exec( + compile(ast.Module(nodes, type_ignores=[]), str(SOURCE), "exec"), + discovery_namespace, +) + + +class DiscoveryTests(unittest.TestCase): + def setUp(self): + self.original = discovery_namespace.copy() + discovery_namespace.update( + reference_discovery={ + "names": [], + "ignored": [], + "scanner_errors": [], + "truncated": False, + }, + _discovery_chars=[0], + ) + + def tearDown(self): + discovery_namespace.clear() + discovery_namespace.update(self.original) + + def test_scanner_errors_do_not_change_selection(self): + class Scanner: + def run(self, callback, onerror): + callback(None, "ok", None) + onerror("broken.child") + onerror("broken") + onerror("broken") + + discovery_namespace["ModuleScanner"] = Scanner + self.assertEqual(discovery_namespace["scan_modules"](), ["ok", "broken"]) + self.assertEqual( + discovery_namespace["reference_discovery"]["scanner_errors"], + ["broken.child", "broken", "broken"], + ) + + def test_discovery_records_ignored_and_failed_names(self): + discovery_namespace.update( + scan_modules=lambda: ["ok", "bad", "skip"], + name_sort_key=lambda name: name, + IGNORED_MODULES={"skip"}, + dir_of_mod_or_error=lambda name, keep_other: ( + ImportError("bad") if name == "bad" else {} + ), + import_module=lambda name: types.ModuleType(name), + BUILTIN_TYPES=[], + ) + modules, _failed = discovery_namespace["gen_modules"]() + self.assertEqual(set(modules), {"ok"}) + self.assertEqual( + discovery_namespace["reference_discovery"]["names"], ["bad", "ok", "skip"] + ) + self.assertEqual( + discovery_namespace["reference_discovery"]["ignored"], ["skip"] + ) + + def test_sorted_lookup_precedes_scanner_execution(self): + events = [] + + def original_sorted(items, **kwargs): + events.append("original") + return sorted(items, **kwargs) + + def replacement_sorted(items, **kwargs): + events.append("replacement") + return sorted(items, **kwargs) + + def scan(): + discovery_namespace["sorted"] = replacement_sorted + return [] + + discovery_namespace.update( + sorted=original_sorted, + scan_modules=scan, + name_sort_key=lambda name: name, + IGNORED_MODULES=set(), + ) + discovery_namespace["gen_modules"]() + self.assertEqual(events, ["original"]) + + def test_record_count_and_name_lengths_are_bounded(self): + discovery_namespace["_MAX_DISCOVERY_RECORDS"] = 1 + record = discovery_namespace["record_reference_discovery"] + record("scanner_errors", "") + record("scanner_errors", "") + self.assertEqual( + discovery_namespace["reference_discovery"]["scanner_errors"], [""] + ) + self.assertTrue(discovery_namespace["reference_discovery"]["truncated"]) + discovery_namespace["reference_discovery"] = { + "names": [], + "ignored": [], + "scanner_errors": [], + "truncated": False, + } + discovery_namespace["_discovery_chars"] = [0] + record("names", "x" * 4097) + self.assertEqual(discovery_namespace["reference_discovery"]["names"], []) + self.assertTrue(discovery_namespace["reference_discovery"]["truncated"]) + + def test_non_exact_name_is_not_represented_or_reformatted(self): + class Hostile(str): + def __repr__(self): + raise AssertionError("repr called") + + def __str__(self): + raise AssertionError("str called") + + discovery_namespace["record_reference_discovery"]("names", Hostile("x")) + self.assertEqual(discovery_namespace["reference_discovery"]["names"], []) + self.assertTrue(discovery_namespace["reference_discovery"]["truncated"]) + + +names = { + "record_reference_issue", + "record_reference_expanded_class", + "ensure_reference_class_scope", + "record_reference_class_selection", + "reference_direct_names", + "check_reference_class_member", + "_expand_class_members", + "gen_methods", +} +nodes = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names] +inventory_namespace = { + "_reference_type": type, + "_reference_str": str, + "_reference_len": len, + "_reference_set": set, + "_reference_sum": sum, + "_reference_any": any, + "_reference_chars_used": [0], + "_MAX_REFERENCE_FIELD_CHARS": 4096, + "_MAX_REFERENCE_TOTAL_CHARS": 32768, + "_MAX_REFERENCE_ISSUES": 1024, + "reference_inventory_diagnostics": {"issues": [], "truncated": False}, + "reference_expanded_classes": {}, + "reference_class_selection": {}, +} +exec( + compile(ast.Module(nodes, type_ignores=[]), str(SOURCE), "exec"), + inventory_namespace, +) + + +class InventoryTests(unittest.TestCase): + def setUp(self): + self.original = inventory_namespace.copy() + inventory_namespace["reference_inventory_diagnostics"] = { + "issues": [], + "truncated": False, + } + inventory_namespace["_reference_chars_used"] = [0] + inventory_namespace["reference_expanded_classes"] = {} + inventory_namespace["reference_class_selection"] = {} + + def tearDown(self): + inventory_namespace.clear() + inventory_namespace.update(self.original) + + def test_direct_dotted_and_generated_collisions(self): + result = {"A.member": "direct"} + seen = inventory_namespace["reference_direct_names"](result, "demo") + check = inventory_namespace["check_reference_class_member"] + check(seen, "demo", "member", "A.member") + result["A.member"] = "first" + check(seen, "demo", "member", "A.member") + result["A.member"] = "second" + check(seen, "demo", "nested.member", "A.nested.member") + result["A.nested.member"] = "third" + self.assertEqual(result["A.member"], "second") + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"]["issues"], + [ + ("dotted_module_attribute", "demo", "A.member"), + ("flattened_name_collision", "demo", "A.member"), + ("flattened_name_collision", "demo", "A.member"), + ("dotted_class_attribute", "demo", "A.nested.member"), + ], + ) + + def test_different_class_paths_collide_after_flattening(self): + check = inventory_namespace["check_reference_class_member"] + seen = set() + check(seen, "demo", "B.C", "A.B.C") + check(seen, "demo", "C", "A.B.C") + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"]["issues"], + [ + ("dotted_class_attribute", "demo", "A.B.C"), + ("flattened_name_collision", "demo", "A.B.C"), + ], + ) + + def test_non_exact_formatted_key_is_not_hashed(self): + class Hostile(str): + def __hash__(self): + raise AssertionError("hash called") + + def __repr__(self): + raise AssertionError("repr called") + + inventory_namespace["check_reference_class_member"]( + set(), "demo", "x", Hostile("C.x") + ) + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"]["issues"], + [("non_exact_flattened_name", "demo", None)], + ) + + def test_non_exact_names_add_no_hash_equality_or_contains_callbacks(self): + calls = [] + + class Hostile(str): + def __hash__(self): + calls.append("hash") + return super().__hash__() + + def __eq__(self, other): + calls.append("eq") + return super().__eq__(other) + + def __contains__(self, other): + calls.append("contains") + return super().__contains__(other) + + def __repr__(self): + raise AssertionError("repr called") + + result = {Hostile("C.member"): 1} + calls.clear() + inventory_namespace["reference_direct_names"](result, "demo") + self.assertEqual(calls, []) + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"]["issues"], + [("non_exact_module_attribute", "demo", None)], + ) + + def test_existing_formatter_caller_and_count_are_preserved(self): + import sys + + calls = [] + + class Hostile(str): + def __format__(self, spec): + caller = sys._getframe(1).f_code.co_name + calls.append(caller) + return caller + + def __repr__(self): + raise AssertionError("repr called") + + class DecimalType: + pass + + module = types.SimpleNamespace(DecimalType=DecimalType) + result = {"DecimalType": {}} + inventory_namespace.update( + BUILTIN_TYPES=[], own_attrs=lambda obj: [(Hostile("x"), 1)] + ) + inventory_namespace["_expand_class_members"](result, module) + self.assertEqual(calls, ["_expand_class_members"]) + self.assertEqual(result["DecimalType._expand_class_members"], 1) + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"]["issues"], + [("non_exact_class_name_or_attribute", "decimal", None)], + ) + + def test_hostile_formatter_cannot_change_original_rhs_value(self): + import sys + + class Hostile(str): + def __format__(self, spec): + sys._getframe(1).f_locals["info"] = "mutated" + return "x" + + class DecimalType: + pass + + module = types.SimpleNamespace(DecimalType=DecimalType) + result = {"DecimalType": {}} + inventory_namespace.update( + BUILTIN_TYPES=[], own_attrs=lambda obj: [(Hostile("x"), "original")] + ) + inventory_namespace["_expand_class_members"](result, module) + self.assertEqual(result["DecimalType.x"], "original") + self.assertTrue( + inventory_namespace["reference_inventory_diagnostics"]["issues"] + ) + + def test_non_exact_scope_is_reported_without_repr(self): + class Hostile(str): + def __repr__(self): + raise AssertionError("repr called") + + inventory_namespace["reference_direct_names"]({}, Hostile("demo")) + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"]["issues"], + [("non_exact_module_name", None, None)], + ) + + def test_oversized_diagnostics_are_truncated(self): + inventory_namespace["_MAX_REFERENCE_FIELD_CHARS"] = 2 + inventory_namespace["record_reference_issue"]("large", "demo", "x") + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"], + {"issues": [], "truncated": True}, + ) + + def test_total_text_budget_is_enforced(self): + inventory_namespace["_MAX_REFERENCE_TOTAL_CHARS"] = 4 + record = inventory_namespace["record_reference_issue"] + record("one", "d", "xy") + record("two", "d", "xy") + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"], + {"issues": [("one", "d", "xy")], "truncated": True}, + ) + + def test_decimal_expansion_accounts_for_direct_names(self): + class DecimalType: + pass + + DecimalType.__name__ = "DecimalType" + module = types.SimpleNamespace(DecimalType=DecimalType) + result = {"DecimalType": {}, "DecimalType.x": "direct"} + inventory_namespace.update( + BUILTIN_TYPES=[], own_attrs=lambda obj: [("x", "member")] + ) + inventory_namespace["_expand_class_members"](result, module) + self.assertEqual(result["DecimalType.x"], "member") + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"]["issues"], + [ + ("dotted_module_attribute", "decimal", "DecimalType.x"), + ("flattened_name_collision", "decimal", "DecimalType.x"), + ], + ) + + def test_reference_class_selection_covers_other_and_dotted_names(self): + class Empty: + pass + + module = types.SimpleNamespace(Empty=Empty, plain=1) + result = {"Empty": {}, "plain": {}, "A.b": {}} + inventory_namespace.update(BUILTIN_TYPES=[], own_attrs=lambda obj: []) + inventory_namespace["_expand_class_members"](result, module) + self.assertEqual( + inventory_namespace["reference_class_selection"], + { + "decimal": { + "Empty": "selected", + "plain": "not_selected", + "A.b": "skipped_dotted", + } + }, + ) + + def test_zero_member_expanded_class_is_recorded(self): + class Empty: + pass + + module = types.SimpleNamespace(Empty=Empty) + result = {"Empty": {}} + inventory_namespace.update(BUILTIN_TYPES=[], own_attrs=lambda obj: []) + inventory_namespace["_expand_class_members"](result, module) + self.assertEqual( + inventory_namespace["reference_expanded_classes"], {"decimal": ["Empty"]} + ) + self.assertEqual( + inventory_namespace["reference_class_selection"], + {"decimal": {"Empty": "selected"}}, + ) + + def test_duplicate_builtin_names(self): + inventory_namespace.update( + BUILTIN_TYPES=[], + eval=lambda code: list, + extra_info=lambda obj: {}, + own_attrs=lambda obj: [], + name_sort_key=lambda name: name, + ) + inventory_namespace["gen_methods"]() + self.assertTrue( + any( + item[0] == "duplicate_builtin_type" + for item in inventory_namespace["reference_inventory_diagnostics"][ + "issues" + ] + ) + ) + + def test_dotted_builtin_type_is_ambiguous(self): + unusual = type("A.B", (), {}) + inventory_namespace.update( + BUILTIN_TYPES=[], + eval=lambda code: unusual, + extra_info=lambda obj: {}, + own_attrs=lambda obj: [], + name_sort_key=lambda name: name, + ) + inventory_namespace["gen_methods"]() + self.assertIn( + ("dotted_builtin_type", "builtins", "A.B"), + inventory_namespace["reference_inventory_diagnostics"]["issues"], + ) + + def test_non_native_builtin_type_keeps_original_rhs_order(self): + import sys + + events = [] + + class FakeType: + @property + def __name__(self): + events.append("name") + sys._getframe(1).f_locals["info"] = "mutated" + return "Repeated" + + typ = FakeType() + inventory_namespace.update( + BUILTIN_TYPES=[], + eval=lambda code: typ, + extra_info=lambda obj: events.append("info") or {"original": True}, + own_attrs=lambda obj: events.append("attrs") or [], + name_sort_key=lambda name: name, + ) + output = inventory_namespace["gen_methods"]() + self.assertEqual(events, ["info", "attrs", "name"] * (len(events) // 3)) + self.assertIn("'original': True", output) + self.assertNotIn("mutated", output) + self.assertTrue( + any( + item[0] == "non_native_builtin_type" + for item in inventory_namespace["reference_inventory_diagnostics"][ + "issues" + ] + ) + ) + + def test_rhs_callback_can_replace_type_without_changing_assignment_order(self): + import sys + + class Hostile: + @property + def __name__(self): + sys._getframe(1).f_locals["info"] = "mutated" + return "Replacement" + + replacement = Hostile() + + def inspect_type(obj): + sys._getframe(1).f_locals["typ"] = replacement + return {"original": True} + + inventory_namespace.update( + BUILTIN_TYPES=[], + eval=lambda code: list, + extra_info=inspect_type, + own_attrs=lambda obj: [], + name_sort_key=lambda name: name, + ) + output = inventory_namespace["gen_methods"]() + self.assertIn("'original': True", output) + self.assertNotIn("mutated", output) + self.assertTrue( + any( + item[0] == "non_native_builtin_type" + for item in inventory_namespace["reference_inventory_diagnostics"][ + "issues" + ] + ) + ) + + def test_diagnostics_are_bounded_and_truncation_explicit(self): + inventory_namespace["_MAX_REFERENCE_ISSUES"] = 1 + record = inventory_namespace["record_reference_issue"] + record("one", "demo", "x") + record("two", "demo", "y") + self.assertEqual( + inventory_namespace["reference_inventory_diagnostics"], + {"issues": [("one", "demo", "x")], "truncated": True}, + ) + + +names = { + "attr_is_not_inherited", + "compare", + "observe_real_type", + "observe_real_exception", + "dir_of_mod_or_error", + "name_sort_key", +} +nodes = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name in names] +coverage_namespace = { + "cpython_failed_imports": {}, + "reference_discovery": {}, + "inspect": inspect, + "re": re, + "sys": sys, + "reference_inventory_diagnostics": {"issues": [], "truncated": False}, + "reference_expanded_classes": {}, + "reference_class_selection": {}, + "actual_parent_scans": {}, + "_safe_type": type, + "_safe_str": str, + "_safe_frozenset": frozenset, +} +exec( + compile(ast.Module(nodes, type_ignores=[]), str(SOURCE), "exec"), coverage_namespace +) +for name in ("extra_info",): + node = next( + n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == name + ) + exec( + compile(ast.Module([node], type_ignores=[]), str(SOURCE), "exec"), + coverage_namespace, + ) + + +class CoverageTests(unittest.TestCase): + def setUp(self): + original = coverage_namespace.copy() + coverage_namespace["actual_parent_scans"] = {} + coverage_namespace["reference_expanded_classes"] = {} + + def restore(): + coverage_namespace.clear() + coverage_namespace.update(original) + + self.addCleanup(restore) + + def test_real_type_observation_ignores_spoofed_class(self): + calls = [] + + class PretendsToBeType: + @property + def __class__(self): + calls.append("class") + return type + + obj = PretendsToBeType() + self.assertTrue(isinstance(obj, type)) + calls.clear() + self.assertEqual(coverage_namespace["observe_real_type"](obj), "not_real_type") + self.assertEqual(calls, []) + self.assertEqual(coverage_namespace["observe_real_type"](list), "real_type") + + def test_direct_scan_records_selected_parents_without_extra_getters(self): + calls = [] + + class Pretend: + @property + def __class__(self): + calls.append("spoofed_class") + return type + + class Item: + pass + + bad = object() + values = {"Type": Item, "Pretend": Pretend(), "Failure": bad} + + class Module: + def __dir__(self): + return list(values) + + def __getattribute__(self, name): + if name in values: + calls.append(name) + return values[name] + return super().__getattribute__(name) + + observe = coverage_namespace["observe_real_type"] + coverage_namespace.update( + import_module=lambda name: Module(), + extra_info=lambda obj: {"sig": None, "sig_error": False, "doc": None}, + observe_real_type=lambda obj: ( + "classification_failed" if obj is bad else observe(obj) + ), + reference_expanded_classes={ + "demo": ["Type", "Pretend", "Failure", "Missing"] + }, + ) + coverage_namespace["dir_of_mod_or_error"]("demo") + self.assertEqual(calls, ["Failure", "Pretend", "Type"]) + self.assertEqual( + coverage_namespace["actual_parent_scans"], + { + "demo": { + "Failure": "classification_failed", + "Pretend": "not_real_type", + "Type": "real_type", + } + }, + ) + + def test_module_scan_and_second_import_outcomes_are_distinct(self): + ref = { + "sig": "(self, /)", + "sig_error": False, + "doc": "same", + } + with tempfile.TemporaryDirectory() as tmp: + pathlib.Path(tmp, "failed.py").touch() + pathlib.Path(tmp, "demo.py").touch() + coverage_namespace.update( + expected_methods={}, + cpymods={ + "absent": {}, + "failed": {}, + "demo": {"Thing": ref, "Thing.member": ref}, + }, + libdir=os.fsencode(tmp), + reference_expanded_classes={ + "absent": ["Empty"], + "failed": ["Empty"], + "demo": ["Thing"], + }, + dir_of_mod_or_error=lambda name: ( + RuntimeError("failed") if name == "failed" else {"Thing": ref} + ), + import_module=lambda name: RuntimeError("second import failed"), + ) + output = io.StringIO() + with redirect_stdout(output): + coverage_namespace["compare"]() + result = json.loads(output.getvalue()) + self.assertEqual( + result["actual_scan_status"], + { + "absent": "not_discovered", + "failed": "scan_returned_exception", + "demo": "scan_completed", + }, + ) + self.assertEqual( + result["actual_second_import_status"], + { + "absent": "not_attempted", + "failed": "not_attempted", + "demo": "returned_exception", + }, + ) + self.assertEqual( + result["actual_parent_decisions"]["demo"], + {"Thing.member": "isinstance_false"}, + ) + self.assertEqual( + result["actual_parent_scans"]["absent"], {"Empty": "not_observed"} + ) + + def test_module_inherited_and_missing_observations(self): + class Parent: + def same(self): + pass + + def other(self): + pass + + class Child(Parent): + pass + + module = types.ModuleType("demo") + module.Thing = Child + ref = { + "sig": "(self, /)", + "sig_error": False, + "doc": "same", + } + actual = { + **ref, + } + incompatible = {**actual, "sig": "(self, required, /)"} + + def inspect_item(obj): + return incompatible if obj is Parent.other else actual + + with tempfile.TemporaryDirectory() as tmp: + pathlib.Path(tmp, "demo.py").touch() + coverage_namespace.update( + { + "expected_methods": {}, + "reference_expanded_classes": {"demo": ["Thing", "Empty"]}, + "actual_parent_scans": {"demo": {"Thing": "real_type"}}, + "cpymods": { + "demo": { + "Thing": ref, + "Thing.same": ref, + "Thing.other": ref, + "Thing.missing": ref, + } + }, + "libdir": os.fsencode(tmp), + "extra_info": inspect_item, + "dir_of_mod_or_error": lambda name: ( + {"Thing": actual} if name == "demo" else {} + ), + "import_module": lambda name: module, + } + ) + output = io.StringIO() + with redirect_stdout(output): + coverage_namespace["compare"]() + result = json.loads(output.getvalue()) + self.assertIn("demo.Thing.other (inherited)", result["missing_items"]["demo"]) + self.assertIn("demo.Thing.missing", result["missing_items"]["demo"]) + self.assertNotIn("demo.Thing.same", result["missing_items"]["demo"]) + self.assertEqual(result["actual_scan_status"]["demo"], "scan_completed") + self.assertEqual( + result["actual_second_import_status"]["demo"], "returned_nonexception" + ) + self.assertEqual( + result["actual_parent_scans"]["demo"], + {"Thing": "real_type", "Empty": "not_observed"}, + ) + self.assertEqual( + result["actual_parent_decisions"]["demo"], + { + "Thing.same": "isinstance_true", + "Thing.other": "isinstance_true", + "Thing.missing": "isinstance_true", + }, + ) + + +class ReferenceErrorTests(unittest.TestCase): + def setUp(self): + global reference_error_namespace + reference_error_namespace = coverage_namespace + original = coverage_namespace.copy() + reference_error_namespace["actual_parent_scans"] = {} + reference_error_namespace["reference_expanded_classes"] = {} + + def restore(): + coverage_namespace.clear() + coverage_namespace.update(original) + + self.addCleanup(restore) + + def run_comparison(self, *, module_error): + builtin = {"sig": "ValueError('builtin')", "sig_error": True, "doc": None} + reference = { + "sig": "ValueError('module')" if module_error else "(x, /)", + "sig_error": module_error, + "doc": "same", + } + actual = {"sig": "(x, /)", "sig_error": False, "doc": "same"} + with tempfile.TemporaryDirectory() as tmp: + pathlib.Path(tmp, "demo.py").touch() + reference_error_namespace.update( + expected_methods={"demo": (type, builtin, [])}, + cpymods={"demo": {"f": reference}}, + libdir=os.fsencode(tmp), + dir_of_mod_or_error=lambda name: {"f": actual}, + import_module=lambda name: types.ModuleType(name), + ) + output = io.StringIO() + with redirect_stdout(output): + reference_error_namespace["compare"]() + return json.loads(output.getvalue()) + + def test_builtin_name_collision_does_not_hide_clean_module(self): + result = self.run_comparison(module_error=False) + self.assertIn("demo", result["implemented"]) + self.assertEqual( + result["uncomparable_signatures"]["demo"], + [["demo", "ValueError('builtin')"]], + ) + + def test_module_reference_error_still_prevents_clean_classification(self): + result = self.run_comparison(module_error=True) + self.assertNotIn("demo", result["implemented"]) + self.assertIn( + ["demo.f", "ValueError('module')"], + result["uncomparable_signatures"]["demo"], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/update_lib/cmd_copy_lib.py b/scripts/update_lib/cmd_copy_lib.py index 1b16497fc83..386c07e87e2 100644 --- a/scripts/update_lib/cmd_copy_lib.py +++ b/scripts/update_lib/cmd_copy_lib.py @@ -8,6 +8,7 @@ # Directory python scripts/update_lib copy-lib cpython/Lib/json + """ import argparse @@ -16,6 +17,14 @@ import sys +def _ignore_bytecode_caches(directory: str, names: list[str]) -> set[str]: + return { + name + for name in names + if name == "__pycache__" and (pathlib.Path(directory) / name).is_dir() + } + + def _copy_single( src_path: pathlib.Path, lib_path: pathlib.Path, @@ -38,7 +47,7 @@ def _copy_single( if verbose: print(f"Copying directory: {src_path} -> {lib_path}") lib_path.parent.mkdir(parents=True, exist_ok=True) - shutil.copytree(src_path, lib_path) + shutil.copytree(src_path, lib_path, ignore=_ignore_bytecode_caches) else: if verbose: print(f"Copying file: {src_path} -> {lib_path}") @@ -46,6 +55,14 @@ def _copy_single( shutil.copy2(src_path, lib_path) +def _reject_python_tests(src_path: pathlib.Path, relative: pathlib.Path) -> None: + is_test_tree = len(relative.parts) >= 2 and relative.parts[1].casefold() == "test" + if is_test_tree and (src_path.is_dir() or src_path.suffix.casefold() == ".py"): + raise ValueError( + "Use migrate for Python tests; copy-lib would replace Lib/test" + ) + + def copy_lib( src_path: pathlib.Path, verbose: bool = True, @@ -66,6 +83,16 @@ def copy_lib( path_str = str(src_path).replace("\\", "/") if "/Lib/" not in path_str: raise ValueError(f"Path must contain '/Lib/' (got: {src_path})") + if not src_path.exists(): + raise FileNotFoundError(f"Source path does not exist: {src_path}") + relative = parse_lib_path(src_path) + _reject_python_tests(src_path, relative) + + # Data files name an exact asset, not the containing top-level module. + # Expanding Lib/test/data.txt as "test" would replace the entire test tree. + if src_path.is_file() and src_path.suffix != ".py": + _copy_single(src_path, relative, verbose) + return cpython_prefix, after_lib = path_str.split("/Lib/", 1) # Get module name (first component, without .py) @@ -76,11 +103,12 @@ def copy_lib( # Get all paths to copy from DEPENDENCIES table all_src_paths = get_lib_paths(name, cpython_prefix) - # Copy each file - for src in all_src_paths: - if src.exists(): - lib_path = parse_lib_path(src) - _copy_single(src, lib_path, verbose) + # Validate the entire expansion before removing any destination. + plan = [(src, parse_lib_path(src)) for src in all_src_paths if src.exists()] + for src, lib_path in plan: + _reject_python_tests(src, lib_path) + for src, lib_path in plan: + _copy_single(src, lib_path, verbose) def main(argv: list[str] | None = None) -> int: @@ -93,7 +121,6 @@ def main(argv: list[str] | None = None) -> int: type=pathlib.Path, help="Source path containing /Lib/ (e.g., cpython/Lib/dataclasses.py)", ) - args = parser.parse_args(argv) try: diff --git a/scripts/update_lib/cmd_migrate.py b/scripts/update_lib/cmd_migrate.py index 97cdf7b141b..e7cac09d1e6 100644 --- a/scripts/update_lib/cmd_migrate.py +++ b/scripts/update_lib/cmd_migrate.py @@ -1,17 +1,42 @@ #!/usr/bin/env python """ -Migrate test file(s) from CPython, preserving RustPython markers. +Migrate Python Lib files from CPython, preserving explicit local adaptations. Usage: python scripts/update_lib migrate cpython/Lib/test/test_foo.py + python scripts/update_lib migrate cpython/Lib/test/test_foo.py --patches remaining.json + python scripts/update_lib migrate cpython/Lib/example.py --new-file-adaptations new.json -This will: +Remaining metadata names the exact repository-relative target and its existing +decorator patches. An optional "doctests" object selects existing guarded inputs +by exact source text, mapping each to a single-line reason. Guarded doctests need +this explicit selection; an empty object retires all their guards. Canonical +expected output is never copied from the old file. Optional "blocks" lists +[canonical, local] source pairs to preserve exact existing changes. +Both fragments must match uniquely; no module-specific defaults are inferred. +Non-marker adaptations require reviewed blocks on each migration, for example +{"target": "Lib/example.py", "patches": {}, "blocks": [["old = 1", "old = 2"]]}. +Use a host Python that parses the source version (Python 3.15 for 3.15 syntax), +as required by the existing marker extraction and application steps. + +For a new destination only, --new-file-adaptations accepts exactly "target", +"source_sha256" (the raw canonical file hash), and "blocks". Each canonical +fragment must occur uniquely, and fragments must not overlap. Only top-level +imports and existing binding values may change; all class/function bodies are +preserved. These adaptations still require review: preserving their AST does +not prove behavioral equivalence. Existing destinations are never overwritten. + +Ordinary migration will: 1. Extract patches from Lib/test/test_foo.py (if exists) 2. Apply them to cpython/Lib/test/test_foo.py 3. Write result to Lib/test/test_foo.py """ import argparse +import ast +import collections +import hashlib +import json import pathlib import shutil import sys @@ -21,10 +46,115 @@ from update_lib.file_utils import parse_lib_path +def migrate_new_file(src_path: pathlib.Path, document: dict) -> None: + """Introduce reviewed import/binding adaptations into a new canonical file. + + This opt-in path never overwrites an existing destination or changes the + preservation rules of ordinary migrations. Metadata pins the raw source + hash and exact target; all fragments are validated before any write. + Import and binding values still require review: AST preservation alone does + not establish behavioral equivalence of the adapted module. + """ + if not isinstance(document, dict) or set(document) != { + "target", + "source_sha256", + "blocks", + }: + raise ValueError( + "New-file adaptations require target, source_sha256 and blocks" + ) + target_name = document["target"] + if not isinstance(target_name, str) or "\\" in target_name: + raise ValueError("Expected a repository-relative Lib Python file") + relative = pathlib.Path(target_name) + if ( + relative.is_absolute() + or ".." in relative.parts + or relative.parts[:1] != ("Lib",) + or relative.suffix != ".py" + or relative.as_posix() != target_name + or relative != parse_lib_path(src_path) + ): + raise ValueError("New-file adaptation target does not match canonical Lib path") + repository = pathlib.Path(__file__).resolve().parents[2] + target = repository / relative + if any( + (repository / parent).is_symlink() for parent in (relative, *relative.parents) + ): + raise ValueError("New-file destination must not contain symlinks") + if target.exists(): + raise ValueError("New-file adaptation destination already exists") + if not src_path.is_file() or src_path.is_symlink(): + raise ValueError("New-file source must be a regular canonical file") + raw = src_path.read_bytes() + if hashlib.sha256(raw).hexdigest() != document["source_sha256"]: + raise ValueError("New-file canonical source hash mismatch") + canonical = raw.decode("utf-8") + blocks = document["blocks"] + if ( + not isinstance(blocks, list) + or not blocks + or any( + not isinstance(pair, list) + or len(pair) != 2 + or any(not isinstance(text, str) or not text.strip() for text in pair) + for pair in blocks + ) + ): + raise ValueError("New-file blocks must be nonempty canonical/local pairs") + edits = [] + for old, new in blocks: + start = canonical.find(old) + if start < 0 or canonical.find(old, start + 1) >= 0: + raise ValueError("Missing or ambiguous new-file canonical fragment") + edits.append((start, start + len(old), new)) + edits.sort() + if any(left[1] > right[0] for left, right in zip(edits, edits[1:])): + raise ValueError("Overlapping new-file adaptation fragments") + adapted = canonical + for start, end, new in reversed(edits): + adapted = adapted[:start] + new + adapted[end:] + + def protected_structure(text): + tree = ast.parse(text) + protected = [] + for node in tree.body: + if isinstance(node, (ast.Import, ast.ImportFrom)): + continue + if isinstance(node, (ast.Assign, ast.AnnAssign)): + # Only the value of an existing top-level binding may change. + # Assignment targets, their order and annotations are retained. + node.value = ast.Constant(value=None) + protected.append(ast.dump(node, include_attributes=False)) + return protected + + try: + if protected_structure(canonical) != protected_structure(adapted): + raise ValueError( + "New-file adaptations may change only imports and bindings" + ) + except SyntaxError as error: + raise ValueError("Invalid Python in new-file adaptation") from error + target.parent.mkdir(parents=True, exist_ok=True) + try: + with target.open("xb") as output: + output.write(adapted.encode("utf-8")) + except FileExistsError as error: + raise ValueError("New-file adaptation destination already exists") from error + + +def _preserve_block(old, new, canonical, local): + """Preserve an explicit existing fragment; do not infer module adaptations.""" + if old.count(local) != 1 or new.count(canonical) != 1: + raise ValueError("Changed or ambiguous preservation block") + return new.replace(canonical, local, 1) + + def patch_single_content( src_path: pathlib.Path, lib_path: pathlib.Path, -) -> str: + patches_document: dict | None = None, +) -> str | None: """ Patch content without writing to disk. @@ -33,25 +163,86 @@ def patch_single_content( lib_path: Lib path to extract patches from (e.g., Lib/test/foo.py) Returns: - The patched content. + The patched content, or None for an unchanged negative-syntax fixture. """ from update_lib import apply_patches, extract_patches + from update_lib.patch_spec import apply_doctest_metadata, extract_doctest_guards # Extract patches from existing file (if exists) if lib_path.exists(): - patches = extract_patches(lib_path.read_text(encoding="utf-8")) + old_content = lib_path.read_text(encoding="utf-8") + try: + patches = extract_patches(old_content) + except SyntaxError: + # A fixture may be invalid Python on purpose. If its bytes agree, + # preserve it as-is without trying to migrate AST-based markers. + if ( + patches_document is None + and src_path.read_bytes() == lib_path.read_bytes() + ): + return None + raise else: patches = {} + repository = pathlib.Path(__file__).resolve().parents[2] + try: + relative_path = lib_path.resolve().relative_to(repository) + except ValueError: + # Explicit output paths outside this repository are not its Lib. + relative_path = pathlib.Path("__external_output__") + if patches_document is not None: + from update_lib.patch_spec import select_remaining_patches + + patches = select_remaining_patches( + patches, + patches_document, + relative_path, + old_content=old_content if lib_path.exists() else None, + ) + + blocks = patches_document.get("blocks", []) if patches_document else [] + if not isinstance(blocks, list) or any( + not isinstance(pair, list) + or len(pair) != 2 + or any(not isinstance(text, str) or not text.strip() for text in pair) + for pair in blocks + ): + raise ValueError("Blocks must be canonical/local source pairs") + if blocks and not lib_path.exists(): + raise ValueError("Blocks require an existing local file") + # Apply patches to source content src_content = src_path.read_text(encoding="utf-8") - return apply_patches(src_content, patches) + if lib_path.exists(): + if any(src_content.count(canonical) != 1 for canonical, _ in blocks): + raise ValueError("Changed or ambiguous canonical preservation block") + for canonical, local in blocks: + src_content = _preserve_block(old_content, src_content, canonical, local) + guards = extract_doctest_guards(old_content) + selection = patches_document.get("doctests") if patches_document else None + if guards and selection is None: + raise ValueError( + "Existing doctest guards require explicit doctests metadata" + ) + if selection is not None: + src_content = apply_doctest_metadata(old_content, src_content, selection) + if not src_content and not patches: + return src_content + try: + result = apply_patches(src_content, patches) + except SyntaxError as error: + if blocks: + raise ValueError("Preserved blocks produced invalid Python") from error + raise + return result def patch_file( src_path: pathlib.Path, lib_path: pathlib.Path | None = None, verbose: bool = True, + patches_document: dict | None = None, ) -> None: """ Patch a single file from source to lib. @@ -67,10 +258,14 @@ def patch_file( if lib_path.exists(): if verbose: print(f"Patching: {src_path} -> {lib_path}") - content = patch_single_content(src_path, lib_path) + content = patch_single_content(src_path, lib_path, patches_document) + if content is None: + return else: if verbose: print(f"Copying: {src_path} -> {lib_path}") + if patches_document is not None: + raise ValueError("Marker override requires an existing target") content = src_path.read_text(encoding="utf-8") lib_path.parent.mkdir(parents=True, exist_ok=True) @@ -93,29 +288,231 @@ def patch_directory( if lib_dir is None: lib_dir = parse_lib_path(src_dir) - src_files = sorted(f for f in src_dir.glob("**/*") if f.is_file()) + src_files = sorted( + f + for f in src_dir.glob("**/*") + if f.is_file() and "__pycache__" not in f.relative_to(src_dir).parts[:-1] + ) + # Prepare every Python migration before writing earlier paths. A syntax + # or marker error later in the package must not leave a partial update. + pending = [] for src_file in src_files: - rel_path = src_file.relative_to(src_dir) - lib_file = lib_dir / rel_path - - if src_file.suffix == ".py": - if lib_file.exists(): - if verbose: - print(f"Patching: {src_file} -> {lib_file}") - content = patch_single_content(src_file, lib_file) - else: - if verbose: - print(f"Copying: {src_file} -> {lib_file}") - content = src_file.read_text(encoding="utf-8") - - lib_file.parent.mkdir(parents=True, exist_ok=True) - lib_file.write_text(content, encoding="utf-8") - else: - if verbose: - print(f"Copying: {src_file} -> {lib_file}") - lib_file.parent.mkdir(parents=True, exist_ok=True) + lib_file = lib_dir / src_file.relative_to(src_dir) + content = None + patching = src_file.suffix == ".py" and lib_file.exists() + if patching: + content = patch_single_content(src_file, lib_file) + if content is None: + continue + elif src_file.suffix == ".py": + content = src_file.read_text(encoding="utf-8") + pending.append((src_file, lib_file, content, patching)) + + for src_file, lib_file, content, patching in pending: + if verbose: + action = "Patching" if patching else "Copying" + print(f"{action}: {src_file} -> {lib_file}") + lib_file.parent.mkdir(parents=True, exist_ok=True) + if content is None: shutil.copy2(src_file, lib_file) + else: + lib_file.write_text(content, encoding="utf-8") + + +def retire_legacy_paths(src_dir: pathlib.Path, mapping: dict) -> None: + """Retire explicit upstream-absent files after checking their replacements. + + Flat legacy maps use repository-relative Lib paths and name an already + canonical replacement, or null for an upstream removal. They never rewrite + replacements or recursively prune directories. + """ + from update_lib.file_utils import get_cpython_dir + + canonical = get_cpython_dir(src_dir).resolve() + local = pathlib.Path.cwd().resolve() + if not (canonical / "Lib").is_dir() or not src_dir.is_dir(): + raise ValueError("Canonical Lib or migration source directory does not exist") + + def lib_file(root, name): + path = pathlib.Path(name) + if path.is_absolute() or ".." in path.parts or path.parts[:1] != ("Lib",): + raise ValueError(f"Expected a repository-relative Lib file: {name}") + result = root / path + if result.is_symlink() or not result.resolve().is_relative_to(root / "Lib"): + raise ValueError(f"Lib file escapes its source tree: {name}") + return result + + legacy_files = [] + for old, new in mapping.items(): + legacy = lib_file(local, old) + upstream_old = lib_file(canonical, old) + if upstream_old.exists() or not legacy.is_file(): + raise ValueError(f"Not an existing upstream-absent file: {old}") + if new is not None: + replacement = lib_file(local, new) + upstream_new = lib_file(canonical, new) + if ( + not upstream_new.is_file() + or not replacement.is_file() + or replacement.read_bytes() != upstream_new.read_bytes() + ): + raise ValueError(f"Replacement is not canonical: {new}") + legacy_files.append(legacy) + + # Check the whole map before retiring any file. + for legacy in legacy_files: + legacy.unlink() + + +def migrate_package( + src_dir: pathlib.Path, lib_dir: pathlib.Path, mapping_path: pathlib.Path +) -> None: + """Validate the complete migration before writing or removing legacy files. + + The JSON map names legacy files beside lib_dir, mapping every marked class + to its canonical file relative to src_dir. Empty maps retire unmarked files. + No test modules are imported or executed. + """ + from update_lib.patch_spec import ( + _iter_class_methods, + _iter_module_classes, + apply_patches, + build_patch_dict, + extract_doctest_guards, + iter_patches, + ) + + mapping = json.loads(mapping_path.read_text(encoding="utf-8")) + if not isinstance(mapping, dict) or not mapping: + raise ValueError("Legacy mapping must be a nonempty object") + if all(value is None or isinstance(value, str) for value in mapping.values()): + retire_legacy_paths(src_dir, mapping) + return + if lib_dir.exists(): + raise ValueError(f"Destination already exists: {lib_dir}") + if ( + src_dir.resolve() == lib_dir.resolve() + or src_dir.resolve() in lib_dir.resolve().parents + ): + raise ValueError("Source and destination overlap") + source_files = sorted( + p + for p in src_dir.rglob("*") + if p.is_file() and "__pycache__" not in p.relative_to(src_dir).parts[:-1] + ) + if not (src_dir / "__init__.py").is_file(): + raise ValueError("Source must be a Python package") + if any( + p.is_symlink() or src_dir.resolve() not in p.resolve().parents + for p in source_files + ): + raise ValueError("Source files must remain inside the canonical package") + contents = {p.relative_to(src_dir): p.read_bytes() for p in source_files} + entries = collections.defaultdict(list) + owners = {} + legacy_files = [] + for name, class_map in mapping.items(): + if pathlib.Path(name).name != name or not name.endswith(".py"): + raise ValueError(f"Legacy file must be a sibling .py file: {name}") + if not isinstance(class_map, dict): + raise ValueError(f"Class map must be an object: {name}") + legacy = lib_dir.parent / name + if legacy.is_symlink() or legacy.resolve().parent != lib_dir.parent.resolve(): + raise ValueError(f"Legacy file escapes destination parent: {name}") + if ( + legacy.resolve() == lib_dir.resolve() + or src_dir.resolve() in legacy.resolve().parents + ): + raise ValueError(f"Legacy file overlaps canonical package: {name}") + legacy_files.append(legacy) + legacy_content = legacy.read_text(encoding="utf-8") + if extract_doctest_guards(legacy_content): + raise ValueError("Legacy package migration cannot select doctest guards") + patches = list(iter_patches(legacy_content)) + legacy_classes = collections.defaultdict(list) + for cls in _iter_module_classes(ast.parse(legacy_content)): + legacy_classes[cls.name].append(cls) + if set(class_map) != {p.parent_class for p in patches}: + raise ValueError(f"Missing or unused class mapping: {name}") + for entry in patches: + source_classes = legacy_classes[entry.parent_class] + if len(source_classes) != 1: + raise ValueError(f"Ambiguous legacy class: {entry.parent_class}") + if ( + entry.test_name != "__self__" + and sum( + method.name == entry.test_name + for method in _iter_class_methods(source_classes[0]) + ) + != 1 + ): + raise ValueError( + f"Ambiguous legacy method: {entry.parent_class}.{entry.test_name}" + ) + target = pathlib.Path(class_map[entry.parent_class]) + if target.is_absolute() or ".." in target.parts or target not in contents: + raise ValueError(f"Invalid canonical destination: {target}") + if target.suffix != ".py": + raise ValueError(f"Marker destination is not Python: {target}") + tree = ast.parse(contents[target].decode("utf-8")) + classes = collections.defaultdict(list) + for cls in _iter_module_classes(tree): + classes[cls.name].append(cls) + + def has_method(class_name, seen): + if class_name in seen: + return False + seen = seen | {class_name} + nodes = classes.get(class_name, []) + if len(nodes) != 1: + raise ValueError(f"Missing or ambiguous class: {class_name}") + cls = nodes[0] + methods = [ + m for m in _iter_class_methods(cls) if m.name == entry.test_name + ] + if len(methods) > 1: + raise ValueError( + f"Ambiguous method: {class_name}.{entry.test_name}" + ) + if methods or entry.test_name == "__self__": + return True + return any( + has_method(base.id, seen) + for base in cls.bases + if isinstance(base, ast.Name) and base.id in classes + ) + + if not has_method(entry.parent_class, set()): + raise ValueError( + f"Missing method: {entry.parent_class}.{entry.test_name}" + ) + owner_key = (target, entry.parent_class, entry.test_name) + if owner_key in owners and owners[owner_key] != legacy: + raise ValueError( + f"Duplicate mapped marker: {entry.parent_class}.{entry.test_name}" + ) + owners[owner_key] = legacy + entries[target].append(entry) + # Render and validate everything before changing the destination. + for target, patches in entries.items(): + contents[target] = apply_patches( + contents[target].decode("utf-8"), build_patch_dict(iter(patches)) + ).encode("utf-8") + for target, data in contents.items(): + if target.suffix == ".py": + text = data.decode("utf-8") + ast.parse(text) + if collections.Counter(iter_patches(text)) != collections.Counter( + entries[target] + ): + raise ValueError(f"Marker roundtrip mismatch: {target}") + for target, data in contents.items(): + destination = lib_dir / target + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_bytes(data) + for legacy in legacy_files: + legacy.unlink() def main(argv: list[str] | None = None) -> int: @@ -129,13 +526,49 @@ def main(argv: list[str] | None = None) -> int: help="Source path containing /Lib/ (file or directory)", ) + parser.add_argument( + "--legacy-map", + type=pathlib.Path, + help="Legacy class mapping, or exact Lib path to canonical replacement/null map", + ) + parser.add_argument( + "--patches", + type=pathlib.Path, + help="Single-file target, remaining decorator patches, and optional doctests JSON", + ) + parser.add_argument( + "--new-file-adaptations", + type=pathlib.Path, + help="Opt-in exact source hash and import/binding blocks for a new Lib file", + ) args = parser.parse_args(argv) try: - if args.path.is_dir(): + if args.new_file_adaptations is not None: + if ( + args.path.is_dir() + or args.legacy_map is not None + or args.patches is not None + ): + raise ValueError("--new-file-adaptations requires a single new file") + migrate_new_file( + args.path, + json.loads(args.new_file_adaptations.read_text(encoding="utf-8")), + ) + return 0 + if args.patches is not None and ( + args.path.is_dir() or args.legacy_map is not None + ): + raise ValueError("--patches requires a single file without --legacy-map") + document = ( + json.loads(args.patches.read_text()) if args.patches is not None else None + ) + if args.legacy_map is not None: + migrate_package(args.path, parse_lib_path(args.path), args.legacy_map) + elif args.path.is_dir(): patch_directory(args.path) else: - patch_file(args.path) + patch_file(args.path, patches_document=document) return 0 except ValueError as e: print(f"Error: {e}", file=sys.stderr) diff --git a/scripts/update_lib/cpython315-retirements.json b/scripts/update_lib/cpython315-retirements.json new file mode 100644 index 00000000000..30f82be9723 --- /dev/null +++ b/scripts/update_lib/cpython315-retirements.json @@ -0,0 +1,41 @@ +{ + "Lib/_dummy_thread.py": null, + "Lib/dummy_threading.py": null, + "Lib/sre_compile.py": null, + "Lib/sre_constants.py": null, + "Lib/sre_parse.py": null, + "Lib/test/_test_gc_fast_cycles.py": null, + "Lib/test/audiotest.au": null, + "Lib/test/badsyntax_3131.py": "Lib/test/tokenizedata/badsyntax_3131.py", + "Lib/test/badsyntax_pep3120.py": "Lib/test/tokenizedata/badsyntax_pep3120.py", + "Lib/test/dataclass_module_1.py": "Lib/test/test_dataclasses/dataclass_module_1.py", + "Lib/test/dataclass_module_1_str.py": "Lib/test/test_dataclasses/dataclass_module_1_str.py", + "Lib/test/dataclass_module_2.py": "Lib/test/test_dataclasses/dataclass_module_2.py", + "Lib/test/dataclass_module_2_str.py": "Lib/test/test_dataclasses/dataclass_module_2_str.py", + "Lib/test/dataclass_textanno.py": "Lib/test/test_dataclasses/dataclass_textanno.py", + "Lib/test/double_const.py": "Lib/test/test_import/data/double_const.py", + "Lib/test/dtracedata/line.d": null, + "Lib/test/dtracedata/line.d.expected": null, + "Lib/test/dtracedata/line.py": null, + "Lib/test/floating_points.txt": "Lib/test/mathdata/floating_points.txt", + "Lib/test/formatfloat_testcases.txt": "Lib/test/mathdata/formatfloat_testcases.txt", + "Lib/test/recursion.tar": "Lib/test/archivetestdata/recursion.tar", + "Lib/test/test_cprofile.py": "Lib/test/test_profiling/test_tracing_profiler.py", + "Lib/test/test_ctypes/test_unions.py": "Lib/test/test_ctypes/test_structunion.py", + "Lib/test/test_doctest2.py": "Lib/test/test_doctest/test_doctest2.py", + "Lib/test/test_dummy_thread.py": null, + "Lib/test/test_dummy_threading.py": null, + "Lib/test/testtar.tar": "Lib/test/archivetestdata/testtar.tar", + "Lib/test/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt": "Lib/test/tokenizedata/tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt", + "Lib/test/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt": "Lib/test/tokenizedata/tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt", + "Lib/test/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt": "Lib/test/tokenizedata/tokenize_tests-utf8-coding-cookie-and-no-utf8-bom-sig.txt", + "Lib/test/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt": "Lib/test/tokenizedata/tokenize_tests-utf8-coding-cookie-and-utf8-bom-sig.txt", + "Lib/test/tokenize_tests.txt": "Lib/test/tokenizedata/tokenize_tests.txt", + "Lib/test/zip_cp437_header.zip": "Lib/test/archivetestdata/zip_cp437_header.zip", + "Lib/test/zipdir.zip": "Lib/test/archivetestdata/zipdir.zip", + "Lib/test/ziptestdata/README.md": "Lib/test/archivetestdata/README.md", + "Lib/test/ziptestdata/exe_with_z64": "Lib/test/archivetestdata/exe_with_z64", + "Lib/test/ziptestdata/exe_with_zip": "Lib/test/archivetestdata/exe_with_zip", + "Lib/test/ziptestdata/header.sh": "Lib/test/archivetestdata/header.sh", + "Lib/test/ziptestdata/testdata_module_inside_zip.py": "Lib/test/archivetestdata/testdata_module_inside_zip.py" +} diff --git a/scripts/update_lib/deps.py b/scripts/update_lib/deps.py index da49490c7ec..28db5930389 100644 --- a/scripts/update_lib/deps.py +++ b/scripts/update_lib/deps.py @@ -329,7 +329,6 @@ def clear_import_graph_caches() -> None: ], }, "re": { - "hard_deps": ["sre_compile.py", "sre_constants.py", "sre_parse.py"], "test": [ "test_re.py", "re_tests.py", @@ -570,10 +569,7 @@ def clear_import_graph_caches() -> None: "io": { "hard_deps": ["_pyio.py"], "test": [ - "test_io.py", - "test_bufio.py", - "test_fileio.py", - "test_memoryio.py", + "test_io", ], }, "dbm": { @@ -607,8 +603,7 @@ def clear_import_graph_caches() -> None: "file": { "lib": [], "test": [ - "test_file.py", - "test_largefile.py", + "test_io", ], }, "fcntl": { @@ -651,6 +646,7 @@ def clear_import_graph_caches() -> None: "lib": [], "test": [ "test_math.py", + "test_math_integer.py", "test_math_property.py", ], }, @@ -663,7 +659,7 @@ def clear_import_graph_caches() -> None: }, "zipfile": { "test": [ - "test_zipfile.py", + "test_zipfile/", "test_zipfile64.py", ], }, @@ -676,7 +672,7 @@ def clear_import_graph_caches() -> None: "profile": { "test": [ "test_profile.py", - "test_cprofile.py", + "test_profiling/test_tracing_profiler.py", ], }, "string": { @@ -691,7 +687,7 @@ def clear_import_graph_caches() -> None: "test_popen.py", ], }, - "pyrepl": { + "_pyrepl": { "test": [ "test_pyrepl", "test_repl.py", @@ -807,6 +803,9 @@ def resolve_test_to_lib(test_name: str) -> str | None: # - hard_deps: files to migrate (tightly coupled, must be migrated together) # - data: directories to copy without migration TEST_DEPENDENCIES = { + "test_datetime": { + "hard_deps": ["datetimetester.py"], + }, # Audio tests "test_winsound": { "data": ["audiodata"], diff --git a/scripts/update_lib/file_utils.py b/scripts/update_lib/file_utils.py index cb86ee2e664..1aa7a54aa1a 100644 --- a/scripts/update_lib/file_utils.py +++ b/scripts/update_lib/file_utils.py @@ -15,6 +15,7 @@ import ast import filecmp import pathlib +import warnings from collections.abc import Callable, Iterator # === I/O utilities === @@ -31,7 +32,10 @@ def safe_read_text(path: pathlib.Path) -> str | None: def safe_parse_ast(content: str) -> ast.Module | None: """Parse Python content into AST, returning None on syntax error.""" try: - return ast.parse(content) + # Test fixtures may deliberately contain syntax that emits warnings. + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) + return ast.parse(content) except SyntaxError: return None @@ -69,7 +73,10 @@ def parse_lib_path(path: pathlib.Path | str) -> pathlib.Path: raise ValueError(f"Path must contain '/Lib/' or '\\Lib\\' (got: {path})") idx = path_str.index(lib_marker) - return pathlib.Path(path_str[idx + 1 :]) + relative = pathlib.Path(path_str[idx + 1 :]) + if ".." in relative.parts: + raise ValueError(f"Path must not escape or traverse within Lib/ (got: {path})") + return relative def is_lib_path(path: pathlib.Path) -> bool: @@ -218,11 +225,29 @@ def get_cpython_dir(src_path: pathlib.Path) -> pathlib.Path: # === Comparison utilities === +def _files_are_same(left: pathlib.Path, right: pathlib.Path) -> bool: + # Recheck contents even when size and timestamps match, including after a + # previous comparison. filecmp caches results by those metadata alone. + with left.open("rb") as left_file, right.open("rb") as right_file: + while True: + chunk = left_file.read(65536) + if chunk != right_file.read(65536): + return False + if not chunk: + return True + + def _dircmp_is_same(dcmp: filecmp.dircmp) -> bool: """Recursively check if two directories are identical.""" - if dcmp.diff_files or dcmp.left_only or dcmp.right_only: + if dcmp.left_only or dcmp.right_only or dcmp.common_funny: return False + for name in dcmp.common_files: + if not _files_are_same( + pathlib.Path(dcmp.left) / name, pathlib.Path(dcmp.right) / name + ): + return False + for subdir in dcmp.subdirs.values(): if not _dircmp_is_same(subdir): return False @@ -232,14 +257,17 @@ def _dircmp_is_same(dcmp: filecmp.dircmp) -> bool: def compare_paths(cpython_path: pathlib.Path, local_path: pathlib.Path) -> bool: """Compare a CPython path with a local path (file or directory).""" - if not local_path.exists(): + if not cpython_path.exists() or not local_path.exists(): return False - if cpython_path.is_file(): - return filecmp.cmp(cpython_path, local_path, shallow=False) - - dcmp = filecmp.dircmp(cpython_path, local_path) - return _dircmp_is_same(dcmp) + try: + if cpython_path.is_file(): + return local_path.is_file() and _files_are_same(cpython_path, local_path) + if not cpython_path.is_dir() or not local_path.is_dir(): + return False + return _dircmp_is_same(filecmp.dircmp(cpython_path, local_path)) + except OSError: + return False def compare_file_contents( diff --git a/scripts/update_lib/patch_spec.py b/scripts/update_lib/patch_spec.py index 996b78bfa18..95be59524a9 100644 --- a/scripts/update_lib/patch_spec.py +++ b/scripts/update_lib/patch_spec.py @@ -11,10 +11,12 @@ import ast import collections import contextlib +import doctest import enum import re import textwrap import typing +from pathlib import Path if typing.TYPE_CHECKING: from collections.abc import Iterator @@ -121,7 +123,9 @@ def try_from_ast_node( # If our ut_method has args then, # we need to search for a constant that contains our `COMMENT`. # Otherwise we need to search it in the raw source code :/ - if ut_method.has_args(): + if ut_method.has_args() and not ( + ut_method is UtMethod.Skip and isinstance(node, ast.Attribute) + ): reason = next( ( inner_node.value @@ -197,7 +201,10 @@ def visit_ClassDef(self, node: ast.ClassDef): patch = patch._replace(test_name="__self__") self.patches.append(patch) - self.generic_visit(node) + # Keep conditional methods in this namespace, but do not enter + # nested classes or the bodies of methods. + for item in _iter_class_methods(node): + self.visit(item) class PatchEntry(typing.NamedTuple): @@ -228,22 +235,35 @@ def iter_patch_entries( yield from visitor.patches -def iter_tests( - tree: ast.Module, -) -> "Iterator[tuple[ast.ClassDef, ast.FunctionDef | ast.AsyncFunctionDef]]": - for key, nodes in ast.iter_fields(tree): - if key != "body": - continue +def _iter_module_classes(node: ast.AST) -> "Iterator[ast.ClassDef]": + """Find module-scope classes, including conditional definitions. - for cls_node in nodes: - if not isinstance(cls_node, ast.ClassDef): - continue + Function-local and class-nested definitions have different namespaces and + cannot be addressed by the patch format's unqualified class names. + """ + for child in ast.iter_child_nodes(node): + if isinstance(child, ast.ClassDef): + yield child + elif not isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + yield from _iter_module_classes(child) - for fn_node in cls_node.body: - if not isinstance(fn_node, (ast.FunctionDef, ast.AsyncFunctionDef)): - continue - yield (cls_node, fn_node) +def _iter_class_methods( + node: ast.AST, +) -> "Iterator[ast.FunctionDef | ast.AsyncFunctionDef]": + for child in ast.iter_child_nodes(node): + if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)): + yield child + elif not isinstance(child, (ast.ClassDef, ast.Lambda)): + yield from _iter_class_methods(child) + + +def iter_tests( + tree: ast.Module, +) -> "Iterator[tuple[ast.ClassDef, ast.FunctionDef | ast.AsyncFunctionDef]]": + for cls_node in _iter_module_classes(tree): + for fn_node in _iter_class_methods(cls_node): + yield (cls_node, fn_node) def iter_patches(contents: str) -> "Iterator[PatchEntry]": @@ -286,24 +306,43 @@ def _iter_patch_lines( # Track class bases for inherited async method lookup class_bases: dict[str, list[str]] = {} all_classes = set() - all_class_nodes = [] - for node in tree.body: - if not isinstance(node, ast.ClassDef): - continue - + all_class_nodes = list(_iter_module_classes(tree)) + # Only names used to place a patch (including inherited methods) need a + # unique definition. Conditional, unpatched helpers are common upstream. + relevant_classes = set(patches) + while True: + ancestors = { + base.id + for node in all_class_nodes + if node.name in relevant_classes + for base in node.bases + if isinstance(base, ast.Name) + } + expanded = relevant_classes | ancestors + if expanded == relevant_classes: + break + relevant_classes = expanded + for node in all_class_nodes: + if node.name in all_classes and node.name in relevant_classes: + raise ValueError(f"Ambiguous module-scope class name: {node.name}") all_classes.add(node.name) - all_class_nodes.append(node) + method_counts = collections.Counter( + item.name for item in _iter_class_methods(node) + ) + for method in patches.get(node.name, {}): + if method_counts[method] > 1: + raise ValueError(f"Ambiguous method name: {node.name}.{method}") - for node in tree.body: + for node in all_class_nodes: if isinstance(node, ast.ClassDef): - cache[node.name] = node.end_lineno + cache[node.name] = (node.end_lineno, node.col_offset + len(DEFAULT_INDENT)) class_bases[node.name] = [ base.id for base in node.bases if isinstance(base, ast.Name) and base.id in all_classes ] cls_async: set[str] = set() - for item in node.body: + for item in _iter_class_methods(node): if isinstance(item, ast.AsyncFunctionDef): cls_async.add(item.name) if cls_async: @@ -319,10 +358,11 @@ def _iter_patch_lines( # Phase 2: Iterate and mark inherited tests for cls_name, tests in sorted(patches.items()): - lineno = cache.get(cls_name) - if not lineno: + location = cache.get(cls_name) + if not location: print(f"WARNING: {cls_name} does not exist in remote file", file=sys.stderr) continue + lineno, indent = location for test_name, specs in sorted(tests.items()): if test_name == "__self__": @@ -356,7 +396,7 @@ async def {test_name}(self): def {test_name}(self): {DEFAULT_INDENT}return super().{test_name}() """.rstrip() - yield (lineno, textwrap.indent(patch_lines, DEFAULT_INDENT)) + yield (lineno, textwrap.indent(patch_lines, " " * indent)) # Phase 3: Mark the class itself for cls_node in all_class_nodes: @@ -393,8 +433,36 @@ def _find_import_insert_line(tree: ast.Module) -> int: return 0 +def _expand_inline_class_suites(contents: str, patches: Patches) -> str: + """Make room for inherited overrides without changing existing class bodies.""" + tree = ast.parse(contents) + lines = contents.splitlines() + replacements = [] + for node in _iter_module_classes(tree): + methods = {method.name for method in _iter_class_methods(node)} + inherited = set(patches.get(node.name, {})) - methods - {"__self__"} + if not inherited: + continue + first = node.body[0] + line = lines[first.lineno - 1].encode("utf-8") + header = line[: first.col_offset].decode("utf-8") + if not header.strip(): + continue + body = line[first.col_offset :].decode("utf-8") + replacements.append( + ( + first.lineno - 1, + header.rstrip() + "\n" + " " * (node.col_offset + 4) + body, + ) + ) + for index, replacement in sorted(replacements, reverse=True): + lines[index] = replacement + return "\n".join(lines) + "\n" + + def apply_patches(contents: str, patches: Patches) -> str: """Apply patches to file contents and return modified contents.""" + contents = _expand_inline_class_suites(contents, patches) tree = ast.parse(contents) lines = contents.splitlines() @@ -415,6 +483,7 @@ def apply_patches(contents: str, patches: Patches) -> str: lines.insert(lineno, patch) joined = "\n".join(lines) + ast.parse(joined) return f"{joined}\n" @@ -480,3 +549,223 @@ def temp_attr(obj: object, attr: str, value: object): yield obj finally: setattr(obj, attr, old) + + +def _conditional_retirements(document, old_content): + entries = document.get("retire_conditional", []) + if not isinstance(entries, list): + raise ValueError("Conditional retirements must be a list") + if not entries: + return {} + if not isinstance(old_content, str): + raise ValueError("Conditional retirements require original source") + tree = ast.parse(old_content) + lines = old_content.splitlines(keepends=True) + result = {} + for entry in entries: + if not isinstance(entry, dict) or set(entry) != { + "class", + "method", + "decorator", + }: + raise ValueError("Invalid conditional retirement metadata") + if not all(isinstance(value, str) and value for value in entry.values()): + raise ValueError("Conditional retirement fields must be nonempty strings") + key = (entry["class"], entry["method"]) + if key in result: + raise ValueError("Duplicate conditional retirement") + classes = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.ClassDef) and node.name == key[0] + ] + if len(classes) != 1: + raise ValueError("Missing or ambiguous conditional retirement class") + methods = [ + node for node in _iter_class_methods(classes[0]) if node.name == key[1] + ] + if len(methods) != 1: + raise ValueError("Missing or ambiguous conditional retirement method") + matches = [ + node + for node in methods[0].decorator_list + if "".join(lines[node.lineno - 1 : node.end_lineno]) == entry["decorator"] + ] + if len(matches) != 1: + raise ValueError( + "Original conditional decorator does not match exactly once" + ) + marker = PatchSpec.try_from_ast_node(matches[0], old_content.splitlines()) + if marker is None or marker.ut_method not in ( + UtMethod.ExpectedFailureIf, + UtMethod.Skip, + ): + raise ValueError( + "Only explicit expectedFailureIf and skip retirements are supported" + ) + result[key] = marker + return result + + +def select_remaining_patches( + current, document, relative_path: Path, *, old_content=None +): + if not isinstance(document, dict) or ( + not {"target", "patches"} <= set(document) + or not set(document) + <= {"target", "patches", "doctests", "retire_conditional", "blocks"} + ): + raise ValueError("Expected target and patches metadata") + if ( + relative_path.parts[:1] != ("Lib",) + or relative_path.suffix != ".py" + or document["target"] != relative_path.as_posix() + ): + raise ValueError("Patch target does not match the Lib file") + if "doctests" in document and not isinstance(document["doctests"], dict): + raise ValueError("Doctests metadata must be an object") + try: + remaining = patches_from_json(document["patches"]) + except (TypeError, KeyError, AttributeError, ValueError) as error: + raise ValueError("Invalid remaining marker metadata") from error + retirements = _conditional_retirements(document, old_content) + consumed = set() + for cls, methods in remaining.items(): + if cls not in current or any(method not in current[cls] for method in methods): + raise ValueError("Marker override cannot add targets") + for cls, methods in current.items(): + for method, existing in methods.items(): + pending = list(existing) + omitted = [] + for marker in remaining.get(cls, {}).get(method, []): + original = marker + if ( + original not in pending + and marker.ut_method == UtMethod.ExpectedFailureIf + and marker.cond + ): + # A condition only retires part of an unconditional failure. + original = marker._replace( + ut_method=UtMethod.ExpectedFailure, cond=None + ) + if original not in pending: + raise ValueError( + "Marker override cannot add, change, or reorder markers" + ) + index = pending.index(original) + omitted.extend(pending[:index]) + pending = pending[index + 1 :] + omitted.extend(pending) + for marker in omitted: + if marker.ut_method == UtMethod.ExpectedFailure: + continue + key = (cls, method) + if ( + key in consumed + or retirements.get(key) != marker + or existing.count(marker) != 1 + ): + raise ValueError( + "Conditional removal requires an exact explicit retirement" + ) + consumed.add(key) + if consumed != set(retirements): + raise ValueError("Conditional retirement was not removed exactly once") + return remaining + + +EXPECTED_FAILURE = doctest.register_optionflag("EXPECTED_FAILURE") +CANONICAL_LOAD_TESTS = """def load_tests(loader, tests, pattern): + tests.addTest(doctest.DocTestSuite()) + return tests""" +PATCHED_LOAD_TESTS = """def load_tests(loader, tests, pattern): + from test.support.rustpython import DocTestChecker # TODO: RUSTPYTHON + tests.addTest(doctest.DocTestSuite(checker=DocTestChecker())) # TODO: RUSTPYTHON + return tests""" + + +def _examples(contents): + tree = ast.parse(contents) + if not tree.body or not isinstance(tree.body[0], ast.Expr): + raise ValueError("Missing module doctest") + doc = tree.body[0].value + if not isinstance(doc, ast.Constant) or not isinstance(doc.value, str): + raise ValueError("Missing module doctest") + # Raw docstring offsets map directly to source lines, unlike cleaned docs. + return tree, doc, doctest.DocTestParser().get_examples(doc.value) + + +def apply_doctest_metadata(old, canonical, metadata): + """Preserve only listed guards, without carrying old expected output.""" + if not isinstance(metadata, dict) or any( + not isinstance(source, str) + or not isinstance(reason, str) + or "\n" in reason + or "\r" in reason + for source, reason in metadata.items() + ): + raise ValueError("Doctest metadata must map exact input to single-line reasons") + _, _, old_examples = _examples(old) + tree, doc, examples = _examples(canonical) + lines = canonical.splitlines(keepends=True) + for source in metadata: + old_matches = [ + example + for example in old_examples + if re.sub(r"\s+# TODO: RUSTPYTHON[^\n]*", "", example.source) == source + ] + if len(old_matches) != 1 or not old_matches[0].options.get(EXPECTED_FAILURE): + raise ValueError("Missing or ambiguous existing doctest guard") + matches = [example for example in examples if example.source == source] + if len(matches) != 1 or matches[0].options: + raise ValueError("Missing, ambiguous, or already marked canonical doctest") + index = doc.lineno - 1 + matches[0].lineno + line = lines[index] + if ( + ">>>" not in line + or line.split(">>>", 1)[1].strip() != source.splitlines()[0] + ): + raise ValueError("Unrecognized canonical doctest prompt") + lines[index] = ( + line.rstrip("\n") + + " # TODO: RUSTPYTHON; " + + metadata[source] + + " # doctest: +EXPECTED_FAILURE\n" + ) + + if not metadata: + return canonical + + loaders = [ + node + for node in ast.walk(tree) + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + and node.name == "load_tests" + ] + if len(loaders) != 1 or loaders[0] not in tree.body: + raise ValueError("Missing or ambiguous doctest loader") + if ast.get_source_segment(canonical, loaders[0]) != CANONICAL_LOAD_TESTS: + raise ValueError("Changed canonical doctest loader") + result = "".join(lines) + if result.count(CANONICAL_LOAD_TESTS) != 1: + raise ValueError("Ambiguous canonical doctest loader text") + return result.replace(CANONICAL_LOAD_TESTS, PATCHED_LOAD_TESTS, 1) + + +def extract_doctest_guards(contents: str) -> dict[str, str]: + """Extract guarded module-docstring inputs without executing examples.""" + tree = ast.parse(contents) + if not tree.body or not isinstance(tree.body[0], ast.Expr): + return {} + doc = tree.body[0].value + if not isinstance(doc, ast.Constant) or not isinstance(doc.value, str): + return {} + guards = {} + for example in doctest.DocTestParser().get_examples(doc.value): + if not example.options.get(EXPECTED_FAILURE): + continue + source = re.sub(r"\s+# TODO: RUSTPYTHON[^\n]*", "", example.source) + if source in guards: + raise ValueError("Ambiguous existing doctest guard") + guards[source] = example.source + return guards diff --git a/scripts/update_lib/tests/test_copy_lib.py b/scripts/update_lib/tests/test_copy_lib.py index aca00cb18f3..69b430af985 100644 --- a/scripts/update_lib/tests/test_copy_lib.py +++ b/scripts/update_lib/tests/test_copy_lib.py @@ -1,5 +1,6 @@ """Tests for copy_lib.py - library copying with dependencies.""" +import contextlib import pathlib import tempfile import unittest @@ -57,10 +58,114 @@ def test_removes_existing_before_copy(self): self.assertEqual(dst.read_text(), "new content") + def test_directory_copy_excludes_bytecode_cache_directories(self): + from update_lib.cmd_copy_lib import _copy_single + + with tempfile.TemporaryDirectory() as tmpdir: + root = pathlib.Path(tmpdir) + src = root / "source" + dst = root / "destination" + for relative in ("__pycache__", "package/__pycache__", "assets"): + (src / relative).mkdir(parents=True) + files = { + "__init__.py": b"source\n", + "package/module.py": b"nested source\n", + "assets/data.bin": b"\x00\xffasset", + "assets/__pycache__": b"ordinary file, not a directory", + "assets/fixture.pyc": b"canonical bytecode fixture", + "__pycache__/module.cpython-315.pyc": b"stale cache", + "package/__pycache__/module.cpython-315.pyc": b"nested cache", + } + for relative, content in files.items(): + (src / relative).write_bytes(content) + + _copy_single(src, dst, verbose=False) + + expected = { + relative: content + for relative, content in files.items() + if "__pycache__" not in pathlib.Path(relative).parts[:-1] + } + actual = { + path.relative_to(dst).as_posix(): path.read_bytes() + for path in dst.rglob("*") + if path.is_file() + } + self.assertEqual(actual, expected) + self.assertFalse((dst / "__pycache__").exists()) + self.assertFalse((dst / "package/__pycache__").exists()) + for relative, content in files.items(): + self.assertEqual((src / relative).read_bytes(), content) + class TestCopyLib(unittest.TestCase): """Tests for copy_lib function.""" + def test_nested_data_file_preserves_siblings(self): + from update_lib.cmd_copy_lib import copy_lib + + for name in ("hierarchy.txt", "fixture.bin", "README"): + with self.subTest(name=name), tempfile.TemporaryDirectory() as tmpdir: + root = pathlib.Path(tmpdir) + source = root / "cpython/Lib/test/data" / name + source.parent.mkdir(parents=True) + source.write_bytes(b"canonical\x00\xff\n") + (source.parent / "other.txt").write_bytes(b"unselected source") + target = root / "Lib/test/data" / name + target.parent.mkdir(parents=True) + target.write_bytes(b"old") + sibling = root / "Lib/test/test_local.py" + sibling.write_bytes(b"local guards\n") + with contextlib.chdir(root): + copy_lib(source, verbose=False) + self.assertEqual(target.read_bytes(), source.read_bytes()) + self.assertEqual(sibling.read_bytes(), b"local guards\n") + self.assertFalse((target.parent / "other.txt").exists()) + + def test_missing_data_file_does_not_copy_containing_package(self): + from update_lib.cmd_copy_lib import copy_lib + + with tempfile.TemporaryDirectory() as tmpdir: + root = pathlib.Path(tmpdir) + source = root / "cpython/Lib/test/missing.txt" + source.parent.mkdir(parents=True) + (source.parent / "other.py").write_text("unselected source") + sibling = root / "Lib/test/test_local.py" + sibling.parent.mkdir(parents=True) + sibling.write_bytes(b"local guards\n") + with contextlib.chdir(root), self.assertRaises(FileNotFoundError): + copy_lib(source, verbose=False) + self.assertEqual(sibling.read_bytes(), b"local guards\n") + self.assertFalse((sibling.parent / "other.py").exists()) + + def test_python_module_still_copies_hard_dependencies(self): + from update_lib.cmd_copy_lib import copy_lib + + with tempfile.TemporaryDirectory() as tmpdir: + root = pathlib.Path(tmpdir) + source = root / "cpython/Lib" + source.mkdir(parents=True) + for name in ("pickle.py", "_compat_pickle.py"): + (source / name).write_text(name) + with contextlib.chdir(root): + copy_lib(source / "pickle.py", verbose=False) + for name in ("pickle.py", "_compat_pickle.py"): + self.assertEqual((root / "Lib" / name).read_text(), name) + + def test_package_still_copies_directory(self): + from update_lib.cmd_copy_lib import copy_lib + + with tempfile.TemporaryDirectory() as tmpdir: + root = pathlib.Path(tmpdir) + source = root / "cpython/Lib/json" + source.mkdir(parents=True) + for name in ("__init__.py", "decoder.py"): + (source / name).write_text(name) + with contextlib.chdir(root): + copy_lib(source, verbose=False) + for name in ("__init__.py", "decoder.py"): + self.assertEqual((root / "Lib/json" / name).read_text(), name) + def test_raises_on_path_without_lib(self): """Test that copy_lib raises ValueError when path doesn't contain /Lib/.""" from update_lib.cmd_copy_lib import copy_lib diff --git a/scripts/update_lib/tests/test_deps.py b/scripts/update_lib/tests/test_deps.py index d97af2867aa..40deecd055d 100644 --- a/scripts/update_lib/tests/test_deps.py +++ b/scripts/update_lib/tests/test_deps.py @@ -313,6 +313,26 @@ def test_filters_nonexistent(self): class TestDircmpIsSame(unittest.TestCase): """Tests for _dircmp_is_same function.""" + def test_matching_metadata(self): + import os + + from update_lib.file_utils import compare_paths + + with tempfile.TemporaryDirectory() as tmpdir: + left, right = (pathlib.Path(tmpdir) / name for name in ("left", "right")) + for directory in (left, right): + (directory / "nested").mkdir(parents=True) + (directory / "nested/module.py").write_bytes(b"x = 1\n") + source, destination = (p / "nested/module.py" for p in (left, right)) + timestamp = source.stat().st_mtime_ns + os.utime(destination, ns=(timestamp, timestamp)) + self.assertTrue(compare_paths(source, destination)) + self.assertTrue(compare_paths(left, right)) + destination.write_bytes(b"x = 2\n") + os.utime(destination, ns=(timestamp, timestamp)) + self.assertFalse(compare_paths(source, destination)) + self.assertFalse(compare_paths(left, right)) + def test_identical_directories(self): """Test that identical directories return True.""" import filecmp diff --git a/scripts/update_lib/tests/test_migrate.py b/scripts/update_lib/tests/test_migrate.py index 0cc247ba841..60cd9bf8465 100644 --- a/scripts/update_lib/tests/test_migrate.py +++ b/scripts/update_lib/tests/test_migrate.py @@ -1,20 +1,422 @@ """Tests for migrate.py - file migration operations.""" +import contextlib +import hashlib +import io +import json import pathlib import tempfile import unittest +from pathlib import Path +from unittest.mock import patch from update_lib.cmd_migrate import ( + _preserve_block, + main, + migrate_new_file, + migrate_package, patch_directory, patch_file, patch_single_content, + retire_legacy_paths, ) -from update_lib.patch_spec import COMMENT +from update_lib.patch_spec import ( + CANONICAL_LOAD_TESTS, + COMMENT, + PatchSpec, + UtMethod, + extract_patches, + iter_patches, + patches_to_json, + select_remaining_patches, +) + + +class TestNewFileAdaptations(unittest.TestCase): + canonical = ( + "import ctypes\n" + "api = ctypes.pythonapi.example\n" + "class Example:\n" + " def test_api(self):\n" + " assert api() == 1\n" + ) + + @contextlib.contextmanager + def files(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source = root / "cpython/Lib/test/test_example.py" + source.parent.mkdir(parents=True) + source.write_text(self.canonical) + repository = root / "rustpython" + target = repository / "Lib/test/test_example.py" + document = { + "target": "Lib/test/test_example.py", + "source_sha256": hashlib.sha256(source.read_bytes()).hexdigest(), + "blocks": [ + [ + "api = ctypes.pythonapi.example", + "api = getattr(ctypes.pythonapi, 'example')", + ] + ], + } + with patch( + "update_lib.cmd_migrate.__file__", + str(repository / "scripts/update_lib/cmd_migrate.py"), + ): + yield source, target, document + + def test_new_file_and_import_binding_scope(self): + with self.files() as (source, target, document): + document["blocks"].append(["import ctypes", "import ctypes\nimport sys"]) + migrate_new_file(source, document) + self.assertEqual( + target.read_text(), + self.canonical.replace( + "import ctypes", "import ctypes\nimport sys" + ).replace( + "ctypes.pythonapi.example", "getattr(ctypes.pythonapi, 'example')" + ), + ) + self.assertEqual(source.read_text(), self.canonical) + + def test_cli_is_explicit_and_existing_target_is_never_overwritten(self): + with self.files() as (source, target, document): + metadata = source.parent / "adapters.json" + metadata.write_text(json.dumps(document)) + self.assertEqual( + main([str(source), "--new-file-adaptations", str(metadata)]), 0 + ) + previous = target.read_bytes() + with contextlib.redirect_stderr(io.StringIO()): + self.assertEqual( + main([str(source), "--new-file-adaptations", str(metadata)]), 1 + ) + self.assertEqual( + main( + [ + str(source), + "--new-file-adaptations", + str(metadata), + "--patches", + str(metadata), + ] + ), + 1, + ) + self.assertEqual(target.read_bytes(), previous) + + def test_hash_path_schema_and_block_validation_before_write(self): + for mutation in ( + {"source_sha256": "0" * 64}, + {"target": "Lib/test/other.py"}, + {"target": "Lib/test/../test_example.py"}, + {"target": "/Lib/test/test_example.py"}, + {"target": "Lib\\test\\test_example.py"}, + {"target": "Lib//test/test_example.py"}, + {"unexpected": True}, + {"blocks": []}, + {"blocks": [["", "x"]]}, + {"blocks": [["not present", "x"]]}, + {"blocks": [["api", "x"]]}, + { + "blocks": [ + ["import ctypes", "import sys"], + ["import ctypes", "import os"], + ] + }, + {"blocks": [["import ctypes", "import sys"], ["ctypes\napi", "sys\napi"]]}, + {"blocks": [["api = ctypes.pythonapi.example", "api = ("]]}, + ): + with ( + self.subTest(mutation=mutation), + self.files() as (source, target, document), + ): + document.update(mutation) + with self.assertRaises(ValueError): + migrate_new_file(source, document) + self.assertFalse(target.exists()) + + def test_class_assertion_binding_target_and_statement_order_are_protected(self): + for old, new in ( + ("assert api() == 1", "assert api() == 2"), + ("class Example", "class Different"), + ("api = ctypes.pythonapi.example", "other = ctypes.pythonapi.example"), + ("import ctypes", "import ctypes\nraise RuntimeError"), + ("class Example:", "@unittest.skip('unsupported')\nclass Example:"), + ): + with self.subTest(old=old), self.files() as (source, target, document): + document["blocks"] = [[old, new]] + with self.assertRaisesRegex(ValueError, "only imports and bindings"): + migrate_new_file(source, document) + self.assertFalse(target.exists()) + + def test_symlink_source_and_destination_parent_are_rejected(self): + with self.files() as (source, target, document): + original = source.with_name("original.py") + source.rename(original) + source.symlink_to(original) + with self.assertRaises(ValueError): + migrate_new_file(source, document) + self.assertFalse(target.exists()) + with self.files() as (source, target, document): + target.parent.parent.parent.mkdir(parents=True) + outside = source.parent / "outside" + outside.mkdir() + target.parent.parent.symlink_to(outside, target_is_directory=True) + with self.assertRaises(ValueError): + migrate_new_file(source, document) + self.assertEqual(list(outside.iterdir()), []) + + +class TestRetireLegacyPaths(unittest.TestCase): + @contextlib.contextmanager + def trees(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source = root / "cpython" / "Lib" / "test" + source.mkdir(parents=True) + local = root / "rustpython" + (local / "Lib" / "test").mkdir(parents=True) + with contextlib.chdir(local): + yield source + + def test_flat_map_retires_only_explicit_paths_without_parsing(self): + with self.trees() as source: + mapping = {} + for name, content in ( + ("bad.py", b"invalid syntax !"), + ("data.bin", b"\xff\x00"), + ): + (source / "new").mkdir(exist_ok=True) + (source / "new" / name).write_bytes(content) + Path("Lib/test/new").mkdir(exist_ok=True) + Path("Lib/test/new", name).write_bytes(content) + Path("Lib/test", name).write_bytes(content) + mapping[f"Lib/test/{name}"] = f"Lib/test/new/{name}" + Path("Lib/test/removed.py").write_text("old = True\n") + mapping["Lib/test/removed.py"] = None + Path("Lib/test/original.py").write_text("preserve = True\n") + Path("map.json").write_text(json.dumps(mapping)) + + self.assertEqual(main([str(source), "--legacy-map", "map.json"]), 0) + + for old in mapping: + self.assertFalse(Path(old).exists()) + self.assertEqual( + Path("Lib/test/original.py").read_text(), "preserve = True\n" + ) + self.assertEqual(Path("Lib/test/new/data.bin").read_bytes(), b"\xff\x00") + self.assertEqual( + Path("Lib/test/new/bad.py").read_bytes(), b"invalid syntax !" + ) + + def test_late_missing_or_adapted_replacement_preserves_all_legacy_files(self): + for replacement in (None, b"local adaptation"): + with self.subTest(replacement=replacement), self.trees() as source: + Path("Lib/test/first.py").write_text("first") + Path("Lib/test/second.py").write_text("second") + (source / "new.py").write_bytes(b"canonical") + if replacement is not None: + Path("Lib/test/new.py").write_bytes(replacement) + with self.assertRaisesRegex(ValueError, "Replacement is not canonical"): + retire_legacy_paths( + source, + { + "Lib/test/first.py": None, + "Lib/test/second.py": "Lib/test/new.py", + }, + ) + self.assertTrue(Path("Lib/test/first.py").exists()) + self.assertTrue(Path("Lib/test/second.py").exists()) + + def test_file_still_upstream_is_not_retired(self): + with self.trees() as source: + (source / "active.py").write_text("active") + Path("Lib/test/active.py").write_text("active") + with self.assertRaisesRegex(ValueError, "upstream-absent"): + retire_legacy_paths(source, {"Lib/test/active.py": None}) + self.assertTrue(Path("Lib/test/active.py").exists()) + + def test_outside_paths_and_missing_source_are_rejected(self): + with self.trees() as source: + Path("Lib/test/removed.py").write_text("preserve") + for name in ("outside.py", "Lib/../outside.py", "/tmp/outside.py"): + with self.subTest(name=name), self.assertRaises(ValueError): + retire_legacy_paths(source, {name: None}) + for missing in ( + source / "missing", + source.parent.parent / "missing/Lib/test", + ): + with ( + self.subTest(missing=missing), + self.assertRaisesRegex(ValueError, "Canonical Lib"), + ): + retire_legacy_paths(missing, {"Lib/test/removed.py": None}) + self.assertEqual(Path("Lib/test/removed.py").read_text(), "preserve") class TestPatchSingleContent(unittest.TestCase): """Tests for patch_single_content function.""" + def test_explicit_blocks_preserve_existing_changes(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source, target = root / "canonical.py", root / "Lib/test/test_example.py" + target.parent.mkdir(parents=True) + source.write_text("import unittest\nvalue = 2\n") + target.write_text("import sys\nimport unittest\nvalue = 1\n") + document = { + "target": "Lib/test/test_example.py", + "patches": {}, + "blocks": [["import unittest\n", "import sys\nimport unittest\n"]], + } + with patch( + "update_lib.cmd_migrate.__file__", + str(root / "scripts/update_lib/cmd_migrate.py"), + ): + self.assertEqual( + patch_single_content(source, target), source.read_text() + ) + result = patch_single_content(source, target, document) + self.assertEqual(result, "import sys\nimport unittest\nvalue = 2\n") + for blocks in ( + None, + [[]], + [["import unittest\n", "import missing\n"]], + [["value = 2\n", "import sys\n"], ["import sys\n", "value = 1\n"]], + ): + with self.subTest(blocks=blocks), self.assertRaises(ValueError): + patch_file( + source, + target, + verbose=False, + patches_document={**document, "blocks": blocks}, + ) + self.assertEqual( + target.read_text(), "import sys\nimport unittest\nvalue = 1\n" + ) + + def test_nested_fragments_and_ambiguous_inputs(self): + canonical, local = " value = 1\n", " value = 2\n" + self.assertEqual( + _preserve_block( + "class X:\n" + local, "class X:\n" + canonical, canonical, local + ), + "class X:\n" + local, + ) + for old, new in ( + (local * 2, canonical), + (local, canonical * 2), + ("", canonical), + ): + with self.subTest(old=old, new=new), self.assertRaises(ValueError): + _preserve_block(old, new, canonical, local) + + def test_invalid_result_does_not_write_production_file(self): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) + source, target = root / "canonical.py", root / "Lib/example.py" + target.parent.mkdir() + source.write_text("x = 1\n") + target.write_text("x = 'a'\n") + document = { + "target": "Lib/example.py", + "patches": {}, + "blocks": [["1", "'a"]], + } + with patch( + "update_lib.cmd_migrate.__file__", + str(root / "scripts/update_lib/cmd_migrate.py"), + ): + with self.assertRaisesRegex(ValueError, "invalid Python"): + patch_file(source, target, verbose=False, patches_document=document) + self.assertEqual(target.read_text(), "x = 'a'\n") + + def migrate_doctest(self, selection=None, explicit=False): + old = '''""" +>>> raise X, Y # TODO: RUSTPYTHON; old mismatch # doctest: +EXPECTED_FAILURE +SyntaxError: old result +>>> raise Z # TODO: RUSTPYTHON; obsolete mismatch # doctest: +EXPECTED_FAILURE +SyntaxError: obsolete result +""" +''' + canonical = ( + '''""" +>>> raise X, Y +SyntaxError: canonical result +>>> raise Z +SyntaxError: canonical second result +""" +''' + + CANONICAL_LOAD_TESTS + + "\n" + ) + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) / "repository" + target = root / "Lib/test/test_example.py" + target.parent.mkdir(parents=True) + target.write_text(old) + source = Path(temporary) / "canonical/Lib/test/test_example.py" + source.parent.mkdir(parents=True) + source.write_text(canonical) + args = [str(source)] + if explicit: + metadata = Path(temporary) / "selection.json" + metadata.write_text( + json.dumps( + { + "target": "Lib/test/test_example.py", + "patches": {}, + "doctests": selection, + } + ) + ) + args += ["--patches", str(metadata)] + with ( + contextlib.chdir(root), + patch( + "update_lib.cmd_migrate.__file__", + str(root / "scripts/update_lib/cmd_migrate.py"), + ), + contextlib.redirect_stdout(io.StringIO()), + contextlib.redirect_stderr(io.StringIO()), + ): + result = main(args) + return result, target.read_text(), old, canonical + + def test_doctest_default_requires_explicit_selection(self): + status, result, old, _ = self.migrate_doctest() + self.assertEqual(status, 1) + self.assertEqual(result, old) + + def test_doctest_cli_selection_keeps_only_reviewed_guard(self): + status, result, _, _ = self.migrate_doctest( + {"raise X, Y\n": "known mismatch"}, True + ) + self.assertEqual(status, 0) + self.assertEqual(result.count("+EXPECTED_FAILURE"), 1) + self.assertIn("SyntaxError: canonical result", result) + self.assertIn("SyntaxError: canonical second result", result) + self.assertNotIn("obsolete mismatch", result) + + def test_doctest_empty_selection_keeps_canonical_unchanged(self): + status, result, _, canonical = self.migrate_doctest({}, True) + self.assertEqual(status, 0) + self.assertEqual(result, canonical) + + def test_doctest_invalid_selection_writes_nothing(self): + for selection in ( + None, + [], + {"raise unknown\n": "unrecognized"}, + {"raise X, Y\n": "line\nbreak"}, + ): + with self.subTest(selection=selection): + status, result, old, _ = self.migrate_doctest(selection, True) + self.assertEqual(status, 1) + self.assertEqual(result, old) + def test_patch_with_no_existing_file(self): """Test patching when lib file doesn't exist.""" with tempfile.TemporaryDirectory() as tmpdir: @@ -136,6 +538,83 @@ def test_one(self): class TestPatchDirectory(unittest.TestCase): """Tests for patch_directory function.""" + def test_empty_canonical_fixture_stays_byte_empty(self): + with tempfile.TemporaryDirectory() as temporary: + source, target = Path(temporary) / "canonical", Path(temporary) / "local" + source.mkdir() + target.mkdir() + (source / "empty.py").write_bytes(b"") + (target / "empty.py").write_bytes(b"\n") + for _ in range(2): + patch_directory(source, target, verbose=False) + self.assertEqual((target / "empty.py").read_bytes(), b"") + + def test_preserves_identical_invalid_python_fixture(self): + with tempfile.TemporaryDirectory() as temporary: + source, target = Path(temporary) / "source", Path(temporary) / "target" + source.mkdir() + target.mkdir() + invalid = b"def invalid(\r\n" + for directory in (source, target): + (directory / "negative.py").write_bytes(invalid) + (source / "normal.py").write_text("x = 2\n") + (target / "normal.py").write_text("x = 1\n") + + patch_directory(source, target, verbose=False) + + self.assertEqual((target / "negative.py").read_bytes(), invalid) + self.assertEqual((target / "normal.py").read_text(), "x = 2\n") + + def test_changed_invalid_python_prevents_directory_writes(self): + with tempfile.TemporaryDirectory() as temporary: + source, target = Path(temporary) / "source", Path(temporary) / "target" + source.mkdir() + target.mkdir() + (source / "a_normal.py").write_text("x = 2\n") + (source / "b_asset").write_bytes(b"new") + (source / "c_negative.py").write_text("def invalid(a\n") + (target / "a_normal.py").write_text("x = 1\n") + (target / "b_asset").write_bytes(b"old") + (target / "c_negative.py").write_text("def invalid(b\n") + + with self.assertRaises(SyntaxError): + patch_directory(source, target, verbose=False) + + self.assertEqual((target / "a_normal.py").read_text(), "x = 1\n") + self.assertEqual((target / "b_asset").read_bytes(), b"old") + self.assertEqual((target / "c_negative.py").read_text(), "def invalid(b\n") + + def test_excludes_cache_directories_but_preserves_canonical_assets(self): + with tempfile.TemporaryDirectory() as temporary: + root = pathlib.Path(temporary) + source = root / "source" + destination = root / "destination" + for relative in ("__pycache__", "nested/__pycache__", "assets"): + (source / relative).mkdir(parents=True) + files = { + "module.py": b"# canonical source\n", + "__pycache__/module.cpython-315.pyc": b"stale cache", + "nested/__pycache__/module.cpython-315.pyc": b"nested cache", + "assets/__pycache__": b"ordinary canonical file", + "assets/fixture.pyc": b"canonical bytecode fixture", + } + for relative, content in files.items(): + (source / relative).write_bytes(content) + patch_directory(source, destination, verbose=False) + expected = { + relative: content + for relative, content in files.items() + if "__pycache__" not in pathlib.Path(relative).parts[:-1] + } + actual = { + path.relative_to(destination).as_posix(): path.read_bytes() + for path in destination.rglob("*") + if path.is_file() + } + self.assertEqual(actual, expected) + for relative, content in files.items(): + self.assertEqual((source / relative).read_bytes(), content) + def test_patch_directory_all_files(self): """Test that patch_directory processes all .py files.""" with tempfile.TemporaryDirectory() as tmpdir: @@ -192,5 +671,536 @@ def test_one(self): self.assertIn("@unittest.expectedFailure", content) +OVERRIDE_CLEAN = """import unittest +class Example(unittest.TestCase): + def test_known(self): + self.assertEqual(1, 1) + def test_guarded(self): + self.assertEqual(2, 2) +""" +OVERRIDE_OLD = OVERRIDE_CLEAN.replace( + " def test_known", + " @unittest.expectedFailure # TODO: RUSTPYTHON; old failure\n def test_known", +).replace( + " def test_guarded", + ' @unittest.skip("TODO: RUSTPYTHON; retained guard")\n def test_guarded', +) + + +class MarkerOverrideTests(unittest.TestCase): + def invoke(self, mutation=None, directory=False, override=True, legacy=False): + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary) / "repository" + output = root / "Lib" / "test" / "test_example.py" + output.parent.mkdir(parents=True) + output.write_text(OVERRIDE_OLD) + source = Path(temporary) / "cpython" / "Lib" / "test" / "test_example.py" + source.parent.mkdir(parents=True) + source.write_text(OVERRIDE_CLEAN) + markers = patches_to_json(extract_patches(OVERRIDE_OLD)) + del markers["Example"]["test_known"] + document = {"target": "Lib/test/test_example.py", "patches": markers} + if mutation: + mutation(document) + metadata = Path(temporary) / "remaining.json" + metadata.write_text(json.dumps(document)) + args = [str(source.parent if directory else source)] + if override: + args += ["--patches", str(metadata)] + if legacy: + args += ["--legacy-map", str(metadata)] + with ( + contextlib.chdir(root), + patch( + "update_lib.cmd_migrate.__file__", + str(root / "scripts/update_lib/cmd_migrate.py"), + ), + contextlib.redirect_stdout(io.StringIO()), + contextlib.redirect_stderr(io.StringIO()), + ): + status = main(args) + return status, output.read_text() + + def test_cli_override_removes_only_requested_expected_failure(self): + status, result = self.invoke() + self.assertEqual(status, 0) + self.assertNotIn("expectedFailure", result) + self.assertIn('unittest.skip("TODO: RUSTPYTHON; retained guard")', result) + self.assertIn("self.assertEqual(1, 1)", result) + self.assertIn("self.assertEqual(2, 2)", result) + + def test_default_migration_preserves_all_markers(self): + status, result = self.invoke(override=False) + self.assertEqual(status, 0) + self.assertIn("expectedFailure", result) + self.assertIn("retained guard", result) + + def test_invalid_target_does_not_write(self): + status, result = self.invoke( + lambda document: document.update(target="Lib/test/other.py") + ) + self.assertEqual(status, 1) + self.assertEqual(result, OVERRIDE_OLD) + + def test_removing_skip_does_not_write(self): + status, result = self.invoke( + lambda document: document["patches"]["Example"].clear() + ) + self.assertEqual(status, 1) + self.assertEqual(result, OVERRIDE_OLD) + + def test_directory_override_does_not_write(self): + status, result = self.invoke(directory=True) + self.assertEqual(status, 1) + self.assertEqual(result, OVERRIDE_OLD) + + def test_legacy_combination_does_not_write(self): + status, result = self.invoke(legacy=True) + self.assertEqual(status, 1) + self.assertEqual(result, OVERRIDE_OLD) + + def test_added_changed_or_reordered_markers_fail(self): + failure = PatchSpec(UtMethod.ExpectedFailure, reason="known failure") + success = PatchSpec(UtMethod.ExpectedSuccess, reason="known success") + current = {"Example": {"test_known": [failure, success]}} + for markers in ( + [failure, success, failure], + [PatchSpec(UtMethod.ExpectedFailure, reason="changed"), success], + [success, failure], + ): + document = { + "target": "Lib/test/test_example.py", + "patches": patches_to_json({"Example": {"test_known": markers}}), + } + with self.subTest(markers=markers), self.assertRaises(ValueError): + select_remaining_patches(current, document, Path(document["target"])) + + def test_cli_narrows_unconditional_failure(self): + def narrow(document): + document["patches"]["Example"]["test_known"] = [ + { + "ut_method": "expectedFailureIf", + "cond": "MS_WINDOWS", + "reason": "old failure", + } + ] + + status, result = self.invoke(narrow) + self.assertEqual(status, 0) + self.assertIn( + 'unittest.expectedFailureIf(MS_WINDOWS, "TODO: RUSTPYTHON; old failure")', + result, + ) + self.assertIn('unittest.skip("TODO: RUSTPYTHON; retained guard")', result) + self.assertIn("self.assertEqual(1, 1)", result) + + def test_narrowing_preserves_reason_order_and_existing_targets(self): + failure = PatchSpec(UtMethod.ExpectedFailure, reason="known failure") + narrowed = failure._replace( + ut_method=UtMethod.ExpectedFailureIf, cond="MS_WINDOWS" + ) + success = PatchSpec(UtMethod.ExpectedSuccess, reason="known success") + current = {"Example": {"test_known": [failure, success]}} + for markers in ( + [narrowed, success, narrowed], + [narrowed._replace(reason="changed"), success], + [success, narrowed], + [narrowed._replace(ut_method=UtMethod.SkipIf), success], + [narrowed._replace(ut_method=UtMethod.ExpectedSuccess), success], + [narrowed._replace(cond=None), success], + ): + document = { + "target": "Lib/test/test_example.py", + "patches": patches_to_json({"Example": {"test_known": markers}}), + } + with self.subTest(markers=markers), self.assertRaises(ValueError): + select_remaining_patches(current, document, Path(document["target"])) + + document["patches"] = patches_to_json({"Example": {"test_new": [narrowed]}}) + with self.assertRaises(ValueError): + select_remaining_patches(current, document, Path(document["target"])) + + def test_conditional_failure_cannot_be_broadened_or_changed(self): + conditional = PatchSpec(UtMethod.ExpectedFailureIf, cond="MS_WINDOWS") + current = {"Example": {"test_known": [conditional]}} + for marker in ( + conditional._replace(ut_method=UtMethod.ExpectedFailure, cond=None), + conditional._replace(cond="True"), + conditional._replace(cond="not MS_WINDOWS"), + ): + document = { + "target": "Lib/test/test_example.py", + "patches": patches_to_json({"Example": {"test_known": [marker]}}), + } + with self.subTest(marker=marker), self.assertRaises(ValueError): + select_remaining_patches(current, document, Path(document["target"])) + + +class ConditionalMarkerOverrideTests(unittest.TestCase): + decorator = ( + ' @unittest.expectedFailureIf(not support.is_android, "TODO: RUSTPYTHON")\n' + ) + + def fixture(self): + old = OVERRIDE_CLEAN.replace( + " def test_known", self.decorator + " def test_known" + ) + current = extract_patches(old) + document = { + "target": "Lib/test/test_example.py", + "patches": {}, + "retire_conditional": [ + { + "class": "Example", + "method": "test_known", + "decorator": self.decorator, + } + ], + } + return old, current, document + + def select(self, old, current, document): + return select_remaining_patches( + current, + document, + Path(document["target"]), + old_content=old, + ) + + def test_explicit_conditional_retirement(self): + old, current, document = self.fixture() + self.assertEqual(self.select(old, current, document), {}) + + def test_omitted_conditional_without_authorization_fails(self): + old, current, document = self.fixture() + del document["retire_conditional"] + with self.assertRaises(ValueError): + self.select(old, current, document) + + def test_absent_duplicate_modified_and_retained_fail_closed(self): + for change in ( + "absent", + "duplicate", + "text", + "condition", + "retained", + "duplicate_source", + ): + old, current, document = self.fixture() + with self.subTest(change=change), self.assertRaises(ValueError): + if change == "absent": + document["retire_conditional"][0]["method"] = "missing" + elif change == "duplicate": + document["retire_conditional"] *= 2 + elif change == "text": + document["retire_conditional"][0]["decorator"] = ( + self.decorator.replace('"', "'") + ) + elif change == "condition": + old = old.replace("not support.is_android", "support.is_android") + current = extract_patches(old) + elif change == "retained": + document["patches"] = patches_to_json(current) + elif change == "duplicate_source": + old = old.replace(self.decorator, self.decorator * 2) + current = extract_patches(old) + self.select(old, current, document) + + def test_other_guards_and_original_source_required(self): + for replacement in ("skipIf", "expectedFailureIfWindows"): + old, current, document = self.fixture() + old = old.replace("expectedFailureIf", replacement) + document["retire_conditional"][0]["decorator"] = self.decorator.replace( + "expectedFailureIf", replacement + ) + with self.subTest(replacement=replacement), self.assertRaises(ValueError): + self.select(old, extract_patches(old), document) + old, current, document = self.fixture() + with self.assertRaises(ValueError): + self.select(None, current, document) + + def test_explicit_skip_retirement_preserves_other_markers(self): + decorator = ' @unittest.skip("TODO: RUSTPYTHON; known limitation")\n' + old = OVERRIDE_OLD.replace( + " @unittest.expectedFailure # TODO: RUSTPYTHON; old failure\n", + decorator, + ) + + def authorize(document): + document["retire_conditional"] = [ + { + "class": "Example", + "method": "test_known", + "decorator": decorator, + } + ] + + with patch(__name__ + ".OVERRIDE_OLD", old): + status, result = MarkerOverrideTests().invoke(authorize) + self.assertEqual(status, 0) + self.assertNotIn("known limitation", result) + self.assertIn('unittest.skip("TODO: RUSTPYTHON; retained guard")', result) + status, result = MarkerOverrideTests().invoke() + self.assertEqual(status, 1) + self.assertEqual(result, old) + + def test_skip_retirement_fails_closed(self): + self.decorator = ' @unittest.skip("TODO: RUSTPYTHON; known limitation")\n' + for change in ( + "text", + "duplicate", + "retained", + "duplicate_source", + "skipIf", + "skipUnless", + ): + old, current, document = self.fixture() + if change == "text": + document["retire_conditional"][0]["decorator"] = self.decorator.replace( + '"', "'" + ) + elif change == "duplicate": + document["retire_conditional"] *= 2 + elif change == "retained": + document["patches"] = patches_to_json(current) + elif change == "duplicate_source": + old = old.replace(self.decorator, self.decorator * 2) + current = extract_patches(old) + else: + replacement = self.decorator.replace("skip(", change + "(True, ") + old = old.replace(self.decorator, replacement) + current = extract_patches(old) + document["retire_conditional"][0]["decorator"] = replacement + with self.subTest(change=change), self.assertRaises(ValueError): + self.select(old, current, document) + + def test_cli_conditional_retirement_preserves_remaining_markers(self): + old = OVERRIDE_OLD.replace( + " @unittest.expectedFailure # TODO: RUSTPYTHON; old failure\n", + self.decorator, + ) + + def authorize(document): + document["retire_conditional"] = [ + { + "class": "Example", + "method": "test_known", + "decorator": self.decorator, + } + ] + + with patch(__name__ + ".OVERRIDE_OLD", old): + status, result = MarkerOverrideTests().invoke(authorize) + self.assertEqual(status, 0) + self.assertNotIn("expectedFailureIf", result) + self.assertIn('unittest.skip("TODO: RUSTPYTHON; retained guard")', result) + status, result = MarkerOverrideTests().invoke() + self.assertEqual(status, 1) + self.assertEqual(result, old) + + +PACKAGE_MARKED = """import unittest +class Example: + @unittest.expectedFailure # TODO: RUSTPYTHON; retained reason + def test_one(self): + pass +""" +PACKAGE_CANONICAL = """import unittest +class Example: + def test_one(self): + pass +""" + + +class TestMigratePackage(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.src = self.root / "canonical" / "package" + self.src.mkdir(parents=True) + (self.src / "__init__.py").write_text("# canonical package\n") + (self.src / "test_part.py").write_text(PACKAGE_CANONICAL) + self.dest = self.root / "Lib" / "test" / "package" + self.dest.parent.mkdir(parents=True) + self.old = self.dest.parent / "old.py" + self.old.write_text(PACKAGE_MARKED) + self.manifest = self.root / "map.json" + self.mapping = {"old.py": {"Example": "test_part.py"}} + + def run_migration(self): + self.manifest.write_text(json.dumps(self.mapping)) + migrate_package(self.src, self.dest, self.manifest) + + def assert_rejected(self): + before = self.old.read_bytes() + with self.assertRaises((ValueError, FileNotFoundError, SyntaxError)): + self.run_migration() + self.assertFalse(self.dest.exists()) + self.assertEqual(self.old.read_bytes(), before) + + def test_preserves_marker_and_canonical_asset(self): + (self.src / "asset.dat").write_bytes(b"\x00canonical") + self.run_migration() + self.assertFalse(self.old.exists()) + self.assertEqual((self.dest / "asset.dat").read_bytes(), b"\x00canonical") + self.assertEqual( + list(iter_patches((self.dest / "test_part.py").read_text())), + list(iter_patches(PACKAGE_MARKED)), + ) + + def test_preserves_inherited_override(self): + (self.src / "test_part.py").write_text( + PACKAGE_CANONICAL.replace("class Example:", "class Base:") + + "\nclass Example(Base):\n pass\n" + ) + self.run_migration() + text = (self.dest / "test_part.py").read_text() + self.assertIn("return super().test_one()", text) + self.assertEqual(list(iter_patches(text)), list(iter_patches(PACKAGE_MARKED))) + + def test_excludes_cache_directories_but_preserves_canonical_assets(self): + for relative in ("__pycache__", "nested/__pycache__", "assets"): + (self.src / relative).mkdir(parents=True) + files = { + "__pycache__/module.cpython-315.pyc": b"stale cache", + "nested/__pycache__/module.cpython-315.pyc": b"nested cache", + "assets/__pycache__": b"ordinary canonical file", + "assets/fixture.pyc": b"canonical bytecode fixture", + } + for relative, content in files.items(): + (self.src / relative).write_bytes(content) + self.run_migration() + self.assertFalse((self.dest / "__pycache__").exists()) + self.assertFalse((self.dest / "nested" / "__pycache__").exists()) + for relative in ("assets/__pycache__", "assets/fixture.pyc"): + self.assertEqual((self.dest / relative).read_bytes(), files[relative]) + for relative, content in files.items(): + self.assertEqual((self.src / relative).read_bytes(), content) + + def test_missing_method(self): + (self.src / "test_part.py").write_text( + PACKAGE_CANONICAL.replace("test_one", "test_other") + ) + self.assert_rejected() + + def test_missing_class(self): + (self.src / "test_part.py").write_text( + PACKAGE_CANONICAL.replace("Example", "Other") + ) + self.assert_rejected() + + def test_ambiguous_class(self): + (self.src / "test_part.py").write_text(PACKAGE_CANONICAL + PACKAGE_CANONICAL) + self.assert_rejected() + + def test_ambiguous_method(self): + (self.src / "test_part.py").write_text( + PACKAGE_CANONICAL + " def test_one(self):\n pass\n" + ) + self.assert_rejected() + + def test_missing_destination(self): + self.mapping["old.py"]["Example"] = "missing.py" + self.assert_rejected() + + def test_unused_mapping(self): + self.mapping["old.py"]["Unused"] = "test_part.py" + self.assert_rejected() + + def test_unmapped_marker(self): + self.mapping["old.py"] = {} + self.assert_rejected() + + def test_target_traversal(self): + self.mapping["old.py"]["Example"] = "../outside.py" + self.assert_rejected() + + def test_legacy_traversal(self): + self.mapping["../old.py"] = self.mapping.pop("old.py") + self.assert_rejected() + + def test_duplicate_marker(self): + (self.old.parent / "second.py").write_text(PACKAGE_MARKED) + self.mapping["second.py"] = self.mapping["old.py"] + self.assert_rejected() + self.assertEqual((self.old.parent / "second.py").read_text(), PACKAGE_MARKED) + + def test_preserves_ordered_markers_from_one_legacy_method(self): + marked = PACKAGE_MARKED.replace( + " def test_one", + ' @unittest.skip("TODO: RUSTPYTHON; retained skip")\n def test_one', + ) + self.old.write_text(marked) + self.run_migration() + result = (self.dest / "test_part.py").read_text() + self.assertEqual(list(iter_patches(result)), list(iter_patches(marked))) + self.assertLess(result.index("expectedFailure"), result.index("unittest.skip")) + + def test_duplicate_legacy_owner_is_rejected(self): + for source in ( + PACKAGE_MARKED + PACKAGE_MARKED, + PACKAGE_MARKED + " def test_one(self):\n pass\n", + ): + with self.subTest(source=source): + self.old.write_text(source) + self.assert_rejected() + + def test_unmarked_legacy_retired(self): + self.old.write_text(PACKAGE_CANONICAL) + self.mapping["old.py"] = {} + self.run_migration() + self.assertFalse(self.old.exists()) + self.assertEqual((self.dest / "test_part.py").read_text(), PACKAGE_CANONICAL) + + def test_legacy_doctest_guards_prevent_all_writes(self): + self.old.write_text( + '"""\n' + ">>> raise ValueError # TODO: RUSTPYTHON; mismatch # doctest: +EXPECTED_FAILURE\n" + "ValueError\n" + '"""\n' + PACKAGE_MARKED + ) + self.assert_rejected() + + def test_validation_failure_after_valid_entry_writes_nothing(self): + self.mapping["missing.py"] = {} + self.assert_rejected() + + def test_existing_destination_is_not_overwritten(self): + self.dest.mkdir() + with self.assertRaises(ValueError): + self.run_migration() + self.assertTrue(self.old.exists()) + self.assertEqual(list(self.dest.iterdir()), []) + + def test_source_escape_rejected(self): + outside = self.root / "outside.py" + outside.write_text(PACKAGE_CANONICAL) + (self.src / "test_part.py").unlink() + (self.src / "test_part.py").symlink_to(outside) + self.assert_rejected() + + def test_legacy_symlink_rejected(self): + outside = self.root / "outside.py" + outside.write_text(PACKAGE_MARKED) + self.old.unlink() + self.old.symlink_to(outside) + self.assert_rejected() + + def test_inheritance_cycle_rejected(self): + (self.src / "test_part.py").write_text( + "class Example(Base):\n pass\nclass Base(Example):\n pass\n" + ) + self.assert_rejected() + + def test_canonical_marker_collision_rejected(self): + (self.src / "test_part.py").write_text(PACKAGE_MARKED) + self.assert_rejected() + + def test_unmarked_syntax_error_prevents_all_writes(self): + (self.src / "broken.py").write_text("class :\n") + self.assert_rejected() + + if __name__ == "__main__": unittest.main() diff --git a/scripts/update_lib/tests/test_patch_spec.py b/scripts/update_lib/tests/test_patch_spec.py index 92a0a35a153..1a68ca10d26 100644 --- a/scripts/update_lib/tests/test_patch_spec.py +++ b/scripts/update_lib/tests/test_patch_spec.py @@ -4,11 +4,15 @@ import unittest from update_lib.patch_spec import ( + CANONICAL_LOAD_TESTS, COMMENT, + PATCHED_LOAD_TESTS, PatchSpec, UtMethod, _find_import_insert_line, + apply_doctest_metadata, apply_patches, + extract_doctest_guards, extract_patches, iter_tests, ) @@ -67,6 +71,73 @@ async def test_async(self): class TestExtractPatches(unittest.TestCase): """Tests for extract_patches function.""" + def test_class_conditional_method_markers_are_preserved(self): + code = """class Owner: + if enabled: + @unittest.expectedFailure # TODO: RUSTPYTHON + def test_value(self): + return 42 +""" + patches = extract_patches(code) + self.assertIn("test_value", patches["Owner"]) + clean = code.replace( + " @unittest.expectedFailure # TODO: RUSTPYTHON\n", "" + ) + result = apply_patches(clean, patches) + self.assertIn(" @unittest.expectedFailure", result) + method = list(iter_tests(ast.parse(result)))[0][1] + self.assertEqual(method.col_offset, 8) + self.assertEqual(ast.dump(method.body[0]), "Return(value=Constant(value=42))") + + def test_nested_class_markers_do_not_target_module_names(self): + code = """class Container: + class Target: + @unittest.expectedFailure # TODO: RUSTPYTHON + def test_value(self): + pass +def factory(): + class Target: + @unittest.expectedFailure # TODO: RUSTPYTHON + def test_value(self): + pass +""" + self.assertEqual(extract_patches(code), {}) + + def test_bare_marked_skip_roundtrip(self): + clean = """class Owner: + def test_value(self): + return 42 +""" + marked = clean.replace( + " def test_value", + " @unittest.skip # TODO: RUSTPYTHON; original guard\n def test_value", + ) + patches = extract_patches(marked) + self.assertEqual( + patches["Owner"]["test_value"], + [PatchSpec(UtMethod.Skip, reason="original guard")], + ) + result = apply_patches(clean, patches) + self.assertIn('@unittest.skip("TODO: RUSTPYTHON; original guard")', result) + self.assertEqual(apply_patches(clean, extract_patches(result)), result) + method = list(iter_tests(ast.parse(result)))[0][1] + self.assertEqual(ast.dump(method.body[0]), "Return(value=Constant(value=42))") + + def test_unmarked_bare_skip_and_unrelated_decorators_are_not_patches(self): + code = """class Owner: + @unittest.skip + def test_unmarked(self): + pass + @other.skip # TODO: RUSTPYTHON; unrelated + def test_other(self): + pass + @unittest.other # TODO: RUSTPYTHON; unrelated + def test_unknown(self): + pass +""" + self.assertEqual(extract_patches(code), {}) + self.assertEqual(apply_patches(code, {}), code) + def test_extract_expected_failure(self): """Test extracting @unittest.expectedFailure decorator.""" code = f""" @@ -177,6 +248,143 @@ def test_one(self): class TestApplyPatches(unittest.TestCase): """Tests for apply_patches function.""" + def test_conditional_class_existing_method(self): + code = """import unittest +if enabled: + class TestConditional: + def test_value(self): + assert 1 + 1 == 2 +""" + result = apply_patches( + code, + { + "TestConditional": { + "test_value": [ + PatchSpec( + UtMethod.ExpectedFailureIf, "condition", "known limitation" + ) + ] + } + }, + ) + original = list(iter_tests(ast.parse(code)))[0][1] + updated = list(iter_tests(ast.parse(result)))[0][1] + self.assertEqual(ast.dump(original.body[0]), ast.dump(updated.body[0])) + self.assertEqual(updated.col_offset, 8) + self.assertIn(" @unittest.expectedFailureIf", result) + + def test_conditional_class_inherited_override(self): + code = """import unittest +class Parent: + async def test_value(self): + return 42 +if enabled: + class Child(Parent): + pass +""" + result = apply_patches( + code, {"Child": {"test_value": [PatchSpec(UtMethod.ExpectedSuccess)]}} + ) + methods = list(iter_tests(ast.parse(result))) + self.assertEqual([cls.name for cls, _ in methods], ["Parent", "Child"]) + self.assertIsInstance(methods[1][1], ast.AsyncFunctionDef) + self.assertIn(" return await super().test_value()", result) + self.assertIn(" @unittest.expectedSuccess", result) + + def test_duplicate_conditional_class_names_are_rejected(self): + code = """if enabled: + class Duplicate: + pass +else: + class Duplicate: + pass +""" + with self.assertRaisesRegex(ValueError, "Ambiguous.*Duplicate"): + apply_patches( + code, + {"Duplicate": {"test_value": [PatchSpec(UtMethod.ExpectedFailure)]}}, + ) + + def test_unpatched_conditional_helpers_are_allowed(self): + code = """if enabled: + class Helper: + pass +else: + class Helper: + pass +class Target: + helper = Helper + def test_value(self): + return 1 +""" + result = apply_patches( + code, {"Target": {"test_value": [PatchSpec(UtMethod.ExpectedFailure)]}} + ) + self.assertEqual(result.count("class Helper:"), 2) + self.assertEqual(result.count("@unittest.expectedFailure"), 1) + + def test_ambiguous_transitive_ancestor_is_rejected(self): + code = """if enabled: + class Ancestor: + async def test_value(self): + pass +else: + class Ancestor: + def test_value(self): + pass +class Middle(Ancestor): + pass +class Target(Middle): + pass +""" + with self.assertRaisesRegex(ValueError, "Ambiguous.*Ancestor"): + apply_patches( + code, {"Target": {"test_value": [PatchSpec(UtMethod.ExpectedFailure)]}} + ) + + def test_local_class_names_do_not_shadow_module_class(self): + code = """import unittest +class Target: + def test_value(self): + return 1 +class Container: + class Target: + def test_value(self): + return 2 +def factory(): + class Target: + def test_value(self): + return 3 +""" + result = apply_patches( + code, {"Target": {"test_value": [PatchSpec(UtMethod.ExpectedFailure)]}} + ) + tree = ast.parse(result) + targets = [ + node + for node in ast.walk(tree) + if isinstance(node, ast.ClassDef) and node.name == "Target" + ] + self.assertEqual( + [len(node.body[0].decorator_list) for node in targets], [1, 0, 0] + ) + + def test_duplicate_conditional_method_names_are_rejected(self): + code = """class Owner: + if enabled: + def test_value(self): + return 1 + else: + def test_value(self): + return 2 +""" + with self.assertRaisesRegex( + ValueError, "Ambiguous method name: Owner.test_value" + ): + apply_patches( + code, {"Owner": {"test_value": [PatchSpec(UtMethod.ExpectedFailure)]}} + ) + def test_apply_expected_failure(self): """Test applying @unittest.expectedFailure.""" code = """import unittest @@ -242,6 +450,39 @@ def test_one(self): self.assertIn("@some_decorator", result) self.assertIn("@unittest.expectedFailure", result) + def test_inherited_override_expands_inline_class(self): + for source in ( + "class Child(Base): pass # keep comment\n", + "class Child(Base): value = 1; other = 2\n", + "class Child(\n Base\n): pass\n", + "if True:\n class Child(Base): pass\n", + "class Café(Base): pass\n", + ): + with self.subTest(source=source): + name = "Café" if "Café" in source else "Child" + patches = { + name: { + "test_parent": [PatchSpec(UtMethod.ExpectedFailure, None, "")] + } + } + before = ast.parse(source) + result = apply_patches(source, patches) + after = ast.parse(result) + old_class = next( + node for node in ast.walk(before) if isinstance(node, ast.ClassDef) + ) + new_class = next( + node for node in ast.walk(after) if isinstance(node, ast.ClassDef) + ) + self.assertEqual( + [ast.dump(node) for node in old_class.body], + [ast.dump(node) for node in new_class.body[:-1]], + ) + self.assertEqual(new_class.body[-1].name, "test_parent") + self.assertIn("return super().test_parent()", result) + if "# keep comment" in source: + self.assertIn("# keep comment", result) + def test_apply_inherited_method(self): """Test applying patch to inherited method (creates override).""" code = """import unittest @@ -408,5 +649,90 @@ def test_no_imports_no_docstring(self): self.assertEqual(line, 0) +DOCTEST_SOURCE = "raise X, Y\n" +DOCTEST_METADATA = {DOCTEST_SOURCE: "known mismatch"} +DOCTEST_OLD = ( + '''""" +>>> raise X, Y # TODO: RUSTPYTHON; old reason # doctest: +EXPECTED_FAILURE +Traceback (most recent call last): +SyntaxError: old message +""" +''' + + PATCHED_LOAD_TESTS + + "\n" +) +DOCTEST_CANONICAL = ( + '''""" +>>> raise X, Y +Traceback (most recent call last): +SyntaxError: final message +""" +''' + + CANONICAL_LOAD_TESTS + + "\n" +) + + +class ExactDoctestTests(unittest.TestCase): + def test_extracts_only_existing_guards(self): + self.assertEqual(set(extract_doctest_guards(DOCTEST_OLD)), {DOCTEST_SOURCE}) + self.assertEqual(extract_doctest_guards(DOCTEST_CANONICAL), {}) + self.assertEqual(extract_doctest_guards("value = 1\n"), {}) + + def test_duplicate_existing_guards_are_rejected(self): + duplicate = DOCTEST_OLD.replace( + ">>> raise X, Y # TODO:", + ">>> raise X, Y # TODO: RUSTPYTHON; duplicate # doctest: +EXPECTED_FAILURE\n" + ">>> raise X, Y # TODO:", + ) + with self.assertRaises(ValueError): + extract_doctest_guards(duplicate) + + def test_preserves_final_output_and_roundtrips(self): + result = apply_doctest_metadata( + DOCTEST_OLD, DOCTEST_CANONICAL, DOCTEST_METADATA + ) + self.assertIn("SyntaxError: final message", result) + self.assertNotIn("old message", result) + self.assertEqual(result.count("doctest: +EXPECTED_FAILURE"), 1) + self.assertIn(PATCHED_LOAD_TESTS, result) + self.assertEqual( + apply_doctest_metadata(result, DOCTEST_CANONICAL, DOCTEST_METADATA), result + ) + + def test_duplicate_input_is_rejected(self): + duplicate = DOCTEST_CANONICAL.replace( + ">>> raise X, Y\n", ">>> raise X, Y\n>>> raise X, Y\n" + ) + with self.assertRaises(ValueError): + apply_doctest_metadata(DOCTEST_OLD, duplicate, DOCTEST_METADATA) + + def test_missing_canonical_or_old_case_is_rejected(self): + with self.assertRaises(ValueError): + apply_doctest_metadata( + DOCTEST_OLD, + DOCTEST_CANONICAL.replace("raise X, Y", "raise X"), + DOCTEST_METADATA, + ) + with self.assertRaises(ValueError): + apply_doctest_metadata( + DOCTEST_OLD.replace("raise X, Y", "raise X"), + DOCTEST_CANONICAL, + DOCTEST_METADATA, + ) + + def test_changed_loader_and_unmarked_old_case_are_rejected(self): + with self.assertRaises(ValueError): + apply_doctest_metadata( + DOCTEST_OLD, + DOCTEST_CANONICAL.replace("DocTestSuite()", "DocTestSuite(None)"), + DOCTEST_METADATA, + ) + with self.assertRaises(ValueError): + apply_doctest_metadata( + DOCTEST_CANONICAL, DOCTEST_CANONICAL, DOCTEST_METADATA + ) + + if __name__ == "__main__": unittest.main() diff --git a/scripts/whats_left.py b/scripts/whats_left.py index 40b7b5be9d8..0fa09dbe013 100755 --- a/scripts/whats_left.py +++ b/scripts/whats_left.py @@ -1,6 +1,6 @@ #!/usr/bin/env -S python3 -I # /// script -# requires-python = ">=3.14" +# requires-python = ">=3.15.0" # /// # This script generates Lib/snippets/whats_left_data.py with these variables defined: @@ -39,9 +39,9 @@ implementation = platform.python_implementation() if implementation != "CPython": sys.exit(f"whats_left.py must be run under CPython, got {implementation} instead") -if sys.version_info[:2] < (3, 14): +if sys.version_info[:2] < (3, 15): sys.exit( - f"whats_left.py must be run under CPython 3.14 or newer, got {implementation} {sys.version} instead. If you have uv, try `uv run python -I scripts/whats_left.py` to select a proper Python interpreter easier." + f"whats_left.py must be run under CPython 3.15 or newer, got {implementation} {sys.version} instead. If you have uv, try `uv run python -I scripts/whats_left.py` to select a proper Python interpreter easier." ) @@ -100,6 +100,41 @@ def parse_args(): IGNORED_MODULES = {"this", "antigravity"} | CPYTHON_SPECIFIC_MODS +# This records only the top-level names returned by the existing scanner. +# A truncated manifest is explicitly incomplete and must not certify coverage. +reference_discovery = { + "names": [], + "ignored": [], + "scanner_errors": [], + "truncated": False, +} +_discovery_type, _discovery_str, _discovery_len = type, str, len +_discovery_chars = [0] +_MAX_DISCOVERY_RECORDS = 16384 +_MAX_DISCOVERY_CHARS = 1048576 + + +def record_reference_discovery(group, name): + if _discovery_type(name) is not _discovery_str: + reference_discovery["truncated"] = True + return + size = _discovery_len(name) + count = ( + _discovery_len(reference_discovery["names"]) + + _discovery_len(reference_discovery["ignored"]) + + _discovery_len(reference_discovery["scanner_errors"]) + ) + if ( + size > 4096 + or count >= _MAX_DISCOVERY_RECORDS + or _discovery_chars[0] + size > _MAX_DISCOVERY_CHARS + ): + reference_discovery["truncated"] = True + return + _discovery_chars[0] += size + reference_discovery[group].append(name) + + sys.path = [ path for path in sys.path @@ -114,6 +149,31 @@ def attr_is_not_inherited(type_, attr): return attr in type_.__dict__ +_safe_type, _safe_str, _safe_frozenset = type, str, frozenset + + +def observe_real_type(obj, _type=type, _issubclass=issubclass, _exception=Exception): + # This checks the real metaclass without reading a spoofable __class__. + try: + return "real_type" if _issubclass(_type(obj), _type) else "not_real_type" + except _exception: + return "classification_failed" + + +def observe_real_exception( + obj, _type=type, _issubclass=issubclass, _exception=Exception +): + # Classify the returned object without asking it for __class__. + try: + return ( + "returned_exception" + if _issubclass(_type(obj), _exception) + else "returned_nonexception" + ) + except _exception: + return "classification_failed" + + def extra_info(obj): import sys @@ -171,6 +231,7 @@ def stable_signature(target): try: return { "sig": stable_signature(obj), + "sig_error": False, "doc": doc, } except Exception as e: @@ -179,16 +240,19 @@ def stable_signature(target): if exception.replace('"', "'").startswith("ValueError('no signature found"): return { "sig": "ValueError('no signature found')", + "sig_error": True, "doc": doc, } return { "sig": exception, + "sig_error": True, "doc": doc, } return { "sig": None, + "sig_error": False, "doc": None, } @@ -263,6 +327,100 @@ def is_native_class(obj): return True +# These observations qualify the reference inventory. They do not change the +# legacy flattened report; a gate must reject incomplete or ambiguous evidence. +reference_inventory_diagnostics = {"issues": [], "truncated": False} +reference_expanded_classes = {} +reference_class_selection = {} +actual_parent_scans = {} +_reference_type = type +_reference_str = str +_reference_len = len +_reference_set = set +_reference_sum = sum +_reference_any = any +_MAX_REFERENCE_ISSUES = 1024 +_MAX_REFERENCE_FIELD_CHARS = 4096 +_MAX_REFERENCE_TOTAL_CHARS = 32768 +_reference_chars_used = [0] + + +def record_reference_issue(kind, scope, name): + issues = reference_inventory_diagnostics["issues"] + scope = scope if _reference_type(scope) is _reference_str else None + name = name if _reference_type(name) is _reference_str else None + size = _reference_sum( + _reference_len(value) for value in (scope, name) if value is not None + ) + if ( + _reference_len(issues) >= _MAX_REFERENCE_ISSUES + or _reference_any( + _reference_len(value) > _MAX_REFERENCE_FIELD_CHARS + for value in (scope, name) + if value is not None + ) + or _reference_chars_used[0] + size > _MAX_REFERENCE_TOTAL_CHARS + ): + reference_inventory_diagnostics["truncated"] = True + return + _reference_chars_used[0] += size + issues.append((kind, scope, name)) + + +def ensure_reference_class_scope(scope): + if _reference_type(scope) is _reference_str: + reference_class_selection.setdefault(scope, {}) + else: + record_reference_issue("non_exact_module_name", None, None) + + +def record_reference_class_selection(scope, name, status): + if ( + _reference_type(scope) is not _reference_str + or _reference_type(name) is not _reference_str + ): + record_reference_issue("non_exact_class_selection", scope, None) + return + reference_class_selection.setdefault(scope, {})[name] = status + + +def record_reference_expanded_class(scope, name): + if ( + _reference_type(scope) is not _reference_str + or _reference_type(name) is not _reference_str + ): + record_reference_issue("non_exact_expanded_class", scope, None) + return + reference_expanded_classes.setdefault(scope, []).append(name) + + +def reference_direct_names(result, module_name): + seen = _reference_set() + if _reference_type(module_name) is not _reference_str: + record_reference_issue("non_exact_module_name", None, None) + for name in result: + if _reference_type(name) is not _reference_str: + record_reference_issue("non_exact_module_attribute", module_name, None) + continue + seen.add(name) + if "." in name: + record_reference_issue("dotted_module_attribute", module_name, name) + return seen + + +def check_reference_class_member(seen, module_name, attr, name): + if _reference_type(attr) is not _reference_str: + record_reference_issue("non_exact_class_attribute", module_name, None) + elif "." in attr: + record_reference_issue("dotted_class_attribute", module_name, name) + if _reference_type(name) is not _reference_str: + record_reference_issue("non_exact_flattened_name", module_name, None) + return + if name in seen: + record_reference_issue("flattened_name_collision", module_name, name) + seen.add(name) + + def gen_methods(): objects = [t.__name__ for t in BUILTIN_TYPES] objects.append("type(None)") @@ -286,7 +444,39 @@ def gen_methods(): methods = {} for typ_code in objects + iters: typ = eval(typ_code) + before = _reference_len(methods) + native_type = _reference_type(typ) is _reference_type + # Keep the original single assignment: callbacks during the RHS can + # modify the caller's locals before Python evaluates this target. methods[typ.__name__] = (typ_code, extra_info(typ), own_attrs(typ)) + if not native_type or _reference_type(typ) is not _reference_type: + record_reference_issue("non_native_builtin_type", "builtins", None) + if _reference_len(methods) == before: + record_reference_issue("duplicate_builtin_type", "builtins", None) + + seen_flat = _reference_set() + for name, (_, _, attrs) in methods.items(): + if _reference_type(name) is not _reference_str: + record_reference_issue("non_exact_builtin_type", "builtins", None) + continue + if "." in name: + record_reference_issue("dotted_builtin_type", "builtins", name) + if name in seen_flat: + record_reference_issue("flattened_name_collision", "builtins", name) + seen_flat.add(name) + for attr, _ in attrs: + if _reference_type(attr) is not _reference_str: + record_reference_issue("non_exact_class_attribute", "builtins", None) + continue + if "." in attr: + record_reference_issue("dotted_class_attribute", "builtins", attr) + key = f"{name}.{attr}" + if _reference_type(key) is not _reference_str: + record_reference_issue("non_exact_flattened_name", "builtins", None) + continue + if key in seen_flat: + record_reference_issue("flattened_name_collision", "builtins", key) + seen_flat.add(key) output = "expected_methods = {\n" for name in sorted(methods.keys(), key=name_sort_key): @@ -314,6 +504,7 @@ def callback(path, modname, desc, modules=modules): modules[modname] = 1 def onerror(modname): + record_reference_discovery("scanner_errors", modname) callback(None, modname, None) with warnings.catch_warnings(): @@ -351,6 +542,11 @@ def dir_of_mod_or_error(module_name, keep_other=True): module = import_module(module_name) if isinstance(module, Exception): return module + selected_parents = () + if keep_other is True and _safe_type(module_name) is _safe_str: + selected_parents = _safe_frozenset( + reference_expanded_classes.get(module_name, ()) + ) item_names = sorted(set(dir(module))) result = {} for item_name in item_names: @@ -362,12 +558,27 @@ def dir_of_mod_or_error(module_name, keep_other=True): if item_name == "__doc__": # extra_info() reports a docstring for a callable only, and a module # is not one. getdoc() matches how a callable's is normalized. - result[item_name] = {"sig": None, "doc": inspect.getdoc(module)} + result[item_name] = { + "sig": None, + "sig_error": False, + "doc": inspect.getdoc(module), + } continue item = getattr(module, item_name) # don't repeat items imported from other modules if keep_other or is_child(module, item) or inspect.getmodule(item) is None: result[item_name] = extra_info(item) + # Observe the item local after inspection, without another getattr. + # This is not atomic with either the inspection or later lookups. + if ( + keep_other is True + and _safe_type(module_name) is _safe_str + and _safe_type(item_name) is _safe_str + and item_name in selected_parents + ): + actual_parent_scans.setdefault(module_name, {})[item_name] = ( + observe_real_type(item) + ) return result @@ -382,8 +593,11 @@ def _is_decimal_fallback_item(item): def _expand_class_members(dir_result, module): + seen = reference_direct_names(dir_result, "decimal") + ensure_reference_class_scope("decimal") for item_name in list(dir_result): if "." in item_name: + record_reference_class_selection("decimal", item_name, "skipped_dotted") continue item = getattr(module, item_name) if ( @@ -391,8 +605,23 @@ def _expand_class_members(dir_result, module): and item not in BUILTIN_TYPES and getattr(item, "__name__", None) == item_name ): + record_reference_expanded_class("decimal", item_name) + record_reference_class_selection("decimal", item_name, "selected") for attr, info in own_attrs(item): - dir_result[f"{item_name}.{attr}"] = info + if ( + _reference_type(item_name) is not _reference_str + or _reference_type(attr) is not _reference_str + ): + record_reference_issue( + "non_exact_class_name_or_attribute", "decimal", None + ) + dir_result[f"{item_name}.{attr}"] = info + else: + name = f"{item_name}.{attr}" + check_reference_class_member(seen, "decimal", attr, name) + dir_result[name] = info + else: + record_reference_class_selection("decimal", item_name, "not_selected") def _pure_decimal_baseline(wrapper): @@ -404,7 +633,11 @@ def _pure_decimal_baseline(wrapper): if item_name == "__builtins__": continue if item_name == "__doc__": - result[item_name] = {"sig": None, "doc": inspect.getdoc(wrapper)} + result[item_name] = { + "sig": None, + "sig_error": False, + "doc": inspect.getdoc(wrapper), + } continue item = getattr(_pydecimal, item_name) if not _is_decimal_fallback_item(item): @@ -418,15 +651,19 @@ def gen_modules(): # check name because modules listed have side effects on import, # e.g. printing something or opening a webpage modules = {} + failed = {} for mod_name in sorted(scan_modules(), key=name_sort_key): + record_reference_discovery("names", mod_name) if mod_name in IGNORED_MODULES: + record_reference_discovery("ignored", mod_name) continue # decimal's accelerated types are not the implementation under test. if mod_name == "decimal": module = import_module(mod_name) if isinstance(module, Exception): + failed[mod_name] = f"{type(module).__name__}: {str(module)}" print( - f"!!! {mod_name} skipped because {type(module).__name__}: {str(module)}", + f"!!! {mod_name} skipped because {failed[mod_name]}", file=sys.stderr, ) continue @@ -435,12 +672,12 @@ def gen_modules(): # when generating CPython list, ignore items defined by other modules dir_result = dir_of_mod_or_error(mod_name, keep_other=False) if isinstance(dir_result, Exception): - print( - f"!!! {mod_name} skipped because {type(dir_result).__name__}: {str(dir_result)}", - file=sys.stderr, - ) + failed[mod_name] = f"{type(dir_result).__name__}: {str(dir_result)}" + print(f"!!! {mod_name} skipped because {failed[mod_name]}", file=sys.stderr) continue module = import_module(mod_name) + seen = reference_direct_names(dir_result, mod_name) + ensure_reference_class_scope(mod_name) for item_name in list(dir_result): item = getattr(module, item_name) # an alias such as array.ArrayType is scanned under its real name @@ -449,10 +686,25 @@ def gen_modules(): and item not in BUILTIN_TYPES and item.__name__ == item_name ): + record_reference_expanded_class(mod_name, item_name) + record_reference_class_selection(mod_name, item_name, "selected") for attr, info in own_attrs(item): - dir_result[f"{item_name}.{attr}"] = info + if ( + _reference_type(item_name) is not _reference_str + or _reference_type(attr) is not _reference_str + ): + record_reference_issue( + "non_exact_class_name_or_attribute", mod_name, None + ) + dir_result[f"{item_name}.{attr}"] = info + else: + name = f"{item_name}.{attr}" + check_reference_class_member(seen, mod_name, attr, name) + dir_result[name] = info + else: + record_reference_class_selection(mod_name, item_name, "not_selected") modules[mod_name] = dir_result - return modules + return modules, failed output = """\ @@ -462,11 +714,20 @@ def gen_modules(): # VERSION AND PYTHON ENVIRONMENT USED # TO RUN not_impl_mods_gen.py +import sys + """ output += gen_methods() +cpymods, cpython_failed_imports = gen_modules() output += f""" -cpymods = {gen_modules()!r} +cpymods = {cpymods!r} +cpython_failed_imports = {cpython_failed_imports!r} +reference_inventory_diagnostics = {reference_inventory_diagnostics!r} +reference_expanded_classes = {reference_expanded_classes!r} +reference_class_selection = {reference_class_selection!r} +actual_parent_scans = {{}} +reference_discovery = {reference_discovery!r} libdir = {os.path.abspath("Lib/").encode("utf8")!r} """ @@ -474,17 +735,27 @@ def gen_modules(): # Copy the source code of functions we will reuse in the generated script REUSED = [ attr_is_not_inherited, + observe_real_type, + observe_real_exception, extra_info, dir_of_mod_or_error, import_module, is_child, + name_sort_key, ] +output += "_safe_type, _safe_str, _safe_frozenset = type, str, frozenset\n\n" for fn in REUSED: output += "".join(inspect.getsourcelines(fn)[0]) + "\n\n" # Prevent missing variable linter errors from compare() expected_methods = {} cpymods = {} +reference_inventory_diagnostics = {} +reference_expanded_classes = {} +reference_class_selection = {} +actual_parent_scans = {} +reference_discovery = {} +cpython_failed_imports = {} libdir = "" @@ -496,15 +767,21 @@ def compare(): import os import platform import re - import sys import warnings from contextlib import redirect_stdout - def sig_mismatch(rustpy_sig, cpython_sig): - # A signature CPython cannot produce is never a mismatch; having one is fine. - if cpython_sig is None or cpython_sig.startswith("ValueError("): + def sig_mismatch(rustpy_sig, cpython_info): + # A reference introspection failure cannot establish a mismatch. + if cpython_info["sig"] is None or cpython_info["sig_error"]: return False - return rustpy_sig != cpython_sig + return rustpy_sig != cpython_info["sig"] + + def info_equivalent(rustpy_info, cpython_info): + # A failed reference signature cannot prove an inherited member differs. + signatures_match = ( + cpython_info["sig_error"] or rustpy_info["sig"] == cpython_info["sig"] + ) + return signatures_match and rustpy_info["doc"] == cpython_info["doc"] def method_incompatibility_reason(typ, method_name, real_method_value): has_method = hasattr(typ, method_name) @@ -514,25 +791,34 @@ def method_incompatibility_reason(typ, method_name, real_method_value): is_inherited = not attr_is_not_inherited(typ, method_name) # Inheriting something that reads the same as CPython's own member # leaves nothing to implement. - if is_inherited and extra_info(getattr(typ, method_name)) != real_method_value: - return "(inherited)" + if is_inherited: + value = extra_info(getattr(typ, method_name)) + if not info_equivalent(value, real_method_value): + return "(inherited)" return None not_implementeds = {} mismatched_methods = {} mismatched_method_docs = {} + uncomparable = {} for name, (typ, real_value, methods) in expected_methods.items(): + if real_value["sig_error"]: + uncomparable.setdefault(name, []).append((name, real_value["sig"])) missing_methods = {} for method, real_method_value in methods: + item = f"{name}.{method}" + if real_method_value["sig_error"]: + uncomparable.setdefault(name, []).append( + (item, real_method_value["sig"]) + ) reason = method_incompatibility_reason(typ, method, real_method_value) if reason is not None: missing_methods[method] = reason continue # A method that exists but differs is a mismatch, not a missing one. value = extra_info(getattr(typ, method)) - item = f"{name}.{method}" - if sig_mismatch(value["sig"], real_method_value["sig"]): + if sig_mismatch(value["sig"], real_method_value): mismatched_methods.setdefault(name, []).append( (item, value["sig"], real_method_value["sig"]) ) @@ -556,30 +842,65 @@ def method_incompatibility_reason(typ, method_name, real_method_value): ] mod_names += list(sys.builtin_module_names) # Remove easter egg modules - mod_names = sorted(set(mod_names) - {"this", "antigravity"}) + # Match the reference scan's ordering for symbolic defaults that depend + # on previously imported modules. + mod_names = sorted(set(mod_names) - {"this", "antigravity"}, key=name_sort_key) rustpymods = {mod: dir_of_mod_or_error(mod) for mod in mod_names} + for modname, classes in reference_expanded_classes.items(): + observations = actual_parent_scans.setdefault(modname, {}) + for class_name in classes: + observations.setdefault(class_name, "not_observed") result = { "cpython_modules": {}, + "reference_inventory_diagnostics": reference_inventory_diagnostics, + "reference_builtin_inventory": { + name: [method for method, _ in methods] + for name, (_, _, methods) in expected_methods.items() + }, + "reference_expanded_classes": reference_expanded_classes, + "reference_class_selection": reference_class_selection, + "actual_scan_status": {}, + "actual_second_import_status": {}, + "actual_parent_scans": actual_parent_scans, + "actual_parent_decisions": {}, + "reference_discovery": reference_discovery, "implemented": {}, "not_implemented": {}, "failed_to_import": {}, "missing_items": {}, # builtin types first, keyed by type name, then modules "mismatched_items": mismatched_methods, + "uncomparable_signatures": uncomparable, "mismatched_doc_items": mismatched_method_docs, } for modname, cpymod in cpymods.items(): + module_has_uncomparable = False + for item, info in cpymod.items(): + if info["sig_error"]: + module_has_uncomparable = True + uncomparable.setdefault(modname, []).append( + (f"{modname}.{item}", info["sig"]) + ) rustpymod = rustpymods.get(modname) + result["actual_parent_decisions"][modname] = {} if rustpymod is None: + result["actual_scan_status"][modname] = "not_discovered" + result["actual_second_import_status"][modname] = "not_attempted" result["not_implemented"][modname] = None elif isinstance(rustpymod, Exception): + result["actual_scan_status"][modname] = "scan_returned_exception" + result["actual_second_import_status"][modname] = "not_attempted" result["failed_to_import"][modname] = ( f"{rustpymod.__class__.__name__}: {rustpymod}" ) else: + result["actual_scan_status"][modname] = "scan_completed" module = import_module(modname) + result["actual_second_import_status"][modname] = observe_real_exception( + module + ) skipped = set() inherited = set() for item in cpymod: @@ -588,17 +909,25 @@ def method_incompatibility_reason(typ, method_name, real_method_value): continue cls = getattr(module, cls_name, None) if not isinstance(cls, type): + result["actual_parent_decisions"][modname][item] = ( + "isinstance_false" + ) # The class line already reports a missing class or one # implemented as something else. skipped.add(item) elif not hasattr(cls, attr): + result["actual_parent_decisions"][modname][item] = "isinstance_true" continue elif attr_is_not_inherited(cls, attr): + result["actual_parent_decisions"][modname][item] = "isinstance_true" rustpymod[item] = extra_info(getattr(cls, attr)) - elif extra_info(getattr(cls, attr)) == cpymod[item]: - rustpymod[item] = cpymod[item] else: - inherited.add(item) + result["actual_parent_decisions"][modname][item] = "isinstance_true" + value = extra_info(getattr(cls, attr)) + if info_equivalent(value, cpymod[item]): + rustpymod[item] = value + else: + inherited.add(item) implemented_items = sorted(set(cpymod) & set(rustpymod)) mod_missing_items = set(cpymod) - set(rustpymod) - skipped mod_missing_items = sorted( @@ -608,7 +937,7 @@ def method_incompatibility_reason(typ, method_name, real_method_value): mod_mismatched_items = [ (f"{modname}.{item}", rustpymod[item]["sig"], cpymod[item]["sig"]) for item in implemented_items - if sig_mismatch(rustpymod[item]["sig"], cpymod[item]["sig"]) + if sig_mismatch(rustpymod[item]["sig"], cpymod[item]) ] mod_mismatched_doc_items = [ (f"{modname}.{item}", rustpymod[item]["doc"], cpymod[item]["doc"]) @@ -621,10 +950,20 @@ def method_incompatibility_reason(typ, method_name, real_method_value): result["mismatched_items"][modname] = mod_mismatched_items if mod_mismatched_doc_items: result["mismatched_doc_items"][modname] = mod_mismatched_doc_items - if not (mod_missing_items or mod_mismatched_items): + if not ( + mod_missing_items or mod_mismatched_items or module_has_uncomparable + ): result["implemented"][modname] = None result["cpython_modules"] = cpymods + result["cpython_failed_imports"] = cpython_failed_imports + result["cpython_builtin_signatures"] = { + name: { + "type": real_value["sig"], + "methods": {method: info["sig"] for method, info in methods}, + } + for name, (_, real_value, methods) in expected_methods.items() + } result["not_implementeds"] = not_implementeds print(json.dumps(result)) @@ -683,6 +1022,7 @@ def resolve_rustpython(path): # The last line should be json output, the rest of the lines can contain noise # because importing certain modules can print stuff to stdout/stderr print(result.stderr, file=sys.stderr) +result.check_returncode() result = json.loads(result.stdout.splitlines()[-1]) if args.json: @@ -722,6 +1062,15 @@ def resolve_rustpython(path): if i < len(mismatched) - 1: print() +if args.signature: + print( + "\n# uncomparable signature observations (CPython introspection errors; aliases may repeat)" + ) + for entries in result["uncomparable_signatures"].values(): + for item, error in entries: + print(f"{item}: {error}") + + if args.doc: print("\n# mismatching `__doc__`s (warnings)") for modname, mismatched in result["mismatched_doc_items"].items(): @@ -732,4 +1081,32 @@ def resolve_rustpython(path): print() print("# summary") for error_type, modules in result.items(): - print("# ", error_type, len(modules)) + if error_type not in { + "reference_discovery", + "reference_inventory_diagnostics", + "reference_builtin_inventory", + "reference_expanded_classes", + "reference_class_selection", + "actual_scan_status", + "actual_second_import_status", + "actual_parent_scans", + "actual_parent_decisions", + }: + print("# ", error_type, len(modules)) +diagnostics = result["reference_inventory_diagnostics"] +if diagnostics["issues"] or diagnostics["truncated"]: + print("# reference inventory issues", len(diagnostics["issues"])) + if diagnostics["truncated"]: + print("# reference inventory issue list truncated") +discovery = result["reference_discovery"] +print( + "# reference discovery:", + len(discovery["names"]), + "names,", + len(discovery["ignored"]), + "ignored,", + len(discovery["scanner_errors"]), + "scanner errors", +) +if discovery["truncated"]: + print("# reference discovery manifest truncated") diff --git a/src/interpreter.rs b/src/interpreter.rs index a8b03cba0b0..a28e26cfb3d 100644 --- a/src/interpreter.rs +++ b/src/interpreter.rs @@ -19,11 +19,13 @@ impl InterpreterBuilderExt for InterpreterBuilder { let builder = builder.init_hook(install_default_tls_provider); cfg_select! { - feature = "freeze-stdlib" => { - builder - .add_frozen_modules(rustpython_pylib::FROZEN_STDLIB) - .init_hook(set_frozen_stdlib_dir) - } + feature = "freeze-stdlib" => builder + .add_frozen_modules_with_resources( + rustpython_pylib::FROZEN_STDLIB, + rustpython_pylib::FROZEN_STDLIB_RESOURCES, + ) + .expect("validated embedded standard-library resources") + .init_hook(set_frozen_stdlib_dir), _ => builder.init_hook(setup_dynamic_stdlib), } } @@ -57,32 +59,30 @@ fn install_default_tls_provider(_vm: &mut crate::VirtualMachine) { fn set_frozen_stdlib_dir(vm: &mut crate::VirtualMachine) { use rustpython_vm::common::rc::PyRc; - let state = PyRc::get_mut(&mut vm.state).unwrap(); - state.config.paths.stdlib_dir = Some(rustpython_pylib::LIB_PATH.to_owned()); + if !vm.state.config.settings.use_frozen_modules { + setup_dynamic_stdlib(vm); + return; + } + + if use_build_stdlib(vm) { + let state = PyRc::get_mut(&mut vm.state).unwrap(); + state.config.paths.stdlib_dir = + Some(canonical_stdlib_path(rustpython_pylib::LIB_PATH.to_owned())); + } } /// Setup dynamic standard library loading from filesystem -#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))] +#[cfg(feature = "stdlib")] fn setup_dynamic_stdlib(vm: &mut crate::VirtualMachine) { use rustpython_vm::common::rc::PyRc; + if !use_build_stdlib(vm) { + return; + } let state = PyRc::get_mut(&mut vm.state).unwrap(); let paths: Vec = collect_stdlib_paths() .into_iter() - .map(|p| { - std::fs::canonicalize(&p) - .map(|canonical| { - let s = canonical.to_string_lossy(); - #[cfg(windows)] - { - if let Some(stripped) = s.strip_prefix(r"\\?\") { - return stripped.to_owned(); - } - } - s.into_owned() - }) - .unwrap_or(p) - }) + .map(canonical_stdlib_path) .collect(); // Set stdlib_dir to the first stdlib path if available @@ -90,14 +90,44 @@ fn setup_dynamic_stdlib(vm: &mut crate::VirtualMachine) { state.config.paths.stdlib_dir = Some(first_path.clone()); } - // Insert at the beginning so stdlib comes before user paths - for path in paths.into_iter().rev() { - state.config.paths.module_search_paths.insert(0, path); - } + rustpython_vm::getpath::add_build_time_paths( + &state.config.settings, + &mut state.config.paths, + paths, + ); +} + +// Preserve a discovered library. Only an explicit nonempty prefix half of +// PYTHONHOME forbids falling back to the build-tree pure-Python library. +#[cfg(feature = "stdlib")] +fn use_build_stdlib(vm: &crate::VirtualMachine) -> bool { + vm.state.config.settings.under_pth.is_none() + && vm.state.config.paths.stdlib_dir.is_none() + && vm.state.config.settings.home.as_deref().is_none_or(|home| { + let (prefix, _) = home + .split_once(if cfg!(windows) { ';' } else { ':' }) + .unwrap_or((home, home)); + prefix.is_empty() + }) +} + +/// Resolve the build-tree library link consistently for both backends. +#[cfg(feature = "stdlib")] +fn canonical_stdlib_path(path: String) -> String { + std::fs::canonicalize(&path) + .map(|canonical| { + let value = canonical.to_string_lossy(); + #[cfg(windows)] + if let Some(stripped) = value.strip_prefix(r"\\?\") { + return stripped.to_owned(); + } + value.into_owned() + }) + .unwrap_or(path) } /// Collect standard library paths from build-time configuration -#[cfg(all(feature = "stdlib", not(feature = "freeze-stdlib")))] +#[cfg(feature = "stdlib")] fn collect_stdlib_paths() -> Vec { // BUILDTIME_RUSTPYTHONPATH should be set when distributing if let Some(paths) = option_env!("BUILDTIME_RUSTPYTHONPATH") { diff --git a/src/lib.rs b/src/lib.rs index e3798512602..41a169d273b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -59,9 +59,12 @@ mod shell; #[cfg(feature = "rustpython-pylib")] pub use rustpython_pylib as pylib; -use rustpython_vm::{AsObject, PyObjectRef, PyResult, VirtualMachine, scope::Scope}; +use rustpython_vm::{ + AsObject, PyObjectRef, PyResult, VirtualMachine, builtins::PyBaseExceptionRef, scope::Scope, +}; use std::env; use std::io::IsTerminal; +use std::path::{Path, PathBuf}; use std::process::ExitCode; pub use interpreter::InterpreterBuilderExt; @@ -81,11 +84,28 @@ compile_error!( /// The main cli of the `rustpython` interpreter. This function will return `std::process::ExitCode` /// based on the return code of the python code ran through the cli. /// +/// This retains the caller's process locale. The standalone executable uses +/// `run_with_locale` to opt into environment setup during single-threaded startup. +/// /// **Note**: This function provides no way to further initialize the VM after the builder is applied. /// All VM initialization (adding native modules, init hooks, etc.) must be done through the /// [`InterpreterBuilder`] parameter before calling this function. -#[must_use] -pub fn run(mut builder: InterpreterBuilder) -> ExitCode { +pub fn run(builder: InterpreterBuilder) -> ExitCode { + run_impl(builder, false) +} + +/// Run the command-line interpreter, configuring LC_CTYPE from the environment. +/// +/// # Safety +/// +/// Call only during single-threaded startup, before other threads or libraries +/// can read the environment or use the process-global locale. Embedded callers +/// that cannot guarantee this should use `run` or build an interpreter directly. +pub unsafe fn run_with_locale(builder: InterpreterBuilder) -> ExitCode { + run_impl(builder, true) +} + +fn run_impl(mut builder: InterpreterBuilder, configure_locale: bool) -> ExitCode { env_logger::init(); // NOTE: This is not a WASI convention. But it will be convenient since POSIX shell always defines it. @@ -104,6 +124,15 @@ pub fn run(mut builder: InterpreterBuilder) -> ExitCode { } }; + #[cfg(all(feature = "host_env", any(target_os = "linux", target_os = "macos")))] + if configure_locale { + // SAFETY: only run_with_locale enables this, under its caller's + // single-threaded process-startup contract. + unsafe { vm::host_env::locale::initialize_ctype(settings.ignore_environment) }; + } + #[cfg(not(all(feature = "host_env", any(target_os = "linux", target_os = "macos"))))] + let _ = configure_locale; + // don't translate newlines (\r\n <=> \n) #[cfg(windows)] { @@ -111,9 +140,9 @@ pub fn run(mut builder: InterpreterBuilder) -> ExitCode { fn _setmode(fd: i32, flags: i32) -> i32; } unsafe { - _setmode(0, libc::O_BINARY); - _setmode(1, libc::O_BINARY); - _setmode(2, libc::O_BINARY); + rustpython_vm::host_env::suppress_iph!(_setmode(0, libc::O_BINARY)); + rustpython_vm::host_env::suppress_iph!(_setmode(1, libc::O_BINARY)); + rustpython_vm::host_env::suppress_iph!(_setmode(2, libc::O_BINARY)); } } @@ -121,13 +150,8 @@ pub fn run(mut builder: InterpreterBuilder) -> ExitCode { let interp = builder.interpreter(); let exitcode = cfg_select! { - feature = "capi" => {{ - let local_vm = interp.enter(|vm| vm.new_thread()); - rustpython_capi::init_main_interpreter(interp); - let result = local_vm.run(|vm| run_rustpython(vm, run_mode)); - rustpython_capi::get_main_interpreter().take().unwrap().finalize(result.err()) - }}, - _ => interp.run(move |vm| run_rustpython(vm, run_mode)), + feature = "capi" => rustpython_capi::run_main_interpreter(interp, move |vm| run_rustpython(vm, run_mode)), + _ => interp.run_main(move |vm| run_rustpython(vm, run_mode)), }; rustpython_vm::host_env::os::exit_code(exitcode) @@ -165,106 +189,97 @@ fn install_pip(installer: InstallPipMode, scope: Scope, vm: &VirtualMachine) -> } } -/// The working directory, when it can be named. -fn current_dir() -> Option { - env::current_dir().ok()?.into_os_string().into_string().ok() -} - /// `_Py_abspath`: `path` joined onto the working directory. Windows normalizes /// the result through `GetFullPathNameW`; elsewhere it is left as joined. -fn abs_path(path: &str) -> String { - if path.is_empty() || path == "." { - return current_dir().unwrap_or_else(|| path.to_owned()); +fn abs_path(path: &Path) -> PathBuf { + if path.as_os_str().is_empty() || path == Path::new(".") { + return env::current_dir().unwrap_or_else(|_| path.to_owned()); } if cfg!(windows) { - return std::path::absolute(path) - .ok() - .and_then(|p| p.into_os_string().into_string().ok()) - .unwrap_or_else(|| path.to_owned()); + return std::path::absolute(path).unwrap_or_else(|_| path.to_owned()); } - if std::path::Path::new(path).is_absolute() { + if path.is_absolute() { return path.to_owned(); } // Keep the relative path when the working directory is unavailable. - current_dir().map_or_else( - || path.to_owned(), - |cwd| format!("{cwd}{}{path}", std::path::MAIN_SEPARATOR), - ) + env::current_dir().map_or_else(|_| path.to_owned(), |cwd| cwd.join(path)) } /// `_PyPathConfig_ComputeSysPath0` for a script argument: the directory holding /// the script, with symlinks resolved. -fn script_sys_path0(argv0: &str) -> String { +fn script_sys_path0(argv0: &Path) -> PathBuf { // `realpath()`, which Windows has no counterpart for; there the path is // only made absolute. let resolved = if cfg!(windows) { Some(abs_path(argv0)) } else { - std::fs::canonicalize(argv0) - .ok() - .and_then(|p| p.into_os_string().into_string().ok()) + std::fs::canonicalize(argv0).ok() }; let path0 = resolved.as_deref().unwrap_or(argv0); - let Some(sep) = path0.rfind(std::path::is_separator) else { - return String::new(); - }; - // Drop the trailing separator unless it is all that is left of a root. - let end = if sep == 0 || (cfg!(windows) && path0[..sep].ends_with(':')) { - sep + 1 - } else { - sep - }; - path0[..end].to_owned() + path0.parent().unwrap_or_else(|| Path::new("")).to_owned() } // pymain_run_file_obj in Modules/main.c -fn run_file(vm: &VirtualMachine, scope: Scope, argv0: &str) -> PyResult<()> { +fn run_file(vm: &VirtualMachine, scope: Scope, argv0: impl AsRef) -> PyResult { + let argv0 = argv0.as_ref(); // config_run_filename_abspath: __file__ and co_filename are absolute even // when the script was named relative to the working directory. - let path = &abs_path(argv0); + let path = abs_path(argv0); + let filename = vm.fsdecode(path.as_os_str())?; // Check if path is a package/directory with __main__.py - if let Some(_importer) = get_importer(path, vm)? { - vm.insert_sys_path(vm.new_pyobj(path.clone()))?; + if let Some(_importer) = get_importer(&filename, vm)? { + vm.insert_sys_path(filename.clone().into())?; let runpy = vm.import("runpy", 0)?; let run_module_as_main = runpy.get_attr("_run_module_as_main", vm)?; run_module_as_main.call((vm::identifier!(vm, __main__).to_owned(), false), vm)?; - return Ok(()); + return Ok(0); } // Add script directory to sys.path[0] if !vm.state.config.settings.safe_path { - vm.insert_sys_path(vm.new_pyobj(script_sys_path0(argv0)))?; + vm.insert_sys_path( + vm.fsdecode(script_sys_path0(argv0).into_os_string())? + .into(), + )?; } cfg_select! { - feature = "host_env" => { - match rustpython_vm::host_env::fs::metadata(path) { - Ok(_) => vm.run_any_file(scope, path), - Err(err) => cant_open_file(vm, path, &err), - } - } + feature = "host_env" => match rustpython_vm::host_env::fs::metadata(&path) { + Ok(_) => vm.run_any_file(scope, &path).map(|()| 0), + Err(err) => cant_open_file(vm, &filename, &err), + }, _ => { // In sandbox mode, the binary reads the file and feeds source to the VM. // The VM itself has no filesystem access. - let path = if path.is_empty() { "???" } else { path }; - match std::fs::read_to_string(path) { - Ok(source) => vm.run_string(scope, &source, path).map(drop), - Err(err) => cant_open_file(vm, path, &err), + match std::fs::read_to_string(&path) { + Ok(source) => vm.run_string_with_filename(scope, &source, &filename).map(|_| 0), + Err(err) => cant_open_file(vm, &filename, &err), } } } } -fn cant_open_file(vm: &VirtualMachine, path: &str, err: &std::io::Error) -> PyResult<()> { - let program = &vm.state.config.paths.executable; - let filename_repr = vm.ctx.new_str(path).as_object().repr(vm)?; +fn cant_open_file( + vm: &VirtualMachine, + path: &vm::Py, + err: &std::io::Error, +) -> PyResult { + let program_name = vm.fsdecode(vm.state.config.paths.program_name.clone())?; + let filename_repr = path.as_object().repr(vm)?; let errno = err.raw_os_error().unwrap_or(2); - eprintln!("{program}: can't open file {filename_repr}: [Errno {errno}] {err}"); - Err(vm.new_system_exit(vec![vm.ctx.new_int(2).into()].into())) + let strerror = vm::host_env::errno::strerror_string(errno).unwrap_or_default(); + writeln!( + vm::stdlib::sys::PyStderr(vm), + "{program_name}: can't open file {filename_repr}: [Errno {errno}] {strerror}" + ); + Ok(2) } -fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult> { +fn get_importer( + path: &vm::Py, + vm: &VirtualMachine, +) -> PyResult> { use rustpython_vm::builtins::PyDictRef; use rustpython_vm::convert::TryFromObject; @@ -273,7 +288,7 @@ fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult if let Some(importer) = path_importer_cache.get_item_opt(path, vm)? { return Ok(Some(importer)); } - let path_obj = vm.ctx.new_str(path); + let path_obj = path.to_owned(); let path_hooks = vm.sys_module.get_attr("path_hooks", vm)?; let mut importer = None; let path_hooks: Vec = path_hooks.try_into_value(vm)?; @@ -295,43 +310,65 @@ fn get_importer(path: &str, vm: &VirtualMachine) -> PyResult }) } -// pymain_run_python -fn run_rustpython(vm: &VirtualMachine, run_mode: RunMode) -> PyResult<()> { +fn run_rustpython(vm: &VirtualMachine, run_mode: RunMode) -> u32 { #[cfg(feature = "flame-it")] let main_guard = flame::start_guard("RustPython main"); + let exitcode = + pymain_run_python(vm, run_mode).unwrap_or_else(|exc| vm.handle_exit_exception(exc)); + + #[cfg(feature = "flame-it")] + { + main_guard.end(); + if let Err(e) = write_profile(&vm.state.as_ref().config.settings) { + error!("Error writing profile information: {}", e); + } + } + + exitcode +} + +// pymain_run_python +fn pymain_run_python(vm: &VirtualMachine, run_mode: RunMode) -> PyResult { + vm.check_stdlib_initialization()?; let scope = vm.new_scope_with_main()?; - // Initialize warnings module to process sys.warnoptions - // _PyWarnings_Init() - if vm.import("warnings", 0).is_err() { + // The native warnings state already holds the default filters. Import the + // Python module only when startup options require processing (-W, -b, dev). + let warnoptions = vm.sys_module.dict().get_item_opt("warnoptions", vm)?; + if warnoptions + .as_ref() + .and_then(|options| options.downcast_ref::()) + .is_some_and(|options| options.__len__() > 0) + && vm.import("warnings", 0).is_err() + { warn!("Failed to import warnings module"); } // Import site first, before setting sys.path[0] // This matches CPython's behavior where site.removeduppaths() runs // before sys.path[0] is set, preventing '' from being converted to cwd - let site_result = vm.import("site", 0); - if site_result.is_err() { + if vm.state.config.settings.import_site && vm.import("site", 0).is_err() { warn!( "Failed to import site, consider adding the Lib directory to your RUSTPYTHONPATH \ environment variable", ); } + // CPython activates configured all-mode after site to avoid startup cycles. + vm.apply_startup_lazy_imports(); + // _PyPathConfig_ComputeSysPath0 - set sys.path[0] after site import if !vm.state.config.settings.safe_path { - let path0: Option = match &run_mode { - RunMode::Command(_) => Some(String::new()), - RunMode::Module(_) => env::current_dir() - .ok() - .and_then(|p| p.to_str().map(|s| s.to_owned())), + let path0 = match &run_mode { + RunMode::Command(_) => Some(PathBuf::new()), + RunMode::Module(_) => env::current_dir().ok(), RunMode::Script(_) | RunMode::InstallPip(_) => None, // handled by run_script - RunMode::Repl => Some(String::new()), + RunMode::Repl => Some(PathBuf::new()), }; if let Some(path) = path0 { - vm.insert_sys_path(vm.new_pyobj(path))?; + vm.insert_sys_path(vm.fsdecode(path.into_os_string())?.into())?; } } @@ -342,8 +379,9 @@ fn run_rustpython(vm: &VirtualMachine, run_mode: RunMode) -> PyResult<()> { } let is_repl = matches!(run_mode, RunMode::Repl); + // pymain_header if !vm.state.config.settings.quiet - && (vm.state.config.settings.verbose > 0 || (is_repl && std::io::stdin().is_terminal())) + && (vm.state.config.settings.verbose > 0 || (is_repl && vm.stdin_is_interactive())) { eprintln!( "Welcome to the magnificent Rust Python {} interpreter \u{1f631} \u{1f596}", @@ -358,58 +396,258 @@ fn run_rustpython(vm: &VirtualMachine, run_mode: RunMode) -> PyResult<()> { eprintln!("Type \"help\", \"copyright\", \"credits\" or \"license\" for more information."); } - let res = match run_mode { + + let set_running_main = vm.state.set_running_main(); + let exitcode = + pymain_run_main(vm, scope, run_mode).unwrap_or_else(|exc| vm.handle_exit_exception(exc)); + if set_running_main { + vm.state.set_not_running_main(); + } + Ok(exitcode) +} + +/// The part of pymain_run_python that runs while the main thread owns +/// `__main__`. +fn pymain_run_main(vm: &VirtualMachine, scope: Scope, run_mode: RunMode) -> PyResult { + let is_repl = matches!(run_mode, RunMode::Repl); + vm.check_signals()?; + let result = match run_mode { RunMode::Command(command) => { - debug!("Running command {command}"); - vm.run_string(scope.clone(), &command, "").map(drop) + debug!("Running command {command:?}"); + run_command(vm, scope, command) } RunMode::Module(module) => { debug!("Running module {module}"); - vm.run_module(&module) + vm.run_module(&module).map(|()| 0) } - RunMode::InstallPip(installer) => install_pip(installer, scope.clone(), vm), + RunMode::InstallPip(installer) => install_pip(installer, scope, vm).map(|()| 0), RunMode::Script(script_path) => { // pymain_run_file_obj - debug!("Running script {script_path}"); - run_file(vm, scope.clone(), &script_path) + debug!("Running script {script_path:?}"); + run_file(vm, scope, &script_path) } - RunMode::Repl => Ok(()), + RunMode::Repl => Ok(pymain_run_stdin(vm, scope)), }; - let result = if is_repl || vm.state.config.settings.inspect { - if std::io::stdin().is_terminal() { - warn_if_pyrepl_unavailable(vm); - } - shell::run_shell(vm, scope) - } else { - res + let mut exitcode = result.unwrap_or_else(|exc| vm.handle_exit_exception(exc)); + vm.check_signals()?; + + pymain_repl(vm, !is_repl, &mut exitcode); + Ok(exitcode) +} + +fn run_command( + vm: &VirtualMachine, + scope: Scope, + mut command: std::ffi::OsString, +) -> PyResult { + // CPython appends a newline before auditing and executing -c. + command.push("\n"); + let command = vm.fsdecode(command)?; + // Audit failures do not receive the command-decoding error prefix. + vm.audit("cpython.run_command", || (command.clone(),))?; + + let Some(source) = command.to_str() else { + // CPython's dedent first requests strict UTF-8, so report positions + // in the original command, before removing indentation. These are + // Unicode character indices, not offsets into its WTF-8 bytes. + let mut points = command.as_wtf8().code_points(); + let start = points + .position(|point| point.to_char().is_none()) + .ok_or_else(|| vm.new_runtime_error("non-UTF-8 command has no surrogate"))?; + let end = start + 1 + points.take_while(|point| point.to_char().is_none()).count(); + let exc = vm.new_unicode_encode_error( + vm.ctx.new_str("utf-8"), + command, + start, + end, + vm.ctx.new_str("surrogates not allowed"), + ); + writeln!( + vm::stdlib::sys::PyStderr(vm), + "Unable to decode the command from the command line:" + ); + return Err(exc); }; - #[cfg(feature = "flame-it")] + let source = settings::dedent(source); + vm.run_string(scope, &source, "").map(|_| 0) +} + +/// pymain_err_print +/// +/// Report `exc` and return the exit code if it ends the process. +fn pymain_err_print(vm: &VirtualMachine, exc: PyBaseExceptionRef) -> Option { + if let Some(exitcode) = vm.handle_system_exit_and_keyboard_interrupt(&exc) { + return Some(exitcode); + } + vm.print_uncaught_exception(&exc); + None +} + +// pymain_set_inspect +fn pymain_set_inspect(vm: &VirtualMachine, inspect: bool) { + if let Err(exc) = vm.config_set_inspect(inspect) { + eprintln!("Could not set the inspect flag"); + vm.print_uncaught_exception(&exc); + } +} + +// pymain_run_startup +fn pymain_run_startup(vm: &VirtualMachine, scope: Scope) -> Option { + let exc = run_startup(vm, scope).err()?; + pymain_err_print(vm, exc) +} + +fn run_startup(vm: &VirtualMachine, scope: Scope) -> PyResult<()> { + if vm.state.config.settings.ignore_environment { + return Ok(()); + } + let Some(startup) = env::var_os("PYTHONSTARTUP").filter(|value| !value.is_empty()) else { + return Ok(()); + }; + let startup = vm.fsdecode(startup)?; + vm.audit("cpython.run_startup", || (startup.clone(),))?; + let could_not_open = |err: std::io::Error| { + use vm::convert::ToPyException; + writeln!( + vm::stdlib::sys::PyStderr(vm), + "Could not open PYTHONSTARTUP" + ); + let exc = err.to_pyexception(vm); + exc.as_object().set_attr("filename", startup.clone(), vm)?; + Err(exc) + }; + let path = vm.fsencode(&startup)?; + cfg_select! { + feature = "host_env" => match vm::host_env::fs::open(&path) { + Ok(_) => vm.run_any_file(scope, &path), + Err(err) => could_not_open(err), + }, + _ => match std::fs::read_to_string(&path) { + Ok(source) => vm.run_string_with_filename(scope, &source, &startup).map(drop), + Err(err) => could_not_open(err), + }, + } +} + +// pymain_run_interactive_hook +fn pymain_run_interactive_hook(vm: &VirtualMachine) -> Option { + let exc = run_interactive_hook(vm).err()?; + writeln!( + vm::stdlib::sys::PyStderr(vm), + "Failed calling sys.__interactivehook__" + ); + pymain_err_print(vm, exc) +} + +fn run_interactive_hook(vm: &VirtualMachine) -> PyResult<()> { + let Some(hook) = vm + .sys_module + .dict() + .get_item_opt("__interactivehook__", vm)? + else { + return Ok(()); + }; + vm.audit("cpython.run_interactivehook", || (hook.clone(),))?; + hook.call((), vm)?; + Ok(()) +} + +// pymain_run_stdin +fn pymain_run_stdin(vm: &VirtualMachine, scope: Scope) -> u32 { + if vm.stdin_is_interactive() { + // do exit on SystemExit + pymain_set_inspect(vm, false); + + if let Some(exitcode) = pymain_run_startup(vm, scope) { + return exitcode; + } + if let Some(exitcode) = pymain_run_interactive_hook(vm) { + return exitcode; + } + } + pymain_run_repl(vm, false) +} + +// pymain_repl +fn pymain_repl(vm: &VirtualMachine, run_code: bool, exitcode: &mut u32) { + // Check this environment variable at the end, to give programs the + // opportunity to set it from Python. + if !vm.config_inspect() + && !vm.state.config.settings.ignore_environment + && env::var_os("PYTHONINSPECT").is_some_and(|value| !value.is_empty()) { - main_guard.end(); - if let Err(e) = write_profile(&vm.state.as_ref().config.settings) { - error!("Error writing profile information: {}", e); + pymain_set_inspect(vm, true); + } + + if !(vm.config_inspect() && vm.stdin_is_interactive() && run_code) { + return; + } + + pymain_set_inspect(vm, false); + if let Some(code) = pymain_run_interactive_hook(vm) { + *exitcode = code; + return; + } + + *exitcode = pymain_run_repl(vm, true); +} + +// _pymain_run_repl +fn pymain_run_repl(vm: &VirtualMachine, startup: bool) -> u32 { + run_repl(vm, startup).unwrap_or_else(|exc| vm.handle_exit_exception(exc)) +} + +fn run_repl(vm: &VirtualMachine, startup: bool) -> PyResult { + vm.check_signals()?; + vm.audit("cpython.run_stdin", || ())?; + + let tty = std::io::stdin().is_terminal(); + if tty + && (vm.state.config.settings.ignore_environment + || env::var_os("PYTHON_BASIC_REPL").is_none_or(|value| value.is_empty())) + { + match vm.import("_pyrepl", 0) { + Ok(_) => return Ok(pymain_run_pyrepl(vm, startup)), + Err(exc) if !exc.fast_isinstance(vm.ctx.exceptions.module_not_found_error) => { + eprintln!("Could not import _pyrepl.main"); + return Err(exc); + } + Err(_) => {} } } - result + // _PyRun_AnyFile(stdin, "") + vm.run_any_stdin()?; + Ok(0) } -/// When the fancy REPL cannot start (for example `TERM=dumb`), print the same -/// warning `_pyrepl.main` would have printed, then keep the rustyline shell. -fn warn_if_pyrepl_unavailable(vm: &VirtualMachine) { - let _ = vm.run_simple_string( - r" -import os, sys -if not os.getenv('PYTHON_BASIC_REPL'): - try: - from _pyrepl.main import CAN_USE_PYREPL, FAIL_REASON - if not CAN_USE_PYREPL and FAIL_REASON: - print(FAIL_REASON, file=sys.stderr) - except Exception: - pass -", - ); +// pymain_run_pyrepl +fn pymain_run_pyrepl(vm: &VirtualMachine, pythonstartup: bool) -> u32 { + run_pyrepl(vm, pythonstartup).map_or_else(|exc| vm.handle_exit_exception(exc), |()| 0) +} + +fn run_pyrepl(vm: &VirtualMachine, pythonstartup: bool) -> PyResult<()> { + let pyrepl = vm.import("_pyrepl.main", 0).inspect_err(|_| { + eprintln!("Could not import _pyrepl.main"); + })?; + let console = pyrepl + .get_attr("main", vm) + .and_then(|main| main.get_attr("interactive_console", vm)) + .inspect_err(|_| { + eprintln!("Could not access _pyrepl.main.interactive_console"); + })?; + let kwargs: vm::function::KwArgs = [ + ("mainmodule".to_owned(), vm.add_main_module()?.into()), + ( + "pythonstartup".to_owned(), + vm.ctx.new_bool(pythonstartup).into(), + ), + ] + .into_iter() + .collect(); + console.call(vm::function::FuncArgs::new(vec![], kwargs), vm)?; + Ok(()) } #[cfg(feature = "flame-it")] diff --git a/src/main.rs b/src/main.rs index 32a8ccbddcd..6940763d991 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,12 +4,86 @@ use rustpython::{InterpreterBuilder, InterpreterBuilderExt}; #[global_allocator] static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc; -#[must_use] pub fn main() -> std::process::ExitCode { let mut config = InterpreterBuilder::new(); #[cfg(feature = "stdlib")] { config = config.init_stdlib(); } - rustpython::run(config) + #[cfg(all( + feature = "host_env", + feature = "stdio", + any(target_os = "linux", target_os = "macos") + ))] + { + let closed = startup_stdio::closed(); + config = config.init_hook(move |vm| { + rustpython::vm::common::rc::PyRc::get_mut(&mut vm.state) + .unwrap() + .config + .settings + .closed_stdio = closed; + }); + } + // SAFETY: the executable has not started threads or initialized the VM. + unsafe { rustpython::run_with_locale(config) } +} + +// Rust opens /dev/null for missing standard descriptors before calling main. +// Keep that safety measure, but remember which Python streams should be None. +// This initializer belongs to the executable, never an embedding library. +#[cfg(all( + feature = "host_env", + feature = "stdio", + any(target_os = "linux", target_os = "macos") +))] +mod startup_stdio { + use core::sync::atomic::{AtomicU8, Ordering}; + + static CLOSED: AtomicU8 = AtomicU8::new(0); + + extern "C" fn capture() { + // SAFETY: libc has initialized this thread-local cell before constructors. + #[cfg(target_os = "linux")] + let errno_ptr = unsafe { libc::__errno_location() }; + #[cfg(target_os = "macos")] + let errno_ptr = unsafe { libc::__error() }; + // SAFETY: the pointer is valid for this thread throughout the callback. + let saved_errno = unsafe { *errno_ptr }; + let mut mask = 0; + for fd in 0..3 { + loop { + // SAFETY: F_GETFD observes an integer descriptor without touching memory. + if unsafe { libc::fcntl(fd, libc::F_GETFD) } != -1 { + break; + } + // SAFETY: fcntl updated this thread's errno on failure. + let errno = unsafe { *errno_ptr }; + if errno == libc::EINTR { + continue; + } + if errno == libc::EBADF { + mask |= 1 << fd; + } + break; + } + } + // SAFETY: restore the same thread-local cell, leaving other constructors + // with the errno value they would have seen without these queries. + unsafe { *errno_ptr = saved_errno }; + CLOSED.store(mask, Ordering::Relaxed); + } + + // SAFETY: the loader calls this before Rust's runtime initialization. capture + // only uses libc descriptor queries and a lock-free atomic; no Rust I/O, + // allocation, thread creation, VM access, or descriptor mutation occurs. + #[used] + #[cfg_attr(target_os = "linux", unsafe(link_section = ".init_array"))] + #[cfg_attr(target_os = "macos", unsafe(link_section = "__DATA,__mod_init_func"))] + static CAPTURE: extern "C" fn() = capture; + + pub(super) fn closed() -> [bool; 3] { + let mask = CLOSED.load(Ordering::Relaxed); + core::array::from_fn(|fd| mask & (1 << fd) != 0) + } } diff --git a/src/settings.rs b/src/settings.rs index 975204c00e0..a4bb23cde9e 100644 --- a/src/settings.rs +++ b/src/settings.rs @@ -5,10 +5,12 @@ use lexopt::Arg::{Long, Short, Value}; use lexopt::ValueExt; use rustpython_vm::{Settings, vm::CheckHashPycsMode}; use std::env; +use std::ffi::OsString; +use std::path::PathBuf; pub enum RunMode { - Script(String), - Command(String), + Script(OsString), + Command(OsString), Module(String), InstallPip(InstallPipMode), Repl, @@ -95,6 +97,8 @@ Options (and corresponding environment variables): also PYTHONWARNINGS=arg -x : skip first line of source, allowing use of non-Unix forms of #!cmd -X opt : set implementation-specific option +-X lazy_imports=all|normal: control global lazy imports (default: normal); + also PYTHON_LAZY_IMPORTS --check-hash-based-pycs always|default|never: control how Python invalidates hash-based .pyc files --help-env: print help about Python environment variables and exit @@ -110,25 +114,21 @@ file : program read from script file arg ...: arguments passed to program in sys.argv[1:] "; -fn parse_args() -> Result<(CliArgs, RunMode, Vec), lexopt::Error> { +fn parse_args() -> Result<(CliArgs, RunMode, Vec), lexopt::Error> { let mut args = CliArgs::default(); let mut parser = lexopt::Parser::from_env(); - fn argv(argv0: String, mut parser: lexopt::Parser) -> Result, lexopt::Error> { - core::iter::once(Ok(argv0)) - .chain(parser.raw_args()?.map(|arg| arg.string())) - .collect() + fn argv(argv0: OsString, mut parser: lexopt::Parser) -> Result, lexopt::Error> { + // Arguments after the entry point are filesystem-encoded data, not + // necessarily Unicode. Decode only when constructing Python strings. + Ok(core::iter::once(argv0).chain(parser.raw_args()?).collect()) } while let Some(arg) = parser.next()? { match arg { Short('b') => args.bytes_warning += 1, Short('B') => args.dont_write_bytecode = true, Short('c') => { - let cmd = parser.value()?.string()?; - return Ok(( - args, - RunMode::Command(dedent(&cmd)), - argv("-c".to_owned(), parser)?, - )); + let cmd = parser.value()?; + return Ok((args, RunMode::Command(cmd), argv("-c".into(), parser)?)); } Short('d') => args.debug += 1, Short('E') => args.ignore_environment = true, @@ -137,7 +137,7 @@ fn parse_args() -> Result<(CliArgs, RunMode, Vec), lexopt::Error> { Short('I') => args.isolate = true, Short('m') => { let module = parser.value()?.string()?; - let argv = argv("-m".to_owned(), parser)?; + let argv = argv("-m".into(), parser)?; return Ok((args, RunMode::Module(module), argv)); } Short('O') => args.optimize += 1, @@ -169,22 +169,21 @@ fn parse_args() -> Result<(CliArgs, RunMode, Vec), lexopt::Error> { Long("install-pip") => { let (mode, argv) = if let Some(val) = parser.optional_value() { - (val.parse()?, vec![val.string()?]) + (val.parse()?, vec![val]) } else if let Ok(argv0) = parser.value() { let mode = argv0.parse()?; - (mode, argv(argv0.string()?, parser)?) + (mode, argv(argv0, parser)?) } else { ( InstallPipMode::Ensurepip, ["ensurepip", "--upgrade", "--default-pip"] - .map(str::to_owned) + .map(OsString::from) .into(), ) }; return Ok((args, RunMode::InstallPip(mode), argv)); } Value(script_name) => { - let script_name = script_name.string()?; let mode = if script_name == "-" { RunMode::Repl } else { @@ -215,14 +214,20 @@ pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> { let (args, mode, argv) = parse_args()?; let mut settings = Settings::default(); - settings.isolated = args.isolate; + if let Err(err) = rustpython_vm::getpath::configure_under_pth(&mut settings) { + eprintln!("Fatal Python error: cannot configure ._pth paths: {err}"); + std::process::exit(1); + } + settings.isolated |= args.isolate; settings.ignore_environment = settings.isolated || args.ignore_environment; settings.bytes_warning = args.bytes_warning.into(); - settings.import_site = !args.no_site; + if settings.under_pth != Some(rustpython_vm::getpath::UnderPth::Isolated) { + settings.import_site = !args.no_site; + } let ignore_environment = settings.ignore_environment; - if !ignore_environment { + if !ignore_environment && settings.under_pth.is_none() { settings.path_list.extend(get_paths("RUSTPYTHONPATH")); settings.path_list.extend(get_paths("PYTHONPATH")); } @@ -231,6 +236,12 @@ pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> { let get_env = |env| (!ignore_environment).then(|| env::var_os(env)).flatten(); + if settings.under_pth.is_none() { + settings.home = get_env("PYTHONHOME") + .filter(|home| !home.is_empty()) + .map(|home| home.to_string_lossy().into_owned()); + } + let env_count = |env| { get_env(env).filter(|v| !v.is_empty()).map_or(0, |val| { val.to_str().and_then(|v| v.parse::().ok()).unwrap_or(1) @@ -239,9 +250,26 @@ pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> { settings.optimize = cmp::max(args.optimize, env_count("PYTHONOPTIMIZE")); settings.verbose = cmp::max(args.verbose, env_count("PYTHONVERBOSE")); - settings.debug = cmp::max(args.debug, env_count("PYTHONDEBUG")); + settings.debug = u8::from(cmp::max(args.debug, env_count("PYTHONDEBUG")) != 0); + + #[cfg(windows)] + { + // _Py_get_env_flag: nonzero integers and invalid values enable the flag. + // spell-checker:ignore PYTHONLEGACYWINDOWSFSENCODING + settings.legacy_windows_fs_encoding = get_env("PYTHONLEGACYWINDOWSFSENCODING") + .filter(|value| !value.is_empty()) + .is_some_and(|value| { + value.to_str().and_then(|value| { + value + .trim_start_matches(|c: char| c.is_ascii_whitespace()) + .parse::() + .ok() + }) != Some(0) + }); + } let env_bool = |env| get_env(env).is_some_and(|v| !v.is_empty()); + settings.dev_mode = env_bool("PYTHONDEVMODE"); settings.user_site_directory = !(settings.isolated || args.no_user_site || env_bool("PYTHONNOUSERSITE")); @@ -280,25 +308,27 @@ pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> { } settings.check_hash_pycs_mode = args.check_hash_based_pycs; + settings.pycache_prefix = get_env("PYTHONPYCACHEPREFIX").filter(|value| !value.is_empty()); - if let Some(val) = get_env("PYTHONUTF8") - && let Some(val_str) = val.to_str() - && !val_str.is_empty() - { - settings.utf8_mode = match val_str { - "1" => 1, - "0" => 0, - _ => { - error!( - "Fatal Python error: config_init_utf8_mode: \ - PYTHONUTF8=N: N is missing or invalid\n\ - Python runtime state: preinitialized" - ); - std::process::exit(1); - } - }; + if let Some(val) = get_env("PYTHON_LAZY_IMPORTS").filter(|val| !val.is_empty()) { + settings.lazy_imports = parse_lazy_imports(val.to_str(), "PYTHON_LAZY_IMPORTS"); + } + + if let Some(value) = get_env("PYTHONPROFILEIMPORTTIME").filter(|value| !value.is_empty()) { + settings.import_time = parse_import_time(value.to_str(), "PYTHONPROFILEIMPORTTIME"); + } + + if let Some(value) = get_env("PYTHON_FROZEN_MODULES").filter(|value| !value.is_empty()) { + settings.use_frozen_modules = + parse_frozen_modules(Some(&value.to_string_lossy()), "PYTHON_FROZEN_MODULES"); } + // CPython uses the first occurrence of these -X options. + let mut lazy_imports_option_seen = false; + let mut import_time_option_seen = false; + let mut frozen_modules_option_seen = false; + let mut utf8_option_seen = false; + let mut pycache_prefix_option_seen = false; let xopts = args.implementation_option.into_iter().map(|s| { let (name, value) = match s.split_once('=') { Some((name, value)) => (name.to_owned(), Some(value)), @@ -306,25 +336,43 @@ pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> { }; match &*name { "dev" => settings.dev_mode = true, + "pycache_prefix" if !pycache_prefix_option_seen => { + settings.pycache_prefix = value.filter(|value| !value.is_empty()).map(Into::into); + pycache_prefix_option_seen = true; + } + "importtime" if !import_time_option_seen => { + settings.import_time = parse_import_time(value, "-X importtime"); + import_time_option_seen = true; + } + "frozen_modules" if !frozen_modules_option_seen => { + settings.use_frozen_modules = + parse_frozen_modules(value, "option -X frozen_modules"); + frozen_modules_option_seen = true; + } "faulthandler" => settings.faulthandler = true, "warn_default_encoding" => settings.warn_default_encoding = true, - "utf8" => { + "utf8" if !utf8_option_seen && !settings.legacy_windows_fs_encoding => { settings.utf8_mode = match value { None => 1, Some("1") => 1, Some("0") => 0, _ => { error!( - "Fatal Python error: config_init_utf8_mode: \ - -X utf8=n: n is missing or invalid\n\ + "Fatal Python error: preconfig_init_utf8_mode: \ + invalid -X utf8 option value\n\ Python runtime state: preinitialized" ); std::process::exit(1); } }; + utf8_option_seen = true; } "no_sig_int" => settings.install_signal_handlers = false, "no_debug_ranges" => settings.code_debug_ranges = false, + "lazy_imports" if !lazy_imports_option_seen => { + settings.lazy_imports = parse_lazy_imports(value, "-X lazy_imports"); + lazy_imports_option_seen = true; + } "cpu_count" => { settings.cpu_count = match parse_cpu_count(value) { Ok(cpu_count) => cpu_count, @@ -373,9 +421,42 @@ pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> { }); settings.xoptions.extend(xopts); + if !settings.legacy_windows_fs_encoding + && !utf8_option_seen + && let Some(val) = get_env("PYTHONUTF8").filter(|value| !value.is_empty()) + { + settings.utf8_mode = match val.to_str() { + Some("1") => 1, + Some("0") => 0, + _ => { + error!( + "Fatal Python error: preconfig_init_utf8_mode: \ + invalid PYTHONUTF8 environment variable value\n\ + Python runtime state: preinitialized" + ); + std::process::exit(1); + } + }; + } + + // CPython validates the first frozen_modules option before initialization, + // then getpath's config dictionary round-trip keeps the last occurrence. + if let Some((_, value)) = settings + .xoptions + .iter() + .rev() + .find(|(name, _)| name == "frozen_modules") + { + settings.use_frozen_modules = + parse_frozen_modules(value.as_deref(), "option -X frozen_modules"); + } + // Resolve utf8_mode if not explicitly set by PYTHONUTF8 or -X utf8. - // Default to UTF-8 mode since RustPython's locale encoding detection - // is incomplete. Users can set PYTHONUTF8=0 or -X utf8=0 to disable. + // CPython 3.15 defaults to UTF-8 mode (PEP 686). + // Users can set PYTHONUTF8=0 or -X utf8=0 to disable. + if cfg!(windows) && settings.legacy_windows_fs_encoding { + settings.utf8_mode = 0; + } if settings.utf8_mode < 0 { settings.utf8_mode = 1; } @@ -418,30 +499,34 @@ pub fn parse_opts() -> Result<(Settings, RunMode), lexopt::Error> { } } + // Lowest to highest priority; exact duplicate options keep their first position. + let mut add_warning = |warning: String| { + if !settings.warnoptions.contains(&warning) { + settings.warnoptions.push(warning); + } + }; if settings.dev_mode { - settings.warnoptions.push("default".to_owned()); + add_warning("default".to_owned()); settings.faulthandler = true; } + if let Some(val) = get_env("PYTHONWARNINGS") + && let Some(val_str) = val.to_str() + { + for warning in val_str.split(',').filter(|warning| !warning.is_empty()) { + add_warning(warning.to_owned()); + } + } + for warning in args.warning_control { + add_warning(warning); + } if settings.bytes_warning > 0 { let warn = if settings.bytes_warning > 1 { "error::BytesWarning" } else { "default::BytesWarning" }; - settings.warnoptions.push(warn.to_owned()); - } - if let Some(val) = get_env("PYTHONWARNINGS") - && let Some(val_str) = val.to_str() - && !val_str.is_empty() - { - for warning in val_str.split(',') { - let warning = warning.trim(); - if !warning.is_empty() { - settings.warnoptions.push(warning.to_owned()); - } - } + add_warning(warn.to_owned()); } - settings.warnoptions.extend(args.warning_control); settings.hash_seed = match (!args.random_hash_seed) .then(|| get_env("PYTHONHASHSEED")) @@ -488,17 +573,68 @@ fn parse_cpu_count(value: Option<&str>) -> Result, ()> { } } -fn get_paths(env_variable_name: &str) -> impl Iterator + '_ { +fn parse_frozen_modules(value: Option<&str>, source: &str) -> bool { + match value { + None | Some("" | "on") => true, + Some("off") => false, + _ => { + eprintln!( + "Fatal Python error: config_init_import: bad value for {source} (expected \"on\" or \"off\")" + ); + std::process::exit(1); + } + } +} + +/// = config_init_import_time +fn parse_import_time(value: Option<&str>, source: &str) -> u8 { + let value = value + .and_then(|value| { + value + .trim_start_matches([' ', '\t', '\n', '\r', '\x0b', '\x0c']) + .parse::() + .ok() + }) + .unwrap_or(1); + if !(0..=2).contains(&value) { + let numeric = if source == "PYTHONPROFILEIMPORTTIME" { + "numeric " + } else { + "" + }; + eprintln!( + "Fatal Python error: config_init_import_time: {source}: \ + {numeric}values other than 1 and 2 are reserved for future use.\n\ + Python runtime state: preinitialized\n" + ); + std::process::exit(1); + } + value as u8 +} + +/// = config_init_lazy_imports +fn parse_lazy_imports(value: Option<&str>, source: &str) -> i8 { + match value { + Some("normal") => -1, + Some("all") => 1, + _ => { + eprintln!( + "Fatal Python error: config_init_lazy_imports: \ + {source}: invalid value; expected 'all' or 'normal'\n\ + Python runtime state: preinitialized\n" + ); + std::process::exit(1); + } + } +} + +fn get_paths(env_variable_name: &str) -> impl Iterator + '_ { env::var_os(env_variable_name) .filter(|v| !v.is_empty()) .into_iter() - .flat_map(move |paths| { + .flat_map(|paths| { split_paths(&paths) - .map(|path| { - path.into_os_string() - .into_string() - .unwrap_or_else(|_| panic!("{env_variable_name} isn't valid unicode")) - }) + .map(PathBuf::into_os_string) .collect::>() }) } @@ -522,7 +658,7 @@ pub(crate) fn split_paths + ?Sized>( /// This is like textwrap.dedent, and is used to process -c's code /// argument. It's different from ruff's dedent, which does not /// distinguish between tab and space characters when dedenting. -fn dedent(input: &str) -> String { +pub(crate) fn dedent(input: &str) -> String { let mut prefix: Option = None; let isspace = |c| c == ' ' || c == '\t'; diff --git a/src/shell.rs b/src/shell.rs index d727003e6d6..7d206f28e9e 100644 --- a/src/shell.rs +++ b/src/shell.rs @@ -1,241 +1,41 @@ mod helper; -use rustpython_compiler::{ - CompileError, ParseError, parser::InterpolatedStringErrorType, parser::LexicalErrorType, - parser::ParseErrorType, -}; use rustpython_vm::{ - AsObject, PyResult, VirtualMachine, - builtins::PyBaseExceptionRef, - bytecode::CodeFlags, - compiler::{self}, + PyResult, VirtualMachine, readline::{Readline, ReadlineResult}, scope::Scope, - vm::VmCompileError, + vm::InteractiveLine, }; -enum ShellExecResult { - Ok, - PyErr(PyBaseExceptionRef), - ContinueBlock, - ContinueLine, -} - -fn shell_exec( - vm: &VirtualMachine, - source: &str, - scope: Scope, - empty_line_given: bool, - continuing_block: bool, - future_features: &mut CodeFlags, -) -> ShellExecResult { - // compiling expects only UNIX style line endings, and will replace windows line endings - // internally. Since we might need to analyze the source to determine if an error could be - // resolved by future input, we need the location from the error to match the source code that - // was actually compiled. - #[cfg(windows)] - let source = &source.replace("\r\n", "\n"); - let opts = compiler::CompileOpts { - future_features: *future_features, - ..vm.compile_opts() - }; - match vm.compile_with_opts(source, compiler::Mode::Single, "", opts) { - Ok(code) => { - *future_features |= code.code.flags & CodeFlags::FUTURE_MASK; - let _ = vm.register_code_in_linecache(&code, source); - if empty_line_given || !continuing_block { - match vm.run_code_obj(code, scope) { - Ok(_val) => ShellExecResult::Ok, - Err(err) => ShellExecResult::PyErr(err), - } - } else { - // We can just return an ok result - ShellExecResult::Ok - } - } - Err(err) => { - if matches!( - &err, - VmCompileError::Compile(CompileError::Parse(ParseError { - error: ParseErrorType::Lexical( - LexicalErrorType::Eof - | LexicalErrorType::FStringError( - InterpolatedStringErrorType::UnterminatedTripleQuotedString, - ) - ), - .. - })) - ) { - return ShellExecResult::ContinueLine; - } - if let VmCompileError::Compile(CompileError::Parse(ParseError { - error: ParseErrorType::Lexical(LexicalErrorType::UnclosedStringError), - raw_location, - .. - })) = &err - { - let loc = raw_location.start().to_usize(); - let mut iter = source.chars(); - if let Some(quote) = iter.nth(loc) - && iter.next() == Some(quote) - && iter.next() == Some(quote) - { - return ShellExecResult::ContinueLine; - } - } - - // An unfinished suite is _IncompleteInputError, not IndentationError. - let exc = err.into_pyexception_maybe_incomplete(vm, Some(source), !empty_line_given); - if !empty_line_given && exc.fast_isinstance(vm.ctx.exceptions.incomplete_input_error) { - ShellExecResult::ContinueBlock - } else { - ShellExecResult::PyErr(exc) - } - } - } -} - -fn flush_stdio(vm: &VirtualMachine) { - for name in ["stdout", "stderr"] { - if let Ok(stream) = vm.sys_module.get_attr(name, vm) { - let _ = vm.call_method(&stream, "flush", ()); - } - } -} - /// Enter a repl loop +/// +/// rustyline takes the role of `PyOS_Readline` with the readline module, +/// adding line editing, completion and history. pub fn run_shell(vm: &VirtualMachine, scope: Scope) -> PyResult<()> { - let mut repl = Readline::new(helper::ShellHelper::new(vm, scope.globals.clone())); - let mut full_input = String::new(); - - // Retrieve a `history_path_str` dependent on the OS - let repl_history_path = match dirs::config_dir() { - Some(mut path) => { + let mut repl = Readline::new(helper::ShellHelper::new(vm, scope.globals)); + let history = dirs::config_dir().map_or_else( + || ".repl_history.txt".into(), + |mut path| { path.push("rustpython"); path.push("repl_history.txt"); path + }, + ); + let _ = repl.load_history(&history); + let result = vm.run_interactive_loop(|prompt| match repl.readline(prompt) { + ReadlineResult::Line(line) => { + let _ = repl.add_history_entry(line.trim_end()); + Ok(Some(InteractiveLine::Text(line))) } - None => ".repl_history.txt".into(), - }; - - let _ = repl.load_history(&repl_history_path); - - // We might either be waiting to know if a block is complete, or waiting to know if a multiline - // statement is complete. In the former case, we need to ensure that we read one extra new line - // to know that the block is complete. In the latter, we can execute as soon as the statement is - // valid. - let mut continuing_block = false; - let mut continuing_line = false; - let mut future_features = CodeFlags::empty(); - - loop { - let prompt_name = if continuing_block || continuing_line { - "ps2" - } else { - "ps1" - }; - let prompt = vm - .sys_module - .get_attr(prompt_name, vm) - .and_then(|prompt| prompt.str(vm)); - let prompt = match prompt { - Ok(ref s) => s.expect_str(), - Err(_) => "", - }; - - continuing_line = false; - let result = match repl.readline(prompt) { - ReadlineResult::Line(line) => { - #[cfg(debug_assertions)] - debug!("You entered {line:?}"); - - repl.add_history_entry(line.trim_end()).unwrap(); - - let empty_line_given = line.is_empty(); - - if full_input.is_empty() { - full_input = line; - } else { - full_input.push_str(&line); - } - full_input.push('\n'); - - match shell_exec( - vm, - &full_input, - scope.clone(), - empty_line_given, - continuing_block, - &mut future_features, - ) { - ShellExecResult::Ok => { - if continuing_block { - if empty_line_given { - // We should exit continue mode since the block successfully executed - continuing_block = false; - full_input.clear(); - } - } else { - // We aren't in continue mode so proceed normally - full_input.clear(); - } - Ok(()) - } - // Continue, but don't change the mode - ShellExecResult::ContinueLine => { - continuing_line = true; - Ok(()) - } - ShellExecResult::ContinueBlock => { - continuing_block = true; - Ok(()) - } - ShellExecResult::PyErr(err) => { - continuing_block = false; - full_input.clear(); - Err(err) - } - } - } - ReadlineResult::Interrupt => { - continuing_block = false; - full_input.clear(); - let keyboard_interrupt = - vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned()); - Err(keyboard_interrupt) - } - ReadlineResult::Eof => { - break; - } - #[cfg(unix)] - ReadlineResult::OsError(num) => { - let os_error = vm.new_exception_msg( - vm.ctx.exceptions.os_error.to_owned(), - format!("{num:?}").into(), - ); - vm.print_exception(&os_error); - break; - } - ReadlineResult::Other(err) => { - eprintln!("Readline error: {err:?}"); - break; - } - ReadlineResult::Io(err) => { - eprintln!("IO error: {err:?}"); - break; - } - }; - - if let Err(exc) = result { - if exc.fast_isinstance(vm.ctx.exceptions.system_exit) { - repl.save_history(&repl_history_path).unwrap(); - return Err(exc); - } - vm.print_exception(&exc); + ReadlineResult::Eof => Ok(None), + ReadlineResult::Interrupt => { + Err(vm.new_exception_empty(vm.ctx.exceptions.keyboard_interrupt.to_owned())) } - flush_stdio(vm); - } - repl.save_history(&repl_history_path).unwrap(); - - Ok(()) + ReadlineResult::Io(_) => Ok(None), + #[cfg(unix)] + ReadlineResult::OsError(_) => Ok(None), + ReadlineResult::Other(_) => Ok(None), + }); + let _ = repl.save_history(&history); + result } diff --git a/src/shell/helper.rs b/src/shell/helper.rs index 15fc75563dc..a1c8c6301a2 100644 --- a/src/shell/helper.rs +++ b/src/shell/helper.rs @@ -1,14 +1,14 @@ #![cfg_attr(target_arch = "wasm32", allow(dead_code))] use rustpython_vm::{ - AsObject, PyResult, TryFromObject, VirtualMachine, - builtins::{PyDictRef, PyStrRef}, + AsObject, PyRef, PyResult, TryFromObject, VirtualMachine, + builtins::{PyAnyDict, PyStrRef}, function::ArgIterable, identifier, }; pub(super) struct ShellHelper<'vm> { vm: &'vm VirtualMachine, - globals: PyDictRef, + globals: PyRef, } fn reverse_string(s: &mut String) { @@ -54,7 +54,7 @@ fn split_idents_on_dot(line: &str) -> Option<(usize, Vec)> { } impl<'vm> ShellHelper<'vm> { - pub(super) const fn new(vm: &'vm VirtualMachine, globals: PyDictRef) -> Self { + pub(super) const fn new(vm: &'vm VirtualMachine, globals: PyRef) -> Self { ShellHelper { vm, globals } } @@ -149,8 +149,8 @@ impl<'vm> ShellHelper<'vm> { cfg_select! { not(target_arch = "wasm32") => { use rustyline::{ - completion::Completer, highlight::Highlighter, hint::Hinter, validate::Validator, Context, - Helper, + Context, Helper, completion::Completer, highlight::Highlighter, hint::Hinter, + validate::Validator, }; impl Completer for ShellHelper<'_> { type Candidate = String; diff --git a/tools/opcode_metadata/conf.toml b/tools/opcode_metadata/conf.toml index e69de29bb2d..765ecd1b45b 100644 --- a/tools/opcode_metadata/conf.toml +++ b/tools/opcode_metadata/conf.toml @@ -0,0 +1,2 @@ +[BuildListFromArg] +stack_effect = { pushed = "2", popped = "1" } diff --git a/tools/opcode_metadata/cpython.py b/tools/opcode_metadata/cpython.py index 56743a88842..950193c5621 100644 --- a/tools/opcode_metadata/cpython.py +++ b/tools/opcode_metadata/cpython.py @@ -1,3 +1,4 @@ +import functools import os import pathlib import sys @@ -18,10 +19,11 @@ from stack import get_stack_effect +@functools.cache def get_analysis() -> Analysis: from generators_common import DEFAULT_INPUT analysis = analyze_files([DEFAULT_INPUT]) - # Our speration is done at the enum definition + # Our separation is done at the enum definition analysis.instructions |= analysis.pseudos return analysis diff --git a/tools/opcode_metadata/generate_py_opcode_metadata.py b/tools/opcode_metadata/generate_py_opcode_metadata.py index 08f350e4b39..2341588cd5c 100644 --- a/tools/opcode_metadata/generate_py_opcode_metadata.py +++ b/tools/opcode_metadata/generate_py_opcode_metadata.py @@ -1,7 +1,5 @@ """ Generate Lib/_opcode_metadata.py for RustPython bytecode. - -This file generates opcode metadata that is compatible with CPython 3.14. """ import functools @@ -24,10 +22,10 @@ "RESUME", "INSTRUMENTED_LINE", "ENTER_EXECUTOR", + "TRACE_RECORD", } INDENT = " " * 4 -INDENT2 = INDENT * 2 def main(): @@ -43,52 +41,51 @@ def main(): out.write( f""" # This file is generated by {script_path} -# for RustPython bytecode format (CPython 3.14 compatible opcode numbers). +# for RustPython bytecode format. # Do not edit! """.lstrip() ) # _specializations - out.write("\n") - out.write("_specializations = {\n") + out.write("_specializations = frozendict(\n") deopts = functools.reduce(operator.ior, map(operator.attrgetter("deopts"), infos)) for key, lst in deopts.items(): key = to_upper_snake_case(key) - out.write(f'{INDENT}"{key}": [\n') + out.write(f"{INDENT}{key}=(\n") - for item in map(to_upper_snake_case, lst): - out.write(f'{INDENT2}"{item}",\n') + for item in map(to_upper_snake_case, dict.fromkeys(lst)): + out.write(f'{INDENT * 3}"{item}",\n') - out.write(f"{INDENT}],\n") + out.write(f"{INDENT}),\n") - out.write("}\n") + out.write(")\n") # _specialized_opmap out.write("\n") - out.write("_specialized_opmap = {\n") + out.write("_specialized_opmap = frozendict(\n") specialized = set(itertools.chain.from_iterable(deopts.values())) for opcode in sorted(opcodes, key=lambda op: op.cpython_name): if opcode.rust_name not in specialized: continue - out.write(f"{INDENT}'{opcode.cpython_name}': {opcode.id},\n") + out.write(f"{INDENT}{opcode.cpython_name}={opcode.id},\n") - out.write("}\n") + out.write(")\n") # opmap out.write("\n") - out.write("opmap = {\n") + out.write("opmap = frozendict(\n") key = lambda op: (op.cpython_name not in PRIORITY_OPMAP, op.id) for opcode in sorted(opcodes, key=key): if opcode.rust_name in specialized: continue - out.write(f"{INDENT}'{opcode.cpython_name}': {opcode.id},\n") + out.write(f"{INDENT}{opcode.cpython_name}={opcode.id},\n") - out.write("}\n") + out.write(")\n") # min out.write("\n") diff --git a/tools/opcode_metadata/generate_rs_opcode_metadata.py b/tools/opcode_metadata/generate_rs_opcode_metadata.py index b0a7e3f37ca..8009c481cd4 100644 --- a/tools/opcode_metadata/generate_rs_opcode_metadata.py +++ b/tools/opcode_metadata/generate_rs_opcode_metadata.py @@ -8,9 +8,8 @@ import pathlib import subprocess import sys -import typing - import tomllib +import typing from cpython import Analysis, get_analysis, get_stack_effect from opcodes import OpcodeInfo diff --git a/tools/opcode_metadata/opcodes.py b/tools/opcode_metadata/opcodes.py index 9178921b2c0..7550af1e258 100644 --- a/tools/opcode_metadata/opcodes.py +++ b/tools/opcode_metadata/opcodes.py @@ -33,10 +33,11 @@ def deopts(self) -> dict[str, list[str]]: for member in family.members: member_name = to_pascal_case(member.name) - if member.name == family_name: + if member_name == family_name or member_name not in names: continue - res[family_name].append(member_name) + if member_name not in res[family_name]: + res[family_name].append(member_name) return dict(res) @@ -76,6 +77,17 @@ def iter_opcodes(text: str, override_confs: OverrideConfs) -> Iterable[Opcode]: opcode = Opcode.from_str(entry) rust_name = opcode.rust_name + # Shared opcodes use CPython's wire-format IDs; RustPython-only + # instructions must occupy an otherwise unused slot. + expected_id = analysis.opmap.get(opcode.cpython_name) + if expected_id is not None and opcode.id != expected_id: + raise ValueError( + f"{rust_name} has opcode ID {opcode.id}; CPython requires {expected_id}" + ) + if expected_id is None and opcode.id in analysis.opmap.values(): + raise ValueError( + f"RustPython-only opcode {rust_name} collides with CPython ID {opcode.id}" + ) override = override_confs.get(rust_name, SKIP_OVERRIDE) cpython_name = opcode.cpython_name diff --git a/tools/opcode_metadata/utils.py b/tools/opcode_metadata/utils.py index bc3a9ace8d5..63f915ccd6c 100644 --- a/tools/opcode_metadata/utils.py +++ b/tools/opcode_metadata/utils.py @@ -2,7 +2,6 @@ import pathlib import re import sys - import tomllib ROOT = pathlib.Path(__file__).parents[2].resolve() diff --git a/wasm/demo/package-lock.json b/wasm/demo/package-lock.json index 3860bd7bd44..1a1a6318df4 100644 --- a/wasm/demo/package-lock.json +++ b/wasm/demo/package-lock.json @@ -9,22 +9,22 @@ "version": "1.0.0", "license": "MIT", "dependencies": { - "@codemirror/lang-python": "^6.1.6", - "@xterm/addon-fit": "^0.10.0", - "@xterm/xterm": "^5.3.0", - "codemirror": "^6.0.1", + "@codemirror/lang-python": "^6.2.1", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", + "codemirror": "^6.0.2", "upgrade": "^1.1.0", - "xterm-readline": "^1.1.2" + "xterm-readline": "^1.3.1" }, "devDependencies": { "@wasm-tool/wasm-pack-plugin": "^1.7.0", - "css-loader": "^7.1.2", - "html-webpack-plugin": "^5.6.3", - "mini-css-extract-plugin": "^2.9.2", - "serve": "^14.2.6", - "webpack": "^5.105.0", - "webpack-cli": "^6.0.1", - "webpack-dev-server": "^5.2.6" + "css-loader": "^7.1.5", + "html-webpack-plugin": "^5.6.8", + "mini-css-extract-plugin": "^2.10.2", + "serve": "^14.2.8", + "webpack": "^5.112.2", + "webpack-cli": "^7.3.1", + "webpack-dev-server": "^6.1.0" } }, "node_modules/@codemirror/autocomplete": { @@ -52,9 +52,9 @@ } }, "node_modules/@codemirror/lang-python": { - "version": "6.1.7", - "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.1.7.tgz", - "integrity": "sha512-mZnFTsL4lW5p9ch8uKNKeRU3xGGxr1QpESLilfON2E3fQzOa/OygEMkaDvERvXDJWJA9U9oN/D4w0ZuUzNO4+g==", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/@codemirror/lang-python/-/lang-python-6.2.1.tgz", + "integrity": "sha512-IRjC8RUBhn9mGR9ywecNhB51yePWCGgvHfY1lWN/Mrp3cKuHr0isDKia+9HnvhiWNnMpbGhWrkhuWOc09exRyw==", "license": "MIT", "dependencies": { "@codemirror/autocomplete": "^6.3.2", @@ -121,9 +121,9 @@ } }, "node_modules/@discoveryjs/json-ext": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-0.6.3.tgz", - "integrity": "sha512-4B4OijXeVNOPZlYA2oEwWOTkzyltLao+xbotHQeqN++Rv27Y6s818+n2Qkp8q+Fxhn0t/5lA5X1Mxktud8eayQ==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@discoveryjs/json-ext/-/json-ext-1.1.0.tgz", + "integrity": "sha512-Xc3VhU02wqZ1HvHRJUwL09HkZSTvidqY5Ya0NXBSYOxAp+Ln9dcJr9fySI+CkONzP3PekQo9WdzCv0PGER/mOA==", "dev": true, "license": "MIT", "engines": { @@ -184,9 +184,9 @@ "license": "MIT" }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.25", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", - "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "dev": true, "license": "MIT", "dependencies": { @@ -246,14 +246,14 @@ } }, "node_modules/@jsonjoy.com/fs-core": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-core/-/fs-core-4.80.0.tgz", - "integrity": "sha512-qMKWshnyjbyhm+NbzqGE3w5y1mckFFEMj0aDPU2/JBNh1BzIjVy9esq9lBmRnNVmhMEkxwDzLZ8Gqh5G1P5Dag==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-core/-/fs-core-4.80.1.tgz", + "integrity": "sha512-SPNK9zGATkbtrGuxs0ozJyPARUxCjGAPElbwldaxcygJYF1JmGsmUJo5xyGSCZHR7lbM62FIcavCU677TIQXCg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@jsonjoy.com/fs-node-builtins": "4.80.0", - "@jsonjoy.com/fs-node-utils": "4.80.0", + "@jsonjoy.com/fs-node-builtins": "4.80.1", + "@jsonjoy.com/fs-node-utils": "4.80.1", "thingies": "^2.5.0" }, "engines": { @@ -268,15 +268,15 @@ } }, "node_modules/@jsonjoy.com/fs-fsa": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-fsa/-/fs-fsa-4.80.0.tgz", - "integrity": "sha512-ZBEKl7J6dbkRCfmrFV48Re211A/FHqniTUhsWCsaRteNSOqMgkX3qF1UreVgwB9oSPm81JLAwhIi6Lb/NH/PoA==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-fsa/-/fs-fsa-4.80.1.tgz", + "integrity": "sha512-KkgyRMPWFAv87SonKaNHYmVbVc4Y7YI2xvkushnWuFDtbO9qbLTcs2ysbCnTEfRq8duo5e/2gKqnZnNOR/oJaw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@jsonjoy.com/fs-core": "4.80.0", - "@jsonjoy.com/fs-node-builtins": "4.80.0", - "@jsonjoy.com/fs-node-utils": "4.80.0", + "@jsonjoy.com/fs-core": "4.80.1", + "@jsonjoy.com/fs-node-builtins": "4.80.1", + "@jsonjoy.com/fs-node-utils": "4.80.1", "thingies": "^2.5.0" }, "engines": { @@ -291,17 +291,17 @@ } }, "node_modules/@jsonjoy.com/fs-node": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node/-/fs-node-4.80.0.tgz", - "integrity": "sha512-yiBlUfkMMRFFGy8CD/h2zd5rPnrM6bjlF+nx2LRAxNV6hOSiuObQIUEE7m7y2VTMisjxCRtzINH94bFGySWL7g==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node/-/fs-node-4.80.1.tgz", + "integrity": "sha512-yLS6KOoaByVp/B9w2bM9xDMd2uTWjY0hYfk9bTxqQrpBkRvxkJsPYzMej+j05AyR4u6Q/LYgrWQE7qs0r0NkZg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@jsonjoy.com/fs-core": "4.80.0", - "@jsonjoy.com/fs-node-builtins": "4.80.0", - "@jsonjoy.com/fs-node-utils": "4.80.0", - "@jsonjoy.com/fs-print": "4.80.0", - "@jsonjoy.com/fs-snapshot": "4.80.0", + "@jsonjoy.com/fs-core": "4.80.1", + "@jsonjoy.com/fs-node-builtins": "4.80.1", + "@jsonjoy.com/fs-node-utils": "4.80.1", + "@jsonjoy.com/fs-print": "4.80.1", + "@jsonjoy.com/fs-snapshot": "4.80.1", "glob-to-regex.js": "^1.3.1", "thingies": "^2.5.0" }, @@ -317,9 +317,9 @@ } }, "node_modules/@jsonjoy.com/fs-node-builtins": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-builtins/-/fs-node-builtins-4.80.0.tgz", - "integrity": "sha512-OIOIhqaWiwUySFMny4epIAoviXsyMaQQ63PTc3zH+5HEOvarl5hpUmZIhp2m5+OfyKAh5ylxXnQIgew1OgJDVw==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-builtins/-/fs-node-builtins-4.80.1.tgz", + "integrity": "sha512-GpbDCdBVkKdh6rZ0xYX0xw/VqGInAgSkafcCVbvaBHKL+sFLheYWF21KHpE7MGzvoDrw3CTYA3Mq6AJEHkwoEg==", "dev": true, "license": "Apache-2.0", "engines": { @@ -334,15 +334,15 @@ } }, "node_modules/@jsonjoy.com/fs-node-to-fsa": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-to-fsa/-/fs-node-to-fsa-4.80.0.tgz", - "integrity": "sha512-ljeaR5xwtX1EyRmB0wvXANUMQZ3mjKcm7z8s2N8D8SLQ04CcAGtUhHFRZQXFb9mhgFyEVMydQGQtSOFS7pcrFQ==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-to-fsa/-/fs-node-to-fsa-4.80.1.tgz", + "integrity": "sha512-HRr5pDz5B8EAtpHUh2rzw+HA6yU3ppYeNDHJouU8CvxFfxTVBv19F2owwW3z5UbOoFd1+y/gZZPvLQrzO4i8OA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@jsonjoy.com/fs-fsa": "4.80.0", - "@jsonjoy.com/fs-node-builtins": "4.80.0", - "@jsonjoy.com/fs-node-utils": "4.80.0" + "@jsonjoy.com/fs-fsa": "4.80.1", + "@jsonjoy.com/fs-node-builtins": "4.80.1", + "@jsonjoy.com/fs-node-utils": "4.80.1" }, "engines": { "node": ">=10.0" @@ -356,13 +356,13 @@ } }, "node_modules/@jsonjoy.com/fs-node-utils": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-utils/-/fs-node-utils-4.80.0.tgz", - "integrity": "sha512-xwHeVVi3f+Khg/Fmb8i5qoYVmQ08QznE5TWhQokUmIZjz4KBPzU+zt/+bahBI6G1ghtqajt27lWuAciIxApuzA==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-node-utils/-/fs-node-utils-4.80.1.tgz", + "integrity": "sha512-cZVc6+cj6RTSwqxHNCCdqCKQ49b/Zn0ebmG+7m2Vvozkh5ZuiiKJIK8ZULp07u5uMilxDokERw+5opfR7/AhJw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@jsonjoy.com/fs-node-builtins": "4.80.0", + "@jsonjoy.com/fs-node-builtins": "4.80.1", "glob-to-regex.js": "^1.3.1" }, "engines": { @@ -377,13 +377,13 @@ } }, "node_modules/@jsonjoy.com/fs-print": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-print/-/fs-print-4.80.0.tgz", - "integrity": "sha512-1ocZLJw/m/xlq0moaIHO7HV9nHRVBUvdc2zMzhsJGkFOrqfwWvexfCv5cYCPPLRhP+9p3yunoi4Ep5YhRORC9Q==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-print/-/fs-print-4.80.1.tgz", + "integrity": "sha512-FPVCZbuvb343XUzVuR571+U8boOIEysgWYvCY2rns5K0Sb1efRIk4WDvLUmyA/RO/OKMZP+sp1gC7Gqw20f5iQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@jsonjoy.com/fs-node-utils": "4.80.0", + "@jsonjoy.com/fs-node-utils": "4.80.1", "tree-dump": "^1.1.0" }, "engines": { @@ -398,14 +398,14 @@ } }, "node_modules/@jsonjoy.com/fs-snapshot": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-snapshot/-/fs-snapshot-4.80.0.tgz", - "integrity": "sha512-3AV23Q1H228KTtJKTUE0nNq8FCtxSvtENOLrEat80wkAJCKHuqQEv8yjhpS8Bei2OEFJAnluGXp9Ri2SWBlROw==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/@jsonjoy.com/fs-snapshot/-/fs-snapshot-4.80.1.tgz", + "integrity": "sha512-q0edmZlsrGyzWRacYMO6aAE+PkCJVBVO7d+kJAJkXIHtOEhErbSr3PTPXef9yamgKLwf4MXkMGJMo4cl2f3PHQ==", "dev": true, "license": "Apache-2.0", "dependencies": { "@jsonjoy.com/buffers": "^17.65.0", - "@jsonjoy.com/fs-node-utils": "4.80.0", + "@jsonjoy.com/fs-node-utils": "4.80.1", "@jsonjoy.com/json-pack": "^17.65.0", "@jsonjoy.com/util": "^17.65.0" }, @@ -897,65 +897,29 @@ "@types/node": "*" } }, - "node_modules/@types/eslint": { - "version": "9.6.1", - "resolved": "https://registry.npmjs.org/@types/eslint/-/eslint-9.6.1.tgz", - "integrity": "sha512-FXx2pKgId/WyYo2jXw63kk7/+TY7u7AziEJxJAnSFzHlqTAS3Ync6SvgYAN/k4/PQpnnVuzoMuVnByKK2qp0ag==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/estree": "*", - "@types/json-schema": "*" - } - }, - "node_modules/@types/eslint-scope": { - "version": "3.7.7", - "resolved": "https://registry.npmjs.org/@types/eslint-scope/-/eslint-scope-3.7.7.tgz", - "integrity": "sha512-MzMFlSLBqNF2gcHWO0G1vP/YQyfvrxZ0bF+u7mzUdZ1/xK4A4sru+nraZz5i3iEIk1l1uyicaDVTB4QbbEkAYg==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/eslint": "*", - "@types/estree": "*" - } - }, "node_modules/@types/estree": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", - "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", "dev": true, "license": "MIT" }, "node_modules/@types/express": { - "version": "4.17.25", - "resolved": "https://registry.npmjs.org/@types/express/-/express-4.17.25.tgz", - "integrity": "sha512-dVd04UKsfpINUnK0yBoYHDF3xu7xVH4BuDotC/xGuycx4CgbP48X/KF/586bcObxT0HENHXEU8Nqtu6NR+eKhw==", + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/@types/express/-/express-5.0.6.tgz", + "integrity": "sha512-sKYVuV7Sv9fbPIt/442koC7+IIwK5olP1KWeD88e/idgoJqDm3JV/YUiPwkoKK92ylff2MGxSz1CSjsXelx0YA==", "dev": true, "license": "MIT", "dependencies": { "@types/body-parser": "*", - "@types/express-serve-static-core": "^4.17.33", - "@types/qs": "*", - "@types/serve-static": "^1" + "@types/express-serve-static-core": "^5.0.0", + "@types/serve-static": "^2" } }, "node_modules/@types/express-serve-static-core": { - "version": "5.0.6", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.0.6.tgz", - "integrity": "sha512-3xhRnjJPkULekpSzgtoNYYcTWgEZkp4myc+Saevii5JPnHNvHMRlBSHDbs7Bh1iPPoVTERHEZXyhyLbMEsExsA==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*", - "@types/send": "*" - } - }, - "node_modules/@types/express/node_modules/@types/express-serve-static-core": { - "version": "4.19.6", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz", - "integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==", + "version": "5.1.3", + "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-5.1.3.tgz", + "integrity": "sha512-dPfW8NFiOF4wOHc7+N/QSxlY9cfSsenewGbAz8C8U/MULPd/YZ27LvJUIlzaXie7e6Ove9YunJGgC9tbHD2cKw==", "dev": true, "license": "MIT", "dependencies": { @@ -973,22 +937,12 @@ "license": "MIT" }, "node_modules/@types/http-errors": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.4.tgz", - "integrity": "sha512-D0CFMMtydbJAegzOyHjtiKPLlvnm3iTZyZRSZoLq2mRhDdmLfIWOCYPfQJ4cu2erKghU++QvjcUjp/5h7hESpA==", + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@types/http-errors/-/http-errors-2.0.5.tgz", + "integrity": "sha512-r8Tayk8HJnX0FztbZN7oVqGccWgw98T/0neJphO91KkmOzug1KkofZURD4UaD5uH8AqcFLfdPErnBod0u71/qg==", "dev": true, "license": "MIT" }, - "node_modules/@types/http-proxy": { - "version": "1.17.16", - "resolved": "https://registry.npmjs.org/@types/http-proxy/-/http-proxy-1.17.16.tgz", - "integrity": "sha512-sdWoUajOB1cd0A8cRRQ1cfyWNbmFKLAqBB89Y8x5iYyG/mkJHc0YUH8pdWBy2omi9qtCpiIgGjuwO0dQST2l5w==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*" - } - }, "node_modules/@types/json-schema": { "version": "7.0.15", "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", @@ -1027,13 +981,6 @@ "dev": true, "license": "MIT" }, - "node_modules/@types/retry": { - "version": "0.12.2", - "resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.2.tgz", - "integrity": "sha512-XISRgDJ2Tc5q4TRqvgJtzsRkFYNJzZrhTdtMoGVBttwzzQJkPnS3WWTFc7kuDRoPtPakl+T+OfdEUjYJj7Jbow==", - "dev": true, - "license": "MIT" - }, "node_modules/@types/send": { "version": "0.17.4", "resolved": "https://registry.npmjs.org/@types/send/-/send-0.17.4.tgz", @@ -1056,31 +1003,20 @@ } }, "node_modules/@types/serve-static": { - "version": "1.15.7", - "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-1.15.7.tgz", - "integrity": "sha512-W8Ym+h8nhuRwaKPaDw34QUkwsGi6Rc4yYqvKFo5rm2FUEhCFbzVWrxXUxuKK8TASjWsysJY0nsmNCGhCOIsrOw==", + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@types/serve-static/-/serve-static-2.2.0.tgz", + "integrity": "sha512-8mam4H1NHLtu7nmtalF7eyBH14QyOASmcxHhSfEoRyr0nP/YdoesEtU+uSRvMe96TW/HPTtkoKqQLl53N7UXMQ==", "dev": true, "license": "MIT", "dependencies": { "@types/http-errors": "*", - "@types/node": "*", - "@types/send": "*" - } - }, - "node_modules/@types/sockjs": { - "version": "0.3.36", - "resolved": "https://registry.npmjs.org/@types/sockjs/-/sockjs-0.3.36.tgz", - "integrity": "sha512-MK9V6NzAS1+Ud7JV9lJLFqW85VbC9dq3LmwZCuBe4wBDgKC0Kj/jd8Xl+nSviU+Qc3+m7umHHyHg//2KSa0a0Q==", - "dev": true, - "license": "MIT", - "dependencies": { "@types/node": "*" } }, "node_modules/@types/ws": { - "version": "8.5.14", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.14.tgz", - "integrity": "sha512-bd/YFLW+URhBzMXurx7lWByOu+xzU9+kb3RboOteXYDfW+tr+JZa99OyNmPINEGB/ahzKrEuc8rcv4gnpJmxTw==", + "version": "8.18.2", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.2.tgz", + "integrity": "sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==", "dev": true, "license": "MIT", "dependencies": { @@ -1261,67 +1197,20 @@ "@xtuc/long": "4.2.2" } }, - "node_modules/@webpack-cli/configtest": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@webpack-cli/configtest/-/configtest-3.0.1.tgz", - "integrity": "sha512-u8d0pJ5YFgneF/GuvEiDA61Tf1VDomHHYMjv/wc9XzYj7nopltpG96nXN5dJRstxZhcNpV1g+nT6CydO7pHbjA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12.0" - }, - "peerDependencies": { - "webpack": "^5.82.0", - "webpack-cli": "6.x.x" - } - }, - "node_modules/@webpack-cli/info": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@webpack-cli/info/-/info-3.0.1.tgz", - "integrity": "sha512-coEmDzc2u/ffMvuW9aCjoRzNSPDl/XLuhPdlFRpT9tZHmJ/039az33CE7uH+8s0uL1j5ZNtfdv0HkfaKRBGJsQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12.0" - }, - "peerDependencies": { - "webpack": "^5.82.0", - "webpack-cli": "6.x.x" - } - }, - "node_modules/@webpack-cli/serve": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@webpack-cli/serve/-/serve-3.0.1.tgz", - "integrity": "sha512-sbgw03xQaCLiT6gcY/6u3qBDn01CWw/nbaXl3gTdTFuJJ75Gffv3E3DBpgvY2fkkrdS1fpjaXNOmJlnbtKauKg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=18.12.0" - }, - "peerDependencies": { - "webpack": "^5.82.0", - "webpack-cli": "6.x.x" - }, - "peerDependenciesMeta": { - "webpack-dev-server": { - "optional": true - } - } - }, "node_modules/@xterm/addon-fit": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.10.0.tgz", - "integrity": "sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==", - "license": "MIT", - "peerDependencies": { - "@xterm/xterm": "^5.0.0" - } + "version": "0.11.0", + "resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz", + "integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==", + "license": "MIT" }, "node_modules/@xterm/xterm": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz", - "integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==", - "license": "MIT" + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz", + "integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==", + "license": "MIT", + "workspaces": [ + "addons/*" + ] }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", @@ -1345,14 +1234,14 @@ "license": "MIT" }, "node_modules/accepts": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", - "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz", + "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==", "dev": true, "license": "MIT", "dependencies": { - "mime-types": "~2.1.34", - "negotiator": "0.6.3" + "mime-types": "^3.0.0", + "negotiator": "^1.0.0" }, "engines": { "node": ">= 0.6" @@ -1371,19 +1260,6 @@ "node": ">=0.4.0" } }, - "node_modules/acorn-import-phases": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/acorn-import-phases/-/acorn-import-phases-1.0.4.tgz", - "integrity": "sha512-wKmbr/DDiIXzEOiWrTTUcDm24kQ2vGfZQvM2fwg2vXqR5uW6aapr7ObPtj1th32b9u90/Pf4AItvdTh42fBmVQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10.13.0" - }, - "peerDependencies": { - "acorn": "^8.14.0" - } - }, "node_modules/ajv": { "version": "8.18.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.18.0.tgz", @@ -1402,9 +1278,9 @@ } }, "node_modules/ajv-formats": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-2.1.1.tgz", - "integrity": "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA==", + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz", + "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==", "dev": true, "license": "MIT", "dependencies": { @@ -1464,19 +1340,6 @@ "node": ">=8" } }, - "node_modules/ansi-html-community": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/ansi-html-community/-/ansi-html-community-0.0.8.tgz", - "integrity": "sha512-1APHAyr3+PCamwNw3bXCPp4HFLONZt/yIH0sZp0/469KWNTEy+qN5jQ3GVX6DMZ1UXAi34yVwtTeaG/HpBuuzw==", - "dev": true, - "engines": [ - "node >= 0.8.0" - ], - "license": "Apache-2.0", - "bin": { - "ansi-html": "bin/ansi-html" - } - }, "node_modules/ansi-regex": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", @@ -1499,41 +1362,6 @@ "node": ">=4" } }, - "node_modules/anymatch": { - "version": "3.1.3", - "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", - "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", - "dev": true, - "license": "ISC", - "dependencies": { - "normalize-path": "^3.0.0", - "picomatch": "^2.0.4" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/arch": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/arch/-/arch-2.2.0.tgz", - "integrity": "sha512-Of/R0wqp83cgHozfIYLbBMnej79U/SVGOOyuB3VVFv1NRM/PSFMK12x9KVtiYzJqmnU5WR2qp0Z5rHb7sWGnFQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/arg": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/arg/-/arg-5.0.2.tgz", @@ -1541,13 +1369,6 @@ "dev": true, "license": "MIT" }, - "node_modules/array-flatten": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", - "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==", - "dev": true, - "license": "MIT" - }, "node_modules/asn1js": { "version": "3.0.10", "resolved": "https://registry.npmjs.org/asn1js/-/asn1js-3.0.10.tgz", @@ -1590,42 +1411,29 @@ "dev": true, "license": "MIT" }, - "node_modules/binary-extensions": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", - "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/body-parser": { - "version": "1.20.5", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", - "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.4.0.tgz", + "integrity": "sha512-Ifk1KcLrxaGt1occQagQNFNNOqRt1LFuehEnHHzB8Z6cRgIxRU1TBaiIsUiCdA+gy5PL7Y1IX31DNKkRmxtXjQ==", "dev": true, "license": "MIT", "dependencies": { - "bytes": "~3.1.2", - "content-type": "~1.0.5", - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "~1.2.0", - "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", - "on-finished": "~2.4.1", - "qs": "~6.15.1", - "raw-body": "~2.5.3", - "type-is": "~1.6.18", - "unpipe": "~1.0.0" + "bytes": "^3.1.2", + "content-type": "^2.1.0", + "debug": "^4.4.3", + "http-errors": "^2.0.1", + "iconv-lite": "^0.7.3", + "on-finished": "^2.4.1", + "qs": "^6.16.1", + "raw-body": "^3.0.2", + "type-is": "^2.1.0" }, "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/body-parser/node_modules/bytes": { @@ -1638,36 +1446,30 @@ "node": ">= 0.8" } }, - "node_modules/body-parser/node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "node_modules/body-parser/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" + "ms": "^2.1.3" }, "engines": { - "node": ">= 0.8" + "node": ">=6.0" }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "node_modules/body-parser/node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "node_modules/body-parser/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } + "license": "MIT" }, "node_modules/bonjour-service": { "version": "1.3.0", @@ -1789,9 +1591,9 @@ "license": "MIT" }, "node_modules/bundle-name": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.0.tgz", - "integrity": "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q==", + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/bundle-name/-/bundle-name-4.1.1.tgz", + "integrity": "sha512-DdH81/zPLVS11EUgWq3tEu/xn+EzljlMYooDNdzWEnFha3R3NBMpMV1UqYIpjYHV/SgpFKMIX1Oh7o06SjM/oA==", "dev": true, "license": "MIT", "dependencies": { @@ -1839,14 +1641,14 @@ } }, "node_modules/call-bound": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.3.tgz", - "integrity": "sha512-YTd+6wGlNlPxSuri7Y6X8tY2dmm12UMH66RpKMhiX6rsk5wXXnYgbUcOt8kiS31/AjfoTOvCsE+w8nZQLQnzHA==", + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", "dev": true, "license": "MIT", "dependencies": { - "call-bind-apply-helpers": "^1.0.1", - "get-intrinsic": "^1.2.6" + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" }, "engines": { "node": ">= 0.4" @@ -2008,28 +1810,19 @@ } }, "node_modules/chokidar": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", - "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-5.0.0.tgz", + "integrity": "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw==", "dev": true, "license": "MIT", "dependencies": { - "anymatch": "~3.1.2", - "braces": "~3.0.2", - "glob-parent": "~5.1.2", - "is-binary-path": "~2.1.0", - "is-glob": "~4.0.1", - "normalize-path": "~3.0.0", - "readdirp": "~3.6.0" + "readdirp": "^5.0.0" }, "engines": { - "node": ">= 8.10.0" + "node": ">= 20.19.0" }, "funding": { "url": "https://paulmillr.com/funding/" - }, - "optionalDependencies": { - "fsevents": "~2.3.2" } }, "node_modules/chrome-trace-event": { @@ -2068,24 +1861,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/clipboardy": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/clipboardy/-/clipboardy-3.0.0.tgz", - "integrity": "sha512-Su+uU5sr1jkUy1sGRpLKjKrvEOVXgSgiSInwa/qeID6aJ07yh+5NWc3h2QfjHjBnfX4LhtFcuAWKUsJ3r+fjbg==", - "dev": true, - "license": "MIT", - "dependencies": { - "arch": "^2.2.0", - "execa": "^5.1.1", - "is-wsl": "^2.2.0" - }, - "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/clone-deep": { "version": "4.0.1", "resolved": "https://registry.npmjs.org/clone-deep/-/clone-deep-4.0.1.tgz", @@ -2102,9 +1877,9 @@ } }, "node_modules/codemirror": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.1.tgz", - "integrity": "sha512-J8j+nZ+CdWmIeFIGXEFbFPtpiYacFMDR8GlHK3IyHQJMCaVRfGx9NT+Hxivv1ckLWPvNdZqndbr/7lVhrf/Svg==", + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/codemirror/-/codemirror-6.0.2.tgz", + "integrity": "sha512-VhydHotNW5w1UGK0Qj96BwSk/Zqbp9WbnyK2W/eVMv4QyF41INRGpjUhFJY7/uDNuudSc33a/PKr4iDqRduvHw==", "license": "MIT", "dependencies": { "@codemirror/autocomplete": "^6.0.0", @@ -2133,13 +1908,6 @@ "dev": true, "license": "MIT" }, - "node_modules/colorette": { - "version": "2.0.20", - "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", - "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", - "dev": true, - "license": "MIT" - }, "node_modules/command-exists": { "version": "1.2.9", "resolved": "https://registry.npmjs.org/command-exists/-/command-exists-1.2.9.tgz", @@ -2171,15 +1939,16 @@ } }, "node_modules/compression": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", - "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "version": "1.8.2", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.2.tgz", + "integrity": "sha512-o8vI5RE5A6EVVOd9o41jKp41aJom+QTEO/Bx8MYNjexMo/Bv2WOjUfZr+aL0WnYSgymUy6zeguqLTsIhV0gMvQ==", "dev": true, "license": "MIT", "dependencies": { "bytes": "3.1.2", "compressible": "~2.0.18", "debug": "2.6.9", + "destroy": "1.2.0", "negotiator": "~0.6.4", "on-headers": "~1.1.0", "safe-buffer": "5.2.1", @@ -2187,6 +1956,10 @@ }, "engines": { "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/compression/node_modules/bytes": { @@ -2258,19 +2031,23 @@ } }, "node_modules/content-type": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", - "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz", + "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==", "dev": true, "license": "MIT", "engines": { - "node": ">= 0.6" + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/cookie": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", - "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", "dev": true, "license": "MIT", "engines": { @@ -2278,18 +2055,14 @@ } }, "node_modules/cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz", + "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==", "dev": true, - "license": "MIT" - }, - "node_modules/core-util-is": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", - "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", - "dev": true, - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">=6.6.0" + } }, "node_modules/crelt": { "version": "1.0.6", @@ -2297,36 +2070,21 @@ "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", "license": "MIT" }, - "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.1.0", - "shebang-command": "^2.0.0", - "which": "^2.0.1" - }, - "engines": { - "node": ">= 8" - } - }, "node_modules/css-loader": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-7.1.2.tgz", - "integrity": "sha512-6WvYYn7l/XEGN8Xu2vWFt9nVzrCn39vKyTEFf/ExEyoksJjjSZV/0/35XPlMbpnr6VGhZIUg5yJrL8tGfes/FA==", + "version": "7.1.5", + "resolved": "https://registry.npmjs.org/css-loader/-/css-loader-7.1.5.tgz", + "integrity": "sha512-Q7iAfQkU2twNBryKX/vGAlE+GAmkF7quhSzAGNK8fBimxk3+tqg245rH52UPb9dioBolBc8rP0ihmHBaDTJQBA==", "dev": true, "license": "MIT", "dependencies": { "icss-utils": "^5.1.0", - "postcss": "^8.4.33", + "postcss": "^8.4.40", "postcss-modules-extract-imports": "^3.1.0", "postcss-modules-local-by-default": "^4.0.5", "postcss-modules-scope": "^3.2.0", "postcss-modules-values": "^4.0.0", "postcss-value-parser": "^4.2.0", - "semver": "^7.5.4" + "semver": "^7.6.3" }, "engines": { "node": ">= 18.12.0" @@ -2336,7 +2094,7 @@ "url": "https://opencollective.com/webpack" }, "peerDependencies": { - "@rspack/core": "0.x || 1.x", + "@rspack/core": "0.x || ^1.0.0 || ^2.0.0-0", "webpack": "^5.27.0" }, "peerDependenciesMeta": { @@ -2412,9 +2170,9 @@ } }, "node_modules/default-browser": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.2.1.tgz", - "integrity": "sha512-WY/3TUME0x3KPYdRRxEJJvXRHV4PyPoUsxtZa78lwItwRQRHhd2U9xOscaT/YTf8uCXIAjeJOFBVEh/7FtD8Xg==", + "version": "5.5.1", + "resolved": "https://registry.npmjs.org/default-browser/-/default-browser-5.5.1.tgz", + "integrity": "sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==", "dev": true, "license": "MIT", "dependencies": { @@ -2429,9 +2187,9 @@ } }, "node_modules/default-browser-id": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.0.tgz", - "integrity": "sha512-A6p/pu/6fyBcA1TRz/GqWYPViplrftcW2gZC9q79ngNCKAeR/X3gcEdXQHl4KNXV+3wgIJ1CPkJQ3IHM6lcsyA==", + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/default-browser-id/-/default-browser-id-5.0.1.tgz", + "integrity": "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==", "dev": true, "license": "MIT", "engines": { @@ -2464,24 +2222,6 @@ "node": ">= 0.8" } }, - "node_modules/destroy": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", - "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8", - "npm": "1.2.8000 || >= 1.4.16" - } - }, - "node_modules/detect-node": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", - "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", - "dev": true, - "license": "MIT" - }, "node_modules/dns-packet": { "version": "5.6.1", "resolved": "https://registry.npmjs.org/dns-packet/-/dns-packet-5.6.1.tgz", @@ -2619,24 +2359,28 @@ "license": "MIT" }, "node_modules/encodeurl": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", - "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.3.tgz", + "integrity": "sha512-mIteYONiEfc4xWf2F1WXovh1c8npzS00vNeiUPdwFF+QlVJni+gNvpQltLMQhob8rew/bWWc/bGTuUr0EUGt0w==", "dev": true, "license": "MIT", "engines": { "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/enhanced-resolve": { - "version": "5.19.0", - "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.19.0.tgz", - "integrity": "sha512-phv3E1Xl4tQOShqSte26C7Fl84EwUdZsyOuSSk9qtAGyyQs2s3jJzComh+Abf4g187lUUAvH+H26omrqia2aGg==", + "version": "5.26.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.26.0.tgz", + "integrity": "sha512-9vhedylFonb2YGogzUKX6+Ja72gOJbN1QHAqdrvqLwhdl/QWbKopzoUC9EbQNVsAns/bx/4uyqalrQAoy1IByw==", "dev": true, "license": "MIT", "dependencies": { "graceful-fs": "^4.2.4", - "tapable": "^2.3.0" + "tapable": "^2.3.3" }, "engines": { "node": ">=10.13.0" @@ -2653,9 +2397,9 @@ } }, "node_modules/envinfo": { - "version": "7.14.0", - "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.14.0.tgz", - "integrity": "sha512-CO40UI41xDQzhLB1hWyqUKgFhs250pNcGbyGKe1l/e4FSaI/+YE4IMG76GDt0In67WLPACIITC+sOi08x4wIvg==", + "version": "7.21.0", + "resolved": "https://registry.npmjs.org/envinfo/-/envinfo-7.21.0.tgz", + "integrity": "sha512-Lw7I8Zp5YKHFCXL7+Dz95g4CcbMEpgvqZNNq3AmlT5XAV6CgAAk6gyAMqn2zjw08K9BHfcNuKrMiCPLByGafow==", "dev": true, "license": "MIT", "bin": { @@ -2686,16 +2430,16 @@ } }, "node_modules/es-module-lexer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.0.0.tgz", - "integrity": "sha512-5POEcUuZybH7IdmGsD8wlf0AI55wMecM9rVBTI/qEAy2c1kTOm3DjFYjrBdI2K3BaJjJYfYFeRtM0t9ssnRuxw==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz", + "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==", "dev": true, "license": "MIT" }, "node_modules/es-object-atoms": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", - "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz", + "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==", "dev": true, "license": "MIT", "dependencies": { @@ -2732,53 +2476,6 @@ "node": ">=0.8.0" } }, - "node_modules/eslint-scope": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-5.1.1.tgz", - "integrity": "sha512-2NxwbF/hZ0KpepYN0cNbo+FN6XoK7GaHlQhgx/hIZl6Va0bF45RQOOwhLIy8lQDbuCiadSLCBnH2CFYquit5bw==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "esrecurse": "^4.3.0", - "estraverse": "^4.1.1" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/esrecurse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", - "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", - "dev": true, - "license": "BSD-2-Clause", - "dependencies": { - "estraverse": "^5.2.0" - }, - "engines": { - "node": ">=4.0" - } - }, - "node_modules/esrecurse/node_modules/estraverse": { - "version": "5.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", - "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, - "node_modules/estraverse": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-4.3.0.tgz", - "integrity": "sha512-39nnKffWz8xN1BU/2c79n9nB9HDzo0niYUqx6xyqUnyoAnQyyWpOTdZEeiCch8BBu515t4wp9ZmgVfVhn9EBpw==", - "dev": true, - "license": "BSD-2-Clause", - "engines": { - "node": ">=4.0" - } - }, "node_modules/etag": { "version": "1.8.1", "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", @@ -2789,13 +2486,6 @@ "node": ">= 0.6" } }, - "node_modules/eventemitter3": { - "version": "4.0.7", - "resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-4.0.7.tgz", - "integrity": "sha512-8guHBZCwKnFhYdHr2ysuRWErTwhoN2X8XELRlrRwpmfeY2jjuUN4taQMsULKUVo1K4DvZl+0pgfyoysHxvmvEw==", - "dev": true, - "license": "MIT" - }, "node_modules/events": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz", @@ -2806,128 +2496,103 @@ "node": ">=0.8.x" } }, - "node_modules/execa": { - "version": "5.1.1", - "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", - "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", - "dev": true, - "license": "MIT", - "dependencies": { - "cross-spawn": "^7.0.3", - "get-stream": "^6.0.0", - "human-signals": "^2.1.0", - "is-stream": "^2.0.0", - "merge-stream": "^2.0.0", - "npm-run-path": "^4.0.1", - "onetime": "^5.1.2", - "signal-exit": "^3.0.3", - "strip-final-newline": "^2.0.0" + "node_modules/express": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/express/-/express-5.3.0.tgz", + "integrity": "sha512-qCqy1xSoaugxOD4IVHb1ZWdkvCF2W3aE2okKouWj8VwJ+ztskSiXoBnCSJqfKT+cVPJhuJqe9YLbY425+Zh00g==", + "dev": true, + "license": "MIT", + "dependencies": { + "accepts": "^2.0.0", + "body-parser": "^2.3.0", + "content-disposition": "^2.0.1", + "content-type": "^2.0.0", + "cookie": "^0.7.1", + "cookie-signature": "^1.2.1", + "debug": "^4.4.0", + "depd": "^2.0.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "finalhandler": "^2.1.0", + "fresh": "^2.0.0", + "http-errors": "^2.0.0", + "merge-descriptors": "^2.0.0", + "mime-types": "^3.0.0", + "on-finished": "^2.4.1", + "once": "^1.4.0", + "parseurl": "^1.3.3", + "proxy-addr": "^2.0.8", + "qs": "^6.16.0", + "range-parser": "^1.2.1", + "router": "^2.2.0", + "send": "^1.1.0", + "serve-static": "^2.2.0", + "statuses": "^2.0.1", + "type-is": "^2.1.0", + "vary": "^1.1.2" }, "engines": { - "node": ">=10" + "node": ">= 18" }, "funding": { - "url": "https://github.com/sindresorhus/execa?sponsor=1" + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/express": { - "version": "4.22.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", - "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", + "node_modules/express/node_modules/content-disposition": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-2.0.1.tgz", + "integrity": "sha512-e+H0ZXHSWYrENhQzw1LPuP4oF5MzVKmDU6d3hxlvaPEYLLg62MxtQNPRx4SYSuYJSBUgnQIG4HIN2tEtNv7Dog==", "dev": true, "license": "MIT", - "dependencies": { - "accepts": "~1.3.8", - "array-flatten": "1.1.1", - "body-parser": "~1.20.5", - "content-disposition": "~0.5.4", - "content-type": "~1.0.4", - "cookie": "~0.7.1", - "cookie-signature": "~1.0.6", - "debug": "2.6.9", - "depd": "2.0.0", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "finalhandler": "~1.3.1", - "fresh": "~0.5.2", - "http-errors": "~2.0.0", - "merge-descriptors": "1.0.3", - "methods": "~1.1.2", - "on-finished": "~2.4.1", - "parseurl": "~1.3.3", - "path-to-regexp": "~0.1.12", - "proxy-addr": "~2.0.7", - "qs": "~6.15.1", - "range-parser": "~1.2.1", - "safe-buffer": "5.2.1", - "send": "~0.19.0", - "serve-static": "~1.16.2", - "setprototypeof": "1.2.0", - "statuses": "~2.0.1", - "type-is": "~1.6.18", - "utils-merge": "1.0.1", - "vary": "~1.1.2" - }, "engines": { - "node": ">= 0.10.0" + "node": ">=18" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, - "node_modules/express/node_modules/content-disposition": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", - "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "node_modules/express/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { - "safe-buffer": "5.2.1" + "ms": "^2.1.3" }, "engines": { - "node": ">= 0.6" + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "node_modules/express/node_modules/path-to-regexp": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", - "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==", + "node_modules/express/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true, "license": "MIT" }, "node_modules/express/node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/express/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/fast-deep-equal": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", @@ -2936,9 +2601,9 @@ "license": "MIT" }, "node_modules/fast-uri": { - "version": "3.1.7", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.7.tgz", - "integrity": "sha512-dOvZVzjdZdz7phd9v6jCbwxrBW3fK6n8Rc0CtdmM4bumzMnxywBYhuph6J819RRw/ku+rLbelwfMunktuzVVHg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { @@ -2952,29 +2617,6 @@ ], "license": "BSD-3-Clause" }, - "node_modules/fastest-levenshtein": { - "version": "1.0.16", - "resolved": "https://registry.npmjs.org/fastest-levenshtein/-/fastest-levenshtein-1.0.16.tgz", - "integrity": "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 4.9.1" - } - }, - "node_modules/faye-websocket": { - "version": "0.11.4", - "resolved": "https://registry.npmjs.org/faye-websocket/-/faye-websocket-0.11.4.tgz", - "integrity": "sha512-CzbClwlXAuiRQAlUyfqPgvPoNKTckTPGfwZV4ZdAhVcP2lh9KUxJg2b5GkE7XbjKQ3YJnQ9z6D9ntLAlB+tP8g==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "websocket-driver": ">=0.5.1" - }, - "engines": { - "node": ">=0.8.0" - } - }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", @@ -2989,38 +2631,52 @@ } }, "node_modules/finalhandler": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", - "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz", + "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==", "dev": true, "license": "MIT", "dependencies": { - "debug": "2.6.9", - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "on-finished": "2.4.1", - "parseurl": "~1.3.3", - "statuses": "2.0.1", - "unpipe": "~1.0.0" + "debug": "^4.4.0", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "on-finished": "^2.4.1", + "parseurl": "^1.3.3", + "statuses": "^2.0.1" }, "engines": { - "node": ">= 0.8" + "node": ">= 18.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/find-up": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", - "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "node_modules/finalhandler/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { - "locate-path": "^5.0.0", - "path-exists": "^4.0.0" + "ms": "^2.1.3" }, "engines": { - "node": ">=8" + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, "node_modules/flat": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", @@ -3031,27 +2687,6 @@ "flat": "cli.js" } }, - "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", - "dev": true, - "funding": [ - { - "type": "individual", - "url": "https://github.com/sponsors/RubenVerborgh" - } - ], - "license": "MIT", - "engines": { - "node": ">=4.0" - }, - "peerDependenciesMeta": { - "debug": { - "optional": true - } - } - }, "node_modules/forwarded": { "version": "0.2.0", "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", @@ -3063,28 +2698,13 @@ } }, "node_modules/fresh": { - "version": "0.5.2", - "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", - "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/fsevents": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", - "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz", + "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==", "dev": true, - "hasInstallScript": true, "license": "MIT", - "optional": true, - "os": [ - "darwin" - ], "engines": { - "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + "node": ">= 0.8" } }, "node_modules/function-bind": { @@ -3136,32 +2756,6 @@ "node": ">= 0.4" } }, - "node_modules/get-stream": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", - "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/glob-parent": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", - "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", - "dev": true, - "license": "ISC", - "dependencies": { - "is-glob": "^4.0.1" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/glob-to-regex.js": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/glob-to-regex.js/-/glob-to-regex.js-1.3.1.tgz", @@ -3179,13 +2773,6 @@ "tslib": "2" } }, - "node_modules/glob-to-regexp": { - "version": "0.4.1", - "resolved": "https://registry.npmjs.org/glob-to-regexp/-/glob-to-regexp-0.4.1.tgz", - "integrity": "sha512-lkX1HJXwyMcprw/5YUZc2s7DrpAiHB21/V+E1rHUrVNokkvB6bqMzT0VfV6/86ZNabt1k14YOIaT7nDvOX3Iiw==", - "dev": true, - "license": "BSD-2-Clause" - }, "node_modules/gopd": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", @@ -3206,13 +2793,6 @@ "dev": true, "license": "ISC" }, - "node_modules/handle-thing": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/handle-thing/-/handle-thing-2.0.1.tgz", - "integrity": "sha512-9Qn4yBxelxoh2Ow62nP+Ka/kMnOXRi8BXnRaUwezLNhqelnN49xKz4F/dPP8OYLxLxq6JDtZb2i9XznUQbNPTg==", - "dev": true, - "license": "MIT" - }, "node_modules/has-flag": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", @@ -3237,9 +2817,9 @@ } }, "node_modules/hasown": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", - "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz", + "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==", "dev": true, "license": "MIT", "dependencies": { @@ -3259,45 +2839,6 @@ "he": "bin/he" } }, - "node_modules/hpack.js": { - "version": "2.1.6", - "resolved": "https://registry.npmjs.org/hpack.js/-/hpack.js-2.1.6.tgz", - "integrity": "sha512-zJxVehUdMGIKsRaNt7apO2Gqp0BdqW5yaiGHXXmbpvxgBYVZnAql+BJb4RO5ad2MgpbZKn5G6nMnegrH1FcNYQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "inherits": "^2.0.1", - "obuf": "^1.0.0", - "readable-stream": "^2.0.1", - "wbuf": "^1.1.0" - } - }, - "node_modules/hpack.js/node_modules/readable-stream": { - "version": "2.3.8", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", - "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", - "dev": true, - "license": "MIT", - "dependencies": { - "core-util-is": "~1.0.0", - "inherits": "~2.0.3", - "isarray": "~1.0.0", - "process-nextick-args": "~2.0.0", - "safe-buffer": "~5.1.1", - "string_decoder": "~1.1.1", - "util-deprecate": "~1.0.1" - } - }, - "node_modules/hpack.js/node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dev": true, - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, "node_modules/html-minifier-terser": { "version": "6.1.0", "resolved": "https://registry.npmjs.org/html-minifier-terser/-/html-minifier-terser-6.1.0.tgz", @@ -3321,9 +2862,9 @@ } }, "node_modules/html-webpack-plugin": { - "version": "5.6.3", - "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-5.6.3.tgz", - "integrity": "sha512-QSf1yjtSAsmf7rYBV7XX86uua4W/vkhIt0xNXKbsi2foEeW7vjJQz4bhnpL3xH+l1ryl1680uNv968Z+X6jSYg==", + "version": "5.6.8", + "resolved": "https://registry.npmjs.org/html-webpack-plugin/-/html-webpack-plugin-5.6.8.tgz", + "integrity": "sha512-MZmKQcTnhEh1SPSyMiEytIeDZDUoBZVorNHivQGXMASHf/BSGGOrKa2xQ5bGx3TCe1n109ecCt+cpww7wwWhKA==", "dev": true, "license": "MIT", "dependencies": { @@ -3341,7 +2882,7 @@ "url": "https://opencollective.com/html-webpack-plugin" }, "peerDependencies": { - "@rspack/core": "0.x || 1.x", + "@rspack/core": "0.x || 1.x || 2.x", "webpack": "^5.20.0" }, "peerDependenciesMeta": { @@ -3373,86 +2914,75 @@ "entities": "^2.0.0" } }, - "node_modules/http-deceiver": { - "version": "1.2.7", - "resolved": "https://registry.npmjs.org/http-deceiver/-/http-deceiver-1.2.7.tgz", - "integrity": "sha512-LmpOGxTfbpgtGVxJrj5k7asXHCgNZp5nLfp+hWc8QQRqtb7fUy6kRY3BO1h9ddF6yIPYUARgxGOwB42DnxIaNw==", - "dev": true, - "license": "MIT" - }, "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", "dev": true, "license": "MIT", "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" }, "engines": { "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/http-parser-js": { - "version": "0.5.9", - "resolved": "https://registry.npmjs.org/http-parser-js/-/http-parser-js-0.5.9.tgz", - "integrity": "sha512-n1XsPy3rXVxlqxVioEWdC+0+M+SQw0DpJynwtOPo1X+ZlvdzTLtDBIJJlDQTnwZIFJrZSzSGmIOUdP8tu+SgLw==", - "dev": true, - "license": "MIT" - }, - "node_modules/http-proxy": { - "version": "1.18.1", - "resolved": "https://registry.npmjs.org/http-proxy/-/http-proxy-1.18.1.tgz", - "integrity": "sha512-7mz/721AbnJwIVbnaSv1Cz3Am0ZLT/UBwkC92VlxhXv/k/BBQfM2fXElQNC27BVGr0uwUpplYPQM9LnaBMR5NQ==", + "node_modules/http-proxy-middleware": { + "version": "4.2.2", + "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-4.2.2.tgz", + "integrity": "sha512-GHP6tbjWsdSZbWSyqYvwPwoR76ozJ2IccVYoBR702N9vfqO0KBIwJ9vkDRErxwbb5Z6ej2Wn+9D/YitlUTseSQ==", "dev": true, "license": "MIT", "dependencies": { - "eventemitter3": "^4.0.0", - "follow-redirects": "^1.0.0", - "requires-port": "^1.0.0" + "debug": "^4.4.3", + "httpxy": "^0.5.6", + "is-glob": "^4.0.3", + "is-plain-obj": "^4.1.0", + "micromatch": "^4.0.8" }, "engines": { - "node": ">=8.0.0" + "node": "^22.15.0 || ^24.0.0 || >=26.0.0" } }, - "node_modules/http-proxy-middleware": { - "version": "2.0.10", - "resolved": "https://registry.npmjs.org/http-proxy-middleware/-/http-proxy-middleware-2.0.10.tgz", - "integrity": "sha512-RKzRWNPxUZqbuk3BC5mGVJbBnWgr+diEnjJexIOytFbBzDy88Fbh/YvBr3DsNrl1jYAfjWfpATEv0NO35FDuPQ==", + "node_modules/http-proxy-middleware/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { - "@types/http-proxy": "^1.17.8", - "http-proxy": "^1.18.1", - "is-glob": "^4.0.1", - "is-plain-obj": "^3.0.0", - "micromatch": "^4.0.2" + "ms": "^2.1.3" }, "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "@types/express": "^4.17.13" + "node": ">=6.0" }, "peerDependenciesMeta": { - "@types/express": { + "supports-color": { "optional": true } } }, - "node_modules/human-signals": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", - "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "node_modules/http-proxy-middleware/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=10.17.0" - } + "license": "MIT" + }, + "node_modules/httpxy": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/httpxy/-/httpxy-0.5.6.tgz", + "integrity": "sha512-iqc3nOxvNb5FxbhJozt8wNmHgjlmk4zzba512jMEXVwHCEBCbGAj49eGfy5PI8ts3/LFSFq8siiSNqwfY1AlfQ==", + "dev": true, + "license": "MIT" }, "node_modules/hyperdyperid": { "version": "1.2.0", @@ -3465,16 +2995,20 @@ } }, "node_modules/iconv-lite": { - "version": "0.4.24", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", - "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", "dev": true, "license": "MIT", "dependencies": { - "safer-buffer": ">= 2.1.2 < 3" + "safer-buffer": ">= 2.1.2 < 3.0.0" }, "engines": { "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/icss-utils": { @@ -3490,26 +3024,6 @@ "postcss": "^8.1.0" } }, - "node_modules/import-local": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/import-local/-/import-local-3.2.0.tgz", - "integrity": "sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA==", - "dev": true, - "license": "MIT", - "dependencies": { - "pkg-dir": "^4.2.0", - "resolve-cwd": "^3.0.0" - }, - "bin": { - "import-local-fixture": "fixtures/cli.js" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/inherits": { "version": "2.0.4", "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", @@ -3535,55 +3049,26 @@ } }, "node_modules/ipaddr.js": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.2.0.tgz", - "integrity": "sha512-Ag3wB2o37wslZS19hZqorUnrnzSkpOVy+IiiDEiTqNubEYpYuHWIf6K4psgN2ZWKExS4xhVCrRVfb/wfW8fWJA==", + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.5.0.tgz", + "integrity": "sha512-aq+t5NAc+cS6rZQQVWC2x98CPqGtKKTMDd4Gaodv0wShnItdKg/51djkGJ1hqH+Oy0ivDftCbSLCQob8zso01w==", "dev": true, "license": "MIT", "engines": { "node": ">= 10" } }, - "node_modules/is-binary-path": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", - "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", - "dev": true, - "license": "MIT", - "dependencies": { - "binary-extensions": "^2.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dev": true, - "license": "MIT", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/is-docker": { - "version": "2.2.1", - "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-2.2.1.tgz", - "integrity": "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ==", + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", + "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", "dev": true, "license": "MIT", "bin": { "is-docker": "cli.js" }, "engines": { - "node": ">=8" + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -3621,45 +3106,42 @@ "node": ">=0.10.0" } }, - "node_modules/is-inside-container": { + "node_modules/is-in-ssh": { "version": "1.0.0", - "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", - "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", + "resolved": "https://registry.npmjs.org/is-in-ssh/-/is-in-ssh-1.0.0.tgz", + "integrity": "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==", "dev": true, "license": "MIT", - "dependencies": { - "is-docker": "^3.0.0" - }, - "bin": { - "is-inside-container": "cli.js" - }, "engines": { - "node": ">=14.16" + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-inside-container/node_modules/is-docker": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-docker/-/is-docker-3.0.0.tgz", - "integrity": "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ==", + "node_modules/is-inside-container": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-inside-container/-/is-inside-container-1.0.0.tgz", + "integrity": "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==", "dev": true, "license": "MIT", + "dependencies": { + "is-docker": "^3.0.0" + }, "bin": { - "is-docker": "cli.js" + "is-inside-container": "cli.js" }, "engines": { - "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + "node": ">=14.16" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, "node_modules/is-network-error": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.1.0.tgz", - "integrity": "sha512-tUdRRAnhT+OtCZR/LxZelH/C7QtjtFrTu5tXCA8pl55eTUElUHT+GPYV8MBMBvea/j+NxQqVt3LbWMRir7Gx9g==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.2.tgz", + "integrity": "sha512-PhBY86zaxNZUuWP6h13Vu5oFe0XY6/UlKzQnYFELzGVHygP3MxmvTfYSG7GN3aIab/iWudSMgjSnG9Dq+nHrgA==", "dev": true, "license": "MIT", "engines": { @@ -3680,13 +3162,13 @@ } }, "node_modules/is-plain-obj": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-3.0.0.tgz", - "integrity": "sha512-gwsOE28k+23GP1B6vFl1oVh/WOzmawBrKwo5Ev6wMKzPkaXaCDIQKzLnvsA42DRlbVTWorkgTKIviAKCWkfUwA==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-4.1.0.tgz", + "integrity": "sha512-+Pgi+vMuUNkJyExiMBt5IlFoMyKnr5zhJ4Uspz58WOhBF5QoIZkFyNHIbBAtHwzVAgk5RtndVNsDRN61/mmDqg==", "dev": true, "license": "MIT", "engines": { - "node": ">=10" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" @@ -3718,39 +3200,29 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-stream": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", - "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "node_modules/is-promise": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz", + "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } + "license": "MIT" }, "node_modules/is-wsl": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-2.2.0.tgz", - "integrity": "sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww==", + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.1.tgz", + "integrity": "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw==", "dev": true, "license": "MIT", "dependencies": { - "is-docker": "^2.0.0" + "is-inside-container": "^1.0.0" }, "engines": { - "node": ">=8" + "node": ">=16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/isarray": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", - "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", - "dev": true, - "license": "MIT" - }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -3809,13 +3281,6 @@ "url": "https://github.com/chalk/supports-color?sponsor=1" } }, - "node_modules/json-parse-even-better-errors": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", - "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", - "dev": true, - "license": "MIT" - }, "node_modules/json-schema-traverse": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", @@ -3834,41 +3299,14 @@ } }, "node_modules/launch-editor": { - "version": "2.14.1", - "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.1.tgz", - "integrity": "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==", + "version": "2.14.2", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.2.tgz", + "integrity": "sha512-NHJEb30MGBCkmZXLZwz25t37QR4aY03ZzPYUJXOJaOa92uWwExI9SBQUuIznBYc1xkD7cJNGX7oc3Nl3sq2kQQ==", "dev": true, "license": "MIT", "dependencies": { "picocolors": "^1.1.1", - "shell-quote": "^1.8.4" - } - }, - "node_modules/loader-runner": { - "version": "4.3.1", - "resolved": "https://registry.npmjs.org/loader-runner/-/loader-runner-4.3.1.tgz", - "integrity": "sha512-IWqP2SCPhyVFTBtRcgMHdzlf9ul25NwaFx4wCEH/KjAXuuHY4yNjvPXsBokp8jCB936PyWRaPKUNh8NvylLp2Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6.11.5" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - } - }, - "node_modules/locate-path": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", - "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-locate": "^4.1.0" - }, - "engines": { - "node": ">=8" + "shell-quote": "^1.10.0" } }, "node_modules/lodash": { @@ -3899,30 +3337,34 @@ } }, "node_modules/media-typer": { - "version": "0.3.0", - "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", - "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz", + "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==", "dev": true, "license": "MIT", "engines": { - "node": ">= 0.6" + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/memfs": { - "version": "4.80.0", - "resolved": "https://registry.npmjs.org/memfs/-/memfs-4.80.0.tgz", - "integrity": "sha512-N70W2isi44XdGn7uPo9NJ4zRukcdkwSFHlnYx42SWOH/+hzqNc8P7+tVoA2up4z7faHvNi1RSNCFjxoYQ71VPQ==", + "version": "4.80.1", + "resolved": "https://registry.npmjs.org/memfs/-/memfs-4.80.1.tgz", + "integrity": "sha512-TpBOB/np/5Uw1c9Z+NHhrbVVrnvfGyUMM0imlMaMB8pe3glseKeHDPFViNsg59tnoeAI6ubHCs3tWdzqBq3YdQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@jsonjoy.com/fs-core": "4.80.0", - "@jsonjoy.com/fs-fsa": "4.80.0", - "@jsonjoy.com/fs-node": "4.80.0", - "@jsonjoy.com/fs-node-builtins": "4.80.0", - "@jsonjoy.com/fs-node-to-fsa": "4.80.0", - "@jsonjoy.com/fs-node-utils": "4.80.0", - "@jsonjoy.com/fs-print": "4.80.0", - "@jsonjoy.com/fs-snapshot": "4.80.0", + "@jsonjoy.com/fs-core": "4.80.1", + "@jsonjoy.com/fs-fsa": "4.80.1", + "@jsonjoy.com/fs-node": "4.80.1", + "@jsonjoy.com/fs-node-builtins": "4.80.1", + "@jsonjoy.com/fs-node-to-fsa": "4.80.1", + "@jsonjoy.com/fs-node-utils": "4.80.1", + "@jsonjoy.com/fs-print": "4.80.1", + "@jsonjoy.com/fs-snapshot": "4.80.1", "@jsonjoy.com/json-pack": "^1.11.0", "@jsonjoy.com/util": "^1.9.0", "glob-to-regex.js": "^1.3.1", @@ -3936,11 +3378,14 @@ } }, "node_modules/merge-descriptors": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", - "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz", + "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==", "dev": true, "license": "MIT", + "engines": { + "node": ">=18" + }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } @@ -3952,16 +3397,6 @@ "dev": true, "license": "MIT" }, - "node_modules/methods": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", - "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/micromatch": { "version": "4.0.8", "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", @@ -3976,19 +3411,6 @@ "node": ">=8.6" } }, - "node_modules/mime": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", - "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", - "dev": true, - "license": "MIT", - "bin": { - "mime": "cli.js" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/mime-db": { "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", @@ -4000,42 +3422,26 @@ } }, "node_modules/mime-types": { - "version": "2.1.35", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", - "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", + "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", "dev": true, "license": "MIT", "dependencies": { - "mime-db": "1.52.0" + "mime-db": "^1.54.0" }, "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mime-types/node_modules/mime-db": { - "version": "1.52.0", - "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", - "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/mimic-fn": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", - "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/mini-css-extract-plugin": { - "version": "2.9.2", - "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.9.2.tgz", - "integrity": "sha512-GJuACcS//jtq4kCtd5ii/M0SZf7OZRH+BxdqXZHaJfb8TJiVl+NgQRPwiYt2EuqeSkNydn/7vP+bcE27C5mb9w==", + "version": "2.10.2", + "resolved": "https://registry.npmjs.org/mini-css-extract-plugin/-/mini-css-extract-plugin-2.10.2.tgz", + "integrity": "sha512-AOSS0IdEB95ayVkxn5oGzNQwqAi2J0Jb/kKm43t7H73s8+f5873g0yuj0PNvK4dO75mu5DHg4nlgp4k6Kga8eg==", "dev": true, "license": "MIT", "dependencies": { @@ -4053,13 +3459,6 @@ "webpack": "^5.0.0" } }, - "node_modules/minimalistic-assert": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", - "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==", - "dev": true, - "license": "ISC" - }, "node_modules/minimatch": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", @@ -4083,6 +3482,79 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/minimizer-webpack-plugin": { + "version": "5.13.1", + "resolved": "https://registry.npmjs.org/minimizer-webpack-plugin/-/minimizer-webpack-plugin-5.13.1.tgz", + "integrity": "sha512-1mhAfvachWYYOm8tpmany5NLuvP+F2wxZWBSX8DC0uFS2wJpM9q3rWgN9wBooAH9d5V12wX0BjyJe4fMjHMarQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/trace-mapping": "^0.3.31", + "jest-worker": "^27.4.5", + "schema-utils": "^4.6.0", + "terser": "^5.51.0" + }, + "engines": { + "node": ">= 10.13.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.1.0" + }, + "peerDependenciesMeta": { + "@minify-html/node": { + "optional": true + }, + "@napi-rs/image": { + "optional": true + }, + "@swc/core": { + "optional": true + }, + "@swc/css": { + "optional": true + }, + "@swc/html": { + "optional": true + }, + "clean-css": { + "optional": true + }, + "cssnano": { + "optional": true + }, + "csso": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "html-minifier-terser": { + "optional": true + }, + "imagemin": { + "optional": true + }, + "lightningcss": { + "optional": true + }, + "postcss": { + "optional": true + }, + "sharp": { + "optional": true + }, + "svgo": { + "optional": true + }, + "uglify-js": { + "optional": true + } + } + }, "node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", @@ -4124,22 +3596,22 @@ } }, "node_modules/negotiator": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", - "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz", + "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==", "dev": true, "license": "MIT", + "dependencies": { + "content-type": "^2.1.0" + }, "engines": { - "node": ">= 0.6" + "node": ">=18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/neo-async": { - "version": "2.6.2", - "resolved": "https://registry.npmjs.org/neo-async/-/neo-async-2.6.2.tgz", - "integrity": "sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw==", - "dev": true, - "license": "MIT" - }, "node_modules/no-case": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/no-case/-/no-case-3.0.4.tgz", @@ -4161,33 +3633,10 @@ "node": ">=18" } }, - "node_modules/normalize-path": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", - "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/npm-run-path": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", - "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", - "dev": true, - "license": "MIT", - "dependencies": { - "path-key": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/nth-check": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", - "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", + "node_modules/nth-check": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", + "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", "dev": true, "license": "BSD-2-Clause", "dependencies": { @@ -4210,17 +3659,10 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/obuf": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/obuf/-/obuf-1.1.2.tgz", - "integrity": "sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==", - "dev": true, - "license": "MIT" - }, "node_modules/on-finished": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", - "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.2.tgz", + "integrity": "sha512-ATWUv387i+nLD49EiDoOft5scf32Vsdz3ktrQJG9bi7jRFmaXTssvyvj1EmeKVVgvesbqUtvQQvaS2TpTukAZQ==", "dev": true, "license": "MIT", "dependencies": { @@ -4228,6 +3670,10 @@ }, "engines": { "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/on-headers": { @@ -4240,114 +3686,53 @@ "node": ">= 0.8" } }, - "node_modules/onetime": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", - "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", "dev": true, - "license": "MIT", + "license": "ISC", "dependencies": { - "mimic-fn": "^2.1.0" - }, - "engines": { - "node": ">=6" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "wrappy": "1" } }, "node_modules/open": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/open/-/open-10.1.0.tgz", - "integrity": "sha512-mnkeQ1qP5Ue2wd+aivTD3NHd/lZ96Lu0jgf0pwktLPtx6cTZiH7tyeGRRHs0zX0rbrahXPnXlUnbeXyaBBuIaw==", + "version": "11.0.4", + "resolved": "https://registry.npmjs.org/open/-/open-11.0.4.tgz", + "integrity": "sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==", "dev": true, "license": "MIT", "dependencies": { - "default-browser": "^5.2.1", + "default-browser": "^5.5.1", "define-lazy-prop": "^3.0.0", + "is-in-ssh": "^1.0.0", "is-inside-container": "^1.0.0", - "is-wsl": "^3.1.0" - }, - "engines": { - "node": ">=18" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/open/node_modules/is-wsl": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/is-wsl/-/is-wsl-3.1.0.tgz", - "integrity": "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw==", - "dev": true, - "license": "MIT", - "dependencies": { - "is-inside-container": "^1.0.0" - }, - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/p-limit": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", - "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-try": "^2.0.0" + "powershell-utils": "^0.2.1", + "wsl-utils": "^1.0.0" }, "engines": { - "node": ">=6" + "node": ">=20" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-locate": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", - "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", - "dev": true, - "license": "MIT", - "dependencies": { - "p-limit": "^2.2.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/p-retry": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-6.2.1.tgz", - "integrity": "sha512-hEt02O4hUct5wtwg4H4KcWgDdm+l1bOaEy/hWzd8xtXB9BqxTWBBhb+2ImAtH4Cv4rPjV76xN3Zumqk3k3AhhQ==", + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-8.0.1.tgz", + "integrity": "sha512-NAigyu8hfvJe7MsS18mnc4is0MZtau3QMdBklaJKK23oBQb6occO3UPM3vHmTckW8KhfyjMZaUOqdTFEYliHgg==", "dev": true, "license": "MIT", "dependencies": { - "@types/retry": "0.12.2", - "is-network-error": "^1.0.0", - "retry": "^0.13.1" + "is-network-error": "^1.3.0" }, "engines": { - "node": ">=16.17" + "node": ">=22" }, "funding": { "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/p-try": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", - "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/param-case": { "version": "3.0.4", "resolved": "https://registry.npmjs.org/param-case/-/param-case-3.0.4.tgz", @@ -4380,16 +3765,6 @@ "tslib": "^2.0.3" } }, - "node_modules/path-exists": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", - "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/path-is-inside": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/path-is-inside/-/path-is-inside-1.0.2.tgz", @@ -4397,23 +3772,6 @@ "dev": true, "license": "(WTFPL OR MIT)" }, - "node_modules/path-key": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", - "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", - "dev": true, - "license": "MIT" - }, "node_modules/path-to-regexp": { "version": "3.3.0", "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-3.3.0.tgz", @@ -4441,19 +3799,6 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, - "node_modules/pkg-dir": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/pkg-dir/-/pkg-dir-4.2.0.tgz", - "integrity": "sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "find-up": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/pkijs": { "version": "3.4.0", "resolved": "https://registry.npmjs.org/pkijs/-/pkijs-3.4.0.tgz", @@ -4565,9 +3910,9 @@ } }, "node_modules/postcss-selector-parser": { - "version": "7.1.5", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.5.tgz", - "integrity": "sha512-KvvtD7SrlBP7dlgkBghEE3r84CABm5SmV2aNcG4oCA+qDnJ/tvKonFVvwWAyyWUEwxuNawdfEAZKP9zM3oZ2Uw==", + "version": "7.1.6", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.6.tgz", + "integrity": "sha512-7qASPzhKF2l2KLboRZux8CCTRMdGiV08vWmyKzPz22qZ7ZjQBOeY7rNzNoCLSUiftJ7HUq0GERHmxw/t0dCdMw==", "dev": true, "license": "MIT", "dependencies": { @@ -4585,6 +3930,19 @@ "dev": true, "license": "MIT" }, + "node_modules/powershell-utils": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/powershell-utils/-/powershell-utils-0.2.1.tgz", + "integrity": "sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/pretty-error": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-4.0.0.tgz", @@ -4596,17 +3954,10 @@ "renderkid": "^3.0.0" } }, - "node_modules/process-nextick-args": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", - "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", - "dev": true, - "license": "MIT" - }, "node_modules/proxy-addr": { - "version": "2.0.7", - "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", - "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz", + "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==", "dev": true, "license": "MIT", "dependencies": { @@ -4615,6 +3966,10 @@ }, "engines": { "node": ">= 0.10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/proxy-addr/node_modules/ipaddr.js": { @@ -4648,13 +4003,14 @@ } }, "node_modules/qs": { - "version": "6.15.2", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz", - "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==", + "version": "6.17.1", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.17.1.tgz", + "integrity": "sha512-jd3COkaKVgGUW+ZHyEHCG9bH7RoaaiWuMgzsIBjUMVjLAaWGWpoUAVwljVvBHxRu/2qEHnadLGZrkutYUBPQJA==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.1.0" + "es-define-property": "^1.0.1", + "side-channel": "^1.1.1" }, "engines": { "node": ">=0.6" @@ -4674,19 +4030,19 @@ } }, "node_modules/raw-body": { - "version": "2.5.3", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", - "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz", + "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==", "dev": true, "license": "MIT", "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", - "iconv-lite": "~0.4.24", + "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" }, "engines": { - "node": ">= 0.8" + "node": ">= 0.10" } }, "node_modules/raw-body/node_modules/bytes": { @@ -4699,37 +4055,6 @@ "node": ">= 0.8" } }, - "node_modules/raw-body/node_modules/http-errors": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", - "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "depd": "~2.0.0", - "inherits": "~2.0.4", - "setprototypeof": "~1.2.0", - "statuses": "~2.0.2", - "toidentifier": "~1.0.1" - }, - "engines": { - "node": ">= 0.8" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/raw-body/node_modules/statuses": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", - "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/rc": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", @@ -4746,45 +4071,31 @@ "rc": "cli.js" } }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "dev": true, - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, "node_modules/readdirp": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", - "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-5.1.1.tgz", + "integrity": "sha512-Kko+Y5XQ6fM+Ce3dq3m9YGxnacYZYl9cA1wZjaF3Vbry2L3i1qVg8+CAgNPsXRArPMUMCaOR7oa9Nqntc43JKA==", "dev": true, "license": "MIT", - "dependencies": { - "picomatch": "^2.2.1" - }, "engines": { - "node": ">=8.10.0" + "node": ">= 20.19.0" + }, + "funding": { + "type": "individual", + "url": "https://paulmillr.com/funding/" } }, "node_modules/rechoir": { - "version": "0.8.0", - "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-0.8.0.tgz", - "integrity": "sha512-/vxpCXddiX8NGfGO/mTafwjq4aFa/71pvamip0++IQk3zG8cbCj0fifNPrjjF1XMXUne91jL9OoxmdykoEtifQ==", + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/rechoir/-/rechoir-1.0.0.tgz", + "integrity": "sha512-vyBa7bWz11iJRwzJR0nGLt6r45bymWfYXAgd1FmP08BNP/DHAVabgpGPyEXQmBtKvhgxi17SQz2szhvkberQsg==", "dev": true, "license": "MIT", - "dependencies": { - "resolve": "^1.20.0" - }, "engines": { - "node": ">= 10.13.0" + "node": ">= 22.15.0" + }, + "funding": { + "url": "https://github.com/sponsors/gulpjs" } }, "node_modules/reflect-metadata": { @@ -4852,71 +4163,63 @@ "node": ">=0.10.0" } }, - "node_modules/requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true, - "license": "MIT" - }, - "node_modules/resolve": { - "version": "1.22.10", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.10.tgz", - "integrity": "sha512-NPRy+/ncIMeDlTAsuqwKIiferiawhefFJtkNSW0qZJEqMEb+qBt/77B/jGeeek+F0uOeN05CDa6HXbbIgtVX4w==", + "node_modules/router": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz", + "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==", "dev": true, "license": "MIT", "dependencies": { - "is-core-module": "^2.16.0", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" + "debug": "^4.4.0", + "depd": "^2.0.0", + "is-promise": "^4.0.0", + "parseurl": "^1.3.3", + "path-to-regexp": "^8.0.0" }, "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" + "node": ">= 18" } }, - "node_modules/resolve-cwd": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/resolve-cwd/-/resolve-cwd-3.0.0.tgz", - "integrity": "sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg==", + "node_modules/router/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", "dependencies": { - "resolve-from": "^5.0.0" + "ms": "^2.1.3" }, "engines": { - "node": ">=8" + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, - "node_modules/resolve-from": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-5.0.0.tgz", - "integrity": "sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==", + "node_modules/router/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } + "license": "MIT" }, - "node_modules/retry": { - "version": "0.13.1", - "resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz", - "integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==", + "node_modules/router/node_modules/path-to-regexp": { + "version": "8.4.2", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz", + "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==", "dev": true, "license": "MIT", - "engines": { - "node": ">= 4" + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/run-applescript": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.0.0.tgz", - "integrity": "sha512-9by4Ij99JUr/MCFBUkDKLWK3G9HVXmabKz9U5MlIAIuvuzkiOicRYs8XJLxX+xahD+mLiiCYDqF9dKAgtzKP1A==", + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/run-applescript/-/run-applescript-7.1.0.tgz", + "integrity": "sha512-DPe5pVFaAsinSaV6QjQ6gdiedWDcRCbUuiQfQa2wmWV7+xC9bGulGI8+TdRmoFkAPaBXk8CrAbnlY2ISniJ47Q==", "dev": true, "license": "MIT", "engines": { @@ -4941,31 +4244,52 @@ "license": "MIT" }, "node_modules/schema-utils": { - "version": "4.3.3", - "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.3.3.tgz", - "integrity": "sha512-eflK8wEtyOE6+hsaRVPxvUKYCpRgzLqDTb8krvAsRIwOGlHoSgYLgBXoubGgLd2fT41/OUYdb48v4k4WWHQurA==", + "version": "4.8.1", + "resolved": "https://registry.npmjs.org/schema-utils/-/schema-utils-4.8.1.tgz", + "integrity": "sha512-x39pYlJPyH7Uge5QO64B9XGP9zLDc9WNmiQZc+CE3IzZPvMu3lHOuAMGpYNoPixEL7MSWlGhYTg5UlLSL8G6iw==", "dev": true, "license": "MIT", "dependencies": { - "@types/json-schema": "^7.0.9", - "ajv": "^8.9.0", - "ajv-formats": "^2.1.1", + "@types/json-schema": "^7.0.15", + "ajv": "^8.20.0", + "ajv-formats": "^3.0.1", "ajv-keywords": "^5.1.0" }, + "bin": { + "schema-utils": "bin/schema-utils.js" + }, "engines": { "node": ">= 10.13.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" + }, + "peerDependencies": { + "webpack": "^5.112.0" + }, + "peerDependenciesMeta": { + "webpack": { + "optional": true + } } }, - "node_modules/select-hose": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/select-hose/-/select-hose-2.0.0.tgz", - "integrity": "sha512-mEugaLK+YfkijB4fx0e6kImuJdCIt2LxCRcbEYPqRGCs4F2ogyfZU5IAZRdjCP8JPq2AtdNoC/Dux63d9Kiryg==", + "node_modules/schema-utils/node_modules/ajv": { + "version": "8.20.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", + "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", "dev": true, - "license": "MIT" + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "fast-uri": "^3.0.1", + "json-schema-traverse": "^1.0.0", + "require-from-string": "^2.0.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } }, "node_modules/selfsigned": { "version": "5.5.0", @@ -4995,38 +4319,48 @@ } }, "node_modules/send": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", - "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", + "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==", "dev": true, "license": "MIT", "dependencies": { - "debug": "2.6.9", - "depd": "2.0.0", - "destroy": "1.2.0", - "encodeurl": "~1.0.2", - "escape-html": "~1.0.3", - "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", - "mime": "1.6.0", - "ms": "2.1.3", - "on-finished": "2.4.1", - "range-parser": "~1.2.1", - "statuses": "2.0.1" + "debug": "^4.4.3", + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "etag": "^1.8.1", + "fresh": "^2.0.0", + "http-errors": "^2.0.1", + "mime-types": "^3.0.2", + "ms": "^2.1.3", + "on-finished": "^2.4.1", + "range-parser": "^1.2.1", + "statuses": "^2.0.2" }, "engines": { - "node": ">= 0.8.0" + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, - "node_modules/send/node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "node_modules/send/node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", "dev": true, "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, "engines": { - "node": ">= 0.8" + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } } }, "node_modules/send/node_modules/ms": { @@ -5037,19 +4371,23 @@ "license": "MIT" }, "node_modules/send/node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", "dev": true, "license": "MIT", "engines": { "node": ">= 0.6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/serve": { - "version": "14.2.6", - "resolved": "https://registry.npmjs.org/serve/-/serve-14.2.6.tgz", - "integrity": "sha512-QEjUSA+sD4Rotm1znR8s50YqA3kYpRGPmtd5GlFxbaL9n/FdUNbqMhxClqdditSk0LlZyA/dhud6XNRTOC9x2Q==", + "version": "14.2.8", + "resolved": "https://registry.npmjs.org/serve/-/serve-14.2.8.tgz", + "integrity": "sha512-7or7YqR3zXwHhiBGj40l9yODyQY146O+hXKaEAfQYQkcvHtMDdX95K96xr50qL9EjXScyYVJb1NIgVE8F0i5cA==", "dev": true, "license": "MIT", "dependencies": { @@ -5059,10 +4397,10 @@ "boxen": "7.0.0", "chalk": "5.0.1", "chalk-template": "0.4.0", - "clipboardy": "3.0.0", - "compression": "1.8.1", + "compression": "1.8.2", "is-port-reachable": "4.0.0", "serve-handler": "6.1.7", + "tinyclip": "^0.1.12", "update-check": "1.5.4" }, "bin": { @@ -5112,22 +4450,40 @@ } }, "node_modules/serve-index": { - "version": "1.9.1", - "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.1.tgz", - "integrity": "sha512-pXHfKNP4qujrtteMrSBb0rc8HJ9Ms/GrXwcUtUtD5s4ewDJI8bT3Cz2zTVRMKtri49pLx2e0Ya8ziP5Ya2pZZw==", + "version": "1.9.2", + "resolved": "https://registry.npmjs.org/serve-index/-/serve-index-1.9.2.tgz", + "integrity": "sha512-KDj11HScOaLmrPxl70KYNW1PksP4Nb/CLL2yvC+Qd2kHMPEEpfc4Re2e4FOay+bC/+XQl/7zAcWON3JVo5v3KQ==", "dev": true, "license": "MIT", "dependencies": { - "accepts": "~1.3.4", + "accepts": "~1.3.8", "batch": "0.6.1", "debug": "2.6.9", "escape-html": "~1.0.3", - "http-errors": "~1.6.2", - "mime-types": "~2.1.17", - "parseurl": "~1.3.2" + "http-errors": "~1.8.0", + "mime-types": "~2.1.35", + "parseurl": "~1.3.3" }, "engines": { "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/serve-index/node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" } }, "node_modules/serve-index/node_modules/depd": { @@ -5141,34 +4497,54 @@ } }, "node_modules/serve-index/node_modules/http-errors": { - "version": "1.6.3", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.6.3.tgz", - "integrity": "sha512-lks+lVC8dgGyh97jxvxeYTWQFvh4uw4yC12gVl63Cg30sjPX4wuGcdkICVXDAESr6OJGjqGA8Iz5mkeN6zlD7A==", + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.8.1.tgz", + "integrity": "sha512-Kpk9Sm7NmI+RHhnj6OIWDI1d6fIoFAtFt9RLaTMRlg/8w49juAStsrBgp0Dp4OdxdVbRIeKhtCUvoi/RuAhO4g==", "dev": true, "license": "MIT", "dependencies": { "depd": "~1.1.2", - "inherits": "2.0.3", - "setprototypeof": "1.1.0", - "statuses": ">= 1.4.0 < 2" + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": ">= 1.5.0 < 2", + "toidentifier": "1.0.1" }, "engines": { "node": ">= 0.6" } }, - "node_modules/serve-index/node_modules/inherits": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.3.tgz", - "integrity": "sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==", + "node_modules/serve-index/node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", "dev": true, - "license": "ISC" + "license": "MIT", + "engines": { + "node": ">= 0.6" + } }, - "node_modules/serve-index/node_modules/setprototypeof": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.0.tgz", - "integrity": "sha512-BvE/TwpZX4FXExxOxZyRGQQv651MSwmWKZGqvmPcRIjDqWub67kTKuIMx43cZZrS/cBBzwBcNDWoFxt2XEFIpQ==", + "node_modules/serve-index/node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", "dev": true, - "license": "ISC" + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/serve-index/node_modules/negotiator": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } }, "node_modules/serve-index/node_modules/statuses": { "version": "1.5.0", @@ -5181,19 +4557,23 @@ } }, "node_modules/serve-static": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", - "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz", + "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==", "dev": true, "license": "MIT", "dependencies": { - "encodeurl": "~2.0.0", - "escape-html": "~1.0.3", - "parseurl": "~1.3.3", - "send": "0.19.0" + "encodeurl": "^2.0.0", + "escape-html": "^1.0.3", + "parseurl": "^1.3.3", + "send": "^1.2.0" }, "engines": { - "node": ">= 0.8.0" + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/serve/node_modules/chalk": { @@ -5229,33 +4609,10 @@ "node": ">=8" } }, - "node_modules/shebang-command": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", - "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "shebang-regex": "^3.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/shebang-regex": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", - "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/shell-quote": { - "version": "1.10.0", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.10.0.tgz", - "integrity": "sha512-w1aiOKwKuRgtwAReIIj89puqg+I7GvX4IbLrvmhXbzQsj1+Zwi4VO3+fa6ZF91TWSjIxoEkKnMeHcLEODK5ZXA==", + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", "dev": true, "license": "MIT", "engines": { @@ -5266,15 +4623,15 @@ } }, "node_modules/side-channel": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", - "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", + "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3", - "side-channel-list": "^1.0.0", + "object-inspect": "^1.13.4", + "side-channel-list": "^1.0.1", "side-channel-map": "^1.0.1", "side-channel-weakmap": "^1.0.2" }, @@ -5286,14 +4643,14 @@ } }, "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", "dev": true, "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" + "object-inspect": "^1.13.4" }, "engines": { "node": ">= 0.4" @@ -5323,196 +4680,64 @@ }, "node_modules/side-channel-weakmap": { "version": "1.0.2", - "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", - "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", - "dev": true, - "license": "MIT", - "dependencies": { - "call-bound": "^1.0.2", - "es-errors": "^1.3.0", - "get-intrinsic": "^1.2.5", - "object-inspect": "^1.13.3", - "side-channel-map": "^1.0.1" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "dev": true, - "license": "ISC" - }, - "node_modules/sockjs": { - "version": "0.3.24", - "resolved": "https://registry.npmjs.org/sockjs/-/sockjs-0.3.24.tgz", - "integrity": "sha512-GJgLTZ7vYb/JtPSSZ10hsOYIvEYsjbNU+zPdIHcUaWVNUEPivzxku31865sSSud0Da0W4lEeOPlmw93zLQchuQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "faye-websocket": "^0.11.3", - "uuid": "^8.3.2", - "websocket-driver": "^0.7.4" - } - }, - "node_modules/source-map": { - "version": "0.6.1", - "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", - "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", - "dev": true, - "license": "BSD-3-Clause", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dev": true, - "license": "MIT", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, - "node_modules/spdy": { - "version": "4.0.2", - "resolved": "https://registry.npmjs.org/spdy/-/spdy-4.0.2.tgz", - "integrity": "sha512-r46gZQZQV+Kl9oItvl1JZZqJKGr+oEkB08A6BzkiR7593/7IbtuncXHd2YoYeTsG4157ZssMu9KYvUHLcjcDoA==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.1.0", - "handle-thing": "^2.0.0", - "http-deceiver": "^1.2.7", - "select-hose": "^2.0.0", - "spdy-transport": "^3.0.0" - }, - "engines": { - "node": ">=6.0.0" - } - }, - "node_modules/spdy-transport": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/spdy-transport/-/spdy-transport-3.0.0.tgz", - "integrity": "sha512-hsLVFE5SjA6TCisWeJXFKniGGOpBgMLmerfO2aCyCU5s7nJ/rpAepqmFifv/GCbSbueEeAJJnmSQ2rKC/g8Fcw==", - "dev": true, - "license": "MIT", - "dependencies": { - "debug": "^4.1.0", - "detect-node": "^2.0.4", - "hpack.js": "^2.1.6", - "obuf": "^1.1.2", - "readable-stream": "^3.0.6", - "wbuf": "^1.7.3" - } - }, - "node_modules/spdy-transport/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", - "dev": true, - "license": "MIT", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/spdy-transport/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "dev": true, - "license": "MIT" - }, - "node_modules/spdy/node_modules/debug": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", - "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", "dev": true, "license": "MIT", "dependencies": { - "ms": "^2.1.3" + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" }, "engines": { - "node": ">=6.0" + "node": ">= 0.4" }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } + "funding": { + "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/spdy/node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", "dev": true, - "license": "MIT" + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } }, - "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "node_modules/source-map-js": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "dev": true, - "license": "MIT", + "license": "BSD-3-Clause", "engines": { - "node": ">= 0.8" + "node": ">=0.10.0" } }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", + "node_modules/source-map-support": { + "version": "0.5.21", + "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", + "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", "dev": true, "license": "MIT", "dependencies": { - "safe-buffer": "~5.2.0" + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" } }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" + "license": "MIT", + "engines": { + "node": ">= 0.8" + } }, "node_modules/string-width": { "version": "5.1.2", @@ -5573,16 +4798,6 @@ "node": ">=8" } }, - "node_modules/strip-final-newline": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", - "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/strip-json-comments": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", @@ -5612,23 +4827,10 @@ "node": ">=4" } }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/tapable": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz", - "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==", + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.3.tgz", + "integrity": "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A==", "dev": true, "license": "MIT", "engines": { @@ -5640,14 +4842,14 @@ } }, "node_modules/terser": { - "version": "5.39.0", - "resolved": "https://registry.npmjs.org/terser/-/terser-5.39.0.tgz", - "integrity": "sha512-LBAhFyLho16harJoWMg/nZsQYgTrg5jXOn2nCYjRUcZZEdE3qa2zb8QEDRUGVZBW4rlazf2fxkg8tztybTaqWw==", + "version": "5.51.2", + "resolved": "https://registry.npmjs.org/terser/-/terser-5.51.2.tgz", + "integrity": "sha512-bWnjSNscmuI+GJze6ZupnHP8G/cTcsJF+bXCeQknk2SHQsgbNJnLrqiH9jZ2W4STPVXH2mDKKRX3iwPhc9Cn/Q==", "dev": true, "license": "BSD-2-Clause", "dependencies": { "@jridgewell/source-map": "^0.3.3", - "acorn": "^8.8.2", + "acorn": "^8.15.0", "commander": "^2.20.0", "source-map-support": "~0.5.20" }, @@ -5658,40 +4860,6 @@ "node": ">=10" } }, - "node_modules/terser-webpack-plugin": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/terser-webpack-plugin/-/terser-webpack-plugin-5.4.0.tgz", - "integrity": "sha512-Bn5vxm48flOIfkdl5CaD2+1CiUVbonWQ3KQPyP7/EuIl9Gbzq/gQFOzaMFUEgVjB1396tcK0SG8XcNJ/2kDH8g==", - "dev": true, - "license": "MIT", - "dependencies": { - "@jridgewell/trace-mapping": "^0.3.25", - "jest-worker": "^27.4.5", - "schema-utils": "^4.3.0", - "terser": "^5.31.1" - }, - "engines": { - "node": ">= 10.13.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/webpack" - }, - "peerDependencies": { - "webpack": "^5.1.0" - }, - "peerDependenciesMeta": { - "@swc/core": { - "optional": true - }, - "esbuild": { - "optional": true - }, - "uglify-js": { - "optional": true - } - } - }, "node_modules/terser/node_modules/commander": { "version": "2.20.3", "resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz", @@ -5723,6 +4891,64 @@ "dev": true, "license": "MIT" }, + "node_modules/tinyclip": { + "version": "0.1.15", + "resolved": "https://registry.npmjs.org/tinyclip/-/tinyclip-0.1.15.tgz", + "integrity": "sha512-uo33abH+Ays0xYaDysoBt494Hb3hsEczMpcC0MwFl773pazORx4fmvKhclhR1wonUbB6vvpRsvVMwnhfqeMc+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^16.14.0 || >= 17.3.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", @@ -5804,17 +5030,22 @@ } }, "node_modules/type-is": { - "version": "1.6.18", - "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", - "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz", + "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==", "dev": true, "license": "MIT", "dependencies": { - "media-typer": "0.3.0", - "mime-types": "~2.1.24" + "content-type": "^2.0.0", + "media-typer": "^1.1.0", + "mime-types": "^3.0.0" }, "engines": { - "node": ">= 0.6" + "node": ">= 18" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/undici-types": { @@ -5896,26 +5127,6 @@ "dev": true, "license": "MIT" }, - "node_modules/utils-merge": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", - "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.4.0" - } - }, - "node_modules/uuid": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", - "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==", - "dev": true, - "license": "MIT", - "bin": { - "uuid": "dist/bin/uuid" - } - }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -5933,61 +5144,42 @@ "license": "MIT" }, "node_modules/watchpack": { - "version": "2.5.1", - "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.5.1.tgz", - "integrity": "sha512-Zn5uXdcFNIA1+1Ei5McRd+iRzfhENPCe7LeABkJtNulSxjma+l7ltNx55BWZkRlwRnpOgHqxnjyaDgJnNXnqzg==", + "version": "2.6.3", + "resolved": "https://registry.npmjs.org/watchpack/-/watchpack-2.6.3.tgz", + "integrity": "sha512-s3NZy0QpTY9qGqzc0wtz4qI28z3+5qKbbAec4MV4G9N3CfgZ9wgvQRr0cl2jh/tqkWG1NWHkmVMHZpCamev5Wg==", "dev": true, "license": "MIT", "dependencies": { - "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.1.2" }, "engines": { "node": ">=10.13.0" } }, - "node_modules/wbuf": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/wbuf/-/wbuf-1.7.3.tgz", - "integrity": "sha512-O84QOnr0icsbFGLS0O3bI5FswxzRr8/gHwWkDlQFskhSPryQXvrTMxjxGP4+iWYoauLoBvfDpkrOauZ+0iZpDA==", - "dev": true, - "license": "MIT", - "dependencies": { - "minimalistic-assert": "^1.0.0" - } - }, "node_modules/webpack": { - "version": "5.105.0", - "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.105.0.tgz", - "integrity": "sha512-gX/dMkRQc7QOMzgTe6KsYFM7DxeIONQSui1s0n/0xht36HvrgbxtM1xBlgx596NbpHuQU8P7QpKwrZYwUX48nw==", + "version": "5.112.2", + "resolved": "https://registry.npmjs.org/webpack/-/webpack-5.112.2.tgz", + "integrity": "sha512-B2tp1LI9D8GVpPDqprdt12ukTkXXahj9MzqSWJq4faSPgOUM7CdZaGAB6HrL/8E6UwbBpdj4vzWDbKoFnVoU6g==", "dev": true, "license": "MIT", "dependencies": { - "@types/eslint-scope": "^3.7.7", "@types/estree": "^1.0.8", "@types/json-schema": "^7.0.15", "@webassemblyjs/ast": "^1.14.1", "@webassemblyjs/wasm-edit": "^1.14.1", "@webassemblyjs/wasm-parser": "^1.14.1", - "acorn": "^8.15.0", - "acorn-import-phases": "^1.0.3", "browserslist": "^4.28.1", "chrome-trace-event": "^1.0.2", - "enhanced-resolve": "^5.19.0", - "es-module-lexer": "^2.0.0", - "eslint-scope": "5.1.1", + "enhanced-resolve": "^5.26.0", + "es-module-lexer": "^2.1.0", "events": "^3.2.0", - "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.2.11", - "json-parse-even-better-errors": "^2.3.1", - "loader-runner": "^4.3.1", - "mime-types": "^2.1.27", - "neo-async": "^2.6.2", - "schema-utils": "^4.3.3", + "mime-db": "^1.54.0", + "minimizer-webpack-plugin": "^5.13.0", + "schema-utils": "^4.8.1", "tapable": "^2.3.0", - "terser-webpack-plugin": "^5.3.16", - "watchpack": "^2.5.1", - "webpack-sources": "^3.3.3" + "watchpack": "^2.6.3", + "webpack-sources": "^3.6.0" }, "bin": { "webpack": "bin/webpack.js" @@ -6006,40 +5198,51 @@ } }, "node_modules/webpack-cli": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-6.0.1.tgz", - "integrity": "sha512-MfwFQ6SfwinsUVi0rNJm7rHZ31GyTcpVE5pgVA3hwFRb7COD4TzjUUwhGWKfO50+xdc2MQPuEBBJoqIMGt3JDw==", + "version": "7.3.1", + "resolved": "https://registry.npmjs.org/webpack-cli/-/webpack-cli-7.3.1.tgz", + "integrity": "sha512-enXzN0/2fWHX3tP2gpTV6U8/zz5RSbfWjSAc0VXOi0+hOY4ePdHanA+2kxrAC/SX0LHO4fOX5c9G1TdwpvUj/g==", "dev": true, "license": "MIT", "dependencies": { - "@discoveryjs/json-ext": "^0.6.1", - "@webpack-cli/configtest": "^3.0.1", - "@webpack-cli/info": "^3.0.1", - "@webpack-cli/serve": "^3.0.1", - "colorette": "^2.0.14", - "commander": "^12.1.0", - "cross-spawn": "^7.0.3", - "envinfo": "^7.14.0", - "fastest-levenshtein": "^1.0.12", - "import-local": "^3.0.2", + "@discoveryjs/json-ext": "^1.1.0", + "commander": "^14.0.3", + "envinfo": "^7.21.0", "interpret": "^3.1.1", - "rechoir": "^0.8.0", + "rechoir": "^1.0.0", "webpack-merge": "^6.0.1" }, "bin": { "webpack-cli": "bin/cli.js" }, "engines": { - "node": ">=18.12.0" + "node": ">=20.9.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" }, "peerDependencies": { - "webpack": "^5.82.0" + "@bomb.sh/tab": "^0.0.22", + "js-yaml": "^4.0.0 || ^5.0.0", + "json5": "^2.2.3", + "toml": "^3.0.0 || ^4.0.0 || ^5.0.0", + "webpack": "^5.101.0", + "webpack-bundle-analyzer": "^4.0.0 || ^5.0.0", + "webpack-dev-server": "^5.0.0 || ^6.0.0" }, "peerDependenciesMeta": { + "@bomb.sh/tab": { + "optional": true + }, + "js-yaml": { + "optional": true + }, + "json5": { + "optional": true + }, + "toml": { + "optional": true + }, "webpack-bundle-analyzer": { "optional": true }, @@ -6049,38 +5252,39 @@ } }, "node_modules/webpack-cli/node_modules/commander": { - "version": "12.1.0", - "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", - "integrity": "sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA==", + "version": "14.0.3", + "resolved": "https://registry.npmjs.org/commander/-/commander-14.0.3.tgz", + "integrity": "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==", "dev": true, "license": "MIT", "engines": { - "node": ">=18" + "node": ">=20" } }, "node_modules/webpack-dev-middleware": { - "version": "7.4.6", - "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-7.4.6.tgz", - "integrity": "sha512-yBWCMvIfUmuhAE8vdqUKzH0vg9kuWN0KeG4vBnqRplUFHRU7lMQjkiJWxVQzvo2BTewqhPhDlMB41rAt2jVA9A==", + "version": "8.6.1", + "resolved": "https://registry.npmjs.org/webpack-dev-middleware/-/webpack-dev-middleware-8.6.1.tgz", + "integrity": "sha512-XU+DA98yi8FpeI0zPEEki2t4cYKoFOf6PmXl+ocBZ/VXcxFfzeFGK48SZIuFy0o5opnRPVdDGTb71Gy102eiGg==", "dev": true, "license": "MIT", "dependencies": { - "colorette": "^2.0.10", - "memfs": "^4.43.1", - "mime-types": "^3.0.1", - "on-finished": "^2.4.1", - "range-parser": "^1.2.1", - "schema-utils": "^4.0.0" + "memfs": "^4.68.2", + "mime-db": "^1.54.0", + "range-parser": "^1.3.0", + "schema-utils": "^4.3.3" }, "engines": { - "node": ">= 18.12.0" + "node": ">= 20.9.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" }, + "optionalDependencies": { + "ws": "^8.18.3" + }, "peerDependencies": { - "webpack": "^5.0.0" + "webpack": "^5.101.0" }, "peerDependenciesMeta": { "webpack": { @@ -6088,81 +5292,64 @@ } } }, - "node_modules/webpack-dev-middleware/node_modules/mime-types": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz", - "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==", + "node_modules/webpack-dev-middleware/node_modules/range-parser": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz", + "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==", "dev": true, "license": "MIT", - "dependencies": { - "mime-db": "^1.54.0" - }, "engines": { - "node": ">=18" + "node": ">= 0.6" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/express" } }, - "node_modules/webpack-dev-middleware/node_modules/range-parser": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", - "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 0.6" - } - }, "node_modules/webpack-dev-server": { - "version": "5.2.6", - "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-5.2.6.tgz", - "integrity": "sha512-HNLRmamRvVavZQ+avceZifmv8hmdUjg43t6MI4SqJDwFdW7RPQwH5vzGhDRZSX59SgfbeHhLnq3g+uooWo7pVw==", + "version": "6.1.0", + "resolved": "https://registry.npmjs.org/webpack-dev-server/-/webpack-dev-server-6.1.0.tgz", + "integrity": "sha512-T52SEoefJWZDgiYRMeQn4q/w9EVIZjBNWfy/WNRR2+EosPwpUmdUY1Wj0b1Mk7+svgKXojdQTP425fJ+DN58yg==", "dev": true, "license": "MIT", "dependencies": { "@types/bonjour": "^3.5.13", "@types/connect-history-api-fallback": "^1.5.4", - "@types/express": "^4.17.25", - "@types/express-serve-static-core": "^4.17.21", + "@types/express": "^5.0.6", + "@types/express-serve-static-core": "^5.1.1", "@types/serve-index": "^1.9.4", - "@types/serve-static": "^1.15.5", - "@types/sockjs": "^0.3.36", - "@types/ws": "^8.5.10", - "ansi-html-community": "^0.0.8", - "bonjour-service": "^1.2.1", - "chokidar": "^3.6.0", - "colorette": "^2.0.10", + "@types/serve-static": "^2.2.0", + "@types/ws": "^8.18.1", + "bonjour-service": "^1.3.0", + "chokidar": "^5.0.0", "compression": "^1.8.1", "connect-history-api-fallback": "^2.0.0", - "express": "^4.22.1", - "graceful-fs": "^4.2.6", - "http-proxy-middleware": "^2.0.9", - "ipaddr.js": "^2.1.0", + "express": "^5.2.1", + "graceful-fs": "^4.2.11", + "http-proxy-middleware": "^4.1.1", + "ipaddr.js": "^2.3.0", "launch-editor": "^2.14.1", - "open": "^10.0.3", - "p-retry": "^6.2.0", - "schema-utils": "^4.2.0", + "open": "^11.0.0", + "p-retry": "^8.0.0", + "schema-utils": "^4.3.3", "selfsigned": "^5.5.0", - "serve-index": "^1.9.1", - "sockjs": "^0.3.24", - "spdy": "^4.0.2", - "webpack-dev-middleware": "^7.4.2", - "ws": "^8.18.0" + "serve-index": "^1.9.2", + "tinyglobby": "^0.2.15", + "webpack-dev-middleware": "^8.4.0", + "ws": "^8.20.0" }, "bin": { "webpack-dev-server": "bin/webpack-dev-server.js" }, "engines": { - "node": ">= 18.12.0" + "node": ">= 22.15.0" }, "funding": { "type": "opencollective", "url": "https://opencollective.com/webpack" }, "peerDependencies": { - "webpack": "^5.0.0" + "webpack": "^5.101.0" }, "peerDependenciesMeta": { "webpack": { @@ -6173,19 +5360,6 @@ } } }, - "node_modules/webpack-dev-server/node_modules/@types/express-serve-static-core": { - "version": "4.19.6", - "resolved": "https://registry.npmjs.org/@types/express-serve-static-core/-/express-serve-static-core-4.19.6.tgz", - "integrity": "sha512-N4LZ2xG7DatVqhCZzOGb1Yi5lMbXSZcmdLDe9EzSndPV2HpWYWzRbaerl2n27irrm94EPpprqa8KpskPT085+A==", - "dev": true, - "license": "MIT", - "dependencies": { - "@types/node": "*", - "@types/qs": "*", - "@types/range-parser": "*", - "@types/send": "*" - } - }, "node_modules/webpack-merge": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/webpack-merge/-/webpack-merge-6.0.1.tgz", @@ -6202,40 +5376,15 @@ } }, "node_modules/webpack-sources": { - "version": "3.3.3", - "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.3.3.tgz", - "integrity": "sha512-yd1RBzSGanHkitROoPFd6qsrxt+oFhg/129YzheDGqeustzX0vTZJZsSsQjVQC4yzBQ56K55XU8gaNCtIzOnTg==", + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/webpack-sources/-/webpack-sources-3.6.0.tgz", + "integrity": "sha512-EIMmPVvNI0CYXyRPp34F2Qk7W37/BZVZIofS6LAUnrNjCVahS+hO4mxwFJDjQjODTGZDtVzLYoN2+1dYkhk9qA==", "dev": true, "license": "MIT", "engines": { "node": ">=10.13.0" } }, - "node_modules/websocket-driver": { - "version": "0.7.5", - "resolved": "https://registry.npmjs.org/websocket-driver/-/websocket-driver-0.7.5.tgz", - "integrity": "sha512-ZL2+3c7kMBdIRCMz6l8jQMHyGVxj+UL+xVk74Ombiciboca8rHa15L86B19E5oh1pL9Ii/uj54gtsIrZGMo6zA==", - "dev": true, - "license": "Apache-2.0", - "dependencies": { - "http-parser-js": ">=0.5.1", - "safe-buffer": ">=5.1.0", - "websocket-extensions": ">=0.1.1" - }, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/websocket-extensions": { - "version": "0.1.4", - "resolved": "https://registry.npmjs.org/websocket-extensions/-/websocket-extensions-0.1.4.tgz", - "integrity": "sha512-OqedPIGOfsDlo31UNwYbCFMSaO9m9G/0faIHj5/dZFDMFqPTcx6UwqyOy3COEaEOg/9VsGIpdqn62W5KhoKSpg==", - "dev": true, - "license": "Apache-2.0", - "engines": { - "node": ">=0.8.0" - } - }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -6335,6 +5484,13 @@ "url": "https://github.com/chalk/strip-ansi?sponsor=1" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", + "dev": true, + "license": "ISC" + }, "node_modules/ws": { "version": "8.21.1", "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.1.tgz", @@ -6357,16 +5513,33 @@ } } }, + "node_modules/wsl-utils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/wsl-utils/-/wsl-utils-1.0.1.tgz", + "integrity": "sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-wsl": "^3.1.0", + "powershell-utils": "^0.2.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/xterm-readline": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/xterm-readline/-/xterm-readline-1.1.2.tgz", - "integrity": "sha512-1+W2nVuQvCYz9OUYwFBiolrSQUui51aDDyacKXt4PuxeBHqzvabQEJ2kwdBDzsmOjz5BwlDTAjJmYpH2OGqLFA==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/xterm-readline/-/xterm-readline-1.3.1.tgz", + "integrity": "sha512-5dyP/rP3oj6Cm0Cf4g+h+AfzK+1nTC0uD48iI99NyJBnyzmXK8uKci7E30576hD+LpqclQb0mLYarWj6mKXw5w==", "license": "MIT", "dependencies": { "string-width": "^4" }, "peerDependencies": { - "@xterm/xterm": "^5.5.0" + "@xterm/xterm": "^5.5.0 || ^6.0.0" } }, "node_modules/xterm-readline/node_modules/emoji-regex": { diff --git a/wasm/demo/package.json b/wasm/demo/package.json index 2aa9e5867ae..ef173605cbd 100644 --- a/wasm/demo/package.json +++ b/wasm/demo/package.json @@ -4,22 +4,22 @@ "description": "Bindings to the RustPython library for WebAssembly", "main": "index.js", "dependencies": { - "@codemirror/lang-python": "^6.1.6", - "@xterm/addon-fit": "^0.10.0", - "@xterm/xterm": "^5.3.0", - "codemirror": "^6.0.1", + "@codemirror/lang-python": "^6.2.1", + "@xterm/addon-fit": "^0.11.0", + "@xterm/xterm": "^6.0.0", + "codemirror": "^6.0.2", "upgrade": "^1.1.0", - "xterm-readline": "^1.1.2" + "xterm-readline": "^1.3.1" }, "devDependencies": { "@wasm-tool/wasm-pack-plugin": "^1.7.0", - "css-loader": "^7.1.2", - "html-webpack-plugin": "^5.6.3", - "mini-css-extract-plugin": "^2.9.2", - "serve": "^14.2.6", - "webpack": "^5.105.0", - "webpack-cli": "^6.0.1", - "webpack-dev-server": "^5.2.6" + "css-loader": "^7.1.5", + "html-webpack-plugin": "^5.6.8", + "mini-css-extract-plugin": "^2.10.2", + "serve": "^14.2.8", + "webpack": "^5.112.2", + "webpack-cli": "^7.3.1", + "webpack-dev-server": "^6.1.0" }, "scripts": { "dev": "webpack serve", diff --git a/wasm/example/package.json b/wasm/example/package.json index 40b70e0b75d..f885db7f322 100644 --- a/wasm/example/package.json +++ b/wasm/example/package.json @@ -2,12 +2,12 @@ "name": "rustpython-wasm-example", "version": "1.0.0", "dependencies": { - "rustpython_wasm": "0.1.0-pre-alpha.1" + "rustpython_wasm": "0.1.0-pre-alpha.2" }, "devDependencies": { - "raw-loader": "1.0.0", - "webpack": "5.104.1", - "webpack-cli": "^3.1.2" + "raw-loader": "4.0.2", + "webpack": "5.112.2", + "webpack-cli": "^7.2.3" }, "scripts": { "build": "webpack", diff --git a/wasm/notebook/package.json b/wasm/notebook/package.json index 64517331c49..af520d0cf4c 100644 --- a/wasm/notebook/package.json +++ b/wasm/notebook/package.json @@ -4,12 +4,12 @@ "description": "Bindings to the RustPython library for WebAssembly", "main": "index.js", "dependencies": { - "codemirror": "^5.42.0", + "codemirror": "^6.0.2", "file-loader": "^6.1.0", - "katex": "^0.12.0", + "katex": "^0.19.0", "local-echo": "^0.2.0", - "marked": "^1.1.1", - "xterm": "^3.8.0" + "marked": "^18.1.1", + "xterm": "^5.3.0" }, "devDependencies": { "@wasm-tool/wasm-pack-plugin": "^1.7.0", @@ -18,8 +18,8 @@ "lezer-loader": "^0.3.0", "mini-css-extract-plugin": "^2.9.2", "webpack": "^5.97.1", - "webpack-cli": "^6.0.1", - "webpack-dev-server": "^5.2.0" + "webpack-cli": "^7.2.3", + "webpack-dev-server": "^6.1.0" }, "scripts": { "dev": "webpack serve",